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

## Description
A short message about something that happened in the background.

`import { Toaster, toast } from "@/components/cobalt/ui/toaster"`, source `registry/cobalt/ui/toaster.tsx`, status `ready-with-gaps`.
Foundation: `shadcn sonner (base-luma, base)`. Traps checked: `trap/toast-errors`, `trap/toast-timer`, `trap/live-region-double`, `trap/reduced-motion-ignored`, `trap/motion-overshoot`, `trap/motion-layout-property`, `trap/motion-blocks-input`, `trap/surface-double-edge`, `trap/safe-area`, `trap/viewport-height` (n/a: the region is fixed to the bottom edge with an offset in px and reads no viewport unit), `trap/color-only-status` (n/a: the system styles no toast type, so the words carry the result and no colour does), `trap/numbers-shift` (n/a: a toast carries no changing number), `trap/loop-offscreen` (n/a: nothing loops), `trap/motion-restart` (n/a: a second `toast()` is a new element, not a retrigger).

### Foundation
| Given by the foundation | Added by the team |
|---|---|
| Sonner 2.0.8: a `section` live region (`aria-live="polite"`, `aria-relevant="additions text"`, `tabindex="-1"`) named by `containerAriaLabel` plus the Alt+T hotkey that focuses it, a list of `li` toasts each focusable, a stack of at most 3 visible toasts that expands under the pointer or on the hotkey, a 4000ms lifetime that pauses under the pointer and while the tab is hidden, a close button that hangs half off the toast's corner as a 20px circle, swipe to dismiss, `toast()` with `description`, `action`, `cancel`, `duration` and `closeButton`, and its own motion (`transform`, `opacity` and `height` over 400ms on `ease`) | The `label` prop as the region's name with the English default "Notifications" (D6); the theme read from `useIsDark` so a dark page gets a dark toast; the region portalled into the system's portal container through `useCobaltPortal`, so a toast keeps every token and sits beside, not under, a modal's inert page (`registry/cobalt/ui/toaster.tsx:159`); only the first Toaster mounted renders, so two mounted at once (a layout and a page, two examples on one page) show each toast once (`registry/cobalt/ui/toaster.tsx:95-96`); the lifetime paused while keyboard focus is inside a toast as well as under the pointer, and running on once both have left, through sonner's own timer, so an Undo never expires under the keyboard (`registry/cobalt/ui/toaster.tsx:54-66`); `expand` always on, so the stack never collapses into sonner's scaled pile; a toast past the visible count hidden at once with `visibility: hidden` and no shadow; the bottom-right corner at 20px with a 10px gap, and on a phone 148px from the bottom with 16px sides so a toast clears a tab bar and a composer (`registry/cobalt/ui/toaster.tsx:102-108`); the floating surface, `bg-popover` on `rounded-3xl` like every popup, with the lighter `shadow-raised` and no border, padded by `--pad-popup`, so a button in its corner, at a control's corner, is concentric with it (D38), as an alert's action is; the words 18px in and the buttons centred on them: in a one-line toast the 36px buttons sit `--pad-popup` from every edge, concentric with the corner, and in a toast with a description they hold the middle of its height and sit as far from the end edge as from the top and bottom, 17px (`has-data-description:has-data-button:pe-[calc(var(--pad-popup)+(58px-var(--control))/2)]`, measured 17/17/17 at 1440 and 390; before, 6px from the top and end over a 28px empty strip), 14px text in place of sonner's 13px, the title at `text-base font-semibold` like every other title and a muted description, and the action and cancel buttons at the control height, `min-h-(--control)` and `rounded-(--r-control)`, growing with their text rather than clipping it, their colour changing on `--t-press` in place of sonner's 400ms and 200ms, the cancel a ghost with no fill; the close button the system's 36px ghost icon button with the system's X, inside the toast's top corner at `--pad-popup`, concentric with it, the actions keeping clear of it (`registry/cobalt/ui/toaster.tsx:149-151`); the words keep at least 192px, so an action that would squeeze them moves to its own line at the trailing edge, and the toast's width is sonner's 356px written in the spacing scale, so it widens when someone raises their text size (`registry/cobalt/ui/toaster.tsx:138`, `registry/cobalt/ui/toaster.tsx:115`) |

## Examples
The toaster mounted once, with reports that archive at once and offer Undo for ten seconds, and an export that says when it is ready.

Real uses, 0 call sites (`rg -n "<Toaster\b" app registry --glob '!registry/cobalt/ui/*'`): the showcase chrome mounts no Toaster of its own yet, and the examples folder does not count.

