SPB Git

Repository Public

PropertyMap.tsx 5.3 KB 169 lines tsx

1// Mini-carte de la fiche de propriété : la propriété et ce qui l'entoure, sur2// un fond calme. Pas de zoom à la molette : la page défile.3// Dérivée de FicheMap (Lou-Ka), sans dépendance directe à la marque.45import { useEffect, useRef, useState } from "react";6import type { Map as MbMap, Marker } from "mapbox-gl";7import type { Theme } from "@/lib/store";8import { createMap, loadMapbox, mapSupported, presetFor, setPreset } from "./mapbox";9import "./map.css";1011export interface MapPoint {12  key: string;13  lng: number;14  lat: number;15  label: string;16  /** couleur CSS du point */17  color: string;18}1920/** Marqueur de la propriété : une maison et sa porte, aux couleurs du thème21 *  (le socle pourra y substituer le symbole de la marque). */22function homeEl() {23  const wrap = document.createElement("div");24  wrap.style.zIndex = "4";25  const el = document.createElement("div");26  el.className = "lk-pin";27  el.innerHTML =28    `<svg width="34" height="34" viewBox="0 0 34 34" aria-hidden="true">` +29    `<path d="M17 3.5 4.5 14v15.5h25V14Z" fill="var(--brand)" stroke="var(--surface)" stroke-width="2" stroke-linejoin="round"/>` +30    `<path d="M14 29.5v-9.5h6v9.5" fill="var(--accent)"/></svg>`;31  wrap.appendChild(el);32  return wrap;33}3435function dotEl(p: MapPoint) {36  const el = document.createElement("button");37  el.type = "button";38  el.title = p.label;39  el.setAttribute("aria-label", p.label);40  el.dataset.key = p.key;41  el.style.cssText = `width:12px;height:12px;border-radius:50%;background:${p.color};border:2px solid var(--surface);box-shadow:var(--shadow);cursor:pointer;padding:0;`;42  return el;43}4445export function PropertyMap({46  lng,47  lat,48  points,49  activeKey,50  theme,51  onReady,52  className,53}: {54  lng: number;55  lat: number;56  points: MapPoint[];57  activeKey?: string | null;58  theme: Theme;59  onReady?: (map: MbMap) => void;60  className?: string;61}) {62  const el = useRef<HTMLDivElement>(null);63  const mapRef = useRef<MbMap | null>(null);64  const markers = useRef<Map<string, Marker>>(new Map());65  const [ready, setReady] = useState(false);66  const [failed, setFailed] = useState(false);67  const readyCb = useRef(onReady);68  readyCb.current = onReady;6970  useEffect(() => {71    if (!el.current) return;72    if (!mapSupported()) {73      setFailed(true);74      return;75    }76    let dead = false;77    let map: MbMap | null = null;78    Promise.all([79      createMap(el.current, presetFor(theme), {80        center: [lng, lat],81        zoom: 14.8,82        pitch: 0,83        bearing: 0,84        scrollZoom: false,85        dragRotate: true,86        maxBounds: undefined,87      }),88      loadMapbox(),89    ])90      .then(([m, mapboxgl]) => {91        if (dead) return m.remove();92        map = m;93        mapRef.current = m;94        m.on("error", (e) => {95          const status = (e.error as { status?: number } | undefined)?.status;96          if (status === 401 || status === 403) setFailed(true);97        });98        new mapboxgl.Marker({ element: homeEl(), anchor: "bottom", offset: [0, -8] }).setLngLat([lng, lat]).addTo(m);99        m.on("style.load", () => {100          setReady(true);101          readyCb.current?.(m);102        });103      })104      .catch(() => setFailed(true));105    return () => {106      dead = true;107      markers.current.clear();108      map?.remove();109      mapRef.current = null;110    };111    // la carte est créée une fois par adresse112    // eslint-disable-next-line react-hooks/exhaustive-deps113  }, [lng, lat]);114115  useEffect(() => {116    const m = mapRef.current;117    if (ready && m) setPreset(m, presetFor(theme));118  }, [theme, ready]);119120  // points d'intérêt121  useEffect(() => {122    const m = mapRef.current;123    if (!ready || !m) return;124    let cancelled = false;125    loadMapbox().then((mapboxgl) => {126      if (cancelled) return;127      markers.current.forEach((mk) => mk.remove());128      markers.current.clear();129      for (const p of points) {130        const mk = new mapboxgl.Marker({ element: dotEl(p), anchor: "center" })131          .setLngLat([p.lng, p.lat])132          .setPopup(new mapboxgl.Popup({ offset: 12, closeButton: false, maxWidth: "240px" }).setHTML(133            `<div style="background:var(--surface);color:var(--ink);border:1px solid var(--line-2);border-radius:8px;padding:6px 10px;font-size:13px;font-weight:500;box-shadow:var(--shadow-lg)">${p.label.replace(/[<>&]/g, "")}</div>`,134          ))135          .addTo(m);136        markers.current.set(p.key, mk);137      }138    });139    return () => {140      cancelled = true;141    };142  }, [points, ready]);143144  // mise en évidence depuis la liste145  useEffect(() => {146    markers.current.forEach((mk, key) => {147      const node = mk.getElement();148      node.style.transform = `${node.style.transform.replace(/ scale\([^)]*\)/, "")}`;149      const inner = node as HTMLElement;150      inner.style.zIndex = key === activeKey ? "5" : "";151      inner.style.outline = key === activeKey ? "2px solid var(--accent)" : "";152      inner.style.outlineOffset = key === activeKey ? "2px" : "";153    });154  }, [activeKey, points]);155156  if (failed) {157    return (158      <div className={className}>159        <div className="grid size-full place-items-center bg-surface-2 p-6 text-center text-sm text-ink-3">La carte ne peut pas s'afficher dans ce navigateur.</div>160      </div>161    );162  }163  return (164    <div className={className}>165      <div ref={el} className="size-full" />166    </div>167  );168}169
Files main
Menu

Theme