FreeLoading
Toast Stack
Notifications on a raised surface that stack, fan out on hover or focus and dismiss by swipe, Escape or Delete, with optional thumbnail and undo action; timers pause while the tab is hidden.
When to use it
- Confirmations after save, copy or add to cart
- Non blocking errors that the user can retry
Watch out
- Do not put critical errors only in a toast
- Keep messages short and give actions a clear label
Let your agent add it
One copy holds the install command, when to use it, the props and the design rules. Paste it into Claude Code, Cursor or Codex.
Install with the CLI
Uses the shadcn CLI. The source is copied into your project, so you own every line.
$ npx shadcn@latest add https://sunui.synvize.com/r/toast-stack.jsonOr install manually
- 1. Install the dependencies.
$ npm install clsx tailwind-merge framer-motion - 2. Add a
cnhelper atlib/utils.tsif you do not have one. Not using shadcn/ui? Also add sunui-theme.css for the colour tokens (how). Then copy the component.toast-stack.tsx"use client"; import { AnimatePresence, motion, useReducedMotion, type PanInfo } from "framer-motion"; import { useCallback, useEffect, useLayoutEffect, useRef, useState, type Dispatch, type KeyboardEvent, type ReactNode, type SetStateAction, } from "react"; import { cn } from "@/lib/utils"; export type ToastTone = "default" | "success" | "error" | "info"; export interface ToastInput { id?: string; title: ReactNode; description?: ReactNode; tone?: ToastTone; /** Small image on the left, e.g. a product thumbnail for add-to-cart */ media?: ReactNode; /** Milliseconds; Infinity means never auto-dismiss */ duration?: number; action?: { label: string; onClick: () => void }; } export interface ToastItem extends ToastInput { id: string; } /** Manages the toast queue; the newest is first */ export function useToasts({ max = 5 }: { max?: number } = {}) { const [toasts, setToasts] = useState<ToastItem[]>([]); const counter = useRef(0); const push = useCallback( (input: ToastInput) => { counter.current += 1; const id = input.id ?? `toast-${counter.current}`; setToasts((prev) => [{ ...input, id }, ...prev.filter((t) => t.id !== id)].slice(0, max)); return id; }, [max], ); const dismiss = useCallback((id: string) => setToasts((prev) => prev.filter((t) => t.id !== id)), []); const clear = useCallback(() => setToasts([]), []); return { toasts, push, dismiss, clear }; } export interface UndoableOptions<T> { /** If the previous state was empty there is nothing to undo, so show only a plain success notice */ isEmpty?: (value: T) => boolean; /** When omitted, uses the built-in text for the locale */ undoLabel?: string; /** UI language: en, zh-TW, zh-CN, ja. Tags such as zh-Hant-HK or ja-JP are accepted too */ locale?: string; } /** * For deleting things or replacing a whole data set: the change takes effect immediately with no confirmation dialog, and a notification with "Undo" is shown instead. * A notification with undo does not dismiss itself; pressing Undo puts the entire previous state back. */ export function useUndoable<T>( value: T, setValue: Dispatch<SetStateAction<T>>, toasts: Pick<ReturnType<typeof useToasts>, "push">, { isEmpty, undoLabel, locale = "en" }: UndoableOptions<T> = {}, ) { // When changes are made back to back within one render, use the latest value as the "before" state const latest = useRef(value); useLayoutEffect(() => { latest.current = value; }, [value]); const { push } = toasts; return useCallback( (change: (prev: T) => T, title: ReactNode, toast: Omit<ToastInput, "title" | "action" | "duration"> = {}) => { const before = latest.current; const next = change(before); latest.current = next; setValue(next); if (isEmpty?.(before)) { push({ tone: "success", ...toast, title }); return; } const restore = () => { latest.current = before; setValue(before); }; push({ ...toast, title, duration: Infinity, action: { label: undoLabel ?? MESSAGES[resolveLocale(locale)].undo, onClick: restore } }); }, [setValue, push, isEmpty, undoLabel, locale], ); } export interface ToastStackProps { toasts: ToastItem[]; onDismiss: (id: string) => void; /** Default auto-dismiss time (milliseconds) */ duration?: number; /** Number of layers visible when collapsed */ visibleCount?: number; placement?: "top" | "bottom"; /** Fixed to the bottom right of the window by default; when false, absolute so the parent positions it */ fixed?: boolean; /** How far each layer peeks out when collapsed */ peek?: number; gap?: number; /** UI language: en, zh-TW, zh-CN, ja. Tags such as zh-Hant-HK or ja-JP are accepted too */ locale?: string; /** Override the built-in strings; takes priority over locale */ labels?: Partial<ToastStackLabels>; className?: string; } export interface ToastStackLabels { region: string; dismiss: string; /** The undo button of useUndoable */ undo: string; } type SunLocale = "en" | "zh-TW" | "zh-CN" | "ja"; /** Map any language tag to one of the four built-in languages; everything else falls back to English */ function resolveLocale(tag?: string): SunLocale { const t = (tag ?? "en").toLowerCase(); if (t.startsWith("zh")) return /hant|tw|hk|mo/.test(t) ? "zh-TW" : "zh-CN"; if (t.startsWith("ja")) return "ja"; return "en"; } const MESSAGES: Record<SunLocale, ToastStackLabels> = { en: { region: "Notifications", dismiss: "Dismiss notification", undo: "Undo" }, "zh-TW": { region: "通知", dismiss: "關閉通知", undo: "復原" }, "zh-CN": { region: "通知", dismiss: "关闭通知", undo: "撤销" }, ja: { region: "通知", dismiss: "通知を閉じる", undo: "元に戻す" }, }; // Design language (DESIGN.md, craft quality): surface, hairline, text colour const surface = "bg-card shadow-[0_1px_2px_rgb(0_0_0/0.05),0_4px_12px_-6px_rgb(0_0_0/0.06)] dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.06)]"; const edge = "border-foreground/10"; const ink = "text-foreground"; const inkMuted = "text-muted-foreground"; /** Brand accent: follows the theme's --primary by default; set --sunui-spot to use your own brand colour. Used only for the action key and the remaining-time bar */ const spotBg = "bg-[color:var(--sunui-spot,var(--primary))]"; // Material (DESIGN.md section 7): the action is a small lacquered key in the brand colour, lit from straight above, with a darker // bottom edge for thickness; on press it travels 1px down. The rest of the notification stays a quiet surface const lacquerKey = "bg-[color:var(--sunui-spot,var(--primary))] bg-[linear-gradient(180deg,color-mix(in_oklch,var(--sunui-spot,var(--primary))_74%,white),var(--sunui-spot,var(--primary))_52%,color-mix(in_oklch,var(--sunui-spot,var(--primary))_82%,black))] text-[color:var(--sunui-spot-foreground,var(--primary-foreground))] " + "shadow-[inset_0_1px_0_rgb(255_255_255/0.35),inset_0_-2px_0_rgb(0_0_0/0.2),0_0_0_1px_rgb(0_0_0/0.1),0_1px_2px_rgb(0_0_0/0.16)] " + "active:translate-y-px active:shadow-[inset_0_1px_0_rgb(255_255_255/0.25),inset_0_-1px_0_rgb(0_0_0/0.2),0_0_0_1px_rgb(0_0_0/0.1)]"; const springs = { gentle: { type: "spring", stiffness: 240, damping: 30 }, } as const; /** Status is expressed with a small icon only, with no background fill */ const toneIcons: Record<ToastTone, ReactNode> = { default: null, success: <path d="M5 12.5l4.5 4.5L19 7.5" className="text-[color:var(--sunui-success,#1f9d55)] dark:text-[color:var(--sunui-success,#4cd68a)]" />, error: ( <g className="text-destructive"> <path d="M10.3 4.6L3.4 17a2 2 0 0 0 1.7 3h13.8a2 2 0 0 0 1.7-3L13.7 4.6a2 2 0 0 0-3.4 0z" /> <path d="M12 9.5v4" /> <circle cx="12" cy="16.6" r="1" fill="currentColor" stroke="none" /> </g> ), info: ( <> <circle cx="12" cy="12" r="8.5" /> <path d="M12 11v5" /> <circle cx="12" cy="8" r="1" fill="currentColor" stroke="none" /> </> ), }; export function ToastStack({ toasts, onDismiss, duration = 4500, visibleCount = 3, placement = "bottom", fixed = true, peek = 10, gap = 8, locale = "en", labels, className, }: ToastStackProps) { const reduceMotion = useReducedMotion(); const text = { ...MESSAGES[resolveLocale(locale)], ...labels }; const [hovered, setHovered] = useState(false); const [focused, setFocused] = useState(false); const expanded = hovered || focused; const [heights, setHeights] = useState<Record<string, number>>({}); const dir = placement === "bottom" ? -1 : 1; // Pause the countdown while the tab is hidden and resume it on return const [pageHidden, setPageHidden] = useState(false); useEffect(() => { const sync = () => setPageHidden(document.hidden); sync(); document.addEventListener("visibilitychange", sync); return () => document.removeEventListener("visibilitychange", sync); }, []); const paused = expanded || pageHidden; const dismissRef = useRef(onDismiss); useLayoutEffect(() => { dismissRef.current = onDismiss; }); // Auto-dismiss timer; paused while expanded, and the remaining time is recorded const remaining = useRef(new Map<string, number>()); useEffect(() => { const ids = new Set(toasts.map((t) => t.id)); for (const id of remaining.current.keys()) if (!ids.has(id)) remaining.current.delete(id); if (paused) return; const start = Date.now(); const timers: number[] = []; for (const t of toasts) { const d = t.duration ?? duration; if (!Number.isFinite(d) || d <= 0) continue; const left = remaining.current.get(t.id) ?? d; remaining.current.set(t.id, left); timers.push(window.setTimeout(() => dismissRef.current(t.id), left)); } return () => { const elapsed = Date.now() - start; for (const t of toasts) { const left = remaining.current.get(t.id); if (left !== undefined) remaining.current.set(t.id, Math.max(0, left - elapsed)); } timers.forEach((id) => window.clearTimeout(id)); }; }, [toasts, paused, duration]); const measure = useCallback((id: string, h: number) => { setHeights((prev) => (prev[id] === h ? prev : { ...prev, [id]: h })); }, []); const heightOf = (id: string) => heights[id] ?? 64; const frontHeight = toasts[0] ? heightOf(toasts[0].id) : 0; const shown = Math.min(toasts.length, visibleCount); const stackHeight = expanded ? toasts.reduce((sum, t, i) => sum + heightOf(t.id) + (i > 0 ? gap : 0), 0) : frontHeight + Math.max(0, shown - 1) * peek; const offsetOf = (index: number) => { if (!expanded) return index * peek * dir; let sum = 0; for (let i = 0; i < index; i++) sum += heightOf(toasts[i].id) + gap; return sum * dir; }; const onKeyDown = (e: KeyboardEvent<HTMLElement>) => { if (e.key === "Escape" && toasts[0]) { e.stopPropagation(); onDismiss(toasts[0].id); } }; const transition = reduceMotion ? { duration: 0 } : springs.gentle; return ( <section aria-label={text.region} onMouseEnter={() => setHovered(true)} onMouseLeave={() => setHovered(false)} onFocus={() => setFocused(true)} onBlur={(e) => { if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setFocused(false); }} onKeyDown={onKeyDown} className={cn( fixed ? "fixed z-50" : "absolute z-10", placement === "bottom" ? "bottom-4" : "top-4", "right-4 w-[min(22rem,calc(100%-2rem))]", className, )} > <ol aria-live="polite" aria-relevant="additions" className="relative transition-[height] duration-300 ease-out motion-reduce:transition-none" style={{ height: stackHeight }} > <AnimatePresence initial={false}> {toasts.map((t, index) => { const hidden = !expanded && index >= visibleCount; const d = t.duration ?? duration; return ( <motion.li key={t.id} className={cn( "absolute inset-x-0 overflow-hidden rounded-xl border shadow-[0_1px_2px_rgb(0_0_0/0.05),0_4px_12px_-6px_rgb(0_0_0/0.06)] dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.06)] outline-none focus-visible:ring-2 focus-visible:ring-ring", surface, edge, ink, placement === "bottom" ? "bottom-0 origin-bottom" : "top-0 origin-top", )} style={{ zIndex: toasts.length - index }} initial={reduceMotion ? { opacity: 0 } : { opacity: 0, y: 28 * -dir }} animate={{ opacity: hidden ? 0 : 1, y: offsetOf(index), scale: expanded ? 1 : 1 - index * 0.04, height: !expanded && index > 0 ? frontHeight : "auto", }} exit={reduceMotion ? { opacity: 0, transition: { duration: 0 } } : { opacity: 0, y: 12 * -dir, transition: { duration: 0.16 } }} transition={transition} drag={index === 0 || expanded ? "x" : false} dragConstraints={{ left: 0, right: 0 }} dragElastic={0.6} onDragEnd={(_, info: PanInfo) => { if (Math.abs(info.offset.x) > 90 || Math.abs(info.velocity.x) > 600) onDismiss(t.id); }} aria-hidden={hidden || undefined} aria-atomic="true" tabIndex={hidden ? -1 : 0} onKeyDown={(e) => { // While a notification has focus, Delete or Backspace dismisses that one if ((e.key === "Delete" || e.key === "Backspace") && e.target === e.currentTarget) { e.stopPropagation(); onDismiss(t.id); } }} > <ToastBody item={t} dismissLabel={text.dismiss} onDismiss={() => onDismiss(t.id)} onMeasure={(h) => measure(t.id, h)} inert={hidden} /> {/* Remaining time: a thin line at the bottom slowly shrinks */} {!reduceMotion && Number.isFinite(d) && d > 0 && ( <span aria-hidden="true" className={cn("absolute inset-x-0 bottom-0 h-0.5 origin-left opacity-80", spotBg)} style={{ animation: `sunui-toast-timer ${d}ms linear forwards`, animationPlayState: paused ? "paused" : "running" }} /> )} </motion.li> ); })} </AnimatePresence> </ol> <style>{`@keyframes sunui-toast-timer { from { transform: scaleX(1) } to { transform: scaleX(0) } }`}</style> </section> ); } function ToastBody({ item, dismissLabel, onDismiss, onMeasure, inert, }: { item: ToastItem; dismissLabel: string; onDismiss: () => void; onMeasure: (h: number) => void; inert: boolean; }) { const ref = useRef<HTMLDivElement>(null); const measureRef = useRef(onMeasure); useLayoutEffect(() => { measureRef.current = onMeasure; }); useLayoutEffect(() => { const el = ref.current; if (!el) return; measureRef.current(el.offsetHeight); const ro = new ResizeObserver(() => measureRef.current(el.offsetHeight)); ro.observe(el); return () => ro.disconnect(); }, []); const icon = toneIcons[item.tone ?? "default"]; return ( <div ref={ref} className="flex items-start gap-3 p-3 pr-2" {...(inert ? { inert: true } : {})}> {item.media ? ( <span aria-hidden="true" className={cn("size-11 shrink-0 overflow-hidden rounded-[3px] border", edge)}> {item.media} </span> ) : ( icon && ( <svg viewBox="0 0 24 24" className="mt-0.5 size-4 shrink-0" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"> {icon} </svg> ) )} <div className="min-w-0 flex-1 py-0.5"> <p className="text-sm font-medium">{item.title}</p> {item.description && <p className={cn("mt-0.5 text-[13px] leading-snug", inkMuted)}>{item.description}</p>} </div> {item.action && ( <button type="button" onClick={() => { item.action?.onClick(); onDismiss(); }} className={cn("mt-0.5 shrink-0 rounded-md px-2.5 py-1 text-[13px] leading-4 font-semibold outline-none hover:brightness-105 focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-card motion-safe:active:scale-[0.97] transition-[filter,translate,box-shadow,scale]", lacquerKey)} > {item.action.label} </button> )} <button type="button" onClick={onDismiss} aria-label={dismissLabel} className={cn("shrink-0 rounded-[3px] p-1 outline-none transition-[color,background-color,border-color,opacity,scale] hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring motion-safe:active:scale-[0.97]", inkMuted)} > <svg viewBox="0 0 24 24" className="size-3.5" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" aria-hidden="true" strokeLinejoin="round"> <path d="M6.5 6.5l11 11M17.5 6.5l-11 11" /> </svg> </button> </div> ); }
Similar blocks
- Pro
- Pro
- Pro