Uses inside the registry, which other components build on (planned as product uses once the first screen lands on the system):
- None render it. The registry's skill names `toast()` copy as the shape a result takes, `registry/cobalt/SKILL.md:128`.

The docs shell mounts the one Toaster for every page, as a product mounts it once at the root (`rule/toaster-mount-once`). default.tsx keeps its own mount to show where it goes; only the first Toaster mounted renders, so it adds no second copy. Every other example calls `toast()` only. Before this, each example mounted its own and one call rendered three toasts, measured in `.design-system/evidence/toaster/measure-390.json`.

### Example files
| File | Covers | Caption |
|---|---|---|
| `docs/system/examples/toaster/default.tsx` | default | Archiving has Undo; an export says when it is ready |
| Not applicable: the stack is reached by pressing any button in default.tsx three times | state:stacked | Up to 3 toasts at full size, 10px apart, nothing scaled |
| Not applicable: the stack is always expanded; the pointer over it pauses the timers | state:expanded | Every visible toast at full size, 10px apart |
| Not applicable: the pointer resting on any toast, or Tab into one, pauses it | state:paused | The toast stays until the pointer and focus leave |
| Not applicable: leaving follows the 4000ms lifetime, a swipe or the action on any example | state:leaving | The toast slides out over `--t-arrive` and fades over `--t-fade` |
| `docs/system/examples/toaster/persistent.tsx` | state:persistent | A failure that stays until you dismiss it or retry |
| `docs/system/examples/toaster/in-dialog.tsx` | composition:Dialog | A toast raised from an open dialog shows above it |

Example: Archiving has Undo; an export says when it is ready (`docs/system/examples/toaster/default.tsx`)

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

import { Button } from "@/components/cobalt/ui/button";
import { StateButton } from "@/components/cobalt/ui/state-button";
import { Toaster, toast } from "@/components/cobalt/ui/toaster";
import { Presence, PresenceRow } from "@/lib/cobalt/presence";
import { useAction } from "@/lib/cobalt/use-action";

// Stands in for your API call that starts an export. It answers after 900ms, and fails while the
// browser is offline or the address has ?network=offline. The file itself is ready 2.5 seconds later.
const startExport = () =>
  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();
    }, 900),
  );

// Stands in for your API call that archives. It answers after 800ms, and fails the same way.
const archive = () =>
  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();
    }, 800),
  );

const reports = ["Q1 holdings report", "Q2 holdings report", "Q3 holdings report"];

// The finished file: computed here so nothing is fetched.
function download() {
  const rows = reports.map((report, i) => `${report},${186 + i * 4},${(4.1 + i * 0.35).toFixed(2)}`);
  const url = URL.createObjectURL(
    new Blob([["report,holdings,net_assets_bn", ...rows].join("\n")], { type: "text/csv" }),
  );
  const link = document.createElement("a");
  link.href = url;
  link.download = "holdings-reports.csv";
  link.click();
  URL.revokeObjectURL(url);
}

// The row's own box, so the item's height can close to nothing around it.
const row = "flex min-h-(--control) items-center justify-between gap-3 text-sm";

