hotkey-router 0.3.0 → 0.3.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.
package/README.md CHANGED
@@ -1,540 +1,541 @@
1
- # hotkey-router
2
-
3
- [![npm](https://img.shields.io/npm/v/hotkey-router)](https://www.npmjs.com/package/hotkey-router)
4
- [![downloads](https://img.shields.io/npm/dm/hotkey-router)](https://www.npmjs.com/package/hotkey-router)
5
- [![bundle size](https://img.shields.io/bundlephobia/minzip/hotkey-router)](https://bundlephobia.com/package/hotkey-router)
6
- [![license](https://img.shields.io/npm/l/hotkey-router)](https://github.com/iWhatty/hotkey-router/blob/main/LICENSE)
7
- [![stars](https://img.shields.io/github/stars/iWhatty/hotkey-router?style=social)](https://github.com/iWhatty/hotkey-router)
8
- [![types](https://img.shields.io/npm/types/hotkey-router)](https://www.npmjs.com/package/hotkey-router)
9
-
10
- A tiny, deterministic keyboard routing engine for modern web apps. Not a key utility, a predictable plugin-first routing layer for keyboard shortcuts.
11
-
12
- ## Features
13
-
14
- - O(1) dispatch
15
- - Plugin-safe lifecycle management
16
- - Deterministic winner selection (priority + recency)
17
- - Input-safe by default
18
- - Testable via `trigger()`
19
- - Optional opt-in browser/OS conflict warnings (tree-shakable)
20
- - ~3 kB minified + gzipped (core); ~7.5 kB with conflict warnings
21
- - Zero dependencies
22
-
23
- ---
24
-
25
- ## Install
26
-
27
- ```sh
28
- pnpm add hotkey-router
29
- ```
30
-
31
- ESM:
32
-
33
- ```js
34
- import hotkeys from 'hotkey-router'
35
- ```
36
-
37
- CommonJS:
38
-
39
- ```js
40
- const hotkeys = require('hotkey-router')
41
- ```
42
-
43
- CDN (ESM):
44
-
45
- ```js
46
- import hotkeys from 'https://cdn.jsdelivr.net/npm/hotkey-router/dist/hotkey-router.min.js'
47
- ```
48
-
49
- ---
50
-
51
- ## Quick start
52
-
53
- ```js
54
- import hotkeys from 'hotkey-router'
55
-
56
- // Simple keydown
57
- hotkeys.bind('ctrl+k', () => {
58
- openCommandPalette()
59
- })
60
-
61
- // Multi-modifier combos, including the spacebar
62
- hotkeys.bind('mod+shift+space', summonCommandPalette)
63
-
64
- // Keyup using " up" suffix
65
- hotkeys.bind('ctrl+p up', () => {
66
- console.log('Released CTRL+P')
67
- })
68
-
69
- // AHK-style modifiers also supported
70
- hotkeys.bind('^k', () => {
71
- openCommandPalette() // ctrl+k
72
- })
73
-
74
- // Bare-modifier bindings (Alt-as-mode UX)
75
- hotkeys.bind('alt', enterSelectMode) // fires on Alt keydown
76
- hotkeys.bind('alt up', exitSelectMode) // fires on Alt keyup
77
-
78
- // Layout-stable matching via KeyboardEvent.code (cross-platform Alt+letter,
79
- // works on macOS where Option remaps Alt+X to ≈)
80
- hotkeys.bind('alt+code:KeyX', deleteHovered, null, { preventDefault: true })
81
-
82
- // Plugin grouping
83
- hotkeys.registerPlugin('docs', {
84
- 'ctrl+f': openSearch,
85
- 'escape': closeSearch,
86
- })
87
- ```
88
-
89
- ---
90
-
91
- ## API
92
-
93
- ### `bind(hotkey, handler, plugin?, options?)`
94
-
95
- Register a hotkey. Returns an `off()` function.
96
-
97
- ```js
98
- const off = hotkeys.bind('mod+k', openPalette)
99
-
100
- // Later
101
- off()
102
- ```
103
-
104
- **Options**
105
-
106
- ```ts
107
- {
108
- preventDefault?: boolean
109
- stopPropagation?: boolean
110
- stopImmediatePropagation?: boolean
111
- repeat?: boolean // default false on keydown
112
- once?: boolean
113
- when?: (event) => boolean
114
- allowIn?: (event) => boolean
115
- priority?: number // default 0
116
- warnOnReserved?: boolean // only read when conflict warnings are installed
117
- capture?: boolean // v0.3.0+: run in the capture phase, before the page's listeners
118
- altGraph?: boolean // v0.3.0+: also fire on an AltGr keystroke that types a character
119
- composing?: boolean // v0.3.0+: also fire during IME composition
120
- }
121
- ```
122
-
123
- By default (v0.3.0+), a binding is skipped when the keystroke is AltGr typing
124
- a character (Windows reports AltGr as Ctrl+Alt, so `ctrl+alt+code:Comma`
125
- would otherwise swallow the `<` a Polish or Czech user typed) and while an
126
- IME is composing.
127
-
128
- **Examples**
129
-
130
- Ignore repeat keydown (default behavior):
131
-
132
- ```js
133
- hotkeys.bind('j', nextItem)
134
- ```
135
-
136
- Allow inside inputs:
137
-
138
- ```js
139
- hotkeys.bind('mod+k', openPalette, null, {
140
- allowIn: () => true,
141
- preventDefault: true,
142
- })
143
- ```
144
-
145
- Conditional binding:
146
-
147
- ```js
148
- hotkeys.bind('delete', deleteItem, null, {
149
- when: () => selectionCount() > 0,
150
- })
151
- ```
152
-
153
- Run once:
154
-
155
- ```js
156
- hotkeys.bind('ctrl+s', saveDraft, null, { once: true })
157
- ```
158
-
159
- ### `unbind(hotkey, handler?)`
160
-
161
- Remove bindings.
162
-
163
- ```js
164
- hotkeys.unbind('ctrl+k')
165
- hotkeys.unbind('ctrl+k', openPalette)
166
- ```
167
-
168
- ### `registerPlugin(name, map)`
169
-
170
- Batch register hotkeys under a plugin namespace.
171
-
172
- ```js
173
- const unregister = hotkeys.registerPlugin('files', {
174
- 'mod+o': openFile,
175
- 'delete': deleteFile,
176
- })
177
-
178
- // Later
179
- unregister()
180
- ```
181
-
182
- Plugin cleanup is isolated. Removing one plugin never affects other bindings.
183
-
184
- ### `unregisterPlugin(name)`
185
-
186
- Remove all hotkeys associated with a plugin.
187
-
188
- ### `onBind(hook)`
189
-
190
- Subscribe to bind events. The hook receives `{ combo, raw, options, plugin, id }` after every successful `bind()`. Returns an unsubscribe function. Used internally by `installReservationWarnings`; exposed for telemetry, dev panels, and custom validation.
191
-
192
- ```js
193
- const off = hotkeys.onBind(({ raw }) => {
194
- console.debug('bound:', raw)
195
- })
196
- // off() unsubscribes.
197
- ```
198
-
199
- Hook errors are caught and logged via `console.error`. A buggy hook can't break the bind.
200
-
201
- ### `pause()` / `resume()`
202
-
203
- Temporarily disable or re-enable all routing.
204
-
205
- ### `ignoreInput(boolean = true)`
206
-
207
- By default, hotkeys do **not** fire inside:
208
-
209
- - `<input>`
210
- - `<textarea>`
211
- - `<select>`
212
- - `[contenteditable]`
213
- - `role="textbox"`
214
-
215
- Override per-binding with `allowIn()`.
216
-
217
- ### `init(options?)`
218
-
219
- Manually attach listeners.
220
-
221
- ```js
222
- hotkeys.init({
223
- target: window,
224
- capture: false,
225
- })
226
- ```
227
-
228
- Auto-initializes on `window` by default (browser environments).
229
-
230
- With `capture: false` (the default), bindings run in the bubble phase except
231
- those bound with `{ capture: true }`, which a second, capture-phase listener
232
- handles (v0.3.0+). `capture: true` here runs every binding in the capture
233
- phase.
234
-
235
- ### `parseHotkey(hotkey)` / `comboFromEvent(event, options?)` (v0.3.0+)
236
-
237
- Named exports (also on the default object). `comboFromEvent` turns a
238
- keyboard event into a hotkey string for a "press your keys" recorder:
239
- physical by default, `{ useMod: true }` writes the platform's primary
240
- modifier as `mod`, and it returns `null` while only a modifier is held.
241
-
242
- ```js
243
- import { comboFromEvent } from 'hotkey-router'
244
-
245
- input.addEventListener('keydown', (e) => {
246
- const combo = comboFromEvent(e, { useMod: true }) // 'mod+shift+code:Period'
247
- if (combo) save(combo)
248
- })
249
- ```
250
-
251
- ### `destroy()`
252
-
253
- Removes all listeners and clears internal state.
254
-
255
- ### `trigger(hotkey, options?)`
256
-
257
- Programmatically trigger a hotkey. Useful for testing.
258
-
259
- ```js
260
- hotkeys.trigger('ctrl+k')
261
- ```
262
-
263
- Returns `true` if a handler ran.
264
-
265
- ---
266
-
267
- ## Notes
268
-
269
- ### Routing model
270
-
271
- When multiple handlers match the same hotkey:
272
-
273
- 1. Highest `priority` wins.
274
- 2. If equal priority, newest binding wins.
275
-
276
- This makes modal overrides simple:
277
-
278
- ```js
279
- hotkeys.bind('escape', closeModal, null, {
280
- priority: 100,
281
- preventDefault: true,
282
- })
283
- ```
284
-
285
- ### Bare-modifier bindings (v0.1.0+)
286
-
287
- Some UX patterns are driven by a bare modifier rather than a chord. For example, "hold Alt to enter select mode, release Alt to exit."
288
-
289
- ```js
290
- hotkeys.bind('alt', onAltDown) // fires on Alt keydown
291
- hotkeys.bind('alt up', onAltUp) // fires on Alt keyup
292
- hotkeys.bind('ctrl', onCtrlDown) // any single modifier supported
293
- ```
294
-
295
- - Only **single** bare modifiers are supported. Multi-modifier bare bindings (`'ctrl+alt'`) throw, add a base key for those.
296
- - Default `repeat: false` applies, so a held modifier fires only once on keydown.
297
- - Loose match: a bare-Alt binding fires whenever the Alt key is the one being pressed/released, regardless of which other modifier flags are also set. Add a `when` filter for exact-set semantics.
298
-
299
- ### Code-based matching (v0.1.0+)
300
-
301
- `KeyboardEvent.key` is layout- and modifier-dependent. Alt+X gives `≈` on macOS, `x` on Linux/Windows. For shortcuts that should be stable across platforms, bind to `KeyboardEvent.code` instead:
302
-
303
- ```js
304
- hotkeys.bind('alt+code:KeyX', deleteHovered) // matches the physical X key
305
- hotkeys.bind('ctrl+code:Digit1', goToTab1) // matches digit row, not numpad
306
- hotkeys.bind('!code:KeyX', deleteHovered) // AHK shorthand also works
307
- ```
308
-
309
- The `code:` value is **case-sensitive** (matches the camelCase `KeyboardEvent.code` spec values: `KeyA`, `Digit1`, `ArrowLeft`, etc.). Only one `code:` token per binding is allowed; multiple `code:` tokens throw a parse error. Both key-based and code-based bindings can coexist; the standard priority + recency rules pick the winner.
310
-
311
- ### Conflict warnings (v0.2.0+)
312
-
313
- Some combos are reserved by the browser chrome (find bar, devtools, bookmarks) or the OS (Spotlight, window management). They never reach page-world JavaScript, no matter how early you listen or whether you call `preventDefault`. hotkey-router ships an **opt-in** reservation table that emits a soft warning at bind time, so the silent failure becomes a noisy one.
314
-
315
- The feature is opt-in by design: the core router stays ~3 KB gzipped, and the ~5 KB reservation data is tree-shaken out entirely unless you import it.
316
-
317
- **Two ways to opt in.** One-line ergonomic, use the `auto` entry. Same default export as `hotkey-router`, with warnings pre-installed:
318
-
319
- ```js
320
- import hotkeys from 'hotkey-router/auto'
321
-
322
- hotkeys.bind('meta+shift+f', toggleFullscreen)
323
- // Firefox on macOS:
324
- // [hotkey-router] "meta+shift+f" reserved by firefox on macOS:
325
- // "Toggle fullscreen" [hard], will not fire.
326
- ```
327
-
328
- Explicit install, keep using the tiny core, install warnings yourself:
329
-
330
- ```js
331
- import hotkeys from 'hotkey-router'
332
- import { installReservationWarnings } from 'hotkey-router/reservations'
333
-
334
- installReservationWarnings(hotkeys)
335
- hotkeys.bind('meta+shift+f', toggleFullscreen)
336
- ```
337
-
338
- `installReservationWarnings()` returns an `uninstall` function if you ever need to detach. The warning is **never fatal**, the binding is still registered, in case you're running in a browser/platform where the conflict doesn't apply.
339
-
340
- **Severity to log level:**
341
-
342
- | Severity | Log level | Meaning |
343
- | ----------------- | --------- | ------------------------------------------------------- |
344
- | `hard` | `warn` | Browser intercepts before page world; combo won't fire. |
345
- | `os` | `warn` | OS intercepts globally. |
346
- | `menu-activation` | `warn` | Alt+letter activates the browser menu bar (Win/Linux). |
347
- | `find-bar-only` | `info` | Reserved only when the find bar is focused. |
348
- | `compose` | `info` | macOS Option+letter types a special char in inputs. |
349
- | `system-text` | `info` | Mac Ctrl+letter cursor controls inside text inputs. |
350
- | `devtools-open` | `info` | Only relevant when DevTools is already open. |
351
-
352
- **Per-bind opt-out:**
353
-
354
- ```js
355
- hotkeys.bind('meta+shift+f', toggleFullscreen, null, { warnOnReserved: false })
356
- ```
357
-
358
- To turn warnings off globally, just don't install them (use the bare `hotkey-router` entry instead of `hotkey-router/auto`).
359
-
360
- **Force a platform/browser (tests, SSR previews):**
361
-
362
- ```js
363
- installReservationWarnings(hotkeys, { platform: 'mac', browser: 'firefox' })
364
- ```
365
-
366
- Accepted platforms: `'mac' | 'windows' | 'linux'`. Browsers: `'firefox' | 'chrome' | 'safari' | 'edge'`.
367
-
368
- **Caveats:**
369
-
370
- - Reservations reflect **default** keybindings. Users with custom shortcuts (Edge 95+ rebinds, Firefox add-ons, OS-level customization) may not match.
371
- - KDE/XFCE desktop reservations beyond GNOME are not yet catalogued. Linux coverage is conservative.
372
- - Layout-specific differences (Dvorak, AZERTY) change which physical key produces `event.key === 'f'`. For layout-stable bindings against the physical key, use `code:KeyX` syntax. The reservation lookup normalizes both.
373
-
374
- **Programmatic lookup.** If you want to query the table yourself (e.g. building a cheatsheet that flags conflicts):
375
-
376
- ```js
377
- import { lookupReservation } from 'hotkey-router/reservations'
378
-
379
- const r = lookupReservation(
380
- { meta: true, shift: true, key: 'f' },
381
- { platform: 'mac', browser: 'firefox' }
382
- )
383
- // → { source: 'browser', action: 'Toggle fullscreen', severity: 'hard', ... }
384
- ```
385
-
386
- **Extension hook (`onBind`).** Reservation warnings are built on a public `onBind` hook, useful for telemetry, dev panels, or any cross-cutting concern that needs to observe every binding:
387
-
388
- ```js
389
- const off = hotkeys.onBind(({ combo, raw, options, plugin, id }) => {
390
- // combo: parsed combo { ctrl, meta, alt, shift, key, code, bareModifier }
391
- // raw: original hotkey string
392
- })
393
- // off() unsubscribes.
394
- ```
395
-
396
- ### Website shortcuts (v0.3.0+)
397
-
398
- Apps that run on other people's pages (browser extensions, embedded widgets)
399
- collide with the page's own shortcuts: Google Docs uses Ctrl+Shift+. for font
400
- size, GitHub for "quote". Unlike browser keys, those reach the page, so the
401
- app can choose. `hotkey-router/sites` knows which popular sites use which
402
- chords in the Ctrl/Cmd+Shift, Ctrl/Cmd+Alt, Shift+Alt and Ctrl/Cmd+Alt+Shift
403
- families ([docs/site-hotkeys.md](docs/site-hotkeys.md), sourced data in
404
- `data/site-hotkeys.json`) and builds a `when()` gate that yields to the site
405
- unless the user is focused on the app:
406
-
407
- ```js
408
- import hotkeys from 'hotkey-router'
409
- import { siteAware } from 'hotkey-router/sites'
410
-
411
- hotkeys.bind('mod+shift+code:Period', nextTypo, null, {
412
- capture: true, // see the key before the page's editor
413
- preventDefault: true,
414
- stopPropagation: true, // when we take it, the page doesn't run it too
415
- allowIn: () => true,
416
- when: siteAware('mod+shift+code:Period', {
417
- engaged: () => popupIsOpen() || panelHasFocus(),
418
- }),
419
- })
420
- ```
421
-
422
- On sites that don't use the chord the gate is always true. On sites that do
423
- (Docs, Slides, Confluence, GitHub, WordPress ...), it returns `engaged()`;
424
- when that is false, the router leaves the event untouched and the site's
425
- shortcut runs.
426
-
427
- Also exported: `lookupSiteConflicts(combo, { url, platform, verifiedOnly })`,
428
- `matchSites(url)`, `siteLookupKey(combo, platform)`, `detectSitePlatform()`
429
- and `listSites()`. Platforms: `windows` (also used for Linux), `mac`,
430
- `chromeos`. The runtime table is ~7 KB gzipped and imports nothing from the
431
- core, so it never creates a second router.
432
-
433
- ### Validating a recorded combo (v0.3.0+)
434
-
435
- For a "press your keys" setting: record with `comboFromEvent`, then check
436
- with `hotkey-router/validate` before saving. Reasons come in plain language,
437
- ready to show.
438
-
439
- ```js
440
- import { comboFromEvent } from 'hotkey-router'
441
- import { validateCombo } from 'hotkey-router/validate'
442
-
443
- field.addEventListener('keydown', (e) => {
444
- e.preventDefault()
445
- const combo = comboFromEvent(e, { useMod: true })
446
- if (!combo) return // still holding modifiers
447
- const { ok, reasons } = validateCombo(combo, {
448
- requirePrimary: true, // must include Ctrl (Cmd on macOS)
449
- minModifiers: 2,
450
- taken: ['mod+shift+code:Space'],
451
- })
452
- show(reasons.map((r) => r.message))
453
- if (ok) save(combo)
454
- })
455
- ```
456
-
457
- Errors (`ok: false`): no key, no modifier, Alt as the only modifier on
458
- Windows/Linux, a rule you asked for (`requirePrimary`, `minModifiers`),
459
- already in `taken`, or reserved by a browser/OS (never reaches the page).
460
- Warnings (`ok: true`): reserved only in some situations, Ctrl+Alt acting as
461
- AltGr on some Windows layouts, and sites that use the same keys.
462
-
463
- ### Supported syntax
464
-
465
- **Standard:**
466
-
467
- - `ctrl+k`
468
- - `shift+a`
469
- - `ctrl+k up`
470
- - `mod+s` (meta on macOS, ctrl elsewhere)
471
- - `ctrl++` or `ctrl+plus`
472
-
473
- **AHK-style prefix modifiers:**
474
-
475
- - `^k` → `ctrl+k`
476
- - `!k` → `alt+k`
477
- - `+k` → `shift+k`
478
- - `#k` → `meta+k`
479
- - `^!k` → `ctrl+alt+k`
480
-
481
- Modifiers must appear before the base key.
482
-
483
- **Modifier aliases:**
484
-
485
- - `ctrl`, `control`, `⌃`
486
- - `shift`, `⇧`, `+`
487
- - `alt`, `option`, `⌥`, `!`
488
- - `meta`, `cmd`, `command`, `win`, `⌘`, `#`
489
- - `mod` (meta on macOS, ctrl elsewhere)
490
-
491
- **Navigation / special key aliases:**
492
-
493
- - `escape`, `esc`
494
- - `enter`, `return`
495
- - `space`, `spacebar`
496
- - `tab`
497
- - `backspace`
498
- - `delete`, `del`
499
- - `home`, `end`
500
- - `pageup`, `pgup`
501
- - `pagedown`, `pgdn`
502
- - `up`, `down`, `left`, `right`
503
- - `f1`–`f19`
504
-
505
- Keys are case-insensitive.
506
-
507
- ### Philosophy
508
-
509
- hotkey-router follows three core rules:
510
-
511
- 1. **Predictable routing.** Highest priority wins. Ties go to the most recently bound handler.
512
- 2. **Safe composition.** Plugins can register and unregister without affecting others.
513
- 3. **Modern only.** Built for modern browsers using `KeyboardEvent.key`.
514
-
515
- No keycodes. No legacy IE hacks. No hidden global scope state.
516
-
517
- ### What this is not
518
-
519
- - Not a keycode polyfill
520
- - Not a legacy browser shim
521
- - Not a global scope manager
522
- - Not a VSCode-style sequence engine
523
-
524
- This is a small, deterministic routing layer for modern applications.
525
-
526
- ### Browser support
527
-
528
- Modern browsers supporting:
529
-
530
- - `KeyboardEvent.key`
531
- - `Map`
532
- - `addEventListener`
533
-
534
- Chrome, Firefox, Safari, Edge.
535
-
536
- ---
537
-
538
- ## License
539
-
540
- Licensed under AGPL-3.0 with WATT3D Additional Terms. See [LICENSE](./LICENSE) and [ADDITIONAL_TERMS.md](./ADDITIONAL_TERMS.md). Commercial AI/model-training use requires compliance with those terms or a separate WATT3D license. © WATT3D.
1
+ # hotkey-router
2
+
3
+ [![npm](https://img.shields.io/npm/v/hotkey-router)](https://www.npmjs.com/package/hotkey-router)
4
+ [![downloads](https://img.shields.io/npm/dm/hotkey-router)](https://www.npmjs.com/package/hotkey-router)
5
+ [![bundle size](https://img.shields.io/bundlephobia/minzip/hotkey-router)](https://bundlephobia.com/package/hotkey-router)
6
+ [![license](https://img.shields.io/npm/l/hotkey-router)](https://github.com/iWhatty/hotkey-router/blob/main/LICENSE)
7
+ [![stars](https://img.shields.io/github/stars/iWhatty/hotkey-router?style=social)](https://github.com/iWhatty/hotkey-router)
8
+ [![types](https://img.shields.io/npm/types/hotkey-router)](https://www.npmjs.com/package/hotkey-router)
9
+
10
+ A tiny, deterministic keyboard routing engine for modern web apps. Not a key utility, a predictable plugin-first routing layer for keyboard shortcuts.
11
+
12
+ ## Features
13
+
14
+ - O(1) dispatch
15
+ - Plugin-safe lifecycle management
16
+ - Deterministic winner selection (priority + recency)
17
+ - Input-safe by default
18
+ - Testable via `trigger()`
19
+ - Optional opt-in browser/OS conflict warnings (tree-shakable)
20
+ - ~3 kB minified + gzipped (core); ~7.5 kB with conflict warnings
21
+ - Zero dependencies
22
+
23
+ ---
24
+
25
+ ## Install
26
+
27
+ ```sh
28
+ pnpm add hotkey-router
29
+ ```
30
+
31
+ ESM:
32
+
33
+ ```js
34
+ import hotkeys from 'hotkey-router'
35
+ ```
36
+
37
+ CommonJS:
38
+
39
+ ```js
40
+ const hotkeys = require('hotkey-router')
41
+ ```
42
+
43
+ CDN (ESM):
44
+
45
+ ```js
46
+ import hotkeys from 'https://cdn.jsdelivr.net/npm/hotkey-router/dist/hotkey-router.min.js'
47
+ ```
48
+
49
+ ---
50
+
51
+ ## Quick start
52
+
53
+ ```js
54
+ import hotkeys from 'hotkey-router'
55
+
56
+ // Simple keydown
57
+ hotkeys.bind('ctrl+k', () => {
58
+ openCommandPalette()
59
+ })
60
+
61
+ // Multi-modifier combos, including the spacebar
62
+ hotkeys.bind('mod+shift+space', summonCommandPalette)
63
+
64
+ // Keyup using " up" suffix
65
+ hotkeys.bind('ctrl+p up', () => {
66
+ console.log('Released CTRL+P')
67
+ })
68
+
69
+ // AHK-style modifiers also supported
70
+ hotkeys.bind('^k', () => {
71
+ openCommandPalette() // ctrl+k
72
+ })
73
+
74
+ // Bare-modifier bindings (Alt-as-mode UX)
75
+ hotkeys.bind('alt', enterSelectMode) // fires on Alt keydown
76
+ hotkeys.bind('alt up', exitSelectMode) // fires on Alt keyup
77
+
78
+ // Layout-stable matching via KeyboardEvent.code (cross-platform Alt+letter,
79
+ // works on macOS where Option remaps Alt+X to ≈)
80
+ hotkeys.bind('alt+code:KeyX', deleteHovered, null, { preventDefault: true })
81
+
82
+ // Plugin grouping
83
+ hotkeys.registerPlugin('docs', {
84
+ 'ctrl+f': openSearch,
85
+ 'escape': closeSearch,
86
+ })
87
+ ```
88
+
89
+ ---
90
+
91
+ ## API
92
+
93
+ ### `bind(hotkey, handler, plugin?, options?)`
94
+
95
+ Register a hotkey. Returns an `off()` function.
96
+
97
+ ```js
98
+ const off = hotkeys.bind('mod+k', openPalette)
99
+
100
+ // Later
101
+ off()
102
+ ```
103
+
104
+ **Options**
105
+
106
+ ```ts
107
+ {
108
+ preventDefault?: boolean
109
+ stopPropagation?: boolean
110
+ stopImmediatePropagation?: boolean
111
+ repeat?: boolean // default false on keydown
112
+ once?: boolean
113
+ when?: (event) => boolean
114
+ allowIn?: (event) => boolean
115
+ priority?: number // default 0
116
+ warnOnReserved?: boolean // only read when conflict warnings are installed
117
+ capture?: boolean // v0.3.0+: run in the capture phase, before the page's listeners
118
+ altGraph?: boolean // v0.3.0+: also fire on an AltGr keystroke that types a character
119
+ composing?: boolean // v0.3.0+: also fire during IME composition
120
+ }
121
+ ```
122
+
123
+ By default (v0.3.0+), a binding is skipped when the keystroke is AltGr typing
124
+ a character (Windows reports AltGr as Ctrl+Alt, so `ctrl+alt+code:Comma`
125
+ would otherwise swallow the `<` a Polish or Czech user typed) and while an
126
+ IME is composing.
127
+
128
+ **Examples**
129
+
130
+ Ignore repeat keydown (default behavior):
131
+
132
+ ```js
133
+ hotkeys.bind('j', nextItem)
134
+ ```
135
+
136
+ Allow inside inputs:
137
+
138
+ ```js
139
+ hotkeys.bind('mod+k', openPalette, null, {
140
+ allowIn: () => true,
141
+ preventDefault: true,
142
+ })
143
+ ```
144
+
145
+ Conditional binding:
146
+
147
+ ```js
148
+ hotkeys.bind('delete', deleteItem, null, {
149
+ when: () => selectionCount() > 0,
150
+ })
151
+ ```
152
+
153
+ Run once:
154
+
155
+ ```js
156
+ hotkeys.bind('ctrl+s', saveDraft, null, { once: true })
157
+ ```
158
+
159
+ ### `unbind(hotkey, handler?)`
160
+
161
+ Remove bindings.
162
+
163
+ ```js
164
+ hotkeys.unbind('ctrl+k')
165
+ hotkeys.unbind('ctrl+k', openPalette)
166
+ ```
167
+
168
+ ### `registerPlugin(name, map)`
169
+
170
+ Batch register hotkeys under a plugin namespace.
171
+
172
+ ```js
173
+ const unregister = hotkeys.registerPlugin('files', {
174
+ 'mod+o': openFile,
175
+ 'delete': deleteFile,
176
+ })
177
+
178
+ // Later
179
+ unregister()
180
+ ```
181
+
182
+ Plugin cleanup is isolated. Removing one plugin never affects other bindings.
183
+
184
+ ### `unregisterPlugin(name)`
185
+
186
+ Remove all hotkeys associated with a plugin.
187
+
188
+ ### `onBind(hook)`
189
+
190
+ Subscribe to bind events. The hook receives `{ combo, raw, options, plugin, id }` after every successful `bind()`. Returns an unsubscribe function. Used internally by `installReservationWarnings`; exposed for telemetry, dev panels, and custom validation.
191
+
192
+ ```js
193
+ const off = hotkeys.onBind(({ raw }) => {
194
+ console.debug('bound:', raw)
195
+ })
196
+ // off() unsubscribes.
197
+ ```
198
+
199
+ Hook errors are caught and logged via `console.error`. A buggy hook can't break the bind.
200
+
201
+ ### `pause()` / `resume()`
202
+
203
+ Temporarily disable or re-enable all routing.
204
+
205
+ ### `ignoreInput(boolean = true)`
206
+
207
+ By default, hotkeys do **not** fire inside:
208
+
209
+ - `<input>`
210
+ - `<textarea>`
211
+ - `<select>`
212
+ - `[contenteditable]`
213
+ - `role="textbox"`
214
+
215
+ Override per-binding with `allowIn()`.
216
+
217
+ ### `init(options?)`
218
+
219
+ Manually attach listeners.
220
+
221
+ ```js
222
+ hotkeys.init({
223
+ target: window,
224
+ capture: false,
225
+ })
226
+ ```
227
+
228
+ Auto-initializes on `window` by default (browser environments).
229
+
230
+ With `capture: false` (the default), bindings run in the bubble phase except
231
+ those bound with `{ capture: true }`, which a second, capture-phase listener
232
+ handles (v0.3.0+). `capture: true` here runs every binding in the capture
233
+ phase.
234
+
235
+ ### `parseHotkey(hotkey)` / `comboFromEvent(event, options?)` (v0.3.0+)
236
+
237
+ Named exports (also on the default object). `comboFromEvent` turns a
238
+ keyboard event into a hotkey string for a "press your keys" recorder:
239
+ physical by default, `{ useMod: true }` writes the platform's primary
240
+ modifier as `mod`, and it returns `null` while only a modifier is held.
241
+
242
+ ```js
243
+ import { comboFromEvent } from 'hotkey-router'
244
+
245
+ input.addEventListener('keydown', (e) => {
246
+ const combo = comboFromEvent(e, { useMod: true }) // 'mod+shift+code:Period'
247
+ if (combo) save(combo)
248
+ })
249
+ ```
250
+
251
+ ### `destroy()`
252
+
253
+ Removes all listeners and clears internal state.
254
+
255
+ ### `trigger(hotkey, options?)`
256
+
257
+ Programmatically trigger a hotkey. Useful for testing.
258
+
259
+ ```js
260
+ hotkeys.trigger('ctrl+k')
261
+ ```
262
+
263
+ Returns `true` if a handler ran.
264
+
265
+ ---
266
+
267
+ ## Notes
268
+
269
+ ### Routing model
270
+
271
+ When multiple handlers match the same hotkey:
272
+
273
+ 1. Highest `priority` wins.
274
+ 2. If equal priority, newest binding wins.
275
+
276
+ This makes modal overrides simple:
277
+
278
+ ```js
279
+ hotkeys.bind('escape', closeModal, null, {
280
+ priority: 100,
281
+ preventDefault: true,
282
+ })
283
+ ```
284
+
285
+ ### Bare-modifier bindings (v0.1.0+)
286
+
287
+ Some UX patterns are driven by a bare modifier rather than a chord. For example, "hold Alt to enter select mode, release Alt to exit."
288
+
289
+ ```js
290
+ hotkeys.bind('alt', onAltDown) // fires on Alt keydown
291
+ hotkeys.bind('alt up', onAltUp) // fires on Alt keyup
292
+ hotkeys.bind('ctrl', onCtrlDown) // any single modifier supported
293
+ ```
294
+
295
+ - Only **single** bare modifiers are supported. Multi-modifier bare bindings (`'ctrl+alt'`) throw, add a base key for those.
296
+ - Default `repeat: false` applies, so a held modifier fires only once on keydown.
297
+ - Loose match: a bare-Alt binding fires whenever the Alt key is the one being pressed/released, regardless of which other modifier flags are also set. Add a `when` filter for exact-set semantics.
298
+
299
+ ### Code-based matching (v0.1.0+)
300
+
301
+ `KeyboardEvent.key` is layout- and modifier-dependent. Alt+X gives `≈` on macOS, `x` on Linux/Windows. For shortcuts that should be stable across platforms, bind to `KeyboardEvent.code` instead:
302
+
303
+ ```js
304
+ hotkeys.bind('alt+code:KeyX', deleteHovered) // matches the physical X key
305
+ hotkeys.bind('ctrl+code:Digit1', goToTab1) // matches digit row, not numpad
306
+ hotkeys.bind('!code:KeyX', deleteHovered) // AHK shorthand also works
307
+ ```
308
+
309
+ The `code:` value is **case-sensitive** (matches the camelCase `KeyboardEvent.code` spec values: `KeyA`, `Digit1`, `ArrowLeft`, etc.). Only one `code:` token per binding is allowed; multiple `code:` tokens throw a parse error. Both key-based and code-based bindings can coexist; the standard priority + recency rules pick the winner.
310
+
311
+ ### Conflict warnings (v0.2.0+)
312
+
313
+ Some combos are reserved by the browser chrome (find bar, devtools, bookmarks) or the OS (Spotlight, window management). They never reach page-world JavaScript, no matter how early you listen or whether you call `preventDefault`. hotkey-router ships an **opt-in** reservation table that emits a soft warning at bind time, so the silent failure becomes a noisy one.
314
+
315
+ The feature is opt-in by design: the core router stays ~3 KB gzipped, and the ~5 KB reservation data is tree-shaken out entirely unless you import it.
316
+
317
+ **Two ways to opt in.** One-line ergonomic, use the `auto` entry. Same default export as `hotkey-router`, with warnings pre-installed:
318
+
319
+ ```js
320
+ import hotkeys from 'hotkey-router/auto'
321
+
322
+ hotkeys.bind('meta+shift+f', toggleFullscreen)
323
+ // Firefox on macOS:
324
+ // [hotkey-router] "meta+shift+f" reserved by firefox on macOS:
325
+ // "Toggle fullscreen" [hard], will not fire.
326
+ ```
327
+
328
+ Explicit install, keep using the tiny core, install warnings yourself:
329
+
330
+ ```js
331
+ import hotkeys from 'hotkey-router'
332
+ import { installReservationWarnings } from 'hotkey-router/reservations'
333
+
334
+ installReservationWarnings(hotkeys)
335
+ hotkeys.bind('meta+shift+f', toggleFullscreen)
336
+ ```
337
+
338
+ `installReservationWarnings()` returns an `uninstall` function if you ever need to detach. The warning is **never fatal**, the binding is still registered, in case you're running in a browser/platform where the conflict doesn't apply.
339
+
340
+ **Severity to log level:**
341
+
342
+ | Severity | Log level | Meaning |
343
+ | ----------------- | --------- | ------------------------------------------------------- |
344
+ | `hard` | `warn` | Browser intercepts before page world; combo won't fire. |
345
+ | `os` | `warn` | OS intercepts globally. |
346
+ | `menu-activation` | `warn` | Alt+letter activates the browser menu bar (Win/Linux). |
347
+ | `find-bar-only` | `info` | Reserved only when the find bar is focused. |
348
+ | `compose` | `info` | macOS Option+letter types a special char in inputs. |
349
+ | `system-text` | `info` | Mac Ctrl+letter cursor controls inside text inputs. |
350
+ | `devtools-open` | `info` | Only relevant when DevTools is already open. |
351
+
352
+ **Per-bind opt-out:**
353
+
354
+ ```js
355
+ hotkeys.bind('meta+shift+f', toggleFullscreen, null, { warnOnReserved: false })
356
+ ```
357
+
358
+ To turn warnings off globally, just don't install them (use the bare `hotkey-router` entry instead of `hotkey-router/auto`).
359
+
360
+ **Force a platform/browser (tests, SSR previews):**
361
+
362
+ ```js
363
+ installReservationWarnings(hotkeys, { platform: 'mac', browser: 'firefox' })
364
+ ```
365
+
366
+ Accepted platforms: `'mac' | 'windows' | 'linux'`. Browsers: `'firefox' | 'chrome' | 'safari' | 'edge'`.
367
+
368
+ **Caveats:**
369
+
370
+ - Reservations reflect **default** keybindings. Users with custom shortcuts (Edge 95+ rebinds, Firefox add-ons, OS-level customization) may not match.
371
+ - KDE/XFCE desktop reservations beyond GNOME are not yet catalogued. Linux coverage is conservative.
372
+ - Layout-specific differences (Dvorak, AZERTY) change which physical key produces `event.key === 'f'`. For layout-stable bindings against the physical key, use `code:KeyX` syntax. The reservation lookup normalizes both.
373
+ - macOS menu-bar shortcuts that every app gets from the system (Cmd+Shift+/ for Help menu search, Cmd+H, Cmd+Option+H, Cmd+M, Cmd+Q, Cmd+`) are listed under the mac `system` table. Punctuation matches whether you bind it by code (`mod+shift+code:Slash`) or by key (`mod+shift+/`); a shifted character such as `?` depends on the layout, so bind the physical key.
374
+
375
+ **Programmatic lookup.** If you want to query the table yourself (e.g. building a cheatsheet that flags conflicts):
376
+
377
+ ```js
378
+ import { lookupReservation } from 'hotkey-router/reservations'
379
+
380
+ const r = lookupReservation(
381
+ { meta: true, shift: true, key: 'f' },
382
+ { platform: 'mac', browser: 'firefox' }
383
+ )
384
+ // → { source: 'browser', action: 'Toggle fullscreen', severity: 'hard', ... }
385
+ ```
386
+
387
+ **Extension hook (`onBind`).** Reservation warnings are built on a public `onBind` hook, useful for telemetry, dev panels, or any cross-cutting concern that needs to observe every binding:
388
+
389
+ ```js
390
+ const off = hotkeys.onBind(({ combo, raw, options, plugin, id }) => {
391
+ // combo: parsed combo { ctrl, meta, alt, shift, key, code, bareModifier }
392
+ // raw: original hotkey string
393
+ })
394
+ // off() unsubscribes.
395
+ ```
396
+
397
+ ### Website shortcuts (v0.3.0+)
398
+
399
+ Apps that run on other people's pages (browser extensions, embedded widgets)
400
+ collide with the page's own shortcuts: Google Docs uses Ctrl+Shift+. for font
401
+ size, GitHub for "quote". Unlike browser keys, those reach the page, so the
402
+ app can choose. `hotkey-router/sites` knows which popular sites use which
403
+ chords in the Ctrl/Cmd+Shift, Ctrl/Cmd+Alt, Shift+Alt and Ctrl/Cmd+Alt+Shift
404
+ families ([docs/site-hotkeys.md](docs/site-hotkeys.md), sourced data in
405
+ `data/site-hotkeys.json`) and builds a `when()` gate that yields to the site
406
+ unless the user is focused on the app:
407
+
408
+ ```js
409
+ import hotkeys from 'hotkey-router'
410
+ import { siteAware } from 'hotkey-router/sites'
411
+
412
+ hotkeys.bind('mod+shift+code:Period', nextTypo, null, {
413
+ capture: true, // see the key before the page's editor
414
+ preventDefault: true,
415
+ stopPropagation: true, // when we take it, the page doesn't run it too
416
+ allowIn: () => true,
417
+ when: siteAware('mod+shift+code:Period', {
418
+ engaged: () => popupIsOpen() || panelHasFocus(),
419
+ }),
420
+ })
421
+ ```
422
+
423
+ On sites that don't use the chord the gate is always true. On sites that do
424
+ (Docs, Slides, Confluence, GitHub, WordPress ...), it returns `engaged()`;
425
+ when that is false, the router leaves the event untouched and the site's
426
+ shortcut runs.
427
+
428
+ Also exported: `lookupSiteConflicts(combo, { url, platform, verifiedOnly })`,
429
+ `matchSites(url)`, `siteLookupKey(combo, platform)`, `detectSitePlatform()`
430
+ and `listSites()`. Platforms: `windows` (also used for Linux), `mac`,
431
+ `chromeos`. The runtime table is ~7 KB gzipped and imports nothing from the
432
+ core, so it never creates a second router.
433
+
434
+ ### Validating a recorded combo (v0.3.0+)
435
+
436
+ For a "press your keys" setting: record with `comboFromEvent`, then check
437
+ with `hotkey-router/validate` before saving. Reasons come in plain language,
438
+ ready to show.
439
+
440
+ ```js
441
+ import { comboFromEvent } from 'hotkey-router'
442
+ import { validateCombo } from 'hotkey-router/validate'
443
+
444
+ field.addEventListener('keydown', (e) => {
445
+ e.preventDefault()
446
+ const combo = comboFromEvent(e, { useMod: true })
447
+ if (!combo) return // still holding modifiers
448
+ const { ok, reasons } = validateCombo(combo, {
449
+ requirePrimary: true, // must include Ctrl (Cmd on macOS)
450
+ minModifiers: 2,
451
+ taken: ['mod+shift+code:Space'],
452
+ })
453
+ show(reasons.map((r) => r.message))
454
+ if (ok) save(combo)
455
+ })
456
+ ```
457
+
458
+ Errors (`ok: false`): no key, no modifier, Alt as the only modifier on
459
+ Windows/Linux, a rule you asked for (`requirePrimary`, `minModifiers`),
460
+ already in `taken`, or reserved by a browser/OS (never reaches the page).
461
+ Warnings (`ok: true`): reserved only in some situations, Ctrl+Alt acting as
462
+ AltGr on some Windows layouts, and sites that use the same keys.
463
+
464
+ ### Supported syntax
465
+
466
+ **Standard:**
467
+
468
+ - `ctrl+k`
469
+ - `shift+a`
470
+ - `ctrl+k up`
471
+ - `mod+s` (meta on macOS, ctrl elsewhere)
472
+ - `ctrl++` or `ctrl+plus`
473
+
474
+ **AHK-style prefix modifiers:**
475
+
476
+ - `^k` → `ctrl+k`
477
+ - `!k` → `alt+k`
478
+ - `+k` → `shift+k`
479
+ - `#k` → `meta+k`
480
+ - `^!k` → `ctrl+alt+k`
481
+
482
+ Modifiers must appear before the base key.
483
+
484
+ **Modifier aliases:**
485
+
486
+ - `ctrl`, `control`, `⌃`
487
+ - `shift`, `⇧`, `+`
488
+ - `alt`, `option`, `⌥`, `!`
489
+ - `meta`, `cmd`, `command`, `win`, `⌘`, `#`
490
+ - `mod` (meta on macOS, ctrl elsewhere)
491
+
492
+ **Navigation / special key aliases:**
493
+
494
+ - `escape`, `esc`
495
+ - `enter`, `return`
496
+ - `space`, `spacebar`
497
+ - `tab`
498
+ - `backspace`
499
+ - `delete`, `del`
500
+ - `home`, `end`
501
+ - `pageup`, `pgup`
502
+ - `pagedown`, `pgdn`
503
+ - `up`, `down`, `left`, `right`
504
+ - `f1`–`f19`
505
+
506
+ Keys are case-insensitive.
507
+
508
+ ### Philosophy
509
+
510
+ hotkey-router follows three core rules:
511
+
512
+ 1. **Predictable routing.** Highest priority wins. Ties go to the most recently bound handler.
513
+ 2. **Safe composition.** Plugins can register and unregister without affecting others.
514
+ 3. **Modern only.** Built for modern browsers using `KeyboardEvent.key`.
515
+
516
+ No keycodes. No legacy IE hacks. No hidden global scope state.
517
+
518
+ ### What this is not
519
+
520
+ - Not a keycode polyfill
521
+ - Not a legacy browser shim
522
+ - Not a global scope manager
523
+ - Not a VSCode-style sequence engine
524
+
525
+ This is a small, deterministic routing layer for modern applications.
526
+
527
+ ### Browser support
528
+
529
+ Modern browsers supporting:
530
+
531
+ - `KeyboardEvent.key`
532
+ - `Map`
533
+ - `addEventListener`
534
+
535
+ Chrome, Firefox, Safari, Edge.
536
+
537
+ ---
538
+
539
+ ## License
540
+
541
+ Licensed under AGPL-3.0 with WATT3D Additional Terms. See [LICENSE](./LICENSE) and [ADDITIONAL_TERMS.md](./ADDITIONAL_TERMS.md). Commercial AI/model-training use requires compliance with those terms or a separate WATT3D license. © WATT3D.