entangled-worlds-orbiters-shared 4.1.0 → 4.2.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,51 @@
1
+ // The Entangled Worlds catalogues: the studio (where a world's clip is made) and the full-window
2
+ // player. Escape and Enter inside dialogs stay with the dialogs and are not listed here.
3
+
4
+ import type { ShortcutAction } from './match.js'
5
+
6
+ export const EW_STUDIO_SECTION = 'ew-studio'
7
+ export const EW_PLAYER_SECTION = 'ew-player'
8
+
9
+ /** The studio's actions all act on what is open in it; the player has no other scope. */
10
+ export type EntangledWorldsShortcut = ShortcutAction<'studio' | 'player'>
11
+
12
+ const studio = (id: string, label: string, defaultKeys: readonly string[], group: string, command?: false): EntangledWorldsShortcut =>
13
+ Object.freeze({
14
+ id: `ew.studio.${id}`, section: EW_STUDIO_SECTION, label, defaultKeys: Object.freeze([...defaultKeys]), scope: 'studio' as const,
15
+ group, ...(command === false ? { command } : {}),
16
+ })
17
+
18
+ /** How the studio's command menu groups its actions, in its order. */
19
+ export const EW_STUDIO_COMMAND_GROUPS = Object.freeze([
20
+ { id: 'edit', label: 'Edit' },
21
+ { id: 'playback', label: 'Playback' },
22
+ { id: 'steps', label: 'Steps' },
23
+ { id: 'help', label: 'Help' },
24
+ ] as const)
25
+
26
+ export const EW_STUDIO_SHORTCUTS: readonly EntangledWorldsShortcut[] = Object.freeze([
27
+ studio('undo', 'Undo', ['Mod+KeyZ'], 'edit'),
28
+ studio('redo', 'Redo', ['Mod+Shift+KeyZ'], 'edit'),
29
+ studio('duplicate', 'Duplicate the selection', ['Mod+KeyD'], 'edit'),
30
+ studio('copy', 'Copy the selection', ['Mod+KeyC'], 'edit'),
31
+ studio('paste', 'Paste', ['Mod+KeyV'], 'edit'),
32
+ studio('playPause', 'Play or pause', ['Shift?+Space'], 'playback'),
33
+ studio('remove', 'Remove the selection', ['Shift?+Delete', 'Shift?+Backspace'], 'edit'),
34
+ studio('step.audio', 'Audio step', ['Digit1', 'Numpad1'], 'steps'),
35
+ studio('step.animations', 'Animations step', ['Digit2', 'Numpad2'], 'steps'),
36
+ studio('step.third', 'Export step (Release where there is no export)', ['Digit3', 'Numpad3'], 'steps'),
37
+ studio('step.release', 'Release step', ['Digit4', 'Numpad4'], 'steps'),
38
+ studio('help', 'Keyboard shortcuts', ['Shift?+Slash'], 'help'),
39
+ // Opens the menu itself, so the menu does not list it.
40
+ studio('commands', 'Commands', ['Mod+KeyK'], 'help', false),
41
+ ])
42
+
43
+ export const EW_PLAYER_SHORTCUTS: readonly EntangledWorldsShortcut[] = Object.freeze([
44
+ Object.freeze({
45
+ id: 'ew.player.playPause',
46
+ section: EW_PLAYER_SECTION,
47
+ label: 'Play or pause',
48
+ defaultKeys: Object.freeze(['Shift?+Alt?+Ctrl?+Meta?+Space']),
49
+ scope: 'player' as const,
50
+ }),
51
+ ])
@@ -0,0 +1,143 @@
1
+ // A key string for people: how a chord is shown (`⌘⇧Z`, `Ctrl+Shift+Z`, `Q`), and the key string a
2
+ // press makes when someone sets a key ("press a key to change").
3
+
4
+ import { isModifierCode, parseChord, type Chord } from './chord.js'
5
+
6
+ /** Apple keyboards show modifiers as symbols, and their command key is ⌘ (`Mod`); others write words and Ctrl. */
7
+ export type ShortcutPlatform = 'apple' | 'other'
8
+
9
+ /** The platform of this browser, by its own report; `other` outside a browser. */
10
+ export function shortcutPlatform(): ShortcutPlatform {
11
+ const nav = (globalThis as { navigator?: { platform?: string; userAgentData?: { platform?: string } } }).navigator
12
+ const name = nav?.userAgentData?.platform ?? nav?.platform ?? ''
13
+ return /mac|iphone|ipad|ipod/i.test(name) ? 'apple' : 'other'
14
+ }
15
+
16
+ /**
17
+ * The character a key place prints on this person's keyboard, when the browser can say
18
+ * (`navigator.keyboard.getLayoutMap()`, Chromium only); a key place it does not know is shown from
19
+ * its name.
20
+ */
21
+ export type KeyLayout = ReadonlyMap<string, string>
22
+
23
+ const NAMED: Readonly<Record<string, string>> = {
24
+ Space: 'Space', Enter: 'Enter', Escape: 'Esc', Tab: 'Tab', Backspace: 'Backspace', Delete: 'Delete',
25
+ Insert: 'Insert', Home: 'Home', End: 'End', PageUp: 'Page up', PageDown: 'Page down',
26
+ ArrowUp: '↑', ArrowDown: '↓', ArrowLeft: '←', ArrowRight: '→',
27
+ Minus: '-', Equal: '=', BracketLeft: '[', BracketRight: ']', Backslash: '\\', Semicolon: ';', Quote: "'",
28
+ Backquote: '`', Comma: ',', Period: '.', Slash: '/', IntlBackslash: '§',
29
+ NumpadAdd: 'Num +', NumpadSubtract: 'Num -', NumpadMultiply: 'Num *', NumpadDivide: 'Num /',
30
+ NumpadDecimal: 'Num .', NumpadEnter: 'Num Enter',
31
+ }
32
+
33
+ /** What a key place is called on a keyboard: `KeyQ` → `Q`, `Digit1` → `1`, `Numpad4` → `Num 4`. */
34
+ export function keyLabel(code: string, layout?: KeyLayout): string {
35
+ const printed = layout?.get(code)
36
+ if (printed && printed.trim()) return printed.length === 1 ? printed.toUpperCase() : printed
37
+ if (/^Key[A-Z]$/.test(code)) return code.slice(3)
38
+ if (/^Digit\d$/.test(code)) return code.slice(5)
39
+ if (/^Numpad\d$/.test(code)) return `Num ${code.slice(6)}`
40
+ return NAMED[code] ?? code
41
+ }
42
+
43
+ const SYMBOLS = { ctrl: '⌃', alt: '⌥', shift: '⇧', meta: '⌘' } as const
44
+ const WORDS = { ctrl: 'Ctrl', alt: 'Alt', shift: 'Shift', meta: 'Meta' } as const
45
+
46
+ /**
47
+ * The parts a chord is shown as, one per key to press: modifiers first, in the order the platform
48
+ * writes them, then the key. A modifier the chord merely allows (`Shift?`) is not shown — it is not
49
+ * a key anyone has to press. `null` for a key string that names no chord.
50
+ */
51
+ export function chordParts(keys: string, platform: ShortcutPlatform = shortcutPlatform(), layout?: KeyLayout): string[] | null {
52
+ // A sequence: each key's parts, one after the other (`G`, `H`).
53
+ if (typeof keys === 'string' && keys.includes(' ')) {
54
+ const steps = keys.split(' ').map((step) => (step.includes(' ') ? null : chordParts(step, platform, layout)))
55
+ return steps.length === 2 && steps.every(Boolean) ? (steps as string[][]).flat() : null
56
+ }
57
+ const chord = parseChord(keys)
58
+ if (!chord) return null
59
+ const held = (rule: Chord['shift']) => rule === 'held'
60
+ const ctrl = held(chord.ctrl) || (held(chord.mod) && platform === 'other')
61
+ const meta = held(chord.meta) || (held(chord.mod) && platform === 'apple')
62
+ const names = platform === 'apple' ? SYMBOLS : WORDS
63
+ // Apple's order is ⌃⌥⇧⌘; elsewhere Ctrl, Alt, Shift (and the rare Meta last).
64
+ const parts: string[] = []
65
+ if (ctrl) parts.push(names.ctrl)
66
+ if (held(chord.alt)) parts.push(platform === 'apple' ? names.alt : 'Alt')
67
+ if (held(chord.shift)) parts.push(names.shift)
68
+ if (meta) parts.push(names.meta)
69
+ // The help key is `?` wherever it lets Shift be held (its place is `/`): show what people press.
70
+ parts.push(chord.code === 'Slash' && chord.shift === 'any' && !layout ? '?' : keyLabel(chord.code, layout))
71
+ return parts
72
+ }
73
+
74
+ /** One line for a chord: `⌘⇧Z` on Apple keyboards, `Ctrl+Shift+Z` elsewhere. */
75
+ export function formatChord(keys: string, platform: ShortcutPlatform = shortcutPlatform(), layout?: KeyLayout): string {
76
+ if (keys.includes(' ')) return keys.split(' ').map((step) => formatChord(step, platform, layout)).join(' ')
77
+ const parts = chordParts(keys, platform, layout)
78
+ if (!parts) return keys
79
+ return parts.join(platform === 'apple' ? '' : '+')
80
+ }
81
+
82
+
83
+ /**
84
+ * The key string a press makes, for someone setting a key: exactly the modifiers held, the command
85
+ * key of their platform written `Mod` (⌘ on Apple, Ctrl elsewhere) so the key works on both. `null`
86
+ * while only modifiers are down, or for a press with no key place.
87
+ */
88
+ export function chordFromEvent(
89
+ event: { code: string; shiftKey: boolean; altKey: boolean; ctrlKey: boolean; metaKey: boolean },
90
+ platform: ShortcutPlatform = shortcutPlatform(),
91
+ ): string | null {
92
+ if (!event.code || isModifierCode(event.code)) return null
93
+ const parts: string[] = []
94
+ // ⌘ (Ctrl elsewhere) is written Mod so the key works on both — unless Ctrl and ⌘ are both held,
95
+ // which Mod cannot say: then both by name.
96
+ if (event.ctrlKey && event.metaKey) parts.push('Ctrl', 'Meta')
97
+ else if (platform === 'apple' ? event.metaKey : event.ctrlKey) parts.push('Mod')
98
+ else if (event.ctrlKey) parts.push('Ctrl')
99
+ else if (event.metaKey) parts.push('Meta')
100
+ if (event.altKey) parts.push('Alt')
101
+ if (event.shiftKey) parts.push('Shift')
102
+ parts.push(event.code)
103
+ const keys = parts.join('+')
104
+ return parseChord(keys) ? keys : null
105
+ }
106
+
107
+ const sameModifiers = (a: Chord, b: Chord) =>
108
+ a.shift === b.shift && a.alt === b.alt && a.ctrl === b.ctrl && a.meta === b.meta && a.mod === b.mod
109
+
110
+ /**
111
+ * The keys of several actions shown as one ("1 2 3", "Q W E", "⌥ 0–9"): when each has exactly one
112
+ * key and they differ only in the last key, the shared modifiers once and then the keys. Otherwise
113
+ * every key of every action, as it is. Read from the keys in force, so a person's own keys show.
114
+ */
115
+ export function mergedKeyParts(
116
+ keysPerAction: ReadonlyArray<readonly string[]>,
117
+ platform: ShortcutPlatform = shortcutPlatform(),
118
+ layout?: KeyLayout,
119
+ ): string[][] {
120
+ const chords = keysPerAction.map((keys) => (keys.length === 1 ? parseChord(keys[0]) : null))
121
+ const first = chords[0]
122
+ if (keysPerAction.length > 1 && first && chords.every((c) => c && sameModifiers(c, first))) {
123
+ const modifiers = (chordParts(keysPerAction[0][0], platform, layout) ?? []).slice(0, -1)
124
+ const labels = chords.map((c) => keyLabel(c!.code, layout))
125
+ const digits = labels.join('')
126
+ // The whole number row, in the row's order: one range.
127
+ const tail = digits === '1234567890' ? ['0–9'] : [labels.join(' ')]
128
+ return [[...modifiers, ...tail]]
129
+ }
130
+ return keysPerAction.flatMap((keys) => keys.map((k) => chordParts(k, platform, layout) ?? [k]))
131
+ }
132
+
133
+ /**
134
+ * A key someone just pressed for an action, as it is stored: when every default key of the action
135
+ * lets Shift be held (`Shift?`, the play keys that work while selecting several Orbiters) and the
136
+ * press had no Shift, the new key lets it be held too, so the action keeps working the same way.
137
+ */
138
+ export function recordedKeys(defaultKeys: readonly string[], pressed: string): string {
139
+ const chord = parseChord(pressed)
140
+ if (!chord || chord.shift !== 'free' || defaultKeys.length === 0) return pressed
141
+ const shiftFree = defaultKeys.every((keys) => parseChord(keys)?.shift === 'any')
142
+ return shiftFree ? `Shift?+${pressed}` : pressed
143
+ }
@@ -0,0 +1,69 @@
1
+ // Keyboard shortcuts, one system for every app: each app's catalogue of actions (id, section, label,
2
+ // default keys, scope) and one matcher that says which action a key press is. Keys are named by
3
+ // their place on the keyboard (`KeyboardEvent.code`). Framework-free: no React, no DOM beyond reading
4
+ // a key event.
5
+
6
+ export {
7
+ parseChord,
8
+ parseKeys,
9
+ keysOverlap,
10
+ chordMatches,
11
+ chordsOverlap,
12
+ isCommandChord,
13
+ type Chord,
14
+ type ModifierRule,
15
+ type ModifierState,
16
+ } from './chord.js'
17
+ export {
18
+ matchShortcut,
19
+ createShortcutMatcher,
20
+ SEQUENCE_WAIT_MS,
21
+ resolveBindings,
22
+ findClashes,
23
+ claimKeys,
24
+ isKeyClaimed,
25
+ isTypingTarget,
26
+ type ShortcutAction,
27
+ type ShortcutBindings,
28
+ type ShortcutOverrides,
29
+ type ShortcutEvent,
30
+ } from './match.js'
31
+ export {
32
+ ORBITERS_PLAY_SHORTCUTS,
33
+ ORBITERS_STUDIO_SHORTCUTS,
34
+ ORBITERS_PLAY_SECTION,
35
+ ORBITERS_STUDIO_SECTION,
36
+ ORBITERS_KEYBOARD_SURFACE_KEYS,
37
+ ORBITERS_COMMAND_GROUPS,
38
+ ORBITERS_PLAY_SHEET,
39
+ type OrbitersShortcut,
40
+ type OrbitersShortcutScope,
41
+ } from './orbiters.js'
42
+ export {
43
+ shortcutPlatform,
44
+ keyLabel,
45
+ chordParts,
46
+ formatChord,
47
+ chordFromEvent,
48
+ mergedKeyParts,
49
+ recordedKeys,
50
+ type ShortcutPlatform,
51
+ type KeyLayout,
52
+ } from './format.js'
53
+ export { SHORTCUT_SECTIONS, SHORTCUT_APPS, type ShortcutSection, type ShortcutAppId } from './sections.js'
54
+ export { SITE_SHORTCUTS, SITE_SECTION, type SiteShortcut } from './site.js'
55
+ export {
56
+ EW_STUDIO_SHORTCUTS,
57
+ EW_PLAYER_SHORTCUTS,
58
+ EW_STUDIO_SECTION,
59
+ EW_PLAYER_SECTION,
60
+ EW_STUDIO_COMMAND_GROUPS,
61
+ type EntangledWorldsShortcut,
62
+ } from './entangledWorlds.js'
63
+ export { shortcutLabel, shortcutSectionLabel, shortcutName } from './labels.js'
64
+ export {
65
+ createShortcutOverridesSource,
66
+ parseOverrides,
67
+ type ShortcutOverridesSource,
68
+ type ReadAccountSettings,
69
+ } from './overrides.js'
@@ -0,0 +1,139 @@
1
+ // What the actions and sections are called in each language the platform speaks, beside the
2
+ // English in the catalogues. One table, read by every app and the settings page, so a name is
3
+ // translated once.
4
+
5
+ import type { ShortcutAction } from './match.js'
6
+
7
+ type Names = Readonly<Record<string, string>>
8
+
9
+ const ES: Names = Object.freeze({
10
+ "ew.player.playPause": "Reproducir o pausar",
11
+ "ew.studio.commands": "Comandos",
12
+ "ew.studio.copy": "Copiar la selección",
13
+ "ew.studio.duplicate": "Duplicar la selección",
14
+ "ew.studio.help": "Atajos de teclado",
15
+ "ew.studio.paste": "Pegar",
16
+ "ew.studio.playPause": "Reproducir o pausar",
17
+ "ew.studio.redo": "Rehacer",
18
+ "ew.studio.remove": "Quitar la selección",
19
+ "ew.studio.step.animations": "Paso de animaciones",
20
+ "ew.studio.step.audio": "Paso de audio",
21
+ "ew.studio.step.release": "Paso de publicación",
22
+ "ew.studio.step.third": "Paso de exportación (Publicación donde no hay exportación)",
23
+ "ew.studio.undo": "Deshacer",
24
+ "orbiters.play.body.moon": "Luna",
25
+ "orbiters.play.body.star": "Estrella",
26
+ "orbiters.play.body.world": "Mundo",
27
+ "orbiters.play.dimension.1": "Primera dimensión",
28
+ "orbiters.play.dimension.2": "Segunda dimensión",
29
+ "orbiters.play.dimension.3": "Tercera dimensión",
30
+ "orbiters.play.help": "Atajos de teclado",
31
+ "orbiters.play.history.redo": "Rehacer",
32
+ "orbiters.play.history.undo": "Deshacer",
33
+ "orbiters.play.midiLearn": "MIDI learn",
34
+ "orbiters.play.panel.cosmicLfo": "Cosmic LFO",
35
+ "orbiters.play.panel.jamming": "Jamming",
36
+ "orbiters.play.panel.playback": "Reproducción",
37
+ "orbiters.play.panel.sensors": "Sensores",
38
+ "orbiters.play.performanceMode": "Modo rendimiento",
39
+ "orbiters.play.rec.hold": "Grabar mientras se mantiene",
40
+ "orbiters.play.rec.toggle": "Activar o desactivar Rec",
41
+ "orbiters.play.snapshot.recall.0": "Recuperar instantánea 0",
42
+ "orbiters.play.snapshot.recall.1": "Recuperar instantánea 1",
43
+ "orbiters.play.snapshot.recall.2": "Recuperar instantánea 2",
44
+ "orbiters.play.snapshot.recall.3": "Recuperar instantánea 3",
45
+ "orbiters.play.snapshot.recall.4": "Recuperar instantánea 4",
46
+ "orbiters.play.snapshot.recall.5": "Recuperar instantánea 5",
47
+ "orbiters.play.snapshot.recall.6": "Recuperar instantánea 6",
48
+ "orbiters.play.snapshot.recall.7": "Recuperar instantánea 7",
49
+ "orbiters.play.snapshot.recall.8": "Recuperar instantánea 8",
50
+ "orbiters.play.snapshot.recall.9": "Recuperar instantánea 9",
51
+ "orbiters.play.snapshot.store.0": "Guardar instantánea 0",
52
+ "orbiters.play.snapshot.store.1": "Guardar instantánea 1",
53
+ "orbiters.play.snapshot.store.2": "Guardar instantánea 2",
54
+ "orbiters.play.snapshot.store.3": "Guardar instantánea 3",
55
+ "orbiters.play.snapshot.store.4": "Guardar instantánea 4",
56
+ "orbiters.play.snapshot.store.5": "Guardar instantánea 5",
57
+ "orbiters.play.snapshot.store.6": "Guardar instantánea 6",
58
+ "orbiters.play.snapshot.store.7": "Guardar instantánea 7",
59
+ "orbiters.play.snapshot.store.8": "Guardar instantánea 8",
60
+ "orbiters.play.snapshot.store.9": "Guardar instantánea 9",
61
+ "orbiters.play.transport.restart": "Reproducir desde el principio",
62
+ "orbiters.play.transport.toggle": "Reproducir o pausar",
63
+ "orbiters.studio.map": "Mapear",
64
+ "orbiters.studio.redo": "Rehacer",
65
+ "orbiters.studio.undo": "Deshacer",
66
+ "site.commands": "Comandos",
67
+ "site.search": "Buscar",
68
+ "site.go.home": "Inicio",
69
+ "site.go.playground": "Playground",
70
+ "site.go.notifications": "Notificaciones",
71
+ "site.go.audios": "Mis audios",
72
+ "site.go.orbiters": "Mis Orbiters",
73
+ "site.go.worlds": "Mis Entangled Worlds",
74
+ "site.go.collections": "Mis colecciones",
75
+ "site.go.stars": "Mis estrellas",
76
+ "site.new.orbiter": "Nuevo Orbiter",
77
+ "site.new.audio": "Nuevo audio",
78
+ "site.new.world": "Nuevo Entangled World",
79
+ "site.settings": "Abrir la configuración",
80
+ "section:site": "Plantasia Space",
81
+ "app:plantasia-space": "Plantasia Space",
82
+ "app:orbiters": "Orbiters",
83
+ "app:entangled-worlds": "Entangled Worlds",
84
+ "part:orbiters-play": "Tocar",
85
+ "part:orbiters-studio": "Estudio",
86
+ "part:ew-studio": "Estudio",
87
+ "part:ew-player": "Reproductor",
88
+ "section:orbiters-play": "Orbiters: tocar",
89
+ "section:orbiters-studio": "Orbiter Studio",
90
+ "section:ew-studio": "Estudio de Entangled Worlds",
91
+ "section:ew-player": "Reproductor de Entangled Worlds",
92
+ "orbiters.play.screenCapture": "Captura de pantalla",
93
+ "orbiters.play.share": "Compartir",
94
+ "orbiters.play.fullscreen": "Pantalla completa",
95
+ "orbiters.play.commands": "Comandos",
96
+ "group:edit": "Edición",
97
+ "group:playback": "Reproducción",
98
+ "group:steps": "Pasos",
99
+ "group:help": "Ayuda",
100
+ "group:transport": "Transporte",
101
+ "group:view": "Vista",
102
+ "group:snapshots": "Instantáneas",
103
+ "group:panels": "Paneles",
104
+ "group:orbiter": "Orbiter",
105
+ "group:studio": "Estudio",
106
+ "row:playPause": "Reproducir / pausar",
107
+ "row:playFromStart": "Reproducir desde el inicio",
108
+ "row:recHeld": "REC mientras se mantiene",
109
+ "row:recLatch": "REC fijo",
110
+ "row:undo": "Deshacer",
111
+ "row:redo": "Rehacer",
112
+ "row:dimensions": "Dimensión I · II · III",
113
+ "row:bodies": "Mundo · Luna · Estrella",
114
+ "row:snapshotRecall": "Recuperar instantánea",
115
+ "row:snapshotStore": "Guardar instantánea",
116
+ "row:jamming": "Jamming",
117
+ "row:playback": "Reproducción",
118
+ "row:cosmicLfo": "Cosmic LFO",
119
+ "row:sensors": "Sensores",
120
+ "row:midiLearn": "MIDI learn",
121
+ "row:performanceMode": "Modo rendimiento",
122
+ })
123
+
124
+ const NAMES: Readonly<Record<string, Names>> = Object.freeze({ es: ES })
125
+
126
+ /** An action's name in a language (`es`, `es-AR`), falling back to the catalogue's English. */
127
+ export function shortcutLabel(action: Pick<ShortcutAction, 'id' | 'label'>, locale?: string): string {
128
+ return NAMES[(locale ?? '').slice(0, 2).toLowerCase()]?.[action.id] ?? action.label
129
+ }
130
+
131
+ /** A section's name in a language, falling back to the English. */
132
+ export function shortcutSectionLabel(section: { id: string; label: string }, locale?: string): string {
133
+ return NAMES[(locale ?? '').slice(0, 2).toLowerCase()]?.[`section:${section.id}`] ?? section.label
134
+ }
135
+
136
+ /** Any other named thing of the shortcuts (a command group `group:<id>`, a sheet row `row:<id>`). */
137
+ export function shortcutName(key: string, english: string, locale?: string): string {
138
+ return NAMES[(locale ?? '').slice(0, 2).toLowerCase()]?.[key] ?? english
139
+ }
@@ -0,0 +1,195 @@
1
+ // Which action a key press is. Each app keeps what its actions DO; this only answers which one a
2
+ // press names, so every app reads keys the same way: the modifiers, a field being typed in, and a
3
+ // surface that holds letters of its own are decided here, once.
4
+
5
+ import { chordMatches, isCommandChord, isModifierCode, keysOverlap, parseChord, parseKeys, type Chord, type ModifierState } from './chord.js'
6
+
7
+ /** One thing a key can do, as an app's catalogue declares it. */
8
+ export interface ShortcutAction<Scope extends string = string> {
9
+ /** `<app>.<area>.<action>`, e.g. `orbiters.play.panel.jamming`: the key a person's override is stored under. */
10
+ readonly id: string
11
+ /** The group it is shown in, one per app surface (`orbiters-play`). Keys clash only inside a section. */
12
+ readonly section: string
13
+ /** What it does, in sentence case. */
14
+ readonly label: string
15
+ /** The keys it has until the person changes them (chord strings, see `chord.ts`). */
16
+ readonly defaultKeys: readonly string[]
17
+ /** What it acts on, in the app's own terms (Orbiters: one deck, or this machine). */
18
+ readonly scope: Scope
19
+ /** Where a command menu lists it (`panels`, `snapshots`); unset, under the section itself. */
20
+ readonly group?: string
21
+ /** `false`: a key only, never a command to pick from a list (a key held down, the menu itself). */
22
+ readonly command?: boolean
23
+ }
24
+
25
+ /** The keys of each action, in the order they are tried: the first action a press matches is the one. */
26
+ export type ShortcutBindings = Iterable<readonly [actionId: string, keys: readonly string[]]>
27
+
28
+ /**
29
+ * A person's changes, as their settings store them: an action's own keys (`[]` = no key). An action
30
+ * left out keeps its defaults, so a default changed in code reaches everyone who never touched it.
31
+ */
32
+ export type ShortcutOverrides = ReadonlyArray<{ readonly id: string; readonly keys: readonly string[] }>
33
+
34
+ /** The key press as the matcher reads it: a `KeyboardEvent` has all of it. */
35
+ export interface ShortcutEvent extends ModifierState {
36
+ readonly code: string
37
+ readonly key: string
38
+ readonly target?: unknown
39
+ }
40
+
41
+ /**
42
+ * Every action's keys: its defaults, or the person's override (unknown actions and keys that name no
43
+ * chord are dropped). Catalogue order is kept, so the earlier catalogue wins where two match one press.
44
+ */
45
+ export function resolveBindings(
46
+ catalogue: Iterable<ShortcutAction>,
47
+ overrides: ShortcutOverrides = [],
48
+ ): Map<string, readonly string[]> {
49
+ const own = new Map<string, readonly string[]>()
50
+ for (const entry of Array.isArray(overrides) ? overrides : []) {
51
+ if (entry && typeof entry.id === 'string' && Array.isArray(entry.keys)) own.set(entry.id, entry.keys)
52
+ }
53
+ const bindings = new Map<string, readonly string[]>()
54
+ for (const action of catalogue) {
55
+ const keys = own.get(action.id) ?? action.defaultKeys
56
+ bindings.set(action.id, keys.filter((key) => typeof key === 'string' && parseKeys(key) !== null))
57
+ }
58
+ return bindings
59
+ }
60
+
61
+ /** Two actions one press could be: `[first, second, the key of the first that clashes]`. */
62
+ export function findClashes(bindings: ShortcutBindings): Array<readonly [string, string, string]> {
63
+ const entries = [...bindings]
64
+ const clashes: Array<readonly [string, string, string]> = []
65
+ entries.forEach(([a, aKeys], i) => {
66
+ for (const [b, bKeys] of entries.slice(i + 1)) {
67
+ const key = aKeys.find((ak) => bKeys.some((bk) => keysOverlap(ak, bk)))
68
+ if (key !== undefined) clashes.push([a, b, key])
69
+ }
70
+ })
71
+ return clashes
72
+ }
73
+
74
+ // ---------------------------------------------------------------------------------------------
75
+ // Surface claims
76
+
77
+ const claims = new Set<ReadonlySet<string>>()
78
+
79
+ /**
80
+ * Take letters away from the shortcuts while a surface is on screen, until the returned release is
81
+ * called. An on-screen keyboard plays from the computer keyboard, and a note key that also switched a
82
+ * panel would take the keyboard away mid-phrase. Keys are `event.key` values, lower-cased (the
83
+ * character, as the keyboard surface reads them).
84
+ */
85
+ export function claimKeys(keys: Iterable<string>): () => void {
86
+ const claim: ReadonlySet<string> = new Set([...keys].map((key) => key.toLowerCase()))
87
+ claims.add(claim)
88
+ return () => {
89
+ claims.delete(claim)
90
+ }
91
+ }
92
+
93
+ /** Whether a surface holds this key. A key with Ctrl, ⌘ or Option is never claimed (⌘Z stays undo). */
94
+ export function isKeyClaimed(event: Pick<ShortcutEvent, 'key' | 'metaKey' | 'ctrlKey' | 'altKey'>): boolean {
95
+ if (!claims.size || typeof event.key !== 'string' || event.metaKey || event.ctrlKey || event.altKey) return false
96
+ const key = event.key.toLowerCase()
97
+ for (const claim of claims) if (claim.has(key)) return true
98
+ return false
99
+ }
100
+
101
+ // ---------------------------------------------------------------------------------------------
102
+ // Typing
103
+
104
+ interface TargetLike {
105
+ readonly isContentEditable?: boolean
106
+ readonly tagName?: unknown
107
+ readonly type?: unknown
108
+ getAttribute?(name: string): string | null
109
+ }
110
+
111
+ const asTarget = (target: unknown): TargetLike | null =>
112
+ target !== null && typeof target === 'object' ? (target as TargetLike) : null
113
+
114
+ const roleOf = (el: TargetLike) => (typeof el.getAttribute === 'function' ? el.getAttribute('role') : null)
115
+
116
+ /** Inputs that take no typing: a slider keeps the shortcuts working while it holds focus. */
117
+ const UNTYPED_INPUTS = new Set(['range', 'color', 'file'])
118
+
119
+ /** A text field: every key typed there is the field's, ⌘Z included (it undoes the typing). */
120
+ export function isTypingTarget(target: unknown): boolean {
121
+ const el = asTarget(target)
122
+ if (!el) return false
123
+ if (el.isContentEditable === true || roleOf(el) === 'textbox') return true
124
+ const tag = typeof el.tagName === 'string' ? el.tagName.toUpperCase() : ''
125
+ if (tag === 'INPUT') return !UNTYPED_INPUTS.has(typeof el.type === 'string' ? el.type.toLowerCase() : '')
126
+ return tag === 'TEXTAREA' || tag === 'SELECT'
127
+ }
128
+
129
+ /** A widget that reads typed characters (a combobox's type-to-find), though it is no text field. */
130
+ function readsCharacters(target: unknown): boolean {
131
+ const el = asTarget(target)
132
+ return el !== null && roleOf(el) === 'combobox'
133
+ }
134
+
135
+ /**
136
+ * The action this press is, or `null`. Not one while the person is typing in a field, nor a key a
137
+ * surface holds; a widget that reads characters keeps its characters but not the ⌘ commands.
138
+ */
139
+ export function matchShortcut(event: ShortcutEvent, bindings: ShortcutBindings): string | null {
140
+ if (!event.code || isTypingTarget(event.target) || isKeyClaimed(event)) return null
141
+ const characters = readsCharacters(event.target)
142
+ for (const [actionId, keys] of bindings) {
143
+ for (const key of keys) {
144
+ const chord = parseChord(key)
145
+ if (!chord || !chordMatches(chord, event.code, event)) continue
146
+ if (characters && !isCommandChord(chord)) return null
147
+ return actionId
148
+ }
149
+ }
150
+ return null
151
+ }
152
+
153
+ // ---------------------------------------------------------------------------------------------
154
+ // Sequences
155
+
156
+ /** How long the second key of a sequence (`G`, then `H`) may follow the first. */
157
+ export const SEQUENCE_WAIT_MS = 1500
158
+
159
+ // The sequences of a set of bindings, read once per bindings object (they change with the overrides).
160
+ const sequencesOf = new WeakMap<object, Array<readonly [string, Chord[]]>>()
161
+ function sequences(bindings: ShortcutBindings): Array<readonly [string, Chord[]]> {
162
+ const known = typeof bindings === 'object' ? sequencesOf.get(bindings) : undefined
163
+ if (known) return known
164
+ const found = [...bindings].flatMap(([id, keys]) =>
165
+ keys.map((k) => [id, parseKeys(k)] as const).filter((entry): entry is readonly [string, Chord[]] => entry[1]?.length === 2))
166
+ if (typeof bindings === 'object') sequencesOf.set(bindings, found)
167
+ return found
168
+ }
169
+
170
+ /**
171
+ * A matcher that also knows sequences: it remembers the first key of one for a moment and answers
172
+ * the action when the second follows. One per listener (it holds that moment). A first key answers
173
+ * nothing; any other key, a typed one or a wait past `waitMs` forgets it.
174
+ */
175
+ export function createShortcutMatcher(waitMs: number = SEQUENCE_WAIT_MS, now: () => number = Date.now) {
176
+ let first: (ModifierState & { code: string; at: number }) | null = null
177
+ return function match(event: ShortcutEvent, bindings: ShortcutBindings): string | null {
178
+ if (event.code && isModifierCode(event.code)) return null
179
+ const pending = first && now() - first.at <= waitMs ? first : null
180
+ first = null
181
+ if (!event.code || isTypingTarget(event.target) || isKeyClaimed(event)) return null
182
+ // A widget that reads characters keeps them: no sequence starts or ends there.
183
+ const characters = readsCharacters(event.target)
184
+ const known = characters ? [] : sequences(bindings)
185
+ if (pending) {
186
+ for (const [id, [one, two]] of known)
187
+ if (chordMatches(one, pending.code, pending) && chordMatches(two, event.code, event)) return id
188
+ }
189
+ if (known.some(([, [one]]) => chordMatches(one, event.code, event))) {
190
+ first = { code: event.code, shiftKey: event.shiftKey, altKey: event.altKey, ctrlKey: event.ctrlKey, metaKey: event.metaKey, at: now() }
191
+ return null
192
+ }
193
+ return matchShortcut(event, bindings)
194
+ }
195
+ }