# Forms

Where a page's form posts go, how the page builder checks them, and how a plugin offers its own forms through a form provider.

Every form on a page builder site posts to one route of the page builder. The route checks
the post, finds the form on the published page, and hands the answers to the form's
provider. This is experimental: the route's fields and the provider contract may change
before the page builder is stable.

## The Form block

A Form works with JavaScript off. A visitor fills it in and presses the button; the browser
posts the answers to the page builder, and comes back to the same page with the answer in
place of the form, or a message above it. The block adds no script to the page.

### Picking a form from the Forms plugin

With the Forms plugin installed (or another plugin that offers forms), the Form block's first
setting is **Form**: pick one of the site's forms from the list. A draft form is marked
"(Draft)" and a closed one "(Closed)". Once a form is picked, the panel says "Fields, emails,
spam protection and saved responses come from Forms.", and **Edit this form ↗** opens the
form in the admin, in a new tab. The block's own fields, its button and **Send to** are put
away while a form is picked; **or use a simple form** brings them back as they were.

The canvas draws a picked form as a visitor will see it once it's published, read with your
own access, so you see a draft form too. Over the block it says:

* "Draft form: visitors can't send it until it's published", over a draft;
* "This form is closed. Visitors see its closed message.", with **Pick another form**, over a
  closed form;
* "This form was deleted.", with **Pick another form**, where the form is gone or you can no
  longer read it. The live page shows nothing there.

Without a forms plugin, the block edits its own fields, as below, with the hint "Want saved
responses, emails and spam protection? Install the Forms plugin. This block will then let
you pick a form."

### The block's own fields

A new Form starts with **Name** and **Email**, both required, then **Message**, and a
**Send** button. In the block's **Fields**, **+ Add field** adds a field, the handle beside
each one drags it into a new order (or moves it with the arrow keys), and opening a field
edits its label, its type and **Required**. The types are Text, Email, Phone, Number, Link,
Date, Long text, Dropdown, Checkbox and Choice; a Dropdown and a Choice take a list of
options.

Each field's answer is sent under a name made from its label ("Your email" is sent as
`your-email`), unique within the form. Set your own under the field's **Advanced** options.

Required fields carry a visible `*` and say "required" to a screen reader, and the form says
"\* Required" once above its fields. The browser refuses an empty required field, a
malformed email or a link that isn't one with its own message, before anything is sent, and
the server checks the same rules again.

In the **After sending** section, **Then** chooses what a visitor sees once a send is accepted:

* **Show a message**: the form is replaced by the message, "Thanks, we got your message."
  unless you write another. The message takes the keyboard and screen reader focus.
* **Go to a page**: the visitor is sent to a page of the site, or to an address you write.

A simple form sends its answers to the address in **Send to**. While that's empty, the canvas
says "Answers have nowhere to go yet: add an address, or install the Forms plugin to save
them", and the page's checks list it under Content and data as "Form answers have nowhere to
go", opening **Send to** when you pick it.

When the server refuses a send, the visitor comes back to the form with one message above
it: "Some answers weren't accepted. Please check them and send again.", "This form isn't
taking answers right now." or "Something went wrong. Please try again."

The page stays cacheable: nothing in its HTML depends on a send. The block draws each
message hidden, with an id the route's answer names in the address's fragment
(`#form-<id>-sent`, `-invalid`, `-closed`, `-error`), and a CSS `:target` rule shows the one
named. A browser without `:has()` shows the sent message above the fields rather than in
their place.

### Known limits

* The receiver's address assumes Nextly's handler is mounted at `/admin/api`, as a
  scaffolded project mounts it, under the app's `basePath` where it has one.
* A plain form post through the page builder carries no file. A provider's form with a file
  field says "This form needs JavaScript to send a file." beside the field, and the route
  refuses a post to it with that sentence rather than sending it on without the file.

## The receiving route

