@niccolofanton/corkboard 0.1.0 → 0.2.1
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 +102 -1
- package/README.md +47 -136
- package/dist/chunk-CNSKM2Mi.d.ts +2992 -0
- package/dist/chunk-layer-9my2O3ye.js +7405 -0
- package/dist/chunk-layer-9my2O3ye.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
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"chunk-layer-9my2O3ye.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/resolve.ts","../src/embed/bootstrap.ts","../src/embed/previewCache.ts","../src/embed/sandbox.ts","../src/embed/tile.ts","../src/styles.ts","../src/embed/layer.ts","../src/events.ts","../src/check.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/internals.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/store/order.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"],"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 { Card } from '../types';\n\n/** Axis-aligned bounding box in world px, rbush-compatible. */\nexport interface Aabb {\n minX: number;\n minY: number;\n maxX: number;\n maxY: number;\n}\n\n/** A rectangle in world px: position and size. */\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 = (): Aabb => ({\n minX: Infinity,\n minY: Infinity,\n maxX: -Infinity,\n maxY: -Infinity,\n});\nexport const boxW = (b: Aabb): number => b.maxX - b.minX;\nexport const boxH = (b: Aabb): number => b.maxY - b.minY;\nexport const boxCx = (b: Aabb): number => (b.minX + b.maxX) / 2;\nexport const boxCy = (b: Aabb): number => (b.minY + b.maxY) / 2;\n\nexport function boxesIntersect(a: Aabb, b: Aabb): boolean {\n return a.minX <= b.maxX && a.maxX >= b.minX && a.minY <= b.maxY && a.maxY >= b.minY;\n}\nexport function boxContains(outer: Aabb, inner: Aabb): 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: Aabb, b: Aabb): Aabb {\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: Aabb, by: number): Aabb {\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 }): Aabb {\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<Card, '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<Card, 'x' | 'y' | 'w' | 'h' | 'rot'>): Aabb {\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: Aabb, 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: Aabb): 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\n/** One window of frame-time samples from the frame-rate monitor. */\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\n/** What the frame-rate monitor needs from its environment (a seam for tests). */\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\n/** Measures the page's frame rate in short bursts, for the layers that shed load when it is slow. */\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\n/** A card's box in world px: the top-left of the unrotated box, its size and its rotation in degrees. */\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\n/** The most a page's layout viewport is made wide or tall, CSS px. */\nexport const MAX_LAYOUT_PX = 4096;\n/** The default virtual screen for embeds: `'720p'`. */\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\n/** Where and how big a live iframe is laid out, and the scale that maps it onto its card. */\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\n/** Computes the iframe's layout size and the transform that fits it on a card's box. Pure. */\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\n/** Default `embeds.maxLive` on a mouse / pen device. */\nexport const MAX_LIVE_DESKTOP = 12;\n/** Default `embeds.maxLiveTouch` on a touch device. */\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;\n/** Width of the 320 x 200 reference box, CSS px: the aspect a numeric `embeds.minLivePx` keeps. */\nexport const MIN_LIVE_W = 320;\n/** Height of the 320 x 200 reference box, CSS px. */\nexport const MIN_LIVE_H = 200;\n/** Below this zoom nothing mounts, selected or not. */\nexport const MIN_LIVE_SCALE = 0.25;\n/**\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.\n */\nexport const KEEP_FACTOR = 0.6;\n\n/** A card as the live-iframe policy sees it. */\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\n/** Input of {@link planLive}: the cards, the caps and the zoom. */\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\n/** What {@link planLive} decides: which cards go live and which are parked. */\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\n/** Whether a card may be live at this zoom: big enough on screen, or selected. Pure. */\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\n/** Chooses which embed cards hold a live iframe, within the caps. Pure. */\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","// 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 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 /** `aspect`: height / width of the card. */\n aspect?: number;\n /** Shown on the generated tile and as the iframe's `title`. */\n title?: string;\n /**\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 */\n frameable?: boolean;\n}\n\n/**\n * A lookup on a server of yours for what the browser cannot know about a URL: oEmbed thumbnails and titles,\n * `og:image`, a screenshot, whether the page may be framed at all (`X-Frame-Options`, CSP `frame-ancestors`).\n * Cache it and re-host the poster CORS-enabled (a WebGL texture needs CORS).\n *\n * @example\n * ```ts\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 * }\n * ```\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 (`board.embeds.info(id)`). */\nexport interface ResolvedEmbed {\n /** A page (`'url'`) or a snippet (`'html'`). */\n kind: 'url' | 'html';\n /** The provider, `'generic'` for a snippet or an unknown host. */\n provider: EmbedProvider;\n /** The card's URL (normalised), or '' for a snippet. */\n url: string;\n /** Host of the URL (`'html'` for a snippet). */\n host: string;\n /** What the tile says: the provider, else the host; the title if there is one. */\n label: string;\n /** The title, from the card or the resolver. */\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 /** `false`: the page refuses framing; the card is a bookmark and never goes live. */\n frameable: boolean;\n /**\n * `true`: a snippet that kept navigating its frame away from its document (3 times within 10 s) and was\n * blocked; it stays on its poster, and `frameable` is `false` while this is set. Cleared when the card's content\n * changes. Absent otherwise.\n */\n blocked?: boolean;\n /** `aspect`: height / width of the card, when the provider or the resolver gave one. */\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/**\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.\n */\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/**\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.\n */\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 = requestAnimationFrame.bind(window), caf = cancelAnimationFrame.bind(window);\nvar paused = false, n = 0, pend = {}, hand = {}, stopped = [];\nvar st = setTimeout.bind(window), ct = clearTimeout.bind(window);\nvar si = setInterval.bind(window), ci = 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, 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(a => a.playState === 'running');\n stopped.forEach(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 (/^(offset|easing|composite|computedOffset)$/.test(p)) continue;\n s.add(p === 'cssFloat' ? 'float' : p.replace(/[A-Z]/g, c => '-' + 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) {}\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, '').replace(/\\n{2,}/g, '\\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 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. The memory map is per page and uses a cheap\n// 64-bit hash of that; the persistent store outlives the page, so its entries are named by the SHA-256 of it\n// (a collision would show one snippet's picture on another card, for good).\n\n/** `-v2`: the entries of `-v1` were named by a different hash and can never be read again. */\nexport const PREVIEW_CACHE_NAME = 'corkboard-previews-v2';\nconst LEGACY_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/**\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).\n */\nexport const PREVIEW_PERSIST_MAX = 1000;\n\n/**\n * Where the rendered previews of HTML snippets are kept. `'memory'`: this page only. `'persistent'`: also in Cache Storage,\n * under the default name. `{ persistent: true, name }`: the same, in the Cache Storage entry `name` (to keep several boards apart, or to clear one without touching the others).\n */\nexport type PreviewCacheMode = 'memory' | 'persistent' | { persistent: true; name?: string };\n\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.\n */\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\n/** What decides a preview, as one string: the persistent store hashes it with SHA-256, the memory map with FNV. */\nexport function previewMaterial(html: string, bucket: number, resolution: string, w: number, h: number): string {\n return `${resolution}|${bucket}|${w}x${h}|${html}`;\n}\n\nexport function previewKey(html: string, bucket: number, resolution: string, w: number, h: number): string {\n return hashString(previewMaterial(html, bucket, resolution, w, h));\n}\n\n// SHA-256 as hex, null where `crypto.subtle` is missing (it only exists in secure contexts).\nasync function sha256Hex(s: string): Promise<string | null> {\n try {\n const subtle = typeof crypto === 'undefined' ? undefined : crypto.subtle;\n if (!subtle) return null;\n const digest = new Uint8Array(await subtle.digest('SHA-256', new TextEncoder().encode(s)));\n let hex = '';\n for (const b of digest) hex += b.toString(16).padStart(2, '0');\n return hex;\n } catch {\n return null;\n }\n}\n\nconst hasSubtle = (): boolean => typeof crypto !== 'undefined' && typeof crypto.subtle?.digest === 'function';\n\n/**\n * Deletes the Cache Storage entry of the previews (default: the default name, and the one an older version\n * used). Resolves when done; never throws, and does nothing where Cache Storage does not exist.\n */\nexport async function clearPreviewCache(name: string = PREVIEW_CACHE_NAME): Promise<void> {\n if (typeof caches === 'undefined') return;\n const names = name === PREVIEW_CACHE_NAME ? [name, LEGACY_CACHE_NAME] : [name];\n for (const n of names) {\n try {\n await caches.delete(n);\n } catch {\n // Nothing to clear, or not allowed.\n }\n }\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 private wantsPersistent = false;\n private name = PREVIEW_CACHE_NAME;\n\n constructor(mode: PreviewCacheMode) {\n this.mode = mode;\n }\n\n get mode(): PreviewCacheMode {\n return this.wantsPersistent ? { persistent: true, name: this.name } : 'memory';\n }\n\n set mode(m: PreviewCacheMode) {\n this.wantsPersistent = m !== 'memory';\n const name = typeof m === 'object' && m.name ? m.name : PREVIEW_CACHE_NAME;\n // Another cache: opened (and counted) again on the next use.\n if (name !== this.name) {\n this.name = name;\n this.cache = null;\n this.stored = 0;\n }\n }\n\n // Whether `getPersistent` can find anything: asked for, Cache Storage exists, and there is a SHA-256 to name\n // the entries with (an insecure context has none: memory only then).\n get persistent(): boolean {\n return this.wantsPersistent && typeof caches !== 'undefined' && hasSubtle();\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 // `material`: what `previewMaterial` made the key from.\n async getPersistent(material: string): Promise<Blob | null> {\n try {\n if (!this.persistent) return null;\n const name = await sha256Hex(material);\n if (name === null) return null;\n const cache = await this.open();\n const res = await cache?.match(urlOf(name));\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 // `material`: also write it to Cache Storage, named by its SHA-256 (not when it came from there).\n put(key: string, blob: Blob, material?: string): 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 (material !== undefined && this.persistent) void this.putPersistent(material, blob);\n }\n\n clear(): void {\n this.memory.clear();\n }\n\n private async putPersistent(material: string, blob: Blob): Promise<void> {\n try {\n const name = await sha256Hex(material);\n if (name === null) return;\n const cache = await this.open();\n if (!cache) return;\n await cache.put(urlOf(name), 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 if (typeof caches === 'undefined') return null;\n // The cache of an older version can never be read again: dropped (not when it was asked for by name).\n if (this.name !== LEGACY_CACHE_NAME) void Promise.resolve(caches.delete?.(LEGACY_CACHE_NAME)).catch(() => undefined);\n const cache = await caches.open(this.name);\n 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 { CorkboardError } from '../errors';\nimport type { EmbedSource } from '../types';\nimport { SNIPPET_BOOTSTRAP } from './bootstrap';\nimport { normalizeEmbedUrl, providerOfIframeSrc, type EmbedProvider } from './providers';\n\n/** How much a frame is trusted: a known `provider`, an `arbitrary` URL or an HTML `snippet`. */\nexport type SandboxProfile = 'provider' | 'arbitrary' | 'snippet';\n\n/**\n * Allowlisted providers: they run their player (scripts, their own origin's storage), post forms, open\n * popups and go presentation mode.\n */\nexport const SANDBOX_PROVIDER =\n 'allow-scripts allow-same-origin allow-forms allow-popups allow-presentation';\n/**\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 unless that page is itself served from the same origin\n * (see `appOrigin`, which is best-effort: it only looks at the URL the frame starts with). Never serve\n * user-controlled HTML on the board's origin. `arbitrarySameOrigin: false` drops the flag for every\n * arbitrary URL (opaque origin: no cookies, no storage), `isolatedHosts` for the hosts it names, at the cost\n * of the sites that need them.\n */\nexport const SANDBOX_ARBITRARY = 'allow-scripts allow-same-origin allow-forms allow-popups';\n/**\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.\n */\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\n/**\n * What an HTML snippet may load. `'images'`: pictures and fonts over https (still requests to any server, so a snippet can tell one it was shown).\n * `'none'`: only what it carries itself (`data:` and `blob:`): no subresource request (image, font, `fetch`...) is\n * allowed. Advisory, not isolation. The CSP is the policy of the snippet's own document, and a snippet can\n * navigate its own frame (`location.href = 'https://x/?...'`): that request always leaves (its URL can carry data\n * out), and the page that answers is not under the snippet CSP. Chromium additionally enforces the CSP on whatever\n * the frame navigates to (the iframe `csp` attribute, see `IframeSpec.csp`), so there the page does not run; other\n * engines run it, for as long as it likes. The layer's navigation guard is best effort against accidents (a link\n * clicked in interact mode), not a security boundary. Only serving snippets from a separate origin would be one.\n */\nexport type SnippetNetwork = 'images' | 'none';\n\n/** The CSP of a snippet with `snippetNetwork: 'images'`. */\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/** The CSP of a snippet with `snippetNetwork: 'none'`. */\nexport const SNIPPET_CSP_NONE =\n \"default-src 'none'; img-src data: blob:; style-src 'unsafe-inline'; script-src 'unsafe-inline'; font-src data:\";\n\n/** The CSP a snippet document carries for a `snippetNetwork` mode. */\nexport const snippetCsp = (network: SnippetNetwork = 'images'): string =>\n network === 'none' ? SNIPPET_CSP_NONE : SNIPPET_CSP;\n\n/** The referrer policy of every embed frame. */\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\n/** The attributes an embed frame is created with: `sandbox`, `allow`, `referrerpolicy`, `src` or `srcdoc`. */\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 // Snippets: the CSP the iframe `csp` attribute carries (Embedded Enforcement, Chromium only: every document the\n // frame loads must accept it, so a page it navigates to that does not send `Allow-CSP-From` is blocked instead\n // of run). Other engines ignore the attribute.\n csp?: 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/**\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.\n *\n * This policy is the document's own. The host page's CSP applies on top of it (a `srcdoc` frame inherits it):\n * a nonce-based `script-src` there blocks the bootstrap and the snippet's inline scripts.\n */\nexport function snippetDocument(html: string, network: SnippetNetwork = 'images'): string {\n return (\n `<!doctype html><meta http-equiv=\"Content-Security-Policy\" content=\"${snippetCsp(network)}\">` +\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\nconst IPV4 = /^\\d{1,3}(?:\\.\\d{1,3}){3}$/;\nconst HOSTNAME = /^[a-z0-9_](?:[a-z0-9_.-]*[a-z0-9_])?$/;\nconst SCHEME = /^[a-z][a-z0-9+.-]*:\\/\\//i;\n\n/** Whether a canonical host (`URL.hostname`, no trailing dot) is an IP literal: v4, or v6 in brackets. */\nconst isIpHost = (host: string): boolean => IPV4.test(host) || host.startsWith('[');\n\nconst invalidHost = (entry: string, why: string): CorkboardError =>\n new CorkboardError('invalid', `isolatedHosts: \"${entry}\" is not a host (${why})`);\n\n/**\n * One `isolatedHosts` entry as the host it names: lowercase, punycode, no port, no trailing dot, IPv6 in brackets.\n * Accepts a bare host (`example.com`, `bücher.de`, `.example.com`, `*.example.com`, `example.com:443`, `::1`,\n * `[::1]`) or a full URL (`https://example.com/`: its host). null: blank (matches nothing). Throws\n * `CorkboardError('invalid')` for what is no host: a path, credentials, a query, a wildcard anywhere but the front,\n * or something that cannot be parsed. Idempotent.\n */\nexport function normalizeIsolatedHost(entry: string): string | null {\n const raw = entry.trim();\n let rest = raw;\n const isUrl = SCHEME.test(rest);\n if (!isUrl) rest = rest.replace(/^(?:\\*\\.|\\.+)/, '');\n if (rest === '' || rest === '.') return null;\n if (!isUrl) {\n // A bare IPv6 literal has no brackets to hold it apart from a port.\n if (rest.split(':').length > 2 && !rest.includes('[')) rest = `[${rest}]`;\n if (/[\\s/\\\\?#@*]/.test(rest)) throw invalidHost(raw, 'only a host, optionally with a port');\n rest = `https://${rest}`;\n }\n let u: URL;\n try {\n u = new URL(rest);\n } catch {\n throw invalidHost(raw, 'it cannot be parsed');\n }\n if (u.username !== '' || u.password !== '') throw invalidHost(raw, 'credentials');\n if ((u.pathname !== '' && u.pathname !== '/') || u.search !== '' || u.hash !== '') throw invalidHost(raw, 'a path, query or fragment');\n const host = u.hostname.toLowerCase().replace(/\\.$/, '');\n if (host === '' || (!isIpHost(host) && (!HOSTNAME.test(host) || host.includes('..')))) throw invalidHost(raw, 'it cannot be parsed');\n return host;\n}\n\n/**\n * The canonical hosts of an `isolatedHosts` list (see {@link normalizeIsolatedHost}); blank entries are dropped.\n * Throws `CorkboardError('invalid')` for an entry that is no host.\n */\nexport function normalizeIsolatedHosts(entries: readonly string[] | undefined): string[] {\n const out: string[] = [];\n for (const entry of entries ?? []) {\n const host = normalizeIsolatedHost(entry);\n if (host !== null) out.push(host);\n }\n return out;\n}\n\n/**\n * Whether `url`'s host is one of `hosts` or a subdomain of one. Entries are normalised first (see\n * {@link normalizeIsolatedHost}; it throws for one that is no host). A domain entry covers itself and its\n * subdomains (`example.com` and `.example.com` and `*.example.com` alike); an IP literal covers exactly that\n * address and is never a suffix (`0.1` does not cover `127.0.0.1`).\n */\nexport function hostIsolated(url: string, hosts: readonly string[] | undefined): boolean {\n if (!hosts || hosts.length === 0) return false;\n const list = normalizeIsolatedHosts(hosts);\n let host: string;\n try {\n host = new URL(url).hostname.toLowerCase().replace(/\\.$/, '');\n } catch {\n return false;\n }\n for (const h of list) {\n if (host === h || (!isIpHost(h) && host.endsWith(`.${h}`))) return true;\n }\n return false;\n}\n\n/** What decides an embed frame's attributes. */\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 // Hosts (and their subdomains; an IP literal only itself) whose frames never get `allow-same-origin`, whatever\n // the profile. Normalised by `hostIsolated`, which throws for an entry that is no host. Like\n // `appOrigin`, it judges the URL the frame starts with: a redirect or a link followed in interact mode is\n // not looked at.\n isolatedHosts?: readonly string[];\n // What a snippet may load (default 'images'). See SnippetNetwork.\n snippetNetwork?: SnippetNetwork;\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, input.snippetNetwork),\n sandbox: SANDBOX_SNIPPET,\n csp: snippetCsp(input.snippetNetwork),\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. Best\n // effort: only the URL the frame starts with is checked, not where it ends up.\n if (input.appOrigin !== undefined && originOf(src) === input.appOrigin) {\n sandbox = sandbox.replace(' allow-same-origin', '');\n }\n if (hostIsolated(src, input.isolatedHosts)) sandbox = sandbox.replace(' allow-same-origin', '');\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","// 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\n/** The icon on a generated tile. */\nexport type TileGlyph = 'play' | 'music' | 'code' | 'design' | 'globe' | 'link-off';\n\n/** What a generated tile (the poster of an embed card with no picture) looks like. */\nexport interface TileSpec {\n // null: none (an HTML snippet: its tile is plain grey text until its preview lands).\n glyph: TileGlyph | null;\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. null: grey (an HTML snippet has no\n // site to colour it by, and a made-up hue reads as content it does not have).\n hue: number | null;\n}\n\n/** A stable hue, in degrees, for a host name. */\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\n/** The look of the generated tile for a resolved embed. Pure. */\nexport function tileSpec(r: ResolvedEmbed): TileSpec {\n let glyph: TileGlyph | null = r.kind === 'html' ? null : 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: r.kind === 'html' ? null : 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 ?? 0} ${spec.hue === null ? 0 : 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 = spec.glyph === null ? 0 : 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 if (spec.glyph !== null) 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 <style> elements the library injects into a document, shared by every board on it and removed with the\n// last one. A reference count per document and sheet: the first user creates the element, the last one to let\n// go removes it. A sheet that is already in the document and not ours (another copy of the library, a page\n// that pre-declared it) is used as it is and never removed.\n\ninterface Sheet {\n // CSS selector that finds the element in the document.\n selector: string;\n // Marks the element it creates, so `selector` finds it.\n mark(el: HTMLStyleElement): void;\n css: string;\n}\n\ninterface Entry {\n count: number;\n // The element we created (null: it was there already, so it is not ours to remove).\n own: HTMLStyleElement | null;\n}\n\nconst registry = new WeakMap<Document, Map<string, Entry>>();\n\n/**\n * Makes sure `sheet` is in the document's <head> and returns the function that lets go of it (idempotent).\n * `nonce` is set on the element it creates, for a CSP with a nonce-based `style-src`.\n */\nexport function acquireStyle(doc: Document, sheet: Sheet, nonce?: string): () => void {\n let perDoc = registry.get(doc);\n if (!perDoc) {\n perDoc = new Map();\n registry.set(doc, perDoc);\n }\n const map = perDoc;\n let entry = map.get(sheet.selector);\n if (!entry) {\n entry = { count: 0, own: null };\n map.set(sheet.selector, entry);\n }\n const e = entry;\n // The element may have been removed from under us (a page that rewrites its <head>): make it again.\n const present = e.own ? e.own.isConnected : doc.head?.querySelector(sheet.selector) != null;\n if (!present && doc.head) {\n const style = doc.createElement('style');\n sheet.mark(style);\n if (nonce) style.nonce = nonce;\n style.textContent = sheet.css;\n doc.head.appendChild(style);\n e.own = style;\n }\n e.count++;\n let released = false;\n return () => {\n if (released) return;\n released = true;\n if (--e.count > 0) return;\n e.own?.remove();\n map.delete(sheet.selector);\n };\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 { Card, CardId, 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 type { BoardErrorEvent } from '../errors';\nimport { PreviewStore, previewKey, previewMaterial, type PreviewCacheMode } from './previewCache';\nimport { iframeSpecFor, normalizeIsolatedHosts, type IframeSpec, type SnippetNetwork } from './sandbox';\nimport { drawTile, tileSpec } from './tile';\nimport { acquireStyle } from '../styles';\n\n/**\n * Options of the embed layer (`CorkboardOptions.embeds`, `board.embeds.setOptions()`). Numeric limits accept `Infinity` for\n * \"no cap\". A page is a live iframe only while its card is in view and within these limits; the rest show their poster.\n */\nexport interface EmbedOptions {\n /**\n * Live iframes at once on a mouse / pen device.\n * @default 12\n */\n maxLive?: number;\n /**\n * Live iframes at once on a touch device.\n * @default 3\n */\n maxLiveTouch?: number;\n /**\n * Mounted iframes at once (live + parked) on a mouse / pen device.\n * @default 24\n */\n maxMounted?: number;\n /**\n * Mounted iframes at once (live + parked) on a touch device.\n * @default 6\n */\n maxMountedTouch?: number;\n /**\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. The most recently seen stay; the rest are destroyed when the camera\n * settles. `Infinity`: only `maxMounted` limits them.\n * @default 64\n */\n maxOffscreen?: number;\n /**\n * The same as `maxOffscreen`, on a touch device.\n * @default 12\n */\n maxOffscreenTouch?: number;\n /**\n * How far past the viewport a card still counts as on screen, as a fraction of the viewport on each side. Frames in\n * that ring keep rendering, and cards entering it mount ahead of the pan.\n * @default 0.5\n */\n cullMargin?: number;\n /**\n * A card goes live when it is at least this big on screen, in CSS px, or selected. Default 0: any card in view, up\n * to `maxLive`, the biggest on screen first. A number is the width; the height keeps a 320:200 ratio.\n */\n minLivePx?: number | { w: number; h: number };\n /**\n * Below this zoom no new iframe mounts. Interacting still flies in to a zoom of 0.25.\n * @default 0 (any zoom)\n */\n minLiveScale?: number;\n /**\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. A failed or\n * timed-out lookup is reported through the `error` event (kind 'embed') and the card falls back to what the\n * URL says. `setOptions` takes it too (it cannot be unset): it applies to lookups started afterwards; cards\n * already resolved keep their result.\n */\n resolve?: EmbedResolver;\n /**\n * Give up on `resolve` after this long, ms, and use what the URL says. `board.embeds.setOptions` changes it for lookups started afterwards.\n * @default 4000\n */\n resolveTimeoutMs?: number;\n /**\n * The virtual screen a live page is laid out at; a card's `embed.resolution` wins.\n * @default '720p'\n */\n resolution?: EmbedResolution;\n /**\n * Keep `allow-same-origin` in the sandbox of arbitrary (non-provider) URLs. Many sites break without their own\n * cookies and storage, but the frame then keeps its real origin across the navigations it makes. `false`: those\n * frames get an opaque origin. Providers and snippets are not affected.\n * @default true\n */\n arbitrarySameOrigin?: boolean;\n /**\n * Hosts whose frames never get `allow-same-origin` (opaque origin: no cookies, no storage), whatever the\n * profile. Each entry is normalised once: a bare host (`example.com`, `bücher.de`, `.example.com`,\n * `*.example.com`, `example.com:443`, `::1`) or a full URL (its host is taken); case, port, a trailing dot and\n * punycode do not matter. A URL matches a domain entry when its host equals it or is a subdomain of it\n * (`example.com`, `.example.com` and `*.example.com` all cover `app.example.com`). An IP literal (v4 or v6)\n * matches exactly that address and is never a suffix. A blank entry matches nothing; an entry with a path,\n * credentials or a query, or that cannot be parsed, throws `CorkboardError` (`'invalid'`) from the constructor\n * or `setOptions`. Judged by the URL the frame starts with only: a redirect, or a link followed in interact\n * mode, can land on a host that is not listed. Changing it remounts the frames it affects.\n */\n isolatedHosts?: readonly string[];\n /**\n * What a snippet (`embed.html`) may load: `'images'` is pictures and fonts over https, which are still requests\n * to any server; `'none'` is only `data:` and `blob:`: no subresource request (image, font, `fetch`...) is\n * allowed. It is advisory, not isolation: a snippet can still navigate its own frame\n * (`location.href = 'https://x/leak?...'`), and that request always leaves (its URL can carry data out); the CSP and\n * the sandbox cannot stop a self-navigation. The page that answers is not under the snippet CSP either, except\n * in Chromium, which enforces the CSP on the pages the frame navigates to (the iframe `csp` attribute) and does not\n * run them; on other engines it runs for as long as it likes. The layer's navigation guard (see `error`) only\n * catches accidents, such as a link clicked in interact mode. Only serving snippets from a separate origin would\n * isolate. Applies to frames mounted after the change; a frame that is already live keeps the policy it was mounted with.\n * @default 'images'\n */\n snippetNetwork?: SnippetNetwork;\n /**\n * Start YouTube and Vimeo videos playing on their own, muted and looping, as soon as their card goes live. Changing it remounts the live frames. Snippets run their own scripts either way.\n * @default false\n */\n autoplay?: boolean;\n /**\n * Iframes loading at once. New frames mount in chunks, nearest the centre of the view first, as earlier ones\n * finish, so a board full of embeds does not start hundreds of pages in the same frame. A frame that has not\n * loaded after 8 s gives its slot up. `Infinity`: no limit.\n * @default 6\n */\n maxLoading?: number;\n /**\n * A mounted card whose short side on screen drops under this many CSS px is not worth rendering. A snippet frame is\n * frozen: it is snapshotted into the card's poster and hidden. A YouTube / Vimeo frame is paused. Both come back above\n * 1.4x this size, when selected or in interact mode. `0`: neither freezing nor size-based pausing (parked and culled frames are still paused).\n * @default 140\n */\n freezePx?: number;\n /**\n * At most this many mounted, visible frames that can be paused (snippets, YouTube / Vimeo) animate at once; the\n * rest are paused, showing their last frame, biggest on screen and nearest the centre first. Pages that cannot be\n * paused (plain URLs, Spotify, CodePen, Figma) are not counted.\n * @default Infinity\n */\n maxAnimating?: number;\n /**\n * Lower the number of animating frames while the page runs under 40 fps, and raise it back (up to `maxAnimating`) when it is smooth again. `false`: always `maxAnimating`.\n * @default true\n */\n adaptive?: boolean;\n /**\n * Hidden frames that render snippets which have not been live, to give their cards a real picture instead of a generated tile. `0`: none, the tile stays until the card goes live.\n * @default 3\n */\n previewWorkers?: number;\n /**\n * Where those pictures are kept: `'memory'` is this page only. `'persistent'` also keeps them in Cache Storage (at\n * most 1000, oldest dropped first), so a reload shows them at once; it leaves pictures of the snippets on the\n * visitor's disk, hence opt-in. Falls back to memory where Cache Storage cannot be used, or in an insecure context\n * (entries are named by a SHA-256, which needs `crypto.subtle`). `{ persistent: true, name }` uses the Cache Storage\n * entry `name` instead of the default `corkboard-previews-v2`. `Corkboard.clearPreviewCache(name?)` empties it.\n * @default 'memory'\n */\n previewCache?: PreviewCacheMode;\n}\n\n/** The embed layer's events, on the board's `on()` (see `CorkboardEvents`). */\nexport interface EmbedEvents {\n /** Interact mode began (`active: true`) or ended on an embed card. */\n embedInteract: { id: CardId; active: boolean };\n /** A card's iframe was mounted (`live: true`) or destroyed. */\n embedLive: { id: CardId; live: boolean };\n /**\n * A card's embed was resolved. `poster` is a URL worth persisting (the host's own or a provider thumbnail), absent for a\n * generated tile or any blob URL this layer made (they die with the page).\n */\n embedResolved: {\n id: CardId;\n provider: EmbedProvider;\n frameable: boolean;\n aspect?: number;\n title?: string;\n poster?: string;\n };\n /**\n * Something failed at runtime (`kind: 'embed'`): the resolver threw or timed out, or a snippet kept navigating its\n * frame away from its document (3 times within 10 s; each time the layer put its document back, and now the card\n * stays on its poster and `info()` says `blocked`). The navigation guard is best effort against accidents, such as a\n * link clicked in interact mode: it is not a security boundary (see `snippetNetwork`). The card keeps working on its\n * fallback (URL-derived info, or its poster).\n */\n error: BoardErrorEvent;\n}\n\n/** What the embed layer is given by the board. */\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 // `nonce` of the injected <style> (a CSP with a nonce-based `style-src`).\n nonce?: string;\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 // A snippet whose frame kept navigating away from its document (see `guardLoad`): it never goes live again\n // (until its content changes, which makes a new entry).\n blocked: boolean;\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 material: 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: CardId;\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 navigation guard (see `guardLoad`): the window the iframe had at the last accepted load, when the\n // layer last put the document back (its next load is that document, not a navigation), and the times of the\n // strikes (Date.now()) still within NAV_STRIKE_MS.\n win: Window | null;\n restoring: boolean;\n strikes: number[];\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\n// A snippet's frame that loads something other than its own document is given its document back; this many times\n// within NAV_STRIKE_MS and the card is blocked (until its content changes) and an `error` is emitted.\nexport const NAV_STRIKES = 3;\nexport const NAV_STRIKE_MS = 10_000;\nexport const MAX_LOADING = 6;\nexport const LOAD_SLOT_MS = 8000;\n/**\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.\n */\nexport const CULL_MARGIN = 0.5;\n/**\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.\n */\nexport const FREEZE_PX = 140;\nexport const FREEZE_HYSTERESIS = 1.4;\n/**\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.\n */\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/**\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.\n */\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/**\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).\n */\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/**\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.\n */\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`;\nconst SHEET = {\n selector: `style#${STYLE_ID}`,\n mark: (el: HTMLStyleElement): void => {\n el.id = STYLE_ID;\n },\n css: CSS,\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\n/** The live iframes of the embed cards: mounting, limits, parking, freezing, previews and interact mode. The board owns one; reach it with `getInternals`. */\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<CardId, Entry>();\n private readonly frames = new Map<CardId, 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 isolatedHosts: readonly string[];\n snippetNetwork: SnippetNetwork;\n autoplay: boolean;\n maxLoading: number;\n freezePx: number;\n maxAnimating: number;\n adaptive: boolean;\n previewWorkers: number;\n };\n private selected = new Set<CardId>();\n private touch = false;\n private moving = false;\n private planDirty = false;\n private interactId: CardId | null = null;\n // Double-click on a card too small to mount (zoomed far out): fly to it, then interact.\n private pendingInteract: CardId | 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<CardId>();\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 isolatedHosts: normalizeIsolatedHosts(options.isolatedHosts),\n snippetNetwork: options.snippetNetwork ?? 'images',\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 this.cleanups.push(acquireStyle(this.doc, SHEET, deps.nonce));\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 // The board never sees this wheel: consume it here so a swipe over the button is not a history swipe.\n if (t === 'wheel') e.preventDefault();\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<CardId> {\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<CardId> {\n const out = new Set<CardId>();\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<CardId> {\n const out = new Set<CardId>();\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<CardId> {\n const out = new Set<CardId>();\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<CardId> {\n const out = new Set<CardId>();\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<CardId> {\n const out = new Set<CardId>();\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(): CardId | 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 // A blocked snippet (see `guardLoad`) says so, and that it is not frameable; a content change clears it.\n info(id: CardId): Readonly<ResolvedEmbed> | null {\n const e = this.entries.get(id);\n if (!e) return null;\n return e.blocked ? Object.freeze({ ...e.info, frameable: false, blocked: true }) : e.info;\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 // First: an invalid list throws before anything else is applied.\n const isolated = o.isolatedHosts === undefined ? undefined : normalizeIsolatedHosts(o.isolatedHosts);\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 if (o.resolve !== undefined) this.opts.resolve = o.resolve;\n if (o.resolveTimeoutMs !== undefined) this.opts.resolveTimeoutMs = o.resolveTimeoutMs;\n const sandboxChanged = o.arbitrarySameOrigin !== undefined && o.arbitrarySameOrigin !== this.opts.arbitrarySameOrigin;\n const autoplayChanged = o.autoplay !== undefined && o.autoplay !== this.opts.autoplay;\n const isolatedChanged = isolated !== undefined && !sameList(isolated, this.opts.isolatedHosts);\n const networkChanged = o.snippetNetwork !== undefined && o.snippetNetwork !== this.opts.snippetNetwork;\n if (sandboxChanged || autoplayChanged || isolatedChanged || networkChanged) {\n if (o.arbitrarySameOrigin !== undefined) this.opts.arbitrarySameOrigin = o.arbitrarySameOrigin;\n if (o.autoplay !== undefined) this.opts.autoplay = o.autoplay;\n if (isolated !== undefined) this.opts.isolatedHosts = isolated;\n if (o.snippetNetwork !== undefined) this.opts.snippetNetwork = o.snippetNetwork;\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. A snippet's document\n // (its CSP) is not: a live snippet keeps the policy it loaded with, only frames mounted later get the new one.\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: CardId): 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 CardId[]): 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: CardId | 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: CardId): 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: CardId): void {\n const el = this.store.get(id);\n if (el) this.track(el);\n }\n\n private track(el: Card): 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 blocked: false,\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: CardId, 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 isolatedHosts: this.opts.isolatedHosts,\n snippetNetwork: this.opts.snippetNetwork,\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: CardId, 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 if (alive()) this.emit('error', { kind: 'embed', id, url: entry.info.url, cause: 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)) }, 'system');\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: CardId): 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: CardId, 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: CardId, 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: CardId, 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: CardId, 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 && !entry.blocked,\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 CardId[]): CardId[] {\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<CardId, 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: CardId): 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 // Chromium refuses to run, in this frame, a page that does not accept the snippet's CSP (see IframeSpec.csp).\n if (spec.csp !== undefined) iframe.setAttribute('csp', spec.csp);\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 win: null,\n restoring: false,\n strikes: [],\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 page that follows a link, a snippet's frame reloaded because the\n // host moved the board in the DOM), and each one is a new document: it knows nothing of what the previous one\n // was told or asked.\n iframe.addEventListener('load', () => {\n // A snippet's document is its `srcdoc`, which reloads as itself. Whatever else loads (a `location`\n // assignment, a meta refresh, a link) is not the document the CSP and the bootstrap were written for: it is\n // replaced by that document again (see `guardLoad`). The `about:blank` load of a frame this layer already\n // destroyed is not looked at.\n if (frame.kind === 'snippet' && this.frames.get(id) === frame && !this.guardLoad(id, entry, frame)) return;\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 // The navigation guard, run for each `load` of a snippet's frame. true: the load is the snippet's own document.\n //\n // Best effort against accidents (a link clicked in interact mode, a stray `location` assignment), not a security\n // boundary: no frame-level signal says which document loaded (a navigation during parse means our `srcdoc` never\n // fires `load` at all, and a page that never finishes loading fires none), so a hostile snippet can run another\n // page in its frame for as long as it likes. Chromium does not run such a page (the `csp` attribute), other\n // engines do.\n // - the first load, a load with a new `contentWindow` (the host moved the board in the DOM: a reparented\n // iframe is a new browsing context that reloads its `srcdoc`), and the load of the document this layer put\n // back are accepted;\n // - any other load is a navigation: the `srcdoc` is assigned again (the frame loads its own document back)\n // and it counts as a strike; NAV_STRIKES within NAV_STRIKE_MS block the card.\n private guardLoad(id: CardId, entry: Entry, f: Frame): boolean {\n const win = f.iframe.contentWindow;\n if (f.win === null || win !== f.win) {\n f.win = win;\n f.restoring = false;\n return true;\n }\n if (f.restoring) {\n f.restoring = false;\n return true;\n }\n const now = Date.now();\n f.strikes = f.strikes.filter((t) => now - t < NAV_STRIKE_MS);\n f.strikes.push(now);\n if (f.strikes.length >= NAV_STRIKES) this.blockSnippet(id, entry);\n else {\n f.restoring = true;\n f.iframe.srcdoc = f.iframe.srcdoc;\n }\n return false;\n }\n\n private blockSnippet(id: CardId, entry: Entry): void {\n if (this.disposed || this.entries.get(id) !== entry) return;\n entry.blocked = true;\n this.destroyFrame(id);\n this.emit('error', { kind: 'embed', id, cause: new Error('snippet navigated away from its document') });\n this.requestPlan();\n }\n\n private destroyFrame(id: CardId): 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: CardId, 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: CardId, 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: CardId, 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: CardId, 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: CardId, 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: CardId; 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<CardId>();\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: CardId, 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: CardId, 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) return;\n if (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 (!validSvg(d)) 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 (!validSvg(d)) 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: CardId, 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: CardId, 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: CardId): 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: CardId, entry: Entry): boolean {\n if (entry.info.kind !== 'html' || !entry.ready || entry.blocked || 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: CardId, 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 || entry.blocked) 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 {\n key: previewKey(html, bucket, String(res), w, h),\n material: previewMaterial(html, bucket, String(res), w, h),\n vw: box.width,\n vh: box.height,\n w,\n h,\n };\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, plan.material);\n else entry.pv = 'queued';\n }\n this.pumpPreviews();\n }\n\n private lookupPreview(id: CardId, entry: Entry, key: string, material: string): void {\n entry.pv = 'checking';\n const token = entry.token;\n void this.previews.getPersistent(material).then((blob) => {\n if (this.disposed || this.entries.get(id) !== entry || entry.token !== token || entry.pv !== 'checking') return;\n // Came from Cache Storage: not written back.\n if (blob) this.previews.put(key, blob);\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: CardId, 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: CardId; 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: CardId; 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: CardId, 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 if (spec.csp !== undefined) ifr.setAttribute('csp', spec.csp);\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, job.plan.material);\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: CardId): void {\n const cam = this.stage.cam;\n const r = this.stage.boundsOf([id]);\n if (!r) return;\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: CardId, 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.blocked) return false;\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/**\n * The most a snapshot reply may weigh, as the length of its SVG string (UTF-16 units, about 2 MB as sent): a\n * page that answers with more is treated as a failed snapshot instead of being parsed and drawn here.\n */\nexport const SNAPSHOT_MAX_SVG = 2 * 1024 * 1024;\n\nconst validSvg = (d: { ok?: unknown; svg?: unknown }): d is { svg: string } =>\n d.ok !== false && typeof d.svg === 'string' && d.svg !== '' && d.svg.length <= SNAPSHOT_MAX_SVG;\n\nconst sameList = (a: readonly string[], b: readonly string[]): boolean => a.length === b.length && a.every((v, i) => v === b[i]);\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","/** An event listener. */\nexport type Listener<T> = (payload: T) => void;\n\n// A listener that throws must not stop the others, nor the library's own bookkeeping that runs next to it.\n// The error is reported on the console, once per throw, and swallowed.\nexport function reportListenerError(what: string, err: unknown): void {\n console.error(`[corkboard] ${what} threw`, err);\n}\n\n/**\n * A tiny typed event emitter. A listener that throws is reported with `console.error` and does not stop the others.\n * An event emitted by a listener while another is being delivered waits until that one has reached every listener:\n * events are delivered one at a time, in the order they were emitted.\n */\nexport class Emitter<M extends object> {\n private readonly map = new Map<keyof M, Set<Listener<never>>>();\n private delivering = false;\n private readonly queue: { type: keyof M; payload: unknown }[] = [];\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 if (this.delivering) {\n this.queue.push({ type, payload });\n return;\n }\n this.delivering = true;\n try {\n this.deliver(type, payload);\n // Listeners may emit while we deliver: the queue grows behind the event in hand.\n for (let i = 0; i < this.queue.length; i++) this.deliver(this.queue[i].type, this.queue[i].payload as M[keyof M]);\n } finally {\n this.queue.length = 0;\n this.delivering = false;\n }\n }\n\n private deliver<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]) {\n try {\n (fn as Listener<M[K]>)(payload);\n } catch (err) {\n reportListenerError(`\"${String(type)}\" listener`, err);\n }\n }\n }\n\n clear(): void {\n this.map.clear();\n this.queue.length = 0;\n }\n}\n","// Small argument checks shared by the public entry points (`add`, `update`, the layout, camera and option\n// setters...). Every failure is a `CorkboardError('invalid')` that names the call and the value, instead of a raw\n// TypeError from deep inside or a NaN that lands in the store.\nimport { CorkboardError } from './errors';\nimport type { CardId } from './types';\n\nexport const bad = (where: string, what: string): never => {\n throw new CorkboardError('invalid', `${where}: ${what}`);\n};\n\nexport const show = (v: unknown): string => {\n if (typeof v === 'string') return JSON.stringify(v);\n if (typeof v === 'object' && v !== null) return Array.isArray(v) ? 'an array' : 'an object';\n return String(v);\n};\n\nexport const isObject = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null;\n\nexport const finite = (where: string, field: string, v: unknown): void => {\n if (typeof v !== 'number' || !Number.isFinite(v)) bad(where, `${field} must be a finite number (got ${show(v)})`);\n};\n\nexport const positive = (where: string, field: string, v: unknown): void => {\n if (typeof v !== 'number' || !Number.isFinite(v) || v <= 0) {\n bad(where, `${field} must be a finite number > 0 (got ${show(v)})`);\n }\n};\n\nexport const nonNegative = (where: string, field: string, v: unknown): void => {\n if (typeof v !== 'number' || !Number.isFinite(v) || v < 0) {\n bad(where, `${field} must be a finite number >= 0 (got ${show(v)})`);\n }\n};\n\nexport const boolean = (where: string, field: string, v: unknown): void => {\n if (typeof v !== 'boolean') bad(where, `${field} must be a boolean (got ${show(v)})`);\n};\n\n/** A whole number >= `min`. */\nexport const integer = (where: string, field: string, v: unknown, min: number): void => {\n if (typeof v !== 'number' || !Number.isInteger(v) || v < min) {\n bad(where, `${field} must be an integer >= ${min} (got ${show(v)})`);\n }\n};\n\n/** A limit: a number >= 0 where `Infinity` means \"no cap\" (NaN and negatives are refused). */\nexport const limit = (where: string, field: string, v: unknown): void => {\n if (typeof v !== 'number' || Number.isNaN(v) || v < 0) {\n bad(where, `${field} must be a number >= 0, or Infinity for no cap (got ${show(v)})`);\n }\n};\n\nexport function oneOf<T extends string>(where: string, field: string, v: unknown, allowed: readonly T[]): void {\n if (!allowed.includes(v as T)) bad(where, `${field} must be one of ${allowed.map((a) => `'${a}'`).join(', ')} (got ${show(v)})`);\n}\n\n/** `o` as a record: an object, not null and not an array (`undefined` is for the caller to treat as \"no options\"). */\nexport function record(where: string, what: string, o: unknown): Record<string, unknown> {\n if (!isObject(o) || Array.isArray(o)) return bad(where, `${what} must be an object (got ${show(o)})`);\n return o;\n}\n\n/** The geometry every card must keep, whoever writes it: x, y, rot finite and w, h finite and > 0. Parts left out are not checked. */\nexport function assertGeometry(\n where: string,\n g: { x?: number; y?: number; w?: number; h?: number; rot?: number },\n): void {\n if (g.x !== undefined) finite(where, 'x', g.x);\n if (g.y !== undefined) finite(where, 'y', g.y);\n if (g.w !== undefined) positive(where, 'w', g.w);\n if (g.h !== undefined) positive(where, 'h', g.h);\n if (g.rot !== undefined) finite(where, 'rot', g.rot);\n}\n\n/**\n * The ids a method takes, as a list: one id or an array of ids. `optional`: `undefined` means \"all\" and comes\n * back as `undefined`. Anything else (a number, `null`, an array with a non-string in it) is 'invalid'.\n */\nexport function idList(where: string, ids: unknown, optional: true): CardId[] | undefined;\nexport function idList(where: string, ids: unknown, optional?: false): CardId[];\nexport function idList(where: string, ids: unknown, optional = false): CardId[] | undefined {\n if (ids === undefined && optional) return undefined;\n if (typeof ids === 'string') return [ids];\n if (!Array.isArray(ids)) return bad(where, `ids must be a card id or an array of card ids (got ${show(ids)})`);\n for (let i = 0; i < ids.length; i++) {\n if (typeof ids[i] !== 'string') bad(where, `ids[${i}] must be a card id (a string, got ${show(ids[i])})`);\n }\n return ids as CardId[];\n}\n\n/** A world rectangle `{ x0, y0, x1, y1 }` with finite corners. */\nexport function assertRect(where: string, r: unknown): void {\n if (!isObject(r)) return bad(where, `needs a rectangle { x0, y0, x1, y1 } (got ${show(r)})`);\n for (const k of ['x0', 'y0', 'x1', 'y1']) finite(where, k, r[k]);\n}\n","// Pure camera math. No DOM, no Pixi.\n\n/** The view: a world point (wx, wy) shows at (`tx` + wx * `scale`, `ty` + wy * `scale`) in host-local CSS px. */\nexport interface Camera {\n /** Screen x of the world origin, CSS px. */\n tx: number;\n /** Screen y of the world origin, CSS px. */\n ty: number;\n /** Zoom: CSS px per world px. */\n scale: number;\n}\n\n/**\n * A world rectangle by its corners: (`x0`, `y0`) top-left, (`x1`, `y1`) bottom-right. What `camera.visible()`,\n * `bounds()`, `inRect()` and `camera.zoomTo()` use. See {@link Box} for the `{ x, y, w, h }` shape.\n */\nexport interface Rect {\n /** Left edge. */\n x0: number;\n /** Top edge. */\n y0: number;\n /** Right edge. */\n x1: number;\n /** Bottom edge. */\n y1: number;\n}\n\n/**\n * An x/y/w/h rectangle: top-left corner and size. Each use says whether it is world px or screen px:\n * `board.screenRect(id)` returns one in host-local CSS px (where the card is drawn), the `rects` of the `transform`\n * event are in world px. Not to be confused with {@link Rect}, the world rectangle by corners.\n */\nexport interface Box {\n /** Left edge. */\n x: number;\n /** Top edge. */\n y: number;\n /** Width. */\n w: number;\n /** Height. */\n h: 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\n/** A wheel event reduced to what the camera needs. */\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\n/** The camera of the stage: the current view, animated moves and the zoom limits. */\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 // Changes the zoom range. A camera (or a move in flight) outside it is brought into it about the viewport\n // centre. The caller has checked 0 < min <= max.\n setRange(min: number, max: number): void {\n this.bounds.min = min;\n this.bounds.max = max;\n this.targetScale = clamp(this.targetScale, min, max);\n if (this.fly) this.fly.to = this.clampCamera(this.fly.to);\n if (this.cam.scale < min || this.cam.scale > max) this.jumpTo({ ...this.cam });\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","/** Texture level of a card: 0 placeholder, 1 atlas cell, 2 own texture, 3 close zoom. */\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 { Card } from '../types';\nimport { DEG, type WorldRect } from './geometry';\n\n/** The rectangle of a selection or hover outline. */\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<Card, '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 { Aabb } 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\n/** What the overlay draws for the selection. */\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\n/** The canvas layer that draws the selection, handles, marquee and guides. */\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: Aabb | 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: Aabb | 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\n/** Options of the texture manager. */\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 // A picture that would not load, or the end of the decode workers. The stage turns the card slot into\n // an element id and hands it to the host.\n onError?: (e: TextureError) => void;\n}\n\n/** A texture failure, as the texture manager reports it. */\nexport interface TextureError {\n kind: 'texture' | 'worker';\n slot?: number;\n url?: string;\n cause: unknown;\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\n/** A texture the stage asks the manager for. */\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// The texture system as the partial upload sees it. `getGlSource`, `initSource`, `bind` and `unbind` are public Pixi API;\n// the three underscored members are Pixi internals (all present in 8.22; the peer range in package.json starts\n// there), so they are optional here and feature-detected (see `hasPrivateUpload`).\ninterface GlTextureSystemInternals {\n getGlSource(source: TextureSource): { target: number; texture: WebGLTexture };\n initSource(source: TextureSource): void;\n bind(texture: TextureSource, location?: number): void;\n unbind(texture: TextureSource): void;\n _premultiplyAlpha?: boolean;\n _activateLocation?(location: number): void;\n _setBoundTexture?(location: number, source: TextureSource | null): void;\n}\n\n// Replaced at build time (vite `define`): true only in the e2e build and under vitest. In the library build it is\n// the literal `false`, so the test hook below is dead code and does not reach `dist`.\ndeclare const __CORKBOARD_TEST__: boolean;\n\n// Whether the Pixi private members the fast upload path leans on exist with the expected types. When a Pixi\n// minor renames them the manager falls back to the public path (see `bindPage`/`uploadCell`) instead of throwing.\nexport function hasPrivateUpload(sys: unknown): boolean {\n // Test hook: `globalThis.__corkboardForcePublicUpload = true` before creating a board forces the public upload\n // path (the e2e suite uses it to prove the fallback renders on the Pixi version under test). A local cast: no\n // global is declared, so nothing of it reaches the published types.\n if (\n typeof __CORKBOARD_TEST__ !== 'undefined' &&\n __CORKBOARD_TEST__ &&\n (globalThis as { __corkboardForcePublicUpload?: boolean }).__corkboardForcePublicUpload\n ) {\n return false;\n }\n const s = sys as Partial<GlTextureSystemInternals> | null;\n return (\n !!s &&\n typeof s._activateLocation === 'function' &&\n typeof s._setBoundTexture === 'function' &&\n typeof s._premultiplyAlpha === 'boolean'\n );\n}\n\nlet warnedPublicUpload = false;\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\n/** Decodes pictures in workers and keeps them in atlases and own textures within a memory budget. */\nexport class TextureManager {\n private readonly texSys: GlTextureSystemInternals;\n // True: bind and premultiply through Pixi's private members (no redundant GL calls). False: the public\n // `texture.bind` and a read-and-restore of the GL pixel-store flag (see `bindPage`/`uploadCell`).\n private readonly privateUpload: boolean;\n private readonly gl: WebGL2RenderingContext;\n private readonly workers: Worker[] = [];\n private readonly workerLoad: number[] = [];\n // Workers whose script died (`error`): never sent to again. With none alive nothing can be decoded.\n private readonly workerDead: boolean[] = [];\n private liveWorkers = 0;\n private disposed = false;\n // Failures already reported, per card slot: \"slot|url\". A retry that fails again stays quiet.\n private readonly reported = new Map<number, Set<string>>();\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.privateUpload = hasPrivateUpload(this.texSys);\n if (!this.privateUpload && !warnedPublicUpload) {\n warnedPublicUpload = true;\n console.warn(\n 'corkboard: the Pixi texture system lacks the internals the fast upload path uses; falling back to the public (slower) path.',\n );\n }\n this.retire = new RetireQueue(opts.retireDelay ?? 2);\n this.border = opts.border ?? '';\n this.atlas0 = this.makeAtlas0();\n this.atlas1 = this.makeAtlas1();\n try {\n this.spawnWorkers(opts.workers);\n } catch (e) {\n // A bad `workerUrl` throws from `new Worker`: let go of the ones that did start.\n for (const w of this.workers) w.terminate();\n throw e;\n }\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) => this.onWorkerError(i, e);\n this.workers.push(w);\n this.workerLoad.push(0);\n this.workerDead.push(false);\n this.liveWorkers++;\n }\n }\n\n // A worker died. Its in-flight jobs go back in the queue for the others; with none left they all fail\n // (the cards keep their placeholders) and nothing is dispatched again.\n private onWorkerError(wi: number, cause: unknown): void {\n if (this.disposed || this.workerDead[wi]) return;\n this.workerDead[wi] = true;\n this.liveWorkers--;\n this.workers[wi].terminate();\n this.workerLoad[wi] = 0;\n for (const req of [...this.reqs.values()]) {\n if (!req.inflight || req.worker !== wi) continue;\n this.inflight = Math.max(0, this.inflight - 1);\n if (req.cancelled) {\n this.reqs.delete(req.rid);\n continue;\n }\n req.inflight = false;\n req.worker = -1;\n this.queue.push(req);\n }\n if (this.liveWorkers > 0) {\n this.pump();\n } else {\n for (const r of this.reqs.values()) r.cancelled = true;\n this.reqs.clear();\n this.reqByKey.clear();\n this.queue = [];\n this.inflight = 0;\n }\n this.opts.onError?.({ kind: 'worker', cause });\n }\n\n // ── Queries ────────────────────────────────────────────────────────────────\n get totalBytes(): number {\n return this.pageBytes + this.ownBytes;\n }\n get workerCount(): number {\n return this.liveWorkers;\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 // No worker left: nothing could ever be decoded, and queueing would only pile up.\n if (this.liveWorkers === 0 && this.workers.length > 0) return;\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.liveWorkers * 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 = -1;\n for (let i = 0; i < this.workers.length; i++) {\n if (this.workerDead[i]) continue;\n if (wi < 0 || 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) {\n this.failedAt.set(key(req.card, req.level), performance.now());\n this.reportTexture(req, m.reason);\n }\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 // One `texture` error per card and URL: the retry that follows RETRY_AFTER_MS must not repeat it.\n private reportTexture(req: Req, reason: string): void {\n // L0 is decoded from the ThumbHash, there is no URL to blame.\n const url = this.urlOf(req.card, req.level);\n const tag = `${req.level}|${url ?? ''}`;\n let seen = this.reported.get(req.card.id);\n if (seen?.has(tag)) return;\n if (!seen) this.reported.set(req.card.id, (seen = new Set()));\n seen.add(tag);\n this.opts.onError?.({ kind: 'texture', slot: req.card.id, url, cause: new Error(reason) });\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 this.reported.delete(id);\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 // New pictures have new URLs, but a failure of the same URL after a swap back deserves a new report.\n this.reported.delete(id);\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 if (this.privateUpload) {\n // Always rebinds on the raw GL context (other code may have changed the binding behind Pixi's cache).\n sys._activateLocation!(0);\n gl.bindTexture(glTex.target, glTex.texture);\n sys._setBoundTexture!(0, p.source);\n } else {\n // Public: Pixi keeps its own bound-texture cache in step. `bind` alone is not enough: when its cache says\n // unit 0 already holds the page it skips `activeTexture(0)`, and after a batch that used units 0 and 1 the\n // active unit is 1, so the upload below would land in whatever texture the batch left on unit 1. Dropping the\n // page from the cache first makes `bind` a miss, which always activates unit 0 and binds the page there.\n sys.unbind(p.source);\n sys.bind(p.source, 0);\n }\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 let restorePremultiply = false;\n if (this.privateUpload) {\n if (!this.texSys._premultiplyAlpha) {\n gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);\n this.texSys._premultiplyAlpha = true;\n }\n } else if (!gl.getParameter(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL)) {\n // Pixi's cached copy of the flag is out of reach: flip the real flag for this upload only and put it back,\n // so Pixi's own uploads keep seeing the state it believes in.\n gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);\n restorePremultiply = 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 if (restorePremultiply) gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);\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.workerDead[r.worker]) 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.disposed = true;\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 { Card } from '../../types';\nimport type { BoardCard } from '../types';\nimport { parseHex } from '../theme';\nimport type { CardView, ViewCtx } from './view';\n\nexport class MediaView implements CardView {\n readonly variant = 'media' as const;\n readonly display = new Container();\n private readonly sprite: Sprite;\n el: Card | 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(): Card['kind'] {\n return this.el?.kind ?? 'image';\n }\n\n mount(el: Card, 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: Card, _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 { CardKind } from '../../types';\nimport { MediaView } from './mediaView';\nimport type { CardView } from './view';\n\nexport interface ViewDefinition {\n // The pool name. Kinds that share a view class share a variant.\n variant: string;\n create(): CardView;\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<CardKind, 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 { CardKind } from '../../types';\nimport { VIEW_DEFINITIONS, type ViewDefinition } from './registry';\nimport type { CardView } from './view';\n\n/** Pools of card views, reused as cards enter and leave the viewport. */\nexport class ViewPools {\n private readonly pools = new Map<string, CardView[]>();\n private created = 0;\n private reused = 0;\n\n acquire(kind: CardKind): CardView {\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: CardView): 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: CardKind): 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 {\n Application,\n Container,\n RendererType,\n Texture,\n TilingSprite,\n Ticker,\n type WebGLRenderer,\n} from 'pixi.js';\nimport { CorkboardError, type BoardErrorEvent } from '../errors';\nimport type { Camera, Rect } from '../math';\nimport { elementBox, emptyBox, worldRectOf, type WorldRect } from '../interact/geometry';\nimport type { Aabb } from '../interact/geometry';\nimport type { Percentiles, SlowTick, StageStats } from '../stats';\nimport type { ChangeSet, StoreEvent } from '../store';\nimport { DEFAULTS, MAX_SCALE, MIN_SCALE, type Card, type CardId } 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 TextureError, type WantedItem } from './textures';\nimport { DARK_THEME, type Theme } from './theme';\nimport type { BoardCard } from './types';\nimport { ViewPools, definitionOf } from './views/pool';\nimport { MediaView } from './views/mediaView';\nimport type { CardView, 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: CardId): Card | undefined;\n elements(): IterableIterator<Card>;\n searchInto(box: Aabb, out: Card[]): Card[];\n rank(id: CardId): number;\n readonly orderVersion: number;\n}\n\n/** Options of the stage. `CorkboardOptions.textures` takes the texture ones. */\nexport interface StageOptions {\n /**\n * GPU texture memory budget in bytes. 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 its URL here.\n */\n workerUrl?: string | URL;\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 * Per-frame texture upload budget, ms.\n * @default 4\n */\n uploadBudgetMs?: number;\n /**\n * Overscan, as a fraction of the viewport added on every side.\n * @default 0.5\n */\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 /**\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 */\n minScale?: number;\n maxScale?: number;\n /**\n * A texture that would not load, a decode worker that died, the WebGL context lost: the board forwards\n * these to the host as its `error` event.\n */\n onError?: (e: BoardErrorEvent) => void;\n /** The WebGL context was lost / came back (the textures are rebuilt by themselves). */\n onContextLost?: () => void;\n onContextRestored?: () => void;\n /**\n * Called once per rendered frame (not per idle tick) with the main-thread time of the render and the GPU\n * timer results that arrived meanwhile (those belong to earlier frames; empty without `gpuTimer`).\n */\n onRender?: (e: { cpuMs: number; gpuMs: readonly number[] }) => void;\n /**\n * Cancels `Stage.create`: checked after each await, and when it aborts everything made so far is released\n * and the promise rejects with `signal.reason`.\n */\n signal?: AbortSignal;\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 r2 = (n: number): number => Math.round(n * 100) / 100;\n\n// The spread of the first `n` samples of a ring buffer; null with none.\nfunction spread(a: Float32Array, n: number): Percentiles | null {\n if (n === 0) return null;\n const s = Array.from(a.subarray(0, n)).sort((x, y) => x - y);\n const at = (p: number): number => r2(s[Math.min(n - 1, Math.floor((n - 1) * p))]);\n return { n, p50: at(0.5), p95: at(0.95), max: r2(s[n - 1]) };\n}\n\n// The GPU results of a frame that had none (shared: the render event hands it out read-only).\nconst NO_GPU: readonly number[] = Object.freeze([]) as readonly number[];\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// 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\n/** The WebGL stage of a board: Pixi renderer, camera, culling, texture pipeline and card views. The board owns one; reach it with `getInternals`. */\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'\n | 'workers'\n | 'workerUrl'\n | 'retireDelay'\n | 'cspSafe'\n | 'grid'\n | 'minScale'\n | 'maxScale'\n | 'onError'\n | 'onContextLost'\n | 'onContextRestored'\n | 'onRender'\n | 'signal'\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 readonly onError: ((e: BoardErrorEvent) => void) | undefined;\n private readonly onContextLost: (() => void) | undefined;\n private readonly onContextRestored: (() => void) | undefined;\n private readonly onRender: StageOptions['onRender'];\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<CardId, CardView>();\n private readonly mediaViews = new Set<MediaView>();\n private readonly hits: Card[] = [];\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: CardId; key: number }[] = [];\n private readonly queued = new Set<CardId>();\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<CardId>();\n private pendingRemoved = new Map<CardId, Card>();\n private pendingUpdated = new Map<CardId, Set<string>>();\n private pendingReload = false;\n\n // ── Cards (texture slots) ──\n private slotOf = new Map<CardId, 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<CardId, PreviewRect>();\n private readonly hidden = new Set<CardId>();\n // Runtime pictures that stand in for an element's `media.src` / `sizes` (see setPosterOverride).\n private readonly posters = new Map<CardId, string>();\n private readonly alphas = new Map<CardId, number>();\n // Elements that must stay mounted regardless of the window (previewed, being dragged).\n private readonly pinned = new Set<CardId>();\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: SlowTick[] = [];\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 const { signal } = options;\n if (options.cspSafe) {\n await import('pixi.js/unsafe-eval');\n if (signal?.aborted) throw signal.reason;\n }\n const app = new Application();\n // Whatever was built so far goes: the canvas Pixi appended, the GL context, the ticker hold (by the\n // caller) and, via the manager, the workers.\n const abort = (): void => {\n let canvas: HTMLCanvasElement | null = null;\n try {\n canvas = app.canvas as HTMLCanvasElement;\n } catch {\n // `init` threw before the renderer existed: no canvas to take back.\n }\n try {\n app.destroy(true, { children: true, texture: false });\n } catch {\n // Half-initialised: nothing more to release.\n }\n canvas?.remove();\n };\n try {\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 // Aborted while Pixi was starting: the catch below takes the half-made app apart.\n if (signal?.aborted) throw signal.reason;\n // Pixi falls back to WebGPU or a 2D canvas when WebGL is missing; the stage needs WebGL2.\n if (app.renderer.type !== RendererType.WEBGL || !isWebGL2(app.renderer as WebGLRenderer)) {\n throw new CorkboardError('unsupported', 'Corkboard needs WebGL2, which this browser did not provide');\n }\n Ticker.system.stop();\n app.ticker.stop();\n return new Stage(app, host, options, dpr, unpark);\n } catch (err) {\n abort();\n throw err;\n }\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.onError = options.onError;\n this.onContextLost = options.onContextLost;\n this.onContextRestored = options.onContextRestored;\n this.onRender = options.onRender;\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 onError: (e) => this.reportTextureError(e),\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.reload) {\n // `loadSnapshot` swapped the board: rebuild from the store at the next tick instead of walking the diff.\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 // Per-card state of cards that are gone (a `load` swaps the whole board; the incremental path does the\n // same per removal in `flushStore`).\n for (const id of [...this.posters.keys()]) if (!store.get(id)) this.posters.delete(id);\n for (const id of [...this.previews.keys()]) if (!store.get(id)) this.previews.delete(id);\n for (const id of [...this.alphas.keys()]) if (!store.get(id)) this.alphas.delete(id);\n for (const id of [...this.hidden]) if (!store.get(id)) this.hidden.delete(id);\n for (const id of [...this.pinned]) if (!store.get(id)) this.pinned.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 Card;\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 Card);\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: CardId): 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: CardId): 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: Card): 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: Card): [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: Card): 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: Card): 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: Card): 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: Card): 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: CardId, 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: CardId): 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: CardId, el: Card): 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: Card): WorldRect {\n return this.previews.get(el.id) ?? worldRectOf(el);\n }\n\n private forceMount(id: CardId): boolean {\n return this.pinned.has(id) || this.previews.has(id);\n }\n\n private inWindow(el: Card, 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: Card, 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: CardId; 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: Card): 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: CardId): 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: CardId, view: CardView): 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: CardId, 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: CardId): 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: CardId): 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: CardId, 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: CardId, 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: CardId, 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: CardId): CardView | null {\n return this.views.get(id) ?? null;\n }\n\n isMounted(id: CardId): 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 // The rectangle covering the cards (default: all); undefined when there is none (an empty board, ids that\n // match no card).\n boundsOf(ids?: Iterable<CardId>): Rect | undefined {\n const store = this.store;\n let b = emptyBox();\n let any = false;\n if (store) {\n const list: Iterable<Card | 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 return undefined;\n }\n\n fit(animate = true, pad = 48): void {\n this.cam.requestFit(this.fitTarget(() => this.boundsOf()), 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 // An `undefined` rect (nothing to fit: see `boundsOf`) leaves the camera alone.\n fitRect(r: Rect | undefined | (() => Rect | undefined), 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 none, which leaves the camera alone.\n private fitTarget(r: Rect | undefined | (() => Rect | undefined)): () => Rect | null {\n return () => {\n return (typeof r === 'function' ? r() : r) ?? null;\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 // The zoom range of the camera (see `CameraController.setRange`).\n setScaleRange(min: number, max: number): void {\n this.cam.setRange(min, max);\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 // `RenderGroup.structureDidChange` is Pixi's own flag for that but not a documented one: where a Pixi minor\n // has renamed or dropped it, setting it would just add a stray property, so it is only set when it exists.\n // Otherwise adding and removing a child of the world has the same effect through the public API\n // (`Container.addChild` / `removeChild` mark the render group's structure as changed).\n private rebuildBatches(): void {\n const rg = (this.world as unknown as { renderGroup?: { structureDidChange?: boolean } }).renderGroup;\n if (rg && 'structureDidChange' in rg) {\n rg.structureDidChange = true;\n } else if (!this.world.destroyed) {\n const probe = new Container();\n this.world.addChild(probe);\n this.world.removeChild(probe);\n probe.destroy();\n }\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().debug.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 store: r2(ph.store),\n camera: r2(ph.camera),\n upload: r2(ph.upload),\n overlay: r2(ph.overlay),\n render: r2(ph.render),\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 const cpuMs = performance.now() - t;\n this.renderMs[this.nRender++ & 4095] = cpuMs;\n this.counters.renders++;\n let gpuMs: readonly number[] = NO_GPU;\n if (this.gpu) {\n gpuMs = this.gpu.poll();\n for (const ms of gpuMs) this.gpuMs[this.nGpu++ & 4095] = ms;\n }\n this.emitRender(cpuMs, gpuMs);\n }\n\n // Host code runs here, inside the frame: a throw must not look like a failed render (that rebuilds the\n // textures), so it is counted and reported once, like a hook.\n private emitRender(cpuMs: number, gpuMs: readonly number[]): void {\n const fn = this.onRender;\n if (!fn) return;\n try {\n fn({ cpuMs, gpuMs });\n } catch (e) {\n this.counters.hookErrors++;\n if (this.reportedHooks.has(fn)) return;\n this.reportedHooks.add(fn);\n console.error('[corkboard] a render listener threw (reported once):', e);\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 Card;\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 this.onContextLost?.();\n this.onError?.({ kind: 'context', cause: new Error('WebGL context lost') });\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 this.onContextRestored?.();\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 // The texture manager knows cards by slot; the host knows them by element id.\n private reportTextureError(e: TextureError): void {\n if (this.disposed || !this.onError) return;\n let id: CardId | undefined;\n if (e.slot !== undefined) {\n for (const [eid, slot] of this.slotOf) {\n if (slot === e.slot) {\n id = eid;\n break;\n }\n }\n }\n this.onError({ kind: e.kind, id, url: e.url, cause: e.cause });\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 and the texture pipeline (see `StageStats`). The board adds\n // the embeds and the videos to make its `BoardStats`.\n stats(): StageStats {\n const levels: [number, number, number, number] = [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 s = this.tm.stats;\n const pages = this.tm.pageCount();\n const c = this.counters;\n return {\n cards: this.slotOf.size,\n mounted: this.views.size,\n mountQueue: this.mountQueue.length,\n lost: this.lost,\n scale: r2(this.cam.scale),\n dpr: this.dpr,\n viewport: [this.cam.width, this.cam.height],\n textures: {\n bytes: Math.round(this.tm.totalBytes),\n budget: this.opts.budgetBytes,\n peakBytes: Math.round(s.peakBytes),\n overBudgetMsMax: Math.round(s.overBudgetMsMax),\n levelsMounted: levels,\n pages: { l0: pages.l0, l1: pages.l1 },\n l2: this.tm.l2Count(),\n l3: this.tm.l3Count(),\n retiredPending: this.tm.retiredPending,\n breakdown: 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 evicted: { l1: s.evictedL1, l2: s.evictedL2, l3: s.evictedL3 },\n uploads: s.uploads,\n uploadMsMax: r2(s.uploadMsMax),\n uploadMsAvg: s.uploadFrames ? r2(s.uploadMsTotal / s.uploadFrames) : 0,\n uploadsLastFrame: s.uploadsLastFrame,\n },\n render: {\n frames: c.renders,\n rafCalls: c.rafCalls,\n ticks: c.ticks,\n tickMs: spread(this.tickMs, Math.min(this.nTick, 4096)),\n cpuMs: spread(this.renderMs, Math.min(this.nRender, 4096)),\n gpuMs: this.gpu?.supported ? spread(this.gpuMs, Math.min(this.nGpu, 4096)) : null,\n gpuTimer: this.gpu ? (this.gpu.supported ? 'on' : 'unsupported') : 'off',\n renderErrors: c.renderErrors,\n renderErrorsTotal: this.renderErrorsTotal,\n hookErrors: c.hookErrors,\n firstPaintMs: this.firstPaintMs === null ? null : Math.round(this.firstPaintMs),\n l1CompleteMs: this.l1CompleteMs === null ? null : Math.round(this.l1CompleteMs),\n },\n debug: {\n cullPasses: c.cullPasses,\n requeries: c.requeries,\n lodPasses: c.lodPasses,\n mounts: c.mounts,\n unmounts: c.unmounts,\n slowTicks: [...this.slowTicks],\n requeryMs: {\n search: r2(this.reqMs.search),\n mount: r2(this.reqMs.mount),\n unmount: r2(this.reqMs.unmount),\n lod: r2(this.reqMs.lod),\n },\n lodPassMs: spread(this.lodPassMs, Math.min(this.nLodPass, 1024)),\n worldChildren: this.world.children.length,\n viewPool: this.pools.stats(),\n glRenderer: glRendererString(this.renderer),\n },\n };\n }\n\n dispose(): void {\n this.disposed = true;\n // Every step runs even if an earlier one threw: the texture manager (workers, GPU memory), the Pixi app\n // (the WebGL context) and the ticker hold must always be let go.\n const step = (fn: () => void): void => {\n try {\n fn();\n } catch (err) {\n console.error('[corkboard] stage dispose step failed', err);\n }\n };\n step(() => {\n if (this.raf) cancelAnimationFrame(this.raf);\n });\n step(() => {\n if (this.settleTimer) clearTimeout(this.settleTimer);\n });\n step(() => this.unsub?.());\n for (const f of this.cleanups) step(f);\n step(() => this.ro.disconnect());\n step(() => this.tm.dispose());\n step(() => this.pools.dispose());\n const dots = this.bg.texture;\n step(() => this.app.destroy(true, { children: true, texture: false }));\n // `texture: false` leaves the dot texture to us (it is ours alone, never shared).\n step(() => dots.destroy(true));\n step(() => 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\n// Pixi can hand back a WebGL1 context on old browsers; the texture upload path needs WebGL2.\nfunction isWebGL2(renderer: WebGLRenderer): boolean {\n return typeof WebGL2RenderingContext !== 'undefined' && renderer.gl instanceof WebGL2RenderingContext;\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 { Card } from '../types';\nimport type { Aabb, WorldRect } from './geometry';\nimport { boxOfRect, boxUnion, corners, fromRectLocal, toRectLocal, worldRectOf } from './geometry';\nimport type { CardReader } from './reader';\n\n/** A resize handle of the selection: a corner or an edge. */\nexport type HandleId = 'nw' | 'n' | 'ne' | 'e' | 'se' | 's' | 'sw' | 'w';\n\n/** A resize handle: its id, world position (centre) and mouse cursor. */\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[]): Aabb | null {\n let box: Aabb | null = null;\n for (let i = 0; i < rects.length; i++) {\n const r = rects[i];\n let b: Aabb;\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: CardReader,\n ids: readonly string[],\n zoom: number,\n): SelectionHandles | null {\n const els: Card[] = [];\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// `CardReader`.\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 { Card } from '../types';\nimport type { Aabb } from './geometry';\nimport { pointInRotatedRect } from './geometry';\nimport type { CardReader } from './reader';\n\n/** Options of {@link hitTest}. */\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: Card) => boolean;\n}\n\nconst DEFAULT_TOLERANCE_PX = 4;\nconst candidates: Card[] = [];\nconst searchBox: Aabb = { 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: Card, opts: HitOptions): boolean {\n if (opts.skipLocked && el.locked) return false;\n return opts.filter === undefined || opts.filter(el);\n}\n\nfunction collect(reader: CardReader, wx: number, wy: number, tol: number): Card[] {\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: Card, 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: CardReader,\n wx: number,\n wy: number,\n opts: HitOptions,\n): Card | null {\n const tol = (opts.tolerancePx ?? DEFAULT_TOLERANCE_PX) / safeZoom(opts.zoom);\n const list = collect(reader, wx, wy, tol);\n let best: Card | 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: CardReader,\n wx: number,\n wy: number,\n opts: HitOptions,\n out: Card[] = [],\n): Card[] {\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 `CardReader`.\n//\n// `touch` selects every element whose rotated rect meets the box; `contain` only those wholly inside it.\nimport type { Card } from '../types';\nimport type { Aabb, WorldRect } from './geometry';\nimport {\n boxIntersectsRotatedRect,\n boxUnion,\n elementBox,\n rotatedRectInsideBox,\n worldRectOf,\n} from './geometry';\nimport type { CardReader } from './reader';\n\n/** Options of {@link elementsInBox}. */\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: Card) => boolean;\n}\n\nconst hits: Card[] = [];\nconst scratch: Card[] = [];\n\n/** Ids of the elements selected by dragging `box`, ordered by draw order (bottom first). */\nexport function elementsInBox(\n reader: CardReader,\n box: Aabb,\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/**\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.\n */\nexport function selectionBounds(\n reader: CardReader,\n ids: readonly string[],\n): { box: Aabb; rect: WorldRect | null } | null {\n let box: Aabb | 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 { Aabb } from './geometry';\nimport { DEG } from './geometry';\nimport type { HandleId } from './handles';\nimport { geometryBox, HANDLE_DIRS } from './handles';\nimport type { CardReader } 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: Aabb,\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: Aabb = { 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: CardReader,\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 { Aabb } from './geometry';\n\n/** A card the snapping session compares a moving card against. */\nexport interface SnapCandidate {\n id: string;\n box: Aabb;\n}\n\n/**\n * Screen px: the snap threshold and how far a guide runs past its outermost marker. Callers divide by\n * the zoom.\n */\nexport const SNAP_THRESHOLD_PX = 6;\n/** How far a guide line extends past the cards it joins, screen px. */\nexport const GUIDE_OVERSHOOT_PX = 3;\n/**\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.\n */\nexport const SNAP_RELEASE = 1.5;\nexport const SNAP_SWITCH = 0.5;\n\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.\n */\nexport const SNAP_EPS = 0.01;\n\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.\n */\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/**\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).\n */\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/**\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.\n */\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\n/** Which edges of a card a resize moves. */\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\n/** The alignment lines found along one axis. */\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 equal-gap measures found along one axis. */\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 size-match measures found along one axis. */\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: Aabb): 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/**\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.\n */\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/**\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.\n */\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: Aabb,\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/**\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.\n */\nexport function snapMove(\n index: SnapIndex,\n moving: Aabb,\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/**\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.\n */\nexport function snapResize(\n index: SnapIndex,\n moving: Aabb,\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 { Card } from '../types';\nimport type { Rect } from '../math';\nimport type { Aabb } 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\n/** Snapping while moving and resizing (`CorkboardOptions.snapping`, `board.setSnapping()`). */\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: Card[] = [];\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: Aabb = { 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: Aabb; 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: Aabb): { 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: Aabb, 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, and a\n// dragged card is only drawn on top: `store.lift`); the store is updated once on release, the move and the\n// bring-to-front in one batch, so a gesture is one `change` event. No undo, no history.\nimport { assertGeometry } from '../check';\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 { Box } from '../math';\nimport type { Card, CardId } from '../types';\nimport type { Aabb, 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\n/**\n * Options of the pointer, touch and keyboard layer (`CorkboardOptions.interaction`). Wheel and pinch always pan\n * and zoom.\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 /**\n * Keyboard shortcuts on the focused board.\n * @default true\n */\n keyboard?: boolean;\n /**\n * Dragging, resizing, nudging and Delete write to the store (on release, on each key press) - one `change`\n * event per gesture, `source: 'user'` (default true). With false the layer NEVER writes: it emits `transform`\n * (the proposed rects and, for a drag, the cards to bring to the front) and `delete` (the ids) as proposals and\n * leaves the cards where they are, for a host that owns the state and applies them itself (controlled mode).\n * A card being dragged is still drawn on top until the release.\n */\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 /**\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 */\n keepSelectionOnPan?: boolean;\n /**\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 */\n selectionOutline?: boolean;\n}\n\n/** The events of the interaction layer; the board re-emits them (see `CorkboardEvents`). Points are in world coordinates. */\nexport interface InteractionEvents {\n /** The selection changed: the selected ids now. */\n selection: { ids: readonly CardId[] };\n /** The card under the pointer changed (`null`: none). Touch has no hover. */\n hover: { id: CardId | null };\n /** A click (or tap): the card hit (`null`: the empty canvas), whether Shift was held, and the point in world coordinates. */\n click: { id: CardId | null; shift: boolean; x: number; y: number };\n /** A double click (or double tap): the card hit (`null`: the empty canvas) and the point in world coordinates. */\n dblclick: { id: CardId | null; x: number; y: number };\n /**\n * A drag, resize or arrow-key nudge ended: the new {@link Box} of every card it touched, in world px (already\n * written to the store, in one `change` event, unless `commit` is false: then it is a proposal).\n */\n transform: {\n kind: 'move' | 'resize';\n rects: ReadonlyMap<CardId, Box>;\n /**\n * Set by a pointer drag: the cards it holds, bottom of the draw order first, which a drag brings to the front.\n * Already done when `commit` is on (it is part of the same `change`); with `commit: false` it is the proposal:\n * `board.bringToFront(toFront)`.\n */\n toFront?: readonly CardId[];\n };\n /** A gesture started or ended: its kind, or `null` when it ended. */\n gesture: { kind: 'pan' | 'marquee' | 'drag' | 'resize' | 'pinch' | null };\n /** The pointer device changed between touch and mouse / pen (`touch: true`: touch). */\n touch: { touch: boolean };\n /**\n * Delete was pressed with a selection: the ids (locked cards excluded). With `commit` on they were removed\n * just before this fires; with `commit: false` nothing was, it is a proposal.\n */\n delete: { ids: readonly CardId[] };\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 CardId[];\n additive: boolean;\n }\n | {\n kind: 'press';\n id: CardId;\n x: number;\n y: number;\n shift: boolean;\n wasSelected: boolean;\n }\n | {\n kind: 'drag';\n ids: readonly CardId[];\n start: { x: number; y: number };\n rects: Map<CardId, WorldRect>;\n box: Aabb;\n snap: SnapSession;\n moved: boolean;\n }\n | { kind: 'resize'; session: ResizeSession; snap: SnapSession; handle: HandleId };\n\n/** The pointer, touch and keyboard layer of a board. The board owns one; reach it with `getInternals`. */\nexport class Interaction {\n readonly events = new Emitter<InteractionEvents>();\n selection: readonly CardId[] = [];\n readonly snapping: SnapSettings;\n\n private readonly opts: Required<InteractionOptions>;\n // Options set while a gesture runs, applied at the next pointer down.\n private pendingOpts: Partial<InteractionOptions> | null = null;\n private gesture: Gesture | null = null;\n private readonly pointers = new Map<number, { x: number; y: number }>();\n private pointerType = 'mouse';\n private hoverId: CardId | 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 // `loadSnapshot` replaced the board: what a gesture held (even a card that kept its id) is not what it\n // started from, and releasing would write its position over the loaded one.\n if (e.change.reload) this.cancelGesture();\n this.selDirty = true;\n this.stage.requestFrame();\n }),\n this.stage.onFrame(() => this.onFrame()),\n );\n }\n\n // ── Selection ──────────────────────────────────────────────────────────────\n setSelection(ids: readonly CardId[]): 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 // Changes the options. A running gesture reads them again on release (`commit`, say), so while one is going\n // (or a pointer is down) the change waits for the next pointer down.\n setOptions(o: Partial<InteractionOptions>): void {\n const next = { ...this.pendingOpts };\n for (const k of Object.keys(o) as (keyof InteractionOptions)[]) {\n if (o[k] !== undefined) (next as Record<string, unknown>)[k] = o[k];\n }\n this.pendingOpts = next;\n if (this.gesture === null && this.pointers.size === 0) this.applyOptions();\n }\n\n private applyOptions(): void {\n if (!this.pendingOpts) return;\n Object.assign(this.opts, this.pendingOpts);\n this.pendingOpts = null;\n this.selDirty = true;\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<CardId>): 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: Aabb | null = null;\n for (const r of g.rects.values()) {\n const b = geometryBox([r]) as Aabb;\n box = box ? boxUnion(box, b) : b;\n }\n g.box = box as Aabb;\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: Card[] = [];\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 Aabb;\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 // A two-finger horizontal swipe must never reach the browser's history gesture. The wheel listener\n // below consumes every event it sees; this is the belt: Chromium and Safari read the page root's\n // `overscroll-behavior-x` for swipe-to-navigate (the host is rarely a scroller), and a wheel that lands\n // where the listener cannot (a cross-origin iframe, a control stacked over the board) is covered by it.\n host.style.setProperty('overscroll-behavior', 'none');\n this.cleanups.push(blockHistorySwipe(host.ownerDocument));\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 // A change of options asked for during a gesture lands here, before the next one begins.\n if (this.gesture === null && this.pointers.size === 0) this.applyOptions();\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: Aabb = {\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<CardId, WorldRect>();\n let box: Aabb | null = null;\n for (const id of ids) {\n const el = this.store.get(id) as Card;\n const r = worldRectOf(el);\n rects.set(id, r);\n stage.pin(id, true);\n const b = geometryBox([r]) as Aabb;\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 Aabb, snap, moved: false });\n this.host.style.cursor = 'grabbing';\n // On top while it is held, with no write: the order is committed with the move on release.\n this.store.lift(ids);\n stage.requestFrame();\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: Aabb = {\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: CardId | 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 this.store.lift([]);\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 // `toFront`: the cards a drag brings to the front, written with the move in the same batch.\n private commit(\n kind: 'move' | 'resize',\n ids: readonly CardId[],\n rects: Map<CardId, { x: number; y: number; w: number; h: number }>,\n toFront?: readonly CardId[],\n ): void {\n const stage = this.stage;\n // The lift ends here: with `commit`, the real order takes over in the same synchronous step.\n this.store.lift([]);\n let failure: unknown;\n if (this.opts.commit) {\n try {\n // All or nothing: every rect is checked before the first one is written.\n for (const [id, r] of rects) assertGeometry(`${kind}: card \"${id}\"`, r);\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 }, 'user');\n }\n if (toFront) this.store.bringToFront(toFront, 'user');\n }, 'user');\n } catch (err) {\n failure = err;\n }\n }\n // The gesture ends whatever happened: no preview or pin is left behind.\n for (const id of ids) {\n stage.clearPreview(id);\n stage.pin(id, false);\n }\n if (failure !== undefined) throw failure;\n if (rects.size > 0) {\n this.events.emit('transform', toFront ? { kind, rects, toFront } : { kind, rects });\n }\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<CardId, { 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 // Draw order, bottom first, of the cards that are still there.\n const toFront = [...out.keys()].sort((a, b) => this.store.rank(a) - this.store.rank(b));\n this.commit('move', g.ids, out, toFront);\n }\n\n private commitResize(g: Extract<Gesture, { kind: 'resize' }>): void {\n const out = new Map<CardId, { 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: CardId | 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 Card, worldRectOf(el as Card))\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 // With `commit: false` the host removes the cards itself: it only gets the proposal.\n if (this.opts.commit) this.store.remove(ids, 'user');\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<CardId, { 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 }, 'user');\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.boundsOf(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 // A gesture in progress let go of: the lift, the previews and the pins would outlive this layer.\n this.cancelGesture();\n for (const f of this.cleanups) f();\n this.events.clear();\n }\n}\n\n// Page roots whose `overscroll-behavior-x` is held at `none` by a live board, with the value to restore.\nconst rootHolds = new WeakMap<HTMLElement, { count: number; prev: string }>();\n\n/** Holds `overscroll-behavior-x: none` on the document root (ref-counted across boards); returns the release. */\nfunction blockHistorySwipe(doc: Document): () => void {\n const root = doc.documentElement;\n let hold = rootHolds.get(root);\n if (!hold) {\n hold = { count: 0, prev: root.style.getPropertyValue('overscroll-behavior-x') };\n rootHolds.set(root, hold);\n root.style.setProperty('overscroll-behavior-x', 'none');\n }\n hold.count++;\n const h = hold;\n let released = false;\n return () => {\n if (released) return;\n released = true;\n if (--h.count > 0) return;\n if (h.prev) root.style.setProperty('overscroll-behavior-x', h.prev);\n else root.style.removeProperty('overscroll-behavior-x');\n rootHolds.delete(root);\n };\n}\n","// The way from a board to the parts it is made of, for the `unstable` entry (`getInternals`). The parts are not\n// members of the `Corkboard` type: the board registers them here when it is built, and only this module's\n// readers can find them.\nimport type { Corkboard } from './Corkboard';\nimport type { EmbedLayer } from './embed/layer';\nimport type { Interaction } from './interact/controller';\nimport type { Stage } from './render/stage';\nimport type { Store } from './store';\nimport type { VideoLayer } from './video/layer';\n\n/** The parts a board is made of, as returned by {@link getInternals}. */\nexport interface BoardInternals {\n stage: Stage;\n store: Store;\n // null when the board was made with `interaction: false`.\n interaction: Interaction | null;\n embeds: EmbedLayer;\n video: VideoLayer;\n // The div that covers the canvas, for the DOM overlays (see `addOverlay`).\n overlayRoot: HTMLElement;\n // Whether `dispose()` ran.\n isDisposed(): boolean;\n // Registers a teardown step that `dispose()` runs; returns the function that unregisters it.\n onDispose(fn: () => void): () => void;\n}\n\nconst registry = new WeakMap<Corkboard, BoardInternals>();\n\nexport function registerInternals(board: Corkboard, parts: BoardInternals): void {\n registry.set(board, parts);\n}\n\n/**\n * The stage, store, interaction layer, embed layer and video layer of a board. No stability promise: see\n * `@niccolofanton/corkboard/unstable`. Works on a disposed board too (the parts are then torn down).\n */\nexport function getInternals(board: Corkboard): BoardInternals {\n const parts = registry.get(board);\n if (!parts) throw new TypeError('getInternals: not a Corkboard');\n return parts;\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\n/** Width, world px, assumed for a card with no usable size when placing. */\nexport const PLACEMENT_FALLBACK_WIDTH: number = DEFAULTS.cardWidth;\n/** Height / width assumed for a card with no usable aspect when placing. */\nexport const PLACEMENT_FALLBACK_ASPECT: number = DEFAULTS.cardAspect;\n\n/** A card as the pure layout functions see it: id, size and aspect. */\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\n/** A rectangle a layout function placed a card at, world px. */\nexport interface LayoutRect {\n x: number;\n y: number;\n w: number;\n h: number;\n}\n\n/** What {@link masonry} returns: a rect per card and the block's size. */\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\n/** The height / width a layout uses for a card: its aspect if it is usable, else a default. */\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/**\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`.\n */\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/**\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.\n */\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 Aabb } 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/**\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.\n */\nexport function bandOrder<T extends { id: string; box: Aabb }>(\n items: readonly T[],\n axis: 'x' | 'y' = 'y',\n): T[] {\n const along = axis === 'y' ? boxCy : boxCx;\n const across = (b: Aabb): 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 { Aabb } 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/**\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.\n */\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/**\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.\n */\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\n/** Input of {@link planPlacement}: the new cards and the room around them. */\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\n/** What {@link planPlacement} returns: where the new cards go. */\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: Aabb;\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/**\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].\n */\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 Aabb } from '../interact/geometry';\nimport { PLACEMENT_FALLBACK_WIDTH } from './masonry';\nimport { bandOrder } from './order';\nimport { placementGap } from './placement';\nimport { median } from './stats';\n\n/**\n * Which edge or centre cards line up on: the left / right edge, the vertical centre line (`'centerX'`), the top /\n * bottom edge, or the horizontal centre line (`'middleY'`). Measured on the cards' world bounding boxes (rotation included).\n */\nexport type AlignMode = 'left' | 'centerX' | 'right' | 'top' | 'middleY' | 'bottom';\n\n/** A move: `dx`, `dy` in world px. */\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\n/** Options of the align and distribute functions. */\nexport interface ArrangeGapOptions {\n // The room kept between boxes that would otherwise touch or overlap. Absent: no overlap handling.\n gap?: number;\n}\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).\n */\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: Aabb, d: Delta | undefined): Aabb =>\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/**\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.\n */\nexport function separate(\n items: readonly { id: string; box: Aabb }[],\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: Aabb[] = [];\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/**\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).\n */\nexport function align(\n items: readonly { id: string; box: Aabb }[],\n mode: AlignMode,\n opts: ArrangeGapOptions = {},\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/**\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.\n */\nexport function distribute(\n items: readonly { id: string; box: Aabb }[],\n axis: 'x' | 'y',\n opts: ArrangeGapOptions = {},\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: Aabb): number => (horizontal ? b.minX : b.minY);\n const hi = (b: Aabb): number => (horizontal ? b.maxX : b.maxY);\n const size = (b: Aabb): number => (horizontal ? boxW(b) : boxH(b));\n const centre = (b: Aabb): 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/**\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.\n */\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 Aabb } 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: Aabb,\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/**\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.\n */\nexport function autoSpotArea(\n block: { w: number; h: number },\n viewport: Aabb,\n opts: { step?: number; maxRadiusFactor?: number } = {},\n): Aabb {\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/**\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.\n */\nexport function autoSpot(\n block: { w: number; h: number },\n viewport: Aabb,\n occupied: readonly Aabb[],\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 Aabb[],\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/**\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.\n */\nexport function shouldPanTo(block: Aabb, viewport: Aabb): 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 Aabb } from '../interact/geometry';\nimport type { Box } from '../math';\nimport { effectiveAspect, masonry, slotWidth, type LayoutItem } from './masonry';\nimport { bandOrder } from './order';\nimport { placementGap } from './placement';\nimport { clamp, median } from './stats';\n\n/** A card as {@link tidy} sees it: id, box and aspect. */\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: Aabb;\n // Card size (what the grid places).\n w: number;\n h: number;\n}\n\n/** What {@link tidy} returns: the new rect of every card. */\nexport interface TidyResult {\n // New {@link Box} of every participating item, in world px.\n moves: Map<string, Box>;\n count: number;\n bounds: Aabb;\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\n/** Reorders cards into a masonry grid in reading order, anchored at their current top-left. Pure. */\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","// The draw order as anchors: how a `Change` describes a reorder (`orderMoves`) and how `applyChange` replays\n// one (`placeMoves`). Pure functions over id lists.\nimport type { CardId, OrderMove } from '../types';\n\n// Marks the members of one longest strictly increasing subsequence of `seq` (distinct numbers), O(n log n).\nfunction lisMask(seq: readonly number[]): Uint8Array {\n const n = seq.length;\n const mask = new Uint8Array(n);\n const tails: number[] = []; // tails[k]: index in seq of the smallest tail of an increasing run of length k + 1\n const parent = new Int32Array(n).fill(-1);\n for (let i = 0; i < n; i++) {\n let lo = 0;\n let hi = tails.length;\n while (lo < hi) {\n const mid = (lo + hi) >> 1;\n if (seq[tails[mid]] < seq[i]) lo = mid + 1;\n else hi = mid;\n }\n if (lo > 0) parent[i] = tails[lo - 1];\n tails[lo] = i;\n }\n for (let k = tails.length > 0 ? tails[tails.length - 1] : -1; k >= 0; k = parent[k]) mask[k] = 1;\n return mask;\n}\n\n/**\n * The `order.moved` of a change: the cards to take out and put back to turn `prev` into `next`.\n *\n * `added` are the new cards in the order a replay appends them (they sit on top of the survivors, in this\n * order, before the moves are applied). Without `hint` the moved set is every survivor outside the longest\n * increasing subsequence of old ranks taken in the new order (a card is not moved if it kept its place among\n * the others), every added card that is not where an append puts it, and every removed card. With `hint` (the\n * ids of a `bringToFront` / `sendToBack`; valid only when nothing was added or removed) it is just those.\n * `undefined`: nothing to replay (the order is unchanged, or only grew by the appended cards).\n */\nexport function orderMoves(\n prev: readonly CardId[],\n next: readonly CardId[],\n added: readonly CardId[],\n hint: ReadonlySet<CardId> | null,\n): OrderMove[] | undefined {\n const np = prev.length;\n // Unchanged, or a pure append of the added cards in their replay order.\n if (next.length === np + added.length) {\n let same = true;\n for (let i = 0; same && i < np; i++) same = next[i] === prev[i];\n for (let i = 0; same && i < added.length; i++) same = next[np + i] === added[i];\n if (same) return undefined;\n }\n const prevIdx = new Map<CardId, number>();\n for (let i = 0; i < np; i++) prevIdx.set(prev[i], i);\n const nextSet = new Set(next);\n const out: OrderMove[] = [];\n const below = (list: readonly CardId[], i: number): CardId | null => (i > 0 ? list[i - 1] : null);\n\n let skip: Uint8Array | null = null;\n if (hint === null) {\n const addedIdx = new Map<CardId, number>();\n added.forEach((id, i) => addedIdx.set(id, i));\n const seq = new Array<number>(next.length);\n for (let i = 0; i < next.length; i++) {\n const id = next[i];\n seq[i] = prevIdx.get(id) ?? np + (addedIdx.get(id) ?? added.length);\n }\n skip = lisMask(seq);\n }\n for (let i = 0; i < next.length; i++) {\n const id = next[i];\n if (skip ? skip[i] === 1 : !hint?.has(id)) continue;\n const pi = prevIdx.get(id);\n out.push({ id, prevBelow: pi === undefined ? null : below(prev, pi), nextBelow: below(next, i) });\n }\n for (let i = 0; i < np; i++) {\n if (!nextSet.has(prev[i])) out.push({ id: prev[i], prevBelow: below(prev, i), nextBelow: null });\n }\n return out.length > 0 ? out : undefined;\n}\n\n/**\n * Applies `moves` to the order `cur`: each card is placed directly above its `nextBelow` (`null`: at the\n * bottom), bottom of the result first. An entry whose card or anchor is not in `cur` is skipped (the card keeps\n * its place). Returns the new order, or `undefined` when nothing moves (or the anchors are malformed: a cycle).\n */\nexport function placeMoves(cur: readonly CardId[], moves: readonly OrderMove[]): CardId[] | undefined {\n const present = new Set(cur);\n // The last entry of a card wins; an entry anchored to a card that is absent, or to itself, is skipped.\n const byId = new Map<CardId, OrderMove>();\n for (const m of moves) {\n if (!present.has(m.id)) continue;\n if (m.nextBelow !== null && (m.nextBelow === m.id || !present.has(m.nextBelow))) continue;\n byId.set(m.id, m);\n }\n if (byId.size === 0) return undefined;\n const above = new Map<CardId | null, CardId[]>();\n for (const m of byId.values()) {\n const list = above.get(m.nextBelow);\n if (list) list.push(m.id);\n else above.set(m.nextBelow, [m.id]);\n }\n const out: CardId[] = [];\n // Emits what is placed directly above `anchor`, and what is placed above those, without recursion.\n const emitAbove = (anchor: CardId | null): void => {\n const stack = (above.get(anchor) ?? []).slice().reverse();\n while (stack.length > 0) {\n const id = stack.pop() as CardId;\n out.push(id);\n const kids = above.get(id);\n if (kids) for (let i = kids.length - 1; i >= 0; i--) stack.push(kids[i]);\n }\n };\n emitAbove(null);\n for (const id of cur) {\n if (byId.has(id)) continue;\n out.push(id);\n emitAbove(id);\n }\n if (out.length !== cur.length) return undefined;\n for (let i = 0; i < out.length; i++) if (out[i] !== cur[i]) return out;\n return undefined;\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 { Aabb } from '../interact/geometry';\nimport { elementBox } from '../interact/geometry';\nimport { assertGeometry } from '../check';\nimport { CorkboardError } from '../errors';\nimport { reportListenerError } from '../events';\nimport type {\n Change,\n ChangeSource,\n Card,\n CardId,\n CardPatch,\n CardProp,\n CardUpdate,\n OrderMove,\n} from '../types';\nimport { orderMoves, placeMoves } from './order';\n\nexport type { ChangeSource };\n\n/**\n * What changed in one store batch, as a net diff per card id: `added`, `removed` and `updated` never share an id.\n * Cards are the store's own objects: do not mutate them. This is the public {@link Change} plus `reload`.\n */\nexport interface ChangeSet extends Change {\n source: ChangeSource;\n added: Card[];\n removed: Card[];\n // The element after the change, before it, and the names of the fields that changed.\n updated: CardUpdate[];\n // `loadSnapshot` ran in this batch: the stage rebuilds from the store instead of walking the diff.\n reload?: boolean;\n}\n\n/** An event of the store: `change` (a {@link ChangeSet}) or one of its others. */\nexport type StoreEvent = { type: 'change'; change: ChangeSet };\n\ninterface Entry extends Aabb {\n el: Card;\n}\n\nconst GEOMETRY: readonly string[] = ['x', 'y', 'w', 'h', 'rot'];\n// The fields `update` can change, and the ones a change set compares (everything but the id).\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\n/** The cards of a board: id lookup, draw order, a spatial index, change events and batches. The board owns one; reach it with `getInternals`. */\nexport class Store {\n private readonly map = new Map<CardId, Card>();\n private readonly tree = new RBush<Entry>();\n private readonly entries = new Map<CardId, Entry>();\n // Draw order, bottom first, and each id's index in it (rebuilt lazily after a removal or a reorder).\n // A removal does not shrink `_order` at once (that would cost O(board) per call): it records the id in `dead`,\n // and the next read of `order` drops them all in one pass.\n private _order: CardId[] = [];\n private readonly dead = new Set<CardId>();\n private ranks = new Map<CardId, 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 depth = 0;\n // The batch in progress. Writes are applied at once; what is reported is computed when the outermost batch\n // ends, from the state the batch started in (`touched`) and the state it ends in: a net diff per id.\n // touched id -> the card as it was before the batch's first write to it (undefined: it was not there)\n // batchSource / source / sawLoad see `note`\n // orderLen0 / orderPrev the draw order before the batch: appends only grow the tail, so the first\n // `orderLen0` ids are the old order until the first write that is not an append copies them\n private touched = new Map<CardId, Card | undefined>();\n private batchSource: ChangeSource | undefined;\n private source: ChangeSource | undefined;\n private sawLoad = false;\n private reloaded = false;\n private orderLen0 = -1;\n private orderPrev: CardId[] | null = null;\n // orderHint the ids given to bringToFront / sendToBack in the batch, while that is all that reordered\n // (null: nothing yet); orderHintBad: something else reordered, so the moves are computed\n private orderHint: Set<CardId> | null = null;\n private orderHintBad = false;\n // Cards drawn above the rest while a gesture holds them (see `lift`): render and hit order only.\n private liftRank = new Map<CardId, number>();\n // Change sets go to the listeners one at a time, in the order they were made. A write made by a listener\n // while one is being dispatched queues its change set behind the current one: nobody sees it first.\n private dispatching = false;\n private readonly queue: StoreEvent[] = [];\n\n private get order(): CardId[] {\n if (this.dead.size > 0) this.compact();\n return this._order;\n }\n\n private set order(v: CardId[]) {\n this._order = v;\n this.dead.clear();\n }\n\n private compact(): void {\n const dead = this.dead;\n this._order = this._order.filter((i) => !dead.has(i));\n dead.clear();\n }\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: CardId): Card | undefined {\n return this.map.get(id);\n }\n\n has(id: CardId): boolean {\n return this.map.has(id);\n }\n\n elements(): IterableIterator<Card> {\n return this.map.values();\n }\n\n // The ids in draw order, bottom first.\n ids(): readonly CardId[] {\n return this.order;\n }\n\n rank(id: CardId): number {\n const lifted = this.liftRank.get(id);\n if (lifted !== undefined) return lifted;\n if (this.ranksDirty) this.rebuildRanks();\n return this.ranks.get(id) ?? -1;\n }\n\n // Draws the given cards above all the others (keeping their relative order) until `lift([])`: what a drag does\n // so the card it holds is on top without a write. Only `rank()` (so drawing and hit testing) sees it: the\n // draw order, the snapshot and the change events do not. Replaces the previous lift. Ids not on the board are\n // ignored.\n lift(ids: readonly CardId[]): void {\n const held = ids.filter((id) => this.map.has(id));\n if (held.length === 0 && this.liftRank.size === 0) return;\n held.sort((a, b) => this.baseRank(a) - this.baseRank(b));\n this.liftRank = new Map(held.map((id, i) => [id, this.map.size + i]));\n this.orderVersion++;\n }\n\n // The held cards stay above every other, in the same relative order: ranks from the current length.\n private relift(): void {\n if (this.liftRank.size === 0) return;\n this.liftRank = new Map([...this.liftRank.keys()].map((id, i) => [id, this.map.size + i]));\n this.orderVersion++;\n }\n\n private baseRank(id: CardId): 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: Aabb, out: Card[]): Card[] {\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 // `source` is who made the write ('api' when omitted). A `batch` that names a source overrides it.\n add(els: readonly Card[], source?: ChangeSource): void {\n if (els.length === 0) return;\n // All or nothing: a duplicate anywhere in the batch (against the store or inside it) rejects the lot\n // before the first card goes in.\n const ids = new Set<CardId>();\n for (const el of els) {\n if (this.map.has(el.id) || ids.has(el.id)) {\n throw new CorkboardError('invalid', `duplicate element id \"${el.id}\"`);\n }\n ids.add(el.id);\n // Every write path ends here: a card with a NaN or a zero size never gets in, whoever made it.\n assertGeometry(`add: card \"${el.id}\"`, el);\n }\n this.batch(() => {\n this.note(source);\n this.markOrder(true);\n for (const el of els) {\n this.touch(el.id);\n this.map.set(el.id, el);\n // An id removed earlier in this batch is still in the order until it is compacted: do that first.\n if (this.dead.has(el.id)) this.compact();\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 }\n // A card added while others are held draws below them.\n this.relift();\n });\n }\n\n // Applies `patch` to an element. Returns the names of the properties that changed ([] when none). A field\n // left out of the patch, or `undefined`, is kept - except `data`, which an own `undefined` clears.\n update(id: CardId, patch: CardPatch, source?: ChangeSource): CardProp[] {\n const prev = this.map.get(id);\n if (!prev) return [];\n const props: CardProp[] = [];\n const next: Card = { ...prev };\n const rec = patch as Record<string, unknown>;\n for (const k of PATCHABLE) {\n // An own `data: undefined` clears the field; for every other field `undefined` means \"leave it\".\n if (!(k in rec) || (rec[k] === undefined && k !== 'data')) 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 // Layout, gestures, resizes and `applyChange` all write geometry through here: refuse a NaN / Infinity\n // position or a size <= 0 before anything changes.\n if (props.some((p) => GEOMETRY.includes(p))) assertGeometry(`update: card \"${id}\"`, next);\n this.batch(() => {\n this.note(source);\n this.touch(id);\n this.map.set(id, next);\n if (props.some((p) => GEOMETRY.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 });\n return props;\n }\n\n remove(ids: readonly CardId[], source?: ChangeSource): Card[] {\n const gone: Card[] = [];\n this.batch(() => {\n for (const id of ids) {\n const el = this.map.get(id);\n if (!el) continue;\n if (gone.length === 0) {\n this.note(source);\n this.markOrder(false);\n }\n this.touch(id);\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 }\n if (gone.length > 0) {\n for (const g of gone) this.dead.add(g.id);\n if (this.liftRank.size > 0) {\n const held = [...this.liftRank.keys()].filter((i) => this.map.has(i));\n this.liftRank = new Map(held.map((id, i) => [id, this.map.size + i]));\n }\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). Unknown ids are ignored.\n bringToFront(ids: readonly CardId[], source?: ChangeSource): void {\n const set = new Set(ids.filter((i) => this.map.has(i)));\n if (set.size === 0) return;\n this.reorder(this.order.filter((i) => !set.has(i)).concat(this.order.filter((i) => set.has(i))), source, set);\n }\n\n // Moves the ids to the bottom of the draw order (keeping their relative order). Unknown ids are ignored.\n sendToBack(ids: readonly CardId[], source?: ChangeSource): void {\n const set = new Set(ids.filter((i) => this.map.has(i)));\n if (set.size === 0) return;\n this.reorder(this.order.filter((i) => set.has(i)).concat(this.order.filter((i) => !set.has(i))), source, set);\n }\n\n // Sets the draw order. `ids` must be every id on the board exactly once.\n setOrder(ids: readonly CardId[], source?: ChangeSource): void {\n const seen = new Set<CardId>();\n for (const id of ids) {\n if (!this.map.has(id)) throw new CorkboardError('invalid', `setOrder: no card \"${id}\"`);\n if (seen.has(id)) throw new CorkboardError('invalid', `setOrder: duplicate id \"${id}\"`);\n seen.add(id);\n }\n if (ids.length !== this.map.size) {\n throw new CorkboardError(\n 'invalid',\n `setOrder: expected all ${this.map.size} ids, got ${ids.length}`,\n );\n }\n this.reorder([...ids], source);\n }\n\n // Replays an `order.moved`: each card goes directly above its `nextBelow` (see `placeMoves`). Entries naming a\n // card that is not here are skipped.\n applyOrderMoves(moves: readonly OrderMove[], source?: ChangeSource): void {\n const next = placeMoves(this.order, moves);\n if (next) this.reorder(next, source);\n }\n\n // Empties the store.\n clear(source?: ChangeSource): void {\n if (this.map.size === 0) return;\n this.batch(() => {\n this.note(source);\n this.markOrder(false);\n for (const id of this.map.keys()) this.touch(id);\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.liftRank.clear();\n this.orderVersion++;\n });\n }\n\n // Swaps the whole content (`loadSnapshot`) in one step. The change set is the net diff like any other, and\n // carries `reload: true` so the stage rebuilds from the store instead of walking it.\n replaceAll(els: readonly Card[]): void {\n const ids = new Set<CardId>();\n for (const el of els) {\n if (ids.has(el.id)) throw new CorkboardError('invalid', `duplicate element id \"${el.id}\"`);\n ids.add(el.id);\n }\n this.batch(() => {\n this.reloaded = true;\n this.clear('load');\n this.add(els, 'load');\n // An empty snapshot over an empty board: nothing wrote, so nothing noted 'load'.\n this.note('load');\n }, 'load');\n }\n\n // Groups every change made inside `fn` into one event. `source` names who made them; with nested batches\n // the outermost one that names a source wins, and 'load' wins over any. If `fn` throws, the event for what\n // it did is still emitted (listeners cannot throw out of it) and `fn`'s error is the one rethrown.\n batch(fn: () => void, source?: ChangeSource): void {\n this.depth++;\n if (source !== undefined && this.batchSource === undefined) this.batchSource = source;\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: Card): Entry {\n const b = elementBox(el);\n return { minX: b.minX, minY: b.minY, maxX: b.maxX, maxY: b.maxY, el };\n }\n\n // Remembers who wrote: the batch's source if it named one, else the first writer's.\n private note(source: ChangeSource | undefined): void {\n if (source === 'load') this.sawLoad = true;\n this.source ??= this.batchSource ?? source ?? 'api';\n }\n\n // Remembers a card as it was, before the batch's first write to it. Call it before the write.\n private touch(id: CardId): void {\n if (!this.touched.has(id)) this.touched.set(id, this.map.get(id));\n }\n\n // Remembers the draw order as it was, before the batch's first write to it. `append`: the write only adds\n // ids at the end (so the old order is still the head of the new one).\n private markOrder(append: boolean, hint?: ReadonlySet<CardId>): void {\n if (this.orderLen0 < 0) this.orderLen0 = this._order.length;\n if (append) return;\n if (this.orderPrev === null) this.orderPrev = this.order.slice(0, this.orderLen0);\n if (hint && !this.orderHintBad) {\n this.orderHint ??= new Set();\n for (const id of hint) this.orderHint.add(id);\n } else {\n this.orderHintBad = true;\n }\n }\n\n private reorder(next: CardId[], source: ChangeSource | undefined, hint?: ReadonlySet<CardId>): void {\n const cur = this.order;\n if (next.length === cur.length && next.every((id, i) => id === cur[i])) return;\n this.batch(() => {\n this.note(source);\n this.markOrder(false, hint);\n this.order = next;\n this.ranksDirty = true;\n this.orderVersion++;\n });\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 // Turns the batch into one net change set and hands it to the listeners. A listener that throws is\n // reported and skipped: the others, and the state they keep in step with the store, are not affected.\n private flush(): void {\n if (this.dead.size > 0) this.compact();\n const { touched, orderPrev, orderHint, orderHintBad } = this;\n const source = this.sawLoad ? 'load' : (this.source ?? this.batchSource ?? 'api');\n const reload = this.reloaded;\n this.touched = new Map();\n this.batchSource = this.source = undefined;\n this.sawLoad = this.reloaded = false;\n this.orderLen0 = -1;\n this.orderPrev = null;\n this.orderHint = null;\n this.orderHintBad = false;\n if (touched.size === 0 && orderPrev === null) return;\n\n const added: Card[] = [];\n const removed: Card[] = [];\n const updated: CardUpdate[] = [];\n for (const [id, before] of touched) {\n const after = this.map.get(id);\n if (before === undefined) {\n if (after) added.push(after);\n } else if (!after) {\n removed.push(before);\n } else if (after !== before) {\n const props = PATCHABLE.filter((k) => !Object.is(before[k], after[k]));\n if (props.length > 0) updated.push({ el: after, prev: before, props });\n }\n }\n const c: ChangeSet = { source, added, removed, updated };\n if (orderPrev !== null) {\n // Given ids are enough when the batch only brought cards to the front / sent them back; anything else\n // (an add, a removal, a setOrder) needs the minimal set.\n const hint = !orderHintBad && added.length === 0 && removed.length === 0 ? orderHint : null;\n const moved = orderMoves(orderPrev, this.order, added.map((el) => el.id), hint);\n if (moved) c.order = { moved };\n }\n if (added.length === 0 && removed.length === 0 && updated.length === 0 && !c.order) return;\n if (reload) c.reload = true;\n this.queue.push({ type: 'change', change: c });\n if (this.dispatching) return;\n this.dispatching = true;\n try {\n for (let i = 0; i < this.queue.length; i++) {\n const e = this.queue[i];\n for (const l of [...this.listeners]) {\n try {\n l(e);\n } catch (err) {\n reportListenerError('change listener', err);\n }\n }\n }\n } finally {\n this.queue.length = 0;\n this.dispatching = false;\n }\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\nimport { acquireStyle } from '../styles';\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\nconst SHEET = {\n selector: `style[${STYLE_ATTR}]`,\n mark: (el: HTMLStyleElement): void => el.setAttribute(STYLE_ATTR, ''),\n css: CSS,\n};\n\n// Puts the stylesheet in the document's <head> (one for all its users, reference-counted) and returns the\n// function that lets go of it: the last one out removes it. A caller that never calls it keeps the style\n// for the life of the document. `nonce` is for a CSP with a nonce-based `style-src`.\nexport function injectRevealStyles(doc: Document = document, nonce?: string): () => void {\n return acquireStyle(doc, SHEET, nonce);\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 // `nonce` of the injected <style> (a CSP with a nonce-based `style-src`).\n nonce?: string;\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 const releaseStyles = injectRevealStyles(v.ownerDocument, opts.nonce);\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 releaseStyles();\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 return buildRevealSpinner(doc);\n}\n\n// The same, without touching the stylesheet: for a caller that already holds it.\nexport function buildRevealSpinner(doc: Document): HTMLElement {\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 { Box, Camera } from '../math';\nimport {\n attachVideoReveal,\n buildRevealSpinner,\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 // The card's {@link Box}, in world px.\n box: Box;\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 // `nonce` of the injected <style> (a CSP with a nonce-based `style-src`).\n nonce?: string;\n // The file of the current card failed to load (the element's `error` event).\n onError?: (target: { id: string; src: string }, cause: unknown) => void;\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 = buildRevealSpinner(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, nonce: opts.nonce });\n const onError = opts.onError;\n if (onError) {\n v.addEventListener('error', (e) => {\n // The error of a source we dropped (teardown) is not the card's.\n const t = this.target;\n if (!t || this.disposed || v.getAttribute('src') !== t.src) return;\n onError({ id: t.id, src: t.src }, v.error ?? e);\n });\n }\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 // `nonce` of the <style> the videos inject (a CSP with a nonce-based `style-src`).\n nonce?: string;\n // A card's file failed to load.\n onError?: (target: { id: string; src: string }, cause: unknown) => void;\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 nonce: this.deps.nonce,\n onError: this.deps.onError,\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 { BoardErrorEvent } from '../errors';\nimport type { Store } from '../store';\nimport type { FrameRateMonitor } from '../render/frameRate';\nimport type { Stage } from '../render/stage';\nimport type { CardId } from '../types';\nimport { AmbientVideos } from './ambient';\nimport type { AmbientCandidate } from './ambientPolicy';\nimport { VideoOverlay, type VideoTarget } from './video';\nimport { VideoController } from './videoController';\n\n/**\n * How videos play. `'always'`: every video card in view plays on its own, muted and looping (a pool, limited by\n * `maxPlaying`); hover and selection still play a card with sound when `muted` is false. `'hover'`: a hovered card plays\n * after a short delay, a single selected card plays at once. `'off'`: nothing plays, video cards are their poster.\n */\nexport type VideoMode = 'always' | 'hover' | 'off';\n\n/** Options of the video layer (`CorkboardOptions.video`, `board.video.setOptions()`). A card plays only while it is on screen and the camera is still. */\nexport interface VideoOptions {\n /**\n * How videos play.\n * @default 'always'\n */\n mode?: VideoMode;\n /**\n * Loop the videos.\n * @default true\n */\n loop?: boolean;\n /**\n * Mute the videos. Only a hovered / selected card can play with sound, and only in a page that has had a user gesture (autoplay policy).\n * @default true\n */\n muted?: boolean;\n /**\n * `mode: 'always'`: a card plays on its own only if its long side is at least this many CSS px on screen. Smaller ones stay a thumbnail.\n * @default 160\n */\n minPlayPx?: number;\n /**\n * `mode: 'always'`: at most this many cards play at once on a mouse / pen device. The biggest and most central cards win.\n * @default 8\n */\n maxPlaying?: number;\n /**\n * `mode: 'always'`: at most this many cards play at once on a touch device.\n * @default 2\n */\n maxPlayingTouch?: number;\n}\n\n/** What the video layer is given by the board. */\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 // `nonce` of the injected <style> (a CSP with a nonce-based `style-src`).\n nonce?: string;\n // A <video> that would not load (once per card and file).\n onError?: (e: BoardErrorEvent) => void;\n}\n\n/** Plays the videos of the video cards: the hover / selection overlay and the always-playing pool. The board owns one; reach it with `getInternals`. */\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, onError, nonce } = deps;\n this.store = store;\n this.stage = stage;\n // The hover overlay and the pool can both fail on the same file: the host hears of a card + file once.\n const reported = new Set<string>();\n const fail =\n onError &&\n ((t: { id: string; src: string }, cause: unknown): void => {\n const tag = `${t.id}|${t.src}`;\n if (reported.has(tag)) return;\n reported.add(tag);\n onError({ kind: 'video', id: t.id, url: t.src, cause });\n });\n this.overlay = new VideoOverlay(root, { nonce, onError: fail });\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 nonce,\n onError: fail,\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<CardId> {\n const ids = new Set<CardId>(this.ambient.playingIds);\n const active = this.overlay.activeId;\n if (active !== null) ids.add(active);\n return ids;\n }\n\n // Whether `setPaused(true)` is in effect.\n get isPaused(): boolean {\n return this.paused;\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: CardId | null): void {\n this.controller.setHover(id);\n }\n\n setSelection(ids: readonly CardId[]): 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: CardId, 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: CardId): 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"],"names":["DEG","emptyBox","boxW","b","boxH","boxCx","boxCy","boxUnion","a","boxOfRect","r","worldRectOf","el","rotatedExtent","w","h","rotDeg","c","s","elementBox","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","baseResolved","embed","parsed","parseEmbedUrl","PROVIDER_LABEL","finitePositive","mergeResolved","base","info","out","src","normalizeEmbedUrl","canGoLive","sameEmbed","EMBED_CB","SNAPSHOT_MAX_SIDE","SNAPSHOT_MS","SOURCE","SNIPPET_BOOTSTRAP","PREVIEW_CACHE_NAME","LEGACY_CACHE_NAME","PREVIEW_MEMORY_MAX","PREVIEW_PERSIST_MAX","hashString","previewMaterial","html","bucket","previewKey","sha256Hex","subtle","digest","hex","hasSubtle","clearPreviewCache","name","names","n","PreviewStore","mode","m","key","material","urlOf","cache","keys","excess","SANDBOX_PROVIDER","SANDBOX_ARBITRARY","SANDBOX_SNIPPET","SNIPPET_CSP","SNIPPET_CSP_NONE","snippetCsp","network","REFERRER_POLICY","MEDIA_ALLOW","ALLOW","snippetDocument","originOf","u","IPV4","HOSTNAME","SCHEME","isIpHost","host","invalidHost","entry","why","CorkboardError","normalizeIsolatedHost","raw","rest","isUrl","normalizeIsolatedHosts","entries","hostIsolated","hosts","list","iframeSpecFor","source","title","provider","providerOfIframeSrc","allowlisted","sandbox","allow","hostHue","GLYPH","tileSpec","glyph","pathOf","TILE_WIDTH","TILE_MAX_HEIGHT","tileSize","aspect","wrap","ctx","text","maxW","maxLines","words","lines","line","next","last","drawGlyph","g","color","FONT","paintTile","spec","theme","dark","hsl","fg","dim","pad","labelPx","titlePx","gap","groupH","cssHex","drawTile","resolve","registry","acquireStyle","sheet","nonce","perDoc","map","style","released","NAV_STRIKES","NAV_STRIKE_MS","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","SHEET","DONE_MARGIN","FLY_PAD","FLY_IN_SCALE","REVOKE_DELAY_MS","overlaps","normMinLive","EmbedLayer","options","svg","rasterizeSvg","normBudget","normWorkers","t","onDown","onKeyDoc","onKeyHost","onMessage","isolated","sandboxChanged","autoplayChanged","isolatedChanged","sameList","networkChanged","before","workers","ids","touch","camChanged","view","seen","cur","prev","dt","zoom","retitled","stale","withJsApi","withAutoplay","token","alive","answer","resolver","withTimeout","err","hostPoster","photo","candidate","kind","real","mx","my","cam","grown","visW","visH","force","free","settled","rank","tier","wrapper","iframe","frame","spin","now","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","validSvg","draw","done","tries","rect","hit","best","bestRank","busy","j","on","go","studio","old","ifr","drawn","keyboard","flown","SNAPSHOT_MAX_SVG","img","ms","reject","reportListenerError","what","Emitter","type","set","payload","bad","where","show","isObject","finite","field","positive","nonNegative","boolean","integer","min","limit","oneOf","allowed","record","assertGeometry","idList","optional","assertRect","clamp","lo","hi","zoomAt","ZOOM_PER_PX","MAX_ZOOM_DELTA_PX","wheelZoomFactor","deltaY","deltaMode","visibleWorldRect","FRICTION","STOP_SPEED","CameraController","wake","bounds","MIN_SCALE","MAX_SCALE","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","start","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","guideColor","TextStyle","guides","changed","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","cellsPerRow","cellsPerPage","Atlas","createPage","destroyPage","st","index","reused","col","row","cell","planEviction","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","hasPrivateUpload","sys","warnedPublicUpload","absoluteUrl","card","zeros","clearBuffer","bytes","isOwn","TextureManager","renderer","opts","DecodeWorker","wi","cause","req","pinned","pinnedN","l2","l3","lv","desired","ct","needsOwn","items","wanted","resident","need2","failed","existing","maxLong","cap","reason","tag","budgetMs","t0","destroySource","atlas","bitmap","ImageSource","Texture","Rectangle","moved","border","size","mips","TextureSource","gl","glTex","restorePremultiply","zero","own","perCell","l1","oldTextures","old0","old1","MediaView","Sprite","_props","tex","parseHex","VIEW_DEFINITIONS","ViewPools","def","pool","pooled","definitionOf","LOD_INTERVAL_MS","SETTLE_MS","GRID","VIEW_MARGIN","MOUNT_BUDGET_MS","BAKE_CORNER_SLACK","BAKE_ASPECT_SLACK","r2","spread","NO_GPU","sameBytes","decodeBase64","bin","scaleBounds","Stage","app","unparkTicker","DARK_THEME","slot","GpuTimer","measure","ready","unpark","Ticker","signal","Application","abort","canvas","RendererType","isWebGL2","mq","store","props","all","baked","bakedAspect","DEFAULTS","long","q","fresh","hidden","any","borderChanged","hook","rg","probe","camBusy","dirty","ph","tp","lap","arg","cpuMs","gpuMs","tx","ty","padX","padY","tS","hits","tM","stamp","entered","left","already","tU","tm","l0Missing","lvl","missing","all0","all1","has","onLost","onRestored","eid","detail","e2","levels","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","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","blockHistorySwipe","releaseSpace","onBlur","session","wasSelected","clearOnClick","noClick","inside","press","patches","patch","cancelled","toFront","failure","cmd","rootHolds","root","registerInternals","board","parts","getInternals","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","lisMask","tails","parent","orderMoves","added","hint","np","same","prevIdx","nextSet","below","addedIdx","pi","placeMoves","present","above","emitAbove","stack","kids","GEOMETRY","PATCHABLE","Store","RBush","listener","lifted","rec","append","touched","orderPrev","orderHint","orderHintBad","reload","removed","updated","STYLE_ATTR","injectRevealStyles","INDICATOR_DELAY_MS","FALLBACK_MS","FALLBACK_RVFC_MS","HAVE_CURRENT_DATA","HAVE_FUTURE_DATA","EVENTS","attachVideoReveal","video","releaseStyles","hasRvfc","stalled","state","disposed","generation","rvfc","fallback","busyTimer","write","compute","waiting","clearFrameWatch","setFrame","armFallback","gen","watchFrame","reset","onEvent","buildRevealSpinner","disc","ring","FADE_OUT_MS","HIDE_DELAY_MS","DISC_PX","WORLD_CAMERA","VideoOverlay","onError","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","near","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","none","hover","VideoController","enabled","notify","VideoLayer","frameRate","reported","fail","invalidate"],"mappings":";;;AAwBO,MAAMA,IAAM,KAAK,KAAK,KAEhBC,KAAW,OAAa;AAAA,EACnC,MAAM;AAAA,EACN,MAAM;AAAA,EACN,MAAM;AAAA,EACN,MAAM;AACR,IACaC,KAAO,CAACC,MAAoBA,EAAE,OAAOA,EAAE,MACvCC,KAAO,CAACD,MAAoBA,EAAE,OAAOA,EAAE,MACvCE,KAAQ,CAACF,OAAqBA,EAAE,OAAOA,EAAE,QAAQ,GACjDG,KAAQ,CAACH,OAAqBA,EAAE,OAAOA,EAAE,QAAQ;AAavD,SAASI,GAASC,GAASL,GAAe;AAC/C,SAAO;AAAA,IACL,MAAM,KAAK,IAAIK,EAAE,MAAML,EAAE,IAAI;AAAA,I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