hotkey-router 0.5.1 → 0.6.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 (42) hide show
  1. package/README.md +292 -670
  2. package/data/browser-hotkeys.json +40 -0
  3. package/data/site-hotkeys.json +1 -1
  4. package/data/site-hotkeys.runtime.json +1 -1
  5. package/dist/auto.js +3 -3
  6. package/dist/auto.js.map +2 -2
  7. package/dist/auto.min.js +2 -2
  8. package/dist/core.js +55 -324
  9. package/dist/core.js.map +3 -3
  10. package/dist/dev.js +56 -0
  11. package/dist/dev.js.map +7 -0
  12. package/dist/format.js +13 -178
  13. package/dist/format.js.map +3 -3
  14. package/dist/hotkey-router.cjs +69 -165
  15. package/dist/hotkey-router.cjs.map +3 -3
  16. package/dist/hotkey-router.js +1 -1
  17. package/dist/hotkey-router.js.map +2 -2
  18. package/dist/hotkey-router.min.js +2 -2
  19. package/dist/lookup.js +9 -0
  20. package/dist/lookup.js.map +7 -0
  21. package/dist/parse.js +207 -0
  22. package/dist/parse.js.map +7 -0
  23. package/dist/platform.js +42 -0
  24. package/dist/platform.js.map +7 -0
  25. package/dist/reservations.js +17 -533
  26. package/dist/reservations.js.map +3 -3
  27. package/dist/shifted-punctuation.js +34 -0
  28. package/dist/shifted-punctuation.js.map +7 -0
  29. package/dist/sites.js +4 -203
  30. package/dist/sites.js.map +3 -3
  31. package/dist/testing.js +104 -0
  32. package/dist/testing.js.map +7 -0
  33. package/dist/types/core.d.ts +3 -9
  34. package/dist/types/dev.d.ts +48 -0
  35. package/dist/types/lookup.d.ts +1 -0
  36. package/dist/types/parse.d.ts +0 -13
  37. package/dist/types/reservations.d.ts +14 -41
  38. package/dist/types/shifted-punctuation.d.ts +17 -0
  39. package/dist/types/testing.d.ts +17 -0
  40. package/dist/validate.js +11 -191
  41. package/dist/validate.js.map +3 -3
  42. package/package.json +9 -1
package/README.md CHANGED
@@ -1,43 +1,67 @@
1
1
  # hotkey-router
