entangled-worlds-orbiters-shared 4.2.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.
package/README.md CHANGED
@@ -99,12 +99,13 @@ The capability registry (`createCapabilityRegistry`, `validate` / `assertValid`,
99
99
  - `largestFunction`, `shrinkWasm` - The size check and the shrink step
100
100
 
101
101
  ### Keyboard shortcuts (`entangled-worlds-orbiters-shared/shortcuts`)
102
- - `ShortcutAction` - One catalogue entry: `id`, `section`, `label`, `defaultKeys` (by key place, `event.code`), `scope`
102
+ - `ShortcutAction` - One catalogue entry: `id`, `label` (+ `names` by language), `defaultKeys` (by key place, `event.code`), `scope`
103
103
  - `matchShortcut(event, bindings)` - Which action a press is, or `null`: modifiers, a field being typed in and surface claims decided in one place
104
104
  - Key strings: `Shift+KeyR`, `Mod+KeyZ` (Ctrl or ⌘), `Shift?+KeyQ` (Shift may be held); `parseChord`, `chordsOverlap`
105
105
  - `resolveBindings(catalogue, overrides)`, `findClashes` - Defaults plus a person's overrides (`[{ id, keys }]` as their settings store them, `keys: []` unbinds), and the clash check
106
106
  - `claimKeys`, `isKeyClaimed` - A surface (an on-screen keyboard) takes letters away from the shortcuts while it is up
107
- - `ORBITERS_PLAY_SHORTCUTS`, `ORBITERS_STUDIO_SHORTCUTS` - The Orbiters catalogues
107
+ - `createShortcutSource({ readCatalogue, readAccount })` - The catalogue (every app's actions and default keys, served by the backend: this package holds none) and a person's own keys, read at start and again when the page comes back to the front; `actions(...sectionIds)`, `bindings(actions)`, `subscribe`
108
+ - `parseCatalogue`, `sectionActions`, `findSection`, `shortcutApps`, `localName` - Reading a served catalogue and its names in a language
108
109
 
109
110
  ### Uploads (`entangled-worlds-orbiters-shared/uploads`)
110
111
  - `uploadViaSignedUrl` - The API's signed-URL upload: `/spaces/upload-init` → PUT → `/spaces/upload-complete`, over the app's own authenticated JSON caller
@@ -0,0 +1,72 @@
1
+ import type { ShortcutAction, ShortcutNames } from './match.js';
2
+ /** Something with a name: English `label`, other languages in `names`. */
3
+ export interface ShortcutNamed {
4
+ readonly id: string;
5
+ readonly label: string;
6
+ readonly names?: ShortcutNames;
7
+ }
8
+ /** A row of a keys sheet (`?`): one line for one or more actions whose keys show together. */
9
+ export interface ShortcutSheetRow extends ShortcutNamed {
10
+ readonly actions: readonly string[];
11
+ }
12
+ export interface ShortcutSheetColumn extends ShortcutNamed {
13
+ readonly rows: readonly ShortcutSheetRow[];
14
+ }
15
+ /** One surface's keys (`orbiters-play`, `ew-studio`, `site`). Two actions clash only inside a section. */
16
+ export interface ShortcutSection {
17
+ readonly id: string;
18
+ /** The app it belongs to (`orbiters`) and that app's name. */
19
+ readonly app: string;
20
+ readonly appLabel: string;
21
+ readonly appNames?: ShortcutNames;
22
+ readonly label: string;
23
+ readonly names?: ShortcutNames;
24
+ /** Its name inside the app (`Play`, `Studio`); none when the app has only this section. */
25
+ readonly part?: string;
26
+ readonly partNames?: ShortcutNames;
27
+ /** How a command menu groups the actions, in its order. */
28
+ readonly groups: readonly ShortcutNamed[];
29
+ /** The keys sheet, where the app shows one in columns. */
30
+ readonly sheet?: readonly ShortcutSheetColumn[];
31
+ readonly actions: readonly ShortcutAction[];
32
+ /**
33
+ * Letters a surface of this section plays while it is open (`event.key`, lower-case; the Orbiters
34
+ * on-screen keyboard): a shortcut on one of them waits until it closes.
35
+ */
36
+ readonly heldKeys?: readonly string[];
37
+ }
38
+ export interface ShortcutCatalogue {
39
+ /** Changes whenever the catalogue is edited. */
40
+ readonly version: string;
41
+ readonly sections: readonly ShortcutSection[];
42
+ }
43
+ /** Before the catalogue is read: no sections, so no key does anything yet. */
44
+ export declare const EMPTY_CATALOGUE: ShortcutCatalogue;
45
+ /**
46
+ * The catalogue a response holds (`{ version, sections }`), or `null` when it holds none. A malformed
47
+ * section or action is left out rather than failing the whole read.
48
+ */
49
+ export declare function parseCatalogue(value: unknown): ShortcutCatalogue | null;
50
+ /** A name in a language (`es`, `es-AR`), the English when there is none in it. */
51
+ export declare function localName(item: {
52
+ readonly label: string;
53
+ readonly names?: ShortcutNames;
54
+ }, locale?: string): string;
55
+ /** A section's app name in a language. */
56
+ export declare function localAppName(section: Pick<ShortcutSection, 'appLabel' | 'appNames'>, locale?: string): string;
57
+ /** A section's part name (`Play`, `Studio`) in a language; `undefined` when it has none. */
58
+ export declare function localPartName(section: Pick<ShortcutSection, 'part' | 'partNames'>, locale?: string): string | undefined;
59
+ /** The apps the catalogue has, in its order. */
60
+ export declare function shortcutApps(catalogue: ShortcutCatalogue): ReadonlyArray<{
61
+ id: string;
62
+ label: string;
63
+ names?: ShortcutNames;
64
+ }>;
65
+ /**
66
+ * The actions of these sections, in the order named: where two sections hold one key, the first
67
+ * named wins (the Orbiter Studio lies over play). The same list object for as long as the catalogue
68
+ * is the same, so a cache keyed by it holds.
69
+ */
70
+ export declare function sectionActions(catalogue: ShortcutCatalogue, ...sectionIds: string[]): readonly ShortcutAction[];
71
+ /** One section, if the catalogue has it. */
72
+ export declare function findSection(catalogue: ShortcutCatalogue, sectionId: string): ShortcutSection | undefined;
@@ -0,0 +1,118 @@
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
+ /** Before the catalogue is read: no sections, so no key does anything yet. */
5
+ export const EMPTY_CATALOGUE = Object.freeze({ version: '', sections: Object.freeze([]) });
6
+ const isRecord = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
7
+ const isString = (value) => typeof value === 'string' && value.length > 0;
8
+ function names(value) {
9
+ if (!isRecord(value))
10
+ return undefined;
11
+ const out = {};
12
+ for (const [locale, name] of Object.entries(value))
13
+ if (isString(name))
14
+ out[locale] = name;
15
+ return Object.freeze(out);
16
+ }
17
+ function named(value) {
18
+ if (!isRecord(value) || !isString(value.id) || !isString(value.label))
19
+ return null;
20
+ return { id: value.id, label: value.label, names: names(value.names) };
21
+ }
22
+ function action(value) {
23
+ const base = named(value);
24
+ if (!base || !isRecord(value) || !isString(value.scope) || !Array.isArray(value.defaultKeys))
25
+ return null;
26
+ return Object.freeze({
27
+ ...base,
28
+ defaultKeys: Object.freeze(value.defaultKeys.filter(isString)),
29
+ scope: value.scope,
30
+ ...(isString(value.group) ? { group: value.group } : {}),
31
+ ...(value.command === false ? { command: false } : {}),
32
+ ...(isString(value.href) ? { href: value.href } : {}),
33
+ ...(value.signedIn === true ? { signedIn: true } : {}),
34
+ });
35
+ }
36
+ const list = (value, read) => Object.freeze(Array.isArray(value) ? value.map(read).filter((item) => item !== null) : []);
37
+ function section(value) {
38
+ const base = named(value);
39
+ if (!base || !isRecord(value) || !isString(value.app) || !isString(value.appLabel))
40
+ return null;
41
+ return Object.freeze({
42
+ ...base,
43
+ app: value.app,
44
+ appLabel: value.appLabel,
45
+ appNames: names(value.appNames),
46
+ ...(isString(value.part) ? { part: value.part, partNames: names(value.partNames) } : {}),
47
+ groups: list(value.groups, named),
48
+ ...(Array.isArray(value.sheet)
49
+ ? {
50
+ sheet: list(value.sheet, (column) => {
51
+ const head = named(column);
52
+ if (!head || !isRecord(column))
53
+ return null;
54
+ return Object.freeze({
55
+ ...head,
56
+ rows: list(column.rows, (row) => {
57
+ const line = named(row);
58
+ return line && isRecord(row) ? Object.freeze({ ...line, actions: list(row.actions, (id) => (isString(id) ? id : null)) }) : null;
59
+ }),
60
+ });
61
+ }),
62
+ }
63
+ : {}),
64
+ actions: list(value.actions, action),
65
+ ...(Array.isArray(value.heldKeys) ? { heldKeys: list(value.heldKeys, (key) => (isString(key) ? key : null)) } : {}),
66
+ });
67
+ }
68
+ /**
69
+ * The catalogue a response holds (`{ version, sections }`), or `null` when it holds none. A malformed
70
+ * section or action is left out rather than failing the whole read.
71
+ */
72
+ export function parseCatalogue(value) {
73
+ if (!isRecord(value) || !Array.isArray(value.sections))
74
+ return null;
75
+ return Object.freeze({ version: typeof value.version === 'string' ? value.version : '', sections: list(value.sections, section) });
76
+ }
77
+ /** A name in a language (`es`, `es-AR`), the English when there is none in it. */
78
+ export function localName(item, locale) {
79
+ return item.names?.[(locale ?? '').slice(0, 2).toLowerCase()] ?? item.label;
80
+ }
81
+ /** A section's app name in a language. */
82
+ export function localAppName(section, locale) {
83
+ return localName({ label: section.appLabel, names: section.appNames }, locale);
84
+ }
85
+ /** A section's part name (`Play`, `Studio`) in a language; `undefined` when it has none. */
86
+ export function localPartName(section, locale) {
87
+ return section.part === undefined ? undefined : localName({ label: section.part, names: section.partNames }, locale);
88
+ }
89
+ /** The apps the catalogue has, in its order. */
90
+ export function shortcutApps(catalogue) {
91
+ const seen = new Map();
92
+ for (const s of catalogue.sections)
93
+ if (!seen.has(s.app))
94
+ seen.set(s.app, { id: s.app, label: s.appLabel, names: s.appNames });
95
+ return [...seen.values()];
96
+ }
97
+ const actionLists = new WeakMap();
98
+ /**
99
+ * The actions of these sections, in the order named: where two sections hold one key, the first
100
+ * named wins (the Orbiter Studio lies over play). The same list object for as long as the catalogue
101
+ * is the same, so a cache keyed by it holds.
102
+ */
103
+ export function sectionActions(catalogue, ...sectionIds) {
104
+ let lists = actionLists.get(catalogue);
105
+ if (!lists)
106
+ actionLists.set(catalogue, (lists = new Map()));
107
+ const key = sectionIds.join('\n');
108
+ let found = lists.get(key);
109
+ if (!found) {
110
+ found = Object.freeze(sectionIds.flatMap((id) => catalogue.sections.find((s) => s.id === id)?.actions ?? []));
111
+ lists.set(key, found);
112
+ }
113
+ return found;
114
+ }
115
+ /** One section, if the catalogue has it. */
116
+ export function findSection(catalogue, sectionId) {
117
+ return catalogue.sections.find((s) => s.id === sectionId);
118
+ }
@@ -1,9 +1,5 @@
1
1
  export { parseChord, parseKeys, keysOverlap, chordMatches, chordsOverlap, isCommandChord, type Chord, type ModifierRule, type ModifierState, } from './chord.js';
2
- export { matchShortcut, createShortcutMatcher, SEQUENCE_WAIT_MS, resolveBindings, findClashes, claimKeys, isKeyClaimed, isTypingTarget, type ShortcutAction, type ShortcutBindings, type ShortcutOverrides, type ShortcutEvent, } from './match.js';
3
- export { ORBITERS_PLAY_SHORTCUTS, ORBITERS_STUDIO_SHORTCUTS, ORBITERS_PLAY_SECTION, ORBITERS_STUDIO_SECTION, ORBITERS_KEYBOARD_SURFACE_KEYS, ORBITERS_COMMAND_GROUPS, ORBITERS_PLAY_SHEET, type OrbitersShortcut, type OrbitersShortcutScope, } from './orbiters.js';
2
+ export { matchShortcut, createShortcutMatcher, SEQUENCE_WAIT_MS, resolveBindings, findClashes, claimKeys, isKeyClaimed, isTypingTarget, type ShortcutAction, type ShortcutNames, type ShortcutBindings, type ShortcutOverrides, type ShortcutEvent, } from './match.js';
4
3
  export { shortcutPlatform, keyLabel, chordParts, formatChord, chordFromEvent, mergedKeyParts, recordedKeys, type ShortcutPlatform, type KeyLayout, } from './format.js';
5
- export { SHORTCUT_SECTIONS, SHORTCUT_APPS, type ShortcutSection, type ShortcutAppId } from './sections.js';
6
- export { SITE_SHORTCUTS, SITE_SECTION, type SiteShortcut } from './site.js';
7
- export { EW_STUDIO_SHORTCUTS, EW_PLAYER_SHORTCUTS, EW_STUDIO_SECTION, EW_PLAYER_SECTION, EW_STUDIO_COMMAND_GROUPS, type EntangledWorldsShortcut, } from './entangledWorlds.js';
8
- export { shortcutLabel, shortcutSectionLabel, shortcutName } from './labels.js';
9
- export { createShortcutOverridesSource, parseOverrides, type ShortcutOverridesSource, type ReadAccountSettings, } from './overrides.js';
4
+ export { EMPTY_CATALOGUE, parseCatalogue, localName, localAppName, localPartName, shortcutApps, sectionActions, findSection, type ShortcutCatalogue, type ShortcutSection, type ShortcutNamed, type ShortcutSheetColumn, type ShortcutSheetRow, } from './catalogue.js';
5
+ export { createShortcutSource, localShortcutCatalogueStore, CATALOGUE_STORAGE_KEY, parseOverrides, type ShortcutCatalogueStore, type ShortcutSource, type ReadAccountSettings, type ReadShortcutCatalogue, } from './source.js';
@@ -1,13 +1,9 @@
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.
1
+ // Keyboard shortcuts, one system for every app: the reader of the shortcut catalogue (every app's
2
+ // actions and default keys, served by the backend) and of a person's own keys, and one matcher that
3
+ // says which action a key press is. Keys are named by their place on the keyboard
4
+ // (`KeyboardEvent.code`). Framework-free: no React, no DOM beyond reading a key event.
5
5
  export { parseChord, parseKeys, keysOverlap, chordMatches, chordsOverlap, isCommandChord, } from './chord.js';
6
6
  export { matchShortcut, createShortcutMatcher, SEQUENCE_WAIT_MS, resolveBindings, findClashes, claimKeys, isKeyClaimed, isTypingTarget, } from './match.js';
7
- export { ORBITERS_PLAY_SHORTCUTS, ORBITERS_STUDIO_SHORTCUTS, ORBITERS_PLAY_SECTION, ORBITERS_STUDIO_SECTION, ORBITERS_KEYBOARD_SURFACE_KEYS, ORBITERS_COMMAND_GROUPS, ORBITERS_PLAY_SHEET, } from './orbiters.js';
8
7
  export { shortcutPlatform, keyLabel, chordParts, formatChord, chordFromEvent, mergedKeyParts, recordedKeys, } from './format.js';
9
- export { SHORTCUT_SECTIONS, SHORTCUT_APPS } from './sections.js';
10
- export { SITE_SHORTCUTS, SITE_SECTION } from './site.js';
11
- export { EW_STUDIO_SHORTCUTS, EW_PLAYER_SHORTCUTS, EW_STUDIO_SECTION, EW_PLAYER_SECTION, EW_STUDIO_COMMAND_GROUPS, } from './entangledWorlds.js';
12
- export { shortcutLabel, shortcutSectionLabel, shortcutName } from './labels.js';
13
- export { createShortcutOverridesSource, parseOverrides, } from './overrides.js';
8
+ export { EMPTY_CATALOGUE, parseCatalogue, localName, localAppName, localPartName, shortcutApps, sectionActions, findSection, } from './catalogue.js';
9
+ export { createShortcutSource, localShortcutCatalogueStore, CATALOGUE_STORAGE_KEY, parseOverrides, } from './source.js';
@@ -1,12 +1,12 @@
1
1
  import { type ModifierState } from './chord.js';
2
- /** One thing a key can do, as an app's catalogue declares it. */
2
+ /** One thing a key can do, as the shortcut catalogue (served by the backend) lists it. */
3
3
  export interface ShortcutAction<Scope extends string = string> {
4
4
  /** `<app>.<area>.<action>`, e.g. `orbiters.play.panel.jamming`: the key a person's override is stored under. */
5
5
  readonly id: string;
6
- /** The group it is shown in, one per app surface (`orbiters-play`). Keys clash only inside a section. */
7
- readonly section: string;
8
- /** What it does, in sentence case. */
6
+ /** What it does, in sentence case, in English. */
9
7
  readonly label: string;
8
+ /** Its name in other languages, by locale (`{ es: '…' }`); see `localName`. */
9
+ readonly names?: ShortcutNames;
10
10
  /** The keys it has until the person changes them (chord strings, see `chord.ts`). */
11
11
  readonly defaultKeys: readonly string[];
12
12
  /** What it acts on, in the app's own terms (Orbiters: one deck, or this machine). */
@@ -15,12 +15,18 @@ export interface ShortcutAction<Scope extends string = string> {
15
15
  readonly group?: string;
16
16
  /** `false`: a key only, never a command to pick from a list (a key held down, the menu itself). */
17
17
  readonly command?: boolean;
18
+ /** A site action: the page it opens (`{username}` stands for the signed-in person's). */
19
+ readonly href?: string;
20
+ /** It needs someone signed in. */
21
+ readonly signedIn?: boolean;
18
22
  }
23
+ /** A name in other languages than English, by locale (`es`). */
24
+ export type ShortcutNames = Readonly<Record<string, string>>;
19
25
  /** The keys of each action, in the order they are tried: the first action a press matches is the one. */
20
26
  export type ShortcutBindings = Iterable<readonly [actionId: string, keys: readonly string[]]>;
21
27
  /**
22
28
  * A person's changes, as their settings store them: an action's own keys (`[]` = no key). An action
23
- * left out keeps its defaults, so a default changed in code reaches everyone who never touched it.
29
+ * left out keeps its defaults, so a default changed in the catalogue reaches everyone who never touched it.
24
30
  */
25
31
  export type ShortcutOverrides = ReadonlyArray<{
26
32
  readonly id: string;
@@ -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.2.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",