<!-- generated by scripts/gen-docs.mjs from docs/system/state-button.md. Edit the source and rerun. -->
# StateButton

## Description
Reports a slow action inside the button that started it: after 250ms the label gives way to a spinner and the pending word, then to a check and the success word or a cross and the failure word on a red wash, while the box, the accessible name and keyboard focus stay where they were.

`import { StateButton } from "@/components/cobalt/ui/state-button"`, source `registry/cobalt/ui/state-button.tsx`, status `ready-with-gaps`.
Foundation: `team composition over shadcn button (base-luma, base) with motion/react`. Traps checked: `trap/button-div`, `trap/native-control`, `trap/button-clone`, `trap/control-height`, `trap/button-type`, `trap/submit-repeat`, `trap/weight-shift`, `trap/hover-beats-focus`, `trap/disabled-still-hovers`, `trap/disabled-drops-focus`, `trap/loading-layout-shift`, `trap/loading-label-swap`, `trap/button-label-wrap`, `trap/live-region-double`, `trap/color-only-status`, `trap/loader-small-dots`, `trap/toast-errors`, `trap/demo-on-timers`, `trap/reduced-motion-ignored`, `trap/motion-restart`, `trap/motion-layout-property`, `trap/motion-ease-in-enter`, `trap/motion-exit-slower`, `trap/motion-overshoot`, `trap/motion-linear`.

### Foundation
| Given by the foundation | Added by the team |
|---|---|
| `Button`: a native `<button>` with `type="button"` by default, every variant and size, `pressable`; `motion/react` `AnimatePresence`, `motion.span` and `MotionConfig`; `Spinner`, a 16px ring on `animate-spin` that stops under reduced motion | `status` from the one async vocabulary in `registry/cobalt/lib/status.ts`; the spinner held back `SPINNER_DELAY_MS` (250ms) and kept at least `SPINNER_MINIMUM_MS` (400ms) through `useSlowWait`, so a fast answer goes straight from the label to the result; `aria-busy` and `aria-disabled` with an early return in `onClick` while pending only, instead of native `disabled`, so focus stays and a settled button can be pressed again; the pointer kept while pending, so a double-click lands on the button and selects nothing, with the `hover` variant skipping `aria-disabled` so the fill stays put; the idle label rendered twice, once transparent in the flow as the box's width and the one accessible name, once painted over it and `aria-hidden` as the copy that settles; each result painted as its 16px glyph and its word in the idle label's content box, one row tall: a pending or success word too wide to sit beside its glyph wraps to a clipped second row and the spinner or the check shows alone, which say it; a failure word comes first in the source and is drawn after the cross (`flex-row-reverse`), so where the two do not fit it is the cross that wraps away and the word keeps the row on the red wash, cut at its end with an ellipsis when it is wider than the box (`overflow-x-clip`, so its descenders are never clipped); the status line still says every word in full; a label that wraps keeps a one-line label's room above and below it (`py` of half the control height less one line), so a two-line label grows the box by one line and never reaches its edge; every word, idle or result, trimmed to its capitals as a Button label is, so the capitals and the glyph share the box's centre; a failure drawn in the destructive look, red text on the 10 percent wash (D26), in every variant, so it never reads as a success in the accent, the fill cut at once in the handover's gap 42ms in, so it never blends through a grey mauve; the success copy of a destructive button in `--foreground`, since a red check on the red wash reads as an error; the painted copy clipped by its own layer, not the button, so a small size keeps its extended touch target; Swap's handover, the old copy out on 70 percent of `times.pop` and the new one in on the settle spring 42ms later, so two labels are never legible together; `type` held at `button` while pending, so a submit cannot repeat; a `role="status"` span beside the button, `select-none`, that reads `pendingLabel`, `successLabel` or `failureLabel`; `MotionConfig reducedMotion="user"`; `unconfirmed` from `WriteStatus`, a write whose answer was lost, where the button reads and is named `unconfirmedLabel`, "Check", with no glyph, holds that copy through the check's own wait, and announces `unconfirmedNote`, "Could not confirm" |

## Examples
An export reports itself inside its button, and a press after a failure retries.

Real uses, 0 call sites (`rg -n "<StateButton\b" app registry --glob '!registry/cobalt/ui/*'`): the showcase chrome renders none, the registry's own ui folder never counts, and the examples folder does not count.

Uses in other components' examples, which the rules below sweep as the system's own call sites:
- The dialog's submit, "Sending" then "Not sent" on failure, holding the dialog open while pending, `docs/system/examples/dialog/default.tsx:112-116`.
- The alert dialog's confirm, `destructive`, "Deleting" then "Not deleted", with the failure shown as text in the footer, `docs/system/examples/alert-dialog/default.tsx:63-67`.

Uses inside the registry: none. `Button` names it as the fix for a slow action, `docs/system/button.md`, rule/button-keeps-its-box-when-busy.

### Example files
| File | Covers | Caption |
|---|---|---|
| `docs/system/examples/state-button/default.tsx` | default | An export reports itself inside its button, and a press after a failure retries |
| `docs/system/examples/state-button/matrix-status-variant.tsx` | status=idle | The plain label, which sets the box |
| `docs/system/examples/state-button/matrix-status-variant.tsx` | status=pending | The spinner and the pending word, in the label's box |
| `docs/system/examples/state-button/matrix-status-variant.tsx` | status=success | A check and the success word, in the same box |
| `docs/system/examples/state-button/matrix-status-variant.tsx` | status=failure | A cross and the failure word in red on the wash, in the same box |
| `docs/system/examples/state-button/unconfirmed.tsx` | status=unconfirmed | A payment run whose answer was lost: the button says Check instead of sending again |
| `docs/system/examples/state-button/matrix-status-variant.tsx` | variant=default | The view's one primary action |
| `docs/system/examples/state-button/matrix-status-variant.tsx` | variant=secondary | A secondary action that is slow |
| `docs/system/examples/state-button/matrix-status-variant.tsx` | variant=destructive | Red on light red; the success copy in the page's ink, the failure copy in red as at rest |
| Not applicable: every example is the 36px control height | size=default | The control height |
| Not applicable: disabled is the Button's half opacity, shown on the Button page; a StateButton is disabled only while idle | state:disabled | The label at half opacity, out of the tab order |
| Not applicable: hover is reached with the pointer on any example | state:hover | The fill one step darker |
| Not applicable: focus-visible is reached with the keyboard on any example, and stays through pending | state:focus-visible | The 2px ring outside the corner |
| `docs/system/examples/state-button/default.tsx` | composition:Card | The export button in a card's footer, beside the line that says what it makes or why it failed |
| `docs/system/examples/state-button/submit.tsx` | composition:Field | Enter in the field submits through the button, and while the rename is on its way a second Enter or press does nothing |
| `docs/system/examples/state-button/matrix-status-variant.tsx` | matrix:status,variant | One label sets the box for every status and variant, so a row never changes width; each status is a column under its heading, two columns on a phone |

