@embedpdf/react 3.0.0-next.0 → 3.0.0-next.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/dist/AnnotationListSnapshot-DDxHpJQU-BG32YXxG.d.cts +347 -0
  2. package/dist/AnnotationListSnapshot-DDxHpJQU-BG32YXxG.d.ts +347 -0
  3. package/dist/anchored.cjs +89 -0
  4. package/dist/anchored.cjs.map +1 -0
  5. package/dist/anchored.d.cts +45 -0
  6. package/dist/anchored.d.ts +45 -0
  7. package/dist/anchored.js +60 -0
  8. package/dist/anchored.js.map +1 -0
  9. package/dist/annotation-menu.cjs +33 -84
  10. package/dist/annotation-menu.cjs.map +1 -1
  11. package/dist/annotation-menu.d.cts +28 -2
  12. package/dist/annotation-menu.d.ts +28 -2
  13. package/dist/annotation-menu.js +27 -78
  14. package/dist/annotation-menu.js.map +1 -1
  15. package/dist/annotation.cjs +752 -16
  16. package/dist/annotation.cjs.map +1 -0
  17. package/dist/annotation.d.cts +159 -2
  18. package/dist/annotation.d.ts +159 -2
  19. package/dist/annotation.js +737 -3
  20. package/dist/annotation.js.map +1 -0
  21. package/dist/commands.js +1 -0
  22. package/dist/commands.js.map +1 -1
  23. package/dist/form.cjs +3 -3
  24. package/dist/form.cjs.map +1 -1
  25. package/dist/form.d.cts +2 -2
  26. package/dist/form.d.ts +2 -2
  27. package/dist/form.js +3 -3
  28. package/dist/form.js.map +1 -1
  29. package/dist/index.cjs +34 -5
  30. package/dist/index.d.cts +14 -8
  31. package/dist/index.d.ts +14 -8
  32. package/dist/index.js +8 -6
  33. package/dist/interaction.cjs +17 -4
  34. package/dist/interaction.cjs.map +1 -1
  35. package/dist/interaction.d.cts +2 -2
  36. package/dist/interaction.d.ts +2 -2
  37. package/dist/interaction.js +7 -5
  38. package/dist/interaction.js.map +1 -1
  39. package/dist/link.cjs +29 -6
  40. package/dist/link.cjs.map +1 -1
  41. package/dist/link.d.cts +12 -3
  42. package/dist/link.d.ts +12 -3
  43. package/dist/link.js +31 -8
  44. package/dist/link.js.map +1 -1
  45. package/dist/metadata.js +1 -0
  46. package/dist/metadata.js.map +1 -1
  47. package/dist/page-edit.js +1 -0
  48. package/dist/page-edit.js.map +1 -1
  49. package/dist/page-view.cjs +62 -38
  50. package/dist/page-view.cjs.map +1 -1
  51. package/dist/page-view.js +59 -37
  52. package/dist/page-view.js.map +1 -1
  53. package/dist/redaction.js +1 -0
  54. package/dist/redaction.js.map +1 -1
  55. package/dist/render.cjs +67 -50
  56. package/dist/render.cjs.map +1 -1
  57. package/dist/render.d.cts +6 -19
  58. package/dist/render.d.ts +6 -19
  59. package/dist/render.js +71 -52
  60. package/dist/render.js.map +1 -1
  61. package/dist/rolldown-runtime-BBjsoOtd.js +27 -0
  62. package/dist/{runtime-DV98q7I0.d.ts → runtime-Cvi0wQ4d.d.cts} +23 -10
  63. package/dist/{runtime-CMxIuF2O.d.cts → runtime-DXxr8T4L.d.ts} +23 -10
  64. package/dist/runtime.cjs +6 -5
  65. package/dist/runtime.cjs.map +1 -1
  66. package/dist/runtime.d.cts +1 -1
  67. package/dist/runtime.d.ts +1 -1
  68. package/dist/runtime.js +7 -5
  69. package/dist/runtime.js.map +1 -1
  70. package/dist/search.cjs +36 -19
  71. package/dist/search.cjs.map +1 -1
  72. package/dist/search.d.cts +1 -1
  73. package/dist/search.d.ts +1 -1
  74. package/dist/search.js +36 -19
  75. package/dist/search.js.map +1 -1
  76. package/dist/selection.cjs +217 -22
  77. package/dist/selection.cjs.map +1 -1
  78. package/dist/selection.d.cts +60 -2
  79. package/dist/selection.d.ts +60 -2
  80. package/dist/selection.js +214 -27
  81. package/dist/selection.js.map +1 -1
  82. package/dist/shell.js +1 -0
  83. package/dist/shell.js.map +1 -1
  84. package/dist/stage.cjs +47 -146
  85. package/dist/stage.cjs.map +1 -1
  86. package/dist/stage.d.cts +18 -5
  87. package/dist/stage.d.ts +18 -5
  88. package/dist/stage.js +50 -148
  89. package/dist/stage.js.map +1 -1
  90. package/dist/stamp.js +1 -0
  91. package/dist/stamp.js.map +1 -1
  92. package/dist/toolbar.js +1 -0
  93. package/dist/toolbar.js.map +1 -1
  94. package/dist/views.js +1 -0
  95. package/dist/views.js.map +1 -1
  96. package/package.json +27 -26
  97. package/dist/AnnotationListSnapshot-W0RCsyDE-dWna4TTJ.d.cts +0 -2593
  98. package/dist/AnnotationListSnapshot-W0RCsyDE-dWna4TTJ.d.ts +0 -2593
  99. package/dist/annotation-B6jwfTCh.d.cts +0 -173
  100. package/dist/annotation-Ct6dFtzJ.cjs +0 -913
  101. package/dist/annotation-Ct6dFtzJ.cjs.map +0 -1
  102. package/dist/annotation-DjGWJljY.js +0 -829
  103. package/dist/annotation-DjGWJljY.js.map +0 -1
  104. package/dist/annotation-nUMefyjw.d.ts +0 -173
@@ -1,8 +1,11 @@
1
- import * as React from "react";
2
1
  import { AnyPlugin, CapabilityToken, Engine, EngineFactory, InitialDocument, Kernel } from "@embedpdf/core";
2
+ import * as React from "react";
3
3
  import { PageFrame, PageTransform, Point, Rect } from "@embedpdf/core-geometry";
4
4
  import { PageViewDemand } from "@embedpdf/plugin-render";
5
- //#region src/runtime.d.ts
5
+ declare namespace runtime_d_exports {
6
+ export { DocumentGate, DocumentGateProps, DocumentScope, DocumentScopeProps, EmbedPDF, PageContextValue, PageProvider, Viewer, ViewerProps, makePageContext, shallowArray, useActiveDocumentId, useCapability, useDocumentId, useDocumentStatus, useDocuments, useKernel, useKernelValue, useOptionalCapability, useOptionalSelector, usePage, useSelector };
7
+ }
8
+ import * as import__embedpdf_core from "@embedpdf/core";
6
9
  declare function useKernel(): Kernel;
7
10
  declare const shallowArray: <T>(a: readonly T[], b: readonly T[]) => boolean;
8
11
  /** Read a value derived from the kernel, cached by equality (no tearing loop). */
@@ -160,18 +163,19 @@ interface PageContextValue {
160
163
  frame: PageFrame;
161
164
  /**
162
165
  * The single bridge between PDF points, view px, and device px for this page.
163
- * Layers do ALL coordinate work through it — `pageToContent` to place content-
166
+ * Layers do ALL coordinate work through it — `toPixels` to place content-
164
167
  * space overlays, `renderScale`/`deviceWidth` to render, `contentWidth` for
165
168
  * page-relative sizing. Never re-derive `x * scale` or `* dpr`.
166
169
  */
167
170
  transform: PageTransform;
168
- /** Client (screen) point → PDF point — the one platform-bound hit-test. */
169
- toPagePoint(clientX: number, clientY: number): Point;
170
- /** PDF/content point → client (screen) px — the exact inverse of `toPagePoint`
171
+ /** Client (screen) point → the viewer's coordinates (content point) — the
172
+ * one platform-bound hit-test. */
173
+ toContentPoint(clientX: number, clientY: number): Point;
174
+ /** Content point → client (screen) px — the exact inverse of `toContentPoint`
171
175
  * (rotation applied). Lets viewport-space UI (e.g. a selection menu) anchor to a
172
176
  * page point WITHOUT a Stage camera, so it works the same in `<PageView>`. */
173
177
  toClientPoint(p: Point): Point;
174
- /** PDF/content rect → client (screen) px AABB. Rect analog of `toClientPoint`
178
+ /** Content rect → client (screen) px AABB. Rect analog of `toClientPoint`
175
179
  * for upright viewport-space UI that frames a selected page region. */
176
180
  toClientRect(rect: Rect): Rect;
177
181
  /**
@@ -186,10 +190,19 @@ interface PageContextValue {
186
190
  * a thumbnail-sized demand turns into "never engages" by arithmetic).
187
191
  */
188
192
  getViewDemand?: () => PageViewDemand;
193
+ /**
194
+ * The hosting VIEW's identity — the stage lens id (`stage.lensId()`) or a
195
+ * per-instance PageView id. IDENTITY, not an option: per-view raster
196
+ * planning (tiles) keys its state by this, so two views showing the SAME
197
+ * page never fight over one plan (a thumbnail rail's never-engaging demand
198
+ * must not disturb the main view's tiles). Every page context host must
199
+ * say which view it is.
200
+ */
201
+ view: string;
189
202
  }
190
203
  declare const PageProvider: React.Provider<PageContextValue | null>;
191
204
  declare function usePage(): PageContextValue;
192
- declare function makePageContext(documentId: string, pon: number, pageIndex: number, frame: PageFrame, transform: PageTransform, getRect: () => DOMRect, getViewDemand?: () => PageViewDemand): PageContextValue;
205
+ declare function makePageContext(documentId: string, view: string, pon: number, pageIndex: number, frame: PageFrame, transform: PageTransform, getRect: () => DOMRect, getViewDemand?: () => PageViewDemand): PageContextValue;
193
206
  //#endregion
194
- export { useSelector as S, useKernel as _, EmbedPDF as a, useOptionalSelector as b, Viewer as c, shallowArray as d, useActiveDocumentId as f, useDocuments as g, useDocumentStatus as h, DocumentScopeProps as i, ViewerProps as l, useDocumentId as m, DocumentGateProps as n, PageContextValue as o, useCapability as p, DocumentScope as r, PageProvider as s, DocumentGate as t, makePageContext as u, useKernelValue as v, usePage as x, useOptionalCapability as y };
195
- //# sourceMappingURL=runtime-CMxIuF2O.d.cts.map
207
+ export { useSelector as C, usePage as S, useDocuments as _, EmbedPDF as a, useOptionalCapability as b, Viewer as c, runtime_d_exports as d, shallowArray as f, useDocumentStatus as g, useDocumentId as h, DocumentScopeProps as i, ViewerProps as l, useCapability as m, DocumentGateProps as n, PageContextValue as o, useActiveDocumentId as p, DocumentScope as r, PageProvider as s, DocumentGate as t, makePageContext as u, useKernel as v, useOptionalSelector as x, useKernelValue as y };
208
+ //# sourceMappingURL=runtime-DXxr8T4L.d.ts.map
package/dist/runtime.cjs CHANGED
@@ -248,24 +248,25 @@ function usePage() {
248
248
  if (!c) throw new Error("usePage must be used inside <PageView> or a <Stage> page");
249
249
  return c;
250
250
  }
