@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,1800 @@
1
+ // The `shell` service's state (E8, E10): the workspaces, the current one, the host status, and the current
2
+ // workspace's screens, fetched on load and on window focus, and its node tree (AD-23), fetched when the
3
+ // workspace changes and on its `nodes` status events; the current node, the chosen screen and its path, kept in
4
+ // the URL: `/<slug>/<node>/<screen path>/<item path>`, `/<slug>/<node>/` for the node's home view (AD-11).
5
+ // Each workspace's look is its proposal with the user's Mine for it laid over (research-028, appearance slice 3), again
6
+ // on each change of the client's appearance; the window manager chosen is the look's. A browser's choices from before
7
+ // Mine (theme, style, icons, window manager in localStorage) are carried over once into Mine of every workspace listed
8
+ // (./look.ts `legacyMine`), then forgotten.
9
+ import type { Context } from 'cordis';
10
+ import type {} from '@bridge/ui-renderer/client';
11
+ import { everywhereFields, withEverywhere, withMine } from '@bridge/kernel/look';
12
+ import { isRecord, readJson } from '@bridge/kernel/json';
13
+ import {
14
+ chosenBlocks,
15
+ nodeLayout,
16
+ openingBlock,
17
+ screenBlocks,
18
+ showsBlock,
19
+ } from '@bridge/kernel/node-layout';
20
+ import { nodeTrees } from '@bridge/kernel/node-trees';
21
+ import { gestureOf, type FollowEvent } from '@bridge/ui';
22
+ import { legacyKeys, legacyMine } from './look.ts';
23
+ import { withHint } from './notifications.ts';
24
+ import { createShortcuts, type Shortcuts } from './shortcuts.ts';
25
+ import { pageSlot } from './page-slot.ts';
26
+ import { createViewScopes } from './view-scopes.ts';
27
+ import { keepFocus } from './keep-focus.ts';
28
+
29
+ export type Shell = Context['shell'];
30
+ type ShellState = ReturnType<Shell['get']>;
31
+ export type View = Parameters<Shell['show']>[0];
32
+ type WindowManager = Context['windowManager'];
33
+ /** The active window manager, when one is provided: the service and the plugin it comes from (its `stage` entry's). */
34
+ export type ManagerRef = { service: Partial<WindowManager>; plugin: string };
35
+
36
+ /** The shell's approval-modal review requests (research-031): `emit` asks the modal to open on request `id` (or, with
37
+ * none, the first pending, even one dismissed with Later); the modal subscribes. `shell.reviewRequest` emits, so a
38
+ * plugin (Projects' Review button) opens the one modal wherever the user is. */
39
+ export interface Review {
40
+ emit(id?: string): void;
41
+ subscribe(listener: (id?: string) => void): () => void;
42
+ }
43
+ /** A fresh `Review` (the shell's own when none is handed in). */
44
+ export function createReview(): Review {
45
+ const listeners = new Set<(id?: string) => void>();
46
+ return {
47
+ emit(id) {
48
+ for (const listener of listeners) listener(id);
49
+ },
50
+ subscribe(listener) {
51
+ listeners.add(listener);
52
+ return () => void listeners.delete(listener);
53
+ },
54
+ };
55
+ }
56
+
57
+ /** The view a state shows (the focused window's): its node, screen, item, and utility screen. */
58
+ export const viewOf = ({ node, screen, item, utility }: View): View => ({
59
+ node,
60
+ ...(screen && { screen: { plugin: screen.plugin, id: screen.id } }),
61
+ ...(item !== undefined && { item }),
62
+ ...(utility && { utility: { ...utility } }),
63
+ });
64
+ /** Research-090: `value` as a screen state, a small flat map of strings (at most 16 keys, a key up to 64 characters, a
65
+ * value up to 256); anything else, or an empty map, is none. */
66
+ export const screenStateOf = (value: unknown): Record<string, string> | undefined => {
67
+ if (!isRecord(value)) return undefined;
68
+ const entries = Object.entries(value);
69
+ if (!entries.length || entries.length > 16) return undefined;
70
+ const state: Record<string, string> = {};
71
+ for (const [key, each] of entries) {
72
+ if (!key || key.length > 64 || typeof each !== 'string' || each.length > 256) return undefined;
73
+ state[key] = each;
74
+ }
75
+ return state;
76
+ };
77
+ /** A screen state as the URL's query: `?<key>=<value>&…`, none for none. */
78
+ const searchOf = (state: Record<string, string> | undefined) =>
79
+ state ? `?${new URLSearchParams(state).toString()}` : '';
80
+ /** The screen state the URL's query names (research-090), when `slug` is its workspace; another's names none here. */
81
+ const stateInUrl = (slug: string | undefined) =>
82
+ slug !== undefined && slugInUrl() === slug
83
+ ? screenStateOf(Object.fromEntries(new URLSearchParams(location.search)))
84
+ : undefined;
85
+ const sameState = (a: Record<string, string> | undefined, b: Record<string, string> | undefined) =>
86
+ searchOf(a) === searchOf(b);
87
+ /** `view` with screen state `state` (none: without one). */
88
+ const withState = (view: View, state: Record<string, string> | undefined): View => {
89
+ const { screenState: _, ...rest } = view;
90
+ return state ? { ...rest, screenState: state } : rest;
91
+ };
92
+ /** What a screen state belongs to (research-090): the node, the screen and the utility screen a view shows. */
93
+ const placeOf = ({ node, screen, utility }: Pick<View, 'node' | 'screen' | 'utility'>) =>
94
+ JSON.stringify([node, screen?.plugin, screen?.id, utility?.plugin, utility?.node]);
95
+ /** P8's identity: one window per screen and item (on a node), or per utility screen (on a node); none for a window that
96
+ * shows nothing (several may). */
97
+ const viewKey = (view: View) =>
98
+ view.utility
99
+ ? JSON.stringify(['utility', view.utility.plugin, view.utility.node])
100
+ : view.screen
101
+ ? JSON.stringify(['screen', view.node, view.screen.plugin, view.screen.id, view.item ?? null])
102
+ : undefined;
103
+
104
+ const slugInUrl = () => /^\/([^/]+)\//.exec(location.pathname)?.[1];
105
+ const nodeId = /^(?:root|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/;
106
+ /** What the URL names below `/<slug>/` when `slug` is its workspace: `/<slug>/<node>/<screen path>` (a trailing
107
+ * slash allowed), the screen path being ids from a root screen down, joined by `/` (kebab-case: no encoding), then
108
+ * the screen's item, if any (`screenAt` tells them apart).
109
+ * `/<slug>/` is node `root`. A first segment that is no node id is an old link (`old`): node `root`, the whole
110
+ * rest its screen path. */
111
+ const placeInUrl = (slug: string | undefined, pathname = location.pathname) => {
112
+ const [, inUrl, rest = ''] = /^\/([^/]+)\/(.*?)\/?$/.exec(pathname) ?? [];
113
+ if (inUrl === undefined || inUrl !== slug) return undefined;
114
+ const [first = '', ...below] = rest.split('/');
115
+ if (nodeId.test(first))
116
+ return { node: first, screen: below.length ? below.join('/') : undefined, old: false };
117
+ return { node: 'root', screen: rest || undefined, old: rest !== '' };
118
+ };
119
+ /** Whether the URL names a place below `/<slug>/` (a node, a screen) when `slug` is its workspace. */
120
+ const namesPlace = (slug: string | undefined) =>
121
+ placeInUrl(slug) !== undefined && location.pathname.replace(/\/+$/, '') !== `/${slug}`;
122
+ /** The screen path the URL names, when `slug` is its workspace. */
123
+ export const screenInUrl = (slug: string | undefined) => placeInUrl(slug)?.screen;
124
+ /** A page path: `/<slug>/` for `root` without a screen. */
125
+ const urlOf = (slug: string, node: string, screen?: string) =>
126
+ screen ? `/${slug}/${node}/${screen}` : node === 'root' ? `/${slug}/` : `/${slug}/${node}/`;
127
+ const blocksOf = screenBlocks<NonNullable<ShellState['screens']>['root'][number]>;
128
+ /** The screen at `path` in the tree: the block whose root id is its first id, then each child by id as deep as
129
+ * they match (a child wins over an item); the segments left are its `item`, each decoded, joined by `/`. None for
130
+ * an unknown root id, a bad escape, or a decoded segment no item path holds (`isItemSegment`, the kernel's rule:
131
+ * empty, `.`, `..`, a `/` from `%2F`, a lone surrogate). */
132
+ function screenAt(
133
+ screens: NonNullable<ShellState['screens']>,
134
+ path: string,
135
+ isItemSegment: (segment: string) => boolean,
136
+ ) {
137
+ const [rootId, ...ids] = path.split('/');
138
+ const block = blocksOf(screens).find((b) => b.screen.id === rootId);
139
+ if (!block) return undefined;
140
+ let node = block.screen;
141
+ let depth = 0;
142
+ for (
143
+ let child = node.children?.find((each) => each.id === ids[0]);
144
+ child;
145
+ child = node.children?.find((each) => each.id === ids[depth])
146
+ ) {
147
+ node = child;
148
+ depth++;
149
+ }
150
+ const rest = ids.slice(depth);
151
+ if (!rest.length) return { plugin: block.plugin, id: node.id, item: undefined };
152
+ let segments: string[];
153
+ try {
154
+ segments = rest.map(decodeURIComponent);
155
+ } catch {
156
+ return undefined;
157
+ }
158
+ return segments.every(isItemSegment)
159
+ ? { plugin: block.plugin, id: node.id, item: segments.join('/') }
160
+ : undefined;
161
+ }
162
+ /** An item's URL segments: each encoded. */
163
+ const itemPath = (item: string) => item.split('/').map(encodeURIComponent).join('/');
164
+ const failing = new Set(['failed', 'stopped', 'unresolved']);
165
+ type Status = {
166
+ safe: boolean;
167
+ rootFlag?: string;
168
+ workspaces: {
169
+ slug: string;
170
+ state: string;
171
+ plugins: {
172
+ id: string;
173
+ key: string;
174
+ state: string;
175
+ linked?: true;
176
+ error?: string;
177
+ unresolved?: string[];
178
+ blockedBy?: string[];
179
+ reloadError?: string;
180
+ browserError?: string;
181
+ }[];
182
+ }[];
183
+ };
184
+ const attention = (p: Status['workspaces'][number]['plugins'][number]) =>
185
+ failing.has(p.state) || p.reloadError !== undefined || p.browserError !== undefined;
186
+ export const statusOf = ({ safe, workspaces }: Status): ShellState['status'] =>
187
+ workspaces.some((w) => failing.has(w.state) || w.plugins.some(attention))
188
+ ? 'warning'
189
+ : safe || workspaces.some((w) => w.state === 'safe')
190
+ ? 'safe'
191
+ : 'ok';
192
+
193
+ async function getJson<T>(path: string): Promise<T> {
194
+ return (await readJson(await fetch(path, { cache: 'no-store' }))) as T;
195
+ }
196
+
197
+ /** What the status indicator (the rail's dot, the Bridge status command) opens: Health for a warning (the host opens an
198
+ * episode for every failure the warning stands for: an attention, a plugin's start error or crash, a failed reload, a
199
+ * browser error, a failed workspace), else Admin's Status. */
200
+ export const statusTarget = (status: ShellState['status']): 'health' | 'status' =>
201
+ status === 'warning' ? 'health' : 'status';
202
+
203
+ /** Opens what `statusTarget` says, for the shell's current status. */
204
+ export async function showStatus(
205
+ shell: Pick<Shell, 'get' | 'showHealth' | 'setScreen' | 'setCurrent'>,
206
+ ): Promise<void> {
207
+ if (statusTarget(shell.get().status) === 'health') return shell.showHealth();
208
+ if (shell.get().current?.slug === 'admin')
209
+ return shell.setScreen({ plugin: 'bridge-settings', id: 'status' }, 'root');
210
+ history.pushState(null, '', '/admin/root/status');
211
+ shell.setCurrent('admin');
212
+ }
213
+
214
+ /** Node `node`'s home view (AD-11), as the host resolved it. */
215
+ const homeOf = (nodes: ShellState['nodes'], node: string) => nodes?.resolved?.[node]?.home;
216
+ /** A block's id, `<plugin>/<root screen id>` (research-067). */
217
+ const idOf = ({ plugin, screen }: { plugin: string; screen: { id: string } }) =>
218
+ `${plugin}/${screen.id}`;
219
+ type Block = NonNullable<ShellState['screens']>['root'][number];
220
+ /** Node `node`'s blocks as every navigator lists them (`nodeLayout`, research-067): above the sections, then root's
221
+ * sections; before the tree loads, every screen as fetched. */
222
+ export function blocksOn(
223
+ screens: NonNullable<ShellState['screens']>,
224
+ nodes: ShellState['nodes'],
225
+ node: string,
226
+ ): { top: Block[]; sections: { id: string; title: string; blocks: Block[] }[] } {
227
+ const raw = nodes?.nodes.find((each) => each.id === node);
228
+ if (!raw) return { top: screens.root, sections: screens.sections };
229
+ const all = blocksOf(screens);
230
+ const byId = new Map(all.map((block) => [idOf(block), block]));
231
+ const pick = (ids: string[]) => ids.flatMap((id) => byId.get(id) ?? []);
232
+ const laid = nodeLayout(raw, all.map(idOf), nodes?.resolved?.[node]?.views, chosenBlocks(all));
233
+ return {
234
+ top: pick(laid.top),
235
+ sections: laid.sections.map((section) => ({ ...section, blocks: pick(section.blocks) })),
236
+ };
237
+ }
238
+ /** The block choosing node `node` opens (AD-11, `openingBlock`): its home's first block shown there, else its first
239
+ * block listed; before the tree loads, the first screen. */
240
+ function openingBlockOf(
241
+ screens: NonNullable<ShellState['screens']>,
242
+ nodes: ShellState['nodes'],
243
+ node: string,
244
+ ) {
245
+ const raw = nodes?.nodes.find((each) => each.id === node);
246
+ const all = blocksOf(screens);
247
+ if (!raw) return all[0];
248
+ const id = openingBlock(
249
+ raw,
250
+ all.map(idOf),
251
+ nodes?.resolved?.[node]?.views,
252
+ homeOf(nodes, node),
253
+ chosenBlocks(all),
254
+ );
255
+ return all.find((block) => idOf(block) === id);
256
+ }
257
+ /** What choosing node `node` opens: the root screen id of `openingBlockOf`. */
258
+ function openingOf(
259
+ screens: NonNullable<ShellState['screens']>,
260
+ nodes: ShellState['nodes'],
261
+ node: string,
262
+ ) {
263
+ return openingBlockOf(screens, nodes, node)?.screen.id;
264
+ }
265
+ /** The root screen id of node `node`'s home there: its home's first block it shows. */
266
+ const homeRootOf = (
267
+ screens: NonNullable<ShellState['screens']>,
268
+ nodes: ShellState['nodes'],
269
+ node: string,
270
+ ) => {
271
+ const home = homeOf(nodes, node);
272
+ if (home === undefined) return undefined;
273
+ const { top, sections } = blocksOn(screens, nodes, node);
274
+ return [...top, ...sections.flatMap((section) => section.blocks)].find(
275
+ (block) => block.plugin === home,
276
+ )?.screen.id;
277
+ };
278
+ /** The URL's screen path for `path` (of `plugin`'s tree) on `node`, then `item`'s: none for the node's home (its first
279
+ * root screen) without an item. */
280
+ const urlPathOf = (
281
+ screens: ShellState['screens'],
282
+ nodes: ShellState['nodes'],
283
+ node: string,
284
+ plugin: string | undefined,
285
+ path: { id: string }[],
286
+ item?: string,
287
+ ) =>
288
+ item !== undefined && path.length
289
+ ? `${path.map((each) => each.id).join('/')}/${itemPath(item)}`
290
+ : path.length === 1 &&
291
+ plugin !== undefined &&
292
+ plugin === homeOf(nodes, node) &&
293
+ screens &&
294
+ path[0]!.id === homeRootOf(screens, nodes, node)
295
+ ? undefined
296
+ : path.map((each) => each.id).join('/') || undefined;
297
+
298
+ /** `screens` as root's sections arrange them (research-067): the sidebar organises itself, so its sections and the
299
+ * blocks each holds are the tree's, not the manifests' (`blocksOn` root); the blocks root does not show follow those
300
+ * above the sections, for the other nodes. As fetched when root has no sections (the tree not loaded yet). */
301
+ export function arranged(
302
+ screens: NonNullable<ShellState['screens']>,
303
+ nodes: ShellState['nodes'],
304
+ ): NonNullable<ShellState['screens']> {
305
+ if (!nodes?.nodes.find((node) => node.id === 'root')?.sections) return screens;
306
+ const { top, sections } = blocksOn(screens, nodes, 'root');
307
+ const listed = new Set([...top, ...sections.flatMap((section) => section.blocks)]);
308
+ return {
309
+ root: [...top, ...blocksOf(screens).filter((block) => !listed.has(block))],
310
+ sections,
311
+ order: blocksOf(screens).map(idOf),
312
+ };
313
+ }
314
+
315
+ /** The nodes from a block's root down to `screen`; empty when it is not in the tree. */
316
+ export function pathTo(
317
+ screens: NonNullable<ShellState['screens']>,
318
+ { plugin, id }: { plugin: string; id: string },
319
+ ) {
320
+ type Node = ShellState['path'][number];
321
+ const down = (node: Node): Node[] | undefined => {
322
+ if (node.id === id) return [node];
323
+ for (const child of node.children ?? []) {
324
+ const below = down(child);
325
+ if (below) return [node, ...below];
326
+ }
327
+ return undefined;
328
+ };
329
+ // A plugin with several root screens has a block each.
330
+ for (const block of blocksOf(screens)) {
331
+ const found = block.plugin === plugin ? down(block.screen) : undefined;
332
+ if (found) return found;
333
+ }
334
+ return [];
335
+ }
336
+
337
+ /** Plugin `key` of workspace `slug` as status shows it failed: its id and error with the way out; unresolved (a
338
+ * service it injects is gone), `waiting`, the services it waits for and each failed provider status names, with
339
+ * its way out; enabled (starting, reloading), `waiting` for its start; none otherwise (disabled, removed). */
340
+ async function failureOf(slug: string, key: string): Promise<ShellState['failed']> {
341
+ try {
342
+ const { workspaces, rootFlag = '' } = await getJson<Status>('/_bridge/status');
343
+ const plugins = workspaces.find((w) => w.slug === slug)?.plugins ?? [];
344
+ const plugin = plugins.find((p) => p.key === key);
345
+ if (plugin?.state === 'unresolved') {
346
+ const providers = plugins
347
+ .filter((p) => plugin.blockedBy?.includes(p.id))
348
+ .map((p) =>
349
+ withHint(
350
+ { id: p.id, ...(p.linked && { linked: true }), rootFlag },
351
+ slug,
352
+ `${p.id} failed`,
353
+ ),
354
+ );
355
+ const message = `${plugin.unresolved?.join(', ') || 'a service'} (not running)${providers.length ? `: ${providers.join(' ')}` : ''}`;
356
+ return { key, plugin: plugin.id, message, waiting: true };
357
+ }
358
+ // Enabled yet out of the tree: a reload or a start under way (its new generation is not active yet), not a removal.
359
+ // The screen waits in place; the next tree, once it runs, shows it again.
360
+ if (plugin?.state === 'enabled')
361
+ return { key, plugin: plugin.id, message: 'its start to finish', waiting: true };
362
+ if (plugin?.state !== 'failed') return undefined;
363
+ return {
364
+ key,
365
+ plugin: plugin.id,
366
+ message: withHint(
367
+ { id: plugin.id, ...(plugin.linked && { linked: true }), rootFlag },
368
+ slug,
369
+ plugin.reloadError ?? plugin.error,
370
+ ),
371
+ };
372
+ } catch {
373
+ return undefined;
374
+ }
375
+ }
376
+
377
+ const managerFunctions = ['open', 'focus', 'list', 'focused'] as const;
378
+
379
+ /** The user's appearance as the shell uses it (the kit's client appearance, `@bridge/ui`, given by ./browser.tsx): each
380
+ * workspace's Mine, written; the mode preference; followed. */
381
+ export interface ClientLooks {
382
+ mineOf(slug: string): Record<string, unknown>;
383
+ /** Replace a workspace's Mine (`null`: drop it); answers why it is not kept, if not. */
384
+ setMineFields(slug: string, fields: Record<string, unknown> | null): Promise<string | undefined>;
385
+ mode(): unknown;
386
+ setMode(mode: 'light' | 'dark' | 'system'): Promise<string | undefined>;
387
+ subscribe(listener: () => void): () => void;
388
+ themeOfMode(id: string, mode: 'light' | 'dark'): string | undefined;
389
+ /** The user's look everywhere (research-035, the desktop app's); none: no such layer. */
390
+ everywhere?(): Record<string, unknown>;
391
+ /** Whether this page has the style, icon set or window manager `value` (the navigators the shell knows itself). */
392
+ has?(field: 'style' | 'icons' | 'windowManager', value: string): boolean;
393
+ }
394
+ /** No client appearance (tests): no Mine. */
395
+ const noClient: ClientLooks = {
396
+ mineOf: () => ({}),
397
+ setMineFields: async () => undefined,
398
+ mode: () => undefined,
399
+ setMode: async () => undefined,
400
+ subscribe: () => () => {},
401
+ themeOfMode: () => undefined,
402
+ };
403
+
404
+ /** The browser's choices from before Mine (theme, style, icons, window manager), carried over once into Mine of every
405
+ * workspace in `slugs` (a field Mine already sets kept), then forgotten (appearance slice 3; slice 4 may revisit it). */
406
+ async function carryOver(client: ClientLooks, slugs: string[]) {
407
+ const read = (key: string) => {
408
+ try {
409
+ return localStorage.getItem(key);
410
+ } catch {
411
+ return null;
412
+ }
413
+ };
414
+ const legacy = legacyMine(read, client.themeOfMode);
415
+ // No workspace listed yet: kept for a list that has some (removing the keys now would lose them).
416
+ if (!legacy || slugs.length === 0) return;
417
+ for (const slug of slugs) {
418
+ const mine = client.mineOf(slug);
419
+ const next = { ...legacy.fields, ...mine };
420
+ if (
421
+ Object.keys(next).length !== Object.keys(mine).length &&
422
+ (await client.setMineFields(slug, next)) !== undefined
423
+ )
424
+ return;
425
+ }
426
+ if (
427
+ legacy.mode !== undefined &&
428
+ client.mode() === undefined &&
429
+ (await client.setMode(legacy.mode)) !== undefined
430
+ )
431
+ return;
432
+ for (const key of legacyKeys) {
433
+ try {
434
+ localStorage.removeItem(key);
435
+ } catch {
436
+ /* kept: carried over again, nothing overwritten */
437
+ }
438
+ }
439
+ }
440
+ /** Per page, not per shell: a manager set aside, still said by a shell applied again (a `_host` change re-applies
441
+ * the shell's plugin), until the user chooses. A page slot (./page-slot.ts), so a new shell module instance reads it. */
442
+ const pageManager = pageSlot<{ plugin?: string | undefined; message: string } | undefined>(
443
+ 'bridge.shell.manager',
444
+ );
445
+
446
+ /** `isItemSegment`: the kernel's item path rule (`screenRequests`), for reading the URL. `manager`: the active window
447
+ * manager (research-018 WM3), asked on each call; none, the shell's one window. */
448
+ /** Whether navigator `id` shows: the look's `navigation` names it among those registered; none of them named (no
449
+ * choice, or only navigators this Bridge lacks): every one shows. */
450
+ export function navigatorShown(
451
+ state: {
452
+ navigators: readonly { id: string }[];
453
+ current?: { look?: { navigation?: string[] | undefined } | undefined } | undefined;
454
+ },
455
+ id: string,
456
+ ) {
457
+ const chosen = (state.current?.look?.navigation ?? []).filter((each) =>
458
+ state.navigators.some((navigator) => navigator.id === each),
459
+ );
460
+ return chosen.length === 0 || chosen.includes(id);
461
+ }
462
+
463
+ const sidebarHiddenKey = 'bridge.sidebar.hidden';
464
+ /** The sidebar hidden in this browser (a storage failure: shown). */
465
+ function readSidebarHidden() {
466
+ try {
467
+ return localStorage.getItem(sidebarHiddenKey) === '1';
468
+ } catch {
469
+ return false;
470
+ }
471
+ }
472
+
473
+ /** The shell on the host's status events (`hostStatus.subscribe`), after its first `refresh`: a node tree revision
474
+ * fetches that workspace's tree again; any other event refreshes, but the snapshot `subscribe` replays at once, older
475
+ * than that refresh. The stream's own first snapshot comes later (the page opens it once `_host`'s plugins, the shell
476
+ * among them, are applied): a workspace, plugin or node changed before it was announced to no one, so it refreshes
477
+ * too, the tree with it (bridge#128, bridge#249). Returns the unsubscribe. */
478
+ export function followStatus(
479
+ subscribe: Context['hostStatus']['subscribe'],
480
+ shell: { refresh(): void; nodesChanged(slug?: string, revision?: number): void },
481
+ ) {
482
+ let replaying = true;
483
+ const unsubscribe = subscribe((event) => {
484
+ if (event.event === 'nodes') shell.nodesChanged(event.data.workspace, event.data.revision);
485
+ else if (!(replaying && event.event === 'snapshot')) shell.refresh();
486
+ });
487
+ replaying = false;
488
+ return unsubscribe;
489
+ }
490
+
491
+ export function createShell(
492
+ entries: Context['workspaceEntries'],
493
+ isItemSegment: (segment: string) => boolean,
494
+ manager: () => ManagerRef | undefined = () => undefined,
495
+ shortcuts: Shortcuts = createShortcuts(),
496
+ client: ClientLooks = noClient,
497
+ review: Review = createReview(),
498
+ ) {
499
+ let chosen = slugInUrl();
500
+ /** Every navigator registration, in order (`registerNavigator`); `state.navigators` holds one per id. */
501
+ const registered: { id: string; label: string }[] = [];
502
+ let state: ShellState = {
503
+ workspaces: [],
504
+ current: undefined,
505
+ status: undefined,
506
+ screens: undefined,
507
+ screen: undefined,
508
+ item: undefined,
509
+ path: [],
510
+ loaded: false,
511
+ failed: undefined,
512
+ node: 'root',
513
+ nodes: undefined,
514
+ utility: undefined,
515
+ screenState: undefined,
516
+ managerFailed: undefined,
517
+ managerChoice: undefined,
518
+ sidebarHidden: readSidebarHidden(),
519
+ sidebarFilled: true,
520
+ navigators: [],
521
+ };
522
+ /** The workspaces as `/_bridge/workspaces` last listed them, their looks the proposals. */
523
+ let listed: ShellState['workspaces'] = [];
524
+ /** `list` with each look as this user sees it (Mine over the proposal). */
525
+ /** Whether this page has what a look field names: a navigator this shell knows, else what the client says. */
526
+ const has = (field: (typeof everywhereFields)[number], value: string) =>
527
+ field === 'navigation'
528
+ ? state.navigators.some((navigator) => navigator.id === value)
529
+ : (client.has?.(field, value) ?? true);
530
+ // Each look: the proposal, the user's look everywhere over it where this page has it, their Mine over both.
531
+ const withMines = (list: ShellState['workspaces']) =>
532
+ list.map((w) => {
533
+ const look = withMine(
534
+ withEverywhere(w.look, client.everywhere?.(), has),
535
+ client.mineOf(w.slug),
536
+ );
537
+ const { look: _proposal, ...rest } = w;
538
+ return look === undefined ? rest : { ...rest, look };
539
+ });
540
+ let carried = false;
541
+ // A failure this page saw before this shell came (the shell's plugin applied again): none, for this page only.
542
+ const failedBefore = pageManager.read();
543
+ if (failedBefore) state = { ...state, managerFailed: failedBefore, managerChoice: null };
544
+ const listeners = new Set<() => void>();
545
+ let latest = 0;
546
+ let latestScreens = 0;
547
+ let latestEntries = 0;
548
+ /** Bumped by a workspace change and `stop()`: a tree fetched before is dropped. */
549
+ let nodesEpoch = 0;
550
+ // Tree fetches in launch order, and the one shown: at an equal revision the later launched wins (an activated
551
+ // plugin changes the resolved views without a new revision).
552
+ let nodesFetched = 0;
553
+ let nodesShown = 0;
554
+ /** The page's tree fetches, shared with the workspace plugins' `nodes` service (bridge#50); the shell's own under an
555
+ * older boot kernel. */
556
+ const trees = entries.tree ?? nodeTrees((path) => fetch(path, { cache: 'no-store' })).load;
557
+ /** The node changes waiting for their tree to be shown: `stop()` rejects them. */
558
+ const waitingChanges = new Set<(error: Error) => void>();
559
+ /** Set by `stop()`: no tree is fetched or shown any more, a change answered later rejects. */
560
+ let ended = false;
561
+ /** The screen path the URL names, until a tree says which screen it is. */
562
+ let wanted: string | undefined;
563
+ /** Set by `setScreen` until the tree confirms or drops its screen: that choice gets a history entry. */
564
+ let choosing = false;
565
+ /** The last view routed to the window manager, with its workspace (`route`). */
566
+ let routed: string | undefined;
567
+ let routedSlug: string | undefined;
568
+ /** Set by a ⌘-click (Ctrl-click) for the view change it causes: that view opens in a new window (W8). */
569
+ let beside = false;
570
+ /** Set by an ⌥-click in the sidebar, with `beside`: that view opens on a new desk (W8). */
571
+ let newDesk = false;
572
+ /** ⌘K's ⇧↵, ⇧⌘↵ (research-034): the next view change opens floating, or maximized. */
573
+ let shape: 'float' | 'max' | undefined;
574
+ /** The next view change is ⌘K's (`placeNext`): a window showing it already is gone to, never closed (`toggle`). */
575
+ let placed = false;
576
+ let besideTimer: ReturnType<typeof setTimeout> | undefined;
577
+ /** A modified click's view in another workspace (`openIn`): opened beside there once that workspace is routed. */
578
+ let pending: { slug: string; view: View; desk: boolean } | undefined;
579
+ /** Whether the URL named a node or a screen when the current workspace was entered (or on Back/Forward): that place
580
+ * is shown (a screen gone: nothing), never replaced by a window's restored view; only a bare `/<slug>/` (or a URL
581
+ * of another workspace) restores. */
582
+ let urlNamed = false;
583
+ /** Set when a window manager shows an empty window (`show` with a node alone), or a link names no screen on `root`:
584
+ * the node's home is not opened in it; dropped by any choice (a view, a node, a utility screen, Back or Forward, another workspace). */
585
+ let bare = false;
586
+ /** A manager set aside (C6): this page goes on with none, until the user chooses or reloads. Not stored: a failure
587
+ * (a plugin reloaded under the page, a transient throw) must not turn this browser's windows off for good. */
588
+ const setAside = (failure: NonNullable<ShellState['managerFailed']>) => {
589
+ pageManager.write(failure);
590
+ state = { ...state, managerFailed: failure, managerChoice: null };
591
+ };
592
+ /** The current view, as a window manager restored it: the state shows `view` (its path when the tree has it). */
593
+ const adopt = (view: View) => {
594
+ const path = view.screen && state.screens ? pathTo(state.screens, view.screen) : [];
595
+ state = {
596
+ ...state,
597
+ node: view.node,
598
+ screen: view.screen,
599
+ item: view.screen ? view.item : undefined,
600
+ utility: view.utility,
601
+ screenState: screenStateOf(view.screenState),
602
+ path,
603
+ failed: undefined,
604
+ };
605
+ const slug = state.current?.slug;
606
+ if (slug !== undefined && path.length)
607
+ history.replaceState(
608
+ null,
609
+ '',
610
+ `${urlOf(
611
+ slug,
612
+ view.node,
613
+ urlPathOf(state.screens, state.nodes, view.node, view.screen?.plugin, path, view.item),
614
+ )}${searchOf(state.screenState)}`,
615
+ );
616
+ };
617
+ /** Tells the window manager the current view once it settled (not while the URL's screen waits for the tree), when
618
+ * it changed or a ⌘-click asked for a new window: P8 first (a window showing it is focused), else `open` (beside
619
+ * when asked). Entering a workspace without a view to show (`restore`, or a workspace change), the manager's focused
620
+ * window's view is adopted. A manager missing a function or throwing is set aside for the page (C6). */
621
+ const route = (restore = false) => {
622
+ if (state.managerFailed || wanted !== undefined || !state.current) return;
623
+ const ref = manager();
624
+ if (!ref) {
625
+ routed = undefined;
626
+ return;
627
+ }
628
+ const wm = ref.service;
629
+ const slug = state.current.slug;
630
+ try {
631
+ for (const fn of managerFunctions)
632
+ if (typeof wm[fn] !== 'function') throw new TypeError(`its windowManager has no ${fn}()`);
633
+ const { open, focus, list, focused } = wm as WindowManager;
634
+ let view = withState(viewOf(state), state.screenState);
635
+ // Root's first sidebar item, shown by default, gives way to the focused window's view too.
636
+ const home =
637
+ view.node === 'root' && view.item === undefined && state.screens
638
+ ? openingBlockOf(state.screens, state.nodes, 'root')
639
+ : undefined;
640
+ const homed =
641
+ home !== undefined &&
642
+ view.screen?.plugin === home.plugin &&
643
+ view.screen.id === home.screen.id;
644
+ if ((restore || slug !== routedSlug) && !urlNamed && (viewKey(view) === undefined || homed)) {
645
+ const at = focused.call(wm);
646
+ const kept = list.call(wm).find((each) => each.id === at)?.view;
647
+ if (
648
+ kept &&
649
+ viewKey(kept) !== undefined &&
650
+ (!kept.screen || !state.screens || pathTo(state.screens, kept.screen).length)
651
+ ) {
652
+ adopt(kept);
653
+ view = withState(viewOf(state), state.screenState);
654
+ }
655
+ }
656
+ const asked = beside;
657
+ const desk = newDesk;
658
+ const shaped = shape;
659
+ beside = false;
660
+ newDesk = false;
661
+ shape = undefined;
662
+ placed = false;
663
+ const text = JSON.stringify([slug, view]);
664
+ if (!asked && !restore && text === routed) return void placePending(slug);
665
+ routed = text;
666
+ routedSlug = slug;
667
+ const key = viewKey(view);
668
+ const shown =
669
+ key === undefined ? undefined : list.call(wm).find((each) => viewKey(each.view) === key);
670
+ // A new desk (⌥) opens one, even for a view a window shows already.
671
+ if (shown && !desk) {
672
+ if (shown.id !== focused.call(wm)) focus.call(wm, shown.id);
673
+ // Research-090: the window takes the current view's screen state (a screen opened again: its default).
674
+ if (!sameState(screenStateOf(shown.view.screenState), view.screenState))
675
+ open.call(wm, view, { into: shown.id });
676
+ } else
677
+ open.call(
678
+ wm,
679
+ view,
680
+ asked
681
+ ? {
682
+ beside: true,
683
+ ...(desk && { desk: 'new' as const }),
684
+ ...(shaped === 'float' && { float: true }),
685
+ ...(shaped === 'max' && { max: true }),
686
+ }
687
+ : {},
688
+ );
689
+ placePending(slug);
690
+ } catch (error) {
691
+ setAside({
692
+ plugin: ref.plugin,
693
+ message: error instanceof Error ? error.message : String(error),
694
+ });
695
+ }
696
+ };
697
+ /** `openIn`'s view, once its workspace is the one routed: beside its focused window, or on a new desk. */
698
+ const placePending = (slug: string) => {
699
+ if (pending?.slug !== slug) return;
700
+ const { view, desk } = pending;
701
+ pending = undefined;
702
+ request(view, desk ? { desk: true } : { beside: true });
703
+ };
704
+ /** The active window manager, every function the shell calls there checked (`close` optional); none (or one set aside:
705
+ * the failure said), `undefined`. */
706
+ const usable = () => {
707
+ if (state.managerFailed || !state.current) return undefined;
708
+ const ref = manager();
709
+ if (!ref) return undefined;
710
+ for (const fn of managerFunctions) {
711
+ if (typeof ref.service[fn] !== 'function')
712
+ return void failed(ref, new TypeError(`its windowManager has no ${fn}()`));
713
+ }
714
+ return { ref, wm: ref.service as WindowManager & { close?: WindowManager['close'] } };
715
+ };
716
+ /** A manager that threw: set aside (C6), said. */
717
+ const failed = (ref: ManagerRef, error: unknown) => {
718
+ setAside({
719
+ plugin: ref.plugin,
720
+ message: error instanceof Error ? error.message : String(error),
721
+ });
722
+ for (const listener of listeners) listener();
723
+ };
724
+ /** A modified click's view change (the flags `besideNext` and `deskNext` set; not ⌘K's, `placed`): `view` opened by
725
+ * the manager as a plugin's request is (`request`: beside the focused window, which keeps the focus; ⌘ on what
726
+ * another window shows closes it, W8; ⌥ on a new desk), the current view, the URL and the history kept
727
+ * (research-048). Says whether it did; without a manager, `unplaced` said nothing happens. */
728
+ const placeBeside = (view: View) => {
729
+ if (!beside || placed) return false;
730
+ const desk = newDesk;
731
+ beside = false;
732
+ newDesk = false;
733
+ shape = undefined;
734
+ return request(view, desk ? { desk: true } : { beside: true });
735
+ };
736
+ /** A plugin's request with hints (`ctx.screen.open(item, { beside, reuse })`): `view` shown in another window than the
737
+ * one asking, the focused one (a click focuses its window first), which keeps the focus (W7): the current view, the
738
+ * URL and the history stay. A window of the desk showing `view` already: closed on `beside` (a ⌘-click, as `toggle`),
739
+ * unless it is the one asking; else left as it is. `reuse`: in another window of the desk showing the same screen on
740
+ * the same node (its item replaced), the one the manager's `reusable` names (slice 6c: of the kind asked, focused
741
+ * last; none: beside), else, a manager without it, the first; none, beside. False without a window manager (the one
742
+ * window shows it). */
743
+ const request = (
744
+ view: View,
745
+ { beside: asked, desk, reuse }: { beside?: true; desk?: true; reuse?: true },
746
+ source?: string,
747
+ ) => {
748
+ const fresh = asked ?? desk;
749
+ const at = usable();
750
+ if (!at) return false;
751
+ try {
752
+ // The window asking: the one a link was clicked in (research-048), else the focused one.
753
+ const from = source ?? at.wm.focused();
754
+ const windows = at.wm.list();
755
+ const key = viewKey(view);
756
+ const shown = windows.find((each) => viewKey(each.view) === key);
757
+ // A new desk (⌥) is asked for whatever shows that view already: never a close (W8's toggle is ⌘'s).
758
+ if (shown && !desk) {
759
+ // ⌘ on what another window shows: closed (W8); a manager that cannot close focuses it (P8).
760
+ if (fresh && shown.id !== from) {
761
+ if (typeof at.wm.close === 'function') at.wm.close(shown.id);
762
+ else at.wm.focus(shown.id);
763
+ }
764
+ return true;
765
+ }
766
+ const into =
767
+ fresh || desk || !reuse
768
+ ? undefined
769
+ : typeof at.wm.reusable === 'function'
770
+ ? at.wm.reusable(view, from)
771
+ : windows.find(
772
+ ({ id, view: each }) =>
773
+ id !== from &&
774
+ !each.utility &&
775
+ each.node === view.node &&
776
+ each.screen?.plugin === view.screen?.plugin &&
777
+ each.screen?.id === view.screen?.id,
778
+ )?.id;
779
+ // A window the manager does not list, or the one asking: beside.
780
+ const target =
781
+ into === undefined || into === from ? undefined : windows.find((each) => each.id === into);
782
+ const known = target !== undefined;
783
+ // Research-090: another item in a window of the same screen keeps that window's screen state.
784
+ at.wm.open(
785
+ known && view.screenState === undefined
786
+ ? withState(view, screenStateOf(target.view.screenState))
787
+ : view,
788
+ known
789
+ ? { into: target.id }
790
+ : {
791
+ beside: true,
792
+ ...(desk && { desk: 'new' as const }),
793
+ ...(from !== undefined && { from }),
794
+ },
795
+ );
796
+ return true;
797
+ } catch (error) {
798
+ failed(at.ref, error);
799
+ return false;
800
+ }
801
+ };
802
+ /** A plugin's `beside` while none of its screens is shown (its tab in another plugin's screen: a session's browser):
803
+ * its first root screen with `item`, on the node shown when the plugin shows there, else the root, in a new window
804
+ * beside the focused one, which keeps the focus; the window showing it already focused instead. Nothing without a
805
+ * window manager. */
806
+ /** Whether a window manager took it (opened or focused a window). */
807
+ const elsewhere = (plugin: string, item: string | undefined, desk?: true): boolean => {
808
+ const at = usable();
809
+ const block =
810
+ state.screens &&
811
+ [...state.screens.root, ...state.screens.sections.flatMap((section) => section.blocks)].find(
812
+ (each) => each.plugin === plugin,
813
+ );
814
+ if (!at || !block) return false;
815
+ const node = state.nodes?.resolved?.[state.node]?.views.includes(plugin) ? state.node : 'root';
816
+ const view: View = {
817
+ node,
818
+ screen: { plugin, id: block.screen.id },
819
+ ...(item !== undefined && { item }),
820
+ };
821
+ try {
822
+ const shown = at.wm.list().find((each) => viewKey(each.view) === viewKey(view));
823
+ if (shown) {
824
+ at.wm.focus(shown.id);
825
+ return true;
826
+ }
827
+ const from = at.wm.focused();
828
+ at.wm.open(view, {
829
+ beside: true,
830
+ ...(desk && { desk: 'new' as const }),
831
+ ...(from !== undefined && { from }),
832
+ });
833
+ return true;
834
+ } catch (error) {
835
+ failed(at.ref, error);
836
+ return false;
837
+ }
838
+ };
839
+ /** A modified click (⌘, Ctrl, ⌥, a middle click: the flags `besideNext` sets) without a window manager does nothing
840
+ * (research-048): no fallback to the same window. Not ⌘K's placements (`placeNext`): those show here then. Says
841
+ * whether it dropped the view change. */
842
+ const unplaced = () => {
843
+ if (!beside || placed || usable()) return false;
844
+ beside = false;
845
+ newDesk = false;
846
+ shape = undefined;
847
+ return true;
848
+ };
849
+ /** Applies `next`; another current workspace drops the screens and the selection (but the one its URL
850
+ * names, taken once a tree has its path, kept through a failed fetch), and loads its own screens and
851
+ * browser entries. A URL path not in the tree (an unknown id, a level skipped) or a selected screen not
852
+ * in it (its plugin disabled or removed) is no longer selected, nor in the URL; but a shown screen whose
853
+ * plugin failed or is unresolved (`failed`) keeps its path and URL, and renders in place once its plugin is
854
+ * back; while the tree loads or after it failed to, nothing proves it gone: kept, and checked when the tree
855
+ * arrives. A URL naming no
856
+ * workspace listed gets the one shown instead (and it becomes the choice: a workspace created later
857
+ * under that slug does not take over). */
858
+ /** The utility screen `setUtility` showed on another node, pushing a history entry: `closeUtility` goes back off it
859
+ * while that very one is shown (one reopened, or closed by the history, is not). */
860
+ let pushedFor: ShellState['utility'];
861
+ /** The current workspace's screens as `/screens` answered them, before `arranged`. */
862
+ let fetchedScreens: ShellState['screens'];
863
+ const update = (next: Partial<ShellState>) => {
864
+ const workspaces = next.workspaces ?? state.workspaces;
865
+ const current = workspaces.find((w) => w.slug === chosen) ?? workspaces[0];
866
+ const moved = current?.slug !== state.current?.slug;
867
+ const merged = {
868
+ ...state,
869
+ ...next,
870
+ current,
871
+ ...(moved && {
872
+ screens: undefined,
873
+ screen: undefined,
874
+ item: undefined,
875
+ loaded: false,
876
+ failed: undefined,
877
+ nodes: undefined,
878
+ node: placeInUrl(current?.slug)?.node ?? 'root',
879
+ utility: undefined,
880
+ screenState: stateInUrl(current?.slug),
881
+ }),
882
+ };
883
+ if (merged.utility !== pushedFor) pushedFor = undefined;
884
+ if (moved) {
885
+ nodesEpoch++;
886
+ wanted = screenInUrl(current?.slug);
887
+ urlNamed = namesPlace(current?.slug);
888
+ bare = false;
889
+ }
890
+ // A node the loaded tree does not have: `root` (AD-6).
891
+ if (merged.nodes && !merged.nodes.nodes.some((node) => node.id === merged.node))
892
+ merged.node = 'root';
893
+ // The URL names the current node, in the current form (an old link gets `root/` in place).
894
+ const place = placeInUrl(current?.slug);
895
+ if (current && place && (place.old || place.node !== merged.node)) {
896
+ history.replaceState(
897
+ null,
898
+ '',
899
+ `${urlOf(current.slug, merged.node, place.screen)}${place.screen && location.pathname.endsWith('/') ? '/' : ''}`,
900
+ );
901
+ }
902
+ // The screens as fetched, arranged by the tree each time either changes.
903
+ if (next.screens !== undefined) fetchedScreens = next.screens;
904
+ if (merged.screens && fetchedScreens && ('screens' in next || 'nodes' in next))
905
+ merged.screens = arranged(fetchedScreens, merged.nodes);
906
+ const { screens } = merged;
907
+ const named = screenInUrl(current?.slug);
908
+ let dropped = false;
909
+ if (wanted !== undefined && screens) {
910
+ const at = screenAt(screens, wanted, isItemSegment);
911
+ merged.screen = at && { plugin: at.plugin, id: at.id };
912
+ merged.item = at?.item;
913
+ dropped = !merged.screen && named === wanted;
914
+ wanted = undefined;
915
+ }
916
+ const { screen } = merged;
917
+ merged.path = screen && screens ? pathTo(screens, screen) : [];
918
+ const shown =
919
+ screen &&
920
+ state.screen?.plugin === screen.plugin &&
921
+ state.screen.id === screen.id &&
922
+ state.path.length > 0;
923
+ if (screen && screens && !merged.path.length && shown && merged.failed?.key === screen.plugin)
924
+ merged.path = state.path;
925
+ else {
926
+ merged.failed = undefined;
927
+ if (screen && screens && !merged.path.length) {
928
+ merged.screen = undefined;
929
+ // Nothing chosen now: a URL naming a screen (this one, or one a deep link named before) goes.
930
+ dropped = named !== undefined;
931
+ }
932
+ }
933
+ if (!merged.screen) merged.item = undefined;
934
+ // A node shown without a screen (a bare `/<slug>/` or `/<slug>/<node>/`, Back to it, its screen gone): its home,
935
+ // else its first view (AD-11): the workspace (`root`) opens on the first item of its sidebar, so dragging one to
936
+ // the top makes it the home; a link naming no screen there keeps the notice, through later updates too (`bare`,
937
+ // dropped by the next choice).
938
+ if (dropped && merged.node === 'root') bare = true;
939
+ if (!merged.screen && !bare && screens && merged.nodes) {
940
+ const id = openingOf(screens, merged.nodes, merged.node);
941
+ const at = id === undefined ? undefined : screenAt(screens, id, isItemSegment);
942
+ if (at) {
943
+ merged.screen = { plugin: at.plugin, id: at.id };
944
+ merged.path = pathTo(screens, at);
945
+ }
946
+ }
947
+ const inUrl = slugInUrl();
948
+ if (current && inUrl !== undefined && !workspaces.some((w) => w.slug === inUrl)) {
949
+ chosen = current.slug;
950
+ history.replaceState(null, '', `/${current.slug}/`);
951
+ }
952
+ if (dropped) history.replaceState(null, '', urlOf(current!.slug, merged.node));
953
+ // A screen the tree confirms gets its path as URL: a new history entry when chosen (once: choosing it
954
+ // again adds none; also chosen while the tree loaded), else in place (a refresh moving it in its tree:
955
+ // Back must not land on the old path).
956
+ const target = urlPathOf(
957
+ merged.screens,
958
+ merged.nodes,
959
+ merged.node,
960
+ merged.screen?.plugin,
961
+ merged.path,
962
+ merged.item,
963
+ );
964
+ if (merged.path.length && named !== target) {
965
+ history[choosing ? 'pushState' : 'replaceState'](
966
+ null,
967
+ '',
968
+ urlOf(current!.slug, merged.node, target),
969
+ );
970
+ }
971
+ if (screens || moved) choosing = false;
972
+ // Research-090: a screen state belongs to its node and screen; the view shows another (not named by `next`): dropped.
973
+ if (
974
+ !('screenState' in next) &&
975
+ !moved &&
976
+ (state.screen || state.utility) &&
977
+ placeOf(merged) !== placeOf(state)
978
+ )
979
+ merged.screenState = undefined;
980
+ // The URL's query is the current view's screen state, once its screen is known (or none is shown).
981
+ if (current && slugInUrl() === current.slug && !(merged.screen && !merged.path.length)) {
982
+ const search = searchOf(merged.screenState);
983
+ if (location.search !== search)
984
+ history.replaceState(history.state, '', `${location.pathname}${search}${location.hash}`);
985
+ }
986
+ state = merged;
987
+ route();
988
+ for (const listener of listeners) listener();
989
+ if (moved) {
990
+ void loadScreens();
991
+ void loadEntries();
992
+ void loadNodes();
993
+ }
994
+ return moved;
995
+ };
996
+ // The user's appearance changed (Mine set here, in Settings, in another tab or instance): the looks again; another
997
+ // window manager for the workspace shown is a small reboot, as `chooseManager`.
998
+ const unmine = client.subscribe(() => looksAgain());
999
+ /** The looks again (Mine or the look everywhere changed, or what this page has: a pack, a manager, a navigator). */
1000
+ function looksAgain() {
1001
+ if (!listed.length) return;
1002
+ const manager = state.current?.look?.windowManager;
1003
+ update({ workspaces: withMines(listed) });
1004
+ if (state.current?.look?.windowManager === manager) return;
1005
+ routed = undefined;
1006
+ route(true);
1007
+ }
1008
+ /** The current workspace's node tree (`/_bridge/workspaces/<slug>/nodes`), at `revision` or newer when given (a change
1009
+ * or its `nodes` event: it joins the fetch on its way, `trees`); whatever order the fetches answer in, a
1010
+ * tree applies unless an older revision than the one shown (the host's revision only grows), or the same revision
1011
+ * fetched before the shown one, or fetched before a
1012
+ * workspace change or `stop()`; a failed fetch keeps what was shown. */
1013
+ const loadNodes = async (revision?: number) => {
1014
+ const epoch = nodesEpoch;
1015
+ const fetched = ++nodesFetched;
1016
+ const slug = state.current?.slug;
1017
+ if (slug === undefined || ended) return;
1018
+ try {
1019
+ const nodes = (await trees(slug, revision)) as NonNullable<ShellState['nodes']>;
1020
+ const shown = state.nodes?.revision ?? -1;
1021
+ if (
1022
+ epoch === nodesEpoch &&
1023
+ nodes !== state.nodes &&
1024
+ (nodes.revision > shown || (nodes.revision === shown && fetched > nodesShown))
1025
+ ) {
1026
+ nodesShown = fetched;
1027
+ update({ nodes });
1028
+ }
1029
+ } catch {
1030
+ /* kept */
1031
+ }
1032
+ };
1033
+ /** The kernel disposes the previous workspace's plugins and loads the current one's; `loaded` once they
1034
+ * settled, unless the current workspace changed meanwhile. */
1035
+ const loadEntries = async () => {
1036
+ const run = ++latestEntries;
1037
+ await entries.open(state.current?.slug);
1038
+ if (run === latestEntries) update({ loaded: true });
1039
+ };
1040
+ /** Like `refresh`: a failed fetch keeps what was shown (`null` when nothing was: not loading forever),
1041
+ * and only the latest call applies, so an answer for a workspace no longer current is dropped. */
1042
+ const loadScreens = async () => {
1043
+ const run = ++latestScreens;
1044
+ const slug = state.current?.slug;
1045
+ if (slug === undefined) return;
1046
+ try {
1047
+ const screens = await getJson<NonNullable<ShellState['screens']>>(
1048
+ `/_bridge/workspaces/${encodeURIComponent(slug)}/screens`,
1049
+ );
1050
+ // The chosen screen's plugin gone from the tree: failed, or removed for another reason? Status asked after
1051
+ // the tree: a plugin the tree left out as failed shows failed there too.
1052
+ const chosen = state.screen;
1053
+ const failed =
1054
+ chosen && !blocksOf(screens).some((b) => b.plugin === chosen.plugin)
1055
+ ? await failureOf(slug, chosen.plugin)
1056
+ : undefined;
1057
+ if (run === latestScreens) update({ screens, failed });
1058
+ } catch {
1059
+ if (run === latestScreens && state.screens === undefined) update({ screens: null });
1060
+ }
1061
+ };
1062
+ const stoppedError = () => new Error('The shell stopped before the change was shown.');
1063
+ /** One call to the current workspace's nodes endpoint; resolves once a tree at the revision it made is shown,
1064
+ * whichever fetch brought it (the sidebar then focuses a row that is still there). Its own fetch failed twice: rejects
1065
+ * with `code: 'not-shown'`, the change made but not shown; `stop()` rejects it too. */
1066
+ const changeNodes = async (method: string, below: string, body: object): Promise<unknown> => {
1067
+ const slug = state.current?.slug;
1068
+ if (slug === undefined) throw new Error('No workspace shown');
1069
+ const res = await fetch(`/_bridge/workspaces/${encodeURIComponent(slug)}/nodes${below}`, {
1070
+ method,
1071
+ headers: { 'content-type': 'application/json' },
1072
+ body: JSON.stringify(body),
1073
+ });
1074
+ const answer = await readJson(res);
1075
+ if ('dryRun' in body && body.dryRun) return answer;
1076
+ if (ended) throw stoppedError();
1077
+ const revision = isRecord(answer) && typeof answer.revision === 'number' ? answer.revision : 0;
1078
+ const shown = () => slug !== state.current?.slug || (state.nodes?.revision ?? -1) >= revision;
1079
+ let check = () => {};
1080
+ let stopped = (_error: Error) => {};
1081
+ const applied = new Promise<void>((resolve, reject) => {
1082
+ check = () => void (shown() && resolve());
1083
+ stopped = reject;
1084
+ listeners.add(check);
1085
+ waitingChanges.add(stopped);
1086
+ // Its `nodes` event may have shown the tree before the change answered.
1087
+ check();
1088
+ });
1089
+ const fetched = (async () => {
1090
+ await loadNodes(revision);
1091
+ if (!shown()) await loadNodes(revision);
1092
+ if (!shown())
1093
+ throw Object.assign(
1094
+ new Error(
1095
+ 'The change is saved, but the tree could not be fetched again: reload the page to see it.',
1096
+ ),
1097
+ { code: 'not-shown' },
1098
+ );
1099
+ })();
1100
+ try {
1101
+ await Promise.race([applied, fetched]);
1102
+ } finally {
1103
+ listeners.delete(check);
1104
+ waitingChanges.delete(stopped);
1105
+ }
1106
+ return answer;
1107
+ };
1108
+ // Research-069: a turn's window that becomes editing spends that turn, whatever comes after (a save).
1109
+ const viewScopes = createViewScopes((id) => {
1110
+ const slug = state.current?.slug;
1111
+ if (slug === undefined) return;
1112
+ const turns = presented(slug);
1113
+ let spent = false;
1114
+ for (const [turn, window] of turns)
1115
+ if (window === id) {
1116
+ turns.set(turn, SPENT);
1117
+ spent = true;
1118
+ }
1119
+ if (spent) save(slug);
1120
+ });
1121
+ /** Research-069, one window per agent's turn: the window each turn showed its page in, per workspace, held here
1122
+ * (read from the page's storage once, so a reload keeps it), the last turns only; written there when it can be. */
1123
+ const presentedKey = (slug: string) => `bridge.presented.${slug}`;
1124
+ /** A turn whose window became editing (or closed): nothing more opens in it. No window has this id. */
1125
+ const SPENT = '';
1126
+ const turnsBySlug = new Map<string, Map<string, string>>();
1127
+ const presented = (slug: string): Map<string, string> => {
1128
+ let turns = turnsBySlug.get(slug);
1129
+ if (turns) return turns;
1130
+ turns = new Map();
1131
+ try {
1132
+ const stored: unknown = JSON.parse(sessionStorage.getItem(presentedKey(slug)) ?? '[]');
1133
+ if (Array.isArray(stored))
1134
+ for (const each of stored)
1135
+ if (Array.isArray(each) && typeof each[0] === 'string' && typeof each[1] === 'string')
1136
+ turns.set(each[0], each[1]);
1137
+ } catch {
1138
+ // Nothing readable: this page's turns start here.
1139
+ }
1140
+ turnsBySlug.set(slug, turns);
1141
+ return turns;
1142
+ };
1143
+ const save = (slug: string) => {
1144
+ try {
1145
+ sessionStorage.setItem(presentedKey(slug), JSON.stringify([...presented(slug)]));
1146
+ } catch {
1147
+ // No storage (full, a private window): held for this page's life, lost only on a reload.
1148
+ }
1149
+ };
1150
+ const remember = (slug: string, turn: string | undefined, window: string) => {
1151
+ if (turn === undefined) return;
1152
+ const turns = presented(slug);
1153
+ turns.delete(turn);
1154
+ turns.set(turn, window);
1155
+ for (const old of [...turns.keys()].slice(0, -20)) turns.delete(old);
1156
+ save(slug);
1157
+ };
1158
+
1159
+ const shell = {
1160
+ get: () => state,
1161
+ viewState: viewScopes.viewState,
1162
+ viewScope: viewScopes.viewScope,
1163
+ present(view: View, from: string, turn?: string) {
1164
+ type Reason = 'no-manager' | 'not-shown' | 'hidden' | 'turn-used' | 'no-room';
1165
+ const refused = (reason: Reason) => ({ shown: false as const, reason });
1166
+ const at = usable();
1167
+ if (!at || !state.current) return refused('no-manager');
1168
+ const slug = state.current.slug;
1169
+ try {
1170
+ const windows = at.wm.list();
1171
+ const source = windows.find((each) => each.id === from);
1172
+ if (!source || source.hidden) return refused('not-shown');
1173
+ // What may be replaced: a window the user sees, idle (its state known), neither the session's nor the one the user
1174
+ // has focused (owner).
1175
+ const focused = at.wm.focused();
1176
+ const eligible = (id: string) =>
1177
+ id !== from &&
1178
+ id !== focused &&
1179
+ windows.some((each) => each.id === id && !each.hidden) &&
1180
+ viewScopes.viewState(id) === 'idle';
1181
+ const key = viewKey(view);
1182
+ const exact =
1183
+ key === undefined ? undefined : windows.find((each) => viewKey(each.view) === key);
1184
+ if (exact)
1185
+ return exact.hidden ? refused('hidden') : { shown: 'visible' as const, window: exact.id };
1186
+ const used = turn === undefined ? undefined : presented(slug).get(turn);
1187
+ if (used !== undefined && !eligible(used)) return refused('turn-used');
1188
+ const into =
1189
+ used ??
1190
+ (typeof at.wm.reusable === 'function' ? at.wm.reusable(view, from, eligible) : undefined);
1191
+ if (into !== undefined && eligible(into)) {
1192
+ keepFocus(into);
1193
+ at.wm.open(view, { into });
1194
+ remember(slug, turn, into);
1195
+ return { shown: 'replaced' as const, window: into };
1196
+ }
1197
+ if (typeof at.wm.tryOpen !== 'function') return refused('no-room');
1198
+ const opened = at.wm.tryOpen(view, from);
1199
+ if (opened === undefined) return refused('no-room');
1200
+ // Its view mounts once the page renders again, after this call.
1201
+ keepFocus(opened);
1202
+ remember(slug, turn, opened);
1203
+ return { shown: 'opened' as const, window: opened };
1204
+ } catch (error) {
1205
+ failed(at.ref, error);
1206
+ return refused('no-manager');
1207
+ }
1208
+ },
1209
+ setCurrent(slug: string) {
1210
+ chosen = slug;
1211
+ update({});
1212
+ },
1213
+ /** The user asks to review request `id` (or, with none, the first pending) from the page (Projects' Review
1214
+ * button): the shell's approval modal opens on it, even one dismissed with Later. */
1215
+ reviewRequest(id?: string) {
1216
+ review.emit(id);
1217
+ },
1218
+ /** A new object each call, even for the same screen: the sidebar reveals it again. Its URL goes in
1219
+ * the history once the tree has it. `node`: shown on that node (a view chosen under another node). `item`: the
1220
+ * screen's item (none by default); the same screen with another item stays mounted (the shell keys by node). */
1221
+ setScreen(
1222
+ { plugin, id }: { plugin: string; id: string },
1223
+ node?: string,
1224
+ item?: string,
1225
+ asked?: Record<string, string>,
1226
+ ) {
1227
+ if (unplaced()) return;
1228
+ const screenState = screenStateOf(asked);
1229
+ // A ⌘- or ⌥-click (not ⌘K's placements): in a new window, the focused one keeping the focus, its view, the URL
1230
+ // and the history (research-048); on what another window shows, ⌘ closes that window (W8).
1231
+ if (
1232
+ placeBeside(
1233
+ withState(
1234
+ {
1235
+ node: node ?? state.node,
1236
+ screen: { plugin, id },
1237
+ ...(item !== undefined && { item }),
1238
+ },
1239
+ screenState,
1240
+ ),
1241
+ )
1242
+ )
1243
+ return;
1244
+ wanted = undefined;
1245
+ bare = false;
1246
+ const slug = state.current?.slug;
1247
+ if (node === undefined || node === state.node || slug === undefined || !state.screens) {
1248
+ choosing = true;
1249
+ return void update({ screen: { plugin, id }, item, utility: undefined, screenState });
1250
+ }
1251
+ // Another node: one history entry for both (the URL first, so the node change rewrites no older entry).
1252
+ history.pushState(
1253
+ null,
1254
+ '',
1255
+ urlOf(
1256
+ slug,
1257
+ node,
1258
+ urlPathOf(
1259
+ state.screens,
1260
+ state.nodes,
1261
+ node,
1262
+ plugin,
1263
+ pathTo(state.screens, { plugin, id }),
1264
+ item,
1265
+ ),
1266
+ ),
1267
+ );
1268
+ choosing = false;
1269
+ update({ node, screen: { plugin, id }, item, utility: undefined, screenState });
1270
+ },
1271
+ /** Plugin `plugin`'s `ctx.screen.open(item?, hints?)` (the kernel's `screenRequests`): its screen shown, with `item`
1272
+ * (`setScreen`); ignored unless that plugin's screen is shown, confirmed by the tree, with no utility screen over
1273
+ * it. An item starting with the id of a child of that screen throws a `TypeError`: its URL would name the child.
1274
+ * `beside`, `reuse`: in another window (`request`), the asking one keeping the focus; no manager, as without.
1275
+ * `show` (research-034): none of its screens shown, its first root screen with `item`, here. */
1276
+ openItem(
1277
+ plugin: string,
1278
+ item: string | undefined,
1279
+ hints: { beside?: true; desk?: true; reuse?: true; show?: true } = {},
1280
+ ) {
1281
+ const { screen, path, utility, node } = state;
1282
+ // `beside` with `show` (a toast's Open, research-034): a window beside with a manager, else shown here.
1283
+ if (
1284
+ (hints.beside || hints.desk) &&
1285
+ screen?.plugin !== plugin &&
1286
+ (elsewhere(plugin, item, hints.desk) || !hints.show)
1287
+ )
1288
+ return;
1289
+ // `show`: from another view, or from under a utility screen (choosing a view closes it).
1290
+ if (hints.show && (screen?.plugin !== plugin || utility)) {
1291
+ const block =
1292
+ state.screens &&
1293
+ [
1294
+ ...state.screens.root,
1295
+ ...state.screens.sections.flatMap((section) => section.blocks),
1296
+ ].find((each) => each.plugin === plugin);
1297
+ if (!block) return;
1298
+ const first = item?.split('/')[0];
1299
+ if (block.screen.children?.some((child) => child.id === first))
1300
+ throw new TypeError(
1301
+ `workspace plugin ${plugin}: item ${item} starts with ${block.screen.id}'s child screen ${first}: its URL would name that screen`,
1302
+ );
1303
+ // A node where it is a view: this one, else the root, else the first that has it; none, nothing shown.
1304
+ const resolved = state.nodes?.resolved;
1305
+ const has = (id: string) => resolved?.[id]?.views.includes(plugin) === true;
1306
+ const where = !resolved
1307
+ ? node
1308
+ : has(node)
1309
+ ? node
1310
+ : has('root')
1311
+ ? 'root'
1312
+ : Object.keys(resolved).find(has);
1313
+ if (where === undefined) return;
1314
+ return shell.setScreen({ plugin, id: block.screen.id }, where, item);
1315
+ }
1316
+ if (screen?.plugin !== plugin || !path.length || utility) return;
1317
+ const first = item?.split('/')[0];
1318
+ if (path.at(-1)!.children?.some((child) => child.id === first)) {
1319
+ throw new TypeError(
1320
+ `workspace plugin ${plugin}: item ${item} starts with ${screen.id}'s child screen ${first}: its URL would name that screen`,
1321
+ );
1322
+ }
1323
+ if (
1324
+ (hints.beside || hints.desk || hints.reuse) &&
1325
+ request(
1326
+ {
1327
+ node,
1328
+ screen: { plugin: screen.plugin, id: screen.id },
1329
+ ...(item !== undefined && { item }),
1330
+ },
1331
+ hints,
1332
+ )
1333
+ )
1334
+ return;
1335
+ // Another item of the screen shown keeps its screen state (research-090).
1336
+ shell.setScreen(screen, node, item, state.screenState);
1337
+ },
1338
+ /** Shows node `id` in a new history entry: its home view (AD-11, at `/<slug>/<id>/`; also from another view of the
1339
+ * node shown), else the chosen view kept when it is shown there, else the node's first view, else none; the chosen
1340
+ * view (or none) kept while the tree's resolution is not in. */
1341
+ setNode(id: string) {
1342
+ /** Whether node `id` shows the screen shown now (its root screen's block, research-067): choosing it keeps the
1343
+ * screen; every screen before the tree loads. */
1344
+ const keepsScreen = (id: string) => {
1345
+ const views = state.nodes?.resolved?.[id]?.views;
1346
+ if (!views) return true;
1347
+ const root = state.path[0]?.id;
1348
+ return (
1349
+ state.screen !== undefined &&
1350
+ root !== undefined &&
1351
+ showsBlock(
1352
+ state.nodes?.nodes.find((node) => node.id === id),
1353
+ `${state.screen.plugin}/${root}`,
1354
+ views,
1355
+ state.screens ? chosenBlocks(blocksOf(state.screens)) : [],
1356
+ )
1357
+ );
1358
+ };
1359
+ const slug = state.current?.slug;
1360
+ if (slug === undefined || unplaced()) return;
1361
+ // A ⌘- or ⌥-click (not ⌘K's placements): the view choosing the node shows (its home or first view, else the screen
1362
+ // kept there), opened beside before anything here changes: the focused window keeps the focus, its view, the URL
1363
+ // and the history (research-048). None to name yet (the tree not loaded): nothing.
1364
+ if (beside && !placed) {
1365
+ const block = state.screens ? openingBlockOf(state.screens, state.nodes, id) : undefined;
1366
+ const kept =
1367
+ homeOf(state.nodes, id) === undefined && state.screen !== undefined && keepsScreen(id)
1368
+ ? state.screen
1369
+ : undefined;
1370
+ const screen = kept ?? (block && { plugin: block.plugin, id: block.screen.id });
1371
+ if (!screen || placeBeside({ node: id, screen: { plugin: screen.plugin, id: screen.id } }))
1372
+ return;
1373
+ }
1374
+ bare = false;
1375
+ const home = homeOf(state.nodes, id);
1376
+ const chosen = state.path.length
1377
+ ? state.path.map((node) => node.id).join('/')
1378
+ : screenInUrl(slug);
1379
+ const opening =
1380
+ home !== undefined && state.screens ? openingOf(state.screens, state.nodes, id) : undefined;
1381
+ // The node shown: nothing to do without a home, or on what its row opens (but to clear an item).
1382
+ if (
1383
+ id === state.node &&
1384
+ state.item === undefined &&
1385
+ (home === undefined || (opening !== undefined && chosen === opening))
1386
+ )
1387
+ return void (state.utility && update({ utility: undefined }));
1388
+ const keep = home === undefined && keepsScreen(id);
1389
+ const screen = keep
1390
+ ? chosen
1391
+ : (opening ?? (state.screens ? openingOf(state.screens, state.nodes, id) : undefined));
1392
+ const atHome =
1393
+ screen !== undefined &&
1394
+ state.screens !== undefined &&
1395
+ state.screens !== null &&
1396
+ screen === homeRootOf(state.screens, state.nodes, id);
1397
+ // Its home is the node's URL; the home's tree not loaded yet: the bare URL too, the home taken once it is.
1398
+ history.pushState(
1399
+ null,
1400
+ '',
1401
+ urlOf(
1402
+ slug,
1403
+ id,
1404
+ atHome || (home !== undefined && screen === undefined) ? undefined : screen,
1405
+ ),
1406
+ );
1407
+ if (keep) return void update({ node: id, item: undefined, utility: undefined });
1408
+ wanted = screen;
1409
+ choosing = false;
1410
+ update({ node: id, screen: undefined, utility: undefined });
1411
+ },
1412
+ /** Shows (or, `undefined`, closes) a utility screen; on another node, that node is selected too (a new history
1413
+ * entry), its home or first view behind the utility screen, as `setNode` without the view shown. */
1414
+ setUtility(utility: ShellState['utility']) {
1415
+ bare = false;
1416
+ const slug = state.current?.slug;
1417
+ if (!utility || utility.node === state.node || slug === undefined)
1418
+ return void update({ utility });
1419
+ history.pushState(null, '', urlOf(slug, utility.node));
1420
+ wanted = undefined;
1421
+ choosing = false;
1422
+ pushedFor = utility;
1423
+ update({ node: utility.node, screen: undefined, utility });
1424
+ },
1425
+ /** Closes the utility screen as the browser's Back would: shown on another node (`setUtility` pushed an entry),
1426
+ * back off that entry to the node it came from; else in place, the view under it. */
1427
+ closeUtility() {
1428
+ if (!state.utility) return;
1429
+ if (state.utility === pushedFor) history.back();
1430
+ else shell.setUtility(undefined);
1431
+ },
1432
+ /** Creates a node under `parent` in the current workspace (AD-23); rejects with the host's message. */
1433
+ createNode: (parent: string, title: string) =>
1434
+ changeNodes('POST', '', { parent, title }) as Promise<{ id: string; revision: number }>,
1435
+ /** Renames, moves (`dryRun`: only says which plugins it would stop being active, `lost`), archives, unarchives,
1436
+ * shows or hides a view on, or sets the home view of (`null`: automatic) node `id` of the current workspace,
1437
+ * places a view (`place`) or changes root's sections (`section`, research-067); rejects with the host's message. */
1438
+ changeNode: (
1439
+ id: string,
1440
+ change:
1441
+ | { title: string }
1442
+ | { parent: string; dryRun?: boolean }
1443
+ | { before: string | null }
1444
+ | { archived: boolean }
1445
+ | { view: { plugin: string; shown: boolean; block?: string } }
1446
+ | { home: string | null }
1447
+ | {
1448
+ place: {
1449
+ block: string;
1450
+ before?: string | null;
1451
+ section?: string | null;
1452
+ from?: string;
1453
+ };
1454
+ }
1455
+ | {
1456
+ section:
1457
+ | { title: string }
1458
+ | { id: string; title: string }
1459
+ | { id: string; before: string | null }
1460
+ | { id: string; removed: true };
1461
+ },
1462
+ ) =>
1463
+ changeNodes('PATCH', `/${encodeURIComponent(id)}`, change) as Promise<{
1464
+ revision: number;
1465
+ lost?: string[];
1466
+ id?: string;
1467
+ }>,
1468
+ /** A window manager's focus change (or a window closed): `view`, the focused window's, becomes the current view, its
1469
+ * URL in place. A node alone (an empty window) stays so: its home is not opened in it. */
1470
+ show(view: View) {
1471
+ const slug = state.current?.slug;
1472
+ if (slug === undefined) return;
1473
+ wanted = undefined;
1474
+ choosing = false;
1475
+ bare = !view.screen && !view.utility;
1476
+ const path = view.screen && state.screens ? pathTo(state.screens, view.screen) : [];
1477
+ history.replaceState(
1478
+ null,
1479
+ '',
1480
+ urlOf(
1481
+ slug,
1482
+ view.node,
1483
+ path.length
1484
+ ? urlPathOf(state.screens, state.nodes, view.node, view.screen?.plugin, path, view.item)
1485
+ : undefined,
1486
+ ),
1487
+ );
1488
+ update({
1489
+ node: view.node,
1490
+ screen: view.screen,
1491
+ item: view.screen ? view.item : undefined,
1492
+ utility: view.utility,
1493
+ screenState: screenStateOf(view.screenState),
1494
+ });
1495
+ },
1496
+ /** Research-090 (./shell.d.ts). */
1497
+ setScreenState(
1498
+ window: string,
1499
+ next: Record<string, string> | undefined,
1500
+ options: { push?: boolean } = {},
1501
+ ) {
1502
+ const screenState = screenStateOf(next);
1503
+ const at = usable();
1504
+ // Another of its windows than the focused one: its view, kept by its manager. A window it does not list (the
1505
+ // phone's one window, the shell's own while a manager is installed) shows the current view.
1506
+ if (at) {
1507
+ try {
1508
+ const view =
1509
+ window === at.wm.focused()
1510
+ ? undefined
1511
+ : at.wm.list().find((each) => each.id === window)?.view;
1512
+ if (view) {
1513
+ if (!sameState(screenStateOf(view.screenState), screenState))
1514
+ at.wm.open(withState(view, screenState), { into: window });
1515
+ return;
1516
+ }
1517
+ } catch (error) {
1518
+ return failed(at.ref, error);
1519
+ }
1520
+ }
1521
+ if (sameState(state.screenState, screenState) || !state.current) return;
1522
+ if (options.push && slugInUrl() === state.current.slug)
1523
+ history.pushState(null, '', `${location.pathname}${searchOf(screenState)}`);
1524
+ update({ screenState });
1525
+ },
1526
+ setSidebarHidden(hidden: boolean) {
1527
+ if (state.sidebarHidden === hidden) return;
1528
+ try {
1529
+ if (hidden) localStorage.setItem(sidebarHiddenKey, '1');
1530
+ else localStorage.removeItem(sidebarHiddenKey);
1531
+ } catch {
1532
+ /* kept for this page */
1533
+ }
1534
+ state = { ...state, sidebarHidden: hidden };
1535
+ for (const listener of listeners) listener();
1536
+ },
1537
+ subscribe(listener: () => void) {
1538
+ listeners.add(listener);
1539
+ return () => {
1540
+ listeners.delete(listener);
1541
+ };
1542
+ },
1543
+ /** A ⌘-click (Ctrl-click) on the page: the view change it causes, in this task, opens in a new window. */
1544
+ besideNext() {
1545
+ beside = true;
1546
+ clearTimeout(besideTimer);
1547
+ besideTimer = setTimeout(() => {
1548
+ beside = false;
1549
+ newDesk = false;
1550
+ shape = undefined;
1551
+ placed = false;
1552
+ });
1553
+ },
1554
+ /** ⌘K's ↵ with a modifier (research-034): the view change it causes, in this task, opens in a new window beside, on a
1555
+ * new desk, floating, or maximized (a manager without these: beside; none: here). */
1556
+ placeNext(where: 'beside' | 'desk' | 'float' | 'max') {
1557
+ if (where === 'desk') shell.deskNext();
1558
+ else shell.besideNext();
1559
+ placed = true;
1560
+ if (where === 'float' || where === 'max') shape = where;
1561
+ },
1562
+ /** An ⌥-click in the sidebar: the view change it causes, in this task, opens on a new desk (beside, for a manager
1563
+ * without desks). */
1564
+ deskNext() {
1565
+ shell.besideNext();
1566
+ newDesk = true;
1567
+ },
1568
+ /** A window manager came (a new `stage` entry registered: installed, enabled, or reloaded under the page): it gets
1569
+ * the current view, or, without one, the shell takes its focused window's. One set aside on this page gets its
1570
+ * chance again (a reload may have mended it), on this browser's stored choice. */
1571
+ registerNavigator(navigator: { id: string; label: string }) {
1572
+ const entry = { id: navigator.id, label: navigator.label };
1573
+ registered.push(entry);
1574
+ const publish = () => {
1575
+ // One per id, the latest registration's: `_host`'s and a workspace's navigator may share an id (research-046).
1576
+ const byId = new Map(registered.map((each) => [each.id, each]));
1577
+ state = { ...state, navigators: [...byId.values()] };
1578
+ for (const listener of listeners) listener();
1579
+ looksAgain();
1580
+ };
1581
+ publish();
1582
+ return () => {
1583
+ const at = registered.indexOf(entry);
1584
+ if (at < 0) return;
1585
+ registered.splice(at, 1);
1586
+ publish();
1587
+ };
1588
+ },
1589
+ /** The shell's own: what this page has changed (a pack, a window manager came or went): the looks again. */
1590
+ looksAgain() {
1591
+ looksAgain();
1592
+ },
1593
+ navigatorShown(id: string) {
1594
+ return navigatorShown(state, id);
1595
+ },
1596
+ /** The shell's own: whether a plugin fills the `sidebar` slot (`ShellState.sidebarFilled`). */
1597
+ sidebarFilled(filled: boolean) {
1598
+ if (state.sidebarFilled === filled) return;
1599
+ state = { ...state, sidebarFilled: filled };
1600
+ for (const listener of listeners) listener();
1601
+ },
1602
+ managerChanged() {
1603
+ routed = undefined;
1604
+ if (state.managerFailed) {
1605
+ pageManager.write(undefined);
1606
+ state = { ...state, managerFailed: undefined, managerChoice: undefined };
1607
+ }
1608
+ route(true);
1609
+ for (const listener of listeners) listener();
1610
+ },
1611
+ /** The window manager's `stage` entry crashed: set aside (C6), this page on none, the shell's one window. */
1612
+ managerCrashed(plugin: string | undefined, error: unknown) {
1613
+ if (state.managerFailed) return;
1614
+ setAside({
1615
+ ...(plugin !== undefined && { plugin }),
1616
+ message: error instanceof Error ? error.message : String(error),
1617
+ });
1618
+ for (const listener of listeners) listener();
1619
+ },
1620
+ /** The user's window manager for the current workspace (WM5, its Mine's `windowManager`): a plugin key, `null` for
1621
+ * none, `undefined` for the workspace's own choice. Switching is a small reboot (C4): the manager now active gets
1622
+ * the current view (the focused window's), nothing else. */
1623
+ chooseManager(choice: string | null | undefined) {
1624
+ // Any choice ends a failure's notice (`setAside` sets it again after).
1625
+ pageManager.write(undefined);
1626
+ const slug = state.current?.slug;
1627
+ if (slug !== undefined)
1628
+ void client.setMineFields(slug, {
1629
+ ...client.mineOf(slug),
1630
+ windowManager: choice === null ? 'none' : choice,
1631
+ });
1632
+ routed = undefined;
1633
+ state = { ...state, managerChoice: undefined, managerFailed: undefined };
1634
+ route(true);
1635
+ for (const listener of listeners) listener();
1636
+ },
1637
+ /** Follows an item link of the window `from` shows (research-048): `view` is that window's view with the item. A
1638
+ * plain click shows it there, a history entry (`reuse`: in another window of its screen when there is one); ⌘
1639
+ * (Ctrl) or middle beside that window, ⌥ on a new desk, the focused view and the URL kept; without a manager, a
1640
+ * modified click does nothing. */
1641
+ followItem(
1642
+ view: View,
1643
+ event: FollowEvent,
1644
+ { from, reuse }: { from?: string; reuse?: boolean } = {},
1645
+ ) {
1646
+ const gesture = gestureOf(event);
1647
+ if (gesture === undefined || !view.screen || (gesture !== 'here' && !usable())) return;
1648
+ if (gesture === 'here') {
1649
+ if (reuse && request(view, { reuse: true }, from)) return;
1650
+ // An item of the window's own screen keeps its screen state (research-090).
1651
+ const kept =
1652
+ !state.utility && placeOf(state) === placeOf(view) ? state.screenState : undefined;
1653
+ return shell.setScreen(view.screen, view.node, view.item, view.screenState ?? kept);
1654
+ }
1655
+ request(view, gesture === 'desk' ? { desk: true } : { beside: true }, from);
1656
+ },
1657
+ /** Follows a link to `view` of workspace `slug` (research-048): the current one, `follow`; another, entered first,
1658
+ * then `view` shown there (a plain click), or opened beside its focused window or on a new desk once routed (a
1659
+ * modified one; nothing without a window manager, not even the workspace change). */
1660
+ openIn(slug: string, view: View, event: FollowEvent) {
1661
+ const gesture = gestureOf(event);
1662
+ if (gesture === undefined) return;
1663
+ if (state.current?.slug === slug) return shell.follow(view, event);
1664
+ if (gesture !== 'here') {
1665
+ if (!usable()) return;
1666
+ pending = { slug, view, desk: gesture === 'desk' };
1667
+ return shell.setCurrent(slug);
1668
+ }
1669
+ shell.setCurrent(slug);
1670
+ if (view.screen) shell.setScreen(view.screen, view.node, view.item, view.screenState);
1671
+ else shell.setNode(view.node);
1672
+ },
1673
+ /** Whether a window manager is active (a modified click has somewhere to go). */
1674
+ managed: () => usable() !== undefined,
1675
+ /** Follows a link to `view` as `event` asks (research-048, ./shell.d.ts). */
1676
+ follow(view: View, event: FollowEvent) {
1677
+ const gesture = gestureOf(event);
1678
+ if (gesture === undefined || (gesture !== 'here' && !usable())) return;
1679
+ if (gesture === 'desk') shell.deskNext();
1680
+ else if (gesture === 'beside') shell.besideNext();
1681
+ if (view.screen) shell.setScreen(view.screen, view.node, view.item, view.screenState);
1682
+ else shell.setNode(view.node);
1683
+ },
1684
+ /** The URL of `view` in the current workspace (a link's `href`), as `setScreen` and `setNode` write it. */
1685
+ hrefOf(view: View): string | undefined {
1686
+ const slug = state.current?.slug;
1687
+ if (slug === undefined || (view.screen && !state.screens)) return undefined;
1688
+ if (!view.screen || !state.screens) return urlOf(slug, view.node);
1689
+ const path = pathTo(state.screens, view.screen);
1690
+ if (!path.length) return undefined;
1691
+ return `${urlOf(
1692
+ slug,
1693
+ view.node,
1694
+ urlPathOf(state.screens, state.nodes, view.node, view.screen.plugin, path, view.item),
1695
+ )}${searchOf(screenStateOf(view.screenState))}`;
1696
+ },
1697
+ /** The view a page path names (`/<slug>/<node>/<screen path>/<item path>`, the URL's rules), when it names the
1698
+ * current workspace and a screen its tree has, or a node alone (`/<slug>/<node>/`); none otherwise (another
1699
+ * workspace, a node the node tree lacks, an unknown screen, a tree not loaded). */
1700
+ viewAt(pathname: string): View | undefined {
1701
+ const slug = state.current?.slug;
1702
+ const place = slug === undefined ? undefined : placeInUrl(slug, pathname);
1703
+ if (!place || !state.screens || !state.nodes?.nodes.some((node) => node.id === place.node))
1704
+ return undefined;
1705
+ if (place.screen === undefined) return { node: place.node };
1706
+ const at = screenAt(state.screens, place.screen, isItemSegment);
1707
+ return (
1708
+ at && {
1709
+ node: place.node,
1710
+ screen: { plugin: at.plugin, id: at.id },
1711
+ ...(at.item !== undefined && { item: at.item }),
1712
+ }
1713
+ );
1714
+ },
1715
+ /** The window shortcuts (research-018 C5): a manager registers its keys, a plugin declares its pointer gestures and
1716
+ * the keys its screen handles itself; the help lists them. */
1717
+ shortcuts: {
1718
+ register: shortcuts.register,
1719
+ list: shortcuts.list,
1720
+ gesture: shortcuts.gesture,
1721
+ gestures: shortcuts.gestures,
1722
+ declare: shortcuts.declare,
1723
+ declared: shortcuts.declared,
1724
+ subscribe: shortcuts.subscribe,
1725
+ },
1726
+ /** The current workspace's node tree changed (a `nodes` status event for `slug`, at `revision`; any slug,
1727
+ * `undefined`): fetched again, unless the tree at `revision` was fetched already or is on its way. */
1728
+ nodesChanged(slug?: string, revision?: number) {
1729
+ if (slug === undefined || slug === state.current?.slug) void loadNodes(revision);
1730
+ },
1731
+ /** Back/forward: the URL names the workspace, the node, the screen and its item again (a screen only under the
1732
+ * workspace shown: not under an unknown slug's fallback). */
1733
+ followUrl() {
1734
+ bare = false;
1735
+ chosen = slugInUrl();
1736
+ const current = state.workspaces.find((w) => w.slug === chosen) ?? state.workspaces[0];
1737
+ wanted = screenInUrl(current?.slug);
1738
+ urlNamed = namesPlace(current?.slug);
1739
+ choosing = false;
1740
+ update({
1741
+ screen: undefined,
1742
+ node: placeInUrl(current?.slug)?.node ?? 'root',
1743
+ utility: undefined,
1744
+ screenState: stateInUrl(current?.slug),
1745
+ });
1746
+ },
1747
+ /** Drops any refresh in flight and closes the workspace's plugins (the plugin is disposed). */
1748
+ stop() {
1749
+ latest++;
1750
+ latestScreens++;
1751
+ latestEntries++;
1752
+ nodesEpoch++;
1753
+ ended = true;
1754
+ for (const stopped of waitingChanges) stopped(stoppedError());
1755
+ unmine();
1756
+ void entries.open(undefined);
1757
+ },
1758
+ /** A failed fetch keeps what was shown (the host restarting, a session expiring: the kernel says so).
1759
+ * Only the latest call applies: an older answer arriving late, or one after `stop()`, is dropped.
1760
+ * The screens reload too (already on their way when the current workspace changed), and after an
1761
+ * answered list the browser entries: a plugin enabled or rebuilt since, or a list that failed, loads. */
1762
+ async refresh() {
1763
+ const run = ++latest;
1764
+ // A tree changed while the stream was down, or a workspace restarted with a repaired one: fetched at once, in
1765
+ // the turn of the event, which the `nodes` service's load joins (bridge#169); a workspace change drops it.
1766
+ void loadNodes();
1767
+ const [list, status] = await Promise.allSettled([
1768
+ getJson<{ workspaces: ShellState['workspaces'] }>('/_bridge/workspaces'),
1769
+ getJson<Status>('/_bridge/status'),
1770
+ ]);
1771
+ if (run !== latest) return;
1772
+ if (list.status === 'fulfilled') {
1773
+ listed = list.value.workspaces;
1774
+ if (!carried && listed.length > 0) {
1775
+ carried = true;
1776
+ void carryOver(
1777
+ client,
1778
+ listed.map((w) => w.slug),
1779
+ );
1780
+ }
1781
+ }
1782
+ const moved = update({
1783
+ ...(list.status === 'fulfilled' && { workspaces: withMines(listed) }),
1784
+ ...(status.status === 'fulfilled' && {
1785
+ status: statusOf(status.value),
1786
+ compositions: Object.fromEntries(
1787
+ status.value.workspaces.map(({ slug, plugins }) => [
1788
+ slug,
1789
+ plugins.map(({ id, state }) => `${id}:${state}`).join(' '),
1790
+ ]),
1791
+ ),
1792
+ }),
1793
+ });
1794
+ if (moved) return;
1795
+ void loadScreens();
1796
+ if (list.status === 'fulfilled') void loadEntries();
1797
+ },
1798
+ };
1799
+ return shell;
1800
+ }