@marver-design/marver 0.26.1 → 0.27.2

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 (109) hide show
  1. package/CHANGELOG.md +198 -0
  2. package/README.md +12 -4
  3. package/dist/{anchor-check-l-ny3UzH.mjs → anchor-check-gkxkPAIv.mjs} +1 -1
  4. package/dist/{board-tree-DRioF94d.mjs → board-tree-BXR8dw4b.mjs} +3 -1
  5. package/dist/{boards-CGg6piKF.mjs → boards-BHKP5yhI.mjs} +1 -1
  6. package/dist/{boards-DYG22tOe.mjs → boards-BqUqKNW8.mjs} +4 -4
  7. package/dist/{build-BDRiO_mP.mjs → build-VgNg4rr8.mjs} +8 -23
  8. package/dist/cli.mjs +45 -19
  9. package/dist/{collab-Dxg2trOK.mjs → collab-BEAcXrBb.mjs} +1 -1
  10. package/dist/{comments-BqXua-XL.mjs → comments-YEU1Zhv9.mjs} +4 -4
  11. package/dist/{context-HQ4Giw58.mjs → context-Ccjrhr1J.mjs} +3 -3
  12. package/dist/{daemon-DL6Fwq6D.mjs → daemon-Dc9AH0M3.mjs} +9 -7
  13. package/dist/detect-C0wpaePX.mjs +125 -0
  14. package/dist/dev-lock-C_FC70Mu.mjs +65 -0
  15. package/dist/dev-ri6nAlRp.mjs +1273 -0
  16. package/dist/exclusive-B1RtpeeP.mjs +150 -0
  17. package/dist/{init-D8DtrK_F.mjs → init-W0nxR1OY.mjs} +8 -6
  18. package/dist/{link-BNzLvdhI.mjs → link-CdTgn94Y.mjs} +23 -11
  19. package/dist/ls-BZ5TAtd5.mjs +38 -0
  20. package/dist/{manifest-Nl3KSVOk.mjs → manifest-aFyDmL8C.mjs} +2 -2
  21. package/dist/{marks-DyWMv_Z1.mjs → marks-BF9pNEgH.mjs} +3 -3
  22. package/dist/{marks-CKgzucHZ.mjs → marks-CnCCfAbD.mjs} +3 -3
  23. package/dist/{marver-id-gate-BjF6v4bT.mjs → marver-id-gate-D-R0hSt_.mjs} +1 -1
  24. package/dist/perf-DkAUFT6W.mjs +1319 -0
  25. package/dist/perf-jam-BaH3Lg0m.mjs +635 -0
  26. package/dist/plugin-B8UghYuF.mjs +5242 -0
  27. package/dist/{poster-BdtSKMDm.mjs → poster-BNgafWMK.mjs} +1 -1
  28. package/dist/{profile-WU9qcbIo.mjs → profile-jIS6BcAs.mjs} +1 -1
  29. package/dist/{publish-bakes-9RzRToXV.mjs → publish-bakes-38Nja78p.mjs} +3 -3
  30. package/dist/{queue-29ok5_eZ.mjs → queue-CAM_vNmX.mjs} +1 -1
  31. package/dist/recover-B8AiI29B.mjs +66 -0
  32. package/dist/{serve-C8rVheYk.mjs → serve-Dp3nHstu.mjs} +3 -3
  33. package/dist/{share--oFJ1bCI.mjs → share-Ce4tP7ji.mjs} +1 -1
  34. package/dist/{shot-XQV7HC9A.mjs → shot-CMQgMVZm.mjs} +1 -1
  35. package/dist/{shot-DQeR_Pfn.mjs → shot-Ch24tiMO.mjs} +36 -5
  36. package/dist/slots-CFNnegCc.mjs +478 -0
  37. package/dist/{sync-DKk-yT1V.mjs → sync-CQdGARJ9.mjs} +4 -3
  38. package/dist/{work-VvX_JIgl.mjs → work-Bxz-ObF3.mjs} +4 -2
  39. package/dist/{work-F5u-twpJ.mjs → work-CNhFF9pU.mjs} +5 -3
  40. package/docs/boards-and-folders.md +3 -1
  41. package/docs/jam-session.md +57 -2
  42. package/docs/performance.md +424 -0
  43. package/package.json +2 -2
  44. package/src/client/content/index.tsx +3 -0
  45. package/src/client/content/video.tsx +16 -4
  46. package/src/client/frame-host/bridge.js +22 -6
  47. package/src/client/frame-host/main.tsx +17 -5
  48. package/src/client/shell/App.tsx +188 -26
  49. package/src/client/shell/BoardList.tsx +5 -5
  50. package/src/client/shell/Comments.tsx +8 -5
  51. package/src/client/shell/ContextMenu.tsx +5 -3
  52. package/src/client/shell/JamSurface.tsx +4 -2
  53. package/src/client/shell/LockedApp.tsx +8 -5
  54. package/src/client/shell/Play.tsx +20 -10
  55. package/src/client/shell/Tip.tsx +3 -1
  56. package/src/client/shell/Toolbar.tsx +12 -1
  57. package/src/client/shell/api.ts +233 -0
  58. package/src/client/shell/app-bridge.ts +254 -0
  59. package/src/client/shell/app-perf.ts +92 -0
  60. package/src/client/shell/canvas/Canvas.tsx +141 -21
  61. package/src/client/shell/canvas/FrameNode.tsx +22 -9
  62. package/src/client/shell/canvas/admission.ts +31 -9
  63. package/src/client/shell/canvas/camera-broadcast.ts +15 -5
  64. package/src/client/shell/canvas/ctl.ts +8 -0
  65. package/src/client/shell/canvas/frame-registry.ts +28 -2
  66. package/src/client/shell/canvas/sleep.ts +60 -17
  67. package/src/client/shell/canvas/updates.ts +2 -1
  68. package/src/client/shell/comments-store.ts +12 -4
  69. package/src/client/shell/goto.ts +22 -10
  70. package/src/client/shell/inset.ts +44 -0
  71. package/src/client/shell/jam-capture.ts +41 -22
  72. package/src/client/shell/jam-keys.ts +12 -3
  73. package/src/client/shell/jam-panel.tsx +9 -3
  74. package/src/client/shell/jam-queue.ts +3 -3
  75. package/src/client/shell/jam-session.tsx +14 -8
  76. package/src/client/shell/jam-voice.ts +55 -15
  77. package/src/client/shell/legacy-links.ts +2 -2
  78. package/src/client/shell/main.tsx +18 -1
  79. package/src/client/shell/marks-ui.tsx +5 -3
  80. package/src/client/shell/marver-app.ts +21 -0
  81. package/src/client/shell/notes.ts +8 -1
  82. package/src/client/shell/perf-run-probe.ts +34 -0
  83. package/src/client/shell/perf-run.ts +70 -0
  84. package/src/client/shell/perf.ts +80 -58
  85. package/src/client/shell/recorder-core.ts +183 -0
  86. package/src/client/shell/recorder.ts +607 -0
  87. package/src/client/shell/store.ts +294 -110
  88. package/src/client/shell/styles.css +72 -15
  89. package/src/client/shell/unsaved.ts +81 -0
  90. package/src/client/shell/whiteout-probes.ts +141 -0
  91. package/src/shared/app-api.ts +205 -0
  92. package/src/shared/app-perf.ts +308 -0
  93. package/src/shared/logo-sniff.ts +86 -0
  94. package/src/shared/machine.ts +132 -0
  95. package/src/shared/perf-run.ts +177 -0
  96. package/templates/AGENTS-embedded.md +25 -4
  97. package/templates/AGENTS-studio.md +25 -4
  98. package/templates/demo/dark.tsx +1 -1
  99. package/templates/demo/welcome.tsx +1 -1
  100. package/templates/instructions/boards.md +3 -1
  101. package/templates/instructions/welcome.md +6 -3
  102. package/dist/bake-C-awKgLA.mjs +0 -786
  103. package/dist/config-Cf7EjAMf.mjs +0 -292
  104. package/dist/dev-Bw_qYWWq.mjs +0 -755
  105. package/dist/dev-lock-DWSpa6nj.mjs +0 -179
  106. package/dist/perf-C75MZ73h.mjs +0 -167
  107. package/dist/perf-DPbLGhhO.mjs +0 -49
  108. package/dist/perf-jam-BU3TVrZu.mjs +0 -239
  109. package/dist/plugin-DkGmZs_r.mjs +0 -2423
