Toast stack

A ToastProvider and useToast hook for stacked notifications. Toasts collapse into a deck and expand on hover or focus, auto-dismiss with timers that pause while hovered, focused or in a hidden tab, and can be updated in place (loading to success). Five variants plus default, optional action button, six positions, a limit on open toasts, and polite or assertive live-region announcements.

Alerts & toastsComponentTailwind v4

Source

"use client";

import {
  createContext, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState,
  type CSSProperties, type ReactNode,
} from "react";
import { CircleCheck, CircleX, Info, LoaderCircle, TriangleAlert, X } from "lucide-react";
import { cn } from "@/lib/utils";

export type ToastVariant = "default" | "success" | "error" | "warning" | "info" | "loading";
export type ToastPosition = "bottom-right" | "bottom-left" | "bottom-center" | "top-right" | "top-left" | "top-center";

export interface ToastOptions {
  /** Reuse an id to replace a toast in place, for example loading → success. */
  id?: string;
  title: ReactNode;
  description?: ReactNode;
  variant?: ToastVariant;
  /** Milliseconds before it closes; Infinity keeps it open. Loading toasts stay until updated. */
  duration?: number;
  action?: { label: string; onClick: () => void };
  onDismiss?: () => void;
}

interface ToastRecord extends ToastOptions {
  id: string;
  variant: ToastVariant;
  duration: number;
  version: number;
  leaving: boolean;
}

export interface ToastApi {
  /** Shows a toast and returns its id. */
  toast: (options: ToastOptions) => string;
  update: (id: string, options: Partial<ToastOptions>) => void;
  /** Closes one toast, or all of them without an id. */
  dismiss: (id?: string) => void;
}

const ToastContext = createContext<ToastApi | null>(null);

export function useToast(): ToastApi {
  const api = useContext(ToastContext);
  if (!api) throw new Error("useToast must be used inside <ToastProvider>.");
  return api;
}

const GAP = 10;
const PEEK = 10;
const VISIBLE_COLLAPSED = 3;
const EXIT_MS = 200;

const positions: Record<ToastPosition, string> = {
  "bottom-right": "bottom-4 right-4 sm:bottom-6 sm:right-6",
  "bottom-left": "bottom-4 left-4 sm:bottom-6 sm:left-6",
  "bottom-center": "bottom-4 left-1/2 -translate-x-1/2 sm:bottom-6",
  "top-right": "top-4 right-4 sm:top-6 sm:right-6",
  "top-left": "top-4 left-4 sm:top-6 sm:left-6",
  "top-center": "top-4 left-1/2 -translate-x-1/2 sm:top-6",
};

let counter = 0;

export interface ToastProviderProps {
  children: ReactNode;
  position?: ToastPosition;
  /** Default time on screen, in milliseconds. */
  duration?: number;
  /** Most toasts kept at once; the oldest close first. */
  max?: number;
  /** Name of the notifications landmark. */
  label?: string;
}

