# Toast

An outcome nothing else on screen shows: three at most, stacked at the window's bottom end, opening into a list under the pointer. An agent toast adds a picture drawn from data.

Live variants: https://design.arcadia.is/components/toast

```tsx
import { Toast, Toaster, toast, createToastStore } from "@arcadia/ui";
```

## In context

Archive a draft, then use Undo in the toast.

```tsx
import { Button, toast } from "@arcadia/ui";

<Button variant="secondary" onClick={() => toast("Draft archived", { action: { label: "Undo", onClick: () => toast("Draft restored") } })}>
  Archive draft
</Button>
```

## When to use

Report background work or offer a quick way to undo.

## When not to use

Keep required decisions and form errors inline, where the work happens.

## Usage

```tsx
import { Button, toast } from "@arcadia/ui";

<Button variant="secondary" onClick={() => toast("Draft archived", { action: { label: "Undo", onClick: () => toast("Draft restored") } })}>
  Archive draft
</Button>
```

Mount one `Toaster` near the app root. Call `toast` from anywhere.

Repeating a visible message restarts its timer without adding another toast.

Three toasts show and three wait. Errors and actions take priority in the queue.

## Anatomy

- Glyph: Each variant's outline in its own ink, success, warning and error, or a spinner while it loads. A plain toast has none. A change of variant swaps the glyph in its box.
- Title: What happened, in the past tense, in one line: Body in `--text-1`.
- Description: One more fact, under it, in `--text-2`.
- Cancel, action and icon act: The kit buttons at the end: a quiet ghost cancel, a secondary action, and one icon act between them. Each closes the toast, then runs; a control with `dismiss: false` runs without closing it. A control's `label` is its accessible name unless `ariaLabel` overrides it; a blank `ariaLabel` is left out. An act with an `icon` draws as a kit IconButton, its `label` its tooltip and, with no `ariaLabel`, its accessible name. A control may also carry `name`, the act's own constant drawn as `data-action`. A control with a press name waits until its whole toast has stood still for 1.5 seconds, in the Button's disabled ink, and answers only a press the person saw the toast through: a pointer press on it, Enter or Space on focus a Tab gave it, or a screen reader's own press.
- Dismiss: The close button at the end, in every toast.
- The stack: Newest in front; up to two behind it, each set up a step and smaller, their words hidden. Three more wait their turn, undrawn.
- Picture: On an agent toast, one of seven drawn by the kit from data, in a slot of one width (56, and 40 compact) so every title starts on one edge. Its corner is the frame's less the padding (`nest`).
- Sender: On an agent toast, the agent that sent it: its picture and name in Caption above the title. A product's own notice has none.

## Examples

### Variants

Each tone except plain pairs its message with a glyph.

```tsx
import { Button, toast } from "@arcadia/ui";

<Button variant="secondary" onClick={() => toast("Agent archived", { description: "Pricing edge cases" })}>Plain</Button>
<Button variant="secondary" onClick={() => toast.success("Link copied")}>Success</Button>
<Button variant="secondary" onClick={() => toast.warning("The server is slow to answer", { description: "Changes are kept and sent when it answers." })}>Warning</Button>
<Button variant="secondary" onClick={() => toast.error("Couldn't delete the chat", { description: "500: internal error" })}>Error</Button>
<Button variant="secondary" onClick={() => toast.promise(new Promise((done) => setTimeout(done, 1600)), { loading: "Saving changes", success: "Changes saved", error: "Couldn't save the changes" })}>
  Promise
</Button>
<Button variant="secondary" onClick={() => toast("Card archived", { action: { label: "Undo", onClick: () => toast("Card restored") } })}>With an action</Button>
```

### The stack

Hover or Tab into the stack to open it and pause timers.

Swipe a toast toward the end or down to throw it away; a short swipe springs back.

```tsx
import { useState } from "react";
import { Button, createToastStore, toast } from "@arcadia/ui";

function Stack() {
  const [store] = useState(() => {
    const own = createToastStore();
    own("Agent archived", { description: "Pricing edge cases", ...keep });
    own.warning("The server is slow to answer", keep);
    own.success("Link copied", keep);
    own("Moved to receipts", { ...keep, action: { label: "Undo", onClick: () => own("Moved back") } });
    return own;
  });
  return (
    <Scene store={store}>
      <div {...sx("cmp-toast-row", s.row)}>
        <Button variant="secondary" onClick={() => store("Draft saved")}>Add one</Button>
        <Button variant="ghost" onClick={() => store.dismiss()}>Dismiss all</Button>
      </div>
    </Scene>
  );
}
```

