1import React, {createContext, useRef, useState} from "react";
2import {faExclamationTriangle} from "@fortawesome/free-solid-svg-icons";
3import "./styles.sass";
4import {FontAwesomeIcon} from "@fortawesome/react-fontawesome";
5
6export const ToastNotificationContext = createContext({});
7
8export const ToastNotificationProvider = (props) => {
9
10 const notificationRef = useRef();
11 const [timeOutId, setTimeOutId] = useState(null);
12 const [toastNotification, setToastNotification] = useState(null);
13
14 const updateToast = (text, color = "red", icon = faExclamationTriangle) => {
15 setToastNotification({text, color, icon});
16
17 if (timeOutId) {
18 clearTimeout(timeOutId);
19 setTimeOutId(null);
20 }
21 setTimeOutId(setTimeout(close, 5000));
22 }
23
24 const close = () => {
25 notificationRef.current.classList.add("toast-hidden");
26 }
27
28 const onAnimationEnd = (event) => {
29 if (event.animationName === "moveOut")
30 setToastNotification(null);
31 }
32
33 return (
34 <ToastNotificationContext.Provider value={updateToast}>
35 <div className={"toast-notification" + (toastNotification ? "" : " toast-hidden") + " toast-" + toastNotification?.color}
36 onAnimationEnd={onAnimationEnd} ref={notificationRef} onClick={close}>
37 {toastNotification && <div className="toast-content">
38 <FontAwesomeIcon icon={toastNotification.icon} />
39 <h2>{toastNotification.text}</h2>
40 </div>}
41 </div>
42
43 {props.children}
44 </ToastNotificationContext.Provider>
45 );
46}