Example: An export reports itself inside its button, and a press after a failure retries (`docs/system/examples/state-button/default.tsx`)

```tsx
import { Card, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/cobalt/ui/card";
import { StateButton } from "@/components/cobalt/ui/state-button";
import { useAction } from "@/lib/cobalt/use-action";

// Stands in for your API call. It answers after a second, and fails while the browser is offline or
// the address has ?network=offline.
const request = () =>
  new Promise<void>((resolve, reject) =>
    setTimeout(() => {
      const offline = !navigator.onLine || new URLSearchParams(location.search).get("network") === "offline";
      if (offline) reject(new Error("offline"));
      else resolve();
    }, 1000),
  );

// The file the export hands back: one row per paper, computed so nothing is stored.
const papers = Array.from({ length: 1284 }, (_, i) => `P-${20_000 + i},${2014 + (i % 12)},${(i * 37) % 410}`);

function download() {
  const url = URL.createObjectURL(new Blob([["id,year,citations", ...papers].join("\n")], { type: "text/csv" }));
  const link = document.createElement("a");
  link.href = url;
  link.download = "papers.csv";
  link.click();
  URL.revokeObjectURL(url);
}

export default function Example() {
  const exporting = useAction(async () => {
    await request();
    download();
  });
  return (
    <Card className="w-full max-w-sm">
      <CardHeader>
        <CardTitle>Export results</CardTitle>
        <CardDescription>Papers matching “retrieval”, six columns</CardDescription>
      </CardHeader>
      {/* The line beside the button is as wide as the space the button leaves, so its words can change
          without moving anything; a failure says why in the same place. */}
      <CardFooter className="h-10 gap-4">
        <p className="line-clamp-2 min-w-0 flex-1 text-sm text-muted-foreground">
          {exporting.error === null ? (
            "CSV, 22 KB"
          ) : (
            <span className="text-destructive">You are offline. Try again.</span>
          )}
        </p>
        <StateButton
          status={exporting.status}
          pendingLabel="Exporting"
          successLabel="Exported"
          failureLabel="Not exported"
          onClick={() => void exporting.run()}
        >
          Export 1,284 rows
        </StateButton>
      </CardFooter>
    </Card>
  );
}
```

Example: The export button in a card's footer, beside the line that says what it makes or why it failed (`docs/system/examples/state-button/default.tsx`)

```tsx
import { Card, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/cobalt/ui/card";
import { StateButton } from "@/components/cobalt/ui/state-button";
import { useAction } from "@/lib/cobalt/use-action";

// Stands in for your API call. It answers after a second, and fails while the browser is offline or
// the address has ?network=offline.
const request = () =>
  new Promise<void>((resolve, reject) =>
    setTimeout(() => {
      const offline = !navigator.onLine || new URLSearchParams(location.search).get("network") === "offline";
      if (offline) reject(new Error("offline"));
      else resolve();
    }, 1000),
  );

// The file the export hands back: one row per paper, computed so nothing is stored.
const papers = Array.from({ length: 1284 }, (_, i) => `P-${20_000 + i},${2014 + (i % 12)},${(i * 37) % 410}`);

function download() {
  const url = URL.createObjectURL(new Blob([["id,year,citations", ...papers].join("\n")], { type: "text/csv" }));
  const link = document.createElement("a");
  link.href = url;
  link.download = "papers.csv";
  link.click();
  URL.revokeObjectURL(url);
}

export default function Example() {
  const exporting = useAction(async () => {
    await request();
    download();
  });
  return (
    <Card className="w-full max-w-sm">
      <CardHeader>
        <CardTitle>Export results</CardTitle>
        <CardDescription>Papers matching “retrieval”, six columns</CardDescription>
      </CardHeader>
      {/* The line beside the button is as wide as the space the button leaves, so its words can change
          without moving anything; a failure says why in the same place. */}
      <CardFooter className="h-10 gap-4">
        <p className="line-clamp-2 min-w-0 flex-1 text-sm text-muted-foreground">
          {exporting.error === null ? (
            "CSV, 22 KB"
          ) : (
            <span className="text-destructive">You are offline. Try again.</span>
          )}
        </p>
        <StateButton
          status={exporting.status}
          pendingLabel="Exporting"
          successLabel="Exported"
          failureLabel="Not exported"
          onClick={() => void exporting.run()}
        >
          Export 1,284 rows
        </StateButton>
      </CardFooter>
    </Card>
  );
}
```

Example: Enter in the field submits through the button, and while the rename is on its way a second Enter or press does nothing (`docs/system/examples/state-button/submit.tsx`)

