format-lib.js 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905
  1. /**
  2. * FeHelper Json Format Lib
  3. */
  4. var JsonFormatEntrance = (function () {
  5. "use strict";
  6. var jfContent,
  7. pre,
  8. jfStyleEl,
  9. formattingMsg,
  10. slowAnalysisTimeout,
  11. isJsonTime,
  12. exitedNotJsonTime,
  13. displayedFormattedJsonTime
  14. ;
  15. // Add listener to receive response from BG when ready
  16. var postMessage = function (msg) {
  17. // console.log('Port msg received', msg[0], (""+msg[1]).substring(0,30)) ;
  18. switch (msg[0]) {
  19. case 'NOT JSON' :
  20. pre.style.display = "";
  21. // console.log('Unhidden the PRE') ;
  22. jfContent.innerHTML = '<span class="x-json-tips">JSON不合法,请检查:</span>';
  23. exitedNotJsonTime = +(new Date());
  24. break;
  25. case 'FORMATTING' :
  26. isJsonTime = +(new Date());
  27. // It is JSON, and it's now being formatted in the background worker.
  28. // Clear the slowAnalysisTimeout (if the BG worker had taken longer than 1s to respond with an answer to whether or not this is JSON, then it would have fired, unhiding the PRE... But now that we know it's JSON, we can clear this timeout, ensuring the PRE stays hidden.)
  29. clearTimeout(slowAnalysisTimeout);
  30. // Create option bar
  31. var optionBar = document.getElementById('optionBar');
  32. if (optionBar) {
  33. optionBar.parentNode.removeChild(optionBar);
  34. }
  35. optionBar = document.createElement('div');
  36. optionBar.id = 'optionBar';
  37. // Create toggleFormat button
  38. var buttonFormatted = document.createElement('button'),
  39. buttonCollapseAll = document.createElement('button');
  40. buttonFormatted.id = 'buttonFormatted';
  41. buttonFormatted.innerText = '格式化';
  42. buttonFormatted.classList.add('selected');
  43. buttonCollapseAll.id = 'buttonCollapseAll';
  44. buttonCollapseAll.innerText = '折叠所有';
  45. var plainOn = false;
  46. buttonFormatted.addEventListener('click', function () {
  47. // When formatted button clicked...
  48. if (plainOn) {
  49. plainOn = false;
  50. pre.style.display = "none";
  51. jfContent.style.display = "block";
  52. $(this).text('元数据');
  53. } else {
  54. plainOn = true;
  55. pre.style.display = "block";
  56. jfContent.style.display = "none";
  57. $(this).text('格式化');
  58. }
  59. $(this).parent().find('button').removeClass('selected');
  60. $(this).addClass('selected');
  61. }, false);
  62. buttonCollapseAll.addEventListener('click', function () {
  63. // 如果内容还没有格式化过,需要再格式化一下
  64. if (plainOn) {
  65. buttonFormatted.click();
  66. }
  67. // When collapaseAll button clicked...
  68. if (!plainOn) {
  69. if (buttonCollapseAll.innerText === '折叠所有') {
  70. buttonCollapseAll.innerText = '展开所有';
  71. collapse(document.getElementsByClassName('objProp'));
  72. } else {
  73. buttonCollapseAll.innerText = '折叠所有';
  74. expand(document.getElementsByClassName('objProp'));
  75. }
  76. $(this).parent().find('button').removeClass('selected');
  77. $(this).addClass('selected');
  78. }
  79. }, false);
  80. // Put it in optionBar
  81. optionBar.appendChild(buttonFormatted);
  82. optionBar.appendChild(buttonCollapseAll);
  83. // Attach event handlers
  84. document.addEventListener('click', generalClick, false);
  85. // Put option bar in DOM
  86. jfContent.parentNode.appendChild(optionBar);
  87. break;
  88. case 'FORMATTED' :
  89. // Insert HTML content
  90. formattingMsg.style.display = "";
  91. jfContent.innerHTML = msg[1];
  92. displayedFormattedJsonTime = +(new Date());
  93. // console.markTimeline('JSON formatted and displayed') ;
  94. break;
  95. default :
  96. throw new Error('Message not understood: ' + msg[0]);
  97. }
  98. };
  99. // console.timeEnd('established port') ;
  100. var lastKvovIdGiven = 0;
  101. function collapse(elements) {
  102. var el, i, blockInner, count;
  103. for (i = elements.length - 1; i >= 0; i--) {
  104. el = elements[i];
  105. el.classList.add('collapsed');
  106. // (CSS hides the contents and shows an ellipsis.)
  107. // Add a count of the number of child properties/items (if not already done for this item)
  108. if (!el.id) {
  109. el.id = 'kvov' + (++lastKvovIdGiven);
  110. // Find the blockInner
  111. blockInner = el.firstElementChild;
  112. while (blockInner && !blockInner.classList.contains('blockInner')) {
  113. blockInner = blockInner.nextElementSibling;
  114. }
  115. if (!blockInner)
  116. continue;
  117. // See how many children in the blockInner
  118. count = blockInner.children.length;
  119. // Generate comment text eg "4 items"
  120. var comment = count + (count === 1 ? ' item' : ' items');
  121. // Add CSS that targets it
  122. jfStyleEl.insertAdjacentHTML(
  123. 'beforeend',
  124. '\n#kvov' + lastKvovIdGiven + '.collapsed:after{color: #aaa; content:" // ' + comment + '"}'
  125. );
  126. }
  127. }
  128. }
  129. function expand(elements) {
  130. for (var i = elements.length - 1; i >= 0; i--)
  131. elements[i].classList.remove('collapsed');
  132. }
  133. var mac = navigator.platform.indexOf('Mac') !== -1,
  134. modKey;
  135. if (mac)
  136. modKey = function (ev) {
  137. return ev.metaKey;
  138. };
  139. else
  140. modKey = function (ev) {
  141. return ev.ctrlKey;
  142. };
  143. function generalClick(ev) {
  144. // console.log('click', ev) ;
  145. if (ev.which === 1) {
  146. var elem = ev.target;
  147. if (elem.className === 'e') {
  148. // It's a click on an expander.
  149. ev.preventDefault();
  150. var parent = elem.parentNode,
  151. div = jfContent,
  152. prevBodyHeight = document.body.offsetHeight,
  153. scrollTop = document.body.scrollTop,
  154. parentSiblings
  155. ;
  156. // Expand or collapse
  157. if (parent.classList.contains('collapsed')) {
  158. // EXPAND
  159. if (modKey(ev))
  160. expand(parent.parentNode.children);
  161. else
  162. expand([parent]);
  163. }
  164. else {
  165. // COLLAPSE
  166. if (modKey(ev))
  167. collapse(parent.parentNode.children);
  168. else
  169. collapse([parent]);
  170. }
  171. // Restore scrollTop somehow
  172. // Clear current extra margin, if any
  173. div.style.marginBottom = 0;
  174. // No need to worry if all content fits in viewport
  175. if (document.body.offsetHeight < window.innerHeight) {
  176. // console.log('document.body.offsetHeight < window.innerHeight; no need to adjust height') ;
  177. return;
  178. }
  179. // And no need to worry if scrollTop still the same
  180. if (document.body.scrollTop === scrollTop) {
  181. // console.log('document.body.scrollTop === scrollTop; no need to adjust height') ;
  182. return;
  183. }
  184. // console.log('Scrolltop HAS changed. document.body.scrollTop is now '+document.body.scrollTop+'; was '+scrollTop) ;
  185. // The body has got a bit shorter.
  186. // We need to increase the body height by a bit (by increasing the bottom margin on the jfContent div). The amount to increase it is whatever is the difference between our previous scrollTop and our new one.
  187. // Work out how much more our target scrollTop is than this.
  188. var difference = scrollTop - document.body.scrollTop + 8; // it always loses 8px; don't know why
  189. // Add this difference to the bottom margin
  190. //var currentMarginBottom = parseInt(div.style.marginBottom) || 0 ;
  191. div.style.marginBottom = difference + 'px';
  192. // Now change the scrollTop back to what it was
  193. document.body.scrollTop = scrollTop;
  194. return;
  195. }
  196. }
  197. }
  198. /**
  199. * 执行代码格式化
  200. * @param {[type]} jsonStr [description]
  201. * @return {[type]}
  202. */
  203. var format = function (jsonStr) {
  204. // 如果jsonStr和上一次的一模一样,就不用再格式化了
  205. try {
  206. var str1 = JSON.stringify(JSON.parse(jsonStr));
  207. var str2 = JSON.stringify(JSON.parse(pre.innerText));
  208. if (str1 == str2) {
  209. alert('JSON内容没有变化');
  210. return false;
  211. }
  212. } catch (e) {
  213. }
  214. try {
  215. jfContent.innerHTML = '';
  216. pre.innerHTML = '';
  217. document.querySelector('#boxOpt').remove();
  218. } catch (e) {
  219. }
  220. // Send the contents of the PRE to the BG script
  221. // Add jfContent DIV, ready to display stuff
  222. jfContent = document.getElementById('jfContent');
  223. if (!jfContent) {
  224. jfContent = document.createElement('div');
  225. jfContent.id = 'jfContent';
  226. document.body.appendChild(jfContent);
  227. }
  228. jfContent.style.display = '';
  229. pre = document.getElementById('jfContent_pre');
  230. if (!pre) {
  231. pre = document.createElement('pre');
  232. pre.id = 'jfContent_pre';
  233. document.body.appendChild(pre);
  234. }
  235. pre.innerHTML = JSON.stringify(JSON.parse(jsonStr), null, 4);
  236. pre.style.display = "none";
  237. jfStyleEl = document.getElementById('jfStyleEl');
  238. if (!jfStyleEl) {
  239. jfStyleEl = document.createElement('style');
  240. document.head.appendChild(jfStyleEl);
  241. }
  242. formattingMsg = document.getElementById('formattingMsg');
  243. if (!formattingMsg) {
  244. formattingMsg = document.createElement('pre');
  245. formattingMsg.id = 'formattingMsg';
  246. formattingMsg.innerHTML = '<svg id="spinner" width="16" height="16" viewBox="0 0 300 300" xmlns="http://www.w3.org/2000/svg" version="1.1">' +
  247. '<path d="M 150,0 a 150,150 0 0,1 106.066,256.066 l -35.355,-35.355 a -100,-100 0 0,0 -70.711,-170.711 z" fill="#3d7fe6"></path></svg> 格式化中...';
  248. document.body.appendChild(formattingMsg);
  249. }
  250. // Post the contents of the PRE
  251. JsonFormatDealer.postMessage({
  252. type: "SENDING TEXT",
  253. text: jsonStr,
  254. length: jsonStr.length
  255. });
  256. _loadJquery();
  257. // 事件绑定
  258. _addEvents();
  259. // 支持文件下载
  260. _downloadSupport(JSON.parse(jsonStr));
  261. };
  262. var _loadJquery = function () {
  263. if (typeof Tarp === 'object') {
  264. if (!window.jQuery && typeof jQuery !== 'function') {
  265. window.jQuery = window.$ = Tarp.require('../static/vendor/jquery/jquery-3.3.1.min.js');
  266. }
  267. Tarp.require('../static/js/utils.js');
  268. } else {
  269. alert('无法加载Tarp.require.js');
  270. }
  271. };
  272. /**
  273. * 直接下载,能解决中文乱码
  274. * @param json
  275. * @private
  276. */
  277. var _downloadSupport = function (json) {
  278. // 下载链接
  279. var localUrl = location.href;
  280. var dt = (new Date()).format('yyyyMMddHHmmss');
  281. var content = JSON.stringify(json, null, 4);
  282. content = ['/* ', localUrl, ' */', '\n', content].join('');
  283. var blob = new Blob([content], {type: 'application/octet-stream'});
  284. var aLink = $('<a id="btnDownload" target="_blank" title="保存到本地">下载JSON数据</a>').prependTo('#optionBar');
  285. aLink.attr('download', 'FeHelper-' + dt + '.json');
  286. aLink.attr('href', URL.createObjectURL(blob));
  287. };
  288. /**
  289. * chrome 下复制到剪贴板
  290. * @param text
  291. */
  292. var _copyToClipboard = function (text) {
  293. var input = document.createElement('textarea');
  294. input.style.position = 'fixed';
  295. input.style.opacity = 0;
  296. input.value = text;
  297. document.body.appendChild(input);
  298. input.select();
  299. document.execCommand('Copy');
  300. document.body.removeChild(input);
  301. alert('Json片段复制成功,随处粘贴可用!')
  302. };
  303. /**
  304. * 给某个节点增加操作项
  305. * @param el
  306. * @private
  307. */
  308. var _addOptForItem = function (el) {
  309. // 下载json片段
  310. var fnDownload = function (ec) {
  311. var txt = el.text().replace(/":\s/gm, '":').replace(/,$/, '').trim();
  312. if (!(/^{/.test(txt) && /\}$/.test(txt)) && !(/^\[/.test(txt) && /\]$/.test(txt))) {
  313. txt = '{' + txt + '}';
  314. }
  315. try {
  316. txt = JSON.stringify(JSON.parse(txt), null, 4);
  317. } catch (err) {
  318. }
  319. // 下载片段
  320. var dt = (new Date()).format('yyyyMMddHHmmss');
  321. var blob = new Blob([txt], {type: 'application/octet-stream'});
  322. $(this).attr('download', 'FeHelper-' + dt + '.json').attr('href', URL.createObjectURL(blob));
  323. };
  324. // 复制json片段
  325. var fnCopy = function (ec) {
  326. var txt = el.text().replace(/":\s/gm, '":').replace(/,$/, '').trim();
  327. if (!(/^{/.test(txt) && /\}$/.test(txt)) && !(/^\[/.test(txt) && /\]$/.test(txt))) {
  328. txt = '{' + txt + '}';
  329. }
  330. try {
  331. txt = JSON.stringify(JSON.parse(txt), null, 4);
  332. } catch (err) {
  333. }
  334. _copyToClipboard(txt);
  335. };
  336. // 删除json片段
  337. var fnDel = function (ed) {
  338. if (el.parent().is('#formattedJson')) {
  339. alert('如果连最外层的Json也删掉的话,就没啥意义了哦!');
  340. return false;
  341. }
  342. alert('节点已删除成功!');
  343. el.remove();
  344. boxOpt.css('top', -1000).hide();
  345. };
  346. var boxOpt = $('#boxOpt');
  347. if (!boxOpt.length) {
  348. boxOpt = $('<div id="boxOpt"><a class="opt-download" target="_blank">下载</a>|<a class="opt-copy">复制</a>|<a class="opt-del">删除</a></div>').appendTo('body');
  349. }
  350. boxOpt.find('a.opt-download').unbind('click').bind('click', fnDownload);
  351. boxOpt.find('a.opt-copy').unbind('click').bind('click', fnCopy);
  352. boxOpt.find('a.opt-del').unbind('click').bind('click', fnDel);
  353. boxOpt.css({
  354. left: el.offset().left + el.width() - 90,
  355. top: el.offset().top
  356. }).show();
  357. };
  358. // 附加操作
  359. var _addEvents = function () {
  360. $('#jfContent .kvov').bind('click', function (e) {
  361. if ($(this).hasClass('x-outline')) {
  362. $('#boxOpt').remove();
  363. $(this).removeClass('x-outline');
  364. return false;
  365. }
  366. $('.x-outline').removeClass('x-outline');
  367. var el = $(this).removeClass('x-hover').addClass('x-outline');
  368. // 增加复制、删除功能
  369. _addOptForItem(el);
  370. if (!$(e.target).is('.kvov .e')) {
  371. e.stopPropagation();
  372. } else {
  373. $(e.target).parent().trigger('click');
  374. }
  375. }).bind('mouseover', function (e) {
  376. $(this).addClass('x-hover');
  377. return false;
  378. }).bind('mouseout', function (e) {
  379. $(this).removeClass('x-hover');
  380. });
  381. };
  382. return {
  383. format: format,
  384. postMessage: postMessage
  385. }
  386. })();
  387. var JsonFormatDealer = (function () {
  388. "use strict";
  389. // Constants
  390. var
  391. TYPE_STRING = 1,
  392. TYPE_NUMBER = 2,
  393. TYPE_OBJECT = 3,
  394. TYPE_ARRAY = 4,
  395. TYPE_BOOL = 5,
  396. TYPE_NULL = 6
  397. ;
  398. // Utility functions
  399. function removeComments(str) {
  400. str = ('__' + str + '__').split('');
  401. var mode = {
  402. singleQuote: false,
  403. doubleQuote: false,
  404. regex: false,
  405. blockComment: false,
  406. lineComment: false,
  407. condComp: false
  408. };
  409. for (var i = 0, l = str.length; i < l; i++) {
  410. if (mode.regex) {
  411. if (str[i] === '/' && str[i - 1] !== '\\') {
  412. mode.regex = false;
  413. }
  414. continue;
  415. }
  416. if (mode.singleQuote) {
  417. if (str[i] === "'" && str[i - 1] !== '\\') {
  418. mode.singleQuote = false;
  419. }
  420. continue;
  421. }
  422. if (mode.doubleQuote) {
  423. if (str[i] === '"' && str[i - 1] !== '\\') {
  424. mode.doubleQuote = false;
  425. }
  426. continue;
  427. }
  428. if (mode.blockComment) {
  429. if (str[i] === '*' && str[i + 1] === '/') {
  430. str[i + 1] = '';
  431. mode.blockComment = false;
  432. }
  433. str[i] = '';
  434. continue;
  435. }
  436. if (mode.lineComment) {
  437. if (str[i + 1] === '\n' || str[i + 1] === '\r') {
  438. mode.lineComment = false;
  439. }
  440. str[i] = '';
  441. continue;
  442. }
  443. if (mode.condComp) {
  444. if (str[i - 2] === '@' && str[i - 1] === '*' && str[i] === '/') {
  445. mode.condComp = false;
  446. }
  447. continue;
  448. }
  449. mode.doubleQuote = str[i] === '"';
  450. mode.singleQuote = str[i] === "'";
  451. if (str[i] === '/') {
  452. if (str[i + 1] === '*' && str[i + 2] === '@') {
  453. mode.condComp = true;
  454. continue;
  455. }
  456. if (str[i + 1] === '*') {
  457. str[i] = '';
  458. mode.blockComment = true;
  459. continue;
  460. }
  461. if (str[i + 1] === '/') {
  462. str[i] = '';
  463. mode.lineComment = true;
  464. continue;
  465. }
  466. mode.regex = true;
  467. }
  468. }
  469. return str.join('').slice(2, -2);
  470. }
  471. // function spin(seconds) {
  472. // // spin - Hog the CPU for the specified number of seconds
  473. // // (for simulating long processing times in development)
  474. // var stop = +new Date() + (seconds*1000) ;
  475. // while (new Date() < stop) {}
  476. // return true ;
  477. // }
  478. // Record current version (in case future update wants to know)
  479. localStorage.jfVersion = '0.5.6';
  480. // Template elements
  481. var templates,
  482. baseDiv = document.createElement('div'),
  483. baseSpan = document.createElement('span');
  484. function getSpanBoth(innerText, className) {
  485. var span = baseSpan.cloneNode(false);
  486. span.className = className;
  487. span.innerText = innerText;
  488. return span;
  489. }
  490. function getSpanText(innerText) {
  491. var span = baseSpan.cloneNode(false);
  492. span.innerText = innerText;
  493. return span;
  494. }
  495. function getSpanClass(className) {
  496. var span = baseSpan.cloneNode(false);
  497. span.className = className;
  498. return span;
  499. }
  500. function getDivClass(className) {
  501. var span = baseDiv.cloneNode(false);
  502. span.className = className;
  503. return span;
  504. }
  505. // Create template nodes
  506. var templatesObj = {
  507. t_kvov: getDivClass('kvov'),
  508. t_exp: getSpanClass('e'),
  509. t_key: getSpanClass('k'),
  510. t_string: getSpanClass('s'),
  511. t_number: getSpanClass('n'),
  512. t_null: getSpanBoth('null', 'nl'),
  513. t_true: getSpanBoth('true', 'bl'),
  514. t_false: getSpanBoth('false', 'bl'),
  515. t_oBrace: getSpanBoth('{', 'b'),
  516. t_cBrace: getSpanBoth('}', 'b'),
  517. t_oBracket: getSpanBoth('[', 'b'),
  518. t_cBracket: getSpanBoth(']', 'b'),
  519. t_ellipsis: getSpanClass('ell'),
  520. t_blockInner: getSpanClass('blockInner'),
  521. t_colonAndSpace: document.createTextNode(':\u00A0'),
  522. t_commaText: document.createTextNode(','),
  523. t_dblqText: document.createTextNode('"')
  524. };
  525. // Core recursive DOM-building function
  526. function getKvovDOM(value, keyName) {
  527. var type,
  528. kvov,
  529. nonZeroSize,
  530. templates = templatesObj, // bring into scope for tiny speed boost
  531. objKey,
  532. keySpan,
  533. valueElement
  534. ;
  535. // Establish value type
  536. if (typeof value === 'string')
  537. type = TYPE_STRING;
  538. else if (typeof value === 'number')
  539. type = TYPE_NUMBER;
  540. else if (value === false || value === true)
  541. type = TYPE_BOOL;
  542. else if (value === null)
  543. type = TYPE_NULL;
  544. else if (value instanceof Array)
  545. type = TYPE_ARRAY;
  546. else
  547. type = TYPE_OBJECT;
  548. // Root node for this kvov
  549. kvov = templates.t_kvov.cloneNode(false);
  550. // Add an 'expander' first (if this is object/array with non-zero size)
  551. if (type === TYPE_OBJECT || type === TYPE_ARRAY) {
  552. nonZeroSize = false;
  553. for (objKey in value) {
  554. if (value.hasOwnProperty(objKey)) {
  555. nonZeroSize = true;
  556. break; // no need to keep counting; only need one
  557. }
  558. }
  559. if (nonZeroSize)
  560. kvov.appendChild(templates.t_exp.cloneNode(false));
  561. }
  562. // If there's a key, add that before the value
  563. if (keyName !== false) { // NB: "" is a legal keyname in JSON
  564. // This kvov must be an object property
  565. kvov.classList.add('objProp');
  566. // Create a span for the key name
  567. keySpan = templates.t_key.cloneNode(false);
  568. keySpan.textContent = JSON.stringify(keyName).slice(1, -1); // remove quotes
  569. // Add it to kvov, with quote marks
  570. kvov.appendChild(templates.t_dblqText.cloneNode(false));
  571. kvov.appendChild(keySpan);
  572. kvov.appendChild(templates.t_dblqText.cloneNode(false));
  573. // Also add ":&nbsp;" (colon and non-breaking space)
  574. kvov.appendChild(templates.t_colonAndSpace.cloneNode(false));
  575. }
  576. else {
  577. // This is an array element instead
  578. kvov.classList.add('arrElem');
  579. }
  580. // Generate DOM for this value
  581. var blockInner, childKvov;
  582. switch (type) {
  583. case TYPE_STRING:
  584. // If string is a URL, get a link, otherwise get a span
  585. var innerStringEl = baseSpan.cloneNode(false),
  586. escapedString = JSON.stringify(value);
  587. escapedString = escapedString.substring(1, escapedString.length - 1); // remove quotes
  588. if (value[0] === 'h' && value.substring(0, 4) === 'http') { // crude but fast - some false positives, but rare, and UX doesn't suffer terribly from them.
  589. var innerStringA = document.createElement('A');
  590. innerStringA.href = value;
  591. innerStringA.innerText = escapedString;
  592. innerStringEl.appendChild(innerStringA);
  593. }
  594. else {
  595. innerStringEl.innerText = escapedString;
  596. }
  597. valueElement = templates.t_string.cloneNode(false);
  598. valueElement.appendChild(templates.t_dblqText.cloneNode(false));
  599. valueElement.appendChild(innerStringEl);
  600. valueElement.appendChild(templates.t_dblqText.cloneNode(false));
  601. kvov.appendChild(valueElement);
  602. break;
  603. case TYPE_NUMBER:
  604. // Simply add a number element (span.n)
  605. valueElement = templates.t_number.cloneNode(false);
  606. valueElement.innerText = value;
  607. kvov.appendChild(valueElement);
  608. break;
  609. case TYPE_OBJECT:
  610. // Add opening brace
  611. kvov.appendChild(templates.t_oBrace.cloneNode(true));
  612. // If any properties, add a blockInner containing k/v pair(s)
  613. if (nonZeroSize) {
  614. // Add ellipsis (empty, but will be made to do something when kvov is collapsed)
  615. kvov.appendChild(templates.t_ellipsis.cloneNode(false));
  616. // Create blockInner, which indents (don't attach yet)
  617. blockInner = templates.t_blockInner.cloneNode(false);
  618. // For each key/value pair, add as a kvov to blockInner
  619. var count = 0, k, comma;
  620. for (k in value) {
  621. if (value.hasOwnProperty(k)) {
  622. count++;
  623. childKvov = getKvovDOM(value[k], k);
  624. // Add comma
  625. comma = templates.t_commaText.cloneNode();
  626. childKvov.appendChild(comma);
  627. blockInner.appendChild(childKvov);
  628. }
  629. }
  630. // Now remove the last comma
  631. childKvov.removeChild(comma);
  632. // Add blockInner
  633. kvov.appendChild(blockInner);
  634. }
  635. // Add closing brace
  636. kvov.appendChild(templates.t_cBrace.cloneNode(true));
  637. break;
  638. case TYPE_ARRAY:
  639. // Add opening bracket
  640. kvov.appendChild(templates.t_oBracket.cloneNode(true));
  641. // If non-zero length array, add blockInner containing inner vals
  642. if (nonZeroSize) {
  643. // Add ellipsis
  644. kvov.appendChild(templates.t_ellipsis.cloneNode(false));
  645. // Create blockInner (which indents) (don't attach yet)
  646. blockInner = templates.t_blockInner.cloneNode(false);
  647. // For each key/value pair, add the markup
  648. for (var i = 0, length = value.length, lastIndex = length - 1; i < length; i++) {
  649. // Make a new kvov, with no key
  650. childKvov = getKvovDOM(value[i], false);
  651. // Add comma if not last one
  652. if (i < lastIndex)
  653. childKvov.appendChild(templates.t_commaText.cloneNode());
  654. // Append the child kvov
  655. blockInner.appendChild(childKvov);
  656. }
  657. // Add blockInner
  658. kvov.appendChild(blockInner);
  659. }
  660. // Add closing bracket
  661. kvov.appendChild(templates.t_cBracket.cloneNode(true));
  662. break;
  663. case TYPE_BOOL:
  664. if (value)
  665. kvov.appendChild(templates.t_true.cloneNode(true));
  666. else
  667. kvov.appendChild(templates.t_false.cloneNode(true));
  668. break;
  669. case TYPE_NULL:
  670. kvov.appendChild(templates.t_null.cloneNode(true));
  671. break;
  672. }
  673. return kvov;
  674. }
  675. // Function to convert object to an HTML string
  676. function jsonObjToHTML(obj, jsonpFunctionName) {
  677. // spin(5) ;
  678. // Format object (using recursive kvov builder)
  679. var rootKvov = getKvovDOM(obj, false);
  680. // The whole DOM is now built.
  681. // Set class on root node to identify it
  682. rootKvov.classList.add('rootKvov');
  683. // Make div#formattedJson and append the root kvov
  684. var divFormattedJson = document.createElement('DIV');
  685. divFormattedJson.id = 'formattedJson';
  686. divFormattedJson.appendChild(rootKvov);
  687. // Convert it to an HTML string (shame about this step, but necessary for passing it through to the content page)
  688. var returnHTML = divFormattedJson.outerHTML;
  689. // Top and tail with JSONP padding if necessary
  690. if (jsonpFunctionName !== null) {
  691. returnHTML =
  692. '<div id="jsonpOpener">' + jsonpFunctionName + ' ( </div>' +
  693. returnHTML +
  694. '<div id="jsonpCloser">)</div>';
  695. }
  696. // Return the HTML
  697. return returnHTML;
  698. }
  699. // Listen for requests from content pages wanting to set up a port
  700. var postMessage = function (msg) {
  701. var jsonpFunctionName = null;
  702. if (msg.type === 'SENDING TEXT') {
  703. // Try to parse as JSON
  704. var obj,
  705. text = msg.text;
  706. try {
  707. obj = new Function('return ' + text)();
  708. }
  709. catch (e) {
  710. // Not JSON; could be JSONP though.
  711. // Try stripping 'padding' (if any), and try parsing it again
  712. text = text.trim();
  713. // Find where the first paren is (and exit if none)
  714. var indexOfParen;
  715. if (!(indexOfParen = text.indexOf('('))) {
  716. JsonFormatEntrance.postMessage(['NOT JSON', 'no opening parenthesis']);
  717. return;
  718. }
  719. // Get the substring up to the first "(", with any comments/whitespace stripped out
  720. var firstBit = removeComments(text.substring(0, indexOfParen)).trim();
  721. if (!firstBit.match(/^[a-zA-Z_$][\.\[\]'"0-9a-zA-Z_$]*$/)) {
  722. // The 'firstBit' is NOT a valid function identifier.
  723. JsonFormatEntrance.postMessage(['NOT JSON', 'first bit not a valid function name']);
  724. return;
  725. }
  726. // Find last parenthesis (exit if none)
  727. var indexOfLastParen;
  728. if (!(indexOfLastParen = text.lastIndexOf(')'))) {
  729. JsonFormatEntrance.postMessage(['NOT JSON', 'no closing paren']);
  730. return;
  731. }
  732. // Check that what's after the last parenthesis is just whitespace, comments, and possibly a semicolon (exit if anything else)
  733. var lastBit = removeComments(text.substring(indexOfLastParen + 1)).trim();
  734. if (lastBit !== "" && lastBit !== ';') {
  735. JsonFormatEntrance.postMessage(['NOT JSON', 'last closing paren followed by invalid characters']);
  736. return;
  737. }
  738. // So, it looks like a valid JS function call, but we don't know whether it's JSON inside the parentheses...
  739. // Check if the 'argument' is actually JSON (and record the parsed result)
  740. text = text.substring(indexOfParen + 1, indexOfLastParen);
  741. try {
  742. obj = JSON.parse(text);
  743. }
  744. catch (e2) {
  745. // Just some other text that happens to be in a function call.
  746. // Respond as not JSON, and exit
  747. JsonFormatEntrance.postMessage(['NOT JSON', 'looks like a function call, but the parameter is not valid JSON']);
  748. return;
  749. }
  750. jsonpFunctionName = firstBit;
  751. }
  752. // If still running, we now have obj, which is valid JSON.
  753. // Ensure it's not a number or string (technically valid JSON, but no point prettifying it)
  754. if (typeof obj !== 'object' && typeof obj !== 'array') {
  755. JsonFormatEntrance.postMessage(['NOT JSON', 'technically JSON but not an object or array']);
  756. return;
  757. }
  758. // And send it the message to confirm that we're now formatting (so it can show a spinner)
  759. JsonFormatEntrance.postMessage(['FORMATTING' /*, JSON.stringify(localStorage)*/]);
  760. // Do formatting
  761. var html = jsonObjToHTML(obj, jsonpFunctionName);
  762. // Post the HTML string to the content script
  763. JsonFormatEntrance.postMessage(['FORMATTED', html]);
  764. }
  765. };
  766. return {
  767. postMessage: postMessage
  768. };
  769. })();
  770. module.exports = {
  771. format: JsonFormatEntrance.format
  772. };