@marver-design/marver 0.34.0 → 0.35.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 (31) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/README.md +1 -1
  3. package/dist/{anchor-check-Cld22HFE.mjs → anchor-check-DREwCQiE.mjs} +1 -1
  4. package/dist/{build-C1AGScLz.mjs → build-3AH123fe.mjs} +3 -3
  5. package/dist/cli.mjs +3 -6
  6. package/dist/{daemon-CWl_0QF8.mjs → daemon-BE-t9iU-.mjs} +1 -1
  7. package/dist/{dev-Kfv8FgVw.mjs → dev-Dw6mcoP8.mjs} +7 -7
  8. package/dist/{notes-CRAX4wgk.mjs → notes-CmfQ9604.mjs} +13 -4
  9. package/dist/{pdf-6JNQAKJv.mjs → pdf-CkE4Ir2P.mjs} +3 -3
  10. package/dist/{plugin-C1SEQSU5.mjs → plugin-C6jEpbCx.mjs} +38 -15
  11. package/dist/{poster-BO971KQR.mjs → poster-d10h73z0.mjs} +1 -1
  12. package/dist/{publish-bakes-JCG2kvQP.mjs → publish-bakes-weNQnNqE.mjs} +2 -2
  13. package/dist/{recover-BIHPEDTa.mjs → recover-Dekpav7b.mjs} +1 -1
  14. package/dist/{shot-G0bBXwHl.mjs → shot-Ct2FiEbu.mjs} +2 -2
  15. package/docs/performance.md +4 -0
  16. package/package.json +1 -1
  17. package/src/client/const.ts +5 -0
  18. package/src/client/content/img-lod.ts +3 -1
  19. package/src/client/frame-host/inplace.ts +43 -0
  20. package/src/client/frame-host/main.tsx +10 -1
  21. package/src/client/shell/App.tsx +26 -18
  22. package/src/client/shell/LockedApp.tsx +6 -5
  23. package/src/client/shell/canvas/Canvas.tsx +50 -16
  24. package/src/client/shell/canvas/FrameNode.tsx +40 -7
  25. package/src/client/shell/canvas/admission.ts +138 -5
  26. package/src/client/shell/canvas/sleep.ts +258 -26
  27. package/src/client/shell/hash.ts +24 -0
  28. package/src/client/shell/jam-capture.ts +3 -2
  29. package/src/client/shell/notes.ts +11 -4
  30. package/src/client/shell/recorder.ts +1 -1
  31. package/src/client/shell/store.ts +63 -11
@@ -35,7 +35,8 @@ import type { BakeWork } from '../../../shared/perf-run.ts'
35
35
  /** `doc`: the revision the document shows (spec 26) - the compiler refuses a document behind its frame */
36
36
  export interface SleepKey { frame: string; theme: string; w: number; h: number; doc?: string }
37
37
  interface Target { sel: string; rect: { x: number; y: number; w: number; h: number }; filter: string; level: number; texture: string; verified: boolean }
38
- type Answer = { ok: true; targets: Target[] } | { ok: false; error: string }
38
+ /** `gen`: the server's source generation the answer holds for (a dev canvas); `kept`: a refusal the server keeps for it */
39
+ type Answer = ({ ok: true; targets: Target[] } | { ok: false; error: string; kept?: boolean }) & { gen?: number }
39
40
 
40
41
  const STYLE_ID = 'mv-sleep'
41
42
  /** How far (CSS px) any EDGE of an element's border box may sit from the one the compiler measured.
@@ -79,8 +80,9 @@ export function scheduleSleep(fn: () => void, ms: number): () => void {
79
80
  const pending = new Map<string, number>()
80
81
  let seq = 0
81
82
  /** Nodes with a retry of a failed compile in flight - or, in a headless perf run, spent: a run's frame retries once
82
- * until it wakes, so the run can reach bake-idle; every other canvas retries every 4 s for as long as the frame
83
- * rests, as before 0.27.2, so a frame recovers when the server does. */
83
+ * until it wakes, so the run can reach bake-idle; every other canvas retries a failure that may pass (not a settled
84
+ * answer: `parked` below) every 4 s for as long as the frame rests, as before 0.27.2, so a frame recovers when the
85
+ * server does. */
84
86
  const retried = new Set<string>()
85
87
  const RETRY_MS = 4000
86
88
  /** The server's answer for a compile still running (src/server/bake.ts COMPILING), and how many times a
@@ -90,6 +92,106 @@ const COMPILING_TRIES = 15
90
92
  /** Looks so far, per node, for the sleep key they were for: a new key (an edit, a theme, a size)
91
93
  * or a wake starts the count again. */
92
94
  const compiling = new Map<string, { key: string; n: number }>()