```tsx
import { useRef, useState } from "react";

import { Field, FieldError, FieldLabel } from "@/components/cobalt/ui/field";
import { Input } from "@/components/cobalt/ui/input";
import { StateButton } from "@/components/cobalt/ui/state-button";
import { useAction } from "@/lib/cobalt/use-action";

// Stands in for your API call. It answers after a second, and fails while the browser is offline or
// the address has ?network=offline.
const request = () =>
  new Promise<void>((resolve, reject) =>
    setTimeout(() => {
      const offline = !navigator.onLine || new URLSearchParams(location.search).get("network") === "offline";
      if (offline) reject(new Error("offline"));
      else resolve();
    }, 1000),
  );

export default function Example() {
  const [name, setName] = useState("Large-cap core");
  const [tried, setTried] = useState(false);
  const field = useRef<HTMLInputElement>(null);
  const rename = useAction(request);
  const empty = name.trim() === "";
  return (
    <form
      className="flex w-full max-w-sm flex-col gap-3"
      onSubmit={(event) => {
        event.preventDefault();
        setTried(true);
        if (empty) return field.current?.focus();
        void rename.run();
      }}
    >
      <Field>
        <FieldLabel>Watchlist name</FieldLabel>
        <Input ref={field} value={name} onChange={(event) => setName(event.target.value)} />
        {tried && empty && <FieldError>Enter a name for the watchlist.</FieldError>}
      </Field>
      {/* The reason sits in the row the button already holds, so it appears without moving anything. */}
      <div className="flex items-center gap-3">
        <p className="min-w-0 flex-1 text-sm text-destructive">
          {rename.error !== null ? "You are offline. Try again." : ""}
        </p>
        <StateButton
          type="submit"
          status={rename.status}
          pendingLabel="Renaming"
          successLabel="Renamed"
          failureLabel="Not renamed"
        >
          Rename watchlist
        </StateButton>
      </div>
    </form>
  );
}
```

Example: One label sets the box for every status and variant, so a row never changes width; each status is a column under its heading, two columns on a phone (`docs/system/examples/state-button/matrix-status-variant.tsx`)

```tsx
import { StateButton } from "@/components/cobalt/ui/state-button";
import type { Status } from "@/lib/cobalt/status";

const statuses: Status[] = ["idle", "pending", "success", "failure"];
const rows = [
  { variant: "default", label: "Save changes", words: ["Saving", "Saved", "Not saved"] },
  { variant: "secondary", label: "Send 3 invites", words: ["Sending", "Sent", "Not sent"] },
  { variant: "destructive", label: "Delete 128 items", words: ["Deleting", "Deleted", "Not deleted"] },
] as const;

export default function Example() {
  // One column per status, each under its heading, so on a phone the pairs still say what they show.
  return (
    <div className="grid w-full max-w-2xl grid-cols-2 gap-x-3 gap-y-6 sm:grid-cols-4">
      {statuses.map((status) => (
        <div key={status} className="flex min-w-0 flex-col items-start gap-3">
          <p className="text-xs text-muted-foreground capitalize">{status}</p>
          {rows.map(({ variant, label, words: [pending, success, failure] }) => (
            <StateButton
              key={variant}
              variant={variant}
              status={status}
              pendingLabel={pending}
              successLabel={success}
              failureLabel={failure}
            >
              {label}
            </StateButton>
          ))}
        </div>
      ))}
    </div>
  );
}
```

## Variants

### status
- `idle`: the action can start; the label shows and `onClick` runs.
- `pending`: the action is running; after 250ms the spinner and `pendingLabel` show, `aria-busy` and `aria-disabled` are set, a press returns early and `pendingLabel` is announced.
- `success`: the action finished; the check and `successLabel` show and are announced, until `useAction` returns `status` to idle after 1500ms or the host closes its dialog. A press runs the action again.
- `failure`: the action did not finish; the button takes the destructive look, red text on the 10 percent wash, in every variant, the cross and `failureLabel` show and are announced, and the host writes the reason as text beside the button. A press retries at once. The wash is a tint, never a solid red fill (D26), so the failure is plain without alarm, and a primary failure no longer differs from its success only by the glyph.

- `unconfirmed`: a write went out and its answer was lost, so nobody knows if it landed. The button reads `unconfirmedLabel`, "Check", in its own look and is named by it; `unconfirmedNote` is announced; it holds until the status moves on. With `useAction`'s `check`, the next press asks the server instead of sending again.

Example: The plain label, which sets the box (`docs/system/examples/state-button/matrix-status-variant.tsx`)

```tsx
import { StateButton } from "@/components/cobalt/ui/state-button";
import type { Status } from "@/lib/cobalt/status";

const statuses: Status[] = ["idle", "pending", "success", "failure"];
const rows = [
  { variant: "default", label: "Save changes", words: ["Saving", "Saved", "Not saved"] },
  { variant: "secondary", label: "Send 3 invites", words: ["Sending", "Sent", "Not sent"] },
  { variant: "destructive", label: "Delete 128 items", words: ["Deleting", "Deleted", "Not deleted"] },
] as const;

export default function Example() {
  // One column per status, each under its heading, so on a phone the pairs still say what they show.
  return (
    <div className="grid w-full max-w-2xl grid-cols-2 gap-x-3 gap-y-6 sm:grid-cols-4">
      {statuses.map((status) => (
        <div key={status} className="flex min-w-0 flex-col items-start gap-3">
          <p className="text-xs text-muted-foreground capitalize">{status}</p>
          {rows.map(({ variant, label, words: [pending, success, failure] }) => (
            <StateButton
              key={variant}
              variant={variant}
              status={status}
              pendingLabel={pending}
              successLabel={success}
              failureLabel={failure}
            >
              {label}
            </StateButton>
          ))}
        </div>
      ))}
    </div>
  );
}
```

Example: The spinner and the pending word, in the label's box (`docs/system/examples/state-button/matrix-status-variant.tsx`)

```tsx
import { StateButton } from "@/components/cobalt/ui/state-button";
import type { Status } from "@/lib/cobalt/status";

const statuses: Status[] = ["idle", "pending", "success", "failure"];
const rows = [
  { variant: "default", label: "Save changes", words: ["Saving", "Saved", "Not saved"] },
  { variant: "secondary", label: "Send 3 invites", words: ["Sending", "Sent", "Not sent"] },
  { variant: "destructive", label: "Delete 128 items", words: ["Deleting", "Deleted", "Not deleted"] },
] as const;

export default function Example() {
  // One column per status, each under its heading, so on a phone the pairs still say what they show.
  return (
    <div className="grid w-full max-w-2xl grid-cols-2 gap-x-3 gap-y-6 sm:grid-cols-4">
      {statuses.map((status) => (
        <div key={status} className="flex min-w-0 flex-col items-start gap-3">
          <p className="text-xs text-muted-foreground capitalize">{status}</p>
          {rows.map(({ variant, label, words: [pending, success, failure] }) => (
            <StateButton
              key={variant}
              variant={variant}
              status={status}
              pendingLabel={pending}
              successLabel={success}
              failureLabel={failure}
            >
              {label}
            </StateButton>
          ))}
        </div>
      ))}
    </div>
  );
}
```

