@typeonce/ritmo-browser 0.22.0 → 0.24.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.
package/src/Keyboard.ts CHANGED
@@ -11,19 +11,45 @@
11
11
  * Bind by character (`"w"`) or by physical key (`Keyboard.code("KeyW")`);
12
12
  * see {@link KeyBinding}. A key released while a modifier changed its
13
13
  * character (W pressed, then Option, then W released as "∑") still releases
14
- * its action.
14
+ * its action. Keys that type the same character (both Shift keys, a digit on
15
+ * the row and on the numpad) are one key to a character binding: it is
16
+ * pressed when the first goes down and released when the last comes up.
15
17
  *
16
- * Some combinations never reach the page: browsers reserve shortcuts such as
17
- * Ctrl+W / Cmd+W (close tab), Ctrl+T / Cmd+T, and Cmd+Q, and pages cannot
18
- * prevent them. Avoid Ctrl and Cmd as held modifiers in games.
18
+ * Browser shortcuts are left to the browser: a key pressed with Cmd held, or
19
+ * with Ctrl held, presses no action and is not `preventDefault`-ed, so Ctrl+R
20
+ * still reloads and Ctrl+F still finds while R and F are bound. AltGr reports
21
+ * Ctrl and Alt together and types characters on many layouts, so a key
22
+ * pressed with both is not a shortcut. A game that binds Control or Meta to
23
+ * an action (`"Control"`, `Keyboard.code("ControlLeft")`, ...) keeps every
24
+ * key pressed with them instead, for as long as its bindings hold one; some
25
+ * combinations still never reach the page (Ctrl+W / Cmd+W, Ctrl+T / Cmd+T,
26
+ * Cmd+Q). macOS sends no keyup for a key released while Cmd is down, so
27
+ * Cmd's own release lets go of every held key but the modifiers. A key still
28
+ * down after that, or after a window blur, is pressed again at its next
29
+ * auto-repeat.
19
30
  *
