@tanstack/hotkeys 0.9.0 → 0.10.1
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/dist/_event-target.js +1 -2
- package/dist/_keyboard-event.js +1 -2
- package/dist/_match.js +1 -2
- package/dist/_named-keys.d.ts +3 -5
- package/dist/_named-keys.js +1 -2
- package/dist/_recorder-chord.js +1 -2
- package/dist/_recording-guard.js +1 -2
- package/dist/_registration.js +1 -2
- package/dist/conflicts.d.ts +4 -7
- package/dist/conflicts.js +1 -2
- package/dist/constants.d.ts +14 -17
- package/dist/constants.js +8 -9
- package/dist/display-labels.d.ts +7 -10
- package/dist/display-labels.js +1 -2
- package/dist/format.d.ts +12 -14
- package/dist/format.js +17 -7
- package/dist/hint.d.ts +3 -6
- package/dist/hint.js +1 -2
- package/dist/hotkey-manager.d.ts +8 -10
- package/dist/hotkey-manager.js +21 -3
- package/dist/hotkey-recorder.d.ts +4 -7
- package/dist/hotkey-recorder.js +9 -6
- package/dist/hotkey-sequence-recorder.d.ts +5 -8
- package/dist/hotkey-sequence-recorder.js +6 -7
- package/dist/hotkey.types.d.ts +15 -18
- package/dist/key-state-tracker.d.ts +4 -7
- package/dist/key-state-tracker.js +6 -3
- package/dist/key.types.d.ts +17 -20
- package/dist/match.d.ts +8 -11
- package/dist/match.js +1 -2
- package/dist/parse.d.ts +11 -14
- package/dist/parse.js +5 -4
- package/dist/platform.d.ts +3 -6
- package/dist/platform.js +1 -2
- package/dist/recorder-options.d.ts +6 -9
- package/dist/sequence-manager.d.ts +11 -14
- package/dist/sequence-manager.js +12 -7
- package/dist/validate.d.ts +5 -8
- package/dist/validate.js +1 -2
- package/package.json +8 -13
- package/dist/_event-target.cjs +0 -73
- package/dist/_event-target.cjs.map +0 -1
- package/dist/_event-target.js.map +0 -1
- package/dist/_keyboard-event.cjs +0 -83
- package/dist/_keyboard-event.cjs.map +0 -1
- package/dist/_keyboard-event.js.map +0 -1
- package/dist/_match.cjs +0 -49
- package/dist/_match.cjs.map +0 -1
- package/dist/_match.js.map +0 -1
- package/dist/_named-keys.cjs +0 -68
- package/dist/_named-keys.cjs.map +0 -1
- package/dist/_named-keys.d.cts +0 -8
- package/dist/_named-keys.js.map +0 -1
- package/dist/_recorder-chord.cjs +0 -44
- package/dist/_recorder-chord.cjs.map +0 -1
- package/dist/_recorder-chord.js.map +0 -1
- package/dist/_recording-guard.cjs +0 -59
- package/dist/_recording-guard.cjs.map +0 -1
- package/dist/_recording-guard.js.map +0 -1
- package/dist/_registration.cjs +0 -54
- package/dist/_registration.cjs.map +0 -1
- package/dist/_registration.js.map +0 -1
- package/dist/conflicts.cjs +0 -55
- package/dist/conflicts.cjs.map +0 -1
- package/dist/conflicts.d.cts +0 -39
- package/dist/conflicts.js.map +0 -1
- package/dist/constants.cjs +0 -410
- package/dist/constants.cjs.map +0 -1
- package/dist/constants.d.cts +0 -165
- package/dist/constants.js.map +0 -1
- package/dist/display-labels.cjs +0 -119
- package/dist/display-labels.cjs.map +0 -1
- package/dist/display-labels.d.cts +0 -93
- package/dist/display-labels.js.map +0 -1
- package/dist/format.cjs +0 -85
- package/dist/format.cjs.map +0 -1
- package/dist/format.d.cts +0 -99
- package/dist/format.js.map +0 -1
- package/dist/hint.cjs +0 -24
- package/dist/hint.cjs.map +0 -1
- package/dist/hint.d.cts +0 -23
- package/dist/hint.js.map +0 -1
- package/dist/hotkey-manager.cjs +0 -414
- package/dist/hotkey-manager.cjs.map +0 -1
- package/dist/hotkey-manager.d.cts +0 -234
- package/dist/hotkey-manager.js.map +0 -1
- package/dist/hotkey-recorder.cjs +0 -235
- package/dist/hotkey-recorder.cjs.map +0 -1
- package/dist/hotkey-recorder.d.cts +0 -119
- package/dist/hotkey-recorder.js.map +0 -1
- package/dist/hotkey-sequence-recorder.cjs +0 -255
- package/dist/hotkey-sequence-recorder.cjs.map +0 -1
- package/dist/hotkey-sequence-recorder.d.cts +0 -86
- package/dist/hotkey-sequence-recorder.js.map +0 -1
- package/dist/hotkey.types.d.cts +0 -236
- package/dist/index.cjs +0 -71
- package/dist/index.d.cts +0 -18
- package/dist/key-state-tracker.cjs +0 -197
- package/dist/key-state-tracker.cjs.map +0 -1
- package/dist/key-state-tracker.d.cts +0 -107
- package/dist/key-state-tracker.js.map +0 -1
- package/dist/key.types.d.cts +0 -82
- package/dist/match.cjs +0 -144
- package/dist/match.cjs.map +0 -1
- package/dist/match.d.cts +0 -101
- package/dist/match.js.map +0 -1
- package/dist/parse.cjs +0 -245
- package/dist/parse.cjs.map +0 -1
- package/dist/parse.d.cts +0 -134
- package/dist/parse.js.map +0 -1
- package/dist/platform.cjs +0 -55
- package/dist/platform.cjs.map +0 -1
- package/dist/platform.d.cts +0 -44
- package/dist/platform.js.map +0 -1
- package/dist/recorder-options.d.cts +0 -34
- package/dist/sequence-manager.cjs +0 -441
- package/dist/sequence-manager.cjs.map +0 -1
- package/dist/sequence-manager.d.cts +0 -172
- package/dist/sequence-manager.js.map +0 -1
- package/dist/validate.cjs +0 -112
- package/dist/validate.cjs.map +0 -1
- package/dist/validate.d.cts +0 -67
- package/dist/validate.js.map +0 -1
- package/src/_event-target.ts +0 -157
- package/src/_keyboard-event.ts +0 -101
- package/src/_match.ts +0 -96
- package/src/_named-keys.ts +0 -62
- package/src/_recorder-chord.ts +0 -76
- package/src/_recording-guard.ts +0 -63
- package/src/_registration.ts +0 -79
- package/src/conflicts.ts +0 -125
- package/src/constants.ts +0 -455
- package/src/display-labels.ts +0 -123
- package/src/format.ts +0 -201
- package/src/hint.ts +0 -42
- package/src/hotkey-manager.ts +0 -814
- package/src/hotkey-recorder.ts +0 -348
- package/src/hotkey-sequence-recorder.ts +0 -410
- package/src/hotkey.types.ts +0 -269
- package/src/index.ts +0 -17
- package/src/key-state-tracker.ts +0 -261
- package/src/key.types.ts +0 -268
- package/src/match.ts +0 -210
- package/src/parse.ts +0 -369
- package/src/platform.ts +0 -66
- package/src/recorder-options.ts +0 -34
- package/src/sequence-manager.ts +0 -769
- package/src/validate.ts +0 -179
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"key-state-tracker.js","names":["#instance","#setupListeners","#keydownListener","#heldEntries","#syncState","#keyupListener","#blurListener","#removeListeners"],"sources":["../src/key-state-tracker.ts"],"sourcesContent":["import { Store } from '@tanstack/store'\nimport { MODIFIER_KEYS, normalizeKeyName } from './constants'\n\n/**\n * State interface for the KeyStateTracker.\n */\nexport interface KeyStateTrackerState {\n /**\n * Array of currently held key names (normalized, e.g. \"Control\", \"A\").\n */\n heldKeys: Array<string>\n /**\n * Map from normalized key name to the physical `event.code` (e.g. \"KeyA\", \"ShiftLeft\").\n * Useful for debugging which physical key was pressed.\n */\n heldCodes: Record<string, string>\n}\n\n/**\n * Returns the default state for KeyStateTracker.\n */\nfunction getDefaultKeyStateTrackerState(): KeyStateTrackerState {\n return {\n heldKeys: [],\n heldCodes: {},\n }\n}\n\n/**\n * Singleton tracker for currently held keyboard keys.\n *\n * This class maintains a list of all keys currently being pressed,\n * which is useful for:\n * - Displaying currently held keys to users\n * - Custom shortcut recording for rebinding\n * - Complex chord detection\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - State can be accessed via `tracker.store.state` when using the class directly\n * - When using framework adapters (React), use `useHeldKeys` and `useHeldKeyCodes` hooks for reactive state\n *\n * @example\n * ```ts\n * const tracker = KeyStateTracker.getInstance()\n *\n * // Access state directly\n * console.log(tracker.store.state.heldKeys) // ['Control', 'Shift']\n *\n * // Subscribe to changes with TanStack Store\n * const unsubscribe = tracker.store.subscribe(() => {\n * console.log('Currently held:', tracker.store.state.heldKeys)\n * })\n *\n * // Check current state\n * console.log(tracker.getHeldKeys()) // ['Control', 'Shift']\n * console.log(tracker.isKeyHeld('Control')) // true\n *\n * // Cleanup\n * unsubscribe()\n * ```\n */\nexport class KeyStateTracker {\n static #instance: KeyStateTracker | null = null\n\n /**\n * The TanStack Store instance containing the tracker state.\n * Use this to subscribe to state changes or access current state.\n */\n readonly store: Store<KeyStateTrackerState> = new Store(\n getDefaultKeyStateTrackerState(),\n )\n\n #heldEntries: Map<string, { key: string; code: string }> = new Map()\n #keydownListener: ((event: KeyboardEvent) => void) | null = null\n #keyupListener: ((event: KeyboardEvent) => void) | null = null\n #blurListener: (() => void) | null = null\n\n private constructor() {\n this.#setupListeners()\n }\n\n /**\n * Gets the singleton instance of KeyStateTracker.\n */\n static getInstance(): KeyStateTracker {\n if (!KeyStateTracker.#instance) {\n KeyStateTracker.#instance = new KeyStateTracker()\n }\n return KeyStateTracker.#instance\n }\n\n /**\n * Resets the singleton instance. Useful for testing.\n */\n static resetInstance(): void {\n if (KeyStateTracker.#instance) {\n KeyStateTracker.#instance.destroy()\n KeyStateTracker.#instance = null\n }\n }\n\n /**\n * Sets up the keyboard event listeners.\n */\n #setupListeners(): void {\n if (typeof document === 'undefined') {\n return // SSR safety\n }\n\n this.#keydownListener = (event: KeyboardEvent) => {\n const key = normalizeKeyName(event.key)\n const identity = event.code || `key:${key}`\n if (!this.#heldEntries.has(identity)) {\n this.#heldEntries.set(identity, { key, code: event.code })\n this.#syncState()\n }\n }\n\n this.#keyupListener = (event: KeyboardEvent) => {\n const key = normalizeKeyName(event.key)\n const identity = event.code || `key:${key}`\n this.#heldEntries.delete(identity)\n\n // Code-less keyup events can only be paired by their logical key.\n if (!event.code) {\n for (const [entryIdentity, entry] of this.#heldEntries) {\n if (entry.key === key) this.#heldEntries.delete(entryIdentity)\n }\n }\n\n // When a modifier key is released, clear any non-modifier keys still\n // marked as held. On macOS, the OS intercepts modifier+key combos\n // (e.g. Cmd+S) and swallows the keyup event for the non-modifier key,\n // leaving it permanently stuck in the held set.\n if (MODIFIER_KEYS.has(key)) {\n for (const [entryIdentity, entry] of this.#heldEntries) {\n if (!MODIFIER_KEYS.has(entry.key)) {\n this.#heldEntries.delete(entryIdentity)\n }\n }\n }\n\n this.#syncState()\n }\n\n // Clear all keys when window loses focus (keys might be released while not focused)\n this.#blurListener = () => {\n if (this.#heldEntries.size > 0) {\n this.#heldEntries.clear()\n this.#syncState()\n }\n }\n\n document.addEventListener('keydown', this.#keydownListener, true)\n document.addEventListener('keyup', this.#keyupListener, true)\n window.addEventListener('blur', this.#blurListener)\n }\n\n /**\n * Syncs the internal Set to the Store state.\n */\n #syncState(): void {\n const heldKeys = Array.from(\n new Set(Array.from(this.#heldEntries.values(), (entry) => entry.key)),\n )\n const heldCodes = Object.fromEntries(\n Array.from(this.#heldEntries.values(), (entry) => [\n entry.key,\n entry.code,\n ]),\n )\n this.store.setState(() => ({\n heldKeys,\n heldCodes,\n }))\n }\n\n /**\n * Removes the keyboard event listeners.\n */\n #removeListeners(): void {\n if (typeof document === 'undefined') {\n return\n }\n\n if (this.#keydownListener) {\n document.removeEventListener('keydown', this.#keydownListener, true)\n this.#keydownListener = null\n }\n\n if (this.#keyupListener) {\n document.removeEventListener('keyup', this.#keyupListener, true)\n this.#keyupListener = null\n }\n\n if (this.#blurListener) {\n window.removeEventListener('blur', this.#blurListener)\n this.#blurListener = null\n }\n }\n\n /**\n * Gets an array of currently held key names.\n *\n * @returns Array of key names currently being pressed\n */\n getHeldKeys(): Array<string> {\n return this.store.state.heldKeys\n }\n\n /**\n * Checks if a specific key is currently being held.\n *\n * @param key - The key name to check (case-insensitive)\n * @returns True if the key is currently held\n */\n isKeyHeld(key: string): boolean {\n const normalizedKey = normalizeKeyName(key)\n return Array.from(this.#heldEntries.values()).some(\n (entry) => entry.key === normalizedKey,\n )\n }\n\n /**\n * Checks if any of the given keys are currently held.\n *\n * @param keys - Array of key names to check\n * @returns True if any of the keys are currently held\n */\n isAnyKeyHeld(keys: Array<string>): boolean {\n return keys.some((key) => this.isKeyHeld(key))\n }\n\n /**\n * Checks if all of the given keys are currently held.\n *\n * @param keys - Array of key names to check\n * @returns True if all of the keys are currently held\n */\n areAllKeysHeld(keys: Array<string>): boolean {\n return keys.every((key) => this.isKeyHeld(key))\n }\n\n /**\n * Destroys the tracker and removes all listeners.\n */\n destroy(): void {\n this.#removeListeners()\n this.#heldEntries.clear()\n this.store.setState(() => getDefaultKeyStateTrackerState())\n }\n}\n\n/**\n * Gets the singleton KeyStateTracker instance.\n * Convenience function for accessing the tracker.\n */\nexport function getKeyStateTracker(): KeyStateTracker {\n return KeyStateTracker.getInstance()\n}\n"],"mappings":";;;;;;;AAqBA,SAAS,iCAAuD;AAC9D,QAAO;EACL,UAAU,EAAE;EACZ,WAAW,EAAE;EACd;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCH,IAAa,kBAAb,MAAa,gBAAgB;CAC3B,QAAOA,WAAoC;CAU3C,+BAA2D,IAAI,KAAK;CACpE,mBAA4D;CAC5D,iBAA0D;CAC1D,gBAAqC;CAErC,AAAQ,cAAc;eATwB,IAAI,MAChD,gCAAgC,CACjC;AAQC,QAAKC,gBAAiB;;;;;CAMxB,OAAO,cAA+B;AACpC,MAAI,CAAC,iBAAgBD,SACnB,kBAAgBA,WAAY,IAAI,iBAAiB;AAEnD,SAAO,iBAAgBA;;;;;CAMzB,OAAO,gBAAsB;AAC3B,MAAI,iBAAgBA,UAAW;AAC7B,oBAAgBA,SAAU,SAAS;AACnC,oBAAgBA,WAAY;;;;;;CAOhC,kBAAwB;AACtB,MAAI,OAAO,aAAa,YACtB;AAGF,QAAKE,mBAAoB,UAAyB;GAChD,MAAM,MAAM,iBAAiB,MAAM,IAAI;GACvC,MAAM,WAAW,MAAM,QAAQ,OAAO;AACtC,OAAI,CAAC,MAAKC,YAAa,IAAI,SAAS,EAAE;AACpC,UAAKA,YAAa,IAAI,UAAU;KAAE;KAAK,MAAM,MAAM;KAAM,CAAC;AAC1D,UAAKC,WAAY;;;AAIrB,QAAKC,iBAAkB,UAAyB;GAC9C,MAAM,MAAM,iBAAiB,MAAM,IAAI;GACvC,MAAM,WAAW,MAAM,QAAQ,OAAO;AACtC,SAAKF,YAAa,OAAO,SAAS;AAGlC,OAAI,CAAC,MAAM,MACT;SAAK,MAAM,CAAC,eAAe,UAAU,MAAKA,YACxC,KAAI,MAAM,QAAQ,IAAK,OAAKA,YAAa,OAAO,cAAc;;AAQlE,OAAI,cAAc,IAAI,IAAI,EACxB;SAAK,MAAM,CAAC,eAAe,UAAU,MAAKA,YACxC,KAAI,CAAC,cAAc,IAAI,MAAM,IAAI,CAC/B,OAAKA,YAAa,OAAO,cAAc;;AAK7C,SAAKC,WAAY;;AAInB,QAAKE,qBAAsB;AACzB,OAAI,MAAKH,YAAa,OAAO,GAAG;AAC9B,UAAKA,YAAa,OAAO;AACzB,UAAKC,WAAY;;;AAIrB,WAAS,iBAAiB,WAAW,MAAKF,iBAAkB,KAAK;AACjE,WAAS,iBAAiB,SAAS,MAAKG,eAAgB,KAAK;AAC7D,SAAO,iBAAiB,QAAQ,MAAKC,aAAc;;;;;CAMrD,aAAmB;EACjB,MAAM,WAAW,MAAM,KACrB,IAAI,IAAI,MAAM,KAAK,MAAKH,YAAa,QAAQ,GAAG,UAAU,MAAM,IAAI,CAAC,CACtE;EACD,MAAM,YAAY,OAAO,YACvB,MAAM,KAAK,MAAKA,YAAa,QAAQ,GAAG,UAAU,CAChD,MAAM,KACN,MAAM,KACP,CAAC,CACH;AACD,OAAK,MAAM,gBAAgB;GACzB;GACA;GACD,EAAE;;;;;CAML,mBAAyB;AACvB,MAAI,OAAO,aAAa,YACtB;AAGF,MAAI,MAAKD,iBAAkB;AACzB,YAAS,oBAAoB,WAAW,MAAKA,iBAAkB,KAAK;AACpE,SAAKA,kBAAmB;;AAG1B,MAAI,MAAKG,eAAgB;AACvB,YAAS,oBAAoB,SAAS,MAAKA,eAAgB,KAAK;AAChE,SAAKA,gBAAiB;;AAGxB,MAAI,MAAKC,cAAe;AACtB,UAAO,oBAAoB,QAAQ,MAAKA,aAAc;AACtD,SAAKA,eAAgB;;;;;;;;CASzB,cAA6B;AAC3B,SAAO,KAAK,MAAM,MAAM;;;;;;;;CAS1B,UAAU,KAAsB;EAC9B,MAAM,gBAAgB,iBAAiB,IAAI;AAC3C,SAAO,MAAM,KAAK,MAAKH,YAAa,QAAQ,CAAC,CAAC,MAC3C,UAAU,MAAM,QAAQ,cAC1B;;;;;;;;CASH,aAAa,MAA8B;AACzC,SAAO,KAAK,MAAM,QAAQ,KAAK,UAAU,IAAI,CAAC;;;;;;;;CAShD,eAAe,MAA8B;AAC3C,SAAO,KAAK,OAAO,QAAQ,KAAK,UAAU,IAAI,CAAC;;;;;CAMjD,UAAgB;AACd,QAAKI,iBAAkB;AACvB,QAAKJ,YAAa,OAAO;AACzB,OAAK,MAAM,eAAe,gCAAgC,CAAC;;;;;;;AAQ/D,SAAgB,qBAAsC;AACpD,QAAO,gBAAgB,aAAa"}
|
package/dist/key.types.d.cts
DELETED
|
@@ -1,82 +0,0 @@
|
|
|
1
|
-
import { LOGICAL_ONLY_NAMED_KEYS, SHARED_NAMED_KEYS } from "./_named-keys.cjs";
|
|
2
|
-
|
|
3
|
-
//#region src/key.types.d.ts
|
|
4
|
-
/**
|
|
5
|
-
* All supported modifier key names, including aliases.
|
|
6
|
-
* - Control/Ctrl: The Control key
|
|
7
|
-
* - Shift: The Shift key
|
|
8
|
-
* - Alt/Option: The Alt key (Option on macOS)
|
|
9
|
-
* - Command/Cmd: The Command key (macOS only)
|
|
10
|
-
* - CommandOrControl/Mod: Command on macOS, Control on other platforms
|
|
11
|
-
*/
|
|
12
|
-
type Modifier = 'Control' | 'Ctrl' | 'Shift' | 'Alt' | 'Option' | 'Command' | 'Cmd' | 'CommandOrControl' | 'Mod';
|
|
13
|
-
/**
|
|
14
|
-
* Canonical modifier names that map to KeyboardEvent properties.
|
|
15
|
-
*/
|
|
16
|
-
type CanonicalModifier = 'Control' | 'Shift' | 'Alt' | 'Meta';
|
|
17
|
-
/**
|
|
18
|
-
* Letter keys A-Z (case-insensitive in matching).
|
|
19
|
-
*/
|
|
20
|
-
type LetterKey = 'A' | 'B' | 'C' | 'D' | 'E' | 'F' | 'G' | 'H' | 'I' | 'J' | 'K' | 'L' | 'M' | 'N' | 'O' | 'P' | 'Q' | 'R' | 'S' | 'T' | 'U' | 'V' | 'W' | 'X' | 'Y' | 'Z';
|
|
21
|
-
/**
|
|
22
|
-
* Number keys 0-9.
|
|
23
|
-
*/
|
|
24
|
-
type NumberKey = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9';
|
|
25
|
-
/**
|
|
26
|
-
* Function keys F1-F24, supported as both logical keys and physical codes.
|
|
27
|
-
*/
|
|
28
|
-
type FunctionKey = 'F1' | 'F2' | 'F3' | 'F4' | 'F5' | 'F6' | 'F7' | 'F8' | 'F9' | 'F10' | 'F11' | 'F12' | 'F13' | 'F14' | 'F15' | 'F16' | 'F17' | 'F18' | 'F19' | 'F20' | 'F21' | 'F22' | 'F23' | 'F24';
|
|
29
|
-
/**
|
|
30
|
-
* Navigation keys for cursor movement.
|
|
31
|
-
*/
|
|
32
|
-
type NavigationKey = 'ArrowUp' | 'ArrowDown' | 'ArrowLeft' | 'ArrowRight' | 'Home' | 'End' | 'PageUp' | 'PageDown';
|
|
33
|
-
/**
|
|
34
|
-
* Editing and special keys.
|
|
35
|
-
*/
|
|
36
|
-
type EditingKey = 'Enter' | 'Escape' | 'Space' | 'Tab' | 'Backspace' | 'Delete';
|
|
37
|
-
/**
|
|
38
|
-
* Printable punctuation glyphs used in keyboard shortcuts. Matching uses the
|
|
39
|
-
* final KeyboardEvent.key glyph, independent of which layout produced it.
|
|
40
|
-
*/
|
|
41
|
-
type PunctuationKey = '/' | '[' | ']' | '\\' | '=' | '-' | ',' | '.' | ';' | '`' | "'" | '+' | '?' | '!' | '@' | '#' | '$' | '%' | '^' | '&' | '*' | '(' | ')' | '_' | '{' | '}' | '|' | ':' | '"' | '<' | '>' | '~';
|
|
42
|
-
/** Additional named logical keys, including media, browser, lock, and input-mode keys. */
|
|
43
|
-
type NamedKey = (typeof SHARED_NAMED_KEYS)[number] | (typeof LOGICAL_ONLY_NAMED_KEYS)[number];
|
|
44
|
-
/** Supported logical key names other than printable punctuation. */
|
|
45
|
-
type NonPunctuationKey = LetterKey | NumberKey | EditingKey | NavigationKey | FunctionKey | NamedKey;
|
|
46
|
-
/**
|
|
47
|
-
* Supported physical KeyboardEvent.code names, independent of keyboard layout.
|
|
48
|
-
* Letter, digit, numpad, and sided modifier names use finite template unions.
|
|
49
|
-
* `Unidentified` is excluded because it cannot identify a physical key.
|
|
50
|
-
*
|
|
51
|
-
* @see https://www.w3.org/TR/uievents-code/
|
|
52
|
-
*/
|
|
53
|
-
type PhysicalKeyCode = `Key${LetterKey}` | `Digit${NumberKey}` | `Numpad${NumberKey}` | `${'Alt' | 'Control' | 'Meta' | 'Shift'}${'Left' | 'Right'}` | EditingKey | NavigationKey | FunctionKey | (typeof SHARED_NAMED_KEYS)[number] | 'Backquote' | 'Backslash' | 'BracketLeft' | 'BracketRight' | 'Comma' | 'Equal' | 'IntlBackslash' | 'IntlRo' | 'IntlYen' | 'Minus' | 'Period' | 'Quote' | 'Semicolon' | 'Slash' | `Lang${1 | 2 | 3 | 4 | 5}` | `Numpad${'Add' | 'Backspace' | 'Clear' | 'ClearEntry' | 'Comma' | 'Decimal' | 'Divide' | 'Enter' | 'Equal' | 'Hash' | 'MemoryAdd' | 'MemoryClear' | 'MemoryRecall' | 'MemoryStore' | 'MemorySubtract' | 'Multiply' | 'ParenLeft' | 'ParenRight' | 'Star' | 'Subtract'}` | 'LaunchApp1' | 'LaunchApp2' | 'MediaSelect' | 'Sleep' | 'Turbo' | 'Abort' | 'Resume' | 'Suspend';
|
|
54
|
-
/**
|
|
55
|
-
* An explicit physical key token. All codes use brackets, including names such
|
|
56
|
-
* as `[Enter]` that also exist as logical keys. Invalid code names are rejected
|
|
57
|
-
* by TypeScript, and supported names are available in autocomplete.
|
|
58
|
-
*/
|
|
59
|
-
type PhysicalKey = `[${PhysicalKeyCode}]`;
|
|
60
|
-
/** Supported logical key names, excluding bracketed physical-code syntax. */
|
|
61
|
-
type LogicalKey = NonPunctuationKey | PunctuationKey;
|
|
62
|
-
/** All supported logical keys and bracketed physical key tokens. */
|
|
63
|
-
type Key = LogicalKey | PhysicalKey;
|
|
64
|
-
/**
|
|
65
|
-
* Includes both modifier keys and regular keys.
|
|
66
|
-
*/
|
|
67
|
-
type IndividualKey = CanonicalModifier | Key;
|
|
68
|
-
/** Keyboard event properties normalized for internal matching and recording. */
|
|
69
|
-
interface NormalizedKeyboardEvent {
|
|
70
|
-
key: string;
|
|
71
|
-
code: string;
|
|
72
|
-
ctrl: boolean;
|
|
73
|
-
shift: boolean;
|
|
74
|
-
alt: boolean;
|
|
75
|
-
meta: boolean;
|
|
76
|
-
altGraph: boolean;
|
|
77
|
-
location: number;
|
|
78
|
-
isComposing: boolean;
|
|
79
|
-
}
|
|
80
|
-
//#endregion
|
|
81
|
-
export { CanonicalModifier, EditingKey, FunctionKey, IndividualKey, Key, LetterKey, LogicalKey, Modifier, NamedKey, NavigationKey, NonPunctuationKey, NormalizedKeyboardEvent, NumberKey, PhysicalKey, PhysicalKeyCode, PunctuationKey };
|
|
82
|
-
//# sourceMappingURL=key.types.d.cts.map
|
package/dist/match.cjs
DELETED
|
@@ -1,144 +0,0 @@
|
|
|
1
|
-
const require_platform = require('./platform.cjs');
|
|
2
|
-
const require__keyboard_event = require('./_keyboard-event.cjs');
|
|
3
|
-
const require_parse = require('./parse.cjs');
|
|
4
|
-
const require__match = require('./_match.cjs');
|
|
5
|
-
|
|
6
|
-
//#region src/match.ts
|
|
7
|
-
/**
|
|
8
|
-
* Checks if a KeyboardEvent matches a hotkey.
|
|
9
|
-
*
|
|
10
|
-
* Physical bindings such as `Mod+[KeyS]` match `event.code` exactly.
|
|
11
|
-
* Logical bindings use `event.key`, with a fallback to `code`
|
|
12
|
-
* for letter keys, digit keys (0-9), and punctuation keys when `key` produces special
|
|
13
|
-
* characters (e.g., macOS Option+letter, Shift+number, or Option+punctuation).
|
|
14
|
-
* Letter keys are matched case-insensitively.
|
|
15
|
-
*
|
|
16
|
-
* Also handles "dead key" events where `event.key` is `'Dead'` instead of the expected
|
|
17
|
-
* character. This commonly occurs on macOS with Option+letter combinations (e.g., Option+E,
|
|
18
|
-
* Option+I, Option+U, Option+N) and on Windows/Linux with international keyboard layouts.
|
|
19
|
-
* In these cases, `event.code` is used to determine the physical key.
|
|
20
|
-
*
|
|
21
|
-
* @param event - The KeyboardEvent to check
|
|
22
|
-
* @param hotkey - The hotkey string or ParsedHotkey to match against
|
|
23
|
-
* @param platform - The target platform for resolving 'Mod' (defaults to auto-detection)
|
|
24
|
-
* @returns True if the event matches the hotkey
|
|
25
|
-
*
|
|
26
|
-
* @example
|
|
27
|
-
* ```ts
|
|
28
|
-
* document.addEventListener('keydown', (event) => {
|
|
29
|
-
* if (matchesKeyboardEvent(event, 'Mod+S')) {
|
|
30
|
-
* event.preventDefault()
|
|
31
|
-
* handleSave()
|
|
32
|
-
* }
|
|
33
|
-
* })
|
|
34
|
-
* ```
|
|
35
|
-
*/
|
|
36
|
-
function matchesKeyboardEvent(event, hotkey, platform = require_platform.detectPlatform()) {
|
|
37
|
-
return require__match.matchKeyboardEvent(event, hotkey, platform).matched;
|
|
38
|
-
}
|
|
39
|
-
/**
|
|
40
|
-
* Creates a keyboard event handler that calls the callback when the hotkey matches.
|
|
41
|
-
*
|
|
42
|
-
* @param hotkey - The hotkey string or ParsedHotkey to match
|
|
43
|
-
* @param callback - The function to call when the hotkey matches
|
|
44
|
-
* @param options - Options for matching and handling
|
|
45
|
-
* @returns A function that can be used as an event handler
|
|
46
|
-
*
|
|
47
|
-
* @example
|
|
48
|
-
* ```ts
|
|
49
|
-
* const handler = createHotkeyHandler('Mod+S', (event, { hotkey, parsedHotkey }) => {
|
|
50
|
-
* console.log(`${hotkey} was pressed`)
|
|
51
|
-
* handleSave()
|
|
52
|
-
* })
|
|
53
|
-
*
|
|
54
|
-
* document.addEventListener('keydown', handler)
|
|
55
|
-
* ```
|
|
56
|
-
*/
|
|
57
|
-
function createHotkeyHandler(hotkey, callback, options = {}) {
|
|
58
|
-
const { preventDefault = true, stopPropagation = true, platform } = options;
|
|
59
|
-
const resolvedPlatform = platform ?? require_platform.detectPlatform();
|
|
60
|
-
const hotkeyString = typeof hotkey === "string" ? hotkey : formatParsedHotkey(hotkey);
|
|
61
|
-
const parsed = typeof hotkey === "string" ? require_parse.parseHotkey(hotkey, resolvedPlatform) : hotkey;
|
|
62
|
-
const context = {
|
|
63
|
-
hotkey: hotkeyString,
|
|
64
|
-
parsedHotkey: parsed
|
|
65
|
-
};
|
|
66
|
-
return (event) => {
|
|
67
|
-
if (matchesKeyboardEvent(event, parsed, resolvedPlatform)) {
|
|
68
|
-
if (preventDefault) event.preventDefault();
|
|
69
|
-
if (stopPropagation) event.stopPropagation();
|
|
70
|
-
callback(event, context);
|
|
71
|
-
}
|
|
72
|
-
};
|
|
73
|
-
}
|
|
74
|
-
/**
|
|
75
|
-
* Creates a handler that matches multiple hotkeys.
|
|
76
|
-
*
|
|
77
|
-
* @param handlers - A map of hotkey strings to their handlers
|
|
78
|
-
* @param options - Options for matching and handling
|
|
79
|
-
* @returns A function that can be used as an event handler
|
|
80
|
-
*
|
|
81
|
-
* @example
|
|
82
|
-
* ```ts
|
|
83
|
-
* const handler = createMultiHotkeyHandler({
|
|
84
|
-
* 'Mod+S': (event, { hotkey }) => handleSave(),
|
|
85
|
-
* 'Mod+Z': (event, { hotkey }) => handleUndo(),
|
|
86
|
-
* 'Mod+Shift+Z': (event, { hotkey }) => handleRedo(),
|
|
87
|
-
* })
|
|
88
|
-
*
|
|
89
|
-
* document.addEventListener('keydown', handler)
|
|
90
|
-
* ```
|
|
91
|
-
*/
|
|
92
|
-
function createMultiHotkeyHandler(handlers, options = {}) {
|
|
93
|
-
const { preventDefault = true, stopPropagation = true, platform } = options;
|
|
94
|
-
const resolvedPlatform = platform ?? require_platform.detectPlatform();
|
|
95
|
-
const parsedHandlers = Object.entries(handlers).filter((entry) => Boolean(entry[1])).map(([hotkey, handler]) => {
|
|
96
|
-
const parsed = require_parse.parseHotkey(hotkey, resolvedPlatform);
|
|
97
|
-
return {
|
|
98
|
-
parsed,
|
|
99
|
-
handler,
|
|
100
|
-
context: {
|
|
101
|
-
hotkey,
|
|
102
|
-
parsedHotkey: parsed
|
|
103
|
-
}
|
|
104
|
-
};
|
|
105
|
-
});
|
|
106
|
-
return (event) => {
|
|
107
|
-
for (const { parsed, handler, context } of parsedHandlers) if (matchesKeyboardEvent(event, parsed, resolvedPlatform)) {
|
|
108
|
-
if (preventDefault) event.preventDefault();
|
|
109
|
-
if (stopPropagation) event.stopPropagation();
|
|
110
|
-
handler(event, context);
|
|
111
|
-
return;
|
|
112
|
-
}
|
|
113
|
-
};
|
|
114
|
-
}
|
|
115
|
-
/**
|
|
116
|
-
* Formats a ParsedHotkey back to a hotkey string.
|
|
117
|
-
* Used internally to provide the hotkey string in callback context.
|
|
118
|
-
*/
|
|
119
|
-
function formatParsedHotkey(parsed) {
|
|
120
|
-
const parts = [];
|
|
121
|
-
if (parsed.ctrl) parts.push("Control");
|
|
122
|
-
if (parsed.alt) parts.push("Alt");
|
|
123
|
-
if (parsed.shift) parts.push("Shift");
|
|
124
|
-
if (parsed.meta) parts.push("Meta");
|
|
125
|
-
parts.push(parsed.code !== void 0 ? `[${parsed.code}]` : parsed.key);
|
|
126
|
-
return parts.join("+");
|
|
127
|
-
}
|
|
128
|
-
/**
|
|
129
|
-
* Compares normalized binding identity, including all four modifiers.
|
|
130
|
-
* Aliases resolve on the supplied platform. A physical code and a logical key
|
|
131
|
-
* remain distinct even when one keyboard event could match both.
|
|
132
|
-
*/
|
|
133
|
-
function areHotkeysEqual(left, right, platform = require_platform.detectPlatform()) {
|
|
134
|
-
const a = require_parse.parseRegisterableHotkey(left, platform);
|
|
135
|
-
const b = require_parse.parseRegisterableHotkey(right, platform);
|
|
136
|
-
return a.ctrl === b.ctrl && a.alt === b.alt && a.shift === b.shift && a.meta === b.meta && (a.code !== void 0 || b.code !== void 0 ? a.code === b.code : require__keyboard_event.keysEqual(a.key, b.key));
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
//#endregion
|
|
140
|
-
exports.areHotkeysEqual = areHotkeysEqual;
|
|
141
|
-
exports.createHotkeyHandler = createHotkeyHandler;
|
|
142
|
-
exports.createMultiHotkeyHandler = createMultiHotkeyHandler;
|
|
143
|
-
exports.matchesKeyboardEvent = matchesKeyboardEvent;
|
|
144
|
-
//# sourceMappingURL=match.cjs.map
|
package/dist/match.cjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"match.cjs","names":["detectPlatform","matchKeyboardEvent","parseHotkey","parseRegisterableHotkey","keysEqual"],"sources":["../src/match.ts"],"sourcesContent":["import { matchKeyboardEvent } from './_match'\nimport { parseHotkey, parseRegisterableHotkey } from './parse'\nimport { detectPlatform } from './platform'\nimport { keysEqual } from './_keyboard-event'\nimport type {\n Hotkey,\n HotkeyCallback,\n HotkeyCallbackContext,\n ParsedHotkey,\n RegisterableHotkey,\n} from './hotkey.types'\n\nexport interface KeyboardEventMatch {\n matched: boolean\n score: 0 | 1 | 2 | 3\n source?: 'key' | 'code' | 'fallback'\n identity?: { key: string; code: string }\n}\n\n/**\n * Checks if a KeyboardEvent matches a hotkey.\n *\n * Physical bindings such as `Mod+[KeyS]` match `event.code` exactly.\n * Logical bindings use `event.key`, with a fallback to `code`\n * for letter keys, digit keys (0-9), and punctuation keys when `key` produces special\n * characters (e.g., macOS Option+letter, Shift+number, or Option+punctuation).\n * Letter keys are matched case-insensitively.\n *\n * Also handles \"dead key\" events where `event.key` is `'Dead'` instead of the expected\n * character. This commonly occurs on macOS with Option+letter combinations (e.g., Option+E,\n * Option+I, Option+U, Option+N) and on Windows/Linux with international keyboard layouts.\n * In these cases, `event.code` is used to determine the physical key.\n *\n * @param event - The KeyboardEvent to check\n * @param hotkey - The hotkey string or ParsedHotkey to match against\n * @param platform - The target platform for resolving 'Mod' (defaults to auto-detection)\n * @returns True if the event matches the hotkey\n *\n * @example\n * ```ts\n * document.addEventListener('keydown', (event) => {\n * if (matchesKeyboardEvent(event, 'Mod+S')) {\n * event.preventDefault()\n * handleSave()\n * }\n * })\n * ```\n */\nexport function matchesKeyboardEvent(\n event: KeyboardEvent,\n hotkey: Hotkey | ParsedHotkey,\n platform: 'mac' | 'windows' | 'linux' = detectPlatform(),\n): boolean {\n return matchKeyboardEvent(event, hotkey, platform).matched\n}\n\n/**\n * Options for creating a hotkey handler.\n */\nexport interface CreateHotkeyHandlerOptions {\n /** Prevent the default browser action when the hotkey matches. Defaults to true */\n preventDefault?: boolean\n /** Stop event propagation when the hotkey matches. Defaults to true */\n stopPropagation?: boolean\n /** The target platform for resolving 'Mod' */\n platform?: 'mac' | 'windows' | 'linux'\n}\n\n/**\n * Creates a keyboard event handler that calls the callback when the hotkey matches.\n *\n * @param hotkey - The hotkey string or ParsedHotkey to match\n * @param callback - The function to call when the hotkey matches\n * @param options - Options for matching and handling\n * @returns A function that can be used as an event handler\n *\n * @example\n * ```ts\n * const handler = createHotkeyHandler('Mod+S', (event, { hotkey, parsedHotkey }) => {\n * console.log(`${hotkey} was pressed`)\n * handleSave()\n * })\n *\n * document.addEventListener('keydown', handler)\n * ```\n */\nexport function createHotkeyHandler(\n hotkey: Hotkey | ParsedHotkey,\n callback: HotkeyCallback,\n options: CreateHotkeyHandlerOptions = {},\n): (event: KeyboardEvent) => void {\n const { preventDefault = true, stopPropagation = true, platform } = options\n const resolvedPlatform = platform ?? detectPlatform()\n\n const hotkeyString: Hotkey =\n typeof hotkey === 'string' ? hotkey : formatParsedHotkey(hotkey)\n const parsed =\n typeof hotkey === 'string' ? parseHotkey(hotkey, resolvedPlatform) : hotkey\n\n const context: HotkeyCallbackContext = {\n hotkey: hotkeyString,\n parsedHotkey: parsed,\n }\n\n return (event: KeyboardEvent) => {\n if (matchesKeyboardEvent(event, parsed, resolvedPlatform)) {\n if (preventDefault) {\n event.preventDefault()\n }\n if (stopPropagation) {\n event.stopPropagation()\n }\n callback(event, context)\n }\n }\n}\n\nexport type MultiHotkeyHandler = { [K in Hotkey]?: HotkeyCallback }\n\n/**\n * Creates a handler that matches multiple hotkeys.\n *\n * @param handlers - A map of hotkey strings to their handlers\n * @param options - Options for matching and handling\n * @returns A function that can be used as an event handler\n *\n * @example\n * ```ts\n * const handler = createMultiHotkeyHandler({\n * 'Mod+S': (event, { hotkey }) => handleSave(),\n * 'Mod+Z': (event, { hotkey }) => handleUndo(),\n * 'Mod+Shift+Z': (event, { hotkey }) => handleRedo(),\n * })\n *\n * document.addEventListener('keydown', handler)\n * ```\n */\nexport function createMultiHotkeyHandler(\n handlers: MultiHotkeyHandler,\n options: CreateHotkeyHandlerOptions = {},\n): (event: KeyboardEvent) => void {\n const { preventDefault = true, stopPropagation = true, platform } = options\n const resolvedPlatform = platform ?? detectPlatform()\n\n // Pre-parse all hotkeys for efficiency\n const parsedHandlers = Object.entries(handlers)\n .filter((entry): entry is [string, HotkeyCallback] => Boolean(entry[1]))\n .map(([hotkey, handler]) => {\n const parsed = parseHotkey(hotkey as Hotkey, resolvedPlatform)\n const context: HotkeyCallbackContext = {\n hotkey: hotkey as Hotkey,\n parsedHotkey: parsed,\n }\n return { parsed, handler, context }\n })\n\n return (event: KeyboardEvent) => {\n for (const { parsed, handler, context } of parsedHandlers) {\n if (matchesKeyboardEvent(event, parsed, resolvedPlatform)) {\n if (preventDefault) {\n event.preventDefault()\n }\n if (stopPropagation) {\n event.stopPropagation()\n }\n handler(event, context)\n return // Only handle the first match\n }\n }\n }\n}\n\n/**\n * Formats a ParsedHotkey back to a hotkey string.\n * Used internally to provide the hotkey string in callback context.\n */\nfunction formatParsedHotkey(parsed: ParsedHotkey): Hotkey {\n const parts: Array<string> = []\n\n if (parsed.ctrl) parts.push('Control')\n if (parsed.alt) parts.push('Alt')\n if (parsed.shift) parts.push('Shift')\n if (parsed.meta) parts.push('Meta')\n parts.push(parsed.code !== undefined ? `[${parsed.code}]` : parsed.key)\n\n return parts.join('+') as Hotkey\n}\n\n/**\n * Compares normalized binding identity, including all four modifiers.\n * Aliases resolve on the supplied platform. A physical code and a logical key\n * remain distinct even when one keyboard event could match both.\n */\nexport function areHotkeysEqual(\n left: RegisterableHotkey,\n right: RegisterableHotkey,\n platform = detectPlatform(),\n): boolean {\n const a = parseRegisterableHotkey(left, platform)\n const b = parseRegisterableHotkey(right, platform)\n return (\n a.ctrl === b.ctrl &&\n a.alt === b.alt &&\n a.shift === b.shift &&\n a.meta === b.meta &&\n (a.code !== undefined || b.code !== undefined\n ? a.code === b.code\n : keysEqual(a.key, b.key))\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,SAAgB,qBACd,OACA,QACA,WAAwCA,iCAAgB,EAC/C;AACT,QAAOC,kCAAmB,OAAO,QAAQ,SAAS,CAAC;;;;;;;;;;;;;;;;;;;;AAiCrD,SAAgB,oBACd,QACA,UACA,UAAsC,EAAE,EACR;CAChC,MAAM,EAAE,iBAAiB,MAAM,kBAAkB,MAAM,aAAa;CACpE,MAAM,mBAAmB,YAAYD,iCAAgB;CAErD,MAAM,eACJ,OAAO,WAAW,WAAW,SAAS,mBAAmB,OAAO;CAClE,MAAM,SACJ,OAAO,WAAW,WAAWE,0BAAY,QAAQ,iBAAiB,GAAG;CAEvE,MAAM,UAAiC;EACrC,QAAQ;EACR,cAAc;EACf;AAED,SAAQ,UAAyB;AAC/B,MAAI,qBAAqB,OAAO,QAAQ,iBAAiB,EAAE;AACzD,OAAI,eACF,OAAM,gBAAgB;AAExB,OAAI,gBACF,OAAM,iBAAiB;AAEzB,YAAS,OAAO,QAAQ;;;;;;;;;;;;;;;;;;;;;;AAyB9B,SAAgB,yBACd,UACA,UAAsC,EAAE,EACR;CAChC,MAAM,EAAE,iBAAiB,MAAM,kBAAkB,MAAM,aAAa;CACpE,MAAM,mBAAmB,YAAYF,iCAAgB;CAGrD,MAAM,iBAAiB,OAAO,QAAQ,SAAS,CAC5C,QAAQ,UAA6C,QAAQ,MAAM,GAAG,CAAC,CACvE,KAAK,CAAC,QAAQ,aAAa;EAC1B,MAAM,SAASE,0BAAY,QAAkB,iBAAiB;AAK9D,SAAO;GAAE;GAAQ;GAAS,SAJa;IAC7B;IACR,cAAc;IACf;GACkC;GACnC;AAEJ,SAAQ,UAAyB;AAC/B,OAAK,MAAM,EAAE,QAAQ,SAAS,aAAa,eACzC,KAAI,qBAAqB,OAAO,QAAQ,iBAAiB,EAAE;AACzD,OAAI,eACF,OAAM,gBAAgB;AAExB,OAAI,gBACF,OAAM,iBAAiB;AAEzB,WAAQ,OAAO,QAAQ;AACvB;;;;;;;;AAUR,SAAS,mBAAmB,QAA8B;CACxD,MAAM,QAAuB,EAAE;AAE/B,KAAI,OAAO,KAAM,OAAM,KAAK,UAAU;AACtC,KAAI,OAAO,IAAK,OAAM,KAAK,MAAM;AACjC,KAAI,OAAO,MAAO,OAAM,KAAK,QAAQ;AACrC,KAAI,OAAO,KAAM,OAAM,KAAK,OAAO;AACnC,OAAM,KAAK,OAAO,SAAS,SAAY,IAAI,OAAO,KAAK,KAAK,OAAO,IAAI;AAEvE,QAAO,MAAM,KAAK,IAAI;;;;;;;AAQxB,SAAgB,gBACd,MACA,OACA,WAAWF,iCAAgB,EAClB;CACT,MAAM,IAAIG,sCAAwB,MAAM,SAAS;CACjD,MAAM,IAAIA,sCAAwB,OAAO,SAAS;AAClD,QACE,EAAE,SAAS,EAAE,QACb,EAAE,QAAQ,EAAE,OACZ,EAAE,UAAU,EAAE,SACd,EAAE,SAAS,EAAE,SACZ,EAAE,SAAS,UAAa,EAAE,SAAS,SAChC,EAAE,SAAS,EAAE,OACbC,kCAAU,EAAE,KAAK,EAAE,IAAI"}
|
package/dist/match.d.cts
DELETED
|
@@ -1,101 +0,0 @@
|
|
|
1
|
-
import { Hotkey, HotkeyCallback, ParsedHotkey, RegisterableHotkey } from "./hotkey.types.cjs";
|
|
2
|
-
|
|
3
|
-
//#region src/match.d.ts
|
|
4
|
-
interface KeyboardEventMatch {
|
|
5
|
-
matched: boolean;
|
|
6
|
-
score: 0 | 1 | 2 | 3;
|
|
7
|
-
source?: 'key' | 'code' | 'fallback';
|
|
8
|
-
identity?: {
|
|
9
|
-
key: string;
|
|
10
|
-
code: string;
|
|
11
|
-
};
|
|
12
|
-
}
|
|
13
|
-
/**
|
|
14
|
-
* Checks if a KeyboardEvent matches a hotkey.
|
|
15
|
-
*
|
|
16
|
-
* Physical bindings such as `Mod+[KeyS]` match `event.code` exactly.
|
|
17
|
-
* Logical bindings use `event.key`, with a fallback to `code`
|
|
18
|
-
* for letter keys, digit keys (0-9), and punctuation keys when `key` produces special
|
|
19
|
-
* characters (e.g., macOS Option+letter, Shift+number, or Option+punctuation).
|
|
20
|
-
* Letter keys are matched case-insensitively.
|
|
21
|
-
*
|
|
22
|
-
* Also handles "dead key" events where `event.key` is `'Dead'` instead of the expected
|
|
23
|
-
* character. This commonly occurs on macOS with Option+letter combinations (e.g., Option+E,
|
|
24
|
-
* Option+I, Option+U, Option+N) and on Windows/Linux with international keyboard layouts.
|
|
25
|
-
* In these cases, `event.code` is used to determine the physical key.
|
|
26
|
-
*
|
|
27
|
-
* @param event - The KeyboardEvent to check
|
|
28
|
-
* @param hotkey - The hotkey string or ParsedHotkey to match against
|
|
29
|
-
* @param platform - The target platform for resolving 'Mod' (defaults to auto-detection)
|
|
30
|
-
* @returns True if the event matches the hotkey
|
|
31
|
-
*
|
|
32
|
-
* @example
|
|
33
|
-
* ```ts
|
|
34
|
-
* document.addEventListener('keydown', (event) => {
|
|
35
|
-
* if (matchesKeyboardEvent(event, 'Mod+S')) {
|
|
36
|
-
* event.preventDefault()
|
|
37
|
-
* handleSave()
|
|
38
|
-
* }
|
|
39
|
-
* })
|
|
40
|
-
* ```
|
|
41
|
-
*/
|
|
42
|
-
declare function matchesKeyboardEvent(event: KeyboardEvent, hotkey: Hotkey | ParsedHotkey, platform?: 'mac' | 'windows' | 'linux'): boolean;
|
|
43
|
-
/**
|
|
44
|
-
* Options for creating a hotkey handler.
|
|
45
|
-
*/
|
|
46
|
-
interface CreateHotkeyHandlerOptions {
|
|
47
|
-
/** Prevent the default browser action when the hotkey matches. Defaults to true */
|
|
48
|
-
preventDefault?: boolean;
|
|
49
|
-
/** Stop event propagation when the hotkey matches. Defaults to true */
|
|
50
|
-
stopPropagation?: boolean;
|
|
51
|
-
/** The target platform for resolving 'Mod' */
|
|
52
|
-
platform?: 'mac' | 'windows' | 'linux';
|
|
53
|
-
}
|
|
54
|
-
/**
|
|
55
|
-
* Creates a keyboard event handler that calls the callback when the hotkey matches.
|
|
56
|
-
*
|
|
57
|
-
* @param hotkey - The hotkey string or ParsedHotkey to match
|
|
58
|
-
* @param callback - The function to call when the hotkey matches
|
|
59
|
-
* @param options - Options for matching and handling
|
|
60
|
-
* @returns A function that can be used as an event handler
|
|
61
|
-
*
|
|
62
|
-
* @example
|
|
63
|
-
* ```ts
|
|
64
|
-
* const handler = createHotkeyHandler('Mod+S', (event, { hotkey, parsedHotkey }) => {
|
|
65
|
-
* console.log(`${hotkey} was pressed`)
|
|
66
|
-
* handleSave()
|
|
67
|
-
* })
|
|
68
|
-
*
|
|
69
|
-
* document.addEventListener('keydown', handler)
|
|
70
|
-
* ```
|
|
71
|
-
*/
|
|
72
|
-
declare function createHotkeyHandler(hotkey: Hotkey | ParsedHotkey, callback: HotkeyCallback, options?: CreateHotkeyHandlerOptions): (event: KeyboardEvent) => void;
|
|
73
|
-
type MultiHotkeyHandler = { [K in Hotkey]?: HotkeyCallback };
|
|
74
|
-
/**
|
|
75
|
-
* Creates a handler that matches multiple hotkeys.
|
|
76
|
-
*
|
|
77
|
-
* @param handlers - A map of hotkey strings to their handlers
|
|
78
|
-
* @param options - Options for matching and handling
|
|
79
|
-
* @returns A function that can be used as an event handler
|
|
80
|
-
*
|
|
81
|
-
* @example
|
|
82
|
-
* ```ts
|
|
83
|
-
* const handler = createMultiHotkeyHandler({
|
|
84
|
-
* 'Mod+S': (event, { hotkey }) => handleSave(),
|
|
85
|
-
* 'Mod+Z': (event, { hotkey }) => handleUndo(),
|
|
86
|
-
* 'Mod+Shift+Z': (event, { hotkey }) => handleRedo(),
|
|
87
|
-
* })
|
|
88
|
-
*
|
|
89
|
-
* document.addEventListener('keydown', handler)
|
|
90
|
-
* ```
|
|
91
|
-
*/
|
|
92
|
-
declare function createMultiHotkeyHandler(handlers: MultiHotkeyHandler, options?: CreateHotkeyHandlerOptions): (event: KeyboardEvent) => void;
|
|
93
|
-
/**
|
|
94
|
-
* Compares normalized binding identity, including all four modifiers.
|
|
95
|
-
* Aliases resolve on the supplied platform. A physical code and a logical key
|
|
96
|
-
* remain distinct even when one keyboard event could match both.
|
|
97
|
-
*/
|
|
98
|
-
declare function areHotkeysEqual(left: RegisterableHotkey, right: RegisterableHotkey, platform?: "mac" | "windows" | "linux"): boolean;
|
|
99
|
-
//#endregion
|
|
100
|
-
export { CreateHotkeyHandlerOptions, KeyboardEventMatch, MultiHotkeyHandler, areHotkeysEqual, createHotkeyHandler, createMultiHotkeyHandler, matchesKeyboardEvent };
|
|
101
|
-
//# sourceMappingURL=match.d.cts.map
|
package/dist/match.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"match.js","names":[],"sources":["../src/match.ts"],"sourcesContent":["import { matchKeyboardEvent } from './_match'\nimport { parseHotkey, parseRegisterableHotkey } from './parse'\nimport { detectPlatform } from './platform'\nimport { keysEqual } from './_keyboard-event'\nimport type {\n Hotkey,\n HotkeyCallback,\n HotkeyCallbackContext,\n ParsedHotkey,\n RegisterableHotkey,\n} from './hotkey.types'\n\nexport interface KeyboardEventMatch {\n matched: boolean\n score: 0 | 1 | 2 | 3\n source?: 'key' | 'code' | 'fallback'\n identity?: { key: string; code: string }\n}\n\n/**\n * Checks if a KeyboardEvent matches a hotkey.\n *\n * Physical bindings such as `Mod+[KeyS]` match `event.code` exactly.\n * Logical bindings use `event.key`, with a fallback to `code`\n * for letter keys, digit keys (0-9), and punctuation keys when `key` produces special\n * characters (e.g., macOS Option+letter, Shift+number, or Option+punctuation).\n * Letter keys are matched case-insensitively.\n *\n * Also handles \"dead key\" events where `event.key` is `'Dead'` instead of the expected\n * character. This commonly occurs on macOS with Option+letter combinations (e.g., Option+E,\n * Option+I, Option+U, Option+N) and on Windows/Linux with international keyboard layouts.\n * In these cases, `event.code` is used to determine the physical key.\n *\n * @param event - The KeyboardEvent to check\n * @param hotkey - The hotkey string or ParsedHotkey to match against\n * @param platform - The target platform for resolving 'Mod' (defaults to auto-detection)\n * @returns True if the event matches the hotkey\n *\n * @example\n * ```ts\n * document.addEventListener('keydown', (event) => {\n * if (matchesKeyboardEvent(event, 'Mod+S')) {\n * event.preventDefault()\n * handleSave()\n * }\n * })\n * ```\n */\nexport function matchesKeyboardEvent(\n event: KeyboardEvent,\n hotkey: Hotkey | ParsedHotkey,\n platform: 'mac' | 'windows' | 'linux' = detectPlatform(),\n): boolean {\n return matchKeyboardEvent(event, hotkey, platform).matched\n}\n\n/**\n * Options for creating a hotkey handler.\n */\nexport interface CreateHotkeyHandlerOptions {\n /** Prevent the default browser action when the hotkey matches. Defaults to true */\n preventDefault?: boolean\n /** Stop event propagation when the hotkey matches. Defaults to true */\n stopPropagation?: boolean\n /** The target platform for resolving 'Mod' */\n platform?: 'mac' | 'windows' | 'linux'\n}\n\n/**\n * Creates a keyboard event handler that calls the callback when the hotkey matches.\n *\n * @param hotkey - The hotkey string or ParsedHotkey to match\n * @param callback - The function to call when the hotkey matches\n * @param options - Options for matching and handling\n * @returns A function that can be used as an event handler\n *\n * @example\n * ```ts\n * const handler = createHotkeyHandler('Mod+S', (event, { hotkey, parsedHotkey }) => {\n * console.log(`${hotkey} was pressed`)\n * handleSave()\n * })\n *\n * document.addEventListener('keydown', handler)\n * ```\n */\nexport function createHotkeyHandler(\n hotkey: Hotkey | ParsedHotkey,\n callback: HotkeyCallback,\n options: CreateHotkeyHandlerOptions = {},\n): (event: KeyboardEvent) => void {\n const { preventDefault = true, stopPropagation = true, platform } = options\n const resolvedPlatform = platform ?? detectPlatform()\n\n const hotkeyString: Hotkey =\n typeof hotkey === 'string' ? hotkey : formatParsedHotkey(hotkey)\n const parsed =\n typeof hotkey === 'string' ? parseHotkey(hotkey, resolvedPlatform) : hotkey\n\n const context: HotkeyCallbackContext = {\n hotkey: hotkeyString,\n parsedHotkey: parsed,\n }\n\n return (event: KeyboardEvent) => {\n if (matchesKeyboardEvent(event, parsed, resolvedPlatform)) {\n if (preventDefault) {\n event.preventDefault()\n }\n if (stopPropagation) {\n event.stopPropagation()\n }\n callback(event, context)\n }\n }\n}\n\nexport type MultiHotkeyHandler = { [K in Hotkey]?: HotkeyCallback }\n\n/**\n * Creates a handler that matches multiple hotkeys.\n *\n * @param handlers - A map of hotkey strings to their handlers\n * @param options - Options for matching and handling\n * @returns A function that can be used as an event handler\n *\n * @example\n * ```ts\n * const handler = createMultiHotkeyHandler({\n * 'Mod+S': (event, { hotkey }) => handleSave(),\n * 'Mod+Z': (event, { hotkey }) => handleUndo(),\n * 'Mod+Shift+Z': (event, { hotkey }) => handleRedo(),\n * })\n *\n * document.addEventListener('keydown', handler)\n * ```\n */\nexport function createMultiHotkeyHandler(\n handlers: MultiHotkeyHandler,\n options: CreateHotkeyHandlerOptions = {},\n): (event: KeyboardEvent) => void {\n const { preventDefault = true, stopPropagation = true, platform } = options\n const resolvedPlatform = platform ?? detectPlatform()\n\n // Pre-parse all hotkeys for efficiency\n const parsedHandlers = Object.entries(handlers)\n .filter((entry): entry is [string, HotkeyCallback] => Boolean(entry[1]))\n .map(([hotkey, handler]) => {\n const parsed = parseHotkey(hotkey as Hotkey, resolvedPlatform)\n const context: HotkeyCallbackContext = {\n hotkey: hotkey as Hotkey,\n parsedHotkey: parsed,\n }\n return { parsed, handler, context }\n })\n\n return (event: KeyboardEvent) => {\n for (const { parsed, handler, context } of parsedHandlers) {\n if (matchesKeyboardEvent(event, parsed, resolvedPlatform)) {\n if (preventDefault) {\n event.preventDefault()\n }\n if (stopPropagation) {\n event.stopPropagation()\n }\n handler(event, context)\n return // Only handle the first match\n }\n }\n }\n}\n\n/**\n * Formats a ParsedHotkey back to a hotkey string.\n * Used internally to provide the hotkey string in callback context.\n */\nfunction formatParsedHotkey(parsed: ParsedHotkey): Hotkey {\n const parts: Array<string> = []\n\n if (parsed.ctrl) parts.push('Control')\n if (parsed.alt) parts.push('Alt')\n if (parsed.shift) parts.push('Shift')\n if (parsed.meta) parts.push('Meta')\n parts.push(parsed.code !== undefined ? `[${parsed.code}]` : parsed.key)\n\n return parts.join('+') as Hotkey\n}\n\n/**\n * Compares normalized binding identity, including all four modifiers.\n * Aliases resolve on the supplied platform. A physical code and a logical key\n * remain distinct even when one keyboard event could match both.\n */\nexport function areHotkeysEqual(\n left: RegisterableHotkey,\n right: RegisterableHotkey,\n platform = detectPlatform(),\n): boolean {\n const a = parseRegisterableHotkey(left, platform)\n const b = parseRegisterableHotkey(right, platform)\n return (\n a.ctrl === b.ctrl &&\n a.alt === b.alt &&\n a.shift === b.shift &&\n a.meta === b.meta &&\n (a.code !== undefined || b.code !== undefined\n ? a.code === b.code\n : keysEqual(a.key, b.key))\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,SAAgB,qBACd,OACA,QACA,WAAwC,gBAAgB,EAC/C;AACT,QAAO,mBAAmB,OAAO,QAAQ,SAAS,CAAC;;;;;;;;;;;;;;;;;;;;AAiCrD,SAAgB,oBACd,QACA,UACA,UAAsC,EAAE,EACR;CAChC,MAAM,EAAE,iBAAiB,MAAM,kBAAkB,MAAM,aAAa;CACpE,MAAM,mBAAmB,YAAY,gBAAgB;CAErD,MAAM,eACJ,OAAO,WAAW,WAAW,SAAS,mBAAmB,OAAO;CAClE,MAAM,SACJ,OAAO,WAAW,WAAW,YAAY,QAAQ,iBAAiB,GAAG;CAEvE,MAAM,UAAiC;EACrC,QAAQ;EACR,cAAc;EACf;AAED,SAAQ,UAAyB;AAC/B,MAAI,qBAAqB,OAAO,QAAQ,iBAAiB,EAAE;AACzD,OAAI,eACF,OAAM,gBAAgB;AAExB,OAAI,gBACF,OAAM,iBAAiB;AAEzB,YAAS,OAAO,QAAQ;;;;;;;;;;;;;;;;;;;;;;AAyB9B,SAAgB,yBACd,UACA,UAAsC,EAAE,EACR;CAChC,MAAM,EAAE,iBAAiB,MAAM,kBAAkB,MAAM,aAAa;CACpE,MAAM,mBAAmB,YAAY,gBAAgB;CAGrD,MAAM,iBAAiB,OAAO,QAAQ,SAAS,CAC5C,QAAQ,UAA6C,QAAQ,MAAM,GAAG,CAAC,CACvE,KAAK,CAAC,QAAQ,aAAa;EAC1B,MAAM,SAAS,YAAY,QAAkB,iBAAiB;AAK9D,SAAO;GAAE;GAAQ;GAAS,SAJa;IAC7B;IACR,cAAc;IACf;GACkC;GACnC;AAEJ,SAAQ,UAAyB;AAC/B,OAAK,MAAM,EAAE,QAAQ,SAAS,aAAa,eACzC,KAAI,qBAAqB,OAAO,QAAQ,iBAAiB,EAAE;AACzD,OAAI,eACF,OAAM,gBAAgB;AAExB,OAAI,gBACF,OAAM,iBAAiB;AAEzB,WAAQ,OAAO,QAAQ;AACvB;;;;;;;;AAUR,SAAS,mBAAmB,QAA8B;CACxD,MAAM,QAAuB,EAAE;AAE/B,KAAI,OAAO,KAAM,OAAM,KAAK,UAAU;AACtC,KAAI,OAAO,IAAK,OAAM,KAAK,MAAM;AACjC,KAAI,OAAO,MAAO,OAAM,KAAK,QAAQ;AACrC,KAAI,OAAO,KAAM,OAAM,KAAK,OAAO;AACnC,OAAM,KAAK,OAAO,SAAS,SAAY,IAAI,OAAO,KAAK,KAAK,OAAO,IAAI;AAEvE,QAAO,MAAM,KAAK,IAAI;;;;;;;AAQxB,SAAgB,gBACd,MACA,OACA,WAAW,gBAAgB,EAClB;CACT,MAAM,IAAI,wBAAwB,MAAM,SAAS;CACjD,MAAM,IAAI,wBAAwB,OAAO,SAAS;AAClD,QACE,EAAE,SAAS,EAAE,QACb,EAAE,QAAQ,EAAE,OACZ,EAAE,UAAU,EAAE,SACd,EAAE,SAAS,EAAE,SACZ,EAAE,SAAS,UAAa,EAAE,SAAS,SAChC,EAAE,SAAS,EAAE,OACb,UAAU,EAAE,KAAK,EAAE,IAAI"}
|
package/dist/parse.cjs
DELETED
|
@@ -1,245 +0,0 @@
|
|
|
1
|
-
const require_constants = require('./constants.cjs');
|
|
2
|
-
const require_platform = require('./platform.cjs');
|
|
3
|
-
const require__keyboard_event = require('./_keyboard-event.cjs');
|
|
4
|
-
|
|
5
|
-
//#region src/parse.ts
|
|
6
|
-
/**
|
|
7
|
-
* Parses a hotkey string into its component parts.
|
|
8
|
-
*
|
|
9
|
-
* @param hotkey - The hotkey string to parse (e.g., 'Mod+Shift+S')
|
|
10
|
-
* @param platform - The target platform for resolving 'Mod' (defaults to auto-detection)
|
|
11
|
-
* @returns A ParsedHotkey with either logical key or physical code and modifier flags
|
|
12
|
-
*
|
|
13
|
-
* @example
|
|
14
|
-
* ```ts
|
|
15
|
-
* parseHotkey('Mod+S') // On Mac: { key: 'S', ctrl: false, shift: false, alt: false, meta: true, modifiers: ['Meta'] }
|
|
16
|
-
* parseHotkey('Mod+S') // On Windows: { key: 'S', ctrl: true, shift: false, alt: false, meta: false, modifiers: ['Control'] }
|
|
17
|
-
* parseHotkey('Control+Shift+A') // { key: 'A', ctrl: true, shift: true, alt: false, meta: false, modifiers: ['Control', 'Shift'] }
|
|
18
|
-
* ```
|
|
19
|
-
*/
|
|
20
|
-
function parseHotkey(hotkey, platform = require_platform.detectPlatform()) {
|
|
21
|
-
const parts = require__keyboard_event.splitHotkeyParts(hotkey);
|
|
22
|
-
const modifiers = /* @__PURE__ */ new Set();
|
|
23
|
-
let key = "";
|
|
24
|
-
for (let i = 0; i < parts.length; i++) {
|
|
25
|
-
const part = parts[i].trim();
|
|
26
|
-
if (i === parts.length - 1) key = require_constants.normalizeKeyName(part);
|
|
27
|
-
else {
|
|
28
|
-
const alias = require_constants.MODIFIER_ALIASES[part] ?? require_constants.MODIFIER_ALIASES[part.toLowerCase()];
|
|
29
|
-
if (alias) {
|
|
30
|
-
const resolved = require_platform.resolveModifier(alias, platform);
|
|
31
|
-
modifiers.add(resolved);
|
|
32
|
-
} else if (parts.length === 1) key = require_constants.normalizeKeyName(part);
|
|
33
|
-
}
|
|
34
|
-
}
|
|
35
|
-
if (!key && parts.length > 0) key = require_constants.normalizeKeyName(parts[parts.length - 1].trim());
|
|
36
|
-
const code = /^\[([A-Za-z][A-Za-z0-9]*)\]$/.exec(key)?.[1];
|
|
37
|
-
return {
|
|
38
|
-
...code !== void 0 ? { code } : { key },
|
|
39
|
-
ctrl: modifiers.has("Control"),
|
|
40
|
-
shift: modifiers.has("Shift"),
|
|
41
|
-
alt: modifiers.has("Alt"),
|
|
42
|
-
meta: modifiers.has("Meta"),
|
|
43
|
-
modifiers: require_constants.MODIFIER_ORDER.filter((m) => modifiers.has(m))
|
|
44
|
-
};
|
|
45
|
-
}
|
|
46
|
-
/**
|
|
47
|
-
* Converts a RawHotkey object to a ParsedHotkey.
|
|
48
|
-
* Optional modifier booleans default to false; modifiers array is derived from them.
|
|
49
|
-
* When `mod` is true, it is resolved to Control or Meta based on platform.
|
|
50
|
-
*
|
|
51
|
-
* @param raw - The raw hotkey object
|
|
52
|
-
* @param platform - The target platform for resolving 'Mod' (defaults to auto-detection)
|
|
53
|
-
* @returns A ParsedHotkey suitable for matching and formatting
|
|
54
|
-
*
|
|
55
|
-
* @example
|
|
56
|
-
* ```ts
|
|
57
|
-
* rawHotkeyToParsedHotkey({ key: 'Escape' })
|
|
58
|
-
* // { key: 'Escape', ctrl: false, shift: false, alt: false, meta: false, modifiers: [] }
|
|
59
|
-
*
|
|
60
|
-
* rawHotkeyToParsedHotkey({ key: 'S', mod: true }, 'mac')
|
|
61
|
-
* // { key: 'S', ctrl: false, shift: false, alt: false, meta: true, modifiers: ['Meta'] }
|
|
62
|
-
*
|
|
63
|
-
* rawHotkeyToParsedHotkey({ key: 'S', mod: true, shift: true }, 'windows')
|
|
64
|
-
* // { key: 'S', ctrl: true, shift: true, alt: false, meta: false, modifiers: ['Control', 'Shift'] }
|
|
65
|
-
* ```
|
|
66
|
-
*/
|
|
67
|
-
function rawHotkeyToParsedHotkey(raw, platform = require_platform.detectPlatform()) {
|
|
68
|
-
if (raw.code === void 0) require__keyboard_event.assertLogicalKey(raw.key);
|
|
69
|
-
let ctrl = raw.ctrl ?? false;
|
|
70
|
-
const shift = raw.shift ?? false;
|
|
71
|
-
const alt = raw.alt ?? false;
|
|
72
|
-
let meta = raw.meta ?? false;
|
|
73
|
-
if (raw.mod) if (require_platform.resolveModifier("Mod", platform) === "Control") ctrl = true;
|
|
74
|
-
else meta = true;
|
|
75
|
-
const modifiers = require_constants.MODIFIER_ORDER.filter((m) => {
|
|
76
|
-
switch (m) {
|
|
77
|
-
case "Control": return ctrl;
|
|
78
|
-
case "Shift": return shift;
|
|
79
|
-
case "Alt": return alt;
|
|
80
|
-
case "Meta": return meta;
|
|
81
|
-
default: return false;
|
|
82
|
-
}
|
|
83
|
-
});
|
|
84
|
-
return {
|
|
85
|
-
...raw.code !== void 0 ? { code: raw.code } : { key: require_constants.normalizeKeyName(raw.key) },
|
|
86
|
-
ctrl,
|
|
87
|
-
shift,
|
|
88
|
-
alt,
|
|
89
|
-
meta,
|
|
90
|
-
modifiers
|
|
91
|
-
};
|
|
92
|
-
}
|
|
93
|
-
/**
|
|
94
|
-
* Serializes a parsed hotkey to the canonical string form used for registration
|
|
95
|
-
* and storage: `Mod` first when the platform allows, then `Alt`, then `Shift`;
|
|
96
|
-
* otherwise full `Control+Alt+Shift+Meta` order.
|
|
97
|
-
*/
|
|
98
|
-
function normalizedHotkeyStringFromParsed(parsed, platform) {
|
|
99
|
-
if (parsed.code === void 0) require__keyboard_event.assertLogicalKey(parsed.key);
|
|
100
|
-
const canUseMod = platform === "mac" ? parsed.meta && !parsed.ctrl : parsed.ctrl && !parsed.meta;
|
|
101
|
-
const parts = [];
|
|
102
|
-
if (canUseMod) {
|
|
103
|
-
parts.push("Mod");
|
|
104
|
-
if (parsed.alt) parts.push("Alt");
|
|
105
|
-
if (parsed.shift) parts.push("Shift");
|
|
106
|
-
} else for (const modifier of require_constants.MODIFIER_ORDER) if (parsed.modifiers.includes(modifier)) parts.push(modifier);
|
|
107
|
-
parts.push(parsed.code !== void 0 ? `[${parsed.code}]` : require_constants.normalizeKeyName(parsed.key));
|
|
108
|
-
return parts.join("+");
|
|
109
|
-
}
|
|
110
|
-
/**
|
|
111
|
-
* Normalizes a hotkey string to its canonical form.
|
|
112
|
-
*
|
|
113
|
-
* - When `Mod` is allowed for the platform (Command on Mac without Control;
|
|
114
|
-
* Control on Windows/Linux without Meta): emits `Mod`, then `Alt`, then `Shift`,
|
|
115
|
-
* then the key (e.g. `Mod+Shift+E`, `Mod+S`).
|
|
116
|
-
* - Otherwise: literal modifiers in `Control+Alt+Shift+Meta` order, then the key.
|
|
117
|
-
* - Resolves aliases and normalizes key casing (e.g. `esc` → `Escape`, `a` → `A`).
|
|
118
|
-
*
|
|
119
|
-
* @param hotkey - The hotkey string to normalize
|
|
120
|
-
* @param platform - The target platform for resolving `Mod` (defaults to auto-detection)
|
|
121
|
-
* @returns The normalized hotkey string
|
|
122
|
-
*
|
|
123
|
-
* @example
|
|
124
|
-
* ```ts
|
|
125
|
-
* normalizeHotkey('shift+meta+e', 'mac') // 'Mod+Shift+E'
|
|
126
|
-
* normalizeHotkey('ctrl+a', 'windows') // 'Mod+A'
|
|
127
|
-
* normalizeHotkey('esc') // 'Escape'
|
|
128
|
-
* ```
|
|
129
|
-
*/
|
|
130
|
-
function normalizeHotkey(hotkey, platform = require_platform.detectPlatform()) {
|
|
131
|
-
return normalizedHotkeyStringFromParsed(parseHotkey(hotkey, platform), platform);
|
|
132
|
-
}
|
|
133
|
-
/**
|
|
134
|
-
* Same canonical string as {@link normalizeHotkey}, but from an already-parsed hotkey.
|
|
135
|
-
*/
|
|
136
|
-
function normalizeHotkeyFromParsed(parsed, platform = require_platform.detectPlatform()) {
|
|
137
|
-
return normalizedHotkeyStringFromParsed(parsed, platform);
|
|
138
|
-
}
|
|
139
|
-
/**
|
|
140
|
-
* Normalizes a string or {@link RawHotkey} object to the same canonical hotkey string.
|
|
141
|
-
* Use this in framework adapters instead of branching on `formatHotkey(rawHotkeyToParsedHotkey(...))`.
|
|
142
|
-
*/
|
|
143
|
-
function normalizeRegisterableHotkey(hotkey, platform = require_platform.detectPlatform()) {
|
|
144
|
-
return typeof hotkey === "string" ? normalizeHotkey(hotkey, platform) : normalizeHotkeyFromParsed(rawHotkeyToParsedHotkey(hotkey, platform), platform);
|
|
145
|
-
}
|
|
146
|
-
/**
|
|
147
|
-
* Checks if a string is a recognized modifier token (including aliases).
|
|
148
|
-
*
|
|
149
|
-
* For a `KeyboardEvent`, use `isModifier(normalizeKeyName(event.key))` so DOM
|
|
150
|
-
* spellings like `OS` / `Win` match the same alias table.
|
|
151
|
-
*
|
|
152
|
-
* @param key - Key name or alias (e.g. from a hotkey string or `event.key`)
|
|
153
|
-
* @returns True if the string is a recognized modifier
|
|
154
|
-
*/
|
|
155
|
-
function isModifierKey(key) {
|
|
156
|
-
return key in require_constants.MODIFIER_ALIASES || key.toLowerCase() in require_constants.MODIFIER_ALIASES;
|
|
157
|
-
}
|
|
158
|
-
/**
|
|
159
|
-
* Parses a KeyboardEvent into a ParsedHotkey object.
|
|
160
|
-
*
|
|
161
|
-
* This function extracts the key and modifier state from a keyboard event
|
|
162
|
-
* and converts it into the same format used by `parseHotkey()`.
|
|
163
|
-
*
|
|
164
|
-
* @param event - The KeyboardEvent to parse
|
|
165
|
-
* @param platform - The target platform for resolving modifiers (defaults to auto-detection)
|
|
166
|
-
* @returns A ParsedHotkey object representing the keyboard event
|
|
167
|
-
*
|
|
168
|
-
* @example
|
|
169
|
-
* ```ts
|
|
170
|
-
* document.addEventListener('keydown', (event) => {
|
|
171
|
-
* const parsed = parseKeyboardEvent(event)
|
|
172
|
-
* console.log(parsed) // { key: 'S', ctrl: true, shift: false, ... }
|
|
173
|
-
* })
|
|
174
|
-
* ```
|
|
175
|
-
*/
|
|
176
|
-
function parseKeyboardEvent(event, platform) {
|
|
177
|
-
const normalized = require__keyboard_event.normalizeKeyboardEvent(event, platform);
|
|
178
|
-
const ctrl = normalized.altGraph ? false : normalized.ctrl;
|
|
179
|
-
const alt = normalized.altGraph ? false : normalized.alt;
|
|
180
|
-
const shift = normalized.shift;
|
|
181
|
-
const modifiers = [];
|
|
182
|
-
if (ctrl) modifiers.push("Control");
|
|
183
|
-
if (alt) modifiers.push("Alt");
|
|
184
|
-
if (shift) modifiers.push("Shift");
|
|
185
|
-
if (normalized.meta) modifiers.push("Meta");
|
|
186
|
-
return {
|
|
187
|
-
key: normalized.key,
|
|
188
|
-
ctrl,
|
|
189
|
-
shift,
|
|
190
|
-
alt,
|
|
191
|
-
meta: normalized.meta,
|
|
192
|
-
modifiers
|
|
193
|
-
};
|
|
194
|
-
}
|
|
195
|
-
/**
|
|
196
|
-
* Normalizes a keyboard event to the same canonical hotkey string as {@link normalizeHotkey}.
|
|
197
|
-
*
|
|
198
|
-
* @param event - The keyboard event (typically `keydown`)
|
|
199
|
-
* @param platform - Target platform for `Mod` eligibility
|
|
200
|
-
*/
|
|
201
|
-
function normalizeHotkeyFromEvent(event, platform = require_platform.detectPlatform()) {
|
|
202
|
-
return normalizedHotkeyStringFromParsed(parseKeyboardEvent(event, platform), platform);
|
|
203
|
-
}
|
|
204
|
-
/**
|
|
205
|
-
* Checks if a hotkey or ParsedHotkey contains at least one non-modifier key.
|
|
206
|
-
*
|
|
207
|
-
* This is useful for validating that a recorded hotkey is complete and not
|
|
208
|
-
* just a combination of modifiers without an action key.
|
|
209
|
-
*
|
|
210
|
-
* @param hotkey - The hotkey string or ParsedHotkey to check
|
|
211
|
-
* @param platform - The target platform for parsing (defaults to auto-detection)
|
|
212
|
-
* @returns True if the hotkey contains at least one non-modifier key
|
|
213
|
-
*
|
|
214
|
-
* @example
|
|
215
|
-
* ```ts
|
|
216
|
-
* hasNonModifierKey('Control+Shift+S') // true
|
|
217
|
-
* hasNonModifierKey('Control+Shift') // false (no action key)
|
|
218
|
-
* hasNonModifierKey(parseHotkey('Mod+A')) // true
|
|
219
|
-
* ```
|
|
220
|
-
*/
|
|
221
|
-
function hasNonModifierKey(hotkey, platform = require_platform.detectPlatform()) {
|
|
222
|
-
const parsed = typeof hotkey === "string" ? parseHotkey(hotkey, platform) : hotkey;
|
|
223
|
-
if (parsed.code !== void 0) return parsed.code.length > 0 && !/^(Control|Shift|Alt|Meta)(Left|Right)$/.test(parsed.code);
|
|
224
|
-
return !isModifierKey(parsed.key) && parsed.key.length > 0;
|
|
225
|
-
}
|
|
226
|
-
/**
|
|
227
|
-
* Parses a string or raw binding, resolving Mod for the supplied platform.
|
|
228
|
-
* Physical tokens such as `[KeyQ]` retain `code`; they never become logical Q.
|
|
229
|
-
*/
|
|
230
|
-
function parseRegisterableHotkey(hotkey, platform = require_platform.detectPlatform()) {
|
|
231
|
-
return typeof hotkey === "string" ? parseHotkey(hotkey, platform) : rawHotkeyToParsedHotkey(hotkey, platform);
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
//#endregion
|
|
235
|
-
exports.hasNonModifierKey = hasNonModifierKey;
|
|
236
|
-
exports.isModifierKey = isModifierKey;
|
|
237
|
-
exports.normalizeHotkey = normalizeHotkey;
|
|
238
|
-
exports.normalizeHotkeyFromEvent = normalizeHotkeyFromEvent;
|
|
239
|
-
exports.normalizeHotkeyFromParsed = normalizeHotkeyFromParsed;
|
|
240
|
-
exports.normalizeRegisterableHotkey = normalizeRegisterableHotkey;
|
|
241
|
-
exports.parseHotkey = parseHotkey;
|
|
242
|
-
exports.parseKeyboardEvent = parseKeyboardEvent;
|
|
243
|
-
exports.parseRegisterableHotkey = parseRegisterableHotkey;
|
|
244
|
-
exports.rawHotkeyToParsedHotkey = rawHotkeyToParsedHotkey;
|
|
245
|
-
//# sourceMappingURL=parse.cjs.map
|