hotkeys.common.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  1. /**!
  2. * hotkeys-js v3.9.4
  3. * A simple micro-library for defining and dispatching keyboard shortcuts. It has no dependencies.
  4. *
  5. * Copyright (c) 2022 kenny wong <wowohoo@qq.com>
  6. * http://jaywcjlove.github.io/hotkeys
  7. * Licensed under the MIT license
  8. */
  9. 'use strict';
  10. var isff = typeof navigator !== 'undefined' ? navigator.userAgent.toLowerCase().indexOf('firefox') > 0 : false; // 绑定事件
  11. function addEvent(object, event, method, useCapture) {
  12. if (object.addEventListener) {
  13. object.addEventListener(event, method, useCapture);
  14. } else if (object.attachEvent) {
  15. object.attachEvent("on".concat(event), function () {
  16. method(window.event);
  17. });
  18. }
  19. } // 修饰键转换成对应的键码
  20. function getMods(modifier, key) {
  21. var mods = key.slice(0, key.length - 1);
  22. for (var i = 0; i < mods.length; i++) {
  23. mods[i] = modifier[mods[i].toLowerCase()];
  24. }
  25. return mods;
  26. } // 处理传的key字符串转换成数组
  27. function getKeys(key) {
  28. if (typeof key !== 'string') key = '';
  29. key = key.replace(/\s/g, ''); // 匹配任何空白字符,包括空格、制表符、换页符等等
  30. var keys = key.split(','); // 同时设置多个快捷键,以','分割
  31. var index = keys.lastIndexOf(''); // 快捷键可能包含',',需特殊处理
  32. for (; index >= 0;) {
  33. keys[index - 1] += ',';
  34. keys.splice(index, 1);
  35. index = keys.lastIndexOf('');
  36. }
  37. return keys;
  38. } // 比较修饰键的数组
  39. function compareArray(a1, a2) {
  40. var arr1 = a1.length >= a2.length ? a1 : a2;
  41. var arr2 = a1.length >= a2.length ? a2 : a1;
  42. var isIndex = true;
  43. for (var i = 0; i < arr1.length; i++) {
  44. if (arr2.indexOf(arr1[i]) === -1) isIndex = false;
  45. }
  46. return isIndex;
  47. }
  48. var _keyMap = {
  49. backspace: 8,
  50. tab: 9,
  51. clear: 12,
  52. enter: 13,
  53. return: 13,
  54. esc: 27,
  55. escape: 27,
  56. space: 32,
  57. left: 37,
  58. up: 38,
  59. right: 39,
  60. down: 40,
  61. del: 46,
  62. delete: 46,
  63. ins: 45,
  64. insert: 45,
  65. home: 36,
  66. end: 35,
  67. pageup: 33,
  68. pagedown: 34,
  69. capslock: 20,
  70. num_0: 96,
  71. num_1: 97,
  72. num_2: 98,
  73. num_3: 99,
  74. num_4: 100,
  75. num_5: 101,
  76. num_6: 102,
  77. num_7: 103,
  78. num_8: 104,
  79. num_9: 105,
  80. num_multiply: 106,
  81. num_add: 107,
  82. num_enter: 108,
  83. num_subtract: 109,
  84. num_decimal: 110,
  85. num_divide: 111,
  86. '⇪': 20,
  87. ',': 188,
  88. '.': 190,
  89. '/': 191,
  90. '`': 192,
  91. '-': isff ? 173 : 189,
  92. '=': isff ? 61 : 187,
  93. ';': isff ? 59 : 186,
  94. '\'': 222,
  95. '[': 219,
  96. ']': 221,
  97. '\\': 220
  98. }; // Modifier Keys
  99. var _modifier = {
  100. // shiftKey
  101. '⇧': 16,
  102. shift: 16,
  103. // altKey
  104. '⌥': 18,
  105. alt: 18,
  106. option: 18,
  107. // ctrlKey
  108. '⌃': 17,
  109. ctrl: 17,
  110. control: 17,
  111. // metaKey
  112. '⌘': 91,
  113. cmd: 91,
  114. command: 91
  115. };
  116. var modifierMap = {
  117. 16: 'shiftKey',
  118. 18: 'altKey',
  119. 17: 'ctrlKey',
  120. 91: 'metaKey',
  121. shiftKey: 16,
  122. ctrlKey: 17,
  123. altKey: 18,
  124. metaKey: 91
  125. };
  126. var _mods = {
  127. 16: false,
  128. 18: false,
  129. 17: false,
  130. 91: false
  131. };
  132. var _handlers = {}; // F1~F12 special key
  133. for (var k = 1; k < 20; k++) {
  134. _keyMap["f".concat(k)] = 111 + k;
  135. }
  136. var _downKeys = []; // 记录摁下的绑定键
  137. var winListendFocus = false; // window是否已经监听了focus事件
  138. var _scope = 'all'; // 默认热键范围
  139. var elementHasBindEvent = []; // 已绑定事件的节点记录
  140. // 返回键码
  141. var code = function code(x) {
  142. return _keyMap[x.toLowerCase()] || _modifier[x.toLowerCase()] || x.toUpperCase().charCodeAt(0);
  143. }; // 设置获取当前范围(默认为'所有')
  144. function setScope(scope) {
  145. _scope = scope || 'all';
  146. } // 获取当前范围
  147. function getScope() {
  148. return _scope || 'all';
  149. } // 获取摁下绑定键的键值
  150. function getPressedKeyCodes() {
  151. return _downKeys.slice(0);
  152. } // 表单控件控件判断 返回 Boolean
  153. // hotkey is effective only when filter return true
  154. function filter(event) {
  155. var target = event.target || event.srcElement;
  156. var tagName = target.tagName;
  157. var flag = true; // ignore: isContentEditable === 'true', <input> and <textarea> when readOnly state is false, <select>
  158. if (target.isContentEditable || (tagName === 'INPUT' || tagName === 'TEXTAREA' || tagName === 'SELECT') && !target.readOnly) {
  159. flag = false;
  160. }
  161. return flag;
  162. } // 判断摁下的键是否为某个键,返回true或者false
  163. function isPressed(keyCode) {
  164. if (typeof keyCode === 'string') {
  165. keyCode = code(keyCode); // 转换成键码
  166. }
  167. return _downKeys.indexOf(keyCode) !== -1;
  168. } // 循环删除handlers中的所有 scope(范围)
  169. function deleteScope(scope, newScope) {
  170. var handlers;
  171. var i; // 没有指定scope,获取scope
  172. if (!scope) scope = getScope();
  173. for (var key in _handlers) {
  174. if (Object.prototype.hasOwnProperty.call(_handlers, key)) {
  175. handlers = _handlers[key];
  176. for (i = 0; i < handlers.length;) {
  177. if (handlers[i].scope === scope) handlers.splice(i, 1);else i++;
  178. }
  179. }
  180. } // 如果scope被删除,将scope重置为all
  181. if (getScope() === scope) setScope(newScope || 'all');
  182. } // 清除修饰键
  183. function clearModifier(event) {
  184. var key = event.keyCode || event.which || event.charCode;
  185. var i = _downKeys.indexOf(key); // 从列表中清除按压过的键
  186. if (i >= 0) {
  187. _downKeys.splice(i, 1);
  188. } // 特殊处理 cmmand 键,在 cmmand 组合快捷键 keyup 只执行一次的问题
  189. if (event.key && event.key.toLowerCase() === 'meta') {
  190. _downKeys.splice(0, _downKeys.length);
  191. } // 修饰键 shiftKey altKey ctrlKey (command||metaKey) 清除
  192. if (key === 93 || key === 224) key = 91;
  193. if (key in _mods) {
  194. _mods[key] = false; // 将修饰键重置为false
  195. for (var k in _modifier) {
  196. if (_modifier[k] === key) hotkeys[k] = false;
  197. }
  198. }
  199. }
  200. function unbind(keysInfo) {
  201. // unbind(), unbind all keys
  202. if (typeof keysInfo === 'undefined') {
  203. Object.keys(_handlers).forEach(function (key) {
  204. return delete _handlers[key];
  205. });
  206. } else if (Array.isArray(keysInfo)) {
  207. // support like : unbind([{key: 'ctrl+a', scope: 's1'}, {key: 'ctrl-a', scope: 's2', splitKey: '-'}])
  208. keysInfo.forEach(function (info) {
  209. if (info.key) eachUnbind(info);
  210. });
  211. } else if (typeof keysInfo === 'object') {
  212. // support like unbind({key: 'ctrl+a, ctrl+b', scope:'abc'})
  213. if (keysInfo.key) eachUnbind(keysInfo);
  214. } else if (typeof keysInfo === 'string') {
  215. for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  216. args[_key - 1] = arguments[_key];
  217. }
  218. // support old method
  219. // eslint-disable-line
  220. var scope = args[0],
  221. method = args[1];
  222. if (typeof scope === 'function') {
  223. method = scope;
  224. scope = '';
  225. }
  226. eachUnbind({
  227. key: keysInfo,
  228. scope: scope,
  229. method: method,
  230. splitKey: '+'
  231. });
  232. }
  233. } // 解除绑定某个范围的快捷键
  234. var eachUnbind = function eachUnbind(_ref) {
  235. var key = _ref.key,
  236. scope = _ref.scope,
  237. method = _ref.method,
  238. _ref$splitKey = _ref.splitKey,
  239. splitKey = _ref$splitKey === void 0 ? '+' : _ref$splitKey;
  240. var multipleKeys = getKeys(key);
  241. multipleKeys.forEach(function (originKey) {
  242. var unbindKeys = originKey.split(splitKey);
  243. var len = unbindKeys.length;
  244. var lastKey = unbindKeys[len - 1];
  245. var keyCode = lastKey === '*' ? '*' : code(lastKey);
  246. if (!_handlers[keyCode]) return; // 判断是否传入范围,没有就获取范围
  247. if (!scope) scope = getScope();
  248. var mods = len > 1 ? getMods(_modifier, unbindKeys) : [];
  249. _handlers[keyCode] = _handlers[keyCode].filter(function (record) {
  250. // 通过函数判断,是否解除绑定,函数相等直接返回
  251. var isMatchingMethod = method ? record.method === method : true;
  252. return !(isMatchingMethod && record.scope === scope && compareArray(record.mods, mods));
  253. });
  254. });
  255. }; // 对监听对应快捷键的回调函数进行处理
  256. function eventHandler(event, handler, scope, element) {
  257. if (handler.element !== element) {
  258. return;
  259. }
  260. var modifiersMatch; // 看它是否在当前范围
  261. if (handler.scope === scope || handler.scope === 'all') {
  262. // 检查是否匹配修饰符(如果有返回true)
  263. modifiersMatch = handler.mods.length > 0;
  264. for (var y in _mods) {
  265. if (Object.prototype.hasOwnProperty.call(_mods, y)) {
  266. if (!_mods[y] && handler.mods.indexOf(+y) > -1 || _mods[y] && handler.mods.indexOf(+y) === -1) {
  267. modifiersMatch = false;
  268. }
  269. }
  270. } // 调用处理程序,如果是修饰键不做处理
  271. if (handler.mods.length === 0 && !_mods[16] && !_mods[18] && !_mods[17] && !_mods[91] || modifiersMatch || handler.shortcut === '*') {
  272. if (handler.method(event, handler) === false) {
  273. if (event.preventDefault) event.preventDefault();else event.returnValue = false;
  274. if (event.stopPropagation) event.stopPropagation();
  275. if (event.cancelBubble) event.cancelBubble = true;
  276. }
  277. }
  278. }
  279. } // 处理keydown事件
  280. function dispatch(event, element) {
  281. var asterisk = _handlers['*'];
  282. var key = event.keyCode || event.which || event.charCode; // 表单控件过滤 默认表单控件不触发快捷键
  283. if (!hotkeys.filter.call(this, event)) return; // Gecko(Firefox)的command键值224,在Webkit(Chrome)中保持一致
  284. // Webkit左右 command 键值不一样
  285. if (key === 93 || key === 224) key = 91;
  286. /**
  287. * Collect bound keys
  288. * If an Input Method Editor is processing key input and the event is keydown, return 229.
  289. * https://stackoverflow.com/questions/25043934/is-it-ok-to-ignore-keydown-events-with-keycode-229
  290. * http://lists.w3.org/Archives/Public/www-dom/2010JulSep/att-0182/keyCode-spec.html
  291. */
  292. if (_downKeys.indexOf(key) === -1 && key !== 229) _downKeys.push(key);
  293. /**
  294. * Jest test cases are required.
  295. * ===============================
  296. */
  297. ['ctrlKey', 'altKey', 'shiftKey', 'metaKey'].forEach(function (keyName) {
  298. var keyNum = modifierMap[keyName];
  299. if (event[keyName] && _downKeys.indexOf(keyNum) === -1) {
  300. _downKeys.push(keyNum);
  301. } else if (!event[keyName] && _downKeys.indexOf(keyNum) > -1) {
  302. _downKeys.splice(_downKeys.indexOf(keyNum), 1);
  303. } else if (keyName === 'metaKey' && event[keyName] && _downKeys.length === 3) {
  304. /**
  305. * Fix if Command is pressed:
  306. * ===============================
  307. */
  308. if (!(event.ctrlKey || event.shiftKey || event.altKey)) {
  309. _downKeys = _downKeys.slice(_downKeys.indexOf(keyNum));
  310. }
  311. }
  312. });
  313. /**
  314. * -------------------------------
  315. */
  316. if (key in _mods) {
  317. _mods[key] = true; // 将特殊字符的key注册到 hotkeys 上
  318. for (var k in _modifier) {
  319. if (_modifier[k] === key) hotkeys[k] = true;
  320. }
  321. if (!asterisk) return;
  322. } // 将 modifierMap 里面的修饰键绑定到 event 中
  323. for (var e in _mods) {
  324. if (Object.prototype.hasOwnProperty.call(_mods, e)) {
  325. _mods[e] = event[modifierMap[e]];
  326. }
  327. }
  328. /**
  329. * https://github.com/jaywcjlove/hotkeys/pull/129
  330. * This solves the issue in Firefox on Windows where hotkeys corresponding to special characters would not trigger.
  331. * An example of this is ctrl+alt+m on a Swedish keyboard which is used to type μ.
  332. * Browser support: https://caniuse.com/#feat=keyboardevent-getmodifierstate
  333. */
  334. if (event.getModifierState && !(event.altKey && !event.ctrlKey) && event.getModifierState('AltGraph')) {
  335. if (_downKeys.indexOf(17) === -1) {
  336. _downKeys.push(17);
  337. }
  338. if (_downKeys.indexOf(18) === -1) {
  339. _downKeys.push(18);
  340. }
  341. _mods[17] = true;
  342. _mods[18] = true;
  343. } // 获取范围 默认为 `all`
  344. var scope = getScope(); // 对任何快捷键都需要做的处理
  345. if (asterisk) {
  346. for (var i = 0; i < asterisk.length; i++) {
  347. if (asterisk[i].scope === scope && (event.type === 'keydown' && asterisk[i].keydown || event.type === 'keyup' && asterisk[i].keyup)) {
  348. eventHandler(event, asterisk[i], scope, element);
  349. }
  350. }
  351. } // key 不在 _handlers 中返回
  352. if (!(key in _handlers)) return;
  353. for (var _i = 0; _i < _handlers[key].length; _i++) {
  354. if (event.type === 'keydown' && _handlers[key][_i].keydown || event.type === 'keyup' && _handlers[key][_i].keyup) {
  355. if (_handlers[key][_i].key) {
  356. var record = _handlers[key][_i];
  357. var splitKey = record.splitKey;
  358. var keyShortcut = record.key.split(splitKey);
  359. var _downKeysCurrent = []; // 记录当前按键键值
  360. for (var a = 0; a < keyShortcut.length; a++) {
  361. _downKeysCurrent.push(code(keyShortcut[a]));
  362. }
  363. if (_downKeysCurrent.sort().join('') === _downKeys.sort().join('')) {
  364. // 找到处理内容
  365. eventHandler(event, record, scope, element);
  366. }
  367. }
  368. }
  369. }
  370. } // 判断 element 是否已经绑定事件
  371. function isElementBind(element) {
  372. return elementHasBindEvent.indexOf(element) > -1;
  373. }
  374. function hotkeys(key, option, method) {
  375. _downKeys = [];
  376. var keys = getKeys(key); // 需要处理的快捷键列表
  377. var mods = [];
  378. var scope = 'all'; // scope默认为all,所有范围都有效
  379. var element = document; // 快捷键事件绑定节点
  380. var i = 0;
  381. var keyup = false;
  382. var keydown = true;
  383. var splitKey = '+';
  384. var capture = false; // 对为设定范围的判断
  385. if (method === undefined && typeof option === 'function') {
  386. method = option;
  387. }
  388. if (Object.prototype.toString.call(option) === '[object Object]') {
  389. if (option.scope) scope = option.scope; // eslint-disable-line
  390. if (option.element) element = option.element; // eslint-disable-line
  391. if (option.keyup) keyup = option.keyup; // eslint-disable-line
  392. if (option.keydown !== undefined) keydown = option.keydown; // eslint-disable-line
  393. if (option.capture !== undefined) capture = option.capture; // eslint-disable-line
  394. if (typeof option.splitKey === 'string') splitKey = option.splitKey; // eslint-disable-line
  395. }
  396. if (typeof option === 'string') scope = option; // 对于每个快捷键进行处理
  397. for (; i < keys.length; i++) {
  398. key = keys[i].split(splitKey); // 按键列表
  399. mods = []; // 如果是组合快捷键取得组合快捷键
  400. if (key.length > 1) mods = getMods(_modifier, key); // 将非修饰键转化为键码
  401. key = key[key.length - 1];
  402. key = key === '*' ? '*' : code(key); // *表示匹配所有快捷键
  403. // 判断key是否在_handlers中,不在就赋一个空数组
  404. if (!(key in _handlers)) _handlers[key] = [];
  405. _handlers[key].push({
  406. keyup: keyup,
  407. keydown: keydown,
  408. scope: scope,
  409. mods: mods,
  410. shortcut: keys[i],
  411. method: method,
  412. key: keys[i],
  413. splitKey: splitKey,
  414. element: element
  415. });
  416. } // 在全局document上设置快捷键
  417. if (typeof element !== 'undefined' && !isElementBind(element) && window) {
  418. elementHasBindEvent.push(element);
  419. addEvent(element, 'keydown', function (e) {
  420. dispatch(e, element);
  421. }, capture);
  422. if (!winListendFocus) {
  423. winListendFocus = true;
  424. addEvent(window, 'focus', function () {
  425. _downKeys = [];
  426. }, capture);
  427. }
  428. addEvent(element, 'keyup', function (e) {
  429. dispatch(e, element);
  430. clearModifier(e);
  431. }, capture);
  432. }
  433. }
  434. function trigger(shortcut) {
  435. var scope = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'all';
  436. Object.keys(_handlers).forEach(function (key) {
  437. var data = _handlers[key].find(function (item) {
  438. return item.scope === scope && item.shortcut === shortcut;
  439. });
  440. if (data && data.method) {
  441. data.method();
  442. }
  443. });
  444. }
  445. var _api = {
  446. setScope: setScope,
  447. getScope: getScope,
  448. deleteScope: deleteScope,
  449. getPressedKeyCodes: getPressedKeyCodes,
  450. isPressed: isPressed,
  451. filter: filter,
  452. trigger: trigger,
  453. unbind: unbind,
  454. keyMap: _keyMap,
  455. modifier: _modifier,
  456. modifierMap: modifierMap
  457. };
  458. for (var a in _api) {
  459. if (Object.prototype.hasOwnProperty.call(_api, a)) {
  460. hotkeys[a] = _api[a];
  461. }
  462. }
  463. if (typeof window !== 'undefined') {
  464. var _hotkeys = window.hotkeys;
  465. hotkeys.noConflict = function (deep) {
  466. if (deep && window.hotkeys === hotkeys) {
  467. window.hotkeys = _hotkeys;
  468. }
  469. return hotkeys;
  470. };
  471. window.hotkeys = hotkeys;
  472. }
  473. module.exports = hotkeys;