# Forms

A form is a column of labelled fields with one submit. Labels stay visible, errors sit under their fields, and nothing is lost on the way out.

API [Label](/ui/storybook/?path=/docs/ui-primitives-label--docs) [FieldDescription](/ui/storybook/?path=/docs/ui-primitives-fielddescription--docs) [FileDrop](/ui/storybook/?path=/docs/ui-primitives-filedrop--docs) [InfoPopover](/ui/storybook/?path=/docs/ui-primitives-infopopover--docs) [Input](/ui/storybook/?path=/docs/ui-primitives-input--docs) [NumberInput](/ui/storybook/?path=/docs/ui-primitives-numberinput--docs) [PasswordInput](/ui/storybook/?path=/docs/ui-primitives-passwordinput--docs) [Textarea](/ui/storybook/?path=/docs/ui-primitives-textarea--docs) [Select](/ui/storybook/?path=/docs/ui-primitives-select--docs) [Checkbox](/ui/storybook/?path=/docs/ui-primitives-checkbox--docs) [RadioGroup](/ui/storybook/?path=/docs/ui-primitives-radiogroup--docs) [QueryBox](/ui/storybook/?path=/docs/ui-querybox--docs) [UnsavedChangesDialog](/ui/storybook/?path=/docs/ui-unsavedchangesdialog--docs)

**Lay a form out as one column: a visible label above each field, the error or hint under it, and one primary button at the end that names what it saves.**

```tsx
import {
  PROFILE,
  type Profile,
  sameProfile,
  TIME_ZONES,
} from "@orz/fixtures/account.ts";
import { Button } from "@orz/ui/components/button";
import { Checkbox } from "@orz/ui/components/checkbox";
import { FieldDescription, FieldError } from "@orz/ui/components/field";
import { Input } from "@orz/ui/components/input";
import { Label } from "@orz/ui/components/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@orz/ui/components/select";
import { useRef, useState } from "react";
import { toast } from "sonner";

const checkEmail = (email: string) =>
  /^\S+@\S+\.\S+$/.test(email)
    ? undefined
    : "Enter an email address, like alice@example.com.";

export function ProfileForm() {
  const [saved, setSaved] = useState(PROFILE);
  const [draft, setDraft] = useState(PROFILE);
  const [error, setError] = useState<string>();
  const emailRef = useRef<HTMLInputElement>(null);
  const edit = (next: Partial<Profile>) =>
    setDraft((was) => ({ ...was, ...next }));
  return (
    <form
      className="grid max-w-md gap-5"
      noValidate
      onSubmit={(event) => {
        event.preventDefault();
        const problem = checkEmail(draft.email);
        setError(problem);
        if (problem) {
          emailRef.current?.focus();
          return;
        }
        setSaved(draft);
        toast.success("Profile saved");
      }}
      onReset={(event) => {
        event.preventDefault();
        const lost = draft;
        setDraft(saved);
        setError(undefined);
        if (sameProfile(lost, saved)) return;
        toast("Changes discarded", {
          action: { label: "Undo", onClick: () => setDraft(lost) },
        });
      }}
    >
      <div className="grid gap-2">
        <Label htmlFor="profile-name">Display name</Label>
        <Input
          id="profile-name"
          autoComplete="nickname"
          value={draft.name}
          onChange={(event) => edit({ name: event.target.value })}
        />
      </div>
      <div className="grid gap-2">
        <Label htmlFor="profile-email">Email</Label>
        <Input
          ref={emailRef}
          id="profile-email"
          type="email"
          autoComplete="email"
          value={draft.email}
          onChange={(event) => {
            edit({ email: event.target.value });
            if (error) setError(checkEmail(event.target.value));
          }}
          aria-invalid={error !== undefined}
          aria-describedby={
            error ? "profile-email-error" : "profile-email-hint"
          }
        />
        {error ? (
          <FieldError id="profile-email-error">{error}</FieldError>
        ) : (
          <FieldDescription id="profile-email-hint">
            Like name@example.com.
          </FieldDescription>
        )}
      </div>
      <div className="grid gap-2">
        <Label htmlFor="profile-time-zone">Time zone</Label>
        <Select
          value={draft.timeZone}
          onValueChange={(timeZone) => edit({ timeZone })}
        >
          <SelectTrigger id="profile-time-zone" className="w-full">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            {TIME_ZONES.map(({ value, label }) => (
              <SelectItem key={value} value={value}>
                {label}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>
      <div className="flex items-center gap-2">
        <Checkbox
          id="profile-show-email"
          checked={draft.showEmail}
          onCheckedChange={(checked) => edit({ showEmail: checked === true })}
        />
        <Label htmlFor="profile-show-email">Show my email on my profile</Label>
      </div>
      <div className="flex justify-end gap-2">
        <Button type="reset" variant="outline">
          Discard changes
        </Button>
        <Button type="submit">Save profile</Button>
      </div>
    </form>
  );
}
```

