---
title: "Your own form controls — Vue"
description: "Attach your own UI to a form field, such as a calendar next to a date field or a tag on the fields still to fill in, and draw a field's control with your own component."
framework: "Vue"
other_frameworks:
  "React": "https://www.embedpdf.com/docs/headless/react/forms/controls.md"
  "Svelte": "https://www.embedpdf.com/docs/headless/svelte/forms/controls.md"
  "Angular": "https://www.embedpdf.com/docs/headless/angular/forms/controls.md"
source: "https://www.embedpdf.com/docs/headless/vue/forms/controls"
---

# Your own form controls

The form layer draws each field as an HTML control: a text box, a checkbox, a list. You can put your
own UI on a field, or draw its control yourself: a calendar next to a date field, a tag on the
fields still to fill in, a switch instead of a checkbox.

This changes the screen only. What people enter is still the field's value in the PDF, so other PDF
apps, printing and downloads show the field as the PDF describes it.

## Its control, or UI on it

Ask whether it should zoom and turn with the PDF:

| You want                                                                 | Use                                                  | It                                                                                       |
| :----------------------------------------------------------------------- | :--------------------------------------------------- | :--------------------------------------------------------------------------------------- |
| A calendar, a hint or a menu next to a field                             | [Anchored UI](#show-a-calendar-next-to-a-date-field) | Floats over the pages, and moves to stay in view                                         |
| A tag that stays on a field: "Required", a signer's name, a ✓            | [Pinned anchored UI](#pin-a-tag-to-a-field)          | Floats over the pages, upright and the same size at every zoom, exactly where you put it |
| A different control: a switch for a checkbox, a button inside a text box | A [control](#draw-a-control-your-way)                | Is part of the page: it zooms and turns with the field                                   |

It's the same choice as for [an annotation](https://www.embedpdf.com/docs/headless/vue/annotations/custom-rendering.md#its-look-or-ui-on-it).
Most of what an app adds to a form is the first two, and they need nothing from the form layer.

## Show a calendar next to a date field

`useFormWidgetAnchor(widget)` gives you the anchor of one box of a field, and follows it when the
field is moved. A date picker is a card next to the date field the cursor is in:

**`date-picker.vue`**

```vue
<!-- DatePicker.vue -->
<script setup lang="ts">
import { computed, shallowRef } from 'vue';
import { Anchored } from '@embedpdf/vue/anchored';
import {
  formatDate,
  useForm,
  useFormEvent,
  useFormWidgetAnchor,
  type DatePartsInput,
  type FormFocusChangedEvent,
} from '@embedpdf/vue/form';
import Calendar from './Calendar.vue'; // your own

const form = useForm();
const focus = shallowRef<FormFocusChangedEvent | null>(null);
useFormEvent(
  (form) => form.onFocusChanged,
  (event) => (focus.value = event),
);
const anchor = useFormWidgetAnchor(() => focus.value?.widget ?? null);

// The date field the cursor is in, and the pattern of its dates.
const date = computed(() => {
  const field = focus.value?.field;
  const format = field && 'format' in field ? field.format : null;
  return field && format?.kind === 'date' ? { field, pattern: format.pattern } : null;
});

const pick = (day: DatePartsInput) => {
  if (!date.value) return;
  const { field, pattern } = date.value;
  // A text box writes what was typed when the cursor leaves it: the picked day goes in after.
  (document.activeElement as HTMLElement | null)?.blur();
  void form.setValue(field.ref, { value: formatDate(day, pattern) });
};
</script>

<template>
  <Anchored v-if="date" :anchor="anchor" placement="bottom-start">
    <!-- A press on the calendar leaves the cursor in the field until a day is picked. -->
    <div @mousedown.prevent>
      <Calendar @pick="pick" />
    </div>
  </Anchored>
</template>
```

Mount it in the Stage's `#overlay`
slot, like a [menu](https://www.embedpdf.com/docs/headless/vue/ui/anchored.md). Three things make it work:

1. `onFocusChanged` carries the field the cursor moved into, and the box it's in.
2. `field.format` says what shape the field's value has. For a date it is
   `{ kind: 'date', pattern: 'dd/mm/yyyy' }`, read from the PDF, so a date field made in Acrobat
   has it too. See [Dates](https://www.embedpdf.com/docs/headless/vue/forms.md#dates).
3. `formatDate()` writes the picked day the way the field's pattern asks, and `setValue()` fills
   the field in with the form's own checks, as typing does.

**`App.vue`**

```vue
<script setup lang="ts">
import { DocumentGate, Viewer } from '@embedpdf/vue/runtime';
import type { OpenInput } from '@embedpdf/vue/runtime';
import { Stage, stagePlugin } from '@embedpdf/vue/stage';
import { RenderLayer, renderPlugin } from '@embedpdf/vue/render';
import { interactionPlugin } from '@embedpdf/vue/interaction';
import { FormLayer, formPlugin } from '@embedpdf/vue/form';
import { localEngine } from '@embedpdf/engine';
import DatePicker from './DatePicker.vue';
import Refused from './Refused.vue';

import '../date-picker.css';

const engine = localEngine();
// No JavaScript here: the form plugin checks a typed date against the field's pattern itself.
const plugins = [stagePlugin(), renderPlugin(), interactionPlugin(), formPlugin()];

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

<template>
  <Viewer :engine="engine" :plugins="plugins" :initial-documents="[{ source: invoice }]">
    <DocumentGate>
      <template #fallback><p class="loading">Loading…</p></template>
      <Refused />
      <Stage class="stage">
        <template #page>
          <RenderLayer />
          <FormLayer />
        </template>
        <template #overlay>
          <DatePicker />
        </template>
      </Stage>
    </DocumentGate>
  </Viewer>
</template>
```

**`date-picker.css`**

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

/* What the form says, above the pages */
.toolbar {
  display: flex;
  flex-wrap: wrap;
  align-items: baseline;
  gap: 12px;
  margin-bottom: 14px;
}

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

/* The calendar: a card next to the date field */
.calendar {
  width: 212px;
  padding: 8px;
  font-size: 13px;
  color: var(--ink);
  background: var(--surface);
  border: 1px solid var(--line);
  border-radius: 12px;
  box-shadow:
    0 1px 2px var(--shadow),
    0 14px 32px -18px rgb(7 32 76 / 0.45);
}

.calendar-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 4px;
}

.calendar-month {
  font-weight: 600;
}

.calendar-turn {
  width: 26px;
  height: 26px;
  padding: 0;
  font: inherit;
  font-size: 16px;
  line-height: 1;
  color: var(--muted);
  background: none;
  border: 0;
  border-radius: 8px;
  cursor: pointer;
}

.calendar-turn:hover {
  color: var(--ink);
  background: var(--tint);
}

.calendar-days {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 2px;
}

.calendar-day {
  height: 24px;
  padding: 0;
  font: inherit;
  font-size: 12.5px;
  color: var(--ink);
  background: none;
  border: 0;
  border-radius: 8px;
  cursor: pointer;
}

.calendar-day:hover {
  background: var(--tint);
}

.calendar-day[aria-pressed='true'] {
  color: var(--on-accent);
  background: var(--accent);
}

.calendar-turn:focus-visible,
.calendar-day:focus-visible {
  outline: 2px solid var(--focus);
  outline-offset: 1px;
}

/* The pages: tall enough for the calendar to open under the date field */
.stage {
  height: 480px;
  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);
}
```

**`Calendar.vue`**

```vue
<!-- A month of days. `shown` is the day the field holds, when it holds one. -->
<script setup lang="ts">
import { ref } from 'vue';
import type { DatePartsInput } from '@embedpdf/vue/form';
import { daysOf, today } from './days';

const props = defineProps<{ shown: DatePartsInput | null }>();
const emit = defineEmits<{ pick: [day: DatePartsInput] }>();

const MONTHS = [
  'January',
  'February',
  'March',
  'April',
  'May',
  'June',
  'July',
  'August',
  'September',
  'October',
  'November',
  'December',
];

const start = props.shown ?? today();
const year = ref(start.year);
const month = ref(start.month);

const turn = (by: number) => {
  const next = new Date(year.value, month.value - 1 + by, 1);
  year.value = next.getFullYear();
  month.value = next.getMonth() + 1;
};
</script>

<template>
  <div class="calendar" role="group" aria-label="Pick a date">
    <div class="calendar-bar">
      <button type="button" class="calendar-turn" aria-label="Month before" @click="turn(-1)">
        ‹
      </button>
      <span class="calendar-month">{{ MONTHS[month - 1] }} {{ year }}</span>
      <button type="button" class="calendar-turn" aria-label="Month after" @click="turn(1)">
        ›
      </button>
    </div>
    <div class="calendar-days">
      <template v-for="(day, at) in daysOf(year, month)" :key="at">
        <span v-if="day === null" />
        <button
          v-else
          type="button"
          class="calendar-day"
          :aria-pressed="shown?.year === year && shown.month === month && shown.day === day"
          @click="emit('pick', { year, month, day })"
        >
          {{ day }}
        </button>
      </template>
    </div>
  </div>
</template>
```

**`DatePicker.vue`**

```vue
<!-- A calendar next to the date field the cursor is in. -->
<script setup lang="ts">
import { computed, shallowRef } from 'vue';
import { Anchored } from '@embedpdf/vue/anchored';
import {
  formatDate,
  parseDate,
  useForm,
  useFormEvent,
  useFormWidgetAnchor,
} from '@embedpdf/vue/form';
import type { DatePartsInput, FormFocusChangedEvent } from '@embedpdf/vue/form';
import Calendar from './Calendar.vue';
import { today } from './days';

const form = useForm();
const focus = shallowRef<FormFocusChangedEvent | null>(null);
useFormEvent(
  (form) => form.onFocusChanged,
  (event) => (focus.value = event),
);
const anchor = useFormWidgetAnchor(() => focus.value?.widget ?? null);

// A date field says so in its format, read from the PDF.
const date = computed(() => {
  const field = focus.value?.field;
  const format = field && 'format' in field ? field.format : null;
  if (!field || field.kind !== 'text' || format?.kind !== 'date') return null;
  return { field, pattern: format.pattern };
});

const pick = (day: DatePartsInput) => {
  if (!date.value) return;
  const { field, pattern } = date.value;
  // A text box writes what was typed when the cursor leaves it: the picked day goes in after.
  (document.activeElement as HTMLElement | null)?.blur();
  void form.setValue(field.ref, { value: formatDate(day, pattern) });
};
</script>

<template>
  <Anchored v-if="date" :anchor="anchor" placement="bottom-start" :gap="6">
    <!-- A press on the calendar leaves the cursor in the field until a day is picked. -->
    <div @mousedown.prevent>
      <Calendar
        :key="date.field.name"
        :shown="parseDate(date.field.value, date.pattern, today())"
        @pick="pick"
      />
    </div>
  </Anchored>
</template>
```

**`days.ts`**

```typescript
import type { DatePartsInput } from '@embedpdf/vue/form';

/** Today, as the calendar counts: a year, a month from 1, a day. */
export function today(): DatePartsInput {
  const now = new Date();
  return { year: now.getFullYear(), month: now.getMonth() + 1, day: now.getDate() };
}

/** The days of a month, after the blanks that put the 1st under its weekday (Monday first). */
export function daysOf(year: number, month: number): (number | null)[] {
  const blanks = (new Date(year, month - 1, 1).getDay() + 6) % 7;
  const count = new Date(year, month, 0).getDate();
  return [...Array<null>(blanks).fill(null), ...Array.from({ length: count }, (_, at) => at + 1)];
}
```

**`Refused.vue`**

```vue
<!-- What the form refused last, so a mistyped date says why. -->
<script setup lang="ts">
import { ref } from 'vue';
import { useFormEvent } from '@embedpdf/vue/form';

const refused = ref<string | null>(null);

useFormEvent(
  (form) => form.onValidationRejected,
  ({ issues }) => (refused.value = issues[0]?.message ?? 'The form refused that value.'),
);
useFormEvent(
  (form) => form.onValueChanged,
  () => (refused.value = null),
);
</script>

<template>
  <div class="toolbar">
    <output class="readout">{{ refused ?? 'Click the order date, or type one.' }}</output>
  </div>
</template>
```

> **Try it:** click the order form's date box: a calendar opens under it. Pick a day, and the
> field shows it as day/month/year. Typing still works: type `5/3/26` and press Tab, and it shows
> as `05/03/2026`; type `soon`, and the field refuses it.

Typing a date still works, with the picker open or without one. The calendar is your own
component: the example draws a small one, and a date library's fits the same way. A press on the
card leaves the cursor in the field, so the card stays open while someone turns the months. A
pick takes the cursor out of the field first: a text box writes what was typed when the cursor
leaves it, so the picked day goes in after that and nothing types over it.

## Pin a tag to a field

A tag on each field that still has to be filled in, a signer's name on each of their fields, a ✓ on
a field that's done: UI that belongs to one field and stays on it. The same anchor holds it, and
`pinned` keeps the tag exactly where you put it:

**`field-tag.vue`**

```vue
<!-- FieldTag.vue -->
<script setup lang="ts">
import { Anchored } from '@embedpdf/vue/anchored';
import { useForm, useFormWidgetAnchor, type FormField } from '@embedpdf/vue/form';

const props = defineProps<{ field: FormField }>();

// A tag beside the first box of a field.
const form = useForm();
const anchor = useFormWidgetAnchor(() => form.getWidgets(props.field.ref)[0]?.ref ?? null);
</script>

<template>
  <Anchored :anchor="anchor" placement="left" :gap="4" pinned>
    <span class="tag"><slot /></span>
  </Anchored>
</template>
```

Pass the box as a function, and the anchor follows `field` when it changes.

Draw one for each field that needs it: `form.validate().missing` lists the required fields this
user still has to fill in. Mount
them in the Stage's `#overlay` slot, like a [menu](https://www.embedpdf.com/docs/headless/vue/ui/anchored.md).

**`App.vue`**

```vue
<script setup lang="ts">
import { DocumentGate, Viewer } from '@embedpdf/vue/runtime';
import type { OpenInput } from '@embedpdf/vue/runtime';
import { Stage, stagePlugin } from '@embedpdf/vue/stage';
import { RenderLayer, renderPlugin } from '@embedpdf/vue/render';
import { interactionPlugin } from '@embedpdf/vue/interaction';
import { FormLayer, formPlugin } from '@embedpdf/vue/form';
import { localEngine } from '@embedpdf/engine';
import RequiredTags from './RequiredTags.vue';
import ViewButtons from './ViewButtons.vue';

import '../tags.css';

const engine = localEngine();
const plugins = [stagePlugin(), renderPlugin(), interactionPlugin(), 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()) };
};
</script>

<template>
  <Viewer :engine="engine" :plugins="plugins" :initial-documents="[{ source: forms }]">
    <DocumentGate>
      <template #fallback><p class="loading">Loading…</p></template>
      <ViewButtons />
      <Stage class="stage">
        <template #page>
          <RenderLayer />
          <FormLayer />
        </template>
        <template #overlay>
          <RequiredTags />
        </template>
      </Stage>
    </DocumentGate>
  </Viewer>
</template>
```

**`tags.css`**

```css
/* Colors */
:root {
  --ink: #1a2748;
  --muted: #5a6b92;
  --line: #e6eaf2;
  --line-strong: #dce8fc;
  --surface: #ffffff;
  --tint: #f3f7fe;
  --canvas: #f7f9fc;
  --accent: #b45309;
  --accent-strong: #92400e;
  --on-accent: #ffffff;
  --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;
}

/* The tag on a field that still has to be filled in: a small round mark. It keeps its size
   at every zoom, while the page's margin shrinks with the page, so it is no wider than the
   margin of a page shown small. */
.tag {
  display: block;
  width: 18px;
  height: 18px;
  padding: 0;
  font: inherit;
  font-size: 12px;
  font-weight: 700;
  line-height: 18px;
  text-align: center;
  color: var(--on-accent);
  background: var(--accent);
  border: 0;
  border-radius: 50%;
  cursor: pointer;
  box-shadow: 0 2px 6px rgb(7 32 76 / 0.18);
  transition: background-color 0.15s ease;
}

.tag:hover {
  background: var(--accent-strong);
}

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

/* 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);
}
```

**`RequiredTags.vue`**

```vue
<script setup lang="ts">
import { computed } from 'vue';
import { useForm, useFormState } from '@embedpdf/vue/form';
import Tag from './Tag.vue';

const form = useForm();
const { fields } = useFormState();

// A tag on every required field that is still empty.
const missing = computed(() => {
  void fields.value; // again when a field is filled in
  return form.validate().missing;
});
</script>

<template>
  <Tag v-for="field in missing" :key="field.name" :field="field" />
</template>
```

**`Tag.vue`**

```vue
<script setup lang="ts">
import { Anchored } from '@embedpdf/vue/anchored';
import { useForm, useFormWidgetAnchor } from '@embedpdf/vue/form';
import type { FormField } from '@embedpdf/vue/form';

const props = defineProps<{ field: FormField }>();

// A tag beside the first box of a field: pinned, so it stays on the field. A pinned tag keeps
// its size at every zoom, so this one is small: it fits in the page's margin on a phone too.
const form = useForm();
const anchor = useFormWidgetAnchor(() => form.getWidgets(props.field.ref)[0]?.ref ?? null);
</script>

<template>
  <Anchored :anchor="anchor" placement="left" :gap="6" pinned>
    <button
      type="button"
      class="tag"
      title="Required"
      :aria-label="`Required: ${field.alternateName ?? field.name}`"
      @click="form.focus(field.ref)"
    >
      !
    </button>
  </Anchored>
</template>
```

**`ViewButtons.vue`**

```vue
<script setup lang="ts">
import { useStage } from '@embedpdf/vue/stage';

// The view's own controls: the tags follow the view when it zooms and turns.
const stage = useStage();
</script>

<template>
  <div class="toolbar">
    <button type="button" class="button" @click="stage.zoomOut()">Zoom out</button>
    <button type="button" class="button" @click="stage.zoomIn()">Zoom in</button>
    <button type="button" class="button" @click="stage.rotateViewBy(90)">Turn the view</button>
  </div>
</template>
```

> **Try it:** each required field that is still empty has an orange tag. Fill one in: its tag
> goes. Scroll, zoom and turn the view, and the tags stay on their fields, at the same size.

A field can show in several boxes, so an anchor is for one box: `form.getWidgets(field.ref)` lists
a field's boxes, each with its `ref`. Anchored UI on a page that isn't on screen isn't drawn, so a
form with hundreds of fields costs only the ones in view. See
[Where it goes](https://www.embedpdf.com/docs/headless/vue/ui/anchored.md#where-it-goes) for `placement` and `gap`.

A pinned tag keeps its size and its side at every zoom, and isn't moved to where there is room. The
room beside a field shrinks with the page: next to a field at the edge of a page shown small, such
as on a phone, there are a few dozen pixels. So keep a tag there small, as the example's is, or put
it on a side of the field that has room.

## Draw a control your way

Give the layer a list of **controls**. Each one says which
boxes it draws and with which component:

**`controls.vue`**

```vue
<script setup lang="ts">
import { FormLayer, type FieldControl } from '@embedpdf/vue/form';
import FieldSwitch from './FieldSwitch.vue';

const controls: FieldControl[] = [
  {
    for: (widget) => widget.control === 'toggle' && widget.kind === 'checkbox',
    component: FieldSwitch,
  },
];
</script>

<template>
  <FormLayer :controls />
</template>
```

`for`
gets the box, with [what it tells you](#what-a-box-tells-you), so you can pick by control, by the
field's group or anything else. The first control that matches wins; a box no control matches is
drawn as usual.

Your component draws into a **frame**: a box the layer places, turns and scales exactly like
the field. Fill it, with `width` and `height` at `100%`, and draw at the field's 100% size: the
layer scales your drawing with the page. A field that is [turned](https://www.embedpdf.com/docs/headless/vue/forms.md#turned-fields) turns
its frame, so your control reads the way the field reads with no code of yours.

**`switch.vue`**

```vue
<!-- FieldSwitch.vue -->
<script setup lang="ts">
import type { FieldControlProps } from '@embedpdf/vue/form';

defineProps<FieldControlProps>();
</script>

<template>
  <!-- It fills its frame (`width` and `height` 100% in your CSS), and turns with the field. -->
  <button
    v-if="widget.control === 'toggle'"
    role="switch"
    class="switch"
    :aria-checked="widget.checked"
    :aria-label="widget.label"
    :disabled="widget.disabled"
    @click="setValue({ checked: !widget.checked })"
  />
</template>
```

Your component gets:

| Prop        | What it is                                                                                                                                                                                                                     |
| :---------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `widget`    | The box, as `listWidgets()` gives it: its field (`fieldRef`), its control, its value, and [what it tells you](#what-a-box-tells-you).                                                                                          |
| `frame`     | The box you draw into: its `width` and `height` in pixels at the field's 100% size, its `rotation` on screen in degrees clockwise, and the `scale` the layer draws it at.                                                      |
| `native`    | The layer's own control for the box with the field's picture, filling the frame. Render it to keep the control and add to it.                                                                                                  |
| `set-value` | Fills in the field: `setValue({ value })`, `({ checked })` or `({ selectedValues })`, with the same checks, scripts and undo step as [`form.setValue()`](https://www.embedpdf.com/docs/headless/vue/forms.md#fill-in-a-field). |
| `focused`   | True while the cursor is in this box.                                                                                                                                                                                          |

The frame is the same one an [annotation renderer](https://www.embedpdf.com/docs/headless/vue/annotations/custom-rendering.md#draw-an-annotation-your-way)
gets. Your control is drawn in place of the field's picture, so a switch shows no check mark under
it.

**`App.vue`**

```vue
<script setup lang="ts">
import { DocumentGate, Viewer } from '@embedpdf/vue/runtime';
import type { OpenInput } from '@embedpdf/vue/runtime';
import { Stage, stagePlugin } from '@embedpdf/vue/stage';
import { RenderLayer, renderPlugin } from '@embedpdf/vue/render';
import { interactionPlugin } from '@embedpdf/vue/interaction';
import { FormLayer, formPlugin } from '@embedpdf/vue/form';
import type { FieldControl } from '@embedpdf/vue/form';
import { localEngine } from '@embedpdf/engine';
import Switch from './Switch.vue';
import ViewButtons from './ViewButtons.vue';

import '../controls.css';

const engine = localEngine();
const plugins = [stagePlugin(), renderPlugin(), interactionPlugin(), 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()) };
};

// The first control that matches a box draws it; the layer draws every other box.
const controls: FieldControl[] = [
  { for: (widget) => widget.control === 'toggle' && widget.kind === 'checkbox', component: Switch },
];
</script>

<template>
  <Viewer :engine="engine" :plugins="plugins" :initial-documents="[{ source: forms }]">
    <DocumentGate>
      <template #fallback><p class="loading">Loading…</p></template>
      <ViewButtons />
      <Stage class="stage">
        <template #page>
          <RenderLayer />
          <FormLayer :controls="controls" />
        </template>
      </Stage>
    </DocumentGate>
  </Viewer>
</template>
```

**`controls.css`**

```css
/* Colors */
:root {
  --ink: #1a2748;
  --muted: #5a6b92;
  --line: #e6eaf2;
  --line-strong: #dce8fc;
  --surface: #ffffff;
  --tint: #f3f7fe;
  --canvas: #f7f9fc;
  --off: #c3cbdb;
  --on: #2f6fed;
  --knob: #ffffff;
  --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;
}

/* The switch. It is drawn in the field's frame, at the field's 100% size: the layer scales it
   with the page. A printed tick box is square and a switch is wide, so this one is as tall as its
   frame and reaches past it to the left. Its corners are the printed box's own, 4px at that
   size, and it has a hair of its own color around it, so it covers the box it stands on. */
.switch {
  position: absolute;
  top: 0;
  right: 0;
  height: 100%;
  aspect-ratio: 9 / 5;
  margin: 0;
  padding: 0;
  border: 0;
  border-radius: 4px;
  --track: var(--off);
  background: var(--track);
  box-shadow: 0 0 0 0.5px var(--track);
  cursor: pointer;
  transition:
    background-color 0.15s ease,
    box-shadow 0.15s ease;
}

.switch::after {
  content: '';
  position: absolute;
  top: 2px;
  left: 2px;
  height: calc(100% - 4px);
  aspect-ratio: 1;
  border-radius: 2px;
  background: var(--knob);
  box-shadow: 0 1px 2px rgb(7 32 76 / 0.3);
  transition: left 0.15s ease;
}

.switch[aria-checked='true'] {
  --track: var(--on);
}

/* The knob is as wide as the switch is tall, less its 2px margins: five ninths of the width. */
.switch[aria-checked='true']::after {
  left: calc(100% * 4 / 9 + 2px);
}

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

.switch:disabled {
  opacity: 0.5;
  cursor: default;
}

/* 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);
}
```

**`Switch.vue`**

```vue
<script setup lang="ts">
import type { FieldControlProps } from '@embedpdf/vue/form';

// A checkbox as a switch. A click fills the field in, as a click on the checkbox would.
defineProps<FieldControlProps>();
</script>

<template>
  <button
    v-if="widget.control === 'toggle'"
    type="button"
    role="switch"
    class="switch"
    :aria-checked="widget.checked"
    :aria-label="widget.label"
    :disabled="widget.disabled"
    @click="setValue({ checked: !widget.checked })"
  />
</template>
```

**`ViewButtons.vue`**

```vue
<script setup lang="ts">
import { useStage } from '@embedpdf/vue/stage';

// The view's own controls: the switches follow the view when it zooms and turns.
const stage = useStage();
</script>

<template>
  <div class="toolbar">
    <button type="button" class="button" @click="stage.zoomOut()">Zoom out</button>
    <button type="button" class="button" @click="stage.zoomIn()">Zoom in</button>
    <button type="button" class="button" @click="stage.rotateViewBy(90)">Turn the view</button>
  </div>
</template>
```

> **Try it:** flip a switch, and the checkbox it stands for is filled in. Press Tab to move through
> the fields, the switches among them. Zoom and turn the view: the switches zoom and turn with the
> page.

A click on your control also runs the field's own action, when the PDF gives it one, after the
value you wrote: as a click on the layer's control does.

### Add to the layer's control

`native` is what the layer would have drawn: the field's picture, and its control. Render it and
put your own parts next to it, such as a button at the end of a text box that empties it:

**`clear-button.vue`**

```vue
<!-- TextBox.vue -->
<script setup lang="ts">
import { useForm, type FieldControlProps } from '@embedpdf/vue/form';

const props = defineProps<FieldControlProps>();
const form = useForm();

// Empty the box, then put the cursor back in it, ready for the new value.
const clear = () => props.setValue({ value: '' }).then(() => form.focus(props.widget.fieldRef));
</script>

<template>
  <!-- The layer's own text box, and a button at its end that empties it. -->
  <component :is="native" />
  <!-- Tab goes to the text box. -->
  <button
    v-if="widget.control === 'text' && !widget.disabled && widget.value !== ''"
    class="clear-button"
    :aria-label="`Clear ${widget.label}`"
    tabindex="-1"
    @click="clear"
  />
</template>
```

**`App.vue`**

```vue
<script setup lang="ts">
import { DocumentGate, Viewer } from '@embedpdf/vue/runtime';
import type { OpenInput } from '@embedpdf/vue/runtime';
import { Stage, stagePlugin } from '@embedpdf/vue/stage';
import { RenderLayer, renderPlugin } from '@embedpdf/vue/render';
import { interactionPlugin } from '@embedpdf/vue/interaction';
import { FormLayer, formPlugin } from '@embedpdf/vue/form';
import type { FieldControl } from '@embedpdf/vue/form';
import { localEngine } from '@embedpdf/engine';
import TextBox from './TextBox.vue';
import Toolbar from './Toolbar.vue';

import '../clear-button.css';

const engine = localEngine();
const plugins = [stagePlugin(), renderPlugin(), interactionPlugin(), 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()) };
};

// The one-line text boxes get the button; the layer draws every other box.
const controls: FieldControl[] = [
  { for: (widget) => widget.control === 'text' && !widget.multiline, component: TextBox },
];
</script>

<template>
  <Viewer :engine="engine" :plugins="plugins" :initial-documents="[{ source: forms }]">
    <DocumentGate>
      <template #fallback><p class="loading">Loading…</p></template>
      <Toolbar />
      <Stage class="stage">
        <template #page>
          <RenderLayer />
          <FormLayer :controls="controls" />
        </template>
      </Stage>
    </DocumentGate>
  </Viewer>
</template>
```

**`clear-button.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;
}

/* The button at the end of a text box. It is drawn in the field's frame, at the field's
   100% size, next to the layer's own text box: the layer scales both with the page. */
.clear-button {
  position: absolute;
  top: 50%;
  right: 6px;
  width: 16px;
  height: 16px;
  margin: 0;
  padding: 0;
  transform: translateY(-50%);
  border: 0;
  border-radius: 50%;
  font: inherit;
  font-size: 13px;
  font-weight: 600;
  line-height: 16px;
  text-align: center;
  color: var(--surface);
  background: var(--muted);
  cursor: pointer;
  transition: background-color 0.15s ease;
}

.clear-button::before {
  content: '×';
}

.clear-button:hover {
  background: var(--ink);
}

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

/* 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);
}
```

**`TextBox.vue`**

```vue
<script setup lang="ts">
import { useForm } from '@embedpdf/vue/form';
import type { FieldControlProps } from '@embedpdf/vue/form';

// A text box with a button at its end that empties it. `native` is the layer's own text box:
// the field as the PDF draws it, and the editor people type in. The button is yours.
const props = defineProps<FieldControlProps>();
const form = useForm();

// Empty the box, then put the cursor back in it, ready for the new value.
const clear = () => props.setValue({ value: '' }).then(() => form.focus(props.widget.fieldRef));
</script>

<template>
  <component :is="native" />
  <!-- Tab goes to the text box. -->
  <button
    v-if="widget.control === 'text' && !widget.disabled && widget.value !== ''"
    type="button"
    class="clear-button"
    :aria-label="`Clear ${widget.label}`"
    tabindex="-1"
    @click="clear"
  />
</template>
```

**`Toolbar.vue`**

```vue
<script setup lang="ts">
import { useForm } from '@embedpdf/vue/form';
import { useStage } from '@embedpdf/vue/stage';

const form = useForm();
const stage = useStage();

const fillIn = () =>
  form.importValues({
    name: 'Ada Lovelace',
    email: 'ada@example.com',
    company: 'Lanternfield',
  });
</script>

<template>
  <div class="toolbar">
    <button type="button" class="button" @click="fillIn">Fill in</button>
    <button type="button" class="button" @click="stage.zoomIn()">Zoom in</button>
    <button type="button" class="button" @click="stage.rotateViewBy(90)">Turn the view</button>
  </div>
</template>
```

> **Try it:** press **Fill in**, or type in a text box and press Tab: a button at the end of the
> box empties it, and leaves the cursor in the box. The box is still the layer's own: it shows
> the field as the PDF draws it, you type in it, and Tab moves on to the next field, past the
> button.

What you draw in the frame zooms with the page. Open a menu or a picker from it as a card, with
[anchored UI](#show-a-calendar-next-to-a-date-field) or your own popover.

### The cursor and Tab

[Tab, `focus()` and `focusNext()`](https://www.embedpdf.com/docs/headless/vue/forms.md#move-between-fields) put the cursor in the first
element of your control that takes focus: an `<input>`, a `<button>`, or an element with
`tabindex="0"`. Give it one, and the field takes part in the form's order like any other. While the
cursor is anywhere inside your control, the field is the focused field. An element that is hidden,
disabled or inert doesn't count. A control with no element that does takes no cursor: Tab,
`focus()` and `focusNext()` pass over its field.

The layer draws its [focus ring](https://www.embedpdf.com/docs/headless/vue/forms.md#move-between-fields) on its own controls, `native`
among them. On what you draw yourself it draws none: `focused` says when to show yours.

Safari gives a pressed `<button>` no focus. The layer puts the cursor in its own controls after
a press there, `native` among them. If a press on a button of yours should make its field the
focused one too, call `focus()` on the button in its click handler.

A box that is `disabled` takes no input: draw it, and leave out what people would click.

## What a box tells you

Each box says where it is, what it holds, and whose it is. `listWidgets(page)` gives the boxes of
a page, and a control gets its box as `widget`:

| Value                     | What it is                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| :------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `control`                 | Which control it is: `'text'`, `'toggle'`, `'choice'`, `'button'`, `'signature'` or `'image'` for an [image field](https://www.embedpdf.com/docs/headless/vue/forms/building.md#image-fields)                                                                                                                                                                                                                                                                                                                                                     |
| `fieldRef`                | The field it belongs to: what `setValue()` and `get()` take                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `ref`                     | The box's own ref: what `useFormWidgetAnchor()` and `getWidget()` take                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `label`                   | Its name for screen readers: the field's tooltip, else its name, then whose field it is when its [group](https://www.embedpdf.com/docs/headless/vue/forms.md#fields-for-several-people) has a label, or "Anyone" for a field [anyone fills in](https://www.embedpdf.com/docs/headless/vue/forms.md#fields-anyone-fills-in)                                                                                                                                                                                                                        |
| `groupId`                 | The [group](https://www.embedpdf.com/docs/engine/forms/groups.md) the field is in, or `null`                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `assignment`              | Who fills the field in, as its field says: `{ kind: 'group', groupId }` for one group's signers, `{ kind: 'anyone' }` for a field [anyone fills in](https://www.embedpdf.com/docs/headless/vue/forms.md#fields-anyone-fills-in), `{ kind: 'unassigned' }` for no one in particular. `groupId` is `null` for the last two                                                                                                                                                                                                                          |
| `canFill`                 | Whether this user may fill it in, or sign it for a signature field: their permissions, and no signature [locked](https://www.embedpdf.com/docs/headless/vue/forms.md#signed-documents) the field. `fillable` and a read-only field don't change it                                                                                                                                                                                                                                                                                                |
| `yours`                   | Whether it's this user's to fill in: they may fill it in, the box takes input (`fillable` lets people, so it isn't `disabled`), and it still takes a value, so it isn't read-only, locked by a signature nor a signed signature. The layer paints only such a box: its tint, its edge and its placeholder. See [A field's look and its tint](https://www.embedpdf.com/docs/headless/vue/forms.md#a-fields-look-and-its-tint)                                                                                                                      |
| `accent`                  | Its tint, `{ color, strength }`, or `null`: its [group's](https://www.embedpdf.com/docs/headless/vue/forms.md#fields-for-several-people) color, else `fields.anyoneTintColor` for a field [anyone fills in](https://www.embedpdf.com/docs/headless/vue/forms.md#fields-anyone-fills-in), else `fields.tintColor`, as strong as `fields.tint`, while it's `yours`. A tint that is one of those two settings names it, as `setting` (`'form.fields.tintColor'`), so `fieldTintOf()` lets the setting's CSS variable win                             |
| `disabled`                | Draw it, take no input: a read-only field, one this user may not fill in, one a signature locked, one [`fillable`](https://www.embedpdf.com/docs/headless/vue/forms.md#settings) leaves out, or a value on its way                                                                                                                                                                                                                                                                                                                                |
| `required`                | The form asks for a value. The layer's own control says so with `aria-required` where its role has the state, so not on a radio button, a signature field or an image field; say it on yours. See [Screen readers](https://www.embedpdf.com/docs/headless/vue/forms.md#screen-readers)                                                                                                                                                                                                                                                            |
| `empty`                   | It holds nothing yet: no text, nothing ticked or picked, no picture, and for a signature field neither a signature nor a mark drawn in. What [`validate()`](https://www.embedpdf.com/docs/headless/vue/forms.md#check-required-fields) counts as missing                                                                                                                                                                                                                                                                                          |
| `purpose`                 | What the field is for, such as `'name'`, `'email'` or `'date-signed'`, or `null`. See [What a field is for](https://www.embedpdf.com/docs/headless/vue/forms/building.md#what-a-field-is-for)                                                                                                                                                                                                                                                                                                                                                     |
| `format`                  | The shape of its value: `{ kind: 'date', pattern }`, `{ kind: 'time', pattern }`, `{ kind: 'other' }` for a format only the PDF's script knows, or `null`. Always `null` for a box that isn't a text box or a dropdown. See [Dates](https://www.embedpdf.com/docs/headless/vue/forms.md#dates)                                                                                                                                                                                                                                                    |
| `placeholder`             | What it shows while it's empty and `yours`, or `null`: the field's own [placeholder](https://www.embedpdf.com/docs/headless/vue/forms/building.md#a-fields-placeholder), as its author wrote it, else its purpose's label, such as "Email", in the viewer's language. A text box, a dropdown, a signature field and an image field have one; a signature box with a mark drawn in it has none, nor does a box while an [armed mark's preview](https://www.embedpdf.com/docs/headless/vue/forms/signatures.md#let-people-click-to-sign) sits in it |
| `placeholderAlign`        | Where the placeholder sits across the box, where the value will: `'left'`, `'center'` or `'right'`. A text box and a dropdown align it as they align their text; a signature field and an image field centre it                                                                                                                                                                                                                                                                                                                                   |
| `hint`                    | A sentence about it, for its tooltip and screen readers (`aria-description`), or `null`. The date of signing says "Filled in when you sign" to the person whose date it is                                                                                                                                                                                                                                                                                                                                                                        |
| `box`, `rotation`, `rect` | Where it is; see [Turned fields](https://www.embedpdf.com/docs/headless/vue/forms.md#turned-fields)                                                                                                                                                                                                                                                                                                                                                                                                                                               |

Then each control has its value: a text box its `value`, a checkbox or radio button `checked` and
its `exportValue`, a dropdown or list its `options` and `selected`, a signature box `signed`, an
image box `hasImage`.

## Good to know

### Design mode

Controls fill forms in. They take input while the active tool fills forms (the `pointer` and `pan`
tools do), as the layer's own do. In [design mode](https://www.embedpdf.com/docs/headless/vue/forms/building.md#design-mode) fields are boxes people
select and move, drawn by the annotation layer, and your controls stand down with the layer's own.
Under any other tool, such as a stamp or a pen, your controls show as the layer's own do, and like
them take no input and no pointer: the layer makes their boxes `inert`, so the tool works over
them.

### A field's tint

A field shows its [tint](https://www.embedpdf.com/docs/headless/vue/forms.md#a-fields-look-and-its-tint) while it's `yours`, and an edge in
`fields.border` when it has no border of its own and no tint. Once `fields.required` has a
color, a box that is `yours`, `required` and `empty` has its edge in that color. All of it is
part of the layer's own control, so a control that keeps `native` shows them, and one that draws
the box alone doesn't.
`widget.accent` is the tint the layer would show, `{ color, strength }`, or `null`, for a look of
your own. A lent field has the same `accent` on the annotation layer in design mode.

### Placeholders

An empty field shows its own [placeholder](https://www.embedpdf.com/docs/headless/vue/forms/building.md#a-fields-placeholder), the text its author
wrote, or else the label of its [purpose](https://www.embedpdf.com/docs/headless/vue/forms/building.md#what-a-field-is-for), while it's `yours`. Its
own text is shown as written and never translated; a purpose's label is in the viewer's
language. A text box, a dropdown, a signature field and an image field show one, since a
checkbox, a radio button and a list have no room for it. Another person's field and a read-only one show none. A signature field with a mark drawn in it is filled in, before it is signed too, so it shows the mark alone. The
placeholder sits where the value will: in a text box and a dropdown, where the field aligns its
text; in a signature field and an image field, in the middle, where the mark and the picture go.
That side is a side of the screen, as the value's is: a left-aligned field shows its placeholder at
the left on a right-to-left page too, and the words read in their own direction, so a Hebrew label
reads from the right on any page.
It is part of the layer's own control, so a control that keeps `native` shows it, and one
that draws the box alone reads `widget.placeholder` and `widget.placeholderAlign` and draws its own. The
layer's text box also carries the browser's `autocomplete` for the purposes the web knows; your
own control reads `widget.purpose` for that. In design mode the placeholder shows on the field
too, so whoever builds the form sees what each field shows.

### Signature fields

An empty signature field's control is a button. A click makes the field the
[target](https://www.embedpdf.com/docs/headless/vue/forms/signatures.md#sign-here-in-a-form), where the next mark goes. Your own control for it calls
`signature.setTarget(widget.fieldRef)`, or opens your own signing UI.

### Image fields

An [image field](https://www.embedpdf.com/docs/headless/vue/forms/building.md#image-fields)'s box is `control: 'image'`: every box of a push button
that takes an image (`takesImage`). Any other push button's box is `control: 'button'`, one that
only shows a picture, such as a logo, among them. With the signature plugin,
the layer's control is a button: a press makes the field the
[target](https://www.embedpdf.com/docs/headless/vue/forms/signatures.md#sign-here-in-a-form), as a signature box's does, empty or filled, and runs no
script. Without the signature plugin the box is only its picture. Your own control for it calls
`signature.setTarget(widget.fieldRef)`, or opens your own picker and calls
`form.setButtonImage(widget.fieldRef, { source })`.

The layer offers no way to take a picture out. To let people take theirs out, give your card a
button that calls `form.setButtonImage(widget.fieldRef, null)` while `widget.hasImage` is true.

### Dropdown lists

The list a dropdown opens is the browser's own, so it opens unturned and at the browser's size. For
a list in your app's look, draw the dropdown as a control and open your list as anchored UI.

### Drawing every field yourself

A control replaces one box inside the form layer, which still places it, turns it, and moves the
cursor between fields. To draw a form without the layer, `listWidgets(page)` gives you every box
with these same values.
