@bridgebrew/shell 0.0.0-stage → 0.0.2

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,2025 @@
1
+ // The shell's frame (E8, research-018 F1): fills `root` and declares `rail`, `sidebar`, `main`, and `overlay`. Owner,
2
+ // 11 October 2026: the shell defines the spaces, the window manager the windows and their design. So the shell paints
3
+ // the canvas (the sidebar's colour, or the current workspace's paint: ./look.ts) the rail and the sidebar sit on, puts
4
+ // the theme controls at the bottom of the sidebar column, and leaves the stage beside it to `main`: a window manager's
5
+ // windows, framed and spaced in its design around the parts the shell gives (`renderWindow`: each window's
6
+ // breadcrumb, its screen); without one, the current view shows flat in the stage, the minimum frame Bridge had before
7
+ // windows (`flatFrame`: lines between the rail, the sidebar and the stage, a 44px top bar with the breadcrumb). It mounts the kit's
8
+ // providers and owns the `sidebar` slot's width (resizable, kept per browser), so a replacement sidebar is resizable
9
+ // too. It also provides `shell`, the small state the rail, the sidebar, and the window's bar share: the workspaces, the
10
+ // current one, the host status, and the current workspace's screens, fetched on load, on window focus, and
11
+ // on each host status event (E4), and the current workspace's node tree (again on its `nodes` events); the
12
+ // screens also when the current workspace changes, when the kernel loads
13
+ // that workspace's browser entries too (E10). It toasts the host's failures and removals (./notifications.ts). It fills
14
+ // `main` by default with the `stage` (research-018 WM2): a window manager (`windows`, a `_host` plugin) lays out
15
+ // windows there, each the shell's parts in the manager's frame; the shell routes each
16
+ // view it shows to that manager's `windowManager` (P8 first: a view a window shows focuses it; a ⌘-click opens it
17
+ // beside), and shows its own flat window when there is none, or it failed (C6, toasted with the way out). A window's
18
+ // screen is the `screen` slot under the screen's plugin key, which that plugin fills with the screen's id, the node
19
+ // shown, and the item it opened (`ctx.screen.open`, the kernel's `screenRequests`). The focused window's view is the
20
+ // current view: the sidebar, the URL, `openItem` follow it. A screen's URL is the node, then its path in its plugin's
21
+ // tree, like the breadcrumb, then its item: `/<slug>/<node>/<root-id>/<id>/…/<item>`; the node's home view (AD-11) is
22
+ // the node alone, `/<slug>/<node>/`, its breadcrumb the node's. A utility screen (Settings,
23
+ // `shell.setUtility`) shows in `main` over the chosen view, its breadcrumb its node's then its title. A window showing an
24
+ // item ends its breadcrumb with the item's title, as its plugin gives it (research-018 slice 6e).
25
+ // Research-028: the workspace shown proposes its style, icons, theme pair and window manager (its look), applied where
26
+ // this browser chose none. Research-018 slice 3c: the window manager is this browser's choice (the theme menu: the installed ones, or "None",
27
+ // the shell's one window; one that fails puts this page on none, its toast's "Choose" opening that menu); a
28
+ // manager registers its keys through `shell.shortcuts` (./shortcuts.ts: Bridge's own keys refused), the shell runs them
29
+ // on `keydown` and lists them in one help (`?`, or the menu), with the keys a screen declares (it handles them itself,
30
+ // only while its window is the one the user works in: the `screen` slot's `focused`, from `renderWindow`'s `active`); a link of this origin naming the current workspace shows
31
+ // its view without a page load (a ⌘-click or a middle click: in a new window); an empty window offers the node's views.
32
+ // The contract (`shell`, the slots) is declared once in ./shell.d.ts; the state behind `shell` is in
33
+ // ./shell-state.ts, the theme controls in ./theme-controls.tsx.
34
+ // In the desktop app, while a remote page shows under this one, its toasts go to the app's toast view (window-layout.md),
35
+ // which is this page again, drawing those toasts only (`ToastView`).
36
+ import * as React from 'react';
37
+ import {
38
+ Breadcrumb,
39
+ Button,
40
+ Dialog,
41
+ DialogBody,
42
+ DialogContent,
43
+ DialogDescription,
44
+ DialogHeader,
45
+ DialogTitle,
46
+ Icon,
47
+ SIDEBAR_DEFAULT_WIDTH,
48
+ SidebarResizeHandle,
49
+ ToastProvider,
50
+ FollowProvider,
51
+ PackThemesProvider,
52
+ ViewScopeProvider,
53
+ gestureOf,
54
+ type FollowEvent,
55
+ type Follow,
56
+ CommandHostProvider,
57
+ ToastStack,
58
+ TooltipProvider,
59
+ DEFAULT_ICON_SET,
60
+ DEFAULT_KIT,
61
+ clampSidebarWidth,
62
+ everywhereOf,
63
+ getClientAppearance,
64
+ getIconSets,
65
+ getRenderings,
66
+ getColourMode,
67
+ type Command,
68
+ mineImageOf,
69
+ useWallpaperTheme,
70
+ mineOf,
71
+ setMineFields,
72
+ setMode,
73
+ setWorkspaceAppearance,
74
+ subscribeClientAppearance,
75
+ subscribeIconSets,
76
+ subscribeRenderings,
77
+ themeOfMode,
78
+ useColourMode,
79
+ useThemeOfMode,
80
+ useRendering,
81
+ useToast,
82
+ type ToastSink,
83
+ usePackThemes,
84
+ modalOpen,
85
+ isRecord,
86
+ readJson,
87
+ } from '@bridge/ui';
88
+ import type { Context } from 'cordis';
89
+ import type {} from '@bridge/ui-renderer/client';
90
+ import { notifier, toastOf, type Fix, type Notice } from './notifications.ts';
91
+ import {
92
+ ActionConfirm,
93
+ ErrorsModal,
94
+ errorsSignal,
95
+ fixLabel,
96
+ runFix,
97
+ type ErrorsSignal,
98
+ } from './errors.tsx';
99
+ import { createNodeActions } from './node-actions.ts';
100
+ import { RestartScreen } from './restart-screen.tsx';
101
+ import { Approvals } from './approvals.tsx';
102
+ import type { BridgeDesktop, DesktopToast, ShellViewScope, ViewState } from './shell.d.ts';
103
+ import {
104
+ blocksOn,
105
+ createReview,
106
+ createShell,
107
+ followStatus,
108
+ pathTo,
109
+ screenInUrl,
110
+ showStatus,
111
+ viewOf,
112
+ screenStateOf,
113
+ type ManagerRef,
114
+ type Review,
115
+ type Shell,
116
+ type View,
117
+ } from './shell-state.ts';
118
+ import {
119
+ createShortcuts,
120
+ displayGesture,
121
+ displayKeys,
122
+ isEditable,
123
+ guessLayout,
124
+ learnLayout,
125
+ type KeyLayout,
126
+ } from './shortcuts.ts';
127
+ import './look.css';
128
+ import { useWallpaperInk } from './wallpaper-ink.ts';
129
+ import './window.css';
130
+ import { canvasOf, inkOf, lookStyle, wallpaperOf, wallpaperUrl, managerOf } from './look.ts';
131
+ import {
132
+ defaultTransition,
133
+ directionOf,
134
+ durations,
135
+ ownTransition,
136
+ readDuration,
137
+ readTransition,
138
+ transitionTo,
139
+ type Transition,
140
+ } from './transition.ts';
141
+ import { SidebarToggle, ThemeControls, type ManagerOption } from './theme-controls.tsx';
142
+ import {
143
+ MobileFrame,
144
+ mobileFrame,
145
+ mobileOwner,
146
+ setSidebarItems,
147
+ transitions,
148
+ useMobile,
149
+ } from './mobile.tsx';
150
+
151
+ export const name = 'shell';
152
+ export const inject = ['slots', 'workspaceEntries', 'hostStatus', 'screenRequests', 'sidebarItems'];
153
+
154
+ const widthKey = 'bridge.sidebar.width';
155
+
156
+ /** The sidebar's width: stored per browser (anything but a number of pixels ignored; a storage failure
157
+ * keeps it for this page only), clamped on load and again when the window resizes. */
158
+ function useSidebarWidth() {
159
+ const [width, setWidth] = React.useState(() => {
160
+ let stored: string | null = null;
161
+ try {
162
+ stored = localStorage.getItem(widthKey);
163
+ } catch {
164
+ /* the default */
165
+ }
166
+ return clampSidebarWidth(
167
+ stored !== null && /^\d+(\.\d+)?$/.test(stored) ? Number(stored) : SIDEBAR_DEFAULT_WIDTH,
168
+ );
169
+ });
170
+ React.useEffect(() => {
171
+ try {
172
+ localStorage.setItem(widthKey, String(width));
173
+ } catch {
174
+ /* kept in memory */
175
+ }
176
+ }, [width]);
177
+ React.useEffect(() => {
178
+ const clamp = () => setWidth((current) => clampSidebarWidth(current));
179
+ window.addEventListener('resize', clamp);
180
+ return () => window.removeEventListener('resize', clamp);
181
+ }, []);
182
+ return [width, setWidth] as const;
183
+ }
184
+
185
+ type RenderScreen = (
186
+ key: 'screen' | 'mobileScreen',
187
+ owner: {
188
+ screen: string;
189
+ node: string;
190
+ readOnly: boolean;
191
+ item?: string;
192
+ focused?: boolean;
193
+ others?: Others;
194
+ screenState?: Record<string, string>;
195
+ setScreenState?: (
196
+ next: Record<string, string> | undefined,
197
+ options?: { push?: boolean },
198
+ ) => void;
199
+ },
200
+ opts: { entryKey: string; fallback: React.ReactNode },
201
+ ) => React.ReactNode;
202
+ type Others = readonly { item?: string; kind?: string }[];
203
+ /** ./shell.d.ts `WindowParts`, `WindowOptions`. */
204
+ type Parts = {
205
+ window: {
206
+ 'data-slot': 'shell-window';
207
+ 'data-window': string;
208
+ 'data-focused'?: true;
209
+ 'data-active'?: true;
210
+ 'data-state'?: ViewState;
211
+ role: 'region';
212
+ 'aria-label': string;
213
+ };
214
+ bar: { 'data-slot': 'shell-window-bar' };
215
+ crumbs: React.ReactNode;
216
+ body: React.ReactNode;
217
+ };
218
+ type Options = {
219
+ focused: boolean;
220
+ active?: boolean;
221
+ choices?: boolean;
222
+ others?: Others;
223
+ frame?: (parts: Parts) => React.ReactNode;
224
+ };
225
+ type StageOwner = {
226
+ renderWindow: (id: string, view: View, options: Options) => React.ReactNode;
227
+ view: View;
228
+ workspace: string | undefined;
229
+ };
230
+
231
+ /** The shell's own frame for a window (no window manager, or one that draws none): flat in the stage, as Bridge was
232
+ * before windows (main's `shell-top-bar`): a line on its left against the sidebar, a 44px top bar holding the
233
+ * breadcrumb over a line, the screen under it scrolling alone; no corner, no shadow (./window.css adds the line between
234
+ * the rail and the sidebar). */
235
+ export const flatFrame = ({ window, bar, crumbs, body }: Parts) => (
236
+ <div
237
+ {...window}
238
+ data-flat=""
239
+ className="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden border-l border-border bg-(--shell-window)"
240
+ >
241
+ <header {...bar} className="flex h-11 shrink-0 items-center gap-4 border-b border-border px-4">
242
+ {crumbs}
243
+ </header>
244
+ {body}
245
+ </div>
246
+ );
247
+
248
+ /** The desktop app draws no title bar (research-111 slice 6): the window's own buttons sit over the page,
249
+ * in its corner on macOS, at the stage's end on Linux. The page learns where from `env(titlebar-area-*)` (the Window
250
+ * Controls Overlay; none in a browser, so every inset is 0). The stage always starts under the bar (`--shell-top`); the
251
+ * rail and the sidebar too when the buttons are on the left (`--shell-top-left`: the bar's height when
252
+ * `titlebar-area-x` is past 0, else 0, as `min(height, x × 1000)`), so nothing sits beside the traffic lights. */
253
+ const titleBarInsets = {
254
+ '--shell-top': 'env(titlebar-area-height, 0px)',
255
+ '--shell-top-left':
256
+ 'max(0px, min(env(titlebar-area-height, 0px), calc(env(titlebar-area-x, 0px) * 1000)))',
257
+ };
258
+
259
+ /** The room a column leaves under the bar: canvas only, it drags the window, and a double click maximizes it. */
260
+ const TitleBarBand = ({ height }: { height: 'h-(--shell-top)' | 'h-(--shell-top-left)' }) => (
261
+ <div
262
+ data-slot="shell-titlebar"
263
+ aria-hidden="true"
264
+ className={`absolute inset-x-0 top-0 [-webkit-app-region:drag] ${height}`}
265
+ />
266
+ );
267
+
268
+ /** A CSS colour's red, green and blue as the page draws it (a canvas reads any CSS colour), for the ink a painted
269
+ * canvas takes (./look.ts `inkOf`); kept by colour. */
270
+ const rgbs = new Map<string, [number, number, number] | undefined>();
271
+ const rgbOf = (given: string) => {
272
+ // A theme's colour (`var(--accent)`) as the page's theme has it now: never kept, the theme may change.
273
+ const token = /^var\((--[a-z0-9-]+)\)$/.exec(given)?.[1];
274
+ const colour = token
275
+ ? getComputedStyle(document.documentElement).getPropertyValue(token).trim()
276
+ : given;
277
+ if (!rgbs.has(colour)) {
278
+ const context = document.createElement('canvas').getContext('2d', { willReadFrequently: true });
279
+ let rgb: [number, number, number] | undefined;
280
+ if (context) {
281
+ context.fillStyle = colour;
282
+ context.fillRect(0, 0, 1, 1);
283
+ const [r, g, b] = context.getImageData(0, 0, 1, 1).data;
284
+ rgb = [r!, g!, b!];
285
+ }
286
+ rgbs.set(colour, rgb);
287
+ }
288
+ return rgbs.get(colour);
289
+ };
290
+
291
+ /** A request without data, for components the shell mounts apart: open the help, open the theme menu. */
292
+ function signal() {
293
+ const listeners = new Set<() => void>();
294
+ return {
295
+ emit() {
296
+ for (const listener of listeners) listener();
297
+ },
298
+ subscribe(listener: () => void) {
299
+ listeners.add(listener);
300
+ return () => {
301
+ listeners.delete(listener);
302
+ };
303
+ },
304
+ };
305
+ }
306
+ type Signal = ReturnType<typeof signal>;
307
+ /** The shell's `themeMenu` setting (./package.json), followed live. */
308
+ type ThemeMenu = { get(): boolean; subscribe(listener: () => void): () => void };
309
+ /** Whether the page runs in Bridge's Electron app (⌘ works for ⌥ there, research-018 K3). */
310
+ const inApp = () => typeof navigator !== 'undefined' && /\bElectron\//.test(navigator.userAgent);
311
+ /** A remote Bridge's page in the desktop app (its session's user agent says so, SPEC multi-instance CAP-10): the app's
312
+ * home rail is drawn over its left edge, so the page leaves the rail's room and draws none. */
313
+ const embedded = typeof navigator !== 'undefined' && /\bBridgeEmbedded\b/.test(navigator.userAgent);
314
+ type DesktopState = Awaited<ReturnType<NonNullable<Window['bridgeDesktop']>['state']>>;
315
+ /** The desktop app's state on its home page (`window.bridgeDesktop`); `undefined` elsewhere. */
316
+ function useDesktopState() {
317
+ const [state, setState] = React.useState<DesktopState>();
318
+ React.useEffect(() => {
319
+ const desktop = window.bridgeDesktop;
320
+ if (!desktop) return;
321
+ const off = desktop.onState(setState);
322
+ void desktop.state().then(setState);
323
+ return off;
324
+ }, []);
325
+ return state;
326
+ }
327
+ /** The home toasts handed to the desktop app while a remote page shows (window-layout.md): its toast view draws them,
328
+ * over the remote page, where this page is only the rail; what is used there comes back here. */
329
+ const desktopSink = (desktop: BridgeDesktop): ToastSink => ({
330
+ show: (toasts) =>
331
+ void desktop.showToasts(
332
+ toasts.map(({ action, secondary: _secondary, ...toast }): DesktopToast => ({
333
+ ...toast,
334
+ ...(action && { action: { label: action.label } }),
335
+ })),
336
+ ),
337
+ subscribe: (listener) => desktop.onToastUsed(listener),
338
+ });
339
+
340
+ /** A CSS colour as `#rrggbb` (a theme's may be `oklch()`, which the app's views do not read). */
341
+ const hexOf = (color: string) => {
342
+ const canvas = document.createElement('canvas').getContext('2d');
343
+ if (!canvas) return undefined;
344
+ canvas.fillStyle = color;
345
+ canvas.fillRect(0, 0, 1, 1);
346
+ const [r, g, b] = canvas.getImageData(0, 0, 1, 1).data;
347
+ return `#${[r, g, b].map((each) => each!.toString(16).padStart(2, '0')).join('')}`;
348
+ };
349
+
350
+ /** The desktop app's toast view (`bridgeDesktop.toastView`): this page draws the home page's toasts and nothing else,
351
+ * its stack's size the view's, measured whenever it changes; a toast fading out leaves it at once (hidden), so the
352
+ * view shrinks as the fade starts. An action used closes its toast, as the app's toasts do. */
353
+ function ToastView({ desktop }: { desktop: BridgeDesktop }) {
354
+ const [toasts, setToasts] = React.useState<DesktopToast[]>([]);
355
+ React.useEffect(() => {
356
+ let heard = false;
357
+ const off = desktop.onToasts((list) => {
358
+ heard = true;
359
+ setToasts(list);
360
+ });
361
+ void desktop.toasts().then((result) => {
362
+ if (result.ok && !heard) setToasts(result.toasts);
363
+ });
364
+ document.documentElement.style.overflow = 'hidden';
365
+ return off;
366
+ }, []);
367
+ // The stack is there while there are toasts; gone (React 19 runs the returned cleanup), the view has none.
368
+ const stack = React.useCallback((element: HTMLDivElement | null) => {
369
+ if (!element) return;
370
+ const report = () => {
371
+ const box = element.getBoundingClientRect();
372
+ const background = hexOf(getComputedStyle(element).backgroundColor);
373
+ void desktop.toastSize({
374
+ width: Math.ceil(box.width),
375
+ height: Math.ceil(box.height),
376
+ ...(background && { background }),
377
+ });
378
+ };
379
+ report();
380
+ const observer = new ResizeObserver(report);
381
+ observer.observe(element);
382
+ return () => {
383
+ observer.disconnect();
384
+ void desktop.toastSize({ width: 0, height: 0 });
385
+ };
386
+ }, []);
387
+ return (
388
+ <ToastStack
389
+ ref={stack}
390
+ toasts={toasts}
391
+ onAction={(id) => {
392
+ void desktop.toastUsed(id, 'action');
393
+ void desktop.toastUsed(id, 'dismiss');
394
+ }}
395
+ onDismiss={(id) => void desktop.toastUsed(id, 'dismiss')}
396
+ className="fixed left-0 top-0 w-max bg-surface text-foreground antialiased [&>div:has([data-leaving])]:hidden"
397
+ />
398
+ );
399
+ }
400
+
401
+ /** Where this browser keeps the keyboard layout's letters learnt from typing (`learnLayout`). */
402
+ const layoutKey = 'bridge.shortcuts.layout';
403
+ const readLearnt = (): KeyLayout => {
404
+ try {
405
+ const stored: unknown = JSON.parse(localStorage.getItem(layoutKey) ?? '[]');
406
+ return new Map(
407
+ Array.isArray(stored)
408
+ ? stored.filter(
409
+ (each): each is [string, string] =>
410
+ Array.isArray(each) && typeof each[0] === 'string' && typeof each[1] === 'string',
411
+ )
412
+ : [],
413
+ );
414
+ } catch {
415
+ return new Map();
416
+ }
417
+ };
418
+
419
+ /** The slot's fallback in a window's view (research-069): while it shows, the view is `state` (failed or missing:
420
+ * `failed`, not loaded yet: `reloading`), never replaced by an agent's page. */
421
+ function FallbackState({
422
+ scope,
423
+ state,
424
+ children,
425
+ }: {
426
+ scope: ShellViewScope;
427
+ state: 'reloading' | 'failed';
428
+ children: React.ReactNode;
429
+ }) {
430
+ React.useEffect(() => {
431
+ scope.fallback(state);
432
+ return () => scope.fallback(undefined);
433
+ }, [scope, state]);
434
+ return children;
435
+ }
436
+
437
+ /** A window's outer attributes (./shell.d.ts `WindowParts.window`), the anatomy managers and renderings rely on. */
438
+ export const windowAttributes = (
439
+ id: string,
440
+ focused: boolean,
441
+ active: boolean | undefined,
442
+ label: string,
443
+ state?: ViewState,
444
+ ): Parts['window'] => ({
445
+ 'data-slot': 'shell-window',
446
+ 'data-window': id,
447
+ ...(focused && { 'data-focused': true as const }),
448
+ ...(active && { 'data-active': true as const }),
449
+ ...(state && { 'data-state': state }),
450
+ role: 'region',
451
+ 'aria-label': label,
452
+ });
453
+
454
+ /** One window's parts (research-018 WM1, ./shell.d.ts `WindowParts`), in `frame`, the manager's or the shell's flat
455
+ * one: the breadcrumb of the view's node and screen path for its bar, over its view's screen, which its plugin renders
456
+ * in `screen` under its key; a short line without a view, and once the workspace's entries settled without that plugin
457
+ * filling it. The current view (the focused window's) reads the shell's state as it is (its path kept while its plugin
458
+ * failed, a URL's screen waiting for the tree); another window's, the tree. */
459
+ export function ShellWindow({
460
+ shell,
461
+ renderSlot,
462
+ id,
463
+ view,
464
+ focused,
465
+ active,
466
+ choices,
467
+ others,
468
+ frame,
469
+ mobile,
470
+ }: {
471
+ shell: Shell;
472
+ renderSlot: RenderScreen;
473
+ mobile?: boolean | undefined;
474
+ id: string;
475
+ view: View;
476
+ focused: boolean;
477
+ active?: boolean | undefined;
478
+ choices?: boolean | undefined;
479
+ others?: Others | undefined;
480
+ frame: (parts: Parts) => React.ReactNode;
481
+ }) {
482
+ const state = React.useSyncExternalStore(shell.subscribe, shell.get);
483
+ const titles = React.useSyncExternalStore(itemTitles.subscribe, itemTitles.get);
484
+ const { current, screens, loaded, nodes } = state;
485
+ const sidebarHidden = state.sidebarHidden || !state.sidebarFilled;
486
+ // The sidebar hidden (⌥B): the empty window does not send the user to it.
487
+ const where = sidebarHidden ? '' : ' in the sidebar';
488
+ const isCurrent = JSON.stringify(viewOf(state)) === JSON.stringify(viewOf(view));
489
+ const { screen, item, utility } = view;
490
+ const node = utility?.node ?? view.node;
491
+ const path = isCurrent ? state.path : screen && screens ? pathTo(screens, screen) : [];
492
+ const failed = isCurrent ? state.failed : undefined;
493
+ // Research-090: the screen's own state in this window: the shell's for the current view (the URL's, ahead of the
494
+ // manager's copy), else the window's as its manager keeps it.
495
+ const screenState = isCurrent ? state.screenState : screenStateOf(view.screenState);
496
+ const setScreenState = React.useCallback(
497
+ (next: Record<string, string> | undefined, options?: { push?: boolean }) =>
498
+ shell.setScreenState(id, next, options),
499
+ [shell, id],
500
+ );
501
+ const stateProps = { ...(screenState && { screenState }), setScreenState };
502
+ // Research-069: the view's scope, one per view generation (a node change remounts the view): its editors register
503
+ // there; the state the shell shows (a notice in its place) is told once rendered.
504
+ const generation = `${utility ? 'utility ' : ''}${node}`;
505
+ const scope = React.useMemo(() => shell.viewScope(id), [shell, id, generation]);
506
+ React.useEffect(() => scope.attach(), [scope]);
507
+ const viewState = React.useSyncExternalStore(scope.subscribe, scope.state);
508
+ let shown: 'idle' | 'reloading' | 'failed' = 'idle';
509
+ const notice = (text: string) => (
510
+ <p data-slot="main-notice" className="m-auto p-4 text-center text-sm text-secondary">
511
+ {text}
512
+ </p>
513
+ );
514
+ // An archived node, or one under an archived node: its views are read-only, under a banner (AD-6).
515
+ const byId = new Map(nodes?.nodes.map((each) => [each.id, each]));
516
+ let readOnly = false;
517
+ for (
518
+ let at = byId.get(node);
519
+ at && !readOnly;
520
+ at = at.parent === null ? undefined : byId.get(at.parent)
521
+ )
522
+ readOnly = at.archived;
523
+ // Bridge's click rule for the links of this window's view (research-048): an item alone is its screen's.
524
+ const follow = React.useMemo<Follow>(() => {
525
+ const full = (target: Parameters<Follow['href']>[0]): View | undefined =>
526
+ 'node' in target
527
+ ? target
528
+ : view.screen && {
529
+ node: view.node,
530
+ screen: view.screen,
531
+ ...(target.item !== undefined && { item: target.item }),
532
+ };
533
+ return {
534
+ href: (target) => {
535
+ const at = full(target);
536
+ return at && shell.hrefOf(at);
537
+ },
538
+ follow: (target, event) => {
539
+ if ('node' in target) return shell.follow(target, event);
540
+ const gesture = gestureOf(event);
541
+ // A modified click without a window manager: nothing (research-048), no fallback to this window.
542
+ if (!view.screen || gesture === undefined || (gesture !== 'here' && !shell.managed()))
543
+ return;
544
+ // A plugin's item, of this window's view (not the focused window's), beside this window.
545
+ shell.followItem(
546
+ {
547
+ node: view.node,
548
+ screen: view.screen,
549
+ ...(target.item !== undefined && { item: target.item }),
550
+ },
551
+ event,
552
+ { from: id, ...(target.reuse && { reuse: true }) },
553
+ );
554
+ },
555
+ };
556
+ }, [shell, view, id]);
557
+ let body: React.ReactNode;
558
+ // Whether the user works in this window (its screen's keys act only then): said by the manager, else not passed.
559
+ const at = active === undefined ? {} : { focused: active };
560
+ // The node's views, as the sidebar lists them (an empty window offers them): not hidden, a `view: false` screen only
561
+ // where the node placed it.
562
+ const laid = screens ? blocksOn(screens, nodes, node) : undefined;
563
+ const views = laid ? [...laid.top, ...laid.sections.flatMap((section) => section.blocks)] : [];
564
+ // A utility screen (Settings): its plugin's entry in `screen` for its node, over the chosen view.
565
+ if (utility)
566
+ body = (
567
+ <React.Fragment key={`${id} utility ${node}`}>
568
+ {renderSlot(
569
+ 'screen',
570
+ { screen: utility.plugin, node, readOnly, ...at, ...stateProps },
571
+ {
572
+ entryKey: utility.plugin,
573
+ fallback: (
574
+ <FallbackState scope={scope} state={loaded ? 'failed' : 'reloading'}>
575
+ {loaded ? notice(`${utility.title} is not installed in this workspace.`) : null}
576
+ </FallbackState>
577
+ ),
578
+ },
579
+ )}
580
+ </React.Fragment>
581
+ );
582
+ // Nothing while a screen the URL names waits for the tree (loading, or its fetch failed): taken once it has it.
583
+ else if (!screen)
584
+ body =
585
+ isCurrent && !screens && screenInUrl(current?.slug) ? null : choices && views.length ? (
586
+ // An empty window (research-018 P8, ⌥\): the node's views as buttons, as the sidebar lists them; a click shows one
587
+ // here (the window is focused on the pointer down). No view there: the notice alone.
588
+ <div
589
+ data-slot="main-notice"
590
+ className="m-auto flex flex-col items-center gap-3 p-4 text-center text-sm text-secondary"
591
+ >
592
+ <p className="m-0">Choose a view{where}, or:</p>
593
+ <div
594
+ data-slot="shell-window-choices"
595
+ className="flex max-w-[480px] flex-wrap justify-center gap-2"
596
+ >
597
+ {views.map((block) => (
598
+ <Button
599
+ key={`${block.plugin} ${block.screen.id}`}
600
+ size="sm"
601
+ onClick={(event) =>
602
+ shell.follow(
603
+ { node, screen: { plugin: block.plugin, id: block.screen.id } },
604
+ event,
605
+ )
606
+ }
607
+ onAuxClick={(event) => {
608
+ if (event.button !== 1) return;
609
+ event.preventDefault();
610
+ shell.follow(
611
+ { node, screen: { plugin: block.plugin, id: block.screen.id } },
612
+ event,
613
+ );
614
+ }}
615
+ >
616
+ {block.screen.icon !== undefined && <Icon name={block.screen.icon} size={14} />}
617
+ {block.screen.title}
618
+ </Button>
619
+ ))}
620
+ </div>
621
+ </div>
622
+ ) : (
623
+ notice(`Choose a view${where}.`)
624
+ );
625
+ // Not confirmed by the tree yet (loading, or its fetch failed): a URL may name a screen that does not exist. Another
626
+ // window's screen the loaded tree lacks: gone (its plugin failed, disabled, or removed).
627
+ else if (!path.length) {
628
+ shown = isCurrent || !screens ? 'reloading' : 'failed';
629
+ body =
630
+ isCurrent || !screens
631
+ ? null
632
+ : notice('This view is not available: its plugin failed, was disabled, or was removed.');
633
+ }
634
+ // Its plugin failed or waits for a service: the screen stays chosen, back in place once the plugin runs.
635
+ else if (failed) {
636
+ shown = failed.waiting ? 'reloading' : 'failed';
637
+ body = notice(
638
+ failed.waiting
639
+ ? `${failed.plugin} is waiting for ${failed.message}`
640
+ : `${failed.plugin} failed: ${failed.message}`,
641
+ );
642
+ }
643
+ // AD-25: its plugin is not active on the node shown (a deep link, a node change): a notice instead of its entry.
644
+ else if (nodes?.resolved[node] && !nodes.resolved[node].active.includes(screen.plugin)) {
645
+ shown = 'failed';
646
+ body = notice('Not active on this node');
647
+ }
648
+ // Keyed by the window and the node: a view never shows the previous node's data (AD-11). Another item only
649
+ // re-renders it. On a phone (./mobile.tsx), a screen with a phone variant (`"mobile": true`) renders its plugin's
650
+ // `mobileScreen` entry, any other its desktop `screen` (D4).
651
+ else {
652
+ const owner = {
653
+ screen: screen.id,
654
+ node,
655
+ readOnly,
656
+ ...(item !== undefined && { item }),
657
+ ...at,
658
+ ...(others && { others }),
659
+ ...stateProps,
660
+ };
661
+ // Research-069: shown, the slot has no entry for it (failed, missing, or not loaded yet): the view says so.
662
+ const fallback = (
663
+ <FallbackState scope={scope} state={loaded ? 'failed' : 'reloading'}>
664
+ {loaded
665
+ ? notice(
666
+ "Nothing to show: this screen's plugin has no browser entry, or it failed to load (see the host output and the browser console).",
667
+ )
668
+ : null}
669
+ </FallbackState>
670
+ );
671
+ body = (
672
+ <React.Fragment key={`${id} ${node}`}>
673
+ {mobile && path.at(-1)?.mobile
674
+ ? renderSlot(
675
+ 'mobileScreen',
676
+ { ...owner, ...mobileOwner(screen) },
677
+ { entryKey: screen.plugin, fallback },
678
+ )
679
+ : renderSlot('screen', owner, { entryKey: screen.plugin, fallback })}
680
+ </React.Fragment>
681
+ );
682
+ }
683
+
684
+ // The node shown's ancestors below `root` (the workspace, AD-11: no sidebar row), top first.
685
+ const places: { id: string; title: string }[] = [];
686
+ for (
687
+ let at = byId.get(node);
688
+ at && at.id !== 'root' && places.length < byId.size;
689
+ at = at.parent === null ? undefined : byId.get(at.parent)
690
+ )
691
+ places.unshift(at);
692
+ // At the node's home view (AD-11): the node stands for it, no screen crumb. A utility screen: its title alone.
693
+ // Slice 6e, as the prototype's `crumbs('Contacts', name)`: an item, the screen's path then the item as its plugin names
694
+ // it (`ctx.screen.title`; none given, as it is), the screen's crumb choosable (the screen without the item).
695
+ const itemTitle =
696
+ screen && item !== undefined && path.length
697
+ ? (titles.get(screen.plugin)?.get(item)?.title ?? item)
698
+ : undefined;
699
+ // What the item's plugin says in place of its screen's title (a session's branch, research-083): still its link.
700
+ const itemContext =
701
+ screen && item !== undefined ? titles.get(screen.plugin)?.get(item)?.context : undefined;
702
+ const screenCrumbs =
703
+ itemContext !== undefined && path.length
704
+ ? [...path.slice(0, -1), { ...path.at(-1)!, title: itemContext }]
705
+ : path;
706
+ const crumbs = utility
707
+ ? [{ id: utility.plugin, title: utility.title }]
708
+ : itemTitle !== undefined
709
+ ? [...screenCrumbs, { id: item!, title: itemTitle }]
710
+ : screen !== undefined && path.length === 1 && screen.plugin === nodes?.resolved[node]?.home
711
+ ? []
712
+ : path;
713
+ React.useEffect(() => scope.show(shown), [scope, shown]);
714
+ return frame({
715
+ window: windowAttributes(
716
+ id,
717
+ focused,
718
+ active,
719
+ utility?.title ??
720
+ itemTitle ??
721
+ path.at(-1)?.title ??
722
+ places.at(-1)?.title ??
723
+ (screen ? 'Window' : 'Empty window'),
724
+ viewState,
725
+ ),
726
+ bar: { 'data-slot': 'shell-window-bar' },
727
+ // The node's path below the workspace (the sidebar's header names it), then the screen's path, each ancestor
728
+ // choosable; nothing at the workspace without a choice (no empty navigation landmark). Long titles truncate.
729
+ // Its crumbs are links of this window: under its `follow`, as its view's are.
730
+ crumbs: (crumbs.length > 0 || places.length > 0) && (
731
+ <FollowProvider value={follow}>
732
+ <Breadcrumb
733
+ className="min-w-0 [&>[data-slot=breadcrumb-item]]:truncate [&>[data-slot=breadcrumb-separator]]:shrink-0"
734
+ items={[
735
+ ...places.map((place, index) => ({
736
+ label: place.title,
737
+ ...((index < places.length - 1 || utility) && { to: { node: place.id } }),
738
+ })),
739
+ ...crumbs.map((each, index) => ({
740
+ label: each.title,
741
+ ...(screen &&
742
+ !utility &&
743
+ index < crumbs.length - 1 && {
744
+ to: { node: view.node, screen: { plugin: screen.plugin, id: each.id } },
745
+ }),
746
+ })),
747
+ ]}
748
+ />
749
+ </FollowProvider>
750
+ ),
751
+ body: (
752
+ <div data-slot="shell-window-body" className="flex min-h-0 flex-1 flex-col overflow-y-auto">
753
+ {/* One parent whether archived or not: only a node change remounts the view. */}
754
+ <div className="flex min-h-0 flex-1 flex-col">
755
+ {readOnly && (
756
+ <p
757
+ role="status"
758
+ data-slot="main-banner"
759
+ className="m-0 border-b border-border px-4 py-2 text-sm text-secondary"
760
+ >
761
+ This node is archived
762
+ </p>
763
+ )}
764
+ <ViewScopeProvider value={scope}>
765
+ <FollowProvider value={follow}>{body}</FollowProvider>
766
+ </ViewScopeProvider>
767
+ </div>
768
+ </div>
769
+ ),
770
+ });
771
+ }
772
+
773
+ /** `main` by default (research-018 WM2): the `stage`, where a window manager lays out its windows, each framed by it
774
+ * around the parts `renderWindow` gives; empty, none chosen in this browser, or its manager set aside (it threw, missed
775
+ * a function, or its entry crashed), the shell's one window showing the current view, flat (`flatFrame`). A manager set aside toasts, naming it: this
776
+ * page goes on without one (not stored) until the user chooses, the manager comes again, or a reload; the toast's
777
+ * "Choose" opens the menu that offers the choice (C6). */
778
+ function Main({
779
+ shell,
780
+ stagePlugin,
781
+ chooser,
782
+ renderSlot,
783
+ }: {
784
+ shell: Shell;
785
+ stagePlugin: () => string | undefined;
786
+ chooser: Signal;
787
+ renderSlot: RenderScreen &
788
+ ((
789
+ key: 'stage',
790
+ owner: StageOwner,
791
+ opts: { fallback: React.ReactNode; registrant: string },
792
+ ) => React.ReactNode) &
793
+ ((key: 'dialogs', owner: object) => React.ReactNode);
794
+ }) {
795
+ const state = React.useSyncExternalStore(shell.subscribe, shell.get);
796
+ const mobile = useMobile();
797
+ const { toast } = useToast();
798
+ const failed = state.managerFailed;
799
+ React.useEffect(() => {
800
+ if (!failed) return;
801
+ const { plugin, message } = failed;
802
+ const name = plugin === undefined ? 'The window manager' : `The window manager ${plugin}`;
803
+ toast({
804
+ ...toastOf({
805
+ variant: 'error',
806
+ title: `${name} failed: no window manager for now`,
807
+ description: `${message}. This page shows one window until you choose a window manager, or reload.`,
808
+ }),
809
+ key: `window-manager ${plugin ?? ''}`,
810
+ action: { label: 'Choose', onClick: () => chooser.emit() },
811
+ });
812
+ }, [failed, toast, chooser]);
813
+ const renderWindow = React.useCallback(
814
+ (id: string, view: View, { focused, active, choices, others, frame }: Options) => (
815
+ <ShellWindow
816
+ key={id}
817
+ shell={shell}
818
+ renderSlot={renderSlot}
819
+ id={id}
820
+ view={view}
821
+ focused={focused}
822
+ active={active}
823
+ choices={choices}
824
+ others={others}
825
+ frame={frame ?? flatFrame}
826
+ mobile={mobile}
827
+ />
828
+ ),
829
+ [shell, renderSlot, mobile],
830
+ );
831
+ const view = viewOf(state);
832
+ // Workspace plugins' dialogs (research-034): each portals its own modal over the page, on a phone too.
833
+ const dialogs = renderSlot('dialogs', {});
834
+ // On a phone: no window manager, the one view full screen under the phone's header (./mobile.tsx).
835
+ if (mobile)
836
+ return (
837
+ <>
838
+ {renderWindow('main', view, {
839
+ focused: false,
840
+ active: true,
841
+ frame: mobileFrame(shell, view),
842
+ })}
843
+ {dialogs}
844
+ </>
845
+ );
846
+ // The shell's one window, flat in the stage: the window the user works in.
847
+ const one = renderWindow('main', view, { focused: false, active: true });
848
+ // Set aside, none chosen, or none installed (re-read on each change: the shell notifies when `stage` changes).
849
+ const plugin = stagePlugin();
850
+ if (failed || plugin === undefined)
851
+ return (
852
+ <>
853
+ {one}
854
+ {dialogs}
855
+ </>
856
+ );
857
+ return (
858
+ <>
859
+ {renderSlot(
860
+ 'stage',
861
+ { renderWindow, view, workspace: state.current?.slug },
862
+ { fallback: one, registrant: plugin },
863
+ )}
864
+ {dialogs}
865
+ </>
866
+ );
867
+ }
868
+
869
+ /** The keyboard shortcuts' help (research-018 C5): Bridge's own keys, then every key registered (a window manager's),
870
+ * the keys screens declared (Sessions'), and the pointer gestures, with their labels; opened by `?` outside a field and by the theme menu's "Keyboard shortcuts". */
871
+ function ShortcutsHelp({ shell, help, app }: { shell: Shell; help: Signal; app: boolean }) {
872
+ const [open, setOpen] = React.useState(false);
873
+ React.useEffect(() => help.subscribe(() => setOpen((was) => !was)), [help]);
874
+ const list = React.useSyncExternalStore(shell.shortcuts.subscribe, shell.shortcuts.list);
875
+ const gestures = React.useSyncExternalStore(shell.shortcuts.subscribe, shell.shortcuts.gestures);
876
+ const declared = React.useSyncExternalStore(shell.shortcuts.subscribe, shell.shortcuts.declared);
877
+ // macOS names its keys by symbol (⌥ ⇧ ⌘); elsewhere by name (Alt, Shift, Ctrl).
878
+ const mac = /Mac/.test(navigator.platform || navigator.userAgent);
879
+ const rows: { keys: string[]; label: string; description?: string | undefined }[] = [
880
+ { keys: ['?'], label: 'Keyboard shortcuts' },
881
+ {
882
+ keys: [mac ? '⌘-click' : 'Ctrl-click', 'middle click'],
883
+ label: 'Open a view or a link in a new window',
884
+ },
885
+ ...list.map(({ keys, label, description }) => ({
886
+ keys: keys.map((each) => displayKeys(each, mac)),
887
+ label,
888
+ description,
889
+ })),
890
+ // The keys screens handle themselves (Sessions'), in the focused window, each with its plugin.
891
+ ...declared.map(({ keys, label, by }) => ({
892
+ keys: keys.map((each) => displayKeys(each, mac)),
893
+ label: by === undefined ? label : `${label} (${by})`,
894
+ })),
895
+ // The pointer gestures plugins declared (Point's, the window manager's), each with its plugin.
896
+ ...gestures.map(({ modifiers, action, label, by }) => ({
897
+ keys: [displayGesture(modifiers, action, mac)],
898
+ label: by === undefined ? label : `${label} (${by})`,
899
+ })),
900
+ ];
901
+ const hint = !mac
902
+ ? 'Alt is the window key.'
903
+ : app
904
+ ? '⌥ is Option; in the app, ⌘ works in its place for W, M, \\ and the digits.'
905
+ : '⌥ is Option.';
906
+ return (
907
+ <Dialog open={open} onOpenChange={setOpen}>
908
+ <DialogContent className="w-[600px]">
909
+ <DialogHeader>
910
+ <DialogTitle>Keyboard shortcuts</DialogTitle>
911
+ </DialogHeader>
912
+ <DialogBody className="flex flex-col gap-3 pb-3">
913
+ <DialogDescription>{hint}</DialogDescription>
914
+ {/* The keys' column as wide as its keys, up to 45%: a long row of them (⌥1 … ⌥9) wraps, the labels keep
915
+ their room. */}
916
+ <dl
917
+ data-slot="shell-shortcuts"
918
+ className="m-0 grid grid-cols-[fit-content(45%)_1fr] items-baseline gap-x-4 gap-y-1.5 text-[13px]"
919
+ >
920
+ {rows.map(({ keys, label, description }) => (
921
+ <React.Fragment key={`${keys.join(' ')} ${label}`}>
922
+ <dt className="flex flex-wrap gap-1">
923
+ {keys.map((each) => (
924
+ <kbd
925
+ key={each}
926
+ className="rounded border border-border px-1.5 font-mono text-xs whitespace-nowrap"
927
+ >
928
+ {each}
929
+ </kbd>
930
+ ))}
931
+ </dt>
932
+ <dd className="m-0 text-secondary">
933
+ {label}
934
+ {description !== undefined && (
935
+ <span className="block text-xs text-muted">{description}</span>
936
+ )}
937
+ </dd>
938
+ </React.Fragment>
939
+ ))}
940
+ </dl>
941
+ {list.length === 0 && (
942
+ <p className="m-0 text-sm text-secondary">
943
+ No window manager shortcuts: none is active.
944
+ </p>
945
+ )}
946
+ </DialogBody>
947
+ </DialogContent>
948
+ </Dialog>
949
+ );
950
+ }
951
+
952
+ /** Whether a field of the page holds text not sent yet: a text input, a text area or an editable element. A draft lives
953
+ * only in the page (a prompt keeps its text in React state), so a reload would lose it. */
954
+ const holdsUnsentText = () =>
955
+ [
956
+ ...document.querySelectorAll(
957
+ 'input, textarea, [contenteditable]:not([contenteditable="false"])',
958
+ ),
959
+ ].some((field) =>
960
+ field instanceof HTMLTextAreaElement
961
+ ? field.value !== ''
962
+ : field instanceof HTMLInputElement
963
+ ? /^(text|search|url|email|tel|number|password|)$/.test(field.getAttribute('type') ?? '') &&
964
+ field.value !== ''
965
+ : field.textContent.trim() !== '',
966
+ );
967
+
968
+ /** Reloads the page for a new Bridge UI build, unless a field holds unsent text: then `notice` asks the user to reload
969
+ * (Bridge was updated · Reload page), so a draft is never lost. */
970
+ export const reloadWhenIdle = (notice: () => void, reload = () => location.reload()) =>
971
+ holdsUnsentText() ? notice() : reload();
972
+
973
+ /** Toasts the host's status events (./notifications.ts), from its mount on. A failure's `fix` is its button: the request
974
+ * runs (`runFix`, ./errors.tsx) and the status events that follow dismiss the toast once the failure is gone; a refusal
975
+ * toasts its message and hint. A notice with `details` also gets a Details button, opening the Errors modal scrolled to
976
+ * its item, and one with `copy` a Copy button. */
977
+ function Notifications({
978
+ hostStatus,
979
+ showErrors,
980
+ shell,
981
+ }: {
982
+ hostStatus: Context['hostStatus'];
983
+ showErrors: (key?: string) => void;
984
+ shell: Shell;
985
+ }) {
986
+ const { toast, dismiss } = useToast();
987
+ React.useEffect(() => {
988
+ const openSetting = (fix: Extract<Fix, { action: 'setting' }>, event?: FollowEvent) =>
989
+ shell.openSetting(fix.slug, fix.plugin, fix.setting, event);
990
+ const shown = ({ fix, copy, details, closed, ...notice }: Notice, key?: string) =>
991
+ toast({
992
+ ...toastOf(notice),
993
+ ...(copy !== undefined && { copy }),
994
+ ...(key !== undefined && { key }),
995
+ ...(closed && { onClose: closed }),
996
+ ...(fix && {
997
+ action: {
998
+ label: fixLabel(fix),
999
+ onClick: (event?: FollowEvent) =>
1000
+ fix.action === 'setting' ? openSetting(fix, event) : runFix(fix, notice.title, toast),
1001
+ },
1002
+ }),
1003
+ ...(details !== undefined && {
1004
+ secondary: { label: 'Details', onClick: () => showErrors(details) },
1005
+ }),
1006
+ });
1007
+ const offStatus = hostStatus.subscribe(notifier(shown, dismiss));
1008
+ // Bridge updated under this page: as the other notifications, with Reload page on the right.
1009
+ // Its key keeps it one: told again (a rerender, a shell remount), it replaces itself in place.
1010
+ const offUpdated = hostStatus.pageUpdated?.(() => {
1011
+ // A local Bridge UI under development (research-083): its new build reloads the page by itself, as a dev server
1012
+ // does when a module cannot be swapped (the kit is in the page's import map), with no notice; unless a field holds
1013
+ // unsent text. Otherwise, or then, as the other notifications, with Reload page on the right.
1014
+ void fetch('/_bridge/host/ui', { cache: 'no-store' })
1015
+ .then((res) => (res.ok ? readJson(res) : undefined))
1016
+ .catch(() => undefined)
1017
+ .then((body: unknown) => {
1018
+ const served = isRecord(body) && isRecord(body.served) ? body.served : undefined;
1019
+ // Its key keeps it one: told again (a rerender, a shell remount), it replaces itself in place.
1020
+ const notice = () =>
1021
+ toast({
1022
+ ...toastOf({
1023
+ variant: 'info',
1024
+ title: 'Bridge was updated',
1025
+ description: 'Reload the page to use the new version.',
1026
+ }),
1027
+ key: 'bridge-updated',
1028
+ // An info notice fades by default: this one stays until the page reloads.
1029
+ duration: Infinity,
1030
+ dismissible: false,
1031
+ action: { label: 'Reload page', onClick: () => location.reload() },
1032
+ });
1033
+ if (served?.source === 'local') return reloadWhenIdle(notice);
1034
+ notice();
1035
+ });
1036
+ });
1037
+ return () => {
1038
+ offStatus();
1039
+ offUpdated?.();
1040
+ };
1041
+ }, [hostStatus, toast, dismiss, showErrors, shell]);
1042
+ return null;
1043
+ }
1044
+
1045
+ /** The installed window managers for the theme menu (WM5): every `stage` entry's plugin, the default (the slot's head)
1046
+ * first; any can be chosen (CAP-6). */
1047
+ function useManagers(slots: Context['slots']): ManagerOption[] {
1048
+ const read = React.useCallback(
1049
+ () => JSON.stringify(liveStages(slots).map((entry) => entry.registrant ?? null)),
1050
+ [slots],
1051
+ );
1052
+ const text = React.useSyncExternalStore(
1053
+ React.useCallback((listener: () => void) => slots.subscribe('stage', listener), [slots]),
1054
+ read,
1055
+ );
1056
+ return React.useMemo(() => {
1057
+ const keys = [
1058
+ ...new Set(
1059
+ // oxlint-disable-next-line bridge/no-new-unchecked-cast -- text is JSON.stringify'd by `read` just above
1060
+ (JSON.parse(text) as (string | null)[]).filter((key): key is string => key !== null),
1061
+ ),
1062
+ ];
1063
+ return keys.map((key) => ({ key, title: managerTitles[key] ?? key }));
1064
+ }, [text]);
1065
+ }
1066
+ /** `stage` entries that crashed (set aside by the slot, still listed by `entries`). */
1067
+ const crashedStages = new WeakSet<object>();
1068
+ /** Every `stage` entry but those that crashed, the default (the slot's head) first. */
1069
+ const liveStages = (slots: Context['slots']) =>
1070
+ slots.entries('stage').filter((entry) => !crashedStages.has(entry));
1071
+ /** Titles of known window managers; another shows its plugin key. */
1072
+ const managerTitles: Record<string, string> = { windows: 'Windows' };
1073
+
1074
+ /** The theme controls (./theme-controls.tsx) for the workspace shown: under the sidebar, or at the rail's bottom while it
1075
+ * is hidden (`inRail`: without the sidebar's button, which the rail puts last). */
1076
+ export function ShellControls({
1077
+ shell,
1078
+ slots,
1079
+ help,
1080
+ chooser,
1081
+ extra,
1082
+ hasWallpaper,
1083
+ themeMenu,
1084
+ inRail = false,
1085
+ narrow = false,
1086
+ }: {
1087
+ inRail?: boolean;
1088
+ /** In the narrow column an embedded page keeps with the sidebar hidden: stacked, as in the rail. */
1089
+ narrow?: boolean;
1090
+ shell: Shell;
1091
+ slots: Context['slots'];
1092
+ help: Signal;
1093
+ chooser: Signal;
1094
+ themeMenu: ThemeMenu;
1095
+ /** The `controls` slot's entries (a Start button with no dock), first. */
1096
+ extra: React.ReactNode;
1097
+ hasWallpaper: boolean;
1098
+ }) {
1099
+ const managers = useManagers(slots);
1100
+ const showMenu = React.useSyncExternalStore(themeMenu.subscribe, themeMenu.get);
1101
+ const {
1102
+ managerChoice: asideChoice,
1103
+ current,
1104
+ sidebarFilled,
1105
+ sidebarHidden,
1106
+ navigators,
1107
+ } = React.useSyncExternalStore(shell.subscribe, shell.get);
1108
+ // In sight: the rail's while the column is hidden, else the column's (the other kept, inert, while it slides or shrinks
1109
+ // away). Only that one opens its menu on a request: never two menus.
1110
+ const columnHidden = sidebarHidden || !sidebarFilled;
1111
+ const inSight = inRail ? columnHidden : !columnHidden || narrow;
1112
+ // The manager active: the one the look names (the user's Mine, else the workspace's proposal) when installed, else the
1113
+ // default (the first); none when "None" is chosen or one is set aside.
1114
+ const managerChoice = managerOf(asideChoice, current?.look);
1115
+ const active =
1116
+ managerChoice === null
1117
+ ? null
1118
+ : managers.some((each) => each.key === managerChoice)
1119
+ ? managerChoice!
1120
+ : (managers[0]?.key ?? null);
1121
+ return (
1122
+ <ThemeControls
1123
+ managers={managers}
1124
+ active={active}
1125
+ workspace={current?.slug}
1126
+ onChoose={(key) => shell.chooseManager(key)}
1127
+ onShortcuts={help.emit}
1128
+ openRequests={inSight ? chooser : undefined}
1129
+ // Laid out where they stand, not as the column is: the rail keeps its own while they shrink away as the column comes
1130
+ // back, the column its own while it slides away.
1131
+ sidebarHidden={inRail || narrow}
1132
+ onSidebarHidden={
1133
+ sidebarFilled && !inRail ? (hidden) => shell.setSidebarHidden(hidden) : undefined
1134
+ }
1135
+ navigators={navigators}
1136
+ navigatorShown={(id) => shell.navigatorShown(id)}
1137
+ extra={extra}
1138
+ hasWallpaper={hasWallpaper}
1139
+ look={current?.look}
1140
+ themeMenu={showMenu}
1141
+ />
1142
+ );
1143
+ }
1144
+
1145
+ type CommandsService = {
1146
+ get(): Context['commands'] | undefined;
1147
+ subscribe(listener: () => void): () => void;
1148
+ };
1149
+
1150
+ /** The workspace shown proposes its look, the user's Mine over it: applied by both frames, the desktop's and the phone's. */
1151
+ function useWorkspaceLook(shell: React.ComponentProps<typeof Frame>['shell']) {
1152
+ const state = React.useSyncExternalStore(shell.subscribe, shell.get);
1153
+ const { current } = state;
1154
+ // The workspace shown proposes its style, icons and theme pair, the user's Mine over them (research-028).
1155
+ const look = current?.look;
1156
+ const proposal = JSON.stringify([
1157
+ look?.style,
1158
+ look?.icons,
1159
+ look?.lightTheme,
1160
+ look?.darkTheme,
1161
+ look?.controlHeight,
1162
+ look?.controlRadius,
1163
+ ]);
1164
+ // Before the paint (the new workspace never shows a frame in the last one's theme); none once the page had a workspace
1165
+ // and has none left (until the first answer, the boot page's proposal stays).
1166
+ const hadWorkspace = React.useRef(false);
1167
+ React.useLayoutEffect(() => {
1168
+ if (current) hadWorkspace.current = true;
1169
+ else if (!hadWorkspace.current) return;
1170
+ setWorkspaceAppearance(
1171
+ current && {
1172
+ kit: look?.style,
1173
+ icons: look?.icons,
1174
+ lightTheme: look?.lightTheme,
1175
+ darkTheme: look?.darkTheme,
1176
+ controlHeight: look?.controlHeight,
1177
+ controlRadius: look?.controlRadius,
1178
+ },
1179
+ );
1180
+ }, [current?.slug, proposal]);
1181
+ // The themes the workspace's packs bring (research-038), again when its plugins change.
1182
+ usePackThemes(
1183
+ current?.slug,
1184
+ `${current ? (state.compositions?.[current.slug] ?? '') : ''} | ${state.compositions?._host ?? ''}`,
1185
+ );
1186
+ }
1187
+
1188
+ /** Where the host serves the themes packs bring (research-038), for the kit's pack-theme hooks. */
1189
+ const workspaceThemes = (slug: string) => `/_bridge/workspaces/${encodeURIComponent(slug)}/themes`;
1190
+ const packThemeRoutes = {
1191
+ themes: workspaceThemes,
1192
+ stylesheet: (slug: string) => `${workspaceThemes(slug)}.css`,
1193
+ hostThemes: workspaceThemes('_host'),
1194
+ };
1195
+
1196
+ /** The desktop frame, or on a phone (./mobile.tsx) the phone's: no rail, no sidebar, the drawer. */
1197
+ function RootFrame(props: React.ComponentProps<typeof Frame>) {
1198
+ const mobile = useMobile();
1199
+ useWorkspaceLook(props.shell);
1200
+ if (!mobile) return <Frame {...props} />;
1201
+ const { shell, hostStatus, errors, renderSlot } = props;
1202
+ return (
1203
+ <ToastProvider>
1204
+ <Notifications hostStatus={hostStatus} showErrors={errors.emit} shell={shell} />
1205
+ <RestartScreen hostStatus={hostStatus} />
1206
+ <TooltipProvider>
1207
+ <MobileFrame shell={shell} renderSlot={renderSlot} />
1208
+ </TooltipProvider>
1209
+ <ErrorsModal
1210
+ hostStatus={hostStatus}
1211
+ errors={errors}
1212
+ openSetting={shell.openSetting}
1213
+ showHealth={shell.showHealth}
1214
+ />
1215
+ </ToastProvider>
1216
+ );
1217
+ }
1218
+
1219
+ function Frame({
1220
+ shell,
1221
+ slots,
1222
+ hostStatus,
1223
+ help,
1224
+ chooser,
1225
+ review,
1226
+ app,
1227
+ errors,
1228
+ renderSlot,
1229
+ commands,
1230
+ themeMenu,
1231
+ }: {
1232
+ shell: Shell;
1233
+ slots: Context['slots'];
1234
+ hostStatus: Context['hostStatus'];
1235
+ help: Signal;
1236
+ chooser: Signal;
1237
+ themeMenu: ThemeMenu;
1238
+ review: Review;
1239
+ app: boolean;
1240
+ errors: ErrorsSignal;
1241
+ renderSlot: (
1242
+ key: 'rail' | 'sidebar' | 'main' | 'overlay' | 'controls',
1243
+ props: object,
1244
+ ) => React.ReactNode;
1245
+ commands: CommandsService;
1246
+ }) {
1247
+ // The `commands` plugin's palette (research-034), when one provides it: every screen's CommandScope hands it its
1248
+ // commands instead of opening its own ⌘K menu.
1249
+ const palette = React.useSyncExternalStore(commands.subscribe, commands.get);
1250
+ const host = React.useMemo(() => palette && { register: palette.register }, [palette]);
1251
+ const [sidebarWidth, setSidebarWidth] = useSidebarWidth();
1252
+ const managers = useManagers(slots);
1253
+ const themeCanvas = useRendering()?.canvas;
1254
+ const state = React.useSyncExternalStore(shell.subscribe, shell.get);
1255
+ const { current } = state;
1256
+ // Whether a plugin fills `rail` (research-112): none, no rail column at all.
1257
+ const railFilled = React.useSyncExternalStore(
1258
+ React.useCallback((changed: () => void) => slots.subscribe('rail', changed), [slots]),
1259
+ () => slots.entriesOfSlot('rail').length > 0,
1260
+ );
1261
+ // No plugin in `sidebar`: no column, as hidden.
1262
+ const sidebarHidden = state.sidebarHidden || !state.sidebarFilled;
1263
+ // The column hidden, its controls stand under the rail; embedded in the app (no rail of this page), a narrow column
1264
+ // keeps them.
1265
+ const inRail = sidebarHidden && !embedded;
1266
+ // While the column slides (shown or hidden, not while it is resized): its width transitions, until it ends. Set in the
1267
+ // render that changes the width (not in an effect after it), so no style is computed between the two.
1268
+ const [sliding, setSliding] = React.useState(false);
1269
+ const [wasHidden, setWasHidden] = React.useState(sidebarHidden);
1270
+ if (wasHidden !== sidebarHidden) {
1271
+ setWasHidden(sidebarHidden);
1272
+ setSliding(!embedded && !matchMedia('(prefers-reduced-motion: reduce)').matches);
1273
+ }
1274
+ const mode = useColourMode();
1275
+ const shownTheme = useThemeOfMode(mode);
1276
+ // The shell's own commands in the ⌘K palette (research-034), under "Bridge", after the focused screen's: read when the
1277
+ // palette draws, so they follow the managers and the status.
1278
+ const bridgeCommands = React.useRef<Command[]>([]);
1279
+ /** A joined Bridge's page shows under this one (the desktop app): this page's dialogs would be clipped to the rail. */
1280
+ const remoteUnder = React.useRef(false);
1281
+ bridgeCommands.current = [
1282
+ {
1283
+ id: 'status',
1284
+ label: 'Bridge status',
1285
+ group: 'Bridge',
1286
+ icon: 'activity',
1287
+ run: () => {
1288
+ // Something needs attention: Health, its open problems (research-047); else Status.
1289
+ void shell.showStatus().catch((error: unknown) => console.error('Bridge status:', error));
1290
+ if (remoteUnder.current) void window.bridgeDesktop?.select(null, 'admin');
1291
+ },
1292
+ },
1293
+ {
1294
+ id: 'mode',
1295
+ label: mode === 'dark' ? 'Light mode' : 'Dark mode',
1296
+ group: 'Bridge',
1297
+ icon: 'monitor',
1298
+ run: () => void setMode(getColourMode() === 'dark' ? 'light' : 'dark'),
1299
+ },
1300
+ {
1301
+ id: 'manager',
1302
+ label: 'Window manager…',
1303
+ group: 'Bridge',
1304
+ icon: 'layout-dashboard',
1305
+ run: () => {},
1306
+ children: [
1307
+ { id: 'workspace', label: "Workspace's choice", run: () => shell.chooseManager(undefined) },
1308
+ ...managers.map((m) => ({
1309
+ id: m.key,
1310
+ label: m.title,
1311
+ run: () => shell.chooseManager(m.key),
1312
+ })),
1313
+ { id: 'none', label: 'None (one window)', run: () => shell.chooseManager(null) },
1314
+ ],
1315
+ },
1316
+ {
1317
+ id: 'shortcuts',
1318
+ label: 'Keyboard shortcuts',
1319
+ keys: '?',
1320
+ group: 'Bridge',
1321
+ icon: 'list',
1322
+ run: help.emit,
1323
+ },
1324
+ ];
1325
+ React.useEffect(
1326
+ () =>
1327
+ palette?.register({
1328
+ depth: 0,
1329
+ level: 'bridge',
1330
+ subject: () => undefined,
1331
+ // Over a joined page, its own Keyboard shortcuts are listed (this page's dialog would be clipped).
1332
+ commands: () =>
1333
+ bridgeCommands.current.filter(
1334
+ (each) => !(remoteUnder.current && each.id === 'shortcuts'),
1335
+ ),
1336
+ subscribe: () => () => {},
1337
+ }),
1338
+ [palette],
1339
+ );
1340
+ const look = current?.look;
1341
+ // The theme from the wallpaper (any image the look keeps, shown or not), each mode's image.
1342
+ const kept = look?.wallpaper;
1343
+ useWallpaperTheme(
1344
+ current?.slug,
1345
+ {
1346
+ light: kept && current && wallpaperUrl(current.slug, kept.hash, mineImageOf),
1347
+ dark: kept && current && wallpaperUrl(current.slug, kept.dark ?? kept.hash, mineImageOf),
1348
+ },
1349
+ JSON.stringify([kept?.hash, kept?.dark]),
1350
+ );
1351
+ // The sidebar's ink on the wallpaper shown: what reads on the image under it (./wallpaper-ink.ts).
1352
+ const shown = wallpaperOf(look);
1353
+ const shownId = shown && (mode === 'dark' && shown.dark !== undefined ? shown.dark : shown.hash);
1354
+ const sidebarInk = useWallpaperInk(
1355
+ shownId && current && wallpaperUrl(current.slug, shownId, mineImageOf),
1356
+ shown?.fit,
1357
+ // The theme too: its canvas shows around a contained image.
1358
+ shownId === undefined ? '' : `${shownId}|${shownTheme}`,
1359
+ );
1360
+ // The desktop app shows a remote workspace under this page (window-layout.md): only the rail, a translucent tint over
1361
+ // the remote page; the rest transparent (kept mounted, hidden).
1362
+ const desktopState = useDesktopState();
1363
+ const over = !!desktopState?.shown;
1364
+ remoteUnder.current = over;
1365
+ // While a popup of this page covers the window (`overlay`), its toasts are drawn here, over it.
1366
+ const sinking = over && !desktopState?.overlay;
1367
+ const sink = React.useMemo(
1368
+ () => (sinking && window.bridgeDesktop ? desktopSink(window.bridgeDesktop) : undefined),
1369
+ [sinking],
1370
+ );
1371
+ // A home workspace chosen another way than its tile (a shortcut, Back, a link) while a remote page shows: home again.
1372
+ const slug = current?.slug;
1373
+ const lastSlug = React.useRef(slug);
1374
+ React.useEffect(() => {
1375
+ if (lastSlug.current === slug) return;
1376
+ lastSlug.current = slug;
1377
+ if (over && slug !== undefined) void window.bridgeDesktop?.select(null, slug);
1378
+ }, [slug]);
1379
+ return (
1380
+ <ToastProvider sink={sink}>
1381
+ <Notifications hostStatus={hostStatus} showErrors={errors.emit} shell={shell} />
1382
+ <RestartScreen hostStatus={hostStatus} />
1383
+ <TooltipProvider>
1384
+ <CommandHostProvider value={host ?? null}>
1385
+ {/* The canvas the rail and the sidebar sit on (`--shell-canvas`): `--bg-sidebar`, darker in a dark theme, where
1386
+ the window is a little lighter (`--shell-window`), so the window stands out in any theme (`light-dark()`
1387
+ follows the theme's `color-scheme`); or the current workspace's paint (`--shell-paint`, ./look.ts) in the mode
1388
+ shown, else the rendering's canvas (its `canvas`, `data-paint="theme"`): on what is drawn on it
1389
+ (`data-canvas-ink`), the ink its colours ask for (`data-ink`: light on the tint and the rendering's canvas, the
1390
+ theme's under a wallpaper's frost). An empty slot's placeholder (the slot platform's own markup), centred in
1391
+ kit colours. */}
1392
+ <div
1393
+ data-slot="shell"
1394
+ data-paint={
1395
+ over ? 'tint' : (canvasOf(current?.look) ?? (themeCanvas ? 'theme' : undefined))
1396
+ }
1397
+ data-wallpaper={over ? undefined : wallpaperOf(current?.look)?.fit}
1398
+ data-wallpaper-ink={over ? undefined : sidebarInk}
1399
+ data-ink={
1400
+ over
1401
+ ? 'light'
1402
+ : wallpaperOf(current?.look) !== undefined
1403
+ ? undefined
1404
+ : canvasOf(current?.look) !== undefined
1405
+ ? inkOf(current?.look, mode, rgbOf)
1406
+ : themeCanvas
1407
+ ? 'light'
1408
+ : undefined
1409
+ }
1410
+ data-remote-shown={over || undefined}
1411
+ style={
1412
+ {
1413
+ '--shell-canvas':
1414
+ 'light-dark(var(--bg-sidebar), color-mix(in oklch, var(--bg-sidebar), black 35%))',
1415
+ '--shell-window': 'light-dark(var(--bg), color-mix(in oklch, var(--bg), white 3%))',
1416
+ ...titleBarInsets,
1417
+ ...(themeCanvas && { '--shell-paint': themeCanvas, '--shell-canvas': themeCanvas }),
1418
+ ...(current && lookStyle(current.look, current.slug, mode, rgbOf, mineImageOf)),
1419
+ ...(over && { background: 'transparent' }),
1420
+ } as React.CSSProperties
1421
+ }
1422
+ className="fixed inset-0 flex overflow-hidden [background:var(--shell-paint,var(--shell-canvas))] text-foreground antialiased [&_[data-slot-placeholder]]:m-auto [&_[data-slot-placeholder]]:p-4 [&_[data-slot-placeholder]]:text-center [&_[data-slot-placeholder]]:text-sm [&_[data-slot-placeholder]]:text-secondary [&_[data-slot-placeholder]_a]:text-accent"
1423
+ >
1424
+ {/* Embedded in the desktop app, the room of the app's rail (`w-[60px]`, as the workspace rail); else the rail, on a
1425
+ tint while a remote page shows under this one. */}
1426
+ {embedded ? (
1427
+ <div
1428
+ data-slot="shell-rail-space"
1429
+ aria-hidden="true"
1430
+ className="h-full w-[60px] shrink-0"
1431
+ />
1432
+ ) : !railFilled ? null : (
1433
+ <div
1434
+ data-slot="shell-rail"
1435
+ className={`relative flex h-full shrink-0 flex-col pt-(--shell-top-left)${over ? ' bg-[rgb(14_14_20/0.45)]' : ''}`}
1436
+ >
1437
+ <TitleBarBand height="h-(--shell-top-left)" />
1438
+ {/* The sidebar column hidden, its controls go to the rail's bottom (above its status and Admin), its
1439
+ button last: at once, the rail growing them in while the column slides away. */}
1440
+ <div className="flex min-h-0 flex-1">
1441
+ {renderSlot(
1442
+ 'rail',
1443
+ inRail
1444
+ ? {
1445
+ controls: (
1446
+ <ShellControls
1447
+ shell={shell}
1448
+ slots={slots}
1449
+ help={help}
1450
+ chooser={chooser}
1451
+ themeMenu={themeMenu}
1452
+ extra={renderSlot('controls', {})}
1453
+ hasWallpaper={kept !== undefined}
1454
+ inRail
1455
+ />
1456
+ ),
1457
+ sidebarToggle: state.sidebarFilled && (
1458
+ <SidebarToggle
1459
+ sidebarHidden
1460
+ onSidebarHidden={(hidden) => shell.setSidebarHidden(hidden)}
1461
+ />
1462
+ ),
1463
+ }
1464
+ : {},
1465
+ )}
1466
+ </div>
1467
+ </div>
1468
+ )}
1469
+ {/* The handle's container starts where the sidebar does; the kit's Sidebar reads `--sidebar-width`. */}
1470
+ <div
1471
+ className={`relative flex h-full min-w-0 flex-1${over ? ' invisible' : ''}`}
1472
+ style={{ '--sidebar-width': `${sidebarWidth}px` } as React.CSSProperties}
1473
+ >
1474
+ {/* The sidebar column, the sidebar's width even when nothing fills the slot: the slot (the kit's Sidebar
1475
+ transparent on the canvas), then a footer that never scrolls, the theme controls at its left. */}
1476
+ {/* Hidden (⌥B), the slot stays mounted (the sidebar keeps what it holds) and inert; the column slides to
1477
+ nothing, its content at its width, the stage growing beside it. */}
1478
+ <aside
1479
+ data-slot="shell-sidebar"
1480
+ data-canvas-ink=""
1481
+ data-sidebar-hidden={sidebarHidden || undefined}
1482
+ inert={inRail || undefined}
1483
+ onTransitionEnd={(event) => {
1484
+ if (event.target === event.currentTarget) setSliding(false);
1485
+ }}
1486
+ onTransitionCancel={(event) => {
1487
+ if (event.target === event.currentTarget) setSliding(false);
1488
+ }}
1489
+ className={
1490
+ embedded && sidebarHidden
1491
+ ? 'flex h-full shrink-0 flex-col justify-end px-2 pb-3'
1492
+ : `relative flex h-full min-h-0 shrink-0 flex-col overflow-hidden pt-(--shell-top-left) [&_[data-slot=sidebar]]:bg-transparent ${inRail ? 'w-0' : 'w-(--sidebar-width)'}${sliding ? ' transition-[width] duration-250 ease-[cubic-bezier(0.2,0,0,1)] motion-reduce:transition-none' : ''}`
1493
+ }
1494
+ >
1495
+ {!(embedded && sidebarHidden) && <TitleBarBand height="h-(--shell-top-left)" />}
1496
+ <div
1497
+ className={
1498
+ embedded && sidebarHidden
1499
+ ? 'hidden'
1500
+ : 'flex min-h-0 w-(--sidebar-width) flex-1 flex-col'
1501
+ }
1502
+ >
1503
+ {/* No plugin in `sidebar`, nothing mounted there (no placeholder either, research-112). */}
1504
+ {state.sidebarFilled && renderSlot('sidebar', {})}
1505
+ </div>
1506
+ {/* Kept while the column slides away, as the rail grows its own in beside it. */}
1507
+ {(!inRail || sliding) && (
1508
+ <div
1509
+ data-slot="shell-sidebar-footer"
1510
+ className={
1511
+ embedded && sidebarHidden
1512
+ ? 'flex'
1513
+ : 'flex w-(--sidebar-width) shrink-0 items-center px-2 pb-3'
1514
+ }
1515
+ >
1516
+ <ShellControls
1517
+ shell={shell}
1518
+ slots={slots}
1519
+ help={help}
1520
+ chooser={chooser}
1521
+ themeMenu={themeMenu}
1522
+ extra={renderSlot('controls', {})}
1523
+ hasWallpaper={kept !== undefined}
1524
+ narrow={embedded && sidebarHidden}
1525
+ />
1526
+ </div>
1527
+ )}
1528
+ </aside>
1529
+ {/* The stage: `main`, on the canvas, nothing drawn: a window manager's windows and their margin, or the
1530
+ shell's one window, flat (`flatFrame`). */}
1531
+ <main
1532
+ data-slot="shell-stage"
1533
+ className="relative flex min-h-0 min-w-0 flex-1 pt-(--shell-top)"
1534
+ >
1535
+ <TitleBarBand height="h-(--shell-top)" />
1536
+ {renderSlot('main', {})}
1537
+ </main>
1538
+ {!sidebarHidden && (
1539
+ <SidebarResizeHandle width={sidebarWidth} onWidthChange={setSidebarWidth} />
1540
+ )}
1541
+ </div>
1542
+ </div>
1543
+ {/* Over the whole frame: floating tools (`point`'s selections and windows), each positioned by its plugin; hidden
1544
+ (kept mounted) while a remote page shows under this one, where they would cover the rail. */}
1545
+ <div data-slot="shell-overlay" className={over ? 'hidden' : 'contents'}>
1546
+ {renderSlot('overlay', {})}
1547
+ </div>
1548
+ <ShortcutsHelp shell={shell} help={help} app={app} />
1549
+ <ErrorsModal
1550
+ hostStatus={hostStatus}
1551
+ errors={errors}
1552
+ openSetting={shell.openSetting}
1553
+ showHealth={shell.showHealth}
1554
+ />
1555
+ <ActionConfirm />
1556
+ <Approvals shell={shell} review={review} hostStatus={hostStatus} />
1557
+ </CommandHostProvider>
1558
+ </TooltipProvider>
1559
+ </ToastProvider>
1560
+ );
1561
+ }
1562
+
1563
+ /** The titles plugins give their items (`ctx.screen.title`, the boot kernel's), set by `apply`: a window's bar names
1564
+ * its item. */
1565
+ const noTitles = new Map<string, ReadonlyMap<string, { title: string }>>();
1566
+ let itemTitles: Context['screenRequests']['titles'] = {
1567
+ get: () => noTitles,
1568
+ subscribe: () => () => {},
1569
+ };
1570
+
1571
+ /** The page's click listeners (research-048). `beside`, seen before the page handles a click (capture): a ⌘-click
1572
+ * (Ctrl-click) opens the view it causes in a new window (W8), an ⌥-click on a new desk; ⇧ with them (⌥⇧: Point's,
1573
+ * ⌘⇧: reserved) arms nothing. Without a window manager, that view change does nothing (`setScreen`). `follow`, for
1574
+ * internal links (a link of this origin naming the current workspace, `/<slug>/…` by the URL's rules): its view
1575
+ * without a page load, by Bridge's rule (`shell.follow`): plain in the focused window, ⌘ or a middle click in a new
1576
+ * window (not a browser tab), ⌥ on a new desk, ⇧ nothing (reserved, not the browser's new window). Seen once the page
1577
+ * had its say: a link whose click a plugin handled is left alone; other links (another origin or workspace, a node the
1578
+ * tree lacks, a query string that is no screen state, `download`, a plain click to another target) keep the browser's
1579
+ * way. */
1580
+ export function clickListeners(
1581
+ shell: Pick<Shell, 'viewAt' | 'follow'> & { besideNext(): void; deskNext(): void },
1582
+ ) {
1583
+ const beside = (event: MouseEvent) => {
1584
+ if (event.shiftKey) return;
1585
+ if (event.metaKey || event.ctrlKey) shell.besideNext();
1586
+ else if (event.altKey) shell.deskNext();
1587
+ };
1588
+ const follow = (event: MouseEvent) => {
1589
+ if (event.defaultPrevented) return;
1590
+ const middle = event.type === 'auxclick' && event.button === 1;
1591
+ const modified = event.metaKey || event.ctrlKey || event.altKey || event.shiftKey;
1592
+ if (!middle && !(event.type === 'click' && event.button === 0)) return;
1593
+ const link = event.target instanceof Element ? event.target.closest('a[href]') : null;
1594
+ if (!(link instanceof HTMLAnchorElement) || link.hasAttribute('download')) return;
1595
+ if (!middle && !modified && link.target !== '' && link.target !== '_self') return;
1596
+ const url = new URL(link.href, location.href);
1597
+ if (url.origin !== location.origin || (url.hash !== '' && url.pathname === location.pathname))
1598
+ return;
1599
+ // A query is a screen's state (research-090, as `hrefOf` writes it), on a screen; any other keeps the browser's way.
1600
+ const screenState = screenStateOf(Object.fromEntries(url.searchParams));
1601
+ if (url.search !== '' && !screenState) return;
1602
+ const at = shell.viewAt(url.pathname);
1603
+ if (!at || (screenState && !at.screen)) return;
1604
+ const view = screenState ? { ...at, screenState } : at;
1605
+ event.preventDefault();
1606
+ shell.follow(view, event);
1607
+ };
1608
+ return { beside, follow };
1609
+ }
1610
+
1611
+ export function apply(ctx: Context) {
1612
+ itemTitles = ctx.screenRequests.titles;
1613
+ setSidebarItems(ctx.sidebarItems);
1614
+ // The active window manager (research-018 WM3): the `stage` entry that renders and the `windowManager` service; read
1615
+ // on each call, so one disabled, replaced, or added is followed. The look decides (WM5, research-028 CAP-6: the user's
1616
+ // Mine over the workspace's proposal): "None", none; one installed, its `stage` entry renders, even when another's
1617
+ // comes first in the slot; one no longer installed, the default (the slot's head). Its service is used only when
1618
+ // that same plugin provides it; without it, its stage still renders (the shell routing nothing to it).
1619
+ const manager = (): ManagerRef | undefined => {
1620
+ const plugin = stagePlugin();
1621
+ const provider = ctx.reflect._getImpl('windowManager', false);
1622
+ if (plugin === undefined || provider?.ctx.fiber.name !== plugin || !provider.value)
1623
+ return undefined;
1624
+ return { service: provider.value as ManagerRef['service'], plugin };
1625
+ };
1626
+ /** The window manager whose `stage` entry renders: the one the current workspace's look names (the user's Mine over
1627
+ * its proposal) when installed, else the default (the slot's head); none for "None" or without any. */
1628
+ const stagePlugin = (): string | undefined => {
1629
+ const { managerChoice: own, current } = shell.get();
1630
+ const choice = managerOf(own, current?.look);
1631
+ if (choice === null) return undefined;
1632
+ if (choice !== undefined && liveStages(ctx.slots).some((entry) => entry.registrant === choice))
1633
+ return choice;
1634
+ return ctx.slots.entriesOfSlot('stage')[0]?.registrant;
1635
+ };
1636
+ const app = inApp();
1637
+ const shortcuts = createShortcuts({ app });
1638
+ // The approval modal's review requests (research-031): the shell service emits, the modal subscribes.
1639
+ const review = createReview();
1640
+ /** The `commands` service (research-034), followed as a plugin provides or disposes it. */
1641
+ const commands: CommandsService = {
1642
+ get: () => ctx.get('commands') as Context['commands'] | undefined,
1643
+ subscribe: (listener) =>
1644
+ ctx.on('internal/service', (name) => {
1645
+ if (name === 'commands') listener();
1646
+ }),
1647
+ };
1648
+ const created = createShell(
1649
+ ctx.workspaceEntries,
1650
+ ctx.screenRequests.isItemSegment,
1651
+ manager,
1652
+ shortcuts,
1653
+ {
1654
+ mineOf,
1655
+ setMineFields,
1656
+ setMode,
1657
+ themeOfMode,
1658
+ subscribe: subscribeClientAppearance,
1659
+ mode: () => getClientAppearance().prefs.mode,
1660
+ // The user's look everywhere (research-035): only the desktop app keeps one for every Bridge.
1661
+ everywhere: () => (window.bridgeAppearance ? everywhereOf() : {}),
1662
+ has: (field, value) =>
1663
+ field === 'style'
1664
+ ? value === DEFAULT_KIT || getRenderings().some((each) => each.id === value)
1665
+ : field === 'icons'
1666
+ ? value === DEFAULT_ICON_SET || getIconSets().some((each) => each.id === value)
1667
+ : value === 'none' ||
1668
+ ctx.slots.entries('stage').some((each) => each.registrant === value),
1669
+ },
1670
+ review,
1671
+ );
1672
+ const help = signal();
1673
+ const chooser = signal();
1674
+ const errors = errorsSignal();
1675
+ const plain = { metaKey: false, ctrlKey: false, altKey: false, shiftKey: false };
1676
+ /** `view` of workspace `slug`, by Bridge's rule for `event` (none: a plain click). Another workspace than the one shown:
1677
+ * entered first, the view shown there or, a modified click, opened beside there (`openIn`, research-048). */
1678
+ const go = (slug: string, view: View, event?: FollowEvent) =>
1679
+ created.openIn(slug, view, event ?? plain);
1680
+
1681
+ // `showErrors` (./shell.d.ts) opens the modal this component tree mounts, so it is wired here.
1682
+ const shell = Object.assign(created, {
1683
+ showErrors: (key?: string) => errors.emit(key),
1684
+ showShortcuts: () => help.emit(),
1685
+ nodeActions: createNodeActions(),
1686
+ /** Open the setting (research-046): Settings on that plugin's field, in its workspace (a toast's fix, Health's);
1687
+ * `event`, the click's, followed by Bridge's rule (research-048). */
1688
+ openSetting(slug: string, plugin: string, setting: string, event?: FollowEvent) {
1689
+ // Bridge's own plugins (`_host`) are Admin's, under its Bridge root.
1690
+ go(
1691
+ slug === '_host' ? 'admin' : slug,
1692
+ {
1693
+ node: 'root',
1694
+ screen: { plugin: 'plugin-manager', id: 'settings' },
1695
+ // No field (`service_waiting`'s fix): the plugin's settings page.
1696
+ item: setting === '' ? `${slug}/${plugin}` : `${slug}/${plugin}/${setting}`,
1697
+ },
1698
+ event,
1699
+ );
1700
+ },
1701
+ /** Opens plugin `plugin`'s Logs tab (its id) in workspace `slug`'s Plugins screen, a navigation entry: the records up
1702
+ * to `until` (an ISO time, a Health episode's), else its live log. */
1703
+ openBridgeLogs(item?: string, event?: FollowEvent) {
1704
+ go(
1705
+ 'admin',
1706
+ {
1707
+ node: 'root',
1708
+ screen: { plugin: 'bridge-settings', id: 'logs' },
1709
+ ...(item !== undefined && { item }),
1710
+ },
1711
+ event,
1712
+ );
1713
+ },
1714
+ openLogs(slug: string, plugin: string, until?: string, event?: FollowEvent) {
1715
+ go(
1716
+ slug === '_host' ? 'admin' : slug,
1717
+ {
1718
+ node: 'root',
1719
+ screen: { plugin: 'plugin-manager', id: 'plugins' },
1720
+ item: `${slug}/${plugin}/logs${until === undefined ? '' : `/${until}`}`,
1721
+ },
1722
+ event,
1723
+ );
1724
+ },
1725
+ /** Runs plugin `plugin`'s settings action `fix.action` in workspace `slug` (a Health row's fix), its `confirm`
1726
+ * asked first. */
1727
+ runAction(
1728
+ slug: string,
1729
+ plugin: string,
1730
+ fix: { action: string; label: string; confirm?: string },
1731
+ ) {
1732
+ runFix(
1733
+ {
1734
+ action: 'plugin-action',
1735
+ slug,
1736
+ plugin,
1737
+ id: fix.action,
1738
+ label: fix.label,
1739
+ ...(fix.confirm !== undefined && { confirm: fix.confirm }),
1740
+ },
1741
+ fix.label,
1742
+ () => '',
1743
+ );
1744
+ },
1745
+ showStatus: () => showStatus(shell),
1746
+ /** Admin's Health screen (research-047), on its open problems. */
1747
+ showHealth(event?: FollowEvent) {
1748
+ if (created.get().current?.slug === 'admin' || event)
1749
+ return go(
1750
+ 'admin',
1751
+ { node: 'root', screen: { plugin: 'bridge-settings', id: 'health' } },
1752
+ event,
1753
+ );
1754
+ history.pushState(null, '', '/admin/root/health');
1755
+ created.setCurrent('admin');
1756
+ },
1757
+ });
1758
+ // On a phone, a change of view reaches the page through a view transition (./mobile.tsx); its window listener goes
1759
+ // when the shell does.
1760
+ const stopTransitions = transitions(shell);
1761
+ ctx.effect(() => stopTransitions);
1762
+ // The change of workspace drawn as the shell's setting says (./transition.ts), read from `_host`'s root and followed
1763
+ // live; an older Bridge without `hostNodes`: the default.
1764
+ let transition: Transition = defaultTransition;
1765
+ let duration = durations.default;
1766
+ // The theme menu's button (`themeMenu`, Legacy): off by default, followed live like the transition.
1767
+ let showThemeMenu = false;
1768
+ const themeMenuChanged = signal();
1769
+ const themeMenu: ThemeMenu = {
1770
+ get: () => showThemeMenu,
1771
+ subscribe: themeMenuChanged.subscribe,
1772
+ };
1773
+ const hostNodes = ctx.get('hostNodes') as Context['nodes'] | undefined;
1774
+ if (hostNodes) {
1775
+ const follow = () => {
1776
+ const values = hostNodes.settings(name, 'root')?.values;
1777
+ transition = readTransition(values);
1778
+ duration = readDuration(values);
1779
+ const next = values?.themeMenu?.value === true;
1780
+ if (next !== showThemeMenu) {
1781
+ showThemeMenu = next;
1782
+ themeMenuChanged.emit();
1783
+ }
1784
+ };
1785
+ follow();
1786
+ ctx.effect(() => {
1787
+ const unfollow = hostNodes.subscribe(follow);
1788
+ return () => {
1789
+ unfollow();
1790
+ transition = defaultTransition;
1791
+ duration = durations.default;
1792
+ };
1793
+ });
1794
+ }
1795
+ const setCurrent = shell.setCurrent;
1796
+ shell.setCurrent = (slug) => {
1797
+ const { workspaces, current } = shell.get();
1798
+ if (slug === current?.slug) return setCurrent(slug);
1799
+ transitionTo(
1800
+ ownTransition(getClientAppearance().prefs.workspaceTransition) ?? transition,
1801
+ duration,
1802
+ directionOf(
1803
+ workspaces.map((each) => each.slug),
1804
+ current?.slug,
1805
+ slug,
1806
+ ),
1807
+ () => setCurrent(slug),
1808
+ );
1809
+ };
1810
+ ctx.provide('shell', shell);
1811
+ // What this page has changes (a pack, an icon set, a window manager comes or goes): the looks again, the user's look
1812
+ // everywhere applying where it now can (research-035).
1813
+ ctx.effect(() => {
1814
+ const again = () => shell.looksAgain();
1815
+ const off = [
1816
+ subscribeRenderings(again),
1817
+ subscribeIconSets(again),
1818
+ ctx.slots.subscribe('stage', again),
1819
+ ];
1820
+ return () => off.forEach((each) => each());
1821
+ });
1822
+ // Disposed, the shell stops updating: listeners removed, a refresh in flight dropped.
1823
+ // The keyboard layout's letters (an AZERTY ⌥W is at QWERTY's Z): the browser's map where it tells it (a secure page:
1824
+ // the app, localhost; read again on each return to the page), else learnt from the letters typed (`learnLayout`),
1825
+ // kept for this browser, else guessed from the browser's languages (`guessLayout`: a Belgian Mac is AZERTY).
1826
+ const keyboard = (
1827
+ navigator as Navigator & {
1828
+ keyboard?: { getLayoutMap?: () => Promise<ReadonlyMap<string, string>> };
1829
+ }
1830
+ ).keyboard;
1831
+ ctx.effect(() => {
1832
+ let learnt = readLearnt();
1833
+ let told = false;
1834
+ shortcuts.setLayout(
1835
+ learnt.size ? learnt : guessLayout(navigator.languages ?? [navigator.language]),
1836
+ );
1837
+ const readLayout = () =>
1838
+ void keyboard?.getLayoutMap?.().then(
1839
+ (map) => {
1840
+ told = true;
1841
+ shortcuts.setLayout(map);
1842
+ },
1843
+ () => {},
1844
+ );
1845
+ const learn = (event: KeyboardEvent) => {
1846
+ if (told) return;
1847
+ const next = learnLayout(learnt, event);
1848
+ if (next === learnt) return;
1849
+ learnt = next;
1850
+ shortcuts.setLayout(learnt);
1851
+ try {
1852
+ localStorage.setItem(layoutKey, JSON.stringify([...learnt]));
1853
+ } catch {
1854
+ /* learnt again next time */
1855
+ }
1856
+ };
1857
+ readLayout();
1858
+ window.addEventListener('focus', readLayout);
1859
+ window.addEventListener('keydown', learn, true);
1860
+ return () => {
1861
+ window.removeEventListener('focus', readLayout);
1862
+ window.removeEventListener('keydown', learn, true);
1863
+ };
1864
+ });
1865
+ ctx.effect(() => {
1866
+ const refresh = () => void shell.refresh();
1867
+ window.addEventListener('focus', refresh);
1868
+ window.addEventListener('popstate', shell.followUrl);
1869
+ refresh();
1870
+ const unsubscribe = followStatus(ctx.hostStatus.subscribe, {
1871
+ refresh,
1872
+ nodesChanged: shell.nodesChanged,
1873
+ });
1874
+ // A plugin opens an item of its screen shown (`shell.openItem`).
1875
+ const unrequest = ctx.screenRequests.subscribe(shell.openItem);
1876
+ const { beside, follow } = clickListeners(shell);
1877
+ window.addEventListener('click', beside, true);
1878
+ window.addEventListener('click', follow);
1879
+ window.addEventListener('auxclick', follow);
1880
+ // C5: the shortcuts registered (a window manager's), seen before the page (a tree's arrows, a field's ⌥←: the
1881
+ // window's key wins, and goes no further); `?` outside a field opens their help, unless the page used it.
1882
+ const keydown = (event: KeyboardEvent) => {
1883
+ // Not while composing text, nor under a modal dialog (the help, a confirmation): its keys are its own.
1884
+ if (event.isComposing || modalOpen()) return;
1885
+ if (!shortcuts.dispatch(event)) return;
1886
+ event.preventDefault();
1887
+ event.stopPropagation();
1888
+ };
1889
+ const question = (event: KeyboardEvent) => {
1890
+ if (
1891
+ event.defaultPrevented ||
1892
+ event.isComposing ||
1893
+ event.key !== '?' ||
1894
+ event.altKey ||
1895
+ event.metaKey ||
1896
+ event.ctrlKey ||
1897
+ isEditable(event.target)
1898
+ )
1899
+ return;
1900
+ event.preventDefault();
1901
+ help.emit();
1902
+ };
1903
+ window.addEventListener('keydown', keydown, true);
1904
+ window.addEventListener('keydown', question);
1905
+ // A new `stage` entry (a manager added, reloaded, or enabled again) is told the current view; one crashing is set
1906
+ // aside (C6): the shell's one window, this page on none until the user chooses, a new entry comes, or a reload.
1907
+ let winner: unknown;
1908
+ const staged = () => {
1909
+ const entry = ctx.slots.entriesOfSlot('stage')[0];
1910
+ if (entry === undefined || entry === winner) return;
1911
+ winner = entry;
1912
+ shell.managerChanged();
1913
+ };
1914
+ const unstage = ctx.slots.subscribe('stage', staged);
1915
+ staged();
1916
+ const uncrash = ctx.slots.onEntryError((key, registration, error) => {
1917
+ if (key === 'stage') crashedStages.add(registration);
1918
+ if (key === 'stage')
1919
+ shell.managerCrashed(
1920
+ ('registrant' in registration && registration.registrant) || undefined,
1921
+ error,
1922
+ );
1923
+ });
1924
+ return () => {
1925
+ shell.stop();
1926
+ unsubscribe();
1927
+ unrequest();
1928
+ unstage();
1929
+ uncrash();
1930
+ window.removeEventListener('click', beside, true);
1931
+ window.removeEventListener('click', follow);
1932
+ window.removeEventListener('auxclick', follow);
1933
+ window.removeEventListener('keydown', keydown, true);
1934
+ window.removeEventListener('keydown', question);
1935
+ window.removeEventListener('focus', refresh);
1936
+ window.removeEventListener('popstate', shell.followUrl);
1937
+ };
1938
+ });
1939
+ // Whether a plugin fills `sidebar`: none, no column (another navigator, the Start menu, in its place).
1940
+ // A filler that is a navigator (research-035) shows only when the look's `navigation` shows it.
1941
+ ctx.effect(() => {
1942
+ const update = () => {
1943
+ const filler = ctx.slots.entriesOfSlot('sidebar')[0];
1944
+ const id = filler?.registrant;
1945
+ const isNavigator = shell.get().navigators.some((each) => each.id === id);
1946
+ shell.sidebarFilled(!!filler && (!isNavigator || shell.navigatorShown(id!)));
1947
+ };
1948
+ update();
1949
+ const unslot = ctx.slots.subscribe('sidebar', update);
1950
+ const unshell = shell.subscribe(update);
1951
+ return () => {
1952
+ unslot();
1953
+ unshell();
1954
+ };
1955
+ });
1956
+ // ⌥B hides or shows the sidebar column; hidden, the theme controls stand under the rail.
1957
+ ctx.effect(() =>
1958
+ shortcuts.register(
1959
+ {
1960
+ keys: 'Alt+KeyB',
1961
+ label: 'Show or hide the sidebar',
1962
+ run: () => {
1963
+ if (shell.get().sidebarFilled) shell.setSidebarHidden(!shell.get().sidebarHidden);
1964
+ },
1965
+ },
1966
+ name,
1967
+ ),
1968
+ );
1969
+ const slot = { kind: 'single', scope: 'root' } as const;
1970
+ // `sidebar` and `controls` are open to the shown workspace's plugins (research-046): a workspace may bring its own
1971
+ // navigator (a sidebar, a Start button), ahead of `_host`'s, which stays behind it as the fallback.
1972
+ const open = { workspace: true } as const;
1973
+ ctx.slots.register(
1974
+ {
1975
+ name: 'root',
1976
+ priority: 10,
1977
+ children: {
1978
+ rail: slot,
1979
+ sidebar: { ...slot, ...open },
1980
+ main: slot,
1981
+ overlay: { kind: 'list', scope: 'root' },
1982
+ controls: { kind: 'list', scope: 'root', ...open },
1983
+ },
1984
+ },
1985
+ ({ renderSlot }) =>
1986
+ window.bridgeDesktop?.toastView ? (
1987
+ <ToastView desktop={window.bridgeDesktop} />
1988
+ ) : (
1989
+ <PackThemesProvider value={packThemeRoutes}>
1990
+ <RootFrame
1991
+ shell={shell}
1992
+ slots={ctx.slots}
1993
+ hostStatus={ctx.hostStatus}
1994
+ help={help}
1995
+ chooser={chooser}
1996
+ review={review}
1997
+ app={app}
1998
+ errors={errors}
1999
+ renderSlot={renderSlot}
2000
+ commands={commands}
2001
+ themeMenu={themeMenu}
2002
+ />
2003
+ </PackThemesProvider>
2004
+ ),
2005
+ );
2006
+ // At 10: a `_host` plugin fills `main` in its place at a lower priority. Known limit: `screen` is
2007
+ // declared by this entry only (a second declarer is refused), so such a replacement cannot render
2008
+ // workspace screens. `stage` (single) is where a window manager lays out the windows (research-018 WM2).
2009
+ ctx.slots.register(
2010
+ {
2011
+ name: 'main',
2012
+ priority: 10,
2013
+ children: {
2014
+ screen: { kind: 'keyed', scope: 'root' },
2015
+ stage: slot,
2016
+ dialogs: { kind: 'list', scope: 'root' },
2017
+ // A screen's phone variant (research-020 C): the same owner as `screen`, rendered on a phone in its place.
2018
+ mobileScreen: { kind: 'keyed', scope: 'root' },
2019
+ },
2020
+ },
2021
+ ({ renderSlot }) => (
2022
+ <Main shell={shell} stagePlugin={stagePlugin} chooser={chooser} renderSlot={renderSlot} />
2023
+ ),
2024
+ );
2025
+ }