{"version":3,"file":"index.cjs","names":["ActionsToken","NO_FRAME","ZoomMode","ZOOM_MIN","ZOOM_MAX","ZoomMode","ZOOM_MAX","ZOOM_MIN","ZoomMode","PluginError","StageToken","ActionsToken","StageToken","ZoomMode"],"sources":["../src/working-set.ts","../src/connect.ts","../src/motion.ts","../src/camera/animation.ts","../src/responsive.ts","../src/settings.ts","../src/model.ts","../src/camera/gestures.ts","../src/navigation/turn.ts","../src/camera/coasting.ts","../src/camera/wheel.ts","../src/camera/write.ts","../src/services/placement-latch.ts","../src/navigation/arrive.ts","../src/destination.ts","../src/navigation/reveal.ts","../src/navigation/zoom.ts","../src/navigation/zoom-drag.ts","../src/read/pages.ts","../src/services/events.ts","../src/services/scene.ts","../src/services/index.ts","../src/settings/settings.ts","../src/view/lifecycle.ts","../src/controller.ts","../src/stage.plugin.ts","../src/state.ts","../src/scroll-handler.ts","../src/zoom-drag-handler.ts"],"sourcesContent":["/**\n * What this lens shows, told to the engine as the lens's working set\n * (`doc.setWorkingSet`): the engine ranks the jobs for those pages by it, and\n * keeps those pages parsed longest. Every lens tells its own, so a thumbnail\n * rail's small pages rank after the main view's.\n *\n * It comes from the pages the lens lays out (`listVisiblePages`):\n * - `visible`: a page with some of it on screen, with that part and its device\n *   pixels, which rank visible pages among themselves: the page the user looks\n *   at has the most;\n * - `near`: a page laid out just off screen (the scene's overscan), where the\n *   view goes next.\n */\nimport type { PluginContext, WorkingSetPage } from '@embedpdf/core';\n\nimport type { VisiblePage } from './contract';\nimport type { StageHostCapability } from './host-contract';\nimport type { StageModel } from './model';\n\n/** A lens's working set, from the pages it lays out. */\nexport function workingSetOf(pages: readonly VisiblePage[]): WorkingSetPage[] {\n  return pages.map(({ ref, visibleRect, transform }) => {\n    if (visibleRect.width <= 0 || visibleRect.height <= 0) {\n      return { page: ref, role: 'near', pixels: 0 };\n    }\n    const pixels = visibleRect.width * visibleRect.height * transform.renderScale ** 2;\n    return { page: ref, role: 'visible', visible: visibleRect, pixels: Math.round(pixels) };\n  });\n}\n\n/**\n * Tells the engine what the lens shows, now and whenever it changes: once per\n * camera move, so at most once per input event while the camera moves.\n */\nexport function connectWorkingSet(\n  ctx: PluginContext<StageModel>,\n  stage: Pick<StageHostCapability, 'listVisiblePages'>,\n): void {\n  let told = '';\n  const tell = (shown: readonly VisiblePage[]) => {\n    const pages = workingSetOf(shown);\n    const key = keyOf(pages);\n    if (key === told) return;\n    told = key;\n    ctx.doc.setWorkingSet(ctx.id, pages);\n  };\n  ctx.watch(() => stage.listVisiblePages(), tell);\n  tell(stage.listVisiblePages());\n}\n\n/** A working set as one comparable string. */\nfunction keyOf(pages: readonly WorkingSetPage[]): string {\n  return pages\n    .map(({ page, role, visible, pixels }) => {\n      const part = visible\n        ? `${Math.round(visible.x)},${Math.round(visible.y)},${Math.round(visible.width)},${Math.round(visible.height)}`\n        : '';\n      return `${page.objectNumber}:${role}:${pixels}:${part}`;\n    })\n    .join('|');\n}\n","/**\n * The stage's wiring to its surroundings, run once every dependency exists:\n * the refit on page-registry changes and the working set told to the engine\n * (every lens) and, for the default lens only, the page-state feed and the navigation executors of the actions\n * plugin. A thumbnail lens must never report page state or win the\n * last-wins executor registry and start navigating the sidebar.\n */\nimport type { PluginContext } from '@embedpdf/core';\nimport { ActionsToken, type ActionsHostCapability } from '@embedpdf/plugin-actions/contract/host';\n\nimport type { StageHostCapability } from './host-contract';\nimport type { StageModel } from './model';\nimport { connectWorkingSet } from './working-set';\n\n/** The id of the main lens; additional lenses register under their own id. */\nexport const DEFAULT_LENS_ID = 'stage';\n\nexport function connectStage(ctx: PluginContext<StageModel>, stage: StageHostCapability): void {\n  // Rotate, move and delete change the registry revision, so the page geometry\n  // under this lens changed: re-resolve the zoom intent and re-place. It\n  // reacts to changes only, never to the initial value, so it cannot race the\n  // level-triggered initial placement.\n  ctx.watch(\n    () => ctx.document()?.pagesSequence ?? 0,\n    () => stage.refit(),\n  );\n  connectWorkingSet(ctx, stage);\n\n  if (ctx.id !== DEFAULT_LENS_ID) return;\n  const actions = ctx.tryGet(ActionsToken);\n  if (!actions) return;\n  feedPageState(ctx, stage, actions);\n  registerNavigationExecutors(ctx, stage, actions);\n}\n\n/**\n * The page-state feed. The stage is authoritative for what page the viewer is\n * on; the actions plugin's lifecycle coordinator owns when page-lifecycle\n * triggers fire. The feed reports `{ currentPage, visiblePages, placed, cause }`\n * (page refs, not indexes, so reordering is safe) on placement and on every\n * change; the coordinator buffers reports until the document has opened and\n * diffs them against what it last emitted, so this side only reports.\n */\nfunction feedPageState(\n  ctx: PluginContext<StageModel>,\n  stage: StageHostCapability,\n  actions: ActionsHostCapability,\n): void {\n  const snapshot = () => {\n    const state = ctx.state.get();\n    if (!state.placed) return null;\n    return {\n      currentPage: stage.getCurrentPage(),\n      visiblePages: stage.listVisiblePages().map((page) => page.ref),\n      cause: state.motionCause,\n    };\n  };\n  ctx.watch(\n    // The signature covers what is reported: the current page and the visible\n    // page set. `cause` is left out on purpose: a cause flip alone is not a\n    // page-state change and must not produce a report.\n    () => {\n      const current = snapshot();\n      return current === null\n        ? 'unplaced'\n        : `${current.currentPage?.objectNumber ?? -1}|${current.visiblePages\n            .map((page) => page.objectNumber)\n            .sort((left, right) => left - right)\n            .join(',')}`;\n    },\n    () => {\n      const current = snapshot();\n      if (current === null) return;\n      actions.reportPageState({\n        currentPage: current.currentPage,\n        visiblePages: current.visiblePages,\n        placed: true,\n        cause: current.cause,\n      });\n    },\n  );\n}\n\n/**\n * The GoTo and Named page verbs for the action engine. The dispatcher runs\n * them as deferred navigation effects, after every document node of a tree\n * succeeded, never in the middle of a walk. They move the view by its own\n * `scrollBehavior` setting, as a link does. /N Print is not handled here: the\n * dispatcher owns it (policy and the UI adapter).\n */\nfunction registerNavigationExecutors(\n  ctx: PluginContext<StageModel>,\n  stage: StageHostCapability,\n  actions: ActionsHostCapability,\n): void {\n  ctx.cleanup(\n    actions.registerExecutor('goto', (node) => {\n      if (node.type !== 'goto') return { status: 'inert', reason: 'not a goto node' };\n      if (!ctx.getPage(node.destination.page))\n        return { status: 'failed', error: 'the destination page is not in this document' };\n      stage.goToDestination(node.destination);\n      return { status: 'executed' };\n    }),\n  );\n  ctx.cleanup(\n    actions.registerExecutor('named', (node) => {\n      if (node.type !== 'named') return { status: 'inert', reason: 'not a named node' };\n      switch (node.name) {\n        case 'NextPage':\n          stage.nextPage();\n          return { status: 'executed' };\n        case 'PrevPage':\n          stage.previousPage();\n          return { status: 'executed' };\n        case 'FirstPage':\n          stage.goToFirstPage();\n          return { status: 'executed' };\n        case 'LastPage':\n          stage.goToLastPage();\n          return { status: 'executed' };\n        default:\n          return { status: 'inert', reason: `unknown named action '${node.name}'` };\n      }\n    }),\n  );\n}\n","/**\n * The camera's motion vocabulary, every formula pure.\n *\n * The capability owns the impure drivers (the clock's frames, state writes,\n * gesture state); the laws those drivers integrate live here, parameterized\n * by elapsed time with no state and no clock, so they are unit-testable in\n * isolation and have no plugin dependencies.\n *\n * Two families:\n *   • ballistic — one per-axis law for every free motion: `glideStep` (the\n *     touch fling, decaying on UIScrollView's curve) and `springStep` (a\n *     critically-damped return to the clamp). A glide that reaches a content\n *     edge converts to a spring with its velocity carried in, so the bounce\n *     grows out of physics rather than a scripted overshoot.\n *   • resistance — the iOS rubber-band curve `rubberOut` and its exact inverse\n *     `rubberIn`: dragging past an edge displays an asymptotically bounded\n *     stretch, and re-entering a gesture over a stretched camera (catching it\n *     mid-bounce) reconstructs the finger-integrated position the curve came\n *     from.\n * Plus the tween interpolators: `easeOutCubic` for coordinate tweens and\n * `zoomLerp`, a geometric zoom interpolation (zoom is multiplicative: equal\n * ratios per unit time, not equal deltas).\n */\n\n// ── constants ──\n/** Resistance coefficient of the rubber-band curve (the iOS feel). */\nexport const RUBBER = 0.55;\n/** Glide decay per ms: UIScrollView's normal deceleration rate. */\nexport const FLING_DECAY = 0.998;\n/** px/ms; below about 20 px/s the eye reads \"stopped\". */\nexport const FLING_STOP = 0.02;\n/** rad/ms; critically damped, settling in about 400 ms. */\nexport const SPRING_OMEGA = 0.015;\n\n// ── resistance (rubber-band) ──\n/**\n * Overshoot distance → displayed stretch, asymptotic to the viewport\n * dimension, so the content never leaves the screen however far the finger\n * travels. `rubberOut(0) === 0`: inside the bounds the curve is invisible.\n */\nexport const rubberOut = (distance: number, dimension: number): number =>\n  (1 - 1 / ((distance * RUBBER) / dimension + 1)) * dimension;\n/** The exact inverse of `rubberOut` (defined for `stretch < dimension`). */\nexport const rubberIn = (stretch: number, dimension: number): number =>\n  (stretch * dimension) / (RUBBER * (dimension - stretch));\n\n// ── ballistic (one axis, one frame) ──\n/** The state one integration step hands back; `done` means \"at rest\". */\nexport interface MotionStep {\n  position: number;\n  velocity: number;\n  done: boolean;\n}\n/**\n * One frame of free glide: exponential velocity decay, the position advanced\n * by the midpoint integral of the decay over `elapsedMs` (exact for the\n * exponential, so frame-rate independent).\n */\nexport const glideStep = (position: number, velocity: number, elapsedMs: number): MotionStep => {\n  const decay = Math.pow(FLING_DECAY, elapsedMs);\n  const nextPosition = position + velocity * ((elapsedMs * (1 + decay)) / 2);\n  const nextVelocity = velocity * decay;\n  return Math.abs(nextVelocity) < FLING_STOP\n    ? { position: nextPosition, velocity: 0, done: true }\n    : { position: nextPosition, velocity: nextVelocity, done: false };\n};\n/**\n * One frame of a critically-damped spring toward `edge`: semi-implicit Euler\n * on x'' = −ω²(x−e) − 2ωx'. Lands exactly on the edge (position snapped,\n * velocity zeroed) once within half a pixel at negligible speed.\n */\nexport const springStep = (\n  position: number,\n  velocity: number,\n  edge: number,\n  elapsedMs: number,\n): MotionStep => {\n  const nextVelocity =\n    velocity +\n    (-SPRING_OMEGA * SPRING_OMEGA * (position - edge) - 2 * SPRING_OMEGA * velocity) * elapsedMs;\n  const nextPosition = position + nextVelocity * elapsedMs;\n  if (Math.abs(nextPosition - edge) < 0.5 && Math.abs(nextVelocity) < 0.01) {\n    return { position: edge, velocity: 0, done: true };\n  }\n  return { position: nextPosition, velocity: nextVelocity, done: false };\n};\n\n// ── tween interpolators ──\nexport const easeOutCubic = (progress: number): number => 1 - Math.pow(1 - progress, 3);\n/**\n * Geometric zoom interpolation: `from·(to/from)^progress`. Zoom is\n * multiplicative, so a constant-rate zoom moves equal ratios per unit time;\n * interpolating the level linearly makes the start rush and the end crawl\n * (and, under a focal anchor, swings the anchored point along a curve).\n */\nexport const zoomLerp = (from: number, to: number, progress: number): number =>\n  from * Math.pow(to / from, progress);\n","/**\n * Camera motion over the host's frames (`ctx.clock`): the coordinate tween,\n * the zoom-anchored tween (it animates the invariant, so the focal page-point\n * holds still by construction), and the momentum and edge physics (glide,\n * spring). One frame is waited for at a time: `cancelAnimation`, every verb's\n * first act, is also \"catch\".\n */\nimport {\n  cameraForAnchorAtScreen,\n  clampCamera,\n  type Anchor,\n  type Camera,\n  type Point,\n  type Rect,\n} from '@embedpdf/core-stage';\nimport type { Cancel } from '@embedpdf/core';\n\nimport type { StageHostCapability } from '../host-contract';\nimport { easeOutCubic, FLING_STOP, glideStep, springStep, zoomLerp } from '../motion';\nimport type { StageServices } from '../services';\nimport type { StageCameraWrite } from './write';\n\n/** The default tween duration. */\nconst TWEEN_MS = 240;\n\nconst lerp = (from: number, to: number, progress: number) => from + (to - from) * progress;\n\nexport function createAnimation(\n  { events, clock, scene }: Pick<StageServices, 'events' | 'clock' | 'scene'>,\n  write: StageCameraWrite,\n) {\n  const { motionEnded } = events;\n  const { camera, viewport, buildScene, stayBounds, constraint } = scene;\n  const { writeCamera, writeCameraUnclamped, axisTravels, syncCursorFromCamera } = write;\n\n  // Cancels the frame the running motion waits for; null while nothing moves.\n  let cancelFrame: Cancel | null = null;\n  const cancelAnimation = () => {\n    cancelFrame?.();\n    cancelFrame = null;\n  };\n  /** A tween or fling reached its natural end. */\n  const endMotion = () => {\n    cancelFrame = null;\n    motionEnded.emit({ camera: camera() });\n  };\n\n  // The tween clamps to an explicit bounds rect every frame (never a\n  // re-derived current item), so animating toward a different item is not\n  // clamped back. `then` runs on natural completion only: a cancelled tween\n  // belongs to the verb that cancelled it.\n  const animateTo = (target: Camera, bounds: Rect, durationMs = TWEEN_MS, then?: () => void) => {\n    if (!clock.hasFrames) {\n      writeCamera(target, bounds);\n      then?.();\n      return;\n    }\n    cancelAnimation();\n    const from = camera();\n    let started = false;\n    let startedAt = 0;\n    const tick = (now: number) => {\n      if (!started) {\n        started = true;\n        startedAt = now; // anchor to the first real timestamp (works even when now === 0)\n      }\n      const progress = easeOutCubic(Math.min(1, (now - startedAt) / durationMs));\n      writeCamera(\n        {\n          x: lerp(from.x, target.x, progress),\n          y: lerp(from.y, target.y, progress),\n          zoom: lerp(from.zoom, target.zoom, progress),\n        },\n        bounds,\n      );\n      if (progress < 1) {\n        cancelFrame = clock.nextFrame(tick);\n      } else {\n        endMotion();\n        then?.();\n      }\n    };\n    cancelFrame = clock.nextFrame(tick);\n  };\n\n  /**\n   * The zoom-anchored tween animates the invariant, not the coordinates: the\n   * focal page-point stays at `point` while the scale changes. Lerping x, y\n   * and zoom independently breaks that mid-flight, because holding a screen\n   * point requires `x(t) = focal.x − point.x / zoom(t)`, hyperbolic in the\n   * zoom, so linear coordinates swing the tapped point along a curve (a\n   * visible dip). Here the zoom interpolates geometrically (zoom is\n   * multiplicative) and each frame's camera derives from the anchor at that\n   * zoom, then clamps: the focal point is stationary by construction, and a\n   * zoom-out rails into its fit as the shrinking travel range lets the clamp\n   * take over.\n   */\n  const animateZoomAnchored = (\n    focal: Anchor,\n    point: Point,\n    targetZoom: number,\n    durationMs = TWEEN_MS,\n    then?: () => void,\n  ) => {\n    if (!clock.hasFrames) {\n      const scene = buildScene();\n      if (scene.itemCount) writeCamera(cameraForAnchorAtScreen(focal, scene, point, targetZoom));\n      then?.();\n      return;\n    }\n    cancelAnimation();\n    const startZoom = camera().zoom;\n    let started = false;\n    let startedAt = 0;\n    const tick = (now: number) => {\n      if (!started) {\n        started = true;\n        startedAt = now;\n      }\n      const progress = easeOutCubic(Math.min(1, (now - startedAt) / durationMs));\n      const zoom = zoomLerp(startZoom, targetZoom, progress);\n      const scene = buildScene();\n      if (scene.itemCount) writeCamera(cameraForAnchorAtScreen(focal, scene, point, zoom));\n      if (progress < 1) {\n        cancelFrame = clock.nextFrame(tick);\n      } else {\n        endMotion();\n        then?.();\n      }\n    };\n    cancelFrame = clock.nextFrame(tick);\n  };\n\n  // Momentum and edge physics, the driver over motion.ts's per-axis laws:\n  //   glide  — the touch fling, decaying on UIScrollView's curve across free\n  //            travel;\n  //   spring — a critically-damped return to the clamp, entered when a glide\n  //            reaches a content edge (the remaining velocity becomes the\n  //            bounce) or when the motion starts displaced (released while\n  //            stretched).\n  // Axes are independent (a diagonal fling can bounce off the bottom while\n  // still gliding horizontally), and every trajectory ends on the clamp. It\n  // shares the tween's frame, so cancelAnimation() is also \"catch\":\n  // catching mid-bounce holds the stretch.\n  const startCameraPhysics = (fingerVelocityX: number, fingerVelocityY: number) => {\n    if (!clock.hasFrames) {\n      writeCamera(camera()); // no host frames: snap straight into bounds\n      return;\n    }\n    cancelAnimation();\n    const zoom = camera().zoom;\n    // Per-axis state in screen px (the camera moves opposite the finger;\n    // positions scale by zoom once, here, so the laws read in px).\n    interface AxisState {\n      position: number;\n      velocity: number;\n      springing: boolean;\n      done: boolean;\n    }\n    const start = camera();\n    const startClamped = clampCamera(start, stayBounds(), viewport(), constraint());\n    const startBounds = stayBounds();\n    const startViewport = viewport();\n    const axisState = (\n      cameraPosition: number,\n      clampedPosition: number,\n      fingerVelocity: number,\n    ): AxisState => ({\n      position: cameraPosition * zoom,\n      velocity: -fingerVelocity / 1000,\n      springing: cameraPosition !== clampedPosition,\n      done: false,\n    });\n    // A fitting axis takes no ballistic motion: no travel to glide across and\n    // no bounce (rigid, like the platform), so its release velocity is\n    // discarded. The spring stays armed for a displaced fitting axis.\n    const axisX = axisState(\n      start.x,\n      startClamped.x,\n      axisTravels('x', startBounds.x, startBounds.width, startViewport.width, zoom)\n        ? fingerVelocityX\n        : 0,\n    );\n    const axisY = axisState(\n      start.y,\n      startClamped.y,\n      axisTravels('y', startBounds.y, startBounds.height, startViewport.height, zoom)\n        ? fingerVelocityY\n        : 0,\n    );\n    if (\n      !axisX.springing &&\n      !axisY.springing &&\n      Math.hypot(axisX.velocity, axisY.velocity) < FLING_STOP\n    ) {\n      return;\n    }\n    let started = false;\n    let lastFrameAt = 0;\n    const tick = (now: number) => {\n      cancelFrame = null;\n      // The first frame assumes one 60 Hz step (anchored like the tween, so a\n      // first timestamp of 0 works).\n      const elapsedMs = started ? Math.min(64, Math.max(1, now - lastFrameAt)) : 16;\n      started = true;\n      lastFrameAt = now;\n      // The clamp of the current position is each axis's home this frame: the\n      // edge for a stretched axis, the rest point for a fitting one.\n      const home = clampCamera(\n        { x: axisX.position / zoom, y: axisY.position / zoom, zoom },\n        stayBounds(),\n        viewport(),\n        constraint(),\n      );\n      const step = (axis: AxisState, edgeWorld: number) => {\n        if (axis.done) return;\n        const next = axis.springing\n          ? springStep(axis.position, axis.velocity, edgeWorld * zoom, elapsedMs)\n          : glideStep(axis.position, axis.velocity, elapsedMs);\n        axis.position = next.position;\n        axis.velocity = next.velocity;\n        axis.done = next.done;\n      };\n      step(axisX, home.x);\n      step(axisY, home.y);\n      // A glide that left the travel range converts to a spring at the edge;\n      // the incoming velocity carries in, so the bounce grows out of physics\n      // rather than a scripted overshoot.\n      const nextHome = clampCamera(\n        { x: axisX.position / zoom, y: axisY.position / zoom, zoom },\n        stayBounds(),\n        viewport(),\n        constraint(),\n      );\n      const convert = (axis: AxisState, clampedPosition: number) => {\n        if (!axis.springing && Math.abs(clampedPosition * zoom - axis.position) > 1e-6) {\n          axis.position = clampedPosition * zoom;\n          axis.springing = true;\n          axis.done = false;\n        }\n      };\n      convert(axisX, nextHome.x);\n      convert(axisY, nextHome.y);\n      writeCameraUnclamped({ x: axisX.position / zoom, y: axisY.position / zoom, zoom });\n      syncCursorFromCamera();\n      if (axisX.done && axisY.done) {\n        writeCamera(camera()); // the exact landing: clamped, snapped, settled\n        motionEnded.emit({ camera: camera() });\n        return;\n      }\n      cancelFrame = clock.nextFrame(tick);\n    };\n    cancelFrame = clock.nextFrame(tick);\n  };\n\n  return {\n    cancelAnimation,\n    animateTo,\n    animateZoomAnchored,\n    startCameraPhysics,\n    api: {\n      isMoving: () => cancelFrame !== null,\n      stopMotion: () => {\n        if (!cancelFrame) return;\n        cancelAnimation();\n        motionEnded.emit({ camera: camera() });\n      },\n    } satisfies Partial<StageHostCapability>,\n  };\n}\nexport type StageAnimation = ReturnType<typeof createAnimation>;\n","import { NO_FRAME } from '@embedpdf/core-geometry';\nimport type { Size } from '@embedpdf/core-stage';\nimport type {\n  BoxQuery,\n  ResponsiveRule,\n  StageBox,\n  StageSettings,\n  StageSettingsPatch,\n} from './contract';\n\n/**\n * Container queries for the settings bag, the pure half. The capability owns\n * the driver (when to re-resolve, how to react); the laws live here: what a\n * box is, when a query matches, and what the effective settings are. No\n * state, so they are property-testable in isolation.\n *\n * The query vocabulary is only the box: a headless, DOM-free stage knows\n * exactly one environmental fact, the viewport it was told. Anything else\n * (pointer coarseness, platform, app state) is either per event\n * (`PointerSample.pointerType`) or the app's own business via\n * `updateSettings()`.\n */\n\n/** The reported viewport as a queryable box. A square box is 'portrait' (CSS). */\nexport const boxOf = (size: Size): StageBox => ({\n  width: size.width,\n  height: size.height,\n  orientation: size.height >= size.width ? 'portrait' : 'landscape',\n});\n\n/** All bounds inclusive, all fields optional, every condition must hold (CSS ranges). */\nexport const matchesQuery = (query: BoxQuery, box: StageBox): boolean =>\n  (query.minWidth === undefined || box.width >= query.minWidth) &&\n  (query.maxWidth === undefined || box.width <= query.maxWidth) &&\n  (query.minHeight === undefined || box.height >= query.minHeight) &&\n  (query.maxHeight === undefined || box.height <= query.maxHeight) &&\n  (query.orientation === undefined || box.orientation === query.orientation);\n\nconst ruleMatches = (rule: ResponsiveRule, box: StageBox): boolean =>\n  typeof rule.when === 'function' ? !!rule.when(box) : matchesQuery(rule.when, box);\n\n/**\n * Merge a patch over settings, skipping undefined values (Partial semantics).\n * Each value replaces the setting whole; a `pageFrame` or a `padding` that names\n * only some sides has 0 on the others, and a `zoomBox` that names only some\n * colors leaves the others following the accent.\n */\nexport const mergeSettings = (into: StageSettings, patch: StageSettingsPatch): StageSettings => {\n  const merged = { ...into };\n  let key: keyof StageSettingsPatch;\n  for (key in patch) {\n    const value =\n      key === 'pageFrame'\n        ? frameOf(patch.pageFrame)\n        : key === 'padding'\n          ? paddingOf(patch.padding)\n          : key === 'zoomBox'\n            ? zoomBoxOf(patch.zoomBox)\n            : patch[key];\n    if (value !== undefined) Object.assign(merged, { [key]: value });\n  }\n  return merged;\n};\n\nconst frameOf = (frame: StageSettingsPatch['pageFrame']) =>\n  frame === undefined ? undefined : { ...NO_FRAME, ...frame };\n\nconst paddingOf = (padding: StageSettingsPatch['padding']) =>\n  padding === undefined || typeof padding === 'number'\n    ? padding\n    : { top: 0, right: 0, bottom: 0, left: 0, ...padding };\n\nconst zoomBoxOf = (look: StageSettingsPatch['zoomBox']) =>\n  look === undefined ? undefined : { fill: look.fill ?? null, stroke: look.stroke ?? null };\n\n/**\n * Setting-value equality: primitives by identity, the flat objects the\n * settings vocabulary uses (`{ px }`, `{ x, y }`, page frames, zoom specs) by\n * one level of own-key comparison. Settings values are never nested deeper.\n */\nexport const eqSetting = (left: unknown, right: unknown): boolean => {\n  if (left === right) return true;\n  if (typeof left !== 'object' || typeof right !== 'object' || left === null || right === null) {\n    return false;\n  }\n  const leftKeys = Object.keys(left);\n  return (\n    leftKeys.length === Object.keys(right).length &&\n    leftKeys.every(\n      (key) => (left as Record<string, unknown>)[key] === (right as Record<string, unknown>)[key],\n    )\n  );\n};\n\nexport interface ResolvedResponsive {\n  /** The base merged with every matching rule's patch, in source order (later wins per key). */\n  effective: StageSettings;\n  /** Names of the matching rules, in source order. */\n  active: string[];\n}\n\nexport const resolveResponsive = (\n  base: StageSettings,\n  rules: readonly ResponsiveRule[],\n  box: StageBox,\n): ResolvedResponsive => {\n  let effective = base;\n  const active: string[] = [];\n  for (const rule of rules) {\n    if (!ruleMatches(rule, box)) continue;\n    if (rule.name !== undefined) active.push(rule.name);\n    if (rule.settings) effective = mergeSettings(effective, rule.settings);\n  }\n  return { effective, active };\n};\n","import { ZOOM_MAX, ZOOM_MIN, ZoomMode } from '@embedpdf/core-stage';\nimport type { ResponsiveRule, StageSettings } from './contract';\nimport { eqSetting } from './responsive';\n\n/**\n * Out-of-the-box defaults: a document-reading feel. Every field is overridable\n * in `stagePlugin(config)` and at runtime through `updateSettings()`. The\n * plugin ships no named presets (\"document\", \"canvas\", …): a preset is an\n * object the app keeps and passes to `updateSettings()`, so that taxonomy\n * stays the app's concern.\n */\nexport const DEFAULT_SETTINGS: StageSettings = {\n  flow: 'continuous',\n  layout: 'vertical',\n  spread: 'none',\n  sizing: 'intrinsic',\n  columns: 'square',\n  bounded: true,\n  padding: 24,\n  gap: 16,\n  pageFrame: { top: 0, right: 0, bottom: 0, left: 0 },\n  direction: 'ltr',\n  fitAlign: { x: 'center', y: 'center' },\n  // The reading defaults: navigation lands at the top and reading start at\n  // every zoom, button zoom inflates around the middle, and resizes pin the\n  // top (the browser scroll model). Construction and presentation apps set\n  // all of these to center/center.\n  arrivalAlign: { x: 'start', y: 'start' },\n  zoomAlign: { x: 'center', y: 'center' },\n  anchorAlign: { x: 'start', y: 'start' },\n  viewRotation: 0,\n  zoom: { mode: ZoomMode.Automatic },\n  minZoom: ZOOM_MIN,\n  maxZoom: ZOOM_MAX,\n  scrollBehavior: 'smooth',\n  interaction: true,\n  panFallback: true,\n  zoomGestures: true,\n  turnGestures: true,\n  scrollChaining: true,\n  zoomBox: { fill: null, stroke: null },\n  // Web: 1 PDF point = 96/72 CSS px, so 100% is physically accurate. A native\n  // adapter overrides this at registration with its own logical-unit factor.\n  viewUnitsPerPoint: 96 / 72,\n};\n\n/**\n * Out-of-the-box responsive rules, the platform feel with zero configuration:\n * a compact container gets the thin gutter phones use (space, not device: an\n * embedded 500px pane on a desktop is compact too). Override the whole list\n * with `stagePlugin({ responsive: [...] })`; `responsive: []` opts out. The\n * 'compact' name is queryable by the app through `stage.matchesRule('compact')`.\n */\nexport const DEFAULT_RESPONSIVE: readonly ResponsiveRule[] = [\n  { name: 'compact', when: { maxWidth: 600 }, settings: { padding: 4 } },\n];\n\n/**\n * How a change to each setting affects the view: the single source of truth.\n * One row per setting, completeness enforced by the compiler (`Record<keyof\n * StageSettings, …>`: adding a setting without classifying it is a type error).\n * Everything else derives from this table: the scene-cache invalidation and\n * key, `updateSettings()`'s reaction, the settings snapshot and patch picks,\n * and the React selector equality.\n *\n *   'reflow'  — crosses the flow boundary: camera coordinates are meaningless\n *               there, so re-place canonically onto the cursor's page.\n *   'scene'   — a layout input: invalidates the scene, then re-applies the anchor.\n *   'refit'   — re-resolves zoom against the (possibly re-keyed) scene: re-applies\n *               the anchor without an explicit invalidation.\n *   'reclamp' — pure clamp policy: re-clamp the current camera in place.\n *   'none'    — guides future verbs and the surface binding only\n *               (arrival/zoom/anchor alignment, scroll behavior, input).\n *\n * The classes also carry each change's invariant — what stays fixed while the\n * view reacts: 'refit' (a zoom-intent change) holds the zoomAlign focal point;\n * 'scene' reframes (and viewport resizes) hold the anchorAlign point.\n */\nexport type SettingEffect = 'reflow' | 'scene' | 'refit' | 'reclamp' | 'none';\nexport const SETTINGS_EFFECT: Record<keyof StageSettings, SettingEffect> = {\n  flow: 'reflow',\n  layout: 'scene',\n  spread: 'scene',\n  sizing: 'scene',\n  columns: 'scene',\n  bounded: 'reclamp',\n  padding: 'reclamp',\n  gap: 'scene',\n  pageFrame: 'scene',\n  direction: 'scene',\n  fitAlign: 'reclamp',\n  arrivalAlign: 'none',\n  zoomAlign: 'none',\n  anchorAlign: 'none',\n  viewRotation: 'scene', // a layout input: every page's footprint swaps w↔h\n  zoom: 'refit',\n  // New limits re-resolve the zoom, which moves only when it falls outside them.\n  minZoom: 'refit',\n  maxZoom: 'refit',\n  scrollBehavior: 'none',\n  // Read by the surface binding, which rebinds its pointer input when they change.\n  interaction: 'none',\n  panFallback: 'none',\n  zoomGestures: 'none',\n  // Read by the Stage's own pan and wheel verbs; the surface binding never sees them.\n  turnGestures: 'none',\n  scrollChaining: 'none',\n  zoomBox: 'none', // paint only\n  viewUnitsPerPoint: 'scene', // a layout input: changing it resizes every page\n};\nexport const SETTING_KEYS = Object.keys(SETTINGS_EFFECT) as Array<keyof StageSettings>;\n\n/** Field-by-field settings equality, derived from the registry, so a new\n *  setting is covered automatically: what an adapter compares settings with. */\nexport const settingsEqual = (left: StageSettings, right: StageSettings): boolean =>\n  SETTING_KEYS.every((key) => eqSetting(left[key], right[key]));\n\n/** The settings slice of a larger object (state, or a saved view), derived\n *  from the registry so the shape is never spelled out by hand. */\nexport const pickSettings = (source: StageSettings): StageSettings => {\n  const settings: Partial<Record<keyof StageSettings, unknown>> = {};\n  for (const key of SETTING_KEYS) settings[key] = source[key];\n  return settings as StageSettings;\n};\n","/**\n * The stage's session state: the flat settings bag plus the camera, the\n * viewport, the cursor and the render-commit latch. Every function below is a\n * pure transition; the controller's areas apply them with `ctx.state.update`,\n * and nothing else changes stage state.\n */\nimport type { PageRef, SettingLock } from '@embedpdf/core';\nimport type { Camera, Point, Size } from '@embedpdf/core-stage';\n\nimport type { StageConfig, StageSettings } from './contract';\nimport { mergeSettings } from './responsive';\nimport { DEFAULT_SETTINGS } from './settings';\n\nexport interface StageModel extends StageSettings {\n  readonly camera: Camera;\n  /**\n   * One-way render-commit latch. False while the initial viewport-driven\n   * placement is unresolved; true only after its camera and settings writes\n   * have completed. Page and scroll screen-space reads refuse to answer while\n   * false, so an adapter can never paint the placeholder camera at the origin.\n   */\n  readonly placed: boolean;\n  /**\n   * Names of the responsive rules currently matching the box, in source order.\n   * State (not derived) so `matchesRule()` is reactive in every framework.\n   */\n  readonly activeRules: readonly string[];\n  /**\n   * False while the zoom is in motion, true once it has rested (about 150 ms\n   * of frames without a zoom write). Device-snapping of page origins is gated\n   * on this: a continuous zoom and a snapped origin cannot coexist without the\n   * anchor point jittering ±0.5 device px per step, so pages place\n   * fractionally while zooming and snap once at rest. Pans always snap (a pure\n   * translation has no anchor error).\n   */\n  readonly cameraResting: boolean;\n  /** The container size the host reported, in viewport px. */\n  readonly viewport: Size;\n  /**\n   * Device pixels per view pixel (web: `window.devicePixelRatio`). Feeds each\n   * page's transform so bitmaps render crisp and boxes land on the device\n   * grid. Defaults to 1.\n   */\n  readonly dpr: number;\n  /**\n   * The current page index, valid in both flows. Navigation sets it; in\n   * continuous flow manipulation derives it from the camera; in paged flow\n   * panning never moves it (the scene is a one-item slice at this page).\n   * An index, so it survives spread and layout regrouping.\n   */\n  readonly pageIndex: number;\n  /**\n   * What last drove the camera or cursor: `'programmatic'` for the arrival\n   * and reveal verbs (the ones action executors use), `'user'` for direct\n   * manipulation (wheel, drag, scrollbars, embedder scroll calls). The\n   * page-state feed hands it to the actions plugin, whose cascade budget\n   * counts only programmatic rounds, so user scrolling is never throttled.\n   */\n  readonly motionCause: 'user' | 'programmatic';\n  /** The `zoom` tool's drag in progress, or null when there is none. */\n  readonly zoomDrag: ZoomDrag | null;\n  /**\n   * Who holds each locked setting (`lockSettings()`). State, so a lock that\n   * changes no value still reaches the controls that read `getLock()`.\n   */\n  readonly locks: StageLocks;\n}\n\n/** The holder of each locked setting. */\nexport type StageLocks = Readonly<Partial<Record<keyof StageSettings, SettingLock>>>;\n\n/**\n * A drag of the `zoom` tool, as two corners on one page's plane: the page\n * under the press (or a visible one, for a press between pages). Page points\n * keep the box on the content when the view scrolls during the drag, and the\n * box may reach past that page onto its neighbours.\n */\nexport interface ZoomDrag {\n  readonly page: PageRef;\n  /** Where the press was, in page coordinates. */\n  readonly from: Point;\n  /** Where the pointer is now, in page coordinates. */\n  readonly to: Point;\n}\n\nexport const initialStageModel = (config: StageConfig): StageModel => {\n  // `responsive` configures the capability, not the settings: strip it so the\n  // spread below stays a pure settings override.\n  const { responsive: _responsive, ...overrides } = config;\n  return {\n    camera: { x: 0, y: 0, zoom: 1 },\n    placed: false,\n    cameraResting: true,\n    viewport: { width: 0, height: 0 },\n    dpr: 1,\n    pageIndex: 0,\n    motionCause: 'user',\n    activeRules: [],\n    zoomDrag: null,\n    locks: {},\n    ...mergeSettings(DEFAULT_SETTINGS, overrides),\n  };\n};\n\nexport const setCamera = (state: StageModel, camera: Camera): StageModel =>\n  state.camera === camera ? state : { ...state, camera };\n\nexport const setCameraResting = (state: StageModel, resting: boolean): StageModel =>\n  state.cameraResting === resting ? state : { ...state, cameraResting: resting };\n\nexport const markPlaced = (state: StageModel): StageModel =>\n  state.placed ? state : { ...state, placed: true };\n\nexport const setViewport = (state: StageModel, viewport: Size): StageModel =>\n  state.viewport === viewport ? state : { ...state, viewport };\n\nexport const setDpr = (state: StageModel, dpr: number): StageModel =>\n  state.dpr === dpr ? state : { ...state, dpr };\n\nexport const setCursor = (state: StageModel, pageIndex: number): StageModel =>\n  state.pageIndex === pageIndex ? state : { ...state, pageIndex };\n\nexport const setMotionCause = (\n  state: StageModel,\n  motionCause: StageModel['motionCause'],\n): StageModel => (state.motionCause === motionCause ? state : { ...state, motionCause });\n\n/**\n * Merge a settings patch. Undefined values are skipped, so a partial restore\n * never clears a setting; the area that patches decides what camera\n * follow-up the change needs.\n */\nexport function patchSettings(state: StageModel, patch: Partial<StageSettings>): StageModel {\n  let next = state;\n  let key: keyof StageSettings;\n  for (key in patch) {\n    const value = patch[key];\n    if (value === undefined || Object.is(next[key], value)) continue;\n    if (next === state) next = { ...state };\n    Object.assign(next, { [key]: value });\n  }\n  return next;\n}\n\nexport const setActiveRules = (state: StageModel, activeRules: readonly string[]): StageModel =>\n  state.activeRules === activeRules ? state : { ...state, activeRules };\n\nexport const setZoomDrag = (state: StageModel, zoomDrag: ZoomDrag | null): StageModel =>\n  state.zoomDrag === zoomDrag ? state : { ...state, zoomDrag };\n\nexport const setLocks = (state: StageModel, locks: StageLocks): StageModel =>\n  state.locks === locks ? state : { ...state, locks };\n","/**\n * Direct manipulation: set, pan, scroll and pinch-zoom the camera, the\n * gesture bracket and the release fling. The camera moves freely and the\n * cursor is derived from it (the manipulation direction of cursor\n * reconciliation). In paged flow the same input turns pages\n * (`navigation/turn.ts`).\n */\nimport type { PluginContext } from '@embedpdf/core';\nimport type { Point } from '@embedpdf/core-geometry';\nimport {\n  anchorAtPoint,\n  cameraForAnchorAtScreen,\n  cameraFromScroll,\n  clampCamera,\n  clampZoom,\n  panByScreen,\n  toWorld,\n  zoomAround,\n  type Camera,\n} from '@embedpdf/core-stage';\n\nimport type { StageScrollToOptions } from '../contract';\nimport type { StageHostCapability } from '../host-contract';\nimport { patchSettings, type StageModel } from '../model';\nimport type { StageTurns } from '../navigation/turn';\nimport type { StagePageReads } from '../read/pages';\nimport type { StageServices } from '../services';\nimport type { StageAnimation } from './animation';\nimport type { StageCameraWrite } from './write';\n\n/** The part of a pan the clamp refused, in screen px, signed like the pan. */\nconst refusedBy = (wanted: Camera, allowed: Camera): Point => ({\n  x: (allowed.x - wanted.x) * wanted.zoom,\n  y: (allowed.y - wanted.y) * wanted.zoom,\n});\n\nexport function createGestures(\n  ctx: PluginContext<StageModel>,\n  { scene }: Pick<StageServices, 'scene'>,\n  write: StageCameraWrite,\n  { cancelAnimation, animateTo, startCameraPhysics }: StageAnimation,\n  { scrollMetricsNow }: Pick<StagePageReads, 'scrollMetricsNow'>,\n  turns: StageTurns,\n) {\n  const { camera, viewport, padding, zoomLimits, buildScene, stayBounds, constraint } = scene;\n  const {\n    gesture,\n    armRest,\n    writeCamera,\n    writeCameraUnclamped,\n    rubberize,\n    unrubberize,\n    syncCursorFromCamera,\n    markCause,\n  } = write;\n\n  const scrollTo = (options: StageScrollToOptions): void => {\n    markCause('user');\n    cancelAnimation();\n    if (!buildScene().itemCount) return;\n    const next = cameraFromScroll(camera(), stayBounds(), viewport(), padding(), options);\n    if (options.behavior === 'smooth') {\n      animateTo(next, stayBounds(), undefined, syncCursorFromCamera);\n    } else {\n      writeCamera(next);\n      syncCursorFromCamera();\n    }\n  };\n\n  return {\n    api: {\n      setCamera: (next) => {\n        markCause('user');\n        cancelAnimation();\n        writeCamera({ ...next, zoom: clampZoom(next.zoom, zoomLimits()) });\n        syncCursorFromCamera();\n      },\n      panBy: (dx, dy) => {\n        if (turns.beforePan()) return; // this stream already turned the page\n        markCause('user');\n        cancelAnimation();\n        if (gesture.depth > 0 && gesture.elastic) {\n          // Elastic: integrate the finger on the unclamped camera and display\n          // it through the resistance curve. Initialized from the displayed\n          // camera's inverse, so catching a mid-bounce stretch continues\n          // seamlessly.\n          gesture.raw = panByScreen(gesture.raw ?? unrubberize(camera()), dx, dy);\n          writeCameraUnclamped(rubberize(gesture.raw));\n        } else {\n          const wanted = panByScreen(camera(), dx, dy);\n          writeCamera(wanted);\n          turns.refused(refusedBy(wanted, camera()));\n        }\n        syncCursorFromCamera();\n      },\n      scrollTo,\n      scrollBy: ({ left, top, behavior }) => {\n        const metrics = scrollMetricsNow();\n        scrollTo({\n          left: left === undefined ? undefined : metrics.scrollLeft + left,\n          top: top === undefined ? undefined : metrics.scrollTop + top,\n          behavior,\n        });\n      },\n      zoomAround: (point, factor) => {\n        cancelAnimation();\n        const before = buildScene();\n        // The page-relative focal point: the durable identity of \"what is\n        // under the pointer\".\n        const focal = before.itemCount ? anchorAtPoint(before, toWorld(camera(), point)) : null;\n        writeCamera(zoomAround(camera(), point, factor, zoomLimits()));\n        // Record the resulting level as the zoom intent (focal, so no\n        // re-anchor). Inside a gesture bracket it is deferred to endGesture:\n        // one patch per pinch instead of one per event.\n        if (gesture.depth === 0) {\n          ctx.state.update(patchSettings, { zoom: { level: camera().zoom } });\n        }\n        // When zoom is a layout input (a wrapped grid) the scene may just have\n        // re-wrapped under the camera, leaving the old world point stale:\n        // re-pin the same page-point under the pointer and clamp against the\n        // new geometry. In every other mode the scene is unchanged and this\n        // never runs.\n        const after = buildScene();\n        if (after !== before && focal && after.itemCount) {\n          writeCamera(cameraForAnchorAtScreen(focal, after, point, camera().zoom));\n        }\n        // A zoom write in an elastic gesture (a pinch) re-bases the pan\n        // integrator: the bounds just changed shape under the stretch, so\n        // the displayed camera becomes the new reference.\n        if (gesture.depth > 0 && gesture.elastic) gesture.raw = unrubberize(camera());\n        syncCursorFromCamera();\n      },\n      beginGesture: (options) => {\n        gesture.depth++;\n        if (gesture.depth === 1) {\n          cancelAnimation(); // catch: the next touch-down stops any tween or fling\n          gesture.zoomed = false;\n          gesture.elastic = options?.elastic === true;\n          gesture.raw = null;\n          turns.dragBegan();\n        }\n      },\n      endGesture: () => {\n        if (gesture.depth === 0) return;\n        gesture.depth--;\n        if (gesture.depth > 0) return;\n        // How far the finger pulled past the edge, read before the bracket forgets it.\n        const overshoot = gesture.raw\n          ? refusedBy(gesture.raw, clampCamera(gesture.raw, stayBounds(), viewport(), constraint()))\n          : { x: 0, y: 0 };\n        const zoomed = gesture.zoomed;\n        gesture.raw = null;\n        const wasElastic = gesture.elastic;\n        gesture.elastic = false;\n        if (gesture.zoomed) {\n          gesture.zoomed = false;\n          // The deferred zoom intent: one patch for the whole gesture. (In a\n          // wrapped grid this may re-wrap the scene; the next reframe\n          // re-anchors through the normal update path.)\n          ctx.state.update(patchSettings, { zoom: { level: camera().zoom } });\n          armRest(); // the gesture is over: the rest countdown runs now\n        }\n        syncCursorFromCamera();\n        // A pull past a paged view's edge turns the page instead of springing home.\n        if (turns.dragEnded(overshoot, zoomed)) return;\n        if (wasElastic) {\n          // Released while stretched: spring home. A fling() right after\n          // re-enters the same physics with the release velocity.\n          const current = camera();\n          const clamped = clampCamera(current, stayBounds(), viewport(), constraint());\n          if (clamped.x !== current.x || clamped.y !== current.y) startCameraPhysics(0, 0);\n        }\n      },\n      fling: (velocityX, velocityY) => {\n        // A flick past a paged view's edge turns the page instead of gliding.\n        if (turns.flung({ x: velocityX, y: velocityY })) return;\n        startCameraPhysics(velocityX, velocityY);\n      },\n    } satisfies Partial<StageHostCapability>,\n  };\n}\nexport type StageGestures = ReturnType<typeof createGestures>;\n","/**\n * Page turns in paged flow: a push past the edge of the page turns it, read\n * off what the host port reports (pans, the drag bracket, the release fling).\n * A push is the part of a pan the clamp refused. A stream is one drag, or one\n * push of a wheel or trackpad with its momentum: the pans up to the next\n * pause, or up to the next push the wheel tells while the last still coasts\n * (`camera/wheel.ts`). A stream turns only at an edge it began at, so reading\n * down to the bottom stops there, and it turns once: the rest of it is spent,\n * so momentum never scrolls the page that just arrived.\n *\n * In every flow it also says whether a push has anywhere to go, which is how\n * the wheel tells a stream of its own from one for the page around the viewer\n * (`camera/wheel.ts`).\n */\nimport type { Cancel, PluginContext } from '@embedpdf/core';\nimport type { Point } from '@embedpdf/core-geometry';\n\nimport type { StageModel } from '../model';\nimport type { StagePageReads } from '../read/pages';\nimport type { StageServices } from '../services';\nimport type { StageArrival } from './arrive';\n\n/** The push past an edge that turns the page, in screen px: about one wheel notch. */\nconst TURN_PUSH = 60;\n/** The release speed past an edge that turns the page, in screen px/s: a flick. */\nconst TURN_FLICK = 600;\n/** The pause that ends a wheel or trackpad stream. */\nexport const QUIET_MS = 200;\n\ntype Axis = 'x' | 'y';\n\n/** Per axis, whether the camera can't move further toward the next page, and toward the previous. */\ninterface Edges {\n  next: Record<Axis, boolean>;\n  previous: Record<Axis, boolean>;\n}\n\ninterface Stream {\n  /** The edges the camera already sat at when the stream began: the only ones it turns at. */\n  startedAt: Edges;\n  /** The push so far, per axis, positive toward the next page. */\n  push: Point;\n  /** It turned: the rest of it moves nothing. */\n  spent: boolean;\n}\n\nconst NO_PUSH: Point = { x: 0, y: 0 };\nconst plus = (left: Point, right: Point): Point => ({ x: left.x + right.x, y: left.y + right.y });\n\nexport function createTurns(\n  ctx: PluginContext<StageModel>,\n  { scene, clock }: Pick<StageServices, 'scene' | 'clock'>,\n  { scrollMetricsNow }: Pick<StagePageReads, 'scrollMetricsNow'>,\n  navigation: Pick<\n    StageArrival['api'],\n    'nextPage' | 'previousPage' | 'canGoNext' | 'canGoPrevious'\n  >,\n) {\n  const state = () => ctx.state.get();\n  const enabled = () => scene.paged() && state().turnGestures;\n  const rtl = () => state().direction === 'rtl';\n\n  /** A screen delta in reading terms: positive toward the next page on each axis. */\n  const ahead = (delta: Point): Point => ({ x: rtl() ? delta.x : -delta.x, y: -delta.y });\n\n  // An axis that doesn't scroll sits at both of its edges.\n  const edgesNow = (): Edges => {\n    const metrics = scrollMetricsNow();\n    const top = !metrics.scrollableY || metrics.scrollTop <= 0.5;\n    const bottom =\n      !metrics.scrollableY ||\n      metrics.scrollTop + metrics.clientHeight >= metrics.scrollHeight - 0.5;\n    const left = !metrics.scrollableX || metrics.scrollLeft <= 0.5;\n    const right =\n      !metrics.scrollableX || metrics.scrollLeft + metrics.clientWidth >= metrics.scrollWidth - 0.5;\n    return {\n      next: { x: rtl() ? left : right, y: bottom },\n      previous: { x: rtl() ? right : left, y: top },\n    };\n  };\n\n  let stream: Stream | null = null;\n  let dragging = false;\n  let cancelQuiet: Cancel | null = null;\n\n  const open = (): Stream => {\n    stream ??= { startedAt: edgesNow(), push: NO_PUSH, spent: false };\n    return stream;\n  };\n  /** End the stream after a pause; every pan restarts the countdown. */\n  const closeWhenQuiet = () => {\n    cancelQuiet?.();\n    cancelQuiet = clock.after(QUIET_MS, () => {\n      cancelQuiet = null;\n      stream = null;\n    });\n  };\n\n  /** Turn when, on either axis, `amount` reaches `threshold` at an edge the stream began at. */\n  const turnPast = (current: Stream, amount: Point, threshold: number): boolean => {\n    for (const axis of ['y', 'x'] as const) {\n      if (amount[axis] >= threshold && current.startedAt.next[axis] && navigation.canGoNext()) {\n        current.spent = true;\n        navigation.nextPage({ behavior: 'instant' });\n        return true;\n      }\n      if (\n        amount[axis] <= -threshold &&\n        current.startedAt.previous[axis] &&\n        navigation.canGoPrevious()\n      ) {\n        current.spent = true;\n        // Back lands where you left it: the bottom of the previous page, or its reading end.\n        navigation.previousPage({\n          behavior: 'instant',\n          arrivalAlign: axis === 'y' ? { y: 'end' } : { x: 'end' },\n        });\n        return true;\n      }\n    }\n    return false;\n  };\n\n  return {\n    /** Before a pan moves the camera. True: this stream already turned, so the pan moves nothing. */\n    beforePan: (): boolean => {\n      if (!enabled()) return false;\n      const current = open();\n      if (!dragging) closeWhenQuiet();\n      return current.spent;\n    },\n    /** After a rigid pan: the part of it the clamp refused, in screen px. */\n    refused: (delta: Point): void => {\n      if (!enabled() || !stream) return;\n      stream.push = plus(stream.push, ahead(delta));\n      // A wheel turns as soon as it has pushed far enough; a drag waits for its release.\n      if (!dragging) turnPast(stream, stream.push, TURN_PUSH);\n    },\n    /**\n     * A wheel or trackpad pushes anew while its last push still coasts: the\n     * next stream begins here, with no pause before it.\n     */\n    pushBegan: (): void => {\n      if (!dragging) stream = null;\n    },\n    /** A drag begins: one stream for all of it, however long it holds still. */\n    dragBegan: (): void => {\n      if (!enabled()) return;\n      cancelQuiet?.();\n      cancelQuiet = null;\n      stream = null;\n      dragging = true;\n      open();\n    },\n    /**\n     * The drag ended, its finger pulled `overshoot` past the edge (screen px).\n     * True: it turned the page, so nothing springs home.\n     */\n    dragEnded: (overshoot: Point, zoomed: boolean): boolean => {\n      dragging = false;\n      if (!enabled() || !stream) return false;\n      // A pinch zooms; it never turns the page, nor does the fling after it.\n      if (zoomed) {\n        stream = null;\n        return false;\n      }\n      closeWhenQuiet(); // the release fling comes next and belongs to this stream\n      return turnPast(stream, plus(stream.push, ahead(overshoot)), TURN_PUSH);\n    },\n    /** The release speed, right after a drag. True: no momentum, as the page turned. */\n    flung: (velocity: Point): boolean => {\n      if (!enabled() || !stream) return false;\n      return stream.spent || turnPast(stream, ahead(velocity), TURN_FLICK);\n    },\n    /**\n     * Whether a push by `delta` (screen px) has anywhere to go along its longer\n     * axis: the camera can move that way, or a turn has a page to turn to.\n     */\n    leadsSomewhere: (delta: Point): boolean => {\n      const axis: Axis = Math.abs(delta.x) > Math.abs(delta.y) ? 'x' : 'y';\n      const toward = ahead(delta)[axis] > 0 ? 'next' : 'previous';\n      // An unbounded camera has no edges.\n      if (!state().bounded || !edgesNow()[toward][axis]) return true;\n      if (!enabled()) return false;\n      return toward === 'next' ? navigation.canGoNext() : navigation.canGoPrevious();\n    },\n  };\n}\nexport type StageTurns = ReturnType<typeof createTurns>;\n","/**\n * Coasting, told from a new push. After the fingers leave a trackpad the\n * scroll coasts: wheels keep coming for a second or more, slower and slower.\n * The next swipe often begins before they stop, so no pause sets the two\n * apart, and a wheel doesn't say which of the two it is. The speed does:\n * coasting only slows down, so a scroll that speeds up after it has slowed is\n * a new push.\n *\n * Speed, not the size of a wheel. A browser hands over one wheel for however\n * many the trackpad sent since the last, so sizes double and halve at a steady\n * speed. Each wheel carries the time it happened, and the distance over that\n * time holds steady.\n */\n\n/** How many times its slowest speed a scroll has to reach, to have sped up. */\nconst PUSH_GROWTH = 2.5;\n\n/**\n * The slowest speed a push is told against, in px per ms. A scroll about to\n * stop moves a pixel or two a frame, where one pixel more doubles its speed.\n */\nconst SLOWEST_TOLD = 0.1;\n\n/**\n * The shortest time a speed is told over: a frame. Wheels closer together\n * count as one, which evens out a screen that sends two or more a frame.\n */\nconst MEASURE_MS = 16;\n\n/**\n * The longest. A scroll that coasts sends a wheel every frame; wheels further\n * apart than this are the notches of a mouse wheel, or a scroll that rested.\n * No speed is told across the gap, so notches never read as a new push.\n */\nconst STEADY_MS = 40;\n\nexport function createCoasting() {\n  /** When the last wheel that began or ended a speed's span came, and how far the scroll has gone since. */\n  let since = -Infinity;\n  let gone = 0;\n  /** The last speed, in px per ms. */\n  let last = 0;\n  /**\n   * The slowest speed since the scroll began to slow. While it has only sped\n   * up there is none, and nothing is a new push.\n   */\n  let slowest = Infinity;\n\n  return {\n    /**\n     * Take the next wheel: `size` px along its longer axis, at `timeMs`. True:\n     * with it the scroll sped up, a new push.\n     */\n    brokenBy: (size: number, timeMs: number): boolean => {\n      const span = timeMs - since;\n      if (span > STEADY_MS) {\n        since = timeMs;\n        gone = 0;\n        return false;\n      }\n      gone += size;\n      if (span < MEASURE_MS) return false;\n      const speed = gone / span;\n      since = timeMs;\n      gone = 0;\n\n      const pushed = speed > PUSH_GROWTH * Math.max(slowest, SLOWEST_TOLD);\n      if (pushed) slowest = Infinity;\n      else if (speed < last) slowest = Math.min(slowest, speed);\n      last = speed;\n      return pushed;\n    },\n    /** The scroll paused: the next wheel has nothing before it. */\n    forget: (): void => {\n      since = -Infinity;\n      gone = 0;\n      last = 0;\n      slowest = Infinity;\n    },\n  };\n}\n","/**\n * The wheel, and whose it is. A scrolling element hands the wheel to the page\n * around it once it can't scroll that way. The Stage is a camera, not a\n * scroller, so it gives that answer itself: `wheelBy` pans and returns true,\n * or returns false for a wheel it leaves to the page, which the surface\n * binding then lets the browser have.\n *\n * The answer holds for a whole stream (the wheels between two pauses, as in\n * `navigation/turn.ts`) and comes from its first wheel, the way a browser\n * picks what a scroll gesture scrolls. A stream is the Stage's when it begins\n * with somewhere to go. So scrolling down to the end stops there, momentum\n * included, and the next push scrolls the page.\n *\n * A trackpad leaves no pause before that next push: a swipe coasts for a\n * second or more, and the next one begins before it stops. So a new push\n * (`coasting.ts`) begins the next stream too. It is the Stage's without\n * asking when the one before it was still moving the pages.\n *\n * Page turns go by the same streams: a new push is the next one to turn a\n * page with, whether or not the wheel chains.\n */\nimport type { Cancel, PluginContext } from '@embedpdf/core';\n\nimport type { StageHostCapability } from '../host-contract';\nimport type { StageModel } from '../model';\nimport { QUIET_MS, type StageTurns } from '../navigation/turn';\nimport type { StageServices } from '../services';\nimport { createCoasting } from './coasting';\nimport type { StageGestures } from './gestures';\n\nexport function createWheel(\n  ctx: PluginContext<StageModel>,\n  { clock }: Pick<StageServices, 'clock'>,\n  turns: Pick<StageTurns, 'leadsSomewhere' | 'pushBegan'>,\n  { panBy }: Pick<StageGestures['api'], 'panBy'>,\n) {\n  /** Whether the stream in progress is the Stage's; null between streams. */\n  let taken: boolean | null = null;\n  /** The stream is moving the pages: it is the Stage's, and its last wheel had somewhere to go. */\n  let moving = false;\n  const coasting = createCoasting();\n  let cancelQuiet: Cancel | null = null;\n\n  /** End the stream after a pause; every wheel restarts the countdown. */\n  const closeWhenQuiet = () => {\n    cancelQuiet?.();\n    cancelQuiet = clock.after(QUIET_MS, () => {\n      cancelQuiet = null;\n      taken = null;\n      moving = false;\n      coasting.forget();\n    });\n  };\n\n  return {\n    api: {\n      wheelBy: (dx, dy, timeMs) => {\n        const chains = ctx.state.get().scrollChaining;\n        // A wheel that moves nothing says nothing about where its stream is\n        // headed. It's kept, so the browser starts no scroll with a stream\n        // that has no direction yet.\n        if (dx === 0 && dy === 0) return !chains || (taken ?? true);\n        const room = turns.leadsSomewhere({ x: dx, y: dy });\n        if (coasting.brokenBy(Math.max(Math.abs(dx), Math.abs(dy)), timeMs)) {\n          turns.pushBegan();\n          // Stopped at an end, the Stage holds what coasts in and no more: the\n          // new push is decided afresh, as it is after a stream the page took.\n          // One that follows a stream still moving the pages stays the\n          // Stage's, wherever it heads.\n          if (!moving) taken = null;\n        }\n        taken ??= room;\n        moving = taken && room;\n        closeWhenQuiet();\n        // With chaining off every wheel is the Stage's.\n        if (chains && !taken) return false;\n        panBy(dx, dy);\n        return true;\n      },\n    } satisfies Partial<StageHostCapability>,\n  };\n}\nexport type StageWheel = ReturnType<typeof createWheel>;\n","/**\n * The camera write path: the one low-level clamped write (`writeCamera`), the\n * elastic unclamped write and its rubber-band curves, the rest detector that\n * gates device snapping, the gesture bracket state, and cursor reconciliation\n * from the camera (manipulation only; navigation sets the cursor as intent).\n */\nimport {\n  clampCamera,\n  anchorFromCamera,\n  travelRange,\n  type Camera,\n  type Rect,\n} from '@embedpdf/core-stage';\nimport type { Cancel, PluginContext } from '@embedpdf/core';\n\nimport { setCamera, setCameraResting, setCursor, setMotionCause, type StageModel } from '../model';\nimport { rubberIn, rubberOut } from '../motion';\nimport type { StageServices } from '../services';\n\n/** How long the zoom must hold still before the camera counts as resting. */\nconst REST_MS = 150;\n\nexport function createCameraWrite(\n  ctx: PluginContext<StageModel>,\n  { clock, placement, scene }: Pick<StageServices, 'clock' | 'placement' | 'scene'>,\n) {\n  const { camera, viewport, padding, paged, buildScene, stayBounds, constraint } = scene;\n\n  // ── the gesture bracket (touch pan and pinch) ──\n  // While open, zoomAround defers its zoom-intent patch and the rest\n  // countdown is held: a hesitation inside a pinch is not \"at rest\". Depth-\n  // counted so nested brackets compose. An elastic gesture may also hold the\n  // camera past the clamp (rubber-band); `raw` is its unclamped,\n  // finger-integrated camera, which the resistance curve maps to what renders.\n  const gesture = { depth: 0, zoomed: false, elastic: false, raw: null as Camera | null };\n\n  // ── the camera-rest detector ──\n  // Origin snapping is gated on rest (see `StageModel.cameraResting`): pages\n  // place fractionally while the zoom moves and snap once it has held still\n  // for REST_MS.\n  let cancelRest: Cancel | null = null;\n  const stopRestCountdown = () => {\n    cancelRest?.();\n    cancelRest = null;\n  };\n  const armRest = () => {\n    // Initial placement snaps immediately (the first paint is crisp), and a\n    // host without frames keeps snapping always on: rest-gating refines live\n    // gestures and is not part of the contract.\n    if (!clock.hasFrames || !placement.started) return;\n    ctx.state.update(setCameraResting, false);\n    stopRestCountdown();\n    cancelRest = clock.after(REST_MS, () => {\n      cancelRest = null;\n      ctx.state.update(setCameraResting, true);\n    });\n  };\n\n  // The one low-level camera write: clamp to `bounds` and store. It never\n  // touches the cursor (see syncCursorFromCamera for that policy).\n  const writeCamera = (next: Camera, bounds: Rect = stayBounds()) => {\n    const clamped = clampCamera(next, bounds, viewport(), constraint());\n    if (clamped.zoom !== camera().zoom) {\n      if (gesture.depth > 0) {\n        // Mid-gesture: un-rest at once (fractional placement) but hold the\n        // countdown; rest is declared at endGesture, not at a pinch hesitation.\n        gesture.zoomed = true;\n        ctx.state.update(setCameraResting, false);\n        stopRestCountdown();\n      } else {\n        armRest();\n      }\n    }\n    ctx.state.update(setCamera, clamped);\n  };\n\n  // ── rubber-band (elastic overscroll) ──\n  // The curve pair lives in motion.ts; these adapt it to camera state. The\n  // rubber softens only the edges of a scroll range: an axis whose content\n  // fits the viewport has no travel, the clamp holds it at its fitAlign rest,\n  // and it stays rigid however hard the finger tugs (the UIScrollView\n  // default: bouncing exists only where content exceeds the bounds).\n  const axisTravels = (\n    axis: 'x' | 'y',\n    origin: number,\n    content: number,\n    view: number,\n    zoom: number,\n  ): boolean => {\n    const inset = padding();\n    const [before, after] = axis === 'x' ? [inset.left, inset.right] : [inset.top, inset.bottom];\n    return !travelRange(origin, content, view, zoom, before, after).fits;\n  };\n  /** The unclamped finger-integrated camera → the displayed camera: clamp,\n   *  then re-apply the overshoot through the resistance curve, per travelling\n   *  axis. Inside the bounds this is exactly the clamp, and on a fitting axis\n   *  it is always the clamp. */\n  const rubberize = (raw: Camera): Camera => {\n    const clamped = clampCamera(raw, stayBounds(), viewport(), constraint());\n    const size = viewport();\n    const bounds = stayBounds();\n    const axis = (\n      rawPosition: number,\n      clampedPosition: number,\n      dimension: number,\n      travels: boolean,\n    ): number => {\n      if (!travels) return clampedPosition;\n      const overshootWorld = rawPosition - clampedPosition;\n      if (overshootWorld === 0) return clampedPosition;\n      const stretch = rubberOut(Math.abs(overshootWorld) * raw.zoom, Math.max(1, dimension));\n      return clampedPosition + (Math.sign(overshootWorld) * stretch) / raw.zoom;\n    };\n    return {\n      zoom: raw.zoom,\n      x: axis(\n        raw.x,\n        clamped.x,\n        size.width,\n        axisTravels('x', bounds.x, bounds.width, size.width, raw.zoom),\n      ),\n      y: axis(\n        raw.y,\n        clamped.y,\n        size.height,\n        axisTravels('y', bounds.y, bounds.height, size.height, raw.zoom),\n      ),\n    };\n  };\n  /** The displayed camera → the raw position `rubberize` would have produced\n   *  it from. The overshoot is capped just under the asymptote so the inverse\n   *  stays finite whatever state a catch finds the camera in. */\n  const unrubberize = (displayed: Camera): Camera => {\n    const clamped = clampCamera(displayed, stayBounds(), viewport(), constraint());\n    const size = viewport();\n    const bounds = stayBounds();\n    const axis = (\n      displayedPosition: number,\n      clampedPosition: number,\n      dimension: number,\n      travels: boolean,\n    ): number => {\n      if (!travels) return clampedPosition;\n      const overshootWorld = displayedPosition - clampedPosition;\n      if (overshootWorld === 0) return clampedPosition;\n      const span = Math.max(1, dimension);\n      const stretch = Math.min(Math.abs(overshootWorld) * displayed.zoom, span - 1);\n      return (\n        clampedPosition + (Math.sign(overshootWorld) * rubberIn(stretch, span)) / displayed.zoom\n      );\n    };\n    return {\n      zoom: displayed.zoom,\n      x: axis(\n        displayed.x,\n        clamped.x,\n        size.width,\n        axisTravels('x', bounds.x, bounds.width, size.width, displayed.zoom),\n      ),\n      y: axis(\n        displayed.y,\n        clamped.y,\n        size.height,\n        axisTravels('y', bounds.y, bounds.height, size.height, displayed.zoom),\n      ),\n    };\n  };\n  // The elastic write path, with no clamp: used only by the elastic pan and\n  // the edge spring, whose math guarantees every trajectory ends clamped.\n  const writeCameraUnclamped = (next: Camera) => ctx.state.update(setCamera, next);\n\n  /**\n   * Cursor reconciliation, one direction per interaction:\n   *   navigation   → the cursor is intent, set explicitly; the camera honors\n   *                  it as far as the clamp allows, and a clamped camera\n   *                  never revokes it.\n   *   manipulation → (pan, drag, pinch) the camera moves freely and the\n   *                  cursor is derived from it. Only those verbs call this.\n   * Paged flow never syncs.\n   */\n  const syncCursorFromCamera = () => {\n    if (paged()) return;\n    const scene = buildScene();\n    if (!scene.itemCount) return;\n    ctx.state.update(setCursor, anchorFromCamera(camera(), scene, viewport()).pageIndex);\n  };\n\n  /** Tag what drives the next camera or cursor change (see `StageModel.motionCause`). */\n  const markCause = (cause: StageModel['motionCause']): void =>\n    ctx.state.update(setMotionCause, cause);\n\n  return {\n    gesture,\n    armRest,\n    writeCamera,\n    writeCameraUnclamped,\n    axisTravels,\n    rubberize,\n    unrubberize,\n    syncCursorFromCamera,\n    markCause,\n  };\n}\nexport type StageCameraWrite = ReturnType<typeof createCameraWrite>;\n","/**\n * The behavioral placement latch: it flips when initial placement starts,\n * while `StageModel.placed` is the render-commit latch that flips only after\n * placement finishes. Camera behavior keys on this one; renderers key on\n * `placed`, so partial geometry is never observable.\n */\nimport type { ScrollBehaviorKind } from '../contract';\n\nexport interface PlacementLatch {\n  started: boolean;\n  /** The last navigation asked for before placement; placement applies it last. */\n  pending: (() => void) | null;\n}\n\nexport const createPlacementLatch = (): PlacementLatch => ({ started: false, pending: null });\n\n/**\n * Run a navigation verb now, or, before the first placement, when it happens.\n * Before placement there is no viewport to move a camera in, and placement\n * would reset it anyway, so the last call waits and lands instantly after the\n * initial view: an app that reveals something as the document opens sees it\n * on the first frame.\n */\nexport function whenPlaced<Options extends { behavior?: ScrollBehaviorKind }>(\n  latch: PlacementLatch,\n  options: Options | undefined,\n  run: (options: Options | undefined) => void,\n): void {\n  if (latch.started) {\n    run(options);\n    return;\n  }\n  latch.pending = () => run({ ...options, behavior: 'instant' } as Options);\n}\n","/**\n * Anchors and arrivals. The anchor is the durable \"what am I looking at\":\n * captured before a structural change and re-applied after, one mechanism for\n * layout, spread, zoom, resize and restore. Navigation is canonical:\n * goToPage(N) always ends in the same camera state whatever the zoom or the\n * starting point.\n */\nimport {\n  cameraFromAnchor,\n  clampCamera,\n  placeCamera,\n  resolveZoom,\n  type AlignmentValue,\n  type Anchor,\n  type Camera,\n  type Rect,\n} from '@embedpdf/core-stage';\nimport type { PluginContext } from '@embedpdf/core';\n\nimport type { GoToOptions } from '../contract';\nimport type { StageAnimation } from '../camera/animation';\nimport type { StageCameraWrite } from '../camera/write';\nimport type { StageHostCapability } from '../host-contract';\nimport { patchSettings, setCursor, type StageModel } from '../model';\nimport type { StageServices } from '../services';\nimport { whenPlaced } from '../services/placement-latch';\n\nexport function createArrival(\n  ctx: PluginContext<StageModel>,\n  { scene, placement }: Pick<StageServices, 'scene' | 'placement'>,\n  { writeCamera, markCause }: Pick<StageCameraWrite, 'writeCamera' | 'markCause'>,\n  { cancelAnimation, animateTo }: Pick<StageAnimation, 'cancelAnimation' | 'animateTo'>,\n) {\n  const {\n    camera,\n    viewport,\n    padding,\n    zoomLimits,\n    paged,\n    isFitAll,\n    itemIndexOfPage,\n    buildScene,\n    sceneRect,\n    itemRect,\n    pageRectOf,\n    currentPages,\n    unitStartOf,\n    fitsAcross,\n    alignPoint,\n    fitBox,\n    boundsFor,\n    constraint,\n    indexOfTarget,\n  } = scene;\n  const state = () => ctx.state.get();\n  const pageCount = () => ctx.document()?.pageCount ?? 0;\n\n  /**\n   * Run a placement whose resolved zoom may change the scene (in wrapped mode\n   * zoom is a layout input), until the scene it placed against is the scene\n   * that results. Every non-wrapped mode is stable after the first pass, and\n   * wrapped fit modes converge on the second (the fit box does not depend on\n   * wrapping). Capped at 3 passes for the one circular case (fit-all +\n   * wrapped).\n   */\n  const stabilized = (place: () => void) => {\n    for (let attempt = 0; attempt < 3; attempt++) {\n      const before = buildScene();\n      place();\n      if (buildScene() === before) return;\n    }\n  };\n\n  const applyAnchor = (anchor: Anchor, align?: AlignmentValue) => {\n    stabilized(() => {\n      const current = buildScene();\n      if (!current.itemCount) return;\n      const item = current.items[current.itemOfPage(anchor.pageIndex)];\n      const zoom = resolveZoom(state().zoom, fitBox(item), viewport(), padding(), zoomLimits());\n      // Resolved against the current viewport: a resize restores the anchor\n      // to the new viewport's policy point (start/start keeps the top pinned).\n      const at = alignPoint(align ?? state().anchorAlign, viewport());\n      writeCamera(cameraFromAnchor(anchor, current, viewport(), zoom, at), boundsFor(item));\n    });\n  };\n  /**\n   * Re-apply the view after a structural, zoom or viewport change. Normally\n   * anchor-preserving (keep looking at the same spot, held at the invariant\n   * point). Under fit-all the subject is the whole scene, so keeping an\n   * anchor is meaningless: re-place instead (which also centers the scene\n   * when unbounded).\n   */\n  const reapply = (anchor: Anchor, align?: AlignmentValue) => {\n    if (isFitAll()) goToTarget(state().pageIndex, { behavior: 'instant' });\n    else applyAnchor(anchor, align);\n  };\n\n  const goToTarget = (pageIndex: number, options?: GoToOptions) => {\n    markCause('programmatic');\n    cancelAnimation();\n    if (pageCount() === 0) return;\n    const target = Math.max(0, Math.min(pageIndex, pageCount() - 1));\n    ctx.state.update(setCursor, target);\n\n    // The restore path (per-page view memory): the exact viewpoint instead of\n    // a fresh placement.\n    if (options?.viewpoint) {\n      ctx.state.update(patchSettings, { zoom: options.viewpoint.zoom });\n      applyAnchor(options.viewpoint.anchor);\n      return;\n    }\n\n    // Placement against the current scene; null when there is nothing to place.\n    const placement = (): { camera: Camera; bounds: Rect } | null => {\n      const current = buildScene(); // paged: the (possibly new) slice; continuous: the full scene\n      if (!current.itemCount) return null;\n      const item = paged() ? current.items[0] : current.items[itemIndexOfPage(target)];\n      const zoom = resolveZoom(state().zoom, fitBox(item), viewport(), padding(), zoomLimits());\n      const subject = isFitAll()\n        ? sceneRect()\n        : fitsAcross(itemRect(item), zoom)\n          ? itemRect(item)\n          : pageRectOf(item, target);\n      // The landing policy: a per-call override beats the setting, and 'keep'\n      // pins that axis to the current camera.\n      const landing = { ...state().arrivalAlign, ...options?.arrivalAlign };\n      const placed = placeCamera(\n        subject,\n        viewport(),\n        zoom,\n        padding(),\n        {\n          x: landing.x === 'keep' ? 'start' : landing.x,\n          y: landing.y === 'keep' ? 'start' : landing.y,\n        },\n        state().direction,\n      );\n      // Arrivals are canonical even on an unbounded stage: the landing clamps\n      // within the true bounds regardless (free roam is a manipulation\n      // affordance, not an arrival one), so an axis with no freedom collapses\n      // to its fitAlign rest and the fit-all scene centers even unbounded.\n      const bounds = boundsFor(item);\n      const settled = clampCamera(placed, bounds, viewport(), { ...constraint(), bounded: true });\n      return {\n        camera: {\n          zoom,\n          x: landing.x === 'keep' ? camera().x : settled.x,\n          y: landing.y === 'keep' ? camera().y : settled.y,\n        },\n        bounds,\n      };\n    };\n\n    if ((options?.behavior ?? state().scrollBehavior) === 'smooth') {\n      const landing = placement();\n      if (landing) animateTo(landing.camera, landing.bounds);\n    } else {\n      // An instant placement converges with the scene (wrapped: zoom is a layout input).\n      stabilized(() => {\n        const landing = placement();\n        if (landing) writeCamera(landing.camera, landing.bounds);\n      });\n    }\n  };\n\n  /**\n   * Step past the pages you're on (`currentPages`): forward to the page after\n   * them, back to the unit before them, so a step always reaches a page you\n   * weren't on. Nothing past either end.\n   */\n  const step = (direction: 1 | -1, options?: GoToOptions) => {\n    const pages = currentPages();\n    if (!pages.length) return;\n    if (direction === 1) {\n      const next = Math.max(...pages) + 1;\n      if (next < pageCount()) goToTarget(next, options);\n    } else {\n      const before = Math.min(...pages) - 1;\n      if (before >= 0) goToTarget(unitStartOf(before), options);\n    }\n  };\n\n  // Home is page 0, a fresh arrival at arrivalAlign (the clamp collapses any\n  // fitting axis to its fitAlign rest point).\n  const resetView = (): void => goToTarget(0, { behavior: 'instant' });\n\n  return {\n    stabilized,\n    applyAnchor,\n    reapply,\n    goToTarget,\n    resetView,\n    api: {\n      goToPage: (page, options) => {\n        const index = indexOfTarget(page);\n        if (index !== null) whenPlaced(placement, options, (go) => goToTarget(index, go));\n      },\n      goToFirstPage: (options) => whenPlaced(placement, options, (go) => goToTarget(0, go)),\n      goToLastPage: (options) =>\n        whenPlaced(placement, options, (go) =>\n          goToTarget(Math.max(0, (ctx.document()?.pageCount ?? 1) - 1), go),\n        ),\n      canGoNext: () => {\n        const pages = currentPages();\n        return pages.length > 0 && Math.max(...pages) < pageCount() - 1;\n      },\n      canGoPrevious: () => {\n        const pages = currentPages();\n        return pages.length > 0 && Math.min(...pages) > 0;\n      },\n      nextPage: (options) => whenPlaced(placement, options, (go) => step(1, go)),\n      previousPage: (options) => whenPlaced(placement, options, (go) => step(-1, go)),\n      resetView,\n    } satisfies Partial<StageHostCapability>,\n  };\n}\nexport type StageArrival = ReturnType<typeof createArrival>;\n","/**\n * A destination as a reveal. A destination (ISO 32000-1 §12.3.2.2) says\n * where on a page to look and how close; the stage's reveal takes the same\n * three knobs:\n *   rect   — what to look at: a point for `xyz`, a rect for `fitR`, the page\n *            for `fit` and the `fitB*` kinds\n *   zoom   — 'keep' | {level} | 'fit' | 'fit-width' | 'fit-height'\n *   anchor — where it lands; 'keep' is the specification's `null`: keep the\n *            current value on that axis\n *\n * Destinations are in page space, the stage's own space, so nothing converts.\n * The `fitB*` kinds fit the page's content bounding box; the whole page\n * stands in for it.\n */\nimport type { PageDestination, PdfSize } from '@embedpdf/core';\n\nimport type { RevealOptions } from './contract';\n\nexport function revealOfDestination(destination: PageDestination, size: PdfSize): RevealOptions {\n  const { width, height } = size;\n  switch (destination.kind) {\n    case 'xyz': {\n      const { x, y, zoom } = destination;\n      return {\n        // A null axis keeps the current camera value; the number fed in for\n        // it is never read (the 'keep' anchor).\n        rect: { x: x ?? 0, y: y ?? 0, width: 0, height: 0 },\n        align: { x: x != null ? 'start' : 'keep', y: y != null ? 'start' : 'keep' },\n        // A zoom of 0 means the same as null: keep the current zoom.\n        zoom: zoom != null && zoom !== 0 ? { level: zoom } : 'keep',\n      };\n    }\n    case 'fit':\n      return { zoom: 'fit' };\n    case 'fitB':\n      return { rect: { x: 0, y: 0, width, height }, zoom: 'fit' };\n    case 'fitH':\n    case 'fitBH': {\n      const { y } = destination;\n      return {\n        rect: { x: 0, y: y ?? 0, width, height: 0 },\n        zoom: 'fit-width',\n        align: { y: y != null ? 'start' : 'keep' },\n      };\n    }\n    case 'fitV':\n    case 'fitBV': {\n      const { x } = destination;\n      return {\n        rect: { x: x ?? 0, y: 0, width: 0, height },\n        zoom: 'fit-height',\n        align: { x: x != null ? 'start' : 'keep' },\n      };\n    }\n    case 'fitR': {\n      const { x, y, width: rectWidth, height: rectHeight } = destination;\n      return { rect: { x, y, width: rectWidth, height: rectHeight }, zoom: 'fit' };\n    }\n  }\n}\n","/**\n * Reveals and destinations. A bare reveal is not navigation: minimal\n * visibility, cursor untouched (in paged flow, revealing a page is navigating\n * to it). A positioned reveal (rect, align or zoom: a search hit) is an\n * arrival: the cursor is set up front, the camera lands per the alignment\n * policy, and a resolved zoom becomes the zoom intent. A destination is a\n * positioned reveal of the spot it names.\n */\nimport { clampZoom, revealCamera, type Camera, type Rect as StageRect } from '@embedpdf/core-stage';\nimport type { PageDestination, PluginContext, PageRef } from '@embedpdf/core';\n\nimport type { GoToDestinationOptions, ArrivalAlignValue, RevealOptions } from '../contract';\nimport { revealOfDestination } from '../destination';\nimport type { StageAnimation } from '../camera/animation';\nimport type { StageCameraWrite } from '../camera/write';\nimport type { StageHostCapability } from '../host-contract';\nimport { patchSettings, setCursor, type StageModel } from '../model';\nimport type { StageServices } from '../services';\nimport { whenPlaced } from '../services/placement-latch';\nimport type { StageArrival } from './arrive';\n\nexport function createReveal(\n  ctx: PluginContext<StageModel>,\n  { scene, placement }: Pick<StageServices, 'scene' | 'placement'>,\n  { writeCamera, markCause }: Pick<StageCameraWrite, 'writeCamera' | 'markCause'>,\n  { cancelAnimation, animateTo }: Pick<StageAnimation, 'cancelAnimation' | 'animateTo'>,\n  { stabilized, goToTarget }: Pick<StageArrival, 'stabilized' | 'goToTarget'>,\n) {\n  const {\n    camera,\n    viewport,\n    padding,\n    zoomLimits,\n    paged,\n    itemIndexOfPage,\n    worldPageFrame,\n    buildScene,\n    sceneRect,\n    pageRectOf,\n    worldRectForContent,\n    boundsFor,\n    indexOfTarget,\n  } = scene;\n  const state = () => ctx.state.get();\n\n  /**\n   * One axis of a positioned-reveal camera. `undefined` is 'nearest' (move\n   * only when the target is outside the padded view), unless the zoom just\n   * changed: then \"do not move\" is meaningless and the slack-axis rule\n   * (center) applies. 'keep' never moves the axis (PDF /XYZ null).\n   */\n  const revealAxis = (\n    align: ArrivalAlignValue | undefined,\n    cameraPosition: number,\n    rectPosition: number,\n    rectExtent: number,\n    viewportExtent: number,\n    zoom: number,\n    zoomChanged: boolean,\n    before: number,\n    after: number,\n  ): number => {\n    if (align === 'keep') return cameraPosition;\n    if (align === undefined) {\n      if (!zoomChanged) {\n        const low = cameraPosition + before / zoom;\n        const high = cameraPosition + (viewportExtent - after) / zoom;\n        if (rectPosition >= low && rectPosition + rectExtent <= high) return cameraPosition; // already visible\n        if (rectExtent > high - low || rectPosition < low) return rectPosition - before / zoom;\n        return rectPosition + rectExtent - (viewportExtent - after) / zoom;\n      }\n      align = 'center';\n    }\n    if (align === 'start') return rectPosition - before / zoom;\n    if (align === 'end') return rectPosition + rectExtent - (viewportExtent - after) / zoom;\n    const fraction = align === 'center' ? 0.5 : Math.min(1, Math.max(0, align));\n    // Over the viewport moved by half the sides' difference, as `placeCamera` does.\n    return (\n      rectPosition + rectExtent / 2 - (viewportExtent * fraction + (before - after) / 2) / zoom\n    );\n  };\n\n  const revealAt = (pageIndex: number, options?: RevealOptions): void => {\n    markCause('programmatic');\n    const pageCount = ctx.document()?.pageCount ?? 0;\n    if (pageCount === 0) return;\n    const target = Math.max(0, Math.min(pageIndex, pageCount - 1));\n    const positioned =\n      !!options &&\n      (options.rect !== undefined ||\n        options.align !== undefined ||\n        (options.zoom !== undefined && options.zoom !== 'keep'));\n\n    if (!positioned) {\n      // A bare reveal is not navigation: minimal visibility, cursor untouched.\n      if (paged()) {\n        // The page is not in the one-item slice: revealing it is navigating to it.\n        goToTarget(target, options);\n        return;\n      }\n      const current = buildScene();\n      if (!current.itemCount) return;\n      const page = pageRectOf(current.items[itemIndexOfPage(target)], target);\n      // Reveal the outer box: pageFrame chrome (labels, buttons) belongs to\n      // the page, so \"make the page visible\" includes its reserved bands.\n      const frame = worldPageFrame();\n      const box = {\n        x: page.x - frame.left,\n        y: page.y - frame.top,\n        width: page.width + frame.left + frame.right,\n        height: page.height + frame.top + frame.bottom,\n      };\n      const next = revealCamera(camera(), box, viewport(), padding());\n      const now = camera();\n      if (next.x === now.x && next.y === now.y) return; // already visible\n      cancelAnimation();\n      if ((options?.behavior ?? state().scrollBehavior) === 'smooth') {\n        animateTo(next, sceneRect());\n      } else {\n        writeCamera(next, sceneRect());\n      }\n      return;\n    }\n\n    // A positioned reveal is an arrival at a rect or point (a search hit, a\n    // PDF destination). Like navigation, the cursor is intent, set up front\n    // (in paged flow this also rebuilds the one-item slice), never derived\n    // from a camera that may be mid-tween.\n    cancelAnimation();\n    ctx.state.update(setCursor, target);\n\n    const place = (): { camera: Camera; bounds: StageRect; zoomChanged: boolean } | null => {\n      const current = buildScene();\n      if (!current.itemCount) return null;\n      const item = paged() ? current.items[0] : current.items[itemIndexOfPage(target)];\n      const world = options.rect\n        ? worldRectForContent(item, target, options.rect)\n        : pageRectOf(item, target);\n      const zoomDirective = options.zoom ?? 'keep';\n      const inset = padding();\n      const availableWidth = Math.max(1, viewport().width - inset.left - inset.right);\n      const availableHeight = Math.max(1, viewport().height - inset.top - inset.bottom);\n      let zoom =\n        typeof zoomDirective === 'object'\n          ? zoomDirective.level\n          : zoomDirective === 'fit'\n            ? Math.min(availableWidth / world.width, availableHeight / world.height)\n            : zoomDirective === 'fit-width'\n              ? availableWidth / world.width\n              : zoomDirective === 'fit-height'\n                ? availableHeight / world.height\n                : camera().zoom;\n      // A degenerate target (a point with a fit directive) only pans.\n      if (!Number.isFinite(zoom) || zoom <= 0) zoom = camera().zoom;\n      // A tiny rect fits at the zoom limit, centered, like any other zoom.\n      zoom = clampZoom(zoom, zoomLimits());\n      const zoomChanged = zoomDirective !== 'keep';\n      const align = options.align ?? {};\n      return {\n        camera: {\n          x: revealAxis(\n            align.x,\n            camera().x,\n            world.x,\n            world.width,\n            viewport().width,\n            zoom,\n            zoomChanged,\n            inset.left,\n            inset.right,\n          ),\n          y: revealAxis(\n            align.y,\n            camera().y,\n            world.y,\n            world.height,\n            viewport().height,\n            zoom,\n            zoomChanged,\n            inset.top,\n            inset.bottom,\n          ),\n          zoom,\n        },\n        bounds: boundsFor(item),\n        zoomChanged,\n      };\n    };\n\n    const first = place();\n    if (!first) return;\n    // A resolved zoom becomes the zoom intent (like zoomAround), so later\n    // resizes and refits keep the destination's magnification.\n    if (first.zoomChanged) {\n      ctx.state.update(patchSettings, { zoom: { level: first.camera.zoom } });\n    }\n    if ((options.behavior ?? state().scrollBehavior) === 'smooth') {\n      // If the zoom patch re-wrapped the scene (zoom is a layout input in\n      // wrapped mode), recompute once against the new geometry.\n      const landing = place() ?? first;\n      animateTo(landing.camera, landing.bounds);\n    } else {\n      stabilized(() => {\n        const landing = place();\n        if (landing) writeCamera(landing.camera, landing.bounds);\n      });\n    }\n  };\n\n  const reveal = (page: PageRef | number, options?: RevealOptions): void => {\n    const index = indexOfTarget(page);\n    if (index !== null) whenPlaced(placement, options, (go) => revealAt(index, go));\n  };\n\n  const goToDestination = (\n    destination: PageDestination,\n    options?: GoToDestinationOptions,\n  ): void => {\n    const layout = ctx.getPage(destination.page);\n    if (!layout) return;\n    const spot = revealOfDestination(destination, layout.size);\n    whenPlaced(placement, { ...spot, behavior: options?.behavior }, (go) =>\n      revealAt(layout.index, go),\n    );\n  };\n\n  return {\n    api: { reveal, goToDestination } satisfies Partial<StageHostCapability>,\n  };\n}\n","/**\n * Zoom verbs. Pointer-less zooms magnify around the zoomAlign focal point\n * (pinch and wheel pass their own pointer to `zoomAround`: physics beats\n * policy); fit modes are zoom intents written through the settings; zoomIn\n * and zoomOut step through round levels; the double-tap ladder ascends\n * reading postures. Every zoom stays inside the minZoom/maxZoom limits.\n */\nimport {\n  anchorAtPoint,\n  clampZoom,\n  resolveZoom,\n  toWorld,\n  ZoomMode,\n  type ZoomLimits,\n} from '@embedpdf/core-stage';\nimport { addRotations, type Rotation } from '@embedpdf/core-geometry';\nimport type { PluginContext } from '@embedpdf/core';\n\nimport type { StageAnimation } from '../camera/animation';\nimport type { StageCameraWrite } from '../camera/write';\nimport type { StageGestures } from '../camera/gestures';\nimport type { StageHostCapability } from '../host-contract';\nimport { patchSettings, type StageModel } from '../model';\nimport type { StageServices } from '../services';\nimport type { StageSettingsArea } from '../settings/settings';\n\n/**\n * The levels zoomIn and zoomOut land on, from ZOOM_MIN to ZOOM_MAX: round\n * percentages, as in Acrobat and the browsers' PDF viewers, about 1.25× to\n * 1.5× apart. From a level between two of them (a fit, a pinch), a step goes\n * to the next one, so 137% zooms in to 150%.\n */\nconst ZOOM_STEPS = [\n  0.05,\n  0.1,\n  0.15,\n  0.2,\n  0.25,\n  1 / 3,\n  0.5,\n  2 / 3,\n  0.75,\n  1,\n  1.25,\n  1.5,\n  2,\n  3,\n  4,\n  6,\n  8,\n  12,\n  16,\n  24,\n  32,\n  48,\n  64,\n];\nconst ZOOM_STEPS_DOWN = [...ZOOM_STEPS].reverse();\n/** The smallest change a step makes: a level within 5% of a round level steps past it, so a\n *  press never moves too little to see (98% zooms in to 125%, not 100%). Below the closest\n *  two levels' ratio (2/3 → 3/4), so a step from a round level never skips the next. */\nconst MIN_STEP = 1.05;\n/** Float slack for comparing a zoom with a limit it was clamped to. */\nconst EPSILON = 1e-9;\n\n/** The next round level above `zoom`, or `limits.max` when that comes first. */\nconst stepIn = (zoom: number, limits: ZoomLimits): number =>\n  clampZoom(ZOOM_STEPS.find((level) => level > zoom * MIN_STEP) ?? limits.max, limits);\n\n/** The next round level below `zoom`, or `limits.min` when that comes first. */\nconst stepOut = (zoom: number, limits: ZoomLimits): number =>\n  clampZoom(ZOOM_STEPS_DOWN.find((level) => level < zoom / MIN_STEP) ?? limits.min, limits);\n\nexport function createZoom(\n  ctx: PluginContext<StageModel>,\n  { scene }: Pick<StageServices, 'scene'>,\n  { syncCursorFromCamera }: Pick<StageCameraWrite, 'syncCursorFromCamera'>,\n  {\n    cancelAnimation,\n    animateZoomAnchored,\n  }: Pick<StageAnimation, 'cancelAnimation' | 'animateZoomAnchored'>,\n  gestures: StageGestures['api'],\n  settings: Pick<StageSettingsArea, 'updateSettings'>,\n) {\n  const {\n    camera,\n    viewport,\n    padding,\n    zoomLimits,\n    paged,\n    itemIndexOfPage,\n    buildScene,\n    alignPoint,\n    fitBox,\n  } = scene;\n  const state = () => ctx.state.get();\n  const zoomAlignPoint = () => alignPoint(state().zoomAlign, viewport());\n  // A step to `target`, around the zoomAlign point; none when the limit holds the zoom.\n  const stepTo = (target: number, around = zoomAlignPoint()) => {\n    if (target !== camera().zoom) gestures.zoomAround(around, target / camera().zoom);\n  };\n\n  const setViewRotation = (viewRotation: Rotation): void =>\n    settings.updateSettings({ viewRotation });\n\n  return {\n    api: {\n      doubleTapZoom: (point) => {\n        cancelAnimation();\n        const before = buildScene();\n        if (!before.itemCount) return;\n        const item = paged() ? before.items[0] : before.items[itemIndexOfPage(state().pageIndex)];\n        // The ladder (the platform convention) ascends reading postures, each\n        // derived from a zoom intent: see the page (automatic), read the text\n        // (fit-width), inspect (2.5× the automatic fit). Stops within 10% of\n        // a neighbor collapse, so on phones, where automatic is fit-width,\n        // the ladder is the familiar two-state toggle.\n        //\n        // As on iOS, the ladder ascends only from a rung: a tap at a posture\n        // moves to the next, wrapping past the top. A pinch to any other\n        // level leaves the ladder, and a double-tap there resets to the base\n        // fit (\"take me back to reading\"), never a further zoom-in.\n        const fit = fitBox(item);\n        const limits = zoomLimits();\n        const automatic = resolveZoom(\n          { mode: ZoomMode.Automatic },\n          fit,\n          viewport(),\n          padding(),\n          limits,\n        );\n        const fitWidth = resolveZoom(\n          { mode: ZoomMode.FitWidth },\n          fit,\n          viewport(),\n          padding(),\n          limits,\n        );\n        const stops = [automatic, fitWidth, clampZoom(automatic * 2.5, limits)]\n          .sort((left, right) => left - right)\n          .filter((zoom, index, all) => index === 0 || zoom > all[index - 1] * 1.1);\n        // The same ±10% band the dedupe uses: \"at a posture\" tolerates fit drift.\n        const near = (zoom: number, stop: number) => zoom > stop / 1.1 && zoom < stop * 1.1;\n        const onRung = stops.findIndex((stop) => near(camera().zoom, stop));\n        const target = onRung >= 0 ? stops[(onRung + 1) % stops.length] : stops[0];\n        // The intent commits up front, as in `reveal`: a caught tween must\n        // never leave the camera at an intermediate zoom while the stored\n        // intent still says \"fit\", or the next refit would snap somewhere the\n        // user did not ask for.\n        ctx.state.update(patchSettings, { zoom: { level: target } });\n        // Wrapped grids re-layout on the intent change: anchor the focal\n        // point against the scene that will actually be on screen.\n        const after = buildScene();\n        if (!after.itemCount) return;\n        const focal = anchorAtPoint(after, toWorld(camera(), point));\n        // The focal-anchored tween keeps the tapped point still.\n        animateZoomAnchored(focal, point, target, undefined, syncCursorFromCamera);\n      },\n      zoomIn: (options) => stepTo(stepIn(camera().zoom, zoomLimits()), options?.around),\n      zoomOut: (options) => stepTo(stepOut(camera().zoom, zoomLimits()), options?.around),\n      canZoomIn: () => camera().zoom < zoomLimits().max * (1 - EPSILON),\n      canZoomOut: () => camera().zoom > zoomLimits().min * (1 + EPSILON),\n      zoomTo: (zoom, options) => {\n        if (typeof zoom === 'number') {\n          if (options?.around) gestures.zoomAround(options.around, zoom / camera().zoom);\n          else settings.updateSettings({ zoom: { level: zoom } });\n          return;\n        }\n        settings.updateSettings({ zoom });\n      },\n      zoomBy: (factor, options) => gestures.zoomAround(options?.around ?? zoomAlignPoint(), factor),\n      fitWidth: () => settings.updateSettings({ zoom: { mode: ZoomMode.FitWidth } }),\n      fitPage: () => settings.updateSettings({ zoom: { mode: ZoomMode.FitPage } }),\n      fitAll: () => settings.updateSettings({ zoom: { mode: ZoomMode.FitAll } }),\n      fitAutomatic: () => settings.updateSettings({ zoom: { mode: ZoomMode.Automatic } }),\n      setViewRotation,\n      rotateViewBy: (delta) =>\n        setViewRotation(addRotations(state().viewRotation, delta === 90 ? 90 : 270)),\n    } satisfies Partial<StageHostCapability>,\n  };\n}\n","/**\n * The zoom tool's drag: a box to zoom into, or a click to zoom one step. The\n * drag is held in page coordinates (see {@link ZoomDrag}); `getZoomBox` hands\n * it to the adapters in viewport px only once it is big enough to be a box,\n * so what shows is what the release does. A box zooms in about one point, so\n * it grows straight out until it fills the view.\n */\nimport {\n  anchorAtPoint,\n  clampCamera,\n  toScreen,\n  ZOOM_MAX,\n  ZOOM_MIN,\n  type Camera,\n} from '@embedpdf/core-stage';\nimport { memo, type PageRef, type PluginContext } from '@embedpdf/core';\nimport type { Point, Rect } from '@embedpdf/core-geometry';\n\nimport type { StageAnimation } from '../camera/animation';\nimport type { StageCameraWrite } from '../camera/write';\nimport type { StageHostCapability } from '../host-contract';\nimport { patchSettings, setZoomDrag, type StageModel, type ZoomDrag } from '../model';\nimport type { StageServices } from '../services';\n\n/** A drag shorter than this on both axes, in viewport px, is a click. */\nconst BOX_THRESHOLD_PX = 4;\n\nconst rectBetween = (from: Point, to: Point): Rect => ({\n  x: Math.min(from.x, to.x),\n  y: Math.min(from.y, to.y),\n  width: Math.abs(to.x - from.x),\n  height: Math.abs(to.y - from.y),\n});\n\nconst isBox = (box: Rect): boolean =>\n  box.width >= BOX_THRESHOLD_PX || box.height >= BOX_THRESHOLD_PX;\n\nexport function createZoomDrag(\n  ctx: PluginContext<StageModel>,\n  { scene }: Pick<StageServices, 'scene'>,\n  {\n    writeCamera,\n    markCause,\n    syncCursorFromCamera,\n  }: Pick<StageCameraWrite, 'writeCamera' | 'markCause' | 'syncCursorFromCamera'>,\n  {\n    cancelAnimation,\n    animateZoomAnchored,\n  }: Pick<StageAnimation, 'cancelAnimation' | 'animateZoomAnchored'>,\n  stage: Pick<\n    StageHostCapability,\n    | 'getPageAt'\n    | 'getPageBox'\n    | 'listVisiblePages'\n    | 'viewportToPage'\n    | 'pageToWorld'\n    | 'zoomIn'\n    | 'zoomOut'\n  >,\n) {\n  const state = () => ctx.state.get();\n\n  // A page point → viewport px through the page as it is drawn, device-snapped:\n  // the exact inverse of `viewportToPage`, so the box sits under the pointer\n  // and its middle lands on the point the user saw there.\n  const toViewport = (page: PageRef, point: Point): Point | null => {\n    const frame = stage.getPageBox(page);\n    if (!frame) return null;\n    const view = frame.transform.pageToView(point);\n    return { x: frame.screenX + view.x, y: frame.screenY + view.y };\n  };\n\n  /** The drag's corners in viewport px; null when its page is not laid out. */\n  const viewportRectOf = (drag: ZoomDrag): Rect | null => {\n    const from = toViewport(drag.page, drag.from);\n    const to = toViewport(drag.page, drag.to);\n    return from && to ? rectBetween(from, to) : null;\n  };\n\n  // Memoized on the drag and everything that moves it on screen, so the read\n  // is reference-stable for adapter selectors.\n  const zoomBox = memo(\n    () => {\n      scene.buildScene(); // keys the scene cache that `cacheKey` reads\n      return [state().zoomDrag, scene.camera(), scene.cacheKey()] as const;\n    },\n    (drag, _camera, _sceneKey): Rect | null => {\n      const box = drag && viewportRectOf(drag);\n      return box && isBox(box) ? box : null;\n    },\n  );\n\n  /** The drag's box in world units, the camera's own space; null when its page is not laid out. */\n  const worldRectOf = (drag: ZoomDrag): Rect | null => {\n    const from = stage.pageToWorld(drag.page, drag.from);\n    const to = stage.pageToWorld(drag.page, drag.to);\n    return from && to ? rectBetween(from, to) : null;\n  };\n\n  /**\n   * Zoom into the box: the zoom that fits it inside the padding, the camera\n   * that centers it (clamped, as every camera is), and the one point that is\n   * at the same place on screen before and after. A tween that holds that\n   * point while the zoom changes is a pure zoom, so the box grows straight\n   * out. Moving the camera's corner and its zoom each on their own would\n   * swing the content away and back on the way.\n   */\n  const zoomInto = (drag: ZoomDrag): void => {\n    const sized = worldRectOf(drag);\n    if (!sized) return;\n    const view = scene.viewport();\n    const inset = scene.padding();\n    const fit = Math.min(\n      Math.max(1, view.width - inset.left - inset.right) / sized.width,\n      Math.max(1, view.height - inset.top - inset.bottom) / sized.height,\n    );\n    if (!Number.isFinite(fit)) return;\n    const zoom = Math.min(ZOOM_MAX, Math.max(ZOOM_MIN, fit));\n    // The level becomes the zoom intent up front, as on a double-tap: a tween\n    // caught halfway must not leave a fit mode stored.\n    ctx.state.update(patchSettings, { zoom: { level: zoom } });\n    // A wrapped grid lays out again at a new zoom: place the box in the scene as it is now.\n    const box = worldRectOf(drag) ?? sized;\n    const from = scene.camera();\n    const target: Camera = clampCamera(\n      {\n        zoom,\n        // Centered in the padded viewport.\n        x: box.x + box.width / 2 - (view.width + inset.left - inset.right) / (2 * zoom),\n        y: box.y + box.height / 2 - (view.height + inset.top - inset.bottom) / (2 * zoom),\n      },\n      scene.stayBounds(),\n      view,\n      scene.constraint(),\n    );\n    markCause('user');\n    if (state().scrollBehavior === 'instant' || Math.abs(target.zoom - from.zoom) < 1e-9) {\n      writeCamera(target);\n      syncCursorFromCamera();\n      return;\n    }\n    // The fixed point w solves (w − from)·from.zoom = (w − target)·target.zoom on each axis.\n    const fixedOn = (start: number, end: number) =>\n      (end * target.zoom - start * from.zoom) / (target.zoom - from.zoom);\n    const fixed = { x: fixedOn(from.x, target.x), y: fixedOn(from.y, target.y) };\n    const current = scene.buildScene();\n    if (!current.itemCount) return;\n    animateZoomAnchored(\n      anchorAtPoint(current, fixed),\n      toScreen(from, fixed),\n      target.zoom,\n      undefined,\n      syncCursorFromCamera,\n    );\n  };\n\n  return {\n    api: {\n      beginZoomDrag: (point) => {\n        cancelAnimation(); // the content holds still under the box\n        // A press between pages anchors on a visible page: every page shares\n        // the scene's plane, so any of them can hold the box.\n        const page = stage.getPageAt(point)?.ref ?? stage.listVisiblePages()[0]?.ref;\n        const from = page ? stage.viewportToPage(page, point) : null;\n        ctx.state.update(setZoomDrag, page && from ? { page, from, to: from } : null);\n      },\n      moveZoomDrag: (point) => {\n        const drag = state().zoomDrag;\n        // Off screen, the drag's page can't take the point: the box keeps its last corner.\n        const to = drag && stage.viewportToPage(drag.page, point);\n        if (drag && to) ctx.state.update(setZoomDrag, { ...drag, to });\n      },\n      endZoomDrag: (options) => {\n        const drag = state().zoomDrag;\n        if (!drag) return;\n        ctx.state.update(setZoomDrag, null);\n        const box = viewportRectOf(drag);\n        if (!box) return;\n        if (!isBox(box)) {\n          const around = { x: box.x, y: box.y };\n          if (options?.zoomOut) stage.zoomOut({ around });\n          else stage.zoomIn({ around });\n          return;\n        }\n        zoomInto(drag);\n      },\n      cancelZoomDrag: () => ctx.state.update(setZoomDrag, null),\n      getZoomBox: zoomBox,\n    } satisfies Partial<StageHostCapability>,\n  };\n}\n","/**\n * The page reads: laid-out pages with their transforms (PDF points → view px\n * → device px), the scroller projection, the visible set (memoized so reads\n * stay reference-stable), coordinate conversions and the camera, zoom and\n * viewpoint reads.\n */\nimport {\n  cameraWorldRect,\n  scrollMetrics,\n  toScreen,\n  toWorld,\n  type PageBox,\n  type ScrollMetrics,\n  type Size,\n} from '@embedpdf/core-stage';\nimport {\n  applyPoint,\n  applyRect,\n  displaySize,\n  intersectRects,\n  pageTransform,\n  rotateScaleMatrix,\n  snapToDevice,\n} from '@embedpdf/core-geometry';\nimport type { Point } from '@embedpdf/core-geometry';\nimport {\n  memo,\n  toPageRef,\n  type PageDestination,\n  type PluginContext,\n  type PageRef,\n} from '@embedpdf/core';\n\nimport type { Viewpoint, VisiblePage } from '../contract';\nimport type { StageHostCapability } from '../host-contract';\nimport type { StageModel } from '../model';\nimport type { StageServices } from '../services';\n\nexport function createPageReads(\n  ctx: PluginContext<StageModel>,\n  { scene }: Pick<StageServices, 'scene'>,\n) {\n  const {\n    camera,\n    viewport,\n    dpr,\n    padding,\n    paged,\n    buildScene,\n    cacheKey,\n    stayBounds,\n    cursorItem,\n    currentPages,\n    currentAnchor,\n  } = scene;\n  const state = () => ctx.state.get();\n\n  // The durable identity of the page at a display index, from the registry.\n  const pageObjectNumberAt = (index: number): number =>\n    ctx.document()?.pages[index]?.ref.objectNumber ?? index + 1;\n\n  // The un-rotated point size of a laid-out box, for when the registry entry\n  // is momentarily absent. `displaySize` is its own inverse (display box →\n  // content box); dividing by contentScale recovers points.\n  const unrotatedPoints = (box: PageBox): Size => {\n    const content = displaySize({ width: box.width, height: box.height }, box.rotation);\n    return { width: content.width / box.contentScale, height: content.height / box.contentScale };\n  };\n\n  // Attach durable identity and the per-page transform (PDF points → view px\n  // → device px). `scale` is view px per point: contentScale (world per\n  // point) × zoom (view px per world); `pageSize` is the page's un-rotated\n  // points from the registry. The transform depends only on zoom, rotation,\n  // contentScale and dpr, so the same box yields the same transform at any pan.\n  const withTransform = (box: PageBox): VisiblePage => {\n    const registered = ctx.document()?.pages[box.pageIndex];\n    const pageSize = registered\n      ? { width: registered.size.width, height: registered.size.height }\n      : unrotatedPoints(box);\n    const current = camera();\n    const ratio = dpr();\n    // The footprint's top-left, camera-resolved. Device-snapped at rest, which\n    // keeps a rotated page on the device grid; while the zoom moves it places\n    // fractionally (see `StageModel.cameraResting`).\n    const rawX = (box.x - current.x) * current.zoom;\n    const rawY = (box.y - current.y) * current.zoom;\n    const resting = state().cameraResting;\n    const screenX = resting ? snapToDevice(rawX, ratio) : rawX;\n    const screenY = resting ? snapToDevice(rawY, ratio) : rawY;\n    const transform = pageTransform({\n      pageSize,\n      rotation: box.rotation,\n      scale: box.contentScale * current.zoom,\n      // The page's physical 100%: the platform unit factor × its /UserUnit,\n      // so `transform.zoom` reads as \"percent of Acrobat's 100%\" per page,\n      // independent of sizing mode or camera state.\n      baseScale: state().viewUnitsPerPoint * (registered?.userUnit ?? 1),\n      dpr: ratio,\n    });\n    // The on-screen page region in points: viewport ∩ footprint in view\n    // space (both axis-aligned), inverted through the transform (exact for\n    // quarter-turns). The virtualizer's query already decided this coarsely;\n    // it is refined per page here, once, so no adapter re-derives camera math\n    // (tiling's demand reads this field).\n    const size = viewport();\n    const onScreen = intersectRects(\n      { x: -screenX, y: -screenY, width: size.width, height: size.height },\n      { x: 0, y: 0, width: transform.viewWidth, height: transform.viewHeight },\n    );\n    const visibleRect =\n      onScreen.width > 0 && onScreen.height > 0\n        ? transform.viewToPageRect(onScreen)\n        : { x: 0, y: 0, width: 0, height: 0 };\n    return {\n      ...box,\n      ref: toPageRef(pageObjectNumberAt(box.pageIndex)),\n      screenX,\n      screenY,\n      transform,\n      visibleRect,\n    };\n  };\n\n  // The scroller projection: the camera in native DOM vocabulary, against the\n  // same bounds the pan clamp uses (stayBounds: the slice item in paged flow,\n  // the scene in continuous). Memoized like the visible pages: the same\n  // reference until a field moves, so adapter reads can use plain equality.\n  const emptyScrollMetrics: ScrollMetrics = {\n    scrollLeft: 0,\n    scrollTop: 0,\n    scrollWidth: 0,\n    scrollHeight: 0,\n    clientWidth: 0,\n    clientHeight: 0,\n    scrollableX: false,\n    scrollableY: false,\n  };\n  let lastMetrics: ScrollMetrics | null = null;\n  const scrollMetricsNow = (): ScrollMetrics => {\n    if (!state().placed) return emptyScrollMetrics;\n    const metrics = scrollMetrics(\n      camera(),\n      buildScene().itemCount ? stayBounds() : { x: 0, y: 0, width: 0, height: 0 },\n      viewport(),\n      padding(),\n    );\n    const previous = lastMetrics;\n    if (\n      previous &&\n      previous.scrollLeft === metrics.scrollLeft &&\n      previous.scrollTop === metrics.scrollTop &&\n      previous.scrollWidth === metrics.scrollWidth &&\n      previous.scrollHeight === metrics.scrollHeight &&\n      previous.clientWidth === metrics.clientWidth &&\n      previous.clientHeight === metrics.clientHeight\n    ) {\n      return previous; // scrollableX/Y derive from the six numbers\n    }\n    lastMetrics = metrics;\n    return metrics;\n  };\n\n  // The visible pages, memoized on everything they depend on so the read is\n  // reference-stable (no useSyncExternalStore tearing loop). Paged flow\n  // renders only the slice's item; continuous flow renders the camera's\n  // query window.\n  const noVisiblePages: VisiblePage[] = [];\n  const placedVisiblePages = memo(\n    () => {\n      const current = camera();\n      const size = viewport();\n      buildScene(); // keys the scene cache that `cacheKey` reads\n      return [\n        cacheKey(),\n        state().flow,\n        current.x,\n        current.y,\n        current.zoom,\n        size.width,\n        size.height,\n        dpr(),\n        state().cameraResting,\n      ] as const;\n    },\n    (_sceneKey, _flow, x, y, zoom, width, height, _dpr, _resting): VisiblePage[] => {\n      const scene = buildScene();\n      const items = paged()\n        ? scene.items.slice(0, 1)\n        : scene.query(cameraWorldRect({ x, y, zoom }, { width, height }));\n      return items.flatMap((item) => item.pages).map(withTransform);\n    },\n  );\n  const visiblePages = (): VisiblePage[] =>\n    state().placed ? placedVisiblePages() : noVisiblePages;\n\n  const getPageBox = (page: PageRef | number): VisiblePage | null => {\n    if (!state().placed) return null;\n    const index = ctx.getPage(page)?.index ?? -1;\n    if (index < 0) return null;\n    const scene = buildScene();\n    if (!scene.itemCount) return null;\n    const box = scene.items[scene.itemOfPage(index)].pages.find(\n      (candidate) => candidate.pageIndex === index,\n    );\n    return box ? withTransform(box) : null;\n  };\n\n  const pageToWorld = (page: PageRef | number, point: Point): Point | null => {\n    const frame = getPageBox(page);\n    if (!frame) return null;\n    // Place the page point into the page's display box through the same\n    // quarter-turn matrix the layout and renderer use (`rotateScaleMatrix`),\n    // so this forward transform and the adapter's inverse hit-test cannot\n    // drift. `displaySize` is its own inverse, so it recovers the un-rotated\n    // content size from the display box.\n    const content = displaySize({ width: frame.width, height: frame.height }, frame.rotation);\n    const matrix = rotateScaleMatrix(\n      frame.contentScale,\n      content.width,\n      content.height,\n      frame.rotation,\n    );\n    const offset = applyPoint(matrix, point);\n    return { x: frame.x + offset.x, y: frame.y + offset.y };\n  };\n\n  // The visible entry of a page given by its ref or its index; null when it is\n  // off screen or not in the document.\n  const visiblePageOf = (page: PageRef | number): VisiblePage | null => {\n    const objectNumber = ctx.getPage(page)?.ref.objectNumber;\n    if (objectNumber === undefined) return null;\n    return visiblePages().find((visible) => visible.ref.objectNumber === objectNumber) ?? null;\n  };\n\n  return {\n    scrollMetricsNow,\n    visiblePages,\n    api: {\n      getCamera: camera,\n      getViewportSize: viewport,\n      getScrollMetrics: scrollMetricsNow,\n      listVisiblePages: visiblePages,\n      isPageVisible: (page) => visiblePageOf(page) !== null,\n      getCurrentPageIndex: () => state().pageIndex,\n      getCurrentPage: () => ctx.document()?.pages[state().pageIndex]?.ref ?? null,\n      getPageCount: () => ctx.document()?.pageCount ?? 0,\n      listCurrentItemPages: () => {\n        const item = cursorItem();\n        const pages = ctx.document()?.pages ?? [];\n        return item\n          ? item.pageIndexes.map((index) => pages[index]).filter((page) => page !== undefined)\n          : [];\n      },\n      listCurrentPages: () => {\n        const pages = ctx.document()?.pages ?? [];\n        return currentPages()\n          .map((index) => pages[index])\n          .filter((page) => page !== undefined);\n      },\n      getPageBox,\n      getPageAt: (point) => {\n        // Find the visible page whose device-snapped display box contains the\n        // point, then invert that page's transform: the same `viewToPage`\n        // the per-page context's `toPagePoint` uses, so the two never drift.\n        for (const page of visiblePages()) {\n          const localX = point.x - page.screenX;\n          const localY = point.y - page.screenY;\n          if (\n            localX >= 0 &&\n            localY >= 0 &&\n            localX <= page.transform.viewWidth &&\n            localY <= page.transform.viewHeight\n          ) {\n            return {\n              ref: page.ref,\n              point: page.transform.viewToPage({ x: localX, y: localY }),\n              scale: page.transform.viewScale,\n              rotation: page.rotation,\n              zoom: page.transform.zoom,\n            };\n          }\n        }\n        return null;\n      },\n      viewportToPage: (page, point) => {\n        // `getPageAt` without the containment check: project onto one page's\n        // plane, valid outside its bounds, through the same inverse transform.\n        const target = visiblePageOf(page);\n        if (!target) return null;\n        return target.transform.viewToPage({\n          x: point.x - target.screenX,\n          y: point.y - target.screenY,\n        });\n      },\n      pageToWorld,\n      pageRectToViewport: (page, rect) => {\n        const frame = getPageBox(page);\n        if (!frame) return null;\n        const content = displaySize({ width: frame.width, height: frame.height }, frame.rotation);\n        const matrix = rotateScaleMatrix(\n          frame.contentScale,\n          content.width,\n          content.height,\n          frame.rotation,\n        );\n        const world = applyRect(matrix, rect);\n        const current = camera();\n        const topLeft = toScreen(current, { x: frame.x + world.x, y: frame.y + world.y });\n        return {\n          x: topLeft.x,\n          y: topLeft.y,\n          width: world.width * current.zoom,\n          height: world.height * current.zoom,\n        };\n      },\n      worldToViewport: (world) => toScreen(camera(), world),\n      viewportToWorld: (point) => toWorld(camera(), point),\n      pageToViewport: (page, point) => {\n        const world = pageToWorld(page, point);\n        return world ? toScreen(camera(), world) : null;\n      },\n      getViewRotation: () => state().viewRotation,\n      getZoomLevel: () => camera().zoom,\n      getZoomMode: () => {\n        const zoom = state().zoom;\n        return 'mode' in zoom ? zoom.mode : 'custom';\n      },\n      getViewpoint: (): Viewpoint => ({ anchor: currentAnchor(), zoom: state().zoom }),\n      getCurrentDestination: (): PageDestination | null => {\n        // Where `goToDestination` puts a destination's point: the padding in from the viewport's\n        // top-left. The page read is the first one reaching past that point; the one above it\n        // may still show in the padding.\n        const { left: insetX, top: insetY } = padding();\n        const current = camera();\n        const first = visiblePages()\n          .filter((page) => {\n            const corner = toScreen(current, { x: page.x + page.width, y: page.y + page.height });\n            return corner.x > insetX && corner.y > insetY;\n          })\n          .sort((left, right) => left.pageIndex - right.pageIndex)[0];\n        const size = first && ctx.getPage(first.ref)?.size;\n        if (!first || !size) return null;\n        // That point on the page's plane, then the nearest point of the page: a quarter-turn\n        // keeps the page's edges on the axes, so clamping each axis is exact.\n        const corner = first.transform.viewToPage({\n          x: insetX - first.screenX,\n          y: insetY - first.screenY,\n        });\n        const clamp = (value: number, max: number) =>\n          Math.round(Math.min(Math.max(value, 0), max) * 100) / 100;\n        return {\n          kind: 'xyz',\n          page: first.ref,\n          x: clamp(corner.x, size.width),\n          y: clamp(corner.y, size.height),\n          zoom: null,\n        };\n      },\n    } satisfies Partial<StageHostCapability>,\n  };\n}\nexport type StagePageReads = ReturnType<typeof createPageReads>;\n","/**\n * The stage's six events. Five of them are derived in one `ctx.state.onChange`\n * listener, from the state before and after each committed change, so a new\n * verb can never forget to announce a page, zoom, camera, settings or viewport\n * change. `motionEnded` is an occurrence: the camera animation emits it where a\n * tween or fling ends.\n */\nimport type { PluginContext } from '@embedpdf/core';\n\nimport type {\n  StageCameraChangedEvent,\n  StageMotionEndedEvent,\n  StagePageChangedEvent,\n  StageSettingsChangedEvent,\n  StageViewportChangedEvent,\n  StageZoomChangedEvent,\n} from '../contract';\nimport type { StageModel } from '../model';\nimport { eqSetting } from '../responsive';\nimport { pickSettings, SETTING_KEYS } from '../settings';\n\nexport function createEvents(ctx: PluginContext<StageModel>) {\n  const pageChanged = ctx.events.source<StagePageChangedEvent>();\n  const zoomChanged = ctx.events.source<StageZoomChangedEvent>();\n  const cameraChanged = ctx.events.source<StageCameraChangedEvent>();\n  const motionEnded = ctx.events.source<StageMotionEndedEvent>();\n  const settingsChanged = ctx.events.source<StageSettingsChangedEvent>();\n  const viewportChanged = ctx.events.source<StageViewportChangedEvent>();\n\n  ctx.state.onChange(({ previous, next }) => {\n    if (previous.camera !== next.camera) {\n      cameraChanged.emit({ camera: next.camera });\n      if (previous.camera.zoom !== next.camera.zoom) {\n        zoomChanged.emit({\n          level: next.camera.zoom,\n          previousLevel: previous.camera.zoom,\n          mode: 'mode' in next.zoom ? next.zoom.mode : 'custom',\n        });\n      }\n    }\n    if (previous.pageIndex !== next.pageIndex) {\n      pageChanged.emit({\n        page: ctx.document()?.pages[next.pageIndex]?.ref ?? null,\n        pageIndex: next.pageIndex,\n        previousPageIndex: previous.pageIndex,\n      });\n    }\n    if (previous.viewport !== next.viewport) viewportChanged.emit({ size: next.viewport });\n    const changedKeys = SETTING_KEYS.filter((key) => !eqSetting(previous[key], next[key]));\n    if (changedKeys.length) settingsChanged.emit({ settings: pickSettings(next), changedKeys });\n  });\n\n  return { pageChanged, zoomChanged, cameraChanged, motionEnded, settingsChanged, viewportChanged };\n}\nexport type StageEvents = ReturnType<typeof createEvents>;\n","/**\n * The scene model: the document's item grouping, the layout, the memoized\n * scene (continuous flow lays out the whole document; paged flow a one-item\n * slice at the origin), and the pure geometry reads every area builds on:\n * fit, alignment points, clamp bounds and anchors. Reads only; nothing here\n * changes state.\n */\nimport {\n  anchorFromCamera,\n  clampZoom,\n  gridLayout,\n  groupPages,\n  linearLayout,\n  paddingSidesOf,\n  resolveZoomLimits,\n  ZoomMode,\n  type AlignmentValue,\n  type AlignValue,\n  type Anchor,\n  type CameraConstraint,\n  type PaddingSides,\n  type PageFrame,\n  type Point,\n  type Rect as StageRect,\n  type Scene,\n  type SceneItem,\n  type Size,\n  type ZoomLimits,\n} from '@embedpdf/core-stage';\nimport { addRotations, applyRect, displaySize, rotateScaleMatrix } from '@embedpdf/core-geometry';\nimport type { Rect } from '@embedpdf/core-geometry';\nimport { memo, type PluginContext, type PageRef } from '@embedpdf/core';\n\nimport type { StageSettings } from '../contract';\nimport type { StageModel } from '../model';\nimport { SETTINGS_EFFECT, SETTING_KEYS } from '../settings';\n\nexport function createScene(ctx: PluginContext<StageModel>) {\n  const state = () => ctx.state.get();\n  const camera = () => state().camera;\n  const viewport = () => state().viewport;\n  const dpr = () => state().dpr;\n  /** The padding, side by side (screen px). */\n  const padding = (): PaddingSides => paddingSidesOf(state().padding);\n  /** The `minZoom`/`maxZoom` range every zoom this view chooses is clamped into. */\n  const zoomLimits = (): ZoomLimits => resolveZoomLimits(state().minZoom, state().maxZoom);\n  const paged = () => state().flow === 'paged';\n  const isFitAll = () => {\n    const zoom = state().zoom;\n    return 'mode' in zoom && zoom.mode === ZoomMode.FitAll;\n  };\n\n  // The document's item model (spread grouping) is independent of the\n  // rendered scene, so navigation can reason about every item while a paged\n  // scene holds only one. The cursor is a page; `itemIndexOfPage` maps it,\n  // which survives regrouping.\n  const grouping = memo(\n    () => [ctx.document()?.pageCount ?? 0, state().spread] as const,\n    (pageCount, spread): { grouping: number[][]; firstPages: number[] } => {\n      const groups = groupPages(pageCount, spread);\n      return { grouping: groups, firstPages: groups.map((item) => item[0]) };\n    },\n  );\n  const itemCountFull = (): number => grouping().grouping.length;\n  const itemIndexOfPage = (pageIndex: number): number => {\n    const firstPages = grouping().firstPages;\n    let low = 0;\n    let high = firstPages.length;\n    while (low < high) {\n      const middle = (low + high) >> 1;\n      if (firstPages[middle] <= pageIndex) low = middle + 1;\n      else high = middle;\n    }\n    return Math.max(0, low - 1);\n  };\n\n  // The zoom that converts screen-px settings into world units. A fixed zoom\n  // intent gives an exact, stable value (the thumbnail case); other intents\n  // use the camera's current zoom, which `stabilized` converges. Screen-px\n  // settings (the wrapped line width, pageFrame, `{ px }` gaps) are the only\n  // way a scene depends on the viewport or the zoom.\n  const effectiveZoom = (): number => {\n    const zoom = state().zoom;\n    return 'level' in zoom\n      ? clampZoom(zoom.level, zoomLimits())\n      : Math.max(state().camera.zoom, 0.0001);\n  };\n\n  // Wrapped grid: the line width (world units) the columns must fit.\n  const wrapLineWidth = (): number => {\n    const { left, right } = padding();\n    return Math.max(1, (viewport().width - left - right) / effectiveZoom());\n  };\n\n  // pageFrame (screen px) → world units at the effective zoom.\n  const worldPageFrame = (): PageFrame => {\n    const frame = state().pageFrame;\n    if (!frame.top && !frame.right && !frame.bottom && !frame.left) return frame;\n    const zoom = effectiveZoom();\n    return {\n      top: frame.top / zoom,\n      right: frame.right / zoom,\n      bottom: frame.bottom / zoom,\n      left: frame.left / zoom,\n    };\n  };\n  const frameKey = (): string => {\n    const frame = state().pageFrame;\n    if (!frame.top && !frame.right && !frame.bottom && !frame.left) return '-';\n    const world = worldPageFrame();\n    return `${Math.round(world.top)},${Math.round(world.right)},${Math.round(world.bottom)},${Math.round(world.left)}`;\n  };\n\n  // gap → world units. A plain number is world units (the scene stays\n  // zoom-invariant, the rigid-canvas default); `{ px }` converts at the\n  // effective zoom like pageFrame (UI-stable spacing for browser-style lenses).\n  const worldGap = (): number => {\n    const gap = state().gap;\n    return typeof gap === 'number' ? gap : gap.px ? gap.px / effectiveZoom() : 0;\n  };\n  const gapKey = (): string => {\n    const gap = state().gap;\n    return typeof gap === 'number' ? String(gap) : `px:${Math.round(worldGap())}`;\n  };\n\n  const layoutFor = (groups: number[][]): Scene => {\n    const settings = state();\n    // Engine page layouts structurally satisfy stage-core's page geometry\n    // (`size` + `rotation`): the intrinsic page size flows straight in.\n    //\n    // The view rotation is composed here, and only here: each page's display\n    // rotation is its /Rotate plus this lens's viewRotation. Everything\n    // downstream (the display-size swap, the page transform, hit-testing, fit\n    // zoom, overlays) reads the composed rotation. `size` stays the page's\n    // own un-rotated points, so page space is view-rotation-invariant.\n    const registryPages = ctx.document()?.pages ?? [];\n    const viewRotation = settings.viewRotation;\n    const pages =\n      viewRotation === 0\n        ? registryPages\n        : registryPages.map((page) => ({\n            ...page,\n            rotation: addRotations(page.rotation, viewRotation),\n          }));\n    const pageFrame = worldPageFrame();\n    const gap = worldGap();\n    const viewUnitsPerPoint = settings.viewUnitsPerPoint;\n    if (settings.layout === 'grid') {\n      return gridLayout(pages, groups, {\n        gap,\n        sizing: settings.sizing,\n        direction: settings.direction,\n        pageFrame,\n        viewUnitsPerPoint,\n        columns: typeof settings.columns === 'number' ? settings.columns : undefined,\n        lineWidth: settings.columns === 'auto' ? wrapLineWidth() : undefined,\n      });\n    }\n    return linearLayout(pages, groups, {\n      axis: settings.layout === 'horizontal' ? 'x' : 'y',\n      gap,\n      sizing: settings.sizing,\n      direction: settings.direction,\n      pageFrame,\n      viewUnitsPerPoint,\n    });\n  };\n\n  // The column policy's part of the scene key; 'auto' quantizes the line\n  // width so sub-pixel resizes do not rebuild the scene.\n  const columnsKey = (): string => {\n    const settings = state();\n    if (settings.layout !== 'grid') return '-';\n    return settings.columns === 'auto'\n      ? `auto:${Math.round(wrapLineWidth())}`\n      : String(settings.columns);\n  };\n\n  // The scene's settings signature, derived from the settings registry: every\n  // 'scene' setting contributes automatically, so a new layout-affecting\n  // setting only needs its SETTINGS_EFFECT row and a stale scene cannot be\n  // forgotten here. Values key by value (objects via JSON); the custom\n  // functions quantize px-derived values so sub-pixel zoom and resize churn\n  // does not rebuild the scene.\n  const SCENE_KEY_FUNCTIONS: Partial<Record<keyof StageSettings, () => string>> = {\n    columns: columnsKey,\n    gap: gapKey,\n    pageFrame: frameKey,\n  };\n  const SCENE_KEYS = SETTING_KEYS.filter((key) => SETTINGS_EFFECT[key] === 'scene');\n  const settingsKey = (): string =>\n    SCENE_KEYS.map((key) => {\n      const keyFunction = SCENE_KEY_FUNCTIONS[key];\n      if (keyFunction) return keyFunction();\n      const value = state()[key];\n      return typeof value === 'object' && value !== null ? JSON.stringify(value) : String(value);\n    }).join('|');\n\n  // The scene cache. Continuous flow lays out the whole document. Paged flow\n  // is a one-item slice at the origin holding only the cursor's item, so\n  // isolation is structural (no other page exists to leak into view),\n  // unbounded pan is free, and coordinates stay local.\n  let sceneCache: { key: string; scene: Scene } | null = null;\n  // The registry signature: page count plus the kernel's monotonic\n  // `pagesSequence`. It changes on every page mutation (rotate, move,\n  // delete), so a change that keeps the page count (a rotation) still re-keys\n  // the scene instead of rendering the page in its stale box.\n  const documentKey = (): string => {\n    const document = ctx.document();\n    return document ? `${document.pageCount}.${document.pagesSequence}` : '0.0';\n  };\n  const buildScene = (): Scene => {\n    const { grouping: groups } = grouping();\n    if (state().flow === 'paged') {\n      const index = groups.length\n        ? Math.min(itemIndexOfPage(state().pageIndex), groups.length - 1)\n        : 0;\n      const key = `paged|${documentKey()}|${settingsKey()}|${index}`;\n      if (sceneCache && sceneCache.key === key) return sceneCache.scene;\n      const scene = layoutFor(groups.length ? [groups[index]] : []);\n      sceneCache = { key, scene };\n      return scene;\n    }\n    const key = `continuous|${documentKey()}|${settingsKey()}`;\n    if (sceneCache && sceneCache.key === key) return sceneCache.scene;\n    const scene = layoutFor(groups);\n    sceneCache = { key, scene };\n    return scene;\n  };\n  /** Drop the memoized scene (a 'scene' or 'reflow' setting changed, or a view was restored). */\n  const invalidate = (): void => {\n    sceneCache = null;\n  };\n  /** The current scene's cache key, part of the visible-pages signature. */\n  const cacheKey = (): string => sceneCache!.key;\n\n  // ── geometry helpers ──\n  const sceneRect = (): StageRect => {\n    const { width, height } = buildScene().size;\n    return { x: 0, y: 0, width, height };\n  };\n  const itemRect = (item: SceneItem): StageRect => ({\n    x: item.x,\n    y: item.y,\n    width: item.width,\n    height: item.height,\n  });\n  const pageRectOf = (item: SceneItem, pageIndex: number): StageRect => {\n    const box = item.pages.find((page) => page.pageIndex === pageIndex) ?? item.pages[0];\n    return { x: box.x, y: box.y, width: box.width, height: box.height };\n  };\n  /** The item shown for the cursor: the slice's only item (paged) or the full-scene item. */\n  const cursorItem = (): SceneItem => {\n    const scene = buildScene();\n    return paged() ? scene.items[0] : scene.items[itemIndexOfPage(state().pageIndex)];\n  };\n\n  /** Whether an item is one navigation unit now: it fits across the view, or fit-all shows all. */\n  const isWhole = (item: SceneItem): boolean =>\n    isFitAll() || fitsAcross(itemRect(item), camera().zoom);\n\n  /**\n   * The pages you're on, the navigation unit: the cursor's item while it is\n   * whole (a spread you see side by side), else the cursor page alone. The\n   * page number names them, and nextPage and previousPage step past them.\n   */\n  const currentPages = (): readonly number[] => {\n    const item = cursorItem();\n    if (!item) return [];\n    return isWhole(item) ? item.pageIndexes : [state().pageIndex];\n  };\n\n  /**\n   * Where the unit that holds `pageIndex` starts: its item's first page while\n   * that item is whole, else the page itself. A paged scene holds only the\n   * cursor's item, so there it measures that one.\n   */\n  const unitStartOf = (pageIndex: number): number => {\n    const group = grouping().grouping[itemIndexOfPage(pageIndex)];\n    if (!group || group.length === 1) return pageIndex;\n    const scene = buildScene();\n    const item = paged() ? scene.items[0] : scene.items[itemIndexOfPage(pageIndex)];\n    return item && isWhole(item) ? group[0] : pageIndex;\n  };\n\n  /**\n   * A page-space rect on a page → a world rect: the same quarter-turn\n   * matrix `pageRectToViewport` uses, minus the camera, so a positioned\n   * reveal and the rendered overlay never disagree about where a rect is.\n   */\n  const worldRectForContent = (item: SceneItem, pageIndex: number, rect: Rect): StageRect => {\n    const box = item.pages.find((page) => page.pageIndex === pageIndex) ?? item.pages[0];\n    const content = displaySize({ width: box.width, height: box.height }, box.rotation);\n    const matrix = rotateScaleMatrix(box.contentScale, content.width, content.height, box.rotation);\n    const world = applyRect(matrix, rect);\n    return { x: box.x + world.x, y: box.y + world.y, width: world.width, height: world.height };\n  };\n\n  // Does this rect fit across the padded viewport at this zoom: its width, the\n  // axis an item's pages sit side by side on? An item that fits across is seen\n  // whole, however tall it is, the way a tall page is still one page. It\n  // decides the navigation unit and the arrival subject, never the alignment.\n  const fitsAcross = (rect: StageRect, zoom: number): boolean => {\n    const size = viewport();\n    const inset = padding();\n    return rect.width * zoom <= size.width - inset.left - inset.right + 0.5;\n  };\n  // An alignment policy → a concrete viewport point: a fraction per axis\n  // (start = 0, center = ½, end = 1; named x stops are logical under RTL).\n  // zoomAlign and anchorAlign both resolve through this. The fraction spans\n  // the padded range: 'start' is the first visible content line just inside\n  // the gutter, where an arrival puts the page edge, so the reference pins\n  // to the page and never to the gap above it.\n  const alignFraction = (value: AlignValue): number =>\n    value === 'start'\n      ? 0\n      : value === 'center'\n        ? 0.5\n        : value === 'end'\n          ? 1\n          : Math.min(1, Math.max(0, value));\n  const alignPoint = (alignment: AlignmentValue, size: Size): Point => {\n    const rtl = state().direction === 'rtl';\n    const alignX =\n      rtl && alignment.x === 'start' ? 'end' : rtl && alignment.x === 'end' ? 'start' : alignment.x;\n    const inset = padding();\n    return {\n      x: inset.left + (size.width - inset.left - inset.right) * alignFraction(alignX),\n      y: inset.top + (size.height - inset.top - inset.bottom) * alignFraction(alignment.y),\n    };\n  };\n  const anchorPoint = (): Point => alignPoint(state().anchorAlign, viewport());\n\n  /** The box the zoom intent fits: the whole scene (fit-all), the current\n   *  item (paged: per-page fit), or the document maximum (continuous: a\n   *  document-stable zoom). */\n  const fitBox = (item: SceneItem): Size => {\n    if (isFitAll()) return buildScene().size;\n    return paged() ? { width: item.width, height: item.height } : buildScene().maxItemSize;\n  };\n  /** The clamp rect for a camera write targeting this item (the scene in continuous flow). */\n  const boundsFor = (item: SceneItem): StageRect => (paged() ? itemRect(item) : sceneRect());\n  /** The clamp rect for a write that stays put (pan, zoom): the slice item (paged) or the scene. */\n  const stayBounds = (): StageRect => (paged() ? itemRect(buildScene().items[0]) : sceneRect());\n\n  const constraint = (): CameraConstraint => ({\n    bounded: state().bounded,\n    padding: padding(),\n    fitAlign: state().fitAlign,\n    direction: state().direction,\n  });\n\n  const anchorAt = (at: Point): Anchor => {\n    const scene = buildScene();\n    return scene.itemCount\n      ? anchorFromCamera(camera(), scene, viewport(), at)\n      : { pageIndex: state().pageIndex, fractionX: 0.5, fractionY: 0 };\n  };\n  const currentAnchor = (): Anchor => anchorAt(anchorPoint());\n\n  const indexOfPage = (page: PageRef): number => ctx.getPage(page)?.index ?? -1;\n  /**\n   * A page argument (a `PageRef` or a display index) as a display index, or\n   * null when it names no page: a ref not in the document, or a number that\n   * isn't a whole number. An index past either end is kept; arrivals clamp it.\n   */\n  const indexOfTarget = (page: PageRef | number): number | null => {\n    if (typeof page === 'number') return Number.isInteger(page) ? page : null;\n    const index = indexOfPage(page);\n    return index >= 0 ? index : null;\n  };\n\n  return {\n    camera,\n    viewport,\n    dpr,\n    padding,\n    zoomLimits,\n    paged,\n    isFitAll,\n    grouping,\n    itemCountFull,\n    itemIndexOfPage,\n    worldPageFrame,\n    buildScene,\n    invalidate,\n    cacheKey,\n    sceneRect,\n    itemRect,\n    pageRectOf,\n    cursorItem,\n    currentPages,\n    unitStartOf,\n    worldRectForContent,\n    fitsAcross,\n    alignPoint,\n    anchorPoint,\n    fitBox,\n    boundsFor,\n    stayBounds,\n    constraint,\n    anchorAt,\n    currentAnchor,\n    indexOfPage,\n    indexOfTarget,\n  };\n}\nexport type StageScene = ReturnType<typeof createScene>;\n","/**\n * Plugin-private services every area is built on: the events, the host's\n * clock, the placement latch and the scene model.\n */\nimport type { PluginClock, PluginContext } from '@embedpdf/core';\n\nimport type { StageModel } from '../model';\nimport { createEvents, type StageEvents } from './events';\nimport { createPlacementLatch, type PlacementLatch } from './placement-latch';\nimport { createScene, type StageScene } from './scene';\n\nexport interface StageServices {\n  readonly events: StageEvents;\n  /** Time, from the host (`ctx.clock`): the tweens, flings and the rest countdown run on it. */\n  readonly clock: PluginClock;\n  readonly placement: PlacementLatch;\n  readonly scene: StageScene;\n}\n\nexport function createServices(ctx: PluginContext<StageModel>): StageServices {\n  return {\n    events: createEvents(ctx),\n    clock: ctx.clock,\n    placement: createPlacementLatch(),\n    scene: createScene(ctx),\n  };\n}\n","/**\n * The settings bag and its resolution. The base (config plus `updateSettings()`\n * changes), then the matching rules' patches, then the locks, is the effective\n * settings the state holds. `applySettings` is the one reactive applier: the\n * strongest effect among the touched settings wins ('reflow' ⊃ 'scene'/'refit'\n * ⊃ 'reclamp' ⊃ 'none'), so a breakpoint crossing gets exactly the invariant a\n * hand-written update would.\n */\nimport { memo, PluginError, type PluginContext, type SettingLock } from '@embedpdf/core';\n\nimport type {\n  ResponsiveRule,\n  StageConfig,\n  StageSettings,\n  StageSettingsLock,\n  StageSettingsPatch,\n  StageViewState,\n} from '../contract';\nimport type { StageAnimation } from '../camera/animation';\nimport type { StageCameraWrite } from '../camera/write';\nimport type { StageHostCapability } from '../host-contract';\nimport {\n  patchSettings,\n  setActiveRules,\n  setCursor,\n  setLocks,\n  type StageLocks,\n  type StageModel,\n} from '../model';\nimport type { StageArrival } from '../navigation/arrive';\nimport { boxOf, eqSetting, mergeSettings, resolveResponsive } from '../responsive';\nimport type { StageServices } from '../services';\nimport { DEFAULT_RESPONSIVE, pickSettings, SETTINGS_EFFECT, SETTING_KEYS } from '../settings';\nimport type { SettingEffect } from '../settings';\n\nconst EFFECT_RANK: Record<SettingEffect, number> = {\n  none: 0,\n  reclamp: 1,\n  refit: 2,\n  scene: 3,\n  reflow: 4,\n};\n\nexport function createSettings(\n  ctx: PluginContext<StageModel>,\n  { scene }: Pick<StageServices, 'scene'>,\n  config: StageConfig,\n  { writeCamera }: Pick<StageCameraWrite, 'writeCamera'>,\n  { cancelAnimation }: Pick<StageAnimation, 'cancelAnimation'>,\n  {\n    applyAnchor,\n    reapply,\n    goToTarget,\n  }: Pick<StageArrival, 'applyAnchor' | 'reapply' | 'goToTarget'>,\n) {\n  const { camera, viewport, alignPoint, anchorAt } = scene;\n  const state = () => ctx.state.get();\n\n  // The same object while no setting changed, so readers compare by identity.\n  const snapshotSettings: () => StageSettings = memo(\n    () => SETTING_KEYS.map((key) => state()[key]),\n    () => pickSettings(state()),\n  );\n\n  /**\n   * React to a settings change per the registry: the strongest effect among\n   * the touched settings wins. Both the public `updateSettings()` and the\n   * responsive driver land here.\n   */\n  const applySettings = (patch: Partial<StageSettings>) => {\n    cancelAnimation();\n    const touched = (effect: SettingEffect) =>\n      SETTING_KEYS.some((key) => patch[key] !== undefined && SETTINGS_EFFECT[key] === effect);\n    // The change's invariant point: a pure zoom-intent change ('refit' alone)\n    // holds the zoomAlign focal point, so zoomTo and fit-mode switches magnify\n    // around the same spot the zoom buttons do; every other reframe holds the\n    // anchorAlign reference. Resolved once, used for capture and restore.\n    const align =\n      touched('refit') && !touched('scene') && !touched('reflow')\n        ? state().zoomAlign\n        : state().anchorAlign;\n    const anchor = anchorAt(alignPoint(align, viewport())); // captured against the current scene\n    ctx.state.update(patchSettings, patch);\n    if (touched('scene')) scene.invalidate();\n    if (touched('reflow')) {\n      // The flow toggled: re-place onto the cursor's page under the new\n      // flow's scene (camera coordinates are meaningless across the flow\n      // boundary).\n      goToTarget(state().pageIndex, { behavior: 'instant' });\n    } else if (touched('scene') || touched('refit')) {\n      reapply(anchor, align); // rebuild, keep the page, re-fit (fit-all re-places the scene)\n    } else if (touched('reclamp')) {\n      writeCamera(camera()); // the clamp policy changed: re-clamp the current camera\n    }\n    // 'none' (arrivalAlign, zoomAlign, anchorAlign, scrollBehavior) guides future verbs only.\n  };\n\n  // ── responsive settings (container queries for the settings bag) ──\n  // Rules assert at transitions (box, base or rules changes), which is why\n  // the sync diffs against the last effective resolution, never against live\n  // state: between crossings interaction owns the state (a pinch-zoomed level\n  // survives a resize unless a rule actually flips), and keys the rules do\n  // not touch are never re-asserted.\n  let base = snapshotSettings();\n  const initialBase = base;\n  let rules: readonly ResponsiveRule[] = config.responsive ?? DEFAULT_RESPONSIVE;\n  let lastEffective = base; // rules first assert when a real box arrives\n  // The locks, in the order they were taken: the last layer, over the base and the rules.\n  let locks: readonly StageSettingsLock[] = [];\n  /** Base, then the matching rules, then the locks: what the state holds. */\n  const resolve = () => {\n    const { effective, active } = resolveResponsive(base, rules, boxOf(viewport()));\n    return {\n      effective: locks.reduce(\n        (settings, lock) => mergeSettings(settings, lock.settings),\n        effective,\n      ),\n      active,\n    };\n  };\n  /** Who holds each locked setting, in state: the first lock that names it. */\n  const publishLocks = () => {\n    const holders: Partial<Record<keyof StageSettings, SettingLock>> = {};\n    for (const lock of locks) {\n      for (const key of lockedKeys(lock)) {\n        holders[key] ??= {\n          by: lock.by,\n          ...(lock.reasonKey !== undefined ? { reasonKey: lock.reasonKey } : {}),\n        };\n      }\n    }\n    const current = state().locks;\n    const keys = Object.keys(holders) as (keyof StageSettings)[];\n    const same =\n      keys.length === Object.keys(current).length &&\n      keys.every(\n        (key) =>\n          current[key]?.by === holders[key]!.by &&\n          current[key]?.reasonKey === holders[key]!.reasonKey,\n      );\n    if (!same) ctx.state.update(setLocks, holders as StageLocks);\n  };\n  const publishActive = (active: readonly string[]) => {\n    const current = state().activeRules;\n    if (current.length !== active.length || active.some((name, index) => name !== current[index])) {\n      ctx.state.update(setActiveRules, active);\n    }\n  };\n  /**\n   * Re-resolve and apply what changed since the last resolution. `react:\n   * true` routes the patch through `applySettings` (the full\n   * anchor-preserving update); `react: false` (inside `setViewportSize`,\n   * whose caller runs its own reframe) only lands the patch and the cache\n   * invalidation and reports the strongest effect, so the caller can\n   * escalate a rule-driven flow flip.\n   *\n   * `asked` names the settings a caller just set. Each of them lands whenever\n   * the live value differs, even if the resolution itself didn't move: a zoom\n   * step, a pinch or a zoom box records its level straight into the state, so\n   * the resolution can still hold the fit mode the user now asks for again.\n   */\n  const syncResponsive = (\n    react: boolean,\n    asked: readonly (keyof StageSettings)[] = [],\n  ): SettingEffect => {\n    const { effective, active } = resolve();\n    const patch: Partial<StageSettings> = {};\n    for (const key of SETTING_KEYS) {\n      const resolved = !eqSetting(effective[key], lastEffective[key]);\n      const reasserted = asked.includes(key) && !eqSetting(effective[key], state()[key]);\n      if (resolved || reasserted) Object.assign(patch, { [key]: effective[key] });\n    }\n    lastEffective = effective;\n    publishActive(active);\n    const keys = Object.keys(patch) as Array<keyof StageSettings>;\n    if (keys.length === 0) return 'none';\n    if (react) {\n      applySettings(patch);\n      return 'none'; // reacted in full: nothing left for the caller\n    }\n    ctx.state.update(patchSettings, patch);\n    let strongest: SettingEffect = 'none';\n    for (const key of keys) {\n      if (EFFECT_RANK[SETTINGS_EFFECT[key]] > EFFECT_RANK[strongest]) {\n        strongest = SETTINGS_EFFECT[key];\n      }\n    }\n    if (strongest === 'scene' || strongest === 'reflow') scene.invalidate();\n    return strongest;\n  };\n\n  const updateSettings = (changes: StageSettingsPatch): void => {\n    // Writes the responsive base; the resolver decides what actually lands (a\n    // matching rule's key wins until its rule stops matching). With no rules\n    // in play this is a direct update.\n    base = mergeSettings(base, changes);\n    syncResponsive(\n      true,\n      SETTING_KEYS.filter((key) => changes[key] !== undefined),\n    );\n  };\n\n  const applyViewState = (view: StageViewState): void => {\n    cancelAnimation();\n    // A restored view is app-level state: it writes the base, and the rules\n    // re-assert on top, so a snapshot saved on a desktop restores compact\n    // padding on a phone. One patch carries the full effective result.\n    base = mergeSettings(base, pickSettings(view));\n    const { effective, active } = resolve();\n    lastEffective = effective;\n    publishActive(active);\n    ctx.state.update(patchSettings, effective);\n    ctx.state.update(setCursor, view.pageIndex ?? 0);\n    scene.invalidate();\n    applyAnchor(view.anchor);\n  };\n\n  /**\n   * The settings a saved view keeps: what shows, but the locked ones as they\n   * are underneath, so restoring it never writes a lock's value as the user's.\n   */\n  const viewStateSettings = (): StageSettings => {\n    const shown = snapshotSettings();\n    if (locks.length === 0) return shown;\n    const { effective: unlocked } = resolveResponsive(base, rules, boxOf(viewport()));\n    const settings = { ...shown };\n    for (const key of Object.keys(state().locks) as (keyof StageSettings)[]) {\n      Object.assign(settings, { [key]: unlocked[key] });\n    }\n    return settings;\n  };\n\n  /**\n   * Hold `lock.settings` over every other writer until the returned function\n   * runs, or the document closes. A setting another lock holds at a different\n   * value is refused.\n   */\n  const lockSettings = (lock: StageSettingsLock): (() => void) => {\n    const keys = lockedKeys(lock);\n    for (const key of keys) {\n      if (!SETTING_KEYS.includes(key)) {\n        throw new PluginError('invalid-input', 'stage', `\"${key}\" is not a Stage setting`);\n      }\n      if (key === 'zoom') {\n        throw new PluginError(\n          'invalid-input',\n          'stage',\n          'the zoom cannot be locked: gestures set it',\n        );\n      }\n      const holder = locks.find((held) => {\n        const value = held.settings[key as keyof StageSettingsLock['settings']];\n        return (\n          value !== undefined && !eqSetting(value, lock.settings[key as keyof typeof lock.settings])\n        );\n      });\n      if (holder) {\n        throw new PluginError(\n          'conflict',\n          'stage',\n          `\"${key}\" is locked by ${holder.by} at another value`,\n        );\n      }\n    }\n    const held: StageSettingsLock = { ...lock, settings: { ...lock.settings } };\n    locks = [...locks, held];\n    publishLocks();\n    syncResponsive(true, keys);\n    let released = false;\n    return () => {\n      if (released) return;\n      released = true;\n      locks = locks.filter((other) => other !== held);\n      publishLocks();\n      syncResponsive(true, keys);\n    };\n  };\n\n  return {\n    snapshotSettings,\n    viewStateSettings,\n    syncResponsive,\n    updateSettings,\n    applyViewState,\n    api: {\n      getSettings: snapshotSettings,\n      resetSettings: () => {\n        base = mergeSettings(initialBase, {});\n        syncResponsive(true, SETTING_KEYS);\n      },\n      updateSettings,\n      setResponsiveRules: (next) => {\n        rules = next;\n        syncResponsive(true);\n      },\n      lockSettings,\n      getLock: (setting) => state().locks[setting] ?? null,\n      matchesRule: (name) => state().activeRules.includes(name),\n      listActiveRules: () => state().activeRules,\n      applyViewState,\n    } satisfies Partial<StageHostCapability>,\n  };\n}\nexport type StageSettingsArea = ReturnType<typeof createSettings>;\n\n/** The settings a lock names a value for. */\nconst lockedKeys = (lock: StageSettingsLock): (keyof StageSettings)[] =>\n  (Object.keys(lock.settings) as (keyof StageSettings)[]).filter(\n    (key) => lock.settings[key as keyof StageSettingsLock['settings']] !== undefined,\n  );\n","/**\n * The view lifecycle: the viewport report (initial placement is\n * level-triggered here, the moment the stage first learns a real size and the\n * document has pages), the device pixel ratio, initial-view providers resolved\n * once by priority, the refit after page-registry changes, and the view\n * memento reads.\n */\nimport type { PluginContext } from '@embedpdf/core';\n\nimport type { StageViewState } from '../contract';\nimport type { StageAnimation } from '../camera/animation';\nimport type { StageHostCapability } from '../host-contract';\nimport { markPlaced, setDpr, setViewport, type StageModel } from '../model';\nimport type { StageArrival } from '../navigation/arrive';\nimport type { StageServices } from '../services';\nimport type { StageSettingsArea } from '../settings/settings';\n\ninterface InitialViewProvider {\n  readonly priority: number;\n  readonly provide: () => StageViewState | null;\n}\n\nexport function createViewLifecycle(\n  ctx: PluginContext<StageModel>,\n  { scene, placement }: Pick<StageServices, 'scene' | 'placement'>,\n  { cancelAnimation }: Pick<StageAnimation, 'cancelAnimation'>,\n  arrive: Pick<StageArrival, 'goToTarget' | 'reapply' | 'resetView'>,\n  settings: Pick<\n    StageSettingsArea,\n    'snapshotSettings' | 'viewStateSettings' | 'syncResponsive' | 'applyViewState'\n  >,\n) {\n  const { dpr, currentAnchor } = scene;\n  const { goToTarget, reapply } = arrive;\n  const { snapshotSettings, viewStateSettings, syncResponsive } = settings;\n  const state = () => ctx.state.get();\n\n  // Initial-view providers (a storage restore, a deep link, an explicit\n  // prop). One owner, `placeInitial`, resolves them by priority, so there is\n  // no ordering race between the providers.\n  const initialViewProviders: InitialViewProvider[] = [];\n\n  const placeInitial = (): void => {\n    placement.started = true;\n    const byPriority = [...initialViewProviders].sort(\n      (left, right) => right.priority - left.priority,\n    );\n    let view: StageViewState | null = null;\n    for (const provider of byPriority) {\n      view = provider.provide();\n      if (view) break;\n    }\n    if (view) settings.applyViewState(view);\n    else arrive.resetView();\n    // Navigation the app asked for before there was a viewport lands last,\n    // from the initial view, so the first frame already shows it.\n    const pending = placement.pending;\n    placement.pending = null;\n    pending?.();\n    // Publish renderability last. The viewport, responsive and camera writes\n    // above are ordinary observable state changes, but page and scroll reads\n    // return stable empty values until this commit lands.\n    ctx.state.update(markPlaced);\n  };\n\n  return {\n    api: {\n      setViewportSize: (size) => {\n        // Initial placement is level-triggered here: the moment the stage\n        // first learns a real size (both axes) and the document has pages,\n        // resolve the initial view (providers, else a reset). Every report\n        // re-checks the condition, so there is no edge to miss when the\n        // viewport was sized before anyone listened.\n        if (!placement.started) {\n          ctx.state.update(setViewport, size);\n          syncResponsive(false); // rules see the box before placement resolves\n          if (size.width > 0 && size.height > 0 && (ctx.document()?.pageCount ?? 0) > 0) {\n            placeInitial();\n          }\n          return;\n        }\n        // Afterwards a report with no area means the view isn't shown: a hidden tab, or an\n        // element taken out of the page before its stage is torn down. There is nothing to fit\n        // to, so the stage keeps its last real viewport and its view, and carries on from them\n        // when it's shown again (as a browser keeps a hidden element's scroll position).\n        if (size.width <= 0 || size.height <= 0) return;\n        // A report of the size the stage already has says nothing new either. Hosts send\n        // them (a ResizeObserver's first callback repeats the size reported at attach), and\n        // treating one as a resize would cancel a navigation still animating, like a reveal\n        // the app asked for as the view opened.\n        const current = state().viewport;\n        if (size.width === current.width && size.height === current.height) return;\n        // Every real resize keeps the same page and re-resolves fit modes.\n        cancelAnimation();\n        const anchor = currentAnchor(); // measured against the old viewport\n        ctx.state.update(setViewport, size);\n        // A breakpoint crossing rides the same reframe: the rule patch lands\n        // before the anchor is re-applied, so the restore resolves under the\n        // new settings. Only a rule-driven flow flip escalates past reapply\n        // (camera coordinates are meaningless across the flow boundary).\n        const effect = syncResponsive(false);\n        if (effect === 'reflow') {\n          goToTarget(state().pageIndex, { behavior: 'instant' });\n        } else {\n          reapply(anchor);\n        }\n      },\n      setDevicePixelRatio: (ratio) => {\n        // A device-resolution change only affects each page transform's device\n        // px (crispness) and sub-pixel box snapping, never the layout or the\n        // camera: store it, and the visible pages re-key on dpr.\n        if (ratio > 0 && ratio !== dpr()) ctx.state.update(setDpr, ratio);\n      },\n      refit: () => {\n        // The page geometry changed underneath (rotate, move, delete). Treat\n        // it like a viewport resize: re-resolve the zoom intent and re-place\n        // against the current scene, keeping the anchored page-point. A no-op\n        // before the first placement; the scene is keyed on the registry\n        // revision, so `reapply` reads the new footprint.\n        if (!placement.started) return;\n        cancelAnimation();\n        reapply(currentAnchor());\n      },\n      getViewState: (): StageViewState => ({\n        // A lock is this document's now, not the user's: the saved view keeps what's under it.\n        ...viewStateSettings(),\n        pageIndex: state().pageIndex,\n        anchor: currentAnchor(),\n      }),\n      getLensId: () => ctx.id,\n      provideInitialView: (priority, provide) => {\n        const entry: InitialViewProvider = { priority, provide };\n        initialViewProviders.push(entry);\n        return () => {\n          const index = initialViewProviders.indexOf(entry);\n          if (index >= 0) initialViewProviders.splice(index, 1);\n        };\n      },\n      placeInitial,\n    } satisfies Partial<StageHostCapability>,\n  };\n}\n","/**\n * The stage controller: the composition root. It builds the plugin's services\n * once (the events, the timing seam, the scene model), wires each area with\n * the services it declares, and assembles the host capability from the areas'\n * API slices. stage-core is the pure spatial math; the areas are the impure\n * shell that writes state, caches and drives motion, and time enters only\n * through the host's clock (`ctx.clock`).\n *\n * The camera model: every camera move is defined by what it holds fixed.\n * Gestures (pan, pinch, wheel) hold the page-point under the pointer;\n * navigation lands its target at the arrivalAlign point; positioned reveals\n * and restored viewpoints hold what the call specifies; pointer-less zooms\n * hold the zoomAlign point; reframes (resize, rotation, layout changes) hold\n * the anchorAlign point; and an axis the camera cannot travel rests at fitAlign.\n */\nimport { composeApi, type PluginContext } from '@embedpdf/core';\n\nimport { createAnimation } from './camera/animation';\nimport { createGestures } from './camera/gestures';\nimport { createWheel } from './camera/wheel';\nimport { createCameraWrite } from './camera/write';\nimport { connectStage } from './connect';\nimport type { StageConfig } from './contract';\nimport type { StageHostCapability } from './host-contract';\nimport type { StageModel } from './model';\nimport { createArrival } from './navigation/arrive';\nimport { createReveal } from './navigation/reveal';\nimport { createTurns } from './navigation/turn';\nimport { createZoom } from './navigation/zoom';\nimport { createZoomDrag } from './navigation/zoom-drag';\nimport { createPageReads } from './read/pages';\nimport { createServices } from './services';\nimport { createSettings } from './settings/settings';\nimport { createViewLifecycle } from './view/lifecycle';\n\nexport function createStageController(ctx: PluginContext<StageModel>, config: StageConfig = {}) {\n  const services = createServices(ctx);\n  const { events } = services;\n\n  // Reads: pure projections of the scene and the camera.\n  const reads = createPageReads(ctx, services);\n\n  // The camera: the one write path and motion over the clock's frames.\n  const write = createCameraWrite(ctx, services);\n  const animation = createAnimation(services, write);\n\n  // Navigation, then gestures: a push past a paged view's edge turns the page,\n  // and a wheel with nowhere to go is left to the page around the viewer.\n  const arrive = createArrival(ctx, services, write, animation);\n  const turns = createTurns(ctx, services, reads, arrive.api);\n  const gestures = createGestures(ctx, services, write, animation, reads, turns);\n  const wheel = createWheel(ctx, services, turns, gestures.api);\n\n  // Settings, zoom and the view lifecycle.\n  const reveal = createReveal(ctx, services, write, animation, arrive);\n  const settings = createSettings(ctx, services, config, write, animation, arrive);\n  const zoom = createZoom(ctx, services, write, animation, gestures.api, settings);\n  const zoomDrag = createZoomDrag(ctx, services, write, animation, { ...reads.api, ...zoom.api });\n  const view = createViewLifecycle(ctx, services, animation, arrive, settings);\n\n  const api: StageHostCapability = composeApi('stage', [\n    reads.api,\n    animation.api,\n    gestures.api,\n    wheel.api,\n    arrive.api,\n    reveal.api,\n    settings.api,\n    zoom.api,\n    zoomDrag.api,\n    view.api,\n    {\n      onPageChanged: events.pageChanged.on,\n      onZoomChanged: events.zoomChanged.on,\n      onCameraChanged: events.cameraChanged.on,\n      onMotionEnded: events.motionEnded.on,\n      onSettingsChanged: events.settingsChanged.on,\n      onViewportChanged: events.viewportChanged.on,\n    },\n  ]);\n\n  return {\n    api,\n    connect: () => connectStage(ctx, api),\n  };\n}\n","import { createHostToken, definePlugin } from '@embedpdf/core';\nimport { ActionsToken } from '@embedpdf/plugin-actions/contract';\n\nimport { DEFAULT_LENS_ID } from './connect';\nimport type { StagePluginOptions } from './contract';\nimport { createStageController } from './controller';\nimport type { StageHostCapability } from './host-contract';\nimport { initialStageModel } from './model';\nimport { StageToken } from './token';\n\n/**\n * The stage plugin: one lens's camera, layout, zoom and navigation over a\n * document. Document-scoped. The actions plugin is optional: with it, the\n * main lens feeds page state to it and interprets GoTo and Named page\n * actions. Pointer input is opted into by the surface binding\n * (`<Stage interaction>` / `createStageSurface`), which both forwards pointer\n * samples and registers this lens's scroll handler.\n */\nexport const stagePlugin = (options: StagePluginOptions = {}) => {\n  const { id = DEFAULT_LENS_ID, token = StageToken, ...config } = options;\n  return definePlugin({\n    id,\n    token: createHostToken<StageHostCapability>(token),\n    scope: 'document',\n    optional: [ActionsToken],\n    state: () => initialStageModel(config),\n    create: (ctx) => createStageController(ctx, config),\n  });\n};\n","/**\n * The Stage page's State table as code: what `useStageState()` returns, and\n * the same fields in every other framework. A second view registered with its\n * own token reads the same fields through its own capability.\n */\nimport { defineState, type PageRef } from '@embedpdf/core';\nimport type { Rotation } from '@embedpdf/core-geometry';\nimport type { ZoomModeValue } from '@embedpdf/core-stage';\n\nimport { StageToken, ZoomMode } from './contract';\n\n/** The zoom, the current page, how many pages, the view's rotation, and the responsive rules that match. */\nexport interface StageState {\n  /** The resolved zoom factor. */\n  readonly zoomLevel: number;\n  /** The zoom intent: a fit mode, or `'custom'` for a fixed level. */\n  readonly zoomMode: ZoomModeValue | 'custom';\n  /** The current page's display index, from 0. */\n  readonly currentPageIndex: number;\n  /** The current page, or `null` before the document has pages. */\n  readonly currentPage: PageRef | null;\n  /** How many pages the document has. */\n  readonly pageCount: number;\n  /** The view's clockwise rotation, on top of each page's own; never written to the document. */\n  readonly viewRotation: Rotation;\n  /** The names of the responsive rules matching the current box, in source order. */\n  readonly activeRules: readonly string[];\n}\n\nexport const stageState = defineState(StageToken, {\n  read: (stage): StageState => ({\n    zoomLevel: stage.getZoomLevel(),\n    zoomMode: stage.getZoomMode(),\n    currentPageIndex: stage.getCurrentPageIndex(),\n    currentPage: stage.getCurrentPage(),\n    pageCount: stage.getPageCount(),\n    viewRotation: stage.getViewRotation(),\n    activeRules: stage.listActiveRules(),\n  }),\n  empty: {\n    zoomLevel: 1,\n    zoomMode: ZoomMode.Automatic,\n    currentPageIndex: 0,\n    currentPage: null,\n    pageCount: 0,\n    viewRotation: 0,\n    activeRules: [],\n  },\n});\n","import type {\n  InteractionHostCapability,\n  InteractionHandler,\n} from '@embedpdf/plugin-interaction/contract/host';\nimport type { StageCapability } from './contract';\n\nexport interface ScrollHandlerOptions {\n  /**\n   * Let a drag over a page gap pan regardless of the active tool, and show a\n   * grab cursor there, so the gutter always pans (outside a page there is\n   * nothing to draw on or select). On-page behavior is untouched: the tool's\n   * own gesture still owns page space. Default true.\n   */\n  panFallback?: boolean;\n}\n\n/**\n * Pan-the-camera as an interaction handler. Live under the built-in `pan` tool\n * (the `scroll` tag) and, with `panFallback`, under every tool that acts only on\n * pages, where it then captures only page-gap drags (on-page downs belong to the\n * active tool, which claims them first at higher priority). A tool with a\n * `gapCursor` acts over the gaps too (the `zoom` tool draws its box there), so\n * the fallback leaves it alone. It uses the sample's viewport delta, so it pans\n * over the whole viewport (pages and gaps).\n *\n * Cursors: a closed hand (`grabbing`) while dragging; an open hand (`grab`)\n * hovering a gap under a non-pan tool. The pan tool's own resting `grab` comes\n * from its `Tool.cursor`, so hovering it needs no claim here.\n */\nexport function createScrollHandler(\n  stage: StageCapability,\n  interaction: InteractionHostCapability,\n  options: ScrollHandlerOptions = {},\n): InteractionHandler {\n  const panFallback = options.panFallback ?? true;\n  let last = { x: 0, y: 0 };\n  const isPanTool = (): boolean => interaction.getActiveTool().enables.has('scroll');\n  return {\n    id: 'stage-scroll',\n    priority: 10, // below page-aware handlers (selection, annotation), which claim first\n    enabledFor: (tool) =>\n      tool.enables.has('scroll') || (panFallback && tool.gapCursor === undefined),\n    onPointerDown: (sample) => {\n      // Fallback: a non-pan tool pans only over a gap. On a page, decline so the\n      // tool's own (higher-priority) handler keeps the down it already captured.\n      if (!isPanTool() && sample.page) return false;\n      last = sample.viewport;\n      interaction.claimCursor('stage-grab', 'grabbing', 40); // closed hand while panning\n      return true; // capture the drag\n    },\n    onPointerMove: (sample) => {\n      stage.panBy(sample.viewport.x - last.x, sample.viewport.y - last.y);\n      last = sample.viewport;\n    },\n    onPointerUp: () => interaction.claimCursor('stage-grab', null),\n    onHover: (sample) => {\n      // An open hand over a gap when a non-pan tool would fall back to pan\n      // there; cleared over a page (the tool's cursor shows). The pan tool\n      // skips this: its resting `grab` is the tool cursor.\n      if (panFallback && !isPanTool()) {\n        interaction.claimCursor('stage-pan-fallback', sample.page ? null : 'grab', 5);\n      }\n    },\n  };\n}\n","import type {\n  InteractionHostCapability,\n  InteractionHandler,\n} from '@embedpdf/plugin-interaction/contract/host';\nimport type { StageHostCapability } from './host-contract';\n\n/**\n * The `zoom` tool as an interaction handler: live under the tool's `zoom-box`\n * tag, over the pages and the space between them. It forwards the pointer in\n * viewport px to the stage's zoom drag, which decides what a box or a click\n * zooms to. A sample from another surface (a `PageView` stamps no lens) is in\n * another element's px, so the handler takes only its own lens's presses.\n *\n * Cursors: the tool's own `zoom-in`, and `zoom-out` while Alt (Option) is\n * held, which turns a click into a step out.\n */\nexport function createZoomDragHandler(\n  stage: StageHostCapability,\n  interaction: InteractionHostCapability,\n): InteractionHandler {\n  return {\n    id: 'stage-zoom-drag',\n    priority: 10, // the stage's own band, as the scroll handler\n    enabledFor: (tool) => tool.enables.has('zoom-box'),\n    onPointerDown: (sample) => {\n      if (sample.source !== stage.getLensId()) return false;\n      stage.beginZoomDrag(sample.viewport);\n      return true;\n    },\n    onPointerMove: (sample) => stage.moveZoomDrag(sample.viewport),\n    onPointerUp: (sample) => stage.endZoomDrag({ zoomOut: sample.modifiers.alt }),\n    onPointerCancel: () => stage.cancelZoomDrag(),\n    onHover: (sample) =>\n      interaction.claimCursor('stage-zoom-out', sample.modifiers.alt ? 'zoom-out' : null),\n  };\n}\n"],"mappings":";;;;;;;;;AAoBA,SAAgB,aAAa,OAAiD;CAC5E,OAAO,MAAM,KAAK,EAAE,KAAK,aAAa,gBAAgB;EACpD,IAAI,YAAY,SAAS,KAAK,YAAY,UAAU,GAClD,OAAO;GAAE,MAAM;GAAK,MAAM;GAAQ,QAAQ;EAAE;EAE9C,MAAM,SAAS,YAAY,QAAQ,YAAY,SAAS,UAAU,eAAe;EACjF,OAAO;GAAE,MAAM;GAAK,MAAM;GAAW,SAAS;GAAa,QAAQ,KAAK,MAAM,MAAM;EAAE;CACxF,CAAC;AACH;;;;;AAMA,SAAgB,kBACd,KACA,OACM;CACN,IAAI,OAAO;CACX,MAAM,QAAQ,UAAkC;EAC9C,MAAM,QAAQ,aAAa,KAAK;EAChC,MAAM,MAAM,MAAM,KAAK;EACvB,IAAI,QAAQ,MAAM;EAClB,OAAO;EACP,IAAI,IAAI,cAAc,IAAI,IAAI,KAAK;CACrC;CACA,IAAI,YAAY,MAAM,iBAAiB,GAAG,IAAI;CAC9C,KAAK,MAAM,iBAAiB,CAAC;AAC/B;;AAGA,SAAS,MAAM,OAA0C;CACvD,OAAO,MACJ,KAAK,EAAE,MAAM,MAAM,SAAS,aAAa;EACxC,MAAM,OAAO,UACT,GAAG,KAAK,MAAM,QAAQ,CAAC,EAAE,GAAG,KAAK,MAAM,QAAQ,CAAC,EAAE,GAAG,KAAK,M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