@marver-design/marver 0.26.1 → 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 (82) hide show
  1. package/CHANGELOG.md +104 -0
  2. package/README.md +8 -3
  3. package/dist/{anchor-check-l-ny3UzH.mjs → anchor-check-ChdDqL5z.mjs} +1 -1
  4. package/dist/{bake-C-awKgLA.mjs → bake-DM_uWgAA.mjs} +1 -1
  5. package/dist/{boards-DYG22tOe.mjs → boards-DlTcpF47.mjs} +1 -1
  6. package/dist/{build-BDRiO_mP.mjs → build-DZnFysGU.mjs} +4 -4
  7. package/dist/cli.mjs +28 -16
  8. package/dist/{comments-BqXua-XL.mjs → comments-DxOkCSNE.mjs} +4 -4
  9. package/dist/{daemon-DL6Fwq6D.mjs → daemon-BSA0lV8d.mjs} +8 -6
  10. package/dist/detect-C0wpaePX.mjs +125 -0
  11. package/dist/dev-eQJhWsqg.mjs +1273 -0
  12. package/dist/dev-lock-C_FC70Mu.mjs +65 -0
  13. package/dist/exclusive-B1RtpeeP.mjs +150 -0
  14. package/dist/{init-D8DtrK_F.mjs → init-COD0x48i.mjs} +5 -3
  15. package/dist/{link-BNzLvdhI.mjs → link-DDXZVGtv.mjs} +20 -8
  16. package/dist/ls-D7O1G505.mjs +38 -0
  17. package/dist/{marks-DyWMv_Z1.mjs → marks-CWM3WJjc.mjs} +1 -1
  18. package/dist/perf-BWzQwZqj.mjs +369 -0
  19. package/dist/perf-BoDSkbEb.mjs +429 -0
  20. package/dist/{perf-jam-BU3TVrZu.mjs → perf-jam-D55U3FZK.mjs} +5 -2
  21. package/dist/{plugin-DkGmZs_r.mjs → plugin-C-E7omsh.mjs} +394 -55
  22. package/dist/{poster-BdtSKMDm.mjs → poster-Bx83ZYVK.mjs} +1 -1
  23. package/dist/{profile-WU9qcbIo.mjs → profile-Bh5Y5zpW.mjs} +1 -1
  24. package/dist/{publish-bakes-9RzRToXV.mjs → publish-bakes-aljgm45S.mjs} +2 -2
  25. package/dist/{queue-29ok5_eZ.mjs → queue-CAM_vNmX.mjs} +1 -1
  26. package/dist/recover-t9Pno3u9.mjs +66 -0
  27. package/dist/{share--oFJ1bCI.mjs → share-W5H3BNvP.mjs} +1 -1
  28. package/dist/{shot-XQV7HC9A.mjs → shot-DoHLl6ig.mjs} +1 -1
  29. package/dist/{shot-DQeR_Pfn.mjs → shot-LFhC-WYD.mjs} +9 -3
  30. package/dist/slots-DCDo3N0x.mjs +471 -0
  31. package/dist/{sync-DKk-yT1V.mjs → sync-BQVlHZpx.mjs} +4 -3
  32. package/dist/{work-F5u-twpJ.mjs → work-Bp1p39kq.mjs} +4 -2
  33. package/dist/{work-VvX_JIgl.mjs → work-BroFwnup.mjs} +4 -2
  34. package/docs/boards-and-folders.md +3 -1
  35. package/docs/jam-session.md +55 -1
  36. package/docs/performance.md +262 -0
  37. package/package.json +2 -2
  38. package/src/client/content/index.tsx +3 -0
  39. package/src/client/content/video.tsx +6 -2
  40. package/src/client/frame-host/bridge.js +22 -6
  41. package/src/client/frame-host/main.tsx +17 -5
  42. package/src/client/shell/App.tsx +180 -25
  43. package/src/client/shell/BoardList.tsx +5 -5
  44. package/src/client/shell/Comments.tsx +3 -2
  45. package/src/client/shell/JamSurface.tsx +4 -2
  46. package/src/client/shell/LockedApp.tsx +5 -5
  47. package/src/client/shell/Play.tsx +16 -8
  48. package/src/client/shell/Toolbar.tsx +12 -1
  49. package/src/client/shell/api.ts +206 -0
  50. package/src/client/shell/canvas/Canvas.tsx +30 -3
  51. package/src/client/shell/canvas/FrameNode.tsx +12 -3
  52. package/src/client/shell/canvas/admission.ts +8 -1
  53. package/src/client/shell/canvas/camera-broadcast.ts +15 -5
  54. package/src/client/shell/canvas/ctl.ts +2 -0
  55. package/src/client/shell/canvas/frame-registry.ts +28 -2
  56. package/src/client/shell/canvas/sleep.ts +4 -1
  57. package/src/client/shell/comments-store.ts +12 -4
  58. package/src/client/shell/goto.ts +22 -10
  59. package/src/client/shell/jam-capture.ts +22 -8
  60. package/src/client/shell/jam-keys.ts +4 -0
  61. package/src/client/shell/jam-panel.tsx +3 -0
  62. package/src/client/shell/jam-queue.ts +3 -3
  63. package/src/client/shell/jam-session.tsx +14 -8
  64. package/src/client/shell/jam-voice.ts +7 -5
  65. package/src/client/shell/legacy-links.ts +2 -2
  66. package/src/client/shell/main.tsx +4 -0
  67. package/src/client/shell/notes.ts +8 -1
  68. package/src/client/shell/perf.ts +69 -58
  69. package/src/client/shell/recorder-core.ts +183 -0
  70. package/src/client/shell/recorder.ts +565 -0
  71. package/src/client/shell/store.ts +254 -98
  72. package/src/client/shell/styles.css +26 -1
  73. package/templates/AGENTS-embedded.md +22 -4
  74. package/templates/AGENTS-studio.md +22 -4
  75. package/templates/demo/dark.tsx +1 -1
  76. package/templates/demo/welcome.tsx +1 -1
  77. package/templates/instructions/welcome.md +6 -3
  78. package/dist/config-Cf7EjAMf.mjs +0 -292
  79. package/dist/dev-Bw_qYWWq.mjs +0 -755
  80. package/dist/dev-lock-DWSpa6nj.mjs +0 -179
  81. package/dist/perf-C75MZ73h.mjs +0 -167
  82. package/dist/perf-DPbLGhhO.mjs +0 -49
