# Form

> Form validation with @salmonui/inputs/form - one rule vocabulary with the Data Grid, native constraint validation, server errors and React 19 actions.

Canonical: https://salmonui.dev/docs/inputs/form

Form validation is declarative: rules live on each
field's `validation` prop (or native constraint attributes), and `Form`
renders a native `<form>` that validates its fields on submit.
There is no validator instance.

```tsx
import { useActionState } from 'react';
import { Form } from '@salmonui/inputs/form';
import { TextField } from '@salmonui/inputs/text-field';
import '@salmonui/inputs/form/styles.css';

const [state, action] = useActionState(saveUser, { errors: {} });

<Form action={action} validationErrors={state.errors}>
  <TextField name="email" label="Email" validation={{ required: true, email: true }} />
  <button type="submit">Save</button>
</Form>
```

### Live demo: Form validation

Live demo: https://salmonui.dev/demos/inputs/form-validation

Field rules in the Data Grid vocabulary, native constraints, an equalTo rule, an async rule and a blocked submit that focuses the first invalid field.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { Form } from '@salmonui/inputs/form';
import { TextField } from '@salmonui/inputs/text-field';

const taken = async (value: unknown): Promise<string | null> => {
  await new Promise((resolve) => setTimeout(resolve, 300));
  return value === 'admin' ? 'This user name is taken.' : null;
};

// Rules from the Data Grid vocabulary, native constraints, an equalTo rule,
// an async rule and the submit outcome.
export default function FormValidationDemo() {
  const [result, setResult] = useState('');
  return (
    <Form
      style={{ display: 'grid', gap: 12, maxWidth: 360 }}
      onSubmit={(event) => {
        event.preventDefault();
        setResult(JSON.stringify(Object.fromEntries(new FormData(event.currentTarget))));
      }}
      onValidate={({ valid }) => !valid && setResult('Fix the highlighted fields.')}
    >
      <TextField name="user" label="User name" description="Try “admin”" validation={{ required: true, minLength: 3, validate: taken }} />
      <TextField name="email" label="Email" type="email" required />
      <TextField name="password" label="Password" type="password" validation={{ required: true, minLength: 8 }} />
      <TextField name="confirm" label="Confirm password" type="password" validation={{ validate: [(value, ctx) => value === ctx.formData?.get('password'), 'The passwords do not match.'] }} />
      <div style={{ display: 'flex', gap: 8 }}>
        <Button type="submit" tone="primary">Create account</Button>
        <Button type="reset" variant="outline" onClick={() => setResult('')}>
          Reset
        </Button>
      </div>
      <output>{result}</output>
    </Form>
  );
}
```

## Rules

`validation` takes the Data Grid `column.validation` vocabulary, compiled by
the same `compileValidationRules` from `@salmonui/core/validation`:
`required`, `min`, `max`, `range`, `minLength`,
`maxLength`, `rangeLength`, `number`, `digits`, `email`, `url`, `date`,
`dateIso`, `creditcard`, `tel`, `pattern` (a regular expression; a partial
match passes, so anchor it) and `validate`. Built-in rules are synchronous
and allocate nothing on success (well under 0.05 ms per field per
keystroke).

- Messages: `[argument, message]` per rule, `validation.messages`, then
  `localeText` keys shared with the Data Grid (`validationRequired`,
  `validationMin`, ...).
- Custom rules: `validate(value, ctx)` returns a message, `null` / `true`
  (valid) or `false` (the `validate` message); `[fn, message]` or an array
  of functions; promises are allowed. `ctx` is `{ name, formData,
  isNew: false }`, so a "must equal" rule is
  `validate: [(v, ctx) => v === ctx.formData?.get('password'), 'Passwords differ']`.
- Changing a field's `validation` prop replaces its rules. Inline objects keep their compiled
  form while they are shallow-equal.
- Native attributes (`required`, `minLength`, `maxLength`, `min`, `max`,
  `step`, `pattern`, `type`) are honored and reported with the same messages.

### Live demo: Validation rules and events

Live demo: https://salmonui.dev/demos/inputs/form-rules

Form validation with per-rule, validation.messages and localeText messages, native HTML constraints read as rules, rules swapped at runtime, error text from a function, onBeforeValidate and onValidate, and the native reportValidity and requestSubmit entry points.

`Demo.tsx`:

```tsx
'use client';