Clear the email and press **Save profile**: the message lands under the field, focus moves to it, and the rest of the form keeps what was typed. Start typing an address and the message updates with each key, then goes once the address is whole. **Discard changes** goes back to what was last saved.

## Do and don't

**Do**

Give every field a `Label` that stays visible, joined through `htmlFor`. A placeholder can show an example value.

**Don't**

Use the placeholder as the label: it disappears with the first keystroke, and with it what the field was for.

**Do**

Check a field when the form is submitted, and again as it is corrected once it has been marked wrong.

**Don't**

Mark a field wrong while it is still being typed for the first time, or disable the submit button without saying what is missing.

## Fields

| The value                                    | Use                                                                                                                        |
| -------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
| One line of text, an email, a URL            | `Input` with the matching `type` and `autoComplete`                                                                        |
| A password                                   | `PasswordInput`, with `autoComplete` `current-password` to sign in or `new-password` to choose one                         |
| A number: a count, a port                    | `NumberInput`, with `min` and `max` where there are limits                                                                 |
| Several lines of text                        | `Textarea`                                                                                                                 |
| Several lines rendered as Markdown           | `MarkdownEditor`, see [Writing Markdown](/ui/guidelines/patterns/writing-markdown/index.md)                                |
| One of a fixed list                          | `Select`, or a `RadioGroup` for two to five, see [Choosing a control](/ui/guidelines/patterns/choosing-a-control/index.md) |
| Yes or no, applied on submit                 | `Checkbox`                                                                                                                 |
| A file: an avatar, an icon, a file to import | `FileDrop` with a `FileDropTrigger`                                                                                        |
| Text in a query language, with completion    | `QueryBox`                                                                                                                 |

