index.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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. isInUSAFlag: false
  26. },
  27. mounted: function () {
  28. // 自动开关灯控制
  29. DarkModeMgr.turnLightAuto();
  30. this.placeHolder = this.defaultResultTpl;
  31. this.autoDecode = localStorage.getItem(AUTO_DECODE);
  32. this.autoDecode = this.autoDecode === 'true';
  33. this.isInUSAFlag = this.isInUSA();
  34. this.jsonLintSwitch = (localStorage.getItem(JSON_LINT) !== 'false');
  35. this.overrideJson = (localStorage.getItem(EDIT_ON_CLICK) === 'true');
  36. this.changeLayout(localStorage.getItem(LOCAL_KEY_OF_LAYOUT));
  37. editor = CodeMirror.fromTextArea(this.$refs.jsonBox, {
  38. mode: "text/javascript",
  39. lineNumbers: true,
  40. matchBrackets: true,
  41. styleActiveLine: true,
  42. lineWrapping: true
  43. });
  44. //输入框聚焦
  45. editor.focus();
  46. // 格式化以后的JSON,点击以后可以重置原内容
  47. window._OnJsonItemClickByFH = (jsonTxt) => {
  48. if (this.overrideJson) {
  49. this.disableEditorChange(jsonTxt);
  50. }
  51. };
  52. editor.on('change', (editor, changes) => {
  53. this.jsonFormattedSource = editor.getValue().replace(/\n/gm, ' ');
  54. this.fireChange && this.format();
  55. });
  56. // 在tab创建或者更新时候,监听事件,看看是否有参数传递过来
  57. if (location.protocol === 'chrome-extension:') {
  58. chrome.tabs.query({currentWindow: true,active: true, }, (tabs) => {
  59. let activeTab = tabs.filter(tab => tab.active)[0];
  60. chrome.runtime.sendMessage({
  61. type: 'fh-dynamic-any-thing',
  62. thing: 'request-page-content',
  63. tabId: activeTab.id
  64. }).then(resp => {
  65. if(!resp || !resp.content) return ;
  66. editor.setValue(resp.content || '');
  67. this.format();
  68. });
  69. });
  70. }
  71. },
  72. methods: {
  73. isInUSA: function () {
  74. // 通过时区判断是否在美国
  75. const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
  76. const isUSTimeZone = /^America\/(New_York|Chicago|Denver|Los_Angeles|Anchorage|Honolulu)/.test(timeZone);
  77. // 通过语言判断
  78. const language = navigator.language || navigator.userLanguage;
  79. const isUSLanguage = language.toLowerCase().indexOf('en-us') > -1;
  80. // 如果时区和语言都符合美国特征,则认为在美国
  81. return (isUSTimeZone && isUSLanguage);
  82. },
  83. format: function () {
  84. this.errorMsg = '';
  85. this.placeHolder = this.defaultResultTpl;
  86. this.jfCallbackName_start = '';
  87. this.jfCallbackName_end = '';
  88. let source = editor.getValue().replace(/\n/gm, ' ');
  89. if (!source) {
  90. return false;
  91. }
  92. // JSONP形式下的callback name
  93. let funcName = null;
  94. // json对象
  95. let jsonObj = null;
  96. // 下面校验给定字符串是否为一个合法的json
  97. try {
  98. // 再看看是不是jsonp的格式
  99. let reg = /^([\w\.]+)\(\s*([\s\S]*)\s*\)$/igm;
  100. let matches = reg.exec(source);
  101. if (matches != null) {
  102. funcName = matches[1];
  103. source = matches[2];
  104. }
  105. // 这里可能会throw exception
  106. jsonObj = JSON.parse(source);
  107. } catch (ex) {
  108. // new Function的方式,能自动给key补全双引号,但是不支持bigint,所以是下下策,放在try-catch里搞
  109. try {
  110. jsonObj = new Function("return " + source)();
  111. } catch (exx) {
  112. try {
  113. // 再给你一次机会,是不是下面这种情况: "{\"ret\":\"0\", \"msg\":\"ok\"}"
  114. jsonObj = new Function("return '" + source + "'")();
  115. if (typeof jsonObj === 'string') {
  116. try {
  117. // 确保bigint不会失真
  118. jsonObj = JSON.parse(jsonObj);
  119. } catch (ie) {
  120. // 最后给你一次机会,是个字符串,老夫给你再转一次
  121. jsonObj = new Function("return " + jsonObj)();
  122. }
  123. }
  124. } catch (exxx) {
  125. this.errorMsg = exxx.message;
  126. }
  127. }
  128. }
  129. try{
  130. // 这里多做一个动作,给没有携带双引号的Key都自动加上,防止Long类型失真
  131. const regex = /([{,]\s*)(\w+)(\s*:)/g;
  132. source = source.replace(regex, '$1"$2"$3');
  133. jsonObj = JSON.parse(source);
  134. }catch(e){
  135. // 这里什么动作都不需要做,这种情况下转换失败的,肯定是Value被污染了,抛弃即可
  136. }
  137. // 是json格式,可以进行JSON自动格式化
  138. if (jsonObj != null && typeof jsonObj === "object" && !this.errorMsg.length) {
  139. try {
  140. let sortType = document.querySelectorAll('[name=jsonsort]:checked')[0].value;
  141. if (sortType !== '0') {
  142. jsonObj = JsonABC.sortObj(jsonObj, parseInt(sortType), true);
  143. }
  144. source = JSON.stringify(jsonObj);
  145. } catch (ex) {
  146. // 通过JSON反解不出来的,一定有问题
  147. this.errorMsg = ex.message;
  148. }
  149. if (!this.errorMsg.length) {
  150. if (this.autoDecode) {
  151. (async () => {
  152. let txt = await JsonEnDecode.urlDecodeByFetch(source);
  153. source = JsonEnDecode.uniDecode(txt);
  154. Formatter.format(source);
  155. })();
  156. } else {
  157. Formatter.format(source);
  158. }
  159. this.placeHolder = '';
  160. this.jsonFormattedSource = source;
  161. // 如果是JSONP格式的,需要把方法名也显示出来
  162. if (funcName != null) {
  163. this.jfCallbackName_start = funcName + '(';
  164. this.jfCallbackName_end = ')';
  165. } else {
  166. this.jfCallbackName_start = '';
  167. this.jfCallbackName_end = '';
  168. }
  169. this.$nextTick(() => {
  170. this.updateWrapperHeight();
  171. })
  172. }
  173. }
  174. if (this.errorMsg.length) {
  175. if (this.jsonLintSwitch) {
  176. return this.lintOn();
  177. } else {
  178. this.placeHolder = '<span class="x-error">' + this.errorMsg + '</span>';
  179. return false;
  180. }
  181. }
  182. return true;
  183. },
  184. compress: function () {
  185. if (this.format()) {
  186. let jsonTxt = this.jfCallbackName_start + this.jsonFormattedSource + this.jfCallbackName_end;
  187. this.disableEditorChange(jsonTxt);
  188. }
  189. },
  190. autoDecodeFn: function () {
  191. this.$nextTick(() => {
  192. localStorage.setItem(AUTO_DECODE, this.autoDecode);
  193. this.format();
  194. });
  195. },
  196. uniEncode: function () {
  197. editor.setValue(JsonEnDecode.uniEncode(editor.getValue()));
  198. },
  199. uniDecode: function () {
  200. editor.setValue(JsonEnDecode.uniDecode(editor.getValue()));
  201. },
  202. urlDecode: function () {
  203. JsonEnDecode.urlDecodeByFetch(editor.getValue()).then(text => editor.setValue(text));
  204. },
  205. updateWrapperHeight: function () {
  206. let curLayout = localStorage.getItem(LOCAL_KEY_OF_LAYOUT);
  207. let elPc = document.querySelector('#pageContainer');
  208. if (curLayout === 'up-down') {
  209. elPc.style.height = 'auto';
  210. } else {
  211. elPc.style.height = Math.max(elPc.scrollHeight, document.body.scrollHeight) + 'px';
  212. }
  213. },
  214. changeLayout: function (type) {
  215. let elPc = document.querySelector('#pageContainer');
  216. if (type === 'up-down') {
  217. elPc.classList.remove('layout-left-right');
  218. elPc.classList.add('layout-up-down');
  219. this.$refs.btnLeftRight.classList.remove('selected');
  220. this.$refs.btnUpDown.classList.add('selected');
  221. } else {
  222. elPc.classList.remove('layout-up-down');
  223. elPc.classList.add('layout-left-right');
  224. this.$refs.btnLeftRight.classList.add('selected');
  225. this.$refs.btnUpDown.classList.remove('selected');
  226. }
  227. localStorage.setItem(LOCAL_KEY_OF_LAYOUT, type);
  228. this.updateWrapperHeight();
  229. },
  230. setCache: function () {
  231. this.$nextTick(() => {
  232. localStorage.setItem(EDIT_ON_CLICK, this.overrideJson);
  233. });
  234. },
  235. lintOn: function () {
  236. this.$nextTick(() => {
  237. localStorage.setItem(JSON_LINT, this.jsonLintSwitch);
  238. });
  239. if (!editor.getValue().trim()) {
  240. return true;
  241. }
  242. this.$nextTick(() => {
  243. if (!this.jsonLintSwitch) {
  244. return;
  245. }
  246. let lintResult = JsonLint.lintDetect(editor.getValue());
  247. if (!isNaN(lintResult.line)) {
  248. this.placeHolder = '<div id="errorTips">' +
  249. '<div id="tipsBox">错误位置:' + (lintResult.line + 1) + '行,' + (lintResult.col + 1) + '列;缺少字符或字符不正确</div>' +
  250. '<div id="errorCode">' + lintResult.dom + '</div></div>';
  251. }
  252. });
  253. return false;
  254. },
  255. disableEditorChange: function (jsonTxt) {
  256. this.fireChange = false;
  257. this.$nextTick(() => {
  258. editor.setValue(jsonTxt);
  259. this.$nextTick(() => {
  260. this.fireChange = true;
  261. })
  262. })
  263. },
  264. openOptionsPage: function(){
  265. chrome.runtime.openOptionsPage();
  266. },
  267. openDonateModal: function(){
  268. chrome.runtime.sendMessage({
  269. type: 'fh-dynamic-any-thing',
  270. thing: 'open-donate-modal',
  271. params: { toolName: 'json-format' }
  272. });
  273. },
  274. setDemo: function () {
  275. 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":"阴晴之间,谨防紫外线侵扰"}]}}';
  276. editor.setValue(demo);
  277. this.$nextTick(() => {
  278. this.format();
  279. })
  280. }
  281. }
  282. });