-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnotificationsList.ts
74 lines (64 loc) · 2.14 KB
/
notificationsList.ts
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 { createSlice, nanoid, PayloadAction } from "@reduxjs/toolkit";
import { combineEpics, Epic } from "redux-observable";
import { of, EMPTY } from "rxjs";
import { filter, mergeMap, delay, map } from "rxjs/operators";
export interface NotificationData {
message: string | string[];
variant: "success" | "danger" | "warning" | "info";
// If no id is provided, one will be generated.
id?: string;
options?: Partial<{
/** Autoclose delay in ms. 0 disables autoclose. Defaults to 6000 */
delay: number;
}>;
}
interface NotificationWithId extends NotificationData {
id: string;
}
export interface NotificationsListState {
notifications: NotificationWithId[];
}
const DEFAULT_AUTOCLOSE_DELAY = 6000 as const;
export const notificationsListSlice = createSlice({
name: "notificationsList",
initialState: { notifications: [] } as NotificationsListState,
reducers: {
addNotification(_state, _action: PayloadAction<NotificationData>): void {},
_addNotificationWithId(
state,
action: PayloadAction<NotificationWithId>
): void {
state.notifications.push(action.payload);
},
removeNotification(state, action: PayloadAction<string>): void {
state.notifications = state.notifications.filter(
(n) => n.id !== action.payload
);
},
},
});
export const { addNotification, removeNotification } =
notificationsListSlice.actions;
const { _addNotificationWithId } = notificationsListSlice.actions;
const addNotificationEpic: Epic = (action$) =>
action$.pipe(
filter(addNotification.match),
map((action) => _addNotificationWithId({ ...action.payload, id: nanoid() }))
);
const addNotificationWithIdEpic: Epic = (action$) =>
action$.pipe(
filter(_addNotificationWithId.match),
mergeMap((action) => {
const closeDelay = action.payload.options?.delay;
if (closeDelay !== undefined && closeDelay === 0) {
return EMPTY;
}
return of(removeNotification(action.payload.id)).pipe(
delay(closeDelay ?? DEFAULT_AUTOCLOSE_DELAY)
);
})
);
export const notificationsListEpic = combineEpics(
addNotificationEpic,
addNotificationWithIdEpic
);