@marver-design/marver 0.26.0 → 0.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/CHANGELOG.md +158 -0
  2. package/README.md +10 -5
  3. package/dist/{anchor-check-Dg5xpNnU.mjs → anchor-check-ChdDqL5z.mjs} +1 -1
  4. package/dist/{audio-CmSRYFEs.mjs → audio-Dw1lfMdb.mjs} +14 -0
  5. package/dist/{bake-DtVlm0_F.mjs → bake-DM_uWgAA.mjs} +1 -1
  6. package/dist/{boards-DYG22tOe.mjs → boards-DlTcpF47.mjs} +1 -1
  7. package/dist/{build-C_gUgcdC.mjs → build-DZnFysGU.mjs} +4 -4
  8. package/dist/{capture-CrqvU_jh.mjs → capture-vadKjuCo.mjs} +2 -1
  9. package/dist/cli.mjs +28 -16
  10. package/dist/{comments-BqXua-XL.mjs → comments-DxOkCSNE.mjs} +4 -4
  11. package/dist/{daemon-DZo6o3rU.mjs → daemon-BSA0lV8d.mjs} +400 -274
  12. package/dist/detect-C0wpaePX.mjs +125 -0
  13. package/dist/dev-eQJhWsqg.mjs +1273 -0
  14. package/dist/dev-lock-C_FC70Mu.mjs +65 -0
  15. package/dist/exclusive-B1RtpeeP.mjs +150 -0
  16. package/dist/{init-D8DtrK_F.mjs → init-COD0x48i.mjs} +5 -3
  17. package/dist/{link-BNzLvdhI.mjs → link-DDXZVGtv.mjs} +20 -8
  18. package/dist/ls-D7O1G505.mjs +38 -0
  19. package/dist/{marks-NQi0wZJ4.mjs → marks-CWM3WJjc.mjs} +1 -1
  20. package/dist/perf-BWzQwZqj.mjs +369 -0
  21. package/dist/perf-BoDSkbEb.mjs +429 -0
  22. package/dist/perf-jam-D55U3FZK.mjs +242 -0
  23. package/dist/{plugin-CTD0rydA.mjs → plugin-C-E7omsh.mjs} +425 -66
  24. package/dist/{poster-ChjXGTS5.mjs → poster-Bx83ZYVK.mjs} +2 -1
  25. package/dist/{profile-WU9qcbIo.mjs → profile-Bh5Y5zpW.mjs} +1 -1
  26. package/dist/{publish-bakes-CEP_2NRc.mjs → publish-bakes-aljgm45S.mjs} +2 -2
  27. package/dist/{queue-BuiCKSX1.mjs → queue-CAM_vNmX.mjs} +3 -3
  28. package/dist/recover-t9Pno3u9.mjs +66 -0
  29. package/dist/{session-qZWKt_VA.mjs → session-BAaJsK5c.mjs} +1 -1
  30. package/dist/{share--oFJ1bCI.mjs → share-W5H3BNvP.mjs} +1 -1
  31. package/dist/shot-DoHLl6ig.mjs +139 -0
  32. package/dist/{shot-DqcxJibP.mjs → shot-LFhC-WYD.mjs} +343 -19
  33. package/dist/slots-DCDo3N0x.mjs +471 -0
  34. package/dist/speech-worker.mjs +40 -5
  35. package/dist/{sync-DKk-yT1V.mjs → sync-BQVlHZpx.mjs} +4 -3
  36. package/dist/{work-F5u-twpJ.mjs → work-Bp1p39kq.mjs} +4 -2
  37. package/dist/{work-VvX_JIgl.mjs → work-BroFwnup.mjs} +4 -2
  38. package/docs/boards-and-folders.md +3 -1
  39. package/docs/jam-session.md +78 -7
  40. package/docs/live-jam.md +8 -0
  41. package/docs/performance.md +262 -0
  42. package/package.json +2 -2
  43. package/src/client/content/index.tsx +3 -0
  44. package/src/client/content/video.tsx +6 -2
  45. package/src/client/frame-host/bridge.js +22 -6
  46. package/src/client/frame-host/inspect.js +8 -3
  47. package/src/client/frame-host/keys.js +6 -2
  48. package/src/client/frame-host/main.tsx +17 -5
  49. package/src/client/shell/App.tsx +188 -29
  50. package/src/client/shell/BoardList.tsx +5 -5
  51. package/src/client/shell/Comments.tsx +3 -2
  52. package/src/client/shell/JamSurface.tsx +13 -5
  53. package/src/client/shell/LockedApp.tsx +5 -5
  54. package/src/client/shell/Play.tsx +27 -15
  55. package/src/client/shell/Toolbar.tsx +17 -5
  56. package/src/client/shell/api.ts +206 -0
  57. package/src/client/shell/canvas/Canvas.tsx +30 -3
  58. package/src/client/shell/canvas/FrameNode.tsx +15 -5
  59. package/src/client/shell/canvas/admission.ts +8 -1
  60. package/src/client/shell/canvas/camera-broadcast.ts +15 -5
  61. package/src/client/shell/canvas/ctl.ts +2 -0
  62. package/src/client/shell/canvas/frame-registry.ts +28 -2
  63. package/src/client/shell/canvas/sleep.ts +4 -1
  64. package/src/client/shell/comments-store.ts +12 -4
  65. package/src/client/shell/goto.ts +22 -10
  66. package/src/client/shell/icons.tsx +2 -0
  67. package/src/client/shell/jam-capture.ts +96 -16
  68. package/src/client/shell/jam-keys.ts +51 -18
  69. package/src/client/shell/jam-lane.tsx +46 -5
  70. package/src/client/shell/jam-panel.tsx +66 -13
  71. package/src/client/shell/jam-queue.ts +3 -3
  72. package/src/client/shell/jam-session.tsx +14 -8
  73. package/src/client/shell/jam-state.ts +48 -6
  74. package/src/client/shell/jam-surface-parts.tsx +10 -6
  75. package/src/client/shell/jam-voice.ts +7 -5
  76. package/src/client/shell/legacy-links.ts +2 -2
  77. package/src/client/shell/main.tsx +4 -0
  78. package/src/client/shell/notes.ts +8 -1
  79. package/src/client/shell/perf.ts +69 -58
  80. package/src/client/shell/recorder-core.ts +183 -0
  81. package/src/client/shell/recorder.ts +565 -0
  82. package/src/client/shell/store.ts +268 -103
  83. package/src/client/shell/styles.css +54 -9
  84. package/src/client/stage/main.tsx +2 -0
  85. package/templates/AGENTS-embedded.md +22 -4
  86. package/templates/AGENTS-studio.md +22 -4
  87. package/templates/demo/dark.tsx +1 -1
  88. package/templates/demo/welcome.tsx +1 -1
  89. package/templates/instructions/jam.md +5 -3
  90. package/templates/instructions/welcome.md +6 -3
  91. package/dist/config-Cf7EjAMf.mjs +0 -292
  92. package/dist/dev-_Nlsc6v9.mjs +0 -742
  93. package/dist/dev-lock-DWSpa6nj.mjs +0 -179
  94. package/dist/perf-D6VmmJ2q.mjs +0 -68
  95. package/dist/perf-DPbLGhhO.mjs +0 -49
  96. package/dist/shot-CNbHoZ6H.mjs +0 -86
