webhotkeys 1.0.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.
@@ -0,0 +1,2047 @@
1
+ /**
2
+ * Default configuration options for Web Hotkeys.
3
+ *
4
+ * @typedef {Object} WebHotkeysDefaults
5
+ * @property {string|boolean} [hint='title'] Values: 'title', 'text', false. Append shorcut text to the element title (ex: 'anchor (Alt+1)') or its text (or its label for the case of a form element).
6
+ * @property {?Key} [helpKey='F1'] Key combination that opens the help. `null` grabs nothing.
7
+ * @property {string|boolean} [help='dialog'] Values: 'dialog', 'alert'. How the help is displayed. The dialog falls back to the alert when the DOM is not available.
8
+ * @property {?Key} [hintKey='F2'] Key combination that toggles the visual badges over all the elements having a hotkey. `null` grabs nothing.
9
+ * @property {boolean} [replaceAccesskeys=true] If true, [accesskey] elements will be converted to hotkeys.
10
+ * @property {boolean} [observe=true] Monitors DOM changes. Automatically un/grab hotkeys as DOM elements with the given attribute dis/appear.
11
+ * @property {?function} [onToggle] When having a DOM element linked, run this callback on hotkey toggle. This will be set to the hotkey, first parameter being the element, second boolean whether it got enabled.
12
+ * @property {?function} [onTrigger] Called after a hotkey fired, receives (hotkey, event). Handy for logging.
13
+ * @property {?function} [onMiss] Called when a keystroke matched no hotkey, receives (event). Handy for debugging.
14
+ * @property {string} [attribute='data-hotkey'] Attribute name to link DOM elements to shorcuts.
15
+ * @property {string} [groupAttribute='data-hotkey-group'] Attribute name to link DOM elements to shorcut groups.
16
+ * @property {string} [actionAttribute='data-hotkey-action'] Attribute name to override what happens with the element ('click', 'focus', 'toggle', 'none'). Without it a text field is focused, a button/checkbox/radio clicked and a DETAILS toggled. @see defaultAction
17
+ * @property {?string|?function} [ignore=null] Selector or callback(activeElement, event). When it matches, no hotkey is triggered at all.
18
+ * @property {number} [sequenceTimeout=1000] Milliseconds a key sequence ('g i') may be spread over. Also how long the F1 dialog waits before committing a recorded sequence.
19
+ * @property {boolean|string} [remap=true] The F1 dialog lets the user click a combination and press their own. A string is used as the localStorage key (true means 'webhotkeys.remap'), false turns the editing off.
20
+ * @property {?function} [onRemap] Called with the remapping object whenever the user changes a combination. Handy to store the layout on the server. @see remapping
21
+ * @property {?boolean} [mac=null] Display the combinations with the macOS symbols (⌘⌥⇧⌃) and resolve the 'Mod' modifier to Meta. Null means autodetect.
22
+ * @property {boolean} [warnConflicts=false] Console warn when a newly grabbed hotkey shadows an existing scope-less one,
23
+ * or when a plain hotkey and a longer sequence (ex: 'g' and 'g i') would shadow one another.
24
+ */
25
+ const WebHotkeysDefaults = {
26
+ replaceAccesskeys: true, helpKey: "F1", help: "dialog", hintKey: "F2",
27
+ attribute: "data-hotkey", groupAttribute: "data-hotkey-group", actionAttribute: "data-hotkey-action",
28
+ observe: true, onToggle: null, onTrigger: null, onMiss: null, hint: "title",
29
+ ignore: null, sequenceTimeout: 1000, mac: null, warnConflicts: false,
30
+ remap: true, onRemap: null
31
+ }
32
+
33
+ /**
34
+ * Like KeyboardEvent but does not have guaranteed to contain all info.
35
+ * Ex: {"code": "Digit1", "altKey": true} (missing shiftKey)
36
+ * @typedef {KeyboardEvent} KeyEvent
37
+ */
38
+ /** Key combination. Either event.code "Digit1", event.key "1" or a combination with a modifier "Ctrl+Digit1".
39
+ * Multiple combinations separated by a space form a sequence: "g i".
40
+ * @typedef {string} Key
41
+ */
42
+ /** @typedef {HTMLElement|Function} ResolvedAction An element or a callback function. */
43
+ /** @typedef {ResolvedAction|string} Action An element, its selector or a callback function. */
44
+ /**
45
+ * Key letter combined with modifiers. Just because JS does not support tuple as a key dict.
46
+ * @typedef {string} KeyState
47
+ */
48
+ /**
49
+ * Modifiers as a string. Just because JS does not support tuple as a key dict.
50
+ * @typedef {string} ModState
51
+ */
52
+
53
+ /** Where the user remapping goes. Dotted on purpose - the page shares the origin, it must not look like its own key. */
54
+ const DEFAULT_STORAGE_KEY = "webhotkeys.remap"
55
+
56
+ const FORM_TAGS = ["INPUT", "SELECT", "TEXTAREA"]
57
+ /** Input types that are not a text field - they never eat a letter key, so the text guard must not stand back for them. */
58
+ const NON_TEXT_INPUT_TYPES = ["checkbox", "radio", "submit", "button", "reset", "image", "file", "range", "color"]
59
+ /** Input types a hotkey should activate instead of merely focusing (a range or a color still wants the focus - the arrows adjust it). */
60
+ const CLICKABLE_INPUT_TYPES = ["checkbox", "radio", "submit", "button", "reset", "image", "file"]
61
+ /** Is the element a text field, ie. would a letter key land in it? (A SELECT counts - letters do its typeahead.) */
62
+ const isTextInput = el => FORM_TAGS.includes(el.tagName) && !(el.tagName === "INPUT" && NON_TEXT_INPUT_TYPES.includes(el.type))
63
+ /**
64
+ * What happens to a linked element when no [data-hotkey-action] says otherwise.
65
+ * A text field is focused (the user wants to type), everything else is activated - including a submit
66
+ * button or a checkbox, which a mere focus would leave untouched. A DETAILS has no activation behaviour
67
+ * of its own (the native toggle sits on its SUMMARY), so clicking it would silently do nothing.
68
+ * @param {HTMLElement} element
69
+ * @returns {string} 'focus' | 'click' | 'toggle'
70
+ */
71
+ const defaultAction = element => {
72
+ if (element.tagName === "DETAILS") {
73
+ return "toggle"
74
+ }
75
+ if (element.tagName === "INPUT" && CLICKABLE_INPUT_TYPES.includes(element.type)) {
76
+ return "click"
77
+ }
78
+ return FORM_TAGS.includes(element.tagName) ? "focus" : "click"
79
+ }
80
+ /** These fire a keydown of their own; a sequence step may consist of them only ('Shift Shift'). */
81
+ const MODIFIER_KEYS = ["Shift", "Alt", "Control", "Meta"]
82
+ /** Written in a hotkey definition -> the real KeyboardEvent.key of a lone modifier. */
83
+ const MODIFIER_ALIASES = { shift: "Shift", alt: "Alt", ctrl: "Control", control: "Control", meta: "Meta", cmd: "Meta", mod: "Mod" }
84
+ /** Convenience spellings accepted in a hotkey definition. */
85
+ const KEY_ALIASES = {
86
+ return: "Enter", esc: "Escape", del: "Delete", ins: "Insert", space: "Space",
87
+ up: "ArrowUp", down: "ArrowDown", left: "ArrowLeft", right: "ArrowRight",
88
+ pgup: "PageUp", pgdown: "PageDown", pgdn: "PageDown"
89
+ }
90
+ /**
91
+ * Shadow codes. When no hotkey claims the pressed `code`, we look up its main-row counterpart,
92
+ * so that a hotkey grabbed as 'Digit1' or 'Enter' fires from the numeric keypad too.
93
+ * A hotkey explicitly grabbed for the numpad code always wins.
94
+ */
95
+ const CODE_ALIASES = {
96
+ NumpadEnter: "Enter", NumpadDecimal: "Period", NumpadDivide: "Slash", NumpadSubtract: "Minus", NumpadAdd: "Equal",
97
+ Numpad0: "Digit0", Numpad1: "Digit1", Numpad2: "Digit2", Numpad3: "Digit3", Numpad4: "Digit4",
98
+ Numpad5: "Digit5", Numpad6: "Digit6", Numpad7: "Digit7", Numpad8: "Digit8", Numpad9: "Digit9"
99
+ }
100
+ const MAC_SYMBOLS = { ctrl: "⌃", alt: "⌥", shift: "⇧", meta: "⌘" }
101
+
102
+ class Hotkey {
103
+ /**
104
+ *
105
+ * @param {ResolvedAction} action
106
+ * @param {string} hint
107
+ * @param {Action} scope
108
+ * @param {KeyEvent|KeyEvent[]} event Single combination or a sequence of them.
109
+ * @param {WebHotkeys} wh
110
+ */
111
+ constructor(action, hint, scope, event, wh) {
112
+ this.action = action
113
+ this.hint = hint
114
+ this.scope = scope
115
+ /** @type {KeyEvent[]} The whole sequence. A plain hotkey is a sequence of a single combination. */
116
+ this.sequence = Array.isArray(event) ? event : [event]
117
+ /** @type {KeyEvent} The combination that actually triggers the hotkey (the last one of the sequence). */
118
+ this.event = this.sequence[this.sequence.length - 1]
119
+ this.wh = wh
120
+ /** @type {boolean} Fire even when the user is typing into an input. @see allowInput */
121
+ this.allowInput = false
122
+ /** @type {string} The combination the hotkey was grabbed with. Survives `rebind`, hence remapping. */
123
+ this.defaultCombination = this.combination
124
+ /** @type {?HTMLElement} The hotkey is linked to this DOM element. */
125
+ const el = this.element = action instanceof HTMLElement ? action : null
126
+ wh._all.add(this)
127
+ this.enabled = this._enable() // do not emit onToggle on first enabling
128
+
129
+ if (el) {
130
+ if (!this.hint) {
131
+ this.hint = el.title || el.innerText.substring(0, 50)
132
+ }
133
+ this._hintElement()
134
+ }
135
+ }
136
+
137
+ /** Append the clue to the linked element (title / text), unless it is already there. */
138
+ _hintElement(previousClue = null) {
139
+ const el = this.element
140
+ const opt = this.wh.options
141
+ if (!el || !opt.hint) {
142
+ return
143
+ }
144
+ const clue = this.clue
145
+ // Stores *which* hotkey's clue was last hinted (not just a boolean), as a
146
+ // data-* attribute so it survives el.cloneNode()/$.clone(). A clone kept
147
+ // with the SAME hotkey (ex: zoom.js's `replace()` re-clones #nav-Close with
148
+ // "Alt+z" on every zoom_refresh()) must not be re-hinted; but a clone given
149
+ // a DIFFERENT hotkey (ex: free-text.js clones the submit button 3x, each
150
+ // with its own Alt+Shift+… hotkey) still needs its own hint appended.
151
+ if (el.dataset.webhotkeysDisplayed === clue) {
152
+ return
153
+ }
154
+ const hint = ` (${clue})`
155
+ const stale = previousClue ? ` (${previousClue})` : null // rebind: replace, do not append twice
156
+ const rewrite = text => stale && text.includes(stale) ? text.replace(stale, hint) : text + hint
157
+ if (opt.hint === "title") {
158
+ el.title = rewrite(el.title || "")
159
+ } else if (opt.hint === "text") {
160
+ if (FORM_TAGS.includes(el.tagName)) {
161
+ if (el.labels?.[0]?.innerHTML) {
162
+ el.labels[0].innerHTML = rewrite(el.labels[0].innerHTML)
163
+ }
164
+ } else {
165
+ el.innerHTML = rewrite(el.innerHTML)
166
+ }
167
+ }
168
+ el.dataset.webhotkeysDisplayed = clue
169
+ }
170
+
171
+ /**
172
+ * Hotkey combination for the text representation. Uses the macOS symbols when applicable.
173
+ * @returns {string}
174
+ */
175
+ get clue() {
176
+ return this.sequence.map(e => Hotkey.comboText(e, this.wh?.isMac())).join(" ")
177
+ }
178
+
179
+ /**
180
+ * The canonical, platform independent definition string. `wh.grab(hotkey.combination, …)`
181
+ * grabs the very same combination. Unlike `clue`, it never uses the macOS symbols.
182
+ * @returns {Key}
183
+ */
184
+ get combination() {
185
+ return this.sequence.map(e => Hotkey.comboText(e, false)).join(" ")
186
+ }
187
+
188
+ /** Text representation. @returns {string} */
189
+ get text() {
190
+ return this.hint ? `${this.clue}: ${this.hint}` : this.clue
191
+ }
192
+
193
+ /**
194
+ * Text form of a single combination.
195
+ * @param {KeyEvent} e
196
+ * @param {boolean} mac Use the macOS symbols.
197
+ * @returns {string}
198
+ */
199
+ static comboText(e, mac = false) {
200
+ const key = (e.key || e.code || "").replace(/^Digit(\d)$/, "$1") // 'Alt+Digit1' -> 'Alt+1'
201
+ if (MODIFIER_KEYS.includes(key)) { // a lone modifier, ex: the 'Shift Shift' double tap
202
+ return mac ? MAC_SYMBOLS[key === "Control" ? "ctrl" : key.toLowerCase()] : key
203
+ }
204
+ const mods = ["ctrl", "alt", "shift", "meta"].filter(m => e[m + "Key"])
205
+ if (mac) {
206
+ // Apple's canonical order, no separator
207
+ return ["ctrl", "alt", "shift", "meta"].filter(m => e[m + "Key"]).map(m => MAC_SYMBOLS[m]).join("") + key
208
+ }
209
+ const order = { ctrl: "Ctrl+", shift: "Shift+", alt: "Alt+", meta: "Meta+" }
210
+ return ["ctrl", "shift", "alt", "meta"].filter(m => mods.includes(m)).map(m => order[m]).join("") + key
211
+ }
212
+
213
+ /**
214
+ * Build the definition string out of a real keystroke. @see WebHotkeys.record
215
+ * @param {KeyEvent} e
216
+ * @returns {Key}
217
+ */
218
+ static fromEvent(e) {
219
+ if (MODIFIER_KEYS.includes(e.key)) {
220
+ return e.key
221
+ }
222
+ return Hotkey.comboText({ ...pickModifiers(e), [e.key?.length === 1 ? "key" : "code"]: e.key?.length === 1 ? e.key : e.code })
223
+ }
224
+
225
+ /**
226
+ * @returns {KeyState}
227
+ */
228
+ get key_state() {
229
+ return (this.event.key || this.event.code) + Hotkey.mod_state(this.event)
230
+ }
231
+
232
+ /**
233
+ * @returns {Hotkey[]}
234
+ */
235
+ get registry() {
236
+ return this.wh._hotkeys[this.key_state] ||= []
237
+ }
238
+
239
+ /**
240
+ *
241
+ * @param {KeyEvent} e
242
+ * @returns {ModState}
243
+ */
244
+ static mod_state(e, supress_shift = false) {
245
+ // If there ever be a clash between key and code, we might put a list into storage
246
+ // and compare hotkeys like this: [modifiers] = [{key: 1}, {code: Digit1}]
247
+ return String((supress_shift ? 0 : e.shiftKey << 3) | e.altKey << 2 | e.ctrlKey << 1 | e.metaKey)
248
+ }
249
+
250
+ /**
251
+ * Does a single combination describe the given keystroke?
252
+ * @param {KeyEvent} spec A parsed combination.
253
+ * @param {KeyEvent} e A real keystroke.
254
+ * @returns {boolean}
255
+ */
256
+ static match(spec, e) {
257
+ if (spec.code && spec.code !== e.code && CODE_ALIASES[e.code] !== spec.code) {
258
+ return false
259
+ }
260
+ if (spec.key && !keyEquals(spec.key, e.key)) {
261
+ return false
262
+ }
263
+ const oneChar = e.key?.length === 1
264
+ return Hotkey.mod_state(spec, oneChar && !/[A-Za-z]/.test(e.key)) === Hotkey.mod_state(e, oneChar && !/[A-Za-z]/.test(e.key))
265
+ }
266
+
267
+ /**
268
+ * Is `shorter` a strict prefix of `longer`? Ex: 'g' is a prefix of the 'g i' sequence -
269
+ * the plain hotkey then shadows the sequence until its keystroke is disambiguated.
270
+ * @param {KeyEvent[]} shorter
271
+ * @param {KeyEvent[]} longer
272
+ * @returns {boolean}
273
+ */
274
+ static isPrefixOf(shorter, longer) {
275
+ return shorter.length < longer.length && shorter.every((step, i) => Hotkey.match(step, longer[i]))
276
+ }
277
+
278
+ /**
279
+ * Move the hotkey to another combination, ex. because the user remapped it.
280
+ * @param {?Key} combination Nothing (or null) puts the hotkey back to its default combination.
281
+ * @param {boolean} store Record the change in the remapping (and persist it). Internal use.
282
+ * @returns {Hotkey}
283
+ */
284
+ rebind(combination = null, store = true) {
285
+ const was = this.enabled
286
+ const previousClue = this.clue
287
+ this.disable()
288
+ this.sequence = this.wh._parseSequence(combination || this.defaultCombination)
289
+ this.event = this.sequence[this.sequence.length - 1]
290
+ this._hintElement(previousClue)
291
+ if (was) {
292
+ this.enable()
293
+ }
294
+ if (store) {
295
+ const current = this.combination
296
+ if (current === this.defaultCombination) {
297
+ delete this.wh._remap[this.defaultCombination]
298
+ } else {
299
+ this.wh._remap[this.defaultCombination] = current
300
+ }
301
+ this.wh._saveRemapping()
302
+ }
303
+ return this
304
+ }
305
+
306
+ _enable() {
307
+ if (!this.registry.includes(this)) {
308
+ this.registry.unshift(this)
309
+ }
310
+ return this.enabled = true
311
+ }
312
+ enable() {
313
+ this._enable()
314
+ this._notify()
315
+ return this
316
+ }
317
+ disable() {
318
+ const index = this.registry.indexOf(this)
319
+ if (index > -1) { // when already disabled, splice(-1, 1) would remove a foreign hotkey sharing the combination
320
+ this.registry.splice(index, 1)
321
+ }
322
+ this.enabled = false
323
+ this._notify()
324
+ return this
325
+ }
326
+ /**
327
+ * @param {?boolean} enable
328
+ */
329
+ toggle(enable = null) {
330
+ enable === null && !this.enabled || enable ? this.enable() : this.disable()
331
+ return this
332
+ }
333
+
334
+ /**
335
+ * Unlike `disable`, this forgets the hotkey for good – it disappears from the groups,
336
+ * from the help and the linked element can be grabbed again.
337
+ * @returns {Hotkey}
338
+ */
339
+ remove() {
340
+ this.disable()
341
+ this.wh._all.delete(this)
342
+ if (this.element && this.wh._dom.get(this.element) === this) {
343
+ this.wh._dom.delete(this.element)
344
+ }
345
+ Object.values(this.wh._groups).forEach(group => {
346
+ const index = group.indexOf(this)
347
+ if (index > -1) {
348
+ group.splice(index, 1)
349
+ }
350
+ })
351
+ return this
352
+ }
353
+
354
+ _notify() {
355
+ if (this.element && this.wh.options.onToggle) {
356
+ this.wh.options.onToggle.call(this, this.action, this.enabled)
357
+ }
358
+ }
359
+ }
360
+
361
+ /**
362
+ * @extends {Array<Hotkey>}
363
+ */
364
+ class HotkeyGroup extends Array {
365
+ enable() {
366
+ return this.toggle(true)
367
+ }
368
+ disable() {
369
+ return this.toggle(false)
370
+ }
371
+ /**
372
+ * @param {?boolean} enable
373
+ */
374
+ toggle(enable = null) {
375
+ this.forEach(hotkey => hotkey.toggle(enable))
376
+ return this
377
+ }
378
+ /** Forget all the hotkeys of the group. @see Hotkey.remove */
379
+ remove() {
380
+ this.slice().forEach(hotkey => hotkey.remove())
381
+ return this
382
+ }
383
+ }
384
+
385
+ /**
386
+ * Main interface to define hotkeys
387
+ */
388
+ class WebHotkeys {
389
+
390
+ /**
391
+ * @param {WebHotkeysDefaults} options
392
+ */
393
+ constructor(options) {
394
+ /** @type {WebHotkeysDefaults} */
395
+ options = this.options = { ...WebHotkeysDefaults, ...options }
396
+ /** @type {Object.<KeyState, Hotkey[]>} */
397
+ this._hotkeys = Object.create(null)
398
+ /** @type {WeakMap.<HTMLElement, Hotkey>} Links DOM elements to its shorcuts. */
399
+ this._dom = new WeakMap()
400
+ /** @type {Set<Hotkey>} Every hotkey ever grabbed, the disabled ones included. */
401
+ this._all = new Set()
402
+ /** @type {{event: KeyEvent, time: number}[]} Recent keystrokes, the material for the key sequences. */
403
+ this._buffer = []
404
+ /** @type {?{hotkey: Hotkey, event: KeyEvent, timer: *}} A plain hotkey whose key also begins a longer
405
+ * registered sequence: held back until `sequenceTimeout` passes or the next keystroke settles it. */
406
+ this._deferred = null
407
+ /**
408
+ * @type {Object.<Key, Key>} The user changes (default combination -> the current one).
409
+ * Kept as the single source of truth, not derived from the hotkeys: a remapping may well
410
+ * concern a hotkey that is not grabbed yet (another SPA view), `grab` consults it.
411
+ */
412
+ this._remap = Object.create(null)
413
+ /** @type {?function} Set while `record` waits for a keystroke; the hotkeys stay silent meanwhile. */
414
+ this._recording = null
415
+ /** @type {_List[]} Every `list()` instance, so `destroy()` can detach their typeahead listeners too. */
416
+ this._lists = []
417
+
418
+ // Object.create(null) (not {}) because the group name is an arbitrary string coming from
419
+ // [data-hotkey-group] in the DOM. A group named e.g. "constructor" or "__proto__" would otherwise
420
+ // collide with an inherited property, returning a builtin instead of a HotkeyGroup (crashing on
421
+ // .push()) or clobbering the registry's own prototype.
422
+ /** @type {Object.<string, Hotkey[]>} */
423
+ this._groups = Object.create(null)
424
+
425
+ //
426
+ // Helper methods
427
+ //
428
+ /**
429
+ * @param {HTMLElement} el
430
+ * @returns {boolean} Has [data-hotkey] attribute
431
+ */
432
+ const eligible = el => el.getAttribute?.(options.attribute)?.length
433
+ /** @param {HTMLElement} el Grab the element's [data-hotkey] attribute */
434
+ // The user might pass a dynamically created element with [data-hotkey] to grab. In such case, MutationObserver will notify us
435
+ // about the element when the original thread ceases. Thus, if we have not checked whether the element has already linked
436
+ // the hotkey through the this._dom, it would be regrabbed and strange bugs would be produced. (Ex: double onToggle callback.)
437
+ // const grab = el => !this._dom.has(el)&& this._dom.set(el, this.grab(el.getAttribute(options.attribute), el.getAttribute("title"), el))
438
+ const grab = el => !this._dom.has(el) && this.grab(el.getAttribute(options.attribute), el.getAttribute("title"), el)
439
+
440
+ //
441
+ // Process options
442
+ //
443
+ if (options.remap) { // load the stored layout before anything gets grabbed
444
+ this._storageKey = isString(options.remap) ? options.remap : DEFAULT_STORAGE_KEY
445
+ this._loadRemapping()
446
+ }
447
+ if (options.replaceAccesskeys) {
448
+ document.querySelectorAll("[accesskey]:not([accesskey=''])").forEach(el => {
449
+ // if concurrent accesskeys exists, preventDefault of the WebHotkeys would make it to fire alongside the hotkey,
450
+ // hence we transform accesskeys to hotkeys as well
451
+ el.setAttribute(options.attribute, "Alt+" + el.getAttribute("accesskey"))
452
+ el.removeAttribute("accesskey")
453
+ })
454
+ }
455
+
456
+ if (options.helpKey) {
457
+ this.grab(options.helpKey, "Help", () => this.toggleHelp())
458
+ }
459
+ if (options.hintKey) {
460
+ this.grab(options.hintKey, "Show the hotkeys over the page", () => this.toggleHints())
461
+ }
462
+
463
+ // Grabs all [data-hotkey] elements. Puts its title as a help text.
464
+ document.querySelectorAll(`[${options.attribute}]`).forEach(grab)
465
+
466
+ if (options.observe) {
467
+ // un/register hotkey on DOM change
468
+ this._observer = new MutationObserver(mutationList => {
469
+ for (const mutation of mutationList) {
470
+ if (mutation.type === "attributes") {
471
+ const el = mutation.target
472
+ this._dom.get(el)?.disable() && this._dom.delete(el) // old hotkey vanished
473
+ if (eligible(el)) { // new hotkey appeared
474
+ grab(el)
475
+ }
476
+ } else if (mutation.type === "childList") {
477
+ // Grab all the added nodes and their subtrees
478
+ [...Array.from(mutation.addedNodes).filter(eligible),
479
+ ...Array.from(mutation.addedNodes).map(el => Array.from(el.querySelectorAll?.(`[${options.attribute}]`) || [])).flat()
480
+ ].forEach(grab); // ; needed
481
+ // Ungrab all the added nodes and their subtrees
482
+ [...Array.from(mutation.removedNodes).filter(eligible),
483
+ ...Array.from(mutation.removedNodes).map(el => Array.from(el.querySelectorAll?.(`[${options.attribute}]`) || [])).flat()]
484
+ .forEach(el => this._dom.get(el).disable() && this._dom.delete(el))
485
+ }
486
+
487
+ }
488
+ })
489
+ this._observer.observe(document, { attributeFilter: [options.attribute], childList: true, subtree: true })
490
+ }
491
+
492
+ //
493
+ // Start listening
494
+ //
495
+ this._listener = e => this._trigger(e)
496
+ document.addEventListener("keydown", this._listener, true)
497
+ return this
498
+ }
499
+
500
+ /**
501
+ * @param {WebHotkeysDefaults} options
502
+ */
503
+ setOptions(options) {
504
+ this.options = { ...this.options, ...options }
505
+ return this
506
+ }
507
+
508
+ /**
509
+ * Stop listening for good – detaches the keydown listener and the MutationObserver, forgets
510
+ * every hotkey and removes the injected styles. Call it when a SPA view unmounts, otherwise
511
+ * the instance keeps intercepting the whole document forever.
512
+ * @returns {WebHotkeys}
513
+ */
514
+ destroy() {
515
+ document.removeEventListener("keydown", this._listener, true)
516
+ this._observer?.disconnect()
517
+ this._recording?.()
518
+ this._hideHelp()
519
+ this._hideHints()
520
+ this._lists.forEach(list => list.destroy())
521
+ this._lists = []
522
+ Array.from(this._all).forEach(hotkey => hotkey.remove())
523
+ this._hotkeys = Object.create(null)
524
+ this._groups = Object.create(null)
525
+ this._dom = new WeakMap()
526
+ this._buffer = []
527
+ this._settleDeferred(false)
528
+ this._style?.remove?.()
529
+ this._style = this._sheet = undefined
530
+ this._destroyed = true
531
+ return this
532
+ }
533
+
534
+ /** @returns {boolean} Should the combinations be rendered the Apple way (⌘⌥⇧⌃)? */
535
+ isMac() {
536
+ if (this.options.mac !== null && this.options.mac !== undefined) {
537
+ return this.options.mac
538
+ }
539
+ const platform = typeof navigator !== "undefined"
540
+ && (navigator.userAgentData?.platform || navigator.platform || navigator.userAgent || "")
541
+ return /mac|iphone|ipad|ipod/i.test(platform || "")
542
+ }
543
+
544
+ /**
545
+ * `document.activeElement` does not pierce the shadow DOM – this does, so that both the scope
546
+ * and the "user is typing" detection work inside the web components.
547
+ * @returns {?HTMLElement}
548
+ */
549
+ activeElement() {
550
+ let el = document.activeElement
551
+ while (el?.shadowRoot?.activeElement) {
552
+ el = el.shadowRoot.activeElement
553
+ }
554
+ return el || null
555
+ }
556
+
557
+ /**
558
+ * @param {boolean} enabledOnly
559
+ * @returns {Hotkey[]}
560
+ */
561
+ getHotkeys(enabledOnly = true) {
562
+ return Array.from(this._all).filter(hotkey => !enabledOnly || hotkey.enabled)
563
+ }
564
+
565
+ /**
566
+ * Hotkeys structured for the help. The ungrouped ones come first, under an empty name.
567
+ * @returns {{name: string, hotkeys: Hotkey[]}[]}
568
+ */
569
+ getGroups() {
570
+ const enabled = new Set(this.getHotkeys())
571
+ const seen = new Set()
572
+ const grouped = Object.entries(this._groups).map(([name, group]) => {
573
+ const hotkeys = group.filter(hotkey => enabled.has(hotkey))
574
+ hotkeys.forEach(hotkey => seen.add(hotkey))
575
+ return { name, hotkeys }
576
+ }).filter(g => g.hotkeys.length) // if at least one hotkey from a group remains enabled
577
+
578
+ const ungrouped = Array.from(enabled).filter(hotkey => !seen.has(hotkey))
579
+ return [...(ungrouped.length ? [{ name: "", hotkeys: ungrouped }] : []), ...grouped]
580
+ }
581
+
582
+ /**
583
+ * @returns {string} Help text to current hotkeys' map.
584
+ */
585
+ getText() {
586
+ return this.getGroups()
587
+ .map(({ name, hotkeys }) => (name ? `\n**${name}**\n` : "") + hotkeys.map(h => h.text).join("\n"))
588
+ .join("\n").trim()
589
+ }
590
+
591
+ /**
592
+ * Scope-less hotkeys fighting over the same combination. The last grabbed one wins,
593
+ * the others are only reached when it returns false.
594
+ * @returns {{combination: string, hotkeys: Hotkey[]}[]}
595
+ */
596
+ getConflicts() {
597
+ const map = new Map()
598
+ this.getHotkeys().filter(hotkey => !hotkey.scope).forEach(hotkey => {
599
+ const key = hotkey.combination
600
+ map.set(key, [...(map.get(key) || []), hotkey])
601
+ })
602
+ return Array.from(map).filter(([, hotkeys]) => hotkeys.length > 1)
603
+ .map(([combination, hotkeys]) => ({ combination, hotkeys }))
604
+ }
605
+
606
+ /**
607
+ * .grab(hotkey, hint, action, [scope|options])
608
+ *
609
+ * @param {Key} hotkey Key combination to be grabbed. Ex: 'Alt+a', 'Ctrl+PageDown', 'g i' (a sequence).
610
+ * @param {string} hint Text shown in the help dialog and hint badges.
611
+ * @param {Action} action What will happen on hotkey trigger.
612
+ * If action returns false, hotkey will be treated as non-existent and event will propagate further.
613
+ * If action is a HTMLElement or its string selector, its click or focus method (form elements) is invoked instead.
614
+ * @param {?Action|{scope: ?Action, inInput: ?boolean, group: ?string}} scope Scope within the hotkey is allowed to be launched,
615
+ * or an options object `{scope, inInput, group}`.
616
+ * The scope can be an HTMLElement that the active element is being search under when the hotkey triggers.
617
+ * The scope can an HTMLElement selector, does not have to exist at the shorcut definition time.
618
+ * The scope can be a function, resolved at the keystroke time. True means the scope matches. That way, you can implement negative scope.
619
+ * (Ex: down arrow should work unless there is DialogOverlay in the document root.)
620
+ * `inInput: true` fires the hotkey even while the user is typing into an input or a contenteditable
621
+ * (ex: arrow keys navigating a combobox's suggestion list). @see Hotkey.allowInput
622
+ * `group` adds the hotkey to a named `HotkeyGroup` (same as `wh.group(name, [[...]])` would).
623
+ * @returns {Hotkey}
624
+ */
625
+ grab(hotkey, hint, action, scope = null) {
626
+ let inInput = false
627
+ let group = null
628
+ // An options object `{scope, inInput, group}`, not a plain scope. Checked by prototype chain depth,
629
+ // not `typeof` (an HTMLElement/selector-result is an object too) nor `=== Object.prototype`
630
+ // (breaks across realms, ex: a test running WebHotkeys.js inside a `vm` context).
631
+ if (scope && typeof scope === "object" && Object.getPrototypeOf(Object.getPrototypeOf(scope) ?? {}) === null) {
632
+ inInput = scope.inInput ?? false
633
+ group = scope.group ?? null
634
+ scope = scope.scope ?? null
635
+ }
636
+ let error = !hotkey || !action
637
+ if (isString(action)) {
638
+ try {
639
+ action = document.querySelector(action)
640
+ } catch (e) {
641
+ error = true
642
+ }
643
+ }
644
+ if (error) {
645
+ console.error(`WebHotkeys.js> Unknown action hotkey for action ${hotkey} ${action}`)
646
+ return
647
+ }
648
+ // register hotkey and set the hint to the DOM
649
+ const hotkeyO = new Hotkey(action, hint, scope, this._parseSequence(hotkey), this)
650
+ hotkeyO.allowInput = inInput
651
+
652
+ // The user may have remapped this very combination in a previous session (or in another
653
+ // view that has been unmounted since) – honour it right away, before anyone sees the hint.
654
+ const remapped = this._remap[hotkeyO.defaultCombination]
655
+ if (remapped && remapped !== hotkeyO.combination) {
656
+ hotkeyO.rebind(remapped, false)
657
+ }
658
+
659
+ const { element } = hotkeyO
660
+ const { groupAttribute } = this.options
661
+ if (element) {
662
+ this._dom.set(element, hotkeyO)
663
+
664
+ // register group
665
+ const groupName = element.closest(`[${groupAttribute}]`)?.getAttribute(groupAttribute)
666
+ if (groupName) {
667
+ this.group(groupName).push(hotkeyO)
668
+ }
669
+ }
670
+ if (group) {
671
+ this.group(group).push(hotkeyO)
672
+ }
673
+ if (this.options.warnConflicts) {
674
+ // Cheap: only scan the bucket this very hotkey landed in, not every grabbed hotkey.
675
+ const combination = hotkeyO.combination
676
+ const conflict = hotkeyO.registry.filter(h => !h.scope && h.combination === combination)
677
+ if (conflict.length > 1) {
678
+ console.warn(`WebHotkeys.js> ${combination} is grabbed ${conflict.length}x:`,
679
+ conflict.map(h => h.hint || h.action))
680
+ }
681
+ if (!hotkeyO.scope) {
682
+ // A plain hotkey next to a longer sequence sharing its start: the plain one always
683
+ // wins after `sequenceTimeout` ms, delaying it - surprising unless done on purpose.
684
+ const shadow = this.getHotkeys().find(h => h !== hotkeyO && !h.scope
685
+ && (Hotkey.isPrefixOf(h.sequence, hotkeyO.sequence) || Hotkey.isPrefixOf(hotkeyO.sequence, h.sequence)))
686
+ if (shadow) {
687
+ const [plain, sequence] = hotkeyO.sequence.length < shadow.sequence.length ? [hotkeyO, shadow] : [shadow, hotkeyO]
688
+ console.warn(`WebHotkeys.js> ${plain.combination} shadows the sequence ${sequence.combination} - `
689
+ + `the plain hotkey fires only after a ${this.options.sequenceTimeout}ms delay, in case the sequence doesn't complete:`,
690
+ [plain.hint || plain.action, sequence.hint || sequence.action])
691
+ }
692
+ }
693
+ }
694
+ return hotkeyO
695
+ }
696
+
697
+ /**
698
+ * Grab multiple hotkeys at once. They are appended to a group.
699
+ * @param {string} name Group name
700
+ * @param {?Array} definitions List of grab parameters. Ex: [["Ctrl+c", "Copy", callback], ["Ctrl+v", "Paste", callback]]
701
+ * @returns {HotkeyGroup}
702
+ */
703
+ group(name, definitions = null) {
704
+ const group = this._groups[name] ||= new HotkeyGroup()
705
+ if (definitions) {
706
+ // If the DOM elements are nested under the same data-hotkey-group, they would be included twice.
707
+ group.push(...definitions.map(d => this.grab(...d)).filter(h => !group.includes(h)))
708
+ }
709
+ return group
710
+ }
711
+
712
+ /**
713
+ * A sequence of combinations, ex: 'g i' or 'Shift Shift'.
714
+ * @param {Key} hotkey
715
+ * @returns {KeyEvent[]}
716
+ */
717
+ _parseSequence(hotkey) {
718
+ return String(hotkey).split(" ").filter(part => part.length).map(part => this._parseHotkey(part))
719
+ }
720
+
721
+ /**
722
+ *
723
+ * @param {Key} hotkey Ex: Shift+s or Alt+Shift+Digit1
724
+ * @returns {KeyEvent}
725
+ */
726
+ _parseHotkey(hotkey) {
727
+ const parts = hotkey.split("+")
728
+ if (parts[parts.length - 1] === "" && parts[parts.length - 2] === "") { // handle the plus key
729
+ parts.splice(parts.length - 2, 2, "+") // `Alt++` -> ["Alt", "", ""] -> ["Alt", "+"]
730
+ }
731
+ let key = parts.pop() // the last element is the actual key, ex: Shift+Digit1 -> Digit1
732
+ key = KEY_ALIASES[key.toLowerCase()] || key
733
+
734
+ const event = {}
735
+ const modifier = name => {
736
+ const mod = MODIFIER_ALIASES[name.toLowerCase()]
737
+ return mod === "Mod" ? (this.isMac() ? "Meta" : "Control") : mod // 'Mod+s' -> Cmd+s on a Mac, Ctrl+s elsewhere
738
+ }
739
+ const lone = parts.length === 0 && modifier(key) // a lone modifier ('Shift Shift'), it is a key on its own
740
+ if (lone) {
741
+ event.key = lone
742
+ event[{ Shift: "shiftKey", Alt: "altKey", Control: "ctrlKey", Meta: "metaKey" }[lone]] = true
743
+ } else {
744
+ event[key.length === 1 ? "key" : "code"] = key // {"key": "f"} | {"code": "KeyF"}
745
+ }
746
+
747
+ parts.forEach(part => {
748
+ const mod = modifier(part)
749
+ if (mod) {
750
+ event[{ Shift: "shiftKey", Alt: "altKey", Control: "ctrlKey", Meta: "metaKey" }[mod]] = true
751
+ } else {
752
+ console.warn(`Unknown modifier at ${hotkey}`)
753
+ }
754
+ })
755
+ return event
756
+ }
757
+
758
+ /**
759
+ * Wait for the next keystroke and hand over its definition string. Lets the user pick
760
+ * their own combination. @see Hotkey.rebind
761
+ *
762
+ * @param {function} callback Receives the combination, ex: 'Ctrl+KeyJ', and the last KeyboardEvent.
763
+ * @param {?{sequence: ?boolean, onProgress: ?function}} options With `sequence`, the keystrokes keep
764
+ * being appended ('g i') until the user pauses for `sequenceTimeout` ms; `onProgress` receives what
765
+ * has been typed so far, so that the UI can display it live.
766
+ * @returns {function} Call it to cancel the recording.
767
+ * @example wh.record(combination => myHotkey.rebind(combination))
768
+ */
769
+ record(callback, { sequence = false, onProgress = null } = {}) {
770
+ const parts = []
771
+ let timer = null
772
+ let last = null
773
+ const listener = e => {
774
+ if (MODIFIER_KEYS.includes(e.key)) {
775
+ return // wait for the modified key, ex: do not record a lone Ctrl of Ctrl+j
776
+ }
777
+ e.preventDefault?.()
778
+ e.stopPropagation?.()
779
+ parts.push(Hotkey.fromEvent(e))
780
+ last = e
781
+ if (!sequence || typeof setTimeout !== "function") {
782
+ return commit()
783
+ }
784
+ // No confirmation key exists (Enter and Escape are legitimate hotkeys), so a sequence
785
+ // ends the same way it is triggered later on - by the user pausing.
786
+ clearTimeout(timer)
787
+ timer = setTimeout(commit, this.options.sequenceTimeout)
788
+ onProgress?.call(this, parts.join(" "), e) // may cancel us, hence called last
789
+ }
790
+ const commit = () => {
791
+ stop()
792
+ callback.call(this, parts.join(" "), last)
793
+ }
794
+ const stop = () => {
795
+ if (timer) {
796
+ clearTimeout(timer)
797
+ timer = null
798
+ }
799
+ document.removeEventListener("keydown", listener, true)
800
+ this._recording = null
801
+ }
802
+ this._recording?.() // only a single recording at a time
803
+ this._recording = stop
804
+ document.addEventListener("keydown", listener, true)
805
+ return stop
806
+ }
807
+
808
+ /**
809
+ * Get or set the user's remapping (original combination -> the current one).
810
+ *
811
+ * `remapping()` returns a copy, ex: {"Ctrl+KeyS": "Ctrl+KeyD"}. Ready to be sent to the server.
812
+ * `remapping(map)` applies the full state – a hotkey missing from the map goes back to its
813
+ * default combination; `null`/`{}` clears every remapping. Storage (localStorage, `onRemap`)
814
+ * is governed solely by the `remap` option.
815
+ * @param {Object.<Key, Key>} [map]
816
+ * @returns {Object.<Key, Key>|WebHotkeys}
817
+ */
818
+ remapping(map) {
819
+ if (arguments.length === 0) {
820
+ return { ...this._remap }
821
+ }
822
+ this._applyRemapping(map, true)
823
+ return this
824
+ }
825
+
826
+ /**
827
+ * @param {?Object.<Key, Key>} map
828
+ * @param {boolean} store Persist the map further on (localStorage, `onRemap`).
829
+ */
830
+ _applyRemapping(map, store) {
831
+ this._remap = Object.create(null)
832
+ const rejected = []
833
+ Object.entries(map || {}).forEach(([from, to]) => {
834
+ if (isSafeCombination(from) && isSafeCombination(to)) {
835
+ this._remap[from] = to
836
+ } else {
837
+ rejected.push(`${from} -> ${to}`)
838
+ }
839
+ })
840
+ if (rejected.length) {
841
+ console.warn("WebHotkeys.js> Dropping a remapping that is not a key combination:", rejected)
842
+ }
843
+ this.getHotkeys(false).forEach(hotkey => {
844
+ const target = this._remap[hotkey.defaultCombination] || hotkey.defaultCombination
845
+ if (target !== hotkey.combination) {
846
+ hotkey.rebind(target, false)
847
+ }
848
+ })
849
+ if (store) {
850
+ this._saveRemapping()
851
+ }
852
+ }
853
+
854
+ /** @returns {WebHotkeys} */
855
+ _loadRemapping() {
856
+ if (typeof localStorage === "undefined") { // ex: server side rendering
857
+ return this
858
+ }
859
+ let stored
860
+ try {
861
+ stored = localStorage.getItem(this._storageKey)
862
+ } catch (e) { // the storage may be disabled altogether
863
+ console.warn("WebHotkeys.js> Cannot read the stored remapping", e)
864
+ this._storageKey = null
865
+ return this
866
+ }
867
+ if (!stored) {
868
+ return this
869
+ }
870
+ const map = parseRemapping(stored)
871
+ if (!map) {
872
+ // We share the origin with the page – whatever sits here is not ours to overwrite.
873
+ console.warn(`WebHotkeys.js> localStorage['${this._storageKey}'] holds a foreign value.`
874
+ + " The remapping will not be stored; point the `remap` option to another key.")
875
+ this._storageKey = null
876
+ return this
877
+ }
878
+ this._applyRemapping(map, false)
879
+ return this
880
+ }
881
+
882
+ _saveRemapping() {
883
+ this.options.onRemap?.call(this, this.remapping())
884
+ if (this._storageKey && typeof localStorage !== "undefined") {
885
+ try {
886
+ localStorage.setItem(this._storageKey, JSON.stringify(this.remapping()))
887
+ } catch (e) {
888
+ console.warn("WebHotkeys.js> Cannot store the remapping", e)
889
+ }
890
+ }
891
+ }
892
+
893
+ /**
894
+ * Looping over the items (yt tracks list, fb notification list...)
895
+ * ∀ page can use this list helper that handles different sorts of menus.
896
+ *
897
+ * @param {String} [query='div'] DOM selector of li or anchors
898
+ * @param {ListOptions} [options]
899
+ * @param {String} [options.current=':focus'] Selector describing the currently selected item.
900
+ * @param {?String} [options.css=null] Injected via `wh._insertCss` as `query + current + css`.
901
+ * @param {boolean} [options.wrap=false] Jump from the last item to the first one and back.
902
+ * @param {boolean} [options.scroll=true] Scroll the newly selected item into the view.
903
+ * @param {?function} [options.onChange=null] Called with (newEl, oldEl) before the change; returning
904
+ * false cancels it.
905
+ * @param {?function} [options.onChanged=null] Called with (newEl) once the change has happened.
906
+ * @param {boolean} [options.upDown=false] Grab ArrowUp/ArrowDown for this listing.
907
+ * @param {boolean} [options.homeEnd=false] Grab Home/End for this listing.
908
+ * @param {boolean|number} [options.typeahead=false] Enable typing the first letters of an item to
909
+ * select it; `true` uses an 800 ms timeout, a number sets a custom one (ms).
910
+ * @param {?Action} [options.scope=null] Restricts the upDown/homeEnd grabs, @see WebHotkeys.grab.
911
+ * Give each list a distinct scope so several lists on the same page don't fight over the arrow keys.
912
+ * @returns {_List}
913
+ *
914
+ * @example wh.list("ul#list li, #div a", { upDown: true }) cycles amongst li-s and a-s at once, using the default (:focus) selector.
915
+ */
916
+ list(query, options = {}) {
917
+ const list = new _List(this)
918
+ list._configure(query, options)
919
+ this._lists.push(list)
920
+ return list;
921
+ }
922
+
923
+ /**
924
+ * 2D keyboard navigation over a table (rows × cells within a row) - Up/Down keep the column and
925
+ * move between rows, Left/Right move between cells of the current row.
926
+ *
927
+ * Every call returns its own independent instance, so several tables can coexist on the same
928
+ * page - give each a distinct `scope` so their arrow keys do not fight over the focus.
929
+ *
930
+ * @param {String} rowQuery DOM selector for the rows, ex: `"table.dbtable tr"`.
931
+ * @param {String} cellQuery DOM selector for the cells within a row, ex: `"td"`.
932
+ * @param {GridOptions} [options]
933
+ * @param {String} [options.current=':focus'] Selector describing the currently selected cell.
934
+ * @param {boolean} [options.wrap=false] Wrap around row/column edges instead of stopping there.
935
+ * @param {boolean} [options.scroll=true] Scroll the newly selected cell into the view.
936
+ * @param {?function} [options.onChange=null] Called with (newEl, oldEl) before the change; returning
937
+ * false cancels it.
938
+ * @param {?function} [options.onChanged=null] Called with (newEl) once the change has happened.
939
+ * @param {?Action} [options.scope=null] Restricts the Up/Down/Left/Right grabs, @see WebHotkeys.grab.
940
+ * @returns {_Grid}
941
+ *
942
+ * @example const rows = wh.grid("table.dbtable tr", "td", { scope: "table.dbtable", wrap: true })
943
+ */
944
+ grid(rowQuery, cellQuery, options = {}) {
945
+ return new _Grid(this, rowQuery, cellQuery, options)
946
+ }
947
+
948
+ /**
949
+ * Is the user typing right now? Then a plain letter or a caret movement is none of our business.
950
+ * @param {KeyEvent} e
951
+ * @param {?HTMLElement} active
952
+ * @returns {boolean}
953
+ */
954
+ _isTextContext(e, active) {
955
+ return !e.altKey
956
+ && !e.metaKey
957
+ && (// this is a mere letter (not Escape, F1... which anticipate a hotkey)
958
+ e.key?.length === 1
959
+ // or a text editing keys that can take use of Ctrl (Left and Ctrl+Left is text editing)
960
+ || ["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown", "Home", "End", "Delete", "Backspace"].includes(e.key)
961
+ // or a text editing key that cannot take use of Ctrl (Enter is text editing, Ctrl+Enter is not)
962
+ || ["Tab", "Enter"].includes(e.key) && !e.ctrlKey
963
+ )
964
+ // We are in a text editing context. Either a form tag like INPUT or within an editable element.
965
+ && !!active
966
+ && (isTextInput(active) || active.contentEditable === "true")
967
+ }
968
+
969
+ /**
970
+ * Hotkeys possibly matching the keystroke, the most recently grabbed first.
971
+ *
972
+ * First check whether a `code` hotkey was defined (`Alt+Digit1`).
973
+ * If not, try its `key` property (`Alt+1` (EN) or `Alt++` (CZ)).
974
+ * If the key is a one-char but-not-letter sign ( -> not affectable by Shift), we ignore the Shift state.
975
+ * Ex: To access the question mark on eng and cz keyboard, we have to hit Shift.
976
+ * However, the developper sets the hotkey as "?", not "Shift+?".
977
+ * If the key is a one-char upper-letter ( -> for sure affected by Shift), we convert it to the lower case.
978
+ * Ex: Grabbed combination "Shift+Alt+l" would always produce "Shift+Alt+L".
979
+ * Finally, the numpad falls back to the main row (`Numpad1` -> `Digit1`), unless claimed explicitly.
980
+ * @param {KeyEvent} e
981
+ * @returns {Hotkey[]}
982
+ */
983
+ _candidates(e) {
984
+ const states = []
985
+ if (e.code) {
986
+ states.push(e.code + Hotkey.mod_state(e))
987
+ }
988
+ if (e.key) {
989
+ const oneChar = e.key.length === 1
990
+ states.push((oneChar && /[A-Z]/.test(e.key) ? e.key.toLowerCase() : e.key)
991
+ + Hotkey.mod_state(e, oneChar && !/[A-Za-z]/.test(e.key)))
992
+ }
993
+ if (CODE_ALIASES[e.code]) { // shadow combination, tried only when nothing else matched
994
+ states.push(CODE_ALIASES[e.code] + Hotkey.mod_state(e))
995
+ }
996
+ return states.flatMap(state => this._hotkeys[state]?.filter(hotkey => hotkey.enabled) || [])
997
+ // A sequence is more specific than a plain hotkey of the same last key ('g i' beats 'i').
998
+ // The sort is stable, so hotkeys of the same length keep the most-recently-grabbed-first order.
999
+ .sort((a, b) => b.sequence.length - a.sequence.length)
1000
+ }
1001
+
1002
+ /**
1003
+ * Have the preceding keystrokes been the beginning of this sequence?
1004
+ * @param {Hotkey} hotkey
1005
+ * @param {number} now
1006
+ * @returns {boolean}
1007
+ */
1008
+ _matchesSequence(hotkey, now) {
1009
+ const specs = hotkey.sequence.slice(0, -1) // the last one is the very keystroke being processed
1010
+ let i = this._buffer.length - 1
1011
+ for (let j = specs.length - 1; j >= 0; j--) {
1012
+ const spec = specs[j]
1013
+ // Hitting Shift+I registers a lone Shift keydown first. Skip such noise,
1014
+ // unless the step itself is a lone modifier (the 'Shift Shift' double tap).
1015
+ while (i >= 0 && !MODIFIER_KEYS.includes(spec.key) && MODIFIER_KEYS.includes(this._buffer[i].event.key)) {
1016
+ i--
1017
+ }
1018
+ const entry = this._buffer[i--]
1019
+ if (!entry || now - entry.time > this.options.sequenceTimeout || !Hotkey.match(spec, entry.event)) {
1020
+ return false
1021
+ }
1022
+ }
1023
+ return true
1024
+ }
1025
+
1026
+ /** @returns {boolean} The buffer is a beginning of some sequence – swallow the key and wait for the rest. */
1027
+ _pendingSequence(now) {
1028
+ return this.getHotkeys().some(hotkey => hotkey.sequence.length > this._buffer.length
1029
+ && this._buffer.every((entry, i) => now - entry.time <= this.options.sequenceTimeout
1030
+ && Hotkey.match(hotkey.sequence[i], entry.event)))
1031
+ }
1032
+
1033
+ /**
1034
+ * @param {KeyEvent} e The keystroke under consideration - not pushed into `_buffer` yet.
1035
+ * @param {number} now
1036
+ * @returns {boolean} Would `_buffer` plus `e` still be a live prefix of some longer registered sequence?
1037
+ * (Ex: a plain 'g' hotkey next to a grabbed 'g i' sequence - 'g' alone must not fire it right away.)
1038
+ */
1039
+ _matchesPrefix(e, now) {
1040
+ return this.getHotkeys().some(hotkey => hotkey.sequence.length > this._buffer.length + 1
1041
+ && this._buffer.every((entry, i) => now - entry.time <= this.options.sequenceTimeout
1042
+ && Hotkey.match(hotkey.sequence[i], entry.event))
1043
+ && Hotkey.match(hotkey.sequence[this._buffer.length], e))
1044
+ }
1045
+
1046
+ /**
1047
+ * A plain hotkey whose key also begins a longer registered sequence must not fire right away -
1048
+ * the user may still be typing that sequence. Swallow it and wait `sequenceTimeout` ms; if nothing
1049
+ * continues the sequence by then, run the plain hotkey after all.
1050
+ * @param {Hotkey} hotkey
1051
+ * @param {KeyEvent} e
1052
+ */
1053
+ _deferPlainHotkey(hotkey, e) {
1054
+ this._deferred = {
1055
+ hotkey, event: e,
1056
+ timer: setTimeout(() => this._settleDeferred(true), this.options.sequenceTimeout),
1057
+ }
1058
+ }
1059
+
1060
+ /**
1061
+ * Resolve a pending `_deferPlainHotkey` - either because its sequenceTimeout elapsed, because
1062
+ * the next keystroke settled things one way or the other, or because the instance is being destroyed.
1063
+ * @param {boolean} fire Run the deferred hotkey (nothing continued its sequence), or just drop it
1064
+ * (some hotkey - typically the sequence it shadows - fired instead).
1065
+ */
1066
+ _settleDeferred(fire) {
1067
+ const deferred = this._deferred
1068
+ if (!deferred) {
1069
+ return
1070
+ }
1071
+ clearTimeout(deferred.timer)
1072
+ this._deferred = null
1073
+ if (fire) {
1074
+ this._fireHotkey(deferred.hotkey, deferred.event)
1075
+ }
1076
+ }
1077
+
1078
+ /**
1079
+ * Actually run a matched hotkey's action. Scope is (re)checked here, at fire time, since a
1080
+ * deferred plain hotkey (see `_deferPlainHotkey`) may run well after its keystroke happened.
1081
+ * @param {Hotkey} hotkey
1082
+ * @param {KeyEvent} e
1083
+ * @returns {boolean} Whether the hotkey fired. False lets the caller try the next candidate.
1084
+ */
1085
+ _fireHotkey(hotkey, e) {
1086
+ const { action, element, scope } = hotkey
1087
+ const active = this.activeElement()
1088
+ // check we are in an allowed scope (the focused element has hotkey.scope for the ancestor)
1089
+ if (scope && !( // The scope is either a selector or a function or an HTMLElement
1090
+ isString(scope) ? active?.closest?.(scope)
1091
+ : (scope instanceof Function ? scope.call(this, active, e)
1092
+ : scope.contains?.(active)))) {
1093
+ return false // not allowed scope
1094
+ }
1095
+
1096
+ let result
1097
+ if (element) {
1098
+ if (element.disabled || !isVisible(element)) {
1099
+ return false // action is a disabled or hidden HTMLElement, try next shorcut
1100
+ }
1101
+ // note that result is always none
1102
+ this._act(element)
1103
+ } else {
1104
+ result = action.call(this, e)
1105
+ }
1106
+
1107
+ if (result === false) {
1108
+ return false // custom method failed, try next hotkey
1109
+ }
1110
+
1111
+ this._buffer.length = 0 // the sequence has been consumed
1112
+ this.options.onTrigger?.call(this, hotkey, e)
1113
+
1114
+ // prevent default behaviour (ex: Ctrl+L going to the address bar)
1115
+ e.stopPropagation?.() // the method may not be available in a crafted event
1116
+ e.preventDefault?.()
1117
+ return true
1118
+ }
1119
+
1120
+ /**
1121
+ *
1122
+ * @param {KeyEvent} e
1123
+ * @returns {undefined|boolean}
1124
+ */
1125
+ _trigger(e) {
1126
+ if (this._destroyed) {
1127
+ return
1128
+ }
1129
+ if (this._recording) {
1130
+ return // `record` is capturing the keystroke; even Escape and F1 belong to it
1131
+ }
1132
+ if (this._help?.open) { // the help dialog swallows the page hotkeys
1133
+ if (["Escape", "F1"].some(key => e.key === key || e.code === key)) {
1134
+ this._hideHelp()
1135
+ e.preventDefault?.()
1136
+ e.stopPropagation?.()
1137
+ }
1138
+ return
1139
+ }
1140
+ this._hideHints() // any keystroke dismisses the badges (the hotkey below still runs)
1141
+
1142
+ const active = this.activeElement()
1143
+ const { ignore } = this.options
1144
+ if (ignore && active && (isString(ignore) ? active.closest?.(ignore) : ignore.call(this, active, e))) {
1145
+ return
1146
+ }
1147
+ // an input field has precedence over shorcuts
1148
+ // Ex: arrow hotkeys must not work, these control text caret
1149
+ const typing = this._isTextContext(e, active)
1150
+ const now = Date.now()
1151
+
1152
+ for (const hotkey of this._candidates(e)) {
1153
+ if (typing && !hotkey.allowInput) {
1154
+ continue
1155
+ }
1156
+ if (hotkey.sequence.length > 1 && !this._matchesSequence(hotkey, now)) {
1157
+ continue // the preceding keystrokes were something else
1158
+ }
1159
+ if (hotkey.sequence.length === 1 && this._matchesPrefix(e, now)) {
1160
+ this._deferPlainHotkey(hotkey, e)
1161
+ continue // let the code below swallow the key and wait to see if the sequence completes
1162
+ }
1163
+
1164
+ if (this._fireHotkey(hotkey, e)) {
1165
+ this._settleDeferred(false) // a hotkey just fired (likely the sequence this deferred one shadows) - drop it
1166
+ return true
1167
+ }
1168
+ }
1169
+
1170
+ if (typing) {
1171
+ return
1172
+ }
1173
+ this._buffer.push({ event: e, time: now })
1174
+ while (this._buffer.length && (this._buffer.length > 8 || now - this._buffer[0].time > this.options.sequenceTimeout)) {
1175
+ this._buffer.shift()
1176
+ }
1177
+ if (this._pendingSequence(now)) {
1178
+ e.preventDefault?.() // ex: 'g' of the 'g i' sequence must not scroll the page
1179
+ e.stopPropagation?.()
1180
+ return
1181
+ }
1182
+ this._buffer.length = 0 // no sequence may start here, forget the history
1183
+ this._settleDeferred(true) // ...including any deferred plain hotkey: nothing continued it, so it wins now
1184
+ this.options.onMiss?.call(this, e)
1185
+ }
1186
+
1187
+ /**
1188
+ * What a linked element does when its hotkey fires. Overridable by [data-hotkey-action].
1189
+ * @param {HTMLElement} element
1190
+ */
1191
+ _act(element) {
1192
+ const mode = element.getAttribute?.(this.options.actionAttribute) || defaultAction(element)
1193
+ switch (mode) {
1194
+ case "focus": return element.focus()
1195
+ case "none": return
1196
+ case "toggle":
1197
+ if (element.tagName === "DETAILS") {
1198
+ element.open = !element.open
1199
+ } else if (element.type === "checkbox") {
1200
+ element.checked = !element.checked
1201
+ element.dispatchEvent?.(new Event("change", { bubbles: true }))
1202
+ } else { // a radio lands here too: clicking checks it *and* unchecks its siblings, flipping `checked` would not
1203
+ this._activate(element)
1204
+ }
1205
+ return
1206
+ default: return this._activate(element)
1207
+ }
1208
+ }
1209
+
1210
+ /**
1211
+ * Click the element the way the user would.
1212
+ * @param {HTMLElement} element
1213
+ */
1214
+ _activate(element) {
1215
+ element.click()
1216
+ if (element.type === "radio") {
1217
+ // A real mouse click focuses through its mousedown; the synthetic click() does not.
1218
+ // Without the focus the arrows could not go on choosing within the group.
1219
+ element.focus?.()
1220
+ }
1221
+ }
1222
+
1223
+ /**
1224
+ *
1225
+ * @param {Key|KeyEvent} hotkey Ex: 'Ctrl+j' or a sequence 'g i' or a KeyEvent-like object.
1226
+ */
1227
+ simulate(hotkey) {
1228
+ if (hotkey.constructor === String) {
1229
+ return this._parseSequence(hotkey).map(event => this._trigger(completeSimulatedEvent(event))).pop()
1230
+ }
1231
+ return this._trigger(completeSimulatedEvent(hotkey))
1232
+ }
1233
+
1234
+ //
1235
+ // Visual helpers
1236
+ //
1237
+
1238
+ /**
1239
+ * Toggle the help dialog. Uses a modal dialog, falls back to an alert.
1240
+ * @param {?boolean} show `null` toggles, true/false forces the state.
1241
+ * @returns {WebHotkeys}
1242
+ */
1243
+ toggleHelp(show = null) {
1244
+ return (show ?? !this._help?.open) ? this._showHelp() : this._hideHelp()
1245
+ }
1246
+
1247
+ /** @returns {WebHotkeys} */
1248
+ _showHelp() {
1249
+ const dialog = this.options.help === "dialog" && createEl("dialog")
1250
+ if (!dialog?.showModal) {
1251
+ typeof alert === "function" ? alert(this.getText()) : console.log(this.getText())
1252
+ return this
1253
+ }
1254
+ this._hideHelp()
1255
+ this._injectStyle()
1256
+ dialog.className = "webhotkeys-dialog"
1257
+
1258
+ const head = createEl("div", "webhotkeys-head", dialog)
1259
+ createEl("strong", "", head).textContent = "Keyboard shortcuts"
1260
+ const filter = createEl("input", "webhotkeys-filter", head)
1261
+ filter.type = "search"
1262
+ filter.placeholder = "Filter…"
1263
+ const close = createEl("button", "webhotkeys-close", head)
1264
+ close.textContent = "✕"
1265
+ close.onclick = () => this._hideHelp()
1266
+
1267
+ const body = createEl("div", "webhotkeys-body", dialog)
1268
+ this.getGroups().forEach(({ name, hotkeys }) => {
1269
+ if (name) {
1270
+ createEl("h3", "", body).textContent = name
1271
+ }
1272
+ hotkeys.forEach(hotkey => {
1273
+ const row = createEl("div", "webhotkeys-row", body)
1274
+ const key = createEl(this.options.remap ? "button" : "kbd", "webhotkeys-key", row)
1275
+ key.textContent = hotkey.clue
1276
+ createEl("span", "webhotkeys-hint", row).textContent = hotkey.hint
1277
+ if (this.options.remap) {
1278
+ this._makeEditable(row, key, hotkey)
1279
+ }
1280
+ })
1281
+ })
1282
+ if (this.options.remap) {
1283
+ createEl("p", "webhotkeys-note", body).textContent = "Click a combination to remap it."
1284
+ }
1285
+ filter.oninput = () => {
1286
+ const needle = filter.value.toLowerCase()
1287
+ body.querySelectorAll(".webhotkeys-row").forEach(row => {
1288
+ row.style.display = row.textContent.toLowerCase().includes(needle) ? "" : "none"
1289
+ })
1290
+ }
1291
+
1292
+ document.body.appendChild(dialog)
1293
+ this._help = dialog
1294
+ dialog.addEventListener("close", () => this._hideHelp())
1295
+ // Escape while recording belongs to the recording, not to the dialog. Our keydown listener
1296
+ // cannot stop this one – the browser closes a <dialog> through the 'cancel' event.
1297
+ dialog.addEventListener("cancel", e => this._recording && e.preventDefault?.())
1298
+ dialog.showModal()
1299
+ return this
1300
+ }
1301
+
1302
+ /**
1303
+ * Turn a help row into a remappable one: click the combination, press your own.
1304
+ * @param {HTMLElement} row
1305
+ * @param {HTMLElement} key The button displaying the combination.
1306
+ * @param {Hotkey} hotkey
1307
+ */
1308
+ _makeEditable(row, key, hotkey) {
1309
+ const PROMPT = "Click and press your own combination"
1310
+ key.type = "button"
1311
+ const reset = createEl("button", "webhotkeys-reset", row)
1312
+ reset.textContent = "↺"
1313
+ reset.title = "Back to the default combination"
1314
+
1315
+ /** @param {boolean} keepFocus Stay on the button the user has just used, ready for another go. */
1316
+ const refresh = (keepFocus = false) => {
1317
+ key.textContent = hotkey.clue
1318
+ key.className = "webhotkeys-key"
1319
+ const changed = hotkey.combination !== hotkey.defaultCombination
1320
+ reset.style.display = changed ? "" : "none"
1321
+ // The whole list is right here – tell the user straight away that somebody else has the key.
1322
+ const clash = this.getConflicts().find(c => c.combination === hotkey.combination)
1323
+ row.className = "webhotkeys-row" + (clash ? " webhotkeys-clash" : "")
1324
+ key.title = clash
1325
+ ? `Also used by: ${clash.hotkeys.filter(h => h !== hotkey).map(h => h.hint).join(", ")}`
1326
+ : PROMPT
1327
+ if (keepFocus) {
1328
+ key.focus?.() // the reset button may have just disappeared, the focus would fall to the body
1329
+ }
1330
+ }
1331
+ refresh()
1332
+
1333
+ reset.onclick = () => {
1334
+ hotkey.rebind()
1335
+ refresh(true)
1336
+ }
1337
+ key.onclick = () => {
1338
+ if (this._recording) { // a second click cancels
1339
+ return this._recording()
1340
+ }
1341
+ key.className = "webhotkeys-key webhotkeys-recording"
1342
+ key.textContent = "…"
1343
+ this.record(combination => {
1344
+ if (combination !== "Escape") {
1345
+ hotkey.rebind(combination)
1346
+ }
1347
+ refresh(true)
1348
+ }, {
1349
+ sequence: true,
1350
+ onProgress: partial => {
1351
+ if (partial.split(" ").pop() === "Escape") { // cancel, do not wait for the timeout
1352
+ this._recording?.()
1353
+ return refresh(true)
1354
+ }
1355
+ key.textContent = partial + " …"
1356
+ }
1357
+ })
1358
+ }
1359
+ }
1360
+
1361
+ /** @returns {WebHotkeys} */
1362
+ _hideHelp() {
1363
+ this._recording?.()
1364
+ if (this._help) {
1365
+ const dialog = this._help
1366
+ this._help = null // prevent the 'close' listener recursion
1367
+ dialog.close?.()
1368
+ dialog.remove?.()
1369
+ }
1370
+ return this
1371
+ }
1372
+
1373
+ /**
1374
+ * Badge every visible element having a hotkey with its combination, the Vimium way.
1375
+ * @returns {WebHotkeys}
1376
+ */
1377
+ _showHints() {
1378
+ if (typeof document === "undefined" || !document.body) {
1379
+ return this
1380
+ }
1381
+ this._hideHints()
1382
+ this._injectStyle()
1383
+ const layer = createEl("div", "webhotkeys-hints")
1384
+ this.getHotkeys().forEach(hotkey => {
1385
+ const el = hotkey.element
1386
+ if (!el || !isVisible(el)) {
1387
+ return
1388
+ }
1389
+ const rect = el.getBoundingClientRect?.()
1390
+ if (!rect || (!rect.width && !rect.height)) {
1391
+ return
1392
+ }
1393
+ const badge = createEl("kbd", "webhotkeys-badge", layer)
1394
+ badge.textContent = hotkey.clue
1395
+ badge.style.left = `${rect.left + window.scrollX}px`
1396
+ badge.style.top = `${rect.top + window.scrollY}px`
1397
+ })
1398
+ document.body.appendChild(layer)
1399
+ this._hints = layer
1400
+ this._dismissHints = () => this._hideHints()
1401
+ window.addEventListener("scroll", this._dismissHints, { passive: true, once: true })
1402
+ window.addEventListener("resize", this._dismissHints, { once: true })
1403
+ return this
1404
+ }
1405
+
1406
+ /** @returns {WebHotkeys} */
1407
+ _hideHints() {
1408
+ if (this._hints) {
1409
+ this._hints.remove?.()
1410
+ this._hints = null
1411
+ window.removeEventListener("scroll", this._dismissHints)
1412
+ window.removeEventListener("resize", this._dismissHints)
1413
+ }
1414
+ return this
1415
+ }
1416
+
1417
+ /**
1418
+ * Toggle the visual hint badges over the elements having a hotkey.
1419
+ * @param {?boolean} show `null` toggles, true/false forces the state.
1420
+ * @returns {WebHotkeys}
1421
+ */
1422
+ toggleHints(show = null) {
1423
+ return (show ?? !this._hints) ? this._showHints() : this._hideHints()
1424
+ }
1425
+
1426
+ /** The stylesheet for the help dialog and the hint badges. Injected on the first use only. */
1427
+ _injectStyle() {
1428
+ if (this._style || typeof document === "undefined" || !document.head) {
1429
+ return
1430
+ }
1431
+ this._style = createEl("style")
1432
+ this._style.textContent = `
1433
+ .webhotkeys-dialog { border: 0; border-radius: .5em; padding: 0; max-width: 40em; width: 90%; max-height: 80vh;
1434
+ box-shadow: 0 .5em 2em rgba(0,0,0,.35); font: inherit; background: Canvas; color: CanvasText; }
1435
+ .webhotkeys-dialog::backdrop { background: rgba(0,0,0,.4); }
1436
+ .webhotkeys-head { display: flex; gap: .5em; align-items: center; padding: .75em 1em; border-bottom: 1px solid rgba(128,128,128,.3); }
1437
+ .webhotkeys-head strong { flex: 0 0 auto; }
1438
+ .webhotkeys-filter { flex: 1 1 auto; min-width: 4em; padding: .25em .5em; font: inherit; }
1439
+ .webhotkeys-close { flex: 0 0 auto; cursor: pointer; border: 0; background: transparent; font: inherit; }
1440
+ .webhotkeys-body { padding: .5em 1em 1em; overflow: auto; max-height: 65vh; }
1441
+ .webhotkeys-body h3 { margin: 1em 0 .25em; font-size: 1em; opacity: .7; }
1442
+ .webhotkeys-row { display: flex; gap: .75em; padding: .15em 0; }
1443
+ .webhotkeys-key { flex: 0 0 9em; text-align: right; }
1444
+ kbd.webhotkeys-key, button.webhotkeys-key { display: inline-block; font-family: monospace; font-size: .85em;
1445
+ padding: .15em .5em; border: 1px solid rgba(128,128,128,.4); border-radius: .3em; background: rgba(128,128,128,.12); }
1446
+ /* The remappable combination is a <button>; it must still read as the plain kbd badge above. */
1447
+ button.webhotkeys-key { color: inherit; cursor: pointer; }
1448
+ button.webhotkeys-key:hover { background: rgba(128,128,128,.22); }
1449
+ button.webhotkeys-key:focus { outline: 2px solid currentColor; outline-offset: 1px; }
1450
+ .webhotkeys-recording { background: #ffd76e; color: #222; }
1451
+ .webhotkeys-hint { flex: 1 1 auto; }
1452
+ .webhotkeys-clash .webhotkeys-key { color: #c0392b; }
1453
+ .webhotkeys-reset { flex: 0 0 auto; border: 0; background: transparent; color: inherit; cursor: pointer; opacity: .6; }
1454
+ .webhotkeys-note { margin: 1.5em 0 0; font-style: italic; font-size: .9em; opacity: .6; }
1455
+ .webhotkeys-hints { position: absolute; inset: 0; pointer-events: none; z-index: 2147483000; }
1456
+ .webhotkeys-badge { position: absolute; transform: translate(-30%, -50%); pointer-events: none;
1457
+ background: #ffd76e; color: #222; border: 1px solid #b98d00; border-radius: .25em;
1458
+ padding: 0 .3em; font: bold 11px/1.5 monospace; white-space: nowrap; }`
1459
+ document.head.appendChild(this._style)
1460
+ }
1461
+
1462
+ /**
1463
+ * Easily get the stylesheet on the fly.
1464
+ *
1465
+ * Based on: https://davidwalsh.name/add-rules-stylesheets
1466
+ *
1467
+ * @return {CSSStyleSheet}
1468
+ */
1469
+ getSheet() {
1470
+ if (typeof this._sheet === "undefined") {
1471
+ this._sheet = (() => {
1472
+ // Create the <style> tag
1473
+ const style = document.createElement("style");
1474
+
1475
+ // Add a media (and/or media query) here if you'd like!
1476
+ // style.setAttribute("media", "screen")
1477
+ // style.setAttribute("media", "only screen and (max-width : 1024px)")
1478
+
1479
+ // WebKit hack :(
1480
+ style.appendChild(document.createTextNode(""));
1481
+
1482
+ // Add the <style> this to the page
1483
+ document.head.appendChild(style);
1484
+ this._userStyle = style
1485
+
1486
+ return style.sheet;
1487
+ })();
1488
+ }
1489
+ return this._sheet;
1490
+ }
1491
+
1492
+ /**
1493
+ * Easily add to the stylesheet on the fly. Internal – used by `_List`'s `css` option.
1494
+ * @param {string} cssRule
1495
+ * @returns {undefined}
1496
+ */
1497
+ _insertCss(cssRule) {
1498
+ this.getSheet().insertRule(cssRule);
1499
+ }
1500
+ }
1501
+
1502
+
1503
+ /**
1504
+ * Options object accepted by `WebHotkeys.list`.
1505
+ * @typedef {Object} ListOptions
1506
+ * @property {String} [current=':focus'] Selector describing the currently selected item.
1507
+ * @property {?String} [css=null] Injected via `wh._insertCss` as `query + current + css`.
1508
+ * @property {boolean} [wrap=false] Jump from the last item to the first one and back.
1509
+ * @property {boolean} [scroll=true] Scroll the newly selected item into the view.
1510
+ * @property {?function} [onChange=null] Called with (newEl, oldEl) before the change; returning false cancels it.
1511
+ * @property {?function} [onChanged=null] Called with (newEl) once the change has happened.
1512
+ * @property {boolean} [upDown=false] Grab ArrowUp/ArrowDown for this listing.
1513
+ * @property {boolean} [homeEnd=false] Grab Home/End for this listing.
1514
+ * @property {boolean|number} [typeahead=false] `true` uses an 800 ms timeout, a number a custom one (ms).
1515
+ */
1516
+
1517
+ /**
1518
+ * @see WebHotkeys.list
1519
+ */
1520
+ class _List {
1521
+ constructor(_wh) {
1522
+ this.query = "div"
1523
+ this.currentSelector = ":focus"
1524
+ this.onChange = null
1525
+ this.onChanged = null
1526
+ this.selected = null
1527
+ this._wh = _wh
1528
+ /** @type {boolean} Jump from the last item to the first one and back. */
1529
+ this.wrap = false
1530
+ /** @type {boolean} Scroll the newly selected item into the view. */
1531
+ this.scroll = true
1532
+ /** @type {?Action} Restricts the upDown/homeEnd grabs, @see WebHotkeys.grab. */
1533
+ this.scope = null
1534
+ /** @type {Hotkey[]} The upDown/homeEnd hotkeys, so `destroy()` can undo just this instance. */
1535
+ this._hotkeys = []
1536
+ }
1537
+
1538
+ /**
1539
+ * Apply the options given to `WebHotkeys.list`. @see WebHotkeys.list
1540
+ * @param {String} [query]
1541
+ * @param {ListOptions} options
1542
+ */
1543
+ _configure(query, {
1544
+ current, css = null, wrap, scroll, onChange, onChanged, scope, upDown = false, homeEnd = false, typeahead = false,
1545
+ } = {}) {
1546
+ if (query !== undefined) {
1547
+ this.query = query
1548
+ }
1549
+ if (current !== undefined) {
1550
+ this.currentSelector = current
1551
+ if (css) {
1552
+ this._wh._insertCss(this.query + this.currentSelector + css)
1553
+ }
1554
+ }
1555
+ if (wrap !== undefined) {
1556
+ this.wrap = wrap
1557
+ }
1558
+ if (scroll !== undefined) {
1559
+ this.scroll = scroll
1560
+ }
1561
+ if (onChange !== undefined) {
1562
+ this.onChange = onChange
1563
+ }
1564
+ if (onChanged !== undefined) {
1565
+ this.onChanged = onChanged
1566
+ }
1567
+ if (scope !== undefined) {
1568
+ this.scope = scope
1569
+ }
1570
+ if (upDown) {
1571
+ this._handleUpDown()
1572
+ }
1573
+ if (homeEnd) {
1574
+ this._handleHomeEnd()
1575
+ }
1576
+ if (typeahead) {
1577
+ this._handleTypeahead(typeof typeahead === "number" ? typeahead : 800)
1578
+ }
1579
+ }
1580
+
1581
+ /** Macro: Arrows UP/DOWN grabbed for listing instead of `this.list().goPrev/goNext` */
1582
+ _handleUpDown() {
1583
+ this._hotkeys.push(
1584
+ this._wh.grab("ArrowUp", "Lists up", () => this.goPrev(), this.scope),
1585
+ this._wh.grab("ArrowDown", "Lists down", () => this.goNext(), this.scope),
1586
+ )
1587
+ }
1588
+
1589
+ /** Macro: Home/End jump to the first/last item. */
1590
+ _handleHomeEnd() {
1591
+ this._hotkeys.push(
1592
+ this._wh.grab("Home", "Lists first", () => this.goFirst(), this.scope),
1593
+ this._wh.grab("End", "Lists last", () => this.goLast(), this.scope),
1594
+ )
1595
+ }
1596
+
1597
+ /**
1598
+ * Type the first letters of an item to select it (the classic listbox behaviour).
1599
+ * @param {number} timeout Milliseconds before the typed prefix is forgotten.
1600
+ */
1601
+ _handleTypeahead(timeout = 800) {
1602
+ let prefix = ""
1603
+ let last = 0
1604
+ this._typeahead = e => {
1605
+ if (e.key?.length !== 1 || e.ctrlKey || e.altKey || e.metaKey || this._wh._isTextContext(e, this._wh.activeElement())) {
1606
+ return
1607
+ }
1608
+ const now = Date.now()
1609
+ prefix = (now - last > timeout ? "" : prefix) + e.key.toLowerCase()
1610
+ last = now
1611
+ if (this.selectByPrefix(prefix)) {
1612
+ e.preventDefault()
1613
+ e.stopPropagation()
1614
+ }
1615
+ }
1616
+ document.addEventListener("keydown", this._typeahead, true)
1617
+ }
1618
+
1619
+ /**
1620
+ * @param {string} prefix
1621
+ * @returns {boolean} Something has been selected.
1622
+ */
1623
+ selectByPrefix(prefix) {
1624
+ this._loadSiblings()
1625
+ const found = Array.from(this.items || []).find(el => (el.innerText || el.textContent || "").trim().toLowerCase().startsWith(prefix))
1626
+ if (found) {
1627
+ this._change(found, this.selected)
1628
+ }
1629
+ return !!found
1630
+ }
1631
+
1632
+ /** Detach the typeahead listener and the upDown/homeEnd grabs of this instance. */
1633
+ destroy() {
1634
+ if (this._typeahead) {
1635
+ document.removeEventListener("keydown", this._typeahead, true)
1636
+ this._typeahead = null
1637
+ }
1638
+ this._hotkeys.forEach(hotkey => hotkey?.remove())
1639
+ this._hotkeys = []
1640
+ return this
1641
+ }
1642
+
1643
+ /**
1644
+ * Set .next, .prev, .selected
1645
+ * @param {int} steps Default: 1. Distance between .next and .selected.
1646
+ * @returns {boolean}
1647
+ */
1648
+ _loadSiblings(steps = 1) {
1649
+ // check if there is a selected item already
1650
+ this.items = document.querySelectorAll(this.query);
1651
+
1652
+
1653
+ if (!this.items.length) {
1654
+ //if (this._debug) {
1655
+ // console.warn("WebHotkeys.js list: Can't list items on query: " + this.query);
1656
+ //}
1657
+ return false;
1658
+ }
1659
+ for (let el of document.querySelectorAll(this.query)) {
1660
+ if (el.matches(this.currentSelector)) {
1661
+ this.selected = el;
1662
+ }
1663
+ }
1664
+
1665
+ if (this.selected) {// item already selected
1666
+ const count = this.items.length
1667
+ for (let i = 0; i < count; i++) { // loops the items
1668
+ if (this.selected.isSameNode(this.items[i])) { // this is our selected item in the DOM
1669
+ this.prev = this.items[this.wrap ? _wrapIndex(i, -steps, count) : _clampIndex(i, -steps, count)];
1670
+ this.next = this.items[this.wrap ? _wrapIndex(i, steps, count) : _clampIndex(i, steps, count)];
1671
+ return true;
1672
+ }
1673
+ }
1674
+ } else {
1675
+ this.prev = this.next = this.selected = this.items[0];
1676
+ return true;
1677
+ }
1678
+ return false;
1679
+ }
1680
+
1681
+ /**
1682
+ * The currently selected element. (Even if it changed since ex: last go call due to another user activity on page.)
1683
+ * @type {null|HTMLElement}
1684
+ */
1685
+ get current() {
1686
+ this._loadSiblings()
1687
+ return this.selected
1688
+ }
1689
+
1690
+ set current(el) {
1691
+ if (this._loadSiblings()) {
1692
+ this._change(el);
1693
+ if (!this._loadSiblings()) {
1694
+ console.error("WebHotkeys.js> Could not change successfully to:", el);
1695
+ }
1696
+ }
1697
+ }
1698
+
1699
+ goNext(steps) {
1700
+ return this._loadSiblings(steps) ? this._change(this.next, this.selected) : false
1701
+ }
1702
+
1703
+ goPrev(steps) {
1704
+ return this._loadSiblings(steps) ? this._change(this.prev, this.selected) : false
1705
+ }
1706
+
1707
+ goFirst() {
1708
+ return this._loadSiblings() ? this._change(this.items[0], this.selected) : false
1709
+ }
1710
+
1711
+ goLast() {
1712
+ return this._loadSiblings() ? this._change(this.items[this.items.length - 1], this.selected) : false
1713
+ }
1714
+
1715
+ /**
1716
+ *
1717
+ * @param {boolean} forward
1718
+ * @param {number} steps
1719
+ * @returns {boolean}
1720
+ */
1721
+ go(forward = true, steps = 1) {
1722
+ return this._loadSiblings(steps) ? this._change((forward ? this.next : this.prev), this.selected) : false
1723
+ }
1724
+
1725
+ _change(newEl, oldEl) {
1726
+ return _applyChange(this, newEl, oldEl)
1727
+ }
1728
+ }
1729
+
1730
+ /**
1731
+ * @typedef GridOptions
1732
+ * @property {String} [current=':focus'] Selector describing the currently selected cell.
1733
+ * @property {boolean} [wrap=false] Wrap around row/column edges instead of stopping there.
1734
+ * @property {boolean} [scroll=true] Scroll the newly selected cell into the view.
1735
+ * @property {?function} [onChange=null] Called with `(newEl, oldEl)` before the change; returning
1736
+ * `false` cancels it.
1737
+ * @property {?function} [onChanged=null] Called with `(newEl)` once the change has happened.
1738
+ * @property {?Action} [scope=null] Restricts the Up/Down/Left/Right grabs, @see WebHotkeys.grab.
1739
+ */
1740
+
1741
+ /**
1742
+ * 2D keyboard navigation over a table (rows × cells within a row).
1743
+ *
1744
+ * Every call to `WebHotkeys.grid()` returns its own independent instance, so several tables can
1745
+ * coexist on one page without one grid stealing the arrow keys from another (give each a distinct
1746
+ * `scope`).
1747
+ * @see WebHotkeys.grid
1748
+ */
1749
+ class _Grid {
1750
+ /**
1751
+ * @param {WebHotkeys} _wh
1752
+ * @param {String} rowQuery Selector for the rows (ex: `"table.dbtable tr"`).
1753
+ * @param {String} cellQuery Selector for the cells within a row (ex: `"td"`).
1754
+ * @param {GridOptions} [options]
1755
+ */
1756
+ constructor(_wh, rowQuery, cellQuery, {
1757
+ current = ":focus", wrap = false, scroll = true, onChange = null, onChanged = null, scope = null,
1758
+ } = {}) {
1759
+ this._wh = _wh
1760
+ this.rowQuery = rowQuery
1761
+ this.cellQuery = cellQuery
1762
+ this.currentSelector = current
1763
+ this.wrap = wrap
1764
+ this.scroll = scroll
1765
+ this.onChange = onChange
1766
+ this.onChanged = onChanged
1767
+ this.selected = null
1768
+ this._hotkeys = [
1769
+ this._wh.grab("ArrowUp", "Grid up", () => this.go(-1, 0), scope),
1770
+ this._wh.grab("ArrowDown", "Grid down", () => this.go(1, 0), scope),
1771
+ this._wh.grab("ArrowLeft", "Grid left", () => this.go(0, -1), scope),
1772
+ this._wh.grab("ArrowRight", "Grid right", () => this.go(0, 1), scope),
1773
+ ]
1774
+ }
1775
+
1776
+ /**
1777
+ * Locate the currently selected cell, its row and its column index. Falls back to the grid's
1778
+ * very first cell when nothing currently matches `currentSelector`.
1779
+ * @returns {boolean} A cell (hence a position) has been found.
1780
+ */
1781
+ _loadPosition() {
1782
+ this.rows = Array.from(document.querySelectorAll(this.rowQuery))
1783
+ if (!this.rows.length) {
1784
+ return false
1785
+ }
1786
+ for (let r = 0; r < this.rows.length; r++) {
1787
+ const cells = this.rows[r].querySelectorAll(this.cellQuery)
1788
+ for (let c = 0; c < cells.length; c++) {
1789
+ if (cells[c].matches(this.currentSelector)) {
1790
+ this.rowIndex = r
1791
+ this.colIndex = c
1792
+ this.selected = cells[c]
1793
+ return true
1794
+ }
1795
+ }
1796
+ }
1797
+ const cells = this.rows[0].querySelectorAll(this.cellQuery)
1798
+ if (!cells.length) {
1799
+ return false
1800
+ }
1801
+ this.rowIndex = 0
1802
+ this.colIndex = 0
1803
+ this.selected = cells[0]
1804
+ return true
1805
+ }
1806
+
1807
+ /**
1808
+ * Move by `rows` down and `cols` right (negative values go up / left). Moving between rows
1809
+ * keeps the column, clamped to the target row's width.
1810
+ * @param {number} [rows=0]
1811
+ * @param {number} [cols=0]
1812
+ * @returns {boolean} The selection has changed.
1813
+ * @example grid.go(1, 0) // down; grid.go(-1, -1) // up and left
1814
+ */
1815
+ go(rows = 0, cols = 0) {
1816
+ if (!this._loadPosition()) {
1817
+ return false
1818
+ }
1819
+ const oldEl = this.selected
1820
+ const rowIndex = rows
1821
+ ? (this.wrap ? _wrapIndex(this.rowIndex, rows, this.rows.length) : _clampIndex(this.rowIndex, rows, this.rows.length))
1822
+ : this.rowIndex
1823
+ const cells = this.rows[rowIndex].querySelectorAll(this.cellQuery)
1824
+ if (!cells.length) {
1825
+ return false
1826
+ }
1827
+ const colIndex = cols
1828
+ ? (this.wrap ? _wrapIndex(this.colIndex, cols, cells.length) : _clampIndex(this.colIndex, cols, cells.length))
1829
+ : Math.min(this.colIndex, cells.length - 1)
1830
+ return _applyChange(this, cells[colIndex], oldEl)
1831
+ }
1832
+
1833
+ /** Detach the Up/Down/Left/Right grabs. */
1834
+ destroy() {
1835
+ this._hotkeys.forEach(hotkey => hotkey?.remove())
1836
+ return this
1837
+ }
1838
+ }
1839
+
1840
+ //
1841
+ // Static methods
1842
+ //
1843
+
1844
+ function isString(t) {
1845
+ return typeof t === 'string' || t instanceof String
1846
+ }
1847
+
1848
+ /** Index `steps` away from `index`, wrapping around a collection of `count` items. */
1849
+ function _wrapIndex(index, steps, count) {
1850
+ return ((index + steps) % count + count) % count
1851
+ }
1852
+
1853
+ /** Index `steps` away from `index`, clamped to the collection bounds (no wrapping). */
1854
+ function _clampIndex(index, steps, count) {
1855
+ return Math.min(Math.max(index + steps, 0), count - 1)
1856
+ }
1857
+
1858
+ /**
1859
+ * Move the "current item" marker from `oldEl` to `newEl`, shared by `_List` and `_Grid`.
1860
+ * @param {{currentSelector: string, onChange: ?function, onChanged: ?function, scroll: boolean, selected: ?HTMLElement}} holder
1861
+ * @param {?HTMLElement} newEl
1862
+ * @param {?HTMLElement} oldEl
1863
+ * @returns {boolean}
1864
+ */
1865
+ function _applyChange(holder, newEl, oldEl) {
1866
+ let proceed = true
1867
+ if (typeof holder.onChange === "function") {
1868
+ proceed = holder.onChange(newEl, oldEl)
1869
+ }
1870
+ if (proceed) {
1871
+ if (holder.currentSelector.substr(0, 1) === ".") {
1872
+ let cl = holder.currentSelector.substr(1)
1873
+ if (oldEl) {
1874
+ oldEl.classList.remove(cl)
1875
+ }
1876
+ if (newEl) {
1877
+ newEl.classList.add(cl)
1878
+ }
1879
+ } else if (holder.currentSelector.substring(0, 1) === "[") {
1880
+ const attrName = holder.currentSelector.substring(1, holder.currentSelector.length - 1)
1881
+ if (oldEl) {
1882
+ oldEl.removeAttribute(attrName)
1883
+ }
1884
+ if (newEl) {
1885
+ newEl.setAttribute(attrName, "1")
1886
+ }
1887
+ } else if (holder.currentSelector.indexOf(":focus") === 0) {
1888
+ newEl.focus();
1889
+ } else { //selector can be I.E. a data-attribute
1890
+ console.error("WebHotkeys.js> Don't know how to process selector type:", holder.currentSelector)
1891
+ return false;
1892
+ }
1893
+ holder.selected = newEl;
1894
+ if (holder.scroll) {
1895
+ newEl?.scrollIntoView?.({ block: "nearest" })
1896
+ }
1897
+ if (holder.onChanged) {
1898
+ holder.onChanged(newEl)
1899
+ }
1900
+ }
1901
+ return true
1902
+ }
1903
+
1904
+ /**
1905
+ * A stored remapping is a flat {combination: combination} object. Anything else found under our
1906
+ * localStorage key belongs to somebody else (the page shares the origin with us) and must be kept intact.
1907
+ * @param {string} stored
1908
+ * @returns {?Object.<Key, Key>} Null when the value is not ours.
1909
+ */
1910
+ function parseRemapping(stored) {
1911
+ let map
1912
+ try {
1913
+ map = JSON.parse(stored)
1914
+ } catch (e) {
1915
+ return null
1916
+ }
1917
+ if (!map || typeof map !== "object" || Array.isArray(map)) {
1918
+ return null
1919
+ }
1920
+ return Object.values(map).every(isString) ? map : null
1921
+ }
1922
+
1923
+ /**
1924
+ * Is the string a combination we could have produced ourselves?
1925
+ *
1926
+ * A remapping arrives from the outside – the localStorage, or the server the page loaded it from
1927
+ * (where it may well be another user's). An unchecked combination ends up in the element hint, and
1928
+ * with the `hint: 'text'` option that means `innerHTML` – ex. '<img src=x onerror=…>' would run.
1929
+ * Hence: modifiers we know of, and a key that is either a single character ('?', '+') or a plain
1930
+ * identifier ('KeyJ', 'ArrowUp', 'F5').
1931
+ *
1932
+ * @param {Key} combination
1933
+ * @returns {boolean}
1934
+ */
1935
+ function isSafeCombination(combination) {
1936
+ if (!isString(combination) || !combination.trim()) {
1937
+ return false
1938
+ }
1939
+ return combination.split(" ").filter(part => part.length).every(part => {
1940
+ const parts = part.split("+")
1941
+ if (parts[parts.length - 1] === "" && parts[parts.length - 2] === "") {
1942
+ parts.splice(parts.length - 2, 2, "+") // the plus key, ex: 'Alt++'
1943
+ }
1944
+ const key = parts.pop()
1945
+ return (key.length === 1 || /^[A-Za-z0-9]+$/.test(key))
1946
+ && parts.every(mod => MODIFIER_ALIASES[mod.toLowerCase()])
1947
+ })
1948
+ }
1949
+
1950
+ /** Named keys where `event.key === event.code` (unlike `KeyF`/`f` or `Digit1`/`1`). */
1951
+ const NAMED_CODES = /^(Arrow(Up|Down|Left|Right)|Home|End|Delete|Backspace|Tab|Enter|Escape|Insert|Space|PageUp|PageDown|F\d{1,2})$/
1952
+
1953
+ /**
1954
+ * `_parseHotkey` only ever fills in `key` *or* `code` (whichever the definition implies), so a
1955
+ * simulated keystroke misses the other side that a real one always carries – `_isTextContext`
1956
+ * looks at `e.key`, so `simulate("ArrowDown")` would not be blocked in a text input the way an
1957
+ * actual arrow-down keypress is. Derive the missing side where it is unambiguous; a lone
1958
+ * single-character `key` (ex: "f", "?") stays as is, its physical `code` is not derivable.
1959
+ * @param {KeyEvent} event
1960
+ * @returns {KeyEvent}
1961
+ */
1962
+ function completeSimulatedEvent(event) {
1963
+ if (event.code === undefined || event.key !== undefined) {
1964
+ return event
1965
+ }
1966
+ const digit = /^Digit(\d)$/.exec(event.code)
1967
+ if (digit) {
1968
+ return { ...event, key: digit[1] }
1969
+ }
1970
+ const letter = /^Key([A-Z])$/.exec(event.code)
1971
+ if (letter) {
1972
+ return { ...event, key: letter[1].toLowerCase() }
1973
+ }
1974
+ if (NAMED_CODES.test(event.code)) {
1975
+ return { ...event, key: event.code }
1976
+ }
1977
+ return event
1978
+ }
1979
+
1980
+ /** @returns {Object} Only the modifier flags of the event. */
1981
+ function pickModifiers(e) {
1982
+ return { ctrlKey: !!e.ctrlKey, shiftKey: !!e.shiftKey, altKey: !!e.altKey, metaKey: !!e.metaKey }
1983
+ }
1984
+
1985
+ /** Case insensitive comparison of the `key` values. */
1986
+ function keyEquals(a, b) {
1987
+ return a === b || (a?.length === 1 && b?.length === 1 && a.toLowerCase() === b.toLowerCase())
1988
+ }
1989
+
1990
+ /**
1991
+ * A hidden element must not swallow its hotkey.
1992
+ * @param {HTMLElement} el
1993
+ * @returns {boolean}
1994
+ */
1995
+ function isVisible(el) {
1996
+ if (el.getClientRects === undefined && el.checkVisibility === undefined) {
1997
+ return true // not a real DOM element (a test stub), do not judge it
1998
+ }
1999
+ if (el.hidden || el.closest?.("[inert],[hidden]")) {
2000
+ return false
2001
+ }
2002
+ if (typeof el.checkVisibility === "function") {
2003
+ return el.checkVisibility()
2004
+ }
2005
+ return !!(el.offsetWidth || el.offsetHeight || el.getClientRects?.().length)
2006
+ }
2007
+
2008
+ /**
2009
+ * @param {string} tag
2010
+ * @param {string} className
2011
+ * @param {?HTMLElement} parent
2012
+ * @returns {?HTMLElement}
2013
+ */
2014
+ function createEl(tag, className = "", parent = null) {
2015
+ if (typeof document === "undefined" || !document.createElement) {
2016
+ return null
2017
+ }
2018
+ const el = document.createElement(tag)
2019
+ if (className) {
2020
+ el.className = className
2021
+ }
2022
+ parent?.appendChild(el)
2023
+ return el
2024
+ }
2025
+
2026
+ //
2027
+ // Public
2028
+ //
2029
+ if (typeof document !== "undefined" && document.currentScript && document.currentScript.dataset.register !== undefined) { // currentScript is unavailable in i.e. a content script
2030
+ window.webHotkeys = new WebHotkeys()
2031
+ }
2032
+
2033
+ // CommonJS/bundler consumers (npm install). Guarded so a plain `<script>` tag (no module system
2034
+ // present) never touches this - the global classes above remain the only thing it defines.
2035
+ if (typeof module !== "undefined" && module.exports) {
2036
+ module.exports = WebHotkeys
2037
+ module.exports.WebHotkeys = WebHotkeys
2038
+ module.exports.Hotkey = Hotkey
2039
+ module.exports.HotkeyGroup = HotkeyGroup
2040
+ } else if (typeof window !== "undefined") {
2041
+ // A classic <script> tag: a top-level `class` is lexically scoped (like `let`), so it never
2042
+ // becomes a window property. Expose it explicitly, so that a vendored copy of this file
2043
+ // makes `new window.WebHotkeys()` work without reading the docs.
2044
+ window.WebHotkeys = WebHotkeys
2045
+ window.Hotkey = Hotkey
2046
+ window.HotkeyGroup = HotkeyGroup
2047
+ }