@tanstack/hotkeys 0.8.0 → 0.10.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.
Files changed (109) hide show
  1. package/README.md +15 -1
  2. package/dist/{manager.utils.js → _event-target.js} +2 -41
  3. package/dist/_keyboard-event.js +75 -0
  4. package/dist/_match.js +48 -0
  5. package/dist/_named-keys.d.ts +6 -0
  6. package/dist/_named-keys.js +65 -0
  7. package/dist/_recorder-chord.js +42 -0
  8. package/dist/_recording-guard.js +55 -0
  9. package/dist/_registration.js +49 -0
  10. package/dist/conflicts.d.ts +36 -0
  11. package/dist/conflicts.js +54 -0
  12. package/dist/constants.d.ts +16 -144
  13. package/dist/constants.js +55 -172
  14. package/dist/display-labels.d.ts +90 -0
  15. package/dist/display-labels.js +112 -0
  16. package/dist/format.d.ts +48 -12
  17. package/dist/format.js +35 -39
  18. package/dist/hint.d.ts +20 -0
  19. package/dist/hint.js +23 -0
  20. package/dist/hotkey-manager.d.ts +14 -12
  21. package/dist/hotkey-manager.js +70 -21
  22. package/dist/hotkey-recorder.d.ts +8 -8
  23. package/dist/hotkey-recorder.js +74 -15
  24. package/dist/hotkey-sequence-recorder.d.ts +13 -9
  25. package/dist/hotkey-sequence-recorder.js +90 -28
  26. package/dist/{hotkey.d.ts → hotkey.types.d.ts} +58 -126
  27. package/dist/index.d.ts +14 -9
  28. package/dist/index.js +10 -6
  29. package/dist/key-state-tracker.d.ts +4 -7
  30. package/dist/key-state-tracker.js +30 -27
  31. package/dist/key.types.d.ts +79 -0
  32. package/dist/match.d.ts +24 -11
  33. package/dist/match.js +19 -30
  34. package/dist/parse.d.ts +18 -15
  35. package/dist/parse.js +39 -22
  36. package/dist/platform.d.ts +41 -0
  37. package/dist/platform.js +52 -0
  38. package/dist/recorder-options.d.ts +31 -0
  39. package/dist/sequence-manager.d.ts +27 -15
  40. package/dist/sequence-manager.js +61 -30
  41. package/dist/validate.d.ts +16 -8
  42. package/dist/validate.js +8 -13
  43. package/package.json +8 -13
  44. package/dist/constants.cjs +0 -535
  45. package/dist/constants.cjs.map +0 -1
  46. package/dist/constants.d.cts +0 -290
  47. package/dist/constants.js.map +0 -1
  48. package/dist/format.cjs +0 -91
  49. package/dist/format.cjs.map +0 -1
  50. package/dist/format.d.cts +0 -60
  51. package/dist/format.js.map +0 -1
  52. package/dist/hotkey-manager.cjs +0 -383
  53. package/dist/hotkey-manager.cjs.map +0 -1
  54. package/dist/hotkey-manager.d.cts +0 -230
  55. package/dist/hotkey-manager.js.map +0 -1
  56. package/dist/hotkey-recorder.cjs +0 -179
  57. package/dist/hotkey-recorder.cjs.map +0 -1
  58. package/dist/hotkey-recorder.d.cts +0 -116
  59. package/dist/hotkey-recorder.js.map +0 -1
  60. package/dist/hotkey-sequence-recorder.cjs +0 -192
  61. package/dist/hotkey-sequence-recorder.cjs.map +0 -1
  62. package/dist/hotkey-sequence-recorder.d.cts +0 -79
  63. package/dist/hotkey-sequence-recorder.js.map +0 -1
  64. package/dist/hotkey.d.cts +0 -301
  65. package/dist/index.cjs +0 -63
  66. package/dist/index.d.cts +0 -13
  67. package/dist/key-state-tracker.cjs +0 -197
  68. package/dist/key-state-tracker.cjs.map +0 -1
  69. package/dist/key-state-tracker.d.cts +0 -107
  70. package/dist/key-state-tracker.js.map +0 -1
  71. package/dist/manager.utils.cjs +0 -115
  72. package/dist/manager.utils.cjs.map +0 -1
  73. package/dist/manager.utils.d.cts +0 -13
  74. package/dist/manager.utils.d.ts +0 -13
  75. package/dist/manager.utils.js.map +0 -1
  76. package/dist/match.cjs +0 -153
  77. package/dist/match.cjs.map +0 -1
  78. package/dist/match.d.cts +0 -85
  79. package/dist/match.js.map +0 -1
  80. package/dist/parse.cjs +0 -228
  81. package/dist/parse.cjs.map +0 -1
  82. package/dist/parse.d.cts +0 -128
  83. package/dist/parse.js.map +0 -1
  84. package/dist/recorder-chord.cjs +0 -18
  85. package/dist/recorder-chord.cjs.map +0 -1
  86. package/dist/recorder-chord.js +0 -18
  87. package/dist/recorder-chord.js.map +0 -1
  88. package/dist/sequence-manager.cjs +0 -415
  89. package/dist/sequence-manager.cjs.map +0 -1
  90. package/dist/sequence-manager.d.cts +0 -157
  91. package/dist/sequence-manager.js.map +0 -1
  92. package/dist/validate.cjs +0 -116
  93. package/dist/validate.cjs.map +0 -1
  94. package/dist/validate.d.cts +0 -56
  95. package/dist/validate.js.map +0 -1
  96. package/src/constants.ts +0 -603
  97. package/src/format.ts +0 -142
  98. package/src/hotkey-manager.ts +0 -759
  99. package/src/hotkey-recorder.ts +0 -272
  100. package/src/hotkey-sequence-recorder.ts +0 -328
  101. package/src/hotkey.ts +0 -436
  102. package/src/index.ts +0 -11
  103. package/src/key-state-tracker.ts +0 -249
  104. package/src/manager.utils.ts +0 -231
  105. package/src/match.ts +0 -259
  106. package/src/parse.ts +0 -328
  107. package/src/recorder-chord.ts +0 -25
  108. package/src/sequence-manager.ts +0 -734
  109. package/src/validate.ts +0 -171
