import clsx from 'clsx'; import React, { useEffect, useRef, useState } from 'react'; import { useThemeStore } from '@/store/themeStore'; import { eventDispatcher } from '@/utils/event'; export type ToastType = 'info' | 'success' | 'warning' | 'error'; export const Toast = () => { const { safeAreaInsets } = useThemeStore(); const [toastMessage, setToastMessage] = useState(''); const [toastType, setToastType] = useState('info'); const [toastTimeout, setToastTimeout] = useState(5000); const [messageClass, setMessageClass] = useState(''); const [isVisible, setIsVisible] = useState(false); const toastDismissTimeout = useRef | null>(null); const toastClassMap = { info: 'toast-info toast-center toast-middle', success: 'toast-success toast-top sm:toast-end toast-center', warning: 'toast-warning toast-top sm:toast-end toast-center', error: 'toast-error toast-top sm:toast-end toast-center', }; const alertClassMap = { info: 'alert-primary border-base-300', success: 'alert-success not-eink:from-green-500 not-eink:to-emerald-500', warning: 'alert-warning not-eink:from-amber-500 not-eink:to-orange-500', error: 'alert-error not-eink:from-red-500 not-eink:to-rose-500', }; const iconMap = { info: ( ), success: ( ), warning: ( ), error: ( ), }; useEffect(() => { if (toastMessage) { setTimeout(() => { setIsVisible(true); }, 0); } }, [toastMessage]); useEffect(() => { if (toastDismissTimeout.current) clearTimeout(toastDismissTimeout.current); if (toastMessage) { const timeout = setTimeout(() => { setIsVisible(false); setTimeout(() => setToastMessage(''), 300); }, toastTimeout); toastDismissTimeout.current = timeout; return () => { if (timeout) clearTimeout(timeout); }; } return; }, [toastMessage, toastTimeout]); const handleShowToast = async (event: CustomEvent) => { const { message, type = 'info', timeout, className = '', callback = null } = event.detail; setToastMessage(message); setToastType(type); if (timeout) setToastTimeout(timeout); if (callback && typeof callback === 'function') { setTimeout(() => callback(), timeout || 5000); } setMessageClass(className); }; useEffect(() => { eventDispatcher.on('toast', handleShowToast); return () => { eventDispatcher.off('toast', handleShowToast); }; }, []); const handleDismiss = () => { setIsVisible(false); setTimeout(() => setToastMessage(''), 300); if (toastDismissTimeout.current) clearTimeout(toastDismissTimeout.current); }; return ( toastMessage && (
{/* Icon */}
{iconMap[toastType]}
{/* Message */} {toastMessage.split('\n').map((line, idx) => ( {line || <> } {idx < toastMessage.split('\n').length - 1 &&
}
))}
{/* Close button */}
) ); };