```tsx
import {
  INBOX_LABEL_COLORS,
  INBOX_LABELS,
  INBOX_ME,
  INBOX_PEOPLE,
} from "@orz/fixtures/inbox.ts";
import { defineQuerySchema, type ValueProviders } from "@orz/query";
import { Badge } from "@orz/ui/components/badge";
import { Button } from "@orz/ui/components/button";
import { Checkbox } from "@orz/ui/components/checkbox";
import { FieldError } from "@orz/ui/components/field";
import { Label } from "@orz/ui/components/label";
import { QueryBox } from "@orz/ui/components/query-box";
import { RadioGroup, RadioGroupItem } from "@orz/ui/components/radio-group";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@orz/ui/components/select";
import { Textarea } from "@orz/ui/components/textarea";
import { useRef, useState } from "react";
import { toast } from "sonner";

const SCHEMA = defineQuerySchema({
  qualifiers: {
    from: { value: { kind: "named", source: "person" }, hint: "a login" },
    label: { value: { kind: "named", source: "label" }, hint: "a label" },
    is: {
      value: { kind: "enum", values: ["unread", "read", "starred"] },
      hint: "unread, read or starred",
    },
  },
});

const PROVIDERS: ValueProviders = {
  person: {
    options: Object.entries(INBOX_PEOPLE)
      .filter(([login]) => login !== INBOX_ME)
      .map(([value, hint]) => ({ value, hint })),
  },
  label: { options: INBOX_LABELS.map((value) => ({ value })) },
};

const THEN = [
  { value: "archive", label: "Archive it" },
  { value: "read", label: "Mark it as read" },
  { value: "inbox", label: "Leave it in the Inbox" },
];

export function MailFilterForm() {
  const form = useRef<HTMLFormElement>(null);
  const [query, setQuery] = useState("");
  const [error, setError] = useState<string>();
  return (
    <form
      ref={form}
      className="grid max-w-md gap-5"
      noValidate
      onSubmit={(event) => {
        event.preventDefault();
        if (query.trim() === "") {
          setError("Enter a search, like from:ci.");
          document.getElementById("filter-query")?.focus();
          return;
        }
        setError(undefined);
        toast.success("Filter created");
      }}
    >
      <div className="grid gap-2">
        <Label htmlFor="filter-query">Matching</Label>
        <QueryBox
          schema={SCHEMA}
          providers={PROVIDERS}
          value={query}
          onValueChange={(value) => {
            setQuery(value);
            if (error && value.trim() !== "") setError(undefined);
          }}
          onSubmit={() => form.current?.requestSubmit()}
          renderSubmitRow={(value, option) => (
            <div {...option}>Use “{value}”</div>
          )}
          listAlign="start"
          inputProps={{
            id: "filter-query",
            enterKeyHint: "go",
            placeholder: "from:ci label:release",
            "aria-invalid": error !== undefined,
            "aria-describedby": error ? "filter-query-error" : undefined,
          }}
        />
        {error && <FieldError id="filter-query-error">{error}</FieldError>}
      </div>
      <div className="grid gap-2">
        <Label id="filter-then-label">Then</Label>
        <RadioGroup
          defaultValue="archive"
          aria-labelledby="filter-then-label"
          name="then"
        >
          {THEN.map(({ value, label }) => (
            <div key={value} className="flex items-center gap-2">
              <RadioGroupItem value={value} id={`filter-then-${value}`} />
              <Label htmlFor={`filter-then-${value}`}>{label}</Label>
            </div>
          ))}
        </RadioGroup>
      </div>
      <div className="grid gap-2">
        <Label htmlFor="filter-label">Label it</Label>
        <Select defaultValue="ci" name="label">
          <SelectTrigger id="filter-label" className="w-full">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            {INBOX_LABELS.map((label) => (
              <SelectItem key={label} value={label}>
                <Badge variant="marker" color={INBOX_LABEL_COLORS[label]}>
                  {label}
                </Badge>
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>
      <div className="grid gap-2">
        <Label htmlFor="filter-reply">
          Reply with <span className="text-muted-foreground">(optional)</span>
        </Label>
        <Textarea id="filter-reply" name="reply" rows={3} />
      </div>
      <div className="flex items-center gap-2">
        <Checkbox id="filter-existing" name="existing" />
        <Label htmlFor="filter-existing">
          Also apply to conversations that match now
        </Label>
      </div>
      <Button type="submit" className="justify-self-end">
        Create filter
      </Button>
    </form>
  );
}
```

Press **Create filter** with **Matching** empty: the error lands under the `QueryBox` as under any other field. Type `from:` in it for the completions; Enter on the query as typed submits the form.

Mark the optional fields "(optional)" in the label rather than every required one with an asterisk: most fields in a short form are required, and a reader should not have to decode a symbol.

## A file

```tsx
import { Avatar, AvatarFallback, AvatarImage } from "@orz/ui/components/avatar";
import { Button } from "@orz/ui/components/button";
import { FieldError } from "@orz/ui/components/field";
import { FileDrop, FileDropTrigger } from "@orz/ui/components/file-drop";
import { InfoPopover } from "@orz/ui/components/info-popover";
import { Label } from "@orz/ui/components/label";
import { Trash2Icon, UploadIcon } from "lucide-react";
import { useEffect, useState } from "react";

export function AvatarField() {
  // A preview of the chosen file, read where it lies; nothing is uploaded.
  const [src, setSrc] = useState<string>();
  const [error, setError] = useState<string>();
  // The address holds the file in memory until it is let go.
  useEffect(
    () => () => {
      if (src) URL.revokeObjectURL(src);
    },
    [src],
  );
  return (
    <div className="grid max-w-md gap-2">
      <div className="flex items-center gap-1">
        <Label id="avatar-field-label">Avatar</Label>
        <InfoPopover label="About the avatar">
          Choose an image, drop one on this row, or paste one.
        </InfoPopover>
      </div>
      <FileDrop
        aria-labelledby="avatar-field-label"
        aria-describedby={error ? "avatar-field-error" : undefined}
        accept="image/png,image/jpeg,image/webp"
        onFile={(file) => {
          setError(undefined);
          setSrc(URL.createObjectURL(file));
        }}
        onReject={() => setError("Choose a PNG, JPEG or WebP image.")}
        className="flex items-center gap-3"
      >
        <Avatar size="lg">
          <AvatarImage src={src} alt="Your avatar" />
          <AvatarFallback>AL</AvatarFallback>
        </Avatar>
        <FileDropTrigger>
          <UploadIcon />
          Upload…
        </FileDropTrigger>
        <Button
          variant="outline"
          disabled={!src}
          onClick={() => setSrc(undefined)}
        >
          <Trash2Icon />
          Remove
        </Button>
      </FileDrop>
      {error && <FieldError id="avatar-field-error">{error}</FieldError>}
    </div>
  );
}
```