export default function Example() {
  const [archived, setArchived] = useState<string[]>([]);
  const buttons = useRef(new Map<string, HTMLButtonElement>());
  const restoreAll = useRef<HTMLButtonElement>(null);
  const exporting = useAction(async () => {
    await startExport();
    // You may be anywhere by the time the file is ready, so a toast brings it to you.
    setTimeout(() => {
      toast("Export ready", {
        description: "Three reports, as a spreadsheet.",
        action: { label: "Download", onClick: download },
      });
    }, 2500);
  });
  const shown = reports.filter((report) => !archived.includes(report));
  return (
    <div className="grid w-full max-w-sm gap-4">
      <Toaster />
      {/* The list keeps the room of every report, so archiving one moves nothing below it. */}
      <ul className="flex min-h-[calc(var(--control)*3)] flex-col">
        <Presence>
          {shown.map((report, index) => (
            <PresenceRow key={report}>
              <div className={row}>
                {report}
              <Button
                ref={(button: HTMLButtonElement | null) => {
                  if (button) buttons.current.set(report, button);
                  else buttons.current.delete(report);
                }}
                variant="ghost"
                size="sm"
                aria-label={`Archive ${report}`}
                onClick={(event) => {
                  // Archiving can be undone, so it happens at once. The row is gone, so the toast
                  // reports it, and Undo stays ten seconds: long enough to notice and reach it.
                  const restore = () => setArchived((list) => list.filter((item) => item !== report));
                  setArchived((list) => [...list, report]);
                  // Focus was on the button that just left; it goes to the next report's, or to
                  // Restore all once none is left.
                  if (document.activeElement === event.currentTarget) {
                    const next = shown[index + 1] ?? shown[index - 1];
                    if (next) buttons.current.get(next)?.focus();
                    else requestAnimationFrame(() => restoreAll.current?.focus());
                  }
                  // The request runs behind the toast; if it fails, the row comes back and a toast says so.
                  archive().catch(() => {
                    restore();
                    toast(`${report} is back`, { description: "It was not archived. You are offline." });
                  });
                  toast(`${report} archived`, {
                    duration: 10_000,
                    action: { label: "Undo", onClick: restore },
                  });
                }}
                >
                  Archive
                </Button>
              </div>
            </PresenceRow>
          ))}
          {shown.length === 0 && (
            <PresenceRow key="none">
              <div className={row}>
                <span className="text-muted-foreground">Every report is archived.</span>
                <Button ref={restoreAll} variant="ghost" size="sm" onClick={() => setArchived([])}>
                  Restore all
                </Button>
              </div>
            </PresenceRow>
          )}
        </Presence>
      </ul>
      <div className="flex flex-wrap items-center gap-3">
        <StateButton
          variant="secondary"
          status={exporting.status}
          pendingLabel="Starting"
          successLabel="Started"
          failureLabel="Not started"
          onClick={() => void exporting.run()}
        >
          Export reports
        </StateButton>
        {exporting.error !== null && (
          <p className="text-sm text-destructive">
            The export did not start. Check your connection and try again.
          </p>
        )}
      </div>
    </div>
  );
}
```

Example: A toast raised from an open dialog shows above it (`docs/system/examples/toaster/in-dialog.tsx`)

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

import { Button } from "@/components/cobalt/ui/button";
import {
  Dialog,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/cobalt/ui/dialog";
import { toast } from "@/components/cobalt/ui/toaster";
import { Presence, PresenceRow } from "@/lib/cobalt/presence";

// Stands in for your API call. It answers after 800ms, 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();
    }, 800),
  );

const people = [
  { name: "Mira Okafor", role: "Can edit" },
  { name: "Jonas Berg", role: "Can view" },
  { name: "Priya Nair", role: "Can view" },
];

export default function Example() {
  const [removed, setRemoved] = useState<string[]>([]);
  const buttons = useRef(new Map<string, HTMLButtonElement>());
  const done = useRef<HTMLButtonElement>(null);
  const shown = people.filter((person) => !removed.includes(person.name));
  return (
    <Dialog>
      <DialogTrigger render={<Button variant="secondary" />}>Share watchlist</DialogTrigger>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Share Credit funds</DialogTitle>
          <DialogDescription>
            {shown.length === 0
              ? "Only you can open this watchlist."
              : `${shown.length} ${shown.length === 1 ? "person" : "people"} can open this watchlist.`}
          </DialogDescription>
        </DialogHeader>
        {/* The list keeps the room of everyone it started with, so the dialog keeps its size and its
            title and Done stay where they are. */}
        <ul className="flex min-h-[calc(var(--control)*3)] flex-col text-sm">
          <Presence>
            {shown.map((person, index) => (
              <PresenceRow key={person.name}>
                <div className="flex min-h-(--control) items-center justify-between gap-3">
                  <span className="min-w-0 truncate">{person.name}</span>
                <span className="flex shrink-0 items-center gap-2 text-muted-foreground">
                  {person.role}
                  <Button
                    ref={(button: HTMLButtonElement | null) => {
                      if (button) buttons.current.set(person.name, button);
                      else buttons.current.delete(person.name);
                    }}
                    variant="ghost"
                    size="sm"
                    aria-label={`Remove ${person.name}`}
                    onClick={(event) => {
                      // Taking access away can be undone, so it happens at once; the toast rises above
                      // the dialog with Undo for ten seconds.
                      const restore = () => setRemoved((was) => was.filter((name) => name !== person.name));
                      setRemoved((was) => [...was, person.name]);
                      // Focus was on the button that just left; it goes to the next person's, or to Done.
                      if (document.activeElement === event.currentTarget) {
                        const next = shown[index + 1] ?? shown[index - 1];
                        (next ? buttons.current.get(next.name) : done.current)?.focus();
                      }
                      // The request runs behind the toast; if it fails, they come back and a toast says so.
                      request().catch(() => {
                        restore();
                        toast(`${person.name} still has access`, {
                          description: "You are offline. Try again.",
                        });
                      });
                      toast(`${person.name} removed`, {
                        description: "They can no longer open the watchlist.",
                        duration: 10_000,
                        action: { label: "Undo", onClick: restore },
                      });
                    }}
                  >
                    Remove
                  </Button>
                  </span>
                </div>
              </PresenceRow>
            ))}
          </Presence>
        </ul>
        <DialogFooter>
          <DialogClose ref={done} render={<Button variant="ghost" />}>
            Done
          </DialogClose>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
```

