@1agh/maude 2.0.4 → 2.0.6

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.
Files changed (129) hide show
  1. package/apps/hub/src/project-transactions/kernel.mjs +10 -1
  2. package/apps/studio/access/filters.ts +12 -5
  3. package/apps/studio/access/known-canvases.ts +24 -1
  4. package/apps/studio/access/refused-inputs.ts +89 -0
  5. package/apps/studio/actions/agents.ts +5 -0
  6. package/apps/studio/actions/defs/app.ts +12 -0
  7. package/apps/studio/actions.manifest.json +13 -1
  8. package/apps/studio/actions.parity.json +7 -1
  9. package/apps/studio/annotations/ui/element-node.tsx +139 -54
  10. package/apps/studio/annotations/ui/lod.tsx +1 -1
  11. package/apps/studio/annotations/ui/text-style.ts +1 -1
  12. package/apps/studio/annotations-layer.tsx +0 -12
  13. package/apps/studio/api.ts +42 -0
  14. package/apps/studio/artboard-live-gate.tsx +267 -0
  15. package/apps/studio/artboard-live.ts +336 -0
  16. package/apps/studio/artboard-webgl.ts +668 -0
  17. package/apps/studio/bin/_agent-browser-bin.mjs +8 -0
  18. package/apps/studio/bin/_agent-browser-safe.mjs +2 -1
  19. package/apps/studio/bin/_canvas-reasons.mjs +34 -0
  20. package/apps/studio/bin/_ds-check-live.mjs +37 -0
  21. package/apps/studio/bin/_ds-check.mjs +4 -1
  22. package/apps/studio/bin/_ds-prove-judge.mjs +167 -0
  23. package/apps/studio/bin/_ds-prove-playwright.mjs +183 -105
  24. package/apps/studio/bin/_import-asset.mjs +2 -1
  25. package/apps/studio/bin/_perf-probe.mjs +2 -1
  26. package/apps/studio/bin/_studio-verb.mjs +24 -3
  27. package/apps/studio/bin/_thumb-blank.mjs +70 -0
  28. package/apps/studio/bin/_thumb-cover.mjs +35 -0
  29. package/apps/studio/bin/_thumbs-playwright.mjs +89 -12
  30. package/apps/studio/bin/ds-check.sh +5 -1
  31. package/apps/studio/bin/perf.sh +11 -1
  32. package/apps/studio/bin/server-up.sh +7 -2
  33. package/apps/studio/bin/smoke.sh +19 -0
  34. package/apps/studio/canvas-lib.tsx +131 -12
  35. package/apps/studio/client/canvas-url.js +13 -0
  36. package/apps/studio/client/home/HomeAccounts.jsx +262 -0
  37. package/apps/studio/client/home/Shelves.jsx +4 -3
  38. package/apps/studio/client/home/home-accounts-model.js +121 -0
  39. package/apps/studio/client/home/home-api.js +6 -0
  40. package/apps/studio/client/home/home-app.jsx +141 -40
  41. package/apps/studio/client/home/home-model.js +172 -6
  42. package/apps/studio/client/home/home.css +169 -5
  43. package/apps/studio/client/home/shell-mode.js +8 -1
  44. package/apps/studio/client/hooks/use-project-data.jsx +2 -0
  45. package/apps/studio/client/panels/ChatPanel.jsx +27 -20
  46. package/apps/studio/client/panels/CreateProject.jsx +19 -5
  47. package/apps/studio/client/panels/caps-cache.js +46 -0
  48. package/apps/studio/client/shell/viewport.jsx +36 -8
  49. package/apps/studio/client/v2/access/access-client.js +2 -0
  50. package/apps/studio/client/v2/access/access-host.jsx +12 -1
  51. package/apps/studio/client/v2/access/trashed-banner.jsx +6 -3
  52. package/apps/studio/client/v2/ai/Advanced.jsx +12 -0
  53. package/apps/studio/client/v2/ai/Composer.jsx +27 -10
  54. package/apps/studio/client/v2/code/canvas-imports-card.jsx +15 -14
  55. package/apps/studio/client/v2/code/canvas-imports-words.js +44 -0
  56. package/apps/studio/client/v2/code/code-bus.js +5 -0
  57. package/apps/studio/client/v2/ds/advanced-host.jsx +11 -26
  58. package/apps/studio/client/v2/ds/ds-refresh.js +161 -0
  59. package/apps/studio/client/v2/ds/library-host.jsx +45 -45
  60. package/apps/studio/client/v2/ds/make-host.jsx +13 -15
  61. package/apps/studio/client/v2/ds/off-system-host.jsx +18 -19
  62. package/apps/studio/client/v2/ds/review-host.jsx +7 -1
  63. package/apps/studio/client/v2/ds/truth-host.jsx +15 -17
  64. package/apps/studio/client/v2/ds/upgrade-host.jsx +26 -10
  65. package/apps/studio/client/v2/history/branch-actions.js +13 -9
  66. package/apps/studio/client/v2/history/git-advanced.jsx +8 -1
  67. package/apps/studio/client/v2/history/git-model.js +3 -1
  68. package/apps/studio/client/v2/history/git-parts.jsx +16 -1
  69. package/apps/studio/client/v2/presence/faces.jsx +42 -14
  70. package/apps/studio/client/v2/shell/account-card.jsx +10 -4
  71. package/apps/studio/client/v2/shell/canvas-crash-guard.js +137 -0
  72. package/apps/studio/client/v2/shell/github-signin-host.jsx +42 -0
  73. package/apps/studio/client/v2/shell/menu-runner.js +11 -0
  74. package/apps/studio/client/v2/shell/project-account-card.jsx +203 -0
  75. package/apps/studio/client/v2/shell/project-account-model.js +182 -0
  76. package/apps/studio/client/v2/shell/share-cluster-host.jsx +137 -10
  77. package/apps/studio/client/v2/shell/share-cluster.css +58 -0
  78. package/apps/studio/client/v2/shell/share-cluster.jsx +26 -7
  79. package/apps/studio/client/v2/shell/team-switch.js +94 -0
  80. package/apps/studio/client/v2/shell/too-heavy-card.jsx +38 -0
  81. package/apps/studio/client/v2/shell/use-account.js +8 -1
  82. package/apps/studio/collab/persistence.ts +9 -1
  83. package/apps/studio/collab/registry.ts +32 -0
  84. package/apps/studio/collab/room.ts +8 -0
  85. package/apps/studio/config-reload-wire.ts +53 -0
  86. package/apps/studio/dist/client.bundle.js +1232 -1232
  87. package/apps/studio/dist/styles.css +1 -1
  88. package/apps/studio/ds/board/specimen.tsx +12 -1
  89. package/apps/studio/ds/canvas-cli.ts +58 -2
  90. package/apps/studio/ds/check.ts +26 -1
  91. package/apps/studio/ds/cli.ts +7 -3
  92. package/apps/studio/ds/convert.ts +34 -6
  93. package/apps/studio/ds/ds-verb.ts +13 -0
  94. package/apps/studio/ds/post-build.ts +38 -0
  95. package/apps/studio/ds/upgrade-apply.ts +27 -5
  96. package/apps/studio/ds/upgrade-cli.ts +22 -2
  97. package/apps/studio/ds/upgrade-prove.ts +198 -15
  98. package/apps/studio/ds/upgrade-stage.ts +4 -1
  99. package/apps/studio/history/trash.ts +6 -0
  100. package/apps/studio/home/accounts.ts +87 -0
  101. package/apps/studio/home/index-reader.ts +24 -2
  102. package/apps/studio/home/routes.ts +19 -0
  103. package/apps/studio/http.ts +14 -2
  104. package/apps/studio/routes/ds-convert.ts +18 -0
  105. package/apps/studio/routes/trash.ts +16 -1
  106. package/apps/studio/server.ts +8 -10
  107. package/apps/studio/sync/accepted-cold-start.ts +28 -13
  108. package/apps/studio/sync/asset-push.ts +146 -23
  109. package/apps/studio/sync/asset-state.ts +3 -2
  110. package/apps/studio/sync/file-membership.ts +28 -3
  111. package/apps/studio/sync/file-plane.ts +40 -9
  112. package/apps/studio/sync/file-pull.ts +304 -33
  113. package/apps/studio/sync/hub-link.ts +1 -2
  114. package/apps/studio/sync/index.ts +308 -150
  115. package/apps/studio/sync/journal-client.ts +94 -5
  116. package/apps/studio/sync/pending-deletes.ts +100 -0
  117. package/apps/studio/sync/projection.ts +77 -12
  118. package/apps/studio/sync/seed-progress.ts +12 -1
  119. package/apps/studio/sync/status.ts +3 -1
  120. package/apps/studio/thumbs/service.ts +12 -2
  121. package/apps/studio/thumbs/validate.ts +7 -0
  122. package/apps/studio/ui-prefs-migrate.ts +4 -0
  123. package/apps/studio/video-comp.tsx +23 -0
  124. package/apps/studio/whats-new.json +72 -0
  125. package/cli/lib/bash-guard.mjs +13 -1
  126. package/cli/lib/design-help.gen.mjs +1 -1
  127. package/cli/lib/design-hook.mjs +20 -0
  128. package/cli/lib/studio-locate.mjs +35 -10
  129. package/package.json +8 -8