### A promise

A loading toast becomes its result without moving.

```tsx
import { useState } from "react";
import { Button, createToastStore, toast } from "@arcadia/ui";

function Promised() {
  const [store] = useState(createToastStore);
  const save = (ok: boolean) => store.promise(
    () => new Promise((done, fail) => setTimeout(() => (ok ? done("notes.md") : fail(new Error("409: the file changed on disk"))), 1600)),
    {
      loading: "Saving changes",
      success: (file) => ({ title: "Changes saved", description: String(file) }),
      error: (reason) => ({ title: "Couldn't save the changes", description: (reason as Error).message }),
    },
  );
  return (
    <Scene store={store}>
      <div {...sx("cmp-toast-row", s.row)}>
        <Button variant="secondary" onClick={() => save(true)}>Save changes</Button>
        <Button variant="secondary" onClick={() => save(false)}>Save, and fail</Button>
      </div>
    </Scene>
  );
}
```

### An action and a cancel

Either button closes the toast. Actions get ten seconds by default.

```tsx
<Stage height="calc(var(--space-16) * 2.25)" pad="0">
  {(c) => <Seeded container={c} seed={(t) => t("Leave this space?", {
    description: "Its chats stay with the people in it.",
    ...keep,
    cancel: { label: "Stay", onClick: () => {} },
    action: { label: "Leave", onClick: () => {} },
  })} />}
</Stage>
```

### An icon act beside a text one

Copy leaves the toast open so Undo stays available.

```tsx
<Stage height="calc(var(--space-16) * 1.75)" pad="0">
  {(c) => <Seeded container={c} seed={(t) => t("Message discarded", {
    ...keep,
    action: { label: "Undo", onClick: () => {} },
    iconAction: { icon: "copy", label: "Copy message", dismiss: false, onClick: () => t("Message copied") },
  })} />}
</Stage>
```

### A held action and cancel

Named controls arm after the toast stands still for 1.5 seconds.

```tsx
import { useState } from "react";
import { Button, createToastStore, toast } from "@arcadia/ui";

function Held() {
  const [store] = useState(() => {
    const own = createToastStore();
    own("Leave this space?", {
      description: "Its chats stay with the people in it.",
      ...keep,
      cancel: { label: "Stay", press: "space.stay", onClick: () => {} },
      action: { label: "Leave", press: "space.leave", onClick: () => {} },
    });
    return own;
  });
  const hold = () => {
    store.dismiss();
    store("Leave this space?", {
      description: "Its chats stay with the people in it.",
      ...keep,
      cancel: { label: "Stay", press: "space.stay", onClick: () => {} },
      action: { label: "Leave", press: "space.leave", onClick: () => {} },
    });
  };
  return (
    <Scene store={store}>
      <div {...sx("cmp-toast-held-actions", s.row)}>
        <Button variant="secondary" onClick={hold}>Hold it again</Button>
        <Button variant="ghost" onClick={() => store.dismiss()}>Dismiss</Button>
      </div>
    </Scene>
  );
}
```

### An agent toast's action

The agent action follows the same hold as other toast controls.

```tsx
import { Toast, toast } from "@arcadia/ui";

<div {...sx("cmp-toast-held-agent", s.card)}>
  <Toast
    title="Context almost full"
    description="184k of 200k"
    tone="warning"
    visual={{ type: "progress-cells", used: 184_000, total: 200_000 }}
    action={{ label: "Compact", press: "context.compact", onClick: () => {} }}
    onDismiss={() => {}}
  />
</div>
```

### Agent toast

Give each sender and subject a stable ID to update in place.