## Variants
Not applicable: the toaster has one form. A toast's title, description, action and duration come from the `toast()` call, and the system styles no toast type apart from the one surface.

## States
| State | Trigger | What the user can do | Shown by, besides color | Checked by |
|---|---|---|---|---|
| empty | the Toaster mounts with nothing to say | nothing; the region is in the tree and silent | an empty `section`, no list and no announcement | test |
| visible | `toast()` from the caller | read it, press its action, swipe it away, focus it or hover it to pause | the toast at the bottom edge, 358px wide at 390, its title announced once by the polite region | screenshot |
| stacked | a second `toast()` within the lifetime | read each one, swipe one away | up to 3 toasts at full size, 10px apart; a fourth and later wait with `visibility: hidden` and no shadow, measured 0 hidden toasts painted after 8 quick toasts (`.design-system/evidence/toaster/toasts-spam.mjs`) | screenshot |
| expanded | always, through `expand` | read every visible toast, press any action | every visible toast at full height, 10px apart, `data-expanded="true"`, measured `transform` a pure translate on every toast | by hand |
| paused | the pointer on the stack, keyboard focus inside a toast, or the tab hidden | finish reading, reach the action | nothing visible; the toast simply stays, measured an Undo toast still present 11.5s into its 10s with focus inside, and gone 9.5s after focus left (`.design-system/evidence/toaster/focus-and-close.json`) | by hand |
| persistent | `duration: Infinity` on the call | press the action, or `closeButton` when set; swipe | the toast stays until dismissed; with `closeButton`, the system's ghost X in its top corner, 36px, 6px in from the edge, inside the toast | screenshot |
| leaving | the lifetime ends, a swipe, the action or `toast.dismiss()` | nothing; a new `toast()` is a new element | `data-removed="true"`, the toast sliding out over 220ms and fading over 150ms, then unmounted by sonner | by hand |

Example: A failure that stays until you dismiss it or retry (`docs/system/examples/toaster/persistent.tsx`)

```tsx
import { StateButton } from "@/components/cobalt/ui/state-button";
import { toast } from "@/components/cobalt/ui/toaster";
import { useAction } from "@/lib/cobalt/use-action";

// Stands in for your export. Starting it answers after 900ms, and fails while the browser is offline
// or the address has ?network=offline. The export then runs on the server for 2.5 seconds; every
// other run fails, as if the server ran out of time, so a retry goes through.
const startExport = () =>
  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();
    }, 900),
  );
let runs = 0;
const runExport = () =>
  new Promise<void>((resolve, reject) =>
    setTimeout(() => (runs++ % 2 === 0 ? reject(new Error("timed out")) : resolve()), 2500),
  );

// The watchlist the export writes, one row per fund, so Download saves a real file.
const watchlist: [string, number][] = [
  ["Harbour Large Cap Core", 0.42],
  ["Northgate Credit Opportunities", 0.88],
  ["Calder Global Equity", 0.61],
  ["Alder Short Duration", 0.25],
  ["Fjord Nordic Small Cap", 0.95],
  ["Meridian Frontier Markets", 1.12],
  ["Albion European Dividend", 0.54],
  ["Kestrel Japan Value", 0.67],
  ["Monsoon India Growth", 0.89],
  ["Evergreen Climate Bond", 0.31],
  ["Andes Latin America Equity", 0.97],
  ["Harbour Treasury Index", 0.05],
];

function download() {
  const rows = watchlist.map(([fund, ratio]) => `${fund},${ratio.toFixed(2)}%`);
  const url = URL.createObjectURL(
    new Blob([["fund,expense_ratio", ...rows].join("\n")], { type: "text/csv" }),
  );
  const link = document.createElement("a");
  link.href = url;
  link.download = "watchlist.csv";
  link.click();
  URL.revokeObjectURL(url);
}

// The failure happened after you looked away, so its toast stays until you act on it.
function watch() {
  runExport().then(
    () =>
      toast("Export ready", {
        description: `${watchlist.length} funds, as a spreadsheet.`,
        action: { label: "Download", onClick: download },
      }),
    () =>
      toast("Export failed", {
        description: "The server ran out of time. Nothing was written.",
        duration: Infinity,
        closeButton: true,
        action: { label: "Retry", onClick: watch },
      }),
  );
}

export default function Example() {
  const exporting = useAction(async () => {
    await startExport();
    watch();
  });
  return (
    <div className="flex flex-wrap items-center gap-3">
      <StateButton
        variant="secondary"
        status={exporting.status}
        pendingLabel="Starting"
        successLabel="Started"
        failureLabel="Not started"
        onClick={() => void exporting.run()}
      >
        Export watchlist
      </StateButton>
      {exporting.error !== null && (
        <p className="text-sm text-destructive">
          The export did not start. Check your connection and try again.
        </p>
      )}
    </div>
  );
}
```

