import { useCallback, useState } from "react"; import type { ToastMessage } from "./types.js"; /** * useToast - 全局 Toast 通知管理 * * 用途:成功/错误/警告/信息提示,自动关闭。 * 与 Zustand ui-store 解耦,提供 hook 层 API。 * * @example * const { toasts, showToast, dismissToast } = useToast(); * showToast({ type: "success", title: "保存成功" }); */ export interface UseToastReturn { /** 当前活跃的 toast 列表 */ toasts: ToastMessage[]; /** 展示 toast */ showToast: (toast: Omit) => string; /** 关闭指定 toast */ dismissToast: (id: string) => void; /** 关闭全部 toast */ dismissAll: () => void; } export function useToast(): UseToastReturn { const [toasts, setToasts] = useState([]); const dismissToast = useCallback((id: string): void => { setToasts((prev) => prev.filter((t) => t.id !== id)); }, []); const showToast = useCallback( (toast: Omit): string => { const id = `toast-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`; const fullToast: ToastMessage = { id, duration: 4000, ...toast, }; setToasts((prev) => [...prev, fullToast]); // 自动关闭 if (fullToast.duration && fullToast.duration > 0) { setTimeout(() => { dismissToast(id); }, fullToast.duration); } return id; }, [dismissToast], ); const dismissAll = useCallback((): void => { setToasts([]); }, []); return { toasts, showToast, dismissToast, dismissAll, }; }