index.js 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. /**
  2. * FeHelper Json Format Tools
  3. */
  4. let editor = {};
  5. let LOCAL_KEY_OF_LAYOUT = 'local-layout-key';
  6. let JSON_LINT = 'jsonformat:json-lint-switch';
  7. let EDIT_ON_CLICK = 'jsonformat:edit-on-click';
  8. // json with bigint supported
  9. Tarp.require('../static/vendor/json-bigint/index');
  10. new Vue({
  11. el: '#pageContainer',
  12. data: {
  13. defaultResultTpl: '<div class="x-placeholder"><img src="./json-demo.jpg" alt="json-placeholder"></div>',
  14. resultContent: '',
  15. jsonFormattedSource: '',
  16. errorMsg: '',
  17. errorJsonCode: '',
  18. errorPos: '',
  19. jfCallbackName_start: '',
  20. jfCallbackName_end: '',
  21. showTips: false,
  22. jsonLintSwitch: true,
  23. fireChange: true,
  24. overrideJson: false
  25. },
  26. mounted: function () {
  27. this.resultContent = this.defaultResultTpl;
  28. this.jsonLintSwitch = (localStorage.getItem(JSON_LINT) !== 'false');
  29. this.overrideJson = (localStorage.getItem(EDIT_ON_CLICK) === 'true');
  30. this.changeLayout(localStorage.getItem(LOCAL_KEY_OF_LAYOUT));
  31. editor = CodeMirror.fromTextArea(this.$refs.jsonBox, {
  32. mode: "text/javascript",
  33. lineNumbers: true,
  34. matchBrackets: true,
  35. styleActiveLine: true,
  36. lineWrapping: true
  37. });
  38. //输入框聚焦
  39. editor.focus();
  40. // 格式化以后的JSON,点击以后可以重置原内容
  41. window._OnJsonItemClickByFH = (jsonTxt) => {
  42. if (this.overrideJson) {
  43. this.disableEditorChange(jsonTxt);
  44. }
  45. };
  46. editor.on('change', (editor, changes) => {
  47. this.fireChange && this.format();
  48. });
  49. // 在tab创建或者更新时候,监听事件,看看是否有参数传递过来
  50. chrome.runtime.onMessage.addListener((request, sender, callback) => {
  51. let MSG_TYPE = Tarp.require('../static/js/msg_type');
  52. if (request.type === MSG_TYPE.TAB_CREATED_OR_UPDATED && request.event === MSG_TYPE.JSON_FORMAT) {
  53. if (request.content) {
  54. editor.setValue(request.content || this.defaultResultTpl);
  55. this.format();
  56. }
  57. }
  58. });
  59. },
  60. methods: {
  61. format: function () {
  62. this.showTips = false;
  63. this.errorMsg = '';
  64. this.resultContent = this.defaultResultTpl;
  65. let source = editor.getValue().replace(/\n/gm, ' ');
  66. if (!source) {
  67. return true;
  68. }
  69. // JSONP形式下的callback name
  70. let funcName = null;
  71. // json对象
  72. let jsonObj = null;
  73. // 下面校验给定字符串是否为一个合法的json
  74. try {
  75. // 再看看是不是jsonp的格式
  76. let reg = /^([\w\.]+)\(\s*([\s\S]*)\s*\)$/igm;
  77. let matches = reg.exec(source);
  78. if (matches != null) {
  79. funcName = matches[1];
  80. source = matches[2];
  81. }
  82. // 这里可能会throw exception
  83. jsonObj = JSON.parse(source);
  84. } catch (ex) {
  85. // new Function的方式,能自动给key补全双引号,但是不支持bigint,所以是下下策,放在try-catch里搞
  86. try {
  87. jsonObj = new Function("return " + source)();
  88. } catch (exx) {
  89. try {
  90. // 再给你一次机会,是不是下面这种情况: "{\"ret\":\"0\", \"msg\":\"ok\"}"
  91. jsonObj = new Function("return '" + source + "'")();
  92. if (typeof jsonObj === 'string') {
  93. // 最后给你一次机会,是个字符串,老夫给你再转一次
  94. jsonObj = new Function("return " + jsonObj)();
  95. }
  96. } catch (exxx) {
  97. this.errorMsg = exxx.message;
  98. }
  99. }
  100. }
  101. // 是json格式,可以进行JSON自动格式化
  102. if (jsonObj != null && typeof jsonObj === "object" && !this.errorMsg.length) {
  103. try {
  104. // 要尽量保证格式化的东西一定是一个json,所以需要把内容进行JSON.stringify处理
  105. source = JSON.stringify(jsonObj);
  106. } catch (ex) {
  107. // 通过JSON反解不出来的,一定有问题
  108. this.errorMsg = ex.message;
  109. }
  110. if (!this.errorMsg.length) {
  111. // 格式化
  112. Tarp.require('./format-lib').format(source);
  113. this.jsonFormattedSource = source;
  114. // 如果是JSONP格式的,需要把方法名也显示出来
  115. if (funcName != null) {
  116. this.jfCallbackName_start = funcName + '(';
  117. this.jfCallbackName_end = ')';
  118. } else {
  119. this.jfCallbackName_start = '';
  120. this.jfCallbackName_end = '';
  121. }
  122. }
  123. }
  124. if (this.errorMsg.length) {
  125. if (this.jsonLintSwitch) {
  126. return this.lintOn();
  127. } else {
  128. this.resultContent = '<span class="x-error">' + this.errorMsg + '</span>';
  129. return true;
  130. }
  131. }
  132. },
  133. compress: function () {
  134. if (this.format()) {
  135. let jsonTxt = this.jfCallbackName_start + this.jsonFormattedSource + this.jfCallbackName_end;
  136. this.disableEditorChange(jsonTxt);
  137. }
  138. },
  139. changeLayout: function (type) {
  140. if (type === 'up-down') {
  141. if (this.$refs.btnUpDown.classList.contains('selected')) {
  142. return;
  143. }
  144. this.$refs.panelBody.classList.add('layout-up-down');
  145. this.$refs.btnLeftRight.classList.remove('selected');
  146. this.$refs.btnUpDown.classList.add('selected');
  147. } else {
  148. if (this.$refs.btnLeftRight.classList.contains('selected')) {
  149. return;
  150. }
  151. this.$refs.panelBody.classList.remove('layout-up-down');
  152. this.$refs.btnLeftRight.classList.add('selected');
  153. this.$refs.btnUpDown.classList.remove('selected');
  154. }
  155. localStorage.setItem(LOCAL_KEY_OF_LAYOUT, type);
  156. },
  157. setCache: function () {
  158. this.$nextTick(() => {
  159. localStorage.setItem(EDIT_ON_CLICK, this.overrideJson);
  160. });
  161. },
  162. lintOn: function () {
  163. this.$nextTick(() => {
  164. localStorage.setItem(JSON_LINT, this.jsonLintSwitch);
  165. });
  166. if (!editor.getValue().trim()) {
  167. return true;
  168. }
  169. this.$nextTick(() => {
  170. if (!this.jsonLintSwitch) {
  171. return;
  172. }
  173. let lintResult = Tarp.require('./jsonlint')(editor.getValue());
  174. if (!isNaN(lintResult.line)) {
  175. this.errorPos = '错误位置:' + (lintResult.line + 1) + '行,' + (lintResult.col + 1) + '列;缺少字符或字符不正确';
  176. this.errorJsonCode = lintResult.dom;
  177. this.showTips = true;
  178. this.$nextTick(() => {
  179. let el = document.querySelector('#errorCode .errorEm');
  180. el && el.scrollIntoView();
  181. let scrollEl = document.querySelector('#errorTips');
  182. scrollEl.scrollBy(0, el.offsetTop - scrollEl.scrollTop - 50);
  183. });
  184. }
  185. });
  186. return false;
  187. },
  188. closeTips: function () {
  189. this.showTips = false;
  190. },
  191. disableEditorChange: function (jsonTxt) {
  192. this.fireChange = false;
  193. this.$nextTick(() => {
  194. editor.setValue(jsonTxt);
  195. this.$nextTick(() => {
  196. this.fireChange = true;
  197. })
  198. })
  199. },
  200. setDemo: function () {
  201. 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":"阴晴之间,谨防紫外线侵扰"}]}}';
  202. editor.setValue(demo);
  203. }
  204. }
  205. });