@bridgebrew/shell 0.0.0-stage → 0.0.1

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,528 @@
1
+ // The shell's shortcut registry (research-018 C5): a window manager registers its keys through the `shell` service
2
+ // (`shell.shortcuts.register`); the shell refuses a key Bridge reserves (Escape, Space, Tab but ⌥Tab, ⌘K, the browser's ⌘L / ⌘R
3
+ // / ⌘T, ⌘C / ⌘V / ⌘X / ⌘A / ⌘Z, and `?`, its own help) or one already registered, and logs the refusal; it dispatches
4
+ // each `keydown` to the shortcut it matches, but none while the focus is in an editable field (its keys are the field's:
5
+ // ⌥← moves by word, ⌥ letters type), except ⌥W and ⌥M (⌘W and ⌘M in the app). A held key repeats only a shortcut that asks
6
+ // (`repeat`). One help lists them all (`list`).
7
+ //
8
+ // A key is written as modifiers then a key, joined by `+`: `Alt+Shift+ArrowLeft`, `Alt+Backslash`, `Alt+KeyM`. The key
9
+ // is a `KeyboardEvent.code` (the physical key: ⌥M types `µ` on a Mac; a letter key, `KeyW`, is the key the keyboard
10
+ // layout prints that letter on, where the browser tells it: `setLayout`), or a single character matched on
11
+ // `KeyboardEvent.key` (`?`), Shift then ignored. `Alt` is the window modifier: ⌥ in the browser; in the Electron app ⌘
12
+ // works too (research-018 K3, S3) on the keys free there only: W, M, \ and ⇧\, 1-9 and ⇧1-9 (never arrows, Enter or F:
13
+ // a field's).
14
+ //
15
+ // A pointer gesture (`gesture`: modifiers held, then a click, a drag or a right drag) is declared, not dispatched: its
16
+ // owner listens to the pointer itself. The registry lists it in the help and refuses one whose modifiers and action are
17
+ // declared already, the warning naming both owners (Point once took ⌥ + press and hid the window manager's ⌥ drag), or
18
+ // Bridge's own (⌘-click, Ctrl-click: a new window). Modifiers are written as for a key, without the key: `Alt+Shift`.
19
+ //
20
+ // A screen's keys (`declare`: Sessions' Escape twice, ⇧⌘S…) are declared the same way: its owner listens itself, and
21
+ // acts only while its window is focused (the `screen` slot's `focused`). The registry lists them in the help and refuses
22
+ // one a window manager registered, or another owner declared, already (a later `register` of it is refused too); Bridge's
23
+ // own keys may be declared (a screen gives Escape or ⌘Z its own meaning outside a field), never registered.
24
+
25
+ export type Shortcut = {
26
+ keys: string | readonly string[];
27
+ /** Short: the ⌘K palette names the command with it. */
28
+ label: string;
29
+ /** What more there is to say (another way to do it, a limit): beside the label, quieter, in the help and ⌘K. */
30
+ description?: string | undefined;
31
+ run: (keys: string) => void;
32
+ repeat?: boolean;
33
+ };
34
+ type Parsed = { alt: boolean; shift: boolean; meta: boolean; ctrl: boolean; key: string };
35
+ type Pressed = Pick<KeyboardEvent, 'altKey' | 'shiftKey' | 'metaKey' | 'ctrlKey' | 'code' | 'key'>;
36
+
37
+ const modifiers = ['Alt', 'Shift', 'Meta', 'Ctrl'] as const;
38
+ /** A key as written, or none when it does not read (an unknown modifier, no key, a modifier twice). */
39
+ export function parseKeys(keys: string): Parsed | undefined {
40
+ const parts = keys.split('+');
41
+ // `+` itself: the last part empty.
42
+ if (keys.endsWith('++')) parts.splice(-2, 2, '+');
43
+ const key = parts.pop();
44
+ if (!key) return undefined;
45
+ const seen = new Set<string>();
46
+ for (const part of parts) {
47
+ if (!(modifiers as readonly string[]).includes(part) || seen.has(part)) return undefined;
48
+ seen.add(part);
49
+ }
50
+ return {
51
+ alt: seen.has('Alt'),
52
+ shift: seen.has('Shift'),
53
+ meta: seen.has('Meta'),
54
+ ctrl: seen.has('Ctrl'),
55
+ key,
56
+ };
57
+ }
58
+ const same = (a: Parsed, b: Parsed) =>
59
+ a.alt === b.alt &&
60
+ a.meta === b.meta &&
61
+ a.ctrl === b.ctrl &&
62
+ a.key === b.key &&
63
+ (a.key.length === 1 || a.shift === b.shift);
64
+
65
+ /** Bridge's own keys (C5): no window manager may take them. */
66
+ const reservedKeys = [
67
+ 'Escape',
68
+ 'Shift+Escape',
69
+ 'Space',
70
+ 'Shift+Space',
71
+ 'Tab',
72
+ 'Shift+Tab',
73
+ '?',
74
+ ...['K', 'L', 'R', 'T', 'C', 'V', 'X', 'A', 'Z'].flatMap((letter) => [
75
+ `Meta+Key${letter}`,
76
+ `Ctrl+Key${letter}`,
77
+ ]),
78
+ 'Meta+Shift+KeyZ',
79
+ 'Ctrl+Shift+KeyZ',
80
+ 'Ctrl+KeyY',
81
+ ].map((each) => parseKeys(each)!);
82
+ /** ⌥Tab, the one Tab a manager may take (research-018 K3: back to the previous desk). */
83
+ const altTab = (parsed: Parsed) =>
84
+ parsed.key === 'Tab' && parsed.alt && !parsed.shift && !parsed.meta && !parsed.ctrl;
85
+ /** Whether Bridge reserves `parsed`: Escape, Space and Tab with any modifier (but ⌥Tab), the others as written. */
86
+ const reserved = (parsed: Parsed) =>
87
+ (['Escape', 'Space', 'Tab'].includes(parsed.key) && !altTab(parsed)) ||
88
+ reservedKeys.some((each) => same(each, parsed));
89
+ /** The keys whose ⌘ form the app frees (its menu leaves ⌘W and ⌘M to the page; ⌘\ and ⌘1-9, the desks, are free). */
90
+ const digitKeys = [
91
+ 'Digit1',
92
+ 'Digit2',
93
+ 'Digit3',
94
+ 'Digit4',
95
+ 'Digit5',
96
+ 'Digit6',
97
+ 'Digit7',
98
+ 'Digit8',
99
+ 'Digit9',
100
+ ];
101
+ const appKeys = ['KeyW', 'KeyM', 'Backslash', ...digitKeys];
102
+ /** The keys that run in an editable field too: W and M with the window modifier alone (⌥W, ⌥M; ⌘W, ⌘M in the app). */
103
+ const windowKey = (parsed: Parsed) =>
104
+ (parsed.key === 'KeyW' || parsed.key === 'KeyM') &&
105
+ parsed.alt &&
106
+ !parsed.shift &&
107
+ !parsed.meta &&
108
+ !parsed.ctrl;
109
+ /** The ⌘ form of an `Alt` key, for the Electron app: only on the keys it frees (⇧ only with \ and the digits), never
110
+ * with Ctrl. */
111
+ const metaForm = (parsed: Parsed): Parsed | undefined =>
112
+ parsed.alt &&
113
+ !parsed.meta &&
114
+ !parsed.ctrl &&
115
+ appKeys.includes(parsed.key) &&
116
+ (parsed.key === 'Backslash' || digitKeys.includes(parsed.key) || !parsed.shift)
117
+ ? { ...parsed, alt: false, meta: true }
118
+ : undefined;
119
+
120
+ /** The keyboard layout's letter for a physical key (`KeyboardEvent.code` → `w`), where the browser tells it
121
+ * (`navigator.keyboard.getLayoutMap()`: Chrome, the Electron app; not Safari nor Firefox). */
122
+ export type KeyLayout = ReadonlyMap<string, string>;
123
+ /** Whether `code` is letter key `want` (`KeyW`): the letter the layout prints on it (⌥W is ⌥ + the key marked W, at
124
+ * `KeyZ` on an AZERTY keyboard, M at `Semicolon`), else, no layout known, the physical key (QWERTY's). Digits,
125
+ * arrows and the others stay physical (⌥1 … ⌥9 the top row, whatever it types). */
126
+ const sameKey = (want: string, code: string, layout?: KeyLayout) => {
127
+ if (!/^Key[A-Z]$/.test(want)) return code === want;
128
+ const wanted = want.slice(3).toLowerCase();
129
+ const letter = layout?.get(code)?.toLowerCase();
130
+ if (letter === wanted) return true;
131
+ // Not that letter: the physical key, unless the layout prints the letter elsewhere (AZERTY's M, at Semicolon, is
132
+ // not at KeyM). A layout without Latin letters (Cyrillic, Greek, Hebrew) has it nowhere: QWERTY's places, as usual.
133
+ return (
134
+ code === want && !(layout && [...layout.values()].some((each) => each.toLowerCase() === wanted))
135
+ );
136
+ };
137
+ /** The letters AZERTY moves (French, Belgian): a letter typed where AZERTY has it tells them all. */
138
+ const azerty: readonly [string, string][] = [
139
+ ['KeyQ', 'a'],
140
+ ['KeyA', 'q'],
141
+ ['KeyW', 'z'],
142
+ ['KeyZ', 'w'],
143
+ ['Semicolon', 'm'],
144
+ ['KeyM', ','],
145
+ ];
146
+ /** A first guess at the layout from the browser's languages, until a map or a letter typed tells: AZERTY for France,
147
+ * Belgium and Monaco (`fr-FR`, `fr-BE`, `nl-BE`, `fr-MC`, a bare `fr`); none else (Swiss, Canadian French are not). */
148
+ export function guessLayout(languages: readonly string[]): KeyLayout {
149
+ const first = languages[0]?.toLowerCase();
150
+ return first !== undefined && ['fr', 'fr-fr', 'fr-be', 'nl-be', 'fr-mc'].includes(first)
151
+ ? new Map(azerty)
152
+ : new Map();
153
+ }
154
+ /** `layout` with what `event` tells of it: a letter typed without ⌥, ⌘ or Ctrl (where the browser keeps its layout
155
+ * map to itself, a page over plain HTTP), and, a letter where AZERTY has it, AZERTY's moved letters. `layout`
156
+ * itself when it tells nothing new. */
157
+ export function learnLayout(
158
+ layout: KeyLayout,
159
+ event: Pick<KeyboardEvent, 'altKey' | 'metaKey' | 'ctrlKey' | 'code' | 'key'>,
160
+ ): KeyLayout {
161
+ if (
162
+ event.altKey ||
163
+ event.metaKey ||
164
+ event.ctrlKey ||
165
+ !/^[a-z]$/i.test(event.key) ||
166
+ !/^(Key[A-Z]|Semicolon)$/.test(event.code)
167
+ )
168
+ return layout;
169
+ const letter = event.key.toLowerCase();
170
+ const told: [string, string][] = azerty.some(
171
+ ([code, each]) => code === event.code && each === letter,
172
+ )
173
+ ? [...azerty]
174
+ : [[event.code, letter]];
175
+ if (told.every(([code, each]) => layout.get(code) === each)) return layout;
176
+ return new Map([...layout, ...told]);
177
+ }
178
+
179
+ /** How `event` presses `parsed`: as written (`exact`), through its ⌘ form in the app (`meta`), or not (`false`). */
180
+ function matches(
181
+ parsed: Parsed,
182
+ event: Pressed,
183
+ app = false,
184
+ layout?: KeyLayout,
185
+ ): 'exact' | 'meta' | false {
186
+ const exact = (want: Parsed) =>
187
+ event.altKey === want.alt &&
188
+ event.metaKey === want.meta &&
189
+ event.ctrlKey === want.ctrl &&
190
+ (want.key.length === 1
191
+ ? event.key === want.key
192
+ : event.shiftKey === want.shift && sameKey(want.key, event.code, layout));
193
+ if (exact(parsed)) return 'exact';
194
+ const meta = app ? metaForm(parsed) : undefined;
195
+ return meta !== undefined && !reserved(meta) && exact(meta) ? 'meta' : false;
196
+ }
197
+
198
+ const names: Record<string, string> = {
199
+ ArrowLeft: '←',
200
+ ArrowUp: '↑',
201
+ ArrowRight: '→',
202
+ ArrowDown: '↓',
203
+ Backslash: '\\',
204
+ Enter: '↩',
205
+ Slash: '/',
206
+ BracketLeft: '[',
207
+ BracketRight: ']',
208
+ Minus: '-',
209
+ Equal: '=',
210
+ Comma: ',',
211
+ Period: '.',
212
+ Semicolon: ';',
213
+ Quote: "'",
214
+ Backquote: '`',
215
+ Backspace: '⌫',
216
+ };
217
+ /** A key as the help shows it: on macOS `⌥ ⇧ ←`, elsewhere `Alt+Shift+←`. */
218
+ export function displayKeys(keys: string, mac = true): string {
219
+ const parsed = parseKeys(keys);
220
+ if (!parsed) return keys;
221
+ const key = names[parsed.key] ?? parsed.key.replace(/^Key|^Digit/, '');
222
+ const shift = parsed.shift && parsed.key.length > 1;
223
+ return mac
224
+ ? [parsed.ctrl && 'Ctrl', parsed.alt && '⌥', shift && '⇧', parsed.meta && '⌘', key]
225
+ .filter(Boolean)
226
+ .join(' ')
227
+ : [parsed.ctrl && 'Ctrl', parsed.alt && 'Alt', shift && 'Shift', parsed.meta && 'Meta', key]
228
+ .filter(Boolean)
229
+ .join('+');
230
+ }
231
+
232
+ /** Whether `target` takes text: an input, a textarea, a select, editable content, or a textbox. */
233
+ export const isEditable = (target: EventTarget | null) =>
234
+ target instanceof Element &&
235
+ (target.closest(
236
+ 'input, textarea, select, [contenteditable]:not([contenteditable="false"]), [role="textbox"]',
237
+ ) !== null ||
238
+ (target as HTMLElement).isContentEditable === true);
239
+
240
+ export type Listed = { keys: readonly string[]; label: string; description?: string | undefined };
241
+ /** A key a screen handles itself (`declare`), with its owner. */
242
+ export type Declared = Listed & { by?: string };
243
+
244
+ /** A pointer gesture's action: a primary click, a primary drag, a secondary (right) drag. */
245
+ export type GestureAction = 'click' | 'drag' | 'right-drag';
246
+ export type Gesture = { modifiers: string; action: GestureAction; label: string };
247
+ export type ListedGesture = Gesture & { by?: string };
248
+ type Held = Omit<Parsed, 'key'>;
249
+ const gestureActions: readonly GestureAction[] = ['click', 'drag', 'right-drag'];
250
+ /** Modifiers as written (`Alt+Shift`; `''`: none), or none when they do not read. */
251
+ function parseModifiers(text: string): Held | undefined {
252
+ const parsed = parseKeys(text === '' ? '_' : `${text}+_`);
253
+ if (!parsed) return undefined;
254
+ return { alt: parsed.alt, shift: parsed.shift, meta: parsed.meta, ctrl: parsed.ctrl };
255
+ }
256
+ const sameHeld = (a: Held, b: Held) =>
257
+ a.alt === b.alt && a.shift === b.shift && a.meta === b.meta && a.ctrl === b.ctrl;
258
+ /** Bridge's own gestures: ⌘-click and Ctrl-click open a view or a link in a new window. */
259
+ const reservedGestures: { held: Held; action: GestureAction }[] = [
260
+ { held: { alt: false, shift: false, meta: true, ctrl: false }, action: 'click' },
261
+ { held: { alt: false, shift: false, meta: false, ctrl: true }, action: 'click' },
262
+ ];
263
+ /** A gesture as the help shows it: on macOS `⌥ ⇧ drag`, elsewhere `Alt+Shift drag`. */
264
+ export function displayGesture(modifiers: string, action: GestureAction, mac = true): string {
265
+ const held = parseModifiers(modifiers);
266
+ const verb = action === 'right-drag' ? 'right drag' : action;
267
+ if (!held) return `${modifiers} ${verb}`;
268
+ const names = mac
269
+ ? [held.ctrl && 'Ctrl', held.alt && '⌥', held.shift && '⇧', held.meta && '⌘']
270
+ .filter(Boolean)
271
+ .join(' ')
272
+ : [held.ctrl && 'Ctrl', held.alt && 'Alt', held.shift && 'Shift', held.meta && 'Meta']
273
+ .filter(Boolean)
274
+ .join('+');
275
+ return names ? `${names} ${verb}` : verb;
276
+ }
277
+
278
+ /** The registry. `log`: where a refusal goes (the console). `app`: in the Electron app (⌘ works for ⌥). */
279
+ export function createShortcuts({
280
+ log = (message: string) => console.warn(message),
281
+ app = false,
282
+ }: { log?: (message: string) => void; app?: boolean } = {}) {
283
+ type Entry = {
284
+ keys: { text: string; parsed: Parsed }[];
285
+ label: string;
286
+ description: string | undefined;
287
+ run: (keys: string) => void;
288
+ repeat: boolean;
289
+ };
290
+ const entries: Entry[] = [];
291
+ const listeners = new Set<() => void>();
292
+ /** The keyboard layout's letters (`setLayout`), once the browser told them. */
293
+ let layout: KeyLayout | undefined;
294
+ let snapshot: readonly (Listed & { run(): void })[] = [];
295
+ const changed = () => {
296
+ snapshot = entries.map(({ keys, label, description, run }) => ({
297
+ keys: keys.map((each) => each.text),
298
+ label,
299
+ description,
300
+ run: () => run(keys[0]!.text),
301
+ }));
302
+ for (const listener of listeners) listener();
303
+ };
304
+ type DeclaredEntry = {
305
+ keys: { text: string; parsed: Parsed }[];
306
+ label: string;
307
+ by?: string;
308
+ copies: number;
309
+ };
310
+ const declarations: DeclaredEntry[] = [];
311
+ let declaredSnapshot: readonly Declared[] = [];
312
+ const declaredChanged = () => {
313
+ declaredSnapshot = declarations.map(({ keys, label, by }) => ({
314
+ keys: keys.map((each) => each.text),
315
+ label,
316
+ ...(by !== undefined && { by }),
317
+ }));
318
+ for (const listener of listeners) listener();
319
+ };
320
+ /** Who holds `parsed` already: a registered shortcut (`''`, a window manager's) or a declaration's owner. */
321
+ const holder = (parsed: Parsed): string | undefined => {
322
+ if (entries.some((entry) => entry.keys.some((each) => same(each.parsed, parsed)))) return '';
323
+ const declared = declarations.find((entry) =>
324
+ entry.keys.some((each) => same(each.parsed, parsed)),
325
+ );
326
+ return declared && (declared.by ?? 'another plugin');
327
+ };
328
+ type GestureEntry = ListedGesture & { held: Held };
329
+ const gestures: GestureEntry[] = [];
330
+ let gestureSnapshot: readonly ListedGesture[] = [];
331
+ const gesturesChanged = () => {
332
+ gestureSnapshot = gestures.map(({ modifiers, action, label, by }) => ({
333
+ modifiers,
334
+ action,
335
+ label,
336
+ ...(by !== undefined && { by }),
337
+ }));
338
+ for (const listener of listeners) listener();
339
+ };
340
+ return {
341
+ /** Registers `shortcut`; returns its removal. Refused, and logged, when one of its keys does not read, is
342
+ * Bridge's, or is registered already: nothing registered, the removal does nothing. */
343
+ register(shortcut: Shortcut, by?: string): () => void {
344
+ const list = typeof shortcut.keys === 'string' ? [shortcut.keys] : [...shortcut.keys];
345
+ const keys: Entry['keys'] = [];
346
+ for (const text of list) {
347
+ const parsed = parseKeys(text);
348
+ const held = parsed && holder(parsed);
349
+ const why = !parsed
350
+ ? 'it does not read as a key'
351
+ : reserved(parsed)
352
+ ? 'Bridge reserves it'
353
+ : held
354
+ ? `${held} declared it already`
355
+ : held === '' || keys.some((each) => same(each.parsed, parsed))
356
+ ? 'it is registered already'
357
+ : undefined;
358
+ if (why) {
359
+ log(
360
+ `shell: shortcut ${text} (${shortcut.label})${by === undefined ? '' : ` from ${by}`} refused: ${why}`,
361
+ );
362
+ return () => {};
363
+ }
364
+ keys.push({ text, parsed: parsed! });
365
+ }
366
+ if (!keys.length) return () => {};
367
+ const entry: Entry = {
368
+ keys,
369
+ label: shortcut.label,
370
+ description: shortcut.description,
371
+ run: shortcut.run,
372
+ repeat: shortcut.repeat === true,
373
+ };
374
+ entries.push(entry);
375
+ changed();
376
+ return () => {
377
+ const at = entries.indexOf(entry);
378
+ if (at < 0) return;
379
+ entries.splice(at, 1);
380
+ changed();
381
+ };
382
+ },
383
+ /** Every shortcut registered, in order: its keys, its label, and its run (as its first key would; the ⌘K
384
+ * palette's, research-034). */
385
+ list: (): readonly (Listed & { run(): void })[] => snapshot,
386
+ /** Declares pointer gesture `gesture` of `by` (which listens to the pointer itself); returns its removal. Refused,
387
+ * and logged, when its modifiers or action do not read, when it is Bridge's (⌘-click, Ctrl-click), or when the same
388
+ * modifiers and action are declared already (the warning names both owners): nothing declared, the removal does
389
+ * nothing. */
390
+ gesture(gesture: Gesture, by?: string): () => void {
391
+ const held = parseModifiers(gesture.modifiers);
392
+ const clash =
393
+ held &&
394
+ gestures.find((each) => each.action === gesture.action && sameHeld(each.held, held));
395
+ const why =
396
+ !held || !gestureActions.includes(gesture.action)
397
+ ? 'it does not read as a gesture'
398
+ : reservedGestures.some(
399
+ (each) => each.action === gesture.action && sameHeld(each.held, held),
400
+ )
401
+ ? 'Bridge reserves it'
402
+ : clash
403
+ ? `${clash.by ?? 'another plugin'} declared it already (${clash.label})`
404
+ : undefined;
405
+ if (why) {
406
+ log(
407
+ `shell: gesture ${gesture.modifiers || 'no modifier'} ${gesture.action} (${gesture.label})${by === undefined ? '' : ` from ${by}`} refused: ${why}`,
408
+ );
409
+ return () => {};
410
+ }
411
+ const entry: GestureEntry = {
412
+ modifiers: gesture.modifiers,
413
+ action: gesture.action,
414
+ label: gesture.label,
415
+ held: held!,
416
+ ...(by !== undefined && { by }),
417
+ };
418
+ gestures.push(entry);
419
+ gesturesChanged();
420
+ return () => {
421
+ const at = gestures.indexOf(entry);
422
+ if (at < 0) return;
423
+ gestures.splice(at, 1);
424
+ gesturesChanged();
425
+ };
426
+ },
427
+ /** Declares the keys of `shortcut` that `by` handles itself (a screen's, while its window is focused), for the help
428
+ * and for clashes; returns its removal. The same declaration from the same owner again is shared (listed once). Refused, and logged naming the holder, when one of its keys does not read or
429
+ * is registered or declared already: nothing declared, the removal does nothing. Bridge's own keys may be declared. */
430
+ declare(
431
+ shortcut: { keys: string | readonly string[]; label: string },
432
+ by?: string,
433
+ ): () => void {
434
+ const list = typeof shortcut.keys === 'string' ? [shortcut.keys] : [...shortcut.keys];
435
+ // The same declaration from the same owner again (a second copy of its screen, another workspace's context of
436
+ // the same plugin): shared, listed once, gone with its last removal.
437
+ const again = declarations.find(
438
+ (entry) =>
439
+ entry.by === by &&
440
+ entry.label === shortcut.label &&
441
+ entry.keys.length === list.length &&
442
+ entry.keys.every((each, at) => each.text === list[at]),
443
+ );
444
+ if (again) {
445
+ again.copies++;
446
+ let removed = false;
447
+ return () => {
448
+ if (removed) return;
449
+ removed = true;
450
+ if (--again.copies > 0) return;
451
+ declarations.splice(declarations.indexOf(again), 1);
452
+ declaredChanged();
453
+ };
454
+ }
455
+ const keys: DeclaredEntry['keys'] = [];
456
+ for (const text of list) {
457
+ const parsed = parseKeys(text);
458
+ const held = parsed && holder(parsed);
459
+ const why = !parsed
460
+ ? 'it does not read as a key'
461
+ : held !== undefined
462
+ ? held === ''
463
+ ? 'a window manager registered it already'
464
+ : `${held} declared it already`
465
+ : keys.some((each) => same(each.parsed, parsed))
466
+ ? 'it is listed twice'
467
+ : undefined;
468
+ if (why) {
469
+ log(
470
+ `shell: shortcut ${text} (${shortcut.label})${by === undefined ? '' : ` from ${by}`} refused: ${why}`,
471
+ );
472
+ return () => {};
473
+ }
474
+ keys.push({ text, parsed: parsed! });
475
+ }
476
+ if (!keys.length) return () => {};
477
+ const entry: DeclaredEntry = {
478
+ keys,
479
+ label: shortcut.label,
480
+ ...(by !== undefined && { by }),
481
+ copies: 1,
482
+ };
483
+ declarations.push(entry);
484
+ declaredChanged();
485
+ let removed = false;
486
+ return () => {
487
+ if (removed) return;
488
+ removed = true;
489
+ if (--entry.copies > 0) return;
490
+ declarations.splice(declarations.indexOf(entry), 1);
491
+ declaredChanged();
492
+ };
493
+ },
494
+ /** Every key declared, in order: its keys, its label, its owner. */
495
+ declared: (): readonly Declared[] => declaredSnapshot,
496
+ /** The keyboard layout's letters, for letter keys pressed as the layout prints them (an AZERTY ⌥W). */
497
+ setLayout(next: KeyLayout | undefined) {
498
+ layout = next;
499
+ },
500
+ /** Every pointer gesture declared, in order: its modifiers, its action, its label, its owner. */
501
+ gestures: (): readonly ListedGesture[] => gestureSnapshot,
502
+ subscribe(listener: () => void) {
503
+ listeners.add(listener);
504
+ return () => {
505
+ listeners.delete(listener);
506
+ };
507
+ },
508
+ /** Runs the shortcut `event` presses, and says so (the caller prevents the default). In an editable field none
509
+ * runs (its keys are the field's) but ⌥W and ⌥M (and ⌘W, ⌘M in the app): a screen made of fields (a contact's
510
+ * card) must still close or minimize its window; they type a rare `∑` and `µ` on a Mac. A held key (`repeat`)
511
+ * runs only a shortcut registered with `repeat`. */
512
+ dispatch(event: Pressed & Pick<KeyboardEvent, 'target'> & { repeat?: boolean }): boolean {
513
+ const field = isEditable(event.target);
514
+ for (const entry of entries) {
515
+ for (const key of entry.keys) {
516
+ const how = matches(key.parsed, event, app, layout);
517
+ if (!how) continue;
518
+ if (field && !windowKey(key.parsed)) return false;
519
+ if (event.repeat && !entry.repeat) return false;
520
+ entry.run(key.text);
521
+ return true;
522
+ }
523
+ }
524
+ return false;
525
+ },
526
+ };
527
+ }
528
+ export type Shortcuts = ReturnType<typeof createShortcuts>;