export function ToastProvider({ children, position = "bottom-right", duration = 5000, max = 5, label = "Notifications" }: ToastProviderProps) {
  const [toasts, setToasts] = useState<ToastRecord[]>([]);
  const [heights, setHeights] = useState<Record<string, number>>({});
  const [hovered, setHovered] = useState(false);
  const [focused, setFocused] = useState(false);
  const [hidden, setHidden] = useState(false);
  const [announcement, setAnnouncement] = useState<{ node: ReactNode; urgent: boolean; key: number } | null>(null);
  const toastsRef = useRef(toasts);
  toastsRef.current = toasts;

  const announce = useCallback((record: Pick<ToastRecord, "title" | "description" | "variant">) => {
    setAnnouncement({
      node: <>{record.title}{record.description ? <>. {record.description}</> : null}</>,
      urgent: record.variant === "error",
      key: Date.now(),
    });
  }, []);

  const dismiss = useCallback((id?: string) => {
    const closing = toastsRef.current.filter((item) => !item.leaving && (!id || item.id === id));
    if (!closing.length) return;
    const ids = new Set(closing.map((item) => item.id));
    closing.forEach((item) => item.onDismiss?.());
    setToasts((list) => list.map((item) => (ids.has(item.id) ? { ...item, leaving: true } : item)));
    const reduce = typeof window !== "undefined" && window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
    setTimeout(() => setToasts((list) => list.filter((item) => !(ids.has(item.id) && item.leaving))), reduce ? 0 : EXIT_MS);
  }, []);

  const toast = useCallback((options: ToastOptions) => {
    const id = options.id ?? `toast-${++counter}`;
    const record: ToastRecord = {
      ...options,
      id,
      variant: options.variant ?? "default",
      duration: options.duration ?? duration,
      version: 0,
      leaving: false,
    };
    setToasts((list) => {
      const existing = list.find((item) => item.id === id);
      if (existing) return list.map((item) => (item.id === id ? { ...record, version: item.version + 1 } : item));
      return [record, ...list];
    });
    announce(record);
    return id;
  }, [announce, duration]);

  const update = useCallback((id: string, options: Partial<ToastOptions>) => {
    const current = toastsRef.current.find((item) => item.id === id);
    if (!current) return;
    const next = { ...current, ...options, variant: options.variant ?? current.variant, duration: options.duration ?? (options.variant && options.variant !== "loading" ? duration : current.duration) };
    setToasts((list) => list.map((item) => (item.id === id ? { ...next, id, version: item.version + 1, leaving: false } : item)));
    announce(next);
  }, [announce, duration]);

  // Over the limit: the oldest live toasts close.
  useEffect(() => {
    const live = toasts.filter((item) => !item.leaving);
    if (live.length > max) live.slice(max).forEach((item) => dismiss(item.id));
  }, [toasts, max, dismiss]);

  useEffect(() => {
    const onVisibility = () => setHidden(document.visibilityState === "hidden");
    document.addEventListener("visibilitychange", onVisibility);
    return () => document.removeEventListener("visibilitychange", onVisibility);
  }, []);

  // Clear the spoken copy shortly after, so it is not read twice when browsing the page.
  useEffect(() => {
    if (!announcement) return;
    const timer = setTimeout(() => setAnnouncement(null), 2500);
    return () => clearTimeout(timer);
  }, [announcement]);

  const reportHeight = useCallback((id: string, height: number) => {
    setHeights((current) => (current[id] === height ? current : { ...current, [id]: height }));
  }, []);

  const api = useMemo(() => ({ toast, update, dismiss }), [toast, update, dismiss]);
  const live = toasts.filter((item) => !item.leaving);
  const expanded = (hovered || focused) && live.length > 1;
  const paused = hovered || focused || hidden;
  const fromTop = position.startsWith("top");

  // Stack geometry: collapsed toasts peek out behind the newest; expanded ones sit in a list.
  const frontHeight = heights[live[0]?.id] ?? 0;
  const offsets = new Map<string, number>();
  let running = 0;
  live.forEach((item, index) => {
    offsets.set(item.id, expanded ? running : Math.min(index, VISIBLE_COLLAPSED - 1) * PEEK);
    running += (heights[item.id] ?? 0) + GAP;
  });
  const stackHeight = live.length === 0 ? 0 : expanded
    ? running - GAP
    : frontHeight + Math.min(live.length - 1, VISIBLE_COLLAPSED - 1) * PEEK;

  return (
    <ToastContext.Provider value={api}>
      {children}
      <section
        aria-label={label}
        tabIndex={-1}
        className={cn("pointer-events-none fixed z-[100] w-[min(22rem,calc(100vw-2rem))] outline-hidden", positions[position])}
      >
        <ol
          onMouseEnter={() => setHovered(true)}
          onMouseLeave={() => setHovered(false)}
          onFocus={() => setFocused(true)}
          onBlur={(event) => {
            if (!event.currentTarget.contains(event.relatedTarget as Node)) setFocused(false);
          }}
          style={{ height: stackHeight }}
          className="pointer-events-auto relative motion-safe:transition-[height] motion-safe:duration-300 motion-safe:ease-[cubic-bezier(.2,.8,.2,1)]"
        >
          {toasts.map((item) => {
            const index = live.indexOf(item);
            return (
              <ToastItem
                key={item.id}
                record={item}
                index={index}
                offset={offsets.get(item.id) ?? 0}
                expanded={expanded}
                fromTop={fromTop}
                frontHeight={frontHeight}
                paused={paused}
                onHeight={reportHeight}
                onDismiss={dismiss}
              />
            );
          })}
        </ol>
      </section>
      <div aria-live="polite" aria-atomic="true" className="sr-only">
        {announcement && !announcement.urgent && <span key={announcement.key}>{announcement.node}</span>}
      </div>
      <div aria-live="assertive" aria-atomic="true" className="sr-only">
        {announcement?.urgent && <span key={announcement.key}>{announcement.node}</span>}
      </div>
    </ToastContext.Provider>
  );
}

const icons: Record<Exclude<ToastVariant, "default">, ReactNode> = {
  success: <CircleCheck className="text-emerald-600 dark:text-emerald-400" />,
  error: <CircleX className="text-destructive" />,
  warning: <TriangleAlert className="text-amber-600 dark:text-amber-400" />,
  info: <Info className="text-sky-600 dark:text-sky-400" />,
  loading: <LoaderCircle className="text-muted-foreground motion-safe:animate-spin" />,
};

interface ToastItemProps {
  record: ToastRecord;
  index: number;
  offset: number;
  expanded: boolean;
  fromTop: boolean;
  frontHeight: number;
  paused: boolean;
  onHeight: (id: string, height: number) => void;
  onDismiss: (id: string) => void;
}

