-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
Expand file tree
/
Copy pathNotification.tsx
More file actions
260 lines (239 loc) · 7.98 KB
/
Notification.tsx
File metadata and controls
260 lines (239 loc) · 7.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
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
import * as React from 'react';
import {
type ComponentsOverrides,
styled,
type Theme,
useThemeProps,
} from '@mui/material/styles';
import { useState, useEffect, useCallback } from 'react';
import {
Button,
Snackbar,
type SnackbarProps,
SnackbarOrigin,
} from '@mui/material';
import clsx from 'clsx';
import {
CloseNotificationContext,
type NotificationPayload,
undoableEventEmitter,
useNotificationContext,
useTakeUndoableMutation,
useTranslate,
} from 'ra-core';
const defaultAnchorOrigin: SnackbarOrigin = {
vertical: 'bottom',
horizontal: 'center',
};
/**
* Provides a way to show a notification.
* @see useNotify
*
* @example <caption>Basic usage</caption>
* <Notification />
*
* @param props The component props
* @param {string} props.type The notification type. Defaults to 'info'.
* @param {number} props.autoHideDuration Duration in milliseconds to wait until hiding a given notification. Defaults to 4000.
* @param {boolean} props.multiLine Set it to `true` if the notification message should be shown in more than one line.
*/
export const Notification = (inProps: NotificationProps) => {
const props = useThemeProps({
props: inProps,
name: PREFIX,
});
const {
className,
type = 'info',
autoHideDuration = 4000,
multiLine = false,
anchorOrigin = defaultAnchorOrigin,
...rest
} = props;
const { notifications, takeNotification } = useNotificationContext();
const takeMutation = useTakeUndoableMutation();
const [open, setOpen] = useState(false);
const [currentNotification, setCurrentNotification] = React.useState<
NotificationPayload | undefined
>(undefined);
const translate = useTranslate();
useEffect(() => {
if (notifications.length && !currentNotification) {
// Set a new snack when we don't have an active one
const notification = takeNotification();
if (notification) {
setCurrentNotification(notification);
setOpen(true);
}
}
if (currentNotification) {
const beforeunload = (e: BeforeUnloadEvent) => {
e.preventDefault();
const confirmationMessage = '';
e.returnValue = confirmationMessage;
return confirmationMessage;
};
if (currentNotification?.notificationOptions?.undoable) {
window.addEventListener('beforeunload', beforeunload);
return () => {
window.removeEventListener('beforeunload', beforeunload);
};
}
}
}, [notifications, currentNotification, open, takeNotification]);
const handleRequestClose = useCallback(() => {
setOpen(false);
}, [setOpen]);
const handleExited = useCallback(() => {
if (
currentNotification &&
currentNotification.notificationOptions?.undoable
) {
const mutation = takeMutation();
if (mutation) {
mutation({ isUndo: false });
} else {
// FIXME kept for BC: remove in v6
undoableEventEmitter.emit('end', { isUndo: false });
}
}
setCurrentNotification(undefined);
}, [currentNotification, takeMutation]);
const handleUndo = useCallback(() => {
const mutation = takeMutation();
if (mutation) {
mutation({ isUndo: true });
} else {
// FIXME kept for BC: remove in v6
undoableEventEmitter.emit('end', { isUndo: true });
}
setOpen(false);
}, [takeMutation]);
if (!currentNotification) return null;
const {
message,
type: typeFromMessage,
notificationOptions,
} = currentNotification;
const {
autoHideDuration: autoHideDurationFromMessage,
messageArgs,
multiLine: multilineFromMessage,
undoable,
...options
} = notificationOptions || {};
return (
<CloseNotificationContext.Provider value={handleRequestClose}>
<StyledSnackbar
className={className}
open={open}
message={
message &&
typeof message === 'string' &&
translate(message, messageArgs)
}
autoHideDuration={
// Only apply the default autoHideDuration when autoHideDurationFromMessage is undefined
// as 0 and null are valid values
autoHideDurationFromMessage === undefined
? autoHideDuration
: autoHideDurationFromMessage ?? undefined
}
disableWindowBlurListener={undoable}
TransitionProps={{ onExited: handleExited }}
onClose={handleRequestClose}
ContentProps={{
className: clsx(
NotificationClasses[typeFromMessage || type],
{
[NotificationClasses.multiLine]:
multilineFromMessage || multiLine,
}
),
}}
action={
undoable ? (
<Button
color="primary"
className={NotificationClasses.undo}
size="small"
onClick={handleUndo}
>
<>{translate('ra.action.undo')}</>
</Button>
) : null
}
anchorOrigin={anchorOrigin}
{...rest}
{...options}
>
{message &&
typeof message !== 'string' &&
React.isValidElement(message)
? message
: undefined}
</StyledSnackbar>
</CloseNotificationContext.Provider>
);
};
const PREFIX = 'RaNotification';
export const NotificationClasses = {
success: `${PREFIX}-success`,
error: `${PREFIX}-error`,
warning: `${PREFIX}-warning`,
undo: `${PREFIX}-undo`,
multiLine: `${PREFIX}-multiLine`,
};
const StyledSnackbar = styled(Snackbar, {
name: PREFIX,
overridesResolver: (props, styles) => styles.root,
})(({ theme, type }: NotificationProps & { theme?: Theme }) => ({
[`& .${NotificationClasses.success}`]: {
backgroundColor: theme?.palette.success.main,
color: theme?.palette.success.contrastText,
},
[`& .${NotificationClasses.error}`]: {
backgroundColor: theme?.palette.error.main,
color: theme?.palette.error.contrastText,
},
[`& .${NotificationClasses.warning}`]: {
backgroundColor: theme?.palette.warning.main,
color: theme?.palette.warning.contrastText,
},
[`& .${NotificationClasses.undo}`]: {
color:
type === 'success'
? theme?.palette.success.contrastText
: theme?.palette.primary.light,
},
[`& .${NotificationClasses.multiLine}`]: {
whiteSpace: 'pre-wrap',
},
}));
export interface NotificationProps extends Omit<SnackbarProps, 'open'> {
type?: string;
autoHideDuration?: number;
multiLine?: boolean;
}
declare module '@mui/material/styles' {
interface ComponentNameToClassKey {
RaNotification:
| 'root'
| 'success'
| 'error'
| 'warning'
| 'undo'
| 'multiLine';
}
interface ComponentsPropsList {
RaNotification: Partial<NotificationProps>;
}
interface Components {
RaNotification?: {
defaultProps?: ComponentsPropsList['RaNotification'];
styleOverrides?: ComponentsOverrides<
Omit<Theme, 'components'>
>['RaNotification'];
};
}
}