Press **Upload…**, drop an image on the row, or copy one and paste it with the pointer on the row: each puts it in the avatar. A PDF gets the message under the row.

- Always give the field a `FileDropTrigger`. A phone has no drag and drop, and mostly cannot paste a file either; the button is the one way in that works everywhere.
- Make the zone the whole field, the row with the picture and its buttons, not the picture alone: an avatar is too small a place to aim a dragged file at.
- Name the zone with `aria-labelledby`, pointing at its `Label`. That it takes a drop or a paste is said behind an `InfoPopover` after the label, not in a line beside the controls.
- Pass `onReject`, and say what the field takes in a `FieldError` under it: "Choose a PNG, JPEG or WebP image." A file the app turns away after reading it, too large or not an image after all, is reported the same way, saying what happened (see [Principles](/ui/guidelines/principles/index.md#say-what-happened)).
- A viewer or an editor that opens the file dropped on it is a `FileDrop` with `purpose="pane"`, put on the region with `asChild`; the [Binary inspector](/ui/demos/binary-inspector/index.md) takes a file dropped anywhere on its window.

## Errors

- The message is a `FieldError` under its field, the field gets `aria-invalid`, and `aria-describedby` points at the message, so a screen reader reads it with the field. A limit the reader needs before anything goes wrong, a format or a length, is a `FieldDescription`, wired the same way. What the field is for, when its label does not say, goes behind an `InfoPopover` after the label instead; see [Writing](/ui/guidelines/content/writing/index.md#explanations).
- After a failed submit, move focus to the first invalid field.
- Say how to fix it: "Enter an email address, like <alice@example.com>", not "Invalid input".
- An error from the server about the whole form, a lost connection or a conflict, sits above the buttons, where people look before pressing them again.

## Leaving with unsaved changes

A form that holds typed work guards it. When people navigate away before saving, ask with `UnsavedChangesDialog`: **Keep editing** is its primary action, and **Discard and leave** is the alternative. It opens with focus on **Keep editing**, so a stray Enter keeps the work. The dialog takes no router; the app's own navigation blocker opens it.

```tsx
import { PROFILE } from "@orz/fixtures/account.ts";
import { Button } from "@orz/ui/components/button";
import { Input } from "@orz/ui/components/input";
import { Label } from "@orz/ui/components/label";
import { NavList, NavListItem, NavListLink } from "@orz/ui/components/nav-list";
import { UnsavedChangesDialog } from "@orz/ui/components/unsaved-changes-dialog";
import { ChevronLeftIcon, ChevronRightIcon } from "lucide-react";
import { useState } from "react";
import { toast } from "sonner";

export function LeaveWithUnsavedChanges() {
  const [open, setOpen] = useState(true);
  const [saved, setSaved] = useState(PROFILE.name);
  const [name, setName] = useState(PROFILE.name);
  const [asking, setAsking] = useState(false);
  const leave = () => {
    setName(saved);
    setOpen(false);
  };

  if (!open) {
    return (
      <nav aria-label="Settings">
        <NavList>
          <NavListItem>
            <NavListLink asChild>
              <button type="button" onClick={() => setOpen(true)}>
                Profile
                <ChevronRightIcon className="ml-auto" />
              </button>
            </NavListLink>
          </NavListItem>
        </NavList>
      </nav>
    );
  }
  return (
    <form
      className="grid max-w-md gap-4"
      onSubmit={(event) => {
        event.preventDefault();
        setSaved(name);
        toast.success("Profile saved");
      }}
    >
      <Button
        type="button"
        variant="ghost"
        className="-ml-2 justify-self-start"
        onClick={() => (name === saved ? leave() : setAsking(true))}
      >
        <ChevronLeftIcon />
        Settings
      </Button>
      <div className="grid gap-2">
        <Label htmlFor="leave-name">Display name</Label>
        <Input
          id="leave-name"
          autoComplete="nickname"
          value={name}
          onChange={(event) => setName(event.target.value)}
        />
      </div>
      <Button type="submit" className="justify-self-end">
        Save profile
      </Button>
      <UnsavedChangesDialog
        open={asking}
        onStay={() => setAsking(false)}
        onProceed={() => {
          setAsking(false);
          leave();
        }}
      />
    </form>
  );
}
```

Change the name and press **Settings**: the dialog asks, and **Keep editing** returns to the field with the name as typed. Save first, or change nothing, and **Settings** leaves at once.

Register the work with `useDirtySource` from `@orz/ui/lib/unsaved-guard`, and have the blocker ask `hasUnsavedWork()`, which reads every source the moment a navigation starts. A form that becomes clean and navigates in one callback (save and open the new record, delete and go to the list, discard and go back) calls the `markClean` that `useDirtySource` returns before it navigates. The state that callback sets has not rendered yet, so without it the source still reads dirty, and people who have just saved are asked whether to leave without saving.

```tsx
const markClean = useDirtySource(() => draft !== saved);

async function saveAndOpen() {
  const { id } = await save(draft);
  markClean();
  setSaved(draft);
  navigate(`/items/${id}`);
}
```

Settings that apply as they change (Switches, see [Choosing a control](/ui/guidelines/patterns/choosing-a-control/index.md)) have nothing unsaved, so a settings page of Switches needs no guard and no Save button.

## On each platform

### Desktop & pointer

- Enter in a single-line field submits the form; Tab moves through the fields in reading order.
- Two short related fields, a first and last name, may share a row on a wide screen. Everything else stays in one column.

### Touch

- The `type` and `inputMode` pick the on-screen keyboard: `email` gets an @ key, `numeric` a digit pad. `autoComplete` lets the phone fill the field in.
- Inputs use a 16px font on touch, so the phone does not zoom into the field on focus.
- The on-screen keyboard covers the lower half of the screen. Keep the submit button in the flow under the last field, not pinned to the bottom, where the keyboard hides it.

## In the demos

- [Releases](/ui/demos/releases/index.md): In Overview, edit the plan and pick another release without saving: Keep editing holds the edits. Save plan stays off until something has changed, and the saved title reaches the list.
- [Settings](/ui/demos/settings/index.md): In Profile, clear the email and press Save profile: the message lands under the field and focus moves there. Edit a field, then pick another section, and Keep editing guards what you typed.
- [Sign in](/ui/demos/sign-in/index.md): Type a password shorter than 8 characters and press Sign in: the message lands under the field and focus moves there. Three in a row, and the whole form's error, Too many attempts, stands above the buttons.
- [Tasks](/ui/demos/tasks/index.md): New task: submit it with an empty title, and the message lands under the field, which is checked again as you type.
- [Mail](/ui/demos/mail/index.md): Compose with nobody in To and press Send: the message lands under the field. Close it with words in it, and the message waits in Drafts.
- [Pull request](/ui/demos/pull-request/index.md): Merge pull request is disabled with the reason beside it, never without one. Comment stays pressable: with the box empty it says what is missing, and ⌘ or Ctrl and Enter posts too.
- [Config editor](/ui/demos/config-editor/index.md): Break the JSON: the first error is named by its line under the editor, and Save waits until the file parses, while that line says why. Edit a file, then open another, and the unsaved edits are guarded.
- [Binary inspector](/ui/demos/binary-inspector/index.md): Edit a byte, then pick another sample: the unsaved edits are guarded by the same dialog a form uses before you leave it.
