@tanstack/hotkeys 0.4.2 → 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,308 @@
1
+ import { Store } from '@tanstack/store'
2
+ import { detectPlatform } from './constants'
3
+ import { hotkeyChordFromKeydown } from './recorder-chord'
4
+ import type { HotkeySequence } from './sequence-manager'
5
+
6
+ /**
7
+ * How the user can commit a recorded sequence from the keyboard.
8
+ * - `'enter'`: plain Enter (no modifiers) commits when at least one step exists.
9
+ * - `'none'`: only {@link HotkeySequenceRecorder.commit} finishes recording (or idle timeout if set).
10
+ */
11
+ export type HotkeySequenceRecorderCommitKeys = 'enter' | 'none'
12
+
13
+ /**
14
+ * State interface for the HotkeySequenceRecorder.
15
+ */
16
+ export interface HotkeySequenceRecorderState {
17
+ /** Whether recording is currently active */
18
+ isRecording: boolean
19
+ /** Chords captured so far in the current recording session */
20
+ steps: HotkeySequence
21
+ /** The last successfully committed sequence, or null if none / after starting a new session */
22
+ recordedSequence: HotkeySequence | null
23
+ }
24
+
25
+ /**
26
+ * Options for configuring a HotkeySequenceRecorder instance.
27
+ */
28
+ export interface HotkeySequenceRecorderOptions {
29
+ /** Callback when a sequence is successfully recorded (including empty array when cleared) */
30
+ onRecord: (sequence: HotkeySequence) => void
31
+ /** Optional callback when recording is cancelled (Escape pressed) */
32
+ onCancel?: () => void
33
+ /** Optional callback when the sequence is cleared (Backspace/Delete with no steps) */
34
+ onClear?: () => void
35
+ /**
36
+ * Whether plain Enter commits the current steps. Ignored when {@link commitKeys} is `'none'`.
37
+ * @default true
38
+ */
39
+ commitOnEnter?: boolean
40
+ /**
41
+ * Keyboard commit mode. When `'none'`, use {@link HotkeySequenceRecorder.commit} (and optional idle timeout).
42
+ * @default 'enter'
43
+ */
44
+ commitKeys?: HotkeySequenceRecorderCommitKeys
45
+ /**
46
+ * Milliseconds of inactivity after the **last completed chord** before auto-committing.
47
+ * The timer does not run while waiting for the first chord (`steps.length === 0`).
48
+ */
49
+ idleTimeoutMs?: number
50
+ }
51
+
52
+ const defaultHotkeySequenceRecorderOptions: Pick<
53
+ HotkeySequenceRecorderOptions,
54
+ 'commitOnEnter' | 'commitKeys'
55
+ > = {
56
+ commitOnEnter: true,
57
+ commitKeys: 'enter',
58
+ }
59
+
60
+ function resolvedCommitOnEnter(
61
+ options: HotkeySequenceRecorderOptions,
62
+ ): boolean {
63
+ if (options.commitKeys === 'none') {
64
+ return false
65
+ }
66
+ return options.commitOnEnter !== false
67
+ }
68
+
69
+ /**
70
+ * Framework-agnostic class for recording multi-chord sequences (Vim-style shortcuts).
71
+ *
72
+ * Each step is captured like a single hotkey chord. Press **Enter** (no modifiers) to commit
73
+ * when {@link HotkeySequenceRecorderOptions.commitKeys} is `'enter'` (default), **Escape** to cancel,
74
+ * **Backspace/Delete** to remove the last step or clear when empty.
75
+ */
76
+ export class HotkeySequenceRecorder {
77
+ readonly store: Store<HotkeySequenceRecorderState> =
78
+ new Store<HotkeySequenceRecorderState>({
79
+ isRecording: false,
80
+ steps: [],
81
+ recordedSequence: null,
82
+ })
83
+
84
+ #keydownHandler: ((event: KeyboardEvent) => void) | null = null
85
+ #options: HotkeySequenceRecorderOptions
86
+ #platform: 'mac' | 'windows' | 'linux'
87
+ #idleTimer: ReturnType<typeof setTimeout> | null = null
88
+
89
+ constructor(options: HotkeySequenceRecorderOptions) {
90
+ this.#options = {
91
+ ...defaultHotkeySequenceRecorderOptions,
92
+ ...options,
93
+ }
94
+ this.#platform = detectPlatform()
95
+ }
96
+
97
+ setOptions(options: Partial<HotkeySequenceRecorderOptions>): void {
98
+ this.#options = {
99
+ ...defaultHotkeySequenceRecorderOptions,
100
+ ...this.#options,
101
+ ...options,
102
+ }
103
+ }
104
+
105
+ #clearIdleTimer(): void {
106
+ if (this.#idleTimer !== null) {
107
+ clearTimeout(this.#idleTimer)
108
+ this.#idleTimer = null
109
+ }
110
+ }
111
+
112
+ #scheduleIdleTimer(): void {
113
+ this.#clearIdleTimer()
114
+ const ms = this.#options.idleTimeoutMs
115
+ if (ms === undefined || ms <= 0) {
116
+ return
117
+ }
118
+ const steps = this.store.state.steps
119
+ if (steps.length === 0) {
120
+ return
121
+ }
122
+ this.#idleTimer = setTimeout(() => {
123
+ this.#idleTimer = null
124
+ if (!this.#keydownHandler) {
125
+ return
126
+ }
127
+ if (this.store.state.steps.length >= 1) {
128
+ this.commit()
129
+ }
130
+ }, ms)
131
+ }
132
+
133
+ #patchSteps(updater: (prev: HotkeySequence) => HotkeySequence): void {
134
+ this.store.setState((s) => ({
135
+ ...s,
136
+ steps: updater(s.steps),
137
+ }))
138
+ }
139
+
140
+ start(): void {
141
+ if (this.#keydownHandler) {
142
+ return
143
+ }
144
+
145
+ this.#clearIdleTimer()
146
+ this.store.setState(() => ({
147
+ isRecording: true,
148
+ steps: [],
149
+ recordedSequence: null,
150
+ }))
151
+
152
+ const handler = (event: KeyboardEvent) => {
153
+ if (!this.#keydownHandler) {
154
+ return
155
+ }
156
+
157
+ event.preventDefault()
158
+ event.stopPropagation()
159
+
160
+ if (event.key === 'Escape') {
161
+ this.cancel()
162
+ return
163
+ }
164
+
165
+ if (event.key === 'Backspace' || event.key === 'Delete') {
166
+ if (
167
+ !event.ctrlKey &&
168
+ !event.shiftKey &&
169
+ !event.altKey &&
170
+ !event.metaKey
171
+ ) {
172
+ const steps = this.store.state.steps
173
+ if (steps.length === 0) {
174
+ this.#options.onClear?.()
175
+ this.#options.onRecord([])
176
+ this.#finishWithoutCommitCallback()
177
+ return
178
+ }
179
+ this.#patchSteps((prev) => prev.slice(0, -1))
180
+ const next = this.store.state.steps
181
+ if (next.length === 0) {
182
+ this.#clearIdleTimer()
183
+ } else {
184
+ this.#scheduleIdleTimer()
185
+ }
186
+ return
187
+ }
188
+ }
189
+
190
+ const enterCommits =
191
+ resolvedCommitOnEnter(this.#options) &&
192
+ event.key === 'Enter' &&
193
+ !event.ctrlKey &&
194
+ !event.shiftKey &&
195
+ !event.altKey &&
196
+ !event.metaKey
197
+
198
+ if (enterCommits && this.store.state.steps.length >= 1) {
199
+ this.commit()
200
+ return
201
+ }
202
+
203
+ if (enterCommits && this.store.state.steps.length === 0) {
204
+ return
205
+ }
206
+
207
+ const finalHotkey = hotkeyChordFromKeydown(event, this.#platform)
208
+ if (finalHotkey === null) {
209
+ return
210
+ }
211
+
212
+ this.#patchSteps((prev) => [...prev, finalHotkey])
213
+ this.#scheduleIdleTimer()
214
+ }
215
+
216
+ this.#keydownHandler = handler
217
+ this.#addListener(handler)
218
+ }
219
+
220
+ /**
221
+ * Commit the current steps as a sequence. No-op if fewer than one step.
222
+ */
223
+ commit(): void {
224
+ const steps = this.store.state.steps
225
+ if (steps.length < 1) {
226
+ return
227
+ }
228
+
229
+ const sequence = [...steps]
230
+
231
+ if (this.#keydownHandler) {
232
+ this.#removeListener(this.#keydownHandler)
233
+ this.#keydownHandler = null
234
+ }
235
+ this.#clearIdleTimer()
236
+
237
+ this.store.setState(() => ({
238
+ isRecording: false,
239
+ steps: [],
240
+ recordedSequence: sequence,
241
+ }))
242
+
243
+ this.#options.onRecord(sequence)
244
+ }
245
+
246
+ #finishWithoutCommitCallback(): void {
247
+ if (this.#keydownHandler) {
248
+ this.#removeListener(this.#keydownHandler)
249
+ this.#keydownHandler = null
250
+ }
251
+ this.#clearIdleTimer()
252
+ this.store.setState(() => ({
253
+ isRecording: false,
254
+ steps: [],
255
+ recordedSequence: null,
256
+ }))
257
+ }
258
+
259
+ stop(): void {
260
+ if (this.#keydownHandler) {
261
+ this.#removeListener(this.#keydownHandler)
262
+ this.#keydownHandler = null
263
+ }
264
+ this.#clearIdleTimer()
265
+ this.store.setState(() => ({
266
+ isRecording: false,
267
+ steps: [],
268
+ recordedSequence: null,
269
+ }))
270
+ }
271
+
272
+ cancel(): void {
273
+ if (this.#keydownHandler) {
274
+ this.#removeListener(this.#keydownHandler)
275
+ this.#keydownHandler = null
276
+ }
277
+ this.#clearIdleTimer()
278
+ this.store.setState(() => ({
279
+ isRecording: false,
280
+ steps: [],
281
+ recordedSequence: null,
282
+ }))
283
+ this.#options.onCancel?.()
284
+ }
285
+
286
+ #addListener(handler: (event: KeyboardEvent) => void): void {
287
+ if (typeof document === 'undefined') {
288
+ return
289
+ }
290
+ document.addEventListener('keydown', handler, true)
291
+ }
292
+
293
+ #removeListener(handler: (event: KeyboardEvent) => void): void {
294
+ if (typeof document === 'undefined') {
295
+ return
296
+ }
297
+ document.removeEventListener('keydown', handler, true)
298
+ }
299
+
300
+ destroy(): void {
301
+ this.stop()
302
+ this.store.setState(() => ({
303
+ isRecording: false,
304
+ steps: [],
305
+ recordedSequence: null,
306
+ }))
307
+ }
308
+ }
package/src/index.ts CHANGED
@@ -5,6 +5,7 @@ export * from './hotkey-manager'
5
5
  export * from './key-state-tracker'