@@ -11,20 +11,23 @@
11
11
  * next) stays prototype-only.
12
12
  */
13
13
  import { setStageSize } from './stage-size.ts'
14
+ import { usable } from './inset.ts'
14
15
  import { frameLoaded, frameReady, onFrameMessage, stageNavigated } from './jam-capture.ts'
15
16
  import { jamKey } from './jam-keys.ts'
16
17
  import { letGoOfTile } from './jam-state.ts'
17
18
  import { JamButton } from './jam-session.tsx'
18
19
  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'
20
+ import { useStore, BOARD_POLICY, BRANDING, CONFIG, PUBLISHED, SOURCE_REVEALED, boardLabel, boardLocked, cap, fetchBoardNames, modeAllowed, playsAsSlides, SLIDE_INTRINSIC, stoppedFor, type Node } from './store.ts'
20
21
  import { deckOrder } from './play-order.ts'
21
22
  import { NO_COMMENTS_HERE, useComments } from './comments-store.ts'
22
23
  import { UNPLACED } from './hash.ts'
23
24
  import { isNoteAnchor } from './notes.ts'
24
25
  import { ROUTE, slideSize } from '../const.ts'
26
+ import { stranded, withWs } from './api.ts'
25
27
  import { poweredByUrl } from '../../shared/utm.ts'
