# Form dialog

A form behind a button: fields, steps, one error line and one row of actions, and the sheets built on it.

Live variants: https://design.arcadia.is/components/form-dialog

```tsx
import {
  FormDialog, FormField, FormStep, FormError, FeedbackDialog, ReportDialog,
  reportNextLine,
} from "@arcadia/ui";
```

Edit the username from its settings row.

```tsx
import { useEffect, useState } from "react";
import {
  Button, FilterDrawer, FilterDrawerOption, FilterDrawerSection, FormDialog,
  FormError, FormField, IconButton, Input, Overlay, SettingsGroup, SettingsRow,
} from "@arcadia/ui";

function Username({ initial }: { initial?: "open" | "invalid" | "taken" } = {}) {
  const [name, setName] = useState("ada");
  const [open, setOpen] = useState(false);
  const [draft, setDraft] = useState(initial === "invalid" ? "ad" : initial === "taken" ? "taken" : name);
  useEffect(() => { if (initial) setOpen(true); }, [initial]);
  const save = async () => {
    if (draft.trim() === "taken") throw new FormError("That username is taken", { field: "username" });
    setName(draft.trim());
  };
  return (
    <SettingsGroup>
      <SettingsRow label="Username" value={name}
        control={<Button size="sm" variant="secondary" onClick={() => { setDraft(name); setOpen(true); }}>Edit</Button>} />
      <FormDialog open={open} onOpenChange={setOpen} title="Change username" submitLabel="Save" onSubmit={save}>
        <FormField name="username" label="Username" rule={draft.trim().length < 3 ? "Use at least 3 characters" : null}>
          <Input name="username" autoComplete="username" value={draft} onChange={(e) => setDraft(e.target.value)} />
        </FormField>
      </FormDialog>
    </SettingsGroup>
  );
}

const OverlayStyles = stylex.create({
  ground: { "--overlay-bg": palette["--bg-elevated"] },
  layout: { display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: space["--space-4"], height: "100%" },
  bar: { position: "absolute", insetBlockStart: space["--space-3"], insetInlineEnd: space["--space-3"] },
  words: { ...stylex.env.text("title-3"), color: palette["--text-1"] },
});

export function Opening({ initiallyOpen = false }: { initiallyOpen?: boolean } = {}) {
  const [open, setOpen] = useState(false);
  useEffect(() => { if (initiallyOpen) setOpen(true); }, [initiallyOpen]);
  return (
    <>
      <Button variant="secondary" onClick={() => setOpen(true)}>Open the layer</Button>
      {open && (
        <Overlay label="A layer over the window" onClose={() => setOpen(false)} rootStyle={OverlayStyles.ground}>
          <div {...sx("cmp-overlay-layout", OverlayStyles.layout)}>
            <span {...sx("cmp-overlay-words", OverlayStyles.words)}>The page behind is inert</span>
            <Button variant="secondary" onClick={() => setOpen(false)}>Done</Button>
          </div>
          <span {...sx("cmp-overlay-bar", OverlayStyles.bar)}><IconButton icon="x" label="Close" size="md" onClick={() => setOpen(false)} /></span>
        </Overlay>
      )}
    </>
  );
}

const FILTER_GROUPS = [
  { label: "Holder", options: [["hana", "Hana", 4], ["omar", "Omar", 2], ["agent", "An agent", 3]] },
  { label: "Priority", options: [["urgent", "Urgent", 1], ["high", "High", 3], ["medium", "Medium", 5], ["low", "Low", 2]] },
  { label: "Label", options: [["bug", "Bug", 4], ["design", "Design", 2], ["docs", "Docs", 1]] },
] as const;

export function Filters({ initiallyOpen = false, selected = ["high"], unavailable = false }: { initiallyOpen?: boolean; selected?: readonly string[]; unavailable?: boolean } = {}) {
  const [open, setOpen] = useState(false);
  const [on, setOn] = useState<ReadonlySet<string>>(() => new Set(selected));
  useEffect(() => { if (initiallyOpen) setOpen(true); }, [initiallyOpen]);
  const toggle = (id: string, next: boolean) => setOn((s) => { const n = new Set(s); if (next) n.add(id); else n.delete(id); return n; });
  return (
    <>
      <Button variant="secondary" icon="filter" aria-haspopup="dialog" onClick={() => setOpen(true)}>{on.size === 0 ? "Filters" : on.size === 1 ? "1 filter" : `${on.size} filters`}</Button>
      <FilterDrawer open={open} onOpenChange={setOpen} onClear={() => setOn(new Set())} clearable={on.size > 0}>
        {FILTER_GROUPS.map((g) => (
          <FilterDrawerSection key={g.label} label={g.label}>
            {g.options.map(([id, label, count]) => (
              <FilterDrawerOption key={id} label={label} end={count} checked={on.has(id)} disabled={unavailable && id === "agent"} onCheckedChange={(next) => toggle(id, next)} />
            ))}
          </FilterDrawerSection>
        ))}
      </FilterDrawer>
    </>
  );
}
```

