format-lib.js 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903
  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. window.jQuery = window.$ = Tarp.require('../static/vendor/jquery/jquery-3.3.1.min.js');
  265. Tarp.require('../static/js/core/utils.js');
  266. } else {
  267. alert('无法加载Tarp.require.js');
  268. }
  269. };
  270. /**
  271. * 直接下载,能解决中文乱码
  272. * @param json
  273. * @private
  274. */
  275. var _downloadSupport = function (json) {
  276. // 下载链接
  277. var localUrl = location.href;
  278. var dt = (new Date()).format('yyyyMMddHHmmss');
  279. var content = JSON.stringify(json, null, 4);
  280. content = ['/* ', localUrl, ' */', '\n', content].join('');
  281. var blob = new Blob([content], {type: 'application/octet-stream'});
  282. var aLink = $('<a id="btnDownload" target="_blank" title="保存到本地">下载JSON数据</a>').prependTo('#optionBar');
  283. aLink.attr('download', 'FeHelper-' + dt + '.json');
  284. aLink.attr('href', URL.createObjectURL(blob));
  285. };
  286. /**
  287. * chrome 下复制到剪贴板
  288. * @param text
  289. */
  290. var _copyToClipboard = function (text) {
  291. var input = document.createElement('textarea');
  292. input.style.position = 'fixed';
  293. input.style.opacity = 0;
  294. input.value = text;
  295. document.body.appendChild(input);
  296. input.select();
  297. document.execCommand('Copy');
  298. document.body.removeChild(input);
  299. alert('Json片段复制成功,随处粘贴可用!')
  300. };
  301. /**
  302. * 给某个节点增加操作项
  303. * @param el
  304. * @private
  305. */
  306. var _addOptForItem = function (el) {
  307. // 下载json片段
  308. var fnDownload = function (ec) {
  309. var txt = el.text().replace(/":\s/gm, '":').replace(/,$/, '').trim();
  310. if (!(/^{/.test(txt) && /\}$/.test(txt)) && !(/^\[/.test(txt) && /\]$/.test(txt))) {
  311. txt = '{' + txt + '}';
  312. }
  313. try {
  314. txt = JSON.stringify(JSON.parse(txt), null, 4);
  315. } catch (err) {
  316. }
  317. // 下载片段
  318. var dt = (new Date()).format('yyyyMMddHHmmss');
  319. var blob = new Blob([txt], {type: 'application/octet-stream'});
  320. $(this).attr('download', 'FeHelper-' + dt + '.json').attr('href', URL.createObjectURL(blob));
  321. };
  322. // 复制json片段
  323. var fnCopy = function (ec) {
  324. var txt = el.text().replace(/":\s/gm, '":').replace(/,$/, '').trim();
  325. if (!(/^{/.test(txt) && /\}$/.test(txt)) && !(/^\[/.test(txt) && /\]$/.test(txt))) {
  326. txt = '{' + txt + '}';
  327. }
  328. try {
  329. txt = JSON.stringify(JSON.parse(txt), null, 4);
  330. } catch (err) {
  331. }
  332. _copyToClipboard(txt);
  333. };
  334. // 删除json片段
  335. var fnDel = function (ed) {
  336. if (el.parent().is('#formattedJson')) {
  337. alert('如果连最外层的Json也删掉的话,就没啥意义了哦!');
  338. return false;
  339. }
  340. alert('节点已删除成功!');
  341. el.remove();
  342. boxOpt.css('top', -1000).hide();
  343. };
  344. var boxOpt = $('#boxOpt');
  345. if (!boxOpt.length) {
  346. boxOpt = $('<div id="boxOpt"><a class="opt-download" target="_blank">下载</a>|<a class="opt-copy">复制</a>|<a class="opt-del">删除</a></div>').appendTo('body');
  347. }
  348. boxOpt.find('a.opt-download').unbind('click').bind('click', fnDownload);
  349. boxOpt.find('a.opt-copy').unbind('click').bind('click', fnCopy);
  350. boxOpt.find('a.opt-del').unbind('click').bind('click', fnDel);
  351. boxOpt.css({
  352. left: el.offset().left + el.width() - 90,
  353. top: el.offset().top
  354. }).show();
  355. };
  356. // 附加操作
  357. var _addEvents = function () {
  358. $('#jfContent .kvov').bind('click', function (e) {
  359. if ($(this).hasClass('x-outline')) {
  360. $('#boxOpt').remove();
  361. $(this).removeClass('x-outline');
  362. return false;
  363. }
  364. $('.x-outline').removeClass('x-outline');
  365. var el = $(this).removeClass('x-hover').addClass('x-outline');
  366. // 增加复制、删除功能
  367. _addOptForItem(el);
  368. if (!$(e.target).is('.kvov .e')) {
  369. e.stopPropagation();
  370. } else {
  371. $(e.target).parent().trigger('click');
  372. }
  373. }).bind('mouseover', function (e) {
  374. $(this).addClass('x-hover');
  375. return false;
  376. }).bind('mouseout', function (e) {
  377. $(this).removeClass('x-hover');
  378. });
  379. };
  380. return {
  381. format: format,
  382. postMessage: postMessage
  383. }
  384. })();
  385. var JsonFormatDealer = (function () {
  386. "use strict";
  387. // Constants
  388. var
  389. TYPE_STRING = 1,
  390. TYPE_NUMBER = 2,
  391. TYPE_OBJECT = 3,
  392. TYPE_ARRAY = 4,
  393. TYPE_BOOL = 5,
  394. TYPE_NULL = 6
  395. ;
  396. // Utility functions
  397. function removeComments(str) {
  398. str = ('__' + str + '__').split('');
  399. var mode = {
  400. singleQuote: false,
  401. doubleQuote: false,
  402. regex: false,
  403. blockComment: false,
  404. lineComment: false,
  405. condComp: false
  406. };
  407. for (var i = 0, l = str.length; i < l; i++) {
  408. if (mode.regex) {
  409. if (str[i] === '/' && str[i - 1] !== '\\') {
  410. mode.regex = false;
  411. }
  412. continue;
  413. }
  414. if (mode.singleQuote) {
  415. if (str[i] === "'" && str[i - 1] !== '\\') {
  416. mode.singleQuote = false;
  417. }
  418. continue;
  419. }
  420. if (mode.doubleQuote) {
  421. if (str[i] === '"' && str[i - 1] !== '\\') {
  422. mode.doubleQuote = false;
  423. }
  424. continue;
  425. }
  426. if (mode.blockComment) {
  427. if (str[i] === '*' && str[i + 1] === '/') {
  428. str[i + 1] = '';
  429. mode.blockComment = false;
  430. }
  431. str[i] = '';
  432. continue;
  433. }
  434. if (mode.lineComment) {
  435. if (str[i + 1] === '\n' || str[i + 1] === '\r') {
  436. mode.lineComment = false;
  437. }
  438. str[i] = '';
  439. continue;
  440. }
  441. if (mode.condComp) {
  442. if (str[i - 2] === '@' && str[i - 1] === '*' && str[i] === '/') {
  443. mode.condComp = false;
  444. }
  445. continue;
  446. }
  447. mode.doubleQuote = str[i] === '"';
  448. mode.singleQuote = str[i] === "'";
  449. if (str[i] === '/') {
  450. if (str[i + 1] === '*' && str[i + 2] === '@') {
  451. mode.condComp = true;
  452. continue;
  453. }
  454. if (str[i + 1] === '*') {
  455. str[i] = '';
  456. mode.blockComment = true;
  457. continue;
  458. }
  459. if (str[i + 1] === '/') {
  460. str[i] = '';
  461. mode.lineComment = true;
  462. continue;
  463. }
  464. mode.regex = true;
  465. }
  466. }
  467. return str.join('').slice(2, -2);
  468. }
  469. // function spin(seconds) {
  470. // // spin - Hog the CPU for the specified number of seconds
  471. // // (for simulating long processing times in development)
  472. // var stop = +new Date() + (seconds*1000) ;
  473. // while (new Date() < stop) {}
  474. // return true ;
  475. // }
  476. // Record current version (in case future update wants to know)
  477. localStorage.jfVersion = '0.5.6';
  478. // Template elements
  479. var templates,
  480. baseDiv = document.createElement('div'),
  481. baseSpan = document.createElement('span');
  482. function getSpanBoth(innerText, className) {
  483. var span = baseSpan.cloneNode(false);
  484. span.className = className;
  485. span.innerText = innerText;
  486. return span;
  487. }
  488. function getSpanText(innerText) {
  489. var span = baseSpan.cloneNode(false);
  490. span.innerText = innerText;
  491. return span;
  492. }
  493. function getSpanClass(className) {
  494. var span = baseSpan.cloneNode(false);
  495. span.className = className;
  496. return span;
  497. }
  498. function getDivClass(className) {
  499. var span = baseDiv.cloneNode(false);
  500. span.className = className;
  501. return span;
  502. }
  503. // Create template nodes
  504. var templatesObj = {
  505. t_kvov: getDivClass('kvov'),
  506. t_exp: getSpanClass('e'),
  507. t_key: getSpanClass('k'),
  508. t_string: getSpanClass('s'),
  509. t_number: getSpanClass('n'),
  510. t_null: getSpanBoth('null', 'nl'),
  511. t_true: getSpanBoth('true', 'bl'),
  512. t_false: getSpanBoth('false', 'bl'),
  513. t_oBrace: getSpanBoth('{', 'b'),
  514. t_cBrace: getSpanBoth('}', 'b'),
  515. t_oBracket: getSpanBoth('[', 'b'),
  516. t_cBracket: getSpanBoth(']', 'b'),
  517. t_ellipsis: getSpanClass('ell'),
  518. t_blockInner: getSpanClass('blockInner'),
  519. t_colonAndSpace: document.createTextNode(':\u00A0'),
  520. t_commaText: document.createTextNode(','),
  521. t_dblqText: document.createTextNode('"')
  522. };
  523. // Core recursive DOM-building function
  524. function getKvovDOM(value, keyName) {
  525. var type,
  526. kvov,
  527. nonZeroSize,
  528. templates = templatesObj, // bring into scope for tiny speed boost
  529. objKey,
  530. keySpan,
  531. valueElement
  532. ;
  533. // Establish value type
  534. if (typeof value === 'string')
  535. type = TYPE_STRING;
  536. else if (typeof value === 'number')
  537. type = TYPE_NUMBER;
  538. else if (value === false || value === true)
  539. type = TYPE_BOOL;
  540. else if (value === null)
  541. type = TYPE_NULL;
  542. else if (value instanceof Array)
  543. type = TYPE_ARRAY;
  544. else
  545. type = TYPE_OBJECT;
  546. // Root node for this kvov
  547. kvov = templates.t_kvov.cloneNode(false);
  548. // Add an 'expander' first (if this is object/array with non-zero size)
  549. if (type === TYPE_OBJECT || type === TYPE_ARRAY) {
  550. nonZeroSize = false;
  551. for (objKey in value) {
  552. if (value.hasOwnProperty(objKey)) {
  553. nonZeroSize = true;
  554. break; // no need to keep counting; only need one
  555. }
  556. }
  557. if (nonZeroSize)
  558. kvov.appendChild(templates.t_exp.cloneNode(false));
  559. }
  560. // If there's a key, add that before the value
  561. if (keyName !== false) { // NB: "" is a legal keyname in JSON
  562. // This kvov must be an object property
  563. kvov.classList.add('objProp');
  564. // Create a span for the key name
  565. keySpan = templates.t_key.cloneNode(false);
  566. keySpan.textContent = JSON.stringify(keyName).slice(1, -1); // remove quotes
  567. // Add it to kvov, with quote marks
  568. kvov.appendChild(templates.t_dblqText.cloneNode(false));
  569. kvov.appendChild(keySpan);
  570. kvov.appendChild(templates.t_dblqText.cloneNode(false));
  571. // Also add ":&nbsp;" (colon and non-breaking space)
  572. kvov.appendChild(templates.t_colonAndSpace.cloneNode(false));
  573. }
  574. else {
  575. // This is an array element instead
  576. kvov.classList.add('arrElem');
  577. }
  578. // Generate DOM for this value
  579. var blockInner, childKvov;
  580. switch (type) {
  581. case TYPE_STRING:
  582. // If string is a URL, get a link, otherwise get a span
  583. var innerStringEl = baseSpan.cloneNode(false),
  584. escapedString = JSON.stringify(value);
  585. escapedString = escapedString.substring(1, escapedString.length - 1); // remove quotes
  586. 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.
  587. var innerStringA = document.createElement('A');
  588. innerStringA.href = value;
  589. innerStringA.innerText = escapedString;
  590. innerStringEl.appendChild(innerStringA);
  591. }
  592. else {
  593. innerStringEl.innerText = escapedString;
  594. }
  595. valueElement = templates.t_string.cloneNode(false);
  596. valueElement.appendChild(templates.t_dblqText.cloneNode(false));
  597. valueElement.appendChild(innerStringEl);
  598. valueElement.appendChild(templates.t_dblqText.cloneNode(false));
  599. kvov.appendChild(valueElement);
  600. break;
  601. case TYPE_NUMBER:
  602. // Simply add a number element (span.n)
  603. valueElement = templates.t_number.cloneNode(false);
  604. valueElement.innerText = value;
  605. kvov.appendChild(valueElement);
  606. break;
  607. case TYPE_OBJECT:
  608. // Add opening brace
  609. kvov.appendChild(templates.t_oBrace.cloneNode(true));
  610. // If any properties, add a blockInner containing k/v pair(s)
  611. if (nonZeroSize) {
  612. // Add ellipsis (empty, but will be made to do something when kvov is collapsed)
  613. kvov.appendChild(templates.t_ellipsis.cloneNode(false));
  614. // Create blockInner, which indents (don't attach yet)
  615. blockInner = templates.t_blockInner.cloneNode(false);
  616. // For each key/value pair, add as a kvov to blockInner
  617. var count = 0, k, comma;
  618. for (k in value) {
  619. if (value.hasOwnProperty(k)) {
  620. count++;
  621. childKvov = getKvovDOM(value[k], k);
  622. // Add comma
  623. comma = templates.t_commaText.cloneNode();
  624. childKvov.appendChild(comma);
  625. blockInner.appendChild(childKvov);
  626. }
  627. }
  628. // Now remove the last comma
  629. childKvov.removeChild(comma);
  630. // Add blockInner
  631. kvov.appendChild(blockInner);
  632. }
  633. // Add closing brace
  634. kvov.appendChild(templates.t_cBrace.cloneNode(true));
  635. break;
  636. case TYPE_ARRAY:
  637. // Add opening bracket
  638. kvov.appendChild(templates.t_oBracket.cloneNode(true));
  639. // If non-zero length array, add blockInner containing inner vals
  640. if (nonZeroSize) {
  641. // Add ellipsis
  642. kvov.appendChild(templates.t_ellipsis.cloneNode(false));
  643. // Create blockInner (which indents) (don't attach yet)
  644. blockInner = templates.t_blockInner.cloneNode(false);
  645. // For each key/value pair, add the markup
  646. for (var i = 0, length = value.length, lastIndex = length - 1; i < length; i++) {
  647. // Make a new kvov, with no key
  648. childKvov = getKvovDOM(value[i], false);
  649. // Add comma if not last one
  650. if (i < lastIndex)
  651. childKvov.appendChild(templates.t_commaText.cloneNode());
  652. // Append the child kvov
  653. blockInner.appendChild(childKvov);
  654. }
  655. // Add blockInner
  656. kvov.appendChild(blockInner);
  657. }
  658. // Add closing bracket
  659. kvov.appendChild(templates.t_cBracket.cloneNode(true));
  660. break;
  661. case TYPE_BOOL:
  662. if (value)
  663. kvov.appendChild(templates.t_true.cloneNode(true));
  664. else
  665. kvov.appendChild(templates.t_false.cloneNode(true));
  666. break;
  667. case TYPE_NULL:
  668. kvov.appendChild(templates.t_null.cloneNode(true));
  669. break;
  670. }
  671. return kvov;
  672. }
  673. // Function to convert object to an HTML string
  674. function jsonObjToHTML(obj, jsonpFunctionName) {
  675. // spin(5) ;
  676. // Format object (using recursive kvov builder)
  677. var rootKvov = getKvovDOM(obj, false);
  678. // The whole DOM is now built.
  679. // Set class on root node to identify it
  680. rootKvov.classList.add('rootKvov');
  681. // Make div#formattedJson and append the root kvov
  682. var divFormattedJson = document.createElement('DIV');
  683. divFormattedJson.id = 'formattedJson';
  684. divFormattedJson.appendChild(rootKvov);
  685. // Convert it to an HTML string (shame about this step, but necessary for passing it through to the content page)
  686. var returnHTML = divFormattedJson.outerHTML;
  687. // Top and tail with JSONP padding if necessary
  688. if (jsonpFunctionName !== null) {
  689. returnHTML =
  690. '<div id="jsonpOpener">' + jsonpFunctionName + ' ( </div>' +
  691. returnHTML +
  692. '<div id="jsonpCloser">)</div>';
  693. }
  694. // Return the HTML
  695. return returnHTML;
  696. }
  697. // Listen for requests from content pages wanting to set up a port
  698. var postMessage = function (msg) {
  699. var jsonpFunctionName = null;
  700. if (msg.type === 'SENDING TEXT') {
  701. // Try to parse as JSON
  702. var obj,
  703. text = msg.text;
  704. try {
  705. obj = new Function('return ' + text)();
  706. }
  707. catch (e) {
  708. // Not JSON; could be JSONP though.
  709. // Try stripping 'padding' (if any), and try parsing it again
  710. text = text.trim();
  711. // Find where the first paren is (and exit if none)
  712. var indexOfParen;
  713. if (!(indexOfParen = text.indexOf('('))) {
  714. JsonFormatEntrance.postMessage(['NOT JSON', 'no opening parenthesis']);
  715. return;
  716. }
  717. // Get the substring up to the first "(", with any comments/whitespace stripped out
  718. var firstBit = removeComments(text.substring(0, indexOfParen)).trim();
  719. if (!firstBit.match(/^[a-zA-Z_$][\.\[\]'"0-9a-zA-Z_$]*$/)) {
  720. // The 'firstBit' is NOT a valid function identifier.
  721. JsonFormatEntrance.postMessage(['NOT JSON', 'first bit not a valid function name']);
  722. return;
  723. }
  724. // Find last parenthesis (exit if none)
  725. var indexOfLastParen;
  726. if (!(indexOfLastParen = text.lastIndexOf(')'))) {
  727. JsonFormatEntrance.postMessage(['NOT JSON', 'no closing paren']);
  728. return;
  729. }
  730. // Check that what's after the last parenthesis is just whitespace, comments, and possibly a semicolon (exit if anything else)
  731. var lastBit = removeComments(text.substring(indexOfLastParen + 1)).trim();
  732. if (lastBit !== "" && lastBit !== ';') {
  733. JsonFormatEntrance.postMessage(['NOT JSON', 'last closing paren followed by invalid characters']);
  734. return;
  735. }
  736. // So, it looks like a valid JS function call, but we don't know whether it's JSON inside the parentheses...
  737. // Check if the 'argument' is actually JSON (and record the parsed result)
  738. text = text.substring(indexOfParen + 1, indexOfLastParen);
  739. try {
  740. obj = JSON.parse(text);
  741. }
  742. catch (e2) {
  743. // Just some other text that happens to be in a function call.
  744. // Respond as not JSON, and exit
  745. JsonFormatEntrance.postMessage(['NOT JSON', 'looks like a function call, but the parameter is not valid JSON']);
  746. return;
  747. }
  748. jsonpFunctionName = firstBit;
  749. }
  750. // If still running, we now have obj, which is valid JSON.
  751. // Ensure it's not a number or string (technically valid JSON, but no point prettifying it)
  752. if (typeof obj !== 'object' && typeof obj !== 'array') {
  753. JsonFormatEntrance.postMessage(['NOT JSON', 'technically JSON but not an object or array']);
  754. return;
  755. }
  756. // And send it the message to confirm that we're now formatting (so it can show a spinner)
  757. JsonFormatEntrance.postMessage(['FORMATTING' /*, JSON.stringify(localStorage)*/]);
  758. // Do formatting
  759. var html = jsonObjToHTML(obj, jsonpFunctionName);
  760. // Post the HTML string to the content script
  761. JsonFormatEntrance.postMessage(['FORMATTED', html]);
  762. }
  763. };
  764. return {
  765. postMessage: postMessage
  766. };
  767. })();
  768. module.exports = {
  769. format: JsonFormatEntrance.format
  770. };