RendyUI 中文

Components / Toast

Toast

Feedback · React / TypeScript Free

Recorded demo

Toast preview

Source

toast.tsx
"use client";

/**
 * Toast — replica of the public UI Stacks spec.
 * Original implementation written from the public API docs.
 */
import * as React from "react";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import { AlertTriangle, CheckCircle2, Info, Loader2, X, XCircle } from "lucide-react";
import { cn } from "../internal";

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

export type ToastOptions = {
  description?: React.ReactNode;
  tone?: ToastTone;
  layout?: "detailed" | "compact";
  duration?: number;
  action?: { label: string; onClick: () => void };
  icon?: React.ReactNode;
  timer?: boolean;
  id?: string;
};

export type ToastRecord = ToastOptions & {
  id: string;
  title: string;
  tone: ToastTone;
  createdAt: number;
  duration: number;
  open: boolean;
};

type Listener = (toasts: ToastRecord[]) => void;

let counter = 0;
let toasts: ToastRecord[] = [];
const listeners = new Set<Listener>();

function emit() {
  listeners.forEach((listener) => listener([...toasts]));
}

function push(title: string, options: ToastOptions = {}): string {
  const id = options.id ?? `toast-${++counter}`;
  const duration = options.duration ?? 4000;
  const next: ToastRecord = {
    ...options,
    id,
    title,
    tone: options.tone ?? "default",
    duration: options.tone === "loading" ? 0 : duration,
    createdAt: Date.now(),
    open: true,
  };
  toasts = [next, ...toasts.filter((toast) => toast.id !== id)].slice(0, 8);
  emit();
  return id;
}

function update(id: string, options: Partial<ToastRecord>) {
  toasts = toasts.map((toast) =>
    toast.id === id ? { ...toast, ...options, open: true } : toast,
  );
  emit();
}

function dismiss(id: string) {
  toasts = toasts.map((toast) =>
    toast.id === id ? { ...toast, open: false } : toast,
  );
  emit();
  window.setTimeout(() => {
    toasts = toasts.filter((toast) => toast.id !== id);
    emit();
  }, 220);
}

export const toast = Object.assign(push, {
  success: (title: string, options?: ToastOptions) =>
    push(title, { ...options, tone: "success" }),
  warning: (title: string, options?: ToastOptions) =>
    push(title, { ...options, tone: "warning" }),
  error: (title: string, options?: ToastOptions) =>
    push(title, { ...options, tone: "error" }),
  info: (title: string, options?: ToastOptions) =>
    push(title, { ...options, tone: "info" }),
  loading: (title: string, options?: ToastOptions) =>
    push(title, { ...options, tone: "loading" }),
  dismiss,
  update,
  promise: async <T,>(
    promise: Promise<T>,
    messages: { loading: string; success: string | ((value: T) => string); error: string | ((error: unknown) => string) },
    options?: Partial<ToastRecord>,
  ) => {
    const id = push(messages.loading, { ...options, tone: "loading", duration: 0 });
    try {
      const value = await promise;
      update(id, {
        tone: "success",
        title:
          typeof messages.success === "function" ? messages.success(value) : messages.success,
        duration: options?.duration ?? 4000,
      });
      return value;
    } catch (error) {
      update(id, {
        tone: "error",
        title:
          typeof messages.error === "function" ? messages.error(error) : messages.error,
        duration: options?.duration ?? 6000,
      });
      throw error;
    }
  },
});

export interface ToasterProps {
  position?: ToastPosition;
  layout?: "detailed" | "compact";
  duration?: number;
  visibleToasts?: number;
  closeButton?: boolean;
  contained?: boolean;
  className?: string;
}

const TONE_ICON: Record<ToastTone, React.ReactNode> = {
  default: null,
  success: <CheckCircle2 className="size-4 text-success" aria-hidden />,
  warning: <AlertTriangle className="size-4 text-warning" aria-hidden />,
  error: <XCircle className="size-4 text-danger" aria-hidden />,
  info: <Info className="size-4 text-select" aria-hidden />,
  loading: <Loader2 className="size-4 animate-spin text-fg-subtle" aria-hidden />,
};

const POSITIONS: Record<ToastPosition, string> = {
  "top-left": "top-4 left-4 items-start",
  "top-center": "top-4 left-1/2 -translate-x-1/2 items-center",
  "top-right": "top-4 right-4 items-end",
  "bottom-left": "bottom-4 left-4 items-start",
  "bottom-center": "bottom-4 left-1/2 -translate-x-1/2 items-center",
  "bottom-right": "bottom-4 right-4 items-end",
};

