@tanstack/hotkeys 0.4.3 → 0.5.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.
@@ -0,0 +1,188 @@
1
+ import { detectPlatform } from "./constants.js";
2
+ import { hotkeyChordFromKeydown } from "./recorder-chord.js";
3
+ import { Store } from "@tanstack/store";
4
+
5
+ //#region src/hotkey-sequence-recorder.ts
6
+ const defaultHotkeySequenceRecorderOptions = {
7
+ commitOnEnter: true,
8
+ commitKeys: "enter"
9
+ };
10
+ function resolvedCommitOnEnter(options) {
11
+ if (options.commitKeys === "none") return false;
12
+ return options.commitOnEnter !== false;
13
+ }
14
+ /**
15
+ * Framework-agnostic class for recording multi-chord sequences (Vim-style shortcuts).
16
+ *
17
+ * Each step is captured like a single hotkey chord. Press **Enter** (no modifiers) to commit
18
+ * when {@link HotkeySequenceRecorderOptions.commitKeys} is `'enter'` (default), **Escape** to cancel,
19
+ * **Backspace/Delete** to remove the last step or clear when empty.
20
+ */
21
+ var HotkeySequenceRecorder = class {
22
+ #keydownHandler = null;
23
+ #options;
24
+ #platform;
25
+ #idleTimer = null;
26
+ constructor(options) {
27
+ this.store = new Store({
28
+ isRecording: false,
29
+ steps: [],
30
+ recordedSequence: null
31
+ });
32
+ this.#options = {
33
+ ...defaultHotkeySequenceRecorderOptions,
34
+ ...options
35
+ };
36
+ this.#platform = detectPlatform();
37
+ }
38
+ setOptions(options) {
39
+ this.#options = {
40
+ ...defaultHotkeySequenceRecorderOptions,
41
+ ...this.#options,
42
+ ...options
43
+ };
44
+ }
45
+ #clearIdleTimer() {
46
+ if (this.#idleTimer !== null) {
47
+ clearTimeout(this.#idleTimer);
48
+ this.#idleTimer = null;
49
+ }
50
+ }
51
+ #scheduleIdleTimer() {
52
+ this.#clearIdleTimer();
53
+ const ms = this.#options.idleTimeoutMs;
54
+ if (ms === void 0 || ms <= 0) return;
55
+ if (this.store.state.steps.length === 0) return;
56
+ this.#idleTimer = setTimeout(() => {
57
+ this.#idleTimer = null;
58
+ if (!this.#keydownHandler) return;
59
+ if (this.store.state.steps.length >= 1) this.commit();
60
+ }, ms);
61
+ }
62
+ #patchSteps(updater) {
63
+ this.store.setState((s) => ({
64
+ ...s,
65
+ steps: updater(s.steps)
66
+ }));
67
+ }
68
+ start() {
69
+ if (this.#keydownHandler) return;
70
+ this.#clearIdleTimer();
71
+ this.store.setState(() => ({
72
+ isRecording: true,
73
+ steps: [],
74
+ recordedSequence: null
75
+ }));
76
+ const handler = (event) => {
77
+ if (!this.#keydownHandler) return;
78
+ event.preventDefault();
79
+ event.stopPropagation();
80
+ if (event.key === "Escape") {
81
+ this.cancel();
82
+ return;
83
+ }
84
+ if (event.key === "Backspace" || event.key === "Delete") {
85
+ if (!event.ctrlKey && !event.shiftKey && !event.altKey && !event.metaKey) {
86
+ if (this.store.state.steps.length === 0) {
87
+ this.#options.onClear?.();
88
+ this.#options.onRecord([]);
89
+ this.#finishWithoutCommitCallback();
90
+ return;
91
+ }
92
+ this.#patchSteps((prev) => prev.slice(0, -1));
93
+ if (this.store.state.steps.length === 0) this.#clearIdleTimer();
94
+ else this.#scheduleIdleTimer();
95
+ return;
96
+ }
97
+ }
98
+ const enterCommits = resolvedCommitOnEnter(this.#options) && event.key === "Enter" && !event.ctrlKey && !event.shiftKey && !event.altKey && !event.metaKey;
99
+ if (enterCommits && this.store.state.steps.length >= 1) {
100
+ this.commit();
101
+ return;
102
+ }
103
+ if (enterCommits && this.store.state.steps.length === 0) return;
104
+ const finalHotkey = hotkeyChordFromKeydown(event, this.#platform);
105
+ if (finalHotkey === null) return;
106
+ this.#patchSteps((prev) => [...prev, finalHotkey]);
107
+ this.#scheduleIdleTimer();
108
+ };
109
+ this.#keydownHandler = handler;
110
+ this.#addListener(handler);
111
+ }
112
+ /**
113
+ * Commit the current steps as a sequence. No-op if fewer than one step.
114
+ */
115
+ commit() {
116
+ const steps = this.store.state.steps;
117
+ if (steps.length < 1) return;
118
+ const sequence = [...steps];
119
+ if (this.#keydownHandler) {
120
+ this.#removeListener(this.#keydownHandler);
121
+ this.#keydownHandler = null;
122
+ }
123
+ this.#clearIdleTimer();
124
+ this.store.setState(() => ({
125
+ isRecording: false,
126
+ steps: [],
127
+ recordedSequence: sequence
128
+ }));
129
+ this.#options.onRecord(sequence);
130
+ }
131
+ #finishWithoutCommitCallback() {
132
+ if (this.#keydownHandler) {
133
+ this.#removeListener(this.#keydownHandler);
134
+ this.#keydownHandler = null;
135
+ }
136
+ this.#clearIdleTimer();
137
+ this.store.setState(() => ({
138
+ isRecording: false,
139
+ steps: [],
140
+ recordedSequence: null
141
+ }));
142
+ }
143
+ stop() {
144
+ if (this.#keydownHandler) {
145
+ this.#removeListener(this.#keydownHandler);
146
+ this.#keydownHandler = null;
147
+ }
148
+ this.#clearIdleTimer();
149
+ this.store.setState(() => ({
150
+ isRecording: false,
151
+ steps: [],
152
+ recordedSequence: null
153
+ }));
154
+ }
155
+ cancel() {
156
+ if (this.#keydownHandler) {
157
+ this.#removeListener(this.#keydownHandler);
158
+ this.#keydownHandler = null;
159
+ }
160
+ this.#clearIdleTimer();
161
+ this.store.setState(() => ({
162
+ isRecording: false,
163
+ steps: [],
164
+ recordedSequence: null
165
+ }));
166
+ this.#options.onCancel?.();
167
+ }
168
+ #addListener(handler) {
169
+ if (typeof document === "undefined") return;
170
+ document.addEventListener("keydown", handler, true);
171
+ }
172
+ #removeListener(handler) {
173
+ if (typeof document === "undefined") return;
174
+ document.removeEventListener("keydown", handler, true);
175
+ }
176
+ destroy() {
177
+ this.stop();
178
+ this.store.setState(() => ({
179
+ isRecording: false,
180
+ steps: [],
181
+ recordedSequence: null
182
+ }));
183
+ }
184
+ };
185
+
186
+ //#endregion
187
+ export { HotkeySequenceRecorder };
188
+ //# sourceMappingURL=hotkey-sequence-recorder.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hotkey-sequence-recorder.js","names":["#options","#platform","#idleTimer","#clearIdleTimer","#keydownHandler","#finishWithoutCommitCallback","#patchSteps","#scheduleIdleTimer","#addListener","#removeListener"],"sources":["../src/hotkey-sequence-recorder.ts"],"sourcesContent":["import { Store } from '@tanstack/store'\nimport { detectPlatform } from './constants'\nimport { hotkeyChordFromKeydown } from './recorder-chord'\nimport type { HotkeySequence } from './sequence-manager'\n\n/**\n * How the user can commit a recorded sequence from the keyboard.\n * - `'enter'`: plain Enter (no modifiers) commits when at least one step exists.\n * - `'none'`: only {@link HotkeySequenceRecorder.commit} finishes recording (or idle timeout if set).\n */\nexport type HotkeySequenceRecorderCommitKeys = 'enter' | 'none'\n\n/**\n * State interface for the HotkeySequenceRecorder.\n */\nexport interface HotkeySequenceRecorderState {\n /** Whether recording is currently active */\n isRecording: boolean\n /** Chords captured so far in the current recording session */\n steps: HotkeySequence\n /** The last successfully committed sequence, or null if none / after starting a new session */\n recordedSequence: HotkeySequence | null\n}\n\n/**\n * Options for configuring a HotkeySequenceRecorder instance.\n */\nexport interface HotkeySequenceRecorderOptions {\n /** Callback when a sequence is successfully recorded (including empty array when cleared) */\n onRecord: (sequence: HotkeySequence) => void\n /** Optional callback when recording is cancelled (Escape pressed) */\n onCancel?: () => void\n /** Optional callback when the sequence is cleared (Backspace/Delete with no steps) */\n onClear?: () => void\n /**\n * Whether plain Enter commits the current steps. Ignored when {@link commitKeys} is `'none'`.\n * @default true\n */\n commitOnEnter?: boolean\n /**\n * Keyboard commit mode. When `'none'`, use {@link HotkeySequenceRecorder.commit} (and optional idle timeout).\n * @default 'enter'\n */\n commitKeys?: HotkeySequenceRecorderCommitKeys\n /**\n * Milliseconds of inactivity after the **last completed chord** before auto-committing.\n * The timer does not run while waiting for the first chord (`steps.length === 0`).\n */\n idleTimeoutMs?: number\n}\n\nconst defaultHotkeySequenceRecorderOptions: Pick<\n HotkeySequenceRecorderOptions,\n 'commitOnEnter' | 'commitKeys'\n> = {\n commitOnEnter: true,\n commitKeys: 'enter',\n}\n\nfunction resolvedCommitOnEnter(\n options: HotkeySequenceRecorderOptions,\n): boolean {\n if (options.commitKeys === 'none') {\n return false\n }\n return options.commitOnEnter !== false\n}\n\n/**\n * Framework-agnostic class for recording multi-chord sequences (Vim-style shortcuts).\n *\n * Each step is captured like a single hotkey chord. Press **Enter** (no modifiers) to commit\n * when {@link HotkeySequenceRecorderOptions.commitKeys} is `'enter'` (default), **Escape** to cancel,\n * **Backspace/Delete** to remove the last step or clear when empty.\n */\nexport class HotkeySequenceRecorder {\n readonly store: Store<HotkeySequenceRecorderState> =\n new Store<HotkeySequenceRecorderState>({\n isRecording: false,\n steps: [],\n recordedSequence: null,\n })\n\n #keydownHandler: ((event: KeyboardEvent) => void) | null = null\n #options: HotkeySequenceRecorderOptions\n #platform: 'mac' | 'windows' | 'linux'\n #idleTimer: ReturnType<typeof setTimeout> | null = null\n\n constructor(options: HotkeySequenceRecorderOptions) {\n this.#options = {\n ...defaultHotkeySequenceRecorderOptions,\n ...options,\n }\n this.#platform = detectPlatform()\n }\n\n setOptions(options: Partial<HotkeySequenceRecorderOptions>): void {\n this.#options = {\n ...defaultHotkeySequenceRecorderOptions,\n ...this.#options,\n ...options,\n }\n }\n\n #clearIdleTimer(): void {\n if (this.#idleTimer !== null) {\n clearTimeout(this.#idleTimer)\n this.#idleTimer = null\n }\n }\n\n #scheduleIdleTimer(): void {\n this.#clearIdleTimer()\n const ms = this.#options.idleTimeoutMs\n if (ms === undefined || ms <= 0) {\n return\n }\n const steps = this.store.state.steps\n if (steps.length === 0) {\n return\n }\n this.#idleTimer = setTimeout(() => {\n this.#idleTimer = null\n if (!this.#keydownHandler) {\n return\n }\n if (this.store.state.steps.length >= 1) {\n this.commit()\n }\n }, ms)\n }\n\n #patchSteps(updater: (prev: HotkeySequence) => HotkeySequence): void {\n this.store.setState((s) => ({\n ...s,\n steps: updater(s.steps),\n }))\n }\n\n start(): void {\n if (this.#keydownHandler) {\n return\n }\n\n this.#clearIdleTimer()\n this.store.setState(() => ({\n isRecording: true,\n steps: [],\n recordedSequence: null,\n }))\n\n const handler = (event: KeyboardEvent) => {\n if (!this.#keydownHandler) {\n return\n }\n\n event.preventDefault()\n event.stopPropagation()\n\n if (event.key === 'Escape') {\n this.cancel()\n return\n }\n\n if (event.key === 'Backspace' || event.key === 'Delete') {\n if (\n !event.ctrlKey &&\n !event.shiftKey &&\n !event.altKey &&\n !event.metaKey\n ) {\n const steps = this.store.state.steps\n if (steps.length === 0) {\n this.#options.onClear?.()\n this.#options.onRecord([])\n this.#finishWithoutCommitCallback()\n return\n }\n this.#patchSteps((prev) => prev.slice(0, -1))\n const next = this.store.state.steps\n if (next.length === 0) {\n this.#clearIdleTimer()\n } else {\n this.#scheduleIdleTimer()\n }\n return\n }\n }\n\n const enterCommits =\n resolvedCommitOnEnter(this.#options) &&\n event.key === 'Enter' &&\n !event.ctrlKey &&\n !event.shiftKey &&\n !event.altKey &&\n !event.metaKey\n\n if (enterCommits && this.store.state.steps.length >= 1) {\n this.commit()\n return\n }\n\n if (enterCommits && this.store.state.steps.length === 0) {\n return\n }\n\n const finalHotkey = hotkeyChordFromKeydown(event, this.#platform)\n if (finalHotkey === null) {\n return\n }\n\n this.#patchSteps((prev) => [...prev, finalHotkey])\n this.#scheduleIdleTimer()\n }\n\n this.#keydownHandler = handler\n this.#addListener(handler)\n }\n\n /**\n * Commit the current steps as a sequence. No-op if fewer than one step.\n */\n commit(): void {\n const steps = this.store.state.steps\n if (steps.length < 1) {\n return\n }\n\n const sequence = [...steps]\n\n if (this.#keydownHandler) {\n this.#removeListener(this.#keydownHandler)\n this.#keydownHandler = null\n }\n this.#clearIdleTimer()\n\n this.store.setState(() => ({\n isRecording: false,\n steps: [],\n recordedSequence: sequence,\n }))\n\n this.#options.onRecord(sequence)\n }\n\n #finishWithoutCommitCallback(): void {\n if (this.#keydownHandler) {\n this.#removeListener(this.#keydownHandler)\n this.#keydownHandler = null\n }\n this.#clearIdleTimer()\n this.store.setState(() => ({\n isRecording: false,\n steps: [],\n recordedSequence: null,\n }))\n }\n\n stop(): void {\n if (this.#keydownHandler) {\n this.#removeListener(this.#keydownHandler)\n this.#keydownHandler = null\n }\n this.#clearIdleTimer()\n this.store.setState(() => ({\n isRecording: false,\n steps: [],\n recordedSequence: null,\n }))\n }\n\n cancel(): void {\n if (this.#keydownHandler) {\n this.#removeListener(this.#keydownHandler)\n this.#keydownHandler = null\n }\n this.#clearIdleTimer()\n this.store.setState(() => ({\n isRecording: false,\n steps: [],\n recordedSequence: null,\n }))\n this.#options.onCancel?.()\n }\n\n #addListener(handler: (event: KeyboardEvent) => void): void {\n if (typeof document === 'undefined') {\n return\n }\n document.addEventListener('keydown', handler, true)\n }\n\n #removeListener(handler: (event: KeyboardEvent) => void): void {\n if (typeof document === 'undefined') {\n return\n }\n document.removeEventListener('keydown', handler, true)\n }\n\n destroy(): void {\n this.stop()\n this.store.setState(() => ({\n isRecording: false,\n steps: [],\n recordedSequence: null,\n }))\n }\n}\n"],"mappings":";;;;;AAmDA,MAAM,uCAGF;CACF,eAAe;CACf,YAAY;CACb;AAED,SAAS,sBACP,SACS;AACT,KAAI,QAAQ,eAAe,OACzB,QAAO;AAET,QAAO,QAAQ,kBAAkB;;;;;;;;;AAUnC,IAAa,yBAAb,MAAoC;CAQlC,kBAA2D;CAC3D;CACA;CACA,aAAmD;CAEnD,YAAY,SAAwC;eAXlD,IAAI,MAAmC;GACrC,aAAa;GACb,OAAO,EAAE;GACT,kBAAkB;GACnB,CAAC;AAQF,QAAKA,UAAW;GACd,GAAG;GACH,GAAG;GACJ;AACD,QAAKC,WAAY,gBAAgB;;CAGnC,WAAW,SAAuD;AAChE,QAAKD,UAAW;GACd,GAAG;GACH,GAAG,MAAKA;GACR,GAAG;GACJ;;CAGH,kBAAwB;AACtB,MAAI,MAAKE,cAAe,MAAM;AAC5B,gBAAa,MAAKA,UAAW;AAC7B,SAAKA,YAAa;;;CAItB,qBAA2B;AACzB,QAAKC,gBAAiB;EACtB,MAAM,KAAK,MAAKH,QAAS;AACzB,MAAI,OAAO,UAAa,MAAM,EAC5B;AAGF,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AAa,SAA+C;AAC1D,MAAI,OAAO,aAAa,YACtB;AAEF,WAAS,iBAAiB,WAAW,SAAS,KAAK;;CAGrD,gBAAgB,SAA+C;AAC7D,MAAI,OAAO,aAAa,YACtB;AAEF,WAAS,oBAAoB,WAAW,SAAS,KAAK;;CAGxD,UAAgB;AACd,OAAK,MAAM;AACX,OAAK,MAAM,gBAAgB;GACzB,aAAa;GACb,OAAO,EAAE;GACT,kBAAkB;GACnB,EAAE"}
package/dist/index.cjs CHANGED
@@ -5,15 +5,18 @@ const require_format = require('./format.cjs');
5
5
  const require_match = require('./match.cjs');
