forked from CredenceOrg/Credence-Frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathToastProvider.tsx
More file actions
209 lines (185 loc) · 6.98 KB
/
Copy pathToastProvider.tsx
File metadata and controls
209 lines (185 loc) · 6.98 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
import { createContext, useContext, useState, useCallback, useRef, type ReactNode } from 'react'
import { useSettings } from '../context/SettingsContext'
import { isWithinQuietHours, nowMinutesSinceMidnight } from '../lib/quietHours'
import Toast, { type ToastData, type ToastSeverity } from './Toast'
import './Toast.css'
const TIMEOUTS: Record<ToastSeverity, number> = {
info: 5000,
success: 5000,
warning: 8000,
danger: 0,
}
// Maximum number of toasts displayed simultaneously
const MAX_TOASTS = 3
interface ToastContextValue {
addToast: (severity: ToastSeverity, message: string) => void
removeToast: (id: string) => void
removeAllToasts: () => void
/** Broadcasts a visually-hidden message to screen readers. */
announce: (message: string, assertive?: boolean) => void
}
const ToastContext = createContext<ToastContextValue | null>(null)
export function useToast() {
const ctx = useContext(ToastContext)
if (!ctx) throw new Error('useToast must be used within ToastProvider')
return ctx
}
export default function ToastProvider({ children }: { children: ReactNode }) {
const {
toastsEnabled,
autoDismiss,
quietHoursEnabled,
quietHoursStart,
quietHoursEnd,
} = useSettings()
/**
* We use a ref to track the current settings to avoid recreating `addToast`
* on every setting change, which would cause unnecessary re-renders of consumers.
*
* Quiet hours are evaluated against `new Date()` at the moment `addToast`
* fires -- there's no need for a minute-tick subscription because addToast is
* the only call site. A user toggling settings mid-session picks up the next
* toast naturally.
*/
const settingsRef = useRef({
toastsEnabled,
autoDismiss,
quietHoursEnabled,
quietHoursStart,
quietHoursEnd,
})
settingsRef.current = {
toastsEnabled,
autoDismiss,
quietHoursEnabled,
quietHoursStart,
quietHoursEnd,
}
const [toasts, setToasts] = useState<ToastData[]>([])
const [announcement, setAnnouncement] = useState('')
const [assertiveAnnouncement, setAssertiveAnnouncement] = useState('')
const idCounter = useRef(0)
const timeoutsMap = useRef<Map<string, ReturnType<typeof setTimeout>>>(new Map())
const announce = useCallback((message: string, assertive = false) => {
if (assertive) {
setAssertiveAnnouncement(message)
// Clear after a short delay so the identical message can be re-announced later if needed
setTimeout(() => setAssertiveAnnouncement(''), 3000)
} else {
setAnnouncement(message)
setTimeout(() => setAnnouncement(''), 3000)
}
}, [])
const removeToast = useCallback((id: string) => {
setToasts((prev: ToastData[]) => prev.filter((t: ToastData) => t.id !== id))
const timerId = timeoutsMap.current.get(id)
if (timerId) {
clearTimeout(timerId)
timeoutsMap.current.delete(id)
}
}, [])
const removeAllToasts = useCallback(() => {
setToasts([])
timeoutsMap.current.forEach((timerId) => clearTimeout(timerId))
timeoutsMap.current.clear()
}, [])
const addToast = useCallback(
(severity: ToastSeverity, message: string) => {
const {
toastsEnabled,
autoDismiss,
quietHoursEnabled,
quietHoursStart,
quietHoursEnd,
} = settingsRef.current
// respect global toast enable setting
if (!toastsEnabled) return
// Quiet hours: silence non-critical toasts. Critical ("danger") toasts
// always surface so incidents and destructive failures are not lost.
// We also skip the aria-live announcement to keep screen readers quiet
// during the user's designated hours -- otherwise the visually-hidden
// polite/assertive regions would still announce.
if (
quietHoursEnabled &&
severity !== 'danger' &&
isWithinQuietHours(quietHoursStart, quietHoursEnd, nowMinutesSinceMidnight())
) {
return
}
// Screen readers often fail to read dynamically injected toasts if they contain nested live regions.
// We manually announce the text to the visually-hidden aria-live region to guarantee it is read.
announce(message, severity === 'danger')
// compute timeout: settings `autoDismiss` can override default TIMEOUTS
let timeout = TIMEOUTS[severity]
if (timeout > 0) {
try {
if (autoDismiss === 'off') {
timeout = 0
} else if (typeof autoDismiss === 'string' && autoDismiss.endsWith('s')) {
const seconds = Number(autoDismiss.replace('s', ''))
if (!Number.isNaN(seconds)) timeout = seconds * 1000
}
} catch {
// fallback to default
}
}
const id = String(++idCounter.current)
const newToast: ToastData = { id, severity, message, durationMs: timeout > 0 ? timeout : 0 }
// Enforce max toast limit: remove oldest if needed
setToasts((prev: ToastData[]) => {
const updated = [...prev]
if (updated.length >= MAX_TOASTS) {
const oldest = updated.shift()
if (oldest) {
const timerId = timeoutsMap.current.get(oldest.id)
if (timerId) {
clearTimeout(timerId)
timeoutsMap.current.delete(oldest.id)
}
}
}
updated.push(newToast)
return updated
})
if (timeout > 0) {
const timerId = setTimeout(() => removeToast(id), timeout)
timeoutsMap.current.set(id, timerId)
}
},
[removeToast, announce]
)
/** Toasts split by politeness: danger -> assertive; all others -> polite. */
const politeToasts = toasts.filter((t: ToastData) => t.severity !== 'danger')
const assertiveToasts = toasts.filter((t: ToastData) => t.severity === 'danger')
return (
<ToastContext.Provider value={{ addToast, removeToast, removeAllToasts, announce }}>
{children}
{/* Visually-hidden aria-live regions for reliable off-screen announcements (e.g. async statuses) */}
<div className="sr-only" aria-live="polite" aria-atomic="true">
{announcement}
</div>
<div className="sr-only" aria-live="assertive" aria-atomic="true">
{assertiveAnnouncement}
</div>
<div className="toast-container">
{toasts.length > 1 && (
<button type="button" className="toast-dismiss-all" onClick={removeAllToasts}>
Dismiss All
</button>
)}
{/* Polite region: info, success, warning -- announced when the screen reader is idle */}
<div role="region" aria-label="Notifications">
{politeToasts.map((t: ToastData) => (
<Toast key={t.id} toast={t} onDismiss={removeToast} />
))}
</div>
{/* Assertive region: danger -- interrupts and announces immediately */}
<div role="region" aria-label="Error notifications">
{assertiveToasts.map((t: ToastData) => (
<Toast key={t.id} toast={t} onDismiss={removeToast} />
))}
</div>
</div>
</ToastContext.Provider>
)
}