entangled-worlds-orbiters-shared 4.1.0 → 5.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,145 @@
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
+ import { chordMatches, isCommandChord, isModifierCode, keysOverlap, parseChord, parseKeys } from './chord.js';
5
+ /**
6
+ * Every action's keys: its defaults, or the person's override (unknown actions and keys that name no
7
+ * chord are dropped). Catalogue order is kept, so the earlier catalogue wins where two match one press.
8
+ */
9
+ export function resolveBindings(catalogue, overrides = []) {
10
+ const own = new Map();
11
+ for (const entry of Array.isArray(overrides) ? overrides : []) {
12
+ if (entry && typeof entry.id === 'string' && Array.isArray(entry.keys))
13
+ own.set(entry.id, entry.keys);
14
+ }
15
+ const bindings = new Map();
16
+ for (const action of catalogue) {
17
+ const keys = own.get(action.id) ?? action.defaultKeys;
18
+ bindings.set(action.id, keys.filter((key) => typeof key === 'string' && parseKeys(key) !== null));
19
+ }
20
+ return bindings;
21
+ }
22
+ /** Two actions one press could be: `[first, second, the key of the first that clashes]`. */
23
+ export function findClashes(bindings) {
24
+ const entries = [...bindings];
25
+ const clashes = [];
26
+ entries.forEach(([a, aKeys], i) => {
27
+ for (const [b, bKeys] of entries.slice(i + 1)) {
28
+ const key = aKeys.find((ak) => bKeys.some((bk) => keysOverlap(ak, bk)));
29
+ if (key !== undefined)
30
+ clashes.push([a, b, key]);
31
+ }
32
+ });
33
+ return clashes;
34
+ }
35
+ // ---------------------------------------------------------------------------------------------
36
+ // Surface claims
37
+ const claims = new Set();
38
+ /**
39
+ * Take letters away from the shortcuts while a surface is on screen, until the returned release is
40
+ * called. An on-screen keyboard plays from the computer keyboard, and a note key that also switched a
41
+ * panel would take the keyboard away mid-phrase. Keys are `event.key` values, lower-cased (the
42
+ * character, as the keyboard surface reads them).
43
+ */
44
+ export function claimKeys(keys) {
45
+ const claim = new Set([...keys].map((key) => key.toLowerCase()));
46
+ claims.add(claim);
47
+ return () => {
48
+ claims.delete(claim);
49
+ };
50
+ }
51
+ /** Whether a surface holds this key. A key with Ctrl, ⌘ or Option is never claimed (⌘Z stays undo). */
52
+ export function isKeyClaimed(event) {
53
+ if (!claims.size || typeof event.key !== 'string' || event.metaKey || event.ctrlKey || event.altKey)
54
+ return false;
55
+ const key = event.key.toLowerCase();
56
+ for (const claim of claims)
57
+ if (claim.has(key))
58
+ return true;
59
+ return false;
60
+ }
61
+ const asTarget = (target) => target !== null && typeof target === 'object' ? target : null;
62
+ const roleOf = (el) => (typeof el.getAttribute === 'function' ? el.getAttribute('role') : null);
63
+ /** Inputs that take no typing: a slider keeps the shortcuts working while it holds focus. */
64
+ const UNTYPED_INPUTS = new Set(['range', 'color', 'file']);
65
+ /** A text field: every key typed there is the field's, ⌘Z included (it undoes the typing). */
66
+ export function isTypingTarget(target) {
67
+ const el = asTarget(target);
68
+ if (!el)
69
+ return false;
70
+ if (el.isContentEditable === true || roleOf(el) === 'textbox')
71
+ return true;
72
+ const tag = typeof el.tagName === 'string' ? el.tagName.toUpperCase() : '';
73
+ if (tag === 'INPUT')
74
+ return !UNTYPED_INPUTS.has(typeof el.type === 'string' ? el.type.toLowerCase() : '');
75
+ return tag === 'TEXTAREA' || tag === 'SELECT';
76
+ }
77
+ /** A widget that reads typed characters (a combobox's type-to-find), though it is no text field. */
78
+ function readsCharacters(target) {
79
+ const el = asTarget(target);
80
+ return el !== null && roleOf(el) === 'combobox';
81
+ }
82
+ /**
83
+ * The action this press is, or `null`. Not one while the person is typing in a field, nor a key a
84
+ * surface holds; a widget that reads characters keeps its characters but not the ⌘ commands.
85
+ */
86
+ export function matchShortcut(event, bindings) {
87
+ if (!event.code || isTypingTarget(event.target) || isKeyClaimed(event))
88
+ return null;
89
+ const characters = readsCharacters(event.target);
90
+ for (const [actionId, keys] of bindings) {
91
+ for (const key of keys) {
92
+ const chord = parseChord(key);
93
+ if (!chord || !chordMatches(chord, event.code, event))
94
+ continue;
95
+ if (characters && !isCommandChord(chord))
96
+ return null;
97
+ return actionId;
98
+ }
99
+ }
100
+ return null;
101
+ }
102
+ // ---------------------------------------------------------------------------------------------
103
+ // Sequences
104
+ /** How long the second key of a sequence (`G`, then `H`) may follow the first. */
105
+ export const SEQUENCE_WAIT_MS = 1500;
106
+ // The sequences of a set of bindings, read once per bindings object (they change with the overrides).
107
+ const sequencesOf = new WeakMap();
108
+ function sequences(bindings) {
109
+ const known = typeof bindings === 'object' ? sequencesOf.get(bindings) : undefined;
110
+ if (known)
111
+ return known;
112
+ const found = [...bindings].flatMap(([id, keys]) => keys.map((k) => [id, parseKeys(k)]).filter((entry) => entry[1]?.length === 2));
113
+ if (typeof bindings === 'object')
114
+ sequencesOf.set(bindings, found);
115
+ return found;
116
+ }
117
+ /**
118
+ * A matcher that also knows sequences: it remembers the first key of one for a moment and answers
119
+ * the action when the second follows. One per listener (it holds that moment). A first key answers
120
+ * nothing; any other key, a typed one or a wait past `waitMs` forgets it.
121
+ */
122
+ export function createShortcutMatcher(waitMs = SEQUENCE_WAIT_MS, now = Date.now) {
123
+ let first = null;
124
+ return function match(event, bindings) {
125
+ if (event.code && isModifierCode(event.code))
126
+ return null;
127
+ const pending = first && now() - first.at <= waitMs ? first : null;
128
+ first = null;
129
+ if (!event.code || isTypingTarget(event.target) || isKeyClaimed(event))
130
+ return null;
131
+ // A widget that reads characters keeps them: no sequence starts or ends there.
132
+ const characters = readsCharacters(event.target);
133
+ const known = characters ? [] : sequences(bindings);
134
+ if (pending) {
135
+ for (const [id, [one, two]] of known)
136
+ if (chordMatches(one, pending.code, pending) && chordMatches(two, event.code, event))
137
+ return id;
138
+ }
139
+ if (known.some(([, [one]]) => chordMatches(one, event.code, event))) {
140
+ first = { code: event.code, shiftKey: event.shiftKey, altKey: event.altKey, ctrlKey: event.ctrlKey, metaKey: event.metaKey, at: now() };
141
+ return null;
142
+ }
143
+ return matchShortcut(event, bindings);
144
+ };
145
+ }
@@ -0,0 +1,62 @@
1
+ import { type ShortcutCatalogue } from './catalogue.js';
2
+ import { type ShortcutAction, type ShortcutOverrides } from './match.js';
3
+ /** The overrides in a stored value, or `null` when it is not a list of `{ id, keys }`. */
4
+ export declare function parseOverrides(value: unknown): ShortcutOverrides | null;
5
+ /**
6
+ * How the app reads the signed-in person's settings: `null` when no one is signed in (the
7
+ * default keys); `undefined` when the read failed (the overrides in force are kept: a blip must not
8
+ * swap someone's keys for the defaults).
9
+ */
10
+ export type ReadAccountSettings = (options: {
11
+ fresh: boolean;
12
+ }) => Promise<{
13
+ shortcuts?: unknown;
14
+ } | null | undefined>;
15
+ /**
16
+ * How the app reads the catalogue (`{ version, sections }`); `undefined` or a throw when the read
17
+ * failed (the catalogue in force is kept). There is no copy in the app: until the first read
18
+ * answers, no key does anything.
19
+ */
20
+ export type ReadShortcutCatalogue = (options: {
21
+ fresh: boolean;
22
+ }) => Promise<unknown>;
23
+ export interface ShortcutSource {
24
+ /** The catalogue in force (empty until it is read). */
25
+ catalogue(): ShortcutCatalogue;
26
+ /** The actions of these sections, the first named winning a shared key; the same list until the catalogue changes. */
27
+ actions(...sectionIds: string[]): readonly ShortcutAction[];
28
+ /** The person's overrides in force. */
29
+ overrides(): ShortcutOverrides;
30
+ /** A list of actions with their keys now (kept until the catalogue or the overrides change). */
31
+ bindings(actions: readonly ShortcutAction[]): Map<string, readonly string[]>;
32
+ /** Called whenever the catalogue or the overrides change; returns the unsubscribe. */
33
+ subscribe(listener: () => void): () => void;
34
+ /** Read both again (`fresh`: past the app's own cached read). The newest read of each wins, whatever order they end in. */
35
+ refresh(options?: {
36
+ fresh?: boolean;
37
+ }): Promise<void>;
38
+ /** Read now, and again whenever the page comes back to the front; once per source. */
39
+ bind(): void;
40
+ /** For tests: set the overrides directly. */
41
+ setOverrides(overrides: ShortcutOverrides): void;
42
+ /** For tests: set the catalogue directly. */
43
+ setCatalogue(catalogue: ShortcutCatalogue): void;
44
+ }
45
+ /**
46
+ * Where a device keeps the last catalogue it read: offline (the desktop app with no connection) the
47
+ * keys are the ones it last had, and on every start they answer before the read comes back. A copy of
48
+ * what was served, never a list of its own.
49
+ */
50
+ export interface ShortcutCatalogueStore {
51
+ load(): unknown;
52
+ save(value: unknown): void;
53
+ }
54
+ export declare const CATALOGUE_STORAGE_KEY = "ps.shortcutCatalogue";
55
+ /** This browser's localStorage, when there is one and it may be used; otherwise nothing is kept. */
56
+ export declare function localShortcutCatalogueStore(): ShortcutCatalogueStore | null;
57
+ export declare function createShortcutSource({ readCatalogue, readAccount, store, }: {
58
+ readCatalogue: ReadShortcutCatalogue;
59
+ readAccount: ReadAccountSettings;
60
+ /** Where the last catalogue read is kept (this browser's localStorage by default; `null`: nowhere). */
61
+ store?: ShortcutCatalogueStore | null;
62
+ }): ShortcutSource;
@@ -0,0 +1,139 @@
1
+ // Where an app's keys come from, read the same way by every app: the catalogue (every action and its
2
+ // default keys, from the backend) and the person's own changes (their account's settings; someone
3
+ // signed out has the defaults). Both are read at start and again whenever the page comes back to the
4
+ // front, so a key changed in the catalogue or on the settings page applies on return, without a reload.
5
+ //
6
+ // Framework-free: the app hands in how it reads each (its own API client) and gets the catalogue, the
7
+ // overrides, and each list of actions' resolved keys back, kept until either changes.
8
+ import { EMPTY_CATALOGUE, parseCatalogue, sectionActions } from './catalogue.js';
9
+ import { resolveBindings } from './match.js';
10
+ /** The overrides in a stored value, or `null` when it is not a list of `{ id, keys }`. */
11
+ export function parseOverrides(value) {
12
+ if (!Array.isArray(value))
13
+ return null;
14
+ return value.filter((entry) => !!entry && typeof entry.id === 'string' && Array.isArray(entry.keys) && entry.keys.every((k) => typeof k === 'string'));
15
+ }
16
+ export const CATALOGUE_STORAGE_KEY = 'ps.shortcutCatalogue';
17
+ /** This browser's localStorage, when there is one and it may be used; otherwise nothing is kept. */
18
+ export function localShortcutCatalogueStore() {
19
+ const storage = globalThis.localStorage;
20
+ if (!storage)
21
+ return null;
22
+ return {
23
+ load() {
24
+ try {
25
+ const raw = storage.getItem(CATALOGUE_STORAGE_KEY);
26
+ return raw ? JSON.parse(raw) : undefined;
27
+ }
28
+ catch {
29
+ return undefined;
30
+ }
31
+ },
32
+ save(value) {
33
+ try {
34
+ storage.setItem(CATALOGUE_STORAGE_KEY, JSON.stringify(value));
35
+ }
36
+ catch {
37
+ // Full or refused (a private window): the next start reads the backend first, as without a store.
38
+ }
39
+ },
40
+ };
41
+ }
42
+ /** Coming back to the front twice in a row (visible, then focus) reads once. */
43
+ const REFRESH_GAP_MS = 2000;
44
+ /** Keeps the answer of the newest read that answered: an older one ending later says nothing new. */
45
+ function newestRead(read, apply) {
46
+ let latest = 0;
47
+ let applied = 0;
48
+ return async (fresh) => {
49
+ const ticket = ++latest;
50
+ let value;
51
+ try {
52
+ value = await read(fresh);
53
+ }
54
+ catch {
55
+ value = undefined;
56
+ }
57
+ if (value === undefined || ticket < applied)
58
+ return;
59
+ applied = ticket;
60
+ apply(value);
61
+ };
62
+ }
63
+ export function createShortcutSource({ readCatalogue, readAccount, store = localShortcutCatalogueStore(), }) {
64
+ let catalogue = (store && parseCatalogue(store.load())) || EMPTY_CATALOGUE;
65
+ let overrides = [];
66
+ let resolved = new WeakMap();
67
+ let lastRefreshAt = -Infinity;
68
+ let bound = false;
69
+ const listeners = new Set();
70
+ const changed = () => {
71
+ resolved = new WeakMap();
72
+ listeners.forEach((listener) => listener());
73
+ };
74
+ const applyOverrides = (next) => {
75
+ if (JSON.stringify(next) === JSON.stringify(overrides))
76
+ return;
77
+ overrides = next;
78
+ changed();
79
+ };
80
+ const applyCatalogue = (next) => {
81
+ if (next === catalogue || (next.version && next.version === catalogue.version && next.sections.length === catalogue.sections.length))
82
+ return;
83
+ catalogue = next;
84
+ changed();
85
+ };
86
+ const refreshCatalogue = newestRead(async (fresh) => {
87
+ const value = await readCatalogue({ fresh });
88
+ const read = value === undefined ? null : parseCatalogue(value);
89
+ if (!read)
90
+ return undefined;
91
+ if (read.version !== catalogue.version)
92
+ store?.save(value);
93
+ return read;
94
+ }, applyCatalogue);
95
+ const refreshAccount = newestRead(async (fresh) => {
96
+ const settings = await readAccount({ fresh });
97
+ return settings === undefined ? undefined : settings === null ? [] : (parseOverrides(settings.shortcuts) ?? []);
98
+ }, applyOverrides);
99
+ const refresh = async ({ fresh = false } = {}) => {
100
+ lastRefreshAt = Date.now();
101
+ await Promise.all([refreshCatalogue(fresh), refreshAccount(fresh)]);
102
+ };
103
+ return {
104
+ catalogue: () => catalogue,
105
+ actions: (...sectionIds) => sectionActions(catalogue, ...sectionIds),
106
+ overrides: () => overrides,
107
+ bindings(actions) {
108
+ let map = resolved.get(actions);
109
+ if (!map) {
110
+ map = resolveBindings(actions, overrides);
111
+ resolved.set(actions, map);
112
+ }
113
+ return map;
114
+ },
115
+ subscribe(listener) {
116
+ listeners.add(listener);
117
+ return () => {
118
+ listeners.delete(listener);
119
+ };
120
+ },
121
+ refresh,
122
+ bind() {
123
+ const win = globalThis;
124
+ if (bound || typeof win.addEventListener !== 'function' || !win.document?.addEventListener)
125
+ return;
126
+ bound = true;
127
+ void refresh();
128
+ const onFront = () => {
129
+ if (win.document?.visibilityState !== 'visible' || Date.now() - lastRefreshAt < REFRESH_GAP_MS)
130
+ return;
131
+ void refresh({ fresh: true });
132
+ };
133
+ win.document.addEventListener('visibilitychange', onFront);
134
+ win.addEventListener('focus', onFront);
135
+ },
136
+ setOverrides: applyOverrides,
137
+ setCatalogue: applyCatalogue,
138
+ };
139
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "entangled-worlds-orbiters-shared",
3
- "version": "4.1.0",
3
+ "version": "5.0.0",
4
4
  "description": "Shared library for entangled worlds orbiters - contains core world rendering, moons system, and UI components",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -86,6 +86,10 @@
86
86
  "./audio": {
87
87
  "types": "./dist/audio/index.d.ts",
88
88
  "import": "./dist/audio/index.js"
89
+ },
90
+ "./shortcuts": {
91
+ "types": "./dist/shortcuts/index.d.ts",
92
+ "import": "./dist/shortcuts/index.js"
89
93
  }
90
94
  },