6
6
  export * from './match'
7
7
  export * from './parse'
8
- export * from './recorder'
8
+ export * from './hotkey-recorder'
9
+ export * from './hotkey-sequence-recorder'
9
10
  export * from './sequence-manager'
10
11
  export * from './validate'
@@ -0,0 +1,26 @@
1
+ import {
2
+ convertToModFormat,
3
+ hasNonModifierKey,
4
+ isModifierKey,
5
+ keyboardEventToHotkey,
6
+ } from './parse'
7
+ import type { Hotkey } from './hotkey'
8
+
9
+ /**
10
+ * Parses a keydown event into a single normalized hotkey chord, or null if
11
+ * the event should be ignored (modifier-only or invalid).
12
+ */
13
+ export function hotkeyChordFromKeydown(
14
+ event: KeyboardEvent,
15
+ platform: 'mac' | 'windows' | 'linux',
16
+ ): Hotkey | null {
17
+ if (isModifierKey(event)) {
18
+ return null
19
+ }
20
+ const hotkey = keyboardEventToHotkey(event)
21
+ const finalHotkey = convertToModFormat(hotkey, platform)
22
+ if (!hasNonModifierKey(finalHotkey, platform)) {
23
+ return null
24
+ }
25
+ return finalHotkey
26
+ }
@@ -1,7 +1,7 @@
1
1
  import { Store } from '@tanstack/store'
