"use client" import { useCallback, useEffect, useRef, useState } from "react" import { cn } from "@lib/utils" import { getCachedFileBlob } from "@/lib/file-cache" interface ImagePreviewProps { url: string title?: string | null documentId?: string | null } export function ImagePreview({ url, title, documentId }: ImagePreviewProps) { const [imageError, setImageError] = useState(false) const [isLoading, setIsLoading] = useState(true) const [retryKey, setRetryKey] = useState(0) const [activeSrc, setActiveSrc] = useState(url) const objectUrlRef = useRef(null) useEffect(() => { return () => { if (objectUrlRef.current) { URL.revokeObjectURL(objectUrlRef.current) objectUrlRef.current = null } } }, []) const handleImageError = useCallback(() => { if (retryKey === 0) { setTimeout(() => setRetryKey(1), 500) return } if (retryKey === 1 && documentId) { getCachedFileBlob(documentId).then((blob) => { if (blob) { if (objectUrlRef.current) { URL.revokeObjectURL(objectUrlRef.current) } const objUrl = URL.createObjectURL(blob) objectUrlRef.current = objUrl setActiveSrc(objUrl) setRetryKey(2) } else { setImageError(true) setIsLoading(false) } }) return } setImageError(true) setIsLoading(false) }, [retryKey, documentId]) if (imageError || !activeSrc) { return (

Failed to load image

) } return (
{isLoading && (
)}
{title setIsLoading(false)} loading="lazy" />
) }