26
28
  import { canvasCtl } from './canvas/ctl.ts'
27
- import { revealFrame } from './goto.ts'
29
+ import { recorder } from './recorder.ts'
30
+ import { revealFrame, switchFor } from './goto.ts'
28
31
  import { Tip } from './Tip.tsx'
29
32
  import { keyAllowed } from '../frame-host/keys.js'
30
33
  import { CommentButton, DevicePicker, HideUIButton, isHideUI, LaserButton, Popover, ThemePicker, toggleHideUI, usePopover } from './Toolbar.tsx'
@@ -147,8 +150,9 @@ async function switchPlayBoard(name: string) {
147
150
  const s = useStore.getState()
148
151
  if (name === s.board) return
149
152
  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
153
+ // a navigation like any other: a link still reading its board gives way to it, and it to a newer one - which then
154
+ // has the board, the stage and the camera
155
+ if (!await switchFor(name)) return
152
156
  const dev = device && device !== 'slide' ? { device } : undefined // the deck's own size does not follow to a prototype
153
157
  if (playsAsSlides(name)) enterSlides(device ? { device } : undefined)
154
158
  else enterPlay(dev)
@@ -305,10 +309,13 @@ function PlayInner() {
305
309
  const slParams = (p: { slides?: boolean }) => p.slides
306
310
  ? `&slides=1${BOARD_POLICY[useStore.getState().board]?.transition === 'none' ? '&tr=none' : ''}`
307
311
  : ''
308
- const src = useRef(play ? `${ROUTE}/stage/?at=${encodeURIComponent(play.at)}&theme=${encodeURIComponent(play.theme)}${slParams(play)}` : '')
309
- const [win, setWin] = useState({ w: window.innerWidth, h: window.innerHeight })
312
+ // the stage runs the project's frames: its URL names the workspace like a frame's (A1.11)
313
+ const src = useRef(play ? withWs(`${ROUTE}/stage/?at=${encodeURIComponent(play.at)}&theme=${encodeURIComponent(play.theme)}${slParams(play)}`) : '')
314
+ // the view below the Mac app's strip when the shell took the inset (inset.ts): fill, the doc preset and every fit
315
+ const [win, setWin] = useState(() => { const u = usable(); return { w: u.width, h: u.height } })
310
316
  const [pillOpen, setPillOpen] = useState(true) // collapse (pill -> re-open fab), like the canvas
311
317
  const [stageReady, setStageReady] = useState(0) // bumps on each sh:stage-ready (reload) - re-drives the highlight
318
+ const [away, setAway] = useState(false) // the stage shows another project's "another canvas" page (A1.11)
312
319
  const fill = play?.device === 'fill'
313
320
  // the mode's shape: focus is single-frame; the doc preset (reading width,
314
321
  // page ground) applies when the board's declared type is doc; lock and deep
@@ -334,7 +341,7 @@ function PlayInner() {
334
341
  if (!playNav || !iframeRef.current) return
335
342
  const p = useStore.getState().play
336
343
  if (!p) return
337
- iframeRef.current.src = `${ROUTE}/stage/?at=${encodeURIComponent(p.at)}&theme=${encodeURIComponent(p.theme)}${slParams(p)}&r=${playNav}`
344
+ iframeRef.current.src = withWs(`${ROUTE}/stage/?at=${encodeURIComponent(p.at)}&theme=${encodeURIComponent(p.theme)}${slParams(p)}&r=${playNav}`)
338
345
  }, [playNav])
339
346
  const applyUpdate = () => useStore.getState().applyPlayUpdate()
340
347
 
@@ -483,6 +490,7 @@ function PlayInner() {
483
490
  else {
484
491
  useStore.setState({ stageShown: null }) // an error card holds the stage now: nothing on it counts as seen
485
492
  s.toast(`play: ${String(data.message ?? 'frame error')}`)
493
+ recorder.error({ source: 'stage', message: data.message })
486
494
  if (s.playNav && !s.stageShown) useStore.setState({ playUpdateRevision: 'retry' }) // an Update that failed: offer it again
487
495
  }
488
496
  } else if (data.type === 'sh:stage-key') {
@@ -542,7 +550,7 @@ function PlayInner() {
542
550
  if (key === 'h') { toggleHideUI(); return }
543
551
  // L: the pointer laser; ⌥L: inspect
544
552
  if (key === 'l' && SOURCE_REVEALED) { commentsStore().setMode(false); useStore.getState().toggleLaser(alt); return }
545
- 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 }
553
+ 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 }
546
554
  if (key === 'C') { const c = commentsStore(); c.setShow(!c.show); return } // ⇧C hides/shows pins
547
555
  if (key === 'L') { const c = commentsStore(); c.setShowAnchor(!c.showAnchor); return } // ⇧L element focus
548
556
 
@@ -575,7 +583,7 @@ function PlayInner() {
575
583
  }, [])
