SPB Git

Repository Public

HomeMap.tsx 7.3 KB 186 lines tsx

1// Carte de l'accueil : où se trouvent les logements en ce moment.2// Même langage que la carte de recherche : fond maison, nappe de densité forêt,3// points nets des immeubles quand on s'approche, et plaques des villes (nom et4// nombre de logements). Un clic ouvre la recherche à cet endroit.56import { useEffect, useRef, useState } from "react";7import type { GeoJSONSource, Map as MbMap, Marker } from "mapbox-gl";8import type { LightsResponse } from "@/lib/api";9import { fmtInt } from "@/lib/format";10import type { Theme } from "@/lib/store";11import { createMap, loadMapbox, mapSupported, presetFor, setPreset } from "./mapbox";12import { easeOutCubic } from "./plaques";13import { mapPalette } from "./tags";14import "./map.css";1516const heatColor = (theme: Theme) => {17  const h = mapPalette(theme).heat;18  return ["interpolate", ["linear"], ["heatmap-density"], 0, h[0], 0.25, h[1], 0.6, h[2], 1, h[3]] as unknown as string;19};2021export function HomeMap({22  lights,23  theme,24  center,25  zoom = 10.4,26  onPick,27  className,28}: {29  lights: LightsResponse | undefined;30  theme: Theme;31  center: [number, number];32  zoom?: number;33  onPick: (lng: number, lat: number, zoom: number) => void;34  className?: string;35}) {36  const el = useRef<HTMLDivElement>(null);37  const mapRef = useRef<MbMap | null>(null);38  const plaques = useRef<Marker[]>([]);39  const [ready, setReady] = useState(false);40  const pick = useRef(onPick);41  pick.current = onPick;42  const themeRef = useRef(theme);43  themeRef.current = theme;4445  useEffect(() => {46    if (!el.current || !mapSupported()) return;47    let dead = false;48    let map: MbMap | null = null;49    createMap(el.current, presetFor(theme), { center, zoom, scrollZoom: false, dragRotate: false, pitchWithRotate: false, touchPitch: false })50      .then((m) => {51        if (dead) return m.remove();52        map = m;53        mapRef.current = m;54        m.touchZoomRotate.disableRotation();55        m.on("style.load", () => {56          const p = mapPalette(themeRef.current);57          m.addSource("density", { type: "geojson", data: { type: "FeatureCollection", features: [] } });58          // nappe de densité : pondérée par le nombre de logements de chaque pâté de maisons59          m.addLayer({60            id: "densite",61            type: "heatmap",62            source: "density",63            slot: "middle",64            maxzoom: 13.5,65            paint: {66              "heatmap-weight": ["interpolate", ["linear"], ["get", "n"], 1, 0.35, 12, 1],67              "heatmap-intensity": ["interpolate", ["linear"], ["zoom"], 7, 0.07, 10, 0.3, 12, 0.8],68              "heatmap-radius": ["interpolate", ["linear"], ["zoom"], 7, 8, 10, 17, 12, 30],69              "heatmap-color": heatColor(themeRef.current),70              "heatmap-opacity": ["interpolate", ["linear"], ["zoom"], 7, 0.95, 11.5, 0.9, 13.5, 0],71            },72          });73          // immeubles : petits points nets, de plus en plus lisibles en s'approchant74          m.addLayer({75            id: "immeubles",76            type: "circle",77            source: "density",78            minzoom: 10.6,79            paint: {80              "circle-radius": ["interpolate", ["linear"], ["zoom"], 10.6, 0.9, 12, ["+", 1.3, ["*", 0.35, ["ln", ["+", 1, ["get", "n"]]]]], 15, ["+", 3, ["*", 1.4, ["ln", ["+", 1, ["get", "n"]]]]]],81              "circle-color": p.dotGood,82              "circle-opacity": ["interpolate", ["linear"], ["zoom"], 10.6, 0, 11.4, 0.85],83              "circle-stroke-width": ["interpolate", ["linear"], ["zoom"], 11, 0, 13, 1],84              "circle-stroke-color": p.dotStroke,85              "circle-emissive-strength": 1,86            },87          });88          setReady(true);89        });90        m.on("click", (e) => pick.current(e.lngLat.lng, e.lngLat.lat, Math.max(12.5, m.getZoom() + 1.5)));91        m.getCanvas().style.cursor = "pointer";92      })93      .catch(() => undefined);94    return () => {95      dead = true;96      plaques.current.forEach((mk) => mk.remove());97      plaques.current = [];98      map?.remove();99      mapRef.current = null;100    };101    // créée une fois102    // eslint-disable-next-line react-hooks/exhaustive-deps103  }, []);104105  useEffect(() => {106    const m = mapRef.current;107    if (!ready || !m) return;108    setPreset(m, presetFor(theme));109    const p = mapPalette(theme);110    m.setPaintProperty("densite", "heatmap-color", heatColor(theme));111    m.setPaintProperty("immeubles", "circle-color", p.dotGood);112    m.setPaintProperty("immeubles", "circle-stroke-color", p.dotStroke);113  }, [theme, ready]);114115  useEffect(() => {116    const m = mapRef.current;117    if (!ready || !m || !lights) return;118    (m.getSource("density") as GeoJSONSource | undefined)?.setData({119      type: "FeatureCollection",120      features: lights.cells.map(([lng, lat, n]) => ({ type: "Feature", geometry: { type: "Point", coordinates: [lng, lat] }, properties: { n } })),121    });122    // plaques des villes : le nom, puis le nombre de logements123    let cancelled = false;124    // les plaques ne se chevauchent jamais : la ville la plus fournie garde sa place125    const declutter = () => {126      const placed: DOMRect[] = [];127      const frame = m.getContainer().getBoundingClientRect();128      for (const mk of plaques.current) {129        const node = mk.getElement();130        node.style.visibility = "";131        const r = node.getBoundingClientRect();132        const pad = 6;133        const outside = r.right < frame.left || r.left > frame.right || r.bottom < frame.top || r.top > frame.bottom;134        const hit = placed.some((q) => r.left < q.right + pad && r.right > q.left - pad && r.top < q.bottom + pad && r.bottom > q.top - pad);135        if (hit && !outside) node.style.visibility = "hidden";136        else if (!outside) placed.push(r);137      }138    };139    m.on("moveend", declutter);140    void loadMapbox().then((mapboxgl) => {141      if (cancelled) return;142      plaques.current.forEach((mk) => mk.remove());143      plaques.current = lights.cities144        .filter((c) => c.n >= 120)145        .slice(0, 18)146        .map((c, i) => {147          const wrap = document.createElement("div");148          wrap.style.zIndex = String(20 - i);149          const b = document.createElement("button");150          b.type = "button";151          b.className = "lk-plaque lk-plaque--city";152          b.style.animationDelay = `${Math.min(i, 8) * 35}ms`;153          b.setAttribute("aria-label", `${c.city} : ${c.n} logements. Voir sur la carte.`);154          const name = document.createElement("span");155          name.textContent = c.city;156          const n = document.createElement("small");157          n.textContent = `${fmtInt(c.n)} logements`;158          b.append(name, n);159          b.addEventListener("click", (ev) => {160            ev.stopPropagation();161            pick.current(c.lng, c.lat, c.n > 3000 ? 11.6 : 12.4);162          });163          wrap.appendChild(b);164          return new mapboxgl.Marker({ element: wrap, anchor: "center" }).setLngLat([c.lng, c.lat]).addTo(m);165        });166      declutter();167    });168    return () => {169      cancelled = true;170      m.off("moveend", declutter);171    };172  }, [lights, ready]);173174  useEffect(() => {175    mapRef.current?.easeTo({ center, zoom, duration: 900, easing: easeOutCubic });176    // recentrage quand la ville change177    // eslint-disable-next-line react-hooks/exhaustive-deps178  }, [center[0], center[1], zoom]);179180  return (181    <div className={className}>182      <div ref={el} className="size-full" role="img" aria-label="Carte des logements disponibles" />183    </div>184  );185}186
Files main
Menu

Theme