Toast
A promise toast turns from loading into done in place: the spinner's arc bends into the check, and its clock stops on the time it took. Swipe any toast back the way it came.
npx shadcn@latest add https://uimaxxer.com/r/toast.jsonPasskeysFix the duplicate Stripe charge
"use client";
// uimaxxer · Toast, MIT. Idea: a promise toast turns from loading into done in place, and you swipe it back the way it came. Delight: the spinner's arc bends into the check, and the clock that ran while it loaded stops on the time it took.
import { AnimatePresence, animate, motion, useAnimationFrame, useMotionValue, useReducedMotion, useTransform } from "motion/react";
import { useCallback, useEffect, useRef, useState, useSyncExternalStore, type PointerEvent, type ReactNode } from "react";
import { EASE, SPRING, SPRING_RELEASE, cx, rubber } from "@/registry/captain/ui/captain";
type ToastType = "default" | "success" | "error" | "loading";
type Action = { label: string; onClick: () => void };
type ToastData = {
id: number;
title: ReactNode;
description?: ReactNode;
type: ToastType;
action?: Action;
/** ms; Infinity keeps it until dismissed. */
duration?: number;
};
type Options = Partial<Omit<ToastData, "id" | "title">> & { id?: number };
// A tiny store outside React, so toast() works from anywhere.
let list: ToastData[] = [];
let seq = 0;
const subs = new Set<() => void>();
const emit = () => subs.forEach((f) => f());
const subscribe = (f: () => void) => {
subs.add(f);
return () => subs.delete(f);
};
function upsert(title: ReactNode, opts: Options = {}) {
const id = opts.id ?? ++seq;
const prev = list.find((t) => t.id === id);
const next: ToastData = { type: "default", ...prev, ...opts, id, title };
list = prev ? list.map((t) => (t.id === id ? next : t)) : [next, ...list];
emit();
return id;
}
export function toast(title: ReactNode, opts?: Options) {
return upsert(title, opts);
}
toast.success = (title: ReactNode, opts?: Options) => upsert(title, { ...opts, type: "success" });
toast.error = (title: ReactNode, opts?: Options) => upsert(title, { ...opts, type: "error" });
toast.dismiss = (id?: number) => {
list = id === undefined ? [] : list.filter((t) => t.id !== id);
emit();
};
toast.promise = <T,>(
p: Promise<T> | (() => Promise<T>),
m: { loading: ReactNode; success: ReactNode | ((v: T) => ReactNode); error: ReactNode | ((e: unknown) => ReactNode); description?: ReactNode | ((v: T) => ReactNode) },
) => {
const id = upsert(m.loading, { type: "loading", duration: Infinity });
const run = typeof p === "function" ? p() : p;
run.then(
(v) =>
upsert(typeof m.success === "function" ? (m.success as (v: T) => ReactNode)(v) : m.success, {
id,
type: "success",
duration: undefined,
description: typeof m.description === "function" ? (m.description as (v: T) => ReactNode)(v) : m.description,
}),
(e) => upsert(typeof m.error === "function" ? (m.error as (e: unknown) => ReactNode)(e) : m.error, { id, type: "error", duration: undefined }),
);
return run;
};
type ToasterProps = {
position?: "bottom-right" | "bottom-center" | "bottom-left" | "top-right" | "top-center" | "top-left";
/** Default time on screen, in ms. */
duration?: number;
/** How many show in the deck. */
visible?: number;
/** Position inside the nearest positioned parent instead of the viewport. */
inline?: boolean;
/** Keep the deck fanned out instead of stacking it until hover. */
expand?: boolean;
/** Toast width in px. Default 356. */
width?: number;
className?: string;
};
const GAP = 10;
const PEEK = 12;
const WIDTH = 356;
export function Toaster({ position = "bottom-right", duration = 4000, visible = 3, inline, expand = false, width = WIDTH, className }: ToasterProps) {
const toasts = useSyncExternalStore(subscribe, () => list, () => list);
const [heights, setHeights] = useState<Record<number, number>>({});
const [hover, setHover] = useState(false);
const [focus, setFocus] = useState(false);
const [hidden, setHidden] = useState(false);
const region = useRef<HTMLElement | null>(null);
const expanded = expand || hover || focus;
const top = position.startsWith("top");
const dir = top ? -1 : 1;
useEffect(() => {
const vis = () => setHidden(document.hidden);
document.addEventListener("visibilitychange", vis);
const hot = (e: KeyboardEvent) => {
if (e.altKey && e.code === "KeyT") {
e.preventDefault();
region.current?.querySelector<HTMLElement>("[data-cu-toast]")?.focus();
}
};
window.addEventListener("keydown", hot);
return () => {
document.removeEventListener("visibilitychange", vis);
window.removeEventListener("keydown", hot);
};
}, []);
useEffect(() => {
if (toasts.length === 0) setHover(false);
}, [toasts.length]);
const measure = useCallback((id: number, h: number) => setHeights((m) => (m[id] === h ? m : { ...m, [id]: h })), []);
const front = heights[toasts[0]?.id ?? -1] ?? 64;
const shown = toasts.slice(0, visible);
const total = shown.reduce((s, t) => s + (heights[t.id] ?? 64), 0) + GAP * Math.max(0, shown.length - 1);
const [v, h] = position.split("-") as ["top" | "bottom", "left" | "right" | "center"];
const place = cx(
inline ? "absolute" : "fixed",
v === "top" ? "top-4" : "bottom-4",
h === "left" ? "left-4" : h === "right" ? "right-4" : "left-1/2 -translate-x-1/2",
);
return (
<section
ref={region}
aria-label="Notifications, Alt+T"
tabIndex={-1}
className={cx(place, "z-[80] outline-none", className)}
style={{ width: `min(${width}px, calc(100% - 32px))` }}
onPointerEnter={(e) => e.pointerType === "mouse" && setHover(true)}
onPointerLeave={(e) => e.pointerType === "mouse" && setHover(false)}
onFocus={() => setFocus(true)}
onBlur={(e) => {
if (!e.currentTarget.contains(e.relatedTarget as Node)) setFocus(false);
}}
>
<motion.div
aria-live="polite"
aria-relevant="additions text"
className="relative"
animate={{ height: toasts.length === 0 ? 0 : expanded ? total : front + PEEK * (shown.length - 1) }}
transition={SPRING}
>
<AnimatePresence initial={false}>
{toasts.map((t, i) => {
const before = toasts.slice(0, i).reduce((s, x) => s + (heights[x.id] ?? 64) + GAP, 0);
return (
<Item
key={t.id}
t={t}
index={i}
dir={dir}
offset={expanded ? before : i * PEEK}
scale={expanded ? 1 : 1 - i * 0.05}
clampTo={expanded || i === 0 ? null : front}
visible={i < visible}
paused={hover || focus || hidden}
duration={t.duration ?? duration}
onHeight={measure}
/>
);
})}
</AnimatePresence>
</motion.div>
</section>
);
}
type ItemProps = {
t: ToastData;
index: number;
dir: 1 | -1;
offset: number;
scale: number;
clampTo: number | null;
visible: boolean;
paused: boolean;
duration: number;
onHeight: (id: number, h: number) => void;
};
function Item({ t, index, dir, offset, scale, clampTo, visible, paused, duration, onHeight }: ItemProps) {
const reduce = useReducedMotion();
const body = useRef<HTMLDivElement | null>(null);
const [own, setOwn] = useState(64);
const sy = useMotionValue(0);
const fade = useTransform(sy, (y) => 1 - Math.min(1, Math.max(0, (y * dir) / 160)));
const drag = useRef<{ id: number; y0: number; t0: number; last: number; lt: number; v: number; on: boolean } | null>(null);
const [swiping, setSwiping] = useState(false);
const left = useRef(duration);
const since = useRef(0);
// A promise carries a clock: it runs while loading and stops on the time it took.
const started = useRef<number | null>(t.type === "loading" ? performance.now() : null);
const [took, setTook] = useState<number | null>(null);
const [tick, setTick] = useState(0);
const mounted = useRef(false);
useEffect(() => {
mounted.current = true;
return () => {
mounted.current = false;
};
}, []);
useEffect(() => {
if (t.type === "loading" && started.current === null) started.current = performance.now();
if (t.type !== "loading" && started.current !== null && took === null) setTook(performance.now() - started.current);
}, [t.type, took]);
useAnimationFrame(() => {
if (!mounted.current || t.type !== "loading" || started.current === null) return;
const s = Math.floor((performance.now() - started.current) / 100);
if (s !== tick) setTick(s);
});
const clock = t.type === "loading" && started.current !== null ? tick / 10 : took !== null ? took / 1000 : null;
useEffect(() => {
const el = body.current;
if (!el) return;
const ro = new ResizeObserver(() => {
setOwn(el.offsetHeight);
onHeight(t.id, el.offsetHeight);
});
ro.observe(el);
return () => ro.disconnect();
}, [t.id, onHeight]);
// Auto-dismiss, paused while the deck is open, the tab is hidden or a finger is on it.
useEffect(() => {
left.current = duration;
}, [duration, t.type, t.title]);
useEffect(() => {
if (paused || swiping || !Number.isFinite(left.current) || !visible) return;
since.current = performance.now();
const timer = setTimeout(() => toast.dismiss(t.id), left.current);
return () => {
clearTimeout(timer);
left.current -= performance.now() - since.current;
};
}, [paused, swiping, visible, t.id, duration, t.type, t.title]);
const down = (e: PointerEvent<HTMLDivElement>) => {
if (e.button !== 0 || (e.target as HTMLElement).closest("button")) return;
e.currentTarget.setPointerCapture(e.pointerId);
const now = performance.now();
drag.current = { id: e.pointerId, y0: e.clientY, t0: now, last: e.clientY, lt: now, v: 0, on: true };
setSwiping(true);
};
const move = (e: PointerEvent<HTMLDivElement>) => {
const d = drag.current;
if (!d || d.id !== e.pointerId) return;
const now = performance.now();
d.v = (e.clientY - d.last) / Math.max(1, now - d.lt);
d.last = e.clientY;
d.lt = now;
const dy = e.clientY - d.y0;
// Back the way it came moves 1:1; the other way meets resistance.
sy.set(dy * dir > 0 ? dy : rubber(dy, 60));
};
const up = (e: PointerEvent<HTMLDivElement>) => {
const d = drag.current;
if (!d || d.id !== e.pointerId) return;
drag.current = null;
setSwiping(false);
const dist = sy.get() * dir;
const speed = d.v * dir;
if (dist > 45 || (speed > 0.11 && dist > 8)) {
animate(sy, dir * (own + 48), { ...SPRING_RELEASE, velocity: d.v * 1000, onComplete: () => toast.dismiss(t.id) });
} else {
animate(sy, 0, reduce ? { duration: 0.15, ease: EASE } : { ...SPRING_RELEASE, velocity: d.v * 1000 });
}
};
const h = clampTo ?? own;
const hide = clampTo !== null;
return (
<motion.div
data-cu-toast=""
tabIndex={0}
role={t.type === "error" ? "alert" : "status"}
aria-atomic="true"
onKeyDown={(e) => {
if (e.key === "Escape") toast.dismiss(t.id);
}}
initial={{ opacity: 0, y: reduce ? 0 : dir * 24, scale: 1 }}
animate={{ opacity: visible ? 1 : 0, y: -offset * dir, scale: reduce ? 1 : scale, height: h }}
exit={{ opacity: 0, scale: reduce ? 1 : 0.96, transition: { duration: 0.16, ease: EASE } }}
transition={reduce ? { duration: 0.15 } : SPRING}
className={cx("group/toast absolute inset-x-0 outline-none", dir === 1 ? "bottom-0 origin-bottom" : "top-0 origin-top")}
style={{ zIndex: 50 - index, pointerEvents: visible ? "auto" : "none" }}
>
<motion.div
onPointerDown={down}
onPointerMove={move}
onPointerUp={up}
onPointerCancel={up}
className="relative h-full touch-none select-none overflow-hidden rounded-shell bg-surface shadow-[inset_0_1px_0_var(--captain-highlight),var(--captain-shadow-menu)]"
style={{ y: sy, opacity: fade }}
>
<span aria-hidden="true" className="pointer-events-none absolute inset-0 bg-accent-tint opacity-0 transition-opacity duration-150 group-focus-visible/toast:opacity-100" />
<motion.div
ref={body}
className="relative flex items-start gap-3 px-4 py-4"
animate={{ opacity: hide ? 0 : 1 }}
transition={{ duration: 0.16, ease: EASE }}
>
<Glyph type={t.type} />
<AnimatePresence mode="popLayout" initial={false}>
<motion.div
key={t.type}
className="min-w-0 flex-1"
initial={{ opacity: 0, y: reduce ? 0 : 4 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: reduce ? 0 : -4 }}
transition={{ duration: 0.18, ease: EASE }}
>
<p className="text-[15px] font-medium leading-[1.35] text-ink">{t.title}</p>
{t.description ? <p className="tnum mt-0.5 text-[13.5px] leading-[1.4] text-ink-2">{t.description}</p> : null}
</motion.div>
</AnimatePresence>
{clock !== null && !t.action ? (
<span className={cx("tnum shrink-0 text-[13px] leading-[1.6]", t.type === "loading" ? "text-ink-3" : "text-ink-2")}>
{t.type === "loading" ? "" : "in "}
{clock.toFixed(1)} s
</span>
) : null}
{t.action ? (
<button
type="button"
onClick={() => {
t.action?.onClick();
toast.dismiss(t.id);
}}
className="pressable raised -my-0.5 shrink-0 rounded-inner px-2.5 py-1 text-[13px] font-medium text-ink transition-colors hover:bg-hover focus-visible:bg-accent-tint"
>
{t.action.label}
</button>
) : null}
</motion.div>
</motion.div>
</motion.div>
);
}
type Pt = [number, number];
const seg = (a: Pt, b: Pt): Pt[] => [a, [a[0] + (b[0] - a[0]) / 3, a[1] + (b[1] - a[1]) / 3], [a[0] + ((b[0] - a[0]) * 2) / 3, a[1] + ((b[1] - a[1]) * 2) / 3], b];
const C = 0.5523 * 7;
/** Two strokes of one cubic each. Loading is three quarters of a ring; done and failed are the same two strokes, bent. */
const SHAPES: Record<Exclude<ToastType, "default">, [Pt[], Pt[]]> = {
loading: [
[[12, 5], [12 + C, 5], [19, 12 - C], [19, 12]],
[[19, 12], [19, 12 + C], [12 + C, 19], [12, 19]],
],
success: [seg([5.5, 12.75], [9.75, 17]), seg([9.75, 17], [18.5, 7.5])],
error: [seg([7, 7], [17, 17]), seg([17, 7], [7, 17])],
};
const TONES: Record<Exclude<ToastType, "default">, string> = { loading: "var(--captain-ink-3)", success: "var(--captain-success)", error: "var(--captain-danger)" };
const flatten = (g: [Pt[], Pt[]]) => g.flat().flat();
const pathOf = (n: number[]) => {
const v = (i: number) => (n[i] ?? 0).toFixed(2);
return `M${v(0)} ${v(1)}C${v(2)} ${v(3)} ${v(4)} ${v(5)} ${v(6)} ${v(7)}M${v(8)} ${v(9)}C${v(10)} ${v(11)} ${v(12)} ${v(13)} ${v(14)} ${v(15)}`;
};
/** One glyph whose strokes bend from the spinner's arc into a check or a cross, so loading turns into done in place. */
function Glyph({ type }: { type: ToastType }) {
const reduce = useReducedMotion();
const shape = type === "default" ? "loading" : type;
const from = useRef(flatten(SHAPES[shape]));
const to = useRef(flatten(SHAPES[shape]));
const now = useRef(flatten(SHAPES[shape]));
const p = useMotionValue(1);
const spin = useMotionValue(0);
const d = useTransform(p, (k) => {
const n = to.current.map((x, i) => (from.current[i] ?? x) + (x - (from.current[i] ?? x)) * k);
now.current = n;
return pathOf(n);
});
useEffect(() => {
from.current = now.current;
to.current = flatten(SHAPES[shape]);
p.jump(0);
const a = animate(p, 1, reduce ? { duration: 0 } : { type: "spring", stiffness: 420, damping: 30, mass: 0.8 });
// Finish the turn the spinner was on, so the arc lands upright as it bends.
if (shape !== "loading" && spin.get() !== 0) animate(spin, Math.ceil(spin.get() / 360) * 360, { duration: 0.28, ease: EASE, onComplete: () => spin.jump(0) });
return () => a.stop();
}, [shape, p, spin, reduce]);
useAnimationFrame((_, delta) => {
if (shape === "loading" && !reduce) spin.set(spin.get() + delta * 0.5);
});
if (type === "default") return null;
return (
<span className="relative -mt-px grid size-[22px] shrink-0 place-items-center">
<motion.svg width="22" height="22" viewBox="0 0 24 24" aria-hidden="true" className="overflow-visible transition-colors duration-200" style={{ rotate: spin, color: TONES[shape] }}>
<motion.path d={d} fill="none" stroke="currentColor" strokeWidth={2.25} strokeLinecap="round" strokeLinejoin="round" />
</motion.svg>
</span>
);
}Usage
import { Toaster, toast } from "@/components/ui/toast"
<Toaster />
toast("Archived run 1187", { action: { label: "Undo", onClick: restore } })
toast.promise(merge(482), { loading: "Merging #482", success: "Merged #482 into main", error: "Merge failed" })Props
| Prop | Type | Default | What it does |
|---|---|---|---|
| toast(title, options) | function | Shows a toast and returns its id. Options: description, action, duration, type, id. | |
| toast.success / toast.error | function | Same, with a drawn check or a warning glyph. | |
| toast.promise(p, messages) | function | One toast that morphs from loading to success or error in place. | |
| toast.dismiss(id?) | function | Dismiss one, or all with no id. | |
| Toaster position | "bottom-right" | "bottom-center" | … | "top-left" | "bottom-right" | Toasts enter from that edge and swipe back toward it. |
| Toaster duration | number | 4000 | Time on screen in ms. Paused while hovered, focused or the tab is hidden. |
| Toaster visible | number | 3 | How many show in the deck. |
| Toaster inline | boolean | Position inside the nearest positioned parent instead of the viewport. | |
| Toaster expand | boolean | false | Keep the deck fanned out instead of stacked until hover. |
| Toaster width | number | 356 | Toast width in px. |
Keyboard
- Alt+T
- Focus the newest toast
- Tab
- Move through toasts and their actions
- Esc
- Dismiss the focused toast
Accessibility
- A labelled region with a polite live list; errors use role=alert.
- Timers pause while the deck is hovered or focused, so nobody has to race a toast.
- Swiping is optional: Esc dismisses and every action is a real button.