6
6
  const require_hotkey_manager = require('./hotkey-manager.cjs');
7
7
  const require_key_state_tracker = require('./key-state-tracker.cjs');
8
- const require_recorder = require('./recorder.cjs');
8
+ const require_hotkey_recorder = require('./hotkey-recorder.cjs');
9
+ const require_hotkey_sequence_recorder = require('./hotkey-sequence-recorder.cjs');
9
10
  const require_sequence_manager = require('./sequence-manager.cjs');
10
11
  const require_validate = require('./validate.cjs');
11
12
 
12
13
  exports.ALL_KEYS = require_constants.ALL_KEYS;
14
+ exports.DEFAULT_SEQUENCE_TIMEOUT = require_sequence_manager.DEFAULT_SEQUENCE_TIMEOUT;
13
15
  exports.EDITING_KEYS = require_constants.EDITING_KEYS;
14
16
  exports.FUNCTION_KEYS = require_constants.FUNCTION_KEYS;
15
17
  exports.HotkeyManager = require_hotkey_manager.HotkeyManager;
16
- exports.HotkeyRecorder = require_recorder.HotkeyRecorder;
18
+ exports.HotkeyRecorder = require_hotkey_recorder.HotkeyRecorder;
19
+ exports.HotkeySequenceRecorder = require_hotkey_sequence_recorder.HotkeySequenceRecorder;
17
20
  exports.KEY_DISPLAY_SYMBOLS = require_constants.KEY_DISPLAY_SYMBOLS;
18
21
  exports.KeyStateTracker = require_key_state_tracker.KeyStateTracker;
19
22
  exports.LETTER_KEYS = require_constants.LETTER_KEYS;