### State precedence
- Stacked and expanded: expanded wins. `expand` keeps every visible toast at its full height, so sonner's scaled stack does not appear.
- Visible and paused: both show. The toast looks the same; only its timer stops, measured as a toast still present 5.8s after it was raised under the pointer in `.design-system/evidence/toaster/measure-390.json`.
- Paused and leaving: leaving wins. A swipe or the action removes a paused toast at once.
- Persistent and stacked: both show. A persistent toast keeps its place in the stack while timed ones leave around it.
- Leaving and a new `toast()`: both show. The new toast enters below while the old one fades, each its own element.
- Expanded and focus inside: both show, and focus inside pauses the timer. Sonner pauses only for the pointer and a hidden tab, so the Toaster tells it the stack is entered when focus comes into a toast and left when focus and the pointer have both gone (`trap/toast-timer`); before, 0 toasts were left 5.8s after focusing one (`.design-system/evidence/toaster/measure-390.json`).

### Motion
| Trigger | Kind | Preset | Properties | Reduced motion |
|---|---|---|---|---|
| enter | announce | `--t-arrive` (220ms) for transform and `--t-fade` (150ms) for opacity on `--curve`, set in styles.css over sonner's own 400ms `ease`; measured as two `CSSTransition`s at entry, 220ms and 150ms on cubic-bezier(0.23, 1, 0.32, 1) (.design-system/evidence/toaster/measure-390.json, re-run after the override) | transform (from below), opacity | sonner sets `transition: none` and `animation: none` on every toast under `prefers-reduced-motion`, so the toast appears in place with no fade; measured `transition-property: none` under reduce in `.design-system/evidence/toaster/measure-390.json` |
| leave | announce | the same transition back: `--t-arrive` for transform, `--t-fade` for opacity, then sonner unmounts the toast | transform, opacity | none; the toast vanishes in place |
| a Banner opens or leaves | announce | `--t-settle` on `--curve-settle`: the stack rises by what the banner takes above the stack's own offset (`--banner-clearance`, written by the banner), and comes down after the banner has faded | translate of the stack | the stack moves at once |
| stack lift and expand | announce | `--t-arrive` on `--curve` for transform and `height`, `--t-fade` for opacity; the height of a leaving toast's slot is still a layout property in motion, kept because sonner positions the stack by it (`trap/motion-layout-property`, accepted) | transform, height, opacity | none |

## Props

<!-- Props generated from registry/cobalt/ui/toaster.tsx with TypeScript by scripts/props-table.mjs -->
| Prop | Type | Default | Purpose |
|---|---|---|---|
| `label?` | `string` | `"Notifications"` | The accessible name of the region the toasts live in. |

Also accepts from sonner: `closeButton`, `customAriaLabel`, `dir`, `duration`, `expand`, `gap`, `hotkey`, `icons`, `id`, `invert`, `mobileOffset`, `offset`, `position`, `richColors`, `swipeDirections`, `toastOptions`, `visibleToasts`.

`label` is the region's accessible name, the English default "Notifications"; sonner appends its hotkey, so a screen reader hears "Notifications alt+T". Every other sonner `ToasterProps` passes through except `theme`, which follows the page, and `containerAriaLabel`, which `label` replaces: `position`, `gap`, `offset` and `mobileOffset` are set by the team and can be overridden, `duration` sets the lifetime for every toast, `closeButton` adds a dismiss button to every toast, `visibleToasts` caps the stack, and `expand` is on by default so the stack stays open. The words of each toast come from `toast()` from `sonner`, not from the Toaster.

## Usage

### When to use
- Something finished while you were elsewhere on the page: an export is ready, a background sync failed, an item was archived from a swipe and can be undone.
- A result has no control of its own left on screen to report it, such as after a dialog closed or a row was removed.