@@ -0,0 +1,206 @@
1
+ /**
2
+ * Every request this page makes to its dev server names the canvas it belongs to (spec 28 A1.11), so a
3
+ * page left open after its canvas stopped can never write into another project that took its port. The
4
+ * server refuses a request naming another workspace before reading anything (server/guard.ts); this
5
+ * side keeps what the page holds, says the canvas stopped, and sends nothing more until its own canvas
6
+ * answers on this address again - then it saves and reloads. A published canvas has no workspace to
7
+ * name: its requests go out as before.
8
+ */
9
+ import { create } from 'zustand'
10
+ import { ROUTE } from '../const.ts'
11
+ // @ts-expect-error virtual module provided by the plugin
12
+ import shConfig from 'virtual:sh-config'
13
+ // @ts-expect-error virtual module: null in dev; a published build inlines manifest+boards
14
+ import shData from 'virtual:sh-data'
15
+
16
+ /** This page's workspace in dev; '' on a published canvas (or a harness that names none). */
17
+ export const WS: string = shData === null && typeof shConfig?.workspace === 'string' ? shConfig.workspace : ''
18
+
19
+ /** A per-viewer preference kept per canvas (A1.6): `<key>:<workspace>` in dev, the bare key when published. */
20
+ export const scoped = (key: string) => (WS ? `${key}:${WS}` : key)
21
+ /** A URL a document or an <img> loads, naming the workspace (frames, the stage, Jam pictures). */
22
+ export const withWs = (url: string) => (WS ? `${url}${url.includes('?') ? '&' : '?'}ws=${WS}` : url)
23
+
24
+ /** live; checking (the live socket dropped, the first answer not in); down (nothing, or not this canvas,
25
+ * answers); elsewhere (another canvas answers here); resuming (this canvas answered: saving, then reload). */
26
+ export type Link = 'live' | 'checking' | 'down' | 'elsewhere' | 'resuming'
27
+ /** `shown`: the "This canvas stopped" banner is up. `unsaved`: this tab holds something only it has (an edit not
28
+ * saved, a capture, words not sent) - the banner says so only then. */
29
+ export const useLink = create<{ link: Link; shown: boolean; unsaved: boolean }>(() => ({ link: 'live', shown: false, unsaved: false }))
30
+ export const stoppedLink = (l: Link) => l === 'checking' || l === 'down' || l === 'elsewhere'
31
+ /** Nothing leaves the page: its canvas is gone from here, or not known to be back yet. */
32
+ export const canvasStopped = () => stoppedLink(useLink.getState().link)
33
+ /** canvasStopped(), for a component: the tools that need the server (comments, Jam) go quiet while it holds. */
34
+ export const useStopped = () => useLink((s) => stoppedLink(s.link))
35
+ /** The way back, said by each tool that needs the server while the canvas is stopped: its toast, its tooltip. */
36
+ export const STOPPED_WAY = 'npx marver dev brings it back'
37
+ export const STOPPED_TIP = 'The canvas stopped - run npx marver dev to bring it back'
38
+ /** The answer a stopped page gives itself (or gets from the server, translated): never a 409 a caller reads. */
39
+ export const isStopped = (r: Response) => r.headers.get('x-mv-stopped') === '1'
40
+ const stoppedAnswer = () => new Response('{"error":"this canvas stopped"}', { status: 503, headers: { 'content-type': 'application/json', 'x-mv-stopped': '1' } })
41
+
42
+ /** Any request to this page's dev server. `fetch` is looked up at call time (tests patch window.fetch)
43
+ * and called before any await, so a `keepalive` request made in `pagehide` still goes out. Callers pass
44
+ * plain-object headers; a GET keeps its init without a method. */
45
+ export function mvFetch(url: string, init: RequestInit = {}): Promise<Response> {
46
+ if (WS && canvasStopped()) return Promise.resolve(stoppedAnswer())
47
+ const sent = fetch(url, WS ? { ...init, headers: { ...(init.headers as Record<string, string> | undefined), 'x-mv-ws': WS } } : init)
48
+ if (!WS) return sent
49
+ // the server's refusal is told apart here, before any caller's own 409 (a board conflict, a stale tree)
50
+ return sent.then((r) => {
51
+ if (r.status !== 409 || r.headers.get('x-mv-elsewhere') !== '1') return r
52
+ lost('elsewhere')
53
+ return stoppedAnswer()
54
+ }, (e: unknown) => {
55
+ // the live socket is gone, so nothing else would say so: a request that reaches nothing stops the page
56
+ if (hmrLost && (e as Error)?.name !== 'AbortError') lost('down')
57
+ throw e
58
+ })
59
+ }
60
+ /** A request under /__mv/api/: `api('boards/main', { method: 'PUT', ... })`. */
61
+ export const api = (path: string, init?: RequestInit) => mvFetch(`${ROUTE}/api/${path}`, init)
62
+
63
+ // ---- the link: losing the canvas, and getting it back --------------------------------------------------
64
+
65
+ /** What must be done before a resumed page reloads (the board save, the heights). Each answers true when
66
+ * the page may reload now; asked again each second while a reload is owed, so each is cheap when there is
67
+ * nothing to do. */
68
+ const flushers = new Set<() => Promise<boolean>>()
69
+ export const beforeResume = (fn: () => Promise<boolean>) => { flushers.add(fn); return () => { flushers.delete(fn) } }
70
+ /** What holds a reload while it answers true: an edit not saved, a capture recording, words typed and not
71
+ * sent. Synchronous, and asked right before the reload, after every flusher has finished - so what a person
72
+ * does while the flushers wait on the server holds it as surely as what was there before they began. */
73
+ const holds = new Set<() => boolean>()
74
+ export const holdsReload = (fn: () => boolean) => { holds.add(fn); return () => { holds.delete(fn) } }
75
+ const held = () => [...holds].some((h) => { try { return h() } catch { return true } })
76
+ /** Asks again whether this tab holds anything only it has (the banner's "unsaved edits"): at a stop, once a
77
+ * second while stopped, and whenever an edit or a word changes it. */
78
+ export function noteUnsaved() {
79
+ if (!WS) return
80
+ const u = held()
81
+ if (u !== useLink.getState().unsaved) useLink.setState({ unsaved: u })
82
+ }
83
+ /** Told when a resumed page stays (a flusher said no): the store's toast, registered by store.ts. */
84
+ let say: (text: string) => void = () => {}
85
+ export const onLinkNotice = (fn: (text: string) => void) => { say = fn }
86
+
87
+ let hmrLost = false
88
+ let probeTimer: ReturnType<typeof setTimeout> | null = null
89
+
90
+ function lost(why: 'down' | 'elsewhere') {
91
+ noteUnsaved()
92
+ if (why === 'elsewhere') useLink.setState({ link: 'elsewhere', shown: true })
93
+ else if (!canvasStopped()) useLink.setState({ link: 'checking' })
94
+ probeTimer ??= setTimeout(probe, 0)
95
+ }
96
+
97
+ /** Once a second while stopped, and while a reload is owed: is this canvas (still) on this address? */
98
+ async function probe() {
99
+ let r: Response | null = null
100
+ // a server that takes the connection and never answers (half up, hung, paused) is no answer: a miss
101
+ try { r = await fetch(`${ROUTE}/api/hello`, { headers: { 'x-mv-ws': WS }, cache: 'no-store', signal: AbortSignal.timeout(2000) }) } catch { r = null }
102
+ const ours = !!r?.ok && (await r.json().catch(() => null))?.ws === WS
103
+ probeTimer = null
104
+ if (ours) return void resume()
105
+ // another canvas answers, or nothing does, or something that is not a canvas of this one (an older
106
+ // marver says 404): the banner - and keep asking
107
+ noteUnsaved()
108
+ useLink.setState({ link: r?.status === 409 && r.headers.get('x-mv-elsewhere') === '1' ? 'elsewhere' : 'down', shown: true })
109
+ probeTimer = setTimeout(probe, 1000)
110
+ }
111
+
112
+ async function resume() {
113
+ const back = useLink.getState().link !== 'live' // from a stop; 'live' is a page that owes a reload
114
+ if (back) useLink.setState({ link: 'resuming' }) // requests flow again: the flushers use them
115
+ let ok = true
116
+ flushing = true
117
+ try { for (const fn of flushers) ok = (await fn().catch(() => false)) && ok } finally { flushing = false }
118
+ const now = useLink.getState().link
119
+ if (now !== 'resuming' && now !== 'live') return // lost again while saving: the probe goes on
120
+ // asked here, with nothing awaited between the answer and the reload: words typed or an edit made while a
121
+ // flusher waited on the server hold it too
122
+ if (ok && held()) ok = false
123
+ // a fresh document on the canvas that answered: live updates again - and the next page says what the resumes came to,
124
+ // this one's and those this reload waited after (a draft, a capture), whose toasts go with this page
125
+ if (hmrLost && ok) { keepOverReload(lostOnResume ?? (savedOnResume ? 'saved' : null)); return void location.reload() }
126
+ if (back || useLink.getState().shown) useLink.setState({ link: 'live', shown: false })
127
+ // no reload owed (Vite's socket held): the page goes on as it is, and what this resume came to was said on it
128
+ if (!hmrLost) { lostOnResume = null; savedOnResume = false; return }
129
+ // Vite's socket never comes back (its client waits on the listener below), so this page owes a reload:
130
+ // until nothing holds it (a capture recording, words not sent) it works as live, keeps asking - a stop
131
+ // is seen again - and reloads the moment it may
132
+ if (back) { say('marver dev is back - this page reloads once nothing is in progress'); unstrand() }
133
+ probeTimer ??= setTimeout(probe, 1000)
134
+ }
135
+
136
+ /** Frames another project answered while this canvas was away show its "another canvas" page, which runs no
137
+ * script - no Vite client to bring them back. A page that stays reloads them in place, on its own canvas. */
138
+ function unstrand() {
139
+ for (const f of document.querySelectorAll('iframe')) if (stranded(f)) f.contentWindow?.location.reload()
140
+ }
141
+ /** Does this frame show another project's "another canvas" page (server/guard.ts)? The shell draws its own quiet
142
+ * placeholder over it: the banner says what happened, once. */
143
+ export function stranded(f: HTMLIFrameElement | null): boolean {
144
+ try { return !!f?.contentDocument?.querySelector('meta[name="mv-elsewhere"]') } catch { return false /* not ours to read */ }
145
+ }
146
+
147
+ // ---- over the resume's own reload: where the person was looking, and what its save came to --------------------
148
+
149
+ /** What the resume's save came to, said by the page after its reload: 'saved' - the board edits only this tab held
150
+ * reached the disk; 'disk' - the board's file changed on disk meanwhile and won, the tab's board edits dropped; 'gone' - the board
151
+ * was renamed or removed meanwhile and is not created again; null - there was nothing to save. */
152
+ export type ResumeOutcome = 'saved' | 'disk' | 'gone' | null
153
+ let flushing = false
154
+ /** What the resumes came to - the board save's own word, lost or saved - kept until the reload that carries it: a
155
+ * resume whose reload is held (a draft, a capture) is not the last one, and the one that reloads at last may have
156
+ * nothing left to save. Each later resume only adds to it - the first loss stays, and a loss outranks a save. A resume
157
+ * that owes no reload (Vite's socket held) ends it. */
158
+ let lostOnResume: 'disk' | 'gone' | null = null
159
+ let savedOnResume = false
160
+ /** The board save, while the resume's flushers run: what this tab held did not reach the disk (store.ts) - the page
161
+ * after the reload says what happened instead, never that the edits were saved. */
162
+ export function lostInResume(why: 'disk' | 'gone') { if (flushing) lostOnResume ??= why }
163
+ /** The board save, while the resume's flushers run: what this tab held reached the disk (store.ts). */
164
+ export function savedInResume() { if (flushing) savedOnResume = true }
165
+
166
+ const RESUMED = 'mv-resumed'
167
+ const keepers = new Set<() => Record<string, unknown>>()
168
+ /** What a resumed page carries over its own reload, read back by the next page (the canvas keeps its camera). */
169
+ export const keepOverResume = (fn: () => Record<string, unknown>) => { keepers.add(fn); return () => { keepers.delete(fn) } }
170
+ function keepOverReload(outcome: ResumeOutcome) {
171
+ const rec: Record<string, unknown> = { at: Date.now(), outcome }
172
+ for (const fn of keepers) { try { Object.assign(rec, fn()) } catch { /* the rest still goes */ } }
173
+ try { sessionStorage.setItem(scoped(RESUMED), JSON.stringify(rec)) } catch { /* storage off: the page boots as any other */ }
174
+ }
175
+ const OUTCOMES: readonly ResumeOutcome[] = ['saved', 'disk', 'gone', null]
176
+ /** What the page before this one left when it reloaded itself on its canvas's return - this tab only, read once
177
+ * at load, and only a fresh one (a reload by hand later on boots as any other). `outcome`: what its save came to;
178
+ * the page says so. */
179
+ export const resumed: { outcome: ResumeOutcome; board?: string; camera?: { x: number; y: number; scale: number } } | null = (() => {
180
+ if (!WS) return null
181
+ try {
182
+ const raw = sessionStorage.getItem(scoped(RESUMED))
183
+ if (raw === null) return null
184
+ sessionStorage.removeItem(scoped(RESUMED))
185
+ const r = JSON.parse(raw)
186
+ return r && typeof r.at === 'number' && Date.now() - r.at < 30_000 ? { ...r, outcome: OUTCOMES.includes(r.outcome) ? r.outcome : null } : null
187
+ } catch { return null }
188
+ })()
189
+
190
+ // words a person typed into the page and has not sent (a comment, a Jam edit, a name): a reload would drop them
191
+ const typed = new WeakSet<EventTarget>()
192
+ const TEXT_FIELDS = 'textarea, input:not([type]), input[type=text], input[type=search], input[type=email], input[type=url], input[type=password]'
193
+ if (WS) {
194
+ document.addEventListener('input', (e) => { if (e.target) typed.add(e.target); if (canvasStopped()) noteUnsaved() }, true)
195
+ holdsReload(() => [...document.querySelectorAll<HTMLInputElement | HTMLTextAreaElement>(TEXT_FIELDS)].some((el) => typed.has(el) && el.value.trim() !== ''))
196
+ }
197
+
198
+ // Vite's client awaits every `vite:ws:disconnect` listener before it pings the server and reloads the
199
+ // page (vite/dist/client/client.mjs, Vite 8). This one never settles: the canvas page is never reloaded by
200
+ // Vite - not into another project that took the port, and not into this one's next run before it has
201
+ // saved what it holds - and its socket stays closed, so no other project's broadcast reaches it. It
202
+ // reloads itself in resume(). Frames keep Vite's own reload: their URLs name the workspace.
203
+ if (WS && import.meta.hot) import.meta.hot.on('vite:ws:disconnect', () => { hmrLost = true; lost('down'); return new Promise<never>(() => {}) })
204
+
205
+ // dev-only inspection hook for tests (never installed in published builds)
206
+ if (WS && import.meta.env.DEV) (window as unknown as { __mvLink: unknown }).__mvLink = useLink
@@ -7,7 +7,10 @@ import { revealFrame } from '../goto.ts'
7
7
  import { startPerf } from '../perf.ts'