```tsx
import { useState, useRef } from "react";
import {
  Button, FormDialog, FormField, Input, SegmentedControl,
} from "@arcadia/ui";

function Focus() {
  const [open, setOpen] = useState(false);
  const [board, setBoard] = useState("design");
  const [card, setCard] = useState<{ title: string; board: string } | null>(null);
  const [draft, setDraft] = useState("");
  const titleField = useRef<HTMLInputElement>(null);
  const opener = useRef<HTMLButtonElement>(null);
  const add = () => setCard({ title: draft.trim() || "Untitled card", board });
  return (
    <div {...sx("cmp-form", cmp.form)}>
      <div {...sx("cmp-bar", cmp.bar)}>
        <Button ref={opener} variant="secondary" onClick={() => { setBoard(card?.board ?? "design"); setOpen(true); }}>New card</Button>
        <span {...sx("cmp-detail", cmp.detail)} role="status">{card ? card.title + " in " + (card.board === "design" ? "Design" : "Build") : "No card created"}</span>
      </div>
      <FormDialog open={open} onOpenChange={setOpen} title="New card" submitLabel="Create card"
        initialFocus={titleField} finalFocus={opener}
        onOpenChangeComplete={(now) => { if (!now) setDraft(""); }}
        onSubmit={add}>
        <FormField name="board" label="Board">
          <SegmentedControl aria-label="Board" value={board} onValueChange={setBoard}
            items={[{ value: "design", label: "Design" }, { value: "build", label: "Build" }]} />
        </FormField>
        <FormField name="title" label="Title">
          <Input ref={titleField} name="title" placeholder="What needs doing"
            value={draft} onChange={(e) => setDraft(e.target.value)} />
        </FormField>
      </FormDialog>
    </div>
  );
}
```

## Feedback

Try sending feedback, or type offline to see a failure.

```tsx
<FeedbackDialog open={open} onOpenChange={setOpen} onSend={(report) => api.feedback(report)} />
```

## Report

Report the file to see what happens next.

```tsx
<ReportDialog open={open} onOpenChange={setOpen} kinds={["copyright", "illegal", "other"]} onSend={(report) => api.report(itemId, report)} />
```

## Accessibility

Focus goes to the first field on open (`initialFocus` names another), and back to the button that opened it on close (`finalFocus` names another). Tab runs the fields, then Cancel or Back, then the primary. An error is announced, and the field it names is marked invalid. While a submit is in flight, Escape and a press outside wait for it. Under 480px the footer's buttons take a line each, the primary first; under reduced motion a step changes with a fade.

- Enter: Continues, or submits on the last step
- Esc: Closes and discards what was typed
- Tab: Fields, then Cancel or Back, then the primary

## API reference

### FormDialog

- `open` (`boolean`, required)
- `onOpenChange` (`(open: boolean) => void`, required)
- `onOpenChangeComplete` (`(open: boolean) => void`): Called after it has opened or closed, once its motion ends.
- `title` (`ReactNode`, required)
- `description` (`ReactNode`): The consequence of the action, when there is one. A FormStep's own description replaces it on that step.
- `size` (`"md" | "lg"`, default `"md"`): `lg` 480px.
- `submitLabel` (`string`, required): The primary's label on the last step ("Change password").
- `tone` (`"neutral" | "danger"`, default `"neutral"`)
- `onSubmit` (`() => Promise<A> | A`, required): Resolves on success (the dialog closes; the caller toasts in three words or fewer). Rejects with a FormError to show its message, on a field and step when it names them; any other rejection is the form's message, or the primary's action ("Couldn't save.") when it says nothing. Its resolved value is what `sentTitle` shows.
- `instant` (`boolean`): It was opened from the keyboard (a row of a menu by Enter): it is there in one frame.
- `sentLabel` (`string`): Once the send resolves, this word stands in the primary's seat and the dialog closes by itself (Feedback's "Sent").
- `sentTitle` (`ReactNode`): Once the send resolves, the dialog stays open on what it answered, under this title, with Done: the receipt.
- `renderSent` (`(answer: A) => ReactNode`): How the answer reads on the receipt: one line of what happens next.
- `canSubmit` (`boolean`, default `true`): The primary is enabled when true. Never false for a form that is not yet valid: its fields' `rule`s hold the submit and say what to fix (K30).
- `initialFocus` (`ComponentProps<typeof DialogContent>["initialFocus"]`): Where focus goes on open: an element, `false` to stay, or a function of how it opened. Default: the form's first field.
- `finalFocus` (`ComponentProps<typeof DialogContent>["finalFocus"]`): Where focus goes on close. Default: wherever it was before it opened.
- `name` (`string`): The form's name, rendered as `data-form` on the dialog: what a test or a product rule finds it by.
- `container` (`PortalContainer`): Where a surface's portal mounts. Default: `document.body`. Pass a themed subtree to keep its `data-theme`, or a transformed stage to contain `position: fixed` overlays (previews): a modal set down in one stays in it, shown in place, out of the browser's top layer.
- `aside` (`ReactNode`)
- `submitProps` (`ButtonMarks`): The product's own marks on the primary while it submits (on a form in steps, the last step's): its `data-*` only.
- `cancelProps` (`ButtonMarks`): The product's own marks on Cancel: its `data-*` only.
- `children` (`ReactNode`, required): Fields (FormField + Input), or FormStep children for a form in steps.

