Skip to main content

Toast

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

Props
Slots

Anatomy#

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 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.

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 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'.

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.

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?)
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.

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.

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.

<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.

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

Updates#

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.

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#

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.

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.

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.

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.

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.

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.

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
data-behind
Slot: toast-item
Description: —
data-bump
Slot: toast-item
Description: —
data-closed
Slot: toast-item
Description: Present when disclosure or transition content is closed.
data-expanded
Slot: toast-listtoast-item
Description: Present when the panel, accordion, or menu is expanded.
data-front
Slot: toast-item
Description: —
data-limited
Slot: toast-item
Description: —
data-swipe-out
Slot: toast-item
Description: —
data-swiping
Slot: toast-item
Description: Present while a swipe gesture is dragging the element.

Props#

Props for the Toast host component. Renders a <section> element by default.

Prop