Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : Vrai-Prix8 * File : src/components/Carte.tsx9 * Module : components10 * Repository : https://git.spboucher.ai/vrai-prix11 * Created : 2026-11-2612 * Last Modified : 2026-11-2613 *14 * Author : Simon-Pierre Boucher15 * Position : Professor of Finance16 * Institution : Université du Québec en Outaouais (UQO)17 * Organization : SP Boucher18 * Website : https://spboucher.ai19 * Git : https://git.spboucher.ai20 *21 * Preferred Contact: contact@spboucher.ai22 * Development : dev@spboucher.ai23 * Support : support@spboucher.ai24 * Security/Admin : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142"use client";43// Carte de recherche : Mapbox GL direct (aucun paquet intermédiaire).44// Pastilles de VALEURS ESTIMÉES 2026 regroupées en grappes, chargement piloté45// par la zone visible (annulation des requêtes dépassées), aperçu d'une unité.46// À charger via next/dynamic({ ssr: false }) : Mapbox GL est navigateur seul.47import { useEffect, useRef, useState } from "react";48import Link from "next/link";49import mapboxgl from "mapbox-gl";50import "mapbox-gl/dist/mapbox-gl.css";51import { useLang } from "@/components/LangContext";52import {53 MAPBOX_TOKEN,54 MIN_ZOOM_FETCH,55 TYPE_FR,56 unitesDansZone,57 valeurCourte,58 type PointUnite,59} from "@/lib/carte";6061const CENTRE_DEFAUT: [number, number] = [-73.6646, 45.5421]; // Montréal62const SOURCE = "unites";63const ENCRE = "#141814";64const ROUGE = "#d8372e";6566const argent = (v: number | null) =>67 v == null68 ? "—"69 : new Intl.NumberFormat("fr-CA", { style: "currency", currency: "CAD", maximumFractionDigits: 0 }).format(v);7071function versGeoJSON(points: PointUnite[]): GeoJSON.FeatureCollection {72 return {73 type: "FeatureCollection",74 features: points.map((p) => ({75 type: "Feature",76 geometry: { type: "Point", coordinates: [p.lng, p.lat] },77 properties: { ...p, etiquette: valeurCourte(p.est2026) },78 })),79 };80}8182export default function Carte() {83 const { lang } = useLang();84 const fr = lang === "fr";85 const conteneur = useRef<HTMLDivElement>(null);86 const carte = useRef<mapboxgl.Map | null>(null);87 const [zoom, setZoom] = useState(13.5);88 const [nombre, setNombre] = useState<number | null>(null);89 const [erreur, setErreur] = useState(false);90 const [choix, setChoix] = useState<PointUnite | null>(null);9192 useEffect(() => {93 if (!conteneur.current || carte.current) return;94 mapboxgl.accessToken = MAPBOX_TOKEN;95 const m = new mapboxgl.Map({96 container: conteneur.current,97 style: "mapbox://styles/mapbox/light-v11",98 center: CENTRE_DEFAUT,99 zoom: 13.5,100 attributionControl: true,101 });102 carte.current = m;103 m.addControl(new mapboxgl.NavigationControl({ showCompass: false }), "top-right");104105 let annule: AbortController | null = null;106107 const charger = async () => {108 const z = m.getZoom();109 setZoom(z);110 const src = m.getSource(SOURCE) as mapboxgl.GeoJSONSource | undefined;111 if (!src) return;112 if (z < MIN_ZOOM_FETCH) {113 src.setData(versGeoJSON([]));114 setNombre(null);115 return;116 }117 annule?.abort();118 annule = new AbortController();119 const b = m.getBounds();120 if (!b) return;121 try {122 const pts = await unitesDansZone(123 { west: b.getWest(), south: b.getSouth(), east: b.getEast(), north: b.getNorth() },124 annule.signal125 );126 src.setData(versGeoJSON(pts));127 setNombre(pts.length);128 setErreur(false);129 } catch (e) {130 if ((e as Error).name !== "AbortError") setErreur(true);131 }132 };133134 m.on("load", () => {135 m.addSource(SOURCE, {136 type: "geojson",137 data: versGeoJSON([]),138 cluster: true,139 clusterMaxZoom: 15,140 clusterRadius: 44,141 });142 m.addLayer({143 id: "grappes",144 type: "circle",145 source: SOURCE,146 filter: ["has", "point_count"],147 paint: {148 "circle-color": ENCRE,149 "circle-radius": ["step", ["get", "point_count"], 15, 25, 19, 100, 24],150 "circle-stroke-width": 1.5,151 "circle-stroke-color": "#ffffff",152 },153 });154 m.addLayer({155 id: "grappes-nombre",156 type: "symbol",157 source: SOURCE,158 filter: ["has", "point_count"],159 layout: { "text-field": ["get", "point_count_abbreviated"], "text-size": 12, "text-font": ["DIN Pro Medium", "Arial Unicode MS Bold"] },160 paint: { "text-color": "#ffffff" },161 });162 m.addLayer({163 id: "unites",164 type: "circle",165 source: SOURCE,166 filter: ["!", ["has", "point_count"]],167 paint: { "circle-color": ROUGE, "circle-radius": 6, "circle-stroke-width": 1.5, "circle-stroke-color": "#ffffff" },168 });169 m.addLayer({170 id: "unites-valeur",171 type: "symbol",172 source: SOURCE,173 filter: ["!", ["has", "point_count"]],174 minzoom: 15,175 layout: {176 "text-field": ["get", "etiquette"],177 "text-size": 11,178 "text-offset": [0, 1.2],179 "text-anchor": "top",180 "text-font": ["DIN Pro Medium", "Arial Unicode MS Bold"],181 },182 paint: { "text-color": ENCRE, "text-halo-color": "#ffffff", "text-halo-width": 1.4 },183 });184185 m.on("click", "grappes", (e) => {186 const f = e.features?.[0];187 if (!f) return;188 const g = f.geometry as GeoJSON.Point;189 m.easeTo({ center: g.coordinates as [number, number], zoom: m.getZoom() + 1.6 });190 });191 m.on("click", "unites", (e) => {192 // les propriétés d'une entité GeoJSON reviennent aplaties (nombres ou chaînes)193 const p = e.features?.[0]?.properties as Record<string, string | number | null> | undefined;194 if (!p) return;195 const texte = (v: string | number | null | undefined) => (v == null || v === "" ? null : String(v));196 setChoix({197 id: String(p.id),198 adresse: texte(p.adresse),199 apt: texte(p.apt),200 municipalite: texte(p.municipalite),201 typeProp: texte(p.typeProp),202 lat: Number(p.lat),203 lng: Number(p.lng),204 est2026: p.est2026 == null || p.est2026 === "" ? null : Number(p.est2026),205 });206 });207 for (const couche of ["grappes", "unites"]) {208 m.on("mouseenter", couche, () => (m.getCanvas().style.cursor = "pointer"));209 m.on("mouseleave", couche, () => (m.getCanvas().style.cursor = ""));210 }211 charger();212 });213 m.on("moveend", charger);214215 return () => {216 annule?.abort();217 m.remove();218 carte.current = null;219 };220 }, []);221222 const localiser = () => {223 navigator.geolocation?.getCurrentPosition(224 (pos) => carte.current?.flyTo({ center: [pos.coords.longitude, pos.coords.latitude], zoom: 15.5 }),225 () => undefined,226 { enableHighAccuracy: true, timeout: 8000 }227 );228 };229230 const loin = zoom < MIN_ZOOM_FETCH;231 return (232 <div className="vpm-wrap">233 <div ref={conteneur} className="vpm-map" />234 <div className="vpm-ctl">235 <button type="button" onClick={localiser}>236 {fr ? "Me localiser" : "Locate me"}237 </button>238 </div>239 <div className="vpm-chip" role="status">240 {erreur241 ? fr242 ? "Chargement impossible, déplacez la carte pour réessayer"243 : "Loading failed, move the map to retry"244 : loin245 ? fr246 ? "Zoomez pour voir les valeurs estimées"247 : "Zoom in to see estimated values"248 : nombre != null249 ? fr250 ? `${nombre.toLocaleString("fr-CA")} propriétés affichées`251 : `${nombre.toLocaleString("en-CA")} properties shown`252 : fr253 ? "Chargement…"254 : "Loading…"}255 </div>256 {choix && (257 <div className="vpm-card">258 <button type="button" className="vpm-card-close" onClick={() => setChoix(null)} aria-label={fr ? "Fermer" : "Close"}>259 ✕260 </button>261 <div className="vpm-pop">262 <div className="klabel">{fr ? "Estimation 2026" : "2026 estimate"}</div>263 <div className="vpm-pop-value">{argent(choix.est2026)}</div>264 <div className="vpm-pop-addr">265 {choix.adresse}266 {choix.apt ? ` app. ${choix.apt}` : ""}267 </div>268 <div className="vpm-pop-meta">269 {[choix.municipalite, choix.typeProp ? TYPE_FR[choix.typeProp] ?? choix.typeProp : null].filter(Boolean).join(" · ")}270 </div>271 <Link href={`/estimation/${encodeURIComponent(choix.id)}`} className="vpm-pop-cta">272 {fr ? "Voir l'estimation complète" : "See full estimate"}273 </Link>274 </div>275 </div>276 )}277 </div>278 );279}280