8
8
  import { FrameNode, HEADER } from './FrameNode.tsx'
9
9
  import { NOTE_GAP } from '../notes.ts'
10
- import { startCameraBroadcast, setCameraScale } from './camera-broadcast.ts'
10
+ import { onMotion, startCameraBroadcast, setCameraScale } from './camera-broadcast.ts'
11
+ import { attachCanvas, recorder } from '../recorder.ts'
12
+ import { sleepingCount } from './sleep.ts'
13
+ import { keepOverResume, resumed } from '../api.ts'
11
14
 
12
15
  /**
13
16
  * The world. rzpp owns pan/zoom; nodes are absolutely positioned children of #sh-world.
@@ -144,7 +147,8 @@ export function Canvas() {
144
147
  const ref = useRef<ReactZoomPanPinchContentRef>(null)
145
148
  const scaleTimer = useRef(0)
146
149
 
147
- useEffect(() => { startPerf(); startCameraBroadcast() }, []) // B0.4: frame-time sampler + image-LOD camera signal
150
+ // B0.4: frame-time sampler + image-LOD camera signal; the recorder hears when the camera stops and what sleeps (spec 28 A1.7)
151
+ useEffect(() => { startPerf(); startCameraBroadcast(); return attachCanvas({ onMotion, sleeping: sleepingCount }) }, [])
148
152
 
149
153
  useEffect(() => {
150
154
  const wrap = () => document.querySelector('.sh-canvas') as HTMLElement | null
@@ -167,7 +171,10 @@ export function Canvas() {
167
171
  px = Math.max(Math.min((vw - w * scale) / 2, vw - p.right - w * scale), p.left)
168
172
  py = Math.max(Math.min((vh - h * scale) / 2, vh - p.bottom - h * scale), p.top)
169
173
  }
170
- ref.current.setTransform(px - x * scale, py - y * scale, scale, 320, 'easeOut')
174
+ const tx = px - x * scale, ty = py - y * scale
175
+ // where this fit lands, in world px: the first one after a board's commit shows its visible cohort (spec 28 A1.7)
176
+ recorder.placed({ x: -tx / scale, y: -ty / scale, w: vw / scale, h: vh / scale })
177
+ ref.current.setTransform(tx, ty, scale, 320, 'easeOut')
171
178
  }
172
179
  const fitKeys = (keys: string[], focus: boolean) => {
173
180
  const st = useStore.getState()
@@ -210,6 +217,17 @@ export function Canvas() {
210
217
  inst.setTransform(cx - (cx - positionX) * k, cy - (cy - positionY) * k, target, 250, 'easeOut')
211
218
  }
212
219
  canvasCtl.cameraBusy = () => !!ref.current?.instance.animation
220
+ // a page that reloads itself when its canvas comes back (spec 28 A1.11) opens where the person was looking
221
+ const unkeep = keepOverResume(() => {
222
+ const t = ref.current?.instance.transformState
223
+ return t ? { board: useStore.getState().board, camera: { x: t.positionX, y: t.positionY, scale: t.scale } } : {}
224
+ })
225
+ canvasCtl.view = () => {
226
+ const el = wrap(), inst = ref.current
227
+ if (!el || !inst) return null
228
+ const { positionX, positionY, scale } = inst.instance.transformState
229
+ return { x: -positionX / scale, y: -positionY / scale, w: el.clientWidth / scale, h: el.clientHeight / scale }
230
+ }
213
231
  canvasCtl.holdView = () => {
214
232
  heldView = null
215
233
  const el = wrap(), inst = ref.current
@@ -222,6 +240,7 @@ export function Canvas() {
222
240
  // the reflow commits before the next frame; an anchor nothing consumed must never steer a later change
223
241
  requestAnimationFrame(() => { if (heldView === held) heldView = null })
224
242
  }
243
+ return unkeep
225
244
  }, [])
226
245
 
227
246
  // first load opens on the whole board (same as ⇧1) - the default 100% transform is an
@@ -233,12 +252,20 @@ export function Canvas() {
233
252
  if (booted.current || nodes.length === 0) return
234
253
  let revealed = false
235
254
  booted.current = true
255
+ // the page before this one reloaded itself when its canvas came back: its camera, on the board it showed
256
+ const cam = resumed?.camera && resumed.board === useStore.getState().board ? resumed.camera : null
236
257
  const fit = () => {
237
258
  const keys = linkTargets(bootHash, useStore.getState().nodes)
238
259
  if (keys.length) {
239
260
  useStore.setState({ selection: keys })
240
261
  const st = useStore.getState() // a link opened is a look (marks not in yet: their first load acknowledges it)
241
262
  st.look(keys)
263
+ }
264
+ const el = document.querySelector('.sh-canvas') as HTMLElement | null
265
+ if (cam && el && ref.current) {
266
+ recorder.placed({ x: -cam.x / cam.scale, y: -cam.y / cam.scale, w: el.clientWidth / cam.scale, h: el.clientHeight / cam.scale })
267
+ ref.current.setTransform(cam.x, cam.y, cam.scale, 0)
268
+ } else if (keys.length) {
242
269
  canvasCtl.fitNodes(keys)
243
270
  } else {
244
271
  canvasCtl.fitAll()
@@ -11,9 +11,11 @@ import { primeCameraFor } from './camera-broadcast.ts'
11
11
  import { sleep, wake } from './sleep.ts'
12
12
  import { canAutoReload, shouldArmReadyWatch } from './ready-watch.ts'
13
13
  import { Stickies, type NoteSpec } from './Sticky.tsx'
14
+ import { recorder } from '../recorder.ts'
14
15
  import { noteId, sceneNoteHost } from '../notes.ts'
15
16
  import { slideSize, stageFit } from '../../const.ts'
16
17
  import { FrameSlot, toneOf, useFrameMark } from '../marks-ui.tsx'
18
+ import { stranded } from '../api.ts'
17
19
 
18
20
  export const HEADER = 28
19
21
  const SNAP = 12
@@ -94,6 +96,8 @@ export const FrameNode = memo(function FrameNode({ node }: { node: Node }) {
94
96
  // survives a theme flip; file changes and reloads navigate imperatively below, only once
95
97
  // admitted - a queued frame takes the fresh revision when its turn comes.
96
98
  const [src, setSrc] = useState<string>()
99
+ // the document is another project's "another canvas" page (spec 28 A1.11): a quiet placeholder over it instead
100
+ const [away, setAway] = useState(false)
97
101
  const admitted = src !== undefined
98
102
  const admittedRef = useRef(false)
99
103
  const fileRef = useRef(frame ? `${frame.kind}:${frame.file}` : null)
@@ -116,6 +120,7 @@ export const FrameNode = memo(function FrameNode({ node }: { node: Node }) {
116
120
  if (n.status !== 'loading') setStatus(node.key, 'loading') // a returning frame boots under the watchdog like any other
117
121
  admittedRef.current = true
118
122
  setSrc(frameUrl(f, n.theme))
123
+ recorder.admitted(node.key)
119
124
  }
120
125
  admit({ key: node.key, rank, start })
121
126
  return () => release(node.key)
@@ -271,7 +276,9 @@ export const FrameNode = memo(function FrameNode({ node }: { node: Node }) {
271
276
  // boot slot - its boot is still running - and gives it back after a second silence.
272
277
  useEffect(() => {
273
278
  if (!admitted || node.status !== 'loading' || !frame || node.missing) return
274
- const t = setTimeout(() => { if (shouldArmReadyWatch(node, true)) reloadRef.current(true); else release(node.key) }, 10_000)
279
+ // the second silence gives the slot back, and is the recorder's never-ready (spec 28 A1.7) - the frame stays
280
+ // loading, never a red card
281
+ const t = setTimeout(() => { if (shouldArmReadyWatch(node, true)) reloadRef.current(true); else { release(node.key); recorder.neverReady(node.key) } }, 10_000)
275
282
  return () => clearTimeout(t)
276
283
  // depend on the frame's stable SIGNATURE, not the manifest object - that object is replaced on
277
284
  // every manifest reconcile, so depending on it would reset the budget on unrelated frames during
@@ -433,7 +440,7 @@ export const FrameNode = memo(function FrameNode({ node }: { node: Node }) {
433
440
  ) : null}
434
441
  {/* a frame still silent after its one auto-retry: a slow dev server, never a failure. A quiet
435
442
  non-covering pill (not the red card) keeps it honest and offers a manual reload. */}
