Toast
The shadcn/ui Sonner Toaster restyled for dark interfaces, with tinted status icons and on-brand rich colors — plus two animated React toast notification blocks built with Motion: a custom toast whose icon morphs from loading to success or error with a progress line and promise helpers, and an undo toast for optimistic deletes.
- Sonner
- Drop-in shadcn API
- Promise toasts
- Motion blocks
"use client";
import { Button } from "@/components/ui/button";
import { animatedToast } from "@/components/dusk/toast/animated-toast";
const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
let attempts = 0;
export default function AnimatedToastDemo() {
return (
<div className="flex flex-wrap justify-center gap-2">
<Button
onClick={() =>
animatedToast.promise(() => wait(2000).then(() => ({ url: "dusk-web.vercel.app" })), {
loading: { title: "Deploying dusk-web…", description: "Building and uploading 128 files" },
success: (data) => ({ title: "Deployed", description: `Live at ${data.url}` }),
error: "Deployment failed",
})
}
>
Deploy
</Button>
<Button
variant="outline"
onClick={() => {
attempts = 0;
animatedToast.promise(
async () => {
await wait(1500);
// Fails the first time; Retry succeeds.
if (attempts++ === 0) throw new Error("Network error");
},
{
loading: "Syncing contacts…",
success: "Contacts synced",
error: (error) => ({
title: "Sync failed",
description: error instanceof Error ? error.message : undefined,
}),
}
);
}}
>
Sync (fails once)
</Button>
<Button variant="outline" onClick={() => animatedToast.success("Invite sent", { description: "ada@dusk.dev can join now." })}>
Success
</Button>
<Button
variant="outline"
onClick={() =>
animatedToast.warning("API key expires in 3 days", {
duration: 8000,
action: { label: "Rotate key", onClick: () => animatedToast.success("New key created") },
})
}
>
With action
</Button>
</div>
);
}Installation
$ npx shadcn@latest add https://duskui.com/r/toast.json1. Install the dependencies.
npm install sonner lucide-react2. Copy the source into
components/ui/sonner.tsx.sonner.tsx "use client"; import * as React from "react"; import { CircleCheckIcon, InfoIcon, Loader2Icon, OctagonXIcon, TriangleAlertIcon, XIcon, } from "lucide-react"; import { Toaster as Sonner, type ToasterProps } from "sonner"; import { cn } from "@/lib/utils"; /* * Sonner injects its own unlayered CSS, which beats Tailwind's layered * utilities. So colors go through Sonner's CSS variables, and the few extra * styles use `!` and are scoped to `data-[styled=true]` so they never touch * fully custom toasts (`toast.custom`). */ const toastClassNames: NonNullable<NonNullable<ToasterProps["toastOptions"]>["classNames"]> = { toast: cn( "data-[styled=true]:gap-2.5! data-[styled=true]:px-4! data-[styled=true]:py-3.5!", "data-[styled=true]:shadow-lg!", "data-[styled=true]:focus-visible:ring-[3px]! data-[styled=true]:focus-visible:ring-ring/50!" ), title: "text-sm! font-medium! leading-snug!", description: "text-[0.8125rem]! leading-snug! text-muted-foreground!", icon: "self-start! mt-0.5!", actionButton: cn( "h-7! rounded-md! bg-primary! px-2.5! text-xs! font-medium! text-primary-foreground!", "transition-[background-color,box-shadow]! hover:bg-primary/90! focus-visible:ring-[3px]! focus-visible:ring-ring/50!" ), cancelButton: cn( "h-7! rounded-md! bg-secondary! px-2.5! text-xs! font-medium! text-secondary-foreground!", "transition-colors! hover:bg-secondary/80! focus-visible:ring-[3px]! focus-visible:ring-ring/50!" ), closeButton: cn( "border-border! bg-popover! text-muted-foreground! transition-colors!", "hover:bg-accent! hover:text-foreground! focus-visible:ring-[3px]! focus-visible:ring-ring/50!" ), }; /** Merges our class names with any the caller passes, key by key. */ function mergeClassNames( extra: NonNullable<ToasterProps["toastOptions"]>["classNames"] ): NonNullable<ToasterProps["toastOptions"]>["classNames"] { if (!extra) return toastClassNames; const keys = new Set([...Object.keys(toastClassNames), ...Object.keys(extra)]) as Set< keyof typeof toastClassNames >; const merged: typeof toastClassNames = {}; for (const key of keys) merged[key] = cn(toastClassNames[key], extra[key]); return merged; } /** * DuskUI Toaster — a drop-in upgrade of the shadcn/ui Sonner Toaster. * * Same component and props as shadcn (every Sonner `ToasterProps`), plus: * - Dark by default and styled with the DuskUI tokens: popover surface, * neutral shadow, mint action button, tinted status icons. * - On-brand `richColors` (success, info, warning, error). * - Your `toastOptions.classNames` are merged with ours instead of replacing them. * Fire toasts with `toast()` from "sonner" anywhere in your app. * Sonner already pauses on hover, supports swipe-to-dismiss and keyboard * focus (Alt+T), and disables its animations under reduced motion. */ function Toaster({ theme = "dark", className, toastOptions, style, icons, ...props }: ToasterProps) { return ( <Sonner theme={theme} // Sonner sets a system font stack on the toaster; use the app font instead. className={cn("toaster group font-sans!", className)} icons={{ success: <CircleCheckIcon className="size-4 text-emerald-300" />, info: <InfoIcon className="size-4 text-sky-300" />, warning: <TriangleAlertIcon className="size-4 text-amber-300" />, error: <OctagonXIcon className="size-4 text-destructive" />, loading: <Loader2Icon className="size-4 animate-spin text-muted-foreground motion-reduce:animate-none" />, close: <XIcon className="size-3" />, ...icons, }} toastOptions={{ ...toastOptions, classNames: mergeClassNames(toastOptions?.classNames), }} style={ { "--normal-bg": "var(--popover)", "--normal-bg-hover": "var(--accent)", "--normal-text": "var(--popover-foreground)", "--normal-border": "var(--border)", "--normal-border-hover": "var(--input)", "--border-radius": "calc(var(--radius) + 4px)", "--success-bg": "color-mix(in oklab, oklch(0.765 0.177 163.2) 10%, var(--popover))", "--success-border": "color-mix(in oklab, oklch(0.765 0.177 163.2) 25%, transparent)", "--success-text": "oklch(0.845 0.143 165)", "--info-bg": "color-mix(in oklab, oklch(0.746 0.16 232.7) 10%, var(--popover))", "--info-border": "color-mix(in oklab, oklch(0.746 0.16 232.7) 25%, transparent)", "--info-text": "oklch(0.828 0.111 230.3)", "--warning-bg": "color-mix(in oklab, oklch(0.828 0.189 84.4) 10%, var(--popover))", "--warning-border": "color-mix(in oklab, oklch(0.828 0.189 84.4) 25%, transparent)", "--warning-text": "oklch(0.879 0.169 91.6)", "--error-bg": "color-mix(in oklab, var(--destructive) 14%, var(--popover))", "--error-border": "color-mix(in oklab, var(--destructive) 35%, transparent)", "--error-text": "oklch(0.8 0.12 25)", ...style, } as React.CSSProperties } {...props} /> ); } export { Toaster };
Replaces components/ui/sonner.tsx; the Toaster export and all Sonner props still work, and your toastOptions.classNames are merged with ours. It defaults to the dark theme and no longer needs next-themes. Mount <Toaster /> once (e.g. in your root layout), then call toast() from sonner anywhere.
Usage
import { Toaster } from "@/components/ui/sonner"
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en" className="dark">
<body>
{children}
<Toaster position="bottom-right" />
</body>
</html>
)
}
// anywhere in a client component
import { toast } from "sonner"
toast.success("Changes saved", { description: "Your team can see them now." })Examples
Types
toast(), toast.success, .info, .warning and .error on the popover surface with a layered shadow, tinted icons and a mint action button. Hover the stack to expand it and pause the timers; swipe to dismiss.
"use client";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
export default function ToastBasicDemo() {
return (
<div className="flex flex-wrap justify-center gap-2">
<Button variant="outline" onClick={() => toast("Event created", { description: "Sunday, December 3 at 9:00 AM" })}>
Default
</Button>
<Button variant="outline" onClick={() => toast.success("Changes saved")}>
Success
</Button>
<Button variant="outline" onClick={() => toast.info("New version available", { description: "Refresh to update." })}>
Info
</Button>
<Button variant="outline" onClick={() => toast.warning("Storage almost full")}>
Warning
</Button>
<Button variant="outline" onClick={() => toast.error("Couldn't reach the server")}>
Error
</Button>
<Button
variant="outline"
onClick={() =>
toast("Message archived", {
action: { label: "Undo", onClick: () => toast.success("Message restored") },
})
}
>
With action
</Button>
</div>
);
}Promise
Sonner's toast.promise shows a spinner until the promise settles, then the success or error message. Pass richColors to the Toaster for tinted success and error toasts in the DuskUI palette.
"use client";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
const save = () =>
new Promise<{ name: string }>((resolve) => setTimeout(() => resolve({ name: "brand-kit.fig" }), 1800));
export default function ToastPromiseDemo() {
return (
<Button
variant="outline"
onClick={() =>
toast.promise(save(), {
loading: "Uploading…",
success: (file) => `${file.name} uploaded`,
error: "Upload failed",
})
}
>
Upload file
</Button>
);
}Blocks
Ready-made variations composed from the base component with Motion. Each installs on its own and pulls in its dependencies automatically.
Animated Toast
A custom toast rendered with toast.custom. Update it by id and the icon changes: the spinner fades out and the check or cross draws itself in. A thin line shows the time left, driven by the same motion value as the timer, so they never drift; it pauses on hover, focus and hidden tabs. animatedToast.promise keeps the spinner up for at least minLoading ms so fast requests don't flash, and when you pass a function it adds a Retry button that re-runs it in the same toast. Try “Sync”.
"use client";
import { Button } from "@/components/ui/button";
import { animatedToast } from "@/components/dusk/toast/animated-toast";
const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
let attempts = 0;
export default function AnimatedToastDemo() {
return (
<div className="flex flex-wrap justify-center gap-2">
<Button
onClick={() =>
animatedToast.promise(() => wait(2000).then(() => ({ url: "dusk-web.vercel.app" })), {
loading: { title: "Deploying dusk-web…", description: "Building and uploading 128 files" },
success: (data) => ({ title: "Deployed", description: `Live at ${data.url}` }),
error: "Deployment failed",
})
}
>
Deploy
</Button>
<Button
variant="outline"
onClick={() => {
attempts = 0;
animatedToast.promise(
async () => {
await wait(1500);
// Fails the first time; Retry succeeds.
if (attempts++ === 0) throw new Error("Network error");
},
{
loading: "Syncing contacts…",
success: "Contacts synced",
error: (error) => ({
title: "Sync failed",
description: error instanceof Error ? error.message : undefined,
}),
}
);
}}
>
Sync (fails once)
</Button>
<Button variant="outline" onClick={() => animatedToast.success("Invite sent", { description: "ada@dusk.dev can join now." })}>
Success
</Button>
<Button
variant="outline"
onClick={() =>
animatedToast.warning("API key expires in 3 days", {
duration: 8000,
action: { label: "Rotate key", onClick: () => animatedToast.success("New key created") },
})
}
>
With action
</Button>
</div>
);
}$ npx shadcn@latest add https://duskui.com/r/animated-toast.json1. Install the dependencies.
npm install motion sonner lucide-react2. Copy the source into
components/dusk/toast/animated-toast.tsx.animated-toast.tsx "use client"; import * as React from "react"; import { animate, AnimatePresence, motion, useMotionValue, useReducedMotion, type MotionValue, } from "motion/react"; import { Bell, Info, TriangleAlert, X } from "lucide-react"; import { toast, type ExternalToast } from "sonner"; import { cn } from "@/lib/utils"; export type ToastStatus = "default" | "loading" | "success" | "error" | "info" | "warning"; const tone: Record<ToastStatus, { icon: string; border: string; bar: string }> = { default: { icon: "text-muted-foreground", border: "border-border", bar: "bg-foreground/30" }, loading: { icon: "text-muted-foreground", border: "border-border", bar: "bg-foreground/30" }, success: { icon: "text-primary", border: "border-border", bar: "bg-foreground/30" }, error: { icon: "text-destructive", border: "border-border", bar: "bg-foreground/30" }, info: { icon: "text-foreground", border: "border-border", bar: "bg-foreground/30" }, warning: { icon: "text-amber-300", border: "border-border", bar: "bg-foreground/30" }, }; // --------------------------------------------------------------------------- // Countdown shared by DuskUI custom toasts // --------------------------------------------------------------------------- /** * Drives a toast's lifetime with a motion value (1 → 0) so the progress UI and * the dismissal can never drift apart. Like Sonner, it pauses while the * pointer is over the toaster, while the toast has keyboard focus and while * the tab is hidden. `onDone` runs once when it reaches 0. */ export function useToastCountdown( ref: React.RefObject<HTMLElement | null>, { duration, enabled = true, restartKey, onDone, }: { duration: number; enabled?: boolean; /** Restart the countdown from full whenever this changes. */ restartKey?: string | number | boolean; onDone: () => void; } ): MotionValue<number> { const progress = useMotionValue(1); const done = React.useEffectEvent(() => onDone()); React.useEffect(() => { const root = ref.current; if (!enabled || !root || !Number.isFinite(duration) || duration <= 0) { progress.jump(1); return; } const toaster = root.closest<HTMLElement>("[data-sonner-toaster]"); const toastEl = root.closest<HTMLElement>("[data-sonner-toast]") ?? root; const reasons = new Set<"hover" | "focus" | "hidden">(); progress.jump(1); const animation = animate(progress, 0, { duration: duration / 1000, ease: "linear", onComplete: () => done(), }); const sync = () => (reasons.size ? animation.pause() : animation.play()); const set = (reason: "hover" | "focus" | "hidden", on: boolean) => { if (on) reasons.add(reason); else reasons.delete(reason); sync(); }; const onEnter = () => set("hover", true); const onLeave = () => set("hover", false); const onFocusIn = () => set("focus", true); const onFocusOut = (event: FocusEvent) => { if (!toastEl.contains(event.relatedTarget as Node | null)) set("focus", false); }; const onVisibility = () => set("hidden", document.hidden); if (toaster?.matches(":hover")) reasons.add("hover"); if (toastEl.contains(document.activeElement)) reasons.add("focus"); if (document.hidden) reasons.add("hidden"); sync(); toaster?.addEventListener("pointerenter", onEnter); toaster?.addEventListener("pointerleave", onLeave); toastEl.addEventListener("focusin", onFocusIn); toastEl.addEventListener("focusout", onFocusOut); document.addEventListener("visibilitychange", onVisibility); return () => { animation.stop(); toaster?.removeEventListener("pointerenter", onEnter); toaster?.removeEventListener("pointerleave", onLeave); toastEl.removeEventListener("focusin", onFocusIn); toastEl.removeEventListener("focusout", onFocusOut); document.removeEventListener("visibilitychange", onVisibility); }; }, [ref, duration, enabled, restartKey, progress]); return progress; } /** The surface every DuskUI custom toast sits on. Matches the DuskUI Toaster's styled toasts. */ export function ToastSurface({ className, ...props }: React.ComponentProps<"div">) { return ( <div data-slot="toast-surface" className={cn( "relative flex w-(--width) items-start gap-3 overflow-hidden rounded-xl border bg-popover p-3.5 pr-10 font-sans text-sm text-popover-foreground max-[600px]:w-full", "shadow-lg", // Collapsed stack: hide the content of toasts behind the front one, like Sonner's styled toasts. // (Height is left alone so Sonner can still measure the toast.) "[[data-sonner-toast][data-expanded=false][data-front=false]_&>*]:opacity-0", className )} {...props} /> ); } /** The round close button in the top-right corner of a custom toast. */ export function ToastClose({ className, label = "Close notification", ...props }: React.ComponentProps<"button"> & { label?: string }) { return ( <button type="button" aria-label={label} className={cn( "absolute top-2.5 right-2.5 inline-flex size-6 items-center justify-center rounded-md text-muted-foreground outline-none", "transition-[color,background-color,box-shadow] duration-150 hover:bg-accent hover:text-foreground", "focus-visible:ring-[3px] focus-visible:ring-ring/50", className )} {...props} > <X className="size-3.5" aria-hidden /> </button> ); } // --------------------------------------------------------------------------- // Status icon that morphs between states // --------------------------------------------------------------------------- const draw = { type: "spring", duration: 0.35, bounce: 0 } as const; function StatusGlyph({ status }: { status: ToastStatus }) { switch (status) { case "loading": return ( <svg viewBox="0 0 24 24" className="size-4 animate-spin motion-reduce:animate-[spin_2.5s_linear_infinite]" fill="none" aria-hidden> <circle cx="12" cy="12" r="9" stroke="currentColor" strokeOpacity="0.2" strokeWidth="2.5" /> <path d="M21 12a9 9 0 0 0-9-9" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" /> </svg> ); case "success": return ( <svg viewBox="0 0 24 24" className="size-4" fill="none" aria-hidden> <motion.path d="M5 12.5l4.5 4.5L19 7.5" stroke="currentColor" strokeWidth="2.75" strokeLinecap="round" strokeLinejoin="round" initial={{ pathLength: 0 }} animate={{ pathLength: 1 }} transition={{ ...draw, delay: 0.08 }} /> </svg> ); case "error": return ( <svg viewBox="0 0 24 24" className="size-4" fill="none" aria-hidden> {["M7 7l10 10", "M17 7L7 17"].map((d, index) => ( <motion.path key={d} d={d} stroke="currentColor" strokeWidth="2.75" strokeLinecap="round" initial={{ pathLength: 0 }} animate={{ pathLength: 1 }} transition={{ ...draw, delay: 0.08 + index * 0.1 }} /> ))} </svg> ); case "info": return <Info className="size-4" aria-hidden />; case "warning": return <TriangleAlert className="size-4" aria-hidden />; default: return <Bell className="size-4" aria-hidden />; } } /** A status glyph that crossfades (scale + path draw) when `status` changes. */ export function ToastStatusIcon({ status, className }: { status: ToastStatus; className?: string }) { const reduceMotion = useReducedMotion(); return ( <span aria-hidden className={cn( "relative grid size-7 shrink-0 place-items-center rounded-full transition-colors duration-300", tone[status].icon, className )} > <AnimatePresence mode="popLayout" initial={false}> <motion.span key={status} className="grid place-items-center" initial={reduceMotion ? { opacity: 0 } : { opacity: 0, scale: 0.8 }} animate={{ opacity: 1, scale: 1 }} exit={reduceMotion ? { opacity: 0 } : { opacity: 0, scale: 0.8 }} transition={{ type: "spring", duration: 0.25, bounce: 0.1 }} > <StatusGlyph status={status} /> </motion.span> </AnimatePresence> </span> ); } // --------------------------------------------------------------------------- // The toast // --------------------------------------------------------------------------- export interface ToastAction { label: React.ReactNode; /** Call `event.preventDefault()` to keep the toast open. */ onClick: (event: React.MouseEvent<HTMLButtonElement>) => void; } export interface AnimatedToastProps { /** The Sonner toast id (from `toast.custom`). */ id: string | number; status?: ToastStatus; title: React.ReactNode; description?: React.ReactNode; /** Lifetime in ms after it settles. `Infinity` keeps it open. Ignored while loading. */ duration?: number; action?: ToastAction; /** Show the close button. */ dismissible?: boolean; onAutoClose?: () => void; onDismiss?: () => void; } /** * A custom Sonner toast. Its icon changes between loading, success and error * (the spinner fades out, the check or cross draws itself in), a thin line * along the bottom shows the time left, and the title crossfades on change. * Render it with `toast.custom`, or use the `animatedToast` helpers below. */ export function AnimatedToast({ id, status = "default", title, description, duration = 5000, action, dismissible = true, onAutoClose, onDismiss, }: AnimatedToastProps) { const ref = React.useRef<HTMLDivElement>(null); const timed = status !== "loading" && Number.isFinite(duration) && duration > 0; const progress = useToastCountdown(ref, { duration, enabled: timed, onDone: () => { onAutoClose?.(); toast.dismiss(id); }, }); return ( <ToastSurface ref={ref} data-status={status} aria-busy={status === "loading" || undefined} className={tone[status].border}> <ToastStatusIcon status={status} /> <div className="grid min-w-0 flex-1 gap-0.5 pt-1"> <motion.p key={`${status}-title`} className="leading-snug font-medium" initial={{ opacity: 0, y: 3 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.25, ease: "easeOut" }} > {title} </motion.p> {description && <p className="text-[0.8125rem] leading-snug text-muted-foreground">{description}</p>} {action && ( <div className="mt-2 flex"> <button type="button" className={cn( "inline-flex h-7 items-center rounded-md border bg-secondary px-2.5 text-xs font-medium text-secondary-foreground outline-none", "transition-[background-color,box-shadow] duration-150 hover:bg-accent focus-visible:ring-[3px] focus-visible:ring-ring/50" )} onClick={(event) => { action.onClick(event); if (!event.defaultPrevented) toast.dismiss(id); }} > {action.label} </button> </div> )} </div> {dismissible && status !== "loading" && ( <ToastClose onClick={() => { onDismiss?.(); toast.dismiss(id); }} /> )} {timed && ( <motion.span aria-hidden className={cn("absolute inset-x-0 bottom-0 h-0.5 origin-left opacity-70", tone[status].bar)} style={{ scaleX: progress }} /> )} </ToastSurface> ); } // --------------------------------------------------------------------------- // Helpers // --------------------------------------------------------------------------- export interface AnimatedToastOptions extends Pick<AnimatedToastProps, "description" | "duration" | "action" | "dismissible" | "onAutoClose" | "onDismiss">, Pick<ExternalToast, "position" | "className"> { /** Reuse an id to update an existing toast in place (its icon morphs). */ id?: string | number; } function show(status: ToastStatus, title: React.ReactNode, { id, position, className, ...options }: AnimatedToastOptions = {}) { return toast.custom( (toastId) => <AnimatedToast id={toastId} status={status} title={title} {...options} />, { id, position, className, // We run our own timer so the progress line and the dismissal stay in sync. duration: Infinity, dismissible: status !== "loading" && options.dismissible !== false, onDismiss: options.onDismiss, } ); } type Message = React.ReactNode | { title: React.ReactNode; description?: React.ReactNode }; function toParts(message: Message) { if (message && typeof message === "object" && !React.isValidElement(message) && "title" in message) { return message; } return { title: message as React.ReactNode, description: undefined }; } export interface PromiseToastMessages<T> { loading: Message; success: Message | ((data: T) => Message); error: Message | ((error: unknown) => Message); } export interface PromiseToastOptions extends Omit<AnimatedToastOptions, "description" | "action"> { /** Keep the spinner up at least this long (ms) so fast requests don't flash. */ minLoading?: number; /** Label of the retry button shown on error. Only when you pass a function (it is called again). Set `false` to hide. */ retryLabel?: React.ReactNode | false; } let counter = 0; const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); /** * One toast that follows a promise: a spinner while it runs, then the icon * morphs into a check or a cross. Pass a function instead of a promise to get * a Retry button on failure that re-runs it in the same toast. * Returns `{ id, unwrap }`; `unwrap()` resolves or rejects with the first attempt. */ function promise<T>( task: Promise<T> | (() => Promise<T>), messages: PromiseToastMessages<T>, { id = `dusk-toast-${++counter}`, minLoading = 600, retryLabel = "Retry", ...options }: PromiseToastOptions = {} ) { const run = (): Promise<T> => { show("loading", toParts(messages.loading).title, { ...options, id, description: toParts(messages.loading).description }); const started = Date.now(); const settle = () => wait(Math.max(0, minLoading - (Date.now() - started))); const pending = typeof task === "function" ? task() : task; return pending.then( async (data) => { await settle(); const message = toParts(typeof messages.success === "function" ? messages.success(data) : messages.success); show("success", message.title, { ...options, id, description: message.description }); return data; }, async (error: unknown) => { await settle(); const message = toParts(typeof messages.error === "function" ? messages.error(error) : messages.error); const canRetry = typeof task === "function" && retryLabel !== false; show("error", message.title, { ...options, id, description: message.description, action: canRetry ? { label: retryLabel, onClick: (event) => { event.preventDefault(); run().catch(() => {}); }, } : undefined, }); throw error; } ); }; const result = run(); // The toast reports the failure; callers who care use unwrap(). result.catch(() => {}); return { id, unwrap: () => result }; } /** * Fire DuskUI animated toasts through the global Sonner Toaster. * * animatedToast("Saved") * animatedToast.success("Deployed", { description: "dusk-web is live" }) * const id = animatedToast.loading("Uploading…") * animatedToast.success("Uploaded", { id }) // same toast, icon morphs * animatedToast.promise(() => save(), { loading: "Saving…", success: "Saved", error: "Couldn't save" }) */ export const animatedToast = Object.assign( (title: React.ReactNode, options?: AnimatedToastOptions) => show("default", title, options), { success: (title: React.ReactNode, options?: AnimatedToastOptions) => show("success", title, options), error: (title: React.ReactNode, options?: AnimatedToastOptions) => show("error", title, options), info: (title: React.ReactNode, options?: AnimatedToastOptions) => show("info", title, options), warning: (title: React.ReactNode, options?: AnimatedToastOptions) => show("warning", title, options), loading: (title: React.ReactNode, options?: AnimatedToastOptions) => show("loading", title, options), promise, dismiss: (id?: string | number) => toast.dismiss(id), } );
| Prop | Type | Default | Description |
|---|---|---|---|
| animatedToast(title, options?) | => id | — | Neutral toast. Also .success, .error, .info, .warning and .loading. |
| animatedToast.promise(task, messages, options?) | => { id, unwrap } | — | task is a promise or a function returning one (enables Retry). Messages are text or { title, description }, or functions of the result / error. |
| options.id | string | number | — | Reuse an id to update a toast in place. |
| options.description | ReactNode | — | Second line. |
| options.duration | number | 5000 | Lifetime in ms once settled. Infinity keeps it open. |
| options.action | { label, onClick } | — | A button under the text. Call event.preventDefault() to keep the toast open. |
| options.dismissible | boolean | true | Show the close button and allow swiping. |
| options.onAutoClose / onDismiss | () => void | — | Timer ran out / the user closed it. |
| minLoading | number | 600 | Promise only: minimum spinner time in ms. |
| retryLabel | ReactNode | false | "Retry" | Promise only: label of the retry button; false hides it. |
| AnimatedToast / ToastSurface / ToastStatusIcon / useToastCountdown | exports | — | The building blocks, for your own custom toasts. |
Undo Toast
The optimistic-delete pattern: remove the item right away, call undoToast(), and only make it permanent in onCommit. A ring drains around the seconds left; Undo (or ⌘Z / Ctrl+Z) calls onUndo and the toast turns into a “Restored” confirmation. onUndo and onCommit are guaranteed to run at most once, and never both. Archive a few emails, then undo one.
Ada Kim
Motion specs for the onboarding flow
Leo Park
Re: Q3 roadmap review
Vercel
Your deployment is ready
"use client";
import * as React from "react";
import { AnimatePresence, motion } from "motion/react";
import { Archive, RotateCcw } from "lucide-react";
import { Button } from "@/components/ui/button";
import { undoToast } from "@/components/dusk/toast/undo-toast";
import { animatedToast } from "@/components/dusk/toast/animated-toast";
const initialEmails = [
{ id: 1, from: "Ada Kim", subject: "Motion specs for the onboarding flow" },
{ id: 2, from: "Leo Park", subject: "Re: Q3 roadmap review" },
{ id: 3, from: "Vercel", subject: "Your deployment is ready" },
];
export default function UndoToastDemo() {
const [emails, setEmails] = React.useState(initialEmails);
const archive = (email: (typeof initialEmails)[number]) => {
// Optimistic: remove now, commit later.
setEmails((list) => list.filter((e) => e.id !== email.id));
undoToast({
title: "Conversation archived",
description: email.subject,
onUndo: () =>
setEmails((list) =>
list.some((e) => e.id === email.id) ? list : [...list, email].sort((a, b) => a.id - b.id)
),
onCommit: () => animatedToast.info("Archived for good", { duration: 2500 }),
});
};
return (
<div className="flex w-full max-w-md flex-col gap-3">
<ul className="overflow-hidden rounded-xl border">
<AnimatePresence initial={false}>
{emails.map((email) => (
<motion.li
key={email.id}
layout
initial={{ opacity: 0, height: 0 }}
animate={{ opacity: 1, height: "auto" }}
exit={{ opacity: 0, height: 0 }}
transition={{ type: "spring", duration: 0.35, bounce: 0 }}
className="overflow-hidden border-b last:border-b-0"
>
<div className="flex items-center gap-3 px-4 py-3">
<div className="min-w-0 flex-1">
<p className="text-sm font-medium">{email.from}</p>
<p className="truncate text-sm text-muted-foreground">{email.subject}</p>
</div>
<Button size="icon-sm" variant="ghost" aria-label={`Archive “${email.subject}”`} onClick={() => archive(email)}>
<Archive />
</Button>
</div>
</motion.li>
))}
</AnimatePresence>
{emails.length === 0 && <li className="px-4 py-6 text-center text-sm text-muted-foreground">Inbox zero.</li>}
</ul>
<Button variant="ghost" size="sm" className="self-start" onClick={() => setEmails(initialEmails)}>
<RotateCcw />
Reset inbox
</Button>
</div>
);
}$ npx shadcn@latest add https://duskui.com/r/undo-toast.json1. Install the dependencies.
npm install motion sonner lucide-react2. Copy the source into
components/dusk/toast/undo-toast.tsx.undo-toast.tsx "use client"; import * as React from "react"; import { motion, useTransform, type MotionValue } from "motion/react"; import { Undo2 } from "lucide-react"; import { toast, type ExternalToast } from "sonner"; import { ToastClose, ToastStatusIcon, ToastSurface, useToastCountdown, } from "@/components/dusk/toast/animated-toast"; import { cn } from "@/lib/utils"; export interface UndoToastOptions extends Pick<ExternalToast, "position" | "className"> { /** What just happened, e.g. "Email archived". */ title: React.ReactNode; description?: React.ReactNode; /** Restore what was removed. Runs at most once, and never after `onCommit`. */ onUndo: () => void; /** Make the change permanent: runs once when the time runs out or the toast is closed without undoing. */ onCommit?: () => void; /** How long the user has to undo, in ms. */ duration?: number; undoLabel?: React.ReactNode; /** Title shown after undoing. */ undoneTitle?: React.ReactNode; /** Also undo with ⌘Z / Ctrl+Z while the toast is up (ignored inside text fields). */ shortcut?: boolean; id?: string | number; } const RADIUS = 11; const CIRCUMFERENCE = 2 * Math.PI * RADIUS; /** * The optimistic-delete pattern as a toast: remove the item from your UI * right away, call `undoToast()`, and only make the change permanent in * `onCommit`. A ring drains around the seconds left; Undo (or ⌘Z / Ctrl+Z) * calls `onUndo` and the toast morphs into a "Restored" confirmation. The * countdown pauses on hover, focus and hidden tabs, like any Sonner toast. * Returns the toast id. */ export function undoToast({ title, description, onUndo, onCommit, duration = 6000, undoLabel = "Undo", undoneTitle = "Restored", shortcut = true, id, position, className, }: UndoToastOptions) { let settled = false; const commit = () => { if (settled) return; settled = true; onCommit?.(); }; const undo = () => { if (settled) return false; settled = true; onUndo(); return true; }; return toast.custom( (toastId) => ( <UndoToast id={toastId} title={title} description={description} duration={duration} undoLabel={undoLabel} undoneTitle={undoneTitle} shortcut={shortcut} onUndo={undo} onCommit={commit} /> ), { id, position, className, duration: Infinity, // Swiping it away counts as "keep the change". onDismiss: commit, } ); } interface UndoToastProps { id: string | number; title: React.ReactNode; description?: React.ReactNode; duration: number; undoLabel: React.ReactNode; undoneTitle: React.ReactNode; shortcut: boolean; /** Returns false if it was too late to undo. */ onUndo: () => boolean; onCommit: () => void; } function UndoToast({ id, title, description, duration, undoLabel, undoneTitle, shortcut, onUndo, onCommit }: UndoToastProps) { const ref = React.useRef<HTMLDivElement>(null); const [undone, setUndone] = React.useState(false); // Phase 1: the undo window. Phase 2 (after undoing): a short confirmation. const progress = useToastCountdown(ref, { duration: undone ? 2000 : duration, restartKey: undone, onDone: () => { if (!undone) onCommit(); toast.dismiss(id); }, }); const handleUndo = React.useCallback(() => { if (onUndo()) setUndone(true); }, [onUndo]); React.useEffect(() => { if (!shortcut || undone) return; const onKeyDown = (event: KeyboardEvent) => { if (event.key.toLowerCase() !== "z" || !(event.metaKey || event.ctrlKey) || event.shiftKey) return; const target = event.target as HTMLElement | null; if (target?.closest("input, textarea, select, [contenteditable=''], [contenteditable='true']")) return; event.preventDefault(); handleUndo(); }; window.addEventListener("keydown", onKeyDown); return () => window.removeEventListener("keydown", onKeyDown); }, [shortcut, undone, handleUndo]); return ( <ToastSurface ref={ref} data-status={undone ? "success" : "pending"}> {undone ? <ToastStatusIcon status="success" /> : <CountdownRing progress={progress} duration={duration} />} <div className="grid min-w-0 flex-1 gap-0.5 pt-1"> <motion.p key={undone ? "undone" : "pending"} className="leading-snug font-medium" initial={{ opacity: 0, y: 3 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.25, ease: "easeOut" }} > {undone ? undoneTitle : title} </motion.p> {description && !undone && <p className="text-[0.8125rem] leading-snug text-muted-foreground">{description}</p>} </div> {!undone && ( <button type="button" onClick={handleUndo} className={cn( "mt-0.5 inline-flex h-7 shrink-0 items-center gap-1.5 self-start rounded-md border bg-secondary px-2.5 text-xs font-medium text-secondary-foreground outline-none", "transition-[background-color,box-shadow] duration-150 hover:bg-accent focus-visible:ring-[3px] focus-visible:ring-ring/50" )} > <Undo2 className="size-3.5" aria-hidden /> {undoLabel} </button> )} <ToastClose onClick={() => { if (!undone) onCommit(); toast.dismiss(id); }} /> </ToastSurface> ); } /** A ring that drains with `progress`, with the whole seconds left in the middle. */ function CountdownRing({ progress, duration }: { progress: MotionValue<number>; duration: number }) { const dashOffset = useTransform(progress, (p) => CIRCUMFERENCE * (1 - p)); const seconds = useTransform(progress, (p) => Math.ceil((p * duration) / 1000)); return ( <span aria-hidden className="relative grid size-7 shrink-0 place-items-center"> <svg viewBox="0 0 28 28" className="absolute inset-0 -rotate-90"> <circle cx="14" cy="14" r={RADIUS} fill="none" strokeWidth="2.5" className="stroke-white/10" /> <motion.circle cx="14" cy="14" r={RADIUS} fill="none" strokeWidth="2.5" strokeLinecap="round" strokeDasharray={CIRCUMFERENCE} className="stroke-muted-foreground" style={{ strokeDashoffset: dashOffset }} /> </svg> <motion.span className="text-[0.6875rem] font-medium text-foreground tabular-nums">{seconds}</motion.span> </span> ); }
| Prop | Type | Default | Description |
|---|---|---|---|
| title | ReactNode | — | What happened, e.g. "Email archived". Required. |
| description | ReactNode | — | Second line, e.g. the item's name. |
| onUndo | () => void | — | Restore the item. Required. |
| onCommit | () => void | — | Runs when time runs out or the toast is closed without undoing. |
| duration | number | 6000 | How long the user has to undo, in ms. |
| undoLabel | ReactNode | "Undo" | Button label. |
| undoneTitle | ReactNode | "Restored" | Title shown after undoing. |
| shortcut | boolean | true | Undo with ⌘Z / Ctrl+Z (ignored in text fields). |
| id / position / className | Sonner options | — | Passed through to toast.custom. |
API Reference
Toaster accepts every Sonner ToasterProps. Fire toasts with the toast function from sonner.
| Prop | Type | Default | Description |
|---|---|---|---|
| theme | "light" | "dark" | "system" | "dark" | Sonner theme. DuskUI is styled for dark. |
| position | "top-left" | "top-center" | "top-right" | "bottom-left" | "bottom-center" | "bottom-right" | "bottom-right" | Where toasts stack. |
| richColors | boolean | false | Tinted success, info, warning and error toasts in the DuskUI palette. |
| toastOptions | ToastOptions | — | Defaults for every toast; classNames are merged with the DuskUI ones. |
| icons | ToastIcons | — | Override any of the status, loading or close icons. |
| expand / visibleToasts / duration / closeButton | Sonner props | — | Stacking, count, default lifetime and close button. |
Accessibility
- Sonner renders toasts in a labelled, polite live region, so new toasts are announced without stealing focus. Alt+T moves focus to the toasts.
- Timers pause while the stack is hovered or focused and while the tab is hidden, giving everyone time to read and act. The blocks follow the same rules with their own timers.
- Close, Retry and Undo are real buttons with accessible labels, reachable by keyboard. Undo Toast also supports ⌘Z / Ctrl+Z.
- Don't put the only path to something important in a toast; it disappears. Use an Alert or Alert Dialog for that.
- Sonner turns off its own animations under prefers-reduced-motion; the blocks skip scale and rotate and keep simple fades.