---
title: "Building forms — React"
description: "Turn any PDF into a form: place text boxes, checkboxes, radio buttons, lists and signature fields, and change their settings."
framework: "React"
other_frameworks:
  "Vue": "https://www.embedpdf.com/docs/headless/vue/forms/building.md"
  "Svelte": "https://www.embedpdf.com/docs/headless/svelte/forms/building.md"
  "Angular": "https://www.embedpdf.com/docs/headless/angular/forms/building.md"
source: "https://www.embedpdf.com/docs/headless/react/forms/building"
---

# Building forms

The form plugin can also add fields to a PDF, and change or remove the ones it has, so people can turn
any document into a form. Switch to **design mode**, pick a field tool, and click or drag on the page:

**`field-palette.tsx`**

```tsx
import { useInteraction, useInteractionState } from '@embedpdf/react/interaction';

const FIELD_TOOLS = [
  ['form-text', 'Text'],
  ['form-checkbox', 'Checkbox'],
  ['form-radio', 'Radio button'],
  ['form-combobox', 'Dropdown'],
  ['form-listbox', 'List'],
  ['form-signature', 'Signature'],
] as const;

export function FieldPalette() {
  const interaction = useInteraction();
  const { activeToolId } = useInteractionState();

  return FIELD_TOOLS.map(([id, label]) => (
    <button key={id} aria-pressed={activeToolId === id} onClick={() => interaction.activateTool(id)}>
      {label}
    </button>
  ));
}
```

