import { useEffect, useState, type ImgHTMLAttributes, type ReactNode } from 'react'; import { Loader2 } from 'lucide-react'; import api from '../services/api'; interface AuthImageProps extends Omit, 'src'> { src: string | null | undefined; fallback?: ReactNode; } /** * Renders an authenticated image. The `` tag cannot send our JWT * Authorization header, so a direct URL to a protected endpoint (e.g. * `/api/v1/photos/...`) returns 401 and shows broken in the browser. * AuthImage fetches the bytes through the axios instance (which injects * the auth header), converts the response to a blob URL, and renders that. * * For dataURLs and blob URLs we render directly without fetching. */ export default function AuthImage({ src, fallback = null, ...imgProps }: AuthImageProps) { const [blobUrl, setBlobUrl] = useState(null); const [error, setError] = useState(false); useEffect(() => { if (!src) { setBlobUrl(null); setError(false); return; } // Pass-through for data: and blob: URLs, and for absolute http(s) URLs // (e.g. Supabase signed URLs already carry their own auth token in the // query string and are fetchable directly by the browser). if ( src.startsWith('data:') || src.startsWith('blob:') || src.startsWith('http://') || src.startsWith('https://') ) { setBlobUrl(src); setError(false); return; } let cancelled = false; let createdUrl: string | null = null; setError(false); // Strip our axios baseURL prefix so the path doesn't double up. const relative = src.replace(/^\/api\/v1/, ''); api .get(relative, { responseType: 'blob' }) .then((res) => { if (cancelled) return; createdUrl = URL.createObjectURL(res.data); setBlobUrl(createdUrl); }) .catch(() => { if (!cancelled) setError(true); }); return () => { cancelled = true; if (createdUrl) URL.revokeObjectURL(createdUrl); }; }, [src]); if (error || !src) return <>{fallback}; if (!blobUrl) { const { className = '', ...rest } = imgProps; return (
)} className={`${className} flex items-center justify-center bg-gray-100`} aria-busy="true" aria-label="Cargando imagen" >
); } return ; }