@@ -0,0 +1,267 @@
1
+ /**
2
+ * @file artboard-live-gate.tsx — 2.0.5: the React half of artboard-live.ts
3
+ * @scope apps/studio/artboard-live-gate.tsx (used by canvas-lib.tsx's DCArtboardBody + DesignCanvas)
4
+ * @purpose One `LiveRegistry` + one `WebglBudget` per canvas document, fed by two shared
5
+ * IntersectionObservers. `ArtboardLiveGate` wraps an artboard's children: it hands them
6
+ * `useArtboardActive()` / `useArtboardSeen()`, pauses the artboard's `<video>`s and CSS
7
+ * animations while it sleeps, and in `light` mode mounts the children only while it is near
8
+ * (a placeholder of the last measured height stands in, so nothing reflows).
9
+ * `holdAllLive()` is the in-frame export's guarantee: every artboard live for the capture.
10
+ */
11
+
12
+ import {
13
+ createContext,
14
+ type ReactNode,
15
+ type RefObject,
16
+ useCallback,
17
+ useContext,
18
+ useEffect,
19
+ useLayoutEffect,
20
+ useRef,
21
+ useSyncExternalStore,
22
+ } from 'react';
23
+ import {
24
+ type ArtboardLiveState,
25
+ type LiveMode,
26
+ LiveRegistry,
27
+ NEAR_MARGIN,
28
+ resolveLiveMode,
29
+ } from './artboard-live.ts';
30
+ import { WebglBudget } from './artboard-webgl.ts';
31
+
32
+ const ALL_LIVE: ArtboardLiveState = { live: true, seen: true };
33
+ const LiveContext = createContext<ArtboardLiveState>(ALL_LIVE);
34
+
35
+ /**
36
+ * Is this artboard running live? `false` while it is offscreen or the canvas is zoomed out to its overview —
37
+ * pause a render loop, a video, a simulation. Always `true` outside an artboard, in captures and exports.
38
+ */
39
+ export function useArtboardActive(): boolean {
40
+ return useContext(LiveContext).live;
41
+ }
42
+
43
+ /**
44
+ * Has this artboard been near the viewport yet? Gate an expensive first mount on it (the design-system
45
+ * board's specimens do). Always `true` in captures and exports.
46
+ */
47
+ export function useArtboardSeen(): boolean {
48
+ return useContext(LiveContext).seen;
49
+ }
50
+
51
+ interface Runtime {
52
+ registry: LiveRegistry;
53
+ budget: WebglBudget | null;
54
+ near: IntersectionObserver | null;
55
+ visible: IntersectionObserver | null;
56
+ ids: WeakMap<Element, string>;
57
+ }
58
+
59
+ let runtime: Runtime | null = null;
60
+ let runtimeSearch: string | null = null;
61
+
62
+ function embedded(): boolean {
63
+ try {
64
+ return window.parent !== window;
65
+ } catch {
66
+ return true;
67
+ }
68
+ }
69
+
70
+ /** Test hook: forget the per-document runtime (the URL decides the mode at first use). */
71
+ export function resetArtboardLive(): void {
72
+ runtime = null;
73
+ runtimeSearch = null;
74
+ }
75
+
76
+ function getRuntime(): Runtime | null {
77
+ if (typeof window === 'undefined') return null;
78
+ if (runtime && runtimeSearch === window.location.search) return runtime;
79
+ const mode: LiveMode = resolveLiveMode({ search: window.location.search, embedded: embedded() });
80
+ runtimeSearch = window.location.search;
81
+ const schedule = (fn: () => void) =>
82
+ typeof requestAnimationFrame === 'function' ? requestAnimationFrame(fn) : setTimeout(fn, 16);
83
+ const registry = new LiveRegistry(mode, schedule);
84
+ const ids = new WeakMap<Element, string>();
85
+ let near: IntersectionObserver | null = null;
86
+ let visible: IntersectionObserver | null = null;
87
+ let budget: WebglBudget | null = null;
88
+ if (mode !== 'off' && typeof IntersectionObserver === 'function') {
89
+ near = new IntersectionObserver(
90
+ (entries) => {
91
+ for (const en of entries) {
92
+ const id = ids.get(en.target);
93
+ if (id) registry.setNear(id, en.isIntersecting);
94
+ }
95
+ },
96
+ { rootMargin: NEAR_MARGIN }
97
+ );
98
+ visible = new IntersectionObserver((entries) => {
99
+ for (const en of entries) {
100
+ const id = ids.get(en.target);
101
+ if (id) registry.setVisible(id, en.isIntersecting);
102
+ }
103
+ });
104
+ budget = new WebglBudget((id) => (id ? registry.isLive(id) : true));
105
+ budget.install(window as Window & typeof globalThis);
106
+ registry.onChange(() => budget?.update());
107
+ (window as unknown as { __maudeWebglStats?: () => unknown }).__maudeWebglStats = () => ({
108
+ ...budget?.stats(),
109
+ mode,
110
+ visible: registry.visibleCount(),
111
+ });
112
+ }
113
+ runtime = { registry, budget, near, visible, ids };
114
+ return runtime;
115
+ }
116
+
117
+ /** The mode this canvas document runs in. */
118
+ export function artboardLiveMode(): LiveMode {
119
+ return getRuntime()?.registry.mode ?? 'off';
120
+ }
121
+
122
+ /**
123
+ * Every artboard live for a capture, at once. Resolves after two frames (restored WebGL contexts and woken
124
+ * players draw again); call the returned release when the capture is done.
125
+ */
126
+ export async function holdAllLive(): Promise<() => void> {
127
+ const rt = getRuntime();
128
+ if (!rt || rt.registry.mode === 'off') return () => {};
129
+ const release = rt.registry.holdAllLive();
130
+ rt.budget?.apply();
131
+ if (typeof requestAnimationFrame === 'function')
132
+ await new Promise<void>((r) => requestAnimationFrame(() => requestAnimationFrame(() => r())));
133
+ return release;
134
+ }
135
+
136
+ /** Feeds the published (settle-cadence) zoom and the gesture flag. Renders nothing. */
137
+ export function ArtboardLiveFeed({ zoom, interacting }: { zoom: number; interacting: boolean }) {
138
+ useEffect(() => {
139
+ const rt = getRuntime();
140
+ if (!rt || rt.registry.mode === 'off') return;
141
+ rt.registry.setZoom(zoom);
142
+ }, [zoom]);
143
+ useEffect(() => {
144
+ const rt = getRuntime();
145
+ if (!rt || rt.registry.mode === 'off') return;
146
+ rt.registry.setInteracting(interacting);
147
+ // A settle can change which contexts are nearest the centre.
148
+ if (!interacting) rt.budget?.update();
149
+ }, [interacting]);
150
+ return null;
151
+ }
152
+
153
+ /** Pause what plays inside a sleeping artboard; resume what WE paused when it wakes. */
154
+ function useMediaSleep(articleRef: RefObject<HTMLElement | null>, live: boolean, on: boolean) {
155
+ const paused = useRef(new Set<HTMLMediaElement>());
156
+ useEffect(() => {
157
+ const el = articleRef.current;
158
+ if (!on || !el) return;
159
+ el.toggleAttribute('data-dc-asleep', !live);
160
+ // VideoComp drives its own Player (useArtboardActive); its <video>s are the Player's to sync.
161
+ const own = (m: Element) => !m.closest('.dc-video-comp');
162
+ if (!live) {
163
+ for (const m of el.querySelectorAll<HTMLMediaElement>('video')) {
164
+ if (!own(m) || m.paused) continue;
165
+ m.pause();
166
+ paused.current.add(m);
167
+ }
168
+ // An autoplay that starts later (data arrives after we slept) is paused too.
169
+ const onPlay = (ev: Event) => {
170
+ const m = ev.target as HTMLMediaElement;
171
+ if (m instanceof HTMLVideoElement && own(m)) {
172
+ m.pause();
173
+ paused.current.add(m);
174
+ }
175
+ };
176
+ el.addEventListener('play', onPlay, true);
177
+ return () => el.removeEventListener('play', onPlay, true);
178
+ }
179
+ for (const m of paused.current) if (m.isConnected) void m.play?.()?.catch?.(() => {});
180
+ paused.current.clear();
181
+ return undefined;
182
+ }, [articleRef, live, on]);
183
+ }
184
+
185
+ export function ArtboardLiveGate({
186
+ id,
187
+ articleRef,
188
+ bodyRef,
189
+ heightFloor,
190
+ children,
191
+ }: {
192
+ id: string;
193
+ articleRef: RefObject<HTMLElement | null>;
194
+ bodyRef: RefObject<HTMLElement | null>;
195
+ heightFloor: number;
196
+ children: ReactNode;
197
+ }) {
198
+ const rt = getRuntime();
199
+ const on = !!rt && rt.registry.mode !== 'off';
200
+ // Stable per (runtime, id): a new subscribe each render would drop the slot (and its near state) in between.
201
+ const subscribe = useCallback(
202
+ (fn: () => void) => (on && rt ? rt.registry.subscribe(id, fn) : () => {}),
203
+ [on, rt, id]
204
+ );
205
+ const state = useSyncExternalStore(
206
+ subscribe,
207
+ () => (on && rt ? rt.registry.get(id) : ALL_LIVE),
208
+ () => ALL_LIVE
209
+ );
210
+ const { live, seen } = state;
211
+
212
+ // Observe the artboard (the article — its size is stable whether its children are mounted or not).
213
+ useEffect(() => {
214
+ const el = articleRef.current;
215
+ if (!on || !rt || !el) return;
216
+ if (!rt.near || !rt.visible) {
217
+ // No IntersectionObserver: fail open, everything near and on screen.
218
+ rt.registry.setNear(id, true);
219
+ return;
220
+ }
221
+ rt.ids.set(el, id);
222
+ rt.near.observe(el);
223
+ rt.visible.observe(el);
224
+ return () => {
225
+ rt.near?.unobserve(el);
226
+ rt.visible?.unobserve(el);
227
+ rt.registry.setNear(id, false);
228
+ rt.registry.setVisible(id, false);
229
+ };
230
+ }, [articleRef, id, on, rt]);
231
+
232
+ useMediaSleep(articleRef, live, on);
233
+
234
+ // light mode: remember the height the children had, so the placeholder holds it.
235
+ const lastHeight = useRef(0);
236
+ useLayoutEffect(() => {
237
+ if (!seen) return;
238
+ const b = bodyRef.current;
239
+ return () => {
240
+ if (b) lastHeight.current = b.offsetHeight;
241
+ };
242
+ }, [seen, bodyRef]);
243
+
244
+ const value = on ? state : ALL_LIVE;
245
+ const mountChildren = !on || rt?.registry.mode !== 'light' || seen;
246
+ return (
247
+ <LiveContext.Provider value={value}>
248
+ {mountChildren ? (
249
+ children
250
+ ) : (
251
+ <div
252
+ className="dc-artboard-sleeping"
253
+ aria-hidden="true"
254
+ style={{ minHeight: Math.max(lastHeight.current, heightFloor) }}
255
+ />
256
+ )}
257
+ </LiveContext.Provider>
258
+ );
259
+ }
260
+
261
+ /** Paused CSS animations while asleep. (A released WebGL canvas's picture is an overlay: artboard-webgl.ts.) */
262
+ export const ARTBOARD_LIVE_CSS = `
263
+ .dc-artboard[data-dc-asleep] .dc-artboard-body *,
264
+ .dc-artboard[data-dc-asleep] .dc-artboard-body *::before,
265
+ .dc-artboard[data-dc-asleep] .dc-artboard-body *::after { animation-play-state: paused !important; }
266
+ .dc-artboard-sleeping { width: 100%; }
267
+ `;
@@ -0,0 +1,336 @@
1
+ /**
2
+ * @file artboard-live.ts — 2.0.5: heavy canvases must not crash the tab
3
+ * @scope apps/studio/artboard-live.ts (React-free core; the React half is artboard-live-gate.tsx)
4
+ * @purpose Decides which artboards of an open canvas run LIVE. A canvas with 88 three.js scenes or 30
5
+ * artboards of decoding video ran every one of them at once, and WebKit killed the page.
6
+ *
7
+ * An artboard is LIVE when it is near the viewport AND the canvas is not in its overview
8
+ * (zoomed out below `LIVE_MIN_ZOOM`, the annotation mosaic's own cut-over, or more than
9
+ * `LIVE_MAX_VISIBLE` artboards on screen at once). A sleeping artboard keeps its DOM and its
10
+ * size; what stops is its heavy content: WebGL contexts (lost, with a snapshot of the last
11
+ * frame), `<video>` (paused), CSS animations (paused), `VideoComp` players (paused) and anything
12
+ * a canvas gates on `useArtboardActive()`.
13
+ *
14
+ * Artboards come back a few per frame (`WAKE_PER_FRAME`) and only once a gesture settles, so a
15
+ * pan never pays for re-starting a dozen scenes at once. The first mount of an artboard's
16
+ * children waits for the same queue in `light` mode (and for `useArtboardSeen()` consumers —
17
+ * the design-system board's specimens), so a canvas never builds what nobody looked at.
18
+ *
19
+ * Captures render EVERYTHING: the mode is `off` for every headless/export render (top-level
20
+ * page, `?hide-chrome=1`, `?thumb-only=`), and the in-frame export (`export-capture`) wakes
21
+ * every artboard for the length of the capture (`forceAll`).
22
+ */
23
+
24
+ import { LOD_ZOOM } from './annotations/ui/lod.tsx';
25
+
26
+ /** Below this (published) zoom the canvas is in its overview: nothing runs live. Same cut-over as the annotation mosaic. */
27
+ export const LIVE_MIN_ZOOM = LOD_ZOOM;
28
+ /** More artboards than this on screen at once is an overview too, whatever the zoom. */
29
+ export const LIVE_MAX_VISIBLE = 16;
30
+ /** At most this many WebGL contexts per canvas stay live — well under the browsers' hard limit (~16). */
31
+ export const WEBGL_LIVE_CAP = 8;
32
+ /** How far past the viewport an artboard still counts as near (IntersectionObserver rootMargin). */
33
+ export const NEAR_MARGIN = '50%';
34
+ /** How many artboards wake (or first mount) per animation frame. */
35
+ export const WAKE_PER_FRAME = 3;
36
+
37
+ /**
38
+ * `off` — every artboard live, every child mounted (captures, exports, headless, tests): the pre-2.0.5 behaviour.
39
+ * `sleep` — the studio default: offscreen / overview artboards sleep, their DOM stays mounted.
40
+ * `light` — "Show visible artboards only" after a crash: an artboard's children mount only while it is live
41
+ * (near the viewport and the canvas not in its overview).
42
+ */
43
+ export type LiveMode = 'off' | 'sleep' | 'light';
44
+
45
+ /** The frame parameter that picks a mode explicitly (`?artboard-live=off|sleep|light`). */
46
+ export const LIVE_PARAM = 'artboard-live';
47
+
48
+ export function resolveLiveMode(env: { search: string; embedded: boolean }): LiveMode {
49
+ const p = new URLSearchParams(env.search);
50
+ // A capture — whoever asks for it — renders every artboard live. This wins over an explicit mode.
51
+ if (p.get('hide-chrome') === '1' || p.has('thumb-only')) return 'off';
52
+ const explicit = p.get(LIVE_PARAM);
53
+ if (explicit === 'off' || explicit === 'sleep' || explicit === 'light') return explicit;
54
+ // Only the studio frames a canvas. A top-level canvas page is a headless render (screenshot,
55
+ // smoke, canvas-rects, perf without --studio) or someone opening the shell URL by hand: all live.
56
+ return env.embedded ? 'sleep' : 'off';
57
+ }
58
+
59
+ /** The overview: zoomed out past the mosaic cut-over, or too many artboards on screen at once. */
60
+ export function inOverview(zoom: number, visibleCount: number): boolean {
61
+ return (zoom > 0 && zoom < LIVE_MIN_ZOOM) || visibleCount > LIVE_MAX_VISIBLE;
62
+ }
63
+
64
+ /** Whether one artboard should be live. `forceAll` (a capture in progress) always wins. */
65
+ export function decideLive(s: {
66
+ near: boolean;
67
+ zoom: number;
68
+ visibleCount: number;
69
+ forceAll: boolean;
70
+ }): boolean {
71
+ if (s.forceAll) return true;
72
+ if (!s.near) return false;
73
+ return !inOverview(s.zoom, s.visibleCount);
74
+ }
75
+
76
+ export interface ArtboardLiveState {
77
+ /** Runs its heavy content. */
78
+ live: boolean;
79
+ /** Its children may be mounted (always true in `sleep`/`off` once seen; follows `live` in `light`). */
80
+ seen: boolean;
81
+ }
82
+
83
+ interface Slot {
84
+ near: boolean;
85
+ visible: boolean;
86
+ admitted: boolean;
87
+ live: boolean;
88
+ /** The last state handed out — one object per change, so React's external store sees a stable snapshot. */
89
+ view: ArtboardLiveState;
90
+ subs: Set<(s: ArtboardLiveState) => void>;
91
+ }
92
+
93
+ const ASLEEP: ArtboardLiveState = Object.freeze({ live: false, seen: false });
94
+
95
+ const ALL_LIVE: ArtboardLiveState = Object.freeze({ live: true, seen: true });
96
+
97
+ /**
98
+ * One per canvas document. Fed by two IntersectionObservers (near / visible), the published zoom and the
99
+ * gesture flag; artboards subscribe by id. Sleeping is immediate; waking goes through a queue drained
100
+ * `WAKE_PER_FRAME` at a time on `schedule` (rAF in the browser), and holds while a gesture is in flight.
101
+ */
102
+ export class LiveRegistry {
103
+ readonly mode: LiveMode;
104
+ private slots = new Map<string, Slot>();
105
+ private zoom = 1;
106
+ private interacting = false;
107
+ private forceAll = 0;
108
+ private pending = new Set<string>();
109
+ private scheduled = false;
110
+ private readonly schedule: (fn: () => void) => void;
111
+ private listeners = new Set<() => void>();
112
+
113
+ constructor(mode: LiveMode, schedule: (fn: () => void) => void) {
114
+ this.mode = mode;
115
+ this.schedule = schedule;
116
+ }
117
+
118
+ get(id: string): ArtboardLiveState {
119
+ if (this.mode === 'off') return ALL_LIVE;
120
+ return this.slots.get(id)?.view ?? ASLEEP;
121
+ }
122
+
123
+ isLive(id: string): boolean {
124
+ return this.get(id).live;
125
+ }
126
+
127
+ /** Any change at all (the WebGL budget re-plans on it). */
128
+ onChange(fn: () => void): () => void {
129
+ this.listeners.add(fn);
130
+ return () => this.listeners.delete(fn);
131
+ }
132
+
133
+ subscribe(id: string, fn: (s: ArtboardLiveState) => void): () => void {
134
+ const s = this.slot(id);
135
+ s.subs.add(fn);
136
+ return () => {
137
+ s.subs.delete(fn);
138
+ if (s.subs.size === 0) {
139
+ this.slots.delete(id);
140
+ this.pending.delete(id);
141
+ this.recompute();
142
+ }
143
+ };
144
+ }
145
+
146
+ setNear(id: string, near: boolean): void {
147
+ const s = this.slot(id);
148
+ if (s.near === near) return;
149
+ s.near = near;
150
+ this.recompute();
151
+ }
152
+
153
+ setVisible(id: string, visible: boolean): void {
154
+ const s = this.slot(id);
155
+ if (s.visible === visible) return;
156
+ s.visible = visible;
157
+ this.recompute();
158
+ }
159
+
160
+ setZoom(zoom: number): void {
161
+ if (!Number.isFinite(zoom) || zoom === this.zoom) return;
162
+ this.zoom = zoom;
163
+ this.recompute();
164
+ }
165
+
166
+ setInteracting(on: boolean): void {
167
+ if (on === this.interacting) return;
168
+ this.interacting = on;
169
+ if (!on) this.kick();
170
+ }
171
+
172
+ /** A capture is running: everything live, NOW (no queue). Returns the release. */
173
+ holdAllLive(): () => void {
174
+ this.forceAll += 1;
175
+ this.recompute();
176
+ let released = false;
177
+ return () => {
178
+ if (released) return;
179
+ released = true;
180
+ this.forceAll -= 1;
181
+ this.recompute();
182
+ };
183
+ }
184
+
185
+ visibleCount(): number {
186
+ let n = 0;
187
+ for (const s of this.slots.values()) if (s.visible) n += 1;
188
+ return n;
189
+ }
190
+
191
+ private slot(id: string): Slot {
192
+ let s = this.slots.get(id);
193
+ if (!s) {
194
+ s = {
195
+ near: false,
196
+ visible: false,
197
+ admitted: false,
198
+ live: false,
199
+ view: ASLEEP,
200
+ subs: new Set(),
201
+ };
202
+ this.slots.set(id, s);
203
+ }
204
+ return s;
205
+ }
206
+
207
+ private target(s: Slot): { live: boolean; admitted: boolean } {
208
+ const force = this.forceAll > 0;
209
+ const live = decideLive({
210
+ near: s.near,
211
+ zoom: this.zoom,
212
+ visibleCount: this.visibleCount(),
213
+ forceAll: force,
214
+ });
215
+ // `sleep` mounts what came near and keeps it. `light` (after a crash) mounts only what is LIVE — near and
216
+ // not in the overview — so a zoomed-out view of 60 scenes mounts none of them, and unmounts what leaves.
217
+ const admitted =
218
+ this.mode === 'light' ? live : force || s.near || (this.mode === 'sleep' && s.admitted);
219
+ return { live, admitted };
220
+ }
221
+
222
+ private recompute(): void {
223
+ if (this.mode === 'off') return;
224
+ const force = this.forceAll > 0;
225
+ let changed = false;
226
+ for (const [id, s] of this.slots) {
227
+ const t = this.target(s);
228
+ const goesDown = (s.live && !t.live) || (s.admitted && !t.admitted);
229
+ const goesUp = (!s.live && t.live) || (!s.admitted && t.admitted);
230
+ if (goesDown && !goesUp) {
231
+ s.live = t.live;
232
+ s.admitted = t.admitted;
233
+ this.pending.delete(id);
234
+ this.notify(id, s);
235
+ changed = true;
236
+ } else if (goesUp) {
237
+ if (force) {
238
+ s.live = t.live;
239
+ s.admitted = t.admitted;
240
+ this.pending.delete(id);
241
+ this.notify(id, s);
242
+ changed = true;
243
+ } else {
244
+ // The part that goes down applies now; the part that goes up waits for the queue.
245
+ if (s.live && !t.live) {
246
+ s.live = false;
247
+ this.notify(id, s);
248
+ changed = true;
249
+ }
250
+ this.pending.add(id);
251
+ }
252
+ } else {
253
+ this.pending.delete(id);
254
+ }
255
+ }
256
+ if (changed) this.emit();
257
+ this.kick();
258
+ }
259
+
260
+ private kick(): void {
261
+ if (this.scheduled || this.pending.size === 0 || this.interacting) return;
262
+ this.scheduled = true;
263
+ this.schedule(() => {
264
+ this.scheduled = false;
265
+ this.drain();
266
+ });
267
+ }
268
+
269
+ /** One frame's worth of wakes. Exposed for tests (the browser drains on rAF). */
270
+ drain(): void {
271
+ if (this.interacting) return;
272
+ let n = 0;
273
+ let changed = false;
274
+ for (const id of [...this.pending]) {
275
+ if (n >= WAKE_PER_FRAME) break;
276
+ this.pending.delete(id);
277
+ const s = this.slots.get(id);
278
+ if (!s) continue;
279
+ const t = this.target(s);
280
+ if (t.live === s.live && t.admitted === s.admitted) continue;
281
+ s.live = t.live;
282
+ s.admitted = t.admitted;
283
+ this.notify(id, s);
284
+ changed = true;
285
+ n += 1;
286
+ }
287
+ if (changed) this.emit();
288
+ this.kick();
289
+ }
290
+
291
+ private notify(_id: string, s: Slot): void {
292
+ if (s.view.live === s.live && s.view.seen === s.admitted) return;
293
+ s.view = Object.freeze({ live: s.live, seen: s.admitted });
294
+ for (const fn of s.subs) fn(s.view);
295
+ }
296
+
297
+ private emit(): void {
298
+ for (const fn of this.listeners) fn();
299
+ }
300
+ }
301
+
302
+ // ── WebGL budget ───────────────────────────────────────────────────────────────────────────────────
303
+
304
+ export interface GlCandidate {
305
+ key: number;
306
+ /** Its artboard is live (a canvas outside any artboard counts as live). */
307
+ live: boolean;
308
+ /** Distance of its centre to the viewport centre, in screen px. */
309
+ distance: number;
310
+ /** Last time it was kept live (ms) — the LRU tie-break. */
311
+ lastLive: number;
312
+ /** Currently lost by us. */
313
+ lost: boolean;
314
+ }
315
+
316
+ /**
317
+ * Which contexts to lose and which to restore: of the live artboards' canvases, the `cap` nearest the
318
+ * viewport centre (ties: most recently live) stay; every other context is released.
319
+ */
320
+ export function planWebgl(
321
+ entries: readonly GlCandidate[],
322
+ cap: number = WEBGL_LIVE_CAP
323
+ ): { lose: number[]; restore: number[] } {
324
+ const ranked = entries
325
+ .filter((e) => e.live)
326
+ .sort((a, b) => a.distance - b.distance || b.lastLive - a.lastLive);
327
+ const keep = new Set(ranked.slice(0, Math.max(0, cap)).map((e) => e.key));
328
+ const lose: number[] = [];
329
+ const restore: number[] = [];
330
+ for (const e of entries) {
331
+ if (keep.has(e.key)) {
332
+ if (e.lost) restore.push(e.key);
333
+ } else if (!e.lost) lose.push(e.key);
334
+ }
335
+ return { lose, restore };
336
+ }