-
-
Notifications
You must be signed in to change notification settings - Fork 31.8k
/
Snackbar.js
419 lines (384 loc) · 12.2 KB
/
Snackbar.js
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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
import * as React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { unstable_composeClasses as composeClasses } from '@mui/base';
import ClickAwayListener from '@mui/base/ClickAwayListener';
import styled from '../styles/styled';
import useTheme from '../styles/useTheme';
import useThemeProps from '../styles/useThemeProps';
import useEventCallback from '../utils/useEventCallback';
import capitalize from '../utils/capitalize';
import Grow from '../Grow';
import SnackbarContent from '../SnackbarContent';
import { getSnackbarUtilityClass } from './snackbarClasses';
const useUtilityClasses = (ownerState) => {
const { classes, anchorOrigin } = ownerState;
const slots = {
root: [
'root',
`anchorOrigin${capitalize(anchorOrigin.vertical)}${capitalize(anchorOrigin.horizontal)}`,
],
};
return composeClasses(slots, getSnackbarUtilityClass, classes);
};
const SnackbarRoot = styled('div', {
name: 'MuiSnackbar',
slot: 'Root',
overridesResolver: (props, styles) => {
const { ownerState } = props;
return [
styles.root,
styles[
`anchorOrigin${capitalize(ownerState.anchorOrigin.vertical)}${capitalize(
ownerState.anchorOrigin.horizontal,
)}`
],
];
},
})(({ theme, ownerState }) => {
const center = {
left: '50%',
right: 'auto',
transform: 'translateX(-50%)',
};
return {
zIndex: (theme.vars || theme).zIndex.snackbar,
position: 'fixed',
display: 'flex',
left: 8,
right: 8,
justifyContent: 'center',
alignItems: 'center',
...(ownerState.anchorOrigin.vertical === 'top' ? { top: 8 } : { bottom: 8 }),
...(ownerState.anchorOrigin.horizontal === 'left' && { justifyContent: 'flex-start' }),
...(ownerState.anchorOrigin.horizontal === 'right' && { justifyContent: 'flex-end' }),
[theme.breakpoints.up('sm')]: {
...(ownerState.anchorOrigin.vertical === 'top' ? { top: 24 } : { bottom: 24 }),
...(ownerState.anchorOrigin.horizontal === 'center' && center),
...(ownerState.anchorOrigin.horizontal === 'left' && {
left: 24,
right: 'auto',
}),
...(ownerState.anchorOrigin.horizontal === 'right' && {
right: 24,
left: 'auto',
}),
},
};
});
const Snackbar = React.forwardRef(function Snackbar(inProps, ref) {
const props = useThemeProps({ props: inProps, name: 'MuiSnackbar' });
const theme = useTheme();
const defaultTransitionDuration = {
enter: theme.transitions.duration.enteringScreen,
exit: theme.transitions.duration.leavingScreen,
};
const {
action,
anchorOrigin: { vertical, horizontal } = { vertical: 'bottom', horizontal: 'left' },
autoHideDuration = null,
children,
className,
ClickAwayListenerProps,
ContentProps,
disableWindowBlurListener = false,
message,
onBlur,
onClose,
onFocus,
onMouseEnter,
onMouseLeave,
open,
resumeHideDuration,
TransitionComponent = Grow,
transitionDuration = defaultTransitionDuration,
TransitionProps: { onEnter, onExited, ...TransitionProps } = {},
...other
} = props;
const ownerState = { ...props, anchorOrigin: { vertical, horizontal } };
const classes = useUtilityClasses(ownerState);
const timerAutoHide = React.useRef();
const [exited, setExited] = React.useState(true);
const handleClose = useEventCallback((...args) => {
if (onClose) {
onClose(...args);
}
});
const setAutoHideTimer = useEventCallback((autoHideDurationParam) => {
if (!onClose || autoHideDurationParam == null) {
return;
}
clearTimeout(timerAutoHide.current);
timerAutoHide.current = setTimeout(() => {
handleClose(null, 'timeout');
}, autoHideDurationParam);
});
React.useEffect(() => {
if (open) {
setAutoHideTimer(autoHideDuration);
}
return () => {
clearTimeout(timerAutoHide.current);
};
}, [open, autoHideDuration, setAutoHideTimer]);
// Pause the timer when the user is interacting with the Snackbar
// or when the user hide the window.
const handlePause = () => {
clearTimeout(timerAutoHide.current);
};
// Restart the timer when the user is no longer interacting with the Snackbar
// or when the window is shown back.
const handleResume = React.useCallback(() => {
if (autoHideDuration != null) {
setAutoHideTimer(resumeHideDuration != null ? resumeHideDuration : autoHideDuration * 0.5);
}
}, [autoHideDuration, resumeHideDuration, setAutoHideTimer]);
const handleFocus = (event) => {
if (onFocus) {
onFocus(event);
}
handlePause();
};
const handleMouseEnter = (event) => {
if (onMouseEnter) {
onMouseEnter(event);
}
handlePause();
};
const handleBlur = (event) => {
if (onBlur) {
onBlur(event);
}
handleResume();
};
const handleMouseLeave = (event) => {
if (onMouseLeave) {
onMouseLeave(event);
}
handleResume();
};
const handleClickAway = (event) => {
if (onClose) {
onClose(event, 'clickaway');
}
};
const handleExited = (node) => {
setExited(true);
if (onExited) {
onExited(node);
}
};
const handleEnter = (node, isAppearing) => {
setExited(false);
if (onEnter) {
onEnter(node, isAppearing);
}
};
React.useEffect(() => {
// TODO: window global should be refactored here
if (!disableWindowBlurListener && open) {
window.addEventListener('focus', handleResume);
window.addEventListener('blur', handlePause);
return () => {
window.removeEventListener('focus', handleResume);
window.removeEventListener('blur', handlePause);
};
}
return undefined;
}, [disableWindowBlurListener, handleResume, open]);
React.useEffect(() => {
if (!open) {
return undefined;
}
/**
* @param {KeyboardEvent} nativeEvent
*/
function handleKeyDown(nativeEvent) {
if (!nativeEvent.defaultPrevented) {
// IE11, Edge (prior to using Bink?) use 'Esc'
if (nativeEvent.key === 'Escape' || nativeEvent.key === 'Esc') {
// not calling `preventDefault` since we don't know if people may ignore this event e.g. a permanently open snackbar
if (onClose) {
onClose(nativeEvent, 'escapeKeyDown');
}
}
}
}
document.addEventListener('keydown', handleKeyDown);
return () => {
document.removeEventListener('keydown', handleKeyDown);
};
}, [exited, open, onClose]);
// So we only render active snackbars.
if (!open && exited) {
return null;
}
return (
<ClickAwayListener onClickAway={handleClickAway} {...ClickAwayListenerProps}>
<SnackbarRoot
className={clsx(classes.root, className)}
onBlur={handleBlur}
onFocus={handleFocus}
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
ownerState={ownerState}
ref={ref}
// ClickAwayListener adds an `onClick` prop which results in the alert not being announced.
// See https://github.com/mui/material-ui/issues/29080
role="presentation"
{...other}
>
<TransitionComponent
appear
in={open}
timeout={transitionDuration}
direction={vertical === 'top' ? 'down' : 'up'}
onEnter={handleEnter}
onExited={handleExited}
{...TransitionProps}
>
{children || <SnackbarContent message={message} action={action} {...ContentProps} />}
</TransitionComponent>
</SnackbarRoot>
</ClickAwayListener>
);
});
Snackbar.propTypes /* remove-proptypes */ = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the d.ts file and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* The action to display. It renders after the message, at the end of the snackbar.
*/
action: PropTypes.node,
/**
* The anchor of the `Snackbar`.
* On smaller screens, the component grows to occupy all the available width,
* the horizontal alignment is ignored.
* @default { vertical: 'bottom', horizontal: 'left' }
*/
anchorOrigin: PropTypes.shape({
horizontal: PropTypes.oneOf(['center', 'left', 'right']).isRequired,
vertical: PropTypes.oneOf(['bottom', 'top']).isRequired,
}),
/**
* The number of milliseconds to wait before automatically calling the
* `onClose` function. `onClose` should then set the state of the `open`
* prop to hide the Snackbar. This behavior is disabled by default with
* the `null` value.
* @default null
*/
autoHideDuration: PropTypes.number,
/**
* Replace the `SnackbarContent` component.
*/
children: PropTypes.element,
/**
* Override or extend the styles applied to the component.
*/
classes: PropTypes.object,
/**
* @ignore
*/
className: PropTypes.string,
/**
* Props applied to the `ClickAwayListener` element.
*/
ClickAwayListenerProps: PropTypes.object,
/**
* Props applied to the [`SnackbarContent`](/material-ui/api/snackbar-content/) element.
*/
ContentProps: PropTypes.object,
/**
* If `true`, the `autoHideDuration` timer will expire even if the window is not focused.
* @default false
*/
disableWindowBlurListener: PropTypes.bool,
/**
* When displaying multiple consecutive Snackbars from a parent rendering a single
* <Snackbar/>, add the key prop to ensure independent treatment of each message.
* e.g. <Snackbar key={message} />, otherwise, the message may update-in-place and
* features such as autoHideDuration may be canceled.
*/
key: () => null,
/**
* The message to display.
*/
message: PropTypes.node,
/**
* @ignore
*/
onBlur: PropTypes.func,
/**
* Callback fired when the component requests to be closed.
* Typically `onClose` is used to set state in the parent component,
* which is used to control the `Snackbar` `open` prop.
* The `reason` parameter can optionally be used to control the response to `onClose`,
* for example ignoring `clickaway`.
*
* @param {React.SyntheticEvent<any> | Event} event The event source of the callback.
* @param {string} reason Can be: `"timeout"` (`autoHideDuration` expired), `"clickaway"`, or `"escapeKeyDown"`.
*/
onClose: PropTypes.func,
/**
* @ignore
*/
onFocus: PropTypes.func,
/**
* @ignore
*/
onMouseEnter: PropTypes.func,
/**
* @ignore
*/
onMouseLeave: PropTypes.func,
/**
* If `true`, the component is shown.
*/
open: PropTypes.bool,
/**
* The number of milliseconds to wait before dismissing after user interaction.
* If `autoHideDuration` prop isn't specified, it does nothing.
* If `autoHideDuration` prop is specified but `resumeHideDuration` isn't,
* we default to `autoHideDuration / 2` ms.
*/
resumeHideDuration: PropTypes.number,
/**
* The system prop that allows defining system overrides as well as additional CSS styles.
*/
sx: PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])),
PropTypes.func,
PropTypes.object,
]),
/**
* The component used for the transition.
* [Follow this guide](/material-ui/transitions/#transitioncomponent-prop) to learn more about the requirements for this component.
* @default Grow
*/
TransitionComponent: PropTypes.elementType,
/**
* The duration for the transition, in milliseconds.
* You may specify a single timeout for all transitions, or individually with an object.
* @default {
* enter: theme.transitions.duration.enteringScreen,
* exit: theme.transitions.duration.leavingScreen,
* }
*/
transitionDuration: PropTypes.oneOfType([
PropTypes.number,
PropTypes.shape({
appear: PropTypes.number,
enter: PropTypes.number,
exit: PropTypes.number,
}),
]),
/**
* Props applied to the transition element.
* By default, the element is based on this [`Transition`](http://reactcommunity.org/react-transition-group/transition/) component.
* @default {}
*/
TransitionProps: PropTypes.object,
};
export default Snackbar;