@marver-design/marver 0.26.0 → 0.27.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 (96) hide show
  1. package/CHANGELOG.md +158 -0
  2. package/README.md +10 -5
  3. package/dist/{anchor-check-Dg5xpNnU.mjs → anchor-check-ChdDqL5z.mjs} +1 -1
  4. package/dist/{audio-CmSRYFEs.mjs → audio-Dw1lfMdb.mjs} +14 -0
  5. package/dist/{bake-DtVlm0_F.mjs → bake-DM_uWgAA.mjs} +1 -1
  6. package/dist/{boards-DYG22tOe.mjs → boards-DlTcpF47.mjs} +1 -1
  7. package/dist/{build-C_gUgcdC.mjs → build-DZnFysGU.mjs} +4 -4
  8. package/dist/{capture-CrqvU_jh.mjs → capture-vadKjuCo.mjs} +2 -1
  9. package/dist/cli.mjs +28 -16
  10. package/dist/{comments-BqXua-XL.mjs → comments-DxOkCSNE.mjs} +4 -4
  11. package/dist/{daemon-DZo6o3rU.mjs → daemon-BSA0lV8d.mjs} +400 -274
  12. package/dist/detect-C0wpaePX.mjs +125 -0
  13. package/dist/dev-eQJhWsqg.mjs +1273 -0
  14. package/dist/dev-lock-C_FC70Mu.mjs +65 -0
  15. package/dist/exclusive-B1RtpeeP.mjs +150 -0
  16. package/dist/{init-D8DtrK_F.mjs → init-COD0x48i.mjs} +5 -3
  17. package/dist/{link-BNzLvdhI.mjs → link-DDXZVGtv.mjs} +20 -8
  18. package/dist/ls-D7O1G505.mjs +38 -0
  19. package/dist/{marks-NQi0wZJ4.mjs → marks-CWM3WJjc.mjs} +1 -1
  20. package/dist/perf-BWzQwZqj.mjs +369 -0
  21. package/dist/perf-BoDSkbEb.mjs +429 -0
  22. package/dist/perf-jam-D55U3FZK.mjs +242 -0
  23. package/dist/{plugin-CTD0rydA.mjs → plugin-C-E7omsh.mjs} +425 -66
  24. package/dist/{poster-ChjXGTS5.mjs → poster-Bx83ZYVK.mjs} +2 -1
  25. package/dist/{profile-WU9qcbIo.mjs → profile-Bh5Y5zpW.mjs} +1 -1
  26. package/dist/{publish-bakes-CEP_2NRc.mjs → publish-bakes-aljgm45S.mjs} +2 -2
  27. package/dist/{queue-BuiCKSX1.mjs → queue-CAM_vNmX.mjs} +3 -3
  28. package/dist/recover-t9Pno3u9.mjs +66 -0
  29. package/dist/{session-qZWKt_VA.mjs → session-BAaJsK5c.mjs} +1 -1
  30. package/dist/{share--oFJ1bCI.mjs → share-W5H3BNvP.mjs} +1 -1
  31. package/dist/shot-DoHLl6ig.mjs +139 -0
  32. package/dist/{shot-DqcxJibP.mjs → shot-LFhC-WYD.mjs} +343 -19
  33. package/dist/slots-DCDo3N0x.mjs +471 -0
  34. package/dist/speech-worker.mjs +40 -5
  35. package/dist/{sync-DKk-yT1V.mjs → sync-BQVlHZpx.mjs} +4 -3
  36. package/dist/{work-F5u-twpJ.mjs → work-Bp1p39kq.mjs} +4 -2
  37. package/dist/{work-VvX_JIgl.mjs → work-BroFwnup.mjs} +4 -2
  38. package/docs/boards-and-folders.md +3 -1
  39. package/docs/jam-session.md +78 -7
  40. package/docs/live-jam.md +8 -0
  41. package/docs/performance.md +262 -0
  42. package/package.json +2 -2
  43. package/src/client/content/index.tsx +3 -0
  44. package/src/client/content/video.tsx +6 -2
  45. package/src/client/frame-host/bridge.js +22 -6
  46. package/src/client/frame-host/inspect.js +8 -3
  47. package/src/client/frame-host/keys.js +6 -2
  48. package/src/client/frame-host/main.tsx +17 -5
  49. package/src/client/shell/App.tsx +188 -29
  50. package/src/client/shell/BoardList.tsx +5 -5
  51. package/src/client/shell/Comments.tsx +3 -2
  52. package/src/client/shell/JamSurface.tsx +13 -5
  53. package/src/client/shell/LockedApp.tsx +5 -5
  54. package/src/client/shell/Play.tsx +27 -15
  55. package/src/client/shell/Toolbar.tsx +17 -5
  56. package/src/client/shell/api.ts +206 -0
  57. package/src/client/shell/canvas/Canvas.tsx +30 -3
  58. package/src/client/shell/canvas/FrameNode.tsx +15 -5
  59. package/src/client/shell/canvas/admission.ts +8 -1
  60. package/src/client/shell/canvas/camera-broadcast.ts +15 -5
  61. package/src/client/shell/canvas/ctl.ts +2 -0
  62. package/src/client/shell/canvas/frame-registry.ts +28 -2
  63. package/src/client/shell/canvas/sleep.ts +4 -1
  64. package/src/client/shell/comments-store.ts +12 -4
  65. package/src/client/shell/goto.ts +22 -10
  66. package/src/client/shell/icons.tsx +2 -0
  67. package/src/client/shell/jam-capture.ts +96 -16
  68. package/src/client/shell/jam-keys.ts +51 -18
  69. package/src/client/shell/jam-lane.tsx +46 -5
  70. package/src/client/shell/jam-panel.tsx +66 -13
  71. package/src/client/shell/jam-queue.ts +3 -3
  72. package/src/client/shell/jam-session.tsx +14 -8
  73. package/src/client/shell/jam-state.ts +48 -6
  74. package/src/client/shell/jam-surface-parts.tsx +10 -6
  75. package/src/client/shell/jam-voice.ts +7 -5
  76. package/src/client/shell/legacy-links.ts +2 -2
  77. package/src/client/shell/main.tsx +4 -0
  78. package/src/client/shell/notes.ts +8 -1
  79. package/src/client/shell/perf.ts +69 -58
  80. package/src/client/shell/recorder-core.ts +183 -0
  81. package/src/client/shell/recorder.ts +565 -0
  82. package/src/client/shell/store.ts +268 -103
  83. package/src/client/shell/styles.css +54 -9
  84. package/src/client/stage/main.tsx +2 -0
  85. package/templates/AGENTS-embedded.md +22 -4
  86. package/templates/AGENTS-studio.md +22 -4
  87. package/templates/demo/dark.tsx +1 -1
  88. package/templates/demo/welcome.tsx +1 -1
  89. package/templates/instructions/jam.md +5 -3
  90. package/templates/instructions/welcome.md +6 -3
  91. package/dist/config-Cf7EjAMf.mjs +0 -292
  92. package/dist/dev-_Nlsc6v9.mjs +0 -742
  93. package/dist/dev-lock-DWSpa6nj.mjs +0 -179
  94. package/dist/perf-D6VmmJ2q.mjs +0 -68
  95. package/dist/perf-DPbLGhhO.mjs +0 -49
  96. package/dist/shot-CNbHoZ6H.mjs +0 -86
@@ -1,14 +1,17 @@
1
1
  import { create } from 'zustand'
2
2
  import { ROUTE, slideSize } from '../const.ts'
3
3
  import { tidy, parseLayout, type BoardLayout, type TidyNode } from './tidy.ts'
4
- import { clearNoteHeights, noteHeight, noteReserve, notesCramped, setNoteHeight } from './notes.ts'
4
+ import { clearNoteHeights, noteHeight, noteReserve, notesCramped, scopeNotes, setNoteHeight } from './notes.ts'
5
5
  import { stableNodeKey } from './keys.ts'
6
6
  import { canvasCtl } from './canvas/ctl.ts'
7
+ import { api, beforeResume, canvasStopped, holdsReload, lostInResume, mvFetch, noteUnsaved, onLinkNotice, savedInResume, scoped, STOPPED_WAY, withWs } from './api.ts'
7
8
  // @ts-expect-error virtual module provided by the plugin
8
9
  import shConfig from 'virtual:sh-config'
9
10
  // @ts-expect-error virtual module: null in dev; a published build inlines manifest+boards
10
11
  import shData from 'virtual:sh-data'
11
12
 
13
+ scopeNotes(scoped('mv-notes')) // a per-viewer preference, kept per canvas (spec 28 A1.6)
14
+
12
15
  /** Published-build data. Non-null = static site: no API, no saves, no live events.
13
16
  * `names` is the switcher list; `default` is where `/` opens - never a synthesized
14
17
  * aggregate of a filtered build. */