### FormField

- `name` (`string`, required): The `name` of the input inside: a FormError names it, and its rule is checked when it is left.
- `rule` (`string | null`): The message while the value breaks a rule ("At least 12 characters"), else null. Shown once the field is left holding something, and on a submit, which waits until every rule of its step is met; never on an empty field before a submit, and never while the first characters are typed.
- `label` (`ReactNode`)
- `hint` (`string`): Why or how, for a field its label cannot explain: a `Hint` after the label, and the control's description. At most 160 characters.
- `description` (`ReactNode`): Help text under the label (text-3, Caption).
- `action` (`ReactNode`): One control at the end of the error line, for an override its message allows ("Save anyway"): it shows with the error, never without one, and moves under the message when the line is narrow.
- `invalid` (`boolean`)
- `disabled` (`boolean`): Disables the control and dims the label.
- `rootStyle` (`RootStyle`): Typed StyleX override: where the field sits.

Rest props go to `<div>` props.

### FormStep

- `nextLabel` (`string`): The primary's label on this step (default "Continue"; the last step's is the dialog's `submitLabel`).
- `canContinue` (`boolean`, default `true`): The primary is enabled when true. Never false for a step that is not yet valid: its fields' `rule`s hold it on Continue and say what to fix (K30).
- `onContinue` (`() => void | Promise<void>`): A check before the next step: throw a FormError to stay with a message. Nothing is sent by default.
- `description` (`ReactNode`): The dialog's description while this step shows (the consequence of the last step belongs on it).

### FeedbackDialog

- `open` (`boolean`, required)
- `onOpenChange` (`(open: boolean) => void`, required)
- `onSend` (`(report: FeedbackReport) => Promise<void> | void`, required): Sends the report. Resolves once it is sent: "Sent" stands where Send stood, then the sheet closes and forgets the report. Rejects to say why: with a `FormError` its message, under the field when it names `text`; with anything else, "Not sent. Try again." The report stays as it was written.
- `instant` (`boolean`): It was opened from the keyboard (a menu's row by Enter): it is there in one frame.
- `finalFocus` (`FocusTarget`): Where focus goes when it closes. Default: wherever it was before it opened.
- `container` (`PortalContainer`): Where a surface's portal mounts. Default: `document.body`. Pass a themed subtree to keep its `data-theme`, or a transformed stage to contain `position: fixed` overlays (previews): a modal set down in one stays in it, shown in place, out of the browser's top layer.

### ReportDialog

- `open` (`boolean`, required)
- `onOpenChange` (`(open: boolean) => void`, required)
- `onSend` (`(report: ReportSubmission) => Promise<ReportReceipt | void> | ReportReceipt | void`, required): Sends the report. Resolves once recorded, and the sheet switches to one line of what happens next until closed: with `{ hidden: true }`, where the product's server hid the item on this report, the line says it is hidden; with `{ hidden: false }` or nothing, it says when the report is looked at and claims nothing hidden. Rejects to explain why: a `FormError` naming a field puts the message beside it; anything else shows above the footer and keeps what was entered.
- `kinds` (`readonly K[]`): The reasons this item can be reported for, by their values in `REPORT_KINDS`, in the order the sheet shows them. Left out: all six. With one there is nothing to choose: the sheet names it.
- `publicPage` (`boolean`, default `false`): True when opened from a public page without signing in; adds the four required fields for intimate-image requests.
- `defaultKind` (`NoInfer<K>`, default `none`): Pre-selected reason when opened from a specific link (for example a public intimate-image form): one of `kinds`.
- `instant` (`boolean`): Opened from the keyboard: appears in one frame.
- `finalFocus` (`FocusTarget`): Where focus goes when closed. Default: what opened it.
- `container` (`PortalContainer`): Where a surface's portal mounts. Default: `document.body`. Pass a themed subtree to keep its `data-theme`, or a transformed stage to contain `position: fixed` overlays (previews): a modal set down in one stays in it, shown in place, out of the browser's top layer.
