@tanstack/hotkeys 0.4.1 → 0.4.3

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 CHANGED
@@ -58,7 +58,7 @@ Type-safe keyboard shortcuts for the web. Template-string bindings, parsed objec
58
58
  > - [**Solid Hotkeys**](https://tanstack.com/hotkeys/latest/docs/framework/solid/reference)
59
59
  > - [**Angular Hotkeys**](https://tanstack.com/hotkeys/latest/docs/framework/angular/reference)
60
60
  > - [**Vue Hotkeys**](https://tanstack.com/hotkeys/latest/docs/framework/vue/reference)
61
- > - Svelte Hotkeys – needs a contributor!
61
+ > - [**Svelte Hotkeys**](https://tanstack.com/hotkeys/latest/docs/framework/svelte/reference)
62
62
 
63
63
  ## Get Involved
64
64
 
@@ -243,9 +243,31 @@ const PUNCTUATION_KEYS = new Set([
243
243
  "-",
244
244
  ",",
245
245
  ".",
246
+ ";",
246
247
  "`"
247
248
  ]);
248
249
  /**
250
+ * Maps `KeyboardEvent.code` values for punctuation keys to their canonical characters.
251
+ *
252
+ * On macOS, holding the Option (Alt) key transforms punctuation keys into special characters
253
+ * (e.g., Option+Minus → en-dash '–'), causing `event.key` to differ from the expected character.
254
+ * However, `event.code` still reports the physical key (e.g., 'Minus'). This map enables
255
+ * falling back to `event.code` for punctuation keys, similar to the existing `Key*`/`Digit*`
256
+ * fallbacks for letters and digits.
257
+ */
258
+ const PUNCTUATION_CODE_MAP = {
259
+ Minus: "-",
260
+ Equal: "=",
261
+ Slash: "/",
262
+ BracketLeft: "[",
263
+ BracketRight: "]",
264
+ Backslash: "\\",
265
+ Comma: ",",
266
+ Period: ".",
267
+ Backquote: "`",
268
+ Semicolon: ";"
269
+ };
270
+ /**
249
271
  * Set of all valid non-modifier keys.
250
272
  *
251
273
  * This is the union of all key type sets (letters, numbers, function keys, navigation,
@@ -442,6 +464,7 @@ exports.MODIFIER_KEYS = MODIFIER_KEYS;
442
464
  exports.MODIFIER_ORDER = MODIFIER_ORDER;
443
465
  exports.NAVIGATION_KEYS = NAVIGATION_KEYS;
444
466
  exports.NUMBER_KEYS = NUMBER_KEYS;
467
+ exports.PUNCTUATION_CODE_MAP = PUNCTUATION_CODE_MAP;
445
468
  exports.PUNCTUATION_KEYS = PUNCTUATION_KEYS;
446
469
  exports.STANDARD_MODIFIER_LABELS = STANDARD_MODIFIER_LABELS;
447
470
  exports.detectPlatform = detectPlatform;
@@ -1 +1 @@
1
- {"version":3,"file":"constants.cjs","names":[],"sources":["../src/constants.ts"],"sourcesContent":["import type {\n CanonicalModifier,\n EditingKey,\n FunctionKey,\n LetterKey,\n NavigationKey,\n NumberKey,\n PunctuationKey,\n} from './hotkey'\n\n// =============================================================================\n// Platform Detection\n// =============================================================================\n\n/**\n * Detects the current platform based on browser navigator properties.\n *\n * Used internally to resolve platform-adaptive modifiers like 'Mod' (Command on Mac,\n * Control elsewhere) and for platform-specific hotkey formatting.\n *\n * @returns The detected platform: 'mac', 'windows', or 'linux'\n * @remarks Defaults to 'linux' in SSR environments where navigator is undefined\n *\n * @example\n * ```ts\n * const platform = detectPlatform() // 'mac' | 'windows' | 'linux'\n * const modifier = resolveModifier('Mod', platform) // 'Meta' on Mac, 'Control' elsewhere\n * ```\n */\nexport function detectPlatform(): 'mac' | 'windows' | 'linux' {\n if (typeof navigator === 'undefined') {\n return 'linux' // Default for SSR\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n const platform = navigator.platform?.toLowerCase() ?? ''\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n const userAgent = navigator.userAgent?.toLowerCase() ?? ''\n\n if (platform.includes('mac') || userAgent.includes('mac')) {\n return 'mac'\n }\n if (platform.includes('win') || userAgent.includes('win')) {\n return 'windows'\n }\n return 'linux'\n}\n\n// =============================================================================\n// Modifier Aliases\n// =============================================================================\n\n/**\n * Canonical order for modifiers in normalized hotkey strings.\n *\n * Defines the standard order in which modifiers should appear when formatting\n * hotkeys. This ensures consistent, predictable output across the library.\n *\n * Order: Control → Alt → Shift → Meta\n *\n * @example\n * ```ts\n * // Input: 'Shift+Control+Meta+S'\n * // Normalized: 'Control+Alt+Shift+Meta+S' (following MODIFIER_ORDER)\n * ```\n */\nexport const MODIFIER_ORDER: Array<CanonicalModifier> = [\n 'Control',\n 'Alt',\n 'Shift',\n 'Meta',\n]\n\n/**\n * Set of canonical modifier key names for fast lookup.\n *\n * Derived from `MODIFIER_ORDER` to ensure consistency. Used to detect when\n * a modifier is released so we can clear non-modifier keys whose keyup events\n * may have been swallowed by the OS (e.g. macOS Cmd+key combos).\n */\nexport const MODIFIER_KEYS = new Set<string>(MODIFIER_ORDER)\n\n/**\n * Maps modifier key aliases to their canonical form or platform-adaptive 'Mod'.\n *\n * This map allows users to write hotkeys using various aliases (e.g., 'Ctrl', 'Cmd', 'Option')\n * which are then normalized to canonical names ('Control', 'Meta', 'Alt') or the\n * platform-adaptive 'Mod' token.\n *\n * The 'Mod' and 'CommandOrControl' aliases are resolved at runtime via `resolveModifier()`\n * based on the detected platform (Command on Mac, Control elsewhere).\n *\n * @remarks Case-insensitive lookups are supported via lowercase variants\n *\n * @example\n * ```ts\n * MODIFIER_ALIASES['Ctrl'] // 'Control'\n * MODIFIER_ALIASES['Cmd'] // 'Meta'\n * MODIFIER_ALIASES['Mod'] // 'Mod' (resolved at runtime)\n * ```\n */\nexport const MODIFIER_ALIASES: Record<string, CanonicalModifier | 'Mod'> = {\n // Control variants\n Control: 'Control',\n Ctrl: 'Control',\n control: 'Control',\n ctrl: 'Control',\n\n // Shift variants\n Shift: 'Shift',\n shift: 'Shift',\n\n // Alt variants\n Alt: 'Alt',\n Option: 'Alt',\n alt: 'Alt',\n option: 'Alt',\n\n // Meta/Command variants\n Command: 'Meta',\n Cmd: 'Meta',\n Meta: 'Meta',\n command: 'Meta',\n cmd: 'Meta',\n meta: 'Meta',\n\n // Platform-adaptive (resolved at runtime)\n CommandOrControl: 'Mod',\n Mod: 'Mod',\n commandorcontrol: 'Mod',\n mod: 'Mod',\n}\n\n/**\n * Resolves the platform-adaptive 'Mod' modifier to the appropriate canonical modifier.\n *\n * The 'Mod' token represents the \"primary modifier\" on each platform:\n * - macOS: 'Meta' (Command key ⌘)\n * - Windows/Linux: 'Control' (Ctrl key)\n *\n * This enables cross-platform hotkey definitions like 'Mod+S' that automatically\n * map to Command+S on Mac and Ctrl+S on Windows/Linux.\n *\n * @param modifier - The modifier to resolve. If 'Mod', resolves based on platform.\n * @param platform - The target platform. Defaults to auto-detection.\n * @returns The canonical modifier name ('Control', 'Shift', 'Alt', or 'Meta')\n *\n * @example\n * ```ts\n * resolveModifier('Mod', 'mac') // 'Meta'\n * resolveModifier('Mod', 'windows') // 'Control'\n * resolveModifier('Control', 'mac') // 'Control' (unchanged)\n * ```\n */\nexport function resolveModifier(\n modifier: CanonicalModifier | 'Mod',\n platform: 'mac' | 'windows' | 'linux' = detectPlatform(),\n): CanonicalModifier {\n if (modifier === 'Mod') {\n return platform === 'mac' ? 'Meta' : 'Control'\n }\n return modifier\n}\n\n// =============================================================================\n// Valid Keys\n// =============================================================================\n\n/**\n * Set of all valid letter keys (A-Z).\n *\n * Used for validation and type checking. Letter keys are matched case-insensitively\n * in hotkey matching, but normalized to uppercase in canonical form.\n */\nexport const LETTER_KEYS = new Set<LetterKey>([\n 'A',\n 'B',\n 'C',\n 'D',\n 'E',\n 'F',\n 'G',\n 'H',\n 'I',\n 'J',\n 'K',\n 'L',\n 'M',\n 'N',\n 'O',\n 'P',\n 'Q',\n 'R',\n 'S',\n 'T',\n 'U',\n 'V',\n 'W',\n 'X',\n 'Y',\n 'Z',\n])\n\n/**\n * Set of all valid number keys (0-9).\n *\n * Note: Number keys are affected by Shift (Shift+1 → '!' on US layout),\n * so they're excluded from Shift-based hotkey combinations to avoid\n * layout-dependent behavior.\n */\nexport const NUMBER_KEYS = new Set<NumberKey>([\n '0',\n '1',\n '2',\n '3',\n '4',\n '5',\n '6',\n '7',\n '8',\n '9',\n])\n\n/**\n * Set of all valid function keys (F1-F12).\n *\n * Function keys are commonly used for system shortcuts (e.g., F12 for DevTools,\n * Alt+F4 to close windows) and application-specific commands.\n */\nexport const FUNCTION_KEYS = new Set<FunctionKey>([\n 'F1',\n 'F2',\n 'F3',\n 'F4',\n 'F5',\n 'F6',\n 'F7',\n 'F8',\n 'F9',\n 'F10',\n 'F11',\n 'F12',\n])\n\n/**\n * Set of all valid navigation keys for cursor movement and document navigation.\n *\n * Includes arrow keys, Home/End (line navigation), and PageUp/PageDown (page navigation).\n * These keys are commonly combined with modifiers for selection (Shift+ArrowUp) or\n * navigation shortcuts (Alt+ArrowLeft for back).\n */\nexport const NAVIGATION_KEYS = new Set<NavigationKey>([\n 'ArrowUp',\n 'ArrowDown',\n 'ArrowLeft',\n 'ArrowRight',\n 'Home',\n 'End',\n 'PageUp',\n 'PageDown',\n])\n\n/**\n * Set of all valid editing and special keys.\n *\n * Includes keys commonly used for text editing (Enter, Backspace, Delete, Tab) and\n * special actions (Escape, Space). These keys are frequently combined with modifiers\n * for editor shortcuts (Mod+Enter to submit, Shift+Tab to go back).\n */\nexport const EDITING_KEYS = new Set<EditingKey>([\n 'Enter',\n 'Escape',\n 'Space',\n 'Tab',\n 'Backspace',\n 'Delete',\n])\n\n/**\n * Set of all valid punctuation keys commonly used in keyboard shortcuts.\n *\n * These are the literal characters as they appear in `KeyboardEvent.key` (layout-dependent,\n * typically US keyboard layout). Common shortcuts include:\n * - `Mod+/` - Toggle comment\n * - `Mod+[` / `Mod+]` - Indent/outdent\n * - `Mod+=` / `Mod+-` - Zoom in/out\n *\n * Note: Punctuation keys are affected by Shift (Shift+',' → '<' on US layout),\n * so they're excluded from Shift-based hotkey combinations to avoid layout-dependent behavior.\n */\nexport const PUNCTUATION_KEYS = new Set<PunctuationKey>([\n '/',\n '[',\n ']',\n '\\\\',\n '=',\n '-',\n ',',\n '.',\n '`',\n])\n\n/**\n * Set of all valid non-modifier keys.\n *\n * This is the union of all key type sets (letters, numbers, function keys, navigation,\n * editing, and punctuation). Used primarily for validation to check if a key string\n * is recognized and will have type-safe autocomplete support.\n *\n * @see {@link LETTER_KEYS}\n * @see {@link NUMBER_KEYS}\n * @see {@link FUNCTION_KEYS}\n * @see {@link NAVIGATION_KEYS}\n * @see {@link EDITING_KEYS}\n * @see {@link PUNCTUATION_KEYS}\n */\nexport const ALL_KEYS = new Set([\n ...LETTER_KEYS,\n ...NUMBER_KEYS,\n ...FUNCTION_KEYS,\n ...NAVIGATION_KEYS,\n ...EDITING_KEYS,\n ...PUNCTUATION_KEYS,\n])\n\n/**\n * Maps key name aliases to their canonical form.\n *\n * Handles common variations and alternative names for keys to provide a more\n * forgiving API. For example, users can write 'Esc', 'esc', or 'escape' and\n * they'll all normalize to 'Escape'.\n *\n * This map is used internally by `normalizeKeyName()` to convert user input\n * into the canonical key names used throughout the library.\n *\n * @remarks Case-insensitive lookups are supported via lowercase variants\n *\n * @example\n * ```ts\n * KEY_ALIASES['Esc'] // 'Escape'\n * KEY_ALIASES['Del'] // 'Delete'\n * KEY_ALIASES['Up'] // 'ArrowUp'\n * ```\n */\nconst KEY_ALIASES: Record<string, string> = {\n // Escape variants\n Esc: 'Escape',\n esc: 'Escape',\n escape: 'Escape',\n\n // Enter variants\n Return: 'Enter',\n return: 'Enter',\n enter: 'Enter',\n\n // Space variants\n ' ': 'Space',\n space: 'Space',\n Spacebar: 'Space',\n spacebar: 'Space',\n\n // Tab variants\n tab: 'Tab',\n\n // Backspace variants\n backspace: 'Backspace',\n\n // Delete variants\n Del: 'Delete',\n del: 'Delete',\n delete: 'Delete',\n\n // Arrow key variants\n Up: 'ArrowUp',\n up: 'ArrowUp',\n arrowup: 'ArrowUp',\n Down: 'ArrowDown',\n down: 'ArrowDown',\n arrowdown: 'ArrowDown',\n Left: 'ArrowLeft',\n left: 'ArrowLeft',\n arrowleft: 'ArrowLeft',\n Right: 'ArrowRight',\n right: 'ArrowRight',\n arrowright: 'ArrowRight',\n\n // Navigation variants\n home: 'Home',\n end: 'End',\n pageup: 'PageUp',\n pagedown: 'PageDown',\n PgUp: 'PageUp',\n PgDn: 'PageDown',\n pgup: 'PageUp',\n pgdn: 'PageDown',\n}\n\n/**\n * Normalizes a key name to its canonical form.\n *\n * Converts various key name formats (aliases, case variations) into the standard\n * canonical names used throughout the library. This enables a more forgiving API\n * where users can write keys in different ways and still get correct behavior.\n *\n * Normalization rules:\n * 1. Check aliases first (e.g., 'Esc' → 'Escape', 'Del' → 'Delete')\n * 2. Single letters → uppercase (e.g., 'a' → 'A', 's' → 'S')\n * 3. Function keys → uppercase (e.g., 'f1' → 'F1', 'F12' → 'F12')\n * 4. Other keys → returned as-is (already canonical or unknown)\n *\n * @param key - The key name to normalize (can be an alias, lowercase, etc.)\n * @returns The canonical key name\n *\n * @example\n * ```ts\n * normalizeKeyName('esc') // 'Escape'\n * normalizeKeyName('a') // 'A'\n * normalizeKeyName('f1') // 'F1'\n * normalizeKeyName('ArrowUp') // 'ArrowUp' (already canonical)\n * ```\n */\nexport function isSingleLetterKey(key: string): boolean {\n return /^\\p{Letter}$/u.test(key)\n}\n\nexport function normalizeKeyName(key: string): string {\n // Check aliases first\n if (key in KEY_ALIASES) {\n return KEY_ALIASES[key]!\n }\n\n if (isSingleLetterKey(key)) {\n const upper = key.toUpperCase()\n // Some Unicode letters (e.g., 'ß') uppercase to multi-character sequences\n // ('SS'). Avoid changing the string length so the rest of the matching\n // logic can rely on a stable single-character key value.\n return upper.length === 1 ? upper : key\n }\n\n // Check if it's a function key (normalize case)\n const upperKey = key.toUpperCase()\n if (/^F([1-9]|1[0-2])$/.test(upperKey)) {\n return upperKey\n }\n\n return key\n}\n\n// =============================================================================\n// Display Symbols\n// =============================================================================\n\n/**\n * Modifier key symbols for macOS display.\n *\n * Used by formatting functions to display hotkeys with macOS-style symbols\n * (e.g., ⌘ for Command, ⌃ for Control) instead of text labels. This provides\n * a native macOS look and feel in hotkey displays.\n *\n * @example\n * ```ts\n * MAC_MODIFIER_SYMBOLS['Meta'] // '⌘'\n * MAC_MODIFIER_SYMBOLS['Control'] // '⌃'\n * MAC_MODIFIER_SYMBOLS['Alt'] // '⌥'\n * MAC_MODIFIER_SYMBOLS['Shift'] // '⇧'\n * ```\n */\nexport const MAC_MODIFIER_SYMBOLS: Record<CanonicalModifier, string> = {\n Control: '⌃',\n Alt: '⌥',\n Shift: '⇧',\n Meta: '⌘',\n}\n\n/**\n * Modifier key labels for Windows/Linux display.\n *\n * Used by formatting functions to display hotkeys with standard text labels\n * (e.g., 'Ctrl' for Control, 'Win' for Meta/Windows key) instead of symbols.\n * This provides a familiar Windows/Linux look and feel in hotkey displays.\n *\n * @example\n * ```ts\n * STANDARD_MODIFIER_LABELS['Control'] // 'Ctrl'\n * STANDARD_MODIFIER_LABELS['Meta'] // 'Win'\n * STANDARD_MODIFIER_LABELS['Alt'] // 'Alt'\n * STANDARD_MODIFIER_LABELS['Shift'] // 'Shift'\n * ```\n */\nexport const STANDARD_MODIFIER_LABELS: Record<CanonicalModifier, string> = {\n Control: 'Ctrl',\n Alt: 'Alt',\n Shift: 'Shift',\n Meta: 'Win',\n}\n\n/**\n * Special key symbols for display formatting.\n *\n * Maps certain keys to their visual symbols for better readability in hotkey displays.\n * Used by formatting functions to show symbols like ↑ for ArrowUp or ↵ for Enter\n * instead of text labels.\n *\n * @example\n * ```ts\n * KEY_DISPLAY_SYMBOLS['ArrowUp'] // '↑'\n * KEY_DISPLAY_SYMBOLS['Enter'] // '↵'\n * KEY_DISPLAY_SYMBOLS['Escape'] // 'Esc'\n * KEY_DISPLAY_SYMBOLS['Space'] // '␣'\n * ```\n */\nexport const KEY_DISPLAY_SYMBOLS: Record<string, string> = {\n ArrowUp: '↑',\n ArrowDown: '↓',\n ArrowLeft: '←',\n ArrowRight: '→',\n Enter: '↵',\n Escape: 'Esc',\n Backspace: '⌫',\n Delete: '⌦',\n Tab: '⇥',\n Space: '␣',\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA6BA,SAAgB,iBAA8C;AAC5D,KAAI,OA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;;;;;;;;AAiBD,MAAa,2BAA8D;CACzE,SAAS;CACT,KAAK;CACL,OAAO;CACP,MAAM;CACP;;;;;;;;;;;;;;;;AAiBD,MAAa,sBAA8C;CACzD,SAAS;CACT,WAAW;CACX,WAAW;CACX,YAAY;CACZ,OAAO;CACP,QAAQ;CACR,WAAW;CACX,QAAQ;CACR,KAAK;CACL,OAAO;CACR"}
1
+ {"version":3,"file":"constants.cjs","names":[],"sources":["../src/constants.ts"],"sourcesContent":["import type {\n CanonicalModifier,\n EditingKey,\n FunctionKey,\n LetterKey,\n NavigationKey,\n NumberKey,\n PunctuationKey,\n} from './hotkey'\n\n// =============================================================================\n// Platform Detection\n// =============================================================================\n\n/**\n * Detects the current platform based on browser navigator properties.\n *\n * Used internally to resolve platform-adaptive modifiers like 'Mod' (Command on Mac,\n * Control elsewhere) and for platform-specific hotkey formatting.\n *\n * @returns The detected platform: 'mac', 'windows', or 'linux'\n * @remarks Defaults to 'linux' in SSR environments where navigator is undefined\n *\n * @example\n * ```ts\n * const platform = detectPlatform() // 'mac' | 'windows' | 'linux'\n * const modifier = resolveModifier('Mod', platform) // 'Meta' on Mac, 'Control' elsewhere\n * ```\n */\nexport function detectPlatform(): 'mac' | 'windows' | 'linux' {\n if (typeof navigator === 'undefined') {\n return 'linux' // Default for SSR\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n const platform = navigator.platform?.toLowerCase() ?? ''\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n const userAgent = navigator.userAgent?.toLowerCase() ?? ''\n\n if (platform.includes('mac') || userAgent.includes('mac')) {\n return 'mac'\n }\n if (platform.includes('win') || userAgent.includes('win')) {\n return 'windows'\n }\n return 'linux'\n}\n\n// =============================================================================\n// Modifier Aliases\n// =============================================================================\n\n/**\n * Canonical order for modifiers in normalized hotkey strings.\n *\n * Defines the standard order in which modifiers should appear when formatting\n * hotkeys. This ensures consistent, predictable output across the library.\n *\n * Order: Control → Alt → Shift → Meta\n *\n * @example\n * ```ts\n * // Input: 'Shift+Control+Meta+S'\n * // Normalized: 'Control+Alt+Shift+Meta+S' (following MODIFIER_ORDER)\n * ```\n */\nexport const MODIFIER_ORDER: Array<CanonicalModifier> = [\n 'Control',\n 'Alt',\n 'Shift',\n 'Meta',\n]\n\n/**\n * Set of canonical modifier key names for fast lookup.\n *\n * Derived from `MODIFIER_ORDER` to ensure consistency. Used to detect when\n * a modifier is released so we can clear non-modifier keys whose keyup events\n * may have been swallowed by the OS (e.g. macOS Cmd+key combos).\n */\nexport const MODIFIER_KEYS = new Set<string>(MODIFIER_ORDER)\n\n/**\n * Maps modifier key aliases to their canonical form or platform-adaptive 'Mod'.\n *\n * This map allows users to write hotkeys using various aliases (e.g., 'Ctrl', 'Cmd', 'Option')\n * which are then normalized to canonical names ('Control', 'Meta', 'Alt') or the\n * platform-adaptive 'Mod' token.\n *\n * The 'Mod' and 'CommandOrControl' aliases are resolved at runtime via `resolveModifier()`\n * based on the detected platform (Command on Mac, Control elsewhere).\n *\n * @remarks Case-insensitive lookups are supported via lowercase variants\n *\n * @example\n * ```ts\n * MODIFIER_ALIASES['Ctrl'] // 'Control'\n * MODIFIER_ALIASES['Cmd'] // 'Meta'\n * MODIFIER_ALIASES['Mod'] // 'Mod' (resolved at runtime)\n * ```\n */\nexport const MODIFIER_ALIASES: Record<string, CanonicalModifier | 'Mod'> = {\n // Control variants\n Control: 'Control',\n Ctrl: 'Control',\n control: 'Control',\n ctrl: 'Control',\n\n // Shift variants\n Shift: 'Shift',\n shift: 'Shift',\n\n // Alt variants\n Alt: 'Alt',\n Option: 'Alt',\n alt: 'Alt',\n option: 'Alt',\n\n // Meta/Command variants\n Command: 'Meta',\n Cmd: 'Meta',\n Meta: 'Meta',\n command: 'Meta',\n cmd: 'Meta',\n meta: 'Meta',\n\n // Platform-adaptive (resolved at runtime)\n CommandOrControl: 'Mod',\n Mod: 'Mod',\n commandorcontrol: 'Mod',\n mod: 'Mod',\n}\n\n/**\n * Resolves the platform-adaptive 'Mod' modifier to the appropriate canonical modifier.\n *\n * The 'Mod' token represents the \"primary modifier\" on each platform:\n * - macOS: 'Meta' (Command key ⌘)\n * - Windows/Linux: 'Control' (Ctrl key)\n *\n * This enables cross-platform hotkey definitions like 'Mod+S' that automatically\n * map to Command+S on Mac and Ctrl+S on Windows/Linux.\n *\n * @param modifier - The modifier to resolve. If 'Mod', resolves based on platform.\n * @param platform - The target platform. Defaults to auto-detection.\n * @returns The canonical modifier name ('Control', 'Shift', 'Alt', or 'Meta')\n *\n * @example\n * ```ts\n * resolveModifier('Mod', 'mac') // 'Meta'\n * resolveModifier('Mod', 'windows') // 'Control'\n * resolveModifier('Control', 'mac') // 'Control' (unchanged)\n * ```\n */\nexport function resolveModifier(\n modifier: CanonicalModifier | 'Mod',\n platform: 'mac' | 'windows' | 'linux' = detectPlatform(),\n): CanonicalModifier {\n if (modifier === 'Mod') {\n return platform === 'mac' ? 'Meta' : 'Control'\n }\n return modifier\n}\n\n// =============================================================================\n// Valid Keys\n// =============================================================================\n\n/**\n * Set of all valid letter keys (A-Z).\n *\n * Used for validation and type checking. Letter keys are matched case-insensitively\n * in hotkey matching, but normalized to uppercase in canonical form.\n */\nexport const LETTER_KEYS = new Set<LetterKey>([\n 'A',\n 'B',\n 'C',\n 'D',\n 'E',\n 'F',\n 'G',\n 'H',\n 'I',\n 'J',\n 'K',\n 'L',\n 'M',\n 'N',\n 'O',\n 'P',\n 'Q',\n 'R',\n 'S',\n 'T',\n 'U',\n 'V',\n 'W',\n 'X',\n 'Y',\n 'Z',\n])\n\n/**\n * Set of all valid number keys (0-9).\n *\n * Note: Number keys are affected by Shift (Shift+1 → '!' on US layout),\n * so they're excluded from Shift-based hotkey combinations to avoid\n * layout-dependent behavior.\n */\nexport const NUMBER_KEYS = new Set<NumberKey>([\n '0',\n '1',\n '2',\n '3',\n '4',\n '5',\n '6',\n '7',\n '8',\n '9',\n])\n\n/**\n * Set of all valid function keys (F1-F12).\n *\n * Function keys are commonly used for system shortcuts (e.g., F12 for DevTools,\n * Alt+F4 to close windows) and application-specific commands.\n */\nexport const FUNCTION_KEYS = new Set<FunctionKey>([\n 'F1',\n 'F2',\n 'F3',\n 'F4',\n 'F5',\n 'F6',\n 'F7',\n 'F8',\n 'F9',\n 'F10',\n 'F11',\n 'F12',\n])\n\n/**\n * Set of all valid navigation keys for cursor movement and document navigation.\n *\n * Includes arrow keys, Home/End (line navigation), and PageUp/PageDown (page navigation).\n * These keys are commonly combined with modifiers for selection (Shift+ArrowUp) or\n * navigation shortcuts (Alt+ArrowLeft for back).\n */\nexport const NAVIGATION_KEYS = new Set<NavigationKey>([\n 'ArrowUp',\n 'ArrowDown',\n 'ArrowLeft',\n 'ArrowRight',\n 'Home',\n 'End',\n 'PageUp',\n 'PageDown',\n])\n\n/**\n * Set of all valid editing and special keys.\n *\n * Includes keys commonly used for text editing (Enter, Backspace, Delete, Tab) and\n * special actions (Escape, Space). These keys are frequently combined with modifiers\n * for editor shortcuts (Mod+Enter to submit, Shift+Tab to go back).\n */\nexport const EDITING_KEYS = new Set<EditingKey>([\n 'Enter',\n 'Escape',\n 'Space',\n 'Tab',\n 'Backspace',\n 'Delete',\n])\n\n/**\n * Set of all valid punctuation keys commonly used in keyboard shortcuts.\n *\n * These are the literal characters as they appear in `KeyboardEvent.key` (layout-dependent,\n * typically US keyboard layout). Common shortcuts include:\n * - `Mod+/` - Toggle comment\n * - `Mod+[` / `Mod+]` - Indent/outdent\n * - `Mod+=` / `Mod+-` - Zoom in/out\n *\n * Note: Punctuation keys are affected by Shift (Shift+',' → '<' on US layout),\n * so they're excluded from Shift-based hotkey combinations to avoid layout-dependent behavior.\n */\nexport const PUNCTUATION_KEYS = new Set<PunctuationKey>([\n '/',\n '[',\n ']',\n '\\\\',\n '=',\n '-',\n ',',\n '.',\n ';',\n '`',\n])\n\n/**\n * Maps `KeyboardEvent.code` values for punctuation keys to their canonical characters.\n *\n * On macOS, holding the Option (Alt) key transforms punctuation keys into special characters\n * (e.g., Option+Minus → en-dash '–'), causing `event.key` to differ from the expected character.\n * However, `event.code` still reports the physical key (e.g., 'Minus'). This map enables\n * falling back to `event.code` for punctuation keys, similar to the existing `Key*`/`Digit*`\n * fallbacks for letters and digits.\n */\nexport const PUNCTUATION_CODE_MAP: Record<string, string> = {\n Minus: '-',\n Equal: '=',\n Slash: '/',\n BracketLeft: '[',\n BracketRight: ']',\n Backslash: '\\\\',\n Comma: ',',\n Period: '.',\n Backquote: '`',\n Semicolon: ';',\n}\n\n/**\n * Set of all valid non-modifier keys.\n *\n * This is the union of all key type sets (letters, numbers, function keys, navigation,\n * editing, and punctuation). Used primarily for validation to check if a key string\n * is recognized and will have type-safe autocomplete support.\n *\n * @see {@link LETTER_KEYS}\n * @see {@link NUMBER_KEYS}\n * @see {@link FUNCTION_KEYS}\n * @see {@link NAVIGATION_KEYS}\n * @see {@link EDITING_KEYS}\n * @see {@link PUNCTUATION_KEYS}\n */\nexport const ALL_KEYS = new Set([\n ...LETTER_KEYS,\n ...NUMBER_KEYS,\n ...FUNCTION_KEYS,\n ...NAVIGATION_KEYS,\n ...EDITING_KEYS,\n ...PUNCTUATION_KEYS,\n])\n\n/**\n * Maps key name aliases to their canonical form.\n *\n * Handles common variations and alternative names for keys to provide a more\n * forgiving API. For example, users can write 'Esc', 'esc', or 'escape' and\n * they'll all normalize to 'Escape'.\n *\n * This map is used internally by `normalizeKeyName()` to convert user input\n * into the canonical key names used throughout the library.\n *\n * @remarks Case-insensitive lookups are supported via lowercase variants\n *\n * @example\n * ```ts\n * KEY_ALIASES['Esc'] // 'Escape'\n * KEY_ALIASES['Del'] // 'Delete'\n * KEY_ALIASES['Up'] // 'ArrowUp'\n * ```\n */\nconst KEY_ALIASES: Record<string, string> = {\n // Escape variants\n Esc: 'Escape',\n esc: 'Escape',\n escape: 'Escape',\n\n // Enter variants\n Return: 'Enter',\n return: 'Enter',\n enter: 'Enter',\n\n // Space variants\n ' ': 'Space',\n space: 'Space',\n Spacebar: 'Space',\n spacebar: 'Space',\n\n // Tab variants\n tab: 'Tab',\n\n // Backspace variants\n backspace: 'Backspace',\n\n // Delete variants\n Del: 'Delete',\n del: 'Delete',\n delete: 'Delete',\n\n // Arrow key variants\n Up: 'ArrowUp',\n up: 'ArrowUp',\n arrowup: 'ArrowUp',\n Down: 'ArrowDown',\n down: 'ArrowDown',\n arrowdown: 'ArrowDown',\n Left: 'ArrowLeft',\n left: 'ArrowLeft',\n arrowleft: 'ArrowLeft',\n Right: 'ArrowRight',\n right: 'ArrowRight',\n arrowright: 'ArrowRight',\n\n // Navigation variants\n home: 'Home',\n end: 'End',\n pageup: 'PageUp',\n pagedown: 'PageDown',\n PgUp: 'PageUp',\n PgDn: 'PageDown',\n pgup: 'PageUp',\n pgdn: 'PageDown',\n}\n\n/**\n * Normalizes a key name to its canonical form.\n *\n * Converts various key name formats (aliases, case variations) into the standard\n * canonical names used throughout the library. This enables a more forgiving API\n * where users can write keys in different ways and still get correct behavior.\n *\n * Normalization rules:\n * 1. Check aliases first (e.g., 'Esc' → 'Escape', 'Del' → 'Delete')\n * 2. Single letters → uppercase (e.g., 'a' → 'A', 's' → 'S')\n * 3. Function keys → uppercase (e.g., 'f1' → 'F1', 'F12' → 'F12')\n * 4. Other keys → returned as-is (already canonical or unknown)\n *\n * @param key - The key name to normalize (can be an alias, lowercase, etc.)\n * @returns The canonical key name\n *\n * @example\n * ```ts\n * normalizeKeyName('esc') // 'Escape'\n * normalizeKeyName('a') // 'A'\n * normalizeKeyName('f1') // 'F1'\n * normalizeKeyName('ArrowUp') // 'ArrowUp' (already canonical)\n * ```\n */\nexport function isSingleLetterKey(key: string): boolean {\n return /^\\p{Letter}$/u.test(key)\n}\n\nexport function normalizeKeyName(key: string): string {\n // Check aliases first\n if (key in KEY_ALIASES) {\n return KEY_ALIASES[key]!\n }\n\n if (isSingleLetterKey(key)) {\n const upper = key.toUpperCase()\n // Some Unicode letters (e.g., 'ß') uppercase to multi-character sequences\n // ('SS'). Avoid changing the string length so the rest of the matching\n // logic can rely on a stable single-character key value.\n return upper.length === 1 ? upper : key\n }\n\n // Check if it's a function key (normalize case)\n const upperKey = key.toUpperCase()\n if (/^F([1-9]|1[0-2])$/.test(upperKey)) {\n return upperKey\n }\n\n return key\n}\n\n// =============================================================================\n// Display Symbols\n// =============================================================================\n\n/**\n * Modifier key symbols for macOS display.\n *\n * Used by formatting functions to display hotkeys with macOS-style symbols\n * (e.g., ⌘ for Command, ⌃ for Control) instead of text labels. This provides\n * a native macOS look and feel in hotkey displays.\n *\n * @example\n * ```ts\n * MAC_MODIFIER_SYMBOLS['Meta'] // '⌘'\n * MAC_MODIFIER_SYMBOLS['Control'] // '⌃'\n * MAC_MODIFIER_SYMBOLS['Alt'] // '⌥'\n * MAC_MODIFIER_SYMBOLS['Shift'] // '⇧'\n * ```\n */\nexport const MAC_MODIFIER_SYMBOLS: Record<CanonicalModifier, string> = {\n Control: '⌃',\n Alt: '⌥',\n Shift: '⇧',\n Meta: '⌘',\n}\n\n/**\n * Modifier key labels for Windows/Linux display.\n *\n * Used by formatting functions to display hotkeys with standard text labels\n * (e.g., 'Ctrl' for Control, 'Win' for Meta/Windows key) instead of symbols.\n * This provides a familiar Windows/Linux look and feel in hotkey displays.\n *\n * @example\n * ```ts\n * STANDARD_MODIFIER_LABELS['Control'] // 'Ctrl'\n * STANDARD_MODIFIER_LABELS['Meta'] // 'Win'\n * STANDARD_MODIFIER_LABELS['Alt'] // 'Alt'\n * STANDARD_MODIFIER_LABELS['Shift'] // 'Shift'\n * ```\n */\nexport const STANDARD_MODIFIER_LABELS: Record<CanonicalModifier, string> = {\n Control: 'Ctrl',\n Alt: 'Alt',\n Shift: 'Shift',\n Meta: 'Win',\n}\n\n/**\n * Special key symbols for display formatting.\n *\n * Maps certain keys to their visual symbols for better readability in hotkey displays.\n * Used by formatting functions to show symbols like ↑ for ArrowUp or ↵ for Enter\n * instead of text labels.\n *\n * @example\n * ```ts\n * KEY_DISPLAY_SYMBOLS['ArrowUp'] // '↑'\n * KEY_DISPLAY_SYMBOLS['Enter'] // '↵'\n * KEY_DISPLAY_SYMBOLS['Escape'] // 'Esc'\n * KEY_DISPLAY_SYMBOLS['Space'] // '␣'\n * ```\n */\nexport const KEY_DISPLAY_SYMBOLS: Record<string, string> = {\n ArrowUp: '↑',\n ArrowDown: '↓',\n ArrowLeft: '←',\n ArrowRight: '→',\n Enter: '↵',\n Escape: 'Esc',\n Backspace: '⌫',\n Delete: '⌦',\n Tab: '⇥',\n Space: '␣',\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA6BA,SAAgB,iBAA8C;AAC5D,KAAI,OAAO,cAAc,YACvB,QAAO;CAIT,MAAM,WAAW,UAAU,UAAU,aAAa,IAAI;CAEtD,MAAM,YAAY,UAAU,WAAW,aAAa,IAAI;AAExD,KAAI,SAAS,SAAS,MAAM,IAAI,UAAU,SAAS,MAAM,CACvD,QAAO;AAET,KAAI,SAAS,SAAS,MAAM,IAAI,UAAU,SAAS,MAAM,CACvD,QAAO;AAET,QAAO;;;;;;;;;;;;;;;;AAqBT,MAAa,iBAA2C;CACtD;CACA;CACA;CACA;CACD;;;;;;;;AASD,MAAa,gBAAgB,IAAI,IAAY,eAAe;;;;;;;;;;;;;;;;;;;;AAqB5D,MAAa,mBAA8D;CAEzE,SAAS;CACT,MAAM;CACN,SAAS;CACT,MAAM;CAGN,OAAO;CACP,OAAO;CAGP,KAAK;CACL,QAAQ;CACR,KAAK;CACL,QAAQ;CAGR,SAAS;CACT,KAAK;CACL,MAAM;CACN,SAAS;CACT,KAAK;CACL,MAAM;CAGN,kBAAkB;CAClB,KAAK;CACL,kBAAkB;CAClB,KAAK;CACN;;;;;;;;;;;;;;;;;;;;;;AAuBD,SAAgB,gBACd,UACA,WAAwC,gBAAgB,EACrC;AACnB,KAAI,aAAa,MACf,QAAO,aAAa,QAAQ,SAAS;AAEvC,QAAO;;;;;;;;AAaT,MAAa,cAAc,IAAI,IAAe;CAC5C;CACA;CACA;CACA;CACA;CACA;CACA;CACA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ACN,KAAK;CACL,QAAQ;CACR,UAAU;CACV,MAAM;CACN,MAAM;CACN,MAAM;CACN,MAAM;CACP;;;;;;;;;;;;;;;;;;;;;;;;;AA0BD,SAAgB,kBAAkB,KAAsB;AACtD,QAAO,gBAAgB,KAAK,IAAI;;AAGlC,SAAgB,iBAAiB,KAAqB;AAEpD,KAAI,OAAO,YACT,QAAO,YAAY;AAGrB,KAAI,kBAAkB,IAAI,EAAE;EAC1B,MAAM,QAAQ,IAAI,aAAa;AAI/B,SAAO,MAAM,WAAW,IAAI,QAAQ;;CAItC,MAAM,WAAW,IAAI,aAAa;AAClC,KAAI,oBAAoB,KAAK,SAAS,CACpC,QAAO;AAGT,QAAO;;;;;;;;;;;;;;;;;AAsBT,MAAa,uBAA0D;CACrE,SAAS;CACT,KAAK;CACL,OAAO;CACP,MAAM;CACP;;;;;;;;;;;;;;;;AAiBD,MAAa,2BAA8D;CACzE,SAAS;CACT,KAAK;CACL,OAAO;CACP,MAAM;CACP;;;;;;;;;;;;;;;;AAiBD,MAAa,sBAA8C;CACzD,SAAS;CACT,WAAW;CACX,WAAW;CACX,YAAY;CACZ,OAAO;CACP,QAAQ;CACR,WAAW;CACX,QAAQ;CACR,KAAK;CACL,OAAO;CACR"}
@@ -133,6 +133,16 @@ declare const EDITING_KEYS: Set<EditingKey>;
133
133
  * so they're excluded from Shift-based hotkey combinations to avoid layout-dependent behavior.
134
134
  */
135
135
  declare const PUNCTUATION_KEYS: Set<PunctuationKey>;
136
+ /**
137
+ * Maps `KeyboardEvent.code` values for punctuation keys to their canonical characters.
138
+ *
139
+ * On macOS, holding the Option (Alt) key transforms punctuation keys into special characters
140
+ * (e.g., Option+Minus → en-dash '–'), causing `event.key` to differ from the expected character.
141
+ * However, `event.code` still reports the physical key (e.g., 'Minus'). This map enables
142
+ * falling back to `event.code` for punctuation keys, similar to the existing `Key*`/`Digit*`
143
+ * fallbacks for letters and digits.
144
+ */
145
+ declare const PUNCTUATION_CODE_MAP: Record<string, string>;
136
146
  /**
137
147
  * Set of all valid non-modifier keys.
138
148
  *
@@ -223,5 +233,5 @@ declare const STANDARD_MODIFIER_LABELS: Record<CanonicalModifier, string>;
223
233
  */
224
234
  declare const KEY_DISPLAY_SYMBOLS: Record<string, string>;
225
235
  //#endregion
226
- export { ALL_KEYS, EDITING_KEYS, FUNCTION_KEYS, KEY_DISPLAY_SYMBOLS, LETTER_KEYS, MAC_MODIFIER_SYMBOLS, MODIFIER_ALIASES, MODIFIER_KEYS, MODIFIER_ORDER, NAVIGATION_KEYS, NUMBER_KEYS, PUNCTUATION_KEYS, STANDARD_MODIFIER_LABELS, detectPlatform, isSingleLetterKey, normalizeKeyName, resolveModifier };
236
+ export { ALL_KEYS, EDITING_KEYS, FUNCTION_KEYS, KEY_DISPLAY_SYMBOLS, LETTER_KEYS, MAC_MODIFIER_SYMBOLS, MODIFIER_ALIASES, MODIFIER_KEYS, MODIFIER_ORDER, NAVIGATION_KEYS, NUMBER_KEYS, PUNCTUATION_CODE_MAP, PUNCTUATION_KEYS, STANDARD_MODIFIER_LABELS, detectPlatform, isSingleLetterKey, normalizeKeyName, resolveModifier };
227
237
  //# sourceMappingURL=constants.d.cts.map
@@ -133,6 +133,16 @@ declare const EDITING_KEYS: Set<EditingKey>;
133
133
  * so they're excluded from Shift-based hotkey combinations to avoid layout-dependent behavior.
134
134
  */
135
135
  declare const PUNCTUATION_KEYS: Set<PunctuationKey>;
136
+ /**
137
+ * Maps `KeyboardEvent.code` values for punctuation keys to their canonical characters.
138
+ *
139
+ * On macOS, holding the Option (Alt) key transforms punctuation keys into special characters
140
+ * (e.g., Option+Minus → en-dash '–'), causing `event.key` to differ from the expected character.
141
+ * However, `event.code` still reports the physical key (e.g., 'Minus'). This map enables
142
+ * falling back to `event.code` for punctuation keys, similar to the existing `Key*`/`Digit*`
143
+ * fallbacks for letters and digits.
144
+ */
145
+ declare const PUNCTUATION_CODE_MAP: Record<string, string>;
136
146
  /**
137
147
  * Set of all valid non-modifier keys.
138
148
  *
@@ -223,5 +233,5 @@ declare const STANDARD_MODIFIER_LABELS: Record<CanonicalModifier, string>;
223
233
  */
224
234
  declare const KEY_DISPLAY_SYMBOLS: Record<string, string>;
225
235
  //#endregion
226
- export { ALL_KEYS, EDITING_KEYS, FUNCTION_KEYS, KEY_DISPLAY_SYMBOLS, LETTER_KEYS, MAC_MODIFIER_SYMBOLS, MODIFIER_ALIASES, MODIFIER_KEYS, MODIFIER_ORDER, NAVIGATION_KEYS, NUMBER_KEYS, PUNCTUATION_KEYS, STANDARD_MODIFIER_LABELS, detectPlatform, isSingleLetterKey, normalizeKeyName, resolveModifier };
236
+ export { ALL_KEYS, EDITING_KEYS, FUNCTION_KEYS, KEY_DISPLAY_SYMBOLS, LETTER_KEYS, MAC_MODIFIER_SYMBOLS, MODIFIER_ALIASES, MODIFIER_KEYS, MODIFIER_ORDER, NAVIGATION_KEYS, NUMBER_KEYS, PUNCTUATION_CODE_MAP, PUNCTUATION_KEYS, STANDARD_MODIFIER_LABELS, detectPlatform, isSingleLetterKey, normalizeKeyName, resolveModifier };
227
237
  //# sourceMappingURL=constants.d.ts.map
package/dist/constants.js CHANGED
@@ -242,9 +242,31 @@ const PUNCTUATION_KEYS = new Set([
242
242
  "-",
243
243
  ",",
244
244
  ".",
245
+ ";",
245
246
  "`"
246
247
  ]);
247
248
  /**
249
+ * Maps `KeyboardEvent.code` values for punctuation keys to their canonical characters.
250
+ *
251
+ * On macOS, holding the Option (Alt) key transforms punctuation keys into special characters
252
+ * (e.g., Option+Minus → en-dash '–'), causing `event.key` to differ from the expected character.
253
+ * However, `event.code` still reports the physical key (e.g., 'Minus'). This map enables
254
+ * falling back to `event.code` for punctuation keys, similar to the existing `Key*`/`Digit*`
255
+ * fallbacks for letters and digits.
256
+ */
257
+ const PUNCTUATION_CODE_MAP = {
258
+ Minus: "-",
259
+ Equal: "=",
260
+ Slash: "/",
261
+ BracketLeft: "[",
262
+ BracketRight: "]",
263
+ Backslash: "\\",
264
+ Comma: ",",
265
+ Period: ".",
266
+ Backquote: "`",
267
+ Semicolon: ";"
268
+ };
269
+ /**
248
270
  * Set of all valid non-modifier keys.
249
271
  *
250
272
  * This is the union of all key type sets (letters, numbers, function keys, navigation,
@@ -430,5 +452,5 @@ const KEY_DISPLAY_SYMBOLS = {
430
452
  };
431
453
 
432
454
  //#endregion
433
- export { ALL_KEYS, EDITING_KEYS, FUNCTION_KEYS, KEY_DISPLAY_SYMBOLS, LETTER_KEYS, MAC_MODIFIER_SYMBOLS, MODIFIER_ALIASES, MODIFIER_KEYS, MODIFIER_ORDER, NAVIGATION_KEYS, NUMBER_KEYS, PUNCTUATION_KEYS, STANDARD_MODIFIER_LABELS, detectPlatform, isSingleLetterKey, normalizeKeyName, resolveModifier };
455
+ export { ALL_KEYS, EDITING_KEYS, FUNCTION_KEYS, KEY_DISPLAY_SYMBOLS, LETTER_KEYS, MAC_MODIFIER_SYMBOLS, MODIFIER_ALIASES, MODIFIER_KEYS, MODIFIER_ORDER, NAVIGATION_KEYS, NUMBER_KEYS, PUNCTUATION_CODE_MAP, PUNCTUATION_KEYS, STANDARD_MODIFIER_LABELS, detectPlatform, isSingleLetterKey, normalizeKeyName, resolveModifier };
434
456
  //# sourceMappingURL=constants.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"constants.js","names":[],"sources":["../src/constants.ts"],"sourcesContent":["import type {\n CanonicalModifier,\n EditingKey,\n FunctionKey,\n LetterKey,\n NavigationKey,\n NumberKey,\n PunctuationKey,\n} from './hotkey'\n\n// =============================================================================\n// Platform Detection\n// =============================================================================\n\n/**\n * Detects the current platform based on browser navigator properties.\n *\n * Used internally to resolve platform-adaptive modifiers like 'Mod' (Command on Mac,\n * Control elsewhere) and for platform-specific hotkey formatting.\n *\n * @returns The detected platform: 'mac', 'windows', or 'linux'\n * @remarks Defaults to 'linux' in SSR environments where navigator is undefined\n *\n * @example\n * ```ts\n * const platform = detectPlatform() // 'mac' | 'windows' | 'linux'\n * const modifier = resolveModifier('Mod', platform) // 'Meta' on Mac, 'Control' elsewhere\n * ```\n */\nexport function detectPlatform(): 'mac' | 'windows' | 'linux' {\n if (typeof navigator === 'undefined') {\n return 'linux' // Default for SSR\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n const platform = navigator.platform?.toLowerCase() ?? ''\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n const userAgent = navigator.userAgent?.toLowerCase() ?? ''\n\n if (platform.includes('mac') || userAgent.includes('mac')) {\n return 'mac'\n }\n if (platform.includes('win') || userAgent.includes('win')) {\n return 'windows'\n }\n return 'linux'\n}\n\n// =============================================================================\n// Modifier Aliases\n// =============================================================================\n\n/**\n * Canonical order for modifiers in normalized hotkey strings.\n *\n * Defines the standard order in which modifiers should appear when formatting\n * hotkeys. This ensures consistent, predictable output across the library.\n *\n * Order: Control → Alt → Shift → Meta\n *\n * @example\n * ```ts\n * // Input: 'Shift+Control+Meta+S'\n * // Normalized: 'Control+Alt+Shift+Meta+S' (following MODIFIER_ORDER)\n * ```\n */\nexport const MODIFIER_ORDER: Array<CanonicalModifier> = [\n 'Control',\n 'Alt',\n 'Shift',\n 'Meta',\n]\n\n/**\n * Set of canonical modifier key names for fast lookup.\n *\n * Derived from `MODIFIER_ORDER` to ensure consistency. Used to detect when\n * a modifier is released so we can clear non-modifier keys whose keyup events\n * may have been swallowed by the OS (e.g. macOS Cmd+key combos).\n */\nexport const MODIFIER_KEYS = new Set<string>(MODIFIER_ORDER)\n\n/**\n * Maps modifier key aliases to their canonical form or platform-adaptive 'Mod'.\n *\n * This map allows users to write hotkeys using various aliases (e.g., 'Ctrl', 'Cmd', 'Option')\n * which are then normalized to canonical names ('Control', 'Meta', 'Alt') or the\n * platform-adaptive 'Mod' token.\n *\n * The 'Mod' and 'CommandOrControl' aliases are resolved at runtime via `resolveModifier()`\n * based on the detected platform (Command on Mac, Control elsewhere).\n *\n * @remarks Case-insensitive lookups are supported via lowercase variants\n *\n * @example\n * ```ts\n * MODIFIER_ALIASES['Ctrl'] // 'Control'\n * MODIFIER_ALIASES['Cmd'] // 'Meta'\n * MODIFIER_ALIASES['Mod'] // 'Mod' (resolved at runtime)\n * ```\n */\nexport const MODIFIER_ALIASES: Record<string, CanonicalModifier | 'Mod'> = {\n // Control variants\n Control: 'Control',\n Ctrl: 'Control',\n control: 'Control',\n ctrl: 'Control',\n\n // Shift variants\n Shift: 'Shift',\n shift: 'Shift',\n\n // Alt variants\n Alt: 'Alt',\n Option: 'Alt',\n alt: 'Alt',\n option: 'Alt',\n\n // Meta/Command variants\n Command: 'Meta',\n Cmd: 'Meta',\n Meta: 'Meta',\n command: 'Meta',\n cmd: 'Meta',\n meta: 'Meta',\n\n // Platform-adaptive (resolved at runtime)\n CommandOrControl: 'Mod',\n Mod: 'Mod',\n commandorcontrol: 'Mod',\n mod: 'Mod',\n}\n\n/**\n * Resolves the platform-adaptive 'Mod' modifier to the appropriate canonical modifier.\n *\n * The 'Mod' token represents the \"primary modifier\" on each platform:\n * - macOS: 'Meta' (Command key ⌘)\n * - Windows/Linux: 'Control' (Ctrl key)\n *\n * This enables cross-platform hotkey definitions like 'Mod+S' that automatically\n * map to Command+S on Mac and Ctrl+S on Windows/Linux.\n *\n * @param modifier - The modifier to resolve. If 'Mod', resolves based on platform.\n * @param platform - The target platform. Defaults to auto-detection.\n * @returns The canonical modifier name ('Control', 'Shift', 'Alt', or 'Meta')\n *\n * @example\n * ```ts\n * resolveModifier('Mod', 'mac') // 'Meta'\n * resolveModifier('Mod', 'windows') // 'Control'\n * resolveModifier('Control', 'mac') // 'Control' (unchanged)\n * ```\n */\nexport function resolveModifier(\n modifier: CanonicalModifier | 'Mod',\n platform: 'mac' | 'windows' | 'linux' = detectPlatform(),\n): CanonicalModifier {\n if (modifier === 'Mod') {\n return platform === 'mac' ? 'Meta' : 'Control'\n }\n return modifier\n}\n\n// =============================================================================\n// Valid Keys\n// =============================================================================\n\n/**\n * Set of all valid letter keys (A-Z).\n *\n * Used for validation and type checking. Letter keys are matched case-insensitively\n * in hotkey matching, but normalized to uppercase in canonical form.\n */\nexport const LETTER_KEYS = new Set<LetterKey>([\n 'A',\n 'B',\n 'C',\n 'D',\n 'E',\n 'F',\n 'G',\n 'H',\n 'I',\n 'J',\n 'K',\n 'L',\n 'M',\n 'N',\n 'O',\n 'P',\n 'Q',\n 'R',\n 'S',\n 'T',\n 'U',\n 'V',\n 'W',\n 'X',\n 'Y',\n 'Z',\n])\n\n/**\n * Set of all valid number keys (0-9).\n *\n * Note: Number keys are affected by Shift (Shift+1 → '!' on US layout),\n * so they're excluded from Shift-based hotkey combinations to avoid\n * layout-dependent behavior.\n */\nexport const NUMBER_KEYS = new Set<NumberKey>([\n '0',\n '1',\n '2',\n '3',\n '4',\n '5',\n '6',\n '7',\n '8',\n '9',\n])\n\n/**\n * Set of all valid function keys (F1-F12).\n *\n * Function keys are commonly used for system shortcuts (e.g., F12 for DevTools,\n * Alt+F4 to close windows) and application-specific commands.\n */\nexport const FUNCTION_KEYS = new Set<FunctionKey>([\n 'F1',\n 'F2',\n 'F3',\n 'F4',\n 'F5',\n 'F6',\n 'F7',\n 'F8',\n 'F9',\n 'F10',\n 'F11',\n 'F12',\n])\n\n/**\n * Set of all valid navigation keys for cursor movement and document navigation.\n *\n * Includes arrow keys, Home/End (line navigation), and PageUp/PageDown (page navigation).\n * These keys are commonly combined with modifiers for selection (Shift+ArrowUp) or\n * navigation shortcuts (Alt+ArrowLeft for back).\n */\nexport const NAVIGATION_KEYS = new Set<NavigationKey>([\n 'ArrowUp',\n 'ArrowDown',\n 'ArrowLeft',\n 'ArrowRight',\n 'Home',\n 'End',\n 'PageUp',\n 'PageDown',\n])\n\n/**\n * Set of all valid editing and special keys.\n *\n * Includes keys commonly used for text editing (Enter, Backspace, Delete, Tab) and\n * special actions (Escape, Space). These keys are frequently combined with modifiers\n * for editor shortcuts (Mod+Enter to submit, Shift+Tab to go back).\n */\nexport const EDITING_KEYS = new Set<EditingKey>([\n 'Enter',\n 'Escape',\n 'Space',\n 'Tab',\n 'Backspace',\n 'Delete',\n])\n\n/**\n * Set of all valid punctuation keys commonly used in keyboard shortcuts.\n *\n * These are the literal characters as they appear in `KeyboardEvent.key` (layout-dependent,\n * typically US keyboard layout). Common shortcuts include:\n * - `Mod+/` - Toggle comment\n * - `Mod+[` / `Mod+]` - Indent/outdent\n * - `Mod+=` / `Mod+-` - Zoom in/out\n *\n * Note: Punctuation keys are affected by Shift (Shift+',' → '<' on US layout),\n * so they're excluded from Shift-based hotkey combinations to avoid layout-dependent behavior.\n */\nexport const PUNCTUATION_KEYS = new Set<PunctuationKey>([\n '/',\n '[',\n ']',\n '\\\\',\n '=',\n '-',\n ',',\n '.',\n '`',\n])\n\n/**\n * Set of all valid non-modifier keys.\n *\n * This is the union of all key type sets (letters, numbers, function keys, navigation,\n * editing, and punctuation). Used primarily for validation to check if a key string\n * is recognized and will have type-safe autocomplete support.\n *\n * @see {@link LETTER_KEYS}\n * @see {@link NUMBER_KEYS}\n * @see {@link FUNCTION_KEYS}\n * @see {@link NAVIGATION_KEYS}\n * @see {@link EDITING_KEYS}\n * @see {@link PUNCTUATION_KEYS}\n */\nexport const ALL_KEYS = new Set([\n ...LETTER_KEYS,\n ...NUMBER_KEYS,\n ...FUNCTION_KEYS,\n ...NAVIGATION_KEYS,\n ...EDITING_KEYS,\n ...PUNCTUATION_KEYS,\n])\n\n/**\n * Maps key name aliases to their canonical form.\n *\n * Handles common variations and alternative names for keys to provide a more\n * forgiving API. For example, users can write 'Esc', 'esc', or 'escape' and\n * they'll all normalize to 'Escape'.\n *\n * This map is used internally by `normalizeKeyName()` to convert user input\n * into the canonical key names used throughout the library.\n *\n * @remarks Case-insensitive lookups are supported via lowercase variants\n *\n * @example\n * ```ts\n * KEY_ALIASES['Esc'] // 'Escape'\n * KEY_ALIASES['Del'] // 'Delete'\n * KEY_ALIASES['Up'] // 'ArrowUp'\n * ```\n */\nconst KEY_ALIASES: Record<string, string> = {\n // Escape variants\n Esc: 'Escape',\n esc: 'Escape',\n escape: 'Escape',\n\n // Enter variants\n Return: 'Enter',\n return: 'Enter',\n enter: 'Enter',\n\n // Space variants\n ' ': 'Space',\n space: 'Space',\n Spacebar: 'Space',\n spacebar: 'Space',\n\n // Tab variants\n tab: 'Tab',\n\n // Backspace variants\n backspace: 'Backspace',\n\n // Delete variants\n Del: 'Delete',\n del: 'Delete',\n delete: 'Delete',\n\n // Arrow key variants\n Up: 'ArrowUp',\n up: 'ArrowUp',\n arrowup: 'ArrowUp',\n Down: 'ArrowDown',\n down: 'ArrowDown',\n arrowdown: 'ArrowDown',\n Left: 'ArrowLeft',\n left: 'ArrowLeft',\n arrowleft: 'ArrowLeft',\n Right: 'ArrowRight',\n right: 'ArrowRight',\n arrowright: 'ArrowRight',\n\n // Navigation variants\n home: 'Home',\n end: 'End',\n pageup: 'PageUp',\n pagedown: 'PageDown',\n PgUp: 'PageUp',\n PgDn: 'PageDown',\n pgup: 'PageUp',\n pgdn: 'PageDown',\n}\n\n/**\n * Normalizes a key name to its canonical form.\n *\n * Converts various key name formats (aliases, case variations) into the standard\n * canonical names used throughout the library. This enables a more forgiving API\n * where users can write keys in different ways and still get correct behavior.\n *\n * Normalization rules:\n * 1. Check aliases first (e.g., 'Esc' → 'Escape', 'Del' → 'Delete')\n * 2. Single letters → uppercase (e.g., 'a' → 'A', 's' → 'S')\n * 3. Function keys → uppercase (e.g., 'f1' → 'F1', 'F12' → 'F12')\n * 4. Other keys → returned as-is (already canonical or unknown)\n *\n * @param key - The key name to normalize (can be an alias, lowercase, etc.)\n * @returns The canonical key name\n *\n * @example\n * ```ts\n * normalizeKeyName('esc') // 'Escape'\n * normalizeKeyName('a') // 'A'\n * normalizeKeyName('f1') // 'F1'\n * normalizeKeyName('ArrowUp') // 'ArrowUp' (already canonical)\n * ```\n */\nexport function isSingleLetterKey(key: string): boolean {\n return /^\\p{Letter}$/u.test(key)\n}\n\nexport function normalizeKeyName(key: string): string {\n // Check aliases first\n if (key in KEY_ALIASES) {\n return KEY_ALIASES[key]!\n }\n\n if (isSingleLetterKey(key)) {\n const upper = key.toUpperCase()\n // Some Unicode letters (e.g., 'ß') uppercase to multi-character sequences\n // ('SS'). Avoid changing the string length so the rest of the matching\n // logic can rely on a stable single-character key value.\n return upper.length === 1 ? upper : key\n }\n\n // Check if it's a function key (normalize case)\n const upperKey = key.toUpperCase()\n if (/^F([1-9]|1[0-2])$/.test(upperKey)) {\n return upperKey\n }\n\n return key\n}\n\n// =============================================================================\n// Display Symbols\n// =============================================================================\n\n/**\n * Modifier key symbols for macOS display.\n *\n * Used by formatting functions to display hotkeys with macOS-style symbols\n * (e.g., ⌘ for Command, ⌃ for Control) instead of text labels. This provides\n * a native macOS look and feel in hotkey displays.\n *\n * @example\n * ```ts\n * MAC_MODIFIER_SYMBOLS['Meta'] // '⌘'\n * MAC_MODIFIER_SYMBOLS['Control'] // '⌃'\n * MAC_MODIFIER_SYMBOLS['Alt'] // '⌥'\n * MAC_MODIFIER_SYMBOLS['Shift'] // '⇧'\n * ```\n */\nexport const MAC_MODIFIER_SYMBOLS: Record<CanonicalModifier, string> = {\n Control: '⌃',\n Alt: '⌥',\n Shift: '⇧',\n Meta: '⌘',\n}\n\n/**\n * Modifier key labels for Windows/Linux display.\n *\n * Used by formatting functions to display hotkeys with standard text labels\n * (e.g., 'Ctrl' for Control, 'Win' for Meta/Windows key) instead of symbols.\n * This provides a familiar Windows/Linux look and feel in hotkey displays.\n *\n * @example\n * ```ts\n * STANDARD_MODIFIER_LABELS['Control'] // 'Ctrl'\n * STANDARD_MODIFIER_LABELS['Meta'] // 'Win'\n * STANDARD_MODIFIER_LABELS['Alt'] // 'Alt'\n * STANDARD_MODIFIER_LABELS['Shift'] // 'Shift'\n * ```\n */\nexport const STANDARD_MODIFIER_LABELS: Record<CanonicalModifier, string> = {\n Control: 'Ctrl',\n Alt: 'Alt',\n Shift: 'Shift',\n Meta: 'Win',\n}\n\n/**\n * Special key symbols for display formatting.\n *\n * Maps certain keys to their visual symbols for better readability in hotkey displays.\n * Used by formatting functions to show symbols like ↑ for ArrowUp or ↵ for Enter\n * instead of text labels.\n *\n * @example\n * ```ts\n * KEY_DISPLAY_SYMBOLS['ArrowUp'] // '↑'\n * KEY_DISPLAY_SYMBOLS['Enter'] // '↵'\n * KEY_DISPLAY_SYMBOLS['Escape'] // 'Esc'\n * KEY_DISPLAY_SYMBOLS['Space'] // '␣'\n * ```\n */\nexport const KEY_DISPLAY_SYMBOLS: Record<string, string> = {\n ArrowUp: '↑',\n ArrowDown: '↓',\n ArrowLeft: '←',\n ArrowRight: '→',\n Enter: '↵',\n Escape: 'Esc',\n Backspace: '⌫',\n Delete: '⌦',\n Tab: '⇥',\n Space: '␣',\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA6BA,SAAgB,iBAA8C;AAC5D,KAAI,OAAO,cAAc,YACvB,QAAO;CAIT,MAAM,WAAW,UAAU,UAAU,aAAa,IAAI;CAEtD,MAAM,YAAY,UAAU,WAAW,aAAa,IAAI;AAExD,KAAI,SAAS,SAAS,MAAM,IAAI,UAAU,SAAS,MAAM,CACvD,QAAO;AAET,KAAI,SAAS,SAAS,MAAM,IAAI,UAAU,SAAS,MAAM,CACvD,QAAO;AAET,QAAO;;;;;;;;;;;;;;;;AAqBT,MAAa,iBAA2C;CACtD;CACA;CACA;CACA;CACD;;;;;;;;AASD,MAAa,gBAAgB,IAAI,IAAY,eAAe;;;;;;;;;;;;;;;;;;;;AAqB5D,MAAa,mBAA8D;CAEzE,SAAS;CACT,MAAM;CACN,SAAS;CACT,MAAM;CAGN,OAAO;CACP,OAAO;CAGP,KAAK;CACL,QAAQ;CACR,KAAK;CACL,QAAQ;CAGR,SAAS;CACT,KAAK;CACL,MAAM;CACN,SAAS;CACT,KAAK;CACL,MAAM;CAGN,kBAAkB;CAClB,KAAK;CACL,kBAAkB;CAClB,KAAK;CACN;;;;;;;;;;;;;;;;;;;;;;AAuBD,SAAgB,gBACd,UACA,WAAwC,gBAAgB,EACrC;AACnB,KAAI,aAA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U;CACV,MAAM;CACN,MAAM;CACN,MAAM;CACN,MAAM;CACP;;;;;;;;;;;;;;;;;;;;;;;;;AA0BD,SAAgB,kBAAkB,KAAsB;AACtD,QAAO,gBAAgB,KAAK,IAAI;;AAGlC,SAAgB,iBAAiB,KAAqB;AAEpD,KAAI,OAAO,YACT,QAAO,YAAY;AAGrB,KAAI,kBAAkB,IAAI,EAAE;EAC1B,MAAM,QAAQ,IAAI,aAAa;AAI/B,SAAO,MAAM,WAAW,IAAI,QAAQ;;CAItC,MAAM,WAAW,IAAI,aAAa;AAClC,KAAI,oBAAoB,KAAK,SAAS,CACpC,QAAO;AAGT,QAAO;;;;;;;;;;;;;;;;;AAsBT,MAAa,uBAA0D;CACrE,SAAS;CACT,KAAK;CACL,OAAO;CACP,MAAM;CACP;;;;;;;;;;;;;;;;AAiBD,MAAa,2BAA8D;CACzE,SAAS;CACT,KAAK;CACL,OAAO;CACP,MAAM;CACP;;;;;;;;;;;;;;;;AAiBD,MAAa,sBAA8C;CACzD,SAAS;CACT,WAAW;CACX,WAAW;CACX,YAAY;CACZ,OAAO;CACP,QAAQ;CACR,WAAW;CACX,QAAQ;CACR,KAAK;CACL,OAAO;CACR"}
1
+ {"version":3,"file":"constants.js","names":[],"sources":["../src/constants.ts"],"sourcesContent":["import type {\n CanonicalModifier,\n EditingKey,\n FunctionKey,\n LetterKey,\n NavigationKey,\n NumberKey,\n PunctuationKey,\n} from './hotkey'\n\n// =============================================================================\n// Platform Detection\n// =============================================================================\n\n/**\n * Detects the current platform based on browser navigator properties.\n *\n * Used internally to resolve platform-adaptive modifiers like 'Mod' (Command on Mac,\n * Control elsewhere) and for platform-specific hotkey formatting.\n *\n * @returns The detected platform: 'mac', 'windows', or 'linux'\n * @remarks Defaults to 'linux' in SSR environments where navigator is undefined\n *\n * @example\n * ```ts\n * const platform = detectPlatform() // 'mac' | 'windows' | 'linux'\n * const modifier = resolveModifier('Mod', platform) // 'Meta' on Mac, 'Control' elsewhere\n * ```\n */\nexport function detectPlatform(): 'mac' | 'windows' | 'linux' {\n if (typeof navigator === 'undefined') {\n return 'linux' // Default for SSR\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n const platform = navigator.platform?.toLowerCase() ?? ''\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n const userAgent = navigator.userAgent?.toLowerCase() ?? ''\n\n if (platform.includes('mac') || userAgent.includes('mac')) {\n return 'mac'\n }\n if (platform.includes('win') || userAgent.includes('win')) {\n return 'windows'\n }\n return 'linux'\n}\n\n// =============================================================================\n// Modifier Aliases\n// =============================================================================\n\n/**\n * Canonical order for modifiers in normalized hotkey strings.\n *\n * Defines the standard order in which modifiers should appear when formatting\n * hotkeys. This ensures consistent, predictable output across the library.\n *\n * Order: Control → Alt → Shift → Meta\n *\n * @example\n * ```ts\n * // Input: 'Shift+Control+Meta+S'\n * // Normalized: 'Control+Alt+Shift+Meta+S' (following MODIFIER_ORDER)\n * ```\n */\nexport const MODIFIER_ORDER: Array<CanonicalModifier> = [\n 'Control',\n 'Alt',\n 'Shift',\n 'Meta',\n]\n\n/**\n * Set of canonical modifier key names for fast lookup.\n *\n * Derived from `MODIFIER_ORDER` to ensure consistency. Used to detect when\n * a modifier is released so we can clear non-modifier keys whose keyup events\n * may have been swallowed by the OS (e.g. macOS Cmd+key combos).\n */\nexport const MODIFIER_KEYS = new Set<string>(MODIFIER_ORDER)\n\n/**\n * Maps modifier key aliases to their canonical form or platform-adaptive 'Mod'.\n *\n * This map allows users to write hotkeys using various aliases (e.g., 'Ctrl', 'Cmd', 'Option')\n * which are then normalized to canonical names ('Control', 'Meta', 'Alt') or the\n * platform-adaptive 'Mod' token.\n *\n * The 'Mod' and 'CommandOrControl' aliases are resolved at runtime via `resolveModifier()`\n * based on the detected platform (Command on Mac, Control elsewhere).\n *\n * @remarks Case-insensitive lookups are supported via lowercase variants\n *\n * @example\n * ```ts\n * MODIFIER_ALIASES['Ctrl'] // 'Control'\n * MODIFIER_ALIASES['Cmd'] // 'Meta'\n * MODIFIER_ALIASES['Mod'] // 'Mod' (resolved at runtime)\n * ```\n */\nexport const MODIFIER_ALIASES: Record<string, CanonicalModifier | 'Mod'> = {\n // Control variants\n Control: 'Control',\n Ctrl: 'Control',\n control: 'Control',\n ctrl: 'Control',\n\n // Shift variants\n Shift: 'Shift',\n shift: 'Shift',\n\n // Alt variants\n Alt: 'Alt',\n Option: 'Alt',\n alt: 'Alt',\n option: 'Alt',\n\n // Meta/Command variants\n Command: 'Meta',\n Cmd: 'Meta',\n Meta: 'Meta',\n command: 'Meta',\n cmd: 'Meta',\n meta: 'Meta',\n\n // Platform-adaptive (resolved at runtime)\n CommandOrControl: 'Mod',\n Mod: 'Mod',\n commandorcontrol: 'Mod',\n mod: 'Mod',\n}\n\n/**\n * Resolves the platform-adaptive 'Mod' modifier to the appropriate canonical modifier.\n *\n * The 'Mod' token represents the \"primary modifier\" on each platform:\n * - macOS: 'Meta' (Command key ⌘)\n * - Windows/Linux: 'Control' (Ctrl key)\n *\n * This enables cross-platform hotkey definitions like 'Mod+S' that automatically\n * map to Command+S on Mac and Ctrl+S on Windows/Linux.\n *\n * @param modifier - The modifier to resolve. If 'Mod', resolves based on platform.\n * @param platform - The target platform. Defaults to auto-detection.\n * @returns The canonical modifier name ('Control', 'Shift', 'Alt', or 'Meta')\n *\n * @example\n * ```ts\n * resolveModifier('Mod', 'mac') // 'Meta'\n * resolveModifier('Mod', 'windows') // 'Control'\n * resolveModifier('Control', 'mac') // 'Control' (unchanged)\n * ```\n */\nexport function resolveModifier(\n modifier: CanonicalModifier | 'Mod',\n platform: 'mac' | 'windows' | 'linux' = detectPlatform(),\n): CanonicalModifier {\n if (modifier === 'Mod') {\n return platform === 'mac' ? 'Meta' : 'Control'\n }\n return modifier\n}\n\n// =============================================================================\n// Valid Keys\n// =============================================================================\n\n/**\n * Set of all valid letter keys (A-Z).\n *\n * Used for validation and type checking. Letter keys are matched case-insensitively\n * in hotkey matching, but normalized to uppercase in canonical form.\n */\nexport const LETTER_KEYS = new Set<LetterKey>([\n 'A',\n 'B',\n 'C',\n 'D',\n 'E',\n 'F',\n 'G',\n 'H',\n 'I',\n 'J',\n 'K',\n 'L',\n 'M',\n 'N',\n 'O',\n 'P',\n 'Q',\n 'R',\n 'S',\n 'T',\n 'U',\n 'V',\n 'W',\n 'X',\n 'Y',\n 'Z',\n])\n\n/**\n * Set of all valid number keys (0-9).\n *\n * Note: Number keys are affected by Shift (Shift+1 → '!' on US layout),\n * so they're excluded from Shift-based hotkey combinations to avoid\n * layout-dependent behavior.\n */\nexport const NUMBER_KEYS = new Set<NumberKey>([\n '0',\n '1',\n '2',\n '3',\n '4',\n '5',\n '6',\n '7',\n '8',\n '9',\n])\n\n/**\n * Set of all valid function keys (F1-F12).\n *\n * Function keys are commonly used for system shortcuts (e.g., F12 for DevTools,\n * Alt+F4 to close windows) and application-specific commands.\n */\nexport const FUNCTION_KEYS = new Set<FunctionKey>([\n 'F1',\n 'F2',\n 'F3',\n 'F4',\n 'F5',\n 'F6',\n 'F7',\n 'F8',\n 'F9',\n 'F10',\n 'F11',\n 'F12',\n])\n\n/**\n * Set of all valid navigation keys for cursor movement and document navigation.\n *\n * Includes arrow keys, Home/End (line navigation), and PageUp/PageDown (page navigation).\n * These keys are commonly combined with modifiers for selection (Shift+ArrowUp) or\n * navigation shortcuts (Alt+ArrowLeft for back).\n */\nexport const NAVIGATION_KEYS = new Set<NavigationKey>([\n 'ArrowUp',\n 'ArrowDown',\n 'ArrowLeft',\n 'ArrowRight',\n 'Home',\n 'End',\n 'PageUp',\n 'PageDown',\n])\n\n/**\n * Set of all valid editing and special keys.\n *\n * Includes keys commonly used for text editing (Enter, Backspace, Delete, Tab) and\n * special actions (Escape, Space). These keys are frequently combined with modifiers\n * for editor shortcuts (Mod+Enter to submit, Shift+Tab to go back).\n */\nexport const EDITING_KEYS = new Set<EditingKey>([\n 'Enter',\n 'Escape',\n 'Space',\n 'Tab',\n 'Backspace',\n 'Delete',\n])\n\n/**\n * Set of all valid punctuation keys commonly used in keyboard shortcuts.\n *\n * These are the literal characters as they appear in `KeyboardEvent.key` (layout-dependent,\n * typically US keyboard layout). Common shortcuts include:\n * - `Mod+/` - Toggle comment\n * - `Mod+[` / `Mod+]` - Indent/outdent\n * - `Mod+=` / `Mod+-` - Zoom in/out\n *\n * Note: Punctuation keys are affected by Shift (Shift+',' → '<' on US layout),\n * so they're excluded from Shift-based hotkey combinations to avoid layout-dependent behavior.\n */\nexport const PUNCTUATION_KEYS = new Set<PunctuationKey>([\n '/',\n '[',\n ']',\n '\\\\',\n '=',\n '-',\n ',',\n '.',\n ';',\n '`',\n])\n\n/**\n * Maps `KeyboardEvent.code` values for punctuation keys to their canonical characters.\n *\n * On macOS, holding the Option (Alt) key transforms punctuation keys into special characters\n * (e.g., Option+Minus → en-dash '–'), causing `event.key` to differ from the expected character.\n * However, `event.code` still reports the physical key (e.g., 'Minus'). This map enables\n * falling back to `event.code` for punctuation keys, similar to the existing `Key*`/`Digit*`\n * fallbacks for letters and digits.\n */\nexport const PUNCTUATION_CODE_MAP: Record<string, string> = {\n Minus: '-',\n Equal: '=',\n Slash: '/',\n BracketLeft: '[',\n BracketRight: ']',\n Backslash: '\\\\',\n Comma: ',',\n Period: '.',\n Backquote: '`',\n Semicolon: ';',\n}\n\n/**\n * Set of all valid non-modifier keys.\n *\n * This is the union of all key type sets (letters, numbers, function keys, navigation,\n * editing, and punctuation). Used primarily for validation to check if a key string\n * is recognized and will have type-safe autocomplete support.\n *\n * @see {@link LETTER_KEYS}\n * @see {@link NUMBER_KEYS}\n * @see {@link FUNCTION_KEYS}\n * @see {@link NAVIGATION_KEYS}\n * @see {@link EDITING_KEYS}\n * @see {@link PUNCTUATION_KEYS}\n */\nexport const ALL_KEYS = new Set([\n ...LETTER_KEYS,\n ...NUMBER_KEYS,\n ...FUNCTION_KEYS,\n ...NAVIGATION_KEYS,\n ...EDITING_KEYS,\n ...PUNCTUATION_KEYS,\n])\n\n/**\n * Maps key name aliases to their canonical form.\n *\n * Handles common variations and alternative names for keys to provide a more\n * forgiving API. For example, users can write 'Esc', 'esc', or 'escape' and\n * they'll all normalize to 'Escape'.\n *\n * This map is used internally by `normalizeKeyName()` to convert user input\n * into the canonical key names used throughout the library.\n *\n * @remarks Case-insensitive lookups are supported via lowercase variants\n *\n * @example\n * ```ts\n * KEY_ALIASES['Esc'] // 'Escape'\n * KEY_ALIASES['Del'] // 'Delete'\n * KEY_ALIASES['Up'] // 'ArrowUp'\n * ```\n */\nconst KEY_ALIASES: Record<string, string> = {\n // Escape variants\n Esc: 'Escape',\n esc: 'Escape',\n escape: 'Escape',\n\n // Enter variants\n Return: 'Enter',\n return: 'Enter',\n enter: 'Enter',\n\n // Space variants\n ' ': 'Space',\n space: 'Space',\n Spacebar: 'Space',\n spacebar: 'Space',\n\n // Tab variants\n tab: 'Tab',\n\n // Backspace variants\n backspace: 'Backspace',\n\n // Delete variants\n Del: 'Delete',\n del: 'Delete',\n delete: 'Delete',\n\n // Arrow key variants\n Up: 'ArrowUp',\n up: 'ArrowUp',\n arrowup: 'ArrowUp',\n Down: 'ArrowDown',\n down: 'ArrowDown',\n arrowdown: 'ArrowDown',\n Left: 'ArrowLeft',\n left: 'ArrowLeft',\n arrowleft: 'ArrowLeft',\n Right: 'ArrowRight',\n right: 'ArrowRight',\n arrowright: 'ArrowRight',\n\n // Navigation variants\n home: 'Home',\n end: 'End',\n pageup: 'PageUp',\n pagedown: 'PageDown',\n PgUp: 'PageUp',\n PgDn: 'PageDown',\n pgup: 'PageUp',\n pgdn: 'PageDown',\n}\n\n/**\n * Normalizes a key name to its canonical form.\n *\n * Converts various key name formats (aliases, case variations) into the standard\n * canonical names used throughout the library. This enables a more forgiving API\n * where users can write keys in different ways and still get correct behavior.\n *\n * Normalization rules:\n * 1. Check aliases first (e.g., 'Esc' → 'Escape', 'Del' → 'Delete')\n * 2. Single letters → uppercase (e.g., 'a' → 'A', 's' → 'S')\n * 3. Function keys → uppercase (e.g., 'f1' → 'F1', 'F12' → 'F12')\n * 4. Other keys → returned as-is (already canonical or unknown)\n *\n * @param key - The key name to normalize (can be an alias, lowercase, etc.)\n * @returns The canonical key name\n *\n * @example\n * ```ts\n * normalizeKeyName('esc') // 'Escape'\n * normalizeKeyName('a') // 'A'\n * normalizeKeyName('f1') // 'F1'\n * normalizeKeyName('ArrowUp') // 'ArrowUp' (already canonical)\n * ```\n */\nexport function isSingleLetterKey(key: string): boolean {\n return /^\\p{Letter}$/u.test(key)\n}\n\nexport function normalizeKeyName(key: string): string {\n // Check aliases first\n if (key in KEY_ALIASES) {\n return KEY_ALIASES[key]!\n }\n\n if (isSingleLetterKey(key)) {\n const upper = key.toUpperCase()\n // Some Unicode letters (e.g., 'ß') uppercase to multi-character sequences\n // ('SS'). Avoid changing the string length so the rest of the matching\n // logic can rely on a stable single-character key value.\n return upper.length === 1 ? upper : key\n }\n\n // Check if it's a function key (normalize case)\n const upperKey = key.toUpperCase()\n if (/^F([1-9]|1[0-2])$/.test(upperKey)) {\n return upperKey\n }\n\n return key\n}\n\n// =============================================================================\n// Display Symbols\n// =============================================================================\n\n/**\n * Modifier key symbols for macOS display.\n *\n * Used by formatting functions to display hotkeys with macOS-style symbols\n * (e.g., ⌘ for Command, ⌃ for Control) instead of text labels. This provides\n * a native macOS look and feel in hotkey displays.\n *\n * @example\n * ```ts\n * MAC_MODIFIER_SYMBOLS['Meta'] // '⌘'\n * MAC_MODIFIER_SYMBOLS['Control'] // '⌃'\n * MAC_MODIFIER_SYMBOLS['Alt'] // '⌥'\n * MAC_MODIFIER_SYMBOLS['Shift'] // '⇧'\n * ```\n */\nexport const MAC_MODIFIER_SYMBOLS: Record<CanonicalModifier, string> = {\n Control: '⌃',\n Alt: '⌥',\n Shift: '⇧',\n Meta: '⌘',\n}\n\n/**\n * Modifier key labels for Windows/Linux display.\n *\n * Used by formatting functions to display hotkeys with standard text labels\n * (e.g., 'Ctrl' for Control, 'Win' for Meta/Windows key) instead of symbols.\n * This provides a familiar Windows/Linux look and feel in hotkey displays.\n *\n * @example\n * ```ts\n * STANDARD_MODIFIER_LABELS['Control'] // 'Ctrl'\n * STANDARD_MODIFIER_LABELS['Meta'] // 'Win'\n * STANDARD_MODIFIER_LABELS['Alt'] // 'Alt'\n * STANDARD_MODIFIER_LABELS['Shift'] // 'Shift'\n * ```\n */\nexport const STANDARD_MODIFIER_LABELS: Record<CanonicalModifier, string> = {\n Control: 'Ctrl',\n Alt: 'Alt',\n Shift: 'Shift',\n Meta: 'Win',\n}\n\n/**\n * Special key symbols for display formatting.\n *\n * Maps certain keys to their visual symbols for better readability in hotkey displays.\n * Used by formatting functions to show symbols like ↑ for ArrowUp or ↵ for Enter\n * instead of text labels.\n *\n * @example\n * ```ts\n * KEY_DISPLAY_SYMBOLS['ArrowUp'] // '↑'\n * KEY_DISPLAY_SYMBOLS['Enter'] // '↵'\n * KEY_DISPLAY_SYMBOLS['Escape'] // 'Esc'\n * KEY_DISPLAY_SYMBOLS['Space'] // '␣'\n * ```\n */\nexport const KEY_DISPLAY_SYMBOLS: Record<string, string> = {\n ArrowUp: '↑',\n ArrowDown: '↓',\n ArrowLeft: '←',\n ArrowRight: '→',\n Enter: '↵',\n Escape: 'Esc',\n Backspace: '⌫',\n Delete: '⌦',\n Tab: '⇥',\n Space: '␣',\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA6BA,SAAgB,iBAA8C;AAC5D,KAAI,OAAO,cAAc,YACvB,QAAO;CAIT,MAAM,WAAW,UAAU,UAAU,aAAa,IAAI;CAEtD,MAAM,YAAY,UAAU,WAAW,aAAa,IAAI;AAExD,KAAI,SAAS,SAAS,MAAM,IAAI,UAAU,SAAS,MAAM,CACvD,QAAO;AAET,KAAI,SAAS,SAAS,MAAM,IAAI,UAAU,SAAS,MAAM,CACvD,QAAO;AAET,QAAO;;;;;;;;;;;;;;;;AAqBT,MAAa,iBAA2C;CACtD;CACA;CACA;CACA;CACD;;;;;;;;AASD,MAAa,gBAAgB,IAAI,IAAY,eAAe;;;;;;;;;;;;;;;;;;;;AAqB5D,MAAa,mBAA8D;CAEzE,SAAS;CACT,MAAM;CACN,SAAS;CACT,MAAM;CAGN,OAAO;CACP,OAAO;CAGP,KAAK;CACL,QAAQ;CACR,KAAK;CACL,QAAQ;CAGR,SAAS;CACT,KAAK;CACL,MAAM;CACN,SAAS;CACT,KAAK;CACL,MAAM;CAGN,kBAAkB;CAClB,KAAK;CACL,kBAAkB;CAClB,KAAK;CACN;;;;;;;;;;;;;;;;;;;;;;AAuBD,SAAgB,gBACd,UACA,WAAwC,gBAAgB,EACrC;AACnB,KAAI,aAAa,MACf,QAAO,aAAa,QAAQ,SAAS;AAEvC,QAAO;;;;;;;;AAaT,MAAa,cAAc,IAAI,IAAe;CAC5C;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;;;;;;;;AASF,MAAa,cAAc,IAAI,IAAe;CAC5C;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;;;;;;;AAQF,MAAa,gBAAgB,IAAI,IAAiB;CAChD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;;;;;;;;AASF,MAAa,kBAAkB,IAAI,IAAmB;CACpD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;;;;;;;;AASF,MAAa,eAAe,IAAI,IAAgB;CAC9C;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;;;;;;;;;;;;;AAcF,MAAa,mBAAmB,IAAI,IAAoB;CACtD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;;;;;;;;;;AAWF,MAAa,uBAA+C;CAC1D,OAAO;CACP,OAAO;CACP,OAAO;CACP,aAAa;CACb,cAAc;CACd,WAAW;CACX,OAAO;CACP,QAAQ;CACR,WAAW;CACX,WAAW;CACZ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QAAQ;CACR,KAAK;CACL,OAAO;CACR"}
package/dist/hotkey.d.cts CHANGED
@@ -37,7 +37,7 @@ type EditingKey = 'Enter' | 'Escape' | 'Space' | 'Tab' | 'Backspace' | 'Delete';
37
37
  * These are the literal characters as they appear in KeyboardEvent.key
38
38
  * (layout-dependent, typically US keyboard layout).
39
39
  */
40
- type PunctuationKey = '/' | '[' | ']' | '\\' | '=' | '-' | ',' | '.' | '`';
40
+ type PunctuationKey = '/' | '[' | ']' | '\\' | '=' | '-' | ',' | '.' | ';' | '`';
41
41
  /**
42
42
  * Keys that don't change their value when Shift is pressed.
43
43
  * These keys produce the same `KeyboardEvent.key` value whether Shift is held or not.
package/dist/hotkey.d.ts CHANGED
@@ -37,7 +37,7 @@ type EditingKey = 'Enter' | 'Escape' | 'Space' | 'Tab' | 'Backspace' | 'Delete';
37
37
  * These are the literal characters as they appear in KeyboardEvent.key
38
38
  * (layout-dependent, typically US keyboard layout).
39
39
  */
40
- type PunctuationKey = '/' | '[' | ']' | '\\' | '=' | '-' | ',' | '.' | '`';
40
+ type PunctuationKey = '/' | '[' | ']' | '\\' | '=' | '-' | ',' | '.' | ';' | '`';
41
41
  /**
42
42
  * Keys that don't change their value when Shift is pressed.
43
43
  * These keys produce the same `KeyboardEvent.key` value whether Shift is held or not.
package/dist/index.cjs CHANGED
@@ -23,6 +23,7 @@ exports.MODIFIER_KEYS = require_constants.MODIFIER_KEYS;
23
23
  exports.MODIFIER_ORDER = require_constants.MODIFIER_ORDER;
24
24
  exports.NAVIGATION_KEYS = require_constants.NAVIGATION_KEYS;
25
25
  exports.NUMBER_KEYS = require_constants.NUMBER_KEYS;
26
+ exports.PUNCTUATION_CODE_MAP = require_constants.PUNCTUATION_CODE_MAP;
26
27
  exports.PUNCTUATION_KEYS = require_constants.PUNCTUATION_KEYS;
27
28
  exports.STANDARD_MODIFIER_LABELS = require_constants.STANDARD_MODIFIER_LABELS;
28
29
  exports.SequenceManager = require_sequence_manager.SequenceManager;
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { CanonicalModifier, EditingKey, FormatDisplayOptions, FunctionKey, HeldKey, Hotkey, HotkeyCallback, HotkeyCallbackContext, Key, LetterKey, Modifier, NavigationKey, NumberKey, ParsedHotkey, PunctuationKey, RawHotkey, RegisterableHotkey, ValidationResult } from "./hotkey.cjs";
2
- import { ALL_KEYS, EDITING_KEYS, FUNCTION_KEYS, KEY_DISPLAY_SYMBOLS, LETTER_KEYS, MAC_MODIFIER_SYMBOLS, MODIFIER_ALIASES, MODIFIER_KEYS, MODIFIER_ORDER, NAVIGATION_KEYS, NUMBER_KEYS, PUNCTUATION_KEYS, STANDARD_MODIFIER_LABELS, detectPlatform, isSingleLetterKey, normalizeKeyName, resolveModifier } from "./constants.cjs";
2
+ import { ALL_KEYS, EDITING_KEYS, FUNCTION_KEYS, KEY_DISPLAY_SYMBOLS, LETTER_KEYS, MAC_MODIFIER_SYMBOLS, MODIFIER_ALIASES, MODIFIER_KEYS, MODIFIER_ORDER, NAVIGATION_KEYS, NUMBER_KEYS, PUNCTUATION_CODE_MAP, PUNCTUATION_KEYS, STANDARD_MODIFIER_LABELS, detectPlatform, isSingleLetterKey, normalizeKeyName, resolveModifier } from "./constants.cjs";
3
3
  import { FormatKeyDebuggingOptions, formatForDisplay, formatHotkey, formatHotkeySequence, formatKeyForDebuggingDisplay, formatWithLabels } from "./format.cjs";
4
4
  import { ConflictBehavior } from "./manager.utils.cjs";
5
5
  import { HotkeyManager, HotkeyOptions, HotkeyRegistration, HotkeyRegistrationHandle, getHotkeyManager } from "./hotkey-manager.cjs";
@@ -9,4 +9,4 @@ import { convertToModFormat, hasNonModifierKey, isModifier, isModifierKey, keybo
9
9
  import { HotkeyRecorder, HotkeyRecorderOptions, HotkeyRecorderState } from "./recorder.cjs";
10
10
  import { HotkeySequence, SequenceManager, SequenceOptions, SequenceRegistrationHandle, SequenceRegistrationView, createSequenceMatcher, getSequenceManager } from "./sequence-manager.cjs";
11
11
  import { assertValidHotkey, checkHotkey, validateHotkey } from "./validate.cjs";
12
- export { ALL_KEYS, CanonicalModifier, ConflictBehavior, CreateHotkeyHandlerOptions, EDITING_KEYS, EditingKey, FUNCTION_KEYS, FormatDisplayOptions, FormatKeyDebuggingOptions, FunctionKey, HeldKey, Hotkey, HotkeyCallback, HotkeyCallbackContext, HotkeyManager, HotkeyOptions, HotkeyRecorder, HotkeyRecorderOptions, HotkeyRecorderState, HotkeyRegistration, HotkeyRegistrationHandle, HotkeySequence, KEY_DISPLAY_SYMBOLS, Key, KeyStateTracker, KeyStateTrackerState, LETTER_KEYS, LetterKey, MAC_MODIFIER_SYMBOLS, MODIFIER_ALIASES, MODIFIER_KEYS, MODIFIER_ORDER, Modifier, NAVIGATION_KEYS, NUMBER_KEYS, NavigationKey, NumberKey, PUNCTUATION_KEYS, ParsedHotkey, PunctuationKey, RawHotkey, RegisterableHotkey, STANDARD_MODIFIER_LABELS, SequenceManager, SequenceOptions, SequenceRegistrationHandle, SequenceRegistrationView, ValidationResult, assertValidHotkey, checkHotkey, convertToModFormat, createHotkeyHandler, createMultiHotkeyHandler, createSequenceMatcher, detectPlatform, formatForDisplay, formatHotkey, formatHotkeySequence, formatKeyForDebuggingDisplay, formatWithLabels, getHotkeyManager, getKeyStateTracker, getSequenceManager, hasNonModifierKey, isModifier, isModifierKey, isSingleLetterKey, keyboardEventToHotkey, matchesKeyboardEvent, normalizeHotkey, normalizeKeyName, parseHotkey, parseKeyboardEvent, rawHotkeyToParsedHotkey, resolveModifier, validateHotkey };
12
+ export { ALL_KEYS, CanonicalModifier, ConflictBehavior, CreateHotkeyHandlerOptions, EDITING_KEYS, EditingKey, FUNCTION_KEYS, FormatDisplayOptions, FormatKeyDebuggingOptions, FunctionKey, HeldKey, Hotkey, HotkeyCallback, HotkeyCallbackContext, HotkeyManager, HotkeyOptions, HotkeyRecorder, HotkeyRecorderOptions, HotkeyRecorderState, HotkeyRegistration, HotkeyRegistrationHandle, HotkeySequence, KEY_DISPLAY_SYMBOLS, Key, KeyStateTracker, KeyStateTrackerState, LETTER_KEYS, LetterKey, MAC_MODIFIER_SYMBOLS, MODIFIER_ALIASES, MODIFIER_KEYS, MODIFIER_ORDER, Modifier, NAVIGATION_KEYS, NUMBER_KEYS, NavigationKey, NumberKey, PUNCTUATION_CODE_MAP, PUNCTUATION_KEYS, ParsedHotkey, PunctuationKey, RawHotkey, RegisterableHotkey, STANDARD_MODIFIER_LABELS, SequenceManager, SequenceOptions, SequenceRegistrationHandle, SequenceRegistrationView, ValidationResult, assertValidHotkey, checkHotkey, convertToModFormat, createHotkeyHandler, createMultiHotkeyHandler, createSequenceMatcher, detectPlatform, formatForDisplay, formatHotkey, formatHotkeySequence, formatKeyForDebuggingDisplay, formatWithLabels, getHotkeyManager, getKeyStateTracker, getSequenceManager, hasNonModifierKey, isModifier, isModifierKey, isSingleLetterKey, keyboardEventToHotkey, matchesKeyboardEvent, normalizeHotkey, normalizeKeyName, parseHotkey, parseKeyboardEvent, rawHotkeyToParsedHotkey, resolveModifier, validateHotkey };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { CanonicalModifier, EditingKey, FormatDisplayOptions, FunctionKey, HeldKey, Hotkey, HotkeyCallback, HotkeyCallbackContext, Key, LetterKey, Modifier, NavigationKey, NumberKey, ParsedHotkey, PunctuationKey, RawHotkey, RegisterableHotkey, ValidationResult } from "./hotkey.js";
2
- import { ALL_KEYS, EDITING_KEYS, FUNCTION_KEYS, KEY_DISPLAY_SYMBOLS, LETTER_KEYS, MAC_MODIFIER_SYMBOLS, MODIFIER_ALIASES, MODIFIER_KEYS, MODIFIER_ORDER, NAVIGATION_KEYS, NUMBER_KEYS, PUNCTUATION_KEYS, STANDARD_MODIFIER_LABELS, detectPlatform, isSingleLetterKey, normalizeKeyName, resolveModifier } from "./constants.js";
2
+ import { ALL_KEYS, EDITING_KEYS, FUNCTION_KEYS, KEY_DISPLAY_SYMBOLS, LETTER_KEYS, MAC_MODIFIER_SYMBOLS, MODIFIER_ALIASES, MODIFIER_KEYS, MODIFIER_ORDER, NAVIGATION_KEYS, NUMBER_KEYS, PUNCTUATION_CODE_MAP, PUNCTUATION_KEYS, STANDARD_MODIFIER_LABELS, detectPlatform, isSingleLetterKey, normalizeKeyName, resolveModifier } from "./constants.js";
3
3
  import { FormatKeyDebuggingOptions, formatForDisplay, formatHotkey, formatHotkeySequence, formatKeyForDebuggingDisplay, formatWithLabels } from "./format.js";
4
4
  import { ConflictBehavior } from "./manager.utils.js";
5
5
  import { HotkeyManager, HotkeyOptions, HotkeyRegistration, HotkeyRegistrationHandle, getHotkeyManager } from "./hotkey-manager.js";
@@ -9,4 +9,4 @@ import { convertToModFormat, hasNonModifierKey, isModifier, isModifierKey, keybo
9
9
  import { HotkeyRecorder, HotkeyRecorderOptions, HotkeyRecorderState } from "./recorder.js";
10
10
  import { HotkeySequence, SequenceManager, SequenceOptions, SequenceRegistrationHandle, SequenceRegistrationView, createSequenceMatcher, getSequenceManager } from "./sequence-manager.js";
11
11
  import { assertValidHotkey, checkHotkey, validateHotkey } from "./validate.js";
12
- export { ALL_KEYS, CanonicalModifier, ConflictBehavior, CreateHotkeyHandlerOptions, EDITING_KEYS, EditingKey, FUNCTION_KEYS, FormatDisplayOptions, FormatKeyDebuggingOptions, FunctionKey, HeldKey, Hotkey, HotkeyCallback, HotkeyCallbackContext, HotkeyManager, HotkeyOptions, HotkeyRecorder, HotkeyRecorderOptions, HotkeyRecorderState, HotkeyRegistration, HotkeyRegistrationHandle, HotkeySequence, KEY_DISPLAY_SYMBOLS, Key, KeyStateTracker, KeyStateTrackerState, LETTER_KEYS, LetterKey, MAC_MODIFIER_SYMBOLS, MODIFIER_ALIASES, MODIFIER_KEYS, MODIFIER_ORDER, Modifier, NAVIGATION_KEYS, NUMBER_KEYS, NavigationKey, NumberKey, PUNCTUATION_KEYS, ParsedHotkey, PunctuationKey, RawHotkey, RegisterableHotkey, STANDARD_MODIFIER_LABELS, SequenceManager, SequenceOptions, SequenceRegistrationHandle, SequenceRegistrationView, ValidationResult, assertValidHotkey, checkHotkey, convertToModFormat, createHotkeyHandler, createMultiHotkeyHandler, createSequenceMatcher, detectPlatform, formatForDisplay, formatHotkey, formatHotkeySequence, formatKeyForDebuggingDisplay, formatWithLabels, getHotkeyManager, getKeyStateTracker, getSequenceManager, hasNonModifierKey, isModifier, isModifierKey, isSingleLetterKey, keyboardEventToHotkey, matchesKeyboardEvent, normalizeHotkey, normalizeKeyName, parseHotkey, parseKeyboardEvent, rawHotkeyToParsedHotkey, resolveModifier, validateHotkey };
12
+ export { ALL_KEYS, CanonicalModifier, ConflictBehavior, CreateHotkeyHandlerOptions, EDITING_KEYS, EditingKey, FUNCTION_KEYS, FormatDisplayOptions, FormatKeyDebuggingOptions, FunctionKey, HeldKey, Hotkey, HotkeyCallback, HotkeyCallbackContext, HotkeyManager, HotkeyOptions, HotkeyRecorder, HotkeyRecorderOptions, HotkeyRecorderState, HotkeyRegistration, HotkeyRegistrationHandle, HotkeySequence, KEY_DISPLAY_SYMBOLS, Key, KeyStateTracker, KeyStateTrackerState, LETTER_KEYS, LetterKey, MAC_MODIFIER_SYMBOLS, MODIFIER_ALIASES, MODIFIER_KEYS, MODIFIER_ORDER, Modifier, NAVIGATION_KEYS, NUMBER_KEYS, NavigationKey, NumberKey, PUNCTUATION_CODE_MAP, PUNCTUATION_KEYS, ParsedHotkey, PunctuationKey, RawHotkey, RegisterableHotkey, STANDARD_MODIFIER_LABELS, SequenceManager, SequenceOptions, SequenceRegistrationHandle, SequenceRegistrationView, ValidationResult, assertValidHotkey, checkHotkey, convertToModFormat, createHotkeyHandler, createMultiHotkeyHandler, createSequenceMatcher, detectPlatform, formatForDisplay, formatHotkey, formatHotkeySequence, formatKeyForDebuggingDisplay, formatWithLabels, getHotkeyManager, getKeyStateTracker, getSequenceManager, hasNonModifierKey, isModifier, isModifierKey, isSingleLetterKey, keyboardEventToHotkey, matchesKeyboardEvent, normalizeHotkey, normalizeKeyName, parseHotkey, parseKeyboardEvent, rawHotkeyToParsedHotkey, resolveModifier, validateHotkey };
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { ALL_KEYS, EDITING_KEYS, FUNCTION_KEYS, KEY_DISPLAY_SYMBOLS, LETTER_KEYS, MAC_MODIFIER_SYMBOLS, MODIFIER_ALIASES, MODIFIER_KEYS, MODIFIER_ORDER, NAVIGATION_KEYS, NUMBER_KEYS, PUNCTUATION_KEYS, STANDARD_MODIFIER_LABELS, detectPlatform, isSingleLetterKey, normalizeKeyName, resolveModifier } from "./constants.js";
1
+ import { ALL_KEYS, EDITING_KEYS, FUNCTION_KEYS, KEY_DISPLAY_SYMBOLS, LETTER_KEYS, MAC_MODIFIER_SYMBOLS, MODIFIER_ALIASES, MODIFIER_KEYS, MODIFIER_ORDER, NAVIGATION_KEYS, NUMBER_KEYS, PUNCTUATION_CODE_MAP, PUNCTUATION_KEYS, STANDARD_MODIFIER_LABELS, detectPlatform, isSingleLetterKey, normalizeKeyName, resolveModifier } from "./constants.js";
2
2
  import { convertToModFormat, hasNonModifierKey, isModifier, isModifierKey, keyboardEventToHotkey, normalizeHotkey, parseHotkey, parseKeyboardEvent, rawHotkeyToParsedHotkey } from "./parse.js";
3
3
  import { formatForDisplay, formatHotkey, formatHotkeySequence, formatKeyForDebuggingDisplay, formatWithLabels } from "./format.js";
4
4
  import { createHotkeyHandler, createMultiHotkeyHandler, matchesKeyboardEvent } from "./match.js";
@@ -8,4 +8,4 @@ import { HotkeyRecorder } from "./recorder.js";
8
8
  import { SequenceManager, createSequenceMatcher, getSequenceManager } from "./sequence-manager.js";
9
9
  import { assertValidHotkey, checkHotkey, validateHotkey } from "./validate.js";
10
10
 
11
- export { ALL_KEYS, EDITING_KEYS, FUNCTION_KEYS, HotkeyManager, HotkeyRecorder, KEY_DISPLAY_SYMBOLS, KeyStateTracker, LETTER_KEYS, MAC_MODIFIER_SYMBOLS, MODIFIER_ALIASES, MODIFIER_KEYS, MODIFIER_ORDER, NAVIGATION_KEYS, NUMBER_KEYS, PUNCTUATION_KEYS, STANDARD_MODIFIER_LABELS, SequenceManager, assertValidHotkey, checkHotkey, convertToModFormat, createHotkeyHandler, createMultiHotkeyHandler, createSequenceMatcher, detectPlatform, formatForDisplay, formatHotkey, formatHotkeySequence, formatKeyForDebuggingDisplay, formatWithLabels, getHotkeyManager, getKeyStateTracker, getSequenceManager, hasNonModifierKey, isModifier, isModifierKey, isSingleLetterKey, keyboardEventToHotkey, matchesKeyboardEvent, normalizeHotkey, normalizeKeyName, parseHotkey, parseKeyboardEvent, rawHotkeyToParsedHotkey, resolveModifier, validateHotkey };
11
+ export { ALL_KEYS, EDITING_KEYS, FUNCTION_KEYS, HotkeyManager, HotkeyRecorder, KEY_DISPLAY_SYMBOLS, KeyStateTracker, LETTER_KEYS, MAC_MODIFIER_SYMBOLS, MODIFIER_ALIASES, MODIFIER_KEYS, MODIFIER_ORDER, NAVIGATION_KEYS, NUMBER_KEYS, PUNCTUATION_CODE_MAP, PUNCTUATION_KEYS, STANDARD_MODIFIER_LABELS, SequenceManager, assertValidHotkey, checkHotkey, convertToModFormat, createHotkeyHandler, createMultiHotkeyHandler, createSequenceMatcher, detectPlatform, formatForDisplay, formatHotkey, formatHotkeySequence, formatKeyForDebuggingDisplay, formatWithLabels, getHotkeyManager, getKeyStateTracker, getSequenceManager, hasNonModifierKey, isModifier, isModifierKey, isSingleLetterKey, keyboardEventToHotkey, matchesKeyboardEvent, normalizeHotkey, normalizeKeyName, parseHotkey, parseKeyboardEvent, rawHotkeyToParsedHotkey, resolveModifier, validateHotkey };
package/dist/match.cjs CHANGED
@@ -6,8 +6,9 @@ const require_parse = require('./parse.cjs');
6
6
  * Checks if a KeyboardEvent matches a hotkey.
7
7
  *
8
8
  * Uses the `key` property from KeyboardEvent for matching, with a fallback to `code`
9
- * for letter keys and digit keys (0-9) when `key` produces special characters
10
- * (e.g., macOS Option+letter or Shift+number). Letter keys are matched case-insensitively.
9
+ * for letter keys, digit keys (0-9), and punctuation keys when `key` produces special
10
+ * characters (e.g., macOS Option+letter, Shift+number, or Option+punctuation).
11
+ * Letter keys are matched case-insensitively.
11
12
  *
12
13
  * Also handles "dead key" events where `event.key` is `'Dead'` instead of the expected
13
14
  * character. This commonly occurs on macOS with Option+letter combinations (e.g., Option+E,
@@ -41,15 +42,16 @@ function matchesKeyboardEvent(event, hotkey, platform = require_constants.detect
41
42
  if (eventKey.toUpperCase() === hotkeyKey.toUpperCase()) return true;
42
43
  if (require_constants.isSingleLetterKey(eventKey) && (/^[A-Za-z]$/.test(eventKey) || !event.altKey)) return false;
43
44
  }
44
- if (eventKey === "Dead" || eventKey.length === 1 && hotkeyKey.length === 1) {
45
- if (event.code?.startsWith("Key")) {
45
+ if (event.code && (eventKey === "Dead" || eventKey.length === 1 && hotkeyKey.length === 1)) {
46
+ if (event.code.startsWith("Key")) {
46
47
  const codeLetter = event.code.slice(3);
47
48
  if (codeLetter.length === 1 && /^[A-Za-z]$/.test(codeLetter)) return codeLetter.toUpperCase() === hotkeyKey.toUpperCase();
48
49
  }
49
- if (event.code?.startsWith("Digit")) {
50
+ if (event.code.startsWith("Digit")) {
50
51
  const codeDigit = event.code.slice(5);
51
52
  if (codeDigit.length === 1 && /^[0-9]$/.test(codeDigit)) return codeDigit === hotkeyKey;
52
53
  }
54
+ if (event.code in require_constants.PUNCTUATION_CODE_MAP) return require_constants.PUNCTUATION_CODE_MAP[event.code] === hotkeyKey;
53
55
  return false;
54
56
  }
55
57
  return eventKey === hotkeyKey;
@@ -1 +1 @@
1
- {"version":3,"file":"match.cjs","names":["detectPlatform","parseHotkey","normalizeKeyName","isSingleLetterKey"],"sources":["../src/match.ts"],"sourcesContent":["import {\n detectPlatform,\n isSingleLetterKey,\n normalizeKeyName,\n} from './constants'\nimport { parseHotkey } from './parse'\nimport type {\n Hotkey,\n HotkeyCallback,\n HotkeyCallbackContext,\n ParsedHotkey,\n} from './hotkey'\n\n/**\n * Checks if a KeyboardEvent matches a hotkey.\n *\n * Uses the `key` property from KeyboardEvent for matching, with a fallback to `code`\n * for letter keys and digit keys (0-9) when `key` produces special characters\n * (e.g., macOS Option+letter or Shift+number). 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 const parsed =\n typeof hotkey === 'string' ? parseHotkey(hotkey, platform) : hotkey\n\n // Check modifiers\n if (event.ctrlKey !== parsed.ctrl) {\n return false\n }\n if (event.shiftKey !== parsed.shift) {\n return false\n }\n if (event.altKey !== parsed.alt) {\n return false\n }\n if (event.metaKey !== parsed.meta) {\n return false\n }\n\n // Check key (case-insensitive for letters)\n const eventKey = normalizeKeyName(event.key)\n const hotkeyKey = parsed.key\n\n // For single-character keys (not dead keys), try direct event.key match first\n if (eventKey !== 'Dead' && eventKey.length === 1 && hotkeyKey.length === 1) {\n if (eventKey.toUpperCase() === hotkeyKey.toUpperCase()) {\n return true\n }\n\n // If event.key is a letter, we usually trust the keyboard layout.\n // For ASCII letters: always trust layout (Dvorak, Colemak, AZERTY support).\n // For non-ASCII letters without Alt: trust layout (e.g., Cyrillic keyboards).\n //\n // For non-ASCII letters WITH Alt held down: fall through to the event.code\n // fallback. macOS Option+letter combinations produce non-ASCII letters as\n // event.key (e.g., Option+A → 'å', Option+' → 'æ', Option+P → 'π'), but\n // event.code still reflects the physical key. We want Alt+A to match even\n // when Option+A fires event.key='å'.\n if (\n isSingleLetterKey(eventKey) &&\n (/^[A-Za-z]$/.test(eventKey) || !event.altKey)\n ) {\n return false\n }\n }\n\n // Fallback to event.code for dead keys or single-char mismatches where\n // event.key is a non-letter special character.\n // Dead keys: Option+letter on macOS, international layouts produce event.key === 'Dead'\n // Single-char mismatches: Cmd+Option+T gives '†' instead of 'T', Shift+4 gives '$'\n if (\n eventKey === 'Dead' ||\n (eventKey.length === 1 && hotkeyKey.length === 1)\n ) {\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- event.code can be undefined in older browsers/mobile\n if (event.code?.startsWith('Key')) {\n const codeLetter = event.code.slice(3)\n if (codeLetter.length === 1 && /^[A-Za-z]$/.test(codeLetter)) {\n return codeLetter.toUpperCase() === hotkeyKey.toUpperCase()\n }\n }\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- event.code can be undefined in older browsers/mobile\n if (event.code?.startsWith('Digit')) {\n const codeDigit = event.code.slice(5)\n if (codeDigit.length === 1 && /^[0-9]$/.test(codeDigit)) {\n return codeDigit === hotkeyKey\n }\n }\n return false\n }\n\n // For special keys, compare exactly (after normalization)\n return eventKey === hotkeyKey\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\ntype 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.key)\n\n return parts.join('+') as Hotkey\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,SAAgB,qBACd,OACA,QACA,WAAwCA,kCAAgB,EAC/C;CACT,MAAM,SACJ,OAAO,WAAW,WAAWC,0BAAY,QAAQ,SAAS,GAAG;AAG/D,KAAI,MAAM,YAAY,OAAO,KAC3B,QAAO;AAET,KAAI,MAAM,aAAa,OAAO,MAC5B,QAAO;AAET,KAAI,MAAM,WAAW,OAAO,IAC1B,QAAO;AAET,KAAI,MAAM,YAAY,OAAO,KAC3B,QAAO;CAIT,MAAM,WAAWC,mCAAiB,MAAM,IAAI;CAC5C,MAAM,YAAY,OAAO;AAGzB,KAAI,aAAa,UAAU,SAAS,WAAW,KAAK,UAAU,WAAW,GAAG;AAC1E,MAAI,SAAS,aAAa,KAAK,UAAU,aAAa,CACpD,QAAO;AAYT,MACEC,oCAAkB,SAAS,KAC1B,aAAa,KAAK,SAAS,IAAI,CAAC,MAAM,QAEvC,QAAO;;AAQX,KACE,aAAa,UACZ,SAAS,WAAW,KAAK,UAAU,WAAW,GAC/C;AAEA,MAAI,MAAM,MAAM,WAAW,MAAM,EAAE;GACjC,MAAM,a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M,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,IAAI;AAEtB,QAAO,MAAM,KAAK,IAAI"}
1
+ {"version":3,"file":"match.cjs","names":["detectPlatform","parseHotkey","normalizeKeyName","isSingleLetterKey","PUNCTUATION_CODE_MAP"],"sources":["../src/match.ts"],"sourcesContent":["import {\n PUNCTUATION_CODE_MAP,\n detectPlatform,\n isSingleLetterKey,\n normalizeKeyName,\n} from './constants'\nimport { parseHotkey } from './parse'\nimport type {\n Hotkey,\n HotkeyCallback,\n HotkeyCallbackContext,\n ParsedHotkey,\n} from './hotkey'\n\n/**\n * Checks if a KeyboardEvent matches a hotkey.\n *\n * Uses the `key` property from KeyboardEvent for matching, 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 const parsed =\n typeof hotkey === 'string' ? parseHotkey(hotkey, platform) : hotkey\n\n // Check modifiers\n if (event.ctrlKey !== parsed.ctrl) {\n return false\n }\n if (event.shiftKey !== parsed.shift) {\n return false\n }\n if (event.altKey !== parsed.alt) {\n return false\n }\n if (event.metaKey !== parsed.meta) {\n return false\n }\n\n // Check key (case-insensitive for letters)\n const eventKey = normalizeKeyName(event.key)\n const hotkeyKey = parsed.key\n\n // For single-character keys (not dead keys), try direct event.key match first\n if (eventKey !== 'Dead' && eventKey.length === 1 && hotkeyKey.length === 1) {\n if (eventKey.toUpperCase() === hotkeyKey.toUpperCase()) {\n return true\n }\n\n // If event.key is a letter, we usually trust the keyboard layout.\n // For ASCII letters: always trust layout (Dvorak, Colemak, AZERTY support).\n // For non-ASCII letters without Alt: trust layout (e.g., Cyrillic keyboards).\n //\n // For non-ASCII letters WITH Alt held down: fall through to the event.code\n // fallback. macOS Option+letter combinations produce non-ASCII letters as\n // event.key (e.g., Option+A → 'å', Option+' → 'æ', Option+P → 'π'), but\n // event.code still reflects the physical key. We want Alt+A to match even\n // when Option+A fires event.key='å'.\n if (\n isSingleLetterKey(eventKey) &&\n (/^[A-Za-z]$/.test(eventKey) || !event.altKey)\n ) {\n return false\n }\n }\n\n // Fallback to event.code for dead keys or single-char mismatches where\n // event.key is a non-letter special character.\n // Dead keys: Option+letter on macOS, international layouts produce event.key === 'Dead'\n // Single-char mismatches: Cmd+Option+T gives '†' instead of 'T', Shift+4 gives '$'\n if (\n event.code &&\n (eventKey === 'Dead' || (eventKey.length === 1 && hotkeyKey.length === 1))\n ) {\n // fallback for letter keys (common with mac option + letter)\n if (event.code.startsWith('Key')) {\n const codeLetter = event.code.slice(3)\n if (codeLetter.length === 1 && /^[A-Za-z]$/.test(codeLetter)) {\n return codeLetter.toUpperCase() === hotkeyKey.toUpperCase()\n }\n }\n\n // fallback for number keys (common with mac option + num)\n if (event.code.startsWith('Digit')) {\n const codeDigit = event.code.slice(5)\n if (codeDigit.length === 1 && /^[0-9]$/.test(codeDigit)) {\n return codeDigit === hotkeyKey\n }\n }\n // Fallback for punctuation keys (e.g., Minus, Slash, BracketLeft).\n // On macOS, Option+punctuation produces composed characters (e.g., Option+- → '–'),\n // but event.code still reports the physical key.\n if (event.code in PUNCTUATION_CODE_MAP) {\n return PUNCTUATION_CODE_MAP[event.code] === hotkeyKey\n }\n\n return false\n }\n\n // For special keys, compare exactly (after normalization)\n return eventKey === hotkeyKey\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\ntype 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.key)\n\n return parts.join('+') as Hotkey\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0CA,SAAgB,qBACd,OACA,QACA,WAAwCA,kCAAgB,EAC/C;CACT,MAAM,SACJ,OAAO,WAAW,WAAWC,0BAAY,QAAQ,SAAS,GAAG;AAG/D,KAAI,MAAM,YAAY,OAAO,KAC3B,QAAO;AAET,KAAI,MAAM,aAAa,OAAO,MAC5B,QAAO;AAET,KAAI,MAAM,WAAW,OAAO,IAC1B,QAAO;AAET,KAAI,MAAM,YAAY,OAAO,KAC3B,QAAO;CAIT,MAAM,WAAWC,mCAAiB,MAAM,IAAI;CAC5C,MAAM,YAAY,OAAO;AAGzB,KAAI,aAAa,UAAU,SAAS,WAAW,KAAK,UAAU,WAAW,GAAG;AAC1E,MAAI,SAAS,aAAa,KAAK,UAAU,aAAa,CACpD,QAAO;AAYT,MACEC,oCAAkB,SAAS,KAC1B,aAAa,KAAK,SAAS,IAAI,CAAC,MAAM,QAEvC,QAAO;;AAQX,KACE,MAAM,SACL,aAAa,UAAW,SAAS,WAAW,KAAK,UAAU,WAAW,IACvE;AAEA,MAAI,MAAM,KAAK,WAAW,MAAM,EAAE;GAChC,MAAM,aAAa,MAAM,KAAK,MAAM,EAAE;AACtC,OAAI,WAAW,WAAW,KAAK,aAAa,KAAK,WAAW,CAC1D,QAAO,WAAW,aAAa,KAAK,UAAU,aAAa;;AAK/D,MAAI,MAAM,KAAK,WAAW,QAAQ,EAAE;GAClC,MAAM,YAAY,MAAM,KAAK,MAAM,EAAE;AACrC,OAAI,UAAU,WAAW,KAAK,UAAU,KAAK,UAAU,CACrD,QAAO,cAAc;;AAMzB,MAAI,MAAM,Q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;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,IAAI;AAEtB,QAAO,MAAM,KAAK,IAAI"}
package/dist/match.d.cts CHANGED
@@ -5,8 +5,9 @@ import { Hotkey, HotkeyCallback, ParsedHotkey } from "./hotkey.cjs";
5
5
  * Checks if a KeyboardEvent matches a hotkey.
6
6
  *
7
7
  * Uses the `key` property from KeyboardEvent for matching, with a fallback to `code`
8
- * for letter keys and digit keys (0-9) when `key` produces special characters
9
- * (e.g., macOS Option+letter or Shift+number). Letter keys are matched case-insensitively.
8
+ * for letter keys, digit keys (0-9), and punctuation keys when `key` produces special
9
+ * characters (e.g., macOS Option+letter, Shift+number, or Option+punctuation).
10
+ * Letter keys are matched case-insensitively.
10
11
  *
11
12
  * Also handles "dead key" events where `event.key` is `'Dead'` instead of the expected
12
13
  * character. This commonly occurs on macOS with Option+letter combinations (e.g., Option+E,
package/dist/match.d.ts CHANGED
@@ -5,8 +5,9 @@ import { Hotkey, HotkeyCallback, ParsedHotkey } from "./hotkey.js";
5
5
  * Checks if a KeyboardEvent matches a hotkey.
6
6
  *
7
7
  * Uses the `key` property from KeyboardEvent for matching, with a fallback to `code`
8
- * for letter keys and digit keys (0-9) when `key` produces special characters
9
- * (e.g., macOS Option+letter or Shift+number). Letter keys are matched case-insensitively.
8
+ * for letter keys, digit keys (0-9), and punctuation keys when `key` produces special
9
+ * characters (e.g., macOS Option+letter, Shift+number, or Option+punctuation).
10
+ * Letter keys are matched case-insensitively.
10
11
  *
11
12
  * Also handles "dead key" events where `event.key` is `'Dead'` instead of the expected
12
13
  * character. This commonly occurs on macOS with Option+letter combinations (e.g., Option+E,
package/dist/match.js CHANGED
@@ -1,4 +1,4 @@
1
- import { detectPlatform, isSingleLetterKey, normalizeKeyName } from "./constants.js";
1
+ import { PUNCTUATION_CODE_MAP, detectPlatform, isSingleLetterKey, normalizeKeyName } from "./constants.js";
2
2
  import { parseHotkey } from "./parse.js";
3
3
 
4
4
  //#region src/match.ts
@@ -6,8 +6,9 @@ import { parseHotkey } from "./parse.js";
6
6
  * Checks if a KeyboardEvent matches a hotkey.
7
7
  *
8
8
  * Uses the `key` property from KeyboardEvent for matching, with a fallback to `code`
9
- * for letter keys and digit keys (0-9) when `key` produces special characters
10
- * (e.g., macOS Option+letter or Shift+number). Letter keys are matched case-insensitively.
9
+ * for letter keys, digit keys (0-9), and punctuation keys when `key` produces special
10
+ * characters (e.g., macOS Option+letter, Shift+number, or Option+punctuation).
11
+ * Letter keys are matched case-insensitively.
11
12
  *
12
13
  * Also handles "dead key" events where `event.key` is `'Dead'` instead of the expected
13
14
  * character. This commonly occurs on macOS with Option+letter combinations (e.g., Option+E,
@@ -41,15 +42,16 @@ function matchesKeyboardEvent(event, hotkey, platform = detectPlatform()) {
41
42
  if (eventKey.toUpperCase() === hotkeyKey.toUpperCase()) return true;
42
43
  if (isSingleLetterKey(eventKey) && (/^[A-Za-z]$/.test(eventKey) || !event.altKey)) return false;
43
44
  }
44
- if (eventKey === "Dead" || eventKey.length === 1 && hotkeyKey.length === 1) {
45
- if (event.code?.startsWith("Key")) {
45
+ if (event.code && (eventKey === "Dead" || eventKey.length === 1 && hotkeyKey.length === 1)) {
46
+ if (event.code.startsWith("Key")) {
46
47
  const codeLetter = event.code.slice(3);
47
48
  if (codeLetter.length === 1 && /^[A-Za-z]$/.test(codeLetter)) return codeLetter.toUpperCase() === hotkeyKey.toUpperCase();
48
49
  }
49
- if (event.code?.startsWith("Digit")) {
50
+ if (event.code.startsWith("Digit")) {
50
51
  const codeDigit = event.code.slice(5);
51
52
  if (codeDigit.length === 1 && /^[0-9]$/.test(codeDigit)) return codeDigit === hotkeyKey;
52
53
  }
54
+ if (event.code in PUNCTUATION_CODE_MAP) return PUNCTUATION_CODE_MAP[event.code] === hotkeyKey;
53
55
  return false;
54
56
  }
55
57
  return eventKey === hotkeyKey;
package/dist/match.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"match.js","names":[],"sources":["../src/match.ts"],"sourcesContent":["import {\n detectPlatform,\n isSingleLetterKey,\n normalizeKeyName,\n} from './constants'\nimport { parseHotkey } from './parse'\nimport type {\n Hotkey,\n HotkeyCallback,\n HotkeyCallbackContext,\n ParsedHotkey,\n} from './hotkey'\n\n/**\n * Checks if a KeyboardEvent matches a hotkey.\n *\n * Uses the `key` property from KeyboardEvent for matching, with a fallback to `code`\n * for letter keys and digit keys (0-9) when `key` produces special characters\n * (e.g., macOS Option+letter or Shift+number). 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 const parsed =\n typeof hotkey === 'string' ? parseHotkey(hotkey, platform) : hotkey\n\n // Check modifiers\n if (event.ctrlKey !== parsed.ctrl) {\n return false\n }\n if (event.shiftKey !== parsed.shift) {\n return false\n }\n if (event.altKey !== parsed.alt) {\n return false\n }\n if (event.metaKey !== parsed.meta) {\n return false\n }\n\n // Check key (case-insensitive for letters)\n const eventKey = normalizeKeyName(event.key)\n const hotkeyKey = parsed.key\n\n // For single-character keys (not dead keys), try direct event.key match first\n if (eventKey !== 'Dead' && eventKey.length === 1 && hotkeyKey.length === 1) {\n if (eventKey.toUpperCase() === hotkeyKey.toUpperCase()) {\n return true\n }\n\n // If event.key is a letter, we usually trust the keyboard layout.\n // For ASCII letters: always trust layout (Dvorak, Colemak, AZERTY support).\n // For non-ASCII letters without Alt: trust layout (e.g., Cyrillic keyboards).\n //\n // For non-ASCII letters WITH Alt held down: fall through to the event.code\n // fallback. macOS Option+letter combinations produce non-ASCII letters as\n // event.key (e.g., Option+A → 'å', Option+' → 'æ', Option+P → 'π'), but\n // event.code still reflects the physical key. We want Alt+A to match even\n // when Option+A fires event.key='å'.\n if (\n isSingleLetterKey(eventKey) &&\n (/^[A-Za-z]$/.test(eventKey) || !event.altKey)\n ) {\n return false\n }\n }\n\n // Fallback to event.code for dead keys or single-char mismatches where\n // event.key is a non-letter special character.\n // Dead keys: Option+letter on macOS, international layouts produce event.key === 'Dead'\n // Single-char mismatches: Cmd+Option+T gives '†' instead of 'T', Shift+4 gives '$'\n if (\n eventKey === 'Dead' ||\n (eventKey.length === 1 && hotkeyKey.length === 1)\n ) {\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- event.code can be undefined in older browsers/mobile\n if (event.code?.startsWith('Key')) {\n const codeLetter = event.code.slice(3)\n if (codeLetter.length === 1 && /^[A-Za-z]$/.test(codeLetter)) {\n return codeLetter.toUpperCase() === hotkeyKey.toUpperCase()\n }\n }\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- event.code can be undefined in older browsers/mobile\n if (event.code?.startsWith('Digit')) {\n const codeDigit = event.code.slice(5)\n if (codeDigit.length === 1 && /^[0-9]$/.test(codeDigit)) {\n return codeDigit === hotkeyKey\n }\n }\n return false\n }\n\n // For special keys, compare exactly (after normalization)\n return eventKey === hotkeyKey\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\ntype 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.key)\n\n return parts.join('+') as Hotkey\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,SAAgB,qBACd,OACA,QACA,WAAwC,gBAAgB,EAC/C;CACT,MAAM,SACJ,OAAO,WAAW,WAAW,YAAY,QAAQ,SAAS,GAAG;AAG/D,KAAI,MAAM,YAAY,OAAO,KAC3B,QAAO;AAET,KAAI,MAAM,aAAa,OAAO,MAC5B,QAAO;AAET,KAAI,MAAM,WAAW,OAAO,IAC1B,QAAO;AAET,KAAI,MAAM,YAAY,OAAO,KAC3B,QAAO;CAIT,MAAM,WAAW,iBAAiB,MAAM,IAAI;CAC5C,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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,IAAI;AAEtB,QAAO,MAAM,KAAK,IAAI"}
1
+ {"version":3,"file":"match.js","names":[],"sources":["../src/match.ts"],"sourcesContent":["import {\n PUNCTUATION_CODE_MAP,\n detectPlatform,\n isSingleLetterKey,\n normalizeKeyName,\n} from './constants'\nimport { parseHotkey } from './parse'\nimport type {\n Hotkey,\n HotkeyCallback,\n HotkeyCallbackContext,\n ParsedHotkey,\n} from './hotkey'\n\n/**\n * Checks if a KeyboardEvent matches a hotkey.\n *\n * Uses the `key` property from KeyboardEvent for matching, 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 const parsed =\n typeof hotkey === 'string' ? parseHotkey(hotkey, platform) : hotkey\n\n // Check modifiers\n if (event.ctrlKey !== parsed.ctrl) {\n return false\n }\n if (event.shiftKey !== parsed.shift) {\n return false\n }\n if (event.altKey !== parsed.alt) {\n return false\n }\n if (event.metaKey !== parsed.meta) {\n return false\n }\n\n // Check key (case-insensitive for letters)\n const eventKey = normalizeKeyName(event.key)\n const hotkeyKey = parsed.key\n\n // For single-character keys (not dead keys), try direct event.key match first\n if (eventKey !== 'Dead' && eventKey.length === 1 && hotkeyKey.length === 1) {\n if (eventKey.toUpperCase() === hotkeyKey.toUpperCase()) {\n return true\n }\n\n // If event.key is a letter, we usually trust the keyboard layout.\n // For ASCII letters: always trust layout (Dvorak, Colemak, AZERTY support).\n // For non-ASCII letters without Alt: trust layout (e.g., Cyrillic keyboards).\n //\n // For non-ASCII letters WITH Alt held down: fall through to the event.code\n // fallback. macOS Option+letter combinations produce non-ASCII letters as\n // event.key (e.g., Option+A → 'å', Option+' → 'æ', Option+P → 'π'), but\n // event.code still reflects the physical key. We want Alt+A to match even\n // when Option+A fires event.key='å'.\n if (\n isSingleLetterKey(eventKey) &&\n (/^[A-Za-z]$/.test(eventKey) || !event.altKey)\n ) {\n return false\n }\n }\n\n // Fallback to event.code for dead keys or single-char mismatches where\n // event.key is a non-letter special character.\n // Dead keys: Option+letter on macOS, international layouts produce event.key === 'Dead'\n // Single-char mismatches: Cmd+Option+T gives '†' instead of 'T', Shift+4 gives '$'\n if (\n event.code &&\n (eventKey === 'Dead' || (eventKey.length === 1 && hotkeyKey.length === 1))\n ) {\n // fallback for letter keys (common with mac option + letter)\n if (event.code.startsWith('Key')) {\n const codeLetter = event.code.slice(3)\n if (codeLetter.length === 1 && /^[A-Za-z]$/.test(codeLetter)) {\n return codeLetter.toUpperCase() === hotkeyKey.toUpperCase()\n }\n }\n\n // fallback for number keys (common with mac option + num)\n if (event.code.startsWith('Digit')) {\n const codeDigit = event.code.slice(5)\n if (codeDigit.length === 1 && /^[0-9]$/.test(codeDigit)) {\n return codeDigit === hotkeyKey\n }\n }\n // Fallback for punctuation keys (e.g., Minus, Slash, BracketLeft).\n // On macOS, Option+punctuation produces composed characters (e.g., Option+- → '–'),\n // but event.code still reports the physical key.\n if (event.code in PUNCTUATION_CODE_MAP) {\n return PUNCTUATION_CODE_MAP[event.code] === hotkeyKey\n }\n\n return false\n }\n\n // For special keys, compare exactly (after normalization)\n return eventKey === hotkeyKey\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\ntype 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.key)\n\n return parts.join('+') as Hotkey\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0CA,SAAgB,qBACd,OACA,QACA,WAAwC,gBAAgB,EAC/C;CACT,MAAM,SACJ,OAAO,WAAW,WAAW,YAAY,QAAQ,SAAS,GAAG;AAG/D,KAAI,MAAM,YAAY,OAAO,KAC3B,QAAO;AAET,KAAI,MAAM,aAAa,OAAO,MAC5B,QAAO;AAET,KAAI,MAAM,WAAW,OAAO,IAC1B,QAAO;AAET,KAAI,MAAM,YAAY,OAAO,KAC3B,QAAO;CAIT,MAAM,WAAW,iBAAiB,MAAM,IAAI;CAC5C,MAAM,YAAY,OAAO;AAGzB,KAAI,aAAa,UAAU,SAAS,WAAW,KAAK,UAAU,WAAW,GAAG;AAC1E,MAAI,SAAS,aAAa,KAAK,UAAU,aAAa,CACpD,QAAO;AAYT,MACE,kBAAkB,SAAS,KAC1B,aAAa,KAAK,SAAS,IAAI,CAAC,MAAM,QAEvC,QAAO;;AAQX,KACE,MAAM,SACL,aAAa,UAAW,SAAS,WAAW,KAAK,UAAU,WAAW,IACvE;AAEA,MAAI,MAAM,KAAK,WAAW,MAAM,EAAE;GAChC,MAAM,aAAa,MAAM,KAAK,MAAM,EAAE;AACtC,OA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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,IAAI;AAEtB,QAAO,MAAM,KAAK,IAAI"}
@@ -30,6 +30,11 @@ function sequenceKey(sequence) {
30
30
  * that trigger callbacks when the full sequence is pressed within
31
31
  * a configurable timeout.
32
32
  *
33
+ * Modifier-only `keydown` / `keyup` events (Shift, Control, Alt, or Meta
34
+ * alone) are not processed: they neither match a step nor reset progress.
35
+ * That supports chained modifier chords (e.g. `Shift+R` then `Shift+T`) when
36
+ * the user presses a modifier alone between steps.
37
+ *
33
38
  * @example
34
39
  * ```ts
35
40
  * const matcher = SequenceManager.getInstance()
@@ -218,6 +223,7 @@ var SequenceManager = class SequenceManager {
218
223
  * Processes keyboard events for a specific target and event type.
219
224
  */
220
225
  #processTargetEvent(event, target, eventType) {
226
+ if (require_parse.isModifierKey(event)) return;
221
227
  const targetRegs = this.#targetRegistrations.get(target);
222
228
  if (!targetRegs) return;
223
229
  const now = Date.now();
@@ -1 +1 @@
1
- {"version":3,"file":"sequence-manager.cjs","names":["#instance","Store","#platform","detectPlatform","parseHotkey","#findConflictingSequence","formatHotkeySequence","#unregister","getDefaultIgnoreInputs","defaultHotkeyOptions","#registrations","#targetRegistrations","#ensureListenersForTarget","#removeListenersForTarget","#targetListeners","#createTargetKeyDownHandler","#createTargetKeyUpHandler","#processTargetEvent","isEventForTarget","isInputElement","matchesKeyboardEvent"],"sources":["../src/sequence-manager.ts"],"sourcesContent":["import { Store } from '@tanstack/store'\nimport { formatHotkeySequence } from './format'\nimport { detectPlatform } from './constants'\nimport { parseHotkey } from './parse'\nimport { matchesKeyboardEvent } from './match'\nimport {\n defaultHotkeyOptions,\n getDefaultIgnoreInputs,\n handleConflict,\n isEventForTarget,\n isInputElement,\n} from './manager.utils'\nimport type { HotkeyOptions } from './hotkey-manager'\nimport type {\n Hotkey,\n HotkeyCallback,\n HotkeyCallbackContext,\n ParsedHotkey,\n} from './hotkey'\n\ntype Target = HTMLElement | Document | Window\n\n/**\n * Options for hotkey sequence matching.\n * Extends HotkeyOptions but excludes requireReset (not applicable to sequences).\n */\nexport interface SequenceOptions extends Omit<HotkeyOptions, 'requireReset'> {\n /** Timeout between keys in milliseconds. Default: 1000 */\n timeout?: number\n}\n\n/**\n * A sequence of hotkeys for Vim-style shortcuts.\n *\n * @example\n * ```ts\n * const gotoTop: HotkeySequence = ['G', 'G'] // gg\n * const deleteLine: HotkeySequence = ['D', 'D'] // dd\n * const deleteWord: HotkeySequence = ['D', 'I', 'W'] // diw\n * ```\n */\nexport type HotkeySequence = Array<Hotkey>\n\n/**\n * Default timeout between keys in a sequence (in milliseconds).\n */\nconst DEFAULT_SEQUENCE_TIMEOUT = 1000\n\nlet sequenceIdCounter = 0\n\n/**\n * Generates a unique ID for sequence registrations.\n */\nfunction generateSequenceId(): string {\n return `sequence_${++sequenceIdCounter}`\n}\n\n/**\n * Returns a canonical string for sequence conflict comparison.\n */\nfunction sequenceKey(sequence: HotkeySequence): string {\n return sequence.join('|')\n}\n\n/**\n * View of a sequence registration for devtools display.\n * Excludes internal matching state (currentIndex, lastKeyTime).\n */\nexport interface SequenceRegistrationView {\n id: string\n sequence: HotkeySequence\n options: SequenceOptions\n target: Target\n triggerCount: number\n}\n\n/**\n * Internal representation of a sequence registration.\n */\ninterface SequenceRegistration {\n id: string\n sequence: HotkeySequence\n parsedSequence: Array<ParsedHotkey>\n callback: HotkeyCallback\n options: SequenceOptions\n target: Target\n currentIndex: number\n lastKeyTime: number\n triggerCount: number\n}\n\n/**\n * A handle returned from SequenceManager.register() that allows updating\n * the callback and options without re-registering the sequence.\n *\n * @example\n * ```ts\n * const handle = manager.register(['G', 'G'], callback, options)\n *\n * handle.callback = newCallback\n * handle.setOptions({ timeout: 500 })\n * handle.unregister()\n * ```\n */\nexport interface SequenceRegistrationHandle {\n readonly id: string\n readonly isActive: boolean\n callback: HotkeyCallback\n setOptions: (options: Partial<SequenceOptions>) => void\n unregister: () => void\n}\n\n/**\n * Manages keyboard sequence matching for Vim-style shortcuts.\n *\n * This class allows registering multi-key sequences like 'g g' or 'd d'\n * that trigger callbacks when the full sequence is pressed within\n * a configurable timeout.\n *\n * @example\n * ```ts\n * const matcher = SequenceManager.getInstance()\n *\n * // Register 'g g' to go to top\n * const unregister = matcher.register(['G', 'G'], (event, context) => {\n * scrollToTop()\n * }, { timeout: 500 })\n *\n * // Later, to unregister:\n * unregister()\n * ```\n */\n/**\n * Builds a devtools view from an internal registration.\n */\nfunction toRegistrationView(\n reg: SequenceRegistration,\n): SequenceRegistrationView {\n return {\n id: reg.id,\n sequence: reg.sequence,\n options: reg.options,\n target: reg.target,\n triggerCount: reg.triggerCount,\n }\n}\n\nexport class SequenceManager {\n static #instance: SequenceManager | null = null\n\n /**\n * The TanStack Store containing sequence registration views for devtools.\n * Subscribe to this to observe registration changes.\n */\n readonly registrations: Store<Map<string, SequenceRegistrationView>> =\n new Store(new Map())\n\n #registrations: Map<string, SequenceRegistration> = new Map()\n #targetListeners: Map<\n Target,\n {\n keydown: (event: KeyboardEvent) => void\n keyup: (event: KeyboardEvent) => void\n }\n > = new Map()\n #targetRegistrations: Map<Target, Set<string>> = new Map()\n #platform: 'mac' | 'windows' | 'linux'\n\n private constructor() {\n this.#platform = detectPlatform()\n }\n\n /**\n * Gets the singleton instance of SequenceManager.\n */\n static getInstance(): SequenceManager {\n if (!SequenceManager.#instance) {\n SequenceManager.#instance = new SequenceManager()\n }\n return SequenceManager.#instance\n }\n\n /**\n * Resets the singleton instance. Useful for testing.\n */\n static resetInstance(): void {\n if (SequenceManager.#instance) {\n SequenceManager.#instance.destroy()\n SequenceManager.#instance = null\n }\n }\n\n /**\n * Registers a hotkey sequence handler.\n *\n * @param sequence - Array of hotkey strings that form the sequence\n * @param callback - Function to call when the sequence is completed\n * @param options - Options for the sequence behavior\n * @returns A handle to update or unregister the sequence\n */\n register(\n sequence: HotkeySequence,\n callback: HotkeyCallback,\n options: SequenceOptions = {},\n ): SequenceRegistrationHandle {\n if (sequence.length === 0) {\n throw new Error('Sequence must contain at least one hotkey')\n }\n\n const id = generateSequenceId()\n const platform = options.platform ?? this.#platform\n const parsedSequence = sequence.map((hotkey) =>\n parseHotkey(hotkey, platform),\n )\n\n // Resolve target: default to document if not provided or null\n const target: Target =\n options.target ??\n (typeof document !== 'undefined' ? document : ({} as Document))\n\n // Resolve conflict behavior\n const conflictBehavior = options.conflictBehavior ?? 'warn'\n\n // Check for existing registrations with the same sequence and target\n const conflictingRegistration = this.#findConflictingSequence(\n sequence,\n target,\n )\n\n if (conflictingRegistration) {\n handleConflict(\n conflictingRegistration.id,\n formatHotkeySequence(sequence),\n conflictBehavior,\n (regId) => this.#unregister(regId),\n )\n }\n\n const firstStep = parsedSequence[0]!\n const resolvedIgnoreInputs =\n options.ignoreInputs ?? getDefaultIgnoreInputs(firstStep)\n\n const baseOptions = {\n ...defaultHotkeyOptions,\n timeout: DEFAULT_SEQUENCE_TIMEOUT,\n ...options,\n platform,\n ignoreInputs: resolvedIgnoreInputs,\n }\n\n const registration: SequenceRegistration = {\n id,\n sequence,\n parsedSequence,\n callback,\n options: baseOptions,\n target,\n currentIndex: 0,\n lastKeyTime: 0,\n triggerCount: 0,\n }\n\n this.#registrations.set(id, registration)\n this.registrations.setState((prev) =>\n new Map(prev).set(id, toRegistrationView(registration)),\n )\n\n // Track registration for this target\n if (!this.#targetRegistrations.has(target)) {\n this.#targetRegistrations.set(target, new Set())\n }\n this.#targetRegistrations.get(target)!.add(id)\n\n // Ensure listeners are attached for this target\n this.#ensureListenersForTarget(target)\n\n const manager = this\n const handle: SequenceRegistrationHandle = {\n get id() {\n return id\n },\n get isActive() {\n return manager.#registrations.has(id)\n },\n get callback() {\n const reg = manager.#registrations.get(id)\n return reg?.callback ?? callback\n },\n set callback(newCallback: HotkeyCallback) {\n const reg = manager.#registrations.get(id)\n if (reg) {\n reg.callback = newCallback\n }\n },\n setOptions: (newOptions: Partial<SequenceOptions>) => {\n const reg = manager.#registrations.get(id)\n if (reg) {\n reg.options = { ...reg.options, ...newOptions }\n manager.registrations.setState((prev) =>\n new Map(prev).set(id, toRegistrationView(reg)),\n )\n }\n },\n unregister: () => {\n manager.#unregister(id)\n },\n }\n\n return handle\n }\n\n /**\n * Unregisters a sequence by its registration ID.\n */\n #unregister(id: string): void {\n const registration = this.#registrations.get(id)\n if (!registration) {\n return\n }\n\n const target = registration.target\n\n this.#registrations.delete(id)\n this.registrations.setState((prev) => {\n const next = new Map(prev)\n next.delete(id)\n return next\n })\n\n // Remove from target registrations tracking\n const targetRegs = this.#targetRegistrations.get(target)\n if (targetRegs) {\n targetRegs.delete(id)\n if (targetRegs.size === 0) {\n this.#removeListenersForTarget(target)\n }\n }\n }\n\n /**\n * Ensures event listeners are attached for a specific target.\n */\n #ensureListenersForTarget(target: Target): void {\n if (typeof document === 'undefined') {\n return // SSR safety\n }\n\n if (this.#targetListeners.has(target)) {\n return\n }\n\n const keydownHandler = this.#createTargetKeyDownHandler(target)\n const keyupHandler = this.#createTargetKeyUpHandler(target)\n\n target.addEventListener('keydown', keydownHandler as EventListener)\n target.addEventListener('keyup', keyupHandler as EventListener)\n\n this.#targetListeners.set(target, {\n keydown: keydownHandler,\n keyup: keyupHandler,\n })\n }\n\n /**\n * Removes event listeners for a specific target.\n */\n #removeListenersForTarget(target: Target): void {\n if (typeof document === 'undefined') {\n return\n }\n\n const listeners = this.#targetListeners.get(target)\n if (!listeners) {\n return\n }\n\n target.removeEventListener('keydown', listeners.keydown as EventListener)\n target.removeEventListener('keyup', listeners.keyup as EventListener)\n\n this.#targetListeners.delete(target)\n this.#targetRegistrations.delete(target)\n }\n\n /**\n * Creates a keydown handler for a specific target.\n */\n #createTargetKeyDownHandler(target: Target): (event: KeyboardEvent) => void {\n return (event: KeyboardEvent) => {\n this.#processTargetEvent(event, target, 'keydown')\n }\n }\n\n /**\n * Creates a keyup handler for a specific target.\n */\n #createTargetKeyUpHandler(target: Target): (event: KeyboardEvent) => void {\n return (event: KeyboardEvent) => {\n this.#processTargetEvent(event, target, 'keyup')\n }\n }\n\n /**\n * Processes keyboard events for a specific target and event type.\n */\n #processTargetEvent(\n event: KeyboardEvent,\n target: Target,\n eventType: 'keydown' | 'keyup',\n ): void {\n const targetRegs = this.#targetRegistrations.get(target)\n if (!targetRegs) {\n return\n }\n\n const now = Date.now()\n\n for (const id of targetRegs) {\n const registration = this.#registrations.get(id)\n if (!registration) {\n continue\n }\n\n if (!isEventForTarget(event, target)) {\n continue\n }\n\n if (!registration.options.enabled) {\n continue\n }\n\n // Check if we should ignore input elements (defaults to true)\n if (registration.options.ignoreInputs !== false) {\n if (isInputElement(event.target)) {\n // Don't ignore if the sequence is explicitly scoped to this input element\n if (event.target !== registration.target) {\n continue\n }\n }\n }\n\n // Only process registrations that listen for this event type\n if (registration.options.eventType !== eventType) {\n continue\n }\n\n const timeout = registration.options.timeout ?? DEFAULT_SEQUENCE_TIMEOUT\n\n // Check if sequence has timed out\n if (\n registration.currentIndex > 0 &&\n now - registration.lastKeyTime > timeout\n ) {\n registration.currentIndex = 0\n }\n\n const expectedHotkey =\n registration.parsedSequence[registration.currentIndex]\n if (!expectedHotkey) {\n continue\n }\n\n if (\n matchesKeyboardEvent(\n event,\n expectedHotkey,\n registration.options.platform,\n )\n ) {\n registration.lastKeyTime = now\n registration.currentIndex++\n\n if (registration.currentIndex >= registration.parsedSequence.length) {\n if (registration.options.preventDefault) {\n event.preventDefault()\n }\n if (registration.options.stopPropagation) {\n event.stopPropagation()\n }\n\n const context: HotkeyCallbackContext = {\n hotkey: registration.sequence.join(' ') as Hotkey,\n parsedHotkey:\n registration.parsedSequence[\n registration.parsedSequence.length - 1\n ]!,\n }\n\n registration.callback(event, context)\n\n registration.currentIndex = 0\n }\n } else if (registration.currentIndex > 0) {\n const firstHotkey = registration.parsedSequence[0]!\n if (\n matchesKeyboardEvent(\n event,\n firstHotkey,\n registration.options.platform,\n )\n ) {\n registration.currentIndex = 1\n registration.lastKeyTime = now\n } else {\n registration.currentIndex = 0\n }\n }\n }\n }\n\n /**\n * Finds an existing registration with the same sequence and target.\n */\n #findConflictingSequence(\n sequence: HotkeySequence,\n target: Target,\n ): SequenceRegistration | null {\n const key = sequenceKey(sequence)\n for (const registration of this.#registrations.values()) {\n if (\n sequenceKey(registration.sequence) === key &&\n registration.target === target\n ) {\n return registration\n }\n }\n return null\n }\n\n /**\n * Resets all sequence progress.\n */\n resetAll(): void {\n for (const registration of this.#registrations.values()) {\n registration.currentIndex = 0\n registration.lastKeyTime = 0\n }\n }\n\n /**\n * Triggers a sequence's callback programmatically from devtools.\n * Creates a synthetic KeyboardEvent from the last key in the sequence.\n *\n * @param id - The registration ID to trigger\n * @returns True if the registration was found and triggered\n */\n triggerSequence(id: string): boolean {\n const registration = this.#registrations.get(id)\n if (!registration) {\n return false\n }\n\n const lastParsed =\n registration.parsedSequence[registration.parsedSequence.length - 1]\n if (!lastParsed) {\n return false\n }\n\n const syntheticEvent = new KeyboardEvent(\n registration.options.eventType ?? 'keydown',\n {\n key: lastParsed.key,\n ctrlKey: lastParsed.ctrl,\n shiftKey: lastParsed.shift,\n altKey: lastParsed.alt,\n metaKey: lastParsed.meta,\n bubbles: true,\n cancelable: true,\n },\n )\n\n registration.triggerCount++\n\n this.registrations.setState((prev) =>\n new Map(prev).set(id, toRegistrationView(registration)),\n )\n\n const context: HotkeyCallbackContext = {\n hotkey: registration.sequence.join(' ') as Hotkey,\n parsedHotkey: lastParsed,\n }\n\n registration.callback(syntheticEvent, context)\n\n return true\n }\n\n /**\n * Gets the number of registered sequences.\n */\n getRegistrationCount(): number {\n return this.#registrations.size\n }\n\n /**\n * Destroys the manager and removes all listeners.\n */\n destroy(): void {\n for (const target of this.#targetListeners.keys()) {\n this.#removeListenersForTarget(target)\n }\n this.#registrations.clear()\n this.registrations.setState(() => new Map())\n }\n}\n\n/**\n * Gets the singleton SequenceManager instance.\n * Convenience function for accessing the manager.\n */\nexport function getSequenceManager(): SequenceManager {\n return SequenceManager.getInstance()\n}\n\n/**\n * Creates a simple sequence matcher for one-off use.\n *\n * This is a low-level helper that does not support ignoreInputs, target,\n * or other HotkeyOptions. Callers must handle input filtering themselves\n * if attaching to document.\n *\n * @param sequence - The sequence of hotkeys to match\n * @param options - Options including timeout\n * @returns An object with match() and reset() methods\n *\n * @example\n * ```ts\n * const matcher = createSequenceMatcher(['G', 'G'], { timeout: 500 })\n *\n * document.addEventListener('keydown', (event) => {\n * if (matcher.match(event)) {\n * console.log('Sequence matched!')\n * }\n * })\n * ```\n */\nexport function createSequenceMatcher(\n sequence: HotkeySequence,\n options: { timeout?: number; platform?: 'mac' | 'windows' | 'linux' } = {},\n): {\n match: (event: KeyboardEvent) => boolean\n reset: () => void\n getProgress: () => number\n} {\n const platform = options.platform ?? detectPlatform()\n const timeout = options.timeout ?? DEFAULT_SEQUENCE_TIMEOUT\n const parsedSequence = sequence.map((hotkey) => parseHotkey(hotkey, platform))\n\n let currentIndex = 0\n let lastKeyTime = 0\n\n return {\n match(event: KeyboardEvent): boolean {\n const now = Date.now()\n\n if (currentIndex > 0 && now - lastKeyTime > timeout) {\n currentIndex = 0\n }\n\n const expected = parsedSequence[currentIndex]\n if (!expected) {\n return false\n }\n\n if (matchesKeyboardEvent(event, expected, platform)) {\n lastKeyTime = now\n currentIndex++\n\n if (currentIndex >= parsedSequence.length) {\n currentIndex = 0\n return true\n }\n } else if (currentIndex > 0) {\n if (matchesKeyboardEvent(event, parsedSequence[0]!, platform)) {\n currentIndex = 1\n lastKeyTime = now\n } else {\n currentIndex = 0\n }\n }\n\n return false\n },\n\n reset(): void {\n currentIndex = 0\n lastKeyTime = 0\n },\n\n getProgress(): number {\n return currentIndex\n },\n }\n}\n"],"mappings":";;;;;;;;;;;AA8CA,MAAM,2BAA2B;AAEjC,IAAI,oBAAoB;;;;AAKxB,SAAS,qBAA6B;AACpC,QAAO,YAAY,EAAE;;;;;AAMvB,SAAS,YAAY,UAAkC;AACrD,QAAO,SAAS,KAAK,IAAI;;;;;;;;;;;;;;;;;;;;;;;;;AA0E3B,SAAS,mBACP,KAC0B;AAC1B,QAAO;EACL,IAAI,IAAI;EACR,UAAU,IAAI;EACd,SAAS,IAAI;EACb,QAAQ,IAAI;EACZ,cAAc,IAAI;EACnB;;AAGH,IAAa,kBAAb,MAAa,gBAAgB;CAC3B,QAAOA,WAAoC;CAS3C,iCAAoD,IAAI,KAAK;CAC7D,mCAMI,IAAI,KAAK;CACb,uCAAiD,IAAI,KAAK;CAC1D;CAEA,AAAQ,cAAc;uBAbpB,IAAIC,sCAAM,IAAI,KAAK,CAAC;AAcpB,QAAKC,WAAYC,kCAAgB;;;;;CAMnC,OAAO,cAA+B;AACpC,MAAI,CAAC,iBAAgBH,SACnB,kBAAgBA,WAAY,IAAI,iBAAiB;AAEnD,SAAO,iBAAgBA;;;;;CAMzB,OAAO,gBAAsB;AAC3B,MAAI,iBAAgBA,UAAW;AAC7B,oBAAgBA,SAAU,SAAS;AACnC,oBAAgBA,WAAY;;;;;;;;;;;CAYhC,SACE,UACA,UACA,UAA2B,EAAE,EACD;AAC5B,MAAI,SAAS,WAAW,EACtB,OAAM,IAAI,MAAM,4CAA4C;EAG9D,MAAM,KAAK,oBAAoB;EAC/B,MAAM,WAAW,QAAQ,YAAY,MAAKE;EAC1C,MAAM,iBAAiB,SAAS,KAAK,WACnCE,0BAAY,QAAQ,SAAS,CAC9B;EAGD,MAAM,SACJ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,YAAYP,kCAAgB;CACrD,MAAM,UAAU,QAAQ,WAAW;CACnC,MAAM,iBAAiB,SAAS,KAAK,WAAWC,0BAAY,QAAQ,SAAS,CAAC;CAE9E,IAAI,eAAe;CACnB,IAAI,cAAc;AAElB,QAAO;EACL,MAAM,OAA+B;GACnC,MAAM,MAAM,KAAK,KAAK;AAEtB,OAAI,eAAe,KAAK,MAAM,cAAc,QAC1C,gBAAe;GAGjB,MAAM,WAAW,eAAe;AAChC,OAAI,CAAC,SACH,QAAO;AAGT,OAAIgB,mCAAqB,OAAO,UAAU,SAAS,EAAE;AACnD,kBAAc;AACd;AAEA,QAAI,gBAAgB,eAAe,QAAQ;AACzC,oBAAe;AACf,YAAO;;cAEA,eAAe,EACxB,KAAIA,mCAAqB,OAAO,eAAe,IAAK,SAAS,EAAE;AAC7D,mBAAe;AACf,kBAAc;SAEd,gBAAe;AAInB,UAAO;;EAGT,QAAc;AACZ,kBAAe;AACf,iBAAc;;EAGhB,cAAsB;AACpB,UAAO;;EAEV"}
1
+ {"version":3,"file":"sequence-manager.cjs","names":["#instance","Store","#platform","detectPlatform","parseHotkey","#findConflictingSequence","formatHotkeySequence","#unregister","getDefaultIgnoreInputs","defaultHotkeyOptions","#registrations","#targetRegistrations","#ensureListenersForTarget","#removeListenersForTarget","#targetListeners","#createTargetKeyDownHandler","#createTargetKeyUpHandler","#processTargetEvent","isModifierKey","isEventForTarget","isInputElement","matchesKeyboardEvent"],"sources":["../src/sequence-manager.ts"],"sourcesContent":["import { Store } from '@tanstack/store'\nimport { formatHotkeySequence } from './format'\nimport { detectPlatform } from './constants'\nimport { isModifierKey, parseHotkey } from './parse'\nimport { matchesKeyboardEvent } from './match'\nimport {\n defaultHotkeyOptions,\n getDefaultIgnoreInputs,\n handleConflict,\n isEventForTarget,\n isInputElement,\n} from './manager.utils'\nimport type { HotkeyOptions } from './hotkey-manager'\nimport type {\n Hotkey,\n HotkeyCallback,\n HotkeyCallbackContext,\n ParsedHotkey,\n} from './hotkey'\n\ntype Target = HTMLElement | Document | Window\n\n/**\n * Options for hotkey sequence matching.\n * Extends HotkeyOptions but excludes requireReset (not applicable to sequences).\n */\nexport interface SequenceOptions extends Omit<HotkeyOptions, 'requireReset'> {\n /** Timeout between keys in milliseconds. Default: 1000 */\n timeout?: number\n}\n\n/**\n * A sequence of hotkeys for Vim-style shortcuts.\n *\n * Each element is one step (a `Hotkey` string). Steps may include modifiers;\n * the same modifier can appear on consecutive steps (e.g. `Shift+R` then\n * `Shift+T`). Modifier-only key events do not advance or reset matching—see\n * `SequenceManager`.\n *\n * @example\n * ```ts\n * const gotoTop: HotkeySequence = ['G', 'G'] // gg\n * const deleteLine: HotkeySequence = ['D', 'D'] // dd\n * const deleteWord: HotkeySequence = ['D', 'I', 'W'] // diw\n * const chainedShift: HotkeySequence = ['Shift+R', 'Shift+T']\n * ```\n */\nexport type HotkeySequence = Array<Hotkey>\n\n/**\n * Default timeout between keys in a sequence (in milliseconds).\n */\nconst DEFAULT_SEQUENCE_TIMEOUT = 1000\n\nlet sequenceIdCounter = 0\n\n/**\n * Generates a unique ID for sequence registrations.\n */\nfunction generateSequenceId(): string {\n return `sequence_${++sequenceIdCounter}`\n}\n\n/**\n * Returns a canonical string for sequence conflict comparison.\n */\nfunction sequenceKey(sequence: HotkeySequence): string {\n return sequence.join('|')\n}\n\n/**\n * View of a sequence registration for devtools display.\n * Excludes internal matching state (currentIndex, lastKeyTime).\n */\nexport interface SequenceRegistrationView {\n id: string\n sequence: HotkeySequence\n options: SequenceOptions\n target: Target\n triggerCount: number\n}\n\n/**\n * Internal representation of a sequence registration.\n */\ninterface SequenceRegistration {\n id: string\n sequence: HotkeySequence\n parsedSequence: Array<ParsedHotkey>\n callback: HotkeyCallback\n options: SequenceOptions\n target: Target\n currentIndex: number\n lastKeyTime: number\n triggerCount: number\n}\n\n/**\n * A handle returned from SequenceManager.register() that allows updating\n * the callback and options without re-registering the sequence.\n *\n * @example\n * ```ts\n * const handle = manager.register(['G', 'G'], callback, options)\n *\n * handle.callback = newCallback\n * handle.setOptions({ timeout: 500 })\n * handle.unregister()\n * ```\n */\nexport interface SequenceRegistrationHandle {\n readonly id: string\n readonly isActive: boolean\n callback: HotkeyCallback\n setOptions: (options: Partial<SequenceOptions>) => void\n unregister: () => void\n}\n\n/**\n * Manages keyboard sequence matching for Vim-style shortcuts.\n *\n * This class allows registering multi-key sequences like 'g g' or 'd d'\n * that trigger callbacks when the full sequence is pressed within\n * a configurable timeout.\n *\n * Modifier-only `keydown` / `keyup` events (Shift, Control, Alt, or Meta\n * alone) are not processed: they neither match a step nor reset progress.\n * That supports chained modifier chords (e.g. `Shift+R` then `Shift+T`) when\n * the user presses a modifier alone between steps.\n *\n * @example\n * ```ts\n * const matcher = SequenceManager.getInstance()\n *\n * // Register 'g g' to go to top\n * const unregister = matcher.register(['G', 'G'], (event, context) => {\n * scrollToTop()\n * }, { timeout: 500 })\n *\n * // Later, to unregister:\n * unregister()\n * ```\n */\n/**\n * Builds a devtools view from an internal registration.\n */\nfunction toRegistrationView(\n reg: SequenceRegistration,\n): SequenceRegistrationView {\n return {\n id: reg.id,\n sequence: reg.sequence,\n options: reg.options,\n target: reg.target,\n triggerCount: reg.triggerCount,\n }\n}\n\nexport class SequenceManager {\n static #instance: SequenceManager | null = null\n\n /**\n * The TanStack Store containing sequence registration views for devtools.\n * Subscribe to this to observe registration changes.\n */\n readonly registrations: Store<Map<string, SequenceRegistrationView>> =\n new Store(new Map())\n\n #registrations: Map<string, SequenceRegistration> = new Map()\n #targetListeners: Map<\n Target,\n {\n keydown: (event: KeyboardEvent) => void\n keyup: (event: KeyboardEvent) => void\n }\n > = new Map()\n #targetRegistrations: Map<Target, Set<string>> = new Map()\n #platform: 'mac' | 'windows' | 'linux'\n\n private constructor() {\n this.#platform = detectPlatform()\n }\n\n /**\n * Gets the singleton instance of SequenceManager.\n */\n static getInstance(): SequenceManager {\n if (!SequenceManager.#instance) {\n SequenceManager.#instance = new SequenceManager()\n }\n return SequenceManager.#instance\n }\n\n /**\n * Resets the singleton instance. Useful for testing.\n */\n static resetInstance(): void {\n if (SequenceManager.#instance) {\n SequenceManager.#instance.destroy()\n SequenceManager.#instance = null\n }\n }\n\n /**\n * Registers a hotkey sequence handler.\n *\n * @param sequence - Array of hotkey strings that form the sequence\n * @param callback - Function to call when the sequence is completed\n * @param options - Options for the sequence behavior\n * @returns A handle to update or unregister the sequence\n */\n register(\n sequence: HotkeySequence,\n callback: HotkeyCallback,\n options: SequenceOptions = {},\n ): SequenceRegistrationHandle {\n if (sequence.length === 0) {\n throw new Error('Sequence must contain at least one hotkey')\n }\n\n const id = generateSequenceId()\n const platform = options.platform ?? this.#platform\n const parsedSequence = sequence.map((hotkey) =>\n parseHotkey(hotkey, platform),\n )\n\n // Resolve target: default to document if not provided or null\n const target: Target =\n options.target ??\n (typeof document !== 'undefined' ? document : ({} as Document))\n\n // Resolve conflict behavior\n const conflictBehavior = options.conflictBehavior ?? 'warn'\n\n // Check for existing registrations with the same sequence and target\n const conflictingRegistration = this.#findConflictingSequence(\n sequence,\n target,\n )\n\n if (conflictingRegistration) {\n handleConflict(\n conflictingRegistration.id,\n formatHotkeySequence(sequence),\n conflictBehavior,\n (regId) => this.#unregister(regId),\n )\n }\n\n const firstStep = parsedSequence[0]!\n const resolvedIgnoreInputs =\n options.ignoreInputs ?? getDefaultIgnoreInputs(firstStep)\n\n const baseOptions = {\n ...defaultHotkeyOptions,\n timeout: DEFAULT_SEQUENCE_TIMEOUT,\n ...options,\n platform,\n ignoreInputs: resolvedIgnoreInputs,\n }\n\n const registration: SequenceRegistration = {\n id,\n sequence,\n parsedSequence,\n callback,\n options: baseOptions,\n target,\n currentIndex: 0,\n lastKeyTime: 0,\n triggerCount: 0,\n }\n\n this.#registrations.set(id, registration)\n this.registrations.setState((prev) =>\n new Map(prev).set(id, toRegistrationView(registration)),\n )\n\n // Track registration for this target\n if (!this.#targetRegistrations.has(target)) {\n this.#targetRegistrations.set(target, new Set())\n }\n this.#targetRegistrations.get(target)!.add(id)\n\n // Ensure listeners are attached for this target\n this.#ensureListenersForTarget(target)\n\n const manager = this\n const handle: SequenceRegistrationHandle = {\n get id() {\n return id\n },\n get isActive() {\n return manager.#registrations.has(id)\n },\n get callback() {\n const reg = manager.#registrations.get(id)\n return reg?.callback ?? callback\n },\n set callback(newCallback: HotkeyCallback) {\n const reg = manager.#registrations.get(id)\n if (reg) {\n reg.callback = newCallback\n }\n },\n setOptions: (newOptions: Partial<SequenceOptions>) => {\n const reg = manager.#registrations.get(id)\n if (reg) {\n reg.options = { ...reg.options, ...newOptions }\n manager.registrations.setState((prev) =>\n new Map(prev).set(id, toRegistrationView(reg)),\n )\n }\n },\n unregister: () => {\n manager.#unregister(id)\n },\n }\n\n return handle\n }\n\n /**\n * Unregisters a sequence by its registration ID.\n */\n #unregister(id: string): void {\n const registration = this.#registrations.get(id)\n if (!registration) {\n return\n }\n\n const target = registration.target\n\n this.#registrations.delete(id)\n this.registrations.setState((prev) => {\n const next = new Map(prev)\n next.delete(id)\n return next\n })\n\n // Remove from target registrations tracking\n const targetRegs = this.#targetRegistrations.get(target)\n if (targetRegs) {\n targetRegs.delete(id)\n if (targetRegs.size === 0) {\n this.#removeListenersForTarget(target)\n }\n }\n }\n\n /**\n * Ensures event listeners are attached for a specific target.\n */\n #ensureListenersForTarget(target: Target): void {\n if (typeof document === 'undefined') {\n return // SSR safety\n }\n\n if (this.#targetListeners.has(target)) {\n return\n }\n\n const keydownHandler = this.#createTargetKeyDownHandler(target)\n const keyupHandler = this.#createTargetKeyUpHandler(target)\n\n target.addEventListener('keydown', keydownHandler as EventListener)\n target.addEventListener('keyup', keyupHandler as EventListener)\n\n this.#targetListeners.set(target, {\n keydown: keydownHandler,\n keyup: keyupHandler,\n })\n }\n\n /**\n * Removes event listeners for a specific target.\n */\n #removeListenersForTarget(target: Target): void {\n if (typeof document === 'undefined') {\n return\n }\n\n const listeners = this.#targetListeners.get(target)\n if (!listeners) {\n return\n }\n\n target.removeEventListener('keydown', listeners.keydown as EventListener)\n target.removeEventListener('keyup', listeners.keyup as EventListener)\n\n this.#targetListeners.delete(target)\n this.#targetRegistrations.delete(target)\n }\n\n /**\n * Creates a keydown handler for a specific target.\n */\n #createTargetKeyDownHandler(target: Target): (event: KeyboardEvent) => void {\n return (event: KeyboardEvent) => {\n this.#processTargetEvent(event, target, 'keydown')\n }\n }\n\n /**\n * Creates a keyup handler for a specific target.\n */\n #createTargetKeyUpHandler(target: Target): (event: KeyboardEvent) => void {\n return (event: KeyboardEvent) => {\n this.#processTargetEvent(event, target, 'keyup')\n }\n }\n\n /**\n * Processes keyboard events for a specific target and event type.\n */\n #processTargetEvent(\n event: KeyboardEvent,\n target: Target,\n eventType: 'keydown' | 'keyup',\n ): void {\n // Skip modifier-only events so pressing e.g. Shift before Shift+C does not reset the sequence.\n if (isModifierKey(event)) {\n return\n }\n\n const targetRegs = this.#targetRegistrations.get(target)\n if (!targetRegs) {\n return\n }\n\n const now = Date.now()\n\n for (const id of targetRegs) {\n const registration = this.#registrations.get(id)\n if (!registration) {\n continue\n }\n\n if (!isEventForTarget(event, target)) {\n continue\n }\n\n if (!registration.options.enabled) {\n continue\n }\n\n // Check if we should ignore input elements (defaults to true)\n if (registration.options.ignoreInputs !== false) {\n if (isInputElement(event.target)) {\n // Don't ignore if the sequence is explicitly scoped to this input element\n if (event.target !== registration.target) {\n continue\n }\n }\n }\n\n // Only process registrations that listen for this event type\n if (registration.options.eventType !== eventType) {\n continue\n }\n\n const timeout = registration.options.timeout ?? DEFAULT_SEQUENCE_TIMEOUT\n\n // Check if sequence has timed out\n if (\n registration.currentIndex > 0 &&\n now - registration.lastKeyTime > timeout\n ) {\n registration.currentIndex = 0\n }\n\n const expectedHotkey =\n registration.parsedSequence[registration.currentIndex]\n if (!expectedHotkey) {\n continue\n }\n\n if (\n matchesKeyboardEvent(\n event,\n expectedHotkey,\n registration.options.platform,\n )\n ) {\n registration.lastKeyTime = now\n registration.currentIndex++\n\n if (registration.currentIndex >= registration.parsedSequence.length) {\n if (registration.options.preventDefault) {\n event.preventDefault()\n }\n if (registration.options.stopPropagation) {\n event.stopPropagation()\n }\n\n const context: HotkeyCallbackContext = {\n hotkey: registration.sequence.join(' ') as Hotkey,\n parsedHotkey:\n registration.parsedSequence[\n registration.parsedSequence.length - 1\n ]!,\n }\n\n registration.callback(event, context)\n\n registration.currentIndex = 0\n }\n } else if (registration.currentIndex > 0) {\n const firstHotkey = registration.parsedSequence[0]!\n if (\n matchesKeyboardEvent(\n event,\n firstHotkey,\n registration.options.platform,\n )\n ) {\n registration.currentIndex = 1\n registration.lastKeyTime = now\n } else {\n registration.currentIndex = 0\n }\n }\n }\n }\n\n /**\n * Finds an existing registration with the same sequence and target.\n */\n #findConflictingSequence(\n sequence: HotkeySequence,\n target: Target,\n ): SequenceRegistration | null {\n const key = sequenceKey(sequence)\n for (const registration of this.#registrations.values()) {\n if (\n sequenceKey(registration.sequence) === key &&\n registration.target === target\n ) {\n return registration\n }\n }\n return null\n }\n\n /**\n * Resets all sequence progress.\n */\n resetAll(): void {\n for (const registration of this.#registrations.values()) {\n registration.currentIndex = 0\n registration.lastKeyTime = 0\n }\n }\n\n /**\n * Triggers a sequence's callback programmatically from devtools.\n * Creates a synthetic KeyboardEvent from the last key in the sequence.\n *\n * @param id - The registration ID to trigger\n * @returns True if the registration was found and triggered\n */\n triggerSequence(id: string): boolean {\n const registration = this.#registrations.get(id)\n if (!registration) {\n return false\n }\n\n const lastParsed =\n registration.parsedSequence[registration.parsedSequence.length - 1]\n if (!lastParsed) {\n return false\n }\n\n const syntheticEvent = new KeyboardEvent(\n registration.options.eventType ?? 'keydown',\n {\n key: lastParsed.key,\n ctrlKey: lastParsed.ctrl,\n shiftKey: lastParsed.shift,\n altKey: lastParsed.alt,\n metaKey: lastParsed.meta,\n bubbles: true,\n cancelable: true,\n },\n )\n\n registration.triggerCount++\n\n this.registrations.setState((prev) =>\n new Map(prev).set(id, toRegistrationView(registration)),\n )\n\n const context: HotkeyCallbackContext = {\n hotkey: registration.sequence.join(' ') as Hotkey,\n parsedHotkey: lastParsed,\n }\n\n registration.callback(syntheticEvent, context)\n\n return true\n }\n\n /**\n * Gets the number of registered sequences.\n */\n getRegistrationCount(): number {\n return this.#registrations.size\n }\n\n /**\n * Destroys the manager and removes all listeners.\n */\n destroy(): void {\n for (const target of this.#targetListeners.keys()) {\n this.#removeListenersForTarget(target)\n }\n this.#registrations.clear()\n this.registrations.setState(() => new Map())\n }\n}\n\n/**\n * Gets the singleton SequenceManager instance.\n * Convenience function for accessing the manager.\n */\nexport function getSequenceManager(): SequenceManager {\n return SequenceManager.getInstance()\n}\n\n/**\n * Creates a simple sequence matcher for one-off use.\n *\n * This is a low-level helper that does not support ignoreInputs, target,\n * or other HotkeyOptions. Callers must handle input filtering themselves\n * if attaching to document.\n *\n * @param sequence - The sequence of hotkeys to match\n * @param options - Options including timeout\n * @returns An object with match() and reset() methods\n *\n * @example\n * ```ts\n * const matcher = createSequenceMatcher(['G', 'G'], { timeout: 500 })\n *\n * document.addEventListener('keydown', (event) => {\n * if (matcher.match(event)) {\n * console.log('Sequence matched!')\n * }\n * })\n * ```\n */\nexport function createSequenceMatcher(\n sequence: HotkeySequence,\n options: { timeout?: number; platform?: 'mac' | 'windows' | 'linux' } = {},\n): {\n match: (event: KeyboardEvent) => boolean\n reset: () => void\n getProgress: () => number\n} {\n const platform = options.platform ?? detectPlatform()\n const timeout = options.timeout ?? DEFAULT_SEQUENCE_TIMEOUT\n const parsedSequence = sequence.map((hotkey) => parseHotkey(hotkey, platform))\n\n let currentIndex = 0\n let lastKeyTime = 0\n\n return {\n match(event: KeyboardEvent): boolean {\n const now = Date.now()\n\n if (currentIndex > 0 && now - lastKeyTime > timeout) {\n currentIndex = 0\n }\n\n const expected = parsedSequence[currentIndex]\n if (!expected) {\n return false\n }\n\n if (matchesKeyboardEvent(event, expected, platform)) {\n lastKeyTime = now\n currentIndex++\n\n if (currentIndex >= parsedSequence.length) {\n currentIndex = 0\n return true\n }\n } else if (currentIndex > 0) {\n if (matchesKeyboardEvent(event, parsedSequence[0]!, platform)) {\n currentIndex = 1\n lastKeyTime = now\n } else {\n currentIndex = 0\n }\n }\n\n return false\n },\n\n reset(): void {\n currentIndex = 0\n lastKeyTime = 0\n },\n\n getProgress(): number {\n return currentIndex\n },\n }\n}\n"],"mappings":";;;;;;;;;;;AAoDA,MAAM,2BAA2B;AAEjC,IAAI,oBAAoB;;;;AAKxB,SAAS,qBAA6B;AACpC,QAAO,YAAY,EAAE;;;;;AAMvB,SAAS,YAAY,UAAkC;AACrD,QAAO,SAAS,KAAK,IAAI;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+E3B,SAAS,mBACP,KAC0B;AAC1B,QAAO;EACL,IAAI,IAAI;EACR,UAAU,IAAI;EACd,SAAS,IAAI;EACb,QAAQ,IAAI;EACZ,cAAc,IAAI;EACnB;;AAGH,IAAa,kBAAb,MAAa,gBAAgB;CAC3B,QAAOA,WAAoC;CAS3C,iCAAoD,IAAI,KAAK;CAC7D,mCAMI,IAAI,KAAK;CACb,uCAAiD,IAAI,KAAK;CAC1D;CAEA,AAAQ,cAAc;uBAbpB,IAAIC,sCAAM,IAAI,KAAK,CAAC;AAcpB,QAAKC,WAAYC,kCAAgB;;;;;CAMnC,OAAO,cAA+B;AACpC,MAAI,CAAC,iBAAgBH,SACnB,kBAAgBA,WAAY,IAAI,iBAAiB;AAEnD,SAAO,iBAAgBA;;;;;CAMzB,OAAO,gBAAsB;AAC3B,MAAI,iBAAgBA,UAAW;AAC7B,oBAAgBA,SAAU,SAAS;AACnC,oBAAgBA,WAAY;;;;;;;;;;;CAYhC,SACE,UACA,UACA,UAA2B,EAAE,EACD;AAC5B,MAAI,SAAS,WAAW,EACtB,OAAM,IAAI,MAAM,4CAA4C;EAG9D,MAAM,KAAK,oBAAoB;EAC/B,MAAM,WAAW,QAAQ,YAAY,MAAKE;EAC1C,MAAM,iBAAiB,SAAS,KAAK,WACnCE,0BAAY,QAAQ,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,SAAgB,sBACd,UACA,UAAwE,EAAE,EAK1E;CACA,MAAM,WAAW,QAAQ,YAAYP,kCAAgB;CACrD,MAAM,UAAU,QAAQ,WAAW;CACnC,MAAM,iBAAiB,SAAS,KAAK,WAAWC,0BAAY,QAAQ,SAAS,CAAC;CAE9E,IAAI,eAAe;CACnB,IAAI,cAAc;AAElB,QAAO;EACL,MAAM,OAA+B;GACnC,MAAM,MAAM,KAAK,KAAK;AAEtB,OAAI,eAAe,KAAK,MAAM,cAAc,QAC1C,gBAAe;GAGjB,MAAM,WAAW,eAAe;AAChC,OAAI,CAAC,SACH,QAAO;AAGT,OAAIiB,mCAAqB,OAAO,UAAU,SAAS,EAAE;AACnD,kBAAc;AACd;AAEA,QAAI,gBAAgB,eAAe,QAAQ;AACzC,oBAAe;AACf,YAAO;;cAEA,eAAe,EACxB,KAAIA,mCAAqB,OAAO,eAAe,IAAK,SAAS,EAAE;AAC7D,mBAAe;AACf,kBAAc;SAEd,gBAAe;AAInB,UAAO;;EAGT,QAAc;AACZ,kBAAe;AACf,iBAAc;;EAGhB,cAAsB;AACpB,UAAO;;EAEV"}
@@ -15,11 +15,17 @@ interface SequenceOptions extends Omit<HotkeyOptions, 'requireReset'> {
15
15
  /**
16
16
  * A sequence of hotkeys for Vim-style shortcuts.
17
17
  *
18
+ * Each element is one step (a `Hotkey` string). Steps may include modifiers;
19
+ * the same modifier can appear on consecutive steps (e.g. `Shift+R` then
20
+ * `Shift+T`). Modifier-only key events do not advance or reset matching—see
21
+ * `SequenceManager`.
22
+ *
18
23
  * @example
19
24
  * ```ts
20
25
  * const gotoTop: HotkeySequence = ['G', 'G'] // gg
21
26
  * const deleteLine: HotkeySequence = ['D', 'D'] // dd
22
27
  * const deleteWord: HotkeySequence = ['D', 'I', 'W'] // diw
28
+ * const chainedShift: HotkeySequence = ['Shift+R', 'Shift+T']
23
29
  * ```
24
30
  */
25
31
  type HotkeySequence = Array<Hotkey>;
@@ -15,11 +15,17 @@ interface SequenceOptions extends Omit<HotkeyOptions, 'requireReset'> {
15
15
  /**
16
16
  * A sequence of hotkeys for Vim-style shortcuts.
17
17
  *
18
+ * Each element is one step (a `Hotkey` string). Steps may include modifiers;
19
+ * the same modifier can appear on consecutive steps (e.g. `Shift+R` then
20
+ * `Shift+T`). Modifier-only key events do not advance or reset matching—see
21
+ * `SequenceManager`.
22
+ *
18
23
  * @example
19
24
  * ```ts
20
25
  * const gotoTop: HotkeySequence = ['G', 'G'] // gg
21
26
  * const deleteLine: HotkeySequence = ['D', 'D'] // dd
22
27
  * const deleteWord: HotkeySequence = ['D', 'I', 'W'] // diw
28
+ * const chainedShift: HotkeySequence = ['Shift+R', 'Shift+T']
23
29
  * ```
24
30
  */
25
31
  type HotkeySequence = Array<Hotkey>;
@@ -1,5 +1,5 @@
1
1
  import { detectPlatform } from "./constants.js";
2
- import { parseHotkey } from "./parse.js";
2
+ import { isModifierKey, parseHotkey } from "./parse.js";
3
3
  import { formatHotkeySequence } from "./format.js";
4
4
  import { matchesKeyboardEvent } from "./match.js";
5
5
  import { defaultHotkeyOptions, getDefaultIgnoreInputs, handleConflict, isEventForTarget, isInputElement } from "./manager.utils.js";
@@ -30,6 +30,11 @@ function sequenceKey(sequence) {
30
30
  * that trigger callbacks when the full sequence is pressed within
31
31
  * a configurable timeout.
32
32
  *
33
+ * Modifier-only `keydown` / `keyup` events (Shift, Control, Alt, or Meta
34
+ * alone) are not processed: they neither match a step nor reset progress.
35
+ * That supports chained modifier chords (e.g. `Shift+R` then `Shift+T`) when
36
+ * the user presses a modifier alone between steps.
37
+ *
33
38
  * @example
34
39
  * ```ts
35
40
  * const matcher = SequenceManager.getInstance()
@@ -218,6 +223,7 @@ var SequenceManager = class SequenceManager {
218
223
  * Processes keyboard events for a specific target and event type.
219
224
  */
220
225
  #processTargetEvent(event, target, eventType) {
226
+ if (isModifierKey(event)) return;
221
227
  const targetRegs = this.#targetRegistrations.get(target);
222
228
  if (!targetRegs) return;
223
229
  const now = Date.now();
@@ -1 +1 @@
1
- {"version":3,"file":"sequence-manager.js","names":["#instance","#platform","#findConflictingSequence","#unregister","#registrations","#targetRegistrations","#ensureListenersForTarget","#removeListenersForTarget","#targetListeners","#createTargetKeyDownHandler","#createTargetKeyUpHandler","#processTargetEvent"],"sources":["../src/sequence-manager.ts"],"sourcesContent":["import { Store } from '@tanstack/store'\nimport { formatHotkeySequence } from './format'\nimport { detectPlatform } from './constants'\nimport { parseHotkey } from './parse'\nimport { matchesKeyboardEvent } from './match'\nimport {\n defaultHotkeyOptions,\n getDefaultIgnoreInputs,\n handleConflict,\n isEventForTarget,\n isInputElement,\n} from './manager.utils'\nimport type { HotkeyOptions } from './hotkey-manager'\nimport type {\n Hotkey,\n HotkeyCallback,\n HotkeyCallbackContext,\n ParsedHotkey,\n} from './hotkey'\n\ntype Target = HTMLElement | Document | Window\n\n/**\n * Options for hotkey sequence matching.\n * Extends HotkeyOptions but excludes requireReset (not applicable to sequences).\n */\nexport interface SequenceOptions extends Omit<HotkeyOptions, 'requireReset'> {\n /** Timeout between keys in milliseconds. Default: 1000 */\n timeout?: number\n}\n\n/**\n * A sequence of hotkeys for Vim-style shortcuts.\n *\n * @example\n * ```ts\n * const gotoTop: HotkeySequence = ['G', 'G'] // gg\n * const deleteLine: HotkeySequence = ['D', 'D'] // dd\n * const deleteWord: HotkeySequence = ['D', 'I', 'W'] // diw\n * ```\n */\nexport type HotkeySequence = Array<Hotkey>\n\n/**\n * Default timeout between keys in a sequence (in milliseconds).\n */\nconst DEFAULT_SEQUENCE_TIMEOUT = 1000\n\nlet sequenceIdCounter = 0\n\n/**\n * Generates a unique ID for sequence registrations.\n */\nfunction generateSequenceId(): string {\n return `sequence_${++sequenceIdCounter}`\n}\n\n/**\n * Returns a canonical string for sequence conflict comparison.\n */\nfunction sequenceKey(sequence: HotkeySequence): string {\n return sequence.join('|')\n}\n\n/**\n * View of a sequence registration for devtools display.\n * Excludes internal matching state (currentIndex, lastKeyTime).\n */\nexport interface SequenceRegistrationView {\n id: string\n sequence: HotkeySequence\n options: SequenceOptions\n target: Target\n triggerCount: number\n}\n\n/**\n * Internal representation of a sequence registration.\n */\ninterface SequenceRegistration {\n id: string\n sequence: HotkeySequence\n parsedSequence: Array<ParsedHotkey>\n callback: HotkeyCallback\n options: SequenceOptions\n target: Target\n currentIndex: number\n lastKeyTime: number\n triggerCount: number\n}\n\n/**\n * A handle returned from SequenceManager.register() that allows updating\n * the callback and options without re-registering the sequence.\n *\n * @example\n * ```ts\n * const handle = manager.register(['G', 'G'], callback, options)\n *\n * handle.callback = newCallback\n * handle.setOptions({ timeout: 500 })\n * handle.unregister()\n * ```\n */\nexport interface SequenceRegistrationHandle {\n readonly id: string\n readonly isActive: boolean\n callback: HotkeyCallback\n setOptions: (options: Partial<SequenceOptions>) => void\n unregister: () => void\n}\n\n/**\n * Manages keyboard sequence matching for Vim-style shortcuts.\n *\n * This class allows registering multi-key sequences like 'g g' or 'd d'\n * that trigger callbacks when the full sequence is pressed within\n * a configurable timeout.\n *\n * @example\n * ```ts\n * const matcher = SequenceManager.getInstance()\n *\n * // Register 'g g' to go to top\n * const unregister = matcher.register(['G', 'G'], (event, context) => {\n * scrollToTop()\n * }, { timeout: 500 })\n *\n * // Later, to unregister:\n * unregister()\n * ```\n */\n/**\n * Builds a devtools view from an internal registration.\n */\nfunction toRegistrationView(\n reg: SequenceRegistration,\n): SequenceRegistrationView {\n return {\n id: reg.id,\n sequence: reg.sequence,\n options: reg.options,\n target: reg.target,\n triggerCount: reg.triggerCount,\n }\n}\n\nexport class SequenceManager {\n static #instance: SequenceManager | null = null\n\n /**\n * The TanStack Store containing sequence registration views for devtools.\n * Subscribe to this to observe registration changes.\n */\n readonly registrations: Store<Map<string, SequenceRegistrationView>> =\n new Store(new Map())\n\n #registrations: Map<string, SequenceRegistration> = new Map()\n #targetListeners: Map<\n Target,\n {\n keydown: (event: KeyboardEvent) => void\n keyup: (event: KeyboardEvent) => void\n }\n > = new Map()\n #targetRegistrations: Map<Target, Set<string>> = new Map()\n #platform: 'mac' | 'windows' | 'linux'\n\n private constructor() {\n this.#platform = detectPlatform()\n }\n\n /**\n * Gets the singleton instance of SequenceManager.\n */\n static getInstance(): SequenceManager {\n if (!SequenceManager.#instance) {\n SequenceManager.#instance = new SequenceManager()\n }\n return SequenceManager.#instance\n }\n\n /**\n * Resets the singleton instance. Useful for testing.\n */\n static resetInstance(): void {\n if (SequenceManager.#instance) {\n SequenceManager.#instance.destroy()\n SequenceManager.#instance = null\n }\n }\n\n /**\n * Registers a hotkey sequence handler.\n *\n * @param sequence - Array of hotkey strings that form the sequence\n * @param callback - Function to call when the sequence is completed\n * @param options - Options for the sequence behavior\n * @returns A handle to update or unregister the sequence\n */\n register(\n sequence: HotkeySequence,\n callback: HotkeyCallback,\n options: SequenceOptions = {},\n ): SequenceRegistrationHandle {\n if (sequence.length === 0) {\n throw new Error('Sequence must contain at least one hotkey')\n }\n\n const id = generateSequenceId()\n const platform = options.platform ?? this.#platform\n const parsedSequence = sequence.map((hotkey) =>\n parseHotkey(hotkey, platform),\n )\n\n // Resolve target: default to document if not provided or null\n const target: Target =\n options.target ??\n (typeof document !== 'undefined' ? document : ({} as Document))\n\n // Resolve conflict behavior\n const conflictBehavior = options.conflictBehavior ?? 'warn'\n\n // Check for existing registrations with the same sequence and target\n const conflictingRegistration = this.#findConflictingSequence(\n sequence,\n target,\n )\n\n if (conflictingRegistration) {\n handleConflict(\n conflictingRegistration.id,\n formatHotkeySequence(sequence),\n conflictBehavior,\n (regId) => this.#unregister(regId),\n )\n }\n\n const firstStep = parsedSequence[0]!\n const resolvedIgnoreInputs =\n options.ignoreInputs ?? getDefaultIgnoreInputs(firstStep)\n\n const baseOptions = {\n ...defaultHotkeyOptions,\n timeout: DEFAULT_SEQUENCE_TIMEOUT,\n ...options,\n platform,\n ignoreInputs: resolvedIgnoreInputs,\n }\n\n const registration: SequenceRegistration = {\n id,\n sequence,\n parsedSequence,\n callback,\n options: baseOptions,\n target,\n currentIndex: 0,\n lastKeyTime: 0,\n triggerCount: 0,\n }\n\n this.#registrations.set(id, registration)\n this.registrations.setState((prev) =>\n new Map(prev).set(id, toRegistrationView(registration)),\n )\n\n // Track registration for this target\n if (!this.#targetRegistrations.has(target)) {\n this.#targetRegistrations.set(target, new Set())\n }\n this.#targetRegistrations.get(target)!.add(id)\n\n // Ensure listeners are attached for this target\n this.#ensureListenersForTarget(target)\n\n const manager = this\n const handle: SequenceRegistrationHandle = {\n get id() {\n return id\n },\n get isActive() {\n return manager.#registrations.has(id)\n },\n get callback() {\n const reg = manager.#registrations.get(id)\n return reg?.callback ?? callback\n },\n set callback(newCallback: HotkeyCallback) {\n const reg = manager.#registrations.get(id)\n if (reg) {\n reg.callback = newCallback\n }\n },\n setOptions: (newOptions: Partial<SequenceOptions>) => {\n const reg = manager.#registrations.get(id)\n if (reg) {\n reg.options = { ...reg.options, ...newOptions }\n manager.registrations.setState((prev) =>\n new Map(prev).set(id, toRegistrationView(reg)),\n )\n }\n },\n unregister: () => {\n manager.#unregister(id)\n },\n }\n\n return handle\n }\n\n /**\n * Unregisters a sequence by its registration ID.\n */\n #unregister(id: string): void {\n const registration = this.#registrations.get(id)\n if (!registration) {\n return\n }\n\n const target = registration.target\n\n this.#registrations.delete(id)\n this.registrations.setState((prev) => {\n const next = new Map(prev)\n next.delete(id)\n return next\n })\n\n // Remove from target registrations tracking\n const targetRegs = this.#targetRegistrations.get(target)\n if (targetRegs) {\n targetRegs.delete(id)\n if (targetRegs.size === 0) {\n this.#removeListenersForTarget(target)\n }\n }\n }\n\n /**\n * Ensures event listeners are attached for a specific target.\n */\n #ensureListenersForTarget(target: Target): void {\n if (typeof document === 'undefined') {\n return // SSR safety\n }\n\n if (this.#targetListeners.has(target)) {\n return\n }\n\n const keydownHandler = this.#createTargetKeyDownHandler(target)\n const keyupHandler = this.#createTargetKeyUpHandler(target)\n\n target.addEventListener('keydown', keydownHandler as EventListener)\n target.addEventListener('keyup', keyupHandler as EventListener)\n\n this.#targetListeners.set(target, {\n keydown: keydownHandler,\n keyup: keyupHandler,\n })\n }\n\n /**\n * Removes event listeners for a specific target.\n */\n #removeListenersForTarget(target: Target): void {\n if (typeof document === 'undefined') {\n return\n }\n\n const listeners = this.#targetListeners.get(target)\n if (!listeners) {\n return\n }\n\n target.removeEventListener('keydown', listeners.keydown as EventListener)\n target.removeEventListener('keyup', listeners.keyup as EventListener)\n\n this.#targetListeners.delete(target)\n this.#targetRegistrations.delete(target)\n }\n\n /**\n * Creates a keydown handler for a specific target.\n */\n #createTargetKeyDownHandler(target: Target): (event: KeyboardEvent) => void {\n return (event: KeyboardEvent) => {\n this.#processTargetEvent(event, target, 'keydown')\n }\n }\n\n /**\n * Creates a keyup handler for a specific target.\n */\n #createTargetKeyUpHandler(target: Target): (event: KeyboardEvent) => void {\n return (event: KeyboardEvent) => {\n this.#processTargetEvent(event, target, 'keyup')\n }\n }\n\n /**\n * Processes keyboard events for a specific target and event type.\n */\n #processTargetEvent(\n event: KeyboardEvent,\n target: Target,\n eventType: 'keydown' | 'keyup',\n ): void {\n const targetRegs = this.#targetRegistrations.get(target)\n if (!targetRegs) {\n return\n }\n\n const now = Date.now()\n\n for (const id of targetRegs) {\n const registration = this.#registrations.get(id)\n if (!registration) {\n continue\n }\n\n if (!isEventForTarget(event, target)) {\n continue\n }\n\n if (!registration.options.enabled) {\n continue\n }\n\n // Check if we should ignore input elements (defaults to true)\n if (registration.options.ignoreInputs !== false) {\n if (isInputElement(event.target)) {\n // Don't ignore if the sequence is explicitly scoped to this input element\n if (event.target !== registration.target) {\n continue\n }\n }\n }\n\n // Only process registrations that listen for this event type\n if (registration.options.eventType !== eventType) {\n continue\n }\n\n const timeout = registration.options.timeout ?? DEFAULT_SEQUENCE_TIMEOUT\n\n // Check if sequence has timed out\n if (\n registration.currentIndex > 0 &&\n now - registration.lastKeyTime > timeout\n ) {\n registration.currentIndex = 0\n }\n\n const expectedHotkey =\n registration.parsedSequence[registration.currentIndex]\n if (!expectedHotkey) {\n continue\n }\n\n if (\n matchesKeyboardEvent(\n event,\n expectedHotkey,\n registration.options.platform,\n )\n ) {\n registration.lastKeyTime = now\n registration.currentIndex++\n\n if (registration.currentIndex >= registration.parsedSequence.length) {\n if (registration.options.preventDefault) {\n event.preventDefault()\n }\n if (registration.options.stopPropagation) {\n event.stopPropagation()\n }\n\n const context: HotkeyCallbackContext = {\n hotkey: registration.sequence.join(' ') as Hotkey,\n parsedHotkey:\n registration.parsedSequence[\n registration.parsedSequence.length - 1\n ]!,\n }\n\n registration.callback(event, context)\n\n registration.currentIndex = 0\n }\n } else if (registration.currentIndex > 0) {\n const firstHotkey = registration.parsedSequence[0]!\n if (\n matchesKeyboardEvent(\n event,\n firstHotkey,\n registration.options.platform,\n )\n ) {\n registration.currentIndex = 1\n registration.lastKeyTime = now\n } else {\n registration.currentIndex = 0\n }\n }\n }\n }\n\n /**\n * Finds an existing registration with the same sequence and target.\n */\n #findConflictingSequence(\n sequence: HotkeySequence,\n target: Target,\n ): SequenceRegistration | null {\n const key = sequenceKey(sequence)\n for (const registration of this.#registrations.values()) {\n if (\n sequenceKey(registration.sequence) === key &&\n registration.target === target\n ) {\n return registration\n }\n }\n return null\n }\n\n /**\n * Resets all sequence progress.\n */\n resetAll(): void {\n for (const registration of this.#registrations.values()) {\n registration.currentIndex = 0\n registration.lastKeyTime = 0\n }\n }\n\n /**\n * Triggers a sequence's callback programmatically from devtools.\n * Creates a synthetic KeyboardEvent from the last key in the sequence.\n *\n * @param id - The registration ID to trigger\n * @returns True if the registration was found and triggered\n */\n triggerSequence(id: string): boolean {\n const registration = this.#registrations.get(id)\n if (!registration) {\n return false\n }\n\n const lastParsed =\n registration.parsedSequence[registration.parsedSequence.length - 1]\n if (!lastParsed) {\n return false\n }\n\n const syntheticEvent = new KeyboardEvent(\n registration.options.eventType ?? 'keydown',\n {\n key: lastParsed.key,\n ctrlKey: lastParsed.ctrl,\n shiftKey: lastParsed.shift,\n altKey: lastParsed.alt,\n metaKey: lastParsed.meta,\n bubbles: true,\n cancelable: true,\n },\n )\n\n registration.triggerCount++\n\n this.registrations.setState((prev) =>\n new Map(prev).set(id, toRegistrationView(registration)),\n )\n\n const context: HotkeyCallbackContext = {\n hotkey: registration.sequence.join(' ') as Hotkey,\n parsedHotkey: lastParsed,\n }\n\n registration.callback(syntheticEvent, context)\n\n return true\n }\n\n /**\n * Gets the number of registered sequences.\n */\n getRegistrationCount(): number {\n return this.#registrations.size\n }\n\n /**\n * Destroys the manager and removes all listeners.\n */\n destroy(): void {\n for (const target of this.#targetListeners.keys()) {\n this.#removeListenersForTarget(target)\n }\n this.#registrations.clear()\n this.registrations.setState(() => new Map())\n }\n}\n\n/**\n * Gets the singleton SequenceManager instance.\n * Convenience function for accessing the manager.\n */\nexport function getSequenceManager(): SequenceManager {\n return SequenceManager.getInstance()\n}\n\n/**\n * Creates a simple sequence matcher for one-off use.\n *\n * This is a low-level helper that does not support ignoreInputs, target,\n * or other HotkeyOptions. Callers must handle input filtering themselves\n * if attaching to document.\n *\n * @param sequence - The sequence of hotkeys to match\n * @param options - Options including timeout\n * @returns An object with match() and reset() methods\n *\n * @example\n * ```ts\n * const matcher = createSequenceMatcher(['G', 'G'], { timeout: 500 })\n *\n * document.addEventListener('keydown', (event) => {\n * if (matcher.match(event)) {\n * console.log('Sequence matched!')\n * }\n * })\n * ```\n */\nexport function createSequenceMatcher(\n sequence: HotkeySequence,\n options: { timeout?: number; platform?: 'mac' | 'windows' | 'linux' } = {},\n): {\n match: (event: KeyboardEvent) => boolean\n reset: () => void\n getProgress: () => number\n} {\n const platform = options.platform ?? detectPlatform()\n const timeout = options.timeout ?? DEFAULT_SEQUENCE_TIMEOUT\n const parsedSequence = sequence.map((hotkey) => parseHotkey(hotkey, platform))\n\n let currentIndex = 0\n let lastKeyTime = 0\n\n return {\n match(event: KeyboardEvent): boolean {\n const now = Date.now()\n\n if (currentIndex > 0 && now - lastKeyTime > timeout) {\n currentIndex = 0\n }\n\n const expected = parsedSequence[currentIndex]\n if (!expected) {\n return false\n }\n\n if (matchesKeyboardEvent(event, expected, platform)) {\n lastKeyTime = now\n currentIndex++\n\n if (currentIndex >= parsedSequence.length) {\n currentIndex = 0\n return true\n }\n } else if (currentIndex > 0) {\n if (matchesKeyboardEvent(event, parsedSequence[0]!, platform)) {\n currentIndex = 1\n lastKeyTime = now\n } else {\n currentIndex = 0\n }\n }\n\n return false\n },\n\n reset(): void {\n currentIndex = 0\n lastKeyTime = 0\n },\n\n getProgress(): number {\n return currentIndex\n },\n }\n}\n"],"mappings":";;;;;;;;;;;AA8CA,MAAM,2BAA2B;AAEjC,IAAI,oBAAoB;;;;AAKxB,SAAS,qBAA6B;AACpC,QAAO,YAAY,EAAE;;;;;AAMvB,SAAS,YAAY,UAAkC;AACrD,QAAO,SAAS,KAAK,IAAI;;;;;;;;;;;;;;;;;;;;;;;;;AA0E3B,SAAS,mBACP,KAC0B;AAC1B,QAAO;EACL,IAAI,IAAI;EACR,UAAU,IAAI;EACd,SAAS,IAAI;EACb,QAAQ,IAAI;EACZ,cAAc,IAAI;EACnB;;AAGH,IAAa,kBAAb,MAAa,gBAAgB;CAC3B,QAAOA,WAAoC;CAS3C,iCAAoD,IAAI,KAAK;CAC7D,mCAMI,IAAI,KAAK;CACb,uCAAiD,IAAI,KAAK;CAC1D;CAEA,AAAQ,cAAc;uBAbpB,IAAI,sBAAM,IAAI,KAAK,CAAC;AAcpB,QAAKC,WAAY,gBAAgB;;;;;CAMnC,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;;;;;;;;;;;CAYhC,SACE,UACA,UACA,UAA2B,EAAE,EACD;AAC5B,MAAI,SAAS,WAAW,EACtB,OAAM,IAAI,MAAM,4CAA4C;EAG9D,MAAM,KAAK,oBAA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AAO,gBAAgB,aAAa;;;;;;;;;;;;;;;;;;;;;;;;AAyBtC,SAAgB,sBACd,UACA,UAAwE,EAAE,EAK1E;CACA,MAAM,WAAW,QAAQ,YAAY,gBAAgB;CACrD,MAAM,UAAU,QAAQ,WAAW;CACnC,MAAM,iBAAiB,SAAS,KAAK,WAAW,YAAY,QAAQ,SAAS,CAAC;CAE9E,IAAI,eAAe;CACnB,IAAI,cAAc;AAElB,QAAO;EACL,MAAM,OAA+B;GACnC,MAAM,MAAM,KAAK,KAAK;AAEtB,OAAI,eAAe,KAAK,MAAM,cAAc,QAC1C,gBAAe;GAGjB,MAAM,WAAW,eAAe;AAChC,OAAI,CAAC,SACH,QAAO;AAGT,OAAI,qBAAqB,OAAO,UAAU,SAAS,EAAE;AACnD,kBAAc;AACd;AAEA,QAAI,gBAAgB,eAAe,QAAQ;AACzC,oBAAe;AACf,YAAO;;cAEA,eAAe,EACxB,KAAI,qBAAqB,OAAO,eAAe,IAAK,SAAS,EAAE;AAC7D,mBAAe;AACf,kBAAc;SAEd,gBAAe;AAInB,UAAO;;EAGT,QAAc;AACZ,kBAAe;AACf,iBAAc;;EAGhB,cAAsB;AACpB,UAAO;;EAEV"}
1
+ {"version":3,"file":"sequence-manager.js","names":["#instance","#platform","#findConflictingSequence","#unregister","#registrations","#targetRegistrations","#ensureListenersForTarget","#removeListenersForTarget","#targetListeners","#createTargetKeyDownHandler","#createTargetKeyUpHandler","#processTargetEvent"],"sources":["../src/sequence-manager.ts"],"sourcesContent":["import { Store } from '@tanstack/store'\nimport { formatHotkeySequence } from './format'\nimport { detectPlatform } from './constants'\nimport { isModifierKey, parseHotkey } from './parse'\nimport { matchesKeyboardEvent } from './match'\nimport {\n defaultHotkeyOptions,\n getDefaultIgnoreInputs,\n handleConflict,\n isEventForTarget,\n isInputElement,\n} from './manager.utils'\nimport type { HotkeyOptions } from './hotkey-manager'\nimport type {\n Hotkey,\n HotkeyCallback,\n HotkeyCallbackContext,\n ParsedHotkey,\n} from './hotkey'\n\ntype Target = HTMLElement | Document | Window\n\n/**\n * Options for hotkey sequence matching.\n * Extends HotkeyOptions but excludes requireReset (not applicable to sequences).\n */\nexport interface SequenceOptions extends Omit<HotkeyOptions, 'requireReset'> {\n /** Timeout between keys in milliseconds. Default: 1000 */\n timeout?: number\n}\n\n/**\n * A sequence of hotkeys for Vim-style shortcuts.\n *\n * Each element is one step (a `Hotkey` string). Steps may include modifiers;\n * the same modifier can appear on consecutive steps (e.g. `Shift+R` then\n * `Shift+T`). Modifier-only key events do not advance or reset matching—see\n * `SequenceManager`.\n *\n * @example\n * ```ts\n * const gotoTop: HotkeySequence = ['G', 'G'] // gg\n * const deleteLine: HotkeySequence = ['D', 'D'] // dd\n * const deleteWord: HotkeySequence = ['D', 'I', 'W'] // diw\n * const chainedShift: HotkeySequence = ['Shift+R', 'Shift+T']\n * ```\n */\nexport type HotkeySequence = Array<Hotkey>\n\n/**\n * Default timeout between keys in a sequence (in milliseconds).\n */\nconst DEFAULT_SEQUENCE_TIMEOUT = 1000\n\nlet sequenceIdCounter = 0\n\n/**\n * Generates a unique ID for sequence registrations.\n */\nfunction generateSequenceId(): string {\n return `sequence_${++sequenceIdCounter}`\n}\n\n/**\n * Returns a canonical string for sequence conflict comparison.\n */\nfunction sequenceKey(sequence: HotkeySequence): string {\n return sequence.join('|')\n}\n\n/**\n * View of a sequence registration for devtools display.\n * Excludes internal matching state (currentIndex, lastKeyTime).\n */\nexport interface SequenceRegistrationView {\n id: string\n sequence: HotkeySequence\n options: SequenceOptions\n target: Target\n triggerCount: number\n}\n\n/**\n * Internal representation of a sequence registration.\n */\ninterface SequenceRegistration {\n id: string\n sequence: HotkeySequence\n parsedSequence: Array<ParsedHotkey>\n callback: HotkeyCallback\n options: SequenceOptions\n target: Target\n currentIndex: number\n lastKeyTime: number\n triggerCount: number\n}\n\n/**\n * A handle returned from SequenceManager.register() that allows updating\n * the callback and options without re-registering the sequence.\n *\n * @example\n * ```ts\n * const handle = manager.register(['G', 'G'], callback, options)\n *\n * handle.callback = newCallback\n * handle.setOptions({ timeout: 500 })\n * handle.unregister()\n * ```\n */\nexport interface SequenceRegistrationHandle {\n readonly id: string\n readonly isActive: boolean\n callback: HotkeyCallback\n setOptions: (options: Partial<SequenceOptions>) => void\n unregister: () => void\n}\n\n/**\n * Manages keyboard sequence matching for Vim-style shortcuts.\n *\n * This class allows registering multi-key sequences like 'g g' or 'd d'\n * that trigger callbacks when the full sequence is pressed within\n * a configurable timeout.\n *\n * Modifier-only `keydown` / `keyup` events (Shift, Control, Alt, or Meta\n * alone) are not processed: they neither match a step nor reset progress.\n * That supports chained modifier chords (e.g. `Shift+R` then `Shift+T`) when\n * the user presses a modifier alone between steps.\n *\n * @example\n * ```ts\n * const matcher = SequenceManager.getInstance()\n *\n * // Register 'g g' to go to top\n * const unregister = matcher.register(['G', 'G'], (event, context) => {\n * scrollToTop()\n * }, { timeout: 500 })\n *\n * // Later, to unregister:\n * unregister()\n * ```\n */\n/**\n * Builds a devtools view from an internal registration.\n */\nfunction toRegistrationView(\n reg: SequenceRegistration,\n): SequenceRegistrationView {\n return {\n id: reg.id,\n sequence: reg.sequence,\n options: reg.options,\n target: reg.target,\n triggerCount: reg.triggerCount,\n }\n}\n\nexport class SequenceManager {\n static #instance: SequenceManager | null = null\n\n /**\n * The TanStack Store containing sequence registration views for devtools.\n * Subscribe to this to observe registration changes.\n */\n readonly registrations: Store<Map<string, SequenceRegistrationView>> =\n new Store(new Map())\n\n #registrations: Map<string, SequenceRegistration> = new Map()\n #targetListeners: Map<\n Target,\n {\n keydown: (event: KeyboardEvent) => void\n keyup: (event: KeyboardEvent) => void\n }\n > = new Map()\n #targetRegistrations: Map<Target, Set<string>> = new Map()\n #platform: 'mac' | 'windows' | 'linux'\n\n private constructor() {\n this.#platform = detectPlatform()\n }\n\n /**\n * Gets the singleton instance of SequenceManager.\n */\n static getInstance(): SequenceManager {\n if (!SequenceManager.#instance) {\n SequenceManager.#instance = new SequenceManager()\n }\n return SequenceManager.#instance\n }\n\n /**\n * Resets the singleton instance. Useful for testing.\n */\n static resetInstance(): void {\n if (SequenceManager.#instance) {\n SequenceManager.#instance.destroy()\n SequenceManager.#instance = null\n }\n }\n\n /**\n * Registers a hotkey sequence handler.\n *\n * @param sequence - Array of hotkey strings that form the sequence\n * @param callback - Function to call when the sequence is completed\n * @param options - Options for the sequence behavior\n * @returns A handle to update or unregister the sequence\n */\n register(\n sequence: HotkeySequence,\n callback: HotkeyCallback,\n options: SequenceOptions = {},\n ): SequenceRegistrationHandle {\n if (sequence.length === 0) {\n throw new Error('Sequence must contain at least one hotkey')\n }\n\n const id = generateSequenceId()\n const platform = options.platform ?? this.#platform\n const parsedSequence = sequence.map((hotkey) =>\n parseHotkey(hotkey, platform),\n )\n\n // Resolve target: default to document if not provided or null\n const target: Target =\n options.target ??\n (typeof document !== 'undefined' ? document : ({} as Document))\n\n // Resolve conflict behavior\n const conflictBehavior = options.conflictBehavior ?? 'warn'\n\n // Check for existing registrations with the same sequence and target\n const conflictingRegistration = this.#findConflictingSequence(\n sequence,\n target,\n )\n\n if (conflictingRegistration) {\n handleConflict(\n conflictingRegistration.id,\n formatHotkeySequence(sequence),\n conflictBehavior,\n (regId) => this.#unregister(regId),\n )\n }\n\n const firstStep = parsedSequence[0]!\n const resolvedIgnoreInputs =\n options.ignoreInputs ?? getDefaultIgnoreInputs(firstStep)\n\n const baseOptions = {\n ...defaultHotkeyOptions,\n timeout: DEFAULT_SEQUENCE_TIMEOUT,\n ...options,\n platform,\n ignoreInputs: resolvedIgnoreInputs,\n }\n\n const registration: SequenceRegistration = {\n id,\n sequence,\n parsedSequence,\n callback,\n options: baseOptions,\n target,\n currentIndex: 0,\n lastKeyTime: 0,\n triggerCount: 0,\n }\n\n this.#registrations.set(id, registration)\n this.registrations.setState((prev) =>\n new Map(prev).set(id, toRegistrationView(registration)),\n )\n\n // Track registration for this target\n if (!this.#targetRegistrations.has(target)) {\n this.#targetRegistrations.set(target, new Set())\n }\n this.#targetRegistrations.get(target)!.add(id)\n\n // Ensure listeners are attached for this target\n this.#ensureListenersForTarget(target)\n\n const manager = this\n const handle: SequenceRegistrationHandle = {\n get id() {\n return id\n },\n get isActive() {\n return manager.#registrations.has(id)\n },\n get callback() {\n const reg = manager.#registrations.get(id)\n return reg?.callback ?? callback\n },\n set callback(newCallback: HotkeyCallback) {\n const reg = manager.#registrations.get(id)\n if (reg) {\n reg.callback = newCallback\n }\n },\n setOptions: (newOptions: Partial<SequenceOptions>) => {\n const reg = manager.#registrations.get(id)\n if (reg) {\n reg.options = { ...reg.options, ...newOptions }\n manager.registrations.setState((prev) =>\n new Map(prev).set(id, toRegistrationView(reg)),\n )\n }\n },\n unregister: () => {\n manager.#unregister(id)\n },\n }\n\n return handle\n }\n\n /**\n * Unregisters a sequence by its registration ID.\n */\n #unregister(id: string): void {\n const registration = this.#registrations.get(id)\n if (!registration) {\n return\n }\n\n const target = registration.target\n\n this.#registrations.delete(id)\n this.registrations.setState((prev) => {\n const next = new Map(prev)\n next.delete(id)\n return next\n })\n\n // Remove from target registrations tracking\n const targetRegs = this.#targetRegistrations.get(target)\n if (targetRegs) {\n targetRegs.delete(id)\n if (targetRegs.size === 0) {\n this.#removeListenersForTarget(target)\n }\n }\n }\n\n /**\n * Ensures event listeners are attached for a specific target.\n */\n #ensureListenersForTarget(target: Target): void {\n if (typeof document === 'undefined') {\n return // SSR safety\n }\n\n if (this.#targetListeners.has(target)) {\n return\n }\n\n const keydownHandler = this.#createTargetKeyDownHandler(target)\n const keyupHandler = this.#createTargetKeyUpHandler(target)\n\n target.addEventListener('keydown', keydownHandler as EventListener)\n target.addEventListener('keyup', keyupHandler as EventListener)\n\n this.#targetListeners.set(target, {\n keydown: keydownHandler,\n keyup: keyupHandler,\n })\n }\n\n /**\n * Removes event listeners for a specific target.\n */\n #removeListenersForTarget(target: Target): void {\n if (typeof document === 'undefined') {\n return\n }\n\n const listeners = this.#targetListeners.get(target)\n if (!listeners) {\n return\n }\n\n target.removeEventListener('keydown', listeners.keydown as EventListener)\n target.removeEventListener('keyup', listeners.keyup as EventListener)\n\n this.#targetListeners.delete(target)\n this.#targetRegistrations.delete(target)\n }\n\n /**\n * Creates a keydown handler for a specific target.\n */\n #createTargetKeyDownHandler(target: Target): (event: KeyboardEvent) => void {\n return (event: KeyboardEvent) => {\n this.#processTargetEvent(event, target, 'keydown')\n }\n }\n\n /**\n * Creates a keyup handler for a specific target.\n */\n #createTargetKeyUpHandler(target: Target): (event: KeyboardEvent) => void {\n return (event: KeyboardEvent) => {\n this.#processTargetEvent(event, target, 'keyup')\n }\n }\n\n /**\n * Processes keyboard events for a specific target and event type.\n */\n #processTargetEvent(\n event: KeyboardEvent,\n target: Target,\n eventType: 'keydown' | 'keyup',\n ): void {\n // Skip modifier-only events so pressing e.g. Shift before Shift+C does not reset the sequence.\n if (isModifierKey(event)) {\n return\n }\n\n const targetRegs = this.#targetRegistrations.get(target)\n if (!targetRegs) {\n return\n }\n\n const now = Date.now()\n\n for (const id of targetRegs) {\n const registration = this.#registrations.get(id)\n if (!registration) {\n continue\n }\n\n if (!isEventForTarget(event, target)) {\n continue\n }\n\n if (!registration.options.enabled) {\n continue\n }\n\n // Check if we should ignore input elements (defaults to true)\n if (registration.options.ignoreInputs !== false) {\n if (isInputElement(event.target)) {\n // Don't ignore if the sequence is explicitly scoped to this input element\n if (event.target !== registration.target) {\n continue\n }\n }\n }\n\n // Only process registrations that listen for this event type\n if (registration.options.eventType !== eventType) {\n continue\n }\n\n const timeout = registration.options.timeout ?? DEFAULT_SEQUENCE_TIMEOUT\n\n // Check if sequence has timed out\n if (\n registration.currentIndex > 0 &&\n now - registration.lastKeyTime > timeout\n ) {\n registration.currentIndex = 0\n }\n\n const expectedHotkey =\n registration.parsedSequence[registration.currentIndex]\n if (!expectedHotkey) {\n continue\n }\n\n if (\n matchesKeyboardEvent(\n event,\n expectedHotkey,\n registration.options.platform,\n )\n ) {\n registration.lastKeyTime = now\n registration.currentIndex++\n\n if (registration.currentIndex >= registration.parsedSequence.length) {\n if (registration.options.preventDefault) {\n event.preventDefault()\n }\n if (registration.options.stopPropagation) {\n event.stopPropagation()\n }\n\n const context: HotkeyCallbackContext = {\n hotkey: registration.sequence.join(' ') as Hotkey,\n parsedHotkey:\n registration.parsedSequence[\n registration.parsedSequence.length - 1\n ]!,\n }\n\n registration.callback(event, context)\n\n registration.currentIndex = 0\n }\n } else if (registration.currentIndex > 0) {\n const firstHotkey = registration.parsedSequence[0]!\n if (\n matchesKeyboardEvent(\n event,\n firstHotkey,\n registration.options.platform,\n )\n ) {\n registration.currentIndex = 1\n registration.lastKeyTime = now\n } else {\n registration.currentIndex = 0\n }\n }\n }\n }\n\n /**\n * Finds an existing registration with the same sequence and target.\n */\n #findConflictingSequence(\n sequence: HotkeySequence,\n target: Target,\n ): SequenceRegistration | null {\n const key = sequenceKey(sequence)\n for (const registration of this.#registrations.values()) {\n if (\n sequenceKey(registration.sequence) === key &&\n registration.target === target\n ) {\n return registration\n }\n }\n return null\n }\n\n /**\n * Resets all sequence progress.\n */\n resetAll(): void {\n for (const registration of this.#registrations.values()) {\n registration.currentIndex = 0\n registration.lastKeyTime = 0\n }\n }\n\n /**\n * Triggers a sequence's callback programmatically from devtools.\n * Creates a synthetic KeyboardEvent from the last key in the sequence.\n *\n * @param id - The registration ID to trigger\n * @returns True if the registration was found and triggered\n */\n triggerSequence(id: string): boolean {\n const registration = this.#registrations.get(id)\n if (!registration) {\n return false\n }\n\n const lastParsed =\n registration.parsedSequence[registration.parsedSequence.length - 1]\n if (!lastParsed) {\n return false\n }\n\n const syntheticEvent = new KeyboardEvent(\n registration.options.eventType ?? 'keydown',\n {\n key: lastParsed.key,\n ctrlKey: lastParsed.ctrl,\n shiftKey: lastParsed.shift,\n altKey: lastParsed.alt,\n metaKey: lastParsed.meta,\n bubbles: true,\n cancelable: true,\n },\n )\n\n registration.triggerCount++\n\n this.registrations.setState((prev) =>\n new Map(prev).set(id, toRegistrationView(registration)),\n )\n\n const context: HotkeyCallbackContext = {\n hotkey: registration.sequence.join(' ') as Hotkey,\n parsedHotkey: lastParsed,\n }\n\n registration.callback(syntheticEvent, context)\n\n return true\n }\n\n /**\n * Gets the number of registered sequences.\n */\n getRegistrationCount(): number {\n return this.#registrations.size\n }\n\n /**\n * Destroys the manager and removes all listeners.\n */\n destroy(): void {\n for (const target of this.#targetListeners.keys()) {\n this.#removeListenersForTarget(target)\n }\n this.#registrations.clear()\n this.registrations.setState(() => new Map())\n }\n}\n\n/**\n * Gets the singleton SequenceManager instance.\n * Convenience function for accessing the manager.\n */\nexport function getSequenceManager(): SequenceManager {\n return SequenceManager.getInstance()\n}\n\n/**\n * Creates a simple sequence matcher for one-off use.\n *\n * This is a low-level helper that does not support ignoreInputs, target,\n * or other HotkeyOptions. Callers must handle input filtering themselves\n * if attaching to document.\n *\n * @param sequence - The sequence of hotkeys to match\n * @param options - Options including timeout\n * @returns An object with match() and reset() methods\n *\n * @example\n * ```ts\n * const matcher = createSequenceMatcher(['G', 'G'], { timeout: 500 })\n *\n * document.addEventListener('keydown', (event) => {\n * if (matcher.match(event)) {\n * console.log('Sequence matched!')\n * }\n * })\n * ```\n */\nexport function createSequenceMatcher(\n sequence: HotkeySequence,\n options: { timeout?: number; platform?: 'mac' | 'windows' | 'linux' } = {},\n): {\n match: (event: KeyboardEvent) => boolean\n reset: () => void\n getProgress: () => number\n} {\n const platform = options.platform ?? detectPlatform()\n const timeout = options.timeout ?? DEFAULT_SEQUENCE_TIMEOUT\n const parsedSequence = sequence.map((hotkey) => parseHotkey(hotkey, platform))\n\n let currentIndex = 0\n let lastKeyTime = 0\n\n return {\n match(event: KeyboardEvent): boolean {\n const now = Date.now()\n\n if (currentIndex > 0 && now - lastKeyTime > timeout) {\n currentIndex = 0\n }\n\n const expected = parsedSequence[currentIndex]\n if (!expected) {\n return false\n }\n\n if (matchesKeyboardEvent(event, expected, platform)) {\n lastKeyTime = now\n currentIndex++\n\n if (currentIndex >= parsedSequence.length) {\n currentIndex = 0\n return true\n }\n } else if (currentIndex > 0) {\n if (matchesKeyboardEvent(event, parsedSequence[0]!, platform)) {\n currentIndex = 1\n lastKeyTime = now\n } else {\n currentIndex = 0\n }\n }\n\n return false\n },\n\n reset(): void {\n currentIndex = 0\n lastKeyTime = 0\n },\n\n getProgress(): number {\n return currentIndex\n },\n }\n}\n"],"mappings":";;;;;;;;;;;AAoDA,MAAM,2BAA2B;AAEjC,IAAI,oBAAoB;;;;AAKxB,SAAS,qBAA6B;AACpC,QAAO,YAAY,EAAE;;;;;AAMvB,SAAS,YAAY,UAAkC;AACrD,QAAO,SAAS,KAAK,IAAI;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+E3B,SAAS,mBACP,KAC0B;AAC1B,QAAO;EACL,IAAI,IAAI;EACR,UAAU,IAAI;EACd,SAAS,IAAI;EACb,QAAQ,IAAI;EACZ,cAAc,IAAI;EACnB;;AAGH,IAAa,kBAAb,MAAa,gBAAgB;CAC3B,QAAOA,WAAoC;CAS3C,iCAAoD,IAAI,KAAK;CAC7D,mCAMI,IAAI,KAAK;CACb,uCAAiD,IAAI,KAAK;CAC1D;CAEA,AAAQ,cAAc;uBAbpB,IAAI,sBAAM,IAAI,KAAK,CAAC;AAcpB,QAAKC,WAAY,gBAAgB;;;;;CAMnC,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;;;;;;;;;;;CAYhC,SACE,UACA,UACA,UAA2B,EAAE,EACD;AAC5B,MAAI,SAAS,WAAW,EACtB,OAAM,IAAI,MAAM,4CAA4C;EAG9D,MAAM,KAAK,oBAAoB;EAC/B,MAAM,WAAW,QAAQ,YAAY,MAAKC;EAC1C,MAAM,iBAAiB,SAAS,KAAK,WACnC,YAAY,QAAQ,SA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,UACA,UAAwE,EAAE,EAK1E;CACA,MAAM,WAAW,QAAQ,YAAY,gBAAgB;CACrD,MAAM,UAAU,QAAQ,WAAW;CACnC,MAAM,iBAAiB,SAAS,KAAK,WAAW,YAAY,QAAQ,SAAS,CAAC;CAE9E,IAAI,eAAe;CACnB,IAAI,cAAc;AAElB,QAAO;EACL,MAAM,OAA+B;GACnC,MAAM,MAAM,KAAK,KAAK;AAEtB,OAAI,eAAe,KAAK,MAAM,cAAc,QAC1C,gBAAe;GAGjB,MAAM,WAAW,eAAe;AAChC,OAAI,CAAC,SACH,QAAO;AAGT,OAAI,qBAAqB,OAAO,UAAU,SAAS,EAAE;AACnD,kBAAc;AACd;AAEA,QAAI,gBAAgB,eAAe,QAAQ;AACzC,oBAAe;AACf,YAAO;;cAEA,eAAe,EACxB,KAAI,qBAAqB,OAAO,eAAe,IAAK,SAAS,EAAE;AAC7D,mBAAe;AACf,kBAAc;SAEd,gBAAe;AAInB,UAAO;;EAGT,QAAc;AACZ,kBAAe;AACf,iBAAc;;EAGhB,cAAsB;AACpB,UAAO;;EAEV"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanstack/hotkeys",
3
- "version": "0.4.1",
3
+ "version": "0.4.3",
4
4
  "description": "Type-safe, framework-agnostic keyboard hotkey management for the browser",
5
5
  "author": "Tanner Linsley",
6
6
  "license": "MIT",
package/src/constants.ts CHANGED
@@ -297,9 +297,32 @@ export const PUNCTUATION_KEYS = new Set<PunctuationKey>([
297
297
  '-',
298
298
  ',',
299
299
  '.',
300
+ ';',
300
301
  '`',
301
302
  ])
302
303
 
304
+ /**
305
+ * Maps `KeyboardEvent.code` values for punctuation keys to their canonical characters.
306
+ *
307
+ * On macOS, holding the Option (Alt) key transforms punctuation keys into special characters
308
+ * (e.g., Option+Minus → en-dash '–'), causing `event.key` to differ from the expected character.
309
+ * However, `event.code` still reports the physical key (e.g., 'Minus'). This map enables
310
+ * falling back to `event.code` for punctuation keys, similar to the existing `Key*`/`Digit*`
311
+ * fallbacks for letters and digits.
312
+ */
313
+ export const PUNCTUATION_CODE_MAP: Record<string, string> = {
314
+ Minus: '-',
315
+ Equal: '=',
316
+ Slash: '/',
317
+ BracketLeft: '[',
318
+ BracketRight: ']',
319
+ Backslash: '\\',
320
+ Comma: ',',
321
+ Period: '.',
322
+ Backquote: '`',
323
+ Semicolon: ';',
324
+ }
325
+
303
326
  /**
304
327
  * Set of all valid non-modifier keys.
305
328
  *
package/src/hotkey.ts CHANGED
@@ -123,6 +123,7 @@ export type PunctuationKey =
123
123
  | '-'
124
124
  | ','
125
125
  | '.'
126
+ | ';'
126
127
  | '`'
127
128
 
128
129
  /**
package/src/match.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import {
2
+ PUNCTUATION_CODE_MAP,
2
3
  detectPlatform,
3
4
  isSingleLetterKey,
4
5
  normalizeKeyName,
@@ -15,8 +16,9 @@ import type {
15
16
  * Checks if a KeyboardEvent matches a hotkey.
16
17
  *
17
18
  * Uses the `key` property from KeyboardEvent for matching, with a fallback to `code`
18
- * for letter keys and digit keys (0-9) when `key` produces special characters
19
- * (e.g., macOS Option+letter or Shift+number). Letter keys are matched case-insensitively.
19
+ * for letter keys, digit keys (0-9), and punctuation keys when `key` produces special
20
+ * characters (e.g., macOS Option+letter, Shift+number, or Option+punctuation).
21
+ * Letter keys are matched case-insensitively.
20
22
  *
21
23
  * Also handles "dead key" events where `event.key` is `'Dead'` instead of the expected
22
24
  * character. This commonly occurs on macOS with Option+letter combinations (e.g., Option+E,
@@ -92,23 +94,31 @@ export function matchesKeyboardEvent(
92
94
  // Dead keys: Option+letter on macOS, international layouts produce event.key === 'Dead'
93
95
  // Single-char mismatches: Cmd+Option+T gives '†' instead of 'T', Shift+4 gives '$'
94
96
  if (
95
- eventKey === 'Dead' ||
96
- (eventKey.length === 1 && hotkeyKey.length === 1)
97
+ event.code &&
98
+ (eventKey === 'Dead' || (eventKey.length === 1 && hotkeyKey.length === 1))
97
99
  ) {
98
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- event.code can be undefined in older browsers/mobile
99
- if (event.code?.startsWith('Key')) {
100
+ // fallback for letter keys (common with mac option + letter)
101
+ if (event.code.startsWith('Key')) {
100
102
  const codeLetter = event.code.slice(3)
101
103
  if (codeLetter.length === 1 && /^[A-Za-z]$/.test(codeLetter)) {
102
104
  return codeLetter.toUpperCase() === hotkeyKey.toUpperCase()
103
105
  }
104
106
  }
105
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- event.code can be undefined in older browsers/mobile
106
- if (event.code?.startsWith('Digit')) {
107
+
108
+ // fallback for number keys (common with mac option + num)
109
+ if (event.code.startsWith('Digit')) {
107
110
  const codeDigit = event.code.slice(5)
108
111
  if (codeDigit.length === 1 && /^[0-9]$/.test(codeDigit)) {
109
112
  return codeDigit === hotkeyKey
110
113
  }
111
114
  }
115
+ // Fallback for punctuation keys (e.g., Minus, Slash, BracketLeft).
116
+ // On macOS, Option+punctuation produces composed characters (e.g., Option+- → '–'),
117
+ // but event.code still reports the physical key.
118
+ if (event.code in PUNCTUATION_CODE_MAP) {
119
+ return PUNCTUATION_CODE_MAP[event.code] === hotkeyKey
120
+ }
121
+
112
122
  return false
113
123
  }
114
124
 
@@ -1,7 +1,7 @@
1
1
  import { Store } from '@tanstack/store'
2
2
  import { formatHotkeySequence } from './format'
3
3
  import { detectPlatform } from './constants'
4
- import { parseHotkey } from './parse'
4
+ import { isModifierKey, parseHotkey } from './parse'
5
5
  import { matchesKeyboardEvent } from './match'
6
6
  import {
7
7
  defaultHotkeyOptions,
@@ -32,11 +32,17 @@ export interface SequenceOptions extends Omit<HotkeyOptions, 'requireReset'> {
32
32
  /**
33
33
  * A sequence of hotkeys for Vim-style shortcuts.
34
34
  *
35
+ * Each element is one step (a `Hotkey` string). Steps may include modifiers;
36
+ * the same modifier can appear on consecutive steps (e.g. `Shift+R` then
37
+ * `Shift+T`). Modifier-only key events do not advance or reset matching—see
38
+ * `SequenceManager`.
39
+ *
35
40
  * @example
36
41
  * ```ts
37
42
  * const gotoTop: HotkeySequence = ['G', 'G'] // gg
38
43
  * const deleteLine: HotkeySequence = ['D', 'D'] // dd
39
44
  * const deleteWord: HotkeySequence = ['D', 'I', 'W'] // diw
45
+ * const chainedShift: HotkeySequence = ['Shift+R', 'Shift+T']
40
46
  * ```
41
47
  */
42
48
  export type HotkeySequence = Array<Hotkey>
@@ -117,6 +123,11 @@ export interface SequenceRegistrationHandle {
117
123
  * that trigger callbacks when the full sequence is pressed within
118
124
  * a configurable timeout.
119
125
  *
126
+ * Modifier-only `keydown` / `keyup` events (Shift, Control, Alt, or Meta
127
+ * alone) are not processed: they neither match a step nor reset progress.
128
+ * That supports chained modifier chords (e.g. `Shift+R` then `Shift+T`) when
129
+ * the user presses a modifier alone between steps.
130
+ *
120
131
  * @example
121
132
  * ```ts
122
133
  * const matcher = SequenceManager.getInstance()
@@ -407,6 +418,11 @@ export class SequenceManager {
407
418
  target: Target,
408
419
  eventType: 'keydown' | 'keyup',
409
420
  ): void {
421
+ // Skip modifier-only events so pressing e.g. Shift before Shift+C does not reset the sequence.
422
+ if (isModifierKey(event)) {
423
+ return
424
+ }
425
+
410
426
  const targetRegs = this.#targetRegistrations.get(target)
411
427
  if (!targetRegs) {
412
428
  return