Forms post to `POST <api mount>/plugins/@nextlyhq/plugin-page-builder/forms/send`, which is
`/admin/api/plugins/@nextlyhq/plugin-page-builder/forms/send` in a scaffolded project. It is
public: a visitor sending a form is signed in to nothing. The post is an ordinary HTML form
post (`application/x-www-form-urlencoded`, or `multipart/form-data`), so it works with no
JavaScript.

Beside the visitor's answers, a post carries these hidden fields:

| Field     | What it holds                                                                                                                                                                                                                                                          |
| --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `_form`   | The document that defines the form: `page:<id>`, `template:<id>`, `component:<id>`, `layout:<id>:<area>` for the component a header & footer set places in an area, or `entry:<collection>:<id>` for a collection's entry drawn by its design, its own blocks included |
| `_node`   | The form block's id in that document                                                                                                                                                                                                                                   |
| `_return` | The path to come back to, such as `/contact`                                                                                                                                                                                                                           |
| `_item`   | For a form repeated in a collection list, the item's position from 0, after those of the lists around it (`0-3`)                                                                                                                                                       |
| `_locale` | The page's language, when the site has several                                                                                                                                                                                                                         |
| `_hp`     | The spam trap. The Form block draws it hidden; a person leaves it empty                                                                                                                                                                                                |

The route answers with a `303` back to `_return`, with the outcome in the fragment:
`#form-<id>-sent`, `#form-<id>-invalid`, `#form-<id>-closed` or `#form-<id>-error`. A form
repeated in a list adds its `_item` to the id (`#form-<id>-<item>-sent`), so the message
shows in the copy that was sent. A field name starting with `_` is the route's own: a
provider's form naming a field with one is not drawn.

## What the route checks

In this order, each before the work it guards:

1. A browser post that another site's page sent (`Sec-Fetch-Site: cross-site`) is refused.
2. A post over 64 KB, or with more than 200 fields, is refused before it is read further.
3. A post with the spam trap filled is answered exactly as a success, and goes no further:
   nothing is read, counted, sent on or stored.
4. Each visitor address may send 10 posts a minute. The count is kept in the deployment's
   shared limit store (`rateLimit.store`), so every instance counts the same posts. Where
   the address can't be read (`security.trustProxy` is off), every visitor shares one
   allowance.
5. The form is read from the **published** document `_form` names, by `_node`. A form only
   a draft holds, a node that isn't a form, or a document that isn't published is refused.
   The fields, the address answers go to and the message shown all come from the stored
   form, never from the post.
6. Only the fields the form has are passed on; any other name is dropped.
7. `_return` is used only when it is a path of the same site. Anything else, such as
   `//elsewhere.example` or `https://elsewhere.example/`, sends the visitor to the site's root.

## A simple form

A Form block with no form picked from a provider is a simple form. Its answers are checked
against the block's own fields, read from the same description its controls are drawn
from, with the rules a browser applies (required fields, an email, a full web address, a
number, a date, a time, a Dropdown's or a Choice's options). Then the site's server posts
them, as `application/x-www-form-urlencoded`, to the block's "Send to" address. The
visitor's browser never posts there itself, and nothing is stored.

Once sent, a simple form shows its message, or sends the visitor to the page its "Go to a
page" names. A page of the site is followed to where the site serves it now; an address is
followed as written.

"Send to" must be an `https` address of a public host. It is checked when each post is
sent on, against every address its host resolves to, so private, loopback and link-local
addresses are refused. Redirects are not followed, and the send gives up after 10 seconds.
A refused or failed send is the `-error` outcome. The answers are never logged; a failed
send is logged with its outcome and the address's host only.

## Offering forms from a plugin

A plugin with forms of its own offers them as a **form provider**. The page builder draws
the provider's forms with the Form block's own markup and styles, and hands the provider
every post to one of its forms. Everything about the forms stays in the provider: which
exist, how answers are checked, stored and emailed, and any spam checks of its own.

