@embedpdf/react 3.0.0-next.6 → 3.0.0-next.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/annotation.d.cts +1 -1
- package/dist/annotation.d.ts +1 -1
- package/dist/index.cjs +14 -1
- package/dist/index.d.cts +4 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.js +3 -3
- package/dist/interaction.cjs +14 -1
- package/dist/interaction.cjs.map +1 -1
- package/dist/interaction.d.cts +2 -2
- package/dist/interaction.d.ts +2 -2
- package/dist/interaction.js +4 -3
- package/dist/interaction.js.map +1 -1
- package/dist/page-view.cjs +5 -3
- package/dist/page-view.cjs.map +1 -1
- package/dist/page-view.js +6 -4
- package/dist/page-view.js.map +1 -1
- package/dist/render.cjs +5 -4
- package/dist/render.cjs.map +1 -1
- package/dist/render.js +5 -4
- package/dist/render.js.map +1 -1
- package/dist/{runtime-CMxIuF2O.d.cts → runtime-Bh_9OtWo.d.ts} +12 -3
- package/dist/{runtime-DV98q7I0.d.ts → runtime-D4TXEICX.d.cts} +12 -3
- package/dist/runtime.cjs +2 -1
- package/dist/runtime.cjs.map +1 -1
- package/dist/runtime.d.cts +1 -1
- package/dist/runtime.d.ts +1 -1
- package/dist/runtime.js +2 -1
- package/dist/runtime.js.map +1 -1
- package/dist/selection.cjs +144 -0
- package/dist/selection.cjs.map +1 -1
- package/dist/selection.d.cts +26 -1
- package/dist/selection.d.ts +26 -1
- package/dist/selection.js +149 -6
- package/dist/selection.js.map +1 -1
- package/dist/stage.cjs +14 -145
- package/dist/stage.cjs.map +1 -1
- package/dist/stage.d.cts +18 -5
- package/dist/stage.d.ts +18 -5
- package/dist/stage.js +15 -146
- package/dist/stage.js.map +1 -1
- package/package.json +23 -23
package/dist/render.js
CHANGED
|
@@ -76,8 +76,9 @@ function TilePlane({ annotations, fadeMs }) {
|
|
|
76
76
|
const page = usePage();
|
|
77
77
|
const render = useCapability(RenderToken);
|
|
78
78
|
const demand = page.getViewDemand?.() ?? { desiredDeviceWidth: page.transform.deviceWidth };
|
|
79
|
-
const
|
|
80
|
-
|
|
79
|
+
const tiles = render.tilesFor(page.view);
|
|
80
|
+
const plan = useSelector(RenderToken, () => tiles.plan(page.pon, demand, { includeAnnotations: annotations }));
|
|
81
|
+
useEffect(() => () => tiles.release(page.pon), [tiles, page.pon]);
|
|
81
82
|
if (plan.paint.length === 0) return null;
|
|
82
83
|
const t = page.transform;
|
|
83
84
|
const s = t.viewScale;
|
|
@@ -100,8 +101,8 @@ function TilePlane({ annotations, fadeMs }) {
|
|
|
100
101
|
height: source.rect.height * s
|
|
101
102
|
},
|
|
102
103
|
fadeMs,
|
|
103
|
-
onPainted: () =>
|
|
104
|
-
onUnpainted: () =>
|
|
104
|
+
onPainted: () => tiles.painted(page.pon, source.key),
|
|
105
|
+
onUnpainted: () => tiles.unpainted(page.pon, source.key)
|
|
105
106
|
}, source.key))]
|
|
106
107
|
});
|
|
107
108
|
}
|
package/dist/render.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"render.js","names":[],"sources":["../src/render.tsx"],"sourcesContent":["/**\n * RenderLayer — the React view of @embedpdf/plugin-render. The page raster\n * is ONE concern with two planes:\n *\n * - the BASE plane: a whole-page <img> at the plugin's resolved render\n * points — the exact settled demand capped at the pixel budget on a\n * continuous (local) engine, the advertised ladder on a lattice (cloud)\n * deployment. Always present; the instant backdrop.\n * - the TILE plane: the plugin's retention-safe paint plan above it,\n * engaging by demand arithmetic when the view wants more pixels than\n * the base may spend. A thumbnail-sized demand engages nothing — the\n * arithmetic is the configuration.\n *\n * The layer is a DUMB painter, deliberately thin: plain <img>s bound through\n * the shared browser adapter, with painted/unpainted reports around their\n * visible lifetime. Every decision — strategy ∧ policy conformance, want\n * sets, level settling, retention, release — is plugin-render's; anything\n * mid-gesture simply CSS-scales until the plugin hands down new pixels.\n */\n\n// One-line-per-feature: registration travels with the UI.\nexport * from '@embedpdf/plugin-render';\nimport * as React from 'react';\nimport { useEffect, useLayoutEffect, useRef } from 'react';\nimport { RenderToken } from '@embedpdf/plugin-render';\nimport type { PageViewDemand, TilePaintSource } from '@embedpdf/plugin-render';\nimport { bindPaintedImage } from '@embedpdf/web';\nimport { useCapability, usePage, useSelector } from './runtime';\n\nexport interface RenderLayerProps {\n /**\n * Bake annotations into the page bitmap (default true). Pass false when an\n * <AnnotationLayer> owns annotation rendering, so they aren't drawn twice.\n */\n annotations?: boolean;\n /**\n * Mount the tile plane (default true). Whether it SPENDS anything is\n * demand arithmetic — leave it on; pass false only for a lens that must\n * never tile even under deep zoom.\n */\n tiles?: boolean;\n}\n\nlet warnedTileSize = false;\n\nexport function RenderLayer({ annotations = true, tiles = true }: RenderLayerProps = {}) {\n const page = usePage();\n const render = useCapability(RenderToken);\n const settings = render.paintSettings();\n const ref = useRef<HTMLImageElement>(null);\n\n // ONE dependency: the raster's canonical identity — conformed width +\n // annotations flag + epoch. Under a lattice it moves only at rung\n // crossings; under exact mode it tracks the demand and is CONSTANT above\n // the budget — so the deep-zoom backdrop never refetches, and the sub-\n // budget range refetches per settled demand exactly like v2 did.\n const sourceKey = useSelector(RenderToken, (c) =>\n c.renderSourceKey(page.pon, {\n scale: page.transform.renderScale,\n includeAnnotations: annotations,\n }),\n );\n\n useEffect(() => {\n const controller = new AbortController();\n let revoke: (() => void) | undefined;\n (async () => {\n try {\n // The capability conforms this to the resolved render points and\n // collapses same-key asks in its raster store. A stale-closure scale\n // is harmless by construction: any scale mapping to this key\n // produces this key's canonical request.\n const image = await render.renderPage(page.pon, {\n scale: page.transform.renderScale,\n includeAnnotations: annotations,\n signal: controller.signal,\n });\n const obj = await image.objectUrl(controller.signal);\n if (controller.signal.aborted) {\n obj.revoke();\n return;\n }\n revoke = obj.revoke;\n // Imperative src on a STABLE element: the browser keeps the old\n // bitmap until the new one decodes, and nothing ever re-requests the\n // old URL — so revoke-on-cleanup is safe here by construction.\n if (ref.current) ref.current.src = obj.url;\n } catch {\n /* aborted (camera moved / unmounted) or render failed */\n }\n })();\n return () => {\n controller.abort();\n revoke?.();\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps -- sourceKey IS the\n // render identity; scale/annotations/epoch are folded into it upstream.\n }, [render, page.pon, sourceKey]);\n\n return (\n <>\n <img\n ref={ref}\n alt=\"\"\n draggable={false}\n style={{\n position: 'absolute',\n inset: 0,\n width: '100%',\n height: '100%',\n pointerEvents: 'none',\n }}\n />\n {tiles && settings.tiles ? (\n <TilePlane annotations={annotations} fadeMs={settings.fadeMs} />\n ) : null}\n </>\n );\n}\n\n/**\n * The sharp plane above the base — the plugin's retention-safe paint plan\n * as keyed <img>s. Each tile reports painted after its first presentation\n * opportunity (and its inverse on unmount), so retained coarser generations\n * release only when their replacement is truly compositable.\n *\n * Tiles are placed in VIEW (CSS px) space directly — never in page points\n * under a scaled container. Blink quantizes layout lengths to 1/64 CSS px\n * BEFORE transforms apply, so a pt-space rect under a ×25 zoom transform\n * turns that harmless 1/64 into ±0.4px+ of per-tile misplacement — visible\n * seams and per-zoom-step letter shifts that grow with depth. In view\n * space the same quantization is a fixed ~1/64 CSS px at every zoom.\n * (v2 placed tiles in screen px for exactly this reason.)\n */\nfunction TilePlane({ annotations, fadeMs }: { annotations: boolean; fadeMs: number }) {\n const page = usePage();\n const render = useCapability(RenderToken);\n // Demand: the host's live camera view (Stage) or whole-page (PageView).\n // Level settling lives in the plugin (its settle gate), pan stays live.\n const demand: PageViewDemand = page.getViewDemand?.() ?? {\n desiredDeviceWidth: page.transform.deviceWidth,\n };\n const plan = useSelector(RenderToken, (c) =>\n c.tilePlan(page.pon, demand, { includeAnnotations: annotations }),\n );\n // Lens unmounted: stop in-flight tile fetches; resolved bytes stay cached.\n useEffect(() => () => render.releaseTiles(page.pon), [render, page.pon]);\n if (plan.paint.length === 0) return null;\n const t = page.transform;\n const s = t.viewScale;\n return (\n <div\n style={{\n position: 'absolute',\n left: 0,\n top: 0,\n width: t.contentWidth,\n height: t.contentHeight,\n pointerEvents: 'none',\n // STACKING CONTRACT: tile <img>s carry zIndex ranks (coarse under\n // fine) that exist only while generations are mixed — mid-zoom. This\n // container MUST be a stacking context so those ranks stay internal;\n // without it they join the Stage's context and paint above every\n // z-auto sibling (annotations, page chrome, menus) exactly while\n // zooming. The old scaled container created one implicitly via its\n // transform; `isolation` is the explicit, no-side-effect way.\n isolation: 'isolate',\n }}\n >\n {fadeMs > 0 ? (\n <style>{`@keyframes epdf-tile-in { from { opacity: 0 } to { opacity: 1 } }`}</style>\n ) : null}\n {plan.paint.map((source) => (\n <TileImg\n key={source.key}\n source={source}\n view={{\n x: source.rect.x * s,\n y: source.rect.y * s,\n width: source.rect.width * s,\n height: source.rect.height * s,\n }}\n fadeMs={fadeMs}\n onPainted={() => render.tilePainted(page.pon, source.key)}\n onUnpainted={() => render.tileUnpainted(page.pon, source.key)}\n />\n ))}\n </div>\n );\n}\n\n/** One tile: geometry plus the shared browser image binding. The binding\n * hides the incomplete image, reports painted after its first presentation\n * opportunity, and inverts that report when the element leaves the DOM. */\nfunction TileImg({\n source,\n view,\n fadeMs,\n onPainted,\n onUnpainted,\n}: {\n source: TilePaintSource;\n /** Placement rect in VIEW (CSS px) space. */\n view: { x: number; y: number; width: number; height: number };\n fadeMs: number;\n onPainted: () => void;\n onUnpainted: () => void;\n}) {\n const ref = useRef<HTMLImageElement>(null);\n useLayoutEffect(() => {\n if (!ref.current) return;\n return bindPaintedImage(ref.current, source.handle, { onPainted, onUnpainted });\n // eslint-disable-next-line react-hooks/exhaustive-deps -- the handle is\n // the bitmap's identity; the report callbacks carry stable values.\n }, [source.handle]);\n return (\n <img\n ref={ref}\n alt=\"\"\n draggable={false}\n onLoad={(e) => {\n // A raster whose intrinsic size disagrees with its rect would be\n // silently stretched into place — the stale-handle bug class.\n const w = e.currentTarget.naturalWidth;\n if (w > 0 && !warnedTileSize) {\n const expected = Math.round(source.rect.width * source.scale);\n if (Math.abs(w - expected) > 1) {\n warnedTileSize = true;\n console.warn(\n `[render] tile bitmap ${w}px wide does not match its rect ` +\n `(expected ~${expected}px) — stale raster identity? key=${source.key}`,\n );\n }\n }\n }}\n style={{\n position: 'absolute',\n left: view.x,\n top: view.y,\n width: view.width,\n height: view.height,\n zIndex: source.z,\n ...(fadeMs > 0 ? { animation: `epdf-tile-in ${fadeMs}ms ease-out` } : null),\n }}\n />\n );\n}\n"],"mappings":";;;;;;;AA2CA,IAAI,iBAAiB;AAErB,SAAgB,YAAY,EAAE,cAAc,MAAM,QAAQ,SAA2B,CAAC,GAAG;CACvF,MAAM,OAAO,QAAQ;CACrB,MAAM,SAAS,cAAc,WAAW;CACxC,MAAM,WAAW,OAAO,cAAc;CACtC,MAAM,MAAM,OAAyB,IAAI;CAOzC,MAAM,YAAY,YAAY,cAAc,MAC1C,EAAE,gBAAgB,KAAK,KAAK;EAC1B,OAAO,KAAK,UAAU;EACtB,oBAAoB;CACtB,CAAC,CACH;CAEA,gBAAgB;EACd,MAAM,aAAa,IAAI,gBAAgB;EACvC,IAAI;EACJ,CAAC,YAAY;GACX,IAAI;IAUF,MAAM,MAAM,OAAM,MALE,OAAO,WAAW,KAAK,KAAK;KAC9C,OAAO,KAAK,UAAU;KACtB,oBAAoB;KACpB,QAAQ,WAAW;IACrB,CAAC,EAAA,CACuB,UAAU,WAAW,MAAM;IACnD,IAAI,WAAW,OAAO,SAAS;KAC7B,IAAI,OAAO;KACX;IACF;IACA,SAAS,IAAI;IAIb,IAAI,IAAI,SAAS,IAAI,QAAQ,MAAM,IAAI;GACzC,QAAQ,CAER;EACF,EAAA,CAAG;EACH,aAAa;GACX,WAAW,MAAM;GACjB,SAAS;EACX;CAGF,GAAG;EAAC;EAAQ,KAAK;EAAK;CAAS,CAAC;CAEhC,OACE,qBAAA,UAAA,EAAA,UAAA,CACE,oBAAC,OAAD;EACO;EACL,KAAI;EACJ,WAAW;EACX,OAAO;GACL,UAAU;GACV,OAAO;GACP,OAAO;GACP,QAAQ;GACR,eAAe;EACjB;CACD,CAAA,GAC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O,iBAAiB,IAAI,SAAS,OAAO,QAAQ;GAAE;GAAW;EAAY,CAAC;CAGhF,GAAG,CAAC,OAAO,MAAM,CAAC;CAClB,OACE,oBAAC,OAAD;EACO;EACL,KAAI;EACJ,WAAW;EACX,SAAS,MAAM;GAGb,MAAM,IAAI,EAAE,cAAc;GAC1B,IAAI,IAAI,KAAK,CAAC,gBAAgB;IAC5B,MAAM,WAAW,KAAK,MAAM,OAAO,KAAK,QAAQ,OAAO,KAAK;IAC5D,IAAI,KAAK,IAAI,IAAI,QAAQ,IAAI,GAAG;KAC9B,iBAAiB;KACjB,QAAQ,KACN,wBAAwB,EAAE,6CACV,SAAS,mCAAmC,OAAO,KACrE;IACF;GACF;EACF;EACA,OAAO;GACL,UAAU;GACV,MAAM,KAAK;GACX,KAAK,KAAK;GACV,OAAO,KAAK;GACZ,QAAQ,KAAK;GACb,QAAQ,OAAO;GACf,GAAI,SAAS,IAAI,EAAE,WAAW,gBAAgB,OAAO,aAAa,IAAI;EACxE;CACD,CAAA;AAEL"}
|
|
1
|
+
{"version":3,"file":"render.js","names":[],"sources":["../src/render.tsx"],"sourcesContent":["/**\n * RenderLayer — the React view of @embedpdf/plugin-render. The page raster\n * is ONE concern with two planes:\n *\n * - the BASE plane: a whole-page <img> at the plugin's resolved render\n * points — the exact settled demand capped at the pixel budget on a\n * continuous (local) engine, the advertised ladder on a lattice (cloud)\n * deployment. Always present; the instant backdrop.\n * - the TILE plane: the plugin's retention-safe paint plan above it,\n * engaging by demand arithmetic when the view wants more pixels than\n * the base may spend. A thumbnail-sized demand engages nothing — the\n * arithmetic is the configuration.\n *\n * The layer is a DUMB painter, deliberately thin: plain <img>s bound through\n * the shared browser adapter, with painted/unpainted reports around their\n * visible lifetime. Every decision — strategy ∧ policy conformance, want\n * sets, level settling, retention, release — is plugin-render's; anything\n * mid-gesture simply CSS-scales until the plugin hands down new pixels.\n */\n\n// One-line-per-feature: registration travels with the UI.\nexport * from '@embedpdf/plugin-render';\nimport * as React from 'react';\nimport { useEffect, useLayoutEffect, useRef } from 'react';\nimport { RenderToken } from '@embedpdf/plugin-render';\nimport type { PageViewDemand, TilePaintSource } from '@embedpdf/plugin-render';\nimport { bindPaintedImage } from '@embedpdf/web';\nimport { useCapability, usePage, useSelector } from './runtime';\n\nexport interface RenderLayerProps {\n /**\n * Bake annotations into the page bitmap (default true). Pass false when an\n * <AnnotationLayer> owns annotation rendering, so they aren't drawn twice.\n */\n annotations?: boolean;\n /**\n * Mount the tile plane (default true). Whether it SPENDS anything is\n * demand arithmetic — leave it on; pass false only for a lens that must\n * never tile even under deep zoom.\n */\n tiles?: boolean;\n}\n\nlet warnedTileSize = false;\n\nexport function RenderLayer({ annotations = true, tiles = true }: RenderLayerProps = {}) {\n const page = usePage();\n const render = useCapability(RenderToken);\n const settings = render.paintSettings();\n const ref = useRef<HTMLImageElement>(null);\n\n // ONE dependency: the raster's canonical identity — conformed width +\n // annotations flag + epoch. Under a lattice it moves only at rung\n // crossings; under exact mode it tracks the demand and is CONSTANT above\n // the budget — so the deep-zoom backdrop never refetches, and the sub-\n // budget range refetches per settled demand exactly like v2 did.\n const sourceKey = useSelector(RenderToken, (c) =>\n c.renderSourceKey(page.pon, {\n scale: page.transform.renderScale,\n includeAnnotations: annotations,\n }),\n );\n\n useEffect(() => {\n const controller = new AbortController();\n let revoke: (() => void) | undefined;\n (async () => {\n try {\n // The capability conforms this to the resolved render points and\n // collapses same-key asks in its raster store. A stale-closure scale\n // is harmless by construction: any scale mapping to this key\n // produces this key's canonical request.\n const image = await render.renderPage(page.pon, {\n scale: page.transform.renderScale,\n includeAnnotations: annotations,\n signal: controller.signal,\n });\n const obj = await image.objectUrl(controller.signal);\n if (controller.signal.aborted) {\n obj.revoke();\n return;\n }\n revoke = obj.revoke;\n // Imperative src on a STABLE element: the browser keeps the old\n // bitmap until the new one decodes, and nothing ever re-requests the\n // old URL — so revoke-on-cleanup is safe here by construction.\n if (ref.current) ref.current.src = obj.url;\n } catch {\n /* aborted (camera moved / unmounted) or render failed */\n }\n })();\n return () => {\n controller.abort();\n revoke?.();\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps -- sourceKey IS the\n // render identity; scale/annotations/epoch are folded into it upstream.\n }, [render, page.pon, sourceKey]);\n\n return (\n <>\n <img\n ref={ref}\n alt=\"\"\n draggable={false}\n style={{\n position: 'absolute',\n inset: 0,\n width: '100%',\n height: '100%',\n pointerEvents: 'none',\n }}\n />\n {tiles && settings.tiles ? (\n <TilePlane annotations={annotations} fadeMs={settings.fadeMs} />\n ) : null}\n </>\n );\n}\n\n/**\n * The sharp plane above the base — the plugin's retention-safe paint plan\n * as keyed <img>s. Each tile reports painted after its first presentation\n * opportunity (and its inverse on unmount), so retained coarser generations\n * release only when their replacement is truly compositable.\n *\n * Tiles are placed in VIEW (CSS px) space directly — never in page points\n * under a scaled container. Blink quantizes layout lengths to 1/64 CSS px\n * BEFORE transforms apply, so a pt-space rect under a ×25 zoom transform\n * turns that harmless 1/64 into ±0.4px+ of per-tile misplacement — visible\n * seams and per-zoom-step letter shifts that grow with depth. In view\n * space the same quantization is a fixed ~1/64 CSS px at every zoom.\n * (v2 placed tiles in screen px for exactly this reason.)\n */\nfunction TilePlane({ annotations, fadeMs }: { annotations: boolean; fadeMs: number }) {\n const page = usePage();\n const render = useCapability(RenderToken);\n // Demand: the host's live camera view (Stage) or whole-page (PageView).\n // Level settling lives in the plugin (its settle gate), pan stays live.\n const demand: PageViewDemand = page.getViewDemand?.() ?? {\n desiredDeviceWidth: page.transform.deviceWidth,\n };\n // THIS view's tile surface: state is per view × page, so a thumbnail\n // rail's never-engaging demand cannot disturb the main lens's plan (shared\n // state made the main view lose its tiles whenever a rail opened). The\n // handle is reference-stable per view — a clean dependency.\n const tiles = render.tilesFor(page.view);\n const plan = useSelector(RenderToken, () =>\n tiles.plan(page.pon, demand, { includeAnnotations: annotations }),\n );\n // View unmounted its plane: stop in-flight fetches; resolved bytes stay cached.\n useEffect(() => () => tiles.release(page.pon), [tiles, page.pon]);\n if (plan.paint.length === 0) return null;\n const t = page.transform;\n const s = t.viewScale;\n return (\n <div\n style={{\n position: 'absolute',\n left: 0,\n top: 0,\n width: t.contentWidth,\n height: t.contentHeight,\n pointerEvents: 'none',\n // STACKING CONTRACT: tile <img>s carry zIndex ranks (coarse under\n // fine) that exist only while generations are mixed — mid-zoom. This\n // container MUST be a stacking context so those ranks stay internal;\n // without it they join the Stage's context and paint above every\n // z-auto sibling (annotations, page chrome, menus) exactly while\n // zooming. The old scaled container created one implicitly via its\n // transform; `isolation` is the explicit, no-side-effect way.\n isolation: 'isolate',\n }}\n >\n {fadeMs > 0 ? (\n <style>{`@keyframes epdf-tile-in { from { opacity: 0 } to { opacity: 1 } }`}</style>\n ) : null}\n {plan.paint.map((source) => (\n <TileImg\n key={source.key}\n source={source}\n view={{\n x: source.rect.x * s,\n y: source.rect.y * s,\n width: source.rect.width * s,\n height: source.rect.height * s,\n }}\n fadeMs={fadeMs}\n onPainted={() => tiles.painted(page.pon, source.key)}\n onUnpainted={() => tiles.unpainted(page.pon, source.key)}\n />\n ))}\n </div>\n );\n}\n\n/** One tile: geometry plus the shared browser image binding. The binding\n * hides the incomplete image, reports painted after its first presentation\n * opportunity, and inverts that report when the element leaves the DOM. */\nfunction TileImg({\n source,\n view,\n fadeMs,\n onPainted,\n onUnpainted,\n}: {\n source: TilePaintSource;\n /** Placement rect in VIEW (CSS px) space. */\n view: { x: number; y: number; width: number; height: number };\n fadeMs: number;\n onPainted: () => void;\n onUnpainted: () => void;\n}) {\n const ref = useRef<HTMLImageElement>(null);\n useLayoutEffect(() => {\n if (!ref.current) return;\n return bindPaintedImage(ref.current, source.handle, { onPainted, onUnpainted });\n // eslint-disable-next-line react-hooks/exhaustive-deps -- the handle is\n // the bitmap's identity; the report callbacks carry stable values.\n }, [source.handle]);\n return (\n <img\n ref={ref}\n alt=\"\"\n draggable={false}\n onLoad={(e) => {\n // A raster whose intrinsic size disagrees with its rect would be\n // silently stretched into place — the stale-handle bug class.\n const w = e.currentTarget.naturalWidth;\n if (w > 0 && !warnedTileSize) {\n const expected = Math.round(source.rect.width * source.scale);\n if (Math.abs(w - expected) > 1) {\n warnedTileSize = true;\n console.warn(\n `[render] tile bitmap ${w}px wide does not match its rect ` +\n `(expected ~${expected}px) — stale raster identity? key=${source.key}`,\n );\n }\n }\n }}\n style={{\n position: 'absolute',\n left: view.x,\n top: view.y,\n width: view.width,\n height: view.height,\n zIndex: source.z,\n ...(fadeMs > 0 ? { animation: `epdf-tile-in ${fadeMs}ms ease-out` } : null),\n }}\n />\n );\n}\n"],"mappings":";;;;;;;AA2CA,IAAI,iBAAiB;AAErB,SAAgB,YAAY,EAAE,cAAc,MAAM,QAAQ,SAA2B,CAAC,GAAG;CACvF,MAAM,OAAO,QAAQ;CACrB,MAAM,SAAS,cAAc,WAAW;CACxC,MAAM,WAAW,OAAO,cAAc;CACtC,MAAM,MAAM,OAAyB,IAAI;CAOzC,MAAM,YAAY,YAAY,cAAc,MAC1C,EAAE,gBAAgB,KAAK,KAAK;EAC1B,OAAO,KAAK,UAAU;EACtB,oBAAoB;CACtB,CAAC,CACH;CAEA,gBAAgB;EACd,MAAM,aAAa,IAAI,gBAAgB;EACvC,IAAI;EACJ,CAAC,YAAY;GACX,IAAI;IAUF,MAAM,MAAM,OAAM,MALE,OAAO,WAAW,KAAK,KAAK;KAC9C,OAAO,KAAK,UAAU;KACtB,oBAAoB;KACpB,QAAQ,WAAW;IACrB,CAAC,EAAA,CACuB,UAAU,WAAW,MAAM;IACnD,IAAI,WAAW,OAAO,SAAS;KAC7B,IAAI,OAAO;KACX;IACF;IACA,SAAS,IAAI;IAIb,IAAI,IAAI,SAAS,IAAI,QAAQ,MAAM,IAAI;GACzC,QAAQ,CAER;EACF,EAAA,CAAG;EACH,aAAa;GACX,WAAW,MAAM;GACjB,SAAS;EACX;CAGF,GAAG;EAAC;EAAQ,KAAK;EAAK;CAAS,CAAC;CAEhC,OACE,qBAAA,UAAA,EAAA,UAAA,CACE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M,OAAO,GAWb,CACF,CACE;;AAET;;;;AAKA,SAAS,QAAQ,EACf,QACA,MACA,QACA,WACA,eAQC;CACD,MAAM,MAAM,OAAyB,IAAI;CACzC,sBAAsB;EACpB,IAAI,CAAC,IAAI,SAAS;EAClB,OAAO,iBAAiB,IAAI,SAAS,OAAO,QAAQ;GAAE;GAAW;EAAY,CAAC;CAGhF,GAAG,CAAC,OAAO,MAAM,CAAC;CAClB,OACE,oBAAC,OAAD;EACO;EACL,KAAI;EACJ,WAAW;EACX,SAAS,MAAM;GAGb,MAAM,IAAI,EAAE,cAAc;GAC1B,IAAI,IAAI,KAAK,CAAC,gBAAgB;IAC5B,MAAM,WAAW,KAAK,MAAM,OAAO,KAAK,QAAQ,OAAO,KAAK;IAC5D,IAAI,KAAK,IAAI,IAAI,QAAQ,IAAI,GAAG;KAC9B,iBAAiB;KACjB,QAAQ,KACN,wBAAwB,EAAE,6CACV,SAAS,mCAAmC,OAAO,KACrE;IACF;GACF;EACF;EACA,OAAO;GACL,UAAU;GACV,MAAM,KAAK;GACX,KAAK,KAAK;GACV,OAAO,KAAK;GACZ,QAAQ,KAAK;GACb,QAAQ,OAAO;GACf,GAAI,SAAS,IAAI,EAAE,WAAW,gBAAgB,OAAO,aAAa,IAAI;EACxE;CACD,CAAA;AAEL"}
|
|
@@ -1,5 +1,5 @@
|
|
|
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
5
|
//#region src/runtime.d.ts
|
|
@@ -186,10 +186,19 @@ interface PageContextValue {
|
|
|
186
186
|
* a thumbnail-sized demand turns into "never engages" by arithmetic).
|
|
187
187
|
*/
|
|
188
188
|
getViewDemand?: () => PageViewDemand;
|
|
189
|
+
/**
|
|
190
|
+
* The hosting VIEW's identity — the stage lens id (`stage.lensId()`) or a
|
|
191
|
+
* per-instance PageView id. IDENTITY, not an option: per-view raster
|
|
192
|
+
* planning (tiles) keys its state by this, so two views showing the SAME
|
|
193
|
+
* page never fight over one plan (a thumbnail rail's never-engaging demand
|
|
194
|
+
* must not disturb the main view's tiles). Every page context host must
|
|
195
|
+
* say which view it is.
|
|
196
|
+
*/
|
|
197
|
+
view: string;
|
|
189
198
|
}
|
|
190
199
|
declare const PageProvider: React.Provider<PageContextValue | null>;
|
|
191
200
|
declare function usePage(): PageContextValue;
|
|
192
|
-
declare function makePageContext(documentId: string, pon: number, pageIndex: number, frame: PageFrame, transform: PageTransform, getRect: () => DOMRect, getViewDemand?: () => PageViewDemand): PageContextValue;
|
|
201
|
+
declare function makePageContext(documentId: string, view: string, pon: number, pageIndex: number, frame: PageFrame, transform: PageTransform, getRect: () => DOMRect, getViewDemand?: () => PageViewDemand): PageContextValue;
|
|
193
202
|
//#endregion
|
|
194
203
|
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-
|
|
204
|
+
//# sourceMappingURL=runtime-Bh_9OtWo.d.ts.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { AnyPlugin, CapabilityToken, Engine, EngineFactory, InitialDocument, Kernel } from "@embedpdf/core";
|
|
2
1
|
import * as React from "react";
|
|
2
|
+
import { AnyPlugin, CapabilityToken, Engine, EngineFactory, InitialDocument, Kernel } from "@embedpdf/core";
|
|
3
3
|
import { PageFrame, PageTransform, Point, Rect } from "@embedpdf/core-geometry";
|
|
4
4
|
import { PageViewDemand } from "@embedpdf/plugin-render";
|
|
5
5
|
//#region src/runtime.d.ts
|
|
@@ -186,10 +186,19 @@ interface PageContextValue {
|
|
|
186
186
|
* a thumbnail-sized demand turns into "never engages" by arithmetic).
|
|
187
187
|
*/
|
|
188
188
|
getViewDemand?: () => PageViewDemand;
|
|
189
|
+
/**
|
|
190
|
+
* The hosting VIEW's identity — the stage lens id (`stage.lensId()`) or a
|
|
191
|
+
* per-instance PageView id. IDENTITY, not an option: per-view raster
|
|
192
|
+
* planning (tiles) keys its state by this, so two views showing the SAME
|
|
193
|
+
* page never fight over one plan (a thumbnail rail's never-engaging demand
|
|
194
|
+
* must not disturb the main view's tiles). Every page context host must
|
|
195
|
+
* say which view it is.
|
|
196
|
+
*/
|
|
197
|
+
view: string;
|
|
189
198
|
}
|
|
190
199
|
declare const PageProvider: React.Provider<PageContextValue | null>;
|
|
191
200
|
declare function usePage(): PageContextValue;
|
|
192
|
-
declare function makePageContext(documentId: string, pon: number, pageIndex: number, frame: PageFrame, transform: PageTransform, getRect: () => DOMRect, getViewDemand?: () => PageViewDemand): PageContextValue;
|
|
201
|
+
declare function makePageContext(documentId: string, view: string, pon: number, pageIndex: number, frame: PageFrame, transform: PageTransform, getRect: () => DOMRect, getViewDemand?: () => PageViewDemand): PageContextValue;
|
|
193
202
|
//#endregion
|
|
194
203
|
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-
|
|
204
|
+
//# sourceMappingURL=runtime-D4TXEICX.d.cts.map
|
package/dist/runtime.cjs
CHANGED
|
@@ -248,9 +248,10 @@ 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,
|
package/dist/runtime.cjs.map
CHANGED
|
@@ -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,KA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AC;EAC/D;EACA,gBAAgB,MAAM;GAIpB,MAAM,IAAI,QAAQ;GAClB,MAAM,IAAI,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 — `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 * 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 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,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;AAEA,SAAgB,gBACd,YACA,MACA,KACA,WACA,OACA,WACA,SACA,eACkB;CAClB,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA,GAAI,gBAAgB,EAAE,cAAc,IAAI,CAAC;EACzC,cAAc,IAAI,OAAO;GAKvB,MAAM,IAAI,QAAQ;GAClB,OAAO,UAAU,WAAW;IAAE,GAAG,KAAK,EAAE;IAAM,GAAG,KAAK,EAAE;GAAI,CAAC;EAC/D;EACA,gBAAgB,MAAM;GAIpB,MAAM,IAAI,QAAQ;GAClB,MAAM,IAAI,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"}
|
package/dist/runtime.d.cts
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-
|
|
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-D4TXEICX.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-
|
|
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-Bh_9OtWo.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
|
@@ -246,9 +246,10 @@ function usePage() {
|
|
|
246
246
|
if (!c) throw new Error("usePage must be used inside <PageView> or a <Stage> page");
|
|
247
247
|
return c;
|
|
248
248
|
}
|
|
249
|
-
function makePageContext(documentId, pon, pageIndex, frame, transform, getRect, getViewDemand) {
|
|
249
|
+
function makePageContext(documentId, view, pon, pageIndex, frame, transform, getRect, getViewDemand) {
|
|
250
250
|
return {
|
|
251
251
|
documentId,
|
|
252
|
+
view,
|
|
252
253
|
pon,
|
|
253
254
|
pageIndex,
|
|
254
255
|
frame,
|
package/dist/runtime.js.map
CHANGED
|
@@ -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(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,IAAI,MAAM,mDAAmD;CAC3E,OAAO;AACT;AAEA,MAAa,gBAAoB,GAAiB,MAChD,MAAM,KAAM,EAAE,WAAW,EAAE,UAAU,EAAE,OAAO,GAAG,MAAM,MAAM,EAAE,EAAE;;AAGnE,SAAgB,eACd,QACA,UAAmC,OAAO,IACvC;CACH,MAAM,SAAS,UAAU;CACzB,M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A,UAAG,cAAc,YAAY,KAAK,KAAK,IAAI,KAAO,CAAA;CAE3D,IAAI,CAAC,KAAK,QAAQ,OAAO;CACzB,OACE,oBAAC,UAAU,UAAX;EAAoB,OAAO,KAAK;EAC7B,UAAA,KAAK,UAAU,UAAU,WAAY,YAAY;CAChC,CAAA;AAExB;AACA,MAAa,WAAW;AAgDxB,MAAM,UAAU,cAAuC,IAAI;AAC3D,MAAa,eAAe,QAAQ;AAEpC,SAAgB,UAA4B;CAC1C,MAAM,IAAI,WAAW,OAAO;CAC5B,IAAI,CAAC,GAAG,MAAM,IAAI,MAAM,0DAA0D;CAClF,OAAO;AACT;AAEA,SAAgB,gBACd,YACA,KACA,WACA,OACA,WACA,SACA,eACkB;CAClB,OAAO;EACL;EACA;EACA;EACA;EACA;EACA,GAAI,gBAAgB,EAAE,cAAc,IAAI,CAAC;EACzC,cAAc,IAAI,OAAO;GAKvB,MAAM,IAAI,QAAQ;GAClB,OAAO,UAAU,WAAW;IAAE,GAAG,KAAK,EAAE;IAAM,GAAG,KAAK,EAAE;GAAI,CAAC;EAC/D;EACA,gBAAgB,MAAM;GAIpB,MAAM,IAAI,QAAQ;GAClB,MAAM,IAAI,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.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 * 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 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,YAAY,cAA6B,IAAI;;AAEnD,MAAM,mBAAmB,cAA6B,IAAI;AAE1D,SAAgB,YAAoB;CAClC,MAAM,IAAI,WAAW,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;;AAGnE,SAAgB,eACd,QACA,UAAmC,OAAO,IACvC;CACH,MAAM,SAAS,UAAU;CACzB,MAAM,OAAO,OAAwB,IAAI;CACzC,MAAM,YAAY;EAChB,MAAM,OAAO,OAAO,MAAM;EAC1B,IAAI,KAAK,WAAW,QAAQ,KAAK,QAAQ,GAAG,IAAI,GAAG,OAAO,KAAK,QAAQ;EACvE,KAAK,UAAU,EAAE,GAAG,KAAK;EACzB,OAAO;CACT;CACA,OAAO,qBAAqB,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AM,UAAU,cAAuC,IAAI;AAC3D,MAAa,eAAe,QAAQ;AAEpC,SAAgB,UAA4B;CAC1C,MAAM,IAAI,WAAW,OAAO;CAC5B,IAAI,CAAC,GAAG,MAAM,IAAI,MAAM,0DAA0D;CAClF,OAAO;AACT;AAEA,SAAgB,gBACd,YACA,MACA,KACA,WACA,OACA,WACA,SACA,eACkB;CAClB,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA,GAAI,gBAAgB,EAAE,cAAc,IAAI,CAAC;EACzC,cAAc,IAAI,OAAO;GAKvB,MAAM,IAAI,QAAQ;GAClB,OAAO,UAAU,WAAW;IAAE,GAAG,KAAK,EAAE;IAAM,GAAG,KAAK,EAAE;GAAI,CAAC;EAC/D;EACA,gBAAgB,MAAM;GAIpB,MAAM,IAAI,QAAQ;GAClB,MAAM,IAAI,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"}
|
package/dist/selection.cjs
CHANGED
|
@@ -6,6 +6,8 @@ let react_jsx_runtime = require("react/jsx-runtime");
|
|
|
6
6
|
let react = require("react");
|
|
7
7
|
react = require_rolldown_runtime.__toESM(react, 1);
|
|
8
8
|
let _embedpdf_web = require("@embedpdf/web");
|
|
9
|
+
let _embedpdf_plugin_stage = require("@embedpdf/plugin-stage");
|
|
10
|
+
let _embedpdf_core_geometry = require("@embedpdf/core-geometry");
|
|
9
11
|
let _embedpdf_plugin_selection = require("@embedpdf/plugin-selection");
|
|
10
12
|
let _embedpdf_plugin_selection_internal = require("@embedpdf/plugin-selection/internal");
|
|
11
13
|
//#region src/selection.tsx
|
|
@@ -76,6 +78,147 @@ function SelectionMenu({ children, gap = 8, placement = "top" }) {
|
|
|
76
78
|
children
|
|
77
79
|
});
|
|
78
80
|
}
|
|
81
|
+
const sameEndpoints = (a, b) => {
|
|
82
|
+
if (a === b) return true;
|
|
83
|
+
if (!a || !b) return false;
|
|
84
|
+
return a.start.pon === b.start.pon && a.end.pon === b.end.pon && a.start.advance === b.start.advance && a.end.advance === b.end.advance && (0, _embedpdf_core_geometry.textQuadEquals)(a.start.glyphQuad, b.start.glyphQuad) && (0, _embedpdf_core_geometry.textQuadEquals)(a.end.glyphQuad, b.end.glyphQuad);
|
|
85
|
+
};
|
|
86
|
+
/** The plugin's structural view over this Stage: point-exact projection in,
|
|
87
|
+
* page resolution out. (`pageRectToScreen` is the AABB projector — upright
|
|
88
|
+
* overlays only — and would collapse exactly the orientation handles need.) */
|
|
89
|
+
const handleView = (stage) => ({
|
|
90
|
+
toOverlay: (pon, pt) => {
|
|
91
|
+
const world = stage.pageToWorld(pon, pt);
|
|
92
|
+
return world ? stage.toScreen(world) : null;
|
|
93
|
+
},
|
|
94
|
+
pageAt: (overlay) => stage.pageAt(overlay),
|
|
95
|
+
pointOnPage: (pon, overlay) => stage.pointOnPage(pon, overlay)
|
|
96
|
+
});
|
|
97
|
+
/**
|
|
98
|
+
* iOS-style draggable selection handles. Each is drawn the way the platform
|
|
99
|
+
* draws them: a thin caret BAR that forms the selection's own start/end edge
|
|
100
|
+
* — the boundary glyph's oriented edge, so rotated text and rotated pages
|
|
101
|
+
* carry the handle with them — capped by a screen-constant circle, above the
|
|
102
|
+
* first line at the start, below the last line at the end.
|
|
103
|
+
*
|
|
104
|
+
* On touch, where a caret drag isn't available, the handles ARE the way to
|
|
105
|
+
* grow or shrink a selection: a long-press selects a word, then each handle
|
|
106
|
+
* extends from the OPPOSITE endpoint, snapping to glyphs and crossing pages
|
|
107
|
+
* exactly like a pointer drag — it rides the same `beginAt`/`extendTo`
|
|
108
|
+
* gesture path, so highlights, menus, and commit signals all behave
|
|
109
|
+
* identically. Mount in the `<Stage>` overlay slot next to `<SelectionMenu>`;
|
|
110
|
+
* outside a Stage it renders nothing (a `PageView` has no camera to project
|
|
111
|
+
* through). Pointer-isolated, so grabbing a handle never pans the stage.
|
|
112
|
+
*/
|
|
113
|
+
function SelectionHandles({ color = "#2196f3", token = _embedpdf_plugin_stage.StageToken }) {
|
|
114
|
+
const host = require_runtime.useCapability(_embedpdf_plugin_selection_internal.SelectionToken);
|
|
115
|
+
const stage = require_runtime.useOptionalCapability(token);
|
|
116
|
+
const selecting = require_runtime.useSelector(_embedpdf_plugin_selection.SelectionToken, (c) => c.isSelecting());
|
|
117
|
+
const visible = require_runtime.useSelector(_embedpdf_plugin_selection_internal.SelectionToken, (c) => c.highlightVisible());
|
|
118
|
+
const endpoints = require_runtime.useSelector(_embedpdf_plugin_selection_internal.SelectionToken, (c) => {
|
|
119
|
+
const s = c.snapshot();
|
|
120
|
+
if (!s.start || !s.end) return null;
|
|
121
|
+
return {
|
|
122
|
+
start: {
|
|
123
|
+
pon: s.start.pon,
|
|
124
|
+
glyphQuad: s.start.glyphQuad,
|
|
125
|
+
advance: s.start.advance
|
|
126
|
+
},
|
|
127
|
+
end: {
|
|
128
|
+
pon: s.end.pon,
|
|
129
|
+
glyphQuad: s.end.glyphQuad,
|
|
130
|
+
advance: s.end.advance
|
|
131
|
+
}
|
|
132
|
+
};
|
|
133
|
+
}, sameEndpoints);
|
|
134
|
+
require_runtime.useKernelValue(() => stage?.visiblePages() ?? null);
|
|
135
|
+
const [dragging, setDragging] = (0, react.useState)(null);
|
|
136
|
+
const armSource = (0, react.useRef)(null);
|
|
137
|
+
armSource.current = stage && endpoints ? {
|
|
138
|
+
stage,
|
|
139
|
+
endpoints
|
|
140
|
+
} : null;
|
|
141
|
+
const bindHandle = (0, react.useMemo)(() => {
|
|
142
|
+
const detach = {};
|
|
143
|
+
const make = (role) => (el) => {
|
|
144
|
+
detach[role]?.();
|
|
145
|
+
delete detach[role];
|
|
146
|
+
if (!el) return;
|
|
147
|
+
detach[role] = (0, _embedpdf_web.attachSelectionHandle)(el, { arm: () => {
|
|
148
|
+
const src = armSource.current;
|
|
149
|
+
if (!src) return null;
|
|
150
|
+
const view = handleView(src.stage);
|
|
151
|
+
const geom = (0, _embedpdf_plugin_selection.selectionHandleGeom)(view, src.endpoints[role], role);
|
|
152
|
+
if (!geom) return null;
|
|
153
|
+
const opposite = src.endpoints[role === "start" ? "end" : "start"];
|
|
154
|
+
const drag = (0, _embedpdf_plugin_selection.createSelectionHandleDrag)(host, view, opposite, src.endpoints[role].pon);
|
|
155
|
+
setDragging(role);
|
|
156
|
+
return {
|
|
157
|
+
base: {
|
|
158
|
+
x: (geom.bar.from.x + geom.bar.to.x) / 2,
|
|
159
|
+
y: (geom.bar.from.y + geom.bar.to.y) / 2
|
|
160
|
+
},
|
|
161
|
+
session: {
|
|
162
|
+
move: drag.move,
|
|
163
|
+
end: () => {
|
|
164
|
+
drag.end();
|
|
165
|
+
setDragging(null);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
};
|
|
169
|
+
} });
|
|
170
|
+
};
|
|
171
|
+
return {
|
|
172
|
+
start: make("start"),
|
|
173
|
+
end: make("end")
|
|
174
|
+
};
|
|
175
|
+
}, [host]);
|
|
176
|
+
if (!stage || !endpoints || !visible) return null;
|
|
177
|
+
if (selecting && !dragging) return null;
|
|
178
|
+
const view = handleView(stage);
|
|
179
|
+
const renderHandle = (role) => {
|
|
180
|
+
const geom = (0, _embedpdf_plugin_selection.selectionHandleGeom)(view, endpoints[role], role);
|
|
181
|
+
if (!geom) return null;
|
|
182
|
+
const barTop = _embedpdf_plugin_selection.HANDLE_PAD + (role === "start" ? _embedpdf_plugin_selection.HANDLE_HEAD : 0);
|
|
183
|
+
const pivotX = _embedpdf_plugin_selection.HANDLE_PAD + _embedpdf_plugin_selection.HANDLE_BAR / 2;
|
|
184
|
+
return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
|
|
185
|
+
ref: bindHandle[role],
|
|
186
|
+
style: {
|
|
187
|
+
position: "absolute",
|
|
188
|
+
left: geom.bar.from.x - pivotX,
|
|
189
|
+
top: geom.bar.from.y - barTop,
|
|
190
|
+
width: _embedpdf_plugin_selection.HANDLE_BAR + 2 * _embedpdf_plugin_selection.HANDLE_PAD,
|
|
191
|
+
height: geom.length + _embedpdf_plugin_selection.HANDLE_HEAD + 2 * _embedpdf_plugin_selection.HANDLE_PAD,
|
|
192
|
+
...geom.upright ? null : {
|
|
193
|
+
transform: `rotate(${geom.rotation}deg)`,
|
|
194
|
+
transformOrigin: `${pivotX}px ${barTop}px`
|
|
195
|
+
},
|
|
196
|
+
touchAction: "none",
|
|
197
|
+
cursor: "grab",
|
|
198
|
+
pointerEvents: "auto"
|
|
199
|
+
},
|
|
200
|
+
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { style: {
|
|
201
|
+
position: "absolute",
|
|
202
|
+
left: _embedpdf_plugin_selection.HANDLE_PAD,
|
|
203
|
+
top: barTop,
|
|
204
|
+
width: _embedpdf_plugin_selection.HANDLE_BAR,
|
|
205
|
+
height: geom.length,
|
|
206
|
+
background: color,
|
|
207
|
+
borderRadius: _embedpdf_plugin_selection.HANDLE_BAR / 2
|
|
208
|
+
} }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { style: {
|
|
209
|
+
position: "absolute",
|
|
210
|
+
left: pivotX - _embedpdf_plugin_selection.HANDLE_HEAD / 2,
|
|
211
|
+
top: role === "start" ? _embedpdf_plugin_selection.HANDLE_PAD : _embedpdf_plugin_selection.HANDLE_PAD + geom.length,
|
|
212
|
+
width: _embedpdf_plugin_selection.HANDLE_HEAD,
|
|
213
|
+
height: _embedpdf_plugin_selection.HANDLE_HEAD,
|
|
214
|
+
borderRadius: "50%",
|
|
215
|
+
background: color,
|
|
216
|
+
boxShadow: "0 1px 4px rgba(0, 0, 0, 0.35)"
|
|
217
|
+
} })]
|
|
218
|
+
}, role);
|
|
219
|
+
};
|
|
220
|
+
return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [renderHandle("start"), renderHandle("end")] });
|
|
221
|
+
}
|
|
79
222
|
/**
|
|
80
223
|
* Mount ONCE per viewer to wire clipboard copy: prefetches the selected text
|
|
81
224
|
* when the selection settles, answers the native `copy` event synchronously,
|
|
@@ -90,6 +233,7 @@ function SelectionClipboard({ prefetch } = {}) {
|
|
|
90
233
|
}
|
|
91
234
|
//#endregion
|
|
92
235
|
exports.SelectionClipboard = SelectionClipboard;
|
|
236
|
+
exports.SelectionHandles = SelectionHandles;
|
|
93
237
|
exports.SelectionLayer = SelectionLayer;
|
|
94
238
|
exports.SelectionMenu = SelectionMenu;
|
|
95
239
|
Object.defineProperty(exports, "copySelection", {
|