@1agh/maude 1.8.1 → 1.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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 +217 -23
  57. package/apps/studio/server.ts +141 -30
  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,723 @@
1
+ // hooks/use-tabs.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 { CANVAS_EXT_RE, SYSTEM_TAB } from '../shell/constants.js';
5
+ import { remapDirPrefix, revealPath } from '../tree-expansion.js';
6
+ import { buildShareLinks, normalizeOpenPath, readOpenParam, withOpenParam } from '../share-link.js';
7
+ import { basename, displayName, previewKind, shellToast } from '../shell/util.js';
8
+ import { notify } from '../../notifications.tsx';
9
+ import { isNativeApp } from '../github.js';
10
+
11
+ export function useTabs({
12
+ groups, treeLoaded, addressMode, previousAddressPath, project, tabs, setTabs, activePath,
13
+ setActivePath, previewPath, setPreviewPath, onPreview, setSelected, cloudLinkedHub,
14
+ localProjectName, systemData, setLoadingPath, setCanvasError, setCanvasReloadNonce, setLoadedPath,
15
+ cfg, loadServerConfig, setFocusedCommentId, updateTreeExp, setShareDialog, setTimelineOpen,
16
+ timelineArtboardId, iframesRef, pushTlUndo, askText, loadTree, loadSystemData, canvasListChangeRef,
17
+ wsSend
18
+ }) {
19
+ // ----- Tab management (single-canvas) -----
20
+ // Single-canvas model: opening a file REPLACES the active one (no tab strip).
21
+ // The `tabs` state stays as a 0-or-1 array so the rest of the plumbing
22
+ // (iframesRef, comments push, WS `tabs` message) doesn't need refactoring.
23
+ // ARTBOARDS slot in the menubar reads `tabs.length` and reports 0 or 1.
24
+ // `reveal: false` for opens the USER didn't just ask for (URL restore on
25
+ // boot, the cloud first-canvas auto-open): nothing expands itself on launch
26
+ // (#124). Every other open reveals the canvas's row in the Files tree.
27
+ const openTab = useCallback((path, { reveal = true } = {}) => {
28
+ if (reveal && path && path !== SYSTEM_TAB)
29
+ updateTreeExp((st) => revealPath(st, groups, path));
30
+ addressMode.current = 'push';
31
+ setFocusedCommentId(null);
32
+ setPreviewPath(null);
33
+ // The same path keeps its mounted iframe. It will not emit a new loaded
34
+ // event, so keep its current loading/error state until an actual retry.
35
+ if (path === activePath) return;
36
+ setTabs((prev) => {
37
+ // Drop the previously-open iframe so we don't leak DOM nodes.
38
+ for (const t of prev) if (t.path !== path) iframesRef.current.delete(t.path);
39
+ return [{ path }];
40
+ });
41
+ setActivePath(path);
42
+ setCanvasError(null);
43
+ setLoadedPath(null);
44
+ // Canvas-compile skeleton — cleared by the iframe's dgn:'loaded' message,
45
+ // the onLoad fallback timer (legacy .html), or a hard 15s cap.
46
+ if (path !== SYSTEM_TAB) setLoadingPath(path);
47
+ }, [activePath, groups, updateTreeExp]);
48
+
49
+ // Resolve URL identities against the loaded tree, including non-canvas previews.
50
+ const openLinkedFile = useCallback((rel, mode = 'push') => {
51
+ const path = groups.flatMap((g) => g.paths || []).find((p) => normalizeOpenPath(p, cfg.designRel) === rel);
52
+ if (path && CANVAS_EXT_RE.test(path)) openTab(path, { reveal: false });
53
+ else if (path && previewKind(basename(path))) onPreview(path);
54
+ else {
55
+ setTabs([]);
56
+ setActivePath(null);
57
+ setPreviewPath(null);
58
+ notify({ title: 'Not here yet', description: `${rel} is not in this project (not synced yet?)`, kind: 'info' });
59
+ }
60
+ addressMode.current = mode;
61
+ }, [groups, cfg.designRel, openTab, onPreview]);
62
+
63
+ const addressBooted = useRef(false);
64
+ useEffect(() => {
65
+ if (!treeLoaded || cfg.cloud === undefined || addressBooted.current) return;
66
+ addressBooted.current = true;
67
+ const rel = readOpenParam(location, cfg.designRel);
68
+ if (rel) openLinkedFile(rel, 'none');
69
+ }, [treeLoaded, cfg.cloud, cfg.designRel, openLinkedFile]);
70
+
71
+ useEffect(() => {
72
+ if (!treeLoaded || cfg.cloud === undefined) return;
73
+ const navigate = () => {
74
+ const rel = readOpenParam(location, cfg.designRel);
75
+ if (rel) openLinkedFile(rel, 'none');
76
+ else {
77
+ addressMode.current = 'none';
78
+ setTabs([]);
79
+ setActivePath(null);
80
+ setPreviewPath(null);
81
+ }
82
+ };
83
+ window.addEventListener('popstate', navigate);
84
+ return () => window.removeEventListener('popstate', navigate);
85
+ }, [treeLoaded, cfg.cloud, cfg.designRel, openLinkedFile]);
86
+
87
+ useEffect(() => {
88
+ const visible = previewPath || (activePath === SYSTEM_TAB ? null : activePath);
89
+ if (visible === previousAddressPath.current) return;
90
+ previousAddressPath.current = visible;
91
+ const rel = normalizeOpenPath(visible, cfg.designRel);
92
+ if (addressMode.current !== 'none' && readOpenParam(location, cfg.designRel) !== rel) {
93
+ history[rel ? 'pushState' : 'replaceState'](rel ? { open: rel } : null, '', withOpenParam(location, rel));
94
+ }
95
+ addressMode.current = 'push';
96
+ }, [activePath, previewPath, cfg.designRel]);
97
+
98
+ const sharePath = previewPath || (activePath === SYSTEM_TAB ? null : activePath);
99
+ const shareShell = cfg.cloud ? 'cloud' : isNativeApp() ? 'native' : 'local';
100
+ const shareLinksFor = (path) => buildShareLinks({
101
+ rel: normalizeOpenPath(path, cfg.designRel), shell: shareShell, location,
102
+ linkedHubUrl: cloudLinkedHub?.url, project: cfg.cloud ? project : localProjectName,
103
+ localUrl: location.origin,
104
+ });
105
+ const showShare = (path = sharePath) => {
106
+ const rel = normalizeOpenPath(path, cfg.designRel);
107
+ if (rel) setShareDialog({ path, rel, label: basename(path) });
108
+ };
109
+
110
+ // Retry from the #115 error panel: re-read /_config FIRST (the stale
111
+ // `canvasOrigin` is the likeliest reason we are here at all), then remount the
112
+ // iframe via the nonce so it navigates against the corrected origin.
113
+ const retryCanvasLoad = useCallback(
114
+ (path) => {
115
+ setCanvasError(null);
116
+ setLoadedPath(null);
117
+ loadServerConfig();
118
+ setCanvasReloadNonce((n) => n + 1);
119
+ if (path && path !== SYSTEM_TAB) setLoadingPath(path);
120
+ },
121
+ [loadServerConfig]
122
+ );
123
+
124
+ /**
125
+ * First open lands on a rendered canvas — Cloud Phase 27 C3.
126
+ *
127
+ * A desktop user chose this project, installed the app and knows what is in
128
+ * it; the empty state is a helpful "pick a screen". A teammate following a
129
+ * link has done none of that, and an empty pane with an arrow pointing at a
130
+ * list is the browser saying "the thing you came for is somewhere else".
131
+ *
132
+ * CLOUD ONLY, and once. The desktop's empty state is deliberately unchanged —
133
+ * it earns its keep there (the ⌘-hover lesson, quick setup) — and re-opening
134
+ * a canvas the person deliberately closed would be a UI arguing with them.
135
+ */
136
+ const autoOpened = useRef(false);
137
+ useEffect(() => {
138
+ if (autoOpened.current) return;
139
+ if (!cfg.cloud) return; // desktop / unknown-yet
140
+ if (new URLSearchParams(location.search).has('open')) { autoOpened.current = true; return; }
141
+ if (tabs.length > 0) return;
142
+ if (!groups.length) return; // tree not loaded
143
+ // The first canvas that is somebody's WORK — a design-system specimen is a
144
+ // rendered canvas too, and not what a teammate followed a link to see.
145
+ let first = null;
146
+ for (const g of groups) {
147
+ for (const p of g.paths || []) {
148
+ if (!CANVAS_EXT_RE.test(p)) continue;
149
+ if (/(^|\/)system\//.test(p)) continue;
150
+ first = p;
151
+ break;
152
+ }
153
+ if (first) break;
154
+ }
155
+ if (!first) return;
156
+ autoOpened.current = true;
157
+ openTab(first, { reveal: false });
158
+ }, [cfg.cloud, groups, tabs.length, openTab]);
159
+
160
+ const openSystem = useCallback(
161
+ (dsName) => {
162
+ // DsFolderRow passes the clicked DS name → scope the System view to it so
163
+ // each folder shows its own tokens + previews. The no-arg callers (menubar,
164
+ // keyboard reopen) only load default data on first open.
165
+ const ds = typeof dsName === 'string' ? dsName : undefined;
166
+ if (ds) loadSystemData(ds);
167
+ else if (!systemData) loadSystemData();
168
+ openTab(SYSTEM_TAB);
169
+ },
170
+ [systemData, loadSystemData, openTab]
171
+ );
172
+
173
+ useEffect(() => {
174
+ wsSend({ type: 'tabs', tabs: tabs.map((t) => t.path).filter((p) => p !== SYSTEM_TAB) });
175
+ }, [tabs]);
176
+
177
+ useEffect(() => {
178
+ if (activePath && activePath !== SYSTEM_TAB) wsSend({ type: 'active', file: activePath });
179
+ else if (activePath === SYSTEM_TAB) wsSend({ type: 'active', file: '' });
180
+ else wsSend({ type: 'active', file: '' });
181
+ }, [activePath]);
182
+
183
+ const closeTab = useCallback(
184
+ (path) => {
185
+ setTabs((prev) => {
186
+ const idx = prev.findIndex((t) => t.path === path);
187
+ if (idx < 0) return prev;
188
+ const next = prev.filter((t) => t.path !== path);
189
+ if (path === activePath) {
190
+ if (next.length === 0) setActivePath(null);
191
+ else setActivePath(next[Math.max(0, idx - 1)].path);
192
+ }
193
+ return next;
194
+ });
195
+ iframesRef.current.delete(path);
196
+ setLoadingPath((p) => (p === path ? null : p));
197
+ },
198
+ [activePath]
199
+ );
200
+
201
+ // The socket stays connected while this ref follows the current config and
202
+ // active tab. Structural events apply to local and remote users alike.
203
+ canvasListChangeRef.current = (change) => {
204
+ if (!change?.rel) return;
205
+ const designRel = (cfg?.designRel || cfg?.designRoot || '.design').replace(/^\/+|\/+$/g, '');
206
+ const file = `${designRel}/${change.rel}`;
207
+ if (change.action === 'removed') {
208
+ closeTab(file);
209
+ } else if (change.action === 'moved' && change.fromRel) {
210
+ const fromFile = `${designRel}/${change.fromRel}`;
211
+ setTabs((prev) => prev.map((t) => t.path === fromFile ? { ...t, path: file } : t));
212
+ setActivePath((prev) => prev === fromFile ? file : prev);
213
+ setLoadingPath((prev) => prev === fromFile ? null : prev);
214
+ iframesRef.current.delete(fromFile);
215
+ }
216
+ };
217
+
218
+ const reloadActive = useCallback(() => {
219
+ if (!activePath || activePath === SYSTEM_TAB) {
220
+ if (activePath === SYSTEM_TAB) loadSystemData();
221
+ return;
222
+ }
223
+ const el = iframesRef.current.get(activePath);
224
+ if (el) el.src = el.src;
225
+ }, [activePath, loadSystemData]);
226
+
227
+ const reloadTree = useCallback(() => loadTree(), [loadTree]);
228
+
229
+ // User-facing tree refresh with a visible spin. The header button and ⌘⇧R call
230
+ // this so the reload icon spins for at least one beat — even when /_index-data
231
+ // returns instantly — so the action registers visually ("something is
232
+ // happening"). The min-duration race keeps the spin from flashing for one
233
+ // frame on a fast read; the ref guard ignores re-entrant clicks. The passive
234
+ // focus backstop below uses the plain reloadTree (no icon to animate).
235
+ const [treeRefreshing, setTreeRefreshing] = useState(false);
236
+ const treeRefreshingRef = useRef(false);
237
+ const refreshTree = useCallback(async () => {
238
+ if (treeRefreshingRef.current) return;
239
+ treeRefreshingRef.current = true;
240
+ setTreeRefreshing(true);
241
+ try {
242
+ await Promise.all([loadTree(), new Promise((r) => setTimeout(r, 550))]);
243
+ } finally {
244
+ treeRefreshingRef.current = false;
245
+ setTreeRefreshing(false);
246
+ }
247
+ }, [loadTree]);
248
+
249
+ // Backstop for the desktop sidecar: re-list the tree whenever the window
250
+ // regains focus. The fs-watch → canvas-list-update auto-refresh can drop
251
+ // events in a `bun --compile` standalone binary (recursive fs.watch is
252
+ // unreliable there) and across a sidecar respawn / WS reconnect, leaving a
253
+ // stale tree after a canvas was created from the ACP chat or a terminal.
254
+ // `/_index-data` is a cheap read and people tab away to the agent and back, so
255
+ // this turns "switch projects to force a refresh" into "just come back to the
256
+ // window". Debounced so a rapid blur/focus burst coalesces to one re-read.
257
+ useEffect(() => {
258
+ let t = null;
259
+ const onFocus = () => {
260
+ if (t) clearTimeout(t);
261
+ t = setTimeout(() => {
262
+ t = null;
263
+ reloadTree();
264
+ }, 150);
265
+ };
266
+ window.addEventListener('focus', onFocus);
267
+ return () => {
268
+ window.removeEventListener('focus', onFocus);
269
+ if (t) clearTimeout(t);
270
+ };
271
+ }, [reloadTree]);
272
+
273
+ // Phase 22 — create a blank brief board from the tree header. POSTs to the
274
+ // main-origin-only /_api/canvas (the untrusted canvas iframe can't reach it),
275
+ // then refreshes the tree and opens the new board so it's immediately the
276
+ // active canvas to annotate. Returns {ok} | {ok:false,error} so the Sidebar
277
+ // can surface a validation/duplicate message inline.
278
+ const createBoard = useCallback(
279
+ async (name) => {
280
+ try {
281
+ const r = await fetch('/_api/canvas', {
282
+ method: 'POST',
283
+ headers: { 'Content-Type': 'application/json' },
284
+ body: JSON.stringify({ name, kind: 'brief-board' }),
285
+ });
286
+ const j = await r.json().catch(() => ({}));
287
+ if (!r.ok || !j.ok) return { ok: false, error: j.error || `create failed (${r.status})` };
288
+ await loadTree();
289
+ openTab(j.file);
290
+ return { ok: true, file: j.file };
291
+ } catch (e) {
292
+ return { ok: false, error: e instanceof Error ? e.message : 'network error' };
293
+ }
294
+ },
295
+ [loadTree, openTab]
296
+ );
297
+
298
+ // Task 20 (enhanced-video-editing) — greenfield "New video": an EMPTY
299
+ // video-comp canvas (drop-first cut building). Dimensions/fps are
300
+ // user-settable (presets 1920×1080 / 1080×1920 / 1080×1080 or custom WxH).
301
+ const createVideo = useCallback(async () => {
302
+ const name = await askText('New video name');
303
+ if (!name) return;
304
+ const dims =
305
+ (await askText(
306
+ 'Size — 1920x1080 (landscape), 1080x1920 (portrait), 1080x1080 (square), or custom WxH',
307
+ '1920x1080'
308
+ )) || '1920x1080';
309
+ const m = dims.toLowerCase().match(/(\d{2,5})\s*[x×]\s*(\d{2,5})/);
310
+ const width = m ? Number(m[1]) : 1920;
311
+ const height = m ? Number(m[2]) : 1080;
312
+ const fps = Math.max(1, Math.min(60, Number(await askText('Frames per second', '30')) || 30));
313
+ try {
314
+ const r = await fetch('/_api/canvas', {
315
+ method: 'POST',
316
+ headers: { 'Content-Type': 'application/json' },
317
+ body: JSON.stringify({ name, kind: 'video-comp', clips: [], fps, width, height }),
318
+ });
319
+ const j = await r.json().catch(() => ({}));
320
+ if (!r.ok || !j.ok) {
321
+ shellToast(`New video failed: ${j.error || `error ${r.status}`}`);
322
+ return;
323
+ }
324
+ await loadTree();
325
+ openTab(j.file);
326
+ setTimelineOpen(true);
327
+ shellToast('New video created — drop clips on the timeline to start the cut.', true);
328
+ } catch (e) {
329
+ shellToast(`New video failed: ${e instanceof Error ? e.message : 'network error'}`);
330
+ }
331
+ }, [loadTree, openTab, askText]);
332
+
333
+ // DDR-150 P4 Task 12 — one-click "udělej z toho video". Reads the ACTIVE
334
+ // canvas's annotation sidecar (main-origin — no cross-origin round-trip),
335
+ // gathers every dropped media-reference chip's src in document order, and POSTs
336
+ // an assembled video-comp (kind: 'video-comp') → opens the new, immediately
337
+ // hand-editable comp. Durations default server-side to fps*3 (the user trims on
338
+ // the Timeline); client-side <video>.duration probing is a documented tightening.
339
+ const assembleVideo = useCallback(async () => {
340
+ if (!activePath || activePath === SYSTEM_TAB) return;
341
+ try {
342
+ const ar = await fetch(`/_api/annotations?file=${encodeURIComponent(activePath)}`);
343
+ const svg = ar.ok ? await ar.text() : '';
344
+ const clips = [];
345
+ if (svg) {
346
+ const doc = new DOMParser().parseFromString(svg, 'image/svg+xml');
347
+ for (const g of doc.querySelectorAll('[data-tool="mediaref"]')) {
348
+ const src = g.getAttribute('data-src');
349
+ if (!src) continue;
350
+ clips.push({ src, mediaKind: g.getAttribute('data-media-kind') === 'audio' ? 'audio' : 'video' });
351
+ }
352
+ }
353
+ if (clips.length === 0) {
354
+ window.alert('Drop video/audio clips on the canvas first, then assemble them into a video.');
355
+ return;
356
+ }
357
+ const baseName = displayName(basename(activePath)).replace(/\.tsx$/i, '');
358
+ const name = `${baseName} Video`;
359
+ const r = await fetch('/_api/canvas', {
360
+ method: 'POST',
361
+ headers: { 'Content-Type': 'application/json' },
362
+ body: JSON.stringify({ name, kind: 'video-comp', clips }),
363
+ });
364
+ const j = await r.json().catch(() => ({}));
365
+ if (!r.ok || !j.ok) {
366
+ window.alert(`Assemble failed: ${j.error || `error ${r.status}`}`);
367
+ return;
368
+ }
369
+ await loadTree();
370
+ openTab(j.file);
371
+ } catch (e) {
372
+ window.alert(`Assemble failed: ${e instanceof Error ? e.message : 'network error'}`);
373
+ }
374
+ }, [activePath, loadTree, openTab]);
375
+
376
+ // DDR-150 dogfood #5 — shared replace-media flow, PICKER-FIRST. The <input
377
+ // type=file> is created + clicked SYNCHRONOUSLY inside the caller's click
378
+ // gesture (browsers revoke transient user-activation after any await, which is
379
+ // why the old fetch-then-click never opened the dialog). The comp-clips lookup
380
+ // + upload + src patch all happen in the change handler, where no activation
381
+ // is needed. `resolveCdId(cc)` maps the fresh enumerator payload to the target
382
+ // media target (sequence clip via cd-id, audio bed via cd-id, or a showreel
383
+ // array-fed src via mediaArrayRef → /_api/edit-array-src). `resolveTarget(cc)`
384
+ // returns { cdId } | { arrayRef } | null.
385
+ const replaceMediaViaPicker = useCallback(
386
+ ({ accept, resolveTarget }) => {
387
+ const canvas = activePath;
388
+ const artboardId = timelineArtboardId || undefined;
389
+ const input = document.createElement('input');
390
+ input.type = 'file';
391
+ input.accept = accept;
392
+ // OFF-SCREEN, not display:none — the native desktop app (Tauri WKWebView)
393
+ // will NOT present the file panel for a `display:none` input (it must be
394
+ // laid out). Off-screen + transparent works in both WKWebView and browsers
395
+ // (dogfood: "replace ... nefunguje ale v desktop app"). Guard against a
396
+ // cancelled dialog leaking the node with a one-shot focus cleanup.
397
+ input.style.cssText =
398
+ 'position:fixed;left:-9999px;top:0;width:1px;height:1px;opacity:0;pointer-events:none';
399
+ document.body.appendChild(input);
400
+ const cleanup = () => {
401
+ if (input.isConnected) input.remove();
402
+ };
403
+ // If the user cancels the panel, `change` never fires — reclaim the node
404
+ // when focus returns to the window (fires on both pick and cancel).
405
+ window.addEventListener('focus', () => setTimeout(cleanup, 300), { once: true });
406
+ input.addEventListener('change', () => {
407
+ const file = input.files?.[0];
408
+ cleanup();
409
+ if (!file) return;
410
+ const ccUrl = `/_api/comp-clips?canvas=${encodeURIComponent(canvas)}${artboardId ? `&artboardId=${encodeURIComponent(artboardId)}` : ''}`;
411
+ fetch(ccUrl)
412
+ .then((r) => r.json().catch(() => ({})))
413
+ .then((cc) => {
414
+ const target = resolveTarget(cc);
415
+ if (!target) {
416
+ shellToast('No replaceable media here (its src is computed) — edit via chat.');
417
+ return null;
418
+ }
419
+ return fetch('/_api/asset', {
420
+ method: 'POST',
421
+ headers: { 'Content-Type': file.type || 'application/octet-stream' },
422
+ body: file,
423
+ })
424
+ .then((r) => r.json().catch(() => ({})))
425
+ .then((up) => {
426
+ if (!up?.path) {
427
+ shellToast(`Upload failed: ${up?.error || 'unknown error'}`);
428
+ return null;
429
+ }
430
+ if (target.arrayRef) {
431
+ // Showreel pattern: the src lives in an array literal.
432
+ return fetch('/_api/edit-array-src', {
433
+ method: 'POST',
434
+ headers: { 'content-type': 'application/json' },
435
+ body: JSON.stringify({
436
+ canvas,
437
+ arrayName: target.arrayRef.arrayName,
438
+ index: target.arrayRef.index,
439
+ field: target.arrayRef.field,
440
+ value: up.path,
441
+ }),
442
+ });
443
+ }
444
+ return fetch('/_api/edit-attr', {
445
+ method: 'POST',
446
+ headers: { 'content-type': 'application/json' },
447
+ body: JSON.stringify({ canvas, id: target.cdId, attr: 'src', value: up.path }),
448
+ });
449
+ });
450
+ })
451
+ .then((r) => (r ? r.json() : null))
452
+ .then((j) => {
453
+ if (j && !j.ok) shellToast(`Replace refused: ${j.error || 'failed'}`);
454
+ else if (j && j.ok) {
455
+ shellToast('Media replaced.', true);
456
+ if (j.seq != null) pushTlUndo(canvas, j.seq, 'replace media');
457
+ }
458
+ })
459
+ .catch(() => shellToast('Replace failed: network error'));
460
+ });
461
+ input.click();
462
+ },
463
+ [activePath, timelineArtboardId, pushTlUndo]
464
+ );
465
+
466
+ // Phase 22 — soft-delete a canvas from the file tree. Confirms (destructive),
467
+ // DELETEs to the main-origin-only endpoint, refreshes the tree, and resets the
468
+ // active tab if the deleted canvas was open. The server moves the whole sidecar
469
+ // set to .design/_trash/ — recoverable locally.
470
+ const deleteBoard = useCallback(
471
+ async (filePath, label) => {
472
+ const ok = window.confirm(
473
+ `Move “${label}” to trash?\n\nIts annotations, history and comments move with it. ` +
474
+ `You can restore it from .design/_trash/.`
475
+ );
476
+ if (!ok) return;
477
+ try {
478
+ const r = await fetch(`/_api/canvas?file=${encodeURIComponent(filePath)}`, {
479
+ method: 'DELETE',
480
+ });
481
+ const j = await r.json().catch(() => ({}));
482
+ if (!r.ok || !j.ok) {
483
+ window.alert(`Could not delete: ${j.error || `error ${r.status}`}`);
484
+ return;
485
+ }
486
+ await loadTree();
487
+ if (activePath === filePath) {
488
+ setTabs([]);
489
+ setActivePath(null);
490
+ }
491
+ } catch (e) {
492
+ window.alert(`Delete failed: ${e instanceof Error ? e.message : 'network error'}`);
493
+ }
494
+ },
495
+ [loadTree, activePath]
496
+ );
497
+
498
+ // feature-file-tree-drag-drop-folders (Task 8/10) — drag-drop AND the
499
+ // context-menu "Move to…" both funnel through this one function. POSTs the
500
+ // main-origin-only /_api/fs-move, then (only AFTER the server ack — no
501
+ // optimistic UI, per rca/issue-canvas-hmr-optimistic-update-consistency)
502
+ // reloads the tree and retargets any open tab / the active path so a
503
+ // dragged-and-open canvas doesn't go dead. Toasts with an inverse-move
504
+ // Undo. Named function expression so the Undo click can call itself.
505
+ const moveCanvasReq = useCallback(
506
+ async function moveCanvasReq(fromPath, toDir) {
507
+ try {
508
+ const r = await fetch('/_api/fs-move', {
509
+ method: 'POST',
510
+ headers: { 'Content-Type': 'application/json' },
511
+ body: JSON.stringify({ file: fromPath, toDir }),
512
+ });
513
+ const j = await r.json().catch(() => ({}));
514
+ if (!r.ok || !j.ok) {
515
+ shellToast(`Could not move: ${j.error || `error ${r.status}`}`);
516
+ return { ok: false, error: j.error };
517
+ }
518
+ const designRel = (cfg?.designRel || cfg?.designRoot || '.design').replace(
519
+ /^\/+|\/+$/g,
520
+ ''
521
+ );
522
+ const fromFile = `${designRel}/${j.fromRel}`;
523
+ const toFile = `${designRel}/${j.toRel}`;
524
+ // #124 — a moved folder keeps its (and its subfolders') open state, and
525
+ // the destination opens so the moved row is visible.
526
+ updateTreeExp((st) => revealPath(remapDirPrefix(st, fromFile, toFile), groups, toFile));
527
+ await loadTree();
528
+ setTabs((prev) => prev.map((t) => (t.path === fromFile ? { path: toFile } : t)));
529
+ setActivePath((prev) => (prev === fromFile ? toFile : prev));
530
+ const fromDir = fromFile.split('/').slice(0, -1).join('/');
531
+ shellToast(`Moved to ${j.toRel.split('/').slice(0, -1).join('/') || '.'}`, true, {
532
+ label: 'Undo',
533
+ onClick: () => {
534
+ moveCanvasReq(toFile, fromDir);
535
+ },
536
+ });
537
+ return { ok: true };
538
+ } catch (e) {
539
+ shellToast(`Move failed: ${e instanceof Error ? e.message : 'network error'}`);
540
+ return { ok: false, error: 'network error' };
541
+ }
542
+ },
543
+ [loadTree, cfg, groups, updateTreeExp]
544
+ );
545
+
546
+ // feature-file-tree-drag-drop-folders (Task 4/9/12) — create a folder under
547
+ // `parentDir`. Two callers: the sidebar header composer (name from its own
548
+ // input state) and the tree-row context menu's "New folder here" (name via
549
+ // `window.prompt` — a native, fully keyboard/screen-reader-operable input,
550
+ // so that path doesn't need its own inline composer instance).
551
+ const newFolderReq = useCallback(
552
+ async (parentDir, name) => {
553
+ try {
554
+ const r = await fetch('/_api/fs-mkdir', {
555
+ method: 'POST',
556
+ headers: { 'Content-Type': 'application/json' },
557
+ body: JSON.stringify({ parent: parentDir, name }),
558
+ });
559
+ const j = await r.json().catch(() => ({}));
560
+ if (!r.ok || !j.ok) {
561
+ const error = j.error || `error ${r.status}`;
562
+ shellToast(`Could not create folder: ${error}`);
563
+ return { ok: false, error };
564
+ }
565
+ // #124 — open the parent so the new folder is visible (it starts closed).
566
+ updateTreeExp((st) => revealPath(st, groups, parentDir, { includeSelf: true }));
567
+ await loadTree();
568
+ return { ok: true, dir: j.dir };
569
+ } catch (e) {
570
+ const error = e instanceof Error ? e.message : 'network error';
571
+ shellToast(`Create folder failed: ${error}`);
572
+ return { ok: false, error };
573
+ }
574
+ },
575
+ [loadTree, groups, updateTreeExp]
576
+ );
577
+
578
+ // feature-file-tree-drag-drop-folders (dogfood follow-up) — delete a
579
+ // folder from the tree-row context menu. Reuses DELETE /_api/canvas (the
580
+ // route now auto-detects a non-.tsx target as a folder delete); every
581
+ // canvas inside is trashed the same recoverable way as a single-canvas
582
+ // delete (`.design/_trash/<stamp>__<slug>/`).
583
+ const deleteFolderReq = useCallback(
584
+ async (dirPath, label) => {
585
+ const ok = window.confirm(
586
+ `Delete folder "${label}"?\n\nEvery canvas inside moves to trash (recoverable from .design/_trash/); ` +
587
+ `any empty subfolders are removed.`
588
+ );
589
+ if (!ok) return;
590
+ try {
591
+ const r = await fetch(`/_api/canvas?file=${encodeURIComponent(dirPath)}`, {
592
+ method: 'DELETE',
593
+ });
594
+ const j = await r.json().catch(() => ({}));
595
+ if (!r.ok || !j.ok) {
596
+ shellToast(`Could not delete folder: ${j.error || `error ${r.status}`}`);
597
+ return;
598
+ }
599
+ await loadTree();
600
+ } catch (e) {
601
+ shellToast(`Delete folder failed: ${e instanceof Error ? e.message : 'network error'}`);
602
+ }
603
+ },
604
+ [loadTree]
605
+ );
606
+
607
+ // Plan T17 — rename a folder: a move to a new name in the same parent (one
608
+ // dir.move action in accepted mode, carrying every canvas inside).
609
+ const renameFolderReq = useCallback(
610
+ async (dirPath, name) => {
611
+ const parent = dirPath.split('/').slice(0, -1).join('/');
612
+ try {
613
+ const r = await fetch('/_api/fs-move', {
614
+ method: 'POST',
615
+ headers: { 'Content-Type': 'application/json' },
616
+ body: JSON.stringify({ file: dirPath, toDir: parent, toName: name }),
617
+ });
618
+ const j = await r.json().catch(() => ({}));
619
+ if (!r.ok || !j.ok) {
620
+ shellToast(`Could not rename folder: ${j.error || `error ${r.status}`}`);
621
+ return;
622
+ }
623
+ // #124 — the renamed folder keeps its open state (and its subfolders').
624
+ const designRel = (cfg?.designRel || cfg?.designRoot || '.design').replace(/^\/+|\/+$/g, '');
625
+ const toDir = typeof j.toRel === 'string' ? `${designRel}/${j.toRel}` : `${parent}/${name}`;
626
+ updateTreeExp((st) => remapDirPrefix(st, dirPath, toDir));
627
+ await loadTree();
628
+ } catch (e) {
629
+ shellToast(`Rename failed: ${e instanceof Error ? e.message : 'network error'}`);
630
+ }
631
+ },
632
+ [loadTree, cfg, updateTreeExp]
633
+ );
634
+
635
+ // Plan T25/L04 — rename a canvas in place (its sidecars follow; an open tab
636
+ // follows the new path) and duplicate one beside itself.
637
+ const renameCanvasReq = useCallback(
638
+ async (filePath, name) => {
639
+ try {
640
+ const r = await fetch('/_api/fs-move', {
641
+ method: 'POST',
642
+ headers: { 'Content-Type': 'application/json' },
643
+ body: JSON.stringify({ file: filePath, toName: name }),
644
+ });
645
+ const j = await r.json().catch(() => ({}));
646
+ if (!r.ok || !j.ok) {
647
+ shellToast(`Could not rename: ${j.error || `error ${r.status}`}`);
648
+ return;
649
+ }
650
+ const designRel = (cfg?.designRel || cfg?.designRoot || '.design').replace(
651
+ /^\/+|\/+$/g,
652
+ ''
653
+ );
654
+ const fromFile = `${designRel}/${j.fromRel}`;
655
+ const toFile = `${designRel}/${j.toRel}`;
656
+ await loadTree();
657
+ setTabs((prev) => prev.map((t) => (t.path === fromFile ? { path: toFile } : t)));
658
+ setActivePath((prev) => (prev === fromFile ? toFile : prev));
659
+ } catch (e) {
660
+ shellToast(`Rename failed: ${e instanceof Error ? e.message : 'network error'}`);
661
+ }
662
+ },
663
+ [loadTree, cfg]
664
+ );
665
+ const duplicateCanvasReq = useCallback(
666
+ async (filePath) => {
667
+ try {
668
+ const r = await fetch('/_api/canvas', {
669
+ method: 'POST',
670
+ headers: { 'Content-Type': 'application/json' },
671
+ body: JSON.stringify({ duplicateOf: filePath }),
672
+ });
673
+ const j = await r.json().catch(() => ({}));
674
+ if (!r.ok || !j.ok) {
675
+ shellToast(`Could not duplicate: ${j.error || `error ${r.status}`}`);
676
+ return;
677
+ }
678
+ await loadTree();
679
+ shellToast(`Duplicated as ${j.rel.split('/').pop().replace(/\.tsx$/i, '')}`, true);
680
+ } catch (e) {
681
+ shellToast(`Duplicate failed: ${e instanceof Error ? e.message : 'network error'}`);
682
+ }
683
+ },
684
+ [loadTree]
685
+ );
686
+
687
+ const deleteFileReq = useCallback(
688
+ async (filePath, name) => {
689
+ if (!window.confirm(`Move “${name}” to trash?\n\nYou can restore it from .design/_trash/.`)) return;
690
+ try {
691
+ const r = await fetch(`/_api/canvas?file=${encodeURIComponent(filePath)}`, { method: 'DELETE' });
692
+ const j = await r.json().catch(() => ({}));
693
+ if (!r.ok || !j.ok) {
694
+ shellToast(`Could not delete: ${j.error || `error ${r.status}`}`);
695
+ return;
696
+ }
697
+ await loadTree();
698
+ } catch (e) {
699
+ shellToast(`Delete failed: ${e instanceof Error ? e.message : 'network error'}`);
700
+ }
701
+ },
702
+ [loadTree]
703
+ );
704
+
705
+ const clearSelected = useCallback(() => {
706
+ wsSend({ type: 'clear-select' });
707
+ setSelected(null);
708
+ if (activePath && activePath !== SYSTEM_TAB) {
709
+ const el = iframesRef.current.get(activePath);
710
+ if (el && el.contentWindow) {
711
+ try {
712
+ el.contentWindow.postMessage({ dgn: 'force-clear' }, '*');
713
+ } catch {}
714
+ }
715
+ }
716
+ }, [activePath]);
717
+ return {
718
+ assembleVideo, clearSelected, closeTab, createBoard, createVideo, deleteBoard, deleteFileReq,
719
+ deleteFolderReq, duplicateCanvasReq, moveCanvasReq, newFolderReq, openLinkedFile, openSystem,
720
+ openTab, refreshTree, reloadActive, renameCanvasReq, renameFolderReq, replaceMediaViaPicker,
721
+ retryCanvasLoad, shareLinksFor, sharePath, shareShell, showShare, treeRefreshing
722
+ };
723
+ }