forked from Creditra/Creditra-Frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNotificationContext.tsx
More file actions
275 lines (237 loc) · 8.52 KB
/
Copy pathNotificationContext.tsx
File metadata and controls
275 lines (237 loc) · 8.52 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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
import {
createContext,
useCallback,
useContext,
useEffect,
useRef,
useState,
} from 'react';
import type {
BannerAlert,
Notification,
NotificationCategory,
NotificationPreferences,
NotificationType,
Toast,
} from '../types/notification';
// ─── Types ────────────────────────────────────────────────────────────────────
interface AddToastOptions {
type: NotificationType;
category?: NotificationCategory;
title: string;
message: string;
duration?: number;
persistent?: boolean;
action?: { label: string; onClick: () => void };
/** If true, also saves to notification history */
saveToHistory?: boolean;
}
interface NotificationContextValue {
// Toasts
toasts: Toast[];
addToast: (opts: AddToastOptions) => string;
dismissToast: (id: string) => void;
// Banners
banners: BannerAlert[];
addBanner: (banner: Omit<BannerAlert, 'id'>) => string;
dismissBanner: (id: string) => void;
// Notification center
notifications: Notification[];
unreadCount: number;
markAsRead: (id: string) => void;
markAllAsRead: () => void;
undoRead: (ids: string[]) => void;
clearAll: () => void;
restoreNotifications: (notifications: Notification[]) => void;
filterByCategory: (category: NotificationCategory | 'all') => Notification[];
// Preferences
preferences: NotificationPreferences;
updatePreferences: (prefs: Partial<NotificationPreferences>) => void;
// Panel
isPanelOpen: boolean;
openPanel: () => void;
closePanel: () => void;
}
// ─── Defaults ─────────────────────────────────────────────────────────────────
const DEFAULT_PREFS: NotificationPreferences = {
transaction: true,
credit_line: true,
risk_score: true,
rate_change: true,
system: true,
};
const STORAGE_KEY = 'creditra_notifications';
const PREFS_KEY = 'creditra_notification_prefs';
// ─── Context ──────────────────────────────────────────────────────────────────
const NotificationContext = createContext<NotificationContextValue | null>(null);
/**
* App-wide notification provider.
*
* Owns three queues:
* - `toasts` — transient, auto-dismissed after `duration` ms unless
* `persistent` is set
* - `banners` — page-level alerts that persist until dismissed
* - `notifications` — durable inbox, persisted to `localStorage` and
* capped at 100 entries to bound storage growth
*
* Per-category mute preferences are also persisted; a muted category
* causes `addToast` to return early with an empty id so callers can
* fire-and-forget without conditionals.
*
* Mount this once, after `WalletProvider`, near the top of the tree.
*/
export function NotificationProvider({ children }: { children: React.ReactNode }) {
const [toasts, setToasts] = useState<Toast[]>([]);
const [banners, setBanners] = useState<BannerAlert[]>([]);
const [notifications, setNotifications] = useState<Notification[]>(() => {
try {
const stored = localStorage.getItem(STORAGE_KEY);
return stored ? JSON.parse(stored) : [];
} catch {
return [];
}
});
const [preferences, setPreferences] = useState<NotificationPreferences>(() => {
try {
const stored = localStorage.getItem(PREFS_KEY);
return stored ? { ...DEFAULT_PREFS, ...JSON.parse(stored) } : DEFAULT_PREFS;
} catch {
return DEFAULT_PREFS;
}
});
const [isPanelOpen, setIsPanelOpen] = useState(false);
const timersRef = useRef<Map<string, ReturnType<typeof setTimeout>>>(new Map());
// Persist notifications
useEffect(() => {
localStorage.setItem(STORAGE_KEY, JSON.stringify(notifications.slice(0, 100)));
}, [notifications]);
// Persist preferences
useEffect(() => {
localStorage.setItem(PREFS_KEY, JSON.stringify(preferences));
}, [preferences]);
const genId = () => `${Date.now()}-${Math.random().toString(36).slice(2, 7)}`;
// ─── Toasts ────────────────────────────────────────────────────────────────
const dismissToast = useCallback((id: string) => {
setToasts(prev => prev.filter(t => t.id !== id));
const timer = timersRef.current.get(id);
if (timer) {
clearTimeout(timer);
timersRef.current.delete(id);
}
}, []);
const addToast = useCallback((opts: AddToastOptions): string => {
const category = opts.category ?? 'system';
if (!preferences[category]) return '';
const id = genId();
const toast: Toast = {
id,
type: opts.type,
category,
title: opts.title,
message: opts.message,
timestamp: new Date().toISOString(),
duration: opts.duration ?? 5500,
persistent: opts.persistent ?? false,
action: opts.action,
};
setToasts(prev => [toast, ...prev].slice(0, 5)); // max 5 stacked
if (!toast.persistent) {
const timer = setTimeout(() => dismissToast(id), toast.duration);
timersRef.current.set(id, timer);
}
if (opts.saveToHistory !== false) {
const notification: Notification = {
id,
type: opts.type,
category,
title: opts.title,
message: opts.message,
timestamp: new Date().toISOString(),
read: false,
action: opts.action,
};
setNotifications(prev => [notification, ...prev].slice(0, 100));
}
return id;
}, [preferences, dismissToast]);
// ─── Banners ───────────────────────────────────────────────────────────────
const addBanner = useCallback((banner: Omit<BannerAlert, 'id'>): string => {
const id = genId();
setBanners(prev => [...prev, { ...banner, id }]);
return id;
}, []);
const dismissBanner = useCallback((id: string) => {
setBanners(prev => prev.filter(b => b.id !== id));
}, []);
// ─── Notification center ───────────────────────────────────────────────────
const unreadCount = notifications.filter(n => !n.read).length;
const markAsRead = useCallback((id: string) => {
setNotifications(prev =>
prev.map(n => (n.id === id ? { ...n, read: true } : n))
);
}, []);
const markAllAsRead = useCallback(() => {
setNotifications(prev => prev.map(n => ({ ...n, read: true })));
}, []);
const undoRead = useCallback((ids: string[]) => {
setNotifications(prev =>
prev.map(n => (ids.includes(n.id) ? { ...n, read: false } : n))
);
}, []);
const clearAll = useCallback(() => {
setNotifications([]);
}, []);
const restoreNotifications = useCallback((toRestore: Notification[]) => {
setNotifications(toRestore);
}, []);
const filterByCategory = useCallback(
(category: NotificationCategory | 'all') =>
category === 'all'
? notifications
: notifications.filter(n => n.category === category),
[notifications]
);
const updatePreferences = useCallback((prefs: Partial<NotificationPreferences>) => {
setPreferences(prev => ({ ...prev, ...prefs }));
}, []);
return (
<NotificationContext.Provider
value={{
toasts,
addToast,
dismissToast,
banners,
addBanner,
dismissBanner,
notifications,
unreadCount,
markAsRead,
markAllAsRead,
undoRead,
clearAll,
restoreNotifications,
filterByCategory,
preferences,
updatePreferences,
isPanelOpen,
openPanel: () => setIsPanelOpen(true),
closePanel: () => setIsPanelOpen(false),
}}
>
{children}
</NotificationContext.Provider>
);
}
/**
* Read the notification context inside a `NotificationProvider`
* subtree.
*
* Throws on misuse rather than returning a possibly-undefined value, so
* a misplaced consumer surfaces at the call site instead of leaking a
* confusing "cannot read property of undefined" downstream.
*/
export function useNotifications() {
const ctx = useContext(NotificationContext);
if (!ctx) throw new Error('useNotifications must be used within NotificationProvider');
return ctx;
}