The types come from `@nextlyhq/plugin-sdk/blocks`. Register the provider from your plugin's
`init`, through the page builder's `forms` service:

```ts
import { definePlugin } from "@nextlyhq/plugin-sdk";
import type {
  FormProvider,
  FormProviderService,
} from "@nextlyhq/plugin-sdk/blocks";

const provider: FormProvider = {
  id: "acme-forms",
  label: "Acme forms",
  // The forms an author may pick, read with the author's own rights.
  list: async () => [{ ref: "contact", title: "Contact", state: "published" }],
  // One form, as the public sees it on the live page.
  describe: async ref =>
    ref === "contact"
      ? {
          ref,
          title: "Contact",
          fields: [
            { name: "email", label: "Email", kind: "email", required: true },
          ],
          submitText: "Send",
          afterSending: {
            kind: "message",
            message: "Thanks, we got your message.",
          },
          encoding: "urlencoded",
        }
      : { unavailable: "missing" },
  // One post, already trimmed to the fields `describe` gave.
  accept: async (_ref, post) =>
    post.answers.get("email")?.[0]
      ? { kind: "sent" }
      : {
          kind: "invalid",
          issues: [{ field: "email", message: "Enter an email." }],
        },
};

export const acmeForms = definePlugin({
  name: "@acme/forms",
  version: "1.0.0",
  nextly: "*",
  init: ctx => {
    const forms = ctx.services.plugins["@nextlyhq/plugin-page-builder"]
      ?.forms as FormProviderService | undefined;
    // Without the page builder there is nowhere to offer forms.
    forms?.register(provider);
  },
});
```

In the builder, `list` fills the Form block's **Form** list, read as the signed-in author,
and `label` is the name in "Fields … come from Forms.". Give each listing an `editHref` (the
form's page in the admin) for **Edit this form ↗**. The canvas reads a picked form through
`describe` as the author, so a draft is drawn too, and through `describe` as the public to
learn whether visitors would find it closed.

`id` is stored in every block that picks one of the provider's forms, so keep it stable.
It is 1 to 64 lower case letters, digits and dashes; `simple` is the page builder's own.
Registering an id that is already registered stops the site from starting.

When a post arrives, the page builder asks `describe` for the form as the public sees it.
A form that is `closed` answers with the `-closed` outcome and a `missing` one with
`-error`, and `accept` is not called. Otherwise `accept` gets the answers to the described
fields and the visitor's request, for the provider's own limits and checks. The page
builder's own spam trap and per-address limit have already run.

### How a provider's form is drawn

The Form block draws a provider's form on the server, from what `describe` gives, with the
same markup and style parts as a simple form, so the block's Style settings apply to both.
Each described field is drawn as its `kind`'s HTML control, with its label, help,
placeholder, options, `accept`, `min`, `max` and `pattern`. A field's `provider` values are
drawn as `data-*` attributes on its control, for the provider's own script; the page
builder never reads them. A form whose `encoding` is `multipart` posts as
`multipart/form-data`.

Each control's `aria-describedby` names its help and an empty, hidden error slot
(`[data-nx-form-error]`) under it. A provider's own script that sends without a reload can
write the reason a field was refused there and show it; the visitor's answers stay as typed.

A described `script` is added, as a module, only to pages that draw that form, once however
many of its forms a page holds. A closed form shows its own message (or "This form isn't
taking answers right now.") in its place; a missing one draws nothing.

**Then** (in After sending) on a block with a provider's form starts as **Use the form's own setting**,
which follows `afterSending`. The block may choose a message or a page of its own instead.

`accept` answers with one of:

* `{ kind: "sent" }`, optionally with `afterSending: { kind: "page", href }` to send the
  visitor to another page of the site;
* `{ kind: "invalid", issues }`;
* `{ kind: "closed" }`;
* `{ kind: "failed" }`. A provider that throws is treated the same way.
