Repository Public
1// Image d'une propriété : miniature optimisée, repli sur l'originale, puis visuel2// de secours — jamais d'icône d'image cassée.34import { useEffect, useRef, useState } from "react";5import { IconHouse } from "@/brand/icons";6import { thumb } from "@/lib/api";7import { cn } from "@/lib/cn";89export function SmartImage({10 src,11 alt,12 width = 480,13 className,14 eager,15 fit = "cover",16}: {17 src: string | null | undefined;18 alt: string;19 width?: 160 | 480 | 800 | 1280;20 className?: string;21 eager?: boolean;22 fit?: "cover" | "contain";23}) {24 // 0 : miniature · 1 : originale · 2 : visuel de secours25 const [stage, setStage] = useState(src ? 0 : 2);26 // l'adresse dont l'image est affichée : une image déjà en cache peut finir de27 // charger avant que React n'écoute `onLoad`, on vérifie donc aussi `complete`28 const [shown, setShown] = useState<string | null>(null);29 const ref = useRef<HTMLImageElement>(null);30 const url = !src ? null : stage === 0 ? thumb(src, width) : src;31 useEffect(() => {32 setStage(src ? 0 : 2);33 }, [src]);34 useEffect(() => {35 const img = ref.current;36 if (img && url && img.complete && img.naturalWidth > 0) setShown(url);37 }, [url]);38 const loaded = shown === url;3940 if (stage === 2 || !src) {41 return (42 <div43 role="img"44 aria-label={alt}45 className={cn(46 "grid place-items-center bg-surface-2 text-ink-3",47 className,48 )}49 >50 <IconHouse size={36} className="opacity-45" strokeWidth={1.2} />51 </div>52 );53 }54 return (55 <img56 ref={ref}57 src={url ?? undefined}58 alt={alt}59 loading={eager ? "eager" : "lazy"}60 decoding="async"61 referrerPolicy="no-referrer"62 onLoad={() => setShown(url)}63 onError={() => setStage((s) => s + 1)}64 className={cn(65 "bg-surface-2 transition-opacity duration-200",66 fit === "cover" ? "object-cover" : "object-contain",67 loaded ? "opacity-100" : "opacity-0",68 className,69 )}70 />71 );72}73