-
-
Notifications
You must be signed in to change notification settings - Fork 319
/
Copy pathNotificationsProvider.tsx
202 lines (178 loc) · 5.33 KB
/
NotificationsProvider.tsx
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
import * as React from 'react';
import {
Alert,
Badge,
Button,
CloseReason,
IconButton,
Snackbar,
SnackbarCloseReason,
SnackbarContent,
SnackbarProps,
} from '@mui/material';
import CloseIcon from '@mui/icons-material/Close';
import { useNonNullableContext } from '@toolpad/utils/react';
import useSlotProps from '@mui/utils/useSlotProps';
import { NotificationsContext } from './NotificationsContext';
import type {
CloseNotification,
ShowNotification,
ShowNotificationOptions,
} from './useNotifications';
const closeText = 'Close';
export interface NotificationsProviderSlotProps {
snackbar: SnackbarProps;
}
export interface NotificationsProviderSlots {
/**
* The component that renders the snackbar.
* @default Snackbar
*/
snackbar: React.ElementType;
}
const RootPropsContext = React.createContext<NotificationsProviderProps | null>(null);
interface NotificationProps {
notificationKey: string;
badge: string | null;
open: boolean;
message: React.ReactNode;
options: ShowNotificationOptions;
}
function Notification({ notificationKey, open, message, options, badge }: NotificationProps) {
const { close } = useNonNullableContext(NotificationsContext);
const { severity, actionText, onAction, autoHideDuration } = options;
const handleClose = React.useCallback(
(event: unknown, reason?: CloseReason | SnackbarCloseReason) => {
if (reason === 'clickaway') {
return;
}
close(notificationKey);
},
[notificationKey, close],
);
const action = (
<React.Fragment>
{onAction ? (
<Button color="inherit" size="small" onClick={onAction}>
{actionText ?? 'Action'}
</Button>
) : null}
<IconButton
size="small"
aria-label={closeText}
title={closeText}
color="inherit"
onClick={handleClose}
>
<CloseIcon fontSize="small" />
</IconButton>
</React.Fragment>
);
const props = React.useContext(RootPropsContext);
const SnackbarComponent = props?.slots?.snackbar ?? Snackbar;
const snackbarSlotProps = useSlotProps({
elementType: SnackbarComponent,
ownerState: props,
externalSlotProps: props?.slotProps?.snackbar,
additionalProps: {
open,
autoHideDuration,
onClose: handleClose,
action,
},
});
return (
<SnackbarComponent key={notificationKey} {...snackbarSlotProps}>
<Badge badgeContent={badge} color="primary" sx={{ width: '100%' }}>
{severity ? (
<Alert severity={severity} sx={{ width: '100%' }} action={action}>
{message}
</Alert>
) : (
<SnackbarContent message={message} action={action} />
)}
</Badge>
</SnackbarComponent>
);
}
interface NotificationQueueEntry {
notificationKey: string;
options: ShowNotificationOptions;
open: boolean;
message: React.ReactNode;
}
interface NotificationsState {
queue: NotificationQueueEntry[];
}
interface NotificationsProps {
state: NotificationsState;
}
function Notifications({ state }: NotificationsProps) {
const currentNotification = state.queue[0] ?? null;
return currentNotification ? (
<Notification
{...currentNotification}
badge={state.queue.length > 1 ? String(state.queue.length) : null}
/>
) : null;
}
export interface NotificationsProviderProps {
children?: React.ReactNode;
// eslint-disable-next-line react/no-unused-prop-types
slots?: Partial<NotificationsProviderSlots>;
// eslint-disable-next-line react/no-unused-prop-types
slotProps?: Partial<NotificationsProviderSlotProps>;
}
let nextId = 0;
const generateId = () => {
const id = nextId;
nextId += 1;
return id;
};
/**
* Provider for Notifications. The subtree of this component can use the `useNotifications` hook to
* access the notifications API. The notifications are shown in the same order they are requested.
*
* Demos:
*
* - [Sign-in Page](https://mui.com/toolpad/core/react-sign-in-page/)
* - [useNotifications](https://mui.com/toolpad/core/react-use-notifications/)
*
* API:
*
* - [NotificationsProvider API](https://mui.com/toolpad/core/api/notifications-provider)
*/
function NotificationsProvider(props: NotificationsProviderProps) {
const { children } = props;
const [state, setState] = React.useState<NotificationsState>({ queue: [] });
const show = React.useCallback<ShowNotification>((message, options = {}) => {
const notificationKey = options.key ?? `::toolpad-internal::notification::${generateId()}`;
setState((prev) => {
if (prev.queue.some((n) => n.notificationKey === notificationKey)) {
// deduplicate by key
return prev;
}
return {
...prev,
queue: [...prev.queue, { message, options, notificationKey, open: true }],
};
});
return notificationKey;
}, []);
const close = React.useCallback<CloseNotification>((key) => {
setState((prev) => ({
...prev,
queue: prev.queue.filter((n) => n.notificationKey !== key),
}));
}, []);
const contextValue = React.useMemo(() => ({ show, close }), [show, close]);
return (
<RootPropsContext.Provider value={props}>
<NotificationsContext.Provider value={contextValue}>
{children}
<Notifications state={state} />
</NotificationsContext.Provider>
</RootPropsContext.Provider>
);
}
export { NotificationsProvider };