SPB Git

Repository Public

Listing.tsx 10.8 KB 257 lines tsx

1// Fiche logement : l'aboutissement de « Ouvrir la porte ». La photo principale2// domine à l'arrivée, puis viennent le prix, le lieu et les faits.3// L'ordre du DOM est l'ordre visuel, identique sur mobile et grand écran :4// photos, prix et adresse, description, inclusions, détails, analyses, carte,5// scores, quartier, gestionnaire, logements à proximité.67import { useEffect, useMemo } from "react";8import { Link, useLocation, useNavigate, useParams } from "react-router";9import { useQuery } from "@tanstack/react-query";10import { ArrowLeft, ChevronRight } from "lucide-react";11import { fetchFairValue, fetchListing, fetchSearch, priceOk, type Listing as ListingT } from "@/lib/api";12import { cleanCity, slugify } from "@/lib/format";13import { useInView, useIsDesktop, useTitle } from "@/lib/hooks";14import { markSeen } from "@/lib/store";15import { LoukaEmptyState } from "@/brand/EmptyState";16import { ListingCard, ListingCardSkeleton } from "@/components/ListingCard";17import { FairValuePanel, HistoryPanel, TrueCostPanel } from "@/components/fiche/Analyses";18import { hasScores, ManagerCard, Neighborhood, ScoresSection } from "@/components/fiche/Area";19import { Amenities, amenitiesOf, Description, hasDescription, Practical } from "@/components/fiche/Content";20import { Gallery } from "@/components/fiche/Gallery";21import { Section } from "@/components/fiche/kit";22import { Nearby } from "@/components/fiche/Nearby";23import { MobileCta, Overview, placeOf, StickySummary, titleOf } from "@/components/fiche/Overview";24import { SectionNav, type NavItem } from "@/components/fiche/SectionNav";25import { ButtonLink } from "@/ui/primitives";2627function Loading() {28  return (29    <div className="container-x pb-32 lg:pt-5" aria-busy="true" aria-label="Chargement de la fiche">30      <div className="skeleton hidden h-5 w-56 lg:block" />31      <div className="skeleton -mx-[clamp(1rem,4vw,2.5rem)] aspect-[4/3] rounded-none lg:mx-0 lg:mt-4 lg:aspect-auto lg:h-[min(60vh,540px)] lg:rounded-xl" />32      <div className="mt-10 grid gap-12 lg:grid-cols-[minmax(0,1fr)_340px]">33        <div className="space-y-4">34          <div className="skeleton h-6 w-28" />35          <div className="skeleton h-10 w-48" />36          <div className="skeleton h-7 w-4/5" />37          <div className="skeleton h-5 w-2/5" />38        </div>39        <div className="skeleton hidden h-72 rounded-xl lg:block" />40      </div>41    </div>42  );43}4445function Similar({ l }: { l: ListingT }) {46  const [ref, inView] = useInView<HTMLElement>("500px");47  const geo = l.lat != null && l.lng != null;48  const q = useQuery({49    queryKey: ["similaires", l.uid],50    queryFn: () => {51      const d = 0.03;52      return fetchSearch({53        bbox: `${l.lng! - d * 1.4},${l.lat! - d},${l.lng! + d * 1.4},${l.lat! + d}`,54        unit_type: l.unit_type || undefined,55        sort: "deal",56        page_size: 13,57        include: "liste",58      });59    },60    enabled: inView && geo,61    staleTime: 3e5,62    retry: 0,63  });64  const items = (q.data?.listings ?? []).filter((x) => x.uid !== l.uid && priceOk(x.price) && (x.fv_deviation ?? 0) > -0.45).slice(0, 8);65  if (!geo || (q.isSuccess && items.length < 3) || q.isError) return <section ref={ref} />;66  return (67    <section ref={ref} className="mt-16 border-t border-line pt-8">68      <h2 className="text-[1.5rem] sm:text-[1.7rem]">{l.unit_type ? `D'autres ${l.unit_type} à proximité` : "D'autres logements à proximité"}</h2>69      <div className="lk-stagger no-scrollbar -mx-[clamp(1rem,4vw,2.5rem)] mt-6 flex snap-x gap-4 overflow-x-auto px-[clamp(1rem,4vw,2.5rem)] sm:mx-0 sm:grid sm:grid-cols-2 sm:gap-x-5 sm:gap-y-8 sm:overflow-visible sm:px-0 lg:grid-cols-4">70        {items.length71          ? items.map((x) => (72              <div key={x.uid} className="w-[72vw] shrink-0 snap-start sm:w-auto">73                <ListingCard listing={x} />74              </div>75            ))76          : Array.from({ length: 4 }, (_, i) => (77              <div key={i} className="w-[72vw] shrink-0 sm:w-auto">78                <ListingCardSkeleton />79              </div>80            ))}81      </div>82    </section>83  );84}8586export default function Listing() {87  const { uid = "" } = useParams();88  const navigate = useNavigate();89  const location = useLocation();90  const desktop = useIsDesktop();91  const q = useQuery({92    queryKey: ["listing", uid],93    queryFn: () => fetchListing(uid),94    staleTime: 3e5,95    retry: (n, e) => !/API 404/.test(String(e)) && n < 1,96  });97  const l = q.data;98  const fvq = useQuery({99    queryKey: ["fairvalue", uid],100    queryFn: () => fetchFairValue(uid),101    enabled: !!l && priceOk(l.price),102    staleTime: 6e5,103    retry: 0,104  });105106  // la fiche s'ouvre toujours en haut107  useEffect(() => {108    window.scrollTo(0, 0);109  }, [uid]);110  useEffect(() => {111    if (l) markSeen(l.uid);112  }, [l]);113  // à l'arrivée, le focus se pose sur le titre (lecteurs d'écran, clavier)114  const loaded = !!l;115  useEffect(() => {116    if (!loaded) return;117    document.querySelector<HTMLElement>("[data-fiche-title]")?.focus({ preventScroll: true });118  }, [loaded, uid, location.key]);119120  useTitle(l ? `${l.unit_type ? `${l.unit_type} · ` : ""}${titleOf(l)}${l.city ? `, ${cleanCity(l.city)}` : ""}` : null);121122  const nav = useMemo<NavItem[]>(() => {123    if (!l) return [];124    const am = amenitiesOf(l);125    const geo = l.lat != null && l.lng != null;126    return [127      { id: "apercu", label: "Aperçu" },128      hasDescription(l) ? { id: "description", label: "Description" } : null,129      am.ok.length + am.others.length > 0 ? { id: "inclusions", label: "Inclusions" } : null,130      { id: "details", label: "Détails" },131      { id: "analyses", label: "Analyses" },132      geo || (l.poi?.length ?? 0) > 0 ? { id: "carte", label: "Carte" } : null,133      hasScores(l) ? { id: "scores", label: "Scores" } : null,134      l.quartier || l.immeuble || l.hiver || geo ? { id: "quartier", label: "Quartier" } : null,135      { id: "gestionnaire", label: "Gestionnaire" },136    ].filter(Boolean) as NavItem[];137  }, [l]);138139  if (q.isPending) return <Loading />;140  if (q.isError || !l) {141    const notFound = /API 404/.test(String(q.error));142    return (143      <div className="container-x py-16">144        <LoukaEmptyState145          kind="closed"146          title={notFound ? "Ce logement est introuvable" : "La fiche n'a pas pu se charger"}147          text={notFound ? "L'annonce a peut-être été retirée par son auteur, ou le lien est incomplet." : "Vérifiez votre connexion, puis réessayez."}148          action={149            <ButtonLink to="/recherche" variant="primary">150              Explorer les logements151            </ButtonLink>152          }153        />154      </div>155    );156  }157158  const city = cleanCity(l.city);159  const inactive = l.active === 0;160  const back = () => (window.history.length > 2 ? navigate(-1) : navigate("/recherche"));161162  return (163    <>164      <div className="container-x pb-36 lg:pb-16 lg:pt-4">165        {/* fil d'Ariane (grand écran) : sur mobile, la photo vient en premier */}166        {desktop && (167          <nav aria-label="Fil d'Ariane" className="mb-3.5 flex items-center gap-1.5 text-[0.84rem] text-ink-3">168            <button type="button" onClick={back} className="mr-2 inline-flex h-8 items-center gap-1.5 rounded-[8px] border border-line-2 px-2.5 text-ink transition-colors duration-150 hover:border-ink-3">169              <ArrowLeft className="size-3.5" /> Retour170            </button>171            <Link to="/recherche" className="hover:text-ink">172              Recherche173            </Link>174            {city && (175              <>176                <ChevronRight className="size-3.5" />177                <Link to={`/ville/${slugify(city)}`} className="hover:text-ink">178                  {city}179                </Link>180              </>181            )}182            <ChevronRight className="size-3.5" />183            <span className="min-w-0 truncate text-ink-2">{titleOf(l)}</span>184          </nav>185        )}186187        <Gallery188          images={l.images ?? []}189          alt={`${titleOf(l)}, ${placeOf(l)}`}190          overlay={191            desktop ? undefined : (192              <button193                type="button"194                onClick={back}195                aria-label="Retour"196                className="grid size-10 place-items-center rounded-full bg-white/92 text-[#181c1a] shadow-[0_1px_3px_rgb(0_0_0/0.18)] active:scale-95"197              >198                <ArrowLeft className="size-[18px]" />199              </button>200            )201          }202        />203204        {inactive && (205          <div role="status" className="mt-4 rounded-[10px] border border-high/40 bg-high-soft px-4 py-3 text-[0.92rem] text-ink">206            <b className="font-semibold">Cette annonce n'est plus en ligne.</b> Elle a été retirée par sa source ; la fiche reste consultable à titre d'archive.{" "}207            <Link to={city ? `/recherche?city=${encodeURIComponent(city)}` : "/recherche"} className="font-medium text-brand underline underline-offset-2">208              Voir les logements disponibles209            </Link>210          </div>211        )}212213        <SectionNav items={nav} />214215        <div className="mt-7 grid gap-12 lg:grid-cols-[minmax(0,1fr)_340px]">216          {/* colonne principale : tout le contenu, dans l'ordre de lecture */}217          <div className="min-w-0 space-y-10">218            <Overview l={l} fv={fvq.data} />219            <Description l={l} />220            <Amenities l={l} />221            <Practical l={l} />222            <Section id="analyses" title="Le prix, vérifié" text="Trois lectures indépendantes du loyer : sa juste valeur, ce qu'il coûte vraiment chaque mois, et son histoire.">223              <div className="space-y-4">224                <FairValuePanel l={l} fv={fvq.data} loading={fvq.isPending && priceOk(l.price)} />225                <TrueCostPanel l={l} />226                <HistoryPanel l={l} />227              </div>228            </Section>229            <Nearby l={l} />230            <ScoresSection l={l} />231            <Neighborhood l={l} />232            <ManagerCard l={l} />233            <p className="border-t border-line pt-5 text-[0.8rem] leading-relaxed text-ink-3">234              Lou-Ka regroupe des annonces publiées ailleurs et renvoie toujours vers la source. Les analyses sont des estimations calculées à partir de données publiques ; elles ne235              remplacent ni une visite ni la lecture du bail. Une information vous semble erronée ?{" "}236              <Link to="/contact" className="text-brand hover:underline">237                Écrivez-nous238              </Link>239              .240            </p>241          </div>242243          {/* colonne latérale : résumé collant, après le contenu dans le DOM */}244          <aside className="hidden lg:block" aria-label="Résumé du logement">245            <div className="sticky top-32">246              <StickySummary l={l} fv={fvq.data} />247            </div>248          </aside>249        </div>250251        <Similar l={l} />252      </div>253      <MobileCta l={l} />254    </>255  );256}257
Files main
Menu

Theme