@@ -1,759 +0,0 @@
1
- import { Store } from '@tanstack/store'
2
- import { detectPlatform, normalizeKeyName } from './constants'
3
- import { formatHotkey } from './format'
4
- import { parseHotkey, rawHotkeyToParsedHotkey } from './parse'
5
- import { matchesKeyboardEvent } from './match'
6
- import {
7
- defaultHotkeyOptions,
8
- getDefaultIgnoreInputs,
9
- handleConflict,
10
- isEventForTarget,
11
- shouldIgnoreInputEvent,
12
- } from './manager.utils'
13
- import type { ConflictBehavior } from './manager.utils'
14
- import type {
15
- Hotkey,
16
- HotkeyCallback,
17
- HotkeyCallbackContext,
18
- HotkeyMeta,
19
- ParsedHotkey,
20
- RegisterableHotkey,
21
- } from './hotkey'
22
-
23
- export type { ConflictBehavior }
24
-
25
- /**
26
- * Options for registering a hotkey.
27
- */
28
- export interface HotkeyOptions {
29
- /** Behavior when this hotkey conflicts with an existing registration on the same target. Defaults to 'warn' */
30
- conflictBehavior?: ConflictBehavior
31
- /**
32
- * Soft-disable: when `false`, the callback does not run but the registration
33
- * stays in `HotkeyManager` (and in devtools). Toggling this should update the
34
- * existing handle via `setOptions` rather than unregistering. Defaults to `true`.
35
- */
36
- enabled?: boolean
37
- /** The event type to listen for. Defaults to 'keydown' */
38
- eventType?: 'keydown' | 'keyup'
39
- /** Whether to ignore hotkeys when keyboard events originate from input-like elements (text inputs, textarea, select, contenteditable — button-type inputs like type=button/submit/reset are not ignored). Defaults based on hotkey: true for single keys and Shift/Alt combos; false for Ctrl/Meta shortcuts and Escape */
40
- ignoreInputs?: boolean
41
- /** The target platform for resolving 'Mod' */
42
- platform?: 'mac' | 'windows' | 'linux'
43
- /** Prevent the default browser action when the hotkey matches. Defaults to true */
44
- preventDefault?: boolean
45
- /** If true, only trigger once until all keys are released. Default: false */
46
- requireReset?: boolean
47
- /** Stop event propagation when the hotkey matches. Defaults to true */
48
- stopPropagation?: boolean
49
- /** The DOM element to attach the event listener to. Defaults to document. */
50
- target?: HTMLElement | Document | Window | null
51
- /** Optional metadata (name, description, custom fields via declaration merging) */
52
- meta?: HotkeyMeta
53
- }
54
-
55
- /**
56
- * A registered hotkey handler in the HotkeyManager.
57
- */
58
- export interface HotkeyRegistration {
59
- /** The callback to invoke */
60
- callback: HotkeyCallback
61
- /** Whether this registration has fired and needs reset (for requireReset) */
62
- hasFired: boolean
63
- /** The original hotkey string */
64
- hotkey: Hotkey
65
- /** Unique identifier for this registration */
66
- id: string
67
- /** Options for this registration */
68
- options: HotkeyOptions
69
- /** The parsed hotkey */
70
- parsedHotkey: ParsedHotkey
71
- /** The resolved target element for this registration */
72
- target: HTMLElement | Document | Window
73
- /** How many times this registration's callback has been triggered */
74
- triggerCount: number
75
- }
76
-
77
- /**
78
- * Public view of a hotkey registration for display and introspection.
79
- * Omits the callback function which is an internal implementation detail.
80
- */
81
- export interface HotkeyRegistrationView {
82
- /** The original hotkey string */
83
- hotkey: Hotkey
84
- /** Unique identifier for this registration */
85
- id: string
86
- /** Options for this registration */
87
- options: HotkeyOptions
88
- /** The parsed hotkey */
89
- parsedHotkey: ParsedHotkey
90
- /** The resolved target element for this registration */
91
- target: HTMLElement | Document | Window
92
- /** How many times this registration's callback has been triggered */
93
- triggerCount: number
94
- /** Whether this registration has fired and needs reset (for requireReset) */
95
- hasFired: boolean
96
- }
97
-
98
- /**
99
- * Creates a public view from an internal registration,
100
- * stripping the callback function.
101
- */
102
- export function toHotkeyRegistrationView(
103
- reg: HotkeyRegistration,
104
- ): HotkeyRegistrationView {
105
- return {
106
- hotkey: reg.hotkey,
107
- id: reg.id,
108
- options: reg.options,
109
- parsedHotkey: reg.parsedHotkey,
110
- target: reg.target,
111
- triggerCount: reg.triggerCount,
112
- hasFired: reg.hasFired,
113
- }
114
- }
115
-
116
- /**
117
- * A handle returned from HotkeyManager.register() that allows updating
118
- * the callback and options without re-registering the hotkey.
119
- *
120
- * @example
121
- * ```ts
122
- * const handle = manager.register('Mod+S', callback, options)
123
- *
124
- * // Update callback without re-registering (avoids stale closures)
125
- * handle.callback = newCallback
126
- *
127
- * // Update options without re-registering
128
- * handle.setOptions({ enabled: false })
129
- *
130
- * // Check if still active
131
- * if (handle.isActive) {
132
- * // ...
133
- * }
134
- *
135
- * // Unregister when done
136
- * handle.unregister()
137
- * ```
138
- */
139
- export interface HotkeyRegistrationHandle {
140
- /**
141
- * The callback function. Can be set directly to update without re-registering.
142
- * This avoids stale closures when the callback references React state.
143
- */
144
- callback: HotkeyCallback
145
- /** Unique identifier for this registration */
146
- readonly id: string
147
- /** Check if this registration is still active (not unregistered) */
148
- readonly isActive: boolean
149
- /**
150
- * Update options (merged with existing options).
151
- * Useful for updating `enabled`, `preventDefault`, etc. without re-registering.
152
- */
153
- setOptions: (options: Partial<HotkeyOptions>) => void
154
- /** Unregister this hotkey */
155
- unregister: () => void
156
- }
157
-
158
- let registrationIdCounter = 0
159
-
160
- /**
161
- * Generates a unique ID for hotkey registrations.
162
- */
163
- function generateId(): string {
164
- return `hotkey_${++registrationIdCounter}`
165
- }
166
-
167
- /**
168
- * Singleton manager for hotkey registrations.
169
- *
170
- * This class provides a centralized way to register and manage keyboard hotkeys.
171
- * It uses a single event listener for efficiency, regardless of how many hotkeys
172
- * are registered.
173
- *
174
- * @example
175
- * ```ts
176
- * const manager = HotkeyManager.getInstance()
177
- *
178
- * const unregister = manager.register('Mod+S', (event, context) => {
179
- * console.log('Save triggered!')
180
- * })
181
- *
182
- * // Later, to unregister:
183
- * unregister()
184
- * ```
185
- */
186
- export class HotkeyManager {
187
- static #instance: HotkeyManager | null = null
188
-
189
- /**
190
- * The TanStack Store containing all hotkey registrations.
191
- * Use this to subscribe to registration changes or access current registrations.
192
- *
193
- * @example
194
- * ```ts
195
- * const manager = HotkeyManager.getInstance()
196
- *
197
- * // Subscribe to registration changes
198
- * const unsubscribe = manager.registrations.subscribe(() => {
199
- * console.log('Registrations changed:', manager.registrations.state.size)
200
- * })
201
- *
202
- * // Access current registrations
203
- * for (const [id, reg] of manager.registrations.state) {
204
- * console.log(reg.hotkey, reg.options.enabled)
205
- * }
206
- * ```
207
- */
208
- readonly registrations: Store<Map<string, HotkeyRegistration>> = new Store(
209
- new Map(),
210
- )
211
- #platform: 'mac' | 'windows' | 'linux'
212
- #targetListeners: Map<
213
- HTMLElement | Document | Window,
214
- {
215
- keydown: (event: KeyboardEvent) => void
216
- keyup: (event: KeyboardEvent) => void
217
- }
218
- > = new Map()
219
- #targetRegistrations: Map<HTMLElement | Document | Window, Set<string>> =
220
- new Map()
221
-
222
- private constructor() {
223
- this.#platform = detectPlatform()
224
- }
225
-
226
- /**
227
- * Gets the singleton instance of HotkeyManager.
228
- */
229
- static getInstance(): HotkeyManager {
230
- if (!HotkeyManager.#instance) {
231
- HotkeyManager.#instance = new HotkeyManager()
232
- }
233
- return HotkeyManager.#instance
234
- }
235
-
236
- /**
237
- * Resets the singleton instance. Useful for testing.
238
- */
239
- static resetInstance(): void {
240
- if (HotkeyManager.#instance) {
241
- HotkeyManager.#instance.destroy()
242
- HotkeyManager.#instance = null
243
- }
244
- }
245
-
246
- /**
247
- * Registers a hotkey handler and returns a handle for updating the registration.
248
- *
249
- * The returned handle allows updating the callback and options without
250
- * re-registering, which is useful for avoiding stale closures in React.
251
- *
252
- * @param hotkey - The hotkey string (e.g., 'Mod+S') or RawHotkey object
253
- * @param callback - The function to call when the hotkey is pressed
254
- * @param options - Options for the hotkey behavior
255
- * @returns A handle for managing the registration
256
- *
257
- * @example
258
- * ```ts
259
- * const handle = manager.register('Mod+S', callback)
260
- *
261
- * // Update callback without re-registering (avoids stale closures)
262
- * handle.callback = newCallback
263
- *
264
- * // Update options
265
- * handle.setOptions({ enabled: false })
266
- *
267
- * // Unregister when done
268
- * handle.unregister()
269
- * ```
270
- */
271
- register(
272
- hotkey: RegisterableHotkey,
273
- callback: HotkeyCallback,
274
- options: HotkeyOptions = {},
275
- ): HotkeyRegistrationHandle {
276
- // In SSR environments, return a no-op handle since there's no DOM to attach listeners to
277
- if (typeof document === 'undefined' && !options.target) {
278
- let currentCallback = callback
279
- return {
280
- id: generateId(),
281
- unregister: () => {},
282
- get callback() {
283
- return currentCallback
284
- },
285
- set callback(newCallback: HotkeyCallback) {
286
- currentCallback = newCallback
287
- },
288
- setOptions: () => {},
289
- get isActive() {
290
- return false
291
- },
292
- }
293
- }
294
-
295
- const id = generateId()
296
- const platform = options.platform ?? this.#platform
297
- const parsedHotkey =
298
- typeof hotkey === 'string'
299
- ? parseHotkey(hotkey, platform)
300
- : rawHotkeyToParsedHotkey(hotkey, platform)
301
- const hotkeyStr = (
302
- typeof hotkey === 'string' ? hotkey : formatHotkey(parsedHotkey)
303
- ) as Hotkey
304
-
305
- // Resolve target: default to document if not provided
306
- // Note: SSR case without explicit target is handled above
307
- const target = options.target ?? document
308
-
309
- // Resolve conflict behavior
310
- const conflictBehavior = options.conflictBehavior ?? 'warn'
311
-
312
- // Check for existing registrations with the same hotkey and target
313
- const conflictingRegistration = this.#findConflictingRegistration(
314
- hotkeyStr,
315
- target,
316
- )
317
-
318
- if (conflictingRegistration) {
319
- handleConflict(
320
- conflictingRegistration.id,
321
- hotkeyStr,
322
- conflictBehavior,
323
- (id) => this.#unregister(id),
324
- )
325
- }
326
-
327
- const resolvedIgnoreInputs =
328
- options.ignoreInputs ?? getDefaultIgnoreInputs(parsedHotkey)
329
-
330
- const baseOptions = {
331
- ...defaultHotkeyOptions,
332
- requireReset: false,
333
- ...options,
334
- platform,
335
- }
336
-
337
- const registration: HotkeyRegistration = {
338
- id,
339
- hotkey: hotkeyStr,
340
- parsedHotkey,
341
- callback,
342
- options: { ...baseOptions, ignoreInputs: resolvedIgnoreInputs },
343
- hasFired: false,
344
- triggerCount: 0,
345
- target,
346
- }
347
-
348
- this.registrations.setState((prev) => new Map(prev).set(id, registration))
349
-
350
- // Track registration for this target
351
- if (!this.#targetRegistrations.has(target)) {
352
- this.#targetRegistrations.set(target, new Set())
353
- }
354
- this.#targetRegistrations.get(target)!.add(id)
355
-
356
- // Ensure listeners are attached for this target
357
- this.#ensureListenersForTarget(target)
358
-
359
- // Create and return the handle
360
- const manager = this
361
- const handle: HotkeyRegistrationHandle = {
362
- get id() {
363
- return id
364
- },
365
- unregister: () => {
366
- manager.#unregister(id)
367
- },
368
- get callback() {
369
- const reg = manager.registrations.state.get(id)
370
- return reg?.callback ?? callback
371
- },
372
- set callback(newCallback: HotkeyCallback) {
373
- const reg = manager.registrations.state.get(id)
374
- if (reg) {
375
- reg.callback = newCallback
376
- }
377
- },
378
- setOptions: (newOptions: Partial<HotkeyOptions>) => {
379
- manager.registrations.setState((prev) => {
380
- const reg = prev.get(id)
381
- if (reg) {
382
- const next = new Map(prev)
383
- next.set(id, { ...reg, options: { ...reg.options, ...newOptions } })
384
- return next
385
- }
386
- return prev
387
- })
388
- },
389
- get isActive() {
390
- return manager.registrations.state.has(id)
391
- },
392
- }
393
-
394
- return handle
395
- }
396
-
397
- /**
398
- * Unregisters a hotkey by its registration ID.
399
- */
400
- #unregister(id: string): void {
401
- const registration = this.registrations.state.get(id)
402
- if (!registration) {
403
- return
404
- }
405
-
406
- const target = registration.target
407
-
408
- // Remove registration
409
- this.registrations.setState((prev) => {
410
- const next = new Map(prev)
411
- next.delete(id)
412
- return next
413
- })
414
-
415
- // Remove from target registrations tracking
416
- const targetRegs = this.#targetRegistrations.get(target)
417
- if (targetRegs) {
418
- targetRegs.delete(id)
419
- // If no more registrations for this target, remove listeners
420
- if (targetRegs.size === 0) {
421
- this.#removeListenersForTarget(target)
422
- }
423
- }
424
- }
425
-
426
- /**
427
- * Ensures event listeners are attached for a specific target.
428
- */
429
- #ensureListenersForTarget(target: HTMLElement | Document | Window): void {
430
- if (typeof document === 'undefined') {
431
- return // SSR safety
432
- }
433
-
434
- // Skip if listeners already exist for this target
435
- if (this.#targetListeners.has(target)) {
436
- return
437
- }
438
-
439
- const keydownHandler = this.#createTargetKeyDownHandler(target)
440
- const keyupHandler = this.#createTargetKeyUpHandler(target)
441
-
442
- target.addEventListener('keydown', keydownHandler as EventListener)
443
- target.addEventListener('keyup', keyupHandler as EventListener)
444
-
445
- this.#targetListeners.set(target, {
446
- keydown: keydownHandler,
447
- keyup: keyupHandler,
448
- })
449
- }
450
-
451
- /**
452
- * Removes event listeners for a specific target.
453
- */
454
- #removeListenersForTarget(target: HTMLElement | Document | Window): void {
455
- if (typeof document === 'undefined') {
456
- return
457
- }
458
-
459
- const listeners = this.#targetListeners.get(target)
460
- if (!listeners) {
461
- return
462
- }
463
-
464
- target.removeEventListener('keydown', listeners.keydown as EventListener)
465
- target.removeEventListener('keyup', listeners.keyup as EventListener)
466
-
467
- this.#targetListeners.delete(target)
468
- this.#targetRegistrations.delete(target)
469
- }
470
-
471
- /**
472
- * Processes keyboard events for a specific target and event type.
473
- */
474
- #processTargetEvent(
475
- event: KeyboardEvent,
476
- target: HTMLElement | Document | Window,
477
- eventType: 'keydown' | 'keyup',
478
- ): void {
479
- const targetRegs = this.#targetRegistrations.get(target)
480
- if (!targetRegs) {
481
- return
482
- }
483
-
484
- for (const id of targetRegs) {
485
- const registration = this.registrations.state.get(id)
486
- if (!registration) {
487
- continue
488
- }
489
-
490
- // Check if event originated from or bubbled to this target
491
- if (!isEventForTarget(event, target)) {
492
- continue
493
- }
494
-
495
- if (!registration.options.enabled) {
496
- continue
497
- }
498
-
499
- // Check if we should ignore input elements (defaults to true)
500
- if (registration.options.ignoreInputs !== false) {
501
- if (shouldIgnoreInputEvent(event, target, registration.target)) {
502
- continue
503
- }
504
- }
505
-
506
- // Handle keydown events
507
- if (eventType === 'keydown') {
508
- if (registration.options.eventType !== 'keydown') {
509
- continue
510
- }
511
-
512
- // Check if the hotkey matches first
513
- const matches = matchesKeyboardEvent(
514
- event,
515
- registration.parsedHotkey,
516
- registration.options.platform,
517
- )
518
-
519
- if (matches) {
520
- // Always apply preventDefault/stopPropagation if the hotkey matches,
521
- // even when requireReset is active and has already fired
522
- if (registration.options.preventDefault) {
523
- event.preventDefault()
524
- }
525
- if (registration.options.stopPropagation) {
526
- event.stopPropagation()
527
- }
528
-
529
- // Only execute callback if requireReset is not active or hasn't fired yet
530
- if (!registration.options.requireReset || !registration.hasFired) {
531
- this.#executeHotkeyCallback(registration, event)
532
-
533
- // Mark as fired if requireReset is enabled
534
- if (registration.options.requireReset) {
535
- registration.hasFired = true
536
- }
537
- }
538
- }
539
- }
540
- // Handle keyup events
541
- else {
542
- if (registration.options.eventType === 'keyup') {
543
- if (
544
- matchesKeyboardEvent(
545
- event,
546
- registration.parsedHotkey,
547
- registration.options.platform,
548
- )
549
- ) {
550
- this.#executeHotkeyCallback(registration, event)
551
- }
552
- }
553
-
554
- // Reset hasFired when any key in the hotkey is released
555
- if (registration.options.requireReset && registration.hasFired) {
556
- if (this.#shouldResetRegistration(registration, event)) {
557
- registration.hasFired = false
558
- }
559
- }
560
- }
561
- }
562
- }
563
-
564
- /**
565
- * Executes a hotkey callback with proper event handling.
566
- */
567
- #executeHotkeyCallback(
568
- registration: HotkeyRegistration,
569
- event: KeyboardEvent,
570
- ): void {
571
- if (registration.options.preventDefault) {
572
- event.preventDefault()
573
- }
574
- if (registration.options.stopPropagation) {
575
- event.stopPropagation()
576
- }
577
-
578
- registration.triggerCount++
579
-
580
- // Notify the store so subscribers (e.g. devtools) see the updated count.
581
- // We create a new Map but keep the same registration reference to preserve
582
- // identity for mutation-based fields like hasFired.
583
- this.registrations.setState((prev) => new Map(prev))
584
-
585
- const context: HotkeyCallbackContext = {
586
- hotkey: registration.hotkey,
587
- parsedHotkey: registration.parsedHotkey,
588
- }
589
-
590
- registration.callback(event, context)
591
- }
592
-
593
- /**
594
- * Creates a keydown handler for a specific target.
595
- */
596
- #createTargetKeyDownHandler(
597
- target: HTMLElement | Document | Window,
598
- ): (event: KeyboardEvent) => void {
599
- return (event: KeyboardEvent) => {
600
- this.#processTargetEvent(event, target, 'keydown')
601
- }
602
- }
603
-
604
- /**
605
- * Creates a keyup handler for a specific target.
606
- */
607
- #createTargetKeyUpHandler(
608
- target: HTMLElement | Document | Window,
609
- ): (event: KeyboardEvent) => void {
610
- return (event: KeyboardEvent) => {
611
- this.#processTargetEvent(event, target, 'keyup')
612
- }
613
- }
614
-
615
- /**
616
- * Finds an existing registration with the same hotkey and target.
617
- */
618
- #findConflictingRegistration(
619
- hotkey: Hotkey,
620
- target: HTMLElement | Document | Window,
621
- ): HotkeyRegistration | null {
622
- for (const registration of this.registrations.state.values()) {
623
- if (registration.hotkey === hotkey && registration.target === target) {
624
- return registration
625
- }
626
- }
627
- return null
628
- }
629
-
630
- /**
631
- * Determines if a registration should be reset based on the keyup event.
632
- */
633
- #shouldResetRegistration(
634
- registration: HotkeyRegistration,
635
- event: KeyboardEvent,
636
- ): boolean {
637
- const parsed = registration.parsedHotkey
638
- const releasedKey = normalizeKeyName(event.key)
639
-
640
- // Reset if the main key is released
641
- // Compare case-insensitively for single-letter keys
642
- const parsedKeyNormalized =
643
- parsed.key.length === 1 ? parsed.key.toUpperCase() : parsed.key
644
- const releasedKeyNormalized =
645
- releasedKey.length === 1 ? releasedKey.toUpperCase() : releasedKey
646
-
647
- if (releasedKeyNormalized === parsedKeyNormalized) {
648
- return true
649
- }
650
-
651
- // Reset if any required modifier is released
652
- // Use normalized key names and check against canonical modifier names
653
- if (parsed.ctrl && releasedKey === 'Control') {
654
- return true
655
- }
656
- if (parsed.shift && releasedKey === 'Shift') {
657
- return true
658
- }
659
- if (parsed.alt && releasedKey === 'Alt') {
660
- return true
661
- }
662
- if (parsed.meta && releasedKey === 'Meta') {
663
- return true
664
- }
665
-
666
- return false
667
- }
668
-
669
- /**
670
- * Triggers a registration's callback programmatically from devtools.
671
- * Creates a synthetic KeyboardEvent and invokes the callback.
672
- *
673
- * @param id - The registration ID to trigger
674
- * @returns True if the registration was found and triggered
675
- */
676
- triggerRegistration(id: string): boolean {
677
- const registration = this.registrations.state.get(id)
678
- if (!registration) {
679
- return false
680
- }
681
-
682
- const parsed = registration.parsedHotkey
683
- const syntheticEvent = new KeyboardEvent(
684
- registration.options.eventType ?? 'keydown',
685
- {
686
- key: parsed.key,
687
- ctrlKey: parsed.ctrl,
688
- shiftKey: parsed.shift,
689
- altKey: parsed.alt,
690
- metaKey: parsed.meta,
691
- bubbles: true,
692
- cancelable: true,
693
- },
694
- )
695
-
696
- registration.triggerCount++
697
-
698
- // Notify the store so subscribers (e.g. devtools) see the updated count
699
- this.registrations.setState((prev) => new Map(prev))
700
-
701
- registration.callback(syntheticEvent, {
702
- hotkey: registration.hotkey,
703
- parsedHotkey: registration.parsedHotkey,
704
- })
705
-
706
- return true
707
- }
708
-
709
- /**
710
- * Gets the number of registered hotkeys.
711
- */
712
- getRegistrationCount(): number {
713
- return this.registrations.state.size
714
- }
715
-
716
- /**
717
- * Checks if a specific hotkey is registered.
718
- *
719
- * @param hotkey - The hotkey string to check
720
- * @param target - Optional target element to match (if provided, both hotkey and target must match)
721
- * @returns True if a matching registration exists
722
- */
723
- isRegistered(
724
- hotkey: Hotkey,
725
- target?: HTMLElement | Document | Window,
726
- ): boolean {
727
- for (const registration of this.registrations.state.values()) {
728
- if (registration.hotkey === hotkey) {
729
- // If target is specified, both must match
730
- if (target === undefined || registration.target === target) {
731
- return true
732
- }
733
- }
734
- }
735
- return false
736
- }
737
-
738
- /**
739
- * Destroys the manager and removes all listeners.
740
- */
741
- destroy(): void {
742
- // Remove all target listeners
743
- for (const target of this.#targetListeners.keys()) {
744
- this.#removeListenersForTarget(target)
745
- }
746
-
747
- this.registrations.setState(() => new Map())
748
- this.#targetListeners.clear()
749
- this.#targetRegistrations.clear()
750
- }
751
- }
752
-
753
- /**
754
- * Gets the singleton HotkeyManager instance.
755
- * Convenience function for accessing the manager.
756
- */
757
- export function getHotkeyManager(): HotkeyManager {
758
- return HotkeyManager.getInstance()
759
- }