/** * 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. * * An app draws a box with a control of its own through `controls` * ({@link FieldControl}), and attaches UI to a box with * `useFormWidgetAnchor()` and ``. */ // One-line-per-feature: registration travels with the UI. export * from '@embedpdf/plugin-form'; import * as React from 'react'; import { createContext, useCallback, useContext, 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 FormSetValueResult, type FormWidgetAnchor, type FormWidgetItem, } from '@embedpdf/plugin-form'; import { FormToken as FormHostToken, type ShownWidget, type WidgetPainting, } from '@embedpdf/plugin-form/contract/host'; import { RenderToken } from '@embedpdf/plugin-render/contract/host'; import { SignatureToken } from '@embedpdf/plugin-signature/contract'; import { autocompleteOf, bindFieldFocus, claimClick, createFieldControlPress, createShownUrls, createTextFieldEditor, fieldControlFor, fieldControlPlaceOf, fieldPlaceholderStyleOf, FORM_CONTROL_FILL, formColorsOf, isClickClaimed, isolatePointerDown, listBoxControlStyleOf, loadAppearanceUrls, pictureOrPainting, pressToggle, rectInPixels, runsActionOnClick, samePageBounds, shownAppearance, svgShapesOf, textFieldEditorStyleOf, widgetBoxStyleOf, type AppearanceUrl, type FieldControlFrame, type FormColors, type MountableFontProgram, type PictureOrPainting, } from '@embedpdf/web'; export type { FieldControlFrame } from '@embedpdf/web'; import { NativeListBox } from './form-listbox'; import { FormFocusRing } from './form-focus-ring'; import { INERT } from './inert'; 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, isolated = true) { const ref = useRef(null); const press = useRef(onPress); press.current = onPress; useEffect( () => ref.current && isolated ? isolatePointerDown(ref.current, () => press.current?.()) : undefined, [isolated], ); return ref; } /** * True for the layer's own control drawn inside a control of the app's * (`native`): the app's box is then the widget's event surface and the * cursor's way in, and the layer's control only fills it. */ const EmbeddedContext = createContext(false); /** * 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`). * A box with nothing to focus says so (`focusable={false}`), and the cursor * passes over it. `custom`: the box holds a control of the app's, and the * cursor goes to the first element in it that Tab stops at. * * Inside a control of the app's ({@link EmbeddedContext}) the box only fills * the place it is given: the app's box around it sends the widget's events * and takes the cursor, and a click this one handled is left alone there. */ function WidgetBox({ item, page, colors, edge = true, focusable = true, custom = false, onClick, children, ...rest }: { item: FormWidgetItem; page: PageContextValue; colors: FormColors; edge?: boolean; focusable?: boolean; custom?: boolean; onClick?: (event: React.MouseEvent) => void; children?: React.ReactNode; } & Omit, 'onClick' | 'children'>) { const form = useCapability(FormHostToken); const embedded = useContext(EmbeddedContext); const { onPress, ...events } = useWidgetEvents(item.fieldRef, item.annotationRef); const wrap = useIsolated(onPress, !embedded); const frame = rectInPixels(item.box, page.transform); const widget = item.annotationRef; // While the layer only shows its controls (an `inert` layer), no box lends the cursor a way in. const filling = useSelector(FormHostToken, (host) => host.getLayerMode() === 'fill'); const takesInput = !item.disabled && !embedded && filling; const radio = item.control === 'toggle' && item.kind === 'radio'; useEffect( () => wrap.current && widget && takesInput ? bindFieldFocus(wrap.current, form, widget, { radio, custom, focusable }) : undefined, [wrap, form, widget, takesInput, radio, custom, focusable], ); if (embedded) { return (
{ claimClick(event.nativeEvent); onClick?.(event); }} style={{ ...widgetBoxStyleOf( { look: item.look, accent: item.accent, yours: item.yours }, { left: 0, top: 0, width: frame.width, height: frame.height }, colors, { edge }, ), ...rest.style, }} > {children}
); } 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}
); } /** * What an empty field shows for its purpose: the layer's paint over the field's picture, never * the field's value. Mounted only for a box that has a placeholder, so a form without purposes * draws what it drew before. Its color is the form's `fields.placeholder`. */ function FieldPlaceholder({ item, page }: { item: FormWidgetItem; page: PageContextValue }) { const color = useSelector(FormHostToken, (form) => form.getSettings().fields.placeholder); const frame = rectInPixels(item.box, page.transform); return ( ); } // ── the controls ─────────────────────────────────────────────────────────── /** A text box: the picture at rest, an editor in the field's own font while focused. */ const TextControl = React.memo(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, // What the field is for: the browser may offer the person's saved value, and a screen // reader hears what an empty box asks for. autoComplete: autocompleteOf(item.purpose), 'aria-placeholder': item.placeholder ?? undefined, 'aria-description': item.hint ?? undefined, 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 ? (