0

Component

Toast stack

Notifications that pile up, fan out on hover, pause while you read, and swipe away.

    Usage

    // Once, near the root:
    <ToastProvider>{children}</ToastProvider>
    
    // Anywhere below it:
    const toast = useToast();
    
    toast.push({ kind: "success", title: "Changes saved" });
    toast.push({ title: "Note deleted", action: { label: "Undo", onClick: restore } });
    toast.promise(publish(), { loading: "Publishing…", success: "Published", error: "Could not publish" });

    Source

    Copy both files into your project. The component has no dependencies beyond React.

    "use client";
    
    import {
      createContext,
      useCallback,
      useContext,
      useEffect,
      useLayoutEffect,
      useMemo,
      useRef,
      useState,
      type PointerEvent,
      type ReactNode,
    } from "react";
    import styles from "./toast-stack.module.css";
    
    export type ToastKind = "info" | "success" | "error" | "loading";
    
    export type ToastInput = {
      title: string;
      description?: string;
      kind?: ToastKind;
      /** Milliseconds on screen. Loading toasts stay until you update them. */
      duration?: number;
      action?: { label: string; onClick: () => void };
    };
    
    type Toast = ToastInput & { id: number; kind: ToastKind; remaining: number; leaving: boolean };
    
    type ToastApi = {
      push: (input: ToastInput) => number;
      update: (id: number, patch: Partial<ToastInput>) => void;
      dismiss: (id: number) => void;
      /** Shows a loading toast, then turns it into success or error when the promise settles. */
      promise: <T>(work: Promise<T>, text: { loading: string; success: string; error: string }) => Promise<T>;
    };
    
    const ToastContext = createContext<ToastApi | null>(null);
    const DEFAULT_DURATION = 5000;
    const GAP = 10;
    const VISIBLE = 3;
    
    export function useToast() {
      const api = useContext(ToastContext);
      if (!api) throw new Error("useToast must be used inside <ToastProvider>.");
      return api;
    }
    
    type ToastProviderProps = {
      children: ReactNode;
      /** Pin the stack to the nearest positioned ancestor instead of the window. */
      contained?: boolean;
    };
    
    export function ToastProvider({ children, contained = false }: ToastProviderProps) {
      const [toasts, setToasts] = useState<Toast[]>([]);
      const [heights, setHeights] = useState<Record<number, number>>({});
      const [expanded, setExpanded] = useState(false);
      const nextId = useRef(1);
      const paused = useRef(false);
      paused.current = expanded;
    
      const dismiss = useCallback((id: number) => {
        setToasts((list) => list.map((toast) => (toast.id === id ? { ...toast, leaving: true } : toast)));
        window.setTimeout(() => {
          setToasts((list) => list.filter((toast) => toast.id !== id));
          setHeights(({ [id]: _gone, ...rest }) => rest);
        }, 240);
      }, []);
    
      const push = useCallback((input: ToastInput) => {
        const id = nextId.current++;
        const kind = input.kind ?? "info";
        setToasts((list) => [{ ...input, id, kind, remaining: input.duration ?? DEFAULT_DURATION, leaving: false }, ...list]);
        return id;
      }, []);
    
      const update = useCallback((id: number, patch: Partial<ToastInput>) => {
        setToasts((list) =>
          list.map((toast) =>
            toast.id === id
              ? { ...toast, ...patch, kind: patch.kind ?? toast.kind, remaining: patch.duration ?? DEFAULT_DURATION }
              : toast,
          ),
        );
      }, []);
    
      const api = useMemo<ToastApi>(
        () => ({
          push,
          update,
          dismiss,
          promise(work, text) {
            const id = push({ kind: "loading", title: text.loading });
            work.then(
              () => update(id, { kind: "success", title: text.success }),
              () => update(id, { kind: "error", title: text.error }),
            );
            return work;
          },
        }),
        [push, update, dismiss],
      );
    
      // One clock for every toast. It stops while the stack is hovered, so nothing vanishes mid-read.
      const active = toasts.length > 0;
      useEffect(() => {
        if (!active) return;
        const id = window.setInterval(() => {
          if (paused.current) return;
          setToasts((list) => {
            const expired: number[] = [];
            const next = list.map((toast) => {
              if (toast.kind === "loading" || toast.leaving) return toast;
              const remaining = toast.remaining - 100;
              if (remaining <= 0) expired.push(toast.id);
              return { ...toast, remaining };
            });
            expired.forEach((gone) => window.setTimeout(() => dismiss(gone), 0));
            return next;
          });
        }, 100);
        return () => window.clearInterval(id);
      }, [active, dismiss]);
    
      const setHeight = useCallback((id: number, height: number) => {
        setHeights((all) => (all[id] === height ? all : { ...all, [id]: height }));
      }, []);
    
      const front = toasts[0] ? heights[toasts[0].id] ?? 0 : 0;
      let stacked = 0;
      const offsets = toasts.map((toast) => {
        const at = stacked;
        stacked += (heights[toast.id] ?? 0) + GAP;
        return at;
      });
      const regionHeight = expanded ? Math.max(0, stacked - GAP) : front + (Math.min(toasts.length, VISIBLE) - 1) * GAP;
    
      return (
        <ToastContext.Provider value={api}>
          {children}
          <ol
            className={styles.region}
            data-contained={contained ? "true" : "false"}
            data-expanded={expanded ? "true" : "false"}
            style={{ height: toasts.length ? regionHeight : 0 }}
            aria-live="polite"
            aria-label="Notifications"
            onPointerEnter={() => setExpanded(true)}
            onPointerLeave={() => setExpanded(false)}
            onFocus={() => setExpanded(true)}
            onBlur={() => setExpanded(false)}
          >
            {toasts.map((toast, index) => (
              <ToastItem
                key={toast.id}
                toast={toast}
                index={index}
                expanded={expanded}
                offset={offsets[index]}
                frontHeight={front}
                onHeight={setHeight}
                onDismiss={dismiss}
              />
            ))}
          </ol>
        </ToastContext.Provider>
      );
    }
    
    function Icon({ kind }: { kind: ToastKind }) {
      if (kind === "loading") return <span className={styles.spinner} aria-hidden="true" />;
      return (
        <svg className={styles.icon} data-kind={kind} viewBox="0 0 16 16" aria-hidden="true">
          <circle cx="8" cy="8" r="7" />
          {kind === "success" ? <path d="M5 8.300 7.200 10.500 11 6" /> : null}
          {kind === "error" ? <path d="M5.700 5.700l4.600 4.600M10.300 5.700l-4.600 4.600" /> : null}
          {kind === "info" ? <path d="M8 7.300v3.700M8 5v.100" /> : null}
        </svg>
      );
    }
    
    function ToastItem({
      toast,
      index,
      expanded,
      offset,
      frontHeight,
      onHeight,
      onDismiss,
    }: {
      toast: Toast;
      index: number;
      expanded: boolean;
      offset: number;
      frontHeight: number;
      onHeight: (id: number, height: number) => void;
      onDismiss: (id: number) => void;
    }) {
      const body = useRef<HTMLDivElement>(null);
      const start = useRef<number | null>(null);
      const [drag, setDrag] = useState(0);
    
      useLayoutEffect(() => {
        if (body.current) onHeight(toast.id, body.current.offsetHeight);
      });
    
      function down(event: PointerEvent<HTMLLIElement>) {
        if ((event.target as Element).closest("button")) return;
        start.current = event.clientX;
        event.currentTarget.setPointerCapture(event.pointerId);
      }
    
      function move(event: PointerEvent<HTMLLIElement>) {
        if (start.current === null) return;
        setDrag(Math.max(0, event.clientX - start.current));
      }
    
      function up() {
        if (start.current === null) return;
        start.current = null;
        if (drag > 90) onDismiss(toast.id);
        else setDrag(0);
      }
    
      const hidden = !expanded && index >= VISIBLE;
      const lift = expanded ? offset : index * GAP;
      const scale = expanded ? 1 : 1 - index * 0.05;
      const swipe = toast.leaving ? Math.max(drag, 0) + 140 : drag;
    
      return (
        <li
          className={styles.toast}
          data-kind={toast.kind}
          data-leaving={toast.leaving ? "true" : "false"}
          data-dragging={start.current !== null ? "true" : "false"}
          style={{
            height: expanded || index === 0 ? undefined : frontHeight,
            zIndex: 100 - index,
            opacity: hidden || toast.leaving ? 0 : 1 - drag / 220,
            pointerEvents: hidden ? "none" : undefined,
            transform: `translate(${swipe}px, ${-lift}px) scale(${scale})`,
          }}
          onPointerDown={down}
          onPointerMove={move}
          onPointerUp={up}
          onPointerCancel={up}
        >
          <div ref={body} className={styles.body}>
            <Icon kind={toast.kind} />
            <div className={styles.copy}>
              <strong>{toast.title}</strong>
              {toast.description ? <span>{toast.description}</span> : null}
            </div>
            {toast.action ? (
              <button
                type="button"
                className={styles.action}
                onClick={() => {
                  toast.action?.onClick();
                  onDismiss(toast.id);
                }}
              >
                {toast.action.label}
              </button>
            ) : null}
            <button type="button" className={styles.close} aria-label="Dismiss" onClick={() => onDismiss(toast.id)}>
              <svg viewBox="0 0 12 12" aria-hidden="true">
                <path d="M3 3l6 6M9 3l-6 6" />
              </svg>
            </button>
          </div>
        </li>
      );
    }