index.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. /**
  2. * FeHelper Json Format Tools
  3. */
  4. // 一些全局变量
  5. let editor = {};
  6. let LOCAL_KEY_OF_LAYOUT = 'local-layout-key';
  7. let JSON_LINT = 'jsonformat:json-lint-switch';
  8. let EDIT_ON_CLICK = 'jsonformat:edit-on-click';
  9. let AUTO_DECODE = 'jsonformat:auto-decode';
  10. new Vue({
  11. el: '#pageContainer',
  12. data: {
  13. defaultResultTpl: '<div class="x-placeholder"><img src="../json-format/json-demo.jpg" alt="json-placeholder"></div>',
  14. placeHolder: '',
  15. jsonFormattedSource: '',
  16. errorMsg: '',
  17. errorJsonCode: '',
  18. errorPos: '',
  19. jfCallbackName_start: '',
  20. jfCallbackName_end: '',
  21. jsonLintSwitch: true,
  22. autoDecode: false,
  23. fireChange: true,
  24. overrideJson: false
  25. },
  26. mounted: function () {
  27. // 自动开关灯控制
  28. DarkModeMgr.turnLightAuto();
  29. this.placeHolder = this.defaultResultTpl;
  30. this.autoDecode = localStorage.getItem(AUTO_DECODE);
  31. this.autoDecode = this.autoDecode === 'true';
  32. this.jsonLintSwitch = (localStorage.getItem(JSON_LINT) !== 'false');
  33. this.overrideJson = (localStorage.getItem(EDIT_ON_CLICK) === 'true');
  34. this.changeLayout(localStorage.getItem(LOCAL_KEY_OF_LAYOUT));
  35. editor = CodeMirror.fromTextArea(this.$refs.jsonBox, {
  36. mode: "text/javascript",
  37. lineNumbers: true,
  38. matchBrackets: true,
  39. styleActiveLine: true,
  40. lineWrapping: true
  41. });
  42. //输入框聚焦
  43. editor.focus();
  44. // 格式化以后的JSON,点击以后可以重置原内容
  45. window._OnJsonItemClickByFH = (jsonTxt) => {
  46. if (this.overrideJson) {
  47. this.disableEditorChange(jsonTxt);
  48. }
  49. };
  50. editor.on('change', (editor, changes) => {
  51. this.jsonFormattedSource = editor.getValue().replace(/\n/gm, ' ');
  52. this.fireChange && this.format();
  53. });
  54. // 在tab创建或者更新时候,监听事件,看看是否有参数传递过来
  55. if (location.protocol === 'chrome-extension:') {
  56. chrome.tabs.query({currentWindow: true,active: true, }, (tabs) => {
  57. let activeTab = tabs.filter(tab => tab.active)[0];
  58. chrome.runtime.sendMessage({
  59. type: 'fh-dynamic-any-thing',
  60. thing: 'request-page-content',
  61. tabId: activeTab.id
  62. }).then(resp => {
  63. if(!resp || !resp.content) return ;
  64. editor.setValue(resp.content || '');
  65. this.format();
  66. });
  67. });
  68. }
  69. },
  70. methods: {
  71. format: function () {
  72. this.errorMsg = '';
  73. this.placeHolder = this.defaultResultTpl;
  74. this.jfCallbackName_start = '';
  75. this.jfCallbackName_end = '';
  76. let source = editor.getValue().replace(/\n/gm, ' ');
  77. if (!source) {
  78. return false;
  79. }
  80. // JSONP形式下的callback name
  81. let funcName = null;
  82. // json对象
  83. let jsonObj = null;
  84. // 下面校验给定字符串是否为一个合法的json
  85. try {
  86. // 再看看是不是jsonp的格式
  87. let reg = /^([\w\.]+)\(\s*([\s\S]*)\s*\)$/igm;
  88. let matches = reg.exec(source);
  89. if (matches != null) {
  90. funcName = matches[1];
  91. source = matches[2];
  92. }
  93. // 这里可能会throw exception
  94. jsonObj = JSON.parse(source);
  95. } catch (ex) {
  96. // new Function的方式,能自动给key补全双引号,但是不支持bigint,所以是下下策,放在try-catch里搞
  97. try {
  98. jsonObj = new Function("return " + source)();
  99. } catch (exx) {
  100. try {
  101. // 再给你一次机会,是不是下面这种情况: "{\"ret\":\"0\", \"msg\":\"ok\"}"
  102. jsonObj = new Function("return '" + source + "'")();
  103. if (typeof jsonObj === 'string') {
  104. try {
  105. // 确保bigint不会失真
  106. jsonObj = JSON.parse(jsonObj);
  107. } catch (ie) {
  108. // 最后给你一次机会,是个字符串,老夫给你再转一次
  109. jsonObj = new Function("return " + jsonObj)();
  110. }
  111. }
  112. } catch (exxx) {
  113. this.errorMsg = exxx.message;
  114. }
  115. }
  116. }
  117. // 是json格式,可以进行JSON自动格式化
  118. if (jsonObj != null && typeof jsonObj === "object" && !this.errorMsg.length) {
  119. try {
  120. let sortType = document.querySelectorAll('[name=jsonsort]:checked')[0].value;
  121. if (sortType !== '0') {
  122. jsonObj = JsonABC.sortObj(jsonObj, parseInt(sortType), true);
  123. }
  124. source = JSON.stringify(jsonObj);
  125. } catch (ex) {
  126. // 通过JSON反解不出来的,一定有问题
  127. this.errorMsg = ex.message;
  128. }
  129. if (!this.errorMsg.length) {
  130. if (this.autoDecode) {
  131. (async () => {
  132. let txt = await JsonEnDecode.urlDecodeByFetch(source);
  133. source = JsonEnDecode.uniDecode(txt);
  134. Formatter.format(source);
  135. })();
  136. } else {
  137. Formatter.format(source);
  138. }
  139. this.placeHolder = '';
  140. this.jsonFormattedSource = source;
  141. // 如果是JSONP格式的,需要把方法名也显示出来
  142. if (funcName != null) {
  143. this.jfCallbackName_start = funcName + '(';
  144. this.jfCallbackName_end = ')';
  145. } else {
  146. this.jfCallbackName_start = '';
  147. this.jfCallbackName_end = '';
  148. }
  149. this.$nextTick(() => {
  150. this.updateWrapperHeight();
  151. })
  152. }
  153. }
  154. if (this.errorMsg.length) {
  155. if (this.jsonLintSwitch) {
  156. return this.lintOn();
  157. } else {
  158. this.placeHolder = '<span class="x-error">' + this.errorMsg + '</span>';
  159. return false;
  160. }
  161. }
  162. return true;
  163. },
  164. compress: function () {
  165. if (this.format()) {
  166. let jsonTxt = this.jfCallbackName_start + this.jsonFormattedSource + this.jfCallbackName_end;
  167. this.disableEditorChange(jsonTxt);
  168. }
  169. },
  170. autoDecodeFn: function () {
  171. this.$nextTick(() => {
  172. localStorage.setItem(AUTO_DECODE, this.autoDecode);
  173. this.format();
  174. });
  175. },
  176. uniEncode: function () {
  177. editor.setValue(JsonEnDecode.uniEncode(editor.getValue()));
  178. },
  179. uniDecode: function () {
  180. editor.setValue(JsonEnDecode.uniDecode(editor.getValue()));
  181. },
  182. urlDecode: function () {
  183. JsonEnDecode.urlDecodeByFetch(editor.getValue()).then(text => editor.setValue(text));
  184. },
  185. updateWrapperHeight: function () {
  186. let curLayout = localStorage.getItem(LOCAL_KEY_OF_LAYOUT);
  187. let elPc = document.querySelector('#pageContainer');
  188. if (curLayout === 'up-down') {
  189. elPc.style.height = 'auto';
  190. } else {
  191. elPc.style.height = Math.max(elPc.scrollHeight, document.body.scrollHeight) + 'px';
  192. }
  193. },
  194. changeLayout: function (type) {
  195. let elPc = document.querySelector('#pageContainer');
  196. if (type === 'up-down') {
  197. elPc.classList.remove('layout-left-right');
  198. elPc.classList.add('layout-up-down');
  199. this.$refs.btnLeftRight.classList.remove('selected');
  200. this.$refs.btnUpDown.classList.add('selected');
  201. } else {
  202. elPc.classList.remove('layout-up-down');
  203. elPc.classList.add('layout-left-right');
  204. this.$refs.btnLeftRight.classList.add('selected');
  205. this.$refs.btnUpDown.classList.remove('selected');
  206. }
  207. localStorage.setItem(LOCAL_KEY_OF_LAYOUT, type);
  208. this.updateWrapperHeight();
  209. },
  210. setCache: function () {
  211. this.$nextTick(() => {
  212. localStorage.setItem(EDIT_ON_CLICK, this.overrideJson);
  213. });
  214. },
  215. lintOn: function () {
  216. this.$nextTick(() => {
  217. localStorage.setItem(JSON_LINT, this.jsonLintSwitch);
  218. });
  219. if (!editor.getValue().trim()) {
  220. return true;
  221. }
  222. this.$nextTick(() => {
  223. if (!this.jsonLintSwitch) {
  224. return;
  225. }
  226. let lintResult = JsonLint.lintDetect(editor.getValue());
  227. if (!isNaN(lintResult.line)) {
  228. this.placeHolder = '<div id="errorTips">' +
  229. '<div id="tipsBox">错误位置:' + (lintResult.line + 1) + '行,' + (lintResult.col + 1) + '列;缺少字符或字符不正确</div>' +
  230. '<div id="errorCode">' + lintResult.dom + '</div></div>';
  231. }
  232. });
  233. return false;
  234. },
  235. disableEditorChange: function (jsonTxt) {
  236. this.fireChange = false;
  237. this.$nextTick(() => {
  238. editor.setValue(jsonTxt);
  239. this.$nextTick(() => {
  240. this.fireChange = true;
  241. })
  242. })
  243. },
  244. openOptionsPage: function(){
  245. chrome.runtime.openOptionsPage();
  246. },
  247. setDemo: function () {
  248. let demo = '{"BigIntSupported":995815895020119788889,"date":"20180322","message":"Success !","status":200,"city":"北京","count":632,"data":{"shidu":"34%","pm25":73,"pm10":91,"quality":"良","wendu":"5","ganmao":"极少数敏感人群应减少户外活动","yesterday":{"date":"21日星期三","sunrise":"06:19","high":"高温 11.0℃","low":"低温 1.0℃","sunset":"18:26","aqi":85,"fx":"南风","fl":"<3级","type":"多云","notice":"阴晴之间,谨防紫外线侵扰"},"forecast":[{"date":"22日星期四","sunrise":"06:17","high":"高温 17.0℃","low":"低温 1.0℃","sunset":"18:27","aqi":98,"fx":"西南风","fl":"<3级","type":"晴","notice":"愿你拥有比阳光明媚的心情"},{"date":"23日星期五","sunrise":"06:16","high":"高温 18.0℃","low":"低温 5.0℃","sunset":"18:28","aqi":118,"fx":"无持续风向","fl":"<3级","type":"多云","notice":"阴晴之间,谨防紫外线侵扰"},{"date":"24日星期六","sunrise":"06:14","high":"高温 21.0℃","low":"低温 7.0℃","sunset":"18:29","aqi":52,"fx":"西南风","fl":"<3级","type":"晴","notice":"愿你拥有比阳光明媚的心情"},{"date":"25日星期日","sunrise":"06:13","high":"高温 22.0℃","low":"低温 7.0℃","sunset":"18:30","aqi":71,"fx":"西南风","fl":"<3级","type":"晴","notice":"愿你拥有比阳光明媚的心情"},{"date":"26日星期一","sunrise":"06:11","high":"高温 21.0℃","low":"低温 8.0℃","sunset":"18:31","aqi":97,"fx":"西南风","fl":"<3级","type":"多云","notice":"阴晴之间,谨防紫外线侵扰"}]}}';
  249. editor.setValue(demo);
  250. this.$nextTick(() => {
  251. this.format();
  252. })
  253. }
  254. }
  255. });