2
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); see [Who gets a key](#who-gets-a-key)
17
- - Separate and scoped routers: per library, dialog, shadow root or iframe (`createRouter`)
18
- - Input-safe by default, with an opt-in mode that lets chords through on checkboxes, sliders and buttons
19
- - Works on any keyboard layout: physical-key `code:` bindings, and Ctrl/Cmd shortcuts on non-Latin layouts
20
- - AltGr and IME aware: no shortcut fires while typing a character
21
- - Testable via `trigger()`
22
- - Optional opt-in browser/OS conflict warnings and website-shortcut awareness (tree-shakable)
23
- - Display helpers: `Ctrl+Shift+.` / `⇧⌘.` and accessible keycaps (`hotkey-router/format`)
24
- - ~4.9 kB minified + gzipped (core); ~9.5 kB with conflict warnings
25
- - Zero dependencies
26
-
27
- ---
3
+ [![npm](https://badgen.net/npm/v/hotkey-router)](https://www.npmjs.com/package/hotkey-router)
4
+ [![types](https://badgen.net/npm/types/hotkey-router)](https://www.npmjs.com/package/hotkey-router)
5
+ [![license](https://badgen.net/static/license/AGPL-3.0%20%2B%20terms/blue)](https://github.com/iWhatty/hotkey-router/blob/main/LICENSE)
28
6
 
29
- ## Install
7
+ A small, deterministic keyboard-shortcut router for modern web apps: named groups of bindings, one predictable
8
+ winner per key.
9
+
10
+ ## First five minutes
30
11
 
31
12
  ```sh
32
13
  npm install hotkey-router
33
14
  ```
34
15
 
35
- (or `pnpm add hotkey-router`, `yarn add hotkey-router`)
16
+ ```js
17
+ import hotkeys from 'hotkey-router' // starts listening on window
18
+
19
+ // `mod` is Cmd on macOS, Ctrl elsewhere
20
+ const off = hotkeys.bind('mod+shift+space', openPalette)
21
+
22
+ // A plugin is a named group of bindings that you remove together
23
+ hotkeys.registerPlugin('search', {
24
+ '/': openSearch,
25
+ 'escape': [closeSearch, { allowIn: () => true }], // also from inside the search field
26
+ })
27
+
28
+ off() // remove one binding
29
+ hotkeys.unregisterPlugin('search') // remove the group
30
+ ```
31
+
32
+ By default no binding fires while the user types in a field, chords included; `allowIn` opts one in (see
33
+ [`ignoreInput`](#ignoreinputvalue)).
34
+ During development, import `hotkey-router/auto` to enable warnings on the same router for reserved keys
35
+ and shifted-punctuation bindings.
36
+
37
+ ## Why this library
38
+
39
+ - **`code:` bindings** match the physical key (`alt+code:KeyX`), whatever the layout or macOS Option types.
40
+ - **Non-Latin layouts:** `ctrl+k` still fires for Ctrl+K on a Russian, Greek or Hebrew layout, as browser
41
+ shortcuts do.
42
+ - **AltGr and IME guards**, on by default: nothing fires while the user types `<` with AltGr or composes CJK
43
+ text.
44
+ - **Input handling:** nothing fires from text fields by default; `'text'` mode lets chords through on
45
+ checkboxes, sliders and buttons; `allowIn` overrides per binding.
46
+ - **One winner per key:** highest priority, then the most recent binding.
47
+ - **Several routers:** one per library on a shared page, or scoped to a dialog, shadow root or iframe.
48
+ - **Opt-in data:** which keys the browser and OS take, and which a page can win with `preventDefault` (Windows
49
+ rows checked with real key presses); which keys popular websites use.
50
+ - **`validateCombo`** for "press your keys" settings, with reasons ready to show.
51
+ - Zero dependencies. Core ~9.7 KB minified and ~4.1 KB gzipped. The data lives in separate entries.
52
+
53
+ It doesn't do key sequences (`g i`, `ctrl+k ctrl+s`), and it targets current browsers only.
54
+
55
+ ## Install
56
+
57
+ ```sh
58
+ npm install hotkey-router # or: pnpm add hotkey-router / yarn add hotkey-router
59
+ ```
36
60
 
37
61
  ESM:
38
62
 
39
63
  ```js
40
- import hotkeys from 'hotkey-router'
64
+ import hotkeys, { createRouter } from 'hotkey-router'
41
65
  ```
42
66
 
43
67
  CommonJS (the router is the `default` export):
@@ -47,18 +71,20 @@ const hotkeys = require('hotkey-router').default
47
71
  const { createRouter } = require('hotkey-router')
48
72
  ```
49
73
 
50
- Only the main entry has a CommonJS build. The subpaths (`/core`, `/auto`,
51
- `/reservations`, `/sites`, `/validate`, `/format`) are ESM only, so load them
52
- with `import` (or `await import()` from CommonJS).
74
+ Only the main entry has a CommonJS build. The subpaths (`/core`, `/auto`, `/reservations`, `/sites`,
75
+ `/validate`, `/format`) are ESM only; load them with `import`, or `await import()` from CommonJS.
53
76
 
54
77
  CDN (ESM), pinned to a version:
55
78
 
56
79
  ```js
57
- import hotkeys from 'https://cdn.jsdelivr.net/npm/hotkey-router@0.5.1/dist/hotkey-router.min.js'
80
+ import hotkeys from 'https://cdn.jsdelivr.net/npm/hotkey-router@0.6.0/dist/hotkey-router.min.js'
58
81
  ```
59
82
 
60
- Nothing at import (v0.4.0+): `hotkey-router/core` has `createRouter` and the
61
- helpers, but no ready router and no listeners until you start one.
83
+ `dist/auto.min.js` at the same path is the router with reservation warnings. It is a standalone build with its
84
+ own router, so don't load both.
85
+
86
+ Importing `hotkey-router` starts the default router on `window`. `hotkey-router/core` does nothing at import:
87
+ `createRouter` and the helpers, no router and no listeners until you start one.
62
88
 
63
89
  ```js
64
90
  import { createRouter } from 'hotkey-router/core'
@@ -67,757 +93,353 @@ const keys = createRouter()
67
93
  keys.init() // when your app is ready
68
94
  ```
69
95
 
70
- ---
96
+ ## Hotkey syntax
71
97
 
72
- ## Quick start
98
+ A hotkey is a string: modifiers, then one key, joined by `+`, with an optional ` up` suffix for keyup (keydown
99
+ by default). The router parses it into a combo; a binding is a combo plus its handler and options.
73
100
 
74
- ```js
75
- import hotkeys from 'hotkey-router'
101
+ | Hotkey | Meaning |
102
+ | --- | --- |
103
+ | `ctrl+alt+x`, `shift+a` | Modifiers before the key; `k+ctrl` and `ctrl+a+b` throw. |
104
+ | `mod+shift+space` | `mod` is Cmd (meta) on macOS, Ctrl elsewhere, decided when the hotkey is parsed. |
105
+ | `ctrl+alt+x up` | Fires on keyup. |
106
+ | `^k` `!k` `+k` `#k` `^!k` | AutoHotkey prefixes: Ctrl, Alt, Shift, Meta, Ctrl+Alt. On its own, `+`, `!`, `#` or `^` is that key. |
107
+ | `ctrl++`, `ctrl+plus` | The `+` key. |
108
+ | `?`, `!`, `ctrl+?` | A character typed with Shift: fires while Shift is held to type it. An exact `shift+?` binding wins. |
109
+ | `alt+code:KeyX`, `!code:KeyX` | A `code:` binding: the physical key, by `KeyboardEvent.code`. |
110
+ | `alt`, `alt up` | A bare modifier: fires when Alt itself goes down or up. |
76
111
 
77
- // Simple keydown. `mod` is Cmd on macOS, Ctrl elsewhere.
78
- hotkeys.bind('mod+shift+space', () => {
79
- openCommandPalette()
80
- })
112
+ - **Modifiers:** `ctrl` `control` `⌃`; `shift` `⇧`; `alt` `option` `opt` `⌥`; `meta` `cmd` `command` `win`
113
+ `⌘`; `mod`.
114
+ - **Keys:** `escape`/`esc`, `enter`/`return`, `space`/`spacebar`, `tab`, `backspace`, `delete`/`del`, `home`,
115
+ `end`, `pageup`/`pgup`, `pagedown`/`pgdn`, `up` `down` `left` `right`, `f1`…`f19`; any other key by its
116
+ `KeyboardEvent.key` (`/`, `[`, `a`).
117
+ - Names and keys are case-insensitive. The `code:` value is case-sensitive, as in the spec (`KeyA`, `Digit1`,
118
+ `ArrowLeft`, `Period`), and a hotkey has one `code:` token at most. A key-based and a `code:` binding for
119
+ the same keys can coexist; priority and recency pick the winner.
120
+ - **Bare modifiers:** one only (`ctrl+alt` throws; add a key). A held modifier fires once. The match is loose:
121
+ `alt` fires whenever Alt goes down or up, whatever else is held; add a `when` check for an exact set.
81
122
 
82
- // Keyup using " up" suffix
83
- hotkeys.bind('mod+shift+x up', () => {
84
- console.log('Released Ctrl+Shift+X')
85
- })
86
-
87
- // AHK-style modifiers also supported
88
- hotkeys.bind('^!k', () => {
89
- openCommandPalette() // ctrl+alt+k
90
- })
91
-
92
- // Bare-modifier bindings (Alt-as-mode UX)
93
- hotkeys.bind('alt', enterSelectMode) // fires on Alt keydown
94
- hotkeys.bind('alt up', exitSelectMode) // fires on Alt keyup
95
-
96
- // Layout-stable matching via KeyboardEvent.code (cross-platform Alt+letter,
97
- // works on macOS where Option remaps Alt+X to ≈)
98
- hotkeys.bind('alt+code:KeyX', deleteHovered, null, { preventDefault: true })
99
-
100
- // Plugin grouping. Plain keys don't fire while the user types in a field.
101
- hotkeys.registerPlugin('docs', {
102
- '/': openSearch,
103
- 'escape': closeSearch,
104
- })
105
- ```
106
-
107
- Browsers and the OS keep some shortcuts for themselves. A page never gets
108
- some of them (Ctrl+T, Ctrl+W, Cmd+Q). Others, like Ctrl+K, Ctrl+F or Ctrl+S on
109
- Windows, reach the page first, but the browser acts on them too unless the
110
- binding sets `preventDefault: true`. The examples above use keys that are free
111
- in every major browser. Before picking your own, see
112
- [Who gets a key](#who-gets-a-key). `hotkey-router/auto` warns in the console
113
- when you bind a reserved one.
114
-
115
- ---
123
+ ## Core API
116
124
 
117
- ## API
125
+ The default export is a router; `createRouter()` makes more with the same methods.
118
126
 
119
127
  ### `bind(hotkey, handler, plugin?, options?)`
120
128
 
121
- Register a hotkey. Returns an `off()` function.
129
+ Adds a binding and returns `off()`, which removes it (and has `off.id` and `off.hotkey`). `plugin` is a label
130
+ that `onBind` hooks receive, or `null`; `unregisterPlugin` only removes bindings made by `registerPlugin`.
122
131
 
123
132
  ```js
124
133
  // preventDefault: on Windows and Linux the browser also uses Ctrl+K (search)
125
- const off = hotkeys.bind('mod+k', openPalette, null, { preventDefault: true })
134
+ hotkeys.bind('mod+k', openPalette, null, { preventDefault: true, allowIn: () => true })
126
135
 
127
- // Later
128
- off()
129
- ```
130
-
131
- **Options**
132
-
133
- ```ts
134
- {
135
- preventDefault?: boolean
136
- stopPropagation?: boolean
137
- stopImmediatePropagation?: boolean
138
- repeat?: boolean // default false on keydown
139
- once?: boolean
140
- when?: (event) => boolean
141
- allowIn?: (event) => boolean
142
- priority?: number // default 0
143
- warnOnReserved?: boolean // only read when conflict warnings are installed
144
- capture?: boolean // v0.3.0+: run in the capture phase, before the page's listeners
145
- altGraph?: boolean // v0.3.0+: also fire on an AltGr keystroke that types a character
146
- composing?: boolean // v0.3.0+: also fire during IME composition
147
- }
148
- ```
149
-
150
- By default (v0.3.0+), a binding is skipped when the keystroke is AltGr typing
151
- a character (Windows reports AltGr as Ctrl+Alt, so `ctrl+alt+code:Comma`
152
- would otherwise swallow the `<` a Polish or Czech user typed) and while an
153
- IME is composing.
154
-
155
- `when` and `allowIn` receive the `KeyboardEvent`, not an element. To check
156
- where the key was typed, read `event.composedPath()[0]` (the element inside an
157
- open shadow root) or `event.target`.
158
-
159
- **Shifted punctuation.** With Shift held, `event.key` is the shifted
160
- character, so a key-based `ctrl+shift+,` waits for a `,` that a US keyboard
161
- reports as `<`, and never fires. Bind the physical key instead:
162
- `ctrl+shift+code:Comma`. Since v0.3.3, `bind()` warns once in the console for
163
- Shift with `` , . / ; ' [ ] \ - = ` ``, and `validateCombo` rejects it with the
164
- reason `shifted-punctuation`.
165
-
166
- **Non-Latin layouts (v0.3.3+).** On a Russian layout Ctrl+K reports
167
- `event.key === 'л'` with `event.code === 'KeyK'`. Like the browser's own
168
- shortcuts, a key-based `ctrl+k` binding still fires there: when Ctrl or Cmd is
169
- held (Shift allowed, Alt not), the key types a letter from a non-Latin script
170
- (Cyrillic, Greek, Hebrew, Arabic, ...), and `code` is `KeyA`..`KeyZ`, the
171
- router also looks up the Latin letter for that key. It does this only when no
172
- exact binding is eligible, so a `ctrl+л` or `ctrl+code:KeyK` binding always
173
- wins over it. Plain and Shift-only letters (typing), Alt and AltGr chords, IME
174
- composition, digits and Latin layouts such as AZERTY are never affected. To
175
- require the exact character, gate the binding: `when: (e) => e.key === 'k'`.
176
-
177
- **Examples**
178
-
179
- Ignore repeat keydown (default behavior):
136
+ // preventDefault, or the browser's Save dialog opens too
137
+ hotkeys.bind('ctrl+s', saveDraft, null, { once: true, preventDefault: true })
180
138
 
181
- ```js
182
- hotkeys.bind('j', nextItem)
139
+ hotkeys.bind('delete', deleteItem, null, { when: () => selectionCount() > 0 })
183
140
  ```
184
141
 
185
- Allow inside inputs:
142
+ | Option | Default | What it does |
143
+ | --- | --- | --- |
144
+ | `preventDefault` | `false` | Call `event.preventDefault()` when this binding wins: keeps the browser's own action (and typing) out. |
145
+ | `stopPropagation` | `false` | Stop the event from reaching listeners further along. |
146
+ | `stopImmediatePropagation` | `false` | Also stop other listeners on the same target. |
147
+ | `repeat` | `false` (keydown) | Fire on auto-repeat while the key is held. |
148
+ | `once` | `false` | Remove the binding before calling its handler, so nested dispatch cannot run it again (even if the handler throws). |
149
+ | `when(event)` | — | Gate: the binding is skipped when it returns exactly `false`. |
150
+ | `allowIn(event)` | — | Return `true` to fire where the input check would block it. |
151
+ | `priority` | `0` | Higher wins; ties go to the most recent binding. |
152
+ | `capture` | `false` | Run in the capture phase, before the page's own listeners. |
153
+ | `altGraph` | `false` | Also fire on an AltGr keystroke that types a character. |
154
+ | `composing` | `false` | Also fire during IME composition. |
155
+ | `warnOnReserved` | `true` | `false` silences [reservation warnings](#reservation-warnings) for this binding. |
156
+
157
+ `when` and `allowIn` get the `KeyboardEvent`. To see where the key was typed, read `event.composedPath()[0]`
158
+ (the element inside an open shadow root) or `event.target`:
186
159
 
187
160
  ```js
188
- hotkeys.bind('mod+k', openPalette, null, {
189
- allowIn: () => true,
190
- preventDefault: true,
191
- })
192
-
193
- // Only in one field (the event, not the element, is passed in)
194
161
  hotkeys.bind('enter', submitFollowUp, null, {
195
162
  allowIn: (e) => e.composedPath()[0] === followUpInput,
196
163
  })
197
164
  ```
198
165
 
199
- Conditional binding:
200
-
201
- ```js
202
- hotkeys.bind('delete', deleteItem, null, {
203
- when: () => selectionCount() > 0,
204
- })
205
- ```
206
-
207
- Run once:
208
-
209
- ```js
210
- // preventDefault, or the browser's Save As dialog opens too
211
- hotkeys.bind('ctrl+s', saveDraft, null, { once: true, preventDefault: true })
212
- ```
213
-
214
166
  ### `unbind(hotkey, handler?)`
215
167
 
216
- Remove bindings.
217
-
218
- ```js
219
- hotkeys.unbind('ctrl+k')
220
- hotkeys.unbind('ctrl+k', openPalette)
221
- ```
222
-
223
- ### `registerPlugin(name, map)`
224
-
225
- Batch register hotkeys under a plugin namespace.
226
-
227
- ```js
228
- const unregister = hotkeys.registerPlugin('files', {
229
- 'mod+o': openFile,
230
- 'delete': deleteFile,
231
- })
232
-
233
- // Later
234
- unregister()
235
- ```
236
-
237
- Plugin cleanup is isolated. Removing one plugin never affects other bindings.
238
- If any key string fails to parse, `registerPlugin` throws and binds nothing
239
- (v0.3.3+).
240
-
241
- ### `unregisterPlugin(name)`
168
+ Removes the bindings for that hotkey and type (keydown or keyup), or only the ones with `handler`. A key-based
169
+ hotkey and its `code:` spelling are different bindings: `unbind('ctrl+k')` leaves `ctrl+code:KeyK`.
242
170
 
243
- Remove all hotkeys associated with a plugin.
171
+ ### `registerPlugin(name, map)` / `unregisterPlugin(name)`
244
172
 
245
- ### `onBind(hook)`
246
-
247
- 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.
173
+ A plugin is a named group of bindings. `registerPlugin` binds every entry of `map` (a handler, or `[handler,
174
+ options]`) under `name` and returns a function that unregisters it. Removing a plugin never touches other
175
+ bindings. If a hotkey in the map doesn't parse, it throws and binds nothing; a name that is already registered
176
+ throws too. The returned cleanup only removes its own registration, even if the name is reused.
248
177
 
249
178
  ```js
250
- const off = hotkeys.onBind(({ raw }) => {
251
- console.debug('bound:', raw)
179
+ const unregister = hotkeys.registerPlugin('editor', {
180
+ 'mod+shift+space': openPalette,
181
+ 'escape': [closeMenu, { priority: 10 }],
252
182
  })
253
- // off() unsubscribes.
254
183
  ```
255
184
 
256
- Hook errors are caught and logged via `console.error`. A buggy hook can't break the bind.
257
-
258
185
  ### `pause()` / `resume()`
259
186
 
260
- Temporarily disable or re-enable all routing.
261
-
262
- ### `ignoreInput(value = true)`
263
-
264
- `value` is `true` / `'all'` (the default, below), `'text'` (v0.4.0+, below)
265
- or `false` (no check). By default, hotkeys do **not** fire inside:
266
-
267
- - `<input>`
268
- - `<textarea>`
269
- - `<select>`
270
- - `[contenteditable]`
271
- - `role="textbox"`
187
+ Stop and restart all routing on this router. Bindings stay registered.
272
188
 
273
- This includes those elements inside an open shadow root (v0.3.3+; the router
274
- reads `event.composedPath()[0]`). A closed shadow root hides its inside from
275
- the page, so only its host element is checked there.
189
+ ### `ignoreInput(value)`
276
190
 
277
- Every `<input>` counts, whatever its `type` and whatever modifiers are held:
278
- a checkbox, radio, range slider, color or file input blocks `ctrl+k` as well
279
- as Space. A native `<button>` is **not** on the list, so a plain `space` or
280
- `enter` binding fires while a button has focus; gate such bindings with
281
- `when` if that matters.
282
-
283
- Override per-binding with `allowIn()`:
284
-
285
- ```js
286
- // Let the palette open from a focused checkbox or slider, but not from text fields
287
- hotkeys.bind('mod+k', openPalette, null, {
288
- allowIn: (e) => ['checkbox', 'radio', 'range'].includes(e.composedPath()[0].type),
289
- preventDefault: true,
290
- })
291
- ```
191
+ The input check. `true` or `'all'` (the default), `'text'`, or `false` (no check). By default no binding fires
192
+ when the key was typed in an `<input>` (any type), `<textarea>`, `<select>`, a contenteditable element or
193
+ `role="textbox"`, including inside an open shadow root (a closed one only shows its host). A native `<button>`
194
+ isn't on the list, so a plain `space` or `enter` binding fires while a button has focus; gate it with `when`
195
+ if that matters.
292
196
 
293
- **The `'text'` mode (v0.4.0+, opt-in).** For apps with forms and settings
294
- panels, `hotkeys.ignoreInput('text')` (or `createRouter({ ignoreInput:
295
- 'text' })`) blocks typing but not shortcuts:
197
+ `'text'` (also `createRouter({ ignoreInput: 'text' })`) is for apps with forms and settings panels: it blocks
198
+ typing, not shortcuts.
296
199
 
297
200
  | Where the key was typed | Plain and Shift-only keys | Chords with Ctrl, Alt or Meta |
298
201
  | --- | --- | --- |
299
202
  | Text entry: text-like and date/time `<input>` types (and any type not listed below), `<textarea>`, `<select>`, contenteditable, `role="textbox"` | blocked | blocked |
300
203
  | Other controls: checkbox, radio, range, color, file, button, submit, reset and image inputs; `<button>`; `role="button"`; any element inside a button | blocked (Space, Enter and arrows belong to the control) | **fire** |
301
204
 
302
- A chord needs a non-modifier key, so bare-modifier bindings (`alt`,
303
- `alt up`) stay blocked on controls. Where an element is both (an editable
304
- element inside a button), text entry wins. `allowIn` still overrides the
305
- input check, but not the AltGr, IME, repeat or `when` checks. The default
306
- stays `'all'`, so nothing changes unless you opt in.
205
+ A chord needs a non-modifier key, so bare-modifier bindings stay blocked on controls. An editable element
206
+ inside a button counts as text entry. `allowIn` overrides the input check, but not the AltGr, IME, repeat or
207
+ `when` checks.
307
208
 
308
- ### `createRouter(options?)` (v0.4.0+)
209
+ ### `init(options?)` / `destroy()`
309
210
 
310
- A separate router: its own bindings, plugins, `pause()`, `ignoreInput()`,
311
- `onBind` hooks and listeners, with the same methods as the default export.
312
- It attaches nothing until you call `init()`.
211
+ `init({ target, capture })` attaches the `keydown` and `keyup` listeners (default: the router's target, `window` for the default router). The
212
+ default router calls it at import in browsers; a router from `createRouter()` waits for you. Calling it again
213
+ calls `destroy()` first. `capture: true` runs every binding in the capture phase; by default only bindings
214
+ with `{ capture: true }` do. `destroy()` removes the listeners and clears all bindings and plugins; `onBind`
215
+ hooks survive it.
313
216
 
314
- ```js
315
- import { createRouter } from 'hotkey-router'
217
+ ### `dispatch(event, type)`
316
218
 
317
- const dialogKeys = createRouter({ target: dialogEl })
318
- dialogKeys.init()
319
- dialogKeys.bind('escape', closeDialog)
320
- // Later
321
- dialogKeys.destroy() // the page's other routers keep working
322
- ```
219
+ Routes a keyboard event directly through one router and returns `true` if a handler ran. Pass `'keydown'`
220
+ or `'keyup'` as `type`. This considers both capture and bubble bindings without going through the DOM.
221
+ For testing from a hotkey string, use `trigger(router, hotkey, options?)` from `hotkey-router/testing`.
222
+ See [docs/testing.md](https://github.com/iWhatty/hotkey-router/blob/main/docs/testing.md).
323
223
 
324
- Options: `target` (default `window` when there is one; an element, a
325
- `ShadowRoot` or an iframe's window scopes the router to keys from inside
326
- it), `capture` (default `false`) and `ignoreInput` (default `true`; also
327
- `'text'` or `false`, as for `ignoreInput()`).
328
- `target` and `capture` are defaults: `init({ target, capture })` overrides
329
- them for that call only. `setTarget(target)` changes the default target of an
330
- existing router, which is useful when other code holds on to it; it doesn't
331
- move listeners until the next `init()`. See [Multiple routers](#multiple-routers-v040).
224
+ ### `parseHotkey(hotkey, options?)`
332
225
 
333
- ### `init(options?)`
226
+ Import `parseHotkey` by name from `hotkey-router` or `hotkey-router/core`. Returns `{ combo, type, raw }`:
227
+ `combo` is `{ ctrl, shift, alt, meta, key, code, bareModifier
228
+ }`, `type` is `'keydown'` or `'keyup'`, `raw` the string you passed. Throws on a hotkey the router can't bind.
229
+ `{ platform }` resolves `mod` for another platform.
334
230
 
335
- Manually attach listeners.
231
+ ### `comboFromEvent(event, options?)`
336
232
 
337
- ```js
338
- hotkeys.init({
339
- target: window,
340
- capture: false,
341
- })
342
- ```
343
-
344
- Auto-initializes on `window` by default (browser environments): importing
345
- `hotkey-router` attaches `keydown` and `keyup` listeners to `window` straight
346
- away, and `hotkey-router/auto` also installs the reservation warnings. The
347
- package's `sideEffects` list names those files so bundlers keep that work;
348
- `/core` (v0.4.0+), `/reservations`, `/sites`, `/validate` and `/format` do
349
- nothing at import and tree-shake away when unused. `hotkey-router` is built
350
- on `hotkey-router/core`, so an app that imports both bundles one copy.
351
-
352
- With `capture: false` (the default), bindings run in the bubble phase except
353
- those bound with `{ capture: true }`, which a second, capture-phase listener
354
- handles (v0.3.0+). `capture: true` here runs every binding in the capture
355
- phase.
356
-
357
- ### `parseHotkey(hotkey, options?)` / `comboFromEvent(event, options?)` (v0.3.0+)
358
-
359
- Named exports (also on the default object). `parseHotkey` returns
360
- `{ combo, type, raw }`: `combo` is the parsed shape
361
- (`{ ctrl, meta, alt, shift, key, code, bareModifier }`) that `lookupReservation`
362
- takes, and `type` is `'keydown'` or `'keyup'`. `comboFromEvent` turns a
363
- keyboard event into a hotkey string for a "press your keys" recorder:
364
- physical by default, `{ useMod: true }` writes the platform's primary
365
- modifier as `mod`, and it returns `null` while only a modifier is held.
366
- Both take `{ platform }` (v0.3.2+) to resolve `mod` for a platform other
367
- than the one detected.
233
+ Import `comboFromEvent` by name from `hotkey-router` or `hotkey-router/core`. Turns a keyboard event into a
234
+ hotkey string for a "press your keys" recorder. Physical by
235
+ default (`ctrl+shift+code:Period`); `{ useMod: true }` writes the platform's primary modifier as `mod`; `{
236
+ physical: false }` uses `event.key`; `{ platform }` decides what `mod` stands for. Returns `null` while only a
237
+ modifier is held.
368
238
 
369
239
  ```js
370
240
  import { comboFromEvent } from 'hotkey-router'
371
241
 
372
- input.addEventListener('keydown', (e) => {
373
- const combo = comboFromEvent(e, { useMod: true }) // 'mod+shift+code:Period'
374
- if (combo) save(combo)
242
+ field.addEventListener('keydown', (e) => {
243
+ const hotkey = comboFromEvent(e, { useMod: true }) // 'mod+shift+code:Period'
244
+ if (hotkey) save(hotkey)
375
245
  })
376
246
  ```
377
247
 
378
- ### `detectPlatform(navigator?, { chromeos? })` (v0.3.2+)
248
+ ### `detectPlatform(navigator?, { chromeos? })`
379
249
 
380
- The one platform detector the router, reservations, sites, validate and
381
- format all use: `'mac'`, `'windows'`, `'linux'` or `null`. ChromeOS counts as
382
- `'linux'` unless you pass `{ chromeos: true }`. Reads
383
- `navigator.userAgentData.platform`, then `navigator.platform`, then the user
384
- agent. Also exported from `hotkey-router/reservations`.
250
+ Import `detectPlatform` by name from `hotkey-router` or `hotkey-router/core`. Returns `'mac'`, `'windows'`,
251
+ `'linux'` or `null`. ChromeOS counts as `'linux'` unless you pass `{
252
+ chromeos: true }`. Reads `navigator.userAgentData.platform`, then `navigator.platform`, then the user agent.
253
+ The router and every add-on use it, so they agree on `mod`.
385
254
 
386
- ### `destroy()`
387
-
388
- Removes all listeners and clears internal state.
389
-
390
- ### `trigger(hotkey, options?)`
255
+ ### `onBind(hook)`
391
256
 
392
- Programmatically trigger a hotkey. Useful for testing.
257
+ Calls `hook({ combo, type, raw, options, plugin, id })` after every successful `bind()` on this router and returns
258
+ an unsubscribe function. `type` is `'keydown'` or `'keyup'`. The development warnings use this hook. The router
259
+ logs a hook error with `console.error` and keeps the binding registered.
393
260
 
394
261
  ```js
395
- hotkeys.trigger('ctrl+k')
396
- hotkeys.trigger('ctrl+k', { target: inputElement }) // as if typed in the input
262
+ const stop = hotkeys.onBind(({ raw, plugin }) => console.debug('bound', raw, plugin))
397
263
  ```
398
264
 
399
- Returns `true` if a handler ran. Since v0.3.2 it fires what a real keypress
400
- would: the synthetic event has both `key` and `code` (US layout), so
401
- `trigger('ctrl+k')` also fires a `ctrl+code:KeyK` binding and the reverse,
402
- and the same guards apply (`when`, `ignoreInput`/`allowIn` with `target`,
403
- priority, `once`, `pause()`).
404
-
405
- Each router's `trigger()` fires only that router's bindings. It doesn't
406
- check the router's scope: `target` only feeds the input check, so a router
407
- on a dialog still fires for a `target` outside the dialog, where a real
408
- keypress would never reach it.
409
-
410
- ---
411
-
412
- ## Notes
265
+ ## How routing works
413
266
 
414
- ### Routing model
267
+ A keypress meets these in order, and each can stop it before the next:
415
268
 
416
- When multiple handlers match the same hotkey:
417
-
418
- 1. Highest `priority` wins.
419
- 2. If equal priority, newest binding wins.
420
-
421
- This makes modal overrides simple:
422
-
423
- ```js
424
- hotkeys.bind('escape', closeModal, null, {
425
- priority: 100,
426
- preventDefault: true,
427
- })
428
- ```
429
-
430
- ### Who gets a key
431
-
432
- A keypress meets these in order, and each one can stop it before the next:
433
-
434
- 1. **The browser and the OS.** Some reserved shortcuts (Ctrl+T, Ctrl+W,
435
- Cmd+Q, Spotlight) are taken before the page gets a keydown, and no
436
- listener can get them back. Others (most Ctrl+letter keys on Windows and
437
- Linux, such as Ctrl+K, Ctrl+F, Ctrl+S) reach the page first: the winning
438
- binding's `preventDefault` keeps the browser out, and without it both act.
439
- [Conflict warnings](#conflict-warnings-v020) flag both kinds when you bind.
440
- 2. **The capture phase, from `window` down to the focused element.** Bindings
441
- with `{ capture: true }`, or every binding of a router started with
442
- `init({ capture: true })`, run here, at the router's target. That's before
443
- the page's own listeners below it, so they can stop the key with
444
- `stopPropagation`. Listeners on the same target run in the order they were
445
- added.
446
- 3. **The focused element, then the bubble phase back up.** The page's own
447
- handlers (an editor's keymap, say) run first and can stop the key. Other
448
- bindings run when it reaches the router's target. For the default router,
449
- that's `window`, last of all.
269
+ 1. **The browser and the OS.** Some shortcuts (Ctrl+T, Ctrl+W, Cmd+Q, Spotlight) are taken before the page
270
+ gets a keydown, and no listener can get them back. Others (most Ctrl+letter keys on Windows and Linux, such
271
+ as Ctrl+K, Ctrl+F, Ctrl+S) reach the page first: the winning binding's `preventDefault` keeps the browser
272
+ out, and without it both act. [Reservation warnings](#reservation-warnings) flag both kinds when you bind.
273
+ 2. **The capture phase, from `window` down to the focused element.** Bindings with `{ capture: true }`, or
274
+ every binding of a router started with `init({ capture: true })`, run here at the router's target: before
275
+ the page's own listeners below it, so they can stop the key with `stopPropagation`.
276
+ 3. **The focused element, then the bubble phase back up.** The page's own handlers (an editor's keymap, say)
277
+ run first and can stop the key. The other bindings run when it reaches the router's target; for the default
278
+ router that's `window`, last of all.
450
279
  4. **Inside one router**, each time its listener runs:
451
- - **Lookup:** the bindings for the key (`ctrl+k`) and for the physical key
452
- (`ctrl+code:KeyK`) are both candidates. The non-Latin fallback (`ctrl+k`
453
- from Russian Ctrl+K) is tried only when neither has an eligible binding.
454
- - **Checks per binding:** AltGr typing a character, IME composition, the
455
- input check (`ignoreInput` / `allowIn`), auto-repeat, then `when`.
456
- A paused router skips all of this.
457
- - **One winner:** highest `priority`, then the most recently bound. One
458
- binding per router fires in each phase.
459
- - **What the winner can do:** `preventDefault` stops the browser's own action
460
- (typing the character, scrolling). `stopPropagation` and
461
- `stopImmediatePropagation` stop the event as in steps 2 and 3.
462
- 5. **Between routers:** each picks its own winner, and both fire if the event
463
- reaches both. See [Multiple routers](#multiple-routers-v040).
464
-
465
- ### Multiple routers (v0.4.0+)
466
-
467
- The default export is one router, started on `window` at import. Each
468
- `createRouter()` call makes another. Use one when:
469
-
470
- - **two libraries in one bundle both use hotkey-router.** They'd otherwise share
471
- the default router (one copy of the module, one registry), so one's
472
- `pause()` or `destroy()` would stop the other's keys. With its own router
473
- each is independent. A browser extension's content scripts don't share a
474
- router with the page's own scripts anyway: they run in a separate,
475
- isolated JavaScript world with their own copy of the module. Key events
476
- still reach both.
477
- - **keys belong to a scope.** A router on a dialog element, a `ShadowRoot` or
478
- an iframe's window only sees keys from inside it, while page-wide keys stay
479
- on the default router.
480
-
481
- Routers don't arbitrate between each other. If two routers bind the same key
482
- and the event reaches both, both fire: priority and recency only pick a
483
- winner within one router. To let one take the key, gate the other with `when`,
484
- or keep their scopes apart. `stopPropagation` doesn't stop another router
485
- listening on the same target. `stopImmediatePropagation` does, but only for
486
- routers whose listeners were added later.
487
-
488
- Shared by every router: the parser, `comboFromEvent`, `detectPlatform`, and
489
- the one-time console warning for shifted punctuation (once per combo per
490
- loaded copy of the module). Reservation warnings are per router:
491
- `installReservationWarnings(router)` covers that router's binds only, and
492
- `hotkey-router/auto` covers the default router.
493
-
494
- ### Bare-modifier bindings (v0.1.0+)
495
-
496
- 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."
280
+ - **Lookup:** bindings for the key (`ctrl+k`) and for the physical key (`ctrl+code:KeyK`) are both
281
+ candidates. The non-Latin fallback is tried only when neither has an eligible binding.
282
+ - **Checks per binding:** AltGr, IME composition, the input check (`ignoreInput` / `allowIn`), auto-repeat,
283
+ then `when`. A paused router skips everything.
284
+ - **One winner:** highest `priority`, then the most recent binding. One binding per router fires in each
285
+ phase.
286
+ - **The winner** can `preventDefault` (no browser action, no typed character) and stop propagation, as in
287
+ steps 2 and 3.
288
+ 5. **Between routers:** each picks its own winner, and both fire if the event reaches both. See [Multiple
289
+ routers](#multiple-routers).
290
+
291
+ **AltGr and IME.** Windows reports AltGr as Ctrl+Alt, so a `ctrl+alt+code:Comma` binding would swallow the `<`
292
+ a Polish or Czech user types with AltGr. A keystroke with AltGr held that types one character is skipped, as
293
+ is every keystroke during IME composition. `altGraph: true` or `composing: true` on a binding turns its guard
294
+ off.
295
+
296
+ **Shifted punctuation.** With Shift held, `event.key` is the shifted character, so a key-based `ctrl+shift+,`
297
+ waits for a `,` that a US keyboard reports as `<`, and never fires. Use the physical key `ctrl+shift+code:Comma`.
298
+ Development warnings flag Shift with `` , . / ; ' [ ] \ - = ` `` or a digit once per combo and event type.
299
+ `validateCombo` reports the same issue as `shifted-punctuation`. The other way round works: a binding for a
300
+ character with no case, such as `?`, `!` or `+`, also fires while Shift is held to type it, unless a `shift+`
301
+ binding matches exactly. Letters and Space keep Shift as part of the key.
302
+
303
+ **Non-Latin layouts.** On a Russian layout Ctrl+K reports `event.key === 'л'` with `event.code === 'KeyK'`.
304
+ When Ctrl or Cmd is held (Shift allowed, Alt not), the key types a letter from a non-Latin script and `code`
305
+ is `KeyA`…`KeyZ`, the router also looks up the Latin letter, so `ctrl+k` fires. It does this only when no
306
+ exact binding is eligible, so `ctrl+л` or `ctrl+code:KeyK` always wins. Plain and Shift-only letters, Alt and
307
+ AltGr chords, IME composition, digits and Latin layouts such as AZERTY are never affected. To require the
308
+ exact character, add `when: (e) => e.key === 'k'`.
309
+
310
+ ## Multiple routers
311
+
312
+ `createRouter(options?)` makes a router with its own bindings, plugins, `pause()`, `ignoreInput()`, `onBind`
313
+ hooks and listeners. It attaches nothing until `init()`. Use one when two libraries in one bundle both use
314
+ hotkey-router (so one's `pause()` or `destroy()` can't stop the other's keys), or when keys belong to a scope:
315
+ a router on a dialog, a `ShadowRoot` or an iframe's window only sees keys from inside it.
497
316
 
498
317
  ```js
499
- hotkeys.bind('alt', onAltDown) // fires on Alt keydown
500
- hotkeys.bind('alt up', onAltUp) // fires on Alt keyup
501
- hotkeys.bind('ctrl', onCtrlDown) // any single modifier supported
502
- ```
503
-
504
- - Only **single** bare modifiers are supported. Multi-modifier bare bindings (`'ctrl+alt'`) throw, add a base key for those.
505
- - Default `repeat: false` applies, so a held modifier fires only once on keydown.
506
- - 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.
318
+ import { createRouter } from 'hotkey-router'
507
319
 
508
- ### Code-based matching (v0.1.0+)
320
+ const dialogKeys = createRouter({ target: dialogEl, ignoreInput: 'text' })
321
+ dialogKeys.init()
322
+ dialogKeys.bind('escape', closeDialog)
323
+ dialogKeys.destroy() // later; the page's other routers keep working
324
+ ```
509
325
 
510
- `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:
326
+ Options: `target` (default `window`), `capture` (default `false`) and `ignoreInput` (default `true`). Routers
327
+ don't arbitrate between each other: if two bind the same key and the event reaches both, both fire. Gate one
328
+ with `when`, keep their scopes apart, or stop the event from the inner one. `setTarget`, how `stopPropagation`
329
+ and `stopImmediatePropagation` work between routers, and what is shared:
330
+ [docs/routers.md](https://github.com/iWhatty/hotkey-router/blob/main/docs/routers.md).
511
331
 
512
- ```js
513
- hotkeys.bind('alt+code:KeyX', deleteHovered) // matches the physical X key
514
- hotkeys.bind('ctrl+code:Digit1', goToTab1) // matches digit row, not numpad
515
- hotkeys.bind('!code:KeyX', deleteHovered) // AHK shorthand also works
516
- ```
332
+ ## Opt-in add-ons
517
333
 
518
- 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.
334
+ Each add-on is a separate entry that the core never imports, so it costs nothing unless you import it. Sizes
335
+ are minified (gzipped) in an app bundle.
519
336
 
520
- ### Conflict warnings (v0.2.0+)
337
+ | Entry | What it does | Size |
338
+ | --- | --- | --- |
339
+ | `hotkey-router/auto` | The default router with development warnings installed | ~30.8 KB (~7.8 KB), router included |
340
+ | `hotkey-router/dev` | Installs reservation and shifted-punctuation warnings on a router | ~24.3 KB (~5.3 KB), reservation table included |
341
+ | `hotkey-router/reservations` | Looks up keys reserved by the browser or OS | ~22.2 KB (~4.4 KB) |
342
+ | `hotkey-router/validate` | Checks a recorded hotkey before you save it | ~62.6 KB (~13.9 KB), both tables |
343
+ | `hotkey-router/format` | Shows a hotkey to people: `Ctrl+Shift+.`, `⇧⌘.`, keycaps | ~8.6 KB (~3.5 KB) |
344
+ | `hotkey-router/sites` | Which keys popular websites use; a `when` gate that yields to them | ~38 KB (~9 KB) |
345
+ | `hotkey-router/testing` | Fires a router binding from a hotkey string in tests | ~1.5 KB (~0.6 KB) with `/core` already bundled |
521
346
 
522
- Some combos are reserved by the browser chrome (find bar, devtools, bookmarks) or the OS (Spotlight, window management). The hard ones never reach page-world JavaScript, no matter how early you listen or whether you call `preventDefault`: Ctrl+T, Ctrl+N and Ctrl+W on Windows, for example. Others reach the page first, and the browser acts on them too unless the page calls `preventDefault`: most Ctrl+letter shortcuts on Windows and Linux, such as Ctrl+K, Ctrl+F, Ctrl+P and Ctrl+S (checked with real key presses in Chrome, Edge and Firefox on Windows, 2026-10-29). hotkey-router ships an **opt-in** reservation table that emits a warning at bind time, so the silent failure (or the double action) becomes a noisy one.
347
+ The data tables are big next to the core. Load `/auto` or `/dev` in development builds. Load `/reservations`,
348
+ `/validate` or `/sites` where your app uses the lookup data, such as a settings page that records keys.
523
349
 
524
- The feature is opt-in by design: the core router is ~11 KB minified (~4.9 KB gzipped), and the reservation module (~23 KB minified, ~5.5 KB gzipped, mostly data) is tree-shaken out entirely unless you import it.
350
+ ### Reservation warnings
525
351
 
526
- **Two ways to opt in.** One-line ergonomic, use the `auto` entry. Same default export as `hotkey-router`, with warnings pre-installed. It is the same router object, so other files can keep importing `hotkey-router` and their bindings are warned about too (v0.3.3+; earlier versions shipped a second copy of the router in `auto`). The CDN file `dist/auto.min.js` is a standalone build with its own router; don't mix it with other hotkey-router imports.
352
+ `hotkey-router/auto` is the same router object as `hotkey-router`, with warnings installed, so bindings made
353
+ through either import are checked:
527
354
 
528
355
  ```js
529
356
  import hotkeys from 'hotkey-router/auto'
530
357
 
531
358
  hotkeys.bind('meta+shift+f', toggleFullscreen)
532
359
  // Firefox on macOS:
533
- // [hotkey-router] "meta+shift+f" (meta+shift+f) reserved by firefox on macOS:
534
- // "Toggle fullscreen" [hard] — will not fire.
360
+ // [hotkey-router] "meta+shift+f" (meta+shift+f) reserved by firefox on macOS: "Toggle fullscreen" [hard] — will not fire.
535
361
  ```
536
362
 
537
- Explicit install, keep using the tiny core, install warnings yourself:
363
+ Call `installDevWarnings(router, { platform, browser })` from `hotkey-router/dev` to enable both warnings on a
364
+ specific router. It returns an unsubscribe function. Keys the page never gets log a `warn`. A key the page
365
+ can win logs an `info` with `preventDefault: true` and a `warn` otherwise. For runtime lookup use
366
+ `lookupReservation(combo, { platform, browser })` from `hotkey-router/reservations`. See
367
+ [docs/reservations.md](https://github.com/iWhatty/hotkey-router/blob/main/docs/reservations.md).
538
368
 
539
- ```js
540
- import hotkeys from 'hotkey-router'
541
- import { installReservationWarnings } from 'hotkey-router/reservations'
542
-
543
- installReservationWarnings(hotkeys)
544
- hotkeys.bind('meta+shift+f', toggleFullscreen)
545
- ```
546
-
547
- `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.
548
-
549
- **Severity to log level:**
550
-
551
- | Severity | Log level | Meaning |
552
- | ----------------- | --------- | ------------------------------------------------------- |
553
- | `hard` | `warn` | Browser intercepts before page world; combo won't fire. |
554
- | `os` | `warn` | OS intercepts globally. |
555
- | `menu-activation` | `warn` | Alt+letter activates the browser menu bar (Win/Linux). |
556
- | `find-bar-only` | `info` | Reserved only when the find bar is focused. |
557
- | `compose` | `info` | macOS Option+letter types a special char in inputs. |
558
- | `system-text` | `info` | Mac Ctrl+letter cursor controls inside text inputs. |
559
- | `devtools-open` | `info` | Only relevant when DevTools is already open. |
560
- | `preventable` | `warn` without `preventDefault: true`, else `info` | The browser's shortcut, but the page sees it first and `preventDefault: true` keeps the browser out. Without it, both act. |
561
-
562
- **Per-bind opt-out:**
369
+ ### Validating a recorded hotkey
563
370
 
564
371
  ```js
565
- hotkeys.bind('meta+shift+f', toggleFullscreen, null, { warnOnReserved: false })
566
- ```
567
-
568
- To turn warnings off globally, just don't install them (use the bare `hotkey-router` entry instead of `hotkey-router/auto`).
569
-
570
- **Force a platform/browser (tests, SSR previews):**
372
+ import { validateCombo } from 'hotkey-router/validate'
571
373
 
572
- ```js
573
- installReservationWarnings(hotkeys, { platform: 'mac', browser: 'firefox' })
374
+ const { ok, reasons } = validateCombo('mod+shift+code:Period', {
375
+ requirePrimary: true, // must include Ctrl (Cmd on macOS)
376
+ taken: ['mod+shift+code:Space'],
377
+ })
378
+ // ok: true; reasons: site-conflict warnings (Google Docs, GitHub, ...)
574
379
  ```
575
380
 
576
- Accepted platforms: `'mac' | 'windows' | 'linux'`. Browsers: `'firefox' | 'chrome' | 'safari' | 'edge'`.
577
-
578
- **Caveats:**
579
-
580
- - Reservations reflect **default** keybindings. Users with custom shortcuts (Edge 95+ rebinds, Firefox add-ons, OS-level customization) may not match.
581
- - KDE/XFCE desktop reservations beyond GNOME are not yet catalogued. Linux coverage is conservative.
582
- - 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.
583
- - 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.
381
+ Errors make `ok` false: no key, no modifier, Alt alone on Windows/Linux, a rule you asked for, already taken,
382
+ reserved by the browser or OS, shifted punctuation. Warnings keep it true: keys the page wins with
383
+ `preventDefault`, Ctrl+Alt as AltGr, sites that use the keys. Every reason code and option:
384
+ [docs/validate.md](https://github.com/iWhatty/hotkey-router/blob/main/docs/validate.md).
584
385
 
585
- **Programmatic lookup.** If you want to query the table yourself (e.g. building a cheatsheet that flags conflicts):
386
+ ### Showing a hotkey
586
387
 
587
388
  ```js
588
- import { lookupReservation } from 'hotkey-router/reservations'
389
+ import { formatCombo, comboTokens } from 'hotkey-router/format'
589
390
 
590
- const r = lookupReservation(
591
- { meta: true, shift: true, key: 'f' },
592
- { platform: 'mac', browser: 'firefox' }
593
- )
594
- // → { source: 'browser', action: 'Toggle fullscreen', severity: 'hard', ... }
391
+ formatCombo('mod+shift+code:Period', { platform: 'windows' }) // 'Ctrl+Shift+.'
392
+ formatCombo('mod+shift+code:Period', { platform: 'mac', style: 'glyphs' }) // '⇧⌘.'
393
+ comboTokens('mod+code:KeyK', { platform: 'mac' })
394
+ // [{ label: '⌘', name: 'Command', modifier: 'meta' }, { label: 'K', name: 'K', key: 'KeyK' }]
595
395
  ```
596
396
 
597
- **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:
598
-
599
- ```js
600
- const off = hotkeys.onBind(({ combo, raw, options, plugin, id }) => {
601
- // combo: parsed combo { ctrl, meta, alt, shift, key, code, bareModifier }
602
- // raw: original hotkey string
603
- })
604
- // off() unsubscribes.
605
- ```
397
+ Modifiers come in each platform's own order, and every keycap has a name a screen reader can say. All
398
+ functions and options: [docs/format.md](https://github.com/iWhatty/hotkey-router/blob/main/docs/format.md).
606
399
 
607
- ### Website shortcuts (v0.3.0+)
400
+ ### Website shortcuts
608
401
 
609
- Apps that run on other people's pages (browser extensions, embedded widgets)
610
- collide with the page's own shortcuts: Google Docs uses Ctrl+Shift+. for font
611
- size, GitHub for "quote". Unlike browser keys, those reach the page, so the
612
- app can choose. `hotkey-router/sites` knows which popular sites use which
613
- chords in the Ctrl/Cmd+Shift, Ctrl/Cmd+Alt, Shift+Alt and Ctrl/Cmd+Alt+Shift
614
- families ([docs/site-hotkeys.md](https://github.com/iWhatty/hotkey-router/blob/main/docs/site-hotkeys.md), sourced data in
615
- `data/site-hotkeys.json`) and builds a `when()` gate that yields to the site
616
- unless the user is focused on the app:
402
+ For browser extensions and widgets that run on other people's pages:
617
403
 
618
404
  ```js
619
405
  import hotkeys from 'hotkey-router'
620
406
  import { siteAware } from 'hotkey-router/sites'
621
407
 
622
408
  hotkeys.bind('mod+shift+code:Period', nextTypo, null, {
623
- capture: true, // see the key before the page's editor
409
+ capture: true, // see the key before the page's editor
624
410
  preventDefault: true,
625
- stopPropagation: true, // when we take it, the page doesn't run it too
411
+ stopPropagation: true, // when we take it, the page doesn't run it too
626
412
  allowIn: () => true,
627
- when: siteAware('mod+shift+code:Period', {
628
- engaged: () => popupIsOpen() || panelHasFocus(),
629
- }),
413
+ when: siteAware('mod+shift+code:Period', { engaged: () => panelHasFocus() }),
630
414
  })
631
415
  ```
632
416
 
633
- On sites that don't use the chord the gate is always true. On sites that do
634
- (Docs, Slides, Confluence, GitHub, WordPress ...), it returns `engaged()`;
635
- when that is false, the router leaves the event untouched and the site's
636
- shortcut runs.
637
-
638
- Also exported: `lookupSiteConflicts(combo, { url, platform, verifiedOnly })`,
639
- `matchSites(url)`, `siteLookupKey(combo, platform)`, `detectSitePlatform()`
640
- and `listSites()`. Platforms: `windows` (also used for Linux), `mac`,
641
- `chromeos`. The module is ~38 KB minified (~9 KB gzipped, mostly the table)
642
- and imports nothing from the core, so it never creates a second router.
643
-
644
- ### Validating a recorded combo (v0.3.0+)
645
-
646
- For a "press your keys" setting: record with `comboFromEvent`, then check
647
- with `hotkey-router/validate` before saving. Reasons come in plain language,
648
- ready to show.
649
-
650
- ```js
651
- import { comboFromEvent } from 'hotkey-router'
652
- import { validateCombo } from 'hotkey-router/validate'
653
-
654
- field.addEventListener('keydown', (e) => {
655
- e.preventDefault()
656
- const combo = comboFromEvent(e, { useMod: true })
657
- if (!combo) return // still holding modifiers
658
- const { ok, reasons } = validateCombo(combo, {
659
- requirePrimary: true, // must include Ctrl (Cmd on macOS)
660
- minModifiers: 2,
661
- taken: ['mod+shift+code:Space'],
662
- })
663
- show(reasons.map((r) => r.message))
664
- if (ok) save(combo)
665
- })
666
- ```
667
-
668
- Errors (`ok: false`): no key, no modifier, Alt as the only modifier on
669
- Windows/Linux, a rule you asked for (`requirePrimary`, `minModifiers`),
670
- already in `taken`, or reserved by a browser/OS (never reaches the page).
671
- Warnings (`ok: true`): reserved only in some situations; the browser's own
672
- shortcut that the page can win with `preventDefault` (`details.severity` is
673
- `'preventable'`; most Ctrl+letter keys on Windows and Linux); Ctrl+Alt acting
674
- as AltGr on some Windows layouts; and sites that use the same keys.
675
-
676
- It loads both data tables: with them, about 69 KB minified (~16 KB
677
- gzipped). Import it in the settings page that records keys, not in code
678
- that runs on every page.
679
-
680
- ### Showing a combo to people (v0.3.2+)
681
-
682
- `hotkey-router/format` turns a hotkey string (or a parsed combo) into what
683
- people read. It loads no data tables (~9 KB minified, ~3.5 KB gzipped).
684
-
685
- ```js
686
- import { formatCombo, comboTokens, modifierLabel } from 'hotkey-router/format'
687
-
688
- formatCombo('mod+shift+code:Period') // 'Ctrl+Shift+.' (Windows/Linux)
689
- formatCombo('mod+shift+code:Period', { platform: 'mac' }) // 'Shift+Cmd+.'
690
- formatCombo('mod+shift+code:Period', { platform: 'mac', style: 'glyphs' }) // '⇧⌘.'
691
-
692
- comboTokens('mod+shift+code:Period', { platform: 'mac' })
693
- // [{ label: '⇧', name: 'Shift', modifier: 'shift' },
694
- // { label: '⌘', name: 'Command', modifier: 'meta' },
695
- // { label: '.', name: 'Period', key: 'Period' }]
696
-
697
- modifierLabel('alt', { platform: 'mac', style: 'both' }) // '⌥ Option'
698
- modifierLabel('mod') // 'Cmd' or 'Ctrl'
699
- ```
700
-
701
- - `formatCombo(combo, { platform, style, order, separator })`: one string.
702
- `style: 'text'` (default) joins words with `+`; `'glyphs'` uses the macOS
703
- symbols (⌃ ⌥ ⇧ ⌘ ↩ ⌫ ⎋ ← …) with no separator.
704
- - `comboTokens(combo, { platform, style, order })`: one keycap per key,
705
- `'glyphs'` by default. `name` is what a screen reader should say; put it in
706
- visually hidden text or `aria-label` next to a glyph.
707
- - `modifierLabel(name, { platform, style })` (`'text'`, `'glyphs'` or
708
- `'both'`), `modifierName(name, { platform })` (spoken), `keyLabel(key,
709
- { platform, style })`, `listModifiers(names, { platform, conjunction })`
710
- (`'Ctrl, Alt or Shift'`), `platformLabel('mac')` (`'macOS'`),
711
- `browserLabel('edge')`.
712
- - `KEY_LABELS`: label and spoken name for `KeyboardEvent.code` values
713
- (`Period` → `.` / "Period", `Enter` → Enter, Return on macOS, ↩).
714
-
715
- Words per platform: macOS Cmd, Option, Control, Shift; Windows Ctrl, Alt,
716
- Shift, Win; Linux the same with Super; ChromeOS with Search. `platform`
717
- defaults to `detectPlatform()`. On Windows, Linux and ChromeOS `'glyphs'`
718
- gives the same words as `'text'` (they have no modifier symbols).
719
-
720
- **Modifier order.** Modifiers come in the platform's own order whatever order
721
- the string is written in: on macOS Apple's ⌃⌥⇧⌘ (Control, Option, Shift,
722
- Command), the order every Mac menu shows, so `mod+shift+.` is `⇧⌘.`; on
723
- Windows, Linux and ChromeOS Win/Super/Search, Ctrl, Alt, Shift. Pass
724
- `{ order: 'combo' }` to keep the written order (`⌘⇧.`).
725
-
726
- ### Supported syntax
727
-
728
- **Standard:**
729
-
730
- - `ctrl+k`
731
- - `shift+a`
732
- - `ctrl+k up`
733
- - `mod+s` (meta on macOS, ctrl elsewhere)
734
- - `ctrl++` or `ctrl+plus` (the `+` key; reservation and site lookups treat
735
- it as `=`, since `+` is Shift+= on most layouts)
736
-
737
- **AHK-style prefix modifiers:**
738
-
739
- - `^k` → `ctrl+k`
740
- - `!k` → `alt+k`
741
- - `+k` → `shift+k`
742
- - `#k` → `meta+k`
743
- - `^!k` → `ctrl+alt+k`
744
-
745
- Modifiers must appear before the base key.
746
-
747
- **Modifier aliases:**
748
-
749
- - `ctrl`, `control`, `⌃`
750
- - `shift`, `⇧`, `+`
751
- - `alt`, `option`, `opt`, `⌥`, `!`
752
- - `meta`, `cmd`, `command`, `win`, `⌘`, `#`
753
- - `mod` (meta on macOS, ctrl elsewhere)
754
-
755
- **Navigation / special key aliases:**
756
-
757
- - `escape`, `esc`
758
- - `enter`, `return`
759
- - `space`, `spacebar`
760
- - `tab`
761
- - `backspace`
762
- - `delete`, `del`
763
- - `home`, `end`
764
- - `pageup`, `pgup`
765
- - `pagedown`, `pgdn`
766
- - `up`, `down`, `left`, `right`
767
- - `f1`–`f19`
768
-
769
- Keys are case-insensitive.
770
-
771
- ### Philosophy
772
-
773
- hotkey-router follows three core rules:
774
-
775
- 1. **Predictable routing.** Highest priority wins. Ties go to the most recently bound handler.
776
- 2. **Safe composition.** Plugins can register and unregister without affecting others.
777
- 3. **Modern only.** Built for modern browsers using `KeyboardEvent.key`.
778
-
779
- No keycodes. No legacy IE hacks. No hidden global scope state.
780
-
781
- ### What this is not
782
-
783
- - Not a keycode polyfill
784
- - Not a legacy browser shim
785
- - Not a global scope manager
786
- - Not a VSCode-style sequence engine
787
-
788
- This is a small, deterministic routing layer for modern applications.
789
-
790
- ### Browser support
791
-
792
- Modern browsers supporting:
417
+ On sites that use the chord (Google Docs, GitHub, ...) the gate returns `engaged()`, and when that's false the
418
+ site's shortcut runs. Options, the other exports and the sourced table:
419
+ [docs/sites.md](https://github.com/iWhatty/hotkey-router/blob/main/docs/sites.md).
793
420
 
794
- - `KeyboardEvent.key`
795
- - `Map`
796
- - `addEventListener`
421
+ ## Browser support
797
422
 
798
- Chrome, Firefox, Safari, Edge.
423
+ Current Chrome, Edge, Firefox and Safari. The core relies on `KeyboardEvent.key` and `.code`, `composedPath()`
424
+ (it walks up from `event.target` when that is missing), `getModifierState('AltGraph')`, `isComposing`, `Map`
425
+ and `Set`, and Unicode property escapes in regular expressions; the build targets ES2020. The browser tests
426
+ run in Chrome and Edge; real keyboard layouts and reserved keys were checked in Chrome, Edge and Firefox on
427
+ Windows. See [docs/testing.md](https://github.com/iWhatty/hotkey-router/blob/main/docs/testing.md).
799
428
 
800
- ### Testing
801
-
802
- Everything runs locally; there is no hosted CI.
429
+ ## Scope
803
430
 
804
- - `npm test`: unit tests in jsdom.
805
- - `npm run test:browser` (v0.4.0+): builds, then runs `browser-tests/` in the
806
- Chrome and Edge installed on this machine through `playwright-core`. That
807
- covers real key events through shadow roots, routers scoped to a dialog, a
808
- shadow root and an iframe, capture against a page that stops keys, the
809
- `'text'` mode on real controls, and the built entries as an app bundles
810
- them. Nothing is downloaded; a browser that isn't installed is skipped.
811
- `BROWSERS=chrome` runs one. Needs Node 22 or later.
812
- - `npm run data:age` (v0.4.0+): how old the browser/OS and website shortcut
813
- tables are; warns past six months (the build prints the same warning).
814
- [docs/data-review.md](https://github.com/iWhatty/hotkey-router/blob/main/docs/data-review.md) says how to review them.
815
- - `scripts/key-check.ahk` (Windows, AutoHotkey 1.1): real keyboard layouts
816
- (Russian, Greek, Hebrew, Polish AltGr) in Chrome, Firefox and Edge, with
817
- results written to `docs/notes/`. See `playground/key-check.html`.
431
+ hotkey-router routes keys: it decides which one binding gets a keypress, and keeps plugins from stepping on
432
+ each other. It is not:
818
433
 
819
- ---
434
+ - a key-sequence engine (`g i`, VS Code-style chords in sequence);
435
+ - a keycode polyfill or a shim for legacy browsers;
436
+ - a scope manager: use separate routers, `when` or `pause()` for modes and dialogs;
437
+ - a store for user-remapped shortcuts: `comboFromEvent` and `validateCombo` help you record and check them,
438
+ and you save them.
820
439
 
821
440
  ## License
822
441
 
823
- Licensed under AGPL-3.0 with WATT3D Additional Terms. See [LICENSE](https://github.com/iWhatty/hotkey-router/blob/main/LICENSE) and [ADDITIONAL_TERMS.md](https://github.com/iWhatty/hotkey-router/blob/main/ADDITIONAL_TERMS.md). Commercial AI/model-training use requires compliance with those terms or a separate WATT3D license. © WATT3D.
442
+ Licensed under AGPL-3.0 with WATT3D Additional Terms. See
443
+ [LICENSE](https://github.com/iWhatty/hotkey-router/blob/main/LICENSE) and
444
+ [ADDITIONAL_TERMS.md](https://github.com/iWhatty/hotkey-router/blob/main/ADDITIONAL_TERMS.md). Commercial
445
+ AI/model-training use requires compliance with those terms or a separate WATT3D license. © WATT3D.