# Forms

A form lives in any scene of any story, written with the same directives as the rest of Récit. It
renders as a native HTML form that works without JavaScript, and as an accessible interactive form
when JavaScript runs. Its answers go to **your** API, following the
[Form submission API](/documentation/reference/form-submission-api): Récit hosts nothing.

```md
---
title: Lorem Meetup
format: docs
lang: en
---

## Join the next meetup

:::form{#signup endpoint=https://api.example.com/v1/forms privacy=/privacy}
::field[Your name]{name=name required autocomplete=name maxlength=120}
::field[Email]{name=email type=email required autocomplete=email}
::field[Attendance]{name=mode type=radio required options="onsite=On site,remote=Remote"}
::field[Company]{name=company visible-if="mode=onsite" required-if="mode=onsite"}
::field[Message]{name=message type=textarea rows=4 maxlength=2000 help="Lorem ipsum dolor sit amet."}
::consent[I agree to be contacted about this meetup]{name=consent required version=2026-10}
::submit[Register]

:::success
Thanks, lorem ipsum.
:::

:::error
Lorem ipsum, please try again later.
:::
:::
```

## Try it

The form of `examples/form-contact`, rendered by this page from the same Markdown, its outer fence
one colon longer (see [In a site](#in-a-site)). It plays in `mock` mode: pick the API's answer above
it, nothing is sent.

::::form{#contact submit=mock antispam=honeypot privacy=/documentation/reference/form-submission-api}
::field[Your name]{name=name required autocomplete=name maxlength=120}
::field[Email]{name=email type=email required autocomplete=email}
::field[Subject]{name=topic type=select required options="question=A question,quote=A quote,other=Something else"}
::field[Company]{name=company autocomplete=organization maxlength=120 help="Only if you write for a company."}
::field[Message]{name=message type=textarea rows=5 required minlength=10 maxlength=2000}
::consent[I agree that Lorem Ipsum Studio stores this message to answer it]{name=consent required version=2026-11}
::submit[Send the message]

:::success
Thanks, lorem ipsum: your message is on its way.
:::

:::error
Lorem ipsum, the message could not be sent. Please try again later.
:::
::::

## The block

| Element                                   | Role                                                                                    |
| ----------------------------------------- | --------------------------------------------------------------------------------------- |
| `:::form{#id …}`                          | the form. `id` is required and unique in the project                                    |
| `::field[Label]{name=… type=…}`           | a field. `name` is required, structural, never translated; `type` defaults to `text`    |
| `options="value=Label,…"`                 | the choices of `select`, `radio`, `checkbox-group`; `other="Label"` adds a free choice  |
| `visible-if`, `required-if`, `enabled-if` | conditions: `name=value`, `name!=value`, `name` (filled), `!name` (empty). Nothing else |
| `help="…"`                                | a help text, linked to the field by `aria-describedby`                                  |
| `compute="a * b"`                         | a computed `number` field, read-only (see « Computed fields » below)                    |
| `::consent[Text]{name version}`           | a consent box, never pre-checked; its `version` is sent with the answer                 |
| `::submit[Label]`                         | the button; a translated default when absent                                            |
| `:::fieldset[Legend]`                     | a group of fields                                                                       |
| `:::success`, `:::error`                  | the text shown after the answer; the API's `message` replaces it                        |

Field types:

| Type                        | Sent as (JSON) | Notes                                                                                     |
| --------------------------- | -------------- | ----------------------------------------------------------------------------------------- |
| `text`, `tel`, `textarea`   | `string`       | `minlength`, `maxlength`, `pattern`, `rows` (`textarea`)                                  |
| `email`, `url`              | `string`       | checked as an email address or URL                                                        |
| `number`                    | `number`       | `min`, `max`, `step`                                                                      |
| `range`                     | `number`       | native slider (with a linked `<output>` when interactive); `min` and `max` are required, without `step` it advances by steps of `1` |
| `date`                      | `string`       | `YYYY-MM-DD`, `min` and `max` compared                                                    |
| `time`                      | `string`       | `HH:MM` (seconds optional), `min` and `max` in `HH:MM`                                    |
| `datetime-local`            | `string`       | `YYYY-MM-DDTHH:MM` (seconds optional), `min` and `max` in `YYYY-MM-DDTHH:MM`              |
| `select`, `radio`           | `string`       | `options="value=Label,..."` (`other="Label"` adds a free choice on `radio`)               |
| `checkbox`                  | `boolean`      | `true` when checked                                                                       |
| `checkbox-group`            | `string[]`     | `options="value=Label,..."` (`other="Label"` adds a free choice)                          |
| `file`                      | multipart file | `accept` and `max-size` (bytes); switches the form to `multipart/form-data`               |
| `hidden`                    | `string`       | `value=` sent without a visible control                                                   |

The HTML attributes are kept as they are: `required`, `min`, `max`, `minlength`, `maxlength`,
`pattern`, `step`, `autocomplete`, `placeholder`, `rows`, `accept`, `max-size` (bytes) and `value`
(prefilled).

Attributes of the form: `endpoint`, `contract` (`recit`, the default, `openapi`, or `formspree`, see below), `submit`
(`fetch`, `native` or `mock`), `encoding` (`form`, the default, or `json`), `method` (`POST`, the
only one), `antispam` (`honeypot`, the default, `turnstile` with `sitekey=`, or `none`), `auth`
(`none`, `publishable-key` with `key=`, or `bearer`, see below), `privacy` (a link to the privacy notice), `retention` (days the answers are kept),
`upload` (`multipart`, the default, or `presigned`, see [Files sent first](#files-sent-first)),
and `openapi` with `operation` (see below). The retention period (in days, `1` to `3650`) is shown
to the visitor near the submit button; it must match the duration kept by the backend (the
resource's `retentionDays`): the block does not check it.

`antispam=turnstile` is opt-in: it loads Cloudflare Turnstile, a third-party script that receives
the visitor's address, only for that form, so the privacy notice must name it. `sitekey=` is the
widget's public key, never its secret; the token travels as `_recit.turnstile` (or
`meta.antispam.turnstile` in JSON), and the server checks it with `siteverify` before the answers
(`createFormHandler` takes `turnstile: { secret }`). It needs `contract=recit`.

`forms` in `recit.config.ts` and `forms:` in a story's front matter set defaults for every `:::form`
(`endpoint`, `contract`, `submit`, `encoding`, `antispam`, `auth`, `publishableKey` for `key=`,
`turnstileSiteKey` for `sitekey=`, `privacy`, `retention` and `upload`): the front matter overrides the config key by key, and an attribute
written on `:::form` wins over both.

```md
---
title: Contact Lorem Ipsum
forms:
  endpoint: https://api.example.com/v1/forms
  privacy: /privacy
---

:::form{#contact}
::field[Email]{name=email type=email required autocomplete=email}
::submit[Send]
:::
```

A `:::fieldset[Legend]` groups fields under a legend; it holds at least one `::field`, never another
fieldset:

```md
:::form{#order endpoint=https://api.example.com/v1/orders privacy=/privacy}
:::fieldset[Delivery]
::field[Street]{name=street required autocomplete=street-address}
::field[City]{name=city required autocomplete=address-level2}
:::
::submit[Order]
:::
```

### Every attribute, one example each

Any attribute missing from these tables is an error, with its line.

| `:::form`   | Example                                                               |
| ----------- | --------------------------------------------------------------------- |
| `id`        | `:::form{#signup endpoint=/api/forms}`                                |
| `endpoint`  | `:::form{#signup endpoint=https://api.example.com/v1/forms}`          |
| `contract`  | `:::form{#ticket contract=openapi openapi=./api.yaml operation=createTicket}` |
| `submit`    | `:::form{#signup submit=mock}`                                        |
| `encoding`  | `:::form{#signup endpoint=/api/forms encoding=json}`                  |
| `method`    | `:::form{#signup endpoint=/api/forms method=POST}`                    |
| `antispam`  | `:::form{#signup endpoint=/api/forms antispam=none}`                  |
| `auth`      | `:::form{#signup endpoint=/api/forms auth=publishable-key key=pk_lorem}` |
| `key`       | `:::form{#signup endpoint=/api/forms auth=publishable-key key=pk_lorem}` |
| `sitekey`   | `:::form{#signup endpoint=/api/forms antispam=turnstile sitekey=0x-lorem-site-key}` (the public site key of Cloudflare Turnstile, never its secret) |
| `privacy`   | `:::form{#signup endpoint=/api/forms privacy=/privacy}`               |
| `retention` | `:::form{#review endpoint=/api/forms retention=30}`                   |
| `upload`    | `:::form{#apply endpoint=/api/forms upload=presigned}` (each file is sent first, see below) |
| `openapi`   | `:::form{#ticket openapi=./api/lorem.yaml operation=createTicket}`    |
| `operation` | `:::form{#ticket openapi=./api/lorem.yaml operation=createTicket}`    |
| `url`       | `:::form{#signup endpoint=/api/forms url=https://example.com/signup}` (the page where the form is answered online; a printed form shows its QR code and address) |

| `::field`      | Example                                                                    |
| -------------- | -------------------------------------------------------------------------- |
| `name`         | `::field[Your name]{name=name}`                                            |
| `type`         | `::field[Arrival]{name=arrival type=time min=09:00 max=18:00}`             |
| `required`     | `::field[Email]{name=email type=email required}`                           |
| `min`          | `::field[Rating]{name=rating type=range min=0 max=10}`                     |
| `max`          | `::field[Slot]{name=slot type=datetime-local max=2026-11-13T18:00}`        |
| `minlength`    | `::field[Message]{name=message type=textarea minlength=10}`                |
| `maxlength`    | `::field[Your name]{name=name maxlength=120}`                              |
| `pattern`      | `::field[Postcode]{name=postcode pattern="[0-9]{5}"}`                      |
| `step`         | `::field[Rating]{name=rating type=range min=0 max=10 step=1}`              |
| `autocomplete` | `::field[Your name]{name=name autocomplete=name}`                          |
| `placeholder`  | `::field[Website]{name=website type=url placeholder="https://example.com"}` |
| `rows`         | `::field[Message]{name=message type=textarea rows=5}`                      |
| `accept`       | `::field[Resume]{name=resume type=file accept=".pdf"}`                     |
| `max-size`     | `::field[Resume]{name=resume type=file max-size=2000000}`                  |
| `value`        | `::field[Source]{name=source type=hidden value=meetup}`                    |
| `options`      | `::field[Size]{name=size type=select options="s=Small,m=Medium,l=Large"}`  |
| `other`        | `::field[Diet]{name=diet type=checkbox-group options="veg=Vegetarian" other="Other"}` |
| `help`         | `::field[Company]{name=company help="Only if you write for a company."}`   |
| `visible-if`   | `::field[Company]{name=company visible-if="mode=onsite"}`                  |
| `required-if`  | `::field[Company]{name=company required-if="mode=onsite"}`                 |
| `enabled-if`   | `::field[Company]{name=company enabled-if="!remote"}`                      |
| `compute`      | `::field[Total]{name=total type=number step=0.01 compute="quantity * price"}` |
| `hidden`       | `::field{name=internalRef hidden}` (a field generated from OpenAPI only)   |

### Computed fields

A `number` field with `compute=` shows a value computed from other fields, as the reader types:

```md
::field[Quantity]{name=quantity type=number min=1}
::field[Unit price]{name=price type=number step=0.01}
::field[Total]{name=total type=number step=0.01 compute="quantity * price"}
```

The expression is closed: numbers, the names of `number` or `range` fields written before it
(another computed field included), `+ - * /` and parentheses. Nothing else is evaluated. Write a
subtraction with spaces (`a - b`): `a-b` is one name. The field is read-only, takes no `value=` and is never required;
it stays empty while a field it reads is empty, or on a division by zero, and is rounded to the
decimals of its `step`. The value sent for it is never trusted: the reference server
(`@recit/form/server`) recomputes it from the other answers, and checks its `min` and `max` like any
number. Without JavaScript, the field stays empty on the page and the server fills it in. On
paper, the field shows its formula with the labels it reads (« Computed: “Quantity” × “Unit price”
»), for the reader to work it out by hand.

A choice that needs one sentence of help under it is written as a `:::field` container, inside a
`::::form` (one more colon than the field): one list item per option, `value=Label` on its first
line and its description on the next lines. The label and the description may hold commas. A
container never takes `options=` as well, and a field generated from OpenAPI takes its options from
the operation's `enum`. A `radio` or a `checkbox-group` shows the description under its choice, as
the choice's accessible description (`aria-describedby`); a `select` keeps it in the definition
only, since an `<option>` holds no more than its label. The description is plain text: Markdown
emphasis or a link in it is read as its words.

```md
::::form{#signup endpoint=/api/forms}
:::field[Attendance]{name=mode type=radio required}
- onsite=On site
  At the venue, with lunch
- remote=Remote
  A video link, sent the day before
:::
::::
```

A `pattern` runs on the server for every value sent, so `recit build`, `recit dev` and `recit form`
refuse one whose matching can backtrack without bound: a repeated group whose iterations can overlap
(`(a+)+`, `([a-z]+\s?)+`, `(a|ab)*`, `(a?a)+`), a back-reference (`\1`), or three unbounded
repetitions in a row that can match the same characters (`\d+\d+\d+`, `.*a.*b.*c`). A repeated
group is accepted when it starts or ends with a separator none of its repetitions can match: write
`[a-z]+(\s[a-z]+)*` rather than `([a-z]+\s?)+`, and `[a-z0-9]+(-[a-z0-9]+)*` for a slug. The server
never runs a pattern on a value longer than its `maxlength`, or than 1,000 characters.

| `::consent` | Example                                                    |
| ----------- | ---------------------------------------------------------- |
| `name`      | `::consent[I agree to be contacted]{name=consent version=2026-10}` |
| `required`  | `::consent[I agree to be contacted]{name=consent required version=2026-10}` |
| `version`   | `::consent[I agree to be contacted]{name=consent version=2026-10}` |

`::submit[Label]` takes no attribute (`::submit[Register]`); `:::success` and `:::error` take none
either and hold the Markdown shown after the answer, as in the first example of this page.

### A field outside the block

A `::field` may be written elsewhere in the same scene, outside its `:::form`, with `form=` and the
form's id: beside a table, after a paragraph, before the form itself. It stays where it is written
and belongs to the form like any other field: the build checks it with the form's rules (its name
is unique among the form's fields, a condition may read it), and it enters the form's definition
and its published schema after the form's own fields, in the order of the scene. In the form's
definition (`/forms/<id>.json`), such a field carries `outside: true` among the form's `fields`,
never among the `fields` of a fieldset.

```md
| Lorem | Ipsum |
| ----- | ----- |
| Dolor | Sit   |

::field[Your name]{name=name form=signup required}

:::form{#signup endpoint=/api/forms}
::field[Email]{name=email type=email required}
::submit[Register]
:::
```

On the page, each of its controls carries the HTML `form` attribute, so the browser sends and
checks it with the form, without JavaScript too. In a site, the form's component draws it in its
place once the page is loaded. A `::field` outside a block without `form=`, or naming a form of
another scene, is an error with its line; inside a block, `form=` is an error, and a form whose
fields come from an OpenAPI operation takes no field from outside.

## Fields from an OpenAPI operation

When an API already describes its `requestBody` in OpenAPI, the form can take its fields from it:

```md
:::form{#ticket openapi=./api/lorem.yaml operation=createTicket privacy=/privacy}
::field[Short summary]{name=title}
::field{name=internalRef hidden}
:::
```

`openapi=` (a YAML or JSON file, relative to the story) implies `contract=openapi`; `operation=` is
the `operationId`, a `POST` without path parameter. The build reads the document (OpenAPI 3.0 or 3.1,
local `$ref` only) through a closed table:

| JSON Schema                                         | Field                                          |
| --------------------------------------------------- | ---------------------------------------------- |
| `string` with `format: email`, `uri`, `date`        | `email`, `url`, `date`                         |
| `string` with `maxLength` over 200                  | `textarea`                                     |
| `string` with `minLength`, `maxLength`, `pattern`   | `text` with the same HTML attributes           |
| `enum` (5 values or fewer, else `select`)           | `radio` or `select`                            |
| `boolean`                                           | `checkbox`                                     |
| `integer`, `number` with `minimum`, `maximum`       | `number` with `min`, `max`, `step`             |
| `array` of `enum`                                   | `checkbox-group`                               |
| `format: binary`, `contentMediaType`                | `file` (the operation must take multipart)     |
| `title`, `description`, `default`                   | label (else derived from the name), help, value |
| `x-recit-order`, `x-recit-hidden`, `x-recit-autocomplete` | order, left out, `autocomplete`          |

A nested object, `oneOf`/`anyOf` (other than with `null`), an array of objects or an external `$ref`
is an error with the line of the document, never a guess. `readOnly` properties are left out. The
`servers[0].url` and the path give the `endpoint` unless the block sets one.

A `::field{name=…}` inside the block overrides a generated field: its label, `help`,
`placeholder`, `autocomplete`, `value`, `rows` and conditions; the overridden fields come first, in
their order. `hidden` leaves a field out, or sends it as a hidden value with `value=` (a required
property needs one). An unknown `name` is an error. `recit form schema <id> --story <file>` prints
the JSON Schema of the data; `-o, --output <dir>` also writes the definition, `/forms/<id>.json`.
`recit build` writes both files under `forms/` in its output directory for each valid form it
renders.

## Sending to Formspree

`contract=formspree` sends the same block to a [Formspree](https://formspree.io) form, without its
SDK: Récit translates the body and the answers, nothing else.

```md
:::form{#contact contract=formspree endpoint=https://formspree.io/f/xyzabcd privacy=/privacy}
::field[Email]{name=email type=email required}
::field[Message]{name=message type=textarea required}
:::
```

- The body is flat, urlencoded (multipart with a file, JSON with `encoding=json`): the fields of the
  author, no `_recit.*` entry and no `Idempotency-Key`, so a urlencoded request needs no preflight.
- The honeypot travels as `_gotcha`, the one Formspree reads; a ticked consent as its version
  (`consent=2026-10`), kept with the answers.
- Formspree's errors land on their fields: `REQUIRED_FIELD_EMPTY` reads as `required`,
  `TYPE_EMAIL` as `format`, `TYPE_NUMERIC` and `TYPE_TEXT` as `type`; an error of the whole form is
  shown above it. `429` waits for `Retry-After`, as with every contract.
- `submit=native` and `key=` are refused at build: the translation needs JavaScript, and Formspree
  knows the form by its address. `submit=mock` plays Formspree's own answers.

## Files sent first

By default a file field travels in the submission itself, as `multipart/form-data`, and the API
receives the bytes. `upload=presigned` sends each file first, straight to the storage the API
chooses (an object store), so the submission stays small and can use `encoding=json`:

```md
:::form{#apply endpoint=https://api.example.com/v1/forms upload=presigned encoding=json privacy=/privacy}
::field[Name]{name=name required autocomplete=name}
::field[CV]{name=cv type=file accept=.pdf max-size=5000000 required}
::submit[Apply]
:::
```

1. For each chosen file, the form asks `<endpoint>/uploads` for a ticket (JSON: the form, the
   field, the file's name, type and size). The API checks `accept=` and `max-size=`; a refusal
   lands on the field, like any error of the answers.
2. It sends the bytes where the ticket says: `PUT` with its headers (a presigned URL), or `POST`
   with its fields then the file (a presigned policy).
3. It submits the answers with the ticket's reference as the field's value, instead of the file.

A file of a field hidden by `visible-if` is never sent. `submit=native` is refused at build (the
two steps need JavaScript), and so are `contract=openapi` and `contract=formspree`, which take their
files in multipart. `submit=mock` accepts every ticket and sends nothing. On the API side, the
reference server takes `uploads: { sign, check }` (see the
[contract](/documentation/reference/form-submission-api#files-sent-first)).

## Submission modes

- **`fetch`** (default): the form checks the answers, posts them urlencoded (multipart with a file),
  maps the API's errors onto the fields, sends once on a double click and waits for `Retry-After`.
- **`native`**: a plain HTML `<form action method="post">`, without JavaScript.
- **`mock`**: nothing leaves the page. A banner says so. For the dev server, demos and tests.

## Rules the build checks

Each problem comes with its file and line:

- **errors**: a missing or duplicate form id, a duplicate `name`, a condition on an unknown name, an
  option without a value, a `range` without `min` and `max`, a malformed `min` or `max` on `number`,
  `range`, `time` or `datetime-local`, `min` greater than `max` (`min` > `max`) on `number`,
  `range`, `date`, `time` or `datetime-local`, an unknown type or attribute, a `name` starting with
  `_recit.`, a missing `endpoint` (unless `submit=mock`), a `pattern` that can backtrack without bound, a
  `:::field` that lists its options with `options=` as well, holds anything but one list, or lists an
  option without a value, and any value that looks like a secret;
- **warnings**: a form that collects personal data (email, phone, a name) without `::consent` nor
  `privacy=` (an error in `recit build`, which then neither renders the form nor writes its files
  under `forms/`; a warning with `recit build --no-strict` and in `recit dev`), and an optional
  field without `help` ("is this field needed?").

## On paper

A form printed in a PDF (a `report` or a `book` exported with `recit export --to pdf`) keeps its
labels, help texts, empty boxes and consent, and leaves out what only works on screen: the submit
button, the Back and Next buttons, the status line and the demo banner. With `url=`, the page where the form is answered
online, the printed form ends with a QR code of that page and its address, so a reader can answer
from a phone:

```md
:::form{#signup endpoint=/api/forms url=https://example.com/signup}
::field[Your name]{name=name required autocomplete=name}
::submit[Register]
:::
```

On screen, the QR code and the address stay hidden. The QR code is drawn at build time, as a vector
in the HTML: nothing is fetched and no script runs.

Paper shows every field, so a field with `visible-if` is printed with its condition in words, above
its label, in the story's language: `visible-if="mode=onsite"` reads « Only if “Attendance” is “On
site” », the labels of the field and of its value as the reader sees them. On screen, the line
stays hidden and the script applies the condition.

## A questionnaire on paper

`recit convert survey.story.md --to report` turns a questionnaire (`format: form`) into a report
that prints it whole. The steps of prose stay sections; the fields of every step go into one
`:::form`, a `:::fieldset` per step legended by its heading, the consent and the submit last, the
completion screen as the message after sending. The `when` of a step becomes the `visible-if` of
each of its fields, so paper writes « Only if “Which best describes you?” is “Developer” » above
them. Other prose of a step with fields has no place in a form: it is left out, with a warning.
`recit export report.md --to pdf` then prints it; `-o report.json` writes the report's twin. With
`--url https://…`, the printed form ends with the QR code of the page where it is answered online.

## A questionnaire on slides

A deck is shown, not filled in. `recit convert survey.story.md --to deck --url https://…` writes a
slide per step: its heading and prose kept, its questions in words where its fields were, each label
followed by its choices (« **Which best describes you?** (Developer, Designer, Other) »), and the
condition of a step written in words under its heading. The consent and the completion screen are
left out. A last slide, « Answer online » in the story's language, holds the QR code of `--url` and
its address. Without `--url` the deck ends on the last step, with a warning; an address that is not
http(s) is an error and nothing is written. `-o deck.json` writes the deck's twin.

`--to webstory` writes the same as web story cards, a card per step; the last card also carries a
call to action to `--url`, for the reader who holds the phone. A card that says too much is reported
when the story is built (`webstory-density`, with its line).

## On a web story card

A web story card cannot be filled in: a `:::form` on a card of a `webstory` shows the QR code of its
`url=` and the address, captioned « Answer online: » in the story's language, drawn like `::qr` with
the project's `utm:`. Without `url=`, the form is an error with its line.

```md
--- id=signup

# Join the next meetup

:::form{#signup url=https://example.com/signup}
::field[Your name]{name=name required}
:::
```

## At the end of a film

A film has no field either: a `:::form` in a scene of a `format: motion` story is its end screen, the
scene's heading above the QR code of `url=` and the address, captioned « Answer online: ». The CLI
draws it like a `::chart` scene, as a still (`recit dev`, `recit render`). Without `url=`, the film
is an error with the form's line.

```md
--- id=thanks

## Join the next meetup

:::form{#signup url=https://example.com/signup}
::field[Your name]{name=name required}
:::
```

## Languages

Labels, help, options, the consent and the messages are translated in `*.fr.md` with the same `id`
and the same `name`. `recit i18n check` refuses a `name`, an option value or a consent version that
differs between languages. The messages of the form itself (required, errors, sending) come from the
`en` and `fr` packs of `@recit/form`.

## Accessibility

Labels are always visible, required fields say so in words, help and errors are linked by
`aria-describedby`, an invalid field has `aria-invalid`. After a failed attempt, a summary of the
errors with a link to each field takes the focus; the state of the submission is announced in a live
region.

## A questionnaire in steps (preview)

A story with `format: form` is one questionnaire, one scene per step. The format is a preview: its
schema ([`form.json`](https://recit.dev/schema/v1/form.json)), JSON twin, build checks and React
player (`@recit/form/steps`) are in place. `recit dev survey.story.md` plays it in the browser and
reloads it on each save; `recit build` writes a static page (`index.html` with the questionnaire and
its first step, and `assets/form.js` and `form.css`, which play the steps). `examples/form-survey`
holds this survey in English and French. In a site, the questionnaire has its own page, and
`<StoryEmbed slug="survey" format="form" />` plays it inside an MDX page.

```md
---
title: Lorem Survey
format: form
lang: en
form:
  id: survey
  endpoint: https://api.example.com/v1/forms
  contract: recit
  progress: steps
  review: true
  privacy: /privacy
---

--- id=intro

# Lorem survey

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

--- id=profile

::field[Which best describes you?]{name=role type=radio required options="dev=Developer,design=Designer,other=Other"}

--- id=tools when="role=dev"

::field[Which tools do you use?]{name=tools type=checkbox-group options="cli=CLI,ide=IDE,web=Web"}

--- id=feedback

::field[Anything else?]{name=feedback type=textarea maxlength=2000}
::consent[I agree that my answers are stored for this survey]{name=consent required version=2026-10}

--- id=thanks end

Thanks, lorem ipsum.
```

The `form:` section of the front matter (`settings.form` in the JSON twin) configures the
questionnaire:

| Key                       | Type / values              | Role                                                                                 |
| ------------------------- | -------------------------- | ------------------------------------------------------------------------------------ |
| `id`                      | `string`                   | Required. Lowercase slug of the questionnaire (`settings.form.id` in the JSON twin). |
| `endpoint`, `contract`, … | same as `forms:`           | Every default of `:::form`: the same keys as `forms:` (see [The block](#the-block)). |
| `progress`                | `steps` \| `bar` \| `none` | Progress indicator across steps (`steps` by default; `settings.form.progress` in the JSON twin). |
| `review`                  | `boolean`                  | Adds a recap step before sending (`settings.form.review` in the JSON twin).          |

Attributes on a step separator (`--- id=…`):

| Attribute | Example                        | Role                                                                                                                                           |
| --------- | ------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| `when`    | `--- id=tools when="role=dev"` | Step condition (`scenes.when` in the JSON twin), with the same closed operators as `visible-if` (`name=value`, `name!=value`, `name`, `!name`). |
| `end`     | `--- id=thanks end`            | Bare word marking the completion screen (`scenes.end` in the JSON twin), one per story.                                                        |

Rules checked today, each reported with the line of the step's separator (an error unless noted):

- more than one `end` step;
- `end` written with a value (`end=false`);
- a bare word other than `end` on a separator (`--- id=thanks done`);
- a step with no field nor text, in any of its languages;
- a `when` that is not a valid condition;
- a `when` naming an unknown field, or a field defined only in the same or a later step;
- more than five fields (`::field` and `::consent`) in a step (**warning**).

A `form:` section without `id` or with an unknown key is an error with its path
(`/settings/form/id`).

### The player

At build time, `buildFormSteps` of `@recit/form/directives` compiles a `format: form` story into a
`FormStepsDocument` (`{ document, problems }`), assembling one form across every step while turning
each step's prose into HTML; `recit dev` and `recit build` call it for you. A
field inside a step with `when` inherits that condition and cannot set its own `visible-if`.

In the browser, `<FormSteps document={document} />` of `@recit/form/steps` (styled by
`@recit/form/styles.css`) plays the document—or its serialized JSON, validated by
`FormStepsDocumentSchema` (`FormStepSchema` validates a single step)—as a single accessible form:

```tsx
import { buildFormSteps } from "@recit/form/directives";
import { FormSteps } from "@recit/form/steps";
import "@recit/form/styles.css";

const { document } = await buildFormSteps(markdown);
// Render <FormSteps document={document} /> when document is defined
```

- **Steps and progress**: shows one playable step at a time, moving focus to its heading on step
  change, and announces progress in a polite live region (`steps` text by default, a `<progress>`
  bar with `bar`, or nothing with `none`).
- **Navigation and keyboard**: **Next** validates the current step's controls before advancing,
  pressing **Enter** in a field acts as **Next**, and **Back** (hidden on the first step) returns to
  the previous step without losing answers.
- **Branches (`when`)**: steps whose `when` condition does not hold are skipped, and their fields
  are neither required nor sent (`@recit/form/steps` also exports `liveValues` to drop answers from
  steps whose `when` is false, alongside `playableSteps`, `endStep` and `stepProgress`).
- **Errors across steps**: on a failed submission, `FormSteps` opens the first step with an error,
  and each link in the error summary moves to the step holding that field and focuses its control
  (via `Form`'s optional `onErrorLink` prop, `(name: string) => boolean`: when it returns `true`,
  `Form` leaves focus to the caller).
- **Review and end screen**: with `review: true`, a recap step before submission lists each shown
  answer alongside a **Change** button that jumps back to its step; after a successful submission,
  the `end` step replaces the form (or `Form`'s success message stays when there is no `end` step).
  There is no draft saving and no timer.

## In JSON

### Form definition

The compiled definition written to `/forms/<id>.json` (`FormBlockSchema` of `@recit/core/schema`) is
validated by [`form-block.json`](https://recit.dev/schema/v1/form-block.json). Alongside the form
attributes (`id`, `endpoint`, `contract`, `submit`, `encoding`, `antispam`, `auth`, `publishableKey`
for `key=`, `privacy`, `retention`, `upload`, `method`, `openapi`, `operation` and `url`), it carries:

| Key                | Type / values                                              | Role                                                                                                                                   |
| ------------------ | ---------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| `fields`           | `FormItem[]`                                               | Required. Ordered items of the form: each item is a field (`fields.name` required) or a fieldset (`fields.legend` + `fields.fields`).  |
| `fields.type`      | `string`                                                   | One of the 16 field types above (`"text"` when absent).                                                                                |
| `fields.label`     | `string` or `Record<string, string>`                       | Visible label of the field (omitted only on `hidden`). `fields.help` and `fields.placeholder` take the same localized shape.           |
| `fields.required`  | `boolean`                                                  | Marks the field required unconditionally.                                                                                              |
| `fields.minlength` | `integer` (`>= 0`)                                         | Minimum character length; `fields.maxlength` (`>= 1`), `fields.min`, `fields.max`, `fields.pattern`, `fields.step`, `fields.rows`, `fields.autocomplete` and `fields.value` mirror the HTML attributes. |
| `fields.maxlength` | `integer` (`>= 1`)                                         | Maximum character length.                                                                                                              |
| `fields.accept`    | `string`                                                   | Accepted MIME types or extensions on `type: "file"`.                                                                                   |
| `fields.maxSize`   | `integer` (`> 0`)                                          | Largest file in bytes on `type: "file"` (`max-size` in Markdown).                                                                      |
| `fields.options`   | `Array<{ value, label, description? }>`                    | Choices of `select`, `radio` and `checkbox-group`: structural `options.value`, localized `options.label` and optional localized `options.description` (the lines under an option of a `:::field` list, shown under the choice of a `radio` or `checkbox-group`). |
| `fields.other`     | `string` or `Record<string, string>`                       | Adds a free-text choice with this label on `radio` or `checkbox-group`.                                                                |
| `fields.visibleIf` | `string`                                                   | Condition (`name=value`, `name!=value`, `name`, `!name`) from `visible-if`; `fields.requiredIf` and `fields.enabledIf` match `required-if` and `enabled-if`. |
| `fields.compute`   | `string`                                                   | On `type: "number"`: the closed expression of a computed field (`compute=` in Markdown), recomputed by the server. |
| `fields.legend`    | `string` or `Record<string, string>`                       | Required on a `:::fieldset` item: legend of the group.                                                                                 |
| `fields.fields`    | `Field[]` (non-empty)                                      | Required on a `:::fieldset` item: nested fields (`fields.fields.*`), each taking the exact same `FieldSchema` keys as a top-level field, never another fieldset. |
| `consent`          | `{ name, label, required?, version }`                      | Optional `::consent` box: structural `consent.name`, localized `consent.label`, optional `consent.required` (`boolean`) and `consent.version`. |
| `submitLabel`      | `string` or `Record<string, string>`                       | Optional button label from `::submit[Label]` (a translated default when absent); `success` and `error` hold the localized `:::success` and `:::error` Markdown. |

### The docs JSON twin

In a `format: docs` story's JSON twin (`DocsSourceSchema`, validated by
[`docs.json`](https://recit.dev/schema/v1/docs.json)), the `:::form` directive stays in the scene's
Markdown body while front matter defaults and page navigation map to typed keys:

| Key             | Type / values                                 | Role                                                                                                                 |
| --------------- | --------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- |
| `settings.forms` | `object`                                     | Optional `forms:` defaults from the front matter (`endpoint`, `contract`, `submit`, `encoding`, `antispam`, `auth`, `publishableKey`, `privacy`, `retention`, `upload`). |
| `scenes.body`   | `string` or `Record<string, string>`          | Optional Markdown or MDX content of the page, including `:::form` blocks ([Scenes](/documentation/writing/scenes)).  |
| `scenes.notes`  | `string` or `Record<string, string>`          | Optional author notes (`:::notes`).                                                                                  |
| `scenes.sidebar` | `boolean` or `{ label?, order? }`            | Sidebar entry of the page (`--- sidebar=false`), or an object with localized `sidebar.label` (`sidebar_label=`) and numeric `sidebar.order` (`sidebar_order=`); `scenes.id`, `scenes.title` and `scenes.attrs` follow [Scenes](/documentation/writing/scenes#in-the-json-twin). |

## In a site

A site renders the block in its pages, `.md` and `.mdx`, with nothing to wire: `@recit/site` runs
the remark plugin of `@recit/form` on every page, in the site's language (`metadata.lang`), and
draws each form with the `Form` of `@recit/form` and its stylesheet. A broken form fails the build
with its file and line.

To draw the forms with a component of your own (a demo that never posts, for instance), map
`RecitForm` in the site's config:

```ts
export default defineConfig({
  mdx: { components: { RecitForm: MyForm } },
});
```

A form with `auth=bearer` needs the token of the person signed in to the site. `@recit/form` never
reads a session: the site gives it, by mapping `RecitForm` to the `Form` with a `token` provider,
asked at each submission:

```tsx
import { Form, type FormProps } from "@recit/form";

const SignedForm = (props: FormProps) => (
  <Form {...props} token={() => mySession.accessToken()} />
);

export default defineConfig({
  mdx: { components: { RecitForm: SignedForm } },
});
```

A session kept in an `HttpOnly` cookie has no token to give: the form then posts to an API of the
same site, which reads its cookie and checks the session in `verifyBearer`'s place.

Only the React `Form` sends the token. A `Form` given no `token` sends no header, and the API answers
`401` to every submission; the static HTML element of a form has no provider at all, so an
`auth=bearer` form needs the site's `RecitForm` mapped as above.

A site that still lists `remarkForm` in `build.remarkPlugins` keeps working: the block is already
converted when its plugin runs.

In an MDX page, a container inside the form (`:::fieldset`, `:::success`, `:::error`) closes on
the first `:::`, the form's included: open the form with one colon more, `::::form{…}`, and close it
with `::::`, as the demo of this page does. A story compiled by `recit build` needs no extra colon:
it pairs the fences itself.

A story compiled by `recit build` renders the native form through the `form` directive handler of
`@recit/form/directives`.
