Toast.tsx
1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
"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>
);
}