436
- {node.status === 'loading' && node.readyRetried ? (
443
+ {node.status === 'loading' && node.readyRetried && !away ? (
437
444
  <div className="sh-loading sh-no-pan">
438
445
  <span>still loading</span>
439
446
  <button className="sh-no-pan" onClick={() => reload(false)}>
@@ -446,9 +453,11 @@ export const FrameNode = memo(function FrameNode({ node }: { node: Node }) {
446
453
  className="sh-live"
447
454
  src={src}
448
455
  title={frame.id}
449
- onLoad={() => { registerWin(); frameLoaded(node.key, iframeRef.current) }}
456
+ onLoad={() => { setAway(stranded(iframeRef.current)); registerWin(); frameLoaded(node.key, iframeRef.current); recorder.loaded(node.key) }}
450
457
  style={{ ...iframeBox(stage, node), display: node.missing || node.status === 'error' ? 'none' : 'block' }}
451
458
  />
459
+ {/* its canvas is away from this address: one calm line, the banner says the rest */}
460
+ {away && <div className="sh-stranded"><span>Waiting for this canvas</span></div>}
452
461
  {/* the overlay eats mouse events for drag-by-body; laser and comment mode both
453
462
  need the mouse INSIDE the frame for hover highlights, so it steps aside
454
463
  (drag still works via the header) */}
@@ -43,10 +43,17 @@ const SETTLE = 350 // the board fit animates ~250 ms from 60 ms after mount: r
43
43
  /** The frame is done booting (ready, error, gone, or its watchdog took over): free the slot, or
44
44
  * leave the queue if it never started. */
45
45
  export function release(key: string): void {
46
- waiting.delete(key)
46
+ const was = waiting.delete(key) || active.has(key)
47
47
  if (active.delete(key)) { primed = true; schedule(0) }
48
+ if (was && admissionIdle()) for (const fn of idle) { try { fn() } catch { /* a listener never stops the queue */ } }
48
49
  }
49
50
 
51
+ const idle = new Set<() => void>()
52
+ /** Nothing queued, nothing booting: a board load settles only then (spec 28 A1.7). */
53
+ export const admissionIdle = (): boolean => !waiting.size && !active.size
54
+ /** Called each time the last frame lets go of its slot or leaves the queue; returns the unsubscribe. */
55
+ export function onAdmissionIdle(fn: () => void): () => void { idle.add(fn); return () => { idle.delete(fn) } }
56
+
50
57
  function schedule(ms: number): void {
51
58
  if (scheduled) return
52
59
  scheduled = true
@@ -22,17 +22,27 @@ function broadcast(moving: boolean): void {
22
22
  for (const w of frameWindows()) { try { w.postMessage(msg, location.origin) } catch { /* cross-doc timing */ } }
23
23
  }
24
24
 
25
+ /** What is moving on the canvas: the camera (a pan or zoom, `sh-camera`) and the layout (a preset or tidy animation,
26
+ * `sh-preset`). The same one observer tells the shell's own listeners - the gesture sampler (perf.ts) and the
27
+ * recorder's camera idle (spec 28 A1.7) - on every change of either, so nothing polls. */
28
+ export interface Motion { camera: boolean; preset: boolean }
29
+ let motion: Motion = { camera: false, preset: false }
30
+ const motionListeners = new Set<(m: Motion) => void>()
31
+ /** Called with the new motion at each change; returns the unsubscribe. */
32
+ export function onMotion(fn: (m: Motion) => void): () => void { motionListeners.add(fn); return () => { motionListeners.delete(fn) } }
33
+
25
34
  let started = false
26
35
  export function startCameraBroadcast(): void {
27
36
  if (started) return
28
37
  const world = document.getElementById('sh-world'); if (!world) return
29
38
  started = true
30
- let moving = false
31
39
  new MutationObserver(() => {
32
- const now = world.classList.contains('sh-camera')
33
- if (now === moving) return
34
- moving = now
35
- broadcast(now) // +sh-camera -> freeze; -sh-camera -> sharpen to the settled scale
40
+ const now = { camera: world.classList.contains('sh-camera'), preset: world.classList.contains('sh-preset') }
41
+ if (now.camera === motion.camera && now.preset === motion.preset) return
42
+ const cameraChanged = now.camera !== motion.camera
43
+ motion = now
44
+ if (cameraChanged) broadcast(now.camera) // +sh-camera -> freeze; -sh-camera -> sharpen to the settled scale
45
+ for (const fn of motionListeners) { try { fn(now) } catch { /* a listener never stops the broadcast */ } }
36
46
  }).observe(world, { attributes: true, attributeFilter: ['class'] })
37
47
  }
38
48
 
@@ -29,4 +29,6 @@ export const canvasCtl = {
29
29
  /** Is the camera mid-flight (a fit, a zoom)? A content-driven reflow waits for it to land: a fit
30
30
  * aimed at the frames a link names must not land on where they were before the rows moved. */
31
31
  cameraBusy(): boolean { return false },
32
+ /** What the camera shows now, in world px (null with no canvas) - a load's visible cohort when no fit landed. */
33
+ view(): { x: number; y: number; w: number; h: number } | null { return null },
32
34
  }
@@ -11,8 +11,34 @@
11
11
  export interface FrameReg { key: string; iframe: HTMLIFrameElement }
12
12
 
13
13
  const byWindow = new WeakMap<WindowProxy, FrameReg>()
14
+ const byKey = new Map<string, HTMLIFrameElement>()
14
15
 
15
- export const registerFrame = (win: WindowProxy, reg: FrameReg): void => { byWindow.set(win, reg) }
16
- export const unregisterFrame = (win: WindowProxy): void => { byWindow.delete(win) }
16
+ export const registerFrame = (win: WindowProxy, reg: FrameReg): void => { byWindow.set(win, reg); byKey.set(reg.key, reg.iframe) }
17
+ export const unregisterFrame = (win: WindowProxy): void => {
18
+ const reg = byWindow.get(win)
19
+ byWindow.delete(win)
20
+ if (reg && byKey.get(reg.key) === reg.iframe) byKey.delete(reg.key)
21
+ }
22
+ /** The iframe a node shows now - the recorder reads its live document's id off it (spec 28 A1.7). */
23
+ export const iframeOf = (key: string): HTMLIFrameElement | undefined => byKey.get(key)
17
24
  export const frameByWindow = (win: unknown): FrameReg | undefined =>
18
25
  win ? byWindow.get(win as WindowProxy) : undefined
26
+
27
+ /** The id of the document an iframe shows now, as its frame bridge set it (`__mvBoot`, spec 28 A1.7) - absent while a
28
+ * new document has not run its bridge yet, or when the frame was navigated off this origin (the read throws). */
29
+ export function bootOf(iframe: HTMLIFrameElement | undefined): string | undefined {
30
+ try {
31
+ const b = (iframe?.contentWindow as { __mvBoot?: unknown } | null | undefined)?.__mvBoot
32
+ return typeof b === 'string' ? b : undefined
33
+ } catch { return undefined }
34
+ }
35
+
36
+ /** A frame's message comes from the document its iframe shows now: the URL revision the shell gave that document
37
+ * (`gen`, against the iframe's src) and the document's own id (`boot`, against the live one). A WindowProxy survives
38
+ * navigation, and a same-URL reload keeps `gen`, so only both tell the document there now from one since replaced
39
+ * whose message was still on its way. Asked before a message changes anything. */
40
+ export function fromLiveDocument(iframe: HTMLIFrameElement, data: { gen?: unknown; boot?: unknown }): boolean {
41
+ const gen = iframe.src.match(/[?&]r=(\d+)/)?.[1] ?? ''
42
+ if (String(data.gen ?? '') !== gen) return false
43
+ return typeof data.boot === 'string' && data.boot !== '' && data.boot === bootOf(iframe)
44
+ }
@@ -27,6 +27,7 @@
27
27
  */
28
28
  import { ROUTE } from '../../const.ts'
29
29
  import { BAKES, PUBLISHED } from '../store.ts'
30
+ import { api } from '../api.ts'
30
31
  import { readOwn, sleepRule } from '../../../shared/sleep-rule.ts'
31
32
 
32
33
  /** `doc`: the revision the document shows (spec 26) - the compiler refuses a document behind its frame */
@@ -48,6 +49,8 @@ const keyOf = (k: SleepKey) => `${k.frame}|${k.theme}|${Math.round(k.w)}|${Math.
48
49
 
49
50
  /** What a node's DOCUMENT is asleep under, published only once its override is INSTALLED. */
50
51
  const asleep = new Map<string, { key: string; doc: Document }>()
52
+ /** How many frames are asleep now (the recorder's weight of a settled load, spec 28 A1.7). */
53
+ export const sleepingCount = (): number => asleep.size
51
54
  /** The node's current request, so a stale answer (a newer sleep, a wake in between) is dropped. */
52
55
  const pending = new Map<string, number>()
53
56
  let seq = 0
@@ -95,7 +98,7 @@ function ask(key: SleepKey): Promise<Answer> {
95
98
  const index = PUBLISHED ? await staticAnswers() : null
96
99
  if (!index) {
97
100
  try {
98
- const r = await fetch(`${ROUTE}/api/bakes`, { method: 'POST', headers: { 'content-type': 'application/json', 'x-mv-c': csrf() }, body: JSON.stringify({ asks }) })
101
+ const r = await api('bakes', { method: 'POST', headers: { 'content-type': 'application/json', 'x-mv-c': csrf() }, body: JSON.stringify({ asks }) })
99
102
  data = r.ok ? await r.json() : null
100
103
  } catch { data = null }
101
104
  }
@@ -11,6 +11,7 @@ import { playPing } from './sound.ts'
11
11
  import { ROUTE } from '../const.ts'
12
12
  import { ALL_SCENES } from '../../shared/board-tree.ts'
13
13
  import { UNPLACED } from './hash.ts'
14
+ import { api as request, canvasStopped, scoped, stoppedLink, useLink } from './api.ts'
14
15
 
15
16
  /** What the Not on a board view says when asked for a comment: a note needs a board to live on. */
16
17
  export const NO_COMMENTS_HERE = 'pin it on a board to comment'
@@ -81,11 +82,11 @@ interface CommentsState {
81
82
 
82
83
  const uuid = () => crypto.randomUUID()
83
84
  const loadMentionSeen = (): Record<string, number> => {
84
- try { return JSON.parse(localStorage.getItem('mv-mention-seen') ?? '{}') } catch { return {} }
85
+ try { return JSON.parse(localStorage.getItem(scoped('mv-mention-seen')) ?? '{}') } catch { return {} }
85
86
  }
86
87
  const csrf = () => /(?:^|;\s*)mv_c=([\w-]+)/.exec(document.cookie)?.[1] ?? ''
87
88
  const api = async (path: string, body?: unknown) => {
88
- const res = await fetch(`${ROUTE}/api/${path}`, body === undefined ? undefined : {
89
+ const res = await request(path, body === undefined ? undefined : {
89
90
  method: 'POST', headers: { 'content-type': 'application/json', 'x-mv-c': csrf() },
90
91
  body: JSON.stringify(body),
91
92
  })
@@ -360,14 +361,15 @@ export const useComments = create<CommentsState>((set, get) => {
360
361
  },
361
362
 
362
363
  // the Not on a board view shows threads but takes no new ones (spec 26): a note needs a board
363
- setMode(on) { if (on && get().board === UNPLACED) return; set({ commentMode: on, ...(on ? { show: true } : { draft: null }) }) },
364
+ // never on while the canvas is stopped (spec 28 A1.11): a comment picked could not be sent
365
+ setMode(on) { if (on && (get().board === UNPLACED || canvasStopped())) return; set({ commentMode: on, ...(on ? { show: true } : { draft: null }) }) },
364
366
  setShow(show) { set({ show }) },
365
367
  setShowAnchor(showAnchor) { set({ showAnchor }) },
366
368
  setActive(active) {
367
369
  // opening a thread is SEEING it - the mention pulse for it stops here
368
370
  if (active) {
369
371
  const mentionSeen = { ...get().mentionSeen, [active]: Date.now() }
370
- try { localStorage.setItem('mv-mention-seen', JSON.stringify(mentionSeen)) } catch { /* private mode */ }
372
+ try { localStorage.setItem(scoped('mv-mention-seen'), JSON.stringify(mentionSeen)) } catch { /* private mode */ }
371
373
  set({ active, mentionSeen })
372
374
  } else set({ active })
373
375
  },
@@ -403,6 +405,12 @@ export const useComments = create<CommentsState>((set, get) => {
403
405
  }
404
406
  })
405
407
 
408
+ // the canvas stopped (spec 28 A1.11): comment mode goes off - a pick could open only a comment that cannot be
409
+ // sent. A comment being written stays, words and all.
410
+ useLink.subscribe((l, p) => {
411
+ if (stoppedLink(l.link) && !stoppedLink(p.link) && useComments.getState().commentMode && !useComments.getState().draft) useComments.getState().setMode(false)
412
+ })
413
+
406
414
  // dev-only debug handle - the canvas store exposes the same
407
415
  if (typeof window !== 'undefined' && (import.meta as any).env?.DEV) (window as any).__mvComments = useComments
408
416
 
@@ -13,10 +13,10 @@ export function goTo(target: string, carry = false): void {
13
13
  const s = useStore.getState()
14
14
  const existing = s.nodes.find((n) => n.frame === target && !n.missing)
15
15
  if (existing) {
16
- navigated() // a local goto supersedes any cross-board one in flight
16
+ const seq = navigated() // a local goto supersedes any cross-board one in flight
17
17
  s.select(existing.key)
18
18
  if (carry) s.setInteract(existing.key)
19
- setTimeout(() => canvasCtl.fitNode(existing.key), 50)
19
+ fitLater(existing.key, seq)
20
20
  } else void gotoAcrossBoards(target, carry)
21
21
  }
22
22
 
@@ -50,7 +50,7 @@ async function gotoAcrossBoards(target: string, carry: boolean) {
50
50
  if (!node) return st.toast(`unknown goto target "${target}"`)
51
51
  st.select(node.key)
52
52
  if (carry) st.setInteract(node.key)
53
- setTimeout(() => canvasCtl.fitNode(node.key), 50)
53
+ fitLater(node.key, seq)
54
54
  return
55
55
  }
56
56
  await landOn(home, target, carry, seq, from)
@@ -59,7 +59,8 @@ async function gotoAcrossBoards(target: string, carry: boolean) {
59
59
  /** Navigation supersedes any goto or reveal still on its way - its board lookup (gotoSeq) AND a board
60
60
  * switch it already started (a switch to the board on screen cancels any pending one: store.ts) - so
61
61
  * a slow lookup can never yank the view away from where the human has gone since. Every entry point
62
- * calls it: a pasted link, back/forward, a goto, a reveal, a board picked in the sidebar. */
62
+ * calls it, the published shell's too: a pasted link, back/forward, a goto, a reveal, a board picked in
63
+ * the sidebar or the play pill, a notification's View - and switches boards only through switchFor. */
63
64
  export function navigated(): number {
64
65
  const s = useStore.getState()
65
66
  if (s.board) void s.switchBoard(s.board)
@@ -67,12 +68,23 @@ export function navigated(): number {
67
68
  }
68
69
  /** Is this still the latest navigation - nothing newer since `navigated()` handed it out? */
69
70
  export const isLatest = (seq: number): boolean => seq === gotoSeq
71
+ /** The one way a navigation changes boards - a link, a goto, a reveal, a board picked in the sidebar or the play pill, a
72
+ * notification's View: the switch is navigation `nav`'s (a new one, unless the caller took it at its own start, before
73
+ * a lookup), and true only once it landed with nothing newer since. What the caller does on the board - select, set a
74
+ * mode, enter play, move the camera - waits for true: a switch a newer navigation cancelled comes back too, and may
75
+ * find the board it asked for, the newer one's by then. */
76
+ export async function switchFor(board: string, nav: number = navigated()): Promise<boolean> {
77
+ await useStore.getState().switchBoard(board)
78
+ return isLatest(nav) && useStore.getState().board === board
79
+ }
80
+ /** The camera to a node once it is drawn - unless a newer navigation has it by then. */
81
+ const fitLater = (key: string, seq: number) => setTimeout(() => { if (isLatest(seq)) canvasCtl.fitNode(key) }, 50)
70
82
 
71
83
  /** Switch to `home` and select + fit `target` there once the board commits - unless the human has
72
84
  * moved on: newer navigation, or a board they switched to themselves while the lookup ran. */
73
85
  async function landOn(home: string, target: string, carry: boolean, seq: number, from: string) {
74
86
  if (seq !== gotoSeq || useStore.getState().board !== from) return
75
- await useStore.getState().switchBoard(home)
87
+ if (!await switchFor(home, seq)) return
76
88
  for (let i = 0; i < 12; i++) { // the board commits async - retry like viewNote
77
89
  if (seq !== gotoSeq) return
78
90
  const st = useStore.getState()
@@ -81,7 +93,7 @@ async function landOn(home: string, target: string, carry: boolean, seq: number,
81
93
  if (node) {
82
94
  st.select(node.key)
83
95
  if (carry) st.setInteract(node.key)
84
- setTimeout(() => canvasCtl.fitNode(node.key), 50)
96
+ fitLater(node.key, seq)
85
97
  return
86
98
  }
87
99
  }
@@ -93,17 +105,17 @@ async function landOn(home: string, target: string, carry: boolean, seq: number,
93
105
  * not show, the way back from a focus link): this board, else the first board that shows it
94
106
  * (archive boards last), else - a frame on no board - the Not on a board view. Unlike a goto it
95
107
  * never spawns - opening a link must not edit a board. */
96
- export async function revealFrame(target: string): Promise<void> {
108
+ export async function revealFrame(target: string, nav?: number): Promise<void> { // `nav`: a caller's navigation, else its own
97
109
  const s = useStore.getState()
98
110
  const here = s.nodes.find((n) => n.frame === target && !n.missing)
99
111
  if (here) {
100
- navigated()
112
+ const seq = nav ?? navigated()
101
113
  s.select(here.key)
102
- setTimeout(() => canvasCtl.fitNode(here.key), 50)
114
+ fitLater(here.key, seq)
103
115
  return
104
116
  }
105
117
  if (!s.manifest?.frames.some((f) => f.id === target)) return s.toast(`no frame "${target}" on this canvas`)
106
- const seq = navigated()
118
+ const seq = nav ?? navigated()
107
119
  const from = s.board
108
120
  let home: string | null = null
109
121
  try {