### When not to use
- The control that was pressed is still on screen and can report its own result. Use StateButton instead, which settles into "Saved" in place.
- The result is an error you must act on in a form. Use Dialog's `DialogError`, or Field's `FieldError` on the field, instead, which stay until fixed.
- The wait itself needs reporting, not its end. Use Spinner inside the control, or ListBody over the rows, instead.
- The message is a confirmation that needs a decision. Use AlertDialog instead.

### Rules
- `rule/toaster-mount-once`: When an app raises toasts, mount exactly 1 `Toaster` at the root inside `CobaltPortalProvider` and call `toast()` from `sonner` anywhere below, instead of mounting a `Toaster` beside each caller, because every mounted Toaster renders every toast and runs its own timer, so two of them show the same message twice and the copy nobody is hovering removes the one being read. Evidence: measured 3 toasts and 3 live regions per `toast()` call on the showcase page, which mounts one per example, `.design-system/evidence/toaster/measure-390.json`; principle wcag: 4.1.3 Status messages, one message is announced once (`trap/live-region-double`). Check: lint `rule/toaster-mount-once` counts `<Toaster` tags in `app` and fails above 1.
  - Don't: `function ExportPanel() { return <><Toaster /><Button onClick={() => toast("Export ready")}>Export</Button></>; }`
  - Do: `<CobaltPortalProvider><App /><Toaster /></CobaltPortalProvider>` once, and `toast("Export ready")` in `ExportPanel`
- `rule/toaster-not-for-the-pressed-control`: When the control that starts the action stays on screen until it finishes, report the result through `StateButton` with `status` from `registry/cobalt/lib/status.ts` instead of a `toast()`, because the eye is already on the control, and a toast at the bottom edge makes you look away from where they are. Evidence: person D2; principle heuristic: visibility of system status, feedback appears where attention is; single use `registry/cobalt/ui/state-button.tsx:55`, the one control in the registry that reports its own result. Check: review of every `toast()` call for a `StateButton` that could carry it.
  - Don't: `<Button onClick={async () => { await save(); toast("Saved"); }}>Save</Button>`
  - Do: `<StateButton status={status} pendingLabel="Saving" successLabel="Saved" onClick={save}>Save</StateButton>`
- `rule/toaster-failure-persists`: When a toast reports a failure you can do something about, pass `duration: Infinity` and an `action` that retries or opens the place to fix it, instead of the 4000ms default, because a timed toast leaves before you look back, and a failure with nothing to press is a dead end. Evidence: principle wcag: 2.2.1 Timing adjustable, a message that needs a response is not on a timer (`trap/toast-errors`); measured 4268ms lifetime for a default toast, `.design-system/evidence/toaster/measure-390.json`. Check: lint `rule/toaster-failure-persists` flags `toast.error(` and `toast(` whose first argument contains "failed" or "could not" without `duration: Infinity`.
  - Don't: `toast("Export failed")`
  - Do: `toast("Export failed", { duration: Infinity, action: { label: "Retry", onClick: retry } })`
- `rule/toaster-persistent-can-be-dismissed`: When a toast has `duration: Infinity`, give it an `action` or `closeButton: true`, because sonner adds no close control by default and the only other way out is a swipe, which a keyboard has no path to. Evidence: principle input: keyboard, every state reachable by pointer has a keyboard path; principle wcag: 2.1.1 Keyboard. Check: lint `rule/toaster-persistent-can-be-dismissed` flags `duration: Infinity` with neither `action` nor `closeButton` in the same call.
  - Don't: `toast("Sync paused", { duration: Infinity })`
  - Do: `toast("Sync paused", { duration: Infinity, action: { label: "Resume", onClick: resume } })`
- `rule/toaster-undo-not-confirm`: When an action can be reversed within the toast's lifetime, such as archiving or removing one item, do it at once and offer `action: { label: "Undo" }` in the toast, instead of an `AlertDialog` before it, because the dialog costs everyone a decision to save those who change their mind, and the toast costs only them one press. Evidence: principle heuristic: user control and freedom, an undo beats a confirmation for a reversible action; single use `docs/system/examples/toaster/default.tsx:99-101`, the archive with "Undo". Check: review of `AlertDialog` call sites whose action is reversible.
  - Don't: `<AlertDialog open={confirming}><AlertDialogAction onClick={archive}>Archive event</AlertDialogAction></AlertDialog>` for an archive you can undo
  - Do: `archive(id); toast("Event archived", { action: { label: "Undo", onClick: () => restore(id) } })`
