@1agh/maude 1.8.1 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/apps/studio/acp/bridge.ts +14 -2
  2. package/apps/studio/acp/probe.ts +51 -1
  3. package/apps/studio/api.ts +19 -4
  4. package/apps/studio/bin/_curl-local.mjs +7 -0
  5. package/apps/studio/bin/annotate.mjs +16 -7
  6. package/apps/studio/bin/read-annotations.mjs +62 -4
  7. package/apps/studio/client/app.jsx +428 -15977
  8. package/apps/studio/client/dialogs/asset-picker.jsx +331 -0
  9. package/apps/studio/client/dialogs/command-palette.jsx +112 -0
  10. package/apps/studio/client/dialogs/export-dialog.jsx +782 -0
  11. package/apps/studio/client/dialogs/help-modal.jsx +324 -0
  12. package/apps/studio/client/dialogs/shortcuts-overlay.jsx +144 -0
  13. package/apps/studio/client/hooks/use-canvas-bridge.jsx +2150 -0
  14. package/apps/studio/client/hooks/use-git-actions.jsx +236 -0
  15. package/apps/studio/client/hooks/use-keyboard-shortcuts.jsx +297 -0
  16. package/apps/studio/client/hooks/use-palette-and-panels.jsx +474 -0
  17. package/apps/studio/client/hooks/use-photo-and-timeline.jsx +901 -0
  18. package/apps/studio/client/hooks/use-project-data.jsx +90 -0
  19. package/apps/studio/client/hooks/use-shell-core.jsx +1212 -0
  20. package/apps/studio/client/hooks/use-tabs.jsx +723 -0
  21. package/apps/studio/client/hooks/use-web-socket.jsx +13 -0
  22. package/apps/studio/client/inspector/artboard-knobs.jsx +456 -0
  23. package/apps/studio/client/inspector/color-picker.jsx +196 -0
  24. package/apps/studio/client/inspector/color.js +92 -0
  25. package/apps/studio/client/inspector/css-knobs.jsx +1720 -0
  26. package/apps/studio/client/inspector/css-vocab.jsx +131 -0
  27. package/apps/studio/client/inspector/ds-tokens.js +90 -0
  28. package/apps/studio/client/inspector/grid-tracks-editor.jsx +97 -0
  29. package/apps/studio/client/inspector/inspect-computed.jsx +68 -0
  30. package/apps/studio/client/inspector/inspector-panel.jsx +769 -0
  31. package/apps/studio/client/inspector/layers.jsx +322 -0
  32. package/apps/studio/client/inspector/selection.js +65 -0
  33. package/apps/studio/client/inspector/token-popover.jsx +301 -0
  34. package/apps/studio/client/menus/menubar.jsx +856 -0
  35. package/apps/studio/client/selection-scope.js +40 -0
  36. package/apps/studio/client/shell/banners.jsx +272 -0
  37. package/apps/studio/client/shell/collapsed-rail.jsx +23 -0
  38. package/apps/studio/client/shell/comments-panel.jsx +177 -0
  39. package/apps/studio/client/shell/constants.js +60 -0
  40. package/apps/studio/client/shell/dock.jsx +131 -0
  41. package/apps/studio/client/shell/icons.jsx +370 -0
  42. package/apps/studio/client/shell/status-bar.jsx +215 -0
  43. package/apps/studio/client/shell/util.js +332 -0
  44. package/apps/studio/client/shell/viewport.jsx +254 -0
  45. package/apps/studio/client/system/system-view.jsx +255 -0
  46. package/apps/studio/client/tree/tree.jsx +1243 -0
  47. package/apps/studio/comments-overlay.tsx +6 -4
  48. package/apps/studio/config.schema.json +5 -0
  49. package/apps/studio/context.ts +13 -0
  50. package/apps/studio/dist/client.bundle.js +1337 -1337
  51. package/apps/studio/dist/comment-mount.js +2 -2
  52. package/apps/studio/exporters/_browser-bundles.ts +21 -2
  53. package/apps/studio/exporters/jobs.ts +75 -15
  54. package/apps/studio/exporters/scope.ts +15 -12
  55. package/apps/studio/format.ts +296 -0
  56. package/apps/studio/http.ts +213 -23
  57. package/apps/studio/server.ts +118 -29
  58. package/apps/studio/sync/accepted-link.ts +6 -0
  59. package/apps/studio/sync/agent.ts +9 -1
  60. package/apps/studio/sync/cold-start-apply.ts +29 -4
  61. package/apps/studio/sync/cold-start.ts +78 -0
  62. package/apps/studio/sync/file-plane.ts +61 -1
  63. package/apps/studio/sync/format-sync.ts +160 -0
  64. package/apps/studio/sync/index.ts +134 -10
  65. package/apps/studio/sync/journal-client.ts +25 -5
  66. package/apps/studio/sync/migrate-seed.ts +8 -1
  67. package/apps/studio/sync/status.ts +2 -0
  68. package/apps/studio/sync/transaction-client.ts +130 -13
  69. package/apps/studio/ui-prefs.ts +95 -10
  70. package/apps/studio/whats-new.json +9 -0
  71. package/apps/studio/ws.ts +19 -4
  72. package/cli/bin/claude-design-server.mjs +0 -0
  73. package/package.json +10 -8
