Repository navigation
Expand file tree
/
Copy pathindex.jsx
More file actions
95 lines (81 loc) · 2.33 KB
/
Copy pathindex.jsx
File metadata and controls
95 lines (81 loc) · 2.33 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
import React, {
useCallback,
useContext,
useEffect,
useRef,
useState,
} from 'react';
import CloseIcon from '@mui/icons-material/Close';
import Alert from '@mui/material/Alert';
import AlertTitle from '@mui/material/AlertTitle';
import Collapse from '@mui/material/Collapse';
import IconButton from '@mui/material/IconButton';
import { MainContext } from '../../contexts/MainContextProvider';
const getRandomTipIndex = (length) =>
length > 0 ? Math.floor(Math.random() * length) : 0;
const PasswordTips = () => {
const [state] = useContext(MainContext);
const { languageIndex, tips } = state;
const language = state.languages[languageIndex];
const [tipsOpen, setTipsOpen] = useState(tips);
const intervalId = useRef(null);
const [tipIndex, setTipIndex] = useState(() =>
getRandomTipIndex(language.passwordTips.length),
);
const currentTip =
language.passwordTips[tipIndex % language.passwordTips.length] ?? '';
/**
* Clear the active tip timer
*/
const clearTipInterval = useCallback(() => {
if (intervalId.current !== null) {
clearInterval(intervalId.current);
intervalId.current = null;
}
}, []);
/**
* Start rotating the current tip
* @param passwordTips The available tips for the current language
*/
const startTipRotation = useCallback(
(passwordTips) => {
clearTipInterval();
if (!passwordTips || passwordTips.length === 0) {
return;
}
intervalId.current = setInterval(() => {
setTipIndex(getRandomTipIndex(passwordTips.length));
}, 30000);
},
[clearTipInterval],
);
useEffect(() => {
if (!tips) {
clearTipInterval();
return clearTipInterval;
}
startTipRotation(language.passwordTips);
return clearTipInterval;
}, [clearTipInterval, language.passwordTips, startTipRotation, tips]);
const closeTips = () => {
setTipsOpen(false);
clearTipInterval();
};
return (
<Collapse in={tips && tipsOpen}>
<Alert
severity="info"
action={
<IconButton aria-label="close" color="inherit" onClick={closeTips}>
<CloseIcon fontSize="inherit" />
</IconButton>
}
sx={{ mb: 2 }}
>
<AlertTitle>{language.tips}</AlertTitle>
{currentTip}
</Alert>
</Collapse>
);
};
export default PasswordTips;