```tsx
import { Button, toast } from "@arcadia/ui";

function AgentLive() {
  const deploy = () => {
    toast.agent({ id: "deploy-482", title: "Deploying", description: "Step 2 of 4", busy: true, visual: { type: "step-dots", steps: ["done", "active", "pending", "pending"] } });
    setTimeout(() => toast.agent({ id: "deploy-482", title: "Deploy live", description: "Build, test, ship, verify", tone: "success", visual: { type: "step-dots", steps: ["done", "done", "done", "done"] } }), 1600);
  };
  return (
    <>
      <Button variant="secondary" onClick={() => toast.agent(SEVEN[0]!)}>Tests passed</Button>
      <Button variant="secondary" onClick={() => toast.agent({ ...SEVEN[4]!, action: { label: "Compact", onClick: () => toast("Context compacted") } })}>Context warning</Button>
      <Button variant="secondary" onClick={() => toast.agent({ ...SIX[1]!, sender: scout })}>Deploy failed</Button>
      <Button variant="secondary" onClick={deploy}>Deploy, then live</Button>
    </>
  );
}
```

### The seven pictures

Pass data, not markup or an image URL.

```tsx
import { Toast, toast } from "@arcadia/ui";

<div {...sx("cmp-agent-toast-column", s.column)}>
  {SEVEN.map((t) => <Toast key={t.title} {...t} onDismiss={() => {}} />)}
</div>
```

### Compact

A smaller picture slot leaves more room for the message.

```tsx
import { Toast, toast } from "@arcadia/ui";

<div {...sx("cmp-agent-toast-grid", s.grid)}>
  {SIX.map((t) => <Toast key={t.title} {...t} density="compact" />)}
</div>
```

### Agent states

The card can open while its action and Dismiss stay separate.

```tsx
import { Toast, toast } from "@arcadia/ui";

<div {...sx("cmp-agent-toast-column", s.column)}>
  <Toast title="Deploying" description="Step 2 of 4" busy visual={{ type: "step-dots", steps: ["done", "active", "pending", "pending"] }} onDismiss={() => {}} />
  <Toast title="Indexing the repository" busy visual={{ type: "icon", icon: "tree" }} onDismiss={() => {}} />
  <Toast title="Deploy failed" description="Migrate timed out" tone="danger" sender={scout} visual={{ type: "step-dots", steps: ["done", "done", "failed", "pending", "pending"] }} action={{ label: "Retry", onClick: () => {} }} onDismiss={() => {}} />
  <Toast title="4 tests failed" description="48 of 52 in 1m 20s" tone="danger" visual={{ type: "cell-grid", passed: 48, failed: 4, total: 52 }} onDismiss={() => {}} />
  <Toast title="Branch pushed" description="fix-login, waiting for review" sender={scout} visual={{ type: "branch-graph", state: "open" }} action={{ label: "Open PR", onClick: () => {} }} />
  <Toast title="Reply from Scout" description="Sign-in is fixed on staging" sender={scout} visual={{ type: "icon", icon: "file-text" }} onOpen={() => {}} onDismiss={() => {}} />
  <Toast title="Context almost full" description="184k of 200k" tone="warning" visual={{ type: "progress-cells", used: 184_000, total: 200_000 }} />
</div>
```

### Agent toasts in the stack

Plain and agent toasts share a stack.

```tsx
import { useState } from "react";
import { Toaster, createToastStore } from "@arcadia/ui";

function AgentStack() {
  const [store] = useState(() => {
    const own = createToastStore();
    own.agent({ ...SEVEN[5]!, ...keep });
    own.agent({ ...SEVEN[1]!, sender: scout, ...keep });
    own.agent({ ...SEVEN[0]!, ...keep });
    return own;
  });
  return (
    <Stage height="calc(var(--space-16) * 3.5)" pad="0">
      {(c) => <Toaster store={store} container={c} />}
    </Stage>
  );
}
```

### Above a bar

Raise the toast stack so it clears the composer.

```tsx
import { useState } from "react";
import { createToastStore } from "@arcadia/ui";

function AboveABar() {
  const [store] = useState(() => {
    const own = createToastStore();
    own.success("Changes saved", keep);
    return own;
  });
  return <Scene store={store} bar />;
}
```

## Pictures

Each picture takes its own data. Invalid counts become zero.

| Type | Data and drawing |
| --- | --- |
| `cell-grid` |  |
| `progress-cells` |  |
| `sparkline` |  |
| `step-dots` |  |
| `branch-graph` |  |
| `diff-counts` |  |
| `icon` |  |

## Agent toast values

