@tanstack/hotkeys 0.4.0 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/constants.cjs +4 -1
- package/dist/constants.cjs.map +1 -1
- package/dist/constants.js +4 -1
- package/dist/constants.js.map +1 -1
- package/dist/match.cjs +1 -1
- package/dist/match.cjs.map +1 -1
- package/dist/match.js +1 -1
- package/dist/match.js.map +1 -1
- package/package.json +1 -1
- package/src/constants.ts +5 -2
- package/src/match.ts +13 -6
package/README.md
CHANGED
|
@@ -44,7 +44,7 @@ Type-safe keyboard shortcuts for the web. Template-string bindings, parsed objec
|
|
|
44
44
|
- Type-safe bindings — template strings (`Mod+Shift+S`, `Escape`) or parsed objects for full control
|
|
45
45
|
- Flexible options — `keydown`/`keyup`, `preventDefault`, `stopPropagation`, conditional enabled, `requireReset`
|
|
46
46
|
- Cross-platform Mod — maps to Cmd on macOS and Ctrl on Windows/Linux
|
|
47
|
-
- Batteries included — validation + matching, sequences (Vim-style), key-state tracking, recorder UI helpers,
|
|
47
|
+
- Batteries included — validation + matching, sequences (Vim-style), key-state tracking, recorder UI helpers, framework adapters, and devtools
|
|
48
48
|
|
|
49
49
|
### <a href="https://tanstack.com/hotkeys">Read the docs →</a>
|
|
50
50
|
|
|
@@ -57,8 +57,8 @@ Type-safe keyboard shortcuts for the web. Template-string bindings, parsed objec
|
|
|
57
57
|
> - [**Preact Hotkeys**](https://tanstack.com/hotkeys/latest/docs/framework/preact/preact-hotkeys)
|
|
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
|
+
> - [**Vue Hotkeys**](https://tanstack.com/hotkeys/latest/docs/framework/vue/reference)
|
|
60
61
|
> - Svelte Hotkeys – needs a contributor!
|
|
61
|
-
> - Vue Hotkeys – needs a contributor!
|
|
62
62
|
|
|
63
63
|
## Get Involved
|
|
64
64
|
|
package/dist/constants.cjs
CHANGED
|
@@ -352,7 +352,10 @@ function isSingleLetterKey(key) {
|
|
|
352
352
|
}
|
|
353
353
|
function normalizeKeyName(key) {
|
|
354
354
|
if (key in KEY_ALIASES) return KEY_ALIASES[key];
|
|
355
|
-
if (isSingleLetterKey(key))
|
|
355
|
+
if (isSingleLetterKey(key)) {
|
|
356
|
+
const upper = key.toUpperCase();
|
|
357
|
+
return upper.length === 1 ? upper : key;
|
|
358
|
+
}
|
|
356
359
|
const upperKey = key.toUpperCase();
|
|
357
360
|
if (/^F([1-9]|1[0-2])$/.test(upperKey)) return upperKey;
|
|
358
361
|
return key;
|
package/dist/constants.cjs.map
CHANGED
|
@@ -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 // Check if it's a single letter (normalize to uppercase)\n if (isSingleLetterKey(key)) {\n return key.toUpperCase()\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: 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AsBT,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.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":";;;;;;;;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AS;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"}
|
package/dist/constants.js
CHANGED
|
@@ -351,7 +351,10 @@ function isSingleLetterKey(key) {
|
|
|
351
351
|
}
|
|
352
352
|
function normalizeKeyName(key) {
|
|
353
353
|
if (key in KEY_ALIASES) return KEY_ALIASES[key];
|
|
354
|
-
if (isSingleLetterKey(key))
|
|
354
|
+
if (isSingleLetterKey(key)) {
|
|
355
|
+
const upper = key.toUpperCase();
|
|
356
|
+
return upper.length === 1 ? upper : key;
|
|
357
|
+
}
|
|
355
358
|
const upperKey = key.toUpperCase();
|
|
356
359
|
if (/^F([1-9]|1[0-2])$/.test(upperKey)) return upperKey;
|
|
357
360
|
return key;
|
package/dist/constants.js.map
CHANGED
|
@@ -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 // Check if it's a single letter (normalize to uppercase)\n if (isSingleLetterKey(key)) {\n return key.toUpperCase()\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;CAC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AAI;;AAGlC,SAAgB,iBAAiB,KAAqB;AAEpD,KAAI,OAAO,YACT,QAAO,YAAY;AAIrB,KAAI,kBAAkB,IAAI,CACxB,QAAO,IAAI,aAAa;CAI1B,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 * 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;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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"}
|
package/dist/match.cjs
CHANGED
|
@@ -39,7 +39,7 @@ function matchesKeyboardEvent(event, hotkey, platform = require_constants.detect
|
|
|
39
39
|
const hotkeyKey = parsed.key;
|
|
40
40
|
if (eventKey !== "Dead" && eventKey.length === 1 && hotkeyKey.length === 1) {
|
|
41
41
|
if (eventKey.toUpperCase() === hotkeyKey.toUpperCase()) return true;
|
|
42
|
-
if (require_constants.isSingleLetterKey(eventKey)) return false;
|
|
42
|
+
if (require_constants.isSingleLetterKey(eventKey) && (/^[A-Za-z]$/.test(eventKey) || !event.altKey)) return false;
|
|
43
43
|
}
|
|
44
44
|
if (eventKey === "Dead" || eventKey.length === 1 && hotkeyKey.length === 1) {
|
|
45
45
|
if (event.code?.startsWith("Key")) {
|
package/dist/match.cjs.map
CHANGED
|
@@ -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 already a letter, trust the keyboard layout.\n // Do NOT fall through to the event.code fallback, which matches based on\n // physical key position and would break non-QWERTY layouts (Dvorak, Colemak,\n // AZERTY, etc.). The code fallback is only needed when event.key produces a\n // non-letter character (e.g., '†' from Option+T on macOS).\n if (isSingleLetterKey(eventKey)) {\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;AAQT,MAAIC,oCAAkB,SAAS,CAC7B,QAAO;;AAQX,KACE,aAAa,UACZ,SAAS,WAAW,KAAK,UAAU,WAAW,GAC/C;AAEA,MAAI,MAAM,MAAM,WAAW,MAAM,EAAE;GACjC,MAAM,aAAa,MAAM,KAAK,MAAM,EAAE;AACtC,OAAI,WAAW,WAAW,KAAK,aAAa,KAAK,WAAW,CAC1D,QAAO,WAAW,aAAa,KAAK,UAAU,aAAa;;AAI/D,MAAI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AAiB;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"],"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,kCAAg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Dead" && eventKey.length === 1 && hotkeyKey.length === 1) {
|
|
41
41
|
if (eventKey.toUpperCase() === hotkeyKey.toUpperCase()) return true;
|
|
42
|
-
if (isSingleLetterKey(eventKey)) return false;
|
|
42
|
+
if (isSingleLetterKey(eventKey) && (/^[A-Za-z]$/.test(eventKey) || !event.altKey)) return false;
|
|
43
43
|
}
|
|
44
44
|
if (eventKey === "Dead" || eventKey.length === 1 && hotkeyKey.length === 1) {
|
|
45
45
|
if (event.code?.startsWith("Key")) {
|
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 already a letter, trust the keyboard layout.\n // Do NOT fall through to the event.code fallback, which matches based on\n // physical key position and would break non-QWERTY layouts (Dvorak, Colemak,\n // AZERTY, etc.). The code fallback is only needed when event.key produces a\n // non-letter character (e.g., '†' from Option+T on macOS).\n if (isSingleLetterKey(eventKey)) {\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;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C,EAAE,EACR;CAChC,MAAM,EAAE,iBAAiB,MAAM,kBAAkB,MAAM,aAAa;CACpE,MAAM,mBAAmB,YAAY,gBAAgB;CAGrD,MAAM,iBAAiB,OAAO,QAAQ,SAAS,CAC5C,QAAQ,UAA6C,QAAQ,MAAM,GAAG,CAAC,CACvE,KAAK,CAAC,QAAQ,aAAa;EAC1B,MAAM,SAAS,YAAY,QAAkB,iBAAiB;AAK9D,SAAO;GAAE;GAAQ;GAAS,SAJa;IAC7B;IACR,cAAc;IACf;GACkC;GACnC;AAEJ,SAAQ,UAAyB;AAC/B,OAAK,MAAM,EAAE,QAAQ,SAAS,aAAa,eACzC,KAAI,qBAAqB,OAAO,QAAQ,iBAAiB,EAAE;AACzD,OAAI,eACF,OAAM,gBAAgB;AAExB,OAAI,gBACF,OAAM,iBAAiB;AAEzB,WAAQ,OAAO,QAAQ;AACvB;;;;;;;;AAUR,SAAS,mBAAmB,QAA8B;CACxD,MAAM,QAAuB,EAAE;AAE/B,KAAI,OAAO,KAAM,OAAM,KAAK,UAAU;AACtC,KAAI,OAAO,IAAK,OAAM,KAAK,MAAM;AACjC,KAAI,OAAO,MAAO,OAAM,KAAK,QAAQ;AACrC,KAAI,OAAO,KAAM,OAAM,KAAK,OAAO;AACnC,OAAM,KAAK,OAAO,IAAI;AAEtB,QAAO,MAAM,KAAK,IAAI"}
|
|
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,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,aAAa,UACZ,SAAS,WAAW,KAAK,UAAU,WAAW,GAC/C;AAEA,MAAI,MAAM,MAAM,WAAW,MAAM,EAAE;GACjC,MAAM,aAAa,MAAM,KAAK,MAAM,EAAE;AACtC,OAAI,WAAW,WAAW,KAAK,aAAa,KAAK,WAAW,CAC1D,QAAO,WAAW,aAAa,KAAK,UAAU,aAAa;;AAI/D,MAAI,MAAM,MAAM,WA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AAO,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"}
|
package/package.json
CHANGED
package/src/constants.ts
CHANGED
|
@@ -429,9 +429,12 @@ export function normalizeKeyName(key: string): string {
|
|
|
429
429
|
return KEY_ALIASES[key]!
|
|
430
430
|
}
|
|
431
431
|
|
|
432
|
-
// Check if it's a single letter (normalize to uppercase)
|
|
433
432
|
if (isSingleLetterKey(key)) {
|
|
434
|
-
|
|
433
|
+
const upper = key.toUpperCase()
|
|
434
|
+
// Some Unicode letters (e.g., 'ß') uppercase to multi-character sequences
|
|
435
|
+
// ('SS'). Avoid changing the string length so the rest of the matching
|
|
436
|
+
// logic can rely on a stable single-character key value.
|
|
437
|
+
return upper.length === 1 ? upper : key
|
|
435
438
|
}
|
|
436
439
|
|
|
437
440
|
// Check if it's a function key (normalize case)
|
package/src/match.ts
CHANGED
|
@@ -70,12 +70,19 @@ export function matchesKeyboardEvent(
|
|
|
70
70
|
return true
|
|
71
71
|
}
|
|
72
72
|
|
|
73
|
-
// If event.key is
|
|
74
|
-
//
|
|
75
|
-
//
|
|
76
|
-
//
|
|
77
|
-
// non-
|
|
78
|
-
|
|
73
|
+
// If event.key is a letter, we usually trust the keyboard layout.
|
|
74
|
+
// For ASCII letters: always trust layout (Dvorak, Colemak, AZERTY support).
|
|
75
|
+
// For non-ASCII letters without Alt: trust layout (e.g., Cyrillic keyboards).
|
|
76
|
+
//
|
|
77
|
+
// For non-ASCII letters WITH Alt held down: fall through to the event.code
|
|
78
|
+
// fallback. macOS Option+letter combinations produce non-ASCII letters as
|
|
79
|
+
// event.key (e.g., Option+A → 'å', Option+' → 'æ', Option+P → 'π'), but
|
|
80
|
+
// event.code still reflects the physical key. We want Alt+A to match even
|
|
81
|
+
// when Option+A fires event.key='å'.
|
|
82
|
+
if (
|
|
83
|
+
isSingleLetterKey(eventKey) &&
|
|
84
|
+
(/^[A-Za-z]$/.test(eventKey) || !event.altKey)
|
|
85
|
+
) {
|
|
79
86
|
return false
|
|
80
87
|
}
|
|
81
88
|
}
|