diff --git a/index.d.ts b/index.d.ts index 3ccc4472..d770931a 100644 --- a/index.d.ts +++ b/index.d.ts @@ -10,7 +10,7 @@ export interface KeyHandler { (keyboardEvent: KeyboardEvent, hotkeysEvent: HotkeysEvent): void | boolean } -type Options = { +export type Options = { scope?: string, element?: HTMLElement | null, keyup?: boolean | null @@ -47,6 +47,8 @@ interface Hotkeys { getPressedKeyCodes(): number[] filter(event: KeyboardEvent): boolean + + addCustomKeyMap(customKeyMap: Record): void } // https://github.com/eiriklv/react-masonry-component/issues/57 declare var hotkeys: Hotkeys diff --git a/src/main.js b/src/main.js index c65ffcf1..006e586d 100644 --- a/src/main.js +++ b/src/main.js @@ -1,13 +1,14 @@ -import { addEvent, getMods, getKeys, compareArray } from './utils'; +import { addEvent, getMods, getKeys, compareArray, isInteger } from './utils'; import { _keyMap, _modifier, modifierMap, _mods, _handlers } from './var'; let _downKeys = []; // 记录摁下的绑定键 +const _customKeyMap = {}; let _scope = 'all'; // 默认热键范围 const elementHasBindEvent = []; // 已绑定事件的节点记录 // 返回键码 -const code = (x) => _keyMap[x.toLowerCase()] +const code = (x) => _customKeyMap[x] || _keyMap[x.toLowerCase()] || _modifier[x.toLowerCase()] || x.toUpperCase().charCodeAt(0); @@ -24,6 +25,28 @@ function getPressedKeyCodes() { return _downKeys.slice(0); } +function addCustomKeyMap(keyMapPatch) { + if (typeof _keyMapPatch !== 'object') { + return; + } + + const _keyMapPatch = {}; + + // check that all values for each key is integer + Object.keys(_keyMapPatch).forEach((key) => { + const keyCode = keyMapPatch[key]; + + if (isInteger(keyCode)) { + _keyMapPatch[key] = keyCode; + } else if (module.hot) { + window.console.warning(`[hotkeys-js] (addCustomKeyMap) key "${key}" has wrong value type, ignored`); + } + }); + + // merge only valid keyCodes + Object.assign(_customKeyMap, _keyMapPatch); +} + // 表单控件控件判断 返回 Boolean // hotkey is effective only when filter return true function filter(event) { @@ -390,6 +413,7 @@ const _api = { isPressed, filter, unbind, + addCustomKeyMap, }; for (const a in _api) { if (Object.prototype.hasOwnProperty.call(_api, a)) { diff --git a/src/utils.js b/src/utils.js index fd8d8c9f..fbfeb9a5 100644 --- a/src/utils.js +++ b/src/utils.js @@ -45,10 +45,15 @@ function compareArray(a1, a2) { return isIndex; } +function isInteger(value) { + return typeof value === 'number' && Number.isFinite(value) && Math.floor(value) === value; +} + export { isff, getMods, getKeys, addEvent, compareArray, + isInteger, };