import { useRef, useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { Form, type FieldValidation } from '@salmonui/inputs/form';
import { TextField } from '@salmonui/inputs/text-field';
import { EventLog, useEventLog } from '../../components/demo-kit';

const PHONE_RULES: FieldValidation = { required: [true, 'A phone number is required for courier delivery.'], tel: true };
const NO_RULES: FieldValidation = {};

// Custom and localized messages, native HTML constraints read as rules,
// rules swapped at runtime, error text from a function, the validation
// events and the native reportValidity() / requestSubmit() entry points.
export default function FormRulesDemo() {
  const form = useRef<HTMLFormElement>(null);
  const phone = useRef<HTMLInputElement>(null);
  const [courier, setCourier] = useState(false);
  const [skip, setSkip] = useState(false);
  const [log, push] = useEventLog(12);
  return (
    <>
      <div className="demo-toolbar">
        <Checkbox checked={courier} onCheckedChange={(checked) => setCourier(checked)}>
          Courier delivery (adds phone rules)
        </Checkbox>
        <Checkbox checked={skip} onCheckedChange={(checked) => setSkip(checked)}>
          Skip client validation (onBeforeValidate)
        </Checkbox>
      </div>
      <Form
        ref={form}
        aria-label="Shipping address"
        style={{ display: 'grid', gap: 16 }}
        onBeforeValidate={(event) => {
          if (skip) event.preventDefault();
          push(`onBeforeValidate${skip ? ': preventDefault()' : ''}`);
        }}
        onValidate={({ valid, errors }) => push(`onValidate valid=${valid} ${JSON.stringify(errors)}`)}
        onSubmit={(event) => {
          event.preventDefault();
          push('onSubmit: submitted');
        }}
        onReset={() => push('reset: errors cleared')}
      >
        <div style={{ display: 'grid', gap: 12, maxInlineSize: 400 }}>
          <TextField
            name="recipient"
            label="Recipient"
            validation={{ required: true, minLength: [3, 'Use at least {0} characters, as on the label.'] }}
            localeText={{ validationRequired: 'Who receives the parcel?' }}
            description="Per-rule message for minLength; localeText for required"
          />
          <TextField
            name="street"
            label="Street"
            validation={{ required: true, maxLength: 30, messages: { maxLength: 'Street lines hold {0} characters at most.' } }}
            description="validation.messages overrides the maxLength text"
          />
          <TextField
            name="zip"
            label="ZIP code"
            required
            pattern="[0-9]{5}"
            minLength={5}
            maxLength={5}
            inputMode="numeric"
            errorMessage={({ errors }) => `ZIP: ${errors.join(' ')} Use five digits, for example 94103.`}
            description="Native required, pattern, minLength and maxLength; the error text comes from a function"
          />
          <TextField name="site" label="Website" type="url" description='Native type="url": type "example" and blur' />
          <TextField ref={phone} name="phone" label="Phone" type="tel" validation={courier ? PHONE_RULES : NO_RULES} description={courier ? 'Required for the courier' : 'Optional'} />
        </div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
          <Button type="submit" tone="primary">Submit</Button>
          <Button type="button" variant="outline" onClick={() => push(`form.reportValidity(): ${String(form.current?.reportValidity())}`)}>
            form.reportValidity()
          </Button>
          <Button type="button" variant="outline" onClick={() => push(`phone.reportValidity(): ${String(phone.current?.reportValidity())}`)}>
            phone.reportValidity()
          </Button>
          <Button type="button" variant="outline" onClick={() => form.current?.requestSubmit()}>
            form.requestSubmit()
          </Button>
          <Button type="reset" variant="outline">
            Reset
          </Button>
        </div>
      </Form>
      <EventLog entries={log} label="Validation events" />
    </>
  );
}
```

### Live demo: One rule engine for forms and grids

Live demo: https://salmonui.dev/demos/inputs/form-shared-rules

The same validation rule object on a Form field and a Data Grid column, compiled by the same compileValidationRules, and a timing of the built-in rules showing the per-keystroke cost and the shared empty result on success.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { compileValidationRules, NO_ERRORS } from '@salmonui/core/validation';
import { Button } from '@salmonui/buttons/button';
import { DataGrid, type DataGridColumn } from '@salmonui/data-grid';
import { Form, type FieldValidation } from '@salmonui/inputs/form';
import { TextField } from '@salmonui/inputs/text-field';

interface Product {
  readonly id: number;
  readonly sku: string;
  readonly name: string;
}

// One rule object, used by a form field and by a Data Grid column.
const SKU_RULES = { required: true, pattern: ['^[A-Z]{3}-\\d{3}$', 'Use three capitals, a dash and three digits (ABC-123).'] } as const satisfies FieldValidation;

const products: Product[] = [
  { id: 1, sku: 'TEA-101', name: 'Green tea' },
  { id: 2, sku: 'COF-202', name: 'Espresso beans' },
  { id: 3, sku: 'MUG-303', name: 'Travel mug' },
];

const columns: DataGridColumn<Product>[] = [
  { field: 'id', header: 'Id', primaryKey: true, width: 70 },
  { field: 'sku', header: 'SKU', width: 140, validation: SKU_RULES },
  { field: 'name', header: 'Name', width: 180 },
];

const RUNS = 200_000;

/** Times the compiled built-in rules the way a field runs them on each keystroke. */
function benchmark(value: string): string {
  const validator = compileValidationRules(SKU_RULES);
  let shared = 0;
  const start = performance.now();
  for (let i = 0; i < RUNS; i++) if (validator.validate(value, null) === NO_ERRORS) shared++;
  const ms = performance.now() - start;
  const perCall = (ms * 1000) / RUNS;
  return `${RUNS.toLocaleString('en-US')} checks of ${JSON.stringify(value)}: ${perCall.toFixed(3)} µs each; ${shared.toLocaleString('en-US')} returned the shared empty NO_ERRORS array (no allocation)`;
}

// the same rules and the same compiled validator in a
// Form field and a Data Grid column, and the per-keystroke cost of the rules.
export default function FormSharedRulesDemo() {
  const [results, setResults] = useState<readonly string[]>([]);
  return (
    <div style={{ display: 'grid', gap: 16 }}>
      <Form aria-label="New product" style={{ maxInlineSize: 320 }} onSubmit={(event) => event.preventDefault()}>
        <TextField name="sku" label="SKU" validation={SKU_RULES} validateOn="change" defaultValue="tea-1" description="Same rules as the grid's SKU column" />
      </Form>
      <DataGrid<Product> aria-label="Products with SKU rules" data={products} columns={columns} resizeMode="auto" height="auto" virtualization={false} locale="en-US" editing={{ mode: 'row', confirmDiscard: false, guardUnsaved: false }} />
      <div className="demo-toolbar" style={{ marginBlockEnd: 0 }}>
        <Button type="button" variant="outline" onClick={() => setResults([benchmark('ABC-123'), benchmark('abc')])}>
          Time the rules
        </Button>
      </div>
      <pre className="demo-log" style={{ marginBlockStart: 0 }} aria-label="Rule timing">
        {results.length === 0 ? '(press "Time the rules")' : results.join('\n')}
      </pre>
    </div>
  );
}
```

## When errors show

`validateOn` (on `Form` or per field): `'blur'` (default) shows errors after
the first blur or a submit attempt, the `:user-invalid` model, and then
updates them on every change; `'change'` shows them while typing;
`'submit'` waits for a submit attempt. Each keystroke re-runs only
its own field's rules and re-renders that field only when its shown errors
change.

Results are written to the native input with `setCustomValidity`, so
`form.reportValidity()`, `requestSubmit()`, `input.reportValidity()` and
`:invalid` agree with what Salmon shows.

## Submitting

- `validationBehavior: 'native'` (default) blocks an invalid submit and
  focuses the first invalid field in document order; `'aria'` marks the fields and lets the submit proceed, for
  server-validated forms.
- Async rules show `data-validating` on the field; a submit waits for them
  and then submits again or focuses the first error.
- `onBeforeValidate(event)` runs before client validation;
  `event.preventDefault()` skips it for that submit. `onValidate({ valid,
  errors })` reports the outcome keyed by field name.
- `validationErrors` (server errors keyed by `name`, for example from
  `useActionState`) show as field errors until the field's value changes;
they survive the automatic reset React performs after an
  action.
- React 19 `action`, `useFormStatus` and `useActionState` work unchanged;
with a server action the form also submits before hydration.
- A native reset restores every uncontrolled field and clears shown errors.

### Live demo: Server errors and actions

Live demo: https://salmonui.dev/demos/inputs/form-server-errors

A Form driven by a React 19 action and useActionState - server errors shown as field errors until the value changes, blocking or non-blocking client validation, and a submit button reading useFormStatus.

`Demo.tsx`:

```tsx
'use client';

import { useActionState, useState } from 'react';
import { useFormStatus } from 'react-dom';
import { Button } from '@salmonui/buttons/button';
import { Form } from '@salmonui/inputs/form';
import { Select } from '@salmonui/dropdowns/select';
import { TextField } from '@salmonui/inputs/text-field';

interface SaveState {
  readonly errors: Record<string, string>;
  readonly message: string;
  /** The submitted values: React resets an action form after the action, so the fields remount with them. */
  readonly values: { readonly handle: string; readonly email: string };
  readonly attempt: number;
}

const BEHAVIORS = [
  { value: 'native', label: 'native (block an invalid submit)' },
  { value: 'aria', label: 'aria (mark fields, submit anyway)' },
];

const TAKEN = new Set(['ada', 'grace', 'admin']);
const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

/** Stands in for a server action: it answers after a delay with errors keyed by field name. */
async function saveProfile(previous: SaveState, formData: FormData): Promise<SaveState> {
  await wait(900);
  const values = { handle: String(formData.get('handle') ?? ''), email: String(formData.get('email') ?? '') };
  const handle = values.handle.trim().toLowerCase();
  const email = values.email.trim();
  const attempt = previous.attempt + 1;
  const errors: Record<string, string> = {};
  if (TAKEN.has(handle)) errors.handle = `The server says “${handle}” is taken.`;
  if (email.endsWith('@example.com')) errors.email = 'The server rejects example.com addresses.';
  if (handle === '') errors.handle = 'The server needs a handle.';
  return Object.keys(errors).length > 0 ? { errors, message: 'The server returned errors.', values, attempt } : { errors: {}, message: `Saved @${handle}.`, values, attempt };
}

/** Reads the pending state of the enclosing form through React 19 useFormStatus. */
function SubmitButton() {
  const { pending } = useFormStatus();
  return (
    <Button type="submit" tone="primary" disabled={pending} aria-busy={pending} style={{ justifySelf: 'start' }}>
      {pending ? 'Saving…' : 'Save profile'}
    </Button>
  );
}

// Server errors from a React 19 action shown as field errors, blocking
// (native) or non-blocking (aria) client validation, and useFormStatus.
export default function FormServerErrorsDemo() {
  const [state, action] = useActionState(saveProfile, { errors: {}, message: 'Try the handle “ada” or an @example.com address.', values: { handle: '', email: '' }, attempt: 0 });
  const [behavior, setBehavior] = useState<'native' | 'aria'>('native');
  return (
    <>
      <div className="demo-toolbar">
        <label>
          validationBehavior
          <Select aria-label="validationBehavior" data={BEHAVIORS} value={behavior} onValueChange={(value) => value != null && setBehavior(value as 'native' | 'aria')} />
        </label>
      </div>
      <Form action={action} validationErrors={state.errors} validationBehavior={behavior} aria-label="Profile" style={{ display: 'grid', gap: 12, maxInlineSize: 380 }}>
        <TextField key={`handle-${state.attempt}`} defaultValue={state.values.handle} name="handle" label="Handle" validation={{ required: true, minLength: 2 }} startAdornment="@" />
        <TextField key={`email-${state.attempt}`} defaultValue={state.values.email} name="email" label="Email" type="email" validation={{ required: true, email: true }} />
        <SubmitButton />
      </Form>
      <p className="demo-status" role="status">
        {state.message}
      </p>
    </>
  );
}
```

### Live demo: Fields in a form

Live demo: https://salmonui.dev/demos/inputs/field-forms

Uncontrolled text, masked, number, radio, checkbox, switch, range slider, rating and signature fields in a native form - names and values submitted through FormData, a required incomplete mask blocking the submit, and a form reset restoring every default.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { Form } from '@salmonui/inputs/form';
import { MaskedField } from '@salmonui/inputs/masked-field';
import { NumberField } from '@salmonui/inputs/number-field';
import { Radio, RadioGroup } from '@salmonui/inputs/radio-group';
import { Rating } from '@salmonui/inputs/rating';
import { Select } from '@salmonui/dropdowns/select';
import { SignaturePad } from '@salmonui/inputs/signature-pad';
import { Slider } from '@salmonui/inputs/slider';
import { Switch } from '@salmonui/inputs/switch';
import { TextField } from '@salmonui/inputs/text-field';

/** One line per FormData entry; long data URLs are shortened. */
function entriesOf(form: HTMLFormElement): string[] {
  return Array.from(new FormData(form), ([key, value]) => {
    const text = typeof value === 'string' ? value : `File ${value.name}`;
    return `${key} = ${text.length > 48 ? `${text.slice(0, 40)}… (${text.length} chars)` : JSON.stringify(text)}`;
  });
}

// Every field is uncontrolled inside a native form: names submit through
// FormData (custom-drawn controls through native or hidden inputs) and the
// Reset button restores each defaultValue and clears the shown errors.
export default function FieldFormsDemo() {
  const [submitValue, setSubmitValue] = useState<'raw' | 'masked'>('raw');
  const [entries, setEntries] = useState<readonly string[]>([]);
  const [status, setStatus] = useState('Change some fields, then submit or reset.');
  return (
    <>
      <div className="demo-toolbar">
        <label>
          MaskedField submitValue
          <Select aria-label="MaskedField submitValue" data={['raw', 'masked']} value={submitValue} onValueChange={(value) => value != null && setSubmitValue(value as 'raw' | 'masked')} />
        </label>
      </div>
      <Form
        aria-label="Delivery preferences"
        style={{ display: 'grid', gap: 16, maxInlineSize: 420 }}
        onSubmit={(event) => {
          event.preventDefault();
          setEntries(entriesOf(event.currentTarget));
          setStatus('Submitted: the FormData entries are listed below.');
        }}
        onValidate={({ valid }) => !valid && setStatus('Not submitted: fix the highlighted field.')}
        onReset={() => {
          setEntries([]);
          setStatus('Reset: every field is back to its defaultValue.');
        }}
      >
        <TextField name="name" label="Name" defaultValue="Ada Lovelace" required />
        <MaskedField name="phone" label="Phone" mask="(000) 000-0000" defaultValue="5551234567" required submitValue={submitValue} description="Required: an incomplete number blocks the submit" />
        <NumberField name="parcels" label="Parcels" defaultValue={2} min={1} max={9} />
        <RadioGroup name="slot" label="Delivery slot" defaultValue="am" orientation="horizontal">
          <Radio value="am">Morning</Radio>
          <Radio value="pm">Afternoon</Radio>
        </RadioGroup>
        <Checkbox name="extras" value="gift-wrap" defaultChecked>
          Gift wrap
        </Checkbox>
        <Switch name="notify" value="sms">
          Text me when it ships
        </Switch>
        <Slider name="window" label="Delivery window (hours)" defaultValue={[9, 17]} min={6} max={22} ticks={{ placement: 'after', majorStep: 4 }} />
        <Rating name="priority" label="Priority" defaultValue={2} count={3} />
        <SignaturePad name="signature" label="Signature" description="Optional: submitted as a PNG data URL" height={120} backgroundColor="#ffffff" />
        <div style={{ display: 'flex', gap: 8 }}>
          <Button type="submit" tone="primary">
            Submit
          </Button>
          <Button type="reset" variant="outline">
            Reset
          </Button>
        </div>
      </Form>
      <p className="demo-status" role="status">
        {status}
      </p>
      <pre className="demo-log" aria-label="Submitted FormData">
        {entries.length === 0 ? '(nothing submitted yet)' : entries.join('\n')}
      </pre>
    </>
  );
}
```

## Required marks

`requiredMark` on `Form` puts a decorative asterisk before the label of
every field inside whose control is required (`required` or
`aria-required`), including `Select` and `Combobox` labels:

```tsx
<Form requiredMark>
  <TextField name="customer" label="Customer" required />
  <Select name="status" label="Status" required data={statuses} />
  <TextField name="note" label="Note" />
</Form>
```

- The mark is CSS only (`@salmonui/inputs/form/styles.css`): a `::before`
  with empty alternative text in the danger text color, at the inline
  start of the label (so it moves to the right under `dir="rtl"`). It is
  never announced; screen readers hear "required" once, from the control.
- `Field requiredMark` marks one custom field; `requiredMark={false}`
  opts a field out under a marking `Form`. The rule follows the control's
  `required` state live, so a field that becomes optional loses the mark.
- Any element with `data-required-mark="true"` (a `<fieldset>`, a
  section of a page) marks the fields inside it the same way.

## Unsaved changes: useFormState

`useFormState()` from `@salmonui/inputs/form/state` tracks whether a form
differs from its initial values. It works with the native `FormData`
model: no field is controlled or registered, and the initial values are
the fields' `defaultValue`s.

```tsx
import { Form } from '@salmonui/inputs/form';
import { useFormState } from '@salmonui/inputs/form/state';

function OrderEditor({ order, onClose }) {
  const form = useFormState();
  const confirm = useConfirm();
  const requestClose = async () => {
    if (form.isDirty && !(await confirm({ title: 'Discard unsaved changes?', tone: 'danger', confirmLabel: 'Discard', cancelLabel: 'Keep editing' }))) return;
    onClose();
  };
  return (
    <Drawer open title="Edit order" onOpenChange={(open) => open || void requestClose()}>
      <Form ref={form.ref} requiredMark onSubmit={save}>
        <Drawer.Body>
          <TextField name="customer" label="Customer" required defaultValue={order.customer} />
        </Drawer.Body>
        <Drawer.Footer>
          {form.isDirty ? (
            <>
              <Button variant="outline" onClick={form.reset}>Discard</Button>
              <Button type="submit">Save</Button>
            </>
          ) : (
            <Button variant="outline" onClick={requestClose}>Close</Button>
          )}
        </Drawer.Footer>
      </Form>
    </Drawer>
  );
}
```

- `ref`: attach to the form (`<Form ref={form.ref}>` or a plain
  `<form ref>`). When the form mounts, its `FormData` is the snapshot of
  initial values; a form that mounts again (a drawer opened again, a `key`
  change after a save) takes a new snapshot and starts clean.
- `isDirty`, `dirtyFields` (the names that differ, in form order) and
  `isFieldDirty(name)`. A field is dirty when its submitted values differ
  from the snapshot, so changing a value back makes it clean again; an
  unchecked checkbox and a disabled field submit nothing, so checking one
  or enabling a field with a value makes it dirty. Files compare by name,
  size and date.
- `reset()` calls `form.reset()`: native controls and every Salmon field
  return to their `defaultValue`, shown errors clear, and the state is
  clean. A controlled field whose value the parent holds stays dirty until
  the parent resets it.
- The hook listens to `input` and `change` events on the form and observes
  its controls, so the hidden inputs and options of custom-drawn fields
  (Select, NumberField, ColorPicker, ...) count too. One `FormData` read
  per change; the form's fields do not re-render, only the component that
  calls the hook, and only when the set of dirty names changes.
- Fields outside the `<form>` element (a `form="id"` attribute) are not
  tracked. On the server the state is clean.
- Its own subpath, so `@salmonui/inputs/form` does not grow for apps that
  do not use it.

### Live demo: Edit drawer with unsaved changes

Live demo: https://salmonui.dev/demos/inputs/form-state-drawer

An order editor in a Drawer built on useFormState - Save and Discard appear only while the form is dirty, closing a dirty form asks through useConfirm, required labels carry a mark, and statuses show as status dot badges.

`Demo.tsx`:

```tsx
'use client';

import { useState, type SubmitEvent } from 'react';
import { Button } from '@salmonui/buttons/button';
import { Select } from '@salmonui/dropdowns/select';
import { Form } from '@salmonui/inputs/form';
import { useFormState } from '@salmonui/inputs/form/state';
import { TextArea, TextField } from '@salmonui/inputs/text-field';
import { Badge, type BadgeTone } from '@salmonui/notifications/badge';
import { DialogProvider, useConfirm } from '@salmonui/overlays/dialog';
import { Drawer } from '@salmonui/overlays/drawer';

interface Order {
  readonly id: string;
  readonly customer: string;
  readonly email: string;
  readonly status: string;
  readonly owner: string;
  readonly note: string;
}

const STATUSES: { value: string; label: string; tone: BadgeTone }[] = [
  { value: 'pending', label: 'Pending', tone: 'primary' },
  { value: 'paid', label: 'Paid', tone: 'success' },
  { value: 'refunded', label: 'Refunded', tone: 'neutral' },
  { value: 'failed', label: 'Payment failed', tone: 'danger' },
];
const OWNERS = ['Olivia', 'Liam', 'Noah', 'Emma'];
const INITIAL: Order[] = [
  { id: 'ORD-1042', customer: 'Ada Lovelace', email: 'ada@example.com', status: 'paid', owner: 'Olivia', note: '' },
  { id: 'ORD-1043', customer: 'Grace Hopper', email: 'grace@example.com', status: 'pending', owner: 'Liam', note: 'Call before shipping.' },
];
const cell = { padding: '8px 12px', borderBlockEnd: '1px solid var(--salmon-border-subtle)', textAlign: 'start' } as const;
const field = { inlineSize: '100%' } as const;

// The editor drawer: Save / Discard only while dirty, Close otherwise; closing a dirty form asks first.
function OrderEditor({ order, onClose, onSave }: { order: Order; onClose: () => void; onSave: (order: Order) => void }) {
  const form = useFormState();
  const confirm = useConfirm();
  const [saving, setSaving] = useState(false);

  const requestClose = async (): Promise<void> => {
    if (saving) return;
    if (form.isDirty) {
      const discard = await confirm({
        title: 'Discard unsaved changes?',
        description: 'Your changes to this order have not been saved and will be lost.',
        tone: 'danger',
        confirmLabel: 'Discard',
        cancelLabel: 'Keep editing',
      });
      if (!discard) return;
    }
    onClose();
  };

  const save = (event: SubmitEvent<HTMLFormElement>): void => {
    event.preventDefault();
    const data = new FormData(event.currentTarget);
    setSaving(true);
    // A pretend request; the drawer closes once it is saved.
    setTimeout(() => {
      onSave({ ...order, customer: String(data.get('customer')), email: String(data.get('email')), status: String(data.get('status')), owner: String(data.get('owner')), note: String(data.get('note')) });
      setSaving(false);
    }, 600);
  };

  return (
    <Drawer
      open
      side="end"
      size="min(440px, 100vw)"
      title={`Edit ${order.id}`}
      closeButton
      onOpenChange={(open) => {
        // Escape, the backdrop and the close button ask before a dirty form closes.
        if (!open) void requestClose();
      }}
    >
      <Form ref={form.ref} requiredMark onSubmit={save} style={{ display: 'contents' }}>
        <Drawer.Body>
          <div style={{ display: 'grid', gap: 16 }}>
            <TextField name="customer" label="Customer" required defaultValue={order.customer} style={field} />
            <TextField name="email" label="Email" type="email" required defaultValue={order.email} style={field} />
            <Select name="status" label="Status" required data={STATUSES} defaultValue={order.status} style={field} />
            <Select name="owner" label="Owner" description="Who follows up with the customer." data={OWNERS} defaultValue={order.owner} style={field} />
            <TextArea name="note" label="Note" defaultValue={order.note} rows={3} style={field} />
            <p style={{ margin: 0, color: 'var(--salmon-text-secondary)', fontSize: 13 }} aria-live="polite">
              {form.isDirty ? `Changed: ${form.dirtyFields.join(', ')}` : 'No changes'}
            </p>
          </div>
        </Drawer.Body>
        <Drawer.Footer>
          {form.isDirty ? (
            <>
              <Button variant="outline" onClick={form.reset} disabled={saving}>
                Discard
              </Button>
              <Button type="submit" tone="primary" loading={saving}>
                Save
              </Button>
            </>
          ) : (
            <Button variant="outline" onClick={() => void requestClose()}>
              Close
            </Button>
          )}
        </Drawer.Footer>
      </Form>
    </Drawer>
  );
}

export default function FormStateDrawerDemo() {
  const [orders, setOrders] = useState(INITIAL);
  const [editing, setEditing] = useState<string | null>(null);
  const order = orders.find((o) => o.id === editing);
  return (
    <DialogProvider>
      <table style={{ borderCollapse: 'collapse', fontSize: 14, inlineSize: '100%', maxInlineSize: 560 }}>
        <thead>
          <tr>
            <th style={cell}>Order</th>
            <th style={cell}>Customer</th>
            <th style={cell}>Status</th>
            <th style={cell}>
              <span className="salmon-visually-hidden">Actions</span>
            </th>
          </tr>
        </thead>
        <tbody>
          {orders.map((o) => {
            const status = STATUSES.find((s) => s.value === o.status);
            return (
              <tr key={o.id}>
                <td style={cell}>{o.id}</td>
                <td style={cell}>{o.customer}</td>
                <td style={cell}>
                  <Badge variant="dot" tone={status?.tone}>
                    {status?.label}
                  </Badge>
                </td>
                <td style={{ ...cell, textAlign: 'end' }}>
                  <Button size="sm" variant="outline" aria-label={`Edit ${o.id}`} onClick={() => setEditing(o.id)}>
                    Edit
                  </Button>
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
      {order ? <OrderEditor key={order.id} order={order} onClose={() => setEditing(null)} onSave={(next) => (setOrders((list) => list.map((o) => (o.id === next.id ? next : o))), setEditing(null))} /> : null}
    </DialogProvider>
  );
}
```

## Performance

Every Inputs subpath has a gating JavaScript and stylesheet row in
`npm run bundle:check`. A keystroke re-renders only the edited field, and
dragging a Slider or drawing a signature causes no React render.

### Live demo: Inputs render cost

Live demo: https://salmonui.dev/demos/inputs/inputs-performance

Render counters around text, number and masked fields show that typing re-renders only the edited field, a Slider drag and a signature stroke run without React renders, and the QueryBuilder subpath loads as its own chunk only when used.

`Demo.tsx`:

```tsx
'use client';

import { lazy, Suspense, useLayoutEffect, useRef, useState, type ReactNode } from 'react';
import { Button } from '@salmonui/buttons/button';
import { MaskedField } from '@salmonui/inputs/masked-field';
import { NumberField } from '@salmonui/inputs/number-field';
import { SignaturePad } from '@salmonui/inputs/signature-pad';
import { Slider } from '@salmonui/inputs/slider';
import { TextField } from '@salmonui/inputs/text-field';

const QueryBuilderPanel = lazy(() => import('./QueryBuilderPanel'));

/**
 * Counts the commits of the component that renders it. The count is written
 * to the DOM from a layout effect, so counting never causes a render.
 */
function RenderCount({ label }: { label: string }) {
  const count = useRef(0);
  const out = useRef<HTMLSpanElement>(null);
  useLayoutEffect(() => {
    count.current += 1;
    if (out.current) out.current.textContent = String(count.current);
  });
  return (
    <span className="demo-badge" aria-label={`${label} renders`}>
      {label} renders: <span ref={out}>0</span>
    </span>
  );
}

/** One field and the render count of the component around it. */
function Cell({ label, children }: { label: string; children: ReactNode }) {
  return (
    <div style={{ display: 'grid', gap: 4 }}>
      {children}
      <RenderCount label={label} />
    </div>
  );
}

/** A controlled field: its owner re-renders per keystroke, nothing else does. */
function ControlledCell() {
  const [value, setValue] = useState('');
  const typedAt = useRef(0);
  const out = useRef<HTMLOutputElement>(null);
  useLayoutEffect(() => {
    if (typedAt.current && out.current) out.current.textContent = `last keystroke: ${(performance.now() - typedAt.current).toFixed(2)} ms from the input event to the commit`;
  });
  return (
    <Cell label="Controlled owner">
      <TextField
        label="Controlled text"
        value={value}
        onValueChange={setValue}
        onKeyDown={() => {
          typedAt.current = performance.now();
        }}
      />
      <output ref={out}>last keystroke: (type to measure)</output>
    </Cell>
  );
}

// typing re-renders only the edited field, dragging writes CSS
// or canvas without React renders, and a subpath loads only when used.
export default function InputsPerformanceDemo() {
  const sliderRenders = useRef(0);
  const moves = useRef(0);
  const strokes = useRef(0);
  const dragOut = useRef<HTMLOutputElement>(null);
  const [showBuilder, setShowBuilder] = useState(false);
  const report = () => {
    if (dragOut.current) dragOut.current.textContent = `pointer moves: ${moves.current}, Slider renders: ${sliderRenders.current}, SignaturePad value changes: ${strokes.current}`;
  };
  return (
    <div style={{ display: 'grid', gap: 20, maxInlineSize: 460 }}>
      <RenderCount label="Demo (parent)" />
      <Cell label="Text owner">
        <TextField label="Uncontrolled text" />
      </Cell>
      <Cell label="Number owner">
        <NumberField label="Uncontrolled number" defaultValue={10} />
      </Cell>
      <Cell label="Masked owner">
        <MaskedField label="Uncontrolled card" mask="0000 0000 0000 0000" />
      </Cell>
      <ControlledCell />
      <div
        style={{ display: 'grid', gap: 16 }}
        onPointerMove={(event) => {
          if (event.buttons === 0) return;
          moves.current += 1;
          report();
        }}
        onPointerUp={report}
      >
        <Slider
          label="Uncontrolled slider"
          defaultValue={50}
          fill
          valueLabel={{ show: 'always' }}
          ticks={{ placement: 'after', majorStep: 25 }}
          renderTick={(tick) => {
            // Instrumentation only: renderTick runs during the Slider's render, once per tick.
            if (tick.value === 0) sliderRenders.current += 1;
            return tick.label;
          }}
        />
        <SignaturePad
          label="Uncontrolled signature"
          style={{ maxInlineSize: 'none' }}
          height={120}
          backgroundColor="#ffffff"
          onValueChange={() => {
            strokes.current += 1;
            report();
          }}
        />
        <output ref={dragOut}>pointer moves: 0, Slider renders: 0, SignaturePad value changes: 0</output>
      </div>
      <div style={{ display: 'grid', gap: 8 }}>
        {showBuilder ? (
          <Suspense fallback={<p className="demo-status">Loading @salmonui/query-builder…</p>}>
            <QueryBuilderPanel />
          </Suspense>
        ) : (
          <Button type="button" variant="outline" onClick={() => setShowBuilder(true)} style={{ justifySelf: 'start' }}>
            Load the QueryBuilder subpath
          </Button>
        )}
      </div>
    </div>
  );
}
```

`QueryBuilderPanel.tsx`:

```tsx
'use client';

import { QueryBuilder, type QueryField } from '@salmonui/query-builder';

const fields: QueryField[] = [
  { field: 'country', label: 'Country' },
  { field: 'total', label: 'Order total', type: 'number' },
];

/** Loaded with a dynamic import: the QueryBuilder subpath arrives as its own chunk. */
export default function QueryBuilderPanel() {
  return <QueryBuilder aria-label="Orders filter" fields={fields} defaultValue={{ logic: 'and', filters: [{ field: 'country', operator: 'equal', value: 'Japan' }] }} />;
}
```

## Error placement

Every field renders its error below the control with the id its
`aria-errormessage` points at; `errorMessage` replaces the text or receives
`{ errors }`. For a custom layout, render `FieldError` yourself in
a [`Field`](https://salmonui.dev/docs/inputs/field) with `errorPlacement="manual"`.

## SSR

`Form` renders a native `<form noValidate>` with the same markup on the
server and the client. Before hydration a submit is a plain native submit
(a server action still runs); the Salmon rules run once the page is
hydrated.

## Design notes

- there are no state class options; state classes would
  duplicate ARIA state, so state is `[data-invalid]` and
  `[aria-invalid="true"]`. Style invalid fields with `[data-invalid]`.
- there is no skip list; a class-based skip list couples markup
  and validation. Fields without rules are not validated and disabled
  fields are skipped natively. Omit `validation` or set `disabled`.
- there is no method that looks an input up by name; the platform
  already does. Use `form.elements.namedItem(name)` or a `ref`.

## API

| `Form` prop | Type | Default |
| --- | --- | --- |
| `validationBehavior` | `'native' \| 'aria'` | `'native'` |
| `validateOn` | `'blur' \| 'change' \| 'submit'` | `'blur'` |
| `validationErrors` | `Record<string, string \| string[]>` | |
| `onBeforeValidate` | `(event: { form, preventDefault() }) => void` | |
| `onValidate` | `({ valid, errors }) => void` | |
| `requiredMark` | `boolean` | `false` |
| `action`, `onSubmit`, `onReset`, native form props | | |

`ref` is the `<form>`. Salmon sets `noValidate` so the browser's own bubbles
stay off; pass `noValidate={false}` to get them back.

`Field`, `FieldError`, `FieldDescription` and the shared field props are
documented on [Field](https://salmonui.dev/docs/inputs/field). Full signatures:
[`@salmonui/inputs/form` API reference](https://salmonui.dev/docs/reference/inputs/form).
