SPB Git

Repository Public

Cities.tsx 10.2 KB 223 lines tsx

1// Toutes les villes du Québec où une propriété est à vendre : un index typographique.23import { useMemo, useState } from "react";4import { Link } from "react-router";5import { useQuery } from "@tanstack/react-query";6import { fetchCityIndex, fetchSiteStats, fetchTopCities, norm, type CityRow } from "@/lib/api.annuaires";7import { fmtInt, fmtMoney, plural } from "@/lib/format";8import { useDebounced, useTitle } from "@/lib/hooks";9import { BrandEmptyState } from "@/brand/compat";10import { Button } from "@/ui/primitives";11import { ErrorState, PageHead, Rows, RowsSkeleton, SearchField, SectionHead, SortSelect, Toolbar, useProgressive } from "@/components/annuaire-ik/shared";1213type Sort = "inscriptions" | "nom" | "prix" | "recent";14const LABELS: Record<Sort, string> = { inscriptions: "Inscriptions", nom: "Nom", prix: "Prix médian", recent: "Mise à jour" };15const FEATURED = 12;1617/** Ligne des grands marchés : nom en serif, inscriptions, prix médian. */18function BigRow({ v }: { v: CityRow }) {19  return (20    <div role="listitem">21      <Link to={`/a-vendre/${v.slug}`} 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">22        <span className="truncate font-display text-[1.25rem] transition-colors duration-150 group-hover:text-brand">{v.city}</span>23        <span className="num flex shrink-0 items-baseline gap-4 text-[0.88rem] text-ink-3">24          {v.n != null && <span>{plural(v.n, "inscription", "inscriptions")}</span>}25          <span className="w-[5.6rem] text-right font-medium text-ink">{v.median != null ? fmtMoney(v.median) : "—"}</span>26        </span>27      </Link>28    </div>29  );30}3132/** Ligne compacte de l'index complet. */33function Row({ v }: { v: CityRow }) {34  return (35    <div role="listitem">36      <Link to={`/a-vendre/${v.slug}`} 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">37        <span className="min-w-0 truncate text-[0.95rem] text-ink transition-colors duration-150 group-hover:text-brand">{v.city}</span>38        {(v.n != null || v.median != null) && (39          <span className="num flex shrink-0 items-baseline gap-3 text-[0.84rem] text-ink-3">40            {v.median != null && <span className="max-[359px]:hidden">{fmtMoney(v.median)}</span>}41            {v.n != null && <span className="min-w-9 text-right font-medium text-ink-2">{fmtInt(v.n)}</span>}42          </span>43        )}44      </Link>45    </div>46  );47}4849const COLS = "grid grid-cols-1 gap-x-10 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4";5051export default function Cities() {52  useTitle("Propriétés à vendre par ville au Québec");53  const q = useQuery({ queryKey: ["ik-villes"], queryFn: fetchCityIndex, staleTime: 36e5 });54  const stats = useQuery({ queryKey: ["ik-stats"], queryFn: fetchSiteStats, staleTime: 3e5 });55  const complete = q.data?.complete ?? false;56  // v1 : pas de compte par ville en lot ; on chiffre les douze plus grandes villes57  const top = useQuery({ queryKey: ["ik-villes-top"], queryFn: ({ signal }) => fetchTopCities(signal), enabled: !!q.data && !complete, staleTime: 36e5, retry: 0 });58  const [input, setInput] = useState("");59  const [chosen, setChosen] = useState<Sort | null>(null);60  const sort: Sort = chosen ?? (complete ? "inscriptions" : "nom");61  const needle = norm(useDebounced(input, 100).trim());6263  const all = useMemo(() => {64    const rows = q.data?.rows ?? [];65    if (complete || !top.data?.length) return rows;66    const known = new Map(top.data.map((t) => [t.slug, t]));67    return rows.map((r) => {68      const t = known.get(r.slug);69      return t ? { ...r, n: t.n, median: t.median } : r;70    });71  }, [q.data, complete, top.data]);7273  const featured = useMemo(74    () =>75      [...all]76        .filter((v) => v.n != null)77        .sort((a, b) => (b.n ?? 0) - (a.n ?? 0))78        .slice(0, FEATURED),79    [all],80  );81  const featuredPending = !complete && top.isPending && !!q.data;8283  const sorts = useMemo(() => (complete ? (["inscriptions", "nom", "prix"] as Sort[]) : (["nom", "recent"] as Sort[])).map((value) => ({ value, label: LABELS[value] })), [complete]);8485  const rows = useMemo(() => {86    const r = needle ? all.filter((v) => norm(v.city).includes(needle)) : [...all];87    if (sort === "nom") r.sort((a, b) => a.city.localeCompare(b.city, "fr"));88    else if (sort === "prix") r.sort((a, b) => (a.median ?? Infinity) - (b.median ?? Infinity) || (b.n ?? 0) - (a.n ?? 0));89    else if (sort === "recent") r.sort((a, b) => (b.lastmod ?? "").localeCompare(a.lastmod ?? "") || a.city.localeCompare(b.city, "fr"));90    else r.sort((a, b) => (b.n ?? 0) - (a.n ?? 0) || a.city.localeCompare(b.city, "fr"));91    return r;92  }, [all, needle, sort]);9394  // index alphabétique : groupes par initiale quand le tri est par nom95  const groups = useMemo(() => {96    if (sort !== "nom") return null;97    const m = new Map<string, CityRow[]>();98    for (const v of rows) {99      const k = norm(v.city).charAt(0).toUpperCase() || "#";100      (m.get(k) ?? m.set(k, []).get(k)!).push(v);101    }102    return [...m.entries()];103  }, [rows, sort]);104105  const { count, sentinel } = useProgressive(rows.length, `${needle}|${sort}`, 160);106  const showFeatured = !needle && (featuredPending || featured.length > 0) && (complete ? sort === "inscriptions" : true);107108  return (109    <>110      <PageHead111        eyebrow="Partout au Québec"112        title="Propriétés à vendre, ville par ville"113        text="Des grands centres aux plus petites municipalités : les villes où des propriétés sont à vendre en ce moment, avec le nombre d'inscriptions actives et le prix médian demandé."114        facts={115          !!q.data &&116          !stats.isPending && [117            { value: fmtInt(all.length), label: "villes et municipalités" },118            { value: stats.data ? fmtInt(stats.data.total) : "—", label: "inscriptions actives" },119            {120              value: featured[0] ? featured[0].city : featuredPending ? <span className="skeleton inline-block h-4 w-24 align-middle" /> : "—",121              label: "offre la plus abondante",122            },123          ]124        }125      />126127      <Toolbar>128        <div className="flex flex-wrap items-center gap-2">129          <SearchField value={input} onChange={setInput} placeholder="Chercher une ville" className="min-w-0 flex-1 basis-64" />130          <SortSelect value={sort} onChange={setChosen} options={sorts} />131        </div>132        {groups && groups.length > 1 && (133          <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">134            {groups.map(([letter]) => (135              <a key={letter} href={`#lettre-${letter}`} 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">136                {letter}137              </a>138            ))}139          </nav>140        )}141      </Toolbar>142143      <div className="container-x pt-8">144        {q.isError ? (145          <ErrorState onRetry={() => q.refetch()} />146        ) : q.isPending ? (147          <RowsSkeleton rows={12} />148        ) : rows.length === 0 ? (149          <BrandEmptyState150            kind="closed"151            title="Aucune ville trouvée"152            text="Vérifiez l'orthographe ou essayez une ville voisine. Seules les villes où au moins trois propriétés sont à vendre figurent dans l'index."153            action={154              <Button variant="outline" onClick={() => setInput("")}>155                Effacer la recherche156              </Button>157            }158          />159        ) : (160          <>161            {showFeatured && (162              <section className="mb-14" aria-labelledby="grands-marches">163                <SectionHead id="grands-marches" title={complete ? "Les grands marchés" : "Les grandes villes"} text="Nombre d'inscriptions actives et prix médian demandé." />164                {featuredPending ? (165                  <ul aria-hidden className="mt-3 grid grid-cols-1 gap-x-12 sm:grid-cols-2">166                    {Array.from({ length: FEATURED }, (_, i) => (167                      <li key={i} className="flex min-h-14 items-center justify-between gap-4 border-b border-line">168                        <span className="skeleton h-5" style={{ width: `${30 + ((i * 13) % 24)}%` }} />169                        <span className="skeleton h-4 w-40" />170                      </li>171                    ))}172                  </ul>173                ) : (174                  <Rows className="mt-3 grid grid-cols-1 gap-x-12 sm:grid-cols-2">175                    {featured.map((v) => (176                      <BigRow key={v.slug} v={v} />177                    ))}178                  </Rows>179                )}180              </section>181            )}182183            <section aria-labelledby="toutes-les-villes">184              <SectionHead185                id="toutes-les-villes"186                title={needle ? "Résultats" : "Toutes les villes"}187                aside={188                  <span className="num text-[0.86rem] text-ink-3" aria-live="polite">189                    {plural(rows.length, "ville", "villes")}190                  </span>191                }192              />193              {groups ? (194                <div className="mt-4 space-y-9">195                  {groups.map(([letter, list]) => (196                    <div key={letter} id={`lettre-${letter}`} className="grid scroll-mt-24 gap-x-8 lg:scroll-mt-48 lg:grid-cols-[3rem_1fr]">197                      <h3 className="text-[1.75rem] leading-none text-ink-3 max-lg:mb-2">{letter}</h3>198                      <div role="list" className={COLS}>199                        {list.map((v) => (200                          <Row key={v.slug} v={v} />201                        ))}202                      </div>203                    </div>204                  ))}205                </div>206              ) : (207                <>208                  <Rows resetKey={sort} className={`mt-3 ${COLS}`}>209                    {rows.slice(0, count).map((v) => (210                      <Row key={v.slug} v={v} />211                    ))}212                  </Rows>213                  {sentinel}214                </>215              )}216            </section>217          </>218        )}219      </div>220    </>221  );222}223
Files main
Menu

Theme