package/dist/index.d.cts CHANGED
@@ -6,7 +6,8 @@ import { HotkeyManager, HotkeyOptions, HotkeyRegistration, HotkeyRegistrationHan
6
6
  import { KeyStateTracker, KeyStateTrackerState, getKeyStateTracker } from "./key-state-tracker.cjs";
7
7
  import { CreateHotkeyHandlerOptions, createHotkeyHandler, createMultiHotkeyHandler, matchesKeyboardEvent } from "./match.cjs";
8
8
  import { convertToModFormat, hasNonModifierKey, isModifier, isModifierKey, keyboardEventToHotkey, normalizeHotkey, parseHotkey, parseKeyboardEvent, rawHotkeyToParsedHotkey } from "./parse.cjs";
9
- import { HotkeyRecorder, HotkeyRecorderOptions, HotkeyRecorderState } from "./recorder.cjs";
10
- import { HotkeySequence, SequenceManager, SequenceOptions, SequenceRegistrationHandle, SequenceRegistrationView, createSequenceMatcher, getSequenceManager } from "./sequence-manager.cjs";
9
+ import { HotkeyRecorder, HotkeyRecorderOptions, HotkeyRecorderState } from "./hotkey-recorder.cjs";
10
+ import { DEFAULT_SEQUENCE_TIMEOUT, HotkeySequence, SequenceManager, SequenceOptions, SequenceRegistrationHandle, SequenceRegistrationView, createSequenceMatcher, getSequenceManager } from "./sequence-manager.cjs";
11
+ import { HotkeySequenceRecorder, HotkeySequenceRecorderCommitKeys, HotkeySequenceRecorderOptions, HotkeySequenceRecorderState } from "./hotkey-sequence-recorder.cjs";
11
12
  import { assertValidHotkey, checkHotkey, validateHotkey } from "./validate.cjs";
12
- export { ALL_KEYS, CanonicalModifier, ConflictBehavior, CreateHotkeyHandlerOptions, EDITING_KEYS, EditingKey, FUNCTION_KEYS, FormatDisplayOptions, FormatKeyDebuggingOptions, FunctionKey, HeldKey, Hotkey, HotkeyCallback, HotkeyCallbackContext, HotkeyManager, HotkeyOptions, HotkeyRecorder, HotkeyRecorderOptions, HotkeyRecorderState, HotkeyRegistration, HotkeyRegistrationHandle, HotkeySequence, KEY_DISPLAY_SYMBOLS, Key, KeyStateTracker, KeyStateTrackerState, LETTER_KEYS, LetterKey, MAC_MODIFIER_SYMBOLS, MODIFIER_ALIASES, MODIFIER_KEYS, MODIFIER_ORDER, Modifier, NAVIGATION_KEYS, NUMBER_KEYS, NavigationKey, NumberKey, PUNCTUATION_CODE_MAP, PUNCTUATION_KEYS, ParsedHotkey, PunctuationKey, RawHotkey, RegisterableHotkey, STANDARD_MODIFIER_LABELS, SequenceManager, SequenceOptions, SequenceRegistrationHandle, SequenceRegistrationView, ValidationResult, assertValidHotkey, checkHotkey, convertToModFormat, createHotkeyHandler, createMultiHotkeyHandler, createSequenceMatcher, detectPlatform, formatForDisplay, formatHotkey, formatHotkeySequence, formatKeyForDebuggingDisplay, formatWithLabels, getHotkeyManager, getKeyStateTracker, getSequenceManager, hasNonModifierKey, isModifier, isModifierKey, isSingleLetterKey, keyboardEventToHotkey, matchesKeyboardEvent, normalizeHotkey, normalizeKeyName, parseHotkey, parseKeyboardEvent, rawHotkeyToParsedHotkey, resolveModifier, validateHotkey };
13
+ export { ALL_KEYS, CanonicalModifier, ConflictBehavior, CreateHotkeyHandlerOptions, DEFAULT_SEQUENCE_TIMEOUT, EDITING_KEYS, EditingKey, FUNCTION_KEYS, FormatDisplayOptions, FormatKeyDebuggingOptions, FunctionKey, HeldKey, Hotkey, HotkeyCallback, HotkeyCallbackContext, HotkeyManager, HotkeyOptions, HotkeyRecorder, HotkeyRecorderOptions, HotkeyRecorderState, HotkeyRegistration, HotkeyRegistrationHandle, HotkeySequence, HotkeySequenceRecorder, HotkeySequenceRecorderCommitKeys, HotkeySequenceRecorderOptions, HotkeySequenceRecorderState, KEY_DISPLAY_SYMBOLS, Key, KeyStateTracker, KeyStateTrackerState, LETTER_KEYS, LetterKey, MAC_MODIFIER_SYMBOLS, MODIFIER_ALIASES, MODIFIER_KEYS, MODIFIER_ORDER, Modifier, NAVIGATION_KEYS, NUMBER_KEYS, NavigationKey, NumberKey, PUNCTUATION_CODE_MAP, PUNCTUATION_KEYS, ParsedHotkey, PunctuationKey, RawHotkey, RegisterableHotkey, STANDARD_MODIFIER_LABELS, SequenceManager, SequenceOptions, SequenceRegistrationHandle, SequenceRegistrationView, ValidationResult, assertValidHotkey, checkHotkey, convertToModFormat, createHotkeyHandler, createMultiHotkeyHandler, createSequenceMatcher, detectPlatform, formatForDisplay, formatHotkey, formatHotkeySequence, formatKeyForDebuggingDisplay, formatWithLabels, getHotkeyManager, getKeyStateTracker, getSequenceManager, hasNonModifierKey, isModifier, isModifierKey, isSingleLetterKey, keyboardEventToHotkey, matchesKeyboardEvent, normalizeHotkey, normalizeKeyName, parseHotkey, parseKeyboardEvent, rawHotkeyToParsedHotkey, resolveModifier, validateHotkey };
package/dist/index.d.ts CHANGED
@@ -6,7 +6,8 @@ import { HotkeyManager, HotkeyOptions, HotkeyRegistration, HotkeyRegistrationHan
6
6
  import { KeyStateTracker, KeyStateTrackerState, getKeyStateTracker } from "./key-state-tracker.js";
7
7
  import { CreateHotkeyHandlerOptions, createHotkeyHandler, createMultiHotkeyHandler, matchesKeyboardEvent } from "./match.js";
8
8
  import { convertToModFormat, hasNonModifierKey, isModifier, isModifierKey, keyboardEventToHotkey, normalizeHotkey, parseHotkey, parseKeyboardEvent, rawHotkeyToParsedHotkey } from "./parse.js";
9
- import { HotkeyRecorder, HotkeyRecorderOptions, HotkeyRecorderState } from "./recorder.js";
10
- import { HotkeySequence, SequenceManager, SequenceOptions, SequenceRegistrationHandle, SequenceRegistrationView, createSequenceMatcher, getSequenceManager } from "./sequence-manager.js";
9
+ import { HotkeyRecorder, HotkeyRecorderOptions, HotkeyRecorderState } from "./hotkey-recorder.js";
10
+ import { DEFAULT_SEQUENCE_TIMEOUT, HotkeySequence, SequenceManager, SequenceOptions, SequenceRegistrationHandle, SequenceRegistrationView, createSequenceMatcher, getSequenceManager } from "./sequence-manager.js";
11
+ import { HotkeySequenceRecorder, HotkeySequenceRecorderCommitKeys, HotkeySequenceRecorderOptions, HotkeySequenceRecorderState } from "./hotkey-sequence-recorder.js";
11
12
  import { assertValidHotkey, checkHotkey, validateHotkey } from "./validate.js";
12
- export { ALL_KEYS, CanonicalModifier, ConflictBehavior, CreateHotkeyHandlerOptions, EDITING_KEYS, EditingKey, FUNCTION_KEYS, FormatDisplayOptions, FormatKeyDebuggingOptions, FunctionKey, HeldKey, Hotkey, HotkeyCallback, HotkeyCallbackContext, HotkeyManager, HotkeyOptions, HotkeyRecorder, HotkeyRecorderOptions, HotkeyRecorderState, HotkeyRegistration, HotkeyRegistrationHandle, HotkeySequence, KEY_DISPLAY_SYMBOLS, Key, KeyStateTracker, KeyStateTrackerState, LETTER_KEYS, LetterKey, MAC_MODIFIER_SYMBOLS, MODIFIER_ALIASES, MODIFIER_KEYS, MODIFIER_ORDER, Modifier, NAVIGATION_KEYS, NUMBER_KEYS, NavigationKey, NumberKey, PUNCTUATION_CODE_MAP, PUNCTUATION_KEYS, ParsedHotkey, PunctuationKey, RawHotkey, RegisterableHotkey, STANDARD_MODIFIER_LABELS, SequenceManager, SequenceOptions, SequenceRegistrationHandle, SequenceRegistrationView, ValidationResult, assertValidHotkey, checkHotkey, convertToModFormat, createHotkeyHandler, createMultiHotkeyHandler, createSequenceMatcher, detectPlatform, formatForDisplay, formatHotkey, formatHotkeySequence, formatKeyForDebuggingDisplay, formatWithLabels, getHotkeyManager, getKeyStateTracker, getSequenceManager, hasNonModifierKey, isModifier, isModifierKey, isSingleLetterKey, keyboardEventToHotkey, matchesKeyboardEvent, normalizeHotkey, normalizeKeyName, parseHotkey, parseKeyboardEvent, rawHotkeyToParsedHotkey, resolveModifier, validateHotkey };
13
+ export { ALL_KEYS, CanonicalModifier, ConflictBehavior, CreateHotkeyHandlerOptions, DEFAULT_SEQUENCE_TIMEOUT, EDITING_KEYS, EditingKey, FUNCTION_KEYS, FormatDisplayOptions, FormatKeyDebuggingOptions, FunctionKey, HeldKey, Hotkey, HotkeyCallback, HotkeyCallbackContext, HotkeyManager, HotkeyOptions, HotkeyRecorder, HotkeyRecorderOptions, HotkeyRecorderState, HotkeyRegistration, HotkeyRegistrationHandle, HotkeySequence, HotkeySequenceRecorder, HotkeySequenceRecorderCommitKeys, HotkeySequenceRecorderOptions, HotkeySequenceRecorderState, KEY_DISPLAY_SYMBOLS, Key, KeyStateTracker, KeyStateTrackerState, LETTER_KEYS, LetterKey, MAC_MODIFIER_SYMBOLS, MODIFIER_ALIASES, MODIFIER_KEYS, MODIFIER_ORDER, Modifier, NAVIGATION_KEYS, NUMBER_KEYS, NavigationKey, NumberKey, PUNCTUATION_CODE_MAP, PUNCTUATION_KEYS, ParsedHotkey, PunctuationKey, RawHotkey, RegisterableHotkey, STANDARD_MODIFIER_LABELS, SequenceManager, SequenceOptions, SequenceRegistrationHandle, SequenceRegistrationView, ValidationResult, assertValidHotkey, checkHotkey, convertToModFormat, createHotkeyHandler, createMultiHotkeyHandler, createSequenceMatcher, detectPlatform, formatForDisplay, formatHotkey, formatHotkeySequence, formatKeyForDebuggingDisplay, formatWithLabels, getHotkeyManager, getKeyStateTracker, getSequenceManager, hasNonModifierKey, isModifier, isModifierKey, isSingleLetterKey, keyboardEventToHotkey, matchesKeyboardEvent, normalizeHotkey, normalizeKeyName, parseHotkey, parseKeyboardEvent, rawHotkeyToParsedHotkey, resolveModifier, validateHotkey };
package/dist/index.js CHANGED
@@ -4,8 +4,9 @@ import { formatForDisplay, formatHotkey, formatHotkeySequence, formatKeyForDebug
4
4
  import { createHotkeyHandler, createMultiHotkeyHandler, matchesKeyboardEvent } from "./match.js";
5
5
  import { HotkeyManager, getHotkeyManager } from "./hotkey-manager.js";
6
6
  import { KeyStateTracker, getKeyStateTracker } from "./key-state-tracker.js";
7
- import { HotkeyRecorder } from "./recorder.js";
8
- import { SequenceManager, createSequenceMatcher, getSequenceManager } from "./sequence-manager.js";
7
+ import { HotkeyRecorder } from "./hotkey-recorder.js";
8
+ import { HotkeySequenceRecorder } from "./hotkey-sequence-recorder.js";
9
+ import { DEFAULT_SEQUENCE_TIMEOUT, SequenceManager, createSequenceMatcher, getSequenceManager } from "./sequence-manager.js";
9
10
  import { assertValidHotkey, checkHotkey, validateHotkey } from "./validate.js";
10
11
 
11
- export { ALL_KEYS, EDITING_KEYS, FUNCTION_KEYS, HotkeyManager, HotkeyRecorder, KEY_DISPLAY_SYMBOLS, KeyStateTracker, LETTER_KEYS, MAC_MODIFIER_SYMBOLS, MODIFIER_ALIASES, MODIFIER_KEYS, MODIFIER_ORDER, NAVIGATION_KEYS, NUMBER_KEYS, PUNCTUATION_CODE_MAP, PUNCTUATION_KEYS, STANDARD_MODIFIER_LABELS, SequenceManager, assertValidHotkey, checkHotkey, convertToModFormat, createHotkeyHandler, createMultiHotkeyHandler, createSequenceMatcher, detectPlatform, formatForDisplay, formatHotkey, formatHotkeySequence, formatKeyForDebuggingDisplay, formatWithLabels, getHotkeyManager, getKeyStateTracker, getSequenceManager, hasNonModifierKey, isModifier, isModifierKey, isSingleLetterKey, keyboardEventToHotkey, matchesKeyboardEvent, normalizeHotkey, normalizeKeyName, parseHotkey, parseKeyboardEvent, rawHotkeyToParsedHotkey, resolveModifier, validateHotkey };
12
+ export { ALL_KEYS, DEFAULT_SEQUENCE_TIMEOUT, EDITING_KEYS, FUNCTION_KEYS, HotkeyManager, HotkeyRecorder, HotkeySequenceRecorder, KEY_DISPLAY_SYMBOLS, KeyStateTracker, LETTER_KEYS, MAC_MODIFIER_SYMBOLS, MODIFIER_ALIASES, MODIFIER_KEYS, MODIFIER_ORDER, NAVIGATION_KEYS, NUMBER_KEYS, PUNCTUATION_CODE_MAP, PUNCTUATION_KEYS, STANDARD_MODIFIER_LABELS, SequenceManager, assertValidHotkey, checkHotkey, convertToModFormat, createHotkeyHandler, createMultiHotkeyHandler, createSequenceMatcher, detectPlatform, formatForDisplay, formatHotkey, formatHotkeySequence, formatKeyForDebuggingDisplay, formatWithLabels, getHotkeyManager, getKeyStateTracker, getSequenceManager, hasNonModifierKey, isModifier, isModifierKey, isSingleLetterKey, keyboardEventToHotkey, matchesKeyboardEvent, normalizeHotkey, normalizeKeyName, parseHotkey, parseKeyboardEvent, rawHotkeyToParsedHotkey, resolveModifier, validateHotkey };
@@ -0,0 +1,17 @@
1
+ const require_parse = require('./parse.cjs');
2
+
3
+ //#region src/recorder-chord.ts
4
+ /**
5
+ * Parses a keydown event into a single normalized hotkey chord, or null if
6
+ * the event should be ignored (modifier-only or invalid).
7
+ */
8
+ function hotkeyChordFromKeydown(event, platform) {
9
+ if (require_parse.isModifierKey(event)) return null;
10
+ const finalHotkey = require_parse.convertToModFormat(require_parse.keyboardEventToHotkey(event), platform);
11
+ if (!require_parse.hasNonModifierKey(finalHotkey, platform)) return null;
12
+ return finalHotkey;
13
+ }
14
+
15
+ //#endregion
16
+ exports.hotkeyChordFromKeydown = hotkeyChordFromKeydown;
17
+ //# sourceMappingURL=recorder-chord.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"recorder-chord.cjs","names":["isModifierKey","convertToModFormat","keyboardEventToHotkey","hasNonModifierKey"],"sources":["../src/recorder-chord.ts"],"sourcesContent":["import {\n convertToModFormat,\n hasNonModifierKey,\n isModifierKey,\n keyboardEventToHotkey,\n} from './parse'\nimport type { Hotkey } from './hotkey'\n\n/**\n * Parses a keydown event into a single normalized hotkey chord, or null if\n * the event should be ignored (modifier-only or invalid).\n */\nexport function hotkeyChordFromKeydown(\n event: KeyboardEvent,\n platform: 'mac' | 'windows' | 'linux',\n): Hotkey | null {\n if (isModifierKey(event)) {\n return null\n }\n const hotkey = keyboardEventToHotkey(event)\n const finalHotkey = convertToModFormat(hotkey, platform)\n if (!hasNonModifierKey(finalHotkey, platform)) {\n return null\n }\n return finalHotkey\n}\n"],"mappings":";;;;;;;AAYA,SAAgB,uBACd,OACA,UACe;AACf,KAAIA,4BAAc,MAAM,CACtB,QAAO;CAGT,MAAM,cAAcC,iCADLC,oCAAsB,MAAM,EACI,SAAS;AACxD,KAAI,CAACC,gCAAkB,aAAa,SAAS,CAC3C,QAAO;AAET,QAAO"}
@@ -0,0 +1,17 @@
1
+ import { convertToModFormat, hasNonModifierKey, isModifierKey, keyboardEventToHotkey } from "./parse.js";
2
+
3
+ //#region src/recorder-chord.ts
4
+ /**
5
+ * Parses a keydown event into a single normalized hotkey chord, or null if
6
+ * the event should be ignored (modifier-only or invalid).
7
+ */
8
+ function hotkeyChordFromKeydown(event, platform) {
9
+ if (isModifierKey(event)) return null;
10
+ const finalHotkey = convertToModFormat(keyboardEventToHotkey(event), platform);
11
+ if (!hasNonModifierKey(finalHotkey, platform)) return null;
12
+ return finalHotkey;
13
+ }
14
+
15
+ //#endregion
16
+ export { hotkeyChordFromKeydown };
17
+ //# sourceMappingURL=recorder-chord.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"recorder-chord.js","names":[],"sources":["../src/recorder-chord.ts"],"sourcesContent":["import {\n convertToModFormat,\n hasNonModifierKey,\n isModifierKey,\n keyboardEventToHotkey,\n} from './parse'\nimport type { Hotkey } from './hotkey'\n\n/**\n * Parses a keydown event into a single normalized hotkey chord, or null if\n * the event should be ignored (modifier-only or invalid).\n */\nexport function hotkeyChordFromKeydown(\n event: KeyboardEvent,\n platform: 'mac' | 'windows' | 'linux',\n): Hotkey | null {\n if (isModifierKey(event)) {\n return null\n }\n const hotkey = keyboardEventToHotkey(event)\n const finalHotkey = convertToModFormat(hotkey, platform)\n if (!hasNonModifierKey(finalHotkey, platform)) {\n return null\n }\n return finalHotkey\n}\n"],"mappings":";;;;;;;AAYA,SAAgB,uBACd,OACA,UACe;AACf,KAAI,cAAc,MAAM,CACtB,QAAO;CAGT,MAAM,cAAc,mBADL,sBAAsB,MAAM,EACI,SAAS;AACxD,KAAI,CAAC,kBAAkB,aAAa,SAAS,CAC3C,QAAO;AAET,QAAO"}
@@ -8,6 +8,7 @@ let _tanstack_store = require("@tanstack/store");
8
8
  //#region src/sequence-manager.ts
9
9
  /**
10
10
  * Default timeout between keys in a sequence (in milliseconds).
11
+ * Exported for consumers that display sequence state (e.g. devtools).
11
12
  */
12
13
  const DEFAULT_SEQUENCE_TIMEOUT = 1e3;
13
14
  let sequenceIdCounter = 0;
@@ -52,12 +53,16 @@ function sequenceKey(sequence) {
52
53
  * Builds a devtools view from an internal registration.
53
54
  */
54
55
  function toRegistrationView(reg) {
56
+ const len = reg.parsedSequence.length;
57
+ const inProgress = reg.currentIndex > 0 && reg.currentIndex < len;
55
58
  return {
56
59
  id: reg.id,
57
60
  sequence: reg.sequence,
58
61
  options: reg.options,
59
62
  target: reg.target,
60
- triggerCount: reg.triggerCount
63
+ triggerCount: reg.triggerCount,
64
+ matchedStepCount: inProgress ? reg.currentIndex : 0,
65
+ partialMatchLastKeyTime: inProgress ? reg.lastKeyTime : 0
61
66
  };
62
67
  }
63
68
  var SequenceManager = class SequenceManager {
@@ -86,6 +91,9 @@ var SequenceManager = class SequenceManager {
86
91
  SequenceManager.#instance = null;
87
92
  }
88
93
  }
94
+ #syncRegistrationView(registration) {
95
+ this.registrations.setState((prev) => new Map(prev).set(registration.id, toRegistrationView(registration)));
96
+ }
89
97
  /**
90
98
  * Registers a hotkey sequence handler.
91
99
  *
@@ -238,8 +246,11 @@ var SequenceManager = class SequenceManager {
238
246
  }
239
247
  }
240
248
  if (registration.options.eventType !== eventType) continue;
241
- const timeout = registration.options.timeout ?? DEFAULT_SEQUENCE_TIMEOUT;
242
- if (registration.currentIndex > 0 && now - registration.lastKeyTime > timeout) registration.currentIndex = 0;
249
+ const timeout = registration.options.timeout ?? 1e3;
250
+ if (registration.currentIndex > 0 && now - registration.lastKeyTime > timeout) {
251
+ registration.currentIndex = 0;
252
+ this.#syncRegistrationView(registration);
253
+ }
243
254
  const expectedHotkey = registration.parsedSequence[registration.currentIndex];
244
255
  if (!expectedHotkey) continue;
245
256
  if (require_match.matchesKeyboardEvent(event, expectedHotkey, registration.options.platform)) {
@@ -252,15 +263,18 @@ var SequenceManager = class SequenceManager {
252
263
  hotkey: registration.sequence.join(" "),
253
264
  parsedHotkey: registration.parsedSequence[registration.parsedSequence.length - 1]
254
265
  };
255
- registration.callback(event, context);
266
+ registration.triggerCount++;
256
267
  registration.currentIndex = 0;
257
- }
268
+ this.#syncRegistrationView(registration);
269
+ registration.callback(event, context);
270
+ } else this.#syncRegistrationView(registration);
258
271
  } else if (registration.currentIndex > 0) {
259
272
  const firstHotkey = registration.parsedSequence[0];
260
273
  if (require_match.matchesKeyboardEvent(event, firstHotkey, registration.options.platform)) {
261
274
  registration.currentIndex = 1;
262
275
  registration.lastKeyTime = now;
263
276
  } else registration.currentIndex = 0;
277
+ this.#syncRegistrationView(registration);
264
278
  }
265
279
  }
266
280
  }
@@ -279,6 +293,7 @@ var SequenceManager = class SequenceManager {
279
293
  for (const registration of this.#registrations.values()) {
280
294
  registration.currentIndex = 0;
281
295
  registration.lastKeyTime = 0;
296
+ this.#syncRegistrationView(registration);
282
297
  }
283
298
  }
284
299
  /**
@@ -303,7 +318,7 @@ var SequenceManager = class SequenceManager {
303
318
  cancelable: true
304
319
  });
305
320
  registration.triggerCount++;
306
- this.registrations.setState((prev) => new Map(prev).set(id, toRegistrationView(registration)));
321
+ this.#syncRegistrationView(registration);
307
322
  const context = {
308
323
  hotkey: registration.sequence.join(" "),
309
324
  parsedHotkey: lastParsed
@@ -357,7 +372,7 @@ function getSequenceManager() {
357
372
  */
358
373
  function createSequenceMatcher(sequence, options = {}) {
359
374
  const platform = options.platform ?? require_constants.detectPlatform();
360
- const timeout = options.timeout ?? DEFAULT_SEQUENCE_TIMEOUT;
375
+ const timeout = options.timeout ?? 1e3;
361
376
  const parsedSequence = sequence.map((hotkey) => require_parse.parseHotkey(hotkey, platform));
362
377
  let currentIndex = 0;
363
378
  let lastKeyTime = 0;
@@ -391,6 +406,7 @@ function createSequenceMatcher(sequence, options = {}) {
391
406
  }
392
407
 
393
408
  //#endregion
409
+ exports.DEFAULT_SEQUENCE_TIMEOUT = DEFAULT_SEQUENCE_TIMEOUT;
394
410
  exports.SequenceManager = SequenceManager;
395
411
  exports.createSequenceMatcher = createSequenceMatcher;
396
412
  exports.getSequenceManager = getSequenceManager;
@@ -1 +1 @@
1
- {"version":3,"file":"sequence-manager.cjs","names":["#instance","Store","#platform","detectPlatform","parseHotkey","#findConflictingSequence","formatHotkeySequence","#unregister","getDefaultIgnoreInputs","defaultHotkeyOptions","#registrations","#targetRegistrations","#ensureListenersForTarget","#removeListenersForTarget","#targetListeners","#createTargetKeyDownHandler","#createTargetKeyUpHandler","#processTargetEvent","isModifierKey","isEventForTarget","isInputElement","matchesKeyboardEvent"],"sources":["../src/sequence-manager.ts"],"sourcesContent":["import { Store } from '@tanstack/store'\nimport { formatHotkeySequence } from './format'\nimport { detectPlatform } from './constants'\nimport { isModifierKey, parseHotkey } from './parse'\nimport { matchesKeyboardEvent } from './match'\nimport {\n defaultHotkeyOptions,\n getDefaultIgnoreInputs,\n handleConflict,\n isEventForTarget,\n isInputElement,\n} from './manager.utils'\nimport type { HotkeyOptions } from './hotkey-manager'\nimport type {\n Hotkey,\n HotkeyCallback,\n HotkeyCallbackContext,\n ParsedHotkey,\n} from './hotkey'\n\ntype Target = HTMLElement | Document | Window\n\n/**\n * Options for hotkey sequence matching.\n * Extends HotkeyOptions but excludes requireReset (not applicable to sequences).\n */\nexport interface SequenceOptions extends Omit<HotkeyOptions, 'requireReset'> {\n /** Timeout between keys in milliseconds. Default: 1000 */\n timeout?: number\n}\n\n/**\n * A sequence of hotkeys for Vim-style shortcuts.\n *\n * Each element is one step (a `Hotkey` string). Steps may include modifiers;\n * the same modifier can appear on consecutive steps (e.g. `Shift+R` then\n * `Shift+T`). Modifier-only key events do not advance or reset matching—see\n * `SequenceManager`.\n *\n * @example\n * ```ts\n * const gotoTop: HotkeySequence = ['G', 'G'] // gg\n * const deleteLine: HotkeySequence = ['D', 'D'] // dd\n * const deleteWord: HotkeySequence = ['D', 'I', 'W'] // diw\n * const chainedShift: HotkeySequence = ['Shift+R', 'Shift+T']\n * ```\n */\nexport type HotkeySequence = Array<Hotkey>\n\n/**\n * Default timeout between keys in a sequence (in milliseconds).\n */\nconst DEFAULT_SEQUENCE_TIMEOUT = 1000\n\nlet sequenceIdCounter = 0\n\n/**\n * Generates a unique ID for sequence registrations.\n */\nfunction generateSequenceId(): string {\n return `sequence_${++sequenceIdCounter}`\n}\n\n/**\n * Returns a canonical string for sequence conflict comparison.\n */\nfunction sequenceKey(sequence: HotkeySequence): string {\n return sequence.join('|')\n}\n\n/**\n * View of a sequence registration for devtools display.\n * Excludes internal matching state (currentIndex, lastKeyTime).\n */\nexport interface SequenceRegistrationView {\n id: string\n sequence: HotkeySequence\n options: SequenceOptions\n target: Target\n triggerCount: number\n}\n\n/**\n * Internal representation of a sequence registration.\n */\ninterface SequenceRegistration {\n id: string\n sequence: HotkeySequence\n parsedSequence: Array<ParsedHotkey>\n callback: HotkeyCallback\n options: SequenceOptions\n target: Target\n currentIndex: number\n lastKeyTime: number\n triggerCount: number\n}\n\n/**\n * A handle returned from SequenceManager.register() that allows updating\n * the callback and options without re-registering the sequence.\n *\n * @example\n * ```ts\n * const handle = manager.register(['G', 'G'], callback, options)\n *\n * handle.callback = newCallback\n * handle.setOptions({ timeout: 500 })\n * handle.unregister()\n * ```\n */\nexport interface SequenceRegistrationHandle {\n readonly id: string\n readonly isActive: boolean\n callback: HotkeyCallback\n setOptions: (options: Partial<SequenceOptions>) => void\n unregister: () => void\n}\n\n/**\n * Manages keyboard sequence matching for Vim-style shortcuts.\n *\n * This class allows registering multi-key sequences like 'g g' or 'd d'\n * that trigger callbacks when the full sequence is pressed within\n * a configurable timeout.\n *\n * Modifier-only `keydown` / `keyup` events (Shift, Control, Alt, or Meta\n * alone) are not processed: they neither match a step nor reset progress.\n * That supports chained modifier chords (e.g. `Shift+R` then `Shift+T`) when\n * the user presses a modifier alone between steps.\n *\n * @example\n * ```ts\n * const matcher = SequenceManager.getInstance()\n *\n * // Register 'g g' to go to top\n * const unregister = matcher.register(['G', 'G'], (event, context) => {\n * scrollToTop()\n * }, { timeout: 500 })\n *\n * // Later, to unregister:\n * unregister()\n * ```\n */\n/**\n * Builds a devtools view from an internal registration.\n */\nfunction toRegistrationView(\n reg: SequenceRegistration,\n): SequenceRegistrationView {\n return {\n id: reg.id,\n sequence: reg.sequence,\n options: reg.options,\n target: reg.target,\n triggerCount: reg.triggerCount,\n }\n}\n\nexport class SequenceManager {\n static #instance: SequenceManager | null = null\n\n /**\n * The TanStack Store containing sequence registration views for devtools.\n * Subscribe to this to observe registration changes.\n */\n readonly registrations: Store<Map<string, SequenceRegistrationView>> =\n new Store(new Map())\n\n #registrations: Map<string, SequenceRegistration> = new Map()\n #targetListeners: Map<\n Target,\n {\n keydown: (event: KeyboardEvent) => void\n keyup: (event: KeyboardEvent) => void\n }\n > = new Map()\n #targetRegistrations: Map<Target, Set<string>> = new Map()\n #platform: 'mac' | 'windows' | 'linux'\n\n private constructor() {\n this.#platform = detectPlatform()\n }\n\n /**\n * Gets the singleton instance of SequenceManager.\n */\n static getInstance(): SequenceManager {\n if (!SequenceManager.#instance) {\n SequenceManager.#instance = new SequenceManager()\n }\n return SequenceManager.#instance\n }\n\n /**\n * Resets the singleton instance. Useful for testing.\n */\n static resetInstance(): void {\n if (SequenceManager.#instance) {\n SequenceManager.#instance.destroy()\n SequenceManager.#instance = null\n }\n }\n\n /**\n * Registers a hotkey sequence handler.\n *\n * @param sequence - Array of hotkey strings that form the sequence\n * @param callback - Function to call when the sequence is completed\n * @param options - Options for the sequence behavior\n * @returns A handle to update or unregister the sequence\n */\n register(\n sequence: HotkeySequence,\n callback: HotkeyCallback,\n options: SequenceOptions = {},\n ): SequenceRegistrationHandle {\n if (sequence.length === 0) {\n throw new Error('Sequence must contain at least one hotkey')\n }\n\n const id = generateSequenceId()\n const platform = options.platform ?? this.#platform\n const parsedSequence = sequence.map((hotkey) =>\n parseHotkey(hotkey, platform),\n )\n\n // Resolve target: default to document if not provided or null\n const target: Target =\n options.target ??\n (typeof document !== 'undefined' ? document : ({} as Document))\n\n // Resolve conflict behavior\n const conflictBehavior = options.conflictBehavior ?? 'warn'\n\n // Check for existing registrations with the same sequence and target\n const conflictingRegistration = this.#findConflictingSequence(\n sequence,\n target,\n )\n\n if (conflictingRegistration) {\n handleConflict(\n conflictingRegistration.id,\n formatHotkeySequence(sequence),\n conflictBehavior,\n (regId) => this.#unregister(regId),\n )\n }\n\n const firstStep = parsedSequence[0]!\n const resolvedIgnoreInputs =\n options.ignoreInputs ?? getDefaultIgnoreInputs(firstStep)\n\n const baseOptions = {\n ...defaultHotkeyOptions,\n timeout: DEFAULT_SEQUENCE_TIMEOUT,\n ...options,\n platform,\n ignoreInputs: resolvedIgnoreInputs,\n }\n\n const registration: SequenceRegistration = {\n id,\n sequence,\n parsedSequence,\n callback,\n options: baseOptions,\n target,\n currentIndex: 0,\n lastKeyTime: 0,\n triggerCount: 0,\n }\n\n this.#registrations.set(id, registration)\n this.registrations.setState((prev) =>\n new Map(prev).set(id, toRegistrationView(registration)),\n )\n\n // Track registration for this target\n if (!this.#targetRegistrations.has(target)) {\n this.#targetRegistrations.set(target, new Set())\n }\n this.#targetRegistrations.get(target)!.add(id)\n\n // Ensure listeners are attached for this target\n this.#ensureListenersForTarget(target)\n\n const manager = this\n const handle: SequenceRegistrationHandle = {\n get id() {\n return id\n },\n get isActive() {\n return manager.#registrations.has(id)\n },\n get callback() {\n const reg = manager.#registrations.get(id)\n return reg?.callback ?? callback\n },\n set callback(newCallback: HotkeyCallback) {\n const reg = manager.#registrations.get(id)\n if (reg) {\n reg.callback = newCallback\n }\n },\n setOptions: (newOptions: Partial<SequenceOptions>) => {\n const reg = manager.#registrations.get(id)\n if (reg) {\n reg.options = { ...reg.options, ...newOptions }\n manager.registrations.setState((prev) =>\n new Map(prev).set(id, toRegistrationView(reg)),\n )\n }\n },\n unregister: () => {\n manager.#unregister(id)\n },\n }\n\n return handle\n }\n\n /**\n * Unregisters a sequence by its registration ID.\n */\n #unregister(id: string): void {\n const registration = this.#registrations.get(id)\n if (!registration) {\n return\n }\n\n const target = registration.target\n\n this.#registrations.delete(id)\n this.registrations.setState((prev) => {\n const next = new Map(prev)\n next.delete(id)\n return next\n })\n\n // Remove from target registrations tracking\n const targetRegs = this.#targetRegistrations.get(target)\n if (targetRegs) {\n targetRegs.delete(id)\n if (targetRegs.size === 0) {\n this.#removeListenersForTarget(target)\n }\n }\n }\n\n /**\n * Ensures event listeners are attached for a specific target.\n */\n #ensureListenersForTarget(target: Target): void {\n if (typeof document === 'undefined') {\n return // SSR safety\n }\n\n if (this.#targetListeners.has(target)) {\n return\n }\n\n const keydownHandler = this.#createTargetKeyDownHandler(target)\n const keyupHandler = this.#createTargetKeyUpHandler(target)\n\n target.addEventListener('keydown', keydownHandler as EventListener)\n target.addEventListener('keyup', keyupHandler as EventListener)\n\n this.#targetListeners.set(target, {\n keydown: keydownHandler,\n keyup: keyupHandler,\n })\n }\n\n /**\n * Removes event listeners for a specific target.\n */\n #removeListenersForTarget(target: Target): void {\n if (typeof document === 'undefined') {\n return\n }\n\n const listeners = this.#targetListeners.get(target)\n if (!listeners) {\n return\n }\n\n target.removeEventListener('keydown', listeners.keydown as EventListener)\n target.removeEventListener('keyup', listeners.keyup as EventListener)\n\n this.#targetListeners.delete(target)\n this.#targetRegistrations.delete(target)\n }\n\n /**\n * Creates a keydown handler for a specific target.\n */\n #createTargetKeyDownHandler(target: Target): (event: KeyboardEvent) => void {\n return (event: KeyboardEvent) => {\n this.#processTargetEvent(event, target, 'keydown')\n }\n }\n\n /**\n * Creates a keyup handler for a specific target.\n */\n #createTargetKeyUpHandler(target: Target): (event: KeyboardEvent) => void {\n return (event: KeyboardEvent) => {\n this.#processTargetEvent(event, target, 'keyup')\n }\n }\n\n /**\n * Processes keyboard events for a specific target and event type.\n */\n #processTargetEvent(\n event: KeyboardEvent,\n target: Target,\n eventType: 'keydown' | 'keyup',\n ): void {\n // Skip modifier-only events so pressing e.g. Shift before Shift+C does not reset the sequence.\n if (isModifierKey(event)) {\n return\n }\n\n const targetRegs = this.#targetRegistrations.get(target)\n if (!targetRegs) {\n return\n }\n\n const now = Date.now()\n\n for (const id of targetRegs) {\n const registration = this.#registrations.get(id)\n if (!registration) {\n continue\n }\n\n if (!isEventForTarget(event, target)) {\n continue\n }\n\n if (!registration.options.enabled) {\n continue\n }\n\n // Check if we should ignore input elements (defaults to true)\n if (registration.options.ignoreInputs !== false) {\n if (isInputElement(event.target)) {\n // Don't ignore if the sequence is explicitly scoped to this input element\n if (event.target !== registration.target) {\n continue\n }\n }\n }\n\n // Only process registrations that listen for this event type\n if (registration.options.eventType !== eventType) {\n continue\n }\n\n const timeout = registration.options.timeout ?? DEFAULT_SEQUENCE_TIMEOUT\n\n // Check if sequence has timed out\n if (\n registration.currentIndex > 0 &&\n now - registration.lastKeyTime > timeout\n ) {\n registration.currentIndex = 0\n }\n\n const expectedHotkey =\n registration.parsedSequence[registration.currentIndex]\n if (!expectedHotkey) {\n continue\n }\n\n if (\n matchesKeyboardEvent(\n event,\n expectedHotkey,\n registration.options.platform,\n )\n ) {\n registration.lastKeyTime = now\n registration.currentIndex++\n\n if (registration.currentIndex >= registration.parsedSequence.length) {\n if (registration.options.preventDefault) {\n event.preventDefault()\n }\n if (registration.options.stopPropagation) {\n event.stopPropagation()\n }\n\n const context: HotkeyCallbackContext = {\n hotkey: registration.sequence.join(' ') as Hotkey,\n parsedHotkey:\n registration.parsedSequence[\n registration.parsedSequence.length - 1\n ]!,\n }\n\n registration.callback(event, context)\n\n registration.currentIndex = 0\n }\n } else if (registration.currentIndex > 0) {\n const firstHotkey = registration.parsedSequence[0]!\n if (\n matchesKeyboardEvent(\n event,\n firstHotkey,\n registration.options.platform,\n )\n ) {\n registration.currentIndex = 1\n registration.lastKeyTime = now\n } else {\n registration.currentIndex = 0\n }\n }\n }\n }\n\n /**\n * Finds an existing registration with the same sequence and target.\n */\n #findConflictingSequence(\n sequence: HotkeySequence,\n target: Target,\n ): SequenceRegistration | null {\n const key = sequenceKey(sequence)\n for (const registration of this.#registrations.values()) {\n if (\n sequenceKey(registration.sequence) === key &&\n registration.target === target\n ) {\n return registration\n }\n }\n return null\n }\n\n /**\n * Resets all sequence progress.\n */\n resetAll(): void {\n for (const registration of this.#registrations.values()) {\n registration.currentIndex = 0\n registration.lastKeyTime = 0\n }\n }\n\n /**\n * Triggers a sequence's callback programmatically from devtools.\n * Creates a synthetic KeyboardEvent from the last key in the sequence.\n *\n * @param id - The registration ID to trigger\n * @returns True if the registration was found and triggered\n */\n triggerSequence(id: string): boolean {\n const registration = this.#registrations.get(id)\n if (!registration) {\n return false\n }\n\n const lastParsed =\n registration.parsedSequence[registration.parsedSequence.length - 1]\n if (!lastParsed) {\n return false\n }\n\n const syntheticEvent = new KeyboardEvent(\n registration.options.eventType ?? 'keydown',\n {\n key: lastParsed.key,\n ctrlKey: lastParsed.ctrl,\n shiftKey: lastParsed.shift,\n altKey: lastParsed.alt,\n metaKey: lastParsed.meta,\n bubbles: true,\n cancelable: true,\n },\n )\n\n registration.triggerCount++\n\n this.registrations.setState((prev) =>\n new Map(prev).set(id, toRegistrationView(registration)),\n )\n\n const context: HotkeyCallbackContext = {\n hotkey: registration.sequence.join(' ') as Hotkey,\n parsedHotkey: lastParsed,\n }\n\n registration.callback(syntheticEvent, context)\n\n return true\n }\n\n /**\n * Gets the number of registered sequences.\n */\n getRegistrationCount(): number {\n return this.#registrations.size\n }\n\n /**\n * Destroys the manager and removes all listeners.\n */\n destroy(): void {\n for (const target of this.#targetListeners.keys()) {\n this.#removeListenersForTarget(target)\n }\n this.#registrations.clear()\n this.registrations.setState(() => new Map())\n }\n}\n\n/**\n * Gets the singleton SequenceManager instance.\n * Convenience function for accessing the manager.\n */\nexport function getSequenceManager(): SequenceManager {\n return SequenceManager.getInstance()\n}\n\n/**\n * Creates a simple sequence matcher for one-off use.\n *\n * This is a low-level helper that does not support ignoreInputs, target,\n * or other HotkeyOptions. Callers must handle input filtering themselves\n * if attaching to document.\n *\n * @param sequence - The sequence of hotkeys to match\n * @param options - Options including timeout\n * @returns An object with match() and reset() methods\n *\n * @example\n * ```ts\n * const matcher = createSequenceMatcher(['G', 'G'], { timeout: 500 })\n *\n * document.addEventListener('keydown', (event) => {\n * if (matcher.match(event)) {\n * console.log('Sequence matched!')\n * }\n * })\n * ```\n */\nexport function createSequenceMatcher(\n sequence: HotkeySequence,\n options: { timeout?: number; platform?: 'mac' | 'windows' | 'linux' } = {},\n): {\n match: (event: KeyboardEvent) => boolean\n reset: () => void\n getProgress: () => number\n} {\n const platform = options.platform ?? detectPlatform()\n const timeout = options.timeout ?? DEFAULT_SEQUENCE_TIMEOUT\n const parsedSequence = sequence.map((hotkey) => parseHotkey(hotkey, platform))\n\n let currentIndex = 0\n let lastKeyTime = 0\n\n return {\n match(event: KeyboardEvent): boolean {\n const now = Date.now()\n\n if (currentIndex > 0 && now - lastKeyTime > timeout) {\n currentIndex = 0\n }\n\n const expected = parsedSequence[currentIndex]\n if (!expected) {\n return false\n }\n\n if (matchesKeyboardEvent(event, expected, platform)) {\n lastKeyTime = now\n currentIndex++\n\n if (currentIndex >= parsedSequence.length) {\n currentIndex = 0\n return true\n }\n } else if (currentIndex > 0) {\n if (matchesKeyboardEvent(event, parsedSequence[0]!, platform)) {\n currentIndex = 1\n lastKeyTime = now\n } else {\n currentIndex = 0\n }\n }\n\n return false\n },\n\n reset(): void {\n currentIndex = 0\n lastKeyTime = 0\n },\n\n getProgress(): number {\n return currentIndex\n },\n }\n}\n"],"mappings":";;;;;;;;;;;AAoDA,MAAM,2BAA2B;AAEjC,IAAI,oBAAoB;;;;AAKxB,SAAS,qBAA6B;AACpC,QAAO,YAAY,EAAE;;;;;AAMvB,SAAS,YAAY,UAAkC;AACrD,QAAO,SAAS,KAAK,IAAI;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+E3B,SAAS,mBACP,KAC0B;AAC1B,QAAO;EACL,IAAI,IAAI;EACR,UAAU,IAAI;EACd,SAAS,IAAI;EACb,QAAQ,IAAI;EACZ,cAAc,IAAI;EACnB;;AAGH,IAAa,kBAAb,MAAa,gBAAgB;CAC3B,QAAOA,WAAoC;CAS3C,iCAAoD,IAAI,KAAK;CAC7D,mCAMI,IAAI,KAAK;CACb,uCAAiD,IAAI,KAAK;CAC1D;CAEA,AAAQ,c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,"file":"sequence-manager.cjs","names":["#instance","Store","#platform","detectPlatform","parseHotkey","#findConflictingSequence","formatHotkeySequence","#unregister","getDefaultIgnoreInputs","defaultHotkeyOptions","#registrations","#targetRegistrations","#ensureListenersForTarget","#removeListenersForTarget","#targetListeners","#createTargetKeyDownHandler","#createTargetKeyUpHandler","#processTargetEvent","isModifierKey","isEventForTarget","isInputElement","#syncRegistrationView","matchesKeyboardEvent"],"sources":["../src/sequence-manager.ts"],"sourcesContent":["import { Store } from '@tanstack/store'\nimport { formatHotkeySequence } from './format'\nimport { detectPlatform } from './constants'\nimport { isModifierKey, parseHotkey } from './parse'\nimport { matchesKeyboardEvent } from './match'\nimport {\n defaultHotkeyOptions,\n getDefaultIgnoreInputs,\n handleConflict,\n isEventForTarget,\n isInputElement,\n} from './manager.utils'\nimport type { HotkeyOptions } from './hotkey-manager'\nimport type {\n Hotkey,\n HotkeyCallback,\n HotkeyCallbackContext,\n ParsedHotkey,\n} from './hotkey'\n\ntype Target = HTMLElement | Document | Window\n\n/**\n * Options for hotkey sequence matching.\n * Extends HotkeyOptions but excludes requireReset (not applicable to sequences).\n */\nexport interface SequenceOptions extends Omit<HotkeyOptions, 'requireReset'> {\n /** Timeout between keys in milliseconds. Default: 1000 */\n timeout?: number\n}\n\n/**\n * A sequence of hotkeys for Vim-style shortcuts.\n *\n * Each element is one step (a `Hotkey` string). Steps may include modifiers;\n * the same modifier can appear on consecutive steps (e.g. `Shift+R` then\n * `Shift+T`). Modifier-only key events do not advance or reset matching—see\n * `SequenceManager`.\n *\n * @example\n * ```ts\n * const gotoTop: HotkeySequence = ['G', 'G'] // gg\n * const deleteLine: HotkeySequence = ['D', 'D'] // dd\n * const deleteWord: HotkeySequence = ['D', 'I', 'W'] // diw\n * const chainedShift: HotkeySequence = ['Shift+R', 'Shift+T']\n * ```\n */\nexport type HotkeySequence = Array<Hotkey>\n\n/**\n * Default timeout between keys in a sequence (in milliseconds).\n * Exported for consumers that display sequence state (e.g. devtools).\n */\nexport const DEFAULT_SEQUENCE_TIMEOUT = 1000\n\nlet sequenceIdCounter = 0\n\n/**\n * Generates a unique ID for sequence registrations.\n */\nfunction generateSequenceId(): string {\n return `sequence_${++sequenceIdCounter}`\n}\n\n/**\n * Returns a canonical string for sequence conflict comparison.\n */\nfunction sequenceKey(sequence: HotkeySequence): string {\n return sequence.join('|')\n}\n\n/**\n * View of a sequence registration for devtools display.\n * Progress fields reflect an in-progress match (between first key and completion or timeout).\n */\nexport interface SequenceRegistrationView {\n id: string\n sequence: HotkeySequence\n options: SequenceOptions\n target: Target\n triggerCount: number\n /** Steps matched in the current attempt (0 when idle or just completed). */\n matchedStepCount: number\n /** `Date.now()` when the last step in the current attempt matched; 0 if none. */\n partialMatchLastKeyTime: number\n}\n\n/**\n * Internal representation of a sequence registration.\n */\ninterface SequenceRegistration {\n id: string\n sequence: HotkeySequence\n parsedSequence: Array<ParsedHotkey>\n callback: HotkeyCallback\n options: SequenceOptions\n target: Target\n currentIndex: number\n lastKeyTime: number\n triggerCount: number\n}\n\n/**\n * A handle returned from SequenceManager.register() that allows updating\n * the callback and options without re-registering the sequence.\n *\n * @example\n * ```ts\n * const handle = manager.register(['G', 'G'], callback, options)\n *\n * handle.callback = newCallback\n * handle.setOptions({ timeout: 500 })\n * handle.unregister()\n * ```\n */\nexport interface SequenceRegistrationHandle {\n readonly id: string\n readonly isActive: boolean\n callback: HotkeyCallback\n setOptions: (options: Partial<SequenceOptions>) => void\n unregister: () => void\n}\n\n/**\n * Manages keyboard sequence matching for Vim-style shortcuts.\n *\n * This class allows registering multi-key sequences like 'g g' or 'd d'\n * that trigger callbacks when the full sequence is pressed within\n * a configurable timeout.\n *\n * Modifier-only `keydown` / `keyup` events (Shift, Control, Alt, or Meta\n * alone) are not processed: they neither match a step nor reset progress.\n * That supports chained modifier chords (e.g. `Shift+R` then `Shift+T`) when\n * the user presses a modifier alone between steps.\n *\n * @example\n * ```ts\n * const matcher = SequenceManager.getInstance()\n *\n * // Register 'g g' to go to top\n * const unregister = matcher.register(['G', 'G'], (event, context) => {\n * scrollToTop()\n * }, { timeout: 500 })\n *\n * // Later, to unregister:\n * unregister()\n * ```\n */\n/**\n * Builds a devtools view from an internal registration.\n */\nfunction toRegistrationView(\n reg: SequenceRegistration,\n): SequenceRegistrationView {\n const len = reg.parsedSequence.length\n const inProgress = reg.currentIndex > 0 && reg.currentIndex < len\n return {\n id: reg.id,\n sequence: reg.sequence,\n options: reg.options,\n target: reg.target,\n triggerCount: reg.triggerCount,\n matchedStepCount: inProgress ? reg.currentIndex : 0,\n partialMatchLastKeyTime: inProgress ? reg.lastKeyTime : 0,\n }\n}\n\nexport class SequenceManager {\n static #instance: SequenceManager | null = null\n\n /**\n * The TanStack Store containing sequence registration views for devtools.\n * Subscribe to this to observe registration changes.\n */\n readonly registrations: Store<Map<string, SequenceRegistrationView>> =\n new Store(new Map())\n\n #registrations: Map<string, SequenceRegistration> = new Map()\n #targetListeners: Map<\n Target,\n {\n keydown: (event: KeyboardEvent) => void\n keyup: (event: KeyboardEvent) => void\n }\n > = new Map()\n #targetRegistrations: Map<Target, Set<string>> = new Map()\n #platform: 'mac' | 'windows' | 'linux'\n\n private constructor() {\n this.#platform = detectPlatform()\n }\n\n /**\n * Gets the singleton instance of SequenceManager.\n */\n static getInstance(): SequenceManager {\n if (!SequenceManager.#instance) {\n SequenceManager.#instance = new SequenceManager()\n }\n return SequenceManager.#instance\n }\n\n /**\n * Resets the singleton instance. Useful for testing.\n */\n static resetInstance(): void {\n if (SequenceManager.#instance) {\n SequenceManager.#instance.destroy()\n SequenceManager.#instance = null\n }\n }\n\n #syncRegistrationView(registration: SequenceRegistration): void {\n this.registrations.setState((prev) =>\n new Map(prev).set(registration.id, toRegistrationView(registration)),\n )\n }\n\n /**\n * Registers a hotkey sequence handler.\n *\n * @param sequence - Array of hotkey strings that form the sequence\n * @param callback - Function to call when the sequence is completed\n * @param options - Options for the sequence behavior\n * @returns A handle to update or unregister the sequence\n */\n register(\n sequence: HotkeySequence,\n callback: HotkeyCallback,\n options: SequenceOptions = {},\n ): SequenceRegistrationHandle {\n if (sequence.length === 0) {\n throw new Error('Sequence must contain at least one hotkey')\n }\n\n const id = generateSequenceId()\n const platform = options.platform ?? this.#platform\n const parsedSequence = sequence.map((hotkey) =>\n parseHotkey(hotkey, platform),\n )\n\n // Resolve target: default to document if not provided or null\n const target: Target =\n options.target ??\n (typeof document !== 'undefined' ? document : ({} as Document))\n\n // Resolve conflict behavior\n const conflictBehavior = options.conflictBehavior ?? 'warn'\n\n // Check for existing registrations with the same sequence and target\n const conflictingRegistration = this.#findConflictingSequence(\n sequence,\n target,\n )\n\n if (conflictingRegistration) {\n handleConflict(\n conflictingRegistration.id,\n formatHotkeySequence(sequence),\n conflictBehavior,\n (regId) => this.#unregister(regId),\n )\n }\n\n const firstStep = parsedSequence[0]!\n const resolvedIgnoreInputs =\n options.ignoreInputs ?? getDefaultIgnoreInputs(firstStep)\n\n const baseOptions = {\n ...defaultHotkeyOptions,\n timeout: DEFAULT_SEQUENCE_TIMEOUT,\n ...options,\n platform,\n ignoreInputs: resolvedIgnoreInputs,\n }\n\n const registration: SequenceRegistration = {\n id,\n sequence,\n parsedSequence,\n callback,\n options: baseOptions,\n target,\n currentIndex: 0,\n lastKeyTime: 0,\n triggerCount: 0,\n }\n\n this.#registrations.set(id, registration)\n this.registrations.setState((prev) =>\n new Map(prev).set(id, toRegistrationView(registration)),\n )\n\n // Track registration for this target\n if (!this.#targetRegistrations.has(target)) {\n this.#targetRegistrations.set(target, new Set())\n }\n this.#targetRegistrations.get(target)!.add(id)\n\n // Ensure listeners are attached for this target\n this.#ensureListenersForTarget(target)\n\n const manager = this\n const handle: SequenceRegistrationHandle = {\n get id() {\n return id\n },\n get isActive() {\n return manager.#registrations.has(id)\n },\n get callback() {\n const reg = manager.#registrations.get(id)\n return reg?.callback ?? callback\n },\n set callback(newCallback: HotkeyCallback) {\n const reg = manager.#registrations.get(id)\n if (reg) {\n reg.callback = newCallback\n }\n },\n setOptions: (newOptions: Partial<SequenceOptions>) => {\n const reg = manager.#registrations.get(id)\n if (reg) {\n reg.options = { ...reg.options, ...newOptions }\n manager.registrations.setState((prev) =>\n new Map(prev).set(id, toRegistrationView(reg)),\n )\n }\n },\n unregister: () => {\n manager.#unregister(id)\n },\n }\n\n return handle\n }\n\n /**\n * Unregisters a sequence by its registration ID.\n */\n #unregister(id: string): void {\n const registration = this.#registrations.get(id)\n if (!registration) {\n return\n }\n\n const target = registration.target\n\n this.#registrations.delete(id)\n this.registrations.setState((prev) => {\n const next = new Map(prev)\n next.delete(id)\n return next\n })\n\n // Remove from target registrations tracking\n const targetRegs = this.#targetRegistrations.get(target)\n if (targetRegs) {\n targetRegs.delete(id)\n if (targetRegs.size === 0) {\n this.#removeListenersForTarget(target)\n }\n }\n }\n\n /**\n * Ensures event listeners are attached for a specific target.\n */\n #ensureListenersForTarget(target: Target): void {\n if (typeof document === 'undefined') {\n return // SSR safety\n }\n\n if (this.#targetListeners.has(target)) {\n return\n }\n\n const keydownHandler = this.#createTargetKeyDownHandler(target)\n const keyupHandler = this.#createTargetKeyUpHandler(target)\n\n target.addEventListener('keydown', keydownHandler as EventListener)\n target.addEventListener('keyup', keyupHandler as EventListener)\n\n this.#targetListeners.set(target, {\n keydown: keydownHandler,\n keyup: keyupHandler,\n })\n }\n\n /**\n * Removes event listeners for a specific target.\n */\n #removeListenersForTarget(target: Target): void {\n if (typeof document === 'undefined') {\n return\n }\n\n const listeners = this.#targetListeners.get(target)\n if (!listeners) {\n return\n }\n\n target.removeEventListener('keydown', listeners.keydown as EventListener)\n target.removeEventListener('keyup', listeners.keyup as EventListener)\n\n this.#targetListeners.delete(target)\n this.#targetRegistrations.delete(target)\n }\n\n /**\n * Creates a keydown handler for a specific target.\n */\n #createTargetKeyDownHandler(target: Target): (event: KeyboardEvent) => void {\n return (event: KeyboardEvent) => {\n this.#processTargetEvent(event, target, 'keydown')\n }\n }\n\n /**\n * Creates a keyup handler for a specific target.\n */\n #createTargetKeyUpHandler(target: Target): (event: KeyboardEvent) => void {\n return (event: KeyboardEvent) => {\n this.#processTargetEvent(event, target, 'keyup')\n }\n }\n\n /**\n * Processes keyboard events for a specific target and event type.\n */\n #processTargetEvent(\n event: KeyboardEvent,\n target: Target,\n eventType: 'keydown' | 'keyup',\n ): void {\n // Skip modifier-only events so pressing e.g. Shift before Shift+C does not reset the sequence.\n if (isModifierKey(event)) {\n return\n }\n\n const targetRegs = this.#targetRegistrations.get(target)\n if (!targetRegs) {\n return\n }\n\n const now = Date.now()\n\n for (const id of targetRegs) {\n const registration = this.#registrations.get(id)\n if (!registration) {\n continue\n }\n\n if (!isEventForTarget(event, target)) {\n continue\n }\n\n if (!registration.options.enabled) {\n continue\n }\n\n // Check if we should ignore input elements (defaults to true)\n if (registration.options.ignoreInputs !== false) {\n if (isInputElement(event.target)) {\n // Don't ignore if the sequence is explicitly scoped to this input element\n if (event.target !== registration.target) {\n continue\n }\n }\n }\n\n // Only process registrations that listen for this event type\n if (registration.options.eventType !== eventType) {\n continue\n }\n\n const timeout = registration.options.timeout ?? DEFAULT_SEQUENCE_TIMEOUT\n\n // Check if sequence has timed out\n if (\n registration.currentIndex > 0 &&\n now - registration.lastKeyTime > timeout\n ) {\n registration.currentIndex = 0\n this.#syncRegistrationView(registration)\n }\n\n const expectedHotkey =\n registration.parsedSequence[registration.currentIndex]\n if (!expectedHotkey) {\n continue\n }\n\n if (\n matchesKeyboardEvent(\n event,\n expectedHotkey,\n registration.options.platform,\n )\n ) {\n registration.lastKeyTime = now\n registration.currentIndex++\n\n if (registration.currentIndex >= registration.parsedSequence.length) {\n if (registration.options.preventDefault) {\n event.preventDefault()\n }\n if (registration.options.stopPropagation) {\n event.stopPropagation()\n }\n\n const context: HotkeyCallbackContext = {\n hotkey: registration.sequence.join(' ') as Hotkey,\n parsedHotkey:\n registration.parsedSequence[\n registration.parsedSequence.length - 1\n ]!,\n }\n\n registration.triggerCount++\n registration.currentIndex = 0\n\n this.#syncRegistrationView(registration)\n\n registration.callback(event, context)\n } else {\n this.#syncRegistrationView(registration)\n }\n } else if (registration.currentIndex > 0) {\n const firstHotkey = registration.parsedSequence[0]!\n if (\n matchesKeyboardEvent(\n event,\n firstHotkey,\n registration.options.platform,\n )\n ) {\n registration.currentIndex = 1\n registration.lastKeyTime = now\n } else {\n registration.currentIndex = 0\n }\n this.#syncRegistrationView(registration)\n }\n }\n }\n\n /**\n * Finds an existing registration with the same sequence and target.\n */\n #findConflictingSequence(\n sequence: HotkeySequence,\n target: Target,\n ): SequenceRegistration | null {\n const key = sequenceKey(sequence)\n for (const registration of this.#registrations.values()) {\n if (\n sequenceKey(registration.sequence) === key &&\n registration.target === target\n ) {\n return registration\n }\n }\n return null\n }\n\n /**\n * Resets all sequence progress.\n */\n resetAll(): void {\n for (const registration of this.#registrations.values()) {\n registration.currentIndex = 0\n registration.lastKeyTime = 0\n this.#syncRegistrationView(registration)\n }\n }\n\n /**\n * Triggers a sequence's callback programmatically from devtools.\n * Creates a synthetic KeyboardEvent from the last key in the sequence.\n *\n * @param id - The registration ID to trigger\n * @returns True if the registration was found and triggered\n */\n triggerSequence(id: string): boolean {\n const registration = this.#registrations.get(id)\n if (!registration) {\n return false\n }\n\n const lastParsed =\n registration.parsedSequence[registration.parsedSequence.length - 1]\n if (!lastParsed) {\n return false\n }\n\n const syntheticEvent = new KeyboardEvent(\n registration.options.eventType ?? 'keydown',\n {\n key: lastParsed.key,\n ctrlKey: lastParsed.ctrl,\n shiftKey: lastParsed.shift,\n altKey: lastParsed.alt,\n metaKey: lastParsed.meta,\n bubbles: true,\n cancelable: true,\n },\n )\n\n registration.triggerCount++\n\n this.#syncRegistrationView(registration)\n\n const context: HotkeyCallbackContext = {\n hotkey: registration.sequence.join(' ') as Hotkey,\n parsedHotkey: lastParsed,\n }\n\n registration.callback(syntheticEvent, context)\n\n return true\n }\n\n /**\n * Gets the number of registered sequences.\n */\n getRegistrationCount(): number {\n return this.#registrations.size\n }\n\n /**\n * Destroys the manager and removes all listeners.\n */\n destroy(): void {\n for (const target of this.#targetListeners.keys()) {\n this.#removeListenersForTarget(target)\n }\n this.#registrations.clear()\n this.registrations.setState(() => new Map())\n }\n}\n\n/**\n * Gets the singleton SequenceManager instance.\n * Convenience function for accessing the manager.\n */\nexport function getSequenceManager(): SequenceManager {\n return SequenceManager.getInstance()\n}\n\n/**\n * Creates a simple sequence matcher for one-off use.\n *\n * This is a low-level helper that does not support ignoreInputs, target,\n * or other HotkeyOptions. Callers must handle input filtering themselves\n * if attaching to document.\n *\n * @param sequence - The sequence of hotkeys to match\n * @param options - Options including timeout\n * @returns An object with match() and reset() methods\n *\n * @example\n * ```ts\n * const matcher = createSequenceMatcher(['G', 'G'], { timeout: 500 })\n *\n * document.addEventListener('keydown', (event) => {\n * if (matcher.match(event)) {\n * console.log('Sequence matched!')\n * }\n * })\n * ```\n */\nexport function createSequenceMatcher(\n sequence: HotkeySequence,\n options: { timeout?: number; platform?: 'mac' | 'windows' | 'linux' } = {},\n): {\n match: (event: KeyboardEvent) => boolean\n reset: () => void\n getProgress: () => number\n} {\n const platform = options.platform ?? detectPlatform()\n const timeout = options.timeout ?? DEFAULT_SEQUENCE_TIMEOUT\n const parsedSequence = sequence.map((hotkey) => parseHotkey(hotkey, platform))\n\n let currentIndex = 0\n let lastKeyTime = 0\n\n return {\n match(event: KeyboardEvent): boolean {\n const now = Date.now()\n\n if (currentIndex > 0 && now - lastKeyTime > timeout) {\n currentIndex = 0\n }\n\n const expected = parsedSequence[currentIndex]\n if (!expected) {\n return false\n }\n\n if (matchesKeyboardEvent(event, expected, platform)) {\n lastKeyTime = now\n currentIndex++\n\n if (currentIndex >= parsedSequence.length) {\n currentIndex = 0\n return true\n }\n } else if (currentIndex > 0) {\n if (matchesKeyboardEvent(event, parsedSequence[0]!, platform)) {\n currentIndex = 1\n lastKeyTime = now\n } else {\n currentIndex = 0\n }\n }\n\n return false\n },\n\n reset(): void {\n currentIndex = 0\n lastKeyTime = 0\n },\n\n getProgress():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OAAKD,yBAA0B,OAAO;AAExC,QAAKH,cAAe,OAAO;AAC3B,OAAK,cAAc,+BAAe,IAAI,KAAK,CAAC;;;;;;;AAQhD,SAAgB,qBAAsC;AACpD,QAAO,gBAAgB,aAAa;;;;;;;;;;;;;;;;;;;;;;;;AAyBtC,SAAgB,sBACd,UACA,UAAwE,EAAE,EAK1E;CACA,MAAM,WAAW,QAAQ,YAAYP,kCAAgB;CACrD,MAAM,UAAU,QAAQ;CACxB,MAAM,iBAAiB,SAAS,KAAK,WAAWC,0BAAY,QAAQ,SAAS,CAAC;CAE9E,IAAI,eAAe;CACnB,IAAI,cAAc;AAElB,QAAO;EACL,MAAM,OAA+B;GACnC,MAAM,MAAM,KAAK,KAAK;AAEtB,OAAI,eAAe,KAAK,MAAM,cAAc,QAC1C,gBAAe;GAGjB,MAAM,WAAW,eAAe;AAChC,OAAI,CAAC,SACH,QAAO;AAGT,OAAIkB,mCAAqB,OAAO,UAAU,SAAS,EAAE;AACnD,kBAAc;AACd;AAEA,QAAI,gBAAgB,eAAe,QAAQ;AACzC,oBAAe;AACf,YAAO;;cAEA,eAAe,EACxB,KAAIA,mCAAqB,OAAO,eAAe,IAAK,SAAS,EAAE;AAC7D,mBAAe;AACf,kBAAc;SAEd,gBAAe;AAInB,UAAO;;EAGT,QAAc;AACZ,kBAAe;AACf,iBAAc;;EAGhB,cAAsB;AACpB,UAAO;;EAEV"}
@@ -29,9 +29,14 @@ interface SequenceOptions extends Omit<HotkeyOptions, 'requireReset'> {
29
29
  * ```
30
30
  */
31
31
  type HotkeySequence = Array<Hotkey>;
32
+ /**
33
+ * Default timeout between keys in a sequence (in milliseconds).
34
+ * Exported for consumers that display sequence state (e.g. devtools).
35
+ */
36
+ declare const DEFAULT_SEQUENCE_TIMEOUT = 1000;
32
37
  /**
33
38
  * View of a sequence registration for devtools display.
34
- * Excludes internal matching state (currentIndex, lastKeyTime).
39
+ * Progress fields reflect an in-progress match (between first key and completion or timeout).
35
40
  */
36
41
  interface SequenceRegistrationView {
37
42
  id: string;
@@ -39,6 +44,10 @@ interface SequenceRegistrationView {
39
44
  options: SequenceOptions;
40
45
  target: Target;
41
46
  triggerCount: number;
47
+ /** Steps matched in the current attempt (0 when idle or just completed). */
48
+ matchedStepCount: number;
49
+ /** `Date.now()` when the last step in the current attempt matched; 0 if none. */
50
+ partialMatchLastKeyTime: number;
42
51
  }
43
52
  /**
44
53
  * A handle returned from SequenceManager.register() that allows updating
@@ -142,5 +151,5 @@ declare function createSequenceMatcher(sequence: HotkeySequence, options?: {
142
151
  getProgress: () => number;
143
152
  };
144
153
  //#endregion
145
- export { HotkeySequence, SequenceManager, SequenceOptions, SequenceRegistrationHandle, SequenceRegistrationView, createSequenceMatcher, getSequenceManager };
154
+ export { DEFAULT_SEQUENCE_TIMEOUT, HotkeySequence, SequenceManager, SequenceOptions, SequenceRegistrationHandle, SequenceRegistrationView, createSequenceMatcher, getSequenceManager };
146
155
  //# sourceMappingURL=sequence-manager.d.cts.map
@@ -29,9 +29,14 @@ interface SequenceOptions extends Omit<HotkeyOptions, 'requireReset'> {
29
29
  * ```
30
30
  */
31
31
  type HotkeySequence = Array<Hotkey>;
32
+ /**
33
+ * Default timeout between keys in a sequence (in milliseconds).
34
+ * Exported for consumers that display sequence state (e.g. devtools).
35
+ */
36
+ declare const DEFAULT_SEQUENCE_TIMEOUT = 1000;
32
37
  /**
33
38
  * View of a sequence registration for devtools display.
34
- * Excludes internal matching state (currentIndex, lastKeyTime).
39
+ * Progress fields reflect an in-progress match (between first key and completion or timeout).
35
40
  */
36
41
  interface SequenceRegistrationView {
37
42
  id: string;
@@ -39,6 +44,10 @@ interface SequenceRegistrationView {
39
44
  options: SequenceOptions;
40
45
  target: Target;
41
46
  triggerCount: number;
47
+ /** Steps matched in the current attempt (0 when idle or just completed). */
48
+ matchedStepCount: number;
49
+ /** `Date.now()` when the last step in the current attempt matched; 0 if none. */
50
+ partialMatchLastKeyTime: number;
42
51
  }
43
52
  /**
44
53
  * A handle returned from SequenceManager.register() that allows updating
@@ -142,5 +151,5 @@ declare function createSequenceMatcher(sequence: HotkeySequence, options?: {
142
151
  getProgress: () => number;
143
152
  };
144
153
  //#endregion
145
- export { HotkeySequence, SequenceManager, SequenceOptions, SequenceRegistrationHandle, SequenceRegistrationView, createSequenceMatcher, getSequenceManager };
154
+ export { DEFAULT_SEQUENCE_TIMEOUT, HotkeySequence, SequenceManager, SequenceOptions, SequenceRegistrationHandle, SequenceRegistrationView, createSequenceMatcher, getSequenceManager };
146
155
  //# sourceMappingURL=sequence-manager.d.ts.map