@@ -0,0 +1,901 @@
1
+ // hooks/use-photo-and-timeline.jsx — moved verbatim out of client/app.jsx (Maude v2 plan V2-0.2, move-only split).
2
+
3
+ import { useCallback, useEffect, useRef, useState } from 'react';
4
+ import { persistUiPrefs, shellToast } from '../shell/util.js';
5
+ import { ANNOT_STORE, LAYERS_MODE_STORE, MINIMAP_STORE, PANEL_SIDES_STORE, SHOW_HIDDEN_STORE, SIDEBAR_STORE, SYSTEM_TAB, THEME_STORE, ZOOMCTL_STORE } from '../shell/constants.js';
6
+ import { activeComp } from '../panels/timeline-comp-target.js';
7
+ import { parseCompTimeline } from '../panels/timeline-parse.js';
8
+ import { PANEL_SIDES_DEFAULTS } from '../shell/dock.jsx';
9
+ import { collectDirPaths, pruneDirs, toggleSection as toggleSectionState } from '../tree-expansion.js';
10
+
11
+ export function usePhotoAndTimeline({
12
+ groups, treeLoaded, activePath, selected, theme, setTheme, sidebarOpen, showHidden, treeExp,
13
+ updateTreeExp, panelSide, setPanelSide, layersMode, setLayersMode, timelineOpen, activeComps,
14
+ setActiveComps, timelineFrame, setTimelineFrame, timelinePlaying, setTimelinePlaying, timelineLoop,
15
+ timelineMuted, canvasActiveArtboard, timelineSequences, setTimelineSequences, setTimelineAudio,
16
+ setTimelineTransitions, timelineTotal, setTimelineTotal, timelineArtboardId, setTimelineArtboardId,
17
+ timelineArtboardIdRef, timelineCompId, timelineSelectedClip, setTimelineSelectedClip,
18
+ timelineRefresh, timelineOpFailed, photoUndoRef, setPhotoRev, autoOpenInspector,
19
+ setAutoOpenInspector, annotationsVisible, setAnnotationsVisible, uiPrefsHydrated,
20
+ setUiPrefsHydrated, minimapVisible, setMinimapVisible, zoomCtlVisible, setZoomCtlVisible,
21
+ setPresentMode, setPrintGuidesVisible, setActiveArtboards, setGitUser, iframesRef,
22
+ postToActiveCanvas, wsSend
23
+ }) {
24
+ // ── feature-photo-editor — the Photo tab's three channels ─────────────────
25
+ // (1) live preview: broadcast the edit DOWN to the active canvas iframe, whose
26
+ // canvas-lib `PhotoPreviewBridge` bakes the composite and swaps it directly
27
+ // into the matching `<img>`/`<image>` element's src/href (iteration 2 — see
28
+ // the bridge's own header comment for why it's a direct swap, not an
29
+ // overlay). (2) undo: a shell-side stack (photo edits are sidecar writes,
30
+ // not the canvas-side source-edit stack). (3) background removal: the
31
+ // client-side @imgly ML flow (Task 12).
32
+ const onPhotoEdit = useCallback(
33
+ (asset, edit) => postToActiveCanvas({ dgn: 'photo-preview', asset, edit }),
34
+ [postToActiveCanvas]
35
+ );
36
+ const onPhotoRecordEdit = useCallback((asset, before, after) => {
37
+ photoUndoRef.current.undo.push({ asset, before, after });
38
+ photoUndoRef.current.redo.length = 0;
39
+ }, []);
40
+ // Pops the shell-side photo-undo stack, re-persists the reverted edit through
41
+ // the same PUT route PhotoKnobs itself uses, re-broadcasts it to the live
42
+ // preview, and bumps `photoRev` so the mounted PhotoKnobs (keyed on
43
+ // `asset:photoRev`) remounts and re-fetches instead of drifting from its own
44
+ // stale local state. Returns false (does nothing) when the requested stack is
45
+ // empty, so callers can fall through to the canvas's own undo stack.
46
+ const performPhotoUndo = useCallback(
47
+ (redo) => {
48
+ const stack = redo ? photoUndoRef.current.redo : photoUndoRef.current.undo;
49
+ if (!stack.length) return false;
50
+ const entry = stack.pop();
51
+ (redo ? photoUndoRef.current.undo : photoUndoRef.current.redo).push(entry);
52
+ const edit = (redo ? entry.after : entry.before) || {};
53
+ onPhotoEdit(entry.asset, edit);
54
+ fetch(`/_api/photo-edit?asset=${encodeURIComponent(entry.asset)}`, {
55
+ method: 'PUT',
56
+ headers: { 'Content-Type': 'application/json' },
57
+ body: JSON.stringify(edit),
58
+ }).catch(() => {});
59
+ setPhotoRev((v) => v + 1);
60
+ return true;
61
+ },
62
+ [onPhotoEdit]
63
+ );
64
+ // Task 12 — magic background removal, entirely client-side (WASM/WebGPU via
65
+ // @imgly/background-removal — NEVER the -node native-addon variant, DDR-070).
66
+ // The lib is DYNAMICALLY imported so a session that never removes a background
67
+ // pays zero bundle cost (the lazy-bundle guarantee). Fetches the source bytes,
68
+ // runs the matte, uploads it content-addressed through the SAME /_api/asset lane
69
+ // drag-drop uses, and returns the new `assets/<sha8>.png` for PhotoEdit.
70
+ const onPhotoRemoveBackground = useCallback(
71
+ async (asset) => {
72
+ // Scan/shimmer reveal on the live photo while the ML pass runs, the same
73
+ // "something is actively happening here" language as the agent-edit
74
+ // artboard rim (artboard-activity-overlay.tsx) — but applied directly to
75
+ // the photo element itself (a `data-photo-busy` attribute + injected CSS
76
+ // mask sweep, inspect.ts) rather than a floating tracked overlay. A
77
+ // floating decoy is exactly the architecture DDR-161's addendum tore out
78
+ // for the live-edit preview (z-index/resize/hit-testing bugs); an
79
+ // attribute toggle on the real element sidesteps that whole class.
80
+ postToActiveCanvas({ dgn: 'photo-busy', asset, busy: true });
81
+ try {
82
+ const srcRes = await fetch(`/${asset.replace(/^\/+/, '')}`);
83
+ if (!srcRes.ok) return null;
84
+ const srcBlob = await srcRes.blob();
85
+ const { removeBackground } = await import('@imgly/background-removal');
86
+ // Inference is 100% CLIENT-SIDE (WASM/WebGPU) — the user's pixels NEVER
87
+ // leave the browser. Only the public model weights (~40 MB, identical for
88
+ // everyone) are fetched from IMG.LY's default host on first use; they're
89
+ // too large to bundle in the npm tarball (`resources.json` ships empty).
90
+ // Self-hosting those weights off the dev server for offline / air-gapped
91
+ // parity is the flagged Task-11 follow-up (a one-time download step) — until
92
+ // then the default host provides them, with no pixel-privacy exposure.
93
+ const matte = await removeBackground(srcBlob);
94
+ const up = await fetch('/_api/asset', {
95
+ method: 'POST',
96
+ headers: { 'content-type': matte.type || 'image/png' },
97
+ body: matte,
98
+ });
99
+ const j = await up.json().catch(() => ({}));
100
+ if (up.ok && j.path) return { maskAsset: j.path };
101
+ return null;
102
+ } catch (err) {
103
+ console.error('[photo] background removal failed', err);
104
+ return null;
105
+ } finally {
106
+ // Always clears, success or failure — an errored pass must not leave
107
+ // the shimmer stuck on the photo forever.
108
+ postToActiveCanvas({ dgn: 'photo-busy', asset, busy: false });
109
+ }
110
+ },
111
+ [postToActiveCanvas]
112
+ );
113
+
114
+ // DDR-150 dogfood #7 — a file dragged from Finder and dropped on a shell area
115
+ // with no drop target used to make the browser NAVIGATE AWAY to the file
116
+ // (file:// replaces the app). Document-level guard: always cancel the default
117
+ // for file drags; the TimelinePanel's own onDrop (bubbling before this) still
118
+ // receives the drop first — this only blocks the browser fallback.
119
+ useEffect(() => {
120
+ const isFileDrag = (e) => Array.from(e.dataTransfer?.types ?? []).includes('Files');
121
+ const onDocDragOver = (e) => {
122
+ if (isFileDrag(e)) e.preventDefault();
123
+ };
124
+ const onDocDrop = (e) => {
125
+ if (isFileDrag(e)) e.preventDefault();
126
+ };
127
+ document.addEventListener('dragover', onDocDragOver);
128
+ document.addEventListener('drop', onDocDrop);
129
+ return () => {
130
+ document.removeEventListener('dragover', onDocDragOver);
131
+ document.removeEventListener('drop', onDocDrop);
132
+ };
133
+ }, []);
134
+
135
+ // DDR-150 P3 Task 9 — timeline keyboard shortcuts. Read live state through a
136
+ // ref so the listener attaches once. Gated on: timeline open + a comp active +
137
+ // focus NOT in a text field. Space doesn't steal the canvas PAN chord because
138
+ // that keydown fires inside the focused canvas iframe, never reaching this
139
+ // top-document listener. Space = play/pause · ←/→ = ±1 frame (Shift = ±1s) ·
140
+ // Home/End = start/end · ,/. = prev/next keyframe boundary.
141
+ const tlKeyRef = useRef({});
142
+ tlKeyRef.current = {
143
+ open: timelineOpen,
144
+ comps: activeComps,
145
+ frame: timelineFrame,
146
+ total: timelineTotal,
147
+ playing: timelinePlaying,
148
+ compId: timelineCompId,
149
+ muted: timelineMuted,
150
+ loop: timelineLoop,
151
+ sequences: timelineSequences,
152
+ post: postToActiveCanvas,
153
+ canvas: activePath,
154
+ };
155
+
156
+ // DDR-150 dogfood #1 — Timeline undo/redo. Every successful clip op (move /
157
+ // trim / remove / insert / z-reorder / replace-src) returns a server `seq`
158
+ // registered in the whole-file undo log; Cmd+Z / Shift+Cmd+Z replay it via
159
+ // /_api/reorder-revert (guarded swap — 409s honestly if the canvas diverged).
160
+ const tlUndoRef = useRef({ undo: [], redo: [] });
161
+ const pushTlUndo = useCallback((canvas, seq, label) => {
162
+ if (typeof seq !== 'number') return;
163
+ tlUndoRef.current.undo.push({ canvas, seq, label });
164
+ tlUndoRef.current.redo = []; // a new edit invalidates the redo branch
165
+ if (tlUndoRef.current.undo.length > 50) tlUndoRef.current.undo.shift();
166
+ }, []);
167
+ const tlUndoRedo = useCallback((dir) => {
168
+ const s = tlUndoRef.current;
169
+ const src = dir === 'undo' ? s.undo : s.redo;
170
+ const dst = dir === 'undo' ? s.redo : s.undo;
171
+ const canvas = tlKeyRef.current.canvas;
172
+ // Last entry for THIS canvas (stacks are global; ops are per-canvas).
173
+ let idx = -1;
174
+ for (let i = src.length - 1; i >= 0; i--) {
175
+ if (src[i].canvas === canvas) {
176
+ idx = i;
177
+ break;
178
+ }
179
+ }
180
+ if (idx < 0) {
181
+ shellToast(dir === 'undo' ? 'Nothing to undo on this timeline.' : 'Nothing to redo.');
182
+ return;
183
+ }
184
+ const entry = src[idx];
185
+ fetch('/_api/reorder-revert', {
186
+ method: 'POST',
187
+ headers: { 'content-type': 'application/json' },
188
+ body: JSON.stringify({ canvas: entry.canvas, seq: entry.seq, dir }),
189
+ })
190
+ .then((r) => r.json().catch(() => ({})))
191
+ .then((j) => {
192
+ src.splice(idx, 1);
193
+ if (j?.ok) {
194
+ dst.push(entry);
195
+ shellToast(`${dir === 'undo' ? 'Undid' : 'Redid'}: ${entry.label}`, true);
196
+ } else {
197
+ // 409 canvas diverged / 404 server restarted — entry is dead, drop it.
198
+ shellToast(`${dir === 'undo' ? 'Undo' : 'Redo'} skipped: ${j?.error || 'failed'}`);
199
+ }
200
+ })
201
+ .catch(() => shellToast(`${dir === 'undo' ? 'Undo' : 'Redo'} failed: network error`));
202
+ }, []);
203
+ // Task 3 — resolve a `{ stableId, index }` clipRef against a fresh comp-clips
204
+ // response. stableId wins (multi-comp-safe, survives reorder); the row index
205
+ // stays as the legacy fallback for rows the enumerator couldn't identify.
206
+ const resolveClipRef = useCallback((cc, clipRef) => {
207
+ const seqs =
208
+ cc?.ok && Array.isArray(cc.clips) ? cc.clips.filter((c) => c.kind === 'sequence') : [];
209
+ if (clipRef == null) return null;
210
+ if (typeof clipRef === 'object') {
211
+ return (
212
+ (clipRef.stableId ? seqs.find((c) => c.stableId === clipRef.stableId) : null) ||
213
+ (Number.isInteger(clipRef.index) ? seqs[clipRef.index] : null) ||
214
+ null
215
+ );
216
+ }
217
+ if (typeof clipRef === 'string') return seqs.find((c) => c.stableId === clipRef) || null;
218
+ return seqs[clipRef] || null;
219
+ }, []);
220
+
221
+ // Task 3 — remove a clip (with server-side ripple for series beats). Shared by
222
+ // the panel's ×/context-menu and the Delete/Backspace key on the selection.
223
+ const timelineRemoveClip = useCallback(
224
+ (clipRef) => {
225
+ const canvas = tlKeyRef.current.canvas;
226
+ if (!canvas || canvas === SYSTEM_TAB) return;
227
+ const artboardId = timelineArtboardIdRef.current || undefined;
228
+ const ccUrl = `/_api/comp-clips?canvas=${encodeURIComponent(canvas)}${artboardId ? `&artboardId=${encodeURIComponent(artboardId)}` : ''}`;
229
+ fetch(ccUrl)
230
+ .then((r) => r.json().catch(() => ({})))
231
+ .then((cc) => {
232
+ const clip = resolveClipRef(cc, clipRef);
233
+ if (!clip?.stableId) return null;
234
+ return fetch('/_api/remove-sequence', {
235
+ method: 'POST',
236
+ headers: { 'content-type': 'application/json' },
237
+ body: JSON.stringify({
238
+ canvas,
239
+ artboardId,
240
+ stableId: clip.stableId,
241
+ contentHash: clip.contentHash,
242
+ }),
243
+ });
244
+ })
245
+ .then((r) => (r ? r.json() : null))
246
+ .then((j) => {
247
+ if (j && !j.ok) {
248
+ console.warn('[remove-clip]', j.error || 'failed');
249
+ timelineOpFailed('Remove refused', j.error);
250
+ } else if (j?.ok) {
251
+ shellToast('Clip removed.', true);
252
+ if (j.seq != null) pushTlUndo(canvas, j.seq, 'remove clip');
253
+ setTimelineSelectedClip(null);
254
+ }
255
+ })
256
+ .catch(() => shellToast('Remove failed: network error'));
257
+ },
258
+ [resolveClipRef, pushTlUndo]
259
+ );
260
+ // Phase 2/3 — the parametric verb pipe (speed/trim-in/audio/detach-audio/
261
+ // framing/grade/transition/split/insert-transition/remove-transition), shared
262
+ // by the inspector popover, context menu, seam chips, and keyboard (⌘B).
263
+ const timelineClipVerb = useCallback(
264
+ (clipRef, verb, params) => {
265
+ const canvas = tlKeyRef.current.canvas;
266
+ if (!canvas || canvas === SYSTEM_TAB) return;
267
+ const artboardId = timelineArtboardIdRef.current || undefined;
268
+ const ccUrl = `/_api/comp-clips?canvas=${encodeURIComponent(canvas)}${artboardId ? `&artboardId=${encodeURIComponent(artboardId)}` : ''}`;
269
+ fetch(ccUrl)
270
+ .then((r) => r.json().catch(() => ({})))
271
+ .then((cc) => {
272
+ const all = cc?.ok && Array.isArray(cc.clips) ? cc.clips : [];
273
+ const clip = clipRef?.transition
274
+ ? all.find((c) => c.kind === 'transition' && c.stableId === clipRef.stableId) || null
275
+ : resolveClipRef(cc, clipRef);
276
+ if (!clip?.stableId) return null;
277
+ return fetch('/_api/clip-edit', {
278
+ method: 'POST',
279
+ headers: { 'content-type': 'application/json' },
280
+ body: JSON.stringify({
281
+ canvas,
282
+ artboardId,
283
+ stableId: clip.stableId,
284
+ contentHash: clip.contentHash,
285
+ verb,
286
+ ...params,
287
+ }),
288
+ });
289
+ })
290
+ .then((r) => (r ? r.json() : null))
291
+ .then((j) => {
292
+ if (j && !j.ok) {
293
+ console.warn('[clip-edit]', verb, j.error || 'failed');
294
+ timelineOpFailed(`${verb} refused`, j.error);
295
+ } else if (j?.ok) {
296
+ const labels = {
297
+ speed: 'set speed',
298
+ 'trim-in': 'trim in-point',
299
+ audio: 'clip audio',
300
+ 'detach-audio': 'detach audio',
301
+ framing: 'crop clip',
302
+ grade: 'grade clip',
303
+ transition: 'edit transition',
304
+ split: 'split clip',
305
+ 'insert-transition': 'add transition',
306
+ 'remove-transition': 'remove transition',
307
+ 'set-text': 'edit text',
308
+ 'to-overlay': 'move to overlay layer',
309
+ 'to-storyline': 'move to storyline',
310
+ 'layer-order': 'reorder layers',
311
+ };
312
+ shellToast(`Applied: ${labels[verb] || verb}.`, true);
313
+ if (j.seq != null) pushTlUndo(canvas, j.seq, labels[verb] || verb);
314
+ }
315
+ })
316
+ .catch(() => shellToast(`${verb} failed: network error`));
317
+ },
318
+ [resolveClipRef, pushTlUndo, timelineOpFailed]
319
+ );
320
+ // Tauri's WKWebView does NOT implement window.prompt() (returns null
321
+ // synchronously — the "click does nothing" desktop bug), so every text ask
322
+ // goes through this promise-based shell modal instead.
323
+ const [shellPromptState, setShellPromptState] = useState(null); // { title, value, resolve }
324
+ const askText = useCallback(
325
+ (title, initial = '') =>
326
+ new Promise((resolve) => {
327
+ setShellPromptState({ title, value: initial, resolve });
328
+ }),
329
+ []
330
+ );
331
+ const settleShellPrompt = useCallback((value) => {
332
+ setShellPromptState((s) => {
333
+ s?.resolve?.(value);
334
+ return null;
335
+ });
336
+ }, []);
337
+
338
+ // Task 23 — timeline comments ride the EXISTING comment system (same WS
339
+ // channel + `_comments/` store), with a `timeline` anchor:
340
+ // { clipStableId, frameOffset } (survives reorder/ripple) or { frame }.
341
+ const timelineAddComment = useCallback((anchor, text) => {
342
+ const canvas = tlKeyRef.current.canvas;
343
+ if (!canvas || canvas === SYSTEM_TAB || !text || !String(text).trim()) return;
344
+ wsSend({
345
+ type: 'comments-add',
346
+ payload: {
347
+ file: canvas,
348
+ text: String(text).trim(),
349
+ selector: '',
350
+ dom_path: [],
351
+ tag: '',
352
+ classes: '',
353
+ bounds: null,
354
+ html_excerpt: '',
355
+ timeline: anchor,
356
+ },
357
+ });
358
+ shellToast('Comment added.', true);
359
+ }, []);
360
+ tlKeyRef.current.selected = timelineSelectedClip;
361
+ tlKeyRef.current.setSelected = setTimelineSelectedClip;
362
+ tlKeyRef.current.removeClip = timelineRemoveClip;
363
+ tlKeyRef.current.clipVerb = timelineClipVerb;
364
+ tlKeyRef.current.addComment = timelineAddComment;
365
+ tlKeyRef.current.askText = askText;
366
+
367
+ useEffect(() => {
368
+ const onKey = (e) => {
369
+ const s = tlKeyRef.current;
370
+ if (!s.open || !s.comps?.length) return;
371
+ const t = e.target;
372
+ const tag = t?.tagName;
373
+ // Range sliders (zoom / volume) keep focus after a drag — Space must
374
+ // still play/pause (the "spacebar stopped working" dogfood bug). Text
375
+ // inputs stay exempt.
376
+ if (tag === 'INPUT' && t?.type !== 'range') return;
377
+ if (tag === 'TEXTAREA' || tag === 'SELECT' || t?.isContentEditable) return;
378
+ // The timebase of the comp the transport is on, not of whichever comp
379
+ // announced first — Shift+arrow is "±1 second" on THIS artboard (#75).
380
+ const fps = activeComp(s.comps, s.compId)?.fps || 30;
381
+ const total = Math.max(1, s.total);
382
+ const doSeek = (f) => {
383
+ const nf = Math.max(0, Math.min(total - 1, Math.round(f)));
384
+ setTimelineFrame(nf);
385
+ setTimelinePlaying(false);
386
+ s.post({ dgn: 'timeline-seek', frame: nf, id: s.compId });
387
+ };
388
+ const snapFrames = () => {
389
+ const pts = new Set([0, total - 1]);
390
+ for (const seq of s.sequences || []) {
391
+ pts.add(seq.from);
392
+ for (const kf of seq.keyframes || []) {
393
+ pts.add(kf.from);
394
+ pts.add(kf.to);
395
+ }
396
+ }
397
+ return [...pts].filter((n) => n >= 0 && n < total).sort((a, b) => a - b);
398
+ };
399
+ if ((e.metaKey || e.ctrlKey) && (e.key === 'z' || e.key === 'Z')) {
400
+ // Cmd+Z / Shift+Cmd+Z — undo/redo the last timeline clip op. Only when
401
+ // the shell (not the canvas iframe) has focus + the timeline is active,
402
+ // so the canvas's own annotation undo is untouched.
403
+ e.preventDefault();
404
+ tlUndoRedo(e.shiftKey ? 'redo' : 'undo');
405
+ return;
406
+ }
407
+ // Task 3 — the select → act grammar: Esc deselects, Delete/Backspace
408
+ // removes the selection (with ripple on the server for series beats).
409
+ if (e.key === 'Escape') {
410
+ if (s.selected != null) {
411
+ e.preventDefault();
412
+ s.setSelected?.(null);
413
+ }
414
+ return;
415
+ }
416
+ if ((e.key === 'Delete' || e.key === 'Backspace') && s.selected != null) {
417
+ e.preventDefault();
418
+ s.removeClip?.({ stableId: s.selected });
419
+ return;
420
+ }
421
+ // Task 23 + dogfood 2026-07-30 — `C` ARMS the panel's comment tool
422
+ // (click-to-place, like the artboard's C); the panel's own window
423
+ // keydown owns the toggle, so the shell must NOT double-handle it.
424
+ // Task 16 — ⌘B splits the selection at the playhead; with nothing
425
+ // selected, the clip under the playhead (iMovie behavior).
426
+ if ((e.metaKey || e.ctrlKey) && (e.key === 'b' || e.key === 'B')) {
427
+ e.preventDefault();
428
+ let ref = s.selected != null ? { stableId: s.selected } : null;
429
+ if (!ref) {
430
+ const rows = s.sequences || [];
431
+ const under =
432
+ rows.find((r2) => r2.series && s.frame >= r2.from && s.frame < r2.from + r2.duration) ||
433
+ rows.find((r2) => s.frame >= r2.from && s.frame < r2.from + r2.duration);
434
+ if (under?.stableId) ref = { stableId: under.stableId };
435
+ }
436
+ if (ref) s.clipVerb?.(ref, 'split', { atFrame: s.frame });
437
+ else shellToast('Nothing under the playhead to split.');
438
+ return;
439
+ }
440
+ if (e.key === ' ' || e.code === 'Space') {
441
+ e.preventDefault();
442
+ if (s.playing) {
443
+ setTimelinePlaying(false);
444
+ s.post({ dgn: 'timeline-pause', id: s.compId });
445
+ } else {
446
+ setTimelinePlaying(true);
447
+ s.post({ dgn: 'timeline-mute', muted: s.muted, id: s.compId });
448
+ s.post({ dgn: 'timeline-loop', loop: s.loop, id: s.compId });
449
+ s.post({ dgn: 'timeline-play', id: s.compId });
450
+ }
451
+ } else if (e.key === 'ArrowRight') {
452
+ e.preventDefault();
453
+ doSeek(s.frame + (e.shiftKey ? fps : 1));
454
+ } else if (e.key === 'ArrowLeft') {
455
+ e.preventDefault();
456
+ doSeek(s.frame - (e.shiftKey ? fps : 1));
457
+ } else if (e.key === 'Home') {
458
+ e.preventDefault();
459
+ doSeek(0);
460
+ } else if (e.key === 'End') {
461
+ e.preventDefault();
462
+ doSeek(total - 1);
463
+ } else if (e.key === '.') {
464
+ e.preventDefault();
465
+ const next = snapFrames().find((n) => n > s.frame);
466
+ if (next != null) doSeek(next);
467
+ } else if (e.key === ',') {
468
+ e.preventDefault();
469
+ const prev = snapFrames()
470
+ .reverse()
471
+ .find((n) => n < s.frame);
472
+ if (prev != null) doSeek(prev);
473
+ }
474
+ };
475
+ window.addEventListener('keydown', onKey);
476
+ return () => window.removeEventListener('keydown', onKey);
477
+ }, []);
478
+
479
+ // DDR-148 — reset the Timeline's comp meta when the active canvas changes (a
480
+ // non-comp canvas fires no announce, so stale comps would linger), then ask
481
+ // the (possibly already-mounted) active canvas to re-announce. video-comp.tsx
482
+ // answers `timeline-request-comps` with a fresh `timeline-comps`.
483
+ useEffect(() => {
484
+ setActiveComps([]);
485
+ setTimelineFrame(0);
486
+ setTimelinePlaying(false);
487
+ setTimelineSelectedClip(null);
488
+ // A stale artboard id from the PREVIOUS canvas would mis-scope the first
489
+ // ops on the next one until its parse lands — clear it with the rest.
490
+ setTimelineArtboardId(null);
491
+ const t = setTimeout(() => postToActiveCanvas({ dgn: 'timeline-request-comps' }), 60);
492
+ return () => clearTimeout(t);
493
+ }, [activePath, postToActiveCanvas]);
494
+
495
+ // DDR-148 — fetch the active canvas's raw source when the Timeline is open.
496
+ // Re-runs when a comp is (re)announced, so it refreshes after a canvas edit.
497
+ const [timelineSource, setTimelineSource] = useState('');
498
+ // DDR-150 dogfood — authoritative per-clip media from the enumerator (handles
499
+ // wrapper components + array-fed src the regex parser can't see), merged into
500
+ // the rows for the kind badge + replace addressing.
501
+ const [timelineClipMedia, setTimelineClipMedia] = useState([]);
502
+ // Phase 2 — the enumerator's transitions (stableId + contentHash), in seam
503
+ // order, for the ⧓ chip → Transition tab flow.
504
+ const [timelineTransClips, setTimelineTransClips] = useState([]);
505
+ useEffect(() => {
506
+ if (!timelineOpen || activeComps.length === 0 || !activePath || activePath === SYSTEM_TAB) {
507
+ setTimelineSource('');
508
+ setTimelineClipMedia([]);
509
+ return undefined;
510
+ }
511
+ let alive = true;
512
+ fetch(`/_api/canvas-source?file=${encodeURIComponent(activePath)}`)
513
+ .then((r) => (r.ok ? r.json() : null))
514
+ .then((j) => {
515
+ if (alive && j?.ok && typeof j.source === 'string') setTimelineSource(j.source);
516
+ })
517
+ .catch(() => {});
518
+ return () => {
519
+ alive = false;
520
+ };
521
+ }, [timelineOpen, activeComps, activePath, timelineRefresh]);
522
+
523
+ // Authoritative per-clip media (comp-clips) — a SEPARATE effect keyed on the
524
+ // RESOLVED artboard id, which the parser only knows AFTER timelineSource
525
+ // arrives. Fetching it here (not in the source effect) means it re-runs once
526
+ // the parser scopes to the right comp — so a multi-comp canvas (the showreel:
527
+ // Movie + Reel) overlays the CORRECT comp's media, not the enumerator's own
528
+ // fallback pick.
529
+ useEffect(() => {
530
+ if (!timelineOpen || !activePath || activePath === SYSTEM_TAB || !timelineSource) {
531
+ setTimelineClipMedia([]);
532
+ setTimelineTransClips([]);
533
+ return undefined;
534
+ }
535
+ let alive = true;
536
+ const artboardId = timelineArtboardId || undefined;
537
+ const ccUrl = `/_api/comp-clips?canvas=${encodeURIComponent(activePath)}${artboardId ? `&artboardId=${encodeURIComponent(artboardId)}` : ''}`;
538
+ fetch(ccUrl)
539
+ .then((r) => (r.ok ? r.json() : null))
540
+ .then((cc) => {
541
+ if (!alive) return;
542
+ const all = cc?.ok && Array.isArray(cc.clips) ? cc.clips : [];
543
+ setTimelineClipMedia(all.filter((c) => c.kind === 'sequence'));
544
+ setTimelineTransClips(all.filter((c) => c.kind === 'transition'));
545
+ })
546
+ .catch(() => {});
547
+ return () => {
548
+ alive = false;
549
+ };
550
+ }, [timelineOpen, activePath, timelineSource, timelineArtboardId, timelineRefresh]);
551
+
552
+ // Parse (cheap) — re-runs on source change AND on selection change, so the
553
+ // Timeline REDRAWS to whichever artboard the user just selected/moved to.
554
+ useEffect(() => {
555
+ if (!timelineSource) {
556
+ setTimelineSequences([]);
557
+ setTimelineAudio([]);
558
+ setTimelineTransitions([]);
559
+ setTimelineTotal(0);
560
+ return;
561
+ }
562
+ const artboard = canvasActiveArtboard ?? selected?.artboardId ?? null;
563
+ // Seed the parser's fallback total from the comp mounted in THIS artboard,
564
+ // not from whichever comp announced first (issue #75).
565
+ const seedComp =
566
+ (artboard && activeComps.find((c) => c.artboardId === artboard || c.id === artboard)) ||
567
+ activeComps[0];
568
+ const total = seedComp?.durationInFrames || 0;
569
+ const parsed = parseCompTimeline(timelineSource, total, artboard);
570
+ setTimelineArtboardId(parsed.artboardId ?? artboard ?? null);
571
+ // Overlay the enumerator's authoritative media (kind badge + replace target)
572
+ // onto each row by sequence index — it sees wrapper-component + array-fed
573
+ // media the row parser can't (the showreel <ClipShot clip={CLIPS[i]}/> case).
574
+ const merged = parsed.sequences.map((s, i) => {
575
+ const cm = timelineClipMedia[i];
576
+ if (!cm) return s;
577
+ return {
578
+ ...s,
579
+ // Task 3 — the enumerator's durable identity rides on every row so the
580
+ // panel can select + address ops by stableId, never by row index.
581
+ stableId: cm.stableId,
582
+ contentHash: cm.contentHash,
583
+ // Phase 2 — authoritative parametric props for the clip inspector.
584
+ mediaProps: cm.mediaProps ?? null,
585
+ // Task 21 — AI placeholder slate (✨ row + Generate flow).
586
+ placeholder: cm.placeholder ?? null,
587
+ mediaTag: cm.mediaTag ?? s.mediaTag,
588
+ mediaSrc: cm.mediaSrc ?? s.mediaSrc,
589
+ // Replaceable when the enumerator found an addressable media target:
590
+ // a literal-src element (mediaCdId) or an array-fed src (mediaArrayRef).
591
+ replaceable: !!(cm.mediaCdId || cm.mediaArrayRef),
592
+ // The clip's stacked layers (mp4 background + title/…) for expandable rows.
593
+ layers: Array.isArray(cm.layers) ? cm.layers : [],
594
+ hidden: !!cm.hidden,
595
+ };
596
+ });
597
+ setTimelineSequences(merged);
598
+ setTimelineAudio(parsed.audio || []);
599
+ setTimelineTransitions(parsed.transitions || []);
600
+ setTimelineTotal(parsed.total);
601
+ }, [timelineSource, timelineClipMedia, selected, activeComps, canvasActiveArtboard]);
602
+
603
+ const toggleAnnotations = useCallback(() => {
604
+ setAnnotationsVisible((v) => {
605
+ const next = !v;
606
+ const el = activePath ? iframesRef.current.get(activePath) : null;
607
+ if (el && el.contentWindow) {
608
+ try {
609
+ el.contentWindow.postMessage({ dgn: 'view-annotations', visible: next }, '*');
610
+ } catch {}
611
+ }
612
+ return next;
613
+ });
614
+ }, [activePath]);
615
+
616
+ // Chrome visibility (minimap / zoom-controls / Presentation Mode) applies to
617
+ // EVERY open canvas iframe, not just the active one — broadcast to all. A
618
+ // freshly-loaded iframe is seeded from the dgn:'loaded' handler below.
619
+ const broadcastChrome = useCallback((patch) => {
620
+ for (const el of iframesRef.current.values()) {
621
+ try {
622
+ el.contentWindow.postMessage({ dgn: 'view-chrome', ...patch }, '*');
623
+ } catch {}
624
+ }
625
+ }, []);
626
+ const toggleMinimap = useCallback(() => {
627
+ setMinimapVisible((v) => {
628
+ const next = !v;
629
+ broadcastChrome({ minimap: next });
630
+ return next;
631
+ });
632
+ }, [broadcastChrome]);
633
+ const toggleZoomCtl = useCallback(() => {
634
+ setZoomCtlVisible((v) => {
635
+ const next = !v;
636
+ broadcastChrome({ zoom: next });
637
+ return next;
638
+ });
639
+ }, [broadcastChrome]);
640
+ const togglePresent = useCallback(() => {
641
+ setPresentMode((v) => {
642
+ const next = !v;
643
+ broadcastChrome({ present: next });
644
+ return next;
645
+ });
646
+ }, [broadcastChrome]);
647
+ const exitPresent = useCallback(() => {
648
+ setPresentMode(false);
649
+ broadcastChrome({ present: false });
650
+ }, [broadcastChrome]);
651
+ // feature-2-print-artboards T3 — per-canvas persisted, so (unlike
652
+ // broadcastChrome above) this targets ONLY the active iframe and PATCHes
653
+ // view.json's `overlays.print` through the same GET-merge/PATCH-split lane
654
+ // the foundation built for `overlays.guides` (api.ts normalizeOverlays is a
655
+ // flat Record<string, boolean> — no server change needed for a new key).
656
+ const togglePrintGuides = useCallback(() => {
657
+ if (!activePath || activePath === SYSTEM_TAB) return;
658
+ setPrintGuidesVisible((v) => {
659
+ const next = !v;
660
+ postToActiveCanvas({ dgn: 'view-chrome', print: next });
661
+ fetch('/_api/canvas-meta', {
662
+ method: 'PATCH',
663
+ headers: { 'Content-Type': 'application/json' },
664
+ body: JSON.stringify({ file: activePath, patch: { overlays: { print: next } } }),
665
+ }).catch(() => {});
666
+ return next;
667
+ });
668
+ }, [activePath, postToActiveCanvas]);
669
+
670
+ // P3 (Plan C) — local git user for the menubar presence avatar. One-shot.
671
+ useEffect(() => {
672
+ let cancelled = false;
673
+ fetch('/_api/git-user')
674
+ .then((r) => r.json())
675
+ .then((d) => {
676
+ if (cancelled) return;
677
+ const n = d && typeof d.name === 'string' ? d.name.trim() : '';
678
+ if (n) setGitUser(n);
679
+ })
680
+ .catch(() => {});
681
+ return () => {
682
+ cancelled = true;
683
+ };
684
+ }, []);
685
+
686
+ // P2 (Plan C) — when the active canvas changes, read its real artboard count
687
+ // from the `<canvas>.meta.json` sidecar (shell-side, no iframe dep).
688
+ useEffect(() => {
689
+ if (!activePath || activePath === SYSTEM_TAB) {
690
+ setActiveArtboards(0);
691
+ setPrintGuidesVisible(false);
692
+ return;
693
+ }
694
+ let cancelled = false;
695
+ fetch('/_api/canvas-meta?file=' + encodeURIComponent(activePath))
696
+ .then((r) => r.json())
697
+ .then((meta) => {
698
+ if (cancelled) return;
699
+ const n = Array.isArray(meta?.artboards) ? meta.artboards.length : 0;
700
+ setActiveArtboards(n);
701
+ // feature-2-print-artboards T3 — reflect THIS canvas's own persisted
702
+ // print-guides flag in the menu checkbox when switching tabs.
703
+ setPrintGuidesVisible(meta?.overlays?.print === true);
704
+ // feature-4 T7b — seed this canvas's persisted locked-layer keys
705
+ // (view.json `locked`, per-user) into the Layers panel state.
706
+ setLockedKeys(new Set(Array.isArray(meta?.locked) ? meta.locked : []));
707
+ })
708
+ .catch(() => {
709
+ if (!cancelled) {
710
+ setActiveArtboards(0);
711
+ setPrintGuidesVisible(false);
712
+ setLockedKeys(new Set());
713
+ }
714
+ });
715
+ return () => {
716
+ cancelled = true;
717
+ };
718
+ }, [activePath]);
719
+
720
+ // feature-4 dogfood fix (2026-07-19) — the Layers panel used to stay EMPTY
721
+ // until something was selected (the tree only posted on selection). Request
722
+ // the tree for the viewport-active artboard whenever it (or the canvas)
723
+ // changes, so Layers work in browse mode with no selection at all. Small
724
+ // debounce — the active-artboard signal can flicker during a fast pan.
725
+ useEffect(() => {
726
+ if (!activePath || activePath === SYSTEM_TAB || !canvasActiveArtboard) return;
727
+ const t = setTimeout(() => {
728
+ postToActiveCanvas({ dgn: 'request-layers', artboardId: canvasActiveArtboard });
729
+ }, 250);
730
+ return () => clearTimeout(t);
731
+ }, [activePath, canvasActiveArtboard, postToActiveCanvas]);
732
+
733
+ // feature-4 T7b — locked layer keys (`"<cdId>:<index>"`, per-user, per-canvas
734
+ // via view.json). Toggling PATCHes the FULL set (replace semantics) + pushes
735
+ // the live set down to the canvas iframe so select/drag enforcement matches
736
+ // the padlock instantly.
737
+ const [lockedKeys, setLockedKeys] = useState(() => new Set());
738
+ const toggleLockedKey = useCallback(
739
+ (key) => {
740
+ if (!activePath || activePath === SYSTEM_TAB) return;
741
+ setLockedKeys((prev) => {
742
+ const next = new Set(prev);
743
+ if (next.has(key)) next.delete(key);
744
+ else next.add(key);
745
+ const arr = [...next];
746
+ fetch('/_api/canvas-meta', {
747
+ method: 'PATCH',
748
+ headers: { 'Content-Type': 'application/json' },
749
+ body: JSON.stringify({ file: activePath, patch: { locked: arr } }),
750
+ }).catch(() => {});
751
+ postToActiveCanvas({ dgn: 'locked-set', locked: arr });
752
+ return next;
753
+ });
754
+ },
755
+ [activePath, postToActiveCanvas]
756
+ );
757
+ // Push the seed to a (re)loaded canvas too — the iframe reads
758
+ // `__canvas_meta__.locked` at boot, but a shell-side toggle after a reload
759
+ // must still reach it; re-broadcast whenever the set or canvas changes.
760
+ useEffect(() => {
761
+ if (!activePath || activePath === SYSTEM_TAB) return;
762
+ postToActiveCanvas({ dgn: 'locked-set', locked: [...lockedKeys] });
763
+ }, [lockedKeys, activePath, postToActiveCanvas]);
764
+
765
+ // Sync theme to <html data-theme> + localStorage on every change.
766
+ useEffect(() => {
767
+ try {
768
+ document.documentElement.setAttribute('data-theme', theme);
769
+ localStorage.setItem(THEME_STORE, theme);
770
+ } catch {}
771
+ // System-review D9 — the canvas-shell chrome (workspace plane, floating
772
+ // toolbar, minimap, zoom HUD, halos) follows the Maude theme. Broadcast to
773
+ // EVERY open canvas iframe (not just activePath — several may be open); the
774
+ // iframe's canvas-shell sets `data-maude-theme` and re-themes its floating
775
+ // chrome via the --maude-chrome-* family. Artboards keep their DS theme.
776
+ // Mirrors the git-lifecycle broadcast-to-all loop below. On the initial
777
+ // mount run iframesRef is empty (no canvas open yet) — a freshly-loaded
778
+ // iframe instead gets the current theme from the `dgn:'loaded'` handler.
779
+ for (const el of iframesRef.current.values()) {
780
+ try {
781
+ el.contentWindow.postMessage({ dgn: 'theme', theme }, '*');
782
+ } catch {}
783
+ }
784
+ }, [theme]);
785
+
786
+ // Persist sidebar / hidden-files / DS-body toggles. Mirror theme pattern.
787
+ useEffect(() => {
788
+ try {
789
+ localStorage.setItem(SIDEBAR_STORE, sidebarOpen ? '1' : '0');
790
+ } catch {}
791
+ }, [sidebarOpen]);
792
+ useEffect(() => {
793
+ try {
794
+ localStorage.setItem(SHOW_HIDDEN_STORE, showHidden ? '1' : '0');
795
+ } catch {}
796
+ }, [showHidden]);
797
+ useEffect(() => {
798
+ try {
799
+ localStorage.setItem(MINIMAP_STORE, minimapVisible ? '1' : '0');
800
+ } catch {}
801
+ }, [minimapVisible]);
802
+ useEffect(() => {
803
+ try {
804
+ localStorage.setItem(ZOOMCTL_STORE, zoomCtlVisible ? '1' : '0');
805
+ } catch {}
806
+ }, [zoomCtlVisible]);
807
+ useEffect(() => {
808
+ try {
809
+ localStorage.setItem(ANNOT_STORE, annotationsVisible ? '1' : '0');
810
+ } catch {}
811
+ }, [annotationsVisible]);
812
+
813
+ // feature-unified-settings-modal — reconcile view prefs with the on-disk store
814
+ // once on mount (disk wins over the localStorage/default init: it survives a
815
+ // cleared localStorage). Applying a value that already matches is a no-op, so
816
+ // there's no flash in the common case. On failure we still mark hydrated so
817
+ // writes resume best-effort.
818
+ useEffect(() => {
819
+ let cancelled = false;
820
+ fetch('/_api/ui-prefs')
821
+ .then((r) => (r.ok ? r.json() : Promise.reject(new Error(`HTTP ${r.status}`))))
822
+ .then((p) => {
823
+ if (cancelled || !p || typeof p !== 'object') return;
824
+ if (p.theme === 'light' || p.theme === 'dark') setTheme(p.theme);
825
+ if (typeof p.minimap === 'boolean') setMinimapVisible(p.minimap);
826
+ if (typeof p.zoom === 'boolean') setZoomCtlVisible(p.zoom);
827
+ if (typeof p.annotations === 'boolean') setAnnotationsVisible(p.annotations);
828
+ if (typeof p.autoOpenInspector === 'boolean') setAutoOpenInspector(p.autoOpenInspector);
829
+ if (p.panelSides && typeof p.panelSides === 'object')
830
+ setPanelSide({ ...PANEL_SIDES_DEFAULTS, ...p.panelSides });
831
+ if (p.layersMode === 'separate' || p.layersMode === 'in-inspector')
832
+ setLayersMode(p.layersMode);
833
+ })
834
+ .catch(() => {})
835
+ .finally(() => {
836
+ if (!cancelled) setUiPrefsHydrated(true);
837
+ });
838
+ return () => {
839
+ cancelled = true;
840
+ };
841
+ }, []);
842
+
843
+ // Mirror every view pref to disk once hydrated. The barrier stops the initial
844
+ // render (localStorage/default values) from overwriting the disk store before
845
+ // the boot GET has reconciled.
846
+ useEffect(() => {
847
+ if (!uiPrefsHydrated) return;
848
+ persistUiPrefs({
849
+ theme,
850
+ minimap: minimapVisible,
851
+ zoom: zoomCtlVisible,
852
+ annotations: annotationsVisible,
853
+ autoOpenInspector,
854
+ panelSides: panelSide,
855
+ layersMode,
856
+ });
857
+ }, [
858
+ uiPrefsHydrated,
859
+ theme,
860
+ minimapVisible,
861
+ zoomCtlVisible,
862
+ annotationsVisible,
863
+ autoOpenInspector,
864
+ panelSide,
865
+ layersMode,
866
+ ]);
867
+ // localStorage mirror for panel sides + layers mode (synchronous no-flash init).
868
+ useEffect(() => {
869
+ try {
870
+ localStorage.setItem(PANEL_SIDES_STORE, JSON.stringify(panelSide));
871
+ } catch {}
872
+ }, [panelSide]);
873
+ useEffect(() => {
874
+ try {
875
+ localStorage.setItem(LAYERS_MODE_STORE, layersMode);
876
+ } catch {}
877
+ }, [layersMode]);
878
+
879
+ // #124 — forget folders that no longer exist (deleted, or moved outside
880
+ // Maude). ONCE per session, on the first loaded tree: pruning on every tree
881
+ // change would race a move's remap against the reload that follows it.
882
+ const treePruned = useRef(false);
883
+ useEffect(() => {
884
+ if (treePruned.current || !treeExp.ready || !treeLoaded || !groups.length) return;
885
+ treePruned.current = true;
886
+ const known = collectDirPaths(groups);
887
+ updateTreeExp((st) => pruneDirs(st, known));
888
+ }, [treeExp.ready, treeLoaded, groups, updateTreeExp]);
889
+
890
+ const toggleSection = useCallback(
891
+ (label) => updateTreeExp((st) => toggleSectionState(st, label)),
892
+ [updateTreeExp]
893
+ );
894
+ return {
895
+ askText, broadcastChrome, exitPresent, lockedKeys, onPhotoEdit, onPhotoRecordEdit,
896
+ onPhotoRemoveBackground, performPhotoUndo, pushTlUndo, resolveClipRef, settleShellPrompt,
897
+ shellPromptState, timelineAddComment, timelineClipVerb, timelineRemoveClip, timelineTransClips,
898
+ tlKeyRef, toggleAnnotations, toggleLockedKey, toggleMinimap, togglePresent, togglePrintGuides,
899
+ toggleSection, toggleZoomCtl
900
+ };
901
+ }