"use client"; import { createContext, useCallback, useContext, useMemo, useState, type ReactNode } from "react"; type ToastTone = "ok" | "warn" | "err"; type ToastItem = { id: string; text: string; tone?: ToastTone; href?: string; actionLabel?: string; onClick?: () => void; }; type PushOpts = { href?: string; actionLabel?: string; onClick?: () => void; durationMs?: number; }; const ToastCtx = createContext<{ push: (text: string, tone?: ToastTone, opts?: PushOpts) => void; } | null>(null); export function ToastProvider({ children }: { children: ReactNode }) { const [items, setItems] = useState([]); const push = useCallback((text: string, tone: ToastTone = "ok", opts?: PushOpts) => { const id = `${Date.now()}-${Math.random()}`; setItems((prev) => [ ...prev.slice(-4), { id, text, tone, href: opts?.href, actionLabel: opts?.actionLabel, onClick: opts?.onClick, }, ]); window.setTimeout(() => { setItems((prev) => prev.filter((x) => x.id !== id)); }, opts?.durationMs ?? (opts?.onClick || opts?.href ? 6000 : 3200)); }, []); const value = useMemo(() => ({ push }), [push]); return ( {children}
{items.map((t) => { const clickable = Boolean(t.onClick || t.href); const body = ( <>
{t.text}
{clickable ? (
{t.actionLabel || "点击查看 →"}
) : null} ); const cls = `pointer-events-auto animate-fade-up rounded-xl border px-3 py-2 text-left text-sm shadow-lg backdrop-blur ${ t.tone === "err" ? "border-rose-500/40 bg-rose-500/20 text-rose-50" : t.tone === "warn" ? "border-amber-500/40 bg-amber-500/20 text-amber-50" : "border-teal-500/40 bg-teal-500/20 text-teal-50" } ${clickable ? "cursor-pointer hover:brightness-110" : ""}`; if (t.href) { return ( {body} ); } if (t.onClick) { return ( ); } return (
{body}
); })}
); } export function useToast() { const ctx = useContext(ToastCtx); if (!ctx) { return { push: (_t: string, _tone?: ToastTone, _opts?: PushOpts) => undefined, }; } return ctx; }