# Toast

Shows a brief notification that dismisses itself.

[View source and API](https://github.com/tempoxyz/ds/blob/main/src/web/components/Toast.tsx)

Figma: [Toast](https://www.figma.com/design/yE96kcymnNR88PJp6G1sPs?node-id=1186-3381) (`Toast.Item`)

## Overview

Toasts are queued with a hook and render in a live region at the edge of the viewport.

## Examples

### Basic

```tsx
import { Button, Toast } from '@tempoxyz/ds'

function Trigger() {
  const toast = Toast.useToast()

  return (
    <Button
      onClick={() =>
        toast.add({ description: 'Transfers settle in seconds.', title: 'Payment sent' })
      }
      size="small"
      variant="secondary"
    >
      Show toast
    </Button>
  )
}

export function Demo() {
  return (
    <Toast.Provider>
      <Trigger />
      <Toast.Viewport />
    </Toast.Provider>
  )
}
```

[View example source](https://github.com/tempoxyz/ds/blob/main/docs/src/examples/demos/Toast/Basic.tsx)

### Intent

Pass `intent` to `toast.add` as `neutral` (default), `info`, `positive`, `warning`, or `negative`.

```tsx
import { Button, style, Toast } from '@tempoxyz/ds'

const intents = ['neutral', 'info', 'positive', 'warning', 'negative'] as const

function Triggers() {
  const toast = Toast.useToast()

  return (
    <div {...styles.row()}>
      {intents.map((intent) => (
        <Button
          key={intent}
          onClick={() =>
            toast.add({
              description: 'Transfers settle in seconds.',
              intent,
              title: `${intent} toast`,
            })
          }
          size="small"
          variant="secondary"
        >
          {intent}
        </Button>
      ))}
    </div>
  )
}

export function Demo() {
  return (
    <Toast.Provider>
      <Triggers />
      <Toast.Viewport />
    </Toast.Provider>
  )
}

namespace styles {
  export const row = style({ alignItems: 'center', display: 'flex', flexWrap: 'wrap', gap: '12' })
}
```

[View example source](https://github.com/tempoxyz/ds/blob/main/docs/src/examples/demos/Toast/Intent.tsx)

### Action

Pass an `action` with a `label` to add a button. Set `timeout: 0` to keep the toast open until dismissed.

```tsx
import { Button, Toast } from '@tempoxyz/ds'

function Trigger() {
  const toast = Toast.useToast()

  return (
    <Button
      onClick={() =>
        toast.add({
          action: { label: 'Undo' },
          intent: 'positive',
          timeout: 0,
          title: 'Archived',
        })
      }
      size="small"
      variant="secondary"
    >
      With action
    </Button>
  )
}

export function Demo() {
  return (
    <Toast.Provider>
      <Trigger />
      <Toast.Viewport />
    </Toast.Provider>
  )
}
```

[View example source](https://github.com/tempoxyz/ds/blob/main/docs/src/examples/demos/Toast/Action.tsx)

### Item

`Toast.Viewport` renders a `Toast.Item` for each queued toast. Render an item yourself only in a custom viewport under `Toast.Provider`, and pass it a toast object, whose `type` sets the intent.

```tsx
import { style, Toast } from '@tempoxyz/ds'

export function Demo() {
  return (
    <Toast.Provider>
      <div {...styles.frame()}>
        <Toast.Item
          toast={{
            description: 'Sent 25.00 USDC to Alice',
            id: 'sent',
            title: 'Payment sent',
            type: 'positive',
          }}
        />
      </div>
    </Toast.Provider>
  )
}

namespace styles {
  // The item sits at the bottom of its containing block, as the viewport places it.
  export const frame = style({ height: '72', position: 'relative', width: '320' })
}
```

[View example source](https://github.com/tempoxyz/ds/blob/main/docs/src/examples/demos/Toast/Item.tsx)

## Anatomy

Import the component and assemble its parts.

```tsx
import { Toast } from '@tempoxyz/ds'

<Toast.Provider>
  <Toast.Viewport />
  <Toast.Item />
</Toast.Provider>
```

## Guidelines

### When to Use

* Confirm that a user action finished, such as Payment sent or Webhook saved.
* Report a background event that needs no response, such as a deposit that arrived while the user was on another page.
* Offer a short Undo after a reversible action, such as Archived, when the same result is reachable elsewhere.

### When Not to Use

* Use an [Alert](/docs/components/alert) for an error or warning that must stay beside its content, such as a failed payment.
* Use a [Banner](/docs/components/banner) for a condition that affects the whole product, such as an outage.
* Use an [AlertDialog](/docs/components/alert-dialog) for a decision before an action continues.
* Use `Field.Error` from [Field](/docs/components/field) for validation messages on an input.
* Use `loading` on a [Button](/docs/components/button), or [Progress](/docs/components/progress), for work that still runs.

### Keep Required Actions Out of Toasts

A toast dismisses itself, and keyboard users must press F6 to reach it. Put required steps in the page or in an [AlertDialog](/docs/components/alert-dialog).

**Do:** Confirm a finished action and include the detail that identifies it.

```tsx
/**
 * Do example for "Keep Required Actions Out of Toasts" on the Toast page.
 * Confirm a finished action and include the detail that identifies it.
 * @module
 */
import { CheckCircle, Close } from '@tempoxyz/ds/icons'
import { style } from '@tempoxyz/ds'

// Toasts render in a portal, so this preview draws one in place with the toast's styles.
/** Renders the static preview, which the guideline card shows inert. */
export function Demo() {
  return (
    <div {...styles.toast()}>
      <CheckCircle {...styles.icon()} />
      <div {...styles.body()}>
        <div {...styles.title()}>Payment sent</div>
        <div {...styles.description()}>50.00 USDC to 0x8f3c…a21b</div>
      </div>
      <Close {...styles.close()} />
    </div>
  )
}

namespace styles {
  export const body = style({
    display: 'flex',
    flex: '1 !custom',
    flexDirection: 'column',
    minWidth: '0px !custom',
    rowGap: '4',
  })

  export const close = style({ color: 'content.tertiary', flexShrink: '0 !custom', fontSize: '16' })

  export const description = style({ color: 'content.secondary', typography: 'body.b2' })

  export const icon = style({ color: 'content.positive', flexShrink: '0 !custom', fontSize: '20' })

  export const title = style({ color: 'content.primary', typography: 'body.b2Strong' })

  export const toast = style({
    alignItems: 'center',
    backgroundColor: 'background.elevated',
    borderRadius: 'sm',
    boxShadow: 'regular',
    boxSizing: 'border-box',
    columnGap: '12',
    display: 'flex',
    paddingBlock: '16',
    paddingInline: '20',
    width: '100% !custom',
  })
}
```

**Don't:** Ask for a confirmation or another required step in a toast.

```tsx
/**
 * Don't example for "Keep Required Actions Out of Toasts" on the Toast page.
 * Don't ask for a confirmation or another required step in a toast.
 * @module
 */
import { AlertTriangle, Close } from '@tempoxyz/ds/icons'
import { style } from '@tempoxyz/ds'

// Toasts render in a portal, so this preview draws one in place with the toast's styles.
/** Renders the static preview, which the guideline card shows inert. */
export function Demo() {
  return (
    <div {...styles.toast()}>
      <AlertTriangle {...styles.icon()} />
      <div {...styles.body()}>
        <div {...styles.title()}>Confirm payment</div>
        <div {...styles.description()}>50.00 USDC to 0x8f3c…a21b</div>
      </div>
      <span {...styles.action()}>Confirm</span>
      <Close {...styles.close()} />
    </div>
  )
}

namespace styles {
  export const action = style({
    alignItems: 'center',
    backgroundColor: 'container.regular',
    borderRadius: 'full',
    color: 'content.primary',
    cornerShape: 'round',
    display: 'inline-flex',
    flexShrink: '0 !custom',
    height: '32',
    paddingInline: '12',
    typography: 'body.b3Strong',
  })

  export const body = style({
    display: 'flex',
    flex: '1 !custom',
    flexDirection: 'column',
    minWidth: '0px !custom',
    rowGap: '4',
  })

  export const close = style({ color: 'content.tertiary', flexShrink: '0 !custom', fontSize: '16' })

  export const description = style({ color: 'content.secondary', typography: 'body.b2' })

  export const icon = style({ color: 'content.warning', flexShrink: '0 !custom', fontSize: '20' })

  export const title = style({ color: 'content.primary', typography: 'body.b2Strong' })

  export const toast = style({
    alignItems: 'center',
    backgroundColor: 'background.elevated',
    borderRadius: 'sm',
    boxShadow: 'regular',
    boxSizing: 'border-box',
    columnGap: '12',
    display: 'flex',
    paddingBlock: '16',
    paddingInline: '20',
    width: '100% !custom',
  })
}
```

An Undo action is fine if the page also reverses the change, such as an Archive tab that restores an archived key.

### Choose an Intent

* **Neutral (neutral):** The default, with no icon. Updates with no outcome to judge, such as Signed out.
* **Info (info):** Events the user didn't start, such as a deposit that arrived.
* **Positive (positive):** An action that succeeded, such as a confirmation that reads Payment sent.
* **Warning (warning):** An action that finished with a caveat, such as a test delivery that timed out.
* **Negative (negative):** A non-critical action that failed and that the user can try again.

### Set Duration by Content

* **Short Content (5 seconds):** The default, for a title and a short description.
* **Longer Description (timeout):** Raise `timeout`, or set it app-wide on `Toast.Provider`.
* **Action (timeout: 0):** Keeps the toast open until dismissed ([SC 2.2.1](https://www.w3.org/WAI/WCAG22/Understanding/timing-adjustable.html)).

### Send One Toast per Outcome

`Toast.Provider` shows up to three toasts by default, and hides older ones past its `limit`. Combine related results into one toast.

**Do:** Combine related results into one toast, such as 3 payments sent.

```tsx
/**
 * Do example for "Send One Toast per Outcome" on the Toast page.
 * Combine related results into one toast, such as 3 payments sent.
 * @module
 */
import { CheckCircle, Close } from '@tempoxyz/ds/icons'
import { style } from '@tempoxyz/ds'

// Toasts render in a portal, so this preview draws one in place with the toast's styles.
/** Renders the static preview, which the guideline card shows inert. */
export function Demo() {
  return (
    <div {...styles.toast()}>
      <CheckCircle {...styles.icon()} />
      <div {...styles.body()}>
        <div {...styles.title()}>3 payments sent</div>
        <div {...styles.description()}>150.00 USDC to 3 recipients</div>
      </div>
      <Close {...styles.close()} />
    </div>
  )
}

namespace styles {
  export const body = style({
    display: 'flex',
    flex: '1 !custom',
    flexDirection: 'column',
    minWidth: '0px !custom',
    rowGap: '4',
  })

  export const close = style({ color: 'content.tertiary', flexShrink: '0 !custom', fontSize: '16' })

  export const description = style({ color: 'content.secondary', typography: 'body.b2' })

  export const icon = style({ color: 'content.positive', flexShrink: '0 !custom', fontSize: '20' })

  export const title = style({ color: 'content.primary', typography: 'body.b2Strong' })

  export const toast = style({
    alignItems: 'center',
    backgroundColor: 'background.elevated',
    borderRadius: 'sm',
    boxShadow: 'regular',
    boxSizing: 'border-box',
    columnGap: '12',
    display: 'flex',
    paddingBlock: '16',
    paddingInline: '20',
    width: '100% !custom',
  })
}
```

**Don't:** Send a separate toast for each result of one action.

```tsx
/**
 * Don't example for "Send One Toast per Outcome" on the Toast page.
 * Don't send a separate toast for each result of one action.
 * @module
 */
import { CheckCircle, Close } from '@tempoxyz/ds/icons'
import { style } from '@tempoxyz/ds'

const payments = ['0x8f3c…a21b', '0x41d0…9c7e', '0xb27a…04f5']

// Toasts render in a portal, so this preview draws them in place with the toast's styles.
/** Renders the static preview, which the guideline card shows inert. */
export function Demo() {
  return (
    <div {...styles.stack()}>
      {payments.map((address) => (
        <div key={address} {...styles.toast()}>
          <CheckCircle {...styles.icon()} />
          <div {...styles.body()}>
            <div {...styles.title()}>Payment sent</div>
            <div {...styles.description()}>50.00 USDC to {address}</div>
          </div>
          <Close {...styles.close()} />
        </div>
      ))}
    </div>
  )
}

namespace styles {
  export const body = style({
    display: 'flex',
    flex: '1 !custom',
    flexDirection: 'column',
    minWidth: '0px !custom',
    rowGap: '4',
  })

  export const close = style({ color: 'content.tertiary', flexShrink: '0 !custom', fontSize: '16' })

  export const description = style({ color: 'content.secondary', typography: 'body.b2' })

  export const icon = style({ color: 'content.positive', flexShrink: '0 !custom', fontSize: '20' })

  export const stack = style({
    display: 'flex',
    flexDirection: 'column',
    gap: '8',
    width: '100% !custom',
  })

  export const title = style({ color: 'content.primary', typography: 'body.b2Strong' })

  export const toast = style({
    alignItems: 'center',
    backgroundColor: 'background.elevated',
    borderRadius: 'sm',
    boxShadow: 'regular',
    boxSizing: 'border-box',
    columnGap: '12',
    display: 'flex',
    paddingBlock: '16',
    paddingInline: '20',
    width: '100% !custom',
  })
}
```

## Content

* Write the title as the result in a few words, usually past tense: Payment sent, Key revoked, Webhook saved.
* Add a description only for the detail that identifies the action, such as 50.00 USDC to 0x8f3c…a21b.
* Leave out exclamation marks and filler such as Success or Done.
* Label the action with one verb, such as Undo or Retry.

## Accessibility

Toasts never take focus on their own. Don't move focus to a new toast yourself.

### Semantics

* **Toast.Viewport (region):** A landmark named "Notifications". Announces new toasts without moving focus.
* **Toast (dialog):** A non-modal dialog, named by its title and described by its description.
* **High Priority (alertdialog):** With `priority: 'high'`, a separate alert interrupts current speech. Intent alone never does.
* **Action and Dismiss (button):** The action is named by `action.label`. Every toast also has a Dismiss button.
* **Intent Icon (aria-hidden):** Hidden from assistive technology, so the title must carry the outcome.

### Keyboard

* **Reach the Viewport (F6):** Moves focus to the toast viewport from anywhere on the page.
* **Move Through the Toast (Tab):** Moves focus to the newest toast, then to its action and Dismiss button.
* **Move Back (Shift+Tab):** Moves focus back. From the viewport, returns focus to where it was before F6.
* **Activate a Button (Enter or Space):** Activates the action or the Dismiss button that holds focus.
* **Dismiss the Toast (Escape):** Dismisses the toast that holds focus, the same as its Dismiss button.

### Dismissal

* **Pausing:** Hover or focus in the viewport pauses all dismiss timers, as does a background window.
* **Swiping:** On touch screens, a swipe down or to the right dismisses a toast.

### Your Responsibilities

* **Reserve High Priority (priority: 'high'):** Use it only for urgent messages. Show critical errors inline or in a [Dialog](/docs/components/dialog).
* **Render One Viewport (F6):** Render one viewport per app, so the shortcut always reaches it.

## Related

[Alert](/docs/components/alert)

Use for messages that stay beside their content.

[Banner](/docs/components/banner)

Use for messages about the whole product.

[AlertDialog](/docs/components/alert-dialog)

Use for decisions before an action continues.

[Feedback and Status](/docs/patterns/feedback-and-status)

Covers choosing a message component.
