vue-debug-helper

Vue components debug helper

当前为 2022-04-29 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name vue-debug-helper
  3. // @name:en vue-debug-helper
  4. // @name:zh Vue调试分析助手
  5. // @name:zh-TW Vue調試分析助手
  6. // @name:ja Vueデバッグ分析アシスタント
  7. // @namespace https://github.com/xxxily/vue-debug-helper
  8. // @homepage https://github.com/xxxily/vue-debug-helper
  9. // @version 0.0.6
  10. // @description Vue components debug helper
  11. // @description:en Vue components debug helper
  12. // @description:zh Vue组件探测、统计、分析辅助脚本
  13. // @description:zh-TW Vue組件探測、統計、分析輔助腳本
  14. // @description:ja Vueコンポーネントの検出、統計、分析補助スクリプト
  15. // @author ankvps
  16. // @icon https://cdn.jsdelivr.net/gh/xxxily/vue-debug-helper@main/logo.png
  17. // @match http://*/*
  18. // @match https://*/*
  19. // @grant unsafeWindow
  20. // @grant GM_addStyle
  21. // @grant GM_setValue
  22. // @grant GM_getValue
  23. // @grant GM_deleteValue
  24. // @grant GM_listValues
  25. // @grant GM_addValueChangeListener
  26. // @grant GM_removeValueChangeListener
  27. // @grant GM_registerMenuCommand
  28. // @grant GM_unregisterMenuCommand
  29. // @grant GM_getTab
  30. // @grant GM_saveTab
  31. // @grant GM_getTabs
  32. // @grant GM_openInTab
  33. // @grant GM_download
  34. // @grant GM_xmlhttpRequest
  35. // @run-at document-start
  36. // @connect 127.0.0.1
  37. // @license GPL
  38. // ==/UserScript==
  39. (function (w) { if (w) { w._vueDebugHelper_ = 'https://github.com/xxxily/vue-debug-helper'; } })();
  40.  
  41. class AssertionError extends Error {}
  42. AssertionError.prototype.name = 'AssertionError';
  43.  
  44. /**
  45. * Minimal assert function
  46. * @param {any} t Value to check if falsy
  47. * @param {string=} m Optional assertion error message
  48. * @throws {AssertionError}
  49. */
  50. function assert (t, m) {
  51. if (!t) {
  52. var err = new AssertionError(m);
  53. if (Error.captureStackTrace) Error.captureStackTrace(err, assert);
  54. throw err
  55. }
  56. }
  57.  
  58. /* eslint-env browser */
  59.  
  60. let ls;
  61. if (typeof window === 'undefined' || typeof window.localStorage === 'undefined') {
  62. // A simple localStorage interface so that lsp works in SSR contexts. Not for persistant storage in node.
  63. const _nodeStorage = {};
  64. ls = {
  65. getItem (name) {
  66. return _nodeStorage[name] || null
  67. },
  68. setItem (name, value) {
  69. if (arguments.length < 2) throw new Error('Failed to execute \'setItem\' on \'Storage\': 2 arguments required, but only 1 present.')
  70. _nodeStorage[name] = (value).toString();
  71. },
  72. removeItem (name) {
  73. delete _nodeStorage[name];
  74. }
  75. };
  76. } else {
  77. ls = window.localStorage;
  78. }
  79.  
  80. var localStorageProxy = (name, opts = {}) => {
  81. assert(name, 'namepace required');
  82. const {
  83. defaults = {},
  84. lspReset = false,
  85. storageEventListener = true
  86. } = opts;
  87.  
  88. const state = new EventTarget();
  89. try {
  90. const restoredState = JSON.parse(ls.getItem(name)) || {};
  91. if (restoredState.lspReset !== lspReset) {
  92. ls.removeItem(name);
  93. for (const [k, v] of Object.entries({
  94. ...defaults
  95. })) {
  96. state[k] = v;
  97. }
  98. } else {
  99. for (const [k, v] of Object.entries({
  100. ...defaults,
  101. ...restoredState
  102. })) {
  103. state[k] = v;
  104. }
  105. }
  106. } catch (e) {
  107. console.error(e);
  108. ls.removeItem(name);
  109. }
  110.  
  111. state.lspReset = lspReset;
  112.  
  113. if (storageEventListener && typeof window !== 'undefined' && typeof window.addEventListener !== 'undefined') {
  114. state.addEventListener('storage', (ev) => {
  115. // Replace state with whats stored on localStorage... it is newer.
  116. for (const k of Object.keys(state)) {
  117. delete state[k];
  118. }
  119. const restoredState = JSON.parse(ls.getItem(name)) || {};
  120. for (const [k, v] of Object.entries({
  121. ...defaults,
  122. ...restoredState
  123. })) {
  124. state[k] = v;
  125. }
  126. opts.lspReset = restoredState.lspReset;
  127. state.dispatchEvent(new Event('update'));
  128. });
  129. }
  130.  
  131. function boundHandler (rootRef) {
  132. return {
  133. get (obj, prop) {
  134. if (typeof obj[prop] === 'object' && obj[prop] !== null) {
  135. return new Proxy(obj[prop], boundHandler(rootRef))
  136. } else if (typeof obj[prop] === 'function' && obj === rootRef && prop !== 'constructor') {
  137. // this returns bound EventTarget functions
  138. return obj[prop].bind(obj)
  139. } else {
  140. return obj[prop]
  141. }
  142. },
  143. set (obj, prop, value) {
  144. obj[prop] = value;
  145. try {
  146. ls.setItem(name, JSON.stringify(rootRef));
  147. rootRef.dispatchEvent(new Event('update'));
  148. return true
  149. } catch (e) {
  150. console.error(e);
  151. return false
  152. }
  153. }
  154. }
  155. }
  156.  
  157. return new Proxy(state, boundHandler(state))
  158. };
  159.  
  160. /**
  161. * 对特定数据结构的对象进行排序
  162. * @param {object} obj 一个对象,其结构应该类似于:{key1: [], key2: []}
  163. * @param {boolean} reverse -可选 是否反转、降序排列,默认为false
  164. * @param {object} opts -可选 指定数组的配置项,默认为{key: 'key', value: 'value'}
  165. * @param {object} opts.key -可选 指定对象键名的别名,默认为'key'
  166. * @param {object} opts.value -可选 指定对象值的别名,默认为'value'
  167. * @returns {array} 返回一个数组,其结构应该类似于:[{key: key1, value: []}, {key: key2, value: []}]
  168. */
  169. const objSort = (obj, reverse, opts = { key: 'key', value: 'value' }) => {
  170. const arr = [];
  171. for (const key in obj) {
  172. if (Object.prototype.hasOwnProperty.call(obj, key) && Array.isArray(obj[key])) {
  173. const tmpObj = {};
  174. tmpObj[opts.key] = key;
  175. tmpObj[opts.value] = obj[key];
  176. arr.push(tmpObj);
  177. }
  178. }
  179.  
  180. arr.sort((a, b) => {
  181. return a[opts.value].length - b[opts.value].length
  182. });
  183.  
  184. reverse && arr.reverse();
  185. return arr
  186. };
  187.  
  188. /**
  189. * 根据指定长度创建空白数据
  190. * @param {number} size -可选 指str的重复次数,默认为1024次,如果str为单个单字节字符,则意味着默认产生1Mb的空白数据
  191. * @param {string|number|any} str - 可选 指定数据的字符串,默认为'd'
  192. */
  193. function createEmptyData (count = 1024, str = 'd') {
  194. const arr = [];
  195. arr.length = count + 1;
  196. return arr.join(str)
  197. }
  198.  
  199. /**
  200. * 将字符串分隔的过滤器转换为数组形式的过滤器
  201. * @param {string|array} filter - 必选 字符串或数组,字符串支持使用 , |符号对多个项进行分隔
  202. * @returns {array}
  203. */
  204. function toArrFilters (filter) {
  205. filter = filter || [];
  206.  
  207. /* 如果是字符串,则支持通过, | 两个符号来指定多个组件名称的过滤器 */
  208. if (typeof filter === 'string') {
  209. /* 移除前后的, |分隔符,防止出现空字符的过滤规则 */
  210. filter.replace(/^(,|\|)/, '').replace(/(,|\|)$/, '');
  211.  
  212. if (/\|/.test(filter)) {
  213. filter = filter.split('|');
  214. } else {
  215. filter = filter.split(',');
  216. }
  217. }
  218.  
  219. filter = filter.map(item => item.trim());
  220.  
  221. return filter
  222. }
  223.  
  224. window.vueDebugHelper = {
  225. /* 存储全部未被销毁的组件对象 */
  226. components: {},
  227. /* 存储全部创建过的组件的概要信息,即使销毁了概要信息依然存在 */
  228. componentsSummary: {},
  229. /* 基于componentsSummary的组件情况统计 */
  230. componentsSummaryStatistics: {},
  231. /* 已销毁的组件概要信息列表 */
  232. destroyList: [],
  233. /* 基于destroyList的组件情况统计 */
  234. destroyStatistics: {},
  235.  
  236. config: {
  237. /* 是否在控制台打印组件生命周期的相关信息 */
  238. lifecycle: {
  239. show: false,
  240. filters: ['created'],
  241. componentFilters: []
  242. },
  243.  
  244. /* 查找组件的过滤器配置 */
  245. findComponentsFilters: [],
  246.  
  247. /* 阻止组件创建的过滤器 */
  248. blockFilters: [],
  249.  
  250. /* 给组件注入空白数据的配置信息 */
  251. dd: {
  252. enabled: false,
  253. filters: [],
  254. count: 1024
  255. }
  256. }
  257. };
  258.  
  259. const helper = window.vueDebugHelper;
  260.  
  261. /* 配置信息跟localStorage联动 */
  262. const state = localStorageProxy('vueDebugHelperConfig', {
  263. defaults: helper.config,
  264. lspReset: false,
  265. storageEventListener: false
  266. });
  267. helper.config = state;
  268.  
  269. const methods = {
  270. objSort,
  271. createEmptyData,
  272. /* 清除全部helper的全部记录数据,以便重新统计 */
  273. clearAll () {
  274. helper.components = {};
  275. helper.componentsSummary = {};
  276. helper.componentsSummaryStatistics = {};
  277. helper.destroyList = [];
  278. helper.destroyStatistics = {};
  279. },
  280.  
  281. /**
  282. * 对当前的helper.components进行统计与排序
  283. * 如果一直没运行过清理函数,则表示统计页面创建至今依然存活的组件对象
  284. * 运行过清理函数,则表示统计清理后新创建且至今依然存活的组件对象
  285. */
  286. componentsStatistics (reverse = true) {
  287. const tmpObj = {};
  288.  
  289. Object.keys(helper.components).forEach(key => {
  290. const component = helper.components[key];
  291.  
  292. tmpObj[component._componentName]
  293. ? tmpObj[component._componentName].push(component)
  294. : (tmpObj[component._componentName] = [component]);
  295. });
  296.  
  297. return objSort(tmpObj, reverse, {
  298. key: 'componentName',
  299. value: 'componentInstance'
  300. })
  301. },
  302.  
  303. /**
  304. * 对componentsSummaryStatistics进行排序输出,以便可以直观查看组件的创建情况
  305. */
  306. componentsSummaryStatisticsSort (reverse = true) {
  307. return objSort(helper.componentsSummaryStatistics, reverse, {
  308. key: 'componentName',
  309. value: 'componentsSummary'
  310. })
  311. },
  312.  
  313. /**
  314. * 对destroyList进行排序输出,以便可以直观查看组件的销毁情况
  315. */
  316. destroyStatisticsSort (reverse = true) {
  317. return objSort(helper.destroyStatistics, reverse, {
  318. key: 'componentName',
  319. value: 'destroyList'
  320. })
  321. },
  322.  
  323. /**
  324. * 对destroyList进行排序输出,以便可以直观查看组件的销毁情况
  325. */
  326. getDestroyByDuration (duration = 1000) {
  327. const destroyList = helper.destroyList;
  328. const destroyListLength = destroyList.length;
  329. const destroyListDuration = destroyList.map(item => item.duration).sort();
  330. const maxDuration = Math.max(...destroyListDuration);
  331. const minDuration = Math.min(...destroyListDuration);
  332. const avgDuration =
  333. destroyListDuration.reduce((a, b) => a + b, 0) / destroyListLength;
  334. const durationRange = maxDuration - minDuration;
  335. const durationRangePercent = (duration - minDuration) / durationRange;
  336.  
  337. return {
  338. destroyList,
  339. destroyListLength,
  340. destroyListDuration,
  341. maxDuration,
  342. minDuration,
  343. avgDuration,
  344. durationRange,
  345. durationRangePercent
  346. }
  347. },
  348.  
  349. /**
  350. * 获取组件的调用链信息
  351. */
  352. getComponentChain (component, moreDetail = false) {
  353. const result = [];
  354. let current = component;
  355. let deep = 0;
  356.  
  357. while (current && deep < 50) {
  358. deep++;
  359.  
  360. /**
  361. * 由于脚本注入的运行时间会比应用创建时间晚,所以会导致部分先创建的组件缺少相关信息
  362. * 这里尝试对部分信息进行修复,以便更好的查看组件的创建情况
  363. */
  364. if (!current._componentTag) {
  365. const tag = current.$vnode?.tag || current.$options?._componentTag || current._uid;
  366. current._componentTag = tag;
  367. current._componentName = isNaN(Number(tag)) ? tag.replace(/^vue-component-\d+-/, '') : 'anonymous-component';
  368. }
  369.  
  370. if (moreDetail) {
  371. result.push({
  372. tag: current._componentTag,
  373. name: current._componentName,
  374. componentsSummary: helper.componentsSummary[current._uid] || null
  375. });
  376. } else {
  377. result.push(current._componentName);
  378. }
  379.  
  380. current = current.$parent;
  381. }
  382.  
  383. if (moreDetail) {
  384. return result
  385. } else {
  386. return result.join(' -> ')
  387. }
  388. },
  389.  
  390. printLifeCycleInfo (lifecycleFilters, componentFilters) {
  391. lifecycleFilters = toArrFilters(lifecycleFilters);
  392. componentFilters = toArrFilters(componentFilters);
  393.  
  394. helper.config.lifecycle = {
  395. show: true,
  396. filters: lifecycleFilters,
  397. componentFilters: componentFilters
  398. };
  399. },
  400. notPrintLifeCycleInfo () {
  401. helper.config.lifecycle = {
  402. show: false,
  403. filters: ['created'],
  404. componentFilters: []
  405. };
  406. },
  407.  
  408. /**
  409. * 查找组件
  410. * @param {string|array} filters 组件名称或组件uid的过滤器,可以是字符串或者数组,如果是字符串多个过滤选可用,或|分隔
  411. * 如果过滤项是数字,则跟组件的id进行精确匹配,如果是字符串,则跟组件的tag信息进行模糊匹配
  412. * @returns {object} {components: [], componentNames: []}
  413. */
  414. findComponents (filters) {
  415. filters = toArrFilters(filters);
  416.  
  417. /* 对filters进行预处理,如果为纯数字则表示通过id查找组件 */
  418. filters = filters.map(filter => {
  419. if (/^\d+$/.test(filter)) {
  420. return Number(filter)
  421. } else {
  422. return filter
  423. }
  424. });
  425.  
  426. helper.config.findComponentsFilters = filters;
  427.  
  428. const result = {
  429. components: [],
  430. destroyedComponents: []
  431. };
  432.  
  433. const components = helper.components;
  434. const keys = Object.keys(components);
  435.  
  436. for (let i = 0; i < keys.length; i++) {
  437. const component = components[keys[i]];
  438.  
  439. for (let j = 0; j < filters.length; j++) {
  440. const filter = filters[j];
  441.  
  442. if (typeof filter === 'number' && component._uid === filter) {
  443. result.components.push(component);
  444. break
  445. } else if (typeof filter === 'string') {
  446. const { _componentTag, _componentName } = component;
  447.  
  448. if (String(_componentTag).includes(filter) || String(_componentName).includes(filter)) {
  449. result.components.push(component);
  450. break
  451. }
  452. }
  453. }
  454. }
  455.  
  456. helper.destroyList.forEach(item => {
  457. for (let j = 0; j < filters.length; j++) {
  458. const filter = filters[j];
  459.  
  460. if (typeof filter === 'number' && item.uid === filter) {
  461. result.destroyedComponents.push(item);
  462. break
  463. } else if (typeof filter === 'string') {
  464. if (String(item.tag).includes(filter) || String(item.name).includes(filter)) {
  465. result.destroyedComponents.push(item);
  466. break
  467. }
  468. }
  469. }
  470. });
  471.  
  472. return result
  473. },
  474.  
  475. findNotContainElementComponents () {
  476. const result = [];
  477. const keys = Object.keys(helper.components);
  478. keys.forEach(key => {
  479. const component = helper.components[key];
  480. const elStr = Object.prototype.toString.call(component.$el);
  481. if (!/(HTML|Comment)/.test(elStr)) {
  482. result.push(component);
  483. }
  484. });
  485.  
  486. return result
  487. },
  488.  
  489. /**
  490. * 阻止组件的创建
  491. * @param {string|array} filters 组件名称过滤器,可以是字符串或者数组,如果是字符串多个过滤选可用,或|分隔
  492. */
  493. blockComponents (filters) {
  494. filters = toArrFilters(filters);
  495. helper.config.blockFilters = filters;
  496. },
  497.  
  498. /**
  499. * 给指定组件注入大量空数据,以便观察组件的内存泄露情况
  500. * @param {Array|string} filter -必选 指定组件的名称,如果为空则表示注入所有组件
  501. * @param {number} count -可选 指定注入空数据的大小,单位Kb,默认为1024Kb,即1Mb
  502. * @returns
  503. */
  504. dd (filter, count = 1024) {
  505. filter = toArrFilters(filter);
  506. helper.config.dd = {
  507. enabled: true,
  508. filters: filter,
  509. count
  510. };
  511. },
  512. /* 禁止给组件注入空数据 */
  513. undd () {
  514. helper.config.dd = {
  515. enabled: false,
  516. filters: [],
  517. count: 1024
  518. };
  519.  
  520. /* 删除之前注入的数据 */
  521. Object.keys(helper.components).forEach(key => {
  522. const component = helper.components[key];
  523. component.$data && delete component.$data.__dd__;
  524. });
  525. }
  526. };
  527.  
  528. helper.methods = methods;
  529.  
  530. class Debug {
  531. constructor (msg, printTime = false) {
  532. const t = this;
  533. msg = msg || 'debug message:';
  534. t.log = t.createDebugMethod('log', null, msg);
  535. t.error = t.createDebugMethod('error', null, msg);
  536. t.info = t.createDebugMethod('info', null, msg);
  537. t.warn = t.createDebugMethod('warn', null, msg);
  538. }
  539.  
  540. create (msg) {
  541. return new Debug(msg)
  542. }
  543.  
  544. createDebugMethod (name, color, tipsMsg) {
  545. name = name || 'info';
  546.  
  547. const bgColorMap = {
  548. info: '#2274A5',
  549. log: '#95B46A',
  550. error: '#D33F49'
  551. };
  552.  
  553. const printTime = this.printTime;
  554.  
  555. return function () {
  556. if (!window._debugMode_) {
  557. return false
  558. }
  559.  
  560. const msg = tipsMsg || 'debug message:';
  561.  
  562. const arg = Array.from(arguments);
  563. arg.unshift(`color: white; background-color: ${color || bgColorMap[name] || '#95B46A'}`);
  564.  
  565. if (printTime) {
  566. const curTime = new Date();
  567. const H = curTime.getHours();
  568. const M = curTime.getMinutes();
  569. const S = curTime.getSeconds();
  570. arg.unshift(`%c [${H}:${M}:${S}] ${msg} `);
  571. } else {
  572. arg.unshift(`%c ${msg} `);
  573. }
  574.  
  575. window.console[name].apply(window.console, arg);
  576. }
  577. }
  578.  
  579. isDebugMode () {
  580. return Boolean(window._debugMode_)
  581. }
  582. }
  583.  
  584. var Debug$1 = new Debug();
  585.  
  586. var debug = Debug$1.create('vueDebugHelper:');
  587.  
  588. /**
  589. * 打印生命周期信息
  590. * @param {Vue} vm vue组件实例
  591. * @param {string} lifeCycle vue生命周期名称
  592. * @returns
  593. */
  594. function printLifeCycle (vm, lifeCycle) {
  595. const lifeCycleConf = helper.config.lifecycle || { show: false, filters: ['created'], componentFilters: [] };
  596.  
  597. if (!vm || !lifeCycle || !lifeCycleConf.show) {
  598. return false
  599. }
  600.  
  601. const { _componentTag, _componentName, _componentChain, _createdHumanTime, _uid } = vm;
  602. const info = `[${lifeCycle}] tag: ${_componentTag}, uid: ${_uid}, createdTime: ${_createdHumanTime}, chain: ${_componentChain}`;
  603. const matchComponentFilters = lifeCycleConf.componentFilters.length === 0 || lifeCycleConf.componentFilters.includes(_componentName);
  604.  
  605. if (lifeCycleConf.filters.includes(lifeCycle) && matchComponentFilters) {
  606. debug.log(info);
  607. }
  608. }
  609.  
  610. function mixinRegister (Vue) {
  611. if (!Vue || !Vue.mixin) {
  612. debug.error('未检查到VUE对象,请检查是否引入了VUE,且将VUE对象挂载到全局变量window.Vue上');
  613. return false
  614. }
  615.  
  616. Vue.mixin({
  617. beforeCreate: function () {
  618. // const tag = this.$options?._componentTag || this.$vnode?.tag || this._uid
  619. const tag = this.$vnode?.tag || this.$options?._componentTag || this._uid;
  620. const chain = helper.methods.getComponentChain(this);
  621. this._componentTag = tag;
  622. this._componentChain = chain;
  623. this._componentName = isNaN(Number(tag)) ? tag.replace(/^vue-component-\d+-/, '') : 'anonymous-component';
  624. this._createdTime = Date.now();
  625.  
  626. /* 增加人类方便查看的时间信息 */
  627. const timeObj = new Date(this._createdTime);
  628. this._createdHumanTime = `${timeObj.getHours()}:${timeObj.getMinutes()}:${timeObj.getSeconds()}`;
  629.  
  630. /* 判断是否为函数式组件,函数式组件无状态 (没有响应式数据),也没有实例,也没生命周期概念 */
  631. if (this._componentName === 'anonymous-component' && !this.$parent && !this.$vnode) {
  632. this._componentName = 'functional-component';
  633. }
  634.  
  635. helper.components[this._uid] = this;
  636.  
  637. /**
  638. * 收集所有创建过的组件信息,此处只存储组件的基础信息,没销毁的组件会包含组件实例
  639. * 严禁对组件内其它对象进行引用,否则会导致组件实列无法被正常回收
  640. */
  641. const componentSummary = {
  642. uid: this._uid,
  643. name: this._componentName,
  644. tag: this._componentTag,
  645. createdTime: this._createdTime,
  646. createdHumanTime: this._createdHumanTime,
  647. // 0 表示还没被销毁
  648. destroyTime: 0,
  649. // 0 表示还没被销毁,duration可持续当当前查看时间
  650. duration: 0,
  651. component: this,
  652. chain
  653. };
  654. helper.componentsSummary[this._uid] = componentSummary;
  655.  
  656. /* 添加到componentsSummaryStatistics里,生成统计信息 */
  657. Array.isArray(helper.componentsSummaryStatistics[this._componentName])
  658. ? helper.componentsSummaryStatistics[this._componentName].push(componentSummary)
  659. : (helper.componentsSummaryStatistics[this._componentName] = [componentSummary]);
  660.  
  661. printLifeCycle(this, 'beforeCreate');
  662.  
  663. /* 使用$destroy阻断组件的创建 */
  664. if (helper.config.blockFilters && helper.config.blockFilters.length) {
  665. if (helper.config.blockFilters.includes(this._componentName)) {
  666. debug.log(`[block component]: name: ${this._componentName}, tag: ${this._componentTag}, uid: ${this._uid}`);
  667. this.$destroy();
  668. return false
  669. }
  670. }
  671. },
  672. created: function () {
  673. /* 增加空白数据,方便观察内存泄露情况 */
  674. if (helper.config.dd.enabled) {
  675. let needDd = false;
  676.  
  677. if (helper.config.dd.filters.length === 0) {
  678. needDd = true;
  679. } else {
  680. for (let index = 0; index < helper.config.dd.filters.length; index++) {
  681. const filter = helper.config.dd.filters[index];
  682. if (filter === this._componentName || String(this._componentName).endsWith(filter)) {
  683. needDd = true;
  684. break
  685. }
  686. }
  687. }
  688.  
  689. if (needDd) {
  690. const count = helper.config.dd.count * 1024;
  691. const componentInfo = `tag: ${this._componentTag}, uid: ${this._uid}, createdTime: ${this._createdHumanTime}`;
  692.  
  693. /* 此处必须使用JSON.stringify对产生的字符串进行消费,否则没法将内存占用上去 */
  694. this.$data.__dd__ = JSON.stringify(componentInfo + ' ' + helper.methods.createEmptyData(count, this._uid));
  695.  
  696. console.log(`[dd success] ${componentInfo} chain: ${this._componentChain}`);
  697. }
  698. }
  699.  
  700. printLifeCycle(this, 'created');
  701. },
  702. beforeMount: function () {
  703. printLifeCycle(this, 'beforeMount');
  704. },
  705. mounted: function () {
  706. printLifeCycle(this, 'mounted');
  707. },
  708. beforeUpdate: function () {
  709. printLifeCycle(this, 'beforeUpdate');
  710. },
  711. activated: function () {
  712. printLifeCycle(this, 'activated');
  713. },
  714. deactivated: function () {
  715. printLifeCycle(this, 'deactivated');
  716. },
  717. updated: function () {
  718. printLifeCycle(this, 'updated');
  719. },
  720. beforeDestroy: function () {
  721. printLifeCycle(this, 'beforeDestroy');
  722. },
  723. destroyed: function () {
  724. printLifeCycle(this, 'destroyed');
  725.  
  726. if (this._componentTag) {
  727. const uid = this._uid;
  728. const name = this._componentName;
  729. const destroyTime = Date.now();
  730.  
  731. /* helper里的componentSummary有可能通过调用clear函数而被清除掉,所以需进行判断再更新赋值 */
  732. const componentSummary = helper.componentsSummary[this._uid];
  733. if (componentSummary) {
  734. /* 补充/更新组件信息 */
  735. componentSummary.destroyTime = destroyTime;
  736. componentSummary.duration = destroyTime - this._createdTime;
  737.  
  738. helper.destroyList.push(componentSummary);
  739.  
  740. /* 统计被销毁的组件信息 */
  741. Array.isArray(helper.destroyStatistics[name])
  742. ? helper.destroyStatistics[name].push(componentSummary)
  743. : (helper.destroyStatistics[name] = [componentSummary]);
  744.  
  745. /* 删除已销毁的组件实例 */
  746. delete componentSummary.component;
  747. }
  748.  
  749. // 解除引用关系
  750. delete this._componentTag;
  751. delete this._componentChain;
  752. delete this._componentName;
  753. delete this._createdTime;
  754. delete this._createdHumanTime;
  755. delete this.$data.__dd__;
  756. delete helper.components[uid];
  757. } else {
  758. console.error('存在未被正常标记的组件,请检查组件采集逻辑是否需完善', this);
  759. }
  760. }
  761. });
  762. }
  763.  
  764. /*!
  765. * @name menuCommand.js
  766. * @version 0.0.1
  767. * @author Blaze
  768. * @date 2019/9/21 14:22
  769. */
  770.  
  771. const monkeyMenu = {
  772. on (title, fn, accessKey) {
  773. return window.GM_registerMenuCommand && window.GM_registerMenuCommand(title, fn, accessKey)
  774. },
  775. off (id) {
  776. return window.GM_unregisterMenuCommand && window.GM_unregisterMenuCommand(id)
  777. },
  778. /* 切换类型的菜单功能 */
  779. switch (title, fn, defVal) {
  780. const t = this;
  781. t.on(title, fn);
  782. }
  783. };
  784.  
  785. /**
  786. * 简单的i18n库
  787. */
  788.  
  789. class I18n {
  790. constructor (config) {
  791. this._languages = {};
  792. this._locale = this.getClientLang();
  793. this._defaultLanguage = '';
  794. this.init(config);
  795. }
  796.  
  797. init (config) {
  798. if (!config) return false
  799.  
  800. const t = this;
  801. t._locale = config.locale || t._locale;
  802. /* 指定当前要是使用的语言环境,默认无需指定,会自动读取 */
  803. t._languages = config.languages || t._languages;
  804. t._defaultLanguage = config.defaultLanguage || t._defaultLanguage;
  805. }
  806.  
  807. use () {}
  808.  
  809. t (path) {
  810. const t = this;
  811. let result = t.getValByPath(t._languages[t._locale] || {}, path);
  812.  
  813. /* 版本回退 */
  814. if (!result && t._locale !== t._defaultLanguage) {
  815. result = t.getValByPath(t._languages[t._defaultLanguage] || {}, path);
  816. }
  817.  
  818. return result || ''
  819. }
  820.  
  821. /* 当前语言值 */
  822. language () {
  823. return this._locale
  824. }
  825.  
  826. languages () {
  827. return this._languages
  828. }
  829.  
  830. changeLanguage (locale) {
  831. if (this._languages[locale]) {
  832. this._languages = locale;
  833. return locale
  834. } else {
  835. return false
  836. }
  837. }
  838.  
  839. /**
  840. * 根据文本路径获取对象里面的值
  841. * @param obj {Object} -必选 要操作的对象
  842. * @param path {String} -必选 路径信息
  843. * @returns {*}
  844. */
  845. getValByPath (obj, path) {
  846. path = path || '';
  847. const pathArr = path.split('.');
  848. let result = obj;
  849.  
  850. /* 递归提取结果值 */
  851. for (let i = 0; i < pathArr.length; i++) {
  852. if (!result) break
  853. result = result[pathArr[i]];
  854. }
  855.  
  856. return result
  857. }
  858.  
  859. /* 获取客户端当前的语言环境 */
  860. getClientLang () {
  861. return navigator.languages ? navigator.languages[0] : navigator.language
  862. }
  863. }
  864.  
  865. var zhCN = {
  866. about: '关于',
  867. issues: '反馈',
  868. setting: '设置',
  869. hotkeys: '快捷键',
  870. donate: '赞赏',
  871. debugHelper: {
  872. viewVueDebugHelperObject: 'vueDebugHelper对象',
  873. componentsStatistics: '当前存活组件统计',
  874. destroyStatisticsSort: '已销毁组件统计',
  875. componentsSummaryStatisticsSort: '全部组件混合统计',
  876. getDestroyByDuration: '组件存活时间信息',
  877. clearAll: '清空统计信息',
  878. printLifeCycleInfo: '打印组件生命周期信息',
  879. notPrintLifeCycleInfo: '取消组件生命周期信息打印',
  880. printLifeCycleInfoPrompt: {
  881. lifecycleFilters: '输入要打印的生命周期名称,多个可用,或|分隔,不输入则默认打印created',
  882. componentFilters: '输入要打印的组件名称,多个可用,或|分隔,不输入则默认打印所有组件'
  883. },
  884. findComponents: '查找组件',
  885. findComponentsPrompt: {
  886. filters: '输入要查找的组件名称,或uid,多个可用,或|分隔'
  887. },
  888. findNotContainElementComponents: '查找不包含DOM对象的组件',
  889. blockComponents: '阻断组件的创建',
  890. blockComponentsPrompt: {
  891. filters: '输入要阻断的组件名称,多个可用,或|分隔,输入为空则取消阻断'
  892. },
  893. dd: '数据注入(dd)',
  894. undd: '取消数据注入(undd)',
  895. ddPrompt: {
  896. filter: '组件过滤器(如果为空,则对所有组件注入)',
  897. count: '指定注入数据的重复次数(默认1024)'
  898. }
  899. }
  900. };
  901.  
  902. var enUS = {
  903. about: 'about',
  904. issues: 'feedback',
  905. setting: 'settings',
  906. hotkeys: 'Shortcut keys',
  907. donate: 'donate',
  908. debugHelper: {
  909. viewVueDebugHelperObject: 'vueDebugHelper object',
  910. componentsStatistics: 'Current surviving component statistics',
  911. destroyStatisticsSort: 'Destroyed component statistics',
  912. componentsSummaryStatisticsSort: 'All components mixed statistics',
  913. getDestroyByDuration: 'Component survival time information',
  914. clearAll: 'Clear statistics',
  915. dd: 'Data injection (dd)',
  916. undd: 'Cancel data injection (undd)',
  917. ddPrompt: {
  918. filter: 'Component filter (if empty, inject all components)',
  919. count: 'Specify the number of repetitions of injected data (default 1024)'
  920. }
  921. }
  922. };
  923.  
  924. var zhTW = {
  925. about: '關於',
  926. issues: '反饋',
  927. setting: '設置',
  928. hotkeys: '快捷鍵',
  929. donate: '讚賞',
  930. debugHelper: {
  931. viewVueDebugHelperObject: 'vueDebugHelper對象',
  932. componentsStatistics: '當前存活組件統計',
  933. destroyStatisticsSort: '已銷毀組件統計',
  934. componentsSummaryStatisticsSort: '全部組件混合統計',
  935. getDestroyByDuration: '組件存活時間信息',
  936. clearAll: '清空統計信息',
  937. dd: '數據注入(dd)',
  938. undd: '取消數據注入(undd)',
  939. ddPrompt: {
  940. filter: '組件過濾器(如果為空,則對所有組件注入)',
  941. count: '指定注入數據的重複次數(默認1024)'
  942. }
  943. }
  944. };
  945.  
  946. const messages = {
  947. 'zh-CN': zhCN,
  948. zh: zhCN,
  949. 'zh-HK': zhTW,
  950. 'zh-TW': zhTW,
  951. 'en-US': enUS,
  952. en: enUS,
  953. };
  954.  
  955. /*!
  956. * @name i18n.js
  957. * @description vue-debug-helper的国际化配置
  958. * @version 0.0.1
  959. * @author xxxily
  960. * @date 2022/04/26 14:56
  961. * @github https://github.com/xxxily
  962. */
  963.  
  964. const i18n = new I18n({
  965. defaultLanguage: 'en',
  966. /* 指定当前要是使用的语言环境,默认无需指定,会自动读取 */
  967. // locale: 'zh-TW',
  968. languages: messages
  969. });
  970.  
  971. /*!
  972. * @name functionCall.js
  973. * @description 统一的提供外部功能调用管理模块
  974. * @version 0.0.1
  975. * @author xxxily
  976. * @date 2022/04/27 17:42
  977. * @github https://github.com/xxxily
  978. */
  979.  
  980. const functionCall = {
  981. viewVueDebugHelperObject () {
  982. debug.log(i18n.t('debugHelper.viewVueDebugHelperObject'), helper);
  983. },
  984. componentsStatistics () {
  985. const result = helper.methods.componentsStatistics();
  986. let total = 0;
  987.  
  988. /* 提供友好的可视化展示方式 */
  989. console.table && console.table(result.map(item => {
  990. total += item.componentInstance.length;
  991. return {
  992. componentName: item.componentName,
  993. count: item.componentInstance.length
  994. }
  995. }));
  996.  
  997. debug.log(`${i18n.t('debugHelper.componentsStatistics')} (total:${total})`, result);
  998. },
  999. destroyStatisticsSort () {
  1000. const result = helper.methods.destroyStatisticsSort();
  1001.  
  1002. /* 提供友好的可视化展示方式 */
  1003. console.table && console.table(result.map(item => {
  1004. const durationList = item.destroyList.map(item => item.duration);
  1005. const maxDuration = Math.max(...durationList);
  1006. const minDuration = Math.min(...durationList);
  1007. const durationRange = maxDuration - minDuration;
  1008.  
  1009. return {
  1010. componentName: item.componentName,
  1011. count: item.destroyList.length,
  1012. avgDuration: durationList.reduce((pre, cur) => pre + cur, 0) / durationList.length,
  1013. maxDuration,
  1014. minDuration,
  1015. durationRange,
  1016. durationRangePercent: (1000 - minDuration) / durationRange
  1017. }
  1018. }));
  1019.  
  1020. debug.log(i18n.t('debugHelper.destroyStatisticsSort'), result);
  1021. },
  1022. componentsSummaryStatisticsSort () {
  1023. const result = helper.methods.componentsSummaryStatisticsSort();
  1024. let total = 0;
  1025.  
  1026. /* 提供友好的可视化展示方式 */
  1027. console.table && console.table(result.map(item => {
  1028. total += item.componentsSummary.length;
  1029. return {
  1030. componentName: item.componentName,
  1031. count: item.componentsSummary.length
  1032. }
  1033. }));
  1034.  
  1035. debug.log(`${i18n.t('debugHelper.componentsSummaryStatisticsSort')} (total:${total})`, result);
  1036. },
  1037. getDestroyByDuration () {
  1038. const destroyInfo = helper.methods.getDestroyByDuration();
  1039. console.table && console.table(destroyInfo.destroyList);
  1040. debug.log(i18n.t('debugHelper.getDestroyByDuration'), destroyInfo);
  1041. },
  1042. clearAll () {
  1043. helper.methods.clearAll();
  1044. debug.log(i18n.t('debugHelper.clearAll'));
  1045. },
  1046.  
  1047. printLifeCycleInfo () {
  1048. const lifecycleFilters = window.prompt(i18n.t('debugHelper.printLifeCycleInfoPrompt.lifecycleFilters'), helper.config.lifecycle.filters.join(','));
  1049. const componentFilters = window.prompt(i18n.t('debugHelper.printLifeCycleInfoPrompt.componentFilters'), helper.config.lifecycle.componentFilters.join(','));
  1050.  
  1051. if (lifecycleFilters !== null && componentFilters !== null) {
  1052. debug.log(i18n.t('debugHelper.printLifeCycleInfo'));
  1053. helper.methods.printLifeCycleInfo(lifecycleFilters, componentFilters);
  1054. }
  1055. },
  1056.  
  1057. notPrintLifeCycleInfo () {
  1058. debug.log(i18n.t('debugHelper.notPrintLifeCycleInfo'));
  1059. helper.methods.notPrintLifeCycleInfo();
  1060. },
  1061.  
  1062. findComponents () {
  1063. const filters = window.prompt(i18n.t('debugHelper.findComponentsPrompt.filters'), helper.config.findComponentsFilters.join(','));
  1064. if (filters !== null) {
  1065. debug.log(i18n.t('debugHelper.findComponents'), helper.methods.findComponents(filters));
  1066. }
  1067. },
  1068.  
  1069. findNotContainElementComponents () {
  1070. debug.log(i18n.t('debugHelper.findNotContainElementComponents'), helper.methods.findNotContainElementComponents());
  1071. },
  1072.  
  1073. blockComponents () {
  1074. const filters = window.prompt(i18n.t('debugHelper.blockComponentsPrompt.filters'), helper.config.blockFilters.join(','));
  1075. if (filters !== null) {
  1076. helper.methods.blockComponents(filters);
  1077. debug.log(i18n.t('debugHelper.blockComponents'), filters);
  1078. }
  1079. },
  1080.  
  1081. dd () {
  1082. const filter = window.prompt(i18n.t('debugHelper.ddPrompt.filter'), helper.config.dd.filters.join(','));
  1083. const count = window.prompt(i18n.t('debugHelper.ddPrompt.count'), helper.config.dd.count);
  1084.  
  1085. if (filter !== null && count !== null) {
  1086. debug.log(i18n.t('debugHelper.dd'));
  1087. helper.methods.dd(filter, Number(count));
  1088. }
  1089. },
  1090. undd () {
  1091. debug.log(i18n.t('debugHelper.undd'));
  1092. helper.methods.undd();
  1093. }
  1094. };
  1095.  
  1096. /*!
  1097. * @name menu.js
  1098. * @description vue-debug-helper的菜单配置
  1099. * @version 0.0.1
  1100. * @author xxxily
  1101. * @date 2022/04/25 22:28
  1102. * @github https://github.com/xxxily
  1103. */
  1104.  
  1105. function menuRegister (Vue) {
  1106. if (!Vue) {
  1107. monkeyMenu.on('not detected ' + i18n.t('issues'), () => {
  1108. window.GM_openInTab('https://github.com/xxxily/vue-debug-helper/issues', {
  1109. active: true,
  1110. insert: true,
  1111. setParent: true
  1112. });
  1113. });
  1114. return false
  1115. }
  1116.  
  1117. // 批量注册菜单
  1118. Object.keys(functionCall).forEach(key => {
  1119. const text = i18n.t(`debugHelper.${key}`);
  1120. if (text && functionCall[key] instanceof Function) {
  1121. monkeyMenu.on(text, functionCall[key]);
  1122. }
  1123. });
  1124.  
  1125. // monkeyMenu.on('i18n.t('setting')', () => {
  1126. // window.alert('功能开发中,敬请期待...')
  1127. // })
  1128.  
  1129. monkeyMenu.on(i18n.t('issues'), () => {
  1130. window.GM_openInTab('https://github.com/xxxily/vue-debug-helper/issues', {
  1131. active: true,
  1132. insert: true,
  1133. setParent: true
  1134. });
  1135. });
  1136.  
  1137. // monkeyMenu.on(i18n.t('donate'), () => {
  1138. // window.GM_openInTab('https://cdn.jsdelivr.net/gh/xxxily/vue-debug-helper@main/donate.png', {
  1139. // active: true,
  1140. // insert: true,
  1141. // setParent: true
  1142. // })
  1143. // })
  1144. }
  1145.  
  1146. const isff = typeof navigator !== 'undefined' ? navigator.userAgent.toLowerCase().indexOf('firefox') > 0 : false;
  1147.  
  1148. // 绑定事件
  1149. function addEvent (object, event, method) {
  1150. if (object.addEventListener) {
  1151. object.addEventListener(event, method, false);
  1152. } else if (object.attachEvent) {
  1153. object.attachEvent(`on${event}`, () => { method(window.event); });
  1154. }
  1155. }
  1156.  
  1157. // 修饰键转换成对应的键码
  1158. function getMods (modifier, key) {
  1159. const mods = key.slice(0, key.length - 1);
  1160. for (let i = 0; i < mods.length; i++) mods[i] = modifier[mods[i].toLowerCase()];
  1161. return mods
  1162. }
  1163.  
  1164. // 处理传的key字符串转换成数组
  1165. function getKeys (key) {
  1166. if (typeof key !== 'string') key = '';
  1167. key = key.replace(/\s/g, ''); // 匹配任何空白字符,包括空格、制表符、换页符等等
  1168. const keys = key.split(','); // 同时设置多个快捷键,以','分割
  1169. let index = keys.lastIndexOf('');
  1170.  
  1171. // 快捷键可能包含',',需特殊处理
  1172. for (; index >= 0;) {
  1173. keys[index - 1] += ',';
  1174. keys.splice(index, 1);
  1175. index = keys.lastIndexOf('');
  1176. }
  1177.  
  1178. return keys
  1179. }
  1180.  
  1181. // 比较修饰键的数组
  1182. function compareArray (a1, a2) {
  1183. const arr1 = a1.length >= a2.length ? a1 : a2;
  1184. const arr2 = a1.length >= a2.length ? a2 : a1;
  1185. let isIndex = true;
  1186.  
  1187. for (let i = 0; i < arr1.length; i++) {
  1188. if (arr2.indexOf(arr1[i]) === -1) isIndex = false;
  1189. }
  1190. return isIndex
  1191. }
  1192.  
  1193. // Special Keys
  1194. const _keyMap = {
  1195. backspace: 8,
  1196. tab: 9,
  1197. clear: 12,
  1198. enter: 13,
  1199. return: 13,
  1200. esc: 27,
  1201. escape: 27,
  1202. space: 32,
  1203. left: 37,
  1204. up: 38,
  1205. right: 39,
  1206. down: 40,
  1207. del: 46,
  1208. delete: 46,
  1209. ins: 45,
  1210. insert: 45,
  1211. home: 36,
  1212. end: 35,
  1213. pageup: 33,
  1214. pagedown: 34,
  1215. capslock: 20,
  1216. num_0: 96,
  1217. num_1: 97,
  1218. num_2: 98,
  1219. num_3: 99,
  1220. num_4: 100,
  1221. num_5: 101,
  1222. num_6: 102,
  1223. num_7: 103,
  1224. num_8: 104,
  1225. num_9: 105,
  1226. num_multiply: 106,
  1227. num_add: 107,
  1228. num_enter: 108,
  1229. num_subtract: 109,
  1230. num_decimal: 110,
  1231. num_divide: 111,
  1232. '⇪': 20,
  1233. ',': 188,
  1234. '.': 190,
  1235. '/': 191,
  1236. '`': 192,
  1237. '-': isff ? 173 : 189,
  1238. '=': isff ? 61 : 187,
  1239. ';': isff ? 59 : 186,
  1240. '\'': 222,
  1241. '[': 219,
  1242. ']': 221,
  1243. '\\': 220
  1244. };
  1245.  
  1246. // Modifier Keys
  1247. const _modifier = {
  1248. // shiftKey
  1249. '⇧': 16,
  1250. shift: 16,
  1251. // altKey
  1252. '⌥': 18,
  1253. alt: 18,
  1254. option: 18,
  1255. // ctrlKey
  1256. '⌃': 17,
  1257. ctrl: 17,
  1258. control: 17,
  1259. // metaKey
  1260. '⌘': 91,
  1261. cmd: 91,
  1262. command: 91
  1263. };
  1264. const modifierMap = {
  1265. 16: 'shiftKey',
  1266. 18: 'altKey',
  1267. 17: 'ctrlKey',
  1268. 91: 'metaKey',
  1269.  
  1270. shiftKey: 16,
  1271. ctrlKey: 17,
  1272. altKey: 18,
  1273. metaKey: 91
  1274. };
  1275. const _mods = {
  1276. 16: false,
  1277. 18: false,
  1278. 17: false,
  1279. 91: false
  1280. };
  1281. const _handlers = {};
  1282.  
  1283. // F1~F12 special key
  1284. for (let k = 1; k < 20; k++) {
  1285. _keyMap[`f${k}`] = 111 + k;
  1286. }
  1287.  
  1288. // https://github.com/jaywcjlove/hotkeys
  1289.  
  1290. let _downKeys = []; // 记录摁下的绑定键
  1291. let winListendFocus = false; // window是否已经监听了focus事件
  1292. let _scope = 'all'; // 默认热键范围
  1293. const elementHasBindEvent = []; // 已绑定事件的节点记录
  1294.  
  1295. // 返回键码
  1296. const code = (x) => _keyMap[x.toLowerCase()] ||
  1297. _modifier[x.toLowerCase()] ||
  1298. x.toUpperCase().charCodeAt(0);
  1299.  
  1300. // 设置获取当前范围(默认为'所有')
  1301. function setScope (scope) {
  1302. _scope = scope || 'all';
  1303. }
  1304. // 获取当前范围
  1305. function getScope () {
  1306. return _scope || 'all'
  1307. }
  1308. // 获取摁下绑定键的键值
  1309. function getPressedKeyCodes () {
  1310. return _downKeys.slice(0)
  1311. }
  1312.  
  1313. // 表单控件控件判断 返回 Boolean
  1314. // hotkey is effective only when filter return true
  1315. function filter (event) {
  1316. const target = event.target || event.srcElement;
  1317. const { tagName } = target;
  1318. let flag = true;
  1319. // ignore: isContentEditable === 'true', <input> and <textarea> when readOnly state is false, <select>
  1320. if (
  1321. target.isContentEditable ||
  1322. ((tagName === 'INPUT' || tagName === 'TEXTAREA' || tagName === 'SELECT') && !target.readOnly)
  1323. ) {
  1324. flag = false;
  1325. }
  1326. return flag
  1327. }
  1328.  
  1329. // 判断摁下的键是否为某个键,返回true或者false
  1330. function isPressed (keyCode) {
  1331. if (typeof keyCode === 'string') {
  1332. keyCode = code(keyCode); // 转换成键码
  1333. }
  1334. return _downKeys.indexOf(keyCode) !== -1
  1335. }
  1336.  
  1337. // 循环删除handlers中的所有 scope(范围)
  1338. function deleteScope (scope, newScope) {
  1339. let handlers;
  1340. let i;
  1341.  
  1342. // 没有指定scope,获取scope
  1343. if (!scope) scope = getScope();
  1344.  
  1345. for (const key in _handlers) {
  1346. if (Object.prototype.hasOwnProperty.call(_handlers, key)) {
  1347. handlers = _handlers[key];
  1348. for (i = 0; i < handlers.length;) {
  1349. if (handlers[i].scope === scope) handlers.splice(i, 1);
  1350. else i++;
  1351. }
  1352. }
  1353. }
  1354.  
  1355. // 如果scope被删除,将scope重置为all
  1356. if (getScope() === scope) setScope(newScope || 'all');
  1357. }
  1358.  
  1359. // 清除修饰键
  1360. function clearModifier (event) {
  1361. let key = event.keyCode || event.which || event.charCode;
  1362. const i = _downKeys.indexOf(key);
  1363.  
  1364. // 从列表中清除按压过的键
  1365. if (i >= 0) {
  1366. _downKeys.splice(i, 1);
  1367. }
  1368. // 特殊处理 cmmand 键,在 cmmand 组合快捷键 keyup 只执行一次的问题
  1369. if (event.key && event.key.toLowerCase() === 'meta') {
  1370. _downKeys.splice(0, _downKeys.length);
  1371. }
  1372.  
  1373. // 修饰键 shiftKey altKey ctrlKey (command||metaKey) 清除
  1374. if (key === 93 || key === 224) key = 91;
  1375. if (key in _mods) {
  1376. _mods[key] = false;
  1377.  
  1378. // 将修饰键重置为false
  1379. for (const k in _modifier) if (_modifier[k] === key) hotkeys[k] = false;
  1380. }
  1381. }
  1382.  
  1383. function unbind (keysInfo, ...args) {
  1384. // unbind(), unbind all keys
  1385. if (!keysInfo) {
  1386. Object.keys(_handlers).forEach((key) => delete _handlers[key]);
  1387. } else if (Array.isArray(keysInfo)) {
  1388. // support like : unbind([{key: 'ctrl+a', scope: 's1'}, {key: 'ctrl-a', scope: 's2', splitKey: '-'}])
  1389. keysInfo.forEach((info) => {
  1390. if (info.key) eachUnbind(info);
  1391. });
  1392. } else if (typeof keysInfo === 'object') {
  1393. // support like unbind({key: 'ctrl+a, ctrl+b', scope:'abc'})
  1394. if (keysInfo.key) eachUnbind(keysInfo);
  1395. } else if (typeof keysInfo === 'string') {
  1396. // support old method
  1397. // eslint-disable-line
  1398. let [scope, method] = args;
  1399. if (typeof scope === 'function') {
  1400. method = scope;
  1401. scope = '';
  1402. }
  1403. eachUnbind({
  1404. key: keysInfo,
  1405. scope,
  1406. method,
  1407. splitKey: '+'
  1408. });
  1409. }
  1410. }
  1411.  
  1412. // 解除绑定某个范围的快捷键
  1413. const eachUnbind = ({
  1414. key, scope, method, splitKey = '+'
  1415. }) => {
  1416. const multipleKeys = getKeys(key);
  1417. multipleKeys.forEach((originKey) => {
  1418. const unbindKeys = originKey.split(splitKey);
  1419. const len = unbindKeys.length;
  1420. const lastKey = unbindKeys[len - 1];
  1421. const keyCode = lastKey === '*' ? '*' : code(lastKey);
  1422. if (!_handlers[keyCode]) return
  1423. // 判断是否传入范围,没有就获取范围
  1424. if (!scope) scope = getScope();
  1425. const mods = len > 1 ? getMods(_modifier, unbindKeys) : [];
  1426. _handlers[keyCode] = _handlers[keyCode].filter((record) => {
  1427. // 通过函数判断,是否解除绑定,函数相等直接返回
  1428. const isMatchingMethod = method ? record.method === method : true;
  1429. return !(
  1430. isMatchingMethod &&
  1431. record.scope === scope &&
  1432. compareArray(record.mods, mods)
  1433. )
  1434. });
  1435. });
  1436. };
  1437.  
  1438. // 对监听对应快捷键的回调函数进行处理
  1439. function eventHandler (event, handler, scope, element) {
  1440. if (handler.element !== element) {
  1441. return
  1442. }
  1443. let modifiersMatch;
  1444.  
  1445. // 看它是否在当前范围
  1446. if (handler.scope === scope || handler.scope === 'all') {
  1447. // 检查是否匹配修饰符(如果有返回true)
  1448. modifiersMatch = handler.mods.length > 0;
  1449.  
  1450. for (const y in _mods) {
  1451. if (Object.prototype.hasOwnProperty.call(_mods, y)) {
  1452. if (
  1453. (!_mods[y] && handler.mods.indexOf(+y) > -1) ||
  1454. (_mods[y] && handler.mods.indexOf(+y) === -1)
  1455. ) {
  1456. modifiersMatch = false;
  1457. }
  1458. }
  1459. }
  1460.  
  1461. // 调用处理程序,如果是修饰键不做处理
  1462. if (
  1463. (handler.mods.length === 0 &&
  1464. !_mods[16] &&
  1465. !_mods[18] &&
  1466. !_mods[17] &&
  1467. !_mods[91]) ||
  1468. modifiersMatch ||
  1469. handler.shortcut === '*'
  1470. ) {
  1471. if (handler.method(event, handler) === false) {
  1472. if (event.preventDefault) event.preventDefault();
  1473. else event.returnValue = false;
  1474. if (event.stopPropagation) event.stopPropagation();
  1475. if (event.cancelBubble) event.cancelBubble = true;
  1476. }
  1477. }
  1478. }
  1479. }
  1480.  
  1481. // 处理keydown事件
  1482. function dispatch (event, element) {
  1483. const asterisk = _handlers['*'];
  1484. let key = event.keyCode || event.which || event.charCode;
  1485.  
  1486. // 表单控件过滤 默认表单控件不触发快捷键
  1487. if (!hotkeys.filter.call(this, event)) return
  1488.  
  1489. // Gecko(Firefox)的command键值224,在Webkit(Chrome)中保持一致
  1490. // Webkit左右 command 键值不一样
  1491. if (key === 93 || key === 224) key = 91;
  1492.  
  1493. /**
  1494. * Collect bound keys
  1495. * If an Input Method Editor is processing key input and the event is keydown, return 229.
  1496. * https://stackoverflow.com/questions/25043934/is-it-ok-to-ignore-keydown-events-with-keycode-229
  1497. * http://lists.w3.org/Archives/Public/www-dom/2010JulSep/att-0182/keyCode-spec.html
  1498. */
  1499. if (_downKeys.indexOf(key) === -1 && key !== 229) _downKeys.push(key);
  1500. /**
  1501. * Jest test cases are required.
  1502. * ===============================
  1503. */
  1504. ['ctrlKey', 'altKey', 'shiftKey', 'metaKey'].forEach((keyName) => {
  1505. const keyNum = modifierMap[keyName];
  1506. if (event[keyName] && _downKeys.indexOf(keyNum) === -1) {
  1507. _downKeys.push(keyNum);
  1508. } else if (!event[keyName] && _downKeys.indexOf(keyNum) > -1) {
  1509. _downKeys.splice(_downKeys.indexOf(keyNum), 1);
  1510. } else if (keyName === 'metaKey' && event[keyName] && _downKeys.length === 3) {
  1511. /**
  1512. * Fix if Command is pressed:
  1513. * ===============================
  1514. */
  1515. if (!(event.ctrlKey || event.shiftKey || event.altKey)) {
  1516. _downKeys = _downKeys.slice(_downKeys.indexOf(keyNum));
  1517. }
  1518. }
  1519. });
  1520. /**
  1521. * -------------------------------
  1522. */
  1523.  
  1524. if (key in _mods) {
  1525. _mods[key] = true;
  1526.  
  1527. // 将特殊字符的key注册到 hotkeys 上
  1528. for (const k in _modifier) {
  1529. if (_modifier[k] === key) hotkeys[k] = true;
  1530. }
  1531.  
  1532. if (!asterisk) return
  1533. }
  1534.  
  1535. // 将 modifierMap 里面的修饰键绑定到 event 中
  1536. for (const e in _mods) {
  1537. if (Object.prototype.hasOwnProperty.call(_mods, e)) {
  1538. _mods[e] = event[modifierMap[e]];
  1539. }
  1540. }
  1541. /**
  1542. * https://github.com/jaywcjlove/hotkeys/pull/129
  1543. * This solves the issue in Firefox on Windows where hotkeys corresponding to special characters would not trigger.
  1544. * An example of this is ctrl+alt+m on a Swedish keyboard which is used to type μ.
  1545. * Browser support: https://caniuse.com/#feat=keyboardevent-getmodifierstate
  1546. */
  1547. if (event.getModifierState && (!(event.altKey && !event.ctrlKey) && event.getModifierState('AltGraph'))) {
  1548. if (_downKeys.indexOf(17) === -1) {
  1549. _downKeys.push(17);
  1550. }
  1551.  
  1552. if (_downKeys.indexOf(18) === -1) {
  1553. _downKeys.push(18);
  1554. }
  1555.  
  1556. _mods[17] = true;
  1557. _mods[18] = true;
  1558. }
  1559.  
  1560. // 获取范围 默认为 `all`
  1561. const scope = getScope();
  1562. // 对任何快捷键都需要做的处理
  1563. if (asterisk) {
  1564. for (let i = 0; i < asterisk.length; i++) {
  1565. if (
  1566. asterisk[i].scope === scope &&
  1567. ((event.type === 'keydown' && asterisk[i].keydown) ||
  1568. (event.type === 'keyup' && asterisk[i].keyup))
  1569. ) {
  1570. eventHandler(event, asterisk[i], scope, element);
  1571. }
  1572. }
  1573. }
  1574. // key 不在 _handlers 中返回
  1575. if (!(key in _handlers)) return
  1576.  
  1577. for (let i = 0; i < _handlers[key].length; i++) {
  1578. if (
  1579. (event.type === 'keydown' && _handlers[key][i].keydown) ||
  1580. (event.type === 'keyup' && _handlers[key][i].keyup)
  1581. ) {
  1582. if (_handlers[key][i].key) {
  1583. const record = _handlers[key][i];
  1584. const { splitKey } = record;
  1585. const keyShortcut = record.key.split(splitKey);
  1586. const _downKeysCurrent = []; // 记录当前按键键值
  1587. for (let a = 0; a < keyShortcut.length; a++) {
  1588. _downKeysCurrent.push(code(keyShortcut[a]));
  1589. }
  1590. if (_downKeysCurrent.sort().join('') === _downKeys.sort().join('')) {
  1591. // 找到处理内容
  1592. eventHandler(event, record, scope, element);
  1593. }
  1594. }
  1595. }
  1596. }
  1597. }
  1598.  
  1599. // 判断 element 是否已经绑定事件
  1600. function isElementBind (element) {
  1601. return elementHasBindEvent.indexOf(element) > -1
  1602. }
  1603.  
  1604. function hotkeys (key, option, method) {
  1605. _downKeys = [];
  1606. const keys = getKeys(key); // 需要处理的快捷键列表
  1607. let mods = [];
  1608. let scope = 'all'; // scope默认为all,所有范围都有效
  1609. let element = document; // 快捷键事件绑定节点
  1610. let i = 0;
  1611. let keyup = false;
  1612. let keydown = true;
  1613. let splitKey = '+';
  1614.  
  1615. // 对为设定范围的判断
  1616. if (method === undefined && typeof option === 'function') {
  1617. method = option;
  1618. }
  1619.  
  1620. if (Object.prototype.toString.call(option) === '[object Object]') {
  1621. if (option.scope) scope = option.scope; // eslint-disable-line
  1622. if (option.element) element = option.element; // eslint-disable-line
  1623. if (option.keyup) keyup = option.keyup; // eslint-disable-line
  1624. if (option.keydown !== undefined) keydown = option.keydown; // eslint-disable-line
  1625. if (typeof option.splitKey === 'string') splitKey = option.splitKey; // eslint-disable-line
  1626. }
  1627.  
  1628. if (typeof option === 'string') scope = option;
  1629.  
  1630. // 对于每个快捷键进行处理
  1631. for (; i < keys.length; i++) {
  1632. key = keys[i].split(splitKey); // 按键列表
  1633. mods = [];
  1634.  
  1635. // 如果是组合快捷键取得组合快捷键
  1636. if (key.length > 1) mods = getMods(_modifier, key);
  1637.  
  1638. // 将非修饰键转化为键码
  1639. key = key[key.length - 1];
  1640. key = key === '*' ? '*' : code(key); // *表示匹配所有快捷键
  1641.  
  1642. // 判断key是否在_handlers中,不在就赋一个空数组
  1643. if (!(key in _handlers)) _handlers[key] = [];
  1644. _handlers[key].push({
  1645. keyup,
  1646. keydown,
  1647. scope,
  1648. mods,
  1649. shortcut: keys[i],
  1650. method,
  1651. key: keys[i],
  1652. splitKey,
  1653. element
  1654. });
  1655. }
  1656. // 在全局document上设置快捷键
  1657. if (typeof element !== 'undefined' && !isElementBind(element) && window) {
  1658. elementHasBindEvent.push(element);
  1659. addEvent(element, 'keydown', (e) => {
  1660. dispatch(e, element);
  1661. });
  1662. if (!winListendFocus) {
  1663. winListendFocus = true;
  1664. addEvent(window, 'focus', () => {
  1665. _downKeys = [];
  1666. });
  1667. }
  1668. addEvent(element, 'keyup', (e) => {
  1669. dispatch(e, element);
  1670. clearModifier(e);
  1671. });
  1672. }
  1673. }
  1674.  
  1675. function trigger (shortcut, scope = 'all') {
  1676. Object.keys(_handlers).forEach((key) => {
  1677. const data = _handlers[key].find((item) => item.scope === scope && item.shortcut === shortcut);
  1678. if (data && data.method) {
  1679. data.method();
  1680. }
  1681. });
  1682. }
  1683.  
  1684. const _api = {
  1685. setScope,
  1686. getScope,
  1687. deleteScope,
  1688. getPressedKeyCodes,
  1689. isPressed,
  1690. filter,
  1691. trigger,
  1692. unbind,
  1693. keyMap: _keyMap,
  1694. modifier: _modifier,
  1695. modifierMap
  1696. };
  1697. for (const a in _api) {
  1698. if (Object.prototype.hasOwnProperty.call(_api, a)) {
  1699. hotkeys[a] = _api[a];
  1700. }
  1701. }
  1702.  
  1703. if (typeof window !== 'undefined') {
  1704. const _hotkeys = window.hotkeys;
  1705. hotkeys.noConflict = (deep) => {
  1706. if (deep && window.hotkeys === hotkeys) {
  1707. window.hotkeys = _hotkeys;
  1708. }
  1709. return hotkeys
  1710. };
  1711. window.hotkeys = hotkeys;
  1712. }
  1713.  
  1714. /*!
  1715. * @name hotKeyRegister.js
  1716. * @description vue-debug-helper的快捷键配置
  1717. * @version 0.0.1
  1718. * @author xxxily
  1719. * @date 2022/04/26 14:37
  1720. * @github https://github.com/xxxily
  1721. */
  1722.  
  1723. function hotKeyRegister () {
  1724. const hotKeyMap = {
  1725. 'shift+alt+a,shift+alt+ctrl+a': functionCall.componentsSummaryStatisticsSort,
  1726. 'shift+alt+l': functionCall.componentsStatistics,
  1727. 'shift+alt+d': functionCall.destroyStatisticsSort,
  1728. 'shift+alt+c': functionCall.clearAll,
  1729. 'shift+alt+e': function (event, handler) {
  1730. if (helper.config.dd.enabled) {
  1731. functionCall.undd();
  1732. } else {
  1733. functionCall.dd();
  1734. }
  1735. }
  1736. };
  1737.  
  1738. Object.keys(hotKeyMap).forEach(key => {
  1739. hotkeys(key, hotKeyMap[key]);
  1740. });
  1741. }
  1742.  
  1743. /*!
  1744. * @name vueDetector.js
  1745. * @description 检测页面是否存在Vue对象
  1746. * @version 0.0.1
  1747. * @author xxxily
  1748. * @date 2022/04/27 11:43
  1749. * @github https://github.com/xxxily
  1750. */
  1751.  
  1752. function mutationDetector (callback, shadowRoot) {
  1753. const win = window;
  1754. const MutationObserver = win.MutationObserver || win.WebKitMutationObserver;
  1755. const docRoot = shadowRoot || win.document.documentElement;
  1756. const maxDetectTries = 1500;
  1757. const timeout = 1000 * 10;
  1758. const startTime = Date.now();
  1759. let detectCount = 0;
  1760. let detectStatus = false;
  1761.  
  1762. if (!MutationObserver) {
  1763. debug.warn('MutationObserver is not supported in this browser');
  1764. return false
  1765. }
  1766.  
  1767. let mObserver = null;
  1768. const mObserverCallback = (mutationsList, observer) => {
  1769. if (detectStatus) {
  1770. return
  1771. }
  1772.  
  1773. /* 超时或检测次数过多,取消监听 */
  1774. if (Date.now() - startTime > timeout || detectCount > maxDetectTries) {
  1775. debug.warn('mutationDetector timeout or detectCount > maxDetectTries, stop detect');
  1776. if (mObserver && mObserver.disconnect) {
  1777. mObserver.disconnect();
  1778. mObserver = null;
  1779. }
  1780. }
  1781.  
  1782. for (let i = 0; i < mutationsList.length; i++) {
  1783. detectCount++;
  1784. const mutation = mutationsList[i];
  1785. if (mutation.target && mutation.target.__vue__) {
  1786. let Vue = Object.getPrototypeOf(mutation.target.__vue__).constructor;
  1787. while (Vue.super) {
  1788. Vue = Vue.super;
  1789. }
  1790.  
  1791. /* 检测成功后销毁观察对象 */
  1792. if (mObserver && mObserver.disconnect) {
  1793. mObserver.disconnect();
  1794. mObserver = null;
  1795. }
  1796.  
  1797. detectStatus = true;
  1798. callback && callback(Vue);
  1799. break
  1800. }
  1801. }
  1802. };
  1803.  
  1804. mObserver = new MutationObserver(mObserverCallback);
  1805. mObserver.observe(docRoot, {
  1806. attributes: true,
  1807. childList: true,
  1808. subtree: true
  1809. });
  1810. }
  1811.  
  1812. /**
  1813. * 检测页面是否存在Vue对象,方法参考:https://github.com/vuejs/devtools/blob/main/packages/shell-chrome/src/detector.js
  1814. * @param {window} win windwod对象
  1815. * @param {function} callback 检测到Vue对象后的回调函数
  1816. */
  1817. function vueDetect (win, callback) {
  1818. let delay = 1000;
  1819. let detectRemainingTries = 10;
  1820. let detectSuc = false;
  1821.  
  1822. // Method 1: MutationObserver detector
  1823. mutationDetector((Vue) => {
  1824. if (!detectSuc) {
  1825. debug.info('------------- Vue mutation detected -------------');
  1826. detectSuc = true;
  1827. callback(Vue);
  1828. }
  1829. });
  1830.  
  1831. function runDetect () {
  1832. if (detectSuc) {
  1833. return false
  1834. }
  1835.  
  1836. // Method 2: Check Vue 3
  1837. const vueDetected = !!(win.__VUE__);
  1838. if (vueDetected) {
  1839. debug.info('------------- Vue 3 detected -------------');
  1840. detectSuc = true;
  1841. callback(win.__VUE__);
  1842. return
  1843. }
  1844.  
  1845. // Method 3: Scan all elements inside document
  1846. const all = document.querySelectorAll('*');
  1847. let el;
  1848. for (let i = 0; i < all.length; i++) {
  1849. if (all[i].__vue__) {
  1850. el = all[i];
  1851. break
  1852. }
  1853. }
  1854. if (el) {
  1855. let Vue = Object.getPrototypeOf(el.__vue__).constructor;
  1856. while (Vue.super) {
  1857. Vue = Vue.super;
  1858. }
  1859. debug.info('------------- Vue 2 detected -------------');
  1860. detectSuc = true;
  1861. callback(Vue);
  1862. return
  1863. }
  1864.  
  1865. if (detectRemainingTries > 0) {
  1866. detectRemainingTries--;
  1867. setTimeout(() => {
  1868. runDetect();
  1869. }, delay);
  1870. delay *= 5;
  1871. }
  1872. }
  1873.  
  1874. setTimeout(() => {
  1875. runDetect();
  1876. }, 100);
  1877. }
  1878.  
  1879. /**
  1880. * 判断是否处于Iframe中
  1881. * @returns {boolean}
  1882. */
  1883. function isInIframe () {
  1884. return window !== window.top
  1885. }
  1886.  
  1887. /**
  1888. * 由于tampermonkey对window对象进行了封装,我们实际访问到的window并非页面真实的window
  1889. * 这就导致了如果我们需要将某些对象挂载到页面的window进行调试的时候就无法挂载了
  1890. * 所以必须使用特殊手段才能访问到页面真实的window对象,于是就有了下面这个函数
  1891. * @returns {Promise<void>}
  1892. */
  1893. async function getPageWindow () {
  1894. return new Promise(function (resolve, reject) {
  1895. if (window._pageWindow) {
  1896. return resolve(window._pageWindow)
  1897. }
  1898.  
  1899. const listenEventList = ['load', 'mousemove', 'scroll', 'get-page-window-event'];
  1900.  
  1901. function getWin (event) {
  1902. window._pageWindow = this;
  1903. // debug.log('getPageWindow succeed', event)
  1904. listenEventList.forEach(eventType => {
  1905. window.removeEventListener(eventType, getWin, true);
  1906. });
  1907. resolve(window._pageWindow);
  1908. }
  1909.  
  1910. listenEventList.forEach(eventType => {
  1911. window.addEventListener(eventType, getWin, true);
  1912. });
  1913.  
  1914. /* 自行派发事件以便用最短的时候获得pageWindow对象 */
  1915. window.dispatchEvent(new window.Event('get-page-window-event'));
  1916. })
  1917. }
  1918.  
  1919. let registerStatus = 'init';
  1920. window._debugMode_ = true
  1921.  
  1922. ;(async function () {
  1923. if (isInIframe()) {
  1924. debug.log('running in iframe, skip init', window.location.href);
  1925. return false
  1926. }
  1927.  
  1928. const win = await getPageWindow();
  1929. vueDetect(win, function (Vue) {
  1930. mixinRegister(Vue);
  1931. menuRegister(Vue);
  1932. hotKeyRegister();
  1933.  
  1934. // 挂载到window上,方便通过控制台调用调试
  1935. helper.Vue = Vue;
  1936. win.vueDebugHelper = helper;
  1937.  
  1938. // 自动开启Vue的调试模式
  1939. if (Vue.config) {
  1940. Vue.config.debug = true;
  1941. Vue.config.devtools = true;
  1942. Vue.config.performance = true;
  1943. } else {
  1944. debug.log('Vue.config is not defined');
  1945. }
  1946.  
  1947. debug.log('vue debug helper register success');
  1948. registerStatus = 'success';
  1949. });
  1950.  
  1951. setTimeout(() => {
  1952. if (registerStatus !== 'success') {
  1953. menuRegister(null);
  1954. debug.warn('vue debug helper register failed, please check if vue is loaded .', win.location.href);
  1955. }
  1956. }, 1000 * 10);
  1957. })();