import * as React from 'react'; import { useEffect, useMemo, useRef, useState } from 'react'; import { createCapabilityToken } from '@embedpdf/core'; import { Viewer, Stage, DocumentScope, RenderLayer, SelectionLayer, AnnotationLayer, AnnotationDraftMenu, AnnotationMenu, AnnotationToken, useAnnotation, useAnnotationState, type CreationDraftAnchor, useAnnotationProperties, useAnnotationDefaults, usePage, useInteraction, useInteractionState, useStage, useStageState, useStageSettings, useDocuments, usePageList, useDocumentsState, useViewManager, useViewManagerState, usePageEdit, useMetadata, useMetadataState, useSelector, FormLayer, useForm, useFormState, FormTransfer, SearchLayer, useSearch, useSearchHits, useSearchState, useStamp, useStampAssets, useStampAssetPreviewUrl, useT, useI18n, useI18nState, stagePlugin, interactionPlugin, selectionPlugin, annotationPlugin, renderPlugin, pageEditPlugin, metadataPlugin, formPlugin, searchPlugin, validateSearchRegex, stampPlugin, i18nPlugin, negotiateLocale, viewManagerPlugin, type Direction, type FlowMode, type GridColumns, type LayoutKind, type SpreadMode, type SizingMode, type StageCapability, type StageSettings, type FormFieldPatch, type StampAsset, type PaneInfo, } from '@embedpdf/react'; import type { AnnotationPatch, AnnotationProperty, FieldValues, LineEndings, TextAlign, } from '@embedpdf/react'; import type { DocumentMetadata, MetadataPatch, OpenInput, PdfSaveMode } from '@embedpdf/core'; import { selectedEngine, engineMode, loadInitialDocuments, newDocument, SAMPLES, fetchBytes, } from './engine'; import { en } from './locales/en'; /** Shared button style for the selection menu overlay. */ const MENU_BTN: React.CSSProperties = { background: 'transparent', border: '1px solid rgba(255,255,255,.18)', borderRadius: 6, color: '#e6e6e6', cursor: 'pointer', fontSize: 12, padding: '3px 8px', }; const DRAFT_MENU_BTN: React.CSSProperties = { width: 40, height: 40, border: '1px solid rgba(255,255,255,.18)', borderRadius: 8, background: 'transparent', color: '#f2f4f8', cursor: 'pointer', fontSize: 20, lineHeight: 1, padding: 0, }; /** The draft menu's contents: anchor DATA arrives via the render prop; the * verbs are plain capability calls — no action bag. */ function DraftMenuBar({ anchor }: { anchor: CreationDraftAnchor }) { const anno = useAnnotation(); const { canFinish, subtype, pointCount, minPoints } = anchor; return (
); } /** The selection menu's contents, composed entirely from hooks: the verbs * from `useAnnotation()`, the reactive reads from selectors — each read is * its own subscription, so nothing here can go stale. */ function AnnotationMenuBar() { const anno = useAnnotation(); const selected = useAnnotationState((state) => state.selected); const canGroup = useSelector(AnnotationToken, (c) => c.selection.canGroup()); const canUngroup = useSelector(AnnotationToken, (c) => c.selection.canUngroup()); return (
{['#e5484d', '#f5a623', '#3858e9', '#30a46c'].map((c) => ( )} {canUngroup && ( )} {(canGroup || canUngroup) && ( )}
); } // The Stage is a LENS: a document can be viewed through several at once. The // sidebar is a second lens — wrapped grid, fixed thumbnail zoom — with its own // camera per document, fully independent of the main view. const ThumbsStageToken = createCapabilityToken('stage-thumbs'); // Plugins are plain, pure values — engine-agnostic. The engine is chosen in // ./engine and injected at the root; nothing here knows local vs cloud vs fake. const plugins = [ stagePlugin({ layout: 'vertical' }), // main lens (tools engage via interactionPlugin below) stagePlugin({ id: 'stage-thumbs', token: ThumbsStageToken, layout: 'grid', columns: 'auto', // WRAPPED: re-wraps as the sidebar resizes sizing: 'uniform', // equalize pages so the pixel target hits every thumb zoom: { pageWidth: 110 }, // thumbs are 110 SCREEN px wide — for ANY document padding: 10, gap: { px: 12 }, // UI-stable spacing: 12px between thumbs in EVERY document pageFrame: { top: 0, right: 0, bottom: 16, left: 0 }, // reserved label band (screen px) fitAlign: { x: 'center', y: 'start' }, // few pages? thumbs hug the TOP, not the middle scrollBehavior: 'instant', interaction: false, // secondary lens: click-to-navigate, never the document's tools }), renderPlugin(), // document-scoped: renders pages through the engine handle pageEditPlugin(), // document-scoped: PON-addressed rotate/move/delete over the handle metadataPlugin(), // document-scoped: reactive Info-dict metadata (own + remote SSE edits) interactionPlugin({ defaultTool: 'pointer' }), // the pointer/tool/cursor hub selectionPlugin(), // text selection (requires the interaction hub) annotationPlugin(), // shapes: create/edit/delete (ambient editing + draw tools) // workspace plugin: stamp ASSET libraries (import a PDF → one vector stamp per // page). No assetEngine configured — the kernel's local engine doubles as the // asset engine; a cloud deployment would add one line here (see StampConfig). stampPlugin(), formPlugin(), // interactive forms: fill mode over doc.forms (fields stay engine truth) // document text search: budgeted engine slices, viewport-first scanning. Hit // navigation lands the match at the viewport's top-middle (y: 0.35 — the // browser find-bar feel); try y: 0.5 for dead center, y: 0.65 for bottom. searchPlugin({ reveal: { align: { y: 0.35 }, behavior: 'smooth' } }), // workspace plugin, engine-free: locale packs as store state. Alive from // createKernel() — the shell below translates while the engine still boots. // 'en' ships eagerly; 'es' is a lazy pack fetched on first switch. The // startup locale is negotiated OUTSIDE the plugin (it never touches the DOM). i18nPlugin({ locale: negotiateLocale(['en', 'es'], navigator.languages) ?? 'en', fallbackLocale: 'en', locales: [en], loaders: { es: () => import('./locales/es').then((m) => m.es) }, }), // workspace plugin: partitions open documents into reorderable panes (each pane // owns its own tab strip; tabs can be dragged between panes). viewManagerPlugin(), ]; // "Presets" are a CUSTOMER concern, not the plugin's: they're just objects of // settings the app keeps and applies with stage.update(...). Define as many as you like. const PRESETS: Record> = { Document: { flow: 'continuous', layout: 'vertical', bounded: true, padding: 24, gap: 16, arrivalAlign: { x: 'start', y: 'start' }, // land at the reading start, at EVERY zoom anchorAlign: { x: 'start', y: 'start' }, // browser-style resizes: the top stays pinned zoomAlign: { x: 'center', y: 'center' }, // button zoom inflates around the middle zoom: { mode: 'automatic' }, }, // Construction: every sheet in view on an infinite canvas, then zoom in to work. // The canvas feel is "all center": arrivals present the sheet, resizes balloon // symmetrically (Figma), zoom stays around the middle. Canvas: { flow: 'continuous', layout: 'grid', bounded: false, padding: 24, gap: 56, // sheets spread out on a table arrivalAlign: { x: 'center', y: 'center' }, // drawings: arrive centered (Drawboard feel) anchorAlign: { x: 'center', y: 'center' }, zoomAlign: { x: 'center', y: 'center' }, zoom: { mode: 'fit-all' }, }, }; // Arrival alignment, expressed as the combos a UI actually offers. The plugin // keeps the orthogonal per-axis primitive; naming the useful pairs is the // app's concern. LOGICAL: 'reading start' = top-left in LTR, top-RIGHT in RTL. const ALIGNMENTS: Record = { 'reading start': { x: 'start', y: 'start' }, // where the text begins (direction-aware) 'reading end': { x: 'end', y: 'start' }, // the far edge of the line center: { x: 'center', y: 'center' }, // drawings (Drawboard feel) }; // ── drag payloads: a tab (document) or a whole pane (view) ─────────────────── type DragPayload = | { kind: 'doc'; documentId: string; fromViewId: string } | { kind: 'view'; viewId: string }; const writePayload = (e: React.DragEvent, payload: DragPayload) => e.dataTransfer.setData('text/plain', JSON.stringify(payload)); const readPayload = (e: React.DragEvent): DragPayload | null => { try { return JSON.parse(e.dataTransfer.getData('text/plain')) as DragPayload; } catch { return null; } }; // A user-defined layer — no SDK involvement, just reads PageContext. function WatermarkLayer() { const page = usePage(); return (
DRAFT
); } // Compact toolbar primitives — small font, tight controls, micro-labels. const tbRow: React.CSSProperties = { display: 'flex', flexWrap: 'wrap', alignItems: 'center', gap: 6, padding: '4px 10px', fontSize: 11, }; const tbSelect: React.CSSProperties = { fontSize: 11, padding: '1px 4px', border: '1px solid #ccc', borderRadius: 4, background: '#fff', }; const tbBtn: React.CSSProperties = { fontSize: 11, padding: '2px 7px', border: '1px solid #ccc', borderRadius: 4, background: '#fff', cursor: 'pointer', }; const tbNum: React.CSSProperties = { ...tbSelect, width: 44 }; const Divider = () => ( ); /** A compact labelled control: a muted micro-label + the input, inline. */ function Field({ label, title, children, }: { label: string; title?: string; children: React.ReactNode; }) { return ( ); } // The /LE line endings the demo can set on a line / polyline (engine wire names). type LineEndingName = | 'none' | 'open-arrow' | 'closed-arrow' | 'r-open-arrow' | 'r-closed-arrow' | 'circle' | 'square' | 'diamond' | 'butt' | 'slash'; const LINE_ENDINGS: { v: LineEndingName; label: string }[] = [ { v: 'none', label: 'none' }, { v: 'open-arrow', label: 'open arrow' }, { v: 'closed-arrow', label: 'closed arrow' }, { v: 'r-open-arrow', label: 'r open arrow' }, { v: 'r-closed-arrow', label: 'r closed arrow' }, { v: 'circle', label: 'circle' }, { v: 'square', label: 'square' }, { v: 'diamond', label: 'diamond' }, { v: 'butt', label: 'butt' }, { v: 'slash', label: 'slash' }, ]; const DRAW_TOOLS = new Set(['square', 'circle', 'line', 'ink']); // Border styles a square/circle can take. A border is three engine fields, so // each option states all of them (a patch replaces each whole); a cloud bulges // out from the shape's box. const BORDER_OPTS: { key: string; label: string; fields: FieldValues }[] = [ { key: 'solid', label: '▭ solid', fields: { borderStyle: 'solid', dashArray: null, cloudyIntensity: null }, }, { key: 'dashed', label: '┄ dashed', fields: { borderStyle: 'dashed', dashArray: [6, 3], cloudyIntensity: null }, }, { key: 'cloudy1', label: '◌ cloud 1', fields: { borderStyle: 'solid', dashArray: null, cloudyIntensity: 1 }, }, { key: 'cloudy2', label: '◌ cloud 2', fields: { borderStyle: 'solid', dashArray: null, cloudyIntensity: 2 }, }, ]; const borderKey = (values: FieldValues): string => { const intensity = values.cloudyIntensity as number | null | undefined; if (intensity) return `cloudy${intensity >= 2 ? 2 : 1}`; return values.borderStyle === 'dashed' ? 'dashed' : 'solid'; }; const NO_ENDS = { start: 'none', end: 'none' } as const; const TOOLS: { id: string; label: string; title: string }[] = [ { id: 'pointer', label: '↖ select', title: 'select text or drag to select annotations' }, { id: 'form-fill', label: '✍ fill', title: 'fill form fields' }, { id: 'pan', label: '✋ pan', title: 'pan (hand)' }, { id: 'square', label: '▭ square', title: 'draw a square' }, { id: 'circle', label: '◯ circle', title: 'draw a circle' }, { id: 'line', label: '╱ line', title: 'draw a line' }, { id: 'polygon', label: '⬠ polygon', title: 'click vertices, double-click to finish' }, { id: 'polyline', label: '⌁ polyline', title: 'click vertices, double-click to finish' }, { id: 'ink', label: '✎ ink', title: 'draw freehand' }, { id: 'free-text', label: 'T text', title: 'add a text box (drag or click, then type)' }, { id: 'free-text-callout', label: '↳ callout', title: 'click the tip, click the elbow, then drag/click the text box', }, ]; // Text-selection tools create from a TEXT SELECTION (select text with the tool active). const MARKUP_TOOLS: { id: string; label: string; title: string }[] = [ { id: 'highlight', label: '🖍 highlight', title: 'select text to highlight' }, { id: 'underline', label: 'U̲ underline', title: 'select text to underline' }, { id: 'strikeout', label: 'S̶ strikeout', title: 'select text to strike out' }, { id: 'squiggly', label: '∿ squiggly', title: 'select text to squiggly-underline' }, { id: 'insert-text', label: '⌃ caret', title: 'select text to add an insert caret' }, ]; const MARKUP_SUBTYPES = new Set(['highlight', 'underline', 'squiggly', 'strikeout']); // Field palette: draw (or click) to place a field; the widget is instantly a // selectable annotation, and the field panel appears in the styles sidebar. const FORM_DESIGN_TOOLS: { id: string; label: string; title: string }[] = [ { id: 'form-text', label: '▭ field', title: 'draw a text field' }, { id: 'form-checkbox', label: '☑ check', title: 'place a checkbox' }, { id: 'form-radio', label: '◉ radio', title: 'place a radio option' }, { id: 'form-combobox', label: '▾ dropdown', title: 'draw a dropdown' }, { id: 'form-listbox', label: '≡ list', title: 'draw a list box' }, ]; /** * The stamp tool button: opens a file picker (PNG / JPEG / single-page PDF) * and arms the payload — every subsequent page click places one stamp until * the tool changes. One line of integration: `annotation.stamps.arm({ source })`. */ function StampButton({ active }: { active: boolean }) { const annotation = useAnnotation(); const fileRef = useRef(null); return ( <> { const file = e.target.files?.[0]; if (file) void annotation.stamps.arm({ source: file }); e.target.value = ''; // allow re-picking the same file later }} /> ); } /** * The stamp LIBRARY strip: import any PDF as a library (each page becomes one * VECTOR stamp), thumbnails render from the plugin's cached previews, and a * click arms the asset — hovering a page then ghosts the exact placement, and * every click places one. Total integration: `stampPlugin()` + three hooks. */ function StampLibraryBar() { const stamp = useStamp(); const assets = useStampAssets(); const { activeToolId } = useInteractionState(); const fileRef = useRef(null); const [armedId, setArmedId] = useState(null); const [busy, setBusy] = useState(false); // The hub owns tool state: leaving the stamp tool un-highlights the gallery. useEffect(() => { if (activeToolId !== 'stamp') setArmedId(null); }, [activeToolId]); const importPdf = (source: Blob, name: string) => { setBusy(true); stamp .importLibrary(source, { name }) .catch((err) => console.error('[demo] library import failed:', err)) .finally(() => setBusy(false)); }; return (
{assets.length === 0 && ( )} { const file = e.target.files?.[0]; e.target.value = ''; if (file) importPdf(file, file.name.replace(/\.pdf$/i, '')); }} /> {assets.map((a) => ( { setArmedId(a.id); void stamp.armAsset(a.id).catch((err) => console.error('[demo] arm failed:', err)); }} /> ))}
); } /** One gallery thumbnail: the plugin's cached preview via an object-URL hook. */ function StampAssetButton({ asset, armed, onArm, }: { asset: StampAsset; armed: boolean; onArm: () => void; }) { const url = useStampAssetPreviewUrl(asset.id); return ( ); } /** * The tool band: the interaction hub's single active tool, switched in one place * (select / pan + the draw tools). The "styles" button opens the property sidebar — * it's opt-in, so the canvas stays full-width until you actually want to edit. */ function AnnotationBar({ stylesOpen, onToggleStyles, }: { stylesOpen: boolean; onToggleStyles: () => void; }) { const interaction = useInteraction(); const { activeToolId } = useInteractionState(); const activate = interaction.activateTool; const annotation = useAnnotation(); // Seed the line tool with an arrow default (Adobe's "line arrow"), demonstrating // per-tool configurable defaults — the sidebar lets you change it live. The fill // default makes a CLOSED ending (closed arrow / circle / square) solid out of the // box; stroke and fill stay independently editable. useEffect(() => { annotation.tools.updateDefaults('line', { interiorColor: '#e5484d', lineEndings: { start: 'none', end: 'open-arrow' }, }); }, [annotation]); return (
{TOOLS.map((t) => ( ))} {/* stamp: pick an image (or single-page PDF), then click a page to place it — `stamps.arm` validates the bytes and activates the stamp tool itself */}
{/* stamp library: import a PDF, click a thumbnail, hover a page — the ghost previews the exact placement (v2 rubber-stamp feel, vector content) */} {/* text-selection tools: created by selecting text with the tool active */}
{MARKUP_TOOLS.map((t) => ( ))}
{FORM_DESIGN_TOOLS.map((t) => ( ))}
); } /** Fields in and out: save every field as a bundle file, or copy a bundle's fields in. */ function FormDataButtons() { const form = useForm(); const [note, setNote] = useState(''); return (
{note && {note}}
); } /** A vertical labelled control for the sidebar: a micro-label stacked over the input. */ function SideField({ label, title, children, }: { label: string; title?: string; children: React.ReactNode; }) { return ( ); } // The standard PDF fonts the demo offers (any registered font key works too). const FONT_OPTIONS: { v: string; label: string }[] = [ { v: 'helvetica', label: 'Helvetica' }, { v: 'helvetica-bold', label: 'Helvetica Bold' }, { v: 'times-roman', label: 'Times Roman' }, { v: 'courier', label: 'Courier' }, ]; /** * ONE control for ONE field spec — the entire per-field UI. The spec's `key` * is the engine field (the border picker states three), and fixes the control * type and its constraints (min/max/step, cloudy); `onChange` emits * `{ [key]: value }`. This switch is the whole surface an app customizes — the * plugin decides WHICH controls show, in what order, per kind (see * `useSelectionFields` / `useToolFields`). */ function FieldControl({ spec, values, mixed, onChange, onChangeEach, }: { spec: AnnotationProperty; values: FieldValues; mixed: boolean; onChange: (patch: FieldValues) => void; /** Patch each target relative to itself: one side of its line endings. */ onChangeEach: (patchOf: (current: FieldValues) => FieldValues) => void; }) { const value = values[spec.key]; const colorInput = (v: string, set: (c: string) => void) => ( set(e.target.value)} style={{ width: 36, height: 24, padding: 0, border: '1px solid #ccc', borderRadius: 4 }} /> ); const label = mixed ? `${spec.label} (mixed)` : spec.label; switch (spec.key) { case 'color': case 'fontColor': return ( {colorInput((value as string) ?? '#000000', (c) => onChange({ [spec.key]: c }))} ); case 'interiorColor': { const fill = (value as string | null) ?? null; return ( onChange({ interiorColor: e.target.checked ? '#ffffff' : null })} style={{ margin: 0 }} /> {colorInput(fill ?? '#ffffff', (c) => onChange({ interiorColor: c }))} ); } case 'opacity': return ( onChange({ opacity: Number(e.target.value) })} style={{ width: '100%' }} /> ); case 'strokeWidth': case 'fontSize': return ( { const n = Number(e.target.value); if (Number.isFinite(n)) onChange({ [spec.key]: n }); }} style={{ ...tbSelect, width: '100%' }} /> ); case 'borderStyle': { const opts = spec.cloudy ? BORDER_OPTS : BORDER_OPTS.filter((o) => !o.key.startsWith('cloudy')); return (
{opts.map((o) => ( ))}
); } case 'lineEndings': { const ends = (value as LineEndings) ?? { start: 'none', end: 'none' }; const side = (which: 'start' | 'end') => ( ); return ( <> {side('start')} {side('end')} ); } case 'fontFamily': return ( ); case 'textAlign': return (
{(['left', 'center', 'right'] as TextAlign[]).map((al) => ( ))}
); } } /** * The FIELD plane panel: appears when the selection is a single widget. * Style props above it stay schema-driven (the widget client kinds declare * them); this edits what only the form plugin owns — name, required, * options — and routes deletion to the right door (cascade vs detach). */ function FieldPanel() { const form = useForm(); const field = useFormState((state) => state.selectedField); if (!field) return null; const patch = (p: Record) => void form.update(field.ref, { kind: field.kind, ...p } as FormFieldPatch); return (
Field · {field.kind} { const next = e.target.value.trim(); if (next && next !== field.name.split('.').pop()) patch({ name: next }); }} style={{ ...tbSelect, width: '100%' }} /> {(field.kind === 'combobox' || field.kind === 'listbox') && (