- `rule/toaster-undo-lasts`: When a toast offers Undo, pass `duration: 10_000` or more, or `duration: Infinity` with `closeButton: true`, instead of the 4000ms default, because the person has to notice the toast, read it, decide and reach the button, and the timer runs while they look for it; it pauses only once the pointer or focus is on the stack. Evidence: principle wcag: 2.2.1 Timing adjustable, a time limit gives at least 20 seconds or a way to extend it, and Undo is the one toast whose timer takes something away; measured 4268ms lifetime for a default toast, `.design-system/evidence/toaster/measure-390.json`; single use `docs/system/examples/toaster/default.tsx:100-101`. Check: review of every `toast(` call with an `action` whose `label` is "Undo".
  - Don't: `toast("Event archived", { action: { label: "Undo", onClick: () => restore(id) } })`
  - Do: `toast("Event archived", { duration: 10_000, action: { label: "Undo", onClick: () => restore(id) } })`

### Content
- Follows `rule/writing-toast-result`.
- Follows `rule/writing-no-exclamation`.
- Follows `rule/writing-heading-sentence-case`.
- `rule/toaster-description-adds-a-fact`: When a toast has a `description`, it carries one fact the title does not, such as a count, a place or a time, in one sentence ending in a period, instead of restating the title, because the description is muted and read second, and a repeated title doubles what the polite region announces. Evidence: principle heuristic: aesthetic and minimalist design, every line carries information; single use `docs/system/examples/toaster/default.tsx:58`, "Three reports, as a spreadsheet." under "Export ready". Check: review of `description` strings in `toast()` calls against their titles.
  - Don't: `toast("Export ready", { description: "Your export is ready." })`
  - Do: `toast("Export ready", { description: "Twelve rows, as a spreadsheet." })`
- `rule/toaster-action-is-a-verb`: When a toast has an `action`, its `label` is one verb, or a verb and its object, such as "Undo" or "Open folder", at most 12 characters, instead of "OK" or "Dismiss", because the action button is a 36px button at 14px text and a dismiss adds nothing a swipe or the timer does not. Evidence: principle heuristic: match between system and the real world, the label names what happens; single use `docs/system/examples/toaster/default.tsx:101`, "Undo". Check: lint copy/template on the `action.label` slot (scripts/copy-check.mjs).
  - Don't: `toast("Item archived", { action: { label: "OK", onClick: () => undefined } })`
  - Do: `toast("Item archived", { action: { label: "Undo", onClick: restore } })`

### Anti-slop
- `rule/toaster-no-typed-toasts`: When a result is reported, call `toast()` with the words instead of `toast.success()`, `toast.error()` or `richColors`, because the system draws every toast on the one `--popover` surface and the words carry the result, so a green or red toast with an icon is the only coloured surface on the page and says nothing the title does not. Evidence: person D13; app 0/6 `toast()` calls in the examples use a typed variant (`rg -n "toast\." docs/system/examples/toaster`). Check: lint `rule/toaster-no-typed-toasts` flags `toast.success(`, `toast.error(`, `toast.warning(`, `toast.info(` and `richColors`.
  - Don't: `toast.success("Changes saved")`
  - Do: `toast("Changes saved")`
- `rule/toaster-no-toast-while-pending`: When an action starts, raise no "Saving" or `toast.loading()` for it, and report only its end, because the pending state belongs inside the control's box (`StateButton`) or over the rows (`ListBody`), and a toast for the start and another for the end announce the same action twice. Evidence: person D2; principle wcag: 4.1.3 Status messages, one change, one announcement. Check: lint `rule/toaster-no-toast-while-pending` flags `toast.loading(` and `toast.promise(`.
  - Don't: `toast.promise(save(), { loading: "Saving", success: "Saved", error: "Failed" })`
  - Do: `<StateButton status={status} pendingLabel="Saving" successLabel="Saved" onClick={save}>Save</StateButton>`
- `rule/toaster-no-position-per-call`: When a toast is raised, leave `position`, `offset` and `mobileOffset` to the one mounted Toaster instead of passing `position` on the call, because the region sits 148px above the bottom edge on a phone to clear a tab bar and a composer, and a toast sent to another corner lands under the nav or the keyboard. Evidence: measured `--mobile-offset-bottom: 148px` with 16px sides and `--offset-bottom: 20px` on the mounted region, `.design-system/evidence/toaster/measure-390.json`; principle platform: one notification edge per app. Check: lint `rule/toaster-no-position-per-call` flags `position:` inside a `toast(` call.
  - Don't: `toast("Saved", { position: "top-center" })`
  - Do: `toast("Saved")`

