Repository Public
1// Toutes les villes du Québec où un logement est à louer : un index typographique.23import { useMemo, useState } from "react";4import { Link } from "react-router";5import { useQuery } from "@tanstack/react-query";6import { fetchVilles, priceOk, type VilleRow } from "@/lib/api";7import { cleanCity, fmtInt, fmtMoney, plural } from "@/lib/format";8import { useDebounced, useTitle } from "@/lib/hooks";9import { LoukaEmptyState } from "@/brand/EmptyState";10import { ErrorState, norm, PageHead, RowsSkeleton, SearchField, SectionHead, SortSelect, Toolbar, useProgressive } from "@/components/annuaire/shared";1112type Sort = "logements" | "nom" | "loyer";13const SORTS: { value: Sort; label: string }[] = [14 { value: "logements", label: "Logements" },15 { value: "nom", label: "Nom" },16 { value: "loyer", label: "Loyer moyen" },17];18const FEATURED = 12;1920/** Villes exploitables : libellé propre, doublons de casse fusionnés par slug. */21function tidy(rows: VilleRow[]): VilleRow[] {22 const seen = new Set<string>();23 const out: VilleRow[] = [];24 for (const v of rows) {25 const city = cleanCity(v.city);26 if (!city || !v.slug || seen.has(v.slug) || /^\d/.test(city)) continue;27 seen.add(v.slug);28 out.push({ ...v, city });29 }30 return out;31}3233/** Ligne des grands marchés : nom en serif, logements, loyer moyen. */34function BigRow({ v }: { v: VilleRow }) {35 return (36 <li>37 <Link38 to={`/ville/${v.slug}`}39 className="group flex min-h-14 items-baseline justify-between gap-4 border-b border-line py-3.5 transition-colors duration-150 hover:border-ink-3"40 >41 <span className="truncate font-display text-[1.25rem] transition-colors duration-150 group-hover:text-brand">{v.city}</span>42 <span className="num flex shrink-0 items-baseline gap-4 text-[0.88rem] text-ink-3">43 <span>{plural(v.n, "logement", "logements")}</span>44 <span className="w-[4.6rem] text-right font-medium text-ink">{priceOk(v.avg_price) ? fmtMoney(v.avg_price) : "—"}</span>45 </span>46 </Link>47 </li>48 );49}5051/** Ligne compacte de l'index complet. */52function Row({ v }: { v: VilleRow }) {53 return (54 <li>55 <Link56 to={`/ville/${v.slug}`}57 className="group flex min-h-11 items-baseline justify-between gap-3 border-b border-line py-2.5 transition-colors duration-150 hover:border-ink-3"58 >59 <span className="min-w-0 truncate text-[0.95rem] text-ink transition-colors duration-150 group-hover:text-brand">{v.city}</span>60 <span className="num flex shrink-0 items-baseline gap-3 text-[0.84rem] text-ink-3">61 {priceOk(v.avg_price) && <span>{fmtMoney(v.avg_price)}</span>}62 <span className="w-9 text-right font-medium text-ink-2">{fmtInt(v.n)}</span>63 </span>64 </Link>65 </li>66 );67}6869const COLS = "grid grid-cols-1 gap-x-10 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4";7071export default function Cities() {72 useTitle("Logements à louer par ville au Québec");73 const q = useQuery({ queryKey: ["villes"], queryFn: fetchVilles, staleTime: 6e5 });74 const [text, setText] = useState("");75 const [sort, setSort] = useState<Sort>("logements");76 const needle = norm(useDebounced(text, 100).trim());7778 const all = useMemo(() => tidy(q.data?.villes ?? []), [q.data]);79 const total = useMemo(() => all.reduce((s, v) => s + v.n, 0), [all]);80 const featured = useMemo(() => [...all].sort((a, b) => b.n - a.n).slice(0, FEATURED), [all]);8182 const rows = useMemo(() => {83 const r = needle ? all.filter((v) => norm(v.city).includes(needle)) : [...all];84 if (sort === "nom") r.sort((a, b) => a.city.localeCompare(b.city, "fr"));85 else if (sort === "loyer")86 r.sort((a, b) => (priceOk(a.avg_price) ? a.avg_price : Infinity) - (priceOk(b.avg_price) ? b.avg_price : Infinity) || b.n - a.n);87 else r.sort((a, b) => b.n - a.n || a.city.localeCompare(b.city, "fr"));88 return r;89 }, [all, needle, sort]);9091 // index alphabétique : groupes par initiale quand le tri est par nom92 const groups = useMemo(() => {93 if (sort !== "nom") return null;94 const m = new Map<string, VilleRow[]>();95 for (const v of rows) {96 const k = norm(v.city).charAt(0).toUpperCase() || "#";97 (m.get(k) ?? m.set(k, []).get(k)!).push(v);98 }99 return [...m.entries()];100 }, [rows, sort]);101102 const { count, sentinel } = useProgressive(rows.length, `${needle}|${sort}`, 160);103104 return (105 <>106 <PageHead107 eyebrow="Partout au Québec"108 title="Logements à louer, ville par ville"109 text="Des grands centres aux plus petites municipalités : le nombre de logements disponibles et le loyer moyen affiché en ce moment."110 facts={111 !!q.data && [112 { value: fmtInt(all.length), label: "villes et municipalités" },113 { value: fmtInt(total), label: "logements à louer" },114 ...(featured[0] ? [{ value: featured[0].city, label: "offre la plus abondante" }] : []),115 ]116 }117 />118119 <Toolbar>120 <div className="flex flex-wrap items-center gap-2">121 <SearchField value={text} onChange={setText} placeholder="Chercher une ville" className="min-w-0 flex-1 basis-64" />122 <SortSelect value={sort} onChange={setSort} options={SORTS} />123 </div>124 {groups && groups.length > 1 && (125 <nav aria-label="Aller à une lettre" className="no-scrollbar -mx-[clamp(1rem,4vw,2.5rem)] flex overflow-x-auto px-[clamp(1rem,4vw,2.5rem)] lg:mx-0 lg:px-0">126 {groups.map(([letter]) => (127 <a128 key={letter}129 href={`#lettre-${letter}`}130 className="grid h-11 min-w-9 shrink-0 place-items-center font-display text-[1.05rem] text-ink-2 transition-colors duration-150 hover:text-brand lg:h-9"131 >132 {letter}133 </a>134 ))}135 </nav>136 )}137 </Toolbar>138139 <div className="container-x pt-8">140 {q.isError ? (141 <ErrorState onRetry={() => q.refetch()} />142 ) : q.isPending ? (143 <RowsSkeleton rows={12} />144 ) : rows.length === 0 ? (145 <LoukaEmptyState kind="closed" title="Aucune ville trouvée" text="Vérifiez l'orthographe ou essayez une ville voisine." />146 ) : (147 <>148 {!needle && sort === "logements" && (149 <section className="mb-14">150 <SectionHead title="Les grands marchés" text="Nombre de logements à louer et loyer moyen affiché." />151 <ul className="mt-3 grid grid-cols-1 gap-x-12 sm:grid-cols-2">152 {featured.map((v) => (153 <BigRow key={v.slug} v={v} />154 ))}155 </ul>156 </section>157 )}158159 <section>160 <SectionHead161 title={needle ? "Résultats" : "Toutes les villes"}162 aside={163 <span className="num text-[0.86rem] text-ink-3" aria-live="polite">164 {plural(rows.length, "ville", "villes")}165 </span>166 }167 />168 {groups ? (169 <div className="mt-4 space-y-9">170 {groups.map(([letter, list]) => (171 <div key={letter} id={`lettre-${letter}`} className="grid scroll-mt-44 gap-x-8 lg:grid-cols-[3rem_1fr]">172 <h3 className="text-[1.75rem] leading-none text-ink-3 max-lg:mb-2">{letter}</h3>173 <ul className={COLS}>174 {list.map((v) => (175 <Row key={v.slug} v={v} />176 ))}177 </ul>178 </div>179 ))}180 </div>181 ) : (182 <>183 <ul key={sort} className={`lk-stagger lk-stagger--swap mt-3 ${COLS}`}>184 {rows.slice(0, count).map((v) => (185 <Row key={v.slug} v={v} />186 ))}187 </ul>188 {sentinel}189 </>190 )}191 </section>192 </>193 )}194 </div>195 </>196 );197}198