Example: A check and the success word, in the same box (`docs/system/examples/state-button/matrix-status-variant.tsx`)

```tsx
import { StateButton } from "@/components/cobalt/ui/state-button";
import type { Status } from "@/lib/cobalt/status";

const statuses: Status[] = ["idle", "pending", "success", "failure"];
const rows = [
  { variant: "default", label: "Save changes", words: ["Saving", "Saved", "Not saved"] },
  { variant: "secondary", label: "Send 3 invites", words: ["Sending", "Sent", "Not sent"] },
  { variant: "destructive", label: "Delete 128 items", words: ["Deleting", "Deleted", "Not deleted"] },
] as const;

export default function Example() {
  // One column per status, each under its heading, so on a phone the pairs still say what they show.
  return (
    <div className="grid w-full max-w-2xl grid-cols-2 gap-x-3 gap-y-6 sm:grid-cols-4">
      {statuses.map((status) => (
        <div key={status} className="flex min-w-0 flex-col items-start gap-3">
          <p className="text-xs text-muted-foreground capitalize">{status}</p>
          {rows.map(({ variant, label, words: [pending, success, failure] }) => (
            <StateButton
              key={variant}
              variant={variant}
              status={status}
              pendingLabel={pending}
              successLabel={success}
              failureLabel={failure}
            >
              {label}
            </StateButton>
          ))}
        </div>
      ))}
    </div>
  );
}
```

Example: A cross and the failure word in red on the wash, in the same box (`docs/system/examples/state-button/matrix-status-variant.tsx`)

```tsx
import { StateButton } from "@/components/cobalt/ui/state-button";
import type { Status } from "@/lib/cobalt/status";

const statuses: Status[] = ["idle", "pending", "success", "failure"];
const rows = [
  { variant: "default", label: "Save changes", words: ["Saving", "Saved", "Not saved"] },
  { variant: "secondary", label: "Send 3 invites", words: ["Sending", "Sent", "Not sent"] },
  { variant: "destructive", label: "Delete 128 items", words: ["Deleting", "Deleted", "Not deleted"] },
] as const;

export default function Example() {
  // One column per status, each under its heading, so on a phone the pairs still say what they show.
  return (
    <div className="grid w-full max-w-2xl grid-cols-2 gap-x-3 gap-y-6 sm:grid-cols-4">
      {statuses.map((status) => (
        <div key={status} className="flex min-w-0 flex-col items-start gap-3">
          <p className="text-xs text-muted-foreground capitalize">{status}</p>
          {rows.map(({ variant, label, words: [pending, success, failure] }) => (
            <StateButton
              key={variant}
              variant={variant}
              status={status}
              pendingLabel={pending}
              successLabel={success}
              failureLabel={failure}
            >
              {label}
            </StateButton>
          ))}
        </div>
      ))}
    </div>
  );
}
```

Example: A payment run whose answer was lost: the button says Check instead of sending again (`docs/system/examples/state-button/unconfirmed.tsx`)

```tsx
import { useRef, useState } from "react";

import { StateButton } from "@/components/cobalt/ui/state-button";
import { TextSwap } from "@/components/cobalt/ui/text-swap";
import { Toggle } from "@/components/cobalt/ui/toggle";
import { Unconfirmed } from "@/lib/cobalt/failure";
import { useAction } from "@/lib/cobalt/use-action";

export default function Example() {
  // Stands in for your server: how many times the run was sent, and a switch that loses the next answer.
  const sent = useRef(0);
  const [loseNext, setLoseNext] = useState(false);
  const [runs, setRuns] = useState(0);
  const send = useAction(
    () =>
      new Promise<void>((resolve, reject) => {
        const lose = loseNext;
        setLoseNext(false);
        setTimeout(() => {
          sent.current += 1;
          setRuns(sent.current);
          if (lose) reject(new Unconfirmed());
          else resolve();
        }, 900);
      }),
    { check: () => new Promise<boolean>((resolve) => setTimeout(() => resolve(sent.current > 0), 700)) },
  );
  return (
    <div className="flex flex-col items-start gap-3">
      <StateButton
        status={send.status}
        pendingLabel="Sending"
        successLabel="Sent"
        failureLabel="Not sent"
        onClick={() => void send.run()}
      >
        Send payment run
      </StateButton>
      {/* Both lines share one cell, so the longer one's room is held and nothing under it moves. */}
      <TextSwap
        show={send.status === "unconfirmed" ? "unconfirmed" : "count"}
        className="text-sm text-muted-foreground tabular-nums"
        options={{
          count: `The server has received the run ${runs} ${runs === 1 ? "time" : "times"}.`,
          unconfirmed: "Could not confirm the run was sent. Check before sending it again.",
        }}
      />
      {/* Docs control, not part of the product: the server's next answer is lost on the way back. */}
      <div className="mt-4 flex w-full flex-wrap items-center gap-2 border-t border-dashed pt-3">
        <Toggle size="sm" pressed={loseNext} onPressedChange={setLoseNext}>
          Lose the next answer
        </Toggle>
      </div>
    </div>
  );
}
```

### variant
- `default`: the view's one primary action.
- `secondary`: a secondary action that is slow, such as Send beside a primary.
- `destructive`: an action that removes something, red on the wash, after a confirmation; its success copy is drawn in the page's ink, so a finished delete does not read as an error, and its failure keeps the red it has at rest, told apart by the cross and the word.

The `outline`, `ghost` and `link` forms type-check; a ghost or link has no fill for the spinner to sit in, so they are not for it.

Example: The view's one primary action (`docs/system/examples/state-button/matrix-status-variant.tsx`)

