Toast.tsx 1.75 KB
"use client";

import { useEffect } from "react";
import { AlertCircle, AlertTriangle, CheckCircle2, Info, X } from "lucide-react";
import { cn } from "@/lib/utils";

export type ToastType = "error" | "success" | "info" | "warning";

export interface ToastState {
  message: string;
  type: ToastType;
}

const ICONS = {
  error: AlertCircle,
  success: CheckCircle2,
  info: Info,
  warning: AlertTriangle,
} as const;

const STYLES = {
  error: "bg-red-50 border-red-200 text-red-700",
  success: "bg-emerald-50 border-emerald-200 text-emerald-700",
  info: "bg-blue-50 border-blue-200 text-blue-700",
  warning: "bg-amber-50 border-amber-200 text-amber-700",
} as const;

/** 右上角轻量提示。错误默认停留久一些,方便用户看清。 */
export default function Toast({
  toast,
  onClose,
}: {
  toast: ToastState | null;
  onClose: () => void;
}) {
  useEffect(() => {
    if (!toast) return;
    const timeout = toast.type === "error" ? 6000 : 3000;
    const timer = setTimeout(onClose, timeout);
    return () => clearTimeout(timer);
  }, [toast, onClose]);

  if (!toast) return null;
  const Icon = ICONS[toast.type];

  return (
    <div className="fixed top-4 left-1/2 -translate-x-1/2 z-[80] animate-in fade-in slide-in-from-top-4 duration-200">
      <div
        className={cn(
          "flex items-center gap-2.5 pl-3.5 pr-2.5 py-2.5 rounded-xl border shadow-lg max-w-md",
          STYLES[toast.type]
        )}
      >
        <Icon className="w-4 h-4 shrink-0" />
        <span className="text-xs font-medium">{toast.message}</span>
        <button
          onClick={onClose}
          className="p-0.5 rounded-md hover:bg-black/5 transition shrink-0"
        >
          <X className="w-3.5 h-3.5" />
        </button>
      </div>
    </div>
  );
}