forked from Nova-reward/Nova-Rewards
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathToast.js
More file actions
74 lines (62 loc) · 1.89 KB
/
Copy pathToast.js
File metadata and controls
74 lines (62 loc) · 1.89 KB
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
import { useState, useCallback, createContext, useContext } from 'react';
const ToastContext = createContext(null);
const ICONS = {
success: '✓',
error: '✕',
warning: '⚠',
info: 'ℹ',
};
const MAX_TOASTS = 3;
const DEFAULT_DURATION = 5000;
function Toast({ toast, onRemove }) {
return (
<div
role="status"
className={`toast toast-${toast.type}`}
>
<span className="toast-icon" aria-hidden="true">{ICONS[toast.type]}</span>
<span className="toast-message">{toast.message}</span>
<button
className="toast-close"
onClick={() => onRemove(toast.id)}
aria-label="Close notification"
>
✕
</button>
</div>
);
}
export function ToastProvider({ children }) {
const [toasts, setToasts] = useState([]);
const removeToast = useCallback((id) => {
setToasts((prev) => prev.filter((t) => t.id !== id));
}, []);
const addToast = useCallback((message, type = 'info', duration = DEFAULT_DURATION) => {
const id = Date.now();
setToasts((prev) => {
const next = [...prev, { id, message, type }];
// drop oldest if over limit
return next.length > MAX_TOASTS ? next.slice(next.length - MAX_TOASTS) : next;
});
if (duration > 0) {
setTimeout(() => removeToast(id), duration);
}
return id;
}, [removeToast]);
return (
<ToastContext.Provider value={{ addToast, removeToast }}>
{children}
{/* aria-live region announces toasts to screen readers */}
<div className="toast-container" aria-live="polite" aria-atomic="false">
{toasts.map((toast) => (
<Toast key={toast.id} toast={toast} onRemove={removeToast} />
))}
</div>
</ToastContext.Provider>
);
}
export function useToast() {
const context = useContext(ToastContext);
if (!context) throw new Error('useToast must be used within ToastProvider');
return context;
}