```tsx
import { StateButton } from "@/components/cobalt/ui/state-button";
import type { Status } from "@/lib/cobalt/status";

const statuses: Status[] = ["idle", "pending", "success", "failure"];
const rows = [
  { variant: "default", label: "Save changes", words: ["Saving", "Saved", "Not saved"] },
  { variant: "secondary", label: "Send 3 invites", words: ["Sending", "Sent", "Not sent"] },
  { variant: "destructive", label: "Delete 128 items", words: ["Deleting", "Deleted", "Not deleted"] },
] as const;

export default function Example() {
  // One column per status, each under its heading, so on a phone the pairs still say what they show.
  return (
    <div className="grid w-full max-w-2xl grid-cols-2 gap-x-3 gap-y-6 sm:grid-cols-4">
      {statuses.map((status) => (
        <div key={status} className="flex min-w-0 flex-col items-start gap-3">
          <p className="text-xs text-muted-foreground capitalize">{status}</p>
          {rows.map(({ variant, label, words: [pending, success, failure] }) => (
            <StateButton
              key={variant}
              variant={variant}
              status={status}
              pendingLabel={pending}
              successLabel={success}
              failureLabel={failure}
            >
              {label}
            </StateButton>
          ))}
        </div>
      ))}
    </div>
  );
}
```

Example: A secondary action that is slow (`docs/system/examples/state-button/matrix-status-variant.tsx`)

```tsx
import { StateButton } from "@/components/cobalt/ui/state-button";
import type { Status } from "@/lib/cobalt/status";

const statuses: Status[] = ["idle", "pending", "success", "failure"];
const rows = [
  { variant: "default", label: "Save changes", words: ["Saving", "Saved", "Not saved"] },
  { variant: "secondary", label: "Send 3 invites", words: ["Sending", "Sent", "Not sent"] },
  { variant: "destructive", label: "Delete 128 items", words: ["Deleting", "Deleted", "Not deleted"] },
] as const;

export default function Example() {
  // One column per status, each under its heading, so on a phone the pairs still say what they show.
  return (
    <div className="grid w-full max-w-2xl grid-cols-2 gap-x-3 gap-y-6 sm:grid-cols-4">
      {statuses.map((status) => (
        <div key={status} className="flex min-w-0 flex-col items-start gap-3">
          <p className="text-xs text-muted-foreground capitalize">{status}</p>
          {rows.map(({ variant, label, words: [pending, success, failure] }) => (
            <StateButton
              key={variant}
              variant={variant}
              status={status}
              pendingLabel={pending}
              successLabel={success}
              failureLabel={failure}
            >
              {label}
            </StateButton>
          ))}
        </div>
      ))}
    </div>
  );
}
```

Example: Red on light red; the success copy in the page's ink, the failure copy in red as at rest (`docs/system/examples/state-button/matrix-status-variant.tsx`)

```tsx
import { StateButton } from "@/components/cobalt/ui/state-button";
import type { Status } from "@/lib/cobalt/status";

const statuses: Status[] = ["idle", "pending", "success", "failure"];
const rows = [
  { variant: "default", label: "Save changes", words: ["Saving", "Saved", "Not saved"] },
  { variant: "secondary", label: "Send 3 invites", words: ["Sending", "Sent", "Not sent"] },
  { variant: "destructive", label: "Delete 128 items", words: ["Deleting", "Deleted", "Not deleted"] },
] as const;

export default function Example() {
  // One column per status, each under its heading, so on a phone the pairs still say what they show.
  return (
    <div className="grid w-full max-w-2xl grid-cols-2 gap-x-3 gap-y-6 sm:grid-cols-4">
      {statuses.map((status) => (
        <div key={status} className="flex min-w-0 flex-col items-start gap-3">
          <p className="text-xs text-muted-foreground capitalize">{status}</p>
          {rows.map(({ variant, label, words: [pending, success, failure] }) => (
            <StateButton
              key={variant}
              variant={variant}
              status={status}
              pendingLabel={pending}
              successLabel={success}
              failureLabel={failure}
            >
              {label}
            </StateButton>
          ))}
        </div>
      ))}
    </div>
  );
}
```

### size
- `default`: the 36px control height.

`xs`, `sm` and `lg` type-check and keep the box; `sm` reaches 44px under a coarse pointer through the Button's `touch-target`. The `icon` squares have no label to hold the width, so they are not for it; an icon-only slow action is a `Button` with `aria-busy` set by the host.

## States
| State | Trigger | What the user can do | Shown by, besides color | Checked by |
|---|---|---|---|---|
| idle | `status="idle"` | press, focus | the label | test |
| pending | `status="pending"` | nothing; a second press returns early and focus stays | the label for the first 250ms, then the spinner and `pendingLabel` in the same box for at least 400ms; `aria-busy`; `pendingLabel` read as a status | test |
| success | `status="success"` | press again to run the action again | the check and `successLabel` in the same box, and `successLabel` read as a status | test |
| failure | `status="failure"` | read the reason beside the button, and press it to retry at once | the red wash, the cross and `failureLabel` in the same box, `failureLabel` read as a status, and the host's reason as text | test |
| unconfirmed | `status="unconfirmed"`, from `useAction` with `check` | press Check, which asks the server | "Check" in the label's box with no glyph, the name "Check", `unconfirmedNote` read as a status, and the host's line beside it | test |
| hover | pointer over, under `(hover: hover)`, not while pending | press | the fill one step darker; no shape change | by hand |
| focus-visible | keyboard focus | press with Enter or Space while idle | the 2px ring, kept through pending and the result | by hand |
| disabled | `disabled` while idle | nothing; focus skips it, and a double-click selects nothing | half opacity and the default cursor | test |

Every status keeps the box the idle label set: measured 117.28 by 36px for "Save changes", 117.06 by 36px for "Send 3 invites", 133.45 by 36px for "Delete 128 items" and 139.95 by 36px for "Export 1,284 rows" in all four statuses, at 1440 and 390, light and dark, with the painted row within 0.01px of the box's centre (`.design-system/evidence/state-button/widths.json`). Where a word fits it shows beside its glyph; where it does not, the glyph shows alone and the status line says the word: the alert's Retry stays 61.63px and shows the spinner alone while "Retrying" is announced. The capitals and the glyphs sit on the box's vertical centre within 0.17px and 0.5px (`.design-system/evidence/state-button/centre.json`). At 320 with the worst case on the stress page (`.design-system/evidence/state-button/narrow-320.json`): before, "Die Änderungen konnten nicht gespeichert werden. Prüfen Sie Ihre Verbindung." showed only the cross, and "Einladung an alle Teilnehmenden erneut senden" wrapped to two lines in a 36px box, its capitals 3px from the edges; after, the failure shows "Die Änderungen konnten ni…" on the wash in the same 214.6 by 36px box, and the two-line label stands in a 48.1px box, 9px from its edges as a one-line label is 13px; every one-line box is unchanged.

