| 31 | } |
| 32 | |
| 33 | export const ToastProvider: React.FC<ToastProviderProps> = ({ children }) => { |
| 34 | const [toasts, setToasts] = useState<Toast[]>([]); |
| 35 | |
| 36 | const showToast = useCallback((message: string, type: ToastType = 'info', duration: number = 3000) => { |
| 37 | const id = `toast-${Date.now()}-${Math.random()}`; |
| 38 | const toast: Toast = { id, message, type, duration }; |
| 39 | |
| 40 | setToasts((prev) => [...prev, toast]); |
| 41 | |
| 42 | if (duration > 0) { |
| 43 | setTimeout(() => { |
| 44 | hideToast(id); |
| 45 | }, duration); |
| 46 | } |
| 47 | }, []); |
| 48 | |
| 49 | const hideToast = useCallback((id: string) => { |
| 50 | setToasts((prev) => prev.filter((t) => t.id !== id)); |
| 51 | }, []); |
| 52 | |
| 53 | const getIcon = (type: ToastType) => { |
| 54 | switch (type) { |
| 55 | case 'success': |
| 56 | return <CheckCircle size={20} />; |
| 57 | case 'error': |
| 58 | return <XCircle size={20} />; |
| 59 | case 'warning': |
| 60 | return <AlertCircle size={20} />; |
| 61 | case 'info': |
| 62 | return <Info size={20} />; |
| 63 | } |
| 64 | }; |
| 65 | |
| 66 | return ( |
| 67 | <ToastContext.Provider value={{ showToast, hideToast }}> |
| 68 | {children} |
| 69 | <div className="toast-container"> |
| 70 | {toasts.map((toast) => ( |
| 71 | <div key={toast.id} className={`toast toast-${toast.type}`}> |
| 72 | <div className="toast-icon"> |
| 73 | {getIcon(toast.type)} |
| 74 | </div> |
| 75 | <div className="toast-message">{toast.message}</div> |
| 76 | <button |
| 77 | className="toast-close" |
| 78 | onClick={() => hideToast(toast.id)} |
| 79 | aria-label="关闭" |
| 80 | > |
| 81 | <X size={16} /> |
| 82 | </button> |
| 83 | </div> |
| 84 | ))} |
| 85 | </div> |
| 86 | </ToastContext.Provider> |
| 87 | ); |
| 88 | }; |