|
| 1 | +import { useState, useEffect, useCallback } from 'react'; |
| 2 | + |
| 3 | +type ToastType = 'success' | 'error' | 'info'; |
| 4 | + |
| 5 | +interface ToastMessage { |
| 6 | + id: number; |
| 7 | + text: string; |
| 8 | + type: ToastType; |
| 9 | +} |
| 10 | + |
| 11 | +let _addToast: ((text: string, type?: ToastType) => void) | null = null; |
| 12 | + |
| 13 | +/** Call from anywhere to show a toast notification. */ |
| 14 | +export function showToast(text: string, type: ToastType = 'info') { |
| 15 | + _addToast?.(text, type); |
| 16 | +} |
| 17 | + |
| 18 | +let _nextId = 1; |
| 19 | + |
| 20 | +export default function ToastContainer() { |
| 21 | + const [toasts, setToasts] = useState<ToastMessage[]>([]); |
| 22 | + |
| 23 | + const addToast = useCallback((text: string, type: ToastType = 'info') => { |
| 24 | + const id = _nextId++; |
| 25 | + setToasts(prev => [...prev, { id, text, type }]); |
| 26 | + setTimeout(() => setToasts(prev => prev.filter(t => t.id !== id)), 3000); |
| 27 | + }, []); |
| 28 | + |
| 29 | + useEffect(() => { _addToast = addToast; return () => { _addToast = null; }; }, [addToast]); |
| 30 | + |
| 31 | + if (toasts.length === 0) return null; |
| 32 | + |
| 33 | + const icons: Record<ToastType, string> = { success: 'check_circle', error: 'error', info: 'info' }; |
| 34 | + |
| 35 | + return ( |
| 36 | + <div className="toast-container"> |
| 37 | + {toasts.map(t => ( |
| 38 | + <div key={t.id} className={`toast-item toast-${t.type}`}> |
| 39 | + <span className="material-icons toast-icon">{icons[t.type]}</span> |
| 40 | + <span className="toast-text">{t.text}</span> |
| 41 | + <button className="toast-close" onClick={() => setToasts(prev => prev.filter(x => x.id !== t.id))}> |
| 42 | + <span className="material-icons">close</span> |
| 43 | + </button> |
| 44 | + </div> |
| 45 | + ))} |
| 46 | + </div> |
| 47 | + ); |
| 48 | +} |
0 commit comments