### State precedence
- Pending and pressed: pending wins. `pressable` skips the tint on `aria-disabled`, and the handler returns early.
- Pending and focus-visible: both show. Focus is kept on purpose, so the ring stays on the spinning button.
- Pending and hover: pending wins. The `hover` variant skips `aria-disabled`, so the fill never changes under the pointer (`trap/disabled-still-hovers`), while the button keeps the pointer, so a double-click lands on it and selects nothing; the status word beside it is `select-none`.
- Pending and disabled: disabled wins. Native `disabled` passes through and drops focus, which is why `disabled` is set only while idle (rule/state-button-disabled-only-idle).
- Success or failure and hover: both show. The fill darkens, the accent or, after a failure, the red wash, and a press starts the action again.
- Success and failure: Not applicable: `status` holds one value.
- Unconfirmed and pending: unconfirmed wins while the check waits under 250ms. The button keeps "Check" until the spinner is due, so it never flashes back to the action that may already have happened.

### Motion
| Trigger | Kind | Preset | Properties | Reduced motion |
|---|---|---|---|---|
| any change of what the button shows | announce | out: 70 percent of `times.pop`, 105ms on `curves.out`; in: `springs.settle`, a 0.3s spring with no bounce, 42ms later; recorded frame by frame at 16ms on a fake clock, the old copy is under 5 percent by 48ms and the fainter of the two never passed 3 percent, where the earlier 200ms exit with an arrival at once drew both labels over 5 percent for 5 frames per change (`.design-system/evidence/state-button/handover.json`) | opacity, y (transform) over 8px, the new copy from above as the old leaves below, clipped by the button's corner | `MotionConfig reducedMotion="user"` drops the movement and keeps the handover of opacity; `aria-busy` and the still spinner keep the state |
| pending to failure, and failure back to idle | announce | none: the fill cuts at once 42ms in, in the handover's gap, with `transition-none` for that one frame, since a fade from the accent to the red wash over `--t-press` passes through a grey mauve; sampled per frame, the fill goes from the accent to the wash in one frame (`.design-system/evidence/state-button/handover.json`, `failureFill`) | background-color and color, the accent or grey to the red wash and back | the same cut |
| while pending | announce | `animate-spin` on the Spinner | transform | `motion-reduce:animate-none`, the ring stands still |
| pointer-down to pointer-up, idle only | input | `pressable`, `--t-press` on `--curve`, from `Button` | box-shadow, background-color | `box-shadow` is not in the reduced-motion list, so the press tint is instant; the fill change stays |

## Props

<!-- Props generated from registry/cobalt/ui/state-button.tsx with TypeScript by scripts/props-table.mjs -->
| Prop | Type | Default | Purpose |
|---|---|---|---|
| `children` | `ReactNode` |  |  |
| `status` | `WriteStatus` |  | `idle` the action can start; `pending` the action is running; `success` the action finished; `failure` the action did not finish; `unconfirmed` a write went out and its answer was lost. |
| `failureLabel?` | `string` | `"Failed"` | Shown beside the cross and read once when the action fails. |
| `pendingLabel?` | `string` | `"Working"` | Shown beside the spinner and read by screen readers while pending. |
| `size?` | `"default" \| "sm" \| "lg" \| "icon" \| "icon-sm" \| "icon-xs" \| "icon-lg"` |  | `default` the 36px control height. |
| `successLabel?` | `string` | `"Done"` | Shown beside the check and read once when the action succeeds. |
| `unconfirmedLabel?` | `string` | `"Check"` | The button's word and name while a write is unconfirmed: the way on, a check. |
| `unconfirmedNote?` | `string` | `"Could not confirm"` | Read once when a write ends unconfirmed: what happened. |
| `variant?` | `"default" \| "secondary" \| "ghost" \| "destructive"` |  | `default` the view's one primary action; `secondary` a secondary action that is slow; `destructive` an action that removes something. |

Also accepts every native `<button>` attribute; from Base UI: `focusableWhenDisabled`, `nativeButton`, `render`.

`status` is required and is the `WriteStatus` union, a `Status` or `unconfirmed`, usually `useAction`'s. `children` is the idle label, the box's width and the one accessible name in every status. `pendingLabel`, `successLabel` and `failureLabel` default to "Working", "Done" and "Failed"; `unconfirmedLabel`, "Check", is the word and the name while unconfirmed, and `unconfirmedNote`, "Could not confirm", is what is announced; each is shown beside its glyph where it fits in the label's width, and read once as a status. Every `Button` prop passes through: `variant`, `size`, `disabled`, `type` (held at `button` while pending), `onClick` (skipped while pending), `render`. `ref` reaches the `<button>`. `className` is merged after `relative` and is for placement.

## Usage

### When to use
- A press starts a request that can take longer than the press: export, save, send, publish, delete.
- The result belongs where you are looking, on the button, and a toast across the screen would be too far away.

### When not to use
- The action stays on the page and answers at once, such as copying or showing a key. Use Button with an IconSwap instead; a spinner that shows for under 400ms reads as a flicker.
- The result lands somewhere else, such as a new row in a list you are not looking at. Use Button and a toast through `rule/writing-toast-result` instead.
- The control is on or off. Use Pill or Toggle instead.
- The whole dialog waits. Use Dialog with `DialogContent status` instead of dimming the button alone, with a StateButton for the action, as the Dialog's own example does.

### Rules
- `rule/state-button-status-is-one-union`: When the host tracks the action, run it through `useAction` and pass its `status`, instead of mapping `isLoading` and `isError` booleans into it, because two booleans can both be true and the union cannot, and `useAction` also returns a result to idle after 1500ms and ignores a second run while one is pending. Evidence: person D39; app 3/3 call sites pass `useAction`'s status (`docs/system/examples/state-button/default.tsx:51`, `docs/system/examples/dialog/default.tsx:114`, `docs/system/examples/alert-dialog/default.tsx:65`). Check: lint through the `status` prop type, which is `Status`, so `pnpm typecheck` fails a boolean; review of the host's state.
  - Don't: `<StateButton status={loading ? "pending" : error ? "failure" : "idle"}>Save</StateButton>`
  - Do: `<StateButton status={save.status} onClick={() => void save.run()}>Save</StateButton>` with `const save = useAction(saveProfile)`
