forked from grafana/grafana
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathTemporaryAlert.tsx
74 lines (64 loc) · 1.6 KB
/
TemporaryAlert.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
import { css } from '@emotion/css';
import { useEffect, useState } from 'react';
import { GrafanaTheme2 } from '@grafana/data';
import { Alert, AlertVariant, useTheme2 } from '@grafana/ui';
enum AlertTimeout {
Error = 7000,
Info = 3000,
Success = 3000,
Warning = 5000,
}
const getStyle = (theme: GrafanaTheme2) => {
return css({
position: 'absolute',
zIndex: theme.zIndex.portal,
top: 0,
right: 10,
});
};
const timeoutMap = {
['error']: AlertTimeout.Error,
['info']: AlertTimeout.Info,
['success']: AlertTimeout.Success,
['warning']: AlertTimeout.Warning,
};
type AlertProps = {
// Severity of the alert. Controls the style of the alert (e.g., background color)
severity: AlertVariant;
// Displayed message. If set to empty string, the alert is not displayed
text: string;
};
export const TemporaryAlert = (props: AlertProps) => {
const style = getStyle(useTheme2());
const [visible, setVisible] = useState(false);
const [timer, setTimer] = useState<NodeJS.Timeout>();
useEffect(() => {
return () => {
if (timer) {
clearTimeout(timer);
}
};
}, [timer]);
useEffect(() => {
if (props.text !== '') {
setVisible(true);
const timer = setTimeout(() => {
setVisible(false);
}, timeoutMap[props.severity]);
setTimer(timer);
}
}, [props.severity, props.text]);
return (
<>
{visible && (
<Alert
className={style}
elevated={true}
onRemove={() => setVisible(false)}
severity={props.severity}
title={props.text}
/>
)}
</>
);
};