@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
@@ -6,7 +6,7 @@ import { JamButton } from './jam-session.tsx'
6
6
  import { useJamCapture } from './jam-capture.ts'
7
7
  import { useJamQueue } from './jam-queue.ts'
8
8
  import { Component, useEffect, useLayoutEffect, useRef, useState, type MouseEvent as ReactMouseEvent, type ReactNode } from 'react'
9
- import { useStore, BOARD_GONE, CONFIG, CANVAS_NAME, DISK_WON, LOCKED_SHELL, PUBLISHED, SOURCE_REVEALED, stoppedFor, logReload, takeReloadCause, addToBoard, boardLabel, cap, humanize, fetchBoardNames, landingBoard, tabTitle, hydrateBoardPolicy, landingMode, playsAsSlides, sceneLabel, switchCount, type FrameEntry } from './store.ts'
9
+ import { useStore, BOARD_GONE, CONFIG, frameById, CANVAS_NAME, DISK_WON, LOCKED_SHELL, PUBLISHED, SOURCE_REVEALED, stoppedFor, logReload, takeReloadCause, addToBoard, boardLabel, cap, humanize, fetchBoardNames, landingBoard, tabTitle, hydrateBoardPolicy, landingMode, playsAsSlides, sceneLabel, switchCount, type FrameEntry } from './store.ts'
10
10
  import { AddToBoard, BoardList } from './BoardList.tsx'
11
11
  import { ContextMenu, copyToClipboard, framePath, useContextMenu, type MenuItem } from './ContextMenu.tsx'
12
12
  import { TOP } from './inset.ts'
@@ -24,7 +24,7 @@ import { takeNavToken } from './recorder-reloads.ts'
24
24
  import { cmd, endAfterFrames, endOnCamera, endOnLoad, endOnStage, foldsIntoSave, keysOf, shellReload, type CmdHandle, type CmdOpts } from './commands.ts'
25
25
  import { enterFocus, enterPlay, enterSlides, playCtl, PlayOverlay } from './Play.tsx'
26
26
  import { PdfNotice } from './pdf-export.tsx'
27
- import { bootHash, linkTargets, parseHash, retargetBoot, UNPLACED, writeHash } from './hash.ts'
27
+ import { bootHash, linkTargets, parseHash, retargetBoot, routedHash, UNPLACED, writeHash } from './hash.ts'
28
28
  import { isLegacyLink, landLegacy } from './legacy-links.ts'
29
29
  import { CaretIcon, CheckIcon, CheckSquareOffsetIcon, ColumnsIcon, FrameRectIcon, ImagesSquareIcon, IntentGlyph, MoonIcon, PanelFilledIcon, PanelHollowIcon, ParallelogramDuoIcon, ParallelogramFillIcon, PencilSimpleIcon, PlayIcon, PlusIcon, SignpostIcon, SlideFrameIcon, SunIcon, VariantsIcon, XIcon } from './icons.tsx'
30
30
  import { deviceIcon, deviceLabel } from './devices.tsx'
