hotkey-router 0.5.0 → 0.5.2

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