-
-
Notifications
You must be signed in to change notification settings - Fork 32.5k
Expand file tree
/
Copy pathSnackbarHideDuration.tsx
More file actions
83 lines (82 loc) · 2.42 KB
/
Copy pathSnackbarHideDuration.tsx
File metadata and controls
83 lines (82 loc) · 2.42 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
import * as React from 'react';
import Button from '@mui/joy/Button';
import FormControl from '@mui/joy/FormControl';
import FormLabel from '@mui/joy/FormLabel';
import Input from '@mui/joy/Input';
import Stack from '@mui/joy/Stack';
import Snackbar from '@mui/joy/Snackbar';
export default function SnackbarHideDuration() {
const [open, setOpen] = React.useState(false);
const [duration, setDuration] = React.useState<undefined | number>();
const [left, setLeft] = React.useState<undefined | number>();
const timer = React.useRef<undefined | number>();
const countdown = () => {
timer.current = window.setInterval(() => {
setLeft((prev) => (prev === undefined ? prev : Math.max(0, prev - 100)));
}, 100);
};
React.useEffect(() => {
if (open && duration !== undefined && duration > 0) {
setLeft(duration);
countdown();
} else {
window.clearInterval(timer.current);
}
}, [open, duration]);
const handlePause = () => {
window.clearInterval(timer.current);
};
const handleResume = () => {
countdown();
};
return (
<div>
<Stack spacing={2} direction="row" alignItems="center">
<FormControl disabled={open} sx={{ display: 'grid', columnGap: 1 }}>
<FormLabel sx={{ gridColumn: 'span 2' }}>
Auto Hide Duration (ms)
</FormLabel>
<Input
type="number"
slotProps={{ input: { step: 100 } }}
value={duration || ''}
onChange={(event) => {
setDuration(event.target.valueAsNumber || undefined);
}}
/>
<Button
disabled={open}
variant="outlined"
color="neutral"
onClick={() => {
setOpen(true);
}}
>
Show snackbar
</Button>
</FormControl>
</Stack>
<Snackbar
variant="solid"
color="danger"
autoHideDuration={duration}
resumeHideDuration={left}
onMouseEnter={handlePause}
onMouseLeave={handleResume}
onFocus={handlePause}
onBlur={handleResume}
onUnmount={() => setLeft(undefined)}
open={open}
onClose={() => {
setOpen(false);
}}
>
This snackbar will{' '}
{left !== undefined
? `disappear in ${left}ms`
: `not disappear until you click away`}
.
</Snackbar>
</div>
);
}