(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 ? (
) : (
)}
);
}
/**
* A checkbox or a radio button: the picture is the control, a click writes the toggled value. A
* radio button's label names its option, and it says where it comes in its group: its buttons
* are placed apart, so no group element can.
*/
function ToggleControl({ item, page, colors }: ControlProps<'toggle'>) {
const form = useCapability(FormHostToken);
const activate = useWidgetActivation(item.annotationRef);
const [focused, setFocused] = useState(false);
// The value first, then the widget's action (Acrobat's order).
const press = () => pressToggle(form, item, activate);
const inGroup = item.kind === 'radio' ? item.inGroup : null;
return (
setFocused(true)}
onBlur={() => setFocused(false)}
onKeyDown={(event) => {
if (event.key === ' ' || event.key === 'Enter') {
event.preventDefault();
press();
}
}}
style={{ cursor: item.disabled ? 'default' : 'pointer', outline: 'none' }}
>
);
}
/** A dropdown: an invisible native select over the field's picture. */
function ComboControl({ item, page, colors }: ControlProps<'choice'>) {
const form = useCapability(FormHostToken);
const activate = useWidgetActivation(item.annotationRef);
const [focused, setFocused] = useState(false);
return (
{/* Controlled, never made again on a change: a new select would drop the focus to the page
while the old one never reports its blur. */}
setFocused(true)}
onBlur={() => setFocused(false)}
onChange={(event) =>
void form.setValue(item.fieldRef, { value: event.currentTarget.value || null })
}
style={{
...FORM_CONTROL_FILL,
opacity: 0,
cursor: item.disabled ? 'default' : 'pointer',
...(item.disabled ? { pointerEvents: 'none' as const } : {}),
}}
>
{item.selected.length === 0 && }
{item.options.map((option, index) => (
{option.label}
))}
);
}
/** A list: a visible native select in the field's own look, the settings where it has none. */
function ListControl({ item, page, colors }: ControlProps<'choice'>) {
const form = useCapability(FormHostToken);
const activate = useWidgetActivation(item.annotationRef);
const [focused, setFocused] = useState(false);
const frame = rectInPixels(item.box, page.transform);
// The rows in the widget's font, as the engine picks it: again once the document's fonts are read.
const font = useSelector(FormHostToken, (host) =>
item.annotationRef ? host.getWidgetFontCss(item.annotationRef) : null,
);
useFontMounts(font ? font.programs : NO_PROGRAMS);
return (
setFocused(true)}
onBlur={() => setFocused(false)}
onSelect={async (values) => {
await form.setValue(item.fieldRef, { selectedValues: values });
}}
style={listBoxControlStyleOf(item, frame, colors, font)}
/>
);
}
/** A push button: a native click target over its picture that runs its action. */
function ButtonControl({ item, page, colors }: ControlProps<'button'>) {
const activate = useWidgetActivation(item.annotationRef);
return (
);
}
/**
* A signature field: with the signature plugin, an empty field is "sign
* here" (it becomes the target the next mark goes to), and a signed one asks
* your UI to show its details. Without it, the field is only its picture.
*/
function SignatureControl({ item, page, colors }: ControlProps<'signature'>) {
const signature = useOptionalCapability(SignatureToken);
const ref = item.fieldRef;
// The signature plugin knows best whether it's signed (it reads again after
// every new version); the field's own value is the fallback.
const signed = useOptionalSelector(
SignatureToken,
(capability) => capability.getSignature(ref)?.signed ?? item.signed,
item.signed,
);
const actionable = signature !== null && (signed || !item.disabled);
return (
{actionable ? (
(signed ? signature.requestInspection(ref) : signature.setTarget(ref))}
style={{
...FORM_CONTROL_FILL,
padding: 0,
border: 0,
background: 'transparent',
cursor: 'inherit',
}}
/>
) : null}
);
}
/**
* The form's fields on one page: their pictures, and the controls people fill
* them in with. Put it above the page's picture (``, and
* `` when the annotation plugin is registered); while it's
* there, the render layer leaves the fields out of the page's picture. The
* controls show while the active tool fills forms (the `pointer` and `pan`
* tools do), and stand down in design mode, where fields are boxes you
* select and move.
*/
export function FormLayer() {
const page = usePage();
const form = useCapability(FormHostToken);
const colors = useFormColors();
const active = useSelector(InteractionToken, (interaction) =>
interaction.activeToolEnables('form-fill'),
);
usePaintsPagePart(page.ref, 'formFields');
useEffect(() => {
void form.ensureLoaded(page.ref);
}, [form, page.ref]);
const items = useSelector(
FormHostToken,
(capability) => capability.listWidgets(page.ref),
shallowArray,
);
return (
{(active ? items : []).map((item) => {
const key = `${item.key}:${item.annotObjectNumber}`;
switch (item.control) {
case 'text':
return ;
case 'toggle':
return ;
case 'choice':
return item.kind === 'list' ? (
) : (
);
case 'button':
return ;
case 'signature':
return ;
}
})}
);
}
/**
* The page's fields as they look now. Each widget shows its picture, as the
* engine draws it (the form plugin's, every state loaded, so a check box
* shows its new state at once), or the painter's drawing while its look is
* pending or its picture is of an older version (`pictureOrPainting`): a
* value, a calculation, a restyle shows at once. Either is drawn at the
* widget's box: a moved widget keeps its picture and takes it along. Hidden
* widgets aren't drawn.
*/
function FieldPictures({ page }: { page: PageContextValue }) {
const form = useCapability(FormHostToken);
const widgets = useSelector(
FormHostToken,
(form) => form.listShownWidgets(page.ref),
shallowArray,
);
// Loaded again when one of the page's widgets is drawn again, and at appearance-scale crossings.
const epoch = useSelector(FormHostToken, (form) => form.getAppearanceEpoch(page.ref));
const scale = useOptionalSelector(
RenderToken,
(render) => render.getAppearanceScale(page.transform.renderScale),
0,
);
// `null` until the page's first pictures arrive.
const [urls, setUrls] = useState | null>(null);
// The pictures shown stay valid until the next ones are shown.
const [shown] = useState(createShownUrls);
useEffect(() => () => shown.release(), [shown]);
useEffect(() => {
if (!scale) return;
return loadAppearanceUrls(
shown,
(signal) => form.renderAppearances(page.ref, scale, signal),
annotationKey,
setUrls,
);
}, [shown, form, page.ref, scale, epoch]);
const looks = widgets.map((widget) =>
pictureOrPainting({
pending: widget.pending,
picture: urls && shownAppearance(urls, annotationKey(widget.ref), widget.appearanceState),
version: widget.pictureVersion,
loaded: urls !== null,
paint: () => form.getWidgetPainting(widget.ref),
}),
);
return (
<>
{widgets.map((widget, index) => {
const look = looks[index];
if (!look) return null;
const key = annotationKey(widget.ref);
// Where the widget is now: a move keeps its picture, which comes along with it.
const frame = rectInPixels(widget.rect, page.transform);
if (look.kind === 'painting') {
const { x, y, width, height } = widget.rect;
return (
);
}
return (
);
})}
>
);
}
const NO_PROGRAMS: readonly MountableFontProgram[] = Object.freeze([]);
// ── hooks ──────────────────────────────────────────────────────────────────
/** The form API for the surrounding document: reading, filling, form data and building. */
export function useForm(): FormCapability {
return useCapability(FormToken);
}
/** Subscribe to one form event while mounted: `useFormEvent((form) => form.onValueChanged, handler)`. */
export function useFormEvent(
select: (form: FormCapability) => EventHook,
handler: (event: T) => void,
): void {
useCapabilityEvent(FormToken, select, handler);
}
/**
* The form's state: every field, whether it's read, what kind of form the
* document has, and the field of the selected widget (the page's State
* table, declared once in `formState`). Takes a selector, and re-renders only
* when what it returns changes.
*/
export const useFormState = stateHook(formState);
/** The form settings (`validation`, `focus`, `fields`), with or without a document. Takes a selector. */
export const useFormSettings = settingsHook(FormToken);
/**
* One field's value, in the shape `setValue()` takes, or `null`: re-renders
* only when that field's value changes. Empty without a document.
*/
export function useFormValue(ref: FormFieldRef): FormFieldValue | null {
const scoped = useDocumentScope();
const key = ref.kind === 'fqn' ? `n:${ref.name}` : `o:${ref.objectNumber}`;
// Keyed by value, so an inline `toFieldRef('total')` never subscribes again.
// eslint-disable-next-line react-hooks/exhaustive-deps
const stable = useMemo(() => ref, [key]);
return useKernelValue(
(kernel) => kernel.tryCapability(FormToken, scoped ?? undefined)?.getValue(stable) ?? null,
);
}