Repository Public
1// Galerie : la photo principale domine (c'est sur elle qu'aboutit la2// transition « la porte de la maison s'ouvre »), mosaïque sur grand écran,3// carrousel tactile bord à bord sur mobile, visionneuse plein écran pilotable4// au clavier (← → Échap) et au balayage. Les photos mortes sont retirées.5// La visionneuse est toujours sombre (noir et blanc neutres), quel que soit le6// thème : c'est le seul endroit de la fiche sans couleur sémantique.78import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";9import { createPortal } from "react-dom";10import { ChevronLeft, ChevronRight, Images, X } from "lucide-react";11import { thumb } from "@/lib/api.propriete";12import { cn } from "@/lib/cn";13import { useIsDesktop } from "@/lib/hooks";14import { SmartImage } from "@/components/SmartImage";1516/**17 * Photo principale : la miniature 480 (déjà en cache depuis la carte de la propriété)18 * s'affiche tout de suite, la haute définition la recouvre dès qu'elle est19 * prête — même cadrage, aucun saut.20 */21function HeroPhoto({ src, alt, className, onDead }: { src: string; alt: string; className?: string; onDead?: (src: string) => void }) {22 // 0 : miniature · 1 : originale (miniature inconnue du serveur)23 const [low, setLow] = useState(0);24 const [high, setHigh] = useState<"wait" | "ok" | "ko">("wait");25 useEffect(() => {26 setLow(0);27 setHigh("wait");28 }, [src]);29 return (30 <span className={cn("absolute inset-0 block bg-surface-2", className)}>31 <img32 src={low === 0 ? thumb(src, 480) : src}33 alt={alt}34 decoding="sync"35 fetchPriority="high"36 referrerPolicy="no-referrer"37 onError={() => (low === 0 ? setLow(1) : onDead?.(src))}38 className="absolute inset-0 size-full object-cover"39 />40 {high !== "ko" && (41 <img42 src={thumb(src, typeof window !== "undefined" && window.innerWidth < 700 ? 800 : 1280)}43 alt=""44 aria-hidden45 decoding="async"46 referrerPolicy="no-referrer"47 onLoad={() => setHigh("ok")}48 onError={() => setHigh("ko")}49 className={cn("absolute inset-0 size-full object-cover", high === "ok" ? "opacity-100" : "opacity-0")}50 />51 )}52 </span>53 );54}5556/** Visionneuse plein écran : s'ouvre depuis la photo touchée, les photos57 * glissent, et sur mobile on la referme en la tirant vers le bas. */58function Lightbox({ images, captions, start, alt, origin, onClose }: { images: string[]; captions?: (string | undefined)[]; start: number; alt: string; origin: DOMRect | null; onClose: () => void }) {59 const [i, setI] = useState(start);60 const [dir, setDir] = useState<1 | -1 | 0>(0);61 const [pull, setPull] = useState(0);62 const [closing, setClosing] = useState(false);63 const n = images.length;64 const go = useCallback(65 (d: number) => {66 setDir(d > 0 ? 1 : -1);67 setI((x) => (x + d + n) % n);68 },69 [n],70 );71 const touch = useRef<{ x: number; y: number; axis: "x" | "y" | null } | null>(null);72 const stage = useRef<HTMLDivElement>(null);73 const root = useRef<HTMLDivElement>(null);7475 const close = useCallback(() => {76 if (closing) return;77 setClosing(true);78 const el = root.current;79 if (!el || document.documentElement.dataset.motion === "off") return onClose();80 el.animate([{ opacity: 1 }, { opacity: 0 }], { duration: 170, easing: "ease-out", fill: "forwards" }).finished.then(onClose, onClose);81 }, [closing, onClose]);8283 // ouverture : la photo part de la vignette touchée et vient remplir l'écran84 useEffect(() => {85 const el = stage.current;86 if (!el || !origin || document.documentElement.dataset.motion === "off") return;87 const r = el.getBoundingClientRect();88 const s = Math.max(0.2, Math.min(origin.width / r.width, origin.height / r.height) * 1.02);89 const dx = origin.left + origin.width / 2 - (r.left + r.width / 2);90 const dy = origin.top + origin.height / 2 - (r.top + r.height / 2);91 el.animate([{ transform: `translate(${dx}px, ${dy}px) scale(${s})`, opacity: 0.4 }, { transform: "none", opacity: 1 }], {92 duration: 340,93 easing: "cubic-bezier(0.32, 0.08, 0.14, 1)",94 });95 // une seule fois, à l'ouverture96 // eslint-disable-next-line react-hooks/exhaustive-deps97 }, []);9899 useEffect(() => {100 const prev = document.activeElement as HTMLElement | null;101 const onKey = (e: KeyboardEvent) => {102 if (e.key === "Escape") close();103 else if (e.key === "ArrowRight") go(1);104 else if (e.key === "ArrowLeft") go(-1);105 };106 document.addEventListener("keydown", onKey);107 const overflow = document.body.style.overflow;108 document.body.style.overflow = "hidden";109 return () => {110 document.removeEventListener("keydown", onKey);111 document.body.style.overflow = overflow;112 prev?.focus?.();113 };114 }, [go, close]);115116 const round = "grid place-items-center rounded-full bg-white/10 text-white transition-colors duration-150 hover:bg-white/20";117 const fade = Math.max(0.35, 1 - pull / 420);118 return createPortal(119 <div ref={root} role="dialog" aria-modal="true" aria-label="Photos de la propriété" className="fixed inset-0 z-[96] flex animate-fade-in flex-col text-white" style={{ background: `rgb(0 0 0 / ${fade * 0.95})` }}>120 <div className="flex items-center justify-between px-4 py-3 sm:px-6">121 <span className="min-w-0 truncate text-[0.88rem] text-white/70">122 <span className="num">123 {i + 1} / {n}124 </span>125 {captions?.[i] && <span className="ml-3 text-white/90">{captions[i]}</span>}126 </span>127 <button type="button" onClick={close} aria-label="Fermer la visionneuse" autoFocus className={cn(round, "size-10")}>128 <X className="size-5" />129 </button>130 </div>131 <div132 ref={stage}133 className={cn("relative min-h-0 flex-1 touch-none", pull === 0 && "transition-transform duration-200 ease-[cubic-bezier(0.2,0.7,0.2,1)]")}134 style={{ transform: pull ? `translateY(${pull}px) scale(${1 - Math.min(pull, 300) / 1800})` : undefined }}135 onTouchStart={(e) => {136 const t = e.touches[0];137 if (t) touch.current = { x: t.clientX, y: t.clientY, axis: null };138 }}139 onTouchMove={(e) => {140 const t0 = touch.current;141 const t = e.touches[0];142 if (!t0 || !t) return;143 const dx = t.clientX - t0.x;144 const dy = t.clientY - t0.y;145 if (!t0.axis && Math.abs(dx) + Math.abs(dy) > 10) t0.axis = Math.abs(dy) > Math.abs(dx) ? "y" : "x";146 if (t0.axis === "y") setPull(Math.max(0, dy));147 }}148 onTouchEnd={(e) => {149 const t0 = touch.current;150 const t = e.changedTouches[0];151 touch.current = null;152 if (!t0 || !t) return;153 if (t0.axis === "y") {154 if (t.clientY - t0.y > 110) close();155 else setPull(0);156 } else if (Math.abs(t.clientX - t0.x) > 48) go(t.clientX < t0.x ? 1 : -1);157 }}158 >159 <div key={i} className={cn("absolute inset-0 px-2 sm:px-20", dir > 0 ? "lk-photo-next" : dir < 0 ? "lk-photo-prev" : "")}>160 <SmartImage src={images[i]} alt={captions?.[i] ? `${captions[i]} · ${alt}` : `${alt}, photo ${i + 1}`} width={1280} fit="contain" eager className="size-full !bg-transparent" />161 </div>162 {n > 1 && (163 <>164 <button type="button" onClick={() => go(-1)} aria-label="Photo précédente" className={cn(round, "lk-press absolute left-3 top-1/2 hidden size-11 -translate-y-1/2 sm:grid")}>165 <ChevronLeft className="size-5" />166 </button>167 <button type="button" onClick={() => go(1)} aria-label="Photo suivante" className={cn(round, "lk-press absolute right-3 top-1/2 hidden size-11 -translate-y-1/2 sm:grid")}>168 <ChevronRight className="size-5" />169 </button>170 </>171 )}172 </div>173 {n > 1 && (174 <div className="no-scrollbar flex gap-1.5 overflow-x-auto px-4 py-4 sm:px-6 [&>:first-child]:ml-auto [&>:last-child]:mr-auto" style={{ opacity: fade }}>175 {images.map((src, k) => (176 <button177 key={src + k}178 type="button"179 onClick={() => {180 setDir(k > i ? 1 : k < i ? -1 : 0);181 setI(k);182 }}183 aria-label={captions?.[k] ? `Photo ${k + 1} : ${captions[k]}` : `Photo ${k + 1}`}184 aria-current={k === i}185 className={cn("relative h-12 w-[4.25rem] shrink-0 overflow-hidden rounded-[6px] transition-[opacity,transform] duration-200", k === i ? "scale-105 outline outline-2 outline-white" : "opacity-45 hover:opacity-90")}186 >187 <SmartImage src={src} alt="" width={160} eager className="size-full" />188 </button>189 ))}190 </div>191 )}192 </div>,193 document.body,194 );195}196197/** Étiquette posée sur les photos : surface pleine du thème, toujours lisible. */198const onPhoto = "border border-line bg-surface text-ink";199200export function Gallery({ images: all, captions: allCaptions, alt, overlay }: { images: string[]; captions?: string[]; alt: string; overlay?: ReactNode }) {201 const desktop = useIsDesktop();202 // photos mortes (la source les a retirées) : écartées dès qu'on le sait203 const [dead, setDead] = useState<string[]>([]);204 const markDead = useCallback((src: string) => setDead((d) => (d.includes(src) ? d : [...d, src])), []);205 const kept = all.map((src, k) => ({ src, cap: allCaptions?.[k] })).filter((x) => !dead.includes(x.src));206 const images = kept.map((x) => x.src);207 const captions = allCaptions?.length ? kept.map((x) => x.cap) : undefined;208 const [open, setOpenState] = useState<number | null>(null);209 const origin = useRef<DOMRect | null>(null);210 const setOpen = (k: number | null, el?: Element | null) => {211 origin.current = el?.getBoundingClientRect() ?? null;212 setOpenState(k);213 };214 const [idx, setIdx] = useState(0);215 const rail = useRef<HTMLDivElement>(null);216 const n = images.length;217 const close = useCallback(() => setOpenState(null), []);218219 const onScroll = () => {220 const el = rail.current;221 if (el) setIdx(Math.round(el.scrollLeft / Math.max(1, el.clientWidth)));222 };223224 // une seule mise en page dans le DOM : la cible de la porte est unique225 return (226 <div id="photos" className="relative">227 {!desktop ? (228 /* mobile : carrousel bord à bord */229 <div className="relative -mx-[clamp(1rem,4vw,2.5rem)]">230 {n === 0 ? (231 <div data-door-target>232 <SmartImage src={null} alt={alt} className="aspect-[4/3] w-full" />233 </div>234 ) : (235 <div ref={rail} onScroll={onScroll} className="no-scrollbar flex snap-x snap-mandatory overflow-x-auto">236 {images.map((src, k) => (237 <button238 key={src + k}239 type="button"240 onClick={(e) => setOpen(k, e.currentTarget)}241 aria-label={`Agrandir la photo ${k + 1} sur ${n}`}242 data-door-target={k === 0 ? "" : undefined}243 className="relative aspect-[4/3] w-full shrink-0 snap-center bg-surface-2"244 >245 {k === 0 ? <HeroPhoto src={src} alt={alt} onDead={markDead} /> : <SmartImage src={src} alt={`${alt}, photo ${k + 1}`} width={800} className="absolute inset-0 size-full" />}246 </button>247 ))}248 </div>249 )}250 {n > 1 && (251 <span className={cn("num pointer-events-none absolute bottom-3 right-3 rounded-[6px] px-2 py-1 text-[0.74rem] font-medium leading-none", onPhoto)}>252 {Math.min(idx + 1, n)} / {n}253 </span>254 )}255 {overlay && <div className="absolute inset-x-3 top-3 flex items-start justify-between gap-2">{overlay}</div>}256 </div>257 ) : (258 /* grand écran : la photo principale, puis jusqu'à quatre vues */259 <div className="relative">260 {n === 0 ? (261 <div data-door-target>262 <SmartImage src={null} alt={alt} className="h-[320px] w-full rounded-xl" />263 </div>264 ) : (265 <div className={cn("grid h-[min(60vh,540px)] gap-1.5 overflow-hidden rounded-xl", n >= 5 ? "grid-cols-4 grid-rows-2" : n >= 3 ? "grid-cols-3 grid-rows-2" : n === 2 ? "grid-cols-3" : "grid-cols-1")}>266 {images.slice(0, n >= 5 ? 5 : n >= 3 ? 3 : n).map((src, k) => (267 <button268 key={src + k}269 type="button"270 onClick={(e) => setOpen(k, e.currentTarget)}271 aria-label={`Agrandir la photo ${k + 1} sur ${n}`}272 data-door-target={k === 0 ? "" : undefined}273 className={cn("group relative overflow-hidden bg-surface-2", k === 0 && (n >= 3 ? "col-span-2 row-span-2" : n === 2 ? "col-span-2" : ""))}274 >275 {k === 0 ? <HeroPhoto src={src} alt={alt} onDead={markDead} /> : <SmartImage src={src} alt={`${alt}, photo ${k + 1}`} width={800} eager className="absolute inset-0 size-full" />}276 <span className="absolute inset-0 bg-black/0 transition-colors duration-150 group-hover:bg-black/10 group-focus-visible:bg-black/10" />277 </button>278 ))}279 </div>280 )}281 {n > 1 && (282 <button283 type="button"284 onClick={() => setOpen(0, document.querySelector("[data-door-target]"))}285 className={cn("lk-press absolute bottom-3 right-3 inline-flex h-10 items-center gap-2 rounded-[8px] px-3 text-[0.84rem] font-medium transition-colors duration-150 hover:border-ink-3", onPhoto)}286 >287 <Images className="size-4" />288 Voir les {n} photos289 </button>290 )}291 {overlay && <div className="absolute inset-x-3 top-3 flex items-start justify-between gap-2">{overlay}</div>}292 </div>293 )}294295 {open != null && n > 0 && <Lightbox origin={origin.current} images={images} captions={captions} start={Math.min(open, n - 1)} alt={alt} onClose={close} />}296 </div>297 );298}299