@@ -517,18 +517,24 @@ export function App() {
517
517
  // selection against the newly loaded state. writeHash skips identical hashes, so
518
518
  // restores never echo back into history.
519
519
  useEffect(() => {
520
- // the switch a navigation started, while it may still run: back/forward, a pasted link and `location.hash =` each
521
- // fire popstate AND hashchange, and a second switch to the same board would supersede the first - a second board
522
- // fetch, and a load that never committed in perf --loads
520
+ // the switch a navigation started, while it may still run: a second navigation to that same hash before it lands -
521
+ // the link followed again (the projection may have written the board still on screen back over the URL meanwhile),
522
+ // a second click on the same link (a popstate alone) - would supersede it: a second board fetch, and a load that
523
+ // never committed in perf --loads. Not the second EVENT of one navigation: routedHash drops that one first.
523
524
  let routing: { hash: string; switches: number } | null = null
524
- // the recorder's (spec 30): back/forward fires both events, a same-board one with no switch to tell them apart
525
+ // the recorder's (spec 30): an event of the same hash just after another - one routedHash cannot pair with its
526
+ // popstate (no newURL) - carries that one's command on
525
527
  let recorded: { hash: string; at: number; h: CmdHandle | null; run: number } = { hash: '', at: -1_000, h: null, run: 0 }
526
- const onPop = async () => {
528
+ const onPop = async (e: Event) => {
529
+ // back/forward, a pasted link and `location.hash =` each fire popstate AND hashchange: the second is the same
530
+ // navigation, routed by the first - routed again it would supersede the first's switch (a second board fetch) or
531
+ // undo whatever came between (hash.ts routedHash)
532
+ const raw = routedHash(e)
533
+ if (raw === null) return
527
534
  // the same hash, and no switch or cancel since this router started its own (a board picked, a goto, a newer
528
- // navigation): the second event of the navigation the first is carrying through - board, frame and view
529
- if (routing && routing.hash === location.hash && routing.switches === switchCount()) return
530
- const raw = location.hash
531
- // the second event carries the first's command on; the first, overtaken by its own twin, does not end it
535
+ // navigation): a navigation to where the one under way is going - its board, frame and view
536
+ if (routing && routing.hash === raw && routing.switches === switchCount()) return
537
+ // the second carries the first's command on; the first, overtaken by it, does not end it
532
538
  const again = raw === recorded.hash && performance.now() - recorded.at < 250
533
539
  const run = recorded.run + 1
534
540
  const nav_ = again ? recorded.h : cmd('history-nav', { via: 'click', in: 'shell' })
@@ -538,7 +544,7 @@ export function App() {
538
544
  // a lookup below still running when newer navigation lands - a link, a board picked, a step in play - is dropped
539
545
  const at = useStore.getState().board, step = useStore.getState().play?.at
540
546
  const overtaken = () => !isLatest(nav) || useStore.getState().board !== at || useStore.getState().play?.at !== step
541
- let h = parseHash()
547
+ let h = parseHash(raw)
542
548
  if (PUBLISHED && h.board === UNPLACED) h = {} // the Not on a board view is dev's: published, the default board
543
549
  const legacy = isLegacyLink(h)
544
550
  if (legacy) {
@@ -976,13 +982,15 @@ export function App() {
976
982
  const onBoard = new Set(nodes.map((n) => n.frame))
977
983
  const frames = (manifest?.frames ?? []).filter((f) => onBoard.has(f.id))
978
984
  // scene groups follow the CANVAS reading order (earliest node y, then x), the
979
- // same law as frame rows - a story board's phases list top-to-bottom as laid out
985
+ // same law as frame rows - a story board's phases list top-to-bottom as laid out.
986
+ // Each scene's first node is found in one pass over the board (this runs on every render), not one per comparison.
987
+ const first = new Map<string, { y: number; x: number }>()
988
+ for (const n of nodes) {
989
+ const sc = frameById(frames, n.frame)?.scene, acc = sc === undefined ? undefined : first.get(sc)
990
+ if (sc !== undefined && (!acc || n.y < acc.y || (n.y === acc.y && n.x < acc.x))) first.set(sc, { y: n.y, x: n.x })
991
+ }
980
992
  const scenes = [...new Set(frames.map((f) => f.scene))].sort((a, b) => {
981
- const min = (sc: string) => nodes.reduce((acc, n) => {
982
- const f = frames.find((x) => x.id === n.frame)
983
- if (f?.scene !== sc) return acc
984
- return !acc || n.y < acc.y || (n.y === acc.y && n.x < acc.x) ? { y: n.y, x: n.x } : acc
985
- }, null as { y: number; x: number } | null)
993
+ const min = (sc: string) => first.get(sc) ?? null
986
994
  const ma = min(a), mb = min(b)
987
995
  if (!ma || !mb) return ma ? -1 : mb ? 1 : a.localeCompare(b)
988
996
  return ma.y - mb.y || ma.x - mb.x || a.localeCompare(b)
@@ -12,7 +12,7 @@
12
12
  import { Component, useEffect, useRef, type ReactNode } from 'react'
13
13
  import { useStore, landingBoard, landingMode, tabTitle } from './store.ts'
14
14
  import { enterFocus, enterPlay, enterSlides, PlayOverlay, playCtl } from './Play.tsx'
15
- import { UNPLACED, bootHash, parseHash, retargetBoot, writeHash } from './hash.ts'
15
+ import { UNPLACED, bootHash, parseHash, retargetBoot, routedHash, writeHash } from './hash.ts'
16
16
  import { isLegacyLink, landLegacy } from './legacy-links.ts'
17
17
  import { useComments } from './comments-store.ts'
18
18
  import { isLatest, navigated, switchFor } from './goto.ts'
@@ -102,17 +102,18 @@ export function App() {
102
102
  // back/forward + pasted links, within what the lock allows
103
103
  useEffect(() => {
104
104
  let recorded: { hash: string; at: number; h: CmdHandle | null; run: number } = { hash: '', at: -1_000, h: null, run: 0 }
105
- const onPop = async () => {
105
+ const onPop = async (e: Event) => {
106
+ // back/forward and a pasted link fire popstate AND hashchange: the second is the same navigation, already routed
107
+ const hash = routedHash(e)
108
+ if (hash === null) return
106
109
  // a lookup newer navigation overtook - a link, a goto, a step on the stage - is dropped
107
110
  const nav = navigated(), was = useStore.getState()
108
- // spec 30: back/forward fires popstate AND hashchange; the second carries the first's command on
109
- const hash = location.hash
110
111
  const again = hash === recorded.hash && performance.now() - recorded.at < 250
111
112
  const run = recorded.run + 1
112
113
  const nav_ = again ? recorded.h : cmd('history-nav', { via: 'click', in: 'shell' })
113
114
  recorded = { hash, at: performance.now(), h: nav_, run }
114
115
  const giveUp = () => { if (recorded.run === run) nav_?.cancel('superseded') }
115
- const parsed = parseHash()
116
+ const parsed = parseHash(hash)
116
117
  const raw = parsed.board === UNPLACED ? {} : parsed // dev's view, and what it names: not here
117
118
  // an old All Scenes link lands on a real board; it, and the bare #/, with no board: the landing one
118
119
  const r = isLegacyLink(raw) ? await landLegacy(raw) : { hash: raw, notice: null }
@@ -10,10 +10,11 @@ import { NOTE_GAP } from '../notes.ts'
10
10
  import { onMotion, startCameraBroadcast, setCameraScale } from './camera-broadcast.ts'
11
11
  import { attachCanvas, recorder } from '../recorder.ts'
12
12
  import { sleepingCount } from './sleep.ts'
13
- import { aimed } from './admission.ts'
13
+ import { aimed, reconsider, wireAdmission } from './admission.ts'
14
14
  import { keepOverResume, resumed, WS } from '../api.ts'
15
15
  import { APP_REOPEN } from '../marver-app.ts'
16
16
  import { TOP } from '../inset.ts'
17
+ import { ZOOM_MAX } from '../../const.ts'
17
18
  import { answerProbesWith } from '../app-perf.ts'
18
19
  import { pick, verify } from '../whiteout-probes.ts'
19
20
 
@@ -124,26 +125,53 @@ function insets(el: HTMLElement) {
124
125
  * zooms with the content, and its pitch re-quantizes in octaves so the on-screen
125
126
  * spacing always lands in [14, 28)px - zooming out doubles the world spacing instead
126
127
  * of dissolving into noise. Alpha fades across the octave so level switches don't pop.
127
- * Painted via CSS vars on the wrapper - no React re-render per frame.
128
+ * Painted via CSS vars - no React re-render per frame.
128
129
  */
129
130
  const GRID = 20
131
+ /** The elements that read the camera's variables: styles.css's readers (test/camera-readers.test.ts holds the two
132
+ * in step) and the inline styles of the selection bar, the group captions and the comment card. Their subtrees
133
+ * inherit the variables; anything else gets its var() default, as play's pins (outside #sh-world) must. */
134
+ const CAMERA_READERS = '.sh-canvas::before, .sh-edge::before, .sh-ctx, #sh-world :is(.sh-node.sel, .sh-node.interact, '
135
+ + '.sh-node.working, .sh-handle, .sh-work-ind, .sh-vbadge, .sh-gcaption, .sh-notes-fold, .sh-stranded, .cm-pin, .cm-lead, '
136
+ + '.cm-stack, .cm-card, .jm-pt, .jm-pickbox)'
137
+ let cameraRule: CSSStyleDeclaration | null | undefined // undefined: not chosen yet; null: inline on .sh-app
138
+ /** Where the camera's variables go. Inline on .sh-app they inherit into every element of the shell, so each tick
139
+ * restyled all of it (628 elements on a 23-frame board, more with every frame). Chromium restyles only what an
140
+ * edited rule matches, so there they go in one rule over the readers (4 elements a tick when nothing is selected).
141
+ * WebKit and Gecko rebuild every style rule of the page on any rule edit, so elsewhere they stay on .sh-app - as
142
+ * they do for good if the stylesheet cannot be made. */
143
+ function cameraStyle(): CSSStyleDeclaration | undefined {
144
+ if (cameraRule === undefined) {
145
+ cameraRule = null
146
+ if ('userAgentData' in navigator) try { // Chromium only
147
+ // constructed, so a page CSP that forbids inline styles cannot block it; a hot update of this module takes
148
+ // over the sheet (and the camera in it) instead of stacking a second, stale one
149
+ const kept: CSSStyleSheet | undefined = import.meta.hot?.data.cameraSheet
150
+ const sheet = kept ?? new CSSStyleSheet()
151
+ sheet.replaceSync(`${CAMERA_READERS} {${kept ? (kept.cssRules[0] as CSSStyleRule).style.cssText : ''}}`)
152
+ if (!kept) document.adoptedStyleSheets = [...document.adoptedStyleSheets, sheet]
153
+ cameraRule = (sheet.cssRules[0] as CSSStyleRule).style
154
+ if (import.meta.hot) import.meta.hot.data.cameraSheet = sheet
155
+ } catch { /* stays inline */ }
156
+ }
157
+ return cameraRule ?? (document.querySelector('.sh-app') as HTMLElement | null)?.style
158
+ }
130
159
  function paintGrid(positionX: number, positionY: number, scale: number) {
131
- // on .sh-app, which the canvas's ::before and the scroll edge (A3.8 #31) both inherit them from - the same element the
132
- // camera's own variables go on every frame, so the style work per frame does not grow
133
- const app = document.querySelector('.sh-app') as HTMLElement | null
134
- if (!app) return
160
+ // the canvas's ::before and the scroll edge (A3.8 #31) paint the grid from these
161
+ const cam = cameraStyle()
162
+ if (!cam) return
135
163
  let step = GRID * scale
136
164
  while (step < 14) step *= 2
137
165
  while (step >= 28) step /= 2
138
166
  const t = (step - 14) / 14
139
- app.style.setProperty('--grid-size', `${step}px ${step}px`)
140
- app.style.setProperty('--grid-pos', `${positionX % step}px ${positionY % step}px`)
141
- app.style.setProperty('--grid-alpha', (0.35 + 0.65 * Math.min(1, t)).toFixed(3))
167
+ cam.setProperty('--grid-size', `${step}px ${step}px`)
168
+ cam.setProperty('--grid-pos', `${positionX % step}px ${positionY % step}px`)
169
+ cam.setProperty('--grid-alpha', (0.35 + 0.65 * Math.min(1, t)).toFixed(3))
142
170
  // screen-space overlays (selection bar) position themselves from these - no re-render per frame
143
- app.style.setProperty('--sh-s', String(scale))
144
- app.style.setProperty('--sh-inv', String(1 / scale)) // world-units-per-screen-px, for zoom-invariant strokes
145
- app.style.setProperty('--sh-tx', `${positionX}px`)
146
- app.style.setProperty('--sh-ty', `${positionY}px`)
171
+ cam.setProperty('--sh-s', String(scale))
172
+ cam.setProperty('--sh-inv', String(1 / scale)) // world-units-per-screen-px, for zoom-invariant strokes
173
+ cam.setProperty('--sh-tx', `${positionX}px`)
174
+ cam.setProperty('--sh-ty', `${positionY}px`)
147
175
  }
148
176
 
149
177
  /**
@@ -235,6 +263,10 @@ export function Canvas() {
235
263
 
236
264
  // B0.4: frame-time sampler + image-LOD camera signal; the recorder hears when the camera stops and what sleeps (spec 28 A1.7)
237
265
  useEffect(() => { startPerf(); startCameraBroadcast(); return attachCanvas({ onMotion, sleeping: sleepingCount }) }, [])
266
+ // what a frame is near may change - the camera at rest, a layout animation's end, a resize, the page shown again, a
267
+ // selection (asked for, it boots): a queue the heap gate parked looks again (admission.ts)
268
+ useEffect(() => wireAdmission(onMotion, window, document), [])
269
+ useEffect(() => useStore.subscribe((s, p) => { if (s.selection !== p.selection) reconsider() }), [])
238
270
  // the pending camera written as the page hides or leaves (A3.8 #43), after the recorder's own listeners
239
271
  useEffect(() => { watchLeave() }, [])
240
272
 
@@ -314,8 +346,10 @@ export function Canvas() {
314
346
  }
315
347
  // a rect on screen now, where it will be when the flight lands: the same world point under the landing transform
316
348
  canvasCtl.landing = (r: DOMRect) => {
317
- const el = wrap(), inst = ref.current
318
- if (!flight || !el || !inst?.instance.animation) return r
349
+ const inst = ref.current
350
+ if (!flight || !inst?.instance.animation) return r // at rest: no lookup (the boot queue asks for every waiting frame)
351
+ const el = wrap()
352
+ if (!el) return r
319
353
  const { positionX, positionY, scale } = inst.instance.transformState
320
354
  const c = el.getBoundingClientRect(), k = flight.scale / scale
321
355
  return new DOMRect(c.left + flight.x + (r.left - c.left - positionX) * k, c.top + flight.y + (r.top - c.top - positionY) * k, r.width * k, r.height * k)
@@ -466,7 +500,7 @@ export function Canvas() {
466
500
  beginGesture(!zooming)
467
501
  if (!zooming) { inst.setTransform(positionX - w.deltaX, positionY - w.deltaY, scale, 0, 'linear'); return }
468
502
  const f = Math.min(1.4, Math.max(1 / 1.4, Math.exp(-w.deltaY * 0.0075 * (CONFIG.zoomSpeed ?? 1))))
469
- const next = Math.min(2, Math.max(0.05, scale * f))
503
+ const next = Math.min(ZOOM_MAX, Math.max(0.05, scale * f))
470
504
  if (next === scale) return
471
505
  const r = canvas.getBoundingClientRect()
472
506
  const cx = w.clientX - r.left, cy = w.clientY - r.top
@@ -1,7 +1,7 @@
1
1
  import { navigatedByHand } from '../goto.ts'
2
2
  import { memo, useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'
3
- import { cap, frameUrl, shownRev, useStore, CONFIG, type Node } from '../store.ts'
4
- import { admit, release } from './admission.ts'
3
+ import { cap, frameById, frameUrl, shownRev, useStore, CONFIG, type Manifest, type Node } from '../store.ts'
4
+ import { admit, readable, release } from './admission.ts'
5
5
  import { canvasCtl } from './ctl.ts'
6
6
  import { CopyIcon, IntentGlyph, ParallelogramFillIcon, ReloadIcon, SlideFrameIcon, XIcon } from '../icons.tsx'
7
7
  import { CommentLayer } from '../Comments.tsx'
@@ -26,6 +26,16 @@ import { cmd, endOnReady, endOnSave, type CmdHandle } from '../commands.ts'
26
26
  export const HEADER = 28
27
27
  const SNAP = 12
28
28
 
29
+ /** The canvas's box, read once per task: the boot queue asks every waiting frame in one pass (admission.ts). */
30
+ let canvasBox: DOMRect | null | undefined
31
+ function canvasRect(): DOMRect | null {
32
+ if (canvasBox === undefined) {
33
+ canvasBox = document.querySelector('.sh-canvas')?.getBoundingClientRect() ?? null
34
+ queueMicrotask(() => { canvasBox = undefined })
35
+ }
36
+ return canvasBox
37
+ }
38
+
29
39
  /** The iframe's box in its node: a frame fills the node; a slide renders at its stage and is
30
40
  * scaled uniformly into the node and centred - resizing a slide node never reflows it. The
31
41
  * identity case carries no transform (no layer, no containing block). */
@@ -54,6 +64,21 @@ function WorkShimmer({ belowBadge }: { belowBadge: boolean }) {
54
64
  )
55
65
  }
56
66
 
67
+ /** A scene note's text and host node, worked out once per board state (nodes, manifest) and scene: every node's selector
68
+ * asks on every store update, and each scanning the board itself cost the square of the board per update. */
69
+ const sceneNotes = new WeakMap<readonly Node[], { manifest: Manifest; of: Map<string, { text?: string; host: string | null }> }>()
70
+ function sceneNoteOf(nodes: readonly Node[], manifest: Manifest, scene: string) {
71
+ let memo = sceneNotes.get(nodes)
72
+ if (memo?.manifest !== manifest) sceneNotes.set(nodes, memo = { manifest, of: new Map() })
73
+ let got = memo.of.get(scene)
74
+ if (!got) {
75
+ const text = manifest.scenes.find((sc) => sc.name === scene)?.note
76
+ got = { text, host: text ? sceneNoteHost(nodes, (id) => frameById(manifest.frames, id)?.scene, scene) : null }
77
+ memo.of.set(scene, got)
78
+ }
79
+ return got
80
+ }
81
+
57
82
  /**
58
83
  * One frame on the canvas. Iframe laws: the iframe element is created once per node key
59
84
  * and never remounted - theme changes go through sh:set-theme, size changes are CSS only.
@@ -82,9 +107,9 @@ export const FrameNode = memo(function FrameNode({ node }: { node: Node }) {
82
107
  // only its column; a pan never re-renders any node (no position subscription here).
83
108
  const sceneNote = useStore((s) => {
84
109
  const scene = frame?.scene
85
- const text = scene ? s.manifest?.scenes.find((sc) => sc.name === scene)?.note : undefined
86
- if (!text) return undefined
87
- return sceneNoteHost(s.nodes, (id) => s.manifest?.frames.find((f) => f.id === id)?.scene, scene!) === node.key ? text : undefined
110
+ if (!scene || !s.manifest) return undefined
111
+ const { text, host } = sceneNoteOf(s.nodes, s.manifest, scene)
112
+ return text && host === node.key ? text : undefined
88
113
  })
89
114
  const notes: NoteSpec[] = []
90
115
  if (frame && sceneNote) notes.push({ kind: 'scene', id: noteId('scene', frame.scene), text: sceneNote })
@@ -117,12 +142,20 @@ export const FrameNode = memo(function FrameNode({ node }: { node: Node }) {
117
142
  // visible first, then by distance to the centre of the canvas (the panel offsets the window's) - where the frame
118
143
  // will be once the camera lands from a fit or zoom on its way (a board's first pick comes as the fit sets off)
119
144
  const rank = () => {
120
- const now = iframeRef.current?.getBoundingClientRect(), c = document.querySelector('.sh-canvas')?.getBoundingClientRect()
145
+ const now = iframeRef.current?.getBoundingClientRect(), c = canvasRect()
121
146
  if (!now || !c) return Infinity
122
147
  const r = canvasCtl.landing(now)
123
148
  const visible = r.right > c.left && r.left < c.right && r.bottom > c.top && r.top < c.bottom
124
149
  return (visible ? 0 : 1e7) + Math.hypot(r.x + r.width / 2 - c.x - c.width / 2, r.y + r.height / 2 - c.y - c.height / 2)
125
150
  }
151
+ // past the heap's line, may it boot (admission.ts readable())? Its iframe as drawn - measured, so a slide fitted onto
152
+ // its stage, a custom size or a frame mid-tidy is what the person sees. Selected: asked for, it boots.
153
+ const near = () => {
154
+ if (useStore.getState().selection.includes(node.key)) return true
155
+ const now = iframeRef.current?.getBoundingClientRect(), c = canvasRect(), s = canvasCtl.transform()?.s
156
+ if (!now || !c || !s) return true
157
+ return readable(canvasCtl.landing(now), c, devicePixelRatio, { width: now.width / s, height: now.height / s })
158
+ }
126
159
  const start = () => {
127
160
  const s = useStore.getState(), n = s.nodes.find((x) => x.key === node.key), f = n && s.frameFor(n)
128
161
  if (!n || !f) { release(node.key); return }
@@ -131,7 +164,7 @@ export const FrameNode = memo(function FrameNode({ node }: { node: Node }) {
131
164
  setSrc(frameUrl(f, n.theme))
132
165
  recorder.admitted(node.key)
133
166
  }
134
- admit({ key: node.key, rank, start })
167
+ admit({ key: node.key, rank, start, near })
135
168
  return () => release(node.key)
136
169
  }, [frame?.id, node.key, node.missing])
137
170
  useEffect(() => { if (node.status !== 'loading') release(node.key) }, [node.status, node.key])
@@ -15,7 +15,24 @@
15
15
  * nearest the centre of the canvas first) on where each frame will be once the camera lands
16
16
  * (canvasCtl.landing) - it need not wait out the fit's ~320 ms flight. With no aim it waits SETTLE, as
17
17
  * long as that flight. A freed slot pumps on the next microtask, ranking again by the view of that moment.
18
+ *
19
+ * The gate is no absolute ceiling: a board with hundreds of frames all readable in view at once still boots them, as on
20
+ * the parent - it holds back only what the person cannot be looking at.
21
+ *
22
+ * Under the heap's line, with or without a gesture, admission is the parent's exactly: a person's pan or zoom stops
23
+ * nothing (holding boots through a gesture was measured and set aside as a candidate for the owner - it trades frames
24
+ * in view arriving about half the pan's length later for a smoother pan: perf/loop/candidates/i10-gesture-hold).
25
+ *
26
+ * Nothing unloads, so a board too heavy for the renderer's heap would boot itself into a crash. Past HEAP_SAFE of the
27
+ * browser's own heap limit (performance.memory, where the browser has it), a frame that is not near the view (its
28
+ * `near`) waits: it boots when the camera comes near it - a gesture's end, an aim, a layout or window change, or at
29
+ * the latest the next look TICK_MS later - like any frame still loading. The gate opens again under HEAP_RESUME. While it
30
+ * is shut and frames wait, it is asked again every TICK_MS whatever else happens (one memory read and one pass over the
31
+ * waiting frames' `near`); the events only make that sooner. A board that stays under the line boots every frame, as
32
+ * before. The boards that change are those whose full load would sit between the gate's lines and the crash line.
18
33
  */
34
+ import { LOD_MIN_PX, ZOOM_MAX } from '../../const.ts'
35
+
19
36
  export const SLOTS = 4
20
37
  /** A new batch's head start: one frame alone until it is done, or until this long - one stalled
21
38
  * first frame must not hold the whole board. */
@@ -25,7 +42,61 @@ let gen = 0 // the batch: a pump scheduled for an earlier one is void
25
42
  let timer: ReturnType<typeof setTimeout> | undefined
26
43
  let settling: ReturnType<typeof setTimeout> | undefined // a pump waiting for the view to settle (SETTLE): aimed() runs it now
27
44
 
28
- export interface Admission { key: string; rank: () => number; start: () => void }
45
+ /**
46
+ * The heap gate's lines, fractions of the browser's own limit (jsHeapSizeLimit), measured in headless Chrome (limit
47
+ * 4,192 MB). The crash: a 733-frame board killed the renderer at 97% of it, its boots halving their pace past ~93% (a
48
+ * page that only allocates died at 87%). A load's own transient: the heaviest board that fits (272 frames) peaks at 69%
49
+ * while it loads and settles at 50% - 19 points of garbage on top of its live heap. Shut at 0.75, reopened under 0.60,
50
+ * the parked 733-frame board comes to rest at 61-65%, and each approach to its parked frames (2-9 near frames) adds
51
+ * ~1-2 points live, up to ~5 transient: room for one load-sized transient on top of the rest, and some 30 approaches
52
+ * before the 97% line. Narrower lines (0.79/0.77) left that board at 81% and six approaches took it to 88% - less room
53
+ * than one transient; a crash is the worst outcome, a board that stops short and boots the rest on approach the mild one.
54
+ *
55
+ * Changed, against the parent: a board whose live heap after loading would exceed ~60% of the limit (~2.5 GB here,
56
+ * ~1.2 GB at a 2 GB limit) stops there and boots the rest as the camera approaches. One that only spikes past 0.75 while
57
+ * it loads and settles under 0.60 finishes on its own: the next look (TICK_MS) after a collection reopens the gate. One
58
+ * that plateaus between the lines stays parked: its far frames boot on approach. Under 0.75, nothing changes.
59
+ */
60
+ export const HEAP_SAFE = 0.75
61
+ export const HEAP_RESUME = 0.6
62
+ /** While the gate is shut and frames wait: how often it is asked again, whatever else happens. One look reads every
63
+ * waiting frame's iframe as drawn (getBoundingClientRect, one canvas rect per pass): 6.0-6.9 ms on the parked 733-frame
64
+ * archive (~460 waiting), about 11 ms per 5 s - and only on a board the gate has parked. */
65
+ export const TICK_MS = 3000
66
+ /** Two changes of the reading known to lie within this window prove it precise (see heapGated). */
67
+ const PRECISE_MS = 60_000
68
+ let gated = false // past HEAP_SAFE: only near frames start, until a reading under HEAP_RESUME
69
+ let precise = false // the page's reading has been seen to move twice within PRECISE_MS: it is exact
70
+ let memLast: number | undefined // the last usedJSHeapSize read
71
+ let readAt = -Infinity // when admission last read it
72
+ let changeFrom = -Infinity // the earliest the last change seen can have happened: the read before it
73
+ let tick: ReturnType<typeof setTimeout> | undefined
74
+ let epoch = 0 // resetAdmission's: a collection's callback from before it does nothing
75
+ let watching = false // a collection will pump the queue (sooner than the tick)
76
+ const collected = typeof FinalizationRegistry === 'function'
77
+ ? new FinalizationRegistry<number>((e) => { if (e !== epoch) return; watching = false; if (gated && waiting.size) schedule(0) })
78
+ : null
79
+
80
+ /** A readable frame's smaller side on screen, device px: 16 CSS px at a 2x display - about one line of text; a strip
81
+ * thinner than that shows nothing to read whatever its length. */
82
+ const STRIP_MIN_PX = 32
83
+ /** Past the heap's line, may a frame boot? Its iframe on screen where the camera lands (r), against the canvas (c): in
84
+ * view or within half a screen of it (updates.ts's margin), and large enough to be read on both sides - the larger at
85
+ * least image-LOD's smallest decode width (LOD_MIN_PX device px), the smaller at least STRIP_MIN_PX - each bar capped at
86
+ * what the ordinary camera can make of that side (its world size, `world`, at ZOOM_MAX), so every frame stays reachable
87
+ * by moving the camera to it. A thumbnail on a zoomed-out board waits until the camera comes closer. */
88
+ export function readable(r: Box, c: Box, dpr: number, world: { width: number; height: number }): boolean {
89
+ const k = Math.min(dpr || 1, 2), mx = c.width / 2, my = c.height / 2
90
+ const big = Math.max(r.width, r.height) * k, small = Math.min(r.width, r.height) * k
91
+ const reach = (side: number) => side * ZOOM_MAX * k - 0.5
92
+ return big >= Math.min(LOD_MIN_PX - 0.5, reach(Math.max(world.width, world.height)))
93
+ && small >= Math.min(STRIP_MIN_PX - 0.5, reach(Math.min(world.width, world.height)))
94
+ && r.right > c.left - mx && r.left < c.right + mx && r.bottom > c.top - my && r.top < c.bottom + my
95
+ }
96
+ type Box = { left: number; right: number; top: number; bottom: number; width: number; height: number }
97
+
98
+ /** `near`: in view or close to it, where the camera will land - a frame that may boot whatever the heap. Absent: always. */
99
+ export interface Admission { key: string; rank: () => number; start: () => void; near?: () => boolean }
29
100
 
30
101
  const waiting = new Map<string, Admission>()
31
102
  const active = new Set<string>()
@@ -36,7 +107,7 @@ let scheduled = false
36
107
  export function admit(a: Admission): void {
37
108
  if (active.has(a.key)) return
38
109
  if (!waiting.size && !active.size) { // a new batch
39
- primed = false; gen++; scheduled = false; clearTimeout(timer); clearTimeout(settling); settling = undefined
110
+ primed = false; gen++; scheduled = false; gated = false; clearTimeout(timer); clearTimeout(settling); settling = undefined
40
111
  timer = setTimeout(() => { primed = true; schedule(0) }, HEAD_MS)
41
112
  }
42
113
  waiting.set(a.key, a)
@@ -50,11 +121,16 @@ const SETTLE = 350
50
121
  * restored (Canvas.tsx). A pump waiting for the view to settle runs now: its ranks read where each frame will be once
51
122
  * the camera lands (canvasCtl.landing), so the first pick is the one SETTLE would have made, a flight earlier. */
52
123
  export function aimed(): void {
53
- if (settling === undefined) return
124
+ if (settling === undefined) { if (gated && waiting.size) schedule(0); return }
54
125
  clearTimeout(settling); settling = undefined; scheduled = false
55
126
  schedule(0)
56
127
  }
57
128
 
129
+ /** What a frame is near may have changed - the camera came to rest, a layout animation ended, the window was resized, the
130
+ * page was shown again: while the heap gate is shut, the queue is looked at again (a frame it keeps may be near now).
131
+ * Under the line it does nothing - admission there is the parent's. */
132
+ export function reconsider(): void { if (gated && waiting.size) schedule(0) }
133
+
58
134
  /** The frame is done booting (ready, error, gone, or its watchdog took over): free the slot, or
59
135
  * leave the queue if it never started. */
60
136
  export function release(key: string): void {
@@ -76,11 +152,47 @@ function schedule(ms: number): void {
76
152
  if (ms) settling = setTimeout(() => { settling = undefined; run() }, ms); else queueMicrotask(run)
77
153
  }
78
154
 
155
+ /**
156
+ * Is the heap gate shut? Only on a reading it can trust. Chromium gives performance.memory exact only to a process locked
157
+ * to one site (cached 50 ms); elsewhere it is bucketed and refreshed at most once every twenty minutes (blink's
158
+ * memory_info.cc). Precision is the process's, so it is proven once: two changes of the reading within PRECISE_MS - a
159
+ * load moves an exact counter at every boot; a bucketed one changes once per twenty minutes, never twice in a minute.
160
+ * Until then - and for good where the reading is bucketed - the gate stays open and the queue runs as it always did. A
161
+ * proven reading is trusted even when it holds still (nothing allocated). Never where the browser does not say (Safari,
162
+ * Firefox).
163
+ */
164
+ function heapGated(): boolean {
165
+ const m = (performance as { memory?: { usedJSHeapSize: number; jsHeapSizeLimit: number } }).memory
166
+ if (!m || !(m.jsHeapSizeLimit > 0)) return (gated = false)
167
+ const now = performance.now(), used = m.usedJSHeapSize
168
+ // a change seen now happened after the read before it: two changes prove a fast counter only if both lie, for sure,
169
+ // inside PRECISE_MS - from the earlier one's lower bound to now. A gap in admission's own reads (the queue empty while
170
+ // another reader, or time, refreshed Chromium's shared sample) proves nothing.
171
+ if (memLast !== undefined && used !== memLast) { if (now - changeFrom < PRECISE_MS) precise = true; changeFrom = readAt }
172
+ memLast = used; readAt = now
173
+ if (!precise) return (gated = false)
174
+ if (used > HEAP_SAFE * m.jsHeapSizeLimit) gated = true
175
+ else if (used < HEAP_RESUME * m.jsHeapSizeLimit) gated = false
176
+ return gated
177
+ }
178
+
79
179
  function pump(): void {
80
180
  scheduled = false
181
+ clearTimeout(tick); tick = undefined
182
+ if (!waiting.size) return
183
+ const high = heapGated() // every pump reads it: an exact counter proves itself within a load's first boots
81
184
  while (active.size < (primed ? SLOTS : 1) && waiting.size) {
82
185
  let best: Admission | undefined, bestRank = Infinity
83
- for (const a of waiting.values()) { const r = a.rank(); if (r < bestRank || !best) { best = a; bestRank = r } }
186
+ for (const a of waiting.values()) {
187
+ if (high && a.near && !a.near()) continue
188
+ const r = a.rank(); if (r < bestRank || !best) { best = a; bestRank = r }
189
+ }
190
+ if (!best) { // parked: asked again at the next tick at the latest, sooner on a collection
191
+ const g = gen
192
+ tick = setTimeout(() => { tick = undefined; if (g === gen) pump() }, TICK_MS)
193
+ if (collected && !watching) { watching = true; collected.register({}, epoch) }
194
+ return
195
+ }
84
196
  waiting.delete(best!.key)
85
197
  active.add(best!.key)
86
198
  ;(globalThis as { __mvAdmitted?: string[] }).__mvAdmitted?.push(best!.key) // diagnostic: the order, when a probe asks for it
@@ -89,4 +201,25 @@ function pump(): void {
89
201
  }
90
202
 
91
203
  /** For tests: nothing queued, nothing active. */
92
- export function resetAdmission(): void { waiting.clear(); active.clear(); primed = false; scheduled = false; gen++; clearTimeout(timer); clearTimeout(settling); settling = undefined }
204
+ export function resetAdmission(): void { waiting.clear(); active.clear(); primed = false; scheduled = false; gen++; clearTimeout(timer); clearTimeout(settling); settling = undefined; clearTimeout(tick); tick = undefined; gated = false; precise = false; memLast = undefined; readAt = -Infinity; changeFrom = -Infinity; watching = false; epoch++ }
205
+
206
+ /** A hot-replaced module leaves nothing of its own behind: no timer, and no pump already queued (its batch is void). */
207
+ export function disposeAdmission(): void {
208
+ clearTimeout(timer); clearTimeout(settling); settling = undefined; clearTimeout(tick); tick = undefined
209
+ gen++; scheduled = false; epoch++
210
+ }
211
+ if (import.meta.hot) import.meta.hot.dispose(disposeAdmission)
212
+
213
+ /** Canvas.tsx's wiring, in one place (tested): what a frame is near changing - the camera at rest, a layout animation's
214
+ * end, a resize, the page shown again (a hidden page's timers run once a minute) - looks again. Returns the unwiring. */
215
+ export function wireAdmission(
216
+ onMotion: (fn: (m: { camera: boolean; preset: boolean }) => void) => () => void,
217
+ win: Pick<EventTarget, 'addEventListener' | 'removeEventListener'>,
218
+ doc: Pick<EventTarget, 'addEventListener' | 'removeEventListener'> & { visibilityState: string },
219
+ ): () => void {
220
+ const off = onMotion((m) => { if (!m.camera && !m.preset) reconsider() })
221
+ const shown = () => { if (doc.visibilityState === 'visible') reconsider() }
222
+ win.addEventListener('resize', reconsider)
223
+ doc.addEventListener('visibilitychange', shown)
224
+ return () => { off(); win.removeEventListener('resize', reconsider); doc.removeEventListener('visibilitychange', shown) }
225
+ }