format-lib.js 32 KB

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