@@ -16,15 +16,17 @@ import { jamKey } from './jam-keys.ts'
16
16
  import { letGoOfTile } from './jam-state.ts'
17
17
  import { JamButton } from './jam-session.tsx'
18
18
  import { useEffect, useRef, useState } from 'react'
19
- import { useStore, BOARD_POLICY, BRANDING, CONFIG, PUBLISHED, SOURCE_REVEALED, boardLabel, boardLocked, cap, fetchBoardNames, modeAllowed, playsAsSlides, SLIDE_INTRINSIC, type Node } from './store.ts'
19
+ import { useStore, BOARD_POLICY, BRANDING, CONFIG, PUBLISHED, SOURCE_REVEALED, boardLabel, boardLocked, cap, fetchBoardNames, modeAllowed, playsAsSlides, SLIDE_INTRINSIC, stoppedFor, type Node } from './store.ts'
20
20
  import { deckOrder } from './play-order.ts'
21
21
  import { NO_COMMENTS_HERE, useComments } from './comments-store.ts'
22
22
  import { UNPLACED } from './hash.ts'
23
23
  import { isNoteAnchor } from './notes.ts'
24
24
  import { ROUTE, slideSize } from '../const.ts'
25
+ import { stranded, withWs } from './api.ts'
25
26
  import { poweredByUrl } from '../../shared/utm.ts'
26
27
  import { canvasCtl } from './canvas/ctl.ts'
27
- import { revealFrame } from './goto.ts'
28
+ import { recorder } from './recorder.ts'
29
+ import { revealFrame, switchFor } from './goto.ts'
28
30
  import { Tip } from './Tip.tsx'
29
31
  import { keyAllowed } from '../frame-host/keys.js'
30
32
  import { CommentButton, DevicePicker, HideUIButton, isHideUI, LaserButton, Popover, ThemePicker, toggleHideUI, usePopover } from './Toolbar.tsx'
