SPB Git

Repository Public

Location.tsx 13.3 KB 271 lines tsx

1// Emplacement et proximité : la carte, les commerces, les services, le2// transport en commun, l'essence. Les lieux viennent d'OpenStreetMap (avec la3// fiche) et des grandes enseignes (chargées à l'approche de la section).45import { useMemo, useRef, useState } from "react";6import { useQuery } from "@tanstack/react-query";7import type { Map as MbMap } from "mapbox-gl";8import {9  Baby, BookOpen, Bus, Coffee, Cross, Dumbbell, Fuel, GraduationCap, Hospital, MapPin, Minus, Pill as PillIcon, Plus, ShoppingBasket, Store, TrainFront, Trees,10} from "lucide-react";11import { fetchCommerces, fetchGaz, type CommerceItem, type Property } from "@/lib/api.propriete";12import { cn } from "@/lib/cn";13import { fmtDist } from "@/lib/format";14import { useInView } from "@/lib/hooks";15import { useMotionAllowed } from "@/lib/motion";16import { useTheme } from "@/lib/store";17import { PropertyMap, type MapPoint } from "@/map/PropertyMap";18import { Sheet } from "@/ui/Sheet";19import { dec1, Lines, MoreLink, Panel, Section, SourceLine, Tile } from "./kit";2021type Lucide = typeof MapPin;2223const POI: Record<string, { icon: Lucide; label: string; color: string }> = {24  metro: { icon: TrainFront, label: "Métro", color: "var(--ink-2)" },25  bus: { icon: Bus, label: "Arrêt de bus", color: "var(--ink-2)" },26  epicerie: { icon: ShoppingBasket, label: "Épicerie", color: "var(--brand)" },27  depanneur: { icon: Store, label: "Dépanneur", color: "var(--brand)" },28  pharmacie: { icon: PillIcon, label: "Pharmacie", color: "var(--brand)" },29  ecole: { icon: GraduationCap, label: "École", color: "var(--brand)" },30  garderie: { icon: Baby, label: "Garderie", color: "var(--brand)" },31  bibliotheque: { icon: BookOpen, label: "Bibliothèque", color: "var(--brand)" },32  clinique: { icon: Cross, label: "Clinique", color: "var(--brand)" },33  hopital: { icon: Hospital, label: "Hôpital", color: "var(--brand)" },34  cafe: { icon: Coffee, label: "Café", color: "var(--brand)" },35  parc: { icon: Trees, label: "Parc", color: "var(--brand)" },36  gym: { icon: Dumbbell, label: "Gym", color: "var(--brand)" },37};3839const GROUPS: { key: string; title: string; cats: string[] }[] = [40  { key: "transport", title: "Transport", cats: ["metro", "bus"] },41  { key: "courses", title: "Courses", cats: ["epicerie", "depanneur", "pharmacie"] },42  { key: "famille", title: "Études et famille", cats: ["ecole", "garderie", "bibliotheque"] },43  { key: "sante", title: "Santé", cats: ["clinique", "hopital"] },44  { key: "quartier", title: "Vie de quartier", cats: ["cafe", "parc", "gym"] },45];4647const TRANSIT_IDS = new Set(["metro_station", "rem_station", "arret_bus", "gare_train"]);48const BANNER_CAT: Record<string, string> = {49  metro_station: "Station de métro", rem_station: "Station du REM", arret_bus: "Arrêt de bus", gare_train: "Gare de train",50  costco: "Entrepôt", walmart: "Grande surface", metro: "Épicerie", iga: "Épicerie", maxi: "Épicerie", superc: "Épicerie", provigo: "Épicerie",51  canadiantire: "Quincaillerie", dollarama: "Magasin à 1 $", saq: "SAQ", pharmaprix: "Pharmacie", jeancoutu: "Pharmacie", homedepot: "Rénovation", rona: "Rénovation",52};5354interface Row {55  key: string;56  icon: Lucide;57  cat: string;58  name: string;59  dist: number;60  color: string;61  lat?: number;62  lng?: number;63}6465const walkMin = (m: number) => Math.max(1, Math.round((m * 1.3) / 80));6667function RowItem({ r, active, onHover }: { r: Row; active: boolean; onHover: (k: string | null) => void }) {68  const Icon = r.icon;69  return (70    <li71      onMouseEnter={() => onHover(r.key)}72      onMouseLeave={() => onHover(null)}73      className={cn("flex min-w-0 items-center gap-3 rounded-[8px] px-2 py-2 transition-colors duration-150", active && "bg-surface-2")}74    >75      <span className="grid size-9 shrink-0 place-items-center rounded-[8px] bg-surface-2 text-ink-2">76        <Icon className="size-4.5" />77      </span>78      <span className="min-w-0 flex-1">79        <span className="block truncate text-[0.93rem] font-medium text-ink">{r.name}</span>80        {r.cat !== r.name && <span className="block truncate text-xs text-ink-3">{r.cat}</span>}81      </span>82      <span className="num shrink-0 text-right">83        <span className="block text-[0.9rem] font-semibold text-ink">{fmtDist(r.dist)}</span>84        {r.dist <= 1600 && <span className="block text-[0.72rem] text-ink-3">{walkMin(r.dist)} min à pied</span>}85      </span>86    </li>87  );88}8990function Gas({ lat, lng, enabled }: { lat: number; lng: number; enabled: boolean }) {91  const [sheet, setSheet] = useState(false);92  const q = useQuery({ queryKey: ["gaz", lat, lng], queryFn: () => fetchGaz(lat, lng, 60), enabled, staleTime: 6e5, retry: 0 });93  const allowed = useMotionAllowed();94  const d = q.data;95  if (!d || !d.stations?.length) return null;96  const cents = (v: number | null | undefined) => (v == null ? "—" : `${dec1(v)} ¢`);97  return (98    <Panel icon={<Fuel className="size-5" />} title="Essence à proximité" className={cn("mt-5", allowed && "lk-rise")}>99      <div className="grid grid-cols-3 gap-x-4 gap-y-3">100        <Tile tone="good" value={cents(d.min_regulier)} label="Meilleur prix" />101        <Tile value={cents(d.mediane_regulier)} label="Médiane du secteur" />102        <Tile value={d.n} label={`Stations à moins de ${fmtDist(d.rayon_m)}`} />103      </div>104      <ul className="mt-3 divide-y divide-line">105        {d.stations.slice(0, 3).map((s, i) => (106          <li key={i} className="flex items-center justify-between gap-3 py-2.5 text-[0.92rem]">107            <span className="min-w-0">108              <span className="block truncate font-medium text-ink">109                {s.nom}110                {s.moins_chere && <span className="ml-2 rounded-[6px] bg-good-soft px-1.5 py-0.5 text-[0.68rem] font-medium text-good">la moins chère</span>}111              </span>112              <span className="text-xs text-ink-3">{fmtDist(s.dist_m)}</span>113            </span>114            <span className="num shrink-0 font-semibold text-ink">115              {cents(s.regulier)}116              <span className="ml-0.5 text-xs font-normal text-ink-3">/ L</span>117            </span>118          </li>119        ))}120      </ul>121      {d.stations.length > 3 && <MoreLink onClick={() => setSheet(true)}>Voir les {d.stations.length} stations</MoreLink>}122      <SourceLine>Prix du régulier, gazquebec.ca{d.maj ? ` · mis à jour ${d.maj}` : ""}</SourceLine>123      <Sheet open={sheet} onClose={() => setSheet(false)} title="Stations-service" size="lg">124        <ul className="divide-y divide-line">125          {d.stations.map((s, i) => (126            <li key={i} className="flex items-center justify-between gap-3 py-3 text-[0.92rem]">127              <span className="min-w-0">128                <span className="block truncate font-medium text-ink">{s.nom}</span>129                <span className="block truncate text-xs text-ink-3">130                  {fmtDist(s.dist_m)}131                  {s.adresse ? ` · ${s.adresse}` : ""} · super {cents(s.super)} · diesel {cents(s.diesel)}132                </span>133              </span>134              <span className="num shrink-0 font-semibold text-ink">{cents(s.regulier)}</span>135            </li>136          ))}137        </ul>138      </Sheet>139    </Panel>140  );141}142143export function hasLocation(l: Property) {144  return (l.lat != null && l.lng != null) || (l.poi?.length ?? 0) > 0;145}146147export function Location({ p: l }: { p: Property }) {148  const theme = useTheme();149  const [ref, inView] = useInView<HTMLDivElement>("500px");150  const [active, setActive] = useState<string | null>(null);151  const [tab, setTab] = useState("tout");152  const mapRef = useRef<MbMap | null>(null);153  const geo = l.lat != null && l.lng != null;154  const lat = l.lat ?? 0;155  const lng = l.lng ?? 0;156157  const commerces = useQuery({ queryKey: ["commerces", lat, lng], queryFn: () => fetchCommerces(lat, lng), enabled: inView && geo, staleTime: 6e5, retry: 0 });158159  const { rows, byGroup } = useMemo(() => {160    const pois: Row[] = (l.poi ?? [])161      .filter((p) => POI[p.cat])162      .map((p) => ({ key: `p-${p.cat}`, icon: POI[p.cat]!.icon, cat: POI[p.cat]!.label, name: (p.name || "").trim() || POI[p.cat]!.label, dist: p.dist_m, color: POI[p.cat]!.color, lat: p.lat, lng: p.lng }));163    const toRow = (c: CommerceItem, transit: boolean): Row => ({164      key: `${transit ? "t" : "b"}-${c.id}`,165      icon: transit ? (c.id === "arret_bus" ? Bus : TrainFront) : Store,166      cat: BANNER_CAT[c.id] ?? c.commerce,167      name: c.nom,168      dist: c.dist_m,169      color: transit ? "var(--ink-2)" : "var(--brand)",170      lat: c.lat,171      lng: c.lng,172    });173    const transit = (commerces.data?.transit ?? []).filter((c) => TRANSIT_IDS.has(c.id)).map((c) => toRow(c, true));174    const banners = (commerces.data?.commerces ?? []).map((c) => toRow(c, false));175    const catOf = new Map<string, string>();176    (l.poi ?? []).forEach((p) => catOf.set(`p-${p.cat}`, p.cat));177    const byGroup: Record<string, Row[]> = {};178    for (const g of GROUPS) {179      byGroup[g.key] = [180        ...pois.filter((r) => g.cats.includes(catOf.get(r.key) ?? "")),181        ...(g.key === "transport" ? transit : []),182        ...(g.key === "courses" ? banners : []),183      ].sort((a, b) => a.dist - b.dist);184    }185    // sans doublon évident (même nom à moins de 60 m)186    const all = [...pois, ...transit, ...banners].sort((a, b) => a.dist - b.dist);187    const rows = all.filter((r, i) => !all.slice(0, i).some((o) => o.name === r.name && Math.abs(o.dist - r.dist) < 60));188    return { rows, byGroup };189  }, [l.poi, commerces.data]);190191  const shown = tab === "tout" ? rows.slice(0, 10) : (byGroup[tab] ?? []).slice(0, 12);192  const points = useMemo<MapPoint[]>(193    () => rows.filter((r) => r.lat != null && r.lng != null).slice(0, 28).map((r) => ({ key: r.key, lng: r.lng!, lat: r.lat!, label: `${r.name} · ${fmtDist(r.dist)}`, color: r.color })),194    [rows],195  );196  const tabs = [{ key: "tout", title: "Le plus proche" }, ...GROUPS.filter((g) => (byGroup[g.key]?.length ?? 0) > 0)];197198  if (!geo && !rows.length) return null;199200  return (201    <Section202      id="emplacement"203      title="Emplacement et proximité"204      text={l.address ? `${l.address}${l.city && !l.address.includes(l.city) ? `, ${l.city.replace(/[()]/g, "").trim()}` : ""}` : undefined}205    >206      <div ref={ref} className="space-y-5">207        {geo && (208          <div className="relative h-[300px] overflow-hidden rounded-xl border border-line sm:h-[400px]">209            {inView ? (210              <PropertyMap lng={lng} lat={lat} points={points} activeKey={active} theme={theme} onReady={(m) => (mapRef.current = m)} className="absolute inset-0" />211            ) : (212              <div className="skeleton absolute inset-0 rounded-none" />213            )}214            <div className="absolute right-3 top-3 flex flex-col overflow-hidden rounded-[10px] border border-line bg-surface">215              <button type="button" aria-label="Zoom avant" onClick={() => mapRef.current?.zoomIn()} className="grid size-10 place-items-center text-ink hover:bg-surface-2">216                <Plus className="size-4.5" />217              </button>218              <span className="h-px bg-line-2" />219              <button type="button" aria-label="Zoom arrière" onClick={() => mapRef.current?.zoomOut()} className="grid size-10 place-items-center text-ink hover:bg-surface-2">220                <Minus className="size-4.5" />221              </button>222            </div>223            <a224              href={`https://www.google.com/maps/search/?api=1&query=${lat},${lng}`}225              target="_blank"226              rel="noopener noreferrer"227              className="absolute bottom-3 right-3 inline-flex h-10 items-center gap-1.5 rounded-[8px] border border-line bg-surface px-3 text-[0.8rem] font-medium text-ink transition-colors duration-150 hover:border-ink-3"228            >229              <MapPin className="size-3.5" /> Itinéraire230            </a>231          </div>232        )}233        {geo && inView && commerces.isPending && rows.length === 0 && (234          <div className="card p-5">235            <Lines n={4} />236          </div>237        )}238        {geo && commerces.isSuccess && rows.length === 0 && <p className="text-[0.92rem] text-ink-3">Aucun commerce ni service recensé à proximité de cette adresse.</p>}239        {rows.length > 0 && (240          <div className="card flex flex-col p-4 sm:p-5">241            <div className="no-scrollbar -mx-1 mb-2 flex gap-1.5 overflow-x-auto px-1 pb-1" role="tablist" aria-label="Catégories à proximité">242              {tabs.map((t) => (243                <button244                  key={t.key}245                  type="button"246                  role="tab"247                  aria-selected={tab === t.key}248                  onClick={() => setTab(t.key)}249                  className={cn(250                    "h-10 shrink-0 rounded-[8px] px-3 text-[0.82rem] transition-colors duration-150",251                    tab === t.key ? "bg-ink font-medium text-bg" : "bg-surface-2 text-ink-2 hover:text-ink",252                  )}253                >254                  {t.title}255                </button>256              ))}257            </div>258            <ul key={tab} className="lk-stagger lk-stagger--swap grid grid-cols-1 gap-x-4 sm:grid-cols-2">259              {shown.map((r) => (260                <RowItem key={r.key} r={r} active={active === r.key} onHover={setActive} />261              ))}262            </ul>263            <SourceLine>Distances à vol d'oiseau, temps de marche estimés. OpenStreetMap et Mapbox.</SourceLine>264          </div>265        )}266      </div>267      {geo && <Gas lat={lat} lng={lng} enabled={inView} />}268    </Section>269  );270}271
Files main
Menu

Theme