/** * RenderLayer — the React view of @embedpdf/plugin-render. The page raster * is one concern with two planes: * * - the base plane: a whole-page at the plugin's resolved render * points — the exact settled demand capped at the pixel budget on a * continuous (local) engine, the advertised ladder on a lattice (cloud) * deployment. Always present; the instant backdrop. * - the tile plane: the plugin's retention-safe paint plan above it, * engaging by demand arithmetic when the view wants more pixels than * the base may spend. A thumbnail-sized demand engages nothing — the * arithmetic is the configuration. * * The layer is a dumb painter, deliberately thin: plain s bound through * the shared browser adapter, with painted/unpainted reports around their * visible lifetime. Every decision — strategy ∧ policy conformance, want * sets, level settling, retention, release — is plugin-render's; anything * mid-gesture simply CSS-scales until the plugin hands down new pixels. */ // One-line-per-feature: registration travels with the UI. export * from '@embedpdf/plugin-render'; // The snapshot's commands, made with the browser's clipboard and file download. export { renderCommands } from './command-lists'; import * as React from 'react'; import { useEffect, useLayoutEffect, useMemo, useRef } from 'react'; // The layer is a host of the render plugin: it paints conformed sources and // drives a view's tile demand. The host lens is the same runtime token. import { RenderToken } from '@embedpdf/plugin-render/contract/host'; import type { OpenPictureReport, PageViewDemand, TilePaintSource, } from '@embedpdf/plugin-render/contract/host'; import { RenderToken as RenderPublicToken } from '@embedpdf/plugin-render'; import type { PaintedPicture, PicturePainter, PictureState, RenderCapability, Snapshot, } from '@embedpdf/plugin-render'; import type { EventHook } from '@embedpdf/core'; import { bindPaintedImage, pageLayersOf, partsDrawnTwice, pictureLayerOptionsOf, rectInPixels, SNAPSHOT_BOX_DASH, snapshotBoxPaint, whenPresented, type PicturePartProps, } from '@embedpdf/web'; import { Anchored, type AnchoredPlacement } from './anchored'; import { devWarn } from './dev'; import { usePaintedParts } from './page-layers'; import { useCapability, useCapabilityEvent, useOptionalSelector, usePage, useSelector, useViewerSettings, } from './runtime'; import { settingsHook } from './state'; /** The render capability (renderPage / renderThumbnail / invalidation / settings) for app code. */ export function useRender(): RenderCapability { return useCapability(RenderPublicToken); } /** The render settings (`fullPage`, `tiles`, `format`, …), with or without a document. Takes a selector. */ export const useRenderSettings = settingsHook(RenderPublicToken); /** Subscribe to one render event for the mounted lifetime: `useRenderEvent((render) => render.onInvalidated, handler)`. */ export function useRenderEvent( select: (render: RenderCapability) => EventHook, handler: (event: T) => void, ): void { useCapabilityEvent(RenderPublicToken, select, handler); } const NO_PICTURE: PictureState = Object.freeze({ status: 'idle', slow: false }); /** * Whether the picture of the page this component is drawn on is on screen in its view: * `{ status, slow }`. `status` is `'loading'` until it is, and `slow` turns on once it waited * `slowAfterMs` (400 ms): the moment to show a loading indicator. Use it in a layer of the page. */ export function usePictureState(): PictureState { const page = usePage(); return useOptionalSelector( RenderPublicToken, (render) => render.getPictureState(page.ref, page.view), NO_PICTURE, ); } export interface RenderLayerProps { /** * Draw the annotations into the page's picture (`true`) or leave them out * (`false`). Left unset, the picture leaves them to an `` * on the page, and otherwise draws them when the user may read them. */ annotations?: boolean; /** The same for the form fields, which a `` paints. */ formFields?: boolean; /** * Mount the tile plane (default true). Whether it spends anything is * demand arithmetic — leave it on; pass false only for a lens that must * never tile even under deep zoom. */ tiles?: boolean; /** * Draw the page's thumbnail instead: one small picture of the whole page, * without tiles, which needs only `doc.render.thumbnail` (a strip of * thumbnails, a page picker). */ thumbnail?: boolean; } let warnedTileSize = false; export function RenderLayer(props: RenderLayerProps = {}) { const page = usePage(); // Another plugin may paint this view's pictures (`handOverPictures`): the layer lends it its box. const painter = useSelector(RenderToken, (render) => render.getPicturePainter()); if (painter?.paints(page.view)) { return } />; } return ; } /** * The page's box, lent to the plugin that paints its picture: it paints into it once, follows the * page as it changes, and takes the picture away when the page goes or the painter is given back. */ function PainterBox({ painter }: { painter: PicturePainter }) { const page = usePage(); const host = useRef(null); const render = useCapability(RenderToken); const painted = useRef<{ picture: PaintedPicture; page: typeof page } | null>(null); useLayoutEffect(() => { // The page is loading until the painter reports its picture on screen. const report = render.reportPicture(page.view, page.ref); painted.current = { picture: painter.paint(host.current!, page, report), page }; return () => { painted.current?.picture.destroy(); painted.current = null; report.close(); }; // eslint-disable-next-line react-hooks/exhaustive-deps -- a new page context is an // update of the same picture, below; only another painter or page paints anew. }, [render, painter, page.ref]); useLayoutEffect(() => { const current = painted.current; if (!current || current.page === page) return; current.page = page; current.picture.update(page); }, [page]); return (
); } /** The render plugin's own picture: the base plane and the tiles. */ function RasterLayer({ annotations, formFields, tiles = true, thumbnail = false, }: RenderLayerProps) { const page = usePage(); const render = useCapability(RenderToken); // The same object until a setting it reads changes, so a settings change re-renders the layer. const settings = useSelector(RenderToken, (render) => render.getPaintSettings()); const ref = useRef(null); const report = useRef(null); const parts: PicturePartProps = { annotations, formFields }; const painted = usePaintedParts(page.ref); const may = useSelector(RenderToken, (render) => render.getLayerRights()); const layers = pictureLayerOptionsOf(painted, parts, may); if (partsDrawnTwice(painted, parts).length > 0) { devWarn( 'render-layer-draws-what-a-layer-paints', ' or draws what an or a ' + ' on the page paints too, so it shows twice. Leave the prop out: the picture ' + 'leaves out what a layer paints.', ); } // One dependency: the raster's canonical identity — conformed width + // the parts it draws + epoch. Under a lattice it moves only at rung // crossings; under exact mode it tracks the demand and is constant above // the budget — so the deep-zoom backdrop never refetches, and the sub- // budget range refetches once per settled demand. // A thumbnail asks for one; anything else leaves the option out, as the plugin's default. const asked = thumbnail ? ({ thumbnail: true } as const) : {}; const sourceKey = useSelector(RenderToken, (render) => render.getSourceKey(page.ref, { scale: page.transform.renderScale, ...asked, ...layers }), ); // The page is loading in this view until the base picture is on screen; the tiles only sharpen. useLayoutEffect(() => { const opened = render.reportPicture(page.view, page.ref); report.current = opened; const stop = whenPresented(ref.current!, () => opened.shown()); return () => { stop(); opened.close(); if (report.current === opened) report.current = null; }; }, [render, page.view, page.ref]); useEffect(() => { // A layer that paints part of the page arrived in this commit, after this // render read the page's layers: the render it causes fetches instead. if (pageLayersOf(page.ref).painted() !== painted) return; const controller = new AbortController(); let revoke: (() => void) | undefined; (async () => { try { // The capability conforms this to the resolved render points and // collapses same-key asks in its raster store. A stale-closure scale // is harmless by construction: any scale mapping to this key // produces this key's canonical request. const image = await render.renderSource(page.ref, { scale: page.transform.renderScale, ...asked, ...layers, view: page.view, signal: controller.signal, }); const obj = await image.objectUrl().abortWith(controller.signal); if (controller.signal.aborted) { obj.revoke(); return; } revoke = obj.revoke; // Imperative src on a stable element: the browser keeps the old // bitmap until the new one decodes, and nothing ever re-requests the // old URL — so revoke-on-cleanup is safe here by construction. if (ref.current) ref.current.src = obj.url; } catch (error) { // Aborted (camera moved / unmounted), or the render failed: the page can't show. if (!controller.signal.aborted) report.current?.failed(error); } })(); return () => { controller.abort(); revoke?.(); }; // eslint-disable-next-line react-hooks/exhaustive-deps -- sourceKey is the // render identity; scale/parts/epoch are folded into it upstream. `painted` // runs the fetch skipped above even when the key comes out the same. }, [render, page.ref, sourceKey, painted]); return ( <> {tiles && !thumbnail && settings.tiles ? : null} ); } /** * The sharp plane above the base — the plugin's retention-safe paint plan * as keyed s. Each tile reports painted after its first presentation * opportunity (and its inverse on unmount), so retained coarser generations * release only when their replacement is truly compositable. * * Tiles are placed in view (CSS px) space directly — never in page points * under a scaled container. Blink quantizes layout lengths to 1/64 CSS px * before transforms apply, so a pt-space rect under a ×25 zoom transform * turns that harmless 1/64 into ±0.4px+ of per-tile misplacement — visible * seams and per-zoom-step letter shifts that grow with depth. In view * space the same quantization is a fixed ~1/64 CSS px at every zoom. */ function TilePlane({ parts }: { parts: PicturePartProps }) { const page = usePage(); const render = useCapability(RenderToken); // Demand: the host's live camera view (Stage) or whole-page (PageView). // Level settling lives in the plugin (its settle gate), pan stays live. const demand: PageViewDemand = page.getViewDemand?.() ?? { desiredDeviceWidth: page.transform.deviceWidth, }; // This view's tile surface: state is per view × page, so a thumbnail // rail's never-engaging demand cannot disturb the main lens's plan (shared // state made the main view lose its tiles whenever a rail opened). The // handle is reference-stable per view and reference-counted — one // `destroy` per `createViewDemand`. const view = useMemo(() => render.createViewDemand(page.view), [render, page.view]); useEffect(() => () => view.destroy(), [view]); // Demand in, plan out: setting the demand is the one call that schedules // fetches (and re-plans); the read below is pure. Layout-timed so a camera // move re-plans before the browser paints this commit. The page's layers // are read now, not at render: one mounted in this commit has said what it // paints by the time layout effects run. useLayoutEffect(() => { const painted = pageLayersOf(page.ref).painted(); const layers = pictureLayerOptionsOf(painted, parts, render.getLayerRights()); view.setDemand(page.ref, demand, layers); }); const plan = useSelector(RenderToken, () => view.getPlan(page.ref)); // View unmounted its plane: stop in-flight fetches; resolved bytes stay cached. useEffect(() => () => view.release(page.ref), [view, page.ref]); if (plan.paint.length === 0) return null; const transform = page.transform; const viewScale = transform.viewScale; return (
s carry zIndex ranks (coarse under // fine) that exist only while generations are mixed — mid-zoom. This // container must be a stacking context so those ranks stay internal; // without it they join the Stage's context and paint above every // z-auto sibling (annotations, page chrome, menus) exactly while // zooming. The old scaled container created one implicitly via its // transform; `isolation` is the explicit, no-side-effect way. isolation: 'isolate', }} > {plan.paint.map((source) => ( view.markPainted(page.ref, source.key)} onUnpainted={() => view.markUnpainted(page.ref, source.key)} /> ))}
); } /** One tile: geometry plus the shared browser image binding. The binding * hides the incomplete image, reports painted after its first presentation * opportunity, and inverts that report when the element leaves the DOM. */ function TileImg({ source, view, onPainted, onUnpainted, }: { source: TilePaintSource; /** Placement rect in view (CSS px) space. */ view: { x: number; y: number; width: number; height: number }; onPainted: () => void; onUnpainted: () => void; }) { const ref = useRef(null); useLayoutEffect(() => { if (!ref.current) return; return bindPaintedImage(ref.current, source.handle, { onPainted, onUnpainted }); // eslint-disable-next-line react-hooks/exhaustive-deps -- the handle is // the bitmap's identity; the report callbacks carry stable values. }, [source.handle]); return ( { // A raster whose intrinsic size disagrees with its rect would be // silently stretched into place — the stale-handle bug class. const naturalWidth = event.currentTarget.naturalWidth; if (naturalWidth > 0 && !warnedTileSize) { const expected = Math.round(source.rect.width * source.scale); if (Math.abs(naturalWidth - expected) > 1) { warnedTileSize = true; console.warn( `[render] tile bitmap ${naturalWidth}px wide does not match its rect ` + `(expected ~${expected}px) — stale raster identity? key=${source.key}`, ); } } }} style={{ position: 'absolute', left: view.x, top: view.y, width: view.width, height: view.height, zIndex: source.z, }} /> ); } /** * The snapshot the `snapshot` tool holds, or `null`: `{ page, rect, image }`, the same object while * it's held. Copy it with `copyImage(snapshot.image)`, in the click itself. */ export function useSnapshot(): Snapshot | null { return useOptionalSelector(RenderPublicToken, (render) => render.getSnapshot(), null); } export interface SnapshotMenuProps { children: React.ReactNode; /** Gap in screen px between the snapshot's box and the menu (default 8). */ gap?: number; /** Where to place the menu around the box. Default 'bottom'. */ placement?: AnchoredPlacement; } /** * Floats by the snapshot the `snapshot` tool holds, once it's taken: hidden * while the box is still dragged, it appears when the pointer lifts. Works * under `` (mount in the overlay slot) and `` alike, the * surface providing the projection. Compose the contents from * `useSnapshot()`, `copyImage` and `saveFile`. */ export function SnapshotMenu({ children, gap = 8, placement = 'bottom' }: SnapshotMenuProps) { const snapshot = useSnapshot(); const anchor = useMemo( () => snapshot && { page: snapshot.page, bounds: snapshot.rect }, [snapshot], ); if (!anchor) return null; return ( {children} ); } /** * The `snapshot` tool's box on this page, while it's dragged and while it's * held: the plugin's box in page space, in the page layer's pixels. It only * draws; the tool's handler takes the pointer. Put it in each page, after the * other layers. */ export function SnapshotLayer() { const page = usePage(); const box = useOptionalSelector(RenderToken, (render) => render.getSnapshotBox(page.ref), null); const colors = useRenderSettings((settings) => settings.snapshot.box); // Unset colors follow the viewer's accent, behind the `--epdf-accent` variable. const accent = useViewerSettings((settings) => settings.accent); if (!box) return null; const { left, top, width, height } = rectInPixels(box, page.transform); return ( ); }