1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
|
import {
createContext,
useCallback,
useContext,
useEffect,
useRef,
useState,
type ReactNode,
} from 'react';
import './Toast.css';
// -- Types -------------------------------------------------------------------
export type ToastType = 'success' | 'error' | 'info';
interface ToastItem {
id: number;
message: string;
type: ToastType;
}
interface ToastContextValue {
addToast: (message: string, type?: ToastType) => void;
}
// -- Context -----------------------------------------------------------------
const ToastContext = createContext<ToastContextValue | null>(null);
export function useToast(): ToastContextValue {
const ctx = useContext(ToastContext);
if (!ctx) throw new Error('useToast must be used within a ToastProvider');
return ctx;
}
// -- Provider ----------------------------------------------------------------
const DISMISS_MS = 3000;
export function ToastProvider({ children }: { children: ReactNode }) {
const [toasts, setToasts] = useState<ToastItem[]>([]);
const nextId = useRef(0);
const addToast = useCallback((message: string, type: ToastType = 'info') => {
const id = nextId.current++;
setToasts((prev) => [...prev, { id, message, type }]);
}, []);
const removeToast = useCallback((id: number) => {
setToasts((prev) => prev.filter((t) => t.id !== id));
}, []);
return (
<ToastContext.Provider value={{ addToast }}>
{children}
<div className="toast-container">
{toasts.map((t) => (
<ToastItem key={t.id} toast={t} onDismiss={removeToast} />
))}
</div>
</ToastContext.Provider>
);
}
// -- Single toast ------------------------------------------------------------
function ToastItem({
toast,
onDismiss,
}: {
toast: ToastItem;
onDismiss: (id: number) => void;
}) {
const [exiting, setExiting] = useState(false);
useEffect(() => {
const timer = setTimeout(() => setExiting(true), DISMISS_MS - 300);
const remove = setTimeout(() => onDismiss(toast.id), DISMISS_MS);
return () => {
clearTimeout(timer);
clearTimeout(remove);
};
}, [toast.id, onDismiss]);
const icon =
toast.type === 'success' ? '\u2713' : toast.type === 'error' ? '\u2717' : '\u2139';
return (
<div
className={`toast-item toast-${toast.type} ${exiting ? 'toast-exit' : 'toast-enter'}`}
role="status"
>
<span className="toast-icon">{icon}</span>
<span className="toast-message">{toast.message}</span>
</div>
);
}
|