@tanstack/hotkeys 0.9.0 → 0.10.1

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