hotkeys.js 17 KB

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