20
- * Keys typed into a form field are left to the field: a key that goes down
21
- * in an `<input>` (any type), `<textarea>`, `<select>`, or contenteditable
22
- * element presses no action and is not `preventDefault`-ed, so a name field
23
- * on the same page as the game receives "wasd" and the player does not move.
24
- * Releases are always processed, so a key held before focus moved into a
25
- * field still releases its action. With `window` as the host this needs no
26
- * setup.
31
+ * Keys the page is using are left to the page: a key that goes down in a
32
+ * form field (`<input>` of any type, `<textarea>`, `<select>`,
33
+ * contenteditable), or inside an open modal dialog (`<dialog>` opened with
34
+ * `showModal()`, or `aria-modal="true"`), or that a listener nearer the
35
+ * target already handled with `preventDefault()` (a menu's arrows, a
36
+ * slider's keys), and Enter, Space, and Tab on a control the player reached
37
+ * by keyboard (Tab to a button, link, tab, or any focusable element: the
38
+ * browser shows it with `:focus-visible`) press no action and are not
39
+ * `preventDefault`-ed. So a name field receives "wasd" and the player does
40
+ * not move, Enter and Space press a focused button, and Escape closes a
41
+ * modal `<dialog>`. Every other key on that focused button is still the
42
+ * game's: movement and hotkeys keep working after the player tabbed to a
43
+ * control. A control the player clicked with the mouse keeps focus but none
44
+ * of the keys: the game keeps playing, and Space does not press it again,
45
+ * with no `tabIndex = -1` or `blur()` in the game. A focused `<canvas>`, or
46
+ * the element passed as the host, is the game, not page UI: when a menu the
47
+ * player used by keyboard closes back into play, focus the canvas
48
+ * (`canvas.tabIndex = -1`, then `canvas.focus()`), or Enter and Space stay
49
+ * with the button the menu handed focus back to. Releases are always
50
+ * processed, so a key held before focus moved still releases its action.
51
+ * With `window` as the host this needs no setup; see {@link KeyEvent} for
52
+ * the exact rule.
27
53
  *
28
54
  * @module Keyboard
29
55
  * @docGroup browser
@@ -88,44 +114,195 @@ import type { Direction, Vector } from "./internal/vectors.ts"
88
114
  export type { Direction }
89
115
 
90
116
  /**
91
- * The subset of `KeyboardEvent` the module reads. `code` (the physical key)
92
- * and `target` (the element the key was typed into) are optional so simple
93
- * test hosts can omit them; browsers always provide them.
117
+ * The subset of `KeyboardEvent` the module reads. `code` (the physical key),
118
+ * the modifiers, `defaultPrevented`, and `target` (the focused element the
119
+ * key went down in) are optional so simple test hosts can omit them;
120
+ * browsers always provide them. `ctrlKey` and `metaKey` mark a browser
121
+ * shortcut, which {@link actions} leaves to the browser, and `altKey` tells
122
+ * AltGr (Ctrl and Alt together) from Ctrl.
94
123
  *
95
- * A target is a form field, whose key presses {@link actions} and
96
- * {@link presses} leave to it, when its `tagName` is `INPUT` (any type,
97
- * checkboxes and buttons included), `TEXTAREA`, or `SELECT`, or its
98
- * `isContentEditable` is `true`. It is read by shape, not `instanceof`, so
99
- * it works across iframes, and a test host types into a field by passing
100
- * `{ tagName: "INPUT" }` or `{ isContentEditable: true }`.
124
+ * {@link actions} leaves a key to the page when any of these holds:
125
+ *
126
+ * - `defaultPrevented` is `true` because a listener nearer the target (a
127
+ * roving-focus group's arrows, a custom slider, a menu) handled it, not
128
+ * because another `Keyboard.actions` on the same host did;
129
+ * - the target is a form field: its `tagName` is `INPUT` (any type,
130
+ * checkboxes and buttons included), `TEXTAREA`, or `SELECT`, or its
131
+ * `isContentEditable` is `true`;
132
+ * - the target is inside an open modal dialog: `closest` finds a
133
+ * `dialog:modal` (opened with `showModal()`) or an `[aria-modal="true"]`
134
+ * element, however the dialog was opened;
135
+ * - the key is Enter, Space, or Tab (the keys a browser itself acts on for
136
+ * a focused control: press it, move focus on) and the target took focus
137
+ * by keyboard: it matched `:focus-visible` when its `focusin` reached the
138
+ * host, and it is not a `<canvas>` or the host itself (the game's own
139
+ * surface). Any other key on that control is the game's, as a page
140
+ * shortcut still works with a button focused, unless the control handled
141
+ * it (the first rule).
142
+ *
143
+ * {@link presses} offers a key the game asked for, usually from inside a
144
+ * settings dialog, so it skips only a form field's keys and Enter, Space,
145
+ * and Tab on a control reached by keyboard: an open modal dialog and a key a
146
+ * widget handled do not hide a press from it.
147
+ *
148
+ * Focus is judged when it arrives because browsers disagree later: Chromium
149
+ * turns `:focus-visible` on for a clicked button at the first key the player
150
+ * presses, so a check at keydown would hand Space back to a "Mute" button
151
+ * clicked minutes earlier. A focus a script moves (`element.focus()`) counts
152
+ * as by keyboard after the player last used the keyboard in Chromium and
153
+ * Safari, never in Firefox; a dialog's own focus is covered by the modal
154
+ * rule in all three.
155
+ *
156
+ * The target is read by shape, not `instanceof`, so it works across
157
+ * iframes, and a test host types into a field by passing
158
+ * `{ tagName: "INPUT" }` or `{ isContentEditable: true }`, and focuses a
159
+ * control by keyboard by sending `focusin` with a target whose
160
+ * `matches(":focus-visible")` returns `true`.
101
161
  */
102
162
  export interface KeyEvent {
103
163
  readonly key: string
104
164
  readonly code?: string
105
165
  readonly repeat: boolean
166
+ readonly ctrlKey?: boolean
167
+ readonly metaKey?: boolean
168
+ readonly altKey?: boolean
169
+ readonly defaultPrevented?: boolean
106
170
  readonly target?: object | null
107
171
  preventDefault(): void
108
172
  }
109
173
 
174
+ /**
175
+ * The subset of the `focusin` event the module reads: the element that took
176
+ * focus, read by shape like {@link KeyEvent}'s target.
177
+ */
178
+ export interface FocusInEvent {
179
+ readonly target?: object | null
180
+ }
181
+
110
182
  /** Every action that is not in use shares this state, so a snapshot of an idle keyboard allocates no states. */
111
183
  const idleState: ActionState = { held: false, pressed: false, released: false }
112
184
 
113
185
  const editableTags: ReadonlySet<string> = new Set(["INPUT", "TEXTAREA", "SELECT"])
114
186
 
187
+ /** The members of an element the module reads, all optional: a test host passes plain objects. */
188
+ interface TargetShape {
189
+ readonly tagName?: unknown
190
+ readonly isContentEditable?: unknown
191
+ readonly matches?: unknown
192
+ readonly closest?: unknown
193
+ }
194
+
115
195
  /** Whether a key event's target is a form field, by the rule on {@link KeyEvent}. */
116
- const isEditableTarget = (target: object | null | undefined): boolean => {
117
- if (target === null || target === undefined) return false
118
- const { tagName, isContentEditable } = target as { readonly tagName?: unknown; readonly isContentEditable?: unknown }
196
+ const isEditableTarget = (target: object): boolean => {
197
+ const { tagName, isContentEditable } = target as TargetShape
119
198
  return isContentEditable === true || (typeof tagName === "string" && editableTags.has(tagName.toUpperCase()))
120
199
  }
121
200
 
201
+ /** `target.matches(selector)`, false for a target without it or a selector the browser does not know. */
202
+ const matchesSelector = (target: object, selector: string): boolean => {
203
+ const { matches } = target as TargetShape
204
+ if (typeof matches !== "function") return false
205
+ try {
206
+ return (matches as (selector: string) => unknown).call(target, selector) === true
207
+ } catch {
208
+ return false
209
+ }
210
+ }
211
+
212
+ /** Whether `target.closest(selector)` finds an element, false where it cannot ask. */
213
+ const hasAncestor = (target: object, selector: string): boolean => {
214
+ const { closest } = target as TargetShape
215
+ if (typeof closest !== "function") return false
216
+ try {
217
+ const found: unknown = (closest as (selector: string) => unknown).call(target, selector)
218
+ return found !== null && found !== undefined
219
+ } catch {
220
+ return false
221
+ }
222
+ }
223
+
224
+ /** Whether the target is inside an open modal dialog. `:modal` is asked of dialogs only, since a fullscreen element can match it too. */
225
+ const isInsideModal = (target: object): boolean =>
226
+ hasAncestor(target, "[aria-modal=\"true\"]") || hasAncestor(target, "dialog:modal")
227
+
122
228
  /**
123
- * The event target the module listens on, usually `window`.
229
+ * The key events a `Keyboard.actions` device prevented: another device on
230
+ * the same host sees them as `defaultPrevented`, and they are still the game's.
231
+ */
232
+ const preventedByKeyboard = new WeakSet()
233
+
234
+ /** The keys a browser itself acts on for a focused control: Enter and Space press it, Tab moves focus on. */
235
+ const isControlKey = (event: KeyEvent): boolean => event.key === "Enter" || event.key === " " || event.key === "Tab"
236
+
237
+ /** Which keys belong to the page on one host, by the rule on {@link KeyEvent}. */
238
+ interface PageKeys {
239
+ /** Whether {@link actions} leaves this key to the page. */
240
+ readonly owns: (event: KeyEvent) => boolean
241
+ /** Whether {@link presses} leaves this key to the page: a form field's keys, and a keyboard-focused control's own. */
242
+ readonly ownsWhileCapturing: (event: KeyEvent) => boolean
243
+ readonly dispose: () => void
244
+ }
245
+
246
+ /**
247
+ * Tracks which element took focus by keyboard on `host`, and answers
248
+ * whether a key belongs to the page by the rule on {@link KeyEvent}.
249
+ */
250
+ const pageKeys = (host: KeyboardHost): PageKeys => {
251
+ // The element that last took focus while it matched `:focus-visible`, read
252
+ // at `focusin` because Chromium turns it on for a clicked control at the next key.
253
+ let keyboardFocused: object | null = null
254
+ const onFocusIn = (event: FocusInEvent): void => {
255
+ const target = event.target ?? null
256
+ keyboardFocused = target !== null && matchesSelector(target, ":focus-visible") ? target : null
257
+ }
258
+ host.addEventListener("focusin", onFocusIn)
259
+ const isGameSurface = (target: object): boolean => {
260
+ const { tagName } = target as TargetShape
261
+ return target === host || (typeof tagName === "string" && tagName.toUpperCase() === "CANVAS")
262
+ }
263
+ const isControlPress = (event: KeyEvent, target: object): boolean =>
264
+ target === keyboardFocused && isControlKey(event) && !isGameSurface(target)
265
+ return {
266
+ owns(event) {
267
+ if (event.defaultPrevented === true && !preventedByKeyboard.has(event)) return true
268
+ const target = event.target ?? null
269
+ if (target === null) return false
270
+ return isEditableTarget(target) || isInsideModal(target) || isControlPress(event, target)
271
+ },
272
+ ownsWhileCapturing(event) {
273
+ const target = event.target ?? null
274
+ return target !== null && (isEditableTarget(target) || isControlPress(event, target))
275
+ },
276
+ dispose() {
277
+ host.removeEventListener("focusin", onFocusIn)
278
+ }
279
+ }
280
+ }
281
+
282
+ const modifierKeys: ReadonlySet<string> = new Set(["Shift", "Control", "Alt", "AltGraph", "Meta"])
283
+ const modifierCodes: ReadonlySet<string> = new Set(["ShiftLeft", "ShiftRight", "ControlLeft", "ControlRight", "AltLeft", "AltRight", "MetaLeft", "MetaRight"])
284
+
285
+ /**
286
+ * Whether a key goes down as a browser shortcut: with Cmd, or with Ctrl
287
+ * without Alt (AltGr reports both and types characters), and not a
288
+ * modifier itself.
289
+ */
290
+ const isShortcut = (event: KeyEvent): boolean =>
291
+ (event.metaKey === true || (event.ctrlKey === true && event.altKey !== true)) && !modifierKeys.has(event.key)
292
+
293
+ const isMeta = (event: KeyEvent): boolean => event.key === "Meta" || event.code === "MetaLeft" || event.code === "MetaRight"
294
+
295
+ /**
296
+ * The event target the module listens on, usually `window`. `focusin` tells
297
+ * which control the player reached by keyboard (see {@link KeyEvent}); a
298
+ * test host that never sends it has no such control.
124
299
  */
125
300
  export interface KeyboardHost {
126
301
  addEventListener(type: "keydown" | "keyup", listener: (event: KeyEvent) => void): void
302
+ addEventListener(type: "focusin", listener: (event: FocusInEvent) => void): void
127
303
  addEventListener(type: "blur", listener: () => void): void
128
304
  removeEventListener(type: "keydown" | "keyup", listener: (event: KeyEvent) => void): void
305
+ removeEventListener(type: "focusin", listener: (event: FocusInEvent) => void): void
129
306
  removeEventListener(type: "blur", listener: () => void): void
130
307
  }
131
308
 
@@ -146,7 +323,10 @@ export interface PhysicalKey {
146
323
  * Character bindings follow the keyboard layout and are what a menu should
147
324
  * show. Physical bindings keep a position fixed: WASD stays under the left
148
325
  * hand on AZERTY keyboards, and modifiers cannot change the match (with
149
- * Option held on macOS, W types "∑"; with Shift, 1 types "!").
326
+ * Option held on macOS, W types "∑"; with Shift, 1 types "!"). A character
327
+ * binding matches every key that types it: `"Shift"` is both Shift keys,
328
+ * held while either is down, and `"1"` is the digit row and the numpad;
329
+ * bind `Keyboard.code("ShiftLeft")` for one of them.
150
330
  */
151
331
  export type KeyBinding = string | PhysicalKey
152
332
 
@@ -267,7 +447,10 @@ export interface Actions<B extends Bindings> extends System.Consumes<"snapshot">
267
447
  export interface ActionsOptions {
268
448
  /**
269
449
  * Call `preventDefault()` for bound keys, so arrows and space do not scroll
270
- * the page. Defaults to `true`.
450
+ * the page and a button clicked with the mouse, which keeps focus, is not
451
+ * pressed again by Space or Enter. Defaults to `true`. With `false`, every
452
+ * key the game takes also does what the page does with it (Space presses
453
+ * that clicked button and scrolls); which keys the game takes does not change.
271
454
  */
272
455
  readonly preventDefault?: boolean
273
456
  }
@@ -326,11 +509,32 @@ const bindingLabel = (binding: KeyBinding): string => typeof binding === "string
326
509
  const labelsOf = (flat: Readonly<Record<string, Keys>>): ReadonlyArray<string> =>
327
510
  [...new Set(Object.values(flat).flatMap((keys) => keys.map(bindingLabel)))]
328
511
 
512
+ const modifierTokens: ReadonlySet<string> = new Set([...[...modifierKeys].map(keyToken), ...[...modifierCodes].map(codeToken)])
513
+
514
+ /** The tokens of Ctrl and Cmd: a game that binds one keeps the keys pressed with them. */
515
+ const shortcutModifierTokens = [
516
+ keyToken("Control"),
517
+ keyToken("Meta"),
518
+ codeToken("ControlLeft"),
519
+ codeToken("ControlRight"),
520
+ codeToken("MetaLeft"),
521
+ codeToken("MetaRight")
522
+ ]
523
+
329
524
  /**
330
525
  * Starts tracking bound keys on `host`, usually `window`, until `dispose()`.
331
- * When the window loses focus every held action is released. A key pressed
332
- * in a form field (see {@link KeyEvent}) is left to the field: it
333
- * presses no action and is not `preventDefault`-ed. Each call is
526
+ * When the window loses focus every held action is released. A key the page
527
+ * is using (a form field, an open modal dialog, a key a widget already
528
+ * handled, Enter, Space, and Tab on a control reached by keyboard; see
529
+ * {@link KeyEvent}) is left to
530
+ * the page, and a browser shortcut (a key pressed with Cmd or Ctrl, unless
531
+ * the bindings use Control or Meta) to the browser: it presses no action and
532
+ * is not `preventDefault`-ed. Use it for every key the host reacts to,
533
+ * one-shot keys too (pause on Escape, mute on M: read their `pressed` edge
534
+ * in the snapshot), instead of a `keydown` listener on `window` that calls
535
+ * `preventDefault()` and so takes Enter and Space from a focused button.
536
+ * Binding Tab keeps a keyboard player from moving focus to the page's
537
+ * controls, so a page with controls leaves it unbound. Each call is
334
538
  * its own device: build one per source (one `Controls` merge, one player
335
539
  * of a pool). Use {@link scripted} for tests and headless runs, and
336
540
  * {@link presses} to capture an unbound key on a settings screen.
@@ -346,6 +550,8 @@ export const actions = <const B extends Bindings>(
346
550
  const names = Object.keys(flatten(initial))
347
551
  let bindings = flatten(initial)
348
552
  const actionsByToken = new Map<string, Array<string>>()
553
+ // Off while the bindings use Ctrl or Cmd as a button: then every key pressed with them is the game's.
554
+ let leavesShortcuts = true
349
555
  const index = (): void => {
350
556
  actionsByToken.clear()
351
557
  for (const name of names) {
@@ -356,8 +562,10 @@ export const actions = <const B extends Bindings>(
356
562
  else actionsByToken.set(token, [name])
357
563
  }
358
564
  }
565
+ leavesShortcuts = !shortcutModifierTokens.some((token) => actionsByToken.has(token))
359
566
  }
360
567
  index()
568
+ const page = pageKeys(host)
361
569
 
362
570
  /**
363
571
  * Each held token and the actions it holds: those bound to it when it went
@@ -368,49 +576,92 @@ export const actions = <const B extends Bindings>(
368
576
  /**
369
577
  * The character token each physical key produced when it went down, so its
370
578
  * release matches even if a modifier changed the character meanwhile
371
- * (W pressed, Option pressed, W released as "∑").
579
+ * (W pressed, Option pressed, W released as "∑"). It also holds the keys
580
+ * known to be down, form fields and shortcuts included: their repeats
581
+ * press nothing.
372
582
  */
373
583
  const keyTokenByCode = new Map<string, string>()
584
+ /**
585
+ * The physical keys holding each held character token, so a character two
586
+ * keys type (both Shifts, a digit on the row and on the numpad) stays held
587
+ * until the last of them comes up. A token held through a host that sends
588
+ * no `code` has no entry, and its first release lets go of it.
589
+ */
590
+ const codesByToken = new Map<string, Set<string>>()
374
591
  const pressed = new Set<string>()
375
592
  const released = new Set<string>()
376
593
 
594
+ const release = (token: string): void => {
595
+ const holding = heldTokens.get(token)
596
+ if (!holding) return
597
+ heldTokens.delete(token)
598
+ codesByToken.delete(token)
599
+ for (const name of holding) released.add(name)
600
+ }
601
+
602
+ /** Lets go of `code`'s hold on a character token, releasing it when no other key holds it. */
603
+ const letGo = (token: string, code: string): void => {
604
+ const codes = codesByToken.get(token)
605
+ if (codes === undefined || !codes.delete(code) || codes.size > 0) return
606
+ release(token)
607
+ }
608
+
377
609
  const onKeyDown = (event: KeyEvent): void => {
378
- // Typed into a form field: the key belongs to the field. Its release is
379
- // still processed by `onKeyUp`.
380
- if (isEditableTarget(event.target)) return
381
610
  const tokens = [keyToken(event.key)]
611
+ // A repeat of a key known to be down presses nothing; one whose release
612
+ // was missed (a blur, or Cmd on macOS) presses it again. Without `code`,
613
+ // a repeat presses any key that is not held.
614
+ const known = event.code !== undefined && keyTokenByCode.has(event.code)
382
615
  if (event.code !== undefined) {
383
- if (!keyTokenByCode.has(event.code)) keyTokenByCode.set(event.code, tokens[0]!)
616
+ if (!event.repeat || !known) {
617
+ // A new press: the key went up unseen if it was known down, so it no
618
+ // longer holds what it typed then, and its release matches what it types now.
619
+ const before = keyTokenByCode.get(event.code)
620
+ if (before !== undefined && before !== tokens[0]) letGo(before, event.code)
621
+ keyTokenByCode.set(event.code, tokens[0]!)
622
+ }
384
623
  tokens.push(codeToken(event.code))
385
624
  }
625
+ // A key the page is using belongs to the page; a shortcut belongs to the
626
+ // browser. Their releases are still processed by `onKeyUp`.
627
+ if (page.owns(event) || (leavesShortcuts && isShortcut(event))) return
386
628
  let handled = false
387
629
  for (const token of tokens) {
388
630
  const bound = actionsByToken.get(token)
389
631
  if (!bound) continue
390
632
  handled = true
391
- if (event.repeat || heldTokens.has(token)) continue
633
+ if (event.repeat && known) continue
634
+ // Another key typing the same character joins its hold: one press for both.
635
+ if (event.code !== undefined && token === tokens[0]) {
636
+ const codes = codesByToken.get(token)
637
+ if (codes) codes.add(event.code)
638
+ else if (!heldTokens.has(token)) codesByToken.set(token, new Set([event.code]))
639
+ }
640
+ if (heldTokens.has(token)) continue
392
641
  heldTokens.set(token, new Set(bound))
393
642
  for (const name of bound) pressed.add(name)
394
643
  }
395
- if (handled && preventDefault) event.preventDefault()
644
+ if (handled && preventDefault) {
645
+ event.preventDefault()
646
+ preventedByKeyboard.add(event)
647
+ }
396
648
  }
397
649
 
398
- // Releases are processed wherever the key was released, form fields
399
- // included, so a key held before focus moved into a field still releases.
650
+ // Releases are processed wherever the key was released, form fields and
651
+ // focused controls included, so a key held before focus moved still releases.
400
652
  const onKeyUp = (event: KeyEvent): void => {
401
- const tokens = [keyToken(event.key)]
653
+ const character = event.code === undefined ? keyToken(event.key) : keyTokenByCode.get(event.code) ?? keyToken(event.key)
654
+ if (event.code === undefined || !codesByToken.has(character)) release(character)
655
+ else letGo(character, event.code)
402
656
  if (event.code !== undefined) {
403
- const downAs = keyTokenByCode.get(event.code)
404
657
  keyTokenByCode.delete(event.code)
405
- if (downAs !== undefined) tokens[0] = downAs
406
- tokens.push(codeToken(event.code))
407
- }
408
- for (const token of tokens) {
409
- const holding = heldTokens.get(token)
410
- if (!holding) continue
411
- heldTokens.delete(token)
412
- for (const name of holding) released.add(name)
658
+ release(codeToken(event.code))
413
659
  }
660
+ // macOS sends no keyup for a key released while Cmd is down: Cmd's own
661
+ // release lets go of every key but the modifiers, which do get theirs.
662
+ if (!isMeta(event)) return
663
+ for (const token of heldTokens.keys()) if (!modifierTokens.has(token)) release(token)
664
+ for (const code of keyTokenByCode.keys()) if (!modifierCodes.has(code)) keyTokenByCode.delete(code)
414
665
  }
415
666
 
416
667
  const onBlur = (): void => {
@@ -418,6 +669,7 @@ export const actions = <const B extends Bindings>(
418
669
  for (const name of holding) released.add(name)
419
670
  }
420
671
  heldTokens.clear()
672
+ codesByToken.clear()
421
673
  keyTokenByCode.clear()
422
674
  }
423
675
 
@@ -465,6 +717,7 @@ export const actions = <const B extends Bindings>(
465
717
  host.removeEventListener("keydown", onKeyDown)
466
718
  host.removeEventListener("keyup", onKeyUp)
467
719
  host.removeEventListener("blur", onBlur)
720
+ page.dispose()
468
721
  }
469
722
  }
470
723
  return live
@@ -482,7 +735,7 @@ export interface KeyPress {
482
735
  export interface Presses extends System.Consumes<"snapshot"> {
483
736
  /** The keys that went down since the previous snapshot, in order, without auto-repeats. */
484
737
  snapshot(): ReadonlyArray<KeyPress>
485
- /** Removes the event listener. */
738
+ /** Removes the event listeners. */
486
739
  dispose(): void
487
740
  }
488
741
 
@@ -490,7 +743,14 @@ export interface Presses extends System.Consumes<"snapshot"> {
490
743
  * Starts collecting every key press on `host`, whatever the bindings, for a
491
744
  * settings screen that waits for the key to bind. Use {@link actions} for
492
745
  * gameplay. It never calls `preventDefault()`, and skips keys pressed in a
493
- * form field (see {@link KeyEvent}).
746
+ * form field, Enter, Space, and Tab on a control reached by keyboard (see
747
+ * {@link KeyEvent}), and browser shortcuts (a key pressed with Cmd or Ctrl),
748
+ * so Ctrl+R on the settings screen binds nothing; Control and Meta pressed
749
+ * alone are offered. Unlike {@link actions} it still offers a key pressed
750
+ * inside an open modal dialog or one a widget handled, since the screen that
751
+ * waits for a key is usually a dialog. For "press any key" on a title or a
752
+ * cutscene, it is the host's listener: it leaves Enter on a button reached
753
+ * by keyboard to the button.
494
754
  *
495
755
  * @example
496
756
  * ```ts
@@ -508,8 +768,9 @@ export interface Presses extends System.Consumes<"snapshot"> {
508
768
  */
509
769
  export const presses = (host: KeyboardHost): Presses => {
510
770
  let pending: Array<KeyPress> = []
771
+ const page = pageKeys(host)
511
772
  const onKeyDown = (event: KeyEvent): void => {
512
- if (event.repeat || isEditableTarget(event.target)) return
773
+ if (event.repeat || page.ownsWhileCapturing(event) || isShortcut(event)) return
513
774
  pending.push({ key: event.key, code: event.code ?? null })
514
775
  }
515
776
  host.addEventListener("keydown", onKeyDown)
@@ -521,6 +782,7 @@ export const presses = (host: KeyboardHost): Presses => {
521
782
  },
522
783
  dispose() {
523
784
  host.removeEventListener("keydown", onKeyDown)
785
+ page.dispose()
524
786
  }
525
787
  }
526
788
  }