Repository Public
1// Une ville : chiffres réels, propriétés à vendre, répartition par type de2// propriété, villes voisines.34import { Link, useParams } from "react-router";5import { useQuery } from "@tanstack/react-query";6import { Map as MapIcon } from "lucide-react";7import { fetchCityFigures, fetchNeighbors, isMissing, resolveCity, tidyCity, typePlural, type CityFigures, type CityIdentity } from "@/lib/api.annuaires";8import { cn } from "@/lib/cn";9import { fmtInt, fmtMoney, plural } from "@/lib/format";10import { useTitle } from "@/lib/hooks";11import { DrawOnView } from "@/lib/motion";12import { BrandEmptyState } from "@/brand/compat";13import { ListingCardSkeleton } from "@/components/ListingCard";14import { ButtonLink, Skeleton } from "@/ui/primitives";15import { Inventory, mapHref } from "@/components/annuaire-ik/Inventory";16import { BackLink, ChipRow, ErrorState, Facts, FactsPlaceholder, Rows, SectionHead, TabLink, type Fact } from "@/components/annuaire-ik/shared";1718const pct = (n: number, total: number) => (total > 0 ? `${Math.max(1, Math.round((n / total) * 100))} %` : "—");1920/** Répartition par type : une ligne par type, une barre qui se trace une fois. */21function TypeBreakdown({ id, figures }: { id: CityIdentity; figures: CityFigures | undefined }) {22 const types = figures?.types ?? [];23 const max = types.reduce((m, t) => Math.max(m, t.n), 0);24 if (figures && types.length === 0) return null;25 const cols = "grid grid-cols-[minmax(0,1fr)_auto] items-center gap-x-4 sm:grid-cols-[13rem_minmax(0,1fr)_4.5rem_3.5rem_7rem] sm:gap-x-6";26 return (27 <section aria-labelledby="repartition-titre">28 <SectionHead id="repartition-titre" title="Répartition par type de propriété" text="Inscriptions actives et prix médian demandé, par type." />29 <div className={cn("mt-5 hidden border-b border-line-2 pb-2 text-[0.76rem] text-ink-3 sm:grid", cols)} aria-hidden>30 <span>Type</span>31 <span />32 <span className="text-right">Inscriptions</span>33 <span className="text-right">Part</span>34 <span className="text-right">Prix médian</span>35 </div>36 {!figures ? (37 <ul aria-hidden className="max-sm:mt-4">38 {Array.from({ length: 5 }, (_, i) => (39 <li key={i} className="flex min-h-[3.75rem] items-center justify-between gap-6 border-b border-line sm:min-h-12">40 <span className="skeleton h-4" style={{ width: `${22 + ((i * 9) % 16)}%` }} />41 <span className="skeleton h-4 w-24" />42 </li>43 ))}44 </ul>45 ) : (46 <DrawOnView className="group max-sm:mt-4" role="list" label="Répartition des inscriptions par type de propriété">47 {types.map((t, i) => {48 const active = id.type?.slug === t.slug;49 return (50 <Link51 key={t.slug}52 role="listitem"53 to={active ? `/a-vendre/${id.slug}` : `/a-vendre/${id.slug}/${t.slug}`}54 aria-current={active ? "page" : undefined}55 className={cn("group/row min-h-[3.75rem] border-b border-line py-2.5 transition-colors duration-150 hover:border-ink-3 sm:min-h-12", cols)}56 >57 <span className={cn("truncate text-[0.98rem] transition-colors duration-150 group-hover/row:text-brand", active ? "font-medium text-brand" : "text-ink")}>{typePlural(t.label)}</span>58 <span className="num text-right text-[0.9rem] sm:hidden">59 <span className="font-semibold text-ink">{fmtInt(t.n)}</span>60 {t.median != null && <span className="text-[0.82rem] text-ink-3"> · {fmtMoney(t.median)}</span>}61 </span>62 <span className="col-span-2 mt-1.5 block h-1.5 overflow-hidden rounded-[2px] bg-surface-3 sm:col-span-1 sm:mt-0" aria-hidden>63 <span64 className="block h-full origin-left rounded-[2px] bg-brand transition-transform duration-700 ease-out group-data-[drawn=false]:scale-x-0"65 style={{ width: `${Math.max(1.5, (t.n / max) * 100)}%`, transitionDelay: `${i * 40}ms` }}66 />67 </span>68 <span className="num hidden text-right text-[0.92rem] font-semibold text-ink sm:block">{fmtInt(t.n)}</span>69 <span className="num hidden text-right text-[0.84rem] text-ink-3 sm:block">{pct(t.n, figures.n)}</span>70 <span className="num hidden text-right text-[0.9rem] text-ink sm:block">{t.median != null ? fmtMoney(t.median) : <span className="text-ink-3">—</span>}</span>71 </Link>72 );73 })}74 </DrawOnView>75 )}76 {figures && figures.others > 0 && (77 <p className="num mt-3 text-[0.84rem] text-ink-3">{plural(figures.others, "autre inscription", "autres inscriptions")} d'un type moins courant ou non précisé par la source.</p>78 )}79 </section>80 );81}8283function Neighbors({ id, given }: { id: CityIdentity; given: { slug: string; city: string; n: number | null; median: number | null }[] | null | undefined }) {84 // v2 : fournies avec les chiffres de la ville ; v1 : déduites des inscriptions géolocalisées autour85 const q = useQuery({86 queryKey: ["ik-ville-voisines", id.slug],87 queryFn: ({ signal }) => fetchNeighbors(id, signal),88 enabled: given === null,89 staleTime: 36e5,90 retry: 0,91 });92 const rows = (given ?? q.data ?? []).filter((n) => n.city);93 const pending = given === undefined || (given === null && q.isPending);94 if (!pending && rows.length === 0) return null;95 return (96 <section aria-labelledby="voisines">97 <SectionHead id="voisines" title="Villes voisines" text="Nombre d'inscriptions actives et prix médian demandé." to="/villes" cta="Toutes les villes" />98 {pending ? (99 <ul aria-hidden className="mt-3 grid grid-cols-1 gap-x-12 sm:grid-cols-2 lg:grid-cols-3">100 {Array.from({ length: 6 }, (_, i) => (101 <li key={i} className="flex min-h-12 items-center justify-between gap-4 border-b border-line">102 <span className="skeleton h-5" style={{ width: `${30 + ((i * 11) % 22)}%` }} />103 <span className="skeleton h-4 w-28" />104 </li>105 ))}106 </ul>107 ) : (108 <Rows className="mt-3 grid grid-cols-1 gap-x-12 sm:grid-cols-2 lg:grid-cols-3">109 {rows.map((n) => (110 <div role="listitem" key={n.slug}>111 <Link to={`/a-vendre/${n.slug}`} className="group flex min-h-12 items-baseline justify-between gap-4 border-b border-line py-3 transition-colors duration-150 hover:border-ink-3">112 <span className="truncate font-display text-[1.12rem] transition-colors duration-150 group-hover:text-brand">{n.city}</span>113 <span className="num flex shrink-0 items-baseline gap-3 text-[0.84rem] text-ink-3">114 {n.n != null && <span>{fmtInt(n.n)}</span>}115 <span className="w-[5.4rem] text-right font-medium text-ink">{n.median != null ? fmtMoney(n.median) : "—"}</span>116 </span>117 </Link>118 </div>119 ))}120 </Rows>121 )}122 </section>123 );124}125126export default function City() {127 const { ville = "", type } = useParams();128 const idQ = useQuery({ queryKey: ["ik-ville", ville, type ?? ""], queryFn: () => resolveCity(ville, type), staleTime: 36e5, retry: (n, e) => !isMissing(e) && n < 1 });129 const id = idQ.data;130 const figQ = useQuery({131 queryKey: ["ik-ville-chiffres", ville],132 queryFn: ({ signal }) => fetchCityFigures(id!, signal),133 enabled: !!id,134 staleTime: 6e5,135 });136 const fig = figQ.data?.figures;137 const city = tidyCity(id?.city);138 const t = id?.type ?? null;139 const what = t ? typePlural(t.label) : "Propriétés";140141 useTitle(city ? `${what} à vendre à ${city}` : "Propriétés à vendre par ville");142143 if (idQ.isError) {144 return (145 <div className="container-x py-10">146 {isMissing(idQ.error) ? (147 <BrandEmptyState148 kind="closed"149 title="Ville introuvable"150 text="Aucune propriété n'est répertoriée sous ce nom en ce moment. Parcourez la liste des villes ou cherchez directement sur la carte."151 action={152 <div className="flex flex-wrap justify-center gap-2">153 <ButtonLink to="/villes" variant="primary">154 Toutes les villes155 </ButtonLink>156 <ButtonLink to="/recherche" variant="outline">157 Explorer la carte158 </ButtonLink>159 </div>160 }161 />162 ) : (163 <ErrorState onRetry={() => idQ.refetch()} />164 )}165 </div>166 );167 }168169 const query = id ? { city: id.city, property_type: t?.label } : null;170 const ofType = t ? fig?.types.find((x) => x.slug === t.slug) : undefined;171 const facts: Fact[] | null = fig172 ? [173 { value: fmtInt(fig.n), label: `${fig.n > 1 ? "inscriptions actives" : "inscription active"}${t ? " dans la ville" : ""}` },174 ...(t ? [{ value: fmtInt(ofType?.n ?? 0), label: typePlural(t.label).toLowerCase() }] : []),175 ...(t176 ? ofType?.median != null177 ? [{ value: fmtMoney(ofType.median), label: `prix médian, ${typePlural(t.label).toLowerCase()}` }]178 : []179 : fig.median != null180 ? [{ value: fmtMoney(fig.median), label: "prix médian demandé" }]181 : []),182 ...(t && fig.median != null ? [{ value: fmtMoney(fig.median), label: "prix médian, tous types" }] : []),183 ...(!t && fig.types.length > 0 ? [{ value: fmtInt(fig.types.length), label: fig.types.length > 1 ? "types de propriété" : "type de propriété" }] : []),184 ...(!t && fig.types[0] ? [{ value: typePlural(fig.types[0].label), label: "type le plus offert" }] : []),185 ].slice(0, 4)186 : null;187188 return (189 <>190 <header className="container-x pb-7 pt-5 lg:pt-10">191 <BackLink to="/villes">Toutes les villes</BackLink>192 <div className="flex min-h-[5.6rem] flex-wrap items-end justify-between gap-x-10 gap-y-5 sm:min-h-[4.9rem]">193 {idQ.isPending ? (194 <div className="w-full space-y-4">195 <Skeleton className="h-4 w-36" />196 <Skeleton className="h-10 w-3/4 max-w-xl" />197 </div>198 ) : (199 <>200 <div className="min-w-0 max-w-2xl">201 <p className="eyebrow">{t ? `${what} à vendre` : "Propriétés à vendre"}</p>202 <h1 className="mt-2.5 text-[1.85rem] leading-[1.08] sm:text-[2.5rem]">203 {what} à vendre à {city}204 </h1>205 </div>206 <ButtonLink to={query ? mapHref(query) : "/recherche"} variant="primary" className="max-sm:w-full">207 <MapIcon className="size-4" /> Voir sur la carte208 </ButtonLink>209 </>210 )}211 </div>212 {facts ? <Facts className="mt-6" items={facts} /> : figQ.isError ? <div className="mt-6 border-t border-line" /> : <FactsPlaceholder className="mt-6" />}213 </header>214215 <div className="container-x space-y-16">216 {!id || !query ? (217 <div className="grid grid-cols-1 gap-x-5 gap-y-8 border-t border-line pt-7 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">218 {Array.from({ length: 8 }, (_, i) => (219 <ListingCardSkeleton key={i} />220 ))}221 </div>222 ) : id.typeMissing ? (223 <BrandEmptyState224 kind="closed"225 title="Type de propriété inconnu"226 text={`Ce type de propriété n'existe pas dans l'index. Consultez toutes les propriétés à vendre à ${city}.`}227 action={228 <ButtonLink to={`/a-vendre/${id.slug}`} variant="primary">229 Toutes les propriétés à {city}230 </ButtonLink>231 }232 />233 ) : (234 <Inventory235 title={t ? `${what} à vendre` : "Propriétés à vendre"}236 query={query}237 hideMap238 known={t ? ofType?.n : fig?.n}239 filters={240 // la rangée garde sa hauteur pendant le calcul de la répartition241 <div className="min-h-11 lg:min-h-9">242 {fig && fig.types.length > 0 && (243 <ChipRow label="Type de propriété">244 <TabLink to={`/a-vendre/${id.slug}`} active={!t} count={fmtInt(fig.n)}>245 Toutes246 </TabLink>247 {fig.types.map((x) => (248 <TabLink key={x.slug} to={`/a-vendre/${id.slug}/${x.slug}`} active={t?.slug === x.slug} count={fmtInt(x.n)}>249 {typePlural(x.label)}250 </TabLink>251 ))}252 </ChipRow>253 )}254 </div>255 }256 emptyTitle={t ? "Aucune propriété de ce type en ce moment" : "Aucune propriété affichée en ce moment"}257 emptyText="L'offre change plusieurs fois par jour. Consultez les autres types de propriété ou une ville voisine."258 emptyAction={259 t && (260 <ButtonLink to={`/a-vendre/${id.slug}`} variant="outline">261 Toutes les propriétés à {city}262 </ButtonLink>263 )264 }265 />266 )}267268 {id && !figQ.isError && <TypeBreakdown id={id} figures={fig} />}269 {id && <Neighbors id={id} given={figQ.isError ? null : figQ.data ? figQ.data.neighbors : undefined} />}270 </div>271 </>272 );273}274