/**
 * Toaster: renders the stack of toasts. Hovering fans the stack out and
 * pauses every timer; a promise moves one toast from loading to success.
 */
export function Toaster({
  position = "bottom-right",
  layout = "detailed",
  duration = 4000,
  visibleToasts = 3,
  closeButton = true,
  contained = false,
  className,
}: ToasterProps) {
  const reduce = useReducedMotion();
  const [items, setItems] = React.useState<ToastRecord[]>([]);
  const [paused, setPaused] = React.useState(false);
  const [hovered, setHovered] = React.useState(false);

  React.useEffect(() => {
    const listener: Listener = (next) => setItems(next);
    listeners.add(listener);
    return () => {
      listeners.delete(listener);
    };
  }, []);

  React.useEffect(() => {
    if (paused) return;
    const timers = items
      .filter((item) => item.duration > 0 && item.open)
      .map((item) =>
        window.setTimeout(() => dismiss(item.id), item.duration),
      );
    return () => timers.forEach((timer) => window.clearTimeout(timer));
  }, [items, paused]);

  const shown = items.slice(0, visibleToasts);

  return (
    <div
      className={cn(
        "pointer-events-none fixed z-[200] flex flex-col gap-2",
        contained ? "absolute" : "fixed",
        POSITIONS[position],
        className,
      )}
      onMouseEnter={() => {
        setHovered(true);
        setPaused(true);
      }}
      onMouseLeave={() => {
        setHovered(false);
        setPaused(false);
      }}
      onFocusCapture={() => setPaused(true)}
      onBlurCapture={() => setPaused(false)}
      role="region"
      aria-label="Notifications"
    >
      <AnimatePresence initial={false}>
        {shown.map((item, index) => (
          <motion.div
            key={item.id}
            layout={!reduce}
            initial={reduce ? false : { opacity: 0, y: 12, scale: 0.96 }}
            animate={{
              opacity: 1,
              y: 0,
              scale: 1,
              transition: { type: "spring", stiffness: 420, damping: 34 },
            }}
            exit={reduce ? undefined : { opacity: 0, x: 24, scale: 0.96 }}
            role="status"
            aria-live="polite"
            className={cn(
              "pointer-events-auto flex w-[320px] items-start gap-2.5 rounded-[12px] border border-border bg-surface p-3 shadow-[var(--shadow-overlay)]",
              hovered && index > 0 && "md:scale-[0.97]",
            )}
            style={{ transformOrigin: position.includes("right") ? "right center" : "center" }}
          >
            {item.icon ?? TONE_ICON[item.tone]}
            <div className="min-w-0 flex-1">
              <div className="text-[13.5px] font-medium leading-5 text-fg">{item.title}</div>
              {layout === "detailed" && item.description ? (
                <div className="mt-0.5 text-[12.5px] leading-5 text-fg-muted">{item.description}</div>
              ) : null}
              {item.action ? (
                <button
                  type="button"
                  onClick={item.action.onClick}
                  className="mt-2 rounded-[7px] border border-border bg-surface px-2.5 py-1 text-[12px] font-medium text-fg transition-colors hover:bg-subtle"
                >
                  {item.action.label}
                </button>
              ) : null}
            </div>
            {closeButton ? (
              <button
                type="button"
                aria-label="Dismiss"
                onClick={() => dismiss(item.id)}
                className="grid size-6 shrink-0 place-items-center rounded-full text-fg-subtle transition-colors hover:bg-subtle hover:text-fg"
              >
                <X className="size-3.5" aria-hidden />
              </button>
            ) : null}
          </motion.div>
        ))}
      </AnimatePresence>
    </div>
  );
}

export default Toaster;

Usage

Add the TSX to your React project and install the required dependencies. Styles use Tailwind CSS and theme tokens。

Package dependencies · lucide-react、motion、react

Shared source · internal.ts

Props

NameTypeDescription
`toast(title, options?)``(string, ToastOptions) => string`Returns the id. Also toast.success / warning / error / info / loading / dismiss.
`toast.promise``(promise, { loading; success; error }, options?) => promise`One toast from loading to success or error.
`options``{ description?; tone?; layout?; duration?; action?; icon?; timer?; id? }`Pass an id to update a toast in place.
`position``"top-left" \| "top-center" \| "top-right" \| "bottom-left" \| "bottom-center" \| "bottom-right"`Where the Toaster sits.
`layout / duration / visibleToasts``"detailed" \| "compact" / number / number`Toaster defaults: detailed, 4000 ms, 3 visible.
`closeButton / contained``boolean`Show ×; keep the stack inside its parent for previews.