2020-11-05 21:26:43 +00:00
|
|
|
import React, {
|
|
|
|
useState,
|
|
|
|
createContext,
|
|
|
|
ReactNode,
|
|
|
|
useContext,
|
|
|
|
useEffect,
|
|
|
|
} from "react";
|
2020-09-15 19:44:28 +00:00
|
|
|
import { AlertType, AlertPanel } from "./AlertPanel";
|
2020-09-01 14:51:59 +00:00
|
|
|
import { AlertVariant } from "@patternfly/react-core";
|
2020-08-07 13:44:34 +00:00
|
|
|
|
2020-10-06 19:25:05 +00:00
|
|
|
type AlertProps = {
|
|
|
|
addAlert: (message: string, variant?: AlertVariant) => void;
|
|
|
|
};
|
|
|
|
|
|
|
|
export const AlertContext = createContext<AlertProps>({
|
|
|
|
addAlert: () => {},
|
|
|
|
});
|
|
|
|
|
|
|
|
export const useAlerts = () => useContext(AlertContext);
|
|
|
|
|
2020-11-05 21:26:43 +00:00
|
|
|
type TimeOut = {
|
|
|
|
key: number;
|
|
|
|
timeOut: NodeJS.Timeout;
|
|
|
|
};
|
|
|
|
|
2020-10-06 19:25:05 +00:00
|
|
|
export const AlertProvider = ({ children }: { children: ReactNode }) => {
|
2020-08-08 13:52:23 +00:00
|
|
|
const [alerts, setAlerts] = useState<AlertType[]>([]);
|
2020-11-05 21:26:43 +00:00
|
|
|
const [timers, setTimers] = useState<TimeOut[]>([]);
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
const timersKeys = timers.map((timer) => timer.key);
|
|
|
|
const timeOuts = alerts
|
|
|
|
.filter((alert) => !timersKeys.includes(alert.key))
|
|
|
|
.map((alert) => {
|
|
|
|
const timeOut = setTimeout(() => hideAlert(alert.key), 8000);
|
|
|
|
return { key: alert.key, timeOut };
|
|
|
|
});
|
|
|
|
setTimers([...timers, ...timeOuts]);
|
|
|
|
return () => timers.forEach((timer) => clearTimeout(timer.timeOut));
|
|
|
|
}, [alerts]);
|
|
|
|
|
2020-08-07 13:44:34 +00:00
|
|
|
const createId = () => new Date().getTime();
|
|
|
|
|
|
|
|
const hideAlert = (key: number) => {
|
2020-08-08 13:52:23 +00:00
|
|
|
setAlerts((alerts) => [...alerts.filter((el) => el.key !== key)]);
|
2020-11-05 21:26:43 +00:00
|
|
|
setTimers((timers) => [...timers.filter((timer) => timer.key === key)]);
|
2020-08-07 13:44:34 +00:00
|
|
|
};
|
|
|
|
|
2020-10-06 19:25:05 +00:00
|
|
|
const addAlert = (
|
2020-09-15 19:44:28 +00:00
|
|
|
message: string,
|
|
|
|
variant: AlertVariant = AlertVariant.default
|
|
|
|
) => {
|
2020-11-05 21:26:43 +00:00
|
|
|
setAlerts([...alerts, { key: createId(), message, variant }]);
|
2020-08-07 13:44:34 +00:00
|
|
|
};
|
|
|
|
|
2020-10-06 19:25:05 +00:00
|
|
|
return (
|
|
|
|
<AlertContext.Provider value={{ addAlert }}>
|
|
|
|
<AlertPanel alerts={alerts} onCloseAlert={hideAlert} />
|
|
|
|
{children}
|
|
|
|
</AlertContext.Provider>
|
|
|
|
);
|
|
|
|
};
|