Elffuss BraidHub

kikocis/utopia public

dev · 2.2 KiBRawPermalink
1/* 全局消息(toast):模块级单例 + <ToastHost/>(挂在应用根部一次)。
2 任何模块 `import { toast } from "./toast"` 即可弹消息,无需 context 接线。
3 右下角堆叠,success/info 3.8s、error 6s 自动消失,可手动关闭。 */
4import { useEffect, useState } from "react";
5import { AlertCircle, CheckCircle2, Info, X } from "lucide-react";
6
7type Kind = "success" | "error" | "info";
8type Item = { id: number; kind: Kind; text: string };
9
10let nextId = 1;
11let items: Item[] = [];
12let listener: ((items: Item[]) => void) | null = null;
13
14function dismiss(id: number) {
15 items = items.filter((t) => t.id !== id);
16 listener?.(items);
17}
18
19function 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
26export 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
32const ICON = { success: CheckCircle2, error: AlertCircle, info: Info } as const;
33const ICON_COLOR: Record<Kind, string> = {
34 success: "text-[var(--u-ok)]",
35 error: "text-[var(--u-danger)]",
36 info: "text-neutral-400",
37};
38
39export 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}