Agent toasts share the stack, timing and motion of plain toasts.

| Token | Role |
| --- | --- |
| `--space-12` |  |
| `--space-10` |  |
| `--radius-frame` |  |
| `--text-success` |  |
| `--text-warning` |  |
| `--text-danger` |  |
| `--fill-2` |  |

## Values

Set `duration` to override the default. Loading toasts have no timer.

Defaults: five seconds, eight for errors and ten with an action.

A held control pauses the timer for up to three seconds per toast.

| Token | Role |
| --- | --- |
| `--toast-width` | The stack's width, never wider than the window less its edges. |
| `--toast-inset-bottom` | What the stack stands above: the page's edge spacing, raised by a surface with a bar at its bottom. |
| `--toast-stack-step` | How far each toast behind the newest stands up from the one in front of it. |
| `--toast-stack-scale` | How much smaller each toast behind stands. |
| `--enter-offset` | How far a toast travels as it arrives. |
| `--duration-toast-shift` | One clock for the arrival, the stack stepping back and the list opening, on the settle spring. |
| `--duration-dialog` | The arrival's fade. |
| `--duration-float-exit` | How long a toast takes to fade out in place. |
| `--toast-swipe-distance` | A swipe this long throws a toast away; a quick flick does too. |

## Accessibility

New toasts are announced politely and errors at once. A toast never takes focus: F6 moves focus into the stack, which opens, and Tab moves through its toasts and their buttons. Every toast has a labelled Dismiss button, which does what a swipe does. While a modal dialog is open the stack stands inside it, so an action still takes a press. A control that carries a press name answers only a press the person saw the toast through: a trusted pointer press that began on it, Enter or Space on focus a Tab gave it, or a screen reader's own press. It answers nothing while its toast is held, and a pointer or a key that began before the toast stood still answers nothing either. Toast controls do not arm while the page is hidden. An agent toast's picture is drawing: a reader hears its data instead ("52 of 52 passed", "2 of 5 steps done, step 3 failed"), or the picture's own `label`, and under reduced motion a busy step's spinner holds still.

- F6: Moves focus into the stack, then back
- Tab: Moves through the toasts and their buttons
- Esc: Gives focus back to where it was

## API reference

### Toaster

- `store` (`ToastStore`)
- `container` (`PortalContainer`): Where a surface's portal mounts. Default: `document.body`. Pass a themed subtree to keep its `data-theme`, or a transformed stage to contain `position: fixed` overlays (previews): a modal set down in one stays in it, shown in place, out of the browser's top layer.

### toast()

- `description` (`ReactNode`)
- `action` (`ToastButton`)
- `cancel` (`ToastButton`)
- `iconAction` (`ToastButton & { icon: IconName }`)
- `id` (`string`, default `""] ?? 0 : 0`)
- `duration` (`number`)

### toast.agent()

- `action` (`ToastButton`)
- `dismissible` (`boolean`, default `true`)
- `id` (`string`, default `""] ?? 0 : 0`)
- `duration` (`number`)
- `title` (`string`, required): What happened, one line, past tense: "Tests passed".
- `description` (`string`): One fact, one line: "52 in 1m 12s".
- `visual` (`AgentToastVisual`, required): The picture in the leading slot, from the closed set.
- `tone` (`"neutral" | "success" | "warning" | "danger"`, default `"neutral"]) : (props as PlainToastProps).variant ?? "plain"`)
- `busy` (`boolean`): Still running: the visual shows the step it is on, a glyph turns to the spinner, and in the stack it has no time.
- `sender` (`{ name: string; avatar?: ReactNode }`): The agent that sent it, named above the title. A product's own notice (a context window filling) has none.
- `density` (`"standard" | "compact"`, default `"standard"`)
- `onOpen` (`() => void`): Opens what the toast is about (its chat, its run): the card's own surface becomes one press, named by the title and the description, under the action and Dismiss, which stay their own controls. In the stack, pressing it closes the toast, then runs this.

### Toast

- `variant` (`"plain" | "success" | "error" | "warning" | "loading"`)
- `title` (`ReactNode`, required)
- `description` (`ReactNode`)
- `action` (`ToastButton`)
- `cancel` (`ToastButton`)
- `iconAction` (`ToastButton & { icon: IconName }`)
