'use client'; import Image from 'next/image'; import { useState, useEffect, memo } from 'react'; interface CachedImageProps { src: string | null; alt: string; fill?: boolean; className?: string; sizes?: string; width?: number; height?: number; onGenerateCachedImageUrl: (url: string) => Promise; fallback?: React.ReactNode; } const imageUrlCache = new Map(); const loadingPromises = new Map>(); const CachedImageComponent = ({ src, alt, fill, className, sizes, width, height, onGenerateCachedImageUrl, fallback, }: CachedImageProps) => { const [cachedUrl, setCachedUrl] = useState(() => { return src ? imageUrlCache.get(src) || null : null; }); const [loading, setLoading] = useState(() => !src || !imageUrlCache.has(src)); const [error, setError] = useState(null); useEffect(() => { if (!src) { setTimeout(() => { setLoading(false); }, 0); return; } const cached = imageUrlCache.get(src); if (cached) { setTimeout(() => { setCachedUrl(cached); setLoading(false); }, 0); return; } let cancelled = false; const loadImage = async () => { try { setLoading(true); setError(null); let loadPromise = loadingPromises.get(src); if (!loadPromise) { loadPromise = onGenerateCachedImageUrl(src); loadingPromises.set(src, loadPromise); loadPromise.finally(() => { loadingPromises.delete(src); }); } const url = await loadPromise; if (!cancelled) { imageUrlCache.set(src, url); setCachedUrl(url); setLoading(false); } } catch (err) { if (!cancelled) { setError(err instanceof Error ? err : new Error('Failed to load image')); setLoading(false); } } }; loadImage(); return () => { cancelled = true; }; }, [src, onGenerateCachedImageUrl]); if (loading) { return (
); } if (error || !cachedUrl) { if (fallback) { return <>{fallback}; } return (
); } if (fill) { return {alt}; } return ( {alt} ); }; const arePropsEqual = (prevProps: CachedImageProps, nextProps: CachedImageProps) => { return ( prevProps.src === nextProps.src && prevProps.alt === nextProps.alt && prevProps.fill === nextProps.fill && prevProps.className === nextProps.className && prevProps.sizes === nextProps.sizes && prevProps.width === nextProps.width && prevProps.height === nextProps.height ); }; export const CachedImage = memo(CachedImageComponent, arePropsEqual); export const clearImageCache = () => { imageUrlCache.clear(); loadingPromises.clear(); };