@tanstack/hotkeys 0.5.0 → 0.6.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 +1 -1
- package/dist/constants.cjs +70 -10
- package/dist/constants.cjs.map +1 -1
- package/dist/constants.d.cts +57 -4
- package/dist/constants.d.ts +57 -4
- package/dist/constants.js +67 -10
- package/dist/constants.js.map +1 -1
- package/dist/format.cjs +20 -125
- package/dist/format.cjs.map +1 -1
- package/dist/format.d.cts +8 -72
- package/dist/format.d.ts +8 -72
- package/dist/format.js +23 -127
- package/dist/format.js.map +1 -1
- package/dist/hotkey-manager.cjs.map +1 -1
- package/dist/hotkey-manager.d.cts +5 -1
- package/dist/hotkey-manager.d.ts +5 -1
- package/dist/hotkey-manager.js.map +1 -1
- package/dist/hotkey.d.cts +2 -0
- package/dist/hotkey.d.ts +2 -0
- package/dist/index.cjs +7 -5
- package/dist/index.d.cts +4 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.js +4 -4
- package/dist/parse.cjs +53 -91
- package/dist/parse.cjs.map +1 -1
- package/dist/parse.d.cts +31 -72
- package/dist/parse.d.ts +31 -72
- package/dist/parse.js +51 -89
- package/dist/parse.js.map +1 -1
- package/dist/recorder-chord.cjs +3 -2
- package/dist/recorder-chord.cjs.map +1 -1
- package/dist/recorder-chord.js +4 -3
- package/dist/recorder-chord.js.map +1 -1
- package/dist/sequence-manager.cjs +1 -1
- package/dist/sequence-manager.cjs.map +1 -1
- package/dist/sequence-manager.js +2 -2
- package/dist/sequence-manager.js.map +1 -1
- package/package.json +1 -1
- package/src/constants.ts +75 -21
- package/src/format.ts +58 -196
- package/src/hotkey-manager.ts +5 -1
- package/src/hotkey.ts +2 -0
- package/src/parse.ts +91 -131
- package/src/recorder-chord.ts +4 -5
- package/src/sequence-manager.ts +2 -2
package/dist/format.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { KEY_DISPLAY_SYMBOLS, MAC_MODIFIER_SYMBOLS, MODIFIER_ORDER,
|
|
2
|
-
import {
|
|
1
|
+
import { KEY_DISPLAY_SYMBOLS, LINUX_MODIFIER_LABELS, MAC_MODIFIER_LABELS, MAC_MODIFIER_SYMBOLS, MODIFIER_ALIASES, MODIFIER_ORDER, PUNCTUATION_KEY_DISPLAY_LABELS, WINDOWS_MODIFIER_LABELS, detectPlatform } from "./constants.js";
|
|
2
|
+
import { isModifierKey, normalizeRegisterableHotkey } from "./parse.js";
|
|
3
3
|
|
|
4
4
|
//#region src/format.ts
|
|
5
5
|
/**
|
|
@@ -38,8 +38,8 @@ function formatHotkey(parsed) {
|
|
|
38
38
|
/**
|
|
39
39
|
* Formats a hotkey for display in a user interface.
|
|
40
40
|
*
|
|
41
|
-
* On macOS, uses symbols (⌘⇧S).
|
|
42
|
-
* On Windows/Linux, uses text (Ctrl+Shift+S).
|
|
41
|
+
* On macOS, uses symbols (⌘⇧S) in the same modifier order as {@link normalizeHotkeyFromParsed}.
|
|
42
|
+
* On Windows/Linux, uses text (Ctrl+Shift+S) with `+` separators.
|
|
43
43
|
*
|
|
44
44
|
* @param hotkey - The hotkey string or ParsedHotkey to format
|
|
45
45
|
* @param options - Formatting options
|
|
@@ -48,7 +48,7 @@ function formatHotkey(parsed) {
|
|
|
48
48
|
* @example
|
|
49
49
|
* ```ts
|
|
50
50
|
* formatForDisplay('Mod+Shift+S', { platform: 'mac' })
|
|
51
|
-
* // Returns: '
|
|
51
|
+
* // Returns: '⌘ ⇧ S' (symbols separated by spaces on macOS)
|
|
52
52
|
*
|
|
53
53
|
* formatForDisplay('Mod+Shift+S', { platform: 'windows' })
|
|
54
54
|
* // Returns: 'Ctrl+Shift+S'
|
|
@@ -59,132 +59,28 @@ function formatHotkey(parsed) {
|
|
|
59
59
|
*/
|
|
60
60
|
function formatForDisplay(hotkey, options = {}) {
|
|
61
61
|
const platform = options.platform ?? detectPlatform();
|
|
62
|
-
const
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
parts.push(keyDisplay);
|
|
74
|
-
return parts.join("");
|
|
75
|
-
}
|
|
76
|
-
/**
|
|
77
|
-
* Formats a hotkey for Windows/Linux display using text labels.
|
|
78
|
-
*/
|
|
79
|
-
function formatForStandard(parsed) {
|
|
80
|
-
const parts = [];
|
|
81
|
-
for (const modifier of MODIFIER_ORDER) if (parsed.modifiers.includes(modifier)) parts.push(STANDARD_MODIFIER_LABELS[modifier]);
|
|
82
|
-
const keyDisplay = KEY_DISPLAY_SYMBOLS[parsed.key] ?? parsed.key;
|
|
83
|
-
parts.push(keyDisplay);
|
|
84
|
-
return parts.join("+");
|
|
85
|
-
}
|
|
86
|
-
/**
|
|
87
|
-
* Formats a hotkey using platform-agnostic labels.
|
|
88
|
-
* Uses 'Cmd' on Mac and 'Ctrl' for Control, etc.
|
|
89
|
-
*
|
|
90
|
-
* @param hotkey - The hotkey string or ParsedHotkey to format
|
|
91
|
-
* @param platform - The target platform
|
|
92
|
-
* @returns A formatted string with platform-appropriate labels
|
|
93
|
-
*/
|
|
94
|
-
function formatWithLabels(hotkey, platform = detectPlatform()) {
|
|
95
|
-
const parsed = typeof hotkey === "string" ? parseHotkey(hotkey, platform) : hotkey;
|
|
96
|
-
const parts = [];
|
|
97
|
-
const labels = {
|
|
98
|
-
Control: "Ctrl",
|
|
99
|
-
Alt: platform === "mac" ? "Option" : "Alt",
|
|
100
|
-
Shift: "Shift",
|
|
101
|
-
Meta: platform === "mac" ? "Cmd" : "Win"
|
|
102
|
-
};
|
|
103
|
-
for (const modifier of MODIFIER_ORDER) if (parsed.modifiers.includes(modifier)) parts.push(labels[modifier] ?? modifier);
|
|
104
|
-
parts.push(parsed.key);
|
|
105
|
-
return parts.join("+");
|
|
62
|
+
const useSymbols = options.useSymbols ?? true;
|
|
63
|
+
return normalizeRegisterableHotkey(hotkey, platform).split("+").map((segment) => {
|
|
64
|
+
if (isModifierKey(segment)) {
|
|
65
|
+
const modifierToken = MODIFIER_ALIASES[segment] ?? MODIFIER_ALIASES[segment.toLowerCase()];
|
|
66
|
+
return platform === "mac" ? useSymbols ? MAC_MODIFIER_SYMBOLS[modifierToken] : MAC_MODIFIER_LABELS[modifierToken] : platform === "windows" ? WINDOWS_MODIFIER_LABELS[modifierToken] : LINUX_MODIFIER_LABELS[modifierToken];
|
|
67
|
+
} else {
|
|
68
|
+
const keyDisplaySymbol = useSymbols && KEY_DISPLAY_SYMBOLS[segment];
|
|
69
|
+
if (keyDisplaySymbol) return keyDisplaySymbol;
|
|
70
|
+
return !useSymbols && PUNCTUATION_KEY_DISPLAY_LABELS[segment] || segment;
|
|
71
|
+
}
|
|
72
|
+
}).join(platform === "mac" && useSymbols ? " " : "+");
|
|
106
73
|
}
|
|
107
74
|
/**
|
|
108
|
-
*
|
|
75
|
+
* @deprecated Use {@link formatForDisplay} instead with `useSymbols: false` option.
|
|
109
76
|
*/
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
Shift: "Shift"
|
|
116
|
-
},
|
|
117
|
-
windows: {
|
|
118
|
-
Control: "Mod (Ctrl)",
|
|
119
|
-
Meta: "Win",
|
|
120
|
-
Alt: "Alt",
|
|
121
|
-
Shift: "Shift"
|
|
122
|
-
},
|
|
123
|
-
linux: {
|
|
124
|
-
Control: "Mod (Ctrl)",
|
|
125
|
-
Meta: "Super",
|
|
126
|
-
Alt: "Alt",
|
|
127
|
-
Shift: "Shift"
|
|
128
|
-
}
|
|
129
|
-
};
|
|
130
|
-
/**
|
|
131
|
-
* Formats a single key name for debugging/devtools display.
|
|
132
|
-
*
|
|
133
|
-
* Unlike `formatForDisplay` which formats full hotkey strings for end-user UIs,
|
|
134
|
-
* this function formats individual key names (from `event.key`) with rich
|
|
135
|
-
* platform-aware labels suitable for debugging tools and developer-facing displays.
|
|
136
|
-
*
|
|
137
|
-
* Features:
|
|
138
|
-
* - Modifier keys show their platform role (e.g., "Mod (Cmd)" for Meta on Mac)
|
|
139
|
-
* - On macOS, modifier keys are prefixed with their symbol (e.g., "⌘ Mod (Cmd)")
|
|
140
|
-
* - Special keys use display symbols (ArrowUp -> "↑", Escape -> "Esc")
|
|
141
|
-
* - Regular keys pass through unchanged
|
|
142
|
-
*
|
|
143
|
-
* @param key - A single key name (e.g., "Meta", "Shift", "ArrowUp", "A")
|
|
144
|
-
* @param options - Formatting options
|
|
145
|
-
* @returns A formatted label suitable for debugging display
|
|
146
|
-
*
|
|
147
|
-
* @example
|
|
148
|
-
* ```ts
|
|
149
|
-
* // On macOS:
|
|
150
|
-
* formatKeyForDebuggingDisplay('Meta') // '⌘ Mod (Cmd)'
|
|
151
|
-
* formatKeyForDebuggingDisplay('Control') // '⌃ Ctrl'
|
|
152
|
-
* formatKeyForDebuggingDisplay('Alt') // '⌥ Opt'
|
|
153
|
-
* formatKeyForDebuggingDisplay('Shift') // '⇧ Shift'
|
|
154
|
-
*
|
|
155
|
-
* // On Windows:
|
|
156
|
-
* formatKeyForDebuggingDisplay('Control') // 'Mod (Ctrl)'
|
|
157
|
-
* formatKeyForDebuggingDisplay('Meta') // 'Win'
|
|
158
|
-
*
|
|
159
|
-
* // Special keys (all platforms):
|
|
160
|
-
* formatKeyForDebuggingDisplay('ArrowUp') // '↑'
|
|
161
|
-
* formatKeyForDebuggingDisplay('Escape') // 'Esc'
|
|
162
|
-
* formatKeyForDebuggingDisplay('Space') // '␣'
|
|
163
|
-
*
|
|
164
|
-
* // Regular keys pass through:
|
|
165
|
-
* formatKeyForDebuggingDisplay('A') // 'A'
|
|
166
|
-
*
|
|
167
|
-
* // With source: 'code', values pass through unchanged:
|
|
168
|
-
* formatKeyForDebuggingDisplay('MetaLeft', { source: 'code' }) // 'MetaLeft'
|
|
169
|
-
* formatKeyForDebuggingDisplay('KeyA', { source: 'code' }) // 'KeyA'
|
|
170
|
-
* ```
|
|
171
|
-
*/
|
|
172
|
-
function formatKeyForDebuggingDisplay(key, options = {}) {
|
|
173
|
-
if (options.source === "code") return key;
|
|
174
|
-
const platform = options.platform ?? detectPlatform();
|
|
175
|
-
const modLabel = MODIFIER_DEBUG_LABELS[platform]?.[key];
|
|
176
|
-
if (modLabel) {
|
|
177
|
-
if (platform === "mac") {
|
|
178
|
-
const symbol = MAC_MODIFIER_SYMBOLS[key];
|
|
179
|
-
if (symbol) return `${symbol} ${modLabel}`;
|
|
180
|
-
}
|
|
181
|
-
return modLabel;
|
|
182
|
-
}
|
|
183
|
-
const symbol = KEY_DISPLAY_SYMBOLS[key];
|
|
184
|
-
if (symbol) return symbol;
|
|
185
|
-
return key;
|
|
77
|
+
function formatWithLabels(hotkey, options = {}) {
|
|
78
|
+
return formatForDisplay(hotkey, {
|
|
79
|
+
...options,
|
|
80
|
+
useSymbols: false
|
|
81
|
+
});
|
|
186
82
|
}
|
|
187
83
|
|
|
188
84
|
//#endregion
|
|
189
|
-
export { formatForDisplay, formatHotkey, formatHotkeySequence,
|
|
85
|
+
export { formatForDisplay, formatHotkey, formatHotkeySequence, formatWithLabels };
|
|
190
86
|
//# sourceMappingURL=format.js.map
|
package/dist/format.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"format.js","names":[],"sources":["../src/format.ts"],"sourcesContent":["import {\n KEY_DISPLAY_SYMBOLS,\n MAC_MODIFIER_SYMBOLS,\n MODIFIER_ORDER,\n STANDARD_MODIFIER_LABELS,\n detectPlatform,\n} from './constants'\nimport { parseHotkey } from './parse'\nimport type { FormatDisplayOptions, Hotkey, ParsedHotkey } from './hotkey'\n\n/**\n * Converts a hotkey sequence array to a display string.\n *\n * @param sequence - Array of hotkey strings that form the sequence\n * @returns A space-separated string (e.g. ['G','G'] → 'G G')\n *\n * @example\n * ```ts\n * formatHotkeySequence(['G', 'G']) // 'G G'\n * formatHotkeySequence(['D', 'I', 'W']) // 'D I W'\n * ```\n */\nexport function formatHotkeySequence(sequence: Array<Hotkey>): string {\n return sequence.join(' ')\n}\n\n/**\n * Converts a ParsedHotkey back to a hotkey string.\n *\n * @param parsed - The parsed hotkey object\n * @returns A hotkey string in canonical form\n *\n * @example\n * ```ts\n * formatHotkey({ key: 'S', ctrl: true, shift: true, alt: false, meta: false, modifiers: ['Control', 'Shift'] })\n * // Returns: 'Control+Shift+S'\n * ```\n */\nexport function formatHotkey(parsed: ParsedHotkey): string {\n const parts: Array<string> = []\n\n // Add modifiers in canonical order\n for (const modifier of MODIFIER_ORDER) {\n if (parsed.modifiers.includes(modifier)) {\n parts.push(modifier)\n }\n }\n\n // Add the key\n parts.push(parsed.key)\n\n return parts.join('+')\n}\n\n/**\n * Formats a hotkey for display in a user interface.\n *\n * On macOS, uses symbols (⌘⇧S).\n * On Windows/Linux, uses text (Ctrl+Shift+S).\n *\n * @param hotkey - The hotkey string or ParsedHotkey to format\n * @param options - Formatting options\n * @returns A formatted string suitable for display\n *\n * @example\n * ```ts\n * formatForDisplay('Mod+Shift+S', { platform: 'mac' })\n * // Returns: '⇧⌘S'\n *\n * formatForDisplay('Mod+Shift+S', { platform: 'windows' })\n * // Returns: 'Ctrl+Shift+S'\n *\n * formatForDisplay('Escape')\n * // Returns: 'Esc' (on all platforms)\n * ```\n */\nexport function formatForDisplay(\n hotkey: Hotkey | (string & {}) | ParsedHotkey,\n options: FormatDisplayOptions = {},\n): string {\n const platform = options.platform ?? detectPlatform()\n const parsed =\n typeof hotkey === 'string' ? parseHotkey(hotkey, platform) : hotkey\n\n if (platform === 'mac') {\n return formatForMac(parsed)\n }\n\n return formatForStandard(parsed)\n}\n\n/**\n * Formats a hotkey for macOS display using symbols.\n */\nfunction formatForMac(parsed: ParsedHotkey): string {\n const parts: Array<string> = []\n\n // Add modifiers in macOS order (typically Control, Option, Shift, Command)\n // But we'll use our canonical order and just use symbols\n for (const modifier of MODIFIER_ORDER) {\n if (parsed.modifiers.includes(modifier)) {\n parts.push(MAC_MODIFIER_SYMBOLS[modifier])\n }\n }\n\n // Add the key (use symbol if available, otherwise the key itself)\n const keyDisplay = KEY_DISPLAY_SYMBOLS[parsed.key] ?? parsed.key\n parts.push(keyDisplay)\n\n // On Mac, modifiers are typically concatenated without separators\n return parts.join('')\n}\n\n/**\n * Formats a hotkey for Windows/Linux display using text labels.\n */\nfunction formatForStandard(parsed: ParsedHotkey): string {\n const parts: Array<string> = []\n\n // Add modifiers in canonical order\n for (const modifier of MODIFIER_ORDER) {\n if (parsed.modifiers.includes(modifier)) {\n parts.push(STANDARD_MODIFIER_LABELS[modifier])\n }\n }\n\n // Add the key (use symbol/short form if available)\n const keyDisplay = KEY_DISPLAY_SYMBOLS[parsed.key] ?? parsed.key\n parts.push(keyDisplay)\n\n // On Windows/Linux, use + as separator\n return parts.join('+')\n}\n\n/**\n * Formats a hotkey using platform-agnostic labels.\n * Uses 'Cmd' on Mac and 'Ctrl' for Control, etc.\n *\n * @param hotkey - The hotkey string or ParsedHotkey to format\n * @param platform - The target platform\n * @returns A formatted string with platform-appropriate labels\n */\nexport function formatWithLabels(\n hotkey: Hotkey | (string & {}),\n platform: 'mac' | 'windows' | 'linux' = detectPlatform(),\n): string {\n const parsed =\n typeof hotkey === 'string' ? parseHotkey(hotkey, platform) : hotkey\n const parts: Array<string> = []\n\n // Custom labels for more readable output\n const labels: Record<string, string> = {\n Control: 'Ctrl',\n Alt: platform === 'mac' ? 'Option' : 'Alt',\n Shift: 'Shift',\n Meta: platform === 'mac' ? 'Cmd' : 'Win',\n }\n\n for (const modifier of MODIFIER_ORDER) {\n if (parsed.modifiers.includes(modifier)) {\n parts.push(labels[modifier] ?? modifier)\n }\n }\n\n // Add the key\n parts.push(parsed.key)\n\n return parts.join('+')\n}\n\n// =============================================================================\n// Debugging Display Labels\n// =============================================================================\n\n/**\n * Maps canonical modifier names to debugging-friendly labels per platform.\n */\nconst MODIFIER_DEBUG_LABELS: Record<string, Record<string, string>> = {\n mac: { Meta: 'Mod (Cmd)', Control: 'Ctrl', Alt: 'Opt', Shift: 'Shift' },\n windows: { Control: 'Mod (Ctrl)', Meta: 'Win', Alt: 'Alt', Shift: 'Shift' },\n linux: { Control: 'Mod (Ctrl)', Meta: 'Super', Alt: 'Alt', Shift: 'Shift' },\n}\n\n/**\n * Options for formatting a single key for debugging display.\n */\nexport interface FormatKeyDebuggingOptions {\n /** The target platform. Defaults to auto-detection. */\n platform?: 'mac' | 'windows' | 'linux'\n /**\n * Whether the input value comes from `event.key` or `event.code`.\n *\n * - `'key'` (default): Applies rich platform-aware formatting (modifier\n * labels, special-key symbols, etc.).\n * - `'code'`: Returns the value unchanged — physical key codes like\n * `\"MetaLeft\"` or `\"KeyA\"` are already descriptive for debugging.\n */\n source?: 'key' | 'code'\n}\n\n/**\n * Formats a single key name for debugging/devtools display.\n *\n * Unlike `formatForDisplay` which formats full hotkey strings for end-user UIs,\n * this function formats individual key names (from `event.key`) with rich\n * platform-aware labels suitable for debugging tools and developer-facing displays.\n *\n * Features:\n * - Modifier keys show their platform role (e.g., \"Mod (Cmd)\" for Meta on Mac)\n * - On macOS, modifier keys are prefixed with their symbol (e.g., \"⌘ Mod (Cmd)\")\n * - Special keys use display symbols (ArrowUp -> \"↑\", Escape -> \"Esc\")\n * - Regular keys pass through unchanged\n *\n * @param key - A single key name (e.g., \"Meta\", \"Shift\", \"ArrowUp\", \"A\")\n * @param options - Formatting options\n * @returns A formatted label suitable for debugging display\n *\n * @example\n * ```ts\n * // On macOS:\n * formatKeyForDebuggingDisplay('Meta') // '⌘ Mod (Cmd)'\n * formatKeyForDebuggingDisplay('Control') // '⌃ Ctrl'\n * formatKeyForDebuggingDisplay('Alt') // '⌥ Opt'\n * formatKeyForDebuggingDisplay('Shift') // '⇧ Shift'\n *\n * // On Windows:\n * formatKeyForDebuggingDisplay('Control') // 'Mod (Ctrl)'\n * formatKeyForDebuggingDisplay('Meta') // 'Win'\n *\n * // Special keys (all platforms):\n * formatKeyForDebuggingDisplay('ArrowUp') // '↑'\n * formatKeyForDebuggingDisplay('Escape') // 'Esc'\n * formatKeyForDebuggingDisplay('Space') // '␣'\n *\n * // Regular keys pass through:\n * formatKeyForDebuggingDisplay('A') // 'A'\n *\n * // With source: 'code', values pass through unchanged:\n * formatKeyForDebuggingDisplay('MetaLeft', { source: 'code' }) // 'MetaLeft'\n * formatKeyForDebuggingDisplay('KeyA', { source: 'code' }) // 'KeyA'\n * ```\n */\nexport function formatKeyForDebuggingDisplay(\n key: string,\n options: FormatKeyDebuggingOptions = {},\n): string {\n // For event.code values, pass through unchanged — they're already\n // descriptive for debugging (e.g. \"MetaLeft\", \"KeyA\", \"ShiftRight\").\n if (options.source === 'code') {\n return key\n }\n\n const platform = options.platform ?? detectPlatform()\n\n // Check if it's a modifier key\n const modLabel = MODIFIER_DEBUG_LABELS[platform]?.[key]\n if (modLabel) {\n // On Mac, prefix modifier labels with their symbol\n if (platform === 'mac') {\n const symbol =\n MAC_MODIFIER_SYMBOLS[key as keyof typeof MAC_MODIFIER_SYMBOLS]\n if (symbol) {\n return `${symbol} ${modLabel}`\n }\n }\n return modLabel\n }\n\n // Check if it's a special key with a display symbol\n const symbol = KEY_DISPLAY_SYMBOLS[key]\n if (symbol) {\n return symbol\n }\n\n // Regular key — pass through\n return key\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAsBA,SAAgB,qBAAqB,UAAiC;AACpE,QAAO,SAAS,KAAK,IAAI;;;;;;;;;;;;;;AAe3B,SAAgB,aAAa,QAA8B;CACzD,MAAM,QAAuB,EAAE;AAG/B,MAAK,MAAM,YAAY,eACrB,KAAI,OAAO,UAAU,SAAS,SAAS,CACrC,OAAM,KAAK,SAAS;AAKxB,OAAM,KAAK,OAAO,IAAI;AAEtB,QAAO,MAAM,KAAK,IAAI;;;;;;;;;;;;;;;;;;;;;;;;AAyBxB,SAAgB,iBACd,QACA,UAAgC,EAAE,EAC1B;CACR,MAAM,WAAW,QAAQ,YAAY,gBAAgB;CACrD,MAAM,SACJ,OAAO,WAAW,WAAW,YAAY,QAAQ,SAA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C5E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6DD,SAAgB,6BACd,KACA,UAAqC,EAAE,EAC/B;AAGR,KAAI,QAAQ,WAAW,OACrB,QAAO;CAGT,MAAM,WAAW,QAAQ,YAAY,gBAAgB;CAGrD,MAAM,WAAW,sBAAsB,YAAY;AACnD,KAAI,UAAU;AAEZ,MAAI,aAAa,OAAO;GACtB,MAAM,SACJ,qBAAqB;AACvB,OAAI,OACF,QAAO,GAAG,OAAO,GAAG;;AAGxB,SAAO;;CAIT,MAAM,SAAS,oBAAoB;AACnC,KAAI,OACF,QAAO;AAIT,QAAO"}
|
|
1
|
+
{"version":3,"file":"format.js","names":[],"sources":["../src/format.ts"],"sourcesContent":["import {\n KEY_DISPLAY_SYMBOLS,\n LINUX_MODIFIER_LABELS,\n MAC_MODIFIER_LABELS,\n MAC_MODIFIER_SYMBOLS,\n MODIFIER_ALIASES,\n MODIFIER_ORDER,\n PUNCTUATION_KEY_DISPLAY_LABELS,\n WINDOWS_MODIFIER_LABELS,\n detectPlatform,\n} from './constants'\nimport {\n isModifierKey,\n normalizeHotkeyFromParsed,\n normalizeRegisterableHotkey,\n} from './parse'\nimport type {\n CanonicalModifier,\n FormatDisplayOptions,\n Hotkey,\n ParsedHotkey,\n RegisterableHotkey,\n} from './hotkey'\n\n/**\n * Converts a hotkey sequence array to a display string.\n *\n * @param sequence - Array of hotkey strings that form the sequence\n * @returns A space-separated string (e.g. ['G','G'] → 'G G')\n *\n * @example\n * ```ts\n * formatHotkeySequence(['G', 'G']) // 'G G'\n * formatHotkeySequence(['D', 'I', 'W']) // 'D I W'\n * ```\n */\nexport function formatHotkeySequence(sequence: Array<Hotkey>): string {\n return sequence.join(' ')\n}\n\n/**\n * Converts a ParsedHotkey back to a hotkey string.\n *\n * @param parsed - The parsed hotkey object\n * @returns A hotkey string in canonical form\n *\n * @example\n * ```ts\n * formatHotkey({ key: 'S', ctrl: true, shift: true, alt: false, meta: false, modifiers: ['Control', 'Shift'] })\n * // Returns: 'Control+Shift+S'\n * ```\n */\nexport function formatHotkey(parsed: ParsedHotkey): string {\n const parts: Array<string> = []\n\n // Add modifiers in canonical order\n for (const modifier of MODIFIER_ORDER) {\n if (parsed.modifiers.includes(modifier)) {\n parts.push(modifier)\n }\n }\n\n // Add the key\n parts.push(parsed.key)\n\n return parts.join('+')\n}\n\n/**\n * Formats a hotkey for display in a user interface.\n *\n * On macOS, uses symbols (⌘⇧S) in the same modifier order as {@link normalizeHotkeyFromParsed}.\n * On Windows/Linux, uses text (Ctrl+Shift+S) with `+` separators.\n *\n * @param hotkey - The hotkey string or ParsedHotkey to format\n * @param options - Formatting options\n * @returns A formatted string suitable for display\n *\n * @example\n * ```ts\n * formatForDisplay('Mod+Shift+S', { platform: 'mac' })\n * // Returns: '⌘ ⇧ S' (symbols separated by spaces on macOS)\n *\n * formatForDisplay('Mod+Shift+S', { platform: 'windows' })\n * // Returns: 'Ctrl+Shift+S'\n *\n * formatForDisplay('Escape')\n * // Returns: 'Esc' (on all platforms)\n * ```\n */\nexport function formatForDisplay(\n hotkey: RegisterableHotkey | (string & {}),\n options: FormatDisplayOptions = {},\n): string {\n const platform = options.platform ?? detectPlatform()\n const useSymbols = options.useSymbols ?? true\n const normalizedHotkey = normalizeRegisterableHotkey(\n hotkey as RegisterableHotkey,\n platform,\n )\n return normalizedHotkey\n .split('+')\n .map((segment) => {\n if (isModifierKey(segment)) {\n const modifierToken = (MODIFIER_ALIASES[segment] ??\n MODIFIER_ALIASES[segment.toLowerCase()]) as CanonicalModifier | 'Mod'\n return platform === 'mac'\n ? useSymbols\n ? MAC_MODIFIER_SYMBOLS[modifierToken]\n : MAC_MODIFIER_LABELS[modifierToken]\n : platform === 'windows'\n ? WINDOWS_MODIFIER_LABELS[modifierToken]\n : LINUX_MODIFIER_LABELS[modifierToken]\n } else {\n const keyDisplaySymbol =\n useSymbols &&\n KEY_DISPLAY_SYMBOLS[segment as keyof typeof KEY_DISPLAY_SYMBOLS]\n if (keyDisplaySymbol) return keyDisplaySymbol\n\n const punctuationKeyDisplayLabel =\n !useSymbols &&\n PUNCTUATION_KEY_DISPLAY_LABELS[\n segment as keyof typeof PUNCTUATION_KEY_DISPLAY_LABELS\n ]\n return punctuationKeyDisplayLabel || segment\n }\n })\n .join(platform === 'mac' && useSymbols ? ' ' : '+')\n}\n\n/**\n * @deprecated Use {@link formatForDisplay} instead with `useSymbols: false` option.\n */\nexport function formatWithLabels(\n hotkey: RegisterableHotkey,\n options: Omit<FormatDisplayOptions, 'useSymbols'> = {},\n): string {\n return formatForDisplay(hotkey, { ...options, useSymbols: false })\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAoCA,SAAgB,qBAAqB,UAAiC;AACpE,QAAO,SAAS,KAAK,IAAI;;;;;;;;;;;;;;AAe3B,SAAgB,aAAa,QAA8B;CACzD,MAAM,QAAuB,EAAE;AAG/B,MAAK,MAAM,YAAY,eACrB,KAAI,OAAO,UAAU,SAAS,SAAS,CACrC,OAAM,KAAK,SAAS;AAKxB,OAAM,KAAK,OAAO,IAAI;AAEtB,QAAO,MAAM,KAAK,IAAI;;;;;;;;;;;;;;;;;;;;;;;;AAyBxB,SAAgB,iBACd,QACA,UAAgC,EAAE,EAC1B;CACR,MAAM,WAAW,QAAQ,YAAY,gBAAgB;CACrD,MAAM,aAAa,QAAQ,cAAc;AAKzC,QAJyB,4BACvB,QACA,SACD,CAEE,MAAM,IAAI,CACV,KAAK,YAAY;AAChB,MAAI,cAAc,QAAQ,EAAE;GAC1B,MAAM,gBAAiB,iBAAiB,YACtC,iBAAiB,QAAQ,aAAa;AACxC,UAAO,aAAa,QAChB,aACE,qBAAqB,iBACrB,oBAAoB,iBACtB,aAAa,YACX,wBAAwB,iBACxB,sBAAsB;SACvB;GACL,MAAM,mBACJ,cACA,oBAAoB;AACtB,OAAI,iBAAkB,QAAO;AAO7B,UAJE,CAAC,cACD,+BACE,YAEiC;;GAEvC,CACD,KAAK,aAAa,SAAS,aAAa,MAAM,IAAI;;;;;AAMvD,SAAgB,iBACd,QACA,UAAoD,EAAE,EAC9C;AACR,QAAO,iBAAiB,QAAQ;EAAE,GAAG;EAAS,YAAY;EAAO,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hotkey-manager.cjs","names":["#instance","Store","#platform","detectPlatform","parseHotkey","rawHotkeyToParsedHotkey","formatHotkey","#findConflictingRegistration","#unregister","getDefaultIgnoreInputs","defaultHotkeyOptions","#targetRegistrations","#ensureListenersForTarget","#removeListenersForTarget","#targetListeners","#createTargetKeyDownHandler","#createTargetKeyUpHandler","isEventForTarget","isInputElement","matchesKeyboardEvent","#executeHotkeyCallback","#shouldResetRegistration","#processTargetEvent","normalizeKeyName"],"sources":["../src/hotkey-manager.ts"],"sourcesContent":["import { Store } from '@tanstack/store'\nimport { detectPlatform, normalizeKeyName } from './constants'\nimport { formatHotkey } from './format'\nimport { parseHotkey, rawHotkeyToParsedHotkey } from './parse'\nimport { matchesKeyboardEvent } from './match'\nimport {\n defaultHotkeyOptions,\n getDefaultIgnoreInputs,\n handleConflict,\n isEventForTarget,\n isInputElement,\n} from './manager.utils'\nimport type { ConflictBehavior } from './manager.utils'\nimport type {\n Hotkey,\n HotkeyCallback,\n HotkeyCallbackContext,\n ParsedHotkey,\n RegisterableHotkey,\n} from './hotkey'\n\nexport type { ConflictBehavior }\n\n/**\n * Options for registering a hotkey.\n */\nexport interface HotkeyOptions {\n /** Behavior when this hotkey conflicts with an existing registration on the same target. Defaults to 'warn' */\n conflictBehavior?: ConflictBehavior\n /** Whether the hotkey is enabled. Defaults to true */\n enabled?: boolean\n /** The event type to listen for. Defaults to 'keydown' */\n eventType?: 'keydown' | 'keyup'\n /** Whether to ignore hotkeys when keyboard events originate from input-like elements (text inputs, textarea, select, contenteditable — button-type inputs like type=button/submit/reset are not ignored). Defaults based on hotkey: true for single keys and Shift/Alt combos; false for Ctrl/Meta shortcuts and Escape */\n ignoreInputs?: boolean\n /** The target platform for resolving 'Mod' */\n platform?: 'mac' | 'windows' | 'linux'\n /** Prevent the default browser action when the hotkey matches. Defaults to true */\n preventDefault?: boolean\n /** If true, only trigger once until all keys are released. Default: false */\n requireReset?: boolean\n /** Stop event propagation when the hotkey matches. Defaults to true */\n stopPropagation?: boolean\n /** The DOM element to attach the event listener to. Defaults to document. */\n target?: HTMLElement | Document | Window | null\n}\n\n/**\n * A registered hotkey handler in the HotkeyManager.\n */\nexport interface HotkeyRegistration {\n /** The callback to invoke */\n callback: HotkeyCallback\n /** Whether this registration has fired and needs reset (for requireReset) */\n hasFired: boolean\n /** The original hotkey string */\n hotkey: Hotkey\n /** Unique identifier for this registration */\n id: string\n /** Options for this registration */\n options: HotkeyOptions\n /** The parsed hotkey */\n parsedHotkey: ParsedHotkey\n /** The resolved target element for this registration */\n target: HTMLElement | Document | Window\n /** How many times this registration's callback has been triggered */\n triggerCount: number\n}\n\n/**\n * A handle returned from HotkeyManager.register() that allows updating\n * the callback and options without re-registering the hotkey.\n *\n * @example\n * ```ts\n * const handle = manager.register('Mod+S', callback, options)\n *\n * // Update callback without re-registering (avoids stale closures)\n * handle.callback = newCallback\n *\n * // Update options without re-registering\n * handle.setOptions({ enabled: false })\n *\n * // Check if still active\n * if (handle.isActive) {\n * // ...\n * }\n *\n * // Unregister when done\n * handle.unregister()\n * ```\n */\nexport interface HotkeyRegistrationHandle {\n /**\n * The callback function. Can be set directly to update without re-registering.\n * This avoids stale closures when the callback references React state.\n */\n callback: HotkeyCallback\n /** Unique identifier for this registration */\n readonly id: string\n /** Check if this registration is still active (not unregistered) */\n readonly isActive: boolean\n /**\n * Update options (merged with existing options).\n * Useful for updating `enabled`, `preventDefault`, etc. without re-registering.\n */\n setOptions: (options: Partial<HotkeyOptions>) => void\n /** Unregister this hotkey */\n unregister: () => void\n}\n\nlet registrationIdCounter = 0\n\n/**\n * Generates a unique ID for hotkey registrations.\n */\nfunction generateId(): string {\n return `hotkey_${++registrationIdCounter}`\n}\n\n/**\n * Singleton manager for hotkey registrations.\n *\n * This class provides a centralized way to register and manage keyboard hotkeys.\n * It uses a single event listener for efficiency, regardless of how many hotkeys\n * are registered.\n *\n * @example\n * ```ts\n * const manager = HotkeyManager.getInstance()\n *\n * const unregister = manager.register('Mod+S', (event, context) => {\n * console.log('Save triggered!')\n * })\n *\n * // Later, to unregister:\n * unregister()\n * ```\n */\nexport class HotkeyManager {\n static #instance: HotkeyManager | null = null\n\n /**\n * The TanStack Store containing all hotkey registrations.\n * Use this to subscribe to registration changes or access current registrations.\n *\n * @example\n * ```ts\n * const manager = HotkeyManager.getInstance()\n *\n * // Subscribe to registration changes\n * const unsubscribe = manager.registrations.subscribe(() => {\n * console.log('Registrations changed:', manager.registrations.state.size)\n * })\n *\n * // Access current registrations\n * for (const [id, reg] of manager.registrations.state) {\n * console.log(reg.hotkey, reg.options.enabled)\n * }\n * ```\n */\n readonly registrations: Store<Map<string, HotkeyRegistration>> = new Store(\n new Map(),\n )\n #platform: 'mac' | 'windows' | 'linux'\n #targetListeners: Map<\n HTMLElement | Document | Window,\n {\n keydown: (event: KeyboardEvent) => void\n keyup: (event: KeyboardEvent) => void\n }\n > = new Map()\n #targetRegistrations: Map<HTMLElement | Document | Window, Set<string>> =\n new Map()\n\n private constructor() {\n this.#platform = detectPlatform()\n }\n\n /**\n * Gets the singleton instance of HotkeyManager.\n */\n static getInstance(): HotkeyManager {\n if (!HotkeyManager.#instance) {\n HotkeyManager.#instance = new HotkeyManager()\n }\n return HotkeyManager.#instance\n }\n\n /**\n * Resets the singleton instance. Useful for testing.\n */\n static resetInstance(): void {\n if (HotkeyManager.#instance) {\n HotkeyManager.#instance.destroy()\n HotkeyManager.#instance = null\n }\n }\n\n /**\n * Registers a hotkey handler and returns a handle for updating the registration.\n *\n * The returned handle allows updating the callback and options without\n * re-registering, which is useful for avoiding stale closures in React.\n *\n * @param hotkey - The hotkey string (e.g., 'Mod+S') or RawHotkey object\n * @param callback - The function to call when the hotkey is pressed\n * @param options - Options for the hotkey behavior\n * @returns A handle for managing the registration\n *\n * @example\n * ```ts\n * const handle = manager.register('Mod+S', callback)\n *\n * // Update callback without re-registering (avoids stale closures)\n * handle.callback = newCallback\n *\n * // Update options\n * handle.setOptions({ enabled: false })\n *\n * // Unregister when done\n * handle.unregister()\n * ```\n */\n register(\n hotkey: RegisterableHotkey,\n callback: HotkeyCallback,\n options: HotkeyOptions = {},\n ): HotkeyRegistrationHandle {\n // In SSR environments, return a no-op handle since there's no DOM to attach listeners to\n if (typeof document === 'undefined' && !options.target) {\n let currentCallback = callback\n return {\n id: generateId(),\n unregister: () => {},\n get callback() {\n return currentCallback\n },\n set callback(newCallback: HotkeyCallback) {\n currentCallback = newCallback\n },\n setOptions: () => {},\n get isActive() {\n return false\n },\n }\n }\n\n const id = generateId()\n const platform = options.platform ?? this.#platform\n const parsedHotkey =\n typeof hotkey === 'string'\n ? parseHotkey(hotkey, platform)\n : rawHotkeyToParsedHotkey(hotkey, platform)\n const hotkeyStr = (\n typeof hotkey === 'string' ? hotkey : formatHotkey(parsedHotkey)\n ) as Hotkey\n\n // Resolve target: default to document if not provided\n // Note: SSR case without explicit target is handled above\n const target = options.target ?? document\n\n // Resolve conflict behavior\n const conflictBehavior = options.conflictBehavior ?? 'warn'\n\n // Check for existing registrations with the same hotkey and target\n const conflictingRegistration = this.#findConflictingRegistration(\n hotkeyStr,\n target,\n )\n\n if (conflictingRegistration) {\n handleConflict(\n conflictingRegistration.id,\n hotkeyStr,\n conflictBehavior,\n (id) => this.#unregister(id),\n )\n }\n\n const resolvedIgnoreInputs =\n options.ignoreInputs ?? getDefaultIgnoreInputs(parsedHotkey)\n\n const baseOptions = {\n ...defaultHotkeyOptions,\n requireReset: false,\n ...options,\n platform,\n }\n\n const registration: HotkeyRegistration = {\n id,\n hotkey: hotkeyStr,\n parsedHotkey,\n callback,\n options: { ...baseOptions, ignoreInputs: resolvedIgnoreInputs },\n hasFired: false,\n triggerCount: 0,\n target,\n }\n\n this.registrations.setState((prev) => new Map(prev).set(id, registration))\n\n // Track registration for this target\n if (!this.#targetRegistrations.has(target)) {\n this.#targetRegistrations.set(target, new Set())\n }\n this.#targetRegistrations.get(target)!.add(id)\n\n // Ensure listeners are attached for this target\n this.#ensureListenersForTarget(target)\n\n // Create and return the handle\n const manager = this\n const handle: HotkeyRegistrationHandle = {\n get id() {\n return id\n },\n unregister: () => {\n manager.#unregister(id)\n },\n get callback() {\n const reg = manager.registrations.state.get(id)\n return reg?.callback ?? callback\n },\n set callback(newCallback: HotkeyCallback) {\n const reg = manager.registrations.state.get(id)\n if (reg) {\n reg.callback = newCallback\n }\n },\n setOptions: (newOptions: Partial<HotkeyOptions>) => {\n manager.registrations.setState((prev) => {\n const reg = prev.get(id)\n if (reg) {\n const next = new Map(prev)\n next.set(id, { ...reg, options: { ...reg.options, ...newOptions } })\n return next\n }\n return prev\n })\n },\n get isActive() {\n return manager.registrations.state.has(id)\n },\n }\n\n return handle\n }\n\n /**\n * Unregisters a hotkey by its registration ID.\n */\n #unregister(id: string): void {\n const registration = this.registrations.state.get(id)\n if (!registration) {\n return\n }\n\n const target = registration.target\n\n // Remove registration\n this.registrations.setState((prev) => {\n const next = new Map(prev)\n next.delete(id)\n return next\n })\n\n // Remove from target registrations tracking\n const targetRegs = this.#targetRegistrations.get(target)\n if (targetRegs) {\n targetRegs.delete(id)\n // If no more registrations for this target, remove listeners\n if (targetRegs.size === 0) {\n this.#removeListenersForTarget(target)\n }\n }\n }\n\n /**\n * Ensures event listeners are attached for a specific target.\n */\n #ensureListenersForTarget(target: HTMLElement | Document | Window): void {\n if (typeof document === 'undefined') {\n return // SSR safety\n }\n\n // Skip if listeners already exist for this target\n if (this.#targetListeners.has(target)) {\n return\n }\n\n const keydownHandler = this.#createTargetKeyDownHandler(target)\n const keyupHandler = this.#createTargetKeyUpHandler(target)\n\n target.addEventListener('keydown', keydownHandler as EventListener)\n target.addEventListener('keyup', keyupHandler as EventListener)\n\n this.#targetListeners.set(target, {\n keydown: keydownHandler,\n keyup: keyupHandler,\n })\n }\n\n /**\n * Removes event listeners for a specific target.\n */\n #removeListenersForTarget(target: HTMLElement | Document | Window): void {\n if (typeof document === 'undefined') {\n return\n }\n\n const listeners = this.#targetListeners.get(target)\n if (!listeners) {\n return\n }\n\n target.removeEventListener('keydown', listeners.keydown as EventListener)\n target.removeEventListener('keyup', listeners.keyup as EventListener)\n\n this.#targetListeners.delete(target)\n this.#targetRegistrations.delete(target)\n }\n\n /**\n * Processes keyboard events for a specific target and event type.\n */\n #processTargetEvent(\n event: KeyboardEvent,\n target: HTMLElement | Document | Window,\n eventType: 'keydown' | 'keyup',\n ): void {\n const targetRegs = this.#targetRegistrations.get(target)\n if (!targetRegs) {\n return\n }\n\n for (const id of targetRegs) {\n const registration = this.registrations.state.get(id)\n if (!registration) {\n continue\n }\n\n // Check if event originated from or bubbled to this target\n if (!isEventForTarget(event, target)) {\n continue\n }\n\n if (!registration.options.enabled) {\n continue\n }\n\n // Check if we should ignore input elements (defaults to true)\n if (registration.options.ignoreInputs !== false) {\n if (isInputElement(event.target)) {\n // Don't ignore if the hotkey is explicitly scoped to this input element\n if (event.target !== registration.target) {\n continue\n }\n }\n }\n\n // Handle keydown events\n if (eventType === 'keydown') {\n if (registration.options.eventType !== 'keydown') {\n continue\n }\n\n // Check if the hotkey matches first\n const matches = matchesKeyboardEvent(\n event,\n registration.parsedHotkey,\n registration.options.platform,\n )\n\n if (matches) {\n // Always apply preventDefault/stopPropagation if the hotkey matches,\n // even when requireReset is active and has already fired\n if (registration.options.preventDefault) {\n event.preventDefault()\n }\n if (registration.options.stopPropagation) {\n event.stopPropagation()\n }\n\n // Only execute callback if requireReset is not active or hasn't fired yet\n if (!registration.options.requireReset || !registration.hasFired) {\n this.#executeHotkeyCallback(registration, event)\n\n // Mark as fired if requireReset is enabled\n if (registration.options.requireReset) {\n registration.hasFired = true\n }\n }\n }\n }\n // Handle keyup events\n else {\n if (registration.options.eventType === 'keyup') {\n if (\n matchesKeyboardEvent(\n event,\n registration.parsedHotkey,\n registration.options.platform,\n )\n ) {\n this.#executeHotkeyCallback(registration, event)\n }\n }\n\n // Reset hasFired when any key in the hotkey is released\n if (registration.options.requireReset && registration.hasFired) {\n if (this.#shouldResetRegistration(registration, event)) {\n registration.hasFired = false\n }\n }\n }\n }\n }\n\n /**\n * Executes a hotkey callback with proper event handling.\n */\n #executeHotkeyCallback(\n registration: HotkeyRegistration,\n event: KeyboardEvent,\n ): void {\n if (registration.options.preventDefault) {\n event.preventDefault()\n }\n if (registration.options.stopPropagation) {\n event.stopPropagation()\n }\n\n registration.triggerCount++\n\n // Notify the store so subscribers (e.g. devtools) see the updated count.\n // We create a new Map but keep the same registration reference to preserve\n // identity for mutation-based fields like hasFired.\n this.registrations.setState((prev) => new Map(prev))\n\n const context: HotkeyCallbackContext = {\n hotkey: registration.hotkey,\n parsedHotkey: registration.parsedHotkey,\n }\n\n registration.callback(event, context)\n }\n\n /**\n * Creates a keydown handler for a specific target.\n */\n #createTargetKeyDownHandler(\n target: HTMLElement | Document | Window,\n ): (event: KeyboardEvent) => void {\n return (event: KeyboardEvent) => {\n this.#processTargetEvent(event, target, 'keydown')\n }\n }\n\n /**\n * Creates a keyup handler for a specific target.\n */\n #createTargetKeyUpHandler(\n target: HTMLElement | Document | Window,\n ): (event: KeyboardEvent) => void {\n return (event: KeyboardEvent) => {\n this.#processTargetEvent(event, target, 'keyup')\n }\n }\n\n /**\n * Finds an existing registration with the same hotkey and target.\n */\n #findConflictingRegistration(\n hotkey: Hotkey,\n target: HTMLElement | Document | Window,\n ): HotkeyRegistration | null {\n for (const registration of this.registrations.state.values()) {\n if (registration.hotkey === hotkey && registration.target === target) {\n return registration\n }\n }\n return null\n }\n\n /**\n * Determines if a registration should be reset based on the keyup event.\n */\n #shouldResetRegistration(\n registration: HotkeyRegistration,\n event: KeyboardEvent,\n ): boolean {\n const parsed = registration.parsedHotkey\n const releasedKey = normalizeKeyName(event.key)\n\n // Reset if the main key is released\n // Compare case-insensitively for single-letter keys\n const parsedKeyNormalized =\n parsed.key.length === 1 ? parsed.key.toUpperCase() : parsed.key\n const releasedKeyNormalized =\n releasedKey.length === 1 ? releasedKey.toUpperCase() : releasedKey\n\n if (releasedKeyNormalized === parsedKeyNormalized) {\n return true\n }\n\n // Reset if any required modifier is released\n // Use normalized key names and check against canonical modifier names\n if (parsed.ctrl && releasedKey === 'Control') {\n return true\n }\n if (parsed.shift && releasedKey === 'Shift') {\n return true\n }\n if (parsed.alt && releasedKey === 'Alt') {\n return true\n }\n if (parsed.meta && releasedKey === 'Meta') {\n return true\n }\n\n return false\n }\n\n /**\n * Triggers a registration's callback programmatically from devtools.\n * Creates a synthetic KeyboardEvent and invokes the callback.\n *\n * @param id - The registration ID to trigger\n * @returns True if the registration was found and triggered\n */\n triggerRegistration(id: string): boolean {\n const registration = this.registrations.state.get(id)\n if (!registration) {\n return false\n }\n\n const parsed = registration.parsedHotkey\n const syntheticEvent = new KeyboardEvent(\n registration.options.eventType ?? 'keydown',\n {\n key: parsed.key,\n ctrlKey: parsed.ctrl,\n shiftKey: parsed.shift,\n altKey: parsed.alt,\n metaKey: parsed.meta,\n bubbles: true,\n cancelable: true,\n },\n )\n\n registration.triggerCount++\n\n // Notify the store so subscribers (e.g. devtools) see the updated count\n this.registrations.setState((prev) => new Map(prev))\n\n registration.callback(syntheticEvent, {\n hotkey: registration.hotkey,\n parsedHotkey: registration.parsedHotkey,\n })\n\n return true\n }\n\n /**\n * Gets the number of registered hotkeys.\n */\n getRegistrationCount(): number {\n return this.registrations.state.size\n }\n\n /**\n * Checks if a specific hotkey is registered.\n *\n * @param hotkey - The hotkey string to check\n * @param target - Optional target element to match (if provided, both hotkey and target must match)\n * @returns True if a matching registration exists\n */\n isRegistered(\n hotkey: Hotkey,\n target?: HTMLElement | Document | Window,\n ): boolean {\n for (const registration of this.registrations.state.values()) {\n if (registration.hotkey === hotkey) {\n // If target is specified, both must match\n if (target === undefined || registration.target === target) {\n return true\n }\n }\n }\n return false\n }\n\n /**\n * Destroys the manager and removes all listeners.\n */\n destroy(): void {\n // Remove all target listeners\n for (const target of this.#targetListeners.keys()) {\n this.#removeListenersForTarget(target)\n }\n\n this.registrations.setState(() => new Map())\n this.#targetListeners.clear()\n this.#targetRegistrations.clear()\n }\n}\n\n/**\n * Gets the singleton HotkeyManager instance.\n * Convenience function for accessing the manager.\n */\nexport function getHotkeyManager(): HotkeyManager {\n return HotkeyManager.getInstance()\n}\n"],"mappings":";;;;;;;;AA+GA,IAAI,wBAAwB;;;;AAK5B,SAAS,aAAqB;AAC5B,QAAO,UAAU,EAAE;;;;;;;;;;;;;;;;;;;;;AAsBrB,IAAa,gBAAb,MAAa,cAAc;CACzB,QAAOA,WAAkC;CAwBzC;CACA,mCAMI,IAAI,KAAK;CACb,uCACE,IAAI,KAAK;CAEX,AAAQ,cAAc;uBAd2C,IAAIC,sCACnE,IAAI,KAAK,CACV;AAaC,QAAKC,WAAYC,kCAAgB;;;;;CAMnC,OAAO,cAA6B;AAClC,MAAI,CAAC,eAAcH,SACjB,gBAAcA,WAAY,IAAI,eAAe;AAE/C,SAAO,eAAcA;;;;;CAMvB,OAAO,gBAAsB;AAC3B,MAAI,eAAcA,UAAW;AAC3B,kBAAcA,SAAU,SAAS;AACjC,kBAAcA,WAAY;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6B9B,SACE,QACA,UACA,UAAyB,EAAE,EACD;AAE1B,MAAI,OAAO,aAAa,eAAe,CAAC,QAAQ,QAAQ;GACtD,IAAI,kBAAkB;AACtB,UAAO;IACL,IAAI,YAAY;IAChB,kBAAkB;IAClB,IAAI,WAAW;AACb,YAAO;;IAET,IAAI,SAAS,aAA6B;AACxC,uBAAkB;;IAEpB,kBAAkB;IAClB,IAAI,WAAW;AACb,YAAO;;IAEV;;EAGH,MAAM,KAAK,YAAY;EACvB,MAAM,WAAW,QAAQ,YAAY,MAAKE;EAC1C,MAAM,eACJ,OAAO,WAAW,WACdE,0BAAY,QAAQ,SAAS,GAC7BC,sCAA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Q,CAC1D,KAAI,aAAa,WAAW,QAE1B;OAAI,WAAW,UAAa,aAAa,WAAW,OAClD,QAAO;;AAIb,SAAO;;;;;CAMT,UAAgB;AAEd,OAAK,MAAM,UAAU,MAAKT,gBAAiB,MAAM,CAC/C,OAAKD,yBAA0B,OAAO;AAGxC,OAAK,cAAc,+BAAe,IAAI,KAAK,CAAC;AAC5C,QAAKC,gBAAiB,OAAO;AAC7B,QAAKH,oBAAqB,OAAO;;;;;;;AAQrC,SAAgB,mBAAkC;AAChD,QAAO,cAAc,aAAa"}
|
|
1
|
+
{"version":3,"file":"hotkey-manager.cjs","names":["#instance","Store","#platform","detectPlatform","parseHotkey","rawHotkeyToParsedHotkey","formatHotkey","#findConflictingRegistration","#unregister","getDefaultIgnoreInputs","defaultHotkeyOptions","#targetRegistrations","#ensureListenersForTarget","#removeListenersForTarget","#targetListeners","#createTargetKeyDownHandler","#createTargetKeyUpHandler","isEventForTarget","isInputElement","matchesKeyboardEvent","#executeHotkeyCallback","#shouldResetRegistration","#processTargetEvent","normalizeKeyName"],"sources":["../src/hotkey-manager.ts"],"sourcesContent":["import { Store } from '@tanstack/store'\nimport { detectPlatform, normalizeKeyName } from './constants'\nimport { formatHotkey } from './format'\nimport { parseHotkey, rawHotkeyToParsedHotkey } from './parse'\nimport { matchesKeyboardEvent } from './match'\nimport {\n defaultHotkeyOptions,\n getDefaultIgnoreInputs,\n handleConflict,\n isEventForTarget,\n isInputElement,\n} from './manager.utils'\nimport type { ConflictBehavior } from './manager.utils'\nimport type {\n Hotkey,\n HotkeyCallback,\n HotkeyCallbackContext,\n ParsedHotkey,\n RegisterableHotkey,\n} from './hotkey'\n\nexport type { ConflictBehavior }\n\n/**\n * Options for registering a hotkey.\n */\nexport interface HotkeyOptions {\n /** Behavior when this hotkey conflicts with an existing registration on the same target. Defaults to 'warn' */\n conflictBehavior?: ConflictBehavior\n /**\n * Soft-disable: when `false`, the callback does not run but the registration\n * stays in `HotkeyManager` (and in devtools). Toggling this should update the\n * existing handle via `setOptions` rather than unregistering. Defaults to `true`.\n */\n enabled?: boolean\n /** The event type to listen for. Defaults to 'keydown' */\n eventType?: 'keydown' | 'keyup'\n /** Whether to ignore hotkeys when keyboard events originate from input-like elements (text inputs, textarea, select, contenteditable — button-type inputs like type=button/submit/reset are not ignored). Defaults based on hotkey: true for single keys and Shift/Alt combos; false for Ctrl/Meta shortcuts and Escape */\n ignoreInputs?: boolean\n /** The target platform for resolving 'Mod' */\n platform?: 'mac' | 'windows' | 'linux'\n /** Prevent the default browser action when the hotkey matches. Defaults to true */\n preventDefault?: boolean\n /** If true, only trigger once until all keys are released. Default: false */\n requireReset?: boolean\n /** Stop event propagation when the hotkey matches. Defaults to true */\n stopPropagation?: boolean\n /** The DOM element to attach the event listener to. Defaults to document. */\n target?: HTMLElement | Document | Window | null\n}\n\n/**\n * A registered hotkey handler in the HotkeyManager.\n */\nexport interface HotkeyRegistration {\n /** The callback to invoke */\n callback: HotkeyCallback\n /** Whether this registration has fired and needs reset (for requireReset) */\n hasFired: boolean\n /** The original hotkey string */\n hotkey: Hotkey\n /** Unique identifier for this registration */\n id: string\n /** Options for this registration */\n options: HotkeyOptions\n /** The parsed hotkey */\n parsedHotkey: ParsedHotkey\n /** The resolved target element for this registration */\n target: HTMLElement | Document | Window\n /** How many times this registration's callback has been triggered */\n triggerCount: number\n}\n\n/**\n * A handle returned from HotkeyManager.register() that allows updating\n * the callback and options without re-registering the hotkey.\n *\n * @example\n * ```ts\n * const handle = manager.register('Mod+S', callback, options)\n *\n * // Update callback without re-registering (avoids stale closures)\n * handle.callback = newCallback\n *\n * // Update options without re-registering\n * handle.setOptions({ enabled: false })\n *\n * // Check if still active\n * if (handle.isActive) {\n * // ...\n * }\n *\n * // Unregister when done\n * handle.unregister()\n * ```\n */\nexport interface HotkeyRegistrationHandle {\n /**\n * The callback function. Can be set directly to update without re-registering.\n * This avoids stale closures when the callback references React state.\n */\n callback: HotkeyCallback\n /** Unique identifier for this registration */\n readonly id: string\n /** Check if this registration is still active (not unregistered) */\n readonly isActive: boolean\n /**\n * Update options (merged with existing options).\n * Useful for updating `enabled`, `preventDefault`, etc. without re-registering.\n */\n setOptions: (options: Partial<HotkeyOptions>) => void\n /** Unregister this hotkey */\n unregister: () => void\n}\n\nlet registrationIdCounter = 0\n\n/**\n * Generates a unique ID for hotkey registrations.\n */\nfunction generateId(): string {\n return `hotkey_${++registrationIdCounter}`\n}\n\n/**\n * Singleton manager for hotkey registrations.\n *\n * This class provides a centralized way to register and manage keyboard hotkeys.\n * It uses a single event listener for efficiency, regardless of how many hotkeys\n * are registered.\n *\n * @example\n * ```ts\n * const manager = HotkeyManager.getInstance()\n *\n * const unregister = manager.register('Mod+S', (event, context) => {\n * console.log('Save triggered!')\n * })\n *\n * // Later, to unregister:\n * unregister()\n * ```\n */\nexport class HotkeyManager {\n static #instance: HotkeyManager | null = null\n\n /**\n * The TanStack Store containing all hotkey registrations.\n * Use this to subscribe to registration changes or access current registrations.\n *\n * @example\n * ```ts\n * const manager = HotkeyManager.getInstance()\n *\n * // Subscribe to registration changes\n * const unsubscribe = manager.registrations.subscribe(() => {\n * console.log('Registrations changed:', manager.registrations.state.size)\n * })\n *\n * // Access current registrations\n * for (const [id, reg] of manager.registrations.state) {\n * console.log(reg.hotkey, reg.options.enabled)\n * }\n * ```\n */\n readonly registrations: Store<Map<string, HotkeyRegistration>> = new Store(\n new Map(),\n )\n #platform: 'mac' | 'windows' | 'linux'\n #targetListeners: Map<\n HTMLElement | Document | Window,\n {\n keydown: (event: KeyboardEvent) => void\n keyup: (event: KeyboardEvent) => void\n }\n > = new Map()\n #targetRegistrations: Map<HTMLElement | Document | Window, Set<string>> =\n new Map()\n\n private constructor() {\n this.#platform = detectPlatform()\n }\n\n /**\n * Gets the singleton instance of HotkeyManager.\n */\n static getInstance(): HotkeyManager {\n if (!HotkeyManager.#instance) {\n HotkeyManager.#instance = new HotkeyManager()\n }\n return HotkeyManager.#instance\n }\n\n /**\n * Resets the singleton instance. Useful for testing.\n */\n static resetInstance(): void {\n if (HotkeyManager.#instance) {\n HotkeyManager.#instance.destroy()\n HotkeyManager.#instance = null\n }\n }\n\n /**\n * Registers a hotkey handler and returns a handle for updating the registration.\n *\n * The returned handle allows updating the callback and options without\n * re-registering, which is useful for avoiding stale closures in React.\n *\n * @param hotkey - The hotkey string (e.g., 'Mod+S') or RawHotkey object\n * @param callback - The function to call when the hotkey is pressed\n * @param options - Options for the hotkey behavior\n * @returns A handle for managing the registration\n *\n * @example\n * ```ts\n * const handle = manager.register('Mod+S', callback)\n *\n * // Update callback without re-registering (avoids stale closures)\n * handle.callback = newCallback\n *\n * // Update options\n * handle.setOptions({ enabled: false })\n *\n * // Unregister when done\n * handle.unregister()\n * ```\n */\n register(\n hotkey: RegisterableHotkey,\n callback: HotkeyCallback,\n options: HotkeyOptions = {},\n ): HotkeyRegistrationHandle {\n // In SSR environments, return a no-op handle since there's no DOM to attach listeners to\n if (typeof document === 'undefined' && !options.target) {\n let currentCallback = callback\n return {\n id: generateId(),\n unregister: () => {},\n get callback() {\n return currentCallback\n },\n set callback(newCallback: HotkeyCallback) {\n currentCallback = newCallback\n },\n setOptions: () => {},\n get isActive() {\n return false\n },\n }\n }\n\n const id = generateId()\n const platform = options.platform ?? this.#platform\n const parsedHotkey =\n typeof hotkey === 'string'\n ? parseHotkey(hotkey, platform)\n : rawHotkeyToParsedHotkey(hotkey, platform)\n const hotkeyStr = (\n typeof hotkey === 'string' ? hotkey : formatHotkey(parsedHotkey)\n ) as Hotkey\n\n // Resolve target: default to document if not provided\n // Note: SSR case without explicit target is handled above\n const target = options.target ?? document\n\n // Resolve conflict behavior\n const conflictBehavior = options.conflictBehavior ?? 'warn'\n\n // Check for existing registrations with the same hotkey and target\n const conflictingRegistration = this.#findConflictingRegistration(\n hotkeyStr,\n target,\n )\n\n if (conflictingRegistration) {\n handleConflict(\n conflictingRegistration.id,\n hotkeyStr,\n conflictBehavior,\n (id) => this.#unregister(id),\n )\n }\n\n const resolvedIgnoreInputs =\n options.ignoreInputs ?? getDefaultIgnoreInputs(parsedHotkey)\n\n const baseOptions = {\n ...defaultHotkeyOptions,\n requireReset: false,\n ...options,\n platform,\n }\n\n const registration: HotkeyRegistration = {\n id,\n hotkey: hotkeyStr,\n parsedHotkey,\n callback,\n options: { ...baseOptions, ignoreInputs: resolvedIgnoreInputs },\n hasFired: false,\n triggerCount: 0,\n target,\n }\n\n this.registrations.setState((prev) => new Map(prev).set(id, registration))\n\n // Track registration for this target\n if (!this.#targetRegistrations.has(target)) {\n this.#targetRegistrations.set(target, new Set())\n }\n this.#targetRegistrations.get(target)!.add(id)\n\n // Ensure listeners are attached for this target\n this.#ensureListenersForTarget(target)\n\n // Create and return the handle\n const manager = this\n const handle: HotkeyRegistrationHandle = {\n get id() {\n return id\n },\n unregister: () => {\n manager.#unregister(id)\n },\n get callback() {\n const reg = manager.registrations.state.get(id)\n return reg?.callback ?? callback\n },\n set callback(newCallback: HotkeyCallback) {\n const reg = manager.registrations.state.get(id)\n if (reg) {\n reg.callback = newCallback\n }\n },\n setOptions: (newOptions: Partial<HotkeyOptions>) => {\n manager.registrations.setState((prev) => {\n const reg = prev.get(id)\n if (reg) {\n const next = new Map(prev)\n next.set(id, { ...reg, options: { ...reg.options, ...newOptions } })\n return next\n }\n return prev\n })\n },\n get isActive() {\n return manager.registrations.state.has(id)\n },\n }\n\n return handle\n }\n\n /**\n * Unregisters a hotkey by its registration ID.\n */\n #unregister(id: string): void {\n const registration = this.registrations.state.get(id)\n if (!registration) {\n return\n }\n\n const target = registration.target\n\n // Remove registration\n this.registrations.setState((prev) => {\n const next = new Map(prev)\n next.delete(id)\n return next\n })\n\n // Remove from target registrations tracking\n const targetRegs = this.#targetRegistrations.get(target)\n if (targetRegs) {\n targetRegs.delete(id)\n // If no more registrations for this target, remove listeners\n if (targetRegs.size === 0) {\n this.#removeListenersForTarget(target)\n }\n }\n }\n\n /**\n * Ensures event listeners are attached for a specific target.\n */\n #ensureListenersForTarget(target: HTMLElement | Document | Window): void {\n if (typeof document === 'undefined') {\n return // SSR safety\n }\n\n // Skip if listeners already exist for this target\n if (this.#targetListeners.has(target)) {\n return\n }\n\n const keydownHandler = this.#createTargetKeyDownHandler(target)\n const keyupHandler = this.#createTargetKeyUpHandler(target)\n\n target.addEventListener('keydown', keydownHandler as EventListener)\n target.addEventListener('keyup', keyupHandler as EventListener)\n\n this.#targetListeners.set(target, {\n keydown: keydownHandler,\n keyup: keyupHandler,\n })\n }\n\n /**\n * Removes event listeners for a specific target.\n */\n #removeListenersForTarget(target: HTMLElement | Document | Window): void {\n if (typeof document === 'undefined') {\n return\n }\n\n const listeners = this.#targetListeners.get(target)\n if (!listeners) {\n return\n }\n\n target.removeEventListener('keydown', listeners.keydown as EventListener)\n target.removeEventListener('keyup', listeners.keyup as EventListener)\n\n this.#targetListeners.delete(target)\n this.#targetRegistrations.delete(target)\n }\n\n /**\n * Processes keyboard events for a specific target and event type.\n */\n #processTargetEvent(\n event: KeyboardEvent,\n target: HTMLElement | Document | Window,\n eventType: 'keydown' | 'keyup',\n ): void {\n const targetRegs = this.#targetRegistrations.get(target)\n if (!targetRegs) {\n return\n }\n\n for (const id of targetRegs) {\n const registration = this.registrations.state.get(id)\n if (!registration) {\n continue\n }\n\n // Check if event originated from or bubbled to this target\n if (!isEventForTarget(event, target)) {\n continue\n }\n\n if (!registration.options.enabled) {\n continue\n }\n\n // Check if we should ignore input elements (defaults to true)\n if (registration.options.ignoreInputs !== false) {\n if (isInputElement(event.target)) {\n // Don't ignore if the hotkey is explicitly scoped to this input element\n if (event.target !== registration.target) {\n continue\n }\n }\n }\n\n // Handle keydown events\n if (eventType === 'keydown') {\n if (registration.options.eventType !== 'keydown') {\n continue\n }\n\n // Check if the hotkey matches first\n const matches = matchesKeyboardEvent(\n event,\n registration.parsedHotkey,\n registration.options.platform,\n )\n\n if (matches) {\n // Always apply preventDefault/stopPropagation if the hotkey matches,\n // even when requireReset is active and has already fired\n if (registration.options.preventDefault) {\n event.preventDefault()\n }\n if (registration.options.stopPropagation) {\n event.stopPropagation()\n }\n\n // Only execute callback if requireReset is not active or hasn't fired yet\n if (!registration.options.requireReset || !registration.hasFired) {\n this.#executeHotkeyCallback(registration, event)\n\n // Mark as fired if requireReset is enabled\n if (registration.options.requireReset) {\n registration.hasFired = true\n }\n }\n }\n }\n // Handle keyup events\n else {\n if (registration.options.eventType === 'keyup') {\n if (\n matchesKeyboardEvent(\n event,\n registration.parsedHotkey,\n registration.options.platform,\n )\n ) {\n this.#executeHotkeyCallback(registration, event)\n }\n }\n\n // Reset hasFired when any key in the hotkey is released\n if (registration.options.requireReset && registration.hasFired) {\n if (this.#shouldResetRegistration(registration, event)) {\n registration.hasFired = false\n }\n }\n }\n }\n }\n\n /**\n * Executes a hotkey callback with proper event handling.\n */\n #executeHotkeyCallback(\n registration: HotkeyRegistration,\n event: KeyboardEvent,\n ): void {\n if (registration.options.preventDefault) {\n event.preventDefault()\n }\n if (registration.options.stopPropagation) {\n event.stopPropagation()\n }\n\n registration.triggerCount++\n\n // Notify the store so subscribers (e.g. devtools) see the updated count.\n // We create a new Map but keep the same registration reference to preserve\n // identity for mutation-based fields like hasFired.\n this.registrations.setState((prev) => new Map(prev))\n\n const context: HotkeyCallbackContext = {\n hotkey: registration.hotkey,\n parsedHotkey: registration.parsedHotkey,\n }\n\n registration.callback(event, context)\n }\n\n /**\n * Creates a keydown handler for a specific target.\n */\n #createTargetKeyDownHandler(\n target: HTMLElement | Document | Window,\n ): (event: KeyboardEvent) => void {\n return (event: KeyboardEvent) => {\n this.#processTargetEvent(event, target, 'keydown')\n }\n }\n\n /**\n * Creates a keyup handler for a specific target.\n */\n #createTargetKeyUpHandler(\n target: HTMLElement | Document | Window,\n ): (event: KeyboardEvent) => void {\n return (event: KeyboardEvent) => {\n this.#processTargetEvent(event, target, 'keyup')\n }\n }\n\n /**\n * Finds an existing registration with the same hotkey and target.\n */\n #findConflictingRegistration(\n hotkey: Hotkey,\n target: HTMLElement | Document | Window,\n ): HotkeyRegistration | null {\n for (const registration of this.registrations.state.values()) {\n if (registration.hotkey === hotkey && registration.target === target) {\n return registration\n }\n }\n return null\n }\n\n /**\n * Determines if a registration should be reset based on the keyup event.\n */\n #shouldResetRegistration(\n registration: HotkeyRegistration,\n event: KeyboardEvent,\n ): boolean {\n const parsed = registration.parsedHotkey\n const releasedKey = normalizeKeyName(event.key)\n\n // Reset if the main key is released\n // Compare case-insensitively for single-letter keys\n const parsedKeyNormalized =\n parsed.key.length === 1 ? parsed.key.toUpperCase() : parsed.key\n const releasedKeyNormalized =\n releasedKey.length === 1 ? releasedKey.toUpperCase() : releasedKey\n\n if (releasedKeyNormalized === parsedKeyNormalized) {\n return true\n }\n\n // Reset if any required modifier is released\n // Use normalized key names and check against canonical modifier names\n if (parsed.ctrl && releasedKey === 'Control') {\n return true\n }\n if (parsed.shift && releasedKey === 'Shift') {\n return true\n }\n if (parsed.alt && releasedKey === 'Alt') {\n return true\n }\n if (parsed.meta && releasedKey === 'Meta') {\n return true\n }\n\n return false\n }\n\n /**\n * Triggers a registration's callback programmatically from devtools.\n * Creates a synthetic KeyboardEvent and invokes the callback.\n *\n * @param id - The registration ID to trigger\n * @returns True if the registration was found and triggered\n */\n triggerRegistration(id: string): boolean {\n const registration = this.registrations.state.get(id)\n if (!registration) {\n return false\n }\n\n const parsed = registration.parsedHotkey\n const syntheticEvent = new KeyboardEvent(\n registration.options.eventType ?? 'keydown',\n {\n key: parsed.key,\n ctrlKey: parsed.ctrl,\n shiftKey: parsed.shift,\n altKey: parsed.alt,\n metaKey: parsed.meta,\n bubbles: true,\n cancelable: true,\n },\n )\n\n registration.triggerCount++\n\n // Notify the store so subscribers (e.g. devtools) see the updated count\n this.registrations.setState((prev) => new Map(prev))\n\n registration.callback(syntheticEvent, {\n hotkey: registration.hotkey,\n parsedHotkey: registration.parsedHotkey,\n })\n\n return true\n }\n\n /**\n * Gets the number of registered hotkeys.\n */\n getRegistrationCount(): number {\n return this.registrations.state.size\n }\n\n /**\n * Checks if a specific hotkey is registered.\n *\n * @param hotkey - The hotkey string to check\n * @param target - Optional target element to match (if provided, both hotkey and target must match)\n * @returns True if a matching registration exists\n */\n isRegistered(\n hotkey: Hotkey,\n target?: HTMLElement | Document | Window,\n ): boolean {\n for (const registration of this.registrations.state.values()) {\n if (registration.hotkey === hotkey) {\n // If target is specified, both must match\n if (target === undefined || registration.target === target) {\n return true\n }\n }\n }\n return false\n }\n\n /**\n * Destroys the manager and removes all listeners.\n */\n destroy(): void {\n // Remove all target listeners\n for (const target of this.#targetListeners.keys()) {\n this.#removeListenersForTarget(target)\n }\n\n this.registrations.setState(() => new Map())\n this.#targetListeners.clear()\n this.#targetRegistrations.clear()\n }\n}\n\n/**\n * Gets the singleton HotkeyManager instance.\n * Convenience function for accessing the manager.\n */\nexport function getHotkeyManager(): HotkeyManager {\n return HotkeyManager.getInstance()\n}\n"],"mappings":";;;;;;;;AAmHA,IAAI,wBAAwB;;;;AAK5B,SAAS,aAAqB;AAC5B,QAAO,UAAU,EAAE;;;;;;;;;;;;;;;;;;;;;AAsBrB,IAAa,gBAAb,MAAa,cAAc;CACzB,QAAOA,WAAkC;CAwBzC;CACA,mCAMI,IAAI,KAAK;CACb,uCACE,IAAI,KAAK;CAEX,AAAQ,cAAc;uBAd2C,IAAIC,sCACnE,IAAI,KAAK,CACV;AAaC,QAAKC,WAAYC,kCAAgB;;;;;CAMnC,OAAO,cAA6B;AAClC,MAAI,CAAC,eAAcH,SACjB,gBAAcA,WAAY,IAAI,eAAe;AAE/C,SAAO,eAAcA;;;;;CAMvB,OAAO,gBAAsB;AAC3B,MAAI,eAAcA,UAAW;AAC3B,kBAAcA,SAAU,SAAS;AACjC,kBAAcA,WAAY;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6B9B,SACE,QACA,UACA,UAAyB,EAAE,EACD;AAE1B,MAAI,OAAO,aAAa,eAAe,CAAC,QAAQ,QAAQ;GACtD,IAAI,kBAAkB;AACtB,UAAO;IACL,IAAI,Y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a;AAGb,OAAK,cAAc,UAAU,SAAS,IAAI,IAAI,KAAK,CAAC;AAEpD,eAAa,SAAS,gBAAgB;GACpC,QAAQ,aAAa;GACrB,cAAc,aAAa;GAC5B,CAAC;AAEF,SAAO;;;;;CAMT,uBAA+B;AAC7B,SAAO,KAAK,cAAc,MAAM;;;;;;;;;CAUlC,aACE,QACA,QACS;AACT,OAAK,MAAM,gBAAgB,KAAK,cAAc,MAAM,QAAQ,CAC1D,KAAI,aAAa,WAAW,QAE1B;OAAI,WAAW,UAAa,aAAa,WAAW,OAClD,QAAO;;AAIb,SAAO;;;;;CAMT,UAAgB;AAEd,OAAK,MAAM,UAAU,MAAKT,gBAAiB,MAAM,CAC/C,OAAKD,yBAA0B,OAAO;AAGxC,OAAK,cAAc,+BAAe,IAAI,KAAK,CAAC;AAC5C,QAAKC,gBAAiB,OAAO;AAC7B,QAAKH,oBAAqB,OAAO;;;;;;;AAQrC,SAAgB,mBAAkC;AAChD,QAAO,cAAc,aAAa"}
|
|
@@ -9,7 +9,11 @@ import { Store } from "@tanstack/store";
|
|
|
9
9
|
interface HotkeyOptions {
|
|
10
10
|
/** Behavior when this hotkey conflicts with an existing registration on the same target. Defaults to 'warn' */
|
|
11
11
|
conflictBehavior?: ConflictBehavior;
|
|
12
|
-
/**
|
|
12
|
+
/**
|
|
13
|
+
* Soft-disable: when `false`, the callback does not run but the registration
|
|
14
|
+
* stays in `HotkeyManager` (and in devtools). Toggling this should update the
|
|
15
|
+
* existing handle via `setOptions` rather than unregistering. Defaults to `true`.
|
|
16
|
+
*/
|
|
13
17
|
enabled?: boolean;
|
|
14
18
|
/** The event type to listen for. Defaults to 'keydown' */
|
|
15
19
|
eventType?: 'keydown' | 'keyup';
|
package/dist/hotkey-manager.d.ts
CHANGED
|
@@ -9,7 +9,11 @@ import { Store } from "@tanstack/store";
|
|
|
9
9
|
interface HotkeyOptions {
|
|
10
10
|
/** Behavior when this hotkey conflicts with an existing registration on the same target. Defaults to 'warn' */
|
|
11
11
|
conflictBehavior?: ConflictBehavior;
|
|
12
|
-
/**
|
|
12
|
+
/**
|
|
13
|
+
* Soft-disable: when `false`, the callback does not run but the registration
|
|
14
|
+
* stays in `HotkeyManager` (and in devtools). Toggling this should update the
|
|
15
|
+
* existing handle via `setOptions` rather than unregistering. Defaults to `true`.
|
|
16
|
+
*/
|
|
13
17
|
enabled?: boolean;
|
|
14
18
|
/** The event type to listen for. Defaults to 'keydown' */
|
|
15
19
|
eventType?: 'keydown' | 'keyup';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hotkey-manager.js","names":["#instance","#platform","#findConflictingRegistration","#unregister","#targetRegistrations","#ensureListenersForTarget","#removeListenersForTarget","#targetListeners","#createTargetKeyDownHandler","#createTargetKeyUpHandler","#executeHotkeyCallback","#shouldResetRegistration","#processTargetEvent"],"sources":["../src/hotkey-manager.ts"],"sourcesContent":["import { Store } from '@tanstack/store'\nimport { detectPlatform, normalizeKeyName } from './constants'\nimport { formatHotkey } from './format'\nimport { parseHotkey, rawHotkeyToParsedHotkey } from './parse'\nimport { matchesKeyboardEvent } from './match'\nimport {\n defaultHotkeyOptions,\n getDefaultIgnoreInputs,\n handleConflict,\n isEventForTarget,\n isInputElement,\n} from './manager.utils'\nimport type { ConflictBehavior } from './manager.utils'\nimport type {\n Hotkey,\n HotkeyCallback,\n HotkeyCallbackContext,\n ParsedHotkey,\n RegisterableHotkey,\n} from './hotkey'\n\nexport type { ConflictBehavior }\n\n/**\n * Options for registering a hotkey.\n */\nexport interface HotkeyOptions {\n /** Behavior when this hotkey conflicts with an existing registration on the same target. Defaults to 'warn' */\n conflictBehavior?: ConflictBehavior\n /** Whether the hotkey is enabled. Defaults to true */\n enabled?: boolean\n /** The event type to listen for. Defaults to 'keydown' */\n eventType?: 'keydown' | 'keyup'\n /** Whether to ignore hotkeys when keyboard events originate from input-like elements (text inputs, textarea, select, contenteditable — button-type inputs like type=button/submit/reset are not ignored). Defaults based on hotkey: true for single keys and Shift/Alt combos; false for Ctrl/Meta shortcuts and Escape */\n ignoreInputs?: boolean\n /** The target platform for resolving 'Mod' */\n platform?: 'mac' | 'windows' | 'linux'\n /** Prevent the default browser action when the hotkey matches. Defaults to true */\n preventDefault?: boolean\n /** If true, only trigger once until all keys are released. Default: false */\n requireReset?: boolean\n /** Stop event propagation when the hotkey matches. Defaults to true */\n stopPropagation?: boolean\n /** The DOM element to attach the event listener to. Defaults to document. */\n target?: HTMLElement | Document | Window | null\n}\n\n/**\n * A registered hotkey handler in the HotkeyManager.\n */\nexport interface HotkeyRegistration {\n /** The callback to invoke */\n callback: HotkeyCallback\n /** Whether this registration has fired and needs reset (for requireReset) */\n hasFired: boolean\n /** The original hotkey string */\n hotkey: Hotkey\n /** Unique identifier for this registration */\n id: string\n /** Options for this registration */\n options: HotkeyOptions\n /** The parsed hotkey */\n parsedHotkey: ParsedHotkey\n /** The resolved target element for this registration */\n target: HTMLElement | Document | Window\n /** How many times this registration's callback has been triggered */\n triggerCount: number\n}\n\n/**\n * A handle returned from HotkeyManager.register() that allows updating\n * the callback and options without re-registering the hotkey.\n *\n * @example\n * ```ts\n * const handle = manager.register('Mod+S', callback, options)\n *\n * // Update callback without re-registering (avoids stale closures)\n * handle.callback = newCallback\n *\n * // Update options without re-registering\n * handle.setOptions({ enabled: false })\n *\n * // Check if still active\n * if (handle.isActive) {\n * // ...\n * }\n *\n * // Unregister when done\n * handle.unregister()\n * ```\n */\nexport interface HotkeyRegistrationHandle {\n /**\n * The callback function. Can be set directly to update without re-registering.\n * This avoids stale closures when the callback references React state.\n */\n callback: HotkeyCallback\n /** Unique identifier for this registration */\n readonly id: string\n /** Check if this registration is still active (not unregistered) */\n readonly isActive: boolean\n /**\n * Update options (merged with existing options).\n * Useful for updating `enabled`, `preventDefault`, etc. without re-registering.\n */\n setOptions: (options: Partial<HotkeyOptions>) => void\n /** Unregister this hotkey */\n unregister: () => void\n}\n\nlet registrationIdCounter = 0\n\n/**\n * Generates a unique ID for hotkey registrations.\n */\nfunction generateId(): string {\n return `hotkey_${++registrationIdCounter}`\n}\n\n/**\n * Singleton manager for hotkey registrations.\n *\n * This class provides a centralized way to register and manage keyboard hotkeys.\n * It uses a single event listener for efficiency, regardless of how many hotkeys\n * are registered.\n *\n * @example\n * ```ts\n * const manager = HotkeyManager.getInstance()\n *\n * const unregister = manager.register('Mod+S', (event, context) => {\n * console.log('Save triggered!')\n * })\n *\n * // Later, to unregister:\n * unregister()\n * ```\n */\nexport class HotkeyManager {\n static #instance: HotkeyManager | null = null\n\n /**\n * The TanStack Store containing all hotkey registrations.\n * Use this to subscribe to registration changes or access current registrations.\n *\n * @example\n * ```ts\n * const manager = HotkeyManager.getInstance()\n *\n * // Subscribe to registration changes\n * const unsubscribe = manager.registrations.subscribe(() => {\n * console.log('Registrations changed:', manager.registrations.state.size)\n * })\n *\n * // Access current registrations\n * for (const [id, reg] of manager.registrations.state) {\n * console.log(reg.hotkey, reg.options.enabled)\n * }\n * ```\n */\n readonly registrations: Store<Map<string, HotkeyRegistration>> = new Store(\n new Map(),\n )\n #platform: 'mac' | 'windows' | 'linux'\n #targetListeners: Map<\n HTMLElement | Document | Window,\n {\n keydown: (event: KeyboardEvent) => void\n keyup: (event: KeyboardEvent) => void\n }\n > = new Map()\n #targetRegistrations: Map<HTMLElement | Document | Window, Set<string>> =\n new Map()\n\n private constructor() {\n this.#platform = detectPlatform()\n }\n\n /**\n * Gets the singleton instance of HotkeyManager.\n */\n static getInstance(): HotkeyManager {\n if (!HotkeyManager.#instance) {\n HotkeyManager.#instance = new HotkeyManager()\n }\n return HotkeyManager.#instance\n }\n\n /**\n * Resets the singleton instance. Useful for testing.\n */\n static resetInstance(): void {\n if (HotkeyManager.#instance) {\n HotkeyManager.#instance.destroy()\n HotkeyManager.#instance = null\n }\n }\n\n /**\n * Registers a hotkey handler and returns a handle for updating the registration.\n *\n * The returned handle allows updating the callback and options without\n * re-registering, which is useful for avoiding stale closures in React.\n *\n * @param hotkey - The hotkey string (e.g., 'Mod+S') or RawHotkey object\n * @param callback - The function to call when the hotkey is pressed\n * @param options - Options for the hotkey behavior\n * @returns A handle for managing the registration\n *\n * @example\n * ```ts\n * const handle = manager.register('Mod+S', callback)\n *\n * // Update callback without re-registering (avoids stale closures)\n * handle.callback = newCallback\n *\n * // Update options\n * handle.setOptions({ enabled: false })\n *\n * // Unregister when done\n * handle.unregister()\n * ```\n */\n register(\n hotkey: RegisterableHotkey,\n callback: HotkeyCallback,\n options: HotkeyOptions = {},\n ): HotkeyRegistrationHandle {\n // In SSR environments, return a no-op handle since there's no DOM to attach listeners to\n if (typeof document === 'undefined' && !options.target) {\n let currentCallback = callback\n return {\n id: generateId(),\n unregister: () => {},\n get callback() {\n return currentCallback\n },\n set callback(newCallback: HotkeyCallback) {\n currentCallback = newCallback\n },\n setOptions: () => {},\n get isActive() {\n return false\n },\n }\n }\n\n const id = generateId()\n const platform = options.platform ?? this.#platform\n const parsedHotkey =\n typeof hotkey === 'string'\n ? parseHotkey(hotkey, platform)\n : rawHotkeyToParsedHotkey(hotkey, platform)\n const hotkeyStr = (\n typeof hotkey === 'string' ? hotkey : formatHotkey(parsedHotkey)\n ) as Hotkey\n\n // Resolve target: default to document if not provided\n // Note: SSR case without explicit target is handled above\n const target = options.target ?? document\n\n // Resolve conflict behavior\n const conflictBehavior = options.conflictBehavior ?? 'warn'\n\n // Check for existing registrations with the same hotkey and target\n const conflictingRegistration = this.#findConflictingRegistration(\n hotkeyStr,\n target,\n )\n\n if (conflictingRegistration) {\n handleConflict(\n conflictingRegistration.id,\n hotkeyStr,\n conflictBehavior,\n (id) => this.#unregister(id),\n )\n }\n\n const resolvedIgnoreInputs =\n options.ignoreInputs ?? getDefaultIgnoreInputs(parsedHotkey)\n\n const baseOptions = {\n ...defaultHotkeyOptions,\n requireReset: false,\n ...options,\n platform,\n }\n\n const registration: HotkeyRegistration = {\n id,\n hotkey: hotkeyStr,\n parsedHotkey,\n callback,\n options: { ...baseOptions, ignoreInputs: resolvedIgnoreInputs },\n hasFired: false,\n triggerCount: 0,\n target,\n }\n\n this.registrations.setState((prev) => new Map(prev).set(id, registration))\n\n // Track registration for this target\n if (!this.#targetRegistrations.has(target)) {\n this.#targetRegistrations.set(target, new Set())\n }\n this.#targetRegistrations.get(target)!.add(id)\n\n // Ensure listeners are attached for this target\n this.#ensureListenersForTarget(target)\n\n // Create and return the handle\n const manager = this\n const handle: HotkeyRegistrationHandle = {\n get id() {\n return id\n },\n unregister: () => {\n manager.#unregister(id)\n },\n get callback() {\n const reg = manager.registrations.state.get(id)\n return reg?.callback ?? callback\n },\n set callback(newCallback: HotkeyCallback) {\n const reg = manager.registrations.state.get(id)\n if (reg) {\n reg.callback = newCallback\n }\n },\n setOptions: (newOptions: Partial<HotkeyOptions>) => {\n manager.registrations.setState((prev) => {\n const reg = prev.get(id)\n if (reg) {\n const next = new Map(prev)\n next.set(id, { ...reg, options: { ...reg.options, ...newOptions } })\n return next\n }\n return prev\n })\n },\n get isActive() {\n return manager.registrations.state.has(id)\n },\n }\n\n return handle\n }\n\n /**\n * Unregisters a hotkey by its registration ID.\n */\n #unregister(id: string): void {\n const registration = this.registrations.state.get(id)\n if (!registration) {\n return\n }\n\n const target = registration.target\n\n // Remove registration\n this.registrations.setState((prev) => {\n const next = new Map(prev)\n next.delete(id)\n return next\n })\n\n // Remove from target registrations tracking\n const targetRegs = this.#targetRegistrations.get(target)\n if (targetRegs) {\n targetRegs.delete(id)\n // If no more registrations for this target, remove listeners\n if (targetRegs.size === 0) {\n this.#removeListenersForTarget(target)\n }\n }\n }\n\n /**\n * Ensures event listeners are attached for a specific target.\n */\n #ensureListenersForTarget(target: HTMLElement | Document | Window): void {\n if (typeof document === 'undefined') {\n return // SSR safety\n }\n\n // Skip if listeners already exist for this target\n if (this.#targetListeners.has(target)) {\n return\n }\n\n const keydownHandler = this.#createTargetKeyDownHandler(target)\n const keyupHandler = this.#createTargetKeyUpHandler(target)\n\n target.addEventListener('keydown', keydownHandler as EventListener)\n target.addEventListener('keyup', keyupHandler as EventListener)\n\n this.#targetListeners.set(target, {\n keydown: keydownHandler,\n keyup: keyupHandler,\n })\n }\n\n /**\n * Removes event listeners for a specific target.\n */\n #removeListenersForTarget(target: HTMLElement | Document | Window): void {\n if (typeof document === 'undefined') {\n return\n }\n\n const listeners = this.#targetListeners.get(target)\n if (!listeners) {\n return\n }\n\n target.removeEventListener('keydown', listeners.keydown as EventListener)\n target.removeEventListener('keyup', listeners.keyup as EventListener)\n\n this.#targetListeners.delete(target)\n this.#targetRegistrations.delete(target)\n }\n\n /**\n * Processes keyboard events for a specific target and event type.\n */\n #processTargetEvent(\n event: KeyboardEvent,\n target: HTMLElement | Document | Window,\n eventType: 'keydown' | 'keyup',\n ): void {\n const targetRegs = this.#targetRegistrations.get(target)\n if (!targetRegs) {\n return\n }\n\n for (const id of targetRegs) {\n const registration = this.registrations.state.get(id)\n if (!registration) {\n continue\n }\n\n // Check if event originated from or bubbled to this target\n if (!isEventForTarget(event, target)) {\n continue\n }\n\n if (!registration.options.enabled) {\n continue\n }\n\n // Check if we should ignore input elements (defaults to true)\n if (registration.options.ignoreInputs !== false) {\n if (isInputElement(event.target)) {\n // Don't ignore if the hotkey is explicitly scoped to this input element\n if (event.target !== registration.target) {\n continue\n }\n }\n }\n\n // Handle keydown events\n if (eventType === 'keydown') {\n if (registration.options.eventType !== 'keydown') {\n continue\n }\n\n // Check if the hotkey matches first\n const matches = matchesKeyboardEvent(\n event,\n registration.parsedHotkey,\n registration.options.platform,\n )\n\n if (matches) {\n // Always apply preventDefault/stopPropagation if the hotkey matches,\n // even when requireReset is active and has already fired\n if (registration.options.preventDefault) {\n event.preventDefault()\n }\n if (registration.options.stopPropagation) {\n event.stopPropagation()\n }\n\n // Only execute callback if requireReset is not active or hasn't fired yet\n if (!registration.options.requireReset || !registration.hasFired) {\n this.#executeHotkeyCallback(registration, event)\n\n // Mark as fired if requireReset is enabled\n if (registration.options.requireReset) {\n registration.hasFired = true\n }\n }\n }\n }\n // Handle keyup events\n else {\n if (registration.options.eventType === 'keyup') {\n if (\n matchesKeyboardEvent(\n event,\n registration.parsedHotkey,\n registration.options.platform,\n )\n ) {\n this.#executeHotkeyCallback(registration, event)\n }\n }\n\n // Reset hasFired when any key in the hotkey is released\n if (registration.options.requireReset && registration.hasFired) {\n if (this.#shouldResetRegistration(registration, event)) {\n registration.hasFired = false\n }\n }\n }\n }\n }\n\n /**\n * Executes a hotkey callback with proper event handling.\n */\n #executeHotkeyCallback(\n registration: HotkeyRegistration,\n event: KeyboardEvent,\n ): void {\n if (registration.options.preventDefault) {\n event.preventDefault()\n }\n if (registration.options.stopPropagation) {\n event.stopPropagation()\n }\n\n registration.triggerCount++\n\n // Notify the store so subscribers (e.g. devtools) see the updated count.\n // We create a new Map but keep the same registration reference to preserve\n // identity for mutation-based fields like hasFired.\n this.registrations.setState((prev) => new Map(prev))\n\n const context: HotkeyCallbackContext = {\n hotkey: registration.hotkey,\n parsedHotkey: registration.parsedHotkey,\n }\n\n registration.callback(event, context)\n }\n\n /**\n * Creates a keydown handler for a specific target.\n */\n #createTargetKeyDownHandler(\n target: HTMLElement | Document | Window,\n ): (event: KeyboardEvent) => void {\n return (event: KeyboardEvent) => {\n this.#processTargetEvent(event, target, 'keydown')\n }\n }\n\n /**\n * Creates a keyup handler for a specific target.\n */\n #createTargetKeyUpHandler(\n target: HTMLElement | Document | Window,\n ): (event: KeyboardEvent) => void {\n return (event: KeyboardEvent) => {\n this.#processTargetEvent(event, target, 'keyup')\n }\n }\n\n /**\n * Finds an existing registration with the same hotkey and target.\n */\n #findConflictingRegistration(\n hotkey: Hotkey,\n target: HTMLElement | Document | Window,\n ): HotkeyRegistration | null {\n for (const registration of this.registrations.state.values()) {\n if (registration.hotkey === hotkey && registration.target === target) {\n return registration\n }\n }\n return null\n }\n\n /**\n * Determines if a registration should be reset based on the keyup event.\n */\n #shouldResetRegistration(\n registration: HotkeyRegistration,\n event: KeyboardEvent,\n ): boolean {\n const parsed = registration.parsedHotkey\n const releasedKey = normalizeKeyName(event.key)\n\n // Reset if the main key is released\n // Compare case-insensitively for single-letter keys\n const parsedKeyNormalized =\n parsed.key.length === 1 ? parsed.key.toUpperCase() : parsed.key\n const releasedKeyNormalized =\n releasedKey.length === 1 ? releasedKey.toUpperCase() : releasedKey\n\n if (releasedKeyNormalized === parsedKeyNormalized) {\n return true\n }\n\n // Reset if any required modifier is released\n // Use normalized key names and check against canonical modifier names\n if (parsed.ctrl && releasedKey === 'Control') {\n return true\n }\n if (parsed.shift && releasedKey === 'Shift') {\n return true\n }\n if (parsed.alt && releasedKey === 'Alt') {\n return true\n }\n if (parsed.meta && releasedKey === 'Meta') {\n return true\n }\n\n return false\n }\n\n /**\n * Triggers a registration's callback programmatically from devtools.\n * Creates a synthetic KeyboardEvent and invokes the callback.\n *\n * @param id - The registration ID to trigger\n * @returns True if the registration was found and triggered\n */\n triggerRegistration(id: string): boolean {\n const registration = this.registrations.state.get(id)\n if (!registration) {\n return false\n }\n\n const parsed = registration.parsedHotkey\n const syntheticEvent = new KeyboardEvent(\n registration.options.eventType ?? 'keydown',\n {\n key: parsed.key,\n ctrlKey: parsed.ctrl,\n shiftKey: parsed.shift,\n altKey: parsed.alt,\n metaKey: parsed.meta,\n bubbles: true,\n cancelable: true,\n },\n )\n\n registration.triggerCount++\n\n // Notify the store so subscribers (e.g. devtools) see the updated count\n this.registrations.setState((prev) => new Map(prev))\n\n registration.callback(syntheticEvent, {\n hotkey: registration.hotkey,\n parsedHotkey: registration.parsedHotkey,\n })\n\n return true\n }\n\n /**\n * Gets the number of registered hotkeys.\n */\n getRegistrationCount(): number {\n return this.registrations.state.size\n }\n\n /**\n * Checks if a specific hotkey is registered.\n *\n * @param hotkey - The hotkey string to check\n * @param target - Optional target element to match (if provided, both hotkey and target must match)\n * @returns True if a matching registration exists\n */\n isRegistered(\n hotkey: Hotkey,\n target?: HTMLElement | Document | Window,\n ): boolean {\n for (const registration of this.registrations.state.values()) {\n if (registration.hotkey === hotkey) {\n // If target is specified, both must match\n if (target === undefined || registration.target === target) {\n return true\n }\n }\n }\n return false\n }\n\n /**\n * Destroys the manager and removes all listeners.\n */\n destroy(): void {\n // Remove all target listeners\n for (const target of this.#targetListeners.keys()) {\n this.#removeListenersForTarget(target)\n }\n\n this.registrations.setState(() => new Map())\n this.#targetListeners.clear()\n this.#targetRegistrations.clear()\n }\n}\n\n/**\n * Gets the singleton HotkeyManager instance.\n * Convenience function for accessing the manager.\n */\nexport function getHotkeyManager(): HotkeyManager {\n return HotkeyManager.getInstance()\n}\n"],"mappings":";;;;;;;;AA+GA,IAAI,wBAAwB;;;;AAK5B,SAAS,aAAqB;AAC5B,QAAO,UAAU,EAAE;;;;;;;;;;;;;;;;;;;;;AAsBrB,IAAa,gBAAb,MAAa,cAAc;CACzB,QAAOA,WAAkC;CAwBzC;CACA,mCAMI,IAAI,KAAK;CACb,uCACE,IAAI,KAAK;CAEX,AAAQ,cAAc;uBAd2C,IAAI,sBACnE,IAAI,KAAK,CACV;AAaC,QAAKC,WAAY,gBAAgB;;;;;CAMnC,OAAO,cAA6B;AAClC,MAAI,CAAC,eAAcD,SACjB,gBAAcA,WAAY,IAAI,eAAe;AAE/C,SAAO,eAAcA;;;;;CAMvB,OAAO,gBAAsB;AAC3B,MAAI,eAAcA,UAAW;AAC3B,kBAAcA,SAAU,SAAS;AACjC,kBAAcA,WAAY;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6B9B,SACE,QACA,UACA,UAAyB,EAAE,EACD;AAE1B,MAAI,OAAO,aAAa,eAAe,CAAC,QAAQ,QAAQ;GACtD,IAAI,kBAAkB;AACtB,UAAO;IACL,IAAI,YAAY;IAChB,kBAAkB;IAClB,IAAI,WAAW;AACb,YAAO;;IAET,IAAI,SAAS,aAA6B;AACxC,uBAAkB;;IAEpB,kBAAkB;IAClB,IAAI,WAAW;AACb,YAAO;;IAEV;;EAGH,MAAM,KAAK,YAAY;EACvB,MAAM,WAAW,QAAQ,YAAY,MAAKC;EAC1C,MAAM,eAC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OAAK,MAAM,gBAAgB,KAAK,cAAc,MAAM,QAAQ,CAC1D,KAAI,aAAa,WAAW,QAE1B;OAAI,WAAW,UAAa,aAAa,WAAW,OAClD,QAAO;;AAIb,SAAO;;;;;CAMT,UAAgB;AAEd,OAAK,MAAM,UAAU,MAAKL,gBAAiB,MAAM,CAC/C,OAAKD,yBAA0B,OAAO;AAGxC,OAAK,cAAc,+BAAe,IAAI,KAAK,CAAC;AAC5C,QAAKC,gBAAiB,OAAO;AAC7B,QAAKH,oBAAqB,OAAO;;;;;;;AAQrC,SAAgB,mBAAkC;AAChD,QAAO,cAAc,aAAa"}
|
|
1
|
+
{"version":3,"file":"hotkey-manager.js","names":["#instance","#platform","#findConflictingRegistration","#unregister","#targetRegistrations","#ensureListenersForTarget","#removeListenersForTarget","#targetListeners","#createTargetKeyDownHandler","#createTargetKeyUpHandler","#executeHotkeyCallback","#shouldResetRegistration","#processTargetEvent"],"sources":["../src/hotkey-manager.ts"],"sourcesContent":["import { Store } from '@tanstack/store'\nimport { detectPlatform, normalizeKeyName } from './constants'\nimport { formatHotkey } from './format'\nimport { parseHotkey, rawHotkeyToParsedHotkey } from './parse'\nimport { matchesKeyboardEvent } from './match'\nimport {\n defaultHotkeyOptions,\n getDefaultIgnoreInputs,\n handleConflict,\n isEventForTarget,\n isInputElement,\n} from './manager.utils'\nimport type { ConflictBehavior } from './manager.utils'\nimport type {\n Hotkey,\n HotkeyCallback,\n HotkeyCallbackContext,\n ParsedHotkey,\n RegisterableHotkey,\n} from './hotkey'\n\nexport type { ConflictBehavior }\n\n/**\n * Options for registering a hotkey.\n */\nexport interface HotkeyOptions {\n /** Behavior when this hotkey conflicts with an existing registration on the same target. Defaults to 'warn' */\n conflictBehavior?: ConflictBehavior\n /**\n * Soft-disable: when `false`, the callback does not run but the registration\n * stays in `HotkeyManager` (and in devtools). Toggling this should update the\n * existing handle via `setOptions` rather than unregistering. Defaults to `true`.\n */\n enabled?: boolean\n /** The event type to listen for. Defaults to 'keydown' */\n eventType?: 'keydown' | 'keyup'\n /** Whether to ignore hotkeys when keyboard events originate from input-like elements (text inputs, textarea, select, contenteditable — button-type inputs like type=button/submit/reset are not ignored). Defaults based on hotkey: true for single keys and Shift/Alt combos; false for Ctrl/Meta shortcuts and Escape */\n ignoreInputs?: boolean\n /** The target platform for resolving 'Mod' */\n platform?: 'mac' | 'windows' | 'linux'\n /** Prevent the default browser action when the hotkey matches. Defaults to true */\n preventDefault?: boolean\n /** If true, only trigger once until all keys are released. Default: false */\n requireReset?: boolean\n /** Stop event propagation when the hotkey matches. Defaults to true */\n stopPropagation?: boolean\n /** The DOM element to attach the event listener to. Defaults to document. */\n target?: HTMLElement | Document | Window | null\n}\n\n/**\n * A registered hotkey handler in the HotkeyManager.\n */\nexport interface HotkeyRegistration {\n /** The callback to invoke */\n callback: HotkeyCallback\n /** Whether this registration has fired and needs reset (for requireReset) */\n hasFired: boolean\n /** The original hotkey string */\n hotkey: Hotkey\n /** Unique identifier for this registration */\n id: string\n /** Options for this registration */\n options: HotkeyOptions\n /** The parsed hotkey */\n parsedHotkey: ParsedHotkey\n /** The resolved target element for this registration */\n target: HTMLElement | Document | Window\n /** How many times this registration's callback has been triggered */\n triggerCount: number\n}\n\n/**\n * A handle returned from HotkeyManager.register() that allows updating\n * the callback and options without re-registering the hotkey.\n *\n * @example\n * ```ts\n * const handle = manager.register('Mod+S', callback, options)\n *\n * // Update callback without re-registering (avoids stale closures)\n * handle.callback = newCallback\n *\n * // Update options without re-registering\n * handle.setOptions({ enabled: false })\n *\n * // Check if still active\n * if (handle.isActive) {\n * // ...\n * }\n *\n * // Unregister when done\n * handle.unregister()\n * ```\n */\nexport interface HotkeyRegistrationHandle {\n /**\n * The callback function. Can be set directly to update without re-registering.\n * This avoids stale closures when the callback references React state.\n */\n callback: HotkeyCallback\n /** Unique identifier for this registration */\n readonly id: string\n /** Check if this registration is still active (not unregistered) */\n readonly isActive: boolean\n /**\n * Update options (merged with existing options).\n * Useful for updating `enabled`, `preventDefault`, etc. without re-registering.\n */\n setOptions: (options: Partial<HotkeyOptions>) => void\n /** Unregister this hotkey */\n unregister: () => void\n}\n\nlet registrationIdCounter = 0\n\n/**\n * Generates a unique ID for hotkey registrations.\n */\nfunction generateId(): string {\n return `hotkey_${++registrationIdCounter}`\n}\n\n/**\n * Singleton manager for hotkey registrations.\n *\n * This class provides a centralized way to register and manage keyboard hotkeys.\n * It uses a single event listener for efficiency, regardless of how many hotkeys\n * are registered.\n *\n * @example\n * ```ts\n * const manager = HotkeyManager.getInstance()\n *\n * const unregister = manager.register('Mod+S', (event, context) => {\n * console.log('Save triggered!')\n * })\n *\n * // Later, to unregister:\n * unregister()\n * ```\n */\nexport class HotkeyManager {\n static #instance: HotkeyManager | null = null\n\n /**\n * The TanStack Store containing all hotkey registrations.\n * Use this to subscribe to registration changes or access current registrations.\n *\n * @example\n * ```ts\n * const manager = HotkeyManager.getInstance()\n *\n * // Subscribe to registration changes\n * const unsubscribe = manager.registrations.subscribe(() => {\n * console.log('Registrations changed:', manager.registrations.state.size)\n * })\n *\n * // Access current registrations\n * for (const [id, reg] of manager.registrations.state) {\n * console.log(reg.hotkey, reg.options.enabled)\n * }\n * ```\n */\n readonly registrations: Store<Map<string, HotkeyRegistration>> = new Store(\n new Map(),\n )\n #platform: 'mac' | 'windows' | 'linux'\n #targetListeners: Map<\n HTMLElement | Document | Window,\n {\n keydown: (event: KeyboardEvent) => void\n keyup: (event: KeyboardEvent) => void\n }\n > = new Map()\n #targetRegistrations: Map<HTMLElement | Document | Window, Set<string>> =\n new Map()\n\n private constructor() {\n this.#platform = detectPlatform()\n }\n\n /**\n * Gets the singleton instance of HotkeyManager.\n */\n static getInstance(): HotkeyManager {\n if (!HotkeyManager.#instance) {\n HotkeyManager.#instance = new HotkeyManager()\n }\n return HotkeyManager.#instance\n }\n\n /**\n * Resets the singleton instance. Useful for testing.\n */\n static resetInstance(): void {\n if (HotkeyManager.#instance) {\n HotkeyManager.#instance.destroy()\n HotkeyManager.#instance = null\n }\n }\n\n /**\n * Registers a hotkey handler and returns a handle for updating the registration.\n *\n * The returned handle allows updating the callback and options without\n * re-registering, which is useful for avoiding stale closures in React.\n *\n * @param hotkey - The hotkey string (e.g., 'Mod+S') or RawHotkey object\n * @param callback - The function to call when the hotkey is pressed\n * @param options - Options for the hotkey behavior\n * @returns A handle for managing the registration\n *\n * @example\n * ```ts\n * const handle = manager.register('Mod+S', callback)\n *\n * // Update callback without re-registering (avoids stale closures)\n * handle.callback = newCallback\n *\n * // Update options\n * handle.setOptions({ enabled: false })\n *\n * // Unregister when done\n * handle.unregister()\n * ```\n */\n register(\n hotkey: RegisterableHotkey,\n callback: HotkeyCallback,\n options: HotkeyOptions = {},\n ): HotkeyRegistrationHandle {\n // In SSR environments, return a no-op handle since there's no DOM to attach listeners to\n if (typeof document === 'undefined' && !options.target) {\n let currentCallback = callback\n return {\n id: generateId(),\n unregister: () => {},\n get callback() {\n return currentCallback\n },\n set callback(newCallback: HotkeyCallback) {\n currentCallback = newCallback\n },\n setOptions: () => {},\n get isActive() {\n return false\n },\n }\n }\n\n const id = generateId()\n const platform = options.platform ?? this.#platform\n const parsedHotkey =\n typeof hotkey === 'string'\n ? parseHotkey(hotkey, platform)\n : rawHotkeyToParsedHotkey(hotkey, platform)\n const hotkeyStr = (\n typeof hotkey === 'string' ? hotkey : formatHotkey(parsedHotkey)\n ) as Hotkey\n\n // Resolve target: default to document if not provided\n // Note: SSR case without explicit target is handled above\n const target = options.target ?? document\n\n // Resolve conflict behavior\n const conflictBehavior = options.conflictBehavior ?? 'warn'\n\n // Check for existing registrations with the same hotkey and target\n const conflictingRegistration = this.#findConflictingRegistration(\n hotkeyStr,\n target,\n )\n\n if (conflictingRegistration) {\n handleConflict(\n conflictingRegistration.id,\n hotkeyStr,\n conflictBehavior,\n (id) => this.#unregister(id),\n )\n }\n\n const resolvedIgnoreInputs =\n options.ignoreInputs ?? getDefaultIgnoreInputs(parsedHotkey)\n\n const baseOptions = {\n ...defaultHotkeyOptions,\n requireReset: false,\n ...options,\n platform,\n }\n\n const registration: HotkeyRegistration = {\n id,\n hotkey: hotkeyStr,\n parsedHotkey,\n callback,\n options: { ...baseOptions, ignoreInputs: resolvedIgnoreInputs },\n hasFired: false,\n triggerCount: 0,\n target,\n }\n\n this.registrations.setState((prev) => new Map(prev).set(id, registration))\n\n // Track registration for this target\n if (!this.#targetRegistrations.has(target)) {\n this.#targetRegistrations.set(target, new Set())\n }\n this.#targetRegistrations.get(target)!.add(id)\n\n // Ensure listeners are attached for this target\n this.#ensureListenersForTarget(target)\n\n // Create and return the handle\n const manager = this\n const handle: HotkeyRegistrationHandle = {\n get id() {\n return id\n },\n unregister: () => {\n manager.#unregister(id)\n },\n get callback() {\n const reg = manager.registrations.state.get(id)\n return reg?.callback ?? callback\n },\n set callback(newCallback: HotkeyCallback) {\n const reg = manager.registrations.state.get(id)\n if (reg) {\n reg.callback = newCallback\n }\n },\n setOptions: (newOptions: Partial<HotkeyOptions>) => {\n manager.registrations.setState((prev) => {\n const reg = prev.get(id)\n if (reg) {\n const next = new Map(prev)\n next.set(id, { ...reg, options: { ...reg.options, ...newOptions } })\n return next\n }\n return prev\n })\n },\n get isActive() {\n return manager.registrations.state.has(id)\n },\n }\n\n return handle\n }\n\n /**\n * Unregisters a hotkey by its registration ID.\n */\n #unregister(id: string): void {\n const registration = this.registrations.state.get(id)\n if (!registration) {\n return\n }\n\n const target = registration.target\n\n // Remove registration\n this.registrations.setState((prev) => {\n const next = new Map(prev)\n next.delete(id)\n return next\n })\n\n // Remove from target registrations tracking\n const targetRegs = this.#targetRegistrations.get(target)\n if (targetRegs) {\n targetRegs.delete(id)\n // If no more registrations for this target, remove listeners\n if (targetRegs.size === 0) {\n this.#removeListenersForTarget(target)\n }\n }\n }\n\n /**\n * Ensures event listeners are attached for a specific target.\n */\n #ensureListenersForTarget(target: HTMLElement | Document | Window): void {\n if (typeof document === 'undefined') {\n return // SSR safety\n }\n\n // Skip if listeners already exist for this target\n if (this.#targetListeners.has(target)) {\n return\n }\n\n const keydownHandler = this.#createTargetKeyDownHandler(target)\n const keyupHandler = this.#createTargetKeyUpHandler(target)\n\n target.addEventListener('keydown', keydownHandler as EventListener)\n target.addEventListener('keyup', keyupHandler as EventListener)\n\n this.#targetListeners.set(target, {\n keydown: keydownHandler,\n keyup: keyupHandler,\n })\n }\n\n /**\n * Removes event listeners for a specific target.\n */\n #removeListenersForTarget(target: HTMLElement | Document | Window): void {\n if (typeof document === 'undefined') {\n return\n }\n\n const listeners = this.#targetListeners.get(target)\n if (!listeners) {\n return\n }\n\n target.removeEventListener('keydown', listeners.keydown as EventListener)\n target.removeEventListener('keyup', listeners.keyup as EventListener)\n\n this.#targetListeners.delete(target)\n this.#targetRegistrations.delete(target)\n }\n\n /**\n * Processes keyboard events for a specific target and event type.\n */\n #processTargetEvent(\n event: KeyboardEvent,\n target: HTMLElement | Document | Window,\n eventType: 'keydown' | 'keyup',\n ): void {\n const targetRegs = this.#targetRegistrations.get(target)\n if (!targetRegs) {\n return\n }\n\n for (const id of targetRegs) {\n const registration = this.registrations.state.get(id)\n if (!registration) {\n continue\n }\n\n // Check if event originated from or bubbled to this target\n if (!isEventForTarget(event, target)) {\n continue\n }\n\n if (!registration.options.enabled) {\n continue\n }\n\n // Check if we should ignore input elements (defaults to true)\n if (registration.options.ignoreInputs !== false) {\n if (isInputElement(event.target)) {\n // Don't ignore if the hotkey is explicitly scoped to this input element\n if (event.target !== registration.target) {\n continue\n }\n }\n }\n\n // Handle keydown events\n if (eventType === 'keydown') {\n if (registration.options.eventType !== 'keydown') {\n continue\n }\n\n // Check if the hotkey matches first\n const matches = matchesKeyboardEvent(\n event,\n registration.parsedHotkey,\n registration.options.platform,\n )\n\n if (matches) {\n // Always apply preventDefault/stopPropagation if the hotkey matches,\n // even when requireReset is active and has already fired\n if (registration.options.preventDefault) {\n event.preventDefault()\n }\n if (registration.options.stopPropagation) {\n event.stopPropagation()\n }\n\n // Only execute callback if requireReset is not active or hasn't fired yet\n if (!registration.options.requireReset || !registration.hasFired) {\n this.#executeHotkeyCallback(registration, event)\n\n // Mark as fired if requireReset is enabled\n if (registration.options.requireReset) {\n registration.hasFired = true\n }\n }\n }\n }\n // Handle keyup events\n else {\n if (registration.options.eventType === 'keyup') {\n if (\n matchesKeyboardEvent(\n event,\n registration.parsedHotkey,\n registration.options.platform,\n )\n ) {\n this.#executeHotkeyCallback(registration, event)\n }\n }\n\n // Reset hasFired when any key in the hotkey is released\n if (registration.options.requireReset && registration.hasFired) {\n if (this.#shouldResetRegistration(registration, event)) {\n registration.hasFired = false\n }\n }\n }\n }\n }\n\n /**\n * Executes a hotkey callback with proper event handling.\n */\n #executeHotkeyCallback(\n registration: HotkeyRegistration,\n event: KeyboardEvent,\n ): void {\n if (registration.options.preventDefault) {\n event.preventDefault()\n }\n if (registration.options.stopPropagation) {\n event.stopPropagation()\n }\n\n registration.triggerCount++\n\n // Notify the store so subscribers (e.g. devtools) see the updated count.\n // We create a new Map but keep the same registration reference to preserve\n // identity for mutation-based fields like hasFired.\n this.registrations.setState((prev) => new Map(prev))\n\n const context: HotkeyCallbackContext = {\n hotkey: registration.hotkey,\n parsedHotkey: registration.parsedHotkey,\n }\n\n registration.callback(event, context)\n }\n\n /**\n * Creates a keydown handler for a specific target.\n */\n #createTargetKeyDownHandler(\n target: HTMLElement | Document | Window,\n ): (event: KeyboardEvent) => void {\n return (event: KeyboardEvent) => {\n this.#processTargetEvent(event, target, 'keydown')\n }\n }\n\n /**\n * Creates a keyup handler for a specific target.\n */\n #createTargetKeyUpHandler(\n target: HTMLElement | Document | Window,\n ): (event: KeyboardEvent) => void {\n return (event: KeyboardEvent) => {\n this.#processTargetEvent(event, target, 'keyup')\n }\n }\n\n /**\n * Finds an existing registration with the same hotkey and target.\n */\n #findConflictingRegistration(\n hotkey: Hotkey,\n target: HTMLElement | Document | Window,\n ): HotkeyRegistration | null {\n for (const registration of this.registrations.state.values()) {\n if (registration.hotkey === hotkey && registration.target === target) {\n return registration\n }\n }\n return null\n }\n\n /**\n * Determines if a registration should be reset based on the keyup event.\n */\n #shouldResetRegistration(\n registration: HotkeyRegistration,\n event: KeyboardEvent,\n ): boolean {\n const parsed = registration.parsedHotkey\n const releasedKey = normalizeKeyName(event.key)\n\n // Reset if the main key is released\n // Compare case-insensitively for single-letter keys\n const parsedKeyNormalized =\n parsed.key.length === 1 ? parsed.key.toUpperCase() : parsed.key\n const releasedKeyNormalized =\n releasedKey.length === 1 ? releasedKey.toUpperCase() : releasedKey\n\n if (releasedKeyNormalized === parsedKeyNormalized) {\n return true\n }\n\n // Reset if any required modifier is released\n // Use normalized key names and check against canonical modifier names\n if (parsed.ctrl && releasedKey === 'Control') {\n return true\n }\n if (parsed.shift && releasedKey === 'Shift') {\n return true\n }\n if (parsed.alt && releasedKey === 'Alt') {\n return true\n }\n if (parsed.meta && releasedKey === 'Meta') {\n return true\n }\n\n return false\n }\n\n /**\n * Triggers a registration's callback programmatically from devtools.\n * Creates a synthetic KeyboardEvent and invokes the callback.\n *\n * @param id - The registration ID to trigger\n * @returns True if the registration was found and triggered\n */\n triggerRegistration(id: string): boolean {\n const registration = this.registrations.state.get(id)\n if (!registration) {\n return false\n }\n\n const parsed = registration.parsedHotkey\n const syntheticEvent = new KeyboardEvent(\n registration.options.eventType ?? 'keydown',\n {\n key: parsed.key,\n ctrlKey: parsed.ctrl,\n shiftKey: parsed.shift,\n altKey: parsed.alt,\n metaKey: parsed.meta,\n bubbles: true,\n cancelable: true,\n },\n )\n\n registration.triggerCount++\n\n // Notify the store so subscribers (e.g. devtools) see the updated count\n this.registrations.setState((prev) => new Map(prev))\n\n registration.callback(syntheticEvent, {\n hotkey: registration.hotkey,\n parsedHotkey: registration.parsedHotkey,\n })\n\n return true\n }\n\n /**\n * Gets the number of registered hotkeys.\n */\n getRegistrationCount(): number {\n return this.registrations.state.size\n }\n\n /**\n * Checks if a specific hotkey is registered.\n *\n * @param hotkey - The hotkey string to check\n * @param target - Optional target element to match (if provided, both hotkey and target must match)\n * @returns True if a matching registration exists\n */\n isRegistered(\n hotkey: Hotkey,\n target?: HTMLElement | Document | Window,\n ): boolean {\n for (const registration of this.registrations.state.values()) {\n if (registration.hotkey === hotkey) {\n // If target is specified, both must match\n if (target === undefined || registration.target === target) {\n return true\n }\n }\n }\n return false\n }\n\n /**\n * Destroys the manager and removes all listeners.\n */\n destroy(): void {\n // Remove all target listeners\n for (const target of this.#targetListeners.keys()) {\n this.#removeListenersForTarget(target)\n }\n\n this.registrations.setState(() => new Map())\n this.#targetListeners.clear()\n this.#targetRegistrations.clear()\n }\n}\n\n/**\n * Gets the singleton HotkeyManager instance.\n * Convenience function for accessing the manager.\n */\nexport function getHotkeyManager(): HotkeyManager {\n return HotkeyManager.getInstance()\n}\n"],"mappings":";;;;;;;;AAmHA,IAAI,wBAAwB;;;;AAK5B,SAAS,aAAqB;AAC5B,QAAO,UAAU,EAAE;;;;;;;;;;;;;;;;;;;;;AAsBrB,IAAa,gBAAb,MAAa,cAAc;CACzB,QAAOA,WAAkC;CAwBzC;CACA,mCAMI,IAAI,KAAK;CACb,uCACE,IAAI,KAAK;CAEX,AAAQ,cAAc;uBAd2C,IAAI,sBACnE,IAAI,KAAK,CACV;AAaC,QAAKC,WAAY,gBAAgB;;;;;CAMnC,OAAO,cAA6B;AAClC,MAAI,CAAC,eAAcD,SACjB,gBAAcA,WAAY,IAAI,eAAe;AAE/C,SAAO,eAAcA;;;;;CAMvB,OAAO,gBAAsB;AAC3B,MAAI,eAAcA,UAAW;AAC3B,kBAAcA,SAAU,SAAS;AACjC,kBAAcA,WAAY;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6B9B,SACE,QACA,UACA,UAAyB,EAAE,EACD;AAE1B,MAAI,OAAO,aAAa,eAAe,CAAC,QAAQ,QAAQ;GACtD,IAAI,kBAAkB;AACtB,UAAO;IACL,IAAI,YAAY;IAChB,kBAAkB;IAClB,IAAI,WAAW;AACb,YAAO;;IAET,IAAI,SAAS,aAA6B;AACxC,uBAA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aAAa;GACrB,cAAc,aAAa;GAC5B,CAAC;AAEF,SAAO;;;;;CAMT,uBAA+B;AAC7B,SAAO,KAAK,cAAc,MAAM;;;;;;;;;CAUlC,aACE,QACA,QACS;AACT,OAAK,MAAM,gBAAgB,KAAK,cAAc,MAAM,QAAQ,CAC1D,KAAI,aAAa,WAAW,QAE1B;OAAI,WAAW,UAAa,aAAa,WAAW,OAClD,QAAO;;AAIb,SAAO;;;;;CAMT,UAAgB;AAEd,OAAK,MAAM,UAAU,MAAKL,gBAAiB,MAAM,CAC/C,OAAKD,yBAA0B,OAAO;AAGxC,OAAK,cAAc,+BAAe,IAAI,KAAK,CAAC;AAC5C,QAAKC,gBAAiB,OAAO;AAC7B,QAAKH,oBAAqB,OAAO;;;;;;;AAQrC,SAAgB,mBAAkC;AAChD,QAAO,cAAc,aAAa"}
|
package/dist/hotkey.d.cts
CHANGED
|
@@ -237,6 +237,8 @@ type RegisterableHotkey = Hotkey | RawHotkey;
|
|
|
237
237
|
interface FormatDisplayOptions {
|
|
238
238
|
/** The target platform. Defaults to auto-detection. */
|
|
239
239
|
platform?: 'mac' | 'windows' | 'linux';
|
|
240
|
+
/** Whether to use symbols for the display. Defaults to true. */
|
|
241
|
+
useSymbols?: boolean;
|
|
240
242
|
}
|
|
241
243
|
/**
|
|
242
244
|
* Result of validating a hotkey string.
|
package/dist/hotkey.d.ts
CHANGED
|
@@ -237,6 +237,8 @@ type RegisterableHotkey = Hotkey | RawHotkey;
|
|
|
237
237
|
interface FormatDisplayOptions {
|
|
238
238
|
/** The target platform. Defaults to auto-detection. */
|
|
239
239
|
platform?: 'mac' | 'windows' | 'linux';
|
|
240
|
+
/** Whether to use symbols for the display. Defaults to true. */
|
|
241
|
+
useSymbols?: boolean;
|
|
240
242
|
}
|
|
241
243
|
/**
|
|
242
244
|
* Result of validating a hotkey string.
|
package/dist/index.cjs
CHANGED
|
@@ -20,6 +20,8 @@ exports.HotkeySequenceRecorder = require_hotkey_sequence_recorder.HotkeySequence
|
|
|
20
20
|
exports.KEY_DISPLAY_SYMBOLS = require_constants.KEY_DISPLAY_SYMBOLS;
|
|
21
21
|
exports.KeyStateTracker = require_key_state_tracker.KeyStateTracker;
|
|
22
22
|
exports.LETTER_KEYS = require_constants.LETTER_KEYS;
|
|
23
|
+
exports.LINUX_MODIFIER_LABELS = require_constants.LINUX_MODIFIER_LABELS;
|
|
24
|
+
exports.MAC_MODIFIER_LABELS = require_constants.MAC_MODIFIER_LABELS;
|
|
23
25
|
exports.MAC_MODIFIER_SYMBOLS = require_constants.MAC_MODIFIER_SYMBOLS;
|
|
24
26
|
exports.MODIFIER_ALIASES = require_constants.MODIFIER_ALIASES;
|
|
25
27
|
exports.MODIFIER_KEYS = require_constants.MODIFIER_KEYS;
|
|
@@ -28,11 +30,11 @@ exports.NAVIGATION_KEYS = require_constants.NAVIGATION_KEYS;
|
|
|
28
30
|
exports.NUMBER_KEYS = require_constants.NUMBER_KEYS;
|
|
29
31
|
exports.PUNCTUATION_CODE_MAP = require_constants.PUNCTUATION_CODE_MAP;
|
|
30
32
|
exports.PUNCTUATION_KEYS = require_constants.PUNCTUATION_KEYS;
|
|
31
|
-
exports.
|
|
33
|
+
exports.PUNCTUATION_KEY_DISPLAY_LABELS = require_constants.PUNCTUATION_KEY_DISPLAY_LABELS;
|
|
32
34
|
exports.SequenceManager = require_sequence_manager.SequenceManager;
|
|
35
|
+
exports.WINDOWS_MODIFIER_LABELS = require_constants.WINDOWS_MODIFIER_LABELS;
|
|
33
36
|
exports.assertValidHotkey = require_validate.assertValidHotkey;
|
|
34
37
|
exports.checkHotkey = require_validate.checkHotkey;
|
|
35
|
-
exports.convertToModFormat = require_parse.convertToModFormat;
|
|
36
38
|
exports.createHotkeyHandler = require_match.createHotkeyHandler;
|
|
37
39
|
exports.createMultiHotkeyHandler = require_match.createMultiHotkeyHandler;
|
|
38
40
|
exports.createSequenceMatcher = require_sequence_manager.createSequenceMatcher;
|
|
@@ -40,19 +42,19 @@ exports.detectPlatform = require_constants.detectPlatform;
|
|
|
40
42
|
exports.formatForDisplay = require_format.formatForDisplay;
|
|
41
43
|
exports.formatHotkey = require_format.formatHotkey;
|
|
42
44
|
exports.formatHotkeySequence = require_format.formatHotkeySequence;
|
|
43
|
-
exports.formatKeyForDebuggingDisplay = require_format.formatKeyForDebuggingDisplay;
|
|
44
45
|
exports.formatWithLabels = require_format.formatWithLabels;
|
|
45
46
|
exports.getHotkeyManager = require_hotkey_manager.getHotkeyManager;
|
|
46
47
|
exports.getKeyStateTracker = require_key_state_tracker.getKeyStateTracker;
|
|
47
48
|
exports.getSequenceManager = require_sequence_manager.getSequenceManager;
|
|
48
49
|
exports.hasNonModifierKey = require_parse.hasNonModifierKey;
|
|
49
|
-
exports.isModifier = require_parse.isModifier;
|
|
50
50
|
exports.isModifierKey = require_parse.isModifierKey;
|
|
51
51
|
exports.isSingleLetterKey = require_constants.isSingleLetterKey;
|
|
52
|
-
exports.keyboardEventToHotkey = require_parse.keyboardEventToHotkey;
|
|
53
52
|
exports.matchesKeyboardEvent = require_match.matchesKeyboardEvent;
|
|
54
53
|
exports.normalizeHotkey = require_parse.normalizeHotkey;
|
|
54
|
+
exports.normalizeHotkeyFromEvent = require_parse.normalizeHotkeyFromEvent;
|
|
55
|
+
exports.normalizeHotkeyFromParsed = require_parse.normalizeHotkeyFromParsed;
|
|
55
56
|
exports.normalizeKeyName = require_constants.normalizeKeyName;
|
|
57
|
+
exports.normalizeRegisterableHotkey = require_parse.normalizeRegisterableHotkey;
|
|
56
58
|
exports.parseHotkey = require_parse.parseHotkey;
|
|
57
59
|
exports.parseKeyboardEvent = require_parse.parseKeyboardEvent;
|
|
58
60
|
exports.rawHotkeyToParsedHotkey = require_parse.rawHotkeyToParsedHotkey;
|