@marver-design/marver 0.33.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 (39) hide show
  1. package/CHANGELOG.md +57 -0
  2. package/README.md +1 -1
  3. package/dist/{anchor-check-KCe6WeRA.mjs → anchor-check-DREwCQiE.mjs} +1 -1
  4. package/dist/{build-4-k2XhhX.mjs → build-3AH123fe.mjs} +3 -3
  5. package/dist/cli.mjs +5 -8
  6. package/dist/{comments-C2SN1QdM.mjs → comments-C7NjFGgl.mjs} +14 -7
  7. package/dist/{daemon-CCDgagw2.mjs → daemon-BE-t9iU-.mjs} +2 -4
  8. package/dist/{dev-CJf5upVK.mjs → dev-Dw6mcoP8.mjs} +7 -7
  9. package/dist/{notes-CRAX4wgk.mjs → notes-CmfQ9604.mjs} +13 -4
  10. package/dist/{pdf-GGya_nI6.mjs → pdf-CkE4Ir2P.mjs} +3 -3
  11. package/dist/{plugin-Cm74UDfp.mjs → plugin-C6jEpbCx.mjs} +43 -34
  12. package/dist/{poster-BnuT9UyW.mjs → poster-d10h73z0.mjs} +1 -1
  13. package/dist/{publish-bakes-zHmPEOB5.mjs → publish-bakes-weNQnNqE.mjs} +2 -2
  14. package/dist/{recover-BpRQxBA7.mjs → recover-Dekpav7b.mjs} +1 -1
  15. package/dist/{shot-HZtclbOT.mjs → shot-Ct2FiEbu.mjs} +2 -2
  16. package/docs/boards-and-folders.md +1 -1
  17. package/docs/performance.md +4 -0
  18. package/docs/slides.md +8 -0
  19. package/package.json +1 -1
  20. package/src/client/const.ts +5 -0
  21. package/src/client/content/img-lod.ts +3 -1
  22. package/src/client/frame-host/inplace.ts +43 -0
  23. package/src/client/frame-host/main.tsx +10 -1
  24. package/src/client/shell/App.tsx +26 -18
  25. package/src/client/shell/LockedApp.tsx +6 -5
  26. package/src/client/shell/canvas/Canvas.tsx +50 -16
  27. package/src/client/shell/canvas/FrameNode.tsx +40 -7
  28. package/src/client/shell/canvas/admission.ts +138 -5
  29. package/src/client/shell/canvas/sleep.ts +258 -26
  30. package/src/client/shell/hash.ts +24 -0
  31. package/src/client/shell/jam-capture.ts +3 -2
  32. package/src/client/shell/notes.ts +11 -4
  33. package/src/client/shell/recorder.ts +1 -1
  34. package/src/client/shell/store.ts +63 -11
  35. package/templates/AGENTS-embedded.md +3 -3
  36. package/templates/AGENTS-studio.md +3 -3
  37. package/templates/instructions/iterate.md +1 -1
  38. package/templates/instructions/reference/deck-replicate.md +44 -0
  39. package/templates/instructions/slides.md +8 -0
