vue-debug-helper

Vue components debug helper

Fra 30.04.2022. Se den seneste versjonen.

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