tinykeys 1.2.0 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +21 -0
- package/dist/tinykeys.d.ts +38 -5
- package/dist/tinykeys.js +1 -1
- package/dist/tinykeys.js.map +1 -1
- package/dist/tinykeys.modern.js +1 -1
- package/dist/tinykeys.modern.js.map +1 -1
- package/dist/tinykeys.module.js +1 -1
- package/dist/tinykeys.module.js.map +1 -1
- package/dist/tinykeys.umd.js +1 -1
- package/dist/tinykeys.umd.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -30,6 +30,27 @@ tinykeys(window, {
|
|
|
30
30
|
})
|
|
31
31
|
```
|
|
32
32
|
|
|
33
|
+
Alternatively, if you want to only create the keybinding handler, and register it as an event listener yourself:
|
|
34
|
+
|
|
35
|
+
```js
|
|
36
|
+
import { createKeybindingsHandler } from "tinykeys"
|
|
37
|
+
|
|
38
|
+
let handler = createKeybindingsHandler({
|
|
39
|
+
"Shift+D": () => {
|
|
40
|
+
alert("The 'Shift' and 'd' keys were pressed at the same time")
|
|
41
|
+
},
|
|
42
|
+
"y e e t": () => {
|
|
43
|
+
alert("The keys 'y', 'e', 'e', and 't' were pressed in order")
|
|
44
|
+
},
|
|
45
|
+
"$mod+KeyD": event => {
|
|
46
|
+
event.preventDefault()
|
|
47
|
+
alert("Either 'Control+d' or 'Meta+d' were pressed")
|
|
48
|
+
},
|
|
49
|
+
})
|
|
50
|
+
|
|
51
|
+
window.addEventListener("keydown", handler)
|
|
52
|
+
```
|
|
53
|
+
|
|
33
54
|
### React Hooks Example
|
|
34
55
|
|
|
35
56
|
If you're using tinykeys within a component, you should also make use of the
|
package/dist/tinykeys.d.ts
CHANGED
|
@@ -4,23 +4,56 @@
|
|
|
4
4
|
export interface KeyBindingMap {
|
|
5
5
|
[keybinding: string]: (event: KeyboardEvent) => void;
|
|
6
6
|
}
|
|
7
|
+
export interface KeyBindingHandlerOptions {
|
|
8
|
+
/**
|
|
9
|
+
* Keybinding sequences will wait this long between key presses before
|
|
10
|
+
* cancelling (default: 1000).
|
|
11
|
+
*
|
|
12
|
+
* **Note:** Setting this value too low (i.e. `300`) will be too fast for many
|
|
13
|
+
* of your users.
|
|
14
|
+
*/
|
|
15
|
+
timeout?: number;
|
|
16
|
+
}
|
|
7
17
|
/**
|
|
8
18
|
* Options to configure the behavior of keybindings.
|
|
9
19
|
*/
|
|
10
|
-
export interface KeyBindingOptions {
|
|
20
|
+
export interface KeyBindingOptions extends KeyBindingHandlerOptions {
|
|
11
21
|
/**
|
|
12
22
|
* Key presses will listen to this event (default: "keydown").
|
|
13
23
|
*/
|
|
14
24
|
event?: "keydown" | "keyup";
|
|
15
25
|
/**
|
|
16
26
|
* Keybinding sequences will wait this long between key presses before
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
27
|
+
* cancelling (default: 1000).
|
|
28
|
+
*
|
|
29
|
+
* **Note:** Setting this value too low (i.e. `300`) will be too fast for many
|
|
30
|
+
* of your users.
|
|
21
31
|
*/
|
|
22
32
|
timeout?: number;
|
|
23
33
|
}
|
|
34
|
+
/**
|
|
35
|
+
* Creates an event listener for handling keybindings.
|
|
36
|
+
*
|
|
37
|
+
* @example
|
|
38
|
+
* ```js
|
|
39
|
+
* import { createKeybindingsHandler } from "../src/keybindings"
|
|
40
|
+
*
|
|
41
|
+
* let handler = createKeybindingsHandler({
|
|
42
|
+
* "Shift+d": () => {
|
|
43
|
+
* alert("The 'Shift' and 'd' keys were pressed at the same time")
|
|
44
|
+
* },
|
|
45
|
+
* "y e e t": () => {
|
|
46
|
+
* alert("The keys 'y', 'e', 'e', and 't' were pressed in order")
|
|
47
|
+
* },
|
|
48
|
+
* "$mod+d": () => {
|
|
49
|
+
* alert("Either 'Control+d' or 'Meta+d' were pressed")
|
|
50
|
+
* },
|
|
51
|
+
* })
|
|
52
|
+
*
|
|
53
|
+
* window.addEvenListener("keydown", handler)
|
|
54
|
+
* ```
|
|
55
|
+
*/
|
|
56
|
+
export declare function createKeybindingsHandler(keyBindingMap: KeyBindingMap, options?: KeyBindingHandlerOptions): EventListener;
|
|
24
57
|
/**
|
|
25
58
|
* Subscribes to keybindings.
|
|
26
59
|
*
|
package/dist/tinykeys.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var e=["Shift","Meta","Alt","Control"],t="object"==typeof navigator&&/Mac|iPod|iPhone|iPad/.test(navigator.platform)?"Meta":"Control";
|
|
1
|
+
var e=["Shift","Meta","Alt","Control"],t="object"==typeof navigator&&/Mac|iPod|iPhone|iPad/.test(navigator.platform)?"Meta":"Control";function n(e,t){return"function"==typeof e.getModifierState&&e.getModifierState(t)}function r(r,o){var i;void 0===o&&(o={});var a=null!=(i=o.timeout)?i:1e3,u=Object.keys(r).map(function(e){return[(n=e,n.trim().split(" ").map(function(e){var n=e.split(/\b\+/),r=n.pop();return[n=n.map(function(e){return"$mod"===e?t:e}),r]})),r[e]];var n}),c=new Map,f=null;return function(t){t instanceof KeyboardEvent&&(u.forEach(function(r){var o=r[0],i=r[1],a=c.get(o)||o;!function(t,r){return!(r[1].toUpperCase()!==t.key.toUpperCase()&&r[1]!==t.code||r[0].find(function(e){return!n(t,e)})||e.find(function(e){return!r[0].includes(e)&&r[1]!==e&&n(t,e)}))}(t,a[0])?n(t,t.key)||c.delete(o):a.length>1?c.set(o,a.slice(1)):(c.delete(o),i(t))}),f&&clearTimeout(f),f=setTimeout(c.clear.bind(c),a))}}exports.createKeybindingsHandler=r,exports.default=function(e,t,n){var o;void 0===n&&(n={});var i=null!=(o=n.event)?o:"keydown",a=r(t,n);return e.addEventListener(i,a),function(){e.removeEventListener(i,a)}};
|
|
2
2
|
//# sourceMappingURL=tinykeys.js.map
|
package/dist/tinykeys.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tinykeys.js","sources":["../src/tinykeys.ts"],"sourcesContent":["type KeyBindingPress = [string[], string]\n\n/**\n * A map of keybinding strings to event handlers.\n */\nexport interface KeyBindingMap {\n\t[keybinding: string]: (event: KeyboardEvent) => void\n}\n\n/**\n * Options to configure the behavior of keybindings.\n */\
|
|
1
|
+
{"version":3,"file":"tinykeys.js","sources":["../src/tinykeys.ts"],"sourcesContent":["type KeyBindingPress = [string[], string]\n\n/**\n * A map of keybinding strings to event handlers.\n */\nexport interface KeyBindingMap {\n\t[keybinding: string]: (event: KeyboardEvent) => void\n}\n\nexport interface KeyBindingHandlerOptions {\n\t/**\n\t * Keybinding sequences will wait this long between key presses before\n\t * cancelling (default: 1000).\n\t *\n\t * **Note:** Setting this value too low (i.e. `300`) will be too fast for many\n\t * of your users.\n\t */\n\ttimeout?: number\n}\n\n/**\n * Options to configure the behavior of keybindings.\n */\nexport interface KeyBindingOptions extends KeyBindingHandlerOptions {\n\t/**\n\t * Key presses will listen to this event (default: \"keydown\").\n\t */\n\tevent?: \"keydown\" | \"keyup\"\n\n\t/**\n\t * Keybinding sequences will wait this long between key presses before\n\t * cancelling (default: 1000).\n\t *\n\t * **Note:** Setting this value too low (i.e. `300`) will be too fast for many\n\t * of your users.\n\t */\n\ttimeout?: number\n}\n\n/**\n * These are the modifier keys that change the meaning of keybindings.\n *\n * Note: Ignoring \"AltGraph\" because it is covered by the others.\n */\nlet KEYBINDING_MODIFIER_KEYS = [\"Shift\", \"Meta\", \"Alt\", \"Control\"]\n\n/**\n * Keybinding sequences should timeout if individual key presses are more than\n * 1s apart by default.\n */\nlet DEFAULT_TIMEOUT = 1000\n\n/**\n * Keybinding sequences should bind to this event by default.\n */\nlet DEFAULT_EVENT = \"keydown\"\n\n/**\n * An alias for creating platform-specific keybinding aliases.\n */\nlet MOD =\n\ttypeof navigator === \"object\" &&\n\t/Mac|iPod|iPhone|iPad/.test(navigator.platform)\n\t\t? \"Meta\"\n\t\t: \"Control\"\n\n/**\n * There's a bug in Chrome that causes event.getModifierState not to exist on\n * KeyboardEvent's for F1/F2/etc keys.\n */\nfunction getModifierState(event: KeyboardEvent, mod: string) {\n\treturn typeof event.getModifierState === \"function\"\n\t\t? event.getModifierState(mod)\n\t\t: false\n}\n\n/**\n * Parses a \"Key Binding String\" into its parts\n *\n * grammar = `<sequence>`\n * <sequence> = `<press> <press> <press> ...`\n * <press> = `<key>` or `<mods>+<key>`\n * <mods> = `<mod>+<mod>+...`\n */\nfunction parse(str: string): KeyBindingPress[] {\n\treturn str\n\t\t.trim()\n\t\t.split(\" \")\n\t\t.map(press => {\n\t\t\tlet mods = press.split(/\\b\\+/)\n\t\t\tlet key = mods.pop() as string\n\t\t\tmods = mods.map(mod => (mod === \"$mod\" ? MOD : mod))\n\t\t\treturn [mods, key]\n\t\t})\n}\n\n/**\n * This tells us if a series of events matches a key binding sequence either\n * partially or exactly.\n */\nfunction match(event: KeyboardEvent, press: KeyBindingPress): boolean {\n\t// prettier-ignore\n\treturn !(\n\t\t// Allow either the `event.key` or the `event.code`\n\t\t// MDN event.key: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key\n\t\t// MDN event.code: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code\n\t\t(\n\t\t\tpress[1].toUpperCase() !== event.key.toUpperCase() &&\n\t\t\tpress[1] !== event.code\n\t\t) ||\n\n\t\t// Ensure all the modifiers in the keybinding are pressed.\n\t\tpress[0].find(mod => {\n\t\t\treturn !getModifierState(event, mod)\n\t\t}) ||\n\n\t\t// KEYBINDING_MODIFIER_KEYS (Shift/Control/etc) change the meaning of a\n\t\t// keybinding. So if they are pressed but aren't part of the current\n\t\t// keybinding press, then we don't have a match.\n\t\tKEYBINDING_MODIFIER_KEYS.find(mod => {\n\t\t\treturn !press[0].includes(mod) && press[1] !== mod && getModifierState(event, mod)\n\t\t})\n\t)\n}\n\n/**\n * Creates an event listener for handling keybindings.\n *\n * @example\n * ```js\n * import { createKeybindingsHandler } from \"../src/keybindings\"\n *\n * let handler = createKeybindingsHandler({\n * \t\"Shift+d\": () => {\n * \t\talert(\"The 'Shift' and 'd' keys were pressed at the same time\")\n * \t},\n * \t\"y e e t\": () => {\n * \t\talert(\"The keys 'y', 'e', 'e', and 't' were pressed in order\")\n * \t},\n * \t\"$mod+d\": () => {\n * \t\talert(\"Either 'Control+d' or 'Meta+d' were pressed\")\n * \t},\n * })\n *\n * window.addEvenListener(\"keydown\", handler)\n * ```\n */\nexport function createKeybindingsHandler(\n\tkeyBindingMap: KeyBindingMap,\n\toptions: KeyBindingHandlerOptions = {},\n): EventListener {\n\tlet timeout = options.timeout ?? DEFAULT_TIMEOUT\n\n\tlet keyBindings = Object.keys(keyBindingMap).map(key => {\n\t\treturn [parse(key), keyBindingMap[key]] as const\n\t})\n\n\tlet possibleMatches = new Map<KeyBindingPress[], KeyBindingPress[]>()\n\tlet timer: number | null = null\n\n\treturn event => {\n\t\t// Ensure and stop any event that isn't a full keyboard event.\n\t\t// Autocomplete option navigation and selection would fire a instanceof Event,\n\t\t// instead of the expected KeyboardEvent\n\t\tif (!(event instanceof KeyboardEvent)) {\n\t\t\treturn\n\t\t}\n\n\t\tkeyBindings.forEach(keyBinding => {\n\t\t\tlet sequence = keyBinding[0]\n\t\t\tlet callback = keyBinding[1]\n\n\t\t\tlet prev = possibleMatches.get(sequence)\n\t\t\tlet remainingExpectedPresses = prev ? prev : sequence\n\t\t\tlet currentExpectedPress = remainingExpectedPresses[0]\n\n\t\t\tlet matches = match(event, currentExpectedPress)\n\n\t\t\tif (!matches) {\n\t\t\t\t// Modifier keydown events shouldn't break sequences\n\t\t\t\t// Note: This works because:\n\t\t\t\t// - non-modifiers will always return false\n\t\t\t\t// - if the current keypress is a modifier then it will return true when we check its state\n\t\t\t\t// MDN: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/getModifierState\n\t\t\t\tif (!getModifierState(event, event.key)) {\n\t\t\t\t\tpossibleMatches.delete(sequence)\n\t\t\t\t}\n\t\t\t} else if (remainingExpectedPresses.length > 1) {\n\t\t\t\tpossibleMatches.set(sequence, remainingExpectedPresses.slice(1))\n\t\t\t} else {\n\t\t\t\tpossibleMatches.delete(sequence)\n\t\t\t\tcallback(event)\n\t\t\t}\n\t\t})\n\n\t\tif (timer) {\n\t\t\tclearTimeout(timer)\n\t\t}\n\n\t\ttimer = setTimeout(possibleMatches.clear.bind(possibleMatches), timeout)\n\t}\n}\n\n/**\n * Subscribes to keybindings.\n *\n * Returns an unsubscribe method.\n *\n * @example\n * ```js\n * import keybindings from \"../src/keybindings\"\n *\n * keybindings(window, {\n * \t\"Shift+d\": () => {\n * \t\talert(\"The 'Shift' and 'd' keys were pressed at the same time\")\n * \t},\n * \t\"y e e t\": () => {\n * \t\talert(\"The keys 'y', 'e', 'e', and 't' were pressed in order\")\n * \t},\n * \t\"$mod+d\": () => {\n * \t\talert(\"Either 'Control+d' or 'Meta+d' were pressed\")\n * \t},\n * })\n * ```\n */\nexport default function keybindings(\n\ttarget: Window | HTMLElement,\n\tkeyBindingMap: KeyBindingMap,\n\toptions: KeyBindingOptions = {},\n): () => void {\n\tlet event = options.event ?? DEFAULT_EVENT\n\tlet onKeyEvent = createKeybindingsHandler(keyBindingMap, options)\n\n\ttarget.addEventListener(event, onKeyEvent)\n\n\treturn () => {\n\t\ttarget.removeEventListener(event, onKeyEvent)\n\t}\n}\n"],"names":["KEYBINDING_MODIFIER_KEYS","MOD","navigator","test","platform","getModifierState","event","mod","createKeybindingsHandler","keyBindingMap","options","timeout","keyBindings","Object","keys","map","key","str","trim","split","press","mods","pop","possibleMatches","Map","timer","KeyboardEvent","forEach","keyBinding","sequence","callback","remainingExpectedPresses","get","toUpperCase","code","find","includes","match","length","set","slice","clearTimeout","setTimeout","clear","bind","target","onKeyEvent","addEventListener","removeEventListener"],"mappings":"AA4CA,IAAIA,EAA2B,CAAC,QAAS,OAAQ,MAAO,WAgBpDC,EACkB,iBAAdC,WACP,uBAAuBC,KAAKD,UAAUE,UACnC,OACA,UAMJ,SAASC,EAAiBC,EAAsBC,GAC/C,MAAyC,mBAA3BD,EAAMD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atC,EAAyBC,EAAeC,GAIzD,OAFAmC,EAAOE,iBAAiBzC,EAAOwC,cAG9BD,EAAOG,oBAAoB1C,EAAOwC"}
|
package/dist/tinykeys.modern.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
let e=["Shift","Meta","Alt","Control"],t="object"==typeof navigator&&/Mac|iPod|iPhone|iPad/.test(navigator.platform)?"Meta":"Control";function n(
|
|
1
|
+
let e=["Shift","Meta","Alt","Control"],t="object"==typeof navigator&&/Mac|iPod|iPhone|iPad/.test(navigator.platform)?"Meta":"Control";function n(e,t){return"function"==typeof e.getModifierState&&e.getModifierState(t)}function o(o,r={}){var i;let a=null!=(i=r.timeout)?i:1e3,l=Object.keys(o).map(e=>{return[(n=e,n.trim().split(" ").map(e=>{let n=e.split(/\b\+/),o=n.pop();return n=n.map(e=>"$mod"===e?t:e),[n,o]})),o[e]];var n}),u=new Map,d=null;return t=>{t instanceof KeyboardEvent&&(l.forEach(o=>{let r=o[0],i=o[1],a=u.get(r)||r;!function(t,o){return!(o[1].toUpperCase()!==t.key.toUpperCase()&&o[1]!==t.code||o[0].find(e=>!n(t,e))||e.find(e=>!o[0].includes(e)&&o[1]!==e&&n(t,e)))}(t,a[0])?n(t,t.key)||u.delete(r):a.length>1?u.set(r,a.slice(1)):(u.delete(r),i(t))}),d&&clearTimeout(d),d=setTimeout(u.clear.bind(u),a))}}function r(e,t,n={}){var r;let i=null!=(r=n.event)?r:"keydown",a=o(t,n);return e.addEventListener(i,a),()=>{e.removeEventListener(i,a)}}export default r;export{o as createKeybindingsHandler};
|
|
2
2
|
//# sourceMappingURL=tinykeys.modern.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tinykeys.modern.js","sources":["../src/tinykeys.ts"],"sourcesContent":["type KeyBindingPress = [string[], string]\n\n/**\n * A map of keybinding strings to event handlers.\n */\nexport interface KeyBindingMap {\n\t[keybinding: string]: (event: KeyboardEvent) => void\n}\n\n/**\n * Options to configure the behavior of keybindings.\n */\
|
|
1
|
+
{"version":3,"file":"tinykeys.modern.js","sources":["../src/tinykeys.ts"],"sourcesContent":["type KeyBindingPress = [string[], string]\n\n/**\n * A map of keybinding strings to event handlers.\n */\nexport interface KeyBindingMap {\n\t[keybinding: string]: (event: KeyboardEvent) => void\n}\n\nexport interface KeyBindingHandlerOptions {\n\t/**\n\t * Keybinding sequences will wait this long between key presses before\n\t * cancelling (default: 1000).\n\t *\n\t * **Note:** Setting this value too low (i.e. `300`) will be too fast for many\n\t * of your users.\n\t */\n\ttimeout?: number\n}\n\n/**\n * Options to configure the behavior of keybindings.\n */\nexport interface KeyBindingOptions extends KeyBindingHandlerOptions {\n\t/**\n\t * Key presses will listen to this event (default: \"keydown\").\n\t */\n\tevent?: \"keydown\" | \"keyup\"\n\n\t/**\n\t * Keybinding sequences will wait this long between key presses before\n\t * cancelling (default: 1000).\n\t *\n\t * **Note:** Setting this value too low (i.e. `300`) will be too fast for many\n\t * of your users.\n\t */\n\ttimeout?: number\n}\n\n/**\n * These are the modifier keys that change the meaning of keybindings.\n *\n * Note: Ignoring \"AltGraph\" because it is covered by the others.\n */\nlet KEYBINDING_MODIFIER_KEYS = [\"Shift\", \"Meta\", \"Alt\", \"Control\"]\n\n/**\n * Keybinding sequences should timeout if individual key presses are more than\n * 1s apart by default.\n */\nlet DEFAULT_TIMEOUT = 1000\n\n/**\n * Keybinding sequences should bind to this event by default.\n */\nlet DEFAULT_EVENT = \"keydown\"\n\n/**\n * An alias for creating platform-specific keybinding aliases.\n */\nlet MOD =\n\ttypeof navigator === \"object\" &&\n\t/Mac|iPod|iPhone|iPad/.test(navigator.platform)\n\t\t? \"Meta\"\n\t\t: \"Control\"\n\n/**\n * There's a bug in Chrome that causes event.getModifierState not to exist on\n * KeyboardEvent's for F1/F2/etc keys.\n */\nfunction getModifierState(event: KeyboardEvent, mod: string) {\n\treturn typeof event.getModifierState === \"function\"\n\t\t? event.getModifierState(mod)\n\t\t: false\n}\n\n/**\n * Parses a \"Key Binding String\" into its parts\n *\n * grammar = `<sequence>`\n * <sequence> = `<press> <press> <press> ...`\n * <press> = `<key>` or `<mods>+<key>`\n * <mods> = `<mod>+<mod>+...`\n */\nfunction parse(str: string): KeyBindingPress[] {\n\treturn str\n\t\t.trim()\n\t\t.split(\" \")\n\t\t.map(press => {\n\t\t\tlet mods = press.split(/\\b\\+/)\n\t\t\tlet key = mods.pop() as string\n\t\t\tmods = mods.map(mod => (mod === \"$mod\" ? MOD : mod))\n\t\t\treturn [mods, key]\n\t\t})\n}\n\n/**\n * This tells us if a series of events matches a key binding sequence either\n * partially or exactly.\n */\nfunction match(event: KeyboardEvent, press: KeyBindingPress): boolean {\n\t// prettier-ignore\n\treturn !(\n\t\t// Allow either the `event.key` or the `event.code`\n\t\t// MDN event.key: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key\n\t\t// MDN event.code: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code\n\t\t(\n\t\t\tpress[1].toUpperCase() !== event.key.toUpperCase() &&\n\t\t\tpress[1] !== event.code\n\t\t) ||\n\n\t\t// Ensure all the modifiers in the keybinding are pressed.\n\t\tpress[0].find(mod => {\n\t\t\treturn !getModifierState(event, mod)\n\t\t}) ||\n\n\t\t// KEYBINDING_MODIFIER_KEYS (Shift/Control/etc) change the meaning of a\n\t\t// keybinding. So if they are pressed but aren't part of the current\n\t\t// keybinding press, then we don't have a match.\n\t\tKEYBINDING_MODIFIER_KEYS.find(mod => {\n\t\t\treturn !press[0].includes(mod) && press[1] !== mod && getModifierState(event, mod)\n\t\t})\n\t)\n}\n\n/**\n * Creates an event listener for handling keybindings.\n *\n * @example\n * ```js\n * import { createKeybindingsHandler } from \"../src/keybindings\"\n *\n * let handler = createKeybindingsHandler({\n * \t\"Shift+d\": () => {\n * \t\talert(\"The 'Shift' and 'd' keys were pressed at the same time\")\n * \t},\n * \t\"y e e t\": () => {\n * \t\talert(\"The keys 'y', 'e', 'e', and 't' were pressed in order\")\n * \t},\n * \t\"$mod+d\": () => {\n * \t\talert(\"Either 'Control+d' or 'Meta+d' were pressed\")\n * \t},\n * })\n *\n * window.addEvenListener(\"keydown\", handler)\n * ```\n */\nexport function createKeybindingsHandler(\n\tkeyBindingMap: KeyBindingMap,\n\toptions: KeyBindingHandlerOptions = {},\n): EventListener {\n\tlet timeout = options.timeout ?? DEFAULT_TIMEOUT\n\n\tlet keyBindings = Object.keys(keyBindingMap).map(key => {\n\t\treturn [parse(key), keyBindingMap[key]] as const\n\t})\n\n\tlet possibleMatches = new Map<KeyBindingPress[], KeyBindingPress[]>()\n\tlet timer: number | null = null\n\n\treturn event => {\n\t\t// Ensure and stop any event that isn't a full keyboard event.\n\t\t// Autocomplete option navigation and selection would fire a instanceof Event,\n\t\t// instead of the expected KeyboardEvent\n\t\tif (!(event instanceof KeyboardEvent)) {\n\t\t\treturn\n\t\t}\n\n\t\tkeyBindings.forEach(keyBinding => {\n\t\t\tlet sequence = keyBinding[0]\n\t\t\tlet callback = keyBinding[1]\n\n\t\t\tlet prev = possibleMatches.get(sequence)\n\t\t\tlet remainingExpectedPresses = prev ? prev : sequence\n\t\t\tlet currentExpectedPress = remainingExpectedPresses[0]\n\n\t\t\tlet matches = match(event, currentExpectedPress)\n\n\t\t\tif (!matches) {\n\t\t\t\t// Modifier keydown events shouldn't break sequences\n\t\t\t\t// Note: This works because:\n\t\t\t\t// - non-modifiers will always return false\n\t\t\t\t// - if the current keypress is a modifier then it will return true when we check its state\n\t\t\t\t// MDN: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/getModifierState\n\t\t\t\tif (!getModifierState(event, event.key)) {\n\t\t\t\t\tpossibleMatches.delete(sequence)\n\t\t\t\t}\n\t\t\t} else if (remainingExpectedPresses.length > 1) {\n\t\t\t\tpossibleMatches.set(sequence, remainingExpectedPresses.slice(1))\n\t\t\t} else {\n\t\t\t\tpossibleMatches.delete(sequence)\n\t\t\t\tcallback(event)\n\t\t\t}\n\t\t})\n\n\t\tif (timer) {\n\t\t\tclearTimeout(timer)\n\t\t}\n\n\t\ttimer = setTimeout(possibleMatches.clear.bind(possibleMatches), timeout)\n\t}\n}\n\n/**\n * Subscribes to keybindings.\n *\n * Returns an unsubscribe method.\n *\n * @example\n * ```js\n * import keybindings from \"../src/keybindings\"\n *\n * keybindings(window, {\n * \t\"Shift+d\": () => {\n * \t\talert(\"The 'Shift' and 'd' keys were pressed at the same time\")\n * \t},\n * \t\"y e e t\": () => {\n * \t\talert(\"The keys 'y', 'e', 'e', and 't' were pressed in order\")\n * \t},\n * \t\"$mod+d\": () => {\n * \t\talert(\"Either 'Control+d' or 'Meta+d' were pressed\")\n * \t},\n * })\n * ```\n */\nexport default function keybindings(\n\ttarget: Window | HTMLElement,\n\tkeyBindingMap: KeyBindingMap,\n\toptions: KeyBindingOptions = {},\n): () => void {\n\tlet event = options.event ?? DEFAULT_EVENT\n\tlet onKeyEvent = createKeybindingsHandler(keyBindingMap, options)\n\n\ttarget.addEventListener(event, onKeyEvent)\n\n\treturn () => {\n\t\ttarget.removeEventListener(event, onKeyEvent)\n\t}\n}\n"],"names":["KEYBINDING_MODIFIER_KEYS","MOD","navigator","test","platform","getModifierState","event","mod","createKeybindingsHandler","keyBindingMap","options","timeout","keyBindings","Object","keys","map","key","str","trim","split","press","mods","pop","possibleMatches","Map","timer","KeyboardEvent","forEach","keyBinding","sequence","callback","remainingExpectedPresses","get","toUpperCase","code","find","includes","match","delete","length","set","slice","clearTimeout","setTimeout","clear","bind","keybindings","target","onKeyEvent","addEventListener","removeEventListener"],"mappings":"AA4CA,IAAIA,EAA2B,CAAC,QAAS,OAAQ,MAAO,WAgBpDC,EACkB,iBAAdC,WACP,uBAAuBC,KAAKD,UAAUE,UACnC,OACA,UAMJ,SAASC,EAAiBC,EAAsBC,GAC/C,MAAyC,mBAA3BD,EAAMD,kBACjBC,EAAMD,iBAAiBE,YA2EXC,EACfC,EACAC,EAAoC,UAEpC,IAAIC,WAAUD,EAAQC,WArGD,IAuGjB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|
|
|
1
|
-
var
|
|
1
|
+
var t=["Shift","Meta","Alt","Control"],e="object"==typeof navigator&&/Mac|iPod|iPhone|iPad/.test(navigator.platform)?"Meta":"Control";function n(t,e){return"function"==typeof t.getModifierState&&t.getModifierState(e)}function r(r,o){var i;void 0===o&&(o={});var a=null!=(i=o.timeout)?i:1e3,u=Object.keys(r).map(function(t){return[(n=t,n.trim().split(" ").map(function(t){var n=t.split(/\b\+/),r=n.pop();return[n=n.map(function(t){return"$mod"===t?e:t}),r]})),r[t]];var n}),f=new Map,c=null;return function(e){e instanceof KeyboardEvent&&(u.forEach(function(r){var o=r[0],i=r[1],a=f.get(o)||o;!function(e,r){return!(r[1].toUpperCase()!==e.key.toUpperCase()&&r[1]!==e.code||r[0].find(function(t){return!n(e,t)})||t.find(function(t){return!r[0].includes(t)&&r[1]!==t&&n(e,t)}))}(e,a[0])?n(e,e.key)||f.delete(o):a.length>1?f.set(o,a.slice(1)):(f.delete(o),i(e))}),c&&clearTimeout(c),c=setTimeout(f.clear.bind(f),a))}}function o(t,e,n){var o;void 0===n&&(n={});var i=null!=(o=n.event)?o:"keydown",a=r(e,n);return t.addEventListener(i,a),function(){t.removeEventListener(i,a)}}export default o;export{r as createKeybindingsHandler};
|
|
2
2
|
//# sourceMappingURL=tinykeys.module.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tinykeys.module.js","sources":["../src/tinykeys.ts"],"sourcesContent":["type KeyBindingPress = [string[], string]\n\n/**\n * A map of keybinding strings to event handlers.\n */\nexport interface KeyBindingMap {\n\t[keybinding: string]: (event: KeyboardEvent) => void\n}\n\n/**\n * Options to configure the behavior of keybindings.\n */\
|
|
1
|
+
{"version":3,"file":"tinykeys.module.js","sources":["../src/tinykeys.ts"],"sourcesContent":["type KeyBindingPress = [string[], string]\n\n/**\n * A map of keybinding strings to event handlers.\n */\nexport interface KeyBindingMap {\n\t[keybinding: string]: (event: KeyboardEvent) => void\n}\n\nexport interface KeyBindingHandlerOptions {\n\t/**\n\t * Keybinding sequences will wait this long between key presses before\n\t * cancelling (default: 1000).\n\t *\n\t * **Note:** Setting this value too low (i.e. `300`) will be too fast for many\n\t * of your users.\n\t */\n\ttimeout?: number\n}\n\n/**\n * Options to configure the behavior of keybindings.\n */\nexport interface KeyBindingOptions extends KeyBindingHandlerOptions {\n\t/**\n\t * Key presses will listen to this event (default: \"keydown\").\n\t */\n\tevent?: \"keydown\" | \"keyup\"\n\n\t/**\n\t * Keybinding sequences will wait this long between key presses before\n\t * cancelling (default: 1000).\n\t *\n\t * **Note:** Setting this value too low (i.e. `300`) will be too fast for many\n\t * of your users.\n\t */\n\ttimeout?: number\n}\n\n/**\n * These are the modifier keys that change the meaning of keybindings.\n *\n * Note: Ignoring \"AltGraph\" because it is covered by the others.\n */\nlet KEYBINDING_MODIFIER_KEYS = [\"Shift\", \"Meta\", \"Alt\", \"Control\"]\n\n/**\n * Keybinding sequences should timeout if individual key presses are more than\n * 1s apart by default.\n */\nlet DEFAULT_TIMEOUT = 1000\n\n/**\n * Keybinding sequences should bind to this event by default.\n */\nlet DEFAULT_EVENT = \"keydown\"\n\n/**\n * An alias for creating platform-specific keybinding aliases.\n */\nlet MOD =\n\ttypeof navigator === \"object\" &&\n\t/Mac|iPod|iPhone|iPad/.test(navigator.platform)\n\t\t? \"Meta\"\n\t\t: \"Control\"\n\n/**\n * There's a bug in Chrome that causes event.getModifierState not to exist on\n * KeyboardEvent's for F1/F2/etc keys.\n */\nfunction getModifierState(event: KeyboardEvent, mod: string) {\n\treturn typeof event.getModifierState === \"function\"\n\t\t? event.getModifierState(mod)\n\t\t: false\n}\n\n/**\n * Parses a \"Key Binding String\" into its parts\n *\n * grammar = `<sequence>`\n * <sequence> = `<press> <press> <press> ...`\n * <press> = `<key>` or `<mods>+<key>`\n * <mods> = `<mod>+<mod>+...`\n */\nfunction parse(str: string): KeyBindingPress[] {\n\treturn str\n\t\t.trim()\n\t\t.split(\" \")\n\t\t.map(press => {\n\t\t\tlet mods = press.split(/\\b\\+/)\n\t\t\tlet key = mods.pop() as string\n\t\t\tmods = mods.map(mod => (mod === \"$mod\" ? MOD : mod))\n\t\t\treturn [mods, key]\n\t\t})\n}\n\n/**\n * This tells us if a series of events matches a key binding sequence either\n * partially or exactly.\n */\nfunction match(event: KeyboardEvent, press: KeyBindingPress): boolean {\n\t// prettier-ignore\n\treturn !(\n\t\t// Allow either the `event.key` or the `event.code`\n\t\t// MDN event.key: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key\n\t\t// MDN event.code: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code\n\t\t(\n\t\t\tpress[1].toUpperCase() !== event.key.toUpperCase() &&\n\t\t\tpress[1] !== event.code\n\t\t) ||\n\n\t\t// Ensure all the modifiers in the keybinding are pressed.\n\t\tpress[0].find(mod => {\n\t\t\treturn !getModifierState(event, mod)\n\t\t}) ||\n\n\t\t// KEYBINDING_MODIFIER_KEYS (Shift/Control/etc) change the meaning of a\n\t\t// keybinding. So if they are pressed but aren't part of the current\n\t\t// keybinding press, then we don't have a match.\n\t\tKEYBINDING_MODIFIER_KEYS.find(mod => {\n\t\t\treturn !press[0].includes(mod) && press[1] !== mod && getModifierState(event, mod)\n\t\t})\n\t)\n}\n\n/**\n * Creates an event listener for handling keybindings.\n *\n * @example\n * ```js\n * import { createKeybindingsHandler } from \"../src/keybindings\"\n *\n * let handler = createKeybindingsHandler({\n * \t\"Shift+d\": () => {\n * \t\talert(\"The 'Shift' and 'd' keys were pressed at the same time\")\n * \t},\n * \t\"y e e t\": () => {\n * \t\talert(\"The keys 'y', 'e', 'e', and 't' were pressed in order\")\n * \t},\n * \t\"$mod+d\": () => {\n * \t\talert(\"Either 'Control+d' or 'Meta+d' were pressed\")\n * \t},\n * })\n *\n * window.addEvenListener(\"keydown\", handler)\n * ```\n */\nexport function createKeybindingsHandler(\n\tkeyBindingMap: KeyBindingMap,\n\toptions: KeyBindingHandlerOptions = {},\n): EventListener {\n\tlet timeout = options.timeout ?? DEFAULT_TIMEOUT\n\n\tlet keyBindings = Object.keys(keyBindingMap).map(key => {\n\t\treturn [parse(key), keyBindingMap[key]] as const\n\t})\n\n\tlet possibleMatches = new Map<KeyBindingPress[], KeyBindingPress[]>()\n\tlet timer: number | null = null\n\n\treturn event => {\n\t\t// Ensure and stop any event that isn't a full keyboard event.\n\t\t// Autocomplete option navigation and selection would fire a instanceof Event,\n\t\t// instead of the expected KeyboardEvent\n\t\tif (!(event instanceof KeyboardEvent)) {\n\t\t\treturn\n\t\t}\n\n\t\tkeyBindings.forEach(keyBinding => {\n\t\t\tlet sequence = keyBinding[0]\n\t\t\tlet callback = keyBinding[1]\n\n\t\t\tlet prev = possibleMatches.get(sequence)\n\t\t\tlet remainingExpectedPresses = prev ? prev : sequence\n\t\t\tlet currentExpectedPress = remainingExpectedPresses[0]\n\n\t\t\tlet matches = match(event, currentExpectedPress)\n\n\t\t\tif (!matches) {\n\t\t\t\t// Modifier keydown events shouldn't break sequences\n\t\t\t\t// Note: This works because:\n\t\t\t\t// - non-modifiers will always return false\n\t\t\t\t// - if the current keypress is a modifier then it will return true when we check its state\n\t\t\t\t// MDN: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/getModifierState\n\t\t\t\tif (!getModifierState(event, event.key)) {\n\t\t\t\t\tpossibleMatches.delete(sequence)\n\t\t\t\t}\n\t\t\t} else if (remainingExpectedPresses.length > 1) {\n\t\t\t\tpossibleMatches.set(sequence, remainingExpectedPresses.slice(1))\n\t\t\t} else {\n\t\t\t\tpossibleMatches.delete(sequence)\n\t\t\t\tcallback(event)\n\t\t\t}\n\t\t})\n\n\t\tif (timer) {\n\t\t\tclearTimeout(timer)\n\t\t}\n\n\t\ttimer = setTimeout(possibleMatches.clear.bind(possibleMatches), timeout)\n\t}\n}\n\n/**\n * Subscribes to keybindings.\n *\n * Returns an unsubscribe method.\n *\n * @example\n * ```js\n * import keybindings from \"../src/keybindings\"\n *\n * keybindings(window, {\n * \t\"Shift+d\": () => {\n * \t\talert(\"The 'Shift' and 'd' keys were pressed at the same time\")\n * \t},\n * \t\"y e e t\": () => {\n * \t\talert(\"The keys 'y', 'e', 'e', and 't' were pressed in order\")\n * \t},\n * \t\"$mod+d\": () => {\n * \t\talert(\"Either 'Control+d' or 'Meta+d' were pressed\")\n * \t},\n * })\n * ```\n */\nexport default function keybindings(\n\ttarget: Window | HTMLElement,\n\tkeyBindingMap: KeyBindingMap,\n\toptions: KeyBindingOptions = {},\n): () => void {\n\tlet event = options.event ?? DEFAULT_EVENT\n\tlet onKeyEvent = createKeybindingsHandler(keyBindingMap, options)\n\n\ttarget.addEventListener(event, onKeyEvent)\n\n\treturn () => {\n\t\ttarget.removeEventListener(event, onKeyEvent)\n\t}\n}\n"],"names":["KEYBINDING_MODIFIER_KEYS","MOD","navigator","test","platform","getModifierState","event","mod","createKeybindingsHandler","keyBindingMap","options","timeout","keyBindings","Object","keys","map","key","str","trim","split","press","mods","pop","possibleMatches","Map","timer","KeyboardEvent","forEach","keyBinding","sequence","callback","remainingExpectedPresses","get","toUpperCase","code","find","includes","match","length","set","slice","clearTimeout","setTimeout","clear","bind","keybindings","target","onKeyEvent","addEventListener","removeEventListener"],"mappings":"AA4CA,IAAIA,EAA2B,CAAC,QAAS,OAAQ,MAAO,WAgBpDC,EACkB,iBAAdC,WACP,uBAAuBC,KAAKD,UAAUE,UACnC,OACA,UAMJ,SAASC,EAAiBC,EAAsBC,GAC/C,MAAyC,mBAA3BD,EAAMD,kBACjBC,EAAMD,iBAAiBE,YA2EXC,EACfC,EACAC,kBAAAA,IAAAA,EAAoC,IAEpC,IAAIC,WAAUD,EAAQC,WArGD,IAuGjBC,EAAcC,OAAOC,KAAKL,GAAeM,IAAI,SAAAC,GAChD,MAAO,EAtEMC,EAsECD,EArERC,EACLC,OACAC,MAAM,KACNJ,IAAI,SAAAK,GACJ,IAAIC,EAAOD,EAAMD,MAAM,QACnBH,EAAMK,EAAKC,MAEf,MAAO,CADPD,EAAOA,EAAKN,IAAI,SAAAR,SAAgB,SAARA,EAAiBN,EAAMM,IACjCS,MA8DKP,EAAcO,IAtEpC,IAAeC,IAyEVM,EAAkB,IAAIC,IACtBC,EAAuB,KAE3B,gBAAOnB,GAIAA,aAAiBoB,gBAIvBd,EAAYe,QAAQ,SAAAC,GACnB,IAAIC,EAAWD,EAAW,GACtBE,EAAWF,EAAW,GAGtBG,EADOR,EAAgBS,IAAIH,IACcA,GAzEhD,SAAevB,EAAsBc,GAEpC,QAKEA,EAAM,GAAGa,gBAAkB3B,EAAMU,IAAIiB,eACrCb,EAAM,KAAOd,EAAM4B,MAIpBd,EAAM,GAAGe,KAAK,SAAA5B,GACb,OAAQF,EAAiBC,EAAOC,MAMjCP,EAAyBmC,KAAK,SAAA5B,GAC7B,OAAQa,EAAM,GAAGgB,SAAS7B,IAAQa,EAAM,KAAOb,GAAOF,EAAiBC,EAAOC,MAwDhE8B,CAAM/B,EAFOyB,EAAyB,IAU9C1B,EAAiBC,EAAOA,EAAMU,MAClCO,SAAuBM,GAEdE,EAAyBO,OAAS,EAC5Cf,EAAgBgB,IAAIV,EAAUE,EAAyBS,MAAM,KAE7DjB,SAAuBM,GACvBC,EAASxB,MAIPmB,GACHgB,aAAahB,GAGdA,EAAQiB,WAAWnB,EAAgBoB,MAAMC,KAAKrB,GAAkBZ,cA0B1CkC,EACvBC,EACArC,EACAC,kBAAAA,IAAAA,EAA6B,IAE7B,IAAIJ,WAAQI,EAAQJ,SA/KD,UAgLfyC,EAAavC,EAAyBC,EAAeC,GAIzD,OAFAoC,EAAOE,iBAAiB1C,EAAOyC,cAG9BD,EAAOG,oBAAoB3C,EAAOyC"}
|
package/dist/tinykeys.umd.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e||self).tinykeys={})}(this,function(e){var t=["Shift","Meta","Alt","Control"],n="object"==typeof navigator&&/Mac|iPod|iPhone|iPad/.test(navigator.platform)?"Meta":"Control";function o(e,t){return"function"==typeof e.getModifierState&&e.getModifierState(t)}function i(e,i){var r;void 0===i&&(i={});var a=null!=(r=i.timeout)?r:1e3,f=Object.keys(e).map(function(t){return[(o=t,o.trim().split(" ").map(function(e){var t=e.split(/\b\+/),o=t.pop();return[t=t.map(function(e){return"$mod"===e?n:e}),o]})),e[t]];var o}),u=new Map,d=null;return function(e){e instanceof KeyboardEvent&&(f.forEach(function(n){var i=n[0],r=n[1],a=u.get(i)||i;!function(e,n){return!(n[1].toUpperCase()!==e.key.toUpperCase()&&n[1]!==e.code||n[0].find(function(t){return!o(e,t)})||t.find(function(t){return!n[0].includes(t)&&n[1]!==t&&o(e,t)}))}(e,a[0])?o(e,e.key)||u.delete(i):a.length>1?u.set(i,a.slice(1)):(u.delete(i),r(e))}),d&&clearTimeout(d),d=setTimeout(u.clear.bind(u),a))}}e.createKeybindingsHandler=i,e.default=function(e,t,n){var o;void 0===n&&(n={});var r=null!=(o=n.event)?o:"keydown",a=i(t,n);return e.addEventListener(r,a),function(){e.removeEventListener(r,a)}}});
|
|
2
2
|
//# sourceMappingURL=tinykeys.umd.js.map
|
package/dist/tinykeys.umd.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tinykeys.umd.js","sources":["../src/tinykeys.ts"],"sourcesContent":["type KeyBindingPress = [string[], string]\n\n/**\n * A map of keybinding strings to event handlers.\n */\nexport interface KeyBindingMap {\n\t[keybinding: string]: (event: KeyboardEvent) => void\n}\n\n/**\n * Options to configure the behavior of keybindings.\n */\
|
|
1
|
+
{"version":3,"file":"tinykeys.umd.js","sources":["../src/tinykeys.ts"],"sourcesContent":["type KeyBindingPress = [string[], string]\n\n/**\n * A map of keybinding strings to event handlers.\n */\nexport interface KeyBindingMap {\n\t[keybinding: string]: (event: KeyboardEvent) => void\n}\n\nexport interface KeyBindingHandlerOptions {\n\t/**\n\t * Keybinding sequences will wait this long between key presses before\n\t * cancelling (default: 1000).\n\t *\n\t * **Note:** Setting this value too low (i.e. `300`) will be too fast for many\n\t * of your users.\n\t */\n\ttimeout?: number\n}\n\n/**\n * Options to configure the behavior of keybindings.\n */\nexport interface KeyBindingOptions extends KeyBindingHandlerOptions {\n\t/**\n\t * Key presses will listen to this event (default: \"keydown\").\n\t */\n\tevent?: \"keydown\" | \"keyup\"\n\n\t/**\n\t * Keybinding sequences will wait this long between key presses before\n\t * cancelling (default: 1000).\n\t *\n\t * **Note:** Setting this value too low (i.e. `300`) will be too fast for many\n\t * of your users.\n\t */\n\ttimeout?: number\n}\n\n/**\n * These are the modifier keys that change the meaning of keybindings.\n *\n * Note: Ignoring \"AltGraph\" because it is covered by the others.\n */\nlet KEYBINDING_MODIFIER_KEYS = [\"Shift\", \"Meta\", \"Alt\", \"Control\"]\n\n/**\n * Keybinding sequences should timeout if individual key presses are more than\n * 1s apart by default.\n */\nlet DEFAULT_TIMEOUT = 1000\n\n/**\n * Keybinding sequences should bind to this event by default.\n */\nlet DEFAULT_EVENT = \"keydown\"\n\n/**\n * An alias for creating platform-specific keybinding aliases.\n */\nlet MOD =\n\ttypeof navigator === \"object\" &&\n\t/Mac|iPod|iPhone|iPad/.test(navigator.platform)\n\t\t? \"Meta\"\n\t\t: \"Control\"\n\n/**\n * There's a bug in Chrome that causes event.getModifierState not to exist on\n * KeyboardEvent's for F1/F2/etc keys.\n */\nfunction getModifierState(event: KeyboardEvent, mod: string) {\n\treturn typeof event.getModifierState === \"function\"\n\t\t? event.getModifierState(mod)\n\t\t: false\n}\n\n/**\n * Parses a \"Key Binding String\" into its parts\n *\n * grammar = `<sequence>`\n * <sequence> = `<press> <press> <press> ...`\n * <press> = `<key>` or `<mods>+<key>`\n * <mods> = `<mod>+<mod>+...`\n */\nfunction parse(str: string): KeyBindingPress[] {\n\treturn str\n\t\t.trim()\n\t\t.split(\" \")\n\t\t.map(press => {\n\t\t\tlet mods = press.split(/\\b\\+/)\n\t\t\tlet key = mods.pop() as string\n\t\t\tmods = mods.map(mod => (mod === \"$mod\" ? MOD : mod))\n\t\t\treturn [mods, key]\n\t\t})\n}\n\n/**\n * This tells us if a series of events matches a key binding sequence either\n * partially or exactly.\n */\nfunction match(event: KeyboardEvent, press: KeyBindingPress): boolean {\n\t// prettier-ignore\n\treturn !(\n\t\t// Allow either the `event.key` or the `event.code`\n\t\t// MDN event.key: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key\n\t\t// MDN event.code: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code\n\t\t(\n\t\t\tpress[1].toUpperCase() !== event.key.toUpperCase() &&\n\t\t\tpress[1] !== event.code\n\t\t) ||\n\n\t\t// Ensure all the modifiers in the keybinding are pressed.\n\t\tpress[0].find(mod => {\n\t\t\treturn !getModifierState(event, mod)\n\t\t}) ||\n\n\t\t// KEYBINDING_MODIFIER_KEYS (Shift/Control/etc) change the meaning of a\n\t\t// keybinding. So if they are pressed but aren't part of the current\n\t\t// keybinding press, then we don't have a match.\n\t\tKEYBINDING_MODIFIER_KEYS.find(mod => {\n\t\t\treturn !press[0].includes(mod) && press[1] !== mod && getModifierState(event, mod)\n\t\t})\n\t)\n}\n\n/**\n * Creates an event listener for handling keybindings.\n *\n * @example\n * ```js\n * import { createKeybindingsHandler } from \"../src/keybindings\"\n *\n * let handler = createKeybindingsHandler({\n * \t\"Shift+d\": () => {\n * \t\talert(\"The 'Shift' and 'd' keys were pressed at the same time\")\n * \t},\n * \t\"y e e t\": () => {\n * \t\talert(\"The keys 'y', 'e', 'e', and 't' were pressed in order\")\n * \t},\n * \t\"$mod+d\": () => {\n * \t\talert(\"Either 'Control+d' or 'Meta+d' were pressed\")\n * \t},\n * })\n *\n * window.addEvenListener(\"keydown\", handler)\n * ```\n */\nexport function createKeybindingsHandler(\n\tkeyBindingMap: KeyBindingMap,\n\toptions: KeyBindingHandlerOptions = {},\n): EventListener {\n\tlet timeout = options.timeout ?? DEFAULT_TIMEOUT\n\n\tlet keyBindings = Object.keys(keyBindingMap).map(key => {\n\t\treturn [parse(key), keyBindingMap[key]] as const\n\t})\n\n\tlet possibleMatches = new Map<KeyBindingPress[], KeyBindingPress[]>()\n\tlet timer: number | null = null\n\n\treturn event => {\n\t\t// Ensure and stop any event that isn't a full keyboard event.\n\t\t// Autocomplete option navigation and selection would fire a instanceof Event,\n\t\t// instead of the expected KeyboardEvent\n\t\tif (!(event instanceof KeyboardEvent)) {\n\t\t\treturn\n\t\t}\n\n\t\tkeyBindings.forEach(keyBinding => {\n\t\t\tlet sequence = keyBinding[0]\n\t\t\tlet callback = keyBinding[1]\n\n\t\t\tlet prev = possibleMatches.get(sequence)\n\t\t\tlet remainingExpectedPresses = prev ? prev : sequence\n\t\t\tlet currentExpectedPress = remainingExpectedPresses[0]\n\n\t\t\tlet matches = match(event, currentExpectedPress)\n\n\t\t\tif (!matches) {\n\t\t\t\t// Modifier keydown events shouldn't break sequences\n\t\t\t\t// Note: This works because:\n\t\t\t\t// - non-modifiers will always return false\n\t\t\t\t// - if the current keypress is a modifier then it will return true when we check its state\n\t\t\t\t// MDN: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/getModifierState\n\t\t\t\tif (!getModifierState(event, event.key)) {\n\t\t\t\t\tpossibleMatches.delete(sequence)\n\t\t\t\t}\n\t\t\t} else if (remainingExpectedPresses.length > 1) {\n\t\t\t\tpossibleMatches.set(sequence, remainingExpectedPresses.slice(1))\n\t\t\t} else {\n\t\t\t\tpossibleMatches.delete(sequence)\n\t\t\t\tcallback(event)\n\t\t\t}\n\t\t})\n\n\t\tif (timer) {\n\t\t\tclearTimeout(timer)\n\t\t}\n\n\t\ttimer = setTimeout(possibleMatches.clear.bind(possibleMatches), timeout)\n\t}\n}\n\n/**\n * Subscribes to keybindings.\n *\n * Returns an unsubscribe method.\n *\n * @example\n * ```js\n * import keybindings from \"../src/keybindings\"\n *\n * keybindings(window, {\n * \t\"Shift+d\": () => {\n * \t\talert(\"The 'Shift' and 'd' keys were pressed at the same time\")\n * \t},\n * \t\"y e e t\": () => {\n * \t\talert(\"The keys 'y', 'e', 'e', and 't' were pressed in order\")\n * \t},\n * \t\"$mod+d\": () => {\n * \t\talert(\"Either 'Control+d' or 'Meta+d' were pressed\")\n * \t},\n * })\n * ```\n */\nexport default function keybindings(\n\ttarget: Window | HTMLElement,\n\tkeyBindingMap: KeyBindingMap,\n\toptions: KeyBindingOptions = {},\n): () => void {\n\tlet event = options.event ?? DEFAULT_EVENT\n\tlet onKeyEvent = createKeybindingsHandler(keyBindingMap, options)\n\n\ttarget.addEventListener(event, onKeyEvent)\n\n\treturn () => {\n\t\ttarget.removeEventListener(event, onKeyEvent)\n\t}\n}\n"],"names":["KEYBINDING_MODIFIER_KEYS","MOD","navigator","test","platform","getModifierState","event","mod","createKeybindingsHandler","keyBindingMap","options","timeout","keyBindings","Object","keys","map","key","str","trim","split","press","mods","pop","possibleMatches","Map","timer","KeyboardEvent","forEach","keyBinding","sequence","callback","remainingExpectedPresses","get","toUpperCase","code","find","includes","match","length","set","slice","clearTimeout","setTimeout","clear","bind","target","onKeyEvent","addEventListener","removeEventListener"],"mappings":"kOA4CA,IAAIA,EAA2B,CAAC,QAAS,OAAQ,MAAO,WAgBpDC,EACkB,iBAAdC,WACP,uBAAuBC,KAAKD,UAAUE,UACnC,OACA,UAMJ,SAASC,EAAiBC,EAAsBC,GAC/C,MAAyC,mBAA3BD,EAAMD,kBACjBC,EAAMD,iBAAiBE,YA2EXC,EACfC,EACAC,kBAAAA,IAAAA,EAAoC,IAEpC,IAAIC,WAAUD,EAAQC,WArGD,IAuGjBC,EAAcC,OAAOC,KAAKL,GAAeM,IAAI,SAAAC,GAChD,MAAO,EAtEMC,EAsECD,EArERC,EACLC,OACAC,MAAM,KACNJ,IAAI,SAAAK,GACJ,IAAIC,EAAOD,EAAMD,MAAM,QACnBH,EAAMK,EAAKC,MAEf,MAAO,CADPD,EAAOA,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