Toast
Short notices that appear in a corner, stack, and leave on their own: saved, copied, failed. A toast() function raises them from anywhere, and one Toaster shows them. A toast never holds the only copy of something the reader needs; for a message that must be answered, use an alert dialog.
Install
npx shadcn@latest add https://thrumui.dev/r/toast.jsonAdds components/ui/toast.tsx and installs @base-ui/react@1.9.0. Nothing else in your project changes.
import { Toaster } from "@/components/ui/toast";Automatically installs icons circle-check, circle-x, triangle-alert and x from the icon set.
Props
| Prop | Type | Default | Description |
|---|---|---|---|
Toaster: position | "top-left" | "top-center" | "top-right" | "bottom-left" | "bottom-center" | "bottom-right" | Default "bottom-right" | The corner or edge of the screen the stack sits at. Toasts enter from that edge. |
Toaster: limit | number | Default 3 | How many toasts show at once. Older ones wait behind and come back when a newer one leaves, if their time is not up. |
Toaster: duration | number | Default 5000 | How long a toast stays, in ms, unless it sets its own. 0 keeps toasts until they are closed. |
Toaster: sound | boolean | Default true | Play the success, warning or error sound when such a toast appears, if the visitor has sound on. |
Toaster: className | string | – | Extra classes for the stack. The default is 384 pixels wide, or the screen less 32 pixels. |
toast(title, options) | (title: ReactNode, options?: ToastOptions) => string | – | Raises a plain toast and returns its id. It has no icon and no sound. |
toast.success / warning / error | (title: ReactNode, options?: ToastOptions) => string | – | The same with an icon and a sound for the outcome. An error interrupts a screen reader; the others wait their turn. |
toast.promise(promise, messages) | (promise: Promise<T>, { loading, success, error }) => Promise<T> | – | Shows loading with a spinner, then turns into success or error when the promise settles. success and error can be functions of the result. |
toast.dismiss(id) | (id?: string) => void | – | Closes one toast, or every toast when called with no id. |
options: description | ReactNode | – | A second line under the title. |
options: duration | number | – | How long this toast stays, in ms. 0 keeps it until it is closed. |
options: action | { label: string; onClick: () => void } | – | A button inside the toast, such as Undo. A press runs onClick and closes the toast. |
options: id | string | – | A name of your own. Raising a toast with the id of one that is showing replaces it in place. |
options: onClose | () => void | – | Runs when the toast closes, whatever closed it. |
Motion and sound
Motion
- A toast slides in from the edge of the screen it sits at and fades in, over 200 ms. The toasts already there move over to make room.
- A toast that times out or is closed fades out where it is, and the others close the gap.
- A swiped toast follows the pointer and leaves in the direction it was pushed. Let go early and it slides back.
- The spinner of a pending promise turns until the promise settles.
- Reduced motion: toasts appear, move and leave at once, and the spinner stands still.
Sound
- A rising pair of tones when a success toast appears, or when a promise resolves.
- A two-note chord when a warning toast appears.
- A falling pair of tones when an error toast appears, or when a promise rejects.
- A plain toast and a loading toast are silent. When several toasts arrive at once, only the newest is heard.
Sound is off until the visitor turns it on. Pass sound={false} to keep this component silent. How sound works
Accessibility
- The stack is a region named Notifications with aria-live polite: a screen reader reads each new toast when it is done speaking.
- An error toast is announced through role alert, which interrupts. Keep errors rare so that stays meaningful.
- Each toast is a small non-modal dialog named by its title. It never takes the focus by itself.
- The timers stop while the pointer is over the stack, while the focus is in it, and while the window is in the background.
- Outcome is never colour alone: success, warning and error each have their own icon shape, and the words say what happened.
- A toast leaves on its own, so it must not hold the only copy of anything. An action such as Undo needs a second way to reach it.
- Swipe is an extra: the close button, 28 pixels square and named Close, does the same.
- A new toast is read without its close button, which screen readers meet once the pointer or the focus is in the stack.
- Under a glass material the toasts are translucent. Their tint keeps the text at 4.5 to 1 over any page.
| Keys | Action |
|---|---|
| F6 | Move the focus to the stack of toasts, from anywhere on the page. The timers stop while it is there. |
| Tab / Shift Tab | Move through the toasts and their buttons. Shift Tab on the stack or on its first toast goes back to where the focus was. |
| Enter / Space | Press the focused action or close button. |
| Esc | Close the toast that holds the focus. The focus moves to the next toast, or back to the page after the last one. |
Source
"use client";
import { useEffect, useRef, type ReactNode } from "react";
import { Toast as ToastPrimitive } from "@base-ui/react/toast";
import { cn } from "@/lib/utils";
import { STATUS } from "@/lib/thrum-chart";
import { play, type SoundName } from "@/lib/thrum-sound";
import { buttonClass } from "@/components/ui/button";
import { CircleCheckIcon } from "@/components/icons/circle-check";
import { CircleXIcon } from "@/components/icons/circle-x";
import { TriangleAlertIcon } from "@/components/icons/triangle-alert";
import { XIcon } from "@/components/icons/x";
export type ToastType = "success" | "warning" | "error" | "loading";
export type ToastPosition = "top-left" | "top-center" | "top-right" | "bottom-left" | "bottom-center" | "bottom-right";
export type ToastOptions = {
/** A second line under the title. */
description?: ReactNode;
/** How long the toast stays, in ms. 0 keeps it until it is closed. The default is the `duration` of the `Toaster`. */
duration?: number;
/** A button inside the toast, such as Undo. A press runs `onClick` and closes the toast. */
action?: { label: string; onClick: () => void };
/** A name of your own. Raising a toast with the id of one that is showing replaces it in place. */
id?: string;
/** Runs when the toast closes, whatever closed it. */
onClose?: () => void;
};
export type ToastPromiseMessages<Value> = {
/** The title while the promise is pending. This toast stays until the promise settles. */
loading: ReactNode;
/** The title once it resolves, or a function that makes one from the result. */
success: ReactNode | ((value: Value) => ReactNode);
/** The title once it rejects, or a function that makes one from the reason. */
error: ReactNode | ((reason: unknown) => ReactNode);
};
// One list for the whole app: `toast()` can be called from anywhere, and the one `Toaster` shows what it is given.
const manager = ToastPrimitive.createToastManager();
function raise(type: ToastType | undefined, title: ReactNode, { description, duration, action, id, onClose }: ToastOptions = {}): string {
const toastId: string = manager.add({
id,
type,
title,
description,
timeout: duration,
onClose,
// An error interrupts a screen reader. Everything else waits for it to finish speaking.
priority: type === "error" ? "high" : "low",
actionProps: action && {
children: action.label,
onClick: () => {
action.onClick();
manager.close(toastId);
},
},
});
return toastId;
}
/**
* Raises a toast and returns its id. Call it from an event handler or an effect, anywhere in the app.
* `toast.success`, `toast.warning` and `toast.error` add an icon and a sound; `toast.promise` follows a promise;
* `toast.dismiss(id)` closes one toast, and all of them with no id.
*/
export const toast = Object.assign((title: ReactNode, options?: ToastOptions) => raise(undefined, title, options), {
success: (title: ReactNode, options?: ToastOptions) => raise("success", title, options),
warning: (title: ReactNode, options?: ToastOptions) => raise("warning", title, options),
error: (title: ReactNode, options?: ToastOptions) => raise("error", title, options),
/** Shows `loading` at once, then turns into `success` or `error` when the promise settles. Returns the same promise. */
promise: <Value,>(promise: Promise<Value>, messages: ToastPromiseMessages<Value>): Promise<Value> =>
manager.promise(promise, {
loading: { title: messages.loading },
success: (value: Value) => ({ title: typeof messages.success === "function" ? messages.success(value) : messages.success }),
error: (reason: unknown) => ({ title: typeof messages.error === "function" ? messages.error(reason) : messages.error, priority: "high" }),
}),
dismiss: (id?: string) => manager.close(id),
});
// Where the stack sits on the screen, 16 pixels in from the edges.
const POSITION: Record<ToastPosition, string> = {
"top-left": "top-4 left-4",
"top-center": "top-4 left-1/2 -translate-x-1/2",
"top-right": "top-4 right-4",
"bottom-left": "bottom-4 left-4",
"bottom-center": "bottom-4 left-1/2 -translate-x-1/2",
"bottom-right": "bottom-4 right-4",
};
const CUE: Partial<Record<string, SoundName>> = { success: "success", warning: "warn", warn: "warn", error: "error" };
const ICON: Record<ToastType, { glyph?: typeof CircleCheckIcon; color?: string }> = {
success: { glyph: CircleCheckIcon, color: STATUS.ok },
warning: { glyph: TriangleAlertIcon, color: STATUS.warn },
error: { glyph: CircleXIcon, color: STATUS.alarm },
loading: {},
};
export type ToasterProps = {
/** The corner or edge of the screen the stack sits at. Toasts enter from that edge. */
position?: ToastPosition;
/** How many toasts show at once. Older ones wait behind and come back when a newer one leaves. */
limit?: number;
/** How long a toast stays, in ms, unless it sets its own. 0 keeps toasts until they are closed. */
duration?: number;
/** Play the success, warning or error sound when such a toast appears, if the visitor has sound on. */
sound?: boolean;
/** Extra classes for the stack, merged last. `max-w-md` makes the toasts wider. */
className?: string;
};
/**
* The place where toasts appear. Put one in the app, near the root; `toast()` then works from anywhere.
* The stack is a labelled region that screen readers follow, and nothing is in it until a toast is raised.
*/
export function Toaster({ position = "bottom-right", limit = 3, duration = 5000, sound = true, className }: ToasterProps) {
return (
<ToastPrimitive.Provider toastManager={manager} limit={limit} timeout={duration}>
<ToastPrimitive.Portal>
<ToastPrimitive.Viewport data-slot="toaster" data-position={position} className={cn("fixed z-60 w-[calc(100%-2rem)] max-w-sm outline-none", POSITION[position], className)}>
<Toasts position={position} sound={sound} />
</ToastPrimitive.Viewport>
</ToastPrimitive.Portal>
</ToastPrimitive.Provider>
);
}
function Toasts({ position, sound }: { position: ToastPosition; sound: boolean }) {
const { toasts } = ToastPrimitive.useToastManager();
// A toast speaks once: when it appears with an outcome, or when its promise settles into one.
const heard = useRef(new Map<string, string | undefined>());
useEffect(() => {
const now = new Map<string, string | undefined>();
let cue: SoundName | undefined;
for (const item of toasts) {
now.set(item.id, item.type);
// Newest first: when several arrive in one go, only the newest is heard.
if (item.transitionStatus !== "ending" && heard.current.get(item.id) !== item.type) cue ??= CUE[item.type ?? ""];
}
heard.current = now;
if (cue && sound) play(cue);
}, [toasts, sound]);
const top = position.startsWith("top");
const across = position.endsWith("left") ? (["left"] as const) : position.endsWith("right") ? (["right"] as const) : (["left", "right"] as const);
return toasts.map((item) => {
const icon = ICON[item.type as ToastType] as (typeof ICON)[ToastType] | undefined;
return (
<ToastPrimitive.Root
key={item.id}
toast={item}
// Swiped away towards the nearest edge of the screen.
swipeDirection={[top ? "up" : "down", ...across]}
data-slot="toast"
data-surface="floating"
className={cn(
"absolute inset-x-0 rounded-lg border bg-popover p-3 text-popover-foreground shadow-lg select-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring",
// Each toast sits past the newer ones, 8 pixels apart. The library reads its position from `transform`, so the slide uses it.
top
? "top-0 [--y:calc(var(--toast-offset-y)_+_var(--toast-index)*0.5rem)] data-starting-style:[--exit-y:-100%]"
: "bottom-0 [--y:calc(var(--toast-offset-y)*-1_-_var(--toast-index)*0.5rem)] data-starting-style:[--exit-y:100%]",
"[transform:translateX(calc(var(--toast-swipe-movement-x)_+_var(--exit-x,0px)))_translateY(calc(var(--y)_+_var(--toast-swipe-movement-y)_+_var(--exit-y,0px)))]",
"transition-[transform,opacity] duration-200 ease-out data-swiping:transition-none motion-reduce:transition-none",
"data-ending-style:opacity-0 data-limited:pointer-events-none data-limited:opacity-0 data-starting-style:opacity-0",
// A swiped toast leaves the way it was pushed. A closed or timed-out one fades where it is.
"data-ending-style:data-[swipe-direction=down]:[--exit-y:calc(100%_+_1rem)] data-ending-style:data-[swipe-direction=left]:[--exit-x:calc(-100%_-_1rem)] data-ending-style:data-[swipe-direction=right]:[--exit-x:calc(100%_+_1rem)] data-ending-style:data-[swipe-direction=up]:[--exit-y:calc(-100%_-_1rem)]",
)}
>
<ToastPrimitive.Content data-slot="toast-content" className="flex items-start gap-3">
{icon &&
(icon.glyph ? (
<icon.glyph size={20} className="mt-1 flex-none" style={{ color: icon.color }} />
) : (
<svg
viewBox="0 0 24 24"
className={cn("mt-1 size-5 flex-none", item.type === "loading" && "animate-spin text-muted-foreground motion-reduce:animate-none")}
style={{ color: icon.color }}
fill="none"
stroke="currentColor"
strokeWidth={1.5}
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden="true"
>
<path d="M12 3.75a8.25 8.25 0 1 0 8.25 8.25" />
</svg>
))}
<div className="grid min-w-0 flex-1 gap-0.5 py-1">
<ToastPrimitive.Title data-slot="toast-title" className="text-sm leading-5 font-medium break-words" />
<ToastPrimitive.Description data-slot="toast-description" className="text-sm break-words text-muted-foreground" />
</div>
<ToastPrimitive.Action data-slot="toast-action" className={buttonClass({ variant: "outline", size: "sm" })} />
<ToastPrimitive.Close
data-slot="toast-close"
aria-label="Close"
className="grid size-7 flex-none cursor-pointer place-items-center rounded-md text-muted-foreground transition-colors duration-150 ease-out hover:bg-accent hover:text-accent-foreground focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring motion-reduce:transition-none"
>
<XIcon size={16} />
</ToastPrimitive.Close>
</ToastPrimitive.Content>
</ToastPrimitive.Root>
);
});
}Files and dependencies
- Adds
components/ui/toast.tsx- Packages
@base-ui/react@1.9.0- Brings along
- Sound engineChart foundationsButton
- Icons
circle-checkcircle-xtriangle-alertx
Changelog
- 1.0.0 · 2026-12-03First release.