@tanstack/hotkeys 0.8.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +15 -1
- package/dist/{manager.utils.js → _event-target.cjs} +5 -41
- package/dist/_event-target.cjs.map +1 -0
- package/dist/{manager.utils.cjs → _event-target.js} +3 -47
- package/dist/_event-target.js.map +1 -0
- package/dist/_keyboard-event.cjs +83 -0
- package/dist/_keyboard-event.cjs.map +1 -0
- package/dist/_keyboard-event.js +76 -0
- package/dist/_keyboard-event.js.map +1 -0
- package/dist/_match.cjs +49 -0
- package/dist/_match.cjs.map +1 -0
- package/dist/_match.js +49 -0
- package/dist/_match.js.map +1 -0
- package/dist/_named-keys.cjs +68 -0
- package/dist/_named-keys.cjs.map +1 -0
- package/dist/_named-keys.d.cts +8 -0
- package/dist/_named-keys.d.ts +8 -0
- package/dist/_named-keys.js +66 -0
- package/dist/_named-keys.js.map +1 -0
- package/dist/_recorder-chord.cjs +44 -0
- package/dist/_recorder-chord.cjs.map +1 -0
- package/dist/_recorder-chord.js +43 -0
- package/dist/_recorder-chord.js.map +1 -0
- package/dist/_recording-guard.cjs +59 -0
- package/dist/_recording-guard.cjs.map +1 -0
- package/dist/_recording-guard.js +56 -0
- package/dist/_recording-guard.js.map +1 -0
- package/dist/_registration.cjs +54 -0
- package/dist/_registration.cjs.map +1 -0
- package/dist/_registration.js +50 -0
- package/dist/_registration.js.map +1 -0
- package/dist/conflicts.cjs +55 -0
- package/dist/conflicts.cjs.map +1 -0
- package/dist/conflicts.d.cts +39 -0
- package/dist/conflicts.d.ts +39 -0
- package/dist/conflicts.js +55 -0
- package/dist/conflicts.js.map +1 -0
- package/dist/constants.cjs +46 -171
- package/dist/constants.cjs.map +1 -1
- package/dist/constants.d.cts +4 -129
- package/dist/constants.d.ts +4 -129
- package/dist/constants.js +48 -164
- package/dist/constants.js.map +1 -1
- package/dist/display-labels.cjs +119 -0
- package/dist/display-labels.cjs.map +1 -0
- package/dist/display-labels.d.cts +93 -0
- package/dist/display-labels.d.ts +93 -0
- package/dist/display-labels.js +113 -0
- package/dist/display-labels.js.map +1 -0
- package/dist/format.cjs +30 -36
- package/dist/format.cjs.map +1 -1
- package/dist/format.d.cts +46 -7
- package/dist/format.d.ts +46 -7
- package/dist/format.js +31 -37
- package/dist/format.js.map +1 -1
- package/dist/hint.cjs +24 -0
- package/dist/hint.cjs.map +1 -0
- package/dist/hint.d.cts +23 -0
- package/dist/hint.d.ts +23 -0
- package/dist/hint.js +24 -0
- package/dist/hint.js.map +1 -0
- package/dist/hotkey-manager.cjs +53 -22
- package/dist/hotkey-manager.cjs.map +1 -1
- package/dist/hotkey-manager.d.cts +6 -2
- package/dist/hotkey-manager.d.ts +6 -2
- package/dist/hotkey-manager.js +49 -18
- package/dist/hotkey-manager.js.map +1 -1
- package/dist/hotkey-recorder.cjs +66 -10
- package/dist/hotkey-recorder.cjs.map +1 -1
- package/dist/hotkey-recorder.d.cts +5 -2
- package/dist/hotkey-recorder.d.ts +5 -2
- package/dist/hotkey-recorder.js +65 -9
- package/dist/hotkey-recorder.js.map +1 -1
- package/dist/hotkey-sequence-recorder.cjs +85 -22
- package/dist/hotkey-sequence-recorder.cjs.map +1 -1
- package/dist/hotkey-sequence-recorder.d.cts +9 -2
- package/dist/hotkey-sequence-recorder.d.ts +9 -2
- package/dist/hotkey-sequence-recorder.js +84 -21
- package/dist/hotkey-sequence-recorder.js.map +1 -1
- package/dist/{hotkey.d.ts → hotkey.types.d.cts} +55 -120
- package/dist/{hotkey.d.cts → hotkey.types.d.ts} +55 -120
- package/dist/index.cjs +18 -10
- package/dist/index.d.cts +14 -9
- package/dist/index.d.ts +14 -9
- package/dist/index.js +10 -6
- package/dist/key-state-tracker.cjs +24 -24
- package/dist/key-state-tracker.cjs.map +1 -1
- package/dist/key-state-tracker.js +24 -24
- package/dist/key-state-tracker.js.map +1 -1
- package/dist/key.types.d.cts +82 -0
- package/dist/key.types.d.ts +82 -0
- package/dist/match.cjs +21 -30
- package/dist/match.cjs.map +1 -1
- package/dist/match.d.cts +19 -3
- package/dist/match.d.ts +19 -3
- package/dist/match.js +19 -29
- package/dist/match.js.map +1 -1
- package/dist/parse.cjs +43 -26
- package/dist/parse.cjs.map +1 -1
- package/dist/parse.d.cts +10 -4
- package/dist/parse.d.ts +10 -4
- package/dist/parse.js +35 -19
- package/dist/parse.js.map +1 -1
- package/dist/platform.cjs +55 -0
- package/dist/platform.cjs.map +1 -0
- package/dist/platform.d.cts +44 -0
- package/dist/platform.d.ts +44 -0
- package/dist/platform.js +53 -0
- package/dist/platform.js.map +1 -0
- package/dist/recorder-options.d.cts +34 -0
- package/dist/recorder-options.d.ts +34 -0
- package/dist/sequence-manager.cjs +54 -28
- package/dist/sequence-manager.cjs.map +1 -1
- package/dist/sequence-manager.d.cts +18 -3
- package/dist/sequence-manager.d.ts +18 -3
- package/dist/sequence-manager.js +49 -23
- package/dist/sequence-manager.js.map +1 -1
- package/dist/validate.cjs +6 -10
- package/dist/validate.cjs.map +1 -1
- package/dist/validate.d.cts +13 -2
- package/dist/validate.d.ts +13 -2
- package/dist/validate.js +7 -11
- package/dist/validate.js.map +1 -1
- package/package.json +1 -1
- package/src/{manager.utils.ts → _event-target.ts} +0 -74
- package/src/_keyboard-event.ts +101 -0
- package/src/_match.ts +96 -0
- package/src/_named-keys.ts +62 -0
- package/src/_recorder-chord.ts +76 -0
- package/src/_recording-guard.ts +63 -0
- package/src/_registration.ts +79 -0
- package/src/conflicts.ts +125 -0
- package/src/constants.ts +48 -196
- package/src/display-labels.ts +123 -0
- package/src/format.ts +111 -52
- package/src/hint.ts +42 -0
- package/src/hotkey-manager.ts +95 -40
- package/src/hotkey-recorder.ts +91 -15
- package/src/hotkey-sequence-recorder.ts +110 -28
- package/src/{hotkey.ts → hotkey.types.ts} +57 -224
- package/src/index.ts +11 -5
- package/src/key-state-tracker.ts +36 -24
- package/src/key.types.ts +268 -0
- package/src/match.ts +41 -90
- package/src/parse.ts +67 -26
- package/src/platform.ts +66 -0
- package/src/recorder-options.ts +34 -0
- package/src/sequence-manager.ts +77 -42
- package/src/validate.ts +29 -21
- package/dist/manager.utils.cjs.map +0 -1
- package/dist/manager.utils.d.cts +0 -13
- package/dist/manager.utils.d.ts +0 -13
- package/dist/manager.utils.js.map +0 -1
- package/dist/recorder-chord.cjs +0 -18
- package/dist/recorder-chord.cjs.map +0 -1
- package/dist/recorder-chord.js +0 -18
- package/dist/recorder-chord.js.map +0 -1
- package/src/recorder-chord.ts +0 -25
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { LOGICAL_ONLY_NAMED_KEYS, SHARED_NAMED_KEYS } from "./_named-keys.js";
|
|
2
|
+
|
|
3
|
+
//#region src/key.types.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* All supported modifier key names, including aliases.
|
|
6
|
+
* - Control/Ctrl: The Control key
|
|
7
|
+
* - Shift: The Shift key
|
|
8
|
+
* - Alt/Option: The Alt key (Option on macOS)
|
|
9
|
+
* - Command/Cmd: The Command key (macOS only)
|
|
10
|
+
* - CommandOrControl/Mod: Command on macOS, Control on other platforms
|
|
11
|
+
*/
|
|
12
|
+
type Modifier = 'Control' | 'Ctrl' | 'Shift' | 'Alt' | 'Option' | 'Command' | 'Cmd' | 'CommandOrControl' | 'Mod';
|
|
13
|
+
/**
|
|
14
|
+
* Canonical modifier names that map to KeyboardEvent properties.
|
|
15
|
+
*/
|
|
16
|
+
type CanonicalModifier = 'Control' | 'Shift' | 'Alt' | 'Meta';
|
|
17
|
+
/**
|
|
18
|
+
* Letter keys A-Z (case-insensitive in matching).
|
|
19
|
+
*/
|
|
20
|
+
type LetterKey = 'A' | 'B' | 'C' | 'D' | 'E' | 'F' | 'G' | 'H' | 'I' | 'J' | 'K' | 'L' | 'M' | 'N' | 'O' | 'P' | 'Q' | 'R' | 'S' | 'T' | 'U' | 'V' | 'W' | 'X' | 'Y' | 'Z';
|
|
21
|
+
/**
|
|
22
|
+
* Number keys 0-9.
|
|
23
|
+
*/
|
|
24
|
+
type NumberKey = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9';
|
|
25
|
+
/**
|
|
26
|
+
* Function keys F1-F24, supported as both logical keys and physical codes.
|
|
27
|
+
*/
|
|
28
|
+
type FunctionKey = 'F1' | 'F2' | 'F3' | 'F4' | 'F5' | 'F6' | 'F7' | 'F8' | 'F9' | 'F10' | 'F11' | 'F12' | 'F13' | 'F14' | 'F15' | 'F16' | 'F17' | 'F18' | 'F19' | 'F20' | 'F21' | 'F22' | 'F23' | 'F24';
|
|
29
|
+
/**
|
|
30
|
+
* Navigation keys for cursor movement.
|
|
31
|
+
*/
|
|
32
|
+
type NavigationKey = 'ArrowUp' | 'ArrowDown' | 'ArrowLeft' | 'ArrowRight' | 'Home' | 'End' | 'PageUp' | 'PageDown';
|
|
33
|
+
/**
|
|
34
|
+
* Editing and special keys.
|
|
35
|
+
*/
|
|
36
|
+
type EditingKey = 'Enter' | 'Escape' | 'Space' | 'Tab' | 'Backspace' | 'Delete';
|
|
37
|
+
/**
|
|
38
|
+
* Printable punctuation glyphs used in keyboard shortcuts. Matching uses the
|
|
39
|
+
* final KeyboardEvent.key glyph, independent of which layout produced it.
|
|
40
|
+
*/
|
|
41
|
+
type PunctuationKey = '/' | '[' | ']' | '\\' | '=' | '-' | ',' | '.' | ';' | '`' | "'" | '+' | '?' | '!' | '@' | '#' | '$' | '%' | '^' | '&' | '*' | '(' | ')' | '_' | '{' | '}' | '|' | ':' | '"' | '<' | '>' | '~';
|
|
42
|
+
/** Additional named logical keys, including media, browser, lock, and input-mode keys. */
|
|
43
|
+
type NamedKey = (typeof SHARED_NAMED_KEYS)[number] | (typeof LOGICAL_ONLY_NAMED_KEYS)[number];
|
|
44
|
+
/** Supported logical key names other than printable punctuation. */
|
|
45
|
+
type NonPunctuationKey = LetterKey | NumberKey | EditingKey | NavigationKey | FunctionKey | NamedKey;
|
|
46
|
+
/**
|
|
47
|
+
* Supported physical KeyboardEvent.code names, independent of keyboard layout.
|
|
48
|
+
* Letter, digit, numpad, and sided modifier names use finite template unions.
|
|
49
|
+
* `Unidentified` is excluded because it cannot identify a physical key.
|
|
50
|
+
*
|
|
51
|
+
* @see https://www.w3.org/TR/uievents-code/
|
|
52
|
+
*/
|
|
53
|
+
type PhysicalKeyCode = `Key${LetterKey}` | `Digit${NumberKey}` | `Numpad${NumberKey}` | `${'Alt' | 'Control' | 'Meta' | 'Shift'}${'Left' | 'Right'}` | EditingKey | NavigationKey | FunctionKey | (typeof SHARED_NAMED_KEYS)[number] | 'Backquote' | 'Backslash' | 'BracketLeft' | 'BracketRight' | 'Comma' | 'Equal' | 'IntlBackslash' | 'IntlRo' | 'IntlYen' | 'Minus' | 'Period' | 'Quote' | 'Semicolon' | 'Slash' | `Lang${1 | 2 | 3 | 4 | 5}` | `Numpad${'Add' | 'Backspace' | 'Clear' | 'ClearEntry' | 'Comma' | 'Decimal' | 'Divide' | 'Enter' | 'Equal' | 'Hash' | 'MemoryAdd' | 'MemoryClear' | 'MemoryRecall' | 'MemoryStore' | 'MemorySubtract' | 'Multiply' | 'ParenLeft' | 'ParenRight' | 'Star' | 'Subtract'}` | 'LaunchApp1' | 'LaunchApp2' | 'MediaSelect' | 'Sleep' | 'Turbo' | 'Abort' | 'Resume' | 'Suspend';
|
|
54
|
+
/**
|
|
55
|
+
* An explicit physical key token. All codes use brackets, including names such
|
|
56
|
+
* as `[Enter]` that also exist as logical keys. Invalid code names are rejected
|
|
57
|
+
* by TypeScript, and supported names are available in autocomplete.
|
|
58
|
+
*/
|
|
59
|
+
type PhysicalKey = `[${PhysicalKeyCode}]`;
|
|
60
|
+
/** Supported logical key names, excluding bracketed physical-code syntax. */
|
|
61
|
+
type LogicalKey = NonPunctuationKey | PunctuationKey;
|
|
62
|
+
/** All supported logical keys and bracketed physical key tokens. */
|
|
63
|
+
type Key = LogicalKey | PhysicalKey;
|
|
64
|
+
/**
|
|
65
|
+
* Includes both modifier keys and regular keys.
|
|
66
|
+
*/
|
|
67
|
+
type IndividualKey = CanonicalModifier | Key;
|
|
68
|
+
/** Keyboard event properties normalized for internal matching and recording. */
|
|
69
|
+
interface NormalizedKeyboardEvent {
|
|
70
|
+
key: string;
|
|
71
|
+
code: string;
|
|
72
|
+
ctrl: boolean;
|
|
73
|
+
shift: boolean;
|
|
74
|
+
alt: boolean;
|
|
75
|
+
meta: boolean;
|
|
76
|
+
altGraph: boolean;
|
|
77
|
+
location: number;
|
|
78
|
+
isComposing: boolean;
|
|
79
|
+
}
|
|
80
|
+
//#endregion
|
|
81
|
+
export { CanonicalModifier, EditingKey, FunctionKey, IndividualKey, Key, LetterKey, LogicalKey, Modifier, NamedKey, NavigationKey, NonPunctuationKey, NormalizedKeyboardEvent, NumberKey, PhysicalKey, PhysicalKeyCode, PunctuationKey };
|
|
82
|
+
//# sourceMappingURL=key.types.d.ts.map
|
package/dist/match.cjs
CHANGED
|
@@ -1,11 +1,14 @@
|
|
|
1
|
-
const
|
|
1
|
+
const require_platform = require('./platform.cjs');
|
|
2
|
+
const require__keyboard_event = require('./_keyboard-event.cjs');
|
|
2
3
|
const require_parse = require('./parse.cjs');
|
|
4
|
+
const require__match = require('./_match.cjs');
|
|
3
5
|
|
|
4
6
|
//#region src/match.ts
|
|
5
7
|
/**
|
|
6
8
|
* Checks if a KeyboardEvent matches a hotkey.
|
|
7
9
|
*
|
|
8
|
-
*
|
|
10
|
+
* Physical bindings such as `Mod+[KeyS]` match `event.code` exactly.
|
|
11
|
+
* Logical bindings use `event.key`, with a fallback to `code`
|
|
9
12
|
* for letter keys, digit keys (0-9), and punctuation keys when `key` produces special
|
|
10
13
|
* characters (e.g., macOS Option+letter, Shift+number, or Option+punctuation).
|
|
11
14
|
* Letter keys are matched case-insensitively.
|
|
@@ -30,31 +33,8 @@ const require_parse = require('./parse.cjs');
|
|
|
30
33
|
* })
|
|
31
34
|
* ```
|
|
32
35
|
*/
|
|
33
|
-
function matchesKeyboardEvent(event, hotkey, platform =
|
|
34
|
-
|
|
35
|
-
if (event.ctrlKey !== parsed.ctrl) return false;
|
|
36
|
-
if (event.shiftKey !== parsed.shift) return false;
|
|
37
|
-
if (event.altKey !== parsed.alt) return false;
|
|
38
|
-
if (event.metaKey !== parsed.meta) return false;
|
|
39
|
-
const eventKey = require_constants.normalizeKeyName(event.key);
|
|
40
|
-
const hotkeyKey = parsed.key;
|
|
41
|
-
if (eventKey !== "Dead" && eventKey.length === 1 && hotkeyKey.length === 1) {
|
|
42
|
-
if (eventKey.toUpperCase() === hotkeyKey.toUpperCase()) return true;
|
|
43
|
-
if (require_constants.isSingleLetterKey(eventKey) && (/^[A-Za-z]$/.test(eventKey) || !event.altKey)) return false;
|
|
44
|
-
}
|
|
45
|
-
if (event.code && (eventKey === "Dead" || eventKey.length === 1 && hotkeyKey.length === 1)) {
|
|
46
|
-
if (event.code.startsWith("Key")) {
|
|
47
|
-
const codeLetter = event.code.slice(3);
|
|
48
|
-
if (codeLetter.length === 1 && /^[A-Za-z]$/.test(codeLetter)) return codeLetter.toUpperCase() === hotkeyKey.toUpperCase();
|
|
49
|
-
}
|
|
50
|
-
if (event.code.startsWith("Digit")) {
|
|
51
|
-
const codeDigit = event.code.slice(5);
|
|
52
|
-
if (codeDigit.length === 1 && /^[0-9]$/.test(codeDigit)) return codeDigit === hotkeyKey;
|
|
53
|
-
}
|
|
54
|
-
if (event.code in require_constants.PUNCTUATION_CODE_MAP) return require_constants.PUNCTUATION_CODE_MAP[event.code] === hotkeyKey;
|
|
55
|
-
return false;
|
|
56
|
-
}
|
|
57
|
-
return eventKey === hotkeyKey;
|
|
36
|
+
function matchesKeyboardEvent(event, hotkey, platform = require_platform.detectPlatform()) {
|
|
37
|
+
return require__match.matchKeyboardEvent(event, hotkey, platform).matched;
|
|
58
38
|
}
|
|
59
39
|
/**
|
|
60
40
|
* Creates a keyboard event handler that calls the callback when the hotkey matches.
|
|
@@ -76,7 +56,7 @@ function matchesKeyboardEvent(event, hotkey, platform = require_constants.detect
|
|
|
76
56
|
*/
|
|
77
57
|
function createHotkeyHandler(hotkey, callback, options = {}) {
|
|
78
58
|
const { preventDefault = true, stopPropagation = true, platform } = options;
|
|
79
|
-
const resolvedPlatform = platform ??
|
|
59
|
+
const resolvedPlatform = platform ?? require_platform.detectPlatform();
|
|
80
60
|
const hotkeyString = typeof hotkey === "string" ? hotkey : formatParsedHotkey(hotkey);
|
|
81
61
|
const parsed = typeof hotkey === "string" ? require_parse.parseHotkey(hotkey, resolvedPlatform) : hotkey;
|
|
82
62
|
const context = {
|
|
@@ -111,7 +91,7 @@ function createHotkeyHandler(hotkey, callback, options = {}) {
|
|
|
111
91
|
*/
|
|
112
92
|
function createMultiHotkeyHandler(handlers, options = {}) {
|
|
113
93
|
const { preventDefault = true, stopPropagation = true, platform } = options;
|
|
114
|
-
const resolvedPlatform = platform ??
|
|
94
|
+
const resolvedPlatform = platform ?? require_platform.detectPlatform();
|
|
115
95
|
const parsedHandlers = Object.entries(handlers).filter((entry) => Boolean(entry[1])).map(([hotkey, handler]) => {
|
|
116
96
|
const parsed = require_parse.parseHotkey(hotkey, resolvedPlatform);
|
|
117
97
|
return {
|
|
@@ -142,11 +122,22 @@ function formatParsedHotkey(parsed) {
|
|
|
142
122
|
if (parsed.alt) parts.push("Alt");
|
|
143
123
|
if (parsed.shift) parts.push("Shift");
|
|
144
124
|
if (parsed.meta) parts.push("Meta");
|
|
145
|
-
parts.push(parsed.key);
|
|
125
|
+
parts.push(parsed.code !== void 0 ? `[${parsed.code}]` : parsed.key);
|
|
146
126
|
return parts.join("+");
|
|
147
127
|
}
|
|
128
|
+
/**
|
|
129
|
+
* Compares normalized binding identity, including all four modifiers.
|
|
130
|
+
* Aliases resolve on the supplied platform. A physical code and a logical key
|
|
131
|
+
* remain distinct even when one keyboard event could match both.
|
|
132
|
+
*/
|
|
133
|
+
function areHotkeysEqual(left, right, platform = require_platform.detectPlatform()) {
|
|
134
|
+
const a = require_parse.parseRegisterableHotkey(left, platform);
|
|
135
|
+
const b = require_parse.parseRegisterableHotkey(right, platform);
|
|
136
|
+
return a.ctrl === b.ctrl && a.alt === b.alt && a.shift === b.shift && a.meta === b.meta && (a.code !== void 0 || b.code !== void 0 ? a.code === b.code : require__keyboard_event.keysEqual(a.key, b.key));
|
|
137
|
+
}
|
|
148
138
|
|
|
149
139
|
//#endregion
|
|
140
|
+
exports.areHotkeysEqual = areHotkeysEqual;
|
|
150
141
|
exports.createHotkeyHandler = createHotkeyHandler;
|
|
151
142
|
exports.createMultiHotkeyHandler = createMultiHotkeyHandler;
|
|
152
143
|
exports.matchesKeyboardEvent = matchesKeyboardEvent;
|
package/dist/match.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"match.cjs","names":["detectPlatform","parseHotkey","normalizeKeyName","isSingleLetterKey","PUNCTUATION_CODE_MAP"],"sources":["../src/match.ts"],"sourcesContent":["import {\n PUNCTUATION_CODE_MAP,\n detectPlatform,\n isSingleLetterKey,\n normalizeKeyName,\n} from './constants'\nimport { parseHotkey } from './parse'\nimport type {\n Hotkey,\n HotkeyCallback,\n HotkeyCallbackContext,\n ParsedHotkey,\n} from './hotkey'\n\n/**\n * Checks if a KeyboardEvent matches a hotkey.\n *\n * Uses the `key` property from KeyboardEvent for matching, with a fallback to `code`\n * for letter keys, digit keys (0-9), and punctuation keys when `key` produces special\n * characters (e.g., macOS Option+letter, Shift+number, or Option+punctuation).\n * Letter keys are matched case-insensitively.\n *\n * Also handles \"dead key\" events where `event.key` is `'Dead'` instead of the expected\n * character. This commonly occurs on macOS with Option+letter combinations (e.g., Option+E,\n * Option+I, Option+U, Option+N) and on Windows/Linux with international keyboard layouts.\n * In these cases, `event.code` is used to determine the physical key.\n *\n * @param event - The KeyboardEvent to check\n * @param hotkey - The hotkey string or ParsedHotkey to match against\n * @param platform - The target platform for resolving 'Mod' (defaults to auto-detection)\n * @returns True if the event matches the hotkey\n *\n * @example\n * ```ts\n * document.addEventListener('keydown', (event) => {\n * if (matchesKeyboardEvent(event, 'Mod+S')) {\n * event.preventDefault()\n * handleSave()\n * }\n * })\n * ```\n */\nexport function matchesKeyboardEvent(\n event: KeyboardEvent,\n hotkey: Hotkey | ParsedHotkey,\n platform: 'mac' | 'windows' | 'linux' = detectPlatform(),\n): boolean {\n const parsed =\n typeof hotkey === 'string' ? parseHotkey(hotkey, platform) : hotkey\n\n // Check modifiers\n if (event.ctrlKey !== parsed.ctrl) {\n return false\n }\n if (event.shiftKey !== parsed.shift) {\n return false\n }\n if (event.altKey !== parsed.alt) {\n return false\n }\n if (event.metaKey !== parsed.meta) {\n return false\n }\n\n // Check key (case-insensitive for letters)\n const eventKey = normalizeKeyName(event.key)\n const hotkeyKey = parsed.key\n\n // For single-character keys (not dead keys), try direct event.key match first\n if (eventKey !== 'Dead' && eventKey.length === 1 && hotkeyKey.length === 1) {\n if (eventKey.toUpperCase() === hotkeyKey.toUpperCase()) {\n return true\n }\n\n // If event.key is a letter, we usually trust the keyboard layout.\n // For ASCII letters: always trust layout (Dvorak, Colemak, AZERTY support).\n // For non-ASCII letters without Alt: trust layout (e.g., Cyrillic keyboards).\n //\n // For non-ASCII letters WITH Alt held down: fall through to the event.code\n // fallback. macOS Option+letter combinations produce non-ASCII letters as\n // event.key (e.g., Option+A → 'å', Option+' → 'æ', Option+P → 'π'), but\n // event.code still reflects the physical key. We want Alt+A to match even\n // when Option+A fires event.key='å'.\n if (\n isSingleLetterKey(eventKey) &&\n (/^[A-Za-z]$/.test(eventKey) || !event.altKey)\n ) {\n return false\n }\n }\n\n // Fallback to event.code for dead keys or single-char mismatches where\n // event.key is a non-letter special character.\n // Dead keys: Option+letter on macOS, international layouts produce event.key === 'Dead'\n // Single-char mismatches: Cmd+Option+T gives '†' instead of 'T', Shift+4 gives '$'\n if (\n event.code &&\n (eventKey === 'Dead' || (eventKey.length === 1 && hotkeyKey.length === 1))\n ) {\n // fallback for letter keys (common with mac option + letter)\n if (event.code.startsWith('Key')) {\n const codeLetter = event.code.slice(3)\n if (codeLetter.length === 1 && /^[A-Za-z]$/.test(codeLetter)) {\n return codeLetter.toUpperCase() === hotkeyKey.toUpperCase()\n }\n }\n\n // fallback for number keys (common with mac option + num)\n if (event.code.startsWith('Digit')) {\n const codeDigit = event.code.slice(5)\n if (codeDigit.length === 1 && /^[0-9]$/.test(codeDigit)) {\n return codeDigit === hotkeyKey\n }\n }\n // Fallback for punctuation keys (e.g., Minus, Slash, BracketLeft).\n // On macOS, Option+punctuation produces composed characters (e.g., Option+- → '–'),\n // but event.code still reports the physical key.\n if (event.code in PUNCTUATION_CODE_MAP) {\n return PUNCTUATION_CODE_MAP[event.code] === hotkeyKey\n }\n\n return false\n }\n\n // For special keys, compare exactly (after normalization)\n return eventKey === hotkeyKey\n}\n\n/**\n * Options for creating a hotkey handler.\n */\nexport interface CreateHotkeyHandlerOptions {\n /** Prevent the default browser action when the hotkey matches. Defaults to true */\n preventDefault?: boolean\n /** Stop event propagation when the hotkey matches. Defaults to true */\n stopPropagation?: boolean\n /** The target platform for resolving 'Mod' */\n platform?: 'mac' | 'windows' | 'linux'\n}\n\n/**\n * Creates a keyboard event handler that calls the callback when the hotkey matches.\n *\n * @param hotkey - The hotkey string or ParsedHotkey to match\n * @param callback - The function to call when the hotkey matches\n * @param options - Options for matching and handling\n * @returns A function that can be used as an event handler\n *\n * @example\n * ```ts\n * const handler = createHotkeyHandler('Mod+S', (event, { hotkey, parsedHotkey }) => {\n * console.log(`${hotkey} was pressed`)\n * handleSave()\n * })\n *\n * document.addEventListener('keydown', handler)\n * ```\n */\nexport function createHotkeyHandler(\n hotkey: Hotkey | ParsedHotkey,\n callback: HotkeyCallback,\n options: CreateHotkeyHandlerOptions = {},\n): (event: KeyboardEvent) => void {\n const { preventDefault = true, stopPropagation = true, platform } = options\n const resolvedPlatform = platform ?? detectPlatform()\n\n const hotkeyString: Hotkey =\n typeof hotkey === 'string' ? hotkey : formatParsedHotkey(hotkey)\n const parsed =\n typeof hotkey === 'string' ? parseHotkey(hotkey, resolvedPlatform) : hotkey\n\n const context: HotkeyCallbackContext = {\n hotkey: hotkeyString,\n parsedHotkey: parsed,\n }\n\n return (event: KeyboardEvent) => {\n if (matchesKeyboardEvent(event, parsed, resolvedPlatform)) {\n if (preventDefault) {\n event.preventDefault()\n }\n if (stopPropagation) {\n event.stopPropagation()\n }\n callback(event, context)\n }\n }\n}\n\ntype MultiHotkeyHandler = { [K in Hotkey]?: HotkeyCallback }\n\n/**\n * Creates a handler that matches multiple hotkeys.\n *\n * @param handlers - A map of hotkey strings to their handlers\n * @param options - Options for matching and handling\n * @returns A function that can be used as an event handler\n *\n * @example\n * ```ts\n * const handler = createMultiHotkeyHandler({\n * 'Mod+S': (event, { hotkey }) => handleSave(),\n * 'Mod+Z': (event, { hotkey }) => handleUndo(),\n * 'Mod+Shift+Z': (event, { hotkey }) => handleRedo(),\n * })\n *\n * document.addEventListener('keydown', handler)\n * ```\n */\nexport function createMultiHotkeyHandler(\n handlers: MultiHotkeyHandler,\n options: CreateHotkeyHandlerOptions = {},\n): (event: KeyboardEvent) => void {\n const { preventDefault = true, stopPropagation = true, platform } = options\n const resolvedPlatform = platform ?? detectPlatform()\n\n // Pre-parse all hotkeys for efficiency\n const parsedHandlers = Object.entries(handlers)\n .filter((entry): entry is [string, HotkeyCallback] => Boolean(entry[1]))\n .map(([hotkey, handler]) => {\n const parsed = parseHotkey(hotkey as Hotkey, resolvedPlatform)\n const context: HotkeyCallbackContext = {\n hotkey: hotkey as Hotkey,\n parsedHotkey: parsed,\n }\n return { parsed, handler, context }\n })\n\n return (event: KeyboardEvent) => {\n for (const { parsed, handler, context } of parsedHandlers) {\n if (matchesKeyboardEvent(event, parsed, resolvedPlatform)) {\n if (preventDefault) {\n event.preventDefault()\n }\n if (stopPropagation) {\n event.stopPropagation()\n }\n handler(event, context)\n return // Only handle the first match\n }\n }\n }\n}\n\n/**\n * Formats a ParsedHotkey back to a hotkey string.\n * Used internally to provide the hotkey string in callback context.\n */\nfunction formatParsedHotkey(parsed: ParsedHotkey): Hotkey {\n const parts: Array<string> = []\n\n if (parsed.ctrl) parts.push('Control')\n if (parsed.alt) parts.push('Alt')\n if (parsed.shift) parts.push('Shift')\n if (parsed.meta) parts.push('Meta')\n parts.push(parsed.key)\n\n return parts.join('+') as Hotkey\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0CA,SAAgB,qBACd,OACA,QACA,WAAwCA,kCAAgB,EAC/C;CACT,MAAM,SACJ,OAAO,WAAW,WAAWC,0BAAY,QAAQ,SAAS,GAAG;AAG/D,KAAI,MAAM,YAAY,OAAO,KAC3B,QAAO;AAET,KAAI,MAAM,aAAa,OAAO,MAC5B,QAAO;AAET,KAAI,MAAM,WAAW,OAAO,IAC1B,QAAO;AAET,KAAI,MAAM,YAAY,OAAO,KAC3B,QAAO;CAIT,MAAM,WAAWC,mCAAiB,MAAM,IAAI;CAC5C,MAAM,YAAY,OAAO;AAGzB,KAAI,aAAa,UAAU,SAAS,WAAW,KAAK,UAAU,WAAW,GAAG;AAC1E,MAAI,SAAS,aAAa,KAAK,UAAU,aAAa,CACpD,QAAO;AAYT,MACEC,oCAAkB,SAAS,KAC1B,aAAa,KAAK,SAAS,IAAI,CAAC,MAAM,QAEvC,QAAO;;AAQX,KACE,MAAM,SACL,aAAa,UAAW,SAAS,WAAW,KAAK,UAAU,WAAW,IACvE;AAEA,MAAI,MAAM,KAAK,WAAW,MAAM,EAAE;GAChC,MAAM,aAAa,MAAM,KAAK,MAAM,EAAE;AACtC,OAAI,WAAW,WAAW,KAAK,aAAa,KAAK,WAAW,CAC1D,QAAO,WAAW,aAAa,KAAK,UAAU,aAAa;;AAK/D,MAAI,MAAM,KAAK,WAAW,QAAQ,EAAE;GAClC,MAAM,YAAY,MAAM,KAAK,MAAM,EAAE;AACrC,OAAI,UAAU,WAAW,KAAK,UAAU,KAAK,UAAU,CACrD,QAAO,cAAc;;AAMzB,MAAI,MAAM,QAAQC,uCAChB,QAAOA,uCAAqB,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AM,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","matchKeyboardEvent","parseHotkey","parseRegisterableHotkey","keysEqual"],"sources":["../src/match.ts"],"sourcesContent":["import { matchKeyboardEvent } from './_match'\nimport { parseHotkey, parseRegisterableHotkey } from './parse'\nimport { detectPlatform } from './platform'\nimport { keysEqual } from './_keyboard-event'\nimport type {\n Hotkey,\n HotkeyCallback,\n HotkeyCallbackContext,\n ParsedHotkey,\n RegisterableHotkey,\n} from './hotkey.types'\n\nexport interface KeyboardEventMatch {\n matched: boolean\n score: 0 | 1 | 2 | 3\n source?: 'key' | 'code' | 'fallback'\n identity?: { key: string; code: string }\n}\n\n/**\n * Checks if a KeyboardEvent matches a hotkey.\n *\n * Physical bindings such as `Mod+[KeyS]` match `event.code` exactly.\n * Logical bindings use `event.key`, with a fallback to `code`\n * for letter keys, digit keys (0-9), and punctuation keys when `key` produces special\n * characters (e.g., macOS Option+letter, Shift+number, or Option+punctuation).\n * Letter keys are matched case-insensitively.\n *\n * Also handles \"dead key\" events where `event.key` is `'Dead'` instead of the expected\n * character. This commonly occurs on macOS with Option+letter combinations (e.g., Option+E,\n * Option+I, Option+U, Option+N) and on Windows/Linux with international keyboard layouts.\n * In these cases, `event.code` is used to determine the physical key.\n *\n * @param event - The KeyboardEvent to check\n * @param hotkey - The hotkey string or ParsedHotkey to match against\n * @param platform - The target platform for resolving 'Mod' (defaults to auto-detection)\n * @returns True if the event matches the hotkey\n *\n * @example\n * ```ts\n * document.addEventListener('keydown', (event) => {\n * if (matchesKeyboardEvent(event, 'Mod+S')) {\n * event.preventDefault()\n * handleSave()\n * }\n * })\n * ```\n */\nexport function matchesKeyboardEvent(\n event: KeyboardEvent,\n hotkey: Hotkey | ParsedHotkey,\n platform: 'mac' | 'windows' | 'linux' = detectPlatform(),\n): boolean {\n return matchKeyboardEvent(event, hotkey, platform).matched\n}\n\n/**\n * Options for creating a hotkey handler.\n */\nexport interface CreateHotkeyHandlerOptions {\n /** Prevent the default browser action when the hotkey matches. Defaults to true */\n preventDefault?: boolean\n /** Stop event propagation when the hotkey matches. Defaults to true */\n stopPropagation?: boolean\n /** The target platform for resolving 'Mod' */\n platform?: 'mac' | 'windows' | 'linux'\n}\n\n/**\n * Creates a keyboard event handler that calls the callback when the hotkey matches.\n *\n * @param hotkey - The hotkey string or ParsedHotkey to match\n * @param callback - The function to call when the hotkey matches\n * @param options - Options for matching and handling\n * @returns A function that can be used as an event handler\n *\n * @example\n * ```ts\n * const handler = createHotkeyHandler('Mod+S', (event, { hotkey, parsedHotkey }) => {\n * console.log(`${hotkey} was pressed`)\n * handleSave()\n * })\n *\n * document.addEventListener('keydown', handler)\n * ```\n */\nexport function createHotkeyHandler(\n hotkey: Hotkey | ParsedHotkey,\n callback: HotkeyCallback,\n options: CreateHotkeyHandlerOptions = {},\n): (event: KeyboardEvent) => void {\n const { preventDefault = true, stopPropagation = true, platform } = options\n const resolvedPlatform = platform ?? detectPlatform()\n\n const hotkeyString: Hotkey =\n typeof hotkey === 'string' ? hotkey : formatParsedHotkey(hotkey)\n const parsed =\n typeof hotkey === 'string' ? parseHotkey(hotkey, resolvedPlatform) : hotkey\n\n const context: HotkeyCallbackContext = {\n hotkey: hotkeyString,\n parsedHotkey: parsed,\n }\n\n return (event: KeyboardEvent) => {\n if (matchesKeyboardEvent(event, parsed, resolvedPlatform)) {\n if (preventDefault) {\n event.preventDefault()\n }\n if (stopPropagation) {\n event.stopPropagation()\n }\n callback(event, context)\n }\n }\n}\n\nexport type MultiHotkeyHandler = { [K in Hotkey]?: HotkeyCallback }\n\n/**\n * Creates a handler that matches multiple hotkeys.\n *\n * @param handlers - A map of hotkey strings to their handlers\n * @param options - Options for matching and handling\n * @returns A function that can be used as an event handler\n *\n * @example\n * ```ts\n * const handler = createMultiHotkeyHandler({\n * 'Mod+S': (event, { hotkey }) => handleSave(),\n * 'Mod+Z': (event, { hotkey }) => handleUndo(),\n * 'Mod+Shift+Z': (event, { hotkey }) => handleRedo(),\n * })\n *\n * document.addEventListener('keydown', handler)\n * ```\n */\nexport function createMultiHotkeyHandler(\n handlers: MultiHotkeyHandler,\n options: CreateHotkeyHandlerOptions = {},\n): (event: KeyboardEvent) => void {\n const { preventDefault = true, stopPropagation = true, platform } = options\n const resolvedPlatform = platform ?? detectPlatform()\n\n // Pre-parse all hotkeys for efficiency\n const parsedHandlers = Object.entries(handlers)\n .filter((entry): entry is [string, HotkeyCallback] => Boolean(entry[1]))\n .map(([hotkey, handler]) => {\n const parsed = parseHotkey(hotkey as Hotkey, resolvedPlatform)\n const context: HotkeyCallbackContext = {\n hotkey: hotkey as Hotkey,\n parsedHotkey: parsed,\n }\n return { parsed, handler, context }\n })\n\n return (event: KeyboardEvent) => {\n for (const { parsed, handler, context } of parsedHandlers) {\n if (matchesKeyboardEvent(event, parsed, resolvedPlatform)) {\n if (preventDefault) {\n event.preventDefault()\n }\n if (stopPropagation) {\n event.stopPropagation()\n }\n handler(event, context)\n return // Only handle the first match\n }\n }\n }\n}\n\n/**\n * Formats a ParsedHotkey back to a hotkey string.\n * Used internally to provide the hotkey string in callback context.\n */\nfunction formatParsedHotkey(parsed: ParsedHotkey): Hotkey {\n const parts: Array<string> = []\n\n if (parsed.ctrl) parts.push('Control')\n if (parsed.alt) parts.push('Alt')\n if (parsed.shift) parts.push('Shift')\n if (parsed.meta) parts.push('Meta')\n parts.push(parsed.code !== undefined ? `[${parsed.code}]` : parsed.key)\n\n return parts.join('+') as Hotkey\n}\n\n/**\n * Compares normalized binding identity, including all four modifiers.\n * Aliases resolve on the supplied platform. A physical code and a logical key\n * remain distinct even when one keyboard event could match both.\n */\nexport function areHotkeysEqual(\n left: RegisterableHotkey,\n right: RegisterableHotkey,\n platform = detectPlatform(),\n): boolean {\n const a = parseRegisterableHotkey(left, platform)\n const b = parseRegisterableHotkey(right, platform)\n return (\n a.ctrl === b.ctrl &&\n a.alt === b.alt &&\n a.shift === b.shift &&\n a.meta === b.meta &&\n (a.code !== undefined || b.code !== undefined\n ? a.code === b.code\n : keysEqual(a.key, b.key))\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,SAAgB,qBACd,OACA,QACA,WAAwCA,iCAAgB,EAC/C;AACT,QAAOC,kCAAmB,OAAO,QAAQ,SAAS,CAAC;;;;;;;;;;;;;;;;;;;;AAiCrD,SAAgB,oBACd,QACA,UACA,UAAsC,EAAE,EACR;CAChC,MAAM,EAAE,iBAAiB,MAAM,kBAAkB,MAAM,aAAa;CACpE,MAAM,mBAAmB,YAAYD,iCAAgB;CAErD,MAAM,eACJ,OAAO,WAAW,WAAW,SAAS,mBAAmB,OAAO;CAClE,MAAM,SACJ,OAAO,WAAW,WAAWE,0BAAY,QAAQ,iBAAiB,GAAG;CAEvE,MAAM,UAAiC;EACrC,QAAQ;EACR,cAAc;EACf;AAED,SAAQ,UAAyB;AAC/B,MAAI,qBAAqB,OAAO,QAAQ,iBAAiB,EAAE;AACzD,OAAI,eACF,OAAM,gBAAgB;AAExB,OAAI,gBACF,OAAM,iBAAiB;AAEzB,YAAS,OAAO,QAAQ;;;;;;;;;;;;;;;;;;;;;;AAyB9B,SAAgB,yBACd,UACA,UAAsC,EAAE,EACR;CAChC,MAAM,EAAE,iBAAiB,MAAM,kBAAkB,MAAM,aAAa;CACpE,MAAM,mBAAmB,YAAYF,iCAAgB;CAGrD,MAAM,iBAAiB,OAAO,QAAQ,SAAS,CAC5C,QAAQ,UAA6C,QAAQ,MAAM,GAAG,CAAC,CACvE,KAAK,CAAC,QAAQ,aAAa;EAC1B,MAAM,SAASE,0BAAY,QAAkB,iBAAiB;AAK9D,SAAO;GAAE;GAAQ;GAAS,SAJa;IAC7B;IACR,cAAc;IACf;GACkC;GACnC;AAEJ,SAAQ,UAAyB;AAC/B,OAAK,MAAM,EAAE,QAAQ,SAAS,aAAa,eACzC,KAAI,qBAAqB,OAAO,QAAQ,iBAAiB,EAAE;AACzD,OAAI,eACF,OAAM,gBAAgB;AAExB,OAAI,gBACF,OAAM,iBAAiB;AAEzB,WAAQ,OAAO,QAAQ;AACvB;;;;;;;;AAUR,SAAS,mBAAmB,QAA8B;CACxD,MAAM,QAAuB,EAAE;AAE/B,KAAI,OAAO,KAAM,OAAM,KAAK,UAAU;AACtC,KAAI,OAAO,IAAK,OAAM,KAAK,MAAM;AACjC,KAAI,OAAO,MAAO,OAAM,KAAK,QAAQ;AACrC,KAAI,OAAO,KAAM,OAAM,KAAK,OAAO;AACnC,OAAM,KAAK,OAAO,SAAS,SAAY,IAAI,OAAO,KAAK,KAAK,OAAO,IAAI;AAEvE,QAAO,MAAM,KAAK,IAAI;;;;;;;AAQxB,SAAgB,gBACd,MACA,OACA,WAAWF,iCAAgB,EAClB;CACT,MAAM,IAAIG,sCAAwB,MAAM,SAAS;CACjD,MAAM,IAAIA,sCAAwB,OAAO,SAAS;AAClD,QACE,EAAE,SAAS,EAAE,QACb,EAAE,QAAQ,EAAE,OACZ,EAAE,UAAU,EAAE,SACd,EAAE,SAAS,EAAE,SACZ,EAAE,SAAS,UAAa,EAAE,SAAS,SAChC,EAAE,SAAS,EAAE,OACbC,kCAAU,EAAE,KAAK,EAAE,IAAI"}
|
package/dist/match.d.cts
CHANGED
|
@@ -1,10 +1,20 @@
|
|
|
1
|
-
import { Hotkey, HotkeyCallback, ParsedHotkey } from "./hotkey.cjs";
|
|
1
|
+
import { Hotkey, HotkeyCallback, ParsedHotkey, RegisterableHotkey } from "./hotkey.types.cjs";
|
|
2
2
|
|
|
3
3
|
//#region src/match.d.ts
|
|
4
|
+
interface KeyboardEventMatch {
|
|
5
|
+
matched: boolean;
|
|
6
|
+
score: 0 | 1 | 2 | 3;
|
|
7
|
+
source?: 'key' | 'code' | 'fallback';
|
|
8
|
+
identity?: {
|
|
9
|
+
key: string;
|
|
10
|
+
code: string;
|
|
11
|
+
};
|
|
12
|
+
}
|
|
4
13
|
/**
|
|
5
14
|
* Checks if a KeyboardEvent matches a hotkey.
|
|
6
15
|
*
|
|
7
|
-
*
|
|
16
|
+
* Physical bindings such as `Mod+[KeyS]` match `event.code` exactly.
|
|
17
|
+
* Logical bindings use `event.key`, with a fallback to `code`
|
|
8
18
|
* for letter keys, digit keys (0-9), and punctuation keys when `key` produces special
|
|
9
19
|
* characters (e.g., macOS Option+letter, Shift+number, or Option+punctuation).
|
|
10
20
|
* Letter keys are matched case-insensitively.
|
|
@@ -80,6 +90,12 @@ type MultiHotkeyHandler = { [K in Hotkey]?: HotkeyCallback };
|
|
|
80
90
|
* ```
|
|
81
91
|
*/
|
|
82
92
|
declare function createMultiHotkeyHandler(handlers: MultiHotkeyHandler, options?: CreateHotkeyHandlerOptions): (event: KeyboardEvent) => void;
|
|
93
|
+
/**
|
|
94
|
+
* Compares normalized binding identity, including all four modifiers.
|
|
95
|
+
* Aliases resolve on the supplied platform. A physical code and a logical key
|
|
96
|
+
* remain distinct even when one keyboard event could match both.
|
|
97
|
+
*/
|
|
98
|
+
declare function areHotkeysEqual(left: RegisterableHotkey, right: RegisterableHotkey, platform?: "mac" | "windows" | "linux"): boolean;
|
|
83
99
|
//#endregion
|
|
84
|
-
export { CreateHotkeyHandlerOptions, createHotkeyHandler, createMultiHotkeyHandler, matchesKeyboardEvent };
|
|
100
|
+
export { CreateHotkeyHandlerOptions, KeyboardEventMatch, MultiHotkeyHandler, areHotkeysEqual, createHotkeyHandler, createMultiHotkeyHandler, matchesKeyboardEvent };
|
|
85
101
|
//# sourceMappingURL=match.d.cts.map
|
package/dist/match.d.ts
CHANGED
|
@@ -1,10 +1,20 @@
|
|
|
1
|
-
import { Hotkey, HotkeyCallback, ParsedHotkey } from "./hotkey.js";
|
|
1
|
+
import { Hotkey, HotkeyCallback, ParsedHotkey, RegisterableHotkey } from "./hotkey.types.js";
|
|
2
2
|
|
|
3
3
|
//#region src/match.d.ts
|
|
4
|
+
interface KeyboardEventMatch {
|
|
5
|
+
matched: boolean;
|
|
6
|
+
score: 0 | 1 | 2 | 3;
|
|
7
|
+
source?: 'key' | 'code' | 'fallback';
|
|
8
|
+
identity?: {
|
|
9
|
+
key: string;
|
|
10
|
+
code: string;
|
|
11
|
+
};
|
|
12
|
+
}
|
|
4
13
|
/**
|
|
5
14
|
* Checks if a KeyboardEvent matches a hotkey.
|
|
6
15
|
*
|
|
7
|
-
*
|
|
16
|
+
* Physical bindings such as `Mod+[KeyS]` match `event.code` exactly.
|
|
17
|
+
* Logical bindings use `event.key`, with a fallback to `code`
|
|
8
18
|
* for letter keys, digit keys (0-9), and punctuation keys when `key` produces special
|
|
9
19
|
* characters (e.g., macOS Option+letter, Shift+number, or Option+punctuation).
|
|
10
20
|
* Letter keys are matched case-insensitively.
|
|
@@ -80,6 +90,12 @@ type MultiHotkeyHandler = { [K in Hotkey]?: HotkeyCallback };
|
|
|
80
90
|
* ```
|
|
81
91
|
*/
|
|
82
92
|
declare function createMultiHotkeyHandler(handlers: MultiHotkeyHandler, options?: CreateHotkeyHandlerOptions): (event: KeyboardEvent) => void;
|
|
93
|
+
/**
|
|
94
|
+
* Compares normalized binding identity, including all four modifiers.
|
|
95
|
+
* Aliases resolve on the supplied platform. A physical code and a logical key
|
|
96
|
+
* remain distinct even when one keyboard event could match both.
|
|
97
|
+
*/
|
|
98
|
+
declare function areHotkeysEqual(left: RegisterableHotkey, right: RegisterableHotkey, platform?: "mac" | "windows" | "linux"): boolean;
|
|
83
99
|
//#endregion
|
|
84
|
-
export { CreateHotkeyHandlerOptions, createHotkeyHandler, createMultiHotkeyHandler, matchesKeyboardEvent };
|
|
100
|
+
export { CreateHotkeyHandlerOptions, KeyboardEventMatch, MultiHotkeyHandler, areHotkeysEqual, createHotkeyHandler, createMultiHotkeyHandler, matchesKeyboardEvent };
|
|
85
101
|
//# sourceMappingURL=match.d.ts.map
|
package/dist/match.js
CHANGED
|
@@ -1,11 +1,14 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { detectPlatform } from "./platform.js";
|
|
2
|
+
import { keysEqual } from "./_keyboard-event.js";
|
|
3
|
+
import { parseHotkey, parseRegisterableHotkey } from "./parse.js";
|
|
4
|
+
import { matchKeyboardEvent } from "./_match.js";
|
|
3
5
|
|
|
4
6
|
//#region src/match.ts
|
|
5
7
|
/**
|
|
6
8
|
* Checks if a KeyboardEvent matches a hotkey.
|
|
7
9
|
*
|
|
8
|
-
*
|
|
10
|
+
* Physical bindings such as `Mod+[KeyS]` match `event.code` exactly.
|
|
11
|
+
* Logical bindings use `event.key`, with a fallback to `code`
|
|
9
12
|
* for letter keys, digit keys (0-9), and punctuation keys when `key` produces special
|
|
10
13
|
* characters (e.g., macOS Option+letter, Shift+number, or Option+punctuation).
|
|
11
14
|
* Letter keys are matched case-insensitively.
|
|
@@ -31,30 +34,7 @@ import { parseHotkey } from "./parse.js";
|
|
|
31
34
|
* ```
|
|
32
35
|
*/
|
|
33
36
|
function matchesKeyboardEvent(event, hotkey, platform = detectPlatform()) {
|
|
34
|
-
|
|
35
|
-
if (event.ctrlKey !== parsed.ctrl) return false;
|
|
36
|
-
if (event.shiftKey !== parsed.shift) return false;
|
|
37
|
-
if (event.altKey !== parsed.alt) return false;
|
|
38
|
-
if (event.metaKey !== parsed.meta) return false;
|
|
39
|
-
const eventKey = normalizeKeyName(event.key);
|
|
40
|
-
const hotkeyKey = parsed.key;
|
|
41
|
-
if (eventKey !== "Dead" && eventKey.length === 1 && hotkeyKey.length === 1) {
|
|
42
|
-
if (eventKey.toUpperCase() === hotkeyKey.toUpperCase()) return true;
|
|
43
|
-
if (isSingleLetterKey(eventKey) && (/^[A-Za-z]$/.test(eventKey) || !event.altKey)) return false;
|
|
44
|
-
}
|
|
45
|
-
if (event.code && (eventKey === "Dead" || eventKey.length === 1 && hotkeyKey.length === 1)) {
|
|
46
|
-
if (event.code.startsWith("Key")) {
|
|
47
|
-
const codeLetter = event.code.slice(3);
|
|
48
|
-
if (codeLetter.length === 1 && /^[A-Za-z]$/.test(codeLetter)) return codeLetter.toUpperCase() === hotkeyKey.toUpperCase();
|
|
49
|
-
}
|
|
50
|
-
if (event.code.startsWith("Digit")) {
|
|
51
|
-
const codeDigit = event.code.slice(5);
|
|
52
|
-
if (codeDigit.length === 1 && /^[0-9]$/.test(codeDigit)) return codeDigit === hotkeyKey;
|
|
53
|
-
}
|
|
54
|
-
if (event.code in PUNCTUATION_CODE_MAP) return PUNCTUATION_CODE_MAP[event.code] === hotkeyKey;
|
|
55
|
-
return false;
|
|
56
|
-
}
|
|
57
|
-
return eventKey === hotkeyKey;
|
|
37
|
+
return matchKeyboardEvent(event, hotkey, platform).matched;
|
|
58
38
|
}
|
|
59
39
|
/**
|
|
60
40
|
* Creates a keyboard event handler that calls the callback when the hotkey matches.
|
|
@@ -142,10 +122,20 @@ function formatParsedHotkey(parsed) {
|
|
|
142
122
|
if (parsed.alt) parts.push("Alt");
|
|
143
123
|
if (parsed.shift) parts.push("Shift");
|
|
144
124
|
if (parsed.meta) parts.push("Meta");
|
|
145
|
-
parts.push(parsed.key);
|
|
125
|
+
parts.push(parsed.code !== void 0 ? `[${parsed.code}]` : parsed.key);
|
|
146
126
|
return parts.join("+");
|
|
147
127
|
}
|
|
128
|
+
/**
|
|
129
|
+
* Compares normalized binding identity, including all four modifiers.
|
|
130
|
+
* Aliases resolve on the supplied platform. A physical code and a logical key
|
|
131
|
+
* remain distinct even when one keyboard event could match both.
|
|
132
|
+
*/
|
|
133
|
+
function areHotkeysEqual(left, right, platform = detectPlatform()) {
|
|
134
|
+
const a = parseRegisterableHotkey(left, platform);
|
|
135
|
+
const b = parseRegisterableHotkey(right, platform);
|
|
136
|
+
return a.ctrl === b.ctrl && a.alt === b.alt && a.shift === b.shift && a.meta === b.meta && (a.code !== void 0 || b.code !== void 0 ? a.code === b.code : keysEqual(a.key, b.key));
|
|
137
|
+
}
|
|
148
138
|
|
|
149
139
|
//#endregion
|
|
150
|
-
export { createHotkeyHandler, createMultiHotkeyHandler, matchesKeyboardEvent };
|
|
140
|
+
export { areHotkeysEqual, createHotkeyHandler, createMultiHotkeyHandler, matchesKeyboardEvent };
|
|
151
141
|
//# sourceMappingURL=match.js.map
|
package/dist/match.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"match.js","names":[],"sources":["../src/match.ts"],"sourcesContent":["import {\n PUNCTUATION_CODE_MAP,\n detectPlatform,\n isSingleLetterKey,\n normalizeKeyName,\n} from './constants'\nimport { parseHotkey } from './parse'\nimport type {\n Hotkey,\n HotkeyCallback,\n HotkeyCallbackContext,\n ParsedHotkey,\n} from './hotkey'\n\n/**\n * Checks if a KeyboardEvent matches a hotkey.\n *\n * Uses the `key` property from KeyboardEvent for matching, with a fallback to `code`\n * for letter keys, digit keys (0-9), and punctuation keys when `key` produces special\n * characters (e.g., macOS Option+letter, Shift+number, or Option+punctuation).\n * Letter keys are matched case-insensitively.\n *\n * Also handles \"dead key\" events where `event.key` is `'Dead'` instead of the expected\n * character. This commonly occurs on macOS with Option+letter combinations (e.g., Option+E,\n * Option+I, Option+U, Option+N) and on Windows/Linux with international keyboard layouts.\n * In these cases, `event.code` is used to determine the physical key.\n *\n * @param event - The KeyboardEvent to check\n * @param hotkey - The hotkey string or ParsedHotkey to match against\n * @param platform - The target platform for resolving 'Mod' (defaults to auto-detection)\n * @returns True if the event matches the hotkey\n *\n * @example\n * ```ts\n * document.addEventListener('keydown', (event) => {\n * if (matchesKeyboardEvent(event, 'Mod+S')) {\n * event.preventDefault()\n * handleSave()\n * }\n * })\n * ```\n */\nexport function matchesKeyboardEvent(\n event: KeyboardEvent,\n hotkey: Hotkey | ParsedHotkey,\n platform: 'mac' | 'windows' | 'linux' = detectPlatform(),\n): boolean {\n const parsed =\n typeof hotkey === 'string' ? parseHotkey(hotkey, platform) : hotkey\n\n // Check modifiers\n if (event.ctrlKey !== parsed.ctrl) {\n return false\n }\n if (event.shiftKey !== parsed.shift) {\n return false\n }\n if (event.altKey !== parsed.alt) {\n return false\n }\n if (event.metaKey !== parsed.meta) {\n return false\n }\n\n // Check key (case-insensitive for letters)\n const eventKey = normalizeKeyName(event.key)\n const hotkeyKey = parsed.key\n\n // For single-character keys (not dead keys), try direct event.key match first\n if (eventKey !== 'Dead' && eventKey.length === 1 && hotkeyKey.length === 1) {\n if (eventKey.toUpperCase() === hotkeyKey.toUpperCase()) {\n return true\n }\n\n // If event.key is a letter, we usually trust the keyboard layout.\n // For ASCII letters: always trust layout (Dvorak, Colemak, AZERTY support).\n // For non-ASCII letters without Alt: trust layout (e.g., Cyrillic keyboards).\n //\n // For non-ASCII letters WITH Alt held down: fall through to the event.code\n // fallback. macOS Option+letter combinations produce non-ASCII letters as\n // event.key (e.g., Option+A → 'å', Option+' → 'æ', Option+P → 'π'), but\n // event.code still reflects the physical key. We want Alt+A to match even\n // when Option+A fires event.key='å'.\n if (\n isSingleLetterKey(eventKey) &&\n (/^[A-Za-z]$/.test(eventKey) || !event.altKey)\n ) {\n return false\n }\n }\n\n // Fallback to event.code for dead keys or single-char mismatches where\n // event.key is a non-letter special character.\n // Dead keys: Option+letter on macOS, international layouts produce event.key === 'Dead'\n // Single-char mismatches: Cmd+Option+T gives '†' instead of 'T', Shift+4 gives '$'\n if (\n event.code &&\n (eventKey === 'Dead' || (eventKey.length === 1 && hotkeyKey.length === 1))\n ) {\n // fallback for letter keys (common with mac option + letter)\n if (event.code.startsWith('Key')) {\n const codeLetter = event.code.slice(3)\n if (codeLetter.length === 1 && /^[A-Za-z]$/.test(codeLetter)) {\n return codeLetter.toUpperCase() === hotkeyKey.toUpperCase()\n }\n }\n\n // fallback for number keys (common with mac option + num)\n if (event.code.startsWith('Digit')) {\n const codeDigit = event.code.slice(5)\n if (codeDigit.length === 1 && /^[0-9]$/.test(codeDigit)) {\n return codeDigit === hotkeyKey\n }\n }\n // Fallback for punctuation keys (e.g., Minus, Slash, BracketLeft).\n // On macOS, Option+punctuation produces composed characters (e.g., Option+- → '–'),\n // but event.code still reports the physical key.\n if (event.code in PUNCTUATION_CODE_MAP) {\n return PUNCTUATION_CODE_MAP[event.code] === hotkeyKey\n }\n\n return false\n }\n\n // For special keys, compare exactly (after normalization)\n return eventKey === hotkeyKey\n}\n\n/**\n * Options for creating a hotkey handler.\n */\nexport interface CreateHotkeyHandlerOptions {\n /** Prevent the default browser action when the hotkey matches. Defaults to true */\n preventDefault?: boolean\n /** Stop event propagation when the hotkey matches. Defaults to true */\n stopPropagation?: boolean\n /** The target platform for resolving 'Mod' */\n platform?: 'mac' | 'windows' | 'linux'\n}\n\n/**\n * Creates a keyboard event handler that calls the callback when the hotkey matches.\n *\n * @param hotkey - The hotkey string or ParsedHotkey to match\n * @param callback - The function to call when the hotkey matches\n * @param options - Options for matching and handling\n * @returns A function that can be used as an event handler\n *\n * @example\n * ```ts\n * const handler = createHotkeyHandler('Mod+S', (event, { hotkey, parsedHotkey }) => {\n * console.log(`${hotkey} was pressed`)\n * handleSave()\n * })\n *\n * document.addEventListener('keydown', handler)\n * ```\n */\nexport function createHotkeyHandler(\n hotkey: Hotkey | ParsedHotkey,\n callback: HotkeyCallback,\n options: CreateHotkeyHandlerOptions = {},\n): (event: KeyboardEvent) => void {\n const { preventDefault = true, stopPropagation = true, platform } = options\n const resolvedPlatform = platform ?? detectPlatform()\n\n const hotkeyString: Hotkey =\n typeof hotkey === 'string' ? hotkey : formatParsedHotkey(hotkey)\n const parsed =\n typeof hotkey === 'string' ? parseHotkey(hotkey, resolvedPlatform) : hotkey\n\n const context: HotkeyCallbackContext = {\n hotkey: hotkeyString,\n parsedHotkey: parsed,\n }\n\n return (event: KeyboardEvent) => {\n if (matchesKeyboardEvent(event, parsed, resolvedPlatform)) {\n if (preventDefault) {\n event.preventDefault()\n }\n if (stopPropagation) {\n event.stopPropagation()\n }\n callback(event, context)\n }\n }\n}\n\ntype MultiHotkeyHandler = { [K in Hotkey]?: HotkeyCallback }\n\n/**\n * Creates a handler that matches multiple hotkeys.\n *\n * @param handlers - A map of hotkey strings to their handlers\n * @param options - Options for matching and handling\n * @returns A function that can be used as an event handler\n *\n * @example\n * ```ts\n * const handler = createMultiHotkeyHandler({\n * 'Mod+S': (event, { hotkey }) => handleSave(),\n * 'Mod+Z': (event, { hotkey }) => handleUndo(),\n * 'Mod+Shift+Z': (event, { hotkey }) => handleRedo(),\n * })\n *\n * document.addEventListener('keydown', handler)\n * ```\n */\nexport function createMultiHotkeyHandler(\n handlers: MultiHotkeyHandler,\n options: CreateHotkeyHandlerOptions = {},\n): (event: KeyboardEvent) => void {\n const { preventDefault = true, stopPropagation = true, platform } = options\n const resolvedPlatform = platform ?? detectPlatform()\n\n // Pre-parse all hotkeys for efficiency\n const parsedHandlers = Object.entries(handlers)\n .filter((entry): entry is [string, HotkeyCallback] => Boolean(entry[1]))\n .map(([hotkey, handler]) => {\n const parsed = parseHotkey(hotkey as Hotkey, resolvedPlatform)\n const context: HotkeyCallbackContext = {\n hotkey: hotkey as Hotkey,\n parsedHotkey: parsed,\n }\n return { parsed, handler, context }\n })\n\n return (event: KeyboardEvent) => {\n for (const { parsed, handler, context } of parsedHandlers) {\n if (matchesKeyboardEvent(event, parsed, resolvedPlatform)) {\n if (preventDefault) {\n event.preventDefault()\n }\n if (stopPropagation) {\n event.stopPropagation()\n }\n handler(event, context)\n return // Only handle the first match\n }\n }\n }\n}\n\n/**\n * Formats a ParsedHotkey back to a hotkey string.\n * Used internally to provide the hotkey string in callback context.\n */\nfunction formatParsedHotkey(parsed: ParsedHotkey): Hotkey {\n const parts: Array<string> = []\n\n if (parsed.ctrl) parts.push('Control')\n if (parsed.alt) parts.push('Alt')\n if (parsed.shift) parts.push('Shift')\n if (parsed.meta) parts.push('Meta')\n parts.push(parsed.key)\n\n return parts.join('+') as Hotkey\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;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"file":"match.js","names":[],"sources":["../src/match.ts"],"sourcesContent":["import { matchKeyboardEvent } from './_match'\nimport { parseHotkey, parseRegisterableHotkey } from './parse'\nimport { detectPlatform } from './platform'\nimport { keysEqual } from './_keyboard-event'\nimport type {\n Hotkey,\n HotkeyCallback,\n HotkeyCallbackContext,\n ParsedHotkey,\n RegisterableHotkey,\n} from './hotkey.types'\n\nexport interface KeyboardEventMatch {\n matched: boolean\n score: 0 | 1 | 2 | 3\n source?: 'key' | 'code' | 'fallback'\n identity?: { key: string; code: string }\n}\n\n/**\n * Checks if a KeyboardEvent matches a hotkey.\n *\n * Physical bindings such as `Mod+[KeyS]` match `event.code` exactly.\n * Logical bindings use `event.key`, with a fallback to `code`\n * for letter keys, digit keys (0-9), and punctuation keys when `key` produces special\n * characters (e.g., macOS Option+letter, Shift+number, or Option+punctuation).\n * Letter keys are matched case-insensitively.\n *\n * Also handles \"dead key\" events where `event.key` is `'Dead'` instead of the expected\n * character. This commonly occurs on macOS with Option+letter combinations (e.g., Option+E,\n * Option+I, Option+U, Option+N) and on Windows/Linux with international keyboard layouts.\n * In these cases, `event.code` is used to determine the physical key.\n *\n * @param event - The KeyboardEvent to check\n * @param hotkey - The hotkey string or ParsedHotkey to match against\n * @param platform - The target platform for resolving 'Mod' (defaults to auto-detection)\n * @returns True if the event matches the hotkey\n *\n * @example\n * ```ts\n * document.addEventListener('keydown', (event) => {\n * if (matchesKeyboardEvent(event, 'Mod+S')) {\n * event.preventDefault()\n * handleSave()\n * }\n * })\n * ```\n */\nexport function matchesKeyboardEvent(\n event: KeyboardEvent,\n hotkey: Hotkey | ParsedHotkey,\n platform: 'mac' | 'windows' | 'linux' = detectPlatform(),\n): boolean {\n return matchKeyboardEvent(event, hotkey, platform).matched\n}\n\n/**\n * Options for creating a hotkey handler.\n */\nexport interface CreateHotkeyHandlerOptions {\n /** Prevent the default browser action when the hotkey matches. Defaults to true */\n preventDefault?: boolean\n /** Stop event propagation when the hotkey matches. Defaults to true */\n stopPropagation?: boolean\n /** The target platform for resolving 'Mod' */\n platform?: 'mac' | 'windows' | 'linux'\n}\n\n/**\n * Creates a keyboard event handler that calls the callback when the hotkey matches.\n *\n * @param hotkey - The hotkey string or ParsedHotkey to match\n * @param callback - The function to call when the hotkey matches\n * @param options - Options for matching and handling\n * @returns A function that can be used as an event handler\n *\n * @example\n * ```ts\n * const handler = createHotkeyHandler('Mod+S', (event, { hotkey, parsedHotkey }) => {\n * console.log(`${hotkey} was pressed`)\n * handleSave()\n * })\n *\n * document.addEventListener('keydown', handler)\n * ```\n */\nexport function createHotkeyHandler(\n hotkey: Hotkey | ParsedHotkey,\n callback: HotkeyCallback,\n options: CreateHotkeyHandlerOptions = {},\n): (event: KeyboardEvent) => void {\n const { preventDefault = true, stopPropagation = true, platform } = options\n const resolvedPlatform = platform ?? detectPlatform()\n\n const hotkeyString: Hotkey =\n typeof hotkey === 'string' ? hotkey : formatParsedHotkey(hotkey)\n const parsed =\n typeof hotkey === 'string' ? parseHotkey(hotkey, resolvedPlatform) : hotkey\n\n const context: HotkeyCallbackContext = {\n hotkey: hotkeyString,\n parsedHotkey: parsed,\n }\n\n return (event: KeyboardEvent) => {\n if (matchesKeyboardEvent(event, parsed, resolvedPlatform)) {\n if (preventDefault) {\n event.preventDefault()\n }\n if (stopPropagation) {\n event.stopPropagation()\n }\n callback(event, context)\n }\n }\n}\n\nexport type MultiHotkeyHandler = { [K in Hotkey]?: HotkeyCallback }\n\n/**\n * Creates a handler that matches multiple hotkeys.\n *\n * @param handlers - A map of hotkey strings to their handlers\n * @param options - Options for matching and handling\n * @returns A function that can be used as an event handler\n *\n * @example\n * ```ts\n * const handler = createMultiHotkeyHandler({\n * 'Mod+S': (event, { hotkey }) => handleSave(),\n * 'Mod+Z': (event, { hotkey }) => handleUndo(),\n * 'Mod+Shift+Z': (event, { hotkey }) => handleRedo(),\n * })\n *\n * document.addEventListener('keydown', handler)\n * ```\n */\nexport function createMultiHotkeyHandler(\n handlers: MultiHotkeyHandler,\n options: CreateHotkeyHandlerOptions = {},\n): (event: KeyboardEvent) => void {\n const { preventDefault = true, stopPropagation = true, platform } = options\n const resolvedPlatform = platform ?? detectPlatform()\n\n // Pre-parse all hotkeys for efficiency\n const parsedHandlers = Object.entries(handlers)\n .filter((entry): entry is [string, HotkeyCallback] => Boolean(entry[1]))\n .map(([hotkey, handler]) => {\n const parsed = parseHotkey(hotkey as Hotkey, resolvedPlatform)\n const context: HotkeyCallbackContext = {\n hotkey: hotkey as Hotkey,\n parsedHotkey: parsed,\n }\n return { parsed, handler, context }\n })\n\n return (event: KeyboardEvent) => {\n for (const { parsed, handler, context } of parsedHandlers) {\n if (matchesKeyboardEvent(event, parsed, resolvedPlatform)) {\n if (preventDefault) {\n event.preventDefault()\n }\n if (stopPropagation) {\n event.stopPropagation()\n }\n handler(event, context)\n return // Only handle the first match\n }\n }\n }\n}\n\n/**\n * Formats a ParsedHotkey back to a hotkey string.\n * Used internally to provide the hotkey string in callback context.\n */\nfunction formatParsedHotkey(parsed: ParsedHotkey): Hotkey {\n const parts: Array<string> = []\n\n if (parsed.ctrl) parts.push('Control')\n if (parsed.alt) parts.push('Alt')\n if (parsed.shift) parts.push('Shift')\n if (parsed.meta) parts.push('Meta')\n parts.push(parsed.code !== undefined ? `[${parsed.code}]` : parsed.key)\n\n return parts.join('+') as Hotkey\n}\n\n/**\n * Compares normalized binding identity, including all four modifiers.\n * Aliases resolve on the supplied platform. A physical code and a logical key\n * remain distinct even when one keyboard event could match both.\n */\nexport function areHotkeysEqual(\n left: RegisterableHotkey,\n right: RegisterableHotkey,\n platform = detectPlatform(),\n): boolean {\n const a = parseRegisterableHotkey(left, platform)\n const b = parseRegisterableHotkey(right, platform)\n return (\n a.ctrl === b.ctrl &&\n a.alt === b.alt &&\n a.shift === b.shift &&\n a.meta === b.meta &&\n (a.code !== undefined || b.code !== undefined\n ? a.code === b.code\n : keysEqual(a.key, b.key))\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;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8B;CACxD,MAAM,QAAuB,EAAE;AAE/B,KAAI,OAAO,KAAM,OAAM,KAAK,UAAU;AACtC,KAAI,OAAO,IAAK,OAAM,KAAK,MAAM;AACjC,KAAI,OAAO,MAAO,OAAM,KAAK,QAAQ;AACrC,KAAI,OAAO,KAAM,OAAM,KAAK,OAAO;AACnC,OAAM,KAAK,OAAO,SAAS,SAAY,IAAI,OAAO,KAAK,KAAK,OAAO,IAAI;AAEvE,QAAO,MAAM,KAAK,IAAI;;;;;;;AAQxB,SAAgB,gBACd,MACA,OACA,WAAW,gBAAgB,EAClB;CACT,MAAM,IAAI,wBAAwB,MAAM,SAAS;CACjD,MAAM,IAAI,wBAAwB,OAAO,SAAS;AAClD,QACE,EAAE,SAAS,EAAE,QACb,EAAE,QAAQ,EAAE,OACZ,EAAE,UAAU,EAAE,SACd,EAAE,SAAS,EAAE,SACZ,EAAE,SAAS,UAAa,EAAE,SAAS,SAChC,EAAE,SAAS,EAAE,OACb,UAAU,EAAE,KAAK,EAAE,IAAI"}
|
package/dist/parse.cjs
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
const require_constants = require('./constants.cjs');
|
|
2
|
+
const require_platform = require('./platform.cjs');
|
|
3
|
+
const require__keyboard_event = require('./_keyboard-event.cjs');
|
|
2
4
|
|
|
3
5
|
//#region src/parse.ts
|
|
4
6
|
/**
|
|
@@ -6,7 +8,7 @@ const require_constants = require('./constants.cjs');
|
|
|
6
8
|
*
|
|
7
9
|
* @param hotkey - The hotkey string to parse (e.g., 'Mod+Shift+S')
|
|
8
10
|
* @param platform - The target platform for resolving 'Mod' (defaults to auto-detection)
|
|
9
|
-
* @returns A ParsedHotkey
|
|
11
|
+
* @returns A ParsedHotkey with either logical key or physical code and modifier flags
|
|
10
12
|
*
|
|
11
13
|
* @example
|
|
12
14
|
* ```ts
|
|
@@ -15,8 +17,8 @@ const require_constants = require('./constants.cjs');
|
|
|
15
17
|
* parseHotkey('Control+Shift+A') // { key: 'A', ctrl: true, shift: true, alt: false, meta: false, modifiers: ['Control', 'Shift'] }
|
|
16
18
|
* ```
|
|
17
19
|
*/
|
|
18
|
-
function parseHotkey(hotkey, platform =
|
|
19
|
-
const parts =
|
|
20
|
+
function parseHotkey(hotkey, platform = require_platform.detectPlatform()) {
|
|
21
|
+
const parts = require__keyboard_event.splitHotkeyParts(hotkey);
|
|
20
22
|
const modifiers = /* @__PURE__ */ new Set();
|
|
21
23
|
let key = "";
|
|
22
24
|
for (let i = 0; i < parts.length; i++) {
|
|
@@ -25,14 +27,15 @@ function parseHotkey(hotkey, platform = require_constants.detectPlatform()) {
|
|
|
25
27
|
else {
|
|
26
28
|
const alias = require_constants.MODIFIER_ALIASES[part] ?? require_constants.MODIFIER_ALIASES[part.toLowerCase()];
|
|
27
29
|
if (alias) {
|
|
28
|
-
const resolved =
|
|
30
|
+
const resolved = require_platform.resolveModifier(alias, platform);
|
|
29
31
|
modifiers.add(resolved);
|
|
30
32
|
} else if (parts.length === 1) key = require_constants.normalizeKeyName(part);
|
|
31
33
|
}
|
|
32
34
|
}
|
|
33
35
|
if (!key && parts.length > 0) key = require_constants.normalizeKeyName(parts[parts.length - 1].trim());
|
|
36
|
+
const code = /^\[([A-Za-z][A-Za-z0-9]*)\]$/.exec(key)?.[1];
|
|
34
37
|
return {
|
|
35
|
-
key,
|
|
38
|
+
...code !== void 0 ? { code } : { key },
|
|
36
39
|
ctrl: modifiers.has("Control"),
|
|
37
40
|
shift: modifiers.has("Shift"),
|
|
38
41
|
alt: modifiers.has("Alt"),
|
|
@@ -61,12 +64,13 @@ function parseHotkey(hotkey, platform = require_constants.detectPlatform()) {
|
|
|
61
64
|
* // { key: 'S', ctrl: true, shift: true, alt: false, meta: false, modifiers: ['Control', 'Shift'] }
|
|
62
65
|
* ```
|
|
63
66
|
*/
|
|
64
|
-
function rawHotkeyToParsedHotkey(raw, platform =
|
|
67
|
+
function rawHotkeyToParsedHotkey(raw, platform = require_platform.detectPlatform()) {
|
|
68
|
+
if (raw.code === void 0) require__keyboard_event.assertLogicalKey(raw.key);
|
|
65
69
|
let ctrl = raw.ctrl ?? false;
|
|
66
70
|
const shift = raw.shift ?? false;
|
|
67
71
|
const alt = raw.alt ?? false;
|
|
68
72
|
let meta = raw.meta ?? false;
|
|
69
|
-
if (raw.mod) if (
|
|
73
|
+
if (raw.mod) if (require_platform.resolveModifier("Mod", platform) === "Control") ctrl = true;
|
|
70
74
|
else meta = true;
|
|
71
75
|
const modifiers = require_constants.MODIFIER_ORDER.filter((m) => {
|
|
72
76
|
switch (m) {
|
|
@@ -78,7 +82,7 @@ function rawHotkeyToParsedHotkey(raw, platform = require_constants.detectPlatfor
|
|
|
78
82
|
}
|
|
79
83
|
});
|
|
80
84
|
return {
|
|
81
|
-
key: raw.key,
|
|
85
|
+
...raw.code !== void 0 ? { code: raw.code } : { key: require_constants.normalizeKeyName(raw.key) },
|
|
82
86
|
ctrl,
|
|
83
87
|
shift,
|
|
84
88
|
alt,
|
|
@@ -92,6 +96,7 @@ function rawHotkeyToParsedHotkey(raw, platform = require_constants.detectPlatfor
|
|
|
92
96
|
* otherwise full `Control+Alt+Shift+Meta` order.
|
|
93
97
|
*/
|
|
94
98
|
function normalizedHotkeyStringFromParsed(parsed, platform) {
|
|
99
|
+
if (parsed.code === void 0) require__keyboard_event.assertLogicalKey(parsed.key);
|
|
95
100
|
const canUseMod = platform === "mac" ? parsed.meta && !parsed.ctrl : parsed.ctrl && !parsed.meta;
|
|
96
101
|
const parts = [];
|
|
97
102
|
if (canUseMod) {
|
|
@@ -99,7 +104,7 @@ function normalizedHotkeyStringFromParsed(parsed, platform) {
|
|
|
99
104
|
if (parsed.alt) parts.push("Alt");
|
|
100
105
|
if (parsed.shift) parts.push("Shift");
|
|
101
106
|
} else for (const modifier of require_constants.MODIFIER_ORDER) if (parsed.modifiers.includes(modifier)) parts.push(modifier);
|
|
102
|
-
parts.push(require_constants.normalizeKeyName(parsed.key));
|
|
107
|
+
parts.push(parsed.code !== void 0 ? `[${parsed.code}]` : require_constants.normalizeKeyName(parsed.key));
|
|
103
108
|
return parts.join("+");
|
|
104
109
|
}
|
|
105
110
|
/**
|
|
@@ -122,20 +127,20 @@ function normalizedHotkeyStringFromParsed(parsed, platform) {
|
|
|
122
127
|
* normalizeHotkey('esc') // 'Escape'
|
|
123
128
|
* ```
|
|
124
129
|
*/
|
|
125
|
-
function normalizeHotkey(hotkey, platform =
|
|
130
|
+
function normalizeHotkey(hotkey, platform = require_platform.detectPlatform()) {
|
|
126
131
|
return normalizedHotkeyStringFromParsed(parseHotkey(hotkey, platform), platform);
|
|
127
132
|
}
|
|
128
133
|
/**
|
|
129
134
|
* Same canonical string as {@link normalizeHotkey}, but from an already-parsed hotkey.
|
|
130
135
|
*/
|
|
131
|
-
function normalizeHotkeyFromParsed(parsed, platform =
|
|
136
|
+
function normalizeHotkeyFromParsed(parsed, platform = require_platform.detectPlatform()) {
|
|
132
137
|
return normalizedHotkeyStringFromParsed(parsed, platform);
|
|
133
138
|
}
|
|
134
139
|
/**
|
|
135
140
|
* Normalizes a string or {@link RawHotkey} object to the same canonical hotkey string.
|
|
136
141
|
* Use this in framework adapters instead of branching on `formatHotkey(rawHotkeyToParsedHotkey(...))`.
|
|
137
142
|
*/
|
|
138
|
-
function normalizeRegisterableHotkey(hotkey, platform =
|
|
143
|
+
function normalizeRegisterableHotkey(hotkey, platform = require_platform.detectPlatform()) {
|
|
139
144
|
return typeof hotkey === "string" ? normalizeHotkey(hotkey, platform) : normalizeHotkeyFromParsed(rawHotkeyToParsedHotkey(hotkey, platform), platform);
|
|
140
145
|
}
|
|
141
146
|
/**
|
|
@@ -168,19 +173,22 @@ function isModifierKey(key) {
|
|
|
168
173
|
* })
|
|
169
174
|
* ```
|
|
170
175
|
*/
|
|
171
|
-
function parseKeyboardEvent(event) {
|
|
172
|
-
const
|
|
176
|
+
function parseKeyboardEvent(event, platform) {
|
|
177
|
+
const normalized = require__keyboard_event.normalizeKeyboardEvent(event, platform);
|
|
178
|
+
const ctrl = normalized.altGraph ? false : normalized.ctrl;
|
|
179
|
+
const alt = normalized.altGraph ? false : normalized.alt;
|
|
180
|
+
const shift = normalized.shift;
|
|
173
181
|
const modifiers = [];
|
|
174
|
-
if (
|
|
175
|
-
if (
|
|
176
|
-
if (
|
|
177
|
-
if (
|
|
182
|
+
if (ctrl) modifiers.push("Control");
|
|
183
|
+
if (alt) modifiers.push("Alt");
|
|
184
|
+
if (shift) modifiers.push("Shift");
|
|
185
|
+
if (normalized.meta) modifiers.push("Meta");
|
|
178
186
|
return {
|
|
179
|
-
key:
|
|
180
|
-
ctrl
|
|
181
|
-
shift
|
|
182
|
-
alt
|
|
183
|
-
meta:
|
|
187
|
+
key: normalized.key,
|
|
188
|
+
ctrl,
|
|
189
|
+
shift,
|
|
190
|
+
alt,
|
|
191
|
+
meta: normalized.meta,
|
|
184
192
|
modifiers
|
|
185
193
|
};
|
|
186
194
|
}
|
|
@@ -190,8 +198,8 @@ function parseKeyboardEvent(event) {
|
|
|
190
198
|
* @param event - The keyboard event (typically `keydown`)
|
|
191
199
|
* @param platform - Target platform for `Mod` eligibility
|
|
192
200
|
*/
|
|
193
|
-
function normalizeHotkeyFromEvent(event, platform =
|
|
194
|
-
return normalizedHotkeyStringFromParsed(parseKeyboardEvent(event), platform);
|
|
201
|
+
function normalizeHotkeyFromEvent(event, platform = require_platform.detectPlatform()) {
|
|
202
|
+
return normalizedHotkeyStringFromParsed(parseKeyboardEvent(event, platform), platform);
|
|
195
203
|
}
|
|
196
204
|
/**
|
|
197
205
|
* Checks if a hotkey or ParsedHotkey contains at least one non-modifier key.
|
|
@@ -210,10 +218,18 @@ function normalizeHotkeyFromEvent(event, platform = require_constants.detectPlat
|
|
|
210
218
|
* hasNonModifierKey(parseHotkey('Mod+A')) // true
|
|
211
219
|
* ```
|
|
212
220
|
*/
|
|
213
|
-
function hasNonModifierKey(hotkey, platform =
|
|
221
|
+
function hasNonModifierKey(hotkey, platform = require_platform.detectPlatform()) {
|
|
214
222
|
const parsed = typeof hotkey === "string" ? parseHotkey(hotkey, platform) : hotkey;
|
|
223
|
+
if (parsed.code !== void 0) return parsed.code.length > 0 && !/^(Control|Shift|Alt|Meta)(Left|Right)$/.test(parsed.code);
|
|
215
224
|
return !isModifierKey(parsed.key) && parsed.key.length > 0;
|
|
216
225
|
}
|
|
226
|
+
/**
|
|
227
|
+
* Parses a string or raw binding, resolving Mod for the supplied platform.
|
|
228
|
+
* Physical tokens such as `[KeyQ]` retain `code`; they never become logical Q.
|
|
229
|
+
*/
|
|
230
|
+
function parseRegisterableHotkey(hotkey, platform = require_platform.detectPlatform()) {
|
|
231
|
+
return typeof hotkey === "string" ? parseHotkey(hotkey, platform) : rawHotkeyToParsedHotkey(hotkey, platform);
|
|
232
|
+
}
|
|
217
233
|
|
|
218
234
|
//#endregion
|
|
219
235
|
exports.hasNonModifierKey = hasNonModifierKey;
|
|
@@ -224,5 +240,6 @@ exports.normalizeHotkeyFromParsed = normalizeHotkeyFromParsed;
|
|
|
224
240
|
exports.normalizeRegisterableHotkey = normalizeRegisterableHotkey;
|
|
225
241
|
exports.parseHotkey = parseHotkey;
|
|
226
242
|
exports.parseKeyboardEvent = parseKeyboardEvent;
|
|
243
|
+
exports.parseRegisterableHotkey = parseRegisterableHotkey;
|
|
227
244
|
exports.rawHotkeyToParsedHotkey = rawHotkeyToParsedHotkey;
|
|
228
245
|
//# sourceMappingURL=parse.cjs.map
|