2021-10-14 22:56:51 +05:30
|
|
|
import { useCallback, useEffect, useRef } from "react";
|
2022-11-01 17:29:58 +01:00
|
|
|
import { CloseIcon } from "./icons";
|
2021-01-15 20:32:46 +05:30
|
|
|
import "./Toast.scss";
|
2022-07-05 21:43:59 +05:30
|
|
|
import { ToolButton } from "./ToolButton";
|
|
|
|
|
|
|
|
const DEFAULT_TOAST_TIMEOUT = 5000;
|
2021-01-15 20:32:46 +05:30
|
|
|
|
|
|
|
export const Toast = ({
|
|
|
|
message,
|
2022-07-11 18:11:13 +05:30
|
|
|
onClose,
|
2022-07-05 21:43:59 +05:30
|
|
|
closable = false,
|
|
|
|
// To prevent autoclose, pass duration as Infinity
|
|
|
|
duration = DEFAULT_TOAST_TIMEOUT,
|
2021-01-15 20:32:46 +05:30
|
|
|
}: {
|
|
|
|
message: string;
|
2022-07-11 18:11:13 +05:30
|
|
|
onClose: () => void;
|
2022-07-05 21:43:59 +05:30
|
|
|
closable?: boolean;
|
|
|
|
duration?: number;
|
2021-01-15 20:32:46 +05:30
|
|
|
}) => {
|
|
|
|
const timerRef = useRef<number>(0);
|
2022-07-05 21:43:59 +05:30
|
|
|
const shouldAutoClose = duration !== Infinity;
|
|
|
|
const scheduleTimeout = useCallback(() => {
|
|
|
|
if (!shouldAutoClose) {
|
|
|
|
return;
|
|
|
|
}
|
2022-07-11 18:11:13 +05:30
|
|
|
timerRef.current = window.setTimeout(() => onClose(), duration);
|
|
|
|
}, [onClose, duration, shouldAutoClose]);
|
2021-01-15 20:32:46 +05:30
|
|
|
|
|
|
|
useEffect(() => {
|
2022-07-05 21:43:59 +05:30
|
|
|
if (!shouldAutoClose) {
|
|
|
|
return;
|
|
|
|
}
|
2021-01-15 20:32:46 +05:30
|
|
|
scheduleTimeout();
|
|
|
|
return () => clearTimeout(timerRef.current);
|
2022-07-05 21:43:59 +05:30
|
|
|
}, [scheduleTimeout, message, duration, shouldAutoClose]);
|
2021-01-15 20:32:46 +05:30
|
|
|
|
2022-07-05 21:43:59 +05:30
|
|
|
const onMouseEnter = shouldAutoClose
|
|
|
|
? () => clearTimeout(timerRef?.current)
|
|
|
|
: undefined;
|
|
|
|
const onMouseLeave = shouldAutoClose ? scheduleTimeout : undefined;
|
2021-01-15 20:32:46 +05:30
|
|
|
return (
|
|
|
|
<div
|
|
|
|
className="Toast"
|
2022-07-05 21:43:59 +05:30
|
|
|
onMouseEnter={onMouseEnter}
|
|
|
|
onMouseLeave={onMouseLeave}
|
2021-01-15 20:32:46 +05:30
|
|
|
>
|
|
|
|
<p className="Toast__message">{message}</p>
|
2022-07-05 21:43:59 +05:30
|
|
|
{closable && (
|
|
|
|
<ToolButton
|
2022-11-01 17:29:58 +01:00
|
|
|
icon={CloseIcon}
|
2022-07-05 21:43:59 +05:30
|
|
|
aria-label="close"
|
|
|
|
type="icon"
|
2022-07-11 18:11:13 +05:30
|
|
|
onClick={onClose}
|
2022-07-05 21:43:59 +05:30
|
|
|
className="close"
|
|
|
|
/>
|
|
|
|
)}
|
2021-01-15 20:32:46 +05:30
|
|
|
</div>
|
|
|
|
);
|
|
|
|
};
|