# Settings form

> A settings page that saves the way people expect: switches save themselves, text edits gather into one bar that rises with "2 unsaved changes".

Settings pages usually pick one behaviour and get the other half wrong: either every field has a Save button, or a toggle you flipped silently waits for a button at the bottom you never scrolled to. Here switches and choices save the moment they change: the thumb is thrown across, "Saving" opens beside the label, a check draws and fades. If your server refuses, the thumb is thrown back with a shake and the reason opens under it. Text edits wait for you instead: a dot swells beside each changed label and one bar rises at the foot of the form, "2 unsaved changes" rolling as you type, and it stays in view while you scroll. A field with an async check (is this address free?) asks a moment after you stop typing. Save or ⌘S sends only what changed; errors your server sends for particular fields open under those fields, and focus goes to the first. Reset blurs the edits back to what was saved.

## Install

```bash
npx shadcn@latest add @hairline/settings-form
```

Needs React 19, Tailwind CSS v4 and shadcn/ui theme variables (any style, light and dark). Icons from lucide-react.

- npm: none
- Hairline UI components it needs (the CLI installs them too): `text-morph`, `number-roll`, `status-button`
- Docs and live preview: https://hairlineui.com/ui/settings-form
- Registry item (source): https://hairlineui.com/r/settings-form.json

## Usage

```tsx
import { SettingsForm } from "@/components/settings-form";

<SettingsForm
  defaultValue={{ name: "Fernhill", digest: true }}
  sections={[
    { title: "Workspace", fields: [{ type: "text", name: "name", label: "Name" }] },
    { title: "Notifications", fields: [{ type: "toggle", name: "digest", label: "Weekly digest" }] },
  ]}
  onSave={(patch) => saveSettings(patch)}
/>
```

## Saved by a server action

onSave receives only what changed, so one server action handles both a switch saving itself and a batch of text edits. Validate on the server too: a SettingsFormError puts each message under its field. The address check asks a route whether the slug is free and passes the AbortSignal along, so a newer keystroke cancels it.

```tsx
// app/settings/actions.ts
"use server";
import { z } from "zod";
import { db } from "@/lib/db";

const Settings = z.object({
  name: z.string().min(1).max(60),
  slug: z.string().regex(/^[a-z0-9-]{3,32}$/),
  digest: z.boolean(),
}).partial();

export async function saveSettings(patch: unknown) {
  const user = await requireUser();
  const parsed = Settings.safeParse(patch);
  if (!parsed.success) return { errors: Object.fromEntries(parsed.error.issues.map((i) => [i.path[0], i.message])) };
  if (parsed.data.slug && (await db.workspace.findFirst({ where: { slug: parsed.data.slug, NOT: { id: user.workspaceId } } })))
    return { errors: { slug: "That address was taken a moment ago." } };
  const saved = await db.workspace.update({ where: { id: user.workspaceId }, data: parsed.data });
  return { saved: { name: saved.name, slug: saved.slug, digest: saved.digest } };
}

// app/settings/form.tsx
"use client";
import { SettingsForm, SettingsFormError, type SettingsValues } from "@/components/settings-form";
import { saveSettings } from "./actions";

export function WorkspaceSettings({ initial }: { initial: SettingsValues }) {
  return (
    <SettingsForm
      defaultValue={initial}
      sections={[
        {
          title: "Workspace",
          fields: [
            { type: "text", name: "name", label: "Name" },
            {
              type: "text", name: "slug", label: "Address", prefix: "relay.app/",
              check: async (slug, { signal }) => {
                const res = await fetch(`/api/slug?q=${encodeURIComponent(slug)}`, { signal });
                return (await res.json()).available ? null : `relay.app/${slug} is taken.`;
              },
            },
          ],
        },
        { title: "Notifications", fields: [{ type: "toggle", name: "digest", label: "Weekly digest" }] },
      ]}
      onSave={async (patch) => {
        const result = await saveSettings(patch);
        if (result.errors) throw new SettingsFormError("Some fields need a look.", result.errors);
        return result.saved;
      }}
    />
  );
}
```

## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `sections` | `{ title, description?, fields }[]` | – | Groups of fields. A field is { type: "toggle" \| "choice" \| "text" \| "textarea", name, label, description? } plus options for a choice and placeholder, prefix, rows, maxLength, validate, check and checkPassed for text. |
| `value` | `Record<string, string \| boolean>` | – | Saved values, controlled. Edits live in the form until they're saved. |
| `defaultValue` | `Record<string, string \| boolean>` | – | Saved values when uncontrolled. |
| `onValueChange` | `(values) => void` | – | The saved values after every successful save. |
| `onSave` | `(patch, values) => Promise<values \| void>` | – | Saves just the changed values (one field for a switch, every edit for the bar). Return what was stored; throw an Error to show its message, or SettingsFormError(message, { field: reason }) to put reasons under fields. |
| `autosave` | `boolean` | `true` | Toggles and choices save the moment they change. Set false to send them with the bar like text. |
| `warnOnLeave` | `boolean` | `true` | Asks before the page unloads while there are unsaved edits. |
| `field.validate` | `(value, values) => string \| null` | – | Refuses a text value before it's sent; the message opens under the field. |
| `field.check` | `(value, { signal }) => Promise<string \| null>` | – | An async check run 450ms after typing stops. Return null when the value is fine or the reason it isn't; a taken value can't be saved. |

## States

- **switch**: A toggle's thumb is thrown 16px with a slight overshoot (420ms); a choice's thumb slides to the option. "Saving" opens beside the label (the column eases open in 380ms) with a spinner, then a check draws and "Saved" fades after 1.6s.
- **refused**: If onSave throws for a switch, the thumb is thrown back, the control shakes ±4px and the message opens under the field; "Not saved" stays beside the label for 2.4s.
- **edit**: Typing in a text field swells a dot beside its label (overshoot, 420ms) and opens the bar at the foot of the form by height; its count rolls as more fields change and the label morphs between change and changes.
- **check**: 450ms after typing stops, check() runs: a spinner sits at the end of the field and "Checking" lifts in under it, then a drawn check and "Available", or the reason in red with a red hairline. A newer keystroke cancels the older check through its AbortSignal.
- **save**: Save (or ⌘S / Ctrl+S anywhere in the form) runs validate() for each changed field first; refusals shake their fields and the bar says how many need a look. Then onSave gets only the changed values; the button says Saving, then Saved, and the bar folds away 1.1s later.
- **server errors**: Throw SettingsFormError(message, { field: reason }) and each reason opens under its field, the field shakes, the bar shows the message and focus moves to the first field with an error.
- **reset**: The changed fields blur from 20% back to their saved values in 420ms; their dots shrink away and the bar folds.

## What it handles

Settings pages usually get one half wrong. Either every field has a Save button, or a toggle you flipped silently waits for a button you never scrolled to. This does each the way people expect.

- **Switches save themselves**: The thumb is thrown across, “Saving” opens beside the label, then a check draws and fades.
- **Refusals are visible**: If your server says no, the thumb is thrown back with a shake and the reason opens under it.
- **Text edits gather into one bar**: A bar rises with “2 unsaved changes”. Save or ⌘S sends only what changed.
- **Checks as you type**: A field can ask your server whether a value is free, shortly after typing stops, and cancels older checks.
- **Server errors go under their fields**: Throw SettingsFormError and each reason opens under its field, with focus on the first.
- **Reset and leave warnings**: Reset blurs the edits back to what was saved, and leaving with unsaved edits asks first.

## Replaces

form state, autosave for toggles, an unsaved changes bar, async field checks, server error mapping, a Save shortcut

## Where it fits

- **Account and workspace settings**: The page of switches, choices and text fields in every SaaS product.
- **Notification preferences**: Toggles that save the moment they are flipped.
- **Profile and URL settings**: A username or slug that checks it is free as you type.
- **Product configuration**: Admin pages with several groups of options.

## Notes

- Toggles are role="switch" buttons labelled by their field label and described by its description. Choices are radio groups: arrows move and select, and only the selected option is in the tab order.
- Every message under a field is linked to its input with aria-describedby, and inputs with errors are aria-invalid. Saves, refusals and resets are announced in a status region; the "Saving" beside a label is for the eye only.
- ⌘S or Ctrl+S saves while focus is in the form. The bar is a sticky footer: on a long page it stays at the bottom of the window while the form is in view.
- A newer change to a switch wins: an older answer that arrives late is ignored. Edits made while a save is running stay unsaved and keep the bar open.
- Text inputs use 16px type on touch screens so phones don't zoom into them.
- Reduced motion changes everything in place: no thrown thumbs, slides, swells or shakes; the words and colours still say what happened.

License: MIT (https://hairlineui.com/license#components)
