2020-09-01 14:51:59 +00:00
|
|
|
import { AlertVariant } from "@patternfly/react-core";
|
2021-07-21 09:30:18 +00:00
|
|
|
import React, { createContext, ReactNode, useState } from "react";
|
|
|
|
import useRequiredContext from "../../utils/useRequiredContext";
|
|
|
|
import { AlertPanel, AlertType } from "./AlertPanel";
|
2020-08-07 13:44:34 +00:00
|
|
|
|
2020-10-06 19:25:05 +00:00
|
|
|
type AlertProps = {
|
2021-02-17 07:17:04 +00:00
|
|
|
addAlert: (
|
|
|
|
message: string,
|
|
|
|
variant?: AlertVariant,
|
|
|
|
description?: string
|
|
|
|
) => void;
|
2020-10-06 19:25:05 +00:00
|
|
|
};
|
|
|
|
|
2021-07-21 09:30:18 +00:00
|
|
|
export const AlertContext = createContext<AlertProps | undefined>(undefined);
|
2020-10-06 19:25:05 +00:00
|
|
|
|
2021-07-21 09:30:18 +00:00
|
|
|
export const useAlerts = () => useRequiredContext(AlertContext);
|
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
|
|
|
|
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-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,
|
2021-07-01 06:48:03 +00:00
|
|
|
variant: AlertVariant = AlertVariant.success,
|
2021-02-17 07:17:04 +00:00
|
|
|
description?: string
|
2020-09-15 19:44:28 +00:00
|
|
|
) => {
|
2021-07-01 06:48:03 +00:00
|
|
|
const key = createId();
|
|
|
|
setTimeout(() => hideAlert(key), 8000);
|
|
|
|
setAlerts([{ key, message, variant, description }, ...alerts]);
|
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>
|
|
|
|
);
|
|
|
|
};
|