| 1 | /* 全局消息(toast):模块级单例 + <ToastHost/>(挂在应用根部一次)。 |
| 2 | 任何模块 `import { toast } from "./toast"` 即可弹消息,无需 context 接线。 |
| 3 | 右下角堆叠,success/info 3.8s、error 6s 自动消失,可手动关闭。 */ |
| 4 | import { useEffect, useState } from "react"; |
| 5 | import { AlertCircle, CheckCircle2, Info, X } from "lucide-react"; |
| 6 | |
| 7 | type Kind = "success" | "error" | "info"; |
| 8 | type Item = { id: number; kind: Kind; text: string }; |
| 9 | |
| 10 | let nextId = 1; |
| 11 | let items: Item[] = []; |
| 12 | let listener: ((items: Item[]) => void) | null = null; |
| 13 | |
| 14 | function dismiss(id: number) { |
| 15 | items = items.filter((t) => t.id !== id); |
| 16 | listener?.(items); |
| 17 | } |
| 18 | |
| 19 | function push(kind: Kind, text: string) { |
| 20 | const id = nextId++; |
| 21 | items = [...items, { id, kind, text }]; |
| 22 | listener?.(items); |
| 23 | window.setTimeout(() => dismiss(id), kind === "error" ? 6000 : 3800); |
| 24 | } |
| 25 | |
| 26 | export const toast = { |
| 27 | success: (text: string) => push("success", text), |
| 28 | error: (text: string) => push("error", text), |
| 29 | info: (text: string) => push("info", text), |
| 30 | }; |
| 31 | |
| 32 | const ICON = { success: CheckCircle2, error: AlertCircle, info: Info } as const; |
| 33 | const ICON_COLOR: Record<Kind, string> = { |
| 34 | success: "text-[var(--u-ok)]", |
| 35 | error: "text-[var(--u-danger)]", |
| 36 | info: "text-neutral-400", |
| 37 | }; |
| 38 | |
| 39 | export function ToastHost() { |
| 40 | const [list, setList] = useState<Item[]>(items); |
| 41 | useEffect(() => { |
| 42 | listener = setList; |
| 43 | return () => { |
| 44 | if (listener === setList) listener = null; |
| 45 | }; |
| 46 | }, []); |
| 47 | if (!list.length) return null; |
| 48 | return ( |
| 49 | <div className="pointer-events-none fixed bottom-5 right-5 z-[100] flex flex-col items-end gap-2"> |
| 50 | {list.map((t) => { |
| 51 | const Icon = ICON[t.kind]; |
| 52 | return ( |
| 53 | <div |
| 54 | key={t.id} |
| 55 | className="u-pop u-toast-in pointer-events-auto flex items-center gap-2.5 rounded-xl py-2.5 pl-3.5 pr-2.5 text-sm text-neutral-200 shadow-xl" |
| 56 | > |
| 57 | <Icon size={15} className={`shrink-0 ${ICON_COLOR[t.kind]}`} /> |
| 58 | <span className="max-w-xs">{t.text}</span> |
| 59 | <button |
| 60 | onClick={() => dismiss(t.id)} |
| 61 | className="text-neutral-600 hover:text-neutral-300" |
| 62 | > |
| 63 | <X size={13} /> |
| 64 | </button> |
| 65 | </div> |
| 66 | ); |
| 67 | })} |
| 68 | </div> |
| 69 | ); |
| 70 | } |