95
+ /**
96
+ * Nodes resting on a SETTLED answer - one the server gives again, word for word, while it retains it: a refusal it keeps
97
+ * for the source generation (`kept`: the frame loops, never stops changing, has too many effects...) or a compile none
98
+ * of whose textures certified (its disk cache). Asking again every 4 s, forever, changed nothing but cost a POST, a
99
+ * computed-style walk, a style rewrite and a forced layout per frame. A parked node asks again through the normal sleep:
100
+ * - when it learns of a generation DIFFERENT from its answer's - a push (`sh:bake-gen`, every source change), or any
101
+ * bake answer over HTTP (the shell's own socket may stay closed: api.ts). Equality only: a replacement server may
102
+ * count from anywhere, so no generation is "newer";
103
+ * - when the server would now answer otherwise with the generation unchanged (its retained answer evicted, deleted,
104
+ * replaced): the BACKSTOP, one batched ask for every parked node each `backstopMs` (30 s: 2 POSTs a minute for
105
+ * the whole board where the retries made 76), which touches no document - only a node whose answer changed goes
106
+ * back through the sleep;
107
+ * - on a reconnect (perhaps a new server), and when it wakes (a new document, theme or size: a new key).
108
+ * No sleep timer, so a parked node is bake-idle; a headless perf run has no backstop (it goes idle and stays so).
109
+ */
110
+ interface Parked { key: SleepKey; gen: number | undefined; sig: string; retry: () => void }
111
+ const parked = new Map<string, Parked>()
112
+ /** What an answer says, for "did it change": the kind, the refusal word for word, whether any texture certifies. */
113
+ const sigOf = (a: Answer): string => (a.ok ? `ok:${a.targets.some((t) => t.verified && t.texture) ? 1 : 0}` : `${a.kept ? 'kept' : 'no'}:${a.error}`)
114
+ /** Every generation heard - a push, any bake answer, a reconnect (`undefined`: perhaps a new server) - numbered, the
115
+ * last HEARD_KEPT of them kept: an ask that one of them overtook asks once more. */
116
+ let heardSeq = 0
117
+ const HEARD_KEPT = 64
118
+ const heardLog: { seq: number; gen: number | undefined }[] = []
119
+ /** Was a generation other than `gen` heard after `since`? (Forgotten ones count as other: one re-ask too many at worst.) */
120
+ function heardOther(since: number, gen: number | undefined): boolean {
121
+ if (heardSeq - since > HEARD_KEPT) return true
122
+ return heardLog.some((e) => e.seq > since && (e.gen === undefined || e.gen !== gen))
123
+ }
124
+ /** When each node last asked (its bake POST went out), on the monotonic clock. Every release of a parked node asks
125
+ * again at max(now + 250 ms, its last ask + RETRY_MS): never more than once per 4 s and never later than 4 s after
126
+ * its previous ask - the old retry's own cadence, at worst - and at once after a long rest. */
127
+ const lastAsk = new Map<string, number>()
128
+ function release(nodeKey: string): void {
129
+ const p = parked.get(nodeKey)
130
+ if (!p) return
131
+ parked.delete(nodeKey)
132
+ const was = lastAsk.get(nodeKey)
133
+ // every node released in the same moment shares one batch
134
+ scheduleSleep(p.retry, was === undefined ? 250 : Math.max(250, was + RETRY_MS - performance.now()))
135
+ }
136
+ /** A generation heard of: every node parked under a DIFFERENT one asks again. `undefined`: perhaps a new server - all do. */
137
+ function heard(gen: number | undefined): void {
138
+ heardLog.push({ seq: ++heardSeq, gen })
139
+ if (heardLog.length > HEARD_KEPT) heardLog.shift()
140
+ for (const [nodeKey, p] of [...parked]) if (gen === undefined || (p.gen !== undefined && p.gen !== gen)) release(nodeKey)
141
+ }
142
+ const pushed = (gen: number | undefined): void => heard(gen)
143
+ function park(nodeKey: string, key: SleepKey, answer: Answer, heardAtAsk: number, retry: () => void): void {
144
+ parked.set(nodeKey, { key, gen: answer.gen, sig: sigOf(answer), retry })
145
+ // another generation was heard while the ask was out (a push, another request's answer): once more, under the
146
+ // cadence (one re-ask per generation heard - never a loop)
147
+ if (heardOther(heardAtAsk, answer.gen)) release(nodeKey)
148
+ backstopSoon()
149
+ }
150
+ /** The backstop's period: 30 s (a test sets another through the dev hook below). */
151
+ let backstopMs = 30_000
152
+ let backstop: ReturnType<typeof setTimeout> | undefined, looking = false
153
+ function backstopSoon(): void {
154
+ if (backstop !== undefined || looking || !parked.size || PERF_RUN || PUBLISHED) return
155
+ backstop = setTimeout(() => { backstop = undefined; looking = true; void lookAgain().finally(() => { looking = false; backstopSoon() }) }, backstopMs)
156
+ }
157
+ /** The backstop: what would the server answer every parked node now? Over HTTP, no document touched. */
158
+ async function lookAgain(): Promise<void> {
159
+ // each key once in the whole look, whatever the chunk: the nodes parked on it ride with it
160
+ const byKey = new Map<string, { key: SleepKey; nodes: [string, Parked][] }>()
161
+ for (const [nodeKey, p] of parked) { const k = keyOf(p.key), e = byKey.get(k); if (e) e.nodes.push([nodeKey, p]); else byKey.set(k, { key: p.key, nodes: [[nodeKey, p]] }) }
162
+ const all = [...byKey.values()]
163
+ for (let i = 0; i < all.length; i += ASKS_MAX) {
164
+ // only nodes still parked on this very answer (a board switch during an earlier chunk sends nothing for them)
165
+ const chunk = all.slice(i, i + ASKS_MAX).map((e) => ({ key: e.key, nodes: e.nodes.filter(([nodeKey, p]) => parked.get(nodeKey) === p) })).filter((e) => e.nodes.length)
166
+ if (!chunk.length) continue
167
+ const part = chunk.flatMap((e) => e.nodes)
168
+ inflight++
169
+ try {
170
+ const data = await post(chunk.map((e) => e.key))
171
+ if (!data) continue // no answer (the server is away): nothing learned, the next look asks again
172
+ const gen = typeof data.gen === 'number' ? data.gen : undefined
173
+ if (gen !== undefined) heard(gen)
174
+ for (const [nodeKey, p] of part) {
175
+ if (parked.get(nodeKey) !== p) continue // woke, released or parked anew meanwhile
176
+ const a = toAnswer(data.answers?.find((x) => keyOf(x) === keyOf(p.key)), gen)
177
+ if (a.ok === false && a.error === 'no answer') continue
178
+ if (sigOf(a) !== p.sig) release(nodeKey)
179
+ }
180
+ } finally { inflight-- }
181
+ }
182
+ }
183
+ if (import.meta.hot) {
184
+ import.meta.hot.on('sh:bake-gen', (m: { gen?: unknown }) => pushed(typeof m?.gen === 'number' ? m.gen : undefined))
185
+ import.meta.hot.on('vite:ws:connect', () => heard(undefined))
186
+ }
187
+ // dev-only inspection hook for tests (never in a published build): what a node is parked on, and a push as the socket
188
+ // would deliver it
189
+ if (import.meta.env.DEV) (window as unknown as { __mvSleep: unknown }).__mvSleep = {
190
+ parkedOn: (k: string) => { const p = parked.get(k); return p ? { gen: p.gen, sig: p.sig } : null },
191
+ pushed,
192
+ bakeWork: () => bakeWork(),
193
+ backstopEvery: (ms: number) => { backstopMs = ms; clearTimeout(backstop); backstop = undefined; backstopSoon() },
194
+ }
93
195
 
