Toast
Short messages that confirm, report progress or offer an undo, then leave on their own. Five variants, each a single file.
Stack
Brief confirmations that stack neatly, fan out on hover and leave on their own.
Installation
$npx shadcn@latest add @stillui/toastOr copy the source into your project. It needs the shadcn color tokens and the cn helper.
"use client";
// stillui.dev/components/toast
import { animate, AnimatePresence, motion, useMotionValue, useReducedMotion, useTransform, type PanInfo } from "motion/react";
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import { cn } from "@/lib/utils";
const DURATION = 4000;
const VISIBLE = 3;
const GAP = 8;
const ENTER = {
type: "spring",
stiffness: 380,
damping: 34,
mass: 0.9,
} as const;
// A swipe this far, or a flick this fast, sends the toast away; anything less springs it back.
const SWIPE_DISTANCE = 80;
const SWIPE_VELOCITY = 500;
type Tone = "neutral" | "success" | "error";
type Toast = {
id: number;
title: string;
description?: string;
tone: Tone;
};
type ToastInput = Omit<Toast, "id" | "tone"> & { tone?: Tone };
const ToastContext = createContext<((toast: ToastInput) => void) | null>(null);
/** Returns a function that shows a toast. Must be used inside <ToastProvider>. */
export function useToast() {
const add = useContext(ToastContext);
if (!add) throw new Error("useToast must be used inside <ToastProvider>");
return add;
}
export function ToastProvider({ children }: { children: ReactNode }) {
const [toasts, setToasts] = useState<Toast[]>([]);
const nextId = useRef(0);
const add = useCallback((toast: ToastInput) => {
const id = nextId.current++;
const next: Toast = { tone: "neutral", ...toast, id };
setToasts((list) => [next, ...list].slice(0, VISIBLE + 1));
}, []);
const remove = useCallback((id: number) => setToasts((list) => list.filter((t) => t.id !== id)), []);
return (
<ToastContext.Provider value={add}>
{children}
<Toaster toasts={toasts} onDismiss={remove} />
</ToastContext.Provider>
);
}
function Toaster({ toasts, onDismiss }: { toasts: Toast[]; onDismiss: (id: number) => void }) {
const [expanded, setExpanded] = useState(false);
const [heights, setHeights] = useState<Record<number, number>>({});
const measure = useCallback((id: number, height: number) => {
setHeights((h) => (h[id] === height ? h : { ...h, [id]: height }));
}, []);
// Offset of each toast when the stack is fanned out on hover.
const offsets = useMemo(() => {
const result: number[] = [];
let total = 0;
for (const t of toasts) {
result.push(total);
total += (heights[t.id] ?? 64) + GAP;
}
return result;
}, [toasts, heights]);
return (
<section
aria-label="Notifications"
className="pointer-events-none fixed bottom-4 right-4 z-[100] w-[min(22rem,calc(100vw-2rem))]"
onPointerEnter={() => setExpanded(true)}
onPointerLeave={() => setExpanded(false)}
>
<ol role="status" aria-live="polite" className="relative">
<AnimatePresence initial={false}>
{toasts.map((toast, index) => (
<ToastItem
key={toast.id}
toast={toast}
index={index}
offset={offsets[index]}
height={expanded ? heights[toast.id] : heights[toasts[0].id]}
expanded={expanded}
paused={expanded}
onMeasure={measure}
onDismiss={onDismiss}
/>
))}
</AnimatePresence>
</ol>
</section>
);
}
type ToastItemProps = {
toast: Toast;
index: number;
offset: number;
/** Collapsed cards take the front card's height so a taller one never sticks out behind it. */
height?: number;
expanded: boolean;
paused: boolean;
onMeasure: (id: number, height: number) => void;
onDismiss: (id: number) => void;
};
function ToastItem({ toast, index, offset, height, expanded, paused, onMeasure, onDismiss }: ToastItemProps) {
const reduce = useReducedMotion();
const ref = useRef<HTMLDivElement>(null);
const hidden = index >= VISIBLE;
const swipeable = !hidden && (expanded || index === 0);
// Swiping right drags the card out; its content fades as it goes.
const x = useMotionValue(0);
const contentOpacity = useTransform(x, [0, 160], [1, 0.2]);
const onDragEnd = (_: unknown, info: PanInfo) => {
if (info.offset.x > SWIPE_DISTANCE || info.velocity.x > SWIPE_VELOCITY) {
const width = ref.current?.offsetWidth ?? 360;
animate(x, width + 48, {
type: "spring",
stiffness: 300,
damping: 34,
velocity: info.velocity.x,
});
window.setTimeout(() => onDismiss(toast.id), 140);
}
};
useEffect(() => {
if (ref.current) onMeasure(toast.id, ref.current.offsetHeight);
}, [toast.id, toast.title, toast.description, onMeasure]);
// Auto-dismiss, paused while the pointer is over the stack.
useEffect(() => {
if (paused) return;
const timer = window.setTimeout(() => onDismiss(toast.id), DURATION);
return () => window.clearTimeout(timer);
}, [paused, toast.id, onDismiss]);
// Collapsed: older toasts tuck behind the newest. Expanded: they fan out into a list.
const y = expanded ? -offset : -index * 10;
const scale = expanded || reduce ? 1 : 1 - index * 0.05;
return (
<motion.li
className="pointer-events-auto absolute bottom-0 right-0 w-full overflow-hidden rounded-xl bg-popover text-popover-foreground shadow-overlay"
style={{ zIndex: 10 - index, originY: 1, x }}
initial={{
opacity: 0,
y: reduce ? 0 : 24,
scale: 1,
filter: reduce ? "none" : "blur(6px)",
}}
animate={{
opacity: hidden ? 0 : 1,
y,
scale,
height: height ?? "auto",
filter: "blur(0px)",
}}
exit={{
opacity: 0,
scale: reduce ? 1 : 0.96,
filter: reduce ? "none" : "blur(4px)",
transition: { duration: 0.15 },
}}
transition={reduce ? { duration: 0 } : ENTER}
drag={swipeable && !reduce ? "x" : false}
dragConstraints={{ left: 0, right: 0 }}
dragElastic={{ left: 0.05, right: 0.9 }}
onDragEnd={onDragEnd}
aria-hidden={hidden || undefined}
>
<motion.div style={{ opacity: contentOpacity }}>
<div ref={ref} className={cn("flex gap-3 p-4 transition-opacity duration-150", !expanded && index > 0 && "opacity-0")}>
<ToneIcon tone={toast.tone} />
<div className="grid min-w-0 flex-1 gap-0.5">
<p className="text-sm font-medium leading-5">{toast.title}</p>
{toast.description ? <p className="text-[13px] leading-5 text-muted-foreground">{toast.description}</p> : null}
</div>
<button
type="button"
onClick={() => onDismiss(toast.id)}
aria-label="Dismiss notification"
className="-m-1 grid size-6 shrink-0 place-items-center rounded-md text-faint-foreground transition-[color,background-color,box-shadow,scale] active:scale-[0.9] hover:bg-secondary hover:text-foreground"
>
<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" className="size-3.5" aria-hidden>
<path d="M4.5 4.5l7 7m0-7l-7 7" />
</svg>
</button>
</div>
</motion.div>
</motion.li>
);
}
function ToneIcon({ tone }: { tone: Tone }) {
if (tone === "neutral") return null;
return (
<svg
viewBox="0 0 16 16"
fill="none"
stroke="currentColor"
strokeWidth="1.75"
strokeLinecap="round"
strokeLinejoin="round"
className={cn("mt-0.5 size-4 shrink-0", tone === "success" ? "text-success" : "text-destructive")}
aria-hidden
>
{tone === "success" ? <path d="M3.5 8.5l3 3 6-7" /> : <path d="M8 4.5v4m0 3v.01" />}
</svg>
);
}States
- Enter
- Rises from below on a soft spring; the previous toast tucks behind it.
- Stacked
- Up to three stay visible, older ones smaller and further back.
- Hover
- The stack fans out into a list and every timer pauses so nothing disappears while you read.
- Dismiss
- Leaves faster than it arrived, after 4 seconds or on the close button.
- Tones
- Neutral, success and error. The icon carries the meaning too, not just its color.
- Screen readers
- Announced politely through a live region, without stealing focus.
Notes
Wrap your app once in ToastProvider, then call useToast() anywhere below it.
Use toasts only for things people need to know. Confirming every small action trains people to ignore them.
Never put the only way to undo something in a toast; it may be gone before someone reaches it.
Pill
One short message in a capsule at the top of the screen. A new message reshapes the same pill instead of stacking.
Installation
$npx shadcn@latest add @stillui/toast-pillOr copy the source into your project. It needs the shadcn color tokens and the cn helper.
"use client";
// stillui.dev/components/toast#pill
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import { createContext, useCallback, useContext, useEffect, useRef, useState, type ReactNode } from "react";
const DURATION = 2400;
const MORPH = { type: "spring", stiffness: 420, damping: 36 } as const;
type Tone = "neutral" | "success" | "error";
type PillToast = {
id: number;
title: string;
tone: Tone;
};
type PillToastInput = { title: string; tone?: Tone };
const PillToastContext = createContext<((toast: PillToastInput) => void) | null>(null);
/** Returns a function that shows a pill. Must be used inside <PillToastProvider>. */
export function usePillToast() {
const show = useContext(PillToastContext);
if (!show) throw new Error("usePillToast must be used inside <PillToastProvider>");
return show;
}
export function PillToastProvider({ children }: { children: ReactNode }) {
const [toast, setToast] = useState<PillToast | null>(null);
const nextId = useRef(0);
// A new message replaces the current one; the pill reshapes around it.
const show = useCallback((input: PillToastInput) => {
setToast({ tone: "neutral", ...input, id: nextId.current++ });
}, []);
useEffect(() => {
if (!toast) return;
const timer = window.setTimeout(() => setToast(null), DURATION);
return () => window.clearTimeout(timer);
}, [toast]);
return (
<PillToastContext.Provider value={show}>
{children}
<Pill toast={toast} />
</PillToastContext.Provider>
);
}
function Pill({ toast }: { toast: PillToast | null }) {
const reduce = useReducedMotion();
const spring = reduce ? { duration: 0 } : MORPH;
return (
<div className="pointer-events-none fixed inset-x-0 top-4 z-[100] flex justify-center px-4">
<div role="status" aria-live="polite" className="sr-only">
{toast?.title}
</div>
<AnimatePresence>
{toast ? (
<motion.div
layout
aria-hidden
className="flex h-10 items-center overflow-hidden bg-foreground px-4 text-background shadow-overlay"
style={{ borderRadius: 999 }}
initial={{ opacity: 0, y: reduce ? 0 : -12, scale: reduce ? 1 : 0.9, filter: reduce ? "none" : "blur(6px)" }}
animate={{ opacity: 1, y: 0, scale: 1, filter: "blur(0px)" }}
exit={{ opacity: 0, y: reduce ? 0 : -8, scale: reduce ? 1 : 0.95, filter: reduce ? "none" : "blur(4px)", transition: { duration: 0.15 } }}
transition={spring}
>
<AnimatePresence mode="popLayout" initial={false}>
<motion.span
key={toast.id}
layout="position"
className="flex items-center gap-2 whitespace-nowrap text-sm font-medium"
initial={{ opacity: 0, y: reduce ? 0 : 8, filter: reduce ? "none" : "blur(4px)" }}
animate={{ opacity: 1, y: 0, filter: "blur(0px)" }}
exit={{ opacity: 0, y: reduce ? 0 : -8, filter: reduce ? "none" : "blur(4px)" }}
transition={spring}
>
<ToneIcon tone={toast.tone} />
{toast.title}
</motion.span>
</AnimatePresence>
</motion.div>
) : null}
</AnimatePresence>
</div>
);
}
// Icons use the pill's own color, so the shape carries the meaning on the inverted background.
function ToneIcon({ tone }: { tone: Tone }) {
if (tone === "neutral") return null;
return (
<svg
viewBox="0 0 16 16"
fill="none"
stroke="currentColor"
strokeWidth="1.75"
strokeLinecap="round"
strokeLinejoin="round"
className="size-4 shrink-0"
aria-hidden
>
{tone === "success" ? (
<path d="M3.5 8.5l3 3 6-7" />
) : (
<>
<circle cx="8" cy="8" r="6" />
<path d="M8 5v3.5m0 2.5v.01" />
</>
)}
</svg>
);
}States
- Enter
- Drops in from above and settles on a spring.
- Replace
- The old text slides out, the new text slides in, and the pill resizes around it.
- Leave
- Fades up and away after 2.4 seconds. Each new message restarts the timer.
- Tones
- Neutral, success and error, told apart by the icon’s shape since the pill is one color.
- Reduced motion
- Appears and changes without movement.
- Screen readers
- The text is announced through a polite live region.
Notes
Best for a word or two: Copied, Saved, Sent. Anything longer, or anything with an action, belongs in the stack or action variant.
Action
One message at the bottom of the screen with a single action, like Undo. It waits while you hover or focus it.
Installation
$npx shadcn@latest add @stillui/toast-actionOr copy the source into your project. It needs the shadcn color tokens and the cn helper.
"use client";
// stillui.dev/components/toast#action
import { AnimatePresence, motion, useReducedMotion, type PanInfo } from "motion/react";
import { createContext, useCallback, useContext, useEffect, useRef, useState, type ReactNode } from "react";
// Longer than a plain toast: people need time to read and decide.
const DURATION = 6000;
const ENTER = { type: "spring", stiffness: 380, damping: 34 } as const;
type ActionToast = {
id: number;
title: string;
action?: { label: string; onAction: () => void };
};
type ActionToastInput = Omit<ActionToast, "id">;
const ActionToastContext = createContext<((toast: ActionToastInput) => void) | null>(null);
/** Returns a function that shows a toast with one action. Must be used inside <ActionToastProvider>. */
export function useActionToast() {
const show = useContext(ActionToastContext);
if (!show) throw new Error("useActionToast must be used inside <ActionToastProvider>");
return show;
}
export function ActionToastProvider({ children }: { children: ReactNode }) {
const [toast, setToast] = useState<ActionToast | null>(null);
const [paused, setPaused] = useState(false);
const nextId = useRef(0);
const show = useCallback((input: ActionToastInput) => setToast({ ...input, id: nextId.current++ }), []);
const dismiss = useCallback(() => setToast(null), []);
// Waits while the pointer or keyboard focus is on the toast.
useEffect(() => {
if (!toast || paused) return;
const timer = window.setTimeout(dismiss, DURATION);
return () => window.clearTimeout(timer);
}, [toast, paused, dismiss]);
return (
<ActionToastContext.Provider value={show}>
{children}
<div
className="pointer-events-none fixed inset-x-0 bottom-6 z-[100] flex justify-center px-4"
onPointerEnter={() => setPaused(true)}
onPointerLeave={() => setPaused(false)}
onFocus={() => setPaused(true)}
onBlur={() => setPaused(false)}
>
<div role="status" aria-live="polite" className="sr-only">
{toast ? `${toast.title}${toast.action ? `. ${toast.action.label} is available.` : ""}` : ""}
</div>
<AnimatePresence mode="popLayout">
{toast ? <ActionCard key={toast.id} toast={toast} onDismiss={dismiss} /> : null}
</AnimatePresence>
</div>
</ActionToastContext.Provider>
);
}
function ActionCard({ toast, onDismiss }: { toast: ActionToast; onDismiss: () => void }) {
const reduce = useReducedMotion();
return (
<motion.div
className="pointer-events-auto flex min-h-12 w-[min(26rem,100%)] items-center gap-3 rounded-xl bg-popover py-2 pl-4 pr-2 text-popover-foreground shadow-overlay"
initial={{ opacity: 0, y: reduce ? 0 : 16, filter: reduce ? "none" : "blur(6px)" }}
animate={{ opacity: 1, y: 0, filter: "blur(0px)" }}
exit={{ opacity: 0, y: reduce ? 0 : 24, filter: reduce ? "none" : "blur(4px)", transition: { duration: 0.18 } }}
transition={reduce ? { duration: 0 } : ENTER}
// Swipe down to put it away; a short or slow pull springs back.
drag={reduce ? false : "y"}
dragConstraints={{ top: 0, bottom: 0 }}
dragElastic={{ top: 0.05, bottom: 0.8 }}
onDragEnd={(_: unknown, info: PanInfo) => (info.offset.y > 48 || info.velocity.y > 400) && onDismiss()}
onKeyDown={(event) => event.key === "Escape" && onDismiss()}
>
<p className="min-w-0 flex-1 text-sm leading-5">{toast.title}</p>
{toast.action ? (
<button
type="button"
onClick={() => {
toast.action?.onAction();
onDismiss();
}}
className="h-8 shrink-0 rounded-md bg-secondary px-3 text-[13px] font-medium text-secondary-foreground transition-[color,background-color,box-shadow,scale] active:scale-[0.96] hover:bg-secondary/70"
>
{toast.action.label}
</button>
) : null}
<button
type="button"
onClick={onDismiss}
aria-label="Dismiss notification"
className="grid size-8 shrink-0 place-items-center rounded-md text-faint-foreground transition-[color,background-color,box-shadow,scale] active:scale-[0.92] hover:bg-secondary hover:text-foreground"
>
<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" className="size-3.5" aria-hidden>
<path d="M4.5 4.5l7 7m0-7l-7 7" />
</svg>
</button>
</motion.div>
);
}States
- Enter
- Rises from the bottom edge. A new toast replaces the current one.
- Action
- Runs the action, then dismisses. There is only ever one action, so the choice is obvious.
- Waiting
- The 6 second timer pauses while the pointer or keyboard focus is on the toast.
- Dismiss
- The close button or Escape, while focus is inside.
- Reduced motion
- Appears and leaves without movement.
- Screen readers
- Announces the message and that an action is available, without moving focus.
Notes
Undo in a toast is a shortcut, not the only way back. Keep deleted items recoverable somewhere people can find later, such as a trash folder.
Promise
Follows a request from start to finish in one toast. The spinner becomes a check or an error, and the text changes in place.
Installation
$npx shadcn@latest add @stillui-pro/toast-promiseA paid component. The command needs the token from your account in STILLUI_TOKEN; your account page shows the one-time setup.
This is a paid component. Its source and install come with access.
States
- Loading
- A spinner and what is happening. Stays for as long as the request takes.
- Success
- The spinner turns into a check that draws itself; the card resizes to the new text.
- Error
- An error mark and a reason, so people know what to try next.
- Leave
- Leaves 3 seconds after the result arrives.
- Overlap
- Starting a new request replaces the toast; a late result from the older one is ignored.
- Reduced motion
- No sliding or drawing; the spinner turns slowly.
Notes
track() returns the same promise, so you can still await it: await track(save(), { loading, success, error }).
Skip the toast for requests that usually finish in under half a second. A flash of loading text is noise.
Anchored
A short message that appears right next to the button that caused it, where the eye already is. No provider needed.
Installation
$npx shadcn@latest add @stillui/toast-anchoredOr copy the source into your project. It needs the shadcn color tokens and the cn helper.
"use client";
// stillui.dev/components/toast#anchored
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import { useCallback, useEffect, useState, type ReactNode } from "react";
import { cn } from "@/lib/utils";
const DURATION = 1800;
const POP = { type: "spring", stiffness: 520, damping: 32 } as const;
// Each message gets a fresh key, so pressing twice replays the pop.
let nextId = 0;
type Tone = "neutral" | "success" | "error";
type AnchoredToast = {
id: number;
title: string;
tone: Tone;
};
type AnchoredToastInput = { title: string; tone?: Tone };
type ToastAnchorProps = {
/** Render the trigger. Call show() from it to put a message next to it. */
children: (show: (toast: AnchoredToastInput) => void) => ReactNode;
/** Where the message appears relative to the trigger. */
side?: "top" | "bottom";
className?: string;
};
/** Shows a short message right where the action happened, so the eye doesn't have to travel. */
export function ToastAnchor({ children, side = "top", className }: ToastAnchorProps) {
const reduce = useReducedMotion();
const [toast, setToast] = useState<AnchoredToast | null>(null);
const show = useCallback((input: AnchoredToastInput) => {
setToast({ tone: "neutral", ...input, id: nextId++ });
}, []);
useEffect(() => {
if (!toast) return;
const timer = window.setTimeout(() => setToast(null), DURATION);
return () => window.clearTimeout(timer);
}, [toast]);
const offset = side === "top" ? 6 : -6;
return (
<span className={cn("relative inline-flex", className)}>
{children(show)}
<span role="status" aria-live="polite" className="sr-only">
{toast?.title}
</span>
<span
aria-hidden
className={cn(
"pointer-events-none absolute inset-x-0 z-50 flex justify-center",
side === "top" ? "bottom-full mb-2" : "top-full mt-2",
)}
>
<AnimatePresence mode="popLayout">
{toast ? (
<motion.span
key={toast.id}
className="flex h-8 items-center gap-1.5 whitespace-nowrap rounded-lg bg-foreground px-2.5 text-[13px] font-medium text-background shadow-overlay"
style={{ originY: side === "top" ? 1 : 0 }}
initial={{ opacity: 0, y: reduce ? 0 : offset, scale: reduce ? 1 : 0.92 }}
animate={{ opacity: 1, y: 0, scale: 1 }}
exit={{ opacity: 0, scale: reduce ? 1 : 0.96, transition: { duration: 0.12 } }}
transition={reduce ? { duration: 0 } : POP}
>
<ToneIcon tone={toast.tone} />
{toast.title}
</motion.span>
) : null}
</AnimatePresence>
</span>
</span>
);
}
function ToneIcon({ tone }: { tone: Tone }) {
if (tone === "neutral") return null;
return (
<svg
viewBox="0 0 16 16"
fill="none"
stroke="currentColor"
strokeWidth="1.75"
strokeLinecap="round"
strokeLinejoin="round"
className="size-3.5 shrink-0"
aria-hidden
>
{tone === "success" ? (
<path d="M3.5 8.5l3 3 6-7" />
) : (
<>
<circle cx="8" cy="8" r="6" />
<path d="M8 5v3.5m0 2.5v.01" />
</>
)}
</svg>
);
}States
- Enter
- Pops out of the trigger on a quick spring, above it by default or below with side="bottom".
- Repeat
- Pressing again restarts the message and its timer instead of piling up copies.
- Leave
- Gone after 1.8 seconds; the message is short enough to read at a glance.
- Tones
- Neutral, success and error, told apart by the icon’s shape.
- Reduced motion
- Appears and leaves without movement.
- Screen readers
- Each anchor has its own polite live region, so the message is announced.
Notes
Use it when the result belongs to one control, such as Copy link. For results that affect the whole page, use the stack or action variant.