function ToastItem({ record, index, offset, expanded, fromTop, frontHeight, paused, onHeight, onDismiss }: ToastItemProps) {
  const { id, title, description, variant, duration, action, version, leaving } = record;
  const ref = useRef<HTMLLIElement>(null);
  const remaining = useRef(duration);

  // offsetHeight ignores the scale transform; add the li's own borders.
  const measure = useCallback(() => {
    const node = ref.current;
    const content = node?.firstElementChild as HTMLElement | null;
    if (node && content) onHeight(id, content.offsetHeight + node.offsetHeight - node.clientHeight);
  }, [id, onHeight]);

  // After every render (content may have changed through an update), and on later size changes such as font loading.
  useLayoutEffect(measure);
  useEffect(() => {
    const content = ref.current?.firstElementChild;
    if (!content) return;
    const observer = new ResizeObserver(measure);
    observer.observe(content);
    return () => observer.disconnect();
  }, [measure]);

  // An update (new content or variant) restarts the clock.
  useEffect(() => {
    remaining.current = duration;
  }, [duration, version]);

  // Auto-dismiss, paused while the stack is hovered or focused, or the tab is hidden.
  useEffect(() => {
    if (leaving || paused || variant === "loading" || !Number.isFinite(duration)) return;
    const started = Date.now();
    const timer = setTimeout(() => onDismiss(id), Math.max(0, remaining.current));
    return () => {
      clearTimeout(timer);
      remaining.current -= Date.now() - started;
    };
  }, [leaving, paused, variant, duration, version, id, onDismiss]);

  const behind = index > 0;
  const hiddenBehind = !expanded && index >= VISIBLE_COLLAPSED;
  const direction = fromTop ? 1 : -1;
  const scale = leaving ? 0.96 : expanded || index < 0 ? 1 : 1 - Math.min(index, VISIBLE_COLLAPSED) * 0.05;

  // Position lives in CSS variables so the enter animation can come from @starting-style, with no JS frame timing.
  const style = {
    "--toast-y": `${direction * offset}px`,
    "--toast-from": `${-direction * 24}px`,
    "--toast-scale": scale,
    zIndex: 50 - Math.max(index, 0),
    // Collapsed, the toasts behind take the front toast's height so only their edge shows.
    height: behind && !expanded && frontHeight ? frontHeight : undefined,
    transformOrigin: fromTop ? "bottom center" : "top center",
  } as CSSProperties;

  return (
    <li
      ref={ref}
      data-variant={variant}
      data-front={index === 0 || undefined}
      aria-hidden={leaving || undefined}
      style={style}
      className={cn(
        "absolute inset-x-0 overflow-hidden rounded-xl border border-border text-popover-foreground",
        // Cards behind the front one are tinted toward the foreground so the deck reads in light and dark themes.
        behind && !expanded ? "bg-[color-mix(in_oklab,var(--popover)_93%,var(--foreground))]" : "bg-popover",
        "[transform:translateY(var(--toast-y))_scale(var(--toast-scale))] starting:opacity-0",
        "motion-safe:starting:[transform:translateY(var(--toast-from))_scale(1)]",
        leaving || hiddenBehind ? "opacity-0" : "opacity-100",
        leaving && "pointer-events-none",
        "shadow-[0_12px_32px_-12px_rgb(0_0_0/0.22),0_2px_6px_-2px_rgb(0_0_0/0.08)] dark:shadow-[0_12px_32px_-12px_rgb(0_0_0/0.7)]",
        "transition-opacity duration-200 motion-safe:transition-[transform,opacity,height] motion-safe:duration-300 motion-safe:ease-[cubic-bezier(.2,.8,.2,1)]",
        fromTop ? "top-0" : "bottom-0",
      )}
    >
      <div className={cn("flex gap-3 p-4 pr-11 transition-opacity duration-200", behind && !expanded && "opacity-0")}>
        {variant !== "default" && (
          <span aria-hidden="true" className="mt-px shrink-0 [&_svg]:size-[18px]">{icons[variant]}</span>
        )}
        <div className="min-w-0 flex-1">
          <p className="text-sm font-medium leading-5 text-foreground">{title}</p>
          {description && <p className="mt-0.5 text-[13px] leading-5 text-muted-foreground">{description}</p>}
          {action && (
            <button
              type="button"
              onClick={() => {
                action.onClick();
                onDismiss(id);
              }}
              className="mt-2.5 inline-flex h-7 items-center rounded-md border border-border bg-background px-2.5 text-xs font-medium text-foreground shadow-xs outline-hidden transition-colors hover:bg-accent focus-visible:ring-[3px] focus-visible:ring-ring/50 dark:bg-input/20"
            >
              {action.label}
            </button>
          )}
        </div>
      </div>
      <button
        type="button"
        aria-label="Dismiss notification"
        onClick={() => onDismiss(id)}
        className={cn(
          "absolute right-2.5 top-2.5 inline-flex size-7 items-center justify-center rounded-md text-muted-foreground outline-hidden",
          "transition-[color,background-color,opacity] hover:bg-accent hover:text-foreground focus-visible:ring-[3px] focus-visible:ring-ring/50",
          behind && !expanded && "opacity-0",
        )}
      >
        <X aria-hidden="true" className="size-4" />
      </button>
    </li>
  );
}