- `rule/state-button-not-for-a-preference`: When a press sets something the person owns, such as Follow, Save, Star or Mute, use a `Button` (or a `SaveToggle`) with `useOptimisticToggle` instead of a `StateButton`, because the change is theirs and shows on the press, while a spinner on it reads as the app hesitating over the easiest action there is; only a refusal moves it back, with the reason beside it. Evidence: person D47; single use `docs/system/examples/blocks/record.tsx:353`, the record scene's Follow, as the screener's; principle heuristic: visibility of system status, the state the person chose shows at once. Check: review of every `StateButton` whose label names a preference.
  - Don't: `<StateButton status={follow.status} pendingLabel="Following" onClick={() => void follow.run(!on)}>Follow</StateButton>`
  - Do: `<Button aria-pressed={follow.on} onClick={() => follow.flip(!follow.on)}>{follow.on ? "Following" : "Follow"}</Button>` with `const follow = useOptimisticToggle("follow:" + id, false, { send })`
- `rule/state-button-check-not-retry`: When a write's answer can be lost, such as a payment or a send behind a timeout, pass `check` to `useAction` so a lost answer ends `unconfirmed` and the next press asks the server, instead of letting the button retry, because a blind retry after a lost answer can send the payment twice. Evidence: person D39; app 1/2 source apps, Tag's "Saving wasn't confirmed" with Check status, docs/research/2026-10-17-missing-parts.md F3. Check: test `use-action.test.ts` "with check, a lost answer is unconfirmed, and the next press checks instead of sending".
  - Don't: `const send = useAction(() => api.sendPaymentRun())` behind a 10-second timeout
  - Do: `const send = useAction(() => api.sendPaymentRun(), { check: () => api.paymentRunSent() })`
- `rule/state-button-disabled-only-idle`: When the action cannot start yet, pass `disabled` only while `status` is `idle`, instead of deriving it from `status`, because native `disabled` passes through, leaves the tab order and drops keyboard focus to the page, which `aria-disabled` is there to avoid. Evidence: person D2; principle platform: a disabled button leaves the tab order, so a focused button that turns disabled sends focus to the body. Check: test `state-button.test.tsx`, pending renders `aria-disabled` and no native `disabled`; review of every `disabled` expression on a StateButton.
  - Don't: `<StateButton status={status} disabled={status !== "idle"}>Save</StateButton>`
  - Do: `<StateButton status={status} disabled={!valid}>Save</StateButton>`
- `rule/state-button-submit-through-type`: When the button submits a form, pass `type="submit"` and run the request from the form's `onSubmit`, instead of an `onClick` on a `type="button"`, because Enter in a field submits through the form's submit button, and the component holds `type` at `button` while pending so Enter cannot submit twice. Evidence: principle platform: a form submits on Enter through its submit button, and a form with no submit button does nothing on Enter; app 2/2 forms in the examples submit through it, `docs/system/examples/dialog/default.tsx:113` and `docs/system/examples/state-button/submit.tsx:48`. Check: test `state-button.test.tsx`, a submit button submits only while idle; review of every StateButton inside a `form`.
  - Don't: `<form><Input /><StateButton status={status} onClick={save}>Save</StateButton></form>`
  - Do: `<form onSubmit={save}><Input /><StateButton type="submit" status={status}>Save</StateButton></form>`
- `rule/state-button-failure-reason-as-text`: When `status` is `failure`, write the reason as visible text beside the button, in a place that already holds a line so nothing moves, such as the card footer's meta line or the dialog's footer, and keep it until the next run, instead of a toast that times out, because the cross says only that it did not work and an error that needs action has to stay. Evidence: app 3/3 call sites show the failure as text, `docs/system/examples/state-button/default.tsx:47`, `docs/system/examples/alert-dialog/default.tsx:58` and `docs/system/examples/dialog/default.tsx:109`; principle heuristic: help users recognize, diagnose and recover from errors, the reason stays where the action is. Check: review of every host that sets `failure`.
  - Don't: `setStatus("failure"); toast("Something went wrong")`
  - Do: `{exporting.error !== null && <span className="text-destructive">You are offline. Try again.</span>}` in the line beside the button
- `rule/state-button-retry-in-place`: When the action fails, let the next press of the same button run it again, by calling `run()` from `useAction` in `onClick` with no check on `status`, instead of disabling the button or waiting for the status to return to idle, because the person has just read the reason beside the button and the retry is the next thing they do, and a button that ignores that press reads as broken. Evidence: measured `aria-disabled="true"` for 1.6s after "Not saved" in the settings scene before this fix, `docs/research/2026-10-16-first-principles.md` defect 6; person D39. Check: test `state-button.test.tsx`, success and failure render no `aria-disabled` and a failed submit keeps `type="submit"`; review of every `onClick` on a StateButton.
  - Don't: `<StateButton status={save.status} disabled={save.status === "failure"} onClick={() => void save.run()}>Save</StateButton>`
  - Do: `<StateButton status={save.status} onClick={() => void save.run()}>Save</StateButton>`

### Content
- Follows `rule/writing-button-verb`.
- Follows `rule/writing-status-verb-ing`.
- `rule/state-button-result-words`: When `successLabel` or `failureLabel` is set, write the label's verb as a past participle, such as "Exported", or "Not" and the participle, such as "Not exported", instead of "Success", "Error" or a sentence, because the word is shown beside its glyph inside the box the idle label sized and read once as a status, so it has to name what happened in one or two words. Evidence: app 4/4 StateButton examples that set both words follow it, `docs/system/examples/state-button/default.tsx:53-54`, every row of `docs/system/examples/state-button/matrix-status-variant.tsx`, "Sent" and "Not sent" in `docs/system/examples/field/in-form.tsx:89-90`; principle heuristic: match between system and the real world, the result names the action. Check: test `state-button.test.tsx`, a result shows its glyph and its word; review of every `successLabel` and `failureLabel`; lint copy/casing on the status slot (scripts/copy-check.mjs).
  - Don't: `<StateButton status={status} successLabel="Success" failureLabel="Error">Send 3 invites</StateButton>`
  - Do: `<StateButton status={status} successLabel="Sent" failureLabel="Not sent">Send 3 invites</StateButton>`