251
- function makePageContext(documentId, pon, pageIndex, frame, transform, getRect, getViewDemand) {
251
+ function makePageContext(documentId, view, pon, pageIndex, frame, transform, getRect, getViewDemand) {
252
252
  return {
253
253
  documentId,
254
+ view,
254
255
  pon,
255
256
  pageIndex,
256
257
  frame,
257
258
  transform,
258
259
  ...getViewDemand ? { getViewDemand } : {},
259
- toPagePoint: (cx, cy) => {
260
+ toContentPoint: (cx, cy) => {
260
261
  const r = getRect();
261
- return transform.viewToPage({
262
+ return transform.viewToContent({
262
263
  x: cx - r.left,
263
264
  y: cy - r.top
264
265
  });
265
266
  },
266
267
  toClientPoint: (p) => {
267
268
  const r = getRect();
268
- const v = transform.pageToView(p);
269
+ const v = transform.contentToView(p);
269
270
  return {
270
271
  x: r.left + v.x,
271
272
  y: r.top + v.y
@@ -273,7 +274,7 @@ function makePageContext(documentId, pon, pageIndex, frame, transform, getRect,
273
274
  },
274
275
  toClientRect: (rect) => {
275
276
  const r = getRect();
276
- const v = transform.pageToViewRect(rect);
277
+ const v = transform.contentToViewRect(rect);
277
278
  return {
278
279
  x: r.left + v.x,
279
280
  y: r.top + v.y,
@@ -1 +1 @@
1
- {"version":3,"file":"runtime.cjs","names":["docInfoListEquals"],"sources":["../src/runtime.tsx"],"sourcesContent":["/**\n * @embedpdf/react — the generic binding.\n *\n * Binds the kernel's one change stream to React (useSyncExternalStore), resolves\n * capabilities (document-scoped ones against the active or `<DocumentScope>`-given\n * document), and provides the page coordinate context. Every plugin and layer rides\n * on this — there is no per-plugin framework code.\n */\n\n// One-line-per-feature: registration travels with the UI.\nexport * from '@embedpdf/core';\nimport * as React from 'react';\nimport {\n createContext,\n useContext,\n useEffect,\n useRef,\n useState,\n useSyncExternalStore,\n} from 'react';\nimport { createKernel, docInfoListEquals } from '@embedpdf/core';\nimport type {\n AnyPlugin,\n CapabilityToken,\n Engine,\n EngineFactory,\n InitialDocument,\n Kernel,\n} from '@embedpdf/core';\n// Pure coordinate math from the geometry base — NOT from stage-core. The\n// PageContext seam stays stage-agnostic (it must also serve standalone PageView).\nimport type { PageFrame, PageTransform, Point, Rect } from '@embedpdf/core-geometry';\nimport type { PageViewDemand } from '@embedpdf/plugin-render';\n\nconst KernelCtx = createContext<Kernel | null>(null);\n/** The document a subtree is bound to. null => use the active document. */\nconst DocumentScopeCtx = createContext<string | null>(null);\n\nexport function useKernel(): Kernel {\n const k = useContext(KernelCtx);\n if (!k) throw new Error('useKernel must be used within <Viewer>/<EmbedPDF>');\n return k;\n}\n\nexport const shallowArray = <T,>(a: readonly T[], b: readonly T[]): boolean =>\n a === b || (a.length === b.length && a.every((x, i) => x === b[i]));\n\n/** Read a value derived from the kernel, cached by equality (no tearing loop). */\nexport function useKernelValue<R>(\n select: (k: Kernel) => R,\n isEqual: (a: R, b: R) => boolean = Object.is,\n): R {\n const kernel = useKernel();\n const last = useRef<{ v: R } | null>(null);\n const get = () => {\n const next = select(kernel);\n if (last.current && isEqual(last.current.v, next)) return last.current.v;\n last.current = { v: next };\n return next;\n };\n return useSyncExternalStore(kernel.subscribe, get, get);\n}\n\nexport function useActiveDocumentId(): string | null {\n return useKernelValue((k) => k.documents.activeId());\n}\n\n/** The document id for this subtree: the nearest <DocumentScope>, else the active doc. */\nexport function useDocumentId(): string | null {\n const scoped = useContext(DocumentScopeCtx);\n const active = useActiveDocumentId();\n return scoped ?? active;\n}\n\nexport interface DocumentScopeProps {\n id: string;\n children: React.ReactNode;\n}\n/** Bind a subtree to a specific document (panes, comparison). */\nexport function DocumentScope({ id, children }: DocumentScopeProps) {\n return <DocumentScopeCtx.Provider value={id}>{children}</DocumentScopeCtx.Provider>;\n}\n\nexport interface DocumentGateProps {\n /** Shown while this subtree has NO document (empty workspace, docs still opening). */\n fallback?: React.ReactNode;\n children: React.ReactNode;\n}\n/**\n * Render children only while this subtree has a READY document — the\n * structural way to say \"this UI is defined over a document\". An empty\n * workspace is a legitimate, designable state (the Viewer no longer blocks on\n * documents so chrome can render at t≈0): workspace-scoped UI (toolbars,\n * commands, i18n) lives OUTSIDE the gate; document-scoped UI (Stage, panels,\n * page chrome) lives inside it, or reads through `useOptionalSelector`.\n * A `loading`/`locked`/`error` tab renders `fallback` — so the gate's\n * fallback doubles as the per-tab boot state; richer chrome (a password\n * prompt, an error pane) branches on `useDocumentStatus()` beside the gate.\n * Sibling of <DocumentScope>, which picks WHICH document; this one handles\n * WHETHER.\n */\nexport function DocumentGate({ fallback = null, children }: DocumentGateProps) {\n const docId = useDocumentId();\n const ready = useKernelValue((k) => (docId ? k.documents.get(docId)?.status === 'ready' : false));\n return <>{ready ? children : fallback}</>;\n}\n\n/** Lifecycle status of this subtree's document (loading/locked/ready/error),\n * or null with no document. The password prompt and error panes key off it. */\nexport function useDocumentStatus() {\n const docId = useDocumentId();\n return useKernelValue((k) => (docId ? (k.documents.get(docId)?.status ?? null) : null));\n}\n\n/**\n * Resolve a capability by token, binding document-scoped ones to this\n * subtree's document. Resolution is a REACTIVE read (`tryCapability` through\n * the kernel's one change stream), not a memoized call — under the\n * request-time lifecycle a document can become resolvable while its id stays\n * the same, so any id-keyed cache goes stale; subscribing makes staleness\n * structurally impossible. Fail-fast: while unresolvable, this re-runs the\n * strict resolver so the kernel's truthful reason (`no capability` / `no\n * document` / `document is loading|locked`) is what throws.\n */\nexport function useCapability<T>(token: CapabilityToken<T>): T {\n const kernel = useKernel();\n const scoped = useContext(DocumentScopeCtx);\n const cap = useKernelValue((k) => k.tryCapability(token, scoped ?? undefined));\n return cap ?? kernel.capability(token, scoped ?? undefined);\n}\n\n/** Like `useCapability`, but null while the token can't resolve (no plugin,\n * no document, or a document that isn't ready yet). */\nexport function useOptionalCapability<T>(token: CapabilityToken<T>): T | null {\n const scoped = useContext(DocumentScopeCtx);\n return useKernelValue((k) => k.tryCapability(token, scoped ?? undefined));\n}\n\n/** Subscribe to a selector over a (document-resolved) capability. */\nexport function useSelector<C, R>(\n token: CapabilityToken<C>,\n select: (cap: C) => R,\n isEqual: (a: R, b: R) => boolean = Object.is,\n): R {\n const kernel = useKernel();\n const cap = useCapability(token);\n const last = useRef<{ v: R } | null>(null);\n const get = () => {\n const next = select(cap);\n if (last.current && isEqual(last.current.v, next)) return last.current.v;\n last.current = { v: next };\n return next;\n };\n return useSyncExternalStore(kernel.subscribe, get, get);\n}\n\n/**\n * Null-safe `useSelector`: `fallback` whenever the token can't resolve — no\n * provider, or a document-scoped token with no document. For chrome that stays\n * mounted across the empty-workspace state (a zoom readout, a mode band).\n * `useSelector` stays strict (fail-fast) for code that KNOWS a document exists\n * — e.g. anything inside a <DocumentGate>.\n *\n * The `select` guard also swallows reads through a capability whose document\n * closed between the store notification and this render — that teardown race\n * resolves to `fallback` for one frame, then re-renders against the new state.\n */\nexport function useOptionalSelector<C, R>(\n token: CapabilityToken<C>,\n select: (cap: C) => R,\n fallback: R,\n isEqual: (a: R, b: R) => boolean = Object.is,\n): R {\n const kernel = useKernel();\n const cap = useOptionalCapability(token);\n const last = useRef<{ v: R } | null>(null);\n const get = () => {\n let next: R;\n if (cap === null) {\n next = fallback;\n } else {\n try {\n next = select(cap);\n } catch {\n next = fallback;\n }\n }\n if (last.current && isEqual(last.current.v, next)) return last.current.v;\n last.current = { v: next };\n return next;\n };\n return useSyncExternalStore(kernel.subscribe, get, get);\n}\n\n/** The document registry (open/close/active/list), reactive. */\nexport function useDocuments() {\n const kernel = useKernel();\n const docs = useKernelValue((k) => k.documents.list(), docInfoListEquals);\n const activeId = useActiveDocumentId();\n return {\n docs,\n activeId,\n open: kernel.documents.open,\n unlock: kernel.documents.unlock,\n close: kernel.documents.close,\n setActive: kernel.documents.setActive,\n move: kernel.documents.move,\n swap: kernel.documents.swap,\n download: kernel.documents.download,\n downloadLayer: kernel.documents.downloadLayer,\n };\n}\n\n// `InitialDocument` is the KERNEL's type (re-exported via `export * from\n// '@embedpdf/core'` above) — one shared shape for every adapter.\n\nexport interface ViewerProps {\n /**\n * The engine, as an instance or a thunk. Engines construct synchronously and\n * boot lazily (`localEngine()` allocates nothing until first use), so\n * ownership follows the SHAPE of what you pass:\n *\n * - An **instance** (`engine={engine}`) is BORROWED: the Viewer uses it and\n * never destroys it, because you acquired it and therefore own it. The\n * common path — a module-scope `const engine = localEngine()` shared\n * across viewers and route changes. The Viewer calls `engine.warmup?.()`\n * on mount so the boot overlaps app initialization.\n * - A **thunk** (`engine={() => localEngine()}`) is VIEWER-OWNED: the\n * Viewer calls it on mount and `destroy()`s the result on unmount. Use it\n * for per-mount isolation (StrictMode/HMR-clean teardown, independent\n * multi-viewer engines).\n *\n * Init-only: captured on first render; later identity changes are ignored (dev warns).\n */\n engine: Engine | EngineFactory;\n /** Init-only: captured on first render; later identity changes are ignored (dev warns). */\n plugins: AnyPlugin[];\n /** Documents to open on startup (with optional tab names). Init-only. */\n initialDocuments?: InitialDocument[];\n fallback?: React.ReactNode;\n /** Rendered when kernel construction or `start()` fails. Without it a boot\n * failure renders nothing — but never a silent forever-fallback. */\n renderError?: (error: unknown) => React.ReactNode;\n children: React.ReactNode;\n}\n\ntype BootState =\n | { phase: 'booting'; kernel: Kernel | null }\n | { phase: 'ready'; kernel: Kernel }\n | { phase: 'error'; error: unknown };\n\n/**\n * Owns the kernel as an EFFECT-scoped resource: each effect setup creates and\n * starts exactly one kernel; each cleanup destroys exactly that one. That is\n * the contract StrictMode exercises (two kernels in dev, the first fully\n * destroyed) — the kernel itself is never restarted after destroy.\n *\n * The kernel is published to context the moment it exists — before `start()`\n * resolves — so the `fallback` can use workspace capabilities (i18n copy on a\n * loading screen) exactly as before. The one exception is the very first\n * render, which happens before the effect: it renders nothing. Children mount\n * once `start()` resolves — which never touches the engine, so the shell is\n * alive while WASM compiles or the transport connects. `initialDocuments`\n * open in the BACKGROUND and stream into the registry (`useDocuments()` is\n * reactive); per-document loading UI is the Stage's job, not a root gate.\n *\n * ENGINE OWNERSHIP. When `engine` is a thunk, the Viewer OWNS it: each effect\n * setup constructs one engine (construction is synchronous and inert — boot\n * happens lazily inside the engine) and each cleanup destroys exactly that one\n * — after the kernel, so handles close first. When `engine` is an instance it\n * is BORROWED and never destroyed here; the Viewer only calls `warmup?.()` so\n * the WASM/transport boot overlaps plugin initialization. StrictMode's\n * double-mount therefore constructs two independent thunk engines and tears\n * the first fully down, matching the kernel's own effect-scoped lifecycle.\n * That means dev-only double resource use (two worker spawns, two font\n * fetches, briefly overlapping) — deliberate, because it is exactly the\n * leak-detection contract StrictMode exists to exercise; production mounts\n * once and boots once.\n */\nexport function Viewer({\n engine,\n plugins,\n initialDocuments,\n fallback,\n renderError,\n children,\n}: ViewerProps) {\n // Init-only inputs: the kernel's lifetime is the component's lifetime, so a\n // changed engine/plugins identity cannot mean \"rebuild the workspace\" —\n // that would silently drop every open document. Capture once, warn in dev.\n const initial = useRef({ engine, plugins, initialDocuments });\n const warned = useRef(false);\n if (process.env.NODE_ENV !== 'production' && !warned.current) {\n if (initial.current.engine !== engine || initial.current.plugins !== plugins) {\n warned.current = true;\n console.warn(\n '[embedpdf] <Viewer> engine/plugins are init-only. A changed identity is ignored — ' +\n 'pass stable references (module scope, useState, or useMemo). ' +\n 'An inline `plugins={[...]}` array recreates its identity every render.',\n );\n }\n }\n\n const [boot, setBoot] = useState<BootState>({ phase: 'booting', kernel: null });\n useEffect(() => {\n const captured = initial.current;\n // A thunk is viewer-owned: call it now, destroy on unmount. An instance is\n // borrowed: use as-is, never destroy. Construction is synchronous and inert\n // either way — the engine boots lazily on first use — so kick `warmup()`\n // to overlap the WASM/transport boot with plugin initialization.\n const ownsEngine = typeof captured.engine === 'function';\n const engine: Engine = ownsEngine\n ? (captured.engine as EngineFactory)()\n : (captured.engine as Engine);\n engine.warmup?.();\n let kernel: Kernel;\n try {\n kernel = createKernel({ engine, plugins: captured.plugins });\n } catch (error) {\n setBoot({ phase: 'error', error }); // plan/graph errors surface, not throw mid-render\n if (ownsEngine) void engine.destroy();\n return;\n }\n let alive = true;\n setBoot({ phase: 'booting', kernel }); // context carries the kernel from this frame on\n kernel.start().then(\n () => {\n if (!alive) return; // unmounted mid-boot — don't open anything\n setBoot({ phase: 'ready', kernel });\n // Kernel-owned boot policy: all tabs appear immediately in array\n // order; the `active` entry (else the first) is selected; failures\n // surface as tab status. See DocumentsCapability.openAll.\n kernel.documents.openAll(captured.initialDocuments ?? []);\n },\n (error) => {\n if (alive) setBoot({ phase: 'error', error });\n },\n );\n return () => {\n alive = false;\n // Kernel first (closes every document handle), THEN the engine we own —\n // ownership follows acquisition. `engine.destroy()` joins an in-flight\n // boot (or no-ops if it never started), so an unmount mid-boot is safe.\n void kernel.destroy().then(() => {\n if (ownsEngine) void engine.destroy();\n });\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n if (boot.phase === 'error') {\n return <>{renderError ? renderError(boot.error) : null}</>;\n }\n if (!boot.kernel) return null; // pre-effect first render only\n return (\n <KernelCtx.Provider value={boot.kernel}>\n {boot.phase === 'ready' ? children : (fallback ?? null)}\n </KernelCtx.Provider>\n );\n}\nexport const EmbedPDF = Viewer;\n\n/**\n * PageContext — the seam. A layer depends ONLY on this, never on the Stage. So the\n * same layer works inside a virtualized Stage and in a standalone <PageView>.\n */\nexport interface PageContextValue {\n documentId: string;\n /** Durable page identity (PDF object number) — use for keys / render / annotations. */\n pon: number;\n /** Display index (page N) — use for ordering / human-facing page numbers. */\n pageIndex: number;\n /**\n * Reserved chrome bands around the page (screen px per side). The page-chrome\n * slot renders into the outer box (content + frame); these thicknesses size\n * the bands — a label in the bottom band is `bottom:0; height: frame.bottom`.\n */\n frame: PageFrame;\n /**\n * The single bridge between PDF points, view px, and device px for this page.\n * Layers do ALL coordinate work through it — `pageToContent` to place content-\n * space overlays, `renderScale`/`deviceWidth` to render, `contentWidth` for\n * page-relative sizing. Never re-derive `x * scale` or `* dpr`.\n */\n transform: PageTransform;\n /** Client (screen) point → PDF point — the one platform-bound hit-test. */\n toPagePoint(clientX: number, clientY: number): Point;\n /** PDF/content point → client (screen) px — the exact inverse of `toPagePoint`\n * (rotation applied). Lets viewport-space UI (e.g. a selection menu) anchor to a\n * page point WITHOUT a Stage camera, so it works the same in `<PageView>`. */\n toClientPoint(p: Point): Point;\n /** PDF/content rect → client (screen) px AABB. Rect analog of `toClientPoint`\n * for upright viewport-space UI that frames a selected page region. */\n toClientRect(rect: Rect): Rect;\n /**\n * The page-view DEMAND for raster planning uses dependency inversion:\n * plugin-render defines the shape; the host that CREATED this\n * context fills it — as a PULL. The Stage host's getter closes over the\n * stage capability and reads `VisiblePage.visibleRect` live at call time\n * (visibility is the STAGE's data; adapters never re-derive camera math or\n * cache a copy). Three states, three meanings: a real sub-rect (visible),\n * a ZERO rect (stage host, page currently off-screen — want nothing), and\n * an undefined getter (stage-less `<PageView>` — whole page visible, which\n * a thumbnail-sized demand turns into \"never engages\" by arithmetic).\n */\n getViewDemand?: () => PageViewDemand;\n}\n\nconst PageCtx = createContext<PageContextValue | null>(null);\nexport const PageProvider = PageCtx.Provider;\n\nexport function usePage(): PageContextValue {\n const c = useContext(PageCtx);\n if (!c) throw new Error('usePage must be used inside <PageView> or a <Stage> page');\n return c;\n}\n\nexport function makePageContext(\n documentId: string,\n pon: number,\n pageIndex: number,\n frame: PageFrame,\n transform: PageTransform,\n getRect: () => DOMRect,\n getViewDemand?: () => PageViewDemand,\n): PageContextValue {\n return {\n documentId,\n pon,\n pageIndex,\n frame,\n transform,\n ...(getViewDemand ? { getViewDemand } : {}),\n toPagePoint: (cx, cy) => {\n // `getRect()` is the rotated content wrapper's axis-aligned bounding box =\n // the page's DISPLAY box on screen. Convert client → box-local view px,\n // then invert rotation + scale via the transform (verified once in geometry,\n // not re-derived per framework adapter).\n const r = getRect();\n return transform.viewToPage({ x: cx - r.left, y: cy - r.top });\n },\n toClientPoint: (p) => {\n // Exact inverse of `toPagePoint`: page/content point → display-box view px\n // (rotation applied by the transform), offset by the same live display-box\n // origin. So the two can never drift, in either <Stage> or <PageView>.\n const r = getRect();\n const v = transform.pageToView(p);\n return { x: r.left + v.x, y: r.top + v.y };\n },\n toClientRect: (rect) => {\n const r = getRect();\n const v = transform.pageToViewRect(rect);\n return { x: r.left + v.x, y: r.top + v.y, width: v.width, height: v.height };\n },\n };\n}\n"],"mappings":";;;;;;;AAkCA,MAAM,aAAA,GAAA,MAAA,cAAA,CAAyC,IAAI;;AAEnD,MAAM,oBAAA,GAAA,MAAA,cAAA,CAAgD,IAAI;AAE1D,SAAgB,YAAoB;CAClC,MAAM,KAAA,GAAA,MAAA,WAAA,CAAe,SAAS;CAC9B,IAAI,CAAC,GAAG,MAAM,IAAI,MAAM,mDAAmD;CAC3E,OAAO;AACT;AAEA,MAAa,gBAAoB,GAAiB,MAChD,MAAM,KAAM,EAAE,WAAW,EAAE,UAAU,EAAE,OAAO,GAAG,MAAM,MAAM,EAAE,EAAE;;A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I,UAAU,WAAW,CAAC;GAChC,OAAO;IAAE,GAAG,EAAE,OAAO,EAAE;IAAG,GAAG,EAAE,MAAM,EAAE;GAAE;EAC3C;EACA,eAAe,SAAS;GACtB,MAAM,IAAI,QAAQ;GAClB,MAAM,IAAI,UAAU,eAAe,IAAI;GACvC,OAAO;IAAE,GAAG,EAAE,OAAO,EAAE;IAAG,GAAG,EAAE,MAAM,EAAE;IAAG,OAAO,EAAE;IAAO,QAAQ,EAAE;GAAO;EAC7E;CACF;AACF"}
1
+ {"version":3,"file":"runtime.cjs","names":["docInfoListEquals"],"sources":["../src/runtime.tsx"],"sourcesContent":["/**\n * @embedpdf/react — the generic binding.\n *\n * Binds the kernel's one change stream to React (useSyncExternalStore), resolves\n * capabilities (document-scoped ones against the active or `<DocumentScope>`-given\n * document), and provides the page coordinate context. Every plugin and layer rides\n * on this — there is no per-plugin framework code.\n */\n\n// One-line-per-feature: registration travels with the UI.\nexport * from '@embedpdf/core';\nimport * as React from 'react';\nimport {\n createContext,\n useContext,\n useEffect,\n useRef,\n useState,\n useSyncExternalStore,\n} from 'react';\nimport { createKernel, docInfoListEquals } from '@embedpdf/core';\nimport type {\n AnyPlugin,\n CapabilityToken,\n Engine,\n EngineFactory,\n InitialDocument,\n Kernel,\n} from '@embedpdf/core';\n// Pure coordinate math from the geometry base — NOT from stage-core. The\n// PageContext seam stays stage-agnostic (it must also serve standalone PageView).\nimport type { PageFrame, PageTransform, Point, Rect } from '@embedpdf/core-geometry';\nimport type { PageViewDemand } from '@embedpdf/plugin-render';\n\nconst KernelCtx = createContext<Kernel | null>(null);\n/** The document a subtree is bound to. null => use the active document. */\nconst DocumentScopeCtx = createContext<string | null>(null);\n\nexport function useKernel(): Kernel {\n const k = useContext(KernelCtx);\n if (!k) throw new Error('useKernel must be used within <Viewer>/<EmbedPDF>');\n return k;\n}\n\nexport const shallowArray = <T,>(a: readonly T[], b: readonly T[]): boolean =>\n a === b || (a.length === b.length && a.every((x, i) => x === b[i]));\n\n/** Read a value derived from the kernel, cached by equality (no tearing loop). */\nexport function useKernelValue<R>(\n select: (k: Kernel) => R,\n isEqual: (a: R, b: R) => boolean = Object.is,\n): R {\n const kernel = useKernel();\n const last = useRef<{ v: R } | null>(null);\n const get = () => {\n const next = select(kernel);\n if (last.current && isEqual(last.current.v, next)) return last.current.v;\n last.current = { v: next };\n return next;\n };\n return useSyncExternalStore(kernel.subscribe, get, get);\n}\n\nexport function useActiveDocumentId(): string | null {\n return useKernelValue((k) => k.documents.activeId());\n}\n\n/** The document id for this subtree: the nearest <DocumentScope>, else the active doc. */\nexport function useDocumentId(): string | null {\n const scoped = useContext(DocumentScopeCtx);\n const active = useActiveDocumentId();\n return scoped ?? active;\n}\n\nexport interface DocumentScopeProps {\n id: string;\n children: React.ReactNode;\n}\n/** Bind a subtree to a specific document (panes, comparison). */\nexport function DocumentScope({ id, children }: DocumentScopeProps) {\n return <DocumentScopeCtx.Provider value={id}>{children}</DocumentScopeCtx.Provider>;\n}\n\nexport interface DocumentGateProps {\n /** Shown while this subtree has NO document (empty workspace, docs still opening). */\n fallback?: React.ReactNode;\n children: React.ReactNode;\n}\n/**\n * Render children only while this subtree has a READY document — the\n * structural way to say \"this UI is defined over a document\". An empty\n * workspace is a legitimate, designable state (the Viewer no longer blocks on\n * documents so chrome can render at t≈0): workspace-scoped UI (toolbars,\n * commands, i18n) lives OUTSIDE the gate; document-scoped UI (Stage, panels,\n * page chrome) lives inside it, or reads through `useOptionalSelector`.\n * A `loading`/`locked`/`error` tab renders `fallback` — so the gate's\n * fallback doubles as the per-tab boot state; richer chrome (a password\n * prompt, an error pane) branches on `useDocumentStatus()` beside the gate.\n * Sibling of <DocumentScope>, which picks WHICH document; this one handles\n * WHETHER.\n */\nexport function DocumentGate({ fallback = null, children }: DocumentGateProps) {\n const docId = useDocumentId();\n const ready = useKernelValue((k) => (docId ? k.documents.get(docId)?.status === 'ready' : false));\n return <>{ready ? children : fallback}</>;\n}\n\n/** Lifecycle status of this subtree's document (loading/locked/ready/error),\n * or null with no document. The password prompt and error panes key off it. */\nexport function useDocumentStatus() {\n const docId = useDocumentId();\n return useKernelValue((k) => (docId ? (k.documents.get(docId)?.status ?? null) : null));\n}\n\n/**\n * Resolve a capability by token, binding document-scoped ones to this\n * subtree's document. Resolution is a REACTIVE read (`tryCapability` through\n * the kernel's one change stream), not a memoized call — under the\n * request-time lifecycle a document can become resolvable while its id stays\n * the same, so any id-keyed cache goes stale; subscribing makes staleness\n * structurally impossible. Fail-fast: while unresolvable, this re-runs the\n * strict resolver so the kernel's truthful reason (`no capability` / `no\n * document` / `document is loading|locked`) is what throws.\n */\nexport function useCapability<T>(token: CapabilityToken<T>): T {\n const kernel = useKernel();\n const scoped = useContext(DocumentScopeCtx);\n const cap = useKernelValue((k) => k.tryCapability(token, scoped ?? undefined));\n return cap ?? kernel.capability(token, scoped ?? undefined);\n}\n\n/** Like `useCapability`, but null while the token can't resolve (no plugin,\n * no document, or a document that isn't ready yet). */\nexport function useOptionalCapability<T>(token: CapabilityToken<T>): T | null {\n const scoped = useContext(DocumentScopeCtx);\n return useKernelValue((k) => k.tryCapability(token, scoped ?? undefined));\n}\n\n/** Subscribe to a selector over a (document-resolved) capability. */\nexport function useSelector<C, R>(\n token: CapabilityToken<C>,\n select: (cap: C) => R,\n isEqual: (a: R, b: R) => boolean = Object.is,\n): R {\n const kernel = useKernel();\n const cap = useCapability(token);\n const last = useRef<{ v: R } | null>(null);\n const get = () => {\n const next = select(cap);\n if (last.current && isEqual(last.current.v, next)) return last.current.v;\n last.current = { v: next };\n return next;\n };\n return useSyncExternalStore(kernel.subscribe, get, get);\n}\n\n/**\n * Null-safe `useSelector`: `fallback` whenever the token can't resolve — no\n * provider, or a document-scoped token with no document. For chrome that stays\n * mounted across the empty-workspace state (a zoom readout, a mode band).\n * `useSelector` stays strict (fail-fast) for code that KNOWS a document exists\n * — e.g. anything inside a <DocumentGate>.\n *\n * The `select` guard also swallows reads through a capability whose document\n * closed between the store notification and this render — that teardown race\n * resolves to `fallback` for one frame, then re-renders against the new state.\n */\nexport function useOptionalSelector<C, R>(\n token: CapabilityToken<C>,\n select: (cap: C) => R,\n fallback: R,\n isEqual: (a: R, b: R) => boolean = Object.is,\n): R {\n const kernel = useKernel();\n const cap = useOptionalCapability(token);\n const last = useRef<{ v: R } | null>(null);\n const get = () => {\n let next: R;\n if (cap === null) {\n next = fallback;\n } else {\n try {\n next = select(cap);\n } catch {\n next = fallback;\n }\n }\n if (last.current && isEqual(last.current.v, next)) return last.current.v;\n last.current = { v: next };\n return next;\n };\n return useSyncExternalStore(kernel.subscribe, get, get);\n}\n\n/** The document registry (open/close/active/list), reactive. */\nexport function useDocuments() {\n const kernel = useKernel();\n const docs = useKernelValue((k) => k.documents.list(), docInfoListEquals);\n const activeId = useActiveDocumentId();\n return {\n docs,\n activeId,\n open: kernel.documents.open,\n unlock: kernel.documents.unlock,\n close: kernel.documents.close,\n setActive: kernel.documents.setActive,\n move: kernel.documents.move,\n swap: kernel.documents.swap,\n download: kernel.documents.download,\n downloadLayer: kernel.documents.downloadLayer,\n };\n}\n\n// `InitialDocument` is the KERNEL's type (re-exported via `export * from\n// '@embedpdf/core'` above) — one shared shape for every adapter.\n\nexport interface ViewerProps {\n /**\n * The engine, as an instance or a thunk. Engines construct synchronously and\n * boot lazily (`localEngine()` allocates nothing until first use), so\n * ownership follows the SHAPE of what you pass:\n *\n * - An **instance** (`engine={engine}`) is BORROWED: the Viewer uses it and\n * never destroys it, because you acquired it and therefore own it. The\n * common path — a module-scope `const engine = localEngine()` shared\n * across viewers and route changes. The Viewer calls `engine.warmup?.()`\n * on mount so the boot overlaps app initialization.\n * - A **thunk** (`engine={() => localEngine()}`) is VIEWER-OWNED: the\n * Viewer calls it on mount and `destroy()`s the result on unmount. Use it\n * for per-mount isolation (StrictMode/HMR-clean teardown, independent\n * multi-viewer engines).\n *\n * Init-only: captured on first render; later identity changes are ignored (dev warns).\n */\n engine: Engine | EngineFactory;\n /** Init-only: captured on first render; later identity changes are ignored (dev warns). */\n plugins: AnyPlugin[];\n /** Documents to open on startup (with optional tab names). Init-only. */\n initialDocuments?: InitialDocument[];\n fallback?: React.ReactNode;\n /** Rendered when kernel construction or `start()` fails. Without it a boot\n * failure renders nothing — but never a silent forever-fallback. */\n renderError?: (error: unknown) => React.ReactNode;\n children: React.ReactNode;\n}\n\ntype BootState =\n | { phase: 'booting'; kernel: Kernel | null }\n | { phase: 'ready'; kernel: Kernel }\n | { phase: 'error'; error: unknown };\n\n/**\n * Owns the kernel as an EFFECT-scoped resource: each effect setup creates and\n * starts exactly one kernel; each cleanup destroys exactly that one. That is\n * the contract StrictMode exercises (two kernels in dev, the first fully\n * destroyed) — the kernel itself is never restarted after destroy.\n *\n * The kernel is published to context the moment it exists — before `start()`\n * resolves — so the `fallback` can use workspace capabilities (i18n copy on a\n * loading screen) exactly as before. The one exception is the very first\n * render, which happens before the effect: it renders nothing. Children mount\n * once `start()` resolves — which never touches the engine, so the shell is\n * alive while WASM compiles or the transport connects. `initialDocuments`\n * open in the BACKGROUND and stream into the registry (`useDocuments()` is\n * reactive); per-document loading UI is the Stage's job, not a root gate.\n *\n * ENGINE OWNERSHIP. When `engine` is a thunk, the Viewer OWNS it: each effect\n * setup constructs one engine (construction is synchronous and inert — boot\n * happens lazily inside the engine) and each cleanup destroys exactly that one\n * — after the kernel, so handles close first. When `engine` is an instance it\n * is BORROWED and never destroyed here; the Viewer only calls `warmup?.()` so\n * the WASM/transport boot overlaps plugin initialization. StrictMode's\n * double-mount therefore constructs two independent thunk engines and tears\n * the first fully down, matching the kernel's own effect-scoped lifecycle.\n * That means dev-only double resource use (two worker spawns, two font\n * fetches, briefly overlapping) — deliberate, because it is exactly the\n * leak-detection contract StrictMode exists to exercise; production mounts\n * once and boots once.\n */\nexport function Viewer({\n engine,\n plugins,\n initialDocuments,\n fallback,\n renderError,\n children,\n}: ViewerProps) {\n // Init-only inputs: the kernel's lifetime is the component's lifetime, so a\n // changed engine/plugins identity cannot mean \"rebuild the workspace\" —\n // that would silently drop every open document. Capture once, warn in dev.\n const initial = useRef({ engine, plugins, initialDocuments });\n const warned = useRef(false);\n if (process.env.NODE_ENV !== 'production' && !warned.current) {\n if (initial.current.engine !== engine || initial.current.plugins !== plugins) {\n warned.current = true;\n console.warn(\n '[embedpdf] <Viewer> engine/plugins are init-only. A changed identity is ignored — ' +\n 'pass stable references (module scope, useState, or useMemo). ' +\n 'An inline `plugins={[...]}` array recreates its identity every render.',\n );\n }\n }\n\n const [boot, setBoot] = useState<BootState>({ phase: 'booting', kernel: null });\n useEffect(() => {\n const captured = initial.current;\n // A thunk is viewer-owned: call it now, destroy on unmount. An instance is\n // borrowed: use as-is, never destroy. Construction is synchronous and inert\n // either way — the engine boots lazily on first use — so kick `warmup()`\n // to overlap the WASM/transport boot with plugin initialization.\n const ownsEngine = typeof captured.engine === 'function';\n const engine: Engine = ownsEngine\n ? (captured.engine as EngineFactory)()\n : (captured.engine as Engine);\n engine.warmup?.();\n let kernel: Kernel;\n try {\n kernel = createKernel({ engine, plugins: captured.plugins });\n } catch (error) {\n setBoot({ phase: 'error', error }); // plan/graph errors surface, not throw mid-render\n if (ownsEngine) void engine.destroy();\n return;\n }\n let alive = true;\n setBoot({ phase: 'booting', kernel }); // context carries the kernel from this frame on\n kernel.start().then(\n () => {\n if (!alive) return; // unmounted mid-boot — don't open anything\n setBoot({ phase: 'ready', kernel });\n // Kernel-owned boot policy: all tabs appear immediately in array\n // order; the `active` entry (else the first) is selected; failures\n // surface as tab status. See DocumentsCapability.openAll.\n kernel.documents.openAll(captured.initialDocuments ?? []);\n },\n (error) => {\n if (alive) setBoot({ phase: 'error', error });\n },\n );\n return () => {\n alive = false;\n // Kernel first (closes every document handle), THEN the engine we own —\n // ownership follows acquisition. `engine.destroy()` joins an in-flight\n // boot (or no-ops if it never started), so an unmount mid-boot is safe.\n void kernel.destroy().then(() => {\n if (ownsEngine) void engine.destroy();\n });\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n if (boot.phase === 'error') {\n return <>{renderError ? renderError(boot.error) : null}</>;\n }\n if (!boot.kernel) return null; // pre-effect first render only\n return (\n <KernelCtx.Provider value={boot.kernel}>\n {boot.phase === 'ready' ? children : (fallback ?? null)}\n </KernelCtx.Provider>\n );\n}\nexport const EmbedPDF = Viewer;\n\n/**\n * PageContext — the seam. A layer depends ONLY on this, never on the Stage. So the\n * same layer works inside a virtualized Stage and in a standalone <PageView>.\n */\nexport interface PageContextValue {\n documentId: string;\n /** Durable page identity (PDF object number) — use for keys / render / annotations. */\n pon: number;\n /** Display index (page N) — use for ordering / human-facing page numbers. */\n pageIndex: number;\n /**\n * Reserved chrome bands around the page (screen px per side). The page-chrome\n * slot renders into the outer box (content + frame); these thicknesses size\n * the bands — a label in the bottom band is `bottom:0; height: frame.bottom`.\n */\n frame: PageFrame;\n /**\n * The single bridge between PDF points, view px, and device px for this page.\n * Layers do ALL coordinate work through it — `toPixels` to place content-\n * space overlays, `renderScale`/`deviceWidth` to render, `contentWidth` for\n * page-relative sizing. Never re-derive `x * scale` or `* dpr`.\n */\n transform: PageTransform;\n /** Client (screen) point → the viewer's coordinates (content point) — the\n * one platform-bound hit-test. */\n toContentPoint(clientX: number, clientY: number): Point;\n /** Content point → client (screen) px — the exact inverse of `toContentPoint`\n * (rotation applied). Lets viewport-space UI (e.g. a selection menu) anchor to a\n * page point WITHOUT a Stage camera, so it works the same in `<PageView>`. */\n toClientPoint(p: Point): Point;\n /** Content rect → client (screen) px AABB. Rect analog of `toClientPoint`\n * for upright viewport-space UI that frames a selected page region. */\n toClientRect(rect: Rect): Rect;\n /**\n * The page-view DEMAND for raster planning uses dependency inversion:\n * plugin-render defines the shape; the host that CREATED this\n * context fills it — as a PULL. The Stage host's getter closes over the\n * stage capability and reads `VisiblePage.visibleRect` live at call time\n * (visibility is the STAGE's data; adapters never re-derive camera math or\n * cache a copy). Three states, three meanings: a real sub-rect (visible),\n * a ZERO rect (stage host, page currently off-screen — want nothing), and\n * an undefined getter (stage-less `<PageView>` — whole page visible, which\n * a thumbnail-sized demand turns into \"never engages\" by arithmetic).\n */\n getViewDemand?: () => PageViewDemand;\n /**\n * The hosting VIEW's identity — the stage lens id (`stage.lensId()`) or a\n * per-instance PageView id. IDENTITY, not an option: per-view raster\n * planning (tiles) keys its state by this, so two views showing the SAME\n * page never fight over one plan (a thumbnail rail's never-engaging demand\n * must not disturb the main view's tiles). Every page context host must\n * say which view it is.\n */\n view: string;\n}\n\nconst PageCtx = createContext<PageContextValue | null>(null);\nexport const PageProvider = PageCtx.Provider;\n\nexport function usePage(): PageContextValue {\n const c = useContext(PageCtx);\n if (!c) throw new Error('usePage must be used inside <PageView> or a <Stage> page');\n return c;\n}\n\nexport function makePageContext(\n documentId: string,\n view: string,\n pon: number,\n pageIndex: number,\n frame: PageFrame,\n transform: PageTransform,\n getRect: () => DOMRect,\n getViewDemand?: () => PageViewDemand,\n): PageContextValue {\n return {\n documentId,\n view,\n pon,\n pageIndex,\n frame,\n transform,\n ...(getViewDemand ? { getViewDemand } : {}),\n toContentPoint: (cx, cy) => {\n // `getRect()` is the rotated content wrapper's axis-aligned bounding box =\n // the page's DISPLAY box on screen. Convert client → box-local view px,\n // then invert rotation + scale via the transform (verified once in geometry,\n // not re-derived per framework adapter).\n const r = getRect();\n return transform.viewToContent({ x: cx - r.left, y: cy - r.top });\n },\n toClientPoint: (p) => {\n // Exact inverse of `toContentPoint`: page/content point → display-box view px\n // (rotation applied by the transform), offset by the same live display-box\n // origin. So the two can never drift, in either <Stage> or <PageView>.\n const r = getRect();\n const v = transform.contentToView(p);\n return { x: r.left + v.x, y: r.top + v.y };\n },\n toClientRect: (rect) => {\n const r = getRect();\n const v = transform.contentToViewRect(rect);\n return { x: r.left + v.x, y: r.top + v.y, width: v.width, height: v.height };\n },\n };\n}\n"],"mappings":";;;;;;;AAkCA,MAAM,aAAA,GAAA,MAAA,cAAA,CAAyC,IAAI;;AAEnD,MAAM,oBAAA,GAAA,MAAA,cAAA,CA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ACL;EACA;EACA;EACA;EACA;EACA;EACA,GAAI,gBAAgB,EAAE,cAAc,IAAI,CAAC;EACzC,iBAAiB,IAAI,OAAO;GAK1B,MAAM,IAAI,QAAQ;GAClB,OAAO,UAAU,cAAc;IAAE,GAAG,KAAK,EAAE;IAAM,GAAG,KAAK,EAAE;GAAI,CAAC;EAClE;EACA,gBAAgB,MAAM;GAIpB,MAAM,IAAI,QAAQ;GAClB,MAAM,IAAI,UAAU,cAAc,CAAC;GACnC,OAAO;IAAE,GAAG,EAAE,OAAO,EAAE;IAAG,GAAG,EAAE,MAAM,EAAE;GAAE;EAC3C;EACA,eAAe,SAAS;GACtB,MAAM,IAAI,QAAQ;GAClB,MAAM,IAAI,UAAU,kBAAkB,IAAI;GAC1C,OAAO;IAAE,GAAG,EAAE,OAAO,EAAE;IAAG,GAAG,EAAE,MAAM,EAAE;IAAG,OAAO,EAAE;IAAO,QAAQ,EAAE;GAAO;EAC7E;CACF;AACF"}
@@ -1,3 +1,3 @@
1
- import { S as useSelector, _ as useKernel, a as EmbedPDF, b as useOptionalSelector, c as Viewer, d as shallowArray, f as useActiveDocumentId, g as useDocuments, h as useDocumentStatus, i as DocumentScopeProps, l as ViewerProps, m as useDocumentId, n as DocumentGateProps, o as PageContextValue, p as useCapability, r as DocumentScope, s as PageProvider, t as DocumentGate, u as makePageContext, v as useKernelValue, x as usePage, y as useOptionalCapability } from "./runtime-CMxIuF2O.cjs";
1
+ import { C as useSelector, S as usePage, _ as useDocuments, a as EmbedPDF, b as useOptionalCapability, c as Viewer, f as shallowArray, g as useDocumentStatus, h as useDocumentId, i as DocumentScopeProps, l as ViewerProps, m as useCapability, n as DocumentGateProps, o as PageContextValue, p as useActiveDocumentId, r as DocumentScope, s as PageProvider, t as DocumentGate, u as makePageContext, v as useKernel, x as useOptionalSelector, y as useKernelValue } from "./runtime-Cvi0wQ4d.cjs";
2
2
  export * from "@embedpdf/core";
3
3
  export { DocumentGate, DocumentGateProps, DocumentScope, DocumentScopeProps, EmbedPDF, PageContextValue, PageProvider, Viewer, ViewerProps, makePageContext, shallowArray, useActiveDocumentId, useCapability, useDocumentId, useDocumentStatus, useDocuments, useKernel, useKernelValue, useOptionalCapability, useOptionalSelector, usePage, useSelector };
package/dist/runtime.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- import { S as useSelector, _ as useKernel, a as EmbedPDF, b as useOptionalSelector, c as Viewer, d as shallowArray, f as useActiveDocumentId, g as useDocuments, h as useDocumentStatus, i as DocumentScopeProps, l as ViewerProps, m as useDocumentId, n as DocumentGateProps, o as PageContextValue, p as useCapability, r as DocumentScope, s as PageProvider, t as DocumentGate, u as makePageContext, v as useKernelValue, x as usePage, y as useOptionalCapability } from "./runtime-DV98q7I0.js";
1
+ import { C as useSelector, S as usePage, _ as useDocuments, a as EmbedPDF, b as useOptionalCapability, c as Viewer, f as shallowArray, g as useDocumentStatus, h as useDocumentId, i as DocumentScopeProps, l as ViewerProps, m as useCapability, n as DocumentGateProps, o as PageContextValue, p as useActiveDocumentId, r as DocumentScope, s as PageProvider, t as DocumentGate, u as makePageContext, v as useKernel, x as useOptionalSelector, y as useKernelValue } from "./runtime-DXxr8T4L.js";
2
2
  export * from "@embedpdf/core";
3
3
  export { DocumentGate, DocumentGateProps, DocumentScope, DocumentScopeProps, EmbedPDF, PageContextValue, PageProvider, Viewer, ViewerProps, makePageContext, shallowArray, useActiveDocumentId, useCapability, useDocumentId, useDocumentStatus, useDocuments, useKernel, useKernelValue, useOptionalCapability, useOptionalSelector, usePage, useSelector };
package/dist/runtime.js CHANGED
@@ -1,3 +1,4 @@
1
+ import "./rolldown-runtime-BBjsoOtd.js";
1
2
  import { Fragment, jsx } from "react/jsx-runtime";
2
3
  import { createKernel, docInfoListEquals } from "@embedpdf/core";
3
4
  import { createContext, useContext, useEffect, useRef, useState, useSyncExternalStore } from "react";
@@ -246,24 +247,25 @@ function usePage() {
246
247
  if (!c) throw new Error("usePage must be used inside <PageView> or a <Stage> page");
247
248
  return c;
248
249
  }
249
- function makePageContext(documentId, pon, pageIndex, frame, transform, getRect, getViewDemand) {
250
+ function makePageContext(documentId, view, pon, pageIndex, frame, transform, getRect, getViewDemand) {
250
251
  return {
251
252
  documentId,
253
+ view,
252
254
  pon,
253
255
  pageIndex,
254
256
  frame,
255
257
  transform,
256
258
  ...getViewDemand ? { getViewDemand } : {},
257
- toPagePoint: (cx, cy) => {
259
+ toContentPoint: (cx, cy) => {
258
260
  const r = getRect();
259
- return transform.viewToPage({
261
+ return transform.viewToContent({
260
262
  x: cx - r.left,
261
263
  y: cy - r.top
262
264
  });
263
265
  },
264
266
  toClientPoint: (p) => {
265
267
  const r = getRect();
266
- const v = transform.pageToView(p);
268
+ const v = transform.contentToView(p);
267
269
  return {
268
270
  x: r.left + v.x,
269
271
  y: r.top + v.y
@@ -271,7 +273,7 @@ function makePageContext(documentId, pon, pageIndex, frame, transform, getRect,
271
273
  },
272
274
  toClientRect: (rect) => {
273
275
  const r = getRect();
274
- const v = transform.pageToViewRect(rect);
276
+ const v = transform.contentToViewRect(rect);
275
277
  return {
276
278
  x: r.left + v.x,
277
279
  y: r.top + v.y,
@@ -1 +1 @@
1
- {"version":3,"file":"runtime.js","names":[],"sources":["../src/runtime.tsx"],"sourcesContent":["/**\n * @embedpdf/react — the generic binding.\n *\n * Binds the kernel's one change stream to React (useSyncExternalStore), resolves\n * capabilities (document-scoped ones against the active or `<DocumentScope>`-given\n * document), and provides the page coordinate context. Every plugin and layer rides\n * on this — there is no per-plugin framework code.\n */\n\n// One-line-per-feature: registration travels with the UI.\nexport * from '@embedpdf/core';\nimport * as React from 'react';\nimport {\n createContext,\n useContext,\n useEffect,\n useRef,\n useState,\n useSyncExternalStore,\n} from 'react';\nimport { createKernel, docInfoListEquals } from '@embedpdf/core';\nimport type {\n AnyPlugin,\n CapabilityToken,\n Engine,\n EngineFactory,\n InitialDocument,\n Kernel,\n} from '@embedpdf/core';\n// Pure coordinate math from the geometry base — NOT from stage-core. The\n// PageContext seam stays stage-agnostic (it must also serve standalone PageView).\nimport type { PageFrame, PageTransform, Point, Rect } from '@embedpdf/core-geometry';\nimport type { PageViewDemand } from '@embedpdf/plugin-render';\n\nconst KernelCtx = createContext<Kernel | null>(null);\n/** The document a subtree is bound to. null => use the active document. */\nconst DocumentScopeCtx = createContext<string | null>(null);\n\nexport function useKernel(): Kernel {\n const k = useContext(KernelCtx);\n if (!k) throw new Error('useKernel must be used within <Viewer>/<EmbedPDF>');\n return k;\n}\n\nexport const shallowArray = <T,>(a: readonly T[], b: readonly T[]): boolean =>\n a === b || (a.length === b.length && a.every((x, i) => x === b[i]));\n\n/** Read a value derived from the kernel, cached by equality (no tearing loop). */\nexport function useKernelValue<R>(\n select: (k: Kernel) => R,\n isEqual: (a: R, b: R) => boolean = Object.is,\n): R {\n const kernel = useKernel();\n const last = useRef<{ v: R } | null>(null);\n const get = () => {\n const next = select(kernel);\n if (last.current && isEqual(last.current.v, next)) return last.current.v;\n last.current = { v: next };\n return next;\n };\n return useSyncExternalStore(kernel.subscribe, get, get);\n}\n\nexport function useActiveDocumentId(): string | null {\n return useKernelValue((k) => k.documents.activeId());\n}\n\n/** The document id for this subtree: the nearest <DocumentScope>, else the active doc. */\nexport function useDocumentId(): string | null {\n const scoped = useContext(DocumentScopeCtx);\n const active = useActiveDocumentId();\n return scoped ?? active;\n}\n\nexport interface DocumentScopeProps {\n id: string;\n children: React.ReactNode;\n}\n/** Bind a subtree to a specific document (panes, comparison). */\nexport function DocumentScope({ id, children }: DocumentScopeProps) {\n return <DocumentScopeCtx.Provider value={id}>{children}</DocumentScopeCtx.Provider>;\n}\n\nexport interface DocumentGateProps {\n /** Shown while this subtree has NO document (empty workspace, docs still opening). */\n fallback?: React.ReactNode;\n children: React.ReactNode;\n}\n/**\n * Render children only while this subtree has a READY document — the\n * structural way to say \"this UI is defined over a document\". An empty\n * workspace is a legitimate, designable state (the Viewer no longer blocks on\n * documents so chrome can render at t≈0): workspace-scoped UI (toolbars,\n * commands, i18n) lives OUTSIDE the gate; document-scoped UI (Stage, panels,\n * page chrome) lives inside it, or reads through `useOptionalSelector`.\n * A `loading`/`locked`/`error` tab renders `fallback` — so the gate's\n * fallback doubles as the per-tab boot state; richer chrome (a password\n * prompt, an error pane) branches on `useDocumentStatus()` beside the gate.\n * Sibling of <DocumentScope>, which picks WHICH document; this one handles\n * WHETHER.\n */\nexport function DocumentGate({ fallback = null, children }: DocumentGateProps) {\n const docId = useDocumentId();\n const ready = useKernelValue((k) => (docId ? k.documents.get(docId)?.status === 'ready' : false));\n return <>{ready ? children : fallback}</>;\n}\n\n/** Lifecycle status of this subtree's document (loading/locked/ready/error),\n * or null with no document. The password prompt and error panes key off it. */\nexport function useDocumentStatus() {\n const docId = useDocumentId();\n return useKernelValue((k) => (docId ? (k.documents.get(docId)?.status ?? null) : null));\n}\n\n/**\n * Resolve a capability by token, binding document-scoped ones to this\n * subtree's document. Resolution is a REACTIVE read (`tryCapability` through\n * the kernel's one change stream), not a memoized call — under the\n * request-time lifecycle a document can become resolvable while its id stays\n * the same, so any id-keyed cache goes stale; subscribing makes staleness\n * structurally impossible. Fail-fast: while unresolvable, this re-runs the\n * strict resolver so the kernel's truthful reason (`no capability` / `no\n * document` / `document is loading|locked`) is what throws.\n */\nexport function useCapability<T>(token: CapabilityToken<T>): T {\n const kernel = useKernel();\n const scoped = useContext(DocumentScopeCtx);\n const cap = useKernelValue((k) => k.tryCapability(token, scoped ?? undefined));\n return cap ?? kernel.capability(token, scoped ?? undefined);\n}\n\n/** Like `useCapability`, but null while the token can't resolve (no plugin,\n * no document, or a document that isn't ready yet). */\nexport function useOptionalCapability<T>(token: CapabilityToken<T>): T | null {\n const scoped = useContext(DocumentScopeCtx);\n return useKernelValue((k) => k.tryCapability(token, scoped ?? undefined));\n}\n\n/** Subscribe to a selector over a (document-resolved) capability. */\nexport function useSelector<C, R>(\n token: CapabilityToken<C>,\n select: (cap: C) => R,\n isEqual: (a: R, b: R) => boolean = Object.is,\n): R {\n const kernel = useKernel();\n const cap = useCapability(token);\n const last = useRef<{ v: R } | null>(null);\n const get = () => {\n const next = select(cap);\n if (last.current && isEqual(last.current.v, next)) return last.current.v;\n last.current = { v: next };\n return next;\n };\n return useSyncExternalStore(kernel.subscribe, get, get);\n}\n\n/**\n * Null-safe `useSelector`: `fallback` whenever the token can't resolve — no\n * provider, or a document-scoped token with no document. For chrome that stays\n * mounted across the empty-workspace state (a zoom readout, a mode band).\n * `useSelector` stays strict (fail-fast) for code that KNOWS a document exists\n * — e.g. anything inside a <DocumentGate>.\n *\n * The `select` guard also swallows reads through a capability whose document\n * closed between the store notification and this render — that teardown race\n * resolves to `fallback` for one frame, then re-renders against the new state.\n */\nexport function useOptionalSelector<C, R>(\n token: CapabilityToken<C>,\n select: (cap: C) => R,\n fallback: R,\n isEqual: (a: R, b: R) => boolean = Object.is,\n): R {\n const kernel = useKernel();\n const cap = useOptionalCapability(token);\n const last = useRef<{ v: R } | null>(null);\n const get = () => {\n let next: R;\n if (cap === null) {\n next = fallback;\n } else {\n try {\n next = select(cap);\n } catch {\n next = fallback;\n }\n }\n if (last.current && isEqual(last.current.v, next)) return last.current.v;\n last.current = { v: next };\n return next;\n };\n return useSyncExternalStore(kernel.subscribe, get, get);\n}\n\n/** The document registry (open/close/active/list), reactive. */\nexport function useDocuments() {\n const kernel = useKernel();\n const docs = useKernelValue((k) => k.documents.list(), docInfoListEquals);\n const activeId = useActiveDocumentId();\n return {\n docs,\n activeId,\n open: kernel.documents.open,\n unlock: kernel.documents.unlock,\n close: kernel.documents.close,\n setActive: kernel.documents.setActive,\n move: kernel.documents.move,\n swap: kernel.documents.swap,\n download: kernel.documents.download,\n downloadLayer: kernel.documents.downloadLayer,\n };\n}\n\n// `InitialDocument` is the KERNEL's type (re-exported via `export * from\n// '@embedpdf/core'` above) — one shared shape for every adapter.\n\nexport interface ViewerProps {\n /**\n * The engine, as an instance or a thunk. Engines construct synchronously and\n * boot lazily (`localEngine()` allocates nothing until first use), so\n * ownership follows the SHAPE of what you pass:\n *\n * - An **instance** (`engine={engine}`) is BORROWED: the Viewer uses it and\n * never destroys it, because you acquired it and therefore own it. The\n * common path — a module-scope `const engine = localEngine()` shared\n * across viewers and route changes. The Viewer calls `engine.warmup?.()`\n * on mount so the boot overlaps app initialization.\n * - A **thunk** (`engine={() => localEngine()}`) is VIEWER-OWNED: the\n * Viewer calls it on mount and `destroy()`s the result on unmount. Use it\n * for per-mount isolation (StrictMode/HMR-clean teardown, independent\n * multi-viewer engines).\n *\n * Init-only: captured on first render; later identity changes are ignored (dev warns).\n */\n engine: Engine | EngineFactory;\n /** Init-only: captured on first render; later identity changes are ignored (dev warns). */\n plugins: AnyPlugin[];\n /** Documents to open on startup (with optional tab names). Init-only. */\n initialDocuments?: InitialDocument[];\n fallback?: React.ReactNode;\n /** Rendered when kernel construction or `start()` fails. Without it a boot\n * failure renders nothing — but never a silent forever-fallback. */\n renderError?: (error: unknown) => React.ReactNode;\n children: React.ReactNode;\n}\n\ntype BootState =\n | { phase: 'booting'; kernel: Kernel | null }\n | { phase: 'ready'; kernel: Kernel }\n | { phase: 'error'; error: unknown };\n\n/**\n * Owns the kernel as an EFFECT-scoped resource: each effect setup creates and\n * starts exactly one kernel; each cleanup destroys exactly that one. That is\n * the contract StrictMode exercises (two kernels in dev, the first fully\n * destroyed) — the kernel itself is never restarted after destroy.\n *\n * The kernel is published to context the moment it exists — before `start()`\n * resolves — so the `fallback` can use workspace capabilities (i18n copy on a\n * loading screen) exactly as before. The one exception is the very first\n * render, which happens before the effect: it renders nothing. Children mount\n * once `start()` resolves — which never touches the engine, so the shell is\n * alive while WASM compiles or the transport connects. `initialDocuments`\n * open in the BACKGROUND and stream into the registry (`useDocuments()` is\n * reactive); per-document loading UI is the Stage's job, not a root gate.\n *\n * ENGINE OWNERSHIP. When `engine` is a thunk, the Viewer OWNS it: each effect\n * setup constructs one engine (construction is synchronous and inert — boot\n * happens lazily inside the engine) and each cleanup destroys exactly that one\n * — after the kernel, so handles close first. When `engine` is an instance it\n * is BORROWED and never destroyed here; the Viewer only calls `warmup?.()` so\n * the WASM/transport boot overlaps plugin initialization. StrictMode's\n * double-mount therefore constructs two independent thunk engines and tears\n * the first fully down, matching the kernel's own effect-scoped lifecycle.\n * That means dev-only double resource use (two worker spawns, two font\n * fetches, briefly overlapping) — deliberate, because it is exactly the\n * leak-detection contract StrictMode exists to exercise; production mounts\n * once and boots once.\n */\nexport function Viewer({\n engine,\n plugins,\n initialDocuments,\n fallback,\n renderError,\n children,\n}: ViewerProps) {\n // Init-only inputs: the kernel's lifetime is the component's lifetime, so a\n // changed engine/plugins identity cannot mean \"rebuild the workspace\" —\n // that would silently drop every open document. Capture once, warn in dev.\n const initial = useRef({ engine, plugins, initialDocuments });\n const warned = useRef(false);\n if (process.env.NODE_ENV !== 'production' && !warned.current) {\n if (initial.current.engine !== engine || initial.current.plugins !== plugins) {\n warned.current = true;\n console.warn(\n '[embedpdf] <Viewer> engine/plugins are init-only. A changed identity is ignored — ' +\n 'pass stable references (module scope, useState, or useMemo). ' +\n 'An inline `plugins={[...]}` array recreates its identity every render.',\n );\n }\n }\n\n const [boot, setBoot] = useState<BootState>({ phase: 'booting', kernel: null });\n useEffect(() => {\n const captured = initial.current;\n // A thunk is viewer-owned: call it now, destroy on unmount. An instance is\n // borrowed: use as-is, never destroy. Construction is synchronous and inert\n // either way — the engine boots lazily on first use — so kick `warmup()`\n // to overlap the WASM/transport boot with plugin initialization.\n const ownsEngine = typeof captured.engine === 'function';\n const engine: Engine = ownsEngine\n ? (captured.engine as EngineFactory)()\n : (captured.engine as Engine);\n engine.warmup?.();\n let kernel: Kernel;\n try {\n kernel = createKernel({ engine, plugins: captured.plugins });\n } catch (error) {\n setBoot({ phase: 'error', error }); // plan/graph errors surface, not throw mid-render\n if (ownsEngine) void engine.destroy();\n return;\n }\n let alive = true;\n setBoot({ phase: 'booting', kernel }); // context carries the kernel from this frame on\n kernel.start().then(\n () => {\n if (!alive) return; // unmounted mid-boot — don't open anything\n setBoot({ phase: 'ready', kernel });\n // Kernel-owned boot policy: all tabs appear immediately in array\n // order; the `active` entry (else the first) is selected; failures\n // surface as tab status. See DocumentsCapability.openAll.\n kernel.documents.openAll(captured.initialDocuments ?? []);\n },\n (error) => {\n if (alive) setBoot({ phase: 'error', error });\n },\n );\n return () => {\n alive = false;\n // Kernel first (closes every document handle), THEN the engine we own —\n // ownership follows acquisition. `engine.destroy()` joins an in-flight\n // boot (or no-ops if it never started), so an unmount mid-boot is safe.\n void kernel.destroy().then(() => {\n if (ownsEngine) void engine.destroy();\n });\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n if (boot.phase === 'error') {\n return <>{renderError ? renderError(boot.error) : null}</>;\n }\n if (!boot.kernel) return null; // pre-effect first render only\n return (\n <KernelCtx.Provider value={boot.kernel}>\n {boot.phase === 'ready' ? children : (fallback ?? null)}\n </KernelCtx.Provider>\n );\n}\nexport const EmbedPDF = Viewer;\n\n/**\n * PageContext — the seam. A layer depends ONLY on this, never on the Stage. So the\n * same layer works inside a virtualized Stage and in a standalone <PageView>.\n */\nexport interface PageContextValue {\n documentId: string;\n /** Durable page identity (PDF object number) — use for keys / render / annotations. */\n pon: number;\n /** Display index (page N) — use for ordering / human-facing page numbers. */\n pageIndex: number;\n /**\n * Reserved chrome bands around the page (screen px per side). The page-chrome\n * slot renders into the outer box (content + frame); these thicknesses size\n * the bands — a label in the bottom band is `bottom:0; height: frame.bottom`.\n */\n frame: PageFrame;\n /**\n * The single bridge between PDF points, view px, and device px for this page.\n * Layers do ALL coordinate work through it — `pageToContent` to place content-\n * space overlays, `renderScale`/`deviceWidth` to render, `contentWidth` for\n * page-relative sizing. Never re-derive `x * scale` or `* dpr`.\n */\n transform: PageTransform;\n /** Client (screen) point → PDF point — the one platform-bound hit-test. */\n toPagePoint(clientX: number, clientY: number): Point;\n /** PDF/content point → client (screen) px — the exact inverse of `toPagePoint`\n * (rotation applied). Lets viewport-space UI (e.g. a selection menu) anchor to a\n * page point WITHOUT a Stage camera, so it works the same in `<PageView>`. */\n toClientPoint(p: Point): Point;\n /** PDF/content rect → client (screen) px AABB. Rect analog of `toClientPoint`\n * for upright viewport-space UI that frames a selected page region. */\n toClientRect(rect: Rect): Rect;\n /**\n * The page-view DEMAND for raster planning uses dependency inversion:\n * plugin-render defines the shape; the host that CREATED this\n * context fills it — as a PULL. The Stage host's getter closes over the\n * stage capability and reads `VisiblePage.visibleRect` live at call time\n * (visibility is the STAGE's data; adapters never re-derive camera math or\n * cache a copy). Three states, three meanings: a real sub-rect (visible),\n * a ZERO rect (stage host, page currently off-screen — want nothing), and\n * an undefined getter (stage-less `<PageView>` — whole page visible, which\n * a thumbnail-sized demand turns into \"never engages\" by arithmetic).\n */\n getViewDemand?: () => PageViewDemand;\n}\n\nconst PageCtx = createContext<PageContextValue | null>(null);\nexport const PageProvider = PageCtx.Provider;\n\nexport function usePage(): PageContextValue {\n const c = useContext(PageCtx);\n if (!c) throw new Error('usePage must be used inside <PageView> or a <Stage> page');\n return c;\n}\n\nexport function makePageContext(\n documentId: string,\n pon: number,\n pageIndex: number,\n frame: PageFrame,\n transform: PageTransform,\n getRect: () => DOMRect,\n getViewDemand?: () => PageViewDemand,\n): PageContextValue {\n return {\n documentId,\n pon,\n pageIndex,\n frame,\n transform,\n ...(getViewDemand ? { getViewDemand } : {}),\n toPagePoint: (cx, cy) => {\n // `getRect()` is the rotated content wrapper's axis-aligned bounding box =\n // the page's DISPLAY box on screen. Convert client → box-local view px,\n // then invert rotation + scale via the transform (verified once in geometry,\n // not re-derived per framework adapter).\n const r = getRect();\n return transform.viewToPage({ x: cx - r.left, y: cy - r.top });\n },\n toClientPoint: (p) => {\n // Exact inverse of `toPagePoint`: page/content point → display-box view px\n // (rotation applied by the transform), offset by the same live display-box\n // origin. So the two can never drift, in either <Stage> or <PageView>.\n const r = getRect();\n const v = transform.pageToView(p);\n return { x: r.left + v.x, y: r.top + v.y };\n },\n toClientRect: (rect) => {\n const r = getRect();\n const v = transform.pageToViewRect(r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AE,OAAO,EAAE;IAAG,GAAG,EAAE,MAAM,EAAE;GAAE;EAC3C;EACA,eAAe,SAAS;GACtB,MAAM,IAAI,QAAQ;GAClB,MAAM,IAAI,UAAU,eAAe,IAAI;GACvC,OAAO;IAAE,GAAG,EAAE,OAAO,EAAE;IAAG,GAAG,EAAE,MAAM,EAAE;IAAG,OAAO,EAAE;IAAO,QAAQ,EAAE;GAAO;EAC7E;CACF;AACF"}
1
+ {"version":3,"file":"runtime.js","names":[],"sources":["../src/runtime.tsx"],"sourcesContent":["/**\n * @embedpdf/react — the generic binding.\n *\n * Binds the kernel's one change stream to React (useSyncExternalStore), resolves\n * capabilities (document-scoped ones against the active or `<DocumentScope>`-given\n * document), and provides the page coordinate context. Every plugin and layer rides\n * on this — there is no per-plugin framework code.\n */\n\n// One-line-per-feature: registration travels with the UI.\nexport * from '@embedpdf/core';\nimport * as React from 'react';\nimport {\n createContext,\n useContext,\n useEffect,\n useRef,\n useState,\n useSyncExternalStore,\n} from 'react';\nimport { createKernel, docInfoListEquals } from '@embedpdf/core';\nimport type {\n AnyPlugin,\n CapabilityToken,\n Engine,\n EngineFactory,\n InitialDocument,\n Kernel,\n} from '@embedpdf/core';\n// Pure coordinate math from the geometry base — NOT from stage-core. The\n// PageContext seam stays stage-agnostic (it must also serve standalone PageView).\nimport type { PageFrame, PageTransform, Point, Rect } from '@embedpdf/core-geometry';\nimport type { PageViewDemand } from '@embedpdf/plugin-render';\n\nconst KernelCtx = createContext<Kernel | null>(null);\n/** The document a subtree is bound to. null => use the active document. */\nconst DocumentScopeCtx = createContext<string | null>(null);\n\nexport function useKernel(): Kernel {\n const k = useContext(KernelCtx);\n if (!k) throw new Error('useKernel must be used within <Viewer>/<EmbedPDF>');\n return k;\n}\n\nexport const shallowArray = <T,>(a: readonly T[], b: readonly T[]): boolean =>\n a === b || (a.length === b.length && a.every((x, i) => x === b[i]));\n\n/** Read a value derived from the kernel, cached by equality (no tearing loop). */\nexport function useKernelValue<R>(\n select: (k: Kernel) => R,\n isEqual: (a: R, b: R) => boolean = Object.is,\n): R {\n const kernel = useKernel();\n const last = useRef<{ v: R } | null>(null);\n const get = () => {\n const next = select(kernel);\n if (last.current && isEqual(last.current.v, next)) return last.current.v;\n last.current = { v: next };\n return next;\n };\n return useSyncExternalStore(kernel.subscribe, get, get);\n}\n\nexport function useActiveDocumentId(): string | null {\n return useKernelValue((k) => k.documents.activeId());\n}\n\n/** The document id for this subtree: the nearest <DocumentScope>, else the active doc. */\nexport function useDocumentId(): string | null {\n const scoped = useContext(DocumentScopeCtx);\n const active = useActiveDocumentId();\n return scoped ?? active;\n}\n\nexport interface DocumentScopeProps {\n id: string;\n children: React.ReactNode;\n}\n/** Bind a subtree to a specific document (panes, comparison). */\nexport function DocumentScope({ id, children }: DocumentScopeProps) {\n return <DocumentScopeCtx.Provider value={id}>{children}</DocumentScopeCtx.Provider>;\n}\n\nexport interface DocumentGateProps {\n /** Shown while this subtree has NO document (empty workspace, docs still opening). */\n fallback?: React.ReactNode;\n children: React.ReactNode;\n}\n/**\n * Render children only while this subtree has a READY document — the\n * structural way to say \"this UI is defined over a document\". An empty\n * workspace is a legitimate, designable state (the Viewer no longer blocks on\n * documents so chrome can render at t≈0): workspace-scoped UI (toolbars,\n * commands, i18n) lives OUTSIDE the gate; document-scoped UI (Stage, panels,\n * page chrome) lives inside it, or reads through `useOptionalSelector`.\n * A `loading`/`locked`/`error` tab renders `fallback` — so the gate's\n * fallback doubles as the per-tab boot state; richer chrome (a password\n * prompt, an error pane) branches on `useDocumentStatus()` beside the gate.\n * Sibling of <DocumentScope>, which picks WHICH document; this one handles\n * WHETHER.\n */\nexport function DocumentGate({ fallback = null, children }: DocumentGateProps) {\n const docId = useDocumentId();\n const ready = useKernelValue((k) => (docId ? k.documents.get(docId)?.status === 'ready' : false));\n return <>{ready ? children : fallback}</>;\n}\n\n/** Lifecycle status of this subtree's document (loading/locked/ready/error),\n * or null with no document. The password prompt and error panes key off it. */\nexport function useDocumentStatus() {\n const docId = useDocumentId();\n return useKernelValue((k) => (docId ? (k.documents.get(docId)?.status ?? null) : null));\n}\n\n/**\n * Resolve a capability by token, binding document-scoped ones to this\n * subtree's document. Resolution is a REACTIVE read (`tryCapability` through\n * the kernel's one change stream), not a memoized call — under the\n * request-time lifecycle a document can become resolvable while its id stays\n * the same, so any id-keyed cache goes stale; subscribing makes staleness\n * structurally impossible. Fail-fast: while unresolvable, this re-runs the\n * strict resolver so the kernel's truthful reason (`no capability` / `no\n * document` / `document is loading|locked`) is what throws.\n */\nexport function useCapability<T>(token: CapabilityToken<T>): T {\n const kernel = useKernel();\n const scoped = useContext(DocumentScopeCtx);\n const cap = useKernelValue((k) => k.tryCapability(token, scoped ?? undefined));\n return cap ?? kernel.capability(token, scoped ?? undefined);\n}\n\n/** Like `useCapability`, but null while the token can't resolve (no plugin,\n * no document, or a document that isn't ready yet). */\nexport function useOptionalCapability<T>(token: CapabilityToken<T>): T | null {\n const scoped = useContext(DocumentScopeCtx);\n return useKernelValue((k) => k.tryCapability(token, scoped ?? undefined));\n}\n\n/** Subscribe to a selector over a (document-resolved) capability. */\nexport function useSelector<C, R>(\n token: CapabilityToken<C>,\n select: (cap: C) => R,\n isEqual: (a: R, b: R) => boolean = Object.is,\n): R {\n const kernel = useKernel();\n const cap = useCapability(token);\n const last = useRef<{ v: R } | null>(null);\n const get = () => {\n const next = select(cap);\n if (last.current && isEqual(last.current.v, next)) return last.current.v;\n last.current = { v: next };\n return next;\n };\n return useSyncExternalStore(kernel.subscribe, get, get);\n}\n\n/**\n * Null-safe `useSelector`: `fallback` whenever the token can't resolve — no\n * provider, or a document-scoped token with no document. For chrome that stays\n * mounted across the empty-workspace state (a zoom readout, a mode band).\n * `useSelector` stays strict (fail-fast) for code that KNOWS a document exists\n * — e.g. anything inside a <DocumentGate>.\n *\n * The `select` guard also swallows reads through a capability whose document\n * closed between the store notification and this render — that teardown race\n * resolves to `fallback` for one frame, then re-renders against the new state.\n */\nexport function useOptionalSelector<C, R>(\n token: CapabilityToken<C>,\n select: (cap: C) => R,\n fallback: R,\n isEqual: (a: R, b: R) => boolean = Object.is,\n): R {\n const kernel = useKernel();\n const cap = useOptionalCapability(token);\n const last = useRef<{ v: R } | null>(null);\n const get = () => {\n let next: R;\n if (cap === null) {\n next = fallback;\n } else {\n try {\n next = select(cap);\n } catch {\n next = fallback;\n }\n }\n if (last.current && isEqual(last.current.v, next)) return last.current.v;\n last.current = { v: next };\n return next;\n };\n return useSyncExternalStore(kernel.subscribe, get, get);\n}\n\n/** The document registry (open/close/active/list), reactive. */\nexport function useDocuments() {\n const kernel = useKernel();\n const docs = useKernelValue((k) => k.documents.list(), docInfoListEquals);\n const activeId = useActiveDocumentId();\n return {\n docs,\n activeId,\n open: kernel.documents.open,\n unlock: kernel.documents.unlock,\n close: kernel.documents.close,\n setActive: kernel.documents.setActive,\n move: kernel.documents.move,\n swap: kernel.documents.swap,\n download: kernel.documents.download,\n downloadLayer: kernel.documents.downloadLayer,\n };\n}\n\n// `InitialDocument` is the KERNEL's type (re-exported via `export * from\n// '@embedpdf/core'` above) — one shared shape for every adapter.\n\nexport interface ViewerProps {\n /**\n * The engine, as an instance or a thunk. Engines construct synchronously and\n * boot lazily (`localEngine()` allocates nothing until first use), so\n * ownership follows the SHAPE of what you pass:\n *\n * - An **instance** (`engine={engine}`) is BORROWED: the Viewer uses it and\n * never destroys it, because you acquired it and therefore own it. The\n * common path — a module-scope `const engine = localEngine()` shared\n * across viewers and route changes. The Viewer calls `engine.warmup?.()`\n * on mount so the boot overlaps app initialization.\n * - A **thunk** (`engine={() => localEngine()}`) is VIEWER-OWNED: the\n * Viewer calls it on mount and `destroy()`s the result on unmount. Use it\n * for per-mount isolation (StrictMode/HMR-clean teardown, independent\n * multi-viewer engines).\n *\n * Init-only: captured on first render; later identity changes are ignored (dev warns).\n */\n engine: Engine | EngineFactory;\n /** Init-only: captured on first render; later identity changes are ignored (dev warns). */\n plugins: AnyPlugin[];\n /** Documents to open on startup (with optional tab names). Init-only. */\n initialDocuments?: InitialDocument[];\n fallback?: React.ReactNode;\n /** Rendered when kernel construction or `start()` fails. Without it a boot\n * failure renders nothing — but never a silent forever-fallback. */\n renderError?: (error: unknown) => React.ReactNode;\n children: React.ReactNode;\n}\n\ntype BootState =\n | { phase: 'booting'; kernel: Kernel | null }\n | { phase: 'ready'; kernel: Kernel }\n | { phase: 'error'; error: unknown };\n\n/**\n * Owns the kernel as an EFFECT-scoped resource: each effect setup creates and\n * starts exactly one kernel; each cleanup destroys exactly that one. That is\n * the contract StrictMode exercises (two kernels in dev, the first fully\n * destroyed) — the kernel itself is never restarted after destroy.\n *\n * The kernel is published to context the moment it exists — before `start()`\n * resolves — so the `fallback` can use workspace capabilities (i18n copy on a\n * loading screen) exactly as before. The one exception is the very first\n * render, which happens before the effect: it renders nothing. Children mount\n * once `start()` resolves — which never touches the engine, so the shell is\n * alive while WASM compiles or the transport connects. `initialDocuments`\n * open in the BACKGROUND and stream into the registry (`useDocuments()` is\n * reactive); per-document loading UI is the Stage's job, not a root gate.\n *\n * ENGINE OWNERSHIP. When `engine` is a thunk, the Viewer OWNS it: each effect\n * setup constructs one engine (construction is synchronous and inert — boot\n * happens lazily inside the engine) and each cleanup destroys exactly that one\n * — after the kernel, so handles close first. When `engine` is an instance it\n * is BORROWED and never destroyed here; the Viewer only calls `warmup?.()` so\n * the WASM/transport boot overlaps plugin initialization. StrictMode's\n * double-mount therefore constructs two independent thunk engines and tears\n * the first fully down, matching the kernel's own effect-scoped lifecycle.\n * That means dev-only double resource use (two worker spawns, two font\n * fetches, briefly overlapping) — deliberate, because it is exactly the\n * leak-detection contract StrictMode exists to exercise; production mounts\n * once and boots once.\n */\nexport function Viewer({\n engine,\n plugins,\n initialDocuments,\n fallback,\n renderError,\n children,\n}: ViewerProps) {\n // Init-only inputs: the kernel's lifetime is the component's lifetime, so a\n // changed engine/plugins identity cannot mean \"rebuild the workspace\" —\n // that would silently drop every open document. Capture once, warn in dev.\n const initial = useRef({ engine, plugins, initialDocuments });\n const warned = useRef(false);\n if (process.env.NODE_ENV !== 'production' && !warned.current) {\n if (initial.current.engine !== engine || initial.current.plugins !== plugins) {\n warned.current = true;\n console.warn(\n '[embedpdf] <Viewer> engine/plugins are init-only. A changed identity is ignored — ' +\n 'pass stable references (module scope, useState, or useMemo). ' +\n 'An inline `plugins={[...]}` array recreates its identity every render.',\n );\n }\n }\n\n const [boot, setBoot] = useState<BootState>({ phase: 'booting', kernel: null });\n useEffect(() => {\n const captured = initial.current;\n // A thunk is viewer-owned: call it now, destroy on unmount. An instance is\n // borrowed: use as-is, never destroy. Construction is synchronous and inert\n // either way — the engine boots lazily on first use — so kick `warmup()`\n // to overlap the WASM/transport boot with plugin initialization.\n const ownsEngine = typeof captured.engine === 'function';\n const engine: Engine = ownsEngine\n ? (captured.engine as EngineFactory)()\n : (captured.engine as Engine);\n engine.warmup?.();\n let kernel: Kernel;\n try {\n kernel = createKernel({ engine, plugins: captured.plugins });\n } catch (error) {\n setBoot({ phase: 'error', error }); // plan/graph errors surface, not throw mid-render\n if (ownsEngine) void engine.destroy();\n return;\n }\n let alive = true;\n setBoot({ phase: 'booting', kernel }); // context carries the kernel from this frame on\n kernel.start().then(\n () => {\n if (!alive) return; // unmounted mid-boot — don't open anything\n setBoot({ phase: 'ready', kernel });\n // Kernel-owned boot policy: all tabs appear immediately in array\n // order; the `active` entry (else the first) is selected; failures\n // surface as tab status. See DocumentsCapability.openAll.\n kernel.documents.openAll(captured.initialDocuments ?? []);\n },\n (error) => {\n if (alive) setBoot({ phase: 'error', error });\n },\n );\n return () => {\n alive = false;\n // Kernel first (closes every document handle), THEN the engine we own —\n // ownership follows acquisition. `engine.destroy()` joins an in-flight\n // boot (or no-ops if it never started), so an unmount mid-boot is safe.\n void kernel.destroy().then(() => {\n if (ownsEngine) void engine.destroy();\n });\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n if (boot.phase === 'error') {\n return <>{renderError ? renderError(boot.error) : null}</>;\n }\n if (!boot.kernel) return null; // pre-effect first render only\n return (\n <KernelCtx.Provider value={boot.kernel}>\n {boot.phase === 'ready' ? children : (fallback ?? null)}\n </KernelCtx.Provider>\n );\n}\nexport const EmbedPDF = Viewer;\n\n/**\n * PageContext — the seam. A layer depends ONLY on this, never on the Stage. So the\n * same layer works inside a virtualized Stage and in a standalone <PageView>.\n */\nexport interface PageContextValue {\n documentId: string;\n /** Durable page identity (PDF object number) — use for keys / render / annotations. */\n pon: number;\n /** Display index (page N) — use for ordering / human-facing page numbers. */\n pageIndex: number;\n /**\n * Reserved chrome bands around the page (screen px per side). The page-chrome\n * slot renders into the outer box (content + frame); these thicknesses size\n * the bands — a label in the bottom band is `bottom:0; height: frame.bottom`.\n */\n frame: PageFrame;\n /**\n * The single bridge between PDF points, view px, and device px for this page.\n * Layers do ALL coordinate work through it — `toPixels` to place content-\n * space overlays, `renderScale`/`deviceWidth` to render, `contentWidth` for\n * page-relative sizing. Never re-derive `x * scale` or `* dpr`.\n */\n transform: PageTransform;\n /** Client (screen) point → the viewer's coordinates (content point) — the\n * one platform-bound hit-test. */\n toContentPoint(clientX: number, clientY: number): Point;\n /** Content point → client (screen) px — the exact inverse of `toContentPoint`\n * (rotation applied). Lets viewport-space UI (e.g. a selection menu) anchor to a\n * page point WITHOUT a Stage camera, so it works the same in `<PageView>`. */\n toClientPoint(p: Point): Point;\n /** Content rect → client (screen) px AABB. Rect analog of `toClientPoint`\n * for upright viewport-space UI that frames a selected page region. */\n toClientRect(rect: Rect): Rect;\n /**\n * The page-view DEMAND for raster planning uses dependency inversion:\n * plugin-render defines the shape; the host that CREATED this\n * context fills it — as a PULL. The Stage host's getter closes over the\n * stage capability and reads `VisiblePage.visibleRect` live at call time\n * (visibility is the STAGE's data; adapters never re-derive camera math or\n * cache a copy). Three states, three meanings: a real sub-rect (visible),\n * a ZERO rect (stage host, page currently off-screen — want nothing), and\n * an undefined getter (stage-less `<PageView>` — whole page visible, which\n * a thumbnail-sized demand turns into \"never engages\" by arithmetic).\n */\n getViewDemand?: () => PageViewDemand;\n /**\n * The hosting VIEW's identity — the stage lens id (`stage.lensId()`) or a\n * per-instance PageView id. IDENTITY, not an option: per-view raster\n * planning (tiles) keys its state by this, so two views showing the SAME\n * page never fight over one plan (a thumbnail rail's never-engaging demand\n * must not disturb the main view's tiles). Every page context host must\n * say which view it is.\n */\n view: string;\n}\n\nconst PageCtx = createContext<PageContextValue | null>(null);\nexport const PageProvider = PageCtx.Provider;\n\nexport function usePage(): PageContextValue {\n const c = useContext(PageCtx);\n if (!c) throw new Error('usePage must be used inside <PageView> or a <Stage> page');\n return c;\n}\n\nexport function makePageContext(\n documentId: string,\n view: string,\n pon: number,\n pageIndex: number,\n frame: PageFrame,\n transform: PageTransform,\n getRect: () => DOMRect,\n getViewDemand?: () => PageViewDemand,\n): PageContextValue {\n return {\n documentId,\n view,\n pon,\n pageIndex,\n frame,\n transform,\n ...(getViewDemand ? { getViewDemand } : {}),\n toContentPoint: (cx, cy) => {\n // `getRect()` is the rotated content wrapper's axis-aligned bounding box =\n // the page's DISPLAY box on screen. Convert client → box-local view px,\n // then invert rotation + scale via the transform (verified once in geometry,\n // not re-derived per framework adapter).\n const r = getRect();\n return transform.viewToContent({ x: cx - r.left, y: cy - r.top });\n },\n toClientPoint: (p) => {\n // Exact inverse of `toContentPoint`: page/content point → display-box view px\n // (rotation applied by the transform), offset by the same live display-box\n // origin. So the two can never drift, in either <Stage> or <PageView>.\n const r = getRect();\n const v = transform.contentToView(p);\n return { x: r.left + v.x, y: r.top + v.y };\n },\n toClientRect: (rect) => {\n const r = getRect();\n const v = transform.contentToViewRect(rect);\n return { x: r.left + v.x, y: r.top + v.y, width: v.width, height: v.height };\n },\n };\n}\n"],"mappings":";;;;;;AAkCA,MAAM,YAAY,cAA6B,IAAI;;AAEnD,MAAM,mBAAmB,cAA6B,IAAI;AAE1D,SAAgB,YAAoB;CAClC,MAAM,IAAI,WAAW,SAAS;CAC9B,IAAI,CAAC,GAAG,MAAM,IA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G,OAAO,EAAE;IAAO,QAAQ,EAAE;GAAO;EAC7E;CACF;AACF"}
package/dist/search.cjs CHANGED
@@ -17,25 +17,42 @@ function SearchLayer({ color = "#ffd500", activeColor = "#ff9632", blendMode = "
17
17
  inset: 0,
18
18
  pointerEvents: "none"
19
19
  },
20
- children: hits.map((hit) => hit.rects.map((r, i) => {
21
- const tl = page.transform.pageToContent({
22
- x: r.x,
23
- y: r.y
24
- });
25
- const br = page.transform.pageToContent({
26
- x: r.x + r.width,
27
- y: r.y + r.height
28
- });
29
- return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { style: {
30
- position: "absolute",
31
- left: tl.x,
32
- top: tl.y,
33
- width: br.x - tl.x,
34
- height: br.y - tl.y,
35
- background: hit === active ? activeColor : color,
36
- mixBlendMode: blendMode,
37
- borderRadius: 2
38
- } }, `${hit.charStart}:${i}`);
20
+ children: hits.map((hit) => hit.segments.map(({ quad: q }, i) => {
21
+ const fill = hit === active ? activeColor : color;
22
+ if (q.upperStart.y === q.upperEnd.y && q.lowerStart.y === q.lowerEnd.y && q.upperStart.x === q.lowerStart.x) {
23
+ const tl = page.transform.toPixels(q.upperStart);
24
+ const br = page.transform.toPixels(q.lowerEnd);
25
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { style: {
26
+ position: "absolute",
27
+ left: tl.x,
28
+ top: tl.y,
29
+ width: br.x - tl.x,
30
+ height: br.y - tl.y,
31
+ background: fill,
32
+ mixBlendMode: blendMode,
33
+ borderRadius: 2
34
+ } }, `${hit.charStart}:${i}`);
35
+ }
36
+ const ring = [
37
+ q.upperStart,
38
+ q.upperEnd,
39
+ q.lowerEnd,
40
+ q.lowerStart
41
+ ].map((p) => page.transform.toPixels(p));
42
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("svg", {
43
+ style: {
44
+ position: "absolute",
45
+ inset: 0,
46
+ width: "100%",
47
+ height: "100%",
48
+ overflow: "visible",
49
+ mixBlendMode: blendMode
50
+ },
51
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("polygon", {
52
+ points: ring.map((p) => `${p.x},${p.y}`).join(" "),
53
+ fill
54
+ })
55
+ }, `${hit.charStart}:${i}`);
39
56
  }))
40
57
  });
41
58
  }
@@ -1 +1 @@
1
- {"version":3,"file":"search.cjs","names":["usePage","useSelector","SearchToken","shallowArray","useCapability"],"sources":["../src/search.tsx"],"sourcesContent":["/**\n * The React surface for @embedpdf/plugin-search.\n *\n * <SearchLayer> is a dumb renderer, the SelectionLayer's twin: it reads\n * the page's content-space hit rects from the capability and paints them\n * through PageContext.pageToContent. The active hit gets its own colour.\n * No pointer handling, no engine calls — search is driven from app chrome\n * via useSearch().\n */\n\n// One-line-per-feature: registration travels with the UI.\nexport * from '@embedpdf/plugin-search';\nimport * as React from 'react';\nimport { SearchToken } from '@embedpdf/plugin-search';\nimport type { SearchHit } from '@embedpdf/plugin-search';\nimport { shallowArray, useCapability, usePage, useSelector } from './runtime';\n\nexport interface SearchLayerProps {\n /** Highlight colour for hits — SOLID (default: highlighter yellow). */\n color?: string;\n /** Highlight colour for the ACTIVE hit — SOLID (default: orange). */\n activeColor?: string;\n /**\n * How the highlight composites with the page. `'multiply'` (default) is\n * the real-highlighter look: text stays crisp black through the colour,\n * only the paper tints. Pass `'normal'` (with translucent colours) for\n * dark/scanned documents where multiply-on-dark would vanish.\n */\n blendMode?: React.CSSProperties['mixBlendMode'];\n}\n\nexport function SearchLayer({\n color = '#ffd500',\n activeColor = '#ff9632',\n blendMode = 'multiply',\n}: SearchLayerProps) {\n const page = usePage();\n const hits = useSelector(SearchToken, (c) => c.hitsForPage(page.pon), shallowArray);\n const active = useSelector(SearchToken, (c) => c.activeHit());\n\n if (hits.length === 0) return null;\n\n return (\n <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none' }}>\n {hits.map((hit: SearchHit) =>\n hit.rects.map((r, i) => {\n const tl = page.transform.pageToContent({ x: r.x, y: r.y });\n const br = page.transform.pageToContent({ x: r.x + r.width, y: r.y + r.height });\n return (\n <div\n key={`${hit.charStart}:${i}`}\n style={{\n position: 'absolute',\n left: tl.x,\n top: tl.y,\n width: br.x - tl.x,\n height: br.y - tl.y,\n background: hit === active ? activeColor : color,\n mixBlendMode: blendMode,\n borderRadius: 2,\n }}\n />\n );\n }),\n )}\n </div>\n );\n}\n\n/** The search capability (search/clear/next/prev/…) for app chrome. */\nexport function useSearch() {\n return useCapability(SearchToken);\n}\n\n/** Reactive search read-model for chrome: the query, status, counts, progress. */\nexport function useSearchState() {\n const query = useSelector(SearchToken, (c) => c.query());\n const status = useSelector(SearchToken, (c) => c.status());\n const hitCount = useSelector(SearchToken, (c) => c.hitCount());\n const activeIndex = useSelector(SearchToken, (c) => c.activeIndex());\n const progress = useSelector(\n SearchToken,\n (c) => c.progress(),\n (a, b) => a.scanned === b.scanned && a.total === b.total,\n );\n const error = useSelector(SearchToken, (c) => c.errorMessage());\n return { query, status, hitCount, activeIndex, progress, error };\n}\n"],"mappings":";;;;;;;;AA+BA,SAAgB,YAAY,EAC1B,QAAQ,WACR,cAAc,WACd,YAAY,cACO;CACnB,MAAM,OAAOA,gBAAAA,QAAQ;CACrB,MAAM,OAAOC,gBAAAA,YAAYC,wBAAAA,cAAc,MAAM,EAAE,YAAY,KAAK,GAAG,GAAGC,gBAAAA,YAAY;CAClF,MAAM,SAASF,gBAAAA,YAAYC,wBAAAA,cAAc,MAAM,EAAE,UAAU,CAAC;CAE5D,IAAI,KAAK,WAAW,GAAG,OAAO;CAE9B,OACE,iBAAA,GAAA,kBAAA,IAAA,CAAC,OAAD;EAAK,OAAO;GAAE,UAAU;GAAY,OAAO;GAAG,eAAe;EAAO;EACjE,UAAA,KAAK,KAAK,QACT,IAAI,MAAM,KAAK,GAAG,MAAM;GACtB,MAAM,KAAK,KAAK,UAAU,cAAc;IAAE,GAAG,EAAE;IAAG,GAAG,EAAE;GAAE,CAAC;GAC1D,MAAM,KAAK,KAAK,UAAU,cAAc;IAAE,GAAG,EAAE,IAAI,EAAE;IAAO,GAAG,EAAE,IAAI,EAAE;GAAO,CAAC;GAC/E,OACE,iBAAA,GAAA,kBAAA,IAAA,CAAC,OAAD,EAEE,OAAO;IACL,UAAU;IACV,MAAM,GAAG;IACT,KAAK,GAAG;IACR,OAAO,GAAG,IAAI,GAAG;IACjB,QAAQ,GAAG,IAAI,GAAG;IAClB,YAAY,QAAQ,SAAS,cAAc;IAC3C,cAAc;IACd,cAAc;GAChB,EACD,GAXM,GAAG,IAAI,UAAU,GAAG,GAW1B;EAEL,CAAC,CACH;CACG,CAAA;AAET;;AAGA,SAAgB,YAAY;CAC1B,OAAOE,gBAAAA,cAAcF,wBAAAA,WAAW;AAClC;;AAGA,SAAgB,iBAAiB;CAW/B,OAAO;EAAE,OAVKD,gBAAAA,YAAYC,wBAAAA,cAAc,MAAM,EAAE,MAAM,CAUzC;EAAG,QATDD,gBAAAA,YAAYC,wBAAAA,cAAc,MAAM,EAAE,OAAO,CASnC;EAAG,UARPD,gBAAAA,YAAYC,wBAAAA,cAAc,MAAM,EAAE,SAAS,CAQ7B;EAAG,aAPdD,gBAAAA,YAAYC,wBAAAA,cAAc,MAAM,EAAE,YAAY,CAOtB;EAAG,UAN9BD,gBAAAA,YACfC,wBAAAA,cACC,MAAM,EAAE,SAAS,IACjB,GAAG,MAAM,EAAE,YAAY,EAAE,WAAW,EAAE,UAAU,EAAE,KAGC;EAAG,OAD3CD,gBAAAA,YAAYC,wBAAAA,cAAc,MAAM,EAAE,aAAa,CACA;CAAE;AACjE"}
1
+ {"version":3,"file":"search.cjs","names":["usePage","useSelector","SearchToken","shallowArray","useCapability"],"sources":["../src/search.tsx"],"sourcesContent":["/**\n * The React surface for @embedpdf/plugin-search.\n *\n * <SearchLayer> is a dumb renderer, the SelectionLayer's twin: it reads\n * the page's content-space hit rects from the capability and paints them\n * through PageContext.toPixels. The active hit gets its own colour.\n * No pointer handling, no engine calls — search is driven from app chrome\n * via useSearch().\n */\n\n// One-line-per-feature: registration travels with the UI.\nexport * from '@embedpdf/plugin-search';\nimport * as React from 'react';\nimport { SearchToken } from '@embedpdf/plugin-search';\nimport type { SearchHit } from '@embedpdf/plugin-search';\nimport { shallowArray, useCapability, usePage, useSelector } from './runtime';\n\nexport interface SearchLayerProps {\n /** Highlight colour for hits — SOLID (default: highlighter yellow). */\n color?: string;\n /** Highlight colour for the ACTIVE hit — SOLID (default: orange). */\n activeColor?: string;\n /**\n * How the highlight composites with the page. `'multiply'` (default) is\n * the real-highlighter look: text stays crisp black through the colour,\n * only the paper tints. Pass `'normal'` (with translucent colours) for\n * dark/scanned documents where multiply-on-dark would vanish.\n */\n blendMode?: React.CSSProperties['mixBlendMode'];\n}\n\nexport function SearchLayer({\n color = '#ffd500',\n activeColor = '#ff9632',\n blendMode = 'multiply',\n}: SearchLayerProps) {\n const page = usePage();\n const hits = useSelector(SearchToken, (c) => c.hitsForPage(page.pon), shallowArray);\n const active = useSelector(SearchToken, (c) => c.activeHit());\n\n if (hits.length === 0) return null;\n\n return (\n <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none' }}>\n {hits.map((hit: SearchHit) =>\n hit.segments.map(({ quad: q }, i) => {\n const fill = hit === active ? activeColor : color;\n // Upright hits keep the classic rounded div (pixel-identical to the\n // pre-orientation layer); rotated hits draw their true oriented cell.\n const upright =\n q.upperStart.y === q.upperEnd.y &&\n q.lowerStart.y === q.lowerEnd.y &&\n q.upperStart.x === q.lowerStart.x;\n if (upright) {\n const tl = page.transform.toPixels(q.upperStart);\n const br = page.transform.toPixels(q.lowerEnd);\n return (\n <div\n key={`${hit.charStart}:${i}`}\n style={{\n position: 'absolute',\n left: tl.x,\n top: tl.y,\n width: br.x - tl.x,\n height: br.y - tl.y,\n background: fill,\n mixBlendMode: blendMode,\n borderRadius: 2,\n }}\n />\n );\n }\n const ring = [q.upperStart, q.upperEnd, q.lowerEnd, q.lowerStart].map((p) =>\n page.transform.toPixels(p),\n );\n return (\n <svg\n key={`${hit.charStart}:${i}`}\n style={{\n position: 'absolute',\n inset: 0,\n width: '100%',\n height: '100%',\n overflow: 'visible',\n mixBlendMode: blendMode,\n }}\n >\n <polygon points={ring.map((p) => `${p.x},${p.y}`).join(' ')} fill={fill} />\n </svg>\n );\n }),\n )}\n </div>\n );\n}\n\n/** The search capability (search/clear/next/prev/…) for app chrome. */\nexport function useSearch() {\n return useCapability(SearchToken);\n}\n\n/** Reactive search read-model for chrome: the query, status, counts, progress. */\nexport function useSearchState() {\n const query = useSelector(SearchToken, (c) => c.query());\n const status = useSelector(SearchToken, (c) => c.status());\n const hitCount = useSelector(SearchToken, (c) => c.hitCount());\n const activeIndex = useSelector(SearchToken, (c) => c.activeIndex());\n const progress = useSelector(\n SearchToken,\n (c) => c.progress(),\n (a, b) => a.scanned === b.scanned && a.total === b.total,\n );\n const error = useSelector(SearchToken, (c) => c.errorMessage());\n return { query, status, hitCount, activeIndex, progress, error };\n}\n"],"mappings":";;;;;;;;AA+BA,SAAgB,YAAY,EAC1B,QAAQ,WACR,cAAc,WACd,YAAY,cACO;CACnB,MAAM,OAAOA,gBAAAA,QAAQ;CACrB,MAAM,OAAOC,gBAAAA,YAAYC,wBAAAA,cAAc,MAAM,EAAE,YAAY,KAAK,GAAG,GAAGC,gBAAAA,YAAY;CAClF,MAAM,SAASF,gBAAAA,YAAYC,wBAAAA,cAAc,MAAM,EAAE,UAAU,CAAC;CAE5D,IAAI,KAAK,WAAW,GAAG,OAAO;CAE9B,OACE,iBAAA,GAAA,kBAAA,IAAA,CAAC,OAAD;EAAK,OAAO;GAAE,UAAU;GAAY,OAAO;GAAG,eAAe;EAAO;EACjE,UAAA,KAAK,KAAK,QACT,IAAI,SAAS,KAAK,EAAE,MAAM,KAAK,MAAM;GACnC,MAAM,OAAO,QAAQ,SAAS,cAAc;GAO5C,IAHE,EAAE,WAAW,MAAM,EAAE,SAAS,KAC9B,EAAE,WAAW,MAAM,EAAE,SAAS,KAC9B,EAAE,WAAW,MAAM,EAAE,WAAW,GACrB;IACX,MAAM,KAAK,K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ACfC,wBAAAA,cACC,MAAM,EAAE,SAAS,IACjB,GAAG,MAAM,EAAE,YAAY,EAAE,WAAW,EAAE,UAAU,EAAE,KAGC;EAAG,OAD3CD,gBAAAA,YAAYC,wBAAAA,cAAc,MAAM,EAAE,aAAa,CACA;CAAE;AACjE"}
package/dist/search.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { r as SearchQuery } from "./AnnotationListSnapshot-W0RCsyDE-dWna4TTJ.cjs";
1
+ import { n as SearchQuery } from "./AnnotationListSnapshot-DDxHpJQU-BG32YXxG.cjs";
2
2
  import * as React from "react";
3
3
  export * from "@embedpdf/plugin-search";
4
4
  //#region src/search.d.ts
package/dist/search.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { r as SearchQuery } from "./AnnotationListSnapshot-W0RCsyDE-dWna4TTJ.js";
1
+ import { n as SearchQuery } from "./AnnotationListSnapshot-DDxHpJQU-BG32YXxG.js";
2
2
  import * as React from "react";
3
3
  export * from "@embedpdf/plugin-search";
4
4
  //#region src/search.d.ts
package/dist/search.js CHANGED
@@ -15,25 +15,42 @@ function SearchLayer({ color = "#ffd500", activeColor = "#ff9632", blendMode = "
15
15
  inset: 0,
16
16
  pointerEvents: "none"
17
17
  },
18
- children: hits.map((hit) => hit.rects.map((r, i) => {
19
- const tl = page.transform.pageToContent({
20
- x: r.x,
21
- y: r.y
22
- });
23
- const br = page.transform.pageToContent({
24
- x: r.x + r.width,
25
- y: r.y + r.height
26
- });
27
- return /* @__PURE__ */ jsx("div", { style: {
28
- position: "absolute",
29
- left: tl.x,
30
- top: tl.y,
31
- width: br.x - tl.x,
32
- height: br.y - tl.y,
33
- background: hit === active ? activeColor : color,
34
- mixBlendMode: blendMode,
35
- borderRadius: 2
36
- } }, `${hit.charStart}:${i}`);
18
+ children: hits.map((hit) => hit.segments.map(({ quad: q }, i) => {
19
+ const fill = hit === active ? activeColor : color;
20
+ if (q.upperStart.y === q.upperEnd.y && q.lowerStart.y === q.lowerEnd.y && q.upperStart.x === q.lowerStart.x) {
21
+ const tl = page.transform.toPixels(q.upperStart);
22
+ const br = page.transform.toPixels(q.lowerEnd);
23
+ return /* @__PURE__ */ jsx("div", { style: {
24
+ position: "absolute",
25
+ left: tl.x,
26
+ top: tl.y,
27
+ width: br.x - tl.x,
28
+ height: br.y - tl.y,
29
+ background: fill,
30
+ mixBlendMode: blendMode,
31
+ borderRadius: 2
32
+ } }, `${hit.charStart}:${i}`);
33
+ }
34
+ const ring = [
35
+ q.upperStart,
36
+ q.upperEnd,
37
+ q.lowerEnd,
38
+ q.lowerStart
39
+ ].map((p) => page.transform.toPixels(p));
40
+ return /* @__PURE__ */ jsx("svg", {
41
+ style: {
42
+ position: "absolute",
43
+ inset: 0,
44
+ width: "100%",
45
+ height: "100%",
46
+ overflow: "visible",
47
+ mixBlendMode: blendMode
48
+ },
49
+ children: /* @__PURE__ */ jsx("polygon", {
50
+ points: ring.map((p) => `${p.x},${p.y}`).join(" "),
51
+ fill
52
+ })
53
+ }, `${hit.charStart}:${i}`);
37
54
  }))
38
55
  });
39
56
  }