@niccolofanton/corkboard 0.1.0 → 0.2.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.
- package/CHANGELOG.md +96 -1
- package/README.md +47 -136
- package/dist/chunk-CNSKM2Mi.d.ts +2992 -0
- package/dist/chunk-layer-CRDYkQT5.js +7394 -0
- package/dist/chunk-layer-CRDYkQT5.js.map +1 -0
- package/dist/chunk-values-D2mwqJ9D.js +253 -0
- package/dist/chunk-values-D2mwqJ9D.js.map +1 -0
- package/dist/corkboard.js +1156 -7393
- package/dist/corkboard.js.map +1 -1
- package/dist/index.d.ts +2 -1543
- package/dist/unstable.d.ts +336 -0
- package/dist/unstable.js +90 -0
- package/dist/unstable.js.map +1 -0
- package/package.json +10 -3
package/dist/corkboard.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"corkboard.js","sources":["../src/interact/geometry.ts","../src/render/frameRate.ts","../src/video/videoGeometry.ts","../src/embed/geometry.ts","../src/embed/policy.ts","../src/embed/poster.ts","../src/embed/providers.ts","../src/embed/resolve.ts","../src/embed/bootstrap.ts","../src/embed/previewCache.ts","../src/embed/sandbox.ts","../src/render/theme.ts","../src/embed/tile.ts","../src/embed/layer.ts","../src/events.ts","../src/types.ts","../src/math.ts","../src/render/camera.ts","../src/render/lod.ts","../src/interact/outline.ts","../src/render/guides.ts","../src/render/overlay.ts","../src/render/parkTicker.ts","../src/render/atlas.ts","../src/render/lru.ts","../src/render/retire.ts","../src/render/textures.ts","../src/render/views/mediaView.ts","../src/render/views/registry.ts","../src/render/views/pool.ts","../src/render/stage.ts","../src/interact/handles.ts","../src/interact/hitTest.ts","../src/interact/marquee.ts","../src/interact/resize.ts","../src/interact/snapping.ts","../src/interact/snap.ts","../src/interact/controller.ts","../src/layout/masonry.ts","../src/layout/stats.ts","../src/layout/order.ts","../src/layout/placement.ts","../src/layout/align.ts","../src/layout/autoSpot.ts","../src/layout/tidy.ts","../src/LayoutApi.ts","../src/model.ts","../src/store/Store.ts","../src/video/reveal.ts","../src/video/video.ts","../src/video/ambientPolicy.ts","../src/video/ambient.ts","../src/video/videoPolicy.ts","../src/video/videoController.ts","../src/video/layer.ts","../src/Corkboard.ts"],"sourcesContent":["// World-space geometry of elements: the one place that knows how (x, y, w, h, rot) turn into\n// rectangles, AABBs (the rbush entries) and point tests. Pure; shared by the store (index), the\n// renderer, hit testing, snapping and layout.\n//\n// Convention (types.ts): `rot` is degrees clockwise about the element's centre.\nimport type { Element } from '../types';\n\n// rbush-compatible box.\nexport interface Box {\n minX: number;\n minY: number;\n maxX: number;\n maxY: number;\n}\n\nexport interface WorldRect {\n x: number;\n y: number;\n w: number;\n h: number;\n rot: number;\n}\n\nexport const DEG = Math.PI / 180;\n\nexport const emptyBox = (): Box => ({\n minX: Infinity,\n minY: Infinity,\n maxX: -Infinity,\n maxY: -Infinity,\n});\nexport const boxW = (b: Box): number => b.maxX - b.minX;\nexport const boxH = (b: Box): number => b.maxY - b.minY;\nexport const boxCx = (b: Box): number => (b.minX + b.maxX) / 2;\nexport const boxCy = (b: Box): number => (b.minY + b.maxY) / 2;\n\nexport function boxesIntersect(a: Box, b: Box): boolean {\n return a.minX <= b.maxX && a.maxX >= b.minX && a.minY <= b.maxY && a.maxY >= b.minY;\n}\nexport function boxContains(outer: Box, inner: Box): boolean {\n return (\n outer.minX <= inner.minX &&\n outer.minY <= inner.minY &&\n outer.maxX >= inner.maxX &&\n outer.maxY >= inner.maxY\n );\n}\nexport function boxUnion(a: Box, b: Box): Box {\n return {\n minX: Math.min(a.minX, b.minX),\n minY: Math.min(a.minY, b.minY),\n maxX: Math.max(a.maxX, b.maxX),\n maxY: Math.max(a.maxY, b.maxY),\n };\n}\nexport function boxGrow(b: Box, by: number): Box {\n return { minX: b.minX - by, minY: b.minY - by, maxX: b.maxX + by, maxY: b.maxY + by };\n}\nexport function boxOfRect(r: { x: number; y: number; w: number; h: number }): Box {\n return { minX: r.x, minY: r.y, maxX: r.x + r.w, maxY: r.y + r.h };\n}\n\nexport function worldRectOf(el: Pick<Element, 'x' | 'y' | 'w' | 'h' | 'rot'>): WorldRect {\n return { x: el.x, y: el.y, w: el.w, h: el.h, rot: el.rot };\n}\n\nexport function rotatedExtent(w: number, h: number, rotDeg: number): { w: number; h: number } {\n if (rotDeg === 0) return { w, h };\n const a = rotDeg * DEG;\n const c = Math.abs(Math.cos(a));\n const s = Math.abs(Math.sin(a));\n return { w: w * c + h * s, h: w * s + h * c };\n}\n\n// World AABB of an element (rotation included).\nexport function elementBox(el: Pick<Element, 'x' | 'y' | 'w' | 'h' | 'rot'>): Box {\n const r = worldRectOf(el);\n const cx = r.x + r.w / 2;\n const cy = r.y + r.h / 2;\n const e = rotatedExtent(r.w, r.h, r.rot);\n return { minX: cx - e.w / 2, minY: cy - e.h / 2, maxX: cx + e.w / 2, maxY: cy + e.h / 2 };\n}\n\n// The four corners of a world rect, clockwise from the top-left: [x0, y0, x1, y1, x2, y2, x3, y3].\nexport function corners(r: WorldRect): number[] {\n const cx = r.x + r.w / 2;\n const cy = r.y + r.h / 2;\n const hw = r.w / 2;\n const hh = r.h / 2;\n const a = r.rot * DEG;\n const c = Math.cos(a);\n const s = Math.sin(a);\n const pts: number[] = [];\n for (const [dx, dy] of [\n [-hw, -hh],\n [hw, -hh],\n [hw, hh],\n [-hw, hh],\n ]) {\n pts.push(cx + dx * c - dy * s, cy + dx * s + dy * c);\n }\n return pts;\n}\n\n// A world point expressed in the rect's own (unrotated, origin at its top-left) frame.\nexport function toRectLocal(r: WorldRect, px: number, py: number): { x: number; y: number } {\n const cx = r.x + r.w / 2;\n const cy = r.y + r.h / 2;\n const a = -r.rot * DEG;\n const c = Math.cos(a);\n const s = Math.sin(a);\n const dx = px - cx;\n const dy = py - cy;\n return { x: dx * c - dy * s + r.w / 2, y: dx * s + dy * c + r.h / 2 };\n}\n\n// Rect-local -> world.\nexport function fromRectLocal(r: WorldRect, lx: number, ly: number): { x: number; y: number } {\n const cx = r.x + r.w / 2;\n const cy = r.y + r.h / 2;\n const a = r.rot * DEG;\n const c = Math.cos(a);\n const s = Math.sin(a);\n const dx = lx - r.w / 2;\n const dy = ly - r.h / 2;\n return { x: cx + dx * c - dy * s, y: cy + dx * s + dy * c };\n}\n\n// `tol` grows the rect on every side (world px).\nexport function pointInRotatedRect(r: WorldRect, px: number, py: number, tol = 0): boolean {\n const l = toRectLocal(r, px, py);\n return l.x >= -tol && l.y >= -tol && l.x <= r.w + tol && l.y <= r.h + tol;\n}\n\n// Squared distance from (px, py) to the segment (ax, ay)-(bx, by).\nexport function distSqToSegment(\n px: number,\n py: number,\n ax: number,\n ay: number,\n bx: number,\n by: number,\n): number {\n const dx = bx - ax;\n const dy = by - ay;\n const len2 = dx * dx + dy * dy;\n let t = len2 === 0 ? 0 : ((px - ax) * dx + (py - ay) * dy) / len2;\n t = t < 0 ? 0 : t > 1 ? 1 : t;\n const qx = ax + t * dx - px;\n const qy = ay + t * dy - py;\n return qx * qx + qy * qy;\n}\n\n// Separating-axis test between two rotated rects (touching counts).\nexport function rotatedRectsIntersect(a: WorldRect, b: WorldRect): boolean {\n const ca = corners(a);\n const cb = corners(b);\n const axes: number[][] = [];\n for (const c of [ca, cb]) {\n for (let i = 0; i < 2; i++) {\n const x0 = c[i * 2];\n const y0 = c[i * 2 + 1];\n const x1 = c[((i + 1) % 4) * 2];\n const y1 = c[((i + 1) % 4) * 2 + 1];\n axes.push([-(y1 - y0), x1 - x0]);\n }\n }\n for (const [ax, ay] of axes) {\n let minA = Infinity;\n let maxA = -Infinity;\n let minB = Infinity;\n let maxB = -Infinity;\n for (let i = 0; i < 4; i++) {\n const pa = ca[i * 2] * ax + ca[i * 2 + 1] * ay;\n const pb = cb[i * 2] * ax + cb[i * 2 + 1] * ay;\n if (pa < minA) minA = pa;\n if (pa > maxA) maxA = pa;\n if (pb < minB) minB = pb;\n if (pb > maxB) maxB = pb;\n }\n if (maxA < minB || maxB < minA) return false;\n }\n return true;\n}\n\n// True when `box` intersects the (possibly rotated) rect.\nexport function boxIntersectsRotatedRect(box: Box, r: WorldRect): boolean {\n return rotatedRectsIntersect(\n { x: box.minX, y: box.minY, w: box.maxX - box.minX, h: box.maxY - box.minY, rot: 0 },\n r,\n );\n}\n\n// True when the (possibly rotated) rect lies entirely inside `box`.\nexport function rotatedRectInsideBox(r: WorldRect, box: Box): boolean {\n const c = corners(r);\n for (let i = 0; i < 4; i++) {\n const x = c[i * 2];\n const y = c[i * 2 + 1];\n if (x < box.minX || x > box.maxX || y < box.minY || y > box.maxY) return false;\n }\n return true;\n}\n","// FrameRateMonitor: measures how fast the page really renders, shared by everything that sheds load when it\n// does not keep up (the embed layer's animating budget and freezing, the ambient video pool).\n//\n// A rAF loop that never stops keeps the page awake for nothing, so it samples in BURSTS: one is started (or\n// extended) by `poke()`, which the consumers call on any event that can change the load (the camera settled,\n// frames mounted / destroyed / frozen, a budget moved, the video pool changed), and again by a heartbeat every\n// HEARTBEAT_MS while any consumer has something rendering. A burst ends after BURST_WINDOWS windows, or as soon\n// as AGREE_WINDOWS in a row say the same (slow, smooth or neither): the reading is stable and the loop stops.\n// A poke inside a burst starts its count over, so a consumer that keeps changing things keeps being measured.\n//\n// fps is read over windows of SAMPLE_WINDOW_MS. The first window of a burst started by an event does not count\n// (it sees frames mounting), nor does one that follows a stall (a hidden page). A window is `slow` under\n// SLOW_FPS and `smooth` over SMOOTH_FPS; both are for a 60 Hz display and scale down with the fastest window\n// seen, so a 30 Hz (low power) screen is judged against its own rate.\n\nexport const SAMPLE_WINDOW_MS = 1000;\nexport const SLOW_FPS = 40;\nexport const SMOOTH_FPS = 55;\n// Windows in a row over SMOOTH_FPS that consumers take as \"room to give something back\".\nexport const SMOOTH_WINDOWS = 2;\nconst REFERENCE_HZ = 60;\n// A gap between two frames this long is a hidden or occluded page, not a slow one: the window is dropped.\nconst STALL_MS = 2500;\n// A burst: at most this many counted windows, or until this many in a row agree.\nexport const BURST_WINDOWS = 4;\nexport const AGREE_WINDOWS = 2;\n// While anything renders, a burst starts at least this often even if nothing happened.\nexport const HEARTBEAT_MS = 10_000;\n\nexport interface FrameWindow {\n fps: number;\n // Under SLOW_FPS (scaled to the display).\n slow: boolean;\n // Over SMOOTH_FPS (scaled to the display).\n smooth: boolean;\n}\n\nexport interface FrameRateDeps {\n // The frame scheduler (default: the window's). A seam for tests; the callback gets the frame's timestamp,\n // which is the only clock the monitor reads.\n raf?: (cb: (time: number) => void) => number;\n caf?: (id: number) => void;\n // For the page's visibility (a hidden tab does not paint: nothing is measured). Default: the global one.\n doc?: Document;\n burstWindows?: number;\n agreeWindows?: number;\n heartbeatMs?: number;\n}\n\ninterface Run {\n id: number;\n // Timestamp of the window's start and of the last frame (NaN: no frame yet), and frames since the start.\n start: number;\n last: number;\n frames: number;\n // The window in progress does not count.\n discard: boolean;\n // Frame intervals of the window in progress: their fast end is the display's refresh rate.\n deltas: number[];\n}\n\nexport class FrameRateMonitor {\n private readonly rafFn: ((cb: (time: number) => void) => number) | undefined;\n private readonly cafFn: ((id: number) => void) | undefined;\n private readonly doc: Document | undefined;\n private readonly burstWindows: number;\n private readonly agreeWindows: number;\n private readonly heartbeatMs: number;\n private run: Run | null = null;\n private readonly loads = new Set<() => boolean>();\n private readonly windowFns = new Set<(w: FrameWindow) => void>();\n private readonly startFns = new Set<() => void>();\n // Counted windows of the burst, and how many in a row had the same verdict.\n private counted = 0;\n private streak = 0;\n private verdict: 'slow' | 'smooth' | 'mid' | null = null;\n private beat: ReturnType<typeof setTimeout> | null = null;\n private peakFps = 0;\n private disposed = false;\n private readonly cleanups: (() => void)[] = [];\n\n constructor(deps: FrameRateDeps = {}) {\n const doc = deps.doc ?? (typeof document !== 'undefined' ? document : undefined);\n const win = doc?.defaultView ?? (typeof window !== 'undefined' ? window : undefined);\n this.doc = doc;\n this.rafFn = deps.raf ?? (win ? (cb) => win.requestAnimationFrame(cb) : undefined);\n this.cafFn = deps.caf ?? (win ? (id) => win.cancelAnimationFrame(id) : undefined);\n this.burstWindows = deps.burstWindows ?? BURST_WINDOWS;\n this.agreeWindows = deps.agreeWindows ?? AGREE_WINDOWS;\n this.heartbeatMs = deps.heartbeatMs ?? HEARTBEAT_MS;\n if (doc) {\n // A hidden tab stops the burst; back, a fresh one measures from scratch.\n const onVisibility = (): void => this.poke();\n doc.addEventListener('visibilitychange', onVisibility);\n this.cleanups.push(() => doc.removeEventListener('visibilitychange', onVisibility));\n }\n }\n\n // A burst is sampling now.\n get running(): boolean {\n return this.run !== null;\n }\n\n // The fastest the display has shown it can go (fps; 0: not known yet).\n get peak(): number {\n return this.peakFps;\n }\n\n // A consumer says whether it has anything rendering that load could slow down. Bursts (and the heartbeat)\n // only run while at least one does. Returns the unsubscribe.\n load(fn: () => boolean): () => void {\n this.loads.add(fn);\n return () => {\n this.loads.delete(fn);\n };\n }\n\n // Called once per counted window. Returns the unsubscribe.\n onWindow(fn: (w: FrameWindow) => void): () => void {\n this.windowFns.add(fn);\n return () => {\n this.windowFns.delete(fn);\n };\n }\n\n // Called when a burst starts afresh: windows before it are no \"in a row\" with the ones to come.\n onStart(fn: () => void): () => void {\n this.startFns.add(fn);\n return () => {\n this.startFns.delete(fn);\n };\n }\n\n // Something that can change the load happened (or may have: a consumer's load can also have gone). Starts a\n // burst, or extends the one running; stops one that has nothing left to measure.\n poke(): void {\n if (this.disposed) return;\n if (!this.canRun()) {\n this.stop();\n this.clearBeat();\n return;\n }\n if (this.run) {\n this.counted = 0;\n this.streak = 0;\n this.verdict = null;\n } else this.start(true);\n this.armBeat();\n }\n\n dispose(): void {\n if (this.disposed) return;\n this.disposed = true;\n this.stop();\n this.clearBeat();\n for (const f of this.cleanups) f();\n this.loads.clear();\n this.windowFns.clear();\n this.startFns.clear();\n }\n\n private canRun(): boolean {\n if (!this.rafFn || this.doc?.visibilityState === 'hidden') return false;\n for (const l of this.loads) if (l()) return true;\n return false;\n }\n\n // The heartbeat: a burst even if nothing happened, while something renders.\n private armBeat(): void {\n if (this.beat !== null || !Number.isFinite(this.heartbeatMs)) return;\n this.beat = setTimeout(() => {\n this.beat = null;\n if (this.disposed) return;\n if (!this.canRun()) return this.stop();\n // Nothing is mounting: the first window is as good as the rest.\n if (!this.run) this.start(false);\n this.armBeat();\n }, this.heartbeatMs);\n }\n\n private clearBeat(): void {\n if (this.beat !== null) clearTimeout(this.beat);\n this.beat = null;\n }\n\n private start(discardFirst: boolean): void {\n const raf = this.rafFn;\n if (!raf) return;\n const s: Run = { id: 0, start: Number.NaN, last: Number.NaN, frames: 0, discard: discardFirst, deltas: [] };\n this.run = s;\n this.counted = 0;\n this.streak = 0;\n this.verdict = null;\n for (const f of [...this.startFns]) f();\n const tick = (ts: number): void => {\n if (this.run !== s) return;\n if (Number.isNaN(s.start) || ts - s.last > STALL_MS) {\n // A stall saw nothing: that window is dropped, and so is the one in progress after it.\n if (!Number.isNaN(s.start)) s.discard = true;\n s.start = ts;\n s.frames = 0;\n s.deltas.length = 0;\n } else {\n s.frames++;\n s.deltas.push(ts - s.last);\n if (ts - s.start >= SAMPLE_WINDOW_MS) {\n const fps = (s.frames * 1000) / (ts - s.start);\n const skip = s.discard;\n s.start = ts;\n s.frames = 0;\n s.discard = false;\n // Every window, discarded or not, tells how fast this display can go: rAF is aligned to vsync, so\n // even a loaded page has some frames one refresh apart. The 10th percentile ignores a stray double tick.\n this.peakFps = Math.max(this.peakFps, fps, refreshOf(s.deltas));\n s.deltas.length = 0;\n if (!skip) this.window(fps);\n }\n }\n s.last = ts;\n // A consumer may have stopped it.\n if (this.run === s) s.id = raf(tick);\n };\n s.id = raf(tick);\n }\n\n private stop(): void {\n const s = this.run;\n if (!s) return;\n this.run = null;\n this.cafFn?.(s.id);\n }\n\n private window(fps: number): void {\n // A slower display (30 Hz low power) lowers the bar; a faster one does not raise it: 40 fps on a 120 Hz\n // screen is still slow, and 60 is smooth enough to give frames back.\n const k = Math.min(1, (this.peakFps > 0 ? this.peakFps : REFERENCE_HZ) / REFERENCE_HZ);\n const w: FrameWindow = { fps, slow: fps < SLOW_FPS * k, smooth: fps > SMOOTH_FPS * k };\n const verdict = w.slow ? 'slow' : w.smooth ? 'smooth' : 'mid';\n this.counted++;\n this.streak = verdict === this.verdict ? this.streak + 1 : 1;\n this.verdict = verdict;\n // A consumer that changes something pokes: the count starts over and the burst goes on.\n for (const f of [...this.windowFns]) f(w);\n if (this.run && (this.counted >= this.burstWindows || this.streak >= this.agreeWindows)) this.stop();\n }\n}\n\n// The refresh rate a window's frame intervals show (0: too few to tell), at most 240 Hz.\nfunction refreshOf(deltas: readonly number[]): number {\n if (deltas.length < 10) return 0;\n const d = [...deltas].sort((a, b) => a - b)[Math.floor(deltas.length * 0.1)];\n return d > 0 ? Math.min(240, 1000 / d) : 0;\n}\n","// Where the video overlay's <video> goes on screen, from the card it covers: pure maths, no DOM, shared\n// by the overlay and its tests.\n//\n// The <video> is laid out ONCE at the card's world size (`width` / `height` in world px, origin 0 0) and\n// moved by `transform` alone: translate(rotated top-left on screen) scale(camera) rotate(card). A card\n// rotates about the centre of its box, so its top-left corner is first rotated about that centre, in\n// world space, to find where it lands; the element then rotates about that corner (its transform\n// origin). The result covers exactly the rect the card's sprite draws, at any zoom, pan, rotation and\n// device pixel ratio (the transform is CSS px, like the sprite).\nimport type { Camera } from '../math';\nimport { DEG } from '../interact/geometry';\n\nexport interface VideoRect {\n // World px: the card's box (x / y is the top-left of the UNROTATED box) and its rotation in degrees.\n x: number;\n y: number;\n w: number;\n h: number;\n rot?: number;\n}\n\nexport interface VideoPlacement {\n // CSS px, relative to the overlay root: where the rotated top-left corner lands.\n x: number;\n y: number;\n // The camera's scale and the card's rotation in degrees (0 when it is not rotated).\n scale: number;\n rot: number;\n // Where the box's centre lands: what a badge on the card centres on.\n cx: number;\n cy: number;\n // The `transform` to write on the <video>.\n transform: string;\n}\n\nconst round3 = (v: number): number => Math.round(v * 1000) / 1000;\nconst round6 = (v: number): number => Math.round(v * 1e6) / 1e6;\n\nexport function videoPlacement(r: VideoRect, camera: Camera): VideoPlacement {\n const rot = r.rot ?? 0;\n const wcx = r.x + r.w / 2;\n const wcy = r.y + r.h / 2;\n let ox = r.x;\n let oy = r.y;\n if (rot !== 0) {\n const a = rot * DEG;\n const c = Math.cos(a);\n const s = Math.sin(a);\n const dx = r.x - wcx;\n const dy = r.y - wcy;\n ox = wcx + dx * c - dy * s;\n oy = wcy + dx * s + dy * c;\n }\n const x = round3(camera.tx + ox * camera.scale);\n const y = round3(camera.ty + oy * camera.scale);\n const scale = round6(camera.scale);\n const rotR = round6(rot);\n return {\n x,\n y,\n scale,\n rot: rotR,\n cx: round3(camera.tx + wcx * camera.scale),\n cy: round3(camera.ty + wcy * camera.scale),\n transform:\n `translate(${x}px, ${y}px) scale(${scale})` + (rotR === 0 ? '' : ` rotate(${rotR}deg)`),\n };\n}\n","// Where a live iframe goes on screen. Pure maths, shared by the layer and its tests.\n//\n// Like the video overlay (src/video/videoGeometry.ts) the iframe is laid out ONCE and moved by `transform`\n// alone, so the page inside re-rasterises at the camera's scale and stays sharp. The layout box is a virtual\n// screen (`EmbedResolution`: 720p by default) with the card's aspect, so a page renders its desktop layout\n// whatever the card's world size; 'native' lays it out at the world size instead. The long side never goes\n// past MAX_LAYOUT_PX, to bound the raster memory (a very tall snippet is laid out smaller).\nimport type { Camera } from '../math';\nimport type { EmbedResolution } from '../types';\nimport { videoPlacement, type VideoRect } from '../video/videoGeometry';\n\nexport const MAX_LAYOUT_PX = 4096;\nexport const DEFAULT_RESOLUTION: EmbedResolution = '720p';\n\n// The short side of the layout box in CSS px, or null for 'native' (the card's world size).\nexport function resolutionShortSide(res: EmbedResolution): number | null {\n if (res === 'native') return null;\n if (res === '720p') return 720;\n if (res === '1080p') return 1080;\n return Number.isFinite(res) && res > 0 ? res : 720;\n}\n\nexport interface EmbedPlacement {\n // CSS px: the layout box of the iframe wrapper (the virtual screen, or the world size for 'native').\n width: number;\n height: number;\n // CSS px relative to the overlay root: where the rotated top-left corner lands.\n x: number;\n y: number;\n // Where the box's centre lands.\n cx: number;\n cy: number;\n // The rotated top-right corner on screen (where the \"Done\" button hangs).\n topRightX: number;\n topRightY: number;\n transform: string;\n}\n\nconst round3 = (v: number): number => Math.round(v * 1000) / 1000;\nconst round6 = (v: number): number => Math.round(v * 1e6) / 1e6;\n\nexport function embedPlacement(\n r: VideoRect,\n camera: Camera,\n resolution: EmbedResolution = DEFAULT_RESOLUTION,\n): EmbedPlacement {\n const p = videoPlacement(r, camera);\n // Layout px per world px.\n const short = resolutionShortSide(resolution);\n const want = short === null ? 1 : short / Math.max(Math.min(r.w, r.h), 1);\n const f = Math.min(want, MAX_LAYOUT_PX / Math.max(r.w, r.h, 1));\n const scale = round6(camera.scale / f);\n const a = ((r.rot ?? 0) * Math.PI) / 180;\n // The top-right corner is `w` along the box's x axis from the top-left, on screen `w * k` long.\n const topRightX = round3(p.x + r.w * camera.scale * Math.cos(a));\n const topRightY = round3(p.y + r.w * camera.scale * Math.sin(a));\n return {\n width: round3(r.w * f),\n height: round3(r.h * f),\n x: p.x,\n y: p.y,\n cx: p.cx,\n cy: p.cy,\n topRightX,\n topRightY,\n transform:\n `translate(${p.x}px, ${p.y}px) scale(${scale})` + (p.rot === 0 ? '' : ` rotate(${p.rot}deg)`),\n };\n}\n","// Which embed cards hold a mounted iframe? Pure rules, shared by the layer and its tests. No DOM, no timers.\n//\n// Two tiers, plus a state a parked card can be in:\n// ACTIVE a card is on screen, at least `minW` x `minH` CSS px big (or selected, at any size above a\n// minimum zoom), and the camera is still. (The layer passes 0 for both: any card in view.) At most `max` at once. A card that is active keeps its\n// place against newcomers (an LRU by last focus), and a selected one always wins. Only active cards\n// are ever newly mounted.\n// PARKED a card that is already mounted, can still be framed and is not active: too small, too far out,\n// partly or wholly off screen, or out of the `max` budget. Its iframe stays mounted but inert and\n// keeps showing its last frame, because a cross-origin page cannot be screenshotted to a poster. A\n// card that has been live is never swapped back to its preview just for being small.\n// CULLED a parked card that is off screen (outside the viewport grown by a margin, see layer.ts). The layer\n// hides it (`display: none`) so it stops rendering, but the document stays alive and comes back as it\n// was. Culled cards are bounded by `maxOffscreen`, most recently seen first.\n// Parked cards are bounded by `maxMounted` (active + parked): on overflow the least valuable parked ones are\n// destroyed (off screen first, then least recently used) and only then does the poster show again.\n\nexport const MAX_LIVE_DESKTOP = 12;\nexport const MAX_LIVE_TOUCH = 3;\n// Mounted iframes in total (active + parked).\nexport const MAX_MOUNTED_DESKTOP = 24;\nexport const MAX_MOUNTED_TOUCH = 6;\n// Culled (off screen) iframes kept alive, a subset of the mounted ones.\nexport const MAX_OFFSCREEN_DESKTOP = 64;\nexport const MAX_OFFSCREEN_TOUCH = 12;\nexport const MIN_LIVE_W = 320;\nexport const MIN_LIVE_H = 200;\n// Below this zoom nothing mounts, selected or not.\nexport const MIN_LIVE_SCALE = 0.25;\n// A live card is kept until it shrinks under this fraction of the size that earned it the iframe, so a\n// card hovering around the threshold does not flicker between poster and iframe.\nexport const KEEP_FACTOR = 0.6;\n\nexport interface PolicyCard {\n id: string;\n // CSS px on screen: the part of the card that is in view.\n screenW: number;\n screenH: number;\n // In view or inside the cull margin (the layer grows the viewport by it). screenW/screenH stay the truly\n // visible part: negative when the card is only in the margin, so such a card is never eligible.\n onScreen: boolean;\n selected: boolean;\n // In interact mode: always kept, ahead of everything.\n interacting: boolean;\n // False: a bookmark (the page refuses framing, or there is nothing to load).\n frameable: boolean;\n live: boolean;\n // Last time the card was selected, interacted with or mounted (ms; larger = more recent).\n lastUsed: number;\n // Last time the card was on screen (larger = more recent); orders the off-screen ones. Falls back to lastUsed.\n lastSeen?: number;\n}\n\nexport interface PolicyInput {\n cards: readonly PolicyCard[];\n // Pan, zoom or pinch in progress: nothing changes until it settles.\n cameraMoving: boolean;\n // Camera scale.\n scale: number;\n // Active cap (Infinity: no cap).\n max: number;\n // Mounted cap, active + parked (default 3 x max; Infinity: no cap).\n maxMounted?: number;\n // Off-screen mounted cards kept (culled), within maxMounted (default maxMounted; Infinity: no extra cap).\n maxOffscreen?: number;\n minW?: number;\n minH?: number;\n minScale?: number;\n}\n\nexport interface PolicyPlan {\n mount: string[];\n destroy: string[];\n // Ids that are mounted and parked once the plan is applied (the rest of the mounted ones are active).\n parked: string[];\n // ... of which these are off screen (the layer keeps them hidden). Always a subset of `parked`.\n culled: string[];\n}\n\nexport function isEligible(c: PolicyCard, scale: number, o: Pick<PolicyInput, 'minW' | 'minH' | 'minScale'>): boolean {\n if (!c.frameable || !c.onScreen) return false;\n // Only in the cull margin: not in view.\n if (c.screenW < 0 || c.screenH < 0) return false;\n if (scale < (o.minScale ?? MIN_LIVE_SCALE)) return false;\n if (c.interacting || c.selected) return true;\n const k = c.live ? KEEP_FACTOR : 1;\n return c.screenW >= (o.minW ?? MIN_LIVE_W) * k && c.screenH >= (o.minH ?? MIN_LIVE_H) * k;\n}\n\nexport function planLive(input: PolicyInput): PolicyPlan {\n const plan: PolicyPlan = { mount: [], destroy: [], parked: [], culled: [] };\n if (input.cameraMoving) return plan;\n const max = Math.max(0, Math.floor(input.max));\n const maxMounted = Math.max(0, Math.floor(input.maxMounted ?? max * 3));\n const eligible = input.cards.filter((c) => isEligible(c, input.scale, input));\n eligible.sort(\n (a, b) =>\n Number(b.interacting) - Number(a.interacting) ||\n Number(b.selected) - Number(a.selected) ||\n Number(b.live) - Number(a.live) ||\n b.lastUsed - a.lastUsed ||\n b.screenW * b.screenH - a.screenW * a.screenH ||\n (a.id < b.id ? -1 : 1),\n );\n const active = new Set(eligible.slice(0, max).map((c) => c.id));\n // Whatever is mounted, frameable and not active is a parking candidate, at any size, zoom or position.\n const candidates = input.cards.filter((c) => c.live && c.frameable && !active.has(c.id));\n const room = Math.max(0, maxMounted - active.size);\n const maxOffscreen = Math.max(0, Math.floor(input.maxOffscreen ?? maxMounted));\n // On screen ones first, as they were; they are never limited by maxOffscreen.\n const onScreen = candidates.filter((c) => c.onScreen);\n onScreen.sort(\n (a, b) =>\n b.lastUsed - a.lastUsed || b.screenW * b.screenH - a.screenW * a.screenH || (a.id < b.id ? -1 : 1),\n );\n // Off screen: the most recently seen stay, up to maxOffscreen and what is left of maxMounted.\n const offScreen = candidates.filter((c) => !c.onScreen);\n offScreen.sort(\n (a, b) =>\n (b.lastSeen ?? b.lastUsed) - (a.lastSeen ?? a.lastUsed) ||\n b.lastUsed - a.lastUsed ||\n b.screenW * b.screenH - a.screenW * a.screenH ||\n (a.id < b.id ? -1 : 1),\n );\n const parkedOn = onScreen.slice(0, room);\n const culled = new Set(offScreen.slice(0, Math.min(maxOffscreen, room - parkedOn.length)).map((c) => c.id));\n const parked = new Set([...parkedOn.map((c) => c.id), ...culled]);\n for (const c of input.cards) {\n if (active.has(c.id)) {\n if (!c.live) plan.mount.push(c.id);\n } else if (parked.has(c.id)) {\n plan.parked.push(c.id);\n if (culled.has(c.id)) plan.culled.push(c.id);\n } else if (c.live) plan.destroy.push(c.id);\n }\n return plan;\n}\n","// Fetches a poster so it is certain to be usable as a WebGL texture: read with CORS, a real image, big\n// enough to be one. The result is a blob URL the decode worker can fetch (and that the layer revokes).\n\nexport const MIN_POSTER_PX = 160;\n\n// null: not readable (no CORS, 404, not an image, or a placeholder thumbnail).\nexport async function fetchPoster(url: string, timeoutMs = 8000): Promise<string | null> {\n const ctl = new AbortController();\n const timer = setTimeout(() => ctl.abort(), timeoutMs);\n try {\n const res = await fetch(url, { mode: 'cors', credentials: 'omit', signal: ctl.signal });\n if (!res.ok) return null;\n const blob = await res.blob();\n if (!blob.type.startsWith('image/')) return null;\n if (typeof createImageBitmap === 'function') {\n const bmp = await createImageBitmap(blob);\n const ok = bmp.width >= MIN_POSTER_PX;\n bmp.close();\n if (!ok) return null;\n }\n return URL.createObjectURL(blob);\n } catch {\n return null;\n } finally {\n clearTimeout(timer);\n }\n}\n","// URL parsing and provider recognition for `embed` cards. Pure: no DOM, no network.\n//\n// A pasted URL becomes a `ParsedEmbed`: the iframe URL to load live (`youtube.com/watch?v=x` ->\n// `youtube-nocookie.com/embed/x`), the poster candidates that need no server, and the shape of the card.\n// What cannot be known here (oEmbed titles, og:image, `X-Frame-Options`) belongs to the host's `resolve`\n// option, on a server (see EmbedResolver in resolve.ts).\n\nexport type EmbedProvider = 'youtube' | 'vimeo' | 'spotify' | 'codepen' | 'figma' | 'generic';\n\nexport interface ParsedEmbed {\n // The URL as the card keeps it: https, no credentials.\n url: string;\n // Host without `www.`, for the generated tile.\n host: string;\n provider: EmbedProvider;\n // What the iframe loads when the card goes live.\n iframeSrc: string;\n // height / width of the card for this provider, when it has a natural one.\n aspect?: number;\n // Poster URLs that need no server, best first (each must be CORS-readable; the layer probes them).\n posters: string[];\n // A human label for the tile (\"YouTube\").\n label: string;\n}\n\nexport const PROVIDER_LABEL: Record<EmbedProvider, string> = {\n youtube: 'YouTube',\n vimeo: 'Vimeo',\n spotify: 'Spotify',\n codepen: 'CodePen',\n figma: 'Figma',\n generic: 'Web page',\n};\n\nconst LOCAL_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']);\n\n// Only http(s) URLs without credentials. `http:` is upgraded to `https:` except on localhost (dev) and on\n// an explicit port (a LAN or dev server there has no TLS). `javascript:`, `data:`, `file:`, `blob:` and the\n// rest are refused.\nexport function normalizeEmbedUrl(raw: string): string | null {\n let u: URL;\n try {\n u = new URL(raw.trim());\n } catch {\n return null;\n }\n if (u.protocol === 'http:' && !LOCAL_HOSTS.has(u.hostname) && u.port === '') u.protocol = 'https:';\n if (u.protocol !== 'https:' && u.protocol !== 'http:') return null;\n if (u.username !== '' || u.password !== '') return null;\n return u.toString();\n}\n\nconst stripWww = (h: string): string => h.replace(/^www\\./, '');\n\n// `90`, `90s`, `1m30s`, `1h2m3s` -> seconds.\nexport function parseTimestamp(t: string | null): number | null {\n if (!t) return null;\n if (/^\\d+$/.test(t)) return Number(t);\n const m = /^(?:(\\d+)h)?(?:(\\d+)m)?(?:(\\d+)s)?$/.exec(t);\n if (!m || (m[1] === undefined && m[2] === undefined && m[3] === undefined)) return null;\n return Number(m[1] ?? 0) * 3600 + Number(m[2] ?? 0) * 60 + Number(m[3] ?? 0);\n}\n\nconst YT_ID = /^[\\w-]{11}$/;\n// Path words that are 11 word characters long, so they look like a video id.\nconst YT_PATH_WORDS = new Set(['videoseries', 'live_stream']);\n// A playlist or channel id: word characters and dashes only, so it is safe in the iframe URL.\nconst YT_LIST = /^[\\w-]+$/;\nconst YT_HOSTS = new Set([\n 'youtube.com',\n 'm.youtube.com',\n 'music.youtube.com',\n 'youtube-nocookie.com',\n 'youtu.be',\n]);\n\nconst ytParam = (u: URL, name: string): string | null => {\n const v = u.searchParams.get(name);\n return v !== null && YT_LIST.test(v) ? v : null;\n};\n\nconst ytEmbed = (path: string, params: Record<string, string>): string => {\n const q = new URLSearchParams(params).toString();\n return `https://www.youtube-nocookie.com/embed/${path}` + (q ? `?${q}` : '');\n};\n\nfunction parseYouTube(u: URL, host: string): Omit<ParsedEmbed, 'url' | 'host' | 'label'> | null {\n if (!YT_HOSTS.has(host)) return null;\n const parts = u.pathname.split('/').filter(Boolean);\n // A playlist or a live stream has no video id: `embed/videoseries?list=` and `embed/live_stream?channel=`.\n // No ytimg poster either (there is no id to ask for): the card gets the generated tile.\n if (host !== 'youtu.be' && parts[0] === 'embed' && YT_PATH_WORDS.has(parts[1] ?? '')) {\n const series = parts[1] === 'videoseries';\n const value = ytParam(u, series ? 'list' : 'channel');\n if (value === null) return null;\n return {\n provider: 'youtube',\n iframeSrc: ytEmbed(parts[1], series ? { list: value } : { channel: value }),\n aspect: 9 / 16,\n posters: [],\n };\n }\n let id: string | null = null;\n if (host === 'youtu.be') id = parts[0] ?? null;\n else if (parts[0] === 'watch') id = u.searchParams.get('v');\n else if (['embed', 'shorts', 'live', 'v'].includes(parts[0] ?? '')) id = parts[1] ?? null;\n if (id === null || !YT_ID.test(id) || YT_PATH_WORDS.has(id)) return null;\n const start = parseTimestamp(u.searchParams.get('t') ?? u.searchParams.get('start'));\n // A video watched inside a playlist keeps the playlist.\n const list = ytParam(u, 'list');\n const params: Record<string, string> = {};\n if (list !== null) params.list = list;\n if (start) params.start = String(start);\n return {\n provider: 'youtube',\n iframeSrc: ytEmbed(id, params),\n aspect: 9 / 16,\n // maxresdefault (1280x720) is missing on some videos; mqdefault (320x180) is always there and, unlike\n // hqdefault, has no letterbox bars.\n posters: [\n `https://i.ytimg.com/vi/${id}/maxresdefault.jpg`,\n `https://i.ytimg.com/vi/${id}/mqdefault.jpg`,\n ],\n };\n}\n\n// Pages that list videos: a bare one (no `video` segment) is not a video.\nconst VIMEO_LISTS = new Set(['showcase', 'album', 'event']);\n\nfunction parseVimeo(u: URL, host: string): Omit<ParsedEmbed, 'url' | 'host' | 'label'> | null {\n if (host !== 'vimeo.com' && host !== 'player.vimeo.com') return null;\n const parts = u.pathname.split('/').filter(Boolean);\n const isId = (p: string | undefined): boolean => p !== undefined && /^\\d+$/.test(p);\n // The digits after `video` / `videos` (`showcase/987/video/123`, `player.vimeo.com/video/123`), else the\n // first number (`123`, `channels/staffpicks/123`) unless the page is a showcase, album or event.\n const v = parts.findIndex((p) => p === 'video' || p === 'videos');\n let i = -1;\n if (v >= 0) i = isId(parts[v + 1]) ? v + 1 : -1;\n else if (!VIMEO_LISTS.has(parts[0] ?? '')) i = parts.findIndex(isId);\n if (i < 0) return null;\n const id = parts[i];\n // An unlisted video carries a hash: `vimeo.com/ID/HASH` or `?h=HASH`.\n const next = parts[i + 1];\n // Only hex goes into the iframe URL: `?h=abc&autoplay=1` or anything else a link carries is dropped.\n const q = u.searchParams.get('h');\n const hash = q !== null && /^[0-9a-f]+$/i.test(q) ? q : next && /^[0-9a-f]{8,}$/i.test(next) ? next : null;\n return {\n provider: 'vimeo',\n iframeSrc:\n `https://player.vimeo.com/video/${id}` + (hash ? `?${new URLSearchParams({ h: hash }).toString()}` : ''),\n aspect: 9 / 16,\n posters: [],\n };\n}\n\nconst SPOTIFY_TYPES = new Set(['track', 'album', 'playlist', 'episode', 'show', 'artist']);\n\nfunction parseSpotify(u: URL, host: string): Omit<ParsedEmbed, 'url' | 'host' | 'label'> | null {\n if (host !== 'open.spotify.com') return null;\n let parts = u.pathname.split('/').filter(Boolean);\n // `/intl-it/track/ID` and `/embed/track/ID`.\n if (parts[0]?.startsWith('intl-')) parts = parts.slice(1);\n if (parts[0] === 'embed') parts = parts.slice(1);\n const [type, id] = parts;\n if (!type || !SPOTIFY_TYPES.has(type) || !id || !/^[A-Za-z0-9]{22}$/.test(id)) return null;\n const compact = type === 'track' || type === 'episode';\n return {\n provider: 'spotify',\n iframeSrc: `https://open.spotify.com/embed/${type}/${id}`,\n // The player is 152 px (compact) or 352 px tall at any width; 400 px is the card's default width.\n aspect: compact ? 152 / 400 : 352 / 400,\n posters: [],\n };\n}\n\nfunction parseCodePen(u: URL, host: string): Omit<ParsedEmbed, 'url' | 'host' | 'label'> | null {\n if (host !== 'codepen.io') return null;\n let parts = u.pathname.split('/').filter(Boolean);\n let team = '';\n if (parts[0] === 'team') {\n team = 'team/';\n parts = parts.slice(1);\n }\n const [user, kind, id] = parts;\n if (!user || !id || !['pen', 'full', 'details', 'embed', 'debug'].includes(kind ?? '')) return null;\n if (!/^[A-Za-z0-9]+$/.test(id)) return null;\n return {\n provider: 'codepen',\n iframeSrc: `https://codepen.io/${team}${user}/embed/${id}?default-tab=result`,\n aspect: 5 / 8,\n posters: [],\n };\n}\n\nfunction parseFigma(u: URL, host: string): Omit<ParsedEmbed, 'url' | 'host' | 'label'> | null {\n if (host !== 'figma.com') return null;\n if (u.pathname === '/embed') return null;\n const kind = u.pathname.split('/').filter(Boolean)[0];\n if (!kind || !['file', 'design', 'proto', 'board', 'slides', 'deck'].includes(kind)) return null;\n return {\n provider: 'figma',\n iframeSrc: `https://www.figma.com/embed?embed_host=corkboard&url=${encodeURIComponent(u.toString())}`,\n aspect: 3 / 4,\n posters: [],\n };\n}\n\nconst PARSERS = [parseYouTube, parseVimeo, parseSpotify, parseCodePen, parseFigma];\n\n// null: not an http(s) URL. Any other URL parses as `generic` (loaded as is, with the stricter sandbox).\nexport function parseEmbedUrl(raw: string): ParsedEmbed | null {\n const url = normalizeEmbedUrl(raw);\n if (url === null) return null;\n const u = new URL(url);\n const host = stripWww(u.hostname);\n for (const parse of PARSERS) {\n const hit = parse(u, host);\n if (hit) return { ...hit, url, host, label: PROVIDER_LABEL[hit.provider] };\n }\n return {\n url,\n host,\n provider: 'generic',\n iframeSrc: url,\n posters: [],\n label: PROVIDER_LABEL.generic,\n };\n}\n\n// The provider that SERVES an iframe URL, by its host and path. The sandbox profile follows this and never\n// what a card claims, so a resolver (or a tampered board) cannot name an arbitrary page \"youtube\". Only the\n// embed URLs the parsers above emit are listed: the same host's other paths (`youtube.com/redirect?q=...`)\n// are arbitrary pages.\nconst ALLOWLIST: readonly { host: string; path: RegExp; provider: EmbedProvider }[] = [\n { host: 'www.youtube-nocookie.com', path: /^\\/embed\\//, provider: 'youtube' },\n { host: 'player.vimeo.com', path: /^\\/video\\//, provider: 'vimeo' },\n { host: 'open.spotify.com', path: /^\\/embed\\//, provider: 'spotify' },\n { host: 'codepen.io', path: /^\\/(?:team\\/)?[^/]+\\/embed\\//, provider: 'codepen' },\n { host: 'www.figma.com', path: /^\\/embed$/, provider: 'figma' },\n];\n\nexport function providerOfIframeSrc(src: string): EmbedProvider {\n try {\n const u = new URL(src);\n if (u.protocol !== 'https:') return 'generic';\n return ALLOWLIST.find((r) => r.host === u.hostname && r.path.test(u.pathname))?.provider ?? 'generic';\n } catch {\n return 'generic';\n }\n}\n\n// The iframe URL of a video provider, set to start playing on its own and muted (browsers only let a muted\n// page autoplay), inline on iOS and looping. YouTube needs `playlist=<id>` to loop a single video; a\n// `list` the URL already carries is kept instead. Vimeo keeps its unlisted-video `h` hash. Any other\n// provider (or a URL that does not parse) comes back as is. Pure; the stored embed info is never touched.\nexport function withAutoplay(provider: EmbedProvider, src: string): string {\n if (provider !== 'youtube' && provider !== 'vimeo') return src;\n let u: URL;\n try {\n u = new URL(src);\n } catch {\n return src;\n }\n const q = u.searchParams;\n if (provider === 'vimeo') {\n q.set('autoplay', '1');\n q.set('muted', '1');\n q.set('loop', '1');\n } else {\n const word = u.pathname.split('/')[2] ?? '';\n q.set('autoplay', '1');\n q.set('mute', '1');\n q.set('playsinline', '1');\n // A live stream has nothing to loop.\n if (word !== 'live_stream') q.set('loop', '1');\n if (word !== 'videoseries' && word !== 'live_stream' && !q.has('list')) q.set('playlist', word);\n }\n return u.toString();\n}\n\n// A YouTube iframe URL with its postMessage API on (`enablejsapi=1`, plus `origin` when the page's is an\n// http(s) one: the player ignores commands from a page it cannot match). The layer pauses and resumes the\n// player with it. Vimeo's player takes its commands without a flag; any other provider (or a URL that does\n// not parse) comes back as is. Pure; the stored embed info is never touched.\nexport function withJsApi(provider: EmbedProvider, src: string, origin?: string): string {\n if (provider !== 'youtube') return src;\n let u: URL;\n try {\n u = new URL(src);\n } catch {\n return src;\n }\n u.searchParams.set('enablejsapi', '1');\n if (origin !== undefined && /^https?:\\/\\//.test(origin)) u.searchParams.set('origin', origin);\n return u.toString();\n}\n\nexport const isAllowlisted = (p: EmbedProvider): boolean => p !== 'generic';\n","// What is known about an embed card, and how a host's `resolve` option adds to it. Pure.\n//\n// The library does what needs no server: it recognises a few providers by URL (providers.ts). Everything\n// that does need one belongs to the host, behind `EmbedResolver`:\n// - oEmbed (`thumbnail_url`, `title`, the real size of a Vimeo video),\n// - `og:image` of an arbitrary page,\n// - a screenshot (headless Chromium) for pages with neither,\n// - whether the page may be framed at all (`X-Frame-Options`, CSP `frame-ancestors`): the browser cannot\n// tell, a cross-origin iframe reports neither `onload` nor `onerror` honestly.\n// All of it should be cached and the poster re-hosted CORS-enabled (a WebGL texture needs CORS).\nimport type { EmbedSource } from '../types';\nimport {\n normalizeEmbedUrl,\n parseEmbedUrl,\n PROVIDER_LABEL,\n type EmbedProvider,\n} from './providers';\n\n// What a resolver may tell about a URL. Every field is optional; what it leaves out stays as the library\n// derived it.\nexport interface EmbedInfo {\n // A CORS-readable image URL for the poster.\n poster?: string;\n // The URL to load in the iframe, when it is not the card's `url` (an oEmbed `iframe` src, say).\n iframeSrc?: string;\n // height / width of the card.\n aspect?: number;\n title?: string;\n // false: the page refuses framing. The card is a bookmark: it never goes live, and a double-click opens\n // the URL in a new tab.\n frameable?: boolean;\n}\n\n// Example (a Cloudflare Worker that caches oEmbed / og:image / framing headers per URL):\n//\n// resolve: async (url) => {\n// const r = await fetch(`/api/embed-info?url=${encodeURIComponent(url)}`);\n// return r.ok ? ((await r.json()) as EmbedInfo) : null;\n// }\nexport type EmbedResolver = (url: string) => Promise<EmbedInfo | null | undefined> | EmbedInfo | null | undefined;\n\n// Everything the layer knows about a card's embed, settled.\nexport interface ResolvedEmbed {\n kind: 'url' | 'html';\n provider: EmbedProvider;\n // The card's URL (normalised), or '' for a snippet.\n url: string;\n host: string;\n // What the tile says: the provider, else the host; the title if there is one.\n label: string;\n title?: string;\n // The URL to load live. null: the card cannot go live (not an http(s) URL) or is a snippet.\n iframeSrc: string | null;\n frameable: boolean;\n aspect?: number;\n // Poster candidates, best first.\n posters: string[];\n}\n\n// The synchronous part: what the URL alone says.\nexport function baseResolved(embed: EmbedSource): ResolvedEmbed {\n if (embed.html !== undefined) {\n return {\n kind: 'html',\n provider: 'generic',\n url: '',\n host: 'html',\n label: 'HTML',\n title: embed.title,\n iframeSrc: null,\n frameable: true,\n posters: [],\n };\n }\n const parsed = parseEmbedUrl(embed.url ?? '');\n if (!parsed) {\n return {\n kind: 'url',\n provider: 'generic',\n url: '',\n host: 'invalid URL',\n label: 'Invalid URL',\n title: embed.title,\n iframeSrc: null,\n frameable: false,\n posters: [],\n };\n }\n return {\n kind: 'url',\n provider: parsed.provider,\n url: parsed.url,\n host: parsed.host,\n label: parsed.provider === 'generic' ? parsed.host : PROVIDER_LABEL[parsed.provider],\n title: embed.title,\n iframeSrc: parsed.iframeSrc,\n frameable: true,\n aspect: parsed.aspect,\n posters: parsed.posters,\n };\n}\n\nconst finitePositive = (n: unknown): n is number => typeof n === 'number' && Number.isFinite(n) && n > 0;\n\n// A resolver's answer over the base. Untrusted: an `iframeSrc` that is not an http(s) URL is ignored, a\n// resolver cannot make a snippet frameable or a card load something the URL parser refused.\nexport function mergeResolved(base: ResolvedEmbed, info: EmbedInfo | null | undefined): ResolvedEmbed {\n if (!info || base.kind === 'html') return base;\n const out: ResolvedEmbed = { ...base };\n if (typeof info.title === 'string' && info.title !== '') out.title = base.title ?? info.title;\n if (finitePositive(info.aspect)) out.aspect = info.aspect;\n if (typeof info.iframeSrc === 'string' && out.iframeSrc !== null) {\n const src = normalizeEmbedUrl(info.iframeSrc);\n if (src !== null) out.iframeSrc = src;\n }\n if (info.frameable === false) out.frameable = false;\n if (typeof info.poster === 'string' && info.poster !== '') {\n out.posters = [info.poster, ...base.posters.filter((p) => p !== info.poster)];\n }\n return out;\n}\n\n// Can the card go live?\nexport const canGoLive = (r: ResolvedEmbed): boolean =>\n r.frameable && (r.kind === 'html' || r.iframeSrc !== null);\n\n// Do two embeds describe the same content? (A card whose embed did not change keeps its poster and its live\n// frame.) The title and the resolution are labels, not content.\nexport const sameEmbed = (a: EmbedSource, b: EmbedSource): boolean => a.url === b.url && a.html === b.html;\n","// The script injected at the top of every snippet's `srcdoc`, before the author's HTML, and the protocol the\n// layer speaks to it. The frame has an opaque origin, so messages go both ways with `postMessage`; the script\n// only listens to its parent (`event.source === parent`), the layer only to the frame it mounted.\n//\n// layer -> frame { cb, op: 'pause' } pause CSS / Web animations and hold requestAnimationFrame,\n// setTimeout and setInterval\n// { cb, op: 'resume' }\n// { cb, op: 'snapshot', id, vw, vh } the document at its CURRENT state, as SVG markup; vw x vh is\n// the size it is laid out at, for when the window reports 0\n// frame -> layer { cb, op: 'snapshot', id, ok, svg? }\n//\n// The snapshot clones the document (its stylesheets come along), bakes in the current value of whatever\n// CSS / Web animations and transitions are changing, turns canvases into images, and returns the SVG\n// `<foreignObject>` markup; the layer draws it onto a canvas (the parent is never throttled). The CSP of the\n// frame already allows what that needs: inline scripts (`script-src 'unsafe-inline'`) and `data:` images\n// (`img-src data:`), so it is not loosened.\n\nexport const EMBED_CB = 'corkboard-embed';\n\n// Longest side of a snapshot, in px.\nexport const SNAPSHOT_MAX_SIDE = 640;\n// The layer gives up on a frame's answer after this long (a busy page delays the messages, not the work).\nexport const SNAPSHOT_MS = 4000;\n\nexport type EmbedOp = 'pause' | 'resume' | 'snapshot';\n\n// Written readable below; shipped without its whole-line comments and indentation (it goes into every snippet).\nconst SOURCE = `(function () {\nvar CB = '${EMBED_CB}';\nvar raf = window.requestAnimationFrame.bind(window), caf = window.cancelAnimationFrame.bind(window);\nvar paused = false, n = 0, pend = {}, hand = {}, stopped = [];\nvar st = window.setTimeout.bind(window), ct = window.clearTimeout.bind(window);\nvar si = window.setInterval.bind(window), ci = window.clearInterval.bind(window);\nvar tm = {}, tn = 0, held = [];\n\n// requestAnimationFrame behind a gate: while paused, callbacks wait and run on resume.\nfunction sched(id) {\n hand[id] = raf(function (t) { var f = pend[id]; delete hand[id]; delete pend[id]; f(t); });\n}\nwindow.requestAnimationFrame = function (f) {\n var id = ++n;\n pend[id] = f;\n if (!paused) sched(id);\n return id;\n};\nwindow.cancelAnimationFrame = function (id) {\n if (hand[id] !== undefined) caf(hand[id]);\n delete hand[id];\n delete pend[id];\n};\n\n// setTimeout / setInterval behind the same gate: a callback that falls due while paused waits and runs once on\n// resume (an interval then goes on with its own schedule). The ids are ours; either clear accepts them.\nfunction timer(set, clear, again) {\n return function (f, ms) {\n if (typeof f !== 'function') return set.apply(window, arguments);\n var args = [].slice.call(arguments, 2), t = { id: ++tn, held: false, clear: clear };\n t.go = function () {\n if (!again) delete tm[t.id];\n f.apply(window, args);\n };\n t.h = set(function () {\n if (!paused) t.go();\n else if (!t.held) { t.held = true; held.push(t); }\n }, ms);\n tm[t.id] = t;\n return t.id;\n };\n}\nfunction untimer(id) {\n var t = tm[id];\n if (!t) return ct(id);\n delete tm[id];\n t.held = false;\n t.clear(t.h);\n}\nwindow.setTimeout = timer(st, ct, false);\nwindow.setInterval = timer(si, ci, true);\nwindow.clearTimeout = window.clearInterval = untimer;\n\nfunction setPaused(p) {\n if (p === paused) return;\n paused = p;\n var id;\n if (p) {\n for (id in hand) { caf(hand[id]); delete hand[id]; }\n stopped = document.getAnimations().filter(function (a) { return a.playState === 'running'; });\n stopped.forEach(function (a) { a.pause(); });\n } else {\n for (id in pend) if (hand[id] === undefined) sched(id);\n stopped.forEach(function (a) { if (a.playState === 'paused') a.play(); });\n stopped = [];\n held.splice(0).forEach(function (t) {\n if (!t.held) return;\n t.held = false;\n st(function () { if (tm[t.id] === t) t.go(); }, 0);\n });\n }\n}\n\n// The clone keeps the stylesheets: bake only what animations change (all computed styles took seconds).\nfunction animated() {\n var m = new Map();\n document.getAnimations().forEach(function (a) {\n var ef = a.effect;\n if (!ef || !ef.target || ef.pseudoElement || !ef.getKeyframes) return;\n var s = m.get(ef.target) || new Set();\n if (a.transitionProperty) s.add(a.transitionProperty);\n ef.getKeyframes().forEach(function (k) {\n for (var p in k) {\n if (p === 'offset' || p === 'easing' || p === 'composite' || p === 'computedOffset') continue;\n s.add(p === 'cssFloat' ? 'float' : p.replace(/[A-Z]/g, function (c) { return '-' + c.toLowerCase(); }));\n }\n });\n m.set(ef.target, s);\n });\n return m;\n}\n\n// Canvases become data: URLs; network images stay blank (unreadable here). Scripts go.\nfunction bake(o, c, props) {\n var tag = o.tagName, css = '', cs;\n if (tag === 'SCRIPT') return c.remove();\n if (props) {\n cs = getComputedStyle(o);\n props.forEach(function (p) { css += p + ':' + cs.getPropertyValue(p) + ';'; });\n c.setAttribute('style', (c.getAttribute('style') || '') + ';' + css);\n }\n if (tag === 'CANVAS') {\n cs = cs || getComputedStyle(o);\n var im = document.createElement('img');\n im.src = o.toDataURL(); // throws on a tainted canvas: no snapshot rather than a blank one\n im.setAttribute('style', (c.getAttribute('style') || '') + ';width:' + cs.width + ';height:' + cs.height +\n ';display:' + cs.display);\n c.replaceWith(im);\n }\n}\n\n// The SVG markup of the document as it is now. Rasterising happens in the parent: a small frame is\n// throttled by the browser, and an image decode or toBlob in it can wait for seconds.\nfunction snapshot(vw, vh) {\n var de = document.documentElement, W = innerWidth || vw, H = innerHeight || vh;\n if (!(W > 0 && H > 0)) return null;\n var from = [de].concat([].slice.call(de.querySelectorAll('*')));\n var clone = de.cloneNode(true);\n var to = [clone].concat([].slice.call(clone.querySelectorAll('*')));\n if (from.length !== to.length || from.length > 3000) return null;\n var anim = animated();\n for (var i = 0; i < from.length; i++) bake(from[i], to[i], anim.get(from[i]));\n clone.style.width = W + 'px';\n clone.style.height = H + 'px';\n var st = document.createElement('style');\n st.textContent = '*,*::before,*::after{animation:none!important;transition:none!important}';\n (clone.querySelector('head') || clone).appendChild(st);\n return '<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"' + W + '\" height=\"' + H + '\">' +\n '<foreignObject width=\"100%\" height=\"100%\">' + new XMLSerializer().serializeToString(clone) +\n '</foreignObject></svg>';\n}\n\n// A page with no background of its own would show the card's poster through it: give it the white a\n// browser tab would. A colour or an image on the root or the body (a gradient) wins.\naddEventListener('DOMContentLoaded', function () {\n function bare(el) {\n if (!el) return true;\n var cs = getComputedStyle(el), c = cs.backgroundColor;\n return cs.backgroundImage === 'none' && (c === 'transparent' || /^rgba\\(.*,\\s*0\\)$/.test(c));\n }\n if (bare(document.documentElement) && bare(document.body)) document.documentElement.style.backgroundColor = '#fff';\n});\n\naddEventListener('message', function (e) {\n var d = e.data;\n if (e.source !== parent || !d || d.cb !== CB) return;\n if (d.op === 'pause') setPaused(true);\n else if (d.op === 'resume') setPaused(false);\n else if (d.op === 'snapshot') {\n var svg = null;\n try { svg = snapshot(d.vw, d.vh); } catch (err) { svg = null; }\n // The parent's origin is known from its message; an opaque one cannot be a target.\n parent.postMessage({ cb: CB, op: 'snapshot', id: d.id, ok: !!svg, svg: svg || undefined }, e.origin === 'null' ? '*' : e.origin);\n }\n});\n})();`;\n\nexport const SNIPPET_BOOTSTRAP = SOURCE.replace(/^[ \\t]*\\/\\/.*\\n/gm, '').replace(/^[ \\t]+/gm, '');\n\n","// Where the previews of snippet cards are kept, so a snippet is rendered once: an in-memory map shared by\n// the layer, and optionally the Cache Storage API, which survives a reload (opt-in: it leaves pictures of\n// the visitor's snippets on disk). Nothing else is ever stored.\n//\n// A preview is keyed by a hash of what decides its picture: the snippet's HTML, the aspect it is laid out at\n// (bucketed), the virtual screen and the size it is drawn at.\n\nexport const PREVIEW_CACHE_NAME = 'corkboard-previews-v1';\n// Previews kept in memory (the oldest go first). A preview is a few tens of KB.\nexport const PREVIEW_MEMORY_MAX = 400;\n// Previews kept in Cache Storage. Past this the oldest are deleted, in the order `Cache.keys()` returns them,\n// which is insertion order in Chromium (the other engines are not relied on: there the cap still holds, but\n// the entries dropped may not be the oldest).\nexport const PREVIEW_PERSIST_MAX = 1000;\n\nexport type PreviewCacheMode = 'memory' | 'persistent';\n\n// FNV-1a over UTF-16 code units. Two runs with different offset bases give 64 bits, so two snippets are\n// not taken for each other by chance.\nexport function hashString(s: string): string {\n let a = 0x811c9dc5;\n let b = 0x01000193 ^ 0x9e3779b9;\n for (let i = 0; i < s.length; i++) {\n const c = s.charCodeAt(i);\n a = Math.imul(a ^ c, 0x01000193);\n b = Math.imul(b ^ c, 0x01000193);\n }\n return (a >>> 0).toString(16).padStart(8, '0') + (b >>> 0).toString(16).padStart(8, '0');\n}\n\nexport function previewKey(html: string, bucket: number, resolution: string, w: number, h: number): string {\n return hashString(`${resolution}|${bucket}|${w}x${h}|${html}`);\n}\n\nexport class PreviewStore {\n private readonly memory = new Map<string, Blob>();\n // null: Cache Storage is not usable here (private mode, file://, no support): memory only from then on.\n private cache: Promise<Cache | null> | null = null;\n // Entries in Cache Storage as far as this page knows: counted when it was opened, then +1 per write.\n private stored = 0;\n\n constructor(public mode: PreviewCacheMode) {}\n\n // Whether `getPersistent` can find anything.\n get persistent(): boolean {\n return this.mode === 'persistent' && typeof caches !== 'undefined';\n }\n\n getMemory(key: string): Blob | undefined {\n const b = this.memory.get(key);\n if (b) {\n // Recently used stays.\n this.memory.delete(key);\n this.memory.set(key, b);\n }\n return b;\n }\n\n async getPersistent(key: string): Promise<Blob | null> {\n try {\n const cache = await this.open();\n const res = await cache?.match(urlOf(key));\n const blob = res ? await res.blob() : null;\n return blob && blob.size > 0 ? blob : null;\n } catch {\n return null;\n }\n }\n\n // `persist`: also write it to Cache Storage (not when it came from there).\n put(key: string, blob: Blob, persist = true): void {\n this.memory.delete(key);\n this.memory.set(key, blob);\n while (this.memory.size > PREVIEW_MEMORY_MAX) this.memory.delete(this.memory.keys().next().value as string);\n if (persist && this.mode === 'persistent') void this.putPersistent(key, blob);\n }\n\n clear(): void {\n this.memory.clear();\n }\n\n private async putPersistent(key: string, blob: Blob): Promise<void> {\n try {\n const cache = await this.open();\n if (!cache) return;\n await cache.put(urlOf(key), new Response(blob, { headers: { 'content-type': blob.type || 'image/webp' } }));\n if (++this.stored > PREVIEW_PERSIST_MAX) await this.trim(cache);\n } catch {\n // Quota, private mode: the preview just is not kept.\n }\n }\n\n private open(): Promise<Cache | null> {\n if (this.cache === null) {\n this.cache = (async () => {\n try {\n const cache = typeof caches === 'undefined' ? null : await caches.open(PREVIEW_CACHE_NAME);\n if (cache) await this.trim(cache);\n return cache;\n } catch {\n return null;\n }\n })();\n }\n return this.cache;\n }\n\n // Deletes the oldest entries past the cap. A cache that cannot list or delete is still a cache.\n private async trim(cache: Cache): Promise<void> {\n try {\n const keys = await cache.keys();\n const excess = keys.length - PREVIEW_PERSIST_MAX;\n for (let i = 0; i < excess; i++) await cache.delete(keys[i]);\n this.stored = Math.min(keys.length, PREVIEW_PERSIST_MAX);\n } catch {\n // Not listable: no cap, as before.\n }\n }\n}\n\n// A same-origin URL that only names the entry; nothing is ever fetched from it.\nconst urlOf = (key: string): string => new URL(`/__corkboard_preview/${key}`, location.href).href;\n","// The iframe attributes of a live embed. Pure. The profile is computed at render time from what the card\n// holds and the host that serves the iframe, and is never stored in the board: a tampered or shared board\n// cannot escalate it.\nimport type { EmbedSource } from '../types';\nimport { SNIPPET_BOOTSTRAP } from './bootstrap';\nimport { normalizeEmbedUrl, providerOfIframeSrc, type EmbedProvider } from './providers';\n\nexport type SandboxProfile = 'provider' | 'arbitrary' | 'snippet';\n\n// Allowlisted providers: they run their player (scripts, their own origin's storage), post forms, open\n// popups and go presentation mode.\nexport const SANDBOX_PROVIDER =\n 'allow-scripts allow-same-origin allow-forms allow-popups allow-presentation';\n// Any other URL: the same minus presentation.\n//\n// `allow-same-origin` is kept here on purpose: many sites break without their own cookies and storage.\n// The risk: the sandbox flags survive navigation inside the frame, so a link the user follows in interact\n// mode loads the next site with scripts AND its real origin (cookies, storage, credentialed requests to\n// its own server). It never reaches the board's page (another origin; a frame on the app's own origin loses\n// the flag, see `appOrigin`). `embeds.arbitrarySameOrigin: false` drops the flag for every arbitrary URL\n// (opaque origin: no cookies, no storage), at the cost of the sites that need them.\nexport const SANDBOX_ARBITRARY = 'allow-scripts allow-same-origin allow-forms allow-popups';\n// User HTML: scripts only. No `allow-same-origin` (the frame gets an opaque origin: no cookies, no storage,\n// no parent DOM), no forms, no popups.\nexport const SANDBOX_SNIPPET = 'allow-scripts';\n\n// Never granted, whatever the profile: allow-top-navigation*, allow-modals, allow-pointer-lock,\n// allow-downloads, allow-popups-to-escape-sandbox.\n\nexport const SNIPPET_CSP =\n \"default-src 'none'; img-src data: https:; style-src 'unsafe-inline'; script-src 'unsafe-inline'; font-src https: data:\";\n\nexport const REFERRER_POLICY = 'strict-origin-when-cross-origin';\n\nconst MEDIA_ALLOW = 'autoplay; encrypted-media; fullscreen; picture-in-picture';\nconst ALLOW: Record<EmbedProvider, string> = {\n youtube: MEDIA_ALLOW,\n vimeo: MEDIA_ALLOW,\n // Audio: full playback needs EME, there is no picture to pop out.\n spotify: 'autoplay; encrypted-media',\n codepen: '',\n figma: '',\n generic: '',\n};\n\nexport interface IframeSpec {\n profile: SandboxProfile;\n provider: EmbedProvider;\n // Exactly one of the two.\n src?: string;\n srcdoc?: string;\n sandbox: string;\n // The Permissions-Policy `allow` attribute (it also covers fullscreen: no `allowfullscreen` attribute).\n // Empty: nothing delegated.\n allow: string;\n referrerPolicy: typeof REFERRER_POLICY;\n loading: 'lazy';\n title: string;\n}\n\n// `<!doctype html>` and the CSP `<meta>` come first so nothing in the snippet is parsed before the policy.\n// A snippet cannot loosen it (several policies only intersect), nor can it unset the sandbox.\n// Then the bootstrap (bootstrap.ts: pause / resume / snapshot for the layer), which runs before the snippet's\n// own scripts so it can gate requestAnimationFrame. The CSP already allows inline scripts, so it is unchanged.\nexport function snippetDocument(html: string): string {\n return (\n `<!doctype html><meta http-equiv=\"Content-Security-Policy\" content=\"${SNIPPET_CSP}\">` +\n `<meta charset=\"utf-8\"><script>${SNIPPET_BOOTSTRAP}</script>${html}`\n );\n}\n\nconst originOf = (u: string): string | null => {\n try {\n return new URL(u).origin;\n } catch {\n return null;\n }\n};\n\nexport interface IframeInput {\n source: EmbedSource;\n // The URL to load, when it is not `source.url` (the provider's embed URL, or a resolver's).\n iframeSrc?: string;\n // The origin of the page hosting the board: a frame on it never gets `allow-same-origin`.\n appOrigin?: string;\n // Keep `allow-same-origin` on arbitrary URLs (default true). See SANDBOX_ARBITRARY.\n arbitrarySameOrigin?: boolean;\n}\n\n// null: nothing safe to load (not an http(s) URL).\nexport function iframeSpecFor(input: IframeInput): IframeSpec | null {\n const { source } = input;\n const title = source.title ?? (source.url !== undefined ? 'Embedded page' : 'Embedded HTML');\n if (source.html !== undefined) {\n return {\n profile: 'snippet',\n provider: 'generic',\n srcdoc: snippetDocument(source.html),\n sandbox: SANDBOX_SNIPPET,\n allow: '',\n referrerPolicy: REFERRER_POLICY,\n loading: 'lazy',\n title,\n };\n }\n const src = normalizeEmbedUrl(input.iframeSrc ?? source.url ?? '');\n if (src === null) return null;\n const provider = providerOfIframeSrc(src);\n const allowlisted = provider !== 'generic';\n let sandbox = allowlisted ? SANDBOX_PROVIDER : SANDBOX_ARBITRARY;\n if (!allowlisted && input.arbitrarySameOrigin === false) sandbox = sandbox.replace(' allow-same-origin', '');\n // `allow-scripts` + `allow-same-origin` on the app's own origin lets the frame remove its sandbox.\n if (input.appOrigin !== undefined && originOf(src) === input.appOrigin) {\n sandbox = sandbox.replace(' allow-same-origin', '');\n }\n const allow = ALLOW[provider];\n return {\n profile: allowlisted ? 'provider' : 'arbitrary',\n provider,\n src,\n sandbox,\n allow,\n referrerPolicy: REFERRER_POLICY,\n loading: 'lazy',\n title,\n };\n}\n","// Canvas colours. Pass a `Theme` to `Corkboard.create` / `board.setTheme`; `DARK_THEME` and `LIGHT_THEME`\n// are ready-made.\n\nexport interface Theme {\n dark: boolean;\n // Canvas background (also the WebGL clear colour).\n canvas: number;\n // Background dots and their opacity (kept low: the grid is a quiet guide, not a pattern).\n dot: number;\n dotAlpha?: number;\n // Hairline around a card: baked into the textures, so a theme change rebuilds them.\n border: number;\n borderAlpha: number;\n // Selection outline, handles and marquee.\n accent: number;\n // Placeholder of a card whose picture has not landed yet and that has no ThumbHash or `color`.\n well: number;\n // Smart guides (alignment lines, spacing and size measures) and the label on their pills. Their own\n // warm hue, apart from the accent of the selection, tuned for contrast on each canvas; the mode's\n // default when absent.\n guide?: number;\n onGuide?: number;\n}\n\n// Rose on the dark canvas (#0f0f0f, contrast 5.1:1), a deeper magenta on the light one (#f4f4f2,\n// 4.5:1): a hairline in either reads at a glance, and the white semibold pill labels stay legible.\nexport const GUIDE_DARK = 0xf23a6a;\nexport const GUIDE_LIGHT = 0xd61f5f;\n\nexport function guideColor(theme: Theme): number {\n return theme.guide ?? (theme.dark ? GUIDE_DARK : GUIDE_LIGHT);\n}\n\nexport const DARK_THEME: Theme = {\n dark: true,\n canvas: 0x0f0f0f,\n dot: 0xffffff,\n dotAlpha: 0.0805,\n border: 0xffffff,\n borderAlpha: 0.1,\n accent: 0x6aa6ff,\n well: 0x1c1c1c,\n guide: GUIDE_DARK,\n onGuide: 0xffffff,\n};\n\nexport const LIGHT_THEME: Theme = {\n dark: false,\n canvas: 0xf4f4f2,\n dot: 0x000000,\n dotAlpha: 0.1035,\n border: 0x000000,\n borderAlpha: 0.1,\n accent: 0x2f6bff,\n well: 0xe8e8e4,\n guide: GUIDE_LIGHT,\n onGuide: 0xffffff,\n};\n\nexport function parseHex(s: string): number | null {\n const m = /^#([0-9a-f]{6})$/i.exec(s);\n return m ? parseInt(m[1], 16) : null;\n}\n\nexport const cssHex = (n: number): string => `#${n.toString(16).padStart(6, '0')}`;\n","// The generated poster of an embed with no picture: a themed tile with the host, the title and a glyph,\n// drawn on a canvas. `tileSpec` (pure) decides what it says; `drawTile` paints it.\nimport type { Theme } from '../render/theme';\nimport { cssHex } from '../render/theme';\nimport type { ResolvedEmbed } from './resolve';\n\nexport type TileGlyph = 'play' | 'music' | 'code' | 'design' | 'globe' | 'link-off';\n\nexport interface TileSpec {\n glyph: TileGlyph;\n // Top line (provider or host), small caps.\n label: string;\n // The main text; may be empty.\n title: string;\n // 0..359, from the host: the same site always gets the same colour.\n hue: number;\n}\n\nexport function hostHue(host: string): number {\n let h = 2166136261;\n for (let i = 0; i < host.length; i++) {\n h ^= host.charCodeAt(i);\n h = Math.imul(h, 16777619);\n }\n return (h >>> 0) % 360;\n}\n\nconst GLYPH: Record<ResolvedEmbed['provider'], TileGlyph> = {\n youtube: 'play',\n vimeo: 'play',\n spotify: 'music',\n codepen: 'code',\n figma: 'design',\n generic: 'globe',\n};\n\nexport function tileSpec(r: ResolvedEmbed): TileSpec {\n let glyph: TileGlyph = r.kind === 'html' ? 'code' : GLYPH[r.provider];\n if (r.kind === 'url' && r.iframeSrc === null) glyph = 'link-off';\n else if (r.kind === 'url' && !r.frameable && r.provider === 'generic') glyph = 'link-off';\n const title =\n r.title ?? (r.kind === 'html' ? 'HTML snippet' : r.provider === 'generic' ? pathOf(r.url) : '');\n return { glyph, label: r.label, title, hue: hostHue(r.host) };\n}\n\nfunction pathOf(url: string): string {\n try {\n const u = new URL(url);\n const p = decodeURIComponent(u.pathname).replace(/^\\/+|\\/+$/g, '');\n return p === '' ? '' : p.replace(/[_-]+/g, ' ').split('/').pop() ?? '';\n } catch {\n return '';\n }\n}\n\nexport const TILE_WIDTH = 640;\nconst TILE_MAX_HEIGHT = 1024;\n\nexport function tileSize(aspect: number): { w: number; h: number } {\n const h = Math.min(TILE_MAX_HEIGHT, Math.max(120, Math.round(TILE_WIDTH * aspect)));\n return { w: TILE_WIDTH, h };\n}\n\ntype Ctx = CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D;\n\nfunction wrap(ctx: Ctx, text: string, maxW: number, maxLines: number): string[] {\n const words = text.split(/\\s+/).filter(Boolean);\n const lines: string[] = [];\n let line = '';\n for (const w of words) {\n const next = line === '' ? w : `${line} ${w}`;\n if (ctx.measureText(next).width <= maxW || line === '') line = next;\n else {\n lines.push(line);\n line = w;\n }\n if (lines.length === maxLines) break;\n }\n if (lines.length < maxLines && line !== '') lines.push(line);\n if (lines.length === maxLines && words.join(' ') !== lines.join(' ')) {\n let last = lines[maxLines - 1];\n while (last.length > 1 && ctx.measureText(`${last}…`).width > maxW) last = last.slice(0, -1);\n lines[maxLines - 1] = `${last}…`;\n }\n return lines;\n}\n\nfunction drawGlyph(ctx: Ctx, g: TileGlyph, cx: number, cy: number, s: number, color: string): void {\n ctx.save();\n ctx.fillStyle = color;\n ctx.strokeStyle = color;\n ctx.lineWidth = s * 0.07;\n ctx.lineCap = 'round';\n ctx.lineJoin = 'round';\n ctx.beginPath();\n if (g === 'play') {\n ctx.arc(cx, cy, s * 0.5, 0, Math.PI * 2);\n ctx.stroke();\n ctx.beginPath();\n ctx.moveTo(cx - s * 0.14, cy - s * 0.24);\n ctx.lineTo(cx + s * 0.26, cy);\n ctx.lineTo(cx - s * 0.14, cy + s * 0.24);\n ctx.closePath();\n ctx.fill();\n } else if (g === 'globe' || g === 'link-off') {\n ctx.arc(cx, cy, s * 0.5, 0, Math.PI * 2);\n ctx.stroke();\n ctx.beginPath();\n ctx.ellipse(cx, cy, s * 0.22, s * 0.5, 0, 0, Math.PI * 2);\n ctx.moveTo(cx - s * 0.5, cy);\n ctx.lineTo(cx + s * 0.5, cy);\n ctx.stroke();\n if (g === 'link-off') {\n ctx.beginPath();\n ctx.moveTo(cx - s * 0.42, cy + s * 0.42);\n ctx.lineTo(cx + s * 0.42, cy - s * 0.42);\n ctx.stroke();\n }\n } else if (g === 'code') {\n ctx.moveTo(cx - s * 0.18, cy - s * 0.3);\n ctx.lineTo(cx - s * 0.48, cy);\n ctx.lineTo(cx - s * 0.18, cy + s * 0.3);\n ctx.moveTo(cx + s * 0.18, cy - s * 0.3);\n ctx.lineTo(cx + s * 0.48, cy);\n ctx.lineTo(cx + s * 0.18, cy + s * 0.3);\n ctx.moveTo(cx + s * 0.07, cy - s * 0.38);\n ctx.lineTo(cx - s * 0.07, cy + s * 0.38);\n ctx.stroke();\n } else if (g === 'music') {\n ctx.moveTo(cx + s * 0.2, cy - s * 0.42);\n ctx.lineTo(cx + s * 0.2, cy + s * 0.26);\n ctx.moveTo(cx + s * 0.2, cy - s * 0.42);\n ctx.lineTo(cx - s * 0.3, cy - s * 0.3);\n ctx.lineTo(cx - s * 0.3, cy + s * 0.34);\n ctx.stroke();\n for (const x of [cx - s * 0.4, cx + s * 0.1]) {\n ctx.beginPath();\n ctx.ellipse(x + s * 0.1, cy + s * 0.34, s * 0.14, s * 0.1, -0.4, 0, Math.PI * 2);\n ctx.fill();\n }\n } else {\n // design: a frame with a plus\n ctx.rect(cx - s * 0.42, cy - s * 0.42, s * 0.84, s * 0.84);\n ctx.moveTo(cx, cy - s * 0.2);\n ctx.lineTo(cx, cy + s * 0.2);\n ctx.moveTo(cx - s * 0.2, cy);\n ctx.lineTo(cx + s * 0.2, cy);\n ctx.stroke();\n }\n ctx.restore();\n}\n\nconst FONT = \"system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif\";\n\n// Paints the tile on `ctx` (size w x h). The theme decides light or dark; the hue is the site's.\nexport function paintTile(ctx: Ctx, w: number, h: number, spec: TileSpec, theme: Theme): void {\n const dark = theme.dark;\n const hsl = (s: number, l: number): string => `hsl(${spec.hue} ${s}% ${l}%)`;\n const g = ctx.createLinearGradient(0, 0, w, h);\n g.addColorStop(0, dark ? hsl(34, 20) : hsl(40, 90));\n g.addColorStop(1, dark ? hsl(30, 12) : hsl(34, 82));\n ctx.fillStyle = g;\n ctx.fillRect(0, 0, w, h);\n const fg = dark ? hsl(30, 88) : hsl(50, 24);\n const dim = dark ? hsl(20, 70) : hsl(30, 38);\n\n // One centred group: glyph, label, title. Sizes follow the tile's width, so text reads at card size.\n const pad = Math.round(w * 0.06);\n const glyph = Math.round(Math.min(w * 0.2, h * 0.34));\n const labelPx = Math.round(w * 0.04);\n const titlePx = Math.round(w * 0.055);\n ctx.textBaseline = 'alphabetic';\n ctx.textAlign = 'center';\n ctx.font = `600 ${titlePx}px ${FONT}`;\n const lines = spec.title === '' ? [] : wrap(ctx, spec.title, w - pad * 2, h < 260 ? 1 : 2);\n const gap = Math.round(glyph * 0.28);\n const groupH =\n glyph + gap + labelPx + (lines.length > 0 ? Math.round(titlePx * 0.5) + lines.length * titlePx * 1.2 : 0);\n let y = Math.max(pad * 0.5, (h - groupH) / 2);\n drawGlyph(ctx, spec.glyph, w / 2, y + glyph / 2, glyph, cssHex(theme.accent));\n y += glyph + gap + labelPx;\n ctx.fillStyle = dim;\n ctx.font = `700 ${labelPx}px ${FONT}`;\n ctx.fillText(spec.label.toUpperCase(), w / 2, y, w - pad * 2);\n if (lines.length > 0) {\n ctx.fillStyle = fg;\n ctx.font = `600 ${titlePx}px ${FONT}`;\n y += Math.round(titlePx * 0.5);\n for (const l of lines) {\n y += titlePx * 1.2;\n ctx.fillText(l, w / 2, y - titlePx * 0.2, w - pad * 2);\n }\n }\n}\n\n// A PNG blob of the tile, or null where there is no canvas (SSR, jsdom).\nexport async function drawTile(spec: TileSpec, aspect: number, theme: Theme): Promise<Blob | null> {\n const { w, h } = tileSize(aspect);\n if (typeof OffscreenCanvas !== 'undefined') {\n const c = new OffscreenCanvas(w, h);\n const ctx = c.getContext('2d');\n if (!ctx) return null;\n paintTile(ctx, w, h, spec, theme);\n return c.convertToBlob({ type: 'image/png' });\n }\n if (typeof document === 'undefined') return null;\n const c = document.createElement('canvas');\n c.width = w;\n c.height = h;\n const ctx = c.getContext('2d');\n if (!ctx) return null;\n paintTile(ctx, w, h, spec, theme);\n return new Promise((resolve) => c.toBlob((b) => resolve(b), 'image/png'));\n}\n","// The embed layer of a corkboard: poster resolution and the live iframes of `embed` cards.\n//\n// poster always. The card is a textured sprite like any other (generated tile, provider thumbnail or\n// the host's picture), through the LOD pipeline. No DOM. What this layer generates (tile, photo it\n// fetched, snapshot, preview) is a runtime override on the stage (`setPosterOverride`), never written\n// to the store: a host that saves the board does not save dead blob URLs, and swapping one picture for\n// another does not flash the placeholder.\n// live an iframe in a DOM layer over the canvas, laid out at the card's world size and moved with the\n// camera as one CSS matrix (geometry.ts), for the cards the policy picks (policy.ts):\n// in view (any size, any zoom, by default) or selected, camera still, at most `maxLive` at a time. The poster stays under it,\n// veiled with a spinner, and the iframe fades in when it has loaded.\n// parked a live iframe that stopped qualifying (too small, zoomed out, off screen, or out of the `maxLive`\n// budget) but stays mounted and inert (`data-parked`), still showing its last frame: a cross-origin\n// page cannot be screenshotted, so the poster would be a downgrade. At most `maxMounted` frames\n// (live + parked) exist; the least valuable parked ones are destroyed past that, and only then does\n// the poster show again. A parked card that qualifies again goes live without remounting.\n// culled a mounted frame whose card is off screen (the viewport grown by CULL_MARGIN): `data-culled`,\n// `display: none`, so it stops rendering while its document stays alive and comes back as it was. Set\n// in `place()` on every frame, even mid-pan: frames hide the moment they leave and show the moment\n// they return. At most `maxOffscreen` are kept, most recently seen first; the plan destroys the rest\n// when the camera settles, and a destroyed card that returns mounts again through the chunked path.\n// A loaded snippet frame is the exception on the way out: hiding it first would leave nothing to\n// snapshot (no layout, no size), so it is asked for a snapshot of its last frame, which becomes the\n// card's poster (`data-culling`, still visible but off screen), and is hidden when the reply is in or\n// after CULL_SNAPSHOT_MS. That costs main-thread work in the frame, so it is throttled (one per frame\n// per CULL_SNAPSHOT_MIN_MS), never takes the slots freezing needs, is skipped while the camera moves\n// fast (the frame is hidden at once) and is drawn here when the browser is idle. Nothing is revealed\n// on the way back: the wrapper is transparent once the frame has loaded (`data-ready`), so the poster\n// under it shows until the frame paints. The same goes for a frozen frame thawing.\n// frozen a snippet frame whose card is small on screen (under `freezePx`) and idle: it is asked for a\n// snapshot of its own document (bootstrap.ts), the picture becomes the card's poster, and once that\n// texture shows the frame is hidden (`data-frozen`, `display: none`, so it stops rendering while its\n// document stays alive). It keeps its place in the live / parked budgets, and shows again the moment\n// the card grows past 1.4x `freezePx`, is selected or enters interact mode. The size is `freezePx`\n// raised (up to 4x) while the page stays slow with the budget at its floor, and lowered back when it is\n// smooth (`freezeThreshold`). A snapshot that fails\n// (a tainted canvas, Safari, a timeout) leaves the frame live: never a generic tile for a card that\n// has been live. The poster that is left is the last frame, which is also what shows if the frame\n// is destroyed later.\n// Life of a card: poster -> live -> parked -> culled -> destroyed (back to its poster).\n// preview a snippet card that has not been live has only a generated tile. A small pool of hidden \"studio\"\n// iframes (`previewWorkers`, 2) renders such snippets in the background, one job per frame: load,\n// wait PREVIEW_SETTLE_MS so it animates into a representative state, ask for a snapshot (the same\n// protocol as freezing), draw it here and make it the card's poster (`ownKind` 'preview'). Jobs are\n// ordered on screen first, nearest the centre, and only start while the camera is still. The studio\n// sits at the top-left of the page at opacity 0, not off screen: Chromium throttles frames that are\n// out of the viewport (no requestAnimationFrame), which would leave a canvas snippet blank. It is\n// laid out like a live frame (same virtual screen and aspect), has the same sandbox, and takes no\n// loading or snapshot slot. A preview never covers a snapshot of a live frame and is never covered\n// by a tile. Pictures are cached by a hash of what shapes them (previewCache.ts): in memory, and\n// across reloads in Cache Storage, where a hit needs no job at all.\n// pause work no one sees is stopped without destroying anything. A snippet frame that is parked, culled\n// or frozen gets `pause` (animations paused, requestAnimationFrame held) and `resume` when it is\n// active again. A YouTube / Vimeo frame is paused through its player's postMessage API while its\n// card is small, parked or culled (a paused player keeps showing the current video frame, which is\n// the \"last frame\" a cross-origin page cannot be snapshotted to), and played again afterwards if\n// this layer paused it. Only on a change of state; never in interact mode.\n// budget what is left to render is bounded too. Of the mounted frames that are on screen, not culled, not\n// parked and not frozen, the ones that can be paused (snippets, and YouTube / Vimeo players that may be\n// playing) are ranked: interacting, selected, then the biggest on screen, then the nearest the centre\n// of the view. The first N animate and the rest are paused (and resumed on re-entering), still showing\n// their last frame. N is `maxAnimating` at most, and with `adaptive` the board's frame-rate\n// monitor (render/frameRate.ts: short bursts of rAF sampling on events that change the load, plus a\n// heartbeat, never a loop that keeps the page awake) lowers it when the page runs under SLOW_FPS and\n// raises it back when it is smooth. Pages that cannot be paused (plain URLs, Spotify, CodePen, Figma) take no slot and are\n// never touched. Ranked on settle and on selection, interaction or budget changes, not every frame.\n// Mounting is not affected: every card in view still mounts. At the floor, a page that is still slow\n// freezes bigger cards too (see frozen): hiding frames is what frees the most.\n// interact the iframe takes pointer events (double-click or Enter on a selected embed). A \"Done\" button,\n// a click outside the iframe or Esc ends it. Until then the canvas keeps pan, zoom, select and\n// drag: the iframe has `pointer-events: none`.\n//\n// What goes in the iframe (sandbox, allow list) is decided at mount time by sandbox.ts, never stored.\nimport type { Camera } from '../math';\nimport type { Stage } from '../render/stage';\nimport type { Store, StoreEvent } from '../store';\nimport type { Theme } from '../render/theme';\nimport { elementBox } from '../interact/geometry';\nimport { FrameRateMonitor, SMOOTH_WINDOWS, type FrameWindow } from '../render/frameRate';\nimport type { Element, ElementId, EmbedResolution, EmbedSource } from '../types';\nimport { DEFAULT_RESOLUTION, embedPlacement } from './geometry';\nimport {\n MAX_LIVE_DESKTOP,\n MAX_LIVE_TOUCH,\n MAX_MOUNTED_DESKTOP,\n MAX_MOUNTED_TOUCH,\n MAX_OFFSCREEN_DESKTOP,\n MAX_OFFSCREEN_TOUCH,\n MIN_LIVE_H,\n MIN_LIVE_SCALE,\n MIN_LIVE_W,\n planLive,\n type PolicyCard,\n} from './policy';\nimport { fetchPoster } from './poster';\nimport { withAutoplay, withJsApi, type EmbedProvider } from './providers';\nimport {\n baseResolved,\n canGoLive,\n mergeResolved,\n sameEmbed,\n type EmbedResolver,\n type ResolvedEmbed,\n} from './resolve';\nimport { EMBED_CB, SNAPSHOT_MAX_SIDE, SNAPSHOT_MS } from './bootstrap';\nimport { PreviewStore, previewKey, type PreviewCacheMode } from './previewCache';\nimport { iframeSpecFor, type IframeSpec } from './sandbox';\nimport { drawTile, tileSpec } from './tile';\n\nexport interface EmbedOptions {\n // Live iframes at once on a mouse / pen device (default 12). Infinity: no cap.\n maxLive?: number;\n // ... and on a touch device (default 3). Infinity: no cap.\n maxLiveTouch?: number;\n // Mounted iframes at once, live + parked, on a mouse / pen device (default 24). Infinity: no cap.\n maxMounted?: number;\n // ... and on a touch device (default 6). Infinity: no cap.\n maxMountedTouch?: number;\n // Mounted iframes kept while their card is off screen (culled: hidden, not rendering, but alive), a subset of\n // maxMounted, on a mouse / pen device (default 64). The most recently seen stay; the rest are destroyed\n // when the camera settles. Infinity: only maxMounted limits them.\n maxOffscreen?: number;\n // ... and on a touch device (default 12). Infinity: only maxMounted limits them.\n maxOffscreenTouch?: number;\n // How far past the viewport a card still counts as on screen, as a fraction of the viewport on each side\n // (default CULL_MARGIN). Frames in that ring keep rendering, and cards entering it mount ahead of the pan.\n cullMargin?: number;\n // A card goes live when it is at least this big on screen, in CSS px, or selected. Default 0: any card in\n // view, up to `maxLive`, the biggest on screen first. A number is the width; the height keeps a 320:200 ratio.\n minLivePx?: number | { w: number; h: number };\n // Below this zoom no new iframe mounts (default 0: any zoom). Interacting still flies in to MIN_LIVE_SCALE.\n minLiveScale?: number;\n // Async lookup for what the browser cannot know: oEmbed thumbnails and titles, og:image, screenshots,\n // and whether the page may be framed at all. Runs on a server of yours. See EmbedResolver.\n resolve?: EmbedResolver;\n // Give up on `resolve` after this long and use what the URL says (default 4000 ms).\n resolveTimeoutMs?: number;\n // The virtual screen a live page is laid out at (default '720p'); a card's `embed.resolution` wins.\n resolution?: EmbedResolution;\n // Keep `allow-same-origin` in the sandbox of arbitrary (non-provider) URLs (default true). Many sites break\n // without their own cookies and storage, but the frame then keeps its real origin across the navigations\n // it makes. false: those frames get an opaque origin. Providers and snippets are not affected.\n arbitrarySameOrigin?: boolean;\n // Start YouTube and Vimeo videos playing on their own, muted and looping, as soon as their card goes live\n // (default false). Changing it remounts the live frames. Snippets run their own scripts either way.\n autoplay?: boolean;\n // Iframes loading at once (default 6). New frames mount in chunks, nearest the centre of the view first,\n // as earlier ones finish, so a board full of embeds does not start hundreds of pages in the same frame.\n // A frame that has not loaded after LOAD_SLOT_MS gives its slot up. Infinity: no limit.\n maxLoading?: number;\n // A mounted card whose short side on screen drops under this many CSS px is not worth rendering (default\n // 140). A snippet frame is frozen: it is snapshotted into the card's poster and hidden. A YouTube / Vimeo\n // frame is paused. Both come back above 1.4x this size, when selected or in interact mode. 0: neither\n // freezing nor size-based pausing (parked and culled frames are still paused).\n freezePx?: number;\n // At most this many mounted, visible frames that can be paused (snippets, YouTube / Vimeo) animate at once;\n // the rest are paused, showing their last frame, biggest on screen and nearest the centre first (default\n // Infinity). Pages that cannot be paused (plain URLs, Spotify, CodePen, Figma) are not counted.\n maxAnimating?: number;\n // Lower the number of animating frames while the page runs under 40 fps, and raise it back (up to\n // `maxAnimating`) when it is smooth again (default true). false: always `maxAnimating`.\n adaptive?: boolean;\n // Hidden frames that render snippets which have not been live, to give their cards a real picture instead\n // of a generated tile (default 3). 0: none, the tile stays until the card goes live.\n previewWorkers?: number;\n // Where those pictures are kept (default 'memory'): this page only. 'persistent' also keeps them in Cache\n // Storage (at most PREVIEW_PERSIST_MAX, oldest dropped first), so a reload shows them at once; it leaves\n // pictures of the snippets on the visitor's disk, hence opt-in. Falls back to memory where Cache Storage\n // cannot be used.\n previewCache?: PreviewCacheMode;\n}\n\nexport interface EmbedEvents {\n // Interact mode began (`active: true`) or ended on an embed card.\n embedInteract: { id: ElementId; active: boolean };\n // A card's iframe was mounted or destroyed.\n embedLive: { id: ElementId; live: boolean };\n // The card's embed was resolved. `poster` is a URL worth persisting (the host's own or a provider\n // thumbnail), absent for a generated tile or any blob URL this layer made (they die with the page).\n embedResolved: {\n id: ElementId;\n provider: EmbedProvider;\n frameable: boolean;\n aspect?: number;\n title?: string;\n poster?: string;\n };\n}\n\nexport interface EmbedLayerDeps {\n // The DOM layer shared with the other overlays (covers the canvas, `pointer-events: none`).\n root: HTMLElement;\n // The board's host: Enter on it enters interact mode.\n host: HTMLElement;\n store: Store;\n stage: Stage;\n emit<K extends keyof EmbedEvents>(type: K, payload: EmbedEvents[K]): void;\n // The board's frame-rate monitor, shared with the video layer. Without one the layer makes its own.\n frameRate?: FrameRateMonitor;\n // The frame scheduler of that own monitor (default: the window's). A seam for tests.\n raf?: (cb: (time: number) => void) => number;\n caf?: (id: number) => void;\n // Draws a snippet's snapshot (SVG markup, see bootstrap.ts) at w x h px (default: an <img> on a canvas). A\n // seam for tests, where nothing can rasterise.\n rasterize?: (svg: string, w: number, h: number) => Promise<Blob | null>;\n}\n\ninterface Entry {\n embed: EmbedSource;\n info: ResolvedEmbed;\n // `resolve` has answered (or there is none): the card knows if it can go live.\n ready: boolean;\n // The title the resolver gave, kept for when the card's own title goes away.\n resolverTitle?: string;\n spec: IframeSpec | null;\n token: number;\n // The blob URL of the poster this layer made (photo, tile, snapshot or preview): a stage override, not in the store.\n ownUrl: string | null;\n ownKind: 'photo' | 'tile' | 'snapshot' | 'preview' | null;\n // Our earlier posters the element may still carry (the embed changed under it).\n stale: Set<string>;\n initialAspect: number;\n lastUsed: number;\n // Last time the card was on screen (inside the cull margin), from the same counter as lastUsed.\n lastSeen: number;\n // Preview queue state of a snippet card. idle: not looked at, or nothing to do; checking: asking the\n // persistent cache; queued: waits for a studio; running: in a studio; done / failed: over.\n pv: 'idle' | 'checking' | 'queued' | 'running' | 'done' | 'failed';\n // Jobs that ended without a picture.\n pvTries: number;\n // The key of its preview when it was queued (jobs on the same one are not run side by side).\n pvKey: string;\n}\n\n// A hidden iframe that renders one snippet at a time for its preview.\ninterface Studio {\n box: HTMLElement;\n // A new iframe per job (null until the first): a document that is still loading when its job ends can\n // never be taken for the next job's.\n iframe: HTMLIFrameElement | null;\n job: PreviewJob | null;\n}\n\ninterface PreviewPlan {\n key: string;\n // The virtual screen the snippet is laid out at, and the size of its picture.\n vw: number;\n vh: number;\n w: number;\n h: number;\n}\n\ninterface PreviewJob {\n id: ElementId;\n entry: Entry;\n token: number;\n studio: Studio | null;\n plan: PreviewPlan;\n // The request in flight (0: not asked yet).\n seq: number;\n loaded: boolean;\n settle: ReturnType<typeof setTimeout> | null;\n timer: ReturnType<typeof setTimeout> | null;\n}\n\ninterface Frame {\n wrapper: HTMLElement;\n iframe: HTMLIFrameElement;\n loaded: boolean;\n // The corner radius last written, in the wrapper's px.\n radius: number;\n // Holds a loading slot until it loads or LOAD_SLOT_MS passes.\n slot: boolean;\n slotTimer: ReturnType<typeof setTimeout> | null;\n w: number;\n h: number;\n transform: string;\n z: number;\n // Off screen. The wrapper is hidden (`data-culled`) at once, or when its last-frame snapshot is in (`cullTimer`).\n culled: boolean;\n // Waiting for the cull snapshot to hide the frame (`data-culling`).\n cullTimer: ReturnType<typeof setTimeout> | null;\n // When the last cull snapshot was asked for (Date.now()).\n cullSnapAt: number;\n // Mirrors `data-parked`.\n parked: boolean;\n kind: 'snippet' | 'video' | 'page';\n provider: EmbedProvider;\n // Where a video player listens (its src origin).\n origin: string;\n // The card is under `freezePx` (with hysteresis) and idle.\n small: boolean;\n // Hidden by a snapshot (`data-frozen`).\n frozen: boolean;\n // The last snapshot failed: no new try until `retry` fires (SNAP_TRIES at most) or the card stops being small.\n snapFailed: boolean;\n snapTries: number;\n retry: ReturnType<typeof setTimeout> | null;\n // The request in flight, if any, and the size its picture is drawn at.\n // `cull`: asked because the card left the view, not to freeze it.\n snap: { id: number; timer: ReturnType<typeof setTimeout>; w: number; h: number; cull: boolean } | null;\n // Waiting for the snapshot poster to show before hiding the frame.\n landTimer: ReturnType<typeof setTimeout> | null;\n // The reply is in and its picture is being drawn here: the frame is not asked again until it is applied\n // (the snapshot slot is already free for the others).\n drawing: boolean;\n // Snippet: the last op sent (true: pause). Video: this layer paused the player.\n paused: boolean;\n // The user has had the frame in interact mode, so a video in it may be playing without autoplay.\n interacted: boolean;\n // Resends the video command once the player has had time to start listening.\n loadTimer: ReturnType<typeof setTimeout> | null;\n // Ranked past the animating budget: paused like a parked frame (never set on a frame that cannot be paused).\n overBudget: boolean;\n}\n\nexport const MAX_LOADING = 6;\nexport const LOAD_SLOT_MS = 8000;\n// A card counts as on screen this far outside the viewport too (fraction of the viewport, each side), so frames\n// just past the edge stay visible and a small pan does not hide and show them.\nexport const CULL_MARGIN = 0.5;\n// Under this short side on screen (CSS px) a frame is frozen or paused, and above FREEZE_HYSTERESIS times it\n// it comes back, so a card hovering around the size does not flip.\nexport const FREEZE_PX = 140;\nexport const FREEZE_HYSTERESIS = 1.4;\n// While the page stays slow with the animating budget at its floor, the size under which snippets freeze is\n// raised by FREEZE_STEP per slow window, up to FREEZE_MAX_MUL x `freezePx`, and lowered back the same way.\nexport const FREEZE_STEP = 1.5;\nexport const FREEZE_MAX_MUL = 4;\n// Snapshots asked for at once: each is main-thread work in the frame.\nexport const MAX_SNAPSHOTS = 6;\n// A frame that leaves the view is hidden once its snapshot is in, or this long after it was asked for.\nexport const CULL_SNAPSHOT_MS = 400;\n// At most one such snapshot per frame in this time, so panning back and forth does not redo the work.\nexport const CULL_SNAPSHOT_MIN_MS = 3000;\n// ... and only while this many of the MAX_SNAPSHOTS slots are free, so freezing is never starved.\nconst CULL_SNAPSHOT_RESERVE = 2;\n// No snapshot on the way out while the camera moves faster than this (screen px per ms): the frame is hidden at\n// once, the pan is not slowed down by main-thread work for pictures nobody will look at.\nexport const CULL_SNAPSHOT_MAX_SPEED = 1.5;\n// A frame gap longer than this is idle time, not a measure of speed.\nconst SPEED_MAX_DT_MS = 100;\n// The picture of a cull snapshot is drawn when the browser is idle, or at the latest this long after.\nconst CULL_DRAW_IDLE_MS = 1000;\n// A reply is awaited a bit longer than the frame's own time box.\nconst SNAPSHOT_WAIT_MS = SNAPSHOT_MS;\n// A failed snapshot is tried again this much later (times the tries so far), this many times in all.\nconst SNAP_RETRY_MS = 2000;\nconst SNAP_TRIES = 3;\n// After a snapshot poster is applied: the first look at whether its texture shows, then every step, up to\n// LAND_TRIES times. The stage keeps the old poster on screen until the new one's first level is resident, so a\n// level read sooner is the old one (stage.posterShown tells).\nconst LAND_FIRST_MS = 200;\nconst LAND_STEP_MS = 100;\nconst LAND_TRIES = 30;\n// The animating budget never adapts below this many frames.\nexport const MIN_ANIMATING = 6;\n// fps is read by the board's FrameRateMonitor (render/frameRate.ts, in bursts); under SLOW_FPS the budget\n// shrinks to 70% of what animates, and after SMOOTH_WINDOWS in a row over SMOOTH_FPS it grows by a quarter (+2).\nexport { SAMPLE_WINDOW_MS, SLOW_FPS, SMOOTH_FPS, SMOOTH_WINDOWS } from '../render/frameRate';\n// A video player is sent its command again this long after the frame loaded (the first may be too early).\nconst PLAYER_READY_MS = 1500;\n\n// Previews: a snippet is asked for its picture this long after it loaded (so it has moved on from its first\n// frame), a job is given up after PREVIEW_JOB_MS, and drawing the reply after PREVIEW_DRAW_MS. A card gets at\n// most PREVIEW_TRIES jobs.\nexport const PREVIEW_WORKERS = 3;\nexport const PREVIEW_SETTLE_MS = 400;\nexport const PREVIEW_JOB_MS = 4000;\nconst PREVIEW_DRAW_MS = 3000;\nconst PREVIEW_TRIES = 2;\n// The aspect (height / width) a preview is laid out at is rounded to 1/PREVIEW_BUCKETS, so cards of nearly the\n// same shape share a picture. Its layout box is PREVIEW_BOX wide before the virtual screen is applied.\nconst PREVIEW_BUCKETS = 50;\nconst PREVIEW_BOX = 1000;\n// Out of the way, yet inside the viewport and visible to the browser (see the header).\nconst STUDIO_CSS = 'position:fixed;left:0;top:0;opacity:0;pointer-events:none;z-index:-1;overflow:hidden;';\n\nconst STYLE_ID = 'cb-embed-styles';\nconst CSS = `\n.cb-embed{position:absolute;left:0;top:0;transform-origin:0 0;overflow:hidden;background:rgba(0,0,0,.28);pointer-events:none;container-type:size;transition:background-color .2s ease}\n.cb-embed[data-ready]{background:transparent}\n.cb-embed[data-culled]{display:none}\n.cb-embed iframe{position:absolute;left:0;top:0;width:100%;height:100%;border:0;display:block;pointer-events:none;color-scheme:normal;opacity:0;transition:opacity .2s ease}\n.cb-embed[data-ready] iframe{opacity:1}\n.cb-embed-spin{position:absolute;left:50%;top:50%;width:20cqmin;height:20cqmin;margin:-10cqmin 0 0 -10cqmin;border-radius:50%;background:rgba(16,17,20,.72);box-shadow:0 0 0 .4cqmin rgba(255,255,255,.18)}\n.cb-embed-spin::after{content:'';position:absolute;inset:24%;box-sizing:border-box;border-radius:50%;border:1.6cqmin solid rgba(255,255,255,.25);border-top-color:#fff;animation:cb-embed-spin .9s linear infinite}\n.cb-embed[data-ready] .cb-embed-spin{display:none}\n@keyframes cb-embed-spin{to{transform:rotate(360deg)}}\n.cb-embed[data-interact]{pointer-events:auto}\n.cb-embed[data-interact] iframe{pointer-events:auto}\n.cb-embed-done{position:absolute;left:0;top:0;z-index:2147483647;pointer-events:auto;font:600 12px/1 system-ui,-apple-system,'Segoe UI',Roboto,sans-serif;color:#fff;background:rgba(20,20,22,.9);border:1px solid rgba(255,255,255,.28);border-radius:999px;padding:8px 14px;cursor:pointer;box-shadow:0 2px 10px rgba(0,0,0,.35);display:none}\n.cb-embed-done:hover{background:rgba(48,48,52,.95)}\n.cb-embed-done:focus-visible{outline:2px solid #6aa6ff;outline-offset:2px}\n@media (prefers-reduced-motion:reduce){.cb-embed,.cb-embed iframe{transition:none}.cb-embed-spin::after{animation-duration:3s}}\n`;\n\nconst DONE_MARGIN = 10;\n// Flying in on a card to interact with it: the screen padding around it, and a hair over the zoom a frame\n// mounts at, so the rounding of the fly cannot land under it.\nconst FLY_PAD = 48;\nconst FLY_IN_SCALE = MIN_LIVE_SCALE * 1.05;\n// Leave the iframe's pixels alone this long after a poster swap before revoking the old blob.\nconst REVOKE_DELAY_MS = 15000;\n\ninterface Rect {\n x0: number;\n y0: number;\n x1: number;\n y1: number;\n}\n\n// A box and a rect that touch count as overlapping.\nconst overlaps = (b: { minX: number; minY: number; maxX: number; maxY: number }, v: Rect): boolean =>\n b.maxX >= v.x0 && b.minX <= v.x1 && b.maxY >= v.y0 && b.minY <= v.y1;\n\nconst normMinLive = (m: EmbedOptions['minLivePx']): { w: number; h: number } =>\n m === undefined\n ? { w: 0, h: 0 }\n : typeof m === 'number'\n ? { w: m, h: (m * MIN_LIVE_H) / MIN_LIVE_W }\n : m;\n\nexport class EmbedLayer {\n private readonly root: HTMLElement;\n private readonly host: HTMLElement;\n private readonly store: Store;\n private readonly stage: Stage;\n private readonly emit: EmbedLayerDeps['emit'];\n private readonly doc: Document;\n private readonly entries = new Map<ElementId, Entry>();\n private readonly frames = new Map<ElementId, Frame>();\n private readonly done: HTMLButtonElement;\n private readonly cleanups: (() => void)[] = [];\n // Pending revokes of retired poster blobs: timer -> URL (dispose revokes the rest at once).\n private readonly timers = new Map<ReturnType<typeof setTimeout>, string>();\n private readonly appOrigin: string | undefined;\n private opts: Required<Pick<EmbedOptions, 'maxLive' | 'maxLiveTouch' | 'maxMounted' | 'maxMountedTouch' | 'maxOffscreen' | 'maxOffscreenTouch' | 'resolveTimeoutMs' | 'cullMargin'>> & {\n minLive: { w: number; h: number };\n minLiveScale: number;\n resolve?: EmbedResolver;\n resolution: EmbedResolution;\n arbitrarySameOrigin: boolean;\n autoplay: boolean;\n maxLoading: number;\n freezePx: number;\n maxAnimating: number;\n adaptive: boolean;\n previewWorkers: number;\n };\n private selected = new Set<ElementId>();\n private touch = false;\n private moving = false;\n private planDirty = false;\n private interactId: ElementId | null = null;\n // Double-click on a card too small to mount (zoomed far out): fly to it, then interact.\n private pendingInteract: ElementId | null = null;\n private clock = 0;\n private snapSeq = 0;\n // Snapshot requests in flight.\n private snapping = 0;\n private disposed = false;\n private readonly monitor: FrameRateMonitor;\n private readonly rasterize: (svg: string, w: number, h: number) => Promise<Blob | null>;\n // The adaptive limit on animating frames (Infinity: none); the effective budget also honours maxAnimating.\n private adaptiveN = Infinity;\n private animatingIds = new Set<ElementId>();\n // Frames that were candidates for a slot at the last ranking, and how many mounted frames render (on screen,\n // not culled, not frozen): the monitor only measures while there are any, and is poked when the count moves.\n private candidates = 0;\n private renderCount = 0;\n // A frame froze or thawed since the last ranking.\n private rankDirty = false;\n private smooth = 0;\n // `freezePx` x this is the size under which a snippet freezes (1..FREEZE_MAX_MUL); smooth windows in a row.\n private freezeMul = 1;\n private freezeSmooth = 0;\n // How fast the camera moved at the last frame (screen px per ms), from the previous camera state.\n private camSpeed = 0;\n private lastCam: { tx: number; ty: number; scale: number; at: number } | null = null;\n private readonly studios: Studio[] = [];\n private readonly previews: PreviewStore;\n // Entries that may need a preview have not all been looked at.\n private previewScan = false;\n // Jobs whose reply is being drawn (they hold no studio).\n private readonly drawing = new Set<PreviewJob>();\n\n constructor(deps: EmbedLayerDeps, options: EmbedOptions = {}) {\n this.host = deps.host;\n this.store = deps.store;\n this.stage = deps.stage;\n this.emit = deps.emit;\n this.doc = deps.root.ownerDocument;\n const win = this.doc.defaultView;\n this.monitor = deps.frameRate ?? new FrameRateMonitor({ raf: deps.raf, caf: deps.caf, doc: this.doc });\n if (!deps.frameRate) this.cleanups.push(() => this.monitor.dispose());\n this.cleanups.push(\n this.monitor.load(() => this.opts.adaptive && !this.disposed && this.renderCount > 0),\n this.monitor.onWindow((w) => this.onWindow(w)),\n // A new burst: the windows before it are no \"in a row\" with the ones to come.\n this.monitor.onStart(() => {\n this.smooth = 0;\n this.freezeSmooth = 0;\n }),\n );\n this.rasterize = deps.rasterize ?? ((svg, w, h) => rasterizeSvg(this.doc, svg, w, h));\n this.appOrigin = typeof location !== 'undefined' ? location.origin : undefined;\n this.opts = {\n maxLive: options.maxLive ?? MAX_LIVE_DESKTOP,\n maxLiveTouch: options.maxLiveTouch ?? MAX_LIVE_TOUCH,\n maxMounted: options.maxMounted ?? MAX_MOUNTED_DESKTOP,\n maxMountedTouch: options.maxMountedTouch ?? MAX_MOUNTED_TOUCH,\n maxOffscreen: options.maxOffscreen ?? MAX_OFFSCREEN_DESKTOP,\n maxOffscreenTouch: options.maxOffscreenTouch ?? MAX_OFFSCREEN_TOUCH,\n cullMargin: options.cullMargin ?? CULL_MARGIN,\n resolveTimeoutMs: options.resolveTimeoutMs ?? 4000,\n minLive: normMinLive(options.minLivePx),\n minLiveScale: options.minLiveScale ?? 0,\n resolve: options.resolve,\n resolution: options.resolution ?? DEFAULT_RESOLUTION,\n arbitrarySameOrigin: options.arbitrarySameOrigin ?? true,\n autoplay: options.autoplay ?? false,\n maxLoading: options.maxLoading ?? MAX_LOADING,\n freezePx: options.freezePx ?? FREEZE_PX,\n maxAnimating: normBudget(options.maxAnimating ?? Infinity),\n adaptive: options.adaptive ?? true,\n previewWorkers: normWorkers(options.previewWorkers ?? PREVIEW_WORKERS),\n };\n this.previews = new PreviewStore(options.previewCache ?? 'memory');\n\n if (!this.doc.getElementById(STYLE_ID)) {\n const style = this.doc.createElement('style');\n style.id = STYLE_ID;\n style.textContent = CSS;\n this.doc.head.appendChild(style);\n }\n this.root = this.doc.createElement('div');\n this.root.style.cssText = 'position:absolute;inset:0;overflow:hidden;pointer-events:none;';\n deps.root.appendChild(this.root);\n\n this.done = this.doc.createElement('button');\n this.done.type = 'button';\n this.done.className = 'cb-embed-done';\n this.done.textContent = 'Done';\n this.done.setAttribute('aria-label', 'Done interacting with the embed');\n // The board listens on its host: nothing the button gets may reach it.\n for (const t of ['pointerdown', 'pointerup', 'dblclick', 'wheel', 'keydown'] as const) {\n this.done.addEventListener(t, (e) => {\n if (t === 'keydown' && (e as KeyboardEvent).key === 'Escape') return;\n e.stopPropagation();\n });\n }\n this.done.addEventListener('click', () => this.exitInteract());\n this.root.appendChild(this.done);\n\n const onDown = (e: PointerEvent): void => {\n if (this.interactId === null) return;\n const f = this.frames.get(this.interactId);\n const t = e.target as Node | null;\n if (f && t && (f.wrapper.contains(t) || this.done.contains(t))) return;\n this.exitInteract();\n };\n const onKeyDoc = (e: KeyboardEvent): void => {\n if (e.key === 'Escape' && this.interactId !== null) {\n e.stopPropagation();\n this.exitInteract();\n }\n };\n const onKeyHost = (e: KeyboardEvent): void => {\n if (e.key !== 'Enter' || e.target !== this.host || e.metaKey || e.ctrlKey || e.altKey) return;\n if (this.interactId !== null || this.selected.size !== 1) return;\n const id = [...this.selected][0];\n if (this.entries.has(id) && this.activate(id, true)) e.preventDefault();\n };\n this.doc.addEventListener('pointerdown', onDown, true);\n this.doc.addEventListener('keydown', onKeyDoc, true);\n this.host.addEventListener('keydown', onKeyHost);\n this.cleanups.push(\n () => this.doc.removeEventListener('pointerdown', onDown, true),\n () => this.doc.removeEventListener('keydown', onKeyDoc, true),\n () => this.host.removeEventListener('keydown', onKeyHost),\n this.store.subscribe((e) => this.onStore(e)),\n );\n const onVisibility = (): void => this.pumpPreviews();\n this.doc.addEventListener('visibilitychange', onVisibility);\n this.cleanups.push(() => this.doc.removeEventListener('visibilitychange', onVisibility));\n if (win) {\n const onMessage = (e: MessageEvent): void => this.onMessage(e);\n win.addEventListener('message', onMessage);\n this.cleanups.push(() => win.removeEventListener('message', onMessage));\n }\n for (const el of this.store.elements()) this.track(el);\n }\n\n // ── Public ─────────────────────────────────────────────────────────────────\n // Ids of the cards that hold a mounted iframe now (active and parked).\n get live(): ReadonlySet<ElementId> {\n return new Set(this.frames.keys());\n }\n\n // ... of which these are parked: mounted but inert, showing their last frame.\n get parked(): ReadonlySet<ElementId> {\n const out = new Set<ElementId>();\n for (const [id, f] of this.frames) if (f.wrapper.dataset.parked !== undefined) out.add(id);\n return out;\n }\n\n // ... and of those, these are off screen: hidden (`data-culled`), not rendering, still alive.\n get culled(): ReadonlySet<ElementId> {\n const out = new Set<ElementId>();\n for (const [id, f] of this.frames) if (f.culled) out.add(id);\n return out;\n }\n\n // ... and these are frozen: a snapshot is their poster and the frame is hidden (`data-frozen`), alive.\n get frozen(): ReadonlySet<ElementId> {\n const out = new Set<ElementId>();\n for (const [id, f] of this.frames) if (f.frozen) out.add(id);\n return out;\n }\n\n // ... and of those, these animate: they can be paused and are within the animating budget. A page that\n // cannot be paused is never in it (it takes no slot), nor is a parked, culled or frozen frame.\n get animating(): ReadonlySet<ElementId> {\n const out = new Set<ElementId>();\n for (const id of this.animatingIds) if (this.frames.has(id)) out.add(id);\n return out;\n }\n\n // How many frames may animate now: maxAnimating, lowered by the frame-rate monitor's windows (Infinity: no limit).\n get animatingBudget(): number {\n return Math.min(this.opts.maxAnimating, this.adaptiveN);\n }\n\n // The short side (CSS px) under which a snippet freezes now: `freezePx`, raised while the page stays slow\n // with the animating budget at its floor.\n get freezeThreshold(): number {\n return this.opts.freezePx * this.freezeMul;\n }\n\n // Ids of the cards whose iframe is mounted and still loading (the spinner shows).\n get loading(): ReadonlySet<ElementId> {\n const out = new Set<ElementId>();\n for (const [id, f] of this.frames) if (!f.loaded) out.add(id);\n return out;\n }\n\n // The card in interact mode (null: none).\n get interacting(): ElementId | null {\n return this.interactId;\n }\n\n get maxLive(): number {\n return this.touch ? this.opts.maxLiveTouch : this.opts.maxLive;\n }\n\n get maxMounted(): number {\n return this.touch ? this.opts.maxMountedTouch : this.opts.maxMounted;\n }\n\n get maxOffscreen(): number {\n return this.touch ? this.opts.maxOffscreenTouch : this.opts.maxOffscreen;\n }\n\n // What is known about a card's embed (null: not an embed card).\n info(id: ElementId): Readonly<ResolvedEmbed> | null {\n return this.entries.get(id)?.info ?? null;\n }\n\n get resolution(): EmbedResolution {\n return this.opts.resolution;\n }\n\n // Snippet previews not done yet: waiting, being looked up in the cache or being rendered in a studio.\n get previewsPending(): number {\n let n = 0;\n for (const e of this.entries.values()) if (e.pv === 'checking' || e.pv === 'queued' || e.pv === 'running') n++;\n return n;\n }\n\n setOptions(o: EmbedOptions): void {\n if (o.maxLive !== undefined) this.opts.maxLive = o.maxLive;\n if (o.maxLoading !== undefined) this.opts.maxLoading = o.maxLoading;\n if (o.freezePx !== undefined) this.opts.freezePx = Math.max(0, o.freezePx);\n if (o.maxAnimating !== undefined) this.opts.maxAnimating = normBudget(o.maxAnimating);\n if (o.adaptive !== undefined && o.adaptive !== this.opts.adaptive) {\n this.opts.adaptive = o.adaptive;\n // Off: back to the ceiling.\n if (!o.adaptive) {\n this.adaptiveN = Infinity;\n this.freezeMul = 1;\n this.requestPlan();\n }\n this.smooth = 0;\n this.freezeSmooth = 0;\n }\n if (o.maxLiveTouch !== undefined) this.opts.maxLiveTouch = o.maxLiveTouch;\n if (o.maxMounted !== undefined) this.opts.maxMounted = o.maxMounted;\n if (o.maxMountedTouch !== undefined) this.opts.maxMountedTouch = o.maxMountedTouch;\n if (o.maxOffscreen !== undefined) this.opts.maxOffscreen = o.maxOffscreen;\n if (o.cullMargin !== undefined) this.opts.cullMargin = o.cullMargin;\n if (o.maxOffscreenTouch !== undefined) this.opts.maxOffscreenTouch = o.maxOffscreenTouch;\n if (o.minLivePx !== undefined) this.opts.minLive = normMinLive(o.minLivePx);\n if (o.minLiveScale !== undefined) this.opts.minLiveScale = o.minLiveScale;\n if (o.resolution !== undefined) {\n this.opts.resolution = o.resolution;\n for (const [id, f] of this.frames) this.place(id, f);\n }\n const sandboxChanged = o.arbitrarySameOrigin !== undefined && o.arbitrarySameOrigin !== this.opts.arbitrarySameOrigin;\n const autoplayChanged = o.autoplay !== undefined && o.autoplay !== this.opts.autoplay;\n if (sandboxChanged || autoplayChanged) {\n if (o.arbitrarySameOrigin !== undefined) this.opts.arbitrarySameOrigin = o.arbitrarySameOrigin;\n if (o.autoplay !== undefined) this.opts.autoplay = o.autoplay;\n for (const [id, e] of this.entries) {\n if (!e.ready) continue;\n const before = e.spec;\n e.spec = this.specFor(e);\n // A live frame is rebuilt with the new sandbox or URL the next time it mounts.\n if ((e.spec?.sandbox !== before?.sandbox || e.spec?.src !== before?.src) && this.frames.has(id)) {\n this.destroyFrame(id);\n }\n }\n }\n if (o.previewCache !== undefined) this.previews.mode = o.previewCache;\n if (o.previewWorkers !== undefined) {\n const workers = normWorkers(o.previewWorkers);\n if (workers === 0 && this.opts.previewWorkers > 0) this.stopPreviews();\n this.opts.previewWorkers = workers;\n this.previewScan = true;\n }\n this.rerank();\n this.requestPlan();\n // A limit or the adaptive switch moved: the load is measured again (or not at all).\n this.monitor.poke();\n }\n\n // Interact mode on a card: make it live (whatever its size) and give it pointer events. A card the page\n // refuses to frame opens its URL in a new tab instead. Returns false when there is nothing to do.\n interact(id: ElementId): boolean {\n return this.activate(id, false);\n }\n\n exitInteract(): void {\n const id = this.interactId;\n this.pendingInteract = null;\n if (id === null) return;\n this.interactId = null;\n const f = this.frames.get(id);\n if (f) {\n delete f.wrapper.dataset.interact;\n }\n this.done.style.display = 'none';\n this.rerank();\n // Keys belong to the board again.\n if (this.doc.activeElement && this.doc.activeElement !== this.host) {\n try {\n this.host.focus({ preventScroll: true });\n } catch {\n // Not focusable.\n }\n }\n this.emit('embedInteract', { id, active: false });\n this.requestPlan();\n }\n\n // ── Board hooks ────────────────────────────────────────────────────────────\n setSelection(ids: readonly ElementId[]): void {\n this.selected = new Set(ids);\n for (const id of ids) {\n const e = this.entries.get(id);\n if (e) e.lastUsed = ++this.clock;\n }\n if (this.interactId !== null && !this.selected.has(this.interactId)) this.exitInteract();\n // The card was deselected while the camera flew in: that interact is stale.\n if (this.pendingInteract !== null && !this.selected.has(this.pendingInteract)) this.pendingInteract = null;\n this.rerank();\n this.requestPlan();\n }\n\n setTouch(touch: boolean): void {\n if (touch === this.touch) return;\n this.touch = touch;\n this.requestPlan();\n }\n\n onDblClick(id: ElementId | null): void {\n if (id !== null && this.entries.has(id)) this.activate(id, false);\n }\n\n // Generated tiles follow the theme.\n setTheme(): void {\n for (const [id, e] of this.entries) if (e.ownKind === 'tile') void this.makeTile(id, e, e.token);\n }\n\n onFrame(camChanged: boolean): void {\n if (this.disposed) return;\n if (camChanged) this.moving = true;\n this.trackSpeed();\n // One stamp per frame: whatever is in view now was seen at this tick, so the order of leaving is known.\n const view = this.cullRect();\n const seen = ++this.clock;\n for (const [id, f] of this.frames) this.place(id, f, view, seen);\n if (!this.moving && this.planDirty) this.runPlan();\n // Only a frame that froze or thawed asks for it here; everything else ranks on settle.\n else if (this.rankDirty) this.rerank();\n if (!this.moving && this.previewScan) this.scanPreviews();\n }\n\n // How far the view moved on screen since the last frame, per ms: where the point that was at the centre is\n // now, plus what a zoom moves at the corners. A frame less than a ms after the last keeps the reading; after\n // a gap (nothing was drawn) the previous camera is no measure, so the camera counts as slow for that frame.\n private trackSpeed(): void {\n const c = this.stage.cam;\n const cur = { tx: c.cam.tx, ty: c.cam.ty, scale: c.scale, at: Date.now() };\n const prev = this.lastCam;\n this.lastCam = cur;\n if (!prev) return;\n const dt = cur.at - prev.at;\n if (dt <= 0) return;\n if (dt > SPEED_MAX_DT_MS) {\n this.camSpeed = 0;\n return;\n }\n const cx = c.width / 2;\n const cy = c.height / 2;\n const dx = ((cx - prev.tx) / prev.scale) * cur.scale + cur.tx - cx;\n const dy = ((cy - prev.ty) / prev.scale) * cur.scale + cur.ty - cy;\n const zoom = Math.abs(cur.scale / prev.scale - 1) * Math.hypot(cx, cy);\n this.camSpeed = (Math.hypot(dx, dy) + zoom) / dt;\n }\n\n onSettle(): void {\n if (this.disposed) return;\n this.moving = false;\n this.planDirty = true;\n if (this.pendingInteract !== null) {\n const id = this.pendingInteract;\n this.pendingInteract = null;\n // One try: a camera that could not fly in far enough does not fly again.\n if (this.activate(id, false, true)) return;\n }\n this.runPlan();\n // The queue was held while the camera moved: it goes on, nearest the new view first.\n if (this.previewScan) this.scanPreviews();\n else this.pumpPreviews();\n }\n\n dispose(): void {\n if (this.disposed) return;\n this.exitInteract();\n this.disposed = true;\n this.stopPreviews();\n this.previews.clear();\n for (const id of [...this.frames.keys()]) this.destroyFrame(id);\n for (const e of this.entries.values()) {\n if (e.ownUrl) URL.revokeObjectURL(e.ownUrl);\n for (const u of e.stale) URL.revokeObjectURL(u);\n }\n for (const [t, url] of this.timers) {\n clearTimeout(t);\n URL.revokeObjectURL(url);\n }\n this.timers.clear();\n this.entries.clear();\n for (const f of this.cleanups) f();\n // A shared monitor stops if this layer was the last thing it was measuring for.\n this.monitor.poke();\n this.root.remove();\n }\n\n // ── Tracking and resolution ────────────────────────────────────────────────\n private onStore(e: StoreEvent): void {\n if (e.type !== 'change' || this.disposed) return;\n for (const el of e.change.removed) this.untrack(el.id);\n // What the store holds now: a card added or updated and then removed in the same batch is gone.\n for (const el of e.change.added) this.trackCurrent(el.id);\n for (const u of e.change.updated) this.trackCurrent(u.el.id);\n this.planDirty = true;\n this.previewScan = true;\n }\n\n private untrack(id: ElementId): void {\n if (this.frames.has(id)) this.destroyFrame(id);\n if (this.interactId === id) this.exitInteract();\n const e = this.entries.get(id);\n if (!e) return;\n e.token++;\n this.abortPreview(e);\n // The element may live on as another kind; a removed one drops its override with it.\n if (this.store.get(id)) this.stage.setPosterOverride(id, null);\n if (e.ownUrl) this.retire(e.ownUrl);\n for (const u of e.stale) this.retire(u);\n this.entries.delete(id);\n }\n\n private trackCurrent(id: ElementId): void {\n const el = this.store.get(id);\n if (el) this.track(el);\n }\n\n private track(el: Element): void {\n const embed = el.media.embed;\n if (el.kind !== 'embed' || !embed) {\n this.untrack(el.id);\n return;\n }\n const prev = this.entries.get(el.id);\n if (prev && sameEmbed(prev.embed, embed)) {\n // Fields `sameEmbed` ignores (the per-card `resolution`, the title) are not new content: the frame, its\n // page and interact mode stay, only what shows them changes.\n if (prev.embed !== embed) {\n const retitled = prev.embed.title !== embed.title;\n prev.embed = embed;\n if (retitled) this.retitle(el.id, prev);\n const f = this.frames.get(el.id);\n if (f) this.place(el.id, f);\n this.requestPlan();\n }\n // The host gave the card a picture of its own, or took it away again: which poster shows follows.\n this.syncOverride(el.id, prev);\n return;\n }\n const stale = new Set<string>();\n if (prev) {\n if (this.frames.has(el.id)) this.destroyFrame(el.id);\n if (this.interactId === el.id) this.exitInteract();\n prev.token++;\n this.abortPreview(prev);\n if (prev.ownUrl) stale.add(prev.ownUrl);\n for (const u of prev.stale) stale.add(u);\n }\n // Our earlier posters stay under the card until the new one lands, unless the host brought a picture.\n if (prev && !this.needsPoster(el.id)) {\n this.stage.setPosterOverride(el.id, null);\n for (const u of stale) this.retire(u);\n stale.clear();\n }\n const info = baseResolved(embed);\n const entry: Entry = {\n embed,\n info,\n ready: false,\n spec: null,\n token: (prev?.token ?? 0) + 1,\n ownUrl: null,\n ownKind: null,\n stale,\n initialAspect: el.w > 0 ? el.h / el.w : 1,\n lastUsed: prev?.lastUsed ?? 0,\n lastSeen: prev?.lastSeen ?? 0,\n pv: 'idle',\n pvTries: 0,\n pvKey: '',\n };\n this.entries.set(el.id, entry);\n // No resolver: what the URL says is final, and the card can go live at once.\n if (!this.opts.resolve || info.kind === 'html' || info.url === '') this.settle(entry);\n void this.resolve(el.id, entry);\n }\n\n // The card's own title wins over the resolver's. Redraws a generated tile with the new one.\n private retitle(id: ElementId, entry: Entry): void {\n entry.info = { ...entry.info, title: entry.embed.title ?? entry.resolverTitle };\n if (entry.ready) {\n entry.spec = this.specFor(entry);\n const f = this.frames.get(id);\n if (f && entry.spec) f.iframe.title = entry.spec.title;\n }\n if (entry.ownKind === 'tile') void this.makeTile(id, entry, entry.token);\n }\n\n private settle(entry: Entry): void {\n entry.ready = true;\n entry.spec = this.specFor(entry);\n if (entry.spec === null && entry.info.kind === 'url') entry.info = { ...entry.info, frameable: false };\n this.previewScan = true;\n this.requestPlan();\n }\n\n private specFor(entry: Entry): IframeSpec | null {\n if (!canGoLive(entry.info)) return null;\n const spec = iframeSpecFor({\n source: entry.embed,\n iframeSrc: entry.info.iframeSrc ?? undefined,\n appOrigin: this.appOrigin,\n arbitrarySameOrigin: this.opts.arbitrarySameOrigin,\n });\n // Only the URL the iframe loads changes; `entry.info` keeps the plain one.\n if (spec?.src !== undefined) {\n spec.src = withJsApi(spec.provider, spec.src, this.appOrigin);\n if (this.opts.autoplay) spec.src = withAutoplay(spec.provider, spec.src);\n }\n return spec;\n }\n\n private async resolve(id: ElementId, entry: Entry): Promise<void> {\n // Never inside the store's change notification that got us here.\n await Promise.resolve();\n const token = entry.token;\n const alive = (): boolean => !this.disposed && this.entries.get(id) === entry && entry.token === token;\n if (!entry.ready) {\n let answer: Awaited<ReturnType<EmbedResolver>> = null;\n const resolver = this.opts.resolve;\n if (resolver) {\n try {\n answer = await withTimeout(Promise.resolve(resolver(entry.info.url)), this.opts.resolveTimeoutMs);\n } catch (err) {\n console.warn('[corkboard] embed resolver failed:', err);\n }\n }\n if (!alive()) return;\n if (typeof answer?.title === 'string' && answer.title !== '') entry.resolverTitle = answer.title;\n entry.info = mergeResolved(entry.info, answer);\n this.settle(entry);\n }\n // The shape a resolver reported, for a card that still has the shape it was created with.\n const el = this.store.get(id);\n if (!el || !alive()) return;\n const a = entry.info.aspect;\n const cur = el.w > 0 ? el.h / el.w : 1;\n if (\n a !== undefined &&\n el.media.aspect === undefined &&\n Math.abs(cur - entry.initialAspect) < 0.01 &&\n Math.abs(a - cur) > 0.005\n ) {\n this.store.update(id, { h: Math.max(1, Math.round(el.w * a)) });\n }\n // A picture of the host's stays as it is; otherwise this layer supplies one.\n const hostPoster = this.needsPoster(id) ? undefined : this.store.get(id)?.media.src;\n const photo = hostPoster === undefined ? await this.loadPoster(id, entry, token) : null;\n if (!alive()) return;\n this.emit('embedResolved', {\n id,\n provider: entry.info.provider,\n frameable: entry.info.frameable,\n aspect: entry.info.aspect,\n title: entry.info.title,\n // A URL worth persisting: the host's, or a provider thumbnail. A generated tile is a blob that dies\n // with the page, so it is not reported.\n poster: hostPoster ?? photo ?? undefined,\n });\n }\n\n // The card has no picture of the host's: this layer supplies one. Any `blob:` src counts as ours: the ones\n // this entry made (current or stale), and those of an earlier session that a saved `board.all()` or an\n // undo stack brought back, whose blob died with that page. (So a host's own `blob:` poster on an embed\n // card is replaced: give it an https or data: URL.)\n private needsPoster(id: ElementId): boolean {\n const src = this.store.get(id)?.media.src;\n return src === undefined || src.startsWith('blob:');\n }\n\n // Returns the candidate URL that became the poster, null for a generated tile.\n private async loadPoster(id: ElementId, entry: Entry, token: number): Promise<string | null> {\n const alive = (): boolean => !this.disposed && this.entries.get(id) === entry && entry.token === token;\n for (const candidate of entry.info.posters) {\n const url = await fetchPoster(candidate);\n if (!alive()) {\n if (url) URL.revokeObjectURL(url);\n return null;\n }\n if (url) {\n this.applyPoster(id, entry, url, 'photo');\n return candidate;\n }\n }\n await this.makeTile(id, entry, token);\n return null;\n }\n\n private async makeTile(id: ElementId, entry: Entry, token: number): Promise<void> {\n const el = this.store.get(id);\n if (!el) return;\n const theme: Theme = this.stage.activeTheme;\n const blob = await drawTile(tileSpec(entry.info), el.w > 0 ? el.h / el.w : 0.5625, theme);\n if (!blob) return;\n if (this.disposed || this.entries.get(id) !== entry || entry.token !== token) return;\n this.applyPoster(id, entry, URL.createObjectURL(blob), 'tile');\n }\n\n private applyPoster(id: ElementId, entry: Entry, url: string, kind: 'photo' | 'tile' | 'snapshot' | 'preview'): void {\n // A late tile or photo never covers a real picture of the snippet: the last frame of a card that went live,\n // or its preview. A preview never covers that last frame either.\n const real = entry.ownKind === 'snapshot' || entry.ownKind === 'preview';\n if (kind !== 'snapshot' && (kind === 'preview' ? entry.ownKind === 'snapshot' : real)) {\n URL.revokeObjectURL(url);\n return;\n }\n if (!this.store.get(id)) {\n URL.revokeObjectURL(url);\n return;\n }\n const prev = entry.ownUrl;\n entry.ownUrl = url;\n entry.ownKind = kind;\n this.syncOverride(id, entry);\n if (prev) this.retire(prev);\n for (const u of entry.stale) this.retire(u);\n entry.stale.clear();\n }\n\n // The poster this layer made is a runtime override on the stage, never written to the store (its URL dies\n // with the page, and a store change per snapshot would reach the host's listeners and its autosave). A\n // picture of the host's in `media.src` wins over a tile or provider photo, not over a real picture of the\n // snippet (a snapshot or preview).\n private syncOverride(id: ElementId, entry: Entry): void {\n if (entry.ownUrl === null) return;\n const real = entry.ownKind === 'snapshot' || entry.ownKind === 'preview';\n this.stage.setPosterOverride(id, real || this.needsPoster(id) ? entry.ownUrl : null);\n }\n\n // The old texture may still be in flight in a decode worker: revoke later.\n private retire(url: string): void {\n const t = setTimeout(() => {\n this.timers.delete(t);\n URL.revokeObjectURL(url);\n }, REVOKE_DELAY_MS);\n this.timers.set(t, url);\n }\n\n // ── Live iframes ───────────────────────────────────────────────────────────\n private requestPlan(): void {\n this.planDirty = true;\n this.stage.markDirty();\n }\n\n // The visible rect grown by `cullMargin` of the viewport on each side: what counts as on screen.\n private cullRect(): Rect {\n const v = this.stage.cam.visibleRect();\n const mx = (v.x1 - v.x0) * this.opts.cullMargin;\n const my = (v.y1 - v.y0) * this.opts.cullMargin;\n return { x0: v.x0 - mx, y0: v.y0 - my, x1: v.x1 + mx, y1: v.y1 + my };\n }\n\n private cards(): PolicyCard[] {\n const cam = this.stage.cam;\n const view = cam.visibleRect();\n const grown = this.cullRect();\n const seen = ++this.clock;\n const k = cam.scale;\n const out: PolicyCard[] = [];\n for (const [id, entry] of this.entries) {\n const el = this.store.get(id);\n if (!el || !entry.ready) continue;\n const r = this.stage.previewRectOf(id) ?? el;\n const b = elementBox({ x: r.x, y: r.y, w: r.w, h: r.h, rot: r.rot });\n // The part of the card that is in view: a neighbour with a sliver showing is not worth an iframe.\n const visW = (Math.min(b.maxX, view.x1) - Math.max(b.minX, view.x0)) * k;\n const visH = (Math.min(b.maxY, view.y1) - Math.max(b.minY, view.y0)) * k;\n const onScreen = overlaps(b, grown);\n if (onScreen) entry.lastSeen = seen;\n out.push({\n id,\n screenW: Math.min(r.w * k, visW),\n screenH: Math.min(r.h * k, visH),\n onScreen,\n selected: this.selected.has(id),\n interacting: this.interactId === id,\n frameable: entry.spec !== null,\n live: this.frames.has(id),\n lastUsed: entry.lastUsed,\n lastSeen: entry.lastSeen,\n });\n }\n return out;\n }\n\n private runPlan(force = false): void {\n this.planDirty = false;\n const plan = planLive({\n cards: this.cards(),\n cameraMoving: this.moving && !force,\n scale: this.stage.cam.scale,\n max: this.maxLive,\n maxMounted: this.maxMounted,\n maxOffscreen: this.maxOffscreen,\n minW: this.opts.minLive.w,\n minH: this.opts.minLive.h,\n minScale: this.opts.minLiveScale,\n });\n for (const id of plan.destroy) this.destroyFrame(id);\n // Chunked start: only as many new frames as there are free loading slots. The rest wait for the next\n // plan, which a load (or a slot timing out) asks for. The card in interact mode never waits.\n let free = this.opts.maxLoading;\n for (const f of this.frames.values()) if (f.slot) free--;\n for (const id of this.byPriority(plan.mount)) {\n if (free <= 0 && id !== this.interactId) continue;\n this.mountFrame(id);\n free--;\n }\n // Parked frames stay on screen but are never in interact mode (an interacting card is always active).\n // `plan.culled` needs no work here: `place()` hides the off-screen frames every frame.\n const parked = new Set(plan.parked);\n const settled = !this.moving;\n for (const [id, f] of this.frames) {\n if (parked.has(id)) {\n if (this.interactId === id) this.exitInteract();\n f.wrapper.dataset.parked = '';\n f.parked = true;\n } else {\n delete f.wrapper.dataset.parked;\n f.parked = false;\n }\n }\n // After parking is known and before each frame is tuned, so the pause it gets already counts the budget.\n this.rerank();\n for (const [id, f] of this.frames) {\n this.tune(id, f, this.stage.previewRectOf(id) ?? this.store.get(id), settled);\n }\n }\n\n // Interacting, then selected, then nearest the centre of the view.\n private byPriority(ids: readonly ElementId[]): ElementId[] {\n if (ids.length < 2) return [...ids];\n const v = this.stage.cam.visibleRect();\n const cx = (v.x0 + v.x1) / 2;\n const cy = (v.y0 + v.y1) / 2;\n const rank = new Map<ElementId, number>();\n for (const id of ids) {\n const r = this.stage.previewRectOf(id) ?? this.store.get(id);\n const d = r ? Math.hypot(r.x + r.w / 2 - cx, r.y + r.h / 2 - cy) : Infinity;\n const tier = this.interactId === id ? 0 : this.selected.has(id) ? 1 : 2;\n rank.set(id, tier * 1e12 + d);\n }\n return [...ids].sort((a, b) => (rank.get(a) ?? 0) - (rank.get(b) ?? 0));\n }\n\n private releaseSlot(f: Frame): void {\n if (f.slotTimer !== null) clearTimeout(f.slotTimer);\n f.slotTimer = null;\n if (!f.slot) return;\n f.slot = false;\n // The next chunk can start.\n this.requestPlan();\n }\n\n private mountFrame(id: ElementId): void {\n const entry = this.entries.get(id);\n const spec = entry?.spec;\n if (!entry || !spec || this.frames.has(id)) return;\n const wrapper = this.doc.createElement('div');\n wrapper.className = 'cb-embed';\n const iframe = this.doc.createElement('iframe');\n iframe.title = spec.title;\n iframe.setAttribute('sandbox', spec.sandbox);\n iframe.setAttribute('allow', spec.allow);\n iframe.setAttribute('referrerpolicy', spec.referrerPolicy);\n iframe.setAttribute('loading', spec.loading);\n if (spec.srcdoc !== undefined) iframe.srcdoc = spec.srcdoc;\n else if (spec.src !== undefined) iframe.src = spec.src;\n const frame: Frame = {\n wrapper,\n iframe,\n loaded: false,\n slot: true,\n slotTimer: null,\n w: NaN,\n h: NaN,\n radius: NaN,\n transform: '',\n z: NaN,\n culled: false,\n cullTimer: null,\n cullSnapAt: -Infinity,\n parked: false,\n kind: spec.profile === 'snippet' ? 'snippet' : spec.provider === 'youtube' || spec.provider === 'vimeo' ? 'video' : 'page',\n provider: spec.provider,\n origin: originOf(spec.src),\n small: false,\n frozen: false,\n snapFailed: false,\n snapTries: 0,\n retry: null,\n snap: null,\n landTimer: null,\n drawing: false,\n paused: false,\n interacted: false,\n loadTimer: null,\n overBudget: false,\n };\n frame.slotTimer = setTimeout(() => this.releaseSlot(frame), LOAD_SLOT_MS);\n // Runs for every navigation of the iframe (a snippet that reloads itself, a page that follows a link), and\n // each one is a new document: it knows nothing of what the previous one was told or asked.\n iframe.addEventListener('load', () => {\n frame.loaded = true;\n // Transparent from here on (the iframe fades in): the poster under it shows until the page paints.\n wrapper.dataset.ready = '';\n this.releaseSlot(frame);\n // So `syncPause` sends again what the new document should be doing. A frozen frame stays frozen (its\n // picture is still the poster); a snapshot request of the old document is dropped.\n frame.paused = false;\n this.dropRequest(frame);\n frame.snapFailed = false;\n frame.snapTries = 0;\n if (frame.retry !== null) clearTimeout(frame.retry);\n frame.retry = null;\n if (frame.loadTimer !== null) clearTimeout(frame.loadTimer);\n frame.loadTimer = null;\n // Pause, resume and snapshots only talk to a loaded document; the plan decides about a snapshot.\n this.syncPause(id, frame, false);\n if (frame.kind === 'video') {\n frame.loadTimer = setTimeout(() => {\n frame.loadTimer = null;\n this.syncPause(id, frame, true);\n }, PLAYER_READY_MS);\n }\n this.requestPlan();\n });\n // Until the page has loaded: the poster under a veil, and a spinner sized to the card.\n const spin = this.doc.createElement('div');\n spin.className = 'cb-embed-spin';\n spin.setAttribute('role', 'progressbar');\n spin.setAttribute('aria-label', 'Loading embed');\n wrapper.append(spin, iframe);\n this.frames.set(id, frame);\n entry.lastUsed = ++this.clock;\n this.place(id, frame);\n this.root.insertBefore(wrapper, this.done);\n this.emit('embedLive', { id, live: true });\n }\n\n private destroyFrame(id: ElementId): void {\n const f = this.frames.get(id);\n if (!f) return;\n this.frames.delete(id);\n this.animatingIds.delete(id);\n if (f.slotTimer !== null) clearTimeout(f.slotTimer);\n if (f.loadTimer !== null) clearTimeout(f.loadTimer);\n if (f.retry !== null) clearTimeout(f.retry);\n if (f.cullTimer !== null) clearTimeout(f.cullTimer);\n f.cullTimer = null;\n this.cancelSnapshot(f);\n if (this.interactId === id) this.exitInteract();\n // Navigate away first so the page (and its process) is released, then drop the node.\n f.iframe.removeAttribute('srcdoc');\n f.iframe.src = 'about:blank';\n f.wrapper.remove();\n // Back to its poster: if that is a tile, it can have a preview now.\n this.previewScan = true;\n this.emit('embedLive', { id, live: false });\n }\n\n // Writes size and transform only when they changed.\n // `view`: the cull rect (computed once per frame by the caller); `seen`: stamp for cards in view.\n private place(id: ElementId, f: Frame, view: Rect = this.cullRect(), seen = 0): void {\n const r = this.stage.previewRectOf(id) ?? this.store.get(id);\n if (!r) return;\n // The card in interact mode is never hidden. A rotated card is tested by its bounding box.\n const off = this.interactId !== id && !overlaps(elementBox({ x: r.x, y: r.y, w: r.w, h: r.h, rot: r.rot }), view);\n if (off !== f.culled) {\n f.culled = off;\n if (off) this.cull(id, f);\n else this.uncull(f);\n }\n if (!off && seen > 0) {\n const entry = this.entries.get(id);\n if (entry) entry.lastSeen = seen;\n }\n const cam: Camera = this.stage.cam.cam;\n const res = this.entries.get(id)?.embed.resolution ?? this.opts.resolution;\n const p = embedPlacement({ x: r.x, y: r.y, w: r.w, h: r.h, rot: r.rot }, cam, res);\n const s = f.wrapper.style;\n if (p.width !== f.w) {\n f.w = p.width;\n s.width = `${p.width}px`;\n }\n if (p.height !== f.h) {\n f.h = p.height;\n s.height = `${p.height}px`;\n }\n if (p.transform !== f.transform) {\n f.transform = p.transform;\n s.transform = p.transform;\n }\n // The card's corner radius is in world px, the wrapper is laid out in its own px (a 720p virtual screen):\n // scaled, so the frame's corners are the poster's corners.\n const radius = Math.round((((this.store.get(id)?.radius ?? 0) * p.width) / Math.max(r.w, 1)) * 100) / 100;\n if (radius !== f.radius) {\n f.radius = radius;\n s.borderRadius = `${radius}px`;\n }\n const z = this.store.rank(id) + 1;\n if (z !== f.z) {\n f.z = z;\n s.zIndex = String(z);\n }\n if (this.interactId === id) {\n const w = this.stage.cam.width;\n const h = this.stage.cam.height;\n const x = Math.min(Math.max(p.topRightX, 90), w) - DONE_MARGIN;\n const y = Math.min(Math.max(p.topRightY, 0), h - 40) + DONE_MARGIN;\n this.done.style.transform = `translate(${Math.round(x)}px, ${Math.round(y)}px) translateX(-100%)`;\n }\n // Not yet settled: a frame can come back (grow, get selected) or be paused (culled) at once, but only the\n // plan, once the camera is still, sends one to sleep.\n this.tune(id, f, r, false);\n }\n\n // ── Leaving and returning ──────────────────────────────────────────────────\n // The card left the view. A loaded snippet is snapshotted first and hidden when that is done (its last frame\n // then waits as the poster); anything else is hidden at once.\n private cull(id: ElementId, f: Frame): void {\n if (!this.canSnapCull(id, f) || !this.requestSnapshot(id, f, true)) {\n f.wrapper.dataset.culled = '';\n return;\n }\n f.wrapper.dataset.culling = '';\n f.cullTimer = setTimeout(() => this.finishCull(f), CULL_SNAPSHOT_MS);\n f.cullSnapAt = Date.now();\n }\n\n private canSnapCull(id: ElementId, f: Frame): boolean {\n return (\n f.kind === 'snippet' &&\n f.loaded &&\n !f.frozen &&\n !f.snap &&\n !f.drawing &&\n f.landTimer === null &&\n this.camSpeed < CULL_SNAPSHOT_MAX_SPEED &&\n this.snapping < MAX_SNAPSHOTS - CULL_SNAPSHOT_RESERVE &&\n Date.now() - f.cullSnapAt >= CULL_SNAPSHOT_MIN_MS &&\n this.entries.has(id)\n );\n }\n\n // The snapshot is in (or took too long): hide the frame, if its card is still away.\n private finishCull(f: Frame): void {\n if (f.cullTimer !== null) clearTimeout(f.cullTimer);\n f.cullTimer = null;\n delete f.wrapper.dataset.culling;\n if (f.culled) f.wrapper.dataset.culled = '';\n }\n\n // The card is back. A frame still waiting to be hidden never was.\n private uncull(f: Frame): void {\n if (f.snap?.cull) {\n this.cancelSnapshot(f);\n // Nothing came of it: the next time the card leaves may ask again.\n f.cullSnapAt = -Infinity;\n }\n if (f.cullTimer !== null) {\n this.finishCull(f);\n return;\n }\n delete f.wrapper.dataset.culled;\n }\n\n // ── Freeze and pause ───────────────────────────────────────────────────────\n // Decides what a mounted frame does with its card's size, selection and parking. Cheap enough to run on\n // every frame for every frame: it writes and posts only when something changed.\n private tune(id: ElementId, f: Frame, r: { w: number; h: number } | undefined, settled: boolean): void {\n const held = this.interactId === id || this.selected.has(id);\n if (this.interactId === id) f.interacted = true;\n const px = this.freezeThreshold;\n let small = f.small;\n if (px <= 0 || held) small = false;\n else if (r && !f.culled) {\n const short = Math.min(r.w, r.h) * this.stage.cam.scale;\n if (small) small = short < px * FREEZE_HYSTERESIS;\n else if (settled) small = short < px;\n }\n if (small !== f.small) {\n f.small = small;\n if (!small) {\n f.snapFailed = false;\n f.snapTries = 0;\n if (f.retry !== null) clearTimeout(f.retry);\n f.retry = null;\n this.cancelSnapshot(f);\n if (f.frozen) this.setFrozen(f, false);\n }\n }\n if (\n small &&\n settled &&\n f.kind === 'snippet' &&\n f.loaded &&\n !f.culled &&\n !f.frozen &&\n !f.snap &&\n !f.drawing &&\n f.landTimer === null &&\n !f.snapFailed &&\n this.snapping < MAX_SNAPSHOTS\n ) {\n this.requestSnapshot(id, f);\n }\n this.syncPause(id, f, false);\n }\n\n private setFrozen(f: Frame, frozen: boolean): void {\n f.frozen = frozen;\n // A frozen frame leaves the ranking and a thawed one joins it.\n this.rankDirty = true;\n if (frozen) f.wrapper.dataset.frozen = '';\n else delete f.wrapper.dataset.frozen;\n }\n\n // Sends a snippet its pause / resume, or a video player its pause / play, when what it should be doing\n // changed. `force` repeats the pause to a player that may not have been listening yet.\n private syncPause(id: ElementId, f: Frame, force: boolean): void {\n if (!f.loaded) return;\n const interacting = this.interactId === id;\n if (f.kind === 'snippet') {\n const want = !interacting && (f.parked || f.culled || f.frozen || f.overBudget);\n if (want === f.paused) return;\n f.paused = want;\n this.post(f, { cb: EMBED_CB, op: want ? 'pause' : 'resume' }, '*');\n } else if (f.kind === 'video') {\n // A player nobody started does not play: pausing it would only for us to start it on the way back.\n const mayPlay = this.opts.autoplay || f.interacted;\n const want = mayPlay && !interacting && (f.small || f.parked || f.culled || f.overBudget);\n if (want === f.paused && !(force && want)) return;\n f.paused = want;\n this.command(f, want ? 'pause' : 'play');\n }\n }\n\n private post(f: Frame, msg: unknown, target: string): void {\n try {\n f.iframe.contentWindow?.postMessage(msg, target);\n } catch {\n // The frame is gone.\n }\n }\n\n // The player APIs: YouTube takes a JSON string, Vimeo an object, both only from the origin they were set up for.\n private command(f: Frame, op: 'pause' | 'play'): void {\n if (f.origin === '') return;\n if (f.provider === 'youtube') {\n const func = op === 'pause' ? 'pauseVideo' : 'playVideo';\n this.post(f, JSON.stringify({ event: 'command', func, args: [] }), f.origin);\n } else if (f.provider === 'vimeo') this.post(f, { method: op }, f.origin);\n }\n\n // ── Animating budget ───────────────────────────────────────────────────────\n // Whether a frame could be animating by itself: it can be paused, is not already asleep for another reason\n // (parked, culled, frozen, a small video) and, for a video, may be playing at all.\n private pausable(f: Frame): boolean {\n if (f.culled || f.frozen || f.parked) return false;\n if (f.kind === 'snippet') return true;\n return f.kind === 'video' && !f.small && (this.opts.autoplay || f.interacted);\n }\n\n // Ranks the frames that can be paused and pauses what is past the budget, resumes what is back inside it.\n // Interacting, then selected, then the most of the card in view, then nearest the centre. A page that cannot\n // be paused takes no slot (giving it one would change nothing) and is left alone.\n private rerank(): void {\n this.rankDirty = false;\n if (this.disposed) return;\n const cam = this.stage.cam;\n const v = cam.visibleRect();\n const k = cam.scale;\n const cx = (v.x0 + v.x1) / 2;\n const cy = (v.y0 + v.y1) / 2;\n const ranked: { id: ElementId; f: Frame; tier: number; area: number; dist: number }[] = [];\n let renderCount = 0;\n for (const [id, f] of this.frames) {\n if (!f.culled && !f.frozen) renderCount++;\n if (!this.pausable(f)) {\n this.setOverBudget(id, f, false);\n continue;\n }\n const r = this.stage.previewRectOf(id) ?? this.store.get(id);\n let area = 0;\n let dist = Infinity;\n if (r) {\n const b = elementBox({ x: r.x, y: r.y, w: r.w, h: r.h, rot: r.rot });\n area = Math.max(0, Math.min(b.maxX, v.x1) - Math.max(b.minX, v.x0)) * Math.max(0, Math.min(b.maxY, v.y1) - Math.max(b.minY, v.y0)) * k * k;\n dist = Math.hypot(r.x + r.w / 2 - cx, r.y + r.h / 2 - cy);\n }\n ranked.push({ id, f, tier: this.interactId === id ? 0 : this.selected.has(id) ? 1 : 2, area, dist });\n }\n ranked.sort((a, b) => a.tier - b.tier || b.area - a.area || a.dist - b.dist || (a.id < b.id ? -1 : 1));\n const budget = this.animatingBudget;\n const animating = new Set<ElementId>();\n ranked.forEach((c, i) => {\n const over = i >= budget;\n if (!over) animating.add(c.id);\n this.setOverBudget(c.id, c.f, over);\n });\n this.animatingIds = animating;\n this.candidates = ranked.length;\n // Frames mounted, destroyed, culled, frozen or thawed: the load changed, so it is measured again.\n if (renderCount !== this.renderCount) {\n this.renderCount = renderCount;\n this.monitor.poke();\n }\n }\n\n private setOverBudget(id: ElementId, f: Frame, over: boolean): void {\n if (over === f.overBudget) return;\n f.overBudget = over;\n this.syncPause(id, f, false);\n }\n\n // One window measured. Slow: shrink to 70% of what animates. Smooth for SMOOTH_WINDOWS in a row: grow.\n private onWindow(w: FrameWindow): void {\n if (!this.opts.adaptive || this.disposed) return;\n const budget = this.animatingBudget;\n let next = this.adaptiveN;\n if (w.slow) {\n this.smooth = 0;\n this.adaptFreeze(true);\n const lowered = Math.max(MIN_ANIMATING, Math.floor(this.animatingIds.size * 0.7));\n // A slow window never raises the budget.\n if (lowered < budget) next = lowered;\n } else if (w.smooth) {\n this.adaptFreeze(false);\n if (++this.smooth >= SMOOTH_WINDOWS && this.adaptiveN < this.opts.maxAnimating) {\n this.smooth = 0;\n next = Math.ceil(this.adaptiveN * 1.25) + 2;\n // Past everything that could animate, or past the ceiling: the limit is gone.\n if (next >= Math.min(this.opts.maxAnimating, this.candidates)) next = Infinity;\n }\n } else {\n this.smooth = 0;\n this.adaptFreeze(null);\n }\n if (next === this.adaptiveN) return;\n this.adaptiveN = next;\n this.rerank();\n // The budget moved: what that does to the page is measured next.\n this.monitor.poke();\n }\n\n // Hiding frames is what frees the most, so once the animating budget cannot go lower and windows are still\n // slow, bigger snippets freeze too (FREEZE_STEP x per slow window, up to FREEZE_MAX_MUL x `freezePx`). The same\n // steps back down after SMOOTH_WINDOWS smooth windows in a row. `null`: a window in between, neither.\n private adaptFreeze(slow: boolean | null): void {\n if (this.opts.freezePx <= 0) return;\n let mul = this.freezeMul;\n if (slow === true) {\n this.freezeSmooth = 0;\n if (this.animatingBudget <= MIN_ANIMATING) mul = Math.min(FREEZE_MAX_MUL, mul * FREEZE_STEP);\n } else if (slow === false) {\n if (++this.freezeSmooth >= SMOOTH_WINDOWS && mul > 1) {\n this.freezeSmooth = 0;\n mul = Math.max(1, mul / FREEZE_STEP);\n }\n } else this.freezeSmooth = 0;\n if (mul === this.freezeMul) return;\n this.freezeMul = mul;\n // Every frame is looked at again against the new size.\n this.requestPlan();\n this.monitor.poke();\n }\n\n // ── Snapshots ──────────────────────────────────────────────────────────────\n // `cull`: the card left the view, so the picture is its last frame at full size rather than a small one.\n // Returns false when there is nothing to ask for.\n private requestSnapshot(id: ElementId, f: Frame, cull = false): boolean {\n const el = this.store.get(id);\n if (!el || el.w <= 0 || el.h <= 0) return false;\n // Sharp at the biggest the card gets while frozen (short side FREEZE_HYSTERESIS x the freeze size, in device px),\n // whatever the zoom is now; at most SNAPSHOT_MAX_SIDE on the long side. A card that left the view comes\n // back at any size, so it gets the most there is.\n const dpr = this.doc.defaultView?.devicePixelRatio || 1;\n const k = Math.min(\n cull ? 2 * dpr : (this.freezeThreshold * FREEZE_HYSTERESIS * dpr) / Math.min(el.w, el.h),\n SNAPSHOT_MAX_SIDE / Math.max(el.w, el.h),\n );\n const seq = ++this.snapSeq;\n const w = Math.max(1, Math.round(el.w * k));\n const h = Math.max(1, Math.round(el.h * k));\n f.snap = { id: seq, timer: setTimeout(() => this.snapshotFailed(f, seq), SNAPSHOT_WAIT_MS), w, h, cull };\n this.snapping++;\n // `vw` x `vh`: the size the page is laid out at, for a frame whose window reports none (hidden).\n this.post(f, { cb: EMBED_CB, op: 'snapshot', id: seq, w, h, vw: f.w, vh: f.h }, '*');\n return true;\n }\n\n // Forgets the request in flight: a reply to it is ignored.\n private dropRequest(f: Frame): void {\n if (!f.snap) return;\n clearTimeout(f.snap.timer);\n f.snap = null;\n this.snapping--;\n }\n\n // ... and the wait for a poster.\n private cancelSnapshot(f: Frame): void {\n this.dropRequest(f);\n if (f.landTimer !== null) clearTimeout(f.landTimer);\n f.landTimer = null;\n }\n\n private snapshotFailed(f: Frame, seq: number): void {\n if (f.snap?.id !== seq) return;\n const cull = f.snap.cull;\n this.cancelSnapshot(f);\n // A failed last-frame snapshot costs nothing but the poster: no retries, and the freeze logic is not told.\n if (cull) this.finishCull(f);\n else this.markSnapFailed(f);\n }\n\n // A busy page can miss a snapshot that would work a moment later: try again, a few times, further apart.\n private markSnapFailed(f: Frame): void {\n f.snapFailed = true;\n if (++f.snapTries < SNAP_TRIES && f.retry === null) {\n f.retry = setTimeout(() => {\n f.retry = null;\n if (this.disposed) return;\n f.snapFailed = false;\n this.requestPlan();\n }, SNAP_RETRY_MS * f.snapTries);\n }\n // The next in the queue.\n this.requestPlan();\n }\n\n private onMessage(e: MessageEvent): void {\n const d = e.data as { cb?: unknown; op?: unknown; id?: unknown; ok?: unknown; svg?: unknown } | null;\n if (this.disposed || !d || typeof d !== 'object' || d.cb !== EMBED_CB || d.op !== 'snapshot') return;\n for (const s of this.studios) {\n const job = s.job;\n if (!job || job.seq !== d.id || e.source !== s.iframe?.contentWindow) continue;\n if (d.ok === false || typeof d.svg !== 'string' || d.svg === '') return this.previewFailed(job);\n return this.previewReply(job, d.svg);\n }\n for (const [id, f] of this.frames) {\n // Only the frame this layer mounted, and only the answer to the request it is waiting for.\n if (e.source !== f.iframe.contentWindow || !f.snap || f.snap.id !== d.id) continue;\n if (d.ok === false || typeof d.svg !== 'string' || d.svg === '') return this.snapshotFailed(f, f.snap.id);\n // The frame's markup, drawn here.\n const svg = d.svg;\n const { w, h, cull } = f.snap;\n const entry = this.entries.get(id);\n this.cancelSnapshot(f);\n // The frame has done its part: it can be hidden while the picture is drawn here, and the next in the\n // queue may ask. This one is not asked again until its picture is applied (`drawing`).\n f.drawing = true;\n if (cull) this.finishCull(f);\n this.requestPlan();\n const draw = (): Promise<Blob | null> => Promise.resolve(this.rasterize(svg, w, h)).catch(() => null);\n const done = (blob: Blob | null): void => {\n f.drawing = false;\n if (this.disposed || this.frames.get(id) !== f || this.entries.get(id) !== entry) return;\n // A frame that was waiting for this picture is looked at again.\n this.requestPlan();\n if (!blob || blob.size === 0) return cull ? undefined : this.markSnapFailed(f);\n this.showSnapshot(id, f, blob, cull);\n };\n // A cull snapshot is a nicety for a card that is off screen: drawn when the browser has nothing better to do.\n if (cull) {\n this.whenIdle(() => {\n if (this.disposed || this.frames.get(id) !== f) done(null);\n else void draw().then(done);\n });\n } else void draw().then(done);\n return;\n }\n }\n\n private whenIdle(fn: () => void): void {\n const win = this.doc.defaultView;\n if (win && typeof win.requestIdleCallback === 'function') win.requestIdleCallback(fn, { timeout: CULL_DRAW_IDLE_MS });\n else setTimeout(fn, 0);\n }\n\n private showSnapshot(id: ElementId, f: Frame, blob: Blob, cull = false): void {\n const entry = this.entries.get(id);\n if (!entry) return;\n if (cull) {\n // The card came back while it was drawn: the frame shows, and a new texture would only flash the placeholder.\n if (!f.culled) f.cullSnapAt = -Infinity;\n // Not frozen: the frame is hidden for being off screen, and shows again with its card.\n else this.applyPoster(id, entry, URL.createObjectURL(blob), 'snapshot');\n return;\n }\n if (!f.small) return;\n this.applyPoster(id, entry, URL.createObjectURL(blob), 'snapshot');\n this.awaitPoster(id, f, 0);\n }\n\n // Hides the frame once the poster under it shows. The stage swaps textures a frame or more after the poster\n // changes, and hiding the frame before that shows the placeholder.\n private awaitPoster(id: ElementId, f: Frame, tries: number): void {\n if (f.landTimer !== null) clearTimeout(f.landTimer);\n f.landTimer = setTimeout(\n () => {\n f.landTimer = null;\n if (this.disposed || this.frames.get(id) !== f || !f.small) return;\n if (this.posterShown(id)) {\n this.setFrozen(f, true);\n this.syncPause(id, f, false);\n } else if (tries + 1 < LAND_TRIES) this.awaitPoster(id, f, tries + 1);\n else f.snapFailed = true;\n },\n tries === 0 ? LAND_FIRST_MS : LAND_STEP_MS,\n );\n }\n\n // The card's sprite shows a rendition of its current poster (not the placeholder, the ThumbHash or the\n // poster it replaced, which stays on screen while the new one decodes).\n private posterShown(id: ElementId): boolean {\n return this.stage.posterShown(id);\n }\n\n // ── Previews ───────────────────────────────────────────────────────────────\n // Whether a card's poster is still no real picture of its snippet, and nothing else is about to make one: a\n // snippet (not a page), not mounted, with a tile or nothing (a picture of the host's is left alone).\n private wantsPreview(id: ElementId, entry: Entry): boolean {\n if (entry.info.kind !== 'html' || !entry.ready || entry.spec?.srcdoc === undefined) return false;\n if (this.frames.has(id) || entry.ownKind === 'snapshot' || entry.ownKind === 'preview') return false;\n return entry.ownKind === 'tile' || this.needsPoster(id);\n }\n\n // What a card's preview is: the layout box a live frame would get at the card's aspect (bucketed, so cards of\n // the same shape share it), and the picture's size, as sharp as a frozen snapshot of it.\n private previewPlan(id: ElementId, entry: Entry): PreviewPlan | null {\n const html = entry.embed.html;\n const el = this.store.get(id);\n if (html === undefined || !el || el.w <= 0 || el.h <= 0) return null;\n const bucket = Math.max(1, Math.round((el.h / el.w) * PREVIEW_BUCKETS));\n const rect = { x: 0, y: 0, w: PREVIEW_BOX, h: (PREVIEW_BOX * bucket) / PREVIEW_BUCKETS };\n const res = entry.embed.resolution ?? this.opts.resolution;\n const box = embedPlacement(rect, { tx: 0, ty: 0, scale: 1 }, res);\n const dpr = this.doc.defaultView?.devicePixelRatio || 1;\n const k = Math.min(\n (Math.max(this.opts.freezePx, FREEZE_PX) * FREEZE_HYSTERESIS * dpr) / Math.min(rect.w, rect.h),\n SNAPSHOT_MAX_SIDE / Math.max(rect.w, rect.h),\n );\n const w = Math.max(1, Math.round(rect.w * k));\n const h = Math.max(1, Math.round(rect.h * k));\n return { key: previewKey(html, bucket, String(res), w, h), vw: box.width, vh: box.height, w, h };\n }\n\n // Looks at the cards that may need a preview and have not been looked at: a picture already in the cache is\n // applied at once, the rest is queued.\n private scanPreviews(): void {\n this.previewScan = false;\n if (this.disposed || this.opts.previewWorkers <= 0) return;\n for (const [id, entry] of this.entries) {\n if (entry.pv !== 'idle' || !this.wantsPreview(id, entry)) continue;\n const plan = this.previewPlan(id, entry);\n if (!plan) continue;\n const hit = this.previews.getMemory(plan.key);\n entry.pvKey = plan.key;\n if (hit) this.applyPreview(id, entry, hit);\n else if (this.previews.persistent) this.lookupPreview(id, entry, plan.key);\n else entry.pv = 'queued';\n }\n this.pumpPreviews();\n }\n\n private lookupPreview(id: ElementId, entry: Entry, key: string): void {\n entry.pv = 'checking';\n const token = entry.token;\n void this.previews.getPersistent(key).then((blob) => {\n if (this.disposed || this.entries.get(id) !== entry || entry.token !== token || entry.pv !== 'checking') return;\n if (blob) this.previews.put(key, blob, false);\n if (!this.wantsPreview(id, entry)) entry.pv = 'idle';\n else if (blob) this.applyPreview(id, entry, blob);\n else entry.pv = 'queued';\n this.pumpPreviews();\n });\n }\n\n private applyPreview(id: ElementId, entry: Entry, blob: Blob): void {\n entry.pv = 'done';\n this.applyPoster(id, entry, URL.createObjectURL(blob), 'preview');\n }\n\n // Cards to render, best first: on screen, then nearest the centre of the view; a card that already failed once\n // goes after all the others.\n private nextPreview(): { id: ElementId; entry: Entry } | null {\n const v = this.stage.cam.visibleRect();\n const cx = (v.x0 + v.x1) / 2;\n const cy = (v.y0 + v.y1) / 2;\n let best: { id: ElementId; entry: Entry } | null = null;\n let bestRank = Infinity;\n // The same snippet on two cards is drawn once: the second waits for the first and then takes its picture.\n const busy = new Set<string>();\n for (const s of this.studios) if (s.job) busy.add(s.job.plan.key);\n for (const j of this.drawing) busy.add(j.plan.key);\n for (const [id, entry] of this.entries) {\n if (entry.pv !== 'queued' || busy.has(entry.pvKey)) continue;\n if (!this.wantsPreview(id, entry)) {\n // Went live or got a picture meanwhile; it is looked at again if it needs one later.\n entry.pv = 'idle';\n continue;\n }\n const r = this.stage.previewRectOf(id) ?? this.store.get(id);\n if (!r) continue;\n const on = overlaps(elementBox({ x: r.x, y: r.y, w: r.w, h: r.h, rot: r.rot }), v);\n const rank = entry.pvTries * 1e15 + (on ? 0 : 1e12) + Math.hypot(r.x + r.w / 2 - cx, r.y + r.h / 2 - cy);\n if (rank < bestRank) {\n bestRank = rank;\n best = { id, entry };\n }\n }\n return best;\n }\n\n // Starts jobs on free studios while there are queued cards. Nothing starts while the camera moves, the tab is\n // hidden (it would not paint) or there are no workers; studios left without a job are removed.\n private pumpPreviews(): void {\n if (this.disposed) return;\n const go = !this.moving && this.opts.previewWorkers > 0 && this.doc.visibilityState !== 'hidden';\n while (go) {\n if (this.studios.filter((s) => s.job).length >= this.opts.previewWorkers) break;\n const next = this.nextPreview();\n if (!next) break;\n const plan = this.previewPlan(next.id, next.entry);\n if (!plan) {\n next.entry.pv = 'failed';\n continue;\n }\n // The same snippet was drawn while this one waited.\n const hit = this.previews.getMemory(plan.key);\n if (hit) {\n this.applyPreview(next.id, next.entry, hit);\n continue;\n }\n const studio = this.studios.find((s) => !s.job) ?? this.makeStudio();\n if (!studio) break;\n this.startPreview(studio, next.id, next.entry, plan);\n }\n for (const s of this.studios.filter((x) => !x.job)) this.removeStudio(s);\n }\n\n private makeStudio(): Studio | null {\n const body = this.doc.body;\n if (!body) return null;\n const box = this.doc.createElement('div');\n box.style.cssText = STUDIO_CSS;\n box.setAttribute('aria-hidden', 'true');\n box.setAttribute('inert', '');\n // The iframe is made by the job, before the box goes in: no empty document loads first.\n const studio: Studio = { box, iframe: null, job: null };\n this.studios.push(studio);\n return studio;\n }\n\n private removeStudio(s: Studio): void {\n const i = this.studios.indexOf(s);\n if (i >= 0) this.studios.splice(i, 1);\n s.job = null;\n if (s.iframe) {\n s.iframe.removeAttribute('srcdoc');\n s.iframe.src = 'about:blank';\n }\n s.box.remove();\n }\n\n private startPreview(studio: Studio, id: ElementId, entry: Entry, plan: PreviewPlan): void {\n const spec = entry.spec;\n if (!spec || spec.srcdoc === undefined) return;\n const job: PreviewJob = { id, entry, token: entry.token, studio, plan, seq: 0, loaded: false, settle: null, timer: null };\n job.timer = setTimeout(() => this.previewFailed(job), PREVIEW_JOB_MS);\n entry.pv = 'running';\n studio.job = job;\n // A fresh iframe: the old one, with whatever it is still loading, is gone with its load event.\n const old = studio.iframe;\n if (old) {\n old.removeAttribute('srcdoc');\n old.src = 'about:blank';\n old.remove();\n }\n const ifr = this.doc.createElement('iframe');\n studio.iframe = ifr;\n ifr.tabIndex = -1;\n ifr.setAttribute('aria-hidden', 'true');\n ifr.style.cssText = 'border:0;display:block;';\n ifr.addEventListener('load', () => {\n // Only the load of this job's document, once.\n if (studio.job !== job || studio.iframe !== ifr || job.loaded) return;\n job.loaded = true;\n job.settle = setTimeout(() => this.askPreview(job), PREVIEW_SETTLE_MS);\n });\n // The same sandbox, CSP and bootstrap as a live frame.\n ifr.title = spec.title;\n ifr.setAttribute('sandbox', spec.sandbox);\n ifr.setAttribute('allow', spec.allow);\n ifr.setAttribute('referrerpolicy', spec.referrerPolicy);\n ifr.style.width = studio.box.style.width = `${plan.vw}px`;\n ifr.style.height = studio.box.style.height = `${plan.vh}px`;\n ifr.srcdoc = spec.srcdoc;\n studio.box.appendChild(ifr);\n if (!studio.box.isConnected) this.doc.body.appendChild(studio.box);\n }\n\n // Loaded and given time to move on from its first frame: ask for the picture.\n private askPreview(job: PreviewJob): void {\n job.settle = null;\n const s = job.studio;\n if (!s || s.job !== job) return;\n job.seq = ++this.snapSeq;\n const { plan } = job;\n try {\n s.iframe?.contentWindow?.postMessage({ cb: EMBED_CB, op: 'snapshot', id: job.seq, w: plan.w, h: plan.h, vw: plan.vw, vh: plan.vh }, '*');\n } catch {\n // The frame is gone: the job times out.\n }\n }\n\n private endJob(job: PreviewJob): void {\n if (job.settle !== null) clearTimeout(job.settle);\n if (job.timer !== null) clearTimeout(job.timer);\n job.settle = job.timer = null;\n if (job.studio?.job === job) job.studio.job = null;\n job.studio = null;\n this.drawing.delete(job);\n }\n\n private jobAlive(job: PreviewJob): boolean {\n return !this.disposed && this.entries.get(job.id) === job.entry && job.entry.token === job.token;\n }\n\n // No picture: the tile stays. One more try, after everything else.\n private previewFailed(job: PreviewJob): void {\n this.endJob(job);\n if (this.jobAlive(job)) {\n job.entry.pvTries++;\n job.entry.pv = job.entry.pvTries < PREVIEW_TRIES ? 'queued' : 'failed';\n }\n this.pumpPreviews();\n }\n\n // The frame answered: it is free for the next job while the markup is drawn here.\n private previewReply(job: PreviewJob, svg: string): void {\n this.endJob(job);\n const drawn = setTimeout(() => this.previewFailed(job), PREVIEW_DRAW_MS);\n job.timer = drawn;\n this.drawing.add(job);\n this.pumpPreviews();\n void Promise.resolve()\n .then(() => this.rasterize(svg, job.plan.w, job.plan.h))\n .catch(() => null)\n .then((blob) => {\n // Timed out meanwhile (the timer fired and requeued it): too late.\n if (job.timer !== drawn) return;\n this.endJob(job);\n if (!this.jobAlive(job)) return;\n if (!blob || blob.size === 0) return this.previewFailed(job);\n this.previews.put(job.plan.key, blob);\n const { id, entry } = job;\n if (this.wantsPreview(id, entry)) this.applyPreview(id, entry, blob);\n else entry.pv = 'idle';\n this.pumpPreviews();\n });\n }\n\n // Drops the job of an entry that is going away (its card was removed or its embed changed).\n private abortPreview(entry: Entry): void {\n for (const s of this.studios) if (s.job?.entry === entry) this.endJob(s.job);\n for (const j of [...this.drawing]) if (j.entry === entry) this.endJob(j);\n entry.pv = 'idle';\n if (!this.disposed) this.pumpPreviews();\n }\n\n // No workers, or the end: jobs are dropped, studios removed, queued cards forgotten.\n private stopPreviews(): void {\n for (const s of [...this.studios]) {\n if (s.job) this.endJob(s.job);\n this.removeStudio(s);\n }\n for (const j of [...this.drawing]) this.endJob(j);\n for (const e of this.entries.values()) if (e.pv === 'checking' || e.pv === 'queued' || e.pv === 'running') e.pv = 'idle';\n }\n\n // ── Interact mode ──────────────────────────────────────────────────────────\n // Fits the card, but never below the zoom a frame mounts at: a card too big for that (a 600x4000 page on\n // a short screen) is centred at that zoom instead.\n private flyIn(id: ElementId): void {\n const cam = this.stage.cam;\n const r = this.stage.contentBounds([id]);\n const w = Math.min(r.x1 - r.x0, Math.max(1, cam.width - FLY_PAD * 2) / FLY_IN_SCALE);\n const h = Math.min(r.y1 - r.y0, Math.max(1, cam.height - FLY_PAD * 2) / FLY_IN_SCALE);\n const cx = (r.x0 + r.x1) / 2;\n const cy = (r.y0 + r.y1) / 2;\n this.stage.fitRect({ x0: cx - w / 2, y0: cy - h / 2, x1: cx + w / 2, y1: cy + h / 2 }, true, FLY_PAD);\n }\n\n // `flown`: the camera has already flown in for this card, so it does not fly again.\n private activate(id: ElementId, keyboard: boolean, flown = false): boolean {\n const entry = this.entries.get(id);\n const el = this.store.get(id);\n if (!entry || !el || !entry.ready) return false;\n if (this.interactId === id) return true;\n if (entry.spec === null) {\n // A bookmark: the page cannot be framed.\n if (entry.info.url !== '') window.open(entry.info.url, '_blank', 'noopener,noreferrer');\n return true;\n }\n if (this.stage.cam.scale < MIN_LIVE_SCALE) {\n // Too far out to mount anything: fly in, then interact once the camera settles (once: a camera that\n // cannot get in far enough, say a low maxScale, gives up).\n if (flown) return false;\n this.pendingInteract = id;\n this.flyIn(id);\n return true;\n }\n if (this.interactId !== null) this.exitInteract();\n entry.lastUsed = ++this.clock;\n this.interactId = id;\n this.runPlan(true);\n const f = this.frames.get(id);\n if (!f) {\n this.interactId = null;\n return false;\n }\n f.wrapper.dataset.interact = '';\n this.done.style.display = 'block';\n this.place(id, f);\n if (keyboard) this.done.focus({ preventScroll: true });\n this.emit('embedInteract', { id, active: true });\n return true;\n }\n}\n\n// A number of studios: whole, never negative.\nconst normWorkers = (n: number): number => (Number.isNaN(n) ? PREVIEW_WORKERS : Math.min(8, Math.max(0, Math.floor(n))));\n\n// A frame count: whole, never negative (Infinity stays).\nconst normBudget = (n: number): number => (Number.isNaN(n) ? Infinity : Math.max(0, Math.floor(n)));\n\nfunction originOf(u: string | undefined): string {\n try {\n return u === undefined ? '' : new URL(u).origin;\n } catch {\n return '';\n }\n}\n\n// An SVG drawn on a white canvas at w x h, as WebP. An SVG image runs no script and loads nothing; it does\n// not taint the canvas in Chromium. null where it cannot be drawn (Safari taints it).\nasync function rasterizeSvg(doc: Document, svg: string, w: number, h: number): Promise<Blob | null> {\n try {\n const img = new Image();\n img.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;\n await img.decode();\n const c = doc.createElement('canvas');\n c.width = w;\n c.height = h;\n const g = c.getContext('2d');\n if (!g) return null;\n g.fillStyle = '#fff';\n g.fillRect(0, 0, w, h);\n g.drawImage(img, 0, 0, w, h);\n return await new Promise<Blob | null>((resolve) => c.toBlob(resolve, 'image/webp', 0.85));\n } catch {\n return null;\n }\n}\n\nfunction withTimeout<T>(p: Promise<T>, ms: number): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const t = setTimeout(() => reject(new Error(`timed out after ${ms} ms`)), ms);\n p.then(\n (v) => {\n clearTimeout(t);\n resolve(v);\n },\n (e: unknown) => {\n clearTimeout(t);\n reject(e instanceof Error ? e : new Error(String(e)));\n },\n );\n });\n}\n","// A tiny typed event emitter.\nexport type Listener<T> = (payload: T) => void;\n\nexport class Emitter<M extends object> {\n private readonly map = new Map<keyof M, Set<Listener<never>>>();\n\n on<K extends keyof M>(type: K, fn: Listener<M[K]>): () => void {\n let set = this.map.get(type);\n if (!set) {\n set = new Set();\n this.map.set(type, set);\n }\n set.add(fn as Listener<never>);\n return () => this.off(type, fn);\n }\n\n off<K extends keyof M>(type: K, fn: Listener<M[K]>): void {\n this.map.get(type)?.delete(fn as Listener<never>);\n }\n\n emit<K extends keyof M>(type: K, payload: M[K]): void {\n const set = this.map.get(type);\n if (!set) return;\n for (const fn of [...set]) (fn as Listener<M[K]>)(payload);\n }\n\n clear(): void {\n this.map.clear();\n }\n}\n","// Public data model of a corkboard. Pure types and constants: no Pixi, no DOM.\n//\n// Coordinates are world px at zoom 1. `rot` is DEGREES clockwise about the element's centre.\n\n// Element kinds. Adding a kind is one view (src/render/views/registry.ts) plus, when it needs DOM, one\n// overlay (src/overlay.ts) or a layer like the video and embed ones (src/video, src/embed).\nexport type ElementKind = 'image' | 'video' | 'embed';\n\nexport type ElementId = string;\n\n// The virtual screen a live iframe is laid out at, then scaled onto the card: '720p' lays the page out with\n// its short side at 720 CSS px (a 16:9 card is a 1280 x 720 page), '1080p' at 1080 (1920 x 1080), a number\n// is that short side in CSS px, and 'native' lays it out at the card's world size (a 400 px card is a\n// 400 px wide page: mobile layouts, big text).\nexport type EmbedResolution = '720p' | '1080p' | 'native' | number;\n\n// What an `embed` card shows live: a page (`url`) or a snippet of HTML (`html`), in a sandboxed iframe.\n// Exactly one of the two. The sandbox profile is derived from this and the provider at render time and is\n// never stored (src/embed/sandbox.ts).\nexport type EmbedSource = (\n | { url: string; html?: undefined }\n | { html: string; url?: undefined }\n) & {\n // Shown on the generated tile and in the iframe's `title`.\n title?: string;\n // Overrides the board's `embeds.resolution` for this card.\n resolution?: EmbedResolution;\n};\n\n// Where a card's pixels come from.\nexport interface MediaSource {\n // The picture: an image URL, or the poster of a video or an embed. Must be fetchable with CORS (the\n // decode worker reads it with `fetch`, then uploads it to WebGL). Required for `image` and `video`\n // cards. An `embed` card may leave it out: the embed layer fills it with a poster it resolves (a\n // provider thumbnail, the `resolve` option's, or a generated tile).\n src?: string;\n // The video file, for a `video` card. Played in a DOM <video> laid over the card (src/video/*).\n video?: string;\n // The content of an `embed` card. Makes the card an `embed` unless `kind` says otherwise.\n embed?: EmbedSource;\n // Optional smaller / larger renditions of `src`. The texture pipeline picks the level that matches\n // the card's size on screen: `small` fills an atlas cell (~160 px long side), `medium` is the sharp\n // texture of a card at normal zoom (~480 px), `large` is for close zoom (~1600 px). A missing\n // rendition falls back to `src`, which the decode worker then downsamples itself.\n sizes?: { small?: string; medium?: string; large?: string };\n // height / width of the picture. Optional: with no `h` on the element it sizes the card; a card\n // whose size is known never needs it.\n aspect?: number;\n // ThumbHash (https://evanw.github.io/thumbhash/) of the picture, <= 25 bytes, as bytes or base64.\n // The blurred first paint of a card; without it the card shows a flat `color` until its picture lands.\n thumbhash?: Uint8Array | string;\n // Flat placeholder colour, \"#rrggbb\".\n color?: string;\n}\n\n// A card as the store holds it.\nexport interface Element {\n id: ElementId;\n kind: ElementKind;\n x: number;\n y: number;\n w: number;\n h: number;\n rot: number;\n locked: boolean;\n media: MediaSource;\n // Corner radius, world px.\n radius: number;\n // Keep w:h when resized (default true for image and video).\n aspectLocked: boolean;\n // Free for the host: carried through unchanged.\n data?: unknown;\n}\n\n// What `add` takes. Everything but `media` is optional: a card with no position is placed by\n// `autoSpot` next to what is on screen (an `x` or `y` it has is kept); a missing size is derived from `w`\n// and the media's aspect (an embed's default width is DEFAULTS.embedWidth).\nexport interface ElementInit {\n id?: ElementId;\n kind?: ElementKind;\n x?: number;\n y?: number;\n w?: number;\n h?: number;\n rot?: number;\n locked?: boolean;\n media: MediaSource;\n radius?: number;\n aspectLocked?: boolean;\n data?: unknown;\n}\n\n// What `update` takes.\nexport type ElementPatch = Partial<Omit<Element, 'id' | 'kind'>> & { kind?: ElementKind };\n\nexport const DEFAULTS = {\n cardWidth: 248,\n cardAspect: 1.25,\n videoAspect: 9 / 16,\n embedAspect: 9 / 16,\n embedWidth: 400,\n cardRadius: 8,\n minCardW: 40,\n maxCardW: 1600,\n} as const;\n\n// Zoom range of the camera.\nexport const MIN_SCALE = 0.05;\nexport const MAX_SCALE = 4;\n","// Pure camera math. No DOM, no Pixi.\n\n// World -> screen camera: a world point (wx, wy) shows at (tx + wx*scale, ty + wy*scale).\nexport interface Camera {\n tx: number;\n ty: number;\n scale: number;\n}\n\n// A world rectangle by its corners.\nexport interface Rect {\n x0: number;\n y0: number;\n x1: number;\n y1: number;\n}\n\nexport const clamp = (v: number, lo: number, hi: number): number => Math.max(lo, Math.min(hi, v));\n\n// Re-scales the camera to `scale` while the world point under the screen point (ax, ay) stays exactly\n// where it is (cursor-anchored zoom).\nexport function zoomAt(cam: Camera, ax: number, ay: number, scale: number): Camera {\n const k = scale / cam.scale;\n return { tx: ax - (ax - cam.tx) * k, ty: ay - (ay - cam.ty) * k, scale };\n}\n\n// Wheel -> multiplicative zoom factor. Pixel-normalizes line/page deltas and caps one event's\n// contribution, so a mouse ctrl+wheel notch (deltaY +-100, or +-3 lines) is one comfortable step instead\n// of slamming the scale into its clamp, while a trackpad pinch (a stream of small deltas) stays\n// proportional.\nexport const ZOOM_PER_PX = 0.012;\nexport const MAX_ZOOM_DELTA_PX = 20;\nexport function wheelZoomFactor(deltaY: number, deltaMode = 0): number {\n const px = deltaMode === 1 ? deltaY * 16 : deltaMode === 2 ? deltaY * 800 : deltaY;\n return Math.exp(-clamp(px, -MAX_ZOOM_DELTA_PX, MAX_ZOOM_DELTA_PX) * ZOOM_PER_PX);\n}\n\n// The world rectangle a viewport of w x h screen px shows through `cam`.\nexport function visibleWorldRect(cam: Camera, w: number, h: number): Rect {\n return {\n x0: -cam.tx / cam.scale,\n y0: -cam.ty / cam.scale,\n x1: (w - cam.tx) / cam.scale,\n y1: (h - cam.ty) / cam.scale,\n };\n}\n","// Board camera: pan, eased cursor-anchored zoom, drag inertia and animated fly-to. No DOM, no Pixi,\n// no React: the stage feeds it input and calls `step(dt)` from its on-demand rAF loop.\n//\n// Friction, zoom ease and wheel normalisation are all integrated against the real frame `dt`, so the\n// feel is identical at 60 and 120 Hz. The zoom range is 5 %..400 %.\nimport {\n clamp,\n visibleWorldRect,\n wheelZoomFactor,\n zoomAt,\n type Camera,\n type Rect,\n} from '../math';\nimport { MAX_SCALE, MIN_SCALE } from '../types';\n\nexport { MAX_SCALE, MIN_SCALE };\n// Fraction of the drag-release velocity KEPT per 1/60 s frame, and the speed under which it stops.\nconst FRICTION = 0.935;\nconst STOP_SPEED = 0.012; // px/ms\n// Exponential zoom smoothing rate (1 - exp(-rate * dt)).\nconst ZOOM_EASE = 18;\n\nexport interface WheelInput {\n x: number;\n y: number;\n deltaX: number;\n deltaY: number;\n deltaMode: number;\n // ctrl / meta: a trackpad pinch (Chromium reports it as ctrl+wheel) or a mouse ctrl+wheel.\n zoom: boolean;\n}\n\ninterface FlyTo {\n from: Camera;\n to: Camera;\n t: number;\n duration: number;\n}\n\nexport class CameraController {\n readonly cam: Camera = { tx: 0, ty: 0, scale: 1 };\n // Bumped on every change of the camera, so consumers can skip untouched frames.\n version = 0;\n width = 0;\n height = 0;\n\n private targetScale = 1;\n private anchor = { x: 0, y: 0 };\n private vel = { vx: 0, vy: 0 };\n private dragging = false;\n private samples: { t: number; x: number; y: number }[] = [];\n private fly: FlyTo | null = null;\n private lastDrag: { x: number; y: number } | null = null;\n // The host has no size yet (hidden tab, pane not laid out): the viewport is a 1 px placeholder.\n private empty = false;\n // A fit asked for while `empty`; `version` is the camera version it was asked at.\n private pendingFit: { target: () => Rect | null; pad: number; version: number } | null = null;\n\n constructor(\n private readonly wake: () => void,\n private readonly bounds: { min: number; max: number } = { min: MIN_SCALE, max: MAX_SCALE },\n ) {}\n\n // `empty`: the host is 0 in either axis; w and h are then only placeholders. A fit requested meanwhile is\n // applied (without animation) by the first call with a real size, unless the camera moved since.\n setViewport(w: number, h: number, empty = false): void {\n const untouched = this.pendingFit !== null && this.pendingFit.version === this.version;\n this.width = w;\n this.height = h;\n this.empty = empty;\n this.version++;\n const p = this.pendingFit;\n if (!p) return;\n if (empty) {\n // Only the placeholder size changed: still the same camera.\n if (untouched) p.version = this.version;\n else this.pendingFit = null;\n return;\n }\n this.pendingFit = null;\n if (untouched) {\n const r = p.target();\n if (r) this.jumpTo(this.fitCamera(r, p.pad));\n }\n }\n\n // The host has no size (yet): see setViewport.\n get isEmpty(): boolean {\n return this.empty;\n }\n\n get scale(): number {\n return this.cam.scale;\n }\n\n // The zoom range this camera clamps to.\n get minScale(): number {\n return this.bounds.min;\n }\n\n get maxScale(): number {\n return this.bounds.max;\n }\n\n // True while an animation owns the camera (inertia, an eased zoom, a fly-to, a live drag).\n get busy(): boolean {\n return (\n this.dragging ||\n this.fly !== null ||\n Math.abs(this.vel.vx) > STOP_SPEED ||\n Math.abs(this.vel.vy) > STOP_SPEED ||\n this.cam.scale !== this.targetScale\n );\n }\n\n visibleRect(): Rect {\n return visibleWorldRect(this.cam, this.width, this.height);\n }\n\n // ── Input ──────────────────────────────────────────────────────────────────\n wheel(e: WheelInput): void {\n this.fly = null;\n if (e.zoom) {\n this.targetScale = clamp(\n this.targetScale * wheelZoomFactor(e.deltaY, e.deltaMode),\n this.bounds.min,\n this.bounds.max,\n );\n this.anchor = { x: e.x, y: e.y };\n } else {\n // Plain wheel / two-finger swipe = pan; macOS already supplies the momentum.\n const k = e.deltaMode === 1 ? 16 : e.deltaMode === 2 ? 800 : 1;\n this.cam.tx -= e.deltaX * k;\n this.cam.ty -= e.deltaY * k;\n this.version++;\n }\n this.wake();\n }\n\n dragStart(x: number, y: number, t: number): void {\n this.fly = null;\n this.dragging = true;\n this.vel.vx = 0;\n this.vel.vy = 0;\n this.lastDrag = { x, y };\n this.samples = [{ t, x, y }];\n this.wake();\n }\n\n dragMove(x: number, y: number, t: number): void {\n if (!this.dragging || !this.lastDrag) return;\n this.cam.tx += x - this.lastDrag.x;\n this.cam.ty += y - this.lastDrag.y;\n this.lastDrag = { x, y };\n this.version++;\n this.samples.push({ t, x, y });\n // Velocity comes from the trailing ~80 ms only, so a flick hands over a believable speed.\n while (this.samples.length > 2 && t - this.samples[0].t > 80) this.samples.shift();\n this.wake();\n }\n\n dragEnd(t: number): void {\n if (!this.dragging) return;\n this.dragging = false;\n const s = this.samples;\n const first = s[0];\n const last = s[s.length - 1];\n if (first && last && t - last.t < 60 && last.t > first.t) {\n this.vel.vx = (last.x - first.x) / (last.t - first.t);\n this.vel.vy = (last.y - first.y) / (last.t - first.t);\n }\n this.samples = [];\n this.lastDrag = null;\n this.wake();\n }\n\n // Immediate moves (scripted drivers: no easing, no inertia).\n panBy(dx: number, dy: number): void {\n this.cam.tx += dx;\n this.cam.ty += dy;\n this.version++;\n }\n\n // Multiplies the scale by `k` (clamped) keeping the world point under (ax, ay) still.\n zoomStep(k: number, ax: number, ay: number): void {\n const next = clamp(this.cam.scale * k, this.bounds.min, this.bounds.max);\n const z = zoomAt(this.cam, ax, ay, next);\n this.cam.tx = z.tx;\n this.cam.ty = z.ty;\n this.cam.scale = this.targetScale = z.scale;\n this.version++;\n }\n\n // Two-pointer pinch, incremental: `ratio` is the distance ratio since the last call and (dx, dy)\n // the midpoint's movement.\n pinch(ax: number, ay: number, ratio: number, dx: number, dy: number): void {\n this.fly = null;\n const next = clamp(this.cam.scale * ratio, this.bounds.min, this.bounds.max);\n const z = zoomAt(this.cam, ax, ay, next);\n this.cam.tx = z.tx + dx;\n this.cam.ty = z.ty + dy;\n this.cam.scale = z.scale;\n this.targetScale = z.scale;\n this.version++;\n this.wake();\n }\n\n // ── Programmatic moves ─────────────────────────────────────────────────────\n // Fits `world` in the viewport with `pad` screen px around it.\n fitCamera(world: Rect, pad = 48): Camera {\n const w = Math.max(1, world.x1 - world.x0);\n const h = Math.max(1, world.y1 - world.y0);\n const scale = clamp(\n Math.min((this.width - pad * 2) / w, (this.height - pad * 2) / h),\n this.bounds.min,\n this.bounds.max,\n );\n return {\n scale,\n tx: (this.width - w * scale) / 2 - world.x0 * scale,\n ty: (this.height - h * scale) / 2 - world.y0 * scale,\n };\n }\n\n // Fits `target` in the viewport. With an empty viewport (see setViewport) it would compute the minimum\n // zoom and leave the board off-centre: the request is kept and applied at the first real size instead.\n // `target` is read when the fit is applied, so cards added meanwhile count. A target of `null` (nothing\n // to fit: an empty board, ids that match no card) leaves the camera where it is.\n requestFit(target: () => Rect | null, pad = 48, animate = true, duration?: number): void {\n if (this.empty) {\n this.pendingFit = { target, pad, version: this.version };\n return;\n }\n const r = target();\n if (!r) return;\n this.pendingFit = null;\n const c = this.fitCamera(r, pad);\n if (animate) this.flyTo(c, duration);\n else this.jumpTo(c);\n }\n\n // `c` with its scale held to the zoom range. The tx / ty of `c` were made for the scale that was asked\n // for, so a clamped scale zooms about the viewport centre: the world point that sat there under `c`\n // stays there (without this the camera would land off-centre by the whole clamped factor).\n private clampCamera(c: Camera): Camera {\n const scale = clamp(c.scale, this.bounds.min, this.bounds.max);\n if (scale === c.scale || !(c.scale > 0 && Number.isFinite(c.scale))) return { ...c, scale };\n return zoomAt(c, this.width / 2, this.height / 2, scale);\n }\n\n jumpTo(c: Camera): void {\n this.pendingFit = null;\n this.fly = null;\n this.vel.vx = this.vel.vy = 0;\n const k = this.clampCamera(c);\n this.cam.tx = k.tx;\n this.cam.ty = k.ty;\n this.cam.scale = this.targetScale = k.scale;\n this.version++;\n this.wake();\n }\n\n // Animated move (log-space on the scale so a long zoom feels even).\n flyTo(c: Camera, duration = 380): void {\n this.pendingFit = null;\n this.vel.vx = this.vel.vy = 0;\n this.targetScale = this.cam.scale;\n this.fly = {\n from: { ...this.cam },\n to: this.clampCamera(c),\n t: 0,\n duration,\n };\n this.wake();\n }\n\n // 100 % about the viewport centre.\n zoomToActual(duration = 280): void {\n const z = zoomAt(this.cam, this.width / 2, this.height / 2, 1);\n this.flyTo(z, duration);\n }\n\n // ── Per frame ──────────────────────────────────────────────────────────────\n // Advances inertia, the eased zoom and any fly-to by `dt` ms. Returns true while more frames are\n // needed.\n step(dt: number): boolean {\n const cam = this.cam;\n let busy = false;\n\n if (this.fly) {\n const f = this.fly;\n f.t = Math.min(1, f.t + dt / f.duration);\n const e = 1 - Math.pow(1 - f.t, 3); // ease-out cubic\n const s0 = Math.log(f.from.scale);\n const s1 = Math.log(f.to.scale);\n cam.scale = Math.exp(s0 + (s1 - s0) * e);\n // Interpolate the world point at the viewport centre, so pan and zoom stay coupled.\n const cx = this.width / 2;\n const cy = this.height / 2;\n const w0x = (cx - f.from.tx) / f.from.scale;\n const w0y = (cy - f.from.ty) / f.from.scale;\n const w1x = (cx - f.to.tx) / f.to.scale;\n const w1y = (cy - f.to.ty) / f.to.scale;\n const wx = w0x + (w1x - w0x) * e;\n const wy = w0y + (w1y - w0y) * e;\n cam.tx = cx - wx * cam.scale;\n cam.ty = cy - wy * cam.scale;\n this.targetScale = cam.scale;\n this.version++;\n if (f.t >= 1) this.fly = null;\n else busy = true;\n return busy;\n }\n\n const vel = this.vel;\n if (!this.dragging && (Math.abs(vel.vx) > STOP_SPEED || Math.abs(vel.vy) > STOP_SPEED)) {\n cam.tx += vel.vx * dt;\n cam.ty += vel.vy * dt;\n const decay = Math.pow(FRICTION, dt / (1000 / 60));\n vel.vx *= decay;\n vel.vy *= decay;\n this.version++;\n busy = true;\n } else if (!this.dragging) {\n vel.vx = 0;\n vel.vy = 0;\n }\n\n const target = this.targetScale;\n if (Math.abs(cam.scale - target) > 0.001 * target) {\n const a = 1 - Math.exp(-ZOOM_EASE * (dt / 1000));\n const next = zoomAt(cam, this.anchor.x, this.anchor.y, cam.scale + (target - cam.scale) * a);\n cam.tx = next.tx;\n cam.ty = next.ty;\n cam.scale = next.scale;\n this.version++;\n busy = true;\n } else if (cam.scale !== target) {\n // Final snap of the last sliver, still pinned to the anchor (a sub-pixel move).\n const next = zoomAt(cam, this.anchor.x, this.anchor.y, target);\n cam.tx = next.tx;\n cam.ty = next.ty;\n cam.scale = target;\n this.version++;\n busy = true;\n }\n return busy || this.dragging;\n }\n}\n","// Level-of-detail choice for a media card.\n//\n// L0 ThumbHash, decoded to <= 32 px (a shared 32 px atlas): first paint and tiny cards\n// L1 ~160 px rendition packed into 128 px atlas cells: cards under ~128 device px\n// L2 ~480 px rendition, an own texture at bucket 256 / 512: up to ~480 device px\n// L3 ~1600 px rendition, an own texture at bucket 1024 / 1600: close zoom, at most MAX_L3 cards at a time\n//\n// The level follows the card's long side in DEVICE pixels. A hysteresis band keeps a view parked\n// on a boundary from flapping (and re-fetching): a card goes up past `T * UP` and down below\n// `T * DOWN`; inside the band it keeps its previous level. Originals never reach the canvas.\nexport type Level = 0 | 1 | 2 | 3;\n\nexport const LOD_L0_MAX_DEVICE_PX = 24;\nexport const LOD_L1_MAX_DEVICE_PX = 128;\nexport const LOD_L2_MAX_DEVICE_PX = 480;\nexport const LOD_THRESHOLDS: readonly [number, number, number] = [\n LOD_L0_MAX_DEVICE_PX,\n LOD_L1_MAX_DEVICE_PX,\n LOD_L2_MAX_DEVICE_PX,\n];\nexport const LOD_UP = 1.25;\nexport const LOD_DOWN = 0.8;\nexport const MAX_LEVEL: Level = 3;\n// Large (1600 px) textures are ~10 MB each: only the cards nearest to the view centre get one.\nexport const MAX_L3 = 12;\n\nexport function pickLevel(\n deviceLongSide: number,\n prev: Level | null = null,\n thresholds: readonly number[] = LOD_THRESHOLDS,\n): Level {\n const start =\n deviceLongSide < thresholds[0]\n ? 0\n : deviceLongSide < thresholds[1]\n ? 1\n : deviceLongSide < thresholds[2]\n ? 2\n : 3;\n let level: number = prev ?? start;\n // Up: past the upper edge of the band above the current level.\n while (level < MAX_LEVEL && deviceLongSide > thresholds[level] * LOD_UP) level++;\n // Down: below the lower edge of the band under the current level.\n while (level > 0 && deviceLongSide < thresholds[level - 1] * LOD_DOWN) level--;\n return level as Level;\n}\n\n// Own textures (L2, L3) are uploaded at the smallest bucket (long side) that covers the on-screen size.\nexport const L2_BUCKETS = [256, 512] as const;\nexport const L3_BUCKETS = [1024, 1600] as const;\nexport function l2Bucket(deviceLongSide: number): number {\n return deviceLongSide <= L2_BUCKETS[0] / 0.9 ? L2_BUCKETS[0] : L2_BUCKETS[1];\n}\nexport function l3Bucket(deviceLongSide: number): number {\n return deviceLongSide <= L3_BUCKETS[0] / 0.9 ? L3_BUCKETS[0] : L3_BUCKETS[1];\n}\nexport function ownBucket(level: 2 | 3, deviceLongSide: number): number {\n return level === 2 ? l2Bucket(deviceLongSide) : l3Bucket(deviceLongSide);\n}\n\n// Fits (w, h) inside a `long`-sided box keeping the aspect (never upscales past `long`).\nexport function fitLong(w: number, h: number, long: number): { w: number; h: number } {\n const k = long / Math.max(w, h);\n return { w: Math.max(1, Math.round(w * k)), h: Math.max(1, Math.round(h * k)) };\n}\n\n// A card's caption (store/caption.ts) is drawn only where it can be read: from CAPTION_MIN_DEVICE_PX of font\n// size up, in device px like every threshold above. Under it the caption is simply not drawn (the card's box,\n// and so the gap under its picture, stays): at that zoom a view holds hundreds of cards and a grey bar per card\n// would cost more than it says. The same hysteresis band keeps a view parked on the edge from flapping.\nexport const CAPTION_MIN_DEVICE_PX = 7;\nexport function captionVisible(fontDevicePx: number, prev: boolean): boolean {\n return fontDevicePx >= (prev ? CAPTION_MIN_DEVICE_PX * LOD_DOWN : CAPTION_MIN_DEVICE_PX);\n}\n","// The outline of an element: the rounded rect the interaction overlay strokes for the hover and the\n// selection. Pure, so the shape is tested without Pixi.\n//\n// An outline follows the corner radius its element is painted with instead of the square box, and\n// `outlinePoints` grows it by a screen-px offset the way a CSS outline-offset does: the outer radius is\n// `r + offset`.\nimport type { Camera } from '../math';\nimport type { Element } from '../types';\nimport { DEG, type WorldRect } from './geometry';\n\n// A world rect plus the corner radius to draw it with.\nexport interface OutlineRect extends WorldRect {\n // World px; 0 / absent = square corners.\n radius?: number;\n}\n\nconst clamp = (v: number, lo: number, hi: number): number => Math.min(hi, Math.max(lo, v));\n\n// The outline of `el` at `rect` (its world rect, or the live preview of it while it is dragged).\nexport function outlineOf(el: Pick<Element, 'radius'>, rect: WorldRect): OutlineRect {\n return { ...rect, radius: clamp(el.radius, 0, Math.min(rect.w, rect.h) / 2) };\n}\n\n// Segments per quarter arc: enough that the polygon is smooth at the screen radius, few for a small one.\nfunction quarterSteps(rs: number): number {\n return clamp(Math.ceil(rs / 2), 3, 14);\n}\n\n// The outline as a closed screen-space polygon [x0, y0, x1, y1, ...], clockwise from the top-left, grown\n// by `offset` screen px on every side (negative shrinks). The radius scales with the camera and gains the\n// offset, so the outline stays concentric with the element's own corners.\nexport function outlinePoints(\n r: OutlineRect,\n cam: Camera,\n offset = 0,\n out: number[] = [],\n): number[] {\n out.length = 0;\n const hw = (r.w * cam.scale) / 2 + offset;\n const hh = (r.h * cam.scale) / 2 + offset;\n if (hw <= 0 || hh <= 0) return out;\n const cx = cam.tx + (r.x + r.w / 2) * cam.scale;\n const cy = cam.ty + (r.y + r.h / 2) * cam.scale;\n const a = r.rot * DEG;\n const c = Math.cos(a);\n const s = Math.sin(a);\n const push = (lx: number, ly: number): void => {\n out.push(cx + lx * c - ly * s, cy + lx * s + ly * c);\n };\n\n const rs = clamp((r.radius ?? 0) * cam.scale + offset, 0, Math.min(hw, hh));\n if (rs < 0.5) {\n push(-hw, -hh);\n push(hw, -hh);\n push(hw, hh);\n push(-hw, hh);\n return out;\n }\n const steps = quarterSteps(rs);\n // Corner centres and the angle each quarter arc starts at: top-right, bottom-right, bottom-left, top-left.\n const arcs: ReadonlyArray<readonly [number, number, number]> = [\n [hw - rs, -(hh - rs), -Math.PI / 2],\n [hw - rs, hh - rs, 0],\n [-(hw - rs), hh - rs, Math.PI / 2],\n [-(hw - rs), -(hh - rs), Math.PI],\n ];\n for (const [ax, ay, a0] of arcs) {\n for (let i = 0; i <= steps; i++) {\n const t = a0 + (i / steps) * (Math.PI / 2);\n push(ax + rs * Math.cos(t), ay + rs * Math.sin(t));\n }\n }\n return out;\n}\n","// Smart guides, drawn in SCREEN space by the overlay (render/overlay.ts) while a box is moved or resized: alignment lines with a \"×\" where they meet each aligned box, spacing and size measures\n// with end caps and a small label pill. The model comes from interact/snapping.ts in world units.\n//\n// The look is a hairline system: every line is exactly one DEVICE pixel wide and sits on the device\n// pixel grid (filled rects, not strokes), so it is equally crisp at any zoom and pixel ratio. One hue of\n// its own (theme.guide), apart from the selection's accent. Guides fade in and out over GUIDE_FADE_MS,\n// keyed by what they show (an alignment line by its axis, kind and position; a measure by its\n// segment), so a guide that stays while the pointer moves within the snap threshold never blinks, and\n// one that goes leaves gently. The layer only redraws when its guides, the camera or a fade changed.\n//\nimport { Container, Graphics, Text, TextStyle } from 'pixi.js';\nimport type { Camera } from '../math';\nimport type { Guide, LineGuide } from '../interact/snapping';\nimport { guideColor, type Theme } from './theme';\n\nconst UI_FONT = \"system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif\";\n\nexport const GUIDE_FADE_MS = 80;\n// Screen px (CSS): half the size of a \"×\" mark and half the length of a measure's end cap.\nconst MARK_ARM = 3;\nconst CAP_HALF = 3.5;\n// The label pill: height, horizontal padding, corner radius, and its distance from a segment too short\n// to hold it (the pill then sits beside the segment).\nconst PILL_H = 16;\nconst PILL_PAD = 5;\nconst PILL_RADIUS = 4;\nconst PILL_OFFSET = 4;\nconst LABEL_SIZE = 11;\n// A width / height match shows this instead of a number.\nconst MATCH_LABEL = '=';\n// The corners of an arm of a mark, as signs of (u, v) (see GuideLayer.line).\nconst MARK_CORNERS = [\n [-1, -1],\n [1, -1],\n [1, 1],\n [-1, 1],\n] as const;\n\ninterface Entry {\n key: string;\n guide: Guide;\n alpha: number;\n // 1 while the guide is set, 0 once it is gone (it fades out, then is dropped).\n target: 0 | 1;\n}\n\n// One pooled label. `label` and `w` cache what the Text shows and its pill width (screen px).\ninterface PillLabel {\n text: Text;\n label: string;\n w: number;\n}\n\nconst isMeasure = (g: Guide): boolean => g.kind === 'gap' || g.kind === 'width';\n\n// World units are rounded to 1/100 in the keys: the snapper's own epsilon.\nconst k = (v: number): number => Math.round(v * 100);\n\n// What a guide IS, independently of how far it runs: an alignment line by its axis, kind and position\n// (it grows and shrinks as the box slides along it); a measure by its segment and kind (its position\n// across the segment moves as the box slides across it).\nexport function guideKey(g: Guide): string {\n if (isMeasure(g)) return `${g.kind}|${g.axis}|${k(g.from)}|${k(g.to)}`;\n return `${g.kind}|${g.axis}|${k(g.at)}`;\n}\n\nfunction sameGeometry(a: Guide, b: Guide): boolean {\n if (a.at !== b.at || a.from !== b.from || a.to !== b.to) return false;\n if (isMeasure(a)) return (a as { label: number }).label === (b as { label: number }).label;\n const ma = (a as LineGuide).marks;\n const mb = (b as LineGuide).marks;\n if (ma === mb) return true;\n if (!ma || !mb || ma.length !== mb.length) return false;\n for (let i = 0; i < ma.length; i++) if (ma[i] !== mb[i]) return false;\n return true;\n}\n\nexport class GuideLayer {\n readonly container = new Container();\n // Lines, caps and marks; the pills go on top of them, then the labels.\n private readonly lines = new Graphics();\n private readonly pillBg = new Graphics();\n private readonly pillStyle: TextStyle;\n private readonly pills: PillLabel[] = [];\n private pillsUsed = 0;\n private entries: Entry[] = [];\n private color: number;\n private dirty = false;\n private lastNow = NaN;\n private readonly lastCam = { tx: NaN, ty: NaN, scale: NaN };\n // Pill rects placed this frame (screen px: x, y, w, h), to keep two labels from overlapping.\n private readonly placed: number[] = [];\n\n // The renderer's pixel ratio (a hairline is one device pixel wide).\n private dpr: number;\n\n constructor(theme: Theme, dpr = 1) {\n this.dpr = dpr;\n this.container.eventMode = 'none';\n this.lines.eventMode = 'none';\n this.pillBg.eventMode = 'none';\n this.container.addChild(this.lines, this.pillBg);\n this.color = guideColor(theme);\n this.pillStyle = new TextStyle({\n fontFamily: UI_FONT,\n fontSize: LABEL_SIZE,\n fontWeight: '600',\n fill: theme.onGuide ?? 0xffffff,\n });\n }\n\n // The pixel ratio changed (browser zoom, another screen): redraw on the new device pixel grid.\n setDpr(dpr: number): void {\n if (dpr === this.dpr) return;\n this.dpr = dpr;\n this.dirty = true;\n }\n\n setTheme(theme: Theme): void {\n this.color = guideColor(theme);\n this.pillStyle.fill = theme.onGuide ?? 0xffffff;\n this.dirty = true;\n }\n\n // The guides to show now. Returns true when that changes anything on screen (the caller asks for a\n // frame); the same guides again (a pointer move that stays snapped) change nothing.\n set(guides: readonly Guide[]): boolean {\n let changed = false;\n const seen = new Set<string>();\n const next: Entry[] = [];\n const prev = new Map<string, Entry>();\n for (const e of this.entries) prev.set(e.key, e);\n for (const g of guides) {\n const key = guideKey(g);\n // Two guides that show the same thing (the snapper merges most): the first one wins.\n if (seen.has(key)) continue;\n seen.add(key);\n const e = prev.get(key);\n if (e) {\n if (e.target !== 1 || !sameGeometry(e.guide, g)) changed = true;\n e.guide = g;\n e.target = 1;\n next.push(e);\n prev.delete(key);\n } else {\n next.push({ key, guide: g, alpha: 0, target: 1 });\n changed = true;\n }\n }\n // The ones no longer set fade out from where they were.\n for (const e of prev.values()) {\n if (e.target !== 0) changed = true;\n e.target = 0;\n next.push(e);\n }\n this.entries = next;\n if (changed) this.dirty = true;\n return changed;\n }\n\n // The guides currently set (fading-out ones excluded).\n get current(): Guide[] {\n const out: Guide[] = [];\n for (const e of this.entries) if (e.target === 1) out.push(e.guide);\n return out;\n }\n\n // How many guides are set (fading-out ones excluded).\n get count(): number {\n let n = 0;\n for (const e of this.entries) if (e.target === 1) n++;\n return n;\n }\n\n // Anything on screen (set or still fading out).\n get active(): boolean {\n return this.entries.length > 0;\n }\n\n // A fade is running: the caller keeps the frames coming.\n get animating(): boolean {\n for (const e of this.entries) if (e.alpha !== e.target) return true;\n return false;\n }\n\n // Advances the fades to `now` and redraws when anything changed. Returns true when it redrew.\n draw(cam: Camera, now: number): boolean {\n const dt = Number.isFinite(this.lastNow) ? Math.min(50, Math.max(0, now - this.lastNow)) : 16;\n this.lastNow = now;\n let fading = false;\n const step = dt / GUIDE_FADE_MS;\n let kept = 0;\n for (const e of this.entries) {\n if (e.alpha !== e.target) {\n e.alpha = e.target === 1 ? Math.min(1, e.alpha + step) : Math.max(0, e.alpha - step);\n fading = true;\n }\n if (e.target === 0 && e.alpha === 0) continue;\n this.entries[kept++] = e;\n }\n const dropped = kept !== this.entries.length;\n this.entries.length = kept;\n const camChanged =\n cam.tx !== this.lastCam.tx || cam.ty !== this.lastCam.ty || cam.scale !== this.lastCam.scale;\n if (!this.dirty && !fading && !dropped && !(camChanged && kept > 0)) return false;\n this.lastCam.tx = cam.tx;\n this.lastCam.ty = cam.ty;\n this.lastCam.scale = cam.scale;\n this.dirty = false;\n this.redraw(cam);\n return true;\n }\n\n // ── Drawing ──────────────────────────────────────────────────────────────────────────────────────\n\n private redraw(cam: Camera): void {\n const g = this.lines;\n const bg = this.pillBg;\n g.clear();\n bg.clear();\n this.placed.length = 0;\n let used = 0;\n // The lines with their marks first, the measures last.\n for (let pass = 0; pass < 2; pass++) {\n for (const e of this.entries) {\n const gd = e.guide;\n const p = isMeasure(gd) ? 1 : 0;\n if (p !== pass || e.alpha <= 0) continue;\n if (p === 1) used = this.measure(gd, cam, e.alpha, used);\n else this.line(gd as LineGuide, cam, e.alpha);\n }\n }\n for (let i = used; i < this.pillsUsed; i++) this.pills[i].text.visible = false;\n this.pillsUsed = used;\n }\n\n // The device pixel a screen coordinate falls in, as its left / top edge in screen px.\n private cell(v: number): number {\n return Math.floor(v * this.dpr + 1e-6) / this.dpr;\n }\n\n // A screen coordinate rounded to the device pixel grid.\n private snap(v: number): number {\n return Math.round(v * this.dpr) / this.dpr;\n }\n\n // A one-device-pixel hairline along `axis` ('x': vertical at screen x = `at`, from `a` to `b` in y).\n private hairline(axis: 'x' | 'y', at: number, a: number, b: number): void {\n const g = this.lines;\n const hp = 1 / this.dpr;\n const c = this.cell(at);\n const lo = this.snap(Math.min(a, b));\n const hi = this.snap(Math.max(a, b));\n if (!(hi > lo)) {\n if (axis === 'x') g.rect(c, lo, hp, hp);\n else g.rect(lo, c, hp, hp);\n return;\n }\n if (axis === 'x') g.rect(c, lo, hp, hi - lo + hp);\n else g.rect(lo, c, hi - lo + hp, hp);\n }\n\n // An alignment line, with a \"×\" at each of its marks.\n private line(gd: LineGuide, cam: Camera, alpha: number): void {\n const g = this.lines;\n const vertical = gd.axis === 'x';\n const at = vertical ? cam.tx + gd.at * cam.scale : cam.ty + gd.at * cam.scale;\n const o = vertical ? cam.ty : cam.tx;\n const a = o + gd.from * cam.scale;\n const b = o + gd.to * cam.scale;\n this.hairline(gd.axis, at, a, b);\n g.fill({ color: this.color, alpha });\n const marks = gd.marks;\n if (!marks || marks.length === 0) return;\n // The × is not stroked: a thin diagonal stroke breaks up on a canvas without antialiasing. Each\n // arm is a thin parallelogram along a diagonal whose edges fall between pixel centres, so the GPU\n // fills a clean staircase of whole device pixels, `t` of them thick (two from a pixel ratio of 2,\n // about one CSS pixel) and symmetric about the mark: centred on the hairline's pixel for t = 1, on\n // the corner after it for t = 2. Two polygons per mark.\n const hp = 1 / this.dpr;\n const t = this.dpr >= 2 ? 2 : 1;\n const n = Math.max(2, Math.round(MARK_ARM * this.dpr) - (t - 1));\n // In device pixels: the half-width across the diagonal and the half-length along it (u = x - y,\n // v = x + y); pixel centres sit on whole u, and the bounds fall halfway between them.\n const hu = t === 1 ? 0.5 : 1.5;\n const hv = t === 1 ? 2 * n + 0.5 : 2 * n + 1.5;\n const off = t === 1 ? hp / 2 : hp;\n const across = this.cell(at) + off;\n for (const m of marks) {\n const along = this.cell(o + m * cam.scale) + off;\n const ox = vertical ? across : along;\n const oy = vertical ? along : across;\n for (const dir of [1, -1]) {\n // A fresh array: the path keeps a reference to it.\n const pts = new Array<number>(8);\n let i = 0;\n for (const [u, v] of MARK_CORNERS) {\n pts[i++] = ox + ((u * hu + v * hv) / 2) * hp;\n pts[i++] = oy + ((dir * (v * hv - u * hu)) / 2) * hp;\n }\n g.poly(pts, true);\n }\n }\n g.fill({ color: this.color, alpha });\n }\n\n // A spacing or size measure: the segment with an end cap at each end and its label in a pill.\n private measure(gd: Guide, cam: Camera, alpha: number, used: number): number {\n const g = this.lines;\n // Measures run ALONG their axis: 'x' is a horizontal segment at y = `at`.\n const horizontal = gd.axis === 'x';\n const at = horizontal ? cam.ty + gd.at * cam.scale : cam.tx + gd.at * cam.scale;\n const o = horizontal ? cam.tx : cam.ty;\n const a = o + gd.from * cam.scale;\n const b = o + gd.to * cam.scale;\n const lineAxis = horizontal ? 'y' : 'x';\n const capAxis = horizontal ? 'x' : 'y';\n this.hairline(lineAxis, at, a, b);\n // The caps sit on the segment's two end pixels.\n const hp = 1 / this.dpr;\n const ea = this.snap(Math.min(a, b));\n const eb = this.snap(Math.max(a, b));\n const mid = this.cell(at) + hp / 2;\n this.hairline(capAxis, ea, mid - CAP_HALF, mid + CAP_HALF);\n this.hairline(capAxis, eb, mid - CAP_HALF, mid + CAP_HALF);\n g.fill({ color: this.color, alpha });\n\n const label = gd.kind === 'width' ? MATCH_LABEL : String((gd as { label: number }).label);\n const pill = this.pill(used, label);\n const w = pill.w;\n const h = PILL_H;\n const len = eb - ea;\n // Centred on the segment when it is long enough to hold the pill with its caps showing, beside it\n // (below a horizontal segment, right of a vertical one) otherwise.\n let cx: number;\n let cy: number;\n if (horizontal) {\n cx = (ea + eb) / 2;\n cy = len >= w + 4 * CAP_HALF ? mid : mid + CAP_HALF + PILL_OFFSET + h / 2;\n } else {\n cy = (ea + eb) / 2;\n cx = len >= h + 4 * CAP_HALF ? mid : mid + CAP_HALF + PILL_OFFSET + w / 2;\n }\n const x = this.snap(cx - w / 2);\n const y = this.snap(cy - h / 2);\n if (this.overlapsPlaced(x, y, w, h)) {\n return used;\n }\n this.placed.push(x, y, w, h);\n this.pillBg.roundRect(x, y, w, h, PILL_RADIUS).fill({ color: this.color, alpha });\n const t = pill.text;\n t.position.set(this.snap(x + (w - t.width) / 2), this.snap(y + (h - t.height) / 2));\n t.alpha = alpha;\n t.visible = true;\n return used + 1;\n }\n\n private overlapsPlaced(x: number, y: number, w: number, h: number): boolean {\n const p = this.placed;\n for (let i = 0; i < p.length; i += 4) {\n if (x < p[i] + p[i + 2] && x + w > p[i] && y < p[i + 1] + p[i + 3] && y + h > p[i + 1]) {\n return true;\n }\n }\n return false;\n }\n\n // The pooled label at `i` showing `label`, grown on demand and never shrunk.\n private pill(i: number, label: string): PillLabel {\n let pill = this.pills[i];\n if (!pill) {\n const text = new Text({ text: '', style: this.pillStyle });\n text.eventMode = 'none';\n text.visible = false;\n this.container.addChild(text);\n pill = { text, label: '', w: 0 };\n this.pills.push(pill);\n }\n if (pill.label !== label) {\n pill.text.text = label;\n pill.label = label;\n // At least as wide as tall: a one-digit label is a rounded square, not a sliver.\n pill.w = Math.max(PILL_H, Math.ceil(pill.text.width + 2 * PILL_PAD));\n }\n return pill;\n }\n}\n","// The interaction overlay: everything that must stay crisp and constant-size at every zoom, drawn in\n// SCREEN space on top of the world: selection outlines and handles, the hover outline, the marquee and\n// the snapping guides.\n//\n// State is set by the interaction layer in WORLD coordinates and the overlay converts with the camera\n// at draw time, so a pan with a live selection only costs a redraw of a few lines. One Graphics,\n// cleared and redrawn when the state or the camera changed (`draw` returns whether it did). The smart\n// guides are their own layer on top (render/guides.ts): hairlines, marks and label pills that fade in\n// and out on their own clock.\n//\n// The overlay is drawn by the stage tick and the stage parks its loop when nothing moves, so every change\n// of state wakes it (`wake`): a caller that sets the selection, the hover or a guide never has to remember\n// to ask for a frame.\nimport { Container, Graphics } from 'pixi.js';\nimport type { Camera } from '../math';\nimport type { Box } from '../interact/geometry';\nimport type { Handle } from '../interact/handles';\nimport { outlinePoints, type OutlineRect } from '../interact/outline';\nimport type { Guide } from '../interact/snapping';\nimport { GuideLayer } from './guides';\nimport type { Theme } from './theme';\n\nexport const HANDLE_SIZE = 8;\nconst OUTLINE = 1.5;\n\nexport interface SelectionVisual {\n // The rect the handles sit on (rotated for a single element): the 1.5 px outline. A single element's\n // carries its corner radius, a multi-selection's box is square.\n frame: OutlineRect;\n // Per-element thin outlines for a multi-selection (empty for a single element), each with its radius.\n members: OutlineRect[];\n handles: readonly Handle[];\n // The handles are hidden while a gesture runs (a resize in progress shows the frame only).\n showHandles: boolean;\n}\n\nconst noop = (): void => {};\n\nexport class OverlayLayer {\n readonly container = new Container();\n private readonly g = new Graphics();\n private theme: Theme;\n private selection: SelectionVisual | null = null;\n private hover: OutlineRect | null = null;\n private marquee: Box | null = null;\n private dirty = true;\n private lastCam = { tx: NaN, ty: NaN, scale: NaN };\n private readonly guides: GuideLayer;\n // Scratch for the outline polygons.\n private readonly pts: number[] = [];\n\n constructor(\n theme: Theme,\n // Asks the stage for a frame: called whenever the overlay has something new to draw.\n private readonly wake: () => void = noop,\n // The renderer's pixel ratio: the guides' hairlines are one device pixel.\n dpr = 1,\n ) {\n this.theme = theme;\n this.container.eventMode = 'none';\n this.g.eventMode = 'none';\n this.guides = new GuideLayer(theme, dpr);\n this.container.addChild(this.g, this.guides.container);\n }\n\n setTheme(theme: Theme): void {\n this.theme = theme;\n this.guides.setTheme(theme);\n this.invalidate();\n }\n\n // The renderer's pixel ratio changed.\n setDpr(dpr: number): void {\n this.guides.setDpr(dpr);\n this.invalidate();\n }\n\n setSelection(s: SelectionVisual | null): void {\n this.selection = s;\n this.invalidate();\n }\n\n setHover(r: OutlineRect | null): void {\n if (r === null && this.hover === null) return;\n this.hover = r;\n this.invalidate();\n }\n\n // World-space box.\n setMarquee(b: Box | null): void {\n if (b === null && this.marquee === null) return;\n this.marquee = b;\n this.invalidate();\n }\n\n // Smart guides (world units). The same guides again cost nothing; a change asks for a frame.\n setGuides(g: readonly Guide[]): void {\n if (this.guides.set(g)) this.wake();\n }\n\n // The guides currently set (not counting the ones fading out): for tests and the demo.\n get guideCount(): number {\n return this.guides.count;\n }\n\n get currentGuides(): Guide[] {\n return this.guides.current;\n }\n\n get active(): boolean {\n return (\n this.selection !== null || this.hover !== null || this.marquee !== null || this.guides.active\n );\n }\n\n // Marks the next draw as needed and wakes the stage loop for it.\n invalidate(): void {\n this.dirty = true;\n this.wake();\n }\n\n // Redraws when something changed. Returns true when anything was rebuilt.\n draw(cam: Camera): boolean {\n const guides = this.guides.draw(cam, performance.now());\n // A fade keeps the frames coming until it is done.\n if (this.guides.animating) this.wake();\n const camChanged =\n cam.tx !== this.lastCam.tx || cam.ty !== this.lastCam.ty || cam.scale !== this.lastCam.scale;\n if (!this.dirty && !(camChanged && this.active)) return guides;\n this.lastCam.tx = cam.tx;\n this.lastCam.ty = cam.ty;\n this.lastCam.scale = cam.scale;\n this.dirty = false;\n const g = this.g;\n g.clear();\n const th = this.theme;\n const sx = (x: number): number => cam.tx + x * cam.scale;\n const sy = (y: number): number => cam.ty + y * cam.scale;\n\n if (this.hover) {\n this.rectPath(g, this.hover, cam);\n g.stroke({ width: 1, color: th.accent, alpha: 0.5 });\n }\n const sel = this.selection;\n if (sel) {\n for (const m of sel.members) {\n this.rectPath(g, m, cam);\n g.stroke({ width: 1, color: th.accent, alpha: 0.85 });\n }\n this.rectPath(g, sel.frame, cam);\n g.stroke({ width: OUTLINE, color: th.accent });\n if (sel.showHandles) {\n const h = HANDLE_SIZE;\n for (const hd of sel.handles) {\n const x = sx(hd.x);\n const y = sy(hd.y);\n g.rect(x - h / 2, y - h / 2, h, h);\n // Fill then stroke the same path: a white handle with an accent outline.\n g.fill({ color: 0xffffff }).stroke({ width: OUTLINE, color: th.accent });\n }\n }\n }\n if (this.marquee) {\n const b = this.marquee;\n const x0 = sx(Math.min(b.minX, b.maxX));\n const y0 = sy(Math.min(b.minY, b.maxY));\n g.rect(x0, y0, Math.abs(b.maxX - b.minX) * cam.scale, Math.abs(b.maxY - b.minY) * cam.scale);\n g.fill({ color: th.accent, alpha: 0.08 });\n g.rect(x0, y0, Math.abs(b.maxX - b.minX) * cam.scale, Math.abs(b.maxY - b.minY) * cam.scale);\n g.stroke({ width: 1, color: th.accent, alpha: 0.9 });\n }\n return true;\n }\n\n // A closed path along the outline of a world rect, in screen space: square or rounded corners (the\n // element's own radius scaled with the zoom).\n private rectPath(g: Graphics, r: OutlineRect, cam: Camera): void {\n g.poly(outlinePoints(r, cam, 0, this.pts), true);\n }\n}\n","// Pixi's system ticker (its GC scheduler) would keep a requestAnimationFrame loop alive forever, so a board\n// parks it. It is a global shared with the host app (and with other boards): remember how it was before the\n// first board parked it and put it back when the last one lets go.\n\nexport interface TickerLike {\n autoStart: boolean;\n readonly started: boolean;\n start(): void;\n stop(): void;\n}\n\ninterface Hold {\n count: number;\n autoStart: boolean;\n started: boolean;\n}\nconst holds = new WeakMap<TickerLike, Hold>();\n\n// Parks `ticker` (no auto start, stopped). Returns the release: idempotent, and the last one restores the\n// state the ticker had before the first park.\nexport function parkTicker(ticker: TickerLike): () => void {\n let hold = holds.get(ticker);\n if (!hold) {\n hold = { count: 0, autoStart: ticker.autoStart, started: ticker.started };\n holds.set(ticker, hold);\n }\n hold.count++;\n ticker.autoStart = false;\n ticker.stop();\n let released = false;\n return () => {\n if (released) return;\n released = true;\n const h = holds.get(ticker);\n if (!h || --h.count > 0) return;\n holds.delete(ticker);\n ticker.autoStart = h.autoStart;\n if (h.started) ticker.start();\n };\n}\n","// Fixed-cell texture atlas bookkeeping (no GL here: see textures.ts for the GPU side).\n//\n// A page is a square of `pageSize` px cut into `cell + 2 * gutter` px strides, so every cell has a\n// transparent gutter that keeps bilinear taps and the first mip levels from bleeding between\n// neighbours. 2048 px pages with 128 px cells and a 4 px gutter hold 15 x 15 = 225 cells.\nexport interface AtlasSpec {\n pageSize: number;\n cell: number;\n gutter: number;\n}\n\nexport interface AtlasCell<P> {\n page: P;\n // Index inside the page.\n index: number;\n // Top-left of the cell's usable area (gutter already skipped), in page pixels.\n x: number;\n y: number;\n // The cell held another occupant before: its pixels are still in the page, so an upload that does not\n // cover the whole cell has to clear the rest.\n reused: boolean;\n}\n\ninterface PageState<P> {\n page: P;\n used: number;\n free: number[];\n // Per cell: handed out at least once (the page starts out empty, so a cell never used needs no clearing).\n touched: Uint8Array;\n}\n\nexport function cellsPerRow(spec: AtlasSpec): number {\n return Math.floor(spec.pageSize / (spec.cell + 2 * spec.gutter));\n}\nexport function cellsPerPage(spec: AtlasSpec): number {\n const n = cellsPerRow(spec);\n return n * n;\n}\n\nexport class Atlas<P> {\n readonly spec: AtlasSpec;\n private readonly perRow: number;\n private readonly stride: number;\n private pages: PageState<P>[] = [];\n\n constructor(\n spec: AtlasSpec,\n private readonly createPage: () => P,\n private readonly destroyPage: (page: P) => void,\n ) {\n this.spec = spec;\n this.stride = spec.cell + 2 * spec.gutter;\n this.perRow = cellsPerRow(spec);\n }\n\n get pageCount(): number {\n return this.pages.length;\n }\n get cellsUsed(): number {\n return this.pages.reduce((n, p) => n + p.used, 0);\n }\n get pageList(): P[] {\n return this.pages.map((p) => p.page);\n }\n\n alloc(): AtlasCell<P> {\n let st = this.pages.find((p) => p.free.length > 0);\n if (!st) {\n const n = this.perRow * this.perRow;\n // Highest index first, so `pop()` hands cells out in reading order.\n const free: number[] = [];\n for (let i = n - 1; i >= 0; i--) free.push(i);\n st = { page: this.createPage(), used: 0, free, touched: new Uint8Array(n) };\n this.pages.push(st);\n }\n const index = st.free.pop() as number;\n st.used++;\n const reused = st.touched[index] === 1;\n st.touched[index] = 1;\n const col = index % this.perRow;\n const row = Math.floor(index / this.perRow);\n return {\n page: st.page,\n index,\n x: col * this.stride + this.spec.gutter,\n y: row * this.stride + this.spec.gutter,\n reused,\n };\n }\n\n // Frees a cell; a page with no cell left is destroyed (all its cells went cold).\n release(cell: AtlasCell<P>): boolean {\n const i = this.pages.findIndex((p) => p.page === cell.page);\n if (i < 0) return false;\n const st = this.pages[i];\n st.free.push(cell.index);\n st.used--;\n if (st.used === 0) {\n this.pages.splice(i, 1);\n this.destroyPage(st.page);\n return true;\n }\n return false;\n }\n\n clear(): void {\n for (const st of this.pages) this.destroyPage(st.page);\n this.pages = [];\n }\n}\n","// Texture eviction policy (pure, so it can be unit tested without a GL context).\n//\n// Texture memory follows what is on screen, not the board size: when the total goes over `budget`,\n// unpinned entries (not on screen) are evicted least recently used first, down to `target * budget`\n// so the next upload does not immediately trigger another pass.\nexport interface LruEntry {\n id: number;\n // Last time (ms) the entry was on screen.\n last: number;\n bytes: number;\n // On screen right now: never evicted.\n pinned: boolean;\n}\n\nexport function planEviction(\n entries: readonly LruEntry[],\n total: number,\n budget: number,\n target = 0.85,\n): number[] {\n if (total <= budget) return [];\n const goal = budget * target;\n const out: number[] = [];\n const candidates = entries.filter((e) => !e.pinned).sort((a, b) => a.last - b.last);\n let t = total;\n for (const e of candidates) {\n if (t <= goal) break;\n out.push(e.id);\n t -= e.bytes;\n }\n return out;\n}\n","// Deferred teardown of GPU objects.\n//\n// Root cause of a \"use after destroy\" (`Cannot read properties of null (reading 'addressModeU')`\n// from GlBatchAdaptor.execute): when a sprite swaps to a texture whose source is ALREADY in its batch (an\n// atlas page, say), Pixi's `Batcher.checkAndUpdateTexture` just reuses that slot and does NOT rebuild the\n// batch, so the batch keeps listing the old texture even though no sprite uses it any more. Destroying\n// that texture later leaves a dead source in a live batch, and the next draw binds it.\n//\n// Two rules therefore: (1) nothing is destroyed inline: the teardown is parked here and runs only after\n// `delay` completed renders, or when the loop goes idle after at least one render; (2) whenever something\n// is parked, the stage forces Pixi to rebuild the world's instruction set (`onRetire`), so by the time\n// the teardown runs no batch can still name the old texture.\nexport class RetireQueue {\n private items: { at: number; run: () => void }[] = [];\n private renders = 0;\n\n constructor(private readonly delay = 2) {}\n\n get size(): number {\n return this.items.length;\n }\n\n push(run: () => void): void {\n this.items.push({ at: this.renders, run });\n }\n\n // Call once per completed render.\n afterRender(): void {\n this.renders++;\n this.flush(this.delay);\n }\n\n // The loop parked: anything that survived one render is safe to tear down now.\n flushIdle(): void {\n this.flush(1);\n }\n\n // Everything, right now (dispose, tests).\n flushAll(): void {\n const run = this.items;\n this.items = [];\n for (const it of run) this.safely(it.run);\n }\n\n private flush(minRenders: number): void {\n if (this.items.length === 0) return;\n const keep: { at: number; run: () => void }[] = [];\n const run: (() => void)[] = [];\n for (const it of this.items) {\n if (this.renders - it.at >= minRenders) run.push(it.run);\n else keep.push(it);\n }\n this.items = keep;\n for (const f of run) this.safely(f);\n }\n\n // One failing teardown must not strand the others (a destroyed-twice texture, a lost context).\n private safely(f: () => void): void {\n try {\n f();\n } catch (e) {\n console.error('[corkboard] teardown failed', e);\n }\n }\n}\n","// TextureManager: owns every GPU texture of the board and the decode worker pool that feeds it.\n//\n// L0 ThumbHash cells in a shared 32 px atlas (1024 px pages, no mips)\n// L1 small renditions in 128 px atlas cells (2048 px pages, 4 px gutters, 3 mip levels)\n// L2 medium renditions as an own texture at bucket 256 / 512 (full mip chain)\n// L3 large renditions as an own texture at bucket 1024 / 1600 (close zoom; the stage caps how many cards want one)\n//\n// Rounded corners (and the card hairline) are baked in the decode worker, so a card is a plain sprite.\n// Decoded bitmaps are uploaded on the main thread under a per-frame time budget; atlas cells go in with\n// `texSubImage2D` (Pixi has no partial-upload API, so this talks to GL through the renderer's own\n// texture system and keeps its bind / unpack-state caches coherent), then the touched pages get\n// their mip chain regenerated once per frame.\n//\n// Texture memory follows what is on screen, not the board size: an LRU over the own textures (and, past\n// that, cold L1 cells) keeps the total under `budgetBytes`. Teardown is always deferred (retire.ts).\nimport { ImageSource, Rectangle, Texture, TextureSource, type WebGLRenderer } from 'pixi.js';\nimport DecodeWorker from './decode.worker?worker&inline';\nimport { Atlas, cellsPerPage, type AtlasCell } from './atlas';\nimport type { DecodeRequest, WorkerIn, WorkerOut } from './decode.protocol';\nimport type { Level } from './lod';\nimport { planEviction, type LruEntry } from './lru';\nimport { RetireQueue } from './retire';\nimport type { BoardCard } from './types';\n\nconst MIP_FACTOR = 4 / 3;\nconst L0_SPEC = { pageSize: 1024, cell: 32, gutter: 2 } as const;\nconst L1_SPEC = { pageSize: 2048, cell: 128, gutter: 4 } as const;\nconst INFLIGHT_PER_WORKER = 4;\n// A failed fetch / decode is not retried for this long (a 404 for an undecodable large rendition must not loop).\nconst RETRY_AFTER_MS = 30_000;\n// Requests for cards that are not on screen (the ThumbHash prefetch) carry at least this distance and\n// always queue behind everything that is.\nexport const FAR_DIST = 1e6;\nconst L1_PAGE_BYTES = L1_SPEC.pageSize ** 2 * 4 * MIP_FACTOR;\n\nexport interface TextureManagerOptions {\n budgetBytes: number;\n workers: number;\n // URL of a module worker script to use instead of the built-in one (see StageOptions.workerUrl).\n workerUrl?: string | URL;\n // Bake corners in a software canvas in the workers (default false: measured ~2x slower to load).\n softCanvas?: boolean;\n // CSS colour of the 1 px card hairline baked into L1+ textures ('' = none).\n border?: string;\n // Completed renders to wait before destroying a retired texture (see retire.ts).\n retireDelay?: number;\n // Called whenever a teardown is parked: the stage rebuilds Pixi's batches before the next render so no\n // batch still lists the retired texture (see retire.ts for why).\n onRetire?: () => void;\n // The decoded pixels are always uploaded premultiplied (see uploadCell).\n onWake: () => void;\n}\n\ninterface Page {\n source: TextureSource;\n bytes: number;\n mips: boolean;\n dirty: boolean;\n // Belongs to an atlas replaced by reset(): already out of the byte count.\n dead?: boolean;\n}\n\ninterface CardTex {\n tex: (Texture | null)[];\n cell: (AtlasCell<Page> | null)[];\n // Own textures (levels 2 and 3): long side (texels) that is resident (0 = none), whether the source\n // ran out of pixels before the requested bucket (a 480 px rendition never fills a 512 bucket), bytes.\n ownLong: number[];\n ownCapped: boolean[];\n ownBytes: number[];\n // Last time the card was on screen, and last time it was on screen wanting an own texture.\n last: number;\n last2: number;\n // The pictures (levels 1..3) of a poster that was swapped, still drawable until the first level of the new\n // one is resident (see swapPictures). While it is set, `tex` holds no level 1..3.\n outgoing: Outgoing | null;\n}\n\ninterface Outgoing {\n tex: (Texture | null)[];\n cell: (AtlasCell<Page> | null)[];\n ownBytes: number[];\n}\n\ninterface Req {\n rid: number;\n card: BoardCard;\n level: Level;\n maxLong: number;\n dist: number;\n inflight: boolean;\n worker: number;\n cancelled: boolean;\n}\n\ninterface Decoded {\n req: Req;\n bitmap: ImageBitmap;\n w: number;\n h: number;\n fetched: number;\n decodeMs: number;\n}\n\nexport interface WantedItem {\n card: BoardCard;\n level: Level;\n // Screen distance from the viewport centre: the priority (lower first).\n dist: number;\n // Own levels only: the bucket (long side, texels).\n bucket?: number;\n}\n\n// Pixi internals the partial upload leans on (all present in 8.22; the peer range in package.json starts there).\ninterface GlTextureSystemInternals {\n getGlSource(source: TextureSource): { target: number; texture: WebGLTexture };\n initSource(source: TextureSource): void;\n _premultiplyAlpha: boolean;\n _activateLocation(location: number): void;\n _setBoundTexture(location: number, source: TextureSource | null): void;\n}\n\n// The worker is started from a blob URL, where a relative URL (`/img/a.jpg`, `a.jpg`) has no base to resolve\n// against: make it absolute against the page here.\nexport function absoluteUrl(url: string | undefined): string | undefined {\n if (url === undefined) return undefined;\n try {\n return new URL(url, typeof document !== 'undefined' ? document.baseURI : undefined).href;\n } catch {\n return url;\n }\n}\n\nconst key = (card: BoardCard, level: Level): number => card.id * 4 + level;\n\n// Zeros to blank part of an atlas cell (grown on demand, shared: it is only ever read).\nlet zeros = new Uint8Array(0);\nfunction clearBuffer(bytes: number): Uint8Array {\n if (zeros.length < bytes) zeros = new Uint8Array(bytes);\n return zeros;\n}\nconst isOwn = (level: Level): level is 2 | 3 => level >= 2;\n\nexport class TextureManager {\n private readonly texSys: GlTextureSystemInternals;\n private readonly gl: WebGL2RenderingContext;\n private readonly workers: Worker[] = [];\n private readonly workerLoad: number[] = [];\n private atlas0: Atlas<Page>;\n private atlas1: Atlas<Page>;\n private readonly cards = new Map<number, CardTex>();\n private readonly reqs = new Map<number, Req>(); // by rid\n private readonly reqByKey = new Map<number, Req>();\n private readonly failedAt = new Map<number, number>();\n private queue: Req[] = [];\n private decoded: Decoded[] = [];\n // Keys of `decoded`: a bitmap that left the request books but is not resident until `frame()` uploads it\n // still counts as present, or the LOD pass (which runs before the upload in a tick) asks for it again.\n private readonly decodedKeys = new Set<number>();\n // Teardown that must wait until the frames that may still draw the old texture have rendered.\n private readonly retire: RetireQueue;\n // Cards whose texture was just evicted: the stage must re-point their sprites before the next draw.\n private evicted: number[] = [];\n private rid = 1;\n private inflight = 0;\n private pageBytes = 0;\n private ownBytes = 0;\n private overSince = 0;\n private border: string;\n readonly stats = {\n uploads: 0,\n uploadFrames: 0,\n uploadMsTotal: 0,\n uploadMsMax: 0,\n uploadsLastFrame: 0,\n uploadMsLastFrame: 0,\n decodes: 0,\n decodeMsTotal: 0,\n fetchedBytes: 0,\n cancelled: 0,\n failed: 0,\n evictedL2: 0,\n evictedL3: 0,\n evictedL1: 0,\n overBudgetMsMax: 0,\n peakBytes: 0,\n };\n\n constructor(\n renderer: WebGLRenderer,\n private readonly opts: TextureManagerOptions,\n ) {\n this.texSys = renderer.texture as unknown as GlTextureSystemInternals;\n this.gl = (renderer as unknown as { gl: WebGL2RenderingContext }).gl;\n this.retire = new RetireQueue(opts.retireDelay ?? 2);\n this.border = opts.border ?? '';\n this.atlas0 = this.makeAtlas0();\n this.atlas1 = this.makeAtlas1();\n this.spawnWorkers(opts.workers);\n }\n\n private makeAtlas0(): Atlas<Page> {\n return new Atlas<Page>(\n L0_SPEC,\n () => this.createPage(L0_SPEC.pageSize, false, 'l0-page'),\n (p) => this.destroyPage(p),\n );\n }\n private makeAtlas1(): Atlas<Page> {\n return new Atlas<Page>(\n L1_SPEC,\n () => this.createPage(L1_SPEC.pageSize, true, 'l1-page'),\n (p) => this.destroyPage(p),\n );\n }\n\n private spawnWorkers(n: number): void {\n for (let i = 0; i < n; i++) {\n // The built-in worker is inlined in the library bundle (a blob URL made at run time), so no asset URL\n // has to survive the host's bundler or dev server.\n const w = this.opts.workerUrl\n ? new Worker(this.opts.workerUrl, { type: 'module' })\n : new DecodeWorker();\n w.onmessage = (e: MessageEvent<WorkerOut>) => this.onWorker(i, e.data);\n w.onerror = (e) => console.error('[corkboard] decode worker error', e.message);\n this.workers.push(w);\n this.workerLoad.push(0);\n }\n }\n\n // ── Queries ────────────────────────────────────────────────────────────────\n get totalBytes(): number {\n return this.pageBytes + this.ownBytes;\n }\n get workerCount(): number {\n return this.workers.length;\n }\n get pendingWork(): boolean {\n return this.decoded.length > 0;\n }\n get queued(): number {\n return this.queue.length;\n }\n get inflightCount(): number {\n return this.inflight;\n }\n get retiredPending(): number {\n return this.retire.size;\n }\n pageCount(): { l0: number; l1: number } {\n return { l0: this.atlas0.pageCount, l1: this.atlas1.pageCount };\n }\n ownCount(level: 2 | 3): number {\n let n = 0;\n for (const c of this.cards.values()) if (c.tex[level]) n++;\n return n;\n }\n l2Count(): number {\n return this.ownCount(2);\n }\n l3Count(): number {\n return this.ownCount(3);\n }\n\n // Where the bytes are: pages, own textures, and the share of the own bytes that is pinned (on screen).\n breakdown(): {\n pageBytes: number;\n l2Bytes: number;\n l3Bytes: number;\n pinnedBytes: number;\n pinned: number;\n } {\n let pinned = 0;\n let pinnedN = 0;\n let l2 = 0;\n let l3 = 0;\n for (const [id, c] of this.cards) {\n for (const lv of [2, 3] as const) {\n if (!c.tex[lv]) continue;\n if (lv === 2) l2 += c.ownBytes[2];\n else l3 += c.ownBytes[3];\n if (this.keep(id, lv)) {\n pinned += c.ownBytes[lv];\n pinnedN++;\n }\n }\n }\n return {\n pageBytes: this.pageBytes,\n l2Bytes: l2,\n l3Bytes: l3,\n pinnedBytes: pinned,\n pinned: pinnedN,\n };\n }\n\n // False while the manager is at or past 85 % of its budget: requesting more for cards that are NOT on\n // screen would only make the next eviction pass drop it again (a fetch / evict loop that never parks).\n hasHeadroom(): boolean {\n return this.totalBytes <= this.opts.budgetBytes * 0.85;\n }\n\n has(card: BoardCard, level: Level): boolean {\n return !!this.cards.get(card.id)?.tex[level];\n }\n\n // The best resident texture for `desired`: the level itself, else the closest sharper level, else\n // the closest blurrier one.\n best(card: BoardCard, desired: Level): { tex: Texture; level: Level } | null {\n const ct = this.cards.get(card.id);\n if (!ct) return null;\n // A swapped poster whose new pictures have not landed: the old ones, not the ThumbHash, until they do.\n const out = ct.outgoing;\n if (out && desired > 0) {\n for (let l = desired; l <= 3; l++) {\n const t = out.tex[l];\n if (t) return { tex: t, level: l as Level };\n }\n for (let l = desired - 1; l >= 1; l--) {\n const t = out.tex[l];\n if (t) return { tex: t, level: l as Level };\n }\n }\n for (let l = desired; l <= 3; l++) {\n const t = ct.tex[l];\n if (t) return { tex: t, level: l as Level };\n }\n for (let l = desired - 1; l >= 0; l--) {\n const t = ct.tex[l];\n if (t) return { tex: t, level: l as Level };\n }\n return null;\n }\n\n hasOutgoing(card: BoardCard): boolean {\n return !!this.cards.get(card.id)?.outgoing;\n }\n\n // `needsOwn`: the card is on screen big enough to want an own texture (L2 / L3).\n touch(card: BoardCard, now: number, needsOwn: boolean): void {\n const ct = this.cards.get(card.id);\n if (!ct) return;\n ct.last = now;\n if (needsOwn) ct.last2 = now;\n }\n\n private urlOf(card: BoardCard, level: Level): string | undefined {\n return level === 1\n ? card.l1Url\n : level === 2\n ? card.l2Url\n : level === 3\n ? card.l3Url\n : undefined;\n }\n\n // ── Requests ───────────────────────────────────────────────────────────────\n // Replaces the wanted set: new items are queued, queued items no longer wanted are dropped and\n // in-flight ones are cancelled.\n setWanted(items: WantedItem[], now = performance.now()): void {\n const wanted = new Set<number>();\n for (const it of items) {\n const k = key(it.card, it.level);\n const ct = this.cards.get(it.card.id);\n const resident = ct?.tex[it.level];\n const need2 =\n isOwn(it.level) && it.bucket\n ? !ct?.ownCapped[it.level] && (ct?.ownLong[it.level] ?? 0) < it.bucket\n : false;\n if (resident && !need2) continue;\n // Decoded and waiting for its upload: on its way, not missing.\n if (this.decodedKeys.has(k)) continue;\n // Not requestable: no source yet (its URL has not arrived), or a recent failure.\n if (it.level === 0 ? !it.card.thumbhash : !this.urlOf(it.card, it.level)) continue;\n const failed = this.failedAt.get(k);\n if (failed !== undefined) {\n if (now - failed < RETRY_AFTER_MS) continue;\n this.failedAt.delete(k);\n }\n wanted.add(k);\n const existing = this.reqByKey.get(k);\n if (existing) {\n existing.dist = it.dist;\n continue;\n }\n const maxLong = it.level === 0 ? 32 : it.level === 1 ? L1_SPEC.cell : (it.bucket ?? 512);\n const req: Req = {\n rid: this.rid++,\n card: it.card,\n level: it.level,\n maxLong,\n dist: it.dist,\n inflight: false,\n worker: -1,\n cancelled: false,\n };\n this.reqs.set(req.rid, req);\n this.reqByKey.set(k, req);\n this.queue.push(req);\n }\n // Drop what is no longer wanted.\n if (this.reqByKey.size > wanted.size) {\n for (const [k, req] of this.reqByKey) {\n if (wanted.has(k)) continue;\n this.reqByKey.delete(k);\n this.cancelReq(req);\n }\n this.queue = this.queue.filter((r) => this.reqs.has(r.rid) && !r.cancelled);\n }\n this.pump();\n }\n\n private cancelReq(req: Req): void {\n if (req.inflight) {\n req.cancelled = true;\n const msg: WorkerIn = { op: 'cancel', rid: req.rid };\n this.workers[req.worker].postMessage(msg);\n this.stats.cancelled++;\n } else {\n this.reqs.delete(req.rid);\n }\n }\n\n private pump(): void {\n const cap = this.workers.length * INFLIGHT_PER_WORKER;\n if (this.inflight >= cap || this.queue.length === 0) return;\n // On-screen cards first; among them the lower level first (cheap, gives a first paint), then the\n // nearest to the viewport centre. After a context loss this restores the view in viewport order.\n this.queue.sort(\n (a, b) =>\n Number(a.dist >= FAR_DIST) - Number(b.dist >= FAR_DIST) ||\n a.level - b.level ||\n a.dist - b.dist,\n );\n while (this.inflight < cap && this.queue.length > 0) {\n const req = this.queue.shift() as Req;\n // Least-loaded worker.\n let wi = 0;\n for (let i = 1; i < this.workers.length; i++) {\n if (this.workerLoad[i] < this.workerLoad[wi]) wi = i;\n }\n req.inflight = true;\n req.worker = wi;\n this.workerLoad[wi]++;\n this.inflight++;\n const card = req.card;\n const msg: DecodeRequest = {\n op: 'load',\n rid: req.rid,\n level: req.level,\n hash: req.level === 0 ? card.thumbhash : undefined,\n url: absoluteUrl(this.urlOf(card, req.level)),\n maxLong: req.maxLong,\n soft: this.opts.softCanvas,\n radiusWorld: card.radius,\n worldLong: Math.max(card.w, card.h),\n aspect: card.w > 0 ? card.h / card.w : undefined,\n border: req.level === 0 ? undefined : this.border || undefined,\n };\n this.workers[wi].postMessage(msg);\n }\n }\n\n private onWorker(wi: number, m: WorkerOut): void {\n const req = this.reqs.get(m.rid);\n if (req) {\n // Only a request still on the books was counted in: after reset() the load is already zero and a late\n // reply (the abort of a cancelled load) must not eat into the new requests' count.\n this.workerLoad[wi] = Math.max(0, this.workerLoad[wi] - 1);\n this.inflight = Math.max(0, this.inflight - 1);\n this.reqs.delete(req.rid);\n if (this.reqByKey.get(key(req.card, req.level)) === req) {\n this.reqByKey.delete(key(req.card, req.level));\n }\n }\n if (m.op === 'fail') {\n if (!m.aborted) {\n this.stats.failed++;\n if (req) this.failedAt.set(key(req.card, req.level), performance.now());\n console.warn('[corkboard] decode failed', m.reason);\n }\n this.pump();\n return;\n }\n if (!req || req.cancelled) {\n m.bitmap.close();\n this.pump();\n return;\n }\n this.stats.decodes++;\n this.stats.decodeMsTotal += m.decodeMs;\n this.stats.fetchedBytes += m.fetched;\n this.decoded.push({\n req,\n bitmap: m.bitmap,\n w: m.w,\n h: m.h,\n fetched: m.fetched,\n decodeMs: m.decodeMs,\n });\n this.decodedKeys.add(key(req.card, req.level));\n this.pump();\n this.opts.onWake();\n }\n\n // ── Uploads (called once per frame, before render) ─────────────────────────\n // Uploads decoded bitmaps until `budgetMs` is spent (at least one). Returns the ids of the cards\n // that got a new texture.\n frame(budgetMs: number, now: number): number[] {\n const changed: number[] = [];\n const t0 = performance.now();\n let n = 0;\n while (this.decoded.length > 0) {\n const d = this.decoded.shift() as Decoded;\n this.decodedKeys.delete(key(d.req.card, d.req.level));\n this.upload(d, now);\n changed.push(d.req.card.id);\n n++;\n if (performance.now() - t0 >= budgetMs) break;\n }\n if (n > 0) {\n for (const p of [...this.atlas1.pageList]) this.flushMips(p);\n const ms = performance.now() - t0;\n const s = this.stats;\n s.uploads += n;\n s.uploadFrames++;\n s.uploadMsTotal += ms;\n s.uploadMsMax = Math.max(s.uploadMsMax, ms);\n s.uploadsLastFrame = n;\n s.uploadMsLastFrame = ms;\n this.enforceBudget(now);\n } else {\n this.stats.uploadsLastFrame = 0;\n this.stats.uploadMsLastFrame = 0;\n }\n return changed;\n }\n\n takeEvicted(): number[] {\n const e = this.evicted;\n this.evicted = [];\n return e;\n }\n\n // Call after every completed render (see retire.ts), and `flushRetired` when the loop parks.\n afterRender(): void {\n this.retire.afterRender();\n }\n flushRetired(): void {\n this.retire.flushIdle();\n }\n\n private retireTexture(t: Texture, destroySource: boolean): void {\n this.retire.push(() => t.destroy(destroySource));\n this.opts.onRetire?.();\n }\n\n private releaseCell(atlas: Atlas<Page>, cell: AtlasCell<Page>): void {\n this.retire.push(() => atlas.release(cell));\n this.opts.onRetire?.();\n }\n\n private upload(d: Decoded, now: number): void {\n const { req, bitmap, w, h } = d;\n const card = req.card;\n const ct = this.cardTex(card.id);\n ct.last = now;\n const level = req.level;\n if (isOwn(level)) {\n ct.last2 = now;\n const source = new ImageSource({\n resource: bitmap,\n width: w,\n height: h,\n alphaMode: 'premultiply-alpha-on-upload',\n autoGenerateMipmaps: true,\n scaleMode: 'linear',\n label: `l${level}`,\n });\n // Uploads now (and builds the mip chain), inside the budgeted step rather than at first draw.\n this.texSys.initSource(source);\n bitmap.close();\n const old = ct.tex[level];\n if (old) {\n this.retireTexture(old, true);\n this.ownBytes -= ct.ownBytes[level];\n }\n ct.tex[level] = new Texture({ source });\n ct.ownLong[level] = Math.max(w, h);\n ct.ownCapped[level] = ct.ownLong[level] < req.maxLong;\n ct.ownBytes[level] = w * h * 4 * MIP_FACTOR;\n this.ownBytes += ct.ownBytes[level];\n this.releaseOutgoing(ct);\n return;\n }\n const atlas = level === 0 ? this.atlas0 : this.atlas1;\n const prev = ct.cell[level];\n if (prev) {\n const old = ct.tex[level];\n if (old) this.retireTexture(old, false);\n this.releaseCell(atlas, prev);\n ct.cell[level] = null;\n ct.tex[level] = null;\n }\n const cell = atlas.alloc();\n this.uploadCell(cell, bitmap, w, h, level === 0 ? L0_SPEC.cell : L1_SPEC.cell);\n bitmap.close();\n cell.page.dirty = true;\n ct.cell[level] = cell;\n ct.tex[level] = new Texture({\n source: cell.page.source,\n frame: new Rectangle(cell.x, cell.y, w, h),\n });\n if (level === 1) this.releaseOutgoing(ct);\n }\n\n private cardTex(id: number): CardTex {\n let ct = this.cards.get(id);\n if (!ct) {\n ct = {\n tex: [null, null, null, null],\n cell: [null, null],\n ownLong: [0, 0, 0, 0],\n ownCapped: [false, false, false, false],\n ownBytes: [0, 0, 0, 0],\n last: 0,\n last2: 0,\n outgoing: null,\n };\n this.cards.set(id, ct);\n }\n return ct;\n }\n\n // ── Card lifecycle ─────────────────────────────────────────────────────────\n // Drops every texture and request of one card (the element was removed, or its media / size changed\n // so what is resident is stale). The caller re-points the card's sprite first (it must not draw the\n // old texture again): teardown is deferred like every other.\n forget(id: number): void {\n for (let level = 0; level < 4; level++) {\n const k = id * 4 + level;\n const req = this.reqByKey.get(k);\n if (req) {\n this.reqByKey.delete(k);\n this.cancelReq(req);\n this.queue = this.queue.filter((r) => r !== req);\n }\n this.failedAt.delete(k);\n }\n // Bitmaps of this card that are decoded but not uploaded yet (a card with nothing resident has them too).\n this.decoded = this.decoded.filter((d) => {\n if (d.req.card.id !== id) return true;\n d.bitmap.close();\n this.decodedKeys.delete(key(d.req.card, d.req.level));\n return false;\n });\n const ct = this.cards.get(id);\n if (!ct) return;\n this.cards.delete(id);\n this.releaseOutgoing(ct);\n for (let level = 0; level < 4; level++) {\n const t = ct.tex[level];\n if (!t) continue;\n if (level >= 2) {\n this.retireTexture(t, true);\n this.ownBytes -= ct.ownBytes[level];\n } else {\n this.retireTexture(t, false);\n const cell = ct.cell[level as 0 | 1];\n if (cell) this.releaseCell(level === 0 ? this.atlas0 : this.atlas1, cell);\n }\n }\n }\n\n // The card's pictures (levels 1..3) are another image now (its URLs changed; ThumbHash, size and corners did\n // not): requests and failures for the old ones are dropped, and what is resident moves aside as `outgoing`\n // instead of being forgotten. `best()` keeps drawing it until the first level of the new picture uploads, so\n // the card goes picture -> picture and never shows the placeholder in between. `keep` false: nothing is\n // kept (no new picture to wait for, or nobody looking). Level 0 is the same ThumbHash and stays.\n swapPictures(id: number, keep: boolean): void {\n for (let level = 1; level < 4; level++) {\n const k = id * 4 + level;\n const req = this.reqByKey.get(k);\n if (req) {\n this.reqByKey.delete(k);\n this.cancelReq(req);\n this.queue = this.queue.filter((r) => r !== req);\n }\n this.failedAt.delete(k);\n }\n this.decoded = this.decoded.filter((d) => {\n if (d.req.card.id !== id || d.req.level === 0) return true;\n d.bitmap.close();\n this.decodedKeys.delete(key(d.req.card, d.req.level));\n return false;\n });\n const ct = this.cards.get(id);\n if (!ct) return;\n const out: Outgoing = { tex: [null, null, null, null], cell: [null, null], ownBytes: [0, 0, 0, 0] };\n let moved = false;\n for (let level = 1; level < 4; level++) {\n const t = ct.tex[level];\n if (!t) continue;\n moved = true;\n out.tex[level] = t;\n ct.tex[level] = null;\n if (level >= 2) {\n // Still counted in `ownBytes` until released.\n out.ownBytes[level] = ct.ownBytes[level];\n ct.ownBytes[level] = 0;\n ct.ownLong[level] = 0;\n ct.ownCapped[level] = false;\n } else {\n out.cell[1] = ct.cell[1];\n ct.cell[1] = null;\n }\n }\n // Nothing resident to keep drawing: an earlier outgoing set (no new level landed since) stays as it is.\n if (moved) {\n this.releaseOutgoing(ct);\n ct.outgoing = out;\n }\n if (!keep) this.releaseOutgoing(ct);\n }\n\n dropOutgoing(card: BoardCard): void {\n const ct = this.cards.get(card.id);\n if (ct) this.releaseOutgoing(ct);\n }\n\n private releaseOutgoing(ct: CardTex): void {\n const out = ct.outgoing;\n if (!out) return;\n ct.outgoing = null;\n for (let level = 1; level < 4; level++) {\n const t = out.tex[level];\n if (!t) continue;\n if (level >= 2) {\n this.retireTexture(t, true);\n this.ownBytes -= out.ownBytes[level];\n } else {\n this.retireTexture(t, false);\n const cell = out.cell[1];\n if (cell) this.releaseCell(this.atlas1, cell);\n }\n }\n }\n\n // The hairline colour changed with the theme: every texture has it baked in.\n setBorder(border: string): void {\n if (border === this.border) return;\n this.border = border;\n }\n\n // ── GL ─────────────────────────────────────────────────────────────────────\n private createPage(size: number, mips: boolean, label: string): Page {\n const source = new TextureSource({\n width: size,\n height: size,\n format: 'rgba8unorm',\n alphaMode: 'premultiply-alpha-on-upload',\n autoGenerateMipmaps: false,\n // Limited mips: the gutters keep 3 levels clean (128 -> 64 -> 32 px cells).\n mipLevelCount: mips ? 3 : 1,\n scaleMode: 'linear',\n mipmapFilter: mips ? 'linear' : 'nearest',\n addressMode: 'clamp-to-edge',\n label,\n });\n // Allocates the (empty) storage now.\n this.texSys.initSource(source);\n const bytes = size * size * 4 * (mips ? MIP_FACTOR : 1);\n this.pageBytes += bytes;\n return { source, bytes, mips, dirty: false };\n }\n\n private destroyPage(p: Page): void {\n if (!p.dead) this.pageBytes -= p.bytes;\n p.source.destroy();\n }\n\n private bindPage(p: Page): { target: number } {\n const gl = this.gl;\n const sys = this.texSys;\n const glTex = sys.getGlSource(p.source);\n sys._activateLocation(0);\n gl.bindTexture(glTex.target, glTex.texture);\n sys._setBoundTexture(0, p.source);\n return glTex;\n }\n\n // `w` x `h` is the bitmap's size, `size` the usable side of a cell.\n private uploadCell(\n cell: AtlasCell<Page>,\n bitmap: ImageBitmap,\n w: number,\n h: number,\n size: number,\n ): void {\n const gl = this.gl;\n const { x, y } = cell;\n const glTex = this.bindPage(cell.page);\n // Canvas-born bitmaps are premultiplied, so upload them as such: no conversion, no fringes.\n if (!this.texSys._premultiplyAlpha) {\n gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);\n this.texSys._premultiplyAlpha = true;\n }\n // A recycled cell still holds its last occupant: a smaller bitmap leaves that picture in the rest of the\n // cell, where the bilinear taps and the mips at the edge of the frame would read it. Clear the rest\n // (the bitmap itself covers the rest of the area; the gutter is never written).\n if (cell.reused && (w < size || h < size)) {\n const zero = clearBuffer(size * size * 4);\n if (w < size) {\n gl.texSubImage2D(glTex.target, 0, x + w, y, size - w, size, gl.RGBA, gl.UNSIGNED_BYTE, zero);\n }\n if (h < size) {\n gl.texSubImage2D(glTex.target, 0, x, y + h, w, size - h, gl.RGBA, gl.UNSIGNED_BYTE, zero);\n }\n }\n gl.texSubImage2D(glTex.target, 0, x, y, gl.RGBA, gl.UNSIGNED_BYTE, bitmap);\n }\n\n private flushMips(p: Page): void {\n if (!p.dirty) return;\n p.dirty = false;\n if (!p.mips) return;\n const glTex = this.bindPage(p);\n this.gl.generateMipmap(glTex.target);\n }\n\n // ── Budget ─────────────────────────────────────────────────────────────────\n // Frees own textures, then cold L1 cells, least recently seen first, until under budget. `keep`\n // says which textures are in use right now (never evicted): an own texture only while its card is on\n // screen and big enough to want that level, an L1 while the card is on screen.\n keep: (id: number, level: 1 | 2 | 3) => boolean = () => false;\n\n enforceBudget(now: number): void {\n const total = this.totalBytes;\n this.stats.peakBytes = Math.max(this.stats.peakBytes, total);\n if (total <= this.opts.budgetBytes) {\n if (this.overSince) {\n this.stats.overBudgetMsMax = Math.max(this.stats.overBudgetMsMax, now - this.overSince);\n this.overSince = 0;\n }\n return;\n }\n if (!this.overSince) this.overSince = now;\n // Own textures first (the big ones), least recently on screen first. An entry is (card, level).\n const own: LruEntry[] = [];\n for (const [id, ct] of this.cards) {\n for (const lv of [2, 3] as const) {\n if (ct.tex[lv]) {\n own.push({\n id: id * 4 + lv,\n last: ct.last2,\n bytes: ct.ownBytes[lv],\n pinned: this.keep(id, lv),\n });\n }\n }\n }\n for (const k of planEviction(own, total, this.opts.budgetBytes)) {\n const id = k >> 2;\n const lv = (k & 3) as 2 | 3;\n const ct = this.cards.get(id) as CardTex;\n this.retireTexture(ct.tex[lv] as Texture, true);\n ct.tex[lv] = null;\n this.ownBytes -= ct.ownBytes[lv];\n ct.ownBytes[lv] = 0;\n ct.ownLong[lv] = 0;\n ct.ownCapped[lv] = false;\n this.evicted.push(id);\n if (lv === 2) this.stats.evictedL2++;\n else this.stats.evictedL3++;\n }\n // Then cold L1 cells. A cell only frees bytes once its whole page is empty (and after the frame),\n // so each one counts as its share of a page: one pass must not strip every cold cell.\n if (this.totalBytes > this.opts.budgetBytes * 0.85) {\n const perCell = L1_PAGE_BYTES / cellsPerPage(L1_SPEC);\n const l1: LruEntry[] = [];\n for (const [id, ct] of this.cards) {\n if (ct.cell[1]) l1.push({ id, last: ct.last, bytes: perCell, pinned: this.keep(id, 1) });\n }\n for (const id of planEviction(l1, this.totalBytes, this.opts.budgetBytes)) {\n const ct = this.cards.get(id) as CardTex;\n this.retireTexture(ct.tex[1] as Texture, false);\n ct.tex[1] = null;\n this.releaseCell(this.atlas1, ct.cell[1] as AtlasCell<Page>);\n ct.cell[1] = null;\n this.evicted.push(id);\n this.stats.evictedL1++;\n }\n }\n if (this.totalBytes <= this.opts.budgetBytes && this.overSince) {\n this.stats.overBudgetMsMax = Math.max(this.stats.overBudgetMsMax, now - this.overSince);\n this.overSince = 0;\n }\n }\n\n // The GL context was lost and restored (or a frame failed): every texture is gone. Forget them all;\n // the stage re-requests what is on screen (from the HTTP cache) in viewport order.\n reset(): void {\n for (const r of this.reqs.values()) {\n if (r.inflight) this.workers[r.worker].postMessage({ op: 'cancel', rid: r.rid } as WorkerIn);\n }\n this.reqs.clear();\n this.reqByKey.clear();\n this.failedAt.clear();\n this.queue = [];\n this.inflight = 0;\n this.workerLoad.fill(0);\n for (const d of this.decoded) d.bitmap.close();\n this.decoded = [];\n this.decodedKeys.clear();\n // Sprites still point at the old textures until the stage re-points them and the next frames have\n // rendered, so tear the old ones down only then (and never touch the new atlases doing it).\n const oldTextures: [Texture, boolean][] = [];\n for (const ct of this.cards.values()) {\n ct.tex.forEach((t, level) => t && oldTextures.push([t, level >= 2]));\n ct.outgoing?.tex.forEach((t, level) => t && oldTextures.push([t, level >= 2]));\n }\n const old0 = this.atlas0;\n const old1 = this.atlas1;\n for (const a of [old0, old1]) for (const p of a.pageList) p.dead = true;\n this.atlas0 = this.makeAtlas0();\n this.atlas1 = this.makeAtlas1();\n this.cards.clear();\n this.retire.push(() => {\n for (const [t, own] of oldTextures) t.destroy(own);\n old0.clear();\n old1.clear();\n });\n this.opts.onRetire?.();\n this.evicted = [];\n this.pageBytes = 0;\n this.ownBytes = 0;\n this.overSince = 0;\n }\n\n dispose(): void {\n this.reset();\n this.retire.flushAll();\n for (const w of this.workers) w.terminate();\n this.workers.length = 0;\n }\n}\n","// A media card (image or video): a container holding the picture, one Sprite. The stage assigns its\n// texture from the TextureManager, level by level. Cards stay plain sprites: corners and hairline are\n// baked into the textures, so they batch with no mask or shader. A video card is drawn the same way (its\n// poster is the picture); the playing <video> is a DOM overlay (src/video/*), not part of this view.\nimport { Container, Sprite, Texture } from 'pixi.js';\nimport { DEG, type WorldRect } from '../../interact/geometry';\nimport type { Element } from '../../types';\nimport type { BoardCard } from '../types';\nimport { parseHex } from '../theme';\nimport type { ElementView, ViewCtx } from './view';\n\nexport class MediaView implements ElementView {\n readonly variant = 'media' as const;\n readonly display = new Container();\n private readonly sprite: Sprite;\n el: Element | null = null;\n mark = 0;\n // The texture-manager side of this card (slot id, size, urls); owned by the stage.\n card: BoardCard | null = null;\n // The level whose texture the sprite shows now (-1: the placeholder).\n shown = -1;\n private rect: WorldRect = { x: 0, y: 0, w: 1, h: 1, rot: 0 };\n // The size `place` last wrote (NaN: a view fresh from the pool, which holds another card's).\n private placedW = Number.NaN;\n private placedH = Number.NaN;\n\n constructor() {\n this.sprite = new Sprite(Texture.WHITE);\n this.sprite.anchor.set(0.5);\n this.sprite.eventMode = 'none';\n this.display.eventMode = 'none';\n this.display.addChild(this.sprite);\n }\n\n get kind(): Element['kind'] {\n return this.el?.kind ?? 'image';\n }\n\n mount(el: Element, rect: WorldRect, ctx: ViewCtx): void {\n this.el = el;\n this.display.alpha = 1;\n this.rect = rect;\n this.place();\n this.paintPlaceholder(ctx);\n }\n\n update(el: Element, _props: readonly string[], rect: WorldRect, ctx: ViewCtx): void {\n this.el = el;\n this.rect = rect;\n this.place();\n if (this.shown < 0) this.paintPlaceholder(ctx);\n }\n\n setRect(r: WorldRect): void {\n this.rect = r;\n this.place();\n }\n\n refresh(ctx: ViewCtx): void {\n this.place();\n if (this.shown < 0) this.paintPlaceholder(ctx);\n }\n\n // The container sits at the box's centre and turns about it. A drag moves and turns it every frame and\n // leaves the size alone: only the position is written then.\n private place(): void {\n const r = this.rect;\n const d = this.display;\n if (r.w !== this.placedW || r.h !== this.placedH) {\n this.placedW = r.w;\n this.placedH = r.h;\n d.pivot.set(r.w / 2, r.h / 2);\n const s = this.sprite;\n s.position.set(r.w / 2, r.h / 2);\n s.width = r.w;\n s.height = r.h;\n }\n d.position.set(r.x + r.w / 2, r.y + r.h / 2);\n d.rotation = r.rot * DEG;\n }\n\n setAlphaOverride(alpha: number): void {\n this.display.alpha = alpha;\n }\n\n // Points the sprite at `tex` (null = placeholder). Returns whether anything changed.\n setTexture(tex: Texture | null, level: number, ctx: ViewCtx): boolean {\n const s = this.sprite;\n if (tex === null) {\n if (this.shown < 0 && s.texture === Texture.WHITE) return false;\n this.shown = -1;\n this.paintPlaceholder(ctx);\n return true;\n }\n if (s.texture === tex) {\n this.shown = level;\n return false;\n }\n const w = s.width;\n const h = s.height;\n s.texture = tex;\n s.tint = 0xffffff;\n // Assigning a texture resets the scale to the new texture's size: restore the card's size.\n s.width = w;\n s.height = h;\n this.shown = level;\n return true;\n }\n\n // A flat well: the media's own `color` when it has one, else the theme's.\n private paintPlaceholder(ctx: ViewCtx): void {\n const s = this.sprite;\n const w = s.width;\n const h = s.height;\n const color = this.el?.media.color;\n s.texture = Texture.WHITE;\n s.tint = (color !== undefined ? parseHex(color) : null) ?? ctx.theme.well;\n s.width = w;\n s.height = h;\n this.shown = -1;\n }\n\n unmount(): void {\n this.el = null;\n this.card = null;\n this.shown = -1;\n this.placedW = Number.NaN;\n this.placedH = Number.NaN;\n }\n}\n","// The view registry: which pooled view class draws each element kind.\n//\n// Adding a kind means adding a `ViewDefinition` here (plus, when the kind needs live DOM, an overlay in\n// the host: see `Overlay` in src/overlay.ts). The stage only knows the interface.\nimport type { ElementKind } from '../../types';\nimport { MediaView } from './mediaView';\nimport type { ElementView } from './view';\n\nexport interface ViewDefinition {\n // The pool name. Kinds that share a view class share a variant.\n variant: string;\n create(): ElementView;\n // The view is a textured card: the stage allocates a texture slot for it and runs the LOD pipeline.\n textured: boolean;\n}\n\nexport const VIEW_DEFINITIONS: Record<ElementKind, ViewDefinition> = {\n image: { variant: 'media', create: () => new MediaView(), textured: true },\n video: { variant: 'media', create: () => new MediaView(), textured: true },\n // The poster of an embed is its texture; the live iframe is a DOM layer (src/embed/*).\n embed: { variant: 'media', create: () => new MediaView(), textured: true },\n};\n","// Per-variant pools of element views: a view is expensive to build (Pixi objects) and cheap to reuse,\n// and the viewport turns over hundreds of elements during a pan.\nimport type { ElementKind } from '../../types';\nimport { VIEW_DEFINITIONS, type ViewDefinition } from './registry';\nimport type { ElementView } from './view';\n\nexport class ViewPools {\n private readonly pools = new Map<string, ElementView[]>();\n private created = 0;\n private reused = 0;\n\n acquire(kind: ElementKind): ElementView {\n const def = VIEW_DEFINITIONS[kind];\n const v = this.pools.get(def.variant)?.pop();\n if (v) {\n this.reused++;\n return v;\n }\n this.created++;\n return def.create();\n }\n\n release(view: ElementView): void {\n let pool = this.pools.get(view.variant);\n if (!pool) {\n pool = [];\n this.pools.set(view.variant, pool);\n }\n pool.push(view);\n }\n\n stats(): { created: number; reused: number; pooled: number } {\n let pooled = 0;\n for (const p of this.pools.values()) pooled += p.length;\n return { created: this.created, reused: this.reused, pooled };\n }\n\n dispose(): void {\n this.pools.clear();\n }\n}\n\nexport const definitionOf = (kind: ElementKind): ViewDefinition => VIEW_DEFINITIONS[kind];\n","// Stage: the Pixi stage of a corkboard. One WebGL canvas, a world container that is a render group (the\n// camera is its GPU transform), pooled views for the elements near the viewport, and an on-demand render\n// loop: nothing runs while nothing moves (0 rAF callbacks, 0 % CPU idle).\n//\n// store events + input ──► CameraController ──► rAF tick ──► (cull + LOD every 100 ms during a\n// gesture, exact on settle) ──► TextureManager uploads (<= 4 ms) ──► overlay ──► one render\n//\n// Design rules: Pixi's own ticker and event system are off, culling is ours (rbush in the store: only\n// elements in the viewport plus a screen of overscan have a display object), and nothing but this loop\n// touches the render path.\n//\n// Draw order: every view's `zIndex` is the element's rank in the store's draw order, and the world\n// container sorts by it.\nimport { Application, Container, Texture, TilingSprite, Ticker, type WebGLRenderer } from 'pixi.js';\nimport type { Camera, Rect } from '../math';\nimport { elementBox, emptyBox, worldRectOf, type WorldRect } from '../interact/geometry';\nimport type { Box } from '../interact/geometry';\nimport type { ChangeSet, StoreEvent } from '../store';\nimport { DEFAULTS, MAX_SCALE, MIN_SCALE, type Element, type ElementId } from '../types';\nimport { CameraController } from './camera';\nimport { l2Bucket, l3Bucket, MAX_L3, pickLevel, type Level } from './lod';\nimport { OverlayLayer } from './overlay';\nimport { parkTicker } from './parkTicker';\nimport { FAR_DIST, TextureManager, type WantedItem } from './textures';\nimport { DARK_THEME, cssHex, type Theme } from './theme';\nimport type { BoardCard } from './types';\nimport { ViewPools, definitionOf } from './views/pool';\nimport { MediaView } from './views/mediaView';\nimport type { ElementView, ViewCtx } from './views/view';\n\n// What the stage reads from the store (`Store` satisfies it structurally).\nexport interface StageStore {\n subscribe(listener: (e: StoreEvent) => void): () => void;\n get(id: ElementId): Element | undefined;\n elements(): IterableIterator<Element>;\n searchInto(box: Box, out: Element[]): Element[];\n rank(id: ElementId): number;\n readonly orderVersion: number;\n}\n\nexport interface StageOptions {\n // Texture memory budget in bytes (default 256 MB; use ~128 MB on small devices).\n budgetBytes?: number;\n // Decode workers (default: a quarter of the cores, 1..4).\n workers?: number;\n // URL of the decode worker script, for pages whose CSP forbids `worker-src blob:` (the built-in worker is\n // inlined and started from a blob URL). Serve `@niccolofanton/corkboard/decode.worker.js` yourself and pass\n // its URL here.\n workerUrl?: string | URL;\n softCanvas?: boolean;\n // Per-frame texture upload budget, ms (default 4).\n uploadBudgetMs?: number;\n // Overscan, as a fraction of the viewport added on every side (default 0.5).\n overscan?: number;\n // Wrap each render in an EXT_disjoint_timer_query_webgl2 query where the browser has one.\n gpuTimer?: boolean;\n theme?: Theme;\n // Show the background dot grid (default true).\n grid?: boolean;\n // Completed renders before a retired texture is destroyed (see retire.ts).\n retireDelay?: number;\n // Load Pixi's CSP-safe build (no `new Function`), for pages whose content security policy forbids eval.\n cspSafe?: boolean;\n // The zoom range of the camera (default 0.05..4). A board of thousands of world px wide that is fitted\n // whole needs a lower minimum.\n minScale?: number;\n maxScale?: number;\n}\n\nconst LOD_INTERVAL_MS = 100;\nconst SETTLE_MS = 140;\n// World px between background dots, also the grid cards snap to when grid snapping is on.\nexport const GRID = 24;\n// How far past the viewport (fraction of its size) a card still counts as on screen.\nconst VIEW_MARGIN = 0.1;\n// Time a tick may spend creating views for elements that entered the viewport (ms).\nconst MOUNT_BUDGET_MS = 5;\n// The rounded corners are baked in texels from the card's world size, so a resize scales them too: the corner\n// drawn is radius * long / bakedLong. Up to this far off (world px) is left alone; past it the card is baked\n// again, which shows its placeholder for a moment. A square-cornered card never needs it.\nconst BAKE_CORNER_SLACK = 1;\n// The textures are cropped to the card's height / width (cover): a ratio that moved by more than this fraction\n// since the bake is baked again.\nconst BAKE_ASPECT_SLACK = 0.01;\n\nconst pct = (a: Float32Array, n: number, p: number): number => {\n if (n === 0) return 0;\n const s = Array.from(a.subarray(0, n)).sort((x, y) => x - y);\n return s[Math.min(n - 1, Math.floor((n - 1) * p))];\n};\nconst r2 = (n: number): number => Math.round(n * 100) / 100;\n\nfunction sameBytes(a: Uint8Array | undefined, b: Uint8Array | undefined): boolean {\n if (a === b) return true;\n if (!a || !b || a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;\n return true;\n}\n\n// The results of `contentBounds` that stand for \"nothing there\" (a fresh rect each, so the public API keeps\n// its shape): a fit of one of them is a no-op instead of a zoom onto the origin.\nconst noContent = new WeakSet<Rect>();\n\n// Base64 (standard or url-safe) -> bytes.\nfunction decodeBase64(s: string): Uint8Array {\n const bin = atob(s.replace(/-/g, '+').replace(/_/g, '/'));\n const out = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);\n return out;\n}\n\n// The camera's zoom range from the options: the defaults for anything missing or not a usable range.\nfunction scaleBounds(o: Pick<StageOptions, 'minScale' | 'maxScale'>): { min: number; max: number } {\n const min = o.minScale !== undefined && o.minScale > 0 ? o.minScale : MIN_SCALE;\n const max = o.maxScale !== undefined && o.maxScale >= min ? o.maxScale : Math.max(MAX_SCALE, min);\n return { min, max };\n}\n\n// A preview / committed geometry in world space, owned by the stage while a gesture runs.\nexport type PreviewRect = WorldRect;\n\nexport class Stage {\n readonly app: Application;\n readonly world: Container;\n readonly overlay: OverlayLayer;\n readonly cam: CameraController;\n readonly tm: TextureManager;\n readonly pools = new ViewPools();\n private readonly renderer: WebGLRenderer;\n private readonly bg: TilingSprite;\n private readonly canvas: HTMLCanvasElement;\n private readonly opts: Required<\n Omit<\n StageOptions,\n 'theme' | 'workers' | 'workerUrl' | 'retireDelay' | 'cspSafe' | 'grid' | 'minScale' | 'maxScale'\n >\n > & { workers: number; retireDelay?: number };\n private readonly ro: ResizeObserver;\n private readonly cleanups: (() => void)[] = [];\n private dpr: number;\n // The element the stage sits in: its page position is read when a pointer needs it (the page can\n // move it without resizing it), not only when it resizes.\n private readonly hostEl: HTMLElement;\n private theme: Theme;\n private showGrid: boolean;\n private readonly ctx: ViewCtx;\n\n // ── Scene ──\n private store: StageStore | null = null;\n private unsub: (() => void) | null = null;\n private readonly views = new Map<ElementId, ElementView>();\n private readonly mediaViews = new Set<MediaView>();\n private readonly hits: Element[] = [];\n // Elements that entered the mount window and wait for their view: mounting is time-budgeted per tick\n // (a zoom-out can bring thousands in at once), nearest first.\n private mountQueue: { id: ElementId; key: number }[] = [];\n private readonly queued = new Set<ElementId>();\n private queueSorted = true;\n private stamp = 0;\n private mountedWin: Rect | null = null;\n private mountedScale = 0;\n private orderSeen = -1;\n // Store changes waiting for the next tick.\n private pendingAdded = new Set<ElementId>();\n private pendingRemoved = new Map<ElementId, Element>();\n private pendingUpdated = new Map<ElementId, Set<string>>();\n private pendingReload = false;\n\n // ── Cards (texture slots) ──\n private slotOf = new Map<ElementId, number>();\n private freeSlots: number[] = [];\n private slotCount = 0;\n private slotCard: (BoardCard | null)[] = [];\n private slotView: (MediaView | null)[] = [];\n // Per slot: the level the card wants (0..3), whether it touches the viewport.\n private slotLevel: Int8Array = new Int8Array(64);\n private slotOnScreen: Uint8Array = new Uint8Array(64);\n private slotOwn: Uint8Array = new Uint8Array(64);\n // Per slot: the long side (world px) the card's textures were last baked at (see BAKE_CORNER_SLACK).\n private slotBaked: Float32Array = new Float32Array(64);\n // Per slot: the card's height / width the textures were cropped to (cover). 0 = none yet.\n private slotBakedAspect: Float32Array = new Float32Array(64);\n private l0Missing = 0;\n // Decoded ThumbHash bytes of base64 strings, by string.\n private readonly hashCache = new Map<string, Uint8Array>();\n\n // ── Overrides applied on top of the committed state ──\n private readonly previews = new Map<ElementId, PreviewRect>();\n private readonly hidden = new Set<ElementId>();\n // Runtime pictures that stand in for an element's `media.src` / `sizes` (see setPosterOverride).\n private readonly posters = new Map<ElementId, string>();\n private readonly alphas = new Map<ElementId, number>();\n // Elements that must stay mounted regardless of the window (previewed, being dragged).\n private readonly pinned = new Set<ElementId>();\n\n // ── Loop state ──\n private raf = 0;\n private lastTs = 0;\n private renderedVersion = -1;\n private dirty = true;\n private lodDirty = false;\n private lastLod = -1e9;\n private settleTimer = 0;\n private lost = false;\n private disposed = false;\n private beforeHooks: (() => void)[] = [];\n private frameHooks: ((camChanged: boolean) => void)[] = [];\n private settleHooks: (() => void)[] = [];\n // Hooks that threw and were already reported (once each: a hook that throws every frame must not flood).\n private readonly reportedHooks = new WeakSet<object>();\n // Watches the page's pixel ratio: a media query for the current value, re-armed after every change.\n private dprQuery: MediaQueryList | null = null;\n // Frames that threw and were healed by rebuilding the textures (never reset).\n private renderErrorsTotal = 0;\n // Which step of the tick is running (names the step in a recovered error).\n private where = 'idle';\n private rendersSinceRetire = 0;\n\n // ── Instrumentation ──\n private t0 = 0;\n private firstPaintMs: number | null = null;\n private l1CompleteMs: number | null = null;\n private counters = {\n renderErrors: 0,\n hookErrors: 0,\n rafCalls: 0,\n ticks: 0,\n renders: 0,\n cullPasses: 0,\n requeries: 0,\n lodPasses: 0,\n mounts: 0,\n unmounts: 0,\n };\n private readonly phase = { store: 0, camera: 0, upload: 0, overlay: 0, render: 0 };\n private slowTicks: Record<string, number>[] = [];\n private reqMs = { search: 0, mount: 0, unmount: 0, lod: 0 };\n private lodPassMs = new Float32Array(1024);\n private nLodPass = 0;\n private tickMs = new Float32Array(4096);\n private renderMs = new Float32Array(4096);\n private nTick = 0;\n private nRender = 0;\n private gpu: GpuTimer | null = null;\n private gpuMs = new Float32Array(4096);\n private nGpu = 0;\n\n static async create(host: HTMLElement, options: StageOptions = {}): Promise<Stage> {\n // Pixi's system ticker (its GC scheduler) would keep a rAF loop alive forever: park it, and put it back\n // the way the host had it when the board is disposed.\n const unpark = parkTicker(Ticker.system);\n try {\n return await Stage.createParked(host, options, unpark);\n } catch (err) {\n unpark();\n throw err;\n }\n }\n\n private static async createParked(\n host: HTMLElement,\n options: StageOptions,\n unpark: () => void,\n ): Promise<Stage> {\n if (options.cspSafe) await import('pixi.js/unsafe-eval');\n const app = new Application();\n const rect = host.getBoundingClientRect();\n const dpr = window.devicePixelRatio || 1;\n await app.init({\n width: Math.max(1, Math.round(rect.width)),\n height: Math.max(1, Math.round(rect.height)),\n resolution: dpr,\n autoDensity: true,\n antialias: false,\n backgroundColor: (options.theme ?? DARK_THEME).canvas,\n preference: 'webgl',\n powerPreference: 'high-performance',\n autoStart: false,\n sharedTicker: false,\n // Our own LRU owns texture lifetimes; Pixi's idle-time GC would unload atlas pages.\n gcActive: false,\n eventFeatures: { move: false, globalMove: false, click: false, wheel: false },\n });\n Ticker.system.stop();\n app.ticker.stop();\n return new Stage(app, host, options, dpr, unpark);\n }\n\n private constructor(\n app: Application,\n host: HTMLElement,\n options: StageOptions,\n dpr: number,\n private readonly unparkTicker: () => void,\n ) {\n this.app = app;\n this.hostEl = host;\n this.dpr = dpr;\n this.theme = options.theme ?? DARK_THEME;\n this.showGrid = options.grid ?? true;\n this.renderer = app.renderer as WebGLRenderer;\n this.canvas = app.canvas as HTMLCanvasElement;\n this.opts = {\n budgetBytes: options.budgetBytes ?? 256 * 1024 * 1024,\n workers:\n options.workers ??\n Math.max(1, Math.min(4, Math.floor((navigator.hardwareConcurrency || 4) / 4))),\n uploadBudgetMs: options.uploadBudgetMs ?? 4,\n overscan: options.overscan ?? 0.5,\n gpuTimer: options.gpuTimer ?? false,\n softCanvas: options.softCanvas ?? false,\n retireDelay: options.retireDelay,\n };\n host.appendChild(this.canvas);\n this.canvas.style.display = 'block';\n this.canvas.style.touchAction = 'none';\n\n this.ctx = {\n theme: this.theme,\n dpr,\n scale: 1,\n wake: () => this.requestFrame(),\n invalidate: () => {\n this.dirty = true;\n },\n };\n\n this.bg = this.makeBackground();\n this.world = new Container({ isRenderGroup: true });\n this.world.sortableChildren = true;\n this.world.eventMode = 'none';\n this.overlay = new OverlayLayer(this.theme, () => this.requestFrame(), dpr);\n this.bg.eventMode = 'none';\n app.stage.eventMode = 'none';\n app.stage.addChild(this.bg, this.world, this.overlay.container);\n\n this.cam = new CameraController(() => this.requestFrame(), scaleBounds(options));\n this.tm = new TextureManager(this.renderer, {\n budgetBytes: this.opts.budgetBytes,\n workers: this.opts.workers,\n workerUrl: options.workerUrl,\n softCanvas: options.softCanvas,\n border: this.borderCss(),\n retireDelay: this.opts.retireDelay,\n onRetire: () => this.rebuildBatches(),\n onWake: () => this.requestFrame(),\n });\n this.tm.keep = (slot, level) =>\n level === 1\n ? this.slotOnScreen[slot] === 1\n : level === 2\n ? this.slotOwn[slot] >= 2\n : this.slotOwn[slot] === 3;\n if (this.opts.gpuTimer) this.gpu = GpuTimer.create(this.renderer);\n this.applyThemeToScene();\n\n const measure = (): void => {\n const r = host.getBoundingClientRect();\n const empty = Math.round(r.width) < 1 || Math.round(r.height) < 1;\n const w = Math.max(1, Math.round(r.width));\n const h = Math.max(1, Math.round(r.height));\n // Browser zoom resizes the host too: take the pixel ratio along with the size.\n const dprChanged = this.setDpr(window.devicePixelRatio || 1);\n if (!dprChanged && w === this.cam.width && h === this.cam.height && empty === this.cam.isEmpty) {\n return;\n }\n this.renderer.resize(w, h, this.dpr);\n this.bg.width = w;\n this.bg.height = h;\n this.cam.setViewport(w, h, empty);\n this.mountedWin = null;\n this.dirty = true;\n // Resizing clears the drawing buffer: draw it again before the browser paints, or the canvas\n // shows a blank frame for every step of a resize that animates.\n if (ready && !this.lost && !this.disposed) this.render();\n this.requestFrame();\n };\n let ready = false;\n measure();\n ready = true;\n this.ro = new ResizeObserver(measure);\n this.ro.observe(host);\n this.bindContextLoss();\n this.watchDpr();\n this.cleanups.push(() => this.unwatchDpr());\n }\n\n // Adopts a new device pixel ratio (browser zoom, a window dragged to another screen). Returns whether it\n // changed. The LOD levels follow device px, so the cull window and the levels are asked for again.\n private setDpr(dpr: number): boolean {\n if (dpr === this.dpr) return false;\n this.dpr = dpr;\n this.ctx.dpr = dpr;\n this.overlay.setDpr(dpr);\n this.mountedWin = null;\n this.lodDirty = true;\n this.dirty = true;\n return true;\n }\n\n // A media query for the current ratio only fires when it stops matching, so it is armed again for the new\n // value after every change.\n private watchDpr(): void {\n this.unwatchDpr();\n if (typeof matchMedia !== 'function') return;\n const mq = matchMedia(`(resolution: ${this.dpr}dppx)`);\n mq.addEventListener('change', this.onDprChange);\n this.dprQuery = mq;\n }\n\n private unwatchDpr(): void {\n this.dprQuery?.removeEventListener('change', this.onDprChange);\n this.dprQuery = null;\n }\n\n private onDprChange = (): void => {\n if (this.disposed) return;\n const changed = this.setDpr(window.devicePixelRatio || 1);\n this.watchDpr();\n if (!changed) return;\n this.renderer.resize(this.cam.width, this.cam.height, this.dpr);\n // Resizing clears the drawing buffer (see `measure`).\n if (!this.lost) this.render();\n this.requestFrame();\n };\n\n get activeTheme(): Theme {\n return this.theme;\n }\n\n get canvasEl(): HTMLCanvasElement {\n return this.canvas;\n }\n\n // ── Store ──────────────────────────────────────────────────────────────────\n attach(store: StageStore): void {\n this.detach();\n this.store = store;\n this.unsub = store.subscribe((e) => this.onStoreEvent(e));\n this.reloadAll();\n }\n\n detach(): void {\n this.unsub?.();\n this.unsub = null;\n this.store = null;\n this.clearViews();\n }\n\n private onStoreEvent(e: StoreEvent): void {\n if (e.type !== 'change') return;\n const c: ChangeSet = e.change;\n if (c.source === 'load') {\n // A full reload: rebuild from the store at the next tick.\n this.pendingReload = true;\n this.requestFrame();\n return;\n }\n for (const el of c.removed) {\n this.pendingAdded.delete(el.id);\n this.pendingUpdated.delete(el.id);\n this.pendingRemoved.set(el.id, el);\n }\n // An id removed and added again before the tick keeps its pending removal: the flush unmounts the old\n // view (and frees its slot) before it mounts the new element, so none of the old geometry or picture\n // survives into the new card.\n for (const el of c.added) this.pendingAdded.add(el.id);\n for (const u of c.updated) {\n if (this.pendingAdded.has(u.el.id)) continue;\n let set = this.pendingUpdated.get(u.el.id);\n if (!set) {\n set = new Set();\n this.pendingUpdated.set(u.el.id, set);\n }\n for (const p of u.props) set.add(p);\n }\n this.requestFrame();\n }\n\n // Applies the store changes that arrived since the last tick.\n private flushStore(): boolean {\n const store = this.store;\n if (!store) return false;\n let changed = false;\n if (this.pendingReload) {\n this.pendingReload = false;\n this.pendingAdded.clear();\n this.pendingRemoved.clear();\n this.pendingUpdated.clear();\n this.reloadAll();\n return true;\n }\n if (this.pendingRemoved.size > 0) {\n for (const [id, el] of this.pendingRemoved) {\n this.unmountId(id);\n if (definitionOf(el.kind).textured) this.freeSlot(id);\n this.previews.delete(id);\n this.hidden.delete(id);\n this.alphas.delete(id);\n this.pinned.delete(id);\n this.posters.delete(id);\n }\n this.pendingRemoved.clear();\n changed = true;\n }\n const win = this.mountedWin;\n if (this.pendingAdded.size > 0) {\n // Before the first cull pass there is no window to test against: the adds wait in the mount queue,\n // which that pass (this same tick) filters, rather than all getting a view.\n const view = win ? null : this.cam.visibleRect();\n for (const id of this.pendingAdded) {\n const el = store.get(id);\n if (!el || this.views.has(id)) continue;\n if (definitionOf(el.kind).textured) this.allocSlot(id);\n if (this.forceMount(id) || (win && this.inWindow(el, win))) {\n this.mount(el);\n changed = true;\n } else if (view) {\n this.enqueueMount(el, (view.x0 + view.x1) / 2, (view.y0 + view.y1) / 2);\n }\n }\n this.pendingAdded.clear();\n this.lodDirty = true;\n this.l0Missing = Math.max(this.l0Missing, 1);\n }\n if (this.pendingUpdated.size > 0) {\n for (const [id, props] of this.pendingUpdated) {\n const el = store.get(id);\n if (!el) continue;\n const view = this.views.get(id);\n if (!view) {\n if (win && this.inWindow(el, win)) {\n this.mount(el);\n changed = true;\n } else {\n // Not mounted, but its slot may hold a card (and textures) of the old media.\n this.syncSlot(id, el);\n }\n continue;\n }\n if (props.has('kind') || definitionOf(el.kind).variant !== view.variant) {\n this.unmountId(id);\n if (definitionOf(el.kind).textured) this.allocSlot(id);\n else this.freeSlot(id);\n this.mount(el);\n } else {\n view.update(el, [...props], this.rectOf(el), this.ctx);\n if (view instanceof MediaView) this.syncCard(view, el);\n this.applyOverrides(id, view);\n }\n changed = true;\n }\n this.pendingUpdated.clear();\n this.lodDirty = true;\n }\n if (store.orderVersion !== this.orderSeen) {\n this.orderSeen = store.orderVersion;\n for (const [id, v] of this.views) v.display.zIndex = store.rank(id);\n changed = true;\n }\n return changed;\n }\n\n // The store was replaced wholesale (first load, `load()`): reconcile the views, slots and textures with\n // it. Textures of cards that are still there stay resident.\n private reloadAll(): void {\n const store = this.store;\n if (!store) return;\n const first = this.views.size === 0 && this.slotOf.size === 0;\n for (const [id, view] of [...this.views]) {\n const el = store.get(id);\n if (!el || el.kind !== view.kind) this.unmountId(id);\n }\n for (const id of [...this.slotOf.keys()]) {\n const el = store.get(id);\n if (!el || !definitionOf(el.kind).textured) this.freeSlot(id);\n }\n for (const id of [...this.posters.keys()]) if (!store.get(id)) this.posters.delete(id);\n for (const el of store.elements()) if (definitionOf(el.kind).textured) this.allocSlot(el.id);\n const all = ['x', 'y', 'w', 'h', 'rot', 'locked', 'media', 'radius'];\n for (const [id, view] of [...this.views]) {\n const el = store.get(id) as Element;\n view.update(el, all, this.rectOf(el), this.ctx);\n if (view instanceof MediaView) this.syncCard(view, el);\n }\n // Slots without a view keep their cards across a reload too: the new store may hold other media.\n for (const [id, slot] of this.slotOf) {\n if (!this.slotView[slot]) this.syncSlot(id, store.get(id) as Element);\n }\n if (first) {\n this.t0 = performance.now();\n this.firstPaintMs = null;\n this.l1CompleteMs = null;\n }\n this.l0Missing = Math.max(this.slotOf.size, this.l0Missing);\n this.mountedWin = null;\n this.orderSeen = -1;\n this.dirty = true;\n this.lodDirty = true;\n this.requestFrame();\n }\n\n private clearViews(): void {\n this.mountQueue.length = 0;\n this.queued.clear();\n for (const id of [...this.views.keys()]) this.unmountId(id);\n this.views.clear();\n this.mediaViews.clear();\n }\n\n // ── Cards: slots and media ─────────────────────────────────────────────────\n private allocSlot(id: ElementId): number {\n let s = this.slotOf.get(id);\n if (s !== undefined) return s;\n s = this.freeSlots.pop() ?? this.slotCount++;\n this.slotOf.set(id, s);\n if (s >= this.slotLevel.length) this.growSlots(s + 1);\n this.slotLevel[s] = -1;\n this.slotOnScreen[s] = 0;\n this.slotOwn[s] = 0;\n this.slotBaked[s] = 0;\n this.slotBakedAspect[s] = 0;\n this.slotCard[s] = null;\n this.slotView[s] = null;\n return s;\n }\n\n private growSlots(min: number): void {\n let n = this.slotLevel.length;\n while (n < min) n *= 2;\n const lv = new Int8Array(n);\n lv.set(this.slotLevel);\n const on = new Uint8Array(n);\n on.set(this.slotOnScreen);\n const own = new Uint8Array(n);\n own.set(this.slotOwn);\n const baked = new Float32Array(n);\n baked.set(this.slotBaked);\n const bakedAspect = new Float32Array(n);\n bakedAspect.set(this.slotBakedAspect);\n this.slotLevel = lv;\n this.slotOnScreen = on;\n this.slotOwn = own;\n this.slotBaked = baked;\n this.slotBakedAspect = bakedAspect;\n }\n\n private freeSlot(id: ElementId): void {\n const s = this.slotOf.get(id);\n if (s === undefined) return;\n this.slotOf.delete(id);\n this.slotCard[s] = null;\n this.slotView[s] = null;\n this.tm.forget(s);\n this.freeSlots.push(s);\n }\n\n private hashOf(h: Uint8Array | string | undefined): Uint8Array | undefined {\n if (h === undefined) return undefined;\n if (typeof h !== 'string') return h;\n let b = this.hashCache.get(h);\n if (!b) {\n try {\n b = decodeBase64(h);\n } catch {\n return undefined;\n }\n this.hashCache.set(h, b);\n }\n return b;\n }\n\n private fillCard(card: BoardCard, el: Element): void {\n const m = el.media;\n card.w = el.w;\n card.h = el.h;\n card.thumbhash = this.hashOf(m.thumbhash);\n [card.l1Url, card.l2Url, card.l3Url] = this.urlsOf(el);\n card.radius = el.radius;\n }\n\n // The renditions a card requests: its poster override when it has one, else the element's own. A missing\n // rendition falls back to the picture itself: the decode worker downsamples it.\n private urlsOf(el: Element): [string | undefined, string | undefined, string | undefined] {\n const o = this.posters.get(el.id);\n if (o !== undefined) return [o, o, o];\n const m = el.media;\n return [m.sizes?.small ?? m.src, m.sizes?.medium ?? m.src, m.sizes?.large ?? m.src];\n }\n\n private newCard(slot: number, el: Element): BoardCard {\n const card: BoardCard = {\n id: slot,\n w: el.w,\n h: el.h,\n thumbhash: undefined,\n l1Url: undefined,\n l2Url: undefined,\n l3Url: undefined,\n radius: DEFAULTS.cardRadius,\n };\n this.fillCard(card, el);\n this.slotBaked[slot] = Math.max(el.w, el.h);\n this.slotBakedAspect[slot] = el.w > 0 ? el.h / el.w : 0;\n return card;\n }\n\n private mountMedia(view: MediaView, el: Element): void {\n const slot = this.allocSlot(el.id);\n let card = this.slotCard[slot];\n if (!card) {\n card = this.newCard(slot, el);\n this.slotCard[slot] = card;\n } else this.refreshCard(card, el);\n view.card = card;\n this.slotView[slot] = view;\n this.mediaViews.add(view);\n }\n\n // Brings a slot's BoardCard up to date with its element and returns whether what is resident for it went\n // stale (and was forgotten). A rendition URL or ThumbHash that CHANGED (not just appeared) means another\n // picture; a different corner radius, or a long side so far from the size the textures were baked at that\n // the corners drawn are off by more than BAKE_CORNER_SLACK, means the baked rounded corners no longer fit;\n // and a height / width ratio that moved by more than BAKE_ASPECT_SLACK means the textures were cropped\n // (cover) to another shape.\n // Only committed store changes get here: a live drag / resize preview never touches the card.\n private refreshCard(card: BoardCard, el: Element): boolean {\n const m = el.media;\n const [l1, l2, l3] = this.urlsOf(el);\n const long = Math.max(el.w, el.h);\n const baked = this.slotBaked[card.id];\n const aspect = el.w > 0 ? el.h / el.w : 0;\n const bakedAspect = this.slotBakedAspect[card.id];\n const stale =\n (card.l1Url !== undefined && card.l1Url !== l1) ||\n (card.l2Url !== undefined && card.l2Url !== l2) ||\n (card.l3Url !== undefined && card.l3Url !== l3) ||\n (card.thumbhash !== undefined && !sameBytes(card.thumbhash, this.hashOf(m.thumbhash))) ||\n card.radius !== el.radius ||\n (baked > 0 && (el.radius * Math.abs(long - baked)) / baked > BAKE_CORNER_SLACK) ||\n (bakedAspect > 0 && Math.abs(aspect - bakedAspect) / bakedAspect > BAKE_ASPECT_SLACK);\n this.fillCard(card, el);\n if (stale) {\n this.tm.forget(card.id);\n this.slotLevel[card.id] = -1;\n this.slotBaked[card.id] = long;\n this.slotBakedAspect[card.id] = aspect;\n this.l0Missing++;\n }\n return stale;\n }\n\n // The element's size or media changed: keep the BoardCard current, and show the placeholder again when\n // what was resident went stale.\n private syncCard(view: MediaView, el: Element): void {\n const card = view.card;\n if (card && this.refreshCard(card, el)) view.setTexture(null, -1, this.ctx);\n }\n\n // A runtime picture for an element, used in place of its `media.src` / `sizes` and never written to the\n // store (a generated tile, a snapshot of a live page: blob URLs that die with the page). null: back to the\n // element's own. Dropped when the element is removed. The change swaps the card's pictures without the\n // placeholder in between: what is resident stays on screen until the first level of the new one lands\n // (TextureManager.swapPictures), so a poster that replaces a poster never flashes.\n setPosterOverride(id: ElementId, url: string | null): void {\n if ((this.posters.get(id) ?? null) === url) return;\n if (url === null) this.posters.delete(id);\n else this.posters.set(id, url);\n const slot = this.slotOf.get(id);\n const card = slot === undefined ? null : this.slotCard[slot];\n const el = this.store?.get(id);\n // No card yet: it is built from the override when it is.\n if (slot === undefined || !card || !el) return;\n const [l1, l2, l3] = this.urlsOf(el);\n if (card.l1Url === l1 && card.l2Url === l2 && card.l3Url === l3) return;\n card.l1Url = l1;\n card.l2Url = l2;\n card.l3Url = l3;\n const view = this.slotView[slot];\n // Nothing to swap to (the override went and the element has no picture of its own), or nobody looking.\n this.tm.swapPictures(card.id, view !== null && l1 !== undefined);\n if (view && this.paintMedia(view)) this.dirty = true;\n this.lodDirty = true;\n this.requestFrame();\n }\n\n // The card's sprite shows a rendition of its current picture: not the placeholder, not the ThumbHash and not\n // what a poster override replaced (still on screen while the new one decodes).\n posterShown(id: ElementId): boolean {\n const v = this.views.get(id);\n return v instanceof MediaView && v.card !== null && v.shown >= 1 && !this.tm.hasOutgoing(v.card);\n }\n\n // The same for a slot that has no view (the element is off screen): its card, and the textures its ThumbHash\n // and thumbnails already got, must not outlive a change of media.\n private syncSlot(id: ElementId, el: Element): void {\n const slot = this.slotOf.get(id);\n const card = slot === undefined ? null : this.slotCard[slot];\n if (card) this.refreshCard(card, el);\n }\n\n // ── Views ──────────────────────────────────────────────────────────────────\n // The committed world rect of an element (or its live preview).\n private rectOf(el: Element): WorldRect {\n return this.previews.get(el.id) ?? worldRectOf(el);\n }\n\n private forceMount(id: ElementId): boolean {\n return this.pinned.has(id) || this.previews.has(id);\n }\n\n private inWindow(el: Element, win: Rect): boolean {\n const b = elementBox(el);\n return b.minX <= win.x1 && b.maxX >= win.x0 && b.minY <= win.y1 && b.maxY >= win.y0;\n }\n\n // Puts an element in the mount queue, ordered by its distance from the view centre (cx, cy).\n private enqueueMount(el: Element, cx: number, cy: number): void {\n if (this.queued.has(el.id)) return;\n const b = elementBox(el);\n const d = Math.hypot((b.minX + b.maxX) / 2 - cx, (b.minY + b.maxY) / 2 - cy);\n this.mountQueue.push({ id: el.id, key: d });\n this.queued.add(el.id);\n this.queueSorted = false;\n }\n\n // Creates the views of queued elements until the tick's budget is spent. Anything that left the window\n // meanwhile (a fast pan) is dropped without ever being built.\n private drainMounts(): void {\n const q = this.mountQueue;\n const store = this.store;\n if (q.length === 0 || !store) return;\n if (!this.queueSorted) {\n // Descending, so pop() hands out the nearest first.\n q.sort((a, b) => b.key - a.key);\n this.queueSorted = true;\n }\n const t0 = performance.now();\n const win = this.mountedWin;\n let n = 0;\n while (q.length > 0) {\n const it = q.pop() as { id: ElementId; key: number };\n this.queued.delete(it.id);\n const el = store.get(it.id);\n if (!el || this.views.has(it.id)) continue;\n if (win && !this.forceMount(it.id) && !this.inWindow(el, win)) continue;\n this.mount(el);\n n++;\n if (performance.now() - t0 >= MOUNT_BUDGET_MS) break;\n }\n if (n > 0) {\n this.dirty = true;\n this.lodDirty = true;\n }\n }\n\n private mount(el: Element): void {\n const store = this.store as StageStore;\n const view = this.pools.acquire(el.kind);\n view.mark = this.stamp;\n this.ctx.scale = this.cam.scale;\n if (view instanceof MediaView) this.mountMedia(view, el);\n view.mount(el, this.rectOf(el), this.ctx);\n view.display.zIndex = store.rank(el.id);\n this.views.set(el.id, view);\n if (view instanceof MediaView) this.paintMedia(view);\n this.applyOverrides(el.id, view);\n this.world.addChild(view.display);\n this.counters.mounts++;\n }\n\n private unmountId(id: ElementId): void {\n const view = this.views.get(id);\n if (!view) return;\n this.views.delete(id);\n this.world.removeChild(view.display);\n view.setAlphaOverride(1);\n view.display.visible = true;\n if (view instanceof MediaView) {\n const s = view.card?.id;\n if (s !== undefined) {\n this.slotOnScreen[s] = 0;\n this.slotOwn[s] = 0;\n this.slotView[s] = null;\n }\n this.mediaViews.delete(view);\n }\n view.unmount();\n this.pools.release(view);\n this.counters.unmounts++;\n }\n\n private applyOverrides(id: ElementId, view: ElementView): void {\n view.setAlphaOverride(this.alphas.get(id) ?? 1);\n view.display.visible = !this.hidden.has(id);\n const p = this.previews.get(id);\n if (p) view.setRect(p);\n }\n\n // ── Overrides (set by the interaction layer) ───────────────────────────────\n // A drag / resize preview: the element is drawn at this rect (world space) without touching the\n // store. Call every pointer move; cheap for a few hundred elements.\n setPreview(id: ElementId, x: number, y: number, w: number, h: number, rot: number): void {\n // A fresh rect on every call, never the previous one rewritten: a view keeps the rect it was last given.\n const p: PreviewRect = { x, y, w, h, rot };\n const fresh = !this.previews.has(id);\n this.previews.set(id, p);\n if (fresh) {\n const el = this.store?.get(id);\n if (el && !this.views.has(id)) this.mount(el);\n }\n const v = this.views.get(id);\n if (v) v.setRect(p);\n this.dirty = true;\n this.requestFrame();\n }\n\n clearPreview(id: ElementId): void {\n const p = this.previews.get(id);\n if (!p) return;\n this.previews.delete(id);\n const el = this.store?.get(id);\n const v = this.views.get(id);\n if (el && v) {\n v.update(el, ['x', 'y', 'w', 'h', 'rot'], this.rectOf(el), this.ctx);\n if (v instanceof MediaView) this.syncCard(v, el);\n }\n this.dirty = true;\n this.requestFrame();\n }\n\n clearPreviews(): void {\n for (const id of [...this.previews.keys()]) this.clearPreview(id);\n }\n\n previewRectOf(id: ElementId): PreviewRect | undefined {\n return this.previews.get(id);\n }\n\n get previewCount(): number {\n return this.previews.size;\n }\n\n // Hides the canvas copy of an element.\n setHidden(id: ElementId, hidden: boolean): void {\n if (hidden) this.hidden.add(id);\n else this.hidden.delete(id);\n const v = this.views.get(id);\n if (v) v.display.visible = !hidden;\n this.dirty = true;\n this.requestFrame();\n }\n\n setAlpha(id: ElementId, alpha: number | null): void {\n if (alpha === null || alpha >= 1) this.alphas.delete(id);\n else this.alphas.set(id, alpha);\n const v = this.views.get(id);\n if (v) v.setAlphaOverride(alpha ?? 1);\n this.dirty = true;\n this.requestFrame();\n }\n\n // Keeps an element mounted whatever the window says.\n pin(id: ElementId, pinned: boolean): void {\n if (pinned) {\n this.pinned.add(id);\n const el = this.store?.get(id);\n if (el && !this.views.has(id)) this.mount(el);\n } else this.pinned.delete(id);\n }\n\n // The view of a mounted element (animations, tests); null when not mounted.\n viewOf(id: ElementId): ElementView | null {\n return this.views.get(id) ?? null;\n }\n\n isMounted(id: ElementId): boolean {\n return this.views.has(id);\n }\n\n // ── Camera and coordinates ─────────────────────────────────────────────────\n screenToWorld(sx: number, sy: number): { x: number; y: number } {\n const c = this.cam.cam;\n return { x: (sx - c.tx) / c.scale, y: (sy - c.ty) / c.scale };\n }\n\n worldToScreen(wx: number, wy: number): { x: number; y: number } {\n const c = this.cam.cam;\n return { x: c.tx + wx * c.scale, y: c.ty + wy * c.scale };\n }\n\n // Page (client) coordinates -> host-local screen coordinates.\n clientToLocal(cx: number, cy: number): { x: number; y: number } {\n const r = this.hostEl.getBoundingClientRect();\n return { x: cx - r.left, y: cy - r.top };\n }\n\n get dprValue(): number {\n return this.dpr;\n }\n\n contentBounds(ids?: Iterable<ElementId>): Rect {\n const store = this.store;\n let b = emptyBox();\n let any = false;\n if (store) {\n const list: Iterable<Element | undefined> = ids\n ? (function* () {\n for (const id of ids) yield store.get(id);\n })()\n : store.elements();\n for (const el of list) {\n if (!el) continue;\n const eb = elementBox(el);\n b = {\n minX: Math.min(b.minX, eb.minX),\n minY: Math.min(b.minY, eb.minY),\n maxX: Math.max(b.maxX, eb.maxX),\n maxY: Math.max(b.maxY, eb.maxY),\n };\n any = true;\n }\n }\n if (any) return { x0: b.minX, y0: b.minY, x1: b.maxX, y1: b.maxY };\n // Nothing resolved: a unit rect at the origin (the public shape), remembered as \"no content\" so a fit\n // of it does nothing.\n const none = { x0: 0, y0: 0, x1: 1, y1: 1 };\n noContent.add(none);\n return none;\n }\n\n fit(animate = true, pad = 48): void {\n this.cam.requestFit(this.fitTarget(() => this.contentBounds()), pad, animate);\n }\n\n // `r` may be a function: it is read when the fit is applied (a fit asked for on a host that has no size\n // yet waits for the first real size).\n fitRect(r: Rect | (() => Rect), animate = true, pad = 48): void {\n this.cam.requestFit(this.fitTarget(r), pad, animate, 440);\n }\n\n // What a fit reads: the rect, or null for the \"no content\" rect of `contentBounds` (an empty board, ids\n // that match no card), which leaves the camera alone.\n private fitTarget(r: Rect | (() => Rect)): () => Rect | null {\n return () => {\n const rect = typeof r === 'function' ? r() : r;\n return noContent.has(rect) ? null : rect;\n };\n }\n\n zoomToActual(): void {\n this.cam.zoomToActual();\n }\n\n setCamera(c: Camera): void {\n this.cam.jumpTo(c);\n }\n\n zoomBy(k: number): void {\n const cam = this.cam.cam;\n const cx = this.cam.width / 2;\n const cy = this.cam.height / 2;\n const s = Math.min(this.cam.maxScale, Math.max(this.cam.minScale, cam.scale * k));\n const z = {\n scale: s,\n tx: cx - (cx - cam.tx) * (s / cam.scale),\n ty: cy - (cy - cam.ty) * (s / cam.scale),\n };\n this.cam.flyTo(z, 220);\n }\n\n // ── Theme ──────────────────────────────────────────────────────────────────\n setTheme(theme: Theme): void {\n const borderChanged =\n theme.border !== this.theme.border || theme.borderAlpha !== this.theme.borderAlpha;\n this.theme = theme;\n this.ctx.theme = theme;\n this.applyThemeToScene();\n // The dots' opacity is the theme's (derived with the camera), not only the tint.\n this.applyCamera();\n this.overlay.setTheme(theme);\n for (const v of this.views.values()) v.refresh(this.ctx);\n if (borderChanged) {\n // The hairline is baked into every texture: rebuild them.\n this.tm.setBorder(this.borderCss());\n this.dropAllTextures();\n }\n this.dirty = true;\n this.requestFrame();\n }\n\n setGrid(on: boolean): void {\n this.showGrid = on;\n this.applyCamera();\n this.dirty = true;\n this.requestFrame();\n }\n\n private borderCss(): string {\n const t = this.theme;\n const r = (t.border >> 16) & 255;\n const g = (t.border >> 8) & 255;\n const b = t.border & 255;\n return `rgba(${r},${g},${b},${t.borderAlpha})`;\n }\n\n private applyThemeToScene(): void {\n this.app.renderer.background.color = this.theme.canvas;\n this.bg.tint = this.theme.dot;\n }\n\n // ── Loop ───────────────────────────────────────────────────────────────────\n requestFrame(): void {\n if (this.raf || this.disposed) return;\n if (this.settleTimer) {\n clearTimeout(this.settleTimer);\n this.settleTimer = 0;\n }\n this.counters.rafCalls++;\n this.raf = requestAnimationFrame(this.tick);\n }\n\n // Runs at the start of every tick (the input controller flushes coalesced pointer moves here, so a\n // drag preview and its render share one frame).\n onBeforeFrame(hook: () => void): () => void {\n this.beforeHooks.push(hook);\n return () => {\n this.beforeHooks = this.beforeHooks.filter((h) => h !== hook);\n };\n }\n\n // Forces Pixi to rebuild the world's batches at the next render (see retire.ts): a batch keeps listing\n // a texture its sprites stopped using, and we are about to destroy it.\n private rebuildBatches(): void {\n const rg = (this.world as unknown as { renderGroup?: { structureDidChange: boolean } })\n .renderGroup;\n if (rg) rg.structureDidChange = true;\n this.dirty = true;\n }\n\n // DOM overlays (the video layer) sync from here, in the same rAF as the render.\n onFrame(hook: (camChanged: boolean) => void): () => void {\n this.frameHooks.push(hook);\n return () => {\n this.frameHooks = this.frameHooks.filter((h) => h !== hook);\n };\n }\n\n // Runs once the camera has been still for SETTLE_MS (the exact pass is done).\n onSettle(hook: () => void): () => void {\n this.settleHooks.push(hook);\n return () => {\n this.settleHooks = this.settleHooks.filter((h) => h !== hook);\n };\n }\n\n markDirty(): void {\n this.dirty = true;\n this.requestFrame();\n }\n\n private tick = (ts: number): void => {\n this.raf = 0;\n if (this.disposed) return;\n const t0 = performance.now();\n this.counters.ticks++;\n const dt = this.lastTs ? Math.min(50, ts - this.lastTs) : 16.7;\n this.lastTs = ts;\n for (const h of this.beforeHooks) this.runHook(h);\n const camBusy = this.cam.step(dt);\n let dirty = this.dirty;\n this.dirty = false;\n let camChanged = false;\n this.ctx.scale = this.cam.scale;\n\n const ph = this.phase;\n ph.store = ph.camera = ph.upload = ph.overlay = ph.render = 0;\n let tp = performance.now();\n const lap = (k: 'store' | 'camera' | 'upload' | 'overlay' | 'render'): void => {\n const n = performance.now();\n ph[k] = n - tp;\n tp = n;\n };\n try {\n this.where = 'store';\n if (this.flushStore()) dirty = true;\n lap('store');\n this.where = 'camera';\n if (this.cam.version !== this.renderedVersion) {\n this.renderedVersion = this.cam.version;\n this.applyCamera();\n dirty = true;\n camChanged = true;\n // No window yet (first tick, a resize): the mount queue needs one before it drains.\n if (t0 - this.lastLod >= LOD_INTERVAL_MS || this.mountedWin === null) {\n this.cullAndLod(t0, false);\n }\n } else if (this.lodDirty) {\n this.cullAndLod(t0, false);\n }\n this.drainMounts();\n // View-level changes made by the LOD pass (placeholder repaints) need a render too.\n if (this.dirty) {\n dirty = true;\n this.dirty = false;\n }\n lap('camera');\n this.where = 'upload';\n if (!this.lost) {\n const changed = this.tm.frame(this.opts.uploadBudgetMs, t0);\n if (changed.length > 0) {\n for (const slot of changed) this.applySlot(slot);\n dirty = true;\n }\n if (this.repointEvicted()) dirty = true;\n }\n lap('upload');\n this.where = 'overlay';\n if (this.overlay.draw(this.cam.cam)) dirty = true;\n lap('overlay');\n this.where = 'hooks';\n // A hook is host / layer code: a throw there says nothing about the textures, so it is reported on\n // its own and never reaches `recoverTextures`.\n for (const h of this.frameHooks) this.runHook(h, camChanged);\n this.where = 'render';\n if (dirty && !this.lost) {\n this.render();\n lap('render');\n this.tm.afterRender();\n this.rendersSinceRetire++;\n }\n this.where = 'idle';\n } catch (e) {\n this.recoverTextures(e);\n }\n this.trackProgress(t0);\n\n const ms = performance.now() - t0;\n this.tickMs[this.nTick++ & 4095] = ms;\n if (ms > 25) {\n // The slowest frames, with where the time went (read through stats().slowTicks).\n this.slowTicks.push({\n ms: r2(ms),\n scale: r2(this.cam.scale),\n mounted: this.views.size,\n mounts: this.counters.mounts,\n ...Object.fromEntries(Object.entries(ph).map(([k, v]) => [k, r2(v)])),\n });\n if (this.slowTicks.length > 40) this.slowTicks.shift();\n }\n\n if (camBusy || this.uploadsPending() || this.lodDirty || this.dirty || this.mountQueue.length > 0) {\n this.requestFrame();\n } else {\n // Parked: no rAF until the next input or decode. One timer runs the exact cull + LOD pass\n // once the camera has been still for SETTLE_MS.\n this.lastTs = 0;\n this.settleTimer = window.setTimeout(this.settle, SETTLE_MS);\n }\n };\n\n private settle = (): void => {\n this.settleTimer = 0;\n if (this.disposed) return;\n this.cullAndLod(performance.now(), true);\n // Everything retired has been through at least one render by now.\n this.tm.flushRetired();\n for (const h of this.settleHooks) this.runHook(h);\n if (this.dirty || this.uploadsPending() || this.mountQueue.length > 0) {\n this.requestFrame();\n }\n };\n\n // Decoded bitmaps wait for the upload step. While the GL context is lost that step is skipped, so they\n // cannot keep the loop spinning: the restore (`dropAllTextures`) starts it again.\n private uploadsPending(): boolean {\n return this.tm.pendingWork && !this.lost;\n }\n\n // Runs a hook so that one that throws neither stops the others nor the loop. Reported once per hook\n // (console), counted every time (`hookErrors` in the stats).\n private runHook(hook: (arg: boolean) => void, arg = false): void {\n try {\n hook(arg);\n } catch (e) {\n this.counters.hookErrors++;\n if (this.reportedHooks.has(hook)) return;\n this.reportedHooks.add(hook);\n console.error('[corkboard] a hook threw (reported once per hook):', e);\n }\n }\n\n private render(): void {\n const t = performance.now();\n this.gpu?.begin();\n this.app.render();\n this.gpu?.end();\n this.renderMs[this.nRender++ & 4095] = performance.now() - t;\n this.counters.renders++;\n if (this.gpu) {\n for (const ms of this.gpu.poll()) this.gpuMs[this.nGpu++ & 4095] = ms;\n }\n }\n\n private applyCamera(): void {\n const { tx, ty, scale } = this.cam.cam;\n this.world.position.set(tx, ty);\n this.world.scale.set(scale);\n // Background dots: a screen-space tiling sprite following the camera; hidden below 25 % zoom.\n const a = Math.max(0, Math.min(1, (scale - 0.25) / 0.15));\n this.bg.visible = this.showGrid && a > 0;\n if (this.bg.visible) {\n this.bg.alpha = a * (this.theme.dotAlpha ?? 0.0805);\n const k = (scale * GRID) / 64;\n this.bg.tileScale.set(k);\n this.bg.tilePosition.set(tx - (GRID / 2) * scale, ty - (GRID / 2) * scale);\n }\n }\n\n // ── Culling + LOD ──────────────────────────────────────────────────────────\n private cullAndLod(now: number, settled: boolean): void {\n this.lodDirty = false;\n if (!this.store || this.cam.width === 0) return;\n this.lastLod = now;\n this.counters.cullPasses++;\n const view = this.cam.visibleRect();\n const scale = this.cam.scale;\n const covered =\n this.mountedWin !== null &&\n view.x0 >= this.mountedWin.x0 &&\n view.y0 >= this.mountedWin.y0 &&\n view.x1 <= this.mountedWin.x1 &&\n view.y1 <= this.mountedWin.y1 &&\n scale / this.mountedScale < 1.5 &&\n scale / this.mountedScale > 1 / 1.5;\n if (!covered || settled) this.requery(view, scale);\n this.lodPass(now, view, scale);\n this.lodPassMs[this.nLodPass++ & 1023] = performance.now() - now;\n }\n\n private requery(view: Rect, scale: number): void {\n const store = this.store as StageStore;\n this.counters.requeries++;\n const padX = (view.x1 - view.x0) * this.opts.overscan;\n const padY = (view.y1 - view.y0) * this.opts.overscan;\n const win: Rect = {\n x0: view.x0 - padX,\n y0: view.y0 - padY,\n x1: view.x1 + padX,\n y1: view.y1 + padY,\n };\n const tS = performance.now();\n const hits = store.searchInto(\n { minX: win.x0, minY: win.y0, maxX: win.x1, maxY: win.y1 },\n this.hits,\n );\n this.reqMs.search += performance.now() - tS;\n const tM = performance.now();\n const stamp = ++this.stamp;\n let entered = 0;\n let left = 0;\n let already = 0;\n const cx = (view.x0 + view.x1) / 2;\n const cy = (view.y0 + view.y1) / 2;\n for (let i = 0; i < hits.length; i++) {\n const el = hits[i];\n const v = this.views.get(el.id);\n if (v) {\n v.mark = stamp;\n already++;\n } else if (!this.queued.has(el.id)) {\n this.enqueueMount(el, cx, cy);\n entered++;\n }\n }\n this.reqMs.mount += performance.now() - tM;\n const tU = performance.now();\n // More mounted than hit means some are stale (and the pinned / previewed ones stay).\n if (this.views.size !== already) {\n for (const [id, v] of this.views) {\n if (v.mark !== stamp && !this.forceMount(id)) {\n this.unmountId(id);\n left++;\n }\n }\n }\n this.reqMs.unmount += performance.now() - tU;\n this.hits.length = 0;\n this.mountedWin = win;\n this.mountedScale = scale;\n if (entered > 0 || left > 0) this.dirty = true;\n }\n\n // Points a card's sprite at the best resident texture for its wanted level.\n private paintMedia(view: MediaView): boolean {\n const card = view.card;\n if (!card) return false;\n const want = Math.max(0, this.slotLevel[card.id]) as Level;\n const b = this.tm.best(card, want);\n return view.setTexture(b ? b.tex : null, b ? b.level : -1, this.ctx);\n }\n\n private applySlot(slot: number): boolean {\n const v = this.slotView[slot];\n return v ? this.paintMedia(v) : false;\n }\n\n private lodPass(now: number, view: Rect, scale: number): void {\n this.counters.lodPasses++;\n this.ctx.scale = scale;\n const k = scale * this.dpr;\n const cx = (view.x0 + view.x1) / 2;\n const cy = (view.y0 + view.y1) / 2;\n const wanted: WantedItem[] = [];\n const tm = this.tm;\n let l0Missing = 0;\n let changed = false;\n // Texture memory follows what is ON SCREEN, not what is mounted: the overscan ring exists so a pan\n // finds sprites already there (with a thumbnail), but only cards touching the viewport (plus a\n // small margin) get an own texture and are protected from eviction.\n const mx = (view.x1 - view.x0) * VIEW_MARGIN;\n const my = (view.y1 - view.y0) * VIEW_MARGIN;\n const l3: { slot: number; dist: number; d: number }[] = [];\n const room = tm.hasHeadroom();\n for (const v of this.mediaViews) {\n const card = v.card;\n const el = v.el;\n if (!card || !el) continue;\n const slot = card.id;\n const d = Math.max(el.w, el.h) * k;\n const prev = this.slotLevel[slot];\n let lvl = pickLevel(d, prev < 0 ? null : (prev as Level));\n // With no ThumbHash there is no L0 to show: the small rendition is the first level.\n if (lvl === 0 && !card.thumbhash) lvl = 1;\n const r = this.rectOf(el);\n const onScreen =\n r.x < view.x1 + mx &&\n r.x + r.w > view.x0 - mx &&\n r.y < view.y1 + my &&\n r.y + r.h > view.y0 - my;\n const dist = Math.hypot(r.x + r.w / 2 - cx, r.y + r.h / 2 - cy) * scale;\n // The old picture of a swapped poster is only worth keeping while the card shows (and asks for) the new.\n if ((lvl === 0 || !onScreen) && tm.hasOutgoing(card)) tm.dropOutgoing(card);\n if (lvl === 3) {\n if (onScreen) l3.push({ slot, dist, d });\n lvl = 2;\n }\n this.slotLevel[slot] = lvl;\n this.slotOnScreen[slot] = onScreen ? 1 : 0;\n this.slotOwn[slot] = onScreen && lvl >= 2 ? lvl : 0;\n if (onScreen) tm.touch(card, now, lvl >= 2);\n if (card.thumbhash && !tm.has(card, 0)) {\n wanted.push({ card, level: 0, dist });\n l0Missing++;\n }\n // L1 is also the stopgap while an L2 is on its way. A card off screen only gets one while there is\n // room: past the budget the eviction pass would drop it again and the loop would never park.\n if (lvl >= 1 && !tm.has(card, 1) && (onScreen || room)) wanted.push({ card, level: 1, dist });\n if (lvl === 2 && onScreen) wanted.push({ card, level: 2, dist, bucket: l2Bucket(d) });\n }\n // At most MAX_L3 cards (the nearest to the view centre) get the large rendition.\n if (l3.length > 0) {\n l3.sort((a, b) => a.dist - b.dist);\n for (let i = 0; i < l3.length; i++) {\n const { slot, dist, d } = l3[i];\n const card = this.slotCard[slot] as BoardCard;\n if (i < MAX_L3) {\n this.slotLevel[slot] = 3;\n this.slotOwn[slot] = 3;\n // L2 stays the stopgap until the large texture lands.\n if (!tm.has(card, 2)) wanted.push({ card, level: 2, dist, bucket: l2Bucket(480) });\n wanted.push({ card, level: 3, dist, bucket: l3Bucket(d) });\n } else {\n wanted.push({ card, level: 2, dist, bucket: l2Bucket(d) });\n }\n }\n }\n // ThumbHash cells for everything else, so a pan finds a placeholder already there.\n const store = this.store as StageStore;\n if (this.l0Missing > 0) {\n let missing = 0;\n for (const [id, slot] of this.slotOf) {\n let card = this.slotCard[slot];\n if (!card) {\n // Never mounted: build its BoardCard now so the thumbhash can be requested.\n const el = store.get(id);\n if (!el) continue;\n card = this.newCard(slot, el);\n this.slotCard[slot] = card;\n }\n if (this.slotView[slot] || tm.has(card, 0)) continue;\n if (!card.thumbhash) continue;\n missing++;\n const el = store.get(id) as Element;\n const r = this.rectOf(el);\n const dist = Math.hypot(r.x + r.w / 2 - cx, r.y + r.h / 2 - cy) * scale;\n wanted.push({ card, level: 0, dist: dist + FAR_DIST });\n }\n this.l0Missing = missing + l0Missing;\n } else this.l0Missing = l0Missing;\n tm.setWanted(wanted, now);\n // Pins moved with the camera: evict what just left the screen if the budget asks for it.\n tm.enforceBudget(now);\n for (const v of this.mediaViews) if (this.paintMedia(v)) changed = true;\n if (this.repointEvicted() || changed) this.dirty = true;\n }\n\n // An evicted texture is destroyed after later renders: any sprite still showing it must fall back to\n // what is left (a lower level, else the placeholder) before the next render.\n private repointEvicted(): boolean {\n let any = false;\n for (const slot of this.tm.takeEvicted()) if (this.applySlot(slot)) any = true;\n return any;\n }\n\n private trackProgress(now: number): void {\n if (this.firstPaintMs !== null && this.l1CompleteMs !== null) return;\n if (this.mediaViews.size === 0 || this.mountQueue.length > 0) return;\n let all0 = true;\n let all1 = true;\n for (const v of this.mediaViews) {\n const card = v.card;\n if (!card) continue;\n const has = (l: Level): boolean => this.tm.has(card, l);\n if (!has(0) && !has(1) && !has(2) && !has(3)) all0 = false;\n if (!has(1) && !has(2) && !has(3)) all1 = false;\n if (!all0) break;\n }\n if (all0 && this.firstPaintMs === null) this.firstPaintMs = now - this.t0;\n if (all1 && this.l1CompleteMs === null) this.l1CompleteMs = now - this.t0;\n }\n\n // ── Context loss ───────────────────────────────────────────────────────────\n private loseExt: WEBGL_lose_context | null = null;\n private bindContextLoss(): void {\n const c = this.canvas;\n const onLost = (e: Event): void => {\n e.preventDefault();\n this.lost = true;\n };\n const onRestored = (): void => {\n // Pixi has re-initialised its GL state; every texture of ours is gone.\n this.lost = false;\n this.dropAllTextures();\n };\n c.addEventListener('webglcontextlost', onLost);\n c.addEventListener('webglcontextrestored', onRestored);\n this.cleanups.push(() => {\n c.removeEventListener('webglcontextlost', onLost);\n c.removeEventListener('webglcontextrestored', onRestored);\n });\n }\n\n // Forgets every texture and reloads what is on screen, in viewport order (context restore, theme\n // change, and the recovery path below).\n private dropAllTextures(): void {\n this.tm.reset();\n for (const v of this.mediaViews) v.setTexture(null, -1, this.ctx);\n this.slotLevel.fill(-1);\n this.l0Missing = Math.max(this.slotOf.size, 1);\n this.dirty = true;\n this.mountedWin = null;\n this.cullAndLod(performance.now(), true);\n this.requestFrame();\n }\n\n // A render or an upload threw: in practice a texture destroyed while a Pixi batch still held it (the\n // RetireQueue's two-render delay is the structural fix; this guard stays as the safety net). Count it,\n // log it, and rebuild the textures so the board heals instead of throwing on every frame.\n private recoverTextures(e: unknown): void {\n this.counters.renderErrors++;\n this.renderErrorsTotal++;\n const detail =\n e instanceof Error\n ? `${e.message} | ${(e.stack ?? '').split('\\n').slice(1, 10).join(' | ')}`\n : String(e);\n console.error(`[corkboard] frame failed in ${this.where}, rebuilding textures: ${detail}`);\n try {\n this.dropAllTextures();\n } catch (e2) {\n console.error('[corkboard] recovery failed', e2);\n }\n }\n\n // Test hooks (WEBGL_lose_context).\n loseContext(): void {\n const gl = this.renderer.gl as WebGL2RenderingContext;\n this.loseExt = gl.getExtension('WEBGL_lose_context');\n this.loseExt?.loseContext();\n }\n restoreContext(): void {\n this.loseExt?.restoreContext();\n }\n\n // ── Stats ──────────────────────────────────────────────────────────────────\n resetStats(): void {\n this.nTick = 0;\n this.nRender = 0;\n this.nGpu = 0;\n this.counters = {\n renderErrors: 0,\n hookErrors: 0,\n rafCalls: 0,\n ticks: 0,\n renders: 0,\n cullPasses: 0,\n requeries: 0,\n lodPasses: 0,\n mounts: 0,\n unmounts: 0,\n };\n this.slowTicks = [];\n this.reqMs = { search: 0, mount: 0, unmount: 0, lod: 0 };\n this.nLodPass = 0;\n const s = this.tm.stats;\n s.uploadMsMax = 0;\n s.overBudgetMsMax = 0;\n s.peakBytes = this.tm.totalBytes;\n }\n\n // Counters and timings of the render loop: rAF callbacks, ticks, renders, mounted views, texture\n // memory by level, decode / upload numbers, tick / render / GPU percentiles.\n stats(): Record<string, unknown> {\n const levels = [0, 0, 0, 0];\n for (const v of this.mediaViews) {\n const s = v.card?.id;\n if (s !== undefined && this.slotLevel[s] >= 0) levels[this.slotLevel[s]]++;\n }\n const nt = Math.min(this.nTick, 4096);\n const nr = Math.min(this.nRender, 4096);\n const ng = Math.min(this.nGpu, 4096);\n const s = this.tm.stats;\n const pages = this.tm.pageCount();\n return {\n cards: this.slotOf.size,\n mounted: this.views.size,\n mountQueue: this.mountQueue.length,\n slowTicks: this.slowTicks,\n requeryMs: Object.fromEntries(Object.entries(this.reqMs).map(([k, v]) => [k, r2(v)])),\n lodPassMs: {\n n: Math.min(this.nLodPass, 1024),\n p50: r2(pct(this.lodPassMs, Math.min(this.nLodPass, 1024), 0.5)),\n p95: r2(pct(this.lodPassMs, Math.min(this.nLodPass, 1024), 0.95)),\n max: r2(Math.max(0, ...this.lodPassMs.subarray(0, Math.min(this.nLodPass, 1024)))),\n },\n worldChildren: this.world.children.length,\n pool: this.pools.stats(),\n scale: r2(this.cam.scale),\n dpr: this.dpr,\n viewport: [this.cam.width, this.cam.height],\n levelsMounted: levels,\n textureBytes: Math.round(this.tm.totalBytes),\n textureBudget: this.opts.budgetBytes,\n textureBytesPeak: Math.round(s.peakBytes),\n overBudgetMsMax: Math.round(s.overBudgetMsMax),\n l0Pages: pages.l0,\n l1Pages: pages.l1,\n l2Textures: this.tm.l2Count(),\n l3Textures: this.tm.l3Count(),\n retiredPending: this.tm.retiredPending,\n bytes: this.tm.breakdown(),\n queued: this.tm.queued,\n inflight: this.tm.inflightCount,\n decodes: s.decodes,\n decodeMsAvg: s.decodes ? r2(s.decodeMsTotal / s.decodes) : 0,\n fetchedBytes: s.fetchedBytes,\n cancelled: s.cancelled,\n failed: s.failed,\n evictedL2: s.evictedL2,\n evictedL3: s.evictedL3,\n evictedL1: s.evictedL1,\n uploads: s.uploads,\n uploadMsMax: r2(s.uploadMsMax),\n uploadMsAvg: s.uploadFrames ? r2(s.uploadMsTotal / s.uploadFrames) : 0,\n uploadsLastFrame: s.uploadsLastFrame,\n ...this.counters,\n tickMs: {\n n: nt,\n p10: r2(pct(this.tickMs, nt, 0.1)),\n p50: r2(pct(this.tickMs, nt, 0.5)),\n p95: r2(pct(this.tickMs, nt, 0.95)),\n p99: r2(pct(this.tickMs, nt, 0.99)),\n max: r2(nt ? Math.max(...this.tickMs.subarray(0, nt)) : 0),\n },\n renderMs: {\n n: nr,\n p10: r2(pct(this.renderMs, nr, 0.1)),\n p50: r2(pct(this.renderMs, nr, 0.5)),\n p95: r2(pct(this.renderMs, nr, 0.95)),\n p99: r2(pct(this.renderMs, nr, 0.99)),\n max: r2(nr ? Math.max(...this.renderMs.subarray(0, nr)) : 0),\n },\n gpuMs: this.gpu\n ? this.gpu.supported\n ? {\n n: ng,\n p10: r2(pct(this.gpuMs, ng, 0.1)),\n p50: r2(pct(this.gpuMs, ng, 0.5)),\n p95: r2(pct(this.gpuMs, ng, 0.95)),\n max: r2(ng ? Math.max(...this.gpuMs.subarray(0, ng)) : 0),\n }\n : 'unsupported'\n : 'off',\n firstPaintMs: this.firstPaintMs === null ? null : Math.round(this.firstPaintMs),\n l1CompleteMs: this.l1CompleteMs === null ? null : Math.round(this.l1CompleteMs),\n renderErrorsTotal: this.renderErrorsTotal,\n lost: this.lost,\n glRenderer: glRendererString(this.renderer),\n theme: cssHex(this.theme.canvas),\n };\n }\n\n dispose(): void {\n this.disposed = true;\n if (this.raf) cancelAnimationFrame(this.raf);\n if (this.settleTimer) clearTimeout(this.settleTimer);\n this.unsub?.();\n for (const f of this.cleanups) f();\n this.ro.disconnect();\n this.tm.dispose();\n this.pools.dispose();\n const dots = this.bg.texture;\n this.app.destroy(true, { children: true, texture: false });\n // `texture: false` leaves the dot texture to us (it is ours alone, never shared).\n dots.destroy(true);\n this.unparkTicker();\n }\n\n private makeBackground(): TilingSprite {\n // 64 px texture = one 24-world-px grid cell, a soft dot in the middle (white, tinted by the theme).\n const c = document.createElement('canvas');\n c.width = c.height = 64;\n const g = c.getContext('2d') as CanvasRenderingContext2D;\n g.fillStyle = '#ffffff';\n g.beginPath();\n g.arc(32, 32, 3, 0, Math.PI * 2);\n g.fill();\n // Not in Pixi's global texture cache (it would keep the canvas and texture alive past the board).\n const tex = Texture.from(c, true);\n return new TilingSprite({ texture: tex, width: 1, height: 1 });\n }\n}\n\nfunction glRendererString(renderer: WebGLRenderer): string {\n const gl = renderer.gl as WebGL2RenderingContext;\n const ext = gl.getExtension('WEBGL_debug_renderer_info');\n return ext\n ? String(gl.getParameter(ext.UNMASKED_RENDERER_WEBGL))\n : String(gl.getParameter(gl.RENDERER));\n}\n\n// GPU time per render through EXT_disjoint_timer_query_webgl2 (not available everywhere).\nclass GpuTimer {\n supported = false;\n private ext: { TIME_ELAPSED_EXT: number; GPU_DISJOINT_EXT: number } | null = null;\n private pending: WebGLQuery[] = [];\n private current: WebGLQuery | null = null;\n private constructor(private readonly gl: WebGL2RenderingContext) {}\n\n static create(renderer: WebGLRenderer): GpuTimer {\n const t = new GpuTimer(renderer.gl as WebGL2RenderingContext);\n t.ext = t.gl.getExtension('EXT_disjoint_timer_query_webgl2') as GpuTimer['ext'];\n t.supported = !!t.ext;\n return t;\n }\n begin(): void {\n if (!this.ext || this.current) return;\n this.current = this.gl.createQuery();\n if (this.current) this.gl.beginQuery(this.ext.TIME_ELAPSED_EXT, this.current);\n }\n end(): void {\n if (!this.ext || !this.current) return;\n this.gl.endQuery(this.ext.TIME_ELAPSED_EXT);\n this.pending.push(this.current);\n this.current = null;\n }\n poll(): number[] {\n const out: number[] = [];\n if (!this.ext) return out;\n const gl = this.gl;\n const disjoint = gl.getParameter(this.ext.GPU_DISJOINT_EXT);\n while (this.pending.length) {\n const q = this.pending[0];\n if (!gl.getQueryParameter(q, gl.QUERY_RESULT_AVAILABLE)) break;\n this.pending.shift();\n if (!disjoint) out.push(Number(gl.getQueryParameter(q, gl.QUERY_RESULT)) / 1e6);\n gl.deleteQuery(q);\n }\n return out;\n }\n}\n","// Resize handles of the current selection: which handles exist, where they are in world space, which\n// cursor each one shows, and which handle a pointer position is on. Pure; the overlay draws\n// `SelectionHandles` and the interaction controller feeds pointer positions to `handleAt`.\nimport type { Element } from '../types';\nimport type { Box, WorldRect } from './geometry';\nimport { boxOfRect, boxUnion, corners, fromRectLocal, toRectLocal, worldRectOf } from './geometry';\nimport type { ElementReader } from './reader';\n\nexport type HandleId = 'nw' | 'n' | 'ne' | 'e' | 'se' | 's' | 'sw' | 'w';\n\nexport interface Handle {\n id: HandleId;\n // World position of the handle centre.\n x: number;\n y: number;\n cursor: string;\n}\n\nexport interface SelectionHandles {\n // The rect the handles sit on: the element's rotated world rect (single selection), the shared\n // axis-aligned bounding rect (several).\n rect: WorldRect;\n // The four corners, drawn.\n handles: Handle[];\n // The edges that resize by dragging the edge itself (`handleAt` finds them): present only when every\n // selected element may change its aspect.\n edges: HandleId[];\n}\n\n// Screen-px constants.\nexport const HANDLE_HIT_PX = 10;\n// Below this on-screen side length the edge on that side is not grabbable: its band would sit on top\n// of the corner handles.\nconst EDGE_HANDLE_MIN_PX = 24;\n// The grab band of an edge, screen px across (half either side of the edge line).\nexport const EDGE_HIT_PX = 8;\n\n// Direction of each handle in the element's own frame: -1 = west / north, +1 = east / south.\nexport const HANDLE_DIRS: Readonly<Record<HandleId, readonly [number, number]>> = {\n nw: [-1, -1],\n n: [0, -1],\n ne: [1, -1],\n e: [1, 0],\n se: [1, 1],\n s: [0, 1],\n sw: [-1, 1],\n w: [-1, 0],\n};\n\n// Handle id -> axis angle, degrees clockwise from east, modulo 180 (the cursor shows a line along it).\nconst BASE_AXIS: Readonly<Record<HandleId, number>> = {\n e: 0,\n w: 0,\n se: 45,\n nw: 45,\n s: 90,\n n: 90,\n sw: 135,\n ne: 135,\n};\nconst AXIS_CURSORS = ['ew-resize', 'nwse-resize', 'ns-resize', 'nesw-resize'] as const;\n\n// The standard resize cursor, turned to the nearest 45 degrees of the element's rotation.\nexport function resizeCursor(id: HandleId, rotDeg: number): string {\n const step = Math.round((BASE_AXIS[id] + rotDeg) / 45);\n return AXIS_CURSORS[((step % 4) + 4) % 4];\n}\n\n// Axis-aligned box of the rotated rects themselves: what resize handles wrap.\nexport function geometryBox(rects: readonly WorldRect[]): Box | null {\n let box: Box | null = null;\n for (let i = 0; i < rects.length; i++) {\n const r = rects[i];\n let b: Box;\n if (r.rot === 0) {\n b = boxOfRect(r);\n } else {\n const c = corners(r);\n b = {\n minX: Math.min(c[0], c[2], c[4], c[6]),\n minY: Math.min(c[1], c[3], c[5], c[7]),\n maxX: Math.max(c[0], c[2], c[4], c[6]),\n maxY: Math.max(c[1], c[3], c[5], c[7]),\n };\n }\n box = box === null ? b : boxUnion(box, b);\n }\n return box;\n}\n\nfunction make(rect: WorldRect, id: HandleId, rot: number): Handle {\n const d = HANDLE_DIRS[id];\n const p = fromRectLocal(rect, ((d[0] + 1) / 2) * rect.w, ((d[1] + 1) / 2) * rect.h);\n return { id, x: p.x, y: p.y, cursor: resizeCursor(id, rot) };\n}\n\n// The handles of the selection, or null for an empty set or when any element is locked.\nexport function selectionHandles(\n reader: ElementReader,\n ids: readonly string[],\n zoom: number,\n): SelectionHandles | null {\n const els: Element[] = [];\n const rects: WorldRect[] = [];\n for (let i = 0; i < ids.length; i++) {\n const el = reader.get(ids[i]);\n if (!el) continue;\n if (el.locked) return null;\n els.push(el);\n rects.push(worldRectOf(el));\n }\n if (els.length === 0) return null;\n const z = zoom > 0 && Number.isFinite(zoom) ? zoom : 1;\n const free = els.every((e) => !e.aspectLocked);\n\n if (els.length > 1) {\n const b = geometryBox(rects);\n if (b === null) return null;\n const rect: WorldRect = { x: b.minX, y: b.minY, w: b.maxX - b.minX, h: b.maxY - b.minY, rot: 0 };\n return {\n rect,\n handles: (['nw', 'ne', 'se', 'sw'] as const).map((id) => make(rect, id, 0)),\n edges: [],\n };\n }\n\n const rect = rects[0];\n const edges: HandleId[] = [];\n if (free) {\n if (rect.w * z >= EDGE_HANDLE_MIN_PX) edges.push('n', 's');\n if (rect.h * z >= EDGE_HANDLE_MIN_PX) edges.push('e', 'w');\n }\n return {\n rect,\n handles: (['nw', 'ne', 'se', 'sw'] as const).map((id) => make(rect, id, rect.rot)),\n edges,\n };\n}\n\n// The handle under the pointer, if any. Hit boxes are `hitPx` screen px squares; where boxes overlap\n// (tiny selections) the nearest centre wins. Corners are tested before edges.\nexport function handleAt(\n sel: SelectionHandles,\n wx: number,\n wy: number,\n zoom: number,\n hitPx: number = HANDLE_HIT_PX,\n): Handle | null {\n const half = hitPx / 2 / (zoom > 0 ? zoom : 1);\n let best: Handle | null = null;\n let bestD = Infinity;\n for (let i = 0; i < sel.handles.length; i++) {\n const h = sel.handles[i];\n const dx = Math.abs(wx - h.x);\n const dy = Math.abs(wy - h.y);\n if (dx > half || dy > half) continue;\n const d = dx * dx + dy * dy;\n if (d < bestD) {\n best = h;\n bestD = d;\n }\n }\n return best ?? edgeAt(sel, wx, wy, zoom);\n}\n\n// The resizable edge under the pointer: a band of EDGE_HIT_PX across the edge line, over its length\n// (the corner handles are tested first, so they win at the ends). The band never takes more than a\n// quarter of a small side, so the middle of a tiny element can still be grabbed to move it.\nfunction edgeAt(sel: SelectionHandles, wx: number, wy: number, zoom: number): Handle | null {\n if (sel.edges.length === 0) return null;\n const z = zoom > 0 ? zoom : 1;\n const r = sel.rect;\n const half = Math.min(EDGE_HIT_PX / 2 / z, r.w / 4, r.h / 4);\n const p = toRectLocal(r, wx, wy);\n const inX = p.x >= -half && p.x <= r.w + half;\n const inY = p.y >= -half && p.y <= r.h + half;\n let id: HandleId | null = null;\n let d = Infinity;\n for (const e of sel.edges) {\n const dir = HANDLE_DIRS[e];\n const horizontal = dir[1] !== 0; // n / s: a horizontal edge\n const across = horizontal\n ? Math.abs(p.y - (dir[1] > 0 ? r.h : 0))\n : Math.abs(p.x - (dir[0] > 0 ? r.w : 0));\n if (across > half || !(horizontal ? inX : inY)) continue;\n if (across < d) {\n d = across;\n id = e;\n }\n }\n if (id === null) return null;\n const dir = HANDLE_DIRS[id];\n const lx = dir[0] === 0 ? Math.min(Math.max(p.x, 0), r.w) : ((dir[0] + 1) / 2) * r.w;\n const ly = dir[1] === 0 ? Math.min(Math.max(p.y, 0), r.h) : ((dir[1] + 1) / 2) * r.h;\n const at = fromRectLocal(r, lx, ly);\n return { id, x: at.x, y: at.y, cursor: resizeCursor(id, r.rot) };\n}\n","// Point hit testing against elements. Pure: the store is reached only through the structural\n// `ElementReader`.\n//\n// The query is two-phase: a spatial search with a tiny box around the point (grown by the screen\n// tolerance), then an exact rotated-rect test on the few candidates. Everything is in WORLD units; the\n// screen-px tolerance is divided by the zoom.\nimport type { Element } from '../types';\nimport type { Box } from './geometry';\nimport { pointInRotatedRect } from './geometry';\nimport type { ElementReader } from './reader';\n\nexport interface HitOptions {\n // Camera scale; the tolerance is `tolerancePx / zoom` in world units.\n zoom: number;\n // Screen px (default 4).\n tolerancePx?: number;\n // Ignore locked elements (a marquee does). Default false: a click on a locked element hits it.\n skipLocked?: boolean;\n filter?: (el: Element) => boolean;\n}\n\nconst DEFAULT_TOLERANCE_PX = 4;\nconst candidates: Element[] = [];\nconst searchBox: Box = { minX: 0, minY: 0, maxX: 0, maxY: 0 };\n\nconst safeZoom = (z: number): number => (z > 0 && Number.isFinite(z) ? z : 1);\n\nfunction eligible(el: Element, opts: HitOptions): boolean {\n if (opts.skipLocked && el.locked) return false;\n return opts.filter === undefined || opts.filter(el);\n}\n\nfunction collect(reader: ElementReader, wx: number, wy: number, tol: number): Element[] {\n searchBox.minX = wx - tol;\n searchBox.minY = wy - tol;\n searchBox.maxX = wx + tol;\n searchBox.maxY = wy + tol;\n return reader.searchInto(searchBox, candidates);\n}\n\nconst hits = (el: Element, wx: number, wy: number, tol: number): boolean =>\n pointInRotatedRect({ x: el.x, y: el.y, w: el.w, h: el.h, rot: el.rot }, wx, wy, tol);\n\n// The topmost element under the point (by draw order), or null.\nexport function hitTest(\n reader: ElementReader,\n wx: number,\n wy: number,\n opts: HitOptions,\n): Element | null {\n const tol = (opts.tolerancePx ?? DEFAULT_TOLERANCE_PX) / safeZoom(opts.zoom);\n const list = collect(reader, wx, wy, tol);\n let best: Element | null = null;\n let bestRank = -Infinity;\n for (let i = 0; i < list.length; i++) {\n const el = list[i];\n if (!eligible(el, opts)) continue;\n const rank = reader.rank(el.id);\n // Only elements above the current best can win: skip the exact test for the others.\n if (rank <= bestRank) continue;\n if (!hits(el, wx, wy, tol)) continue;\n best = el;\n bestRank = rank;\n }\n list.length = 0;\n return best;\n}\n\n// Every element under the point, top to bottom. `out` is cleared and returned.\nexport function hitTestAll(\n reader: ElementReader,\n wx: number,\n wy: number,\n opts: HitOptions,\n out: Element[] = [],\n): Element[] {\n out.length = 0;\n const tol = (opts.tolerancePx ?? DEFAULT_TOLERANCE_PX) / safeZoom(opts.zoom);\n const list = collect(reader, wx, wy, tol);\n for (let i = 0; i < list.length; i++) {\n const el = list[i];\n if (eligible(el, opts) && hits(el, wx, wy, tol)) out.push(el);\n }\n list.length = 0;\n if (out.length > 1) out.sort((a, b) => reader.rank(b.id) - reader.rank(a.id));\n return out;\n}\n","// Marquee (rubber-band) selection and selection bounds. Pure: reads elements through `ElementReader`.\n//\n// `touch` selects every element whose rotated rect meets the box; `contain` only those wholly inside it.\nimport type { Element } from '../types';\nimport type { Box, WorldRect } from './geometry';\nimport {\n boxIntersectsRotatedRect,\n boxUnion,\n elementBox,\n rotatedRectInsideBox,\n worldRectOf,\n} from './geometry';\nimport type { ElementReader } from './reader';\n\nexport interface MarqueeOptions {\n // Default true: locked elements are not selectable by a marquee (a click still selects them).\n skipLocked?: boolean;\n filter?: (el: Element) => boolean;\n}\n\nconst hits: Element[] = [];\nconst scratch: Element[] = [];\n\n// Ids of the elements selected by dragging `box`, ordered by draw order (bottom first).\nexport function elementsInBox(\n reader: ElementReader,\n box: Box,\n mode: 'touch' | 'contain',\n opts: MarqueeOptions = {},\n): string[] {\n const skipLocked = opts.skipLocked ?? true;\n const filter = opts.filter;\n const list = reader.searchInto(box, scratch);\n hits.length = 0;\n for (let i = 0; i < list.length; i++) {\n const el = list[i];\n if (skipLocked && el.locked) continue;\n if (filter !== undefined && !filter(el)) continue;\n const r = worldRectOf(el);\n const ok = mode === 'contain' ? rotatedRectInsideBox(r, box) : boxIntersectsRotatedRect(box, r);\n if (ok) hits.push(el);\n }\n list.length = 0;\n if (hits.length > 1) hits.sort((a, b) => reader.rank(a.id) - reader.rank(b.id));\n const ids: string[] = new Array<string>(hits.length);\n for (let i = 0; i < hits.length; i++) ids[i] = hits[i].id;\n hits.length = 0;\n return ids;\n}\n\n// Union AABB of the elements, plus the rotated world rect when exactly one element is selected (so the\n// selection outline follows its rotation). Locked elements count; missing ids are ignored; null when\n// nothing resolves.\nexport function selectionBounds(\n reader: ElementReader,\n ids: readonly string[],\n): { box: Box; rect: WorldRect | null } | null {\n let box: Box | null = null;\n let count = 0;\n let single: WorldRect | null = null;\n for (let i = 0; i < ids.length; i++) {\n const el = reader.get(ids[i]);\n if (!el) continue;\n const b = elementBox(el);\n box = box === null ? b : boxUnion(box, b);\n count++;\n if (count === 1) single = worldRectOf(el);\n }\n if (box === null) return null;\n return { box, rect: count === 1 ? single : null };\n}\n","// Resize sessions. A `ResizeSession` is created on pointer-down on a handle and `update`d on every\n// pointer move; it returns the new geometry of every affected element as patches the caller applies.\n// Pure: no store writes, no Pixi, no DOM. Pointers and handle geometry are WORLD coordinates.\n//\n// One element resizes about the corner or edge opposite the handle (about the centre with Alt), keeping\n// its aspect when it is locked or Shift is held. Several elements scale together, uniformly, about the\n// shared box.\nimport type { Box } from './geometry';\nimport { DEG } from './geometry';\nimport type { HandleId } from './handles';\nimport { geometryBox, HANDLE_DIRS } from './handles';\nimport type { ElementReader } from './reader';\n\n\nexport interface Mods {\n shift: boolean;\n alt: boolean;\n // Disables snapping while held.\n ctrl: boolean;\n}\n\n// Wired by the controller: `box` is the proposed world AABB of the selection and `edges` the dragged\n// edges (both objects are reused between calls: do not keep them). Returns the correction to ADD to\n// the snapped edge. Resizing about the centre flags both edges of an axis: `edgeX` / `edgeY` then say\n// which of the two the correction belongs to (absent: the dragged one).\nexport type Snapper = (\n box: Box,\n edges: { left?: boolean; right?: boolean; top?: boolean; bottom?: boolean },\n) => { dx: number; dy: number; edgeX?: 'min' | 'max'; edgeY?: 'min' | 'max' };\n\n// New geometry of one element.\nexport interface GeometryPatch {\n x: number;\n y: number;\n w: number;\n h: number;\n}\n\n// Smallest card edge a resize can reach, world px.\nexport const MIN_SIZE = 24;\n// Largest a card can be scaled to (long side), world px.\nexport const MAX_SIZE = 4000;\n\ntype Mode = 'noop' | 'single' | 'multi';\n\ninterface Item {\n id: string;\n // Start geometry: world top-left, size, rotation (degrees) and its trig, world centre.\n wx: number;\n wy: number;\n w: number;\n h: number;\n rot: number;\n cos: number;\n sin: number;\n cx: number;\n cy: number;\n aspectLocked: boolean;\n patch: GeometryPatch;\n}\n\n// Scratch result of `solveResize`: new rect in the OLD local frame (origin = old top-left).\nconst S = { l: 0, t: 0, w: 0, h: 0 };\n\n// Where a resized axis starts, in the old local frame. The anchor (the edge opposite the dragged one)\n// stays put; `flipped` means the dragged edge crossed it. Centred when resizing about the centre or\n// when the axis is not being dragged.\nfunction placeAxis(f: number, size: number, n: number, alt: boolean, flipped: boolean): number {\n if (f === 0 || alt) return (size - n) / 2;\n const anchor = f > 0 ? 0 : size;\n const end = anchor + (flipped ? -f : f) * n;\n return end < anchor ? end : anchor;\n}\n\n// Resizes a w x h box by dragging the handle direction (fx, fy) by (dx, dy), both in the box's own\n// frame. `lock` keeps the aspect (the larger relative scale wins), `alt` resizes about the centre.\nfunction solveResize(\n w: number,\n h: number,\n fx: number,\n fy: number,\n dx: number,\n dy: number,\n alt: boolean,\n lock: boolean,\n minW: number,\n minH: number,\n maxScale: number,\n): void {\n const k = alt ? 2 : 1;\n if (lock && w > 0 && h > 0) {\n const sx = fx !== 0 ? (w + k * fx * dx) / w : 0;\n const sy = fy !== 0 ? (h + k * fy * dy) / h : 0;\n let s: number;\n if (fx !== 0 && fy !== 0) s = Math.max(sx, sy);\n else s = fx !== 0 ? sx : sy;\n let a = s;\n const minS = Math.max(minW / w, minH / h);\n if (a < minS) a = minS;\n if (a > maxScale) a = maxScale;\n S.w = w * a;\n S.h = h * a;\n S.l = placeAxis(fx, w, S.w, alt, false);\n S.t = placeAxis(fy, h, S.h, alt, false);\n return;\n }\n if (fx === 0) {\n S.l = 0;\n S.w = w;\n } else {\n const n = Math.max(w + k * fx * dx, minW);\n S.w = n;\n S.l = placeAxis(fx, w, n, alt, false);\n }\n if (fy === 0) {\n S.t = 0;\n S.h = h;\n } else {\n const n = Math.max(h + k * fy * dy, minH);\n S.h = n;\n S.t = placeAxis(fy, h, n, alt, false);\n }\n}\n\n// The pointer shift that moves a snapped edge by `delta`. Resizing about the centre can snap the edge\n// opposite the dragged one (`edge` min / max against the dragged direction `dir`, -1 min / +1 max): it\n// moves the other way as the pointer does.\nfunction pointerShift(delta: number, edge: 'min' | 'max' | undefined, dir: number): number {\n if (edge === undefined || dir === 0) return delta;\n return (edge === 'min') === dir < 0 ? delta : -delta;\n}\n\nexport class ResizeSession {\n readonly handle: HandleId;\n readonly affected: readonly string[];\n\n private readonly mode: Mode;\n private readonly items: Item[] = [];\n private readonly out = new Map<string, GeometryPatch>();\n private readonly start: { x: number; y: number };\n // Handle direction in the element's own frame.\n private fx = 0;\n private fy = 0;\n // Shared geometry box of the items (multi resize).\n private bx = 0;\n private by = 0;\n private bw = 0;\n private bh = 0;\n // Snapper scratch (reused: no allocation per pointer move).\n private readonly snapBox: Box = { minX: 0, minY: 0, maxX: 0, maxY: 0 };\n private readonly snapEdges = { left: false, right: false, top: false, bottom: false };\n private readonly centre = { x: 0, y: 0 };\n\n constructor(\n reader: ElementReader,\n ids: readonly string[],\n handle: HandleId,\n startWorld: { x: number; y: number },\n ) {\n this.handle = handle;\n this.start = { x: startWorld.x, y: startWorld.y };\n const seen = new Set<string>();\n const affected: string[] = [];\n for (const id of ids) {\n const el = reader.get(id);\n if (!el || el.locked || seen.has(el.id)) continue;\n seen.add(el.id);\n const a = el.rot * DEG;\n const item: Item = {\n id: el.id,\n wx: el.x,\n wy: el.y,\n w: el.w,\n h: el.h,\n rot: el.rot,\n cos: el.rot === 0 ? 1 : Math.cos(a),\n sin: el.rot === 0 ? 0 : Math.sin(a),\n cx: el.x + el.w / 2,\n cy: el.y + el.h / 2,\n aspectLocked: el.aspectLocked,\n // Identity until the first update.\n patch: { x: el.x, y: el.y, w: el.w, h: el.h },\n };\n this.items.push(item);\n this.out.set(item.id, item.patch);\n affected.push(item.id);\n }\n this.affected = affected;\n this.mode = this.items.length === 0 ? 'noop' : this.items.length > 1 ? 'multi' : 'single';\n const d = HANDLE_DIRS[handle];\n this.fx = d[0];\n this.fy = d[1];\n if (this.mode === 'multi') {\n const b = geometryBox(\n this.items.map((it) => ({ x: it.wx, y: it.wy, w: it.w, h: it.h, rot: it.rot })),\n );\n if (b !== null) {\n this.bx = b.minX;\n this.by = b.minY;\n this.bw = b.maxX - b.minX;\n this.bh = b.maxY - b.minY;\n }\n }\n }\n\n // The geometry of every affected element at this pointer position (world). The returned Map and its\n // patches are reused by the next call: apply them before calling `update` again.\n update(\n pointer: { x: number; y: number },\n mods: Mods,\n snap?: Snapper,\n ): Map<string, GeometryPatch> {\n const useSnap = snap !== undefined && !mods.ctrl ? snap : undefined;\n if (this.mode === 'single') this.updateSingle(pointer.x, pointer.y, mods, useSnap);\n else if (this.mode === 'multi') this.updateMulti(pointer.x, pointer.y, mods, useSnap);\n return this.out;\n }\n\n // ── single element ─────────────────────────────────────────────────────────\n\n private solveSingle(it: Item, px: number, py: number, mods: Mods): void {\n const dxw = px - this.start.x;\n const dyw = py - this.start.y;\n // Pointer delta in the element's own (rotated) frame.\n const dl = dxw * it.cos + dyw * it.sin;\n const dv = -dxw * it.sin + dyw * it.cos;\n const long = Math.max(it.w, it.h);\n solveResize(\n it.w,\n it.h,\n this.fx,\n this.fy,\n dl,\n dv,\n mods.alt,\n it.aspectLocked || mods.shift,\n MIN_SIZE,\n MIN_SIZE,\n long > 0 ? MAX_SIZE / long : Infinity,\n );\n }\n\n // World centre of the solved rect.\n private solvedCenter(it: Item, out: { x: number; y: number }): void {\n const lx = S.l + S.w / 2 - it.w / 2;\n const ly = S.t + S.h / 2 - it.h / 2;\n out.x = it.cx + lx * it.cos - ly * it.sin;\n out.y = it.cy + lx * it.sin + ly * it.cos;\n }\n\n private updateSingle(px: number, py: number, mods: Mods, snap: Snapper | undefined): void {\n const it = this.items[0];\n this.solveSingle(it, px, py, mods);\n // Snapping is axis-aligned: only elements turned by whole quarter turns have world edges that\n // correspond to their own edges.\n if (snap !== undefined && it.rot % 90 === 0) {\n this.solvedCenter(it, this.centre);\n const swap = Math.abs(it.rot / 90) % 2 === 1;\n const ew = swap ? S.h : S.w;\n const eh = swap ? S.w : S.h;\n const b = this.snapBox;\n b.minX = this.centre.x - ew / 2;\n b.maxX = this.centre.x + ew / 2;\n b.minY = this.centre.y - eh / 2;\n b.maxY = this.centre.y + eh / 2;\n // The dragged edge directions in world axes (exact for quarter turns).\n const dirX = Math.round(this.fx * it.cos - this.fy * it.sin);\n const dirY = Math.round(this.fx * it.sin + this.fy * it.cos);\n this.setEdges(dirX, dirY, mods.alt);\n const c = snap(b, this.snapEdges);\n if (c.dx !== 0 || c.dy !== 0) {\n const dx = pointerShift(c.dx, c.edgeX, dirX);\n const dy = pointerShift(c.dy, c.edgeY, dirY);\n this.solveSingle(it, px + dx, py + dy, mods);\n }\n }\n this.solvedCenter(it, this.centre);\n const p = it.patch;\n p.x = this.centre.x - S.w / 2;\n p.y = this.centre.y - S.h / 2;\n p.w = S.w;\n p.h = S.h;\n }\n\n private setEdges(dirX: number, dirY: number, alt: boolean): void {\n const e = this.snapEdges;\n e.left = dirX < 0 || (alt && dirX !== 0);\n e.right = dirX > 0 || (alt && dirX !== 0);\n e.top = dirY < 0 || (alt && dirY !== 0);\n e.bottom = dirY > 0 || (alt && dirY !== 0);\n }\n\n // ── several elements ───────────────────────────────────────────────────────\n\n private solveMulti(px: number, py: number, mods: Mods): void {\n solveResize(\n this.bw,\n this.bh,\n this.fx,\n this.fy,\n px - this.start.x,\n py - this.start.y,\n mods.alt,\n true,\n MIN_SIZE,\n MIN_SIZE,\n Infinity,\n );\n }\n\n private updateMulti(px: number, py: number, mods: Mods, snap: Snapper | undefined): void {\n this.solveMulti(px, py, mods);\n if (snap !== undefined) {\n const b = this.snapBox;\n b.minX = this.bx + S.l;\n b.minY = this.by + S.t;\n b.maxX = b.minX + S.w;\n b.maxY = b.minY + S.h;\n this.setEdges(this.fx, this.fy, mods.alt);\n const c = snap(b, this.snapEdges);\n if (c.dx !== 0 || c.dy !== 0) {\n const dx = pointerShift(c.dx, c.edgeX, this.fx);\n const dy = pointerShift(c.dy, c.edgeY, this.fy);\n this.solveMulti(px + dx, py + dy, mods);\n }\n }\n const s = this.bw > 0 ? S.w / this.bw : 1;\n const left = this.bx + S.l;\n const top = this.by + S.t;\n for (const it of this.items) {\n const w = Math.max(it.w * s, 1);\n const h = Math.max(it.h * s, 1);\n // Scale the centre about the box origin so rotated elements stay consistent.\n const ncx = left + (it.cx - this.bx) * s;\n const ncy = top + (it.cy - this.by) * s;\n const p = it.patch;\n p.x = ncx - w / 2;\n p.y = ncy - h / 2;\n p.w = w;\n p.h = h;\n }\n }\n}\n","// Snapping of edges, centres, gaps and sizes, plus the guide model. Pure: no Pixi, no DOM.\n//\n// While a box is moved or resized it snaps, X and Y independently, to four families of targets:\n// - alignment: its left / centre / right (top / middle / bottom) lines against the same lines of\n// nearby elements;\n// - equal gaps (move, and the dragged edge of a resize): the gap to the nearest neighbour on its row\n// (column) becomes equal to a gap already present between two elements of that row (column), or the\n// box centres itself between its two neighbours so both gaps are equal;\n// - width / height match (resize of one edge): the box takes the width (height) of a nearby element on\n// its row or in its column.\n// The smallest |delta| within the threshold wins; on a tie alignment beats a size match, which beats a\n// gap. The caller converts the SNAP_THRESHOLD_PX screen threshold to world units (`/ zoom`, so it feels\n// the same at every zoom) and passes the candidates (viewport grown by 25 %, nearest N) once per drag.\n// Hysteresis: a result object reused across a drag remembers each axis' winner, which then holds\n// until the box is SNAP_RELEASE thresholds away from it or another target is clearly nearer\n// (SNAP_SWITCH thresholds), so the box never chatters between two targets or across the threshold. `SnapIndex` is built once from them:\n// sorted lines per axis, the owner boxes, the gaps between neighbouring boxes (sorted by size) and the\n// sorted widths / heights. A move then costs a few binary searches plus one linear pass over the\n// candidates to find the box's neighbours, with no allocation beyond the guide objects.\nimport type { Box } from './geometry';\n\nexport interface SnapCandidate {\n id: string;\n box: Box;\n}\n\n// Screen px: the snap threshold and how far a guide runs past its outermost marker. Callers divide by\n// the zoom.\nexport const SNAP_THRESHOLD_PX = 6;\nexport const GUIDE_OVERSHOOT_PX = 3;\n// Hysteresis, in thresholds: a held target lets go beyond SNAP_RELEASE, and a new target takes over\n// only when it is nearer than the held one by more than SNAP_SWITCH.\nexport const SNAP_RELEASE = 1.5;\nexport const SNAP_SWITCH = 0.5;\n\n// Lines closer than this (world units) count as the same line: it collects coincident candidates into\n// one guide and absorbs floating point noise left by the correction.\nexport const SNAP_EPS = 0.01;\n\n// An alignment guide. A vertical guide (axis 'x') is the line x = `at` running from y = `from` to\n// y = `to`; a horizontal guide (axis 'y') is the line y = `at` running from x = `from` to x = `to`.\n// World units. `kind` follows the moving line that produced it ('center' for the centre / middle line,\n// 'edge' for the outer ones).\n// `marks`: where the line meets each aligned box, sorted (positions along the line, world units): the\n// two corners of a box aligned by an edge, the midpoint of one aligned by its centre, for the moving\n// box and the candidates on the line nearest to it (at most six). The span runs from the first mark to\n// the last plus the overshoot.\nexport interface LineGuide {\n axis: 'x' | 'y';\n at: number;\n from: number;\n to: number;\n kind: 'edge' | 'center';\n marks?: number[];\n}\n\n// A measurement marker. NOTE the axis convention differs from `LineGuide`: here `axis` is the direction\n// the measured segment RUNS along. A segment along 'x' is horizontal: it sits at y = `at` and runs from\n// x = `from` to x = `to`; along 'y' it is vertical at x = `at`, from y = `from` to y = `to`. World units.\n// - 'gap': the empty space between two boxes, `label` = its size in world px, rounded to an integer.\n// Emitted for the moving box's own gap(s) and for each existing gap it was matched to; `at` is the\n// middle of the range the two boxes face each other over.\n// - 'width' (axis 'x') / 'height' (axis 'y'): the extent of one box, spanning from edge to edge, drawn\n// at the middle of the box (`at`). Emitted for the resized box and for each box whose extent it was\n// matched to; `label` = the extent in world px, rounded (the overlay draws \"=\" instead).\nexport interface MeasureGuide {\n axis: 'x' | 'y';\n at: number;\n from: number;\n to: number;\n kind: 'gap' | 'width';\n label: number;\n}\n\n// Every guide carries `axis`, `at`, `from`, `to` and `kind`; tell the families apart by `kind`.\nexport type Guide = LineGuide | MeasureGuide;\n\n// `dx` / `dy`: the correction to ADD to the moving box (0 when that axis does not snap). A box that\n// already lies on a line reports 0 and still carries the guide.\nexport interface SnapResult {\n dx: number;\n dy: number;\n guides: Guide[];\n // A resize that flags both opposite edges of an axis (a symmetric resize): the edge `dx` / `dy` applies to.\n // Absent when that axis did not snap, or for a move.\n edgeX?: 'min' | 'max';\n edgeY?: 'min' | 'max';\n}\n\nexport interface ResizeEdges {\n left?: boolean;\n right?: boolean;\n top?: boolean;\n bottom?: boolean;\n}\n\n// Line kinds (candidate lines and moving lines share the first two).\nconst EDGE = 0;\nconst CENTER = 1;\n\n// Which family won an axis.\nconst WIN_NONE = 0;\nconst WIN_ALIGN = 1;\nconst WIN_SIZE = 2;\nconst WIN_GAP = 3;\n\n// Gaps are only collected among the first 400 candidate boxes (the engine never passes more): the\n// neighbour search at build time is quadratic in the worst case.\nconst GAP_BOX_CAP = 400;\n// A box looks at most this many closer boxes deep when it collects its neighbours.\nconst MAX_BLOCKERS = 64;\n// At most this many existing gaps / matched boxes are drawn next to the moving box's own (the nearest\n// ones: a far match adds clutter, not information). The scan for the nearest is bounded too.\nconst MAX_REF_GAPS = 3;\nconst MAX_SIZE_MATCHES = 3;\nconst REF_GAP_SCAN = 256;\n\nconst AXES = ['x', 'y'] as const;\n\ninterface AxisLines {\n // Sorted line positions, with the owner (index into `boxes`) and kind of each line.\n readonly v: Float64Array;\n readonly owner: Int32Array;\n readonly kind: Uint8Array;\n}\n\n// The gaps along one axis, sorted by size: each is the empty space between two candidate boxes that\n// face each other over a positive length of the other axis, with nothing between them.\ninterface GapList {\n readonly v: Float64Array;\n // Owners of the box before (smaller coordinate) and after the gap.\n readonly before: Int32Array;\n readonly after: Int32Array;\n}\n\n// The extents (widths or heights) of the candidate boxes, sorted.\ninterface SizeList {\n readonly v: Float64Array;\n readonly owner: Int32Array;\n}\n\n// Opaque to callers: build it with `buildSnapIndex`, hand it back to `snapMove` / `snapResize`.\nexport interface SnapIndex {\n // Number of owners (the candidates that were usable).\n readonly count: number;\n readonly candCount: number;\n readonly ids: readonly string[];\n // Four numbers per owner: minX, minY, maxX, maxY.\n readonly boxes: Float64Array;\n readonly x: AxisLines;\n readonly y: AxisLines;\n // Horizontal gaps (boxes side by side on a row) and vertical gaps (boxes stacked in a column).\n readonly gapsX: GapList;\n readonly gapsY: GapList;\n readonly widths: SizeList;\n readonly heights: SizeList;\n}\n\nconst EMPTY_LINES: AxisLines = {\n v: new Float64Array(0),\n owner: new Int32Array(0),\n kind: new Uint8Array(0),\n};\n\nconst EMPTY_GAPS: GapList = {\n v: new Float64Array(0),\n before: new Int32Array(0),\n after: new Int32Array(0),\n};\n\nconst EMPTY_SIZES: SizeList = { v: new Float64Array(0), owner: new Int32Array(0) };\n\n// The indices 0..n-1 ordered by `key`.\nfunction sortedOrder(key: ArrayLike<number>, n: number): Uint32Array {\n const order = new Uint32Array(n);\n for (let i = 0; i < n; i++) order[i] = i;\n order.sort((a, b) => key[a] - key[b]);\n return order;\n}\n\n// Sort the raw (value, owner, kind) triples by value. A permutation sort keeps the three arrays\n// parallel without packing; the order among equal values is irrelevant (runs are scanned whole).\nfunction sortLines(\n rawV: Float64Array,\n rawOwner: Int32Array,\n rawKind: Uint8Array,\n n: number,\n): AxisLines {\n if (n === 0) return EMPTY_LINES;\n const order = sortedOrder(rawV, n);\n const v = new Float64Array(n);\n const owner = new Int32Array(n);\n const kind = new Uint8Array(n);\n for (let i = 0; i < n; i++) {\n const s = order[i];\n v[i] = rawV[s];\n owner[i] = rawOwner[s];\n kind[i] = rawKind[s];\n }\n return { v, owner, kind };\n}\n\nfunction validBox(b: Box): boolean {\n return (\n Number.isFinite(b.minX) &&\n Number.isFinite(b.minY) &&\n Number.isFinite(b.maxX) &&\n Number.isFinite(b.maxY) &&\n b.maxX >= b.minX &&\n b.maxY >= b.minY\n );\n}\n\n// The extent of every candidate box along `ax` (0: width, 1: height), sorted.\nfunction buildSizes(boxes: Float64Array, n: number, ax: number): SizeList {\n if (n === 0) return EMPTY_SIZES;\n const raw = new Float64Array(n);\n for (let o = 0; o < n; o++) raw[o] = boxes[o * 4 + ax + 2] - boxes[o * 4 + ax];\n const order = sortedOrder(raw, n);\n const v = new Float64Array(n);\n const owner = new Int32Array(n);\n for (let i = 0; i < n; i++) {\n v[i] = raw[order[i]];\n owner[i] = order[i];\n }\n return { v, owner };\n}\n\n// The gaps between neighbouring boxes along `ax` (0: horizontal gaps, 1: vertical ones). For each box\n// `a` the boxes that start at or after its far edge and face it over a positive length of the other\n// axis are visited nearest first; one is a neighbour unless a closer neighbour of `a` already hides the\n// whole stretch they face each other over. Touching neighbours (no gap) are neighbours too: they hide\n// what lies behind them. O(n log n) for the sort plus, per box, the scan over what lies on its side,\n// which stops as soon as the closer boxes cover its whole extent (bounded by MAX_BLOCKERS).\nfunction buildGaps(boxes: Float64Array, n: number, ax: number): GapList {\n if (n < 2) return EMPTY_GAPS;\n const pa = 1 - ax;\n const keys = new Float64Array(n);\n for (let o = 0; o < n; o++) keys[o] = boxes[o * 4 + ax];\n const order = sortedOrder(keys, n);\n const sortedLo = new Float64Array(n);\n for (let i = 0; i < n; i++) sortedLo[i] = keys[order[i]];\n const blkLo = new Float64Array(MAX_BLOCKERS);\n const blkHi = new Float64Array(MAX_BLOCKERS);\n const gv: number[] = [];\n const gBefore: number[] = [];\n const gAfter: number[] = [];\n\n for (let i = 0; i < n; i++) {\n const a = order[i];\n const ka = a * 4;\n const aHi = boxes[ka + ax + 2];\n const aPlo = boxes[ka + pa];\n const aPhi = boxes[ka + pa + 2];\n let nb = 0;\n // The union of what the accepted neighbours cover of `a`'s extent (only growing runs that touch the\n // first one: it is an early exit, a miss just scans further).\n let covLo = Infinity;\n let covHi = -Infinity;\n for (let j = lowerBound(sortedLo, aHi - SNAP_EPS); j < n; j++) {\n const b = order[j];\n if (b === a) continue;\n const kb = b * 4;\n const ovLo = Math.max(aPlo, boxes[kb + pa]);\n const ovHi = Math.min(aPhi, boxes[kb + pa + 2]);\n if (!(ovHi > ovLo)) continue;\n let hidden = false;\n for (let m = 0; m < nb; m++) {\n if (blkLo[m] <= ovLo + SNAP_EPS && blkHi[m] >= ovHi - SNAP_EPS) {\n hidden = true;\n break;\n }\n }\n if (hidden) continue;\n const gap = boxes[kb + ax] - aHi;\n if (gap > SNAP_EPS) {\n gv.push(gap);\n gBefore.push(a);\n gAfter.push(b);\n }\n if (nb === MAX_BLOCKERS) break;\n blkLo[nb] = boxes[kb + pa];\n blkHi[nb] = boxes[kb + pa + 2];\n nb++;\n if (covHi < covLo) {\n covLo = ovLo;\n covHi = ovHi;\n } else if (ovLo <= covHi + SNAP_EPS && ovHi >= covLo - SNAP_EPS) {\n if (ovLo < covLo) covLo = ovLo;\n if (ovHi > covHi) covHi = ovHi;\n }\n if (covLo <= aPlo + SNAP_EPS && covHi >= aPhi - SNAP_EPS) break;\n }\n }\n\n const m = gv.length;\n if (m === 0) return EMPTY_GAPS;\n const perm = sortedOrder(gv, m);\n const v = new Float64Array(m);\n const before = new Int32Array(m);\n const after = new Int32Array(m);\n for (let i = 0; i < m; i++) {\n const s = perm[i];\n v[i] = gv[s];\n before[i] = gBefore[s];\n after[i] = gAfter[s];\n }\n return { v, before, after };\n}\n\n// O(n log n) for the lines and sizes, done once at drag start; the gaps cost a bounded quadratic pass\n// over at most GAP_BOX_CAP boxes. Candidates give left / centre / right and top / middle / bottom\n// lines, gaps and sizes. Boxes that are not finite are ignored.\nexport function buildSnapIndex(candidates: readonly SnapCandidate[]): SnapIndex {\n const maxOwners = candidates.length;\n const boxes = new Float64Array(maxOwners * 4);\n const ids: string[] = [];\n const maxLines = candidates.length * 3;\n const xv = new Float64Array(maxLines);\n const xo = new Int32Array(maxLines);\n const xk = new Uint8Array(maxLines);\n const yv = new Float64Array(maxLines);\n const yo = new Int32Array(maxLines);\n const yk = new Uint8Array(maxLines);\n let owners = 0;\n let nx = 0;\n let ny = 0;\n\n for (let i = 0; i < candidates.length; i++) {\n const c = candidates[i];\n const b = c.box;\n if (!validBox(b)) continue;\n const o = owners++;\n ids.push(c.id);\n boxes[o * 4] = b.minX;\n boxes[o * 4 + 1] = b.minY;\n boxes[o * 4 + 2] = b.maxX;\n boxes[o * 4 + 3] = b.maxY;\n xv[nx] = b.minX;\n xo[nx] = o;\n xk[nx++] = EDGE;\n xv[nx] = (b.minX + b.maxX) / 2;\n xo[nx] = o;\n xk[nx++] = CENTER;\n xv[nx] = b.maxX;\n xo[nx] = o;\n xk[nx++] = EDGE;\n yv[ny] = b.minY;\n yo[ny] = o;\n yk[ny++] = EDGE;\n yv[ny] = (b.minY + b.maxY) / 2;\n yo[ny] = o;\n yk[ny++] = CENTER;\n yv[ny] = b.maxY;\n yo[ny] = o;\n yk[ny++] = EDGE;\n }\n const candCount = owners;\n\n const gapBoxes = Math.min(candCount, GAP_BOX_CAP);\n return {\n count: owners,\n candCount,\n ids,\n boxes,\n x: sortLines(xv, xo, xk, nx),\n y: sortLines(yv, yo, yk, ny),\n gapsX: buildGaps(boxes, gapBoxes, 0),\n gapsY: buildGaps(boxes, gapBoxes, 1),\n widths: buildSizes(boxes, candCount, 0),\n heights: buildSizes(boxes, candCount, 1),\n };\n}\n\n// First index whose value is >= x (v.length when none).\nfunction lowerBound(v: Float64Array, x: number): number {\n let lo = 0;\n let hi = v.length;\n while (lo < hi) {\n const mid = (lo + hi) >>> 1;\n if (v[mid] < x) lo = mid + 1;\n else hi = mid;\n }\n return lo;\n}\n\n// Tie-break between matches at the same distance: centre-to-centre, then edge-to-edge, then a mixed\n// pair (an edge on a centre).\nfunction pairRank(movingKind: number, lineKind: number): number {\n if (movingKind === CENTER) return lineKind === CENTER ? 0 : 2;\n return lineKind === CENTER ? 2 : 1;\n}\n\n// Scratch for the axis search (module level: the search runs on the main thread only and never\n// re-enters, and it keeps the per-move path free of allocations).\nlet bestFound = false;\nlet bestAbs = 0;\nlet bestDelta = 0;\nlet bestRank = 0;\nlet bestLine = 0;\n\n// Evaluate the run of equal-valued lines that starts at `start` and extends in `dir`, then keep it if\n// it beats the best match so far (smaller |delta| wins; within SNAP_EPS the better rank wins; a full\n// tie keeps the earlier one, so the result is deterministic).\nfunction consider(\n lines: AxisLines,\n start: number,\n dir: 1 | -1,\n abs: number,\n delta: number,\n movingKind: number,\n movingLine: number,\n): void {\n const v = lines.v;\n const w = v[start];\n let rank = 4;\n for (let j = start; j >= 0 && j < v.length && Math.abs(v[j] - w) <= SNAP_EPS; j += dir) {\n const r = pairRank(movingKind, lines.kind[j]);\n if (r < rank) rank = r;\n }\n if (!bestFound || abs < bestAbs - SNAP_EPS || (abs <= bestAbs + SNAP_EPS && rank < bestRank)) {\n bestFound = true;\n bestAbs = abs;\n bestDelta = delta;\n bestRank = rank;\n bestLine = movingLine;\n }\n}\n\n// Find the nearest line to `m` on each side, within the threshold, and feed them to `consider`.\nfunction probe(\n lines: AxisLines,\n m: number,\n movingKind: number,\n movingLine: number,\n threshold: number,\n): void {\n const v = lines.v;\n const n = v.length;\n if (n === 0) return;\n const i = lowerBound(v, m);\n if (i < n) {\n const abs = v[i] - m;\n if (abs <= threshold) consider(lines, i, 1, abs, v[i] - m, movingKind, movingLine);\n }\n if (i > 0) {\n const abs = m - v[i - 1];\n if (abs <= threshold) consider(lines, i - 1, -1, abs, v[i - 1] - m, movingKind, movingLine);\n }\n}\n\n// ── Equal gaps ────────────────────────────────────────────────────────────────────────────────────\n\n// The moving box and the box the guides are measured from (min x, min y, max x, max y).\nconst mv = new Float64Array(4);\nconst fb = new Float64Array(4);\n\n// Neighbours of the moving box along an axis (owner and facing edge; owner -1 when there is none).\nlet nbBefore = -1;\nlet nbAfter = -1;\nlet nbBeforeEdge = 0;\nlet nbAfterEdge = 0;\n\n// The nearest candidate box before (ending at or before `m0`) and after (starting at or after `m1`)\n// the span m0..m1 of axis `ax`, among those that overlap p0..p1 on the other axis. Nothing lies\n// between the box and its neighbour: any such box would be nearer.\nfunction findNeighbours(\n index: SnapIndex,\n ax: number,\n m0: number,\n m1: number,\n p0: number,\n p1: number,\n): void {\n const boxes = index.boxes;\n const pa = 1 - ax;\n const n = index.candCount;\n let before = -1;\n let after = -1;\n let beforeEdge = -Infinity;\n let afterEdge = Infinity;\n for (let o = 0; o < n; o++) {\n const k = o * 4;\n if (!(boxes[k + pa + 2] > p0 && boxes[k + pa] < p1)) continue;\n const hi = boxes[k + ax + 2];\n if (hi <= m0 + SNAP_EPS) {\n if (hi > beforeEdge) {\n beforeEdge = hi;\n before = o;\n }\n } else {\n const lo = boxes[k + ax];\n if (lo >= m1 - SNAP_EPS && lo < afterEdge) {\n afterEdge = lo;\n after = o;\n }\n }\n }\n nbBefore = before;\n nbAfter = after;\n nbBeforeEdge = beforeEdge;\n nbAfterEdge = afterEdge;\n}\n\n// Does gap `j` sit on the moving box's row (column): do its two boxes face each other over part of\n// p0..p1 of the other axis?\nfunction gapInRow(\n index: SnapIndex,\n gl: GapList,\n j: number,\n pa: number,\n p0: number,\n p1: number,\n): boolean {\n const b = index.boxes;\n const ka = gl.before[j] * 4;\n const kb = gl.after[j] * 4;\n const lo = Math.max(b[ka + pa], b[kb + pa]);\n const hi = Math.min(b[ka + pa + 2], b[kb + pa + 2]);\n return hi > p0 && lo < p1;\n}\n\n// Best gap snap so far on the current axis.\nlet gapFound = false;\nlet gapAbs = 0;\nlet gapDelta = 0;\nlet gapLine = 0;\nlet gapSize = 0;\n\nfunction offerGap(abs: number, delta: number, line: number, size: number): void {\n if (!gapFound || abs < gapAbs - SNAP_EPS) {\n gapFound = true;\n gapAbs = abs;\n gapDelta = delta;\n gapLine = line;\n gapSize = size;\n }\n}\n\n// The existing gaps nearest to the moving box's current gap `gc`, in both directions and within the\n// threshold, that sit on its row. `sign` is +1 when the moving edge is the min one (the gap grows with\n// the coordinate) and -1 when it is the max one.\nfunction probeGapSizes(\n index: SnapIndex,\n gl: GapList,\n gc: number,\n sign: number,\n line: number,\n pa: number,\n p0: number,\n p1: number,\n threshold: number,\n): void {\n const v = gl.v;\n const n = v.length;\n if (n === 0) return;\n const i = lowerBound(v, gc);\n for (let j = i; j < n; j++) {\n const d = v[j] - gc;\n if (d > threshold) break;\n if (gapInRow(index, gl, j, pa, p0, p1)) {\n offerGap(d, sign * d, line, v[j]);\n break;\n }\n }\n for (let j = i - 1; j >= 0; j--) {\n const d = gc - v[j];\n if (d > threshold) break;\n if (gapInRow(index, gl, j, pa, p0, p1)) {\n offerGap(d, -sign * d, line, v[j]);\n break;\n }\n }\n}\n\n// Gap snaps along axis `ax` for the moving box `mv`. A whole box may match either of its neighbours'\n// gaps to an existing one, or centre itself between them; a resize only moves the dragged edge, so only\n// the gap on that side counts (`mask` is 1 for the min edge, 4 for the max one).\nfunction probeGaps(\n index: SnapIndex,\n ax: number,\n mask: number,\n wholeBox: boolean,\n threshold: number,\n): void {\n gapFound = false;\n if (index.candCount === 0) return;\n const pa = 1 - ax;\n const m0 = mv[ax];\n const m1 = mv[ax + 2];\n const p0 = mv[pa];\n const p1 = mv[pa + 2];\n findNeighbours(index, ax, m0, m1, p0, p1);\n const before = nbBefore;\n const after = nbAfter;\n const beforeEdge = nbBeforeEdge;\n const afterEdge = nbAfterEdge;\n const gl = ax === 0 ? index.gapsX : index.gapsY;\n if (wholeBox && before >= 0 && after >= 0) {\n const free = afterEdge - beforeEdge - (m1 - m0);\n if (free > 2 * SNAP_EPS) {\n const delta = beforeEdge + free / 2 - m0;\n const abs = Math.abs(delta);\n if (abs <= threshold) offerGap(abs, delta, 0, free / 2);\n }\n }\n if (before >= 0 && (wholeBox || mask === 1)) {\n probeGapSizes(index, gl, m0 - beforeEdge, 1, 0, pa, p0, p1, threshold);\n }\n if (after >= 0 && (wholeBox || mask === 4)) {\n probeGapSizes(index, gl, afterEdge - m1, -1, 2, pa, p0, p1, threshold);\n }\n}\n\n// ── Width / height match ──────────────────────────────────────────────────────────────────────────\n\n// Best size match so far on the current axis.\nlet sizeFound = false;\nlet sizeAbs = 0;\nlet sizeDelta = 0;\nlet sizeOwner = -1;\n\nfunction offerSize(abs: number, delta: number, owner: number): void {\n if (!sizeFound || abs < sizeAbs - SNAP_EPS) {\n sizeFound = true;\n sizeAbs = abs;\n sizeDelta = delta;\n sizeOwner = owner;\n }\n}\n\n// A box to match sizes with: one on the moving box's row (it overlaps p0..p1) or in its column (it\n// overlaps m0..m1). Far-away boxes elsewhere on the board do not count.\nfunction nearbyForSize(\n boxes: Float64Array,\n o: number,\n ax: number,\n m0: number,\n m1: number,\n p0: number,\n p1: number,\n): boolean {\n const k = o * 4;\n const pa = 1 - ax;\n return (\n (boxes[k + pa + 2] > p0 && boxes[k + pa] < p1) || (boxes[k + ax + 2] > m0 && boxes[k + ax] < m1)\n );\n}\n\n// Resizing the `edge` (0: min, 2: max) of the moving box along `ax`: the box takes the extent of a\n// nearby box when its current extent is within the threshold of it. The nearest extent in each\n// direction that belongs to a nearby box counts.\nfunction probeSizes(index: SnapIndex, ax: number, edge: number, threshold: number): void {\n sizeFound = false;\n const sizes = ax === 0 ? index.widths : index.heights;\n const v = sizes.v;\n const n = v.length;\n if (n === 0) return;\n const pa = 1 - ax;\n const m0 = mv[ax];\n const m1 = mv[ax + 2];\n const p0 = mv[pa];\n const p1 = mv[pa + 2];\n const w = m1 - m0;\n const boxes = index.boxes;\n const i = lowerBound(v, w);\n for (let j = i; j < n; j++) {\n const d = v[j] - w;\n if (d > threshold) break;\n if (nearbyForSize(boxes, sizes.owner[j], ax, m0, m1, p0, p1)) {\n offerSize(d, edge === 2 ? d : -d, sizes.owner[j]);\n break;\n }\n }\n for (let j = i - 1; j >= 0; j--) {\n const d = w - v[j];\n if (d > threshold) break;\n if (nearbyForSize(boxes, sizes.owner[j], ax, m0, m1, p0, p1)) {\n offerSize(d, edge === 2 ? -d : d, sizes.owner[j]);\n break;\n }\n }\n}\n\n// ── One axis ──────────────────────────────────────────────────────────────────────────────────────\n\n// Outcome per axis (index 0: x, 1: y). `axLine` is the moving line that carries the correction (0: min\n// edge, 1: centre, 2: max edge; for a whole box any value counts as the whole box shifting).\nconst axWin = new Uint8Array(2);\nconst axLine = new Int8Array(2);\nconst axDelta = new Float64Array(2);\n// The gap size a gap snap aims at, the box a size snap matches, and the neighbours of a gap snap.\nconst axGap = new Float64Array(2);\nconst axOwner = new Int32Array(2);\nconst axBefore = new Int32Array(2);\nconst axAfter = new Int32Array(2);\n\n// Alignment, size match and gap snap compete: the smallest |delta| wins, and within SNAP_EPS an\n// alignment beats a size match, which beats a gap.\nfunction snapAxis(\n index: SnapIndex,\n ax: number,\n mask: number,\n wholeBox: boolean,\n threshold: number,\n st: Sticky | null,\n): void {\n const lines = ax === 0 ? index.x : index.y;\n const lo = mv[ax];\n const hi = mv[ax + 2];\n let win = WIN_NONE;\n let abs = 0;\n let delta = 0;\n let line = -1;\n\n bestFound = false;\n if (mask & 1) probe(lines, lo, EDGE, 0, threshold);\n if (mask & 2) probe(lines, (lo + hi) / 2, CENTER, 1, threshold);\n if (mask & 4) probe(lines, hi, EDGE, 2, threshold);\n if (bestFound) {\n win = WIN_ALIGN;\n abs = bestAbs;\n delta = bestDelta;\n line = bestLine;\n }\n\n // Sizes and gaps of a resize only make sense for one dragged edge (a symmetric resize moves both).\n if (!wholeBox && (mask === 1 || mask === 4)) {\n probeSizes(index, ax, mask === 1 ? 0 : 2, threshold);\n if (sizeFound && (win === WIN_NONE || sizeAbs < abs - SNAP_EPS)) {\n win = WIN_SIZE;\n abs = sizeAbs;\n delta = sizeDelta;\n line = mask === 1 ? 0 : 2;\n axOwner[ax] = sizeOwner;\n }\n }\n if (wholeBox || mask === 1 || mask === 4) {\n probeGaps(index, ax, mask, wholeBox, threshold);\n if (gapFound && (win === WIN_NONE || gapAbs < abs - SNAP_EPS)) {\n win = WIN_GAP;\n abs = gapAbs;\n delta = gapDelta;\n line = gapLine;\n axGap[ax] = gapSize;\n axBefore[ax] = nbBefore;\n axAfter[ax] = nbAfter;\n }\n }\n\n // Hysteresis: the target this axis held on the previous call wins while it is within the release\n // distance, unless the fresh winner is clearly nearer.\n if (st !== null && st.win[ax] !== WIN_NONE && mask & LINE_BIT[st.line[ax]]) {\n const l = st.line[ax];\n const pos = l === 0 ? lo : l === 2 ? hi : (lo + hi) / 2;\n const sd = st.target[ax] - pos;\n const sabs = Math.abs(sd);\n if (\n sabs <= threshold * SNAP_RELEASE &&\n (win === WIN_NONE || abs > sabs - threshold * SNAP_SWITCH)\n ) {\n win = st.win[ax];\n delta = sd;\n line = l;\n axGap[ax] = st.gap[ax];\n axOwner[ax] = st.owner[ax];\n axBefore[ax] = st.before[ax];\n axAfter[ax] = st.after[ax];\n }\n }\n if (st !== null) {\n st.win[ax] = win;\n if (win !== WIN_NONE) {\n st.line[ax] = line;\n st.target[ax] = (line === 0 ? lo : line === 2 ? hi : (lo + hi) / 2) + delta;\n st.gap[ax] = axGap[ax];\n st.owner[ax] = axOwner[ax];\n st.before[ax] = axBefore[ax];\n st.after[ax] = axAfter[ax];\n }\n }\n\n axWin[ax] = win;\n axDelta[ax] = delta;\n axLine[ax] = line;\n}\n\n// The mask bit of each moving line (0: min edge, 1: centre, 2: max edge).\nconst LINE_BIT = [1, 2, 4] as const;\n\n// What one result object remembers between calls of a drag (per axis: the winning family, moving\n// line, the coordinate that line was snapped to, and the gap / size details its guides need). Keyed\n// by the result object, and reset when the index changes (a new gesture builds a new index).\ninterface Sticky {\n index: SnapIndex;\n win: Uint8Array;\n line: Int8Array;\n target: Float64Array;\n gap: Float64Array;\n owner: Int32Array;\n before: Int32Array;\n after: Int32Array;\n}\n\nconst stickies = new WeakMap<SnapResult, Sticky>();\n\nfunction stickyFor(out: SnapResult, index: SnapIndex): Sticky {\n let st = stickies.get(out);\n if (!st) {\n st = {\n index,\n win: new Uint8Array(2),\n line: new Int8Array(2),\n target: new Float64Array(2),\n gap: new Float64Array(2),\n owner: new Int32Array(2),\n before: new Int32Array(2),\n after: new Int32Array(2),\n };\n stickies.set(out, st);\n } else if (st.index !== index) {\n st.index = index;\n st.win[0] = WIN_NONE;\n st.win[1] = WIN_NONE;\n }\n return st;\n}\n\n// Forget what `out` held (the next call snaps afresh): for a caller that skipped snapping for a while\n// (the modifier that suspends it) and does not want the old target back.\nexport function resetSnapHysteresis(out: SnapResult): void {\n const st = stickies.get(out);\n if (st) {\n st.win[0] = WIN_NONE;\n st.win[1] = WIN_NONE;\n }\n}\n\n// Sorted, without near-duplicates (within SNAP_EPS), in place.\nfunction uniqueSorted(v: number[]): number[] {\n v.sort((a, b) => a - b);\n let n = 0;\n for (let i = 0; i < v.length; i++) {\n if (n === 0 || v[i] - v[n - 1] > SNAP_EPS) v[n++] = v[i];\n }\n v.length = n;\n return v;\n}\n\n// Add (or extend) the guide at `at`. Coincident moving lines (a zero-width box) and several matching\n// candidates all collapse into one guide per (axis, position, kind), whose marks are merged.\nfunction pushGuide(\n guides: Guide[],\n axis: 'x' | 'y',\n at: number,\n marks: number[],\n extend: number,\n kind: LineGuide['kind'],\n): void {\n for (let i = 0; i < guides.length; i++) {\n const g = guides[i];\n if (g.axis === axis && g.kind === kind && Math.abs(g.at - at) <= SNAP_EPS) {\n const merged = uniqueSorted([...((g as LineGuide).marks ?? []), ...marks]);\n (g as LineGuide).marks = merged;\n g.from = Math.min(g.from, merged[0] - extend);\n g.to = Math.max(g.to, merged[merged.length - 1] + extend);\n return;\n }\n }\n uniqueSorted(marks);\n guides.push({\n axis,\n at,\n from: marks[0] - extend,\n to: marks[marks.length - 1] + extend,\n kind,\n marks,\n });\n}\n\n// Guides for one snapped moving line now sitting at `target`: the candidate lines within SNAP_EPS of\n// it join the guide, the MAX_LINE_BOXES boxes nearest to the moving box. Each leaves its marks (both\n// corners when aligned by an edge, the midpoint when aligned by its centre), and the span runs from the\n// first mark to the last, plus `extend`. `sameLo` / `sameHi` (the\n// moved box's extent across a centre line): a candidate aligned centre to centre with exactly that\n// extent has both its edges on the box's edge lines, whose guides already show it, so it is left out\n// (and the centre guide is dropped when nothing else is on it).\nfunction addGuides(\n guides: Guide[],\n axis: 'x' | 'y',\n index: SnapIndex,\n lines: AxisLines,\n target: number,\n movingKind: number,\n perpLo: number,\n perpHi: number,\n extend: number,\n sameLo = NaN,\n sameHi = NaN,\n): void {\n const v = lines.v;\n const boxes = index.boxes;\n // Along a vertical line the owners' extent is their y range, along a horizontal one their x range;\n // `ext*` is the extent across the line (to recognise a box of the moving box's size).\n const loOff = axis === 'x' ? 1 : 0;\n const hiOff = axis === 'x' ? 3 : 2;\n const extLoOff = axis === 'x' ? 0 : 1;\n const extHiOff = axis === 'x' ? 2 : 3;\n // The candidate boxes on the line, nearest to the moving box first (at most MAX_LINE_BOXES: on a\n // dense board a whole column lines up, and the far ones only add clutter).\n let kept = 0;\n const end = target + SNAP_EPS;\n for (let j = lowerBound(v, target - SNAP_EPS); j < v.length && v[j] <= end; j++) {\n const o = lines.owner[j] * 4;\n const lo = boxes[o + loOff];\n const hi = boxes[o + hiOff];\n const k = lines.kind[j];\n if (\n k === CENTER &&\n Math.abs(boxes[o + extLoOff] - sameLo) <= SNAP_EPS &&\n Math.abs(boxes[o + extHiOff] - sameHi) <= SNAP_EPS\n ) {\n continue;\n }\n const d = Math.max(0, lo - perpHi, perpLo - hi);\n let slot = kept;\n while (slot > 0 && lineD[slot - 1] > d) slot--;\n if (slot >= MAX_LINE_BOXES) continue;\n for (let q = Math.min(kept, MAX_LINE_BOXES - 1); q > slot; q--) {\n lineD[q] = lineD[q - 1];\n lineA[q] = lineA[q - 1];\n lineB[q] = lineB[q - 1];\n }\n lineD[slot] = d;\n // An edge match marks both corners; a centre match its midpoint (twice: one code path).\n lineA[slot] = k === CENTER ? (lo + hi) / 2 : lo;\n lineB[slot] = k === CENTER ? (lo + hi) / 2 : hi;\n if (kept < MAX_LINE_BOXES) kept++;\n }\n let main: number[] | null = null;\n if (kept > 0) {\n main = [];\n for (let q = 0; q < kept; q++) main.push(lineA[q], lineB[q]);\n }\n if (main === null) return;\n // The moving box's own marks.\n const ownLo = movingKind === CENTER ? (perpLo + perpHi) / 2 : perpLo;\n const ownHi = movingKind === CENTER ? ownLo : perpHi;\n main.push(ownLo, ownHi);\n pushGuide(guides, axis, target, main, extend, movingKind === CENTER ? 'center' : 'edge');\n}\n\n// At most this many candidate boxes are marked on one alignment guide (the nearest), and their scratch.\nconst MAX_LINE_BOXES = 6;\nconst lineD = new Float64Array(MAX_LINE_BOXES);\nconst lineA = new Float64Array(MAX_LINE_BOXES);\nconst lineB = new Float64Array(MAX_LINE_BOXES);\n\n// Markers of a gap snap along `ax`, measured from the corrected box `fb`: the moving box's gap to each\n// neighbour that now has the target size, then the existing gaps of that size on its row (at most\n// MAX_REF_GAPS), which are the ones it was matched to.\nfunction addGapGuides(guides: Guide[], index: SnapIndex, ax: number): void {\n const boxes = index.boxes;\n const pa = 1 - ax;\n const axis = AXES[ax];\n const size = axGap[ax];\n const label = Math.round(size);\n const m0 = fb[ax];\n const m1 = fb[ax + 2];\n const p0 = fb[pa];\n const p1 = fb[pa + 2];\n const before = axBefore[ax];\n const after = axAfter[ax];\n if (before >= 0) {\n const k = before * 4;\n const edge = boxes[k + ax + 2];\n if (Math.abs(m0 - edge - size) <= SNAP_EPS) {\n const at = (Math.max(boxes[k + pa], p0) + Math.min(boxes[k + pa + 2], p1)) / 2;\n guides.push({ axis, at, from: edge, to: m0, kind: 'gap', label });\n }\n }\n if (after >= 0) {\n const k = after * 4;\n const edge = boxes[k + ax];\n if (Math.abs(edge - m1 - size) <= SNAP_EPS) {\n const at = (Math.max(boxes[k + pa], p0) + Math.min(boxes[k + pa + 2], p1)) / 2;\n guides.push({ axis, at, from: m1, to: edge, kind: 'gap', label });\n }\n }\n const gl = ax === 0 ? index.gapsX : index.gapsY;\n const v = gl.v;\n // The matching gaps on the row nearest to the moving box (by the distance between centres along\n // the axis), at most MAX_REF_GAPS, kept sorted in a small insertion list.\n const mid = (m0 + m1) / 2;\n let kept = 0;\n let scanned = 0;\n for (\n let j = lowerBound(v, size - SNAP_EPS);\n j < v.length && v[j] <= size + SNAP_EPS && scanned < REF_GAP_SCAN;\n j++, scanned++\n ) {\n if (!gapInRow(index, gl, j, pa, p0, p1)) continue;\n const d = Math.abs((boxes[gl.before[j] * 4 + ax + 2] + boxes[gl.after[j] * 4 + ax]) / 2 - mid);\n let slot = kept;\n while (slot > 0 && refDist[slot - 1] > d) slot--;\n if (slot >= MAX_REF_GAPS) continue;\n for (let q = Math.min(kept, MAX_REF_GAPS - 1); q > slot; q--) {\n refDist[q] = refDist[q - 1];\n refIdx[q] = refIdx[q - 1];\n }\n refDist[slot] = d;\n refIdx[slot] = j;\n if (kept < MAX_REF_GAPS) kept++;\n }\n for (let r = 0; r < kept; r++) {\n const j = refIdx[r];\n const ka = gl.before[j] * 4;\n const kb = gl.after[j] * 4;\n const at =\n (Math.max(boxes[ka + pa], boxes[kb + pa]) +\n Math.min(boxes[ka + pa + 2], boxes[kb + pa + 2])) /\n 2;\n guides.push({\n axis,\n at,\n from: boxes[ka + ax + 2],\n to: boxes[kb + ax],\n kind: 'gap',\n label,\n });\n }\n}\n\n// Scratch of `addGapGuides`: the nearest reference gaps so far.\nconst refDist = new Float64Array(MAX_REF_GAPS);\nconst refIdx = new Int32Array(MAX_REF_GAPS);\n\n// One extent marker across the middle of box `o` (the resized box itself when `o` is -1).\nfunction pushSizeGuide(\n guides: Guide[],\n index: SnapIndex,\n ax: number,\n o: number,\n label: number,\n): void {\n const pa = 1 - ax;\n let lo: number;\n let hi: number;\n let plo: number;\n let phi: number;\n if (o < 0) {\n lo = fb[ax];\n hi = fb[ax + 2];\n plo = fb[pa];\n phi = fb[pa + 2];\n } else {\n const k = o * 4;\n lo = index.boxes[k + ax];\n hi = index.boxes[k + ax + 2];\n plo = index.boxes[k + pa];\n phi = index.boxes[k + pa + 2];\n }\n guides.push({ axis: AXES[ax], at: (plo + phi) / 2, from: lo, to: hi, kind: 'width', label });\n}\n\n// Markers of a size match along `ax`: the corrected box `fb` and the box it matched, plus any other\n// nearby boxes of that exact extent (up to MAX_SIZE_MATCHES boxes in all).\nfunction addSizeGuides(guides: Guide[], index: SnapIndex, ax: number): void {\n const size = fb[ax + 2] - fb[ax];\n const label = Math.round(size);\n const winner = axOwner[ax];\n pushSizeGuide(guides, index, ax, -1, label);\n pushSizeGuide(guides, index, ax, winner, label);\n const sizes = ax === 0 ? index.widths : index.heights;\n const v = sizes.v;\n const pa = 1 - ax;\n let matched = 1;\n for (\n let j = lowerBound(v, size - SNAP_EPS);\n j < v.length && v[j] <= size + SNAP_EPS && matched < MAX_SIZE_MATCHES;\n j++\n ) {\n const o = sizes.owner[j];\n if (o === winner) continue;\n if (!nearbyForSize(index.boxes, o, ax, fb[ax], fb[ax + 2], fb[pa], fb[pa + 2])) continue;\n pushSizeGuide(guides, index, ax, o, label);\n matched++;\n }\n}\n\nfunction newResult(): SnapResult {\n return { dx: 0, dy: 0, guides: [] };\n}\n\n// Shared by move and resize. `maskX` / `maskY` select which moving lines may snap on each axis\n// (bit 0: min edge, bit 1: centre, bit 2: max edge). A move uses all three; a resize only the\n// dragged edges. The winning line of each axis is shifted by its correction, which decides the final\n// box the guides are measured from: a move shifts the whole box, a resize only the dragged edge.\nfunction snap(\n index: SnapIndex,\n moving: Box,\n maskX: number,\n maskY: number,\n wholeBox: boolean,\n threshold: number,\n extend: number,\n out: SnapResult,\n): SnapResult {\n out.dx = 0;\n out.dy = 0;\n out.edgeX = undefined;\n out.edgeY = undefined;\n out.guides.length = 0;\n if (!(threshold > 0) || index.count === 0 || (maskX === 0 && maskY === 0)) return out;\n\n mv[0] = moving.minX;\n mv[1] = moving.minY;\n mv[2] = moving.maxX;\n mv[3] = moving.maxY;\n axWin[0] = WIN_NONE;\n axWin[1] = WIN_NONE;\n const st = stickyFor(out, index);\n if (maskX !== 0) snapAxis(index, 0, maskX, wholeBox, threshold, st);\n else st.win[0] = WIN_NONE;\n if (maskY !== 0) snapAxis(index, 1, maskY, wholeBox, threshold, st);\n else st.win[1] = WIN_NONE;\n const winX = axWin[0];\n const winY = axWin[1];\n if (winX === WIN_NONE && winY === WIN_NONE) return out;\n\n // The box after the correction: the guides are measured against it.\n const lineX = winX !== WIN_NONE ? axLine[0] : -1;\n const lineY = winY !== WIN_NONE ? axLine[1] : -1;\n const dx = winX !== WIN_NONE ? axDelta[0] : 0;\n const dy = winY !== WIN_NONE ? axDelta[1] : 0;\n out.dx = dx;\n out.dy = dy;\n if (!wholeBox) {\n if (lineX >= 0) out.edgeX = lineX === 0 ? 'min' : 'max';\n if (lineY >= 0) out.edgeY = lineY === 0 ? 'min' : 'max';\n }\n const shiftMinX = lineX >= 0 && (wholeBox || lineX === 0);\n const shiftMaxX = lineX >= 0 && (wholeBox || lineX === 2);\n const shiftMinY = lineY >= 0 && (wholeBox || lineY === 0);\n const shiftMaxY = lineY >= 0 && (wholeBox || lineY === 2);\n const minX = shiftMinX ? moving.minX + dx : moving.minX;\n const maxX = shiftMaxX ? moving.maxX + dx : moving.maxX;\n const minY = shiftMinY ? moving.minY + dy : moving.minY;\n const maxY = shiftMaxY ? moving.maxY + dy : moving.maxY;\n const guides = out.guides;\n\n // Alignment guides for whatever ended up on a line, whichever family won the axis.\n if (lineX >= 0) {\n if (wholeBox) {\n addGuides(guides, 'x', index, index.x, minX, EDGE, minY, maxY, extend);\n addGuides(guides, 'x', index, index.x, maxX, EDGE, minY, maxY, extend);\n const cx = (minX + maxX) / 2;\n addGuides(guides, 'x', index, index.x, cx, CENTER, minY, maxY, extend, minX, maxX);\n } else {\n const at = lineX === 0 ? minX : maxX;\n addGuides(guides, 'x', index, index.x, at, EDGE, minY, maxY, extend);\n }\n }\n if (lineY >= 0) {\n if (wholeBox) {\n addGuides(guides, 'y', index, index.y, minY, EDGE, minX, maxX, extend);\n addGuides(guides, 'y', index, index.y, maxY, EDGE, minX, maxX, extend);\n const cy = (minY + maxY) / 2;\n addGuides(guides, 'y', index, index.y, cy, CENTER, minX, maxX, extend, minY, maxY);\n } else {\n const at = lineY === 0 ? minY : maxY;\n addGuides(guides, 'y', index, index.y, at, EDGE, minX, maxX, extend);\n }\n }\n\n if (winX === WIN_GAP || winX === WIN_SIZE || winY === WIN_GAP || winY === WIN_SIZE) {\n fb[0] = minX;\n fb[1] = minY;\n fb[2] = maxX;\n fb[3] = maxY;\n if (winX === WIN_GAP) addGapGuides(guides, index, 0);\n else if (winX === WIN_SIZE) addSizeGuides(guides, index, 0);\n if (winY === WIN_GAP) addGapGuides(guides, index, 1);\n else if (winY === WIN_SIZE) addSizeGuides(guides, index, 1);\n }\n return out;\n}\n\n// Moving a whole box (a card, or a multi-selection's union). The smallest |delta| within\n// `thresholdWorld` wins over the three lines of each axis and the gap snaps; ties prefer\n// centre-to-centre, then edge-to-edge, and an alignment over a gap. Pass `out`\n// to reuse one result object across a drag.\nexport function snapMove(\n index: SnapIndex,\n moving: Box,\n thresholdWorld: number,\n extendWorld: number,\n out: SnapResult = newResult(),\n): SnapResult {\n return snap(index, moving, 7, 7, true, thresholdWorld, extendWorld, out);\n}\n\n// Resizing: only the dragged edges snap (a centre moves with the box, so it never does), to lines, to\n// the box's width / height matching a nearby box's, and to equal gaps next to the dragged edge. The\n// correction applies to the dragged edge's coordinate: `dx` to the left or right edge, `dy` to the\n// top or bottom one. If both opposite edges of an axis are flagged (a symmetric resize), only the\n// nearer one snaps to a line and sizes and gaps are skipped; `edgeX` / `edgeY` then say which edge the\n// correction belongs to.\nexport function snapResize(\n index: SnapIndex,\n moving: Box,\n edges: ResizeEdges,\n thresholdWorld: number,\n extendWorld: number,\n out: SnapResult = newResult(),\n): SnapResult {\n const maskX = (edges.left ? 1 : 0) | (edges.right ? 4 : 0);\n const maskY = (edges.top ? 1 : 0) | (edges.bottom ? 4 : 0);\n return snap(index, moving, maskX, maskY, false, thresholdWorld, extendWorld, out);\n}\n","// The snapping session of a drag or a resize: smart guides (alignment, equal gaps, size matches against\n// the cards around) plus an optional snap to the background grid. Built once at gesture start from the\n// cards near the viewport, then asked on every pointer move.\nimport type { Store } from '../store';\nimport type { Element } from '../types';\nimport type { Rect } from '../math';\nimport type { Box } from './geometry';\nimport { boxCx, boxCy, elementBox } from './geometry';\nimport {\n buildSnapIndex,\n GUIDE_OVERSHOOT_PX,\n resetSnapHysteresis,\n snapMove,\n snapResize,\n SNAP_THRESHOLD_PX,\n type Guide,\n type ResizeEdges,\n type SnapIndex,\n type SnapResult,\n} from './snapping';\n\n// At most this many cards are indexed (the nearest to the viewport centre): the equal-gap search is\n// quadratic in the worst case.\nconst MAX_CANDIDATES = 400;\n// The viewport grown by this fraction on every side is searched for candidates.\nconst VIEW_GROW = 0.25;\n\nexport interface SnapSettings {\n // Alignment lines, equal gaps and size matches against other cards, drawn as guides.\n guides: boolean;\n // Snap to the background dot grid where no guide snapped.\n grid: boolean;\n}\n\nexport const DEFAULT_SNAPPING: SnapSettings = { guides: true, grid: false };\n\n// What a resize snap asks of the caller: see `SnapSession.resize`.\nexport interface ResizeSnap {\n dx: number;\n dy: number;\n edgeX?: 'min' | 'max';\n edgeY?: 'min' | 'max';\n guides: readonly Guide[];\n}\n\nconst isAxis = (g: Guide, axis: 'x' | 'y'): boolean => g.axis === axis;\n\nexport class SnapSession {\n private index: SnapIndex | null = null;\n private zoom = 1;\n private readonly result: SnapResult = { dx: 0, dy: 0, guides: [] };\n private readonly hits: Element[] = [];\n\n constructor(\n private readonly settings: SnapSettings,\n private readonly gridSize: number,\n ) {}\n\n // `view` is the visible world rect; `exclude` are the cards being moved.\n begin(store: Store, view: Rect, zoom: number, exclude: ReadonlySet<string>): void {\n this.zoom = zoom > 0 ? zoom : 1;\n this.index = null;\n resetSnapHysteresis(this.result);\n if (!this.settings.guides) return;\n const gx = (view.x1 - view.x0) * VIEW_GROW;\n const gy = (view.y1 - view.y0) * VIEW_GROW;\n const box: Box = { minX: view.x0 - gx, minY: view.y0 - gy, maxX: view.x1 + gx, maxY: view.y1 + gy };\n const cx = (view.x0 + view.x1) / 2;\n const cy = (view.y0 + view.y1) / 2;\n const cands: { id: string; box: Box; d: number }[] = [];\n for (const el of store.searchInto(box, this.hits)) {\n if (exclude.has(el.id)) continue;\n const b = elementBox(el);\n cands.push({ id: el.id, box: b, d: Math.hypot(boxCx(b) - cx, boxCy(b) - cy) });\n }\n if (cands.length > MAX_CANDIDATES) {\n cands.sort((a, b) => a.d - b.d);\n cands.length = MAX_CANDIDATES;\n }\n this.index = buildSnapIndex(cands);\n }\n\n end(): void {\n this.index = null;\n }\n\n private gridDelta(v: number): number {\n const g = this.gridSize;\n return Math.round(v / g) * g - v;\n }\n\n // The correction to add to a box being moved, and the guides to draw.\n move(box: Box): { dx: number; dy: number; guides: readonly Guide[] } {\n const threshold = SNAP_THRESHOLD_PX / this.zoom;\n let dx = 0;\n let dy = 0;\n let guides: readonly Guide[] = [];\n if (this.index) {\n const r = snapMove(this.index, box, threshold, GUIDE_OVERSHOOT_PX / this.zoom, this.result);\n dx = r.dx;\n dy = r.dy;\n guides = r.guides;\n }\n if (this.settings.grid) {\n const gx = this.gridDelta(box.minX);\n const gy = this.gridDelta(box.minY);\n if (!guides.some((g) => isAxis(g, 'x')) && Math.abs(gx) <= threshold) dx = gx;\n if (!guides.some((g) => isAxis(g, 'y')) && Math.abs(gy) <= threshold) dy = gy;\n }\n return { dx, dy, guides };\n }\n\n // The correction to add to the dragged edges of a box being resized. A symmetric resize flags both\n // edges of an axis: `edgeX` / `edgeY` then say which one the correction belongs to.\n resize(box: Box, edges: ResizeEdges): ResizeSnap {\n const threshold = SNAP_THRESHOLD_PX / this.zoom;\n let dx = 0;\n let dy = 0;\n let edgeX: 'min' | 'max' | undefined;\n let edgeY: 'min' | 'max' | undefined;\n let guides: readonly Guide[] = [];\n if (this.index) {\n const r = snapResize(\n this.index,\n box,\n edges,\n threshold,\n GUIDE_OVERSHOOT_PX / this.zoom,\n this.result,\n );\n dx = r.dx;\n dy = r.dy;\n edgeX = r.edgeX;\n edgeY = r.edgeY;\n guides = r.guides;\n }\n if (this.settings.grid) {\n if (!guides.some((g) => isAxis(g, 'x'))) {\n const g = this.gridEdge(box.minX, box.maxX, edges.left, edges.right, threshold);\n if (g) {\n dx = g.delta;\n edgeX = g.edge;\n }\n }\n if (!guides.some((g) => isAxis(g, 'y'))) {\n const g = this.gridEdge(box.minY, box.maxY, edges.top, edges.bottom, threshold);\n if (g) {\n dy = g.delta;\n edgeY = g.edge;\n }\n }\n }\n return { dx, dy, edgeX, edgeY, guides };\n }\n\n // The grid correction of the flagged edge of an axis (the nearer one when both are), within the threshold.\n private gridEdge(\n min: number,\n max: number,\n lo: boolean | undefined,\n hi: boolean | undefined,\n threshold: number,\n ): { delta: number; edge: 'min' | 'max' } | null {\n const a = lo ? this.gridDelta(min) : Infinity;\n const b = hi ? this.gridDelta(max) : Infinity;\n const delta = Math.abs(a) <= Math.abs(b) ? a : b;\n if (!(Math.abs(delta) <= threshold)) return null;\n return { delta, edge: delta === a ? 'min' : 'max' };\n }\n}\n","// The interaction layer: pointer, wheel, touch and keyboard on the board's host element.\n//\n// wheel / pinch pan and zoom (ctrl or cmd + wheel zooms about the cursor)\n// drag on empty pans (with inertia); with Shift it draws a marquee instead (`emptyDrag: 'marquee'`\n// flips the two)\n// click / shift select / toggle a card; click on empty clears\n// drag a card moves the selection, snapping to guides and the grid; Shift locks the axis\n// drag a handle resizes (aspect-locked cards keep their ratio; Alt resizes about the centre)\n// keys Delete removes, Esc clears, Cmd/Ctrl+A selects all, arrows nudge, 0 fits, 1 = 100 %\n//\n// During a gesture the cards are drawn at a preview rect by the stage (nothing is written to the store);\n// the store is updated once on release. No undo, no history.\nimport { Emitter } from '../events';\nimport type { SelectionVisual } from '../render/overlay';\nimport type { Stage } from '../render/stage';\nimport { GRID } from '../render/stage';\nimport type { Store } from '../store';\nimport type { Element, ElementId } from '../types';\nimport type { Box, WorldRect } from './geometry';\nimport { boxUnion, worldRectOf } from './geometry';\nimport type { Guide } from './snapping';\nimport { geometryBox, handleAt, selectionHandles, type HandleId, type SelectionHandles } from './handles';\nimport { hitTest } from './hitTest';\nimport { elementsInBox } from './marquee';\nimport { outlineOf, type OutlineRect } from './outline';\nimport { ResizeSession, type Mods } from './resize';\nimport { SnapSession, type SnapSettings } from './snap';\n\nexport interface InteractionOptions {\n // Selecting, moving and resizing cards (default true). With false the layer only pans and zooms.\n select?: boolean;\n // What dragging the empty canvas does (default 'pan'); Shift does the other one.\n emptyDrag?: 'pan' | 'marquee';\n // Keyboard shortcuts on the focused board (default true).\n keyboard?: boolean;\n // Dragging and resizing write to the store on release, arrow keys on each press (default true). With\n // false the layer only emits 'transform' with the proposed rects and leaves the cards where they are.\n commit?: boolean;\n // Rubber-band selection (default true). With false a drag on the empty canvas always pans, Shift or not.\n marquee?: boolean;\n // A drag on the empty canvas pans without clearing the selection first; a click that does not move still\n // clears it (default false: the selection is cleared as soon as the pointer goes down on empty canvas).\n keepSelectionOnPan?: boolean;\n // Draw the selection outline and the resize handles on the canvas (default true). With false the layer\n // still selects, moves and resizes (the handles keep their hit areas) but draws no selection: the host\n // draws its own. The hover outline is not part of it.\n selectionOutline?: boolean;\n}\n\nexport interface InteractionEvents {\n selection: { ids: readonly ElementId[] };\n hover: { id: ElementId | null };\n click: { id: ElementId | null; shift: boolean; x: number; y: number };\n dblclick: { id: ElementId | null; x: number; y: number };\n // A drag or resize ended: the new rect of every card it touched (already written to the store unless\n // `commit` is false).\n transform: {\n kind: 'move' | 'resize';\n rects: ReadonlyMap<ElementId, { x: number; y: number; w: number; h: number }>;\n };\n // A gesture started / ended ('pan' | 'marquee' | 'drag' | 'resize' | 'pinch'; null when it ended).\n gesture: { kind: 'pan' | 'marquee' | 'drag' | 'resize' | 'pinch' | null };\n // The pointer device changed between touch and mouse / pen (touch has no hover).\n touch: { touch: boolean };\n // Delete pressed with a selection: the ids that were removed.\n delete: { ids: readonly ElementId[] };\n}\n\nconst DRAG_THRESHOLD_PX = 3;\nconst NUDGE = 1;\nconst NUDGE_BIG = 10;\nconst round2 = (v: number): number => Math.round(v * 100) / 100;\n\ntype Gesture =\n // `noClick`: the pan began as a drag of a locked card, so letting go is not a click on the canvas.\n | { kind: 'pan'; x: number; y: number; clearOnClick?: boolean; noClick?: boolean }\n | { kind: 'pinch'; dist: number; mx: number; my: number }\n | {\n kind: 'marquee';\n // Where it began: in world space (the box) and in screen space (is it a click).\n sx: number;\n sy: number;\n x: number;\n y: number;\n base: readonly ElementId[];\n additive: boolean;\n }\n | {\n kind: 'press';\n id: ElementId;\n x: number;\n y: number;\n shift: boolean;\n wasSelected: boolean;\n }\n | {\n kind: 'drag';\n ids: readonly ElementId[];\n start: { x: number; y: number };\n rects: Map<ElementId, WorldRect>;\n box: Box;\n snap: SnapSession;\n moved: boolean;\n }\n | { kind: 'resize'; session: ResizeSession; snap: SnapSession; handle: HandleId };\n\nexport class Interaction {\n readonly events = new Emitter<InteractionEvents>();\n selection: readonly ElementId[] = [];\n readonly snapping: SnapSettings;\n\n private readonly opts: Required<InteractionOptions>;\n private gesture: Gesture | null = null;\n private readonly pointers = new Map<number, { x: number; y: number }>();\n private pointerType = 'mouse';\n private hoverId: ElementId | null = null;\n private selDirty = true;\n private spaceDown = false;\n // A host-driven hand tool (`setPanMode`): like holding Space.\n private panMode = false;\n private handles: SelectionHandles | null = null;\n // The zoom the handles were built at: an edge too short on screen has no handle, so they follow the zoom.\n private handlesScale = 1;\n // Whether the stage had previews at the last frame.\n private hadPreviews = false;\n private lastMods: Mods = { shift: false, alt: false, ctrl: false };\n private readonly cleanups: (() => void)[] = [];\n private disposed = false;\n\n constructor(\n private readonly host: HTMLElement,\n private readonly stage: Stage,\n private readonly store: Store,\n snapping: SnapSettings,\n options: InteractionOptions = {},\n ) {\n this.snapping = snapping;\n this.opts = {\n select: options.select ?? true,\n emptyDrag: options.emptyDrag ?? 'pan',\n keyboard: options.keyboard ?? true,\n commit: options.commit ?? true,\n marquee: options.marquee ?? true,\n keepSelectionOnPan: options.keepSelectionOnPan ?? false,\n selectionOutline: options.selectionOutline ?? true,\n };\n this.bind();\n this.cleanups.push(\n this.store.subscribe((e) => {\n if (e.type !== 'change') return;\n const gone = e.change.removed;\n if (gone.length > 0) this.dropRemoved(new Set(gone.map((g) => g.id)));\n this.selDirty = true;\n this.stage.requestFrame();\n }),\n this.stage.onFrame(() => this.onFrame()),\n );\n }\n\n // ── Selection ──────────────────────────────────────────────────────────────\n setSelection(ids: readonly ElementId[]): void {\n const next = ids.filter((id, i) => this.store.has(id) && ids.indexOf(id) === i);\n const same =\n next.length === this.selection.length && next.every((id, i) => id === this.selection[i]);\n if (same) return;\n this.selection = next;\n this.selDirty = true;\n this.events.emit('selection', { ids: next });\n this.stage.requestFrame();\n }\n\n // A hand tool the host can switch (a toolbar button, a key of its own): while on, a left-button drag\n // pans the canvas wherever it starts, over a card included, exactly as with Space held.\n setPanMode(on: boolean): void {\n this.panMode = on;\n if (on) this.setHover(null);\n }\n\n // Cards left the store: out of the selection, the hover and the gesture that holds them.\n private dropRemoved(dead: ReadonlySet<ElementId>): void {\n if (this.selection.length > 0) {\n const next = this.selection.filter((id) => !dead.has(id));\n if (next.length !== this.selection.length) this.setSelection(next);\n }\n if (this.hoverId !== null && dead.has(this.hoverId)) this.setHover(null);\n const g = this.gesture;\n if (g?.kind === 'press') {\n if (dead.has(g.id)) this.cancelGesture();\n } else if (g?.kind === 'drag') {\n const left = g.ids.filter((id) => !dead.has(id));\n if (left.length === g.ids.length) return;\n for (const id of g.ids) {\n if (!dead.has(id)) continue;\n g.rects.delete(id);\n this.stage.clearPreview(id);\n this.stage.pin(id, false);\n }\n if (left.length === 0) {\n this.cancelGesture();\n return;\n }\n g.ids = left;\n let box: Box | null = null;\n for (const r of g.rects.values()) {\n const b = geometryBox([r]) as Box;\n box = box ? boxUnion(box, b) : b;\n }\n g.box = box as Box;\n } else if (g?.kind === 'resize') {\n const lost = g.session.affected.filter((id) => dead.has(id));\n if (lost.length === 0) return;\n for (const id of lost) {\n this.stage.clearPreview(id);\n this.stage.pin(id, false);\n }\n // The rest keeps scaling about the box it started in.\n if (lost.length === g.session.affected.length) this.cancelGesture();\n }\n }\n\n // ── Frame ──────────────────────────────────────────────────────────────────\n private onFrame(): void {\n const g = this.gesture;\n const live = g !== null && (g.kind === 'drag' || g.kind === 'resize');\n if (this.stage.cam.scale !== this.handlesScale) this.selDirty = true;\n // Cards drawn at a preview that is not ours (a layout animation) move under the selection: it follows\n // them, handles hidden, and is drawn once more at the store's rects when the previews are gone.\n const previewed = this.stage.previewCount > 0;\n if (previewed || this.hadPreviews) this.selDirty = true;\n this.hadPreviews = previewed;\n if (!this.selDirty && !live) return;\n this.selDirty = false;\n const visual = this.selectionVisual(!live && !previewed);\n this.stage.overlay.setSelection(this.opts.selectionOutline ? visual : null);\n if (live) this.stage.requestFrame();\n }\n\n private selectionVisual(showHandles: boolean): SelectionVisual | null {\n this.handlesScale = this.stage.cam.scale;\n const els: Element[] = [];\n for (const id of this.selection) {\n const el = this.store.get(id);\n if (el) els.push(el);\n }\n this.handles = null;\n if (els.length === 0) return null;\n const rects = els.map((el) => this.stage.previewRectOf(el.id) ?? worldRectOf(el));\n if (els.length === 1) {\n this.handles = selectionHandles(this.store, this.selection, this.stage.cam.scale);\n return {\n frame: outlineOf(els[0], rects[0]),\n members: [],\n handles: this.handles?.handles ?? [],\n showHandles: showHandles && this.handles !== null,\n };\n }\n const b = geometryBox(rects) as Box;\n this.handles = selectionHandles(this.store, this.selection, this.stage.cam.scale);\n return {\n frame: { x: b.minX, y: b.minY, w: b.maxX - b.minX, h: b.maxY - b.minY, rot: 0, radius: 0 },\n members: els.map((el, i) => outlineOf(el, rects[i])),\n handles: this.handles?.handles ?? [],\n showHandles: showHandles && this.handles !== null,\n };\n }\n\n // ── Input ──────────────────────────────────────────────────────────────────\n private bind(): void {\n const host = this.host;\n host.tabIndex = 0;\n host.style.outline = 'none';\n host.style.touchAction = 'none';\n const on = <K extends keyof HTMLElementEventMap>(\n type: K,\n fn: (e: HTMLElementEventMap[K]) => void,\n opts?: AddEventListenerOptions,\n ): void => {\n host.addEventListener(type, fn as EventListener, opts);\n this.cleanups.push(() => host.removeEventListener(type, fn as EventListener, opts));\n };\n on('wheel', (e) => this.onWheel(e), { passive: false });\n on('pointerdown', (e) => this.onDown(e));\n on('pointermove', (e) => this.onMove(e));\n on('pointerup', (e) => this.onUp(e));\n on('pointercancel', (e) => this.onUp(e, true));\n // The capture went away under a held button (the element was hidden, the browser took the pointer\n // back): no pointerup is coming.\n on('lostpointercapture', (e) => {\n if (this.pointers.has(e.pointerId)) this.onUp(e, true);\n });\n on('pointerleave', () => this.setHover(null));\n on('dblclick', (e) => this.onDblClick(e));\n on('keydown', (e) => this.onKey(e));\n on('contextmenu', (e) => {\n if (this.gesture) e.preventDefault();\n });\n // Space is let go wherever focus is by then (a key released in another window, or after focus moved\n // off the board, never reaches the host): listen on the window, and drop it when the window blurs.\n const releaseSpace = (e: KeyboardEvent): void => {\n if (e.code === 'Space') this.spaceDown = false;\n };\n // A window that loses focus mid-gesture never hears the pointerup either: the gesture is dropped.\n const onBlur = (): void => {\n this.spaceDown = false;\n this.cancelGesture();\n this.pointers.clear();\n };\n window.addEventListener('keyup', releaseSpace);\n window.addEventListener('blur', onBlur);\n this.cleanups.push(() => {\n window.removeEventListener('keyup', releaseSpace);\n window.removeEventListener('blur', onBlur);\n });\n }\n\n private local(e: { clientX: number; clientY: number }): { x: number; y: number } {\n return this.stage.clientToLocal(e.clientX, e.clientY);\n }\n\n private mods(e: { shiftKey: boolean; altKey: boolean; ctrlKey: boolean; metaKey: boolean }): Mods {\n this.lastMods = { shift: e.shiftKey, alt: e.altKey, ctrl: e.ctrlKey || e.metaKey };\n return this.lastMods;\n }\n\n private onWheel(e: WheelEvent): void {\n e.preventDefault();\n const p = this.local(e);\n this.stage.cam.wheel({\n x: p.x,\n y: p.y,\n deltaX: e.deltaX,\n deltaY: e.deltaY,\n deltaMode: e.deltaMode,\n zoom: e.ctrlKey || e.metaKey,\n });\n this.setHover(null);\n }\n\n private startGesture(g: Gesture): void {\n this.gesture = g;\n if (g.kind === 'press') return;\n this.events.emit('gesture', { kind: g.kind });\n }\n\n private endGesture(): void {\n const g = this.gesture;\n this.gesture = null;\n this.stage.overlay.setGuides([]);\n this.stage.overlay.setMarquee(null);\n this.host.style.cursor = '';\n this.selDirty = true;\n this.stage.requestFrame();\n if (g && g.kind !== 'press') this.events.emit('gesture', { kind: null });\n }\n\n private onDown(e: PointerEvent): void {\n if (e.button !== 0 && e.button !== 1) return;\n this.host.focus({ preventScroll: true });\n try {\n this.host.setPointerCapture(e.pointerId);\n } catch {\n // Synthetic events carry no active pointer.\n }\n const touch = e.pointerType === 'touch';\n if (touch !== (this.pointerType === 'touch')) this.events.emit('touch', { touch });\n this.pointerType = e.pointerType;\n const p = this.local(e);\n // This pointer is already down: the release of its last press never came. That gesture is over.\n if (this.gesture && this.pointers.has(e.pointerId)) this.cancelGesture();\n this.pointers.set(e.pointerId, p);\n this.mods(e);\n this.setHover(null);\n\n if (this.pointers.size === 2) {\n this.cancelGesture();\n this.stage.cam.dragEnd(-1e9);\n const [a, b] = [...this.pointers.values()];\n this.startGesture({\n kind: 'pinch',\n dist: Math.hypot(a.x - b.x, a.y - b.y),\n mx: (a.x + b.x) / 2,\n my: (a.y + b.y) / 2,\n });\n return;\n }\n if (this.pointers.size > 2) return;\n\n const stage = this.stage;\n const w = stage.screenToWorld(p.x, p.y);\n if (e.button === 1 || this.spaceDown || this.panMode || !this.opts.select) {\n this.beginPan(p, e);\n return;\n }\n // A handle of the current selection? Built now: the zoom may have moved since the last frame.\n const sel =\n this.selection.length > 0 ? selectionHandles(this.store, this.selection, stage.cam.scale) : null;\n if (sel) {\n const h = handleAt(sel, w.x, w.y, stage.cam.scale);\n if (h) {\n const session = new ResizeSession(this.store, this.selection, h.id, w);\n if (session.affected.length > 0) {\n const snap = new SnapSession(this.snapping, GRID);\n snap.begin(this.store, stage.cam.visibleRect(), stage.cam.scale, new Set(session.affected));\n this.startGesture({ kind: 'resize', session, snap, handle: h.id });\n for (const id of session.affected) stage.pin(id, true);\n this.selDirty = true;\n return;\n }\n }\n }\n const hit = hitTest(this.store, w.x, w.y, { zoom: stage.cam.scale });\n if (hit) {\n const wasSelected = this.selection.includes(hit.id);\n if (e.shiftKey) {\n // Shift on a selected card takes it out of the selection when let go without a drag (see onUp): a\n // drag moves the whole selection, this card included.\n if (!wasSelected) this.setSelection([...this.selection, hit.id]);\n } else if (!wasSelected) {\n this.setSelection([hit.id]);\n }\n this.startGesture({ kind: 'press', id: hit.id, x: p.x, y: p.y, shift: e.shiftKey, wasSelected });\n return;\n }\n // Empty canvas.\n const marquee = this.opts.marquee && (this.opts.emptyDrag === 'marquee') !== e.shiftKey;\n if (marquee) {\n this.startGesture({\n kind: 'marquee',\n sx: w.x,\n sy: w.y,\n x: p.x,\n y: p.y,\n base: e.shiftKey ? this.selection : [],\n additive: e.shiftKey,\n });\n if (!e.shiftKey) this.setSelection([]);\n } else {\n const keep = this.opts.keepSelectionOnPan;\n if (!e.shiftKey && !keep) this.setSelection([]);\n this.beginPan(p, e, keep && !e.shiftKey);\n }\n }\n\n private beginPan(\n p: { x: number; y: number },\n e: PointerEvent,\n clearOnClick = false,\n noClick = false,\n ): void {\n this.startGesture({ kind: 'pan', x: p.x, y: p.y, clearOnClick, noClick });\n this.stage.cam.dragStart(p.x, p.y, e.timeStamp);\n this.host.style.cursor = 'grabbing';\n }\n\n private onMove(e: PointerEvent): void {\n const p = this.local(e);\n const m = this.mods(e);\n if (!this.pointers.has(e.pointerId)) {\n if (e.buttons === 0 && e.pointerType !== 'touch') this.updateHover(p);\n return;\n }\n const g = this.gesture;\n // A mouse that moves with no button down let go where we could not hear it (outside the window): the\n // gesture is over, dropped like a pointercancel.\n if (g && e.pointerType === 'mouse' && e.buttons === 0) {\n this.onUp(e, true);\n return;\n }\n this.pointers.set(e.pointerId, p);\n if (!g) return;\n const stage = this.stage;\n switch (g.kind) {\n case 'pan':\n stage.cam.dragMove(p.x, p.y, e.timeStamp);\n break;\n case 'pinch': {\n if (this.pointers.size < 2) break;\n const [a, b] = [...this.pointers.values()];\n const dist = Math.hypot(a.x - b.x, a.y - b.y);\n const mx = (a.x + b.x) / 2;\n const my = (a.y + b.y) / 2;\n stage.cam.pinch(mx, my, dist / Math.max(1, g.dist), mx - g.mx, my - g.my);\n g.dist = dist;\n g.mx = mx;\n g.my = my;\n break;\n }\n case 'marquee': {\n const w = stage.screenToWorld(p.x, p.y);\n const box: Box = {\n minX: Math.min(g.sx, w.x),\n minY: Math.min(g.sy, w.y),\n maxX: Math.max(g.sx, w.x),\n maxY: Math.max(g.sy, w.y),\n };\n stage.overlay.setMarquee(box);\n const inside = elementsInBox(this.store, box, 'touch');\n this.setSelection(g.additive ? [...new Set([...g.base, ...inside])] : inside);\n break;\n }\n case 'press': {\n if (Math.hypot(p.x - g.x, p.y - g.y) < DRAG_THRESHOLD_PX) break;\n this.beginDrag(g, p);\n break;\n }\n case 'drag':\n this.updateDrag(g, p, m);\n break;\n case 'resize':\n this.updateResize(g, p, m);\n break;\n }\n }\n\n private beginDrag(press: Extract<Gesture, { kind: 'press' }>, p: { x: number; y: number }): void {\n const stage = this.stage;\n const ids = this.selection.filter((id) => {\n const el = this.store.get(id);\n return el !== undefined && !el.locked;\n });\n if (ids.length === 0) {\n // Locked card: dragging it pans the canvas instead (and is not a click on the canvas).\n this.gesture = null;\n this.beginPan(p, { timeStamp: performance.now() } as PointerEvent, false, true);\n return;\n }\n const rects = new Map<ElementId, WorldRect>();\n let box: Box | null = null;\n for (const id of ids) {\n const el = this.store.get(id) as Element;\n const r = worldRectOf(el);\n rects.set(id, r);\n stage.pin(id, true);\n const b = geometryBox([r]) as Box;\n box = box ? boxUnion(box, b) : b;\n }\n const snap = new SnapSession(this.snapping, GRID);\n snap.begin(this.store, stage.cam.visibleRect(), stage.cam.scale, new Set(ids));\n const start = stage.screenToWorld(press.x, press.y);\n this.startGesture({ kind: 'drag', ids, start, rects, box: box as Box, snap, moved: false });\n this.host.style.cursor = 'grabbing';\n this.store.bringToFront(ids);\n this.updateDrag(this.gesture as Extract<Gesture, { kind: 'drag' }>, p, this.lastMods);\n }\n\n private updateDrag(g: Extract<Gesture, { kind: 'drag' }>, p: { x: number; y: number }, m: Mods): void {\n const stage = this.stage;\n const w = stage.screenToWorld(p.x, p.y);\n let dx = w.x - g.start.x;\n let dy = w.y - g.start.y;\n // Shift locks the move to the dominant axis.\n if (m.shift) {\n if (Math.abs(dx) >= Math.abs(dy)) dy = 0;\n else dx = 0;\n }\n g.moved = true;\n const moved: Box = {\n minX: g.box.minX + dx,\n minY: g.box.minY + dy,\n maxX: g.box.maxX + dx,\n maxY: g.box.maxY + dy,\n };\n if (m.ctrl) {\n stage.overlay.setGuides([]);\n } else {\n const s = g.snap.move(moved);\n if (!(m.shift && dx === 0)) dx += s.dx;\n if (!(m.shift && dy === 0)) dy += s.dy;\n stage.overlay.setGuides(s.guides as Guide[]);\n }\n for (const [id, r] of g.rects) stage.setPreview(id, r.x + dx, r.y + dy, r.w, r.h, r.rot);\n this.selDirty = true;\n }\n\n private updateResize(g: Extract<Gesture, { kind: 'resize' }>, p: { x: number; y: number }, m: Mods): void {\n const stage = this.stage;\n const w = stage.screenToWorld(p.x, p.y);\n let guides: readonly Guide[] = [];\n const patches = g.session.update(w, m, (box, edges) => {\n const s = g.snap.resize(box, edges);\n guides = s.guides;\n return s;\n });\n stage.overlay.setGuides(m.ctrl ? [] : (guides as Guide[]));\n for (const [id, patch] of patches) {\n const el = this.store.get(id);\n if (el) stage.setPreview(id, patch.x, patch.y, patch.w, patch.h, el.rot);\n }\n this.selDirty = true;\n }\n\n private onUp(e: PointerEvent, cancelled = false): void {\n if (!this.pointers.has(e.pointerId)) return;\n const p = this.local(e);\n this.pointers.delete(e.pointerId);\n try {\n this.host.releasePointerCapture(e.pointerId);\n } catch {\n // Already released.\n }\n const g = this.gesture;\n if (!g) return;\n const stage = this.stage;\n switch (g.kind) {\n case 'pan':\n stage.cam.dragEnd(cancelled ? -1e9 : e.timeStamp);\n if (!cancelled && !g.noClick && Math.hypot(p.x - g.x, p.y - g.y) < DRAG_THRESHOLD_PX) {\n if (g.clearOnClick) this.setSelection([]);\n this.emitClick(null, e, p);\n }\n break;\n case 'pinch':\n if (this.pointers.size < 2) {\n this.gesture = null;\n this.events.emit('gesture', { kind: null });\n return;\n }\n return;\n case 'marquee':\n if (!cancelled && Math.hypot(p.x - g.x, p.y - g.y) < DRAG_THRESHOLD_PX) this.emitClick(null, e, p);\n break;\n case 'press':\n if (!cancelled) {\n if (g.shift) {\n if (g.wasSelected) this.setSelection(this.selection.filter((i) => i !== g.id));\n } else if (g.wasSelected && this.selection.length > 1) this.setSelection([g.id]);\n this.emitClick(g.id, e, p);\n }\n break;\n case 'drag':\n if (cancelled) this.cancelDrag(g);\n else this.commitDrag(g);\n break;\n case 'resize':\n if (cancelled) this.cancelResize(g);\n else this.commitResize(g);\n break;\n }\n this.endGesture();\n }\n\n private emitClick(id: ElementId | null, e: PointerEvent, p: { x: number; y: number }): void {\n const w = this.stage.screenToWorld(p.x, p.y);\n this.events.emit('click', { id, shift: e.shiftKey, x: w.x, y: w.y });\n }\n\n private onDblClick(e: MouseEvent): void {\n const w = this.stage.screenToWorld(this.local(e).x, this.local(e).y);\n const hit = hitTest(this.store, w.x, w.y, { zoom: this.stage.cam.scale });\n this.events.emit('dblclick', { id: hit?.id ?? null, x: w.x, y: w.y });\n }\n\n // Drops the previews of a cancelled gesture.\n private cancelGesture(): void {\n const g = this.gesture;\n if (g?.kind === 'drag') this.cancelDrag(g);\n else if (g?.kind === 'resize') this.cancelResize(g);\n else if (g?.kind === 'pan') this.stage.cam.dragEnd(-1e9);\n if (g) this.endGesture();\n }\n\n private cancelDrag(g: Extract<Gesture, { kind: 'drag' }>): void {\n for (const id of g.ids) {\n this.stage.clearPreview(id);\n this.stage.pin(id, false);\n }\n }\n\n private cancelResize(g: Extract<Gesture, { kind: 'resize' }>): void {\n for (const id of g.session.affected) {\n this.stage.clearPreview(id);\n this.stage.pin(id, false);\n }\n }\n\n // `ids`: every card the gesture held (previewed and pinned), whether or not it ends up in `rects`.\n private commit(\n kind: 'move' | 'resize',\n ids: readonly ElementId[],\n rects: Map<ElementId, { x: number; y: number; w: number; h: number }>,\n ): void {\n const stage = this.stage;\n if (this.opts.commit) {\n this.store.batch(() => {\n for (const [id, r] of rects) {\n this.store.update(id, { x: r.x, y: r.y, w: r.w, h: r.h });\n }\n });\n }\n for (const id of ids) {\n stage.clearPreview(id);\n stage.pin(id, false);\n }\n if (rects.size > 0) this.events.emit('transform', { kind, rects });\n }\n\n private commitDrag(g: Extract<Gesture, { kind: 'drag' }>): void {\n if (!g.moved) {\n this.cancelDrag(g);\n return;\n }\n const out = new Map<ElementId, { x: number; y: number; w: number; h: number }>();\n for (const id of g.ids) {\n const p = this.stage.previewRectOf(id);\n if (p && this.store.has(id)) out.set(id, { x: round2(p.x), y: round2(p.y), w: p.w, h: p.h });\n }\n this.commit('move', g.ids, out);\n }\n\n private commitResize(g: Extract<Gesture, { kind: 'resize' }>): void {\n const out = new Map<ElementId, { x: number; y: number; w: number; h: number }>();\n for (const id of g.session.affected) {\n const p = this.stage.previewRectOf(id);\n if (p && this.store.has(id)) {\n out.set(id, { x: round2(p.x), y: round2(p.y), w: round2(p.w), h: round2(p.h) });\n }\n }\n this.commit('resize', g.session.affected, out);\n }\n\n // ── Hover and cursor ───────────────────────────────────────────────────────\n private updateHover(p: { x: number; y: number }): void {\n if (this.gesture || !this.opts.select || this.panMode) return;\n const stage = this.stage;\n const w = stage.screenToWorld(p.x, p.y);\n const h = this.handles ? handleAt(this.handles, w.x, w.y, stage.cam.scale) : null;\n if (h) {\n this.host.style.cursor = h.cursor;\n this.setHover(null);\n return;\n }\n this.host.style.cursor = '';\n const hit = hitTest(this.store, w.x, w.y, { zoom: stage.cam.scale });\n this.setHover(hit ? hit.id : null);\n }\n\n private setHover(id: ElementId | null): void {\n if (id === this.hoverId) return;\n this.hoverId = id;\n const el = id ? this.store.get(id) : undefined;\n const showOutline = el !== undefined && !this.selection.includes(el.id);\n const r: OutlineRect | null = showOutline\n ? outlineOf(el as Element, worldRectOf(el as Element))\n : null;\n this.stage.overlay.setHover(r);\n this.events.emit('hover', { id });\n }\n\n // ── Keyboard ───────────────────────────────────────────────────────────────\n private onKey(e: KeyboardEvent): void {\n // Keydown bubbles from everything inside the host (an overlay's <input>, a toolbar button): only keys\n // pressed on the board itself are the board's.\n if (e.target !== this.host) return;\n if (e.code === 'Space') {\n this.spaceDown = true;\n e.preventDefault();\n return;\n }\n if (!this.opts.keyboard) return;\n const stage = this.stage;\n const cmd = e.metaKey || e.ctrlKey;\n if (cmd && e.key.toLowerCase() === 'a' && this.opts.select) {\n this.setSelection([...this.store.ids()]);\n } else if (e.key === 'Escape') {\n this.setSelection([]);\n } else if ((e.key === 'Delete' || e.key === 'Backspace') && this.selection.length > 0) {\n const ids = this.selection.filter((id) => !this.store.get(id)?.locked);\n if (ids.length === 0) return;\n this.store.remove(ids);\n this.events.emit('delete', { ids });\n } else if (e.key.startsWith('Arrow') && this.selection.length > 0 && !cmd) {\n const step = e.shiftKey ? NUDGE_BIG : NUDGE;\n const dx = e.key === 'ArrowLeft' ? -step : e.key === 'ArrowRight' ? step : 0;\n const dy = e.key === 'ArrowUp' ? -step : e.key === 'ArrowDown' ? step : 0;\n const rects = new Map<ElementId, { x: number; y: number; w: number; h: number }>();\n // With `commit: false` the host moves the cards itself: it only gets the proposal.\n this.store.batch(() => {\n for (const id of this.selection) {\n const el = this.store.get(id);\n if (!el || el.locked) continue;\n if (this.opts.commit) this.store.update(id, { x: el.x + dx, y: el.y + dy });\n rects.set(id, { x: el.x + dx, y: el.y + dy, w: el.w, h: el.h });\n }\n });\n if (rects.size > 0) this.events.emit('transform', { kind: 'move', rects });\n } else if (cmd) {\n return;\n } else if (e.key === '0') {\n if (this.selection.length > 0) stage.fitRect(stage.contentBounds(this.selection));\n else if (this.store.size > 0) stage.fit();\n } else if (e.key === '1') {\n stage.zoomToActual();\n } else if (e.key === '+' || e.key === '=') {\n stage.zoomBy(1.25);\n } else if (e.key === '-') {\n stage.zoomBy(0.8);\n } else return;\n e.preventDefault();\n }\n\n dispose(): void {\n if (this.disposed) return;\n this.disposed = true;\n for (const f of this.cleanups) f();\n this.events.clear();\n }\n}\n","// Masonry packing: the one primitive behind both the placement of new cards and \"tidy into a grid\".\n// Pure: items in, rectangles relative to the block's top-left out.\nimport { DEFAULTS } from '../types';\n\nexport const PLACEMENT_FALLBACK_WIDTH: number = DEFAULTS.cardWidth;\nexport const PLACEMENT_FALLBACK_ASPECT: number = DEFAULTS.cardAspect;\n\nexport interface LayoutItem {\n // Height / width. 0, negative, NaN or missing falls back to PLACEMENT_FALLBACK_ASPECT.\n aspect: number;\n // Explicit width. Such an item sits left-aligned in a column slot.\n w?: number;\n // Explicit height. Only for items that keep their exact size (tidy keeps a free-aspect card's real\n // height instead of re-deriving it from a rounded aspect).\n h?: number;\n}\n\nexport interface LayoutRect {\n x: number;\n y: number;\n w: number;\n h: number;\n}\n\nexport interface MasonryResult {\n rects: LayoutRect[];\n // Bounds of the block: gaps only between items, none after the last.\n width: number;\n height: number;\n}\n\nexport function effectiveAspect(aspect: number | undefined): number {\n return aspect !== undefined && Number.isFinite(aspect) && aspect > 0\n ? aspect\n : PLACEMENT_FALLBACK_ASPECT;\n}\n\n// Column slot width that never lets an item with its own (larger) width spill into the next\n// column: callers that mix fixed-width items with resized cards pass it as `opts.slot`.\nexport function slotWidth(items: readonly LayoutItem[], width: number): number {\n let slot = width;\n for (let i = 0; i < items.length; i++) {\n const w = items[i].w;\n if (w !== undefined && w > slot) slot = w;\n }\n return slot;\n}\n\n// Items go in order into the shortest column, the leftmost when tied. Heights are integers\n// (width * aspect rounded) so equal-height columns tie exactly and the layout is reproducible.\nexport function masonry(\n items: readonly LayoutItem[],\n opts: { width: number; gap: number; columns: number; slot?: number },\n): MasonryResult {\n const cols = Math.max(1, Math.floor(opts.columns));\n const slot = (opts.slot ?? opts.width) + opts.gap;\n // Where the next item of each column starts (previous bottom + gap; 0 while empty).\n const next = new Float64Array(cols);\n const rects = new Array<LayoutRect>(items.length);\n let width = 0;\n let height = 0;\n for (let i = 0; i < items.length; i++) {\n const it = items[i];\n let c = 0;\n let best = next[0];\n for (let k = 1; k < cols; k++) {\n if (next[k] < best) {\n best = next[k];\n c = k;\n }\n }\n const w = it.w !== undefined && it.w > 0 ? it.w : opts.width;\n const h =\n it.h !== undefined && it.h > 0\n ? it.h\n : Math.max(1, Math.round(w * effectiveAspect(it.aspect)));\n const x = c * slot;\n const y = best;\n rects[i] = { x, y, w, h };\n next[c] = y + h + opts.gap;\n if (x + w > width) width = x + w;\n if (y + h > height) height = y + h;\n }\n return { rects, width, height };\n}\n","// Tiny numeric helpers shared by the layout modules. Pure.\n\nexport const clamp = (v: number, lo: number, hi: number): number => (v < lo ? lo : v > hi ? hi : v);\n\n// Median of a list (the mean of the two middle values for an even count); 0 for an empty list.\n// Sorts a copy: the callers run once per carry or per command, never per frame.\nexport function median(values: readonly number[]): number {\n const n = values.length;\n if (n === 0) return 0;\n // Float64Array#sort is numeric (a plain Array#sort would compare as strings).\n const sorted = Float64Array.from(values).sort();\n const mid = n >> 1;\n return n % 2 === 1 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;\n}\n","// Reading order of boxes laid out in rows (or, along x, in columns): the order \"tidy\" lays cards out\n// in and the order align / separate stack them in. Pure.\nimport { boxCx, boxCy, boxH, boxW, type Box } from '../interact/geometry';\nimport { median } from './stats';\n\nconst byId = (a: { id: string }, b: { id: string }): number =>\n a.id < b.id ? -1 : a.id > b.id ? 1 : 0;\n\n// Bands along `axis` ('y': rows, top to bottom; 'x': columns, left to right), each band sorted along the\n// other axis. Items are clustered by centre (a band's tolerance is half the median extent along `axis`,\n// measured from the band's running mean centre), so cards of a row that differ in height stay one row\n// instead of being shuffled by their centres.\nexport function bandOrder<T extends { id: string; box: Box }>(\n items: readonly T[],\n axis: 'x' | 'y' = 'y',\n): T[] {\n const along = axis === 'y' ? boxCy : boxCx;\n const across = (b: Box): number => (axis === 'y' ? b.minX : b.minY);\n const tol = median(items.map((it) => (axis === 'y' ? boxH(it.box) : boxW(it.box)))) / 2;\n const sorted = items.slice().sort((a, b) => along(a.box) - along(b.box) || byId(a, b));\n const bands: T[][] = [];\n let band: T[] = [];\n let sum = 0;\n for (const it of sorted) {\n const c = along(it.box);\n if (band.length > 0 && c - sum / band.length > tol) {\n bands.push(band);\n band = [];\n sum = 0;\n }\n band.push(it);\n sum += c;\n }\n if (band.length > 0) bands.push(band);\n\n const ordered: T[] = [];\n for (const b of bands) {\n b.sort((x, y) => across(x.box) - across(y.box) || byId(x, y));\n for (const it of b) ordered.push(it);\n }\n return ordered;\n}\n","// Placement: where a block of new cards lands. Computed once and re-run only when its inputs change;\n// while a pointer moves the caller can just translate the cached result. Everything is in world space.\nimport type { Box } from '../interact/geometry';\nimport {\n PLACEMENT_FALLBACK_ASPECT,\n PLACEMENT_FALLBACK_WIDTH,\n effectiveAspect,\n masonry,\n slotWidth,\n type LayoutItem,\n type LayoutRect,\n} from './masonry';\nimport { clamp, median } from './stats';\n\n// Below this many cards on the board the median is noise: use the default card width.\nconst MIN_CARDS_FOR_MEDIAN = 3;\nconst MIN_GAP = 12;\nconst MAX_GAP = 48;\nconst MIN_COLUMNS = 2;\nconst MAX_COLUMNS = 10;\n\n// W: the median width of the cards already on the canvas, so new cards blend in (>= 3 cards),\n// else the default card width.\nexport function placementWidth(existingCardWidths: readonly number[]): number {\n const widths: number[] = [];\n for (let i = 0; i < existingCardWidths.length; i++) {\n const w = existingCardWidths[i];\n if (Number.isFinite(w) && w > 0) widths.push(w);\n }\n return widths.length >= MIN_CARDS_FOR_MEDIAN ? median(widths) : PLACEMENT_FALLBACK_WIDTH;\n}\n\n// G: a tenth of the width, kept between 12 and 48 so tiny cards still breathe and huge ones\n// don't float apart.\nexport function placementGap(width: number): number {\n return clamp(Math.round(width / 10), MIN_GAP, MAX_GAP);\n}\n\n// c: roughly square block. One item is one column; Shift (singleRow) lays everything out in a row.\nexport function placementColumns(n: number, meanAspect: number, singleRow = false): number {\n if (n <= 1) return 1;\n if (singleRow) return n;\n return clamp(Math.round(Math.sqrt(n * effectiveAspect(meanAspect))), MIN_COLUMNS, MAX_COLUMNS);\n}\n\nexport interface PlacementInput {\n items: readonly LayoutItem[];\n existingCardWidths: readonly number[];\n // Shift held: a single row.\n singleRow?: boolean;\n anchor: // The block's top-left sits exactly at (x, y): n == 1, the caller keeps the grab offset.\n | { kind: 'grab'; x: number; y: number }\n // The block is centred on (x, y): n >= 2, the drop scatters outward from the stack.\n | { kind: 'center'; x: number; y: number };\n}\n\nexport interface PlacementResult {\n // World rectangles in input order.\n rects: LayoutRect[];\n // Bounds of the block (what snapping and the outline use).\n bounds: Box;\n // The item width W (not the block width: that is boxW(bounds)).\n width: number;\n gap: number;\n columns: number;\n}\n\n// Pure and cheap (100 items: well under a millisecond): the caller caches the result per carry\n// and only moves it with translatePlacement[InPlace].\nexport function planPlacement(input: PlacementInput): PlacementResult {\n const { items, anchor } = input;\n const n = items.length;\n const width = placementWidth(input.existingCardWidths);\n const gap = placementGap(width);\n\n let aspectSum = 0;\n for (let i = 0; i < n; i++) aspectSum += effectiveAspect(items[i].aspect);\n const meanAspect = n > 0 ? aspectSum / n : PLACEMENT_FALLBACK_ASPECT;\n const columns = placementColumns(n, meanAspect, input.singleRow);\n\n const block = masonry(items, { width, gap, columns, slot: slotWidth(items, width) });\n const ox = anchor.kind === 'center' ? anchor.x - block.width / 2 : anchor.x;\n const oy = anchor.kind === 'center' ? anchor.y - block.height / 2 : anchor.y;\n const rects = block.rects;\n for (let i = 0; i < rects.length; i++) {\n rects[i].x += ox;\n rects[i].y += oy;\n }\n return {\n rects,\n bounds: { minX: ox, minY: oy, maxX: ox + block.width, maxY: oy + block.height },\n width,\n gap,\n columns,\n };\n}\n\n// Shifted copy; the input is untouched.\nexport function translatePlacement(\n result: PlacementResult,\n dx: number,\n dy: number,\n): PlacementResult {\n const rects = new Array<LayoutRect>(result.rects.length);\n for (let i = 0; i < rects.length; i++) {\n const r = result.rects[i];\n rects[i] = { x: r.x + dx, y: r.y + dy, w: r.w, h: r.h };\n }\n const b = result.bounds;\n return {\n ...result,\n rects,\n bounds: { minX: b.minX + dx, minY: b.minY + dy, maxX: b.maxX + dx, maxY: b.maxY + dy },\n };\n}\n\n// Per-pointer-move path: no allocation, mutates the cached result and returns it.\nexport function translatePlacementInPlace(\n result: PlacementResult,\n dx: number,\n dy: number,\n): PlacementResult {\n const rects = result.rects;\n for (let i = 0; i < rects.length; i++) {\n rects[i].x += dx;\n rects[i].y += dy;\n }\n const b = result.bounds;\n b.minX += dx;\n b.maxX += dx;\n b.minY += dy;\n b.maxY += dy;\n return result;\n}\n","// Align / distribute / equal width. Pure; the results are deltas and sizes the\n// caller turns into ops. Everything works on world AABBs (rotation and paint pad included), so\n// \"aligned\" means the visible edges line up.\n//\n// Lining boxes up is, on its own, what makes a board pile up: align everything to the left and\n// every card of a row lands on the same spot. So `align` and `distribute` take a gap\n// (`opts.gap`, see `arrangeGap`): with it the edge is still the one asked for, but whatever would end up\n// on top of another box (or closer than the gap) slides along the OTHER axis until it is clear. Without\n// it they are the plain geometric operations.\nimport { boxCx, boxCy, boxH, boxW, type Box } from '../interact/geometry';\nimport { PLACEMENT_FALLBACK_WIDTH } from './masonry';\nimport { bandOrder } from './order';\nimport { placementGap } from './placement';\nimport { median } from './stats';\n\nexport type AlignMode = 'left' | 'centerX' | 'right' | 'top' | 'middleY' | 'bottom';\n\nexport interface Delta {\n dx: number;\n dy: number;\n}\n\n// Anything below this is floating point noise, not a move.\nconst EPS = 1e-9;\n// Two boxes are clear of each other when the room between them is the gap, give or take this.\nconst CLEAR_EPS = 1e-6;\n\nexport interface ArrangeOpts {\n // The room kept between boxes that would otherwise touch or overlap. Absent: no overlap handling.\n gap?: number;\n}\n\n// The gap an arrange keeps between the selected items: the placement gap of their median width (the same\n// `placementGap` the grid and the placement of new cards use).\nexport function arrangeGap(widths: readonly number[]): number {\n const w = median(widths.filter((v) => Number.isFinite(v) && v > 0));\n return placementGap(w > 0 ? w : PLACEMENT_FALLBACK_WIDTH);\n}\n\nconst shifted = (b: Box, d: Delta | undefined): Box =>\n d === undefined\n ? b\n : { minX: b.minX + d.dx, minY: b.minY + d.dy, maxX: b.maxX + d.dx, maxY: b.maxY + d.dy };\n\nconst addDelta = (out: Map<string, Delta>, id: string, d: Delta): void => {\n const prev = out.get(id);\n const dx = (prev?.dx ?? 0) + d.dx;\n const dy = (prev?.dy ?? 0) + d.dy;\n if (Math.abs(dx) > EPS || Math.abs(dy) > EPS) out.set(id, { dx, dy });\n else out.delete(id);\n};\n\n// Slides boxes apart until none is on top of another or closer than `gap`: the minimal moves, the first\n// of every pile staying where it is. Items are settled one after the other; one that collides with the\n// ones already settled goes past them, to the right or down by whichever is shorter (`axis` forces\n// one). Only ever right or down, so a box that has cleared another stays clear of it and the loop ends.\n//\n// Order: the bands of `axis` (a row stays in its left-to-right order, a column in its top-to-bottom\n// one), else reading order (rows, then left to right); `inOrder` takes the items as given (the caller\n// ordered them on their boxes from before a move). Pure; returns the deltas of the boxes that moved.\nexport function separate(\n items: readonly { id: string; box: Box }[],\n gap: number,\n axis?: 'x' | 'y',\n inOrder = false,\n): Map<string, Delta> {\n const out = new Map<string, Delta>();\n const n = items.length;\n if (n < 2) return out;\n const g = Number.isFinite(gap) && gap > 0 ? gap : 0;\n const order = inOrder ? items : bandOrder(items, axis ?? 'y');\n const placed: Box[] = [];\n for (const it of order) {\n let box = it.box;\n let dx = 0;\n let dy = 0;\n // Every pass clears all the boxes it hit for good: at most one pass per settled box.\n for (let pass = 0; pass <= placed.length; pass++) {\n let farX = -Infinity;\n let farY = -Infinity;\n for (const p of placed) {\n if (\n box.minX < p.maxX + g - CLEAR_EPS &&\n p.minX < box.maxX + g - CLEAR_EPS &&\n box.minY < p.maxY + g - CLEAR_EPS &&\n p.minY < box.maxY + g - CLEAR_EPS\n ) {\n if (p.maxX > farX) farX = p.maxX;\n if (p.maxY > farY) farY = p.maxY;\n }\n }\n if (farX === -Infinity) break;\n const right = farX + g - box.minX;\n const down = farY + g - box.minY;\n const goRight = axis === 'x' || (axis === undefined && right <= down);\n const step = goRight ? { dx: right, dy: 0 } : { dx: 0, dy: down };\n box = shifted(box, step);\n dx += step.dx;\n dy += step.dy;\n }\n placed.push(box);\n if (Math.abs(dx) > EPS || Math.abs(dy) > EPS) out.set(it.id, { dx, dy });\n }\n return out;\n}\n\n// Move every item so the chosen edge or centre matches the union box of the items. Items that\n// already are aligned are omitted. With `opts.gap` the items that would pile up on the aligned edge\n// slide along the other axis (a row aligned left becomes a column, in the row's order).\nexport function align(\n items: readonly { id: string; box: Box }[],\n mode: AlignMode,\n opts: ArrangeOpts = {},\n): Map<string, Delta> {\n const out = new Map<string, Delta>();\n if (items.length < 2) return out;\n let minX = Infinity;\n let minY = Infinity;\n let maxX = -Infinity;\n let maxY = -Infinity;\n for (const { box } of items) {\n if (box.minX < minX) minX = box.minX;\n if (box.minY < minY) minY = box.minY;\n if (box.maxX > maxX) maxX = box.maxX;\n if (box.maxY > maxY) maxY = box.maxY;\n }\n for (const { id, box } of items) {\n let dx = 0;\n let dy = 0;\n switch (mode) {\n case 'left':\n dx = minX - box.minX;\n break;\n case 'centerX':\n dx = (minX + maxX) / 2 - boxCx(box);\n break;\n case 'right':\n dx = maxX - box.maxX;\n break;\n case 'top':\n dy = minY - box.minY;\n break;\n case 'middleY':\n dy = (minY + maxY) / 2 - boxCy(box);\n break;\n case 'bottom':\n dy = maxY - box.maxY;\n break;\n }\n if (Math.abs(dx) > EPS || Math.abs(dy) > EPS) out.set(id, { dx, dy });\n }\n if (opts.gap !== undefined) {\n // The aligned edge fixes one axis; the boxes are free on the other.\n const free = mode === 'left' || mode === 'centerX' || mode === 'right' ? 'y' : 'x';\n // Stacked in the order they had before: once aligned they all share the edge, which says nothing.\n const aligned = bandOrder(items, free).map((it) => ({\n id: it.id,\n box: shifted(it.box, out.get(it.id)),\n }));\n for (const [id, d] of separate(aligned, opts.gap, free, true)) addDelta(out, id, d);\n }\n return out;\n}\n\n// Equal GAPS between consecutive boxes (not equal centres): sorted by position along the axis,\n// the two extremes stay and the ones between slide. Needs three or more items. With `opts.gap` the\n// gap is never smaller than that (a span too short for the boxes would overlap them): then the last\n// ones move on past the far extreme.\nexport function distribute(\n items: readonly { id: string; box: Box }[],\n axis: 'x' | 'y',\n opts: ArrangeOpts = {},\n): Map<string, Delta> {\n const out = new Map<string, Delta>();\n const n = items.length;\n if (n < 3) return out;\n const horizontal = axis === 'x';\n const lo = (b: Box): number => (horizontal ? b.minX : b.minY);\n const hi = (b: Box): number => (horizontal ? b.maxX : b.maxY);\n const size = (b: Box): number => (horizontal ? boxW(b) : boxH(b));\n const centre = (b: Box): number => (horizontal ? boxCx(b) : boxCy(b));\n\n const sorted = items.slice().sort((a, b) => {\n const d = centre(a.box) - centre(b.box) || lo(a.box) - lo(b.box);\n return d !== 0 ? d : a.id < b.id ? -1 : a.id > b.id ? 1 : 0;\n });\n let total = 0;\n for (const it of sorted) total += size(it.box);\n const start = lo(sorted[0].box);\n let gap = (hi(sorted[n - 1].box) - start - total) / (n - 1);\n if (opts.gap !== undefined && gap < opts.gap) gap = opts.gap;\n\n let cursor = start;\n for (const { id, box } of sorted) {\n const d = cursor - lo(box);\n if (Math.abs(d) > EPS) out.set(id, horizontal ? { dx: d, dy: 0 } : { dx: 0, dy: d });\n cursor += size(box) + gap;\n }\n return out;\n}\n\n// Equal width: every item takes the median width; aspect-locked items (cards) scale their\n// height along. Items that already have the median width are omitted.\nexport function equalWidth(\n items: readonly { id: string; w: number; h: number; aspectLocked: boolean }[],\n): Map<string, { w: number; h: number }> {\n const out = new Map<string, { w: number; h: number }>();\n if (items.length === 0) return out;\n const target = median(items.map((it) => it.w));\n for (const it of items) {\n if (Math.abs(it.w - target) <= EPS) continue;\n out.set(it.id, {\n w: target,\n h: it.aspectLocked && it.w > 0 ? (it.h * target) / it.w : it.h,\n });\n }\n return out;\n}\n","// Auto spot: where an inserted block goes when nobody places it by hand. Search outward from the\n// viewport centre for the nearest free position.\nimport { boxCx, boxCy, boxH, boxW, type Box } from '../interact/geometry';\n\nconst DEFAULT_STEP = 48;\nconst DEFAULT_MAX_RADIUS_FACTOR = 2;\n// First window of the search, in rings. The window doubles until the bound, so a mostly empty\n// board never pays for the big lattice.\nconst INITIAL_RINGS = 8;\n// Hard cap on rings (lattice of (2 * 160 + 1)^2 = 103k cells). A viewport at very low zoom spans\n// hundreds of thousands of world px: past the cap the step grows so 2 diagonals still fit.\nconst MAX_RINGS = 160;\n// Tolerance in lattice units so boxes that exactly touch (floating point noise included) stay free.\nconst EPS = 1e-9;\n\n// The lattice the search runs on: the block centred on the viewport (ox, oy is its top-left), the step,\n// and how many rings out the search goes. NaN or infinite inputs give a non-finite `maxRadius`.\nfunction searchPlan(\n block: { w: number; h: number },\n viewport: Box,\n opts: { step?: number; maxRadiusFactor?: number },\n): { ox: number; oy: number; step: number; maxRings: number; maxRadius: number } {\n const step0 = opts.step !== undefined && opts.step > 0 ? opts.step : DEFAULT_STEP;\n const factor = opts.maxRadiusFactor ?? DEFAULT_MAX_RADIUS_FACTOR;\n // Top-left of the block when centred on the viewport.\n const ox = boxCx(viewport) - block.w / 2;\n const oy = boxCy(viewport) - block.h / 2;\n const maxRadius = factor * Math.hypot(boxW(viewport), boxH(viewport));\n\n let step = step0;\n let maxRings = Math.max(1, Math.floor(maxRadius / step));\n if (maxRings > MAX_RINGS) {\n maxRings = MAX_RINGS;\n step = maxRadius / MAX_RINGS;\n }\n return { ox, oy, step, maxRings, maxRadius };\n}\n\n// The world area `autoSpot` can put the block in: only boxes meeting it can block a candidate. Query the\n// store for this, not for the viewport: the search reaches 2 viewport diagonals out, and the block's own\n// size past that.\nexport function autoSpotArea(\n block: { w: number; h: number },\n viewport: Box,\n opts: { step?: number; maxRadiusFactor?: number } = {},\n): Box {\n const { ox, oy, step, maxRings } = searchPlan(block, viewport, opts);\n const reach = step * maxRings;\n return { minX: ox - reach, minY: oy - reach, maxX: ox + block.w + reach, maxY: oy + block.h + reach };\n}\n\n// How the search works: the block's top-left at lattice point p overlaps the box B exactly when\n// p lies strictly inside B grown by the block's size on its min sides, i.e. in the open range\n// (B.min - blockSize, B.max). So instead of testing every candidate against every box, each\n// box paints a rectangle of lattice cells into a 2D difference array; one prefix-sum pass then\n// tells whether any candidate is blocked. Cost: O(boxes + cells), independent of block size.\nexport function autoSpot(\n block: { w: number; h: number },\n viewport: Box,\n occupied: readonly Box[],\n opts: { step?: number; maxRadiusFactor?: number } = {},\n): { x: number; y: number } {\n const { ox, oy, step, maxRings, maxRadius } = searchPlan(block, viewport, opts);\n // A non-finite viewport or block has no lattice (the ring loop would never end): the centre, or the\n // origin when even that is not a number.\n if (!Number.isFinite(maxRadius) || !Number.isFinite(ox) || !Number.isFinite(oy)) {\n return { x: Number.isFinite(ox) ? ox : 0, y: Number.isFinite(oy) ? oy : 0 };\n }\n\n let rings = Math.min(maxRings, INITIAL_RINGS);\n let from = 0; // first ring not yet known to be fully blocked\n for (;;) {\n const found = searchRings(block, ox, oy, step, occupied, rings, from);\n if (found) return { x: ox + found.i * step, y: oy + found.j * step };\n if (rings >= maxRings) break;\n from = rings + 1;\n rings = Math.min(maxRings, rings * 2);\n }\n return { x: ox, y: oy };\n}\n\n// Lattice offsets (i, j) in steps of the first free candidate in rings [from, rings], or null.\n// Ring r holds the offsets with max(|i|, |j|) = r; within a ring the nearest to the centre wins\n// and distance ties go to the first in reading order (top row first, then left).\nfunction searchRings(\n block: { w: number; h: number },\n ox: number,\n oy: number,\n step: number,\n occupied: readonly Box[],\n rings: number,\n from: number,\n): { i: number; j: number } | null {\n const R = rings;\n const side = 2 * R + 1;\n const stride = side + 1; // one extra row/column for the difference array's far edge\n const grid = new Int32Array(stride * stride);\n\n for (let k = 0; k < occupied.length; k++) {\n const b = occupied[k];\n let i0 = Math.floor((b.minX - block.w - ox) / step + EPS) + 1;\n let i1 = Math.ceil((b.maxX - ox) / step - EPS) - 1;\n let j0 = Math.floor((b.minY - block.h - oy) / step + EPS) + 1;\n let j1 = Math.ceil((b.maxY - oy) / step - EPS) - 1;\n if (i0 < -R) i0 = -R;\n if (j0 < -R) j0 = -R;\n if (i1 > R) i1 = R;\n if (j1 > R) j1 = R;\n // Also rejects NaN (invalid boxes) and empty boxes (min = Infinity).\n if (!(i0 <= i1) || !(j0 <= j1)) continue;\n const a = (j0 + R) * stride + (i0 + R);\n const di = i1 - i0 + 1;\n const dj = (j1 - j0 + 1) * stride;\n grid[a] += 1;\n grid[a + di] -= 1;\n grid[a + dj] -= 1;\n grid[a + di + dj] += 1;\n }\n\n // 2D prefix sum in place: grid[j][i] becomes the number of boxes blocking that lattice cell.\n for (let j = 0; j < side; j++) {\n const row = j * stride;\n let run = 0;\n for (let i = 0; i < side; i++) {\n run += grid[row + i];\n grid[row + i] = j > 0 ? run + grid[row - stride + i] : run;\n }\n }\n\n const free = (i: number, j: number): boolean => grid[(j + R) * stride + (i + R)] === 0;\n\n if (from === 0 && free(0, 0)) return { i: 0, j: 0 };\n for (let r = Math.max(1, from); r <= R; r++) {\n let bestI = 0;\n let bestJ = 0;\n let bestD = Infinity;\n // Reading order over the ring's perimeter: the top row, the two side cells of each middle\n // row, the bottom row. The strict `<` keeps the first of equally distant candidates.\n for (let j = -r; j <= r; j++) {\n const edge = j === -r || j === r;\n for (let i = -r; i <= r; i += edge ? 1 : 2 * r) {\n const d = i * i + j * j;\n if (d < bestD && free(i, j)) {\n bestD = d;\n bestI = i;\n bestJ = j;\n }\n }\n }\n if (bestD < Infinity) return { i: bestI, j: bestJ };\n }\n return null;\n}\n\n// True when more than half of the block lies outside the viewport: the camera then flies there.\n// Exactly half visible does not count.\nexport function shouldPanTo(block: Box, viewport: Box): boolean {\n const area = boxW(block) * boxH(block);\n if (area <= 0) {\n // A degenerate block (a line, a point): judge by its centre.\n const x = boxCx(block);\n const y = boxCy(block);\n return x < viewport.minX || x > viewport.maxX || y < viewport.minY || y > viewport.maxY;\n }\n const iw = Math.min(block.maxX, viewport.maxX) - Math.max(block.minX, viewport.minX);\n const ih = Math.min(block.maxY, viewport.maxY) - Math.max(block.minY, viewport.minY);\n const inside = iw > 0 && ih > 0 ? iw * ih : 0;\n return inside < area / 2;\n}\n","// Tidy: reorder cards into a masonry grid in reading order. Pure and in world space; the caller resets\n// any rotation (a move carries no `rot`).\nimport { emptyBox, type Box } from '../interact/geometry';\nimport { effectiveAspect, masonry, slotWidth, type LayoutItem } from './masonry';\nimport { bandOrder } from './order';\nimport { placementGap } from './placement';\nimport { clamp, median } from './stats';\n\nexport interface TidyItem {\n id: string;\n // Items with `fixed` set stay put (they do not take part in the grid).\n fixed?: boolean;\n // A free-aspect item keeps its own size in the grid; the others take the median width and their aspect.\n free?: boolean;\n // World AABB of the painted element (what reading order and the default anchor use).\n box: Box;\n // Element size (what the grid places).\n w: number;\n h: number;\n}\n\nexport interface TidyResult {\n // New world top-left and size of every participating item.\n moves: Map<string, { x: number; y: number; w: number; h: number }>;\n count: number;\n bounds: Box;\n}\n\nconst MAX_COLUMNS = 10;\n\nfunction participates(it: TidyItem): boolean {\n return (\n !it.fixed &&\n Number.isFinite(it.w) &&\n Number.isFinite(it.h) &&\n it.w > 0 &&\n it.h > 0\n );\n}\n\nexport function tidy(\n items: readonly TidyItem[],\n opts: {\n anchor?: { x: number; y: number };\n // Space between items (default: `placementGap` of the median width).\n gap?: number;\n // Number of columns (default: roughly square block, at most 10).\n columns?: number;\n } = {},\n): TidyResult {\n const part = items.filter(participates);\n if (part.length < 2) {\n const at =\n opts.anchor ??\n (part.length === 1 ? { x: part[0].box.minX, y: part[0].box.minY } : { x: 0, y: 0 });\n return {\n moves: new Map(),\n count: 0,\n bounds: { minX: at.x, minY: at.y, maxX: at.x, maxY: at.y },\n };\n }\n\n // 1. Cluster by vertical centre (a row's tolerance is half the median height, measured\n // from the row's running mean centre), rows top to bottom, each sorted left to right.\n const ordered = bandOrder(part, 'y');\n const n = ordered.length;\n\n // 2. W is the median width of the cards; free-aspect items keep their size.\n const cardWidths: number[] = [];\n for (const it of ordered) if (!it.free) cardWidths.push(it.w);\n const width = median(cardWidths.length > 0 ? cardWidths : ordered.map((it) => it.w));\n const gap = opts.gap ?? placementGap(width);\n\n // 3. c = clamp(round(sqrt(n * mean h/w)), 1, 10).\n const layout: LayoutItem[] = new Array<LayoutItem>(n);\n let aspectSum = 0;\n for (let i = 0; i < n; i++) {\n const it = ordered[i];\n const aspect = effectiveAspect(it.h / it.w);\n aspectSum += aspect;\n layout[i] = it.free ? { aspect, w: it.w, h: it.h } : { aspect };\n }\n const columns =\n opts.columns ?? clamp(Math.round(Math.sqrt(n * (aspectSum / n))), 1, MAX_COLUMNS);\n\n // 4. Anchored at the current top-left of what moves (or the caller's anchor). A fixed-size item\n // wider than W gets a wider slot so it cannot overlap the next column.\n const block = masonry(layout, { width, gap, columns, slot: slotWidth(layout, width) });\n let ax: number;\n let ay: number;\n if (opts.anchor) {\n ax = opts.anchor.x;\n ay = opts.anchor.y;\n } else {\n const u = emptyBox();\n for (const it of ordered) {\n if (it.box.minX < u.minX) u.minX = it.box.minX;\n if (it.box.minY < u.minY) u.minY = it.box.minY;\n }\n ax = u.minX;\n ay = u.minY;\n }\n\n const moves: TidyResult['moves'] = new Map();\n for (let i = 0; i < n; i++) {\n const r = block.rects[i];\n moves.set(ordered[i].id, { x: ax + r.x, y: ay + r.y, w: r.w, h: r.h });\n }\n return {\n moves,\n count: n,\n bounds: { minX: ax, minY: ay, maxX: ax + block.width, maxY: ay + block.height },\n };\n}\n","// Auto layout: the pure layout functions (src/layout/*) applied to the elements of a store, with an\n// optional animated transition. Every method takes the ids to arrange (default: all) and writes the\n// result to the store in one batch, right away: the animation only changes how the cards are drawn.\nimport { boxOfRect, elementBox, type Box } from './interact/geometry';\nimport {\n align as alignBoxes,\n arrangeGap,\n autoSpot,\n autoSpotArea,\n distribute as distributeBoxes,\n equalWidth as equalWidths,\n masonry as masonryPack,\n placementColumns,\n placementGap,\n planPlacement,\n separate,\n slotWidth,\n tidy as tidyBoxes,\n effectiveAspect,\n type AlignMode,\n type LayoutItem,\n} from './layout/index';\nimport { median } from './layout/stats';\nimport { clamp } from './math';\nimport type { Stage } from './render/stage';\nimport type { Store } from './store';\nimport type { Element, ElementId } from './types';\n\nexport interface ArrangeOptions {\n // Animate the move (default true; elements far from the viewport jump).\n animate?: boolean;\n // Duration of the animation, ms (default 320).\n duration?: number;\n}\n\nexport interface GridOptions extends ArrangeOptions {\n // Space between cards, world px (default: a tenth of the card width, 12..48).\n gap?: number;\n // Number of columns (default: a roughly square block, at most 10).\n columns?: number;\n}\n\nexport interface MasonryOptions extends GridOptions {\n // Width of every card, world px (default: the median width).\n width?: number;\n}\n\ninterface Rect4 {\n x: number;\n y: number;\n w: number;\n h: number;\n}\n\n// The viewport new cards are placed against while the host has no size.\nconst NOMINAL_VIEW = { w: 1280, h: 800 };\n\nconst ease = (t: number): number => 1 - Math.pow(1 - t, 3);\nconst prefersReducedMotion = (): boolean =>\n typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;\n\ninterface Shown extends Rect4 {\n rot: number;\n}\n\nexport class LayoutApi {\n // The running animation: where each of its cards is drawn now, and the way to end it.\n private animation: { shown: Map<ElementId, Shown>; cancel: () => void } | null = null;\n\n constructor(\n private readonly store: Store,\n private readonly stage: Stage,\n ) {}\n\n private elementsOf(ids?: readonly ElementId[]): Element[] {\n const out: Element[] = [];\n if (ids) {\n for (const id of ids) {\n const el = this.store.get(id);\n if (el) out.push(el);\n }\n } else {\n for (const id of this.store.ids()) out.push(this.store.get(id) as Element);\n }\n return out;\n }\n\n // Reorders the cards into a masonry grid in reading order (rows top to bottom, left to right). Cards\n // take the median width and keep their aspect; the block stays anchored at its current top-left.\n tidy(ids?: readonly ElementId[], opts: GridOptions = {}): void {\n const els = this.elementsOf(ids).filter((e) => !e.locked);\n const result = tidyBoxes(\n els.map((e) => ({\n id: e.id,\n box: elementBox(e),\n w: e.w,\n h: e.h,\n free: !e.aspectLocked,\n })),\n { gap: opts.gap, columns: opts.columns },\n );\n const patches = new Map<ElementId, Rect4>();\n for (const [id, m] of result.moves) patches.set(id, m);\n this.apply(patches, opts, true);\n }\n\n // Packs the cards into columns in the order given (the store's draw order by default): each goes into\n // the shortest column. Unlike `tidy` nothing is reordered by position.\n masonry(ids?: readonly ElementId[], opts: MasonryOptions = {}): void {\n const els = this.elementsOf(ids).filter((e) => !e.locked);\n if (els.length === 0) return;\n const width = opts.width ?? (median(els.map((e) => e.w)) || 248);\n const gap = opts.gap ?? placementGap(width);\n const items: LayoutItem[] = els.map((e) => ({ aspect: effectiveAspect(e.h / e.w) }));\n let aspectSum = 0;\n for (const it of items) aspectSum += it.aspect;\n const columns = opts.columns ?? placementColumns(els.length, aspectSum / els.length);\n const block = masonryPack(items, { width, gap, columns, slot: slotWidth(items, width) });\n let ax = Infinity;\n let ay = Infinity;\n for (const e of els) {\n const b = elementBox(e);\n ax = Math.min(ax, b.minX);\n ay = Math.min(ay, b.minY);\n }\n const patches = new Map<ElementId, Rect4>();\n els.forEach((e, i) => {\n const r = block.rects[i];\n patches.set(e.id, { x: ax + r.x, y: ay + r.y, w: r.w, h: r.h });\n });\n this.apply(patches, opts, true);\n }\n\n align(mode: AlignMode, ids?: readonly ElementId[], opts: ArrangeOptions = {}): void {\n const els = this.elementsOf(ids).filter((e) => !e.locked);\n const gap = arrangeGap(els.map((e) => e.w));\n const deltas = alignBoxes(\n els.map((e) => ({ id: e.id, box: elementBox(e) })),\n mode,\n { gap },\n );\n this.applyDeltas(deltas, opts);\n }\n\n // Equal gaps between the cards along an axis (three or more).\n distribute(axis: 'x' | 'y', ids?: readonly ElementId[], opts: ArrangeOptions = {}): void {\n const els = this.elementsOf(ids).filter((e) => !e.locked);\n const gap = arrangeGap(els.map((e) => e.w));\n const deltas = distributeBoxes(\n els.map((e) => ({ id: e.id, box: elementBox(e) })),\n axis,\n { gap },\n );\n this.applyDeltas(deltas, opts);\n }\n\n // Every card takes the median width; aspect-locked cards scale their height along. A card that grew\n // pushes its neighbours away (the arrange gap), as with align and distribute.\n equalWidth(ids?: readonly ElementId[], opts: ArrangeOptions = {}): void {\n const els = this.elementsOf(ids).filter((e) => !e.locked);\n const sizes = equalWidths(\n els.map((e) => ({ id: e.id, w: e.w, h: e.h, aspectLocked: e.aspectLocked })),\n );\n if (sizes.size === 0) return;\n const rects = new Map<ElementId, Rect4>();\n const items: { id: ElementId; box: Box }[] = [];\n for (const el of els) {\n const s = sizes.get(el.id);\n // Resized about the centre so the card does not jump.\n const r = s\n ? { x: el.x + (el.w - s.w) / 2, y: el.y + (el.h - s.h) / 2, w: s.w, h: s.h }\n : { x: el.x, y: el.y, w: el.w, h: el.h };\n rects.set(el.id, r);\n items.push({ id: el.id, box: elementBox({ ...r, rot: el.rot }) });\n }\n const patches = new Map<ElementId, Rect4>();\n const deltas = separate(items, arrangeGap(els.map((e) => e.w)));\n for (const [id, r] of rects) {\n const d = deltas.get(id);\n if (d || sizes.has(id)) patches.set(id, d ? { ...r, x: r.x + d.dx, y: r.y + d.dy } : r);\n }\n this.apply(patches, opts, false);\n }\n\n // Gives the elements that have no position a free spot near the middle of what is on screen, laid\n // out as one block. Mutates the given elements (they are not in the store yet). `fixedSize` keeps the\n // size an element came with; `given` keeps the one coordinate (x or y) a card was added with.\n placeNew(\n els: Element[],\n fixedSize: ReadonlySet<ElementId>,\n given: ReadonlyMap<ElementId, { x?: number; y?: number }> = new Map(),\n ): void {\n if (els.length === 0) return;\n const widths: number[] = [];\n for (const e of this.store.elements()) widths.push(e.w);\n const items: LayoutItem[] = els.map((e) =>\n fixedSize.has(e.id)\n ? { aspect: effectiveAspect(e.h / e.w), w: e.w, h: e.h }\n : { aspect: effectiveAspect(e.h / e.w) },\n );\n const plan = planPlacement({\n items,\n existingCardWidths: widths,\n anchor: { kind: 'grab', x: 0, y: 0 },\n });\n const block = { w: plan.bounds.maxX - plan.bounds.minX, h: plan.bounds.maxY - plan.bounds.minY };\n const view = this.placementView();\n // Everything the search can reach, not only what is near the viewport.\n const occupied = this.store.searchInto(autoSpotArea(block, view), []).map((e) => elementBox(e));\n const spot = autoSpot(block, view, occupied);\n els.forEach((e, i) => {\n const r = plan.rects[i];\n const g = given.get(e.id);\n e.x = g?.x ?? spot.x + r.x;\n e.y = g?.y ?? spot.y + r.y;\n e.w = r.w;\n e.h = r.h;\n });\n }\n\n // The viewport placement works against: the camera's, or a nominal one around its centre while the host\n // has no size (the camera then reports a 1 px placeholder, and the search would not leave its spot).\n private placementView(): Box {\n const cam = this.stage.cam;\n const v = cam.visibleRect();\n if (!cam.isEmpty && cam.width > 1 && cam.height > 1) {\n return { minX: v.x0, minY: v.y0, maxX: v.x1, maxY: v.y1 };\n }\n const cx = (v.x0 + v.x1) / 2;\n const cy = (v.y0 + v.y1) / 2;\n return {\n minX: cx - NOMINAL_VIEW.w / 2,\n minY: cy - NOMINAL_VIEW.h / 2,\n maxX: cx + NOMINAL_VIEW.w / 2,\n maxY: cy + NOMINAL_VIEW.h / 2,\n };\n }\n\n // ── Applying ───────────────────────────────────────────────────────────────\n private applyDeltas(\n deltas: Map<ElementId, { dx: number; dy: number }>,\n opts: ArrangeOptions,\n ): void {\n const patches = new Map<ElementId, Rect4>();\n for (const [id, d] of deltas) {\n const el = this.store.get(id) as Element;\n patches.set(id, { x: el.x + d.dx, y: el.y + d.dy, w: el.w, h: el.h });\n }\n this.apply(patches, opts, false);\n }\n\n // Writes the patches to the store at once (one batch, the final rects), then animates the cards near the\n // viewport: the stage draws them at preview rects that run from where they were to where they are now.\n // `resetRot`: a grid lays cards out upright.\n private apply(patches: Map<ElementId, Rect4>, opts: ArrangeOptions, resetRot: boolean): void {\n // Where the cards of a running animation are drawn now: a new one starts from there.\n const shown = this.animation?.shown;\n this.animation?.cancel();\n this.animation = null;\n if (patches.size === 0) return;\n const animate = (opts.animate ?? true) && !prefersReducedMotion();\n const moving: { id: ElementId; from: Shown; to: Rect4; toRot: number }[] = [];\n if (animate) {\n // Only cards that start or end near the viewport are animated; the rest jump (a preview forces a\n // view to be mounted, and a thousand of them would be the cost the culling exists to avoid).\n const v = this.stage.cam.visibleRect();\n const gx = (v.x1 - v.x0) * 0.2;\n const gy = (v.y1 - v.y0) * 0.2;\n const near: Box = { minX: v.x0 - gx, minY: v.y0 - gy, maxX: v.x1 + gx, maxY: v.y1 + gy };\n const hits = (b: Box): boolean =>\n b.minX <= near.maxX && b.maxX >= near.minX && b.minY <= near.maxY && b.maxY >= near.minY;\n for (const [id, to] of patches) {\n const el = this.store.get(id);\n if (!el) continue;\n const from = shown?.get(id) ?? { x: el.x, y: el.y, w: el.w, h: el.h, rot: el.rot };\n if (hits(boxOfRect(from)) || hits(boxOfRect(to))) {\n moving.push({ id, from, to, toRot: resetRot ? 0 : el.rot });\n }\n }\n }\n this.store.batch(() => {\n for (const [id, r] of patches) this.store.update(id, resetRot ? { ...r, rot: 0 } : r);\n });\n if (moving.length === 0) return;\n const duration = opts.duration ?? 320;\n const stage = this.stage;\n const start = performance.now();\n const current = new Map<ElementId, Shown>();\n let done = false;\n const finish = (): void => {\n if (done) return;\n done = true;\n off();\n // The store holds the final rects already: dropping the previews shows them.\n for (const m of moving) {\n stage.clearPreview(m.id);\n stage.pin(m.id, false);\n }\n if (this.animation?.cancel === finish) this.animation = null;\n };\n const draw = (e: number): void => {\n for (const m of moving) {\n // A card removed mid-animation is gone from the stage too: no preview to leave behind.\n if (!this.store.has(m.id)) continue;\n const r = {\n x: m.from.x + (m.to.x - m.from.x) * e,\n y: m.from.y + (m.to.y - m.from.y) * e,\n w: m.from.w + (m.to.w - m.from.w) * e,\n h: m.from.h + (m.to.h - m.from.h) * e,\n rot: m.from.rot + (m.toRot - m.from.rot) * e,\n };\n current.set(m.id, r);\n stage.setPreview(m.id, r.x, r.y, r.w, r.h, r.rot);\n }\n };\n const off = stage.onBeforeFrame(() => {\n if (done) return;\n const t = clamp((performance.now() - start) / duration, 0, 1);\n draw(ease(t));\n if (t >= 1) finish();\n else stage.requestFrame();\n });\n for (const m of moving) stage.pin(m.id, true);\n // The first frame is the old arrangement: the final rects are in the store already.\n draw(0);\n this.animation = { shown: current, cancel: finish };\n stage.requestFrame();\n }\n}\n","// Turns what the host passes to `add` into stored elements.\nimport { thumbHashToApproximateAspectRatio } from 'thumbhash';\nimport { parseEmbedUrl } from './embed/providers';\nimport { DEFAULTS, type Element, type ElementInit, type ElementKind, type MediaSource } from './types';\n\nfunction decodeBase64(s: string): Uint8Array {\n const bin = atob(s.replace(/-/g, '+').replace(/_/g, '/'));\n const out = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);\n return out;\n}\n\n// height / width of the picture, from the media's `aspect`, else from its ThumbHash, else a default.\nexport function aspectOf(media: MediaSource, kind: ElementKind): number {\n if (media.aspect !== undefined && Number.isFinite(media.aspect) && media.aspect > 0) {\n return media.aspect;\n }\n if (media.thumbhash !== undefined) {\n try {\n const bytes =\n typeof media.thumbhash === 'string' ? decodeBase64(media.thumbhash) : media.thumbhash;\n const r = thumbHashToApproximateAspectRatio(bytes);\n if (Number.isFinite(r) && r > 0) return 1 / r;\n } catch {\n // A malformed hash: fall through to the default.\n }\n }\n if (kind === 'embed') {\n // A known provider has a shape of its own (16:9 for a video, a strip for a Spotify track).\n const url = media.embed?.url;\n return (url !== undefined ? parseEmbedUrl(url)?.aspect : undefined) ?? DEFAULTS.embedAspect;\n }\n return kind === 'video' ? DEFAULTS.videoAspect : DEFAULTS.cardAspect;\n}\n\nexport const kindOf = (init: Pick<ElementInit, 'kind' | 'media'>): ElementKind =>\n init.kind ?? (init.media.embed ? 'embed' : init.media.video ? 'video' : 'image');\n\n// Size of a card: a given `w` and `h` win; a lone `w` or `h` is completed with the aspect.\nexport function sizeOf(init: ElementInit, kind: ElementKind): { w: number; h: number } {\n const aspect = aspectOf(init.media, kind);\n if (init.w !== undefined && init.h !== undefined) return { w: init.w, h: init.h };\n if (init.h !== undefined) return { w: init.h / aspect, h: init.h };\n const w = init.w ?? (kind === 'embed' ? DEFAULTS.embedWidth : DEFAULTS.cardWidth);\n return { w, h: Math.max(1, Math.round(w * aspect)) };\n}\n\n// `x` / `y` default to 0 here; `Corkboard.add` places cards that have none before it gets this far.\nexport function createElement(init: ElementInit, id: string): Element {\n const kind = kindOf(init);\n const { w, h } = sizeOf(init, kind);\n return {\n id,\n kind,\n x: init.x ?? 0,\n y: init.y ?? 0,\n w,\n h,\n rot: init.rot ?? 0,\n locked: init.locked ?? false,\n media: init.media,\n radius: init.radius ?? DEFAULTS.cardRadius,\n aspectLocked: init.aspectLocked ?? true,\n data: init.data,\n };\n}\n\nlet counter = 0;\nexport function newId(): string {\n counter++;\n return typeof crypto !== 'undefined' && 'randomUUID' in crypto\n ? crypto.randomUUID()\n : `cb-${Date.now().toString(36)}-${counter.toString(36)}`;\n}\n","// The in-memory element store: an id -> element map, an rbush spatial index over the world AABBs, the\n// draw order, and change events. This is everything the renderer and the interaction layer read.\n//\n// Elements are plain objects owned by the store; callers never mutate them, they go through `update`.\n// Changes are batched by `batch(fn)`: listeners get one `ChangeSet` per batch.\nimport RBush from 'rbush';\nimport type { Box } from '../interact/geometry';\nimport { elementBox } from '../interact/geometry';\nimport type { Element, ElementId, ElementPatch } from '../types';\n\nexport type ChangeSource = 'load' | 'local';\n\nexport interface ChangeSet {\n source: ChangeSource;\n added: Element[];\n removed: Element[];\n // The element after the change and the names of the properties that changed.\n updated: { el: Element; props: string[] }[];\n}\n\nexport type StoreEvent = { type: 'change'; change: ChangeSet };\n\ninterface Entry extends Box {\n el: Element;\n}\n\nconst GEOMETRY = ['x', 'y', 'w', 'h', 'rot'] as const;\nconst PATCHABLE = [\n 'x',\n 'y',\n 'w',\n 'h',\n 'rot',\n 'locked',\n 'media',\n 'radius',\n 'aspectLocked',\n 'data',\n 'kind',\n] as const;\n\nexport class Store {\n private readonly map = new Map<ElementId, Element>();\n private readonly tree = new RBush<Entry>();\n private readonly entries = new Map<ElementId, Entry>();\n // Draw order, bottom first, and each id's index in it (rebuilt lazily after a removal or a reorder).\n private order: ElementId[] = [];\n private ranks = new Map<ElementId, number>();\n private ranksDirty = false;\n // Bumped when existing ranks change (not on a plain append): the stage then re-sorts its views.\n orderVersion = 0;\n\n private readonly listeners = new Set<(e: StoreEvent) => void>();\n private pending: ChangeSet | null = null;\n private depth = 0;\n\n get size(): number {\n return this.map.size;\n }\n\n subscribe(listener: (e: StoreEvent) => void): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n // ── Reads ──────────────────────────────────────────────────────────────────\n get(id: ElementId): Element | undefined {\n return this.map.get(id);\n }\n\n has(id: ElementId): boolean {\n return this.map.has(id);\n }\n\n elements(): IterableIterator<Element> {\n return this.map.values();\n }\n\n // The ids in draw order, bottom first.\n ids(): readonly ElementId[] {\n return this.order;\n }\n\n rank(id: ElementId): number {\n if (this.ranksDirty) this.rebuildRanks();\n return this.ranks.get(id) ?? -1;\n }\n\n // Elements whose world AABB intersects `box`. `out` is cleared and returned.\n searchInto(box: Box, out: Element[]): Element[] {\n out.length = 0;\n const hits = this.tree.search(box);\n for (let i = 0; i < hits.length; i++) out.push(hits[i].el);\n return out;\n }\n\n // ── Writes ─────────────────────────────────────────────────────────────────\n add(els: readonly Element[], source: ChangeSource = 'local'): void {\n if (els.length === 0) return;\n this.batch(() => {\n for (const el of els) {\n if (this.map.has(el.id)) throw new Error(`corkboard: duplicate element id \"${el.id}\"`);\n this.map.set(el.id, el);\n this.order.push(el.id);\n if (!this.ranksDirty) this.ranks.set(el.id, this.order.length - 1);\n const e = this.entryOf(el);\n this.entries.set(el.id, e);\n this.tree.insert(e);\n this.change(source).added.push(el);\n }\n });\n }\n\n // Applies `patch` to an element. Returns the names of the properties that changed ([] when none).\n update(id: ElementId, patch: ElementPatch, source: ChangeSource = 'local'): string[] {\n const prev = this.map.get(id);\n if (!prev) return [];\n const props: string[] = [];\n const next: Element = { ...prev };\n const rec = patch as Record<string, unknown>;\n for (const k of PATCHABLE) {\n if (!(k in rec) || rec[k] === undefined) continue;\n if (Object.is((next as unknown as Record<string, unknown>)[k], rec[k])) continue;\n (next as unknown as Record<string, unknown>)[k] = rec[k];\n props.push(k);\n }\n if (props.length === 0) return props;\n this.map.set(id, next);\n if (props.some((p) => (GEOMETRY as readonly string[]).includes(p))) {\n const old = this.entries.get(id);\n if (old) this.tree.remove(old);\n const e = this.entryOf(next);\n this.entries.set(id, e);\n this.tree.insert(e);\n } else {\n const e = this.entries.get(id);\n if (e) e.el = next;\n }\n this.batch(() => {\n const c = this.change(source);\n // A second update of the same element in one batch folds into one entry.\n const at = c.updated.findIndex((u) => u.el.id === id);\n if (at >= 0) {\n const merged = new Set([...c.updated[at].props, ...props]);\n c.updated[at] = { el: next, props: [...merged] };\n } else c.updated.push({ el: next, props });\n });\n return props;\n }\n\n remove(ids: readonly ElementId[], source: ChangeSource = 'local'): Element[] {\n const gone: Element[] = [];\n this.batch(() => {\n for (const id of ids) {\n const el = this.map.get(id);\n if (!el) continue;\n this.map.delete(id);\n const e = this.entries.get(id);\n if (e) this.tree.remove(e);\n this.entries.delete(id);\n gone.push(el);\n this.change(source).removed.push(el);\n }\n if (gone.length > 0) {\n const dead = new Set(gone.map((g) => g.id));\n this.order = this.order.filter((i) => !dead.has(i));\n this.ranksDirty = true;\n this.orderVersion++;\n }\n });\n return gone;\n }\n\n // Moves the ids to the top of the draw order (keeping their relative order).\n bringToFront(ids: readonly ElementId[]): void {\n const set = new Set(ids.filter((i) => this.map.has(i)));\n if (set.size === 0) return;\n const keep = this.order.filter((i) => !set.has(i));\n const lifted = this.order.filter((i) => set.has(i));\n this.order = keep.concat(lifted);\n this.ranksDirty = true;\n this.orderVersion++;\n this.batch(() => {\n for (const id of lifted) {\n const el = this.map.get(id) as Element;\n this.change('local').updated.push({ el, props: ['order'] });\n }\n });\n }\n\n // Replaces everything (the stage reloads from the store at its next tick).\n clear(): void {\n const all = [...this.map.values()];\n this.map.clear();\n this.entries.clear();\n this.tree.clear();\n this.order = [];\n this.ranks.clear();\n this.ranksDirty = false;\n this.orderVersion++;\n if (all.length === 0) return;\n this.batch(() => {\n this.change('local').removed.push(...all);\n });\n }\n\n // Groups every change made inside `fn` into one event.\n batch(fn: () => void): void {\n this.depth++;\n try {\n fn();\n } finally {\n this.depth--;\n if (this.depth === 0) this.flush();\n }\n }\n\n // ── Internals ──────────────────────────────────────────────────────────────\n private entryOf(el: Element): Entry {\n const b = elementBox(el);\n return { minX: b.minX, minY: b.minY, maxX: b.maxX, maxY: b.maxY, el };\n }\n\n private change(source: ChangeSource): ChangeSet {\n return (this.pending ??= { source, added: [], removed: [], updated: [] });\n }\n\n private rebuildRanks(): void {\n this.ranks = new Map();\n for (let i = 0; i < this.order.length; i++) this.ranks.set(this.order[i], i);\n this.ranksDirty = false;\n }\n\n private flush(): void {\n const c = this.pending;\n this.pending = null;\n if (!c || (c.added.length === 0 && c.removed.length === 0 && c.updated.length === 0)) return;\n for (const l of [...this.listeners]) l({ type: 'change', change: c });\n }\n}\n","// How a video comes in over its picture, one behaviour for every video. The controller reads the media\n// element's events and writes two attributes on a HOST element (by default the video's parent); the look\n// is CSS (injected once by `injectRevealStyles`), so nothing re-renders and nothing runs per frame.\n//\n// data-state poster the picture shows (not asked for, hovered out, or the file failed)\n// loading asked for, and no frame of it has been PRESENTED yet: the picture stays\n// playing a frame is on screen: the video fades in over the picture (also paused)\n// stalled it ran dry mid-play: the last frame stays, no fall back to the picture\n// data-busy \"true\" once `loading` or `stalled` has lasted INDICATOR_DELAY_MS: the buffering ring\n// shows (a wait shorter than that would be a blink, not information)\n//\n// \"A frame is on screen\" is `requestVideoFrameCallback` where the browser has it (the frame was handed to\n// the compositor, so the fade starts on a picture and never on a black or empty box); else `playing` once\n// the clock has moved. A safety timer covers a browser that never calls back (a hidden tab).\n\nconst STYLE_ATTR = 'data-corkboard-video';\n\n// In: the first frame over the picture. Out: back to the picture. The ring is a ring on a soft disc, so it\n// reads on any picture; its colours belong to the media, not to a page theme.\nconst CSS = `\n.cb-video{opacity:0;--cb-in:240ms;--cb-out:150ms;--cb-ease:cubic-bezier(0.2,0,0,1);--cb-dur:var(--cb-out);transition:opacity var(--cb-dur) var(--cb-ease)}\n[data-state='playing'] .cb-video,[data-state='stalled'] .cb-video{opacity:1;--cb-dur:var(--cb-in)}\n.cb-spinner{display:flex;align-items:center;justify-content:center;width:52px;height:52px;border-radius:50%;background:rgb(0 0 0 / 0.4);opacity:0;pointer-events:none;transition:opacity 160ms ease}\n.cb-ring{box-sizing:border-box;width:36px;height:36px;border-radius:50%;border:2px solid transparent;border-color:rgb(255 255 255 / 0.25);border-top-color:rgb(255 255 255 / 0.8);animation:cb-spin 800ms linear infinite;animation-play-state:paused}\n[data-busy='true'] .cb-spinner{opacity:1}\n[data-busy='true'] .cb-ring{animation-play-state:running}\n@keyframes cb-spin{to{transform:rotate(360deg)}}\n@media (prefers-reduced-motion:reduce){.cb-video,.cb-spinner{transition:none}.cb-ring{animation:none}}\n`;\n\n// Appends the stylesheet to the document's <head> the first time it is needed (idempotent).\nexport function injectRevealStyles(doc: Document = document): void {\n const head = doc.head;\n if (!head || head.querySelector(`style[${STYLE_ATTR}]`)) return;\n const style = doc.createElement('style');\n style.setAttribute(STYLE_ATTR, '');\n style.textContent = CSS;\n head.appendChild(style);\n}\n\nexport type RevealState = 'poster' | 'loading' | 'playing' | 'stalled';\n\n// A wait shorter than this shows no ring.\nexport const INDICATOR_DELAY_MS = 250;\n// `playing` with no frame callback after this long: take the frame as presented. The callback of a\n// browser that has one follows `playing` by a frame or two, so its safety net is far slower.\nconst FALLBACK_MS = 120;\nconst FALLBACK_RVFC_MS = 600;\n// HAVE_CURRENT_DATA / HAVE_FUTURE_DATA of the media element.\nconst HAVE_CURRENT_DATA = 2;\nconst HAVE_FUTURE_DATA = 3;\n\nconst EVENTS = [\n 'loadstart',\n 'emptied',\n 'loadeddata',\n 'playing',\n 'waiting',\n 'stalled',\n 'canplay',\n 'seeked',\n 'timeupdate',\n 'error',\n] as const;\n\nexport interface VideoRevealOptions {\n // Carries data-state and data-busy. Default: the video's parent. Its CSS (`.cb-video`, `.cb-spinner`)\n // applies to the descendants.\n host?: HTMLElement | null;\n // Called when the state changes (a card that also wants it in React state; at most a few times a hover).\n onState?: (state: RevealState) => void;\n}\n\nexport interface VideoReveal {\n readonly state: RevealState;\n // The video is wanted (a hover began, play was pressed): from now on its first frame fades in.\n request(): void;\n // It is not (hovered out, stopped): back to the picture.\n release(): void;\n dispose(): void;\n}\n\nexport function attachVideoReveal(\n video: HTMLVideoElement,\n opts: VideoRevealOptions = {},\n): VideoReveal {\n const v = video;\n injectRevealStyles(v.ownerDocument);\n const host = opts.host === undefined ? video.parentElement : opts.host;\n // Older browsers (and jsdom) have no frame callbacks; the types say every one does.\n const hasRvfc = typeof v.requestVideoFrameCallback === 'function';\n let wanted = false;\n let frame = false;\n let stalled = false;\n let failed = false;\n let state: RevealState = 'poster';\n let busy = false;\n let disposed = false;\n // Bumped when the source changes or the controller lets go: a callback of an older one is ignored.\n let generation = 0;\n let rvfc: number | null = null;\n let fallback: ReturnType<typeof setTimeout> | null = null;\n let busyTimer: ReturnType<typeof setTimeout> | null = null;\n\n const write = (): void => {\n if (!host) return;\n if (host.dataset.state !== state) host.dataset.state = state;\n if (busy) {\n if (host.dataset.busy !== 'true') host.dataset.busy = 'true';\n } else if (host.hasAttribute('data-busy')) host.removeAttribute('data-busy');\n };\n\n const compute = (): void => {\n if (disposed) return;\n const next: RevealState =\n !wanted || failed ? 'poster' : !frame ? 'loading' : stalled ? 'stalled' : 'playing';\n const waiting = next === 'loading' || next === 'stalled';\n if (next !== state) {\n state = next;\n opts.onState?.(state);\n }\n if (!waiting) {\n if (busyTimer !== null) clearTimeout(busyTimer);\n busyTimer = null;\n busy = false;\n } else if (!busy && busyTimer === null) {\n busyTimer = setTimeout(() => {\n busyTimer = null;\n busy = true;\n write();\n }, INDICATOR_DELAY_MS);\n }\n write();\n };\n\n const clearFrameWatch = (): void => {\n if (rvfc !== null) v.cancelVideoFrameCallback?.(rvfc);\n rvfc = null;\n if (fallback !== null) clearTimeout(fallback);\n fallback = null;\n };\n\n const setFrame = (): void => {\n if (frame) return;\n frame = true;\n clearFrameWatch();\n compute();\n };\n\n // `playing` with no frame callback yet: the safety net that takes the frame as presented. Some browsers\n // never call back for a video that is still transparent (iOS Safari does not composite it), so this is\n // armed whenever a wanted video is seen playing, whatever came first: the event or the request.\n const armFallback = (): void => {\n if (frame || !wanted || fallback !== null) return;\n const gen = generation;\n fallback = setTimeout(\n () => {\n fallback = null;\n if (gen === generation && wanted && !v.paused) setFrame();\n // Paused when it fired (a moment off screen): the next `playing` or clock tick arms it again.\n },\n hasRvfc ? FALLBACK_RVFC_MS : FALLBACK_MS,\n );\n };\n\n // Watches for the first presented frame of the source that is loading now.\n const watchFrame = (): void => {\n if (!wanted || frame || !hasRvfc || rvfc !== null) return;\n const gen = generation;\n rvfc = v.requestVideoFrameCallback(() => {\n rvfc = null;\n if (gen === generation && wanted) setFrame();\n });\n };\n\n const reset = (): void => {\n generation++;\n frame = false;\n stalled = false;\n failed = false;\n clearFrameWatch();\n watchFrame();\n compute();\n };\n\n const onEvent = (e: Event): void => {\n if (disposed) return;\n switch (e.type) {\n case 'loadstart':\n case 'emptied':\n // A new source (or none): whatever frame there was is gone.\n reset();\n break;\n case 'error':\n failed = true;\n compute();\n break;\n case 'playing':\n stalled = false;\n if (!frame) {\n if (!hasRvfc && v.currentTime > 0) setFrame();\n else armFallback();\n }\n compute();\n break;\n case 'timeupdate':\n // No frame callbacks: the clock moving is the sign of a frame.\n if (!frame && wanted && !v.paused && v.currentTime > 0) {\n if (!hasRvfc) setFrame();\n // The clock moves and no frame was called back: the `playing` may have come before the request.\n else armFallback();\n } else if (stalled && v.readyState >= HAVE_FUTURE_DATA) {\n stalled = false;\n compute();\n }\n break;\n case 'waiting':\n case 'stalled':\n if (frame && v.readyState < HAVE_FUTURE_DATA) {\n stalled = true;\n compute();\n }\n break;\n case 'canplay':\n case 'seeked':\n if (stalled && v.readyState >= HAVE_FUTURE_DATA) {\n stalled = false;\n compute();\n }\n break;\n default:\n break;\n }\n };\n for (const type of EVENTS) v.addEventListener(type, onEvent);\n write();\n\n return {\n get state() {\n return state;\n },\n request() {\n if (disposed) return;\n wanted = true;\n // A new `src` empties the element at once: a frame from before it is not one of this source.\n if (v.readyState < HAVE_CURRENT_DATA) {\n frame = false;\n stalled = false;\n }\n failed = !!v.error;\n watchFrame();\n // Asked for while it already plays (its `playing` came first): the safety net starts now.\n if (!v.paused && v.readyState >= HAVE_CURRENT_DATA) armFallback();\n compute();\n },\n release() {\n if (disposed) return;\n wanted = false;\n generation++;\n clearFrameWatch();\n compute();\n },\n dispose() {\n if (disposed) return;\n disposed = true;\n generation++;\n clearFrameWatch();\n if (busyTimer !== null) clearTimeout(busyTimer);\n busyTimer = null;\n for (const type of EVENTS) v.removeEventListener(type, onEvent);\n if (host) {\n delete host.dataset.state;\n delete host.dataset.busy;\n }\n },\n };\n}\n\n// The buffering ring (a disc and a ring in it), for the code that builds its DOM by hand. It shows while\n// the host's data-busy is \"true\".\nexport function createRevealSpinner(doc: Document): HTMLElement {\n injectRevealStyles(doc);\n const disc = doc.createElement('span');\n disc.className = 'cb-spinner';\n disc.setAttribute('aria-hidden', 'true');\n const ring = doc.createElement('span');\n ring.className = 'cb-ring';\n disc.appendChild(ring);\n return disc;\n}\n","// The video overlay: ONE looping <video> laid over the video card that currently plays. It is\n// transform-synced from the render loop: `sync` and `follow` write only `transform` (and the size when\n// the card was resized); source and clip change in `show`.\n//\n// It must cover exactly the card, so it FOLLOWS it: the host calls `follow` every frame with the card's\n// current rect (the live drag / resize / rotate preview, else the stored one), because a card can move\n// while it plays: it is dragged or resized, an edit is undone, another client moves it. Where the box\n// lands is `videoPlacement` (videoGeometry.ts), rotation included.\n//\n// The card's own thumbnail (drawn by WebGL, underneath) is the poster. The <video> is transparent until a\n// frame of it is on screen, then fades in over the thumbnail (reveal.ts: data-state / data-busy on the\n// overlay's host, the look in the injected `.cb-*` styles). It fills the card's box the way the sprite\n// does (`object-fit: cover`: the thumbnail is cropped to the card's shape, centred, never stretched), so\n// the two are one picture and the fade shows no jump. While the picture a card was asked for is not there (loading, or stalled mid-way) a ring spins\n// over its centre after INDICATOR_DELAY_MS, so a cached video never flashes it. Stopping fades back to\n// the thumbnail first, and only then lets go of the network.\nimport type { Camera } from '../math';\nimport {\n attachVideoReveal,\n createRevealSpinner,\n INDICATOR_DELAY_MS,\n type VideoReveal,\n} from './reveal';\nimport { videoPlacement, type VideoRect } from './videoGeometry';\n\nexport interface VideoTarget {\n id: string;\n src: string;\n box: { x: number; y: number; w: number; h: number };\n // Degrees; the card rotates about the centre of its box.\n rot?: number;\n // World px. Applied as `clip-path: inset(0 round R)` in the video's own (world) space, so the\n // transform scales the corners with the card.\n radius: number;\n}\n\n// A wait shorter than this shows no ring: it would be a blink, not information.\nexport const SPINNER_DELAY_MS = INDICATOR_DELAY_MS;\n// The fade back to the thumbnail (`--cb-out` in reveal.ts) and a margin: the network is let go after it.\nexport const FADE_OUT_MS = 150;\nconst HIDE_DELAY_MS = FADE_OUT_MS + 30;\n// The ring's disc (`.cb-spinner` in reveal.ts), to centre it on the card.\nconst DISC_PX = 52;\n\nconst round3 = (v: number): number => Math.round(v * 1000) / 1000;\n\nexport interface VideoOverlayOptions {\n // The buffering ring over the card (default on). The ambient pool turns it off: a dozen cards\n // loading at once would be a dozen spinners.\n spinner?: boolean;\n // The element is placed in WORLD space, inside a parent that carries the camera's transform (the\n // ambient pool: one transform per frame for the whole screenful, instead of one per video). Then\n // `sync` has nothing to do and `follow` only writes when the card itself moved.\n worldSpace?: boolean;\n}\n\n// What a world-space overlay is placed with: the camera's identity (the parent has the real one).\nconst WORLD_CAMERA: Camera = { tx: 0, ty: 0, scale: 1 };\n\nexport class VideoOverlay {\n private readonly video: HTMLVideoElement;\n // Carries data-state / data-busy (reveal.ts); `display: contents`, it has no box of its own.\n private readonly host: HTMLElement;\n private readonly disc: HTMLElement;\n private readonly reveal: VideoReveal;\n private readonly worldSpace: boolean;\n private target: VideoTarget | null = null;\n private rect: VideoRect = { x: 0, y: 0, w: 0, h: 0, rot: 0 };\n // The sound switch (setPlayback); the element itself may be muted for one card (play()).\n private wantMuted = true;\n private wroteTransform = '';\n private wroteDisc = '';\n private wroteW = NaN;\n private wroteH = NaN;\n // Stopped, and fading back to the thumbnail: the source and the box stay until the fade is done.\n private hideTimer: ReturnType<typeof setTimeout> | null = null;\n private disposed = false;\n\n constructor(root: HTMLElement, opts: VideoOverlayOptions = {}) {\n const doc = root.ownerDocument;\n this.worldSpace = opts.worldSpace === true;\n const host = doc.createElement('div');\n host.style.display = 'contents';\n const v = doc.createElement('video');\n v.className = 'cb-video';\n v.muted = true;\n v.loop = true;\n v.playsInline = true;\n v.preload = 'metadata';\n // Attributes too: iOS Safari and the autoplay policy read the markup form.\n v.setAttribute('muted', '');\n v.setAttribute('playsinline', '');\n v.setAttribute('loop', '');\n v.setAttribute('disablepictureinpicture', '');\n // Many CSS resets set `max-width: 100%` / `height: auto` on every <video>: left alone they would clamp\n // a card wider than the viewport (zoomed in) to the viewport's width, and the box would no longer be\n // the card's.\n v.style.cssText =\n 'position:absolute;left:0;top:0;transform-origin:0 0;pointer-events:none;' +\n 'max-width:none;max-height:none;object-fit:cover;display:none;';\n\n // The ring stays upright and the same size on screen, centred on the card: placed by `transform`.\n const disc = createRevealSpinner(doc);\n disc.style.cssText =\n 'position:absolute;left:0;top:0;' + (opts.spinner === false ? 'display:none;' : '');\n\n host.append(v, disc);\n root.append(host);\n this.video = v;\n this.host = host;\n this.disc = disc;\n this.reveal = attachVideoReveal(v, { host });\n }\n\n // Playback switches. Applied at once and kept for every later card.\n setPlayback(o: { loop: boolean; muted: boolean }): void {\n const v = this.video;\n v.loop = o.loop;\n v.muted = o.muted;\n this.wantMuted = o.muted;\n if (o.loop) v.setAttribute('loop', '');\n else v.removeAttribute('loop');\n if (o.muted) v.setAttribute('muted', '');\n else v.removeAttribute('muted');\n }\n\n get activeId(): string | null {\n return this.target?.id ?? null;\n }\n\n // The file the element has loaded (null when idle).\n get activeSrc(): string | null {\n return this.target !== null ? this.video.getAttribute('src') : null;\n }\n\n // The tab went to the background: the clock stops, the element and its place stay.\n suspend(): void {\n if (!this.target) return;\n try {\n this.video.pause();\n } catch {\n // Not implemented (jsdom).\n }\n }\n\n // The tab is back: carry on from where it stopped.\n resume(): void {\n if (this.disposed || !this.target || this.hideTimer !== null) return;\n this.play();\n }\n\n // `load: false` is the hover delay: the card is asked for but not fetched yet. Nothing is shown, the ring\n // already counts its wait; `show` (load) follows when the delay is over, `hide` if the hover ended.\n show(target: VideoTarget, camera: Camera, load = true): void {\n if (this.disposed) return;\n const v = this.video;\n if (this.hideTimer !== null) {\n // Back while it was fading out: the same card carries on from where it is; another one starts clean.\n if (this.target !== null && v.getAttribute('src') === target.src) this.cancelHide();\n else this.teardown();\n }\n const sameSource = this.target !== null && v.getAttribute('src') === target.src;\n this.target = target;\n this.rect = { ...target.box, rot: target.rot ?? 0 };\n // A new picture is coming: the card shows through until its first frame (the reveal resets on\n // `loadstart`).\n if (load && !sameSource) {\n // A card muted after a refused autoplay (play()) does not carry that to the next one.\n v.muted = this.wantMuted;\n v.src = target.src;\n }\n v.style.clipPath = `inset(0 round ${round3(target.radius)}px)`;\n v.style.display = 'block';\n this.writeSize();\n this.wroteTransform = '';\n this.wroteDisc = '';\n this.writeTransform(camera);\n this.reveal.request();\n if (load) this.play();\n }\n\n // Transform only (the camera moved).\n sync(camera: Camera): void {\n if (this.disposed || !this.target || this.worldSpace) return;\n this.writeTransform(camera);\n }\n\n // The card's box changed (dragged, resized, rotated, undone, moved by a peer): the overlay goes with\n // it. Returns whether the SIZE changed (the card may have become too small to play).\n follow(rect: VideoRect, camera: Camera): boolean {\n if (this.disposed || !this.target) return false;\n const r = this.rect;\n const rot = rect.rot ?? 0;\n const resized = rect.w !== r.w || rect.h !== r.h;\n r.x = rect.x;\n r.y = rect.y;\n r.w = rect.w;\n r.h = rect.h;\n r.rot = rot;\n if (resized) this.writeSize();\n this.writeTransform(camera);\n return resized;\n }\n\n // Fades back to the thumbnail (the card keeps playing under the fade), then releases the network.\n hide(): void {\n if (this.disposed || !this.target || this.hideTimer !== null) return;\n this.reveal.release();\n const reduced =\n typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;\n if (reduced) this.teardown();\n else this.hideTimer = setTimeout(() => this.teardown(), HIDE_DELAY_MS);\n }\n\n dispose(): void {\n if (this.disposed) return;\n this.teardown();\n this.disposed = true;\n this.reveal.dispose();\n this.host.remove();\n }\n\n private cancelHide(): void {\n if (this.hideTimer !== null) clearTimeout(this.hideTimer);\n this.hideTimer = null;\n }\n\n // Pause, drop the source and reload the empty element (the documented way to make the browser abort\n // the download).\n private teardown(): void {\n this.cancelHide();\n if (!this.target) return;\n this.target = null;\n this.reveal.release();\n const v = this.video;\n try {\n v.pause();\n } catch {\n // Not implemented (jsdom) or already detached: nothing to stop.\n }\n if (v.hasAttribute('src')) {\n v.removeAttribute('src');\n try {\n v.load();\n } catch {\n // Same as above.\n }\n }\n v.style.display = 'none';\n }\n\n // The <video> is laid out at the card's world size; the transform scales it to the screen.\n private writeSize(): void {\n const { w, h } = this.rect;\n if (w !== this.wroteW) {\n this.video.style.width = `${round3(w)}px`;\n this.wroteW = w;\n }\n if (h !== this.wroteH) {\n this.video.style.height = `${round3(h)}px`;\n this.wroteH = h;\n }\n }\n\n private writeTransform(cam: Camera): void {\n if (!this.target) return;\n const camera = this.worldSpace ? WORLD_CAMERA : cam;\n const p = videoPlacement(this.rect, camera);\n if (p.transform !== this.wroteTransform) {\n this.wroteTransform = p.transform;\n this.video.style.transform = p.transform;\n }\n // The ring belongs to the screen (upright, one size): a world-space overlay has none.\n if (this.worldSpace) return;\n const disc = `translate(${round3(p.cx - DISC_PX / 2)}px, ${round3(p.cy - DISC_PX / 2)}px)`;\n if (disc !== this.wroteDisc) {\n this.wroteDisc = disc;\n this.disc.style.transform = disc;\n }\n }\n\n // Autoplay can be refused (no user gesture yet, data saver) or aborted by a quick hide(): both are\n // routine, so the rejection is swallowed.\n // A video that keeps its sound is refused unmuted autoplay until the page has had a gesture (and on\n // iOS almost always): the card would stay on its thumbnail. Then it plays muted for this card, and the\n // next card tries with sound again.\n private play(): void {\n const v = this.video;\n const target = this.target;\n try {\n const p: Promise<void> | undefined = v.play();\n p?.catch((e: unknown) => {\n if (v.muted || (e as { name?: string } | null)?.name !== 'NotAllowedError') return;\n // Hidden or moved to another card meanwhile: that one asks for itself.\n if (this.target !== target || target === null) return;\n v.muted = true;\n v.play()?.catch(() => {});\n });\n } catch {\n // Not implemented (jsdom).\n }\n }\n}\n","// Which video cards play on their own in `mode: 'always'` (ambient.ts)? Pure rules shared by the pool\n// and its tests. No DOM, no timers.\n//\n// A card plays only when it is worth a stream: it touches the viewport (plus a margin, so a card scrolling\n// in is already moving) AND it is big enough on screen (`minPlayPx`, on its long side: a 20 px card at 10 %\n// zoom shows nothing a thumbnail does not). Of those, at most `cap` play at once (8 on a mouse device, 2 on\n// touch): a <video> is a decoder and a socket, and a screenful of them is what stalls a laptop. The biggest\n// and most central win. A card that stays in the set keeps its stream; one that leaves is let go of.\nimport type { Camera } from '../math';\nimport { DEG } from '../interact/geometry';\n\n// Streams that may run at once, whatever the options say: a ceiling against a runaway `maxPlaying`.\nexport const AMBIENT_MAX_STREAMS = 96;\n// Defaults of `video.maxPlaying` / `video.maxPlayingTouch` and `video.minPlayPx`.\nexport const AMBIENT_MAX_PLAYING = 8;\nexport const AMBIENT_MAX_PLAYING_TOUCH = 2;\nexport const AMBIENT_MIN_PLAY_PX = 160;\n// How far past the viewport (fraction of its size, each side) a card still plays.\nexport const AMBIENT_MARGIN = 0.25;\n// Over the ceiling, a card that already plays keeps its seat unless another is clearly better: two\n// near-equal cards must not swap on every pan.\nconst KEEP_BONUS = 1.25;\n\nexport interface AmbientCandidate {\n id: string;\n // World px: the card's box (x / y is the top-left of the UNROTATED box) and its rotation in degrees.\n x: number;\n y: number;\n w: number;\n h: number;\n rot?: number;\n}\n\nexport interface AmbientPlanInput {\n cards: Iterable<AmbientCandidate>;\n camera: Camera;\n viewport: { w: number; h: number };\n // At most this many ids (default `AMBIENT_MAX_PLAYING`, never past `AMBIENT_MAX_STREAMS`).\n cap?: number;\n // A card plays only if its long side is at least this many CSS px on screen (default\n // `AMBIENT_MIN_PLAY_PX`; 0 = any size).\n minPlayPx?: number;\n // Ids that play now (they keep their seat on a near tie).\n playing?: ReadonlySet<string>;\n margin?: number;\n}\n\ninterface ScreenBox {\n x0: number;\n y0: number;\n x1: number;\n y1: number;\n}\n\n// The axis-aligned box on screen of a card (rotation included: the box of its four corners).\nfunction screenBox(c: AmbientCandidate, cam: Camera): ScreenBox {\n const rot = c.rot ?? 0;\n let x0 = c.x;\n let y0 = c.y;\n let x1 = c.x + c.w;\n let y1 = c.y + c.h;\n if (rot !== 0) {\n const a = rot * DEG;\n const cos = Math.abs(Math.cos(a));\n const sin = Math.abs(Math.sin(a));\n const bw = c.w * cos + c.h * sin;\n const bh = c.w * sin + c.h * cos;\n const cx = c.x + c.w / 2;\n const cy = c.y + c.h / 2;\n x0 = cx - bw / 2;\n x1 = cx + bw / 2;\n y0 = cy - bh / 2;\n y1 = cy + bh / 2;\n }\n return {\n x0: cam.tx + x0 * cam.scale,\n y0: cam.ty + y0 * cam.scale,\n x1: cam.tx + x1 * cam.scale,\n y1: cam.ty + y1 * cam.scale,\n };\n}\n\nconst overlap = (a: ScreenBox, b: ScreenBox): number => {\n const w = Math.min(a.x1, b.x1) - Math.max(a.x0, b.x0);\n const h = Math.min(a.y1, b.y1) - Math.max(a.y0, b.y0);\n return w > 0 && h > 0 ? w * h : 0;\n};\n\n// The ids that should play, best first: the big enough cards in the viewport (by the area they show, then\n// the nearest to the centre), then the ones only in the margin (by their size), up to the cap. Ties break\n// on the id, so the answer does not depend on the order the cards arrive in.\nexport function planAmbient(input: AmbientPlanInput): string[] {\n const { camera, viewport } = input;\n const cap = Math.min(input.cap ?? AMBIENT_MAX_PLAYING, AMBIENT_MAX_STREAMS);\n if (!(cap > 0) || viewport.w <= 0 || viewport.h <= 0) return [];\n const minPx = input.minPlayPx ?? AMBIENT_MIN_PLAY_PX;\n const m = input.margin ?? AMBIENT_MARGIN;\n const view: ScreenBox = { x0: 0, y0: 0, x1: viewport.w, y1: viewport.h };\n const near: ScreenBox = {\n x0: -viewport.w * m,\n y0: -viewport.h * m,\n x1: viewport.w * (1 + m),\n y1: viewport.h * (1 + m),\n };\n const cx = viewport.w / 2;\n const cy = viewport.h / 2;\n const scored: { id: string; inView: boolean; score: number; dist: number }[] = [];\n for (const c of input.cards) {\n if (Math.max(c.w, c.h) * camera.scale < minPx) continue;\n const box = screenBox(c, camera);\n const visible = overlap(box, view);\n const inView = visible > 0;\n if (!inView && overlap(box, near) === 0) continue;\n const size = (box.x1 - box.x0) * (box.y1 - box.y0);\n let score = inView ? visible : size;\n if (input.playing?.has(c.id)) score *= KEEP_BONUS;\n const dist = Math.hypot((box.x0 + box.x1) / 2 - cx, (box.y0 + box.y1) / 2 - cy);\n scored.push({ id: c.id, inView, score, dist });\n }\n scored.sort(\n (a, b) =>\n Number(b.inView) - Number(a.inView) ||\n b.score - a.score ||\n a.dist - b.dist ||\n (a.id < b.id ? -1 : a.id > b.id ? 1 : 0),\n );\n return (scored.length > cap ? scored.slice(0, cap) : scored).map((s) => s.id);\n}\n\n// What the page lets us do. Injected so the pool runs under test; the default reads the browser.\nexport interface AmbientEnv {\n // The user asked for less motion: nothing plays on its own.\n reducedMotion(): boolean;\n // Data saver is on: no stream starts on its own.\n saveData(): boolean;\n // The tab is in the background.\n hidden(): boolean;\n}\n\ninterface NetworkInformationLike {\n saveData?: boolean;\n}\n\nexport const browserAmbientEnv: AmbientEnv = {\n reducedMotion: () =>\n typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches,\n saveData: () =>\n (navigator as Navigator & { connection?: NetworkInformationLike }).connection?.saveData ===\n true,\n hidden: () => typeof document !== 'undefined' && document.visibilityState === 'hidden',\n};\n\n// May videos start on their own at all?\nexport function ambientAllowed(env: AmbientEnv): boolean {\n return !env.reducedMotion() && !env.saveData();\n}\n","// `mode: 'always'`: the video cards that are in view play on their own, muted. A small pool of\n// VideoOverlay elements, one per playing card, each laid over its card exactly like the hover overlay\n// (video.ts: the card's thumbnail is the poster, the <video> fades in over it once a frame is up).\n// With `mode: 'hover'` this pool stays off and VideoController drives a single overlay instead: hover\n// plays a card after HOVER_DELAY_MS, a single selected card plays at once.\n//\n// Rules (a <video> is a decoder, and a canvas may hold hundreds of video cards):\n// - Only the cards that touch the viewport, are at least `minPlayPx` on screen (long side) and make the\n// cut of `maxPlaying` (8, or 2 on touch; the biggest and most central win) play (ambientPolicy.ts).\n// The others have no element at all, so nothing is fetched or decoded for them: their thumbnail is\n// all there is.\n// - A card that leaves the set is paused and its file let go of; its element is reused by the next\n// card (a pan creates no elements once the pool has grown to the screen). The set is re-planned when\n// the camera settles and, throttled, while it moves, so a card scrolling in starts a moment before\n// it shows.\n// - New cards start a handful at a time, a few frames apart, not all in the same tick; the ones that\n// show the most start first.\n// - Nothing plays with `prefers-reduced-motion` or data saver on; a background tab pauses the clocks\n// (the elements stay), and `setPaused` (e.g. a full-screen viewer open over the canvas) lets go of every stream.\n// - The elements are muted + playsinline (the only kind a phone starts without a gesture).\n// A card the hover overlay plays WITH sound (the pool is muted, the overlay is not) is excluded from the pool\n// while it does (`exclude`), so one card is never two streams.\nimport type { Camera } from '../math';\nimport { SMOOTH_WINDOWS, type FrameRateMonitor, type FrameWindow } from '../render/frameRate';\nimport { VideoOverlay, type VideoTarget } from './video';\nimport {\n AMBIENT_MAX_STREAMS,\n AMBIENT_MAX_PLAYING,\n AMBIENT_MAX_PLAYING_TOUCH,\n AMBIENT_MIN_PLAY_PX,\n ambientAllowed,\n browserAmbientEnv,\n planAmbient,\n type AmbientCandidate,\n type AmbientEnv,\n} from './ambientPolicy';\nimport type { VideoRect } from './videoGeometry';\n\n// The plan is recomputed at most this often while the camera moves (and once it settles).\nexport const REPLAN_THROTTLE_MS = 150;\n// New streams per pass, and the pause between passes (about three frames): a screenful of videos does\n// not open all its connections in one tick, and still all of them are up in well under a second.\nexport const STARTS_PER_PASS = 6;\nexport const START_SPACING_MS = 50;\n// Elements kept (empty) for the next card; past this they are let go of for good.\nexport const MAX_IDLE = 16;\n// A slow window cuts the playing cap to this share of what plays (never under 1 clip); a pair of smooth ones\n// gives back this much (rounded up), until `maxPlaying` is reached again.\nexport const SLOW_FACTOR = 0.6;\nexport const SMOOTH_GROWTH = 1.5;\n\nexport interface AmbientDeps {\n // The overlay layer the elements go in.\n root: HTMLElement;\n camera(): Camera;\n viewport(): { w: number; h: number };\n // Every video card, with its box (cheap: called on every plan).\n candidates(): Iterable<AmbientCandidate>;\n // A card's target as it is NOW (the live drag / resize preview, else the store's), null when it is\n // gone or has no video. Called for the cards that play, every frame (`follow`) or when they start.\n target(id: string): VideoTarget | null;\n // Subscribes `invalidate` to whatever changes the plan (cards moved, added, got their video).\n // Returns the unsubscribe.\n watch?(invalidate: () => void): () => void;\n // The set of playing cards changed (the hover overlay may now be redundant, or not).\n onChange?(): void;\n env?: AmbientEnv;\n // An extra reduced-motion switch (the OS one is read from `env`).\n reducedMotion?(): boolean;\n // Default to the globals, looked up at call time.\n setTimer?: typeof setTimeout;\n clearTimer?: typeof clearTimeout;\n now?(): number;\n // The board's frame-rate monitor: while the page runs slow the pool plays fewer clips (see `cap`).\n frameRate?: FrameRateMonitor;\n}\n\nexport class AmbientVideos {\n private readonly deps: AmbientDeps;\n private readonly env: AmbientEnv;\n // Playing cards -> their element.\n private readonly active = new Map<string, VideoOverlay>();\n // The elements live in this layer, which carries the camera: panning or zooming is ONE transform for\n // the whole screenful (a transform per video, 40 times a frame, is what stalls the compositor), and a\n // video's own style is written only when its card moves.\n private readonly world: HTMLElement;\n private wroteWorld = '';\n // Elements not on a card (kept to reuse; at most MAX_IDLE).\n private readonly idle: VideoOverlay[] = [];\n private on = false;\n private loop = true;\n // The sound switch: when muted the pool fully covers a card, so the hover overlay stays out.\n private soundMuted = true;\n private paused = false;\n private suspended = false;\n private touch = false;\n private minPlayPx = AMBIENT_MIN_PLAY_PX;\n private maxPlaying = AMBIENT_MAX_PLAYING;\n private maxPlayingTouch = AMBIENT_MAX_PLAYING_TOUCH;\n private excluded: string | null = null;\n // The cap the frame rate allows (Infinity: none); the effective one also honours maxPlaying.\n private adaptiveCap = Infinity;\n private smooth = 0;\n private lastPlan = 0;\n private timer: ReturnType<typeof setTimeout> | null = null;\n private disposed = false;\n private readonly cleanups: (() => void)[] = [];\n\n constructor(deps: AmbientDeps) {\n this.deps = deps;\n this.env = deps.env ?? browserAmbientEnv;\n this.suspended = this.env.hidden();\n const world = deps.root.ownerDocument.createElement('div');\n world.style.cssText =\n 'position:absolute;left:0;top:0;width:0;height:0;transform-origin:0 0;pointer-events:none;';\n deps.root.append(world);\n this.world = world;\n this.writeWorld(deps.camera());\n if (deps.watch) this.cleanups.push(deps.watch(() => this.schedule()));\n const monitor = deps.frameRate;\n if (monitor) {\n this.cleanups.push(\n // Only a playing pool is worth measuring.\n monitor.load(() => this.active.size > 0 && !this.suspended && !this.disposed),\n monitor.onWindow((w) => this.onWindow(w)),\n monitor.onStart(() => {\n this.smooth = 0;\n }),\n );\n }\n if (typeof document !== 'undefined') {\n const onVisibility = (): void => this.setSuspended(this.env.hidden());\n document.addEventListener('visibilitychange', onVisibility);\n this.cleanups.push(() => document.removeEventListener('visibilitychange', onVisibility));\n }\n // The OS switch can change while the canvas is open.\n if (typeof matchMedia === 'function') {\n const mq = matchMedia('(prefers-reduced-motion: reduce)');\n const fn = (): void => this.replan();\n mq.addEventListener?.('change', fn);\n this.cleanups.push(() => mq.removeEventListener?.('change', fn));\n }\n }\n\n // How many clips may play now: `maxPlaying` (`maxPlayingTouch` on touch), lowered while the page runs slow.\n get cap(): number {\n return Math.min(this.touch ? this.maxPlayingTouch : this.maxPlaying, this.adaptiveCap, AMBIENT_MAX_STREAMS);\n }\n\n // The ids that play now.\n get playingIds(): ReadonlySet<string> {\n return new Set(this.active.keys());\n }\n\n isPlaying(id: string): boolean {\n return this.active.has(id);\n }\n\n // The hover / selection overlay has nothing to add to this card: it plays here, muted, and the sound\n // switch is off.\n covers(id: string): boolean {\n return this.soundMuted && this.active.has(id);\n }\n\n // The switches: `always` turns the pool on, `loop` and `muted` are the playback options (the pool's own elements are muted whatever `muted` says: it only tells whether the hover overlay is\n // redundant).\n setOptions(o: {\n always: boolean;\n loop: boolean;\n muted: boolean;\n minPlayPx?: number;\n maxPlaying?: number;\n maxPlayingTouch?: number;\n }): void {\n if (this.disposed) return;\n if (o.minPlayPx !== undefined) this.minPlayPx = o.minPlayPx;\n if (o.maxPlaying !== undefined) this.maxPlaying = o.maxPlaying;\n if (o.maxPlayingTouch !== undefined) this.maxPlayingTouch = o.maxPlayingTouch;\n const loopChanged = o.loop !== this.loop;\n this.loop = o.loop;\n this.soundMuted = o.muted;\n this.on = o.always;\n if (!o.always) this.resetBudget();\n if (loopChanged) for (const v of [...this.active.values(), ...this.idle]) this.configure(v);\n this.replan();\n }\n\n // A finger (true) or a mouse / pen: the pool is smaller on touch.\n setTouch(touch: boolean): void {\n if (touch === this.touch || this.disposed) return;\n this.touch = touch;\n this.replan();\n }\n\n // Something covers the canvas (a full-screen viewer): every stream is let go of until it closes.\n setPaused(paused: boolean): void {\n if (paused === this.paused) return;\n this.paused = paused;\n this.replan();\n }\n\n // The card the hover overlay plays with sound (null: none). The pool lets go of it meanwhile.\n exclude(id: string | null): void {\n if (id === this.excluded) return;\n this.excluded = id;\n this.replan();\n }\n\n private resetBudget(): void {\n this.adaptiveCap = Infinity;\n this.smooth = 0;\n }\n\n // One window measured. Slow: play 60% of what plays now (at least one clip), the most visible ones. Smooth for\n // SMOOTH_WINDOWS in a row: give back 50%, up to `maxPlaying`.\n private onWindow(w: FrameWindow): void {\n if (this.disposed || !this.on || this.active.size === 0) return;\n const cap = this.cap;\n const ceiling = Math.min(this.touch ? this.maxPlayingTouch : this.maxPlaying, AMBIENT_MAX_STREAMS);\n let next = this.adaptiveCap;\n if (w.slow) {\n this.smooth = 0;\n const lowered = Math.max(1, Math.floor(Math.min(cap, this.active.size) * SLOW_FACTOR));\n // A slow window never raises the cap.\n if (lowered < cap) next = lowered;\n } else if (w.smooth) {\n if (++this.smooth >= SMOOTH_WINDOWS && this.adaptiveCap < ceiling) {\n this.smooth = 0;\n next = Math.ceil(this.adaptiveCap * SMOOTH_GROWTH);\n if (next >= ceiling) next = Infinity;\n }\n } else this.smooth = 0;\n if (next === this.adaptiveCap) return;\n this.adaptiveCap = next;\n this.replan();\n // The pool changed (replan pokes when the set of clips did): measure what that did to the page.\n this.deps.frameRate?.poke();\n }\n\n // The camera moved: the elements go with it (a transform each), and the plan is refreshed, throttled.\n sync(camera: Camera): void {\n if (this.disposed) return;\n // Every element, the ones still fading out (a card that left the set) included, is in this layer.\n this.writeWorld(camera);\n this.schedule();\n }\n\n // Every frame: each playing element goes where its card is now. A card that is gone, or resized, makes\n // the pool re-plan.\n follow(camera: Camera): void {\n if (this.disposed || this.active.size === 0) return;\n let stale = false;\n for (const [id, v] of this.active) {\n const t = this.deps.target(id);\n if (!t) {\n stale = true;\n continue;\n }\n const rect: VideoRect = { ...t.box, rot: t.rot };\n if (v.follow(rect, camera)) stale = true;\n }\n if (stale) this.schedule();\n }\n\n // Something that decides the plan changed (a card moved, appeared, got its video): refresh, throttled.\n invalidate(): void {\n this.schedule();\n }\n\n // The camera settled: refresh now.\n settle(): void {\n this.replan();\n }\n\n dispose(): void {\n if (this.disposed) return;\n this.disposed = true;\n this.cancelTimer();\n for (const f of this.cleanups) f();\n for (const v of [...this.active.values(), ...this.idle]) v.dispose();\n this.active.clear();\n this.idle.length = 0;\n this.world.remove();\n }\n\n private writeWorld(cam: Camera): void {\n const t = `translate(${cam.tx}px, ${cam.ty}px) scale(${cam.scale})`;\n if (t === this.wroteWorld) return;\n this.wroteWorld = t;\n this.world.style.transform = t;\n }\n\n private canPlay(): boolean {\n return this.on && !this.paused && !this.disposed && ambientAllowed(this.env) && !this.reduced();\n }\n\n private reduced(): boolean {\n return this.deps.reducedMotion?.() === true;\n }\n\n private setSuspended(hidden: boolean): void {\n if (hidden === this.suspended || this.disposed) return;\n this.suspended = hidden;\n if (hidden) {\n for (const v of this.active.values()) v.suspend();\n } else {\n for (const v of this.active.values()) v.resume();\n this.replan();\n }\n }\n\n private configure(v: VideoOverlay): void {\n // Always muted: the pool never makes noise.\n v.setPlayback({ loop: this.loop, muted: true });\n }\n\n private schedule(): void {\n if (this.disposed || this.timer !== null) return;\n // Switched off and nothing left to let go of: changes to the cards cost nothing here.\n if (!this.on && this.active.size === 0) return;\n const set = this.deps.setTimer ?? setTimeout;\n const now = (this.deps.now ?? Date.now)();\n const wait = Math.max(0, this.lastPlan + REPLAN_THROTTLE_MS - now);\n this.timer = set(() => {\n this.timer = null;\n this.replan();\n }, wait);\n }\n\n private cancelTimer(): void {\n if (this.timer === null) return;\n (this.deps.clearTimer ?? clearTimeout)(this.timer);\n this.timer = null;\n }\n\n // Brings the playing set to what the plan wants: let go of the cards that left, start (a few at a time)\n // the ones that came in.\n private replan(): void {\n if (this.disposed) return;\n this.cancelTimer();\n this.lastPlan = (this.deps.now ?? Date.now)();\n let changed = false;\n // The cards to play with their targets (a card that has no target any more is not one).\n const want: [string, VideoTarget][] = [];\n if (this.canPlay()) {\n const cards = [...this.deps.candidates()].filter((c) => c.id !== this.excluded);\n const ids = planAmbient({\n cards,\n camera: this.deps.camera(),\n viewport: this.deps.viewport(),\n playing: new Set(this.active.keys()),\n cap: this.cap,\n minPlayPx: this.minPlayPx,\n });\n for (const id of ids) {\n const t = this.deps.target(id);\n if (t) want.push([id, t]);\n }\n }\n const wanted = new Set(want.map(([id]) => id));\n for (const [id, v] of this.active) {\n if (wanted.has(id)) continue;\n v.hide();\n this.active.delete(id);\n this.idle.push(v);\n changed = true;\n }\n let starts = 0;\n let more = false;\n for (const [id, t] of want) {\n const have = this.active.get(id);\n if (have) {\n // Same card, new file (the card's video was replaced): start it over.\n if (have.activeSrc !== null && have.activeSrc !== t.src) have.show(t, this.deps.camera());\n continue;\n }\n if (starts >= STARTS_PER_PASS) {\n more = true;\n continue;\n }\n const v = this.take();\n this.active.set(id, v);\n this.writeWorld(this.deps.camera());\n v.show(t, this.deps.camera());\n if (this.suspended) v.suspend();\n starts++;\n changed = true;\n }\n // Spare elements past what the next pan needs go for good.\n while (this.idle.length > MAX_IDLE) this.idle.shift()?.dispose();\n if (more) {\n const set = this.deps.setTimer ?? setTimeout;\n this.timer = set(() => {\n this.timer = null;\n this.replan();\n }, START_SPACING_MS);\n }\n if (changed) {\n this.deps.onChange?.();\n // The pool changed: the load did too.\n this.deps.frameRate?.poke();\n }\n }\n\n // An element for a new card: one that is free, else a new one.\n private take(): VideoOverlay {\n const idle = this.idle.pop();\n if (idle) return idle;\n const v = new VideoOverlay(this.world, {\n spinner: false,\n worldSpace: true,\n });\n this.configure(v);\n return v;\n }\n}\n","// When may a video card play on hover or selection? Pure rules, shared by the controller and its tests.\n// No DOM, no timers.\n\n// Hover must be held this long before a card starts playing (a pointer sweeping across the canvas must\n// not start a stream per card).\nexport const HOVER_DELAY_MS = 300;\n// Below this on-screen width a card is too small to be worth a stream.\nexport const MIN_SCREEN_PX = 160;\n\nexport interface VideoCardState {\n id: string;\n hasVideo: boolean;\n // CSS px on screen (world width x zoom).\n screenWidth: number;\n // The always-playing pool already plays this card, muted, and sound is off: the hover / selection\n // overlay would only restart the same picture over itself.\n covered?: boolean;\n}\n\nexport type PlaybackSource = 'selection' | 'hover';\n\nexport interface PolicyInput {\n // Edit gestures (drags, carries) block playback through `enabled`; touch has no hover and no\n // selection playback; a moving camera hides the overlay until it settles.\n enabled: boolean;\n touch: boolean;\n // Hover playback switch; selection playback is not affected.\n hoverPlay?: boolean;\n cameraMoving: boolean;\n selection: readonly string[];\n hoverId: string | null;\n card(id: string): VideoCardState | null;\n}\n\nexport interface PlaybackWant {\n // A single selected video card: plays at once.\n immediate: string | null;\n // The hovered video card: plays after HOVER_DELAY_MS, unless it already plays.\n delayed: string | null;\n}\n\nexport function isPlayable(card: VideoCardState | null): boolean {\n return (\n card !== null && card.hasVideo && card.covered !== true && card.screenWidth >= MIN_SCREEN_PX\n );\n}\n\n// Selection beats hover, but only when the selected card can actually play: a selected image card\n// does not stop a hovered video from starting.\nexport function wantedPlayback(input: PolicyInput): PlaybackWant {\n const none: PlaybackWant = { immediate: null, delayed: null };\n if (!input.enabled || input.touch || input.cameraMoving) return none;\n if (input.selection.length === 1) {\n const id = input.selection[0];\n if (isPlayable(input.card(id))) return { immediate: id, delayed: null };\n }\n const hover = input.hoverId;\n if (input.hoverPlay === false) return none;\n if (hover !== null && isPlayable(input.card(hover))) return { immediate: null, delayed: hover };\n return none;\n}\n","// Decides which video card plays, and when, from the pointer / selection / camera state (`mode: 'hover'`).\n// The side effects are injected (`show`, `hide`, timers), so the whole matrix runs under fake timers.\nimport {\n HOVER_DELAY_MS,\n wantedPlayback,\n type PlaybackWant,\n type VideoCardState,\n} from './videoPolicy';\n\nexport { HOVER_DELAY_MS, MIN_SCREEN_PX } from './videoPolicy';\nexport type { VideoCardState } from './videoPolicy';\n\nexport interface VideoControllerDeps {\n show(id: string): void;\n hide(): void;\n // The pointer rests on a playable card and the hover delay is running: `id` (the card is asked for, so\n // the overlay can start its buffering clock now, not when the delay is over), or null when the hover\n // ended or the card stopped being playable before it played. `show` follows when the delay is over.\n pending?(id: string | null): void;\n // Re-read whenever a decision is made (and when the hover timer fires), never cached.\n card(id: string): VideoCardState | null;\n // Default to the globals, looked up at call time.\n setTimer?: typeof setTimeout;\n clearTimer?: typeof clearTimeout;\n}\n\nexport class VideoController {\n private readonly deps: VideoControllerDeps;\n private selection: readonly string[] = [];\n private hoverId: string | null = null;\n private moving = false;\n private touch = false;\n private enabled = true;\n private hoverPlay = true;\n private playing: string | null = null;\n // The hover timer: the card it was armed for, and its handle.\n private timerFor: string | null = null;\n private timer: ReturnType<typeof setTimeout> | null = null;\n\n constructor(deps: VideoControllerDeps) {\n this.deps = deps;\n }\n\n get playingId(): string | null {\n return this.playing;\n }\n\n // Pointer over a card (or null when it left every card).\n setHover(id: string | null): void {\n if (id === this.hoverId) return;\n this.hoverId = id;\n this.reconcile();\n }\n\n setSelection(ids: readonly string[]): void {\n // Copied: the caller's array may be a reused buffer.\n this.selection = ids.slice();\n this.reconcile();\n }\n\n setCameraMoving(moving: boolean): void {\n if (moving === this.moving) return;\n this.moving = moving;\n this.reconcile();\n }\n\n setTouch(touch: boolean): void {\n if (touch === this.touch) return;\n this.touch = touch;\n this.reconcile();\n }\n\n setEnabled(enabled: boolean): void {\n if (enabled === this.enabled) return;\n this.enabled = enabled;\n this.reconcile();\n }\n\n setHoverPlay(on: boolean): void {\n if (on === this.hoverPlay) return;\n this.hoverPlay = on;\n this.reconcile();\n }\n\n // Card sizes changed (zoom) or a card gained / lost its video.\n recheck(): void {\n this.reconcile();\n }\n\n dispose(): void {\n this.clearTimer();\n this.stop();\n }\n\n private want(): PlaybackWant {\n return wantedPlayback({\n enabled: this.enabled,\n touch: this.touch,\n hoverPlay: this.hoverPlay,\n cameraMoving: this.moving,\n selection: this.selection,\n hoverId: this.hoverId,\n card: this.deps.card,\n });\n }\n\n private reconcile(): void {\n const want = this.want();\n if (want.immediate !== null) {\n this.clearTimer();\n this.start(want.immediate);\n } else if (want.delayed !== null) {\n const id = want.delayed;\n if (this.playing === id) {\n // Selection released while the pointer is still on it: keep playing.\n this.clearTimer();\n return;\n }\n // Another card was playing: it stops now, the new one waits for its delay.\n this.stop();\n if (this.timerFor !== id) this.armTimer(id);\n } else {\n this.clearTimer();\n this.stop();\n }\n }\n\n private start(id: string): void {\n if (this.playing === id) return;\n this.playing = id;\n this.deps.show(id);\n }\n\n private stop(): void {\n if (this.playing === null) return;\n this.playing = null;\n this.deps.hide();\n }\n\n private armTimer(id: string): void {\n this.clearTimer(false);\n this.timerFor = id;\n this.deps.pending?.(id);\n const set = this.deps.setTimer ?? setTimeout;\n this.timer = set(() => {\n this.timer = null;\n this.timerFor = null;\n // The card may have shrunk, lost its video or been unhovered during the delay: ask again.\n if (this.want().delayed === id) this.start(id);\n else {\n this.deps.pending?.(null);\n this.reconcile();\n }\n }, HOVER_DELAY_MS);\n }\n\n // `notify`: tell the deps the pending card is gone (false when another card takes its place at once).\n private clearTimer(notify = true): void {\n if (this.timer !== null) {\n const clear = this.deps.clearTimer ?? clearTimeout;\n clear(this.timer);\n this.timer = null;\n if (notify) this.deps.pending?.(null);\n }\n this.timerFor = null;\n }\n}\n","// The video layer of a corkboard: wires the playing-video machinery (the hover / selection overlay, its\n// controller and the always-playing pool) to the store and the stage.\n//\n// mode 'always' every video card in view plays on its own, muted and looping (the pool, ambient.ts);\n// hover and selection still play a card with sound when `muted` is false\n// mode 'hover' a hovered card plays after a short delay, a single selected card plays at once\n// mode 'off' nothing plays: video cards are their poster\n//\n// A card plays only while it is on screen and at least MIN_SCREEN_PX wide (hover / selection) and the\n// camera is not moving. The poster is the card's own texture, drawn by WebGL underneath the <video>.\nimport type { Store } from '../store';\nimport type { FrameRateMonitor } from '../render/frameRate';\nimport type { Stage } from '../render/stage';\nimport type { ElementId } from '../types';\nimport { AmbientVideos } from './ambient';\nimport type { AmbientCandidate } from './ambientPolicy';\nimport { VideoOverlay, type VideoTarget } from './video';\nimport { VideoController } from './videoController';\n\nexport type VideoMode = 'always' | 'hover' | 'off';\n\nexport interface VideoOptions {\n // Default 'always'.\n mode?: VideoMode;\n // Loop the videos (default true).\n loop?: boolean;\n // Mute the videos (default true). Only a hovered / selected card can play with sound, and only in a\n // page that has had a user gesture (autoplay policy).\n muted?: boolean;\n // `mode: 'always'`: a card plays on its own only if its long side is at least this many CSS px on screen\n // (default 160). Smaller ones stay a thumbnail.\n minPlayPx?: number;\n // `mode: 'always'`: at most this many cards play at once on a mouse / pen device (default 8) ...\n maxPlaying?: number;\n // ... and on a touch device (default 2). The biggest and most central cards win.\n maxPlayingTouch?: number;\n}\n\nexport interface VideoLayerDeps {\n // The DOM layer the <video> elements go in (position: absolute, covering the canvas).\n root: HTMLElement;\n store: Store;\n stage: Stage;\n // The board's frame-rate monitor: with `mode: 'always'` the pool plays fewer clips while the page is slow.\n frameRate?: FrameRateMonitor;\n}\n\nexport class VideoLayer {\n private readonly overlay: VideoOverlay;\n private readonly controller: VideoController;\n private readonly ambient: AmbientVideos;\n private readonly store: Store;\n private readonly stage: Stage;\n private mode: VideoMode = 'always';\n private loop = true;\n private muted = true;\n private paused = false;\n // The tab is in the background: the overlay stays paused (sound included) until it is back.\n private hidden: boolean;\n private readonly cleanups: (() => void)[] = [];\n\n constructor(deps: VideoLayerDeps, options: VideoOptions = {}) {\n const { root, store, stage, frameRate } = deps;\n this.store = store;\n this.stage = stage;\n this.overlay = new VideoOverlay(root);\n const doc = root.ownerDocument;\n this.hidden = doc.visibilityState === 'hidden';\n const onVisibility = (): void => this.setHidden(doc.visibilityState === 'hidden');\n doc.addEventListener('visibilitychange', onVisibility);\n this.cleanups.push(() => doc.removeEventListener('visibilitychange', onVisibility));\n this.ambient = new AmbientVideos({\n root,\n camera: () => stage.cam.cam,\n viewport: () => ({ w: stage.cam.width, h: stage.cam.height }),\n candidates: () => this.candidates(),\n target: (id) => this.targetOf(id),\n // A card that got (or lost) its video, or moved: the store's changes.\n watch: (invalidate) =>\n store.subscribe((e) => {\n if (e.type === 'change') invalidate();\n }),\n // Which cards the pool plays decides whether the hover overlay has anything to add.\n onChange: () => this.controller.recheck(),\n frameRate,\n });\n this.controller = new VideoController({\n show: (id) => {\n this.showOverlay(id);\n this.ambient.exclude(id);\n },\n hide: () => {\n this.overlay.hide();\n this.ambient.exclude(null);\n },\n // The hover delay: the ring's wait starts with the pointer, not when the file is first asked for.\n pending: (id) => (id === null ? this.overlay.hide() : this.showOverlay(id, false)),\n card: (id) => {\n const el = this.store.get(id);\n if (!el || !el.media.video) return null;\n return {\n id,\n hasVideo: true,\n screenWidth: el.w * stage.cam.scale,\n covered: this.ambient.covers(id),\n };\n },\n });\n this.setOptions(options);\n }\n\n setOptions(o: VideoOptions): void {\n const mode = o.mode ?? this.mode;\n this.mode = mode;\n this.loop = o.loop ?? this.loop;\n this.muted = o.muted ?? this.muted;\n this.overlay.setPlayback({ loop: this.loop, muted: this.muted });\n this.controller.setEnabled(!this.paused && mode !== 'off');\n this.ambient.setOptions({\n always: mode === 'always',\n loop: this.loop,\n muted: this.muted,\n minPlayPx: o.minPlayPx,\n maxPlaying: o.maxPlaying,\n maxPlayingTouch: o.maxPlayingTouch,\n });\n // Whether the pool covers a card (it does not once the sound is on) decides the overlay too.\n this.controller.recheck();\n }\n\n get playing(): ReadonlySet<ElementId> {\n const ids = new Set<ElementId>(this.ambient.playingIds);\n const active = this.overlay.activeId;\n if (active !== null) ids.add(active);\n return ids;\n }\n\n // How many clips the pool may play now: `maxPlaying`, lowered while the page runs slow (read it with `playing`).\n get playingBudget(): number {\n return this.ambient.cap;\n }\n\n // The pointer is over a video card (null: none).\n setHover(id: ElementId | null): void {\n this.controller.setHover(id);\n }\n\n setSelection(ids: readonly ElementId[]): void {\n this.controller.setSelection(ids);\n }\n\n // A finger has no hover and no selection playback.\n setTouch(touch: boolean): void {\n this.controller.setTouch(touch);\n this.ambient.setTouch(touch);\n }\n\n // Pauses every stream (a lightbox over the canvas, say).\n setPaused(paused: boolean): void {\n this.paused = paused;\n this.controller.setEnabled(!paused && this.mode !== 'off');\n this.ambient.setPaused(paused);\n }\n\n // Called by the stage on every frame, after the camera moved or not.\n onFrame(camChanged: boolean): void {\n const cam = this.stage.cam.cam;\n if (camChanged) {\n this.overlay.sync(cam);\n this.ambient.sync(cam);\n this.controller.setCameraMoving(true);\n this.controller.recheck();\n }\n this.follow();\n this.ambient.follow(cam);\n }\n\n // The camera has been still for a moment.\n onSettle(): void {\n this.ambient.settle();\n this.controller.setCameraMoving(false);\n }\n\n dispose(): void {\n for (const f of this.cleanups) f();\n this.controller.dispose();\n this.ambient.dispose();\n this.overlay.dispose();\n }\n\n // The playing overlay goes where its card is NOW, every frame: the live drag / resize preview, else\n // the store. A card that is gone, or shrank under the playback threshold, stops through the controller.\n private follow(): void {\n const id = this.overlay.activeId;\n if (id === null) return;\n const r = this.stage.previewRectOf(id) ?? this.store.get(id);\n if (!r) this.controller.recheck();\n else if (this.overlay.follow({ x: r.x, y: r.y, w: r.w, h: r.h, rot: r.rot }, this.stage.cam.cam)) {\n this.controller.recheck();\n }\n }\n\n private setHidden(hidden: boolean): void {\n if (hidden === this.hidden) return;\n this.hidden = hidden;\n if (hidden) this.overlay.suspend();\n else this.overlay.resume();\n }\n\n private showOverlay(id: ElementId, load = true): void {\n const t = this.targetOf(id);\n if (!t) return;\n this.overlay.show(t, this.stage.cam.cam, load);\n // A card that starts while the tab is in the background stays paused.\n if (this.hidden) this.overlay.suspend();\n }\n\n private targetOf(id: ElementId): VideoTarget | null {\n const el = this.store.get(id);\n if (!el || !el.media.video) return null;\n // The live drag / resize preview, else the store's.\n const r = this.stage.previewRectOf(id) ?? el;\n return {\n id,\n src: el.media.video,\n box: { x: r.x, y: r.y, w: r.w, h: r.h },\n rot: r.rot,\n radius: el.radius,\n };\n }\n\n private *candidates(): IterableIterator<AmbientCandidate> {\n for (const el of this.store.elements()) {\n if (!el.media.video) continue;\n yield { id: el.id, x: el.x, y: el.y, w: el.w, h: el.h, rot: el.rot };\n }\n }\n}\n","// The public face of the library: an infinite canvas of image and video cards.\n//\n// const board = await Corkboard.create(div, { theme: 'dark' });\n// board.add([{ media: { src: 'https://…/a.jpg' } }, …]);\n// board.layout.tidy();\n// board.camera.fit();\n// board.on('selection', ({ ids }) => …);\n// board.dispose();\n//\n// `create` mounts a WebGL canvas and a DOM overlay layer in `host` (which needs a size: it is observed)\n// and sets `position: relative` on it if it was static.\nimport { EmbedLayer, type EmbedEvents, type EmbedOptions } from './embed/layer';\nimport { Emitter } from './events';\nimport { Interaction, type InteractionEvents, type InteractionOptions } from './interact/controller';\nimport { DEFAULT_SNAPPING, type SnapSettings } from './interact/snap';\nimport { elementBox } from './interact/geometry';\nimport { LayoutApi } from './LayoutApi';\nimport type { Camera, Rect } from './math';\nimport { createElement, kindOf, newId, sizeOf } from './model';\nimport type { OverlayFactory, Overlay } from './overlay';\nimport { FrameRateMonitor } from './render/frameRate';\nimport { Stage, type StageOptions } from './render/stage';\nimport { DARK_THEME, LIGHT_THEME, type Theme } from './render/theme';\nimport { Store } from './store';\nimport type { Element, ElementId, ElementInit, ElementPatch } from './types';\nimport { VideoLayer, type VideoOptions } from './video/layer';\n\nexport interface CorkboardOptions {\n // 'dark' (default), 'light', or a full `Theme`.\n theme?: Theme | 'dark' | 'light';\n // Background dot grid (default true).\n grid?: boolean;\n // Snapping while moving and resizing (default: guides on, grid off). `false` turns both off.\n snapping?: Partial<SnapSettings> | boolean;\n // Pointer, touch and keyboard handling (default on). `false` leaves the canvas to the host: drive the\n // camera with `board.camera` and the cards with the API.\n interaction?: boolean | InteractionOptions;\n // Video playback (see VideoOptions).\n video?: VideoOptions;\n // Embed cards (`media.embed`): live iframe limits and the poster / framing `resolve` hook.\n embeds?: EmbedOptions;\n // Texture pipeline knobs.\n textures?: Pick<StageOptions, 'budgetBytes' | 'workers' | 'workerUrl' | 'uploadBudgetMs' | 'overscan' | 'softCanvas'>;\n // Extra DOM overlays (a new element kind that needs live DOM).\n overlays?: OverlayFactory[];\n // The zoom range of the camera (default 0.05..4). Lower the minimum for a board that is much wider than\n // the screen and must still fit whole.\n camera?: { minScale?: number; maxScale?: number };\n // Load Pixi's CSP-safe build (no `new Function`).\n cspSafe?: boolean;\n // Time each GPU render (EXT_disjoint_timer_query_webgl2) for `stats()`.\n gpuTimer?: boolean;\n}\n\nexport interface CorkboardEvents extends InteractionEvents, EmbedEvents {\n // Elements were added, changed or removed (from the API or from a gesture).\n change: { added: readonly Element[]; updated: readonly Element[]; removed: readonly Element[] };\n // The camera moved (every frame of a move).\n camera: { camera: Camera };\n // The camera has been still for a moment.\n cameraSettled: { camera: Camera };\n}\n\nexport interface CameraOptions {\n // Animate the move (default true).\n animate?: boolean;\n // Screen px kept free around the target (default 48).\n padding?: number;\n}\n\nexport class CameraApi {\n constructor(\n private readonly stage: Stage,\n private readonly store: Store,\n ) {}\n\n get(): Camera {\n return { ...this.stage.cam.cam };\n }\n\n set(c: Camera): void {\n this.stage.setCamera(c);\n }\n\n // Fits the given cards (default: all) in the view. With nothing to fit (an empty board, or none of the\n // ids is a card) the camera stays where it is.\n fit(ids?: readonly ElementId[], o: CameraOptions = {}): void {\n if (ids ? !ids.some((id) => this.store.has(id)) : this.store.size === 0) return;\n this.stage.fitRect(() => this.stage.contentBounds(ids), o.animate ?? true, o.padding ?? 48);\n }\n\n // Fits a world rectangle in the view.\n zoomTo(r: Rect, o: CameraOptions = {}): void {\n this.stage.fitRect(r, o.animate ?? true, o.padding ?? 48);\n }\n\n zoomBy(k: number): void {\n this.stage.zoomBy(k);\n }\n\n // 100 % about the middle of the view.\n actual(): void {\n this.stage.zoomToActual();\n }\n\n // Centres the view on a world point, optionally at a given zoom.\n center(x: number, y: number, scale?: number, o: CameraOptions = {}): void {\n const s = scale ?? this.stage.cam.scale;\n const c: Camera = {\n scale: s,\n tx: this.stage.cam.width / 2 - x * s,\n ty: this.stage.cam.height / 2 - y * s,\n };\n if (o.animate ?? true) this.stage.cam.flyTo(c);\n else this.stage.setCamera(c);\n }\n\n // The world rectangle in view.\n visible(): Rect {\n return this.stage.cam.visibleRect();\n }\n\n screenToWorld(x: number, y: number): { x: number; y: number } {\n return this.stage.screenToWorld(x, y);\n }\n\n worldToScreen(x: number, y: number): { x: number; y: number } {\n return this.stage.worldToScreen(x, y);\n }\n}\n\nconst THEMES = { dark: DARK_THEME, light: LIGHT_THEME } as const;\nconst themeOf = (t: CorkboardOptions['theme']): Theme =>\n t === undefined ? DARK_THEME : typeof t === 'string' ? THEMES[t] : t;\n\nexport class Corkboard {\n readonly store = new Store();\n readonly camera: CameraApi;\n readonly layout: LayoutApi;\n // The render stage and the interaction layer, for advanced use (and the demo's stats panel).\n readonly stage: Stage;\n readonly interaction: Interaction | null;\n\n private readonly emitter = new Emitter<CorkboardEvents>();\n private readonly snapSettings: SnapSettings;\n private readonly overlayRoot: HTMLElement;\n private readonly videoLayer: VideoLayer;\n // Measures the page's frame rate in short bursts for the layers that shed load when it is slow.\n private readonly frameRate = new FrameRateMonitor();\n // The live iframes of the `embed` cards (see src/embed/layer.ts).\n readonly embeds: EmbedLayer;\n private readonly overlays: Overlay[] = [];\n private readonly cleanups: (() => void)[] = [];\n private disposed = false;\n\n static async create(host: HTMLElement, options: CorkboardOptions = {}): Promise<Corkboard> {\n const stage = await Stage.create(host, {\n ...options.textures,\n theme: themeOf(options.theme),\n grid: options.grid,\n gpuTimer: options.gpuTimer,\n cspSafe: options.cspSafe,\n minScale: options.camera?.minScale,\n maxScale: options.camera?.maxScale,\n });\n return new Corkboard(host, stage, options);\n }\n\n private constructor(\n host: HTMLElement,\n stage: Stage,\n options: CorkboardOptions,\n ) {\n this.stage = stage;\n stage.attach(this.store);\n this.camera = new CameraApi(stage, this.store);\n this.layout = new LayoutApi(this.store, stage);\n\n const sn = options.snapping;\n this.snapSettings =\n sn === false\n ? { guides: false, grid: false }\n : { ...DEFAULT_SNAPPING, ...(typeof sn === 'object' ? sn : {}) };\n\n if (getComputedStyle(host).position === 'static') host.style.position = 'relative';\n this.overlayRoot = document.createElement('div');\n Object.assign(this.overlayRoot.style, {\n position: 'absolute',\n inset: '0',\n overflow: 'hidden',\n pointerEvents: 'none',\n });\n host.appendChild(this.overlayRoot);\n\n this.videoLayer = new VideoLayer(\n { root: this.overlayRoot, store: this.store, stage, frameRate: this.frameRate },\n options.video,\n );\n this.embeds = new EmbedLayer(\n {\n root: this.overlayRoot,\n host,\n store: this.store,\n stage,\n frameRate: this.frameRate,\n emit: (type, payload) => this.emitter.emit(type, payload as CorkboardEvents[typeof type]),\n },\n options.embeds,\n );\n for (const make of options.overlays ?? []) {\n this.overlays.push(make({ root: this.overlayRoot, store: this.store, stage }));\n }\n\n this.cleanups.push(\n stage.onFrame((camChanged) => {\n this.videoLayer.onFrame(camChanged);\n this.embeds.onFrame(camChanged);\n for (const o of this.overlays) o.onFrame?.(camChanged);\n if (camChanged) this.emitter.emit('camera', { camera: { ...stage.cam.cam } });\n }),\n stage.onSettle(() => {\n this.videoLayer.onSettle();\n this.embeds.onSettle();\n // Still camera: the cheapest moment to see what the page really costs.\n this.frameRate.poke();\n for (const o of this.overlays) o.onSettle?.();\n this.emitter.emit('cameraSettled', { camera: { ...stage.cam.cam } });\n }),\n this.store.subscribe((e) => {\n if (e.type !== 'change') return;\n const c = e.change;\n this.emitter.emit('change', {\n added: c.added,\n updated: c.updated.map((u) => u.el),\n removed: c.removed,\n });\n }),\n );\n\n if (options.interaction !== false) {\n const iopts = typeof options.interaction === 'object' ? options.interaction : {};\n const it = new Interaction(host, stage, this.store, this.snapSettings, iopts);\n this.interaction = it;\n // Interaction events are the board's events.\n const forward = <K extends keyof InteractionEvents>(type: K): void => {\n this.cleanups.push(it.events.on(type, (p) => this.emitter.emit(type, p as CorkboardEvents[K])));\n };\n for (const t of [\n 'selection',\n 'hover',\n 'click',\n 'dblclick',\n 'transform',\n 'gesture',\n 'touch',\n 'delete',\n ] as const) {\n forward(t);\n }\n this.cleanups.push(\n it.events.on('hover', ({ id }) => {\n const el = id ? this.store.get(id) : undefined;\n this.videoLayer.setHover(el && el.media.video ? el.id : null);\n }),\n it.events.on('selection', ({ ids }) => {\n this.videoLayer.setSelection(ids);\n this.embeds.setSelection(ids);\n }),\n it.events.on('touch', ({ touch }) => {\n this.videoLayer.setTouch(touch);\n this.embeds.setTouch(touch);\n }),\n it.events.on('dblclick', ({ id }) => this.embeds.onDblClick(id)),\n );\n } else {\n this.interaction = null;\n }\n }\n\n // ── Elements ───────────────────────────────────────────────────────────────\n // Adds cards and returns their ids. A card with no `x` / `y` is placed on a free spot near the middle\n // of what is on screen, together with the others that have none, as one masonry block. Its size is the\n // one it was given, or its kind's default if that has a width of its own (embeds); an `x` or `y` it\n // came with is kept, the other coordinate is placed.\n add(input: ElementInit | readonly ElementInit[]): ElementId[] {\n const inits: readonly ElementInit[] = Array.isArray(input) ? input : [input as ElementInit];\n const els: Element[] = [];\n const unplaced: Element[] = [];\n const fixedSize = new Set<ElementId>();\n const given = new Map<ElementId, { x?: number; y?: number }>();\n for (const init of inits) {\n const id = init.id ?? newId();\n const el = createElement(init, id);\n els.push(el);\n if (init.x === undefined || init.y === undefined) {\n unplaced.push(el);\n if (init.w !== undefined || init.h !== undefined || el.kind === 'embed') fixedSize.add(id);\n if (init.x !== undefined || init.y !== undefined) given.set(id, { x: init.x, y: init.y });\n }\n }\n this.layout.placeNew(unplaced, fixedSize, given);\n this.store.add(els);\n return els.map((e) => e.id);\n }\n\n // Changes a card. Returns false when there is no such card.\n update(id: ElementId, patch: ElementPatch): boolean {\n if (!this.store.has(id)) return false;\n const p = { ...patch };\n // A new media with no explicit size keeps the card's width and takes the new aspect.\n if (p.media && p.w === undefined && p.h === undefined) {\n const cur = this.store.get(id) as Element;\n const size = sizeOf({ media: p.media, w: cur.w }, p.kind ?? cur.kind);\n if (p.media.aspect !== undefined || p.media.thumbhash !== undefined) p.h = size.h;\n }\n if (p.media && !p.kind) p.kind = kindOf({ media: p.media });\n this.store.update(id, p);\n return true;\n }\n\n // Removes cards; returns how many existed.\n remove(ids: ElementId | readonly ElementId[]): number {\n const list = typeof ids === 'string' ? [ids] : ids;\n return this.store.remove(list).length;\n }\n\n clear(): void {\n this.interaction?.setSelection([]);\n this.store.clear();\n }\n\n get(id: ElementId): Element | undefined {\n return this.store.get(id);\n }\n\n all(): Element[] {\n return [...this.store.elements()];\n }\n\n get size(): number {\n return this.store.size;\n }\n\n // The ids of the cards whose box meets a world rectangle.\n inRect(r: Rect): ElementId[] {\n return this.store\n .searchInto({ minX: r.x0, minY: r.y0, maxX: r.x1, maxY: r.y1 }, [])\n .map((e) => e.id);\n }\n\n // World rectangle covering the given cards (default: all).\n bounds(ids?: readonly ElementId[]): Rect {\n return this.stage.contentBounds(ids);\n }\n\n // ── Selection ──────────────────────────────────────────────────────────────\n get selection(): readonly ElementId[] {\n return this.interaction?.selection ?? [];\n }\n\n select(ids: readonly ElementId[]): void {\n this.interaction?.setSelection(ids);\n }\n\n selectAll(): void {\n this.interaction?.setSelection([...this.store.ids()]);\n }\n\n clearSelection(): void {\n this.interaction?.setSelection([]);\n }\n\n // The selected cards when two or more are, else all of them: what an \"arrange\" button should act on.\n get arrangeTargets(): readonly ElementId[] | undefined {\n return this.selection.length >= 2 ? this.selection : undefined;\n }\n\n // ── Settings ───────────────────────────────────────────────────────────────\n setTheme(theme: Theme | 'dark' | 'light'): void {\n this.stage.setTheme(themeOf(theme));\n this.embeds.setTheme();\n }\n\n setGrid(on: boolean): void {\n this.stage.setGrid(on);\n }\n\n // Alignment guides / snap to the background grid while moving and resizing.\n setSnapping(s: Partial<SnapSettings> | boolean): void {\n if (typeof s === 'boolean') {\n this.snapSettings.guides = s;\n this.snapSettings.grid = s;\n } else Object.assign(this.snapSettings, s);\n }\n\n get snapping(): Readonly<SnapSettings> {\n return this.snapSettings;\n }\n\n setVideo(o: VideoOptions): void {\n this.videoLayer.setOptions(o);\n }\n\n // Ids of the cards whose video plays now.\n get playing(): ReadonlySet<ElementId> {\n return this.videoLayer.playing;\n }\n\n // How many clips the always-playing pool may run now: `video.maxPlaying`, lowered while the page runs slow\n // and raised back when it is smooth (compare with `playing.size`).\n get videoBudget(): number {\n return this.videoLayer.playingBudget;\n }\n\n // Pauses every video (a lightbox open over the canvas, say).\n setVideoPaused(paused: boolean): void {\n this.videoLayer.setPaused(paused);\n }\n\n // Embed cards: live iframe limits (`maxLive`, `maxLiveTouch`, `minLivePx`) and the `resolution` of the\n // virtual screen pages are laid out at can change at any time.\n setEmbeds(o: EmbedOptions): void {\n this.embeds.setOptions(o);\n }\n\n // ── Events ─────────────────────────────────────────────────────────────────\n on<K extends keyof CorkboardEvents>(type: K, fn: (payload: CorkboardEvents[K]) => void): () => void {\n return this.emitter.on(type, fn);\n }\n\n off<K extends keyof CorkboardEvents>(type: K, fn: (payload: CorkboardEvents[K]) => void): void {\n this.emitter.off(type, fn);\n }\n\n // ── Diagnostics ────────────────────────────────────────────────────────────\n // Render loop counters and timings (rAF callbacks, mounted views, texture memory, percentiles).\n stats(): Record<string, unknown> {\n return {\n ...this.stage.stats(),\n embedsLive: this.embeds.live.size,\n embedsMaxLive: this.embeds.maxLive,\n };\n }\n\n // Bounding box of a card on screen, in host-local px (for HTML UI pinned to a card).\n screenRect(id: ElementId): { x: number; y: number; w: number; h: number } | null {\n const el = this.store.get(id);\n if (!el) return null;\n const b = elementBox(el);\n const a = this.stage.worldToScreen(b.minX, b.minY);\n const k = this.stage.cam.scale;\n return { x: a.x, y: a.y, w: (b.maxX - b.minX) * k, h: (b.maxY - b.minY) * k };\n }\n\n dispose(): void {\n if (this.disposed) return;\n this.disposed = true;\n this.interaction?.dispose();\n for (const f of this.cleanups) f();\n this.videoLayer.dispose();\n this.embeds.dispose();\n this.frameRate.dispose();\n for (const o of this.overlays) o.dispose();\n this.overlayRoot.remove();\n this.stage.dispose();\n this.emitter.clear();\n }\n}\n"],"names":["DEG","emptyBox","boxW","b","boxH","boxCx","boxCy","boxUnion","a","boxOfRect","worldRectOf","el","rotatedExtent","w","h","rotDeg","c","s","elementBox","r","cx","cy","e","corners","hw","hh","pts","dx","dy","toRectLocal","px","py","fromRectLocal","lx","ly","pointInRotatedRect","tol","l","rotatedRectsIntersect","ca","cb","axes","i","x0","y0","x1","y1","ax","ay","minA","maxA","minB","maxB","pa","pb","boxIntersectsRotatedRect","box","rotatedRectInsideBox","x","y","SAMPLE_WINDOW_MS","SLOW_FPS","SMOOTH_FPS","SMOOTH_WINDOWS","REFERENCE_HZ","STALL_MS","BURST_WINDOWS","AGREE_WINDOWS","HEARTBEAT_MS","FrameRateMonitor","deps","doc","win","id","onVisibility","fn","f","discardFirst","raf","tick","ts","fps","skip","refreshOf","k","verdict","deltas","d","round3","v","round6","videoPlacement","camera","rot","wcx","wcy","ox","oy","scale","rotR","MAX_LAYOUT_PX","DEFAULT_RESOLUTION","resolutionShortSide","res","embedPlacement","resolution","p","short","want","topRightX","topRightY","MAX_LIVE_DESKTOP","MAX_LIVE_TOUCH","MAX_MOUNTED_DESKTOP","MAX_MOUNTED_TOUCH","MAX_OFFSCREEN_DESKTOP","MAX_OFFSCREEN_TOUCH","MIN_LIVE_W","MIN_LIVE_H","MIN_LIVE_SCALE","KEEP_FACTOR","isEligible","o","planLive","input","plan","max","maxMounted","eligible","active","candidates","room","maxOffscreen","onScreen","offScreen","parkedOn","culled","parked","MIN_POSTER_PX","fetchPoster","url","timeoutMs","ctl","timer","blob","bmp","ok","PROVIDER_LABEL","LOCAL_HOSTS","normalizeEmbedUrl","raw","u","stripWww","parseTimestamp","t","m","YT_ID","YT_PATH_WORDS","YT_LIST","YT_HOSTS","ytParam","name","ytEmbed","path","params","q","parseYouTube","host","parts","series","value","start","list","VIMEO_LISTS","parseVimeo","isId","next","hash","SPOTIFY_TYPES","parseSpotify","type","compact","parseCodePen","team","user","kind","parseFigma","PARSERS","parseEmbedUrl","parse","hit","ALLOWLIST","providerOfIframeSrc","src","withAutoplay","provider","word","withJsApi","origin","isAllowlisted","baseResolved","embed","parsed","finitePositive","n","mergeResolved","base","info","out","canGoLive","sameEmbed","EMBED_CB","SNAPSHOT_MAX_SIDE","SNAPSHOT_MS","SOURCE","SNIPPET_BOOTSTRAP","PREVIEW_CACHE_NAME","PREVIEW_MEMORY_MAX","PREVIEW_PERSIST_MAX","hashString","previewKey","html","bucket","PreviewStore","mode","key","urlOf","persist","cache","keys","excess","SANDBOX_PROVIDER","SANDBOX_ARBITRARY","SANDBOX_SNIPPET","SNIPPET_CSP","REFERRER_POLICY","MEDIA_ALLOW","ALLOW","snippetDocument","originOf","iframeSpecFor","source","title","allowlisted","sandbox","allow","GUIDE_DARK","GUIDE_LIGHT","guideColor","theme","DARK_THEME","LIGHT_THEME","parseHex","cssHex","hostHue","GLYPH","tileSpec","glyph","pathOf","TILE_WIDTH","TILE_MAX_HEIGHT","tileSize","aspect","wrap","ctx","text","maxW","maxLines","words","lines","line","last","drawGlyph","g","color","FONT","paintTile","spec","dark","hsl","fg","dim","pad","labelPx","titlePx","gap","groupH","drawTile","resolve","MAX_LOADING","LOAD_SLOT_MS","CULL_MARGIN","FREEZE_PX","FREEZE_HYSTERESIS","FREEZE_STEP","FREEZE_MAX_MUL","MAX_SNAPSHOTS","CULL_SNAPSHOT_MS","CULL_SNAPSHOT_MIN_MS","CULL_SNAPSHOT_RESERVE","CULL_SNAPSHOT_MAX_SPEED","SPEED_MAX_DT_MS","CULL_DRAW_IDLE_MS","SNAPSHOT_WAIT_MS","SNAP_RETRY_MS","SNAP_TRIES","LAND_FIRST_MS","LAND_STEP_MS","LAND_TRIES","MIN_ANIMATING","PLAYER_READY_MS","PREVIEW_WORKERS","PREVIEW_SETTLE_MS","PREVIEW_JOB_MS","PREVIEW_DRAW_MS","PREVIEW_TRIES","PREVIEW_BUCKETS","PREVIEW_BOX","STUDIO_CSS","STYLE_ID","CSS","DONE_MARGIN","FLY_PAD","FLY_IN_SCALE","REVOKE_DELAY_MS","overlaps","normMinLive","EmbedLayer","options","svg","rasterizeSvg","normBudget","normWorkers","style","onDown","onKeyDoc","onKeyHost","onMessage","sandboxChanged","autoplayChanged","before","workers","ids","touch","camChanged","view","seen","cur","prev","dt","zoom","retitled","stale","entry","token","alive","answer","resolver","withTimeout","err","hostPoster","photo","candidate","real","mx","my","cam","grown","visW","visH","force","free","settled","rank","tier","wrapper","iframe","frame","spin","off","radius","z","held","small","frozen","interacting","msg","target","op","func","ranked","renderCount","area","dist","budget","animating","over","lowered","slow","mul","cull","dpr","seq","job","draw","done","tries","rect","best","bestRank","busy","j","on","go","studio","old","ifr","drawn","keyboard","flown","img","ms","reject","Emitter","set","payload","DEFAULTS","MIN_SCALE","MAX_SCALE","clamp","lo","hi","zoomAt","ZOOM_PER_PX","MAX_ZOOM_DELTA_PX","wheelZoomFactor","deltaY","deltaMode","visibleWorldRect","FRICTION","STOP_SPEED","CameraController","wake","bounds","empty","untouched","first","ratio","world","animate","duration","s0","s1","w0x","w0y","w1x","w1y","wx","wy","vel","decay","LOD_L0_MAX_DEVICE_PX","LOD_L1_MAX_DEVICE_PX","LOD_L2_MAX_DEVICE_PX","LOD_THRESHOLDS","LOD_UP","LOD_DOWN","MAX_LEVEL","MAX_L3","pickLevel","deviceLongSide","thresholds","level","L2_BUCKETS","L3_BUCKETS","l2Bucket","l3Bucket","outlineOf","quarterSteps","rs","outlinePoints","offset","push","steps","arcs","a0","UI_FONT","GUIDE_FADE_MS","MARK_ARM","CAP_HALF","PILL_H","PILL_PAD","PILL_RADIUS","PILL_OFFSET","LABEL_SIZE","MATCH_LABEL","MARK_CORNERS","isMeasure","guideKey","sameGeometry","ma","mb","GuideLayer","Container","Graphics","TextStyle","guides","changed","now","fading","step","kept","dropped","bg","used","pass","gd","axis","at","hp","alpha","vertical","marks","hu","hv","across","along","dir","horizontal","lineAxis","capAxis","ea","eb","mid","label","pill","len","Text","HANDLE_SIZE","OUTLINE","noop","OverlayLayer","th","sx","sy","sel","hd","holds","parkTicker","ticker","hold","released","cellsPerRow","cellsPerPage","Atlas","createPage","destroyPage","st","index","reused","col","row","cell","planEviction","entries","total","goal","RetireQueue","delay","run","it","minRenders","keep","MIP_FACTOR","L0_SPEC","L1_SPEC","INFLIGHT_PER_WORKER","RETRY_AFTER_MS","FAR_DIST","L1_PAGE_BYTES","absoluteUrl","card","zeros","clearBuffer","bytes","isOwn","TextureManager","renderer","opts","DecodeWorker","pinned","pinnedN","l2","l3","lv","desired","ct","needsOwn","items","wanted","resident","need2","failed","existing","maxLong","req","cap","wi","budgetMs","t0","destroySource","atlas","bitmap","ImageSource","Texture","Rectangle","moved","border","size","mips","TextureSource","gl","sys","glTex","zero","own","perCell","l1","oldTextures","old0","old1","MediaView","Sprite","_props","tex","VIEW_DEFINITIONS","ViewPools","def","pool","pooled","definitionOf","LOD_INTERVAL_MS","SETTLE_MS","GRID","VIEW_MARGIN","MOUNT_BUDGET_MS","BAKE_CORNER_SLACK","BAKE_ASPECT_SLACK","pct","r2","sameBytes","noContent","decodeBase64","bin","scaleBounds","min","Stage","app","unparkTicker","slot","GpuTimer","measure","ready","unpark","Ticker","Application","mq","store","props","all","baked","bakedAspect","long","fresh","hidden","any","none","borderChanged","hook","rg","camBusy","dirty","ph","tp","lap","arg","tx","ty","padX","padY","tS","hits","tM","stamp","entered","left","already","tU","tm","l0Missing","lvl","missing","all0","all1","has","onLost","onRestored","detail","e2","levels","nt","nr","ng","pages","glRendererString","dots","TilingSprite","ext","disjoint","HANDLE_HIT_PX","EDGE_HANDLE_MIN_PX","EDGE_HIT_PX","HANDLE_DIRS","BASE_AXIS","AXIS_CURSORS","resizeCursor","geometryBox","rects","make","selectionHandles","reader","els","edges","handleAt","hitPx","half","bestD","edgeAt","inX","inY","DEFAULT_TOLERANCE_PX","searchBox","safeZoom","collect","hitTest","scratch","elementsInBox","skipLocked","filter","MIN_SIZE","MAX_SIZE","S","placeAxis","alt","flipped","anchor","end","solveResize","fx","fy","lock","minW","minH","maxScale","minS","pointerShift","delta","edge","ResizeSession","handle","startWorld","affected","item","pointer","mods","snap","useSnap","dxw","dyw","dl","dv","swap","ew","eh","dirX","dirY","top","ncx","ncy","SNAP_THRESHOLD_PX","GUIDE_OVERSHOOT_PX","SNAP_RELEASE","SNAP_SWITCH","SNAP_EPS","EDGE","CENTER","WIN_NONE","WIN_ALIGN","WIN_SIZE","WIN_GAP","GAP_BOX_CAP","MAX_BLOCKERS","MAX_REF_GAPS","MAX_SIZE_MATCHES","REF_GAP_SCAN","AXES","EMPTY_LINES","EMPTY_GAPS","EMPTY_SIZES","sortedOrder","order","sortLines","rawV","rawOwner","rawKind","owner","validBox","buildSizes","boxes","buildGaps","sortedLo","blkLo","blkHi","gv","gBefore","gAfter","ka","aHi","aPlo","aPhi","nb","covLo","covHi","lowerBound","kb","ovLo","ovHi","perm","after","buildSnapIndex","maxOwners","xv","xo","xk","yv","yo","yk","owners","nx","ny","candCount","gapBoxes","pairRank","movingKind","lineKind","bestFound","bestAbs","bestDelta","bestLine","consider","abs","movingLine","probe","threshold","mv","fb","nbBefore","nbAfter","nbBeforeEdge","nbAfterEdge","findNeighbours","m0","m1","p0","p1","beforeEdge","afterEdge","gapInRow","gapFound","gapAbs","gapDelta","gapLine","gapSize","offerGap","probeGapSizes","gc","sign","probeGaps","mask","wholeBox","sizeFound","sizeAbs","sizeDelta","sizeOwner","offerSize","nearbyForSize","probeSizes","sizes","axWin","axLine","axDelta","axGap","axOwner","axBefore","axAfter","snapAxis","LINE_BIT","pos","sd","sabs","stickies","stickyFor","resetSnapHysteresis","uniqueSorted","pushGuide","extend","merged","addGuides","perpLo","perpHi","sameLo","sameHi","loOff","hiOff","extLoOff","extHiOff","lineD","MAX_LINE_BOXES","lineA","lineB","main","ownLo","ownHi","addGapGuides","scanned","refDist","refIdx","pushSizeGuide","plo","phi","addSizeGuides","winner","matched","newResult","moving","maskX","maskY","winX","winY","lineX","lineY","shiftMinX","shiftMaxX","shiftMinY","shiftMaxY","minX","maxX","minY","maxY","snapMove","thresholdWorld","extendWorld","snapResize","MAX_CANDIDATES","VIEW_GROW","DEFAULT_SNAPPING","isAxis","SnapSession","settings","gridSize","exclude","gx","gy","cands","edgeX","edgeY","DRAG_THRESHOLD_PX","NUDGE","NUDGE_BIG","round2","Interaction","stage","snapping","gone","dead","lost","live","previewed","visual","showHandles","releaseSpace","onBlur","session","wasSelected","clearOnClick","noClick","inside","press","patches","patch","cancelled","cmd","PLACEMENT_FALLBACK_WIDTH","PLACEMENT_FALLBACK_ASPECT","effectiveAspect","slotWidth","width","masonry","cols","height","median","values","sorted","byId","bandOrder","bands","band","sum","ordered","MIN_CARDS_FOR_MEDIAN","MIN_GAP","MAX_GAP","MIN_COLUMNS","MAX_COLUMNS","placementWidth","existingCardWidths","widths","placementGap","placementColumns","meanAspect","singleRow","planPlacement","aspectSum","columns","block","translatePlacement","result","translatePlacementInPlace","EPS","CLEAR_EPS","arrangeGap","shifted","addDelta","separate","inOrder","placed","farX","farY","right","down","align","aligned","distribute","centre","cursor","equalWidth","DEFAULT_STEP","DEFAULT_MAX_RADIUS_FACTOR","INITIAL_RINGS","MAX_RINGS","searchPlan","viewport","step0","factor","maxRadius","maxRings","autoSpotArea","reach","autoSpot","occupied","rings","from","found","searchRings","R","side","stride","grid","i0","i1","j0","j1","di","dj","bestI","bestJ","shouldPanTo","iw","ih","participates","tidy","part","cardWidths","layout","moves","NOMINAL_VIEW","ease","prefersReducedMotion","LayoutApi","tidyBoxes","masonryPack","alignBoxes","distributeBoxes","equalWidths","fixedSize","given","spot","resetRot","shown","near","to","current","finish","aspectOf","media","thumbHashToApproximateAspectRatio","kindOf","init","sizeOf","createElement","counter","newId","GEOMETRY","PATCHABLE","Store","RBush","listener","rec","lifted","STYLE_ATTR","injectRevealStyles","head","INDICATOR_DELAY_MS","FALLBACK_MS","FALLBACK_RVFC_MS","HAVE_CURRENT_DATA","HAVE_FUTURE_DATA","EVENTS","attachVideoReveal","video","hasRvfc","stalled","state","disposed","generation","rvfc","fallback","busyTimer","write","compute","waiting","clearFrameWatch","setFrame","armFallback","gen","watchFrame","reset","onEvent","createRevealSpinner","disc","ring","FADE_OUT_MS","HIDE_DELAY_MS","DISC_PX","WORLD_CAMERA","VideoOverlay","root","load","sameSource","resized","AMBIENT_MAX_STREAMS","AMBIENT_MAX_PLAYING","AMBIENT_MAX_PLAYING_TOUCH","AMBIENT_MIN_PLAY_PX","AMBIENT_MARGIN","KEEP_BONUS","screenBox","cos","sin","bw","bh","overlap","planAmbient","minPx","scored","visible","inView","score","browserAmbientEnv","ambientAllowed","env","REPLAN_THROTTLE_MS","STARTS_PER_PASS","START_SPACING_MS","MAX_IDLE","SLOW_FACTOR","SMOOTH_GROWTH","AmbientVideos","monitor","loopChanged","paused","ceiling","wait","cards","starts","more","have","idle","HOVER_DELAY_MS","MIN_SCREEN_PX","isPlayable","wantedPlayback","hover","VideoController","enabled","notify","VideoLayer","frameRate","invalidate","CameraApi","THEMES","themeOf","Corkboard","sn","iopts","forward","inits","unplaced"],"mappings":";;;AAuBO,MAAMA,IAAM,KAAK,KAAK,KAEhBC,KAAW,OAAY;AAAA,EAClC,MAAM;AAAA,EACN,MAAM;AAAA,EACN,MAAM;AAAA,EACN,MAAM;AACR,IACaC,KAAO,CAACC,MAAmBA,EAAE,OAAOA,EAAE,MACtCC,KAAO,CAACD,MAAmBA,EAAE,OAAOA,EAAE,MACtCE,KAAQ,CAACF,OAAoBA,EAAE,OAAOA,EAAE,QAAQ,GAChDG,KAAQ,CAACH,OAAoBA,EAAE,OAAOA,EAAE,QAAQ;AAatD,SAASI,GAASC,GAAQL,GAAa;AAC5C,SAAO;AAAA,IACL,MAAM,KAAK,IAAIK,EAAE,MAAML,EAAE,IAAI;AAAA,IAC7B,MAAM,KAAK,IAAIK,EAAE,MAAML,EAAE,IAAI;AAAA,IAC7B,MAAM,KAAK,IAAIK,EAAE,MAAML,EAAE,IAAI;AAAA,IAC7B,MAAM,KAAK,IAAIK,EAAE,MAAML,EAAE,IAAI;AAAA,EAAA;AAEjC;AAIO,SAASM,GAAU,GAAwD;AAChF,SAAO,EAAE,MAAM,EAAE,GAAG,MAAM,EAAE,GAAG,MAAM,EAAE,IAAI,EAAE,GAAG,MAAM,EAAE,IAAI,EAAE,EAAA;AAChE;AAEO,SAASC,EAAYC,GAA6D;AACvF,SAAO,EAAE,GAAGA,EAAG,GAAG,GAAGA,EAAG,GAAG,GAAGA,EAAG,GAAG,GAAGA,EAAG,GAAG,KAAKA,EAAG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,KAAK,aAAa,QAAA;AAClB,iBAAWR,KAAK,KAAK,SAAU,CAAAA,EAAA;AAC/B,WAAK,WAAW,QAAA,GAChB,KAAK,OAAO,QAAA,GACZ,KAAK,UAAU,QAAA;AACf,iBAAW8C,KAAK,KAAK,SAAU,CAAAA,EAAE,QAAA;AACjC,WAAK,YAAY,OAAA,GACjB,KAAK,MAAM,QAAA,GACX,KAAK,QAAQ,MAAA;AAAA;AAAA,EACf;AACF;"}
|
|
1
|
+
{"version":3,"file":"corkboard.js","sources":["../src/options.ts","../src/BoardCamera.ts","../src/BoardLayout.ts","../src/equal.ts","../src/model.ts","../src/change.ts","../src/validate.ts","../src/snapshot.ts","../src/Corkboard.ts"],"sourcesContent":["// Checks on the options the host passes to `Corkboard.create`, the `set*` / `setOptions` methods and the camera and\n// layout calls. A bad value is refused up front with a `CorkboardError('invalid')` that names the option, instead\n// of a raw TypeError later or a NaN that ends up in the camera, the store or a layer's budget. Numbers must be\n// finite and in range; `Infinity` is accepted only where the option documents \"no cap\".\nimport type { ArrangeOptions, CameraMoveOptions, GridOptions, MasonryOptions } from './api';\nimport type { CorkboardOptions, TextureOptions } from './Corkboard';\nimport type { EmbedOptions } from './embed/layer';\nimport type { InteractionOptions } from './interact/controller';\nimport type { SnapSettings } from './interact/snap';\nimport { DARK_THEME, LIGHT_THEME, type Theme } from './render/theme';\nimport type { VideoOptions } from './video/layer';\nimport { bad, boolean, finite, integer, isObject, limit, nonNegative, oneOf, positive, record, show } from './check';\n\n/** The keys of `o` that are set (an `undefined` value means \"leave it\", as in the setters). */\nconst given = <T extends object>(o: T): (keyof T & string)[] =>\n (Object.keys(o) as (keyof T & string)[]).filter((k) => o[k] !== undefined);\n\n// 0 < min <= max, both finite (also checks the `camera` option at create).\nexport function assertRange(where: string, min: unknown, max: unknown): void {\n const ok = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v) && v > 0;\n if (!ok(min) || !ok(max) || min > max) {\n bad(where, `needs finite numbers with 0 < min <= max (got min ${show(min)}, max ${show(max)})`);\n }\n}\n\n// ── Theme ────────────────────────────────────────────────────────────────────\nconst THEMES = { dark: DARK_THEME, light: LIGHT_THEME } as const;\n\nconst color = (where: string, field: string, v: unknown): void => {\n if (typeof v !== 'number' || !Number.isInteger(v) || v < 0 || v > 0xffffff) {\n bad(where, `${field} must be a colour number 0x000000..0xffffff (got ${show(v)})`);\n }\n};\n\nconst unit = (where: string, field: string, v: unknown): void => {\n if (typeof v !== 'number' || !(v >= 0 && v <= 1)) bad(where, `${field} must be a number from 0 to 1 (got ${show(v)})`);\n};\n\n/** `'dark'`, `'light'` or a whole {@link Theme}, as the theme to use. `undefined` is the dark one. */\nexport function resolveTheme(where: string, t: unknown): Theme {\n if (t === undefined) return DARK_THEME;\n if (t === 'dark' || t === 'light') return THEMES[t];\n if (!isObject(t) || Array.isArray(t)) {\n return bad(where, `theme must be 'dark', 'light' or a Theme object (got ${show(t)})`);\n }\n boolean(where, 'theme.dark', t.dark);\n for (const k of ['canvas', 'dot', 'border', 'accent', 'well']) color(where, `theme.${k}`, t[k]);\n unit(where, 'theme.borderAlpha', t.borderAlpha);\n if (t.dotAlpha !== undefined) unit(where, 'theme.dotAlpha', t.dotAlpha);\n if (t.guide !== undefined) color(where, 'theme.guide', t.guide);\n if (t.onGuide !== undefined) color(where, 'theme.onGuide', t.onGuide);\n return t as unknown as Theme;\n}\n\n// ── Snapping ─────────────────────────────────────────────────────────────────\n/** `setSnapping` / the `snapping` option: a boolean, or `{ guides?, grid? }`. */\nexport function checkSnapping(where: string, s: unknown): Partial<SnapSettings> | boolean {\n if (typeof s === 'boolean') return s;\n const o = record(where, 'snapping', s);\n for (const k of given(o)) {\n if (k === 'guides' || k === 'grid') boolean(where, `snapping.${k}`, o[k]);\n }\n return o as Partial<SnapSettings>;\n}\n\n// ── Video ────────────────────────────────────────────────────────────────────\n/** `video` at create, `video.setOptions`. */\nexport function checkVideoOptions(where: string, o: unknown): VideoOptions {\n const v = record(where, 'options', o) as VideoOptions & Record<string, unknown>;\n if (v.mode !== undefined) oneOf(where, 'mode', v.mode, ['always', 'hover', 'off']);\n if (v.loop !== undefined) boolean(where, 'loop', v.loop);\n if (v.muted !== undefined) boolean(where, 'muted', v.muted);\n if (v.minPlayPx !== undefined) nonNegative(where, 'minPlayPx', v.minPlayPx);\n if (v.maxPlaying !== undefined) limit(where, 'maxPlaying', v.maxPlaying);\n if (v.maxPlayingTouch !== undefined) limit(where, 'maxPlayingTouch', v.maxPlayingTouch);\n return v;\n}\n\n// ── Embeds ───────────────────────────────────────────────────────────────────\nconst LIMITS = [\n 'maxLive',\n 'maxLiveTouch',\n 'maxMounted',\n 'maxMountedTouch',\n 'maxOffscreen',\n 'maxOffscreenTouch',\n 'maxLoading',\n 'maxAnimating',\n] as const;\n\n/** `embeds` at create, `embeds.setOptions`. (`isolatedHosts` is checked, and normalised, by the layer.) */\nexport function checkEmbedOptions(where: string, o: unknown): EmbedOptions {\n const e = record(where, 'options', o) as EmbedOptions & Record<string, unknown>;\n for (const k of LIMITS) if (e[k] !== undefined) limit(where, k, e[k]);\n if (e.cullMargin !== undefined) nonNegative(where, 'cullMargin', e.cullMargin);\n if (e.minLiveScale !== undefined) nonNegative(where, 'minLiveScale', e.minLiveScale);\n if (e.resolveTimeoutMs !== undefined) nonNegative(where, 'resolveTimeoutMs', e.resolveTimeoutMs);\n if (e.freezePx !== undefined) nonNegative(where, 'freezePx', e.freezePx);\n if (e.previewWorkers !== undefined) integer(where, 'previewWorkers', e.previewWorkers, 0);\n if (e.minLivePx !== undefined) {\n const m = e.minLivePx;\n if (isObject(m)) {\n nonNegative(where, 'minLivePx.w', m.w);\n nonNegative(where, 'minLivePx.h', m.h);\n } else nonNegative(where, 'minLivePx', m);\n }\n if (e.resolve !== undefined && typeof e.resolve !== 'function') {\n bad(where, `resolve must be a function (got ${show(e.resolve)})`);\n }\n if (e.resolution !== undefined && e.resolution !== '720p' && e.resolution !== '1080p' && e.resolution !== 'native') {\n if (typeof e.resolution !== 'number') {\n bad(where, `resolution must be '720p', '1080p', 'native' or a number > 0 (got ${show(e.resolution)})`);\n }\n positive(where, 'resolution', e.resolution);\n }\n if (e.arbitrarySameOrigin !== undefined) boolean(where, 'arbitrarySameOrigin', e.arbitrarySameOrigin);\n if (e.autoplay !== undefined) boolean(where, 'autoplay', e.autoplay);\n if (e.adaptive !== undefined) boolean(where, 'adaptive', e.adaptive);\n if (e.snippetNetwork !== undefined) oneOf(where, 'snippetNetwork', e.snippetNetwork, ['images', 'none']);\n if (e.isolatedHosts !== undefined && !Array.isArray(e.isolatedHosts)) {\n bad(where, `isolatedHosts must be an array of host strings (got ${show(e.isolatedHosts)})`);\n }\n if (e.previewCache !== undefined) {\n const c = e.previewCache;\n const ok =\n c === 'memory' ||\n c === 'persistent' ||\n (isObject(c) && c.persistent === true && (c.name === undefined || typeof c.name === 'string'));\n if (!ok) bad(where, `previewCache must be 'memory', 'persistent' or { persistent: true, name? } (got ${show(c)})`);\n }\n return e;\n}\n\n// ── Interaction ──────────────────────────────────────────────────────────────\n/** `interaction` as an object at create, `interaction.setOptions`. */\nexport function checkInteractionOptions(where: string, o: unknown): InteractionOptions {\n const i = record(where, 'options', o) as InteractionOptions & Record<string, unknown>;\n for (const k of ['select', 'keyboard', 'commit', 'marquee', 'keepSelectionOnPan', 'selectionOutline'] as const) {\n if (i[k] !== undefined) boolean(where, k, i[k]);\n }\n if (i.emptyDrag !== undefined) oneOf(where, 'emptyDrag', i.emptyDrag, ['pan', 'marquee']);\n return i;\n}\n\n// ── Textures ─────────────────────────────────────────────────────────────────\n/** `textures` at create. */\nexport function checkTextureOptions(where: string, o: unknown): TextureOptions {\n const t = record(where, 'textures', o) as TextureOptions & Record<string, unknown>;\n if (t.budgetBytes !== undefined) positive(where, 'textures.budgetBytes', t.budgetBytes);\n if (t.workers !== undefined) integer(where, 'textures.workers', t.workers, 1);\n if (t.uploadBudgetMs !== undefined) positive(where, 'textures.uploadBudgetMs', t.uploadBudgetMs);\n if (t.overscan !== undefined) nonNegative(where, 'textures.overscan', t.overscan);\n if (t.softCanvas !== undefined) boolean(where, 'textures.softCanvas', t.softCanvas);\n if (t.workerUrl !== undefined && typeof t.workerUrl !== 'string' && !(t.workerUrl instanceof URL)) {\n bad(where, `textures.workerUrl must be a string or a URL (got ${show(t.workerUrl)})`);\n }\n return t;\n}\n\n// ── Create ───────────────────────────────────────────────────────────────────\n/** Every option of `Corkboard.create`, before anything is made. Returns the options as an object. */\nexport function checkCreateOptions(host: unknown, options: unknown): CorkboardOptions {\n const where = 'Corkboard.create';\n if (!isObject(host) || (host as { nodeType?: unknown }).nodeType !== 1) {\n bad(where, `host must be an HTMLElement (got ${show(host)})`);\n }\n const o = (options === undefined ? {} : record(where, 'options', options)) as CorkboardOptions & Record<string, unknown>;\n if (o.theme !== undefined) resolveTheme(`${where}: option \"theme\"`, o.theme);\n if (o.grid !== undefined) boolean(where, 'option \"grid\"', o.grid);\n if (o.snapping !== undefined) checkSnapping(`${where}: option \"snapping\"`, o.snapping);\n if (o.interaction !== undefined && typeof o.interaction !== 'boolean') {\n checkInteractionOptions(`${where}: option \"interaction\"`, o.interaction);\n }\n if (o.video !== undefined) checkVideoOptions(`${where}: option \"video\"`, o.video);\n if (o.embeds !== undefined) checkEmbedOptions(`${where}: option \"embeds\"`, o.embeds);\n if (o.textures !== undefined) checkTextureOptions(`${where}: option`, o.textures);\n // The zoom range itself is checked by `assertRange` in `create`, once the defaults are filled in.\n if (o.camera !== undefined) record(where, 'option \"camera\"', o.camera);\n if (o.cspSafe !== undefined) boolean(where, 'option \"cspSafe\"', o.cspSafe);\n if (o.gpuTimer !== undefined) boolean(where, 'option \"gpuTimer\"', o.gpuTimer);\n if (o.nonce !== undefined && typeof o.nonce !== 'string') {\n bad(where, `option \"nonce\" must be a string (got ${show(o.nonce)})`);\n }\n if (o.signal !== undefined && !(isObject(o.signal) && typeof o.signal.aborted === 'boolean')) {\n bad(where, `option \"signal\" must be an AbortSignal (got ${show(o.signal)})`);\n }\n return o;\n}\n\n// ── Camera and layout calls ──────────────────────────────────────────────────\n/** The `animate` / `padding` options of the camera moves. */\nexport function checkMoveOptions(where: string, o: unknown): CameraMoveOptions {\n const m = record(where, 'options', o) as CameraMoveOptions & Record<string, unknown>;\n if (m.animate !== undefined) boolean(where, 'animate', m.animate);\n if (m.padding !== undefined) nonNegative(where, 'padding', m.padding);\n return m;\n}\n\n/** The options of every layout call: `animate`, `duration`, and for the grids `gap`, `columns` and `width`. */\nexport function checkLayoutOptions(where: string, o: unknown, grid: 'none' | 'grid' | 'masonry' = 'none'): MasonryOptions {\n const m = record(where, 'options', o) as MasonryOptions & Record<string, unknown>;\n const a: ArrangeOptions = m;\n if (a.animate !== undefined) boolean(where, 'animate', a.animate);\n if (a.duration !== undefined) nonNegative(where, 'duration', a.duration);\n if (grid !== 'none') {\n const g: GridOptions = m;\n if (g.gap !== undefined) nonNegative(where, 'gap', g.gap);\n if (g.columns !== undefined) integer(where, 'columns', g.columns, 1);\n }\n if (grid === 'masonry' && m.width !== undefined) positive(where, 'width', m.width);\n return m;\n}\n\n/** A point of the world or of the screen: both coordinates finite. */\nexport function checkPoint(where: string, x: unknown, y: unknown): void {\n finite(where, 'x', x);\n finite(where, 'y', y);\n}\n","// `board.camera` (typed as `CameraApi` in api.ts): moves and reads the stage's camera.\nimport type { CameraApi, CameraMoveOptions } from './api';\nimport { assertRect, idList, positive } from './check';\nimport { CorkboardError } from './errors';\nimport { assertRange, checkMoveOptions, checkPoint } from './options';\nimport type { Camera, Rect } from './math';\nimport type { Stage } from './render/stage';\nimport type { Store } from './store';\nimport type { CardId } from './types';\n\nexport class BoardCamera implements CameraApi {\n constructor(\n private readonly stage: Stage,\n private readonly store: Store,\n // Throws once the board is disposed (the board's own check; a standalone api never does).\n private readonly alive: () => void = () => {},\n ) {}\n\n get(): Camera {\n this.alive();\n return { ...this.stage.cam.cam };\n }\n\n set(c: Camera): void {\n this.alive();\n const ok = (v: unknown): boolean => typeof v === 'number' && Number.isFinite(v);\n if (typeof c !== 'object' || c === null || !ok(c.tx) || !ok(c.ty) || !ok(c.scale) || c.scale <= 0) {\n throw new CorkboardError(\n 'invalid',\n 'camera.set: needs { tx, ty } finite and { scale } finite and > 0 (got ' + JSON.stringify(c) + ')',\n );\n }\n this.stage.setCamera(c);\n }\n\n // The zoom range.\n setRange(min: number, max: number): void {\n this.alive();\n assertRange('camera.setRange', min, max);\n this.stage.setScaleRange(min, max);\n }\n\n // Fits the given cards (default: all) in the view. With nothing to fit (an empty board, or none of the\n // ids is a card) the camera stays where it is.\n fit(ids?: CardId | readonly CardId[], o: CameraMoveOptions = {}): void {\n this.alive();\n const list = idList('camera.fit', ids, true);\n const opts = checkMoveOptions('camera.fit', o);\n if (list ? !list.some((id) => this.store.has(id)) : this.store.size === 0) return;\n this.stage.fitRect(() => this.stage.boundsOf(list), opts.animate ?? true, opts.padding ?? 48);\n }\n\n // Fits a world rectangle in the view.\n zoomTo(r: Rect, o: CameraMoveOptions = {}): void {\n this.alive();\n assertRect('camera.zoomTo', r);\n const opts = checkMoveOptions('camera.zoomTo', o);\n this.stage.fitRect({ x0: r.x0, y0: r.y0, x1: r.x1, y1: r.y1 }, opts.animate ?? true, opts.padding ?? 48);\n }\n\n zoomBy(k: number): void {\n this.alive();\n positive('camera.zoomBy', 'k', k);\n this.stage.zoomBy(k);\n }\n\n // 100 % about the middle of the view.\n actual(): void {\n this.alive();\n this.stage.zoomToActual();\n }\n\n // Centres the view on a world point, optionally at a given zoom.\n center(x: number, y: number, scale?: number, o: CameraMoveOptions = {}): void {\n this.alive();\n checkPoint('camera.center', x, y);\n if (scale !== undefined) positive('camera.center', 'scale', scale);\n const opts = checkMoveOptions('camera.center', o);\n const s = scale ?? this.stage.cam.scale;\n const c: Camera = {\n scale: s,\n tx: this.stage.cam.width / 2 - x * s,\n ty: this.stage.cam.height / 2 - y * s,\n };\n if (opts.animate ?? true) this.stage.cam.flyTo(c);\n else this.stage.setCamera(c);\n }\n\n // The world rectangle in view.\n visible(): Rect {\n this.alive();\n return this.stage.cam.visibleRect();\n }\n\n screenToWorld(x: number, y: number): { x: number; y: number } {\n this.alive();\n checkPoint('camera.screenToWorld', x, y);\n return this.stage.screenToWorld(x, y);\n }\n\n worldToScreen(x: number, y: number): { x: number; y: number } {\n this.alive();\n checkPoint('camera.worldToScreen', x, y);\n return this.stage.worldToScreen(x, y);\n }\n}\n","// Auto layout (`board.layout`, typed as `LayoutApi` in api.ts): the pure layout functions (src/layout/*) applied\n// to the elements of a store, with an optional animated transition. Every method takes the ids to arrange\n// (default: all) and writes the result to the store in one batch, right away: the animation only changes how\n// the cards are drawn.\nimport { boxOfRect, elementBox, type Aabb } from './interact/geometry';\nimport {\n align as alignBoxes,\n arrangeGap,\n autoSpot,\n autoSpotArea,\n distribute as distributeBoxes,\n equalWidth as equalWidths,\n masonry as masonryPack,\n placementColumns,\n placementGap,\n planPlacement,\n separate,\n slotWidth,\n tidy as tidyBoxes,\n effectiveAspect,\n type AlignMode,\n type LayoutItem,\n} from './layout/index';\nimport { median } from './layout/stats';\nimport type { ArrangeOptions, GridOptions, LayoutApi, MasonryOptions } from './api';\nimport { assertGeometry, idList, oneOf } from './check';\nimport { clamp } from './math';\nimport { checkLayoutOptions } from './options';\nimport type { Stage } from './render/stage';\nimport type { Store } from './store';\nimport type { Card, CardId } from './types';\n\ninterface Rect4 {\n x: number;\n y: number;\n w: number;\n h: number;\n}\n\n// The viewport new cards are placed against while the host has no size.\nconst NOMINAL_VIEW = { w: 1280, h: 800 };\n\nconst ALIGN_MODES: readonly AlignMode[] = ['left', 'centerX', 'right', 'top', 'middleY', 'bottom'];\n\nconst ease = (t: number): number => 1 - Math.pow(1 - t, 3);\nconst prefersReducedMotion = (): boolean =>\n typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;\n\ninterface Shown extends Rect4 {\n rot: number;\n}\n\nexport class BoardLayout implements LayoutApi {\n // The running animation: where each of its cards is drawn now, and the way to end it.\n private animation: { shown: Map<CardId, Shown>; cancel: () => void } | null = null;\n\n constructor(\n private readonly store: Store,\n private readonly stage: Stage,\n // Throws once the board is disposed (the board's own check; a standalone api never does).\n private readonly alive: () => void = () => {},\n ) {}\n\n // Ends a running animation at once: the cards show their final rects (already in the store). The board\n // calls this before `load()` swaps its cards.\n cancelAnimation(): void {\n this.animation?.cancel();\n this.animation = null;\n }\n\n private elementsOf(ids?: readonly CardId[]): Card[] {\n const out: Card[] = [];\n if (ids) {\n for (const id of ids) {\n const el = this.store.get(id);\n if (el) out.push(el);\n }\n } else {\n for (const id of this.store.ids()) out.push(this.store.get(id) as Card);\n }\n return out;\n }\n\n // Reorders the cards into a masonry grid in reading order (rows top to bottom, left to right). Cards\n // take the median width and keep their aspect; the block stays anchored at its current top-left.\n tidy(ids?: CardId | readonly CardId[], options: GridOptions = {}): void {\n this.alive();\n const list = idList('layout.tidy', ids, true);\n const opts = checkLayoutOptions('layout.tidy', options, 'grid');\n const els = this.elementsOf(list).filter((e) => !e.locked);\n const result = tidyBoxes(\n els.map((e) => ({\n id: e.id,\n box: elementBox(e),\n w: e.w,\n h: e.h,\n free: !e.aspectLocked,\n })),\n { gap: opts.gap, columns: opts.columns },\n );\n const patches = new Map<CardId, Rect4>();\n for (const [id, m] of result.moves) patches.set(id, m);\n this.apply(patches, opts, true);\n }\n\n // Packs the cards into columns in the order given (the store's draw order by default): each goes into\n // the shortest column. Unlike `tidy` nothing is reordered by position.\n masonry(ids?: CardId | readonly CardId[], options: MasonryOptions = {}): void {\n this.alive();\n const list = idList('layout.masonry', ids, true);\n const opts = checkLayoutOptions('layout.masonry', options, 'masonry');\n const els = this.elementsOf(list).filter((e) => !e.locked);\n if (els.length === 0) return;\n const width = opts.width ?? (median(els.map((e) => e.w)) || 248);\n const gap = opts.gap ?? placementGap(width);\n const items: LayoutItem[] = els.map((e) => ({ aspect: effectiveAspect(e.h / e.w) }));\n let aspectSum = 0;\n for (const it of items) aspectSum += it.aspect;\n const columns = opts.columns ?? placementColumns(els.length, aspectSum / els.length);\n const block = masonryPack(items, { width, gap, columns, slot: slotWidth(items, width) });\n let ax = Infinity;\n let ay = Infinity;\n for (const e of els) {\n const b = elementBox(e);\n ax = Math.min(ax, b.minX);\n ay = Math.min(ay, b.minY);\n }\n const patches = new Map<CardId, Rect4>();\n els.forEach((e, i) => {\n const r = block.rects[i];\n patches.set(e.id, { x: ax + r.x, y: ay + r.y, w: r.w, h: r.h });\n });\n this.apply(patches, opts, true);\n }\n\n align(mode: AlignMode, ids?: CardId | readonly CardId[], options: ArrangeOptions = {}): void {\n this.alive();\n oneOf('layout.align', 'mode', mode, ALIGN_MODES);\n const list = idList('layout.align', ids, true);\n const opts = checkLayoutOptions('layout.align', options);\n const els = this.elementsOf(list).filter((e) => !e.locked);\n const gap = arrangeGap(els.map((e) => e.w));\n const deltas = alignBoxes(\n els.map((e) => ({ id: e.id, box: elementBox(e) })),\n mode,\n { gap },\n );\n this.applyDeltas(deltas, opts);\n }\n\n // Equal gaps between the cards along an axis (three or more).\n distribute(axis: 'x' | 'y', ids?: CardId | readonly CardId[], options: ArrangeOptions = {}): void {\n this.alive();\n oneOf('layout.distribute', 'axis', axis, ['x', 'y']);\n const list = idList('layout.distribute', ids, true);\n const opts = checkLayoutOptions('layout.distribute', options);\n const els = this.elementsOf(list).filter((e) => !e.locked);\n const gap = arrangeGap(els.map((e) => e.w));\n const deltas = distributeBoxes(\n els.map((e) => ({ id: e.id, box: elementBox(e) })),\n axis,\n { gap },\n );\n this.applyDeltas(deltas, opts);\n }\n\n // Every card takes the median width; aspect-locked cards scale their height along. A card that grew\n // pushes its neighbours away (the arrange gap), as with align and distribute.\n equalWidth(ids?: CardId | readonly CardId[], options: ArrangeOptions = {}): void {\n this.alive();\n const list = idList('layout.equalWidth', ids, true);\n const opts = checkLayoutOptions('layout.equalWidth', options);\n const els = this.elementsOf(list).filter((e) => !e.locked);\n const sizes = equalWidths(\n els.map((e) => ({ id: e.id, w: e.w, h: e.h, aspectLocked: e.aspectLocked })),\n );\n if (sizes.size === 0) return;\n const rects = new Map<CardId, Rect4>();\n const items: { id: CardId; box: Aabb }[] = [];\n for (const el of els) {\n const s = sizes.get(el.id);\n // Resized about the centre so the card does not jump.\n const r = s\n ? { x: el.x + (el.w - s.w) / 2, y: el.y + (el.h - s.h) / 2, w: s.w, h: s.h }\n : { x: el.x, y: el.y, w: el.w, h: el.h };\n rects.set(el.id, r);\n items.push({ id: el.id, box: elementBox({ ...r, rot: el.rot }) });\n }\n const patches = new Map<CardId, Rect4>();\n const deltas = separate(items, arrangeGap(els.map((e) => e.w)));\n for (const [id, r] of rects) {\n const d = deltas.get(id);\n if (d || sizes.has(id)) patches.set(id, d ? { ...r, x: r.x + d.dx, y: r.y + d.dy } : r);\n }\n this.apply(patches, opts, false);\n }\n\n // Gives the elements that have no position a free spot near the middle of what is on screen, laid\n // out as one block. Mutates the given elements (they are not in the store yet). `fixedSize` keeps the\n // size an element came with; `given` keeps the one coordinate (x or y) a card was added with.\n placeNew(\n els: Card[],\n fixedSize: ReadonlySet<CardId>,\n given: ReadonlyMap<CardId, { x?: number; y?: number }> = new Map(),\n ): void {\n this.alive();\n if (els.length === 0) return;\n const widths: number[] = [];\n for (const e of this.store.elements()) widths.push(e.w);\n const items: LayoutItem[] = els.map((e) =>\n fixedSize.has(e.id)\n ? { aspect: effectiveAspect(e.h / e.w), w: e.w, h: e.h }\n : { aspect: effectiveAspect(e.h / e.w) },\n );\n const plan = planPlacement({\n items,\n existingCardWidths: widths,\n anchor: { kind: 'grab', x: 0, y: 0 },\n });\n const block = { w: plan.bounds.maxX - plan.bounds.minX, h: plan.bounds.maxY - plan.bounds.minY };\n const view = this.placementView();\n // Everything the search can reach, not only what is near the viewport.\n const occupied = this.store.searchInto(autoSpotArea(block, view), []).map((e) => elementBox(e));\n const spot = autoSpot(block, view, occupied);\n els.forEach((e, i) => {\n const r = plan.rects[i];\n const g = given.get(e.id);\n e.x = g?.x ?? spot.x + r.x;\n e.y = g?.y ?? spot.y + r.y;\n e.w = r.w;\n e.h = r.h;\n });\n }\n\n // The viewport placement works against: the camera's, or a nominal one around its centre while the host\n // has no size (the camera then reports a 1 px placeholder, and the search would not leave its spot).\n private placementView(): Aabb {\n const cam = this.stage.cam;\n const v = cam.visibleRect();\n if (!cam.isEmpty && cam.width > 1 && cam.height > 1) {\n return { minX: v.x0, minY: v.y0, maxX: v.x1, maxY: v.y1 };\n }\n const cx = (v.x0 + v.x1) / 2;\n const cy = (v.y0 + v.y1) / 2;\n return {\n minX: cx - NOMINAL_VIEW.w / 2,\n minY: cy - NOMINAL_VIEW.h / 2,\n maxX: cx + NOMINAL_VIEW.w / 2,\n maxY: cy + NOMINAL_VIEW.h / 2,\n };\n }\n\n // ── Applying ───────────────────────────────────────────────────────────────\n private applyDeltas(\n deltas: Map<CardId, { dx: number; dy: number }>,\n opts: ArrangeOptions,\n ): void {\n const patches = new Map<CardId, Rect4>();\n for (const [id, d] of deltas) {\n const el = this.store.get(id) as Card;\n patches.set(id, { x: el.x + d.dx, y: el.y + d.dy, w: el.w, h: el.h });\n }\n this.apply(patches, opts, false);\n }\n\n // Writes the patches to the store at once (one batch, the final rects), then animates the cards near the\n // viewport: the stage draws them at preview rects that run from where they were to where they are now.\n // `resetRot`: a grid lays cards out upright.\n private apply(patches: Map<CardId, Rect4>, opts: ArrangeOptions, resetRot: boolean): void {\n // Nothing is written (and no animation is touched) unless every rect is a real one.\n for (const [id, r] of patches) assertGeometry(`layout: card \"${id}\"`, r);\n // Where the cards of a running animation are drawn now: a new one starts from there.\n const shown = this.animation?.shown;\n this.animation?.cancel();\n this.animation = null;\n if (patches.size === 0) return;\n const animate = (opts.animate ?? true) && !prefersReducedMotion();\n const moving: { id: CardId; from: Shown; to: Rect4; toRot: number }[] = [];\n if (animate) {\n // Only cards that start or end near the viewport are animated; the rest jump (a preview forces a\n // view to be mounted, and a thousand of them would be the cost the culling exists to avoid).\n const v = this.stage.cam.visibleRect();\n const gx = (v.x1 - v.x0) * 0.2;\n const gy = (v.y1 - v.y0) * 0.2;\n const near: Aabb = { minX: v.x0 - gx, minY: v.y0 - gy, maxX: v.x1 + gx, maxY: v.y1 + gy };\n const hits = (b: Aabb): boolean =>\n b.minX <= near.maxX && b.maxX >= near.minX && b.minY <= near.maxY && b.maxY >= near.minY;\n for (const [id, to] of patches) {\n const el = this.store.get(id);\n if (!el) continue;\n const from = shown?.get(id) ?? { x: el.x, y: el.y, w: el.w, h: el.h, rot: el.rot };\n if (hits(boxOfRect(from)) || hits(boxOfRect(to))) {\n moving.push({ id, from, to, toRot: resetRot ? 0 : el.rot });\n }\n }\n }\n this.store.batch(() => {\n for (const [id, r] of patches) this.store.update(id, resetRot ? { ...r, rot: 0 } : r);\n });\n if (moving.length === 0) return;\n const duration = opts.duration ?? 320;\n const stage = this.stage;\n const start = performance.now();\n const current = new Map<CardId, Shown>();\n let done = false;\n const finish = (): void => {\n if (done) return;\n done = true;\n off();\n // The store holds the final rects already: dropping the previews shows them.\n for (const m of moving) {\n stage.clearPreview(m.id);\n stage.pin(m.id, false);\n }\n if (this.animation?.cancel === finish) this.animation = null;\n };\n const draw = (e: number): void => {\n for (const m of moving) {\n // A card removed mid-animation is gone from the stage too: no preview to leave behind.\n if (!this.store.has(m.id)) continue;\n const r = {\n x: m.from.x + (m.to.x - m.from.x) * e,\n y: m.from.y + (m.to.y - m.from.y) * e,\n w: m.from.w + (m.to.w - m.from.w) * e,\n h: m.from.h + (m.to.h - m.from.h) * e,\n rot: m.from.rot + (m.toRot - m.from.rot) * e,\n };\n current.set(m.id, r);\n stage.setPreview(m.id, r.x, r.y, r.w, r.h, r.rot);\n }\n };\n const off = stage.onBeforeFrame(() => {\n if (done) return;\n const t = clamp((performance.now() - start) / duration, 0, 1);\n draw(ease(t));\n if (t >= 1) finish();\n else stage.requestFrame();\n });\n for (const m of moving) stage.pin(m.id, true);\n // The first frame is the old arrangement: the final rects are in the store already.\n draw(0);\n this.animation = { shown: current, cancel: finish };\n stage.requestFrame();\n }\n}\n","// Structural equality for the JSON-like values a card holds (`media`, `data`): used to keep the board's own\n// object when an incoming value is equal to it, so a no-op load or replay is not reported as a change.\n//\n// Plain objects and arrays are compared by value, on own keys only (an own key holding `undefined` equals a\n// missing key, as in JSON; `{}` and `{ constructor: 'x' }` differ); numbers by `===` (so 0 equals -0, which JSON\n// cannot tell apart); anything else (a Date, a Map, a class instance, a function) by identity. A pair of objects\n// that is met again while comparing counts as equal the second time (if it were not, the first visit has already\n// answered `false`): a value that shares parts, or points back to itself, is compared in time linear in its\n// distinct pairs, not in its paths. Past a nesting depth of 64 the answer is `false`, so a very deep `data`\n// cannot overflow the stack.\nconst MAX_DEPTH = 64;\nconst hasOwn = Object.prototype.hasOwnProperty;\n\nconst isPlain = (o: object): boolean => {\n const p = Object.getPrototypeOf(o);\n return p === Object.prototype || p === null;\n};\n\ntype Seen = WeakMap<object, WeakSet<object>>;\n\nexport function deepEqual(a: unknown, b: unknown): boolean {\n return eq(a, b, 0, undefined);\n}\n\n// `seen` is made at the first pair of objects: comparing numbers and strings allocates nothing.\nfunction eq(a: unknown, b: unknown, depth: number, seen: Seen | undefined): boolean {\n if (a === b) return true;\n if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) {\n return typeof a === 'number' && typeof b === 'number' && a !== a && b !== b;\n }\n if (depth > MAX_DEPTH) return false;\n const arrA = Array.isArray(a);\n if (arrA !== Array.isArray(b)) return false;\n if (!arrA && (!isPlain(a) || !isPlain(b))) return false;\n seen ??= new WeakMap();\n let peers = seen.get(a);\n if (peers === undefined) seen.set(a, (peers = new WeakSet()));\n if (peers.has(b)) return true;\n peers.add(b);\n if (arrA) {\n const x = a as unknown[];\n const y = b as unknown[];\n if (x.length !== y.length) return false;\n for (let i = 0; i < x.length; i++) if (!eq(x[i], y[i], depth + 1, seen)) return false;\n return true;\n }\n const x = a as Record<string, unknown>;\n const y = b as Record<string, unknown>;\n for (const k of Object.keys(x)) {\n if (!eq(x[k], hasOwn.call(y, k) ? y[k] : undefined, depth + 1, seen)) return false;\n }\n for (const k of Object.keys(y)) if (!hasOwn.call(x, k) && y[k] !== undefined) return false;\n return true;\n}\n","// Turns what the host passes to `add` into stored elements.\nimport { thumbHashToApproximateAspectRatio } from 'thumbhash';\nimport { parseEmbedUrl } from './embed/providers';\nimport { DEFAULTS, type Card, type CardInit, type CardKind, type CardMedia, type CardMediaInput } from './types';\n\nexport function decodeBase64(s: string): Uint8Array {\n const bin = atob(s.replace(/-/g, '+').replace(/_/g, '/'));\n const out = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);\n return out;\n}\n\nexport function toBase64(bytes: Uint8Array): string {\n let bin = '';\n for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]);\n return btoa(bin);\n}\n\nconst SIZES = ['small', 'medium', 'large'] as const;\n\n// A copy of `m` that shares nothing with it, as the board stores it: only the known fields, the thumbhash as\n// base64. `keep` filters the URLs (a snapshot leaves out a `blob:` one: it is dead after a reload).\nexport function copyMedia(\n m: CardMediaInput,\n keep: (url: string | undefined) => boolean = () => true,\n): CardMedia {\n const out: CardMedia = {};\n if (m.src !== undefined && keep(m.src)) out.src = m.src;\n if (m.video !== undefined && keep(m.video)) out.video = m.video;\n if (m.aspect !== undefined) out.aspect = m.aspect;\n if (m.color !== undefined) out.color = m.color;\n if (m.embed !== undefined) out.embed = { ...m.embed };\n if (m.sizes) {\n const sizes: NonNullable<CardMediaInput['sizes']> = {};\n for (const k of SIZES) if (m.sizes[k] !== undefined && keep(m.sizes[k])) sizes[k] = m.sizes[k];\n if (Object.keys(sizes).length > 0) out.sizes = sizes;\n }\n if (m.thumbhash !== undefined) {\n out.thumbhash = typeof m.thumbhash === 'string' ? m.thumbhash : toBase64(m.thumbhash);\n }\n return out;\n}\n\n// height / width of the picture, from the media's `aspect`, else from its ThumbHash, else a default.\nexport function aspectOf(media: CardMediaInput, kind: CardKind): number {\n if (media.aspect !== undefined && Number.isFinite(media.aspect) && media.aspect > 0) {\n return media.aspect;\n }\n if (media.thumbhash !== undefined) {\n try {\n const bytes =\n typeof media.thumbhash === 'string' ? decodeBase64(media.thumbhash) : media.thumbhash;\n const r = thumbHashToApproximateAspectRatio(bytes);\n if (Number.isFinite(r) && r > 0) return 1 / r;\n } catch {\n // A malformed hash: fall through to the default.\n }\n }\n if (kind === 'embed') {\n // A known provider has a shape of its own (16:9 for a video, a strip for a Spotify track).\n const url = media.embed?.url;\n return (url !== undefined ? parseEmbedUrl(url)?.aspect : undefined) ?? DEFAULTS.embedAspect;\n }\n return kind === 'video' ? DEFAULTS.videoAspect : DEFAULTS.cardAspect;\n}\n\nexport const kindOf = (init: Pick<CardInit, 'kind' | 'media'>): CardKind =>\n init.kind ?? (init.media.embed ? 'embed' : init.media.video ? 'video' : 'image');\n\n// Size of a card: a given `w` and `h` win; a lone `w` or `h` is completed with the aspect.\nexport function sizeOf(init: CardInit, kind: CardKind): { w: number; h: number } {\n const aspect = aspectOf(init.media, kind);\n if (init.w !== undefined && init.h !== undefined) return { w: init.w, h: init.h };\n if (init.h !== undefined) return { w: init.h / aspect, h: init.h };\n const w = init.w ?? (kind === 'embed' ? DEFAULTS.embedWidth : DEFAULTS.cardWidth);\n return { w, h: Math.max(1, Math.round(w * aspect)) };\n}\n\n// `x` / `y` default to 0 here; `Corkboard.add` places cards that have none before it gets this far.\nexport function createElement(init: CardInit, id: string): Card {\n const kind = kindOf(init);\n const { w, h } = sizeOf(init, kind);\n return {\n id,\n kind,\n x: init.x ?? 0,\n y: init.y ?? 0,\n w,\n h,\n rot: init.rot ?? 0,\n locked: init.locked ?? false,\n media: copyMedia(init.media),\n radius: init.radius ?? DEFAULTS.cardRadius,\n aspectLocked: init.aspectLocked ?? true,\n data: init.data,\n };\n}\n\nlet counter = 0;\nexport function newId(): string {\n counter++;\n return typeof crypto !== 'undefined' && 'randomUUID' in crypto\n ? crypto.randomUUID()\n : `cb-${Date.now().toString(36)}-${counter.toString(36)}`;\n}\n","// Replaying and inverting a `Change`: `invertChange` (pure) and `applyChangeTo` (what `board.applyChange` runs on\n// the store). See `Corkboard.applyChange` for the contract.\nimport { deepEqual } from './equal';\nimport { copyMedia } from './model';\nimport type { Store } from './store';\nimport type { Change, ChangeSource, Card, CardPatch, CardProp, CardUpdate } from './types';\n\n/**\n * The change that undoes `c`: `added` and `removed` swap, each `updated` entry swaps `el` and `prev` (its\n * `props` stay), and each `order.moved` entry swaps `prevBelow` and `nextBelow`. `source` is kept. Pure, and an\n * involution: `invertChange(invertChange(c))` deep-equals `c`.\n *\n * Applying the result to a board in the state `c` left it in (`board.applyChange(c, { invert: true })` does\n * both) brings the board back to the state before `c`, draw order included.\n */\nexport function invertChange(c: Change): Change {\n const out: Change = {\n source: c.source,\n added: [...c.removed],\n removed: [...c.added],\n updated: c.updated.map((u): CardUpdate => ({ el: u.prev, prev: u.el, props: u.props })),\n };\n if (c.order) {\n out.order = {\n moved: c.order.moved.map((m) => ({ id: m.id, prevBelow: m.nextBelow, nextBelow: m.prevBelow })),\n };\n }\n return out;\n}\n\n/** Options of `board.applyChange`. */\nexport interface ApplyChangeOptions {\n /**\n * Apply the inverse of the change (an undo).\n * @default false\n */\n invert?: boolean;\n /**\n * The `source` of the `change` event this produces.\n * @default 'undo' when `invert` is set, else 'apply'\n */\n source?: ChangeSource;\n /**\n * What to do with an `updated` field that is no longer what the change started from (it was edited since):\n * `'skip'` leaves that field alone, `'overwrite'` writes it anyway. Cards that were `removed` and cards that\n * were `added` are not subject to it.\n * @default 'skip' when `invert` is set, else 'overwrite'\n */\n conflict?: 'skip' | 'overwrite';\n}\n\nconst PROPS: readonly CardProp[] = [\n 'x',\n 'y',\n 'w',\n 'h',\n 'rot',\n 'locked',\n 'media',\n 'radius',\n 'aspectLocked',\n 'data',\n 'kind',\n];\n\n// A whole card as the store keeps it: the change's fields exactly, `media` copied.\nfunction elementOf(src: Card): Card {\n return {\n id: src.id,\n kind: src.kind,\n x: src.x,\n y: src.y,\n w: src.w,\n h: src.h,\n rot: src.rot,\n locked: src.locked,\n media: copyMedia(src.media),\n radius: src.radius,\n aspectLocked: src.aspectLocked,\n data: src.data,\n };\n}\n\n/**\n * Replays `c` (inverted if asked) on the store: remove, upsert, update, then the draw order, in ONE batch. The\n * change must be valid (`validateChange`); nothing here throws for anything else: ids that are not there are\n * skipped.\n */\nexport function applyChangeTo(store: Store, c: Change, opts: ApplyChangeOptions): void {\n const change = opts.invert ? invertChange(c) : c;\n const skip = (opts.conflict ?? (opts.invert ? 'skip' : 'overwrite')) === 'skip';\n const source = opts.source ?? (opts.invert ? 'undo' : 'apply');\n store.batch(() => {\n // (a) removals\n if (change.removed.length > 0) store.remove(change.removed.map((el) => el.id), source);\n\n // (b) upserts: the card exactly as given. An id already there is overwritten in place, a new one goes on top.\n const added: Card[] = [];\n for (const el of change.added) {\n const next = elementOf(el);\n const cur = store.get(next.id);\n if (!cur) {\n added.push(next);\n continue;\n }\n if (deepEqual(cur.media, next.media)) next.media = cur.media;\n if (deepEqual(cur.data, next.data)) next.data = cur.data;\n store.update(next.id, next as CardPatch, source);\n }\n if (added.length > 0) store.add(added, source);\n\n // (c) field updates, written as they are (no size is derived from the media)\n for (const u of change.updated) {\n const cur = store.get(u.el.id);\n if (!cur) continue;\n const patch: Record<string, unknown> = {};\n let any = false;\n for (const p of u.props) {\n if (!PROPS.includes(p)) continue;\n if (skip && !deepEqual(cur[p], u.prev[p])) continue;\n const value = p === 'media' ? copyMedia(u.el.media) : u.el[p];\n if (deepEqual(cur[p], value)) continue;\n patch[p] = value;\n any = true;\n }\n if (any) store.update(cur.id, patch as CardPatch, source);\n }\n\n // (d) the draw order\n if (change.order && change.order.moved.length > 0) store.applyOrderMoves(change.order.moved, source);\n }, source);\n}\n","// Checks on what the host passes to `add`, `update` and `loadSnapshot`, before anything is stored. One place\n// (`checkMedia`, `checkFields`), so the entry points agree - a card `add` takes is a card `loadSnapshot` takes -\n// and a bad value is named (card and field) instead of surfacing later as a NaN transform or an empty canvas.\nimport { invertChange } from './change';\nimport { bad, boolean, finite, isObject, nonNegative, positive, show } from './check';\nimport type { Change, Card, CardId, CardInit, CardKind, CardPatch, CardMediaInput } from './types';\n\nconst KINDS: readonly CardKind[] = ['image', 'video', 'embed'];\n\n// Base64, standard or url-safe, padded or not (what the decode path reads): whatever passes must decode. `atob`\n// refuses a padded string whose length is not a multiple of 4, and a single leftover sextet.\nfunction checkThumbhash(where: string, v: unknown): void {\n if (v instanceof Uint8Array) return;\n let ok = false;\n if (typeof v === 'string' && /^[A-Za-z0-9+/_-]+={0,2}$/.test(v)) {\n const bare = v.replace(/=+$/, '');\n ok = bare.length % 4 !== 1 && (bare.length === v.length || v.length % 4 === 0);\n }\n if (!ok) bad(where, 'media.thumbhash must be a base64 string or a Uint8Array');\n}\n\nfunction checkMedia(where: string, media: unknown): void {\n if (typeof media !== 'object' || media === null || Array.isArray(media)) {\n return bad(where, `media must be an object (got ${show(media)})`);\n }\n const m = media as CardMediaInput;\n if (m.aspect !== undefined) positive(where, 'media.aspect', m.aspect);\n if (m.thumbhash !== undefined) checkThumbhash(where, m.thumbhash);\n const e = m.embed;\n if (e === undefined) return;\n if (typeof e !== 'object' || e === null) return bad(where, 'media.embed must be an object');\n const hasUrl = e.url !== undefined;\n const hasHtml = e.html !== undefined;\n if (hasUrl === hasHtml) bad(where, 'media.embed needs exactly one of url / html');\n if (hasUrl && (typeof e.url !== 'string' || e.url === '')) bad(where, 'media.embed.url must be a non-empty string');\n if (hasHtml && (typeof e.html !== 'string' || e.html === '')) bad(where, 'media.embed.html must be a non-empty string');\n}\n\n// The fields `add`, `update` and `loadSnapshot` all take (each only when given).\nfunction checkFields(where: string, o: Partial<CardInit>): void {\n if (o.kind !== undefined && !KINDS.includes(o.kind)) {\n bad(where, `kind must be one of ${KINDS.join(', ')} (got ${show(o.kind)})`);\n }\n if (o.x !== undefined) finite(where, 'x', o.x);\n if (o.y !== undefined) finite(where, 'y', o.y);\n if (o.rot !== undefined) finite(where, 'rot', o.rot);\n if (o.w !== undefined) positive(where, 'w', o.w);\n if (o.h !== undefined) positive(where, 'h', o.h);\n if (o.radius !== undefined) nonNegative(where, 'radius', o.radius);\n if (o.locked !== undefined) boolean(where, 'locked', o.locked);\n if (o.aspectLocked !== undefined) boolean(where, 'aspectLocked', o.aspectLocked);\n}\n\n// Every init of a batch, before any of them is stored. `exists` answers for the cards already on the board.\nexport function validateInits(inits: readonly CardInit[], exists: (id: CardId) => boolean): void {\n const seen = new Set<CardId>();\n inits.forEach((init, i) => {\n if (typeof init !== 'object' || init === null) return bad(`add: item ${i}`, 'must be an object');\n const id = init.id;\n if (id !== undefined && (typeof id !== 'string' || id === '')) {\n bad(`add: item ${i}`, `id must be a non-empty string (got ${show(id)})`);\n }\n const where = id !== undefined ? `add: item ${i} (\"${id}\")` : `add: item ${i}`;\n checkMedia(where, init.media);\n checkFields(where, init);\n if (id !== undefined) {\n if (exists(id)) bad(where, 'a card with this id already exists');\n if (seen.has(id)) bad(where, 'duplicate id in this batch');\n seen.add(id);\n }\n });\n}\n\n// The fields of a patch that were given (an `undefined` one means \"leave it\", as in `Store.update`).\nexport function validatePatch(id: CardId, patch: CardPatch): void {\n const where = `update (\"${id}\")`;\n if (typeof patch !== 'object' || patch === null) return bad(where, 'patch must be an object');\n if (patch.media !== undefined) checkMedia(where, patch.media);\n checkFields(where, patch);\n}\n\n// One card of a snapshot, as `getSnapshot` wrote it (or a hand-written one): the same checks as `add`, and\n// since a snapshot carries positions, x / y / w / h are required. `kind` is not: it comes from `media`.\nexport function validateSnapshotElement(i: number, el: unknown, seen: Set<CardId>): void {\n if (typeof el !== 'object' || el === null || Array.isArray(el)) {\n return bad(`loadSnapshot: element ${i}`, 'must be an object');\n }\n const o = el as Record<string, unknown> & Partial<CardInit>;\n const id = o.id;\n if (typeof id !== 'string' || id === '') {\n bad(`loadSnapshot: element ${i}`, `id must be a non-empty string (got ${show(id)})`);\n }\n const where = `loadSnapshot: element ${i} (\"${id}\")`;\n if (seen.has(id as string)) bad(where, 'duplicate id');\n seen.add(id as string);\n finite(where, 'x', o.x);\n finite(where, 'y', o.y);\n positive(where, 'w', o.w);\n positive(where, 'h', o.h);\n checkFields(where, o);\n checkMedia(where, o.media);\n}\n\nconst FIELDS = ['x', 'y', 'w', 'h', 'rot', 'locked', 'media', 'radius', 'aspectLocked', 'data', 'kind'] as const;\n\n// Every field of a whole card (a `Change` carries full cards, so none may be missing).\nfunction checkWholeElement(where: string, el: unknown): void {\n if (typeof el !== 'object' || el === null || Array.isArray(el)) return bad(where, 'must be an object');\n const o = el as Record<string, unknown> & Partial<Card>;\n if (typeof o.id !== 'string' || o.id === '') bad(where, `id must be a non-empty string (got ${show(o.id)})`);\n const at = `${where} (\"${o.id}\")`;\n if (o.kind === undefined) bad(at, `kind must be one of ${KINDS.join(', ')} (got undefined)`);\n for (const f of ['x', 'y', 'w', 'h', 'rot', 'radius', 'locked', 'aspectLocked'] as const) {\n if (o[f] === undefined) bad(at, `${f} is missing`);\n }\n checkFields(at, o as Partial<CardInit>);\n checkMedia(at, o.media);\n}\n\nconst checkId = (where: string, label: string, id: unknown): void => {\n if (typeof id !== 'string' || id === '') bad(where, `${label} must be a non-empty string (got ${show(id)})`);\n};\n\n// The shape of a `Change` as given: enough for `invertChange` to run on it without a TypeError, and nothing\n// about the values yet.\nfunction checkChangeShape(where: string, o: Partial<Change>): void {\n for (const k of ['added', 'removed', 'updated'] as const) {\n if (!Array.isArray(o[k])) bad(where, `${k} must be an array`);\n }\n o.added?.forEach((el, i) => {\n if (!isObject(el)) bad(`${where}: added[${i}]`, 'must be an object');\n });\n o.removed?.forEach((el, i) => {\n if (!isObject(el)) bad(`${where}: removed[${i}]`, 'must be an object');\n });\n o.updated?.forEach((u, i) => {\n const at = `${where}: updated[${i}]`;\n if (!isObject(u)) return bad(at, 'must be an object');\n if (!isObject(u.el)) bad(at, 'el must be an object');\n if (!isObject(u.prev)) bad(at, 'prev must be an object');\n if (!Array.isArray(u.props)) bad(at, 'props must be an array');\n });\n if (o.order !== undefined) {\n const moved = (o.order as { moved?: unknown } | null)?.moved;\n if (!Array.isArray(moved)) bad(where, 'order.moved must be an array');\n (moved as unknown[]).forEach((m, i) => {\n const at = `${where}: order.moved[${i}]`;\n if (!isObject(m)) return bad(at, 'must be an object');\n checkId(at, 'id', m.id);\n for (const k of ['prevBelow', 'nextBelow']) {\n if (m[k] !== null && (typeof m[k] !== 'string' || m[k] === '')) bad(at, `${k} must be an id or null (got ${show(m[k])})`);\n }\n });\n }\n}\n\n// An id may appear once in a list, and an id cannot be both added and removed: a change is a net diff.\nfunction checkUnique(where: string, label: string, ids: readonly unknown[]): Set<unknown> {\n const seen = new Set<unknown>();\n ids.forEach((id, i) => {\n if (seen.has(id)) bad(`${where}: ${label}[${i}]`, `duplicate id \"${String(id)}\"`);\n seen.add(id);\n });\n return seen;\n}\n\n/**\n * A `Change`, before `applyChange` touches the board: its shape and every value it would write. Throws 'invalid'\n * naming the entry, with nothing changed. `invert`: the change is applied inverted, so what is checked is the\n * inverse (the `removed` cards are written back whole, the `prev` of each `updated` entry is what lands).\n */\nexport function validateChange(c: unknown, invert = false): void {\n const where = 'applyChange';\n if (!isObject(c)) return bad(where, 'change must be an object');\n const o = c as Partial<Change>;\n checkChangeShape(where, o);\n // From here on `eff` is what will be written. The names in messages stay those of the change as given.\n const eff = invert ? invertChange(o as Change) : (o as Change);\n const addedLabel = invert ? 'removed' : 'added';\n const removedLabel = invert ? 'added' : 'removed';\n eff.added.forEach((el, i) => checkWholeElement(`${where}: ${addedLabel}[${i}]`, el));\n eff.removed.forEach((el, i) => checkId(`${where}: ${removedLabel}[${i}]`, 'id', (el as Partial<Card>).id));\n const addedIds = checkUnique(where, addedLabel, eff.added.map((el) => el.id));\n const removedIds = checkUnique(where, removedLabel, eff.removed.map((el) => el.id));\n for (const id of addedIds) {\n if (removedIds.has(id)) bad(where, `\"${String(id)}\" is both added and removed`);\n }\n eff.updated.forEach((u, i) => {\n const at = `${where}: updated[${i}]${invert ? ' (inverted: prev is written)' : ''}`;\n const el = u.el as Partial<Card>;\n checkId(at, invert ? 'prev.id' : 'el.id', el.id);\n const name = `${at} (\"${el.id}\")`;\n for (const p of u.props) {\n if (!(FIELDS as readonly string[]).includes(p)) bad(name, `unknown prop ${show(p)}`);\n if (p === 'data') continue;\n if (p === 'media') checkMedia(name, el.media);\n else if (el[p] === undefined) bad(name, `${p} is missing`);\n else checkFields(name, { [p]: el[p] });\n }\n });\n checkUnique(where, 'updated', eff.updated.map((u) => u.el.id));\n}\n","// A board as plain JSON: `getSnapshot()` writes one, `loadSnapshot()` reads one (src/Corkboard.ts). Pure: no\n// Pixi, no DOM.\n//\n// A snapshot never shares an object with the store: `media` (the only nested value the board owns) is copied on\n// the way out and on the way in. `data` is the host's and passes by reference.\nimport { deepEqual } from './equal';\nimport { CorkboardError } from './errors';\nimport type { Camera } from './math';\nimport { copyMedia, kindOf } from './model';\nimport { DEFAULTS, type Card, type CardId, type CardKind, type CardMedia, type CardMediaInput } from './types';\nimport { validateSnapshotElement } from './validate';\n\n/**\n * The version of the snapshot format this build writes, and the newest it reads. It goes up whenever a field\n * is added to, or changes meaning in, what a snapshot persists (the card fields, `media`, the camera): an older\n * build then refuses the file instead of dropping the field. `data` is the extension slot - put what you need\n * to persist there and the version does not change.\n */\nexport const SNAPSHOT_VERSION = 1;\n\n/** A card as a snapshot holds it: a `Card` (its `media.thumbhash` is a base64 string). */\nexport type SnapshotCard = Card;\n\n/**\n * A card as `loadSnapshot` reads it: the `id`, the position and size and the `media` are required, every other\n * field takes the default `add` gives it (`kind` comes from `media`). A `getSnapshot()` card fits.\n */\nexport type SnapshotCardInput = Pick<Card, 'id' | 'x' | 'y' | 'w' | 'h'> &\n Partial<Omit<Card, 'id' | 'x' | 'y' | 'w' | 'h' | 'media'>> & { media: CardMediaInput };\n\n/** What `loadSnapshot` takes: a {@link BoardSnapshot}, or one written by hand with only the required card fields. */\nexport interface BoardSnapshotInput {\n /** Must be `'corkboard'`. */\n format: 'corkboard';\n /** Format version; a newer one than this build reads is refused. */\n version: number;\n /** The cards, bottom of the draw order first. */\n elements: readonly SnapshotCardInput[];\n /** The view to jump to. */\n camera?: Camera;\n}\n\n/**\n * The persistent part of a board: its cards, bottom of the draw order first, and the camera. Selection,\n * theme, settings and runtime state (posters, snapshots, resolved embed posters) are not in it.\n */\nexport interface BoardSnapshot {\n /** Marks the object as a corkboard snapshot. */\n format: 'corkboard';\n /** Format version, {@link SNAPSHOT_VERSION}. `loadSnapshot()` refuses a newer one. */\n version: typeof SNAPSHOT_VERSION;\n /** Draw order, bottom first. */\n elements: SnapshotCard[];\n /** The view when it was taken. Absent with `getSnapshot({ camera: false })`. */\n camera?: Camera;\n}\n\nexport const SNAPSHOT_FORMAT = 'corkboard';\n\nconst isBlob = (u: string | undefined): boolean => u !== undefined && u.startsWith('blob:');\n\n// Whether two medias hold the same values (`loadSnapshot` keeps the store's media object for a card that\n// did not change, so the card does not show up in the `change` event).\nconst sameMedia = (a: CardMedia, b: CardMedia): boolean => deepEqual(a, b);\n\n// A `blob:` URL dies with the page that made it: after a reload it points at nothing, so it is left out\n// (the card then shows its placeholder until the host sets a durable URL with `update`).\nconst mediaToJSON = (m: CardMedia): CardMedia => copyMedia(m, (u) => !isBlob(u));\n\nexport function elementToJSON(el: Card): SnapshotCard {\n const out: SnapshotCard = {\n id: el.id,\n kind: el.kind,\n x: el.x,\n y: el.y,\n w: el.w,\n h: el.h,\n rot: el.rot,\n locked: el.locked,\n media: mediaToJSON(el.media),\n radius: el.radius,\n aspectLocked: el.aspectLocked,\n };\n // JSON drops an undefined `data` anyway; keep the object free of the key so deep-equality on it is exact.\n if (el.data !== undefined) out.data = el.data;\n return out;\n}\n\nexport function toSnapshot(elements: readonly Card[], camera: Camera | undefined): BoardSnapshot {\n const s: BoardSnapshot = {\n format: SNAPSHOT_FORMAT,\n version: SNAPSHOT_VERSION,\n elements: elements.map(elementToJSON),\n };\n if (camera) s.camera = { scale: camera.scale, tx: camera.tx, ty: camera.ty };\n return s;\n}\n\nconst invalid = (what: string): never => {\n throw new CorkboardError('invalid', `loadSnapshot: ${what}`);\n};\n\n// Checks the whole snapshot, then builds the elements; throws a `CorkboardError('invalid')` before any of\n// it is used. Fields a hand-written snapshot may leave out (all but id, x, y, w, h and media) take the same\n// defaults as `add`; keys it has that a card does not are dropped. `existing` looks up the cards on the board now.\nexport function fromSnapshot(\n s: unknown,\n existing: (id: CardId) => Card | undefined = () => undefined,\n): { elements: Card[]; camera?: Camera } {\n if (typeof s !== 'object' || s === null) return invalid('snapshot must be an object');\n const o = s as Record<string, unknown>;\n if (o.format !== SNAPSHOT_FORMAT) invalid(`format must be \"${SNAPSHOT_FORMAT}\" (got ${JSON.stringify(o.format)})`);\n const v = o.version;\n if (typeof v !== 'number' || !Number.isInteger(v) || v < 1) {\n invalid(`version must be a positive integer (got ${JSON.stringify(v)})`);\n }\n if ((v as number) > SNAPSHOT_VERSION) {\n invalid(\n `snapshot written by a newer corkboard (v${v}); this build reads up to v${SNAPSHOT_VERSION}`,\n );\n }\n if (!Array.isArray(o.elements)) return invalid('elements must be an array');\n let camera: Camera | undefined;\n if (o.camera !== undefined) {\n const c = o.camera as Partial<Camera> | null;\n const num = (v: unknown): boolean => typeof v === 'number' && Number.isFinite(v);\n if (typeof c !== 'object' || c === null || !num(c.scale) || !num(c.tx) || !num(c.ty) || (c.scale as number) <= 0) {\n invalid('camera must be { scale > 0, tx, ty } with finite numbers');\n }\n const cam = c as Camera;\n camera = { scale: cam.scale, tx: cam.tx, ty: cam.ty };\n }\n const seen = new Set<CardId>();\n o.elements.forEach((el, i) => validateSnapshotElement(i, el, seen));\n const elements = (o.elements as SnapshotCardInput[]).map((e): Card => {\n const copy = copyMedia(e.media);\n const prev = existing(e.id);\n const kind: CardKind = e.kind ?? kindOf({ media: copy });\n return {\n id: e.id,\n kind,\n x: e.x,\n y: e.y,\n w: e.w,\n h: e.h,\n rot: e.rot ?? 0,\n locked: e.locked ?? false,\n media: prev && sameMedia(prev.media, copy) ? prev.media : copy,\n radius: e.radius ?? DEFAULTS.cardRadius,\n aspectLocked: e.aspectLocked ?? true,\n // A `data` equal to the board's keeps the board's object: no phantom update, as with `media`.\n data: prev && deepEqual(prev.data, e.data) ? prev.data : e.data,\n };\n });\n return camera ? { elements, camera } : { elements };\n}\n","import { EmbedLayer, type EmbedEvents, type EmbedOptions } from './embed/layer';\nimport { clearPreviewCache } from './embed/previewCache';\nimport { CorkboardError, type BoardErrorEvent } from './errors';\nimport { Emitter } from './events';\nimport type { CameraApi, EmbedsApi, InteractionApi, LayoutApi, VideoApi } from './api';\nimport { BoardCamera } from './BoardCamera';\nimport { assertRect, bad, boolean, idList, show } from './check';\nimport { Interaction, type InteractionEvents, type InteractionOptions } from './interact/controller';\nimport { registerInternals } from './internals';\nimport { DEFAULT_SNAPPING, type SnapSettings } from './interact/snap';\nimport { elementBox } from './interact/geometry';\nimport { BoardLayout } from './BoardLayout';\nimport type { Camera, Rect, Box } from './math';\nimport {\n assertRange,\n checkCreateOptions,\n checkEmbedOptions,\n checkInteractionOptions,\n checkSnapping,\n checkVideoOptions,\n resolveTheme,\n} from './options';\nimport { applyChangeTo, type ApplyChangeOptions } from './change';\nimport { copyMedia, createElement, kindOf, newId, sizeOf } from './model';\nimport { FrameRateMonitor } from './render/frameRate';\nimport { Stage } from './render/stage';\nimport type { Theme } from './render/theme';\nimport { fromSnapshot, toSnapshot, type BoardSnapshot, type BoardSnapshotInput } from './snapshot';\nimport type { BoardStats } from './stats';\nimport { Store } from './store';\nimport { MAX_SCALE, MIN_SCALE } from './types';\nimport type { Change, ChangeSource, Card, CardId, CardInit, CardPatch, OrderChange } from './types';\nimport { validateChange, validateInits, validatePatch } from './validate';\nimport { VideoLayer, type VideoOptions } from './video/layer';\n\n/** The texture pipeline's options (`CorkboardOptions.textures`). Every one is optional. Create-only: the pipeline is built once, per board. */\nexport interface TextureOptions {\n /**\n * GPU texture memory budget in bytes (a finite number > 0). Use ~128 MB on small devices.\n * @default 268435456 (256 MB)\n */\n budgetBytes?: number;\n /**\n * Decode workers.\n * @default a quarter of the cores, 1..4\n */\n workers?: number;\n /**\n * URL of the decode worker script, for pages whose CSP forbids `worker-src blob:` (the built-in worker is\n * inlined and started from a blob URL). Serve `@niccolofanton/corkboard/decode.worker.js` yourself and pass\n * its URL here.\n */\n workerUrl?: string | URL;\n /**\n * Per-frame texture upload budget, ms.\n * @default 4\n */\n uploadBudgetMs?: number;\n /**\n * How far past the viewport textures are prepared, as a fraction of the viewport added on every side.\n * @default 0.5\n */\n overscan?: number;\n /**\n * Bake the rounded corners in a software canvas in the workers. Measured about 2x slower to load.\n * @default false\n */\n softCanvas?: boolean;\n}\n\n/** The zoom range of the camera (`CorkboardOptions.camera`). Both limits are optional. */\nexport interface CameraRange {\n /**\n * Lowest zoom. Lower it for a board that is much wider than the screen and must still fit whole.\n * @default 0.05\n */\n minScale?: number;\n /**\n * Highest zoom.\n * @default 4\n */\n maxScale?: number;\n}\n\n/**\n * Options of {@link Corkboard.create}. Every one is optional, and each is checked up front: a bad value (a NaN or\n * negative limit, an unknown theme name or enum value...) rejects `create` with `CorkboardError('invalid')`.\n *\n * Changeable later: `theme` (`setTheme`), `grid` (`setGrid`), `snapping` (`setSnapping`), `video`\n * (`video.setOptions`), `embeds` (`embeds.setOptions`), `camera` (`camera.setRange`) and the options of an\n * `interaction` object (`interaction.setOptions`). Create-only: `interaction` on / off, `textures`, `cspSafe`,\n * `nonce`, `gpuTimer` and `signal`.\n */\nexport interface CorkboardOptions {\n /**\n * `'dark'`, `'light'`, or a full {@link Theme}.\n * @default 'dark'\n */\n theme?: Theme | 'dark' | 'light';\n /**\n * Background dot grid.\n * @default true\n */\n grid?: boolean;\n /**\n * Snapping while moving and resizing. `false` turns guides and grid off, `true` turns both on.\n * @default { guides: true, grid: false }\n */\n snapping?: Partial<SnapSettings> | boolean;\n /**\n * Pointer, touch and keyboard handling. `false` leaves the canvas to the host: drive the camera with\n * `board.camera` and the cards with the API (and `board.interaction` is `null`).\n * @default true\n */\n interaction?: boolean | InteractionOptions;\n /** Video playback: mode, loop, mute and how many clips play at once. */\n video?: VideoOptions;\n /** Embed cards (`media.embed`): live iframe limits, the `resolve` hook and the security options. */\n embeds?: EmbedOptions;\n /** Texture pipeline: memory budget, decode workers, upload budget. */\n textures?: TextureOptions;\n /** The zoom range of the camera (`0 < minScale <= maxScale`, else `create` rejects with `'invalid'`; `camera.setRange` changes it later). */\n camera?: CameraRange;\n /**\n * Load Pixi's CSP-safe build, which does not use `new Function`. Needed under a CSP without `'unsafe-eval'`.\n * @default false\n */\n cspSafe?: boolean;\n /**\n * Nonce for the `<style>` elements the board injects (the embed layer's and the video layer's), for a CSP\n * with a nonce-based `style-src`. The styles are shared by the boards on a document and removed when the\n * last one is disposed.\n */\n nonce?: string;\n /**\n * Time each GPU render (`EXT_disjoint_timer_query_webgl2`): `stats().render.gpuMs` and the `render` event's\n * `gpuMs`. Off by default: the timer queries are not free.\n * @default false\n */\n gpuTimer?: boolean;\n /**\n * Cancels a pending `create` (React StrictMode mounts, unmounts and mounts again before the first board is\n * up): if it aborts before `create` resolves, the half-made board is disposed and `create` rejects with\n * `signal.reason`. Once the board exists the signal does nothing: call `dispose()`.\n */\n signal?: AbortSignal;\n}\n\n/**\n * The events of a board, for {@link Corkboard.on}. The interaction events (`selection`, `hover`, `click`,\n * `dblclick`, `transform`, `gesture`, `touch`, `delete`) are emitted only when `interaction` is not `false`.\n */\nexport interface CorkboardEvents extends InteractionEvents, EmbedEvents {\n /**\n * Cards were added, changed or removed: one event per API call, per gesture commit, per `batch` and per\n * `loadSnapshot`. It is the NET difference between the board before and after: a card id appears in at most\n * one of `added`, `removed` and `updated`.\n * - add then remove of a card in one batch: nothing; remove then add of the same id: one update (`prev` is the\n * card that was there); add then update: one add with the final card.\n * - `updated` entries run from the first `prev` to the last `el`; a card that ends up as it started is not\n * there, and a batch with no net change emits no event.\n * - `loadSnapshot` follows the same rules: a card with the same id becomes an update, an unchanged card is\n * not reported.\n *\n * `source` says who: a gesture (`'user'`), a call on the board or on `board.layout` (`'api'`), `loadSnapshot`\n * (`'load'`), `applyChange` (`'apply'`, or `'undo'` when inverted), the library itself (`'system'`, e.g. an\n * embed resized to its content), or the tag a host gave `batch(fn, { source })`. When recording history or\n * broadcasting, skip `'system'`, `'undo'` and `'apply'`.\n *\n * `order` is present when the draw order changed other than by cards appended on top: a card brought to the\n * front, a reorder, a removal. It lists the cards that moved with the card below each one before and after\n * (see {@link OrderChange}), not whole id lists. A drag is ONE event: the move and the bring-to-front.\n *\n * The payload is a {@link Change}: keep it, `invertChange` it, replay it with {@link Corkboard.applyChange}.\n */\n change: Change;\n /**\n * A frame was rendered (not emitted while the board is idle): the main-thread time of the render call and\n * the GPU timer results that arrived meanwhile, in ms. GPU results come back a few frames late, so `gpuMs`\n * holds the timings of earlier frames (0, 1 or several), and is always empty unless `gpuTimer: true`.\n */\n render: { cpuMs: number; gpuMs: readonly number[] };\n /** The camera moved (emitted every frame of a move). */\n camera: { camera: Camera };\n /** The camera has been still for a moment. */\n cameraSettled: { camera: Camera };\n /**\n * Something failed at runtime without throwing: a picture or video that would not load, a dead decode\n * worker, an embed lookup that failed, the WebGL context lost (`kind: 'context'`, together with\n * `contextLost`). The card stays on its placeholder.\n */\n error: BoardErrorEvent;\n /** The WebGL context was lost: nothing is drawn until `contextRestored` (the textures then reload). */\n contextLost: Record<string, never>;\n /** The WebGL context is back and the textures reload by themselves. */\n contextRestored: Record<string, never>;\n}\n\n/**\n * An infinite canvas of image, video and embed cards, drawn with WebGL.\n *\n * Make one with {@link Corkboard.create}; it mounts a canvas and a DOM overlay layer in the host and runs until\n * `dispose()`. After `dispose()` every method throws a {@link CorkboardError} (`'disposed'`) except `off`\n * (a no-op) and the getters, which keep the last state.\n *\n * @example\n * ```ts\n * const board = await Corkboard.create(div, { theme: 'dark' });\n * board.add([{ media: { src: 'https://example.com/a.jpg' } }]);\n * board.layout.tidy();\n * board.camera.fit();\n * board.on('selection', ({ ids }) => console.log(ids));\n * // later\n * board.dispose();\n * ```\n */\nexport class Corkboard {\n /** Camera control: pan, zoom, fit and the world / screen conversions. */\n readonly camera: CameraApi;\n /** Auto layout: tidy, masonry, align, distribute, equal width. */\n readonly layout: LayoutApi;\n /** The live iframes of the `embed` cards: what is mounted, what is known about a card, interact mode, their options. */\n readonly embeds: EmbedsApi;\n /** Video playback: what plays, the budget, pause, the options. */\n readonly video: VideoApi;\n /** The pointer, touch and keyboard layer (`null` with `interaction: false`). */\n readonly interaction: InteractionApi | null;\n\n // The parts below are reached with `getInternals` from `@niccolofanton/corkboard/unstable`.\n private readonly store = new Store();\n private readonly stage: Stage;\n private readonly layoutCtl: BoardLayout;\n private readonly input: Interaction | null;\n\n private readonly emitter: Emitter<CorkboardEvents>;\n private readonly snapSettings: SnapSettings;\n private readonly overlayRoot: HTMLElement;\n private readonly videoLayer: VideoLayer;\n // Measures the page's frame rate in short bursts for the layers that shed load when it is slow.\n private readonly frameRate = new FrameRateMonitor();\n // The live iframes of the `embed` cards (see src/embed/layer.ts).\n private readonly embedLayer: EmbedLayer;\n private readonly cleanups: (() => void)[] = [];\n private disposed = false;\n\n /** Whether this browser can run a board: a WebGL2 context can be made. Never throws. */\n static isSupported(): boolean {\n try {\n if (typeof document === 'undefined') return false;\n const canvas = document.createElement('canvas');\n const gl = canvas.getContext('webgl2');\n if (!gl) return false;\n // Hand the context back at once: browsers allow only a handful per page.\n gl.getExtension('WEBGL_lose_context')?.loseContext();\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Deletes the Cache Storage entry that keeps the rendered previews of HTML snippets.\n *\n * @param name The `embeds.previewCache` name, if you set one. Default: the default cache and the one\n * version 0.1 used.\n * @returns Resolves when done. Never throws, and does nothing where Cache Storage does not exist. Boards\n * already open keep the previews they hold in memory.\n */\n static clearPreviewCache(name?: string): Promise<void> {\n return clearPreviewCache(name);\n }\n\n /**\n * Creates a board in `host`: mounts a WebGL canvas and a DOM overlay layer in it, and sets `position:\n * relative` on the host if it was static. The host needs a size (it is observed).\n *\n * @param host The element to draw in.\n * @param options See {@link CorkboardOptions}.\n * @throws {CorkboardError} `'invalid'` when `host` is not an element or an option holds a value it cannot use\n * (an unknown theme name, a NaN or negative limit, a zoom range with `minScale > maxScale`...); nothing is made.\n * @throws {CorkboardError} `'unsupported'` when the browser cannot run WebGL2.\n * @throws The `signal`'s reason, if it aborts before the board is up.\n * @example\n * ```ts\n * const ctl = new AbortController();\n * const board = await Corkboard.create(host, { theme: 'light', signal: ctl.signal });\n * ```\n */\n static async create(host: HTMLElement, opts: CorkboardOptions = {}): Promise<Corkboard> {\n const options = checkCreateOptions(host, opts);\n const { signal } = options;\n if (signal?.aborted) throw signal.reason;\n const minScale = options.camera?.minScale ?? MIN_SCALE;\n const maxScale = options.camera?.maxScale ?? MAX_SCALE;\n assertRange('Corkboard.create: camera option', minScale, maxScale);\n // The stage reports before the board exists to hold the listeners: they share this emitter.\n const emitter = new Emitter<CorkboardEvents>();\n const stage = await Stage.create(host, {\n ...options.textures,\n theme: resolveTheme('Corkboard.create: option \"theme\"', options.theme),\n grid: options.grid,\n gpuTimer: options.gpuTimer,\n cspSafe: options.cspSafe,\n minScale,\n maxScale,\n signal,\n onError: (e) => emitter.emit('error', e),\n onRender: (e) => emitter.emit('render', e),\n onContextLost: () => emitter.emit('contextLost', {}),\n onContextRestored: () => emitter.emit('contextRestored', {}),\n });\n if (signal?.aborted) {\n stage.dispose();\n throw signal.reason;\n }\n try {\n return new Corkboard(host, stage, options, emitter);\n } catch (err) {\n stage.dispose();\n throw err;\n }\n }\n\n private constructor(\n host: HTMLElement,\n stage: Stage,\n options: CorkboardOptions,\n emitter: Emitter<CorkboardEvents>,\n ) {\n this.stage = stage;\n this.emitter = emitter;\n const alive = (): void => this.alive();\n this.camera = new BoardCamera(stage, this.store, alive);\n this.layoutCtl = new BoardLayout(this.store, stage, alive);\n this.layout = this.layoutCtl;\n try {\n stage.attach(this.store);\n const sn = options.snapping;\n this.snapSettings =\n sn === false\n ? { guides: false, grid: false }\n : { ...DEFAULT_SNAPPING, ...(typeof sn === 'object' ? sn : {}) };\n\n if (getComputedStyle(host).position === 'static') host.style.position = 'relative';\n this.overlayRoot = document.createElement('div');\n Object.assign(this.overlayRoot.style, {\n position: 'absolute',\n inset: '0',\n overflow: 'hidden',\n pointerEvents: 'none',\n });\n host.appendChild(this.overlayRoot);\n\n this.videoLayer = new VideoLayer(\n {\n root: this.overlayRoot,\n store: this.store,\n stage,\n frameRate: this.frameRate,\n nonce: options.nonce,\n onError: (e) => this.emitter.emit('error', e),\n },\n options.video,\n );\n const videoLayer = this.videoLayer;\n this.video = {\n get playing() {\n return videoLayer.playing;\n },\n get budget() {\n return videoLayer.playingBudget;\n },\n get paused() {\n return videoLayer.isPaused;\n },\n setPaused: (paused) => {\n this.alive();\n boolean('video.setPaused', 'paused', paused);\n videoLayer.setPaused(paused);\n },\n setOptions: (o) => {\n this.alive();\n videoLayer.setOptions(checkVideoOptions('video.setOptions', o));\n },\n };\n const embedLayer = new EmbedLayer(\n {\n root: this.overlayRoot,\n host,\n store: this.store,\n stage,\n frameRate: this.frameRate,\n nonce: options.nonce,\n emit: (type, payload) => this.emitter.emit(type, payload as CorkboardEvents[typeof type]),\n },\n options.embeds,\n );\n this.embedLayer = embedLayer;\n this.embeds = {\n get live() {\n return embedLayer.live;\n },\n get interacting() {\n return embedLayer.interacting;\n },\n info: (id) => {\n this.alive();\n return embedLayer.info(id) ?? undefined;\n },\n setOptions: (o) => {\n this.alive();\n embedLayer.setOptions(checkEmbedOptions('embeds.setOptions', o));\n },\n interact: (id) => {\n this.alive();\n return embedLayer.interact(id);\n },\n exitInteract: () => {\n this.alive();\n embedLayer.exitInteract();\n },\n };\n\n this.cleanups.push(\n stage.onFrame((camChanged) => {\n this.videoLayer.onFrame(camChanged);\n this.embedLayer.onFrame(camChanged);\n if (camChanged) this.emitter.emit('camera', { camera: { ...stage.cam.cam } });\n }),\n stage.onSettle(() => {\n this.videoLayer.onSettle();\n this.embedLayer.onSettle();\n // Still camera: the cheapest moment to see what the page really costs.\n this.frameRate.poke();\n this.emitter.emit('cameraSettled', { camera: { ...stage.cam.cam } });\n }),\n );\n\n if (options.interaction !== false) {\n const iopts = typeof options.interaction === 'object' ? options.interaction : {};\n const it = new Interaction(host, stage, this.store, this.snapSettings, iopts);\n this.input = it;\n this.interaction = {\n setPanMode: (on) => {\n this.alive();\n boolean('interaction.setPanMode', 'on', on);\n it.setPanMode(on);\n },\n setOptions: (o) => {\n this.alive();\n it.setOptions(checkInteractionOptions('interaction.setOptions', o));\n },\n };\n // Interaction events are the board's events.\n const forward = <K extends keyof InteractionEvents>(type: K): void => {\n this.cleanups.push(it.events.on(type, (p) => this.emitter.emit(type, p as CorkboardEvents[K])));\n };\n for (const t of [\n 'selection',\n 'hover',\n 'click',\n 'dblclick',\n 'transform',\n 'gesture',\n 'touch',\n 'delete',\n ] as const) {\n forward(t);\n }\n this.cleanups.push(\n it.events.on('hover', ({ id }) => {\n const el = id ? this.store.get(id) : undefined;\n this.videoLayer.setHover(el && el.media.video ? el.id : null);\n }),\n it.events.on('selection', ({ ids }) => {\n this.videoLayer.setSelection(ids);\n this.embedLayer.setSelection(ids);\n }),\n it.events.on('touch', ({ touch }) => {\n this.videoLayer.setTouch(touch);\n this.embedLayer.setTouch(touch);\n }),\n it.events.on('dblclick', ({ id }) => this.embedLayer.onDblClick(id)),\n );\n } else {\n this.input = null;\n this.interaction = null;\n }\n // The public `change` event goes out LAST among the store's listeners (the stage, the layers and the\n // interaction layer subscribed before): by the time host code runs, the selection has dropped the cards\n // that left and every layer has seen the change.\n this.cleanups.push(\n this.store.subscribe((e) => {\n const c = e.change;\n const out: CorkboardEvents['change'] = {\n source: c.source,\n added: c.added,\n removed: c.removed,\n updated: c.updated,\n };\n if (c.order) out.order = c.order;\n this.emitter.emit('change', out);\n }),\n );\n registerInternals(this, {\n stage,\n store: this.store,\n interaction: this.input,\n embeds: this.embedLayer,\n video: this.videoLayer,\n overlayRoot: this.overlayRoot,\n isDisposed: () => this.disposed,\n onDispose: (fn) => {\n this.cleanups.push(fn);\n return () => {\n const i = this.cleanups.indexOf(fn);\n if (i >= 0) this.cleanups.splice(i, 1);\n };\n },\n });\n } catch (err) {\n // A later step threw: let go of what was already made. The stage is the caller's (`create` disposes it).\n this.disposed = true;\n this.teardown();\n throw err;\n }\n }\n\n // ── Elements ───────────────────────────────────────────────────────────────\n /**\n * Adds cards and returns their ids. A card with no `x` / `y` is placed on a free spot near the middle of what\n * is on screen, together with the others that have none, as one masonry block. Its size is the one it was\n * given, or its kind's default if that has a width of its own (embeds); an `x` or `y` it came with is kept,\n * the other coordinate is placed.\n *\n * @param input One card or an array of them. Pass thousands as ONE array: each call places its unplaced cards\n * against the whole board. `media` is copied (and a `Uint8Array` thumbhash stored as base64): changing the\n * object you passed afterwards does not touch the card or the history.\n * @returns The ids, in order.\n * @throws {CorkboardError} `'invalid'` on a value a card cannot hold (a NaN, a size <= 0, a duplicate id, an\n * embed with both or neither of `url` / `html`...). Nothing was added, whatever the batch.\n */\n add(input: CardInit | readonly CardInit[]): CardId[] {\n this.alive();\n const inits: readonly CardInit[] = Array.isArray(input) ? input : [input as CardInit];\n validateInits(inits, (id) => this.store.has(id));\n const els: Card[] = [];\n const unplaced: Card[] = [];\n const fixedSize = new Set<CardId>();\n const given = new Map<CardId, { x?: number; y?: number }>();\n for (const init of inits) {\n const id = init.id ?? newId();\n const el = createElement(init, id);\n els.push(el);\n if (init.x === undefined || init.y === undefined) {\n unplaced.push(el);\n if (init.w !== undefined || init.h !== undefined || el.kind === 'embed') fixedSize.add(id);\n if (init.x !== undefined || init.y !== undefined) given.set(id, { x: init.x, y: init.y });\n }\n }\n this.layoutCtl.placeNew(unplaced, fixedSize, given);\n this.store.add(els);\n return els.map((e) => e.id);\n }\n\n /**\n * Changes a card. A field left out, or set to `undefined`, is left as it is - except `data`: a patch with an\n * own `data` key set to `undefined` clears it (`{ data: undefined }`; `{ data: null }` stores `null`).\n * `media` is copied, with a `Uint8Array` thumbhash stored as base64. A new `media` with an `aspect` or a\n * `thumbhash` and no `w` / `h` in the patch keeps the card's width and takes the new height.\n *\n * @returns `false` when there is no such card.\n * @throws {CorkboardError} `'invalid'` on a value a card cannot hold; nothing changed.\n */\n update(id: CardId, patch: CardPatch): boolean {\n this.alive();\n if (!this.store.has(id)) return false;\n validatePatch(id, patch);\n const p = { ...patch };\n // A new media with no explicit size keeps the card's width and takes the new aspect.\n if (p.media && p.w === undefined && p.h === undefined) {\n const cur = this.store.get(id) as Card;\n const size = sizeOf({ media: p.media, w: cur.w }, p.kind ?? cur.kind);\n if (p.media.aspect !== undefined || p.media.thumbhash !== undefined) p.h = size.h;\n }\n if (p.media && !p.kind) p.kind = kindOf({ media: p.media });\n const next: Record<string, unknown> = { ...p };\n if (p.media) next.media = copyMedia(p.media);\n this.store.update(id, next as CardPatch);\n return true;\n }\n\n /**\n * Removes cards.\n *\n * @param ids One id or a list of ids.\n * @returns How many of the ids existed.\n * @throws {CorkboardError} `'invalid'` when `ids` is not a string or an array of strings.\n */\n remove(ids: CardId | readonly CardId[]): number {\n this.alive();\n return this.store.remove(idList('remove', ids)).length;\n }\n\n /** Removes every card and clears the selection. */\n clear(): void {\n this.alive();\n this.input?.setSelection([]);\n this.store.clear();\n }\n\n /**\n * Runs `fn` and emits ONE `change` event for everything it did (`add`, `update`, `remove`, `loadSnapshot`,\n * `applyChange`, `board.layout.*`, the z-order methods): the net difference, see {@link CorkboardEvents}. Batches nest: an\n * inner one folds into the outer. Reads inside `fn` see every change made so far. `fn` must be synchronous.\n *\n * If `fn` throws there is no rollback: what it already did stays, the event for it is still emitted (after\n * `fn` stopped), and `fn`'s error is the one rethrown - a listener that throws does not replace it.\n *\n * @param opts `source` tags the event (see `ChangeSource`); default `'api'`. With nested batches the\n * outermost one that names a source wins; `'load'` (from `loadSnapshot`) wins over any.\n */\n batch(fn: () => void, opts: { source?: ChangeSource } = {}): void {\n this.alive();\n this.store.batch(fn, opts.source);\n }\n\n /**\n * Replays a {@link Change} (or its inverse) on the board: the one primitive behind undo, redo and sync.\n *\n * ```ts\n * board.on('change', (c) => { if (!['system', 'undo', 'apply'].includes(c.source)) undoStack.push(c); });\n * board.applyChange(undoStack.pop()!, { invert: true }); // undo\n * board.applyChange(redoChange); // redo / apply a peer's change (JSON round trip is fine)\n * ```\n *\n * First every value is validated (`'invalid'` on a bad one, nothing changed; with `invert`, the inverse is what is checked; an id may not repeat in `added`, `removed` or `updated`, nor be both added and removed), then ONE batch (one `change`\n * event) does, in this order:\n * 1. `removed` cards are removed (ids that are not on the board are skipped).\n * 2. `added` cards are upserted exactly as given: no placement, no default size; an id already on the board is\n * overwritten in place.\n * 3. `updated` entries write each field of `props` from `el` as it is (no height is derived from the media's\n * aspect; a field that is `undefined` - `data` cleared - clears it). A card that is gone is skipped. With\n * `conflict: 'skip'` (the default for an inverted change) a field is written only if the card still holds\n * the value the change started from (`prev`), compared structurally.\n * 4. `order.moved` is replayed bottom first: each card goes directly above its `nextBelow` (`null`: the\n * bottom). An entry whose card or anchor is not on the board is skipped. A card that was only appended on\n * top is not in `order`, so redoing such an `add` puts it on top.\n *\n * It does not touch the camera or the selection: those are the host's. The result is a pure function of the\n * change and the board, so peers that start equal and replay the same changes stay equal.\n *\n * @param c A change from the `change` event, or its JSON round trip.\n * @param opts See {@link ApplyChangeOptions}.\n * @throws {CorkboardError} `'invalid'` when the change holds a value a card cannot hold, or repeats an id; nothing changed.\n */\n applyChange(c: Change, opts: ApplyChangeOptions = {}): void {\n this.alive();\n validateChange(c, opts.invert === true);\n this.layoutCtl.cancelAnimation();\n applyChangeTo(this.store, c, opts);\n }\n\n /**\n * The cards and the camera as plain data, to persist or to restore with {@link Corkboard.loadSnapshot}: the\n * cards in draw order (bottom first), each as `add` took it plus the size and position the board gave it.\n *\n * The snapshot shares no object with the board: `media` is copied (so is a `Uint8Array` thumbhash, which\n * becomes base64). `data` is the exception, passed by reference: keep it JSON-safe, since `JSON.stringify`\n * of the snapshot walks it. `data` is also the place for what you need to persist beyond the card fields:\n * any new persisted field of the library bumps `SNAPSHOT_VERSION`, `data` never does. A `blob:` URL\n * (`media.src`, `video`, `sizes`) is left out, since it is dead after a reload. Not included: selection,\n * theme, grid, snapping, video and embed settings, runtime posters and snapshots, and the poster an embed\n * resolved (the `embedResolved` event's `poster`, or `embeds.info(id)?.posters[0]`): to keep that one, read it\n * and store it yourself, then `update(id, { media: { ...board.get(id)!.media, src: poster } })`.\n *\n * @param o `camera: false` leaves the camera out.\n */\n getSnapshot(o: { camera?: boolean } = {}): BoardSnapshot {\n this.alive();\n return toSnapshot(this.all(), o.camera === false ? undefined : { ...this.stage.cam.cam });\n }\n\n /**\n * Replaces the board with a snapshot (from {@link Corkboard.getSnapshot}, or `JSON.parse` of a saved one).\n *\n * All or nothing: the format, the version and every card are checked first with the same rules as `add`\n * (plus finite x / y and w / h > 0, required here) - a card `add` accepts, a snapshot accepts. Only `id`, `x`,\n * `y`, `w`, `h` and `media` are required: the other fields take the defaults of `add` (`kind` comes from\n * `media`). Keys a card does not have are dropped. Then the selection is cleared, a running layout animation and any drag or resize in progress end, and the cards are\n * swapped in one step with their ids, positions and order kept (nothing is auto-placed); `media` is copied,\n * `data` is taken by reference - except that a `data` structurally equal to the card's current one keeps the\n * current object, like `media`, so loading the same JSON twice emits nothing. The camera jumps to the snapshot's one, if it has one and `camera` is not\n * `false`. Emits at most one `change` event with `source: 'load'`, as a net diff (see {@link CorkboardEvents}):\n * cards with a new id are `added`, cards gone are `removed`, a card whose id is in both is an `updated` entry,\n * and one that did not change is not reported.\n *\n * @throws {CorkboardError} `'invalid'` when the snapshot is malformed or written by a newer corkboard than\n * this build reads (`SNAPSHOT_VERSION`); nothing changed.\n */\n loadSnapshot(snapshot: BoardSnapshot | BoardSnapshotInput, o: { camera?: boolean } = {}): void {\n this.alive();\n const { elements, camera } = fromSnapshot(snapshot, (id) => this.store.get(id));\n this.input?.setSelection([]);\n this.layoutCtl.cancelAnimation();\n this.store.replaceAll(elements);\n if (camera && o.camera !== false) this.stage.setCamera(camera);\n }\n\n /** A card by id (`undefined`: none). The object is the store's: do not mutate it, use `update`. */\n get(id: CardId): Card | undefined {\n this.alive();\n return this.store.get(id);\n }\n\n /** Every card in draw order, bottom first: the order of `getSnapshot()`, and the one a gesture changes when it brings a card to the front. */\n all(): Card[] {\n this.alive();\n return this.store.ids().map((id) => this.store.get(id) as Card);\n }\n\n /**\n * Moves cards to the top of the draw order, keeping their relative order. Ids that are not on the board are\n * ignored. Throws `'invalid'` when `ids` is not a string or an array of strings.\n */\n bringToFront(ids: CardId | readonly CardId[]): void {\n this.alive();\n this.store.bringToFront(idList('bringToFront', ids));\n }\n\n /**\n * Moves cards to the bottom of the draw order, keeping their relative order. Ids that are not on the board are\n * ignored. Throws `'invalid'` when `ids` is not a string or an array of strings.\n */\n sendToBack(ids: CardId | readonly CardId[]): void {\n this.alive();\n this.store.sendToBack(idList('sendToBack', ids));\n }\n\n /**\n * Sets the whole draw order, bottom first.\n *\n * @param ids Every id on the board exactly once (as `all().map((e) => e.id)` returns them, reordered). An array\n * only: unlike the other id lists it takes no single id.\n * @throws {CorkboardError} `'invalid'` when `ids` is not an array that is a permutation of the ids on the board; nothing changed.\n */\n setOrder(ids: readonly CardId[]): void {\n this.alive();\n if (!Array.isArray(ids)) bad('setOrder', `needs the full list of ids as an array (got ${show(ids)})`);\n this.store.setOrder(idList('setOrder', ids));\n }\n\n /** How many cards are on the board. */\n get size(): number {\n return this.store.size;\n }\n\n /** The ids of the cards whose box meets a world rectangle. */\n inRect(r: Rect): CardId[] {\n this.alive();\n assertRect('inRect', r);\n return this.store\n .searchInto({ minX: r.x0, minY: r.y0, maxX: r.x1, maxY: r.y1 }, [])\n .map((e) => e.id);\n }\n\n /**\n * The world rectangle covering the given cards (default: all).\n *\n * @param ids One id or a list of ids.\n * @returns `undefined` when there is nothing to cover: an empty board, or none of the ids is a card.\n * @throws {CorkboardError} `'invalid'` when `ids` is not a string or an array of strings.\n */\n bounds(ids?: CardId | readonly CardId[]): Rect | undefined {\n this.alive();\n return this.stage.boundsOf(idList('bounds', ids, true));\n }\n\n // ── Selection ──────────────────────────────────────────────────────────────\n /** The selected card ids. Always empty with `interaction: false`. */\n get selection(): readonly CardId[] {\n return this.input?.selection ?? [];\n }\n\n /**\n * Selects exactly these cards (one id or a list; an empty array clears the selection) and emits `selection`.\n * Does nothing with `interaction: false`. Throws `'invalid'` when `ids` is not a string or an array of strings.\n *\n * For an \"arrange\" button: `board.layout.tidy(board.selection.length >= 2 ? board.selection : undefined)`.\n */\n select(ids: CardId | readonly CardId[]): void {\n this.alive();\n const list = idList('select', ids);\n this.input?.setSelection(list);\n }\n\n /** Selects every card. Does nothing with `interaction: false`. */\n selectAll(): void {\n this.alive();\n this.input?.setSelection([...this.store.ids()]);\n }\n\n // ── Settings ───────────────────────────────────────────────────────────────\n /**\n * Switches the theme.\n *\n * @throws {CorkboardError} `'invalid'` for a name other than `'dark'` / `'light'` or a `Theme` that is missing\n * a field or holds a bad colour.\n */\n setTheme(theme: Theme | 'dark' | 'light'): void {\n this.alive();\n if (theme === undefined) bad('setTheme', \"theme must be 'dark', 'light' or a Theme object (got undefined)\");\n this.stage.setTheme(resolveTheme('setTheme', theme));\n this.embedLayer.setTheme();\n }\n\n /** Shows or hides the background dot grid. Throws `'invalid'` unless `on` is a boolean. */\n setGrid(on: boolean): void {\n this.alive();\n boolean('setGrid', 'on', on);\n this.stage.setGrid(on);\n }\n\n /**\n * Alignment guides / snap to the background grid while moving and resizing. `true` / `false` set both. Throws\n * `'invalid'` for anything but a boolean or `{ guides?, grid? }` of booleans.\n */\n setSnapping(s: Partial<SnapSettings> | boolean): void {\n this.alive();\n checkSnapping('setSnapping', s);\n if (typeof s === 'boolean') {\n this.snapSettings.guides = s;\n this.snapSettings.grid = s;\n } else Object.assign(this.snapSettings, s);\n }\n\n /** The snapping settings now (a copy: change them with `setSnapping`). */\n get snapping(): Readonly<SnapSettings> {\n return { ...this.snapSettings };\n }\n\n // ── Events ─────────────────────────────────────────────────────────────────\n /**\n * Subscribes to an event (see {@link CorkboardEvents}).\n *\n * @returns The function that unsubscribes.\n */\n on<K extends keyof CorkboardEvents>(type: K, fn: (payload: CorkboardEvents[K]) => void): () => void {\n this.alive();\n return this.emitter.on(type, fn);\n }\n\n /** Removes a listener added with `on`. Does nothing after `dispose()`. */\n off<K extends keyof CorkboardEvents>(type: K, fn: (payload: CorkboardEvents[K]) => void): void {\n this.emitter.off(type, fn);\n }\n\n // ── Diagnostics ────────────────────────────────────────────────────────────\n /**\n * A snapshot of the counters and timings of the board: the render loop and its percentiles, texture memory\n * and the decode pipeline, the embeds and the videos (see {@link BoardStats}). Cheap enough to call twice a\n * second; it sorts the timing history, so not every frame (listen to the `render` event for that).\n */\n stats(): BoardStats {\n this.alive();\n const e = this.embedLayer;\n return {\n ...this.stage.stats(),\n embeds: {\n live: e.live.size,\n active: e.live.size - e.parked.size,\n maxLive: e.maxLive,\n parked: e.parked.size,\n culled: e.culled.size,\n frozen: e.frozen.size,\n animating: e.animating.size,\n animatingBudget: e.animatingBudget,\n loading: e.loading.size,\n previewsPending: e.previewsPending,\n freezeThreshold: e.freezeThreshold,\n interacting: e.interacting,\n },\n video: { playing: this.videoLayer.playing.size, budget: this.videoLayer.playingBudget },\n };\n }\n\n /**\n * The bounding box of a card on screen, as a {@link Box} in host-local CSS px (for HTML UI pinned to a card).\n *\n * @returns `undefined` when there is no such card.\n */\n screenRect(id: CardId): Box | undefined {\n this.alive();\n const el = this.store.get(id);\n if (!el) return undefined;\n const b = elementBox(el);\n const a = this.stage.worldToScreen(b.minX, b.minY);\n const k = this.stage.cam.scale;\n return { x: a.x, y: a.y, w: (b.maxX - b.minX) * k, h: (b.maxY - b.minY) * k };\n }\n\n /**\n * Tears the board down: events, DOM, workers, textures, the WebGL context. Idempotent. Every other method\n * throws a {@link CorkboardError} (`'disposed'`) afterwards, except `off` (a no-op) and the getters (`size`,\n * `selection`, `video.playing`...), which keep the last state.\n */\n dispose(): void {\n if (this.disposed) return;\n this.disposed = true;\n this.teardown();\n this.attempt(() => this.stage.dispose());\n this.emitter.clear();\n }\n\n private alive(): void {\n if (this.disposed) throw new CorkboardError('disposed', 'Corkboard: the board has been disposed');\n }\n\n // Lets go of everything but the stage and the emitter. Safe on a board the constructor did not finish:\n // a step that threw must not keep the others from running.\n private teardown(): void {\n this.attempt(() => this.input?.dispose());\n // A copy: a step may unregister itself (an overlay's disposer) while this runs.\n for (const f of this.cleanups.splice(0)) this.attempt(f);\n this.attempt(() => this.videoLayer?.dispose());\n this.attempt(() => this.embedLayer?.dispose());\n this.attempt(() => this.frameRate.dispose());\n this.attempt(() => this.overlayRoot?.remove());\n }\n\n private attempt(fn: () => void): void {\n try {\n fn();\n } catch (e) {\n console.error('[corkboard] dispose step failed', e);\n }\n }\n}\n"],"names":["given","o","k","assertRange","where","min","max","ok","v","bad","show","THEMES","DARK_THEME","LIGHT_THEME","color","field","unit","resolveTheme","t","isObject","boolean","checkSnapping","s","record","checkVideoOptions","oneOf","LIMITS","checkEmbedOptions","e","limit","integer","m","nonNegative","positive","c","checkInteractionOptions","i","checkTextureOptions","checkCreateOptions","host","options","checkMoveOptions","checkLayoutOptions","grid","a","g","checkPoint","x","y","finite","BoardCamera","stage","store","alive","CorkboardError","ids","list","idList","opts","id","r","assertRect","scale","NOMINAL_VIEW","ALIGN_MODES","ease","prefersReducedMotion","BoardLayout","out","el","els","result","tidyBoxes","elementBox","patches","width","median","gap","placementGap","items","effectiveAspect","aspectSum","it","columns","placementColumns","block","masonryPack","slotWidth","ax","ay","b","mode","arrangeGap","deltas","alignBoxes","axis","distributeBoxes","sizes","equalWidths","rects","separate","d","fixedSize","widths","plan","planPlacement","view","occupied","autoSpotArea","spot","autoSpot","cam","cx","cy","resetRot","assertGeometry","shown","animate","moving","gx","gy","near","hits","to","from","boxOfRect","duration","start","current","done","finish","off","draw","clamp","MAX_DEPTH","hasOwn","isPlain","p","deepEqual","eq","depth","seen","arrA","peers","decodeBase64","bin","toBase64","bytes","SIZES","copyMedia","keep","aspectOf","media","kind","thumbHashToApproximateAspectRatio","url","parseEmbedUrl","DEFAULTS","kindOf","init","sizeOf","aspect","w","createElement","h","counter","newId","invertChange","u","PROPS","elementOf","src","applyChangeTo","change","skip","source","added","next","cur","patch","any","value","KINDS","checkThumbhash","bare","checkMedia","hasUrl","hasHtml","checkFields","validateInits","inits","exists","validatePatch","validateSnapshotElement","FIELDS","checkWholeElement","at","f","checkId","label","checkChangeShape","moved","checkUnique","validateChange","invert","eff","addedLabel","removedLabel","addedIds","removedIds","name","SNAPSHOT_VERSION","SNAPSHOT_FORMAT","isBlob","sameMedia","mediaToJSON","elementToJSON","toSnapshot","elements","camera","invalid","what","fromSnapshot","existing","num","copy","prev","Corkboard","Store","FrameRateMonitor","gl","clearPreviewCache","signal","minScale","MIN_SCALE","maxScale","MAX_SCALE","emitter","Emitter","Stage","err","sn","DEFAULT_SNAPPING","VideoLayer","videoLayer","paused","embedLayer","EmbedLayer","type","payload","camChanged","iopts","Interaction","on","forward","touch","registerInternals","fn","input","unplaced","size","snapshot","theme"],"mappings":";;;;AAcA,MAAMA,KAAQ,CAAmBC,MAC9B,OAAO,KAAKA,CAAC,EAA2B,OAAO,CAACC,MAAMD,EAAEC,CAAC,MAAM,MAAS;AAGpE,SAASC,GAAYC,GAAeC,GAAcC,GAAoB;AAC3E,QAAMC,IAAK,CAACC,MAA4B,OAAOA,KAAM,YAAY,OAAO,SAASA,CAAC,KAAKA,IAAI;AAC3F,GAAI,CAACD,EAAGF,CAAG,KAAK,CAACE,EAAGD,CAAG,KAAKD,IAAMC,MAChCG,EAAIL,GAAO,qDAAqDM,EAAKL,CAAG,CAAC,SAASK,EAAKJ,CAAG,CAAC,GAAG;AAElG;AAGA,MAAMK,KAAS,EAAE,MAAMC,IAAY,OAAOC,GAAA,GAEpCC,IAAQ,CAACV,GAAeW,GAAeP,MAAqB;AAChE,GAAI,OAAOA,KAAM,YAAY,CAAC,OAAO,UAAUA,CAAC,KAAKA,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