### Anti-slop
- `rule/state-button-no-label-swap`: When the action runs, keep `children` as the idle label and let `status` show the progress, instead of a ternary that writes "Saving" into `children`, because the idle label is the box's width and the one accessible name, and a new label mid-action moves the box and renames the control. Evidence: person D2; measured every status of each label at the same box, 117.28 by 36px for "Save changes", `.design-system/evidence/state-button/widths.json`. Check: lint trap/loading-label-swap (scripts/check-system.mjs); test `state-button.test.tsx`, the box is held by the label in the flow.
  - Don't: `<StateButton status={status}>{status === "pending" ? "Saving" : "Save"}</StateButton>`
  - Do: `<StateButton status={status} pendingLabel="Saving">Save changes</StateButton>`
- `rule/state-button-no-second-announcement`: When the action succeeds in place, let the check and `successLabel` report it and add no toast, instead of a toast that says the same thing, because two live regions read one result twice. Evidence: principle wcag: 4.1.3 Status messages, one message per change of status; single use `docs/system/examples/state-button/default.tsx:30`, which raises no toast. Check: review of every host that sets `success` in place.
  - Don't: `setStatus("success"); toast("Changes saved")`
  - Do: `setStatus("success")`

### Limits
- `rule/state-button-label-length`: When you write the three status words, keep each one no wider than the idle label less 22px, the 16px glyph and its 6px gap, instead of a word as long as or longer than the label, because the idle label sets the box: a pending or success word that does not fit beside its glyph drops to a clipped second row and leaves the bare glyph, and a failure word that does not fit drops the cross and is cut at its end; the status line still announces the word, but a sighted reader sees only the glyph or the start of the word. At 14px, "Save changes" holds "Saving", "Saved" and "Not saved"; "Rename watchlist" holds "Renaming", "Renamed" and "Not renamed"; "Retry" holds none of "Retrying", "Done" or "Failed", so it shows the spinner alone while the status line says "Retrying", and when it fails, "Failed", 38.4px in a 35.6px row, cut at its end on the wash. Evidence: measured on the docs at 1440 and 390 in light and dark, `.design-system/evidence/state-button/widths.json`, and at 320 and at 200% text, `docs/research/2026-10-16-break-ui-inputs.md`. Check: probe the stress page `/stress/state-button` at 320 with the worst data; review of every StateButton's words against its label.
  - Don't: `<StateButton status={status} pendingLabel="Renaming" failureLabel="Not renamed">Rename</StateButton>`
  - Do: `<StateButton status={status} pendingLabel="Renaming" failureLabel="Not renamed">Rename watchlist</StateButton>`

## Accessibility
Rests on `<button>` from `Button`, with a `role="status"` span beside it.

### Keyboard
| Key | Where focus is | Effect | Focus after | Checked by |
|---|---|---|---|---|
| Tab | before the button | focuses it and shows the ring | the button | by hand |
| Enter or Space | the button, idle | presses it and starts the action | the button, through pending and the result | by hand |
| Enter or Space | the button, pending | nothing; the handler returns early | the button | by hand |
| Enter or Space | the button, success or failure | presses it and runs the action again; after a failure this is the retry | the button | by hand |
| Enter | a field in the form, `type="submit"`, idle | submits the form | the button or where the host sends it | by hand |
| Enter | a field in the form, pending | nothing; the button is `type="button"` while pending | the field | test |

### ARIA
| Part | Role | Accessible name from | States and properties | Announced | Checked by |
|---|---|---|---|---|---|
| root | button | `children`, the idle label, in every status | `aria-busy` and `aria-disabled` while pending only; `disabled` from the caller while idle | the name and role on focus, with busy or dimmed while pending, in the screen reader's words | test |
| painted copy | none | hidden, `aria-hidden="true"` | none | nothing; the Spinner's own status text sits inside it and is not read | test |
| status | status | `pendingLabel`, `successLabel` or `failureLabel`; empty while idle | polite live region | the word once, when `status` changes | test |

Contrast: the default fill measured 6.07 to 1, white on `--primary`, and the secondary fill 15.42 to 1, in the showcase's example frame, .design-system/evidence/state-button/grow-390.json. The destructive wash, which every failure takes, is the Button's: `--destructive` on its 10 percent wash is 4.7 to 1 over the page by the token's own note, not measured here.

## Tokens
| Part | State | Token |
|---|---|---|
| root | all | the Button's: `--control`, `--r-control`, `--t-press`, `--curve`, `--ring` |
| root | failure, every variant | the destructive look: `--destructive` at 10 percent (20 in dark), `--destructive` |
| copy | success, destructive | `--foreground` |
| copy | settling | `springs.settle`, `times.pop`, `curves.out`, `distances.settle` from `registry/cobalt/lib/motion.ts` |
| spinner | pending | `currentColor`, 16px (`size-4`), shown after `SPINNER_DELAY_MS` and kept `SPINNER_MINIMUM_MS` |
| default | rest and hover | `--primary`, `--primary-foreground`, `--primary-hover` |
| secondary | rest and hover | `--secondary`, `--secondary-foreground`, `--muted-hover` |
| destructive | rest | `--destructive` at 10 percent, `--destructive` |

## Related
- Button: the button underneath, for an action that answers at once.
- Spinner: the ring that shows while pending.
- Dialog: holds open while its StateButton is pending, through `DialogContent status`.
- AlertDialog: the destructive confirm whose action is a StateButton.
- Toaster: the result that lands away from the control, when it does.
- IconSwap: trades two glyphs in one fixed slot, for an action that answers at once.
- TextSwap: changes a word in place, such as Pause and Resume.
- Swap: content leaving and arriving with a direction, on the same settle spring.
- IconButton: an icon action that answers at once.
- Progress: how much of a known amount is done, outside the button.
- Skeleton: content on its way, held in its own slot.
- PageProblem: a page that could not load, with the reason and a way to try again.
- SaveLine: a quiet line saying a form's changes are saving, saved or not saved.
