@zinejs/core 0.8.2 → 0.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +73 -0
- package/README.md +27 -49
- package/dist/{bundled-Cp43MIt0.js → bundled-ESapkNsS.js} +34 -34
- package/dist/bundled-ESapkNsS.js.map +1 -0
- package/dist/controls/contextMenu.d.ts +16 -0
- package/dist/controls/controls.d.ts +10 -3
- package/dist/controls/icons.d.ts +6 -2
- package/dist/controls/menu.d.ts +68 -0
- package/dist/controls/search.d.ts +15 -2
- package/dist/controls/styles.d.ts +1 -1
- package/dist/controls/toolbar.d.ts +1 -1
- package/dist/controls/types.d.ts +6 -0
- package/dist/{controls-DgEXR2zi.js → controls-DzVdwPJB.js} +349 -196
- package/dist/controls-DzVdwPJB.js.map +1 -0
- package/dist/curls.js +1 -1
- package/dist/flipSound-BFXSkWBo.js +78 -0
- package/dist/flipSound-BFXSkWBo.js.map +1 -0
- package/dist/geometry/curls/cone.d.ts +4 -3
- package/dist/index.js +671 -440
- package/dist/index.js.map +1 -1
- package/dist/index.umd.js +26 -7
- package/dist/index.umd.js.map +1 -1
- package/dist/loading/loading.d.ts +1 -1
- package/dist/loading-DF88K9yJ.js +45 -0
- package/dist/loading-DF88K9yJ.js.map +1 -0
- package/dist/renderer/gl/texture.d.ts +13 -2
- package/dist/renderer/types.d.ts +6 -0
- package/dist/renderer/webglRenderer.d.ts +1 -0
- package/dist/{share-WXdscwp3.js → share-Cq3RsjPr.js} +2 -2
- package/dist/{share-WXdscwp3.js.map → share-Cq3RsjPr.js.map} +1 -1
- package/dist/sound/clip.d.ts +9 -0
- package/dist/sound/flipSound.d.ts +30 -0
- package/dist/source/types.d.ts +5 -0
- package/dist/styles-C1Qp5pby.js +42 -0
- package/dist/styles-C1Qp5pby.js.map +1 -0
- package/dist/{webglRenderer-nGRruZk2.js → webglRenderer-CmQ_mUrX.js} +113 -101
- package/dist/webglRenderer-CmQ_mUrX.js.map +1 -0
- package/dist/zine.d.ts +75 -1
- package/options.schema.json +66 -0
- package/package.json +13 -11
- package/dist/bundled-Cp43MIt0.js.map +0 -1
- package/dist/controls-DgEXR2zi.js.map +0 -1
- package/dist/loading-BBK6YbSW.js +0 -45
- package/dist/loading-BBK6YbSW.js.map +0 -1
- package/dist/styles-B8fFoYm_.js +0 -40
- package/dist/styles-B8fFoYm_.js.map +0 -1
- package/dist/webglRenderer-nGRruZk2.js.map +0 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["#radius","#mounted","#listeners","#state","#handlers","#activeId","#start","#prev","#last","#end","#reset","#pinching","#points","#pair","#startDistance","#remove","#base","#front","#back","#rawPages","#resolvePages","#resolved","#image","#cache","#renderer","#container","#source","#direction","#deepLinkEnabled","#disableContextMenu","#spreadMode","#configuredMode","#curl","#clickToFlip","#clickZoneSize","#singlePageThreshold","#responsiveSpread","#controlsOption","#loadingOption","#startPageOption","#buildSpreadModel","#flipDuration","#zoomEnabled","#wheelZoom","#doubleClickLevels","#maxZoom","#honorDoubleClickInFlipZone","#clickFlipDelayValue","#ready","#init","#currentPage","#spreads","#current","#singlePage","#narrow","#rebuildSpreads","#renderCurrent","#applySinglePage","#getPage","#sameOriginFile","#outline","#isCrossOrigin","#emitter","#stepFlip","#requestFlip","#startFlip","#spreadIndexForPage","#machine","#activeAnim","#queuedFlip","#finishActiveAnim","#raf","#flushPendingUpgrades","#scale","#tx","#ty","#clampPan","#applyTouchAction","#refreshZoomTiles","#destroyed","#clearPendingClickFlip","#resizeObserver","#deepLink","#unsubscribeDeepLink","#controlsCleanup","#dismissLoader","#a11yCleanup","#unbindWheel","#unbindDblClick","#unbindContextMenu","#unbindInput","#tileTimer","#tileGeneration","#leadPage","#runFlip","#flipGeneration","#resolveContent","#currentContent","#effectiveCurl","#anchorY","#animateProgress","#commit","#announcePage","#effectiveDuration","#announce","#paintSpread","#prefetchWindow","#lastFlipAt","#drainQueuedFlip","#pinching","#pan","#contentRect","#toBookPoint","#press","#pendingGrab","#drag","#stageDrag","#promoteGrab","#swipeFlip","#maybeClickFlip","#cancelFlip","#canFlip","#clickFlipDirection","#pendingClickTimer","#pinchBaseScale","#lastClick","#zoomAt","#onLoadProgress","#mountLoader","#setLoaderPhase","#mountWithFallback","#onPageUpdate","#onDragStart","#onDragMove","#onDragEnd","#onPinchStart","#onPinchMove","#onPinchEnd","#bindWheelZoom","#bindDoubleClickZoom","#bindContextMenu","#setupReducedMotion","#setupA11y","#observeResize","#bindDeepLink","#mountControls","#lastProgress","#loader","#loaderPhase","#fallbackToCss","#fellBack","#reducedMotion","#onKeyDown","#liveRegion","#effectiveMode","#effectiveModeShown","#applyContainerAspect","#zoomedAt","#lastAspect","#pendingUpgrades","#upgradeScale","#renderZoomTiles","#fitFactor","#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/engine/deeplink.ts","../src/renderer/select.ts","../src/source/compose.ts","../src/zine.ts","../src/source/imageSource.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';\nimport type { LoadProgress } from '../source/types.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 /** The document is downloading. Fires only for sources that report byte progress (a PDF from a\n * URL); use it to drive a custom loading indicator, and hide it on `ready`. */\n progress: LoadProgress;\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","/**\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","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, LoadProgress, 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 onProgress?: (handler: (progress: LoadProgress) => 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.onProgress === 'function') {\n // Download progress is about the whole document, not any one page, so it passes straight\n // through: covers and replacements do not shift it.\n this.onProgress = (handler) => base.onProgress!(handler);\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","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 {\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, LoadProgress, OutlineItem, Source } from './source/types';\nimport { composeSource } from './source/compose';\nimport type { ControlsOptions } from './controls/types';\nimport type { LoaderHandle } from './loading/loading';\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. Also the window\n * within which the library pairs two clicks into its own double-click (see #bindDoubleClickZoom). */\nconst DOUBLE_CLICK_MS = 250;\n\n/** How far (px) the second click of a pair may land from the first and still count as the same\n * spot. Forgiving enough for a wobble, tight enough that two different zones don't pair. */\nconst DOUBLE_CLICK_MOVE = 24;\n\n/** Grace period after a flip lands during which a paired double-click in a *dead* edge zone (the\n * first/last spread, where the turn can't happen) is read as the tail of a rapid flipping streak\n * and swallowed rather than zooming. Two streak clicks pair within DOUBLE_CLICK_MS of each other,\n * so two of them span this window; a deliberate zoom comes after the reader pauses on the end\n * page, well outside it. */\nconst FLIP_STREAK_MS = 2 * DOUBLE_CLICK_MS;\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/** Raster texels we want per CSS px for crisp text (roughly retina density). A raster matched 1:1\n * to CSS px looks soft: glyph antialiasing is baked at exactly the on-screen size and then\n * bilinear-sampled under a fractional transform, with nothing to downsample. Rendering ~2x and\n * letting the GPU minify supersamples the edges. A retina display already paints its raster at\n * ~2x CSS px, so this floor is scaled by 1/dpr and only lifts low-dpr screens. */\nconst TEXT_SUPERSAMPLE = 1.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/** Eased fold pose (0..1) at which the page number is announced, while the fold keeps animating to\n * its full duration. The eases decelerate into the finish, so by this pose the turn already reads\n * as landed; announcing here updates the number on time without shortening the visible flip. This\n * is a pure timing lead for the number: it does not touch the animation clock or the end pose. */\nconst PAGE_LEAD = 0.85;\n\n/** The single-page turn ends in a dissolve, not a fold landing on a facing half, so its tail is\n * longer and flatter and read as landed earlier — the number lagged most here. A lower pose\n * threshold announces sooner in that tail, matching when the fade already looks complete. */\nconst PAGE_LEAD_LONE = 0.72;\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 * The built-in loading indicator, shown while a source that reports download progress (a PDF\n * from a URL) fetches and prepares its first spread. On by default; pass `false` to render none\n * and drive your own from the `progress` event and the `ready` promise. Retheme the default with\n * the `--zine-loading-bg`, `--zine-loading-fg`, `--zine-loading-accent`, and `--zine-loading-track`\n * CSS variables.\n */\n loading?: boolean;\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 /** First click of a possible library-detected double-click, and when/where it landed. Kept\n * because the browser's own `dblclick` misfires on rapid streaks (the counter resets). */\n #lastClick: { t: number; x: number; y: number } | null = null;\n /** When the last flip committed (performance.now()). A dead-edge double-click landing soon after\n * is the tail of a flipping streak, not a zoom request; see #zoomAt and FLIP_STREAK_MS. */\n #lastFlipAt = Number.NEGATIVE_INFINITY;\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 #loadingOption: boolean;\n #loader: LoaderHandle | null = null;\n #lastProgress: LoadProgress | null = null;\n /** 'download' while bytes arrive, 'preparing' while the first spread rasterizes, 'done' after\n * it paints. Guards a late-arriving loader chunk from mounting once the book is already up. */\n #loaderPhase: 'download' | 'preparing' | 'done' = 'download';\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.#loadingOption = options.loading ?? 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 * Where the book is actually painted inside the container, in container pixels: the\n * aspect-fitted, centred region, which is shorter (or narrower) than the container whenever the\n * two aspect-ratios do not match. A side rail uses it to stand exactly as tall as the page rather\n * than the whole container. Null before the first paint, when there is nothing to measure yet.\n */\n getPageBox(): { x: number; y: number; width: number; height: number } | null {\n return this.#renderer?.measure().book ?? null;\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 /**\n * Whether this book can be printed: the source must have an original document, and the browser\n * must render PDFs inline. {@link print} loads the file into an offscreen iframe and drives it\n * with `window.print()`, which needs a built-in PDF viewer; Android Chrome has none, so the\n * frame never lays out and the print silently does nothing. `pdfViewerEnabled` reports exactly\n * that capability, so hide the control when it is explicitly false. It is only hidden on that\n * explicit false — a browser too old to report the property (undefined) keeps the button.\n */\n canPrint(): boolean {\n if (typeof this.#source.getDownload !== 'function') return false;\n const nav = this.#container.ownerDocument?.defaultView?.navigator;\n return nav?.pdfViewerEnabled !== false;\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 // A cross-origin PDF loads into the frame but the frame is then cross-origin, so calling\n // print() on its window throws and the dialog never opens. Pull it into a same-origin blob so\n // the frame is scriptable — the same fetch the download path uses.\n const { url, revoke } = await this.#sameOriginFile(info, doc);\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 = 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 (revoke) URL.revokeObjectURL(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 // The `download` attribute is honoured only for same-origin (and blob/data) URLs; for a\n // cross-origin one the browser ignores it and just navigates to the file, opening the PDF in\n // a tab instead of saving it. Pulling the file into a same-origin blob forces the save with\n // its filename.\n const { url, revoke } = await this.#sameOriginFile(info, doc);\n const link = doc.createElement('a');\n link.href = 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 (revoke) setTimeout(() => URL.revokeObjectURL(url), 10_000);\n return true;\n }\n\n /**\n * A same-origin URL for the source file, so an `<a download>` saves it and a print frame can be\n * scripted. A file that is already same-origin, or a blob we made ourselves (`revoke`), is\n * returned unchanged; a cross-origin one is fetched into a blob. The server must allow CORS,\n * which it already does — the viewer fetched the same PDF to render it. On a fetch failure the\n * raw URL is returned (opens in a tab, no worse than before).\n */\n async #sameOriginFile(info: DownloadInfo, doc: Document): Promise<{ url: string; revoke: boolean }> {\n if (info.revoke || !this.#isCrossOrigin(info.url, doc)) {\n return { url: info.url, revoke: info.revoke ?? false };\n }\n try {\n const blob = await (await fetch(info.url)).blob();\n return { url: URL.createObjectURL(blob), revoke: true };\n } catch {\n return { url: info.url, revoke: false };\n }\n }\n\n /** Whether `url` resolves to a different origin than the page, so an `<a download>` would be\n * ignored for it. A relative or same-origin URL, or one that fails to parse, counts as same. */\n #isCrossOrigin(url: string, doc: Document): boolean {\n const here = doc.defaultView?.location?.href;\n if (!here) return false;\n try {\n return new URL(url, here).origin !== new URL(here).origin;\n } catch {\n return false;\n }\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 // Crossing in/out of zoom flips who owns vertical panning: browser scroll at rest, us when zoomed.\n if ((s1 > 1) !== (s2 > 1)) this.#applyTouchAction();\n this.#refreshZoomTiles();\n this.#emitter.emit('zoomChanged', { scale: s2 });\n }\n\n resetZoom(): void {\n this.setZoom(1);\n }\n\n /** Hand the browser the gestures we don't use, so a flipbook filling the viewport doesn't trap\n * the page. At rest we only claim horizontal turns, so vertical panning (page scroll) stays the\n * browser's — `pan-y`. Zoomed in, one finger pans the image in both axes, so we take it all. */\n #applyTouchAction(): void {\n this.#container.style.touchAction = this.#scale > 1 ? 'none' : 'pan-y';\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.#dismissLoader();\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(\n 0,\n 1,\n direction,\n () => this.#commit(targetIndex, toPage, toContent),\n () => this.#announcePage(toPage),\n );\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 onLead?: () => 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. onDone announces the\n // page itself, so there is no separate lead to fire.\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 let ledPage = false;\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 // Both eases decelerate hard into the end, so once the pose crosses the lead threshold the\n // fold already reads as landed. Announce the page number there — once — while the fold plays\n // on to its full duration: the number leads the near-still tail without shortening the flip.\n if (onLead && !ledPage) {\n const lead = this.#singlePage ? PAGE_LEAD_LONE : PAGE_LEAD;\n if (eased >= lead) {\n ledPage = true;\n onLead();\n }\n }\n // `raw < 1` (not `raw >= 1`) so a finished — or NaN, under a rAF stub that omits the\n // timestamp — clock still lands rather than looping forever.\n if (raw < 1) {\n this.#renderer?.setFlipProgress(fromT + (toT - fromT) * eased, direction);\n this.#raf = requestAnimationFrame(step);\n } else {\n this.#renderer?.setFlipProgress(toT, direction);\n this.#raf = null;\n this.#activeAnim = null;\n onDone();\n }\n };\n this.#raf = requestAnimationFrame(step);\n }\n\n /** The page-facing half of a landing: current page, a11y text, and `pageChanged`. Fired from the\n * animation lead a little before the fold finishes so the number updates on time, then guarded\n * so the end-of-flip #commit does not repeat it. A jump with no animation just calls it inline. */\n #announcePage(toPage: number): void {\n if (this.#currentPage === toPage) return; // already led this turn (or nothing moved)\n this.#currentPage = toPage;\n this.#announce();\n this.#emitter.emit('pageChanged', { page: toPage });\n }\n\n #commit(targetIndex: number, toPage: number, toContent: SpreadContent): void {\n const spread = this.#spreads[targetIndex];\n this.#current = targetIndex;\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 // Stamp the landing so a dead-edge double-click that arrives on its heels reads as the tail of\n // a flipping streak rather than a zoom (see #zoomAt).\n this.#lastFlipAt = performance.now();\n // No-op if the animation already led the number; otherwise (reduced motion, a canceled lead,\n // or an interrupt landing before the threshold) this is where it lands.\n this.#announcePage(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 // Grabbable along the whole outer band of each side edge, not just the corners: a drag\n // from the vertical middle should peel and follow the finger too, the way a corner does.\n // The fold then anchors at the grabbed height, so mid-edge grabs curl from the middle.\n const edgeBand = Math.min(b.width, b.height) * CORNER_FRACTION;\n const insidePage = point.x >= 0 && point.x <= b.width && point.y >= 0 && point.y <= b.height;\n const nearSideEdge = point.x <= edgeBand || point.x >= b.width - edgeBand;\n const wantsGrab = insidePage && nearSideEdge;\n // A fold may already be mid-flight when this press lands.\n if (this.#machine.state !== 'idle') {\n // Only an edge grab that can land the running turn takes it over. A live finger drag has\n // no animation to cut short (#activeAnim null), and a non-grab press (centre tap, or an\n // edge *tap* handled on release) must leave the animation to play out — so both bail here.\n // A flip's async content-staging also has #activeAnim null, so that window bails too.\n if (!this.#activeAnim || !wantsGrab) {\n this.#pendingGrab = null;\n return;\n }\n // Commit the running turn now so this grab peels straight on from where the book lands,\n // exactly the way repeated taps interrupt-and-advance. #current updates before we target.\n this.#finishActiveAnim();\n }\n if (!wantsGrab) {\n return; // not near a side edge — 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 point\n // Arm a potential drag; it only becomes a real flip once the pointer moves\n // (so an edge *tap* never fires a spurious flipStart). The right edge\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 grab (the press was not on a side edge, so no live peel armed). A fast\n // horizontal flick from anywhere still turns the page; otherwise it was a tap.\n this.#pendingGrab = null;\n if (!this.#swipeFlip(gesture)) this.#maybeClickFlip(gesture);\n return;\n }\n this.#drag = null;\n this.#machine.send('release');\n\n // A flick at release throws the page, and its direction is the release velocity (vx), not the\n // net displacement: you can peel a page well past halfway and then flick it back toward the\n // edge to let go — the mobile counterpart of dragging back to cancel on desktop. An onward\n // throw commits even from short of halfway; a back-throw cancels even from past it. Position\n // (drag.t) decides only when the release is not a horizontal flick.\n const horizFlick = gesture.swipe && Math.abs(gesture.vx) > Math.abs(gesture.vy);\n const onward = drag.direction === 'forward' ? gesture.vx < 0 : gesture.vx > 0;\n const flungOnward = horizFlick && onward;\n const flungBack = horizFlick && !onward;\n if (flungOnward || (drag.t >= 0.5 && !flungBack)) {\n this.#animateProgress(\n drag.t,\n 1,\n drag.direction,\n () => this.#commit(drag.targetIndex, drag.toPage, drag.toContent),\n () => this.#announcePage(drag.toPage),\n );\n } else {\n this.#animateProgress(drag.t, 0, drag.direction, () => this.#cancelFlip());\n }\n }\n\n /** A fast horizontal flick that started away from the side edges (so no live peel was armed):\n * turn the page in the flick's direction. Returns whether it consumed the gesture, so the caller\n * skips click-to-flip. Zoomed in the same gesture pans, so this only applies at scale 1. */\n #swipeFlip(gesture: GestureEnd): boolean {\n if (this.#scale > 1) return false;\n // A flick, and predominantly horizontal — a vertical flick (page scroll intent) is not a turn.\n if (!gesture.swipe || Math.abs(gesture.dx) <= Math.abs(gesture.dy)) return false;\n // In LTR a leftward flick (dx < 0) turns forward; RTL and the reading direction mirror it.\n const forward = this.#direction === 'rtl' ? gesture.dx > 0 : gesture.dx < 0;\n const direction: FlipDirection = forward ? 'forward' : 'backward';\n if (!this.#canFlip(direction)) return false;\n const step = forward ? 1 : -1;\n this.#requestFlip(() => this.#startFlip(this.#current + step));\n return true;\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 || !this.#canFlip(direction)) 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 step = direction === 'forward' ? 1 : -1;\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 /** Whether a flip in `direction` has somewhere to land: false at the first spread going back\n * and the last spread going forward. A flip zone that fails this is dead, so a double-click\n * there should zoom rather than defer to a turn that can never happen. */\n #canFlip(direction: FlipDirection): boolean {\n const target = this.#current + (direction === 'forward' ? 1 : -1);\n return target >= 0 && target < this.#spreads.length;\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 // The library pairs clicks itself rather than trusting the browser's `dblclick`. The native\n // event drops out on rapid streaks — four fast clicks in one spot fire only a single\n // `dblclick`, because the browser resets its click counter mid-streak (often when the first\n // zoom shifts the target under the pointer). Detecting pairs from raw `click` events makes\n // every second click of a streak zoom (or cycle), so continuous clicks keep toggling.\n const onClick = (event: MouseEvent): void => {\n const levels = this.#doubleClickLevels;\n if (!this.#zoomEnabled || levels === null || !this.#renderer) return;\n const t = performance.now();\n const prev = this.#lastClick;\n const paired =\n prev !== null &&\n t - prev.t <= DOUBLE_CLICK_MS &&\n Math.hypot(event.clientX - prev.x, event.clientY - prev.y) <= DOUBLE_CLICK_MOVE;\n if (!paired) {\n // First click of a potential pair: remember it and wait for a second.\n this.#lastClick = { t, x: event.clientX, y: event.clientY };\n return;\n }\n // Second click within the window → a double-click. Consume it so the next click starts a\n // fresh pair rather than chaining a third click into another zoom.\n this.#lastClick = null;\n this.#zoomAt(event.clientX, event.clientY, levels);\n };\n this.#container.addEventListener('click', onClick as EventListener);\n this.#unbindDblClick = () =>\n this.#container.removeEventListener('click', onClick as EventListener);\n }\n\n /** Cycle to the next configured zoom level, keeping the clicked point fixed. Honors the\n * flip-zone arbitration at scale 1 so an edge double-click still turns the page there, and\n * suppresses zoom on the tail of a rapid flipping streak (see below). */\n #zoomAt(clientX: number, clientY: number, levels: number[]): void {\n // At scale 1 a double-click inside a live 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(clientX, clientY);\n const dir = this.#clickFlipDirection(local);\n // Yield to a zone that can actually turn: click-to-flip owns it, not zoom.\n if (dir !== null && this.#canFlip(dir)) return;\n // Otherwise — a dead edge at the book's ends, or the centre dead zone. That normally zooms,\n // but if the reader is mid-streak (a flip still folding, or one that just landed) the pair is\n // the tail of rapid flipping, not a zoom: swallow it. This is the cover/lone-page glitch —\n // the flip zone sits mid-screen there, so the first click turns the page and the second lands\n // in the centre of the spread it flipped to. A deliberate zoom comes once the reader pauses,\n // past the streak window.\n if (this.#machine.state === 'animating' || performance.now() - this.#lastFlipAt <= FLIP_STREAK_MS) {\n return;\n }\n }\n // A double-click means the single-click flip we may have queued was really a zoom.\n this.#clearPendingClickFlip();\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: clientX - rect.left, y: clientY - rect.top });\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 // Report the download to the progress event and the built-in loader; register before open()\n // so the very first bytes are seen.\n this.#source.onProgress?.((p) => this.#onLoadProgress(p));\n if (typeof this.#source.open === 'function') {\n void this.#mountLoader(); // an async source has a wait worth indicating; sync ones do not\n try {\n await this.#source.open();\n this.#buildSpreadModel(); // page count known now; validates + builds spreads\n } catch (error) {\n this.#dismissLoader(); // tear the overlay down before `ready` rejects\n throw error;\n }\n this.#setLoaderPhase('preparing'); // bytes are in; the wait is now rasterizing\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 // We now own horizontal gestures; hand vertical panning (page scroll) back to the browser.\n this.#applyTouchAction();\n this.#bindWheelZoom();\n this.#bindDoubleClickZoom();\n this.#bindContextMenu();\n this.#setupReducedMotion();\n this.#a11yCleanup = this.#setupA11y();\n\n await this.#renderCurrent();\n this.#dismissLoader(); // the first spread is painted; drop the overlay before the toolbar mounts\n this.#observeResize();\n this.#prefetchWindow();\n this.#announce();\n this.#bindDeepLink();\n await this.#mountControls();\n this.#emitter.emit('ready');\n }\n\n /** Forward a download-progress tick to the public event and the built-in loader. */\n #onLoadProgress(progress: LoadProgress): void {\n this.#lastProgress = progress;\n this.#emitter.emit('progress', progress);\n this.#loader?.update(progress);\n }\n\n /**\n * Fetch the loader chunk and show the overlay, unless disabled or the book is already up.\n *\n * Lazy, so `loading: false` (or a source that never reports progress) never downloads it.\n * Failure is swallowed: a loader that cannot load should cost the reader a spinner, not the book.\n */\n async #mountLoader(): Promise<void> {\n if (this.#loadingOption === false || this.#destroyed) return;\n const container = this.#container;\n if (!container.ownerDocument || typeof container.appendChild !== 'function') return;\n try {\n const { mountLoading } = await import('./loading/loading');\n // The spread may have painted while the chunk was in flight; do not pop an overlay over it.\n if (this.#loaderPhase === 'done' || this.#destroyed) return;\n this.#loader = mountLoading(container);\n if (this.#lastProgress) this.#loader.update(this.#lastProgress);\n if (this.#loaderPhase === 'preparing') this.#loader.preparing();\n } catch {\n // No overlay; the book itself is unaffected.\n }\n }\n\n #setLoaderPhase(phase: 'preparing'): void {\n if (this.#loaderPhase === 'done') return;\n this.#loaderPhase = phase;\n this.#loader?.preparing();\n }\n\n #dismissLoader(): void {\n this.#loaderPhase = 'done';\n this.#loader?.destroy();\n this.#loader = null;\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 * How many device pixels the visible page is painted across, over how many its fit-resolution\n * raster has (the neediest page of the spread). > 1 means the raster is stretched to cover the\n * display and text is soft; < 1 means the raster already has pixels to spare (a high-res image on\n * a low-dpr screen), which must be allowed so a crispness floor doesn't wastefully re-request it.\n *\n * A single-page spread gives one page the width two shared, so a fit raster sized for the double\n * layout is stretched over ~2x the space; this is the magnification the upgrade pass must undo.\n */\n #fitFactor(): number {\n const m = this.#renderer?.measure();\n const box = m?.content ?? m?.book;\n if (!box || box.width <= 0) return 1;\n const c = this.#currentContent;\n const painted = (c.left ? 1 : 0) + (c.right ? 1 : 0);\n if (painted === 0) return 1;\n // Both halves of a spread are equal width, so the per-page painted width is the box over the\n // number of pages in it (1 for a lone page, whose `content` box is already the centered half).\n const paintedPageCss = box.width / painted;\n const dpr = typeof devicePixelRatio === 'number' && devicePixelRatio > 0 ? devicePixelRatio : 1;\n let f = 0;\n for (const p of [c.left, c.right]) {\n if (!p || p.width <= 0) continue;\n // #renderZoomTiles swaps an upgraded (larger) raster into #currentContent and records its\n // multiplier in #zoomedAt; dividing it back out recovers the invariant fit-resolution width,\n // so a re-measure of an already-sharp page reports the same factor instead of flip-flopping\n // between fit and sharp.\n const intrinsic = p.width / this.#zoomedAt;\n f = Math.max(f, (paintedPageCss * dpr) / intrinsic);\n }\n return f === 0 ? 1 : f;\n }\n\n /**\n * The resolution multiplier to rasterize the visible pages at.\n *\n * Three demands compound onto the fit raster. `#fitFactor` covers a page painted larger than its\n * raster (device px). Zoom magnifies it further. And a text-crispness floor lifts the raster to\n * ~2x CSS px even when it already covers the display 1:1, because a 1:1 raster reads soft; the\n * floor is scaled by 1/dpr so a retina screen (already ~2x) is left alone and pays no memory.\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.\n */\n #upgradeScale(): number {\n const dpr = typeof devicePixelRatio === 'number' && devicePixelRatio > 0 ? devicePixelRatio : 1;\n const crispnessFloor = Math.max(1, TEXT_SUPERSAMPLE / dpr);\n const zoom = this.#scale <= 1 ? 1 : this.#scale;\n const raw = this.#fitFactor() * Math.max(zoom, crispnessFloor);\n if (raw <= 1 + 1e-3) return 1;\n return Math.min(Math.ceil(raw * 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 // An upgrade repaints through renderSpread, which clears the renderer's turning leaf. If a flip\n // is animating (rapid edge clicks queue a settle-time upgrade whose debounce fires mid-next-turn)\n // painting now would wipe the curl and the leaf would snap flat. Skip: the flip's own settle\n // repaints and re-requests this once the book is idle, the defer rule #onPageUpdate follows too.\n // Checked here, before the slow rasterize, so a turn in progress costs nothing.\n if (this.#machine.state !== 'idle') 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, zoomed elsewhere, or begun a flip while\n // it resolved (the slow-source race the entry check cannot catch). Any of those and this raster\n // is stale; drop it and let the settle re-request.\n if (\n generation !== this.#tileGeneration ||\n this.#upgradeScale() !== scale ||\n this.#machine.state !== 'idle'\n ) {\n return;\n }\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', 'loading'] 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 const colorScheme = (controls as { colorScheme?: unknown } | undefined)?.colorScheme;\n if (colorScheme !== undefined && !['light', 'dark', 'auto'].includes(colorScheme as string)) {\n throw new Error(\n `Zine: controls.colorScheme must be 'light', 'dark', or 'auto'; got ${JSON.stringify(colorScheme)}.`,\n );\n }\n const arrows = (controls as { arrows?: unknown } | undefined)?.arrows;\n if (arrows !== undefined && typeof arrows !== 'boolean' && !['desktop', 'mobile'].includes(arrows as string)) {\n throw new Error(\n `Zine: controls.arrows must be a boolean, 'desktop', or 'mobile'; got ${JSON.stringify(arrows)}.`,\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"],"mappings":";;;AA8BA,SAAgB,EAAa,GAAmB,IAAyB,CAAC,GAAa;CACrF,IAAM,EAAE,eAAY,OAAO,UAAO,YAAY;CAC9C,IAAI,KAAa,GAAG,OAAO,CAAC;CAE5B,IAAM,KAAQ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ACvC,EAAa,MAAM,MAAW,EAAO,MAAM,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC;EAE9D,KAAKA,GAAO,MAAM;CACpB;CAEA,GAAQ,GAAqC;EAC3C,IAAM,IAAS,KAAKA,GAAO,IAAI,CAAK;EACpC,IAAI,GAAQ,OAAO;EAEnB,IAAM,IAAM,KAAKH,GAAM;EACvB,IAAI,MAAQ,KAAA,GACV,OAAO,QAAQ,OACb,gBAAI,WAAW,qBAAqB,EAAM,uBAAuB,KAAK,YAAY,EAAE,GAAG,CACzF;EAGF,IAAM,KAAW,YAAY;GAC3B,IAAM,IAAM,MAAM,MAAM,CAAG;GAC3B,IAAI,CAAC,EAAI,IACP,MAAU,MAAM,qCAAqC,EAAM,IAAI,EAAI,WAAW,EAAI,OAAO,EAAE;GAE7F,OAAO,kBAAkB,MAAM,EAAI,KAAK,CAAC;EAC3C,EAAA,CAAG,CAAC,CAAC,OAAO,MAAiB;GAE3B,MADA,KAAKG,GAAO,OAAO,CAAK,GAClB;EACR,CAAC;EAGD,OADA,KAAKA,GAAO,IAAI,GAAO,CAAO,GACvB;CACT;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["#radius","#mounted","#listeners","#state","#handlers","#activeId","#start","#prev","#last","#end","#reset","#pinching","#points","#pair","#startDistance","#remove","#base","#front","#back","#rawPages","#resolvePages","#resolved","#image","#cache","#renderer","#container","#source","#direction","#deepLinkEnabled","#disableContextMenu","#spreadMode","#configuredMode","#curl","#clickToFlip","#clickZoneSize","#cursorHints","#hintsEnabled","#hintsPersist","#loadLearned","#soundEnabled","#soundOptions","#soundMuted","#soundPersist","#loadSoundMuted","#singlePageThreshold","#responsiveSpread","#controlsOption","#contextMenuOption","#hiddenControls","#loadingOption","#startPageOption","#buildSpreadModel","#flipDuration","#zoomEnabled","#wheelZoom","#doubleClickLevels","#maxZoom","#honorDoubleClickInFlipZone","#clickFlipDelayValue","#ready","#init","#currentPage","#spreads","#current","#singlePage","#narrow","#rebuildSpreads","#renderCurrent","#applySinglePage","#getPage","#sameOriginFile","#outline","#isCrossOrigin","#emitter","#stepFlip","#requestFlip","#startFlip","#spreadIndexForPage","#machine","#activeAnim","#queuedFlip","#finishActiveAnim","#raf","#flushPendingUpgrades","#scale","#cancelPeek","#cancelNudge","#tx","#ty","#clampPan","#applyTouchAction","#refreshZoomTiles","#updateCursor","#markLearned","#showPanCaption","#sound","#saveSoundMuted","#loadSound","#destroyed","#clearPendingClickFlip","#clearIdleNudge","#clearZoomHint","#hideCaption","#resizeObserver","#deepLink","#unsubscribeDeepLink","#controlsCleanup","#contextMenuCleanup","#dismissLoader","#a11yCleanup","#unbindWheel","#unbindDblClick","#unbindContextMenu","#unbindCursor","#unbindInput","#tileTimer","#tileGeneration","#leadPage","#playFlipSound","#runFlip","#flipGeneration","#resolveContent","#currentContent","#effectiveCurl","#anchorY","#animateProgress","#commit","#announcePage","#effectiveDuration","#announce","#paintSpread","#prefetchWindow","#lastFlipAt","#drainQueuedFlip","#pinching","#pan","#contentRect","#toBookPoint","#press","#pendingGrab","#drag","#stageDrag","#promoteGrab","#swipeFlip","#maybeClickFlip","#cancelFlip","#canFlip","#playEdgeNudge","#clickFlipDirection","#pendingClickTimer","#pointerClient","#cursorFor","#learned","#reducedMotion","#idleTimer","#playPeek","#peekAnim","#repaintRestingSpread","#nudgeAnim","#showCaption","#captionEl","#captionTimer","#zoomHintShown","#lastPointerType","#zoomHintTimer","#zoomHintText","#pinchBaseScale","#lastClick","#maybeArmZoomHint","#zoomAt","#onLoadProgress","#mountLoader","#setLoaderPhase","#mountWithFallback","#onPageUpdate","#onDragStart","#onDragMove","#onDragEnd","#onPinchStart","#onPinchMove","#onPinchEnd","#bindWheelZoom","#bindDoubleClickZoom","#bindContextMenu","#bindCursorHints","#setupReducedMotion","#setupA11y","#observeResize","#bindDeepLink","#mountControls","#armIdleNudge","#soundLoadStarted","#lastProgress","#loader","#loaderPhase","#fallbackToCss","#fellBack","#onKeyDown","#liveRegion","#effectiveMode","#effectiveModeShown","#applyContainerAspect","#zoomedAt","#lastAspect","#pendingUpgrades","#upgradeScale","#renderZoomTiles","#fitFactor","#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/engine/deeplink.ts","../src/renderer/select.ts","../src/source/compose.ts","../src/zine.ts","../src/source/imageSource.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';\nimport type { LoadProgress } from '../source/types.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 /** The document is downloading. Fires only for sources that report byte progress (a PDF from a\n * URL); use it to drive a custom loading indicator, and hide it on `ready`. */\n progress: LoadProgress;\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('Zine: pinch requires two active pointers.');\n return { a, b };\n }\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","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, LoadProgress, 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 onProgress?: (handler: (progress: LoadProgress) => 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.onProgress === 'function') {\n // Download progress is about the whole document, not any one page, so it passes straight\n // through: covers and replacements do not shift it.\n this.onProgress = (handler) => base.onProgress!(handler);\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","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 {\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, LoadProgress, OutlineItem, Source } from './source/types';\nimport { composeSource } from './source/compose';\nimport type { ContextMenuOptions, ControlsOptions } from './controls/types';\nimport type { LoaderHandle } from './loading/loading';\nimport type { FlipSound } from './sound/flipSound';\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. Also the window\n * within which the library pairs two clicks into its own double-click (see #bindDoubleClickZoom). */\nconst DOUBLE_CLICK_MS = 250;\n\n/** How far (px) the second click of a pair may land from the first and still count as the same\n * spot. Forgiving enough for a wobble, tight enough that two different zones don't pair. */\nconst DOUBLE_CLICK_MOVE = 24;\n\n/** Grace period after a flip lands during which a paired double-click in a *dead* edge zone (the\n * first/last spread, where the turn can't happen) is read as the tail of a rapid flipping streak\n * and swallowed rather than zooming. Two streak clicks pair within DOUBLE_CLICK_MS of each other,\n * so two of them span this window; a deliberate zoom comes after the reader pauses on the end\n * page, well outside it. */\nconst FLIP_STREAK_MS = 2 * DOUBLE_CLICK_MS;\n\n/** A lone page fills the container, so it sweeps the full width where a spread leaf only covers\n * its half. `flipDuration` is the spread timing; lone pages stretch it slightly so twice the\n * travel still reads at a comparable speed instead of whipping across. */\nconst LONE_PAGE_FLIP_SCALE = 1.2;\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/** Raster texels we want per CSS px for crisp text (roughly retina density). A raster matched 1:1\n * to CSS px looks soft: glyph antialiasing is baked at exactly the on-screen size and then\n * bilinear-sampled under a fractional transform, with nothing to downsample. Rendering ~2x and\n * letting the GPU minify supersamples the edges. A retina display already paints its raster at\n * ~2x CSS px, so this floor is scaled by 1/dpr and only lifts low-dpr screens. */\nconst TEXT_SUPERSAMPLE = 1.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/** Eased fold pose (0..1) at which the page number is announced, while the fold keeps animating to\n * its full duration. The eases decelerate into the finish, so by this pose the turn already reads\n * as landed; announcing here updates the number on time without shortening the visible flip. This\n * is a pure timing lead for the number: it does not touch the animation clock or the end pose. */\nconst PAGE_LEAD = 0.85;\n\n/** Lone-page turns dissolve rather than land on a facing half; announce a touch earlier than\n * a spread so the number updates as the under-page takes over, not after the fade tail. */\nconst PAGE_LEAD_LONE = 0.82;\n\n/** How far the corner peek hint lifts the leading page (fold progress 0..1) before settling back —\n * enough to read as a liftable page, well short of committing a turn. */\nconst PEEK_PROGRESS = 0.12;\n\n/** Duration of each leg (out, then back) of the corner peek, in ms. */\nconst PEEK_LEG_MS = 360;\n\n/** How far the whole spread slides toward the edge on a dead boundary tap, in px, before it springs\n * back — enough to read as \"nothing past here\", well short of looking like a turn. */\nconst EDGE_NUDGE_PX = 28;\n\n/** Duration of the boundary rubber-band nudge (out and back together), in ms. */\nconst EDGE_NUDGE_MS = 260;\n\n/** How long the reader may sit on the opening spread without turning a page before the peek replays\n * once as a nudge. Long enough not to interrupt someone who is simply reading the first page. */\nconst IDLE_NUDGE_MS = 7000;\n\n/** How long the first-zoom \"drag to move\" caption stays up before fading on its own. */\nconst CAPTION_MS = 2200;\n\n/** localStorage key for learned gestures under `hints.persist`. Shared across books on a site so a\n * gesture learned on one is not re-taught on the next. */\nconst HINTS_STORAGE_KEY = 'zine:hints-learned';\n\n/** localStorage key for the reader's mute choice under `sound.persist`. Shared across books on a\n * site so a reader who silenced (or enabled) flip sound once is remembered everywhere. */\nconst SOUND_MUTED_STORAGE_KEY = 'zine:sound-muted';\n\n/** Which gestures the reader has demonstrated, so the matching discoverability hint stays quiet. */\ninterface Learned {\n turn: boolean;\n zoom: boolean;\n pan: boolean;\n}\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 * On a mouse, change the cursor over the book to hint what a press would do: `pointer` where a\n * click turns the page, `zoom-in` where a double-click zooms (including the edge peel band, so a\n * sweep stays calm), `grab` over the whole page once zoomed (a drag pans), and `grabbing` while a\n * peel or pan is actually in flight. Default true. Set false when a changing cursor would be noise\n * in the embedding design. No effect on touch.\n */\n cursorHints?: boolean;\n /**\n * Subtle, one-shot discoverability hints shown on the book itself (so they reach touch readers,\n * unlike {@link cursorHints}): the leading page corner peeks and settles on first open, nudges\n * once more if the reader sits idle without turning a page, a small \"drag to move\" caption appears\n * the first time they zoom in, and (on a mouse) a \"double-click or Ctrl/⌘-scroll to zoom\" caption\n * appears if a lone click lands in a dead zone where only a double-click would do anything. Each\n * hint stops for good the moment the reader performs the gesture it teaches. Honors\n * `prefers-reduced-motion` (the motion cues are skipped). Default true. Pass an object to keep what\n * the reader has learned across visits: `{ persist: true }` records it in localStorage so a\n * returning reader is not re-taught (default is in-memory, per page load).\n */\n hints?: boolean | { enabled?: boolean; persist?: boolean };\n /**\n * Play a short sound on each page turn. Off by default — web audio is unexpected, so it is\n * strictly opt-in. `true` uses the bundled clip at the default volume; an object overrides it:\n * `url` points at your own clip (fetched at runtime), `volume` is 0..1, and `muted: true` offers\n * the sound but starts it silent so the reader turns it on themselves (via the `mute` control),\n * and `persist: true` remembers the reader's mute choice across visits in localStorage (otherwise\n * it resets each load). Playback is best-effort and never throws: a browser that gates audio behind\n * a gesture, lacks Web Audio, or cannot decode the clip just stays silent. Whenever sound is\n * enabled — audible or muted — a `mute` control appears in the toolbar and right-click menu.\n */\n sound?: boolean | { url?: string; volume?: number; muted?: boolean; persist?: boolean };\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 * The built-in loading indicator, shown while a source that reports download progress (a PDF\n * from a URL) fetches and prepares its first spread. On by default; pass `false` to render none\n * and drive your own from the `progress` event and the `ready` promise. Retheme the default with\n * the `--zine-loading-bg`, `--zine-loading-fg`, `--zine-loading-accent`, and `--zine-loading-track`\n * CSS variables.\n */\n loading?: boolean;\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 * Mutually exclusive with {@link contextMenu}: one replaces the native menu, the other only\n * removes it, so enabling both is a contradiction and throws.\n */\n disableContextMenu?: boolean;\n /**\n * A right-click menu of reading controls (zoom, page turns, fullscreen, print, download, share),\n * opened at the cursor over the book. On by default. Over a canvas the native menu offers only\n * the generic page actions (Back, Reload, View source), so replacing it with the book's own\n * controls is the better trade; pass `false` to keep the browser's menu.\n *\n * Reuses the toolbar's icons and actions, so the same controls appear whether reached from the\n * toolbar or a right-click, and it works even with `controls: false` — a bare book can still\n * offer one. `true` uses the default set; an object with `items` replaces the layout. Mouse\n * affordance only; touch never raises it.\n *\n * Turned off automatically when {@link disableContextMenu} is set (that option removes the native\n * menu with nothing in its place); setting both explicitly throws.\n */\n contextMenu?: boolean | ContextMenuOptions;\n /**\n * Control ids to hide from both surfaces at once: off the toolbar (bar and overflow menu) and out\n * of the right-click menu. `['print', 'download']` removes those two everywhere, wherever they are\n * nested, without having to edit `controls.items` and `contextMenu.items` separately.\n *\n * A blunt cross-cutting filter: it only removes, and it applies to whatever layout each surface\n * ends up with (default or custom). To rearrange or add controls, set the per-surface `items`\n * instead.\n */\n hideControls?: readonly string[];\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 #cursorHints: boolean;\n /** Last mouse position over the container in client px, so the cursor can be re-derived after a\n * page turn, zoom, or resize changes what a press there would do — without the pointer moving. */\n #pointerClient: { x: number; y: number } | null = null;\n #unbindCursor: (() => void) | null = null;\n #hintsEnabled: boolean;\n #hintsPersist: boolean;\n /** Page-flip sound. Off unless `sound` is set; the controller and its clip load lazily (dynamic\n * import) only then, so a silent book pays no audio bytes. Muting is remembered even before the\n * controller finishes loading, via #soundMuted. */\n #soundEnabled: boolean;\n #soundOptions: { url?: string; volume?: number };\n #sound: FlipSound | null = null;\n #soundMuted = false;\n /** Remember the reader's mute choice across visits (localStorage) under `sound.persist`. */\n #soundPersist = false;\n /** Guards the one-time lazy import of the sound chunk. Deferred until sound is actually audible,\n * so a book that starts muted pays nothing until the reader unmutes. */\n #soundLoadStarted = false;\n /** What the reader has demonstrated they already know, so a hint teaching it stays quiet. Set by\n * the gesture itself (a turn, a zoom, a pan); persisted to localStorage when `hints.persist`. */\n #learned: Learned = { turn: false, zoom: false, pan: false };\n /** The one-shot idle nudge timer (armed on ready, cleared by any real gesture). */\n #idleTimer: ReturnType<typeof setTimeout> | null = null;\n /** Tags the peek's own rAF loop so a real flip (or teardown) can cancel a peek mid-play without\n * the stale frame repainting a half-folded page. Distinct from #activeAnim, which is flip-only. */\n #peekAnim: object | null = null;\n /** Tags the boundary rubber-band's rAF loop, so a real flip/drag/zoom (or teardown) cancels a nudge\n * in flight without a stale frame leaving the spread shifted off-center. Shares #raf, like #peekAnim. */\n #nudgeAnim: object | null = null;\n /** The lazily-built hint caption element (null until a caption shows it). */\n #captionEl: HTMLElement | null = null;\n #captionTimer: ReturnType<typeof setTimeout> | null = null;\n /** Delays the \"double-click to zoom\" caption past the pairing window, so a real double-click zooms\n * (which teaches zoom) instead of flashing the hint first. Cleared if the click pairs or zoom is learned. */\n #zoomHintTimer: ReturnType<typeof setTimeout> | null = null;\n /** The zoom caption teaches at most once a session; a reader who ignores it is not nagged on every\n * dead click. (The peek and pan captions are one-shot for the same reason.) */\n #zoomHintShown = false;\n /** pointerType of the last press, so the zoom caption stays mouse-only: touch has no \"double-click\"\n * and double-tap/pinch are already well known (this mirrors why cursorHints is mouse-only). */\n #lastPointerType = '';\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: number | null = null; // 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 /** First click of a possible library-detected double-click, and when/where it landed. Kept\n * because the browser's own `dblclick` misfires on rapid streaks (the counter resets). */\n #lastClick: { t: number; x: number; y: number } | null = null;\n /** When the last flip committed (performance.now()). A dead-edge double-click landing soon after\n * is the tail of a flipping streak, not a zoom request; see #zoomAt and FLIP_STREAK_MS. */\n #lastFlipAt = Number.NEGATIVE_INFINITY;\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 #contextMenuOption: boolean | ContextMenuOptions;\n #contextMenuCleanup: (() => void) | null = null;\n /** Control ids hidden from every surface by {@link ZineOptions.hideControls}. Empty when unset. */\n #hiddenControls: ReadonlySet<string>;\n #loadingOption: boolean;\n #loader: LoaderHandle | null = null;\n #lastProgress: LoadProgress | null = null;\n /** 'download' while bytes arrive, 'preparing' while the first spread rasterizes, 'done' after\n * it paints. Guards a late-arriving loader chunk from mounting once the book is already up. */\n #loaderPhase: 'download' | 'preparing' | 'done' = 'download';\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.#cursorHints = options.cursorHints ?? true;\n const hints = options.hints ?? true;\n this.#hintsEnabled = hints === true || (hints !== false && (hints.enabled ?? true));\n this.#hintsPersist = hints !== true && hints !== false && (hints.persist ?? false);\n if (this.#hintsPersist) this.#loadLearned();\n const sound = options.sound ?? false;\n this.#soundEnabled = sound !== false;\n this.#soundOptions = sound === true || sound === false ? {} : sound;\n // `{ muted: true }` offers the sound but starts it silent: the controller loads, the mute\n // control shows, and the reader unmutes to turn it on.\n this.#soundMuted = typeof sound === 'object' && sound !== null ? (sound.muted ?? false) : false;\n this.#soundPersist = typeof sound === 'object' && sound !== null ? (sound.persist ?? false) : false;\n // A remembered choice from a previous visit overrides the configured default.\n if (this.#soundEnabled && this.#soundPersist) this.#loadSoundMuted();\n this.#singlePageThreshold = options.singlePageThreshold ?? 640;\n this.#responsiveSpread = options.responsiveSpread ?? true;\n this.#controlsOption = options.controls ?? true;\n // On by default, but a book that asked to suppress the native menu with nothing in its place\n // (disableContextMenu) means it: don't hand it our menu unasked. Setting both explicitly is a\n // contradiction and throws in validateOptions.\n this.#contextMenuOption = options.contextMenu ?? (options.disableContextMenu ? false : true);\n this.#hiddenControls = new Set(options.hideControls ?? []);\n this.#loadingOption = options.loading ?? 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 * Where the book is actually painted inside the container, in container pixels: the\n * aspect-fitted, centred region, which is shorter (or narrower) than the container whenever the\n * two aspect-ratios do not match. A side rail uses it to stand exactly as tall as the page rather\n * than the whole container. Null before the first paint, when there is nothing to measure yet.\n */\n getPageBox(): { x: number; y: number; width: number; height: number } | null {\n return this.#renderer?.measure().book ?? null;\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 /**\n * Whether this book can be printed: the source must have an original document, and the browser\n * must render PDFs inline. {@link print} loads the file into an offscreen iframe and drives it\n * with `window.print()`, which needs a built-in PDF viewer; Android Chrome has none, so the\n * frame never lays out and the print silently does nothing. `pdfViewerEnabled` reports exactly\n * that capability, so hide the control when it is explicitly false. It is only hidden on that\n * explicit false — a browser too old to report the property (undefined) keeps the button.\n */\n canPrint(): boolean {\n if (typeof this.#source.getDownload !== 'function') return false;\n const nav = this.#container.ownerDocument?.defaultView?.navigator;\n return nav?.pdfViewerEnabled !== false;\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 // A cross-origin PDF loads into the frame but the frame is then cross-origin, so calling\n // print() on its window throws and the dialog never opens. Pull it into a same-origin blob so\n // the frame is scriptable — the same fetch the download path uses.\n const { url, revoke } = await this.#sameOriginFile(info, doc);\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 = 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 (revoke) URL.revokeObjectURL(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 // The `download` attribute is honoured only for same-origin (and blob/data) URLs; for a\n // cross-origin one the browser ignores it and just navigates to the file, opening the PDF in\n // a tab instead of saving it. Pulling the file into a same-origin blob forces the save with\n // its filename.\n const { url, revoke } = await this.#sameOriginFile(info, doc);\n const link = doc.createElement('a');\n link.href = 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 (revoke) setTimeout(() => URL.revokeObjectURL(url), 10_000);\n return true;\n }\n\n /**\n * A same-origin URL for the source file, so an `<a download>` saves it and a print frame can be\n * scripted. A file that is already same-origin, or a blob we made ourselves (`revoke`), is\n * returned unchanged; a cross-origin one is fetched into a blob. The server must allow CORS,\n * which it already does — the viewer fetched the same PDF to render it. On a fetch failure the\n * raw URL is returned (opens in a tab, no worse than before).\n */\n async #sameOriginFile(info: DownloadInfo, doc: Document): Promise<{ url: string; revoke: boolean }> {\n if (info.revoke || !this.#isCrossOrigin(info.url, doc)) {\n return { url: info.url, revoke: info.revoke ?? false };\n }\n try {\n const blob = await (await fetch(info.url)).blob();\n return { url: URL.createObjectURL(blob), revoke: true };\n } catch {\n return { url: info.url, revoke: false };\n }\n }\n\n /** Whether `url` resolves to a different origin than the page, so an `<a download>` would be\n * ignored for it. A relative or same-origin URL, or one that fails to parse, counts as same. */\n #isCrossOrigin(url: string, doc: Document): boolean {\n const here = doc.defaultView?.location?.href;\n if (!here) return false;\n try {\n return new URL(url, here).origin !== new URL(here).origin;\n } catch {\n return false;\n }\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 this.#cancelPeek(); // a zoom takes over the view; don't leave a peek folding under it\n this.#cancelNudge(); // and don't let a boundary rubber-band fight the zoom's own transform\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 // Crossing in/out of zoom flips who owns vertical panning: browser scroll at rest, us when zoomed.\n if ((s1 > 1) !== (s2 > 1)) this.#applyTouchAction();\n this.#refreshZoomTiles();\n this.#updateCursor(); // crossing in/out of zoom swaps the flip hint for the zoom hint\n // First zoom in: teach panning, since a zoomed page has no visual cue that it can be dragged.\n if (s1 <= 1 && s2 > 1) {\n this.#markLearned('zoom');\n this.#showPanCaption();\n }\n this.#emitter.emit('zoomChanged', { scale: s2 });\n }\n\n resetZoom(): void {\n this.setZoom(1);\n }\n\n /** Whether page-flip sound is enabled for this book (the `sound` option was set). */\n isSoundEnabled(): boolean {\n return this.#soundEnabled;\n }\n\n /** Whether flip sound is currently muted. Always false when sound is not enabled. */\n isSoundMuted(): boolean {\n return this.#soundEnabled && this.#soundMuted;\n }\n\n /** Mute or unmute the flip sound. Remembered even if the sound controller is still loading, and\n * a no-op when `sound` was never enabled. */\n setSoundMuted(muted: boolean): void {\n if (!this.#soundEnabled) return;\n this.#soundMuted = muted;\n this.#sound?.setMuted(muted);\n if (this.#soundPersist) this.#saveSoundMuted(muted);\n // Unmuting a book that started muted is the first time the clip is actually needed: load now.\n if (!muted) void this.#loadSound();\n }\n\n /** Read the reader's remembered mute choice (persist mode), overriding the configured default.\n * Storage can throw in private mode or a sandboxed iframe — fall back to the default silently. */\n #loadSoundMuted(): void {\n try {\n const raw = localStorage.getItem(SOUND_MUTED_STORAGE_KEY);\n if (raw === 'true' || raw === 'false') this.#soundMuted = raw === 'true';\n } catch {\n // No stored choice; keep the configured default.\n }\n }\n\n #saveSoundMuted(muted: boolean): void {\n try {\n localStorage.setItem(SOUND_MUTED_STORAGE_KEY, String(muted));\n } catch {\n // Persisting is best-effort; the in-memory state still holds this session.\n }\n }\n\n /** Hand the browser the gestures we don't use, so a flipbook filling the viewport doesn't trap\n * the page. At rest we only claim horizontal turns, so vertical panning (page scroll) stays the\n * browser's — `pan-y`. Zoomed in, one finger pans the image in both axes, so we take it all. */\n #applyTouchAction(): void {\n this.#container.style.touchAction = this.#scale > 1 ? 'none' : 'pan-y';\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.#clearIdleNudge();\n this.#cancelPeek();\n this.#cancelNudge();\n this.#clearZoomHint();\n this.#hideCaption();\n this.#sound?.destroy();\n this.#sound = null;\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.#contextMenuCleanup?.();\n this.#dismissLoader();\n this.#a11yCleanup?.();\n this.#unbindWheel?.();\n this.#unbindDblClick?.();\n this.#unbindContextMenu?.();\n this.#unbindCursor?.();\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 this.#cancelPeek(); // a real turn is starting; drop any peek folding the same leaf\n this.#cancelNudge(); // and any boundary rubber-band still springing\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 this.#playFlipSound(); // an animated turn (click/swipe/arrow/API) is committed once it starts\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(\n 0,\n 1,\n direction,\n () => this.#commit(targetIndex, toPage, toContent),\n () => this.#announcePage(toPage),\n );\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 onLead?: () => 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. onDone announces the\n // page itself, so there is no separate lead to fire.\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 let ledPage = false;\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 // Same ease for lone and spread so single-page turns feel like the same flipbook, not a\n // stretched dissolve. Curl geometry holds the landed pose through the decelerating tail.\n const raw = Math.min(1, (now - start) / duration);\n const eased = easeInOutQuad(raw);\n // The ease decelerates hard into the end, so once the pose crosses the lead threshold the\n // fold already reads as landed. Announce the page number there — once — while the fold plays\n // on to its full duration: the number leads the near-still tail without shortening the flip.\n if (onLead && !ledPage) {\n const lead = this.#singlePage ? PAGE_LEAD_LONE : PAGE_LEAD;\n if (eased >= lead) {\n ledPage = true;\n onLead();\n }\n }\n // `raw < 1` (not `raw >= 1`) so a finished — or NaN, under a rAF stub that omits the\n // timestamp — clock still lands rather than looping forever.\n if (raw < 1) {\n this.#renderer?.setFlipProgress(fromT + (toT - fromT) * eased, direction);\n this.#raf = requestAnimationFrame(step);\n } else {\n this.#renderer?.setFlipProgress(toT, direction);\n this.#raf = null;\n this.#activeAnim = null;\n onDone();\n }\n };\n this.#raf = requestAnimationFrame(step);\n }\n\n /** The page-facing half of a landing: current page, a11y text, and `pageChanged`. Fired from the\n * animation lead a little before the fold finishes so the number updates on time, then guarded\n * so the end-of-flip #commit does not repeat it. A jump with no animation just calls it inline. */\n #announcePage(toPage: number): void {\n if (this.#currentPage === toPage) return; // already led this turn (or nothing moved)\n this.#currentPage = toPage;\n this.#announce();\n this.#emitter.emit('pageChanged', { page: toPage });\n }\n\n #commit(targetIndex: number, toPage: number, toContent: SpreadContent): void {\n const spread = this.#spreads[targetIndex];\n this.#current = targetIndex;\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 // Stamp the landing so a dead-edge double-click that arrives on its heels reads as the tail of\n // a flipping streak rather than a zoom (see #zoomAt).\n this.#lastFlipAt = performance.now();\n // No-op if the animation already led the number; otherwise (reduced motion, a canceled lead,\n // or an interrupt landing before the threshold) this is where it lands.\n this.#announcePage(toPage);\n this.#markLearned('turn'); // a page has turned — the peek/idle-nudge have taught their lesson\n this.#updateCursor(); // the new spread may have reached an end, killing a flip zone under the pointer\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.#cancelNudge(); // a new press reclaims the view from a boundary rubber-band still springing\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 // Grabbable along the whole outer band of each side edge, not just the corners: a drag\n // from the vertical middle should peel and follow the finger too, the way a corner does.\n // The fold then anchors at the grabbed height, so mid-edge grabs curl from the middle.\n const edgeBand = Math.min(b.width, b.height) * CORNER_FRACTION;\n const insidePage = point.x >= 0 && point.x <= b.width && point.y >= 0 && point.y <= b.height;\n const nearSideEdge = point.x <= edgeBand || point.x >= b.width - edgeBand;\n const wantsGrab = insidePage && nearSideEdge;\n // A fold may already be mid-flight when this press lands.\n if (this.#machine.state !== 'idle') {\n // Only an edge grab that can land the running turn takes it over. A live finger drag has\n // no animation to cut short (#activeAnim null), and a non-grab press (centre tap, or an\n // edge *tap* handled on release) must leave the animation to play out — so both bail here.\n // A flip's async content-staging also has #activeAnim null, so that window bails too.\n if (!this.#activeAnim || !wantsGrab) {\n this.#pendingGrab = null;\n return;\n }\n // Commit the running turn now so this grab peels straight on from where the book lands,\n // exactly the way repeated taps interrupt-and-advance. #current updates before we target.\n this.#finishActiveAnim();\n }\n if (!wantsGrab) {\n return; // not near a side edge — 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 point\n // Arm a potential drag; it only becomes a real flip once the pointer moves\n // (so an edge *tap* never fires a spurious flipStart). The right edge\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 this.#markLearned('pan'); // the reader is panning — the caption has served its purpose\n this.#hideCaption();\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 this.#updateCursor(); // pan over → re-derive the resting hint (no move fires on release)\n return;\n }\n const drag = this.#drag;\n if (!drag) {\n // Never became a grab (the press was not on a side edge, so no live peel armed). A fast\n // horizontal flick from anywhere still turns the page; otherwise it was a tap.\n this.#pendingGrab = null;\n if (!this.#swipeFlip(gesture)) this.#maybeClickFlip(gesture);\n return;\n }\n this.#drag = null;\n this.#machine.send('release');\n\n // A flick at release throws the page, and its direction is the release velocity (vx), not the\n // net displacement: you can peel a page well past halfway and then flick it back toward the\n // edge to let go — the mobile counterpart of dragging back to cancel on desktop. An onward\n // throw commits even from short of halfway; a back-throw cancels even from past it. Position\n // (drag.t) decides only when the release is not a horizontal flick.\n const horizFlick = gesture.swipe && Math.abs(gesture.vx) > Math.abs(gesture.vy);\n const onward = drag.direction === 'forward' ? gesture.vx < 0 : gesture.vx > 0;\n const flungOnward = horizFlick && onward;\n const flungBack = horizFlick && !onward;\n if (flungOnward || (drag.t >= 0.5 && !flungBack)) {\n this.#playFlipSound(); // the drag committed to a turn (flung on, or released past halfway)\n this.#animateProgress(\n drag.t,\n 1,\n drag.direction,\n () => this.#commit(drag.targetIndex, drag.toPage, drag.toContent),\n () => this.#announcePage(drag.toPage),\n );\n } else {\n this.#animateProgress(drag.t, 0, drag.direction, () => this.#cancelFlip());\n }\n }\n\n /** A fast horizontal flick that started away from the side edges (so no live peel was armed):\n * turn the page in the flick's direction. Returns whether it consumed the gesture, so the caller\n * skips click-to-flip. Zoomed in the same gesture pans, so this only applies at scale 1. */\n #swipeFlip(gesture: GestureEnd): boolean {\n if (this.#scale > 1) return false;\n // A flick, and predominantly horizontal — a vertical flick (page scroll intent) is not a turn.\n if (!gesture.swipe || Math.abs(gesture.dx) <= Math.abs(gesture.dy)) return false;\n // In LTR a leftward flick (dx < 0) turns forward; RTL and the reading direction mirror it.\n const forward = this.#direction === 'rtl' ? gesture.dx > 0 : gesture.dx < 0;\n const direction: FlipDirection = forward ? 'forward' : 'backward';\n if (!this.#canFlip(direction)) {\n this.#playEdgeNudge(direction); // swiped past the end: rubber-band toward the edge\n return false;\n }\n const step = forward ? 1 : -1;\n this.#requestFlip(() => this.#startFlip(this.#current + step));\n return true;\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 if (!this.#canFlip(direction)) {\n this.#playEdgeNudge(direction); // nowhere to turn: rubber-band toward the edge instead\n return;\n }\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 step = direction === 'forward' ? 1 : -1;\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 /** Whether a flip in `direction` has somewhere to land: false at the first spread going back\n * and the last spread going forward. A flip zone that fails this is dead, so a double-click\n * there should zoom rather than defer to a turn that can never happen. */\n #canFlip(direction: FlipDirection): boolean {\n const target = this.#current + (direction === 'forward' ? 1 : -1);\n return target >= 0 && target < this.#spreads.length;\n }\n\n /** Watch the pointer at rest and hint what a press there would do through the cursor (mouse only;\n * touch never fires these). A separate listener from the gesture recognizer so it can be removed\n * on its own; both read the same `pointermove` stream. */\n #bindCursorHints(): void {\n const move = (e: Event): void => {\n const p = e as PointerEvent;\n this.#pointerClient = { x: p.clientX, y: p.clientY };\n this.#updateCursor();\n };\n const leave = (): void => {\n this.#pointerClient = null;\n this.#updateCursor();\n };\n this.#container.addEventListener('pointermove', move);\n this.#container.addEventListener('pointerleave', leave);\n this.#unbindCursor = (): void => {\n this.#container.removeEventListener('pointermove', move);\n this.#container.removeEventListener('pointerleave', leave);\n };\n }\n\n /** Re-derive the cursor from the last pointer position. Called both on movement and after a page\n * turn, zoom, or resize changes what a press at the same spot would do without the mouse moving. */\n #updateCursor(): void {\n if (!this.#cursorHints || !this.#renderer) return;\n let cursor = '';\n if (this.#drag || this.#pan) {\n cursor = 'grabbing'; // a peel or pan is in flight — the hand has hold of the page\n } else if (this.#pointerClient) {\n cursor = this.#cursorFor(this.#pointerClient.x, this.#pointerClient.y);\n }\n this.#container.style.cursor = cursor;\n }\n\n /**\n * The cursor for a resting pointer at client (x, y): a hint for what a press would do, read from\n * the same zone classifiers the gestures use. Returns '' (the default arrow) off the drawn page\n * or where a press does nothing.\n *\n * Zoomed in, the whole page pans, so one steady 'grab' covers it — no flicker as the reader moves,\n * and it never lies about a double-click that would zoom back out (grab, not a stale zoom-in). At\n * rest there are two hints: 'pointer' over a live click-to-flip zone, and 'zoom-in' everywhere else\n * a double-click would zoom (including the edge peel band, so a sweep across the page stays calm).\n * A drag peels regardless; it just is not called out with its own resting cursor.\n */\n #cursorFor(clientX: number, clientY: number): string {\n if (!this.#renderer) return '';\n const b = this.#contentRect();\n const p = this.#toBookPoint(clientX, clientY);\n if (p.x < 0 || p.y < 0 || p.x > b.width || p.y > b.height) return ''; // a letterbox bar\n // Zoomed in the page pans everywhere: a drag is the standing gesture, so hint it with grab.\n if (this.#scale > 1) return 'grab';\n // At rest a click turns the page in the flip zones...\n const flipDir = this.#clickFlipDirection(p);\n if (flipDir && this.#canFlip(flipDir)) return 'pointer';\n // ...and elsewhere a double-click zooms in (from rest the next configured level is always up).\n if (this.#zoomEnabled && this.#doubleClickLevels !== null) return 'zoom-in';\n return '';\n }\n\n // --- Discoverability hints (corner peek, idle nudge, first-zoom caption) ---\n\n /** Read the learned flags from localStorage (persist mode). Storage can throw in private mode or a\n * sandboxed iframe, and a corrupt value is not worth crashing over — either way, learn nothing. */\n #loadLearned(): void {\n try {\n const raw = localStorage.getItem(HINTS_STORAGE_KEY);\n if (!raw) return;\n const saved = JSON.parse(raw) as Partial<Learned>;\n this.#learned = {\n turn: saved.turn === true,\n zoom: saved.zoom === true,\n pan: saved.pan === true,\n };\n } catch {\n // No stored history; the reader is simply taught fresh.\n }\n }\n\n /** Record that the reader has performed a gesture, so the hint teaching it stays quiet from now on\n * (and across visits under persist). Idempotent; tears down whatever that signal silences. */\n #markLearned(signal: 'turn' | 'zoom' | 'pan'): void {\n if (this.#learned[signal]) return;\n this.#learned[signal] = true;\n if (signal === 'turn') this.#clearIdleNudge(); // no more peeks once a page has been turned\n if (signal === 'zoom') this.#clearZoomHint(); // reader zoomed; a pending zoom caption is moot\n if (this.#hintsPersist) {\n try {\n localStorage.setItem(HINTS_STORAGE_KEY, JSON.stringify(this.#learned));\n } catch {\n // Persisting is best-effort; the in-memory flag still silences the hint this session.\n }\n }\n }\n\n /** Arm the one-shot idle nudge: if the reader turns no page within IDLE_NUDGE_MS, replay the peek\n * once. Any real turn clears the timer first (see #markLearned('turn')). */\n #armIdleNudge(): void {\n if (!this.#hintsEnabled || this.#reducedMotion || this.#learned.turn) return;\n this.#clearIdleNudge();\n this.#idleTimer = setTimeout(() => {\n this.#idleTimer = null;\n this.#playPeek();\n }, IDLE_NUDGE_MS);\n }\n\n #clearIdleNudge(): void {\n if (this.#idleTimer !== null) {\n clearTimeout(this.#idleTimer);\n this.#idleTimer = null;\n }\n }\n\n /**\n * The corner peek: lift the leading page's outer edge to PEEK_PROGRESS and settle it back, once,\n * without committing a turn. A wordless \"this page turns\" cue that reaches touch and mouse alike.\n *\n * Its own rAF loop, not #animateProgress — that one is wired to #commit and the flip generation.\n * Tagged by #peekAnim so a real flip (or destroy) cancels a peek in flight; the leaf is repainted\n * flat at the end so nothing is left half-folded.\n */\n async #playPeek(): Promise<void> {\n if (\n !this.#hintsEnabled ||\n this.#reducedMotion ||\n this.#learned.turn ||\n !this.#renderer ||\n typeof requestAnimationFrame !== 'function' || // no way to animate; skip the cosmetic cue\n this.#machine.state !== 'idle' // a real flip/drag/pan owns the leaf; don't fight it\n ) {\n return;\n }\n const targetIndex = this.#current + 1;\n const toSpread = this.#spreads[targetIndex];\n if (!toSpread) return; // nothing ahead to peek toward (single spread, or already at the end)\n const toContent = await this.#resolveContent(toSpread);\n // Guard the async gap: a turn, a zoom, a teardown, or a second peek may have intervened.\n if (this.#destroyed || this.#learned.turn || this.#machine.state !== 'idle' || this.#peekAnim) {\n return;\n }\n // Anchor the fold at the bottom-outer corner, the natural place a thumb lifts a page.\n this.#anchorY = 1;\n this.#renderer.beginFlip(this.#currentContent, toContent, 'forward', {\n fill: this.#singlePage,\n curl: this.#effectiveCurl(),\n anchor: { y: this.#anchorY },\n });\n const token = {};\n this.#peekAnim = token;\n const start = performance.now();\n const total = PEEK_LEG_MS * 2;\n // Read the clock from performance.now(), not the rAF timestamp arg: it is what drives the two\n // legs, and it keeps the loop working under a rAF stub that omits the timestamp.\n const step = (): void => {\n if (this.#peekAnim !== token) return; // superseded/cancelled → this frame is void\n const raw = Math.min(1, (performance.now() - start) / total);\n // Out to PEEK_PROGRESS by the midpoint, back to 0 by the end; a soft sine so it eases at both\n // the lift and the settle rather than snapping.\n const t = PEEK_PROGRESS * Math.sin(raw * Math.PI);\n this.#renderer?.setFlipProgress(Math.max(0, t), 'forward');\n if (raw < 1) {\n this.#raf = requestAnimationFrame(step);\n } else {\n this.#raf = null;\n this.#peekAnim = null;\n this.#repaintRestingSpread(); // clear the turning leaf, back to a flat spread\n }\n };\n this.#raf = requestAnimationFrame(step);\n }\n\n /** Stop a peek mid-play (a real gesture is taking over) and leave the spread flat. */\n #cancelPeek(): void {\n if (!this.#peekAnim) return;\n this.#peekAnim = null;\n if (this.#raf !== null) {\n cancelAnimationFrame(this.#raf);\n this.#raf = null;\n }\n this.#repaintRestingSpread();\n }\n\n /** Repaint the current spread flat (no turning leaf), used to land a finished/cancelled peek. */\n #repaintRestingSpread(): void {\n const spread = this.#spreads[this.#current];\n if (spread && this.#machine.state === 'idle') this.#paintSpread(spread, this.#currentContent);\n }\n\n /**\n * The boundary rubber-band: on a tap/swipe that would turn the page but has nowhere to land (the\n * last spread going forward, the first going back), slide the whole spread a little toward that\n * edge and spring it back. A wordless \"this is the end\" that reads on touch and mouse alike.\n *\n * A view-transform animation (setViewTransform), not a fold — there is no next page to curl toward\n * at a boundary. Its own rAF loop, tagged by #nudgeAnim so a real gesture cancels it mid-spring.\n */\n #playEdgeNudge(direction: FlipDirection): void {\n if (\n !this.#renderer ||\n typeof requestAnimationFrame !== 'function' || // no way to animate; skip the cosmetic cue\n this.#reducedMotion ||\n this.#machine.state !== 'idle' || // a flip/drag owns the view; don't fight it\n this.#scale > 1 || // zoomed: the transform is the reader's pan, not ours to move\n this.#nudgeAnim // one nudge at a time\n ) {\n return;\n }\n // Slide toward the edge the reader tried to reach: forward turns off the right in LTR, so the\n // spread travels left (negative x); RTL and backward mirror it.\n const forward = direction === 'forward';\n const toRightEdge = this.#direction === 'rtl' ? !forward : forward;\n const sign = toRightEdge ? -1 : 1;\n const token = {};\n this.#nudgeAnim = token;\n const start = performance.now();\n const step = (): void => {\n if (this.#nudgeAnim !== token) return; // superseded/cancelled → this frame is void\n const raw = Math.min(1, (performance.now() - start) / EDGE_NUDGE_MS);\n // Out to EDGE_NUDGE_PX at the midpoint, back to 0 by the end — a soft sine springs at both ends.\n const offset = EDGE_NUDGE_PX * Math.sin(raw * Math.PI);\n this.#renderer?.setViewTransform(1, sign * offset, 0);\n if (raw < 1) {\n this.#raf = requestAnimationFrame(step);\n } else {\n this.#raf = null;\n this.#nudgeAnim = null;\n this.#renderer?.setViewTransform(1, 0, 0); // land exactly on center\n }\n };\n this.#raf = requestAnimationFrame(step);\n }\n\n /** Stop a boundary nudge mid-spring (a real gesture is taking over) and reset the view to center. */\n #cancelNudge(): void {\n if (!this.#nudgeAnim) return;\n this.#nudgeAnim = null;\n if (this.#raf !== null) {\n cancelAnimationFrame(this.#raf);\n this.#raf = null;\n }\n this.#renderer?.setViewTransform(1, 0, 0);\n }\n\n /** Show the one-time \"drag to move\" caption over the book on the first zoom. Self-contained inline\n * styles: the controls stylesheet is absent when `controls: false`, and this hint must still work.\n * A dark toast pill with light text reads on any page background and either theme. */\n #showPanCaption(): void {\n if (this.#learned.pan) return;\n this.#showCaption('Drag to move'); // panning has no visual analog, so this one hint uses words\n }\n\n /** Show a transient caption pill over the book, replacing any caption already up. Self-contained\n * inline styles: the controls stylesheet is absent when `controls: false`, and a hint must still\n * work. Guarded by #hintsEnabled so `hints: false` shows nothing. */\n #showCaption(text: string): void {\n if (!this.#hintsEnabled) return;\n const doc = this.#container.ownerDocument;\n if (!doc || typeof this.#container.appendChild !== 'function') return;\n this.#hideCaption(); // one pill at a time; drop any caption (and its timer) already showing\n const el = doc.createElement('div');\n el.className = 'zine-hint-caption';\n el.setAttribute('aria-hidden', 'true'); // decorative; screen readers get the gesture via a11y text\n el.textContent = text;\n el.style.cssText =\n 'position:absolute;left:50%;bottom:16px;transform:translateX(-50%);z-index:3;' +\n 'pointer-events:none;padding:6px 12px;border-radius:999px;font:500 13px/1.2 system-ui,sans-serif;' +\n 'color:#fff;background:rgba(24,24,27,0.82);box-shadow:0 1px 4px rgba(0,0,0,0.35);' +\n 'white-space:nowrap;opacity:0;';\n const canAnimate = !this.#reducedMotion && typeof requestAnimationFrame === 'function';\n if (canAnimate) el.style.transition = 'opacity 200ms ease';\n this.#container.appendChild(el);\n this.#captionEl = el;\n if (canAnimate) {\n // Next frame so the initial opacity:0 is committed before the transition to 1.\n requestAnimationFrame(() => {\n if (this.#captionEl === el) el.style.opacity = '1';\n });\n } else {\n el.style.opacity = '1'; // no fade available — just show it\n }\n this.#captionTimer = setTimeout(() => this.#hideCaption(), CAPTION_MS);\n }\n\n /** Remove the caption (on the gesture it taught, its timeout, or teardown). */\n #hideCaption(): void {\n if (this.#captionTimer !== null) {\n clearTimeout(this.#captionTimer);\n this.#captionTimer = null;\n }\n this.#captionEl?.remove();\n this.#captionEl = null;\n }\n\n /** After a lone click lands where only a double-click would do anything (a dead zone at rest),\n * wait out the pairing window; if no second click pairs, the reader tried to act and nothing\n * happened — hint how to zoom. Mouse-only (touch has no double-click), once a session, and never\n * once zoom is learned. A real double-click clears this (it zooms, which teaches zoom directly). */\n #maybeArmZoomHint(clientX: number, clientY: number): void {\n if (!this.#hintsEnabled || this.#learned.zoom || this.#zoomHintShown) return;\n if (this.#lastPointerType !== 'mouse') return;\n // Only where a single click did nothing but a double-click would zoom (dead zone, scale 1, zoom\n // on). #cursorFor already folds in letterbox, flip-zone, and scale arbitration.\n if (this.#cursorFor(clientX, clientY) !== 'zoom-in') return;\n // Not on the tail of a rapid flipping streak — those dead-zone clicks are turning, not zooming.\n if (this.#machine.state === 'animating' || performance.now() - this.#lastFlipAt <= FLIP_STREAK_MS) {\n return;\n }\n this.#clearZoomHint();\n this.#zoomHintTimer = setTimeout(() => {\n this.#zoomHintTimer = null;\n if (this.#learned.zoom || this.#zoomHintShown) return; // a zoom landed while we waited\n this.#zoomHintShown = true;\n this.#showCaption(this.#zoomHintText());\n }, DOUBLE_CLICK_MS);\n }\n\n /** The zoom caption's text, naming whichever zoom gestures are actually enabled. Double-click is\n * always one (this fires only where a double-click would zoom); Ctrl/⌘-scroll is added when wheel\n * zoom is on, with the platform's modifier. */\n #zoomHintText(): string {\n const parts: string[] = [];\n if (this.#doubleClickLevels !== null) parts.push('Double-click');\n if (this.#wheelZoom) {\n const nav = this.#container.ownerDocument?.defaultView?.navigator;\n const mac = /Mac|iPhone|iPad/.test(nav?.platform ?? '');\n parts.push(`${mac ? '⌘' : 'Ctrl'}-scroll`);\n }\n return `${parts.join(' or ')} to zoom`;\n }\n\n #clearZoomHint(): void {\n if (this.#zoomHintTimer !== null) {\n clearTimeout(this.#zoomHintTimer);\n this.#zoomHintTimer = null;\n }\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.#updateCursor(); // the snapped-back spread may have changed the hint under a resting pointer\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 // The library pairs clicks itself rather than trusting the browser's `dblclick`. The native\n // event drops out on rapid streaks — four fast clicks in one spot fire only a single\n // `dblclick`, because the browser resets its click counter mid-streak (often when the first\n // zoom shifts the target under the pointer). Detecting pairs from raw `click` events makes\n // every second click of a streak zoom (or cycle), so continuous clicks keep toggling.\n // Click carries no pointerType; capture it from the preceding pointerdown so the zoom hint can\n // stay mouse-only (touch has no double-click).\n const onDown = (event: PointerEvent): void => {\n this.#lastPointerType = event.pointerType;\n };\n const onClick = (event: MouseEvent): void => {\n const levels = this.#doubleClickLevels;\n if (!this.#zoomEnabled || levels === null || !this.#renderer) return;\n const t = performance.now();\n const prev = this.#lastClick;\n const paired =\n prev !== null &&\n t - prev.t <= DOUBLE_CLICK_MS &&\n Math.hypot(event.clientX - prev.x, event.clientY - prev.y) <= DOUBLE_CLICK_MOVE;\n if (!paired) {\n // First click of a potential pair: remember it and wait for a second.\n this.#lastClick = { t, x: event.clientX, y: event.clientY };\n // A lone click in a dead zone is a reader who tried something and got nothing: hint how to\n // zoom, unless the second click of a pair arrives first (a real zoom teaches it directly).\n this.#maybeArmZoomHint(event.clientX, event.clientY);\n return;\n }\n // Second click within the window → a double-click. Consume it so the next click starts a\n // fresh pair rather than chaining a third click into another zoom.\n this.#lastClick = null;\n this.#clearZoomHint(); // this pair is a real double-click; drop the pending lone-click hint\n this.#zoomAt(event.clientX, event.clientY, levels);\n };\n this.#container.addEventListener('pointerdown', onDown as EventListener);\n this.#container.addEventListener('click', onClick as EventListener);\n this.#unbindDblClick = () => {\n this.#container.removeEventListener('pointerdown', onDown as EventListener);\n this.#container.removeEventListener('click', onClick as EventListener);\n };\n }\n\n /** Cycle to the next configured zoom level, keeping the clicked point fixed. Honors the\n * flip-zone arbitration at scale 1 so an edge double-click still turns the page there, and\n * suppresses zoom on the tail of a rapid flipping streak (see below). */\n #zoomAt(clientX: number, clientY: number, levels: number[]): void {\n // At scale 1 a double-click inside a live 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(clientX, clientY);\n const dir = this.#clickFlipDirection(local);\n // Yield to a zone that can actually turn: click-to-flip owns it, not zoom.\n if (dir !== null && this.#canFlip(dir)) return;\n // Otherwise — a dead edge at the book's ends, or the centre dead zone. That normally zooms,\n // but if the reader is mid-streak (a flip still folding, or one that just landed) the pair is\n // the tail of rapid flipping, not a zoom: swallow it. This is the cover/lone-page glitch —\n // the flip zone sits mid-screen there, so the first click turns the page and the second lands\n // in the centre of the spread it flipped to. A deliberate zoom comes once the reader pauses,\n // past the streak window.\n if (this.#machine.state === 'animating' || performance.now() - this.#lastFlipAt <= FLIP_STREAK_MS) {\n return;\n }\n }\n // A double-click means the single-click flip we may have queued was really a zoom.\n this.#clearPendingClickFlip();\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: clientX - rect.left, y: clientY - rect.top });\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 // Report the download to the progress event and the built-in loader; register before open()\n // so the very first bytes are seen.\n this.#source.onProgress?.((p) => this.#onLoadProgress(p));\n if (typeof this.#source.open === 'function') {\n void this.#mountLoader(); // an async source has a wait worth indicating; sync ones do not\n try {\n await this.#source.open();\n this.#buildSpreadModel(); // page count known now; validates + builds spreads\n } catch (error) {\n this.#dismissLoader(); // tear the overlay down before `ready` rejects\n throw error;\n }\n this.#setLoaderPhase('preparing'); // bytes are in; the wait is now rasterizing\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 // We now own horizontal gestures; hand vertical panning (page scroll) back to the browser.\n this.#applyTouchAction();\n this.#bindWheelZoom();\n this.#bindDoubleClickZoom();\n this.#bindContextMenu();\n this.#bindCursorHints();\n this.#setupReducedMotion();\n this.#a11yCleanup = this.#setupA11y();\n\n await this.#renderCurrent();\n this.#dismissLoader(); // the first spread is painted; drop the overlay before the toolbar mounts\n this.#observeResize();\n this.#prefetchWindow();\n this.#announce();\n this.#bindDeepLink();\n await this.#mountControls();\n void this.#loadSound();\n this.#emitter.emit('ready');\n // The book is live: peek the leading corner once, then watch for an idle reader.\n void this.#playPeek();\n this.#armIdleNudge();\n }\n\n /**\n * Lazily import and build the flip-sound controller, once, when sound is enabled and audible — so\n * a silent book (`sound: false`, or `{ muted: true }` never unmuted) never pulls in the audio code\n * or the bundled clip. Called on ready for an audible book and again when the reader unmutes.\n * Best-effort: a failed import is ignored.\n */\n async #loadSound(): Promise<void> {\n if (!this.#soundEnabled || this.#soundMuted || this.#soundLoadStarted || this.#destroyed) return;\n this.#soundLoadStarted = true;\n try {\n const { FlipSound } = await import('./sound/flipSound');\n if (this.#destroyed) return; // torn down while the chunk loaded\n this.#sound = new FlipSound(this.#soundOptions);\n this.#sound.setMuted(this.#soundMuted); // honor a mute toggled while the chunk arrived\n } catch {\n // No audio code available: the book just stays silent.\n }\n }\n\n /** Play the flip sound, if enabled and ready. Called only where a turn is actually committed. */\n #playFlipSound(): void {\n this.#sound?.play();\n }\n\n /** Forward a download-progress tick to the public event and the built-in loader. */\n #onLoadProgress(progress: LoadProgress): void {\n this.#lastProgress = progress;\n this.#emitter.emit('progress', progress);\n this.#loader?.update(progress);\n }\n\n /**\n * Fetch the loader chunk and show the overlay, unless disabled or the book is already up.\n *\n * Lazy, so `loading: false` (or a source that never reports progress) never downloads it.\n * Failure is swallowed: a loader that cannot load should cost the reader a spinner, not the book.\n */\n async #mountLoader(): Promise<void> {\n if (this.#loadingOption === false || this.#destroyed) return;\n const container = this.#container;\n if (!container.ownerDocument || typeof container.appendChild !== 'function') return;\n try {\n const { mountLoading } = await import('./loading/loading');\n // The spread may have painted while the chunk was in flight; do not pop an overlay over it.\n if (this.#loaderPhase === 'done' || this.#destroyed) return;\n this.#loader = mountLoading(container);\n if (this.#lastProgress) this.#loader.update(this.#lastProgress);\n if (this.#loaderPhase === 'preparing') this.#loader.preparing();\n } catch {\n // No overlay; the book itself is unaffected.\n }\n }\n\n #setLoaderPhase(phase: 'preparing'): void {\n if (this.#loaderPhase === 'done') return;\n this.#loaderPhase = phase;\n this.#loader?.preparing();\n }\n\n #dismissLoader(): void {\n this.#loaderPhase = 'done';\n this.#loader?.destroy();\n this.#loader = null;\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 and the right-click menu, whichever are wanted, if the container is real DOM.\n *\n * The chunk is fetched lazily so a book with neither feature never downloads it. Both share the\n * one chunk, so a book with `controls: false` but `contextMenu` on still gets the right-click menu\n * without a toolbar. Failure is swallowed on purpose: controls that cannot load should cost the\n * reader the controls, not the whole flipbook — `#init` has no error handling of its own, so a\n * throw here would reject `ready`.\n */\n async #mountControls(): Promise<void> {\n const wantsToolbar = this.#controlsOption !== false;\n const wantsContextMenu = this.#contextMenuOption !== false;\n if ((!wantsToolbar && !wantsContextMenu) || this.#destroyed) return;\n const container = this.#container;\n if (!container.ownerDocument || typeof container.appendChild !== 'function') return;\n try {\n const { mountControls, mountContextMenu } = await import('./controls/controls');\n if (this.#destroyed) return; // destroyed while the chunk was in flight\n if (this.#controlsOption !== false) {\n const options = this.#controlsOption === true ? {} : this.#controlsOption;\n this.#controlsCleanup = mountControls(this, container, options, this.#hiddenControls);\n }\n if (this.#contextMenuOption !== false) {\n const options = this.#contextMenuOption === true ? {} : this.#contextMenuOption;\n this.#contextMenuCleanup = mountContextMenu(this, container, options, this.#hiddenControls);\n }\n } catch {\n // No controls; 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 this.#updateCursor(); // the drawn box (and its zones) may have moved under a resting pointer\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;\n // Tolerance, not exact equality: writing `aspect-ratio` resizes the container, whose ResizeObserver\n // re-measures a book box off by a sub-pixel and would rewrite a marginally different ratio, an\n // endless resize/measure/write feedback loop (cheap for images, but re-rasterizes a PDF each turn,\n // freezing the tab). Ignoring changes below ~0.5% lets it settle after the first write.\n if (this.#lastAspect !== null && Math.abs(ratio - this.#lastAspect) < 0.005) return;\n this.#lastAspect = ratio;\n this.#container.style.aspectRatio = ratio.toFixed(4);\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)) return;\n // While the reader is zoomed, the upgrade touched the fit raster underneath the sharp tile, not\n // what they see. A fit #renderCurrent would flash the page soft before the tiles rebuilt; refresh\n // the tiles instead (a no-op when they are already at the viewed scale).\n if (this.#scale > 1) {\n this.#refreshZoomTiles();\n return;\n }\n void this.#renderCurrent();\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 * How many device pixels the visible page is painted across, over how many its fit-resolution\n * raster has (the neediest page of the spread). > 1 means the raster is stretched to cover the\n * display and text is soft; < 1 means the raster already has pixels to spare (a high-res image on\n * a low-dpr screen), which must be allowed so a crispness floor doesn't wastefully re-request it.\n *\n * A single-page spread gives one page the width two shared, so a fit raster sized for the double\n * layout is stretched over ~2x the space; this is the magnification the upgrade pass must undo.\n */\n #fitFactor(): number {\n const m = this.#renderer?.measure();\n const box = m?.content ?? m?.book;\n if (!box || box.width <= 0) return 1;\n const c = this.#currentContent;\n const painted = (c.left ? 1 : 0) + (c.right ? 1 : 0);\n if (painted === 0) return 1;\n // Both halves of a spread are equal width, so the per-page painted width is the box over the\n // number of pages in it (1 for a lone page, whose `content` box is already the centered half).\n const paintedPageCss = box.width / painted;\n const dpr = typeof devicePixelRatio === 'number' && devicePixelRatio > 0 ? devicePixelRatio : 1;\n let f = 0;\n for (const p of [c.left, c.right]) {\n if (!p || p.width <= 0) continue;\n // #renderZoomTiles swaps an upgraded (larger) raster into #currentContent and records its\n // multiplier in #zoomedAt; dividing it back out recovers the invariant fit-resolution width,\n // so a re-measure of an already-sharp page reports the same factor instead of flip-flopping\n // between fit and sharp.\n const intrinsic = p.width / this.#zoomedAt;\n f = Math.max(f, (paintedPageCss * dpr) / intrinsic);\n }\n return f === 0 ? 1 : f;\n }\n\n /**\n * The resolution multiplier to rasterize the visible pages at.\n *\n * Three demands compound onto the fit raster. `#fitFactor` covers a page painted larger than its\n * raster (device px). Zoom magnifies it further. And a text-crispness floor lifts the raster to\n * ~2x CSS px even when it already covers the display 1:1, because a 1:1 raster reads soft; the\n * floor is scaled by 1/dpr so a retina screen (already ~2x) is left alone and pays no memory.\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.\n */\n #upgradeScale(): number {\n const dpr = typeof devicePixelRatio === 'number' && devicePixelRatio > 0 ? devicePixelRatio : 1;\n const crispnessFloor = Math.max(1, TEXT_SUPERSAMPLE / dpr);\n const zoom = this.#scale <= 1 ? 1 : this.#scale;\n const raw = this.#fitFactor() * Math.max(zoom, crispnessFloor);\n if (raw <= 1 + 1e-3) return 1;\n return Math.min(Math.ceil(raw * 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 // An upgrade repaints through renderSpread, which clears the renderer's turning leaf. If a flip\n // is animating (rapid edge clicks queue a settle-time upgrade whose debounce fires mid-next-turn)\n // painting now would wipe the curl and the leaf would snap flat. Skip: the flip's own settle\n // repaints and re-requests this once the book is idle, the defer rule #onPageUpdate follows too.\n // Checked here, before the slow rasterize, so a turn in progress costs nothing.\n if (this.#machine.state !== 'idle') 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, {\n scale,\n region: whole,\n maxSize: this.#renderer?.maxTextureSize,\n });\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, zoomed elsewhere, or begun a flip while\n // it resolved (the slow-source race the entry check cannot catch). Any of those and this raster\n // is stale; drop it and let the settle re-request.\n if (\n generation !== this.#tileGeneration ||\n this.#upgradeScale() !== scale ||\n this.#machine.state !== 'idle'\n ) {\n return;\n }\n // A side whose upgrade threw comes back null; keep the readable fit raster already on screen\n // rather than blanking that half (the upgrade is an enhancement, per the get() catch above).\n const left = pages[0] ?? this.#currentContent.left;\n const right = pages[1] ?? this.#currentContent.right;\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) return;\n // Same rule as #onPageUpdate: while the reader is zoomed, a fit #renderCurrent would flash the\n // page soft before the tiles rebuilt. Refresh the tiles instead. Gated on the live zoom scale,\n // not #zoomedAt: the #commit that leads here just repainted at fit and reset #zoomedAt to 1.\n if (this.#scale > 1) this.#refreshZoomTiles();\n else 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\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', 'loading'] 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 const colorScheme = (controls as { colorScheme?: unknown } | undefined)?.colorScheme;\n if (colorScheme !== undefined && !['light', 'dark', 'auto'].includes(colorScheme as string)) {\n throw new Error(\n `Zine: controls.colorScheme must be 'light', 'dark', or 'auto'; got ${JSON.stringify(colorScheme)}.`,\n );\n }\n const arrows = (controls as { arrows?: unknown } | undefined)?.arrows;\n if (arrows !== undefined && typeof arrows !== 'boolean' && !['desktop', 'mobile'].includes(arrows as string)) {\n throw new Error(\n `Zine: controls.arrows must be a boolean, 'desktop', or 'mobile'; got ${JSON.stringify(arrows)}.`,\n );\n }\n\n const contextMenu = o.contextMenu;\n if (contextMenu !== undefined && typeof contextMenu !== 'boolean' && (typeof contextMenu !== 'object' || contextMenu === null)) {\n throw new Error(\n `Zine: contextMenu must be a boolean or an options object; got ${typeName(contextMenu)}.`,\n );\n }\n const menuColorScheme = (contextMenu as { colorScheme?: unknown } | undefined)?.colorScheme;\n if (menuColorScheme !== undefined && !['light', 'dark', 'auto'].includes(menuColorScheme as string)) {\n throw new Error(\n `Zine: contextMenu.colorScheme must be 'light', 'dark', or 'auto'; got ${JSON.stringify(menuColorScheme)}.`,\n );\n }\n if (o.disableContextMenu === true && contextMenu !== undefined && contextMenu !== false) {\n throw new Error(\n \"Zine: disableContextMenu and contextMenu are mutually exclusive — one removes the browser's \" +\n 'right-click menu, the other replaces it. Enable only one.',\n );\n }\n\n const hideControls = o.hideControls;\n if (\n hideControls !== undefined &&\n (!Array.isArray(hideControls) || hideControls.some((id) => typeof id !== 'string'))\n ) {\n throw new Error(\n `Zine: hideControls must be an array of control-id strings; got ${typeName(hideControls)}.`,\n );\n }\n\n const sound = o.sound;\n if (sound !== undefined && typeof sound !== 'boolean' && (typeof sound !== 'object' || sound === null)) {\n throw new Error(`Zine: sound must be a boolean or an options object; got ${typeName(sound)}.`);\n }\n if (typeof sound === 'object' && sound !== null) {\n const s = sound as { url?: unknown; volume?: unknown; muted?: unknown; persist?: unknown };\n if (s.url !== undefined && typeof s.url !== 'string') {\n throw new Error(`Zine: sound.url must be a string URL; got ${typeName(s.url)}.`);\n }\n if (s.volume !== undefined && (typeof s.volume !== 'number' || s.volume < 0 || s.volume > 1)) {\n throw new Error(`Zine: sound.volume must be a number between 0 and 1; got ${JSON.stringify(s.volume)}.`);\n }\n if (s.muted !== undefined && typeof s.muted !== 'boolean') {\n throw new Error(`Zine: sound.muted must be a boolean; got ${typeName(s.muted)}.`);\n }\n if (s.persist !== undefined && typeof s.persist !== 'boolean') {\n throw new Error(`Zine: sound.persist must be a boolean; got ${typeName(s.persist)}.`);\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"],"mappings":";;;AA8BA,SAAgB,EAAa,GAAmB,IAAyB,CAAC,GAAa;CACrF,IAAM,EAAE,eAAY,OAAO,UAAO,YAAY;CAC9C,IAAI,KAAa,GAAG,OAAO,CAAC;CAE5B,IAAM,KAAQ,MAA8B,KAAK,KAAK,IAAI,IAAY,IAAI,MACpE,IAAoB,CAAC;CAE3B,IAAI,MAAS,UACX,KAAK,IAAI,IAAI,GAAG,IAAI,GAAW,KAAK,EAAQ,KAAK;EAAE,MAAM;EAAM,OAAO;CAAE,CAAC;MACpE,IAAI,MAAS,UAClB,KAAK,IAAI,IAAI,GAAG,IAAI,GAAW,KAAK,GAAG,EAAQ,KAAK;EAAE,MAAM,EAAK,CAAC;EAAG,OAAO,EAAK,IAAI,CAAC;CAAE,CAAC;MACpF,IAAI,MAAS,SAAS;EAC3B,EAAQ,KAAK;GAAE,MAAM;GAAM,OAAO;EAAE,CAAC;EACrC,KAAK,IAAI,IAAI,GAAG,IAAI,GAAW,KAAK,GAAG,EAAQ,KAAK;GAAE,MAAM,EAAK,CAAC;GAAG,OAAO,EAAK,IAAI,CAAC;EAAE,CAAC;CAC3F,OAGE,IADA,EAAQ,KAAK;EAAE,MAAM;EAAM,OAAO;CAAE,CAAC,GACjC,IAAY,GAAG;EACjB,KAAK,IAAI,IAAI,GAAG,KAAK,IAAY,GAAG,KAAK,GACvC,EAAQ,KAAK;GAAE,MAAM,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