SPB Git

Repository Public

Gallery.tsx 12.8 KB 288 lines tsx

1// Galerie : la photo principale domine (c'est sur elle qu'aboutit la2// transition « Ouvrir la porte »), mosaïque sur grand écran, carrousel tactile3// bord à bord sur mobile, visionneuse plein écran pilotable au clavier4// (← → Échap) et au balayage.56import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";7import { createPortal } from "react-dom";8import { ChevronLeft, ChevronRight, Images, X } from "lucide-react";9import { thumb } from "@/lib/api";10import { cn } from "@/lib/cn";11import { useIsDesktop } from "@/lib/hooks";12import { SmartImage } from "@/components/SmartImage";1314/**15 * Photo principale : la miniature 480 (déjà en cache depuis la carte d'annonce)16 * s'affiche tout de suite, la haute définition la recouvre dès qu'elle est17 * prête — même cadrage, aucun saut.18 */19function HeroPhoto({ src, alt, className }: { src: string; alt: string; className?: string }) {20  // 0 : miniature · 1 : originale (miniature inconnue du serveur)21  const [low, setLow] = useState(0);22  const [high, setHigh] = useState<"wait" | "ok" | "ko">("wait");23  useEffect(() => {24    setLow(0);25    setHigh("wait");26  }, [src]);27  return (28    <span className={cn("absolute inset-0 block bg-surface-2", className)}>29      <img30        src={low === 0 ? thumb(src, 480) : src}31        alt={alt}32        decoding="sync"33        fetchPriority="high"34        referrerPolicy="no-referrer"35        onError={() => setLow((v) => (v === 0 ? 1 : v))}36        className="absolute inset-0 size-full object-cover"37      />38      {high !== "ko" && (39        <img40          src={thumb(src, typeof window !== "undefined" && window.innerWidth < 700 ? 800 : 1280)}41          alt=""42          aria-hidden43          decoding="async"44          referrerPolicy="no-referrer"45          onLoad={() => setHigh("ok")}46          onError={() => setHigh("ko")}47          className={cn("absolute inset-0 size-full object-cover", high === "ok" ? "opacity-100" : "opacity-0")}48        />49      )}50    </span>51  );52}5354/** Visionneuse plein écran : s'ouvre depuis la photo touchée, les photos55 *  glissent, et sur mobile on la referme en la tirant vers le bas. */56function Lightbox({ images, start, alt, origin, onClose }: { images: string[]; start: number; alt: string; origin: DOMRect | null; onClose: () => void }) {57  const [i, setI] = useState(start);58  const [dir, setDir] = useState<1 | -1 | 0>(0);59  const [pull, setPull] = useState(0);60  const [closing, setClosing] = useState(false);61  const n = images.length;62  const go = useCallback(63    (d: number) => {64      setDir(d > 0 ? 1 : -1);65      setI((x) => (x + d + n) % n);66    },67    [n],68  );69  const touch = useRef<{ x: number; y: number; axis: "x" | "y" | null } | null>(null);70  const stage = useRef<HTMLDivElement>(null);71  const root = useRef<HTMLDivElement>(null);7273  const close = useCallback(() => {74    if (closing) return;75    setClosing(true);76    const el = root.current;77    if (!el || document.documentElement.dataset.motion === "off") return onClose();78    el.animate([{ opacity: 1 }, { opacity: 0 }], { duration: 170, easing: "ease-out", fill: "forwards" }).finished.then(onClose, onClose);79  }, [closing, onClose]);8081  // ouverture : la photo part de la vignette touchée et vient remplir l'écran82  useEffect(() => {83    const el = stage.current;84    if (!el || !origin || document.documentElement.dataset.motion === "off") return;85    const r = el.getBoundingClientRect();86    const s = Math.max(0.2, Math.min(origin.width / r.width, origin.height / r.height) * 1.02);87    const dx = origin.left + origin.width / 2 - (r.left + r.width / 2);88    const dy = origin.top + origin.height / 2 - (r.top + r.height / 2);89    el.animate([{ transform: `translate(${dx}px, ${dy}px) scale(${s})`, opacity: 0.4 }, { transform: "none", opacity: 1 }], {90      duration: 340,91      easing: "cubic-bezier(0.32, 0.08, 0.14, 1)",92    });93    // une seule fois, à l'ouverture94    // eslint-disable-next-line react-hooks/exhaustive-deps95  }, []);9697  useEffect(() => {98    const prev = document.activeElement as HTMLElement | null;99    const onKey = (e: KeyboardEvent) => {100      if (e.key === "Escape") close();101      else if (e.key === "ArrowRight") go(1);102      else if (e.key === "ArrowLeft") go(-1);103    };104    document.addEventListener("keydown", onKey);105    const overflow = document.body.style.overflow;106    document.body.style.overflow = "hidden";107    return () => {108      document.removeEventListener("keydown", onKey);109      document.body.style.overflow = overflow;110      prev?.focus?.();111    };112  }, [go, close]);113114  const round = "grid place-items-center rounded-full bg-white/10 text-white transition-colors duration-150 hover:bg-white/20";115  const fade = Math.max(0.35, 1 - pull / 420);116  return createPortal(117    <div ref={root} role="dialog" aria-modal="true" aria-label="Photos du logement" className="fixed inset-0 z-[96] flex animate-fade-in flex-col text-white" style={{ background: `rgb(12 16 14 / ${fade})` }}>118      <div className="flex items-center justify-between px-4 py-3 sm:px-6">119        <span className="num text-[0.88rem] text-white/70">120          {i + 1} / {n}121        </span>122        <button type="button" onClick={close} aria-label="Fermer la visionneuse" autoFocus className={cn(round, "size-10")}>123          <X className="size-5" />124        </button>125      </div>126      <div127        ref={stage}128        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)]")}129        style={{ transform: pull ? `translateY(${pull}px) scale(${1 - Math.min(pull, 300) / 1800})` : undefined }}130        onTouchStart={(e) => {131          const t = e.touches[0];132          if (t) touch.current = { x: t.clientX, y: t.clientY, axis: null };133        }}134        onTouchMove={(e) => {135          const t0 = touch.current;136          const t = e.touches[0];137          if (!t0 || !t) return;138          const dx = t.clientX - t0.x;139          const dy = t.clientY - t0.y;140          if (!t0.axis && Math.abs(dx) + Math.abs(dy) > 10) t0.axis = Math.abs(dy) > Math.abs(dx) ? "y" : "x";141          if (t0.axis === "y") setPull(Math.max(0, dy));142        }}143        onTouchEnd={(e) => {144          const t0 = touch.current;145          const t = e.changedTouches[0];146          touch.current = null;147          if (!t0 || !t) return;148          if (t0.axis === "y") {149            if (t.clientY - t0.y > 110) close();150            else setPull(0);151          } else if (Math.abs(t.clientX - t0.x) > 48) go(t.clientX < t0.x ? 1 : -1);152        }}153      >154        <div key={i} className={cn("absolute inset-0 px-2 sm:px-20", dir > 0 ? "lk-photo-next" : dir < 0 ? "lk-photo-prev" : "")}>155          <SmartImage src={images[i]} alt={`${alt}, photo ${i + 1}`} width={1280} fit="contain" eager className="size-full !bg-transparent" />156        </div>157        {n > 1 && (158          <>159            <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")}>160              <ChevronLeft className="size-5" />161            </button>162            <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")}>163              <ChevronRight className="size-5" />164            </button>165          </>166        )}167      </div>168      {n > 1 && (169        <div className="no-scrollbar flex gap-1.5 overflow-x-auto px-4 py-4 sm:justify-center sm:px-6" style={{ opacity: fade }}>170          {images.map((src, k) => (171            <button172              key={src + k}173              type="button"174              onClick={() => {175                setDir(k > i ? 1 : k < i ? -1 : 0);176                setI(k);177              }}178              aria-label={`Photo ${k + 1}`}179              aria-current={k === i}180              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")}181            >182              <SmartImage src={src} alt="" width={160} eager className="size-full" />183            </button>184          ))}185        </div>186      )}187    </div>,188    document.body,189  );190}191192/** Étiquette posée sur les photos : fond papier fixe, toujours lisible. */193const onPhoto = "bg-white/92 text-[#181c1a] shadow-[0_1px_3px_rgb(0_0_0/0.18)]";194195export function Gallery({ images, alt, overlay }: { images: string[]; alt: string; overlay?: ReactNode }) {196  const desktop = useIsDesktop();197  const [open, setOpenState] = useState<number | null>(null);198  const origin = useRef<DOMRect | null>(null);199  const setOpen = (k: number | null, el?: Element | null) => {200    origin.current = el?.getBoundingClientRect() ?? null;201    setOpenState(k);202  };203  const [idx, setIdx] = useState(0);204  const rail = useRef<HTMLDivElement>(null);205  const n = images.length;206  const close = useCallback(() => setOpenState(null), []);207208  const onScroll = () => {209    const el = rail.current;210    if (el) setIdx(Math.round(el.scrollLeft / Math.max(1, el.clientWidth)));211  };212213  // une seule mise en page dans le DOM : la cible de la porte est unique214  return (215    <div id="photos" className="relative">216      {!desktop ? (217        /* mobile : carrousel bord à bord */218        <div className="relative -mx-[clamp(1rem,4vw,2.5rem)]">219          {n === 0 ? (220            <div data-door-target>221              <SmartImage src={null} alt={alt} className="aspect-[4/3] w-full" />222            </div>223          ) : (224            <div ref={rail} onScroll={onScroll} className="no-scrollbar flex snap-x snap-mandatory overflow-x-auto">225              {images.map((src, k) => (226                <button227                  key={src + k}228                  type="button"229                  onClick={(e) => setOpen(k, e.currentTarget)}230                  aria-label={`Agrandir la photo ${k + 1} sur ${n}`}231                  data-door-target={k === 0 ? "" : undefined}232                  className="relative aspect-[4/3] w-full shrink-0 snap-center bg-surface-2"233                >234                  {k === 0 ? <HeroPhoto src={src} alt={alt} /> : <SmartImage src={src} alt={`${alt}, photo ${k + 1}`} width={800} className="absolute inset-0 size-full" />}235                </button>236              ))}237            </div>238          )}239          {n > 1 && (240            <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)}>241              {Math.min(idx + 1, n)} / {n}242            </span>243          )}244          {overlay && <div className="absolute inset-x-3 top-3 flex items-start justify-between gap-2">{overlay}</div>}245        </div>246      ) : (247        /* grand écran : la photo principale, puis jusqu'à quatre vues */248        <div className="relative">249          {n === 0 ? (250            <div data-door-target>251              <SmartImage src={null} alt={alt} className="h-[320px] w-full rounded-xl" />252            </div>253          ) : (254            <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")}>255              {images.slice(0, n >= 5 ? 5 : n >= 3 ? 3 : n).map((src, k) => (256                <button257                  key={src + k}258                  type="button"259                  onClick={(e) => setOpen(k, e.currentTarget)}260                  aria-label={`Agrandir la photo ${k + 1} sur ${n}`}261                  data-door-target={k === 0 ? "" : undefined}262                  className={cn("group relative overflow-hidden bg-surface-2", k === 0 && (n >= 3 ? "col-span-2 row-span-2" : n === 2 ? "col-span-2" : ""))}263                >264                  {k === 0 ? <HeroPhoto src={src} alt={alt} /> : <SmartImage src={src} alt={`${alt}, photo ${k + 1}`} width={800} eager className="absolute inset-0 size-full" />}265                  <span className="absolute inset-0 bg-black/0 transition-colors duration-150 group-hover:bg-black/10 group-focus-visible:bg-black/10" />266                </button>267              ))}268            </div>269          )}270          {n > 1 && (271            <button272              type="button"273              onClick={() => setOpen(0, document.querySelector("[data-door-target]"))}274              className={cn("absolute bottom-3 right-3 inline-flex h-9 items-center gap-2 rounded-[8px] px-3 text-[0.84rem] font-medium transition-colors duration-150 hover:bg-white", onPhoto)}275            >276              <Images className="size-4" />277              Voir les {n} photos278            </button>279          )}280          {overlay && <div className="absolute inset-x-3 top-3 flex items-start justify-between gap-2">{overlay}</div>}281        </div>282      )}283284      {open != null && n > 0 && <Lightbox origin={origin.current} images={images} start={open} alt={alt} onClose={close} />}285    </div>286  );287}288
Files main
Menu

Theme