@@ -105,7 +105,7 @@ resolving each one by hand - Jam's questions, reviews and failed runs on them ar
105
105
  live work: a thread Jam is queued or working on is left open and counted ("2 left open: work in
106
106
  progress"). The notice says how many, with **Undo**: it reopens each thread nothing happened in since - no
107
107
  reply, edit, reaction, resolve or reopen ("1 changed since - left as is"); what Jam finished stays finished. From the terminal: `npx marver
108
- comments resolve --all --board <b>` (`--folder`, `--scene`, `--canvas`, `--dry-run`), then `--undo <op>`
108
+ comments resolve --all --board <b>` (`--folder`, `--scene`, `--frame`, `--canvas`, `--dry-run`), then `--undo <op>`
109
109
  with the op it prints. Missed the notice's Undo (it shows for 10 seconds)? Every run is kept as
110
110
  `design/.local/comment-ops/<op>.json` (its `scope` and `at` say which), and `npx marver comments resolve --undo <op>`
111
111
  undoes it. On the board you have open, it saves your latest edits first; while they are not saved it resolves nothing
@@ -162,6 +162,10 @@ Read the load, name the lever, change it, compare the next load - you, or your a
162
162
  file was deleted or renamed.
163
163
  - **The weight** (`settled.weight`) says how heavy the settled board is: elements in the page and its
164
164
  frames, frames awake and asleep, the heap.
165
+ - **A board too heavy for one tab** (in Chrome and the Mac app, which report the heap): past three quarters of the
166
+ tab's memory limit the canvas starts no more frames on its own. A frame you can read on screen - or select - still
167
+ starts within a few seconds, and the rest follow once memory is back under 60%. The board stays open where it used
168
+ to crash; frames not yet started show their placeholder. The lasting fix is still a smaller board: split it.
165
169
  - **Late moves** came after the load ended - settled, or cut. After a cut at 120 s, or while the page was
166
170
  hidden, they are the board still loading. After it settled - and any **`unknown`** move, with no cause
167
171
  named - they say something moved the board after it looked done: worth a look, or an
package/docs/slides.md CHANGED
@@ -89,6 +89,14 @@ same from the canvas, and `--notes` prints a handout with each slide's notes. Gl
89
89
  soft shadows - the effects Chrome prints wrong - are fixed slide by slide and checked against the screen. See
90
90
  [Deck PDFs](pdf.md).
91
91
 
92
+ ## A deck in another presentation tool
93
+
94
+ Ask your agent to replicate the deck in Google Slides, PowerPoint, Keynote, Canva or any presentation tool it can
95
+ drive through a good MCP or API. It rebuilds every slide there from the tool's native components, one element at a
96
+ time (every text a text box, every shape a shape, every line a line, every image an image) so anyone can edit it and
97
+ work on it together. It never pastes pictures of slides. It anchors each text box to the middle so the text lines up
98
+ as on the slide, checks each rebuilt slide against the original, and tells you anything it could not rebuild natively.
99
+
92
100
  ## Motion
93
101
 
94
102
  Motion is yours to write. While a deck plays, the stage puts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@marver-design/marver",
3
- "version": "0.33.0",
3
+ "version": "0.35.0",
4
4
  "description": "The agent-native design canvas. A design/ folder, one command, a canvas of live frames built from your repo's real components - comment @marver and your own coding agent does the work. The tool ships no AI.",
5
5
  "type": "module",
6
6
  "private": false,
@@ -7,6 +7,11 @@ export const ROUTE = '/__mv'
7
7
  /** Content-frame natural widths: Doc layout -> own-size width.
8
8
  * Shared by the Doc primitive (measurement messages) and the server-side
9
9
  * manifest scan (defaultSize for content frames) - one source, no drift. */
10
+ /** Image-LOD's smallest decode width, in device px (content/img-lod.ts's first bucket): under it a frame on screen is a
11
+ * thumbnail - the heap gate's "too small to be read" (canvas/admission.ts) uses the same line. */
12
+ export const LOD_MIN_PX = 256
13
+ /** The ordinary camera's closest zoom: a wheel or pinch (Canvas.tsx) and the zoom menu's top preset. */
14
+ export const ZOOM_MAX = 2
10
15
  export const CONTENT_WIDTH: Record<string, number> = { document: 760, wide: 1280 }
11
16
 
12
17
  /** The default slide stage: 16:9 at 1280×720, deliberately NOT a config viewport - no
@@ -11,6 +11,8 @@
11
11
  // never triggers a decode/resample storm. Crisp at rest, cheap in motion. This mirrors how tldraw does
12
12
  // LOD (resolution by on-screen size, debounced so it never thrashes mid-zoom).
13
13
 
14
+ import { LOD_MIN_PX } from '../const.ts'
15
+
14
16
  /** Feature probe: createImageBitmap with resize + a canvas bitmaprenderer that can receive it. */
15
17
  export const lodSupported = (() => {
16
18
  try {
@@ -22,7 +24,7 @@ export const lodSupported = (() => {
22
24
 
23
25
  // Quantized resize widths (device px). A `want` above the top bucket decodes at NATIVE (bucket 0 = no
24
26
  // resize), reached only when a frame is zoomed in past ~2048 on-screen device px.
25
- const BUCKETS = [256, 640, 1280, 2048]
27
+ const BUCKETS = [LOD_MIN_PX, 640, 1280, 2048]
26
28
  const DPR = (): number => Math.min(window.devicePixelRatio || 1, 2) // cap at 2; 3x buys nothing here
27
29
 
28
30
  // Bounded decode pool: never run more than N createImageBitmap jobs at once (peak decode memory + CPU).
@@ -122,3 +122,46 @@ export function watchInplace(hot: { on(event: string, cb: (p: any) => void): voi
122
122
  } catch { /* the same */ }
123
123
  })
124
124
  }
125
+
126
+ // ---- element stacks while modules load (item 9) --------------------------------------------------------------
127
+ // here rather than in a module of its own: one module fewer for every frame document to fetch
128
+ /**
129
+ * React's development build gives each element it makes a debug stack and a console task (an `Error` and a
130
+ * `console.createTask`), up to 10,000 a second, counted on its shared internals (`recentlyCreatedOwnerStacks`; the
131
+ * renderer gives the budget back at most once a second). An element a module makes as it LOADS - an icon library's
132
+ * hoisted glyphs: phosphor makes one per weight, six per icon, for the whole barrel - has no owner, and its stack would
133
+ * name the import chain. On a heavy frame those were a quarter of a second and megabytes of every document (measured,
134
+ * item 9: `createElement` was 25 s of a 112-frame board's 44).
135
+ *
136
+ * While the frame's own modules evaluate, the budget reads as spent - the path React itself takes past its limit: the
137
+ * element shares React's "unknown owner" stack and task. After, the count is put back where it was, as if those
138
+ * elements had never been counted: a render's elements get their stacks as they would on a frame without them - never
139
+ * fewer than before (a load of thousands of glyphs used to spend the budget before the first render, when it finished
140
+ * inside React's one-second reset). A React without the counter (a production build, React 18, 19.0) is left as it is.
141
+ *
142
+ * Held only while the frame host BOOTS (main.tsx): no root of the frame host exists yet, so no render of its own can
143
+ * make an element in the window. A renderer reset during the hold (React's, at most once a second, when it prepares a
144
+ * render) simply ends it early. One case it does not tell apart: a module that mounts a React root of its own while the
145
+ * frame is still loading - that root's elements made in the window share the stack too. Never held around an update
146
+ * applied in place: a root renders meanwhile, and Vite sends no vite:afterUpdate when a dispose or accept callback throws.
147
+ */
148
+ const INTERNALS = '__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE'
149
+ /** Far past any limit React uses, so no element made during the hold is given a stack. */
150
+ const SPENT = 2 ** 40
151
+
152
+ /** Hold React's element stacks; the function returned gives the count back. Call it once, after the modules loaded. */
153
+ export function holdElementStacks(react: object): () => void {
154
+ const internals = (react as Record<string, unknown>)[INTERNALS] as { recentlyCreatedOwnerStacks?: unknown } | undefined
155
+ if (!internals || typeof internals.recentlyCreatedOwnerStacks !== 'number') return () => {}
156
+ const was = internals.recentlyCreatedOwnerStacks
157
+ internals.recentlyCreatedOwnerStacks = SPENT
158
+ let given = false
159
+ return () => {
160
+ if (given) return
161
+ given = true
162
+ const now = internals.recentlyCreatedOwnerStacks
163
+ // the renderer set it back meanwhile (a render during the hold, which ended it): its count is the true one
164
+ if (typeof now !== 'number' || now < SPENT) return
165
+ internals.recentlyCreatedOwnerStacks = was
166
+ }
167
+ }
@@ -3,6 +3,7 @@
3
3
  * Boot failures (theme, providers, layouts, the frame itself) render a plain-DOM error card
4
4
  * and post sh:error; an ErrorBoundary catches render-time throws the same way.
5
5
  */
6
+ import * as React from 'react'
6
7
  import { Component, createElement, Profiler, useLayoutEffect, type ReactNode } from 'react'
7
8
  import { createRoot } from 'react-dom/client'
8
9
 
@@ -11,7 +12,7 @@ import { frameRenders } from './signals.js'
11
12
  import { frameFile, frames, layoutChain, layouts, providers } from './registry.ts'
12
13
  import { SLIDE_DOC_CSS } from '../const.ts'
13
14
  import { fullRecorder } from '../recorder-level.ts'
14
- import { rootCommitted, watchInplace } from './inplace.ts'
15
+ import { holdElementStacks, rootCommitted, watchInplace } from './inplace.ts'
15
16
 
16
17
  const params = new URLSearchParams(location.search)
17
18
  const id = params.get('id') ?? ''
@@ -82,7 +83,12 @@ function Committed({ onCommit, children }: { onCommit: () => void; children?: Re
82
83
 
83
84
  async function boot() {
84
85
  const phases: Record<string, number> = { boot: Math.round(performance.now()) } // ms since navigation: where a boot spends its time (research/hifi/bootscale.ts)
86
+ // the elements the theme, the frame and its wrappers make as they load get no debug stack each (inplace.ts,
87
+ // holdElementStacks): no root of ours exists yet, so no render of ours can make an element in the window. Updates
88
+ // applied in place later are NOT held - a root renders meanwhile, and Vite skips vite:afterUpdate when a callback throws
89
+ let giveStacks = () => {}
85
90
  try {
91
+ giveStacks = holdElementStacks(React)
86
92
  await import('virtual:sh-theme' as string)
87
93
  phases.theme = Math.round(performance.now())
88
94
 
@@ -113,6 +119,7 @@ async function boot() {
113
119
  for (const lk of layoutChain(fileKey)) wrappers.push((await layouts[lk]() as any).default)
114
120
 
115
121
  phases.wrappers = Math.round(performance.now())
122
+ giveStacks()
116
123
  let tree: ReactNode = createElement(Frame)
117
124
  for (const W of wrappers.reverse()) if (W != null) tree = createElement(W, null, tree)
118
125
 
@@ -126,6 +133,8 @@ async function boot() {
126
133
  createRoot(document.getElementById('root')!).render(onRender ? createElement(Profiler, { id: 'frame', onRender }, app) : app)
127
134
  } catch (err) {
128
135
  fail((err as Error).message, err)
136
+ } finally {
137
+ giveStacks()
129
138
  }
130
139
  }
131
140
 
@@ -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])