'use client'; // Toast 通知系统:右上角弹出,自动消失(替代 alert) // 用法:const { toast } = useToast(); toast('发布成功', 'success'); // 注意:不用 createPortal(SSR 时 document 不存在会造成 hydration mismatch, // 导致整树重建)。toast-container 是 position:fixed,渲染位置不影响视觉。 import { createContext, useContext, useState, useCallback, useRef, useEffect } from 'react'; import { Icon } from './Icons'; const ToastContext = createContext(null); export function useToast() { return useContext(ToastContext); } let idCounter = 0; export function ToastProvider({ children }) { const [toasts, setToasts] = useState([]); const [dialog, setDialog] = useState(null); const timersRef = useRef({}); const dialogTimerRef = useRef(null); const dialogResolverRef = useRef(null); const removeToast = useCallback((id) => { setToasts((prev) => prev.filter((item) => item.id !== id)); delete timersRef.current[id]; }, []); const dismiss = useCallback((id) => { if (timersRef.current[id]) clearTimeout(timersRef.current[id]); setToasts((prev) => prev.map((item) => item.id === id ? { ...item, closing: true } : item)); timersRef.current[id] = setTimeout(() => removeToast(id), 220); }, [removeToast]); const toast = useCallback((message, type = 'success', duration = 3000) => { const id = ++idCounter; setToasts((prev) => [...prev, { id, message, type, closing: false }]); if (timersRef.current[id]) clearTimeout(timersRef.current[id]); timersRef.current[id] = setTimeout(() => dismiss(id), duration); }, [dismiss]); const confirmAction = useCallback((message, options = {}) => { if (dialogResolverRef.current) dialogResolverRef.current(false); const isEnglish = localStorage.getItem('forumlify-lang') === 'en'; setDialog({ message, title: options.title || (isEnglish ? 'Confirm action' : '确认操作'), confirmLabel: options.confirmLabel || (isEnglish ? 'Confirm' : '确定'), cancelLabel: options.cancelLabel || (isEnglish ? 'Cancel' : '取消'), danger: options.danger !== false, closing: false, }); return new Promise((resolve) => { dialogResolverRef.current = resolve; }); }, []); const closeDialog = useCallback((result) => { setDialog((current) => current ? { ...current, closing: true } : current); if (dialogTimerRef.current) clearTimeout(dialogTimerRef.current); dialogTimerRef.current = setTimeout(() => { setDialog(null); const resolve = dialogResolverRef.current; dialogResolverRef.current = null; if (resolve) resolve(result); }, 340); }, []); useEffect(() => () => { Object.values(timersRef.current).forEach(clearTimeout); if (dialogTimerRef.current) clearTimeout(dialogTimerRef.current); if (dialogResolverRef.current) dialogResolverRef.current(false); }, []); return ( {children}
{toasts.map((t) => (
dismiss(t.id)} role="status"> {t.message}
))}
{dialog && (
{ if (e.target === e.currentTarget) closeDialog(false); }}>

{dialog.title}

{dialog.message}

)}
); }