2
2
  import { formatHotkeySequence } from './format'
3
3
  import { detectPlatform } from './constants'
4
- import { parseHotkey } from './parse'
4
+ import { isModifierKey, parseHotkey } from './parse'
5
5
  import { matchesKeyboardEvent } from './match'
6
6
  import {
7
7
  defaultHotkeyOptions,
@@ -32,19 +32,26 @@ export interface SequenceOptions extends Omit<HotkeyOptions, 'requireReset'> {
32
32
  /**
33
33
  * A sequence of hotkeys for Vim-style shortcuts.
34
34
  *
35
+ * Each element is one step (a `Hotkey` string). Steps may include modifiers;
36
+ * the same modifier can appear on consecutive steps (e.g. `Shift+R` then
37
+ * `Shift+T`). Modifier-only key events do not advance or reset matching—see
38
+ * `SequenceManager`.
39
+ *
35
40
  * @example
36
41
  * ```ts
37
42
  * const gotoTop: HotkeySequence = ['G', 'G'] // gg
38
43
  * const deleteLine: HotkeySequence = ['D', 'D'] // dd
39
44
  * const deleteWord: HotkeySequence = ['D', 'I', 'W'] // diw
45
+ * const chainedShift: HotkeySequence = ['Shift+R', 'Shift+T']
40
46
  * ```
41
47
  */
42
48
  export type HotkeySequence = Array<Hotkey>
43
49
 
44
50
  /**
45
51
  * Default timeout between keys in a sequence (in milliseconds).
52
+ * Exported for consumers that display sequence state (e.g. devtools).
46
53
  */
47
- const DEFAULT_SEQUENCE_TIMEOUT = 1000
54
+ export const DEFAULT_SEQUENCE_TIMEOUT = 1000
48
55
 
49
56
  let sequenceIdCounter = 0
50
57
 
@@ -64,7 +71,7 @@ function sequenceKey(sequence: HotkeySequence): string {
64
71
 
65
72
  /**
66
73
  * View of a sequence registration for devtools display.
67
- * Excludes internal matching state (currentIndex, lastKeyTime).
74
+ * Progress fields reflect an in-progress match (between first key and completion or timeout).
68
75
  */
69
76
  export interface SequenceRegistrationView {
70
77
  id: string
@@ -72,6 +79,10 @@ export interface SequenceRegistrationView {
72
79
  options: SequenceOptions
73
80
  target: Target
74
81
  triggerCount: number
82
+ /** Steps matched in the current attempt (0 when idle or just completed). */
83
+ matchedStepCount: number
84
+ /** `Date.now()` when the last step in the current attempt matched; 0 if none. */
85
+ partialMatchLastKeyTime: number
75
86
  }
76
87
 
77
88
  /**
@@ -117,6 +128,11 @@ export interface SequenceRegistrationHandle {
117
128
  * that trigger callbacks when the full sequence is pressed within
118
129
  * a configurable timeout.
119
130
  *
131
+ * Modifier-only `keydown` / `keyup` events (Shift, Control, Alt, or Meta
132
+ * alone) are not processed: they neither match a step nor reset progress.
133
+ * That supports chained modifier chords (e.g. `Shift+R` then `Shift+T`) when
134
+ * the user presses a modifier alone between steps.
135
+ *
120
136
  * @example
121
137
  * ```ts
122
138
  * const matcher = SequenceManager.getInstance()
@@ -136,12 +152,16 @@ export interface SequenceRegistrationHandle {
136
152
  function toRegistrationView(
137
153
  reg: SequenceRegistration,
138
154
  ): SequenceRegistrationView {
155
+ const len = reg.parsedSequence.length
156
+ const inProgress = reg.currentIndex > 0 && reg.currentIndex < len
139
157
  return {
140
158
  id: reg.id,
141
159
  sequence: reg.sequence,
142
160
  options: reg.options,
143
161
  target: reg.target,
144
162
  triggerCount: reg.triggerCount,
163
+ matchedStepCount: inProgress ? reg.currentIndex : 0,
164
+ partialMatchLastKeyTime: inProgress ? reg.lastKeyTime : 0,
145
165
  }
146
166
  }
147
167
 
@@ -190,6 +210,12 @@ export class SequenceManager {
190
210
  }
191
211
  }
192
212
 
213
+ #syncRegistrationView(registration: SequenceRegistration): void {
214
+ this.registrations.setState((prev) =>
215
+ new Map(prev).set(registration.id, toRegistrationView(registration)),
216
+ )
217
+ }
218
+
193
219
  /**
194
220
  * Registers a hotkey sequence handler.
195
221
  *
@@ -407,6 +433,11 @@ export class SequenceManager {
407
433
  target: Target,
408
434
  eventType: 'keydown' | 'keyup',
409
435
  ): void {
436
+ // Skip modifier-only events so pressing e.g. Shift before Shift+C does not reset the sequence.
437
+ if (isModifierKey(event)) {
438
+ return
439
+ }
440
+
410
441
  const targetRegs = this.#targetRegistrations.get(target)
411
442
  if (!targetRegs) {
412
443
  return
@@ -451,6 +482,7 @@ export class SequenceManager {
451
482
  now - registration.lastKeyTime > timeout
452
483
  ) {
453
484
  registration.currentIndex = 0
485
+ this.#syncRegistrationView(registration)
454
486
  }
455
487
 
456
488
  const expectedHotkey =
@@ -485,9 +517,14 @@ export class SequenceManager {
485
517
  ]!,
486
518
  }
487
519
 
488
- registration.callback(event, context)
489
-
520
+ registration.triggerCount++
490
521
  registration.currentIndex = 0
522
+
523
+ this.#syncRegistrationView(registration)
524
+
525
+ registration.callback(event, context)
526
+ } else {
527
+ this.#syncRegistrationView(registration)
491
528
  }
492
529
  } else if (registration.currentIndex > 0) {
493
530
  const firstHotkey = registration.parsedSequence[0]!
@@ -503,6 +540,7 @@ export class SequenceManager {
503
540
  } else {
504
541
  registration.currentIndex = 0
505
542
  }
543
+ this.#syncRegistrationView(registration)
506
544
  }
507
545
  }
508
546
  }
@@ -533,6 +571,7 @@ export class SequenceManager {
533
571
  for (const registration of this.#registrations.values()) {
534
572
  registration.currentIndex = 0
535
573
  registration.lastKeyTime = 0
574
+ this.#syncRegistrationView(registration)
536
575
  }
537
576
  }
538
577
 
@@ -570,9 +609,7 @@ export class SequenceManager {
570
609
 
571
610
  registration.triggerCount++
572
611
 
573
- this.registrations.setState((prev) =>
574
- new Map(prev).set(id, toRegistrationView(registration)),
575
- )
612
+ this.#syncRegistrationView(registration)
576
613
 
577
614
  const context: HotkeyCallbackContext = {
578
615
  hotkey: registration.sequence.join(' ') as Hotkey,
@@ -1 +0,0 @@
1
- {"version":3,"file":"recorder.cjs","names":["Store","#options","#platform","detectPlatform","#keydownHandler","isModifierKey","convertToModFormat","keyboardEventToHotkey","hasNonModifierKey","#removeListener","#addListener"],"sources":["../src/recorder.ts"],"sourcesContent":["import { Store } from '@tanstack/store'\nimport { detectPlatform } from './constants'\nimport {\n convertToModFormat,\n hasNonModifierKey,\n isModifierKey,\n keyboardEventToHotkey,\n} from './parse'\nimport type { Hotkey } from './hotkey'\n\n/**\n * State interface for the HotkeyRecorder.\n */\nexport interface HotkeyRecorderState {\n /** Whether recording is currently active */\n isRecording: boolean\n /** The currently recorded hotkey (for live preview) */\n recordedHotkey: Hotkey | null\n}\n\n/**\n * Options for configuring a HotkeyRecorder instance.\n */\nexport interface HotkeyRecorderOptions {\n /** Callback when a hotkey is successfully recorded */\n onRecord: (hotkey: Hotkey) => void\n /** Optional callback when recording is cancelled (Escape pressed) */\n onCancel?: () => void\n /** Optional callback when shortcut is cleared (Backspace/Delete pressed) */\n onClear?: () => void\n}\n\n/**\n * Framework-agnostic class for recording keyboard shortcuts.\n *\n * This class handles all the complexity of capturing keyboard events,\n * converting them to hotkey strings, and handling edge cases like\n * Escape to cancel or Backspace/Delete to clear.\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - State can be accessed via `recorder.store.state` when using the class directly\n * - When using framework adapters (React), use `useStore` hooks for reactive state\n *\n * @example\n * ```ts\n * const recorder = new HotkeyRecorder({\n * onRecord: (hotkey) => {\n * console.log('Recorded:', hotkey)\n * },\n * onCancel: () => {\n * console.log('Recording cancelled')\n * },\n * })\n *\n * // Start recording\n * recorder.start()\n *\n * // Access state directly\n * console.log(recorder.store.state.isRecording) // true\n *\n * // Subscribe to changes with TanStack Store\n * const unsubscribe = recorder.store.subscribe(() => {\n * console.log('Recording:', recorder.store.state.isRecording)\n * })\n *\n * // Cleanup\n * recorder.destroy()\n * unsubscribe()\n * ```\n */\nexport class HotkeyRecorder {\n /**\n * The TanStack Store instance containing the recorder state.\n * Use this to subscribe to state changes or access current state.\n */\n readonly store: Store<HotkeyRecorderState> = new Store<HotkeyRecorderState>({\n isRecording: false,\n recordedHotkey: null,\n })\n\n #keydownHandler: ((event: KeyboardEvent) => void) | null = null\n #options: HotkeyRecorderOptions\n #platform: 'mac' | 'windows' | 'linux'\n\n constructor(options: HotkeyRecorderOptions) {\n this.#options = options\n this.#platform = detectPlatform()\n }\n\n /**\n * Updates the recorder options, including callbacks.\n * This allows framework adapters to sync callback changes without recreating the recorder.\n */\n setOptions(options: Partial<HotkeyRecorderOptions>): void {\n this.#options = {\n ...this.#options,\n ...options,\n }\n }\n\n /**\n * Start recording a new hotkey.\n *\n * Sets up a keydown event listener that captures keyboard events\n * and converts them to hotkey strings. Recording continues until\n * a valid hotkey is recorded, Escape is pressed, or stop/cancel is called.\n */\n start(): void {\n // Prevent starting recording if already recording\n if (this.#keydownHandler) {\n return\n }\n\n // Update store state\n this.store.setState(() => ({\n isRecording: true,\n recordedHotkey: null,\n }))\n\n // Create keydown handler\n const handler = (event: KeyboardEvent) => {\n // Check if we're still recording (handler might be called after stop/cancel)\n if (!this.#keydownHandler) {\n return\n }\n\n event.preventDefault()\n event.stopPropagation()\n\n // Handle Escape to cancel\n if (event.key === 'Escape') {\n this.cancel()\n return\n }\n\n // Handle Backspace/Delete to clear shortcut\n if (event.key === 'Backspace' || event.key === 'Delete') {\n if (\n !event.ctrlKey &&\n !event.shiftKey &&\n !event.altKey &&\n !event.metaKey\n ) {\n this.#options.onClear?.()\n this.#options.onRecord('' as Hotkey)\n this.stop()\n return\n }\n }\n\n // Ignore pure modifier keys (wait for a non-modifier key)\n if (isModifierKey(event)) {\n return\n }\n\n // Convert event to hotkey string using library function\n const hotkey = keyboardEventToHotkey(event)\n\n // Always convert to Mod format for portability\n const finalHotkey = convertToModFormat(hotkey, this.#platform)\n\n // Validate: must have at least one non-modifier key\n if (hasNonModifierKey(finalHotkey, this.#platform)) {\n // Remove listener FIRST to prevent any additional events\n const handlerToRemove = this.#keydownHandler as\n | ((event: KeyboardEvent) => void)\n | null\n if (handlerToRemove) {\n this.#removeListener(handlerToRemove)\n this.#keydownHandler = null\n }\n\n // Update store state immediately\n this.store.setState(() => ({\n isRecording: false,\n recordedHotkey: finalHotkey,\n }))\n\n // Call callback AFTER listener is removed and state is set\n this.#options.onRecord(finalHotkey)\n }\n }\n\n this.#keydownHandler = handler\n this.#addListener(handler)\n }\n\n /**\n * Stop recording (same as cancel, but doesn't call onCancel).\n *\n * Removes the event listener and resets the recording state.\n */\n stop(): void {\n // Remove event listener immediately\n if (this.#keydownHandler) {\n this.#removeListener(this.#keydownHandler)\n this.#keydownHandler = null\n }\n\n // Update store state\n this.store.setState(() => ({\n isRecording: false,\n recordedHotkey: null,\n }))\n }\n\n /**\n * Cancel recording without saving.\n *\n * Removes the event listener, resets the recording state, and calls\n * the onCancel callback if provided.\n */\n cancel(): void {\n // Remove event listener immediately\n if (this.#keydownHandler) {\n this.#removeListener(this.#keydownHandler)\n this.#keydownHandler = null\n }\n\n // Update store state\n this.store.setState(() => ({\n isRecording: false,\n recordedHotkey: null,\n }))\n\n // Call cancel callback\n this.#options.onCancel?.()\n }\n\n /**\n * Adds the keydown event listener to the document.\n */\n #addListener(handler: (event: KeyboardEvent) => void): void {\n if (typeof document === 'undefined') {\n return // SSR safety\n }\n\n document.addEventListener('keydown', handler, true)\n }\n\n /**\n * Removes the keydown event listener from the document.\n */\n #removeListener(handler: (event: KeyboardEvent) => void): void {\n if (typeof document === 'undefined') {\n return\n }\n\n document.removeEventListener('keydown', handler, true)\n }\n\n /**\n * Clean up event listeners and reset state.\n *\n * Call this when you're done with the recorder to ensure\n * all event listeners are properly removed.\n */\n destroy(): void {\n this.stop()\n this.store.setState(() => ({\n isRecording: false,\n recordedHotkey: null,\n }))\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuEA,IAAa,iBAAb,MAA4B;CAU1B,kBAA2D;CAC3D;CACA;CAEA,YAAY,SAAgC;eATC,IAAIA,sBAA2B;GAC1E,aAAa;GACb,gBAAgB;GACjB,CAAC;AAOA,QAAKC,UAAW;AAChB,QAAKC,WAAYC,kCAAgB;;;;;;CAOnC,WAAW,SAA+C;AACxD,QAAKF,UAAW;GACd,GAAG,MAAKA;GACR,GAAG;GACJ;;;;;;;;;CAUH,QAAc;AAEZ,MAAI,MAAKG,eACP;AAIF,OAAK,MAAM,gBAAgB;GACzB,aAAa;GACb,gBAAgB;GACjB,EAAE;EAGH,MAAM,WAAW,UAAyB;AAExC,OAAI,CAAC,MAAKA,eACR;AAGF,SAAM,gBAAgB;AACtB,SAAM,iBAAiB;AA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gB;AACd,OAAK,MAAM;AACX,OAAK,MAAM,gBAAgB;GACzB,aAAa;GACb,gBAAgB;GACjB,EAAE"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"recorder.js","names":["#options","#platform","#keydownHandler","#removeListener","#addListener"],"sources":["../src/recorder.ts"],"sourcesContent":["import { Store } from '@tanstack/store'\nimport { detectPlatform } from './constants'\nimport {\n convertToModFormat,\n hasNonModifierKey,\n isModifierKey,\n keyboardEventToHotkey,\n} from './parse'\nimport type { Hotkey } from './hotkey'\n\n/**\n * State interface for the HotkeyRecorder.\n */\nexport interface HotkeyRecorderState {\n /** Whether recording is currently active */\n isRecording: boolean\n /** The currently recorded hotkey (for live preview) */\n recordedHotkey: Hotkey | null\n}\n\n/**\n * Options for configuring a HotkeyRecorder instance.\n */\nexport interface HotkeyRecorderOptions {\n /** Callback when a hotkey is successfully recorded */\n onRecord: (hotkey: Hotkey) => void\n /** Optional callback when recording is cancelled (Escape pressed) */\n onCancel?: () => void\n /** Optional callback when shortcut is cleared (Backspace/Delete pressed) */\n onClear?: () => void\n}\n\n/**\n * Framework-agnostic class for recording keyboard shortcuts.\n *\n * This class handles all the complexity of capturing keyboard events,\n * converting them to hotkey strings, and handling edge cases like\n * Escape to cancel or Backspace/Delete to clear.\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - State can be accessed via `recorder.store.state` when using the class directly\n * - When using framework adapters (React), use `useStore` hooks for reactive state\n *\n * @example\n * ```ts\n * const recorder = new HotkeyRecorder({\n * onRecord: (hotkey) => {\n * console.log('Recorded:', hotkey)\n * },\n * onCancel: () => {\n * console.log('Recording cancelled')\n * },\n * })\n *\n * // Start recording\n * recorder.start()\n *\n * // Access state directly\n * console.log(recorder.store.state.isRecording) // true\n *\n * // Subscribe to changes with TanStack Store\n * const unsubscribe = recorder.store.subscribe(() => {\n * console.log('Recording:', recorder.store.state.isRecording)\n * })\n *\n * // Cleanup\n * recorder.destroy()\n * unsubscribe()\n * ```\n */\nexport class HotkeyRecorder {\n /**\n * The TanStack Store instance containing the recorder state.\n * Use this to subscribe to state changes or access current state.\n */\n readonly store: Store<HotkeyRecorderState> = new Store<HotkeyRecorderState>({\n isRecording: false,\n recordedHotkey: null,\n })\n\n #keydownHandler: ((event: KeyboardEvent) => void) | null = null\n #options: HotkeyRecorderOptions\n #platform: 'mac' | 'windows' | 'linux'\n\n constructor(options: HotkeyRecorderOptions) {\n this.#options = options\n this.#platform = detectPlatform()\n }\n\n /**\n * Updates the recorder options, including callbacks.\n * This allows framework adapters to sync callback changes without recreating the recorder.\n */\n setOptions(options: Partial<HotkeyRecorderOptions>): void {\n this.#options = {\n ...this.#options,\n ...options,\n }\n }\n\n /**\n * Start recording a new hotkey.\n *\n * Sets up a keydown event listener that captures keyboard events\n * and converts them to hotkey strings. Recording continues until\n * a valid hotkey is recorded, Escape is pressed, or stop/cancel is called.\n */\n start(): void {\n // Prevent starting recording if already recording\n if (this.#keydownHandler) {\n return\n }\n\n // Update store state\n this.store.setState(() => ({\n isRecording: true,\n recordedHotkey: null,\n }))\n\n // Create keydown handler\n const handler = (event: KeyboardEvent) => {\n // Check if we're still recording (handler might be called after stop/cancel)\n if (!this.#keydownHandler) {\n return\n }\n\n event.preventDefault()\n event.stopPropagation()\n\n // Handle Escape to cancel\n if (event.key === 'Escape') {\n this.cancel()\n return\n }\n\n // Handle Backspace/Delete to clear shortcut\n if (event.key === 'Backspace' || event.key === 'Delete') {\n if (\n !event.ctrlKey &&\n !event.shiftKey &&\n !event.altKey &&\n !event.metaKey\n ) {\n this.#options.onClear?.()\n this.#options.onRecord('' as Hotkey)\n this.stop()\n return\n }\n }\n\n // Ignore pure modifier keys (wait for a non-modifier key)\n if (isModifierKey(event)) {\n return\n }\n\n // Convert event to hotkey string using library function\n const hotkey = keyboardEventToHotkey(event)\n\n // Always convert to Mod format for portability\n const finalHotkey = convertToModFormat(hotkey, this.#platform)\n\n // Validate: must have at least one non-modifier key\n if (hasNonModifierKey(finalHotkey, this.#platform)) {\n // Remove listener FIRST to prevent any additional events\n const handlerToRemove = this.#keydownHandler as\n | ((event: KeyboardEvent) => void)\n | null\n if (handlerToRemove) {\n this.#removeListener(handlerToRemove)\n this.#keydownHandler = null\n }\n\n // Update store state immediately\n this.store.setState(() => ({\n isRecording: false,\n recordedHotkey: finalHotkey,\n }))\n\n // Call callback AFTER listener is removed and state is set\n this.#options.onRecord(finalHotkey)\n }\n }\n\n this.#keydownHandler = handler\n this.#addListener(handler)\n }\n\n /**\n * Stop recording (same as cancel, but doesn't call onCancel).\n *\n * Removes the event listener and resets the recording state.\n */\n stop(): void {\n // Remove event listener immediately\n if (this.#keydownHandler) {\n this.#removeListener(this.#keydownHandler)\n this.#keydownHandler = null\n }\n\n // Update store state\n this.store.setState(() => ({\n isRecording: false,\n recordedHotkey: null,\n }))\n }\n\n /**\n * Cancel recording without saving.\n *\n * Removes the event listener, resets the recording state, and calls\n * the onCancel callback if provided.\n */\n cancel(): void {\n // Remove event listener immediately\n if (this.#keydownHandler) {\n this.#removeListener(this.#keydownHandler)\n this.#keydownHandler = null\n }\n\n // Update store state\n this.store.setState(() => ({\n isRecording: false,\n recordedHotkey: null,\n }))\n\n // Call cancel callback\n this.#options.onCancel?.()\n }\n\n /**\n * Adds the keydown event listener to the document.\n */\n #addListener(handler: (event: KeyboardEvent) => void): void {\n if (typeof document === 'undefined') {\n return // SSR safety\n }\n\n document.addEventListener('keydown', handler, true)\n }\n\n /**\n * Removes the keydown event listener from the document.\n */\n #removeListener(handler: (event: KeyboardEvent) => void): void {\n if (typeof document === 'undefined') {\n return\n }\n\n document.removeEventListener('keydown', handler, true)\n }\n\n /**\n * Clean up event listeners and reset state.\n *\n * Call this when you're done with the recorder to ensure\n * all event listeners are properly removed.\n */\n destroy(): void {\n this.stop()\n this.store.setState(() => ({\n isRecording: false,\n recordedHotkey: null,\n }))\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuEA,IAAa,iBAAb,MA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