94
196
  /** Does this document have anything to compile? Cheap: one computed style per element. */
95
197
  export function hasEffects(doc: Document): boolean {
@@ -108,39 +210,64 @@ const staticAnswers = () => (published ??= (BAKES ? fetch(`${ROUTE}/bakes/${BAKE
108
210
  .then((j: { gen?: number; answers?: Record<string, Answer> }) => (j.gen === BAKES && j.answers) || {}).catch((): Record<string, Answer> => ({})))
109
211
 
110
212
  // ---- one batch per tick: every frame that decides to sleep in the same moment shares a browser
111
- const queue: { key: SleepKey; resolve: (a: Answer) => void }[] = []
213
+ /** A waiter: the node asking, its answer, and whether it still wants one (its sleep's `current()`). */
214
+ interface Waiter { node: string; resolve: (a: Answer) => void; live: () => boolean }
215
+ const queue: { key: SleepKey; w: Waiter }[] = []
112
216
  let flush: ReturnType<typeof setTimeout> | undefined
113
- function ask(key: SleepKey): Promise<Answer> {
217
+ function ask(key: SleepKey, node: string, live: () => boolean): Promise<Answer> {
114
218
  return new Promise((resolve) => {
115
- queue.push({ key, resolve })
219
+ queue.push({ key, w: { node, resolve, live } })
116
220
  clearTimeout(flush)
117
221
  flush = setTimeout(async () => {
118
222
  const batch = queue.splice(0)
119
223
  // one ask per key; every waiter for that key gets the same answer
120
- const byKey = new Map<string, { key: SleepKey; waiters: ((a: Answer) => void)[] }>()
121
- for (const q of batch) { const kk = keyOf(q.key); const e = byKey.get(kk); if (e) e.waiters.push(q.resolve); else byKey.set(kk, { key: q.key, waiters: [q.resolve] }) }
122
- const asks = [...byKey.values()].map((e) => ({ frame: e.key.frame, theme: e.key.theme, w: Math.round(e.key.w), h: Math.round(e.key.h), ...(e.key.doc ? { doc: e.key.doc } : {}) }))
123
- let data: { answers?: (Answer & SleepKey)[] } | null = null
224
+ const byKey = new Map<string, { key: SleepKey; waiters: Waiter[] }>()
225
+ for (const q of batch) { const kk = keyOf(q.key); const e = byKey.get(kk); if (e) e.waiters.push(q.w); else byKey.set(kk, { key: q.key, waiters: [q.w] }) }
124
226
  inflight++
125
227
  try {
126
228
  const index = PUBLISHED ? await staticAnswers() : null
127
- if (!index) {
128
- try {
129
- const r = await api('bakes', { method: 'POST', headers: { 'content-type': 'application/json', 'x-mv-c': csrf() }, body: JSON.stringify({ asks }) })
130
- data = r.ok ? await r.json() : null
131
- } catch { data = null }
229
+ if (index) answerAll(byKey, index, null)
230
+ else {
231
+ // the server takes at most ASKS_MAX a request: a bigger batch (a generation releasing hundreds of parked
232
+ // frames at once) goes in several, sent together (none waits behind another's answer), each answering its own
233
+ // waiters - and as they go, a waiter that no longer wants its answer (woken, its board left) is answered
234
+ // "no answer" and a key with none left is not sent
235
+ const parts: Map<string, { key: SleepKey; waiters: Waiter[] }>[] = []
236
+ for (const e of byKey.values()) {
237
+ const live = e.waiters.filter((w) => w.live())
238
+ for (const w of e.waiters) if (!live.includes(w)) w.resolve({ ok: false, error: 'no answer' })
239
+ if (!live.length) continue
240
+ if (!parts.length || parts[parts.length - 1].size >= ASKS_MAX) parts.push(new Map())
241
+ parts[parts.length - 1].set(keyOf(e.key), { key: e.key, waiters: live })
242
+ }
243
+ const now = performance.now()
244
+ for (const part of parts) for (const e of part.values()) for (const w of e.waiters) lastAsk.set(w.node, now)
245
+ await Promise.all(parts.map(async (part) => answerAll(part, null, await post([...part.values()].map((e) => e.key)))))
132
246
  }
133
- answerAll(byKey, index, data)
134
247
  } finally { inflight-- }
135
248
  }, 40)
136
249
  })
137
250
  }
251
+ type Answers = { gen?: number; answers?: (Answer & SleepKey)[] }
252
+ /** The server's asks limit (api.ts: 1-200 a request). */
253
+ const ASKS_MAX = 200
254
+ /** One POST of the bake asks; null when there is no answer (a network failure, a refusal of the request). */
255
+ async function post(keys: SleepKey[]): Promise<Answers | null> {
256
+ const asks = keys.map((k) => ({ frame: k.frame, theme: k.theme, w: Math.round(k.w), h: Math.round(k.h), ...(k.doc ? { doc: k.doc } : {}) }))
257
+ try {
258
+ const r = await api('bakes', { method: 'POST', headers: { 'content-type': 'application/json', 'x-mv-c': csrf() }, body: JSON.stringify({ asks }) })
259
+ return r.ok ? await r.json() : null
260
+ } catch { return null }
261
+ }
262
+ const toAnswer = (a: (Answer & SleepKey) | Answer | undefined, gen: number | undefined): Answer =>
263
+ a ? (a.ok ? { ok: true, targets: a.targets, gen } : { ok: false, error: a.error, ...(a.kept === true ? { kept: true } : {}), gen }) : { ok: false, error: 'no answer' }
138
264
  /** Every waiter of a batch, its key's answer - before the POST stops counting, so the page is never idle between. */
139
- function answerAll(byKey: Map<string, { key: SleepKey; waiters: ((a: Answer) => void)[] }>, index: Record<string, Answer> | null, data: { answers?: (Answer & SleepKey)[] } | null): void {
265
+ function answerAll(byKey: Map<string, { key: SleepKey; waiters: Waiter[] }>, index: Record<string, Answer> | null, data: Answers | null): void {
266
+ const gen = typeof data?.gen === 'number' ? data.gen : undefined
267
+ if (gen !== undefined) heard(gen)
140
268
  for (const e of byKey.values()) {
141
- const a = index ? index[keyOf(e.key)] : data?.answers?.find((x) => keyOf(x) === keyOf(e.key))
142
- const answer: Answer = a ? (a.ok ? { ok: true, targets: a.targets } : { ok: false, error: a.error }) : { ok: false, error: 'no answer' }
143
- for (const w of e.waiters) w(answer)
269
+ const answer = toAnswer(index ? index[keyOf(e.key)] : data?.answers?.find((x) => keyOf(x) === keyOf(e.key)), gen)
270
+ for (const w of e.waiters) w.resolve(answer)
144
271
  }
145
272
  }
146
273
 
@@ -171,7 +298,8 @@ async function sleepNow(nodeKey: string, iframe: HTMLIFrameElement, key: SleepKe
171
298
  asleep.set(nodeKey, { key: k, doc })
172
299
  return 'asleep'
173
300
  }
174
- const answer = await ask(key)
301
+ const heardAtAsk = heardSeq
302
+ const answer = await ask(key, nodeKey, current)
175
303
  if (!current()) return 'live'
176
304
  // still compiling (issue #23): the server answered in seconds and carries on by itself. The frame
177
305
  // stays LIVE meanwhile - pausing now would freeze a finite animation midway, under a texture of its
@@ -189,17 +317,20 @@ async function sleepNow(nodeKey: string, iframe: HTMLIFrameElement, key: SleepKe
189
317
  // fails to decode (pruned, missing, corrupt) leaves the glass live
190
318
  const decoded = await Promise.all(targets.map((t) => { const im = new Image(); im.src = t.texture; return im.decode().then(() => true, () => false) }))
191
319
  if (!current()) return 'live'
192
- if (decoded.some((ok) => !ok)) targets = []
320
+ const undecoded = decoded.some((ok) => !ok)
321
+ if (undecoded) targets = []
193
322
  // a published document names the generation it was built with: textures dress that build only
194
323
  if (PUBLISHED && targets.length && doc.querySelector('meta[name="mv-bakes"]')?.getAttribute('content') !== String(BAKES)) targets = []
195
324
  if (!install(doc, targets)) return 'live'
196
325
  // a certified sleep is remembered; the pause-only fallback is not, so the next lifecycle event
197
- // asks again (a compile the source outran, a server hiccup), and a retry is scheduled now. A canvas retries
198
- // every 4 s while the frame rests: the retry clears its own mark, so a failure after a failure asks again and
199
- // the glass sleeps once the server recovers. A headless perf run's retry keeps its mark until the node wakes -
200
- // one retry, then nothing more, or a frame the compiler refuses would keep the run from ever being bake-idle
326
+ // asks again. A SETTLED answer (a kept refusal, a compile none of whose textures certified) parks the node
327
+ // until the source generation moves (`park`). Anything else - a compile the source outran, a server hiccup, a
328
+ // texture that did not decode - schedules a retry now. A canvas retries every 4 s while the frame rests: the
329
+ // retry clears its own mark, so a failure after a failure asks again and the glass sleeps once the server
330
+ // recovers. A headless perf run's retry keeps its mark until the node wakes - one retry, then nothing more
201
331
  if (targets.length) { asleep.set(nodeKey, { key: k, doc }); compiling.delete(nodeKey); retried.delete(nodeKey) }
202
332
  else if (answer.ok === false && answer.error === COMPILING) { /* out of looks: the pause alone, final */ }
333
+ else if (!PUBLISHED && !undecoded && (answer.ok || answer.kept)) park(nodeKey, key, answer, heardAtAsk, () => { if (current()) void sleep(nodeKey, iframe, key) }) // settled until the generation moves
203
334
  else if (!PUBLISHED && !retried.has(nodeKey)) { retried.add(nodeKey); scheduleSleep(() => { if (!PERF_RUN) retried.delete(nodeKey); if (current()) void sleep(nodeKey, iframe, key) }, RETRY_MS) } // a static miss is final
204
335
  return 'asleep'
205
336
  }
@@ -210,7 +341,10 @@ export function wake(nodeKey: string, iframe: HTMLIFrameElement | null): void {
210
341
  asleep.delete(nodeKey)
211
342
  compiling.delete(nodeKey)
212
343
  retried.delete(nodeKey)
344
+ parked.delete(nodeKey)
345
+ lastAsk.delete(nodeKey)
213
346
  const doc = iframe?.contentDocument
347
+ if (doc) resumeSmil(doc)
214
348
  const st = doc?.getElementById(STYLE_ID)
215
349
  if (!doc || !st) return
216
350
  const els = [...doc.querySelectorAll<HTMLElement>('[data-mv-sleep]')]
@@ -254,5 +388,103 @@ function install(doc: Document, targets: Target[]): boolean {
254
388
  // one paint, and no authored transition (`transition: all` is common on a pill) may animate the
255
389
  // effect out or the texture in
256
390
  still(doc, els, () => { els.forEach((el, i) => el.setAttribute('data-mv-sleep', String(i))); style.textContent = rules.join('\n') })
391
+ pauseSmil(doc)
257
392
  return true
258
393
  }
394
+
395
+ /** The SVG time containers this sleep holds, per sleeping document. */
396
+ const smilHeld = new WeakMap<Document, Set<SVGSVGElement>>()
397
+ const SMIL = 'animate,animateTransform,animateMotion,set'
398
+ const SVG_NS = 'http://www.w3.org/2000/svg'
399
+ const SHADOWED = ['pauseAnimations', 'unpauseAnimations', 'animationsPaused'] as const
400
+ /** The native timeline methods, taken once from the shell's own realm: a platform method works on an element of any
401
+ * realm, so a hold is undone whatever document the element is in by then, with or without a window. */
402
+ const NATIVE = typeof SVGSVGElement === 'function'
403
+ ? { pause: SVGSVGElement.prototype.pauseAnimations, unpause: SVGSVGElement.prototype.unpauseAnimations, paused: SVGSVGElement.prototype.animationsPaused }
404
+ : null
405
+ /** A held <svg>: what its author last asked for, and the own properties it had under our shadows (restored at wake). */
406
+ interface Hold { paused: boolean; saved: (readonly [string, PropertyDescriptor | undefined])[] }
407
+ const holds = new WeakMap<SVGSVGElement, Hold>()
408
+ /** The shadows, one of each for every held <svg>: they honour `this` - a call on an element not held (another <svg>,
409
+ * or this one after its wake) goes to the native method. */
410
+ const SHADOWS: Record<(typeof SHADOWED)[number], (this: SVGSVGElement) => unknown> = {
411
+ pauseAnimations() { const h = holds.get(this); if (h) h.paused = true; else NATIVE!.pause.call(this) },
412
+ unpauseAnimations() { const h = holds.get(this); if (h) h.paused = false; else NATIVE!.unpause.call(this) },
413
+ animationsPaused() { const h = holds.get(this); return h ? h.paused : NATIVE!.paused.call(this) },
414
+ }
415
+ /**
416
+ * SVG's own animations (SMIL: `<animate>`, `<animateTransform>`, ...) are no CSS animation: `animation-play-state` never
417
+ * reaches them, and one running in any document - a rotating gradient - repaints and commits the WHOLE page every
418
+ * frame. They pause with the CSS ones, by their time container (the outermost <svg>; every <svg> on the way is held
419
+ * too, whichever one an engine keys the timeline on). While asleep the timeline holds still whatever the author calls
420
+ * - as the CSS pause is !important: on each held <svg>, own `pauseAnimations`/`unpauseAnimations` only record what
421
+ * they ask, and `animationsPaused()` answers it (their code sees the state it asked for, as if awake). Wake restores
422
+ * the element's own properties as they were and runs the timeline only if the author's last word is "running" -
423
+ * paused before the sleep and never unpaused, or paused during it, it stays paused. A paused timeline resumes where it
424
+ * stood: nothing jumps, a finished animation does not restart.
425
+ *
426
+ * A hold is all or nothing: an <svg> whose own properties cannot be shadowed (an authored non-configurable one, a
427
+ * non-extensible element) is left unheld - it animates on, as before sleep paused SMIL at all - and sleep never fails
428
+ * for an SVG. Idempotent: a sleep installed again holds nothing twice.
429
+ *
430
+ * Accepted, not handled - each needs code written against the sleep itself; content that drives its SVG the ordinary
431
+ * way (declarative SMIL, or direct method calls on the element) behaves as without sleep:
432
+ * - code that captured the native method before the sleep (a bound `svg.pauseAnimations`, or
433
+ * `SVGSVGElement.prototype.pauseAnimations.call(svg)`) bypasses the record: its pause during a sleep is undone at wake;
434
+ * - an <svg> on which the author installed their OWN pauseAnimations/unpauseAnimations/animationsPaused (a wrapper or
435
+ * accessor with side effects - a player updating its controls): while the frame sleeps a call records the intent
436
+ * but does not run the author's wrapper; the wrapper is back at wake;
437
+ * - an <svg> adopted into another document while its own frame sleeps stays held until that frame wakes - and after
438
+ * the frame's document is replaced, wake() works on the new document and does not resume a hold left on the old
439
+ * one (the old document is gone from the frame);
440
+ * - Gecko's nested <svg> query differs while held: an inner svg's `animationsPaused()` answers its own recorded
441
+ * intent, not its outer container's;
442
+ * - an <svg> mounted after the frame fell asleep is not held (it animates).
443
+ */
444
+ function hold(s: SVGSVGElement): boolean {
445
+ const saved = SHADOWED.map((k) => [k, Object.getOwnPropertyDescriptor(s, k)] as const)
446
+ if (saved.some(([, d]) => d && !d.configurable)) return false
447
+ const h: Hold = { paused: NATIVE!.paused.call(s), saved }
448
+ holds.set(s, h)
449
+ try {
450
+ for (const k of SHADOWED) Object.defineProperty(s, k, { configurable: true, writable: true, value: SHADOWS[k] })
451
+ } catch {
452
+ holds.delete(s)
453
+ unshadow(s, h)
454
+ return false
455
+ }
456
+ if (!h.paused) NATIVE!.pause.call(s) // last: nothing above can leave it paused unrecorded
457
+ return true
458
+ }
459
+ /** The element's own properties back as they were before the hold. */
460
+ function unshadow(s: SVGSVGElement, h: Hold): void {
461
+ for (const [k, d] of h.saved) {
462
+ try { if (d) Object.defineProperty(s, k, d); else delete (s as unknown as Record<string, unknown>)[k] } catch { /* as it is */ }
463
+ }
464
+ }
465
+ function pauseSmil(doc: Document): void {
466
+ if (!NATIVE) return
467
+ const anims = doc.querySelectorAll(SMIL)
468
+ if (!anims.length) return
469
+ let held = smilHeld.get(doc)
470
+ for (const a of anims) {
471
+ if (a.namespaceURI !== SVG_NS) continue
472
+ for (let s = (a as SVGElement).ownerSVGElement; s; s = s.ownerSVGElement) {
473
+ if (holds.has(s) || !hold(s)) continue
474
+ if (!held) smilHeld.set(doc, held = new Set())
475
+ held.add(s)
476
+ }
477
+ }
478
+ }
479
+ function resumeSmil(doc: Document): void {
480
+ const held = smilHeld.get(doc)
481
+ if (!held || !NATIVE) return
482
+ smilHeld.delete(doc)
483
+ for (const s of held) {
484
+ const h = holds.get(s)
485
+ if (!h) continue
486
+ holds.delete(s)
487
+ unshadow(s, h)
488
+ if (!h.paused) NATIVE.unpause.call(s)
489
+ }
490
+ }
@@ -113,12 +113,36 @@ export function buildHash(s: HashState): string {
113
113
  return `#/b/${s.board}${q ? `?${decodeURIComponent(q)}` : ''}`
114
114
  }
115
115
 
116
+ /** The hashes popstates routed whose hashchange is still to come: a navigation that changes the hash fires popstate
117
+ * (synchronously under `location.hash =`, in its own task for back/forward) and queues a hashchange - other tasks,
118
+ * and the next navigation's popstate, can run before it. `seen`: the hash as the router or the projection left it.
119
+ * Never cut by count - a mark dropped while its hashchange can still come would route that navigation again over
120
+ * the newer ones (nine `location.hash =` in one task: nine popstates, then nine hashchanges): each mark goes when its
121
+ * own hashchange comes, with any older one before it, so the list holds the navigations still owed a hashchange. */
122
+ const owed: string[] = []
123
+ let seen = typeof location === 'undefined' ? '' : location.hash
124
+ /** The hash a history event asks the router to apply - or null: the hashchange of a navigation its popstate already
125
+ * routed, the same navigation, never routed again (whatever came since - a goto, a click, the next link - is newer;
126
+ * and by then location.hash may hold the projection, written by a store update rendered in between). A hashchange
127
+ * with no popstate before it is routed from the URL it carries; a synthetic one carrying none, from location.hash. */
128
+ export function routedHash(e: Event): string | null {
129
+ if (e.type === 'popstate') {
130
+ if (location.hash !== seen) owed.push(location.hash) // a same-hash entry has no hashchange to come
131
+ return seen = location.hash
132
+ }
133
+ const h = e instanceof HashChangeEvent && e.newURL ? new URL(e.newURL).hash : null
134
+ const i = h === null ? -1 : owed.indexOf(h)
135
+ if (i >= 0) { owed.splice(0, i + 1); return null }
136
+ return seen = h ?? location.hash
137
+ }
138
+
116
139
  /** Write the hash; identical URLs are skipped so restore paths never loop. */
117
140
  export function writeHash(s: HashState, push = false) {
118
141
  const h = buildHash(s)
119
142
  if (h === location.hash || (h === '#/' && !location.hash)) return
120
143
  if (push) history.pushState(null, '', h)
121
144
  else history.replaceState(null, '', h)
145
+ seen = h
122
146
  }
123
147
 
124
148
  /** The hash as it stood when the app loaded - boot intent, captured once; re-aimed only when an old
@@ -16,7 +16,7 @@
16
16
  import { onScreen, usable } from './inset.ts'
17
17
  import { create } from 'zustand'
18
18
  import { slideSize } from '../const.ts'
19
- import { CONFIG, SLIDE_INTRINSIC, stoppedFor, useStore, type Node } from './store.ts'
19
+ import { CONFIG, SLIDE_INTRINSIC, geometryCause, stoppedFor, useStore, type Node } from './store.ts'
20
20
  import { UNPLACED } from './hash.ts'
21
21
  import type { Bundle, CaptureRecord, Step, View } from '../../server/jam/types.ts'
22
22
  import { forgetHeard, RATE, setWordsListener, voiceBegin, voiceDrop, voiceEnd } from './jam-voice.ts'
@@ -292,7 +292,8 @@ function watchUi() {
292
292
  if (s.selection.join() !== p.selection.join() && s.selection.length) {
293
293
  addStep(id, { at, event: 'select', frames: [...new Set(s.selection.map((k) => frameIdOf(k)).filter((f): f is string => !!f))] }, s.selection, performance.now() - playLeftAt < 200)
294
294
  }
295
- for (const n of s.nodes) {
295
+ // what a person did to a node, never what the manifest did (a frame file's theme edited mid-capture is no step)
296
+ if (geometryCause() !== 'manifest') for (const n of s.nodes) {
296
297
  const o = p.nodes.find((x) => x.key === n.key)
297
298
  if (!o) continue
298
299
  // a device change: the node took a preset's size (its width names the viewport)
@@ -69,14 +69,18 @@ export const clearNoteHeights = (): void => { noteHeights.clear() }
69
69
  * the frames make way. An obstacle is another node's card, or its own note column (two columns
70
70
  * running into each other cramp too) - the two rectangles, never their bounding box: the empty
71
71
  * canvas under a card beside a long column is free. Missing nodes (a deleted frame's card, still
72
- * drawn full size) block room but never host a note. `noteH` is the measured column extent. */
72
+ * drawn full size) block room but never host a note. `noteH` is the measured column extent - a pure lookup: it is
73
+ * asked once per node, when its room is first needed. */
73
74
  export function notesCramped(
74
75
  nodes: readonly { key: string; frame: string; x: number; y: number; w: number; h: number; missing?: boolean }[],
75
76
  manifest: { frames: { id: string; scene: string; note?: string }[]; scenes: { name: string; note?: string }[] } | null,
76
77
  noteH: (key: string) => number = noteHeight,
77
78
  ): boolean {
78
79
  if (!manifest) return false
79
- const entry = (id: string) => manifest.frames.find((f) => f.id === id)
80
+ // asked at each note a board measures: an index of the manifest (the first entry of an id, as a find gives), not a scan per node
81
+ const byId = new Map<string, (typeof manifest.frames)[number]>()
82
+ for (const f of manifest.frames) if (!byId.has(f.id)) byId.set(f.id, f)
83
+ const entry = (id: string) => byId.get(id)
80
84
  const live = nodes.filter((n) => !n.missing)
81
85
  const hosts = new Set<string>()
82
86
  for (const s of manifest.scenes) {
@@ -93,12 +97,15 @@ export function notesCramped(
93
97
  const r = n.missing ? 0 : noteReserve(!!entry(n.frame)?.note, hosts.has(n.key))
94
98
  return r ? { x0: n.x - r, x1: n.x, y0: n.y, y1: n.y + Math.max(n.h + NODE_HEADER, noteH(n.key)) } : null
95
99
  }
100
+ // each node's room once, when first asked (not once per pair) - so noteH is asked once per node, at most
101
+ const rooms = new Map<N, R | null>()
102
+ const roomOf = (n: N): R | null => { let r = rooms.get(n); if (r === undefined) rooms.set(n, r = room(n)); return r }
96
103
  return live.some((n) => {
97
- const mine = room(n)
104
+ const mine = roomOf(n)
98
105
  if (!mine) return false
99
106
  return nodes.some((o) => {
100
107
  if (o === n) return false
101
- const theirs = room(o)
108
+ const theirs = roomOf(o)
102
109
  return hit(mine, card(o)) || (!!theirs && hit(mine, theirs))
103
110
  })
104
111
  })
@@ -72,7 +72,7 @@ const lapsed = new Map<string, Load>()
72
72
  let owner: Load | null = null
73
73
  /** node key -> what its live document said (page-level: a reload of the same board keeps its documents) */
74
74
  const tracks = new Map<string, Track>()
75
- /** each node's geometry as last seen - numbers, not the node objects (applyManifest edits nodes in place) */
75
+ /** each node's geometry as last seen - numbers, not the node objects (a move is told by its numbers, whichever objects hold them) */
76
76
  let baseline = new Map<string, { x: number; y: number; w: number; h: number }>()
77
77
  const outbox = new Outbox()
78
78
  /** a drag's or a resize's move record per node while it waits to be sent: the next pointermove adds to it */
@@ -588,6 +588,19 @@ export function settleRule(n: Node, manifest: Manifest | null): 'measure' | 'rea
588
588
  if (!f) return 'missing'
589
589
  return f.contentWidth && n.sizeMode !== 'device' && measures(f.id) ? 'measure' : 'ready'
590
590
  }
591
+ /** The manifest's entry for a frame id - the first of that id, as a find gives - from an index built once per frames
592
+ * array (a manifest's arrays are replaced, never edited): every node's selectors look their frame up on each store
593
+ * update, and a canvas's manifest can hold thousands. */
594
+ const frameIndex = new WeakMap<FrameEntry[], Map<string, FrameEntry>>()
595
+ export function frameById(frames: FrameEntry[], id: string): FrameEntry | undefined {
596
+ let byId = frameIndex.get(frames)
597
+ if (!byId) {
598
+ byId = new Map()
599
+ for (const f of frames) if (!byId.has(f.id)) byId.set(f.id, f)
600
+ frameIndex.set(frames, byId)
601
+ }
602
+ return byId.get(id)
603
+ }
591
604
  /** Did a measuring node open at a height already known (committed in _sizes.json, or measured earlier in this page)? */
592
605
  export const knownHeight = (frameId: string, w: number): boolean => hasKnownHeight(frameId, Math.round(w))
593
606
  /** What measureNode took: `fit` - the report was taken at the node's width `w` (applied, or its height already) - the
@@ -800,7 +813,33 @@ export const DISK_WON = 'board changed on disk - canvas layout reloaded'
800
813
  /** What a board save says when the board was renamed or removed meanwhile: it is not created again. */
801
814
  export const BOARD_GONE = 'this board was renamed or removed - not recreating it'
802
815
 
803
- export const useStore = create<State>((set, get) => {
816
+ export const useStore = create<State>((rawSet, rawGet, storeApi) => {
817
+ // sh:theme-applied acks, batched: one store update for a switch's burst (112 acks were 0.8 s of the shell
818
+ // re-rendering, one update each). They are applied BEFORE the store's own actions read (get) or write (set), and
819
+ // before any setState from outside, so every state an action or a FUNCTIONAL setState acts on, carries or discards
820
+ // is the one acks written as they came would have made: only a run of acks with nothing else between them becomes
821
+ // one update. React reads through the store's own getState, unflushed: what the batch defers is that one re-render.
822
+ // The one way to break it: a writer outside the store that reads getState(), builds an OBJECT from it and writes it
823
+ // back (`setState({ nodes: getState().nodes.map(...) })`) overwrites a just-applied ack with its stale copy - write
824
+ // nodes from outside with the functional form (`setState((s) => ({ nodes: ... }))`); DEV says so once. Otherwise
825
+ // the acks land at the next animation frame (100 ms on a hidden page), by whichever timer comes first.
826
+ const acks: { pending: Map<string, string>; frame?: number; timer?: ReturnType<typeof setTimeout> } = { pending: new Map() }
827
+ const applyAcks = () => {
828
+ if (acks.frame !== undefined && typeof cancelAnimationFrame === 'function') cancelAnimationFrame(acks.frame)
829
+ clearTimeout(acks.timer)
830
+ acks.frame = acks.timer = undefined
831
+ if (!acks.pending.size) return
832
+ const mine = acks.pending
833
+ acks.pending = new Map()
834
+ rawSet((s) => ({ nodes: s.nodes.map((n) => { const t = mine.get(n.key); return t === undefined || t === n.themeOn ? n : { ...n, themeOn: t } }) }))
835
+ }
836
+ const set = ((partial: Parameters<typeof rawSet>[0], replace?: boolean) => { applyAcks(); rawSet(partial as never, replace as never) }) as typeof rawSet
837
+ const get: typeof rawGet = () => { applyAcks(); return rawGet() }
838
+ let warned = false
839
+ storeApi.setState = ((partial: Parameters<typeof rawSet>[0], replace?: boolean) => {
840
+ if (import.meta.env.DEV && !warned && acks.pending.size && partial && typeof partial === 'object' && 'nodes' in partial) { warned = true; console.error('[marver] setState({ nodes }) from outside while theme acks are pending: write nodes with the functional form, setState((s) => ({ nodes: ... })) - an object built from getState() overwrites them (store.ts)') }
841
+ set(partial as never, replace as never)
842
+ }) as typeof rawSet
804
843
  let saveTimer: ReturnType<typeof setTimeout> | undefined
805
844
  let saveChain: Promise<boolean> = Promise.resolve(true) // saves are serialized; responses only commit if the board is still active
806
845
  let editRev = 0 // bumps per edit; a stale save response may never clear dirty over a newer edit
@@ -1471,9 +1510,15 @@ export const useStore = create<State>((set, get) => {
1471
1510
  }
1472
1511
  const live = new Set(m.frames.map((f) => f.id))
1473
1512
  let retinted = false
1474
- for (const n of next) {
1513
+ for (let i = 0; i < next.length; i++) {
1514
+ // a node the state on screen holds is never written: the one this pass changes is a copy (a subscriber told
1515
+ // before the set below - the pruning toast's - must read the state it was given, and a memo keyed by the
1516
+ // nodes array must hold: same array, same nodes)
1517
+ let n = next[i]
1518
+ const edit = (): Node => (i < nodes.length && n === nodes[i] ? (n = next[i] = { ...n }) : n)
1475
1519
  const missing = !live.has(n.frame)
1476
1520
  if (missing !== !!n.missing) {
1521
+ edit()
1477
1522
  // a node whose frame just ARRIVED (the create-first choreography: the agent
1478
1523
  // appends the board node before the manifest registers the file) was sized by
1479
1524
  // the 390x844 GUESS - its real viewport is only knowable now. ONLY guessed
@@ -1496,16 +1541,16 @@ export const useStore = create<State>((set, get) => {
1496
1541
  // (derived value: re-render yes, dirty/save no)
1497
1542
  const f = m.frames.find((x) => x.id === n.frame)
1498
1543
  const want = n.themeUser ?? f?.theme ?? get().viewTheme
1499
- if (n.theme !== want) { n.theme = want; retinted = true }
1544
+ if (n.theme !== want) { edit().theme = want; retinted = true }
1500
1545
  // content-ness can change live (agent adds/removes the primitives): reconcile
1501
1546
  // provenance or measurements are rejected / UI dims silently omitted from saves.
1502
1547
  // Under an active device view the newcomer joins it as 'device' - a measurement
1503
1548
  // must not override the preset the whole board is showing
1504
- if (f?.contentWidth && !n.sizeMode) { n.sizeMode = deviceView ? 'device' : 'auto'; retinted = true }
1505
- if (!f?.contentWidth && n.sizeMode) { delete n.sizeMode; retinted = true }
1549
+ if (f?.contentWidth && !n.sizeMode) { edit().sizeMode = deviceView ? 'device' : 'auto'; retinted = true }
1550
+ if (!f?.contentWidth && n.sizeMode) { delete edit().sizeMode; retinted = true }
1506
1551
  // an errored frame whose file IS in the fresh manifest gets one automatic retry
1507
1552
  // on a rev-stamped URL - the "unknown frame id" dead end must self-heal (#20)
1508
- if (!missing && n.status === 'error') { n.status = 'loading'; n.nav = (n.nav ?? 0) + 1; n.readyRetried = false; retinted = true }
1553
+ if (!missing && n.status === 'error') { edit(); n.status = 'loading'; n.nav = (n.nav ?? 0) + 1; n.readyRetried = false; retinted = true }
1509
1554
  }
1510
1555
  // auto boards prune deleted frames outright - "auto-managed" must manage both
1511
1556
  // directions (friction log #15). Curated boards keep the explicit card.
@@ -1518,7 +1563,7 @@ export const useStore = create<State>((set, get) => {
1518
1563
  toast(dropped === 1 ? 'removed 1 deleted frame' : `removed ${dropped} deleted frames`)
1519
1564
  }
1520
1565
  }
1521
- // a guessed size corrected above (in place) is a move, seen when this set notifies the recorder
1566
+ // a guessed size corrected above is a move, seen when this set notifies the recorder
1522
1567
  withCause('manifest', () => set((s) => ({
1523
1568
  manifest: m,
1524
1569
  nodes: changed || retinted ? [...final] : final,
@@ -1541,7 +1586,9 @@ export const useStore = create<State>((set, get) => {
1541
1586
  scheduleSave()
1542
1587
  },
1543
1588
 
1544
- frameFor(node) { return get().manifest?.frames.find((f) => f.id === node.frame) },
1589
+ // read from selectors (FrameNode, Comments) while React renders: the raw state - acks touch no manifest, and a
1590
+ // flush there would write the store mid-render
1591
+ frameFor(node) { const m = rawGet().manifest; return m ? frameById(m.frames, node.frame) : undefined },
1545
1592
 
1546
1593
  moveNode(key, x, y) {
1547
1594
  withCause('drag', () => set((s) => ({ nodes: s.nodes.map((n) => (n.key === key ? { ...n, x, y } : n)), dirty: true })))
@@ -1697,7 +1744,12 @@ export const useStore = create<State>((set, get) => {
1697
1744
  else { scheduleSave(); roomForNotes(); recheckLayout() } // ...unless a note grew meanwhile, or a Doc changed size, under the restored rows
1698
1745
  }) },
1699
1746
  bumpRev(key) { set((s) => ({ nodes: s.nodes.map((n) => (n.key === key ? { ...n, rev: (n.rev ?? 0) + 1 } : n)) })) },
1700
- setThemeOn(key, theme) { set((s) => ({ nodes: s.nodes.map((n) => (n.key === key ? { ...n, themeOn: theme } : n)) })) },
1747
+ setThemeOn(key, theme) {
1748
+ acks.pending.set(key, theme) // the last of a key wins, as when each landed at once
1749
+ if (acks.frame !== undefined || acks.timer !== undefined) return
1750
+ if (typeof requestAnimationFrame === 'function') acks.frame = requestAnimationFrame(applyAcks)
1751
+ acks.timer = setTimeout(applyAcks, 100) // a hidden page draws no frames
1752
+ },
1701
1753
  setStatus(key, status, error) {
1702
1754
  // any real ready/error resets the one-shot retry allowance, so a later manual reload or a
1703
1755
  // fresh manifest earns its own auto-retry again
@@ -1931,8 +1983,8 @@ export const useStore = create<State>((set, get) => {
1931
1983
  set((s) => ({
1932
1984
  viewTheme: theme,
1933
1985
  nodes: s.nodes.map((n) => {
1934
- const f = s.manifest?.frames.find((x) => x.id === n.frame)
1935
- return { ...n, themeUser: undefined, theme: f?.theme ?? theme }
1986
+ const t = (s.manifest ? frameById(s.manifest.frames, n.frame)?.theme : undefined) ?? theme
1987
+ return n.theme === t && n.themeUser === undefined ? n : { ...n, themeUser: undefined, theme: t } // by the index, not a scan per node
1936
1988
  }),
1937
1989
  dirty: true,
1938
1990
  }))