@@ -197,8 +200,9 @@ export interface BoardMeta {
197
200
  export async function fetchBoardTree(): Promise<TreeSnapshot> {
198
201
  if (DATA) return { tree: DATA.tree ?? DATA.names.map((n) => ({ kind: 'board', name: n })), base: { boards: {}, folders: null }, titles: DATA.titles ?? {}, meta: DATA.meta ?? {} }
199
202
  const [boards, reg] = await Promise.all([
200
- fetch(`${ROUTE}/api/boards`).then((r) => r.json()) as Promise<{ name: string; sha256: string; order?: number; folder?: string; title?: string; type?: BoardType; status?: BoardMeta['status'] | null; settable?: StatusWord[]; error?: string }[]>,
201
- fetch(`${ROUTE}/api/folders`).then(async (r) => {
203
+ // a refusal says why in the server's own words (a symlinked design/boards: BoardList says it out loud)
204
+ api('boards').then(async (r) => { if (!r.ok) throw new Error((await r.json().catch(() => null))?.error ?? `boards ${r.status}`); return r.json() }) as Promise<{ name: string; sha256: string; order?: number; folder?: string; title?: string; type?: BoardType; status?: BoardMeta['status'] | null; settable?: StatusWord[]; error?: string }[]>,
205
+ api('folders').then(async (r) => {
202
206
  const j = await r.json() as { folders?: { name: string; order?: number; parent?: string; title?: string }[]; sha256?: string | null; error?: string }
203
207
  if (!r.ok) throw new Error(j?.error ?? `folders ${r.status}`)
204
208
  return j
@@ -239,7 +243,7 @@ export const landingBoard = async (): Promise<string> => (await fetchBoardNames(
239
243
  * off a published bundle (whose frames are all on a published board). Throws on transport failure. */
240
244
  export async function fetchMembership(): Promise<{ boards: { name: string; frames: string[] }[]; unplaced: string[] }> {
241
245
  if (!DATA) {
242
- const r = await fetch(`${ROUTE}/api/membership`)
246
+ const r = await api('membership')
243
247
  if (!r.ok) throw new Error(`membership ${r.status}`)
244
248
  return r.json()
245
249
  }
@@ -271,10 +275,10 @@ export const logReload = (entry: Record<string, unknown>) => {
271
275
  if (PUBLISHED) return
272
276
  const body = { tab: TAB, ...entry }
273
277
  // a page's very first request may go before its request cookie exists: a GET primes it, then once more
274
- void postOwner('perf/reload', body).then((r) => (r.status === 403 ? fetch(`${ROUTE}/api/work`).then(() => postOwner('perf/reload', body)) : r)).catch(() => {})
278
+ void postOwner('perf/reload', body).then((r) => (r.status === 403 ? api('work').then(() => postOwner('perf/reload', body)) : r)).catch(() => {})
275
279
  }
276
280
  const postOwner = (path: string, body: unknown) =>
277
- fetch(`${ROUTE}/api/${path}`, { method: 'POST', headers: { 'content-type': 'application/json', 'x-mv-c': csrf() }, body: JSON.stringify(body) })
281
+ api(path, { method: 'POST', headers: { 'content-type': 'application/json', 'x-mv-c': csrf() }, body: JSON.stringify(body) })
278
282
 
279
283
  /** Add to board (the Not on a board view): these frames appended to a board's file, as
280
284
  * `marver boards pin` does. The answer is said; the file change re-reads the sidebar and the view. */
@@ -313,17 +317,19 @@ const nodeKey = () => 'n_' + Math.random().toString(36).slice(2, 8)
313
317
  let manifestRev = 0
314
318
  export const bumpManifestRev = () => { manifestRev++ }
315
319
 
320
+ /** ws= binds the document to this canvas (spec 28 A1.11): another project on this port later answers a
321
+ * frame's own reload with the "another canvas" page (server/guard.ts), never with its frame. */
316
322
  export function frameUrl(frame: FrameEntry, theme: string): string {
317
- return frame.kind === 'html'
323
+ return withWs(frame.kind === 'html'
318
324
  ? `/${frame.file}?theme=${theme}&r=${manifestRev}` // r= carries the generation for the sh:ready guard (static serving ignores it)
319
- : `${ROUTE}/frame/?id=${encodeURIComponent(frame.id)}&theme=${theme}&r=${manifestRev}`
325
+ : `${ROUTE}/frame/?id=${encodeURIComponent(frame.id)}&theme=${theme}&r=${manifestRev}`)
320
326
  }
321
327
 
322
328
  /** The global view theme: the user's sticky preference, applied across boards and
323
329
  * reloads. Frames resolve to it unless they declare meta.theme or carry a user pin. */
324
330
  const initialViewTheme = () => {
325
331
  try {
326
- const t = localStorage.getItem('mv-view-theme')
332
+ const t = localStorage.getItem(scoped('mv-view-theme'))
327
333
  if (t && CONFIG.themes.includes(t)) return t
328
334
  } catch { /* storage unavailable */ }
329
335
  return CONFIG.themes[0] ?? 'light'
@@ -342,30 +348,46 @@ const measuredHeights = new Map<string, number>()
342
348
  * agent may have edited frames since), once from the bundle on a published canvas. A stale entry
343
349
  * is still the best first guess - the live measurement corrects it, and the dev shell writes the
344
350
  * correction back. */
345
- const savedHeights = new Map<string, number>()
346
- /** The frames that measure (render a Doc), as the dev server read their sources at the last load -
347
- * only theirs is a height to trust: a Doc turned bare Md keeps the size its board gives it, even
348
- * in a page that measured it as a Doc earlier. null = no such list (a published bundle ships only
349
- * measuring frames' heights). */
351
+ let savedHeights = new Map<string, number>()
352
+ /** The frames that measure (render a Doc), as the dev server read their sources at the load that
353
+ * committed - only theirs is a height to trust: a Doc turned bare Md keeps the size its board gives
354
+ * it, even in a page that measured it as a Doc earlier. null = no such list (a published bundle
355
+ * ships only measuring frames' heights). */
350
356
  let measuring: Set<string> | null = null
357
+ /** What one board load read of the sizes. Read by its request, installed by its commit (spec 28 A1.7): a
358
+ * request that never commits - another board chosen, a failed read - changes nothing the mounted board
359
+ * reads, its settle rule (settleRule) and its known heights included. */
360
+ interface SizeRead { saved: Map<string, number>; measuring: Set<string> | null }
361
+ /** Set only while a load prepares its nodes (the synchronous end of loadBoardState): the sizes it read. */
362
+ let preparing: SizeRead | null = null
363
+ const savedNow = () => preparing?.saved ?? savedHeights
351
364
  let publishedLoaded = false
352
- async function loadSavedHeights(): Promise<void> {
365
+ /** The sizes as the server has them now, for one load; null = nothing new to read (a published canvas reads its
366
+ * bundle once, here; no answer keeps what is installed). */
367
+ async function readSizes(): Promise<SizeRead | null> {
353
368
  if (DATA) {
354
- if (publishedLoaded) return
355
- publishedLoaded = true
356
- for (const [k, v] of Object.entries(DATA.sizes ?? {})) if (typeof v === 'number' && Number.isFinite(v) && v > 0) savedHeights.set(k, Math.round(v))
357
- return
369
+ if (!publishedLoaded) {
370
+ publishedLoaded = true
371
+ for (const [k, v] of Object.entries(DATA.sizes ?? {})) if (typeof v === 'number' && Number.isFinite(v) && v > 0) savedHeights.set(k, Math.round(v))
372
+ }
373
+ return null
358
374
  }
359
375
  try {
360
- const r = await fetch(`${ROUTE}/api/sizes`)
361
- if (!r.ok) return
376
+ const r = await api('sizes')
377
+ if (!r.ok) return null
362
378
  const body = (await r.json()) as { heights?: Record<string, unknown>; measuring?: unknown }
363
- savedHeights.clear()
364
- for (const [k, v] of Object.entries(body.heights ?? {})) if (typeof v === 'number' && Number.isFinite(v) && v > 0) savedHeights.set(k, Math.round(v))
365
- measuring = Array.isArray(body.measuring) ? new Set(body.measuring.filter((x): x is string => typeof x === 'string')) : null
366
- } catch { /* no cache: placeholders, as before */ }
379
+ const saved = new Map<string, number>()
380
+ for (const [k, v] of Object.entries(body.heights ?? {})) if (typeof v === 'number' && Number.isFinite(v) && v > 0) saved.set(k, Math.round(v))
381
+ return { saved, measuring: Array.isArray(body.measuring) ? new Set(body.measuring.filter((x): x is string => typeof x === 'string')) : null }
382
+ } catch { return null } // no cache: placeholders, as before
367
383
  }
368
- const measures = (frameId: string) => !measuring || measuring.has(frameId)
384
+ /** The committed load's sizes become the page's. */
385
+ function installSizes(read: SizeRead | null): void {
386
+ if (!read) return
387
+ savedHeights = read.saved
388
+ measuring = read.measuring
389
+ }
390
+ const measures = (frameId: string) => { const m = preparing ? preparing.measuring : measuring; return !m || m.has(frameId) }
369
391
 
370
392
  // settled heights that differ from the committed ones, written back in batches (dev only). One
371
393
  // write in flight at a time; a height that changes while its write is in flight queues behind it,
@@ -383,6 +405,7 @@ const persistHeight = (key: string, h: number) => {
383
405
  async function flushHeights() {
384
406
  heightsTimer = undefined
385
407
  if (flushing || !pendingHeights.size) return
408
+ if (canvasStopped()) return // held until the canvas answers again (A1.11): the resume flushes them
386
409
  flushing = true
387
410
  const batch = Object.fromEntries([...pendingHeights].slice(0, 500))
388
411
  for (const [k, v] of Object.entries(batch)) { pendingHeights.delete(k); inflightHeights.set(k, v) }
@@ -405,7 +428,7 @@ async function flushHeights() {
405
428
  if (pendingHeights.size) heightsTimer ??= setTimeout(flushHeights, 1500)
406
429
  }
407
430
 
408
- const hasKnownHeight = (frameId: string, w: number) => measures(frameId) && (measuredHeights.has(`${frameId}@${w}`) || savedHeights.has(`${frameId}@${w}`))
431
+ const hasKnownHeight = (frameId: string, w: number) => measures(frameId) && (measuredHeights.has(`${frameId}@${w}`) || savedNow().has(`${frameId}@${w}`))
409
432
 
410
433
  /** The Doc sizes a layout was computed around: each auto content node whose height is known, by key,
411
434
  * as "WxH" (one line per node in the board file). A composed board saves it with its positions
@@ -439,7 +462,7 @@ function defaultSize(frame: FrameEntry) {
439
462
  const vp = CONFIG.viewports[frame.viewport ?? '']
440
463
  const w = vp?.width ?? frame.contentWidth
441
464
  const key = `${frame.id}@${w}`
442
- const known = measures(frame.id) ? measuredHeights.get(key) ?? savedHeights.get(key) : undefined
465
+ const known = measures(frame.id) ? measuredHeights.get(key) ?? savedNow().get(key) : undefined
443
466
  return { w, h: known ?? vp?.height ?? Math.round(w * 0.75) }
444
467
  }
445
468
  const vp = CONFIG.viewports[frame.viewport ?? ''] ?? CONFIG.viewports.mobile ?? { width: 390, height: 844 }
@@ -450,6 +473,58 @@ let resizedInGesture = false
450
473
  // set inside the store (they need it): a reload's height hold, and the marks-vs-documents check
451
474
  let holdHeight: (key: string) => void = () => {}
452
475
  let reconcile: () => void = () => {}
476
+
477
+ // ---- the recorder's view of the store (spec 28 A1.7) -------------------------------------------------------------
478
+ /** A change that moves or resizes nodes runs under a cause. The recorder's subscriber reads it while that change
479
+ * notifies it (zustand notifies inside set) and calls a move outside any cause `unknown`. The inner cause wins -
480
+ * except that runTidy keeps an outer one (a device preset, a resize, a reflow tidies through it). Synchronous code
481
+ * only: a cause never spans an await. */
482
+ let geoCause: string | null = null
483
+ export const geometryCause = (): string | null => geoCause
484
+ export function withCause<T>(cause: string, fn: () => T): T {
485
+ const was = geoCause
486
+ geoCause = cause
487
+ try { return fn() } finally { geoCause = was }
488
+ }
489
+ /** How a board load started: the page's first, a switch, or the open board read from disk again. */
490
+ export type LoadCause = 'boot' | 'switch' | 'disk-reload'
491
+ /** Why a requested load never committed: a newer load, a failed read, an edit or a board change meanwhile, unsaved edits. */
492
+ export type RequestCut = 'superseded' | 'error' | 'edited' | 'unsaved'
493
+ /** Board loads as the recorder sees them: recorder.ts installs these on a dev canvas - no-ops until then, and for good
494
+ * on a published one. A request owns the geometry from its commit, and `commit` runs right BEFORE the set that
495
+ * mounts the load: mounting it is never a move. */
496
+ export const recorderHooks = {
497
+ request: (_board: string, _cause: LoadCause): string => '',
498
+ /** a request is about to commit: the load that was up ends - before the incoming sizes are installed, so it ends by
499
+ * the sizes it read (which frames measure), its board's nodes still in the store */
500
+ handover: (_request: string): void => {},
501
+ commit: (_request: string, _nodes: readonly Node[], _manifest: Manifest): void => {},
502
+ cut: (_request: string, _reason: RequestCut): void => {},
503
+ /** nothing of the reflow story is left: no reflow pending, no height held, none owed */
504
+ reflowIdle: (): void => {},
505
+ }
506
+ let reflowIdleNow: () => boolean = () => true // set inside the store
507
+ /** switchBoard's calls so far - each switch, and each cancel (a switch to the board on screen): the router tells the
508
+ * second event of one navigation from a new one by nothing having switched since the first (App.tsx). */
509
+ let switchCalls = 0
510
+ export const switchCount = (): number => switchCalls
511
+ /** No reflow pending, no height held, none owed. */
512
+ export const reflowIdle = (): boolean => reflowIdleNow()
513
+ /** What a node waits for before its load settles (recorder.ts): a content frame that measures (renders a Doc) - a
514
+ * settled height at its width now; any other frame (hi-fi, html, a device-sized one, content without a Doc) - its
515
+ * ready; a frame not in the manifest - nothing: it is missing. */
516
+ export function settleRule(n: Node, manifest: Manifest | null): 'measure' | 'ready' | 'missing' {
517
+ const f = n.missing ? undefined : manifest?.frames.find((x) => x.id === n.frame)
518
+ if (!f) return 'missing'
519
+ return f.contentWidth && n.sizeMode !== 'device' && measures(f.id) ? 'measure' : 'ready'
520
+ }
521
+ /** Did a measuring node open at a height already known (committed in _sizes.json, or measured earlier in this page)? */
522
+ export const knownHeight = (frameId: string, w: number): boolean => hasKnownHeight(frameId, Math.round(w))
523
+ /** What measureNode took: `fit` - the report was taken at the node's width `w` (applied, or its height already) - the
524
+ * only one a settled report settles a node with; `width` - it adopted the Doc's own width `w`, and the next report is
525
+ * the one; `held` - kept for when the node's reload lets go; `ignored` - not taken. */
526
+ export interface MeasureResult { took: 'ignored' | 'held' | 'width' | 'fit'; w?: number }
527
+ const IGNORED: MeasureResult = { took: 'ignored' }
453
528
  // sidebar marks: the fetch in flight, and acknowledgements the server has not confirmed yet
454
529
  let marksSeq = 0
455
530
  let marksTimer: ReturnType<typeof setTimeout> | undefined
@@ -506,7 +581,8 @@ interface State {
506
581
  gesture: boolean // a frame drag/resize is in progress - canvas panning is disabled
507
582
  /** the node a person resized last (a new object each time) - a measurement never sets it */
508
583
  resized: { key: string } | null
509
- laser: boolean // laser/inspect mode: frames outline their structure
584
+ laser: boolean // laser mode: a pointer - the element under the cursor lit, a click copies its path
585
+ laserInspect: boolean // the laser as inspect (⌥L): every element outlined, as the laser was before 0.26.1
510
586
  board: string // active board name; UNPLACED is the Not on a board view
511
587
  boardAuto: boolean // auto boards gain new frames on arrival; curated boards never do
512
588
  deviceView: string | null // board-wide device preview (viewport name), null = free-form layout
@@ -542,7 +618,7 @@ interface State {
542
618
  resizeNode(key: string, w: number, h: number): void
543
619
  /** `settled`: the Doc's fonts, images and diagrams are done (content/index.tsx). false = provisional
544
620
  * (an image still loading) - it may grow a frame, never shrink it under a known height. */
545
- measureNode(key: string, frameId: string, ownWidth: number, measuredWidth: number, height: number, settled?: boolean): void
621
+ measureNode(key: string, frameId: string, ownWidth: number, measuredWidth: number, height: number, settled?: boolean): MeasureResult
546
622
  /** A node's sticky column was drawn (or grew, or went): its extent from the node's top, world px. */
547
623
  noteMeasured(key: string, height: number): void
548
624
  setStatus(key: string, status: Node['status'], error?: string): void
@@ -556,7 +632,9 @@ interface State {
556
632
  setInteract(key: string | null): void
557
633
  setPlay(p: State['play']): void
558
634
  setGesture(g: boolean): void
559
- setLaser(on: boolean): void
635
+ setLaser(on: boolean, inspect?: boolean): void
636
+ /** L (`inspect` false) or ⌥L (true): the same mode again turns the laser off; the other switches to it */
637
+ toggleLaser(inspect: boolean): void
560
638
  invalidateFrames(frameIds: string[], revision: string, docs?: { epoch?: string; docs?: Record<string, number> }): void
561
639
  setExternalLease(nodeKey: string, reason: 'laser' | 'comment', on: boolean): void
562
640
  /** A safe point (a lease ended, a gesture ended): stale nodes may reload now. */
@@ -641,12 +719,21 @@ export function frameIsLeased(frameId: string, s: State): boolean {
641
719
  !!s.externalLeases[n.key]))
642
720
  }
643
721
 
722
+ /** What a board save says when the board's file changed on disk meanwhile: the file wins, the board is read again. */
723
+ export const DISK_WON = 'board changed on disk - canvas layout reloaded'
724
+ /** What a board save says when the board was renamed or removed meanwhile: it is not created again. */
725
+ export const BOARD_GONE = 'this board was renamed or removed - not recreating it'
726
+
644
727
  export const useStore = create<State>((set, get) => {
645
728
  let saveTimer: ReturnType<typeof setTimeout> | undefined
646
729
  let saveChain: Promise<boolean> = Promise.resolve(true) // saves are serialized; responses only commit if the board is still active
647
730
  let editRev = 0 // bumps per edit; a stale save response may never clear dirty over a newer edit
648
731
  let loadSeq = 0 // stale boot() responses never overwrite a newer board
649
732
  let switchSeq = 0 // last click wins when board switches race
733
+ let firstLoad = true // the page's first boot() is its boot; every later one reads the board from disk again
734
+ // the recorder's requests in flight (spec 28 A1.7): a newer boot, a newer switch, or a switch that commits supersedes
735
+ // them the moment it does - not when their fetch answers, which may be never
736
+ let bootRequest = '', switchRequest = ''
650
737
  // While a board file is being renamed or rewritten by a structural write (rename, the
651
738
  // sidebar's tree arrange), autosave must not fire against it (a mustExist PUT would
652
739
  // 409-gone and clear dirty, losing the in-flight edit; a stale baseHash would 409 and
@@ -668,12 +755,17 @@ export const useStore = create<State>((set, get) => {
668
755
  // two conditions pending are EITHER one (a later ask never drops an earlier one).
669
756
  let reflowTimer: ReturnType<typeof setTimeout> | undefined
670
757
  let reflowCheck: (() => boolean) | null = null
758
+ /** Why the pending reflow runs (spec 28 A1.7) - merged across the calls it coalesces, kept through a drag, a camera
759
+ * in flight and held heights: the recorder names its moves `reflow:<reasons>`. */
760
+ type ReflowReason = 'measured' | 'cramped' | 'stale' | 'gesture-end'
761
+ let reflowReasons = new Set<ReflowReason>()
671
762
  /** A board load (boot, switch) starts its own reflow story: whatever was pending - an
672
763
  * unconditional reflow from the board that was up - must never carry over and tidy this one. */
673
- const cancelReflow = () => { clearTimeout(reflowTimer); reflowTimer = undefined; reflowCheck = null }
764
+ const cancelReflow = () => { clearTimeout(reflowTimer); reflowTimer = undefined; reflowCheck = null; reflowReasons = new Set() }
674
765
  /** How long a content reflow waits for a camera in flight - past it, the rows move anyway. */
675
766
  const REFLOW_CAMERA_WAIT = 1500
676
- const scheduleReflow = (onlyIf?: () => boolean, delay = 400, cameraSince?: number) => {
767
+ const scheduleReflow = (reason: ReflowReason | null, onlyIf?: () => boolean, delay = 400, cameraSince?: number) => {
768
+ if (reason) reflowReasons.add(reason)
677
769
  const boardAt = get().board
678
770
  const prev = reflowTimer !== undefined ? reflowCheck : undefined // undefined: nothing pending
679
771
  reflowCheck = prev === null || !onlyIf ? null : prev ? () => prev() || onlyIf() : onlyIf
@@ -683,20 +775,23 @@ export const useStore = create<State>((set, get) => {
683
775
  const check = reflowCheck
684
776
  reflowCheck = null
685
777
  const s = get()
686
- if (s.board !== boardAt) return
778
+ if (s.board !== boardAt) { reflowReasons = new Set(); reflowSettled(); return }
687
779
  // defer, never drop - retries after the drag
688
- if (s.gesture) { scheduleReflow(check ?? undefined); return }
780
+ if (s.gesture) { scheduleReflow('gesture-end', check ?? undefined); return }
689
781
  // and after a camera flight: a link's fit lands first, then the rows move around the frames it
690
782
  // showed (holdView keeps them where the fit put them). Looked at often, so the reflow follows the
691
783
  // landing closely - and never waited on past REFLOW_CAMERA_WAIT: a camera that keeps moving (fit
692
784
  // after fit) does not hold the rows apart forever
693
785
  const since = cameraSince ?? Date.now()
694
- if (canvasCtl.cameraBusy() && Date.now() - since < REFLOW_CAMERA_WAIT) { scheduleReflow(check ?? undefined, 60, since); return }
695
- if (check && !check()) return
786
+ if (canvasCtl.cameraBusy() && Date.now() - since < REFLOW_CAMERA_WAIT) { scheduleReflow(null, check ?? undefined, 60, since); return }
787
+ if (check && !check()) { reflowReasons = new Set(); reflowSettled(); return }
696
788
  for (const k of [...holds.keys()]) if (!s.nodes.some((n) => n.key === k && !n.missing)) letGo(k, false) // gone: no longer in the batch
697
- if (holds.size) { reflowOwed = true; return } // a batch is reloading: the rows move once, when it lets go
789
+ if (holds.size) { reflowOwed = true; return } // a batch is reloading: the rows move once, when it lets go (its reasons kept)
790
+ const why = `reflow:${[...reflowReasons].sort().join('+') || 'measured'}`
791
+ reflowReasons = new Set()
698
792
  // content moved the rows, not the human: hold what they are looking at still (Canvas.tsx)
699
- if (composed(s)) { canvasCtl.holdView(); s.runTidy() }
793
+ if (composed(s)) withCause(why, () => { canvasCtl.holdView(); s.runTidy() })
794
+ reflowSettled()
700
795
  }, delay)
701
796
  }
702
797
  /** Boards whose layout the shell owns: a recipe, scene rows, or the auto board. Room for a
@@ -720,11 +815,15 @@ export const useStore = create<State>((set, get) => {
720
815
  clearTimeout(h.timer)
721
816
  holds.delete(key)
722
817
  if (apply && h.last) get().measureNode(...h.last)
723
- if (!holds.size && reflowOwed) { reflowOwed = false; scheduleReflow() }
818
+ if (!holds.size && reflowOwed) { reflowOwed = false; scheduleReflow(null) }
819
+ else reflowSettled()
724
820
  }
725
821
  const dropHolds = () => { for (const h of holds.values()) clearTimeout(h.timer); holds.clear(); reflowOwed = false }
726
822
  /** A content measure moved the rows: once, after the last held node lets go. */
727
- const reflowAfterHolds = () => { if (holds.size) reflowOwed = true; else scheduleReflow() }
823
+ const reflowAfterHolds = () => { reflowReasons.add('measured'); if (holds.size) reflowOwed = true; else scheduleReflow('measured') }
824
+ /** The recorder hears when nothing of the reflow story is left (spec 28 A1.7): no timer, no held height, none owed. */
825
+ reflowIdleNow = () => reflowTimer === undefined && !holds.size && !reflowOwed
826
+ const reflowSettled = () => { if (reflowIdleNow()) recorderHooks.reflowIdle() }
728
827
 
729
828
  // Marks (spec 26): a node that shows an older revision than its frame's `doc` has missed an update
730
829
  // (an event lost while disconnected, an edit that landed while it loaded): it goes stale. The
@@ -762,7 +861,7 @@ export const useStore = create<State>((set, get) => {
762
861
 
763
862
  /** A note may have landed with no room (a frame note via the manifest, a scene note via
764
863
  * sh:scenes, either merged late by boot/switch): a composed board re-applies its layout. */
765
- const roomForNotes = () => { if (composed(get()) && cramped()) scheduleReflow(cramped) }
864
+ const roomForNotes = () => { if (composed(get()) && cramped()) scheduleReflow('cramped', cramped) }
766
865
  /** A composed board's saved positions were laid out around the heights of the session that saved
767
866
  * them. A committed height that changed since (the doc grew or shrank while another board was
768
867
  * open) opens at its new size over - or far above - the row below, and no measurement will re-flow
@@ -787,7 +886,7 @@ export const useStore = create<State>((set, get) => {
787
886
  }
788
887
  const recheckLayout = () => {
789
888
  const s = get()
790
- if (composed(s) && s.nodes.some((n) => n.sizeMode === 'auto' && hasKnownHeight(n.frame, Math.round(n.w)))) scheduleReflow(layoutStale)
889
+ if (composed(s) && s.nodes.some((n) => n.sizeMode === 'auto' && hasKnownHeight(n.frame, Math.round(n.w)))) scheduleReflow('stale', layoutStale)
791
890
  }
792
891
 
793
892
  /** Theme resolution ladder: user pin > the frame's declared meta.theme > viewTheme. */
@@ -831,22 +930,23 @@ export const useStore = create<State>((set, get) => {
831
930
  },
832
931
  }
833
932
 
834
- /** Fetch + normalize a board into ready-to-commit state, WITHOUT touching the store.
933
+ /** Fetch + normalize a board into ready-to-commit state, WITHOUT touching the store - nor the sizes the
934
+ * mounted board reads: those it read come back with it, for the commit to install (installSizes).
835
935
  * null = failure (transport, malformed manifest, non-404 board error) - the caller
836
936
  * keeps whatever board is currently mounted. */
837
- const loadBoardState = async (boardName: string): Promise<Partial<State> | null> => {
937
+ const loadBoardState = async (boardName: string): Promise<{ state: Partial<State>; sizes: SizeRead | null } | null> => {
838
938
  clearNoteHeights() // heights are per column drawn; a key shared by two board files carries none across
839
939
  loadErrors.delete(boardName)
840
940
  try {
841
941
  let raw: any
842
- const saved = loadSavedHeights() // in parallel with the manifest; every size below reads it
942
+ const saved = readSizes() // in parallel with the manifest; every size below reads it
843
943
  if (DATA) raw = DATA.manifest
844
944
  else {
845
- const mRes = await fetch('/design/manifest.json')
945
+ const mRes = await mvFetch('/design/manifest.json')
846
946
  if (!mRes.ok) return null
847
947
  raw = await mRes.json().catch(() => undefined)
848
948
  }
849
- await saved
949
+ const sizes = await saved
850
950
  if (raw === undefined || raw === null || typeof raw !== 'object') return null
851
951
  bumpManifestRev() // fresh manifest → fresh iframe URLs
852
952
  const manifest: Manifest = {
@@ -875,7 +975,7 @@ export const useStore = create<State>((set, get) => {
875
975
  const scenes = [...new Set(manifest.frames.filter((f) => m?.unplaced.includes(f.id)).map((f) => f.scene))]
876
976
  loaded = m ? { board: { nodes: m.unplaced.map((frame) => ({ frame })), ...(scenes.length ? { layout: { rows: [scenes] } } : {}) }, sha256: '' } : null
877
977
  } else {
878
- const res = await fetch(`${ROUTE}/api/boards/${boardName}`)
978
+ const res = await api(`boards/${boardName}`)
879
979
  if (res.ok) {
880
980
  const body = await res.json()
881
981
  loaded = body?.board == null ? 'fresh' : body // board:null = not materialized yet
@@ -884,6 +984,9 @@ export const useStore = create<State>((set, get) => {
884
984
  else { loadErrors.set(boardName, (await res.json().catch(() => null))?.error ?? ''); loaded = null } // anything else must not commit an empty canvas - and says why (#6)
885
985
  }
886
986
  if (loaded === null) return null
987
+ // from here to the return nothing is awaited: the sizes this load read are the ones its nodes are made from,
988
+ // and no other code runs meanwhile to read them in place of the mounted board's
989
+ preparing = sizes
887
990
  if (loaded !== 'fresh') {
888
991
  const { board, sha256 } = loaded
889
992
  boardHash = sha256
@@ -1030,26 +1133,34 @@ export const useStore = create<State>((set, get) => {
1030
1133
  if (layout && boardHash && !needTidy && !cramped && nodes.length) {
1031
1134
  tidy(tidyInput(nodes, manifest), layout, layoutWarn, knownScenes(manifest))
1032
1135
  }
1033
- return { manifest, nodes, boardHash, boardAuto, deviceView, sceneRows, layout, layoutRaw, baseLayout, laidOut, baseLaidOut, selection: [], dirty: prunedAtLoad || cramped }
1034
- } catch { return null }
1136
+ return { state: { manifest, nodes, boardHash, boardAuto, deviceView, sceneRows, layout, layoutRaw, baseLayout, laidOut, baseLaidOut, selection: [], dirty: prunedAtLoad || cramped }, sizes }
1137
+ } catch { return null } finally { preparing = null }
1035
1138
  }
1036
1139
 
1037
1140
  return {
1038
- manifest: null, nodes: [], selection: [], interact: null, viewTheme: initialViewTheme(), play: null, gesture: false, resized: null, laser: false,
1141
+ manifest: null, nodes: [], selection: [], interact: null, viewTheme: initialViewTheme(), play: null, gesture: false, resized: null, laser: false, laserInspect: false,
1039
1142
  board: DATA?.default ?? UNPLACED, boardAuto: false, deviceView: null, sceneRows: null, layout: null, layoutRaw: undefined, baseLayout: null, laidOut: null, baseLaidOut: null,
1040
1143
  panelOpen: true, scale: 1, toasts: [], working: [], workingSince: {}, workingBoards: [], workingSeq: -1, boardHash: null, dirty: false, boardTitles: DATA?.titles ?? {}, boardMeta: DATA?.meta ?? {},
1041
1144
  externalLeases: {}, playUpdateRevision: null, stageShown: null, playNav: 0, pathPulse: 0, imagePulse: 0, imageBusy: false,
1042
1145
 
1043
1146
  async boot(mayCommit) {
1044
1147
  const seq = ++loadSeq
1148
+ recorderHooks.cut(bootRequest, 'superseded')
1045
1149
  const boardName = get().board
1150
+ // the recorder's request (spec 28 A1.7): the page's first load, else the open board read from disk again
1151
+ const request = bootRequest = recorderHooks.request(boardName, firstLoad ? 'boot' : 'disk-reload')
1152
+ firstLoad = false
1046
1153
  const revAtStart = editRev, scenesAtStart = scenesRev
1047
- const next = await loadBoardState(boardName)
1048
- if (seq !== loadSeq) return false // a newer load superseded this one
1049
- if (!next) { get().toast(`board "${boardName}" failed to load${whyNot(boardName)}`); return false }
1154
+ const loaded = await loadBoardState(boardName)
1155
+ if (seq !== loadSeq) { recorderHooks.cut(request, 'superseded'); return false } // a newer load superseded this one
1156
+ if (!loaded) { recorderHooks.cut(request, 'error'); get().toast(`board "${boardName}" failed to load${whyNot(boardName)}`); return false }
1050
1157
  // the user kept editing while we fetched - their newer state wins over the reload
1051
- if (get().board !== boardName || editRev !== revAtStart || (mayCommit && !mayCommit())) return false
1158
+ if (get().board !== boardName || editRev !== revAtStart || (mayCommit && !mayCommit())) { recorderHooks.cut(request, 'edited'); return false }
1159
+ const next = loaded.state
1052
1160
  const live = get().manifest // a WS manifest update may have landed mid-fetch
1161
+ recorderHooks.handover(request) // the load that was up ends by its own sizes
1162
+ installSizes(loaded.sizes) // the sizes this load read are the page's from its commit
1163
+ recorderHooks.commit(request, next.nodes as Node[], next.manifest as Manifest) // before the set: mounting is not a move
1053
1164
  set(next)
1054
1165
  cancelReflow(); dropHolds(); reloadCause.clear()
1055
1166
  if (next.dirty) scheduleSave() // load-time prune must reach the disk
@@ -1062,31 +1173,41 @@ export const useStore = create<State>((set, get) => {
1062
1173
 
1063
1174
  async switchBoard(name) {
1064
1175
  const mySwitch = ++switchSeq // also cancels any pending switch (incl. re-clicking the current board)
1176
+ switchCalls++
1177
+ recorderHooks.cut(switchRequest, 'superseded')
1065
1178
  const scenesAtStart = scenesRev
1066
1179
  if (name === get().board) return
1180
+ // the recorder's request (spec 28 A1.7): the wait starts here, the flush included; the board still mounted
1181
+ // owns the geometry until this one commits
1182
+ const request = switchRequest = recorderHooks.request(name, 'switch')
1067
1183
  // a resize held across a switch: settle THIS board (retidy if it has a recipe)
1068
1184
  // before the flush, so the torn mid-gesture state is never what reaches disk
1069
1185
  if (resizedInGesture) {
1070
1186
  resizedInGesture = false
1071
- if (get().layout || get().sceneRows?.length) get().runTidy()
1187
+ if (get().layout || get().sceneRows?.length) withCause('resize', () => get().runTidy())
1072
1188
  }
1073
1189
  // flush loop: an edit landing mid-save keeps dirty set and gets its own pass
1074
1190
  let ok = true
1075
1191
  for (let i = 0; i < 5 && get().dirty && ok; i++) { clearTimeout(saveTimer); ok = await get().save() }
1076
- if (mySwitch !== switchSeq) return
1077
- if (get().dirty) { get().toast('current board could not be saved - staying here'); return }
1192
+ if (mySwitch !== switchSeq) return recorderHooks.cut(request, 'superseded')
1193
+ if (get().dirty) { recorderHooks.cut(request, 'unsaved'); get().toast('current board could not be saved - staying here'); return }
1078
1194
  // load the target while the current board stays mounted; commit atomically on success -
1079
1195
  // there is never an empty intermediate state and nothing to roll back
1080
- const next = await loadBoardState(name)
1081
- if (mySwitch !== switchSeq) return
1082
- if (!next) { get().toast(`could not load "${name}"${whyNot(name)} - staying on ${get().board}`); return }
1196
+ const loaded = await loadBoardState(name)
1197
+ if (mySwitch !== switchSeq) return recorderHooks.cut(request, 'superseded')
1198
+ if (!loaded) { recorderHooks.cut(request, 'error'); get().toast(`could not load "${name}"${whyNot(name)} - staying on ${get().board}`); return }
1199
+ const next = loaded.state
1083
1200
  // edits may have landed on the still-mounted old board during the target load
1084
1201
  for (let i = 0; i < 5 && get().dirty && ok; i++) { clearTimeout(saveTimer); ok = await get().save() }
1085
- if (mySwitch !== switchSeq) return
1086
- if (get().dirty) { get().toast('current board could not be saved - staying here'); return }
1202
+ if (mySwitch !== switchSeq) return recorderHooks.cut(request, 'superseded')
1203
+ if (get().dirty) { recorderHooks.cut(request, 'unsaved'); get().toast('current board could not be saved - staying here'); return }
1087
1204
  clearTimeout(saveTimer) // a scheduled-but-clean timer must not fire against the new board
1088
1205
  ++loadSeq // invalidate any in-flight boot of the old board
1206
+ recorderHooks.cut(bootRequest, 'superseded')
1089
1207
  const live = get().manifest // a WS manifest update may have landed mid-load
1208
+ recorderHooks.handover(request) // the load that was up ends by its own sizes
1209
+ installSizes(loaded.sizes) // the sizes this load read are the page's from its commit
1210
+ recorderHooks.commit(request, next.nodes as Node[], next.manifest as Manifest) // before the set: mounting is not a move
1090
1211
  set({ board: name, interact: null, ...next })
1091
1212
  cancelReflow(); dropHolds(); reloadCause.clear()
1092
1213
  if (next.dirty) scheduleSave() // load-time prune must reach the disk
@@ -1315,13 +1436,14 @@ export const useStore = create<State>((set, get) => {
1315
1436
  toast(dropped === 1 ? 'removed 1 deleted frame' : `removed ${dropped} deleted frames`)
1316
1437
  }
1317
1438
  }
1318
- set((s) => ({
1439
+ // a guessed size corrected above (in place) is a move, seen when this set notifies the recorder
1440
+ withCause('manifest', () => set((s) => ({
1319
1441
  manifest: m,
1320
1442
  nodes: changed || retinted ? [...final] : final,
1321
1443
  selection: s.selection.filter((k) => final.some((n) => n.key === k)),
1322
1444
  interact: s.interact && final.some((n) => n.key === s.interact) ? s.interact : null,
1323
1445
  ...(changed ? { dirty: true, baseLayout: nextBase } : {}),
1324
- }))
1446
+ })))
1325
1447
  if (changed) scheduleSave()
1326
1448
  roomForNotes() // a frame note file arrived: room in front of its frame
1327
1449
  },
@@ -1340,15 +1462,15 @@ export const useStore = create<State>((set, get) => {
1340
1462
  frameFor(node) { return get().manifest?.frames.find((f) => f.id === node.frame) },
1341
1463
 
1342
1464
  moveNode(key, x, y) {
1343
- set((s) => ({ nodes: s.nodes.map((n) => (n.key === key ? { ...n, x, y } : n)), dirty: true }))
1465
+ withCause('drag', () => set((s) => ({ nodes: s.nodes.map((n) => (n.key === key ? { ...n, x, y } : n)), dirty: true })))
1344
1466
  scheduleSave()
1345
1467
  },
1346
1468
  // group drag: every selected node moves by the same delta from its gesture-start position
1347
1469
  moveSelectedBy(dx, dy, starts) {
1348
- set((s) => ({
1470
+ withCause('drag', () => set((s) => ({
1349
1471
  nodes: s.nodes.map((n) => (starts[n.key] ? { ...n, x: starts[n.key].x + dx, y: starts[n.key].y + dy } : n)),
1350
1472
  dirty: true,
1351
- }))
1473
+ })))
1352
1474
  scheduleSave()
1353
1475
  },
1354
1476
  // scoped theme = an explicit per-frame PIN; it survives board reloads and yields
@@ -1365,7 +1487,7 @@ export const useStore = create<State>((set, get) => {
1365
1487
  const inGesture = get().gesture
1366
1488
  // a manual resize means the board no longer uniformly shows one device; the resized
1367
1489
  // frame's snapshot entry follows the user's new size so Default will not undo it
1368
- set((s) => {
1490
+ withCause('resize', () => set((s) => {
1369
1491
  const W = Math.max(120, w), H = Math.max(80, h)
1370
1492
  const cur = s.nodes.find((n) => n.key === key)
1371
1493
  // a human-resized CONTENT frame goes 'manual': measurements never overwrite it
@@ -1379,7 +1501,7 @@ export const useStore = create<State>((set, get) => {
1379
1501
  ? { ...s.baseLayout, [key]: { ...(s.baseLayout[key] ?? { x: cur.x, y: cur.y }), w: W, h: H } }
1380
1502
  : s.baseLayout,
1381
1503
  }
1382
- })
1504
+ }))
1383
1505
  // mid-gesture saves would persist torn state (new sizes, pre-recipe positions);
1384
1506
  // the gesture-end hook saves once, after any retidy
1385
1507
  if (!inGesture) scheduleSave()
@@ -1396,22 +1518,23 @@ export const useStore = create<State>((set, get) => {
1396
1518
  // auto-fit height: a content frame must always grow/shrink to show ALL its content, even after
1397
1519
  // the human drags its WIDTH. 'manual' just means the human owns the WIDTH; the
1398
1520
  // HEIGHT is still measured, so resizing width reflows and refits height (no clipped/empty frame).
1399
- if (!node || node.sizeMode === 'device') return
1400
- if (node.frame !== frameId) return // generation guard: a reused node key
1521
+ if (!node || node.sizeMode === 'device') return IGNORED
1522
+ if (node.frame !== frameId) return IGNORED // generation guard: a reused node key
1401
1523
  // across a board switch never mis-attributes
1402
1524
  const f = s.manifest?.frames.find((x) => x.id === node.frame)
1403
- if (!f?.contentWidth) return // not a content frame - spoof-proofing
1404
- if (![ownWidth, measuredWidth, height].every((v) => Number.isFinite(v) && v > 0)) return
1525
+ if (!f?.contentWidth) return IGNORED // not a content frame - spoof-proofing
1526
+ if (![ownWidth, measuredWidth, height].every((v) => Number.isFinite(v) && v > 0)) return IGNORED
1405
1527
  // a Doc that reports IS one, whatever the last load's scan said (it arrived since): its heights
1406
1528
  // count until the next load re-reads the sources
1407
1529
  measuring?.add(f.id)
1408
1530
  // held while it reloads (spec 26): only a settled measure lands now; the last other one waits
1409
1531
  const held = holds.get(key)
1410
1532
  if (held) {
1411
- if (settled !== true) { held.last = [key, frameId, ownWidth, measuredWidth, height, settled]; return }
1533
+ if (settled !== true) { held.last = [key, frameId, ownWidth, measuredWidth, height, settled]; return { took: 'held' } }
1412
1534
  holds.delete(key); clearTimeout(held.timer)
1413
1535
  logReload({ kind: 'settled', node: key, frame: frameId, ms: performance.now() - held.at })
1414
- if (!holds.size && reflowOwed) { reflowOwed = false; scheduleReflow() }
1536
+ if (!holds.size && reflowOwed) { reflowOwed = false; scheduleReflow(null) }
1537
+ else reflowSettled()
1415
1538
  }
1416
1539
  // Generous cap: a reference doc with many screenshots is legitimately very tall and must fit in
1417
1540
  // FULL (this was 2.5x a viewport ~= 2700px, which clipped image-heavy docs). Still bounded so a
@@ -1424,7 +1547,7 @@ export const useStore = create<State>((set, get) => {
1424
1547
  // shrink it under a height already known for this width: that one is what the finished doc
1425
1548
  // measures, and shrinking now would only grow back when the image lands - the swim again
1426
1549
  const known = measuredHeights.get(mKey) ?? savedHeights.get(mKey)
1427
- if (settled === false && known !== undefined && H < known) return
1550
+ if (settled === false && known !== undefined && H < known) return IGNORED
1428
1551
  measuredHeights.set(mKey, H)
1429
1552
  // AUTO owns the width too - adopt the Doc's declared/own width. MANUAL keeps the human's width
1430
1553
  // and only fits the height.
@@ -1435,25 +1558,26 @@ export const useStore = create<State>((set, get) => {
1435
1558
  if (W !== curW) {
1436
1559
  // Doc layout changed (document<->wide): adopt the new own width first; the
1437
1560
  // iframe resizes, remeasures, and the height commits on the next message
1438
- set((st) => ({ nodes: st.nodes.map((n) => (n.key === key ? { ...n, w: W } : n)) }))
1561
+ withCause('measure-width', () => set((st) => ({ nodes: st.nodes.map((n) => (n.key === key ? { ...n, w: W } : n)) })))
1439
1562
  reflowAfterHolds()
1440
- return
1563
+ return { took: 'width', w: W }
1441
1564
  }
1442
1565
  }
1443
- if (Math.round(measuredWidth) !== curW) return // height only true at the width it was measured at
1566
+ if (Math.round(measuredWidth) !== curW) return IGNORED // height only true at the width it was measured at
1444
1567
  // a settled height at the frame's OWN width is the one the next load should open at (sizes.ts);
1445
1568
  // a human-owned width is the board file's business (manual sizes save there)
1446
1569
  if (settled === true && node.sizeMode !== 'manual') persistHeight(mKey, H)
1447
- if (Math.round(node.h) === H) return
1448
- set((st) => ({ nodes: st.nodes.map((n) => (n.key === key ? { ...n, h: H } : n)) }))
1570
+ if (Math.round(node.h) === H) return { took: 'fit', w: curW }
1571
+ withCause('measure-height', () => set((st) => ({ nodes: st.nodes.map((n) => (n.key === key ? { ...n, h: H } : n)) })))
1449
1572
  reflowAfterHolds()
1573
+ return { took: 'fit', w: curW }
1450
1574
  },
1451
1575
  noteMeasured(key, height) {
1452
1576
  // the column's height is its content's - the layout learns it here, and a composed board
1453
1577
  // whose next row now stands under a long note re-applies its recipe (0.19.2)
1454
1578
  if (setNoteHeight(key, height)) roomForNotes()
1455
1579
  },
1456
- setDeviceView(name) {
1580
+ setDeviceView(name) { withCause('device', () => {
1457
1581
  const vp = name ? CONFIG.viewports[name] : null
1458
1582
  if (name && !vp) return
1459
1583
  set((s) => {
@@ -1489,7 +1613,7 @@ export const useStore = create<State>((set, get) => {
1489
1613
  })
1490
1614
  if (name) get().runTidy() // restore must NOT tidy - it would destroy positions
1491
1615
  else { scheduleSave(); roomForNotes(); recheckLayout() } // ...unless a note grew meanwhile, or a Doc changed size, under the restored rows
1492
- },
1616
+ }) },
1493
1617
  bumpRev(key) { set((s) => ({ nodes: s.nodes.map((n) => (n.key === key ? { ...n, rev: (n.rev ?? 0) + 1 } : n)) })) },
1494
1618
  setThemeOn(key, theme) { set((s) => ({ nodes: s.nodes.map((n) => (n.key === key ? { ...n, themeOn: theme } : n)) })) },
1495
1619
  setStatus(key, status, error) {
@@ -1529,7 +1653,7 @@ export const useStore = create<State>((set, get) => {
1529
1653
  },
1530
1654
  // scoped device sizing: only the selected frames change; null restores their defaults.
1531
1655
  // Always followed by a tidy - a preset change must never scramble the layout.
1532
- resizeSelected(name) {
1656
+ resizeSelected(name) { withCause('device', () => {
1533
1657
  const vp = name ? CONFIG.viewports[name] : null
1534
1658
  if (name && !vp) return
1535
1659
  set((s) => {
@@ -1552,7 +1676,7 @@ export const useStore = create<State>((set, get) => {
1552
1676
  return { nodes, dirty: true, deviceView: null, baseLayout }
1553
1677
  })
1554
1678
  get().runTidy()
1555
- },
1679
+ }) },
1556
1680
  selectAll() {
1557
1681
  set((s) => ({ selection: s.nodes.map((n) => n.key) }))
1558
1682
  },
@@ -1573,12 +1697,18 @@ export const useStore = create<State>((set, get) => {
1573
1697
  get().flushFrameUpdates() // A6: the frame just left interact is no longer leased
1574
1698
  },
1575
1699
  setPlay(play) { set({ play }) },
1576
- setLaser(laser) {
1577
- if (laser) { set({ laser }); return }
1700
+ toggleLaser(inspect) {
1701
+ const s = get()
1702
+ if (s.laser && s.laserInspect === inspect) s.setLaser(false)
1703
+ else s.setLaser(true, inspect)
1704
+ },
1705
+ setLaser(laser, inspect = false) {
1706
+ if (laser) { set({ laser, laserInspect: inspect }); return }
1578
1707
  // leaving laser mode drops every laser engagement lease (the bridge stops reporting), but
1579
1708
  // keeps comment engagement; the freed frames may now flush a deferred update
1580
1709
  set((s) => ({
1581
1710
  laser,
1711
+ laserInspect: false,
1582
1712
  externalLeases: Object.fromEntries(
1583
1713
  Object.entries(s.externalLeases).filter(([, v]) => v.comment).map(([k]) => [k, { comment: true as const }])),
1584
1714
  }))
@@ -1590,7 +1720,7 @@ export const useStore = create<State>((set, get) => {
1590
1720
  // gesture ends - sizes changed, so lanes and gaps must recompute
1591
1721
  if (!gesture && resizedInGesture) {
1592
1722
  resizedInGesture = false
1593
- if (get().layout || get().sceneRows?.length) get().runTidy() // schedules the save
1723
+ if (get().layout || get().sceneRows?.length) withCause('resize', () => get().runTidy()) // schedules the save
1594
1724
  else scheduleSave()
1595
1725
  }
1596
1726
  if (!gesture) get().flushFrameUpdates() // A6: gesture end is a safe point for deferred updates
@@ -1677,7 +1807,7 @@ export const useStore = create<State>((set, get) => {
1677
1807
  const ctl = new AbortController()
1678
1808
  const timer = setTimeout(() => ctl.abort(), 60_000)
1679
1809
  let meta: { scale?: number; note?: string } = {}
1680
- const png = fetch(`${ROUTE}/api/shot?${qs}`, { headers: { 'x-mv-c': csrf() }, signal: ctl.signal }).then(async (r) => {
1810
+ const png = api(`shot?${qs}`, { headers: { 'x-mv-c': csrf() }, signal: ctl.signal }).then(async (r) => {
1681
1811
  if (!r.ok) throw new Error((await r.json().catch(() => ({}))).error ?? `shot failed (${r.status})`)
1682
1812
  try { meta = JSON.parse(atob((r.headers.get('x-mv-shot') ?? '').replace(/-/g, '+').replace(/_/g, '/'))) } catch { /* summary is advisory */ }
1683
1813
  return r.blob()
@@ -1706,7 +1836,7 @@ export const useStore = create<State>((set, get) => {
1706
1836
  // global theme = the VIEW preference: persists across boards + reloads, clears
1707
1837
  // per-frame pins. Frames declaring meta.theme keep their mode (they only work there).
1708
1838
  setTheme(theme) {
1709
- try { localStorage.setItem('mv-view-theme', theme) } catch { /* storage unavailable */ }
1839
+ try { localStorage.setItem(scoped('mv-view-theme'), theme) } catch { /* storage unavailable */ }
1710
1840
  set((s) => ({
1711
1841
  viewTheme: theme,
1712
1842
  nodes: s.nodes.map((n) => {
@@ -1720,14 +1850,15 @@ export const useStore = create<State>((set, get) => {
1720
1850
  runTidy() {
1721
1851
  const { nodes, manifest, sceneRows, layout } = get()
1722
1852
  const placed = tidy(tidyInput(nodes, manifest), effectiveLayout(layout, sceneRows), layoutWarn, knownScenes(manifest))
1723
- set((s) => ({
1853
+ // a tidy asked for by hand; one a preset, a resize, a reflow or the unplaced view runs keeps its cause
1854
+ withCause(geoCause ?? 'tidy', () => set((s) => ({
1724
1855
  nodes: s.nodes.map((n) => {
1725
1856
  const p = placed.find((x) => x.key === n.key)
1726
1857
  return p ? { ...n, x: p.x, y: p.y } : n
1727
1858
  }),
1728
1859
  laidOut: sizeRecord(nodes),
1729
1860
  dirty: true,
1730
- }))
1861
+ })))
1731
1862
  scheduleSave()
1732
1863
  },
1733
1864
  toast(text) {
@@ -1797,7 +1928,7 @@ export const useStore = create<State>((set, get) => {
1797
1928
  const seq = ++marksSeq
1798
1929
  try {
1799
1930
  for (let i = 0; i < 2; i++) { // the first ask may prime the CSRF cookie (as syncWorking)
1800
- const r = await fetch(`${ROUTE}/api/marks`, { headers: { 'x-mv-c': csrf() } })
1931
+ const r = await api('marks', { headers: { 'x-mv-c': csrf() } })
1801
1932
  if (seq !== marksSeq) return
1802
1933
  if (r.ok) {
1803
1934
  const m = await r.json() as Marks | null
@@ -1864,7 +1995,7 @@ export const useStore = create<State>((set, get) => {
1864
1995
  // a fresh page may ask before its double-submit cookie exists: the refusal primes it (api.ts),
1865
1996
  // so one more try carries it
1866
1997
  for (let i = 0; i < 2; i++) {
1867
- const r = await fetch(`${ROUTE}/api/work`, { headers: { 'x-mv-c': csrf() } })
1998
+ const r = await api('work', { headers: { 'x-mv-c': csrf() } })
1868
1999
  if (r.ok) return get().setWorkingFrom(await r.json())
1869
2000
  if (r.status !== 403) return
1870
2001
  }
@@ -1886,17 +2017,17 @@ export const useStore = create<State>((set, get) => {
1886
2017
  const vp = deviceView ? CONFIG.viewports[deviceView] : null
1887
2018
  const maxX = nodes.reduce((a, n) => Math.max(a, n.x + n.w), 0)
1888
2019
  const node: Node = { key: nodeKey(), frame: f.id, x: maxX + 96, y: 0, w: vp?.width ?? d.w, h: vp?.height ?? d.h, theme: resolveTheme(f), status: 'loading', ...(f.contentWidth ? { sizeMode: (vp ? 'device' : 'auto') as Node['sizeMode'] } : {}) }
1889
- set((s) => ({
2020
+ withCause('spawn', () => set((s) => ({
1890
2021
  nodes: [...s.nodes, node],
1891
2022
  dirty: true,
1892
2023
  ...(vp && baseLayout ? { baseLayout: { ...baseLayout, [node.key]: { x: node.x, y: node.y, w: d.w, h: d.h } } } : {}),
1893
- }))
2024
+ })))
1894
2025
  scheduleSave()
1895
2026
  get().toast(`added ${f.id}`)
1896
2027
  return node
1897
2028
  },
1898
2029
 
1899
- syncUnplaced(ids) {
2030
+ syncUnplaced(ids) { withCause('unplaced', () => {
1900
2031
  const s = get()
1901
2032
  if (s.board !== UNPLACED || !s.manifest) return
1902
2033
  const want = new Set(ids)
@@ -1914,12 +2045,14 @@ export const useStore = create<State>((set, get) => {
1914
2045
  const scenes = [...new Set(nodes.map((n) => s.manifest!.frames.find((f) => f.id === n.frame)?.scene).filter((x): x is string => !!x))]
1915
2046
  set({ nodes, selection: s.selection.filter((k) => nodes.some((n) => n.key === k)), layout: scenes.length ? { rows: [scenes] } : null })
1916
2047
  get().runTidy() // one band of its scenes again; the view is never saved
1917
- },
2048
+ }) },
1918
2049
 
1919
2050
  save() {
1920
2051
  // a rename is moving this board's file - defer every save so nothing writes to the OLD
1921
2052
  // name mid-move (renameBoard reschedules once the move commits under the new name)
1922
2053
  if (saveHolds > 0) return Promise.resolve(false)
2054
+ // the canvas stopped (A1.11): the edits stay here, dirty, until it answers on this address again
2055
+ if (canvasStopped()) return Promise.resolve(false)
1923
2056
  // a resize gesture in flight = torn state (new sizes, pre-recipe positions):
1924
2057
  // even a PREVIOUSLY scheduled timer must defer to the gesture-end save
1925
2058
  if (get().gesture && resizedInGesture) { scheduleSave(); return Promise.resolve(false) }
@@ -1972,7 +2105,9 @@ export const useStore = create<State>((set, get) => {
1972
2105
  })),
1973
2106
  }
1974
2107
  try {
1975
- const res = await fetch(`${ROUTE}/api/boards/${boardName}`, {
2108
+ // a refusal by another canvas comes back as the helper's 503 and takes the `return false` below,
2109
+ // never the 409 branch (disk wins)
2110
+ const res = await api(`boards/${boardName}`, {
1976
2111
  method: 'PUT', headers: { 'content-type': 'application/json' },
1977
2112
  // A9: a board loaded from disk (boardHash set) autosaves with mustExist so a
1978
2113
  // rename/delete out from under us returns 409 instead of resurrecting a ghost.
@@ -1984,17 +2119,19 @@ export const useStore = create<State>((set, get) => {
1984
2119
  if (info?.gone) {
1985
2120
  // renamed/deleted externally - drop the write, don't recreate it or loop
1986
2121
  set({ dirty: false })
1987
- get().toast('this board was renamed or removed - not recreating it')
2122
+ get().toast(BOARD_GONE)
2123
+ lostInResume('gone') // a resume's save: the page after its reload says this, not "saved"
1988
2124
  return true
1989
2125
  }
1990
2126
  const reloaded = await get().boot() // hash advances only when the authoritative reload commits
1991
- if (reloaded) get().toast('board changed on disk - canvas layout reloaded')
2127
+ if (reloaded) { get().toast(DISK_WON); lostInResume('disk') }
1992
2128
  return reloaded // false keeps dirty set; the next debounce retries once edits settle
1993
2129
  }
1994
2130
  if (res.ok) {
1995
2131
  const { sha256 } = await res.json()
1996
2132
  // an edit that landed after this save started keeps dirty set for the next save
1997
2133
  set({ boardHash: sha256, ...(editRev === rev ? { dirty: false } : {}) })
2134
+ savedInResume() // a resume's save: the page after its reload says the edits were saved
1998
2135
  return true
1999
2136
  }
2000
2137
  return false
@@ -2014,5 +2151,33 @@ useStore.subscribe((s, prev) => {
2014
2151
  if (!s.play && prev.play) { useStore.setState({ stageShown: null, playUpdateRevision: null }); pumpUpdates() }
2015
2152
  })
2016
2153
 
2154
+ // spec 28 A1.11: the canvas answered again on this address - what this page holds is saved before it reloads
2155
+ // (never mid-drag: a frame held by the pointer is asked about again a second later)
2156
+ beforeResume(async () => {
2157
+ const s = () => useStore.getState()
2158
+ if (s().gesture) return false
2159
+ for (let i = 0; i < 5 && s().dirty; i++) if (!(await s().save())) break
2160
+ await flushHeights()
2161
+ return !s().dirty && !s().gesture
2162
+ })
2163
+ // and an edit made, or a drag begun, while that save was on its way holds the reload as well
2164
+ holdsReload(() => { const s = useStore.getState(); return s.dirty || !!s.gesture })
2165
+ // while stopped, the banner says "your unsaved edits are kept" from the edit that makes some
2166
+ useStore.subscribe((s, p) => { if ((s.dirty !== p.dirty || s.gesture !== p.gesture) && canvasStopped()) noteUnsaved() })
2167
+ onLinkNotice((text) => useStore.getState().toast(text))
2168
+ /** A tool that needs the server, asked for while the canvas is stopped (A1.11): it says why and the way back, and
2169
+ * does nothing. `what`: "Comments need the canvas running". */
2170
+ export function stoppedFor(what: string): boolean {
2171
+ if (!canvasStopped()) return false
2172
+ useStore.getState().toast(`${what} - ${STOPPED_WAY}`)
2173
+ return true
2174
+ }
2175
+ // a stopped page holds edits only it has: leaving it (a reload by hand, a close) asks first
2176
+ if (typeof window !== 'undefined') window.addEventListener('beforeunload', (e) => {
2177
+ if (!canvasStopped() || !useStore.getState().dirty) return
2178
+ e.preventDefault()
2179
+ e.returnValue = ''
2180
+ })
2181
+
2017
2182
  // dev-only inspection hook for tests/debugging (never installed in published builds)
2018
2183
  if (import.meta.env.DEV) (window as unknown as { __mvStore: unknown }).__mvStore = useStore