@zinejs/core 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"index.umd.cjs","names":["#radius","#mounted","#listeners","#state","#handlers","#activeId","#start","#prev","#last","#end","#reset","#pinching","#points","#pair","#startDistance","#remove","#container","#clip","#viewport","#book","#pageLeft","#makeCanvas","#pageRight","#leaf","#leafFront","#leafBack","#leafShadow","#paint","#container","#canvas","#onContextLost","#onContextRestored","#onVisibilityChange","#gl","#buildGlResources","#clearRestoreTimer","#texCache","#blankTex","#quadVao","#gridVao","#flat","#curl","#cacheBytes","#content","#flip","#fatalHandler","#fill","#render","#flipDir","#flipT","#view","#contextLost","#restoreTimer","#fatal","#fatalFired","#flatU","#curlU","#makeVao","#gridCount","#makeBlankTexture","#resize","#drawFlip","#drawStatic","#useFlat","#drawQuad","#bindFace","#dpr","#textureFor","#evictTextures","#renderer","#container","#source","#direction","#cover","#clickToFlip","#clickZoneSize","#singlePageThreshold","#startPageOption","#buildSpreadModel","#flipDuration","#zoomEnabled","#wheelZoom","#doubleClickLevels","#maxZoom","#honorDoubleClickInFlipZone","#clickFlipDelayValue","#ready","#init","#currentPage","#startFlip","#current","#spreadIndexForPage","#scale","#tx","#ty","#clampPan","#emitter","#destroyed","#raf","#clearPendingClickFlip","#resizeObserver","#a11yCleanup","#unbindWheel","#unbindDblClick","#unbindInput","#spreads","#machine","#leadPage","#runFlip","#resolveContent","#currentContent","#singlePage","#animateProgress","#commit","#effectiveDuration","#paintSpread","#prefetchWindow","#announce","#pinching","#pan","#press","#pendingGrab","#drag","#stageDrag","#promoteGrab","#maybeClickFlip","#cancelFlip","#clickFlipDirection","#pendingClickTimer","#pinchBaseScale","#mountWithFallback","#applySinglePage","#onDragStart","#onDragMove","#onDragEnd","#onPinchStart","#onPinchMove","#onPinchEnd","#bindWheelZoom","#bindDoubleClickZoom","#setupReducedMotion","#setupA11y","#renderCurrent","#observeResize","#fallbackToCss","#fellBack","#reducedMotion","#onKeyDown","#liveRegion","#scheduleUpdate","#updateScheduled","#getPage","#virtualizer","#urls","#preload","#decode","#cache"],"sources":["../src/engine/spread.ts","../src/engine/virtualizer.ts","../src/engine/emitter.ts","../src/engine/stateMachine.ts","../src/engine/input.ts","../src/geometry/hitTest.ts","../src/geometry/flipProgressToPose.ts","../src/renderer/cssRenderer.ts","../src/renderer/gl/context.ts","../src/renderer/gl/program.ts","../src/renderer/gl/texture.ts","../src/renderer/webglRenderer.ts","../src/renderer/select.ts","../src/zine.ts","../src/source/imageSource.ts"],"sourcesContent":["export type Direction = 'ltr' | 'rtl';\n\nexport interface Spread {\n /** Page index shown on the left, or null for a blank side. */\n left: number | null;\n /** Page index shown on the right, or null for a blank side. */\n right: number | null;\n}\n\nexport interface SpreadOptions {\n direction?: Direction;\n /** First page is a lone cover on the leading side; interior pages pair up after it. */\n cover?: boolean;\n /** One page per spread (narrow/portrait viewports). Takes precedence over `cover`. */\n singlePage?: boolean;\n}\n\n/**\n * Map a flat page list (indices 0..pageCount-1) into display spreads.\n *\n * Reading order is always preserved; `direction` only mirrors each spread's\n * left/right positions, so RTL is just an LTR layout with the sides swapped.\n * Out-of-range slots are `null` (a blank half on odd counts / the back cover).\n */\nexport function buildSpreads(pageCount: number, options: SpreadOptions = {}): Spread[] {\n const { direction = 'ltr', cover = false, singlePage = false } = options;\n if (pageCount <= 0) return [];\n\n const page = (i: number): number | null => (i >= 0 && i < pageCount ? i : null);\n const spreads: Spread[] = [];\n\n if (singlePage) {\n for (let i = 0; i < pageCount; i++) {\n spreads.push({ left: null, right: i });\n }\n } else if (cover) {\n spreads.push({ left: null, right: 0 });\n for (let i = 1; i < pageCount; i += 2) {\n spreads.push({ left: page(i), right: page(i + 1) });\n }\n } else {\n for (let i = 0; i < pageCount; i += 2) {\n spreads.push({ left: page(i), right: page(i + 1) });\n }\n }\n\n return direction === 'rtl'\n ? spreads.map((s) => ({ left: s.right, right: s.left }))\n : spreads;\n}\n\n/** Whether a container this wide should fall back to one page per spread. */\nexport function shouldSinglePage(containerWidth: number, threshold: number): boolean {\n return containerWidth < threshold;\n}\n","/** Spread indices that should be mounted around `current`, clamped to the book. */\nexport function mountWindow(current: number, spreadCount: number, radius: number): number[] {\n const window: number[] = [];\n const from = Math.max(0, current - radius);\n const to = Math.min(spreadCount - 1, current + radius);\n for (let i = from; i <= to; i++) {\n window.push(i);\n }\n return window;\n}\n\nexport interface VirtualizerDelta {\n toMount: number[];\n toEvict: number[];\n}\n\n/**\n * Tracks which spreads are mounted and, on each move, reports the difference:\n * spreads entering the ±radius window (`toMount`) and those leaving it\n * (`toEvict`). Default radius 2 = current spread ±2.\n */\nexport class Virtualizer {\n #radius: number;\n #mounted = new Set<number>();\n\n constructor(radius = 2) {\n this.#radius = radius;\n }\n\n get mounted(): number[] {\n return [...this.#mounted].sort((a, b) => a - b);\n }\n\n /** Recenter on `current`; mounts/evicts to match the window and returns the delta. */\n update(current: number, spreadCount: number): VirtualizerDelta {\n const window = new Set(mountWindow(current, spreadCount, this.#radius));\n const toMount = [...window].filter((i) => !this.#mounted.has(i)).sort((a, b) => a - b);\n const toEvict = [...this.#mounted].filter((i) => !window.has(i)).sort((a, b) => a - b);\n for (const i of toEvict) this.#mounted.delete(i);\n for (const i of toMount) this.#mounted.add(i);\n return { toMount, toEvict };\n }\n}\n","export type Listener<T> = (payload: T) => void;\n\n/** Events typed as `void` are emitted with no payload argument. */\ntype PayloadArgs<T> = [T] extends [void] ? [] : [payload: T];\n\n/** Minimal typed event emitter keyed by an event map. */\nexport class Emitter<Events> {\n #listeners = new Map<keyof Events, Set<Listener<unknown>>>();\n\n /** Subscribe; returns an unsubscribe function. */\n on<K extends keyof Events>(type: K, listener: Listener<Events[K]>): () => void {\n let set = this.#listeners.get(type);\n if (!set) {\n set = new Set();\n this.#listeners.set(type, set);\n }\n set.add(listener as Listener<unknown>);\n return () => this.off(type, listener);\n }\n\n off<K extends keyof Events>(type: K, listener: Listener<Events[K]>): void {\n this.#listeners.get(type)?.delete(listener as Listener<unknown>);\n }\n\n emit<K extends keyof Events>(type: K, ...args: PayloadArgs<Events[K]>): void {\n const payload = args[0] as Events[K];\n // Copy so a listener that unsubscribes mid-emit doesn't disturb iteration.\n const set = this.#listeners.get(type);\n if (!set) return;\n for (const listener of [...set]) {\n (listener as Listener<Events[K]>)(payload);\n }\n }\n\n clear(): void {\n this.#listeners.clear();\n }\n}\n\n/**\n * Public event surface of a Zine instance. Payloads are provisional and will\n * firm up as the engine wires the emitters that fire them.\n */\nexport interface ZineEventMap {\n ready: void;\n flipStart: { from: number; to: number };\n flipEnd: { page: number };\n pageChanged: { page: number };\n zoomChanged: { scale: number };\n sourceError: { index: number; error: unknown };\n rendererFallback: { from: string; to: string };\n}\n\nexport type ZineEmitter = Emitter<ZineEventMap>;\n","export type FlipState = 'idle' | 'dragging' | 'animating' | 'zoomed-panning';\n\nexport type FlipEvent = 'grab' | 'release' | 'settle' | 'panStart' | 'panEnd' | 'flip';\n\n/**\n * Legal transitions. A flip drag runs idle → dragging → animating → idle; a\n * programmatic flip jumps idle → animating directly via `flip`; zoom panning\n * (only reachable when zoomed in) is a separate branch idle → zoomed-panning →\n * idle. Any (state, event) pair absent here is illegal.\n */\nconst TRANSITIONS: Record<FlipState, Partial<Record<FlipEvent, FlipState>>> = {\n idle: { grab: 'dragging', panStart: 'zoomed-panning', flip: 'animating' },\n dragging: { release: 'animating' },\n animating: { settle: 'idle' },\n 'zoomed-panning': { panEnd: 'idle' },\n};\n\n/** Pure transition: the next state, or null if `event` is illegal from `state`. */\nexport function nextState(state: FlipState, event: FlipEvent): FlipState | null {\n return TRANSITIONS[state][event] ?? null;\n}\n\n/** Stateful holder around `nextState`; illegal events are ignored. */\nexport class FlipMachine {\n #state: FlipState;\n\n constructor(initial: FlipState = 'idle') {\n this.#state = initial;\n }\n\n get state(): FlipState {\n return this.#state;\n }\n\n /** Apply `event`; returns the new state, or null (no-op) if the event was illegal. */\n send(event: FlipEvent): FlipState | null {\n const next = nextState(this.#state, event);\n if (next !== null) {\n this.#state = next;\n }\n return next;\n }\n}\n","export interface GestureStart {\n x: number;\n y: number;\n t: number;\n}\n\nexport interface GestureMove {\n x: number;\n y: number;\n /** Displacement from the start point. */\n dx: number;\n dy: number;\n}\n\nexport interface GestureEnd {\n x: number;\n y: number;\n dx: number;\n dy: number;\n /** Elapsed time from start to end (ms). */\n dt: number;\n /** Velocity of the final move segment (px/ms). */\n vx: number;\n vy: number;\n /** A fast flick: final speed exceeded the swipe threshold and the gesture was not canceled. */\n swipe: boolean;\n /** The pointer was canceled (e.g. pointercancel) rather than lifted. */\n canceled: boolean;\n}\n\nexport interface PointerHandlers {\n onStart?: (g: GestureStart) => void;\n onMove?: (g: GestureMove) => void;\n onEnd?: (g: GestureEnd) => void;\n}\n\n/** Flick threshold in px/ms; a release faster than this is a swipe. */\nconst SWIPE_VELOCITY = 0.3;\n\ninterface Sample {\n x: number;\n y: number;\n t: number;\n}\n\n/**\n * Recognizes a single-pointer drag from raw pointer samples and reports normalized\n * gestures. DOM-agnostic on purpose: `bindPointerInput` maps real PointerEvents onto\n * it, but the kinematics stay pure and unit-testable. Extra pointers are ignored\n * (multi-touch pinch is a separate recognizer).\n */\nexport class PointerRecognizer {\n #handlers: PointerHandlers;\n #activeId: number | null = null;\n #start: Sample | null = null;\n #prev: Sample | null = null;\n #last: Sample | null = null;\n\n constructor(handlers: PointerHandlers = {}) {\n this.#handlers = handlers;\n }\n\n get active(): boolean {\n return this.#activeId !== null;\n }\n\n down(id: number, x: number, y: number, t: number): void {\n if (this.#activeId !== null) return; // single-pointer; ignore extra pointers\n this.#activeId = id;\n const s: Sample = { x, y, t };\n this.#start = s;\n this.#prev = s;\n this.#last = s;\n this.#handlers.onStart?.({ x, y, t });\n }\n\n move(id: number, x: number, y: number, t: number): void {\n if (id !== this.#activeId || this.#start === null) return;\n this.#prev = this.#last;\n this.#last = { x, y, t };\n this.#handlers.onMove?.({ x, y, dx: x - this.#start.x, dy: y - this.#start.y });\n }\n\n up(id: number, x: number, y: number, t: number): void {\n this.#end(id, x, y, t, false);\n }\n\n cancel(id: number, x: number, y: number, t: number): void {\n this.#end(id, x, y, t, true);\n }\n\n #end(id: number, x: number, y: number, t: number, canceled: boolean): void {\n if (id !== this.#activeId || this.#start === null) return;\n const start = this.#start;\n // Velocity comes from the last move segment, not the release point — on lift the\n // pointer usually stops, so release-relative velocity would kill every flick.\n const last = this.#last ?? start;\n const prev = this.#prev ?? start;\n const segDt = last.t - prev.t;\n const vx = segDt > 0 ? (last.x - prev.x) / segDt : 0;\n const vy = segDt > 0 ? (last.y - prev.y) / segDt : 0;\n const speed = Math.hypot(vx, vy);\n this.#reset();\n this.#handlers.onEnd?.({\n x,\n y,\n dx: x - start.x,\n dy: y - start.y,\n dt: t - start.t,\n vx,\n vy,\n swipe: !canceled && speed > SWIPE_VELOCITY,\n canceled,\n });\n }\n\n #reset(): void {\n this.#activeId = null;\n this.#start = null;\n this.#prev = null;\n this.#last = null;\n }\n}\n\n/**\n * Wire real PointerEvents from `target` into a recognizer. Returns an unbind\n * function that removes every listener. Coordinates are passed through as\n * client-space; mapping to page-local space is the engine's job.\n */\nexport function bindPointerInput(target: EventTarget, recognizer: PointerRecognizer): () => void {\n const down = (e: Event): void => {\n const p = e as PointerEvent;\n recognizer.down(p.pointerId, p.clientX, p.clientY, p.timeStamp);\n };\n const move = (e: Event): void => {\n const p = e as PointerEvent;\n recognizer.move(p.pointerId, p.clientX, p.clientY, p.timeStamp);\n };\n const up = (e: Event): void => {\n const p = e as PointerEvent;\n recognizer.up(p.pointerId, p.clientX, p.clientY, p.timeStamp);\n };\n const cancel = (e: Event): void => {\n const p = e as PointerEvent;\n recognizer.cancel(p.pointerId, p.clientX, p.clientY, p.timeStamp);\n };\n target.addEventListener('pointerdown', down);\n target.addEventListener('pointermove', move);\n target.addEventListener('pointerup', up);\n target.addEventListener('pointercancel', cancel);\n return () => {\n target.removeEventListener('pointerdown', down);\n target.removeEventListener('pointermove', move);\n target.removeEventListener('pointerup', up);\n target.removeEventListener('pointercancel', cancel);\n };\n}\n\n/**\n * Wire PointerEvents from `target` into a drag recognizer and/or a pinch\n * recognizer at once, so a single pointer stream feeds both. Returns an unbind.\n */\nexport function bindGestures(\n target: EventTarget,\n recognizers: { pointer?: PointerRecognizer; pinch?: PinchRecognizer },\n): () => void {\n const { pointer, pinch } = recognizers;\n const down = (e: Event): void => {\n const p = e as PointerEvent;\n pointer?.down(p.pointerId, p.clientX, p.clientY, p.timeStamp);\n pinch?.down(p.pointerId, p.clientX, p.clientY);\n };\n const move = (e: Event): void => {\n const p = e as PointerEvent;\n pointer?.move(p.pointerId, p.clientX, p.clientY, p.timeStamp);\n pinch?.move(p.pointerId, p.clientX, p.clientY);\n };\n const up = (e: Event): void => {\n const p = e as PointerEvent;\n pointer?.up(p.pointerId, p.clientX, p.clientY, p.timeStamp);\n pinch?.up(p.pointerId);\n };\n const cancel = (e: Event): void => {\n const p = e as PointerEvent;\n pointer?.cancel(p.pointerId, p.clientX, p.clientY, p.timeStamp);\n pinch?.cancel(p.pointerId);\n };\n target.addEventListener('pointerdown', down);\n target.addEventListener('pointermove', move);\n target.addEventListener('pointerup', up);\n target.addEventListener('pointercancel', cancel);\n return () => {\n target.removeEventListener('pointerdown', down);\n target.removeEventListener('pointermove', move);\n target.removeEventListener('pointerup', up);\n target.removeEventListener('pointercancel', cancel);\n };\n}\n\nexport interface PinchStart {\n centerX: number;\n centerY: number;\n /** Distance between the two pointers at pinch start. */\n distance: number;\n}\n\nexport interface PinchMove {\n centerX: number;\n centerY: number;\n /** Current distance / start distance. */\n scale: number;\n}\n\nexport interface PinchHandlers {\n onPinchStart?: (g: PinchStart) => void;\n onPinchMove?: (g: PinchMove) => void;\n onPinchEnd?: () => void;\n}\n\ninterface Pt {\n x: number;\n y: number;\n}\n\nfunction distance(a: Pt, b: Pt): number {\n return Math.hypot(a.x - b.x, a.y - b.y);\n}\n\n/**\n * Recognizes a two-pointer pinch and reports zoom scale (relative to the start\n * distance) and the live center point. No timestamps: pinch drives zoom, not a\n * flick. A third pointer is ignored; lifting either tracked pointer ends the pinch.\n * Coordinating this with the drag recognizer (a second finger should suspend a\n * single-finger drag) is the engine's job.\n */\nexport class PinchRecognizer {\n #handlers: PinchHandlers;\n #points = new Map<number, Pt>();\n #startDistance = 0;\n #pinching = false;\n\n constructor(handlers: PinchHandlers = {}) {\n this.#handlers = handlers;\n }\n\n get pinching(): boolean {\n return this.#pinching;\n }\n\n down(id: number, x: number, y: number): void {\n if (this.#points.has(id) || this.#points.size >= 2) return; // track only two\n this.#points.set(id, { x, y });\n if (this.#points.size === 2) {\n const { a, b } = this.#pair();\n this.#startDistance = distance(a, b);\n this.#pinching = true;\n this.#handlers.onPinchStart?.({\n centerX: (a.x + b.x) / 2,\n centerY: (a.y + b.y) / 2,\n distance: this.#startDistance,\n });\n }\n }\n\n move(id: number, x: number, y: number): void {\n const p = this.#points.get(id);\n if (!p) return;\n p.x = x;\n p.y = y;\n if (!this.#pinching) return;\n const { a, b } = this.#pair();\n this.#handlers.onPinchMove?.({\n centerX: (a.x + b.x) / 2,\n centerY: (a.y + b.y) / 2,\n scale: this.#startDistance > 0 ? distance(a, b) / this.#startDistance : 1,\n });\n }\n\n up(id: number): void {\n this.#remove(id);\n }\n\n cancel(id: number): void {\n this.#remove(id);\n }\n\n #remove(id: number): void {\n if (!this.#points.delete(id)) return;\n if (this.#pinching && this.#points.size < 2) {\n this.#pinching = false;\n this.#startDistance = 0;\n this.#handlers.onPinchEnd?.();\n }\n }\n\n #pair(): { a: Pt; b: Pt } {\n const values = [...this.#points.values()];\n const a = values[0];\n const b = values[1];\n if (!a || !b) throw new Error('pinch requires two active pointers');\n return { a, b };\n }\n}\n","import type { PageRect, Vec2 } from './foldFromPointer';\n\nexport type HitRegion = 'corner' | 'page' | 'outside';\n\n/**\n * Classify a page-local point into a hit region.\n *\n * Coordinates are page-local (see `foldFromPointer`): (0,0) top-left,\n * page spanning (0,0)..(width,height). `cornerSize` is the width/height of each\n * grabbable corner box. All four corners report `corner`; the engine decides\n * which are actually grabbable for the current spread layout (LTR/RTL, cover).\n */\nexport function hitTest(point: Vec2, pageRect: PageRect, cornerSize: number): HitRegion {\n const { width, height } = pageRect;\n if (point.x < 0 || point.x > width || point.y < 0 || point.y > height) {\n return 'outside';\n }\n const nearX = point.x <= cornerSize || point.x >= width - cornerSize;\n const nearY = point.y <= cornerSize || point.y >= height - cornerSize;\n return nearX && nearY ? 'corner' : 'page';\n}\n","export interface FlipPose {\n /** Turning-page rotation about the spine, radians: 0 (flat/open) → π (fully turned). */\n angle: number;\n /** Mesh cylinder-wrap curl, 0..1 — flat at the ends, peaks edge-on at t=0.5. CSS renderer ignores it. */\n curl: number;\n /** Fold-shadow intensity, 0..1 — peaks edge-on at t=0.5. */\n shadowAlpha: number;\n}\n\n/**\n * Map a 0→1 flip progress to a renderer-neutral fold pose.\n *\n * Linear in `t` on purpose — easing belongs to the animator that produces `t`,\n * so seeking to a fixed progress (e.g. the 0/.25/.5/.75/1 visual-regression stops)\n * is deterministic. The CSS renderer consumes `angle` as a spine `rotateY`; the\n * WebGL2 renderer additionally bends its mesh by `curl`.\n */\nexport function flipProgressToPose(t: number): FlipPose {\n const clamped = t < 0 ? 0 : t > 1 ? 1 : t;\n const arc = Math.sin(clamped * Math.PI);\n return {\n angle: clamped * Math.PI,\n curl: arc,\n shadowAlpha: arc,\n };\n}\n","import { flipProgressToPose } from '../geometry/flipProgressToPose';\nimport type { Spread } from '../engine/spread';\nimport type {\n FlipDirection,\n LayoutMetrics,\n PageContent,\n Renderer,\n RenderOptions,\n SpreadContent,\n} from './types';\n\nconst RAD_TO_DEG = 180 / Math.PI;\n\n/**\n * Layered gradients painted over the turning leaf to fake paper depth on the flat\n * fold: a crease shadow at the spine, a soft curve sheen, and a free-edge shade.\n * The spine is the leaf's pivot edge — left for a forward flip, right for backward.\n */\nfunction foldOverlay(direction: FlipDirection): string {\n const dir = direction === 'forward' ? 'to right' : 'to left';\n return [\n `linear-gradient(${dir}, rgba(0,0,0,0.6), rgba(0,0,0,0.15) 40%, rgba(0,0,0,0) 60%)`,\n `linear-gradient(${dir}, transparent 40%, rgba(255,255,255,0.32) 66%, transparent 90%)`,\n `linear-gradient(${dir}, transparent 66%, rgba(0,0,0,0.35))`,\n ].join(',');\n}\n\n/**\n * Baseline renderer: a 2-panel CSS-3D fold. Runs on every browser, no GPU. Pages\n * are <canvas> elements; the turning leaf (front + back faces, backface-hidden)\n * rotates about the spine driven by flipProgressToPose(), with a gradient shadow\n * overlay for depth. `beginFlip` stages the surfaces; `setFlipProgress` animates.\n */\nexport class CssRenderer implements Renderer {\n #container: HTMLElement | null = null;\n #clip!: HTMLDivElement;\n #viewport!: HTMLDivElement;\n #book!: HTMLDivElement;\n #pageLeft!: HTMLCanvasElement;\n #pageRight!: HTMLCanvasElement;\n #leaf!: HTMLDivElement;\n #leafFront!: HTMLCanvasElement;\n #leafBack!: HTMLCanvasElement;\n #leafShadow!: HTMLDivElement;\n\n mount(container: HTMLElement): Promise<void> {\n const doc = container.ownerDocument;\n this.#container = container;\n\n // Fixed-size clip box; NOT transformed, so zoom can't scale the crop region.\n this.#clip = doc.createElement('div');\n this.#clip.className = 'zine-clip';\n this.#clip.style.cssText = 'position:relative;width:100%;height:100%;overflow:hidden;';\n\n // Transform target for zoom/pan; lives inside the clip.\n this.#viewport = doc.createElement('div');\n this.#viewport.className = 'zine-viewport';\n this.#viewport.style.cssText = 'position:absolute;inset:0;transform-origin:0 0;';\n\n this.#book = doc.createElement('div');\n this.#book.className = 'zine-book';\n this.#book.style.cssText =\n 'position:absolute;inset:0;perspective:2000px;transform-style:preserve-3d;';\n\n this.#pageLeft = this.#makeCanvas(doc, 'zine-page-left', 'left:0;');\n this.#pageRight = this.#makeCanvas(doc, 'zine-page-right', 'right:0;');\n\n this.#leaf = doc.createElement('div');\n this.#leaf.className = 'zine-leaf';\n this.#leaf.style.cssText =\n 'position:absolute;top:0;width:50%;height:100%;transform-style:preserve-3d;display:none;';\n\n this.#leafFront = doc.createElement('canvas');\n this.#leafFront.className = 'zine-leaf-front';\n this.#leafFront.style.cssText =\n 'position:absolute;inset:0;width:100%;height:100%;backface-visibility:hidden;';\n\n this.#leafBack = doc.createElement('canvas');\n this.#leafBack.className = 'zine-leaf-back';\n this.#leafBack.style.cssText =\n 'position:absolute;inset:0;width:100%;height:100%;backface-visibility:hidden;transform:rotateY(180deg);';\n\n this.#leafShadow = doc.createElement('div');\n this.#leafShadow.className = 'zine-leaf-shadow';\n this.#leafShadow.style.cssText = 'position:absolute;inset:0;opacity:0;pointer-events:none;';\n this.#leafShadow.style.background = foldOverlay('forward'); // default; beginFlip sets per direction\n\n this.#leaf.append(this.#leafFront, this.#leafBack, this.#leafShadow);\n this.#book.append(this.#pageLeft, this.#pageRight, this.#leaf);\n this.#viewport.append(this.#book);\n this.#clip.append(this.#viewport);\n container.append(this.#clip);\n\n return Promise.resolve();\n }\n\n destroy(): void {\n this.#clip?.remove();\n this.#container = null;\n }\n\n renderSpread(_spread: Spread, content: SpreadContent, options?: RenderOptions): void {\n if (options?.fill) {\n // Single-page mode: the lone page fills the container; hide the other panel.\n this.#pageLeft.style.width = '100%';\n this.#pageRight.style.display = 'none';\n this.#paint(this.#pageLeft, content.right ?? content.left);\n } else {\n this.#pageLeft.style.width = '50%';\n this.#pageRight.style.display = '';\n this.#paint(this.#pageLeft, content.left);\n this.#paint(this.#pageRight, content.right);\n }\n // A fresh spread cancels any in-progress flip.\n this.#leaf.style.display = 'none';\n this.#leaf.style.transform = '';\n this.#leafShadow.style.opacity = '0';\n }\n\n beginFlip(\n from: SpreadContent,\n to: SpreadContent,\n direction: FlipDirection,\n options?: RenderOptions,\n ): void {\n if (options?.fill) {\n // Single-page: a full-width leaf turns about one edge, revealing `to` underneath.\n this.#pageLeft.style.width = '100%';\n this.#pageRight.style.display = 'none';\n this.#leaf.style.width = '100%';\n this.#leaf.style.left = '0';\n this.#leaf.style.transformOrigin = direction === 'forward' ? 'left center' : 'right center';\n this.#paint(this.#pageLeft, to.right ?? to.left);\n this.#paint(this.#leafFront, from.right ?? from.left);\n this.#paint(this.#leafBack, to.right ?? to.left);\n } else {\n this.#pageLeft.style.width = '50%';\n this.#pageRight.style.display = '';\n this.#leaf.style.width = '50%';\n if (direction === 'forward') {\n // Right page lifts and swings left about the spine. Left stays; right reveals `to`.\n this.#paint(this.#pageLeft, from.left);\n this.#paint(this.#pageRight, to.right);\n this.#paint(this.#leafFront, from.right);\n this.#paint(this.#leafBack, to.left);\n this.#leaf.style.left = '50%';\n this.#leaf.style.transformOrigin = 'left center';\n } else {\n // Left page swings right about its right edge. Right stays; left reveals `to`.\n this.#paint(this.#pageRight, from.right);\n this.#paint(this.#pageLeft, to.left);\n this.#paint(this.#leafFront, from.left);\n this.#paint(this.#leafBack, to.right);\n this.#leaf.style.left = '0';\n this.#leaf.style.transformOrigin = 'right center';\n }\n }\n this.#leaf.style.display = 'block';\n this.#leaf.style.transform = 'rotateY(0deg)';\n this.#leafShadow.style.background = foldOverlay(direction);\n this.#leafShadow.style.opacity = '0';\n }\n\n setFlipProgress(t: number, direction: FlipDirection): void {\n const pose = flipProgressToPose(t);\n const deg = pose.angle * RAD_TO_DEG;\n this.#leaf.style.display = 'block';\n this.#leaf.style.transform = `rotateY(${direction === 'forward' ? -deg : deg}deg)`;\n this.#leafShadow.style.opacity = String(pose.shadowAlpha);\n }\n\n setViewTransform(scale: number, x: number, y: number): void {\n this.#viewport.style.transform = `translate(${x}px, ${y}px) scale(${scale})`;\n }\n\n measure(): LayoutMetrics {\n const el = this.#container;\n const w = el?.clientWidth ?? 0;\n const h = el?.clientHeight ?? 0;\n return { containerWidth: w, containerHeight: h, pageWidth: w / 2, pageHeight: h };\n }\n\n #makeCanvas(doc: Document, className: string, extra: string): HTMLCanvasElement {\n const c = doc.createElement('canvas');\n c.className = className;\n c.style.cssText = `position:absolute;top:0;width:50%;height:100%;${extra}`;\n return c;\n }\n\n #paint(canvas: HTMLCanvasElement, content: PageContent | null): void {\n const ctx = canvas.getContext('2d');\n if (content === null) {\n ctx?.clearRect(0, 0, canvas.width, canvas.height);\n return;\n }\n canvas.width = content.width;\n canvas.height = content.height;\n ctx?.drawImage(content, 0, 0);\n }\n}\n","/** Create a WebGL2 context, or throw so the caller can fall back to CSS (§8.4). */\nexport function createGlContext(canvas: HTMLCanvasElement): WebGL2RenderingContext {\n const gl = canvas.getContext('webgl2', {\n alpha: true,\n premultipliedAlpha: true,\n antialias: true,\n depth: false,\n stencil: false,\n // We render on demand (not every frame), so the buffer must persist between\n // composites — otherwise the settled page flickers once the flip animation\n // stops and nothing is redrawing each frame.\n preserveDrawingBuffer: true,\n });\n if (gl === null) {\n throw new Error('WebglRenderer: could not create a WebGL2 context.');\n }\n return gl;\n}\n","/** Compile + link a shader program; throws with the driver log on failure. */\nexport function createProgram(\n gl: WebGL2RenderingContext,\n vertexSrc: string,\n fragmentSrc: string,\n): WebGLProgram {\n const program = gl.createProgram();\n if (program === null) throw new Error('WebglRenderer: could not create a program.');\n\n const vs = compileShader(gl, gl.VERTEX_SHADER, vertexSrc);\n const fs = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc);\n gl.attachShader(program, vs);\n gl.attachShader(program, fs);\n gl.linkProgram(program);\n\n // Shaders can be detached/deleted once linked.\n gl.deleteShader(vs);\n gl.deleteShader(fs);\n\n if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {\n const log = gl.getProgramInfoLog(program);\n gl.deleteProgram(program);\n throw new Error(`WebglRenderer: program link failed: ${log ?? 'unknown error'}`);\n }\n return program;\n}\n\nfunction compileShader(gl: WebGL2RenderingContext, type: number, src: string): WebGLShader {\n const shader = gl.createShader(type);\n if (shader === null) throw new Error('WebglRenderer: could not create a shader.');\n gl.shaderSource(shader, src);\n gl.compileShader(shader);\n if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {\n const log = gl.getShaderInfoLog(shader);\n gl.deleteShader(shader);\n throw new Error(`WebglRenderer: shader compile failed: ${log ?? 'unknown error'}`);\n }\n return shader;\n}\n","/** Create a page texture with clamp + linear filtering (no mipmaps — §8.3). */\nexport function createTexture(gl: WebGL2RenderingContext): WebGLTexture {\n const tex = gl.createTexture();\n if (tex === null) throw new Error('WebglRenderer: could not create a texture.');\n gl.bindTexture(gl.TEXTURE_2D, tex);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n return tex;\n}\n\n/** Upload a decoded page raster (ImageBitmap or canvas) into `tex`. */\nexport function uploadTexture(\n gl: WebGL2RenderingContext,\n tex: WebGLTexture,\n source: TexImageSource,\n): void {\n gl.bindTexture(gl.TEXTURE_2D, tex);\n // No Y flip: the vertex shader maps aUnit.y=0 to the page top and samples the\n // source's top row there. UNPACK_FLIP_Y is honored for <canvas> sources but\n // IGNORED for ImageBitmap, so flipping would invert PDF (canvas) pages while\n // leaving image (ImageBitmap) pages upright. Off keeps both consistent.\n gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);\n gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, source);\n}\n","import { flipProgressToPose } from '../geometry/flipProgressToPose';\nimport type { Spread } from '../engine/spread';\nimport type {\n FlipDirection,\n LayoutMetrics,\n Renderer,\n RenderOptions,\n SpreadContent,\n} from './types';\nimport { createGlContext } from './gl/context';\nimport { createProgram } from './gl/program';\nimport { createTexture, uploadTexture } from './gl/texture';\n\n// Flat program: maps a unit quad to a page rect (device px, top-left origin) with\n// zoom/pan. aUnit.y=0 is the page top and samples the source's top row (no flip).\nconst FLAT_VERT = `#version 300 es\nin vec2 aUnit;\nuniform vec2 uViewport;\nuniform vec4 uRect;\nuniform vec3 uView;\nout vec2 vUv;\nvoid main() {\n vec2 px = uRect.xy + aUnit * uRect.zw;\n px = px * uView.x + uView.yz;\n vec2 clip = px / uViewport * 2.0 - 1.0;\n gl_Position = vec4(clip.x, -clip.y, 0.0, 1.0);\n vUv = aUnit;\n}`;\n\nconst FLAT_FRAG = `#version 300 es\nprecision mediump float;\nin vec2 vUv;\nuniform sampler2D uTex;\nuniform float uGutterSide; // +1 = spine at the right edge, -1 = at the left edge, 0 = none\nout vec4 outColor;\nvoid main() {\n vec4 c = texture(uTex, vUv);\n if (uGutterSide != 0.0) {\n // Soft, permanent gutter shadow: darken toward the spine edge where the pages\n // meet, so the turning leaf's spine shadow lands into it instead of vanishing.\n float d = uGutterSide > 0.0 ? (1.0 - vUv.x) : vUv.x;\n c.rgb *= mix(0.72, 1.0, smoothstep(0.0, 0.10, d));\n }\n outColor = c;\n}`;\n\n// Curl program: the turning leaf. u runs from the spine (0) to the free edge (1).\n// The page wraps around a vertical cylinder (radius shrinks with uCurl) and rotates\n// about the spine by uAngle; orthographic (no perspective yet).\nconst CURL_VERT = `#version 300 es\nin vec2 aUnit;\nuniform vec2 uViewport;\nuniform vec4 uLeaf; // spineX, y, width, height (device px)\nuniform vec3 uView; // scale, tx, ty\nuniform float uAngle; // spine rotation 0..PI\nuniform float uCurl; // 0..1 bend amount\nuniform float uDir; // +1 leaf sweeps from +x side, -1 from -x side\nout vec2 vUv;\nout float vU;\nout float vLight; // surface facing: +1 toward viewer, 0 edge-on, -1 away\nconst float CAM = 3.0; // perspective camera distance, in page widths (bigger = subtler)\nvoid main() {\n float u = aUnit.x;\n float W = uLeaf.z;\n // Cylinder wrap of the turning sheet, rotated about the spine (vertical y axis).\n float bend = uCurl * 1.5;\n float phi, xw, zw;\n if (bend > 0.001) {\n float R = W / bend;\n phi = u * bend;\n xw = R * sin(phi);\n zw = R * (1.0 - cos(phi));\n } else {\n phi = 0.0;\n xw = u * W;\n zw = 0.0;\n }\n float X = xw * cos(uAngle) - zw * sin(uAngle); // in-plane\n float Z = xw * sin(uAngle) + zw * cos(uAngle); // depth (+ toward viewer)\n float px = uLeaf.x + uDir * X;\n float py = uLeaf.y + aUnit.y * uLeaf.w;\n // Perspective by depth. X may bulge toward the viewer for 3D pop; Y only ever\n // SHRINKS (persp clamped <= 1) about the page's own vertical center, so the top\n // is never pushed past the frame (that was the hidden-top bug).\n float D = W * CAM;\n float persp = D / max(D - Z, 1.0);\n float cx = uViewport.x * 0.5;\n float cy = uLeaf.y + 0.5 * uLeaf.w;\n px = cx + (px - cx) * persp;\n py = cy + (py - cy) * min(persp, 1.0);\n vec2 p = vec2(px, py) * uView.x + uView.yz;\n vec2 clip = p / uViewport * 2.0 - 1.0;\n gl_Position = vec4(clip.x, -clip.y, 0.0, 1.0);\n vUv = aUnit;\n vU = u;\n vLight = cos(phi + uAngle);\n}`;\n\n// Per-fragment facing: whichever side of the curling sheet faces the viewer shows\n// its own page, so mid-curl you see a sliver of the next page (continuous handoff).\nconst CURL_FRAG = `#version 300 es\nprecision mediump float;\nin vec2 vUv;\nin float vU;\nin float vLight;\nuniform sampler2D uFront;\nuniform sampler2D uBack;\nuniform highp float uDir; // must match the vertex stage's default highp\nout vec4 outColor;\nvoid main() {\n // A backward flip (uDir < 0) mirrors the mesh horizontally, which flips both the\n // projected winding (gl_FrontFacing) and the page's u->x mapping; undo both here.\n float fx = uDir > 0.0 ? vUv.x : 1.0 - vUv.x;\n // Front/back from the sheet's smooth facing (vLight), NOT gl_FrontFacing: the\n // winding-based test flickers per-pixel at grazing angles as the curl overlaps.\n bool showFront = vLight > 0.0;\n vec4 c = showFront ? texture(uFront, vec2(fx, vUv.y)) : texture(uBack, vec2(1.0 - fx, vUv.y));\n\n // Diffuse curl shading from the (smooth) facing magnitude: face-on bright, edge-on dark.\n float diff = clamp(abs(vLight), 0.0, 1.0);\n float lit = mix(0.72, 1.0, diff); // ambient floor, never crushed\n float sheen = smoothstep(0.6, 0.95, diff) * (1.0 - diff) * 0.5; // soft crest highlight\n // Spine crease uses the SAME curve as the static gutter shadow, so when the leaf\n // lands the shadow is continuous instead of popping away.\n lit *= mix(0.72, 1.0, smoothstep(0.0, 0.10, vU));\n\n c.rgb = clamp(c.rgb * lit + sheen, 0.0, 1.0);\n outColor = c;\n}`;\n\nconst GRID_COLS = 24;\n// If a lost context is not restored within this window, give up and let the engine\n// fall back to the CSS renderer (§8.4).\nconst RESTORE_TIMEOUT_MS = 4000;\n// GPU texture LRU ceiling (§9). Page textures are cached by content and evicted\n// least-recently-used beyond this, so flips/zooms don't re-upload every frame.\nconst MAX_TEXTURE_CACHE_BYTES = 256 * 1024 * 1024;\n\ninterface Rect {\n x: number;\n y: number;\n w: number;\n h: number;\n}\n\ninterface FlipState {\n underLeft: TexImageSource | null;\n underRight: TexImageSource | null;\n underFull: TexImageSource | null; // fill mode\n front: TexImageSource | null;\n back: TexImageSource | null;\n dir: number; // +1 / -1 for the curl sweep\n spineAtStart: number; // 0 = spine at left edge, 0.5 = center, 1 = right edge\n fill: boolean;\n}\n\n/**\n * GPU renderer (WebGL2, hand-written, no third-party library). The turning leaf is\n * a grid mesh bent around a cylinder (driven by the shared flipProgressToPose), the\n * static pages are flat textured quads underneath. Restores its GL state in place on\n * context loss; if that fails it signals `onFatal` so the engine can fall back to CSS.\n */\nexport class WebglRenderer implements Renderer {\n #container: HTMLElement | null = null;\n #canvas: HTMLCanvasElement | null = null;\n #gl: WebGL2RenderingContext | null = null;\n\n #flat: WebGLProgram | null = null;\n #curl: WebGLProgram | null = null;\n #quadVao: WebGLVertexArrayObject | null = null;\n #gridVao: WebGLVertexArrayObject | null = null;\n #gridCount = 0;\n #texCache = new Map<TexImageSource, { tex: WebGLTexture; bytes: number }>();\n #cacheBytes = 0;\n #blankTex: WebGLTexture | null = null; // 1x1 transparent, for blank leaf faces\n\n #flatU: Record<string, WebGLUniformLocation | null> = {};\n #curlU: Record<string, WebGLUniformLocation | null> = {};\n\n #view = { scale: 1, tx: 0, ty: 0 };\n #dpr = 1;\n #content: SpreadContent | null = null;\n #fill = false;\n #flip: FlipState | null = null;\n #flipT = 0;\n #flipDir: FlipDirection = 'forward';\n\n #contextLost = false;\n #fatalFired = false;\n #restoreTimer: ReturnType<typeof setTimeout> | null = null;\n #fatalHandler: (() => void) | null = null;\n\n mount(container: HTMLElement): Promise<void> {\n this.#container = container;\n const doc = container.ownerDocument;\n const canvas = doc.createElement('canvas');\n // Fill the container as a plain block, so it doesn't depend on the container\n // being positioned (an absolute canvas would escape a static container).\n canvas.style.cssText = 'display:block;width:100%;height:100%;';\n container.append(canvas);\n this.#canvas = canvas;\n\n canvas.addEventListener('webglcontextlost', this.#onContextLost as EventListener);\n canvas.addEventListener('webglcontextrestored', this.#onContextRestored as EventListener);\n doc.addEventListener('visibilitychange', this.#onVisibilityChange);\n\n this.#gl = createGlContext(canvas); // throws if unavailable -> engine falls back (§8.4)\n this.#buildGlResources();\n\n return Promise.resolve();\n }\n\n destroy(): void {\n this.#clearRestoreTimer();\n const canvas = this.#canvas;\n if (canvas !== null) {\n canvas.removeEventListener('webglcontextlost', this.#onContextLost as EventListener);\n canvas.removeEventListener('webglcontextrestored', this.#onContextRestored as EventListener);\n canvas.ownerDocument.removeEventListener('visibilitychange', this.#onVisibilityChange);\n }\n const gl = this.#gl;\n if (gl !== null) {\n for (const cached of this.#texCache.values()) gl.deleteTexture(cached.tex);\n if (this.#blankTex !== null) gl.deleteTexture(this.#blankTex);\n if (this.#quadVao !== null) gl.deleteVertexArray(this.#quadVao);\n if (this.#gridVao !== null) gl.deleteVertexArray(this.#gridVao);\n if (this.#flat !== null) gl.deleteProgram(this.#flat);\n if (this.#curl !== null) gl.deleteProgram(this.#curl);\n gl.getExtension('WEBGL_lose_context')?.loseContext();\n }\n canvas?.remove();\n this.#texCache.clear();\n this.#cacheBytes = 0;\n this.#blankTex = null;\n this.#container = null;\n this.#canvas = null;\n this.#gl = null;\n this.#content = null;\n this.#flip = null;\n }\n\n onFatal(handler: () => void): void {\n this.#fatalHandler = handler;\n }\n\n renderSpread(_spread: Spread, content: SpreadContent, options?: RenderOptions): void {\n this.#content = content;\n this.#fill = options?.fill ?? false;\n this.#flip = null;\n this.#render();\n }\n\n beginFlip(\n from: SpreadContent,\n to: SpreadContent,\n direction: FlipDirection,\n options?: RenderOptions,\n ): void {\n const fill = options?.fill ?? false;\n this.#flipDir = direction;\n this.#flipT = 0;\n if (fill) {\n this.#flip = {\n underLeft: null,\n underRight: null,\n underFull: to.right ?? to.left,\n front: from.right ?? from.left,\n back: to.right ?? to.left,\n dir: direction === 'forward' ? 1 : -1,\n spineAtStart: direction === 'forward' ? 0 : 1,\n fill: true,\n };\n } else if (direction === 'forward') {\n // Right page lifts and swings left about the spine; left stays, right reveals `to`.\n this.#flip = {\n underLeft: from.left,\n underRight: to.right,\n underFull: null,\n front: from.right,\n back: to.left,\n dir: 1,\n spineAtStart: 0.5,\n fill: false,\n };\n } else {\n // Left page swings right about the spine; right stays, left reveals `to`.\n this.#flip = {\n underLeft: to.left,\n underRight: from.right,\n underFull: null,\n front: from.left,\n back: to.right,\n dir: -1,\n spineAtStart: 0.5,\n fill: false,\n };\n }\n this.#render();\n }\n\n setFlipProgress(t: number, direction: FlipDirection): void {\n this.#flipT = t;\n this.#flipDir = direction;\n this.#render();\n }\n\n setViewTransform(scale: number, x: number, y: number): void {\n this.#view = { scale, tx: x, ty: y };\n this.#render();\n }\n\n measure(): LayoutMetrics {\n const el = this.#container;\n const w = el?.clientWidth ?? 0;\n const h = el?.clientHeight ?? 0;\n return { containerWidth: w, containerHeight: h, pageWidth: w / 2, pageHeight: h };\n }\n\n // --- context loss / restore ---------------------------------------------------\n\n #onContextLost = (event: Event): void => {\n event.preventDefault(); // required, or the browser won't fire 'restored'\n this.#contextLost = true;\n if (this.#restoreTimer === null) {\n this.#restoreTimer = setTimeout(() => this.#fatal(), RESTORE_TIMEOUT_MS);\n }\n };\n\n #onContextRestored = (): void => {\n this.#clearRestoreTimer();\n this.#contextLost = false;\n this.#buildGlResources(); // old GL objects are gone; rebuild on the same context\n this.#render(); // CPU-side content/flip/view were retained, so re-upload + repaint\n };\n\n #onVisibilityChange = (): void => {\n if (this.#canvas?.ownerDocument.visibilityState === 'visible') this.#render();\n };\n\n #fatal(): void {\n if (this.#fatalFired) return;\n this.#fatalFired = true;\n this.#fatalHandler?.();\n }\n\n #clearRestoreTimer(): void {\n if (this.#restoreTimer !== null) {\n clearTimeout(this.#restoreTimer);\n this.#restoreTimer = null;\n }\n }\n\n #buildGlResources(): void {\n const gl = this.#gl;\n if (gl === null) return;\n\n this.#flat = createProgram(gl, FLAT_VERT, FLAT_FRAG);\n this.#curl = createProgram(gl, CURL_VERT, CURL_FRAG);\n for (const name of ['uViewport', 'uRect', 'uView', 'uTex', 'uGutterSide']) {\n this.#flatU[name] = gl.getUniformLocation(this.#flat, name);\n }\n for (const name of ['uViewport', 'uLeaf', 'uView', 'uAngle', 'uCurl', 'uDir', 'uFront', 'uBack']) {\n this.#curlU[name] = gl.getUniformLocation(this.#curl, name);\n }\n\n this.#quadVao = this.#makeVao(gl, this.#flat, new Float32Array([0, 0, 1, 0, 0, 1, 1, 1]));\n\n // Grid strip across the width (columns subdivided, 2 rows) for a smooth bend.\n const grid: number[] = [];\n for (let c = 0; c <= GRID_COLS; c++) {\n const u = c / GRID_COLS;\n grid.push(u, 0, u, 1);\n }\n this.#gridCount = (GRID_COLS + 1) * 2;\n this.#gridVao = this.#makeVao(gl, this.#curl, new Float32Array(grid));\n\n // A (re)created context has no live textures; drop the cache and remake the blank.\n this.#texCache.clear();\n this.#cacheBytes = 0;\n this.#blankTex = this.#makeBlankTexture(gl);\n gl.useProgram(this.#flat);\n gl.uniform1i(this.#flatU.uTex ?? null, 0);\n gl.useProgram(this.#curl);\n gl.uniform1i(this.#curlU.uFront ?? null, 0);\n gl.uniform1i(this.#curlU.uBack ?? null, 1);\n gl.clearColor(0, 0, 0, 0);\n gl.enable(gl.BLEND);\n gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); // premultiplied alpha\n }\n\n // --- drawing ------------------------------------------------------------------\n\n #render(): void {\n const gl = this.#gl;\n const canvas = this.#canvas;\n if (gl === null || canvas === null || this.#contextLost || gl.isContextLost()) return;\n this.#resize();\n gl.clear(gl.COLOR_BUFFER_BIT);\n if (this.#flip !== null) this.#drawFlip();\n else if (this.#content !== null) this.#drawStatic();\n }\n\n #drawStatic(): void {\n const canvas = this.#canvas!;\n const w = canvas.width;\n const h = canvas.height;\n this.#useFlat();\n const content = this.#content!;\n if (this.#fill) {\n this.#drawQuad({ x: 0, y: 0, w, h }, content.right ?? content.left);\n } else {\n this.#drawQuad({ x: 0, y: 0, w: w / 2, h }, content.left, 1);\n this.#drawQuad({ x: w / 2, y: 0, w: w / 2, h }, content.right, -1);\n }\n }\n\n #drawFlip(): void {\n const gl = this.#gl!;\n const canvas = this.#canvas!;\n const w = canvas.width;\n const h = canvas.height;\n const flip = this.#flip!;\n const pose = flipProgressToPose(this.#flipT);\n\n // Static pages underneath.\n this.#useFlat();\n if (flip.fill) {\n this.#drawQuad({ x: 0, y: 0, w, h }, flip.underFull);\n } else {\n this.#drawQuad({ x: 0, y: 0, w: w / 2, h }, flip.underLeft, 1);\n this.#drawQuad({ x: w / 2, y: 0, w: w / 2, h }, flip.underRight, -1);\n }\n\n // Turning leaf: both faces uploaded, per-fragment facing picks front vs back.\n if (flip.front === null && flip.back === null) return;\n this.#bindFace(gl.TEXTURE0, flip.front);\n this.#bindFace(gl.TEXTURE1, flip.back);\n gl.activeTexture(gl.TEXTURE0);\n\n const leafW = flip.fill ? w : w / 2;\n const spineX = flip.spineAtStart * w;\n gl.useProgram(this.#curl);\n gl.bindVertexArray(this.#gridVao);\n gl.uniform2f(this.#curlU.uViewport ?? null, w, h);\n gl.uniform3f(this.#curlU.uView ?? null, this.#view.scale, this.#view.tx * this.#dpr, this.#view.ty * this.#dpr);\n gl.uniform4f(this.#curlU.uLeaf ?? null, spineX, 0, leafW, h);\n gl.uniform1f(this.#curlU.uAngle ?? null, pose.angle);\n gl.uniform1f(this.#curlU.uCurl ?? null, pose.curl);\n gl.uniform1f(this.#curlU.uDir ?? null, flip.dir);\n gl.drawArrays(gl.TRIANGLE_STRIP, 0, this.#gridCount);\n }\n\n #useFlat(): void {\n const gl = this.#gl!;\n const canvas = this.#canvas!;\n gl.useProgram(this.#flat);\n gl.bindVertexArray(this.#quadVao);\n gl.activeTexture(gl.TEXTURE0);\n gl.uniform2f(this.#flatU.uViewport ?? null, canvas.width, canvas.height);\n gl.uniform3f(this.#flatU.uView ?? null, this.#view.scale, this.#view.tx * this.#dpr, this.#view.ty * this.#dpr);\n }\n\n #drawQuad(rect: Rect, source: TexImageSource | null, gutterSide = 0): void {\n const gl = this.#gl!;\n if (source === null) return;\n this.#bindFace(gl.TEXTURE0, source);\n gl.uniform4f(this.#flatU.uRect ?? null, rect.x, rect.y, rect.w, rect.h);\n gl.uniform1f(this.#flatU.uGutterSide ?? null, gutterSide);\n gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);\n }\n\n /** Bind the texture for `source` (a blank 1x1 when null) to a texture unit. */\n #bindFace(unit: number, source: TexImageSource | null): void {\n const gl = this.#gl!;\n gl.activeTexture(unit);\n gl.bindTexture(gl.TEXTURE_2D, source !== null ? this.#textureFor(source) : this.#blankTex);\n }\n\n /** Page texture cached by content: uploaded once, reused across frames, LRU-capped. */\n #textureFor(source: TexImageSource): WebGLTexture {\n const gl = this.#gl!;\n const existing = this.#texCache.get(source);\n if (existing !== undefined) {\n this.#texCache.delete(source); // move to most-recently-used\n this.#texCache.set(source, existing);\n return existing.tex;\n }\n const tex = createTexture(gl); // binds + uploads on the active unit set by the caller\n uploadTexture(gl, tex, source);\n const dims = source as unknown as { width: number; height: number }; // page rasters have both\n const bytes = dims.width * dims.height * 4;\n this.#texCache.set(source, { tex, bytes });\n this.#cacheBytes += bytes;\n this.#evictTextures();\n return tex;\n }\n\n /** Drop least-recently-used page textures past the byte ceiling (keep a small floor). */\n #evictTextures(): void {\n const gl = this.#gl!;\n for (const [src, cached] of this.#texCache) {\n if (this.#cacheBytes <= MAX_TEXTURE_CACHE_BYTES || this.#texCache.size <= 4) break;\n this.#texCache.delete(src);\n this.#cacheBytes -= cached.bytes;\n gl.deleteTexture(cached.tex);\n }\n }\n\n #makeBlankTexture(gl: WebGL2RenderingContext): WebGLTexture {\n const tex = createTexture(gl);\n gl.bindTexture(gl.TEXTURE_2D, tex);\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([0, 0, 0, 0]));\n return tex;\n }\n\n #makeVao(gl: WebGL2RenderingContext, program: WebGLProgram, data: Float32Array): WebGLVertexArrayObject {\n const vao = gl.createVertexArray();\n const buffer = gl.createBuffer();\n if (vao === null || buffer === null) throw new Error('WebglRenderer: could not create buffers.');\n gl.bindVertexArray(vao);\n gl.bindBuffer(gl.ARRAY_BUFFER, buffer);\n gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW);\n const aUnit = gl.getAttribLocation(program, 'aUnit');\n gl.enableVertexAttribArray(aUnit);\n gl.vertexAttribPointer(aUnit, 2, gl.FLOAT, false, 0, 0);\n gl.bindVertexArray(null);\n return vao;\n }\n\n #resize(): void {\n const gl = this.#gl;\n const canvas = this.#canvas;\n const el = this.#container;\n if (gl === null || canvas === null || el === null) return;\n this.#dpr = typeof devicePixelRatio === 'number' ? devicePixelRatio : 1;\n const w = Math.max(1, Math.round(el.clientWidth * this.#dpr));\n const h = Math.max(1, Math.round(el.clientHeight * this.#dpr));\n if (canvas.width !== w || canvas.height !== h) {\n canvas.width = w;\n canvas.height = h;\n gl.viewport(0, 0, w, h);\n }\n }\n}\n","import type { Renderer } from './types';\n\nexport type RendererKind = 'css' | 'webgl2';\n\n/**\n * How the consumer chooses a renderer:\n * - `'auto'` (default): prefer the GPU path (WebGL2), else CSS.\n * - a single kind: force it (`'webgl2'` throws if the device has no WebGL2).\n * - an ordered array: try each in turn, first viable wins.\n * - a `Renderer` instance: use it as-is (custom implementation, §6.1/§11).\n */\nexport type RendererOption = 'auto' | RendererKind | RendererKind[] | Renderer;\n\nexport interface Capabilities {\n /** WebGL2 available — the GPU renderer's only backend. */\n gpu: boolean;\n}\n\ntype RendererLoader = () => Promise<Renderer>;\n\n/**\n * Lazy loaders, one per kind. Each is a dynamic `import()` so the bundler\n * code-splits it into its own chunk and a device fetches only the one selected.\n */\nconst LOADERS: Partial<Record<RendererKind, RendererLoader>> = {\n css: async () => new (await import('./cssRenderer')).CssRenderer(),\n webgl2: async () => new (await import('./webglRenderer')).WebglRenderer(),\n};\n\n// The WebGL2 renderer is auto-selected on GPU-capable devices; CSS is the baseline\n// for non-GPU devices and the fallback for unrecoverable GPU failures (§8.4).\nconst WEBGL2_AUTO = true;\n\nfunction isRenderer(option: RendererOption): option is Renderer {\n return (\n typeof option === 'object' &&\n option !== null &&\n !Array.isArray(option) &&\n typeof (option as Renderer).mount === 'function'\n );\n}\n\nfunction autoOrder(caps: Capabilities): RendererKind[] {\n return caps.gpu && WEBGL2_AUTO ? ['webgl2', 'css'] : ['css'];\n}\n\n/** Detect WebGL2 support — the GPU renderer's only backend (no WebGL1, no WebGPU). */\nexport function detectCapabilities(): Capabilities {\n return { gpu: hasWebGl2() };\n}\n\nfunction hasWebGl2(): boolean {\n try {\n return Boolean(document.createElement('canvas').getContext('webgl2'));\n } catch {\n return false;\n }\n}\n\n/**\n * Resolve the `renderer` option to a mounted renderer instance, lazy-loading its\n * chunk. Throws an agent-actionable error if nothing viable can be loaded.\n */\nexport async function selectRenderer(\n option: RendererOption = 'auto',\n caps: Capabilities = detectCapabilities(),\n): Promise<Renderer> {\n if (isRenderer(option)) return option;\n\n const order = Array.isArray(option) ? option : option === 'auto' ? autoOrder(caps) : [option];\n\n for (const kind of order) {\n if (kind === 'webgl2' && !caps.gpu) continue; // skip the GPU path without WebGL2\n const loader = LOADERS[kind];\n if (loader) return loader();\n }\n\n if (order.length === 1 && order[0] === 'webgl2' && !caps.gpu) {\n throw new Error(\n \"renderer: 'webgl2' was forced but this device has no WebGL2. Use 'css' or 'auto'.\",\n );\n }\n throw new Error(\n `renderer: none of [${order.join(', ')}] could be loaded — use 'css' or 'auto'.`,\n );\n}\n","import { buildSpreads, shouldSinglePage, type Direction, type Spread } from './engine/spread';\nimport { Virtualizer } from './engine/virtualizer';\nimport { Emitter, type ZineEventMap } from './engine/emitter';\nimport { FlipMachine } from './engine/stateMachine';\nimport { PointerRecognizer, PinchRecognizer, bindGestures, type GestureEnd } from './engine/input';\nimport { hitTest } from './geometry/hitTest';\nimport { selectRenderer, type RendererOption } from './renderer/select';\nimport type { FlipDirection, PageContent, Renderer, SpreadContent } from './renderer/types';\nimport type { Source } from './source/types';\n\n/** Grab-zone size as a fraction of the smaller container dimension. */\nconst CORNER_FRACTION = 0.25;\n\n/** Wheel-zoom sensitivity: scale multiplies by exp(-deltaY * this) per wheel event. */\nconst WHEEL_ZOOM_SENSITIVITY = 0.0015;\n\n/** Pointer movement (px) beyond which a press becomes a drag rather than a tap. */\nconst DRAG_THRESHOLD = 6;\n\n/** Window (ms) a single click waits to rule out a double-click before flipping. */\nconst DOUBLE_CLICK_MS = 250;\n\ninterface DragState {\n direction: FlipDirection;\n targetIndex: number;\n toPage: number;\n toContent: SpreadContent;\n width: number;\n t: number;\n}\n\nexport interface ZoomOptions {\n /** Whether zooming is allowed at all; default true. */\n enabled?: boolean;\n /** Maximum zoom scale; default 4. */\n max?: number;\n /** Zoom on Ctrl/⌘ + wheel (also how trackpad pinch arrives on desktop); default true. */\n wheel?: boolean;\n /** Zoom levels cycled by double-click (wraps to the first); `false` disables. Default [1, 2, 4]. */\n doubleClick?: number[] | false;\n /**\n * Listen for double-click zoom inside the click-to-flip zones. Default: off in 'edge' mode\n * (edges flip instantly, no delay), on in 'half' mode. Turning it on in 'edge' mode makes\n * clicks wait out `clickFlipDelay` so a double-click can preempt them with a zoom.\n */\n doubleClickInFlipZone?: boolean;\n}\n\nexport interface ZineOptions {\n /** Content source (e.g. an ImageSource). Required. */\n source: Source;\n /** Renderer selection; default 'auto'. */\n renderer?: RendererOption;\n /** Fixed container width in px; omit to let the container/CSS drive the size. */\n width?: number;\n /** Fixed container height in px; omit to let the container/CSS drive the size. */\n height?: number;\n /** Reading direction; default 'ltr'. */\n direction?: Direction;\n /** First page is a lone cover; default false. */\n cover?: boolean;\n /** Page to open on; default 0. */\n startPage?: number;\n /** Flip animation duration in ms; default 500. */\n flipDuration?: number;\n /** How a tap/click turns pages: near an edge ('edge'), by page half ('half'), or 'off'. Default 'edge'. */\n clickToFlip?: 'edge' | 'half' | 'off';\n /** Edge-zone size in px per side, used when clickToFlip is 'edge'. Default 64. */\n clickZoneSize?: number;\n /**\n * Delay (ms) a click waits before flipping, so a double-click can preempt it with a zoom.\n * Omit for auto: 0 when double-click zoom is inactive, 250 when it's active.\n */\n clickFlipDelay?: number;\n /** Zoom behavior. */\n zoom?: ZoomOptions;\n /** Container widths below this (px) switch to one page per spread; default 640. */\n singlePageThreshold?: number;\n}\n\n/**\n * The public flipbook. Composes the engine (spreads, virtualizer, events), a\n * lazily-selected renderer, and a content source. Construction is synchronous\n * but setup is async — await `ready` (or listen for the `ready` event) before\n * driving it.\n */\nexport class Zine {\n #container: HTMLElement;\n #source: Source;\n #emitter = new Emitter<ZineEventMap>();\n #virtualizer = new Virtualizer(2);\n #machine = new FlipMachine();\n #direction: Direction;\n #cover: boolean;\n #clickToFlip: 'edge' | 'half' | 'off';\n #clickZoneSize: number;\n #honorDoubleClickInFlipZone: boolean;\n #clickFlipDelayValue: number;\n #singlePageThreshold: number;\n #singlePage = false;\n #startPageOption: number | undefined;\n #spreads: Spread[] = [];\n #current = 0;\n #currentPage = 0;\n #currentContent: SpreadContent = { left: null, right: null };\n #flipDuration: number;\n #zoomEnabled: boolean;\n #wheelZoom: boolean;\n #doubleClickLevels: number[] | null;\n #maxZoom: number;\n #resizeObserver: ResizeObserver | null = null;\n #updateScheduled = false;\n #scale = 1;\n #tx = 0;\n #ty = 0;\n #renderer: Renderer | null = null;\n #fellBack = false;\n #destroyed = false;\n #raf: number | null = null;\n #drag: DragState | null = null;\n #pendingGrab: { direction: FlipDirection; targetIndex: number; toPage: number; width: number } | null = null;\n #press: { x: number; y: number } | null = null;\n #pendingClickTimer: ReturnType<typeof setTimeout> | null = null;\n #pan: { baseTx: number; baseTy: number } | null = null;\n #pinching = false;\n #pinchBaseScale = 1;\n #reducedMotion = false;\n #liveRegion: HTMLElement | null = null;\n #unbindInput: (() => void) | null = null;\n #unbindWheel: (() => void) | null = null;\n #unbindDblClick: (() => void) | null = null;\n #a11yCleanup: (() => void) | null = null;\n #ready: Promise<void>;\n\n /** Stable seek API: drive the fold to a fixed progress without animating (visual regression). */\n readonly debug = {\n setFlipProgress: (t: number, direction: FlipDirection): void => {\n this.#renderer?.setFlipProgress(t, direction);\n },\n };\n\n constructor(container: HTMLElement, options: ZineOptions) {\n validateOptions(container, options);\n this.#container = container;\n if (options.width !== undefined) container.style.width = `${options.width}px`;\n if (options.height !== undefined) container.style.height = `${options.height}px`;\n this.#source = options.source;\n const direction = options.direction ?? 'ltr';\n const cover = options.cover ?? false;\n this.#direction = direction;\n this.#cover = cover;\n this.#clickToFlip = options.clickToFlip ?? 'edge';\n this.#clickZoneSize = options.clickZoneSize ?? 64;\n this.#singlePageThreshold = options.singlePageThreshold ?? 640;\n this.#startPageOption = options.startPage;\n // Sync sources (a known page count) build spreads now — so bad pageCount/startPage\n // throw immediately from `new Zine`. Async sources (an `open()`) defer to #init.\n if (typeof this.#source.open !== 'function') {\n this.#buildSpreadModel();\n }\n this.#flipDuration = options.flipDuration ?? 800;\n this.#zoomEnabled = options.zoom?.enabled ?? true;\n this.#wheelZoom = options.zoom?.wheel ?? true;\n const dbl = options.zoom?.doubleClick;\n const levels = dbl === false ? [] : [...(dbl ?? [1, 2, 4])].sort((a, b) => a - b);\n this.#doubleClickLevels = levels.length > 0 ? levels : null;\n this.#maxZoom = options.zoom?.max ?? 4;\n\n // Arbitrate click-to-flip vs double-click zoom inside the flip zones.\n // Listen for double-click zoom in flip zones: default off in 'edge', on in 'half'.\n // clickFlipDelay === 0 hard-disables it. When honored, a delay lets a click wait\n // out a possible double-click; auto default 250 ms, overridable.\n const doubleClickZoomActive = this.#zoomEnabled && this.#doubleClickLevels !== null;\n const listenInFlipZone = options.zoom?.doubleClickInFlipZone ?? (this.#clickToFlip === 'half');\n this.#honorDoubleClickInFlipZone =\n this.#clickToFlip !== 'off' &&\n doubleClickZoomActive &&\n listenInFlipZone &&\n options.clickFlipDelay !== 0;\n this.#clickFlipDelayValue = this.#honorDoubleClickInFlipZone\n ? (options.clickFlipDelay ?? DOUBLE_CLICK_MS)\n : 0;\n\n this.#ready = this.#init(options.renderer ?? 'auto');\n }\n\n /** Resolves once the renderer is mounted and the first spread is painted. */\n get ready(): Promise<void> {\n return this.#ready;\n }\n\n getPageCount(): number {\n return this.#source.pageCount;\n }\n\n getPage(): number {\n return this.#currentPage;\n }\n\n flipNext(): void {\n this.#startFlip(this.#current + 1);\n }\n\n flipPrev(): void {\n this.#startFlip(this.#current - 1);\n }\n\n flipTo(page: number): void {\n const target = clamp(page, 0, Math.max(0, this.#source.pageCount - 1));\n this.#startFlip(this.#spreadIndexForPage(target));\n }\n\n getZoom(): number {\n return this.#scale;\n }\n\n /** Zoom to `scale` (clamped to [1, zoom.max]), keeping `center` (container-local) fixed. */\n setZoom(scale: number, center?: { x: number; y: number }): void {\n if (!this.#renderer || !this.#zoomEnabled) return;\n const s2 = clamp(scale, 1, this.#maxZoom);\n const m = this.#renderer.measure();\n const focal = center ?? { x: m.containerWidth / 2, y: m.containerHeight / 2 };\n const s1 = this.#scale;\n // Solve for the translate that keeps the focal screen point fixed as s1→s2.\n let tx = s2 === 1 ? 0 : focal.x - (s2 / s1) * (focal.x - this.#tx);\n let ty = s2 === 1 ? 0 : focal.y - (s2 / s1) * (focal.y - this.#ty);\n [tx, ty] = this.#clampPan(tx, ty, s2, m.containerWidth, m.containerHeight);\n this.#scale = s2;\n this.#tx = tx;\n this.#ty = ty;\n this.#renderer.setViewTransform(s2, tx, ty);\n this.#emitter.emit('zoomChanged', { scale: s2 });\n }\n\n resetZoom(): void {\n this.setZoom(1);\n }\n\n #clampPan(tx: number, ty: number, scale: number, w: number, h: number): [number, number] {\n // Keep the scaled content covering the viewport (transform-origin is 0,0).\n return [clamp(tx, w * (1 - scale), 0), clamp(ty, h * (1 - scale), 0)];\n }\n\n on<K extends keyof ZineEventMap>(\n event: K,\n listener: (payload: ZineEventMap[K]) => void,\n ): () => void {\n return this.#emitter.on(event, listener);\n }\n\n destroy(): void {\n this.#destroyed = true;\n if (this.#raf !== null) cancelAnimationFrame(this.#raf);\n this.#clearPendingClickFlip();\n this.#resizeObserver?.disconnect();\n this.#a11yCleanup?.();\n this.#unbindWheel?.();\n this.#unbindDblClick?.();\n this.#unbindInput?.();\n this.#renderer?.destroy();\n this.#renderer = null;\n this.#source.destroy();\n this.#emitter.clear();\n }\n\n #startFlip(targetIndex: number): void {\n if (targetIndex < 0 || targetIndex >= this.#spreads.length || targetIndex === this.#current) {\n return;\n }\n // `flip` is legal only from idle; otherwise a flip/drag is already in flight.\n if (this.#machine.send('flip') === null) return;\n\n const direction: FlipDirection = targetIndex > this.#current ? 'forward' : 'backward';\n const toPage = this.#leadPage(targetIndex);\n // State is already locked (send('flip') above), so re-entrant flips are rejected\n // even though staging the destination content below is async.\n this.#emitter.emit('flipStart', { from: this.#currentPage, to: toPage });\n void this.#runFlip(targetIndex, direction, toPage);\n }\n\n async #runFlip(targetIndex: number, direction: FlipDirection, toPage: number): Promise<void> {\n const toSpread = this.#spreads[targetIndex];\n const toContent: SpreadContent = toSpread\n ? await this.#resolveContent(toSpread)\n : { left: null, right: null };\n this.#renderer?.beginFlip(this.#currentContent, toContent, direction, {\n fill: this.#singlePage,\n });\n this.#animateProgress(0, 1, direction, () => this.#commit(targetIndex, toPage, toContent));\n }\n\n /** Animate the fold from `fromT` to `toT`, easing per-frame, then run `onDone`. */\n #animateProgress(\n fromT: number,\n toT: number,\n direction: FlipDirection,\n onDone: () => void,\n ): void {\n const duration = this.#effectiveDuration() * Math.abs(toT - fromT);\n if (duration <= 0) {\n // Reduced motion (or zero-duration): swap without the curl sweep.\n this.#renderer?.setFlipProgress(toT, direction);\n onDone();\n return;\n }\n const start = performance.now();\n const step = (now: number): void => {\n // Easing lives here; flipProgressToPose stays linear so seeks are deterministic.\n const raw = Math.min(1, (now - start) / duration);\n this.#renderer?.setFlipProgress(fromT + (toT - fromT) * easeInOutCubic(raw), direction);\n if (raw < 1) {\n this.#raf = requestAnimationFrame(step);\n } else {\n this.#raf = null;\n onDone();\n }\n };\n this.#raf = requestAnimationFrame(step);\n }\n\n #commit(targetIndex: number, toPage: number, toContent: SpreadContent): void {\n const spread = this.#spreads[targetIndex];\n this.#current = targetIndex;\n this.#currentPage = toPage;\n this.#currentContent = toContent;\n // renderSpread paints the landed spread and clears the turning leaf.\n if (spread) this.#paintSpread(spread, toContent);\n this.#prefetchWindow();\n this.#machine.send('settle');\n this.#announce();\n this.#emitter.emit('pageChanged', { page: toPage });\n this.#emitter.emit('flipEnd', { page: toPage });\n }\n\n #leadPage(spreadIndex: number): number {\n const spread = this.#spreads[spreadIndex];\n if (!spread) return this.#currentPage;\n const pages = [spread.left, spread.right].filter((p): p is number => p !== null);\n return pages.length > 0 ? Math.min(...pages) : this.#currentPage;\n }\n\n #onDragStart(clientX: number, clientY: number): void {\n if (this.#pinching || !this.#renderer || this.#machine.state !== 'idle') return;\n this.#clearPendingClickFlip(); // a new press cancels a click-flip still waiting out its window\n // Zoomed in → a drag pans; at scale 1 → a corner drag flips (§9 mode switch).\n if (this.#scale > 1) {\n if (this.#machine.send('panStart') === null) return;\n this.#pan = { baseTx: this.#tx, baseTy: this.#ty };\n return;\n }\n const rect = this.#container.getBoundingClientRect();\n const point = { x: clientX - rect.left, y: clientY - rect.top };\n this.#press = point; // remembered for tap classification / click-to-flip zone\n const { containerWidth, containerHeight } = this.#renderer.measure();\n const cornerSize = Math.min(containerWidth, containerHeight) * CORNER_FRACTION;\n if (hitTest(point, { width: containerWidth, height: containerHeight }, cornerSize) !== 'corner') {\n return; // not a corner — no drag; a tap here may still click-to-flip on release\n }\n // Arm a potential drag; it only becomes a real flip once the pointer moves\n // (so a corner *tap* never fires a spurious flipStart). Right-side corner\n // turns the page forward in LTR; RTL mirrors it.\n const rightSide = point.x > containerWidth / 2;\n const forward = this.#direction === 'rtl' ? !rightSide : rightSide;\n const targetIndex = this.#current + (forward ? 1 : -1);\n if (targetIndex < 0 || targetIndex >= this.#spreads.length) return;\n this.#pendingGrab = {\n direction: forward ? 'forward' : 'backward',\n targetIndex,\n toPage: this.#leadPage(targetIndex),\n width: containerWidth,\n };\n }\n\n /** Turn an armed corner press into a live drag flip once the pointer has moved. */\n #promoteGrab(): void {\n const grab = this.#pendingGrab;\n if (!grab) return;\n this.#pendingGrab = null;\n if (this.#machine.send('grab') === null) return;\n this.#drag = {\n direction: grab.direction,\n targetIndex: grab.targetIndex,\n toPage: grab.toPage,\n toContent: { left: null, right: null },\n width: grab.width,\n t: 0,\n };\n this.#emitter.emit('flipStart', { from: this.#currentPage, to: grab.toPage });\n void this.#stageDrag(grab.targetIndex, grab.direction);\n }\n\n async #stageDrag(targetIndex: number, direction: FlipDirection): Promise<void> {\n const toSpread = this.#spreads[targetIndex];\n const toContent: SpreadContent = toSpread\n ? await this.#resolveContent(toSpread)\n : { left: null, right: null };\n // The drag may have ended (or retargeted) while content was resolving.\n if (this.#drag?.targetIndex !== targetIndex) return;\n this.#drag.toContent = toContent;\n this.#renderer?.beginFlip(this.#currentContent, toContent, direction, {\n fill: this.#singlePage,\n });\n this.#renderer?.setFlipProgress(this.#drag.t, direction);\n }\n\n #onDragMove(dx: number, dy: number): void {\n if (this.#pinching) return;\n if (this.#pan) {\n if (!this.#renderer) return;\n const m = this.#renderer.measure();\n const [tx, ty] = this.#clampPan(\n this.#pan.baseTx + dx,\n this.#pan.baseTy + dy,\n this.#scale,\n m.containerWidth,\n m.containerHeight,\n );\n this.#tx = tx;\n this.#ty = ty;\n this.#renderer.setViewTransform(this.#scale, tx, ty);\n return;\n }\n // An armed corner press becomes a real flip once it moves past the threshold.\n if (this.#pendingGrab && Math.hypot(dx, dy) > DRAG_THRESHOLD) {\n this.#promoteGrab();\n }\n const drag = this.#drag;\n if (!drag) return;\n const signed = drag.direction === 'forward' ? -dx : dx;\n drag.t = clamp(signed / drag.width, 0, 1);\n this.#renderer?.setFlipProgress(drag.t, drag.direction);\n }\n\n #onDragEnd(gesture: GestureEnd): void {\n if (this.#pinching) return;\n if (this.#pan) {\n this.#pan = null;\n this.#machine.send('panEnd');\n return;\n }\n const drag = this.#drag;\n if (!drag) {\n // Never became a drag → it was a tap; maybe flip via clickToFlip.\n this.#pendingGrab = null;\n this.#maybeClickFlip(gesture);\n return;\n }\n this.#drag = null;\n this.#machine.send('release');\n\n const swiped =\n gesture.swipe &&\n (drag.direction === 'forward' ? gesture.dx < 0 : gesture.dx > 0);\n if (drag.t >= 0.5 || swiped) {\n this.#animateProgress(drag.t, 1, drag.direction, () =>\n this.#commit(drag.targetIndex, drag.toPage, drag.toContent),\n );\n } else {\n this.#animateProgress(drag.t, 0, drag.direction, () => this.#cancelFlip());\n }\n }\n\n #maybeClickFlip(gesture: GestureEnd): void {\n if (this.#clickToFlip === 'off' || this.#scale > 1 || !this.#press) return;\n // A tap barely moves; anything more was a drag we already ignored.\n if (Math.abs(gesture.dx) > DRAG_THRESHOLD || Math.abs(gesture.dy) > DRAG_THRESHOLD) return;\n const direction = this.#clickFlipDirection(this.#press);\n if (!direction) return;\n const targetIndex = this.#current + (direction === 'forward' ? 1 : -1);\n if (targetIndex < 0 || targetIndex >= this.#spreads.length) return;\n this.#clearPendingClickFlip();\n if (this.#clickFlipDelayValue <= 0) {\n // No double-click competing here → flip right away.\n this.#startFlip(targetIndex);\n return;\n }\n // Wait out the window; a double-click (zoom) cancels this.\n this.#pendingClickTimer = setTimeout(() => {\n this.#pendingClickTimer = null;\n this.#startFlip(targetIndex);\n }, this.#clickFlipDelayValue);\n }\n\n /** Which way a tap at `point` (container-local) turns the page, or null for a dead zone. */\n #clickFlipDirection(point: { x: number; y: number }): FlipDirection | null {\n if (!this.#renderer) return null;\n const { containerWidth } = this.#renderer.measure();\n let side: 'left' | 'right' | null;\n if (this.#clickToFlip === 'half') {\n side = point.x > containerWidth / 2 ? 'right' : 'left';\n } else if (point.x <= this.#clickZoneSize) {\n side = 'left';\n } else if (point.x >= containerWidth - this.#clickZoneSize) {\n side = 'right';\n } else {\n side = null; // center dead zone in 'edge' mode\n }\n if (!side) return null;\n const forwardSide = this.#direction === 'rtl' ? 'left' : 'right';\n return side === forwardSide ? 'forward' : 'backward';\n }\n\n #clearPendingClickFlip(): void {\n if (this.#pendingClickTimer !== null) {\n clearTimeout(this.#pendingClickTimer);\n this.#pendingClickTimer = null;\n }\n }\n\n #cancelFlip(): void {\n const spread = this.#spreads[this.#current];\n if (spread) this.#paintSpread(spread, this.#currentContent);\n this.#machine.send('settle');\n this.#emitter.emit('flipEnd', { page: this.#currentPage });\n }\n\n #onPinchStart(): void {\n // A second finger abandons any single-pointer gesture in flight.\n this.#pendingGrab = null;\n this.#clearPendingClickFlip();\n if (this.#drag) {\n this.#drag = null;\n this.#machine.send('release');\n this.#machine.send('settle');\n const spread = this.#spreads[this.#current];\n if (spread) this.#paintSpread(spread, this.#currentContent);\n } else if (this.#pan) {\n this.#pan = null;\n this.#machine.send('panEnd');\n }\n this.#pinching = true;\n this.#pinchBaseScale = this.#scale;\n }\n\n #onPinchMove(centerX: number, centerY: number, scale: number): void {\n if (!this.#pinching) return;\n const rect = this.#container.getBoundingClientRect();\n this.setZoom(this.#pinchBaseScale * scale, { x: centerX - rect.left, y: centerY - rect.top });\n }\n\n #onPinchEnd(): void {\n this.#pinching = false;\n }\n\n #bindWheelZoom(): void {\n const onWheel = (event: WheelEvent): void => {\n // Ctrl/⌘ + wheel only — this is also what a desktop trackpad pinch emits.\n if (!this.#wheelZoom || !this.#zoomEnabled || !(event.ctrlKey || event.metaKey)) return;\n // Override the browser's native page zoom.\n event.preventDefault();\n const rect = this.#container.getBoundingClientRect();\n const factor = Math.exp(-event.deltaY * WHEEL_ZOOM_SENSITIVITY);\n this.setZoom(this.#scale * factor, {\n x: event.clientX - rect.left,\n y: event.clientY - rect.top,\n });\n };\n this.#container.addEventListener('wheel', onWheel as EventListener, { passive: false });\n this.#unbindWheel = () =>\n this.#container.removeEventListener('wheel', onWheel as EventListener);\n }\n\n #bindDoubleClickZoom(): void {\n const onDoubleClick = (event: MouseEvent): void => {\n const levels = this.#doubleClickLevels;\n if (!this.#zoomEnabled || levels === null) return;\n // At scale 1 a double-click inside a flip zone belongs to click-to-flip, not zoom,\n // unless we're honoring double-click zoom there.\n if (this.#scale <= 1 && this.#clickToFlip !== 'off' && !this.#honorDoubleClickInFlipZone) {\n const rect = this.#container.getBoundingClientRect();\n const local = { x: event.clientX - rect.left, y: event.clientY - rect.top };\n if (this.#clickFlipDirection(local) !== null) return; // in a flip zone → leave it to click-to-flip\n }\n // A double-click means the single-click flip we may have queued was really a zoom.\n this.#clearPendingClickFlip();\n event.preventDefault();\n // Next configured level above the current scale, else wrap to the first.\n const next = levels.find((l) => l > this.#scale + 1e-6) ?? levels[0] ?? this.#scale;\n const rect = this.#container.getBoundingClientRect();\n this.setZoom(next, { x: event.clientX - rect.left, y: event.clientY - rect.top });\n };\n this.#container.addEventListener('dblclick', onDoubleClick as EventListener);\n this.#unbindDblClick = () =>\n this.#container.removeEventListener('dblclick', onDoubleClick as EventListener);\n }\n\n async #init(rendererOption: RendererOption): Promise<void> {\n // Load the renderer chunk while opening an async source (e.g. a PDF) in parallel.\n const rendererPromise = selectRenderer(rendererOption);\n if (typeof this.#source.open === 'function') {\n await this.#source.open();\n this.#buildSpreadModel(); // page count known now; validates + builds spreads\n }\n this.#source.prefetch([this.#currentPage]);\n\n const selected = await rendererPromise;\n const renderer = await this.#mountWithFallback(selected);\n this.#renderer = renderer;\n\n // Now that we can measure, apply single-page mode if the container is narrow.\n this.#applySinglePage(renderer.measure().containerWidth);\n\n const pointer = new PointerRecognizer({\n onStart: (g) => this.#onDragStart(g.x, g.y),\n onMove: (g) => this.#onDragMove(g.dx, g.dy),\n onEnd: (g) => this.#onDragEnd(g),\n });\n const pinch = new PinchRecognizer({\n onPinchStart: () => this.#onPinchStart(),\n onPinchMove: (g) => this.#onPinchMove(g.centerX, g.centerY, g.scale),\n onPinchEnd: () => this.#onPinchEnd(),\n });\n this.#unbindInput = bindGestures(this.#container, { pointer, pinch });\n this.#bindWheelZoom();\n this.#bindDoubleClickZoom();\n this.#setupReducedMotion();\n this.#a11yCleanup = this.#setupA11y();\n\n await this.#renderCurrent();\n this.#observeResize();\n this.#prefetchWindow();\n this.#announce();\n this.#emitter.emit('ready');\n }\n\n /** Mount `renderer`; if it can't initialize (e.g. no WebGL2 context) fall back to CSS. */\n async #mountWithFallback(renderer: Renderer): Promise<Renderer> {\n try {\n await renderer.mount(this.#container);\n renderer.onFatal?.(() => {\n void this.#fallbackToCss();\n });\n return renderer;\n } catch {\n renderer.destroy();\n const css = await selectRenderer('css');\n await css.mount(this.#container);\n this.#fellBack = true;\n this.#emitter.emit('rendererFallback', { from: 'webgl2', to: 'css' });\n return css;\n }\n }\n\n /** Runtime fallback: a live renderer signaled an unrecoverable failure (§8.4). */\n async #fallbackToCss(): Promise<void> {\n if (this.#fellBack || this.#destroyed) return;\n this.#fellBack = true;\n this.#renderer?.destroy();\n this.#renderer = null;\n const css = await selectRenderer('css');\n if (this.#destroyed) {\n css.destroy();\n return;\n }\n await css.mount(this.#container);\n this.#renderer = css;\n this.#applySinglePage(css.measure().containerWidth);\n await this.#renderCurrent();\n this.#emitter.emit('rendererFallback', { from: 'webgl2', to: 'css' });\n }\n\n #setupReducedMotion(): void {\n if (typeof matchMedia !== 'function') return;\n const query = matchMedia('(prefers-reduced-motion: reduce)');\n this.#reducedMotion = query.matches;\n query.addEventListener?.('change', (e) => {\n this.#reducedMotion = e.matches;\n });\n }\n\n /** Wire keyboard nav + an aria-live page announcer. Skips non-DOM containers. */\n #setupA11y(): (() => void) | null {\n const container = this.#container;\n const doc = container.ownerDocument;\n if (!doc || typeof container.setAttribute !== 'function') return null;\n\n if (!container.hasAttribute('tabindex')) container.tabIndex = 0;\n container.setAttribute('aria-roledescription', 'flipbook');\n const onKey = (e: KeyboardEvent): void => this.#onKeyDown(e);\n container.addEventListener('keydown', onKey);\n\n const live = doc.createElement('div');\n live.setAttribute('aria-live', 'polite');\n live.setAttribute('aria-atomic', 'true');\n live.style.cssText =\n 'position:absolute;width:1px;height:1px;margin:-1px;padding:0;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap;border:0;';\n container.appendChild(live);\n this.#liveRegion = live;\n\n return () => {\n container.removeEventListener('keydown', onKey);\n live.remove();\n this.#liveRegion = null;\n };\n }\n\n #onKeyDown(event: KeyboardEvent): void {\n const forwardKey = this.#direction === 'rtl' ? 'ArrowLeft' : 'ArrowRight';\n switch (event.key) {\n case 'ArrowRight':\n case 'ArrowLeft':\n if (event.key === forwardKey) this.flipNext();\n else this.flipPrev();\n event.preventDefault();\n break;\n case 'Home':\n this.flipTo(0);\n event.preventDefault();\n break;\n case 'End':\n this.flipTo(this.#source.pageCount - 1);\n event.preventDefault();\n break;\n default:\n break;\n }\n }\n\n #announce(): void {\n if (this.#liveRegion) {\n this.#liveRegion.textContent = `Page ${this.#currentPage + 1} of ${this.#source.pageCount}`;\n }\n }\n\n #effectiveDuration(): number {\n return this.#reducedMotion ? 0 : this.#flipDuration;\n }\n\n /** Re-measure and re-render; call after the container resizes. */\n update(): void {\n if (!this.#renderer || this.#machine.state !== 'idle') return;\n this.#applySinglePage(this.#renderer.measure().containerWidth);\n void this.#renderCurrent();\n }\n\n #applySinglePage(containerWidth: number): void {\n const single = shouldSinglePage(containerWidth, this.#singlePageThreshold);\n if (single === this.#singlePage) return;\n this.#singlePage = single;\n this.#spreads = buildSpreads(this.#source.pageCount, {\n direction: this.#direction,\n cover: this.#cover,\n singlePage: single,\n });\n this.#current = this.#spreadIndexForPage(this.#currentPage);\n }\n\n async #renderCurrent(): Promise<void> {\n const spread = this.#spreads[this.#current];\n if (!spread || !this.#renderer) return;\n this.#currentContent = await this.#resolveContent(spread);\n this.#paintSpread(spread, this.#currentContent);\n }\n\n #paintSpread(spread: Spread, content: SpreadContent): void {\n this.#renderer?.renderSpread(spread, content, { fill: this.#singlePage });\n }\n\n #observeResize(): void {\n if (typeof ResizeObserver === 'undefined') return;\n this.#resizeObserver = new ResizeObserver(() => this.#scheduleUpdate());\n this.#resizeObserver.observe(this.#container);\n }\n\n #scheduleUpdate(): void {\n if (this.#updateScheduled) return;\n this.#updateScheduled = true;\n requestAnimationFrame(() => {\n this.#updateScheduled = false;\n this.update();\n });\n }\n\n async #resolveContent(spread: Spread): Promise<SpreadContent> {\n const [left, right] = await Promise.all([this.#getPage(spread.left), this.#getPage(spread.right)]);\n return { left, right };\n }\n\n /** Decode one page; on failure emit `sourceError` and degrade to a blank (null) page. */\n async #getPage(index: number | null): Promise<PageContent | null> {\n if (index === null) return null;\n try {\n return await this.#source.get(index);\n } catch (error) {\n this.#emitter.emit('sourceError', { index, error });\n return null;\n }\n }\n\n #prefetchWindow(): void {\n const { toMount } = this.#virtualizer.update(this.#current, this.#spreads.length);\n const pages: number[] = [];\n for (const index of toMount) {\n const spread = this.#spreads[index];\n if (spread?.left != null) pages.push(spread.left);\n if (spread?.right != null) pages.push(spread.right);\n }\n this.#source.prefetch(pages);\n }\n\n #spreadIndexForPage(page: number): number {\n const index = this.#spreads.findIndex((s) => s.left === page || s.right === page);\n return index === -1 ? 0 : index;\n }\n\n /** Validate the (now-known) page count + startPage and build the spread model. */\n #buildSpreadModel(): void {\n const pageCount = this.#source.pageCount;\n if (!Number.isInteger(pageCount) || pageCount < 1) {\n throw new Error(`Zine: source has ${pageCount} pages; a Source must have at least 1 page.`);\n }\n const startPage = this.#startPageOption;\n if (\n startPage !== undefined &&\n (!Number.isInteger(startPage) || startPage < 0 || startPage >= pageCount)\n ) {\n throw new Error(\n `Zine: startPage ${JSON.stringify(startPage)} is out of range for a ${pageCount}-page book (valid 0..${pageCount - 1}).`,\n );\n }\n this.#spreads = buildSpreads(pageCount, { direction: this.#direction, cover: this.#cover });\n this.#currentPage = clamp(startPage ?? 0, 0, pageCount - 1);\n this.#current = this.#spreadIndexForPage(this.#currentPage);\n }\n}\n\nfunction clamp(value: number, min: number, max: number): number {\n return value < min ? min : value > max ? max : value;\n}\n\nfunction easeInOutCubic(t: number): number {\n return t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2;\n}\n\nfunction typeName(v: unknown): string {\n if (v === null) return 'null';\n if (Array.isArray(v)) return 'array';\n return typeof v;\n}\n\n/** Validate constructor inputs up front, throwing agent-actionable errors. */\nfunction validateOptions(container: unknown, options: unknown): void {\n if (\n typeof container !== 'object' ||\n container === null ||\n typeof (container as { appendChild?: unknown }).appendChild !== 'function' ||\n typeof (container as { addEventListener?: unknown }).addEventListener !== 'function'\n ) {\n throw new Error(`Zine: container must be a DOM element; received ${typeName(container)}.`);\n }\n if (typeof options !== 'object' || options === null) {\n throw new Error('Zine: an options object with a `source` is required.');\n }\n const o = options as Record<string, unknown>;\n\n const source = o.source as { get?: unknown; pageCount?: unknown } | undefined;\n if (\n typeof source !== 'object' ||\n source === null ||\n typeof source.get !== 'function' ||\n typeof source.pageCount !== 'number'\n ) {\n throw new Error('Zine: `source` is required and must be a Source, e.g. new ImageSource(urls).');\n }\n // Note: pageCount >= 1 and startPage-in-range are validated in #buildSpreadModel —\n // synchronously for a sync source, or after open() for an async one (e.g. PdfSource).\n\n const startPage = o.startPage;\n if (startPage !== undefined && (typeof startPage !== 'number' || !Number.isInteger(startPage) || startPage < 0)) {\n throw new Error(`Zine: startPage must be a non-negative integer; got ${JSON.stringify(startPage)}.`);\n }\n\n const direction = o.direction;\n if (direction !== undefined && direction !== 'ltr' && direction !== 'rtl') {\n throw new Error(`Zine: direction must be 'ltr' or 'rtl'; got ${JSON.stringify(direction)}.`);\n }\n\n const clickToFlip = o.clickToFlip;\n if (clickToFlip !== undefined && !['edge', 'half', 'off'].includes(clickToFlip as string)) {\n throw new Error(`Zine: clickToFlip must be 'edge', 'half', or 'off'; got ${JSON.stringify(clickToFlip)}.`);\n }\n\n assertMin(o.width, 'width', 1);\n assertMin(o.height, 'height', 1);\n assertMin(o.flipDuration, 'flipDuration', 0);\n assertMin(o.clickZoneSize, 'clickZoneSize', 0);\n assertMin(o.clickFlipDelay, 'clickFlipDelay', 0);\n assertMin(o.singlePageThreshold, 'singlePageThreshold', 0);\n validateZoomOption(o.zoom);\n validateRendererOption(o.renderer);\n}\n\nfunction assertMin(value: unknown, name: string, min: number): void {\n if (value === undefined) return;\n if (typeof value !== 'number' || !Number.isFinite(value) || value < min) {\n throw new Error(`Zine: ${name} must be a number >= ${min}; got ${JSON.stringify(value)}.`);\n }\n}\n\nfunction validateZoomOption(zoom: unknown): void {\n if (zoom === undefined) return;\n if (typeof zoom !== 'object' || zoom === null || Array.isArray(zoom)) {\n throw new Error('Zine: zoom must be an object, e.g. { max: 4 }.');\n }\n const z = zoom as Record<string, unknown>;\n if (z.enabled !== undefined && typeof z.enabled !== 'boolean') {\n throw new Error(`Zine: zoom.enabled must be a boolean; got ${JSON.stringify(z.enabled)}.`);\n }\n if (z.wheel !== undefined && typeof z.wheel !== 'boolean') {\n throw new Error(`Zine: zoom.wheel must be a boolean; got ${JSON.stringify(z.wheel)}.`);\n }\n if (z.doubleClickInFlipZone !== undefined && typeof z.doubleClickInFlipZone !== 'boolean') {\n throw new Error(\n `Zine: zoom.doubleClickInFlipZone must be a boolean; got ${JSON.stringify(z.doubleClickInFlipZone)}.`,\n );\n }\n if (z.doubleClick !== undefined && z.doubleClick !== false) {\n const levels = z.doubleClick;\n if (\n !Array.isArray(levels) ||\n levels.some((n) => typeof n !== 'number' || !Number.isFinite(n) || n < 1)\n ) {\n throw new Error(\n 'Zine: zoom.doubleClick must be false or an array of zoom levels >= 1, e.g. [1, 2, 4].',\n );\n }\n }\n assertMin(z.max, 'zoom.max', 1);\n}\n\nfunction validateRendererOption(renderer: unknown): void {\n if (renderer === undefined) return;\n if (typeof renderer === 'string') {\n if (renderer !== 'auto' && renderer !== 'css' && renderer !== 'webgl2') {\n throw new Error(\n `Zine: renderer '${renderer}' is not recognized; use 'auto', 'css', 'webgl2', an array of those, or a custom Renderer.`,\n );\n }\n return;\n }\n if (Array.isArray(renderer)) {\n for (const kind of renderer) {\n if (kind !== 'css' && kind !== 'webgl2') {\n throw new Error(\n `Zine: renderer order array may only contain 'css' or 'webgl2'; got ${JSON.stringify(kind)}.`,\n );\n }\n }\n return;\n }\n if (\n typeof renderer === 'object' &&\n renderer !== null &&\n typeof (renderer as { mount?: unknown }).mount === 'function'\n ) {\n return;\n }\n throw new Error(\n \"Zine: renderer must be 'auto', 'css', 'webgl2', an array of those, or a custom Renderer instance.\",\n );\n}\n","import type { PageContent } from '../renderer/types';\nimport type { Source } from './types';\n\nexport type ImageFit = 'contain' | 'cover';\n\nexport interface ImageSourceOptions {\n /** How many adjacent pages to prefetch around a requested page. Default 1. */\n preload?: number;\n /** How each image fits its page; a hint consumed by the render layer. Default 'contain'. */\n fit?: ImageFit;\n}\n\n/**\n * Default content source for image books: decodes a list of image URLs to\n * ImageBitmaps, memoizes them, and prefetches neighbors on access.\n */\nexport class ImageSource implements Source {\n readonly pageCount: number;\n readonly fit: ImageFit;\n #urls: string[];\n #preload: number;\n #cache = new Map<number, Promise<ImageBitmap>>();\n\n constructor(urls: string[], options: ImageSourceOptions = {}) {\n this.#urls = urls;\n this.pageCount = urls.length;\n this.#preload = options.preload ?? 1;\n this.fit = options.fit ?? 'contain';\n }\n\n get(index: number): Promise<PageContent> {\n const decoded = this.#decode(index);\n for (let d = 1; d <= this.#preload; d++) {\n this.prefetch([index - d, index + d]);\n }\n return decoded;\n }\n\n prefetch(indices: number[]): void {\n for (const i of indices) {\n if (i >= 0 && i < this.pageCount) {\n void this.#decode(i).catch(() => {}); // swallow: prefetch failures surface on real get()\n }\n }\n }\n\n destroy(): void {\n for (const pending of this.#cache.values()) {\n void pending.then((bitmap) => bitmap.close()).catch(() => {});\n }\n this.#cache.clear();\n }\n\n #decode(index: number): Promise<ImageBitmap> {\n const cached = this.#cache.get(index);\n if (cached) return cached;\n\n const url = this.#urls[index];\n if (url === undefined) {\n return Promise.reject(\n new RangeError(`ImageSource: page ${index} is out of range (0..${this.pageCount - 1}).`),\n );\n }\n\n const promise = (async () => {\n const res = await fetch(url);\n if (!res.ok) {\n throw new Error(`ImageSource: failed to fetch page ${index} (${url}) — HTTP ${res.status}.`);\n }\n return createImageBitmap(await res.blob());\n })().catch((err: unknown) => {\n this.#cache.delete(index); // drop the failed entry so a later get() can retry\n throw err;\n });\n\n this.#cache.set(index, promise);\n return promise;\n }\n}\n"],"mappings":"sfAwBA,SAAgB,EAAa,EAAmB,EAAyB,CAAC,EAAa,CACrF,GAAM,CAAE,YAAY,MAAO,QAAQ,GAAO,aAAa,IAAU,EACjE,GAAI,GAAa,EAAG,MAAO,CAAC,EAE5B,IAAM,EAAQ,GAA8B,GAAK,GAAK,EAAI,EAAY,EAAI,KACpE,EAAoB,CAAC,EAE3B,GAAI,EACF,IAAK,IAAI,EAAI,EAAG,EAAI,EAAW,IAC7B,EAAQ,KAAK,CAAE,KAAM,KAAM,MAAO,CAAE,CAAC,OAElC,GAAI,EAAO,CAChB,EAAQ,KAAK,CAAE,KAAM,KAAM,MAAO,CAAE,CAAC,EACrC,IAAK,IAAI,EAAI,EAAG,EAAI,EAAW,GAAK,EAClC,EAAQ,KAAK,CAAE,KAAM,EAAK,CAAC,EAAG,MAAO,EAA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CACpB,CAEA,GAAQ,EAAqC,CAC3C,IAAM,EAAS,KAAKA,GAAO,IAAI,CAAK,EACpC,GAAI,EAAQ,OAAO,EAEnB,IAAM,EAAM,KAAKH,GAAM,GACvB,GAAI,IAAQ,IAAA,GACV,OAAO,QAAQ,OACT,WAAW,qBAAqB,EAAM,uBAAuB,KAAK,UAAY,EAAE,GAAG,CACzF,EAGF,IAAM,GAAW,SAAY,CAC3B,IAAM,EAAM,MAAM,MAAM,CAAG,EAC3B,GAAI,CAAC,EAAI,GACP,MAAU,MAAM,qCAAqC,EAAM,IAAI,EAAI,WAAW,EAAI,OAAO,EAAE,EAE7F,OAAO,kBAAkB,MAAM,EAAI,KAAK,CAAC,CAC3C,EAAA,CAAG,CAAC,CAAC,MAAO,GAAiB,CAE3B,MADA,KAAKG,GAAO,OAAO,CAAK,EAClB,CACR,CAAC,EAGD,OADA,KAAKA,GAAO,IAAI,EAAO,CAAO,EACvB,CACT,CACF"}
1
+ {"version":3,"file":"index.umd.cjs","names":["#radius","#mounted","#listeners","#state","#handlers","#activeId","#start","#prev","#last","#end","#reset","#pinching","#points","#pair","#startDistance","#remove","#container","#clip","#viewport","#book","#pageLeft","#makeCanvas","#pageRight","#leaf","#leafFront","#leafBack","#leafShadow","#paint","#fill","#contentShift","#trackAspect","#layoutBook","#applyShift","#fromShiftUnit","#toShiftUnit","#bookW","#pageAspect","#bookBox","#contentBox","#container","#canvas","#onContextLost","#onContextRestored","#onVisibilityChange","#gl","#buildGlResources","#clearRestoreTimer","#texCache","#blankTex","#quadVao","#curlVao","#flat","#curl","#cacheBytes","#content","#flip","#fatalHandler","#fill","#trackAspect","#render","#pageAspect","#flipT","#curlType","#anchor","#fromShiftUnit","#toShiftUnit","#view","#bookBox","#contentBox","#contextLost","#restoreTimer","#fatal","#fatalFired","#flatU","#curlU","#makeQuadVao","#buildCurlMesh","#makeBlankTexture","#idxCount","#posBuf","#normBuf","#mesh","#resize","#fitBook","#drawFlip","#drawStatic","#bookW","#bookH","#shiftX","#useFlat","#drawQuad","#bindFace","#dpr","#textureFor","#evictTextures","#base","#front","#back","#rawPages","#resolvePages","#image","#resolved","#cache","#renderer","#container","#source","#direction","#spreadMode","#curl","#clickToFlip","#clickZoneSize","#singlePageThreshold","#startPageOption","#buildSpreadModel","#flipDuration","#zoomEnabled","#wheelZoom","#doubleClickLevels","#maxZoom","#honorDoubleClickInFlipZone","#clickFlipDelayValue","#ready","#init","#currentPage","#startFlip","#current","#spreadIndexForPage","#scale","#tx","#ty","#clampPan","#emitter","#destroyed","#raf","#clearPendingClickFlip","#resizeObserver","#a11yCleanup","#unbindWheel","#unbindDblClick","#unbindInput","#spreads","#machine","#leadPage","#runFlip","#resolveContent","#currentContent","#singlePage","#anchorY","#animateProgress","#commit","#effectiveDuration","#paintSpread","#prefetchWindow","#announce","#pinching","#pan","#contentRect","#press","#pendingGrab","#drag","#stageDrag","#promoteGrab","#maybeClickFlip","#cancelFlip","#clickFlipDirection","#pendingClickTimer","#pinchBaseScale","#mountWithFallback","#onPageUpdate","#applySinglePage","#onDragStart","#onDragMove","#onDragEnd","#onPinchStart","#onPinchMove","#onPinchEnd","#bindWheelZoom","#bindDoubleClickZoom","#setupReducedMotion","#setupA11y","#renderCurrent","#observeResize","#fallbackToCss","#fellBack","#reducedMotion","#onKeyDown","#liveRegion","#narrow","#effectiveMode","#applyContainerAspect","#lastAspect","#scheduleUpdate","#updateScheduled","#getPage","#virtualizer","#urls","#preload","#decode","#cache"],"sources":["../src/engine/spread.ts","../src/engine/virtualizer.ts","../src/engine/emitter.ts","../src/engine/stateMachine.ts","../src/engine/input.ts","../src/geometry/hitTest.ts","../src/geometry/curls/types.ts","../src/geometry/flipProgressToPose.ts","../src/renderer/cssRenderer.ts","../src/geometry/curls/mesh.ts","../src/geometry/curls/roll.ts","../src/geometry/curls/simple.ts","../src/geometry/curls/fold.ts","../src/geometry/curls/peel.ts","../src/geometry/curls/index.ts","../src/renderer/gl/context.ts","../src/renderer/gl/program.ts","../src/renderer/gl/texture.ts","../src/renderer/webglRenderer.ts","../src/renderer/select.ts","../src/source/compose.ts","../src/zine.ts","../src/source/imageSource.ts","../src/index.ts"],"sourcesContent":["export type Direction = 'ltr' | 'rtl';\n\n/**\n * How pages group into spreads:\n * - `double`: paired from the start — `[0|1] [2|3] …`\n * - `single`: one page per spread — `[0] [1] …`\n * - `cover`: first page alone, then paired — `[·|0] [1|2] …`\n * - `book`: first AND last alone (front + back cover) — `[·|0] [1|2] … [N-1|·]`\n */\nexport type SpreadMode = 'double' | 'single' | 'cover' | 'book';\n\nexport interface Spread {\n /** Page index shown on the left, or null for a blank side. */\n left: number | null;\n /** Page index shown on the right, or null for a blank side. */\n right: number | null;\n}\n\nexport interface SpreadOptions {\n direction?: Direction;\n mode?: SpreadMode;\n}\n\n/**\n * Map a flat page list (indices 0..pageCount-1) into display spreads.\n *\n * Reading order is always preserved; `direction` only mirrors each spread's\n * left/right positions, so RTL is just an LTR layout with the sides swapped.\n * Out-of-range slots are `null` (a blank half on odd counts / a lone cover).\n */\nexport function buildSpreads(pageCount: number, options: SpreadOptions = {}): Spread[] {\n const { direction = 'ltr', mode = 'cover' } = options;\n if (pageCount <= 0) return [];\n\n const page = (i: number): number | null => (i >= 0 && i < pageCount ? i : null);\n const spreads: Spread[] = [];\n\n if (mode === 'single') {\n for (let i = 0; i < pageCount; i++) spreads.push({ left: null, right: i });\n } else if (mode === 'double') {\n for (let i = 0; i < pageCount; i += 2) spreads.push({ left: page(i), right: page(i + 1) });\n } else if (mode === 'cover') {\n spreads.push({ left: null, right: 0 });\n for (let i = 1; i < pageCount; i += 2) spreads.push({ left: page(i), right: page(i + 1) });\n } else {\n // book: front cover alone, interior paired, back cover alone\n spreads.push({ left: null, right: 0 });\n if (pageCount > 1) {\n for (let i = 1; i <= pageCount - 2; i += 2) {\n spreads.push({ left: page(i), right: i + 1 <= pageCount - 2 ? page(i + 1) : null });\n }\n spreads.push({ left: pageCount - 1, right: null });\n }\n }\n\n return direction === 'rtl'\n ? spreads.map((s) => ({ left: s.right, right: s.left }))\n : spreads;\n}\n\n/** Whether a container this wide should fall back to one page per spread. */\nexport function shouldSinglePage(containerWidth: number, threshold: number): boolean {\n return containerWidth < threshold;\n}\n","/** Spread indices that should be mounted around `current`, clamped to the book. */\nexport function mountWindow(current: number, spreadCount: number, radius: number): number[] {\n const window: number[] = [];\n const from = Math.max(0, current - radius);\n const to = Math.min(spreadCount - 1, current + radius);\n for (let i = from; i <= to; i++) {\n window.push(i);\n }\n return window;\n}\n\nexport interface VirtualizerDelta {\n toMount: number[];\n toEvict: number[];\n}\n\n/**\n * Tracks which spreads are mounted and, on each move, reports the difference:\n * spreads entering the ±radius window (`toMount`) and those leaving it\n * (`toEvict`). Default radius 2 = current spread ±2.\n */\nexport class Virtualizer {\n #radius: number;\n #mounted = new Set<number>();\n\n constructor(radius = 2) {\n this.#radius = radius;\n }\n\n get mounted(): number[] {\n return [...this.#mounted].sort((a, b) => a - b);\n }\n\n /** Recenter on `current`; mounts/evicts to match the window and returns the delta. */\n update(current: number, spreadCount: number): VirtualizerDelta {\n const window = new Set(mountWindow(current, spreadCount, this.#radius));\n const toMount = [...window].filter((i) => !this.#mounted.has(i)).sort((a, b) => a - b);\n const toEvict = [...this.#mounted].filter((i) => !window.has(i)).sort((a, b) => a - b);\n for (const i of toEvict) this.#mounted.delete(i);\n for (const i of toMount) this.#mounted.add(i);\n return { toMount, toEvict };\n }\n}\n","export type Listener<T> = (payload: T) => void;\n\n/** Events typed as `void` are emitted with no payload argument. */\ntype PayloadArgs<T> = [T] extends [void] ? [] : [payload: T];\n\n/** Minimal typed event emitter keyed by an event map. */\nexport class Emitter<Events> {\n #listeners = new Map<keyof Events, Set<Listener<unknown>>>();\n\n /** Subscribe; returns an unsubscribe function. */\n on<K extends keyof Events>(type: K, listener: Listener<Events[K]>): () => void {\n let set = this.#listeners.get(type);\n if (!set) {\n set = new Set();\n this.#listeners.set(type, set);\n }\n set.add(listener as Listener<unknown>);\n return () => this.off(type, listener);\n }\n\n off<K extends keyof Events>(type: K, listener: Listener<Events[K]>): void {\n this.#listeners.get(type)?.delete(listener as Listener<unknown>);\n }\n\n emit<K extends keyof Events>(type: K, ...args: PayloadArgs<Events[K]>): void {\n const payload = args[0] as Events[K];\n // Copy so a listener that unsubscribes mid-emit doesn't disturb iteration.\n const set = this.#listeners.get(type);\n if (!set) return;\n for (const listener of [...set]) {\n (listener as Listener<Events[K]>)(payload);\n }\n }\n\n clear(): void {\n this.#listeners.clear();\n }\n}\n\n/**\n * Public event surface of a Zine instance. Payloads are provisional and will\n * firm up as the engine wires the emitters that fire them.\n */\nexport interface ZineEventMap {\n ready: void;\n flipStart: { from: number; to: number };\n flipEnd: { page: number };\n pageChanged: { page: number };\n zoomChanged: { scale: number };\n sourceError: { index: number; error: unknown };\n rendererFallback: { from: string; to: string };\n}\n\nexport type ZineEmitter = Emitter<ZineEventMap>;\n","export type FlipState = 'idle' | 'dragging' | 'animating' | 'zoomed-panning';\n\nexport type FlipEvent = 'grab' | 'release' | 'settle' | 'panStart' | 'panEnd' | 'flip';\n\n/**\n * Legal transitions. A flip drag runs idle → dragging → animating → idle; a\n * programmatic flip jumps idle → animating directly via `flip`; zoom panning\n * (only reachable when zoomed in) is a separate branch idle → zoomed-panning →\n * idle. Any (state, event) pair absent here is illegal.\n */\nconst TRANSITIONS: Record<FlipState, Partial<Record<FlipEvent, FlipState>>> = {\n idle: { grab: 'dragging', panStart: 'zoomed-panning', flip: 'animating' },\n dragging: { release: 'animating' },\n animating: { settle: 'idle' },\n 'zoomed-panning': { panEnd: 'idle' },\n};\n\n/** Pure transition: the next state, or null if `event` is illegal from `state`. */\nexport function nextState(state: FlipState, event: FlipEvent): FlipState | null {\n return TRANSITIONS[state][event] ?? null;\n}\n\n/** Stateful holder around `nextState`; illegal events are ignored. */\nexport class FlipMachine {\n #state: FlipState;\n\n constructor(initial: FlipState = 'idle') {\n this.#state = initial;\n }\n\n get state(): FlipState {\n return this.#state;\n }\n\n /** Apply `event`; returns the new state, or null (no-op) if the event was illegal. */\n send(event: FlipEvent): FlipState | null {\n const next = nextState(this.#state, event);\n if (next !== null) {\n this.#state = next;\n }\n return next;\n }\n}\n","export interface GestureStart {\n x: number;\n y: number;\n t: number;\n}\n\nexport interface GestureMove {\n x: number;\n y: number;\n /** Displacement from the start point. */\n dx: number;\n dy: number;\n}\n\nexport interface GestureEnd {\n x: number;\n y: number;\n dx: number;\n dy: number;\n /** Elapsed time from start to end (ms). */\n dt: number;\n /** Velocity of the final move segment (px/ms). */\n vx: number;\n vy: number;\n /** A fast flick: final speed exceeded the swipe threshold and the gesture was not canceled. */\n swipe: boolean;\n /** The pointer was canceled (e.g. pointercancel) rather than lifted. */\n canceled: boolean;\n}\n\nexport interface PointerHandlers {\n onStart?: (g: GestureStart) => void;\n onMove?: (g: GestureMove) => void;\n onEnd?: (g: GestureEnd) => void;\n}\n\n/** Flick threshold in px/ms; a release faster than this is a swipe. */\nconst SWIPE_VELOCITY = 0.3;\n\ninterface Sample {\n x: number;\n y: number;\n t: number;\n}\n\n/**\n * Recognizes a single-pointer drag from raw pointer samples and reports normalized\n * gestures. DOM-agnostic on purpose: `bindPointerInput` maps real PointerEvents onto\n * it, but the kinematics stay pure and unit-testable. Extra pointers are ignored\n * (multi-touch pinch is a separate recognizer).\n */\nexport class PointerRecognizer {\n #handlers: PointerHandlers;\n #activeId: number | null = null;\n #start: Sample | null = null;\n #prev: Sample | null = null;\n #last: Sample | null = null;\n\n constructor(handlers: PointerHandlers = {}) {\n this.#handlers = handlers;\n }\n\n get active(): boolean {\n return this.#activeId !== null;\n }\n\n down(id: number, x: number, y: number, t: number): void {\n if (this.#activeId !== null) return; // single-pointer; ignore extra pointers\n this.#activeId = id;\n const s: Sample = { x, y, t };\n this.#start = s;\n this.#prev = s;\n this.#last = s;\n this.#handlers.onStart?.({ x, y, t });\n }\n\n move(id: number, x: number, y: number, t: number): void {\n if (id !== this.#activeId || this.#start === null) return;\n this.#prev = this.#last;\n this.#last = { x, y, t };\n this.#handlers.onMove?.({ x, y, dx: x - this.#start.x, dy: y - this.#start.y });\n }\n\n up(id: number, x: number, y: number, t: number): void {\n this.#end(id, x, y, t, false);\n }\n\n cancel(id: number, x: number, y: number, t: number): void {\n this.#end(id, x, y, t, true);\n }\n\n #end(id: number, x: number, y: number, t: number, canceled: boolean): void {\n if (id !== this.#activeId || this.#start === null) return;\n const start = this.#start;\n // Velocity comes from the last move segment, not the release point — on lift the\n // pointer usually stops, so release-relative velocity would kill every flick.\n const last = this.#last ?? start;\n const prev = this.#prev ?? start;\n const segDt = last.t - prev.t;\n const vx = segDt > 0 ? (last.x - prev.x) / segDt : 0;\n const vy = segDt > 0 ? (last.y - prev.y) / segDt : 0;\n const speed = Math.hypot(vx, vy);\n this.#reset();\n this.#handlers.onEnd?.({\n x,\n y,\n dx: x - start.x,\n dy: y - start.y,\n dt: t - start.t,\n vx,\n vy,\n swipe: !canceled && speed > SWIPE_VELOCITY,\n canceled,\n });\n }\n\n #reset(): void {\n this.#activeId = null;\n this.#start = null;\n this.#prev = null;\n this.#last = null;\n }\n}\n\n/**\n * Wire real PointerEvents from `target` into a recognizer. Returns an unbind\n * function that removes every listener. Coordinates are passed through as\n * client-space; mapping to page-local space is the engine's job.\n */\nexport function bindPointerInput(target: EventTarget, recognizer: PointerRecognizer): () => void {\n const down = (e: Event): void => {\n const p = e as PointerEvent;\n recognizer.down(p.pointerId, p.clientX, p.clientY, p.timeStamp);\n };\n const move = (e: Event): void => {\n const p = e as PointerEvent;\n recognizer.move(p.pointerId, p.clientX, p.clientY, p.timeStamp);\n };\n const up = (e: Event): void => {\n const p = e as PointerEvent;\n recognizer.up(p.pointerId, p.clientX, p.clientY, p.timeStamp);\n };\n const cancel = (e: Event): void => {\n const p = e as PointerEvent;\n recognizer.cancel(p.pointerId, p.clientX, p.clientY, p.timeStamp);\n };\n target.addEventListener('pointerdown', down);\n target.addEventListener('pointermove', move);\n target.addEventListener('pointerup', up);\n target.addEventListener('pointercancel', cancel);\n return () => {\n target.removeEventListener('pointerdown', down);\n target.removeEventListener('pointermove', move);\n target.removeEventListener('pointerup', up);\n target.removeEventListener('pointercancel', cancel);\n };\n}\n\n/**\n * Wire PointerEvents from `target` into a drag recognizer and/or a pinch\n * recognizer at once, so a single pointer stream feeds both. Returns an unbind.\n */\nexport function bindGestures(\n target: EventTarget,\n recognizers: { pointer?: PointerRecognizer; pinch?: PinchRecognizer },\n): () => void {\n const { pointer, pinch } = recognizers;\n const down = (e: Event): void => {\n const p = e as PointerEvent;\n pointer?.down(p.pointerId, p.clientX, p.clientY, p.timeStamp);\n pinch?.down(p.pointerId, p.clientX, p.clientY);\n };\n const move = (e: Event): void => {\n const p = e as PointerEvent;\n pointer?.move(p.pointerId, p.clientX, p.clientY, p.timeStamp);\n pinch?.move(p.pointerId, p.clientX, p.clientY);\n };\n const up = (e: Event): void => {\n const p = e as PointerEvent;\n pointer?.up(p.pointerId, p.clientX, p.clientY, p.timeStamp);\n pinch?.up(p.pointerId);\n };\n const cancel = (e: Event): void => {\n const p = e as PointerEvent;\n pointer?.cancel(p.pointerId, p.clientX, p.clientY, p.timeStamp);\n pinch?.cancel(p.pointerId);\n };\n target.addEventListener('pointerdown', down);\n target.addEventListener('pointermove', move);\n target.addEventListener('pointerup', up);\n target.addEventListener('pointercancel', cancel);\n return () => {\n target.removeEventListener('pointerdown', down);\n target.removeEventListener('pointermove', move);\n target.removeEventListener('pointerup', up);\n target.removeEventListener('pointercancel', cancel);\n };\n}\n\nexport interface PinchStart {\n centerX: number;\n centerY: number;\n /** Distance between the two pointers at pinch start. */\n distance: number;\n}\n\nexport interface PinchMove {\n centerX: number;\n centerY: number;\n /** Current distance / start distance. */\n scale: number;\n}\n\nexport interface PinchHandlers {\n onPinchStart?: (g: PinchStart) => void;\n onPinchMove?: (g: PinchMove) => void;\n onPinchEnd?: () => void;\n}\n\ninterface Pt {\n x: number;\n y: number;\n}\n\nfunction distance(a: Pt, b: Pt): number {\n return Math.hypot(a.x - b.x, a.y - b.y);\n}\n\n/**\n * Recognizes a two-pointer pinch and reports zoom scale (relative to the start\n * distance) and the live center point. No timestamps: pinch drives zoom, not a\n * flick. A third pointer is ignored; lifting either tracked pointer ends the pinch.\n * Coordinating this with the drag recognizer (a second finger should suspend a\n * single-finger drag) is the engine's job.\n */\nexport class PinchRecognizer {\n #handlers: PinchHandlers;\n #points = new Map<number, Pt>();\n #startDistance = 0;\n #pinching = false;\n\n constructor(handlers: PinchHandlers = {}) {\n this.#handlers = handlers;\n }\n\n get pinching(): boolean {\n return this.#pinching;\n }\n\n down(id: number, x: number, y: number): void {\n if (this.#points.has(id) || this.#points.size >= 2) return; // track only two\n this.#points.set(id, { x, y });\n if (this.#points.size === 2) {\n const { a, b } = this.#pair();\n this.#startDistance = distance(a, b);\n this.#pinching = true;\n this.#handlers.onPinchStart?.({\n centerX: (a.x + b.x) / 2,\n centerY: (a.y + b.y) / 2,\n distance: this.#startDistance,\n });\n }\n }\n\n move(id: number, x: number, y: number): void {\n const p = this.#points.get(id);\n if (!p) return;\n p.x = x;\n p.y = y;\n if (!this.#pinching) return;\n const { a, b } = this.#pair();\n this.#handlers.onPinchMove?.({\n centerX: (a.x + b.x) / 2,\n centerY: (a.y + b.y) / 2,\n scale: this.#startDistance > 0 ? distance(a, b) / this.#startDistance : 1,\n });\n }\n\n up(id: number): void {\n this.#remove(id);\n }\n\n cancel(id: number): void {\n this.#remove(id);\n }\n\n #remove(id: number): void {\n if (!this.#points.delete(id)) return;\n if (this.#pinching && this.#points.size < 2) {\n this.#pinching = false;\n this.#startDistance = 0;\n this.#handlers.onPinchEnd?.();\n }\n }\n\n #pair(): { a: Pt; b: Pt } {\n const values = [...this.#points.values()];\n const a = values[0];\n const b = values[1];\n if (!a || !b) throw new Error('pinch requires two active pointers');\n return { a, b };\n }\n}\n","import type { PageRect, Vec2 } from './foldFromPointer';\n\nexport type HitRegion = 'corner' | 'page' | 'outside';\n\n/**\n * Classify a page-local point into a hit region.\n *\n * Coordinates are page-local (see `foldFromPointer`): (0,0) top-left,\n * page spanning (0,0)..(width,height). `cornerSize` is the width/height of each\n * grabbable corner box. All four corners report `corner`; the engine decides\n * which are actually grabbable for the current spread layout (LTR/RTL, cover).\n */\nexport function hitTest(point: Vec2, pageRect: PageRect, cornerSize: number): HitRegion {\n const { width, height } = pageRect;\n if (point.x < 0 || point.x > width || point.y < 0 || point.y > height) {\n return 'outside';\n }\n const nearX = point.x <= cornerSize || point.x >= width - cornerSize;\n const nearY = point.y <= cornerSize || point.y >= height - cornerSize;\n return nearX && nearY ? 'corner' : 'page';\n}\n","/**\n * Curl type identifiers and the deform contract. Kept free of the deform\n * implementations so the engine (and CSS-only builds) can reference the union and the\n * validation list without pulling the WebGL-only curl math into the eager bundle.\n */\nimport type { PageMesh } from './mesh';\n\n/** Where a corner-anchored curl folds from: y in [0,1], 0 = top edge, 1 = bottom edge. */\nexport interface CurlAnchor {\n y: number;\n}\n\nexport type CurlDeform = (mesh: PageMesh, W: number, H: number, t: number, anchor: CurlAnchor) => void;\n\nexport interface CurlModel {\n readonly deform: CurlDeform;\n /** Single-page (fill) variant for curls whose spread form assumes a centered spine or a\n * neighbouring page. Used in fill mode when present; otherwise `deform` is used as-is. */\n readonly deformFill?: CurlDeform;\n /** True when the fold originates at a corner (`anchor.y`) rather than the whole edge. */\n readonly anchored: boolean;\n}\n\nexport type CurlType = 'roll' | 'simple' | 'fold' | 'peel';\n\nexport const CURL_TYPES: CurlType[] = ['roll', 'simple', 'fold', 'peel'];\n\nexport const DEFAULT_CURL: CurlType = 'roll';\n","export interface FlipPose {\n /** Turning-page rotation about the spine, radians: 0 (flat/open) → π (fully turned). */\n angle: number;\n /** Mesh cylinder-wrap curl, 0..1 — flat at the ends, peaks edge-on at t=0.5. CSS renderer ignores it. */\n curl: number;\n /** Fold-shadow intensity, 0..1 — peaks edge-on at t=0.5. */\n shadowAlpha: number;\n}\n\n/**\n * Map a 0→1 flip progress to a renderer-neutral fold pose.\n *\n * Linear in `t` on purpose — easing belongs to the animator that produces `t`,\n * so seeking to a fixed progress (e.g. the 0/.25/.5/.75/1 visual-regression stops)\n * is deterministic. The CSS renderer consumes `angle` as a spine `rotateY`; the\n * WebGL2 renderer additionally bends its mesh by `curl`.\n */\nexport function flipProgressToPose(t: number): FlipPose {\n const clamped = t < 0 ? 0 : t > 1 ? 1 : t;\n const arc = Math.sin(clamped * Math.PI);\n return {\n angle: clamped * Math.PI,\n curl: arc,\n shadowAlpha: arc,\n };\n}\n","import { flipProgressToPose } from '../geometry/flipProgressToPose';\nimport type { Spread } from '../engine/spread';\nimport type {\n FlipDirection,\n LayoutMetrics,\n PageContent,\n Renderer,\n RenderOptions,\n SpreadContent,\n} from './types';\n\nconst RAD_TO_DEG = 180 / Math.PI;\n\n/** How far to shift a spread to centre a lone page, in units of a quarter container width:\n * -1 = only a right page (cover), +1 = only a left page (back), 0 = a full spread. */\nfunction shiftUnit(content: SpreadContent): number {\n const lone = (content.left === null) !== (content.right === null);\n return lone ? (content.right !== null ? -1 : 1) : 0;\n}\n\n/**\n * Layered gradients painted over the turning leaf to fake paper depth on the flat\n * fold: a crease shadow at the spine, a soft curve sheen, and a free-edge shade.\n * The spine is the leaf's pivot edge — left for a forward flip, right for backward.\n */\nfunction foldOverlay(direction: FlipDirection): string {\n const dir = direction === 'forward' ? 'to right' : 'to left';\n return [\n `linear-gradient(${dir}, rgba(0,0,0,0.6), rgba(0,0,0,0.15) 40%, rgba(0,0,0,0) 60%)`,\n `linear-gradient(${dir}, transparent 40%, rgba(255,255,255,0.32) 66%, transparent 90%)`,\n `linear-gradient(${dir}, transparent 66%, rgba(0,0,0,0.35))`,\n ].join(',');\n}\n\n/**\n * Baseline renderer: a 2-panel CSS-3D fold. Runs on every browser, no GPU. Pages\n * are <canvas> elements; the turning leaf (front + back faces, backface-hidden)\n * rotates about the spine driven by flipProgressToPose(), with a gradient shadow\n * overlay for depth. `beginFlip` stages the surfaces; `setFlipProgress` animates.\n */\nexport class CssRenderer implements Renderer {\n #container: HTMLElement | null = null;\n #clip!: HTMLDivElement;\n #viewport!: HTMLDivElement;\n #book!: HTMLDivElement;\n #pageLeft!: HTMLCanvasElement;\n #pageRight!: HTMLCanvasElement;\n #leaf!: HTMLDivElement;\n #leafFront!: HTMLCanvasElement;\n #leafBack!: HTMLCanvasElement;\n #leafShadow!: HTMLDivElement;\n // Lone-page centering, interpolated across a flip (see the WebGL renderer).\n #fromShiftUnit = 0;\n #toShiftUnit = 0;\n // Book aspect fit: the spread is letterboxed to the page aspect (see the WebGL renderer).\n #pageAspect = 0;\n #bookW = 0;\n #fill = false;\n #contentShift = 0; // shiftUnit of the current static spread (nonzero = lone page, centered)\n\n mount(container: HTMLElement): Promise<void> {\n const doc = container.ownerDocument;\n this.#container = container;\n\n // Fixed-size clip box; NOT transformed, so zoom can't scale the crop region.\n this.#clip = doc.createElement('div');\n this.#clip.className = 'zine-clip';\n this.#clip.style.cssText = 'position:relative;width:100%;height:100%;overflow:hidden;';\n\n // Transform target for zoom/pan; lives inside the clip.\n this.#viewport = doc.createElement('div');\n this.#viewport.className = 'zine-viewport';\n this.#viewport.style.cssText = 'position:absolute;inset:0;transform-origin:0 0;';\n\n this.#book = doc.createElement('div');\n this.#book.className = 'zine-book';\n this.#book.style.cssText =\n 'position:absolute;inset:0;perspective:2000px;transform-style:preserve-3d;';\n\n this.#pageLeft = this.#makeCanvas(doc, 'zine-page-left', 'left:0;');\n this.#pageRight = this.#makeCanvas(doc, 'zine-page-right', 'right:0;');\n\n this.#leaf = doc.createElement('div');\n this.#leaf.className = 'zine-leaf';\n this.#leaf.style.cssText =\n 'position:absolute;top:0;width:50%;height:100%;transform-style:preserve-3d;display:none;';\n\n this.#leafFront = doc.createElement('canvas');\n this.#leafFront.className = 'zine-leaf-front';\n this.#leafFront.style.cssText =\n 'position:absolute;inset:0;width:100%;height:100%;backface-visibility:hidden;';\n\n this.#leafBack = doc.createElement('canvas');\n this.#leafBack.className = 'zine-leaf-back';\n this.#leafBack.style.cssText =\n 'position:absolute;inset:0;width:100%;height:100%;backface-visibility:hidden;transform:rotateY(180deg);';\n\n this.#leafShadow = doc.createElement('div');\n this.#leafShadow.className = 'zine-leaf-shadow';\n this.#leafShadow.style.cssText = 'position:absolute;inset:0;opacity:0;pointer-events:none;';\n this.#leafShadow.style.background = foldOverlay('forward'); // default; beginFlip sets per direction\n\n this.#leaf.append(this.#leafFront, this.#leafBack, this.#leafShadow);\n this.#book.append(this.#pageLeft, this.#pageRight, this.#leaf);\n this.#viewport.append(this.#book);\n this.#clip.append(this.#viewport);\n container.append(this.#clip);\n\n return Promise.resolve();\n }\n\n destroy(): void {\n this.#clip?.remove();\n this.#container = null;\n }\n\n renderSpread(_spread: Spread, content: SpreadContent, options?: RenderOptions): void {\n if (options?.fill) {\n // Single-page mode: the lone page fills the container; hide the other panel.\n this.#pageLeft.style.width = '100%';\n this.#pageRight.style.display = 'none';\n this.#paint(this.#pageLeft, content.right ?? content.left);\n } else {\n this.#pageLeft.style.width = '50%';\n this.#pageRight.style.display = '';\n this.#paint(this.#pageLeft, content.left);\n this.#paint(this.#pageRight, content.right);\n }\n this.#fill = options?.fill ?? false;\n this.#contentShift = this.#fill ? 0 : shiftUnit(content);\n this.#trackAspect(content);\n this.#layoutBook();\n this.#applyShift(this.#contentShift);\n // A fresh spread cancels any in-progress flip.\n this.#leaf.style.display = 'none';\n this.#leaf.style.transform = '';\n this.#leafShadow.style.opacity = '0';\n }\n\n beginFlip(\n from: SpreadContent,\n to: SpreadContent,\n direction: FlipDirection,\n options?: RenderOptions,\n ): void {\n if (options?.fill) {\n // Single-page: a full-width leaf turns about one edge, revealing `to` underneath.\n this.#pageLeft.style.width = '100%';\n this.#pageRight.style.display = 'none';\n this.#leaf.style.width = '100%';\n this.#leaf.style.left = '0';\n this.#leaf.style.transformOrigin = direction === 'forward' ? 'left center' : 'right center';\n this.#paint(this.#pageLeft, to.right ?? to.left);\n this.#paint(this.#leafFront, from.right ?? from.left);\n this.#paint(this.#leafBack, to.right ?? to.left);\n } else {\n this.#pageLeft.style.width = '50%';\n this.#pageRight.style.display = '';\n this.#leaf.style.width = '50%';\n if (direction === 'forward') {\n // Right page lifts and swings left about the spine. Left stays; right reveals `to`.\n this.#paint(this.#pageLeft, from.left);\n this.#paint(this.#pageRight, to.right);\n this.#paint(this.#leafFront, from.right);\n this.#paint(this.#leafBack, to.left);\n this.#leaf.style.left = '50%';\n this.#leaf.style.transformOrigin = 'left center';\n } else {\n // Left page swings right about its right edge. Right stays; left reveals `to`.\n this.#paint(this.#pageRight, from.right);\n this.#paint(this.#pageLeft, to.left);\n this.#paint(this.#leafFront, from.left);\n this.#paint(this.#leafBack, to.right);\n this.#leaf.style.left = '0';\n this.#leaf.style.transformOrigin = 'right center';\n }\n }\n this.#fromShiftUnit = options?.fill ? 0 : shiftUnit(from);\n this.#toShiftUnit = options?.fill ? 0 : shiftUnit(to);\n this.#fill = options?.fill ?? false;\n this.#trackAspect(to);\n this.#layoutBook();\n this.#applyShift(this.#fromShiftUnit);\n this.#leaf.style.display = 'block';\n this.#leaf.style.transform = 'rotateY(0deg)';\n this.#leafShadow.style.background = foldOverlay(direction);\n this.#leafShadow.style.opacity = '0';\n }\n\n setFlipProgress(t: number, direction: FlipDirection): void {\n const pose = flipProgressToPose(t);\n const deg = pose.angle * RAD_TO_DEG;\n this.#applyShift(this.#fromShiftUnit + (this.#toShiftUnit - this.#fromShiftUnit) * t);\n this.#leaf.style.display = 'block';\n this.#leaf.style.transform = `rotateY(${direction === 'forward' ? -deg : deg}deg)`;\n this.#leafShadow.style.opacity = String(pose.shadowAlpha);\n }\n\n #applyShift(unit: number): void {\n const px = unit * (this.#bookW / 4);\n this.#book.style.transform = px ? `translateX(${px}px)` : '';\n }\n\n /** Remember the page aspect (width/height) so the book can be letterboxed to it. */\n #trackAspect(content: SpreadContent): void {\n const p = content.left ?? content.right;\n if (p && p.height) this.#pageAspect = p.width / p.height;\n }\n\n /** Letterbox the 2-page book to the page aspect, centered in the container, so pages\n * fill their halves without stretching; the surround is the container background. */\n #layoutBook(): void {\n const b = this.#bookBox();\n this.#bookW = b.width;\n const s = this.#book.style;\n s.inset = 'auto';\n s.left = `${b.x}px`;\n s.top = `${b.y}px`;\n s.width = `${b.width}px`;\n s.height = `${b.height}px`;\n }\n\n /** The fitted book rect in container px (letterbox aware) — a stable 2-page area. */\n #bookBox(): { x: number; y: number; width: number; height: number } {\n const cw = this.#container?.clientWidth ?? 0;\n const ch = this.#container?.clientHeight ?? 0;\n if (this.#pageAspect <= 0 || cw <= 0 || ch <= 0) return { x: 0, y: 0, width: cw, height: ch };\n const ba = (this.#fill ? 1 : 2) * this.#pageAspect;\n let bw = cw;\n let bh = ch;\n if (ba > cw / ch) bh = cw / ba;\n else bw = ch * ba;\n return { x: (cw - bw) / 2, y: (ch - bh) / 2, width: bw, height: bh };\n }\n\n /** Where the current spread is actually painted: the book, or its centered half for a lone\n * page (mirrors #applyShift). This is what the engine hit-tests against. */\n #contentBox(): { x: number; y: number; width: number; height: number } {\n const b = this.#bookBox();\n return this.#contentShift !== 0 ? { x: b.x + b.width / 4, y: b.y, width: b.width / 2, height: b.height } : b;\n }\n\n setViewTransform(scale: number, x: number, y: number): void {\n this.#viewport.style.transform = `translate(${x}px, ${y}px) scale(${scale})`;\n }\n\n measure(): LayoutMetrics {\n const el = this.#container;\n const w = el?.clientWidth ?? 0;\n const h = el?.clientHeight ?? 0;\n const known = this.#pageAspect > 0;\n const book = known ? this.#bookBox() : undefined;\n const content = known ? this.#contentBox() : undefined;\n return { containerWidth: w, containerHeight: h, pageWidth: w / 2, pageHeight: h, book, content };\n }\n\n #makeCanvas(doc: Document, className: string, extra: string): HTMLCanvasElement {\n const c = doc.createElement('canvas');\n c.className = className;\n c.style.cssText = `position:absolute;top:0;width:50%;height:100%;${extra}`;\n return c;\n }\n\n #paint(canvas: HTMLCanvasElement, content: PageContent | null): void {\n const ctx = canvas.getContext('2d');\n if (content === null) {\n ctx?.clearRect(0, 0, canvas.width, canvas.height);\n return;\n }\n canvas.width = content.width;\n canvas.height = content.height;\n ctx?.drawImage(content, 0, 0);\n }\n}\n","/**\n * Shared grid mesh + normal utilities for the page-curl models.\n *\n * A curl model fills `positions`/`normals` in place each frame; UVs are static grid\n * coordinates (no texture swimming). All models bend the same (cols+1)×(rows+1) grid.\n */\n\nexport interface PageMesh {\n readonly cols: number;\n readonly rows: number;\n /** ((cols+1)*(rows+1))*2 — static grid UVs (u across width, v down height). */\n readonly uvs: Float32Array;\n /** *3 — deformed positions, updated by the curl model. */\n readonly positions: Float32Array;\n /** *3 — per-vertex normals, updated by the curl model. */\n readonly normals: Float32Array;\n}\n\n/** Allocate a (cols+1)×(rows+1) grid mesh with static UVs (positions/normals filled by a curl). */\nexport function createPageMesh(cols: number, rows: number): PageMesh {\n const nx = cols + 1;\n const ny = rows + 1;\n const count = nx * ny;\n const uvs = new Float32Array(count * 2);\n for (let j = 0; j < ny; j++) {\n for (let i = 0; i < nx; i++) {\n const k = j * nx + i;\n uvs[k * 2] = i / cols;\n uvs[k * 2 + 1] = j / rows;\n }\n }\n return {\n cols,\n rows,\n uvs,\n positions: new Float32Array(count * 3),\n normals: new Float32Array(count * 3),\n };\n}\n\n/** Per-vertex normals from central differences of the deformed grid (front = +z when flat). */\nexport function computeNormals(mesh: PageMesh): void {\n const nx = mesh.cols + 1;\n const ny = mesh.rows + 1;\n const pos = mesh.positions;\n const nrm = mesh.normals;\n\n for (let j = 0; j < ny; j++) {\n for (let i = 0; i < nx; i++) {\n const iPrev = i > 0 ? i - 1 : i;\n const iNext = i < nx - 1 ? i + 1 : i;\n const jPrev = j > 0 ? j - 1 : j;\n const jNext = j < ny - 1 ? j + 1 : j;\n\n const a = (j * nx + iNext) * 3;\n const b = (j * nx + iPrev) * 3;\n const c = (jNext * nx + i) * 3;\n const e = (jPrev * nx + i) * 3;\n\n const tuX = pos[a]! - pos[b]!;\n const tuY = pos[a + 1]! - pos[b + 1]!;\n const tuZ = pos[a + 2]! - pos[b + 2]!;\n const tvX = pos[c]! - pos[e]!;\n const tvY = pos[c + 1]! - pos[e + 1]!;\n const tvZ = pos[c + 2]! - pos[e + 2]!;\n\n let nx0 = tuY * tvZ - tuZ * tvY;\n let ny0 = tuZ * tvX - tuX * tvZ;\n let nz0 = tuX * tvY - tuY * tvX;\n const l = Math.hypot(nx0, ny0, nz0) || 1;\n nx0 /= l;\n ny0 /= l;\n nz0 /= l;\n\n const k = (j * nx + i) * 3;\n nrm[k] = nx0;\n nrm[k + 1] = ny0;\n nrm[k + 2] = nz0;\n }\n }\n}\n","import { computeNormals, type PageMesh } from './mesh';\n\n/**\n * Roll-and-flop. The leaf wraps a cylinder whose wrap angle grows 0→π over the first\n * half while its radius (= W/theta) shrinks, so the sheet rolls up off the surface in\n * place; over the second half it unwraps π→0 while rigidly rotating around the spine\n * 0→-π down onto the far side. Arc length across the width is exactly preserved.\n */\nexport function deformRoll(mesh: PageMesh, W: number, H: number, t: number): void {\n const nx = mesh.cols + 1;\n const ny = mesh.rows + 1;\n const pos = mesh.positions;\n\n const theta = Math.max(1e-6, t < 0.5 ? t * 2 * Math.PI : (1 - (t - 0.5) * 2) * Math.PI);\n const radius = W / theta;\n const rot = t < 0.5 ? 0 : -(t - 0.5) * 2 * Math.PI;\n const cosR = Math.cos(rot);\n const sinR = Math.sin(rot);\n\n for (let i = 0; i < nx; i++) {\n const rad = (i / mesh.cols) * theta;\n const cx = Math.sin(rad) * radius;\n const cz = (1 - Math.cos(rad)) * radius;\n const X = cx * cosR + cz * sinR;\n const Z = -cx * sinR + cz * cosR;\n for (let j = 0; j < ny; j++) {\n const k = (j * nx + i) * 3;\n pos[k] = X;\n pos[k + 1] = (j / mesh.rows) * H;\n pos[k + 2] = Z;\n }\n }\n\n computeNormals(mesh);\n}\n","import { computeNormals, type PageMesh } from './mesh';\n\n/**\n * Flat page turn — the plainest flip, matching the CSS renderer. The leaf stays a rigid\n * flat sheet and rotates around the spine (angle 0→π), going edge-on at the midpoint. No\n * cylinder bend; GPU-rendered here with the shared perspective so it reads like the CSS fold.\n */\nexport function deformSimple(mesh: PageMesh, W: number, H: number, t: number): void {\n const nx = mesh.cols + 1;\n const ny = mesh.rows + 1;\n const pos = mesh.positions;\n\n const angle = t * Math.PI;\n const cosA = Math.cos(angle);\n const sinA = Math.sin(angle);\n\n for (let i = 0; i < nx; i++) {\n const x0 = (i / mesh.cols) * W; // distance from the spine\n const X = x0 * cosA;\n const Z = x0 * sinA;\n for (let j = 0; j < ny; j++) {\n const k = (j * nx + i) * 3;\n pos[k] = X;\n pos[k + 1] = (j / mesh.rows) * H;\n pos[k + 2] = Z;\n }\n }\n\n computeNormals(mesh);\n}\n\n/**\n * Bent page flip: the single-page (fill) form for spine curls whose spread shape assumes a\n * centered spine or a neighbour (roll). The leaf rotates about its spine edge (0→π) like the\n * flat turn, but the sheet also curves into a shallow arc that peaks mid-flip and flattens at\n * both ends, so the paper visibly bends as it turns instead of staying rigid. Reduces to the\n * flat turn when the bend is zero; arc length across the width is preserved.\n */\nexport function deformBentFlip(mesh: PageMesh, W: number, H: number, t: number): void {\n const nx = mesh.cols + 1;\n const ny = mesh.rows + 1;\n const pos = mesh.positions;\n\n const phi = t * Math.PI; // spine rotation, 0 → π\n // Curl across the width, 0 at the ends. Deep enough that the sheet's facing varies across\n // its width, so the shared fold shading + glossy highlight ride across it as it turns.\n const bend = Math.max(1e-3, 1.6 * Math.sin(Math.PI * t));\n const R = W / bend; // arc radius: arc length W subtends `bend` radians\n const sinPhi = Math.sin(phi);\n const cosPhi = Math.cos(phi);\n\n for (let i = 0; i < nx; i++) {\n const x0 = (i / mesh.cols) * W;\n const a = phi + bend * (x0 / W); // tangent angle at this column (spine → free edge)\n const X = R * (Math.sin(a) - sinPhi);\n const Z = R * (cosPhi - Math.cos(a));\n for (let j = 0; j < ny; j++) {\n const k = (j * nx + i) * 3;\n pos[k] = X;\n pos[k + 1] = (j / mesh.rows) * H;\n pos[k + 2] = Z;\n }\n }\n\n computeNormals(mesh);\n}\n","import { computeNormals, type PageMesh } from './mesh';\nimport type { CurlAnchor } from './types';\n\nconst CREASE = 0.04; // crease radius as a fraction of width — small = a hard, flat fold\nconst DIAG = 0.6; // how far the dragged corner pulls toward the vertical centre mid-turn\n\n/**\n * Flat origami fold. The tapped corner (`anchor.y`) is dragged across the spine; the\n * sheet folds along the perpendicular bisector of corner→pointer, reflecting the corner\n * region flat over the rest with a tight rounded crease. Off-centre taps give a diagonal\n * fold; the fold sweeps to the spine and the page lands (near) flat on the far side.\n */\nexport function deformFold(mesh: PageMesh, W: number, H: number, t: number, anchor: CurlAnchor): void {\n const nx = mesh.cols + 1;\n const ny = mesh.rows + 1;\n const pos = mesh.positions;\n const r = Math.max(1e-4, CREASE * W);\n\n const cy = anchor.y * H;\n const px = W - 2 * W * t; // corner sweeps free edge -> across the spine\n const py = cy + (0.5 * H - cy) * DIAG * Math.sin(Math.PI * t);\n const dx = W - px; // corner - pointer\n const dy = cy - py;\n const len = Math.hypot(dx, dy);\n\n if (len < 1e-4) {\n for (let j = 0; j < ny; j++) {\n for (let i = 0; i < nx; i++) {\n const k = (j * nx + i) * 3;\n pos[k] = (i / mesh.cols) * W;\n pos[k + 1] = (j / mesh.rows) * H;\n pos[k + 2] = 0;\n }\n }\n computeNormals(mesh);\n return;\n }\n\n const nX = dx / len; // toward the corner (fold \"past\" direction)\n const nY = dy / len;\n const fX = -nY; // along the fold line (preserved)\n const fY = nX;\n const midX = (W + px) / 2;\n const midY = (cy + py) / 2;\n\n for (let j = 0; j < ny; j++) {\n const y0 = (j / mesh.rows) * H;\n for (let i = 0; i < nx; i++) {\n const x0 = (i / mesh.cols) * W;\n const relX = x0 - midX;\n const relY = y0 - midY;\n const d = relX * nX + relY * nY; // signed distance past the fold (+ = corner side)\n const e = relX * fX + relY * fY; // position along the fold line\n const k = (j * nx + i) * 3;\n\n if (d <= 0) {\n pos[k] = x0;\n pos[k + 1] = y0;\n pos[k + 2] = 0;\n continue;\n }\n\n const theta = Math.min(d / r, Math.PI); // wrap the crease, then lie flat\n const extra = Math.max(0, d - r * Math.PI);\n const nComp = r * Math.sin(theta) - extra;\n pos[k] = midX + fX * e + nX * nComp;\n pos[k + 1] = midY + fY * e + nY * nComp;\n pos[k + 2] = r * (1 - Math.cos(theta));\n }\n }\n\n computeNormals(mesh);\n}\n","import { computeNormals, type PageMesh } from './mesh';\nimport type { CurlAnchor } from './types';\n\nconst LEAD = 0.7; // how far the anchored corner runs ahead of the far edge (diagonal peel)\n\n/**\n * Diagonal corner peel. Each row runs the roll-and-flop, but rows near the tapped corner\n * (`anchor.y`) lead and rows far behind lag, so the sheet lifts from that corner and\n * sweeps across on a diagonal — a smooth 3D peel. Every row still reaches t=1 together,\n * so the page lands flat.\n */\nexport function deformPeel(mesh: PageMesh, W: number, H: number, t: number, anchor: CurlAnchor): void {\n const nx = mesh.cols + 1;\n const ny = mesh.rows + 1;\n const pos = mesh.positions;\n\n for (let j = 0; j < ny; j++) {\n const v = j / mesh.rows;\n const d = Math.abs(v - anchor.y); // 0 at the tapped corner, up to 1 at the far edge\n const tRow = Math.min(1, Math.max(0, t * (1 + LEAD) - LEAD * d));\n\n const theta = Math.max(1e-6, tRow < 0.5 ? tRow * 2 * Math.PI : (1 - (tRow - 0.5) * 2) * Math.PI);\n const radius = W / theta;\n const rot = tRow < 0.5 ? 0 : -(tRow - 0.5) * 2 * Math.PI;\n const cosR = Math.cos(rot);\n const sinR = Math.sin(rot);\n const y = v * H;\n\n for (let i = 0; i < nx; i++) {\n const rad = (i / mesh.cols) * theta;\n const cx = Math.sin(rad) * radius;\n const cz = (1 - Math.cos(rad)) * radius;\n const k = (j * nx + i) * 3;\n pos[k] = cx * cosR + cz * sinR;\n pos[k + 1] = y;\n pos[k + 2] = -cx * sinR + cz * cosR;\n }\n }\n\n computeNormals(mesh);\n}\n","/**\n * Page-curl registry. Each model turns a 0→1 flip progress into a bent page mesh; the\n * WebGL2 renderer picks one by the `curl` option. `anchored` models fold from a corner\n * given by `anchor.y` (0 = top, 1 = bottom — where the reader tapped); the others roll\n * the whole free edge and ignore it.\n *\n * Importing this module pulls in the deform math, so only the WebGL2 renderer does.\n * The engine references the lightweight `./types` (union + validation list) instead.\n */\nimport { deformRoll } from './roll';\nimport { deformSimple, deformBentFlip } from './simple';\nimport { deformFold } from './fold';\nimport { deformPeel } from './peel';\nimport type { CurlModel, CurlType } from './types';\n\nexport { createPageMesh, computeNormals, type PageMesh } from './mesh';\nexport { CURL_TYPES, DEFAULT_CURL } from './types';\nexport type { CurlAnchor, CurlDeform, CurlModel, CurlType } from './types';\n\nexport const CURLS: Record<CurlType, CurlModel> = {\n roll: { deform: deformRoll, deformFill: deformBentFlip, anchored: false },\n simple: { deform: deformSimple, anchored: false },\n fold: { deform: deformFold, anchored: true },\n peel: { deform: deformPeel, anchored: true },\n};\n","/** Create a WebGL2 context, or throw so the caller can fall back to CSS (§8.4). */\nexport function createGlContext(canvas: HTMLCanvasElement): WebGL2RenderingContext {\n const gl = canvas.getContext('webgl2', {\n alpha: true,\n premultipliedAlpha: true,\n antialias: true,\n depth: false,\n stencil: false,\n // We render on demand (not every frame), so the buffer must persist between\n // composites — otherwise the settled page flickers once the flip animation\n // stops and nothing is redrawing each frame.\n preserveDrawingBuffer: true,\n });\n if (gl === null) {\n throw new Error('WebglRenderer: could not create a WebGL2 context.');\n }\n return gl;\n}\n","/** Compile + link a shader program; throws with the driver log on failure. */\nexport function createProgram(\n gl: WebGL2RenderingContext,\n vertexSrc: string,\n fragmentSrc: string,\n): WebGLProgram {\n const program = gl.createProgram();\n if (program === null) throw new Error('WebglRenderer: could not create a program.');\n\n const vs = compileShader(gl, gl.VERTEX_SHADER, vertexSrc);\n const fs = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc);\n gl.attachShader(program, vs);\n gl.attachShader(program, fs);\n gl.linkProgram(program);\n\n // Shaders can be detached/deleted once linked.\n gl.deleteShader(vs);\n gl.deleteShader(fs);\n\n if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {\n const log = gl.getProgramInfoLog(program);\n gl.deleteProgram(program);\n throw new Error(`WebglRenderer: program link failed: ${log ?? 'unknown error'}`);\n }\n return program;\n}\n\nfunction compileShader(gl: WebGL2RenderingContext, type: number, src: string): WebGLShader {\n const shader = gl.createShader(type);\n if (shader === null) throw new Error('WebglRenderer: could not create a shader.');\n gl.shaderSource(shader, src);\n gl.compileShader(shader);\n if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {\n const log = gl.getShaderInfoLog(shader);\n gl.deleteShader(shader);\n throw new Error(`WebglRenderer: shader compile failed: ${log ?? 'unknown error'}`);\n }\n return shader;\n}\n","/** Create a page texture with clamp + linear filtering (no mipmaps — §8.3). */\nexport function createTexture(gl: WebGL2RenderingContext): WebGLTexture {\n const tex = gl.createTexture();\n if (tex === null) throw new Error('WebglRenderer: could not create a texture.');\n gl.bindTexture(gl.TEXTURE_2D, tex);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n return tex;\n}\n\n/** Upload a decoded page raster (ImageBitmap or canvas) into `tex`. */\nexport function uploadTexture(\n gl: WebGL2RenderingContext,\n tex: WebGLTexture,\n source: TexImageSource,\n): void {\n gl.bindTexture(gl.TEXTURE_2D, tex);\n // No Y flip: the vertex shader maps aUnit.y=0 to the page top and samples the\n // source's top row there. UNPACK_FLIP_Y is honored for <canvas> sources but\n // IGNORED for ImageBitmap, so flipping would invert PDF (canvas) pages while\n // leaving image (ImageBitmap) pages upright. Off keeps both consistent.\n gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);\n gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, source);\n}\n","import {\n CURLS,\n createPageMesh,\n DEFAULT_CURL,\n type CurlAnchor,\n type CurlType,\n type PageMesh,\n} from '../geometry/curls';\nimport type { Spread } from '../engine/spread';\nimport type {\n FlipDirection,\n LayoutMetrics,\n Renderer,\n RenderOptions,\n SpreadContent,\n} from './types';\nimport { createGlContext } from './gl/context';\nimport { createProgram } from './gl/program';\nimport { createTexture, uploadTexture } from './gl/texture';\n\n// Flat program: a page rect (device px, top-left origin) with zoom/pan and a soft\n// permanent gutter shadow toward the spine so the turning leaf's shadow lands into it.\nconst FLAT_VERT = `#version 300 es\nin vec2 aUnit;\nuniform vec2 uViewport;\nuniform vec4 uRect;\nuniform vec3 uView;\nout vec2 vUv;\nvoid main() {\n vec2 px = uRect.xy + aUnit * uRect.zw;\n px = px * uView.x + uView.yz;\n vec2 clip = px / uViewport * 2.0 - 1.0;\n gl_Position = vec4(clip.x, -clip.y, 0.0, 1.0);\n vUv = aUnit;\n}`;\n\nconst FLAT_FRAG = `#version 300 es\nprecision mediump float;\nin vec2 vUv;\nuniform sampler2D uTex;\nuniform float uGutterSide; // +1 = spine at right edge, -1 = at left edge, 0 = none\nout vec4 outColor;\nvoid main() {\n vec4 c = texture(uTex, vUv);\n if (uGutterSide != 0.0) {\n float d = uGutterSide > 0.0 ? (1.0 - vUv.x) : vUv.x;\n c.rgb *= mix(0.72, 1.0, smoothstep(0.0, 0.10, d));\n }\n outColor = c;\n}`;\n\n// Curl program: a thin pass-through for the CPU-deformed page mesh (positions and\n// normals come from the selected curl model). It places the leaf, applies a top-safe depth\n// perspective, and lights from the true surface normal.\nconst CURL_VERT = `#version 300 es\nin vec3 aPos; // leaf-local device px: x = bent offset from spine, y 0..H, z depth\nin vec3 aNormal;\nin vec2 aUv;\nuniform vec2 uViewport;\nuniform vec3 uView; // scale, tx, ty\nuniform float uOriginX; // spine x in device px\nuniform float uDir; // +1 leaf to the right of spine, -1 to the left\nuniform float uLeafW; // leaf width in device px (perspective scale)\nout vec2 vUv;\nout float vFacing;\nout float vU;\nvoid main() {\n float bookX = uOriginX + uDir * aPos.x;\n float bookY = aPos.y;\n float Z = aPos.z;\n float D = uLeafW * 3.0;\n float persp = D / max(D - Z, 1.0);\n float cx = uViewport.x * 0.5;\n float cy = uViewport.y * 0.5;\n float px = cx + (bookX - cx) * persp;\n float py = cy + (bookY - cy) * min(persp, 1.0); // Y only shrinks (top-safe)\n vec2 p = vec2(px, py) * uView.x + uView.yz;\n vec2 clip = p / uViewport * 2.0 - 1.0;\n gl_Position = vec4(clip.x, -clip.y, 0.0, 1.0);\n vUv = aUv;\n vFacing = aNormal.z;\n vU = aUv.x;\n}`;\n\nconst CURL_FRAG = `#version 300 es\nprecision mediump float;\nin vec2 vUv;\nin float vFacing;\nin float vU;\nuniform sampler2D uFront;\nuniform sampler2D uBack;\nuniform highp float uDir;\nuniform float uGloss; // 0 disables the specular highlight (e.g. the flat 'simple' curl)\nout vec4 outColor;\nvoid main() {\n // The turn mesh carries its own facing in the normal; the front points at the viewer\n // (normal.z > 0) until the leaf passes vertical, for both flip directions. u->x still\n // flips with uDir so a left-hand leaf reads spine-inward.\n bool showFront = vFacing > 0.0;\n float fx = uDir > 0.0 ? vUv.x : 1.0 - vUv.x;\n vec4 c = showFront ? texture(uFront, vec2(fx, vUv.y)) : texture(uBack, vec2(1.0 - fx, vUv.y));\n\n // Fold shading: the sheet darkens sharply where it curves away from the viewer, so the\n // rolled edge reads as a deep crease with a soft highlight riding the ridge.\n float diff = clamp(abs(vFacing), 0.0, 1.0);\n float lit = mix(0.42, 1.0, diff);\n lit *= mix(0.7, 1.0, smoothstep(0.0, 0.12, vU)); // spine crease matches the gutter shadow\n\n // Glossy specular: brightest where the surface tilts ~30 deg from facing the viewer,\n // so a thin glossy highlight rides across the sheet as it rolls.\n float spec = pow(max(cos(acos(diff) - 0.52), 0.0), 220.0) * 0.22 * uGloss;\n\n c.rgb = clamp(c.rgb * lit + spec, 0.0, 1.0);\n outColor = c;\n}`;\n\nconst GRID_COLS = 28;\nconst GRID_ROWS = 36;\nconst RESTORE_TIMEOUT_MS = 4000;\nconst MAX_TEXTURE_CACHE_BYTES = 256 * 1024 * 1024;\n\ninterface Rect {\n x: number;\n y: number;\n w: number;\n h: number;\n}\n\ninterface FlipState {\n underLeft: TexImageSource | null;\n underRight: TexImageSource | null;\n underFull: TexImageSource | null; // fill mode\n front: TexImageSource | null;\n back: TexImageSource | null;\n dir: number; // +1 forward (leaf right of spine), -1 backward (left)\n fill: boolean;\n}\n\n/** How far to shift a spread to centre a lone page, in units of a quarter container width:\n * -1 = only a right page (cover), +1 = only a left page (back), 0 = a full spread. */\nfunction shiftUnit(content: SpreadContent): number {\n const lone = (content.left === null) !== (content.right === null);\n return lone ? (content.right !== null ? -1 : 1) : 0;\n}\n\n/**\n * GPU renderer (WebGL2, hand-written). The turning leaf is a dense grid deformed on\n * the CPU by the selected curl model (see geometry/curls) and\n * uploaded each frame, lit from real normals; the static pages are flat quads with a\n * gutter shadow. Restores\n * GL state on context loss; signals onFatal (→ CSS fallback) when unrecoverable.\n */\nexport class WebglRenderer implements Renderer {\n #container: HTMLElement | null = null;\n #canvas: HTMLCanvasElement | null = null;\n #gl: WebGL2RenderingContext | null = null;\n\n #flat: WebGLProgram | null = null;\n #curl: WebGLProgram | null = null;\n #quadVao: WebGLVertexArrayObject | null = null;\n #curlVao: WebGLVertexArrayObject | null = null;\n #posBuf: WebGLBuffer | null = null;\n #normBuf: WebGLBuffer | null = null;\n #idxCount = 0;\n #mesh: PageMesh = createPageMesh(GRID_COLS, GRID_ROWS);\n\n #texCache = new Map<TexImageSource, { tex: WebGLTexture; bytes: number }>();\n #cacheBytes = 0;\n #blankTex: WebGLTexture | null = null;\n\n #flatU: Record<string, WebGLUniformLocation | null> = {};\n #curlU: Record<string, WebGLUniformLocation | null> = {};\n\n #view = { scale: 1, tx: 0, ty: 0 };\n #dpr = 1;\n #content: SpreadContent | null = null;\n #fill = false;\n #flip: FlipState | null = null;\n #flipT = 0;\n #curlType: CurlType = DEFAULT_CURL;\n #anchor: CurlAnchor = { y: 0.5 };\n // A lone page (cover / book front-back) sits on one half; these center it by shifting\n // the view a quarter-width, interpolated across a flip so the open/close doesn't jump.\n #shiftX = 0;\n #fromShiftUnit = 0;\n #toShiftUnit = 0;\n // Book aspect fit: the 2-page spread is letterboxed to the pages' aspect, centered\n // in the container, so pages fill their halves without stretching. 0 = aspect unknown.\n #pageAspect = 0;\n #bookW = 0;\n #bookH = 0;\n\n #contextLost = false;\n #fatalFired = false;\n #restoreTimer: ReturnType<typeof setTimeout> | null = null;\n #fatalHandler: (() => void) | null = null;\n\n mount(container: HTMLElement): Promise<void> {\n this.#container = container;\n const doc = container.ownerDocument;\n const canvas = doc.createElement('canvas');\n canvas.style.cssText = 'display:block;width:100%;height:100%;';\n container.append(canvas);\n this.#canvas = canvas;\n\n canvas.addEventListener('webglcontextlost', this.#onContextLost as EventListener);\n canvas.addEventListener('webglcontextrestored', this.#onContextRestored as EventListener);\n doc.addEventListener('visibilitychange', this.#onVisibilityChange);\n\n this.#gl = createGlContext(canvas); // throws if unavailable -> engine falls back (§8.4)\n this.#buildGlResources();\n return Promise.resolve();\n }\n\n destroy(): void {\n this.#clearRestoreTimer();\n const canvas = this.#canvas;\n if (canvas !== null) {\n canvas.removeEventListener('webglcontextlost', this.#onContextLost as EventListener);\n canvas.removeEventListener('webglcontextrestored', this.#onContextRestored as EventListener);\n canvas.ownerDocument.removeEventListener('visibilitychange', this.#onVisibilityChange);\n }\n const gl = this.#gl;\n if (gl !== null) {\n for (const cached of this.#texCache.values()) gl.deleteTexture(cached.tex);\n if (this.#blankTex !== null) gl.deleteTexture(this.#blankTex);\n if (this.#quadVao !== null) gl.deleteVertexArray(this.#quadVao);\n if (this.#curlVao !== null) gl.deleteVertexArray(this.#curlVao);\n if (this.#flat !== null) gl.deleteProgram(this.#flat);\n if (this.#curl !== null) gl.deleteProgram(this.#curl);\n gl.getExtension('WEBGL_lose_context')?.loseContext();\n }\n canvas?.remove();\n this.#texCache.clear();\n this.#cacheBytes = 0;\n this.#blankTex = null;\n this.#container = null;\n this.#canvas = null;\n this.#gl = null;\n this.#content = null;\n this.#flip = null;\n }\n\n onFatal(handler: () => void): void {\n this.#fatalHandler = handler;\n }\n\n renderSpread(_spread: Spread, content: SpreadContent, options?: RenderOptions): void {\n this.#content = content;\n this.#fill = options?.fill ?? false;\n this.#flip = null;\n this.#trackAspect(content);\n this.#render();\n }\n\n /** Remember the page aspect (width/height) so the book can be letterboxed to it. */\n #trackAspect(content: SpreadContent): void {\n const p = content.left ?? content.right;\n if (p && p.height) this.#pageAspect = p.width / p.height;\n }\n\n beginFlip(\n from: SpreadContent,\n to: SpreadContent,\n direction: FlipDirection,\n options?: RenderOptions,\n ): void {\n const fill = options?.fill ?? false;\n this.#flipT = 0;\n if (options?.curl) this.#curlType = options.curl;\n if (options?.anchor) this.#anchor = options.anchor;\n this.#fromShiftUnit = fill ? 0 : shiftUnit(from);\n this.#toShiftUnit = fill ? 0 : shiftUnit(to);\n this.#trackAspect(to);\n if (fill) {\n this.#flip = {\n underLeft: null,\n underRight: null,\n underFull: to.right ?? to.left,\n front: from.right ?? from.left,\n // A lone page has no facing \"next\" leaf on its back; show the same page mirrored\n // (the shader flips the back UV) so it reads as the sheet's own reverse side.\n back: from.right ?? from.left,\n dir: direction === 'forward' ? 1 : -1,\n fill: true,\n };\n } else if (direction === 'forward') {\n this.#flip = {\n underLeft: from.left,\n underRight: to.right,\n underFull: null,\n front: from.right,\n back: to.left,\n dir: 1,\n fill: false,\n };\n } else {\n this.#flip = {\n underLeft: to.left,\n underRight: from.right,\n underFull: null,\n front: from.left,\n back: to.right,\n dir: -1,\n fill: false,\n };\n }\n this.#render();\n }\n\n setFlipProgress(t: number, _direction: FlipDirection): void {\n this.#flipT = t;\n this.#render();\n }\n\n setViewTransform(scale: number, x: number, y: number): void {\n this.#view = { scale, tx: x, ty: y };\n this.#render();\n }\n\n measure(): LayoutMetrics {\n const el = this.#container;\n const w = el?.clientWidth ?? 0;\n const h = el?.clientHeight ?? 0;\n const known = this.#pageAspect > 0;\n const book = known ? this.#bookBox() : undefined;\n const content = known ? this.#contentBox() : undefined;\n return { containerWidth: w, containerHeight: h, pageWidth: w / 2, pageHeight: h, book, content };\n }\n\n /** The fitted book rect in container CSS px (letterbox aware) — a stable 2-page area. */\n #bookBox(): { x: number; y: number; width: number; height: number } {\n const el = this.#container;\n const cw = el?.clientWidth ?? 0;\n const ch = el?.clientHeight ?? 0;\n if (this.#pageAspect <= 0 || cw <= 0 || ch <= 0) return { x: 0, y: 0, width: cw, height: ch };\n const ba = (this.#fill ? 1 : 2) * this.#pageAspect;\n let bw = cw;\n let bh = ch;\n if (ba > cw / ch) bh = cw / ba;\n else bw = ch * ba;\n return { x: (cw - bw) / 2, y: (ch - bh) / 2, width: bw, height: bh };\n }\n\n /** Where the current spread is actually painted: the book, or its centered half for a lone\n * page (mirrors the draw-time #shiftX centering). This is what the engine hit-tests against. */\n #contentBox(): { x: number; y: number; width: number; height: number } {\n const b = this.#bookBox();\n const lone = !this.#fill && this.#content !== null && shiftUnit(this.#content) !== 0;\n return lone ? { x: b.x + b.width / 4, y: b.y, width: b.width / 2, height: b.height } : b;\n }\n\n // --- context loss / restore ---------------------------------------------------\n\n #onContextLost = (event: Event): void => {\n event.preventDefault();\n this.#contextLost = true;\n if (this.#restoreTimer === null) {\n this.#restoreTimer = setTimeout(() => this.#fatal(), RESTORE_TIMEOUT_MS);\n }\n };\n\n #onContextRestored = (): void => {\n this.#clearRestoreTimer();\n this.#contextLost = false;\n this.#buildGlResources();\n this.#render();\n };\n\n #onVisibilityChange = (): void => {\n if (this.#canvas?.ownerDocument.visibilityState === 'visible') this.#render();\n };\n\n #fatal(): void {\n if (this.#fatalFired) return;\n this.#fatalFired = true;\n this.#fatalHandler?.();\n }\n\n #clearRestoreTimer(): void {\n if (this.#restoreTimer !== null) {\n clearTimeout(this.#restoreTimer);\n this.#restoreTimer = null;\n }\n }\n\n #buildGlResources(): void {\n const gl = this.#gl;\n if (gl === null) return;\n\n this.#flat = createProgram(gl, FLAT_VERT, FLAT_FRAG);\n this.#curl = createProgram(gl, CURL_VERT, CURL_FRAG);\n for (const name of ['uViewport', 'uRect', 'uView', 'uTex', 'uGutterSide']) {\n this.#flatU[name] = gl.getUniformLocation(this.#flat, name);\n }\n for (const name of ['uViewport', 'uView', 'uOriginX', 'uDir', 'uLeafW', 'uFront', 'uBack', 'uGloss']) {\n this.#curlU[name] = gl.getUniformLocation(this.#curl, name);\n }\n\n this.#quadVao = this.#makeQuadVao(gl, this.#flat);\n this.#buildCurlMesh(gl, this.#curl);\n\n this.#texCache.clear();\n this.#cacheBytes = 0;\n this.#blankTex = this.#makeBlankTexture(gl);\n gl.useProgram(this.#flat);\n gl.uniform1i(this.#flatU.uTex ?? null, 0);\n gl.useProgram(this.#curl);\n gl.uniform1i(this.#curlU.uFront ?? null, 0);\n gl.uniform1i(this.#curlU.uBack ?? null, 1);\n gl.clearColor(0, 0, 0, 0);\n gl.enable(gl.BLEND);\n gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); // premultiplied alpha\n }\n\n #makeQuadVao(gl: WebGL2RenderingContext, program: WebGLProgram): WebGLVertexArrayObject {\n const vao = gl.createVertexArray();\n const buffer = gl.createBuffer();\n if (vao === null || buffer === null) throw new Error('WebglRenderer: could not create buffers.');\n gl.bindVertexArray(vao);\n gl.bindBuffer(gl.ARRAY_BUFFER, buffer);\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([0, 0, 1, 0, 0, 1, 1, 1]), gl.STATIC_DRAW);\n const aUnit = gl.getAttribLocation(program, 'aUnit');\n gl.enableVertexAttribArray(aUnit);\n gl.vertexAttribPointer(aUnit, 2, gl.FLOAT, false, 0, 0);\n gl.bindVertexArray(null);\n return vao;\n }\n\n #buildCurlMesh(gl: WebGL2RenderingContext, program: WebGLProgram): void {\n const nx = GRID_COLS + 1;\n const indices: number[] = [];\n for (let j = 0; j < GRID_ROWS; j++) {\n for (let i = 0; i < GRID_COLS; i++) {\n const a = j * nx + i;\n const b = a + 1;\n const c = a + nx;\n const d = c + 1;\n indices.push(a, c, b, b, c, d);\n }\n }\n this.#idxCount = indices.length;\n\n const vao = gl.createVertexArray();\n this.#posBuf = gl.createBuffer();\n this.#normBuf = gl.createBuffer();\n const uvBuf = gl.createBuffer();\n const idxBuf = gl.createBuffer();\n if (vao === null || this.#posBuf === null || this.#normBuf === null || uvBuf === null || idxBuf === null) {\n throw new Error('WebglRenderer: could not create mesh buffers.');\n }\n gl.bindVertexArray(vao);\n\n gl.bindBuffer(gl.ARRAY_BUFFER, this.#posBuf);\n gl.bufferData(gl.ARRAY_BUFFER, this.#mesh.positions, gl.DYNAMIC_DRAW);\n const aPos = gl.getAttribLocation(program, 'aPos');\n gl.enableVertexAttribArray(aPos);\n gl.vertexAttribPointer(aPos, 3, gl.FLOAT, false, 0, 0);\n\n gl.bindBuffer(gl.ARRAY_BUFFER, this.#normBuf);\n gl.bufferData(gl.ARRAY_BUFFER, this.#mesh.normals, gl.DYNAMIC_DRAW);\n const aNormal = gl.getAttribLocation(program, 'aNormal');\n gl.enableVertexAttribArray(aNormal);\n gl.vertexAttribPointer(aNormal, 3, gl.FLOAT, false, 0, 0);\n\n gl.bindBuffer(gl.ARRAY_BUFFER, uvBuf);\n gl.bufferData(gl.ARRAY_BUFFER, this.#mesh.uvs, gl.STATIC_DRAW);\n const aUv = gl.getAttribLocation(program, 'aUv');\n gl.enableVertexAttribArray(aUv);\n gl.vertexAttribPointer(aUv, 2, gl.FLOAT, false, 0, 0);\n\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, idxBuf);\n gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW);\n\n gl.bindVertexArray(null);\n this.#curlVao = vao;\n }\n\n // --- drawing ------------------------------------------------------------------\n\n #render(): void {\n const gl = this.#gl;\n const canvas = this.#canvas;\n if (gl === null || canvas === null || this.#contextLost || gl.isContextLost()) return;\n this.#resize();\n gl.clear(gl.COLOR_BUFFER_BIT);\n this.#fitBook();\n if (this.#flip !== null) this.#drawFlip();\n else if (this.#content !== null) this.#drawStatic();\n }\n\n /** Letterbox the 2-page book to the page aspect, centered; restricts the GL viewport\n * so pages fill their halves without stretching (the surround stays cleared). */\n #fitBook(): void {\n const gl = this.#gl!;\n const canvas = this.#canvas!;\n const cw = canvas.width;\n const ch = canvas.height;\n if (this.#pageAspect > 0) {\n const bookAspect = (this.#fill ? 1 : 2) * this.#pageAspect;\n if (bookAspect > cw / ch) {\n this.#bookW = cw;\n this.#bookH = Math.round(cw / bookAspect);\n } else {\n this.#bookH = ch;\n this.#bookW = Math.round(ch * bookAspect);\n }\n } else {\n this.#bookW = cw;\n this.#bookH = ch;\n }\n const bx = Math.round((cw - this.#bookW) / 2);\n const by = Math.round((ch - this.#bookH) / 2); // centered, so GL's bottom offset == by\n gl.viewport(bx, by, this.#bookW, this.#bookH);\n }\n\n #drawStatic(): void {\n const w = this.#bookW;\n const h = this.#bookH;\n const content = this.#content!;\n this.#shiftX = this.#fill ? 0 : shiftUnit(content) * (w / 4);\n this.#useFlat();\n if (this.#fill) {\n this.#drawQuad({ x: 0, y: 0, w, h }, content.right ?? content.left);\n } else {\n // A lone page (one side null) gets no gutter shadow — it's a standalone, centered page.\n this.#drawQuad({ x: 0, y: 0, w: w / 2, h }, content.left, content.right ? 1 : 0);\n this.#drawQuad({ x: w / 2, y: 0, w: w / 2, h }, content.right, content.left ? -1 : 0);\n }\n }\n\n #drawFlip(): void {\n const gl = this.#gl!;\n const w = this.#bookW;\n const h = this.#bookH;\n const flip = this.#flip!;\n\n // Interpolate the lone-page centering across the flip so an opening cover (or a\n // closing back page) slides between centered and spread instead of jumping.\n this.#shiftX = flip.fill\n ? 0\n : (this.#fromShiftUnit + (this.#toShiftUnit - this.#fromShiftUnit) * this.#flipT) * (w / 4);\n\n // Static pages underneath (with gutter shadow).\n this.#useFlat();\n if (flip.fill) {\n this.#drawQuad({ x: 0, y: 0, w, h }, flip.underFull);\n } else {\n this.#drawQuad({ x: 0, y: 0, w: w / 2, h }, flip.underLeft, 1);\n this.#drawQuad({ x: w / 2, y: 0, w: w / 2, h }, flip.underRight, -1);\n }\n\n if (flip.front === null && flip.back === null) return;\n\n // Deform the leaf mesh with the selected curl model on the CPU, upload it, then draw.\n const leafW = flip.fill ? w : w / 2;\n const originX = flip.fill ? (flip.dir > 0 ? 0 : w) : w / 2;\n // Some curls (roll) assume a centered spine or a neighbouring page; in single-page mode\n // they use a fill-specific variant that reads on a lone page instead of flopping off-screen.\n const model = CURLS[this.#curlType];\n const deform = flip.fill && model.deformFill ? model.deformFill : model.deform;\n deform(this.#mesh, leafW, h, this.#flipT, this.#anchor);\n gl.bindBuffer(gl.ARRAY_BUFFER, this.#posBuf);\n gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.#mesh.positions);\n gl.bindBuffer(gl.ARRAY_BUFFER, this.#normBuf);\n gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.#mesh.normals);\n\n this.#bindFace(gl.TEXTURE0, flip.front);\n this.#bindFace(gl.TEXTURE1, flip.back);\n gl.activeTexture(gl.TEXTURE0);\n\n gl.useProgram(this.#curl);\n gl.bindVertexArray(this.#curlVao);\n gl.uniform2f(this.#curlU.uViewport ?? null, w, h);\n gl.uniform3f(\n this.#curlU.uView ?? null,\n this.#view.scale,\n this.#view.tx * this.#dpr + this.#shiftX,\n this.#view.ty * this.#dpr,\n );\n gl.uniform1f(this.#curlU.uOriginX ?? null, originX);\n gl.uniform1f(this.#curlU.uDir ?? null, flip.dir);\n gl.uniform1f(this.#curlU.uLeafW ?? null, leafW);\n gl.uniform1f(this.#curlU.uGloss ?? null, this.#curlType === 'simple' ? 0 : 1); // flat curl = no shine\n gl.drawElements(gl.TRIANGLES, this.#idxCount, gl.UNSIGNED_SHORT, 0);\n }\n\n #useFlat(): void {\n const gl = this.#gl!;\n gl.useProgram(this.#flat);\n gl.bindVertexArray(this.#quadVao);\n gl.activeTexture(gl.TEXTURE0);\n gl.uniform2f(this.#flatU.uViewport ?? null, this.#bookW, this.#bookH);\n gl.uniform3f(\n this.#flatU.uView ?? null,\n this.#view.scale,\n this.#view.tx * this.#dpr + this.#shiftX,\n this.#view.ty * this.#dpr,\n );\n }\n\n #drawQuad(rect: Rect, source: TexImageSource | null, gutterSide = 0): void {\n const gl = this.#gl!;\n if (source === null) return;\n this.#bindFace(gl.TEXTURE0, source);\n gl.uniform4f(this.#flatU.uRect ?? null, rect.x, rect.y, rect.w, rect.h);\n gl.uniform1f(this.#flatU.uGutterSide ?? null, gutterSide);\n gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);\n }\n\n #bindFace(unit: number, source: TexImageSource | null): void {\n const gl = this.#gl!;\n gl.activeTexture(unit);\n gl.bindTexture(gl.TEXTURE_2D, source !== null ? this.#textureFor(source) : this.#blankTex);\n }\n\n #textureFor(source: TexImageSource): WebGLTexture {\n const gl = this.#gl!;\n const existing = this.#texCache.get(source);\n if (existing !== undefined) {\n this.#texCache.delete(source);\n this.#texCache.set(source, existing);\n return existing.tex;\n }\n const tex = createTexture(gl);\n uploadTexture(gl, tex, source);\n const dims = source as unknown as { width: number; height: number };\n const bytes = dims.width * dims.height * 4;\n this.#texCache.set(source, { tex, bytes });\n this.#cacheBytes += bytes;\n this.#evictTextures();\n return tex;\n }\n\n #evictTextures(): void {\n const gl = this.#gl!;\n for (const [src, cached] of this.#texCache) {\n if (this.#cacheBytes <= MAX_TEXTURE_CACHE_BYTES || this.#texCache.size <= 4) break;\n this.#texCache.delete(src);\n this.#cacheBytes -= cached.bytes;\n gl.deleteTexture(cached.tex);\n }\n }\n\n #makeBlankTexture(gl: WebGL2RenderingContext): WebGLTexture {\n const tex = createTexture(gl);\n gl.bindTexture(gl.TEXTURE_2D, tex);\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([0, 0, 0, 0]));\n return tex;\n }\n\n #resize(): void {\n const gl = this.#gl;\n const canvas = this.#canvas;\n const el = this.#container;\n if (gl === null || canvas === null || el === null) return;\n this.#dpr = typeof devicePixelRatio === 'number' ? devicePixelRatio : 1;\n const w = Math.max(1, Math.round(el.clientWidth * this.#dpr));\n const h = Math.max(1, Math.round(el.clientHeight * this.#dpr));\n if (canvas.width !== w || canvas.height !== h) {\n canvas.width = w;\n canvas.height = h;\n gl.viewport(0, 0, w, h);\n }\n }\n}\n","import type { Renderer } from './types';\n\nexport type RendererKind = 'css' | 'webgl2';\n\n/**\n * How the consumer chooses a renderer:\n * - `'auto'` (default): prefer the GPU path (WebGL2), else CSS.\n * - a single kind: force it (`'webgl2'` throws if the device has no WebGL2).\n * - an ordered array: try each in turn, first viable wins.\n * - a `Renderer` instance: use it as-is (custom implementation, §6.1/§11).\n */\nexport type RendererOption = 'auto' | RendererKind | RendererKind[] | Renderer;\n\nexport interface Capabilities {\n /** WebGL2 available — the GPU renderer's only backend. */\n gpu: boolean;\n}\n\ntype RendererLoader = () => Promise<Renderer>;\n\n/**\n * Lazy loaders, one per kind. Each is a dynamic `import()` so the bundler\n * code-splits it into its own chunk and a device fetches only the one selected.\n */\nconst LOADERS: Partial<Record<RendererKind, RendererLoader>> = {\n css: async () => new (await import('./cssRenderer')).CssRenderer(),\n webgl2: async () => new (await import('./webglRenderer')).WebglRenderer(),\n};\n\n// The WebGL2 renderer is auto-selected on GPU-capable devices; CSS is the baseline\n// for non-GPU devices and the fallback for unrecoverable GPU failures (§8.4).\nconst WEBGL2_AUTO = true;\n\nfunction isRenderer(option: RendererOption): option is Renderer {\n return (\n typeof option === 'object' &&\n option !== null &&\n !Array.isArray(option) &&\n typeof (option as Renderer).mount === 'function'\n );\n}\n\nfunction autoOrder(caps: Capabilities): RendererKind[] {\n return caps.gpu && WEBGL2_AUTO ? ['webgl2', 'css'] : ['css'];\n}\n\n/** Detect WebGL2 support — the GPU renderer's only backend (no WebGL1, no WebGPU). */\nexport function detectCapabilities(): Capabilities {\n return { gpu: hasWebGl2() };\n}\n\nfunction hasWebGl2(): boolean {\n try {\n return Boolean(document.createElement('canvas').getContext('webgl2'));\n } catch {\n return false;\n }\n}\n\n/**\n * Resolve the `renderer` option to a mounted renderer instance, lazy-loading its\n * chunk. Throws an agent-actionable error if nothing viable can be loaded.\n */\nexport async function selectRenderer(\n option: RendererOption = 'auto',\n caps: Capabilities = detectCapabilities(),\n): Promise<Renderer> {\n if (isRenderer(option)) return option;\n\n const order = Array.isArray(option) ? option : option === 'auto' ? autoOrder(caps) : [option];\n\n for (const kind of order) {\n if (kind === 'webgl2' && !caps.gpu) continue; // skip the GPU path without WebGL2\n const loader = LOADERS[kind];\n if (loader) return loader();\n }\n\n if (order.length === 1 && order[0] === 'webgl2' && !caps.gpu) {\n throw new Error(\n \"renderer: 'webgl2' was forced but this device has no WebGL2. Use 'css' or 'auto'.\",\n );\n }\n throw new Error(\n `renderer: none of [${order.join(', ')}] could be loaded — use 'css' or 'auto'.`,\n );\n}\n","import type { PageContent } from '../renderer/types';\nimport type { Source } from './types';\n\nexport interface CompositionOptions {\n /** Image URL prepended as a lone front cover (adds a page). */\n frontCover?: string | null;\n /** Image URL appended as a lone back cover (adds a page). */\n backCover?: string | null;\n /** Replace source pages with image URLs, keyed by 0-based source index (negative = from the end). */\n pages?: Record<number, string> | null;\n}\n\n/**\n * Wrap `base` so image covers/replacements sit alongside it, or return `base`\n * unchanged when nothing is requested. Covers ADD pages (front prepended, back\n * appended); `pages` REPLACE existing source pages. `pages` indexes the base's own\n * pages, so it is unaffected by an added cover.\n */\nexport function composeSource(base: Source, options: CompositionOptions): Source {\n const hasFront = typeof options.frontCover === 'string';\n const hasBack = typeof options.backCover === 'string';\n const hasPages = options.pages != null && Object.keys(options.pages).length > 0;\n if (!hasFront && !hasBack && !hasPages) return base;\n return new CompositeSource(base, options);\n}\n\nfunction loadImage(url: string): Promise<ImageBitmap> {\n return fetch(url)\n .then((res) => {\n if (!res.ok) throw new Error(`zine: could not load image \"${url}\" (HTTP ${res.status}).`);\n return res.blob();\n })\n .then((blob) => createImageBitmap(blob));\n}\n\nclass CompositeSource implements Source {\n #base: Source;\n #front: string | null;\n #back: string | null;\n #rawPages: Record<number, string>;\n #resolved = new Map<number, string>(); // base-index → url (negatives resolved)\n #cache = new Map<string, Promise<ImageBitmap>>();\n open?: () => Promise<void>;\n onPageUpdate?: (handler: (index: number) => void) => void;\n\n constructor(base: Source, options: CompositionOptions) {\n this.#base = base;\n this.#front = typeof options.frontCover === 'string' ? options.frontCover : null;\n this.#back = typeof options.backCover === 'string' ? options.backCover : null;\n this.#rawPages = options.pages ?? {};\n\n if (typeof base.open === 'function') {\n // Async base: page count (and negative indices) known only after open().\n this.open = async (): Promise<void> => {\n await base.open!();\n this.#resolvePages();\n };\n } else {\n this.#resolvePages(); // sync base: count is known now\n }\n\n if (typeof base.onPageUpdate === 'function') {\n // Forward base page updates, shifting to book indices (past the front cover).\n this.onPageUpdate = (handler) => {\n base.onPageUpdate!((src) => handler(src + (this.#front !== null ? 1 : 0)));\n };\n }\n }\n\n get pageCount(): number {\n return this.#base.pageCount + (this.#front !== null ? 1 : 0) + (this.#back !== null ? 1 : 0);\n }\n\n get(index: number): Promise<PageContent> {\n const frontOffset = this.#front !== null ? 1 : 0;\n if (this.#front !== null && index === 0) return this.#image(this.#front);\n if (this.#back !== null && index === this.pageCount - 1) return this.#image(this.#back);\n const src = index - frontOffset;\n const override = this.#resolved.get(src);\n return override !== undefined ? this.#image(override) : this.#base.get(src);\n }\n\n prefetch(indices: number[]): void {\n const frontOffset = this.#front !== null ? 1 : 0;\n const baseIndices: number[] = [];\n for (const index of indices) {\n if (this.#front !== null && index === 0) {\n void this.#image(this.#front).catch(() => {});\n } else if (this.#back !== null && index === this.pageCount - 1) {\n void this.#image(this.#back).catch(() => {});\n } else {\n const src = index - frontOffset;\n const override = this.#resolved.get(src);\n if (override !== undefined) void this.#image(override).catch(() => {});\n else baseIndices.push(src);\n }\n }\n this.#base.prefetch(baseIndices);\n }\n\n destroy(): void {\n this.#base.destroy();\n for (const promise of this.#cache.values()) {\n void promise.then((bmp) => bmp.close()).catch(() => {});\n }\n this.#cache.clear();\n }\n\n #resolvePages(): void {\n const n = this.#base.pageCount;\n this.#resolved.clear();\n for (const [key, url] of Object.entries(this.#rawPages)) {\n const raw = Number(key);\n const src = raw < 0 ? n + raw : raw;\n if (Number.isInteger(src) && src >= 0 && src < n) this.#resolved.set(src, url);\n }\n }\n\n #image(url: string): Promise<ImageBitmap> {\n let promise = this.#cache.get(url);\n if (promise === undefined) {\n promise = loadImage(url).catch((error: unknown) => {\n this.#cache.delete(url); // let a later get() retry\n throw error;\n });\n this.#cache.set(url, promise);\n }\n return promise;\n }\n}\n","import {\n buildSpreads,\n shouldSinglePage,\n type Direction,\n type Spread,\n type SpreadMode,\n} from './engine/spread';\nimport { Virtualizer } from './engine/virtualizer';\nimport { Emitter, type ZineEventMap } from './engine/emitter';\nimport { FlipMachine } from './engine/stateMachine';\nimport { PointerRecognizer, PinchRecognizer, bindGestures, type GestureEnd } from './engine/input';\nimport { hitTest } from './geometry/hitTest';\nimport { CURL_TYPES, DEFAULT_CURL, type CurlType } from './geometry/curls/types';\nimport { selectRenderer, type RendererOption } from './renderer/select';\nimport type { FlipDirection, PageContent, Renderer, SpreadContent } from './renderer/types';\nimport type { Source } from './source/types';\nimport { composeSource } from './source/compose';\n\n/** Grab-zone size as a fraction of the smaller container dimension. */\nconst CORNER_FRACTION = 0.25;\n\n/** Wheel-zoom sensitivity: scale multiplies by exp(-deltaY * this) per wheel event. */\nconst WHEEL_ZOOM_SENSITIVITY = 0.0015;\n\n/** Pointer movement (px) beyond which a press becomes a drag rather than a tap. */\nconst DRAG_THRESHOLD = 6;\n\n/** Window (ms) a single click waits to rule out a double-click before flipping. */\nconst DOUBLE_CLICK_MS = 250;\n\n/** The single-page roll turns with a bent flip (no spread to roll onto); it reads better a\n * touch slower than the spread roll, so its flip duration is scaled up by this automatically. */\nconst SINGLE_PAGE_ROLL_SLOWDOWN = 1.75;\n\ninterface DragState {\n direction: FlipDirection;\n targetIndex: number;\n toPage: number;\n toContent: SpreadContent;\n width: number;\n t: number;\n}\n\nexport interface ZoomOptions {\n /** Whether zooming is allowed at all; default true. */\n enabled?: boolean;\n /** Maximum zoom scale; default 4. */\n max?: number;\n /** Zoom on Ctrl/⌘ + wheel (also how trackpad pinch arrives on desktop); default true. */\n wheel?: boolean;\n /** Zoom levels cycled by double-click (wraps to the first); `false` disables. Default [1, 2, 4]. */\n doubleClick?: number[] | false;\n /**\n * Listen for double-click zoom inside the click-to-flip zones. Default: off in 'edge' mode\n * (edges flip instantly, no delay), on in 'half' mode. Turning it on in 'edge' mode makes\n * clicks wait out `clickFlipDelay` so a double-click can preempt them with a zoom.\n */\n doubleClickInFlipZone?: boolean;\n}\n\nexport interface ZineOptions {\n /** Content source (e.g. an ImageSource). Required. */\n source: Source;\n /** Renderer selection; default 'auto'. */\n renderer?: RendererOption;\n /** Page-curl model for the WebGL2 renderer: 'roll' | 'simple' | 'fold' | 'peel'. Default 'roll'. */\n curl?: CurlType;\n /** Fixed container width in px; omit to let the container/CSS drive the size. */\n width?: number;\n /** Fixed container height in px; omit to let the container/CSS drive the size. */\n height?: number;\n /** Reading direction; default 'ltr'. */\n direction?: Direction;\n /** How pages group into spreads: 'double' | 'single' | 'cover' | 'book'. Default 'cover'. */\n spreadMode?: SpreadMode;\n /** Image URL prepended as a lone front cover (adds a page). */\n frontCover?: string;\n /** Image URL appended as a lone back cover (adds a page). */\n backCover?: string;\n /** Replace source pages with image URLs, keyed by 0-based source index (negative = from the end). */\n pages?: Record<number, string>;\n /** Page to open on; default 0. */\n startPage?: number;\n /** Flip animation duration in ms; default 500. */\n flipDuration?: number;\n /** How a tap/click turns pages: near an edge ('edge'), by page half ('half'), or 'off'. Default 'edge'. */\n clickToFlip?: 'edge' | 'half' | 'off';\n /** Edge-zone size in px per side, used when clickToFlip is 'edge'. Default 64. */\n clickZoneSize?: number;\n /**\n * Delay (ms) a click waits before flipping, so a double-click can preempt it with a zoom.\n * Omit for auto: 0 when double-click zoom is inactive, 250 when it's active.\n */\n clickFlipDelay?: number;\n /** Zoom behavior. */\n zoom?: ZoomOptions;\n /** Container widths below this (px) switch to one page per spread; default 640. */\n singlePageThreshold?: number;\n}\n\n/**\n * The public flipbook. Composes the engine (spreads, virtualizer, events), a\n * lazily-selected renderer, and a content source. Construction is synchronous\n * but setup is async — await `ready` (or listen for the `ready` event) before\n * driving it.\n */\nexport class Zine {\n #container: HTMLElement;\n #source: Source;\n #emitter = new Emitter<ZineEventMap>();\n #virtualizer = new Virtualizer(2);\n #machine = new FlipMachine();\n #direction: Direction;\n #spreadMode: SpreadMode;\n #curl: CurlType;\n #anchorY = 1; // where the last tap/drag grabbed (0=top, 1=bottom); drives anchored curls\n #clickToFlip: 'edge' | 'half' | 'off';\n #clickZoneSize: number;\n #honorDoubleClickInFlipZone: boolean;\n #clickFlipDelayValue: number;\n #singlePageThreshold: number;\n #singlePage = false;\n #narrow = false; // responsive: container currently below singlePageThreshold\n #lastAspect = ''; // last container aspect-ratio written (avoids redundant style writes)\n #startPageOption: number | undefined;\n #spreads: Spread[] = [];\n #current = 0;\n #currentPage = 0;\n #currentContent: SpreadContent = { left: null, right: null };\n #flipDuration: number;\n #zoomEnabled: boolean;\n #wheelZoom: boolean;\n #doubleClickLevels: number[] | null;\n #maxZoom: number;\n #resizeObserver: ResizeObserver | null = null;\n #updateScheduled = false;\n #scale = 1;\n #tx = 0;\n #ty = 0;\n #renderer: Renderer | null = null;\n #fellBack = false;\n #destroyed = false;\n #raf: number | null = null;\n #drag: DragState | null = null;\n #pendingGrab: { direction: FlipDirection; targetIndex: number; toPage: number; width: number } | null = null;\n #press: { x: number; y: number } | null = null;\n #pendingClickTimer: ReturnType<typeof setTimeout> | null = null;\n #pan: { baseTx: number; baseTy: number } | null = null;\n #pinching = false;\n #pinchBaseScale = 1;\n #reducedMotion = false;\n #liveRegion: HTMLElement | null = null;\n #unbindInput: (() => void) | null = null;\n #unbindWheel: (() => void) | null = null;\n #unbindDblClick: (() => void) | null = null;\n #a11yCleanup: (() => void) | null = null;\n #ready: Promise<void>;\n\n /** Stable seek API: drive the fold to a fixed progress without animating (visual regression). */\n readonly debug = {\n setFlipProgress: (t: number, direction: FlipDirection): void => {\n this.#renderer?.setFlipProgress(t, direction);\n },\n };\n\n constructor(container: HTMLElement, options: ZineOptions) {\n validateOptions(container, options);\n this.#container = container;\n if (options.width !== undefined) container.style.width = `${options.width}px`;\n if (options.height !== undefined) container.style.height = `${options.height}px`;\n this.#source = composeSource(options.source, {\n frontCover: options.frontCover,\n backCover: options.backCover,\n pages: options.pages,\n });\n const direction = options.direction ?? 'ltr';\n this.#direction = direction;\n this.#spreadMode = options.spreadMode ?? 'cover';\n this.#curl = options.curl ?? DEFAULT_CURL;\n this.#clickToFlip = options.clickToFlip ?? 'edge';\n this.#clickZoneSize = options.clickZoneSize ?? 64;\n this.#singlePageThreshold = options.singlePageThreshold ?? 640;\n this.#startPageOption = options.startPage;\n // Sync sources (a known page count) build spreads now — so bad pageCount/startPage\n // throw immediately from `new Zine`. Async sources (an `open()`) defer to #init.\n if (typeof this.#source.open !== 'function') {\n this.#buildSpreadModel();\n }\n this.#flipDuration = options.flipDuration ?? 800;\n this.#zoomEnabled = options.zoom?.enabled ?? true;\n this.#wheelZoom = options.zoom?.wheel ?? true;\n const dbl = options.zoom?.doubleClick;\n const levels = dbl === false ? [] : [...(dbl ?? [1, 2, 4])].sort((a, b) => a - b);\n this.#doubleClickLevels = levels.length > 0 ? levels : null;\n this.#maxZoom = options.zoom?.max ?? 4;\n\n // Arbitrate click-to-flip vs double-click zoom inside the flip zones.\n // Listen for double-click zoom in flip zones: default off in 'edge', on in 'half'.\n // clickFlipDelay === 0 hard-disables it. When honored, a delay lets a click wait\n // out a possible double-click; auto default 250 ms, overridable.\n const doubleClickZoomActive = this.#zoomEnabled && this.#doubleClickLevels !== null;\n const listenInFlipZone = options.zoom?.doubleClickInFlipZone ?? (this.#clickToFlip === 'half');\n this.#honorDoubleClickInFlipZone =\n this.#clickToFlip !== 'off' &&\n doubleClickZoomActive &&\n listenInFlipZone &&\n options.clickFlipDelay !== 0;\n this.#clickFlipDelayValue = this.#honorDoubleClickInFlipZone\n ? (options.clickFlipDelay ?? DOUBLE_CLICK_MS)\n : 0;\n\n this.#ready = this.#init(options.renderer ?? 'auto');\n }\n\n /** Resolves once the renderer is mounted and the first spread is painted. */\n get ready(): Promise<void> {\n return this.#ready;\n }\n\n getPageCount(): number {\n return this.#source.pageCount;\n }\n\n getPage(): number {\n return this.#currentPage;\n }\n\n flipNext(): void {\n this.#startFlip(this.#current + 1);\n }\n\n flipPrev(): void {\n this.#startFlip(this.#current - 1);\n }\n\n flipTo(page: number): void {\n const target = clamp(page, 0, Math.max(0, this.#source.pageCount - 1));\n this.#startFlip(this.#spreadIndexForPage(target));\n }\n\n getZoom(): number {\n return this.#scale;\n }\n\n /** Zoom to `scale` (clamped to [1, zoom.max]), keeping `center` (container-local) fixed. */\n setZoom(scale: number, center?: { x: number; y: number }): void {\n if (!this.#renderer || !this.#zoomEnabled) return;\n const s2 = clamp(scale, 1, this.#maxZoom);\n const m = this.#renderer.measure();\n const focal = center ?? { x: m.containerWidth / 2, y: m.containerHeight / 2 };\n const s1 = this.#scale;\n // Solve for the translate that keeps the focal screen point fixed as s1→s2.\n let tx = s2 === 1 ? 0 : focal.x - (s2 / s1) * (focal.x - this.#tx);\n let ty = s2 === 1 ? 0 : focal.y - (s2 / s1) * (focal.y - this.#ty);\n [tx, ty] = this.#clampPan(tx, ty, s2, m.containerWidth, m.containerHeight);\n this.#scale = s2;\n this.#tx = tx;\n this.#ty = ty;\n this.#renderer.setViewTransform(s2, tx, ty);\n this.#emitter.emit('zoomChanged', { scale: s2 });\n }\n\n resetZoom(): void {\n this.setZoom(1);\n }\n\n #clampPan(tx: number, ty: number, scale: number, w: number, h: number): [number, number] {\n // Keep the scaled content covering the viewport (transform-origin is 0,0).\n return [clamp(tx, w * (1 - scale), 0), clamp(ty, h * (1 - scale), 0)];\n }\n\n on<K extends keyof ZineEventMap>(\n event: K,\n listener: (payload: ZineEventMap[K]) => void,\n ): () => void {\n return this.#emitter.on(event, listener);\n }\n\n destroy(): void {\n this.#destroyed = true;\n if (this.#raf !== null) cancelAnimationFrame(this.#raf);\n this.#clearPendingClickFlip();\n this.#resizeObserver?.disconnect();\n this.#a11yCleanup?.();\n this.#unbindWheel?.();\n this.#unbindDblClick?.();\n this.#unbindInput?.();\n this.#renderer?.destroy();\n this.#renderer = null;\n this.#source.destroy();\n this.#emitter.clear();\n }\n\n #startFlip(targetIndex: number): void {\n if (targetIndex < 0 || targetIndex >= this.#spreads.length || targetIndex === this.#current) {\n return;\n }\n // `flip` is legal only from idle; otherwise a flip/drag is already in flight.\n if (this.#machine.send('flip') === null) return;\n\n const direction: FlipDirection = targetIndex > this.#current ? 'forward' : 'backward';\n const toPage = this.#leadPage(targetIndex);\n // State is already locked (send('flip') above), so re-entrant flips are rejected\n // even though staging the destination content below is async.\n this.#emitter.emit('flipStart', { from: this.#currentPage, to: toPage });\n void this.#runFlip(targetIndex, direction, toPage);\n }\n\n async #runFlip(targetIndex: number, direction: FlipDirection, toPage: number): Promise<void> {\n const toSpread = this.#spreads[targetIndex];\n const toContent: SpreadContent = toSpread\n ? await this.#resolveContent(toSpread)\n : { left: null, right: null };\n this.#renderer?.beginFlip(this.#currentContent, toContent, direction, {\n fill: this.#singlePage,\n curl: this.#curl,\n anchor: { y: this.#anchorY },\n });\n this.#animateProgress(0, 1, direction, () => this.#commit(targetIndex, toPage, toContent));\n }\n\n /** Animate the fold from `fromT` to `toT`, easing per-frame, then run `onDone`. */\n #animateProgress(\n fromT: number,\n toT: number,\n direction: FlipDirection,\n onDone: () => void,\n ): void {\n const duration = this.#effectiveDuration() * Math.abs(toT - fromT);\n if (duration <= 0) {\n // Reduced motion (or zero-duration): swap without the curl sweep.\n this.#renderer?.setFlipProgress(toT, direction);\n onDone();\n return;\n }\n const start = performance.now();\n const step = (now: number): void => {\n // Easing lives here; flipProgressToPose stays linear so seeks are deterministic.\n const raw = Math.min(1, (now - start) / duration);\n this.#renderer?.setFlipProgress(fromT + (toT - fromT) * easeInOutCubic(raw), direction);\n if (raw < 1) {\n this.#raf = requestAnimationFrame(step);\n } else {\n this.#raf = null;\n onDone();\n }\n };\n this.#raf = requestAnimationFrame(step);\n }\n\n #commit(targetIndex: number, toPage: number, toContent: SpreadContent): void {\n const spread = this.#spreads[targetIndex];\n this.#current = targetIndex;\n this.#currentPage = toPage;\n this.#currentContent = toContent;\n // renderSpread paints the landed spread and clears the turning leaf.\n if (spread) this.#paintSpread(spread, toContent);\n this.#prefetchWindow();\n this.#machine.send('settle');\n this.#announce();\n this.#emitter.emit('pageChanged', { page: toPage });\n this.#emitter.emit('flipEnd', { page: toPage });\n }\n\n #leadPage(spreadIndex: number): number {\n const spread = this.#spreads[spreadIndex];\n if (!spread) return this.#currentPage;\n const pages = [spread.left, spread.right].filter((p): p is number => p !== null);\n return pages.length > 0 ? Math.min(...pages) : this.#currentPage;\n }\n\n #onDragStart(clientX: number, clientY: number): void {\n if (this.#pinching || !this.#renderer || this.#machine.state !== 'idle') return;\n this.#clearPendingClickFlip(); // a new press cancels a click-flip still waiting out its window\n // Zoomed in → a drag pans; at scale 1 → a corner drag flips (§9 mode switch).\n if (this.#scale > 1) {\n if (this.#machine.send('panStart') === null) return;\n this.#pan = { baseTx: this.#tx, baseTy: this.#ty };\n return;\n }\n const rect = this.#container.getBoundingClientRect();\n const b = this.#contentRect();\n // Points are relative to the letterboxed book, so zones/corners track the page, not the bars.\n const point = { x: clientX - rect.left - b.x, y: clientY - rect.top - b.y };\n this.#press = point; // remembered for tap classification / click-to-flip zone\n const cornerSize = Math.min(b.width, b.height) * CORNER_FRACTION;\n if (hitTest(point, { width: b.width, height: b.height }, cornerSize) !== 'corner') {\n return; // not a corner — no drag; a tap here may still click-to-flip on release\n }\n this.#anchorY = clamp(point.y / b.height, 0, 1); // fold anchors at the grabbed corner\n // Arm a potential drag; it only becomes a real flip once the pointer moves\n // (so a corner *tap* never fires a spurious flipStart). Right-side corner\n // turns the page forward in LTR; RTL mirrors it.\n const rightSide = point.x > b.width / 2;\n const forward = this.#direction === 'rtl' ? !rightSide : rightSide;\n const targetIndex = this.#current + (forward ? 1 : -1);\n if (targetIndex < 0 || targetIndex >= this.#spreads.length) return;\n this.#pendingGrab = {\n direction: forward ? 'forward' : 'backward',\n targetIndex,\n toPage: this.#leadPage(targetIndex),\n width: b.width,\n };\n }\n\n /** Turn an armed corner press into a live drag flip once the pointer has moved. */\n #promoteGrab(): void {\n const grab = this.#pendingGrab;\n if (!grab) return;\n this.#pendingGrab = null;\n if (this.#machine.send('grab') === null) return;\n this.#drag = {\n direction: grab.direction,\n targetIndex: grab.targetIndex,\n toPage: grab.toPage,\n toContent: { left: null, right: null },\n width: grab.width,\n t: 0,\n };\n this.#emitter.emit('flipStart', { from: this.#currentPage, to: grab.toPage });\n void this.#stageDrag(grab.targetIndex, grab.direction);\n }\n\n async #stageDrag(targetIndex: number, direction: FlipDirection): Promise<void> {\n const toSpread = this.#spreads[targetIndex];\n const toContent: SpreadContent = toSpread\n ? await this.#resolveContent(toSpread)\n : { left: null, right: null };\n // The drag may have ended (or retargeted) while content was resolving.\n if (this.#drag?.targetIndex !== targetIndex) return;\n this.#drag.toContent = toContent;\n this.#renderer?.beginFlip(this.#currentContent, toContent, direction, {\n fill: this.#singlePage,\n curl: this.#curl,\n anchor: { y: this.#anchorY },\n });\n this.#renderer?.setFlipProgress(this.#drag.t, direction);\n }\n\n #onDragMove(dx: number, dy: number): void {\n if (this.#pinching) return;\n if (this.#pan) {\n if (!this.#renderer) return;\n const m = this.#renderer.measure();\n const [tx, ty] = this.#clampPan(\n this.#pan.baseTx + dx,\n this.#pan.baseTy + dy,\n this.#scale,\n m.containerWidth,\n m.containerHeight,\n );\n this.#tx = tx;\n this.#ty = ty;\n this.#renderer.setViewTransform(this.#scale, tx, ty);\n return;\n }\n // An armed corner press becomes a real flip once it moves past the threshold.\n if (this.#pendingGrab && Math.hypot(dx, dy) > DRAG_THRESHOLD) {\n this.#promoteGrab();\n }\n const drag = this.#drag;\n if (!drag) return;\n const signed = drag.direction === 'forward' ? -dx : dx;\n drag.t = clamp(signed / drag.width, 0, 1);\n this.#renderer?.setFlipProgress(drag.t, drag.direction);\n }\n\n #onDragEnd(gesture: GestureEnd): void {\n if (this.#pinching) return;\n if (this.#pan) {\n this.#pan = null;\n this.#machine.send('panEnd');\n return;\n }\n const drag = this.#drag;\n if (!drag) {\n // Never became a drag → it was a tap; maybe flip via clickToFlip.\n this.#pendingGrab = null;\n this.#maybeClickFlip(gesture);\n return;\n }\n this.#drag = null;\n this.#machine.send('release');\n\n const swiped =\n gesture.swipe &&\n (drag.direction === 'forward' ? gesture.dx < 0 : gesture.dx > 0);\n if (drag.t >= 0.5 || swiped) {\n this.#animateProgress(drag.t, 1, drag.direction, () =>\n this.#commit(drag.targetIndex, drag.toPage, drag.toContent),\n );\n } else {\n this.#animateProgress(drag.t, 0, drag.direction, () => this.#cancelFlip());\n }\n }\n\n #maybeClickFlip(gesture: GestureEnd): void {\n if (this.#clickToFlip === 'off' || this.#scale > 1 || !this.#press) return;\n // A tap barely moves; anything more was a drag we already ignored.\n if (Math.abs(gesture.dx) > DRAG_THRESHOLD || Math.abs(gesture.dy) > DRAG_THRESHOLD) return;\n const direction = this.#clickFlipDirection(this.#press);\n if (!direction) return;\n const targetIndex = this.#current + (direction === 'forward' ? 1 : -1);\n if (targetIndex < 0 || targetIndex >= this.#spreads.length) return;\n // Anchor the fold at the tapped height (the fold/peel curls fold from where you tap).\n this.#anchorY = clamp(this.#press.y / this.#contentRect().height, 0, 1);\n this.#clearPendingClickFlip();\n if (this.#clickFlipDelayValue <= 0) {\n // No double-click competing here → flip right away.\n this.#startFlip(targetIndex);\n return;\n }\n // Wait out the window; a double-click (zoom) cancels this.\n this.#pendingClickTimer = setTimeout(() => {\n this.#pendingClickTimer = null;\n this.#startFlip(targetIndex);\n }, this.#clickFlipDelayValue);\n }\n\n /** Which way a tap at `point` (container-local) turns the page, or null for a dead zone. */\n /** Where the current spread is actually drawn (lone pages centered), as the renderer reports\n * it — the region taps/drags map into. Falls back to book, then the full container. */\n #contentRect(): { x: number; y: number; width: number; height: number } {\n const m = this.#renderer!.measure();\n return m.content ?? m.book ?? { x: 0, y: 0, width: m.containerWidth, height: m.containerHeight };\n }\n\n #clickFlipDirection(point: { x: number; y: number }): FlipDirection | null {\n if (!this.#renderer) return null;\n const containerWidth = this.#contentRect().width;\n let side: 'left' | 'right' | null;\n if (this.#clickToFlip === 'half') {\n side = point.x > containerWidth / 2 ? 'right' : 'left';\n } else if (point.x <= this.#clickZoneSize) {\n side = 'left';\n } else if (point.x >= containerWidth - this.#clickZoneSize) {\n side = 'right';\n } else {\n side = null; // center dead zone in 'edge' mode\n }\n if (!side) return null;\n const forwardSide = this.#direction === 'rtl' ? 'left' : 'right';\n return side === forwardSide ? 'forward' : 'backward';\n }\n\n #clearPendingClickFlip(): void {\n if (this.#pendingClickTimer !== null) {\n clearTimeout(this.#pendingClickTimer);\n this.#pendingClickTimer = null;\n }\n }\n\n #cancelFlip(): void {\n const spread = this.#spreads[this.#current];\n if (spread) this.#paintSpread(spread, this.#currentContent);\n this.#machine.send('settle');\n this.#emitter.emit('flipEnd', { page: this.#currentPage });\n }\n\n #onPinchStart(): void {\n // A second finger abandons any single-pointer gesture in flight.\n this.#pendingGrab = null;\n this.#clearPendingClickFlip();\n if (this.#drag) {\n this.#drag = null;\n this.#machine.send('release');\n this.#machine.send('settle');\n const spread = this.#spreads[this.#current];\n if (spread) this.#paintSpread(spread, this.#currentContent);\n } else if (this.#pan) {\n this.#pan = null;\n this.#machine.send('panEnd');\n }\n this.#pinching = true;\n this.#pinchBaseScale = this.#scale;\n }\n\n #onPinchMove(centerX: number, centerY: number, scale: number): void {\n if (!this.#pinching) return;\n const rect = this.#container.getBoundingClientRect();\n this.setZoom(this.#pinchBaseScale * scale, { x: centerX - rect.left, y: centerY - rect.top });\n }\n\n #onPinchEnd(): void {\n this.#pinching = false;\n }\n\n #bindWheelZoom(): void {\n const onWheel = (event: WheelEvent): void => {\n // Ctrl/⌘ + wheel only — this is also what a desktop trackpad pinch emits.\n if (!this.#wheelZoom || !this.#zoomEnabled || !(event.ctrlKey || event.metaKey)) return;\n // Override the browser's native page zoom.\n event.preventDefault();\n const rect = this.#container.getBoundingClientRect();\n const factor = Math.exp(-event.deltaY * WHEEL_ZOOM_SENSITIVITY);\n this.setZoom(this.#scale * factor, {\n x: event.clientX - rect.left,\n y: event.clientY - rect.top,\n });\n };\n this.#container.addEventListener('wheel', onWheel as EventListener, { passive: false });\n this.#unbindWheel = () =>\n this.#container.removeEventListener('wheel', onWheel as EventListener);\n }\n\n #bindDoubleClickZoom(): void {\n const onDoubleClick = (event: MouseEvent): void => {\n const levels = this.#doubleClickLevels;\n if (!this.#zoomEnabled || levels === null) return;\n // At scale 1 a double-click inside a flip zone belongs to click-to-flip, not zoom,\n // unless we're honoring double-click zoom there.\n if (this.#scale <= 1 && this.#clickToFlip !== 'off' && !this.#honorDoubleClickInFlipZone) {\n const rect = this.#container.getBoundingClientRect();\n const local = { x: event.clientX - rect.left, y: event.clientY - rect.top };\n if (this.#clickFlipDirection(local) !== null) return; // in a flip zone → leave it to click-to-flip\n }\n // A double-click means the single-click flip we may have queued was really a zoom.\n this.#clearPendingClickFlip();\n event.preventDefault();\n // Next configured level above the current scale, else wrap to the first.\n const next = levels.find((l) => l > this.#scale + 1e-6) ?? levels[0] ?? this.#scale;\n const rect = this.#container.getBoundingClientRect();\n this.setZoom(next, { x: event.clientX - rect.left, y: event.clientY - rect.top });\n };\n this.#container.addEventListener('dblclick', onDoubleClick as EventListener);\n this.#unbindDblClick = () =>\n this.#container.removeEventListener('dblclick', onDoubleClick as EventListener);\n }\n\n async #init(rendererOption: RendererOption): Promise<void> {\n // Load the renderer chunk while opening an async source (e.g. a PDF) in parallel.\n const rendererPromise = selectRenderer(rendererOption);\n if (typeof this.#source.open === 'function') {\n await this.#source.open();\n this.#buildSpreadModel(); // page count known now; validates + builds spreads\n }\n this.#source.prefetch([this.#currentPage]);\n\n const selected = await rendererPromise;\n const renderer = await this.#mountWithFallback(selected);\n this.#renderer = renderer;\n\n // Re-render the current spread when a source upgrades one of its pages in place.\n this.#source.onPageUpdate?.((index) => this.#onPageUpdate(index));\n\n // Now that we can measure, apply single-page mode if the container is narrow.\n this.#applySinglePage(renderer.measure().containerWidth);\n\n const pointer = new PointerRecognizer({\n onStart: (g) => this.#onDragStart(g.x, g.y),\n onMove: (g) => this.#onDragMove(g.dx, g.dy),\n onEnd: (g) => this.#onDragEnd(g),\n });\n const pinch = new PinchRecognizer({\n onPinchStart: () => this.#onPinchStart(),\n onPinchMove: (g) => this.#onPinchMove(g.centerX, g.centerY, g.scale),\n onPinchEnd: () => this.#onPinchEnd(),\n });\n this.#unbindInput = bindGestures(this.#container, { pointer, pinch });\n this.#bindWheelZoom();\n this.#bindDoubleClickZoom();\n this.#setupReducedMotion();\n this.#a11yCleanup = this.#setupA11y();\n\n await this.#renderCurrent();\n this.#observeResize();\n this.#prefetchWindow();\n this.#announce();\n this.#emitter.emit('ready');\n }\n\n /** Mount `renderer`; if it can't initialize (e.g. no WebGL2 context) fall back to CSS. */\n async #mountWithFallback(renderer: Renderer): Promise<Renderer> {\n try {\n await renderer.mount(this.#container);\n renderer.onFatal?.(() => {\n void this.#fallbackToCss();\n });\n return renderer;\n } catch {\n renderer.destroy();\n const css = await selectRenderer('css');\n await css.mount(this.#container);\n this.#fellBack = true;\n this.#emitter.emit('rendererFallback', { from: 'webgl2', to: 'css' });\n return css;\n }\n }\n\n /** Runtime fallback: a live renderer signaled an unrecoverable failure (§8.4). */\n async #fallbackToCss(): Promise<void> {\n if (this.#fellBack || this.#destroyed) return;\n this.#fellBack = true;\n this.#renderer?.destroy();\n this.#renderer = null;\n const css = await selectRenderer('css');\n if (this.#destroyed) {\n css.destroy();\n return;\n }\n await css.mount(this.#container);\n this.#renderer = css;\n this.#applySinglePage(css.measure().containerWidth);\n await this.#renderCurrent();\n this.#emitter.emit('rendererFallback', { from: 'webgl2', to: 'css' });\n }\n\n #setupReducedMotion(): void {\n if (typeof matchMedia !== 'function') return;\n const query = matchMedia('(prefers-reduced-motion: reduce)');\n this.#reducedMotion = query.matches;\n query.addEventListener?.('change', (e) => {\n this.#reducedMotion = e.matches;\n });\n }\n\n /** Wire keyboard nav + an aria-live page announcer. Skips non-DOM containers. */\n #setupA11y(): (() => void) | null {\n const container = this.#container;\n const doc = container.ownerDocument;\n if (!doc || typeof container.setAttribute !== 'function') return null;\n\n if (!container.hasAttribute('tabindex')) container.tabIndex = 0;\n container.setAttribute('aria-roledescription', 'flipbook');\n const onKey = (e: KeyboardEvent): void => this.#onKeyDown(e);\n container.addEventListener('keydown', onKey);\n\n const live = doc.createElement('div');\n live.setAttribute('aria-live', 'polite');\n live.setAttribute('aria-atomic', 'true');\n live.style.cssText =\n 'position:absolute;width:1px;height:1px;margin:-1px;padding:0;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap;border:0;';\n container.appendChild(live);\n this.#liveRegion = live;\n\n return () => {\n container.removeEventListener('keydown', onKey);\n live.remove();\n this.#liveRegion = null;\n };\n }\n\n #onKeyDown(event: KeyboardEvent): void {\n const forwardKey = this.#direction === 'rtl' ? 'ArrowLeft' : 'ArrowRight';\n switch (event.key) {\n case 'ArrowRight':\n case 'ArrowLeft':\n if (event.key === forwardKey) this.flipNext();\n else this.flipPrev();\n event.preventDefault();\n break;\n case 'Home':\n this.flipTo(0);\n event.preventDefault();\n break;\n case 'End':\n this.flipTo(this.#source.pageCount - 1);\n event.preventDefault();\n break;\n default:\n break;\n }\n }\n\n #announce(): void {\n if (this.#liveRegion) {\n this.#liveRegion.textContent = `Page ${this.#currentPage + 1} of ${this.#source.pageCount}`;\n }\n }\n\n #effectiveDuration(): number {\n if (this.#reducedMotion) return 0;\n const singleRoll = this.#singlePage && this.#curl === 'roll';\n return this.#flipDuration * (singleRoll ? SINGLE_PAGE_ROLL_SLOWDOWN : 1);\n }\n\n /** Re-measure and re-render; call after the container resizes. */\n update(): void {\n if (!this.#renderer || this.#machine.state !== 'idle') return;\n this.#applySinglePage(this.#renderer.measure().containerWidth);\n void this.#renderCurrent();\n }\n\n /** The layout to actually use: the responsive narrow fallback forces 'single'. */\n #effectiveMode(): SpreadMode {\n return this.#narrow || this.#spreadMode === 'single' ? 'single' : this.#spreadMode;\n }\n\n #applySinglePage(containerWidth: number): void {\n const narrow = shouldSinglePage(containerWidth, this.#singlePageThreshold);\n if (narrow === this.#narrow) return;\n this.#narrow = narrow;\n const mode = this.#effectiveMode();\n this.#singlePage = mode === 'single';\n this.#spreads = buildSpreads(this.#source.pageCount, { direction: this.#direction, mode });\n this.#current = this.#spreadIndexForPage(this.#currentPage);\n }\n\n async #renderCurrent(): Promise<void> {\n const spread = this.#spreads[this.#current];\n if (!spread || !this.#renderer) return;\n this.#currentContent = await this.#resolveContent(spread);\n this.#paintSpread(spread, this.#currentContent);\n }\n\n #paintSpread(spread: Spread, content: SpreadContent): void {\n this.#renderer?.renderSpread(spread, content, { fill: this.#singlePage });\n this.#applyContainerAspect();\n }\n\n /** Match the container's aspect-ratio to the book so it fits with no letterbox bars.\n * Non-destructive: `aspect-ratio` only drives whichever dimension the consumer leaves\n * auto (fit-width when they set a width), and is ignored if both are fixed. */\n #applyContainerAspect(): void {\n const b = this.#renderer?.measure().book;\n if (!b || b.width <= 0 || b.height <= 0) return;\n const ratio = (b.width / b.height).toFixed(4);\n if (ratio === this.#lastAspect) return;\n this.#lastAspect = ratio;\n this.#container.style.aspectRatio = ratio;\n }\n\n /** A source upgraded a page's content (e.g. progressive PDF); repaint if it's on screen and idle. */\n #onPageUpdate(index: number): void {\n if (this.#machine.state !== 'idle') return; // don't disturb an in-flight flip\n const spread = this.#spreads[this.#current];\n if (spread && (spread.left === index || spread.right === index)) {\n void this.#renderCurrent();\n }\n }\n\n #observeResize(): void {\n if (typeof ResizeObserver === 'undefined') return;\n this.#resizeObserver = new ResizeObserver(() => this.#scheduleUpdate());\n this.#resizeObserver.observe(this.#container);\n }\n\n #scheduleUpdate(): void {\n if (this.#updateScheduled) return;\n this.#updateScheduled = true;\n requestAnimationFrame(() => {\n this.#updateScheduled = false;\n this.update();\n });\n }\n\n async #resolveContent(spread: Spread): Promise<SpreadContent> {\n const [left, right] = await Promise.all([this.#getPage(spread.left), this.#getPage(spread.right)]);\n return { left, right };\n }\n\n /** Decode one page; on failure emit `sourceError` and degrade to a blank (null) page. */\n async #getPage(index: number | null): Promise<PageContent | null> {\n if (index === null) return null;\n try {\n return await this.#source.get(index);\n } catch (error) {\n this.#emitter.emit('sourceError', { index, error });\n return null;\n }\n }\n\n #prefetchWindow(): void {\n const { toMount } = this.#virtualizer.update(this.#current, this.#spreads.length);\n const pages: number[] = [];\n for (const index of toMount) {\n const spread = this.#spreads[index];\n if (spread?.left != null) pages.push(spread.left);\n if (spread?.right != null) pages.push(spread.right);\n }\n this.#source.prefetch(pages);\n }\n\n #spreadIndexForPage(page: number): number {\n const index = this.#spreads.findIndex((s) => s.left === page || s.right === page);\n return index === -1 ? 0 : index;\n }\n\n /** Validate the (now-known) page count + startPage and build the spread model. */\n #buildSpreadModel(): void {\n const pageCount = this.#source.pageCount;\n if (!Number.isInteger(pageCount) || pageCount < 1) {\n throw new Error(`Zine: source has ${pageCount} pages; a Source must have at least 1 page.`);\n }\n const startPage = this.#startPageOption;\n if (\n startPage !== undefined &&\n (!Number.isInteger(startPage) || startPage < 0 || startPage >= pageCount)\n ) {\n throw new Error(\n `Zine: startPage ${JSON.stringify(startPage)} is out of range for a ${pageCount}-page book (valid 0..${pageCount - 1}).`,\n );\n }\n const mode = this.#effectiveMode();\n this.#singlePage = mode === 'single';\n this.#spreads = buildSpreads(pageCount, { direction: this.#direction, mode });\n this.#currentPage = clamp(startPage ?? 0, 0, pageCount - 1);\n this.#current = this.#spreadIndexForPage(this.#currentPage);\n }\n}\n\nfunction clamp(value: number, min: number, max: number): number {\n return value < min ? min : value > max ? max : value;\n}\n\nfunction easeInOutCubic(t: number): number {\n return t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2;\n}\n\nfunction typeName(v: unknown): string {\n if (v === null) return 'null';\n if (Array.isArray(v)) return 'array';\n return typeof v;\n}\n\n/** Validate constructor inputs up front, throwing agent-actionable errors. */\nfunction validateOptions(container: unknown, options: unknown): void {\n if (\n typeof container !== 'object' ||\n container === null ||\n typeof (container as { appendChild?: unknown }).appendChild !== 'function' ||\n typeof (container as { addEventListener?: unknown }).addEventListener !== 'function'\n ) {\n throw new Error(`Zine: container must be a DOM element; received ${typeName(container)}.`);\n }\n if (typeof options !== 'object' || options === null) {\n throw new Error('Zine: an options object with a `source` is required.');\n }\n const o = options as Record<string, unknown>;\n\n const source = o.source as { get?: unknown; pageCount?: unknown } | undefined;\n if (\n typeof source !== 'object' ||\n source === null ||\n typeof source.get !== 'function' ||\n typeof source.pageCount !== 'number'\n ) {\n throw new Error('Zine: `source` is required and must be a Source, e.g. new ImageSource(urls).');\n }\n // Note: pageCount >= 1 and startPage-in-range are validated in #buildSpreadModel —\n // synchronously for a sync source, or after open() for an async one (e.g. PdfSource).\n\n const startPage = o.startPage;\n if (startPage !== undefined && (typeof startPage !== 'number' || !Number.isInteger(startPage) || startPage < 0)) {\n throw new Error(`Zine: startPage must be a non-negative integer; got ${JSON.stringify(startPage)}.`);\n }\n\n const direction = o.direction;\n if (direction !== undefined && direction !== 'ltr' && direction !== 'rtl') {\n throw new Error(`Zine: direction must be 'ltr' or 'rtl'; got ${JSON.stringify(direction)}.`);\n }\n\n const clickToFlip = o.clickToFlip;\n if (clickToFlip !== undefined && !['edge', 'half', 'off'].includes(clickToFlip as string)) {\n throw new Error(`Zine: clickToFlip must be 'edge', 'half', or 'off'; got ${JSON.stringify(clickToFlip)}.`);\n }\n\n const curl = o.curl;\n if (curl !== undefined && !CURL_TYPES.includes(curl as CurlType)) {\n throw new Error(`Zine: curl must be one of ${CURL_TYPES.join(', ')}; got ${JSON.stringify(curl)}.`);\n }\n\n const spreadMode = o.spreadMode;\n if (spreadMode !== undefined && !['double', 'single', 'cover', 'book'].includes(spreadMode as string)) {\n throw new Error(\n `Zine: spreadMode must be 'double', 'single', 'cover', or 'book'; got ${JSON.stringify(spreadMode)}.`,\n );\n }\n\n for (const key of ['frontCover', 'backCover'] as const) {\n const value = o[key];\n if (value !== undefined && typeof value !== 'string') {\n throw new Error(`Zine: ${key} must be an image URL string; got ${JSON.stringify(value)}.`);\n }\n }\n const pages = o.pages;\n if (pages !== undefined && (typeof pages !== 'object' || pages === null || Array.isArray(pages))) {\n throw new Error('Zine: pages must be an object mapping page indices to image URLs.');\n }\n\n assertMin(o.width, 'width', 1);\n assertMin(o.height, 'height', 1);\n assertMin(o.flipDuration, 'flipDuration', 0);\n assertMin(o.clickZoneSize, 'clickZoneSize', 0);\n assertMin(o.clickFlipDelay, 'clickFlipDelay', 0);\n assertMin(o.singlePageThreshold, 'singlePageThreshold', 0);\n validateZoomOption(o.zoom);\n validateRendererOption(o.renderer);\n}\n\nfunction assertMin(value: unknown, name: string, min: number): void {\n if (value === undefined) return;\n if (typeof value !== 'number' || !Number.isFinite(value) || value < min) {\n throw new Error(`Zine: ${name} must be a number >= ${min}; got ${JSON.stringify(value)}.`);\n }\n}\n\nfunction validateZoomOption(zoom: unknown): void {\n if (zoom === undefined) return;\n if (typeof zoom !== 'object' || zoom === null || Array.isArray(zoom)) {\n throw new Error('Zine: zoom must be an object, e.g. { max: 4 }.');\n }\n const z = zoom as Record<string, unknown>;\n if (z.enabled !== undefined && typeof z.enabled !== 'boolean') {\n throw new Error(`Zine: zoom.enabled must be a boolean; got ${JSON.stringify(z.enabled)}.`);\n }\n if (z.wheel !== undefined && typeof z.wheel !== 'boolean') {\n throw new Error(`Zine: zoom.wheel must be a boolean; got ${JSON.stringify(z.wheel)}.`);\n }\n if (z.doubleClickInFlipZone !== undefined && typeof z.doubleClickInFlipZone !== 'boolean') {\n throw new Error(\n `Zine: zoom.doubleClickInFlipZone must be a boolean; got ${JSON.stringify(z.doubleClickInFlipZone)}.`,\n );\n }\n if (z.doubleClick !== undefined && z.doubleClick !== false) {\n const levels = z.doubleClick;\n if (\n !Array.isArray(levels) ||\n levels.some((n) => typeof n !== 'number' || !Number.isFinite(n) || n < 1)\n ) {\n throw new Error(\n 'Zine: zoom.doubleClick must be false or an array of zoom levels >= 1, e.g. [1, 2, 4].',\n );\n }\n }\n assertMin(z.max, 'zoom.max', 1);\n}\n\nfunction validateRendererOption(renderer: unknown): void {\n if (renderer === undefined) return;\n if (typeof renderer === 'string') {\n if (renderer !== 'auto' && renderer !== 'css' && renderer !== 'webgl2') {\n throw new Error(\n `Zine: renderer '${renderer}' is not recognized; use 'auto', 'css', 'webgl2', an array of those, or a custom Renderer.`,\n );\n }\n return;\n }\n if (Array.isArray(renderer)) {\n for (const kind of renderer) {\n if (kind !== 'css' && kind !== 'webgl2') {\n throw new Error(\n `Zine: renderer order array may only contain 'css' or 'webgl2'; got ${JSON.stringify(kind)}.`,\n );\n }\n }\n return;\n }\n if (\n typeof renderer === 'object' &&\n renderer !== null &&\n typeof (renderer as { mount?: unknown }).mount === 'function'\n ) {\n return;\n }\n throw new Error(\n \"Zine: renderer must be 'auto', 'css', 'webgl2', an array of those, or a custom Renderer instance.\",\n );\n}\n","import type { PageContent } from '../renderer/types';\nimport type { Source } from './types';\n\nexport type ImageFit = 'contain' | 'cover';\n\nexport interface ImageSourceOptions {\n /** How many adjacent pages to prefetch around a requested page. Default 1. */\n preload?: number;\n /** How each image fits its page; a hint consumed by the render layer. Default 'contain'. */\n fit?: ImageFit;\n}\n\n/**\n * Default content source for image books: decodes a list of image URLs to\n * ImageBitmaps, memoizes them, and prefetches neighbors on access.\n */\nexport class ImageSource implements Source {\n readonly pageCount: number;\n readonly fit: ImageFit;\n #urls: string[];\n #preload: number;\n #cache = new Map<number, Promise<ImageBitmap>>();\n\n constructor(urls: string[], options: ImageSourceOptions = {}) {\n this.#urls = urls;\n this.pageCount = urls.length;\n this.#preload = options.preload ?? 1;\n this.fit = options.fit ?? 'contain';\n }\n\n get(index: number): Promise<PageContent> {\n const decoded = this.#decode(index);\n for (let d = 1; d <= this.#preload; d++) {\n this.prefetch([index - d, index + d]);\n }\n return decoded;\n }\n\n prefetch(indices: number[]): void {\n for (const i of indices) {\n if (i >= 0 && i < this.pageCount) {\n void this.#decode(i).catch(() => {}); // swallow: prefetch failures surface on real get()\n }\n }\n }\n\n destroy(): void {\n for (const pending of this.#cache.values()) {\n void pending.then((bitmap) => bitmap.close()).catch(() => {});\n }\n this.#cache.clear();\n }\n\n #decode(index: number): Promise<ImageBitmap> {\n const cached = this.#cache.get(index);\n if (cached) return cached;\n\n const url = this.#urls[index];\n if (url === undefined) {\n return Promise.reject(\n new RangeError(`ImageSource: page ${index} is out of range (0..${this.pageCount - 1}).`),\n );\n }\n\n const promise = (async () => {\n const res = await fetch(url);\n if (!res.ok) {\n throw new Error(`ImageSource: failed to fetch page ${index} (${url}) — HTTP ${res.status}.`);\n }\n return createImageBitmap(await res.blob());\n })().catch((err: unknown) => {\n this.#cache.delete(index); // drop the failed entry so a later get() can retry\n throw err;\n });\n\n this.#cache.set(index, promise);\n return promise;\n }\n}\n","export { Zine } from './zine';\nexport type { ZineOptions, ZoomOptions } from './zine';\n\nexport { ImageSource } from './source/imageSource';\nexport type { ImageSourceOptions, ImageFit } from './source/imageSource';\nexport type { Source } from './source/types';\n\nexport type { RendererOption, RendererKind } from './renderer/select';\nexport type { Renderer, SpreadContent, PageContent, FlipDirection, LayoutMetrics, RenderOptions } from './renderer/types';\n\nexport type { ZineEventMap } from './engine/emitter';\nexport type { Direction, Spread } from './engine/spread';\nexport { CURL_TYPES } from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