@tanstack/hotkeys 0.11.0 → 0.12.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.
@@ -1,259 +0,0 @@
1
- import { detectPlatform } from "./platform.js";
2
- import { normalizeKeyboardEvent } from "./_keyboard-event.js";
3
- import { isModifierKey, parseHotkey } from "./parse.js";
4
- import { validateHotkey } from "./validate.js";
5
- import { beginRecording, captureRecordingEvent, endRecording } from "./_recording-guard.js";
6
- import { shouldIgnoreInputEvent } from "./_event-target.js";
7
- import { findHotkeyConflicts } from "./conflicts.js";
8
- import { chordRejection, hotkeyChordFromKeydown } from "./_recorder-chord.js";
9
- import { Store } from "@tanstack/store";
10
-
11
- //#region src/hotkey-sequence-recorder.ts
12
- const defaultHotkeySequenceRecorderOptions = {
13
- commitOnEnter: true,
14
- commitKeys: "enter"
15
- };
16
- /** Resolves the Enter policy, with commitKeys: none overriding the legacy boolean. */
17
- function resolvedCommitOnEnter(options) {
18
- if (options.commitKeys === "none") return false;
19
- return options.commitOnEnter !== false;
20
- }
21
- /**
22
- * Framework-agnostic class for recording multi-chord sequences (Vim-style shortcuts).
23
- *
24
- * Each step is captured like a single hotkey chord. Press **Enter** (no modifiers) to commit
25
- * when {@link HotkeySequenceRecorderOptions.commitKeys} is `'enter'` (default), **Escape** to cancel,
26
- * **Backspace/Delete** to remove the last step or clear when empty.
27
- */
28
- var HotkeySequenceRecorder = class {
29
- store = new Store({
30
- isRecording: false,
31
- steps: [],
32
- recordedSequence: null
33
- });
34
- #keydownHandler = null;
35
- #optionsSource;
36
- #optionOverrides = {};
37
- get #options() {
38
- return {
39
- ...defaultHotkeySequenceRecorderOptions,
40
- ...typeof this.#optionsSource === "function" ? this.#optionsSource() : this.#optionsSource,
41
- ...this.#optionOverrides
42
- };
43
- }
44
- #platform;
45
- #events = [];
46
- #idleTimer = null;
47
- /** Options may be a getter to read current configuration during an active session. */
48
- constructor(options) {
49
- this.#optionsSource = options;
50
- this.#platform = detectPlatform();
51
- }
52
- /** Merges current callbacks and options without discarding recorded steps. */
53
- setOptions(options) {
54
- this.#optionOverrides = {
55
- ...this.#optionOverrides,
56
- ...options
57
- };
58
- }
59
- /** Cancels a pending idle commit so it cannot fire after editing or stopping. */
60
- #clearIdleTimer() {
61
- if (this.#idleTimer !== null) {
62
- clearTimeout(this.#idleTimer);
63
- this.#idleTimer = null;
64
- }
65
- }
66
- /** Restarts optional idle commit after a step is recorded or edited. */
67
- #scheduleIdleTimer() {
68
- this.#clearIdleTimer();
69
- const ms = this.#options.idleTimeoutMs;
70
- if (ms === void 0 || ms <= 0) return;
71
- if (this.store.state.steps.length === 0) return;
72
- this.#idleTimer = setTimeout(() => {
73
- this.#idleTimer = null;
74
- if (!this.#keydownHandler) return;
75
- if (this.store.state.steps.length >= 1) this.commit();
76
- }, ms);
77
- }
78
- /** Publishes edited steps while preserving the remaining recorder state. */
79
- #patchSteps(updater) {
80
- this.store.setState((s) => ({
81
- ...s,
82
- steps: updater(s.steps)
83
- }));
84
- }
85
- /** Starts a fresh recording; repeated starts during an active session are ignored. */
86
- start() {
87
- if (this.#keydownHandler) return;
88
- this.#clearIdleTimer();
89
- this.#events = [];
90
- beginRecording(this);
91
- this.store.setState(() => ({
92
- isRecording: true,
93
- steps: [],
94
- recordedSequence: null
95
- }));
96
- const handler = (event) => {
97
- if (!this.#keydownHandler) return;
98
- if (this.#options.ignoreInputs !== false && event.key !== "Escape" && shouldIgnoreInputEvent(event, document, document)) return;
99
- const platform = this.#options.platform ?? this.#platform;
100
- if (normalizeKeyboardEvent(event, platform).isComposing) return;
101
- captureRecordingEvent(event);
102
- event.preventDefault();
103
- event.stopPropagation();
104
- if (event.repeat) return;
105
- if (event.key === "Escape") {
106
- this.cancel();
107
- return;
108
- }
109
- if (event.key === "Backspace" || event.key === "Delete") {
110
- if (!event.ctrlKey && !event.shiftKey && !event.altKey && !event.metaKey) {
111
- if (this.store.state.steps.length === 0) {
112
- this.stop();
113
- this.#options.onClear?.();
114
- return;
115
- }
116
- this.#events.pop();
117
- this.#patchSteps((prev) => prev.slice(0, -1));
118
- if (this.store.state.steps.length === 0) this.#clearIdleTimer();
119
- else this.#scheduleIdleTimer();
120
- return;
121
- }
122
- }
123
- const enterCommits = resolvedCommitOnEnter(this.#options) && event.key === "Enter" && !event.ctrlKey && !event.shiftKey && !event.altKey && !event.metaKey;
124
- if (enterCommits && this.store.state.steps.length >= 1) {
125
- this.commit();
126
- return;
127
- }
128
- if (enterCommits && this.store.state.steps.length === 0) return;
129
- if (isModifierKey(event.key) || event.key === "AltGraph") return;
130
- const rejection = chordRejection(event, {
131
- ...this.#options,
132
- platform
133
- });
134
- if (rejection) {
135
- this.#options.onReject?.(rejection);
136
- return;
137
- }
138
- const finalHotkey = hotkeyChordFromKeydown(event, platform, this.#options.recordBy);
139
- if (finalHotkey === null) return;
140
- const validation = validateHotkey(finalHotkey);
141
- if (!validation.valid) {
142
- this.#options.onReject?.({
143
- reason: "invalid",
144
- message: validation.errors.join("; "),
145
- hotkey: finalHotkey
146
- });
147
- return;
148
- }
149
- this.#events.push(event);
150
- this.#patchSteps((prev) => [...prev, finalHotkey]);
151
- this.#scheduleIdleTimer();
152
- };
153
- this.#keydownHandler = handler;
154
- this.#addListener(handler);
155
- }
156
- /**
157
- * Commit the current steps as a sequence. No-op if fewer than one step.
158
- */
159
- commit() {
160
- const steps = this.store.state.steps;
161
- if (steps.length < 1) return;
162
- const sequence = [...steps];
163
- const platform = this.#options.platform ?? this.#platform;
164
- this.#clearIdleTimer();
165
- const accepted = this.#options.validate?.(sequence, {
166
- events: [...this.#events],
167
- parsedSequence: sequence.map((step) => parseHotkey(step, platform))
168
- });
169
- if (accepted !== void 0 && accepted !== true) {
170
- this.#options.onReject?.({
171
- reason: "validation",
172
- message: typeof accepted === "string" ? accepted : "This sequence is not allowed.",
173
- sequence
174
- });
175
- return;
176
- }
177
- if (this.#options.detectConflicts) {
178
- const conflicts = findHotkeyConflicts(sequence, {
179
- ...typeof this.#options.detectConflicts === "object" ? this.#options.detectConflicts : {},
180
- platform,
181
- events: this.#events
182
- });
183
- if (conflicts.length) {
184
- this.#options.onReject?.({
185
- reason: "conflict",
186
- message: "This sequence conflicts with a registered binding.",
187
- sequence,
188
- conflicts
189
- });
190
- return;
191
- }
192
- }
193
- endRecording(this);
194
- this.#events = [];
195
- if (this.#keydownHandler) {
196
- this.#removeListener(this.#keydownHandler);
197
- this.#keydownHandler = null;
198
- }
199
- this.#clearIdleTimer();
200
- this.store.setState(() => ({
201
- isRecording: false,
202
- steps: [],
203
- recordedSequence: sequence
204
- }));
205
- this.#options.onRecord(sequence);
206
- }
207
- /** Stops and discards in-progress steps without invoking onCancel. */
208
- stop() {
209
- endRecording(this);
210
- this.#events = [];
211
- if (this.#keydownHandler) {
212
- this.#removeListener(this.#keydownHandler);
213
- this.#keydownHandler = null;
214
- }
215
- this.#clearIdleTimer();
216
- this.store.setState(() => ({
217
- isRecording: false,
218
- steps: [],
219
- recordedSequence: null
220
- }));
221
- }
222
- /** Stops, discards in-progress steps, and notifies onCancel. */
223
- cancel() {
224
- endRecording(this);
225
- this.#events = [];
226
- if (this.#keydownHandler) {
227
- this.#removeListener(this.#keydownHandler);
228
- this.#keydownHandler = null;
229
- }
230
- this.#clearIdleTimer();
231
- this.store.setState(() => ({
232
- isRecording: false,
233
- steps: [],
234
- recordedSequence: null
235
- }));
236
- this.#options.onCancel?.();
237
- }
238
- /** Captures keydowns before application handlers, with an SSR-safe document check. */
239
- #addListener(handler) {
240
- if (typeof document === "undefined") return;
241
- document.addEventListener("keydown", handler, true);
242
- }
243
- /** Detaches the capture listener when recording ends. */
244
- #removeListener(handler) {
245
- if (typeof document === "undefined") return;
246
- document.removeEventListener("keydown", handler, true);
247
- }
248
- destroy() {
249
- this.stop();
250
- this.store.setState(() => ({
251
- isRecording: false,
252
- steps: [],
253
- recordedSequence: null
254
- }));
255
- }
256
- };
257
-
258
- //#endregion
259
- export { HotkeySequenceRecorder };
@@ -1,169 +0,0 @@
1
- import { Hotkey, HotkeyCallback, ParsedHotkey } from "./hotkey.types.js";
2
- import { HotkeyOptions } from "./hotkey-manager.js";
3
- import { Store } from "@tanstack/store";
4
- //#region src/sequence-manager.d.ts
5
- export type Target = HTMLElement | Document | Window;
6
- /**
7
- * Options for hotkey sequence matching.
8
- * Extends HotkeyOptions but excludes requireReset (not applicable to sequences).
9
- */
10
- export interface SequenceOptions extends Omit<HotkeyOptions, 'requireReset'> {
11
- /** Timeout between keys in milliseconds. Default: 1000 */
12
- timeout?: number;
13
- }
14
- /**
15
- * A sequence of hotkeys for Vim-style shortcuts.
16
- *
17
- * Each element is one step (a `Hotkey` string). Steps may include modifiers;
18
- * the same modifier can appear on consecutive steps (e.g. `Shift+R` then
19
- * `Shift+T`). Modifier-only key events do not advance or reset matching—see
20
- * `SequenceManager`. Automatic keydown repeats and IME composition are also ignored.
21
- *
22
- * @example
23
- * ```ts
24
- * const gotoTop: HotkeySequence = ['G', 'G'] // gg
25
- * const deleteLine: HotkeySequence = ['D', 'D'] // dd
26
- * const deleteWord: HotkeySequence = ['D', 'I', 'W'] // diw
27
- * const chainedShift: HotkeySequence = ['Shift+R', 'Shift+T']
28
- * ```
29
- */
30
- export type HotkeySequence = Array<Hotkey>;
31
- /**
32
- * Default timeout between keys in a sequence (in milliseconds).
33
- * Exported for consumers that display sequence state (e.g. devtools).
34
- */
35
- export declare const DEFAULT_SEQUENCE_TIMEOUT = 1000;
36
- /**
37
- * View of a sequence registration for devtools display.
38
- * Progress fields reflect an in-progress match (between first key and completion or timeout).
39
- */
40
- export interface SequenceRegistrationView {
41
- id: string;
42
- sequence: HotkeySequence;
43
- options: SequenceOptions;
44
- target: Target;
45
- triggerCount: number;
46
- /** Whether this sequence has been triggered at least once. */
47
- hasFired: boolean;
48
- /** Steps matched in the current attempt (0 when idle or just completed). */
49
- matchedStepCount: number;
50
- /** `Date.now()` when the last step in the current attempt matched; 0 if none. */
51
- partialMatchLastKeyTime: number;
52
- }
53
- /**
54
- * Internal representation of a sequence registration.
55
- */
56
- export interface SequenceRegistration {
57
- id: string;
58
- sequence: HotkeySequence;
59
- parsedSequence: Array<ParsedHotkey>;
60
- callback: HotkeyCallback;
61
- options: SequenceOptions;
62
- target: Target;
63
- currentIndex: number;
64
- lastKeyTime: number;
65
- triggerCount: number;
66
- hasFired: boolean;
67
- }
68
- /**
69
- * A handle returned from SequenceManager.register() that allows updating
70
- * the callback and options without re-registering the sequence.
71
- *
72
- * @example
73
- * ```ts
74
- * const handle = manager.register(['G', 'G'], callback, options)
75
- *
76
- * handle.callback = newCallback
77
- * handle.setOptions({ timeout: 500 })
78
- * handle.unregister()
79
- * ```
80
- */
81
- export interface SequenceRegistrationHandle {
82
- readonly id: string;
83
- readonly isActive: boolean;
84
- callback: HotkeyCallback;
85
- setOptions: (options: Partial<SequenceOptions>) => void;
86
- unregister: () => void;
87
- }
88
- export declare class SequenceManager {
89
- #private;
90
- /**
91
- * The TanStack Store containing sequence registration views for devtools.
92
- * Subscribe to this to observe registration changes.
93
- */
94
- readonly registrations: Store<Map<string, SequenceRegistrationView>>;
95
- private constructor();
96
- /**
97
- * Gets the singleton instance of SequenceManager.
98
- */
99
- static getInstance(): SequenceManager;
100
- /**
101
- * Resets the singleton instance. Useful for testing.
102
- */
103
- static resetInstance(): void;
104
- /**
105
- * Registers a hotkey sequence handler.
106
- *
107
- * @param sequence - Array of hotkey strings that form the sequence
108
- * @param callback - Function to call when the sequence is completed
109
- * @param options - Options for the sequence behavior
110
- * @returns A handle to update or unregister the sequence
111
- */
112
- register(sequence: HotkeySequence, callback: HotkeyCallback, options?: SequenceOptions): SequenceRegistrationHandle;
113
- /**
114
- * Resets all sequence progress.
115
- */
116
- resetAll(): void;
117
- /**
118
- * Triggers a sequence's callback programmatically from devtools.
119
- * Creates a synthetic KeyboardEvent from the last key in the sequence.
120
- *
121
- * @param id - The registration ID to trigger
122
- * @returns True if the registration was found and triggered
123
- */
124
- triggerSequence(id: string): boolean;
125
- /**
126
- * Gets the number of registered sequences.
127
- */
128
- getRegistrationCount(): number;
129
- /**
130
- * Destroys the manager and removes all listeners.
131
- */
132
- destroy(): void;
133
- }
134
- /**
135
- * Gets the singleton SequenceManager instance.
136
- * Convenience function for accessing the manager.
137
- */
138
- export declare function getSequenceManager(): SequenceManager;
139
- /**
140
- * Creates a simple sequence matcher for one-off use.
141
- *
142
- * This is a low-level helper that does not support ignoreInputs, target,
143
- * or other HotkeyOptions. Callers must handle input filtering themselves
144
- * if attaching to document.
145
- *
146
- * @param sequence - The sequence of hotkeys to match
147
- * @param options - Options including timeout
148
- * @returns An object with match() and reset() methods
149
- *
150
- * @example
151
- * ```ts
152
- * const matcher = createSequenceMatcher(['G', 'G'], { timeout: 500 })
153
- *
154
- * document.addEventListener('keydown', (event) => {
155
- * if (matcher.match(event)) {
156
- * console.log('Sequence matched!')
157
- * }
158
- * })
159
- * ```
160
- */
161
- export declare function createSequenceMatcher(sequence: HotkeySequence, options?: {
162
- timeout?: number;
163
- platform?: 'mac' | 'windows' | 'linux';
164
- }): {
165
- match: (event: KeyboardEvent) => boolean;
166
- reset: () => void;
167
- getProgress: () => number;
168
- };
169
- //#endregion