/** * The React view of @embedpdf/plugin-form. * * `` paints the fields of its page as the engine draws them * (their values, borders and fonts) and puts a real HTML control over each * field box, with or without the annotation plugin. While it's on the page, * the `` leaves the fields out of the page's picture. The * controls add what people interact with on top of the pictures: * * text → the picture at rest; focus shows an editor in the field's font * (the plugin keeps what is typed, so a download writes it); * blur or Enter commits, Escape puts the value back. * toggle → the picture is the control; a click writes the toggled value. * combo → an invisible native : one surface owns the rows, the * keyboard and the scrolling. * button → a native click target over the picture; activation runs the * widget's action. * * What the viewer draws itself (the focus ring, the edge of a field without a * border, the editor) takes its colors from the form settings, which the * `--epdf-form-*` CSS variables override. * * Every control keeps its pointerdown from the interaction hub with a native * listener (`isolatePointerDown`): the Stage listens natively on an ancestor, * so React's synthetic events would run too late. The colors, the field * looks, the boxes' and controls' styles, and the toggle, text-field and * list-box policies are `@embedpdf/web`'s, the same for every framework. */ // One-line-per-feature: registration travels with the UI. export * from '@embedpdf/plugin-form'; import * as React from 'react'; import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react'; import { annotationKey, type EventHook } from '@embedpdf/core'; import { MITER_LIMIT } from '@embedpdf/core-annotation'; import type { PdfAnnotationEventKind } from '@embedpdf/plugin-actions/contract'; import type { AnnotationRef } from '@embedpdf/plugin-annotation/contract'; import { FontsToken } from '@embedpdf/plugin-fonts/contract'; import { FormToken, formState, type FormCapability, type FormFieldRef, type FormFieldValue, type FormWidgetItem, } from '@embedpdf/plugin-form'; import { FormToken as FormHostToken } from '@embedpdf/plugin-form/contract/host'; import { InteractionToken } from '@embedpdf/plugin-interaction/contract/host'; import { RenderToken } from '@embedpdf/plugin-render/contract/host'; import { SignatureToken } from '@embedpdf/plugin-signature/contract'; import { bindFieldFocus, createShownUrls, createTextFieldEditor, FORM_CONTROL_FILL, formColorsOf, isolatePointerDown, listBoxControlStyleOf, loadAppearanceUrls, pictureOrPainting, pressToggle, rectInPixels, shownAppearance, svgShapesOf, textFieldEditorStyleOf, widgetBoxStyleOf, type AppearanceUrl, type FormColors, type MountableFontProgram, } from '@embedpdf/web'; import { NativeListBox } from './form-listbox'; import { FormFocusRing } from './form-focus-ring'; import { usePaintsPagePart } from './page-layers'; import { shallowArray, useCapability, useCapabilityEvent, useDocumentScope, useKernelValue, useOptionalCapability, useOptionalSelector, usePage, useSelector, useViewerSettings, } from './runtime'; import type { PageContextValue } from './runtime'; import { settingsHook, stateHook } from './state'; import { useFontMounts } from './font-mounts'; import { SvgShapes } from './svg-shapes'; // ── what every control shares ────────────────────────────────────────────── /** The colors the viewer draws fields with: the form settings over the viewer's accent. */ function useFormColors(): FormColors { const accent = useViewerSettings((settings) => settings.accent); const focus = useFormSettings((settings) => settings.focus); const fields = useFormSettings((settings) => settings.fields); return useMemo(() => formColorsOf({ focus, fields }, accent), [accent, focus, fields]); } /** * Keep the interaction hub out of gestures that begin inside a control. A * native listener, not React's, so it runs during real DOM bubbling, before * the Stage's own native listener on an ancestor. The press stops there, so * React's own `onPointerDown` never sees it: whoever needs the press passes * `onPress`, which the native listener calls. */ function useIsolated(onPress?: () => void) { const ref = useRef(null); const press = useRef(onPress); press.current = onPress; useEffect( () => (ref.current ? isolatePointerDown(ref.current, () => press.current?.()) : undefined), [], ); return ref; } /** * The widget's pointer and focus events, sent to the actions plugin, which * runs the widget's `/AA` actions (enter, exit, down, up, focus, blur). They * live on the always-active box, never the inner control: "may edit this * field" and "may receive PDF action events" are different rights, and a * session that may not fill must still see hover tooltips. */ function useWidgetEvents( fieldRef: FormFieldRef, annotationRef: AnnotationRef | null, ): Pick< React.DOMAttributes, 'onPointerEnter' | 'onPointerLeave' | 'onPointerUp' | 'onFocus' | 'onBlur' > & { onPress: () => void } { const form = useCapability(FormHostToken); const refBox = useRef(annotationRef); refBox.current = annotationRef; return useMemo(() => { const notify = (event: PdfAnnotationEventKind) => { const target = refBox.current; if (target) form.notifyWidgetEvent(fieldRef, target, event); }; return { onPointerEnter: () => notify('cursorEnter'), onPointerLeave: () => notify('cursorExit'), // The press, from the box's native listener (`useIsolated`). onPress: () => notify('mouseDown'), onPointerUp: () => notify('mouseUp'), // React focus and blur bubble, so the inner control's focus reaches the // box; blur fires after the control's own commit, so a blur script // always sees the committed value. onFocus: () => notify('focus'), onBlur: () => notify('blur'), }; }, [form, fieldRef]); } /** * A click on a widget runs its `/A` action. ISO 32000 puts the activate * action on the widget, whatever its field, and many forms ship "buttons" as * read-only text fields with an `/A` that Acrobat runs; a widget without one * is inert. */ function useWidgetActivation(annotationRef: AnnotationRef | null): () => void { const form = useCapability(FormHostToken); const refBox = useRef(annotationRef); refBox.current = annotationRef; return useCallback(() => { const target = refBox.current; if (target) void form.activateWidget(target); }, [form]); } interface ControlProps { item: Extract; page: PageContextValue; colors: FormColors; } /** * The positioned box every control sits in: the widget's event surface, and * the edge a field without a border of its own gets, so people see where to * fill in. It's also where the form's cursor reaches the control: `focus()` * and Tab go through the form, in the document's order (`bindFieldFocus`), * unless the box has nothing to focus (`focusable`). */ function WidgetBox({ item, page, colors, edge = true, focusable = true, onClick, children, ...rest }: { item: FormWidgetItem; page: PageContextValue; colors: FormColors; edge?: boolean; focusable?: boolean; onClick?: () => void; children?: React.ReactNode; } & Omit, 'onClick' | 'children'>) { const form = useCapability(FormHostToken); const { onPress, ...events } = useWidgetEvents(item.fieldRef, item.annotationRef); const wrap = useIsolated(onPress); const frame = rectInPixels(item.box, page.transform); const widget = item.annotationRef; const takesCursor = focusable && !item.disabled; const radio = item.control === 'toggle' && item.kind === 'radio'; useEffect( () => wrap.current && widget && takesCursor ? bindFieldFocus(wrap.current, form, widget, { radio }) : undefined, [wrap, form, widget, takesCursor, radio], ); return (
{ events.onFocus?.(event); rest.onFocus?.(event); }} onBlur={(event) => { events.onBlur?.(event); rest.onBlur?.(event); }} onClick={onClick} style={{ ...widgetBoxStyleOf(item, frame, colors, { edge }), ...rest.style }} > {children}
); } // ── the controls ─────────────────────────────────────────────────────────── /** A text box: the picture at rest, an editor in the field's own font while focused. */ function TextControl({ item, page, colors }: ControlProps<'text'>) { const form = useCapability(FormHostToken); const activate = useWidgetActivation(item.annotationRef); // The editor is always mounted, see-through at rest and shown while // focused: the DOM is the focus manager, so Tab reaches every field. Typing // drafts, blur or Enter commits, Escape puts the value back. One editing // policy per field (by its key) and form. const editor = useMemo( () => createTextFieldEditor(form, item.fieldRef, item.value), // eslint-disable-next-line react-hooks/exhaustive-deps [form, item.key], ); const { focused, draft } = useSyncExternalStore( editor.subscribe, editor.getState, editor.getState, ); // Take the field's value whenever it changes under us, but never mid-edit. useEffect(() => editor.setValue(item.value), [editor, item.value]); const frame = rectInPixels(item.box, page.transform); // The text being typed, where the engine will draw it, in its fonts: again once they're found. useOptionalSelector(FontsToken, (fonts) => fonts.getPaintFontsEpoch(), 0); const layout = item.annotationRef ? form.getTextEditorLayout(item.annotationRef, draft) : null; useFontMounts(layout ? layout.programs : NO_PROGRAMS); const editorProps = { value: draft, maxLength: item.maxLength ?? undefined, 'aria-label': item.label, disabled: item.disabled, onFocus: editor.focus, onChange: (event: React.ChangeEvent) => editor.input(event.target.value), onBlur: editor.blur, onKeyDown: (event: React.KeyboardEvent) => { if (editor.keyDown(event.key, item.multiline)) event.currentTarget.blur(); }, style: textFieldEditorStyleOf(item, frame, colors, focused, layout), }; return ( // A click runs the widget's action too, as in Acrobat: the editor's // focus click bubbles here, a read-only field's lands here directly. {item.multiline ? (