Toast

Brief feedback after an action, fired from React or plain code.

Source
$npx @dinachi/cli@latest add toast
type
title
description
timeout

Usage

import { Toast, useToastManager } from "@/components/ui/toast"
import { Button } from "@/components/ui/button"

function SaveButton() {
  const toast = useToastManager()
  return (
    <Button onClick={() => toast.add({ title: "Saved", description: "Your changes are live.", type: "success" })}>
      Save
    </Button>
  )
}

export function App() {
  return (
    <Toast>
      <SaveButton />
    </Toast>
  )
}

Examples

A success toast from a button.
import { ToastProvider, ToastPortal, ToastViewport, ToastList, createToastManager } from '@/components/ui/toast';
import { Button } from '@/components/ui/button';

const toastManager = createToastManager();

export function Example() {
  const showToast = () => {
    toastManager.add({
      title: "Success",
      description: "Your message has been sent successfully.",
      type: "success"
    });
  };

  return (
    <ToastProvider toastManager={toastManager}>
      <Button onClick={showToast}>Show Toast</Button>
      <ToastPortal>
        <ToastViewport>
          <ToastList />
        </ToastViewport>
      </ToastPortal>
    </ToastProvider>
  );
}

Notes

The toast manager

useToastManager() inside React and createToastManager() outside it both return add, update, close and promise. The hook also returns the current toasts.

const id = manager.add({ title: "Uploading", type: "loading", timeout: 0 })

// Change it in place: title, description, type, timeout or action.
manager.update(id, { title: "Upload complete", type: "success", timeout: 5000 })

manager.close(id) // one toast
manager.close()   // every toast

promise runs a toast through loading, success and error. Each state takes a string, toast options, or a function of the result or error.

manager.promise(fetch("/api/save", { method: "POST" }), {
  loading: "Saving...",
  success: { title: "Saved", description: "Changes applied." },
  error: (err) => ({ title: "Error", description: err.message }),
})

Toast options

add and update take the same options.

{
  title: ReactNode,
  description: ReactNode,
  type: "success" | "error" | "warning" | "loading" | string,
  timeout: number,          // 0 keeps it until dismissed
  priority: "low" | "high",
  actionProps: ButtonHTMLAttributes,
  data: object,             // anything renderToast needs
  onClose: () => void,
  onRemove: () => void,
}

The type sets the variant: error maps to destructive; success, warning and loading keep their names; anything else is default. getVariantFromType does this mapping for a custom list.

Toasts from outside React

dinachi add toast also writes lib/toast.ts with a shared manager. Pass it to Toast once, then call it from API clients and error handlers.

// lib/toast.ts, written by the CLI
import { createToastManager } from "@/components/ui/toast"
export const toastManager = createToastManager()
// providers.tsx
import { Toast } from "@/components/ui/toast"
import { toastManager } from "@/lib/toast"

export function Providers({ children }: { children: React.ReactNode }) {
  return <Toast toastManager={toastManager}>{children}</Toast>
}
// api-client.ts
import { toastManager } from "@/lib/toast"

export async function apiCall() {
  try {
    const res = await fetch("/api/data")
    if (!res.ok) throw new Error("Request failed")
    return res.json()
  } catch (err) {
    toastManager.add({ title: (err as Error).message, type: "error" })
    throw err
  }
}

Custom rendering

Pass renderToast to Toast or ToastList. Anything passed as data to add is on toast.data.

manager.add({ title: "New message", data: { avatarUrl: "/img/user.png", sender: "Alice" } })

<Toast
  renderToast={(toast) => (
    <ToastContent>
      <img src={toast.data?.avatarUrl} alt={toast.data?.sender} />
      <div>
        <ToastTitle>{toast.title}</ToastTitle>
        <ToastDescription>{toast.description}</ToastDescription>
      </div>
      <ToastClose />
    </ToastContent>
  )}
/>

Keep ToastClose in a custom layout: it is the only non-swipe dismiss and the button the agent presses.

The stack

  • Collapsed, toasts behind the front one are scaled back and offset, and cut to its height.
  • Hovering or focusing the stack expands it into a column.
  • limit sets how many it holds; more than about three stops reading as depth.

Timing

timeout on the provider or on a single add() sets how long a toast lasts; timeout: 0 keeps it until dismissed. Hovering or focusing the viewport pauses every timer.

<Toast timeout={5000}>

// Stays until dismissed.
add({ title: "Quota at 90%", timeout: 0 })

API

limitnumber = 3
Most toasts held at once.
timeoutnumber = 5000
Milliseconds before a toast closes. 0 keeps it until dismissed.
toastManagerToastManager
A manager from createToastManager(), for firing toasts outside React.
renderToast(toast) => ReactNode
Custom layout for each toast.
classNamestring
Viewport classes, for example to move the stack.

Agent

Inside an AgentProvider, it appears in agent.snapshot() as toast.

Reads

label

The toast's title, or toast when it has none.

value

The description.

type

The toast's type, such as success or error.

Actions

dismiss()

Presses the toast's ToastClose button.

Nothing to refuse: dismiss presses the close button as a person would. Without ToastClose in a custom layout, dismiss fails with a message. Action buttons are listed separately as button and take press without approval, even at high priority.

await agent.act({
  steps: [{ ref: "Success", action: "dismiss" }],
})

Accessibility

  • The viewport is a region labelled Notifications, aria-live polite.
  • priority: "high" toasts are also announced assertively. Do not announce them again yourself.
  • Each toast is a dialog named by ToastTitle and described by ToastDescription; omit both and it is an empty dialog.
  • Put any action in a real button inside the toast, so F6 then Tab reaches it.
  • Hover or focus on the viewport pauses every countdown.
  • Use timeout: 0 for anything that must be acted on.
  • The stack expands on focus too. Swiping is pointer only, so keep a close button.