576
584
 
577
585
  useEffect(() => {
578
- const onResize = () => setWin({ w: window.innerWidth, h: window.innerHeight })
586
+ const onResize = () => { const u = usable(); setWin({ w: u.width, h: u.height }) }
579
587
  window.addEventListener('resize', onResize)
580
588
  return () => window.removeEventListener('resize', onResize)
581
589
  }, [])
@@ -632,10 +640,12 @@ function PlayInner() {
632
640
  <iframe
633
641
  ref={iframeRef}
634
642
  src={src.current}
635
- onLoad={() => frameLoaded('stage', iframeRef.current)}
643
+ onLoad={() => { setAway(stranded(iframeRef.current)); frameLoaded('stage', iframeRef.current) }}
636
644
  title="play"
637
645
  style={{ width: vp.width, height: vp.height, transform: `scale(${dw / vp.width}, ${dh / vp.height})` }}
638
646
  />
647
+ {/* its canvas is away from this address: one calm line, the banner says the rest */}
648
+ {away && <div className="sh-stranded"><span>Waiting for this canvas</span></div>}
639
649
  </div>
640
650
  <PlayComments iframe={iframeRef} frameId={play.at} vp={vp} dw={dw} dh={dh} ready={stageReady} />
641
651
  </div>
@@ -1,5 +1,6 @@
1
1
  import { cloneElement, useLayoutEffect, useRef, useState, type ReactElement, type ReactNode } from 'react'
2
2
  import { createPortal } from 'react-dom'
3
+ import { TOP } from './inset.ts'
3
4
 
4
5
  /** shadcn-style tooltip: snappy (150ms in, instant out), contrast-flipped, zoom-fade.
5
6
  * Portaled to the app root - glass never nests, and neither do overlays. `inv` pins the
@@ -37,9 +38,10 @@ export function Tip({ label, side = 'top', inv = false, only, children }: { labe
37
38
  if (over > 0) el.style.marginLeft = `${-over}px`
38
39
  else if (r.left < 8) el.style.marginLeft = `${8 - r.left}px`
39
40
  // and up and down: a tall tip beside a row near the bottom (a status and its evidence) stays whole
41
+ // never under the Mac app's strip (TOP 44 when the shell took the inset: 52 px)
40
42
  const below = r.bottom - (window.innerHeight - 8)
41
43
  if (below > 0) el.style.marginTop = `${-below}px`
42
- else if (r.top < 8) el.style.marginTop = `${8 - r.top}px`
44
+ else if (r.top < TOP + 8) el.style.marginTop = `${TOP + 8 - r.top}px`
43
45
  }, [pos])
44
46
  // a tip is placed once, where its trigger was: anything that scrolls under it puts it away
45
47
  useLayoutEffect(() => {
@@ -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'
@@ -115,7 +116,16 @@ export function CommentButton() {
115
116
  const myBoards = useComments((s) => s.myBoards)
116
117
  const board = useStore((s) => s.board)
117
118
  const asked = useRef(0)
119
+ const stopped = useStopped()
118
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
+ }
119
129
  if (lockedOut) {
120
130
  return (
121
131
  <Tip side="bottom" label={<><b>Commenting is not available for you yet</b><span>click to ask the owner</span></>}>
@@ -134,6 +144,7 @@ export function CommentButton() {
134
144
  <button className={`sh-pill-btn${commentMode ? ' on' : ''}`} onClick={() => {
135
145
  const c = commentsStore()
136
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
137
148
  if (!c.commentMode) useStore.getState().setLaser(false)
138
149
  c.setMode(!c.commentMode)
139
150
  useStore.getState().toast(c.commentMode ? 'comment mode off' : 'comment mode - click an element in a frame')
@@ -0,0 +1,233 @@
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
+ import { guardLeaving, leaveNow, unsavedWhen, workChanged } from './unsaved.ts'
12
+ import { PERF_RUN, perfRunGate, RUN_HEADER, RUN_PARAM } from './perf-run.ts'
13
+ // @ts-expect-error virtual module provided by the plugin
14
+ import shConfig from 'virtual:sh-config'
15
+ // @ts-expect-error virtual module: null in dev; a published build inlines manifest+boards
16
+ import shData from 'virtual:sh-data'
17
+
18
+ /** This page's workspace in dev; '' on a published canvas (or a harness that names none). */
19
+ export const WS: string = shData === null && typeof shConfig?.workspace === 'string' ? shConfig.workspace : ''
20
+
21
+ /** A per-viewer preference kept per canvas (A1.6): `<key>:<workspace>` in dev, the bare key when published. */
22
+ export const scoped = (key: string) => (WS ? `${key}:${WS}` : key)
23
+ const param = (url: string, k: string, v: string) => `${url}${url.includes('?') ? '&' : '?'}${k}=${v}`
24
+ /** A URL a document or an <img> loads, naming the workspace (frames, the stage, Jam pictures) - and, in a headless
25
+ * perf run, the run (spec 28 A3.8 #17): a frame's own writes are refused by its Referer, its Video asks no poster. */
26
+ export const withWs = (url: string) => {
27
+ const u = WS ? param(url, 'ws', WS) : url
28
+ return PERF_RUN ? param(u, RUN_PARAM, PERF_RUN.id) : u
29
+ }
30
+ /** The headers every request of this page carries: its workspace, and its perf run's id. */
31
+ const named = (h: Record<string, string> | undefined): Record<string, string> => ({ ...h, ...(WS ? { 'x-mv-ws': WS } : {}), ...(PERF_RUN ? { [RUN_HEADER]: PERF_RUN.id } : {}) })
32
+
33
+ /** live; checking (the live socket dropped, the first answer not in); down (nothing, or not this canvas,
34
+ * answers); elsewhere (another canvas answers here); resuming (this canvas answered: saving, then reload). */
35
+ export type Link = 'live' | 'checking' | 'down' | 'elsewhere' | 'resuming'
36
+ /** `shown`: the "This canvas stopped" banner is up. `unsaved`: this tab holds something only it has (an edit not
37
+ * saved, a capture, words not sent) - the banner says so only then. */
38
+ export const useLink = create<{ link: Link; shown: boolean; unsaved: boolean }>(() => ({ link: 'live', shown: false, unsaved: false }))
39
+ export const stoppedLink = (l: Link) => l === 'checking' || l === 'down' || l === 'elsewhere'
40
+ /** Nothing leaves the page: its canvas is gone from here, or not known to be back yet. */
41
+ export const canvasStopped = () => stoppedLink(useLink.getState().link)
42
+ /** canvasStopped(), for a component: the tools that need the server (comments, Jam) go quiet while it holds. */
43
+ export const useStopped = () => useLink((s) => stoppedLink(s.link))
44
+ /** The way back, said by each tool that needs the server while the canvas is stopped: its toast, its tooltip. */
45
+ export const STOPPED_WAY = 'npx marver dev brings it back'
46
+ export const STOPPED_TIP = 'The canvas stopped - run npx marver dev to bring it back'
47
+ /** The answer a stopped page gives itself (or gets from the server, translated): never a 409 a caller reads. */
48
+ export const isStopped = (r: Response) => r.headers.get('x-mv-stopped') === '1'
49
+ const stoppedAnswer = () => new Response('{"error":"this canvas stopped"}', { status: 503, headers: { 'content-type': 'application/json', 'x-mv-stopped': '1' } })
50
+
51
+ /** Any request to this page's dev server. `fetch` is looked up at call time (tests patch window.fetch)
52
+ * and called before any await, so a `keepalive` request made in `pagehide` still goes out. Callers pass
53
+ * plain-object headers; a GET keeps its init without a method. In a headless perf run the barrier comes first
54
+ * (perf-run.ts): a write the run may not make is answered 403 here, never sent, and never stops the page. */
55
+ export function mvFetch(url: string, init: RequestInit = {}): Promise<Response> {
56
+ const refused = perfRunGate(url, init)
57
+ if (refused) return Promise.resolve(refused)
58
+ if (WS && canvasStopped()) return Promise.resolve(stoppedAnswer())
59
+ const sent = fetch(url, WS || PERF_RUN ? { ...init, headers: named(init.headers as Record<string, string> | undefined) } : init)
60
+ if (!WS) return sent
61
+ // the server's refusal is told apart here, before any caller's own 409 (a board conflict, a stale tree)
62
+ return sent.then((r) => {
63
+ if (r.status !== 409 || r.headers.get('x-mv-elsewhere') !== '1') return r
64
+ lost('elsewhere')
65
+ return stoppedAnswer()
66
+ }, (e: unknown) => {
67
+ // the live socket is gone, so nothing else would say so: a request that reaches nothing stops the page
68
+ if (hmrLost && (e as Error)?.name !== 'AbortError') lost('down')
69
+ throw e
70
+ })
71
+ }
72
+ /** A request under /__mv/api/: `api('boards/main', { method: 'PUT', ... })`. */
73
+ export const api = (path: string, init?: RequestInit) => mvFetch(`${ROUTE}/api/${path}`, init)
74
+
75
+ // ---- the link: losing the canvas, and getting it back --------------------------------------------------
76
+
77
+ /** What must be done before a resumed page reloads (the board save, the heights). Each answers true when
78
+ * the page may reload now; asked again each second while a reload is owed, so each is cheap when there is
79
+ * nothing to do. */
80
+ const flushers = new Set<() => Promise<boolean>>()
81
+ export const beforeResume = (fn: () => Promise<boolean>) => { flushers.add(fn); return () => { flushers.delete(fn) } }
82
+ /** What holds a reload while it answers true: an edit not saved, heights not in the file yet, a capture recording,
83
+ * words typed and not sent. Synchronous, and asked right before the reload, after every flusher has finished - so what a person
84
+ * does while the flushers wait on the server holds it as surely as what was there before they began. */
85
+ const holds = new Set<() => boolean>()
86
+ export const holdsReload = (fn: () => boolean) => { holds.add(fn); return () => { holds.delete(fn) } }
87
+ const held = () => [...holds].some((h) => { try { return h() } catch { return true } })
88
+ /** Asks again whether this tab holds anything only it has (the banner's "unsaved edits"): at a stop, once a
89
+ * second while stopped, and whenever an edit or a word changes it. */
90
+ export function noteUnsaved() {
91
+ if (!WS) return
92
+ const u = held()
93
+ if (u !== useLink.getState().unsaved) useLink.setState({ unsaved: u })
94
+ }
95
+ /** Told when a resumed page stays (a flusher said no): the store's toast, registered by store.ts. */
96
+ let say: (text: string) => void = () => {}
97
+ export const onLinkNotice = (fn: (text: string) => void) => { say = fn }
98
+
99
+ let hmrLost = false
100
+ let probeTimer: ReturnType<typeof setTimeout> | null = null
101
+
102
+ function lost(why: 'down' | 'elsewhere') {
103
+ owed = true
104
+ noteUnsaved()
105
+ if (why === 'elsewhere') useLink.setState({ link: 'elsewhere', shown: true })
106
+ else if (!canvasStopped()) useLink.setState({ link: 'checking' })
107
+ probeTimer ??= setTimeout(probe, 0)
108
+ }
109
+
110
+ /** Once a second while stopped, and while a reload is owed: is this canvas (still) on this address? */
111
+ async function probe() {
112
+ let r: Response | null = null
113
+ // a server that takes the connection and never answers (half up, hung, paused) is no answer: a miss
114
+ try { r = await fetch(`${ROUTE}/api/hello`, { headers: named({}), cache: 'no-store', signal: AbortSignal.timeout(2000) }) } catch { r = null }
115
+ const ours = !!r?.ok && (await r.json().catch(() => null))?.ws === WS
116
+ probeTimer = null
117
+ if (ours) return void resume()
118
+ // another canvas answers, or nothing does, or something that is not a canvas of this one (an older
119
+ // marver says 404): the banner - and keep asking
120
+ noteUnsaved()
121
+ useLink.setState({ link: r?.status === 409 && r.headers.get('x-mv-elsewhere') === '1' ? 'elsewhere' : 'down', shown: true })
122
+ probeTimer = setTimeout(probe, 1000)
123
+ }
124
+
125
+ async function resume() {
126
+ const back = useLink.getState().link !== 'live' // from a stop; 'live' is a page that owes a reload
127
+ if (back) useLink.setState({ link: 'resuming' }) // requests flow again: the flushers use them
128
+ let ok = true
129
+ for (const fn of flushers) ok = (await fn().catch(() => false)) && ok
130
+ const now = useLink.getState().link
131
+ if (now !== 'resuming' && now !== 'live') return // lost again while saving: the probe goes on
132
+ // asked here, with nothing awaited between the answer and the reload: words typed or an edit made while a
133
+ // flusher waited on the server hold it too
134
+ if (ok && held()) ok = false
135
+ // a fresh document on the canvas that answered: live updates again - and the next page says what the resumes came to,
136
+ // this one's and those this reload waited after (a draft, a capture), whose toasts go with this page
137
+ // its own guard lets this reload through: what it held is saved, and nothing holds it (A2.14 #17)
138
+ if (hmrLost && ok) { keepOverReload(lostOnResume ?? (savedOnResume ? 'saved' : null)); return void leaveNow(() => location.reload()) }
139
+ if (back || useLink.getState().shown) useLink.setState({ link: 'live', shown: false })
140
+ // no reload owed (Vite's socket held): the page goes on as it is, and what this resume came to was said on it
141
+ if (!hmrLost) { owed = false; lostOnResume = null; savedOnResume = false; return }
142
+ // Vite's socket never comes back (its client waits on the listener below), so this page owes a reload:
143
+ // until nothing holds it (a capture recording, words not sent) it works as live, keeps asking - a stop
144
+ // is seen again - and reloads the moment it may
145
+ if (back) { say('marver dev is back - this page reloads once nothing is in progress'); unstrand() }
146
+ probeTimer ??= setTimeout(probe, 1000)
147
+ }
148
+
149
+ /** Frames another project answered while this canvas was away show its "another canvas" page, which runs no
150
+ * script - no Vite client to bring them back. A page that stays reloads them in place, on its own canvas. */
151
+ function unstrand() {
152
+ for (const f of document.querySelectorAll('iframe')) if (stranded(f)) f.contentWindow?.location.reload()
153
+ }
154
+ /** Does this frame show another project's "another canvas" page (server/guard.ts)? The shell draws its own quiet
155
+ * placeholder over it: the banner says what happened, once. */
156
+ export function stranded(f: HTMLIFrameElement | null): boolean {
157
+ try { return !!f?.contentDocument?.querySelector('meta[name="mv-elsewhere"]') } catch { return false /* not ours to read */ }
158
+ }
159
+
160
+ // ---- over the resume's own reload: where the person was looking, and what its save came to --------------------
161
+
162
+ /** What the resume's save came to, said by the page after its reload: 'saved' - the board edits only this tab held
163
+ * reached the disk; 'disk' - the board's file changed on disk meanwhile and won, the tab's board edits dropped; 'gone' - the board
164
+ * was renamed or removed meanwhile and is not created again; null - there was nothing to save. */
165
+ export type ResumeOutcome = 'saved' | 'disk' | 'gone' | null
166
+ /** A resume is owed from the stop until the page's own reload - or, Vite's socket held, until the resume that needs
167
+ * none. Every board save that answers meanwhile is what the resumes came to: the resume's own, and as often the
168
+ * ordinary autosave (store.ts, 500 ms after an edit), which can land before any flusher runs - a pass held by a
169
+ * frame in the hand, then the drop's save - and leave the flushers nothing to save. */
170
+ let owed = false
171
+ /** What the resumes came to - the board save's own word, lost or saved - kept until the reload that carries it: a
172
+ * resume whose reload is held (a draft, a capture) is not the last one, and the one that reloads at last may have
173
+ * nothing left to save. Each later save only adds to it - the first loss stays, and a loss outranks a save. A resume
174
+ * that owes no reload (Vite's socket held) ends it. */
175
+ let lostOnResume: 'disk' | 'gone' | null = null
176
+ let savedOnResume = false
177
+ /** A board save, while a resume is owed: what this tab held did not reach the disk (store.ts) - the page after the
178
+ * reload says what happened instead, never that the edits were saved. */
179
+ export function lostInResume(why: 'disk' | 'gone') { if (owed) lostOnResume ??= why }
180
+ /** A board save, while a resume is owed - the resume's or the autosave's: what this tab held reached the disk (store.ts). */
181
+ export function savedInResume() { if (owed) savedOnResume = true }
182
+
183
+ const RESUMED = 'mv-resumed'
184
+ const keepers = new Set<() => Record<string, unknown>>()
185
+ /** What a resumed page carries over its own reload, read back by the next page (the canvas keeps its camera). */
186
+ export const keepOverResume = (fn: () => Record<string, unknown>) => { keepers.add(fn); return () => { keepers.delete(fn) } }
187
+ function keepOverReload(outcome: ResumeOutcome) {
188
+ const rec: Record<string, unknown> = { at: Date.now(), outcome }
189
+ for (const fn of keepers) { try { Object.assign(rec, fn()) } catch { /* the rest still goes */ } }
190
+ try { sessionStorage.setItem(scoped(RESUMED), JSON.stringify(rec)) } catch { /* storage off: the page boots as any other */ }
191
+ }
192
+ const OUTCOMES: readonly ResumeOutcome[] = ['saved', 'disk', 'gone', null]
193
+ /** What the page before this one left when it reloaded itself on its canvas's return - this tab only, read once
194
+ * at load, and only a fresh one (a reload by hand later on boots as any other). `outcome`: what its save came to;
195
+ * the page says so. */
196
+ export const resumed: { outcome: ResumeOutcome; board?: string; camera?: { x: number; y: number; scale: number } } | null = (() => {
197
+ if (!WS) return null
198
+ try {
199
+ const raw = sessionStorage.getItem(scoped(RESUMED))
200
+ if (raw === null) return null
201
+ sessionStorage.removeItem(scoped(RESUMED))
202
+ const r = JSON.parse(raw)
203
+ return r && typeof r.at === 'number' && Date.now() - r.at < 30_000 ? { ...r, outcome: OUTCOMES.includes(r.outcome) ? r.outcome : null } : null
204
+ } catch { return null }
205
+ })()
206
+
207
+ // words a person typed into the page and has not sent (a comment, a Jam edit, a name): a reload would drop them
208
+ const typed = new WeakSet<EventTarget>()
209
+ const TEXT_FIELDS = 'textarea, input:not([type]), input[type=text], input[type=search], input[type=email], input[type=url], input[type=password]'
210
+ if (WS) {
211
+ document.addEventListener('input', (e) => { if (e.target) typed.add(e.target); if (canvasStopped()) noteUnsaved(); workChanged() }, true)
212
+ const typedWords = () => [...document.querySelectorAll<HTMLInputElement | HTMLTextAreaElement>(TEXT_FIELDS)].some((el) => typed.has(el) && el.value.trim() !== '')
213
+ holdsReload(typedWords)
214
+ // and leaving the page asks first (spec 28 A2.9): the words are only here
215
+ unsavedWhen('typing', typedWords)
216
+ }
217
+
218
+ // one question before this page goes, whatever it holds that the server does not have (unsaved.ts): a capture, a
219
+ // board edit, heights, words - in every browser, and the Mac app reads the same reasons. Never in a headless perf run
220
+ // (spec 28 A3.8 #17): its writes are refused, so `heights` would hold for good and block the context's end
221
+ if (typeof window !== 'undefined' && !PERF_RUN) guardLeaving(window)
222
+
223
+ // Vite's client awaits every `vite:ws:disconnect` listener before it pings the server and reloads the
224
+ // page (vite/dist/client/client.mjs, Vite 8). This one never settles: the canvas page is never reloaded by
225
+ // Vite - not into another project that took the port, and not into this one's next run before it has
226
+ // saved what it holds - and its socket stays closed, so no other project's broadcast reaches it. It
227
+ // reloads itself in resume(). Frames keep Vite's own reload: their URLs name the workspace.
228
+ if (WS && import.meta.hot) import.meta.hot.on('vite:ws:disconnect', () => { hmrLost = true; lost('down'); return new Promise<never>(() => {}) })
229
+
230
+ // dev-only inspection hook for tests (never installed in published builds)
231
+ if (WS && import.meta.env.DEV) (window as unknown as { __mvLink: unknown }).__mvLink = useLink
232
+ // and, in a headless perf run only, the page's own way out: a test sends through the barrier as the shell does
233
+ if (PERF_RUN && import.meta.env.DEV) (window as unknown as { __mvApi: unknown }).__mvApi = { api, withWs }