### Limits
- `rule/toaster-description-length`: When a `description` would run past 97 characters at 390px, cut it to one fact or move the detail to the place the `action` opens, because at 98 characters the description takes a third line and the toast grows to 110px, and 3 of those expanded cover 350px, more than a third of a 390x844 screen. Evidence: measured two lines at 50 characters (90px toast) and three lines at 98 characters (110px toast) on a 330px text column, and 230px for 3 expanded two-line toasts against a 281px third, `.design-system/evidence/toaster/measure-390.json`. Check: lint `rule/toaster-description-length` measures `description` string literals in `toast()` calls.
  - Don't: `toast("Export ready", { description: "Twelve rows were written as a spreadsheet and saved to the shared folder beside last month's export for the whole team." })`
  - Do: `toast("Export ready", { description: "Twelve rows, as a spreadsheet.", action: { label: "Open", onClick: open } })`
- `rule/toaster-visible-three`: When more than 3 toasts are alive at once, keep `visibleToasts` at its default of 3 and let the rest wait behind, instead of raising it or calling `toast()` in a loop per item, because the fourth toast is invisible until one leaves, and a loop of 20 "Row saved" toasts holds the region for 80 seconds. Evidence: measured a visible cap of 3 with 6 toasts raised, 87px collapsed and 230px expanded at 390x844, `.design-system/evidence/toaster/measure-390.json`; principle heuristic: aesthetic and minimalist design, one message for one batch. Check: lint `rule/toaster-visible-three` flags `visibleToasts` above 3 and `toast(` inside a `.map(` or `for` body.
  - Don't: `rows.forEach((row) => toast(row.name + " saved"))`
  - Do: `toast(rows.length + " rows saved")`

## Accessibility
Rests on sonner's `section` live region and its `li` toasts.

### Keyboard
| Key | Where focus is | Effect | Focus after | Checked by |
|---|---|---|---|---|
| Alt+T | anywhere on the page | focuses the region; the stack is already expanded | the region (`tabindex="-1"`) | by hand |
| Tab | the region | moves to the first toast, then its action and cancel buttons | the toast, then its buttons | by hand |
| Enter or Space | a toast's action button | runs the action and dismisses the toast | the element focused before Alt+T, which sonner restores | by hand |
| Escape | the region or a toast | nothing; with `expand` on there is no collapsed stack to return to | where it was | by hand |
| Tab | into a toast | the toast's timer, and every other's, waits while focus is inside | the toast, then its buttons | by hand |
| Tab or Shift+Tab | out of the stack | the timers run on from where they stopped | the next or previous focusable | by hand |
| Enter or Space | a toast's close button | dismisses the toast | the element focused before, which sonner restores | by hand |

### ARIA
| Part | Role | Accessible name from | States and properties | Announced | Checked by |
|---|---|---|---|---|---|
| region | region (`section`) | `label`, default "Notifications", with sonner's " alt+T" appended | `aria-live="polite"`, `aria-relevant="additions text"`, `aria-atomic="false"`, `tabindex="-1"` | each new toast's title and description once, after the current speech | test |
| toast | none (`li`, `tabindex="0"`) | its title and description text | `data-expanded`, `data-removed`, `data-visible` | the text when focused | by hand |
| action and cancel | button | their `label` | none | the label and "button" on focus | by hand |
| close | button | "Close" | none | "Close, button" | by hand |

## Tokens
| Part | State | Token |
|---|---|---|
| toast | all | `--popover`, `--popover-foreground`, `--r-3xl`, `--elev-raised` through `shadow-raised` |
| description | all | `--muted-foreground` |
| toast | all | `--pad-popup` around the buttons; the words 18px in |
| action | all | `--primary`, `--primary-foreground`, `--r-control`, `--control` |
| cancel | rest | no fill, `--foreground`, `--r-control`, `--control` |
| cancel | hover | `--muted` |
| close | rest | no fill, the toast's ink, `--r-control`, `--control`, inset `--pad-popup` |
| close | hover | `--muted` |
| motion | enter, leave, stack | `--t-arrive`, `--t-fade`, `--curve` through the `[data-sonner-toast]` rule in styles.css |

## Related
- StateButton: the control that reports its own result in place.
- Pagination: the rows dimmed while the next page loads.
- AlertDialog: a decision before an action that cannot be undone.
- DialogError: a failure inside the form it belongs to.
- Spinner: the wait itself, inside a control.
- Empty: says what a list has none of, and offers the one next step, in the place where the rows would be.
- Alert: a message that stays on the page until its cause is fixed.
- Banner: a line at the foot of the window for news or a lost connection, until it is resolved.
- Inbox: the bell in a top bar that opens the person's notifications.
- SaveLine: a quiet line saying a form's changes are saving, saved or not saved.