Building needs the [annotation plugin](https://www.embedpdf.com/docs/headless/react/annotations.md) next to the form plugin: in design mode, fields
are boxes you select, move, resize and style like any annotation.

| Tool             | Places                      | A click makes |
| :--------------- | :-------------------------- | :------------ |
| `form-text`      | A text box                  | 160 × 24      |
| `form-checkbox`  | A checkbox                  | 18 × 18       |
| `form-radio`     | A radio button              | 18 × 18       |
| `form-combobox`  | A dropdown                  | 140 × 24      |
| `form-listbox`   | A list                      | 140 × 72      |
| `form-button`    | A push button               | 100 × 28      |
| `form-signature` | A field someone signs later | 160 × 48      |

A see-through preview of the field follows the pointer, drawn as the field will be, so people see
where it lands before they click. Drag instead of clicking for another size. The tool stays active, so placing ten checkboxes is ten
clicks.

**`designer.tsx`**

```tsx
import { useEffect, useRef } from 'react';
import { Viewer, DocumentGate } from '@embedpdf/react/runtime';
import type { OpenInput } from '@embedpdf/react/runtime';
import { Stage, stagePlugin } from '@embedpdf/react/stage';
import { RenderLayer, renderPlugin } from '@embedpdf/react/render';
import { interactionPlugin, useInteraction, useInteractionState } from '@embedpdf/react/interaction';
import { AnnotationLayer, annotationPlugin } from '@embedpdf/react/annotation';
import { FormLayer, formPlugin, useForm, useFormState } from '@embedpdf/react/form';
import { localEngine } from '@embedpdf/engine';

import './designer.css';

const engine = localEngine();
// Building forms needs the annotation plugin: in design mode, fields are boxes like any annotation.
const plugins = [
  stagePlugin(),
  renderPlugin(),
  interactionPlugin(),
  annotationPlugin(),
  formPlugin(),
];

const registration = async (): Promise<OpenInput> => {
  const response = await fetch('https://www.embedpdf.com/pdfs/registration.pdf');
  return { kind: 'bytes', id: 'registration', bytes: new Uint8Array(await response.arrayBuffer()) };
};

const FIELD_TOOLS = [
  ['form-text', 'Text'],
  ['form-checkbox', 'Checkbox'],
  ['form-radio', 'Radio button'],
  ['form-combobox', 'Dropdown'],
  ['form-listbox', 'List'],
  ['form-signature', 'Signature'],
] as const;

/** Start with the text tool picked: the printed form has boxes, but no fields yet. */
function useStartDesigning() {
  const interaction = useInteraction();
  const started = useRef(false);

  useEffect(() => {
    if (started.current) return;
    started.current = true;
    interaction.activateTool('form-text');
  }, [interaction]);
}

function FieldPalette() {
  useStartDesigning();
  const interaction = useInteraction();
  const form = useForm();
  const { activeToolId } = useInteractionState();
  const { fields } = useFormState();
  // The pointer fills the form in; every other tool here designs it.
  const filling = activeToolId === 'pointer';

  if (!form.canDesign()) return <p className="readout">This document’s form can’t be changed.</p>;

  return (
    <div className="toolbar">
      <div className="segments">
        <button
          type="button"
          className="segment"
          aria-pressed={filling}
          onClick={() => interaction.activateTool('pointer')}
        >
          Fill in
        </button>
        <button
          type="button"
          className="segment"
          aria-pressed={!filling}
          onClick={() => interaction.activateTool('form-edit')}
        >
          Design
        </button>
      </div>
      {FIELD_TOOLS.map(([id, label]) => (
        <button
          key={id}
          type="button"
          className="button"
          aria-pressed={activeToolId === id}
          onClick={() => interaction.activateTool(id)}
        >
          {label}
        </button>
      ))}
      <output className="readout">
        {fields.length} fields: click the page to place another
      </output>
    </div>
  );
}

export default function App() {
  return (
    <Viewer engine={engine} plugins={plugins} initialDocuments={[{ source: registration }]}>
      <DocumentGate fallback={<p className="loading">Loading…</p>}>
        <FieldPalette />
        <Stage className="stage">
          {() => (
            <>
              <RenderLayer />
              <AnnotationLayer />
              <FormLayer />
            </>
          )}
        </Stage>
      </DocumentGate>
    </Viewer>
  );
}
```

**`designer.css`**

```css
/* Colors */
:root {
  --ink: #1a2748;
  --muted: #5a6b92;
  --line: #e6eaf2;
  --line-strong: #dce8fc;
  --surface: #ffffff;
  --tint: #f3f7fe;
  --canvas: #f7f9fc;
  --accent: #054fb3;
  --focus: #7db6ff;
  --shadow: rgb(7 32 76 / 0.04);
}

/* The controls, above the pages */
.toolbar {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
  margin-bottom: 14px;
}

.button {
  font: inherit;
  font-size: 13px;
  font-weight: 550;
  line-height: 1;
  color: var(--ink);
  background: var(--surface);
  border: 1px solid var(--line);
  border-radius: 9px;
  padding: 8px 13px;
  cursor: pointer;
  white-space: nowrap;
  box-shadow: 0 1px 2px var(--shadow);
  transition:
    background-color 0.15s ease,
    border-color 0.15s ease;
}

.button:hover {
  background: var(--tint);
  border-color: var(--line-strong);
}

.button:active {
  transform: translateY(1px);
}

.button:focus-visible {
  outline: 2px solid var(--focus);
  outline-offset: 2px;
}

.button:disabled {
  opacity: 0.45;
  cursor: not-allowed;
  transform: none;
}

.button[aria-pressed='true'] {
  color: var(--accent);
  background: var(--tint);
  border-color: var(--line-strong);
}

/* Fill in or design: one of the two */
.segments {
  display: inline-flex;
  gap: 2px;
  padding: 3px;
  background: var(--tint);
  border: 1px solid var(--line);
  border-radius: 10px;
}

.segment {
  font: inherit;
  font-size: 13px;
  font-weight: 550;
  line-height: 1;
  color: var(--muted);
  background: transparent;
  border: 0;
  border-radius: 7px;
  padding: 7px 12px;
  cursor: pointer;
}

.segment:hover {
  color: var(--ink);
}

.segment[aria-pressed='true'] {
  color: var(--accent);
  background: var(--surface);
  box-shadow: 0 1px 3px rgb(7 32 76 / 0.12);
}

.segment:focus-visible {
  outline: 2px solid var(--focus);
  outline-offset: 1px;
}

.readout {
  font-size: 13px;
  font-weight: 600;
  color: var(--ink);
}

/* The pages */
.stage {
  height: 440px;
  border: 1px solid var(--line);
  border-radius: 14px;
  background: var(--canvas);
  box-shadow:
    0 1px 2px var(--shadow),
    0 18px 40px -28px rgb(7 32 76 / 0.28);
}

.loading {
  margin: 0;
  padding: 24px 0;
  text-align: center;
  font-size: 13px;
  color: var(--muted);
}
```

> **Try it:** the form was printed without fields. Click a printed box to put a text field on it,
> pick another kind for the circles, then press **Fill in** to type in your form.

### On a turned page

On a page that is shown turned, such as a scan saved sideways, a field is placed the way its
author sees the page: a click makes the tool's size as the page shows it, and the field is turned
so that what's typed into it reads upright there. The turn is saved with the field as a quarter
turn, the one turn a PDF form field can hold, so every PDF app shows it and fills it in the same
way. `upright: false` on a tool places its fields along the page instead; see
[Rotated pages](https://www.embedpdf.com/docs/headless/react/annotations/tools.md#rotated-pages).

Turn the page, not the view, before you place fields: a page turned with
[`pageEdit.rotateBy()`](https://www.embedpdf.com/docs/headless/react/documents/pages.md#rotate-pages) is saved with the document, and a view rotation is this
session's only. Turn pages before the first signature too, since turning a page afterwards is a
change to a signed document.

## Design mode

The form's own tools are design mode: `form-edit` and the field tools. Fields stop being fillable
and become boxes you can select, move and resize. The `pointer` tool makes them fillable again:

```ts
interaction.activateTool('form-edit'); // design the form
interaction.activateTool('pointer'); // fill it in
```

`form.isDesigning()` says whether the form is being designed now, and the form's state has it as
`designing`. Read it for a Design switch of your own, rather than comparing
tool ids: it's true under every design tool, one you add too, and only while the user may design
and the annotation plugin is there.

In design mode the form lends its boxes to the annotation plugin, which selects, moves, resizes,
restyles, reorders and deletes them with its own tools, next to the annotations. Every edit of a box
is still the form's: its place or look is `updateWidget()`, and deleting every box of a field
deletes the field. A drag of two fields and a stamp is one change: one request, and one step to
undo. Like every change, it shows at once and the engine's answer follows.

A selected checkbox, radio button or one-line field is a small box: it shows four corner handles
just outside it, so its mark stays visible, and dragging its inside moves it
([Change the handles](https://www.embedpdf.com/docs/headless/react/annotations/selecting.md#change-the-handles)).

A field just placed is selected at once, before the engine answers, and the tool goes back to
`form-edit` rather than the default pointer, so design mode goes on. Without `canDesign()` nothing is
lent, and the fields show as they do under any other tool.

Design mode is the tools that carry the `form-design` tag: `form-edit` and every field tool do, and
so can a tool of your own. Under any other tool that doesn't fill forms in, such as a stamp, a pen
or zoom, nobody designs the form, whatever their permissions: fields show as they do while filling,
tints and placeholders included, but take no input and no pointer, so the tool works over them. A
stamp lands on a field, and a pen draws across one.

## Form tools and signing tools

The field tools are two families, one for each job. Both are there from the start: show the ones
your app needs.

- **Form tools, `form-…`, make a form.** The field is part of the document, so it has a look of
  its own, which every PDF app shows and which prints: a box with a gray border and a background.
  It isn't required. They are the seven tools above and [`form-image`](#image-fields).
- **Signing tools, `signer-…`, prepare a document for signing.** The document has its own lines
  and boxes, so the field has no border and no background of its own: the PDF draws nothing for
  an empty one, and nothing prints. The viewer shows it by
  [its own paint](https://www.embedpdf.com/docs/headless/react/forms.md#a-fields-look-and-its-tint), a tint or an edge and what it's for,
  while you design and to the person who fills it in. It's required, so
  [`validate()`](https://www.embedpdf.com/docs/headless/react/forms.md#check-required-fields) lists it for its signer until it's filled in.

| Signing tool                | Places                               | A click makes |
| :-------------------------- | :----------------------------------- | :------------ |
| `signer-signature`          | A field the person signs             | 160 × 48      |
| `signer-initials`           | An image field for their initials    | 72 × 36       |
| `signer-date-signed`        | A read-only date field, `yyyy-mm-dd` | 100 × 24      |
| `signer-name`               | A text box for the person's name     | 160 × 24      |
| `signer-email`              | A text box for their email address   | 160 × 24      |
| `signer-organization`       | A text box for their organization    | 160 × 24      |
| `signer-organization-title` | A text box for their job title       | 160 × 24      |

Each is `signer-` and the [purpose](#what-a-field-is-for) its field has, so an empty one says what
it's for. One of them isn't required: the day of signing is written for the signer, not typed, so
`signer-date-signed` places a read-only field and `validate()` never lists it.

The look and "required" are the whole difference. `signer-signature` places the field
`form-signature` places, `signer-initials` an [image field](#image-fields) as `form-image` does,
and the others a text box as `form-text` does. Each family follows its one rule, so a signing
tool for a value of your own is [a tool you make](#make-your-own-field-tool).

## Place fields for a signer

When a form goes to several people, each field belongs to one of them: it's in their
[group](https://www.embedpdf.com/docs/engine/forms/groups.md). Tell the document
[who its groups are](https://www.embedpdf.com/docs/headless/react/forms.md#fields-for-several-people), then say who the next fields are for:

```ts
form.setDesignGroup('buyer'); // fields placed with a tool are Dana's
```

**`sender-toolbar.tsx`**

```tsx
import { useForm, useFormState } from '@embedpdf/react/form';
import { useInteraction, useInteractionState } from '@embedpdf/react/interaction';

const FIELD_TOOLS = [
  ['form-text', 'Text'],
  ['form-checkbox', 'Checkbox'],
  ['signer-signature', 'Signature'],
] as const;

export function SenderToolbar() {
  const form = useForm();
  const { groups, designGroup } = useFormState();
  const interaction = useInteraction();
  const { activeToolId } = useInteractionState();

  return (
    <>
      {groups.map((group) => (
        <button
          key={group.id}
          aria-pressed={designGroup === group.id}
          disabled={!form.canSetGroup(group.id)}
          onClick={() => form.setDesignGroup(group.id)}
        >
          <i style={{ background: group.color }} /> {group.label ?? group.id}
        </button>
      ))}

      {FIELD_TOOLS.map(([id, label]) => (
        <button
          key={id}
          aria-pressed={activeToolId === id}
          onClick={() => interaction.activateTool(id)}
        >
          {label}
        </button>
      ))}
    </>
  );
}
```

While you design, every field shows: in its group's color, in `fields.tintColor` when it's in
no group, else with an edge in `fields.border`, so a field with no border or background of its own
shows too. Before you click, a field tool shows the field it places where it will land,
see-through: its look, the color of the group you place for, and what it's for. A field placed with a tool goes into
the group you set, which the form's state has as `designGroup`. With `null`, where it starts, it names
no group, and a placed field is in none.

Putting a field in a group other than your own takes the `fields:set-group` permission for that
group, and `form.canSetGroup(groupId)` says whether the user has it. Turn off the signers a user
can't place for: `setDesignGroup()` refuses a group they may not put a field in, as `create()`,
`update()` and `moveToGroup()` do. A field in no group needs no such permission: whoever may
design the form may leave a field in none, or take it out of its group.

**`signers.tsx`**

```tsx
import { useEffect, useLayoutEffect, useRef, useState } from 'react';
import { Viewer, DocumentGate, useDocument, useDocuments } from '@embedpdf/react/runtime';
import type { OpenInput } from '@embedpdf/react/runtime';
import { Stage, stagePlugin } from '@embedpdf/react/stage';
import { RenderLayer, renderPlugin } from '@embedpdf/react/render';
import {
  interactionPlugin,
  useInteraction,
  useInteractionState,
} from '@embedpdf/react/interaction';
import { AnnotationLayer, annotationPlugin } from '@embedpdf/react/annotation';
import { Anchored } from '@embedpdf/react/anchored';
import {
  FormLayer,
  formPlugin,
  useForm,
  useFormState,
  useFormWidgetAnchor,
} from '@embedpdf/react/form';
import { signaturePlugin, useSignature, useSignatureState } from '@embedpdf/react/signature';
import { localEngine } from '@embedpdf/engine';

import './signers.css';

const engine = localEngine();
const plugins = [
  stagePlugin(),
  renderPlugin(),
  interactionPlugin(),
  annotationPlugin(),
  formPlugin(),
  // An empty signature field becomes a button. With no key, a mark is drawn into the field.
  signaturePlugin(),
];

// Who the document's groups are: your app's own list. The PDF holds only each field's group id.
const signers = [
  { id: 'borrower', label: 'Dana Smith', color: '#2563eb' },
  { id: 'approver', label: 'Ada Lovelace' }, // a color is picked for it
];

const loan = async (): Promise<OpenInput> => {
  const response = await fetch('https://www.embedpdf.com/pdfs/loan.pdf');
  return { kind: 'bytes', id: 'loan', bytes: new Uint8Array(await response.arrayBuffer()) };
};

// What each person may do, as permissions: the sender places fields for both signers and for
// anyone, and each signer fills in and signs their own, and fills in anyone's.
const see = ['doc.open', 'doc.render', 'doc.download', 'doc.forms.read'];
const people = {
  sender: {
    name: 'The sender',
    // Every group: a field anyone fills in is every group's.
    scope: [...see, 'doc.forms.modify', 'fields:set-group:all'],
  },
  borrower: {
    name: 'Dana Smith',
    scope: [...see, 'fields:fill:group=borrower', 'fields:sign:group=borrower'],
  },
  approver: {
    name: 'Ada Lovelace',
    scope: [...see, 'fields:fill:group=approver', 'fields:sign:group=approver'],
  },
};
type Person = keyof typeof people;

const FIELD_TOOLS = [
  ['form-text', 'Text'],
  ['form-checkbox', 'Checkbox'],
  ['signer-signature', 'Signature'],
  ['signer-initials', 'Initials'],
] as const;

// The color a field anyone fills in shows in: the form's `fields.anyoneTintColor`.
const ANYONE = 'var(--epdf-form-field-anyone-tint-color, #0891b2)';

// A document keeps the permissions it opened with, so the next person opens the saved form again.
function HandOver({ person }: { person: Person }) {
  const documents = useDocuments();
  const { id } = useDocument();
  const opened = useRef(person);

  useEffect(() => {
    if (person === opened.current || !id) return;
    opened.current = person;
    void (async () => {
      const bytes = await documents.download();
      await documents.close(id);
      await documents.open({ kind: 'bytes', bytes }, { name: 'equipment-loan.pdf' });
    })();
  }, [person, id, documents]);
  return null;
}

/** The sender picks who the next field is for, then a tool, and clicks the page. */
function SenderToolbar() {
  const form = useForm();
  const interaction = useInteraction();
  const { groups, designGroup, designAssignment } = useFormState();
  const forAnyone = designAssignment.kind === 'anyone';
  const { activeToolId } = useInteractionState();

  // One signer signs a signature field, so it's never for anyone: the tool places nothing then.
  const placeForAnyone = () => {
    form.setDesignAssignment({ kind: 'anyone' });
    if (activeToolId === 'signer-signature') interaction.activateTool('form-text');
  };

  // Start by placing text fields for the first signer.
  useEffect(() => {
    form.setDesignGroup('borrower');
    interaction.activateTool('form-text');
  }, [form, interaction]);

  return (
    <div className="toolbar">
      <span className="label">Next field is for</span>
      {groups.map((group) => (
        <button
          key={group.id}
          type="button"
          className="button"
          aria-pressed={designGroup === group.id}
          disabled={!form.canSetGroup(group.id)}
          onClick={() => form.setDesignGroup(group.id)}
        >
          <i className="swatch" style={{ background: group.color }} />
          {group.label ?? group.id}
        </button>
      ))}
      <button
        type="button"
        className="button"
        aria-pressed={forAnyone}
        disabled={!form.canAssign({ kind: 'anyone' })}
        onClick={placeForAnyone}
      >
        <i className="swatch" style={{ background: ANYONE }} />
        Anyone
      </button>
      <span className="divider" />
      {FIELD_TOOLS.map(([id, label]) => (
        <button
          key={id}
          type="button"
          className="button"
          aria-pressed={activeToolId === id}
          disabled={forAnyone && id === 'signer-signature'}
          onClick={() => interaction.activateTool(id)}
        >
          {label}
        </button>
      ))}
    </div>
  );
}

/** A signer sees whose field is whose: theirs stand out, and the others take no input. */
function SignerLegend({ person }: { person: Person }) {
  const { groups, fields } = useFormState();
  return (
    <div className="toolbar">
      {groups.map((group) => (
        <span key={group.id} className="legend">
          <i className="swatch" style={{ background: group.color }} />
          {group.label ?? group.id}: {fields.filter((field) => field.groupId === group.id).length}
        </span>
      ))}
      <span className="legend">
        <i className="swatch" style={{ background: ANYONE }} />
        Anyone: {fields.filter((field) => field.assignment.kind === 'anyone').length}
      </span>
      <output className="readout">
        {people[person].name} fills in the fields in their color, and anyone’s
      </output>
    </div>
  );
}

const INK = '#1d2b53';
type Point = { x: number; y: number };

/**
 * A signer pressed their signature field, with a click or with Tab and Space: the field is the
 * signature plugin's target, and this card opens next to it. What they draw goes into the field.
 */
function SignCard() {
  const form = useForm();
  const signature = useSignature();
  const { target } = useSignatureState();
  const anchor = useFormWidgetAnchor(target ? (form.getWidgets(target)[0]?.ref ?? null) : null);
  const card = useRef<HTMLDivElement>(null);
  const pad = useRef<HTMLCanvasElement>(null);
  const last = useRef<Point | null>(null);
  const [drawn, setDrawn] = useState(false);

  // Each field starts with an empty pad, and the card takes the cursor, so Escape closes it.
  useEffect(() => {
    last.current = null;
    setDrawn(false);
    pad.current?.getContext('2d')?.clearRect(0, 0, pad.current.width, pad.current.height);
    if (target) card.current?.focus();
  }, [target]);

  if (!target) return null;

  const pointOf = (event: React.PointerEvent<HTMLCanvasElement>): Point => {
    const box = event.currentTarget.getBoundingClientRect();
    return { x: event.clientX - box.left, y: event.clientY - box.top };
  };

  const start = (event: React.PointerEvent<HTMLCanvasElement>) => {
    event.currentTarget.setPointerCapture(event.pointerId);
    last.current = pointOf(event);
  };

  const draw = (event: React.PointerEvent<HTMLCanvasElement>) => {
    const from = last.current;
    const ink = event.currentTarget.getContext('2d');
    if (!from || !ink || !event.currentTarget.hasPointerCapture(event.pointerId)) return;
    const to = pointOf(event);
    last.current = to;
    ink.strokeStyle = INK;
    ink.lineWidth = 2;
    ink.lineCap = 'round';
    ink.beginPath();
    ink.moveTo(from.x, from.y);
    ink.lineTo(to.x, to.y);
    ink.stroke();
    setDrawn(true);
  };

  // Close without signing, and put the cursor back on the field.
  const close = () => {
    signature.setTarget(null);
    form.focus(target);
  };

  // The drawing goes into the field as a picture.
  const sign = () =>
    pad.current?.toBlob(async (png) => {
      if (!png) return;
      await signature.placeMark({ source: png }, { field: target });
      form.focus(target);
    });

  return (
    <Anchored anchor={anchor} placement="bottom-start" gap={8}>
      <div
        ref={card}
        className="sign-card"
        role="dialog"
        aria-label="Draw your signature"
        tabIndex={-1}
        onKeyDown={(event) => event.key === 'Escape' && close()}
      >
        {/* Anchored UI keeps a press from reaching the page under it, before React hears it:
            the pad listens while the press is on its way down. */}
        <canvas
          ref={pad}
          className="sign-pad"
          width={240}
          height={100}
          onPointerDownCapture={start}
          onPointerMove={draw}
        />
        <div className="sign-actions">
          <button type="button" className="button" onClick={close}>
            Cancel
          </button>
          <button type="button" className="button" disabled={!drawn} onClick={sign}>
            Sign
          </button>
        </div>
      </div>
    </Anchored>
  );
}

function Toolbar({ person }: { person: Person }) {
  const form = useForm();

  // Tell the open document who its groups are, before the first paint.
  useLayoutEffect(() => {
    form.setGroups(signers);
  }, [form]);

  // The open document says what its user may do: it is the sender's while they may design it.
  return form.canDesign() ? <SenderToolbar /> : <SignerLegend person={person} />;
}

export default function App() {
  const [person, setPerson] = useState<Person>('sender');
  return (
    <Viewer
      engine={engine}
      plugins={plugins}
      scope={people[person].scope}
      initialDocuments={[{ source: loan, name: 'equipment-loan.pdf' }]}
    >
      <div className="toolbar">
        <span className="label">Open the form as</span>
        <div className="segments">
          {(Object.keys(people) as Person[]).map((each) => (
            <button
              key={each}
              type="button"
              className="segment"
              aria-pressed={person === each}
              onClick={() => setPerson(each)}
            >
              {people[each].name}
            </button>
          ))}
        </div>
      </div>
      <HandOver person={person} />
      <DocumentGate fallback={<p className="loading">Opening…</p>}>
        <Toolbar person={person} />
        <Stage className="stage" overlay={<SignCard />}>
          {() => (
            <>
              <RenderLayer />
              <AnnotationLayer />
              <FormLayer />
            </>
          )}
        </Stage>
      </DocumentGate>
    </Viewer>
  );
}
```

**`signers.css`**

```css
/* Colors */
:root {
  --ink: #1a2748;
  --muted: #5a6b92;
  --line: #e6eaf2;
  --line-strong: #dce8fc;
  --surface: #ffffff;
  --tint: #f3f7fe;
  --canvas: #f7f9fc;
  --accent: #054fb3;
  --focus: #7db6ff;
  --shadow: rgb(7 32 76 / 0.04);
}

/* The controls, above the pages */
.toolbar {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
  margin-bottom: 10px;
}

.button {
  font: inherit;
  font-size: 13px;
  font-weight: 550;
  line-height: 1;
  color: var(--ink);
  background: var(--surface);
  border: 1px solid var(--line);
  border-radius: 9px;
  padding: 8px 13px;
  cursor: pointer;
  white-space: nowrap;
  box-shadow: 0 1px 2px var(--shadow);
  transition:
    background-color 0.15s ease,
    border-color 0.15s ease;
}

.button:hover {
  background: var(--tint);
  border-color: var(--line-strong);
}

.button:active {
  transform: translateY(1px);
}

.button:focus-visible {
  outline: 2px solid var(--focus);
  outline-offset: 2px;
}

.button:disabled {
  opacity: 0.45;
  cursor: not-allowed;
  transform: none;
}

.button[aria-pressed='true'] {
  color: var(--accent);
  background: var(--tint);
  border-color: var(--line-strong);
}

/* Fill in or design: one of the two */
.segments {
  display: inline-flex;
  gap: 2px;
  padding: 3px;
  background: var(--tint);
  border: 1px solid var(--line);
  border-radius: 10px;
}

.segment {
  font: inherit;
  font-size: 13px;
  font-weight: 550;
  line-height: 1;
  color: var(--muted);
  background: transparent;
  border: 0;
  border-radius: 7px;
  padding: 7px 12px;
  cursor: pointer;
}

.segment:hover {
  color: var(--ink);
}

.segment[aria-pressed='true'] {
  color: var(--accent);
  background: var(--surface);
  box-shadow: 0 1px 3px rgb(7 32 76 / 0.12);
}

.segment:focus-visible {
  outline: 2px solid var(--focus);
  outline-offset: 1px;
}

/* Who a field is for: a signer's color, beside their name */
.label {
  font-size: 13px;
  font-weight: 600;
  color: var(--muted);
}

.swatch {
  display: inline-block;
  width: 10px;
  height: 10px;
  margin-right: 6px;
  border-radius: 3px;
}

.legend {
  display: inline-flex;
  align-items: center;
  font-size: 13px;
  font-weight: 550;
  color: var(--ink);
}

.divider {
  width: 1px;
  height: 20px;
  background: var(--line);
}

.readout {
  font-size: 13px;
  font-weight: 600;
  color: var(--ink);
}

/* The card a signer draws their signature in */
.sign-card {
  display: grid;
  gap: 8px;
  padding: 10px;
  background: var(--surface);
  border: 1px solid var(--line);
  border-radius: 12px;
  box-shadow: 0 12px 32px -12px rgb(7 32 76 / 0.35);
}

.sign-card:focus {
  outline: none;
}

.sign-pad {
  display: block;
  width: 240px;
  height: 100px;
  background: var(--canvas);
  border: 1px dashed var(--line-strong);
  border-radius: 8px;
  cursor: crosshair;
  touch-action: none;
}

.sign-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

/* The pages */
.stage {
  height: 440px;
  border: 1px solid var(--line);
  border-radius: 14px;
  background: var(--canvas);
  box-shadow:
    0 1px 2px var(--shadow),
    0 18px 40px -28px rgb(7 32 76 / 0.28);
}

.loading {
  margin: 0;
  padding: 24px 0;
  text-align: center;
  font-size: 13px;
  color: var(--muted);
}
```

> **Try it:** as the sender, click the borrower's Name box to place a text field for Dana, then
> pick Signature and click her Signature box. Pick **Initials** and click beside it: an image
> field for her initials. Both are [signing tools](#form-tools-and-signing-tools): neither adds a
> border or a background of its own to the page. Pick Ada and do the same under "Approved by":
> each field shows in its signer's color. Pick **Anyone**: Signature turns off. Place a text field in the "Return by"
> box; it shows in cyan. Then open the form as Dana. Her fields and the Anyone field stand out,
> both take her typing, and Ada's show as the PDF has them. Click Dana's signature field, or Tab
> to it and press Space, draw a signature in the card and press Sign. Click her initials box and
> do the same: the drawing goes in as its picture. Open it as Ada: the Anyone field is hers to
> fill in too.

The signers can sign because the example also has the [signature plugin](https://www.embedpdf.com/docs/headless/react/forms/signatures.md): an empty
signature field is a button, and pressing it makes the field the
[target](https://www.embedpdf.com/docs/headless/react/forms/signatures.md#sign-here-in-a-form). The example's card opens next to the target and places
the drawing in the field as a PNG, with `signature.placeMark({ source: png }, { field })`. With
no signing key, the mark is drawn into the field and nothing is sealed;
[The key](https://www.embedpdf.com/docs/headless/react/forms/signatures.md#the-key) has what a real signature takes. Escape or Cancel closes the card
and puts the cursor back on the field.

A document keeps the permissions it opened with, so the example saves the form and opens it again
for each person, with theirs.

### Place fields anyone fills in

Some fields are no one signer's: a date either party may settle, a note anyone may add. Such a
field is [for anyone](https://www.embedpdf.com/docs/engine/forms/groups.md#fields-anyone-fills-in): it's in no group, and
every signer fills it in. Who a field is for is its `assignment`, one of three:
`{ kind: 'group', groupId }`, `{ kind: 'anyone' }`, or `{ kind: 'unassigned' }` for nobody, the
sender's. Place the next fields for anyone:

```ts
form.setDesignAssignment({ kind: 'anyone' }); // fields placed with a tool are anyone's
form.setDesignGroup('buyer'); // back to Dana's
```

- **One assignment at a time.** `setDesignGroup(groupId)` is short for
  `setDesignAssignment({ kind: 'group', groupId })`, and `setDesignGroup(null)` for
  `{ kind: 'unassigned' }`. The form's state has both, as
  `designAssignment` and `designGroup`, the group's id, or `null` while
  the fields are for anyone or for nobody.
  `onDesignGroupChanged` carries `{ groupId, assignment }`.
- **The signature tools and the Date signed tool place nothing meanwhile.** A signature and the
  day it was made are one signer's, so neither is ever for anyone: `form-signature`,
  `signer-signature` and `signer-date-signed` show no field before you click, and a click goes
  on to the other tools. Turn their buttons off while the design assignment is anyone. For nobody they place as usual, so a form without groups has its
  signature and its date. A date anyone may settle is a plain date field.
- **It shows in a color of its own,** `fields.anyoneTintColor`, a cyan at first: in design
  mode, before you click, and on every signer's page. Screen readers read "Anyone" after its
  name, in the viewer's language.
- **It takes the right to put fields in every group,** `fields:set-group:all`, since every
  group's signers fill it in. `form.canAssign({ kind: 'anyone' })` says whether the user has it,
  and `setDesignAssignment()` refuses without it, as `assign()`, `create()` and `update()` do. A
  group takes what `canSetGroup()` says, and nobody takes no such permission.

Signing [locks](https://www.embedpdf.com/docs/engine/forms/groups.md#signing) a field anyone fills in once it holds a value;
an empty one stays open for the next signer. `prefill()` leaves it alone: a name or a date is one
signer's.

### Give fields to a signer

A form made somewhere else, in Acrobat for example, arrives with its fields in no group. Move one
like any setting, and `null` takes it out of its group again:

```ts
await form.update(field.ref, { groupId: 'seller' });
await form.update(field.ref, { groupId: null }); // nobody's
await form.update(field.ref, { assignment: { kind: 'anyone' } }); // anyone's
```

A field has one assignment: `assignment` replaces whatever it had, and so does `groupId`, which
reads `null` for a field anyone fills in. Name one of the two in a change, not both.

Or move every selected field in one call, which is one step to undo:

**`move-selected.tsx`**

```tsx
import { useForm, useFormState } from '@embedpdf/react/form';

export function GiveSelectedTo() {
  const form = useForm();
  const { groups, selectedFields } = useFormState();

  if (selectedFields.length === 0) return null;
  const refs = selectedFields.map((field) => field.ref);

  return (
    <>
      Give to
      {groups.map((group) => (
        <button
          key={group.id}
          disabled={!form.canSetGroup(group.id)}
          onClick={() => void form.moveToGroup(refs, group.id)}
        >
          <i style={{ background: group.color }} /> {group.label ?? group.id}
        </button>
      ))}
    </>
  );
}
```

`selectedFields` in the form's state has every field with a selected box, and `form.listSelectedFields()`
reads it once. `assign(fields, assignment)` gives them an assignment, as one step to undo: it
leaves out the fields that have it already, shows the rest in their new color at once, and
resolves `{ fields }` as they are now. It refuses `{ kind: 'anyone' }` with `invalid-input` when
one of the fields is a signature field or a `date-signed` field, and moves nothing then; so do
`update()` and `create()`, and `update()` refuses the purpose `date-signed` on a field anyone
fills in. What is no assignment, such as a
misspelt `kind`, is refused the same way, by `update()`, `create()` and `setDesignAssignment()`
too, and `canAssign()` answers `false` for it. `moveToGroup(fields, groupId)` is
short for `assign()` with that group, or with nobody for `null`.

## What a field is for

A field's `purpose` says what its value means, in a word the viewer and your app both read. It's
saved in the PDF with the field, and other PDF apps ignore it:

```ts
await form.update(field.ref, { purpose: 'email' });
await form.update(field.ref, { purpose: null }); // none
```

Any word is a purpose. These are the ones the viewer knows:

| Purpose              | The value is                  |
| :------------------- | :---------------------------- |
| `name`               | The person's full name        |
| `email`              | Their email address           |
| `organization`       | Their company or organization |
| `organization-title` | Their job title               |
| `date-signed`        | The day they signed           |
| `signature`          | Their signature               |
| `initials`           | Their initials                |

A purpose doesn't change what the field is: a name is still a text box. It does three things:

- **An empty field shows what it's for.** The form layer writes the purpose's name in it, such as
  "Email", until it has a value. The text is the layer's paint and never part of the PDF. Its
  color is [`fields.placeholder`](https://www.embedpdf.com/docs/headless/react/forms.md#settings). A field with a
  [placeholder](#a-fields-placeholder) of its own shows that text in its place.
- **Your app can fill it in.** [`prefill()`](https://www.embedpdf.com/docs/headless/react/forms.md#values-the-app-already-knows) writes the
  user's name, email address, organization and job title into their fields, and today's date.
- **The browser can help.** For the first four, the layer's text box says so with `autocomplete`,
  so the browser offers the person's saved name or email address. They are the web's own names
  for these values.

A word of your own is saved and read back like these. The viewer has no name and no value for
it, so its field shows no label and `prefill()` leaves it alone: it is for your app to read. Give
such a field a [placeholder](#a-fields-placeholder) to say what goes in it.

`form.listPurposes()` gives every purpose the viewer knows, each as `{ id, label }` with the
label in the viewer's language.

Each [signing tool](#form-tools-and-signing-tools) places a field with one of these purposes, in
the [group you place for](#place-fields-for-a-signer): `signer-name` a text box for the person's
name, `signer-email` one for their email address, and so on. The field `signer-date-signed`
places is read-only because the day of signing is written for the signer, not typed: `prefill()`
writes today's date into it, and the signer sees it as text, with the tooltip "Filled in when you
sign".

### Make your own field tool

A tool of your own `extends` a field tool and starts from it:

```ts
formPlugin({
  tools: [
    {
      id: 'form-company-number',
      extends: 'form-text',
      field: { purpose: 'company-number', required: true },
    },
    {
      id: 'form-date',
      extends: 'form-text',
      field: {
        format: { kind: 'date', pattern: 'dd/mm/yyyy' },
      },
      clickCreate: { width: 100, height: 24 },
    },
  ],
});

interaction.activateTool('form-date');
```

- **`extends`** names a field tool listed before it: a built-in one, or one of yours.
- **`field`** is what every field the tool places starts with: any setting `create()` takes
  except its kind, its name, its boxes and its group.
- **`defaults`** is how its box looks, as for
  [an annotation tool](https://www.embedpdf.com/docs/headless/react/annotations/tools.md#make-your-own-tool). `color: null` is no border and
  `interiorColor: null` no background, as the signing tools place their fields.
- **`clickCreate`** is the size a click makes, in points.

An entry with the id of an existing tool and no `extends` changes that tool. With `extends`,
that id is refused when the document opens: `extends` adds a tool, and never replaces one. This
gives the built-in date field another pattern:

```ts
formPlugin({
  tools: [
    {
      id: 'signer-date-signed',
      field: {
        format: { kind: 'date', pattern: 'dd/mm/yyyy' },
      },
    },
  ],
});
```

The list is read when a document opens.

## A field's placeholder

A field's `placeholder` is text of your own that an empty field shows, such as an example of
what to type. It's saved in the PDF with the field, beside its purpose, and other PDF apps
ignore it. It is never the field's value:

```ts
await form.update(field.ref, { placeholder: 'NL12 ABCD 0123 4567 89' });
await form.update(field.ref, { placeholder: null }); // none

await form.create({
  kind: 'text',
  name: 'iban',
  placeholder: 'NL12 ABCD 0123 4567 89',
  widgets: [{ page: page.ref, rect: { x: 72, y: 700, width: 220, height: 24 } }],
});
```

What an empty field shows is one rule: its own placeholder, else its
[purpose's](#what-a-field-is-for) label, else nothing.

- **It's shown as you wrote it.** A purpose's label is in the viewer's language. A placeholder
  is your text, in the language you wrote it in, and is never translated.
- **A text box, a dropdown, a signature field and an image field show it.** Every kind of field
  keeps one, but a checkbox, a radio button, a list and a button have no room for it.
- **It shows when a label would.** While the field is empty, while a signature box has no mark
  drawn in it, and, while people fill in the form, only in a field that is the user's to fill
  in. In design mode it shows on every such field.
- **What it takes.** 1 to 256 characters, with no space at the start or the end. `update()` and
  `create()` reject anything else with `invalid-input`, an empty string too, and never trim it:
  `null` takes a placeholder away.
- **Setting it is form design.** It needs `doc.forms.modify`, like any setting. Filling in a
  field never changes it.

A [tool of your own](#make-your-own-field-tool) gives one to every field it places:

```ts
formPlugin({
  tools: [
    {
      id: 'form-iban',
      extends: 'form-text',
      field: { placeholder: 'NL12 ABCD 0123 4567 89' },
    },
  ],
});
```

Before you click, the tool shows the field it places with that text in it, see-through. The
settings panel under [Change a field's settings](#change-a-fields-settings) has an input for a
placeholder: type one, and the selected field shows it.

## Image fields

An image field holds a picture the person puts in: their initials, a second signature, a photo.
It's what Acrobat's Image field tool makes: a push button whose press asks for a picture. The
engine reads that as a fact of the button, `takesImage`, and that fact alone makes a push button
an image field. Two tools place one:

| Tool              | Places                                                | A click makes |
| :---------------- | :---------------------------------------------------- | :------------ |
| `signer-initials` | An image field for the person's initials (`initials`) | 72 × 36       |
| `form-image`      | An image field                                        | 120 × 90      |

`signer-initials` is a [signing tool](#form-tools-and-signing-tools): its field has no border and
no background of its own, and is required. `form-image` places a box, as every form tool does.
`form-signature` and `signer-signature` place their field with the purpose `signature`, so an
empty one says "Signature". Before you click, each tool shows the field it places, see-through:
an empty box in the color of the [group you place for](#place-fields-for-a-signer), with
"Initials" or "Signature" in it. A [tool of your own](#make-your-own-field-tool) that `extends`
one of the two places an image field as well: `takesImage: true` is part of what its `field`
starts with.

From code, a push button with `takesImage: true` is an image field. Give its box
`layout: 'image'`, so it shows the picture alone:

```ts
await form.create({
  kind: 'pushbutton',
  name: 'initials_1',
  purpose: 'initials',
  takesImage: true,
  widgets: [{ page: page.ref, rect: { x: 400, y: 700, width: 72, height: 36 }, layout: 'image' }],
});
```

- **It's an image field in Acrobat too.** `takesImage: true` writes the press Acrobat's own
  image fields have, on every box of the button, so a click on the field in Acrobat asks for a
  picture. `form.update(ref, { takesImage })` switches a button either way. See
  [An image field](https://www.embedpdf.com/docs/engine/forms/authoring.md#an-image-field).
- **A button that only shows a picture is a button.** A logo or a photo kept in a button whose
  box shows its picture alone (`layout: 'image'`) has `takesImage: false`. Nobody fills it in:
  it has no tint and no placeholder, [`validate()`](https://www.embedpdf.com/docs/headless/react/forms.md#check-required-fields) never asks
  for it, and `setButtonImage()` refuses it. A print or submit button that shows a picture is a
  button too, and keeps its action.
- **Never by its name, its layout or its picture.** A field named `_af_image` is a button until
  its press says otherwise, and an image field without a picture yet is still an image field.
- **Every box, or none.** A button is an image field only when every one of its boxes has that
  press, and then every box is an image box. A box whose press you change with
  `updateWidget()`, or that you delete, changes what its button is at once.
- **One more place shows the same picture.** [`addWidget()`](#one-more-button-for-a-group) gives
  an image field's new place the press, with the last box's look, its `layout` among it.

How people fill one in is on [Filling forms](https://www.embedpdf.com/docs/headless/react/forms.md#image-fields).

## Change a field's settings

`useFormState().selectedField` is the field of the selected box, for a settings panel:

**`field-settings.tsx`**

```tsx
import { useForm, useFormState } from '@embedpdf/react/form';

export function FieldSettings() {
  const form = useForm();
  const { selectedField: field } = useFormState();
  if (!field) return null;

  return (
    <>
      <input defaultValue={field.name} onBlur={(e) => form.update(field.ref, { name: e.target.value })} />
      <label>
        <input
          type="checkbox"
          checked={field.required}
          onChange={(e) => form.update(field.ref, { required: e.target.checked })}
        />
        Required
      </label>
    </>
  );
}
```

`update()` takes only what you change, with the same settings a field reads:

| Setting                                      | What it is                                                                                                                                                                                                   |
| :------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `name`                                       | Its own part of its name: renaming `customer.email` to `phone` makes `customer.phone`                                                                                                                        |
| `required`                                   | PDF apps ask for a value before the form is submitted                                                                                                                                                        |
| `readOnly`                                   | People can't change the value                                                                                                                                                                                |
| `alternateName`                              | The tooltip, also read by screen readers                                                                                                                                                                     |
| `placeholder`                                | The text an empty field shows, or `null`. [A field's placeholder](#a-fields-placeholder)                                                                                                                     |
| `defaultValue`                               | What a reset puts back                                                                                                                                                                                       |
| `options`                                    | For a dropdown or list: `{ label, value }` pairs                                                                                                                                                             |
| `maxLength`, `multiline`, `password`, `comb` | For a text box                                                                                                                                                                                               |
| `groupId`                                    | The group it's in: who fills it in. [Give fields to a signer](#give-fields-to-a-signer)                                                                                                                      |
| `assignment`                                 | Who fills it in: `{ kind: 'group', groupId }`, `{ kind: 'anyone' }` or `{ kind: 'unassigned' }`. [Place fields anyone fills in](#place-fields-anyone-fills-in)                                               |
| `purpose`                                    | What it's for, or `null`. [What a field is for](#what-a-field-is-for)                                                                                                                                        |
| `format`                                     | For a text box or a dropdown, the shape of its value: `{ kind: 'date', pattern }`, `{ kind: 'time', pattern }`, or `null` for any text. [Dates](https://www.embedpdf.com/docs/headless/react/forms.md#dates) |

`getFieldSettings(ref)` describes a field's settings for a panel you draw without knowing the
field's kind: `{ properties, values }`, each property a `key` (what `update()` takes), a `control`
(`text`, `flag`, `number`, `choice`, `choices` or `options`), and a `label` in English with its
translation key, `labelKey` (`form.settings.tooltip`), in display order. A `choice`'s options are
the field's own values, shown as they are. While the document has groups, `groupId` is one of the
settings: a `choice` whose options are the ids of the groups the user may put the field in. Show
each with its group's label, from the form's `groups`; none of them, `null`, takes the field out
of its group. Beside it, `assignment` says who fills the field in, whole, with a control of its
own, `assignment`: its options are the assignments the user may give the field
(`canAssign()`), the field's own among them, and never anyone on a signature field. Show a
group by its label, anyone as "Anyone", and nobody in a word of yours. A panel that draws
`assignment` leaves `groupId` out; `groupId` stays for a panel that knows only groups.

On a text box, a dropdown, a signature field and an image field, **`placeholder`** comes after
the tooltip: a `text` setting that is `trimmed`, whose value is the field's placeholder, or
`null`. Write a `trimmed` text without the space typed at its ends, and write `null` when
nothing is left, since `update()` rejects such text and never trims it. The setting also has
`maxLength`, the most characters a placeholder takes: give it to your input as its own
`maxLength`, so typing stops there and a longer paste is cut to it. `update()` rejects a longer
text too. A panel of your own reads both from the description, as the example below does for
the limit.

Two more settings describe what the field is for and the shape of its value:

- **`purpose`** is a `choice` whose options are the ids of the purposes the viewer knows, and
  the field's own when it is another word. Show each with its label, from
  `form.listPurposes()`; none of them, `null`, takes the purpose away.
- **`format`**, on a text box and a dropdown, has a control of its own, `format`. Its value is
  what `update()` takes: `{ kind, pattern }`, or `null` for none. The setting lists the `kinds`
  to offer, `'date'` and `'time'`, and for each the `patterns` Acrobat offers. Let people type a
  pattern of their own too: `isDatePattern()` and `isTimePattern()` say whether the engine takes
  it, and `update()` rejects one it doesn't with `invalid-input`, before anything is written. A
  field whose format is `{ kind: 'other' }` has a format script of its own: show it as it is,
  and `null` takes it away.

An app that draws its panel from the description gains both, so give your panel a case for
`format`, or leave that control out.

A field's look, such as its border, background and font, belongs to its box: change it like any
annotation's, with the [style panel](https://www.embedpdf.com/docs/headless/react/annotations/selecting.md#a-style-panel), or from code with
`form.updateWidget(widget.ref, { color: '#1d4ed8' })`.

**`field-settings.tsx`**

```tsx
import { useEffect, useRef } from 'react';
import { Viewer, DocumentGate } from '@embedpdf/react/runtime';
import type { OpenInput } from '@embedpdf/react/runtime';
import { Stage, stagePlugin } from '@embedpdf/react/stage';
import { RenderLayer, renderPlugin } from '@embedpdf/react/render';
import { interactionPlugin, useInteraction } from '@embedpdf/react/interaction';
import { AnnotationLayer, annotationPlugin, useAnnotation } from '@embedpdf/react/annotation';
import { FormLayer, formPlugin, toFieldRef, useForm, useFormState } from '@embedpdf/react/form';
import type { FormFieldSettings } from '@embedpdf/react/form';
import { localEngine } from '@embedpdf/engine';

import './field-settings.css';

const engine = localEngine();
const plugins = [
  stagePlugin(),
  renderPlugin(),
  interactionPlugin(),
  annotationPlugin(),
  formPlugin(),
];

const forms = async (): Promise<OpenInput> => {
  const response = await fetch('https://www.embedpdf.com/pdfs/forms.pdf');
  return { kind: 'bytes', id: 'forms', bytes: new Uint8Array(await response.arrayBuffer()) };
};

/** On load: design mode, with the name field selected. */
function useDesignForm() {
  const form = useForm();
  const annotation = useAnnotation();
  const interaction = useInteraction();
  const status = useFormState((state) => state.status);
  const started = useRef(false);

  useEffect(() => {
    if (status !== 'ready' || started.current) return;
    started.current = true;
    interaction.activateTool('form-edit');
    const widget = form.get(toFieldRef('name'))?.widgets[0]?.ref;
    if (widget) annotation.selection.select([widget]);
  }, [form, annotation, interaction, status]);
}

/** A field's Placeholder setting, as the form describes it: `null` for a kind that shows none. */
function placeholderSettingOf(settings: FormFieldSettings | null) {
  for (const setting of settings?.properties ?? []) {
    if (setting.key === 'placeholder') return setting;
  }
  return null;
}

/** What a settings panel shows for the selected field, and changes with `update()`. */
function FieldSettings() {
  useDesignForm();
  const form = useForm();
  const { selectedField: field } = useFormState();

  if (!field) return <p className="panel hint">Select a field on the page.</p>;
  // A field whose box shows a placeholder has the setting, with the most characters it takes.
  const placeholder = placeholderSettingOf(form.getFieldSettings(field.ref));

  return (
    <div className="panel">
      <label className="setting">
        Name
        <input
          key={field.name}
          className="input"
          defaultValue={field.name}
          onBlur={(event) => {
            const name = event.target.value.trim();
            if (name && name !== field.name) void form.update(field.ref, { name });
          }}
        />
      </label>
      <label className="setting">
        Tooltip
        <input
          key={`${field.name}:tooltip`}
          className="input"
          defaultValue={field.alternateName ?? ''}
          onBlur={(event) =>
            void form.update(field.ref, { alternateName: event.target.value || null })
          }
        />
      </label>
      {placeholder && (
        <label className="setting">
          Placeholder
          <input
            key={`${field.name}:placeholder`}
            className="input"
            maxLength={placeholder.maxLength}
            defaultValue={field.placeholder ?? ''}
            onBlur={(event) =>
              void form.update(field.ref, { placeholder: event.target.value.trim() || null })
            }
          />
        </label>
      )}
      <label className="check">
        <input
          type="checkbox"
          checked={field.required}
          onChange={(event) => void form.update(field.ref, { required: event.target.checked })}
        />
        Required
      </label>
      <label className="check">
        <input
          type="checkbox"
          checked={field.readOnly}
          onChange={(event) => void form.update(field.ref, { readOnly: event.target.checked })}
        />
        Read-only
      </label>
      <button type="button" className="button" onClick={() => void form.delete(field.ref)}>
        Remove the field
      </button>
    </div>
  );
}

export default function App() {
  return (
    <Viewer engine={engine} plugins={plugins} initialDocuments={[{ source: forms }]}>
      <DocumentGate fallback={<p className="loading">Loading…</p>}>
        <div className="viewer">
          <Stage className="stage">
            {() => (
              <>
                <RenderLayer />
                <AnnotationLayer />
                <FormLayer />
              </>
            )}
          </Stage>
          <FieldSettings />
        </div>
      </DocumentGate>
    </Viewer>
  );
}
```

**`field-settings.css`**

```css
/* Colors */
:root {
  --ink: #1a2748;
  --muted: #5a6b92;
  --line: #e6eaf2;
  --line-strong: #dce8fc;
  --surface: #ffffff;
  --tint: #f3f7fe;
  --canvas: #f7f9fc;
  --accent: #054fb3;
  --focus: #7db6ff;
  --shadow: rgb(7 32 76 / 0.04);
}

/* The pages and the settings panel: stacked, and side by side where there's room */
.viewer {
  container-type: inline-size;
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.stage,
.panel {
  flex: 1 1 100%;
  box-sizing: border-box;
  border: 1px solid var(--line);
  border-radius: 14px;
  box-shadow:
    0 1px 2px var(--shadow),
    0 18px 40px -28px rgb(7 32 76 / 0.28);
}

.stage {
  height: 340px;
  background: var(--canvas);
}

.panel {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin: 0;
  padding: 14px;
  background: var(--surface);
}

@container (min-width: 620px) {
  .stage {
    flex: 1 1 0;
    min-width: 0;
    height: 440px;
  }

  .panel {
    flex: 0 0 220px;
    align-self: flex-start;
  }
}

.hint {
  font-size: 13px;
  color: var(--muted);
}

/* One setting: a label over its input, or a checkbox beside its label */
.setting {
  display: flex;
  flex-direction: column;
  gap: 5px;
  font-size: 12px;
  font-weight: 600;
  color: var(--muted);
}

.input {
  font: inherit;
  font-size: 13px;
  font-weight: 400;
  color: var(--ink);
  background: var(--surface);
  border: 1px solid var(--line);
  border-radius: 8px;
  padding: 7px 9px;
}

.input:focus-visible {
  outline: none;
  border-color: var(--focus);
  box-shadow: 0 0 0 3px rgb(125 182 255 / 0.35);
}

.check {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 13px;
  color: var(--ink);
}

.check input {
  accent-color: var(--accent);
}

.button {
  font: inherit;
  font-size: 13px;
  font-weight: 550;
  line-height: 1;
  color: var(--ink);
  background: var(--surface);
  border: 1px solid var(--line);
  border-radius: 9px;
  padding: 8px 13px;
  cursor: pointer;
  box-shadow: 0 1px 2px var(--shadow);
}

.button:hover {
  background: var(--tint);
  border-color: var(--line-strong);
}

.button:focus-visible {
  outline: 2px solid var(--focus);
  outline-offset: 2px;
}

.loading {
  margin: 0;
  padding: 24px 0;
  text-align: center;
  font-size: 13px;
  color: var(--muted);
}
```

## Turn a field

A field turns by quarter turns, in two ways:

```ts
// The whole box: it stands the other way, and its contents turn with it
await annotation.selection.rotateBy(90); // -90 the other way; resetRotation() for upright

// Only its contents: the box stays where it stands, as Acrobat's Orientation does
await annotation.selection.update((widget) => orientationPatch(widget, 90));
```

`rotateBy()` turns the selected fields as it turns a stamp, about each box's middle (several
together turn about their middle). A field near the edge of its page stays on the page: where the
turn would carry it past the edge, it lands against the edge. A field has no rotation handle,
because a quarter turn is all it can hold. `orientationPatch()` comes with the annotation plugin:
it gives the `box` and `rotation` that turn a field's contents where it stands.

The [style panel](https://www.embedpdf.com/docs/headless/react/annotations/selecting.md#a-style-panel) lists the second as `orientation` for a
selection of fields: a choice of `'0'`, `'90'`, `'180'` and `'270'`, clockwise. Without a
selection, `form.updateWidget(widget.ref, orientationPatch(widget, 90))` does the same for one
box, and `form.updateWidget(widget.ref, { rotation: 90 })` turns the whole box. A box reads its
turn as `rotation`, with `box`, the frame its contents are laid out in, and `rect`, where it
stands; see [Turned fields](https://www.embedpdf.com/docs/headless/react/forms.md#turned-fields).

## Add fields from code

`create()` takes the same settings the engine takes, with the page and the box for each place the
field shows:

```ts
const { field } = await form.create({
  kind: 'combobox',
  name: 'country',
  options: [
    { label: 'Netherlands', value: 'NL' },
    { label: 'Belgium', value: 'BE' },
  ],
  widgets: [{ page: page.ref, rect: { x: 72, y: 252, width: 148, height: 20 } }],
});
```

A radio group is one field with a box per button, each with the value it stands for:

```ts
await form.create({
  kind: 'radio',
  name: 'plan',
  widgets: [
    { page: page.ref, rect: { x: 72, y: 136, width: 16, height: 16 }, exportValue: 'monthly' },
    { page: page.ref, rect: { x: 72, y: 166, width: 16, height: 16 }, exportValue: 'yearly' },
  ],
});
```

A field placed with a tool gets a name like `text_1`; rename it in your settings panel. Every
kind's settings are on [Creating form fields](https://www.embedpdf.com/docs/engine/forms/authoring.md).

**`create.tsx`**

```tsx
import { useState } from 'react';
import { Viewer, DocumentGate, usePageList } from '@embedpdf/react/runtime';
import type { OpenInput } from '@embedpdf/react/runtime';
import { Stage, stagePlugin, useStage } from '@embedpdf/react/stage';
import { RenderLayer, renderPlugin } from '@embedpdf/react/render';
import { interactionPlugin } from '@embedpdf/react/interaction';
import { FormLayer, formPlugin, useForm } from '@embedpdf/react/form';
import type { FormCapability, FormField } from '@embedpdf/react/form';
import type { PageRef } from '@embedpdf/react/runtime';
import { localEngine } from '@embedpdf/engine';

import './create.css';

const engine = localEngine();
const plugins = [stagePlugin(), renderPlugin(), interactionPlugin(), formPlugin()];

const registration = async (): Promise<OpenInput> => {
  const response = await fetch('https://www.embedpdf.com/pdfs/registration.pdf');
  return { kind: 'bytes', id: 'registration', bytes: new Uint8Array(await response.arrayBuffer()) };
};

// The printed boxes are the fields' look: a new field only sets its text size.
const look = { fontSize: 11 };

// The printed table of group tickets: a row every 36 points from the top at 470, with a country
// box at x 96 and a circle for each ticket at x 330 and 430.
const rowTop = (row: number) => 470 + row * 36;

/** A dropdown in a row's country box. */
function addDropdown(form: FormCapability, page: PageRef, row: number) {
  return form.create({
    kind: 'combobox',
    name: `country_${row + 1}`,
    options: [
      { label: 'Netherlands', value: 'NL' },
      { label: 'Belgium', value: 'BE' },
      { label: 'Germany', value: 'DE' },
    ],
    widgets: [{ page, rect: { x: 96, y: rowTop(row), width: 160, height: 24 }, ...look }],
  });
}

/** A radio group in a row's two circles: one field, a widget per circle, each with its value. */
function addRadioGroup(form: FormCapability, page: PageRef, row: number) {
  const y = rowTop(row) + 4;
  return form.create({
    kind: 'radio',
    name: `ticket_${row + 1}`,
    widgets: [
      { page, rect: { x: 330, y, width: 16, height: 16 }, exportValue: 'one-day', ...look },
      { page, rect: { x: 430, y, width: 16, height: 16 }, exportValue: 'both-days', ...look },
    ],
  });
}

function BuildToolbar() {
  const form = useForm();
  const stage = useStage();
  const page = usePageList()[0]?.ref; // the printed form
  const [added, setAdded] = useState<FormField[]>([]);

  // Each kind of field fills its column from the top: the next row that hasn't got one.
  const rowFor = (kind: FormField['kind']) => added.filter((field) => field.kind === kind).length;

  const add = async (addField: typeof addDropdown, kind: FormField['kind']) => {
    if (!page) return;
    const { field } = await addField(form, page, rowFor(kind));
    setAdded((fields) => [...fields, field]);
    stage.reveal(page, { rect: form.getWidget(field.widgets[0])!.rect });
  };

  const last = added.at(-1);

  return (
    <div className="toolbar">
      <button
        type="button"
        className="button"
        disabled={!page || rowFor('combobox') >= 5}
        onClick={() => void add(addDropdown, 'combobox')}
      >
        Add a dropdown
      </button>
      <button
        type="button"
        className="button"
        disabled={!page || rowFor('radio') >= 5}
        onClick={() => void add(addRadioGroup, 'radio')}
      >
        Add a radio group
      </button>
      <button
        type="button"
        className="button"
        disabled={!last}
        onClick={async () => {
          if (!last) return;
          await form.delete(last.ref);
          setAdded((fields) => fields.slice(0, -1));
        }}
      >
        Remove the last
      </button>
      <output className="readout">
        {added.map((field) => field.name).join(', ') || 'No fields in the table yet'}
      </output>
    </div>
  );
}

export default function App() {
  return (
    <Viewer engine={engine} plugins={plugins} initialDocuments={[{ source: registration }]}>
      <DocumentGate fallback={<p className="loading">Loading…</p>}>
        <BuildToolbar />
        <Stage className="stage">
          {() => (
            <>
              <RenderLayer />
              <FormLayer />
            </>
          )}
        </Stage>
      </DocumentGate>
    </Viewer>
  );
}
```

**`create.css`**

```css
/* Colors */
:root {
  --ink: #1a2748;
  --muted: #5a6b92;
  --line: #e6eaf2;
  --line-strong: #dce8fc;
  --surface: #ffffff;
  --tint: #f3f7fe;
  --canvas: #f7f9fc;
  --focus: #7db6ff;
  --shadow: rgb(7 32 76 / 0.04);
}

/* The controls, above the pages */
.toolbar {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
  margin-bottom: 14px;
}

.button {
  font: inherit;
  font-size: 13px;
  font-weight: 550;
  line-height: 1;
  color: var(--ink);
  background: var(--surface);
  border: 1px solid var(--line);
  border-radius: 9px;
  padding: 8px 13px;
  cursor: pointer;
  white-space: nowrap;
  box-shadow: 0 1px 2px var(--shadow);
  transition:
    background-color 0.15s ease,
    border-color 0.15s ease;
}

.button:hover {
  background: var(--tint);
  border-color: var(--line-strong);
}

.button:active {
  transform: translateY(1px);
}

.button:focus-visible {
  outline: 2px solid var(--focus);
  outline-offset: 2px;
}

.button:disabled {
  opacity: 0.45;
  cursor: not-allowed;
  transform: none;
}

.readout {
  font-size: 13px;
  font-weight: 600;
  color: var(--ink);
  overflow-wrap: anywhere;
}

/* The pages */
.stage {
  height: 440px;
  border: 1px solid var(--line);
  border-radius: 14px;
  background: var(--canvas);
  box-shadow:
    0 1px 2px var(--shadow),
    0 18px 40px -28px rgb(7 32 76 / 0.28);
}

.loading {
  margin: 0;
  padding: 24px 0;
  text-align: center;
  font-size: 13px;
  color: var(--muted);
}
```

> **Try it:** add a dropdown and a radio group: each goes into the next row of the printed table.

### One more button for a group

`addWidget(ref)` shows a field in one more place: for a radio group a new choice, for a checkbox a
box that checks together with the others.

```ts
const { widget } = await form.addWidget(plan.ref);
annotation.selection.select([widget.ref]); // in design mode, so it can be dragged
```

Without a place, it goes next in line: below the last button if they stand in a column, beside it
if in a row, at the same size and the same spacing, starting a new column where the page ends. It
looks like the field's last button, and a radio group's new choice gets the next free `Choice<n>`.
Pass what you want instead: `form.addWidget(plan.ref, { rect, exportValue: 'yearly' })` takes
everything an entry of `create()`'s `widgets` takes. An [image field](#image-fields)'s new place
shows its picture, as its last box does, and the field stays an image field, unless you give the
place an `activate` or `mouseUp` action of its own.

## Copy fields

`duplicateWidgets()` copies boxes, as Duplicate does in a designer. What a copy becomes follows
from what its box is:

- **A radio button is one answer to a question.** Its copy is another button in the same group,
  with the next free `Choice<n>` as its value.
- **Any other box is a whole question.** Its copy is a new field, named after the original:
  `email` becomes `email_2`.

```ts
// another button in the group, below the one it copies
await form.duplicateWidgets([button.ref], {
  offset: { x: 0, y: 24 },
});

// a new text field beside the original
const { fields } = await form.duplicateWidgets([box.ref], {
  offset: { x: 10, y: 10 },
});
```

Boxes of one field that are copied together become one new field. `duplicate()` copies whole
fields instead: a radio group becomes a new group with the same buttons and the same values.

```ts
const { fields } = await form.duplicate([plan.ref], {
  offset: { x: 0, y: 80 },
});
```

A new field has its original's settings, scripts and default value. It doesn't have its answer:
it starts empty, as a new field does. Pass `values: true` to copy the answer too. A signature
never comes along.

| Option   | What it does                                        | Default          |
| :------- | :-------------------------------------------------- | :--------------- |
| `page`   | The page the copies go on, as a ref or an index.    | each on its own  |
| `offset` | How far each copy moves: `{ x, y }` in page points. | `{ x: 0, y: 0 }` |
| `values` | Whether a new field gets its original's answer.     | `false`          |

Both resolve `{ fields, widgets, dropped }`: the fields that were made or got a new button, the
new boxes, and what was left out. A copy leaves out what
an [import](https://www.embedpdf.com/docs/engine/forms/import-export.md#whats-left-out) leaves out: a field of a kind the
engine doesn't know, a script when `canWriteScripts()` is false, an action it can't write. A box
in no field is left out too.

One call makes at most 10,000 new fields: the engine's item
[limit](https://www.embedpdf.com/docs/engine/forms/import-export.md#limits), which a server can change. More is refused with
`invalid-input`, and nothing is copied.

In design mode, [Duplicate the selection](https://www.embedpdf.com/docs/headless/react/annotations/selecting.md#duplicate-the-selection)
does this for the selected boxes, together with the annotations selected beside them.

## The same field on more pages

Initials at the foot of every page, a reference number in every header: place the field once, then
repeat it.

```ts
// or a list of pages, as refs or indexes
await form.repeat(initials.ref, { pages: 'all' });
```

Each copy stands at the same place on its page, and all of them are one change and one step to
undo, however many pages there are. What a copy becomes follows from what the field holds:

- **A value is one answer.** A text box, a checkbox or a dropdown gets one more box on each page,
  all of the same field: fill one in, and every page shows it.
- **A mark is made on each page.** An [image field](#image-fields), such as initials, becomes a
  new field on each page, named after the original, so each is filled in on its own and each can
  be required.
- **A signature field isn't repeated.** A signer signs once; put their initials on the other pages.

Pass `as: 'boxes'` or `as: 'fields'` to choose yourself.

| Option  | What it does                                                        | Default                 |
| :------ | :------------------------------------------------------------------ | :---------------------- |
| `pages` | The pages the field goes on: `'all'`, or a list of refs or indexes. | none: say which         |
| `as`    | What each page gets: `'boxes'` or `'fields'`.                       | by what the field holds |

- **What is repeated** is what the field shows on its first page: every box it has on the page of
  its first box. A reference number in the header and the footer of page one goes into both on
  every page.
- **The same place** is measured from the top-left corner of the page as it is shown. On a page
  that is [shown turned](#on-a-turned-page) another way, a copy stands where you see the original
  and reads the same way. On a smaller page, a copy that would stand past the edge is moved in.
- **A page the field already shows on is left as it is,** so after you add pages, repeating again
  reaches only the new ones. That holds for boxes: as fields, every page but the field's own gets
  a new field each time.
- **A radio group** is a value: its buttons go on the other pages with the same values, and
  `repeat()` turns on the group's `radiosInUnison`, so the buttons of one value go on and off
  together. A checkbox or radio group whose values the PDF names in a list (`/Opt`) takes no new
  box: `canRepeat()` is false for it, and with `as: 'fields'` each page gets a group of its own.
- **A new box** has the look, the flags and the actions of the one it repeats, and shows the
  picture an image field holds.
- **A new field** is what [`duplicate()`](#copy-fields) makes: the original's settings, look and
  scripts under the next free name (`initials_2`), who it is for, what it is for and its
  placeholder among them. It has no answer and no picture.

It resolves `{ fields, widgets, dropped }`, as `duplicate()` does: the new fields in the pages'
order, or for boxes the field as it is now; the new boxes; and what was left out, such as a
script when `canWriteScripts()` is false. With no page to go on, it changes nothing. A signature
field is refused with `invalid-input`, and `canRepeat(ref)` says beforehand whether a field can
be repeated.

It is the engine's [`doc.forms.repeat()`](https://www.embedpdf.com/docs/engine/forms/authoring.md#the-same-field-on-more-pages):
one write, and the copies show when the engine answers. One call reaches at most 2,000 pages by
default. More is refused with `invalid-input`, `details.limit` is `'pages'`, and nothing is made:
repeat a range of pages at a time.

## Scripts and calculations

A field's scripts go in `actions` when you create or change it: a calculated total, a formatted
amount, a check on what the user typed. The viewer runs them while the user fills the form in.

```ts
await form.update(total.ref, {
  actions: {
    calculate: {
      type: 'javascript',
      script: 'event.value = this.getField("subtotal").value * 1.21;',
    },
  },
});
await form.reorderCalculations([tax.ref], { before: total.ref });
```

A calculate script puts the field at the end of the order calculations run in;
`reorderCalculations()` moves it. Writing a script needs `canWriteScripts()`. See
[Scripts and calculations](https://www.embedpdf.com/docs/engine/forms/authoring.md#scripts-and-calculations).

A box can do something when it's clicked, too, such as reset the form: give its entry of
`widgets` in `create()` its `actions`. A script, a submit or a web link there needs
`canWriteScripts()` as well. See [Widget actions](https://www.embedpdf.com/docs/engine/forms/authoring.md#widget-actions).
A push button (`kind: 'pushbutton'`) is a box that only does that, with a `caption`; see
[A push button](https://www.embedpdf.com/docs/engine/forms/authoring.md#a-push-button).

## Remove a field

```ts
await form.delete(field.ref);
```

This removes the field and every box it has. To remove one box of a field that shows in several places,
such as a reference number on every page, use `form.deleteWidget(widget.ref)`. It resolves the field
as it is now. In design mode, deleting the selection does the same: one box goes from its field, and
a field whose every box is selected goes whole.

Every building method shows its change at once, is one step to undo, and resolves once the engine
answered.

## Methods

What `useForm()` gives you for building forms. Reading, filling and the form's state are on
[Filling forms](https://www.embedpdf.com/docs/headless/react/forms.md#methods).

| Method                                  | What it does                                                                                                                                                                                                                     |
| :-------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `create(draft)`                         | Adds a field, with a box for each place it shows. Resolves `{ field }`. [Add fields from code](#add-fields-from-code)                                                                                                            |
| `update(ref, patch)`                    | Changes a field's settings; pass only what changes. Resolves `{ field }`. [Change a field's settings](#change-a-fields-settings)                                                                                                 |
| `addWidget(ref, placement?)`            | Shows a field in one more place: a radio group's next choice, a checkbox's next box. Resolves `{ field, widget }`. [One more button for a group](#one-more-button-for-a-group)                                                   |
| `duplicate(fields, options?)`           | Copies whole fields, each as a new field. Resolves `{ fields, widgets, dropped }`. [Copy fields](#copy-fields)                                                                                                                   |
| `duplicateWidgets(widgets, options?)`   | Copies boxes: a radio button joins its group, any other box becomes a new field. Resolves `{ fields, widgets, dropped }`. [Copy fields](#copy-fields)                                                                            |
| `repeat(ref, options)`                  | Shows a field at the same place on more pages: `{ pages, as }`. Resolves `{ fields, widgets, dropped }`. [The same field on more pages](#the-same-field-on-more-pages)                                                           |
| `delete(ref)`                           | Removes a field and every box it has. [Remove a field](#remove-a-field)                                                                                                                                                          |
| `updateWidget(widget, patch)`           | Changes one box's place, turn or look; pass only what changes. Resolves `{ widget }`. [Change a field's settings](#change-a-fields-settings), [Turn a field](#turn-a-field)                                                      |
| `getFieldSettings(ref)`                 | A field's settings described for a panel: `{ properties, values }`, or `null`. [Change a field's settings](#change-a-fields-settings)                                                                                            |
| `deleteWidget(widget)`                  | Removes one box from its page, and from its field when it has one. Resolves `{ field }`, or `{ field: null }` for a box in no field. [Remove a field](#remove-a-field)                                                           |
| `removeWidget(ref, widget)`             | Takes one box out of its field; it stays on the page, in no field, until `deleteWidget()` removes it                                                                                                                             |
| `reorderCalculations(fields, position)` | Moves fields in the order calculate scripts run in. Resolves `{ calculationOrder }`. [Scripts and calculations](#scripts-and-calculations)                                                                                       |
| `repair(options?)`                      | Fixes a form other PDF apps read differently, such as fields missing from the form's list, and resolves what it fixed. See [Repair a broken form](https://www.embedpdf.com/docs/engine/forms/authoring.md#repair-a-broken-form). |
| `canDesign()`                           | Whether adding, changing and removing fields is allowed. [Permissions](#permissions)                                                                                                                                             |
| `canRepeat(ref)`                        | Whether `repeat()` takes this field: design is allowed, the field shows on a page, and it is no signature field. [The same field on more pages](#the-same-field-on-more-pages)                                                   |
| `setDesignGroup(groupId)`               | Says who the next fields are for: a field placed with a tool goes into this group; with `null` it is in none. Fires `onDesignGroupChanged`. [Place fields for a signer](#place-fields-for-a-signer)                              |
| `setDesignAssignment(assignment)`       | Says who the next fields are for: a group, anyone or nobody. Fires `onDesignGroupChanged`. [Place fields anyone fills in](#place-fields-anyone-fills-in)                                                                         |
| `moveToGroup(fields, groupId)`          | Puts fields in a group, or with `null` takes them out of theirs, as one step to undo. Resolves `{ fields }`. [Give fields to a signer](#give-fields-to-a-signer)                                                                 |
| `assign(fields, assignment)`            | Says who fields are for, as one step to undo. Resolves `{ fields }`. [Give fields to a signer](#give-fields-to-a-signer)                                                                                                         |
| `canSetGroup(groupId)`                  | Whether the user may put a field in that group. [Place fields for a signer](#place-fields-for-a-signer)                                                                                                                          |
| `canAssign(assignment)`                 | Whether the user may give a field that assignment. [Place fields anyone fills in](#place-fields-anyone-fills-in)                                                                                                                 |
| `canRestoreAttribution()`               | Whether an import may keep who created its fields, instead of naming the importing user. [Permissions](#permissions)                                                                                                             |
| `canWriteScripts()`                     | Whether scripts, submit buttons and links may be written into fields and their boxes. [Permissions](#permissions)                                                                                                                |

Every method that returns a promise also takes a `signal` in its options, to cancel it.

## Events

**`select-new-field.tsx`**

```tsx
import { useFormEvent } from '@embedpdf/react/form';
import { selectField } from './editor';

export function SelectNewFields() {
  useFormEvent(
    (form) => form.onFieldCreated,
    ({ field }) => selectField(field),
  );

  return null;
}
```

| Event                  | Fires when                                                       | Carries                 |
| :--------------------- | :--------------------------------------------------------------- | :---------------------- |
| `onFieldCreated`       | A field was added                                                | `field`, `origin`       |
| `onFieldUpdated`       | A field's settings changed                                       | `field`, `origin`       |
| `onFieldDeleted`       | A field was removed                                              | `ref`, `origin`         |
| `onDesignGroupChanged` | Who new fields are placed for changed: a group, anyone or nobody | `groupId`, `assignment` |

## Permissions

| Permission             | What it allows                                                  | Check                                |
| :--------------------- | :-------------------------------------------------------------- | :----------------------------------- |
| `doc.forms.modify`     | Adding, changing, removing and repairing fields                 | `form.canDesign()`                   |
| `doc.forms.import`     | Importing fields with who created them                          | `form.canRestoreAttribution()`       |
| `doc.forms.script`     | Writing scripts, submit buttons and links into fields and boxes | `form.canWriteScripts()`             |
| `fields:set-group`     | Putting a field in a group other than your own                  | `form.canSetGroup(groupId)`          |
| `fields:set-group:all` | Making a field one anyone fills in                              | `form.canAssign({ kind: 'anyone' })` |

Hide the field tools when `canDesign()` is false, and the script, submit and link options of a
field's or a box's actions when `canWriteScripts()` is false. Scripts already in the form run either way.

## Good to know

### Fields and boxes

A field is the data: its name, its value, its settings. A **widget** is a box where the field shows on
a page. Most fields have one; a radio group has one per button, and a field can show on several pages,
all with the same value.

### Signature fields

A signature field is a place for someone to sign later. Signing it is on [Signatures](https://www.embedpdf.com/docs/headless/react/forms/signatures.md).
