hotkeys.esm.js 16 KB

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