import PropTypes from 'prop-types';
import React, { useState, useEffect, useCallback } from 'react';
import { Container, Content, Banner, Text, Icon } from './styledComponents';
import { Props, ToasterInterface } from './interfaces';
import {
TOASTER_STATUS,
TOASTER_POSITION,
TOASTER_CUSTOM_ICON,
} from './constants';
import iconClose from '../images/icon-close-cross.svg';
import iconToasterError from '../images/icon-toaster-error.svg';
import iconToasterSuccess from '../images/icon-toaster-success.svg';
import iconToasterWarning from '../images/icon-toaster-warning.svg';
import iconToasterInfo from '../images/icon-toaster-info.svg';
import ColorPalette from '../utils/colorPalette';
const getBackgroundColor = (status?: string): ColorPalette => {
if (status === TOASTER_STATUS.ERROR) {
return ColorPalette.Info_Red;
}
if (status === TOASTER_STATUS.WARNING) {
return ColorPalette.Info_Orange;
}
if (status === TOASTER_STATUS.INFO) {
return ColorPalette.DMGrey;
}
return ColorPalette.Info_Green;
};
const renderIcon = (icon, status): JSX.Element | null => {
if (icon && TOASTER_CUSTOM_ICON[icon]) {
return ;
}
if (status === TOASTER_STATUS.ERROR) {
return ;
}
if (status === TOASTER_STATUS.INFO) {
return ;
}
if (status === TOASTER_STATUS.WARNING) {
return ;
}
return ;
};
const Toaster = (props: Props): JSX.Element | null => {
const {
icon,
text,
status,
hidden,
position,
autoDelete,
dismissTime,
handleClose,
} = props;
const [hideToaster, setHideToaster] = useState(true);
const [toaster, setToaster] = useState(null);
const deleteToast = useCallback(() => {
if (handleClose) {
handleClose();
}
setHideToaster(true);
}, [handleClose]);
useEffect(() => {
if (hideToaster) {
return;
}
setToaster({
text,
status,
position,
});
}, [text, status, position, hideToaster]);
useEffect(() => {
if (hideToaster !== hidden) {
setHideToaster(hidden);
}
}, [hidden, hideToaster, setHideToaster]);
useEffect(() => {
const timeout = setTimeout(() => {
if (autoDelete && !!toaster) {
deleteToast();
}
}, dismissTime);
return () => {
clearTimeout(timeout);
};
}, [toaster, autoDelete, dismissTime, deleteToast]);
if (!toaster) {
return <>>;
}
return (
{renderIcon(icon, toaster.status)}
{toaster.text}
{handleClose && (
)}
);
};
Toaster.propTypes = {
autoDelete: PropTypes.bool,
handleClose: PropTypes.func,
dismissTime: PropTypes.number,
hidden: PropTypes.bool.isRequired,
text: PropTypes.string.isRequired,
status: PropTypes.oneOf(Object.values(TOASTER_STATUS)),
icon: PropTypes.oneOf(Object.keys(TOASTER_CUSTOM_ICON)),
position: PropTypes.oneOf(Object.values(TOASTER_POSITION)),
};
Toaster.defaultProps = {
icon: null,
autoDelete: false,
dismissTime: 3000,
handleClose: null,
status: TOASTER_STATUS.SUCCESS,
position: TOASTER_POSITION.BOTTOM_LEFT,
};
export default Toaster;