@zinejs/core 0.6.0 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"index.umd.js","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","#fillFade","#textureFor","#evictTextures","#canvas","#ctx","#shown","#base","#front","#back","#rawPages","#resolvePages","#resolved","#image","#cache","#doc","#lastFocus","#backdrop","#dialog","#linkRow","#socialRow","#qr","#onKey","#trapFocus","#copy","#timer","#holder","#place","#wrap","#zine","#doc","#bar","#build","#markCurrent","#unsubscribe","#rows","#observeRows","#paint","#observer","#zine","#doc","#bar","#note","#build","#unsubscribe","#markCurrent","#addLevel","#rows","#zine","#doc","#bar","#input","#timer","#search","#hits","#run","#note","#zine","#prev","#button","#next","#place","#refresh","#unsubscribe","#wrap","#zine","#container","#doc","#root","#bar","#onKeyDown","#isolate","#place","#refresh","#unsubscribe","#popover","#closePopover","#wrap","#build","#arrows","#probeOutline","#panel","#panelKind","#context","#buttons","#button","#titleOf","#iconOf","#activate","#openMenu","#showPopover","#placePopover","#hasVisibleChildren","#formFields","#pageInput","#hasOutline","#renderer","#container","#source","#direction","#deepLinkEnabled","#disableContextMenu","#spreadMode","#configuredMode","#curl","#clickToFlip","#clickZoneSize","#singlePageThreshold","#responsiveSpread","#controlsOption","#startPageOption","#buildSpreadModel","#flipDuration","#zoomEnabled","#wheelZoom","#doubleClickLevels","#maxZoom","#honorDoubleClickInFlipZone","#clickFlipDelayValue","#ready","#init","#currentPage","#spreads","#current","#singlePage","#narrow","#rebuildSpreads","#renderCurrent","#applySinglePage","#getPage","#outline","#emitter","#stepFlip","#requestFlip","#startFlip","#spreadIndexForPage","#machine","#activeAnim","#queuedFlip","#finishActiveAnim","#raf","#flushPendingUpgrades","#scale","#tx","#ty","#clampPan","#refreshZoomTiles","#destroyed","#clearPendingClickFlip","#resizeObserver","#deepLink","#unsubscribeDeepLink","#controlsCleanup","#a11yCleanup","#unbindWheel","#unbindDblClick","#unbindContextMenu","#unbindInput","#tileTimer","#tileGeneration","#zoomOverlay","#leadPage","#runFlip","#flipGeneration","#resolveContent","#currentContent","#anchorY","#animateProgress","#commit","#effectiveDuration","#paintSpread","#prefetchWindow","#announce","#drainQueuedFlip","#pinching","#pan","#contentRect","#toBookPoint","#press","#pendingGrab","#drag","#stageDrag","#promoteGrab","#maybeClickFlip","#cancelFlip","#clickFlipDirection","#pendingClickTimer","#pinchBaseScale","#mountWithFallback","#onPageUpdate","#onDragStart","#onDragMove","#onDragEnd","#onPinchStart","#onPinchMove","#onPinchEnd","#bindWheelZoom","#bindDoubleClickZoom","#bindContextMenu","#setupReducedMotion","#setupA11y","#observeResize","#bindDeepLink","#mountControls","#fallbackToCss","#fellBack","#reducedMotion","#onKeyDown","#liveRegion","#effectiveMode","#effectiveModeShown","#applyContainerAspect","#lastAspect","#pendingUpgrades","#renderZoomTiles","#createZoomOverlay","#scheduleUpdate","#updateScheduled","#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/engine/deeplink.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/cone.ts","../src/geometry/curls/leaf.ts","../src/geometry/curls/flick.ts","../src/geometry/curls/silk.ts","../src/geometry/curls/simple.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/engine/zoomTile.ts","../src/source/compose.ts","../src/controls/icons.ts","../src/controls/registry.ts","../src/controls/socials.ts","../src/controls/qr.ts","../src/controls/share.ts","../src/controls/builtins.ts","../src/controls/styles.ts","../src/controls/sidebar.ts","../src/controls/thumbnails.ts","../src/controls/outline.ts","../src/controls/search.ts","../src/controls/arrows.ts","../src/controls/toolbar.ts","../src/controls/controls.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","import type { SpreadMode } from './spread.js';\n\nexport 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 /** Pages regrouped: the spread mode changed, or a narrow container forced one page. */\n spreadChanged: { mode: SpreadMode; singlePage: boolean };\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 * Keeping the page in the URL, so a link opens where the reader was.\n *\n * The hash is treated as shared ground rather than ours: only a `page` key is read or written,\n * anything else in it is preserved, and updates go through `replaceState` so turning pages does\n * not fill the reader's back button with history entries.\n */\nconst KEY = 'page';\n\n/**\n * Whether some book on this page already owns the hash.\n *\n * Two books sharing one URL would each overwrite the other's page, and the second to load would\n * open on the first one's page. Only the first claims it; the rest still work, they just do not\n * appear in the address bar.\n */\nlet claimed = false;\n\n/** Take the hash if it is going, and report whether this caller got it. */\nexport function claimHash(): boolean {\n if (claimed) return false;\n claimed = true;\n return true;\n}\n\n/** Give the hash back, so a book that replaces this one can own it. */\nexport function releaseHash(): void {\n claimed = false;\n}\n\n/** Read the 1-based page from a hash, as a 0-based index. Null when it carries no page. */\nexport function pageFromHash(hash: string): number | null {\n const params = new URLSearchParams(hash.replace(/^#/, ''));\n const raw = params.get(KEY);\n if (raw === null) return null;\n const page = Number(raw);\n return Number.isInteger(page) && page >= 1 ? page - 1 : null;\n}\n\n/** The hash that names `page` (0-based), leaving any other keys in `hash` untouched. */\nexport function hashWithPage(hash: string, page: number): string {\n const params = new URLSearchParams(hash.replace(/^#/, ''));\n params.set(KEY, String(page + 1));\n return `#${params.toString()}`;\n}\n\nexport interface DeepLinkHandle {\n /** Write the current page into the address bar. */\n push(page: number): void;\n stop(): void;\n}\n\n/**\n * Mirror the reader's page in the URL, and follow it when the URL changes (back/forward, or a\n * pasted link). `onNavigate` fires only for a page the book is not already on.\n */\nexport function bindDeepLink(win: Window, onNavigate: (page: number) => void): DeepLinkHandle {\n // The page the URL is known to describe. Compared against rather than the hash string itself:\n // some environments emit `hashchange` for our own replaceState, and a string comparison there\n // would let the echo through and turn the page a second time.\n let shown: number | null = null;\n const onHashChange = (): void => {\n const page = pageFromHash(win.location.hash);\n if (page === null || page === shown) return; // absent, or already where we are\n shown = page;\n onNavigate(page);\n };\n win.addEventListener('hashchange', onHashChange);\n return {\n push(page) {\n if (page === shown) return;\n shown = page;\n const hash = hashWithPage(win.location.hash, page);\n if (hash === win.location.hash) return;\n // replaceState, not assignment: a reader flipping through fifty pages should not have to\n // press Back fifty times to leave.\n win.history?.replaceState?.(win.history.state, '', hash);\n },\n stop() {\n win.removeEventListener('hashchange', onHashChange);\n },\n };\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 * Full-width lone page (single-page mode). The leaf hinges at the container edge and\n * has no facing half to land on — deforms may soften and delay the flop so the curl\n * reads naturally before the renderer dissolves the sheet.\n */\n fill?: boolean;\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 /** 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' | 'cone' | 'leaf' | 'flick' | 'silk' | 'simple';\n\nexport const CURL_TYPES: CurlType[] = ['roll', 'cone', 'leaf', 'flick', 'silk', 'simple'];\n\nexport const DEFAULT_CURL: CurlType = 'cone';\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';\nimport type { CurlAnchor } from './types';\n\n/**\n * Cone angle at peak curl. π/2 is flat; smaller values wind the sheet tighter.\n * ~30° gives a soft, paper-like ridge without self-intersection on typical page\n * aspect ratios (Hong / Nuon / Project Austin all land in the 18–35° band).\n */\nconst THETA_MIN = (30 * Math.PI) / 180;\n/** Gentler opening for full-width lone pages — a tight cone reads as a funnel when\n * the leaf owns the whole viewport and hinges at the edge. */\nconst THETA_MIN_FILL = (44 * Math.PI) / 180;\n\n/**\n * How far past the page the cone apex sits, as a fraction of height, at rest.\n * Closer mid-turn sharpens the diagonal; farther reads more cylindrical.\n * Kept moderately distant so the sheet stays page-like without cloth-y sliding.\n */\nconst APEX_REST = 1.35;\nconst APEX_PEAK = 0.7;\n/** Farther apex on fill: softer diagonal, less cloth-y twist across the full leaf. */\nconst APEX_REST_FILL = 1.85;\nconst APEX_PEAK_FILL = 1.15;\n\n/**\n * Above this |anchor.y − 0.5| the deform is a pure cone; at the mid-edge it\n * blends fully to a cylinder (Project Austin’s conicContribution).\n */\nconst CORNER_PURE = 0.42;\n\n/**\n * Power on fill flop progress. Slightly >1 delays spine rotation so the cone develops\n * over the page before the leaf swings past the edge hinge — kept close to 1 so the\n * flop isn't packed into a late whip (lone pages dissolve rather than land).\n */\nconst FILL_RHO_POWER = 1.08;\n\n/**\n * Natural conical page curl — the Xerox PARC / iBooks model.\n *\n * The leaf wraps an imaginary right circular cone whose apex rides the spine and\n * whose opening angle θ breathes over the turn (Hong, Card & Chen, 2004). A corner\n * grab yields a diagonal cone; a mid-edge grab blends toward a cylinder so the\n * free edge lifts as one. The curled sheet then rotates about the spine and settles\n * flat on the far side. Arc length from the apex is preserved, so the paper never\n * stretches — the motion reads as stiff, premium stock rather than cloth.\n *\n * On a full-width lone page (`anchor.fill`) the hinge is the container edge with no\n * facing half to land on: the cone softens, the flop is delayed so the peel stays\n * over the page longer, and the renderer dissolves the sheet as it finishes.\n */\nexport function deformCone(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 fill = !!anchor.fill;\n\n // Curl envelope: 0 at the ends (flat), 1 at mid-turn. Soft power keeps the\n // ridge full through the middle third — paper holds its bend rather than\n // peaking and collapsing.\n const curl = Math.pow(Math.sin(Math.PI * t), 0.85);\n\n // θ: π/2 (identity) → THETA_MIN (pronounced curl) → π/2.\n const thetaMin = fill ? THETA_MIN_FILL : THETA_MIN;\n const theta = Math.PI / 2 - curl * (Math.PI / 2 - thetaMin);\n const sinTheta = Math.sin(theta);\n const cosTheta = Math.cos(theta);\n const invSinTheta = 1 / Math.max(sinTheta, 1e-6);\n\n // Apex distance: pulled in as the curl develops for a tighter diagonal.\n const apexRest = fill ? APEX_REST_FILL : APEX_REST;\n const apexPeak = fill ? APEX_PEAK_FILL : APEX_PEAK;\n const apexDist = H * (apexRest + (apexPeak - apexRest) * curl);\n\n // Corner bias: −1 = top edge, +1 = bottom. Near 0 → cylinder blend.\n const bias = (anchor.y - 0.5) * 2;\n const fromBottom = bias >= 0;\n const absBias = Math.abs(bias);\n let conic = Math.min(1, absBias / CORNER_PURE);\n const cylWeight = 1 - conic;\n\n // Cylinder radius matched to the cone’s free-edge cross-section (Austin), so\n // the blend is continuous as the grab slides from corner to mid-edge.\n // Apex sits past the *leading* edge (below for a bottom grab, above for top).\n const AyRef = fromBottom ? H + apexDist : -apexDist;\n const cylR = Math.hypot(W, 0.5 * H - AyRef);\n const cylRadius = Math.max(cylR * sinTheta, W / Math.PI);\n\n // Spine rotation: concurrent with the cone so the page flops while it curls.\n // Same x–z convention as `roll` (ρ: 0 → −π). On fill, delay the flop so the\n // peel develops over the page before the leaf swings past the edge hinge.\n const rhoT = fill ? Math.pow(t, FILL_RHO_POWER) : t;\n const rho = -Math.PI * rhoT;\n const cosR = Math.cos(rho);\n const sinR = Math.sin(rho);\n\n // Near the rests the cone is the identity plane. A finite-radius cylinder blend\n // still carries a tiny residual arc — skip it and rotate the flat sheet.\n if (curl < 1e-4) {\n for (let j = 0; j < ny; j++) {\n const y = (j / mesh.rows) * H;\n for (let i = 0; i < nx; i++) {\n const x0 = (i / mesh.cols) * W;\n const k = (j * nx + i) * 3;\n pos[k] = x0 * cosR;\n pos[k + 1] = y;\n pos[k + 2] = -x0 * sinR;\n }\n }\n computeNormals(mesh);\n return;\n }\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\n let cx = x0;\n let cy = y0;\n let cz = 0;\n\n if (conic > 1e-5) {\n // Canonical cone: apex above the page (A < 0) makes the *near* edge lead.\n // In our y-down leaf, that means the top. For a bottom grab we flip into\n // that space, deform, then flip back — one code path for both corners.\n const yIn = fromBottom ? H - y0 : y0;\n const A = -apexDist;\n const R = Math.hypot(x0, yIn - A);\n if (R > 1e-8) {\n const r = R * sinTheta;\n const beta = Math.asin(Math.min(1, Math.max(0, x0 / R))) * invSinTheta;\n const oneCos = 1 - Math.cos(beta);\n const yCone = R + A - r * oneCos * sinTheta;\n cx = r * Math.sin(beta);\n cy = fromBottom ? H - yCone : yCone;\n cz = r * oneCos * cosTheta;\n }\n }\n\n let bx = cx;\n let by = cy;\n let bz = cz;\n\n if (cylWeight > 1e-5) {\n const beta = x0 / cylRadius;\n const sx = cylRadius * Math.sin(beta);\n const sz = cylRadius * (1 - Math.cos(beta));\n bx = conic * cx + cylWeight * sx;\n by = conic * cy + cylWeight * y0;\n bz = conic * cz + cylWeight * sz;\n }\n\n const k = (j * nx + i) * 3;\n pos[k] = bx * cosR + bz * sinR;\n pos[k + 1] = by;\n pos[k + 2] = -bx * sinR + bz * cosR;\n }\n }\n\n computeNormals(mesh);\n}\n","import { computeNormals, type PageMesh } from './mesh';\nimport type { CurlAnchor } from './types';\n\n/** Peak material width occupied by the bending wave. */\nconst MAX_BEND_LENGTH = 0.34;\n\n/** Maximum tilt of the rolling axis for a corner-led turn. */\nconst MAX_TILT = (11 * Math.PI) / 180;\n\nconst PROFILE_STEPS = 128;\n\n/**\n * Unit-length raised-cosine curvature profile.\n *\n * κ(s) = π(1 - cos(2πs)), so its integrated tangent angle is\n * θ(s) = πs - ½sin(2πs). Curvature is exactly zero at both ends and integrates\n * to π: the incoming and outgoing planes are flat, opposite-facing, and meet\n * the bend without a crease. X/Z are arc-length integrals of cos(θ)/sin(θ).\n */\nfunction makeProfile(): { x: Float64Array; z: Float64Array } {\n const x = new Float64Array(PROFILE_STEPS + 1);\n const z = new Float64Array(PROFILE_STEPS + 1);\n const ds = 1 / PROFILE_STEPS;\n const theta = (s: number): number => Math.PI * s - 0.5 * Math.sin(2 * Math.PI * s);\n for (let i = 1; i <= PROFILE_STEPS; i++) {\n const a = theta((i - 1) * ds);\n const b = theta(i * ds);\n x[i] = x[i - 1]! + 0.5 * (Math.cos(a) + Math.cos(b)) * ds;\n z[i] = z[i - 1]! + 0.5 * (Math.sin(a) + Math.sin(b)) * ds;\n }\n // Symmetry makes this analytically zero; remove accumulated floating-point drift.\n x[PROFILE_STEPS] = 0;\n return { x, z };\n}\n\nconst PROFILE = makeProfile();\nconst PROFILE_HEIGHT = PROFILE.z[PROFILE_STEPS]!;\n\nfunction sampleProfile(s: number): [x: number, z: number] {\n const p = Math.max(0, Math.min(1, s)) * PROFILE_STEPS;\n const i = Math.min(PROFILE_STEPS - 1, Math.floor(p));\n const f = p - i;\n return [\n PROFILE.x[i]! + (PROFILE.x[i + 1]! - PROFILE.x[i]!) * f,\n PROFILE.z[i]! + (PROFILE.z[i + 1]! - PROFILE.z[i]!) * f,\n ];\n}\n\n/**\n * Traveling smooth-curvature leaf curl.\n *\n * Inspired by rolling-cylinder page curls and modern developable-surface book\n * simulations, but with a compact raised-cosine curvature wave instead of a\n * constant-radius cylinder. The sheet has three regions:\n *\n * 1. untouched paper before the wave,\n * 2. an isometric bend whose curvature smoothly rises and falls,\n * 3. a flat, reflected flap after the wave.\n *\n * The wave travels from the free edge to just beyond the spine while its width grows\n * and collapses. Integrating a unit tangent preserves material length exactly; straight\n * ruling lines preserve distance along the curl axis. Curvature reaches zero at both\n * seams, eliminating the hard crease shared by circular/fold models.\n */\nexport function deformLeaf(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 // Exact rest poses avoid the tiny numerical ridge left by a vanishing wave.\n if (t <= 1e-7 || t >= 1 - 1e-7) {\n const side = t < 0.5 ? 1 : -1;\n for (let j = 0; j < ny; j++) {\n const y = (j / mesh.rows) * H;\n for (let i = 0; i < nx; i++) {\n const k = (j * nx + i) * 3;\n pos[k] = side * (i / mesh.cols) * W;\n pos[k + 1] = y;\n pos[k + 2] = 0;\n }\n }\n computeNormals(mesh);\n return;\n }\n\n // The wave broadens through the middle, then tightens as the leaf settles.\n const envelope = Math.pow(Math.sin(Math.PI * t), 0.72);\n const bendLength = Math.max(1e-6, W * MAX_BEND_LENGTH * envelope);\n\n // Bottom grabs tilt the ruling clockwise in page coordinates; top grabs mirror it.\n // The tilt fades at both rest states so the page lands exactly square.\n const anchorBias = Math.max(-1, Math.min(1, (anchor.y - 0.5) * 2));\n const tilt = anchorBias * MAX_TILT * Math.pow(Math.sin(Math.PI * t), 1.15);\n const nX = Math.cos(tilt);\n const nY = Math.sin(tilt);\n const fX = -nY;\n const fY = nX;\n\n // Place the axis outside the whole rectangle at t=0 and beyond the spine at t=1.\n // Accounting for tilt keeps every row in the correct physical region at the ends.\n const diagonalReach = Math.abs(nY) * H * 0.5;\n const startX = W + diagonalReach / nX;\n const endX = -(bendLength + diagonalReach) / nX;\n const axisX = startX + (endX - startX) * t;\n const axisY = H * 0.5;\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 - axisX;\n const relY = y0 - axisY;\n const d = relX * nX + relY * nY;\n const e = relX * fX + relY * fY;\n const k = (j * nx + i) * 3;\n\n if (d <= 0) {\n // The wave has not reached this point: untouched front-facing paper.\n pos[k] = x0;\n pos[k + 1] = y0;\n pos[k + 2] = 0;\n continue;\n }\n\n let normalDistance: number;\n let z: number;\n if (d < bendLength) {\n // Scale the unit arc-length profile by the material width of this wave.\n const [profileX, profileZ] = sampleProfile(d / bendLength);\n normalDistance = bendLength * profileX;\n z = bendLength * profileZ;\n } else {\n // The tangent has rotated by π; paper leaves the wave flat and reversed.\n normalDistance = -(d - bendLength);\n z = bendLength * PROFILE_HEIGHT;\n }\n\n pos[k] = axisX + fX * e + nX * normalDistance;\n pos[k + 1] = axisY + fY * e + nY * normalDistance;\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\n/**\n * Peak inertial tip lag in radians (~30°). How far the free edge trails the\n * spine rotation at the height of the acceleration phase, and symmetrically how\n * far it follows through while the turn decelerates.\n */\nconst SWAY = 0.52;\n\n/**\n * Extra lag for rows far from the grabbed corner (0 = whole edge moves as one).\n * The driven corner is held; the diagonal remainder of the sheet trails it.\n */\nconst LAG = 0.45;\n\n/**\n * Inertial follow-through page flick.\n *\n * The leaf is a cantilever clamped at the spine and driven through a rotation\n * ρ(t) = πt. Paper inertia (the Euler force, ∝ −ρ̈) bends the sheet opposite the\n * angular acceleration with a first-mode-like profile — zero curvature at the\n * clamped spine, maximal at the free edge. Under an eased turn the acceleration\n * changes sign at mid-flight, so the free edge trails while the turn winds up,\n * swings through vertical, then overtakes and settles as the turn slows: the\n * follow-through/overlapping-action principle, grounded in base-rotated\n * cantilever dynamics. Tangent angles are integrated along the width, so the\n * sheet never stretches, and the curvature direction reversing over the turn is\n * what none of the wrap-style curls do.\n *\n * Rows far from the grabbed corner lag slightly more than the driven row, so a\n * corner grab pulls a soft living diagonal across the sheet.\n */\nexport function deformFlick(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 cols = mesh.cols;\n const pos = mesh.positions;\n const ds = W / cols;\n\n // Base rotation about the spine, 0 → π (same landing convention as `simple`).\n const rho = Math.PI * t;\n\n // Inertial amplitude ∝ −ρ̈ of an eased unit turn: the tip trails (negative)\n // while accelerating, leads (positive) while braking, and is zero at both\n // rests and at peak speed mid-turn.\n const amplitude = -SWAY * Math.sin(2 * Math.PI * t);\n\n for (let j = 0; j < ny; j++) {\n const v = j / mesh.rows;\n // The grabbed row is driven directly; distance from it adds trailing inertia.\n const rowAmplitude = amplitude * (1 + LAG * Math.abs(v - anchor.y));\n const y = v * H;\n\n // Integrate the unit tangent of θ(u) = ρ + A·u² across the width (trapezoid\n // per grid cell). u² is the first-mode tangent shape: clamped flat at the\n // spine, curving ever more freely toward the edge. Exact arc length.\n let x = 0;\n let z = 0;\n let cosPrev = Math.cos(rho);\n let sinPrev = Math.sin(rho);\n pos[(j * nx) * 3] = 0;\n pos[(j * nx) * 3 + 1] = y;\n pos[(j * nx) * 3 + 2] = 0;\n for (let i = 1; i < nx; i++) {\n const u = i / cols;\n const theta = rho + rowAmplitude * u * u;\n const cosCur = Math.cos(theta);\n const sinCur = Math.sin(theta);\n x += 0.5 * (cosPrev + cosCur) * ds;\n z += 0.5 * (sinPrev + sinCur) * ds;\n cosPrev = cosCur;\n sinPrev = sinCur;\n\n const k = (j * nx + i) * 3;\n pos[k] = x;\n pos[k + 1] = y;\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\n/**\n * Peak S-curve amplitude in radians. Mid-turn the tangent oscillates about the\n * spine angle so the cross-section forms a true inflection (two opposite bends).\n * ~30° reads as thick stock turned by hand, not a knife crease.\n */\nconst S_AMP = 0.52;\n\n/**\n * Early free-edge peel lead in radians. The grabbed tip lifts ahead of the body\n * — first motion of a careful hand turn. Strongest near t≈0.35, gone by rest.\n */\nconst PEEL_LEAD = 0.62;\n\n/**\n * How much rows far from the grab trail the driven corner (0 = rigid across height).\n * Builds the soft diagonal of a corner-led hand turn.\n */\nconst ROW_LAG = 0.5;\n\n/**\n * Power on spine progress for full-width lone pages. >1 delays the flop so the\n * S develops over the sheet before the leaf dissolves off the edge hinge.\n */\nconst FILL_RHO_POWER = 1.12;\n\n/**\n * Silk — hand-turned S-curve page.\n *\n * This is not a traveling contact wave (`leaf`), not a cone wrap (`cone`), not a\n * cylinder roll (`roll`), and not a single-mode inertial cantilever (`flick`).\n *\n * Real paper turned by hand takes an S-shaped cross-section: a main bend through\n * the near half and a reverse bend through the far half (the flap over the\n * fingers). The sheet is a developable strip clamped at the spine and driven\n * through a base rotation ρ(t) = πt. Along the width the tangent is:\n *\n * θ(u) = ρ + env·S·sin(2πu) + peel(t)·u²\n *\n * where:\n * - sin(2πu) is a full-period S (zero net at spine and free edge, opposite\n * bends in the two halves) — a true inflection that none of the other\n * models produce mid-turn,\n * - u² is an early peel lead that lifts the free edge first, then releases.\n *\n * env = sin(πt) holds the S through the middle and forces exact flat rests.\n * Rows far from the tap lag so a corner grab draws a living diagonal.\n * Arc length is integrated with the unit tangent (trapezoid per grid cell), so\n * the paper never stretches.\n */\nexport function deformSilk(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 cols = mesh.cols;\n const pos = mesh.positions;\n const ds = W / cols;\n const fill = !!anchor.fill;\n\n // Exact rests: shaping terms vanish with env, but pin the mesh explicitly.\n if (t <= 1e-7 || t >= 1 - 1e-7) {\n const side = t < 0.5 ? 1 : -1;\n for (let j = 0; j < ny; j++) {\n const y = (j / mesh.rows) * H;\n for (let i = 0; i < nx; i++) {\n const k = (j * nx + i) * 3;\n pos[k] = side * (i / mesh.cols) * W;\n pos[k + 1] = y;\n pos[k + 2] = 0;\n }\n }\n computeNormals(mesh);\n return;\n }\n\n // Spine rotation. On a fill leaf, delay slightly so the S develops on-page.\n const rhoT = fill ? Math.pow(t, FILL_RHO_POWER) : t;\n const rho = Math.PI * rhoT;\n\n // S envelope: 0 at rests, full through the middle third.\n const env = Math.pow(Math.sin(Math.PI * t), 0.8);\n const sAmp = S_AMP * env;\n\n // Early peel lead on the free edge: peaks before mid-turn, zero at both rests.\n // sin(πt)·(1−t) peaks near t≈0.35 — corner lifts while the body catches up.\n const peelAmp = PEEL_LEAD * Math.sin(Math.PI * t) * (1 - t);\n\n for (let j = 0; j < ny; j++) {\n const v = j / mesh.rows;\n const y = v * H;\n // Grabbed row is driven hardest; far rows trail (soft diagonal).\n const rowLead = 1 - ROW_LAG * Math.abs(v - anchor.y);\n const rowS = sAmp * (0.75 + 0.25 * rowLead);\n const rowPeel = peelAmp * rowLead;\n\n let x = 0;\n let z = 0;\n let cosPrev = Math.cos(rho);\n let sinPrev = Math.sin(rho);\n pos[j * nx * 3] = 0;\n pos[j * nx * 3 + 1] = y;\n pos[j * nx * 3 + 2] = 0;\n\n for (let i = 1; i < nx; i++) {\n const u = i / cols;\n // S inflection + early free-edge peel. Spine (u=0) is exactly ρ.\n const theta = rho + rowS * Math.sin(2 * Math.PI * u) + rowPeel * u * u;\n const cosCur = Math.cos(theta);\n const sinCur = Math.sin(theta);\n x += 0.5 * (cosPrev + cosCur) * ds;\n z += 0.5 * (sinPrev + sinCur) * ds;\n cosPrev = cosCur;\n sinPrev = sinCur;\n\n const k = (j * nx + i) * 3;\n pos[k] = x;\n pos[k + 1] = y;\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 * 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 * or rotate 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 { deformCone } from './cone';\nimport { deformLeaf } from './leaf';\nimport { deformFlick } from './flick';\nimport { deformSilk } from './silk';\nimport { deformSimple } from './simple';\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, anchored: false },\n cone: { deform: deformCone, anchored: true },\n leaf: { deform: deformLeaf, anchored: true },\n flick: { deform: deformFlick, anchored: true },\n silk: { deform: deformSilk, anchored: true },\n simple: { deform: deformSimple, anchored: false },\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 // Eye distance, in leaf widths. Keeps the perspective resolution-independent. 5.3 puts the\n // roll's deepest point ~14% larger than flat; stronger than that (a nearer eye) balloons the\n // turning sheet and reads more like a fisheye than a page lifting.\n float D = uLeafW * 5.3;\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)\nuniform float uAlpha; // leaf opacity; a lone page dissolves into the page landing beneath it\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 // Premultiplied alpha (blendFunc ONE, ONE_MINUS_SRC_ALPHA): scale colour as well as alpha,\n // or fading would brighten the sheet additively instead of dissolving it.\n outColor = vec4(c.rgb * uAlpha, c.a * uAlpha);\n}`;\n\nconst GRID_COLS = 28;\nconst GRID_ROWS = 36;\n/** Progress at which a lone page starts dissolving. A full-width leaf has no facing half to\n * flop onto, so instead of landing on empty space it fades into the page arriving beneath it\n * over the rest of the turn. Roll is already flat by mid-turn; curling models stay bent\n * longer, so they dissolve later. The fade itself eases so the leaf settles rather than\n * vanishing while still swinging. */\nconst FILL_FADE_START_ROLL = 0.7;\nconst FILL_FADE_START_CURL = 0.8;\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', 'uAlpha']) {\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 CURLS[this.#curlType].deform(this.#mesh, leafW, h, this.#flipT, {\n y: this.#anchor.y,\n fill: flip.fill,\n });\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.uniform1f(this.#curlU.uAlpha ?? null, flip.fill ? this.#fillFade() : 1);\n gl.drawElements(gl.TRIANGLES, this.#idxCount, gl.UNSIGNED_SHORT, 0);\n }\n\n /** Leaf opacity for a lone page: solid until the curl-appropriate fade start, then\n * dissolving to 0 as it lands, so the turn resolves into the destination page rather\n * than onto blank space. The fade eases so opacity hangs longer then finishes cleanly. */\n #fillFade(): number {\n const start =\n this.#curlType === 'roll' || this.#curlType === 'simple'\n ? FILL_FADE_START_ROLL\n : FILL_FADE_START_CURL;\n const over = (this.#flipT - start) / (1 - start);\n if (over <= 0) return 1;\n if (over >= 1) return 0;\n // Ease-out the remaining opacity: stay readable through most of the window, then settle.\n return Math.pow(1 - over, 1.5);\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 { PageRequest } from '../source/types';\n\n/** A rectangle in container pixels. */\nexport interface Rect {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\n/** The current view: the zoom scale and the translate applied about the container origin. */\nexport interface View {\n scale: number;\n tx: number;\n ty: number;\n}\n\n/** One page of the spread, and where it is painted when unzoomed. */\nexport interface TilePage {\n index: number;\n rect: Rect;\n}\n\n/** What to draw: a page's raster region, and the container-space box it belongs in. */\nexport interface TilePlan {\n index: number;\n request: PageRequest;\n /** Where the tile lands on screen, in *untransformed* container pixels. */\n dest: Rect;\n}\n\n/** Intersection of two rectangles, or null when they do not overlap. */\nfunction intersect(a: Rect, b: Rect): Rect | null {\n const x = Math.max(a.x, b.x);\n const y = Math.max(a.y, b.y);\n const right = Math.min(a.x + a.width, b.x + b.width);\n const bottom = Math.min(a.y + a.height, b.y + b.height);\n if (right <= x || bottom <= y) return null;\n return { x, y, width: right - x, height: bottom - y };\n}\n\n/**\n * Work out which part of each page is visible, and at what magnification.\n *\n * The renderer paints a page into `rect` and then scales the whole viewport about the container\n * origin, so a page occupies `rect * scale + t` on screen. Inverting that gives the part of the\n * page inside the viewport, which is the only part worth rasterizing sharply.\n *\n * Returns the plan in untransformed container coordinates: the caller draws it under the same\n * transform the renderer uses, so the tile tracks the page without any extra bookkeeping.\n */\nexport function planTiles(pages: TilePage[], view: View, viewport: Rect): TilePlan[] {\n const { scale, tx, ty } = view;\n if (scale <= 1) return [];\n\n // The viewport in untransformed container space — what the reader can currently see.\n const visible: Rect = {\n x: (viewport.x - tx) / scale,\n y: (viewport.y - ty) / scale,\n width: viewport.width / scale,\n height: viewport.height / scale,\n };\n\n const plans: TilePlan[] = [];\n for (const page of pages) {\n const hit = intersect(page.rect, visible);\n if (!hit || page.rect.width <= 0 || page.rect.height <= 0) continue;\n plans.push({\n index: page.index,\n request: {\n scale,\n region: {\n x: (hit.x - page.rect.x) / page.rect.width,\n y: (hit.y - page.rect.y) / page.rect.height,\n width: hit.width / page.rect.width,\n height: hit.height / page.rect.height,\n },\n },\n dest: hit,\n });\n }\n return plans;\n}\n\n/** Whether two plans ask for the same pixels, so a re-render can be skipped while panning. */\nexport function sameTile(a: TilePlan, b: TilePlan): boolean {\n if (a.index !== b.index || a.request.scale !== b.request.scale) return false;\n const p = a.request.region;\n const q = b.request.region;\n // A fraction of a page-pixel apart is the same tile; exact equality would re-render every frame.\n const EPS = 1e-4;\n return (\n Math.abs(p.x - q.x) < EPS &&\n Math.abs(p.y - q.y) < EPS &&\n Math.abs(p.width - q.width) < EPS &&\n Math.abs(p.height - q.height) < EPS\n );\n}\n\n/**\n * A canvas laid over the book that paints crisp tiles on top of the magnified page.\n *\n * It sits outside the renderer on purpose: both renderers stretch a page raster to a fixed panel,\n * so neither can place a partial-page tile, and teaching them to would mean the same geometry\n * twice. The overlay applies the same transform the renderer does, so the tiles register exactly\n * over the pixels they replace and simply disappear when the reader zooms out.\n */\nexport class ZoomOverlay {\n #canvas: HTMLCanvasElement;\n #ctx: CanvasRenderingContext2D | null;\n #shown: TilePlan[] = [];\n\n constructor(doc: Document, container: HTMLElement) {\n this.#canvas = doc.createElement('canvas');\n this.#canvas.className = 'zine-zoom-overlay';\n // pointer-events:none keeps every gesture reaching the container underneath.\n this.#canvas.style.cssText =\n 'position:absolute;inset:0;pointer-events:none;opacity:0;transition:opacity 120ms linear;';\n container.append(this.#canvas);\n this.#ctx = this.#canvas.getContext('2d');\n }\n\n /** Drop every tile and hide the overlay, revealing the renderer's own pixels again. */\n clear(): void {\n if (this.#shown.length === 0) return;\n this.#shown = [];\n this.#canvas.style.opacity = '0';\n const ctx = this.#ctx;\n if (ctx) ctx.clearRect(0, 0, this.#canvas.width, this.#canvas.height);\n }\n\n /** The plans currently painted, so the caller can skip re-rendering an unchanged view. */\n get shown(): readonly TilePlan[] {\n return this.#shown;\n }\n\n /**\n * Paint `tiles` under `view`. Sizes the backing store to the device pixel grid so the tiles are\n * not resampled a second time on the way to the screen.\n */\n draw(tiles: { plan: TilePlan; content: PageContent }[], view: View, viewport: Rect): void {\n const ctx = this.#ctx;\n if (!ctx) return;\n if (tiles.length === 0) {\n this.clear();\n return;\n }\n\n const dpr = typeof devicePixelRatio === 'number' ? devicePixelRatio : 1;\n const w = Math.max(1, Math.ceil(viewport.width * dpr));\n const h = Math.max(1, Math.ceil(viewport.height * dpr));\n if (this.#canvas.width !== w || this.#canvas.height !== h) {\n this.#canvas.width = w;\n this.#canvas.height = h;\n }\n\n ctx.setTransform(dpr, 0, 0, dpr, 0, 0);\n ctx.clearRect(0, 0, viewport.width, viewport.height);\n // Match the renderer: scale about the container origin, then translate.\n ctx.translate(view.tx, view.ty);\n ctx.scale(view.scale, view.scale);\n for (const { plan, content } of tiles) {\n const d = plan.dest;\n ctx.drawImage(content, d.x, d.y, d.width, d.height);\n }\n\n this.#shown = tiles.map((t) => t.plan);\n this.#canvas.style.opacity = '1';\n }\n\n destroy(): void {\n this.#canvas.remove();\n this.#ctx = null;\n }\n}\n","import type { PageContent } from '../renderer/types';\nimport type { DownloadInfo, OutlineItem, PageRequest, 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 getText?: (index: number) => Promise<string>;\n getDownload?: () => Promise<DownloadInfo | null>;\n getOutline?: () => Promise<OutlineItem[]>;\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 if (typeof base.getText === 'function') {\n // Mirrors get(): covers and replaced pages are images, so they have no text of their own —\n // returning the base page's text there would describe content the reader cannot see.\n this.getText = async (index) => {\n const frontOffset = this.#front !== null ? 1 : 0;\n if (this.#front !== null && index === 0) return '';\n if (this.#back !== null && index === this.pageCount - 1) return '';\n const src = index - frontOffset;\n if (this.#resolved.has(src)) return '';\n return base.getText!(src);\n };\n }\n\n if (typeof base.getDownload === 'function') {\n // Covers and replacements change what is displayed, not the original document, so the\n // download is the base source's file either way.\n this.getDownload = () => base.getDownload!();\n }\n\n if (typeof base.getOutline === 'function') {\n // The outline points at base pages; a front cover pushes every one of them along by one.\n this.getOutline = async () => {\n const items = await base.getOutline!();\n const offset = this.#front !== null ? 1 : 0;\n if (offset === 0) return items;\n const shift = (list: OutlineItem[]): OutlineItem[] =>\n list.map((item) => ({\n ...item,\n page: item.page === null ? null : item.page + offset,\n children: shift(item.children),\n }));\n return shift(items);\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, opts?: PageRequest): Promise<PageContent> {\n const frontOffset = this.#front !== null ? 1 : 0;\n // Covers and page overrides are images: they have no detail beyond their own resolution, so\n // the zoom request has nothing to act on and is dropped rather than forwarded.\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, opts);\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","/**\n * Toolbar glyphs, inlined so the bundle carries no icon-font or sprite dependency.\n *\n * Paths are from Lucide (https://lucide.dev), ISC licensed:\n * Copyright (c) for portions of Lucide are held by Cole Bemis 2013-2022 as part of Feather\n * (MIT). All other copyright (c) for Lucide are held by Lucide Contributors 2022.\n *\n * Each value is the inner markup of a 24x24 `viewBox` drawn with `stroke=\"currentColor\"`,\n * `fill=\"none\"` and round caps/joins — {@link createIcon} supplies those, so the strings stay to\n * the geometry.\n */\n// Not annotated `Record<string, string>`: that would make every ICONS.foo possibly-undefined\n// under noUncheckedIndexedAccess, even for names written right here. `satisfies` keeps the\n// literal's exact keys while still checking the values are markup strings.\nexport const ICONS = {\n /** chevron-left */\n prev: '<path d=\"m15 18-6-6 6-6\"/>',\n /** chevron-right */\n next: '<path d=\"m9 18 6-6-6-6\"/>',\n /** chevrons-left */\n first: '<path d=\"m11 17-5-5 5-5\"/><path d=\"m18 17-5-5 5-5\"/>',\n /** chevrons-right */\n last: '<path d=\"m6 17 5-5-5-5\"/><path d=\"m13 17 5-5-5-5\"/>',\n /** zoom-in */\n zoomIn:\n '<circle cx=\"11\" cy=\"11\" r=\"8\"/><path d=\"m21 21-4.3-4.3\"/><path d=\"M11 8v6\"/><path d=\"M8 11h6\"/>',\n /** zoom-out */\n zoomOut: '<circle cx=\"11\" cy=\"11\" r=\"8\"/><path d=\"m21 21-4.3-4.3\"/><path d=\"M8 11h6\"/>',\n /** search */\n search: '<circle cx=\"11\" cy=\"11\" r=\"8\"/><path d=\"m21 21-4.3-4.3\"/>',\n /** share-2 */\n share:\n '<circle cx=\"18\" cy=\"5\" r=\"3\"/><circle cx=\"6\" cy=\"12\" r=\"3\"/><circle cx=\"18\" cy=\"19\" r=\"3\"/><path d=\"m8.6 13.5 6.8 4\"/><path d=\"m15.4 6.5-6.8 4\"/>',\n /** ellipsis-vertical */\n menu: '<circle cx=\"12\" cy=\"12\" r=\"1\"/><circle cx=\"12\" cy=\"5\" r=\"1\"/><circle cx=\"12\" cy=\"19\" r=\"1\"/>',\n /** maximize */\n fullscreen:\n '<path d=\"M8 3H5a2 2 0 0 0-2 2v3\"/><path d=\"M21 8V5a2 2 0 0 0-2-2h-3\"/><path d=\"M3 16v3a2 2 0 0 0 2 2h3\"/><path d=\"M16 21h3a2 2 0 0 0 2-2v-3\"/>',\n /** minimize */\n exitFullscreen:\n '<path d=\"M8 3v3a2 2 0 0 1-2 2H3\"/><path d=\"M21 8h-3a2 2 0 0 1-2-2V3\"/><path d=\"M3 16h3a2 2 0 0 1 2 2v3\"/><path d=\"M16 21v-3a2 2 0 0 1 2-2h3\"/>',\n /** gallery-vertical-end */\n thumbnails:\n '<path d=\"M7 2h10\"/><path d=\"M5 6h14\"/><rect width=\"18\" height=\"12\" x=\"3\" y=\"10\" rx=\"2\"/>',\n /** list-tree */\n outline:\n '<path d=\"M21 12h-8\"/><path d=\"M21 6h-8\"/><path d=\"M21 18h-8\"/><path d=\"M3 6v4c0 1.1.9 2 2 2h3\"/><path d=\"M3 10v6c0 1.1.9 2 2 2h3\"/>',\n /** book-open: two facing pages */\n twoPages:\n '<path d=\"M12 7v14\"/><path d=\"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z\"/>',\n /** file: a single page */\n onePage: '<path d=\"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z\"/><path d=\"M14 2v5h6\"/>',\n /** printer */\n print:\n '<path d=\"M6 9V2h12v7\"/><path d=\"M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2\"/><rect width=\"12\" height=\"8\" x=\"6\" y=\"14\" rx=\"1\"/>',\n /** download */\n download: '<path d=\"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4\"/><path d=\"M7 10l5 5 5-5\"/><path d=\"M12 15V3\"/>',\n /** x */\n close: '<path d=\"M18 6 6 18\"/><path d=\"m6 6 12 12\"/>',\n} satisfies Record<string, string>;\n\n/** Build an `<svg>` for one of the {@link ICONS}, or null if the name is unknown. */\nexport function createIcon(doc: Document, markup: string): SVGSVGElement {\n const svg = doc.createElementNS('http://www.w3.org/2000/svg', 'svg');\n svg.setAttribute('viewBox', '0 0 24 24');\n svg.setAttribute('fill', 'none');\n svg.setAttribute('stroke', 'currentColor');\n // Slightly under Lucide's default 2: at the toolbar's icon size a full-weight stroke reads\n // heavy and closes up the tighter shapes.\n svg.setAttribute('stroke-width', '1.75');\n svg.setAttribute('stroke-linecap', 'round');\n svg.setAttribute('stroke-linejoin', 'round');\n svg.setAttribute('aria-hidden', 'true');\n svg.setAttribute('focusable', 'false');\n // Icon markup is library-authored, never consumer input.\n svg.innerHTML = markup;\n return svg;\n}\n","import type { ControlDef, ControlItem } from './types';\n\n/**\n * The control registry.\n *\n * Deliberately just the mechanism — no icons, no built-in definitions — because `defineControl`\n * has to be callable before the toolbar chunk loads, so this module lands in the base bundle.\n * The built-ins live in `./builtins`, which the lazy chunk pulls in along with the icon set.\n */\nconst registry = new Map<string, ControlDef>();\n\n/**\n * Add a control, or replace one by reusing its id. Returns the definition so it can be dropped\n * straight into a layout.\n *\n * ```js\n * defineControl({ id: 'print', title: 'Print', icon: '<path d=\"…\"/>', action: () => print() });\n * new Zine(el, { source, controls: { items: ['prev', 'next', 'print'] } });\n * ```\n */\nexport function defineControl(def: ControlDef): ControlDef {\n registry.set(def.id, def);\n return def;\n}\n\n/** Look up a registered control. */\nexport function getControl(id: string): ControlDef | undefined {\n return registry.get(id);\n}\n\n/**\n * Turn a layout entry into a concrete definition. A bare string names a registered control; an\n * object with only some fields is layered over the registered one, so `{ id: 'next', title: 'Go\n * on' }` relabels the built-in without reimplementing it.\n */\nexport function resolveControl(item: ControlItem): ControlDef {\n if (typeof item === 'string') {\n const found = registry.get(item);\n if (!found) {\n throw new Error(\n `controls: unknown control '${item}'. Register it with defineControl() or pass a definition object.`,\n );\n }\n return found;\n }\n const base = registry.get(item.id);\n if (!base) return item as ControlDef;\n return { ...base, ...item };\n}\n\n/** The toolbar shown when `items` is not given. */\nexport const DEFAULT_ITEMS: readonly ControlItem[] = [\n 'prev',\n 'pageInput',\n 'next',\n '|',\n 'zoomOut',\n 'zoomIn',\n 'search',\n 'share',\n 'menu',\n 'fullscreen',\n];\n","/**\n * Where a reader can send a link, and how each service wants it.\n *\n * These are plain share-intent URLs — no SDKs, no third-party scripts, nothing that could track\n * the reader before they choose to share. Each brand mark is drawn from its own official glyph;\n * they are filled shapes rather than the stroked outlines used elsewhere in the toolbar, so they\n * carry `fill=\"currentColor\"` and no stroke.\n */\nexport interface Social {\n id: string;\n label: string;\n /** Inner SVG markup for a 24x24 viewBox, filled rather than stroked. */\n icon: string;\n href(url: string, title: string): string;\n}\n\nconst e = encodeURIComponent;\n\nexport const SOCIALS: readonly Social[] = [\n {\n id: 'facebook',\n label: 'Facebook',\n icon: '<path fill=\"currentColor\" stroke=\"none\" d=\"M22 12a10 10 0 1 0-11.56 9.88v-6.99H7.9V12h2.54V9.8c0-2.5 1.49-3.89 3.77-3.89 1.1 0 2.24.2 2.24.2v2.46h-1.26c-1.24 0-1.63.77-1.63 1.56V12h2.78l-.45 2.89h-2.33v6.99A10 10 0 0 0 22 12Z\"/>',\n href: (url) => `https://www.facebook.com/sharer/sharer.php?u=${e(url)}`,\n },\n {\n id: 'x',\n label: 'X (Twitter)',\n icon: '<path fill=\"currentColor\" stroke=\"none\" d=\"M17.53 3h3.06l-6.69 7.64L21.75 21h-6.16l-4.82-6.3L5.24 21H2.18l7.15-8.17L2.25 3h6.32l4.36 5.77L17.53 3Zm-1.07 16.17h1.69L7.62 4.73H5.8l10.66 14.44Z\"/>',\n href: (url, title) => `https://twitter.com/intent/tweet?url=${e(url)}&text=${e(title)}`,\n },\n {\n id: 'linkedin',\n label: 'LinkedIn',\n icon: '<path fill=\"currentColor\" stroke=\"none\" d=\"M20.45 20.45h-3.56v-5.57c0-1.33-.02-3.04-1.85-3.04-1.85 0-2.14 1.45-2.14 2.94v5.67H9.35V9h3.41v1.56h.05a3.74 3.74 0 0 1 3.37-1.85c3.6 0 4.27 2.37 4.27 5.46v6.28ZM5.34 7.43a2.07 2.07 0 1 1 0-4.13 2.07 2.07 0 0 1 0 4.13Zm1.78 13.02H3.55V9h3.57v11.45ZM22.22 0H1.77C.79 0 0 .77 0 1.72v20.56C0 23.23.79 24 1.77 24h20.45c.98 0 1.78-.77 1.78-1.72V1.72C24 .77 23.2 0 22.22 0Z\"/>',\n href: (url) => `https://www.linkedin.com/sharing/share-offsite/?url=${e(url)}`,\n },\n {\n id: 'whatsapp',\n label: 'WhatsApp',\n icon: '<path fill=\"currentColor\" stroke=\"none\" d=\"M12.04 2a9.9 9.9 0 0 0-8.5 14.9L2 22l5.25-1.38A9.9 9.9 0 1 0 12.04 2Zm5.8 14.06c-.25.7-1.44 1.33-1.99 1.38-.53.05-1.02.24-3.44-.72-2.9-1.14-4.73-4.1-4.87-4.29-.14-.19-1.16-1.54-1.16-2.94s.73-2.08 1-2.37c.26-.28.57-.35.76-.35h.55c.17 0 .42-.07.65.5.24.58.8 2 .87 2.14.07.14.12.31.02.5-.09.19-.14.3-.28.47l-.42.48c-.14.14-.28.29-.12.57.16.28.7 1.16 1.51 1.88 1.04.93 1.91 1.21 2.19 1.35.28.15.44.12.6-.07.17-.19.7-.81.88-1.09.19-.28.37-.23.63-.14.25.1 1.63.77 1.9.91.29.14.48.21.55.33.07.11.07.67-.18 1.37Z\"/>',\n href: (url, title) => `https://api.whatsapp.com/send?text=${e(`${title} ${url}`)}`,\n },\n {\n id: 'pinterest',\n label: 'Pinterest',\n icon: '<path fill=\"currentColor\" stroke=\"none\" d=\"M12 2a10 10 0 0 0-3.65 19.31c-.09-.78-.17-1.98.03-2.83.19-.78 1.2-4.98 1.2-4.98s-.3-.61-.3-1.52c0-1.42.82-2.48 1.85-2.48.87 0 1.3.66 1.3 1.44 0 .88-.56 2.2-.85 3.42-.24 1.02.51 1.86 1.52 1.86 1.83 0 3.23-1.93 3.23-4.7 0-2.46-1.77-4.18-4.29-4.18-2.92 0-4.64 2.19-4.64 4.46 0 .88.34 1.83.76 2.35a.3.3 0 0 1 .07.29l-.28 1.16c-.05.19-.15.23-.34.14-1.28-.6-2.08-2.47-2.08-3.98 0-3.24 2.35-6.21 6.79-6.21 3.56 0 6.33 2.54 6.33 5.93 0 3.54-2.23 6.39-5.32 6.39-1.04 0-2.02-.54-2.35-1.18l-.64 2.44c-.23.89-.86 2.01-1.28 2.69A10 10 0 1 0 12 2Z\"/>',\n href: (url, title) => `https://pinterest.com/pin/create/button/?url=${e(url)}&description=${e(title)}`,\n },\n {\n id: 'email',\n label: 'Email',\n icon: '<path fill=\"currentColor\" stroke=\"none\" d=\"M20 4H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2Zm0 4.24-7.47 4.67a1 1 0 0 1-1.06 0L4 8.24V6.4l8 5 8-5v1.84Z\"/>',\n href: (url, title) => `mailto:?subject=${e(title)}&body=${e(url)}`,\n },\n];\n","/**\n * A small QR encoder, enough to turn a URL into a scannable grid.\n *\n * Written rather than pulled in so the package keeps its \"no dependencies\" promise, and so no\n * reader's document URL is handed to a third-party image service to be logged. Deliberately\n * narrow: byte mode, error-correction level M, versions 1-10 (up to 271 characters at level M),\n * which covers any sane page URL. Longer input throws rather than silently producing a code that\n * will not scan.\n */\n\n/** Data codewords available per version at error-correction level M, versions 1-10. */\nconst DATA_CODEWORDS = [16, 28, 44, 64, 86, 108, 124, 154, 182, 216];\n/** Error-correction codewords per block, level M, versions 1-10. */\nconst EC_PER_BLOCK = [10, 16, 26, 18, 24, 16, 18, 22, 22, 26];\n/** How many EC blocks the data is split into, level M, versions 1-10. */\nconst BLOCKS = [1, 1, 1, 2, 2, 4, 4, 4, 5, 5];\n/** Where alignment patterns sit, per version (empty for version 1). */\nconst ALIGNMENT = [\n [],\n [6, 18],\n [6, 22],\n [6, 26],\n [6, 30],\n [6, 34],\n [6, 22, 38],\n [6, 24, 42],\n [6, 26, 46],\n [6, 28, 50],\n];\n\n// Galois field tables for GF(256), used by the Reed-Solomon error correction.\nconst EXP = new Uint8Array(512);\nconst LOG = new Uint8Array(256);\nfor (let i = 0, x = 1; i < 255; i++) {\n EXP[i] = x;\n LOG[x] = i;\n x <<= 1;\n if (x & 0x100) x ^= 0x11d; // the QR field's primitive polynomial\n}\nfor (let i = 255; i < 512; i++) EXP[i] = EXP[i - 255]!;\n\nconst mul = (a: number, b: number): number =>\n a === 0 || b === 0 ? 0 : EXP[(LOG[a]! + LOG[b]!) % 255]!;\n\n/** The generator polynomial for `degree` error-correction codewords. */\nfunction generator(degree: number): Uint8Array {\n let poly = new Uint8Array([1]);\n for (let i = 0; i < degree; i++) {\n const next = new Uint8Array(poly.length + 1);\n for (let j = 0; j < poly.length; j++) {\n // Written as explicit reads: a compound assignment on an indexed element is what\n // noUncheckedIndexedAccess objects to, since the target is possibly-undefined.\n next[j] = next[j]! ^ poly[j]!;\n next[j + 1] = next[j + 1]! ^ mul(poly[j]!, EXP[i]!);\n }\n poly = next;\n }\n return poly;\n}\n\n/** Reed-Solomon remainder: the error-correction codewords for one block. */\nfunction ecBlock(data: Uint8Array, count: number): Uint8Array {\n const gen = generator(count);\n const out = new Uint8Array(count);\n for (const byte of data) {\n const factor = byte ^ out[0]!;\n out.copyWithin(0, 1);\n out[count - 1] = 0;\n if (factor !== 0) {\n for (let i = 0; i < count; i++) out[i] = out[i]! ^ mul(gen[i + 1]!, factor);\n }\n }\n return out;\n}\n\n/** The 15-bit format string for level M and a mask, with its BCH check bits. */\nfunction formatBits(mask: number): number {\n const data = (0b00 << 3) | mask; // 00 = level M\n let rem = data;\n for (let i = 0; i < 10; i++) rem = (rem << 1) ^ ((rem >>> 9) * 0x537);\n return ((data << 10) | rem) ^ 0x5412;\n}\n\ntype Grid = { size: number; modules: Uint8Array; reserved: Uint8Array };\n\nconst at = (g: Grid, x: number, y: number): number => g.modules[y * g.size + x]!;\nconst set = (g: Grid, x: number, y: number, dark: boolean, reserve = true): void => {\n g.modules[y * g.size + x] = dark ? 1 : 0;\n if (reserve) g.reserved[y * g.size + x] = 1;\n};\n\nfunction placeFinder(g: Grid, cx: number, cy: number): void {\n for (let dy = -1; dy <= 7; dy++) {\n for (let dx = -1; dx <= 7; dx++) {\n const x = cx + dx;\n const y = cy + dy;\n if (x < 0 || y < 0 || x >= g.size || y >= g.size) continue;\n const d = Math.max(Math.abs(dx - 3), Math.abs(dy - 3));\n set(g, x, y, d !== 2 && d <= 3);\n }\n }\n}\n\n/** Encode `text` as a QR matrix: a square of 0/1 by row. */\nexport function encodeQr(text: string): { size: number; modules: Uint8Array } {\n const bytes = new TextEncoder().encode(text);\n const version = DATA_CODEWORDS.findIndex((cap) => bytes.length + 2 <= cap) + 1;\n if (version === 0) {\n throw new Error(`qr: ${bytes.length} bytes is too long for this encoder (max 214).`);\n }\n\n // --- bit stream: mode, length, payload, terminator, padding ---\n const capacity = DATA_CODEWORDS[version - 1]!;\n const bits: number[] = [];\n const push = (value: number, width: number): void => {\n for (let i = width - 1; i >= 0; i--) bits.push((value >>> i) & 1);\n };\n push(0b0100, 4); // byte mode\n push(bytes.length, version < 10 ? 8 : 16);\n for (const byte of bytes) push(byte, 8);\n push(0, Math.min(4, capacity * 8 - bits.length)); // terminator\n while (bits.length % 8) bits.push(0);\n const data = new Uint8Array(capacity);\n for (let i = 0; i < bits.length; i += 8) {\n let byte = 0;\n for (let b = 0; b < 8; b++) byte = (byte << 1) | bits[i + b]!;\n data[i / 8] = byte;\n }\n for (let i = bits.length / 8, pad = 0; i < capacity; i++, pad++) {\n data[i] = pad % 2 === 0 ? 0xec : 0x11; // the spec's alternating pad bytes\n }\n\n // --- split into blocks, compute EC, interleave ---\n const blockCount = BLOCKS[version - 1]!;\n const ecCount = EC_PER_BLOCK[version - 1]!;\n const shortLen = Math.floor(capacity / blockCount);\n const longCount = capacity % blockCount;\n const dataBlocks: Uint8Array[] = [];\n const ecBlocks: Uint8Array[] = [];\n for (let i = 0, offset = 0; i < blockCount; i++) {\n const len = shortLen + (i >= blockCount - longCount ? 1 : 0);\n const block = data.subarray(offset, offset + len);\n offset += len;\n dataBlocks.push(block);\n ecBlocks.push(ecBlock(block, ecCount));\n }\n const codewords: number[] = [];\n for (let i = 0; i < shortLen + 1; i++) {\n for (const block of dataBlocks) if (i < block.length) codewords.push(block[i]!);\n }\n for (let i = 0; i < ecCount; i++) {\n for (const block of ecBlocks) codewords.push(block[i]!);\n }\n\n // --- lay out the matrix ---\n const size = version * 4 + 17;\n const g: Grid = {\n size,\n modules: new Uint8Array(size * size),\n reserved: new Uint8Array(size * size),\n };\n placeFinder(g, 0, 0);\n placeFinder(g, size - 7, 0);\n placeFinder(g, 0, size - 7);\n for (let i = 8; i < size - 8; i++) {\n const dark = i % 2 === 0; // timing patterns\n set(g, i, 6, dark);\n set(g, 6, i, dark);\n }\n for (const ax of ALIGNMENT[version - 1]!) {\n for (const ay of ALIGNMENT[version - 1]!) {\n // Alignment patterns skip the corners already held by finders.\n if ((ax < 9 && ay < 9) || (ax < 9 && ay > size - 10) || (ax > size - 10 && ay < 9)) continue;\n for (let dy = -2; dy <= 2; dy++) {\n for (let dx = -2; dx <= 2; dx++) {\n set(g, ax + dx, ay + dy, Math.max(Math.abs(dx), Math.abs(dy)) !== 1);\n }\n }\n }\n }\n set(g, 8, size - 8, true); // the always-dark module\n // Reserve the format areas so data does not land in them.\n for (let i = 0; i < 9; i++) {\n if (i !== 6) set(g, i, 8, false), set(g, 8, i, false);\n }\n for (let i = 0; i < 8; i++) set(g, size - 1 - i, 8, false), set(g, 8, size - 1 - i, false);\n set(g, 8, size - 8, true);\n\n // --- weave the codewords in, masking as we go (mask 0: (x + y) % 2) ---\n let bit = 0;\n const total = codewords.length * 8;\n for (let right = size - 1; right >= 1; right -= 2) {\n if (right === 6) right = 5; // the vertical timing column is skipped\n for (let step = 0; step < size; step++) {\n for (let col = 0; col < 2; col++) {\n const x = right - col;\n const upward = ((right + 1) & 2) === 0;\n const y = upward ? size - 1 - step : step;\n if (g.reserved[y * size + x]) continue;\n let dark = false;\n if (bit < total) {\n dark = ((codewords[bit >>> 3]! >>> (7 - (bit & 7))) & 1) === 1;\n bit++;\n }\n if ((x + y) % 2 === 0) dark = !dark; // mask 0\n set(g, x, y, dark, false);\n }\n }\n }\n\n // --- format information, now that the mask is known ---\n const format = formatBits(0);\n for (let i = 0; i < 15; i++) {\n const dark = ((format >>> i) & 1) === 1;\n // Around the top-left finder...\n const a = i < 6 ? i : i < 8 ? i + 1 : 8;\n const b = i < 8 ? 8 : i < 9 ? 7 : 14 - i;\n set(g, a, 8, dark);\n set(g, 8, b, dark);\n // ...and the copy split between the other two.\n if (i < 8) set(g, size - 1 - i, 8, dark);\n else set(g, 8, size - 15 + i, dark);\n }\n set(g, 8, size - 8, true);\n\n return { size, modules: g.modules };\n}\n\n/** Render a QR matrix as an SVG string, sized to `px`. */\nexport function qrSvg(text: string, px: number): string {\n const { size, modules } = encodeQr(text);\n let path = '';\n for (let y = 0; y < size; y++) {\n for (let x = 0; x < size; x++) {\n if (modules[y * size + x]) path += `M${x} ${y}h1v1h-1z`;\n }\n }\n const quiet = 2; // the spec asks for 4; 2 scans fine and wastes less space on screen\n const box = size + quiet * 2;\n return `<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"${px}\" height=\"${px}\" viewBox=\"0 0 ${box} ${box}\" shape-rendering=\"crispEdges\"><rect width=\"${box}\" height=\"${box}\" fill=\"#fff\"/><g transform=\"translate(${quiet} ${quiet})\" fill=\"#000\">${`<path d=\"${path}\"/>`}</g></svg>`;\n}\n","import { createIcon, ICONS } from './icons';\nimport { SOCIALS } from './socials';\nimport { qrSvg } from './qr';\nimport type { Zine } from '../zine';\n\n/** QR edge length in CSS px. */\nconst QR_SIZE = 132;\n/** How long the copy button confirms for. */\nconst COPIED_MS = 1600;\n\n/**\n * The share dialog: a QR code, the link, a copy button and the usual social destinations.\n *\n * Loaded on demand — the whole module, its icons and the QR encoder arrive only when a reader\n * presses Share, so a book nobody shares pays nothing for it.\n */\nexport class ShareDialog {\n #doc: Document;\n #backdrop: HTMLElement;\n #dialog: HTMLElement;\n #lastFocus: Element | null;\n #timer: ReturnType<typeof setTimeout> | null = null;\n #onKey: (e: KeyboardEvent) => void;\n\n constructor(zine: Zine, container: HTMLElement) {\n const doc = container.ownerDocument!;\n this.#doc = doc;\n this.#lastFocus = doc.activeElement;\n\n const url = zine.pageLink();\n const title = doc.title || 'Flipbook';\n\n this.#backdrop = doc.createElement('div');\n this.#backdrop.className = 'zine-share-backdrop';\n this.#backdrop.addEventListener('pointerdown', (e) => {\n if (e.target === this.#backdrop) this.close();\n });\n\n this.#dialog = doc.createElement('div');\n this.#dialog.className = 'zine-share';\n this.#dialog.setAttribute('role', 'dialog');\n this.#dialog.setAttribute('aria-modal', 'true');\n this.#dialog.setAttribute('aria-label', 'Share');\n this.#backdrop.appendChild(this.#dialog);\n\n const head = doc.createElement('div');\n head.className = 'zine-share-head';\n const heading = doc.createElement('strong');\n heading.textContent = 'Share';\n const close = doc.createElement('button');\n close.type = 'button';\n close.className = 'zine-share-close';\n close.setAttribute('aria-label', 'Close');\n close.appendChild(createIcon(doc, ICONS.close));\n close.addEventListener('click', () => this.close());\n head.append(heading, close);\n\n this.#dialog.append(head, this.#linkRow(doc, url), this.#socialRow(doc, url, title));\n const qr = this.#qr(doc, url);\n if (qr) this.#dialog.insertBefore(qr, this.#dialog.children[1]!);\n\n container.ownerDocument.body.appendChild(this.#backdrop);\n\n this.#onKey = (e): void => {\n if (e.key === 'Escape') this.close();\n if (e.key === 'Tab') this.#trapFocus(e);\n };\n this.#backdrop.addEventListener('keydown', this.#onKey);\n close.focus();\n }\n\n /** The QR, or nothing if the URL is too long to encode — better no code than a broken one. */\n #qr(doc: Document, url: string): HTMLElement | null {\n if (!url) return null;\n try {\n const wrap = doc.createElement('div');\n wrap.className = 'zine-share-qr';\n wrap.innerHTML = qrSvg(url, QR_SIZE);\n wrap.setAttribute('aria-label', 'QR code for this page');\n wrap.setAttribute('role', 'img');\n return wrap;\n } catch {\n return null;\n }\n }\n\n #linkRow(doc: Document, url: string): HTMLElement {\n const row = doc.createElement('div');\n row.className = 'zine-share-link';\n const input = doc.createElement('input');\n input.type = 'text';\n input.readOnly = true;\n input.value = url;\n input.setAttribute('aria-label', 'Link to this page');\n input.addEventListener('focus', () => input.select());\n\n const copy = doc.createElement('button');\n copy.type = 'button';\n copy.className = 'zine-share-copy';\n copy.textContent = 'Copy';\n copy.addEventListener('click', () => {\n void this.#copy(url, copy);\n });\n row.append(input, copy);\n return row;\n }\n\n async #copy(url: string, button: HTMLButtonElement): Promise<void> {\n try {\n await navigator.clipboard?.writeText(url);\n button.textContent = 'Copied';\n } catch {\n button.textContent = 'Press Ctrl+C';\n }\n if (this.#timer) clearTimeout(this.#timer);\n this.#timer = setTimeout(() => {\n button.textContent = 'Copy';\n }, COPIED_MS);\n }\n\n #socialRow(doc: Document, url: string, title: string): HTMLElement {\n const row = doc.createElement('div');\n row.className = 'zine-share-socials';\n for (const social of SOCIALS) {\n const link = doc.createElement('a');\n link.className = 'zine-share-social';\n link.href = social.href(url, title);\n link.title = social.label;\n link.setAttribute('aria-label', `Share on ${social.label}`);\n if (social.id !== 'email') {\n link.target = '_blank';\n link.rel = 'noopener noreferrer';\n }\n link.appendChild(createIcon(doc, social.icon));\n row.appendChild(link);\n }\n return row;\n }\n\n /** Keep Tab inside the dialog while it is open. */\n #trapFocus(event: KeyboardEvent): void {\n const focusable = [\n ...this.#dialog.querySelectorAll<HTMLElement>('button, a[href], input'),\n ].filter((el) => !el.hasAttribute('disabled'));\n if (focusable.length === 0) return;\n const first = focusable[0]!;\n const last = focusable.at(-1)!;\n const active = this.#doc.activeElement;\n if (event.shiftKey && active === first) {\n last.focus();\n event.preventDefault();\n } else if (!event.shiftKey && active === last) {\n first.focus();\n event.preventDefault();\n }\n }\n\n close(): void {\n this.destroy();\n }\n\n destroy(): void {\n if (this.#timer) clearTimeout(this.#timer);\n this.#timer = null;\n this.#backdrop.removeEventListener('keydown', this.#onKey);\n this.#backdrop.remove();\n // Hand focus back to whatever opened the dialog.\n (this.#lastFocus as HTMLElement | null)?.focus?.();\n }\n}\n","import { ICONS } from './icons';\nimport { defineControl } from './registry';\nimport type { ControlContext } from './types';\n\n\n/** Zoom step per click: two clicks double the scale. */\nconst ZOOM_STEP = Math.SQRT2;\n\nconst isFullscreen = (ctx: ControlContext): boolean => {\n const doc = ctx.zine.container.ownerDocument;\n return doc?.fullscreenElement === ctx.zine.container;\n};\n\n/**\n * Register the stock controls. Called once as the toolbar chunk loads, so the icon set and these\n * definitions stay out of the base bundle.\n *\n * `pageInput` and `search` are not here: both need the toolbar instance itself (one builds an\n * input, the other opens an anchored panel), so the toolbar registers them.\n */\nexport function registerBuiltins(): void {\n defineControl({\n id: 'prev',\n title: 'Previous page',\n icon: ICONS.prev,\n isDisabled: (ctx) => !ctx.zine.canFlipPrev(),\n action: (ctx) => ctx.zine.flipPrev(),\n });\n\n defineControl({\n id: 'next',\n title: 'Next page',\n icon: ICONS.next,\n isDisabled: (ctx) => !ctx.zine.canFlipNext(),\n action: (ctx) => ctx.zine.flipNext(),\n });\n\n // The chevrons point the way the book travels, which reverses in RTL — same as the page\n // arrows flanking the book.\n const rtl = (ctx: ControlContext): boolean => ctx.zine.getDirection() === 'rtl';\n\n defineControl({\n id: 'first',\n title: 'First page',\n icon: (ctx) => (rtl(ctx) ? ICONS.last : ICONS.first),\n isDisabled: (ctx) => !ctx.zine.canFlipPrev(),\n action: (ctx) => {\n ctx.zine.flipTo(0);\n ctx.close();\n },\n });\n\n defineControl({\n id: 'last',\n title: 'Last page',\n icon: (ctx) => (rtl(ctx) ? ICONS.first : ICONS.last),\n isDisabled: (ctx) => !ctx.zine.canFlipNext(),\n action: (ctx) => {\n ctx.zine.flipTo(ctx.zine.getPageCount() - 1);\n ctx.close();\n },\n });\n\n defineControl({\n id: 'zoomIn',\n title: 'Zoom in',\n icon: ICONS.zoomIn,\n isDisabled: (ctx) => ctx.zine.getZoom() >= ctx.zine.getMaxZoom() - 1e-6,\n action: (ctx) => ctx.zine.setZoom(ctx.zine.getZoom() * ZOOM_STEP),\n });\n\n defineControl({\n id: 'zoomOut',\n title: 'Zoom out',\n icon: ICONS.zoomOut,\n isDisabled: (ctx) => ctx.zine.getZoom() <= 1 + 1e-6,\n action: (ctx) => ctx.zine.setZoom(ctx.zine.getZoom() / ZOOM_STEP),\n });\n\n defineControl({\n id: 'fullscreen',\n title: 'Fullscreen',\n icon: ICONS.fullscreen,\n isVisible: (ctx) => typeof ctx.zine.container.requestFullscreen === 'function',\n isActive: isFullscreen,\n action: (ctx) => {\n const doc = ctx.zine.container.ownerDocument;\n if (isFullscreen(ctx)) void doc?.exitFullscreen?.();\n else void ctx.zine.container.requestFullscreen?.();\n ctx.close();\n },\n });\n\n defineControl({\n id: 'share',\n title: 'Share',\n icon: ICONS.share,\n action: (ctx) => {\n ctx.close();\n // The dialog, its brand marks and the QR encoder are a chunk of their own: a book nobody\n // shares never downloads any of it.\n void import('./share')\n .then(({ ShareDialog }) => new ShareDialog(ctx.zine, ctx.zine.container))\n .catch(() => {\n // No dialog, so fall back to the plain behaviour rather than doing nothing.\n void navigator.clipboard?.writeText(ctx.zine.pageLink()).catch(() => {});\n });\n },\n });\n\n defineControl({\n id: 'download',\n title: 'Download PDF',\n icon: ICONS.download,\n // Hidden for image books and for PDFs opened from a caller-owned pdf.js document, which\n // have no file of their own to save.\n isVisible: (ctx) => ctx.zine.canDownload(),\n action: (ctx) => {\n void ctx.zine.download();\n ctx.close();\n },\n });\n\n defineControl({\n id: 'spread',\n // Says what pressing it will do, not what the book is doing now, and in the reader's terms —\n // \"spread mode\" is the library's word for it, not theirs.\n title: (ctx) => (ctx.zine.isSinglePage() ? 'Show two pages' : 'Show one page'),\n icon: (ctx) => (ctx.zine.isSinglePage() ? ICONS.twoPages : ICONS.onePage),\n // Hidden while a narrow container is forcing one page: pressing it could not honour two.\n isVisible: (ctx) => !ctx.zine.isResponsiveSingle(),\n action: (ctx) => {\n ctx.zine.toggleSpreadMode();\n ctx.close();\n },\n });\n\n defineControl({\n id: 'print',\n title: 'Print',\n icon: ICONS.print,\n // Same reach as download: there has to be an original document to print.\n isVisible: (ctx) => ctx.zine.canPrint(),\n action: (ctx) => {\n void ctx.zine.print();\n ctx.close();\n },\n });\n\n defineControl({\n id: 'menu',\n title: 'More',\n icon: ICONS.menu,\n // Share and fullscreen sit on the bar itself by default, so the overflow holds what is left.\n children: ['first', 'last', 'spread', 'thumbnails', 'outline', 'print', 'download'],\n });\n}\n","/**\n * The toolbar's stylesheet, injected once per document.\n *\n * The rest of the library styles elements inline, but a toolbar needs `:hover`, `:focus-visible`\n * and `:disabled` — states inline styles cannot express — so this is the one place a `<style>`\n * element is warranted. Everything is scoped under `.zine-controls`, and the colours come from\n * custom properties so a consumer can retheme without overriding rules.\n */\nconst STYLE_ID = 'zine-controls-style';\n\nexport const CSS = `\n/* Docked mode wraps the book so the bar can sit beside it without shrinking the container,\n whose measured box the renderer and hit-testing both depend on.\n The wrapper deliberately does not stretch or grow its children: the container keeps whatever\n width, aspect-ratio and auto-margins the consumer's own CSS gave it. */\n.zine-controls-wrap { display: flex; }\n/* Stacked: children keep their own width (so a percentage or auto-margin still resolves against\n the wrapper) and take only the height they ask for. */\n.zine-controls-wrap-top,\n.zine-controls-wrap-bottom { flex-direction: column; align-items: stretch; }\n/* Side by side: the bar is only as wide as its buttons, and both are vertically centred. */\n.zine-controls-wrap-left,\n.zine-controls-wrap-right { flex-direction: row; align-items: center; }\n/* min-height:0 matters as much as min-width here. A flex item's automatic minimum size floors it\n at its content, so once the canvas has grown for a taller layout the book cannot shrink back —\n its aspect-ratio is restored but ignored, leaving the extra height behind. */\n.zine-controls-wrap > * { flex: 0 0 auto; min-width: 0; min-height: 0; }\n\n.zine-controls {\n position: relative;\n display: flex;\n gap: 4px;\n padding: 5px;\n z-index: 2;\n box-sizing: border-box;\n font: 500 12px/1.2 system-ui, sans-serif;\n color: var(--zine-controls-fg, #f4f4f5);\n touch-action: auto;\n -webkit-user-select: none;\n user-select: none;\n}\n.zine-controls-docked { flex: 0 0 auto; justify-content: center; align-items: center; }\n.zine-controls-floating {\n position: absolute;\n /* Transparent to the book except on the buttons themselves, so gaps stay draggable. */\n pointer-events: none;\n}\n.zine-controls-bar {\n display: flex;\n align-items: center;\n gap: 1px;\n padding: 3px;\n border-radius: 8px;\n pointer-events: auto;\n background: var(--zine-controls-bg, rgba(24, 24, 27, 0.82));\n backdrop-filter: blur(8px);\n}\n/* Floating: lifted off the page it covers. Docked: flat, with an outline so it reads as a\n control strip rather than a shadow hanging in empty space. */\n.zine-controls-floating .zine-controls-bar { box-shadow: 0 2px 12px rgba(0, 0, 0, 0.28); }\n.zine-controls-docked .zine-controls-bar {\n border: 1px solid var(--zine-controls-hover, rgba(255, 255, 255, 0.14));\n}\n.zine-controls-floating.zine-controls-bottom { inset: auto 0 0 0; justify-content: center; }\n.zine-controls-floating.zine-controls-top { inset: 0 0 auto 0; justify-content: center; }\n.zine-controls-floating.zine-controls-left { inset: 0 auto 0 0; align-items: center; }\n.zine-controls-floating.zine-controls-right { inset: 0 0 0 auto; align-items: center; }\n/* A bar on a vertical edge stacks its buttons, docked or floating. */\n.zine-controls-left .zine-controls-bar,\n.zine-controls-right .zine-controls-bar { flex-direction: column; }\n\n.zine-controls-btn {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n width: 26px;\n height: 26px;\n padding: 0;\n border: 0;\n border-radius: 6px;\n background: transparent;\n color: inherit;\n cursor: pointer;\n font: inherit;\n}\n.zine-controls-btn svg { width: 15px; height: 15px; }\n.zine-controls-btn:hover:not(:disabled) { background: var(--zine-controls-hover, rgba(255,255,255,0.14)); }\n.zine-controls-btn:focus-visible {\n outline: 2px solid var(--zine-controls-accent, #7dd3fc);\n outline-offset: 1px;\n}\n.zine-controls-btn:disabled { opacity: 0.38; cursor: default; }\n/* A custom widget cannot always be disabled itself, so it is marked instead and reads the same. */\n.zine-controls-off { opacity: 0.38; }\n.zine-controls-off[aria-disabled='true'] { pointer-events: none; }\n.zine-controls-btn[aria-pressed=\"true\"],\n.zine-controls-btn[aria-expanded=\"true\"] { background: var(--zine-controls-hover, rgba(255,255,255,0.14)); }\n\n.zine-controls-sep {\n width: 1px;\n align-self: stretch;\n margin: 3px 3px;\n background: currentColor;\n opacity: 0.22;\n}\n.zine-controls-left .zine-controls-sep,\n.zine-controls-right .zine-controls-sep { width: auto; height: 1px; margin: 3px 3px; }\n\n.zine-controls-page {\n display: inline-flex;\n align-items: center;\n gap: 3px;\n padding: 0 3px;\n pointer-events: auto;\n white-space: nowrap;\n}\n.zine-controls-page input {\n width: 2.2em;\n padding: 2px 3px;\n border: 1px solid var(--zine-controls-hover, rgba(255,255,255,0.2));\n border-radius: 4px;\n background: rgba(0, 0, 0, 0.25);\n color: inherit;\n font: inherit;\n text-align: center;\n -moz-appearance: textfield;\n}\n.zine-controls-page input::-webkit-outer-spin-button,\n.zine-controls-page input::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; }\n.zine-controls-page input:focus-visible {\n outline: 2px solid var(--zine-controls-accent, #7dd3fc);\n outline-offset: 0;\n}\n\n.zine-controls-menu {\n position: absolute;\n display: flex;\n flex-direction: column;\n gap: 1px;\n min-width: 152px;\n padding: 4px;\n border-radius: 8px;\n pointer-events: auto;\n background: var(--zine-controls-bg, rgba(24, 24, 27, 0.94));\n box-shadow: 0 6px 22px rgba(0, 0, 0, 0.36);\n backdrop-filter: blur(8px);\n}\n.zine-controls-menu .zine-controls-btn {\n width: 100%;\n height: auto;\n gap: 8px;\n padding: 6px 8px;\n justify-content: flex-start;\n}\n\n/* Search shares the rail: a query field pinned at the top over a scrolling list of hits. */\n.zine-search { gap: 0; overflow: hidden; }\n.zine-search-input {\n flex: 0 0 auto;\n width: 100%;\n padding: 6px 8px;\n border: 1px solid var(--zine-controls-hover, rgba(255,255,255,0.2));\n border-radius: 6px;\n background: rgba(0, 0, 0, 0.25);\n color: inherit;\n font: inherit;\n box-sizing: border-box;\n}\n.zine-search-hits {\n flex: 1 1 auto;\n overflow-y: auto;\n overscroll-behavior: contain;\n margin-top: 5px;\n scrollbar-width: thin;\n}\n.zine-search-hit {\n display: block;\n width: 100%;\n padding: 6px 8px;\n border: 0;\n border-radius: 5px;\n background: transparent;\n color: inherit;\n font: inherit;\n text-align: left;\n cursor: pointer;\n box-sizing: border-box;\n}\n.zine-search-hit:hover { background: var(--zine-controls-hover, rgba(255,255,255,0.14)); }\n.zine-search-hit:focus-visible {\n outline: 2px solid var(--zine-controls-accent, #7dd3fc);\n outline-offset: -2px;\n}\n.zine-search-page { display: block; font-size: 0.9em; opacity: 0.85; }\n.zine-search-hit small {\n display: block;\n margin-top: 2px;\n opacity: 0.62;\n line-height: 1.35;\n overflow-wrap: anywhere;\n}\n\n/* Page-turn arrows flanking the book. Like the docked toolbar and the side panels, they sit\n outside the container so they never shrink the book or intercept its gestures. */\n.zine-arrows-wrap {\n display: flex;\n align-items: center;\n gap: 4px;\n min-width: 0;\n}\n.zine-arrows-wrap > *:not(.zine-arrow) { flex: 1 1 auto; min-width: 0; min-height: 0; }\n.zine-arrow {\n flex: 0 0 auto;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n width: 40px;\n height: 40px;\n padding: 0;\n border: 0;\n border-radius: 50%;\n background: var(--zine-controls-bg, rgba(24, 24, 27, 0.82));\n color: var(--zine-controls-fg, #f4f4f5);\n cursor: pointer;\n backdrop-filter: blur(8px);\n -webkit-user-select: none;\n user-select: none;\n}\n.zine-arrow svg { width: 22px; height: 22px; }\n.zine-arrow:hover:not(:disabled) { background: var(--zine-controls-hover, rgba(255,255,255,0.22)); }\n.zine-arrow:focus-visible {\n outline: 2px solid var(--zine-controls-accent, #7dd3fc);\n outline-offset: 2px;\n}\n/* Nothing to turn to: invisible, but still occupying its slot so the book does not slide across\n as the reader reaches a cover. */\n.zine-arrow-hidden { visibility: hidden; }\n/* No room to flank on a narrow screen; the toolbar's own prev/next still work. */\n@media (max-width: 640px) {\n .zine-arrow { display: none; }\n}\n@media (prefers-reduced-motion: no-preference) {\n .zine-arrow { transition: background 120ms ease; }\n}\n\n/* Side panels (thumbnails, outline). The rail wraps the book and its docked toolbar so it sits\n beside them without shrinking the container the renderer measures. */\n.zine-panel-wrap { display: flex; align-items: stretch; gap: 8px; }\n\n/* The holder stretches to the book's height; the rail is absolutely positioned inside it so a\n long list scrolls rather than growing the row and running past the bottom of the book. */\n.zine-panel-holder {\n position: relative;\n flex: 0 0 auto;\n align-self: stretch;\n min-height: 0;\n}\n.zine-panel {\n position: absolute;\n inset: 0;\n display: flex;\n flex-direction: column;\n gap: 6px;\n overflow-y: auto;\n overscroll-behavior: contain;\n padding: 6px;\n box-sizing: border-box;\n border-radius: 8px;\n background: var(--zine-controls-bg, rgba(24, 24, 27, 0.82));\n color: var(--zine-controls-fg, #f4f4f5);\n font: 500 11px/1.2 system-ui, sans-serif;\n scrollbar-width: thin;\n touch-action: auto;\n -webkit-user-select: none;\n user-select: none;\n}\n/* Overlay fallback, used when the container has no parent to wrap. */\n.zine-panel-overlay { position: absolute; inset: 0 auto 0 0; z-index: 3; }\n.zine-panel-active { background: var(--zine-controls-hover, rgba(255,255,255,0.18)); }\n.zine-panel-note { padding: 8px; opacity: 0.66; line-height: 1.4; }\n\n.zine-thumbs { align-items: center; }\n\n.zine-thumbs-row {\n display: flex;\n flex-wrap: wrap;\n justify-content: center;\n gap: 2px;\n width: 100%;\n padding: 4px;\n border: 0;\n border-radius: 6px;\n background: transparent;\n color: inherit;\n font: inherit;\n cursor: pointer;\n box-sizing: border-box;\n}\n.zine-thumbs-row:hover { background: var(--zine-controls-hover, rgba(255,255,255,0.14)); }\n.zine-thumbs-row:focus-visible {\n outline: 2px solid var(--zine-controls-accent, #7dd3fc);\n outline-offset: -2px;\n}\n.zine-thumbs-row.zine-panel-active .zine-thumbs-cell {\n outline: 1px solid var(--zine-controls-accent, #7dd3fc);\n}\n\n/* Outline: a single column of headings, indented by depth. */\n.zine-outline { gap: 1px; }\n.zine-outline-row {\n display: block;\n width: 100%;\n padding: 6px 8px;\n border: 0;\n border-radius: 5px;\n background: transparent;\n color: inherit;\n font: inherit;\n text-align: left;\n line-height: 1.35;\n cursor: pointer;\n box-sizing: border-box;\n overflow-wrap: anywhere;\n}\n.zine-outline-row:hover:not(:disabled) {\n background: var(--zine-controls-hover, rgba(255,255,255,0.14));\n}\n.zine-outline-row:focus-visible {\n outline: 2px solid var(--zine-controls-accent, #7dd3fc);\n outline-offset: -2px;\n}\n/* A heading whose destination could not be resolved: shown, but nothing to click through to. */\n.zine-outline-row:disabled { opacity: 0.5; cursor: default; }\n\n.zine-thumbs-cell {\n flex: 1 1 0;\n min-width: 0;\n min-height: 24px;\n display: flex;\n background: rgba(0, 0, 0, 0.3);\n border-radius: 2px;\n overflow: hidden;\n}\n/* A lone page in a book that pairs elsewhere (a cover, a back page) keeps one page's width and\n centres, instead of stretching across both columns. */\n.zine-thumbs-row-lone .zine-thumbs-cell { flex: 0 0 calc(50% - 1px); }\n.zine-thumbs-img { display: block; width: 100%; height: auto; }\n.zine-thumbs-caption { flex: 1 0 100%; text-align: center; opacity: 0.7; }\n\n/* Share dialog. Centred over the page rather than in the side rail: a QR and six destinations\n need more room than the rail gives, and sharing is a brief interruption, not a browsing mode. */\n.zine-share-backdrop {\n position: fixed;\n inset: 0;\n z-index: 2147483000;\n display: flex;\n align-items: center;\n justify-content: center;\n padding: 16px;\n background: rgba(0, 0, 0, 0.55);\n font: 500 13px/1.4 system-ui, sans-serif;\n color: var(--zine-controls-fg, #f4f4f5);\n}\n.zine-share {\n width: min(320px, 100%);\n max-height: 100%;\n overflow-y: auto;\n display: flex;\n flex-direction: column;\n gap: 12px;\n padding: 14px;\n border-radius: 12px;\n background: var(--zine-share-bg, #1c1c20);\n box-shadow: 0 18px 50px rgba(0, 0, 0, 0.45);\n box-sizing: border-box;\n}\n.zine-share-head { display: flex; align-items: center; justify-content: space-between; gap: 8px; }\n.zine-share-head strong { font-size: 15px; }\n.zine-share-close {\n display: inline-flex;\n width: 26px;\n height: 26px;\n align-items: center;\n justify-content: center;\n padding: 0;\n border: 0;\n border-radius: 6px;\n background: transparent;\n color: inherit;\n cursor: pointer;\n}\n.zine-share-close svg { width: 16px; height: 16px; }\n.zine-share-close:hover { background: var(--zine-controls-hover, rgba(255,255,255,0.14)); }\n\n.zine-share-qr {\n align-self: center;\n line-height: 0;\n padding: 8px;\n border-radius: 8px;\n background: #fff;\n}\n.zine-share-qr svg { display: block; }\n\n.zine-share-link { display: flex; gap: 6px; }\n.zine-share-link input {\n flex: 1 1 auto;\n min-width: 0;\n padding: 7px 9px;\n border: 1px solid var(--zine-controls-hover, rgba(255,255,255,0.2));\n border-radius: 7px;\n background: rgba(0, 0, 0, 0.3);\n color: inherit;\n font: inherit;\n}\n.zine-share-copy {\n flex: 0 0 auto;\n min-width: 74px;\n padding: 7px 12px;\n border: 0;\n border-radius: 7px;\n background: var(--zine-controls-accent, #7dd3fc);\n color: #06202c;\n font: inherit;\n font-weight: 600;\n cursor: pointer;\n}\n\n.zine-share-socials { display: flex; flex-wrap: wrap; gap: 6px; justify-content: center; }\n.zine-share-social {\n display: inline-flex;\n width: 38px;\n height: 38px;\n align-items: center;\n justify-content: center;\n border-radius: 8px;\n background: rgba(255, 255, 255, 0.08);\n color: inherit;\n text-decoration: none;\n}\n.zine-share-social svg { width: 19px; height: 19px; }\n.zine-share-social:hover { background: var(--zine-controls-hover, rgba(255,255,255,0.18)); }\n.zine-share-close:focus-visible,\n.zine-share-copy:focus-visible,\n.zine-share-social:focus-visible,\n.zine-share-link input:focus-visible {\n outline: 2px solid var(--zine-controls-accent, #7dd3fc);\n outline-offset: 2px;\n}\n\n@media (prefers-reduced-motion: no-preference) {\n .zine-controls-btn { transition: background 120ms ease; }\n}\n`;\n\n/** Add the stylesheet to `doc` if it is not already there. */\nexport function ensureStyles(doc: Document): void {\n if (doc.getElementById(STYLE_ID)) return;\n const style = doc.createElement('style');\n style.id = STYLE_ID;\n style.textContent = CSS;\n (doc.head ?? doc.documentElement)?.appendChild(style);\n}\n","/**\n * The rail beside the book that the thumbnail and outline lists both sit in.\n *\n * It exists to solve one problem shared by every such panel: the container's measured box is what\n * the renderer sizes the book from and what pointer hit-testing maps into, so a panel must not\n * live inside it. Instead the book (and its docked toolbar, if any) is wrapped in a flex row with\n * the panel as its sibling, and `destroy` unwinds that again.\n *\n * The rail is absolutely positioned inside a holder that stretches to the book's height, so a\n * long list scrolls internally instead of running past the bottom of the book.\n */\nexport class Sidebar {\n /** The scrolling list; panels append their rows here. */\n readonly root: HTMLElement;\n #holder: HTMLElement;\n #wrap: HTMLElement | null = null;\n\n constructor(\n doc: Document,\n container: HTMLElement,\n options: { className: string; label: string; width: number },\n ) {\n this.#holder = doc.createElement('div');\n this.#holder.className = 'zine-panel-holder';\n this.#holder.style.width = `${options.width}px`;\n\n this.root = doc.createElement('div');\n this.root.className = `zine-panel ${options.className}`;\n this.root.setAttribute('role', 'listbox');\n this.root.setAttribute('aria-label', options.label);\n this.#holder.appendChild(this.root);\n\n // In the overlay fallback the rail sits inside the book, where the book's own gesture\n // handlers would otherwise read a click on a row as a page tap.\n for (const type of ['pointerdown', 'pointerup', 'pointermove', 'click', 'dblclick', 'wheel']) {\n this.root.addEventListener(type, (e) => e.stopPropagation());\n }\n\n this.#place(doc, container);\n }\n\n /** Resize the rail, e.g. once a thumbnail list knows whether it needs one column or two. */\n setWidth(px: number): void {\n this.#holder.style.width = `${px}px`;\n }\n\n #place(doc: Document, container: HTMLElement): void {\n const parent = container.parentNode;\n if (!parent) {\n // Not in a document yet: overlay rather than lose the panel.\n this.#holder.classList.add('zine-panel-overlay');\n container.appendChild(this.#holder);\n return;\n }\n // A docked toolbar already wrapped the book; wrap that whole assembly so the rail sits\n // beside book *and* toolbar rather than between them.\n const existing = container.closest('.zine-controls-wrap');\n const target = (existing ?? container) as HTMLElement;\n const wrap = doc.createElement('div');\n wrap.className = 'zine-panel-wrap';\n target.parentNode!.insertBefore(wrap, target);\n wrap.append(this.#holder, target);\n this.#wrap = wrap;\n }\n\n destroy(): void {\n this.#holder.remove();\n const wrap = this.#wrap;\n if (wrap?.parentNode) {\n // The rail is gone, so what is left is the book; put it back where the wrapper was.\n while (wrap.firstChild) wrap.parentNode.insertBefore(wrap.firstChild, wrap);\n wrap.remove();\n }\n this.#wrap = null;\n }\n}\n","import { Sidebar } from './sidebar';\nimport type { Zine } from '../zine';\n\n/** Width of one page thumbnail, in px. A paired rail fits two of these side by side. */\nconst THUMB_WIDTH = 78;\n/** Padding inside the rail, per side. */\nconst RAIL_PAD = 6;\n/** Gap between the two pages of a spread. */\nconst CELL_GAP = 2;\n\n/**\n * A rail of page thumbnails beside the book.\n *\n * Rows mirror the book's own spread model, so a `double` book shows two pages per row and a\n * `single` book one — including the responsive fallback that forces single-page on a narrow\n * container. A book that mixes the two (`cover`, `book`) keeps two columns so pairs line up, and\n * centres its lone first/last page between them. Clicking a row turns to that spread.\n *\n * Pages are drawn only as they scroll into view: a long PDF would otherwise decode every page at\n * once the moment the rail opened.\n */\nexport class Thumbnails {\n #zine: Zine;\n #doc: Document;\n #bar: Sidebar;\n #rows: { el: HTMLElement; spread: number }[] = [];\n #observer: IntersectionObserver | null = null;\n #unsubscribe: (() => void)[] = [];\n\n constructor(zine: Zine, container: HTMLElement) {\n this.#zine = zine;\n const doc = container.ownerDocument!;\n this.#doc = doc;\n this.#bar = new Sidebar(doc, container, {\n className: 'zine-thumbs',\n label: 'Pages',\n width: THUMB_WIDTH + RAIL_PAD * 2,\n });\n\n this.#build();\n\n const onPage = (): void => this.#markCurrent();\n this.#unsubscribe.push(zine.on('pageChanged', onPage));\n this.#markCurrent();\n }\n\n #build(): void {\n const spreads = this.#zine.getSpreads();\n const rtl = this.#zine.getDirection() === 'rtl';\n // Two columns only if the book actually pairs pages somewhere. A wholly single-page book\n // gets a one-page-wide rail rather than a column of half-empty rows.\n const paired = spreads.some((s) => s.left !== null && s.right !== null);\n this.#bar.root.classList.toggle('zine-thumbs-solo', !paired);\n if (paired) this.#bar.setWidth(THUMB_WIDTH * 2 + CELL_GAP + RAIL_PAD * 2);\n\n for (const [index, spread] of spreads.entries()) {\n const row = this.#doc.createElement('button');\n row.type = 'button';\n row.className = 'zine-thumbs-row';\n row.setAttribute('role', 'option');\n if (rtl) row.style.flexDirection = 'row-reverse';\n\n const pages = [spread.left, spread.right].filter((p): p is number => p !== null);\n // A lone page in a book that pairs elsewhere keeps a single page's width and sits in the\n // middle, rather than stretching across both columns or hugging one side.\n if (paired && pages.length === 1) row.classList.add('zine-thumbs-row-lone');\n\n for (const page of pages) {\n const cell = this.#doc.createElement('span');\n cell.className = 'zine-thumbs-cell';\n cell.dataset.page = String(page);\n row.appendChild(cell);\n }\n\n const labels = [...pages].sort((a, b) => a - b).map((p) => p + 1);\n row.setAttribute(\n 'aria-label',\n labels.length > 1 ? `Pages ${labels[0]}–${labels.at(-1)}` : `Page ${labels[0] ?? ''}`,\n );\n\n const caption = this.#doc.createElement('span');\n caption.className = 'zine-thumbs-caption';\n caption.textContent = labels.join('–');\n row.appendChild(caption);\n\n row.addEventListener('click', () => {\n if (pages.length > 0) this.#zine.flipTo(Math.min(...pages));\n });\n this.#bar.root.appendChild(row);\n this.#rows.push({ el: row, spread: index });\n }\n this.#observeRows();\n }\n\n /** Decode a row's pages the first time it comes into view. */\n #observeRows(): void {\n const cells = [...this.#bar.root.querySelectorAll<HTMLElement>('.zine-thumbs-cell[data-page]')];\n if (typeof IntersectionObserver === 'undefined') {\n for (const cell of cells) void this.#paint(cell);\n return;\n }\n this.#observer = new IntersectionObserver(\n (entries, obs) => {\n for (const entry of entries) {\n if (!entry.isIntersecting) continue;\n obs.unobserve(entry.target);\n void this.#paint(entry.target as HTMLElement);\n }\n },\n { root: this.#bar.root, rootMargin: '200px' },\n );\n for (const cell of cells) this.#observer.observe(cell);\n }\n\n async #paint(cell: HTMLElement): Promise<void> {\n const page = Number(cell.dataset.page);\n const content = await this.#zine.getPageImage(page);\n if (!content || !cell.isConnected) return;\n const w = (content as { width: number }).width;\n const h = (content as { height: number }).height;\n if (!w || !h) return;\n // One page's worth of pixels, whatever the rail's column count, so thumbs stay a consistent\n // size between modes. Scaled by dpr so they are not soft on a retina screen.\n const dpr = Math.min(2, globalThis.devicePixelRatio || 1);\n const canvas = this.#doc.createElement('canvas');\n canvas.width = Math.max(1, Math.round(THUMB_WIDTH * dpr));\n canvas.height = Math.max(1, Math.round(((THUMB_WIDTH * h) / w) * dpr));\n canvas.className = 'zine-thumbs-img';\n const ctx = canvas.getContext('2d');\n if (!ctx) return;\n try {\n ctx.drawImage(content as CanvasImageSource, 0, 0, canvas.width, canvas.height);\n } catch {\n return; // an unusable raster is not worth breaking the rail over\n }\n cell.replaceChildren(canvas);\n }\n\n /** Highlight the spread on screen and keep it scrolled into view. */\n #markCurrent(): void {\n const current = this.#zine.getSpreadIndex();\n for (const { el, spread } of this.#rows) {\n const active = spread === current;\n el.classList.toggle('zine-panel-active', active);\n el.setAttribute('aria-selected', String(active));\n if (active) el.scrollIntoView?.({ block: 'nearest' });\n }\n }\n\n destroy(): void {\n for (const off of this.#unsubscribe) off();\n this.#unsubscribe = [];\n this.#observer?.disconnect();\n this.#observer = null;\n this.#bar.destroy();\n }\n}\n","import { Sidebar } from './sidebar';\nimport type { OutlineItem } from '../source/types';\nimport type { Zine } from '../zine';\n\n/** Rail width in px. Wider than the thumbnail rail because it holds headings, not pictures. */\nconst RAIL_WIDTH = 208;\n/** Indent per nesting level, in px. */\nconst INDENT = 12;\n\n/**\n * The document's table of contents beside the book.\n *\n * One row per heading, nested entries indented under their parent. Clicking a row turns to the\n * page it points at; a heading whose destination could not be resolved is still listed, just not\n * clickable. Unlike the thumbnail rail this is a single column — headings are text, and a second\n * column would only make them narrower.\n */\nexport class Outline {\n #zine: Zine;\n #doc: Document;\n #bar: Sidebar;\n #rows: { el: HTMLElement; page: number }[] = [];\n #unsubscribe: (() => void)[] = [];\n\n constructor(zine: Zine, container: HTMLElement) {\n this.#zine = zine;\n const doc = container.ownerDocument!;\n this.#doc = doc;\n this.#bar = new Sidebar(doc, container, {\n className: 'zine-outline',\n label: 'Outline',\n width: RAIL_WIDTH,\n });\n\n this.#note('Loading…');\n void this.#build();\n\n this.#unsubscribe.push(zine.on('pageChanged', () => this.#markCurrent()));\n }\n\n #note(text: string): void {\n const note = this.#doc.createElement('div');\n note.className = 'zine-panel-note';\n note.textContent = text;\n this.#bar.root.replaceChildren(note);\n }\n\n async #build(): Promise<void> {\n const items = await this.#zine.getOutline();\n if (!this.#bar.root.isConnected) return; // closed while the outline was loading\n if (items.length === 0) {\n // The toolbar hides the control when there is nothing to list, so this is only reachable\n // through a hand-written layout that names 'outline' regardless.\n this.#note('This document has no outline.');\n return;\n }\n this.#bar.root.replaceChildren();\n this.#addLevel(items, 0);\n this.#markCurrent();\n }\n\n #addLevel(items: OutlineItem[], depth: number): void {\n for (const item of items) {\n const row = this.#doc.createElement('button');\n row.type = 'button';\n row.className = 'zine-outline-row';\n row.setAttribute('role', 'option');\n row.style.paddingLeft = `${8 + depth * INDENT}px`;\n row.textContent = item.title;\n row.title = item.title;\n if (item.page === null) {\n // Keep the heading visible but inert: it still tells the reader what is in the document.\n row.disabled = true;\n } else {\n const page = item.page;\n row.setAttribute('aria-label', `${item.title}, page ${page + 1}`);\n row.addEventListener('click', () => this.#zine.flipTo(page));\n this.#rows.push({ el: row, page });\n }\n this.#bar.root.appendChild(row);\n if (item.children.length > 0) this.#addLevel(item.children, depth + 1);\n }\n }\n\n /**\n * Mark the entry the reader is inside — the last one at or before the current page, rather\n * than an exact match, since a section spans many pages and rarely starts on the one shown.\n */\n #markCurrent(): void {\n const current = this.#zine.getPage();\n let best: HTMLElement | null = null;\n let bestPage = -1;\n for (const { el, page } of this.#rows) {\n el.classList.remove('zine-panel-active');\n el.removeAttribute('aria-selected');\n if (page <= current && page >= bestPage) {\n best = el;\n bestPage = page;\n }\n }\n if (!best) return;\n best.classList.add('zine-panel-active');\n best.setAttribute('aria-selected', 'true');\n best.scrollIntoView?.({ block: 'nearest' });\n }\n\n destroy(): void {\n for (const off of this.#unsubscribe) off();\n this.#unsubscribe = [];\n this.#bar.destroy();\n }\n}\n","import { Sidebar } from './sidebar';\nimport type { Zine } from '../zine';\n\n/** Rail width in px. Matches the outline: both hold text, not pictures. */\nconst RAIL_WIDTH = 208;\n/** Wait after the last keystroke before searching, so typing does not scan per character. */\nconst DEBOUNCE_MS = 180;\n/** Shorter queries match too much to be useful. */\nconst MIN_QUERY = 2;\n\n/**\n * Full-text search beside the book: a query field over its results.\n *\n * It lives in the same rail as the thumbnails and outline rather than a popover, because results\n * are an open-ended list — a floating panel over the book would either cover the page being\n * searched or clip the very results it found.\n */\nexport class Search {\n #zine: Zine;\n #doc: Document;\n #bar: Sidebar;\n #input: HTMLInputElement;\n #hits: HTMLElement;\n /** Increments per query so a slow search that resolves late cannot overwrite a newer one. */\n #run = 0;\n #timer: ReturnType<typeof setTimeout> | null = null;\n\n constructor(zine: Zine, container: HTMLElement) {\n this.#zine = zine;\n const doc = container.ownerDocument!;\n this.#doc = doc;\n this.#bar = new Sidebar(doc, container, {\n className: 'zine-search',\n label: 'Search results',\n width: RAIL_WIDTH,\n });\n\n this.#input = doc.createElement('input');\n this.#input.type = 'search';\n this.#input.className = 'zine-search-input';\n this.#input.placeholder = 'Search…';\n this.#input.setAttribute('aria-label', 'Search the document');\n this.#input.addEventListener('input', () => {\n if (this.#timer) clearTimeout(this.#timer);\n this.#timer = setTimeout(() => void this.#search(), DEBOUNCE_MS);\n });\n // Enter searches at once rather than waiting out the debounce.\n this.#input.addEventListener('keydown', (e) => {\n if ((e as KeyboardEvent).key !== 'Enter') return;\n if (this.#timer) clearTimeout(this.#timer);\n void this.#search();\n });\n\n this.#hits = doc.createElement('div');\n this.#hits.className = 'zine-search-hits';\n\n this.#bar.root.append(this.#input, this.#hits);\n this.#input.focus();\n }\n\n #note(text: string): void {\n const note = this.#doc.createElement('div');\n note.className = 'zine-panel-note';\n note.textContent = text;\n this.#hits.replaceChildren(note);\n }\n\n async #search(): Promise<void> {\n const query = this.#input.value.trim();\n const mine = ++this.#run;\n if (query.length < MIN_QUERY) {\n this.#hits.replaceChildren();\n return;\n }\n this.#note('Searching…');\n const results = await this.#zine.search(query);\n if (mine !== this.#run || !this.#bar.root.isConnected) return; // superseded, or closed\n if (results.length === 0) {\n this.#note(`No matches for “${query}”`);\n return;\n }\n this.#hits.replaceChildren(\n ...results.map((hit) => {\n const row = this.#doc.createElement('button');\n row.type = 'button';\n row.className = 'zine-search-hit';\n row.setAttribute('role', 'option');\n row.setAttribute('aria-label', `Page ${hit.page + 1}: ${hit.excerpt}`);\n const label = this.#doc.createElement('span');\n label.className = 'zine-search-page';\n label.textContent = `Page ${hit.page + 1}`;\n const excerpt = this.#doc.createElement('small');\n excerpt.textContent = hit.excerpt;\n row.append(label, excerpt);\n row.addEventListener('click', () => this.#zine.flipTo(hit.page));\n return row;\n }),\n );\n }\n\n destroy(): void {\n if (this.#timer) clearTimeout(this.#timer);\n this.#timer = null;\n this.#run++; // any search still in flight is now stale\n this.#bar.destroy();\n }\n}\n","import { createIcon, ICONS } from './icons';\nimport type { Zine } from '../zine';\n\n/**\n * Big page-turn arrows flanking the book.\n *\n * They sit *beside* the book rather than over it, for the same reason the docked toolbar does:\n * the container's measured box is what the renderer sizes pages from and what pointer\n * hit-testing maps into, so anything inside it would shrink the book and skew every tap. The\n * book (with whatever the toolbar already wrapped around it) goes in a flex row between them.\n *\n * An arrow disables itself at the end of the book rather than disappearing, so the layout does\n * not jump as the reader reaches the covers.\n */\nexport class Arrows {\n #zine: Zine;\n #prev: HTMLButtonElement;\n #next: HTMLButtonElement;\n #wrap: HTMLElement | null = null;\n #unsubscribe: (() => void)[] = [];\n\n constructor(zine: Zine, container: HTMLElement) {\n this.#zine = zine;\n const doc = container.ownerDocument!;\n\n const rtl = zine.getDirection() === 'rtl';\n // The arrows point where the page goes, so in RTL they swap: \"back\" is to the right.\n this.#prev = this.#button(doc, rtl ? ICONS.next : ICONS.prev, 'Previous page', () =>\n zine.flipPrev(),\n );\n this.#next = this.#button(doc, rtl ? ICONS.prev : ICONS.next, 'Next page', () =>\n zine.flipNext(),\n );\n\n this.#place(doc, container);\n\n const refresh = (): void => this.#refresh();\n this.#unsubscribe.push(zine.on('pageChanged', refresh));\n this.#unsubscribe.push(zine.on('flipEnd', refresh));\n this.#refresh();\n }\n\n #button(\n doc: Document,\n icon: string,\n label: string,\n onClick: () => void,\n ): HTMLButtonElement {\n const btn = doc.createElement('button');\n btn.type = 'button';\n btn.className = 'zine-arrow';\n btn.title = label;\n btn.setAttribute('aria-label', label);\n btn.appendChild(createIcon(doc, icon));\n btn.addEventListener('click', onClick);\n // The book's gesture handlers sit on the container; an arrow press is not a page tap.\n for (const type of ['pointerdown', 'pointerup', 'click']) {\n btn.addEventListener(type, (e) => e.stopPropagation());\n }\n return btn;\n }\n\n #place(doc: Document, container: HTMLElement): void {\n // Wrap the outermost thing the library has already built around the book — a docked toolbar\n // or a side panel — so the arrows flank the whole assembly, not just the pages.\n const outer =\n container.closest('.zine-panel-wrap') ??\n container.closest('.zine-controls-wrap') ??\n container;\n const parent = outer.parentNode;\n if (!parent) return; // not in a document; nothing sensible to flank\n const wrap = doc.createElement('div');\n wrap.className = 'zine-arrows-wrap';\n parent.insertBefore(wrap, outer);\n wrap.append(this.#prev, outer, this.#next);\n this.#wrap = wrap;\n }\n\n /**\n * Hide an arrow that has nowhere to go — no back arrow on the first page.\n *\n * Hidden rather than removed so its slot stays reserved: dropping it from the flow would slide\n * the book sideways every time the reader reached a cover. `disabled` comes along for the ride\n * so the button is inert even if a consumer's own CSS makes it visible again.\n */\n #refresh(): void {\n for (const [btn, canTurn] of [\n [this.#prev, this.#zine.canFlipPrev()],\n [this.#next, this.#zine.canFlipNext()],\n ] as const) {\n btn.disabled = !canTurn;\n btn.classList.toggle('zine-arrow-hidden', !canTurn);\n }\n }\n\n destroy(): void {\n for (const off of this.#unsubscribe) off();\n this.#unsubscribe = [];\n this.#prev.remove();\n this.#next.remove();\n const wrap = this.#wrap;\n if (wrap?.parentNode) {\n // The arrows are gone, so what is left is the book; put it back where the wrapper was.\n while (wrap.firstChild) wrap.parentNode.insertBefore(wrap.firstChild, wrap);\n wrap.remove();\n }\n this.#wrap = null;\n }\n}\n","import { createIcon, ICONS } from './icons';\nimport { DEFAULT_ITEMS, defineControl, resolveControl } from './registry';\nimport { registerBuiltins } from './builtins';\nimport { ensureStyles } from './styles';\nimport { Thumbnails } from './thumbnails';\nimport { Outline } from './outline';\nimport { Search } from './search';\nimport { Arrows } from './arrows';\n\n/** The side panels, all of which share the one rail beside the book. */\nconst PANELS = { thumbnails: Thumbnails, outline: Outline, search: Search };\ntype PanelKind = keyof typeof PANELS;\n/** What every panel has in common: build itself on construction, and clean up after itself. */\ntype Panel = InstanceType<(typeof PANELS)[PanelKind]>;\nimport type {\n ControlContext,\n ControlDef,\n ControlItem,\n ControlsOptions,\n ControlsPosition,\n} from './types';\nimport type { Zine } from '../zine';\n\n/**\n * Events the container listens to for flipping, zooming and dragging. The gesture layer binds\n * these on the container and never checks `event.target`, so anything the toolbar handles has to\n * be stopped here or a button press would also register as a page tap.\n */\nconst SWALLOWED = ['pointerdown', 'pointerup', 'pointermove', 'click', 'dblclick', 'wheel', 'keydown'];\n\ninterface Popover {\n el: HTMLElement;\n trigger: HTMLElement;\n}\n\nexport class Toolbar {\n #zine: Zine;\n #doc: Document;\n #root: HTMLElement;\n #bar: HTMLElement;\n /** Every control on screen, buttons and `render` widgets alike, so #refresh can reach them. */\n #buttons: { el: HTMLElement; def: ControlDef }[] = [];\n #popover: Popover | null = null;\n #unsubscribe: (() => void)[] = [];\n #pageInput: HTMLInputElement | null = null;\n /** The flex wrapper docked mode inserts around the container; unwound on destroy. */\n #wrap: HTMLElement | null = null;\n #container: HTMLElement;\n /** The side panel currently in the rail. Only one at a time — they share the space. */\n #panel: Panel | null = null;\n #panelKind: PanelKind | null = null;\n /** Whether the document turned out to have any outline entries. Null until known: the answer\n * is async, and the outline control stays hidden rather than flash in and out. */\n #hasOutline: boolean | null = null;\n #arrows: Arrows | null = null;\n\n constructor(zine: Zine, container: HTMLElement, options: ControlsOptions) {\n this.#zine = zine;\n this.#container = container;\n const doc = container.ownerDocument!;\n this.#doc = doc;\n ensureStyles(doc);\n\n const position = options.position ?? 'bottom';\n const docked = options.docked ?? true;\n this.#root = doc.createElement('div');\n this.#root.className = [\n 'zine-controls',\n `zine-controls-${position}`,\n docked ? 'zine-controls-docked' : 'zine-controls-floating',\n options.className,\n ]\n .filter(Boolean)\n .join(' ');\n this.#root.setAttribute('role', 'toolbar');\n this.#root.setAttribute('aria-label', 'Flipbook controls');\n\n this.#bar = doc.createElement('div');\n this.#bar.className = 'zine-controls-bar';\n this.#root.appendChild(this.#bar);\n\n // Toolbar keys are handled first, then every listed event is stopped so none of it reaches\n // the book's gesture, zoom or keyboard handlers on the container.\n this.#root.addEventListener('keydown', (e) => this.#onKeyDown(e as KeyboardEvent));\n for (const event of SWALLOWED) {\n this.#root.addEventListener(event, (e) => this.#isolate(e));\n }\n this.#place(container, position, docked);\n\n const refresh = (): void => this.#refresh();\n this.#unsubscribe.push(zine.on('pageChanged', refresh));\n this.#unsubscribe.push(zine.on('zoomChanged', refresh));\n this.#unsubscribe.push(zine.on('flipEnd', refresh));\n const onDocPointer = (e: Event): void => {\n if (this.#popover && !this.#popover.el.contains(e.target as Node)) this.#closePopover();\n };\n doc.addEventListener('pointerdown', onDocPointer, true);\n this.#unsubscribe.push(() => doc.removeEventListener('pointerdown', onDocPointer, true));\n }\n\n /**\n * Put the toolbar in the page.\n *\n * Floating is simple: a child of the container, absolutely positioned over the book.\n *\n * Docked has to sit *outside* the container, because the container's measured box is what the\n * renderer sizes the book from and what pointer hit-testing maps into — a bar inside it would\n * shrink the book and skew every tap. So the container is wrapped in a flex column (or row),\n * with the toolbar as its sibling. The wrapper inherits the container's own layout box so the\n * arrangement the consumer's CSS set up is preserved.\n */\n #place(container: HTMLElement, position: ControlsPosition, docked: boolean): void {\n if (!docked) {\n container.appendChild(this.#root);\n return;\n }\n const parent = container.parentNode;\n if (!parent) {\n // Not in a document yet: fall back to overlaying rather than losing the toolbar.\n this.#root.classList.replace('zine-controls-docked', 'zine-controls-floating');\n container.appendChild(this.#root);\n return;\n }\n const wrap = this.#doc.createElement('div');\n wrap.className = `zine-controls-wrap zine-controls-wrap-${position}`;\n parent.insertBefore(wrap, container);\n wrap.appendChild(container);\n // 'top'/'left' put the bar first; flex-direction (set in CSS) handles the axis.\n if (position === 'top' || position === 'left') wrap.insertBefore(this.#root, container);\n else wrap.appendChild(this.#root);\n this.#wrap = wrap;\n }\n\n /** Build the layout. Separate from construction so instance-bound widgets (the page field, the\n * search panel) can be registered against this toolbar first. */\n mount(options: ControlsOptions): void {\n this.#build(options.items ?? DEFAULT_ITEMS);\n // After #place, so the arrows can wrap whatever it built around the book.\n if (options.arrows ?? true) this.#arrows = new Arrows(this.#zine, this.#container);\n this.#refresh();\n this.#probeOutline();\n }\n\n destroy(): void {\n for (const off of this.#unsubscribe) off();\n this.#unsubscribe = [];\n this.#closePopover();\n this.#panel?.destroy();\n this.#panel = null;\n this.#panelKind = null;\n this.#root.remove();\n // Unwrap from the inside out: the arrows enclose the toolbar's wrapper, so removing theirs\n // first would leave this one orphaned outside the document.\n const wrap = this.#wrap;\n if (wrap?.parentNode) {\n wrap.parentNode.insertBefore(wrap.firstChild!, wrap);\n wrap.remove();\n }\n this.#wrap = null;\n this.#arrows?.destroy();\n this.#arrows = null;\n }\n\n /** Keep toolbar interaction from reaching the book's own gesture/zoom/keyboard handlers. */\n #isolate(event: Event): void {\n event.stopPropagation();\n }\n\n #context(close: () => void = () => this.#closePopover()): ControlContext {\n return { zine: this.#zine, close };\n }\n\n #build(items: readonly ControlItem[]): void {\n for (const item of items) {\n if (item === '|') {\n const sep = this.#doc.createElement('div');\n sep.className = 'zine-controls-sep';\n this.#bar.appendChild(sep);\n continue;\n }\n const def = resolveControl(item);\n let el: HTMLElement;\n if (def.render) {\n el = def.render(this.#context());\n // Registered like any button so its predicates are re-read on every change; #button\n // does this for the controls it builds.\n this.#buttons.push({ el, def });\n } else {\n el = this.#button(def, 'zine-controls-btn');\n }\n this.#bar.appendChild(el);\n }\n }\n\n /** A control button. Bar buttons are icon-only with the title as tooltip; menu items and any\n * control without an icon also carry a visible label. */\n /** A control's label, which may be a function of the current state. */\n #titleOf(def: ControlDef): string {\n return typeof def.title === 'function' ? def.title(this.#context()) : def.title;\n }\n\n /** A control's glyph, which may likewise depend on state (an RTL mirror, say). */\n #iconOf(def: ControlDef): string | undefined {\n return typeof def.icon === 'function' ? def.icon(this.#context()) : def.icon;\n }\n\n #button(def: ControlDef, className: string, withLabel = false): HTMLButtonElement {\n const btn = this.#doc.createElement('button');\n const title = this.#titleOf(def);\n const icon = this.#iconOf(def);\n btn.type = 'button';\n btn.className = className;\n btn.title = title;\n btn.setAttribute('aria-label', title);\n if (icon) btn.appendChild(createIcon(this.#doc, icon));\n if (withLabel || !icon) {\n const label = this.#doc.createElement('span');\n label.className = 'zine-controls-label';\n label.textContent = title;\n btn.appendChild(label);\n }\n btn.addEventListener('click', () => this.#activate(def, btn));\n this.#buttons.push({ el: btn, def });\n return btn;\n }\n\n #activate(def: ControlDef, trigger: HTMLButtonElement): void {\n if (def.isDisabled?.(this.#context())) return;\n // A submenu toggles its popover; a second press on the same trigger closes it.\n if (def.children) {\n if (this.#popover?.trigger === trigger) this.#closePopover();\n else this.#openMenu(def, trigger);\n return;\n }\n def.action?.(this.#context());\n this.#refresh();\n }\n\n #openMenu(def: ControlDef, trigger: HTMLButtonElement): void {\n this.#closePopover();\n const menu = this.#doc.createElement('div');\n menu.className = 'zine-controls-menu';\n menu.setAttribute('role', 'menu');\n const ctx = this.#context();\n for (const child of def.children ?? []) {\n if (child === '|') continue;\n const childDef = resolveControl(child);\n if (childDef.isVisible && !childDef.isVisible(ctx)) continue;\n let item: HTMLElement;\n if (childDef.render) {\n item = childDef.render(this.#context());\n this.#buttons.push({ el: item, def: childDef });\n } else {\n item = this.#button(childDef, 'zine-controls-btn', true);\n }\n item.setAttribute('role', 'menuitem');\n menu.appendChild(item);\n }\n this.#showPopover(menu, trigger);\n // The entries were only just built, so nothing has evaluated their state yet: without this\n // a menu opens with every entry enabled until the next page turn happens to refresh it.\n this.#refresh();\n menu.querySelector('button')?.focus();\n }\n\n #showPopover(el: HTMLElement, trigger: HTMLElement): void {\n this.#root.appendChild(el);\n this.#popover = { el, trigger };\n trigger.setAttribute('aria-expanded', 'true');\n this.#placePopover(el, trigger);\n }\n\n /** Anchor a popover to its trigger, flipped to stay inside the book. */\n #placePopover(el: HTMLElement, trigger: HTMLElement): void {\n const root = this.#root.getBoundingClientRect();\n const anchor = trigger.getBoundingClientRect();\n const box = el.getBoundingClientRect();\n if (!root.width || !box.width) return; // not laid out (e.g. jsdom): leave to CSS\n let left = anchor.left - root.left + anchor.width / 2 - box.width / 2;\n left = Math.max(4, Math.min(left, root.width - box.width - 4));\n el.style.left = `${left}px`;\n // Prefer opening away from the edge the toolbar sits on.\n const below = anchor.bottom - root.top + 6;\n const above = anchor.top - root.top - box.height - 6;\n el.style.top = `${above >= 0 ? above : below}px`;\n }\n\n #closePopover(): void {\n if (!this.#popover) return;\n const { el, trigger } = this.#popover;\n this.#popover = null;\n trigger.removeAttribute('aria-expanded');\n // Drop buttons that belonged to the popover so #refresh stops touching detached nodes.\n this.#buttons = this.#buttons.filter((b) => !el.contains(b.el));\n el.remove();\n if (this.#doc.activeElement && el.contains(this.#doc.activeElement)) trigger.focus();\n }\n\n /** Arrow keys move between controls; Escape dismisses an open popover. */\n #onKeyDown(event: KeyboardEvent): void {\n if (event.key === 'Escape' && this.#popover) {\n const { trigger } = this.#popover;\n this.#closePopover();\n trigger.focus();\n event.preventDefault();\n return;\n }\n const focusables = [...this.#root.querySelectorAll<HTMLElement>('button, input')];\n const at = focusables.indexOf(this.#doc.activeElement as HTMLElement);\n if (at < 0) return;\n // Let the page-number field use its own arrows for text editing.\n if (this.#doc.activeElement instanceof HTMLInputElement) return;\n const step = event.key === 'ArrowRight' || event.key === 'ArrowDown' ? 1 : event.key === 'ArrowLeft' || event.key === 'ArrowUp' ? -1 : 0;\n if (step === 0) return;\n const next = focusables[(at + step + focusables.length) % focusables.length];\n next?.focus();\n event.preventDefault();\n }\n\n /**\n * Re-read every control's state after the book changes.\n *\n * Applies to custom widgets built with `render` as well as to plain buttons: the predicates\n * are on `ControlDef`, so honouring them only for button-shaped controls would make the same\n * field mean different things depending on how a control chose to draw itself. A widget may be\n * any element, so each piece of state is applied in whatever way that element supports.\n */\n #refresh(): void {\n const ctx = this.#context();\n for (const { el, def } of this.#buttons) {\n // Does not apply to this book at all: take the space back, it is not coming again.\n const applies = def.children ? this.#hasVisibleChildren(def, ctx) : def.isVisible?.(ctx);\n if (applies !== undefined) el.style.display = applies ? '' : 'none';\n\n const disabled = def.isDisabled?.(ctx) ?? false;\n // A wrapper element cannot be disabled, so mark it and disable the fields inside.\n for (const field of this.#formFields(el)) field.disabled = disabled;\n if (!this.#formFields(el).length) el.setAttribute('aria-disabled', String(disabled));\n el.classList.toggle('zine-controls-off', disabled);\n\n if (def.isActive) el.setAttribute('aria-pressed', String(def.isActive(ctx)));\n if (typeof def.title === 'function') {\n const title = def.title(ctx);\n el.title = title;\n el.setAttribute('aria-label', title);\n const label = el.querySelector('.zine-controls-label');\n if (label) label.textContent = title;\n }\n if (typeof def.icon === 'function') {\n el.querySelector('svg')?.replaceWith(createIcon(this.#doc, def.icon(ctx)));\n }\n }\n if (this.#pageInput && this.#doc.activeElement !== this.#pageInput) {\n this.#pageInput.value = String(this.#zine.getPage() + 1);\n }\n }\n\n /** The element itself if it can be disabled, else any inputs/buttons it wraps. */\n #formFields(el: HTMLElement): (HTMLButtonElement | HTMLInputElement)[] {\n if (el instanceof HTMLButtonElement || el instanceof HTMLInputElement) return [el];\n return [...el.querySelectorAll<HTMLButtonElement | HTMLInputElement>('button, input')];\n }\n\n /** A submenu is only worth showing if something inside it is. Keeps the overflow button from\n * opening onto nothing when every entry has hidden itself. */\n #hasVisibleChildren(def: ControlDef, ctx: ControlContext): boolean {\n if (def.isVisible && !def.isVisible(ctx)) return false;\n return (def.children ?? []).some((child) => {\n if (child === '|') return false;\n const childDef = resolveControl(child);\n return childDef.isVisible ? childDef.isVisible(ctx) : true;\n });\n }\n\n /** Registered lazily by {@link registerWidgets} so the widget can reach this instance. */\n makePageInput(): HTMLElement {\n const wrap = this.#doc.createElement('div');\n wrap.className = 'zine-controls-page';\n const input = this.#doc.createElement('input');\n input.type = 'number';\n input.min = '1';\n input.max = String(this.#zine.getPageCount());\n input.value = String(this.#zine.getPage() + 1);\n input.setAttribute('aria-label', 'Page number');\n const total = this.#doc.createElement('span');\n total.textContent = `/ ${this.#zine.getPageCount()}`;\n\n const commit = (): void => {\n const n = Number(input.value);\n if (Number.isFinite(n)) this.#zine.flipTo(Math.round(n) - 1);\n input.value = String(this.#zine.getPage() + 1);\n };\n input.addEventListener('keydown', (e) => {\n if (e.key === 'Enter') {\n commit();\n input.blur();\n }\n });\n input.addEventListener('blur', commit);\n wrap.append(input, total);\n this.#pageInput = input;\n return wrap;\n }\n\n /** Which side panel is showing, if any. */\n openPanel(): PanelKind | null {\n return this.#panelKind;\n }\n\n /**\n * Whether this document has a table of contents worth offering.\n *\n * Many PDFs have none, and a control that can only report its own emptiness is a dead end, so\n * the outline button stays hidden until the outline is known to be non-empty. The first call\n * kicks off the lookup and refreshes the toolbar when it lands; `Zine.getOutline` memoizes, so\n * the panel does not pay for it twice.\n */\n hasOutline(): boolean {\n return this.#hasOutline === true;\n }\n\n /** Ask the document whether it has an outline, and refresh once the answer lands. Started as\n * the toolbar mounts so the button settles into place immediately rather than on first use. */\n #probeOutline(): void {\n if (this.#hasOutline !== null || !this.#zine.canOutline()) return;\n this.#hasOutline = false; // assume not, until we hear otherwise\n void this.#zine.getOutline().then((items) => {\n if (items.length === 0) return;\n this.#hasOutline = true;\n this.#refresh();\n // The menu may already be open with the entry missing; rebuild it so it appears.\n const popover = this.#popover;\n if (popover) {\n const def = this.#buttons.find((b) => b.el === popover.trigger)?.def;\n this.#closePopover();\n if (def) this.#openMenu(def, popover.trigger as HTMLButtonElement);\n }\n });\n }\n\n /**\n * Show one of the side panels, or close it if it is already up. They share the rail beside the\n * book, so opening one closes the others. Rebuilt each time, so the thumbnail rail always\n * matches the current spread grouping (which `spreadMode` and the responsive fallback change).\n */\n togglePanel(kind: PanelKind): void {\n const wasOpen = this.#panelKind;\n this.#panel?.destroy();\n this.#panel = null;\n this.#panelKind = null;\n if (wasOpen !== kind) {\n this.#panel = new PANELS[kind](this.#zine, this.#container);\n this.#panelKind = kind;\n }\n this.#refresh();\n }\n\n}\n\n/**\n * Controls that need the toolbar itself (a DOM widget, or a panel to open) are registered per\n * instance, since the registry is module-level and shared.\n */\nexport function registerWidgets(toolbar: Toolbar): void {\n registerBuiltins();\n defineControl({\n id: 'thumbnails',\n title: () => (toolbar.openPanel() === 'thumbnails' ? 'Hide thumbnails' : 'Show thumbnails'),\n icon: ICONS.thumbnails,\n // Documents only, for now: an image book is already a short, flat list of pictures.\n isVisible: (ctx) => ctx.zine.isDocument(),\n isActive: () => toolbar.openPanel() === 'thumbnails',\n action: (ctx) => {\n toolbar.togglePanel('thumbnails');\n ctx.close();\n },\n });\n defineControl({\n id: 'outline',\n title: () => (toolbar.openPanel() === 'outline' ? 'Hide outline' : 'Show outline'),\n icon: ICONS.outline,\n // Only when the document actually has entries to show.\n isVisible: () => toolbar.hasOutline(),\n isActive: () => toolbar.openPanel() === 'outline',\n action: (ctx) => {\n toolbar.togglePanel('outline');\n ctx.close();\n },\n });\n defineControl({\n id: 'pageInput',\n title: 'Page',\n render: () => toolbar.makePageInput(),\n });\n defineControl({\n id: 'search',\n title: () => (toolbar.openPanel() === 'search' ? 'Hide search' : 'Search'),\n icon: ICONS.search,\n isVisible: (ctx) => ctx.zine.canSearch(),\n isActive: () => toolbar.openPanel() === 'search',\n action: () => toolbar.togglePanel('search'),\n });\n}\n","import { registerWidgets, Toolbar } from './toolbar';\nimport type { ControlsOptions } from './types';\nimport type { Zine } from '../zine';\n\nexport { defineControl, getControl, DEFAULT_ITEMS } from './registry';\nexport { ICONS, createIcon } from './icons';\nexport type {\n ControlContext,\n ControlDef,\n ControlItem,\n ControlsOptions,\n ControlsPosition,\n} from './types';\n\n/**\n * Build the toolbar inside `container` and return its teardown.\n *\n * This module is the lazy chunk `zine.ts` reaches through a dynamic `import()`, so a book built\n * with `controls: false` never downloads the toolbar, its icons or its stylesheet. The file is\n * named `controls.ts` rather than `index.ts` so the emitted chunk is `controls-<hash>.js`, which\n * is what the size-limit budget watches.\n */\nexport function mountControls(\n zine: Zine,\n container: HTMLElement,\n options: ControlsOptions = {},\n): () => void {\n const toolbar = new Toolbar(zine, container, options);\n // Built-ins and the instance-bound widgets have to exist before the layout resolves ids.\n registerWidgets(toolbar);\n toolbar.mount(options);\n return () => toolbar.destroy();\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 {\n bindDeepLink,\n claimHash,\n hashWithPage,\n pageFromHash,\n releaseHash,\n type DeepLinkHandle,\n} from './engine/deeplink';\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 { DownloadInfo, OutlineItem, Source } from './source/types';\nimport { planTiles, sameTile, ZoomOverlay, type TilePage } from './engine/zoomTile';\nimport { composeSource } from './source/compose';\nimport type { ControlsOptions } from './controls/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\n/** A lone page fills the container, so it sweeps the full width where a spread leaf only covers\n * its half — and it dissolves instead of landing on a facing page. Stretch duration so the\n * peel and fade read at a comparable pace to a spread turn rather than whipping away. */\nconst LONE_PAGE_FLIP_SCALE = 1.55;\n\n/** Characters of surrounding text shown on either side of a search match. */\nconst EXCERPT_PAD = 32;\n\n/** Quiet period before re-rendering the zoomed region, so a pinch or pan does not rasterize\n * on every frame. Long enough to coalesce a gesture, short enough to feel immediate on release. */\nconst ZOOM_TILE_DELAY = 120;\n\n/** One page that matched a {@link Zine.search} query. */\nexport interface SearchHit {\n /** Zero-based page index; pass straight to `flipTo`. */\n page: number;\n /** The match with a little text either side, ellipsised where it was cut. */\n excerpt: string;\n}\n\n/** Pull a readable snippet around a match, collapsing the whitespace PDFs are full of. */\nfunction excerptAround(text: string, at: number, length: number): string {\n const start = Math.max(0, at - EXCERPT_PAD);\n const end = Math.min(text.length, at + length + EXCERPT_PAD);\n const slice = text.slice(start, end).replace(/\\s+/g, ' ').trim();\n return `${start > 0 ? '…' : ''}${slice}${end < text.length ? '…' : ''}`;\n}\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' | 'cone' | 'leaf' | 'flick' | 'silk' | 'simple'. Default 'cone'. */\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 * Whether a narrow container may override `spreadMode` and show one page at a time. Default\n * true.\n *\n * Set false to hold the configured mode at every width — a two-page spread stays two pages on\n * a phone, however small. (`singlePageThreshold: 0` has the same effect; this says it out\n * loud, and can be changed at runtime with {@link Zine.setResponsiveSpread}.)\n */\n responsiveSpread?: boolean;\n /**\n * The built-in toolbar. Shown by default; pass `false` to render none, or an object to choose\n * its position and which controls appear.\n */\n controls?: boolean | ControlsOptions;\n /**\n * Keep the current page in the URL hash (`#page=12`), so a link opens where the reader was and\n * back/forward move through the book. Default true.\n *\n * Only a `page` key is read or written — anything else in the hash is left alone — and updates\n * use `replaceState`, so turning pages does not fill the back button. Pass `false` if your app\n * owns the hash.\n */\n deepLink?: boolean;\n /**\n * Suppress the browser's right-click menu over the book. Default false.\n *\n * A mild deterrent for published documents, not protection: the pages are still in the DOM and\n * reachable by anyone who wants them. It also takes away Inspect and \"Open image in new tab\"\n * for everyone, so it is off unless asked for.\n */\n disableContextMenu?: boolean;\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 /** The mode the book was built with, so toggling away from one page can return to it — a\n * `cover` book comes back as `cover`, keeping its lone first page, not as plain `double`. */\n #configuredMode: 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 /** Last layout announced via `spreadChanged`, so a rebuild that changes nothing stays quiet. */\n #effectiveModeShown: SpreadMode | null = null;\n #narrow = false; // responsive: container currently below singlePageThreshold\n #responsiveSpread: boolean;\n #lastAspect = ''; // last container aspect-ratio written (avoids redundant style writes)\n #startPageOption: number | undefined;\n #deepLinkEnabled: boolean;\n #disableContextMenu: boolean;\n #deepLink: DeepLinkHandle | null = null;\n #unsubscribeDeepLink: (() => void) | null = null;\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 // Latest flip intent requested while one was already animating; replayed on settle so\n // clicks/keys during a turn aren't dropped and continuous flipping keeps advancing.\n #queuedFlip: (() => void) | null = null;\n // The fold animation currently on screen, so a new flip request can land it instantly\n // (snap to its end pose + commit) and start immediately instead of waiting it out.\n #activeAnim: { toT: number; direction: FlipDirection; onDone: () => void } | null = null;\n // Bumped per flip so an async #runFlip that resumes after being superseded can bail.\n #flipGeneration = 0;\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 #unbindContextMenu: (() => void) | null = null;\n #unbindDblClick: (() => void) | null = null;\n #a11yCleanup: (() => void) | null = null;\n /** Resolved once and reused; see {@link getOutline}. */\n #outline: Promise<OutlineItem[]> | null = null;\n /** Pages whose content improved while a flip was running, to repaint once it settles. */\n #pendingUpgrades = new Set<number>();\n #controlsOption: boolean | ControlsOptions;\n #controlsCleanup: (() => void) | null = null;\n /** Crisp re-renders of the visible region while zoomed in; null until the reader zooms. */\n #zoomOverlay: ZoomOverlay | null = null;\n /** Guards against an out-of-date tile landing after the view has already moved on. */\n #tileGeneration = 0;\n #tileTimer: ReturnType<typeof setTimeout> | 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 // Set before the spread model is built: that is where a page in the URL is honoured.\n // Claimed before the spread model is built, which is where the hash is read: a second book\n // on the same page must not open on the first one's page.\n this.#deepLinkEnabled = (options.deepLink ?? true) && claimHash();\n this.#disableContextMenu = options.disableContextMenu ?? false;\n this.#spreadMode = options.spreadMode ?? 'cover';\n this.#configuredMode = this.#spreadMode;\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.#responsiveSpread = options.responsiveSpread ?? true;\n this.#controlsOption = options.controls ?? true;\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 /** The element this flipbook was mounted into. */\n get container(): HTMLElement {\n return this.#container;\n }\n\n /**\n * How pages are currently grouped, one entry per spread — the same model the renderer paints,\n * so it already reflects `spreadMode` and the responsive single-page fallback. Useful for\n * building a page list or thumbnail rail that matches the book.\n */\n getSpreads(): readonly Spread[] {\n return this.#spreads;\n }\n\n /** The spread index currently on screen; indexes into {@link getSpreads}. */\n getSpreadIndex(): number {\n return this.#current;\n }\n\n /** Reading direction, which mirrors each spread's left/right sides. */\n getDirection(): Direction {\n return this.#direction;\n }\n\n /** How pages are grouped: the configured mode, not what a narrow container may be forcing. */\n getSpreadMode(): SpreadMode {\n return this.#spreadMode;\n }\n\n /** Whether the book is showing one page at a time, for whatever reason. */\n isSinglePage(): boolean {\n return this.#singlePage;\n }\n\n /**\n * Regroup the pages, keeping the reader on the page they are looking at.\n *\n * A narrow container may still override this with one page at a time; see\n * {@link setResponsiveSpread}.\n */\n setSpreadMode(mode: SpreadMode): void {\n if (mode === this.#spreadMode) return;\n this.#spreadMode = mode;\n // The narrow measurement was taken under the layout we are leaving, and a book showing one\n // page is narrower than the same book showing two. Holding on to it would let a container\n // that only shrank *because* of one-page mode veto the way back out. Drop it and let the\n // next measurement decide afresh.\n this.#narrow = false;\n this.#rebuildSpreads();\n void this.#renderCurrent();\n }\n\n /**\n * Switch between one page and two, and back again.\n *\n * Returning to two pages restores the mode the book was built with, so a `cover` book gets its\n * lone first page back rather than becoming a plain `double`.\n */\n toggleSpreadMode(): void {\n this.setSpreadMode(\n this.#spreadMode === 'single'\n ? this.#configuredMode === 'single'\n ? 'double' // built as single: there is no other mode to return to\n : this.#configuredMode\n : 'single',\n );\n }\n\n /** Whether a narrow container is allowed to override `spreadMode` with one page at a time. */\n getResponsiveSpread(): boolean {\n return this.#responsiveSpread;\n }\n\n /**\n * Whether the book is showing one page at a time *because the container is narrow*, rather\n * than because it was asked to. False when `responsiveSpread` is off.\n *\n * A book already set to `single` is not being overridden, however narrow it is: asking for one\n * page makes the book itself narrower, so reporting that as an override would strand the reader\n * in a layout they could no longer switch out of.\n */\n isResponsiveSingle(): boolean {\n return this.#narrow && this.#spreadMode !== 'single';\n }\n\n /**\n * Allow or forbid the narrow-container override, and re-lay out at once.\n *\n * Turning it off holds the configured `spreadMode` at every width; turning it back on\n * re-measures, so a book on a narrow screen collapses to single again straight away.\n */\n setResponsiveSpread(enabled: boolean): void {\n if (enabled === this.#responsiveSpread) return;\n this.#responsiveSpread = enabled;\n if (!enabled) {\n if (!this.#narrow) return; // nothing was being overridden\n this.#narrow = false;\n this.#rebuildSpreads();\n } else {\n const width = this.#renderer?.measure().containerWidth;\n if (width === undefined) return;\n this.#narrow = false; // let #applySinglePage see a real change and rebuild\n this.#applySinglePage(width);\n }\n void this.#renderCurrent();\n }\n\n /**\n * Resolve one page's raster, for drawing a thumbnail or exporting. Returns null if the page\n * cannot be decoded — the failure is reported through `sourceError` rather than thrown, as it\n * is for the pages the renderer paints.\n */\n getPageImage(index: number): Promise<PageContent | null> {\n return this.#getPage(index);\n }\n\n /** Whether there is a spread after the current one (false on the last). */\n canFlipNext(): boolean {\n return this.#current + 1 < this.#spreads.length;\n }\n\n /** Whether there is a spread before the current one (false on the first). */\n canFlipPrev(): boolean {\n return this.#current > 0;\n }\n\n /** The ceiling `setZoom` clamps to. */\n getMaxZoom(): number {\n return this.#maxZoom;\n }\n\n /** Whether this book's source can produce text — false for image books. */\n canSearch(): boolean {\n return typeof this.#source.getText === 'function';\n }\n\n /** Whether the original document can be downloaded — true for a PDF from a URL or bytes. */\n canDownload(): boolean {\n return typeof this.#source.getDownload === 'function';\n }\n\n /**\n * Whether the book is a document rather than a set of loose images — true for a PDF, false for\n * an `ImageSource`. Document-shaped features (the page rail, the outline) key off this.\n *\n * Inferred from the source implementing document-only capabilities, so a custom source opts in\n * simply by implementing them.\n */\n isDocument(): boolean {\n return typeof this.#source.getOutline === 'function' || typeof this.#source.getText === 'function';\n }\n\n /** Whether this book can be printed — true when the source has an original document. */\n canPrint(): boolean {\n return typeof this.#source.getDownload === 'function';\n }\n\n /**\n * Print the document.\n *\n * The original file is handed to the browser in an offscreen frame rather than printing the\n * host page: printing the page would capture the toolbar and whatever single spread happens to\n * be on screen, while the browser paginates a PDF properly on its own. Resolves false when\n * there is no original to print — an image book, or a caller-owned pdf.js document.\n */\n async print(): Promise<boolean> {\n const info = await this.getSourceFile();\n const doc = this.#container.ownerDocument;\n if (!info || !doc) return false;\n\n const frame = doc.createElement('iframe');\n // Offscreen rather than display:none: a hidden frame does not always lay out its document,\n // and an unlaid-out frame has nothing to print.\n frame.style.cssText =\n 'position:fixed;right:0;bottom:0;width:1px;height:1px;opacity:0;border:0;';\n frame.setAttribute('aria-hidden', 'true');\n frame.src = info.url;\n\n return new Promise<boolean>((resolve) => {\n let settled = false;\n const finish = (ok: boolean): void => {\n if (settled) return;\n settled = true;\n // Outlive the print dialog, which is modal and synchronous in some browsers; removing\n // the frame while it is open cancels the job.\n setTimeout(() => {\n frame.remove();\n if (info.revoke) URL.revokeObjectURL(info.url);\n }, 60_000);\n resolve(ok);\n };\n frame.addEventListener('load', () => {\n try {\n const win = frame.contentWindow;\n if (!win) return finish(false);\n win.focus();\n win.print();\n finish(true);\n } catch {\n finish(false); // a cross-origin PDF cannot be driven from here\n }\n });\n frame.addEventListener('error', () => finish(false));\n doc.body.appendChild(frame);\n });\n }\n\n /** Whether the source can supply a table of contents. True for PDFs; the document may still\n * turn out to have no outline, in which case {@link getOutline} resolves empty. */\n canOutline(): boolean {\n return typeof this.#source.getOutline === 'function';\n }\n\n /**\n * The document's table of contents, or an empty list when it has none.\n *\n * Memoized: an outline does not change for the life of the document, and resolving one means\n * following every entry's destination to a page. The toolbar asks for it up front to decide\n * whether to offer the outline panel at all, and the panel itself then gets it for free.\n */\n getOutline(): Promise<OutlineItem[]> {\n if (!this.#outline) {\n const getOutline = this.#source.getOutline;\n this.#outline =\n typeof getOutline === 'function'\n ? Promise.resolve(getOutline.call(this.#source)).catch(() => [])\n : Promise.resolve([]);\n }\n return this.#outline;\n }\n\n /**\n * Save the original document. Resolves to false when the source has nothing to hand over\n * (an image book, or a PDF opened from a caller-owned pdf.js document).\n */\n /**\n * Where the original document lives, if the source has one — a PDF's URL or a blob of its\n * bytes. Null for an image book, or a PDF opened from a caller-owned pdf.js document.\n *\n * Saving and printing both start here: the original is better than anything reassembled from\n * page rasters, and the browser already knows how to paginate it.\n */\n async getSourceFile(): Promise<DownloadInfo | null> {\n const getDownload = this.#source.getDownload;\n if (typeof getDownload !== 'function') return null;\n return (await getDownload.call(this.#source)) ?? null;\n }\n\n async download(): Promise<boolean> {\n const info = await this.getSourceFile();\n if (!info) return false;\n const doc = this.#container.ownerDocument;\n if (!doc) return false;\n const link = doc.createElement('a');\n link.href = info.url;\n link.download = info.filename;\n link.rel = 'noopener';\n doc.body.appendChild(link);\n link.click();\n link.remove();\n // An object URL is ours to clean up; give the click a tick to start first.\n if (info.revoke) setTimeout(() => URL.revokeObjectURL(info.url), 10_000);\n return true;\n }\n\n /**\n * Find `query` in the book's text, case-insensitively.\n *\n * Pages are read on demand and cached by the source, so the first search over a long document\n * costs one text extraction per page and later ones are cheap. Returns at most one hit per\n * page, in page order. Always empty when {@link canSearch} is false.\n */\n async search(query: string, options: { limit?: number } = {}): Promise<SearchHit[]> {\n const getText = this.#source.getText;\n const needle = query.trim().toLowerCase();\n if (typeof getText !== 'function' || needle === '') return [];\n const limit = options.limit ?? 50;\n const hits: SearchHit[] = [];\n for (let page = 0; page < this.#source.pageCount && hits.length < limit; page++) {\n let text: string;\n try {\n text = await getText.call(this.#source, page);\n } catch (error) {\n this.#emitter.emit('sourceError', { index: page, error });\n continue;\n }\n const at = text.toLowerCase().indexOf(needle);\n if (at < 0) continue;\n hits.push({ page, excerpt: excerptAround(text, at, needle.length) });\n }\n return hits;\n }\n\n flipNext(): void {\n this.#stepFlip(1);\n }\n\n flipPrev(): void {\n this.#stepFlip(-1);\n }\n\n /** Turn one spread in `step`'s direction, counted from wherever the book lands. Interrupting\n * commits the running turn first, so this steps on from there — repeat taps keep advancing,\n * and a reversal goes to the neighbour of the spread that just landed. */\n #stepFlip(step: 1 | -1): void {\n this.#requestFlip(() => this.#startFlip(this.#current + step));\n }\n\n flipTo(page: number): void {\n const target = clamp(page, 0, Math.max(0, this.#source.pageCount - 1));\n this.#requestFlip(() => this.#startFlip(this.#spreadIndexForPage(target)));\n }\n\n /** Run a flip now. If a fold is animating, land it instantly first so the new turn starts\n * immediately on this click (thunks read `#current` lazily, so it steps on from where the\n * interrupted turn landed). A drag in flight can't be interrupted this way, so its request\n * is queued and replayed on settle instead. */\n #requestFlip(run: () => void): void {\n if (this.#machine.state === 'idle') {\n run();\n } else if (this.#activeAnim) {\n // This request supersedes anything still waiting: landing the current turn commits it,\n // and that commit drains the queue. Without clearing it first, an older tap would fire\n // from inside the commit and take the book somewhere the reader has since changed their\n // mind about — a reversal would be undone by the forward tap it was meant to replace.\n this.#queuedFlip = null;\n this.#finishActiveAnim(); // lands the current turn → machine back to idle\n run();\n } else {\n this.#queuedFlip = run; // dragging: no animation to cut short, so wait for release\n }\n }\n\n /** Snap the in-flight fold to its end pose and commit it now, cancelling its RAF loop. */\n #finishActiveAnim(): void {\n const anim = this.#activeAnim;\n if (!anim) return;\n this.#activeAnim = null;\n if (this.#raf !== null) {\n cancelAnimationFrame(this.#raf);\n this.#raf = null;\n }\n this.#renderer?.setFlipProgress(anim.toT, anim.direction);\n anim.onDone();\n }\n\n /** After an animation settles, fire whatever flip was requested mid-turn. */\n #drainQueuedFlip(): void {\n const queued = this.#queuedFlip;\n if (!queued) {\n // Nothing further to turn to, so this is where the book comes to rest: a good moment to\n // apply any page content that improved while it was moving.\n this.#flushPendingUpgrades();\n return;\n }\n this.#queuedFlip = null;\n queued();\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.#refreshZoomTiles();\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.#activeAnim = null;\n this.#queuedFlip = null;\n this.#clearPendingClickFlip();\n this.#resizeObserver?.disconnect();\n this.#deepLink?.stop();\n this.#deepLink = null;\n this.#unsubscribeDeepLink?.();\n if (this.#deepLinkEnabled) releaseHash(); // a later book may own it now\n this.#controlsCleanup?.();\n this.#a11yCleanup?.();\n this.#unbindWheel?.();\n this.#unbindDblClick?.();\n this.#unbindContextMenu?.();\n this.#unbindInput?.();\n if (this.#tileTimer !== null) clearTimeout(this.#tileTimer);\n this.#tileGeneration++; // strand any tile still resolving\n this.#zoomOverlay?.destroy();\n this.#zoomOverlay = null;\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 // Claimed here, synchronously, so this flip owns the run before #runFlip's first await.\n // Bumping inside #runFlip instead let a superseded flip's continuation claim the newest\n // generation and cancel the flip that replaced it.\n void this.#runFlip(targetIndex, direction, toPage, ++this.#flipGeneration);\n }\n\n async #runFlip(\n targetIndex: number,\n direction: FlipDirection,\n toPage: number,\n generation: number,\n ): Promise<void> {\n // Staging the destination is async, so this can resume after a later flip has already\n // superseded it (interrupting mid-turn does exactly that). Without this check the stale\n // continuation would begin animating its own, now-abandoned target and commit it, undoing\n // the turn the reader actually asked for.\n const toSpread = this.#spreads[targetIndex];\n const toContent: SpreadContent = toSpread\n ? await this.#resolveContent(toSpread)\n : { left: null, right: null };\n if (generation !== this.#flipGeneration) return;\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 // Remembered so a mid-turn flip request can #finishActiveAnim() to land it at once.\n // Object identity also tags this run: if #finishActiveAnim (or a new flip) replaces it,\n // a stale frame that still fires bails instead of re-committing or rescheduling itself.\n const anim = { toT, direction, onDone };\n this.#activeAnim = anim;\n const start = performance.now();\n const step = (now: number): void => {\n if (this.#activeAnim !== anim) return; // superseded/interrupted → this frame is void\n // Easing lives here; flipProgressToPose stays linear so seeks are deterministic.\n // Lone pages ease out harder — no facing half to land on, only a dissolve.\n const raw = Math.min(1, (now - start) / duration);\n const eased = this.#singlePage ? easeInOutLone(raw) : easeInOutQuad(raw);\n this.#renderer?.setFlipProgress(fromT + (toT - fromT) * eased, direction);\n if (raw < 1) {\n this.#raf = requestAnimationFrame(step);\n } else {\n this.#raf = null;\n this.#activeAnim = 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 this.#drainQueuedFlip();\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) 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 b = this.#contentRect();\n const point = this.#toBookPoint(clientX, clientY);\n // Recorded before the busy check below: a tap landing mid-flip is still a real tap, and\n // on release it decides which way to turn. Leaving the previous press in place made that\n // release repeat the last flip's direction instead of honouring the side just tapped.\n this.#press = point; // remembered for tap classification / click-to-flip zone\n // Only the drag machinery needs an idle book — a fold is already on screen, so there is\n // nothing to grab. The tap itself is handled on release, which queues or interrupts.\n if (this.#machine.state !== 'idle') {\n this.#pendingGrab = null;\n return;\n }\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 this.#refreshZoomTiles();\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 step = direction === 'forward' ? 1 : -1;\n if (this.#current + step < 0 || this.#current + step >= this.#spreads.length) return;\n // Anchor the fold at the tapped height (cone/leaf/flick curl from where you tap).\n this.#anchorY = clamp(this.#press.y / this.#contentRect().height, 0, 1);\n // Read `#current` lazily: interrupting commits the running turn first, so this steps on\n // from wherever the book actually landed — one spread back from there is the neighbour\n // the reader is looking at, not the spread they tapped on two turns ago.\n const flip = (): void => this.#startFlip(this.#current + step);\n this.#clearPendingClickFlip();\n if (this.#clickFlipDelayValue <= 0) {\n // No double-click competing here → flip right away (or queue if mid-turn).\n this.#requestFlip(flip);\n return;\n }\n // Wait out the window; a double-click (zoom) cancels this.\n this.#pendingClickTimer = setTimeout(() => {\n this.#pendingClickTimer = null;\n this.#requestFlip(flip);\n }, this.#clickFlipDelayValue);\n }\n\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 /** A viewport point in book-local px: relative to the drawn page, not the container. The two\n * differ whenever the book is letterboxed, so every hit test against a zone or corner has to\n * come through here — measuring from the container edge puts the zones off by the bar width. */\n #toBookPoint(clientX: number, clientY: number): { x: number; y: number } {\n const rect = this.#container.getBoundingClientRect();\n const b = this.#contentRect();\n return { x: clientX - rect.left - b.x, y: clientY - rect.top - b.y };\n }\n\n /** Which way a tap at `point` (book-local, via {@link #toBookPoint}) turns the page, or null\n * for a dead zone. */\n #clickFlipDirection(point: { x: number; y: number }): FlipDirection | null {\n if (!this.#renderer) return null;\n const bookWidth = this.#contentRect().width;\n let side: 'left' | 'right' | null;\n if (this.#clickToFlip === 'half') {\n side = point.x > bookWidth / 2 ? 'right' : 'left';\n } else if (point.x <= this.#clickZoneSize) {\n side = 'left';\n } else if (point.x >= bookWidth - 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 this.#drainQueuedFlip();\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 /** Swallow the right-click menu over the book, when the consumer asked for that. */\n #bindContextMenu(): void {\n if (!this.#disableContextMenu) return;\n const onContextMenu = (event: Event): void => event.preventDefault();\n this.#container.addEventListener('contextmenu', onContextMenu);\n this.#unbindContextMenu = () =>\n this.#container.removeEventListener('contextmenu', onContextMenu);\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 || !this.#renderer) 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 local = this.#toBookPoint(event.clientX, event.clientY);\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.#bindContextMenu();\n this.#setupReducedMotion();\n this.#a11yCleanup = this.#setupA11y();\n\n await this.#renderCurrent();\n this.#observeResize();\n this.#prefetchWindow();\n this.#announce();\n this.#bindDeepLink();\n await this.#mountControls();\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 /**\n * Build the toolbar, if it is wanted and the container is real DOM.\n *\n * The chunk is fetched lazily so a book with `controls: false` never downloads it. Failure is\n * swallowed on purpose: a toolbar that cannot load should cost the reader a toolbar, not the\n * whole flipbook — `#init` has no error handling of its own, so a throw here would reject\n * `ready`.\n */\n async #mountControls(): Promise<void> {\n if (this.#controlsOption === false || this.#destroyed) return;\n const container = this.#container;\n if (!container.ownerDocument || typeof container.appendChild !== 'function') return;\n try {\n const { mountControls } = await import('./controls/controls');\n if (this.#destroyed) return; // destroyed while the chunk was in flight\n const options = this.#controlsOption === true ? {} : this.#controlsOption;\n this.#controlsCleanup = mountControls(this, container, options);\n } catch {\n // No toolbar; the book itself is unaffected.\n }\n }\n\n /** Mirror the page in the URL, and follow the URL when it changes. */\n #bindDeepLink(): void {\n if (!this.#deepLinkEnabled || typeof globalThis.location === 'undefined') return;\n const win = globalThis as unknown as Window;\n this.#deepLink = bindDeepLink(win, (page) => {\n // Only act on a hash the reader changed — following a link, or pressing Back. A hash we\n // wrote ourselves describes where the book already is.\n if (page !== this.#currentPage) this.flipTo(page);\n });\n this.#deepLink.push(this.#currentPage);\n this.#unsubscribeDeepLink = this.#emitter.on('pageChanged', ({ page }) => {\n this.#deepLink?.push(page);\n });\n }\n\n /** The URL that opens this book at `page` (defaults to the current one). */\n pageLink(page: number = this.#currentPage): string {\n const href = globalThis.location?.href ?? '';\n if (!href) return '';\n const url = new URL(href);\n url.hash = hashWithPage(url.hash, clamp(page, 0, Math.max(0, this.#source.pageCount - 1)));\n return url.toString();\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 return this.#flipDuration * (this.#singlePage ? LONE_PAGE_FLIP_SCALE : 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 =\n this.#responsiveSpread && shouldSinglePage(containerWidth, this.#singlePageThreshold);\n if (narrow === this.#narrow) return;\n this.#narrow = narrow;\n this.#rebuildSpreads();\n }\n\n /** Regroup the pages after something changes the layout, keeping the reader on the page they\n * were looking at even though its spread index may have moved. */\n #rebuildSpreads(): void {\n const mode = this.#effectiveMode();\n const changed = mode !== this.#effectiveModeShown;\n this.#effectiveModeShown = mode;\n this.#singlePage = mode === 'single';\n this.#spreads = buildSpreads(this.#source.pageCount, { direction: this.#direction, mode });\n this.#current = this.#spreadIndexForPage(this.#currentPage);\n // The book's proportions change with the layout, so consumers sizing around it need to know.\n if (changed) this.#emitter.emit('spreadChanged', { mode, singlePage: this.#singlePage });\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 // Whatever is overlaid was rendered for the pages that just left; drop it and re-request.\n this.#zoomOverlay?.clear();\n this.#refreshZoomTiles();\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 /**\n * A source upgraded a page's content (e.g. a progressive PDF swapping in the crisp render).\n *\n * Repainting mid-flip would disturb the animation, so an upgrade that lands during one is\n * noted and applied on settle instead of dropped. Dropping it left the page stuck at low\n * resolution for good: the upgrade fires once, and jumping straight to a page — from a search\n * hit, the page field, the outline — is exactly when it tends to arrive.\n */\n #onPageUpdate(index: number): void {\n if (this.#machine.state !== 'idle') {\n this.#pendingUpgrades.add(index);\n return;\n }\n const spread = this.#spreads[this.#current];\n if (spread && (spread.left === index || spread.right === index)) {\n void this.#renderCurrent();\n }\n }\n\n /**\n * Ask the source for a crisp render of whatever is visible, and lay it over the magnified page.\n *\n * Zooming is only a view transform, so without this the reader is magnifying the pixels of a\n * raster made to fit the screen. A vector source can do better; one backed by a fixed-resolution\n * original cannot, and says so by handing back a whole page, which is dropped.\n *\n * Debounced: panning and pinching move the view continuously, and rasterizing a PDF region is\n * far too slow to do per frame. The blurry page stays up in the meantime, so the delay costs\n * sharpness briefly rather than showing a gap.\n */\n #refreshZoomTiles(): void {\n if (this.#tileTimer !== null) clearTimeout(this.#tileTimer);\n\n if (this.#scale <= 1) {\n this.#zoomOverlay?.clear();\n this.#tileGeneration++; // abandon anything in flight: it is no longer wanted\n return;\n }\n this.#tileTimer = setTimeout(() => {\n this.#tileTimer = null;\n void this.#renderZoomTiles();\n }, ZOOM_TILE_DELAY);\n }\n\n async #renderZoomTiles(): Promise<void> {\n const renderer = this.#renderer;\n const spread = this.#spreads[this.#current];\n if (!renderer || !spread || this.#scale <= 1) return;\n\n const m = renderer.measure();\n const box = m.content ?? m.book;\n if (!box) return; // no measured page box: nothing to map screen pixels back onto\n\n // In a two-page spread each page owns half the box; a lone page owns all of it.\n const halves: TilePage[] = [];\n const lone = spread.left === null || spread.right === null;\n const width = lone ? box.width : box.width / 2;\n if (spread.left !== null) halves.push({ index: spread.left, rect: { ...box, width } });\n if (spread.right !== null) {\n halves.push({ index: spread.right, rect: { ...box, x: box.x + (lone ? 0 : width), width } });\n }\n\n const view = { scale: this.#scale, tx: this.#tx, ty: this.#ty };\n const viewport = { x: 0, y: 0, width: m.containerWidth, height: m.containerHeight };\n const plans = planTiles(halves, view, viewport);\n\n const current = this.#zoomOverlay?.shown ?? [];\n const unchanged =\n plans.length === current.length && plans.every((p, i) => sameTile(p, current[i]!));\n if (unchanged) return;\n\n const generation = ++this.#tileGeneration;\n const drawn = await Promise.all(\n plans.map(async (plan) => {\n try {\n const content = await this.#source.get(plan.index, plan.request);\n // A source free to ignore the request returns the whole page. Its aspect gives it away:\n // a tile matches the region it was asked for. Drawing a full page into the region's box\n // would squash it, so treat that as \"nothing sharper available\".\n const want = (plan.dest.width / plan.dest.height) * 1;\n const got = content.width / content.height;\n if (Math.abs(want - got) / want > 0.02) return null;\n return { plan, content };\n } catch (error) {\n // A tile is an enhancement: the readable, blurry page is still on screen underneath.\n this.#emitter.emit('sourceError', { index: plan.index, error });\n return null;\n }\n }),\n );\n if (generation !== this.#tileGeneration || this.#scale <= 1) return; // the view moved on\n const tiles = drawn.filter((t): t is NonNullable<typeof t> => t !== null);\n if (tiles.length === 0) return; // leave whatever is up; clearing would only flicker\n\n this.#zoomOverlay ??= this.#createZoomOverlay();\n this.#zoomOverlay?.draw(tiles, view, viewport);\n }\n\n #createZoomOverlay(): ZoomOverlay | null {\n const doc = this.#container.ownerDocument as Document | undefined;\n // Same guard as #setupA11y: tests mount against bare EventTargets with no real DOM.\n if (!doc || typeof this.#container.append !== 'function') return null;\n return new ZoomOverlay(doc, this.#container);\n }\n\n /** Apply any upgrade that arrived mid-flip, now that the book has settled. */\n #flushPendingUpgrades(): void {\n if (this.#pendingUpgrades.size === 0) return;\n const spread = this.#spreads[this.#current];\n const onScreen =\n spread !== undefined &&\n [spread.left, spread.right].some((p) => p !== null && this.#pendingUpgrades.has(p));\n this.#pendingUpgrades.clear();\n if (onScreen) void this.#renderCurrent();\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 // A page in the URL wins over `startPage`: the reader followed a link to it, which is a\n // later and more specific intent than the page the author configured.\n const linked = this.#deepLinkEnabled ? pageFromHash(globalThis.location?.hash ?? '') : null;\n this.#currentPage = clamp(linked ?? 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\n/** Quadratic ease-in-out. Deliberately gentler than a cubic: a cubic leaves the page nearly\n * motionless for the first quarter of the turn and then spikes through the middle at roughly\n * double the peak speed, which reads as a lurch rather than a sheet of paper being turned. */\nfunction easeInOutQuad(t: number): number {\n return t < 0.5 ? 2 * t * t : 1 - Math.pow(-2 * t + 2, 2) / 2;\n}\n\n/** Lone-page turn: same gentle start as the spread ease, then a longer decelerating finish.\n * Without a facing half the landing is a dissolve — front-loading a bit of progress and\n * stretching the tail keeps that fade from reading as a whip. */\nfunction easeInOutLone(t: number): number {\n const x = easeInOutQuad(t);\n return 1 - Math.pow(1 - x, 1.3);\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 for (const flag of ['deepLink', 'disableContextMenu', 'responsiveSpread'] as const) {\n if (o[flag] !== undefined && typeof o[flag] !== 'boolean') {\n throw new Error(`Zine: ${flag} must be a boolean; got ${typeName(o[flag])}.`);\n }\n }\n\n const controls = o.controls;\n if (controls !== undefined && typeof controls !== 'boolean' && (typeof controls !== 'object' || controls === null)) {\n throw new Error(\n `Zine: controls must be a boolean or an options object; got ${typeName(controls)}.`,\n );\n }\n const position = (controls as { position?: unknown } | undefined)?.position;\n if (position !== undefined && !['top', 'bottom', 'left', 'right'].includes(position as string)) {\n throw new Error(\n `Zine: controls.position must be 'top', 'bottom', 'left', or 'right'; got ${JSON.stringify(position)}.`,\n );\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, SearchHit } from './zine';\n\n// Just the registry mechanism — the toolbar, its icons and the built-in definitions all live in\n// the lazily-loaded chunk, so registering a custom control costs nothing up front.\nexport { defineControl, getControl, DEFAULT_ITEMS } from './controls/registry';\nexport type {\n ControlContext,\n ControlDef,\n ControlItem,\n ControlsOptions,\n ControlsPosition,\n} from './controls/types';\n\nexport { ImageSource } from './source/imageSource';\nexport type { ImageSourceOptions, ImageFit } from './source/imageSource';\nexport type { Source, DownloadInfo, OutlineItem, PageRequest } 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 './geometry/curls/types';\nexport type { CurlType, CurlAnchor } from './geometry/curls/types';\n"],"mappings":"sfA8BA,SAAgB,EAAa,EAAmB,EAAyB,CAAC,EAAa,CACrF,GAAM,CAAE,YAAY,MAAO,OAAO,SAAY,EAC9C,GAAI,GAAa,EAAG,MAAO,CAAC,EAE5B,IAAM,EAAQ,GAA8B,GAAK,GAAK,EAAI,EAAY,EAAI,KACpE,EAAoB,CAAC,EAE3B,GAAI,IAAS,SACX,IAAK,IAAI,EAAI,EAAG,EAAI,EAAW,IAAK,EAAQ,KAAK,CAAE,KAAM,KAAM,MAAO,CAAE,CAAC,OACpE,GAAI,IAAS,SAClB,IAAK,IAAI,EAAI,EAAG,EAAI,EAAW,GAAK,EAAG,EAAQ,KAAK,CAAE,KAAM,EAAK,CAAC,EAAG,MAAO,EAAK,EAAI,CAAC,CAAE,CAAC,OACpF,GAAI,IAAS,QAAS,CAC3B,EAAQ,KAAK,CAAE,KAAM,KAAM,MAAO,CAAE,CAAC,EACrC,IAAK,IAAI,EAAI,EAAG,EAAI,EAAW,GAAK,EAAG,EAAQ,KAAK,CAAE,KAAM,EAAK,CAAC,EAAG,MAAO,EAAK,EAAI,CAAC,CAAE,CAAC,CAC3F,MAGE,GADA,EAAQ,KAAK,CAAE,KAAM,KAAM,MAAO,CAAE,CAAC,EACjC,EAAY,EAAG,CACjB,IAAK,IAAI,EAAI,EAAG,GAAK,EAAY,EAAG,GAAK,EACvC,EAAQ,KAAK,CAAE,KAAM,EAAK,CAAC,EAAG,MAAO,EAAI,GAAK,EAA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AAK,EAClC,IAAK,IAAI,EAAI,EAAG,GAAK,KAAKD,GAAU,IAClC,KAAK,SAAS,CAAC,EAAQ,EAAG,EAAQ,CAAC,CAAC,EAEtC,OAAO,CACT,CAEA,SAAS,EAAyB,CAChC,IAAK,IAAM,KAAK,EACV,GAAK,GAAK,EAAI,KAAK,WACrB,KAAUC,GAAQ,CAAC,CAAC,CAAC,UAAY,CAAC,CAAC,CAGzC,CAEA,SAAgB,CACd,IAAK,IAAM,KAAW,KAAKC,GAAO,OAAO,EACvC,EAAa,KAAM,GAAW,EAAO,MAAM,CAAC,CAAC,CAAC,UAAY,CAAC,CAAC,EAE9D,KAAKA,GAAO,MAAM,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,ICzEyD,IAkB9B"}
1
+ {"version":3,"file":"index.umd.js","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","#curlModel","#anchor","#fromShiftUnit","#toShiftUnit","#view","#bookBox","#contentBox","#shiftX","#dpr","#contextLost","#restoreTimer","#fatal","#fatalFired","#flatU","#curlU","#makeQuadVao","#buildCurlMesh","#makeBlankTexture","#idxCount","#posBuf","#normBuf","#mesh","#resize","#fitBook","#drawFlip","#drawStatic","#bookW","#bookH","#useFlat","#drawQuad","#bindFace","#fillFade","#textureFor","#evictTextures","#base","#front","#back","#rawPages","#resolvePages","#resolved","#image","#cache","#doc","#lastFocus","#backdrop","#dialog","#linkRow","#socialRow","#qr","#onKey","#trapFocus","#copy","#timer","#holder","#place","#wrap","#zine","#doc","#bar","#build","#markCurrent","#unsubscribe","#rows","#observeRows","#paint","#observer","#zine","#doc","#bar","#note","#build","#unsubscribe","#markCurrent","#addLevel","#rows","#zine","#doc","#bar","#input","#timer","#search","#hits","#run","#note","#zine","#prev","#button","#next","#place","#refresh","#unsubscribe","#wrap","#zine","#container","#doc","#root","#bar","#onKeyDown","#isolate","#place","#refresh","#unsubscribe","#popover","#closePopover","#wrap","#build","#arrows","#probeOutline","#panel","#panelKind","#context","#buttons","#button","#titleOf","#iconOf","#activate","#openMenu","#showPopover","#placePopover","#hasVisibleChildren","#formFields","#pageInput","#hasOutline","#renderer","#container","#source","#direction","#deepLinkEnabled","#disableContextMenu","#spreadMode","#configuredMode","#curl","#clickToFlip","#clickZoneSize","#singlePageThreshold","#responsiveSpread","#controlsOption","#startPageOption","#buildSpreadModel","#flipDuration","#zoomEnabled","#wheelZoom","#doubleClickLevels","#maxZoom","#honorDoubleClickInFlipZone","#clickFlipDelayValue","#ready","#init","#currentPage","#spreads","#current","#singlePage","#narrow","#rebuildSpreads","#renderCurrent","#applySinglePage","#getPage","#outline","#emitter","#stepFlip","#requestFlip","#startFlip","#spreadIndexForPage","#machine","#activeAnim","#queuedFlip","#finishActiveAnim","#raf","#flushPendingUpgrades","#scale","#tx","#ty","#clampPan","#refreshZoomTiles","#destroyed","#clearPendingClickFlip","#resizeObserver","#deepLink","#unsubscribeDeepLink","#controlsCleanup","#a11yCleanup","#unbindWheel","#unbindDblClick","#unbindContextMenu","#unbindInput","#tileTimer","#tileGeneration","#leadPage","#runFlip","#flipGeneration","#resolveContent","#currentContent","#effectiveCurl","#anchorY","#animateProgress","#commit","#effectiveDuration","#paintSpread","#prefetchWindow","#announce","#drainQueuedFlip","#pinching","#pan","#contentRect","#toBookPoint","#press","#pendingGrab","#drag","#stageDrag","#promoteGrab","#maybeClickFlip","#cancelFlip","#clickFlipDirection","#pendingClickTimer","#pinchBaseScale","#mountWithFallback","#onPageUpdate","#onDragStart","#onDragMove","#onDragEnd","#onPinchStart","#onPinchMove","#onPinchEnd","#bindWheelZoom","#bindDoubleClickZoom","#bindContextMenu","#setupReducedMotion","#setupA11y","#observeResize","#bindDeepLink","#mountControls","#fallbackToCss","#fellBack","#reducedMotion","#onKeyDown","#liveRegion","#effectiveMode","#effectiveModeShown","#applyContainerAspect","#zoomedAt","#lastAspect","#pendingUpgrades","#upgradeScale","#renderZoomTiles","#scheduleUpdate","#updateScheduled","#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/engine/deeplink.ts","../src/geometry/curls/types.ts","../src/geometry/flipProgressToPose.ts","../src/renderer/cssRenderer.ts","../src/geometry/curls/mesh.ts","../src/geometry/curls/cone.ts","../src/geometry/curls/simple.ts","../src/geometry/curls/bundled.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/controls/icons.ts","../src/controls/registry.ts","../src/controls/socials.ts","../src/controls/qr.ts","../src/controls/share.ts","../src/controls/builtins.ts","../src/controls/styles.ts","../src/controls/sidebar.ts","../src/controls/thumbnails.ts","../src/controls/outline.ts","../src/controls/search.ts","../src/controls/arrows.ts","../src/controls/toolbar.ts","../src/controls/controls.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","import type { SpreadMode } from './spread.js';\n\nexport 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 /** Pages regrouped: the spread mode changed, or a narrow container forced one page. */\n spreadChanged: { mode: SpreadMode; singlePage: boolean };\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 * Keeping the page in the URL, so a link opens where the reader was.\n *\n * The hash is treated as shared ground rather than ours: only a `page` key is read or written,\n * anything else in it is preserved, and updates go through `replaceState` so turning pages does\n * not fill the reader's back button with history entries.\n */\nconst KEY = 'page';\n\n/**\n * Whether some book on this page already owns the hash.\n *\n * Two books sharing one URL would each overwrite the other's page, and the second to load would\n * open on the first one's page. Only the first claims it; the rest still work, they just do not\n * appear in the address bar.\n */\nlet claimed = false;\n\n/** Take the hash if it is going, and report whether this caller got it. */\nexport function claimHash(): boolean {\n if (claimed) return false;\n claimed = true;\n return true;\n}\n\n/** Give the hash back, so a book that replaces this one can own it. */\nexport function releaseHash(): void {\n claimed = false;\n}\n\n/** Read the 1-based page from a hash, as a 0-based index. Null when it carries no page. */\nexport function pageFromHash(hash: string): number | null {\n const params = new URLSearchParams(hash.replace(/^#/, ''));\n const raw = params.get(KEY);\n if (raw === null) return null;\n const page = Number(raw);\n return Number.isInteger(page) && page >= 1 ? page - 1 : null;\n}\n\n/** The hash that names `page` (0-based), leaving any other keys in `hash` untouched. */\nexport function hashWithPage(hash: string, page: number): string {\n const params = new URLSearchParams(hash.replace(/^#/, ''));\n params.set(KEY, String(page + 1));\n return `#${params.toString()}`;\n}\n\nexport interface DeepLinkHandle {\n /** Write the current page into the address bar. */\n push(page: number): void;\n stop(): void;\n}\n\n/**\n * Mirror the reader's page in the URL, and follow it when the URL changes (back/forward, or a\n * pasted link). `onNavigate` fires only for a page the book is not already on.\n */\nexport function bindDeepLink(win: Window, onNavigate: (page: number) => void): DeepLinkHandle {\n // The page the URL is known to describe. Compared against rather than the hash string itself:\n // some environments emit `hashchange` for our own replaceState, and a string comparison there\n // would let the echo through and turn the page a second time.\n let shown: number | null = null;\n const onHashChange = (): void => {\n const page = pageFromHash(win.location.hash);\n if (page === null || page === shown) return; // absent, or already where we are\n shown = page;\n onNavigate(page);\n };\n win.addEventListener('hashchange', onHashChange);\n return {\n push(page) {\n if (page === shown) return;\n shown = page;\n const hash = hashWithPage(win.location.hash, page);\n if (hash === win.location.hash) return;\n // replaceState, not assignment: a reader flipping through fifty pages should not have to\n // press Back fifty times to leave.\n win.history?.replaceState?.(win.history.state, '', hash);\n },\n stop() {\n win.removeEventListener('hashchange', onHashChange);\n },\n };\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 * Full-width lone page (single-page mode). The leaf hinges at the container edge and\n * has no facing half to land on — deforms may soften and delay the flop so the curl\n * reads naturally before the renderer dissolves the sheet.\n */\n fill?: boolean;\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 /** True when the fold originates at a corner (`anchor.y`) rather than the whole edge. */\n readonly anchored: boolean;\n /**\n * True when the sheet is flat by mid-turn, so a lone page can start dissolving earlier: there\n * is no curl left to read. Defaults to false, which suits a model still bent as it lands.\n */\n readonly flat?: boolean;\n /**\n * False to drop the specular highlight, for a sheet that never bends and so has no curve to\n * catch the light. Defaults to true.\n */\n readonly gloss?: boolean;\n}\n\n/**\n * The curl models carried in the bundle: the default, and the flat turn reduced motion falls\n * back to. Everything else is imported from `@zinejs/core/curls` and passed as a model, so a\n * book that never uses it never pays for it.\n */\nexport type CurlType = 'cone' | 'simple';\n\nexport const CURL_TYPES: CurlType[] = ['cone', 'simple'];\n\n/**\n * Curl models that exist but are not bundled. Named only so passing one as a string can say what\n * to do about it instead of failing as an unknown value.\n */\nexport const IMPORTABLE_CURLS = ['roll', 'leaf', 'flick', 'silk'];\n\nexport const DEFAULT_CURL: CurlType = 'cone';\n\n/** What the `curl` option accepts: a bundled name, or a model imported (or written) by the caller. */\nexport type CurlSpec = CurlType | CurlModel;\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 // The shift lives on #book, inside the scaled #viewport, so unlike the WebGL2 renderer it\n // magnifies along with everything else and the whole box simply scales.\n const screenAt = content\n ? (scale: number): { x: number; y: number; width: number; height: number } => ({\n x: content.x * scale,\n y: content.y * scale,\n width: content.width * scale,\n height: content.height * scale,\n })\n : undefined;\n return {\n containerWidth: w,\n containerHeight: h,\n pageWidth: w / 2,\n pageHeight: h,\n book,\n content,\n screenAt,\n };\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';\nimport type { CurlAnchor } from './types';\n\n/**\n * Cone angle at peak curl. π/2 is flat; smaller values wind the sheet tighter.\n * ~30° gives a soft, paper-like ridge without self-intersection on typical page\n * aspect ratios (Hong / Nuon / Project Austin all land in the 18–35° band).\n */\nconst THETA_MIN = (30 * Math.PI) / 180;\n/** Gentler opening for full-width lone pages — a tight cone reads as a funnel when\n * the leaf owns the whole viewport and hinges at the edge. */\nconst THETA_MIN_FILL = (44 * Math.PI) / 180;\n\n/**\n * How far past the page the cone apex sits, as a fraction of height, at rest.\n * Closer mid-turn sharpens the diagonal; farther reads more cylindrical.\n * Kept moderately distant so the sheet stays page-like without cloth-y sliding.\n */\nconst APEX_REST = 1.35;\nconst APEX_PEAK = 0.7;\n/** Farther apex on fill: softer diagonal, less cloth-y twist across the full leaf. */\nconst APEX_REST_FILL = 1.85;\nconst APEX_PEAK_FILL = 1.15;\n\n/**\n * Above this |anchor.y − 0.5| the deform is a pure cone; at the mid-edge it\n * blends fully to a cylinder (Project Austin’s conicContribution).\n */\nconst CORNER_PURE = 0.42;\n\n/**\n * Power on fill flop progress. Slightly >1 delays spine rotation so the cone develops\n * over the page before the leaf swings past the edge hinge — kept close to 1 so the\n * flop isn't packed into a late whip (lone pages dissolve rather than land).\n */\nconst FILL_RHO_POWER = 1.08;\n\n/**\n * Natural conical page curl — the Xerox PARC / iBooks model.\n *\n * The leaf wraps an imaginary right circular cone whose apex rides the spine and\n * whose opening angle θ breathes over the turn (Hong, Card & Chen, 2004). A corner\n * grab yields a diagonal cone; a mid-edge grab blends toward a cylinder so the\n * free edge lifts as one. The curled sheet then rotates about the spine and settles\n * flat on the far side. Arc length from the apex is preserved, so the paper never\n * stretches — the motion reads as stiff, premium stock rather than cloth.\n *\n * On a full-width lone page (`anchor.fill`) the hinge is the container edge with no\n * facing half to land on: the cone softens, the flop is delayed so the peel stays\n * over the page longer, and the renderer dissolves the sheet as it finishes.\n */\nexport function deformCone(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 fill = !!anchor.fill;\n\n // Curl envelope: 0 at the ends (flat), 1 at mid-turn. Soft power keeps the\n // ridge full through the middle third — paper holds its bend rather than\n // peaking and collapsing.\n const curl = Math.pow(Math.sin(Math.PI * t), 0.85);\n\n // θ: π/2 (identity) → THETA_MIN (pronounced curl) → π/2.\n const thetaMin = fill ? THETA_MIN_FILL : THETA_MIN;\n const theta = Math.PI / 2 - curl * (Math.PI / 2 - thetaMin);\n const sinTheta = Math.sin(theta);\n const cosTheta = Math.cos(theta);\n const invSinTheta = 1 / Math.max(sinTheta, 1e-6);\n\n // Apex distance: pulled in as the curl develops for a tighter diagonal.\n const apexRest = fill ? APEX_REST_FILL : APEX_REST;\n const apexPeak = fill ? APEX_PEAK_FILL : APEX_PEAK;\n const apexDist = H * (apexRest + (apexPeak - apexRest) * curl);\n\n // Corner bias: −1 = top edge, +1 = bottom. Near 0 → cylinder blend.\n const bias = (anchor.y - 0.5) * 2;\n const fromBottom = bias >= 0;\n const absBias = Math.abs(bias);\n let conic = Math.min(1, absBias / CORNER_PURE);\n const cylWeight = 1 - conic;\n\n // Cylinder radius matched to the cone’s free-edge cross-section (Austin), so\n // the blend is continuous as the grab slides from corner to mid-edge.\n // Apex sits past the *leading* edge (below for a bottom grab, above for top).\n const AyRef = fromBottom ? H + apexDist : -apexDist;\n const cylR = Math.hypot(W, 0.5 * H - AyRef);\n const cylRadius = Math.max(cylR * sinTheta, W / Math.PI);\n\n // Spine rotation: concurrent with the cone so the page flops while it curls.\n // Same x–z convention as `roll` (ρ: 0 → −π). On fill, delay the flop so the\n // peel develops over the page before the leaf swings past the edge hinge.\n const rhoT = fill ? Math.pow(t, FILL_RHO_POWER) : t;\n const rho = -Math.PI * rhoT;\n const cosR = Math.cos(rho);\n const sinR = Math.sin(rho);\n\n // Near the rests the cone is the identity plane. A finite-radius cylinder blend\n // still carries a tiny residual arc — skip it and rotate the flat sheet.\n if (curl < 1e-4) {\n for (let j = 0; j < ny; j++) {\n const y = (j / mesh.rows) * H;\n for (let i = 0; i < nx; i++) {\n const x0 = (i / mesh.cols) * W;\n const k = (j * nx + i) * 3;\n pos[k] = x0 * cosR;\n pos[k + 1] = y;\n pos[k + 2] = -x0 * sinR;\n }\n }\n computeNormals(mesh);\n return;\n }\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\n let cx = x0;\n let cy = y0;\n let cz = 0;\n\n if (conic > 1e-5) {\n // Canonical cone: apex above the page (A < 0) makes the *near* edge lead.\n // In our y-down leaf, that means the top. For a bottom grab we flip into\n // that space, deform, then flip back — one code path for both corners.\n const yIn = fromBottom ? H - y0 : y0;\n const A = -apexDist;\n const R = Math.hypot(x0, yIn - A);\n if (R > 1e-8) {\n const r = R * sinTheta;\n const beta = Math.asin(Math.min(1, Math.max(0, x0 / R))) * invSinTheta;\n const oneCos = 1 - Math.cos(beta);\n const yCone = R + A - r * oneCos * sinTheta;\n cx = r * Math.sin(beta);\n cy = fromBottom ? H - yCone : yCone;\n cz = r * oneCos * cosTheta;\n }\n }\n\n let bx = cx;\n let by = cy;\n let bz = cz;\n\n if (cylWeight > 1e-5) {\n const beta = x0 / cylRadius;\n const sx = cylRadius * Math.sin(beta);\n const sz = cylRadius * (1 - Math.cos(beta));\n bx = conic * cx + cylWeight * sx;\n by = conic * cy + cylWeight * y0;\n bz = conic * cz + cylWeight * sz;\n }\n\n const k = (j * nx + i) * 3;\n pos[k] = bx * cosR + bz * sinR;\n pos[k + 1] = by;\n pos[k + 2] = -bx * sinR + bz * cosR;\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","import { deformCone } from './cone';\nimport { deformSimple } from './simple';\nimport { IMPORTABLE_CURLS, type CurlModel, type CurlSpec, type CurlType } from './types';\n\n/**\n * The curl models carried in the bundle, and the only ones nameable by string.\n *\n * Kept apart from `./index` so importing them does not drag in the other four: the barrel names\n * every model, which is right for a caller picking one but wrong for the renderer, which must\n * only ever pull these two.\n */\nexport const cone: CurlModel = { deform: deformCone, anchored: true };\nexport const simple: CurlModel = {\n deform: deformSimple,\n anchored: false,\n flat: true,\n gloss: false,\n};\n\nexport const BUNDLED_CURLS: Record<CurlType, CurlModel> = { cone, simple };\n\n/**\n * Turn a `curl` option into a model. Strings name a bundled curl; anything else is already a\n * model, imported from `@zinejs/core/curls` or written by the caller.\n */\nexport function resolveCurl(spec: CurlSpec): CurlModel {\n if (typeof spec !== 'string') return spec;\n const model = BUNDLED_CURLS[spec];\n if (model) return model;\n // Reached only when validation was bypassed (a renderer used directly, say), so name the fix\n // rather than the mistake: these curls are real, they just are not bundled.\n if (IMPORTABLE_CURLS.includes(spec)) {\n throw new Error(\n `Zine: the '${spec}' curl is not bundled. Import it and pass the model: ` +\n `import { ${spec} } from '@zinejs/core/curls' → curl: ${spec}`,\n );\n }\n throw new Error(`Zine: unknown curl ${JSON.stringify(spec)}.`);\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","// Imported from the leaf modules, not the barrel: the barrel pulls in every curl, which would\n// defeat the point of only bundling the two the engine can name.\nimport { createPageMesh, type PageMesh } from '../geometry/curls/mesh';\nimport { BUNDLED_CURLS, resolveCurl } from '../geometry/curls/bundled';\nimport { DEFAULT_CURL, type CurlAnchor, type CurlModel, type CurlSpec } from '../geometry/curls/types';\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 // Eye distance, in leaf widths. Keeps the perspective resolution-independent. 5.3 puts the\n // roll's deepest point ~14% larger than flat; stronger than that (a nearer eye) balloons the\n // turning sheet and reads more like a fisheye than a page lifting.\n float D = uLeafW * 5.3;\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)\nuniform float uAlpha; // leaf opacity; a lone page dissolves into the page landing beneath it\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 // Premultiplied alpha (blendFunc ONE, ONE_MINUS_SRC_ALPHA): scale colour as well as alpha,\n // or fading would brighten the sheet additively instead of dissolving it.\n outColor = vec4(c.rgb * uAlpha, c.a * uAlpha);\n}`;\n\nconst GRID_COLS = 28;\nconst GRID_ROWS = 36;\n/** Progress at which a lone page starts dissolving. A full-width leaf has no facing half to\n * flop onto, so instead of landing on empty space it fades into the page arriving beneath it\n * over the rest of the turn. Roll is already flat by mid-turn; curling models stay bent\n * longer, so they dissolve later. The fade itself eases so the leaf settles rather than\n * vanishing while still swinging. */\nconst FILL_FADE_START_ROLL = 0.7;\nconst FILL_FADE_START_CURL = 0.8;\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 #curlModel: CurlModel = BUNDLED_CURLS[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.#curlModel = resolveCurl(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 const screenAt = content\n ? (scale: number): { x: number; y: number; width: number; height: number } => {\n // The shader applies `px * scale + view.t + shiftX`, so the lone-page shift sits\n // *outside* the scale: a fixed screen offset, not part of the magnified geometry.\n const shiftCss = this.#shiftX / this.#dpr;\n return {\n x: (content.x - shiftCss) * scale + shiftCss,\n y: content.y * scale,\n width: content.width * scale,\n height: content.height * scale,\n };\n }\n : undefined;\n return {\n containerWidth: w,\n containerHeight: h,\n pageWidth: w / 2,\n pageHeight: h,\n book,\n content,\n screenAt,\n };\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', 'uAlpha']) {\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 this.#curlModel.deform(this.#mesh, leafW, h, this.#flipT, {\n y: this.#anchor.y,\n fill: flip.fill,\n });\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.#curlModel.gloss === false ? 0 : 1);\n gl.uniform1f(this.#curlU.uAlpha ?? null, flip.fill ? this.#fillFade() : 1);\n gl.drawElements(gl.TRIANGLES, this.#idxCount, gl.UNSIGNED_SHORT, 0);\n }\n\n /** Leaf opacity for a lone page: solid until the curl-appropriate fade start, then\n * dissolving to 0 as it lands, so the turn resolves into the destination page rather\n * than onto blank space. The fade eases so opacity hangs longer then finishes cleanly. */\n #fillFade(): number {\n const start = this.#curlModel.flat ? FILL_FADE_START_ROLL : FILL_FADE_START_CURL;\n const over = (this.#flipT - start) / (1 - start);\n if (over <= 0) return 1;\n if (over >= 1) return 0;\n // Ease-out the remaining opacity: stay readable through most of the window, then settle.\n return Math.pow(1 - over, 1.5);\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 { DownloadInfo, OutlineItem, PageRequest, 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 getText?: (index: number) => Promise<string>;\n getDownload?: () => Promise<DownloadInfo | null>;\n getOutline?: () => Promise<OutlineItem[]>;\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 if (typeof base.getText === 'function') {\n // Mirrors get(): covers and replaced pages are images, so they have no text of their own —\n // returning the base page's text there would describe content the reader cannot see.\n this.getText = async (index) => {\n const frontOffset = this.#front !== null ? 1 : 0;\n if (this.#front !== null && index === 0) return '';\n if (this.#back !== null && index === this.pageCount - 1) return '';\n const src = index - frontOffset;\n if (this.#resolved.has(src)) return '';\n return base.getText!(src);\n };\n }\n\n if (typeof base.getDownload === 'function') {\n // Covers and replacements change what is displayed, not the original document, so the\n // download is the base source's file either way.\n this.getDownload = () => base.getDownload!();\n }\n\n if (typeof base.getOutline === 'function') {\n // The outline points at base pages; a front cover pushes every one of them along by one.\n this.getOutline = async () => {\n const items = await base.getOutline!();\n const offset = this.#front !== null ? 1 : 0;\n if (offset === 0) return items;\n const shift = (list: OutlineItem[]): OutlineItem[] =>\n list.map((item) => ({\n ...item,\n page: item.page === null ? null : item.page + offset,\n children: shift(item.children),\n }));\n return shift(items);\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, opts?: PageRequest): Promise<PageContent> {\n const frontOffset = this.#front !== null ? 1 : 0;\n // Covers and page overrides are images: they have no detail beyond their own resolution, so\n // the zoom request has nothing to act on and is dropped rather than forwarded.\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, opts);\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","/**\n * Toolbar glyphs, inlined so the bundle carries no icon-font or sprite dependency.\n *\n * Paths are from Lucide (https://lucide.dev), ISC licensed:\n * Copyright (c) for portions of Lucide are held by Cole Bemis 2013-2022 as part of Feather\n * (MIT). All other copyright (c) for Lucide are held by Lucide Contributors 2022.\n *\n * Each value is the inner markup of a 24x24 `viewBox` drawn with `stroke=\"currentColor\"`,\n * `fill=\"none\"` and round caps/joins — {@link createIcon} supplies those, so the strings stay to\n * the geometry.\n */\n// Not annotated `Record<string, string>`: that would make every ICONS.foo possibly-undefined\n// under noUncheckedIndexedAccess, even for names written right here. `satisfies` keeps the\n// literal's exact keys while still checking the values are markup strings.\nexport const ICONS = {\n /** chevron-left */\n prev: '<path d=\"m15 18-6-6 6-6\"/>',\n /** chevron-right */\n next: '<path d=\"m9 18 6-6-6-6\"/>',\n /** chevrons-left */\n first: '<path d=\"m11 17-5-5 5-5\"/><path d=\"m18 17-5-5 5-5\"/>',\n /** chevrons-right */\n last: '<path d=\"m6 17 5-5-5-5\"/><path d=\"m13 17 5-5-5-5\"/>',\n /** zoom-in */\n zoomIn:\n '<circle cx=\"11\" cy=\"11\" r=\"8\"/><path d=\"m21 21-4.3-4.3\"/><path d=\"M11 8v6\"/><path d=\"M8 11h6\"/>',\n /** zoom-out */\n zoomOut: '<circle cx=\"11\" cy=\"11\" r=\"8\"/><path d=\"m21 21-4.3-4.3\"/><path d=\"M8 11h6\"/>',\n /** search */\n search: '<circle cx=\"11\" cy=\"11\" r=\"8\"/><path d=\"m21 21-4.3-4.3\"/>',\n /** share-2 */\n share:\n '<circle cx=\"18\" cy=\"5\" r=\"3\"/><circle cx=\"6\" cy=\"12\" r=\"3\"/><circle cx=\"18\" cy=\"19\" r=\"3\"/><path d=\"m8.6 13.5 6.8 4\"/><path d=\"m15.4 6.5-6.8 4\"/>',\n /** ellipsis-vertical */\n menu: '<circle cx=\"12\" cy=\"12\" r=\"1\"/><circle cx=\"12\" cy=\"5\" r=\"1\"/><circle cx=\"12\" cy=\"19\" r=\"1\"/>',\n /** maximize */\n fullscreen:\n '<path d=\"M8 3H5a2 2 0 0 0-2 2v3\"/><path d=\"M21 8V5a2 2 0 0 0-2-2h-3\"/><path d=\"M3 16v3a2 2 0 0 0 2 2h3\"/><path d=\"M16 21h3a2 2 0 0 0 2-2v-3\"/>',\n /** minimize */\n exitFullscreen:\n '<path d=\"M8 3v3a2 2 0 0 1-2 2H3\"/><path d=\"M21 8h-3a2 2 0 0 1-2-2V3\"/><path d=\"M3 16h3a2 2 0 0 1 2 2v3\"/><path d=\"M16 21v-3a2 2 0 0 1 2-2h3\"/>',\n /** gallery-vertical-end */\n thumbnails:\n '<path d=\"M7 2h10\"/><path d=\"M5 6h14\"/><rect width=\"18\" height=\"12\" x=\"3\" y=\"10\" rx=\"2\"/>',\n /** list-tree */\n outline:\n '<path d=\"M21 12h-8\"/><path d=\"M21 6h-8\"/><path d=\"M21 18h-8\"/><path d=\"M3 6v4c0 1.1.9 2 2 2h3\"/><path d=\"M3 10v6c0 1.1.9 2 2 2h3\"/>',\n /** book-open: two facing pages */\n twoPages:\n '<path d=\"M12 7v14\"/><path d=\"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z\"/>',\n /** file: a single page */\n onePage: '<path d=\"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z\"/><path d=\"M14 2v5h6\"/>',\n /** printer */\n print:\n '<path d=\"M6 9V2h12v7\"/><path d=\"M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2\"/><rect width=\"12\" height=\"8\" x=\"6\" y=\"14\" rx=\"1\"/>',\n /** download */\n download: '<path d=\"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4\"/><path d=\"M7 10l5 5 5-5\"/><path d=\"M12 15V3\"/>',\n /** x */\n close: '<path d=\"M18 6 6 18\"/><path d=\"m6 6 12 12\"/>',\n} satisfies Record<string, string>;\n\n/** Build an `<svg>` for one of the {@link ICONS}, or null if the name is unknown. */\nexport function createIcon(doc: Document, markup: string): SVGSVGElement {\n const svg = doc.createElementNS('http://www.w3.org/2000/svg', 'svg');\n svg.setAttribute('viewBox', '0 0 24 24');\n svg.setAttribute('fill', 'none');\n svg.setAttribute('stroke', 'currentColor');\n // Slightly under Lucide's default 2: at the toolbar's icon size a full-weight stroke reads\n // heavy and closes up the tighter shapes.\n svg.setAttribute('stroke-width', '1.75');\n svg.setAttribute('stroke-linecap', 'round');\n svg.setAttribute('stroke-linejoin', 'round');\n svg.setAttribute('aria-hidden', 'true');\n svg.setAttribute('focusable', 'false');\n // Icon markup is library-authored, never consumer input.\n svg.innerHTML = markup;\n return svg;\n}\n","import type { ControlDef, ControlItem } from './types';\n\n/**\n * The control registry.\n *\n * Deliberately just the mechanism — no icons, no built-in definitions — because `defineControl`\n * has to be callable before the toolbar chunk loads, so this module lands in the base bundle.\n * The built-ins live in `./builtins`, which the lazy chunk pulls in along with the icon set.\n */\nconst registry = new Map<string, ControlDef>();\n\n/**\n * Add a control, or replace one by reusing its id. Returns the definition so it can be dropped\n * straight into a layout.\n *\n * ```js\n * defineControl({ id: 'print', title: 'Print', icon: '<path d=\"…\"/>', action: () => print() });\n * new Zine(el, { source, controls: { items: ['prev', 'next', 'print'] } });\n * ```\n */\nexport function defineControl(def: ControlDef): ControlDef {\n registry.set(def.id, def);\n return def;\n}\n\n/** Look up a registered control. */\nexport function getControl(id: string): ControlDef | undefined {\n return registry.get(id);\n}\n\n/**\n * Turn a layout entry into a concrete definition. A bare string names a registered control; an\n * object with only some fields is layered over the registered one, so `{ id: 'next', title: 'Go\n * on' }` relabels the built-in without reimplementing it.\n */\nexport function resolveControl(item: ControlItem): ControlDef {\n if (typeof item === 'string') {\n const found = registry.get(item);\n if (!found) {\n throw new Error(\n `controls: unknown control '${item}'. Register it with defineControl() or pass a definition object.`,\n );\n }\n return found;\n }\n const base = registry.get(item.id);\n if (!base) return item as ControlDef;\n return { ...base, ...item };\n}\n\n/** The toolbar shown when `items` is not given. */\nexport const DEFAULT_ITEMS: readonly ControlItem[] = [\n 'prev',\n 'pageInput',\n 'next',\n '|',\n 'zoomOut',\n 'zoomIn',\n 'search',\n 'share',\n 'menu',\n 'fullscreen',\n];\n","/**\n * Where a reader can send a link, and how each service wants it.\n *\n * These are plain share-intent URLs — no SDKs, no third-party scripts, nothing that could track\n * the reader before they choose to share. Each brand mark is drawn from its own official glyph;\n * they are filled shapes rather than the stroked outlines used elsewhere in the toolbar, so they\n * carry `fill=\"currentColor\"` and no stroke.\n */\nexport interface Social {\n id: string;\n label: string;\n /** Inner SVG markup for a 24x24 viewBox, filled rather than stroked. */\n icon: string;\n href(url: string, title: string): string;\n}\n\nconst e = encodeURIComponent;\n\nexport const SOCIALS: readonly Social[] = [\n {\n id: 'facebook',\n label: 'Facebook',\n icon: '<path fill=\"currentColor\" stroke=\"none\" d=\"M22 12a10 10 0 1 0-11.56 9.88v-6.99H7.9V12h2.54V9.8c0-2.5 1.49-3.89 3.77-3.89 1.1 0 2.24.2 2.24.2v2.46h-1.26c-1.24 0-1.63.77-1.63 1.56V12h2.78l-.45 2.89h-2.33v6.99A10 10 0 0 0 22 12Z\"/>',\n href: (url) => `https://www.facebook.com/sharer/sharer.php?u=${e(url)}`,\n },\n {\n id: 'x',\n label: 'X (Twitter)',\n icon: '<path fill=\"currentColor\" stroke=\"none\" d=\"M17.53 3h3.06l-6.69 7.64L21.75 21h-6.16l-4.82-6.3L5.24 21H2.18l7.15-8.17L2.25 3h6.32l4.36 5.77L17.53 3Zm-1.07 16.17h1.69L7.62 4.73H5.8l10.66 14.44Z\"/>',\n href: (url, title) => `https://twitter.com/intent/tweet?url=${e(url)}&text=${e(title)}`,\n },\n {\n id: 'linkedin',\n label: 'LinkedIn',\n icon: '<path fill=\"currentColor\" stroke=\"none\" d=\"M20.45 20.45h-3.56v-5.57c0-1.33-.02-3.04-1.85-3.04-1.85 0-2.14 1.45-2.14 2.94v5.67H9.35V9h3.41v1.56h.05a3.74 3.74 0 0 1 3.37-1.85c3.6 0 4.27 2.37 4.27 5.46v6.28ZM5.34 7.43a2.07 2.07 0 1 1 0-4.13 2.07 2.07 0 0 1 0 4.13Zm1.78 13.02H3.55V9h3.57v11.45ZM22.22 0H1.77C.79 0 0 .77 0 1.72v20.56C0 23.23.79 24 1.77 24h20.45c.98 0 1.78-.77 1.78-1.72V1.72C24 .77 23.2 0 22.22 0Z\"/>',\n href: (url) => `https://www.linkedin.com/sharing/share-offsite/?url=${e(url)}`,\n },\n {\n id: 'whatsapp',\n label: 'WhatsApp',\n icon: '<path fill=\"currentColor\" stroke=\"none\" d=\"M12.04 2a9.9 9.9 0 0 0-8.5 14.9L2 22l5.25-1.38A9.9 9.9 0 1 0 12.04 2Zm5.8 14.06c-.25.7-1.44 1.33-1.99 1.38-.53.05-1.02.24-3.44-.72-2.9-1.14-4.73-4.1-4.87-4.29-.14-.19-1.16-1.54-1.16-2.94s.73-2.08 1-2.37c.26-.28.57-.35.76-.35h.55c.17 0 .42-.07.65.5.24.58.8 2 .87 2.14.07.14.12.31.02.5-.09.19-.14.3-.28.47l-.42.48c-.14.14-.28.29-.12.57.16.28.7 1.16 1.51 1.88 1.04.93 1.91 1.21 2.19 1.35.28.15.44.12.6-.07.17-.19.7-.81.88-1.09.19-.28.37-.23.63-.14.25.1 1.63.77 1.9.91.29.14.48.21.55.33.07.11.07.67-.18 1.37Z\"/>',\n href: (url, title) => `https://api.whatsapp.com/send?text=${e(`${title} ${url}`)}`,\n },\n {\n id: 'pinterest',\n label: 'Pinterest',\n icon: '<path fill=\"currentColor\" stroke=\"none\" d=\"M12 2a10 10 0 0 0-3.65 19.31c-.09-.78-.17-1.98.03-2.83.19-.78 1.2-4.98 1.2-4.98s-.3-.61-.3-1.52c0-1.42.82-2.48 1.85-2.48.87 0 1.3.66 1.3 1.44 0 .88-.56 2.2-.85 3.42-.24 1.02.51 1.86 1.52 1.86 1.83 0 3.23-1.93 3.23-4.7 0-2.46-1.77-4.18-4.29-4.18-2.92 0-4.64 2.19-4.64 4.46 0 .88.34 1.83.76 2.35a.3.3 0 0 1 .07.29l-.28 1.16c-.05.19-.15.23-.34.14-1.28-.6-2.08-2.47-2.08-3.98 0-3.24 2.35-6.21 6.79-6.21 3.56 0 6.33 2.54 6.33 5.93 0 3.54-2.23 6.39-5.32 6.39-1.04 0-2.02-.54-2.35-1.18l-.64 2.44c-.23.89-.86 2.01-1.28 2.69A10 10 0 1 0 12 2Z\"/>',\n href: (url, title) => `https://pinterest.com/pin/create/button/?url=${e(url)}&description=${e(title)}`,\n },\n {\n id: 'email',\n label: 'Email',\n icon: '<path fill=\"currentColor\" stroke=\"none\" d=\"M20 4H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2Zm0 4.24-7.47 4.67a1 1 0 0 1-1.06 0L4 8.24V6.4l8 5 8-5v1.84Z\"/>',\n href: (url, title) => `mailto:?subject=${e(title)}&body=${e(url)}`,\n },\n];\n","/**\n * A small QR encoder, enough to turn a URL into a scannable grid.\n *\n * Written rather than pulled in so the package keeps its \"no dependencies\" promise, and so no\n * reader's document URL is handed to a third-party image service to be logged. Deliberately\n * narrow: byte mode, error-correction level M, versions 1-10 (up to 271 characters at level M),\n * which covers any sane page URL. Longer input throws rather than silently producing a code that\n * will not scan.\n */\n\n/** Data codewords available per version at error-correction level M, versions 1-10. */\nconst DATA_CODEWORDS = [16, 28, 44, 64, 86, 108, 124, 154, 182, 216];\n/** Error-correction codewords per block, level M, versions 1-10. */\nconst EC_PER_BLOCK = [10, 16, 26, 18, 24, 16, 18, 22, 22, 26];\n/** How many EC blocks the data is split into, level M, versions 1-10. */\nconst BLOCKS = [1, 1, 1, 2, 2, 4, 4, 4, 5, 5];\n/** Where alignment patterns sit, per version (empty for version 1). */\nconst ALIGNMENT = [\n [],\n [6, 18],\n [6, 22],\n [6, 26],\n [6, 30],\n [6, 34],\n [6, 22, 38],\n [6, 24, 42],\n [6, 26, 46],\n [6, 28, 50],\n];\n\n// Galois field tables for GF(256), used by the Reed-Solomon error correction.\nconst EXP = new Uint8Array(512);\nconst LOG = new Uint8Array(256);\nfor (let i = 0, x = 1; i < 255; i++) {\n EXP[i] = x;\n LOG[x] = i;\n x <<= 1;\n if (x & 0x100) x ^= 0x11d; // the QR field's primitive polynomial\n}\nfor (let i = 255; i < 512; i++) EXP[i] = EXP[i - 255]!;\n\nconst mul = (a: number, b: number): number =>\n a === 0 || b === 0 ? 0 : EXP[(LOG[a]! + LOG[b]!) % 255]!;\n\n/** The generator polynomial for `degree` error-correction codewords. */\nfunction generator(degree: number): Uint8Array {\n let poly = new Uint8Array([1]);\n for (let i = 0; i < degree; i++) {\n const next = new Uint8Array(poly.length + 1);\n for (let j = 0; j < poly.length; j++) {\n // Written as explicit reads: a compound assignment on an indexed element is what\n // noUncheckedIndexedAccess objects to, since the target is possibly-undefined.\n next[j] = next[j]! ^ poly[j]!;\n next[j + 1] = next[j + 1]! ^ mul(poly[j]!, EXP[i]!);\n }\n poly = next;\n }\n return poly;\n}\n\n/** Reed-Solomon remainder: the error-correction codewords for one block. */\nfunction ecBlock(data: Uint8Array, count: number): Uint8Array {\n const gen = generator(count);\n const out = new Uint8Array(count);\n for (const byte of data) {\n const factor = byte ^ out[0]!;\n out.copyWithin(0, 1);\n out[count - 1] = 0;\n if (factor !== 0) {\n for (let i = 0; i < count; i++) out[i] = out[i]! ^ mul(gen[i + 1]!, factor);\n }\n }\n return out;\n}\n\n/** The 15-bit format string for level M and a mask, with its BCH check bits. */\nfunction formatBits(mask: number): number {\n const data = (0b00 << 3) | mask; // 00 = level M\n let rem = data;\n for (let i = 0; i < 10; i++) rem = (rem << 1) ^ ((rem >>> 9) * 0x537);\n return ((data << 10) | rem) ^ 0x5412;\n}\n\ntype Grid = { size: number; modules: Uint8Array; reserved: Uint8Array };\n\nconst at = (g: Grid, x: number, y: number): number => g.modules[y * g.size + x]!;\nconst set = (g: Grid, x: number, y: number, dark: boolean, reserve = true): void => {\n g.modules[y * g.size + x] = dark ? 1 : 0;\n if (reserve) g.reserved[y * g.size + x] = 1;\n};\n\nfunction placeFinder(g: Grid, cx: number, cy: number): void {\n for (let dy = -1; dy <= 7; dy++) {\n for (let dx = -1; dx <= 7; dx++) {\n const x = cx + dx;\n const y = cy + dy;\n if (x < 0 || y < 0 || x >= g.size || y >= g.size) continue;\n const d = Math.max(Math.abs(dx - 3), Math.abs(dy - 3));\n set(g, x, y, d !== 2 && d <= 3);\n }\n }\n}\n\n/** Encode `text` as a QR matrix: a square of 0/1 by row. */\nexport function encodeQr(text: string): { size: number; modules: Uint8Array } {\n const bytes = new TextEncoder().encode(text);\n const version = DATA_CODEWORDS.findIndex((cap) => bytes.length + 2 <= cap) + 1;\n if (version === 0) {\n throw new Error(`qr: ${bytes.length} bytes is too long for this encoder (max 214).`);\n }\n\n // --- bit stream: mode, length, payload, terminator, padding ---\n const capacity = DATA_CODEWORDS[version - 1]!;\n const bits: number[] = [];\n const push = (value: number, width: number): void => {\n for (let i = width - 1; i >= 0; i--) bits.push((value >>> i) & 1);\n };\n push(0b0100, 4); // byte mode\n push(bytes.length, version < 10 ? 8 : 16);\n for (const byte of bytes) push(byte, 8);\n push(0, Math.min(4, capacity * 8 - bits.length)); // terminator\n while (bits.length % 8) bits.push(0);\n const data = new Uint8Array(capacity);\n for (let i = 0; i < bits.length; i += 8) {\n let byte = 0;\n for (let b = 0; b < 8; b++) byte = (byte << 1) | bits[i + b]!;\n data[i / 8] = byte;\n }\n for (let i = bits.length / 8, pad = 0; i < capacity; i++, pad++) {\n data[i] = pad % 2 === 0 ? 0xec : 0x11; // the spec's alternating pad bytes\n }\n\n // --- split into blocks, compute EC, interleave ---\n const blockCount = BLOCKS[version - 1]!;\n const ecCount = EC_PER_BLOCK[version - 1]!;\n const shortLen = Math.floor(capacity / blockCount);\n const longCount = capacity % blockCount;\n const dataBlocks: Uint8Array[] = [];\n const ecBlocks: Uint8Array[] = [];\n for (let i = 0, offset = 0; i < blockCount; i++) {\n const len = shortLen + (i >= blockCount - longCount ? 1 : 0);\n const block = data.subarray(offset, offset + len);\n offset += len;\n dataBlocks.push(block);\n ecBlocks.push(ecBlock(block, ecCount));\n }\n const codewords: number[] = [];\n for (let i = 0; i < shortLen + 1; i++) {\n for (const block of dataBlocks) if (i < block.length) codewords.push(block[i]!);\n }\n for (let i = 0; i < ecCount; i++) {\n for (const block of ecBlocks) codewords.push(block[i]!);\n }\n\n // --- lay out the matrix ---\n const size = version * 4 + 17;\n const g: Grid = {\n size,\n modules: new Uint8Array(size * size),\n reserved: new Uint8Array(size * size),\n };\n placeFinder(g, 0, 0);\n placeFinder(g, size - 7, 0);\n placeFinder(g, 0, size - 7);\n for (let i = 8; i < size - 8; i++) {\n const dark = i % 2 === 0; // timing patterns\n set(g, i, 6, dark);\n set(g, 6, i, dark);\n }\n for (const ax of ALIGNMENT[version - 1]!) {\n for (const ay of ALIGNMENT[version - 1]!) {\n // Alignment patterns skip the corners already held by finders.\n if ((ax < 9 && ay < 9) || (ax < 9 && ay > size - 10) || (ax > size - 10 && ay < 9)) continue;\n for (let dy = -2; dy <= 2; dy++) {\n for (let dx = -2; dx <= 2; dx++) {\n set(g, ax + dx, ay + dy, Math.max(Math.abs(dx), Math.abs(dy)) !== 1);\n }\n }\n }\n }\n set(g, 8, size - 8, true); // the always-dark module\n // Reserve the format areas so data does not land in them.\n for (let i = 0; i < 9; i++) {\n if (i !== 6) set(g, i, 8, false), set(g, 8, i, false);\n }\n for (let i = 0; i < 8; i++) set(g, size - 1 - i, 8, false), set(g, 8, size - 1 - i, false);\n set(g, 8, size - 8, true);\n\n // --- weave the codewords in, masking as we go (mask 0: (x + y) % 2) ---\n let bit = 0;\n const total = codewords.length * 8;\n for (let right = size - 1; right >= 1; right -= 2) {\n if (right === 6) right = 5; // the vertical timing column is skipped\n for (let step = 0; step < size; step++) {\n for (let col = 0; col < 2; col++) {\n const x = right - col;\n const upward = ((right + 1) & 2) === 0;\n const y = upward ? size - 1 - step : step;\n if (g.reserved[y * size + x]) continue;\n let dark = false;\n if (bit < total) {\n dark = ((codewords[bit >>> 3]! >>> (7 - (bit & 7))) & 1) === 1;\n bit++;\n }\n if ((x + y) % 2 === 0) dark = !dark; // mask 0\n set(g, x, y, dark, false);\n }\n }\n }\n\n // --- format information, now that the mask is known ---\n const format = formatBits(0);\n for (let i = 0; i < 15; i++) {\n const dark = ((format >>> i) & 1) === 1;\n // Around the top-left finder...\n const a = i < 6 ? i : i < 8 ? i + 1 : 8;\n const b = i < 8 ? 8 : i < 9 ? 7 : 14 - i;\n set(g, a, 8, dark);\n set(g, 8, b, dark);\n // ...and the copy split between the other two.\n if (i < 8) set(g, size - 1 - i, 8, dark);\n else set(g, 8, size - 15 + i, dark);\n }\n set(g, 8, size - 8, true);\n\n return { size, modules: g.modules };\n}\n\n/** Render a QR matrix as an SVG string, sized to `px`. */\nexport function qrSvg(text: string, px: number): string {\n const { size, modules } = encodeQr(text);\n let path = '';\n for (let y = 0; y < size; y++) {\n for (let x = 0; x < size; x++) {\n if (modules[y * size + x]) path += `M${x} ${y}h1v1h-1z`;\n }\n }\n const quiet = 2; // the spec asks for 4; 2 scans fine and wastes less space on screen\n const box = size + quiet * 2;\n return `<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"${px}\" height=\"${px}\" viewBox=\"0 0 ${box} ${box}\" shape-rendering=\"crispEdges\"><rect width=\"${box}\" height=\"${box}\" fill=\"#fff\"/><g transform=\"translate(${quiet} ${quiet})\" fill=\"#000\">${`<path d=\"${path}\"/>`}</g></svg>`;\n}\n","import { createIcon, ICONS } from './icons';\nimport { SOCIALS } from './socials';\nimport { qrSvg } from './qr';\nimport type { Zine } from '../zine';\n\n/** QR edge length in CSS px. */\nconst QR_SIZE = 132;\n/** How long the copy button confirms for. */\nconst COPIED_MS = 1600;\n\n/**\n * The share dialog: a QR code, the link, a copy button and the usual social destinations.\n *\n * Loaded on demand — the whole module, its icons and the QR encoder arrive only when a reader\n * presses Share, so a book nobody shares pays nothing for it.\n */\nexport class ShareDialog {\n #doc: Document;\n #backdrop: HTMLElement;\n #dialog: HTMLElement;\n #lastFocus: Element | null;\n #timer: ReturnType<typeof setTimeout> | null = null;\n #onKey: (e: KeyboardEvent) => void;\n\n constructor(zine: Zine, container: HTMLElement) {\n const doc = container.ownerDocument!;\n this.#doc = doc;\n this.#lastFocus = doc.activeElement;\n\n const url = zine.pageLink();\n const title = doc.title || 'Flipbook';\n\n this.#backdrop = doc.createElement('div');\n this.#backdrop.className = 'zine-share-backdrop';\n this.#backdrop.addEventListener('pointerdown', (e) => {\n if (e.target === this.#backdrop) this.close();\n });\n\n this.#dialog = doc.createElement('div');\n this.#dialog.className = 'zine-share';\n this.#dialog.setAttribute('role', 'dialog');\n this.#dialog.setAttribute('aria-modal', 'true');\n this.#dialog.setAttribute('aria-label', 'Share');\n this.#backdrop.appendChild(this.#dialog);\n\n const head = doc.createElement('div');\n head.className = 'zine-share-head';\n const heading = doc.createElement('strong');\n heading.textContent = 'Share';\n const close = doc.createElement('button');\n close.type = 'button';\n close.className = 'zine-share-close';\n close.setAttribute('aria-label', 'Close');\n close.appendChild(createIcon(doc, ICONS.close));\n close.addEventListener('click', () => this.close());\n head.append(heading, close);\n\n this.#dialog.append(head, this.#linkRow(doc, url), this.#socialRow(doc, url, title));\n const qr = this.#qr(doc, url);\n if (qr) this.#dialog.insertBefore(qr, this.#dialog.children[1]!);\n\n container.ownerDocument.body.appendChild(this.#backdrop);\n\n this.#onKey = (e): void => {\n if (e.key === 'Escape') this.close();\n if (e.key === 'Tab') this.#trapFocus(e);\n };\n this.#backdrop.addEventListener('keydown', this.#onKey);\n close.focus();\n }\n\n /** The QR, or nothing if the URL is too long to encode — better no code than a broken one. */\n #qr(doc: Document, url: string): HTMLElement | null {\n if (!url) return null;\n try {\n const wrap = doc.createElement('div');\n wrap.className = 'zine-share-qr';\n wrap.innerHTML = qrSvg(url, QR_SIZE);\n wrap.setAttribute('aria-label', 'QR code for this page');\n wrap.setAttribute('role', 'img');\n return wrap;\n } catch {\n return null;\n }\n }\n\n #linkRow(doc: Document, url: string): HTMLElement {\n const row = doc.createElement('div');\n row.className = 'zine-share-link';\n const input = doc.createElement('input');\n input.type = 'text';\n input.readOnly = true;\n input.value = url;\n input.setAttribute('aria-label', 'Link to this page');\n input.addEventListener('focus', () => input.select());\n\n const copy = doc.createElement('button');\n copy.type = 'button';\n copy.className = 'zine-share-copy';\n copy.textContent = 'Copy';\n copy.addEventListener('click', () => {\n void this.#copy(url, copy);\n });\n row.append(input, copy);\n return row;\n }\n\n async #copy(url: string, button: HTMLButtonElement): Promise<void> {\n try {\n await navigator.clipboard?.writeText(url);\n button.textContent = 'Copied';\n } catch {\n button.textContent = 'Press Ctrl+C';\n }\n if (this.#timer) clearTimeout(this.#timer);\n this.#timer = setTimeout(() => {\n button.textContent = 'Copy';\n }, COPIED_MS);\n }\n\n #socialRow(doc: Document, url: string, title: string): HTMLElement {\n const row = doc.createElement('div');\n row.className = 'zine-share-socials';\n for (const social of SOCIALS) {\n const link = doc.createElement('a');\n link.className = 'zine-share-social';\n link.href = social.href(url, title);\n link.title = social.label;\n link.setAttribute('aria-label', `Share on ${social.label}`);\n if (social.id !== 'email') {\n link.target = '_blank';\n link.rel = 'noopener noreferrer';\n }\n link.appendChild(createIcon(doc, social.icon));\n row.appendChild(link);\n }\n return row;\n }\n\n /** Keep Tab inside the dialog while it is open. */\n #trapFocus(event: KeyboardEvent): void {\n const focusable = [\n ...this.#dialog.querySelectorAll<HTMLElement>('button, a[href], input'),\n ].filter((el) => !el.hasAttribute('disabled'));\n if (focusable.length === 0) return;\n const first = focusable[0]!;\n const last = focusable.at(-1)!;\n const active = this.#doc.activeElement;\n if (event.shiftKey && active === first) {\n last.focus();\n event.preventDefault();\n } else if (!event.shiftKey && active === last) {\n first.focus();\n event.preventDefault();\n }\n }\n\n close(): void {\n this.destroy();\n }\n\n destroy(): void {\n if (this.#timer) clearTimeout(this.#timer);\n this.#timer = null;\n this.#backdrop.removeEventListener('keydown', this.#onKey);\n this.#backdrop.remove();\n // Hand focus back to whatever opened the dialog.\n (this.#lastFocus as HTMLElement | null)?.focus?.();\n }\n}\n","import { ICONS } from './icons';\nimport { defineControl } from './registry';\nimport type { ControlContext } from './types';\n\n\n/** Zoom step per click: two clicks double the scale. */\nconst ZOOM_STEP = Math.SQRT2;\n\nconst isFullscreen = (ctx: ControlContext): boolean => {\n const doc = ctx.zine.container.ownerDocument;\n return doc?.fullscreenElement === ctx.zine.container;\n};\n\n/**\n * Register the stock controls. Called once as the toolbar chunk loads, so the icon set and these\n * definitions stay out of the base bundle.\n *\n * `pageInput` and `search` are not here: both need the toolbar instance itself (one builds an\n * input, the other opens an anchored panel), so the toolbar registers them.\n */\nexport function registerBuiltins(): void {\n defineControl({\n id: 'prev',\n title: 'Previous page',\n icon: ICONS.prev,\n isDisabled: (ctx) => !ctx.zine.canFlipPrev(),\n action: (ctx) => ctx.zine.flipPrev(),\n });\n\n defineControl({\n id: 'next',\n title: 'Next page',\n icon: ICONS.next,\n isDisabled: (ctx) => !ctx.zine.canFlipNext(),\n action: (ctx) => ctx.zine.flipNext(),\n });\n\n // The chevrons point the way the book travels, which reverses in RTL — same as the page\n // arrows flanking the book.\n const rtl = (ctx: ControlContext): boolean => ctx.zine.getDirection() === 'rtl';\n\n defineControl({\n id: 'first',\n title: 'First page',\n icon: (ctx) => (rtl(ctx) ? ICONS.last : ICONS.first),\n isDisabled: (ctx) => !ctx.zine.canFlipPrev(),\n action: (ctx) => {\n ctx.zine.flipTo(0);\n ctx.close();\n },\n });\n\n defineControl({\n id: 'last',\n title: 'Last page',\n icon: (ctx) => (rtl(ctx) ? ICONS.first : ICONS.last),\n isDisabled: (ctx) => !ctx.zine.canFlipNext(),\n action: (ctx) => {\n ctx.zine.flipTo(ctx.zine.getPageCount() - 1);\n ctx.close();\n },\n });\n\n defineControl({\n id: 'zoomIn',\n title: 'Zoom in',\n icon: ICONS.zoomIn,\n isDisabled: (ctx) => ctx.zine.getZoom() >= ctx.zine.getMaxZoom() - 1e-6,\n action: (ctx) => ctx.zine.setZoom(ctx.zine.getZoom() * ZOOM_STEP),\n });\n\n defineControl({\n id: 'zoomOut',\n title: 'Zoom out',\n icon: ICONS.zoomOut,\n isDisabled: (ctx) => ctx.zine.getZoom() <= 1 + 1e-6,\n action: (ctx) => ctx.zine.setZoom(ctx.zine.getZoom() / ZOOM_STEP),\n });\n\n defineControl({\n id: 'fullscreen',\n title: 'Fullscreen',\n icon: ICONS.fullscreen,\n isVisible: (ctx) => typeof ctx.zine.container.requestFullscreen === 'function',\n isActive: isFullscreen,\n action: (ctx) => {\n const doc = ctx.zine.container.ownerDocument;\n if (isFullscreen(ctx)) void doc?.exitFullscreen?.();\n else void ctx.zine.container.requestFullscreen?.();\n ctx.close();\n },\n });\n\n defineControl({\n id: 'share',\n title: 'Share',\n icon: ICONS.share,\n action: (ctx) => {\n ctx.close();\n // The dialog, its brand marks and the QR encoder are a chunk of their own: a book nobody\n // shares never downloads any of it.\n void import('./share')\n .then(({ ShareDialog }) => new ShareDialog(ctx.zine, ctx.zine.container))\n .catch(() => {\n // No dialog, so fall back to the plain behaviour rather than doing nothing.\n void navigator.clipboard?.writeText(ctx.zine.pageLink()).catch(() => {});\n });\n },\n });\n\n defineControl({\n id: 'download',\n title: 'Download PDF',\n icon: ICONS.download,\n // Hidden for image books and for PDFs opened from a caller-owned pdf.js document, which\n // have no file of their own to save.\n isVisible: (ctx) => ctx.zine.canDownload(),\n action: (ctx) => {\n void ctx.zine.download();\n ctx.close();\n },\n });\n\n defineControl({\n id: 'spread',\n // Says what pressing it will do, not what the book is doing now, and in the reader's terms —\n // \"spread mode\" is the library's word for it, not theirs.\n title: (ctx) => (ctx.zine.isSinglePage() ? 'Show two pages' : 'Show one page'),\n icon: (ctx) => (ctx.zine.isSinglePage() ? ICONS.twoPages : ICONS.onePage),\n // Hidden while a narrow container is forcing one page: pressing it could not honour two.\n isVisible: (ctx) => !ctx.zine.isResponsiveSingle(),\n action: (ctx) => {\n ctx.zine.toggleSpreadMode();\n ctx.close();\n },\n });\n\n defineControl({\n id: 'print',\n title: 'Print',\n icon: ICONS.print,\n // Same reach as download: there has to be an original document to print.\n isVisible: (ctx) => ctx.zine.canPrint(),\n action: (ctx) => {\n void ctx.zine.print();\n ctx.close();\n },\n });\n\n defineControl({\n id: 'menu',\n title: 'More',\n icon: ICONS.menu,\n // Share and fullscreen sit on the bar itself by default, so the overflow holds what is left.\n children: ['first', 'last', 'spread', 'thumbnails', 'outline', 'print', 'download'],\n });\n}\n","/**\n * The toolbar's stylesheet, injected once per document.\n *\n * The rest of the library styles elements inline, but a toolbar needs `:hover`, `:focus-visible`\n * and `:disabled` — states inline styles cannot express — so this is the one place a `<style>`\n * element is warranted. Everything is scoped under `.zine-controls`, and the colours come from\n * custom properties so a consumer can retheme without overriding rules.\n */\nconst STYLE_ID = 'zine-controls-style';\n\nexport const CSS = `\n/* Docked mode wraps the book so the bar can sit beside it without shrinking the container,\n whose measured box the renderer and hit-testing both depend on.\n The wrapper deliberately does not stretch or grow its children: the container keeps whatever\n width, aspect-ratio and auto-margins the consumer's own CSS gave it. */\n.zine-controls-wrap { display: flex; }\n/* Stacked: children keep their own width (so a percentage or auto-margin still resolves against\n the wrapper) and take only the height they ask for. */\n.zine-controls-wrap-top,\n.zine-controls-wrap-bottom { flex-direction: column; align-items: stretch; }\n/* Side by side: the bar is only as wide as its buttons, and both are vertically centred. */\n.zine-controls-wrap-left,\n.zine-controls-wrap-right { flex-direction: row; align-items: center; }\n/* min-height:0 matters as much as min-width here. A flex item's automatic minimum size floors it\n at its content, so once the canvas has grown for a taller layout the book cannot shrink back —\n its aspect-ratio is restored but ignored, leaving the extra height behind. */\n.zine-controls-wrap > * { flex: 0 0 auto; min-width: 0; min-height: 0; }\n\n.zine-controls {\n position: relative;\n display: flex;\n gap: 4px;\n padding: 5px;\n z-index: 2;\n box-sizing: border-box;\n font: 500 12px/1.2 system-ui, sans-serif;\n color: var(--zine-controls-fg, #f4f4f5);\n touch-action: auto;\n -webkit-user-select: none;\n user-select: none;\n}\n.zine-controls-docked { flex: 0 0 auto; justify-content: center; align-items: center; }\n.zine-controls-floating {\n position: absolute;\n /* Transparent to the book except on the buttons themselves, so gaps stay draggable. */\n pointer-events: none;\n}\n.zine-controls-bar {\n display: flex;\n align-items: center;\n gap: 1px;\n padding: 3px;\n border-radius: 8px;\n pointer-events: auto;\n background: var(--zine-controls-bg, rgba(24, 24, 27, 0.82));\n backdrop-filter: blur(8px);\n}\n/* Floating: lifted off the page it covers. Docked: flat, with an outline so it reads as a\n control strip rather than a shadow hanging in empty space. */\n.zine-controls-floating .zine-controls-bar { box-shadow: 0 2px 12px rgba(0, 0, 0, 0.28); }\n.zine-controls-docked .zine-controls-bar {\n border: 1px solid var(--zine-controls-hover, rgba(255, 255, 255, 0.14));\n}\n.zine-controls-floating.zine-controls-bottom { inset: auto 0 0 0; justify-content: center; }\n.zine-controls-floating.zine-controls-top { inset: 0 0 auto 0; justify-content: center; }\n.zine-controls-floating.zine-controls-left { inset: 0 auto 0 0; align-items: center; }\n.zine-controls-floating.zine-controls-right { inset: 0 0 0 auto; align-items: center; }\n/* A bar on a vertical edge stacks its buttons, docked or floating. */\n.zine-controls-left .zine-controls-bar,\n.zine-controls-right .zine-controls-bar { flex-direction: column; }\n\n.zine-controls-btn {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n width: 26px;\n height: 26px;\n padding: 0;\n border: 0;\n border-radius: 6px;\n background: transparent;\n color: inherit;\n cursor: pointer;\n font: inherit;\n}\n.zine-controls-btn svg { width: 15px; height: 15px; }\n.zine-controls-btn:hover:not(:disabled) { background: var(--zine-controls-hover, rgba(255,255,255,0.14)); }\n.zine-controls-btn:focus-visible {\n outline: 2px solid var(--zine-controls-accent, #7dd3fc);\n outline-offset: 1px;\n}\n.zine-controls-btn:disabled { opacity: 0.38; cursor: default; }\n/* A custom widget cannot always be disabled itself, so it is marked instead and reads the same. */\n.zine-controls-off { opacity: 0.38; }\n.zine-controls-off[aria-disabled='true'] { pointer-events: none; }\n.zine-controls-btn[aria-pressed=\"true\"],\n.zine-controls-btn[aria-expanded=\"true\"] { background: var(--zine-controls-hover, rgba(255,255,255,0.14)); }\n\n.zine-controls-sep {\n width: 1px;\n align-self: stretch;\n margin: 3px 3px;\n background: currentColor;\n opacity: 0.22;\n}\n.zine-controls-left .zine-controls-sep,\n.zine-controls-right .zine-controls-sep { width: auto; height: 1px; margin: 3px 3px; }\n\n.zine-controls-page {\n display: inline-flex;\n align-items: center;\n gap: 3px;\n padding: 0 3px;\n pointer-events: auto;\n white-space: nowrap;\n}\n.zine-controls-page input {\n width: 2.2em;\n padding: 2px 3px;\n border: 1px solid var(--zine-controls-hover, rgba(255,255,255,0.2));\n border-radius: 4px;\n background: rgba(0, 0, 0, 0.25);\n color: inherit;\n font: inherit;\n text-align: center;\n -moz-appearance: textfield;\n}\n.zine-controls-page input::-webkit-outer-spin-button,\n.zine-controls-page input::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; }\n.zine-controls-page input:focus-visible {\n outline: 2px solid var(--zine-controls-accent, #7dd3fc);\n outline-offset: 0;\n}\n\n.zine-controls-menu {\n position: absolute;\n display: flex;\n flex-direction: column;\n gap: 1px;\n min-width: 152px;\n padding: 4px;\n border-radius: 8px;\n pointer-events: auto;\n background: var(--zine-controls-bg, rgba(24, 24, 27, 0.94));\n box-shadow: 0 6px 22px rgba(0, 0, 0, 0.36);\n backdrop-filter: blur(8px);\n}\n.zine-controls-menu .zine-controls-btn {\n width: 100%;\n height: auto;\n gap: 8px;\n padding: 6px 8px;\n justify-content: flex-start;\n}\n\n/* Search shares the rail: a query field pinned at the top over a scrolling list of hits. */\n.zine-search { gap: 0; overflow: hidden; }\n.zine-search-input {\n flex: 0 0 auto;\n width: 100%;\n padding: 6px 8px;\n border: 1px solid var(--zine-controls-hover, rgba(255,255,255,0.2));\n border-radius: 6px;\n background: rgba(0, 0, 0, 0.25);\n color: inherit;\n font: inherit;\n box-sizing: border-box;\n}\n.zine-search-hits {\n flex: 1 1 auto;\n overflow-y: auto;\n overscroll-behavior: contain;\n margin-top: 5px;\n scrollbar-width: thin;\n}\n.zine-search-hit {\n display: block;\n width: 100%;\n padding: 6px 8px;\n border: 0;\n border-radius: 5px;\n background: transparent;\n color: inherit;\n font: inherit;\n text-align: left;\n cursor: pointer;\n box-sizing: border-box;\n}\n.zine-search-hit:hover { background: var(--zine-controls-hover, rgba(255,255,255,0.14)); }\n.zine-search-hit:focus-visible {\n outline: 2px solid var(--zine-controls-accent, #7dd3fc);\n outline-offset: -2px;\n}\n.zine-search-page { display: block; font-size: 0.9em; opacity: 0.85; }\n.zine-search-hit small {\n display: block;\n margin-top: 2px;\n opacity: 0.62;\n line-height: 1.35;\n overflow-wrap: anywhere;\n}\n\n/* Page-turn arrows flanking the book. Like the docked toolbar and the side panels, they sit\n outside the container so they never shrink the book or intercept its gestures. */\n.zine-arrows-wrap {\n display: flex;\n align-items: center;\n gap: 4px;\n min-width: 0;\n}\n.zine-arrows-wrap > *:not(.zine-arrow) { flex: 1 1 auto; min-width: 0; min-height: 0; }\n.zine-arrow {\n flex: 0 0 auto;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n width: 40px;\n height: 40px;\n padding: 0;\n border: 0;\n border-radius: 50%;\n background: var(--zine-controls-bg, rgba(24, 24, 27, 0.82));\n color: var(--zine-controls-fg, #f4f4f5);\n cursor: pointer;\n backdrop-filter: blur(8px);\n -webkit-user-select: none;\n user-select: none;\n}\n.zine-arrow svg { width: 22px; height: 22px; }\n.zine-arrow:hover:not(:disabled) { background: var(--zine-controls-hover, rgba(255,255,255,0.22)); }\n.zine-arrow:focus-visible {\n outline: 2px solid var(--zine-controls-accent, #7dd3fc);\n outline-offset: 2px;\n}\n/* Nothing to turn to: invisible, but still occupying its slot so the book does not slide across\n as the reader reaches a cover. */\n.zine-arrow-hidden { visibility: hidden; }\n/* No room to flank on a narrow screen; the toolbar's own prev/next still work. */\n@media (max-width: 640px) {\n .zine-arrow { display: none; }\n}\n@media (prefers-reduced-motion: no-preference) {\n .zine-arrow { transition: background 120ms ease; }\n}\n\n/* Side panels (thumbnails, outline). The rail wraps the book and its docked toolbar so it sits\n beside them without shrinking the container the renderer measures. */\n.zine-panel-wrap { display: flex; align-items: stretch; gap: 8px; }\n\n/* The holder stretches to the book's height; the rail is absolutely positioned inside it so a\n long list scrolls rather than growing the row and running past the bottom of the book. */\n.zine-panel-holder {\n position: relative;\n flex: 0 0 auto;\n align-self: stretch;\n min-height: 0;\n}\n.zine-panel {\n position: absolute;\n inset: 0;\n display: flex;\n flex-direction: column;\n gap: 6px;\n overflow-y: auto;\n overscroll-behavior: contain;\n padding: 6px;\n box-sizing: border-box;\n border-radius: 8px;\n background: var(--zine-controls-bg, rgba(24, 24, 27, 0.82));\n color: var(--zine-controls-fg, #f4f4f5);\n font: 500 11px/1.2 system-ui, sans-serif;\n scrollbar-width: thin;\n touch-action: auto;\n -webkit-user-select: none;\n user-select: none;\n}\n/* Overlay fallback, used when the container has no parent to wrap. */\n.zine-panel-overlay { position: absolute; inset: 0 auto 0 0; z-index: 3; }\n.zine-panel-active { background: var(--zine-controls-hover, rgba(255,255,255,0.18)); }\n.zine-panel-note { padding: 8px; opacity: 0.66; line-height: 1.4; }\n\n.zine-thumbs { align-items: center; }\n\n.zine-thumbs-row {\n display: flex;\n flex-wrap: wrap;\n justify-content: center;\n gap: 2px;\n width: 100%;\n padding: 4px;\n border: 0;\n border-radius: 6px;\n background: transparent;\n color: inherit;\n font: inherit;\n cursor: pointer;\n box-sizing: border-box;\n}\n.zine-thumbs-row:hover { background: var(--zine-controls-hover, rgba(255,255,255,0.14)); }\n.zine-thumbs-row:focus-visible {\n outline: 2px solid var(--zine-controls-accent, #7dd3fc);\n outline-offset: -2px;\n}\n.zine-thumbs-row.zine-panel-active .zine-thumbs-cell {\n outline: 1px solid var(--zine-controls-accent, #7dd3fc);\n}\n\n/* Outline: a single column of headings, indented by depth. */\n.zine-outline { gap: 1px; }\n.zine-outline-row {\n display: block;\n width: 100%;\n padding: 6px 8px;\n border: 0;\n border-radius: 5px;\n background: transparent;\n color: inherit;\n font: inherit;\n text-align: left;\n line-height: 1.35;\n cursor: pointer;\n box-sizing: border-box;\n overflow-wrap: anywhere;\n}\n.zine-outline-row:hover:not(:disabled) {\n background: var(--zine-controls-hover, rgba(255,255,255,0.14));\n}\n.zine-outline-row:focus-visible {\n outline: 2px solid var(--zine-controls-accent, #7dd3fc);\n outline-offset: -2px;\n}\n/* A heading whose destination could not be resolved: shown, but nothing to click through to. */\n.zine-outline-row:disabled { opacity: 0.5; cursor: default; }\n\n.zine-thumbs-cell {\n flex: 1 1 0;\n min-width: 0;\n min-height: 24px;\n display: flex;\n background: rgba(0, 0, 0, 0.3);\n border-radius: 2px;\n overflow: hidden;\n}\n/* A lone page in a book that pairs elsewhere (a cover, a back page) keeps one page's width and\n centres, instead of stretching across both columns. */\n.zine-thumbs-row-lone .zine-thumbs-cell { flex: 0 0 calc(50% - 1px); }\n.zine-thumbs-img { display: block; width: 100%; height: auto; }\n.zine-thumbs-caption { flex: 1 0 100%; text-align: center; opacity: 0.7; }\n\n/* Share dialog. Centred over the page rather than in the side rail: a QR and six destinations\n need more room than the rail gives, and sharing is a brief interruption, not a browsing mode. */\n.zine-share-backdrop {\n position: fixed;\n inset: 0;\n z-index: 2147483000;\n display: flex;\n align-items: center;\n justify-content: center;\n padding: 16px;\n background: rgba(0, 0, 0, 0.55);\n font: 500 13px/1.4 system-ui, sans-serif;\n color: var(--zine-controls-fg, #f4f4f5);\n}\n.zine-share {\n width: min(320px, 100%);\n max-height: 100%;\n overflow-y: auto;\n display: flex;\n flex-direction: column;\n gap: 12px;\n padding: 14px;\n border-radius: 12px;\n background: var(--zine-share-bg, #1c1c20);\n box-shadow: 0 18px 50px rgba(0, 0, 0, 0.45);\n box-sizing: border-box;\n}\n.zine-share-head { display: flex; align-items: center; justify-content: space-between; gap: 8px; }\n.zine-share-head strong { font-size: 15px; }\n.zine-share-close {\n display: inline-flex;\n width: 26px;\n height: 26px;\n align-items: center;\n justify-content: center;\n padding: 0;\n border: 0;\n border-radius: 6px;\n background: transparent;\n color: inherit;\n cursor: pointer;\n}\n.zine-share-close svg { width: 16px; height: 16px; }\n.zine-share-close:hover { background: var(--zine-controls-hover, rgba(255,255,255,0.14)); }\n\n.zine-share-qr {\n align-self: center;\n line-height: 0;\n padding: 8px;\n border-radius: 8px;\n background: #fff;\n}\n.zine-share-qr svg { display: block; }\n\n.zine-share-link { display: flex; gap: 6px; }\n.zine-share-link input {\n flex: 1 1 auto;\n min-width: 0;\n padding: 7px 9px;\n border: 1px solid var(--zine-controls-hover, rgba(255,255,255,0.2));\n border-radius: 7px;\n background: rgba(0, 0, 0, 0.3);\n color: inherit;\n font: inherit;\n}\n.zine-share-copy {\n flex: 0 0 auto;\n min-width: 74px;\n padding: 7px 12px;\n border: 0;\n border-radius: 7px;\n background: var(--zine-controls-accent, #7dd3fc);\n color: #06202c;\n font: inherit;\n font-weight: 600;\n cursor: pointer;\n}\n\n.zine-share-socials { display: flex; flex-wrap: wrap; gap: 6px; justify-content: center; }\n.zine-share-social {\n display: inline-flex;\n width: 38px;\n height: 38px;\n align-items: center;\n justify-content: center;\n border-radius: 8px;\n background: rgba(255, 255, 255, 0.08);\n color: inherit;\n text-decoration: none;\n}\n.zine-share-social svg { width: 19px; height: 19px; }\n.zine-share-social:hover { background: var(--zine-controls-hover, rgba(255,255,255,0.18)); }\n.zine-share-close:focus-visible,\n.zine-share-copy:focus-visible,\n.zine-share-social:focus-visible,\n.zine-share-link input:focus-visible {\n outline: 2px solid var(--zine-controls-accent, #7dd3fc);\n outline-offset: 2px;\n}\n\n@media (prefers-reduced-motion: no-preference) {\n .zine-controls-btn { transition: background 120ms ease; }\n}\n`;\n\n/** Add the stylesheet to `doc` if it is not already there. */\nexport function ensureStyles(doc: Document): void {\n if (doc.getElementById(STYLE_ID)) return;\n const style = doc.createElement('style');\n style.id = STYLE_ID;\n style.textContent = CSS;\n (doc.head ?? doc.documentElement)?.appendChild(style);\n}\n","/**\n * The rail beside the book that the thumbnail and outline lists both sit in.\n *\n * It exists to solve one problem shared by every such panel: the container's measured box is what\n * the renderer sizes the book from and what pointer hit-testing maps into, so a panel must not\n * live inside it. Instead the book (and its docked toolbar, if any) is wrapped in a flex row with\n * the panel as its sibling, and `destroy` unwinds that again.\n *\n * The rail is absolutely positioned inside a holder that stretches to the book's height, so a\n * long list scrolls internally instead of running past the bottom of the book.\n */\nexport class Sidebar {\n /** The scrolling list; panels append their rows here. */\n readonly root: HTMLElement;\n #holder: HTMLElement;\n #wrap: HTMLElement | null = null;\n\n constructor(\n doc: Document,\n container: HTMLElement,\n options: { className: string; label: string; width: number },\n ) {\n this.#holder = doc.createElement('div');\n this.#holder.className = 'zine-panel-holder';\n this.#holder.style.width = `${options.width}px`;\n\n this.root = doc.createElement('div');\n this.root.className = `zine-panel ${options.className}`;\n this.root.setAttribute('role', 'listbox');\n this.root.setAttribute('aria-label', options.label);\n this.#holder.appendChild(this.root);\n\n // In the overlay fallback the rail sits inside the book, where the book's own gesture\n // handlers would otherwise read a click on a row as a page tap.\n for (const type of ['pointerdown', 'pointerup', 'pointermove', 'click', 'dblclick', 'wheel']) {\n this.root.addEventListener(type, (e) => e.stopPropagation());\n }\n\n this.#place(doc, container);\n }\n\n /** Resize the rail, e.g. once a thumbnail list knows whether it needs one column or two. */\n setWidth(px: number): void {\n this.#holder.style.width = `${px}px`;\n }\n\n #place(doc: Document, container: HTMLElement): void {\n const parent = container.parentNode;\n if (!parent) {\n // Not in a document yet: overlay rather than lose the panel.\n this.#holder.classList.add('zine-panel-overlay');\n container.appendChild(this.#holder);\n return;\n }\n // A docked toolbar already wrapped the book; wrap that whole assembly so the rail sits\n // beside book *and* toolbar rather than between them.\n const existing = container.closest('.zine-controls-wrap');\n const target = (existing ?? container) as HTMLElement;\n const wrap = doc.createElement('div');\n wrap.className = 'zine-panel-wrap';\n target.parentNode!.insertBefore(wrap, target);\n wrap.append(this.#holder, target);\n this.#wrap = wrap;\n }\n\n destroy(): void {\n this.#holder.remove();\n const wrap = this.#wrap;\n if (wrap?.parentNode) {\n // The rail is gone, so what is left is the book; put it back where the wrapper was.\n while (wrap.firstChild) wrap.parentNode.insertBefore(wrap.firstChild, wrap);\n wrap.remove();\n }\n this.#wrap = null;\n }\n}\n","import { Sidebar } from './sidebar';\nimport type { Zine } from '../zine';\n\n/** Width of one page thumbnail, in px. A paired rail fits two of these side by side. */\nconst THUMB_WIDTH = 78;\n/** Padding inside the rail, per side. */\nconst RAIL_PAD = 6;\n/** Gap between the two pages of a spread. */\nconst CELL_GAP = 2;\n\n/**\n * A rail of page thumbnails beside the book.\n *\n * Rows mirror the book's own spread model, so a `double` book shows two pages per row and a\n * `single` book one — including the responsive fallback that forces single-page on a narrow\n * container. A book that mixes the two (`cover`, `book`) keeps two columns so pairs line up, and\n * centres its lone first/last page between them. Clicking a row turns to that spread.\n *\n * Pages are drawn only as they scroll into view: a long PDF would otherwise decode every page at\n * once the moment the rail opened.\n */\nexport class Thumbnails {\n #zine: Zine;\n #doc: Document;\n #bar: Sidebar;\n #rows: { el: HTMLElement; spread: number }[] = [];\n #observer: IntersectionObserver | null = null;\n #unsubscribe: (() => void)[] = [];\n\n constructor(zine: Zine, container: HTMLElement) {\n this.#zine = zine;\n const doc = container.ownerDocument!;\n this.#doc = doc;\n this.#bar = new Sidebar(doc, container, {\n className: 'zine-thumbs',\n label: 'Pages',\n width: THUMB_WIDTH + RAIL_PAD * 2,\n });\n\n this.#build();\n\n const onPage = (): void => this.#markCurrent();\n this.#unsubscribe.push(zine.on('pageChanged', onPage));\n this.#markCurrent();\n }\n\n #build(): void {\n const spreads = this.#zine.getSpreads();\n const rtl = this.#zine.getDirection() === 'rtl';\n // Two columns only if the book actually pairs pages somewhere. A wholly single-page book\n // gets a one-page-wide rail rather than a column of half-empty rows.\n const paired = spreads.some((s) => s.left !== null && s.right !== null);\n this.#bar.root.classList.toggle('zine-thumbs-solo', !paired);\n if (paired) this.#bar.setWidth(THUMB_WIDTH * 2 + CELL_GAP + RAIL_PAD * 2);\n\n for (const [index, spread] of spreads.entries()) {\n const row = this.#doc.createElement('button');\n row.type = 'button';\n row.className = 'zine-thumbs-row';\n row.setAttribute('role', 'option');\n if (rtl) row.style.flexDirection = 'row-reverse';\n\n const pages = [spread.left, spread.right].filter((p): p is number => p !== null);\n // A lone page in a book that pairs elsewhere keeps a single page's width and sits in the\n // middle, rather than stretching across both columns or hugging one side.\n if (paired && pages.length === 1) row.classList.add('zine-thumbs-row-lone');\n\n for (const page of pages) {\n const cell = this.#doc.createElement('span');\n cell.className = 'zine-thumbs-cell';\n cell.dataset.page = String(page);\n row.appendChild(cell);\n }\n\n const labels = [...pages].sort((a, b) => a - b).map((p) => p + 1);\n row.setAttribute(\n 'aria-label',\n labels.length > 1 ? `Pages ${labels[0]}–${labels.at(-1)}` : `Page ${labels[0] ?? ''}`,\n );\n\n const caption = this.#doc.createElement('span');\n caption.className = 'zine-thumbs-caption';\n caption.textContent = labels.join('–');\n row.appendChild(caption);\n\n row.addEventListener('click', () => {\n if (pages.length > 0) this.#zine.flipTo(Math.min(...pages));\n });\n this.#bar.root.appendChild(row);\n this.#rows.push({ el: row, spread: index });\n }\n this.#observeRows();\n }\n\n /** Decode a row's pages the first time it comes into view. */\n #observeRows(): void {\n const cells = [...this.#bar.root.querySelectorAll<HTMLElement>('.zine-thumbs-cell[data-page]')];\n if (typeof IntersectionObserver === 'undefined') {\n for (const cell of cells) void this.#paint(cell);\n return;\n }\n this.#observer = new IntersectionObserver(\n (entries, obs) => {\n for (const entry of entries) {\n if (!entry.isIntersecting) continue;\n obs.unobserve(entry.target);\n void this.#paint(entry.target as HTMLElement);\n }\n },\n { root: this.#bar.root, rootMargin: '200px' },\n );\n for (const cell of cells) this.#observer.observe(cell);\n }\n\n async #paint(cell: HTMLElement): Promise<void> {\n const page = Number(cell.dataset.page);\n const content = await this.#zine.getPageImage(page);\n if (!content || !cell.isConnected) return;\n const w = (content as { width: number }).width;\n const h = (content as { height: number }).height;\n if (!w || !h) return;\n // One page's worth of pixels, whatever the rail's column count, so thumbs stay a consistent\n // size between modes. Scaled by dpr so they are not soft on a retina screen.\n const dpr = Math.min(2, globalThis.devicePixelRatio || 1);\n const canvas = this.#doc.createElement('canvas');\n canvas.width = Math.max(1, Math.round(THUMB_WIDTH * dpr));\n canvas.height = Math.max(1, Math.round(((THUMB_WIDTH * h) / w) * dpr));\n canvas.className = 'zine-thumbs-img';\n const ctx = canvas.getContext('2d');\n if (!ctx) return;\n try {\n ctx.drawImage(content as CanvasImageSource, 0, 0, canvas.width, canvas.height);\n } catch {\n return; // an unusable raster is not worth breaking the rail over\n }\n cell.replaceChildren(canvas);\n }\n\n /** Highlight the spread on screen and keep it scrolled into view. */\n #markCurrent(): void {\n const current = this.#zine.getSpreadIndex();\n for (const { el, spread } of this.#rows) {\n const active = spread === current;\n el.classList.toggle('zine-panel-active', active);\n el.setAttribute('aria-selected', String(active));\n if (active) el.scrollIntoView?.({ block: 'nearest' });\n }\n }\n\n destroy(): void {\n for (const off of this.#unsubscribe) off();\n this.#unsubscribe = [];\n this.#observer?.disconnect();\n this.#observer = null;\n this.#bar.destroy();\n }\n}\n","import { Sidebar } from './sidebar';\nimport type { OutlineItem } from '../source/types';\nimport type { Zine } from '../zine';\n\n/** Rail width in px. Wider than the thumbnail rail because it holds headings, not pictures. */\nconst RAIL_WIDTH = 208;\n/** Indent per nesting level, in px. */\nconst INDENT = 12;\n\n/**\n * The document's table of contents beside the book.\n *\n * One row per heading, nested entries indented under their parent. Clicking a row turns to the\n * page it points at; a heading whose destination could not be resolved is still listed, just not\n * clickable. Unlike the thumbnail rail this is a single column — headings are text, and a second\n * column would only make them narrower.\n */\nexport class Outline {\n #zine: Zine;\n #doc: Document;\n #bar: Sidebar;\n #rows: { el: HTMLElement; page: number }[] = [];\n #unsubscribe: (() => void)[] = [];\n\n constructor(zine: Zine, container: HTMLElement) {\n this.#zine = zine;\n const doc = container.ownerDocument!;\n this.#doc = doc;\n this.#bar = new Sidebar(doc, container, {\n className: 'zine-outline',\n label: 'Outline',\n width: RAIL_WIDTH,\n });\n\n this.#note('Loading…');\n void this.#build();\n\n this.#unsubscribe.push(zine.on('pageChanged', () => this.#markCurrent()));\n }\n\n #note(text: string): void {\n const note = this.#doc.createElement('div');\n note.className = 'zine-panel-note';\n note.textContent = text;\n this.#bar.root.replaceChildren(note);\n }\n\n async #build(): Promise<void> {\n const items = await this.#zine.getOutline();\n if (!this.#bar.root.isConnected) return; // closed while the outline was loading\n if (items.length === 0) {\n // The toolbar hides the control when there is nothing to list, so this is only reachable\n // through a hand-written layout that names 'outline' regardless.\n this.#note('This document has no outline.');\n return;\n }\n this.#bar.root.replaceChildren();\n this.#addLevel(items, 0);\n this.#markCurrent();\n }\n\n #addLevel(items: OutlineItem[], depth: number): void {\n for (const item of items) {\n const row = this.#doc.createElement('button');\n row.type = 'button';\n row.className = 'zine-outline-row';\n row.setAttribute('role', 'option');\n row.style.paddingLeft = `${8 + depth * INDENT}px`;\n row.textContent = item.title;\n row.title = item.title;\n if (item.page === null) {\n // Keep the heading visible but inert: it still tells the reader what is in the document.\n row.disabled = true;\n } else {\n const page = item.page;\n row.setAttribute('aria-label', `${item.title}, page ${page + 1}`);\n row.addEventListener('click', () => this.#zine.flipTo(page));\n this.#rows.push({ el: row, page });\n }\n this.#bar.root.appendChild(row);\n if (item.children.length > 0) this.#addLevel(item.children, depth + 1);\n }\n }\n\n /**\n * Mark the entry the reader is inside — the last one at or before the current page, rather\n * than an exact match, since a section spans many pages and rarely starts on the one shown.\n */\n #markCurrent(): void {\n const current = this.#zine.getPage();\n let best: HTMLElement | null = null;\n let bestPage = -1;\n for (const { el, page } of this.#rows) {\n el.classList.remove('zine-panel-active');\n el.removeAttribute('aria-selected');\n if (page <= current && page >= bestPage) {\n best = el;\n bestPage = page;\n }\n }\n if (!best) return;\n best.classList.add('zine-panel-active');\n best.setAttribute('aria-selected', 'true');\n best.scrollIntoView?.({ block: 'nearest' });\n }\n\n destroy(): void {\n for (const off of this.#unsubscribe) off();\n this.#unsubscribe = [];\n this.#bar.destroy();\n }\n}\n","import { Sidebar } from './sidebar';\nimport type { Zine } from '../zine';\n\n/** Rail width in px. Matches the outline: both hold text, not pictures. */\nconst RAIL_WIDTH = 208;\n/** Wait after the last keystroke before searching, so typing does not scan per character. */\nconst DEBOUNCE_MS = 180;\n/** Shorter queries match too much to be useful. */\nconst MIN_QUERY = 2;\n\n/**\n * Full-text search beside the book: a query field over its results.\n *\n * It lives in the same rail as the thumbnails and outline rather than a popover, because results\n * are an open-ended list — a floating panel over the book would either cover the page being\n * searched or clip the very results it found.\n */\nexport class Search {\n #zine: Zine;\n #doc: Document;\n #bar: Sidebar;\n #input: HTMLInputElement;\n #hits: HTMLElement;\n /** Increments per query so a slow search that resolves late cannot overwrite a newer one. */\n #run = 0;\n #timer: ReturnType<typeof setTimeout> | null = null;\n\n constructor(zine: Zine, container: HTMLElement) {\n this.#zine = zine;\n const doc = container.ownerDocument!;\n this.#doc = doc;\n this.#bar = new Sidebar(doc, container, {\n className: 'zine-search',\n label: 'Search results',\n width: RAIL_WIDTH,\n });\n\n this.#input = doc.createElement('input');\n this.#input.type = 'search';\n this.#input.className = 'zine-search-input';\n this.#input.placeholder = 'Search…';\n this.#input.setAttribute('aria-label', 'Search the document');\n this.#input.addEventListener('input', () => {\n if (this.#timer) clearTimeout(this.#timer);\n this.#timer = setTimeout(() => void this.#search(), DEBOUNCE_MS);\n });\n // Enter searches at once rather than waiting out the debounce.\n this.#input.addEventListener('keydown', (e) => {\n if ((e as KeyboardEvent).key !== 'Enter') return;\n if (this.#timer) clearTimeout(this.#timer);\n void this.#search();\n });\n\n this.#hits = doc.createElement('div');\n this.#hits.className = 'zine-search-hits';\n\n this.#bar.root.append(this.#input, this.#hits);\n this.#input.focus();\n }\n\n #note(text: string): void {\n const note = this.#doc.createElement('div');\n note.className = 'zine-panel-note';\n note.textContent = text;\n this.#hits.replaceChildren(note);\n }\n\n async #search(): Promise<void> {\n const query = this.#input.value.trim();\n const mine = ++this.#run;\n if (query.length < MIN_QUERY) {\n this.#hits.replaceChildren();\n return;\n }\n this.#note('Searching…');\n const results = await this.#zine.search(query);\n if (mine !== this.#run || !this.#bar.root.isConnected) return; // superseded, or closed\n if (results.length === 0) {\n this.#note(`No matches for “${query}”`);\n return;\n }\n this.#hits.replaceChildren(\n ...results.map((hit) => {\n const row = this.#doc.createElement('button');\n row.type = 'button';\n row.className = 'zine-search-hit';\n row.setAttribute('role', 'option');\n row.setAttribute('aria-label', `Page ${hit.page + 1}: ${hit.excerpt}`);\n const label = this.#doc.createElement('span');\n label.className = 'zine-search-page';\n label.textContent = `Page ${hit.page + 1}`;\n const excerpt = this.#doc.createElement('small');\n excerpt.textContent = hit.excerpt;\n row.append(label, excerpt);\n row.addEventListener('click', () => this.#zine.flipTo(hit.page));\n return row;\n }),\n );\n }\n\n destroy(): void {\n if (this.#timer) clearTimeout(this.#timer);\n this.#timer = null;\n this.#run++; // any search still in flight is now stale\n this.#bar.destroy();\n }\n}\n","import { createIcon, ICONS } from './icons';\nimport type { Zine } from '../zine';\n\n/**\n * Big page-turn arrows flanking the book.\n *\n * They sit *beside* the book rather than over it, for the same reason the docked toolbar does:\n * the container's measured box is what the renderer sizes pages from and what pointer\n * hit-testing maps into, so anything inside it would shrink the book and skew every tap. The\n * book (with whatever the toolbar already wrapped around it) goes in a flex row between them.\n *\n * An arrow disables itself at the end of the book rather than disappearing, so the layout does\n * not jump as the reader reaches the covers.\n */\nexport class Arrows {\n #zine: Zine;\n #prev: HTMLButtonElement;\n #next: HTMLButtonElement;\n #wrap: HTMLElement | null = null;\n #unsubscribe: (() => void)[] = [];\n\n constructor(zine: Zine, container: HTMLElement) {\n this.#zine = zine;\n const doc = container.ownerDocument!;\n\n const rtl = zine.getDirection() === 'rtl';\n // The arrows point where the page goes, so in RTL they swap: \"back\" is to the right.\n this.#prev = this.#button(doc, rtl ? ICONS.next : ICONS.prev, 'Previous page', () =>\n zine.flipPrev(),\n );\n this.#next = this.#button(doc, rtl ? ICONS.prev : ICONS.next, 'Next page', () =>\n zine.flipNext(),\n );\n\n this.#place(doc, container);\n\n const refresh = (): void => this.#refresh();\n this.#unsubscribe.push(zine.on('pageChanged', refresh));\n this.#unsubscribe.push(zine.on('flipEnd', refresh));\n this.#refresh();\n }\n\n #button(\n doc: Document,\n icon: string,\n label: string,\n onClick: () => void,\n ): HTMLButtonElement {\n const btn = doc.createElement('button');\n btn.type = 'button';\n btn.className = 'zine-arrow';\n btn.title = label;\n btn.setAttribute('aria-label', label);\n btn.appendChild(createIcon(doc, icon));\n btn.addEventListener('click', onClick);\n // The book's gesture handlers sit on the container; an arrow press is not a page tap.\n for (const type of ['pointerdown', 'pointerup', 'click']) {\n btn.addEventListener(type, (e) => e.stopPropagation());\n }\n return btn;\n }\n\n #place(doc: Document, container: HTMLElement): void {\n // Wrap the outermost thing the library has already built around the book — a docked toolbar\n // or a side panel — so the arrows flank the whole assembly, not just the pages.\n const outer =\n container.closest('.zine-panel-wrap') ??\n container.closest('.zine-controls-wrap') ??\n container;\n const parent = outer.parentNode;\n if (!parent) return; // not in a document; nothing sensible to flank\n const wrap = doc.createElement('div');\n wrap.className = 'zine-arrows-wrap';\n parent.insertBefore(wrap, outer);\n wrap.append(this.#prev, outer, this.#next);\n this.#wrap = wrap;\n }\n\n /**\n * Hide an arrow that has nowhere to go — no back arrow on the first page.\n *\n * Hidden rather than removed so its slot stays reserved: dropping it from the flow would slide\n * the book sideways every time the reader reached a cover. `disabled` comes along for the ride\n * so the button is inert even if a consumer's own CSS makes it visible again.\n */\n #refresh(): void {\n for (const [btn, canTurn] of [\n [this.#prev, this.#zine.canFlipPrev()],\n [this.#next, this.#zine.canFlipNext()],\n ] as const) {\n btn.disabled = !canTurn;\n btn.classList.toggle('zine-arrow-hidden', !canTurn);\n }\n }\n\n destroy(): void {\n for (const off of this.#unsubscribe) off();\n this.#unsubscribe = [];\n this.#prev.remove();\n this.#next.remove();\n const wrap = this.#wrap;\n if (wrap?.parentNode) {\n // The arrows are gone, so what is left is the book; put it back where the wrapper was.\n while (wrap.firstChild) wrap.parentNode.insertBefore(wrap.firstChild, wrap);\n wrap.remove();\n }\n this.#wrap = null;\n }\n}\n","import { createIcon, ICONS } from './icons';\nimport { DEFAULT_ITEMS, defineControl, resolveControl } from './registry';\nimport { registerBuiltins } from './builtins';\nimport { ensureStyles } from './styles';\nimport { Thumbnails } from './thumbnails';\nimport { Outline } from './outline';\nimport { Search } from './search';\nimport { Arrows } from './arrows';\n\n/** The side panels, all of which share the one rail beside the book. */\nconst PANELS = { thumbnails: Thumbnails, outline: Outline, search: Search };\ntype PanelKind = keyof typeof PANELS;\n/** What every panel has in common: build itself on construction, and clean up after itself. */\ntype Panel = InstanceType<(typeof PANELS)[PanelKind]>;\nimport type {\n ControlContext,\n ControlDef,\n ControlItem,\n ControlsOptions,\n ControlsPosition,\n} from './types';\nimport type { Zine } from '../zine';\n\n/**\n * Events the container listens to for flipping, zooming and dragging. The gesture layer binds\n * these on the container and never checks `event.target`, so anything the toolbar handles has to\n * be stopped here or a button press would also register as a page tap.\n */\nconst SWALLOWED = ['pointerdown', 'pointerup', 'pointermove', 'click', 'dblclick', 'wheel', 'keydown'];\n\ninterface Popover {\n el: HTMLElement;\n trigger: HTMLElement;\n}\n\nexport class Toolbar {\n #zine: Zine;\n #doc: Document;\n #root: HTMLElement;\n #bar: HTMLElement;\n /** Every control on screen, buttons and `render` widgets alike, so #refresh can reach them. */\n #buttons: { el: HTMLElement; def: ControlDef }[] = [];\n #popover: Popover | null = null;\n #unsubscribe: (() => void)[] = [];\n #pageInput: HTMLInputElement | null = null;\n /** The flex wrapper docked mode inserts around the container; unwound on destroy. */\n #wrap: HTMLElement | null = null;\n #container: HTMLElement;\n /** The side panel currently in the rail. Only one at a time — they share the space. */\n #panel: Panel | null = null;\n #panelKind: PanelKind | null = null;\n /** Whether the document turned out to have any outline entries. Null until known: the answer\n * is async, and the outline control stays hidden rather than flash in and out. */\n #hasOutline: boolean | null = null;\n #arrows: Arrows | null = null;\n\n constructor(zine: Zine, container: HTMLElement, options: ControlsOptions) {\n this.#zine = zine;\n this.#container = container;\n const doc = container.ownerDocument!;\n this.#doc = doc;\n ensureStyles(doc);\n\n const position = options.position ?? 'bottom';\n const docked = options.docked ?? true;\n this.#root = doc.createElement('div');\n this.#root.className = [\n 'zine-controls',\n `zine-controls-${position}`,\n docked ? 'zine-controls-docked' : 'zine-controls-floating',\n options.className,\n ]\n .filter(Boolean)\n .join(' ');\n this.#root.setAttribute('role', 'toolbar');\n this.#root.setAttribute('aria-label', 'Flipbook controls');\n\n this.#bar = doc.createElement('div');\n this.#bar.className = 'zine-controls-bar';\n this.#root.appendChild(this.#bar);\n\n // Toolbar keys are handled first, then every listed event is stopped so none of it reaches\n // the book's gesture, zoom or keyboard handlers on the container.\n this.#root.addEventListener('keydown', (e) => this.#onKeyDown(e as KeyboardEvent));\n for (const event of SWALLOWED) {\n this.#root.addEventListener(event, (e) => this.#isolate(e));\n }\n this.#place(container, position, docked);\n\n const refresh = (): void => this.#refresh();\n this.#unsubscribe.push(zine.on('pageChanged', refresh));\n this.#unsubscribe.push(zine.on('zoomChanged', refresh));\n this.#unsubscribe.push(zine.on('flipEnd', refresh));\n const onDocPointer = (e: Event): void => {\n if (this.#popover && !this.#popover.el.contains(e.target as Node)) this.#closePopover();\n };\n doc.addEventListener('pointerdown', onDocPointer, true);\n this.#unsubscribe.push(() => doc.removeEventListener('pointerdown', onDocPointer, true));\n }\n\n /**\n * Put the toolbar in the page.\n *\n * Floating is simple: a child of the container, absolutely positioned over the book.\n *\n * Docked has to sit *outside* the container, because the container's measured box is what the\n * renderer sizes the book from and what pointer hit-testing maps into — a bar inside it would\n * shrink the book and skew every tap. So the container is wrapped in a flex column (or row),\n * with the toolbar as its sibling. The wrapper inherits the container's own layout box so the\n * arrangement the consumer's CSS set up is preserved.\n */\n #place(container: HTMLElement, position: ControlsPosition, docked: boolean): void {\n if (!docked) {\n container.appendChild(this.#root);\n return;\n }\n const parent = container.parentNode;\n if (!parent) {\n // Not in a document yet: fall back to overlaying rather than losing the toolbar.\n this.#root.classList.replace('zine-controls-docked', 'zine-controls-floating');\n container.appendChild(this.#root);\n return;\n }\n const wrap = this.#doc.createElement('div');\n wrap.className = `zine-controls-wrap zine-controls-wrap-${position}`;\n parent.insertBefore(wrap, container);\n wrap.appendChild(container);\n // 'top'/'left' put the bar first; flex-direction (set in CSS) handles the axis.\n if (position === 'top' || position === 'left') wrap.insertBefore(this.#root, container);\n else wrap.appendChild(this.#root);\n this.#wrap = wrap;\n }\n\n /** Build the layout. Separate from construction so instance-bound widgets (the page field, the\n * search panel) can be registered against this toolbar first. */\n mount(options: ControlsOptions): void {\n this.#build(options.items ?? DEFAULT_ITEMS);\n // After #place, so the arrows can wrap whatever it built around the book.\n if (options.arrows ?? true) this.#arrows = new Arrows(this.#zine, this.#container);\n this.#refresh();\n this.#probeOutline();\n }\n\n destroy(): void {\n for (const off of this.#unsubscribe) off();\n this.#unsubscribe = [];\n this.#closePopover();\n this.#panel?.destroy();\n this.#panel = null;\n this.#panelKind = null;\n this.#root.remove();\n // Unwrap from the inside out: the arrows enclose the toolbar's wrapper, so removing theirs\n // first would leave this one orphaned outside the document.\n const wrap = this.#wrap;\n if (wrap?.parentNode) {\n wrap.parentNode.insertBefore(wrap.firstChild!, wrap);\n wrap.remove();\n }\n this.#wrap = null;\n this.#arrows?.destroy();\n this.#arrows = null;\n }\n\n /** Keep toolbar interaction from reaching the book's own gesture/zoom/keyboard handlers. */\n #isolate(event: Event): void {\n event.stopPropagation();\n }\n\n #context(close: () => void = () => this.#closePopover()): ControlContext {\n return { zine: this.#zine, close };\n }\n\n #build(items: readonly ControlItem[]): void {\n for (const item of items) {\n if (item === '|') {\n const sep = this.#doc.createElement('div');\n sep.className = 'zine-controls-sep';\n this.#bar.appendChild(sep);\n continue;\n }\n const def = resolveControl(item);\n let el: HTMLElement;\n if (def.render) {\n el = def.render(this.#context());\n // Registered like any button so its predicates are re-read on every change; #button\n // does this for the controls it builds.\n this.#buttons.push({ el, def });\n } else {\n el = this.#button(def, 'zine-controls-btn');\n }\n this.#bar.appendChild(el);\n }\n }\n\n /** A control button. Bar buttons are icon-only with the title as tooltip; menu items and any\n * control without an icon also carry a visible label. */\n /** A control's label, which may be a function of the current state. */\n #titleOf(def: ControlDef): string {\n return typeof def.title === 'function' ? def.title(this.#context()) : def.title;\n }\n\n /** A control's glyph, which may likewise depend on state (an RTL mirror, say). */\n #iconOf(def: ControlDef): string | undefined {\n return typeof def.icon === 'function' ? def.icon(this.#context()) : def.icon;\n }\n\n #button(def: ControlDef, className: string, withLabel = false): HTMLButtonElement {\n const btn = this.#doc.createElement('button');\n const title = this.#titleOf(def);\n const icon = this.#iconOf(def);\n btn.type = 'button';\n btn.className = className;\n btn.title = title;\n btn.setAttribute('aria-label', title);\n if (icon) btn.appendChild(createIcon(this.#doc, icon));\n if (withLabel || !icon) {\n const label = this.#doc.createElement('span');\n label.className = 'zine-controls-label';\n label.textContent = title;\n btn.appendChild(label);\n }\n btn.addEventListener('click', () => this.#activate(def, btn));\n this.#buttons.push({ el: btn, def });\n return btn;\n }\n\n #activate(def: ControlDef, trigger: HTMLButtonElement): void {\n if (def.isDisabled?.(this.#context())) return;\n // A submenu toggles its popover; a second press on the same trigger closes it.\n if (def.children) {\n if (this.#popover?.trigger === trigger) this.#closePopover();\n else this.#openMenu(def, trigger);\n return;\n }\n def.action?.(this.#context());\n this.#refresh();\n }\n\n #openMenu(def: ControlDef, trigger: HTMLButtonElement): void {\n this.#closePopover();\n const menu = this.#doc.createElement('div');\n menu.className = 'zine-controls-menu';\n menu.setAttribute('role', 'menu');\n const ctx = this.#context();\n for (const child of def.children ?? []) {\n if (child === '|') continue;\n const childDef = resolveControl(child);\n if (childDef.isVisible && !childDef.isVisible(ctx)) continue;\n let item: HTMLElement;\n if (childDef.render) {\n item = childDef.render(this.#context());\n this.#buttons.push({ el: item, def: childDef });\n } else {\n item = this.#button(childDef, 'zine-controls-btn', true);\n }\n item.setAttribute('role', 'menuitem');\n menu.appendChild(item);\n }\n this.#showPopover(menu, trigger);\n // The entries were only just built, so nothing has evaluated their state yet: without this\n // a menu opens with every entry enabled until the next page turn happens to refresh it.\n this.#refresh();\n menu.querySelector('button')?.focus();\n }\n\n #showPopover(el: HTMLElement, trigger: HTMLElement): void {\n this.#root.appendChild(el);\n this.#popover = { el, trigger };\n trigger.setAttribute('aria-expanded', 'true');\n this.#placePopover(el, trigger);\n }\n\n /** Anchor a popover to its trigger, flipped to stay inside the book. */\n #placePopover(el: HTMLElement, trigger: HTMLElement): void {\n const root = this.#root.getBoundingClientRect();\n const anchor = trigger.getBoundingClientRect();\n const box = el.getBoundingClientRect();\n if (!root.width || !box.width) return; // not laid out (e.g. jsdom): leave to CSS\n let left = anchor.left - root.left + anchor.width / 2 - box.width / 2;\n left = Math.max(4, Math.min(left, root.width - box.width - 4));\n el.style.left = `${left}px`;\n // Prefer opening away from the edge the toolbar sits on.\n const below = anchor.bottom - root.top + 6;\n const above = anchor.top - root.top - box.height - 6;\n el.style.top = `${above >= 0 ? above : below}px`;\n }\n\n #closePopover(): void {\n if (!this.#popover) return;\n const { el, trigger } = this.#popover;\n this.#popover = null;\n trigger.removeAttribute('aria-expanded');\n // Drop buttons that belonged to the popover so #refresh stops touching detached nodes.\n this.#buttons = this.#buttons.filter((b) => !el.contains(b.el));\n el.remove();\n if (this.#doc.activeElement && el.contains(this.#doc.activeElement)) trigger.focus();\n }\n\n /** Arrow keys move between controls; Escape dismisses an open popover. */\n #onKeyDown(event: KeyboardEvent): void {\n if (event.key === 'Escape' && this.#popover) {\n const { trigger } = this.#popover;\n this.#closePopover();\n trigger.focus();\n event.preventDefault();\n return;\n }\n const focusables = [...this.#root.querySelectorAll<HTMLElement>('button, input')];\n const at = focusables.indexOf(this.#doc.activeElement as HTMLElement);\n if (at < 0) return;\n // Let the page-number field use its own arrows for text editing.\n if (this.#doc.activeElement instanceof HTMLInputElement) return;\n const step = event.key === 'ArrowRight' || event.key === 'ArrowDown' ? 1 : event.key === 'ArrowLeft' || event.key === 'ArrowUp' ? -1 : 0;\n if (step === 0) return;\n const next = focusables[(at + step + focusables.length) % focusables.length];\n next?.focus();\n event.preventDefault();\n }\n\n /**\n * Re-read every control's state after the book changes.\n *\n * Applies to custom widgets built with `render` as well as to plain buttons: the predicates\n * are on `ControlDef`, so honouring them only for button-shaped controls would make the same\n * field mean different things depending on how a control chose to draw itself. A widget may be\n * any element, so each piece of state is applied in whatever way that element supports.\n */\n #refresh(): void {\n const ctx = this.#context();\n for (const { el, def } of this.#buttons) {\n // Does not apply to this book at all: take the space back, it is not coming again.\n const applies = def.children ? this.#hasVisibleChildren(def, ctx) : def.isVisible?.(ctx);\n if (applies !== undefined) el.style.display = applies ? '' : 'none';\n\n const disabled = def.isDisabled?.(ctx) ?? false;\n // A wrapper element cannot be disabled, so mark it and disable the fields inside.\n for (const field of this.#formFields(el)) field.disabled = disabled;\n if (!this.#formFields(el).length) el.setAttribute('aria-disabled', String(disabled));\n el.classList.toggle('zine-controls-off', disabled);\n\n if (def.isActive) el.setAttribute('aria-pressed', String(def.isActive(ctx)));\n if (typeof def.title === 'function') {\n const title = def.title(ctx);\n el.title = title;\n el.setAttribute('aria-label', title);\n const label = el.querySelector('.zine-controls-label');\n if (label) label.textContent = title;\n }\n if (typeof def.icon === 'function') {\n el.querySelector('svg')?.replaceWith(createIcon(this.#doc, def.icon(ctx)));\n }\n }\n if (this.#pageInput && this.#doc.activeElement !== this.#pageInput) {\n this.#pageInput.value = String(this.#zine.getPage() + 1);\n }\n }\n\n /** The element itself if it can be disabled, else any inputs/buttons it wraps. */\n #formFields(el: HTMLElement): (HTMLButtonElement | HTMLInputElement)[] {\n if (el instanceof HTMLButtonElement || el instanceof HTMLInputElement) return [el];\n return [...el.querySelectorAll<HTMLButtonElement | HTMLInputElement>('button, input')];\n }\n\n /** A submenu is only worth showing if something inside it is. Keeps the overflow button from\n * opening onto nothing when every entry has hidden itself. */\n #hasVisibleChildren(def: ControlDef, ctx: ControlContext): boolean {\n if (def.isVisible && !def.isVisible(ctx)) return false;\n return (def.children ?? []).some((child) => {\n if (child === '|') return false;\n const childDef = resolveControl(child);\n return childDef.isVisible ? childDef.isVisible(ctx) : true;\n });\n }\n\n /** Registered lazily by {@link registerWidgets} so the widget can reach this instance. */\n makePageInput(): HTMLElement {\n const wrap = this.#doc.createElement('div');\n wrap.className = 'zine-controls-page';\n const input = this.#doc.createElement('input');\n input.type = 'number';\n input.min = '1';\n input.max = String(this.#zine.getPageCount());\n input.value = String(this.#zine.getPage() + 1);\n input.setAttribute('aria-label', 'Page number');\n const total = this.#doc.createElement('span');\n total.textContent = `/ ${this.#zine.getPageCount()}`;\n\n const commit = (): void => {\n const n = Number(input.value);\n if (Number.isFinite(n)) this.#zine.flipTo(Math.round(n) - 1);\n input.value = String(this.#zine.getPage() + 1);\n };\n input.addEventListener('keydown', (e) => {\n if (e.key === 'Enter') {\n commit();\n input.blur();\n }\n });\n input.addEventListener('blur', commit);\n wrap.append(input, total);\n this.#pageInput = input;\n return wrap;\n }\n\n /** Which side panel is showing, if any. */\n openPanel(): PanelKind | null {\n return this.#panelKind;\n }\n\n /**\n * Whether this document has a table of contents worth offering.\n *\n * Many PDFs have none, and a control that can only report its own emptiness is a dead end, so\n * the outline button stays hidden until the outline is known to be non-empty. The first call\n * kicks off the lookup and refreshes the toolbar when it lands; `Zine.getOutline` memoizes, so\n * the panel does not pay for it twice.\n */\n hasOutline(): boolean {\n return this.#hasOutline === true;\n }\n\n /** Ask the document whether it has an outline, and refresh once the answer lands. Started as\n * the toolbar mounts so the button settles into place immediately rather than on first use. */\n #probeOutline(): void {\n if (this.#hasOutline !== null || !this.#zine.canOutline()) return;\n this.#hasOutline = false; // assume not, until we hear otherwise\n void this.#zine.getOutline().then((items) => {\n if (items.length === 0) return;\n this.#hasOutline = true;\n this.#refresh();\n // The menu may already be open with the entry missing; rebuild it so it appears.\n const popover = this.#popover;\n if (popover) {\n const def = this.#buttons.find((b) => b.el === popover.trigger)?.def;\n this.#closePopover();\n if (def) this.#openMenu(def, popover.trigger as HTMLButtonElement);\n }\n });\n }\n\n /**\n * Show one of the side panels, or close it if it is already up. They share the rail beside the\n * book, so opening one closes the others. Rebuilt each time, so the thumbnail rail always\n * matches the current spread grouping (which `spreadMode` and the responsive fallback change).\n */\n togglePanel(kind: PanelKind): void {\n const wasOpen = this.#panelKind;\n this.#panel?.destroy();\n this.#panel = null;\n this.#panelKind = null;\n if (wasOpen !== kind) {\n this.#panel = new PANELS[kind](this.#zine, this.#container);\n this.#panelKind = kind;\n }\n this.#refresh();\n }\n\n}\n\n/**\n * Controls that need the toolbar itself (a DOM widget, or a panel to open) are registered per\n * instance, since the registry is module-level and shared.\n */\nexport function registerWidgets(toolbar: Toolbar): void {\n registerBuiltins();\n defineControl({\n id: 'thumbnails',\n title: () => (toolbar.openPanel() === 'thumbnails' ? 'Hide thumbnails' : 'Show thumbnails'),\n icon: ICONS.thumbnails,\n // Documents only, for now: an image book is already a short, flat list of pictures.\n isVisible: (ctx) => ctx.zine.isDocument(),\n isActive: () => toolbar.openPanel() === 'thumbnails',\n action: (ctx) => {\n toolbar.togglePanel('thumbnails');\n ctx.close();\n },\n });\n defineControl({\n id: 'outline',\n title: () => (toolbar.openPanel() === 'outline' ? 'Hide outline' : 'Show outline'),\n icon: ICONS.outline,\n // Only when the document actually has entries to show.\n isVisible: () => toolbar.hasOutline(),\n isActive: () => toolbar.openPanel() === 'outline',\n action: (ctx) => {\n toolbar.togglePanel('outline');\n ctx.close();\n },\n });\n defineControl({\n id: 'pageInput',\n title: 'Page',\n render: () => toolbar.makePageInput(),\n });\n defineControl({\n id: 'search',\n title: () => (toolbar.openPanel() === 'search' ? 'Hide search' : 'Search'),\n icon: ICONS.search,\n isVisible: (ctx) => ctx.zine.canSearch(),\n isActive: () => toolbar.openPanel() === 'search',\n action: () => toolbar.togglePanel('search'),\n });\n}\n","import { registerWidgets, Toolbar } from './toolbar';\nimport type { ControlsOptions } from './types';\nimport type { Zine } from '../zine';\n\nexport { defineControl, getControl, DEFAULT_ITEMS } from './registry';\nexport { ICONS, createIcon } from './icons';\nexport type {\n ControlContext,\n ControlDef,\n ControlItem,\n ControlsOptions,\n ControlsPosition,\n} from './types';\n\n/**\n * Build the toolbar inside `container` and return its teardown.\n *\n * This module is the lazy chunk `zine.ts` reaches through a dynamic `import()`, so a book built\n * with `controls: false` never downloads the toolbar, its icons or its stylesheet. The file is\n * named `controls.ts` rather than `index.ts` so the emitted chunk is `controls-<hash>.js`, which\n * is what the size-limit budget watches.\n */\nexport function mountControls(\n zine: Zine,\n container: HTMLElement,\n options: ControlsOptions = {},\n): () => void {\n const toolbar = new Toolbar(zine, container, options);\n // Built-ins and the instance-bound widgets have to exist before the layout resolves ids.\n registerWidgets(toolbar);\n toolbar.mount(options);\n return () => toolbar.destroy();\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 {\n bindDeepLink,\n claimHash,\n hashWithPage,\n pageFromHash,\n releaseHash,\n type DeepLinkHandle,\n} from './engine/deeplink';\nimport {\n CURL_TYPES,\n DEFAULT_CURL,\n IMPORTABLE_CURLS,\n type CurlSpec,\n type CurlType,\n} from './geometry/curls/types';\nimport { selectRenderer, type RendererOption } from './renderer/select';\nimport type { FlipDirection, PageContent, Renderer, SpreadContent } from './renderer/types';\nimport type { DownloadInfo, OutlineItem, Source } from './source/types';\nimport { composeSource } from './source/compose';\nimport type { ControlsOptions } from './controls/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\n/** A lone page fills the container, so it sweeps the full width where a spread leaf only covers\n * its half — and it dissolves instead of landing on a facing page. Stretch duration so the\n * peel and fade read at a comparable pace to a spread turn rather than whipping away. */\nconst LONE_PAGE_FLIP_SCALE = 1.55;\n\n/** Characters of surrounding text shown on either side of a search match. */\nconst EXCERPT_PAD = 32;\n\n/** Quiet period before re-rasterizing at a new zoom, so a pinch does not rasterize every frame. */\nconst ZOOM_TILE_DELAY = 60;\n\n/** Ceiling on the zoomed page raster. Memory grows with the square of this, so a letter page at\n * 4x would run past 100 MB; 2.5x keeps a deep zoom far sharper than fit-to-screen for a\n * fraction of that. */\nconst MAX_PAGE_UPGRADE = 2.5;\n\n/** Flip time under `prefers-reduced-motion`. Short enough not to read as animation, long enough\n * to show which way the page went — an instant swap leaves the reader guessing. */\nconst REDUCED_MOTION_DURATION = 120;\n\n/** One page that matched a {@link Zine.search} query. */\nexport interface SearchHit {\n /** Zero-based page index; pass straight to `flipTo`. */\n page: number;\n /** The match with a little text either side, ellipsised where it was cut. */\n excerpt: string;\n}\n\n/** Pull a readable snippet around a match, collapsing the whitespace PDFs are full of. */\nfunction excerptAround(text: string, at: number, length: number): string {\n const start = Math.max(0, at - EXCERPT_PAD);\n const end = Math.min(text.length, at + length + EXCERPT_PAD);\n const slice = text.slice(start, end).replace(/\\s+/g, ' ').trim();\n return `${start > 0 ? '…' : ''}${slice}${end < text.length ? '…' : ''}`;\n}\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 /**\n * Page-curl model for the WebGL2 renderer. Default `'cone'`.\n *\n * `'cone'` and `'simple'` are bundled and can be named directly. The others are imported and\n * passed as models, so a book that never uses them never carries their math:\n *\n * ```ts\n * import { silk } from '@zinejs/core/curls';\n * new Zine(el, { source, curl: silk });\n * ```\n *\n * Any object of the same shape works, so a custom curl needs no registration.\n */\n curl?: CurlSpec;\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 * Whether a narrow container may override `spreadMode` and show one page at a time. Default\n * true.\n *\n * Set false to hold the configured mode at every width — a two-page spread stays two pages on\n * a phone, however small. (`singlePageThreshold: 0` has the same effect; this says it out\n * loud, and can be changed at runtime with {@link Zine.setResponsiveSpread}.)\n */\n responsiveSpread?: boolean;\n /**\n * The built-in toolbar. Shown by default; pass `false` to render none, or an object to choose\n * its position and which controls appear.\n */\n controls?: boolean | ControlsOptions;\n /**\n * Keep the current page in the URL hash (`#page=12`), so a link opens where the reader was and\n * back/forward move through the book. Default true.\n *\n * Only a `page` key is read or written — anything else in the hash is left alone — and updates\n * use `replaceState`, so turning pages does not fill the back button. Pass `false` if your app\n * owns the hash.\n */\n deepLink?: boolean;\n /**\n * Suppress the browser's right-click menu over the book. Default false.\n *\n * A mild deterrent for published documents, not protection: the pages are still in the DOM and\n * reachable by anyone who wants them. It also takes away Inspect and \"Open image in new tab\"\n * for everyone, so it is off unless asked for.\n */\n disableContextMenu?: boolean;\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 /** The mode the book was built with, so toggling away from one page can return to it — a\n * `cover` book comes back as `cover`, keeping its lone first page, not as plain `double`. */\n #configuredMode: SpreadMode;\n #curl: CurlSpec;\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 /** Last layout announced via `spreadChanged`, so a rebuild that changes nothing stays quiet. */\n #effectiveModeShown: SpreadMode | null = null;\n #narrow = false; // responsive: container currently below singlePageThreshold\n #responsiveSpread: boolean;\n #lastAspect = ''; // last container aspect-ratio written (avoids redundant style writes)\n #startPageOption: number | undefined;\n #deepLinkEnabled: boolean;\n #disableContextMenu: boolean;\n #deepLink: DeepLinkHandle | null = null;\n #unsubscribeDeepLink: (() => void) | null = null;\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 // Latest flip intent requested while one was already animating; replayed on settle so\n // clicks/keys during a turn aren't dropped and continuous flipping keeps advancing.\n #queuedFlip: (() => void) | null = null;\n // The fold animation currently on screen, so a new flip request can land it instantly\n // (snap to its end pose + commit) and start immediately instead of waiting it out.\n #activeAnim: { toT: number; direction: FlipDirection; onDone: () => void } | null = null;\n // Bumped per flip so an async #runFlip that resumes after being superseded can bail.\n #flipGeneration = 0;\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 #unbindContextMenu: (() => void) | null = null;\n #unbindDblClick: (() => void) | null = null;\n #a11yCleanup: (() => void) | null = null;\n /** Resolved once and reused; see {@link getOutline}. */\n #outline: Promise<OutlineItem[]> | null = null;\n /** Pages whose content improved while a flip was running, to repaint once it settles. */\n #pendingUpgrades = new Set<number>();\n #controlsOption: boolean | ControlsOptions;\n #controlsCleanup: (() => void) | null = null;\n /** Resolution multiplier the current spread is rasterized at; 1 while not zoomed. */\n #zoomedAt = 1;\n /** Guards against an out-of-date tile landing after the view has already moved on. */\n #tileGeneration = 0;\n #tileTimer: ReturnType<typeof setTimeout> | 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 // Set before the spread model is built: that is where a page in the URL is honoured.\n // Claimed before the spread model is built, which is where the hash is read: a second book\n // on the same page must not open on the first one's page.\n this.#deepLinkEnabled = (options.deepLink ?? true) && claimHash();\n this.#disableContextMenu = options.disableContextMenu ?? false;\n this.#spreadMode = options.spreadMode ?? 'cover';\n this.#configuredMode = this.#spreadMode;\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.#responsiveSpread = options.responsiveSpread ?? true;\n this.#controlsOption = options.controls ?? true;\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 /** The element this flipbook was mounted into. */\n get container(): HTMLElement {\n return this.#container;\n }\n\n /**\n * How pages are currently grouped, one entry per spread — the same model the renderer paints,\n * so it already reflects `spreadMode` and the responsive single-page fallback. Useful for\n * building a page list or thumbnail rail that matches the book.\n */\n getSpreads(): readonly Spread[] {\n return this.#spreads;\n }\n\n /** The spread index currently on screen; indexes into {@link getSpreads}. */\n getSpreadIndex(): number {\n return this.#current;\n }\n\n /** Reading direction, which mirrors each spread's left/right sides. */\n getDirection(): Direction {\n return this.#direction;\n }\n\n /** How pages are grouped: the configured mode, not what a narrow container may be forcing. */\n getSpreadMode(): SpreadMode {\n return this.#spreadMode;\n }\n\n /** Whether the book is showing one page at a time, for whatever reason. */\n isSinglePage(): boolean {\n return this.#singlePage;\n }\n\n /**\n * Regroup the pages, keeping the reader on the page they are looking at.\n *\n * A narrow container may still override this with one page at a time; see\n * {@link setResponsiveSpread}.\n */\n setSpreadMode(mode: SpreadMode): void {\n if (mode === this.#spreadMode) return;\n this.#spreadMode = mode;\n // The narrow measurement was taken under the layout we are leaving, and a book showing one\n // page is narrower than the same book showing two. Holding on to it would let a container\n // that only shrank *because* of one-page mode veto the way back out. Drop it and let the\n // next measurement decide afresh.\n this.#narrow = false;\n this.#rebuildSpreads();\n void this.#renderCurrent();\n }\n\n /**\n * Switch between one page and two, and back again.\n *\n * Returning to two pages restores the mode the book was built with, so a `cover` book gets its\n * lone first page back rather than becoming a plain `double`.\n */\n toggleSpreadMode(): void {\n this.setSpreadMode(\n this.#spreadMode === 'single'\n ? this.#configuredMode === 'single'\n ? 'double' // built as single: there is no other mode to return to\n : this.#configuredMode\n : 'single',\n );\n }\n\n /** Whether a narrow container is allowed to override `spreadMode` with one page at a time. */\n getResponsiveSpread(): boolean {\n return this.#responsiveSpread;\n }\n\n /**\n * Whether the book is showing one page at a time *because the container is narrow*, rather\n * than because it was asked to. False when `responsiveSpread` is off.\n *\n * A book already set to `single` is not being overridden, however narrow it is: asking for one\n * page makes the book itself narrower, so reporting that as an override would strand the reader\n * in a layout they could no longer switch out of.\n */\n isResponsiveSingle(): boolean {\n return this.#narrow && this.#spreadMode !== 'single';\n }\n\n /**\n * Allow or forbid the narrow-container override, and re-lay out at once.\n *\n * Turning it off holds the configured `spreadMode` at every width; turning it back on\n * re-measures, so a book on a narrow screen collapses to single again straight away.\n */\n setResponsiveSpread(enabled: boolean): void {\n if (enabled === this.#responsiveSpread) return;\n this.#responsiveSpread = enabled;\n if (!enabled) {\n if (!this.#narrow) return; // nothing was being overridden\n this.#narrow = false;\n this.#rebuildSpreads();\n } else {\n const width = this.#renderer?.measure().containerWidth;\n if (width === undefined) return;\n this.#narrow = false; // let #applySinglePage see a real change and rebuild\n this.#applySinglePage(width);\n }\n void this.#renderCurrent();\n }\n\n /**\n * Resolve one page's raster, for drawing a thumbnail or exporting. Returns null if the page\n * cannot be decoded — the failure is reported through `sourceError` rather than thrown, as it\n * is for the pages the renderer paints.\n */\n getPageImage(index: number): Promise<PageContent | null> {\n return this.#getPage(index);\n }\n\n /** Whether there is a spread after the current one (false on the last). */\n canFlipNext(): boolean {\n return this.#current + 1 < this.#spreads.length;\n }\n\n /** Whether there is a spread before the current one (false on the first). */\n canFlipPrev(): boolean {\n return this.#current > 0;\n }\n\n /** The ceiling `setZoom` clamps to. */\n getMaxZoom(): number {\n return this.#maxZoom;\n }\n\n /** Whether this book's source can produce text — false for image books. */\n canSearch(): boolean {\n return typeof this.#source.getText === 'function';\n }\n\n /** Whether the original document can be downloaded — true for a PDF from a URL or bytes. */\n canDownload(): boolean {\n return typeof this.#source.getDownload === 'function';\n }\n\n /**\n * Whether the book is a document rather than a set of loose images — true for a PDF, false for\n * an `ImageSource`. Document-shaped features (the page rail, the outline) key off this.\n *\n * Inferred from the source implementing document-only capabilities, so a custom source opts in\n * simply by implementing them.\n */\n isDocument(): boolean {\n return typeof this.#source.getOutline === 'function' || typeof this.#source.getText === 'function';\n }\n\n /** Whether this book can be printed — true when the source has an original document. */\n canPrint(): boolean {\n return typeof this.#source.getDownload === 'function';\n }\n\n /**\n * Print the document.\n *\n * The original file is handed to the browser in an offscreen frame rather than printing the\n * host page: printing the page would capture the toolbar and whatever single spread happens to\n * be on screen, while the browser paginates a PDF properly on its own. Resolves false when\n * there is no original to print — an image book, or a caller-owned pdf.js document.\n */\n async print(): Promise<boolean> {\n const info = await this.getSourceFile();\n const doc = this.#container.ownerDocument;\n if (!info || !doc) return false;\n\n const frame = doc.createElement('iframe');\n // Offscreen rather than display:none: a hidden frame does not always lay out its document,\n // and an unlaid-out frame has nothing to print.\n frame.style.cssText =\n 'position:fixed;right:0;bottom:0;width:1px;height:1px;opacity:0;border:0;';\n frame.setAttribute('aria-hidden', 'true');\n frame.src = info.url;\n\n return new Promise<boolean>((resolve) => {\n let settled = false;\n const finish = (ok: boolean): void => {\n if (settled) return;\n settled = true;\n // Outlive the print dialog, which is modal and synchronous in some browsers; removing\n // the frame while it is open cancels the job.\n setTimeout(() => {\n frame.remove();\n if (info.revoke) URL.revokeObjectURL(info.url);\n }, 60_000);\n resolve(ok);\n };\n frame.addEventListener('load', () => {\n try {\n const win = frame.contentWindow;\n if (!win) return finish(false);\n win.focus();\n win.print();\n finish(true);\n } catch {\n finish(false); // a cross-origin PDF cannot be driven from here\n }\n });\n frame.addEventListener('error', () => finish(false));\n doc.body.appendChild(frame);\n });\n }\n\n /** Whether the source can supply a table of contents. True for PDFs; the document may still\n * turn out to have no outline, in which case {@link getOutline} resolves empty. */\n canOutline(): boolean {\n return typeof this.#source.getOutline === 'function';\n }\n\n /**\n * The document's table of contents, or an empty list when it has none.\n *\n * Memoized: an outline does not change for the life of the document, and resolving one means\n * following every entry's destination to a page. The toolbar asks for it up front to decide\n * whether to offer the outline panel at all, and the panel itself then gets it for free.\n */\n getOutline(): Promise<OutlineItem[]> {\n if (!this.#outline) {\n const getOutline = this.#source.getOutline;\n this.#outline =\n typeof getOutline === 'function'\n ? Promise.resolve(getOutline.call(this.#source)).catch(() => [])\n : Promise.resolve([]);\n }\n return this.#outline;\n }\n\n /**\n * Save the original document. Resolves to false when the source has nothing to hand over\n * (an image book, or a PDF opened from a caller-owned pdf.js document).\n */\n /**\n * Where the original document lives, if the source has one — a PDF's URL or a blob of its\n * bytes. Null for an image book, or a PDF opened from a caller-owned pdf.js document.\n *\n * Saving and printing both start here: the original is better than anything reassembled from\n * page rasters, and the browser already knows how to paginate it.\n */\n async getSourceFile(): Promise<DownloadInfo | null> {\n const getDownload = this.#source.getDownload;\n if (typeof getDownload !== 'function') return null;\n return (await getDownload.call(this.#source)) ?? null;\n }\n\n async download(): Promise<boolean> {\n const info = await this.getSourceFile();\n if (!info) return false;\n const doc = this.#container.ownerDocument;\n if (!doc) return false;\n const link = doc.createElement('a');\n link.href = info.url;\n link.download = info.filename;\n link.rel = 'noopener';\n doc.body.appendChild(link);\n link.click();\n link.remove();\n // An object URL is ours to clean up; give the click a tick to start first.\n if (info.revoke) setTimeout(() => URL.revokeObjectURL(info.url), 10_000);\n return true;\n }\n\n /**\n * Find `query` in the book's text, case-insensitively.\n *\n * Pages are read on demand and cached by the source, so the first search over a long document\n * costs one text extraction per page and later ones are cheap. Returns at most one hit per\n * page, in page order. Always empty when {@link canSearch} is false.\n */\n async search(query: string, options: { limit?: number } = {}): Promise<SearchHit[]> {\n const getText = this.#source.getText;\n const needle = query.trim().toLowerCase();\n if (typeof getText !== 'function' || needle === '') return [];\n const limit = options.limit ?? 50;\n const hits: SearchHit[] = [];\n for (let page = 0; page < this.#source.pageCount && hits.length < limit; page++) {\n let text: string;\n try {\n text = await getText.call(this.#source, page);\n } catch (error) {\n this.#emitter.emit('sourceError', { index: page, error });\n continue;\n }\n const at = text.toLowerCase().indexOf(needle);\n if (at < 0) continue;\n hits.push({ page, excerpt: excerptAround(text, at, needle.length) });\n }\n return hits;\n }\n\n flipNext(): void {\n this.#stepFlip(1);\n }\n\n flipPrev(): void {\n this.#stepFlip(-1);\n }\n\n /** Turn one spread in `step`'s direction, counted from wherever the book lands. Interrupting\n * commits the running turn first, so this steps on from there — repeat taps keep advancing,\n * and a reversal goes to the neighbour of the spread that just landed. */\n #stepFlip(step: 1 | -1): void {\n this.#requestFlip(() => this.#startFlip(this.#current + step));\n }\n\n flipTo(page: number): void {\n const target = clamp(page, 0, Math.max(0, this.#source.pageCount - 1));\n this.#requestFlip(() => this.#startFlip(this.#spreadIndexForPage(target)));\n }\n\n /** Run a flip now. If a fold is animating, land it instantly first so the new turn starts\n * immediately on this click (thunks read `#current` lazily, so it steps on from where the\n * interrupted turn landed). A drag in flight can't be interrupted this way, so its request\n * is queued and replayed on settle instead. */\n #requestFlip(run: () => void): void {\n if (this.#machine.state === 'idle') {\n run();\n } else if (this.#activeAnim) {\n // This request supersedes anything still waiting: landing the current turn commits it,\n // and that commit drains the queue. Without clearing it first, an older tap would fire\n // from inside the commit and take the book somewhere the reader has since changed their\n // mind about — a reversal would be undone by the forward tap it was meant to replace.\n this.#queuedFlip = null;\n this.#finishActiveAnim(); // lands the current turn → machine back to idle\n run();\n } else {\n this.#queuedFlip = run; // dragging: no animation to cut short, so wait for release\n }\n }\n\n /** Snap the in-flight fold to its end pose and commit it now, cancelling its RAF loop. */\n #finishActiveAnim(): void {\n const anim = this.#activeAnim;\n if (!anim) return;\n this.#activeAnim = null;\n if (this.#raf !== null) {\n cancelAnimationFrame(this.#raf);\n this.#raf = null;\n }\n this.#renderer?.setFlipProgress(anim.toT, anim.direction);\n anim.onDone();\n }\n\n /** After an animation settles, fire whatever flip was requested mid-turn. */\n #drainQueuedFlip(): void {\n const queued = this.#queuedFlip;\n if (!queued) {\n // Nothing further to turn to, so this is where the book comes to rest: a good moment to\n // apply any page content that improved while it was moving.\n this.#flushPendingUpgrades();\n return;\n }\n this.#queuedFlip = null;\n queued();\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 // Default to the middle of the pages, not of the container: on a lone page those differ, and\n // zooming toward the container centre would drift the page off toward the gutter.\n const box = m.screenAt?.(this.#scale);\n const focal = center ??\n (box\n ? { x: box.x + this.#tx + box.width / 2, y: box.y + this.#ty + box.height / 2 }\n : null) ?? { 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.#refreshZoomTiles();\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 // Bound the pan by where the pages actually are, not by the container. A lone page (a cover,\n // or the back of a book-mode spread) is painted in the middle half, and letterboxing insets\n // the book on any container whose aspect differs; clamping to the container would let the\n // reader drag the page off to one side and stare at the space beside it.\n //\n // `screen` is where the renderer says the pages are under the *current* view, so the offset\n // between it and the translate that produced it converts a wanted translate into a page\n // position. The renderers place a lone page differently (one shifts outside the view scale,\n // one inside), which is why this asks rather than deriving it.\n // Land on whole device pixels. A fractional offset makes every screen pixel a different\n // bilinear blend of the same texels, so as the page slides the strokes of each glyph thicken\n // and thin: the text appears to shimmer and change weight rather than simply move.\n const dpr = typeof devicePixelRatio === 'number' && devicePixelRatio > 0 ? devicePixelRatio : 1;\n // `|| 0` normalises -0, which Object.is and strict deep-equality treat as distinct from 0.\n const snap = (v: number): number => Math.round(v * dpr) / dpr || 0;\n\n // Asked for `scale` rather than read from the current view, because setZoom clamps before it\n // commits and would otherwise be bounded by the scale it is leaving.\n // Falls back to the container, which is what the pages fill on a renderer that does not\n // report a box: keeps a bare Renderer implementation clamped rather than free to pan away.\n const box = this.#renderer?.measure().screenAt?.(scale) ?? {\n x: 0,\n y: 0,\n width: w * scale,\n height: h * scale,\n };\n const [minX, maxX] = axisPanRange(box.x, box.width, w);\n const [minY, maxY] = axisPanRange(box.y, box.height, h);\n return [snap(clamp(tx, minX, maxX)), snap(clamp(ty, minY, maxY))];\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.#activeAnim = null;\n this.#queuedFlip = null;\n this.#clearPendingClickFlip();\n this.#resizeObserver?.disconnect();\n this.#deepLink?.stop();\n this.#deepLink = null;\n this.#unsubscribeDeepLink?.();\n if (this.#deepLinkEnabled) releaseHash(); // a later book may own it now\n this.#controlsCleanup?.();\n this.#a11yCleanup?.();\n this.#unbindWheel?.();\n this.#unbindDblClick?.();\n this.#unbindContextMenu?.();\n this.#unbindInput?.();\n if (this.#tileTimer !== null) clearTimeout(this.#tileTimer);\n this.#tileGeneration++; // strand any raster still resolving\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 // Claimed here, synchronously, so this flip owns the run before #runFlip's first await.\n // Bumping inside #runFlip instead let a superseded flip's continuation claim the newest\n // generation and cancel the flip that replaced it.\n void this.#runFlip(targetIndex, direction, toPage, ++this.#flipGeneration);\n }\n\n async #runFlip(\n targetIndex: number,\n direction: FlipDirection,\n toPage: number,\n generation: number,\n ): Promise<void> {\n // Staging the destination is async, so this can resume after a later flip has already\n // superseded it (interrupting mid-turn does exactly that). Without this check the stale\n // continuation would begin animating its own, now-abandoned target and commit it, undoing\n // the turn the reader actually asked for.\n const toSpread = this.#spreads[targetIndex];\n const toContent: SpreadContent = toSpread\n ? await this.#resolveContent(toSpread)\n : { left: null, right: null };\n if (generation !== this.#flipGeneration) return;\n this.#renderer?.beginFlip(this.#currentContent, toContent, direction, {\n fill: this.#singlePage,\n curl: this.#effectiveCurl(),\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 // Remembered so a mid-turn flip request can #finishActiveAnim() to land it at once.\n // Object identity also tags this run: if #finishActiveAnim (or a new flip) replaces it,\n // a stale frame that still fires bails instead of re-committing or rescheduling itself.\n const anim = { toT, direction, onDone };\n this.#activeAnim = anim;\n const start = performance.now();\n const step = (now: number): void => {\n if (this.#activeAnim !== anim) return; // superseded/interrupted → this frame is void\n // Easing lives here; flipProgressToPose stays linear so seeks are deterministic.\n // Lone pages ease out harder — no facing half to land on, only a dissolve.\n const raw = Math.min(1, (now - start) / duration);\n const eased = this.#singlePage ? easeInOutLone(raw) : easeInOutQuad(raw);\n this.#renderer?.setFlipProgress(fromT + (toT - fromT) * eased, direction);\n if (raw < 1) {\n this.#raf = requestAnimationFrame(step);\n } else {\n this.#raf = null;\n this.#activeAnim = 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 this.#drainQueuedFlip();\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) 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 b = this.#contentRect();\n const point = this.#toBookPoint(clientX, clientY);\n // Recorded before the busy check below: a tap landing mid-flip is still a real tap, and\n // on release it decides which way to turn. Leaving the previous press in place made that\n // release repeat the last flip's direction instead of honouring the side just tapped.\n this.#press = point; // remembered for tap classification / click-to-flip zone\n // Only the drag machinery needs an idle book — a fold is already on screen, so there is\n // nothing to grab. The tap itself is handled on release, which queues or interrupts.\n if (this.#machine.state !== 'idle') {\n this.#pendingGrab = null;\n return;\n }\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.#effectiveCurl(),\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 this.#refreshZoomTiles();\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 step = direction === 'forward' ? 1 : -1;\n if (this.#current + step < 0 || this.#current + step >= this.#spreads.length) return;\n // Anchor the fold at the tapped height (cone/leaf/flick curl from where you tap).\n this.#anchorY = clamp(this.#press.y / this.#contentRect().height, 0, 1);\n // Read `#current` lazily: interrupting commits the running turn first, so this steps on\n // from wherever the book actually landed — one spread back from there is the neighbour\n // the reader is looking at, not the spread they tapped on two turns ago.\n const flip = (): void => this.#startFlip(this.#current + step);\n this.#clearPendingClickFlip();\n if (this.#clickFlipDelayValue <= 0) {\n // No double-click competing here → flip right away (or queue if mid-turn).\n this.#requestFlip(flip);\n return;\n }\n // Wait out the window; a double-click (zoom) cancels this.\n this.#pendingClickTimer = setTimeout(() => {\n this.#pendingClickTimer = null;\n this.#requestFlip(flip);\n }, this.#clickFlipDelayValue);\n }\n\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 /** A viewport point in book-local px: relative to the drawn page, not the container. The two\n * differ whenever the book is letterboxed, so every hit test against a zone or corner has to\n * come through here — measuring from the container edge puts the zones off by the bar width. */\n #toBookPoint(clientX: number, clientY: number): { x: number; y: number } {\n const rect = this.#container.getBoundingClientRect();\n const b = this.#contentRect();\n return { x: clientX - rect.left - b.x, y: clientY - rect.top - b.y };\n }\n\n /** Which way a tap at `point` (book-local, via {@link #toBookPoint}) turns the page, or null\n * for a dead zone. */\n #clickFlipDirection(point: { x: number; y: number }): FlipDirection | null {\n if (!this.#renderer) return null;\n const bookWidth = this.#contentRect().width;\n let side: 'left' | 'right' | null;\n if (this.#clickToFlip === 'half') {\n side = point.x > bookWidth / 2 ? 'right' : 'left';\n } else if (point.x <= this.#clickZoneSize) {\n side = 'left';\n } else if (point.x >= bookWidth - 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 this.#drainQueuedFlip();\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 /** Swallow the right-click menu over the book, when the consumer asked for that. */\n #bindContextMenu(): void {\n if (!this.#disableContextMenu) return;\n const onContextMenu = (event: Event): void => event.preventDefault();\n this.#container.addEventListener('contextmenu', onContextMenu);\n this.#unbindContextMenu = () =>\n this.#container.removeEventListener('contextmenu', onContextMenu);\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 || !this.#renderer) 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 local = this.#toBookPoint(event.clientX, event.clientY);\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.#bindContextMenu();\n this.#setupReducedMotion();\n this.#a11yCleanup = this.#setupA11y();\n\n await this.#renderCurrent();\n this.#observeResize();\n this.#prefetchWindow();\n this.#announce();\n this.#bindDeepLink();\n await this.#mountControls();\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 /**\n * Build the toolbar, if it is wanted and the container is real DOM.\n *\n * The chunk is fetched lazily so a book with `controls: false` never downloads it. Failure is\n * swallowed on purpose: a toolbar that cannot load should cost the reader a toolbar, not the\n * whole flipbook — `#init` has no error handling of its own, so a throw here would reject\n * `ready`.\n */\n async #mountControls(): Promise<void> {\n if (this.#controlsOption === false || this.#destroyed) return;\n const container = this.#container;\n if (!container.ownerDocument || typeof container.appendChild !== 'function') return;\n try {\n const { mountControls } = await import('./controls/controls');\n if (this.#destroyed) return; // destroyed while the chunk was in flight\n const options = this.#controlsOption === true ? {} : this.#controlsOption;\n this.#controlsCleanup = mountControls(this, container, options);\n } catch {\n // No toolbar; the book itself is unaffected.\n }\n }\n\n /** Mirror the page in the URL, and follow the URL when it changes. */\n #bindDeepLink(): void {\n if (!this.#deepLinkEnabled || typeof globalThis.location === 'undefined') return;\n const win = globalThis as unknown as Window;\n this.#deepLink = bindDeepLink(win, (page) => {\n // Only act on a hash the reader changed — following a link, or pressing Back. A hash we\n // wrote ourselves describes where the book already is.\n if (page !== this.#currentPage) this.flipTo(page);\n });\n this.#deepLink.push(this.#currentPage);\n this.#unsubscribeDeepLink = this.#emitter.on('pageChanged', ({ page }) => {\n this.#deepLink?.push(page);\n });\n }\n\n /** The URL that opens this book at `page` (defaults to the current one). */\n pageLink(page: number = this.#currentPage): string {\n const href = globalThis.location?.href ?? '';\n if (!href) return '';\n const url = new URL(href);\n url.hash = hashWithPage(url.hash, clamp(page, 0, Math.max(0, this.#source.pageCount - 1)));\n return url.toString();\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 // Reduced motion still turns the page, just briefly and flat (see #effectiveCurl): a page\n // that teleports gives the reader no sense of which way the book moved.\n if (this.#reducedMotion) return REDUCED_MOTION_DURATION;\n return this.#flipDuration * (this.#singlePage ? LONE_PAGE_FLIP_SCALE : 1);\n }\n\n /** The curl to turn with: reduced motion flattens the sheet, whatever the book asked for. */\n #effectiveCurl(): CurlSpec {\n return this.#reducedMotion ? 'simple' : this.#curl;\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 =\n this.#responsiveSpread && shouldSinglePage(containerWidth, this.#singlePageThreshold);\n if (narrow === this.#narrow) return;\n this.#narrow = narrow;\n this.#rebuildSpreads();\n }\n\n /** Regroup the pages after something changes the layout, keeping the reader on the page they\n * were looking at even though its spread index may have moved. */\n #rebuildSpreads(): void {\n const mode = this.#effectiveMode();\n const changed = mode !== this.#effectiveModeShown;\n this.#effectiveModeShown = mode;\n this.#singlePage = mode === 'single';\n this.#spreads = buildSpreads(this.#source.pageCount, { direction: this.#direction, mode });\n this.#current = this.#spreadIndexForPage(this.#currentPage);\n // The book's proportions change with the layout, so consumers sizing around it need to know.\n if (changed) this.#emitter.emit('spreadChanged', { mode, singlePage: this.#singlePage });\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 // These pages were resolved at fit-to-screen; if the reader is zoomed, ask for them sharper.\n this.#zoomedAt = 1;\n this.#refreshZoomTiles();\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 /**\n * A source upgraded a page's content (e.g. a progressive PDF swapping in the crisp render).\n *\n * Repainting mid-flip would disturb the animation, so an upgrade that lands during one is\n * noted and applied on settle instead of dropped. Dropping it left the page stuck at low\n * resolution for good: the upgrade fires once, and jumping straight to a page — from a search\n * hit, the page field, the outline — is exactly when it tends to arrive.\n */\n #onPageUpdate(index: number): void {\n if (this.#machine.state !== 'idle') {\n this.#pendingUpgrades.add(index);\n return;\n }\n const spread = this.#spreads[this.#current];\n if (spread && (spread.left === index || spread.right === index)) {\n void this.#renderCurrent();\n }\n }\n\n /**\n * Ask the source for a crisp render of whatever is visible, and lay it over the magnified page.\n *\n * Zooming is only a view transform, so without this the reader is magnifying the pixels of a\n * raster made to fit the screen. A vector source can do better; one backed by a fixed-resolution\n * original cannot, and says so by handing back a whole page, which is dropped.\n *\n * Debounced, and hidden while the view moves. A tile is crisp for one view only, so during a\n * pan it is stale by definition; showing it anyway puts two versions of the same text on screen\n * at once. Hiding leaves the reader with the uniformly magnified page an image book already\n * shows, which is smooth because there is nothing to disagree with it. The tile returns once\n * the view settles.\n */\n /**\n * Re-rasterize the visible pages at the magnification being viewed, and hand them to the\n * renderer as ordinary page content.\n *\n * Zoom is a view transform, so the renderer magnifies a raster made to fit the screen and text\n * goes soft. Giving it a sharper raster for the same page fixes that at the root: panning stays\n * a pure view transform over crisp pixels, which is why an image book pans smoothly and why an\n * overlay painted only between gestures never could.\n *\n * Debounced, since rasterizing a PDF page is far too slow to do per frame.\n */\n #refreshZoomTiles(): void {\n if (this.#tileTimer !== null) clearTimeout(this.#tileTimer);\n const wanted = this.#upgradeScale();\n if (wanted === this.#zoomedAt) return; // already showing this resolution\n if (wanted === 1) {\n this.#tileGeneration++; // abandon anything in flight: it is no longer wanted\n this.#zoomedAt = 1;\n void this.#renderCurrent(); // back to the fit-to-screen raster\n return;\n }\n this.#tileTimer = setTimeout(() => {\n this.#tileTimer = null;\n void this.#renderZoomTiles();\n }, ZOOM_TILE_DELAY);\n }\n\n /**\n * The resolution multiplier to rasterize the visible pages at.\n *\n * Capped because a page costs the square of this in memory: at 4x a letter page is over 100 MB,\n * which would dwarf the source's whole cache. The cap keeps a deep zoom sharper than the\n * fit-to-screen raster without trying to match it pixel for pixel.\n */\n #upgradeScale(): number {\n if (this.#scale <= 1) return 1;\n return Math.min(Math.ceil(this.#scale * 2) / 2, MAX_PAGE_UPGRADE);\n }\n\n async #renderZoomTiles(): Promise<void> {\n const spread = this.#spreads[this.#current];\n if (!this.#renderer || !spread) return;\n const scale = this.#upgradeScale();\n if (scale === 1 || scale === this.#zoomedAt) return;\n\n const generation = ++this.#tileGeneration;\n const whole = { x: 0, y: 0, width: 1, height: 1 };\n const pages = await Promise.all(\n [spread.left, spread.right].map(async (index) => {\n if (index === null) return null;\n try {\n return await this.#source.get(index, { scale, region: whole });\n } catch (error) {\n // An upgrade is an enhancement: the readable, softer page stays on screen.\n this.#emitter.emit('sourceError', { index, error });\n return null;\n }\n }),\n );\n // Rasterizing is slow and the reader may have moved on, or zoomed somewhere else entirely.\n if (generation !== this.#tileGeneration || this.#upgradeScale() !== scale) return;\n const left = pages[0] ?? null;\n const right = pages[1] ?? null;\n // Nothing sharper came back: a source with a fixed-resolution original hands over the raster\n // already on screen, and repainting it would be pure churn.\n if (left === this.#currentContent.left && right === this.#currentContent.right) return;\n\n this.#zoomedAt = scale;\n this.#currentContent = { left, right };\n this.#renderer.renderSpread(spread, this.#currentContent, { fill: this.#singlePage });\n }\n\n /** Apply any upgrade that arrived mid-flip, now that the book has settled. */\n #flushPendingUpgrades(): void {\n if (this.#pendingUpgrades.size === 0) return;\n const spread = this.#spreads[this.#current];\n const onScreen =\n spread !== undefined &&\n [spread.left, spread.right].some((p) => p !== null && this.#pendingUpgrades.has(p));\n this.#pendingUpgrades.clear();\n if (onScreen) void this.#renderCurrent();\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 // A page in the URL wins over `startPage`: the reader followed a link to it, which is a\n // later and more specific intent than the page the author configured.\n const linked = this.#deepLinkEnabled ? pageFromHash(globalThis.location?.hash ?? '') : null;\n this.#currentPage = clamp(linked ?? 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\n/**\n * The translate range that keeps content within the viewport along one axis.\n *\n * `pos`/`size` are where the pages sit with no pan applied, so the view puts them at `pos + t`.\n * When they are larger than the viewport the range spans from their far edge to their near one,\n * so the reader can reach every part. When smaller there is nothing to explore, so the range\n * collapses to the single value that centres them: a lone page at 2x fills the width exactly, and\n * any freedom there would only let it drift off to one side.\n */\nfunction axisPanRange(pos: number, size: number, viewport: number): [min: number, max: number] {\n if (size <= viewport) {\n const centered = (viewport - size) / 2 - pos;\n return [centered, centered];\n }\n return [viewport - (pos + size), -pos];\n}\n\n/** Quadratic ease-in-out. Deliberately gentler than a cubic: a cubic leaves the page nearly\n * motionless for the first quarter of the turn and then spikes through the middle at roughly\n * double the peak speed, which reads as a lurch rather than a sheet of paper being turned. */\nfunction easeInOutQuad(t: number): number {\n return t < 0.5 ? 2 * t * t : 1 - Math.pow(-2 * t + 2, 2) / 2;\n}\n\n/** Lone-page turn: same gentle start as the spread ease, then a longer decelerating finish.\n * Without a facing half the landing is a dissolve — front-loading a bit of progress and\n * stretching the tail keeps that fade from reading as a whip. */\nfunction easeInOutLone(t: number): number {\n const x = easeInOutQuad(t);\n return 1 - Math.pow(1 - x, 1.3);\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) {\n if (typeof curl === 'object' && curl !== null) {\n // An imported or custom model. Check the one member the renderer calls every frame, so a\n // wrong shape fails here rather than as an undefined call mid-flip.\n if (typeof (curl as { deform?: unknown }).deform !== 'function') {\n throw new Error('Zine: a curl model must have a deform() function.');\n }\n } else if (IMPORTABLE_CURLS.includes(curl as string)) {\n // A real curl, just not bundled: say how to get it rather than calling it invalid.\n throw new Error(\n `Zine: the '${String(curl)}' curl is not bundled. Import it and pass the model: ` +\n `import { ${String(curl)} } from '@zinejs/core/curls' → curl: ${String(curl)}`,\n );\n } else if (!CURL_TYPES.includes(curl as CurlType)) {\n throw new Error(\n `Zine: curl must be ${CURL_TYPES.join(' or ')}, or a model imported from ` +\n `'@zinejs/core/curls' (${IMPORTABLE_CURLS.join(', ')}); got ${JSON.stringify(curl)}.`,\n );\n }\n }\n\n for (const flag of ['deepLink', 'disableContextMenu', 'responsiveSpread'] as const) {\n if (o[flag] !== undefined && typeof o[flag] !== 'boolean') {\n throw new Error(`Zine: ${flag} must be a boolean; got ${typeName(o[flag])}.`);\n }\n }\n\n const controls = o.controls;\n if (controls !== undefined && typeof controls !== 'boolean' && (typeof controls !== 'object' || controls === null)) {\n throw new Error(\n `Zine: controls must be a boolean or an options object; got ${typeName(controls)}.`,\n );\n }\n const position = (controls as { position?: unknown } | undefined)?.position;\n if (position !== undefined && !['top', 'bottom', 'left', 'right'].includes(position as string)) {\n throw new Error(\n `Zine: controls.position must be 'top', 'bottom', 'left', or 'right'; got ${JSON.stringify(position)}.`,\n );\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, SearchHit } from './zine';\n\n// Just the registry mechanism — the toolbar, its icons and the built-in definitions all live in\n// the lazily-loaded chunk, so registering a custom control costs nothing up front.\nexport { defineControl, getControl, DEFAULT_ITEMS } from './controls/registry';\nexport type {\n ControlContext,\n ControlDef,\n ControlItem,\n ControlsOptions,\n ControlsPosition,\n} from './controls/types';\n\nexport { ImageSource } from './source/imageSource';\nexport type { ImageSourceOptions, ImageFit } from './source/imageSource';\nexport type { Source, DownloadInfo, OutlineItem, PageRequest } 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, IMPORTABLE_CURLS } from './geometry/curls/types';\nexport type { CurlType, CurlSpec, CurlModel, CurlDeform, CurlAnchor } from './geometry/curls/types';\nexport type { PageMesh } from './geometry/curls/mesh';\n"],"mappings":"sfA8BA,SAAgB,EAAa,EAAmB,EAAyB,CAAC,EAAa,CACrF,GAAM,CAAE,YAAY,MAAO,OAAO,SAAY,EAC9C,GAAI,GAAa,EAAG,MAAO,CAAC,EAE5B,IAAM,EAAQ,GAA8B,GAAK,GAAK,EAAI,EAAY,EAAI,KACpE,EAAoB,CAAC,EAE3B,GAAI,IAAS,SACX,IAAK,IAAI,EAAI,EAAG,EAAI,EAAW,IAAK,EAAQ,KAAK,CAAE,KAAM,KAAM,MAAO,CAAE,CAAC,OACpE,GAAI,IAAS,SAClB,IAAK,IAAI,EAAI,EAAG,EAAI,EAAW,GAAK,EAAG,EAAQ,KAAK,CAAE,KAAM,EAAK,CAAC,EAAG,MAAO,EAAK,EAAI,CAAC,CAAE,CAAC,OACpF,G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