---
title: Toast
description: Show temporary status messages as a stack of notifications
  triggered from static methods.
package: moraine
version: 0.11.0
repository: https://github.com/subframe7536/moraine
---

# Toast

> Show temporary status messages as a stack of notifications triggered from static methods.

## Anatomy

```text
Toast [component; slot=root; <section>]
└── list [slot]
    └── item [slot]
        ├── icon [slot]
        ├── wrapper [slot]
        │   ├── title [slot]
        │   └── description [slot]
        ├── actions [slot]
        │   ├── cancel [slot]
        │   └── action [slot]
        ├── close [slot]
        └── progress [slot]
```

`<Toast />` renders a portaled `root` with `role="region"` and `aria-live="polite"`, holding one
`list` stack per placement and alignment. Each notification is an `item`. The `icon` reflects the
`type`. The `actions` row (holding `cancel` and `action`), `close`, and `progress` appear when the
matching option is set.

## Usage

Use Toast for temporary feedback that stays in the page. Use [Alert Dialog](https://moraine.subf.dev/components/alert-dialog.md)
when the next step should wait for an explicit choice.

Mount `<Toast />` once. It holds no open state. Open notifications from event handlers with the
static methods.

```tsx
import { Button, Toast } from 'moraine'

export function Example() {
  return (
    <>
      <Button onClick={() => Toast.success({ title: 'Preferences saved' })}>Save</Button>
      <Toast />
    </>
  )
}
```

### Shared model

Toast and [Alert Dialog](https://moraine.subf.dev/components/alert-dialog.md) use the same options, actions, handle, and close
reasons. Every instance is created with a static method that takes an options object. Call options
override the host defaults, including `false`, `0`, and `null`. A call before the host is mounted
throws. On the server the call returns a handle whose `result()` is already `'api'`.

```ts
interface Action {
  label?: JSX.Element
  variant?: ButtonT.Variants['variant']
  tone?: ButtonT.Variants['tone']
  leading?: IconT.Name
  disabled?: boolean
  class?: SlotClassValue
  style?: SlotStyleValue
  onClick?: (event?: MouseEvent) => void | Promise<unknown>
}

type CloseReason = 'action' | 'cancel' | 'dismiss' | 'timeout' | 'api'

interface Handle {
  id: string | number
  update: (options: UpdateOptions) => void
  close: () => void
  result: () => Promise<CloseReason>
}
```

`action.onClick` and `cancel.onClick` run before the instance closes. A returned promise shows
loading on that button, disables the other one, and pauses the toast timer. A dialog also blocks
Escape, the overlay, and the corner close button. Calling `event.preventDefault()`, rejecting, or
throwing leaves the instance open. A throw or rejection is reported with `console.error`.
Otherwise the instance closes with `'action'` or `'cancel'`.

`handle.close()` and `close(id)` close with `'api'`. Escape, the overlay, the corner close button,
and a swipe close with `'dismiss'` and do not run the cancel handler. The timer closes with
`'timeout'`. `result()` resolves once with that reason, and calling it again returns the same
promise. The handle itself is not a promise.

`update` merges the next options into an open instance and restarts its timer. An update after close
does not reopen it. Reusing an open `id` in a new call updates that instance in place and returns
its existing handle. `update` replaces `action` and `cancel` as a whole, so include `onClick` again
when the label changes.

Custom content has two entry points. `Toast.custom(render, options?)` supplies a render for that
call. `<Toast itemRender={render} />` supplies one for every other call on that host. A `.custom()`
render wins, then the host render, then the built-in layout. The render receives the `id`, the
resolved `options`, `pending()`, `action()`, `cancel()`, `close()`, `update()`, `index`, and
`expanded`. It replaces the inner content. The toast keeps its stack, swipe, timer, and live region.
`close()` closes with `'dismiss'` unless you pass a reason.

A call without `hostId` goes to the host without an id and throws if only hosts with an id are
mounted. Pass `hostId` to target `<Toast id="alerts" />`.

### Methods

`show` is the neutral notice. `info`, `success`, `warning`, and `error` set the `type`. `loading` is
`show` with `type: 'loading'`. A loading toast never closes on its own because of that type. After
`update` changes the type, the normal duration applies again.

```ts
Toast.show(options)
Toast.info(options)
Toast.success(options)
Toast.warning(options)
Toast.error(options)
Toast.loading(options)
Toast.promise(promise, { loading, success, error })
Toast.custom(render, options?)
Toast.update(id, options)
Toast.close(id?)
```

```tsx
Toast.success({ title: 'Project published', description: 'Your changes are now live.' })
Toast.error({ title: 'Upload failed', description: 'File size exceeds the 10 MB limit.' })
Toast.warning({ title: 'Low disk space', description: 'Volume is at 92% capacity.' })
Toast.info({ title: 'Update available', description: 'Version 2.4 is ready to install.' })
Toast.show({ title: 'Draft saved' })
```

### Action and dismissal

`action` is the primary button. `cancel: true` uses the locale label, and `cancel: { label }` sets
one. The corner close button shows when `closable` is set on the call or the host. Loading toasts
hide the close button and the progress bar.

```tsx
Toast.show({
  title: 'Conversation archived',
  action: {
    label: 'Undo',
    onClick: () => restoreConversation(),
  },
})
```

### Large layout

`size="lg"` moves the actions onto their own row and the close control to the top corner.

```tsx
Toast.success({
  title: 'Export finished',
  description: 'Your dataset is packaged and ready to download.',
  size: 'lg',
  action: { label: 'Download', onClick: () => downloadFile() },
  cancel: { label: 'Dismiss' },
  closable: true,
})
```

`<Toast size="lg" />` applies that layout to every toast on the host.

### Host options

`<Toast />` options set defaults for every toast on that host, and call options override them.
`placement` (`'top'` or `'bottom'`, default `'bottom'`) and `align` (default `'end'`) choose the
corner; each placement and alignment pair gets its own stack. `type`, `size`, `variant`, `duration`,
`closable`, `progress`, and `preventDuplicate` set per-toast defaults. `maxVisible` (default 3)
limits each stack, and later toasts stay queued until earlier ones close. A collapsed stack expands
while the pointer is over it; set `expanded` to keep it expanded. `gap` (default 14 px) sets the
spacing between toasts. `translations` overrides the viewport label and the close and cancel
labels.

```tsx
<Toast placement="top" align="center" maxVisible={5} closable progress />
```

### Promises

`promise` opens a loading toast and updates it when the promise settles. It accepts a promise or a
function that returns one. `loading`, `success`, and `error` are the same options object used
everywhere else. `success` and `error` may also be functions of the settled value or the rejection
reason. When either is omitted, that outcome closes the toast with `'api'`. The method returns the
ordinary handle. Keep the original promise when you need the value.

```tsx
const task = deployProject()
Toast.promise(task, {
  loading: { title: 'Deploying project...' },
  success: { title: 'Deployment live!' },
  error: (err) => ({ title: `Deploy failed: ${String(err)}` }),
})
```

### Updates

```tsx
const handle = Toast.loading({ title: 'Exporting report...' })

Toast.update(handle.id, { title: 'Report ready', type: 'success' })

handle.close()
Toast.close()
```

`Toast.close(id)` closes one toast, and `Toast.close()` without an id closes every toast.

### Duplicates

`preventDuplicate` compares the new toast with the front toast in the same host and corner. A match
bumps that toast, restarting its timer, and returns its handle. The option is a boolean on the host
or on the call. It does not apply to a call that sets `id`.

```tsx
Toast.info({
  title: 'Link copied to clipboard',
  preventDuplicate: true,
})
```

### Duration and progress

`duration` defaults to 4000 milliseconds, and `Infinity` keeps the toast open until dismissed.
`progress` shows the remaining-time bar. The timer pauses while the pointer is over the stack, the
window is blurred or the tab is hidden, a swipe is in progress, or an action promise is pending.

### Custom content

```tsx
Toast.custom((props) => (
  <div class="flex gap-4 items-center justify-between">
    <span class="text-sm">Maintenance scheduled in 10 minutes</span>
    <Button size="sm" variant="ghost" onClick={() => props.close()}>
      Dismiss
    </Button>
  </div>
))
```

## Examples

### Archive an item with undo

The action button restores the conversation with another toast.

```tsx
import { Button, Toast } from 'moraine'

export function ArchiveItem() {
  const handleArchive = () => {
    Toast.show({
      title: 'Conversation archived',
      description: 'Moved to your archive folder.',
      action: {
        label: 'Undo',
        onClick: () => {
          Toast.success({ title: 'Conversation restored' })
        },
      },
    })
  }

  return (
    <Button variant="outline" leading="i-lucide:archive" onClick={handleArchive}>
      Archive conversation
    </Button>
  )
}
```

### Track an asynchronous deployment

`promise` swaps the loading toast for the success or error options.

```tsx
import { Button, Toast } from 'moraine'

export function TrackDeployment() {
  const deploy = (shouldSucceed: boolean) => {
    const task = new Promise<{ version: string }>((resolve, reject) => {
      setTimeout(() => {
        if (shouldSucceed) {
          resolve({ version: 'v2.4.0' })
        } else {
          reject(new Error('Connection timed out'))
        }
      }, 1500)
    })

    Toast.promise(task, {
      loading: { title: 'Deploying to production...' },
      success: (data) => ({ title: `Deployed ${data.version} successfully!` }),
      error: (err) => ({ title: `Deploy failed: ${(err as Error).message}` }),
    })
  }

  return (
    <div class="flex flex-wrap gap-3 items-center">
      <Button leading="i-lucide:rocket" onClick={() => deploy(true)}>
        Deploy project
      </Button>
      <Button variant="outline" leading="i-lucide:alert-circle" onClick={() => deploy(false)}>
        Simulate deploy failure
      </Button>
    </div>
  )
}
```

### Report distinct task outcomes

The `type` methods set the icon and the live-region role. An error toast uses `alert`. The others
use `status`.

```tsx
import { Button, Toast } from 'moraine'

export function StatusOutcomes() {
  return (
    <div class="flex flex-wrap gap-3 items-center">
      <Button
        variant="outline"
        leading="i-lucide:check"
        onClick={() =>
          Toast.success({
            title: 'Preferences saved',
            description: 'Your account preferences have been updated.',
          })
        }
      >
        Save preferences
      </Button>
      <Button
        variant="outline"
        leading="i-lucide:alert-triangle"
        onClick={() =>
          Toast.warning({
            title: 'Storage warning',
            description: 'Workspace is using 92% of available disk space.',
          })
        }
      >
        Check disk usage
      </Button>
      <Button
        variant="outline"
        leading="i-lucide:refresh-cw"
        onClick={() =>
          Toast.error({
            title: 'Sync failed',
            description: 'Could not connect to the remote repository.',
          })
        }
      >
        Sync repository
      </Button>
    </div>
  )
}
```

### Deduplicate rapid user actions

`preventDuplicate` keeps a repeated click on the front toast.

```tsx
import { Button, Toast } from 'moraine'

export function PreventDuplicate() {
  return (
    <div class="flex flex-wrap gap-3 items-center">
      <Button
        variant="outline"
        leading="i-lucide:copy"
        onClick={() =>
          Toast.info({
            title: 'Link copied',
            description: 'Invite URL copied to clipboard.',
            preventDuplicate: true,
          })
        }
      >
        Copy invite link
      </Button>
      <Button
        variant="outline"
        leading="i-lucide:bell-ring"
        onClick={() =>
          Toast.show({
            title: 'Already up to date',
            description: 'Checked for updates just now.',
            preventDuplicate: true,
          })
        }
      >
        Check for updates
      </Button>
    </div>
  )
}
```

### Route notifications to a custom viewport corner

`hostId` sends the toast to `<Toast id="bottom-dock" />`. `Toast.close()` dismisses every toast.

```tsx
import { Button, Toast } from 'moraine'

export function CustomPlacement() {
  return (
    <div class="flex flex-wrap gap-3 items-center">
      <Toast id="bottom-dock" placement="bottom" align="start" />
      <Button
        variant="outline"
        leading="i-lucide:arrow-down-left"
        onClick={() =>
          Toast.info({
            title: 'Background task started',
            description: 'Analyzing code workspace...',
            hostId: 'bottom-dock',
          })
        }
      >
        Notify bottom-left
      </Button>
      <Button variant="ghost" leading="i-lucide:x" onClick={() => Toast.close()}>
        Dismiss all
      </Button>
    </div>
  )
}
```

### Show upload progress

`.custom()` draws the progress row. The toast shell still owns stacking, swipe, and the timer.
`duration: Infinity` keeps this one open until it is dismissed.

```tsx
import { Button, Toast } from 'moraine'
import { createSignal, onCleanup } from 'solid-js'

export function UploadProgress() {
  const upload = () => {
    Toast.custom(
      (props) => {
        const [progress, setProgress] = createSignal(8)
        const timer = setInterval(() => {
          setProgress((value) => {
            const next = Math.min(100, value + 12)
            if (next === 100) {
              clearInterval(timer)
              props.update({ title: 'report.pdf uploaded' })
            }
            return next
          })
        }, 180)
        onCleanup(() => clearInterval(timer))

        return (
          <div class="flex flex-col gap-2 w-full">
            <div class="flex gap-3 items-center justify-between">
              <span class="text-sm font-medium">{props.options.title}</span>
              <span class="text-xs text-muted-foreground">{progress()}%</span>
            </div>
            <div class="rounded-full bg-muted h-1.5 overflow-hidden">
              <div class="rounded-full bg-primary h-full" style={{ width: `${progress()}%` }} />
            </div>
          </div>
        )
      },
      { title: 'Uploading report.pdf', duration: Infinity },
    )
  }

  return (
    <Button variant="outline" leading="i-lucide:upload" onClick={upload}>
      Upload report
    </Button>
  )
}
```

## API Reference

### Attributes

| Attributes | Slot | Description |
| --- | --- | --- |
| `data-behind` | `toast-item` | — |
| `data-bump` | `toast-item` | — |
| `data-closed` | `toast-item` | Present when disclosure or transition content is closed. |
| `data-expanded` | `toast-list`, `toast-item` | Present when the panel, accordion, or menu is expanded. |
| `data-front` | `toast-item` | — |
| `data-limited` | `toast-item` | — |
| `data-swipe-out` | `toast-item` | — |
| `data-swiping` | `toast-item` | Present while a swipe gesture is dragging the element. |

### Props

Props for the Toast host component.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| align | 'start' \| 'center' \| 'end' \| undefined | 'end' | Horizontal alignment of the stack. |
| closable | boolean \| undefined | false | Whether toasts on this host show a close button by default; a toast's own `closable`<br>takes precedence. |
| duration | number \| undefined | 4000 | Default auto-close duration in milliseconds for toasts on this host; a toast's own<br>`duration` takes precedence. |
| expanded | boolean \| undefined | false | Whether the stacked toast list is always expanded. When `false`, stacks collapse behind<br>the front toast and expand while the pointer is over them. |
| gap | number \| undefined | 14 | Spacing in pixels between toasts. Collapsed stacks use it as the peek offset of each toast<br>behind the front one; expanded stacks add it between full toast heights. |
| id | string \| undefined | — | Identifier of this host. A toast opened with `hostId: id` is shown here; toasts without<br>`hostId` go to the host that has no `id`. Use unique ids when mounting several hosts. |
| itemRender | Component<ItemRenderProps> \| undefined | — | Renders the inner content of every toast on this host that was not opened with<br>`Toast.custom`, replacing the default icon, title, description, actions, and close button.<br>Receives the instance context and the resolved call options. |
| maxVisible | number \| undefined | 3 | Max number of toasts shown per stack (one stack per `placement` and `align`). Toasts beyond<br>the limit stay queued but are hidden until earlier ones close. |
| placement | 'top' \| 'bottom' \| undefined | 'bottom' | Vertical stack placement on the viewport. |
| preventDuplicate | boolean \| undefined | false | Whether toasts on this host skip content that matches the front toast by default; a toast's<br>own `preventDuplicate` takes precedence. |
| progress | boolean \| undefined | false | Whether toasts on this host show the remaining duration progress bar by default; a<br>toast's own `progress` takes precedence. |
| size | 'md' \| 'lg' \| undefined | 'md' | `lg` uses a multi-line layout with the actions on their own row. |
| translations | Translations \| undefined | — | Localized labels for this host's viewport (`viewport`) and, unless a toast sets its own,<br>the `close` and `cancel` buttons of its toasts. |
| type | 'default' \| 'success' \| 'warning' \| 'error' \| 'info' \| 'loading' \| undefined | 'default' | Visual status variant. |
| variant | 'default' \| 'invert' \| undefined | 'default' | `invert` flips the colors (e.g. dark toast on light theme). |
| class | SlotClassValue \| undefined | — | Class applied to the component root or trigger element. |
| classes | Classes \| undefined | — | Family slot class defaults for this instance. |
| style | SlotStyleValue \| undefined | — | Style applied to the component root or trigger element. |
| styles | Styles \| undefined | — | Family slot style defaults for this instance. |

**`itemRender` example**

```tsx
import { Toast } from 'moraine'

<Toast
  itemRender={(ctx) => (
    <div>
      <strong>{ctx.options.title}</strong>
      <button type="button" onClick={() => ctx.close()}>
        Dismiss
      </button>
    </div>
  )}
/>
```
