format-lib.js 30 KB

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