@@ -147,8 +149,9 @@ async function switchPlayBoard(name: string) {
147
149
  const s = useStore.getState()
148
150
  if (name === s.board) return
149
151
  const device = s.play?.device // the device is the viewer's choice - it survives the switch
150
- await s.switchBoard(name)
151
- if (useStore.getState().board !== name) return
152
+ // a navigation like any other: a link still reading its board gives way to it, and it to a newer one - which then
153
+ // has the board, the stage and the camera
154
+ if (!await switchFor(name)) return
152
155
  const dev = device && device !== 'slide' ? { device } : undefined // the deck's own size does not follow to a prototype
153
156
  if (playsAsSlides(name)) enterSlides(device ? { device } : undefined)
154
157
  else enterPlay(dev)
@@ -305,10 +308,12 @@ function PlayInner() {
305
308
  const slParams = (p: { slides?: boolean }) => p.slides
306
309
  ? `&slides=1${BOARD_POLICY[useStore.getState().board]?.transition === 'none' ? '&tr=none' : ''}`
307
310
  : ''
308
- const src = useRef(play ? `${ROUTE}/stage/?at=${encodeURIComponent(play.at)}&theme=${encodeURIComponent(play.theme)}${slParams(play)}` : '')
311
+ // the stage runs the project's frames: its URL names the workspace like a frame's (A1.11)
312
+ const src = useRef(play ? withWs(`${ROUTE}/stage/?at=${encodeURIComponent(play.at)}&theme=${encodeURIComponent(play.theme)}${slParams(play)}`) : '')
309
313
  const [win, setWin] = useState({ w: window.innerWidth, h: window.innerHeight })
310
314
  const [pillOpen, setPillOpen] = useState(true) // collapse (pill -> re-open fab), like the canvas
311
315
  const [stageReady, setStageReady] = useState(0) // bumps on each sh:stage-ready (reload) - re-drives the highlight
316
+ const [away, setAway] = useState(false) // the stage shows another project's "another canvas" page (A1.11)
312
317
  const fill = play?.device === 'fill'
313
318
  // the mode's shape: focus is single-frame; the doc preset (reading width,
314
319
  // page ground) applies when the board's declared type is doc; lock and deep
@@ -334,13 +339,14 @@ function PlayInner() {
334
339
  if (!playNav || !iframeRef.current) return
335
340
  const p = useStore.getState().play
336
341
  if (!p) return
337
- iframeRef.current.src = `${ROUTE}/stage/?at=${encodeURIComponent(p.at)}&theme=${encodeURIComponent(p.theme)}${slParams(p)}&r=${playNav}`
342
+ iframeRef.current.src = withWs(`${ROUTE}/stage/?at=${encodeURIComponent(p.at)}&theme=${encodeURIComponent(p.theme)}${slParams(p)}&r=${playNav}`)
338
343
  }, [playNav])
339
344
  const applyUpdate = () => useStore.getState().applyPlayUpdate()
340
345
 
341
346
  // laser / comment ride the same rail as canvas frames, broadcast to the stage iframe.
342
347
  // Re-sent on stage-ready (below) so a stage reload restores the mode.
343
- useEffect(() => { postStage({ type: 'sh:laser', on: laser }) }, [laser])
348
+ const laserInspect = useStore((s) => s.laserInspect)
349
+ useEffect(() => { postStage({ type: 'sh:laser', on: laser, inspect: laserInspect }) }, [laser, laserInspect])
344
350
  useEffect(() => { postStage({ type: 'sh:pick', on: commentMode, quiet: !useComments.getState().showAnchor }) }, [commentMode, playShowAnchor])
345
351
 
346
352
  const exit = () => {
@@ -462,7 +468,7 @@ function PlayInner() {
462
468
  if (typeof data.at === 'string' && data.at !== p.at) postStage({ type: 'sh:stage-set', at: p.at })
463
469
  postStage({ type: 'sh:set-theme', theme: p.theme })
464
470
  }
465
- postStage({ type: 'sh:laser', on: s.laser })
471
+ postStage({ type: 'sh:laser', on: s.laser, inspect: s.laserInspect })
466
472
  postStage({ type: 'sh:pick', on: commentsStore().commentMode, quiet: !commentsStore().showAnchor })
467
473
  setStageReady((n) => n + 1) // a reload wiped the frame's lock; let PlayComments re-drive it
468
474
  } else if (data.type === 'sh:stage-shown') {
@@ -482,11 +488,12 @@ function PlayInner() {
482
488
  else {
483
489
  useStore.setState({ stageShown: null }) // an error card holds the stage now: nothing on it counts as seen
484
490
  s.toast(`play: ${String(data.message ?? 'frame error')}`)
491
+ recorder.error({ source: 'stage', message: data.message })
485
492
  if (s.playNav && !s.stageShown) useStore.setState({ playUpdateRevision: 'retry' }) // an Update that failed: offer it again
486
493
  }
487
494
  } else if (data.type === 'sh:stage-key') {
488
495
  if (data.meta && data.key === '/') toggleCollapse()
489
- else handleKey(String(data.key), String(data.code))
496
+ else handleKey(String(data.key), String(data.code), !!data.alt)
490
497
  } else if (data.type === 'sh:picked') {
491
498
  // comment pick from the stage: stage the draft on the walked frame (its canvas
492
499
  // node when one is on this board, so the thread also lands on the canvas). Stamp
@@ -522,7 +529,7 @@ function PlayInner() {
522
529
  }, [])
523
530
 
524
531
  // shared handler: keys arrive directly (focus in shell) or forwarded by the stage
525
- const handleKey = (key: string, code: string) => {
532
+ const handleKey = (key: string, code: string, alt = false) => {
526
533
  if (key === 'Escape') {
527
534
  // a live review mode swallows Escape first (cancel), so it never ejects you from
528
535
  // the prototype mid-comment; a second Escape (nothing live) exits
@@ -539,8 +546,9 @@ function PlayInner() {
539
546
  if (key === ']') { switchVariant(1); return }
540
547
  if (key === 'r') { restart(); return }
541
548
  if (key === 'h') { toggleHideUI(); return }
542
- if (key === 'l' && SOURCE_REVEALED) { const s = useStore.getState(); if (!s.laser) commentsStore().setMode(false); s.setLaser(!s.laser); return }
543
- if (key === 'c') { const c = commentsStore(); if (!c.commentMode && useStore.getState().board === UNPLACED) return useStore.getState().toast(NO_COMMENTS_HERE); if (!c.commentMode) useStore.getState().setLaser(false); c.setMode(!c.commentMode); return }
549
+ // L: the pointer laser; ⌥L: inspect
550
+ if (key === 'l' && SOURCE_REVEALED) { commentsStore().setMode(false); useStore.getState().toggleLaser(alt); return }
551
+ if (key === 'c') { const c = commentsStore(); if (!c.commentMode && useStore.getState().board === UNPLACED) return useStore.getState().toast(NO_COMMENTS_HERE); if (!c.commentMode && stoppedFor('Comments need the canvas running')) return; if (!c.commentMode) useStore.getState().setLaser(false); c.setMode(!c.commentMode); return }
544
552
  if (key === 'C') { const c = commentsStore(); c.setShow(!c.show); return } // ⇧C hides/shows pins
545
553
  if (key === 'L') { const c = commentsStore(); c.setShowAnchor(!c.showAnchor); return } // ⇧L element focus
546
554
 
@@ -561,10 +569,12 @@ function PlayInner() {
561
569
  const onKey = (e: KeyboardEvent) => {
562
570
  if (!keyAllowed(e)) return // the one key guard (frame-host/keys.js): never from a field, an editable, an IME composition
563
571
  // Jam's keys first - a review open takes the arrows before they step screens
564
- if (!e.repeat && jamKey({ key: e.key, shift: e.shiftKey, alt: e.altKey, meta: e.metaKey, ctrl: e.ctrlKey })) { e.preventDefault(); return }
572
+ // with Option a Mac types a symbol (⌥L is "¬"): an Alt shortcut is named by the key pressed
573
+ const key = e.altKey && /^Key[A-Z]$/.test(e.code) ? e.code.slice(3).toLowerCase() : e.key
574
+ if (!e.repeat && jamKey({ key, shift: e.shiftKey, alt: e.altKey, meta: e.metaKey, ctrl: e.ctrlKey })) { e.preventDefault(); return }
565
575
  if ((e.metaKey || e.ctrlKey) && e.key === '/') { e.preventDefault(); toggleCollapse(); return }
566
576
  if (e.metaKey || e.ctrlKey) return
567
- handleKey(e.key, e.code)
577
+ handleKey(key, e.code, e.altKey)
568
578
  }
569
579
  window.addEventListener('keydown', onKey)
570
580
  return () => window.removeEventListener('keydown', onKey)
@@ -628,10 +638,12 @@ function PlayInner() {
628
638
  <iframe
629
639
  ref={iframeRef}
630
640
  src={src.current}
631
- onLoad={() => frameLoaded('stage', iframeRef.current)}
641
+ onLoad={() => { setAway(stranded(iframeRef.current)); frameLoaded('stage', iframeRef.current) }}
632
642
  title="play"
633
643
  style={{ width: vp.width, height: vp.height, transform: `scale(${dw / vp.width}, ${dh / vp.height})` }}
634
644
  />
645
+ {/* its canvas is away from this address: one calm line, the banner says the rest */}
646
+ {away && <div className="sh-stranded"><span>Waiting for this canvas</span></div>}
635
647
  </div>
636
648
  <PlayComments iframe={iframeRef} frameId={play.at} vp={vp} dw={dw} dh={dh} ready={stageReady} />
637
649
  </div>
@@ -8,7 +8,8 @@
8
8
  */
9
9
  import { createPortal } from 'react-dom'
10
10
  import { useEffect, useRef, useState, type ReactNode } from 'react'
11
- import { useStore, CONFIG, SOURCE_REVEALED, cap } from './store.ts'
11
+ import { useStore, CONFIG, SOURCE_REVEALED, cap, stoppedFor } from './store.ts'
12
+ import { STOPPED_TIP, useStopped } from './api.ts'
12
13
  import { NO_COMMENTS_HERE, useComments } from './comments-store.ts'
13
14
  import { UNPLACED } from './hash.ts'
14
15
  import { Tip } from './Tip.tsx'
@@ -89,15 +90,16 @@ function TipRows({ rows }: { rows: [string, string][] }) {
89
90
  * since the two are one-at-a-time). */
90
91
  export function LaserButton() {
91
92
  const laser = useStore((s) => s.laser)
93
+ const laserInspect = useStore((s) => s.laserInspect)
92
94
  const showAnchor = useComments((s) => s.showAnchor)
93
95
  // stripped build: the paths are not in the bundle, so the button that would
94
96
  // copy them has nothing honest to offer
95
97
  if (!SOURCE_REVEALED) return null
96
98
  return (
97
- <Tip side="bottom" label={<TipRows rows={[['Laser mode', 'L'], [showAnchor ? 'Hide laser comment' : 'Show laser comment', '⇧L']]} />}>
98
- <button className={`sh-pill-btn${laser ? ' on' : ''}`} onClick={() => {
99
- if (!laser) commentsStore().setMode(false)
100
- useStore.getState().setLaser(!laser)
99
+ <Tip side="bottom" label={<TipRows rows={[['Laser', 'L'], ['Inspect', '⌥L'], [showAnchor ? 'Hide laser comment' : 'Show laser comment', '⇧L']]} />}>
100
+ <button className={`sh-pill-btn${laser ? ' on' : ''}`} data-laser={laser ? (laserInspect ? 'inspect' : 'pointer') : 'off'} onClick={(e) => {
101
+ commentsStore().setMode(false)
102
+ useStore.getState().toggleLaser(e.altKey)
101
103
  }}><LaserIcon size={16} /></button>
102
104
  </Tip>
103
105
  )
@@ -114,7 +116,16 @@ export function CommentButton() {
114
116
  const myBoards = useComments((s) => s.myBoards)
115
117
  const board = useStore((s) => s.board)
116
118
  const asked = useRef(0)
119
+ const stopped = useStopped()
117
120
  const lockedOut = !!me && !!myBoards && myBoards[board] === 'view'
121
+ // the canvas stopped (spec 28 A1.11): off, saying why - a comment could not be sent
122
+ if (stopped && !commentMode) {
123
+ return (
124
+ <Tip side="bottom" label={<div className="sh-tip-lines"><b>Comments need the canvas running</b><small>{STOPPED_TIP}</small></div>}>
125
+ <button className="sh-pill-btn off" aria-disabled="true" data-stopped="" onClick={() => stoppedFor('Comments need the canvas running')}><CommentIcon size={16} /></button>
126
+ </Tip>
127
+ )
128
+ }
118
129
  if (lockedOut) {
119
130
  return (
120
131
  <Tip side="bottom" label={<><b>Commenting is not available for you yet</b><span>click to ask the owner</span></>}>
@@ -133,6 +144,7 @@ export function CommentButton() {
133
144
  <button className={`sh-pill-btn${commentMode ? ' on' : ''}`} onClick={() => {
134
145
  const c = commentsStore()
135
146
  if (!c.commentMode && useStore.getState().board === UNPLACED) return useStore.getState().toast(NO_COMMENTS_HERE)
147
+ if (!c.commentMode && stoppedFor('Comments need the canvas running')) return
136
148
  if (!c.commentMode) useStore.getState().setLaser(false)
137
149
  c.setMode(!c.commentMode)
138
150
  useStore.getState().toast(c.commentMode ? 'comment mode off' : 'comment mode - click an element in a frame')
@@ -0,0 +1,206 @@
1
+ /**
2
+ * Every request this page makes to its dev server names the canvas it belongs to (spec 28 A1.11), so a
3
+ * page left open after its canvas stopped can never write into another project that took its port. The
4
+ * server refuses a request naming another workspace before reading anything (server/guard.ts); this
5
+ * side keeps what the page holds, says the canvas stopped, and sends nothing more until its own canvas
6
+ * answers on this address again - then it saves and reloads. A published canvas has no workspace to
7
+ * name: its requests go out as before.
8
+ */
9
+ import { create } from 'zustand'
10
+ import { ROUTE } from '../const.ts'
11
+ // @ts-expect-error virtual module provided by the plugin
12
+ import shConfig from 'virtual:sh-config'
13
+ // @ts-expect-error virtual module: null in dev; a published build inlines manifest+boards
14
+ import shData from 'virtual:sh-data'
15
+
16
+ /** This page's workspace in dev; '' on a published canvas (or a harness that names none). */
17
+ export const WS: string = shData === null && typeof shConfig?.workspace === 'string' ? shConfig.workspace : ''
18
+
19
+ /** A per-viewer preference kept per canvas (A1.6): `<key>:<workspace>` in dev, the bare key when published. */
20
+ export const scoped = (key: string) => (WS ? `${key}:${WS}` : key)
21
+ /** A URL a document or an <img> loads, naming the workspace (frames, the stage, Jam pictures). */
22
+ export const withWs = (url: string) => (WS ? `${url}${url.includes('?') ? '&' : '?'}ws=${WS}` : url)
23
+
24
+ /** live; checking (the live socket dropped, the first answer not in); down (nothing, or not this canvas,
25
+ * answers); elsewhere (another canvas answers here); resuming (this canvas answered: saving, then reload). */
26
+ export type Link = 'live' | 'checking' | 'down' | 'elsewhere' | 'resuming'
27
+ /** `shown`: the "This canvas stopped" banner is up. `unsaved`: this tab holds something only it has (an edit not
28
+ * saved, a capture, words not sent) - the banner says so only then. */
29
+ export const useLink = create<{ link: Link; shown: boolean; unsaved: boolean }>(() => ({ link: 'live', shown: false, unsaved: false }))
30
+ export const stoppedLink = (l: Link) => l === 'checking' || l === 'down' || l === 'elsewhere'
31
+ /** Nothing leaves the page: its canvas is gone from here, or not known to be back yet. */
32
+ export const canvasStopped = () => stoppedLink(useLink.getState().link)
33
+ /** canvasStopped(), for a component: the tools that need the server (comments, Jam) go quiet while it holds. */
34
+ export const useStopped = () => useLink((s) => stoppedLink(s.link))
35
+ /** The way back, said by each tool that needs the server while the canvas is stopped: its toast, its tooltip. */
36
+ export const STOPPED_WAY = 'npx marver dev brings it back'
37
+ export const STOPPED_TIP = 'The canvas stopped - run npx marver dev to bring it back'
38
+ /** The answer a stopped page gives itself (or gets from the server, translated): never a 409 a caller reads. */
39
+ export const isStopped = (r: Response) => r.headers.get('x-mv-stopped') === '1'
40
+ const stoppedAnswer = () => new Response('{"error":"this canvas stopped"}', { status: 503, headers: { 'content-type': 'application/json', 'x-mv-stopped': '1' } })
41
+
42
+ /** Any request to this page's dev server. `fetch` is looked up at call time (tests patch window.fetch)
43
+ * and called before any await, so a `keepalive` request made in `pagehide` still goes out. Callers pass
44
+ * plain-object headers; a GET keeps its init without a method. */
45
+ export function mvFetch(url: string, init: RequestInit = {}): Promise<Response> {
46
+ if (WS && canvasStopped()) return Promise.resolve(stoppedAnswer())
47
+ const sent = fetch(url, WS ? { ...init, headers: { ...(init.headers as Record<string, string> | undefined), 'x-mv-ws': WS } } : init)
48
+ if (!WS) return sent
49
+ // the server's refusal is told apart here, before any caller's own 409 (a board conflict, a stale tree)
50
+ return sent.then((r) => {
51
+ if (r.status !== 409 || r.headers.get('x-mv-elsewhere') !== '1') return r
52
+ lost('elsewhere')
53
+ return stoppedAnswer()
54
+ }, (e: unknown) => {
55
+ // the live socket is gone, so nothing else would say so: a request that reaches nothing stops the page
56
+ if (hmrLost && (e as Error)?.name !== 'AbortError') lost('down')
57
+ throw e
58
+ })
59
+ }
60
+ /** A request under /__mv/api/: `api('boards/main', { method: 'PUT', ... })`. */
61
+ export const api = (path: string, init?: RequestInit) => mvFetch(`${ROUTE}/api/${path}`, init)
62
+
63
+ // ---- the link: losing the canvas, and getting it back --------------------------------------------------
64
+
65
+ /** What must be done before a resumed page reloads (the board save, the heights). Each answers true when
66
+ * the page may reload now; asked again each second while a reload is owed, so each is cheap when there is
67
+ * nothing to do. */
68
+ const flushers = new Set<() => Promise<boolean>>()
69
+ export const beforeResume = (fn: () => Promise<boolean>) => { flushers.add(fn); return () => { flushers.delete(fn) } }
70
+ /** What holds a reload while it answers true: an edit not saved, a capture recording, words typed and not
71
+ * sent. Synchronous, and asked right before the reload, after every flusher has finished - so what a person
72
+ * does while the flushers wait on the server holds it as surely as what was there before they began. */
73
+ const holds = new Set<() => boolean>()
74
+ export const holdsReload = (fn: () => boolean) => { holds.add(fn); return () => { holds.delete(fn) } }
75
+ const held = () => [...holds].some((h) => { try { return h() } catch { return true } })
76
+ /** Asks again whether this tab holds anything only it has (the banner's "unsaved edits"): at a stop, once a
77
+ * second while stopped, and whenever an edit or a word changes it. */
78
+ export function noteUnsaved() {
79
+ if (!WS) return
80
+ const u = held()
81
+ if (u !== useLink.getState().unsaved) useLink.setState({ unsaved: u })
82
+ }
83
+ /** Told when a resumed page stays (a flusher said no): the store's toast, registered by store.ts. */
84
+ let say: (text: string) => void = () => {}
85
+ export const onLinkNotice = (fn: (text: string) => void) => { say = fn }
86
+
87
+ let hmrLost = false
88
+ let probeTimer: ReturnType<typeof setTimeout> | null = null
89
+
90
+ function lost(why: 'down' | 'elsewhere') {
91
+ noteUnsaved()
92
+ if (why === 'elsewhere') useLink.setState({ link: 'elsewhere', shown: true })
93
+ else if (!canvasStopped()) useLink.setState({ link: 'checking' })
94
+ probeTimer ??= setTimeout(probe, 0)
95
+ }
96
+
97
+ /** Once a second while stopped, and while a reload is owed: is this canvas (still) on this address? */
98
+ async function probe() {
99
+ let r: Response | null = null
100
+ // a server that takes the connection and never answers (half up, hung, paused) is no answer: a miss
101
+ try { r = await fetch(`${ROUTE}/api/hello`, { headers: { 'x-mv-ws': WS }, cache: 'no-store', signal: AbortSignal.timeout(2000) }) } catch { r = null }
102
+ const ours = !!r?.ok && (await r.json().catch(() => null))?.ws === WS
103
+ probeTimer = null
104
+ if (ours) return void resume()
105
+ // another canvas answers, or nothing does, or something that is not a canvas of this one (an older
106
+ // marver says 404): the banner - and keep asking
107
+ noteUnsaved()
108
+ useLink.setState({ link: r?.status === 409 && r.headers.get('x-mv-elsewhere') === '1' ? 'elsewhere' : 'down', shown: true })
109
+ probeTimer = setTimeout(probe, 1000)
110
+ }
111
+
112
+ async function resume() {
113
+ const back = useLink.getState().link !== 'live' // from a stop; 'live' is a page that owes a reload
114
+ if (back) useLink.setState({ link: 'resuming' }) // requests flow again: the flushers use them
115
+ let ok = true
116
+ flushing = true
117
+ try { for (const fn of flushers) ok = (await fn().catch(() => false)) && ok } finally { flushing = false }
118
+ const now = useLink.getState().link
119
+ if (now !== 'resuming' && now !== 'live') return // lost again while saving: the probe goes on
120
+ // asked here, with nothing awaited between the answer and the reload: words typed or an edit made while a
121
+ // flusher waited on the server hold it too
122
+ if (ok && held()) ok = false
123
+ // a fresh document on the canvas that answered: live updates again - and the next page says what the resumes came to,
124
+ // this one's and those this reload waited after (a draft, a capture), whose toasts go with this page
125
+ if (hmrLost && ok) { keepOverReload(lostOnResume ?? (savedOnResume ? 'saved' : null)); return void location.reload() }
126
+ if (back || useLink.getState().shown) useLink.setState({ link: 'live', shown: false })
127
+ // no reload owed (Vite's socket held): the page goes on as it is, and what this resume came to was said on it
128
+ if (!hmrLost) { lostOnResume = null; savedOnResume = false; return }
129
+ // Vite's socket never comes back (its client waits on the listener below), so this page owes a reload:
130
+ // until nothing holds it (a capture recording, words not sent) it works as live, keeps asking - a stop
131
+ // is seen again - and reloads the moment it may
132
+ if (back) { say('marver dev is back - this page reloads once nothing is in progress'); unstrand() }
133
+ probeTimer ??= setTimeout(probe, 1000)
134
+ }
135
+
136
+ /** Frames another project answered while this canvas was away show its "another canvas" page, which runs no
137
+ * script - no Vite client to bring them back. A page that stays reloads them in place, on its own canvas. */
138
+ function unstrand() {
139
+ for (const f of document.querySelectorAll('iframe')) if (stranded(f)) f.contentWindow?.location.reload()
140
+ }
141
+ /** Does this frame show another project's "another canvas" page (server/guard.ts)? The shell draws its own quiet
142
+ * placeholder over it: the banner says what happened, once. */
143
+ export function stranded(f: HTMLIFrameElement | null): boolean {
144
+ try { return !!f?.contentDocument?.querySelector('meta[name="mv-elsewhere"]') } catch { return false /* not ours to read */ }
145
+ }
146
+
147
+ // ---- over the resume's own reload: where the person was looking, and what its save came to --------------------
148
+
149
+ /** What the resume's save came to, said by the page after its reload: 'saved' - the board edits only this tab held
150
+ * reached the disk; 'disk' - the board's file changed on disk meanwhile and won, the tab's board edits dropped; 'gone' - the board
151
+ * was renamed or removed meanwhile and is not created again; null - there was nothing to save. */
152
+ export type ResumeOutcome = 'saved' | 'disk' | 'gone' | null
153
+ let flushing = false
154
+ /** What the resumes came to - the board save's own word, lost or saved - kept until the reload that carries it: a
155
+ * resume whose reload is held (a draft, a capture) is not the last one, and the one that reloads at last may have
156
+ * nothing left to save. Each later resume only adds to it - the first loss stays, and a loss outranks a save. A resume
157
+ * that owes no reload (Vite's socket held) ends it. */
158
+ let lostOnResume: 'disk' | 'gone' | null = null
159
+ let savedOnResume = false
160
+ /** The board save, while the resume's flushers run: what this tab held did not reach the disk (store.ts) - the page
161
+ * after the reload says what happened instead, never that the edits were saved. */
162
+ export function lostInResume(why: 'disk' | 'gone') { if (flushing) lostOnResume ??= why }
163
+ /** The board save, while the resume's flushers run: what this tab held reached the disk (store.ts). */
164
+ export function savedInResume() { if (flushing) savedOnResume = true }
165
+
166
+ const RESUMED = 'mv-resumed'
167
+ const keepers = new Set<() => Record<string, unknown>>()
168
+ /** What a resumed page carries over its own reload, read back by the next page (the canvas keeps its camera). */
169
+ export const keepOverResume = (fn: () => Record<string, unknown>) => { keepers.add(fn); return () => { keepers.delete(fn) } }
170
+ function keepOverReload(outcome: ResumeOutcome) {
171
+ const rec: Record<string, unknown> = { at: Date.now(), outcome }
172
+ for (const fn of keepers) { try { Object.assign(rec, fn()) } catch { /* the rest still goes */ } }
173
+ try { sessionStorage.setItem(scoped(RESUMED), JSON.stringify(rec)) } catch { /* storage off: the page boots as any other */ }
174
+ }
175
+ const OUTCOMES: readonly ResumeOutcome[] = ['saved', 'disk', 'gone', null]
176
+ /** What the page before this one left when it reloaded itself on its canvas's return - this tab only, read once
177
+ * at load, and only a fresh one (a reload by hand later on boots as any other). `outcome`: what its save came to;
178
+ * the page says so. */
179
+ export const resumed: { outcome: ResumeOutcome; board?: string; camera?: { x: number; y: number; scale: number } } | null = (() => {
180
+ if (!WS) return null
181
+ try {
182
+ const raw = sessionStorage.getItem(scoped(RESUMED))
183
+ if (raw === null) return null
184
+ sessionStorage.removeItem(scoped(RESUMED))
185
+ const r = JSON.parse(raw)
186
+ return r && typeof r.at === 'number' && Date.now() - r.at < 30_000 ? { ...r, outcome: OUTCOMES.includes(r.outcome) ? r.outcome : null } : null
187
+ } catch { return null }
188
+ })()
189
+
190
+ // words a person typed into the page and has not sent (a comment, a Jam edit, a name): a reload would drop them
191
+ const typed = new WeakSet<EventTarget>()
192
+ const TEXT_FIELDS = 'textarea, input:not([type]), input[type=text], input[type=search], input[type=email], input[type=url], input[type=password]'
193
+ if (WS) {
194
+ document.addEventListener('input', (e) => { if (e.target) typed.add(e.target); if (canvasStopped()) noteUnsaved() }, true)
195
+ holdsReload(() => [...document.querySelectorAll<HTMLInputElement | HTMLTextAreaElement>(TEXT_FIELDS)].some((el) => typed.has(el) && el.value.trim() !== ''))
196
+ }
197
+
198
+ // Vite's client awaits every `vite:ws:disconnect` listener before it pings the server and reloads the
199
+ // page (vite/dist/client/client.mjs, Vite 8). This one never settles: the canvas page is never reloaded by
200
+ // Vite - not into another project that took the port, and not into this one's next run before it has
201
+ // saved what it holds - and its socket stays closed, so no other project's broadcast reaches it. It
202
+ // reloads itself in resume(). Frames keep Vite's own reload: their URLs name the workspace.
203
+ if (WS && import.meta.hot) import.meta.hot.on('vite:ws:disconnect', () => { hmrLost = true; lost('down'); return new Promise<never>(() => {}) })
204
+
205
+ // dev-only inspection hook for tests (never installed in published builds)
206
+ if (WS && import.meta.env.DEV) (window as unknown as { __mvLink: unknown }).__mvLink = useLink
@@ -7,7 +7,10 @@ import { revealFrame } from '../goto.ts'
7
7
  import { startPerf } from '../perf.ts'
8
8
  import { FrameNode, HEADER } from './FrameNode.tsx'
9
9
  import { NOTE_GAP } from '../notes.ts'
10
- import { startCameraBroadcast, setCameraScale } from './camera-broadcast.ts'
10
+ import { onMotion, startCameraBroadcast, setCameraScale } from './camera-broadcast.ts'
11
+ import { attachCanvas, recorder } from '../recorder.ts'
12
+ import { sleepingCount } from './sleep.ts'
13
+ import { keepOverResume, resumed } from '../api.ts'
11
14
 
12
15
  /**
13
16
  * The world. rzpp owns pan/zoom; nodes are absolutely positioned children of #sh-world.
@@ -144,7 +147,8 @@ export function Canvas() {
144
147
  const ref = useRef<ReactZoomPanPinchContentRef>(null)
145
148
  const scaleTimer = useRef(0)
146
149
 
147
- useEffect(() => { startPerf(); startCameraBroadcast() }, []) // B0.4: frame-time sampler + image-LOD camera signal
150
+ // B0.4: frame-time sampler + image-LOD camera signal; the recorder hears when the camera stops and what sleeps (spec 28 A1.7)
151
+ useEffect(() => { startPerf(); startCameraBroadcast(); return attachCanvas({ onMotion, sleeping: sleepingCount }) }, [])
148
152
 
149
153
  useEffect(() => {
150
154
  const wrap = () => document.querySelector('.sh-canvas') as HTMLElement | null
@@ -167,7 +171,10 @@ export function Canvas() {
167
171
  px = Math.max(Math.min((vw - w * scale) / 2, vw - p.right - w * scale), p.left)
168
172
  py = Math.max(Math.min((vh - h * scale) / 2, vh - p.bottom - h * scale), p.top)
169
173
  }
170
- ref.current.setTransform(px - x * scale, py - y * scale, scale, 320, 'easeOut')
174
+ const tx = px - x * scale, ty = py - y * scale
175
+ // where this fit lands, in world px: the first one after a board's commit shows its visible cohort (spec 28 A1.7)
176
+ recorder.placed({ x: -tx / scale, y: -ty / scale, w: vw / scale, h: vh / scale })
177
+ ref.current.setTransform(tx, ty, scale, 320, 'easeOut')
171
178
  }
172
179
  const fitKeys = (keys: string[], focus: boolean) => {
173
180
  const st = useStore.getState()
@@ -210,6 +217,17 @@ export function Canvas() {
210
217
  inst.setTransform(cx - (cx - positionX) * k, cy - (cy - positionY) * k, target, 250, 'easeOut')
211
218
  }
212
219
  canvasCtl.cameraBusy = () => !!ref.current?.instance.animation
220
+ // a page that reloads itself when its canvas comes back (spec 28 A1.11) opens where the person was looking
221
+ const unkeep = keepOverResume(() => {
222
+ const t = ref.current?.instance.transformState
223
+ return t ? { board: useStore.getState().board, camera: { x: t.positionX, y: t.positionY, scale: t.scale } } : {}
224
+ })
225
+ canvasCtl.view = () => {
226
+ const el = wrap(), inst = ref.current
227
+ if (!el || !inst) return null
228
+ const { positionX, positionY, scale } = inst.instance.transformState
229
+ return { x: -positionX / scale, y: -positionY / scale, w: el.clientWidth / scale, h: el.clientHeight / scale }
230
+ }
213
231
  canvasCtl.holdView = () => {
214
232
  heldView = null
215
233
  const el = wrap(), inst = ref.current
@@ -222,6 +240,7 @@ export function Canvas() {
222
240
  // the reflow commits before the next frame; an anchor nothing consumed must never steer a later change
223
241
  requestAnimationFrame(() => { if (heldView === held) heldView = null })
224
242
  }
243
+ return unkeep
225
244
  }, [])
226
245
 
227
246
  // first load opens on the whole board (same as ⇧1) - the default 100% transform is an
@@ -233,12 +252,20 @@ export function Canvas() {
233
252
  if (booted.current || nodes.length === 0) return
234
253
  let revealed = false
235
254
  booted.current = true
255
+ // the page before this one reloaded itself when its canvas came back: its camera, on the board it showed
256
+ const cam = resumed?.camera && resumed.board === useStore.getState().board ? resumed.camera : null
236
257
  const fit = () => {
237
258
  const keys = linkTargets(bootHash, useStore.getState().nodes)
238
259
  if (keys.length) {
239
260
  useStore.setState({ selection: keys })
240
261
  const st = useStore.getState() // a link opened is a look (marks not in yet: their first load acknowledges it)
241
262
  st.look(keys)
263
+ }
264
+ const el = document.querySelector('.sh-canvas') as HTMLElement | null
265
+ if (cam && el && ref.current) {
266
+ recorder.placed({ x: -cam.x / cam.scale, y: -cam.y / cam.scale, w: el.clientWidth / cam.scale, h: el.clientHeight / cam.scale })
267
+ ref.current.setTransform(cam.x, cam.y, cam.scale, 0)
268
+ } else if (keys.length) {
242
269
  canvasCtl.fitNodes(keys)
243
270
  } else {
244
271
  canvasCtl.fitAll()
@@ -11,9 +11,11 @@ import { primeCameraFor } from './camera-broadcast.ts'
11
11
  import { sleep, wake } from './sleep.ts'
12
12
  import { canAutoReload, shouldArmReadyWatch } from './ready-watch.ts'
13
13
  import { Stickies, type NoteSpec } from './Sticky.tsx'
14
+ import { recorder } from '../recorder.ts'
14
15
  import { noteId, sceneNoteHost } from '../notes.ts'
15
16
  import { slideSize, stageFit } from '../../const.ts'
16
17
  import { FrameSlot, toneOf, useFrameMark } from '../marks-ui.tsx'
18
+ import { stranded } from '../api.ts'
17
19
 
18
20
  export const HEADER = 28
19
21
  const SNAP = 12
@@ -94,6 +96,8 @@ export const FrameNode = memo(function FrameNode({ node }: { node: Node }) {
94
96
  // survives a theme flip; file changes and reloads navigate imperatively below, only once
95
97
  // admitted - a queued frame takes the fresh revision when its turn comes.
96
98
  const [src, setSrc] = useState<string>()
99
+ // the document is another project's "another canvas" page (spec 28 A1.11): a quiet placeholder over it instead
100
+ const [away, setAway] = useState(false)
97
101
  const admitted = src !== undefined
98
102
  const admittedRef = useRef(false)
99
103
  const fileRef = useRef(frame ? `${frame.kind}:${frame.file}` : null)
@@ -116,6 +120,7 @@ export const FrameNode = memo(function FrameNode({ node }: { node: Node }) {
116
120
  if (n.status !== 'loading') setStatus(node.key, 'loading') // a returning frame boots under the watchdog like any other
117
121
  admittedRef.current = true
118
122
  setSrc(frameUrl(f, n.theme))
123
+ recorder.admitted(node.key)
119
124
  }
120
125
  admit({ key: node.key, rank, start })
121
126
  return () => release(node.key)
@@ -158,6 +163,7 @@ export const FrameNode = memo(function FrameNode({ node }: { node: Node }) {
158
163
  // laser mode rides the same rail; re-sent when a frame becomes ready
159
164
  // so late loaders join an already-lasered board
160
165
  const laser = useStore((s) => s.laser)
166
+ const laserInspect = useStore((s) => s.laserInspect)
161
167
  const commentMode = useComments((s) => s.commentMode)
162
168
  // a node hosting the OPEN thread card (or a draft composer) rises above its
163
169
  // neighbors - each node is a stacking context, so an overflowing card would
@@ -167,8 +173,8 @@ export const FrameNode = memo(function FrameNode({ node }: { node: Node }) {
167
173
  t.id === s.active && !t.resolved && threadHostKey(t, useStore.getState().nodes) === node.key)) || s.draft?.nodeKey === node.key)
168
174
  useEffect(() => {
169
175
  if (node.status === 'ready' || !laser)
170
- iframeRef.current?.contentWindow?.postMessage({ type: 'sh:laser', on: laser }, location.origin)
171
- }, [laser, node.status])
176
+ iframeRef.current?.contentWindow?.postMessage({ type: 'sh:laser', on: laser, inspect: laserInspect }, location.origin)
177
+ }, [laser, laserInspect, node.status])
172
178
  // comment mode = pick mode in the frame (late loaders join like laser does); quiet when
173
179
  // laser comment (⇧L) is off - clicks still anchor, no lighting in the artwork
174
180
  const showAnchor = useComments((s) => s.showAnchor)
@@ -270,7 +276,9 @@ export const FrameNode = memo(function FrameNode({ node }: { node: Node }) {
270
276
  // boot slot - its boot is still running - and gives it back after a second silence.
271
277
  useEffect(() => {
272
278
  if (!admitted || node.status !== 'loading' || !frame || node.missing) return
273
- const t = setTimeout(() => { if (shouldArmReadyWatch(node, true)) reloadRef.current(true); else release(node.key) }, 10_000)
279
+ // the second silence gives the slot back, and is the recorder's never-ready (spec 28 A1.7) - the frame stays
280
+ // loading, never a red card
281
+ const t = setTimeout(() => { if (shouldArmReadyWatch(node, true)) reloadRef.current(true); else { release(node.key); recorder.neverReady(node.key) } }, 10_000)
274
282
  return () => clearTimeout(t)
275
283
  // depend on the frame's stable SIGNATURE, not the manifest object - that object is replaced on
276
284
  // every manifest reconcile, so depending on it would reset the budget on unrelated frames during
@@ -432,7 +440,7 @@ export const FrameNode = memo(function FrameNode({ node }: { node: Node }) {
432
440
  ) : null}
433
441
  {/* a frame still silent after its one auto-retry: a slow dev server, never a failure. A quiet
434
442
  non-covering pill (not the red card) keeps it honest and offers a manual reload. */}
435
- {node.status === 'loading' && node.readyRetried ? (
443
+ {node.status === 'loading' && node.readyRetried && !away ? (
436
444
  <div className="sh-loading sh-no-pan">
437
445
  <span>still loading</span>
438
446
  <button className="sh-no-pan" onClick={() => reload(false)}>
@@ -445,9 +453,11 @@ export const FrameNode = memo(function FrameNode({ node }: { node: Node }) {
445
453
  className="sh-live"
446
454
  src={src}
447
455
  title={frame.id}
448
- onLoad={() => { registerWin(); frameLoaded(node.key, iframeRef.current) }}
456
+ onLoad={() => { setAway(stranded(iframeRef.current)); registerWin(); frameLoaded(node.key, iframeRef.current); recorder.loaded(node.key) }}
449
457
  style={{ ...iframeBox(stage, node), display: node.missing || node.status === 'error' ? 'none' : 'block' }}
450
458
  />
459
+ {/* its canvas is away from this address: one calm line, the banner says the rest */}
460
+ {away && <div className="sh-stranded"><span>Waiting for this canvas</span></div>}
451
461
  {/* the overlay eats mouse events for drag-by-body; laser and comment mode both
452
462
  need the mouse INSIDE the frame for hover highlights, so it steps aside
453
463
  (drag still works via the header) */}
@@ -43,10 +43,17 @@ const SETTLE = 350 // the board fit animates ~250 ms from 60 ms after mount: r
43
43
  /** The frame is done booting (ready, error, gone, or its watchdog took over): free the slot, or
44
44
  * leave the queue if it never started. */
45
45
  export function release(key: string): void {
46
- waiting.delete(key)
46
+ const was = waiting.delete(key) || active.has(key)
47
47
  if (active.delete(key)) { primed = true; schedule(0) }
48
+ if (was && admissionIdle()) for (const fn of idle) { try { fn() } catch { /* a listener never stops the queue */ } }
48
49
  }
49
50
 
51
+ const idle = new Set<() => void>()
52
+ /** Nothing queued, nothing booting: a board load settles only then (spec 28 A1.7). */
53
+ export const admissionIdle = (): boolean => !waiting.size && !active.size
54
+ /** Called each time the last frame lets go of its slot or leaves the queue; returns the unsubscribe. */
55
+ export function onAdmissionIdle(fn: () => void): () => void { idle.add(fn); return () => { idle.delete(fn) } }
56
+
50
57
  function schedule(ms: number): void {
51
58
  if (scheduled) return
52
59
  scheduled = true
@@ -22,17 +22,27 @@ function broadcast(moving: boolean): void {
22
22
  for (const w of frameWindows()) { try { w.postMessage(msg, location.origin) } catch { /* cross-doc timing */ } }
23
23
  }
24
24
 
25
+ /** What is moving on the canvas: the camera (a pan or zoom, `sh-camera`) and the layout (a preset or tidy animation,
26
+ * `sh-preset`). The same one observer tells the shell's own listeners - the gesture sampler (perf.ts) and the
27
+ * recorder's camera idle (spec 28 A1.7) - on every change of either, so nothing polls. */
28
+ export interface Motion { camera: boolean; preset: boolean }
29
+ let motion: Motion = { camera: false, preset: false }
30
+ const motionListeners = new Set<(m: Motion) => void>()
31
+ /** Called with the new motion at each change; returns the unsubscribe. */
32
+ export function onMotion(fn: (m: Motion) => void): () => void { motionListeners.add(fn); return () => { motionListeners.delete(fn) } }
33
+
25
34
  let started = false
26
35
  export function startCameraBroadcast(): void {
27
36
  if (started) return
28
37
  const world = document.getElementById('sh-world'); if (!world) return
29
38
  started = true
30
- let moving = false
31
39
  new MutationObserver(() => {
32
- const now = world.classList.contains('sh-camera')
33
- if (now === moving) return
34
- moving = now
35
- broadcast(now) // +sh-camera -> freeze; -sh-camera -> sharpen to the settled scale
40
+ const now = { camera: world.classList.contains('sh-camera'), preset: world.classList.contains('sh-preset') }
41
+ if (now.camera === motion.camera && now.preset === motion.preset) return
42
+ const cameraChanged = now.camera !== motion.camera
43
+ motion = now
44
+ if (cameraChanged) broadcast(now.camera) // +sh-camera -> freeze; -sh-camera -> sharpen to the settled scale
45
+ for (const fn of motionListeners) { try { fn(now) } catch { /* a listener never stops the broadcast */ } }
36
46
  }).observe(world, { attributes: true, attributeFilter: ['class'] })
37
47
  }
38
48
 
@@ -29,4 +29,6 @@ export const canvasCtl = {
29
29
  /** Is the camera mid-flight (a fit, a zoom)? A content-driven reflow waits for it to land: a fit
30
30
  * aimed at the frames a link names must not land on where they were before the rows moved. */
31
31
  cameraBusy(): boolean { return false },
32
+ /** What the camera shows now, in world px (null with no canvas) - a load's visible cohort when no fit landed. */
33
+ view(): { x: number; y: number; w: number; h: number } | null { return null },
32
34
  }