import { createContext, useCallback, useContext, useEffect, useRef, useState, type ReactNode } from 'react'; import { registerShopToastListener, type ShopToastVariant } from '../lib/toast'; type ShopToastContextValue = { showToast: (message: string, variant?: ShopToastVariant) => void; }; const ShopToastContext = createContext(null); export function ShopToastProvider({ children }: { children: ReactNode }) { const [toast, setToast] = useState(''); const [variant, setVariant] = useState('error'); const timerRef = useRef(null); const showToast = useCallback((message: string, nextVariant: ShopToastVariant = 'error') => { if (timerRef.current) window.clearTimeout(timerRef.current); setVariant(nextVariant); setToast(message); timerRef.current = window.setTimeout(() => { setToast(''); timerRef.current = null; }, nextVariant === 'error' ? 2800 : 2000); }, []); useEffect(() => { registerShopToastListener(showToast); return () => { registerShopToastListener(null); if (timerRef.current) window.clearTimeout(timerRef.current); }; }, [showToast]); return ( {children} {toast ? (
{toast}
) : null}
); } export function useShopToast(): ShopToastContextValue { const ctx = useContext(ShopToastContext); if (!ctx) throw new Error('useShopToast 必须在 ShopToastProvider 内使用'); return ctx; }