91
95
  "files": [
@@ -0,0 +1,172 @@
1
+ // The shortcut catalogue as the apps read it: every app's sections of actions, their default keys and
2
+ // names, as the backend serves them (from its config, so a key or a name changes without a library
3
+ // release). This file only reads what was served; it holds no actions of its own.
4
+
5
+ import type { ShortcutAction, ShortcutNames } from './match.js'
6
+
7
+ /** Something with a name: English `label`, other languages in `names`. */
8
+ export interface ShortcutNamed {
9
+ readonly id: string
10
+ readonly label: string
11
+ readonly names?: ShortcutNames
12
+ }
13
+
14
+ /** A row of a keys sheet (`?`): one line for one or more actions whose keys show together. */
15
+ export interface ShortcutSheetRow extends ShortcutNamed {
16
+ readonly actions: readonly string[]
17
+ }
18
+
19
+ export interface ShortcutSheetColumn extends ShortcutNamed {
20
+ readonly rows: readonly ShortcutSheetRow[]
21
+ }
22
+
23
+ /** One surface's keys (`orbiters-play`, `ew-studio`, `site`). Two actions clash only inside a section. */
24
+ export interface ShortcutSection {
25
+ readonly id: string
26
+ /** The app it belongs to (`orbiters`) and that app's name. */
27
+ readonly app: string
28
+ readonly appLabel: string
29
+ readonly appNames?: ShortcutNames
30
+ readonly label: string
31
+ readonly names?: ShortcutNames
32
+ /** Its name inside the app (`Play`, `Studio`); none when the app has only this section. */
33
+ readonly part?: string
34
+ readonly partNames?: ShortcutNames
35
+ /** How a command menu groups the actions, in its order. */
36
+ readonly groups: readonly ShortcutNamed[]
37
+ /** The keys sheet, where the app shows one in columns. */
38
+ readonly sheet?: readonly ShortcutSheetColumn[]
39
+ readonly actions: readonly ShortcutAction[]
40
+ /**
41
+ * Letters a surface of this section plays while it is open (`event.key`, lower-case; the Orbiters
42
+ * on-screen keyboard): a shortcut on one of them waits until it closes.
43
+ */
44
+ readonly heldKeys?: readonly string[]
45
+ }
46
+
47
+ export interface ShortcutCatalogue {
48
+ /** Changes whenever the catalogue is edited. */
49
+ readonly version: string
50
+ readonly sections: readonly ShortcutSection[]
51
+ }
52
+
53
+ /** Before the catalogue is read: no sections, so no key does anything yet. */
54
+ export const EMPTY_CATALOGUE: ShortcutCatalogue = Object.freeze({ version: '', sections: Object.freeze([]) })
55
+
56
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
57
+ !!value && typeof value === 'object' && !Array.isArray(value)
58
+ const isString = (value: unknown): value is string => typeof value === 'string' && value.length > 0
59
+
60
+ function names(value: unknown): ShortcutNames | undefined {
61
+ if (!isRecord(value)) return undefined
62
+ const out: Record<string, string> = {}
63
+ for (const [locale, name] of Object.entries(value)) if (isString(name)) out[locale] = name
64
+ return Object.freeze(out)
65
+ }
66
+
67
+ function named(value: unknown): ShortcutNamed | null {
68
+ if (!isRecord(value) || !isString(value.id) || !isString(value.label)) return null
69
+ return { id: value.id, label: value.label, names: names(value.names) }
70
+ }
71
+
72
+ function action(value: unknown): ShortcutAction | null {
73
+ const base = named(value)
74
+ if (!base || !isRecord(value) || !isString(value.scope) || !Array.isArray(value.defaultKeys)) return null
75
+ return Object.freeze({
76
+ ...base,
77
+ defaultKeys: Object.freeze(value.defaultKeys.filter(isString)),
78
+ scope: value.scope,
79
+ ...(isString(value.group) ? { group: value.group } : {}),
80
+ ...(value.command === false ? { command: false } : {}),
81
+ ...(isString(value.href) ? { href: value.href } : {}),
82
+ ...(value.signedIn === true ? { signedIn: true } : {}),
83
+ })
84
+ }
85
+
86
+ const list = <T>(value: unknown, read: (item: unknown) => T | null): readonly T[] =>
87
+ Object.freeze(Array.isArray(value) ? value.map(read).filter((item): item is T => item !== null) : [])
88
+
89
+ function section(value: unknown): ShortcutSection | null {
90
+ const base = named(value)
91
+ if (!base || !isRecord(value) || !isString(value.app) || !isString(value.appLabel)) return null
92
+ return Object.freeze({
93
+ ...base,
94
+ app: value.app,
95
+ appLabel: value.appLabel,
96
+ appNames: names(value.appNames),
97
+ ...(isString(value.part) ? { part: value.part, partNames: names(value.partNames) } : {}),
98
+ groups: list(value.groups, named),
99
+ ...(Array.isArray(value.sheet)
100
+ ? {
101
+ sheet: list(value.sheet, (column) => {
102
+ const head = named(column)
103
+ if (!head || !isRecord(column)) return null
104
+ return Object.freeze({
105
+ ...head,
106
+ rows: list(column.rows, (row) => {
107
+ const line = named(row)
108
+ return line && isRecord(row) ? Object.freeze({ ...line, actions: list(row.actions, (id) => (isString(id) ? id : null)) }) : null
109
+ }),
110
+ })
111
+ }),
112
+ }
113
+ : {}),
114
+ actions: list(value.actions, action),
115
+ ...(Array.isArray(value.heldKeys) ? { heldKeys: list(value.heldKeys, (key) => (isString(key) ? key : null)) } : {}),
116
+ })
117
+ }
118
+
119
+ /**
120
+ * The catalogue a response holds (`{ version, sections }`), or `null` when it holds none. A malformed
121
+ * section or action is left out rather than failing the whole read.
122
+ */
123
+ export function parseCatalogue(value: unknown): ShortcutCatalogue | null {
124
+ if (!isRecord(value) || !Array.isArray(value.sections)) return null
125
+ return Object.freeze({ version: typeof value.version === 'string' ? value.version : '', sections: list(value.sections, section) })
126
+ }
127
+
128
+ /** A name in a language (`es`, `es-AR`), the English when there is none in it. */
129
+ export function localName(item: { readonly label: string; readonly names?: ShortcutNames }, locale?: string): string {
130
+ return item.names?.[(locale ?? '').slice(0, 2).toLowerCase()] ?? item.label
131
+ }
132
+
133
+ /** A section's app name in a language. */
134
+ export function localAppName(section: Pick<ShortcutSection, 'appLabel' | 'appNames'>, locale?: string): string {
135
+ return localName({ label: section.appLabel, names: section.appNames }, locale)
136
+ }
137
+
138
+ /** A section's part name (`Play`, `Studio`) in a language; `undefined` when it has none. */
139
+ export function localPartName(section: Pick<ShortcutSection, 'part' | 'partNames'>, locale?: string): string | undefined {
140
+ return section.part === undefined ? undefined : localName({ label: section.part, names: section.partNames }, locale)
141
+ }
142
+
143
+ /** The apps the catalogue has, in its order. */
144
+ export function shortcutApps(catalogue: ShortcutCatalogue): ReadonlyArray<{ id: string; label: string; names?: ShortcutNames }> {
145
+ const seen = new Map<string, { id: string; label: string; names?: ShortcutNames }>()
146
+ for (const s of catalogue.sections) if (!seen.has(s.app)) seen.set(s.app, { id: s.app, label: s.appLabel, names: s.appNames })
147
+ return [...seen.values()]
148
+ }
149
+
150
+ const actionLists = new WeakMap<ShortcutCatalogue, Map<string, readonly ShortcutAction[]>>()
151
+
152
+ /**
153
+ * The actions of these sections, in the order named: where two sections hold one key, the first
154
+ * named wins (the Orbiter Studio lies over play). The same list object for as long as the catalogue
155
+ * is the same, so a cache keyed by it holds.
156
+ */
157
+ export function sectionActions(catalogue: ShortcutCatalogue, ...sectionIds: string[]): readonly ShortcutAction[] {
158
+ let lists = actionLists.get(catalogue)
159
+ if (!lists) actionLists.set(catalogue, (lists = new Map()))
160
+ const key = sectionIds.join('\n')
161
+ let found = lists.get(key)
162
+ if (!found) {
163
+ found = Object.freeze(sectionIds.flatMap((id) => catalogue.sections.find((s) => s.id === id)?.actions ?? []))
164
+ lists.set(key, found)
165
+ }
166
+ return found
167
+ }
168
+
169
+ /** One section, if the catalogue has it. */
170
+ export function findSection(catalogue: ShortcutCatalogue, sectionId: string): ShortcutSection | undefined {
171
+ return catalogue.sections.find((s) => s.id === sectionId)
172
+ }
@@ -0,0 +1,122 @@
1
+ // One key with its modifiers, written as a string: `Shift+KeyR`, `Mod+KeyZ`, `Shift?+Digit1`.
2
+ //
3
+ // The last part is the key's PLACE (`KeyboardEvent.code`), so a French or German keyboard keeps the
4
+ // same layout: the key, not the letter it prints. Before it, the modifiers:
5
+ //
6
+ // Shift, Alt, Ctrl, Meta held. One left out must NOT be held.
7
+ // Mod Ctrl or ⌘ (either, or both), the command key of every platform.
8
+ // Shift? (any, with ?) may be held or not: the action is the same either way.
9
+ //
10
+ // So `KeyQ` is Q alone, `Shift?+KeyQ` is Q with or without Shift, `Mod+Shift+KeyZ` is ⌘⇧Z or Ctrl⇧Z.
11
+ //
12
+ // Two chords with a space between are a sequence, pressed one after the other: `KeyG KeyH` is G,
13
+ // then H. A sequence is never one press, so `parseChord` names none; `parseKeys` reads both kinds.
14
+
15
+ /** What a modifier has to be for a chord to match: held, not held, or either. */
16
+ export type ModifierRule = 'held' | 'free' | 'any'
17
+
18
+ export interface Chord {
19
+ readonly code: string
20
+ readonly shift: ModifierRule
21
+ readonly alt: ModifierRule
22
+ readonly ctrl: ModifierRule
23
+ readonly meta: ModifierRule
24
+ /** Ctrl or ⌘: when `held`, at least one of the two is down, and neither is otherwise checked. */
25
+ readonly mod: ModifierRule
26
+ }
27
+
28
+ /** The modifier state of a key press: the four flags of a `KeyboardEvent`. */
29
+ export interface ModifierState {
30
+ readonly shiftKey: boolean
31
+ readonly altKey: boolean
32
+ readonly ctrlKey: boolean
33
+ readonly metaKey: boolean
34
+ }
35
+
36
+ const MODIFIERS = { Shift: 'shift', Alt: 'alt', Ctrl: 'ctrl', Meta: 'meta', Mod: 'mod' } as const
37
+ type ModifierName = keyof typeof MODIFIERS
38
+
39
+ const CODE = /^[A-Za-z][A-Za-z0-9]*$/
40
+
41
+ const parsed = new Map<string, Chord | null>()
42
+
43
+ /** The chord a key string names, or `null` when it names none (an unknown modifier, a doubled one, no key). */
44
+ export function parseChord(keys: string): Chord | null {
45
+ const known = parsed.get(keys)
46
+ if (known !== undefined) return known
47
+ const chord = parse(keys)
48
+ parsed.set(keys, chord)
49
+ return chord
50
+ }
51
+
52
+ function parse(keys: string): Chord | null {
53
+ if (typeof keys !== 'string') return null
54
+ const parts = keys.split('+')
55
+ const code = parts.pop()
56
+ if (!code || !CODE.test(code)) return null
57
+ const rules: Record<(typeof MODIFIERS)[ModifierName], ModifierRule> = {
58
+ shift: 'free', alt: 'free', ctrl: 'free', meta: 'free', mod: 'free',
59
+ }
60
+ const seen = new Set<string>()
61
+ for (const part of parts) {
62
+ const optional = part.endsWith('?')
63
+ const name = (optional ? part.slice(0, -1) : part) as ModifierName
64
+ if (!Object.hasOwn(MODIFIERS, name) || seen.has(name)) return null
65
+ seen.add(name)
66
+ rules[MODIFIERS[name]] = optional ? 'any' : 'held'
67
+ }
68
+ // Mod already speaks for Ctrl and ⌘: naming one of them beside it says two things about one key.
69
+ if (rules.mod !== 'free' && (rules.ctrl !== 'free' || rules.meta !== 'free')) return null
70
+ return { code, ...rules }
71
+ }
72
+
73
+ const fits = (rule: ModifierRule, down: boolean) => rule === 'any' || (rule === 'held') === Boolean(down)
74
+
75
+ /** Whether a press of `code` with these modifiers is this chord. */
76
+ export function chordMatches(chord: Chord, code: string, state: ModifierState): boolean {
77
+ if (chord.code !== code) return false
78
+ if (!fits(chord.shift, state.shiftKey) || !fits(chord.alt, state.altKey)) return false
79
+ if (chord.mod === 'held') return Boolean(state.ctrlKey || state.metaKey)
80
+ if (chord.mod === 'any') return true
81
+ return fits(chord.ctrl, state.ctrlKey) && fits(chord.meta, state.metaKey)
82
+ }
83
+
84
+ /** A chord that needs Ctrl or ⌘: a command, never a character typed. */
85
+ export function isCommandChord(chord: Chord): boolean {
86
+ return chord.mod === 'held' || chord.ctrl === 'held' || chord.meta === 'held'
87
+ }
88
+
89
+ const STATES: ModifierState[] = Array.from({ length: 16 }, (_, i) => ({
90
+ shiftKey: Boolean(i & 1), altKey: Boolean(i & 2), ctrlKey: Boolean(i & 4), metaKey: Boolean(i & 8),
91
+ }))
92
+
93
+ /** Whether one press could be both chords — the test for a clash. */
94
+ export function chordsOverlap(a: Chord, b: Chord): boolean {
95
+ return a.code === b.code && STATES.some((state) => chordMatches(a, a.code, state) && chordMatches(b, b.code, state))
96
+ }
97
+
98
+ /** The chords a key string names, one or two (a sequence); `null` when it names none. */
99
+ export function parseKeys(keys: string): Chord[] | null {
100
+ if (typeof keys !== 'string') return null
101
+ const steps = keys.split(' ')
102
+ if (steps.length > 2) return null
103
+ const chords = steps.map(parseChord)
104
+ return chords.every((chord): chord is Chord => chord !== null) ? chords : null
105
+ }
106
+
107
+ /**
108
+ * Whether two key strings could answer the same presses — the test for a clash. A single key and a
109
+ * sequence that starts with it clash too: the single key would fire before the sequence went on.
110
+ */
111
+ export function keysOverlap(a: string, b: string): boolean {
112
+ const as = parseKeys(a)
113
+ const bs = parseKeys(b)
114
+ if (!as || !bs) return false
115
+ if (as.length !== bs.length) return chordsOverlap(as[0], bs[0])
116
+ return as.every((chord, i) => chordsOverlap(chord, bs[i]))
117
+ }
118
+
119
+ const MODIFIER_CODES = new Set(['ShiftLeft', 'ShiftRight', 'AltLeft', 'AltRight', 'ControlLeft', 'ControlRight', 'MetaLeft', 'MetaRight', 'CapsLock', 'Fn', 'FnLock'])
120
+
121
+ /** A key that is only a modifier (or Caps Lock, Fn): never a shortcut's key on its own. */
122
+ export const isModifierCode = (code: string): boolean => MODIFIER_CODES.has(code)