SPB Git

Repository Public

MetricViz.tsx 40.3 KB 1,068 lines tsx

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : Vrai-Prix8 * File             : src/components/MetricViz.tsx9 * Module           : components10 * Repository       : https://git.spboucher.ai/vrai-prix11 * Created          : 2026-08-0912 * Last Modified    : 2026-08-2513 *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/**43 * MetricViz — visualisations signature générées par les données du registre.44 * Langage v2 « terminal éditorial » : lignes 2 px, grilles hairline pleines,45 * étiquettes directes sur les marques, point courant rouge signal, infobulles46 * crosshair au pointeur ET au toucher. SVG pur, aucun aléatoire : mêmes données,47 * même dessin. Palette séries validée (CVD 28,6 / contraste ≥ 3:1) :48 * encre #141814 · rouge #d8372e · gris #6b736d.49 */50"use client";51import { useEffect, useRef, useState } from "react";5253/** Nombre localisé (« 1 206,6 » en FR, « 1,206.6 » en EN). */54export function locNum(55  v: number | null | undefined,56  lang: string,57  opts?: { unit?: string; maxFrac?: number }58): string {59  if (v == null) return "—";60  const s = v.toLocaleString(lang === "fr" ? "fr-CA" : "en-CA", {61    maximumFractionDigits: opts?.maxFrac ?? 1,62  });63  return opts?.unit ? `${s} ${opts.unit}` : s;64}6566const MONTHS_FR = ["janv.", "févr.", "mars", "avr.", "mai", "juin", "juil.", "août", "sept.", "oct.", "nov.", "déc."];67const MONTHS_EN = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];68function fmtMonth(month: string, lang: string): string {69  const [y, m] = month.split("-").map(Number);70  const names = lang === "fr" ? MONTHS_FR : MONTHS_EN;71  return `${names[(m ?? 1) - 1]} ${y}`;72}7374/* ---------------------------- compteur animé ---------------------------- */75/** Rendu serveur = valeur finale (jamais « 0 $ » à l'écran) ; anime 0 → valeur au montage. */76export function CountUp({77  value,78  format,79  duration = 900,80}: {81  value: number;82  format: (v: number) => string;83  duration?: number;84}) {85  const [display, setDisplay] = useState(value);8687  useEffect(() => {88    if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;89    let raf = 0;90    const t0 = performance.now();91    const tick = (t: number) => {92      const p = Math.min(1, (t - t0) / duration);93      const eased = 1 - Math.pow(1 - p, 3);94      setDisplay(value * eased);95      if (p < 1) raf = requestAnimationFrame(tick);96    };97    raf = requestAnimationFrame(tick);98    return () => cancelAnimationFrame(raf);99  }, [value, duration]);100101  return <span>{format(display)}</span>;102}103104/* --------------------------- jauge de confiance --------------------------- */105export function ConfidenceDial({106  pct,107  level,108  label,109}: {110  pct: number;111  level: "A" | "B" | "C" | "D";112  label: string;113}) {114  const [mounted, setMounted] = useState(false);115  useEffect(() => {116    const id = setTimeout(() => setMounted(true), 60);117    return () => clearTimeout(id);118  }, []);119  const R = 52;120  const CIRC = Math.PI * R; // demi-cercle121  const frac = mounted ? Math.max(0.02, Math.min(1, pct / 100)) : 0.02;122  const color =123    level === "A" || level === "B"124      ? "var(--ink)"125      : level === "C"126        ? "var(--amber)"127        : "var(--danger)";128  return (129    <div className="flex flex-col items-center" aria-label={`${label} : ${level} ${pct} %`}>130      <svg viewBox="0 0 128 78" className="w-[124px]">131        <path d="M 12 66 A 52 52 0 0 1 116 66" fill="none" stroke="var(--line)" strokeWidth="8" strokeLinecap="butt" />132        <path133          d="M 12 66 A 52 52 0 0 1 116 66"134          fill="none"135          stroke={color}136          strokeWidth="8"137          strokeLinecap="butt"138          strokeDasharray={`${CIRC * frac} ${CIRC}`}139          style={{ transition: "stroke-dasharray 1s cubic-bezier(.2,.8,.2,1)" }}140        />141        {/* graduations */}142        {[0, 0.25, 0.5, 0.75, 1].map((g) => {143          const a = Math.PI * (1 - g);144          const x1 = 64 + Math.cos(a) * 42;145          const y1 = 66 - Math.sin(a) * 42;146          const x2 = 64 + Math.cos(a) * 46;147          const y2 = 66 - Math.sin(a) * 46;148          return <line key={g} x1={x1} y1={y1} x2={x2} y2={y2} stroke="var(--ink)" strokeWidth="1" opacity="0.4" />;149        })}150        {/* pointe de lecture — rouge signal */}151        {(() => {152          const a = Math.PI * (1 - Math.max(0.02, Math.min(1, pct / 100)));153          const x1 = 64 + Math.cos(a) * 44;154          const y1 = 66 - Math.sin(a) * 44;155          const x2 = 64 + Math.cos(a) * 60;156          const y2 = 66 - Math.sin(a) * 60;157          return <line x1={x1} y1={y1} x2={x2} y2={y2} stroke="var(--accent)" strokeWidth="2" />;158        })()}159        <text x="64" y="52" textAnchor="middle" fontSize="27" fontWeight="700" fill="var(--ink)" fontFamily="var(--font-space-grotesk)">160          {level}161        </text>162        <text x="64" y="70" textAnchor="middle" fontSize="10.5" fontWeight="500" fill="var(--ink-2)" fontFamily="var(--font-jetbrains)">163          {pct} %164        </text>165      </svg>166      <p className="klabel mt-1 max-w-[150px] text-center">{label}</p>167    </div>168  );169}170171/* --------------------------- façade de bâtiment --------------------------- */172/** Terrain sans bâtiment : borne d'arpenteur et conifères, pas de fausse maison. */173function VacantGlyph({ lang }: { lang: string }) {174  const tree = (x: number, sc: number) => (175    <g transform={`translate(${x}, 128) scale(${sc})`}>176      <path d="M0,-46 L13,-14 L5,-14 L16,8 L-16,8 L-5,-14 L-13,-14 Z" fill="none" stroke="var(--ink)" strokeWidth="1.6" />177      <rect x="-2.5" y="8" width="5" height="9" fill="var(--ink)" />178    </g>179  );180  return (181    <svg viewBox="0 0 190 150" className="w-full max-w-[210px]" aria-label={lang === "fr" ? "Terrain sans bâtiment" : "Vacant land"}>182      {tree(52, 1)}183      {tree(96, 0.72)}184      {tree(134, 0.9)}185      {/* borne d'arpenteur */}186      <g transform="translate(24, 128)">187        <rect x="-2.5" y="-26" width="5" height="26" fill="var(--ink)" />188        <rect x="-8" y="-34" width="16" height="10" fill="var(--accent)" stroke="var(--ink)" strokeWidth="1.4" />189      </g>190      <line x1="8" y1="145" x2="182" y2="145" stroke="var(--ink)" strokeWidth="1.6" />191      <text x="95" y="120" textAnchor="middle" fontSize="9" fontWeight="700" fontFamily="var(--font-jetbrains)" fill="var(--ink-2)" letterSpacing="2">192        {lang === "fr" ? "SANS BÂTIMENT" : "NO BUILDING"}193      </text>194    </svg>195  );196}197198/** Façade dessinée à partir du registre : étages, logements, genre de construction.199 *  Sans bâtiment au registre (ni aire, ni année, ni étages) → borne d'arpenteur. */200export function BuildingGlyph({201  floors,202  dwellings,203  genre,204  yearBuilt,205  floorAreaM2,206  lang = "fr",207}: {208  floors: number | null;209  dwellings: number | null;210  genre: string | null;211  yearBuilt: number | null;212  floorAreaM2?: number | null;213  lang?: string;214}) {215  if (!floorAreaM2 && !yearBuilt && !floors && !dwellings) {216    return <VacantGlyph lang={lang} />;217  }218  const nF = Math.max(1, Math.min(6, Math.round(floors ?? 1)));219  const nD = Math.max(1, Math.min(24, Math.round(dwellings ?? 1)));220  const winPerFloor = Math.max(1, Math.min(4, Math.ceil(nD / nF)));221  const W = 190;222  const bw = 64 + winPerFloor * 18;223  const bx = (W - bw) / 2;224  const fh = 24;225  const groundY = 128;226  const bodyTop = groundY - nF * fh;227  const mansard = (genre ?? "").toLowerCase().includes("mansard");228  const flat = (genre ?? "").toLowerCase().includes("plain-pied") && nF === 1;229230  const windows: React.ReactNode[] = [];231  for (let f = 0; f < nF; f++) {232    for (let wi = 0; wi < winPerFloor; wi++) {233      const idx = f * winPerFloor + wi;234      windows.push(235        <rect236          key={`${f}-${wi}`}237          x={bx + 14 + wi * ((bw - 28) / winPerFloor) + ((bw - 28) / winPerFloor - 12) / 2}238          y={bodyTop + f * fh + 6}239          width="12"240          height="11"241          fill={idx < nD ? "var(--accent)" : "var(--surface-2)"}242          stroke="var(--ink)"243          strokeWidth="1"244          className="vv-win"245          style={{ animationDelay: `${idx * 60}ms` }}246        />247      );248    }249  }250251  return (252    <svg viewBox={`0 0 ${W} 150`} className="w-full max-w-[210px]" aria-label="Silhouette du bâtiment selon le registre">253      {/* soleil-repère */}254      <circle cx={W - 22} cy="22" r="9" fill="none" stroke="var(--ink)" strokeWidth="1.2" />255      <circle cx={W - 22} cy="22" r="3" fill="var(--accent)" />256      {/* corps */}257      <rect x={bx} y={bodyTop} width={bw} height={nF * fh} fill="var(--surface)" stroke="var(--ink)" strokeWidth="1.6" />258      {/* séparations d'étages */}259      {Array.from({ length: nF - 1 }, (_, i) => (260        <line key={i} x1={bx} y1={bodyTop + (i + 1) * fh} x2={bx + bw} y2={bodyTop + (i + 1) * fh} stroke="var(--ink)" strokeWidth="0.8" opacity="0.35" />261      ))}262      {/* toit */}263      {flat ? (264        <rect x={bx - 6} y={bodyTop - 8} width={bw + 12} height="8" fill="var(--ink)" />265      ) : mansard ? (266        <path d={`M ${bx - 6} ${bodyTop} L ${bx + 10} ${bodyTop - 20} L ${bx + bw - 10} ${bodyTop - 20} L ${bx + bw + 6} ${bodyTop} Z`} fill="var(--ink)" />267      ) : (268        <path d={`M ${bx - 8} ${bodyTop} L ${bx + bw / 2} ${bodyTop - 24} L ${bx + bw + 8} ${bodyTop} Z`} fill="var(--ink)" />269      )}270      {/* cheminée */}271      <rect x={bx + bw - 22} y={bodyTop - (flat ? 20 : 30)} width="8" height={flat ? 14 : 18} fill="var(--ink)" />272      {windows}273      {/* porte */}274      <rect x={bx + bw / 2 - 7} y={groundY - 17} width="14" height="17" fill="var(--ink)" />275      <circle cx={bx + bw / 2 + 3.5} cy={groundY - 8} r="1.4" fill="var(--accent)" />276      {/* sol */}277      <line x1="8" y1={groundY} x2={W - 8} y2={groundY} stroke="var(--ink)" strokeWidth="1.6" />278      {/* millésime gravé */}279      {yearBuilt && (280        <text x={W / 2} y="146" textAnchor="middle" fontSize="10" fontWeight="700" fontFamily="var(--font-jetbrains)" fill="var(--ink-2)" letterSpacing="2">281          ANNO {yearBuilt}282        </text>283      )}284    </svg>285  );286}287288/* ----------------------------- schéma du terrain ----------------------------- */289/** Terrain à l'échelle réelle : frontage × profondeur déduite de la superficie. */290export function LotDiagram({291  areaM2,292  frontageM,293  footprintM2,294  lang,295  isCondo,296}: {297  areaM2: number | null;298  frontageM: number | null;299  footprintM2: number | null;300  lang: string;301  isCondo?: boolean;302}) {303  if (!areaM2 || areaM2 <= 0) {304    return (305      <svg viewBox="0 0 190 150" className="w-full max-w-[210px]" aria-label={lang === "fr" ? "Terrain non applicable" : "Lot not applicable"}>306        <rect x="30" y="30" width="130" height="86" fill="var(--surface-2)" stroke="var(--ink)" strokeWidth="1.2" strokeDasharray="5 5" />307        <text x="95" y="66" textAnchor="middle" fontSize="20" fill="var(--ink-3)">⌂</text>308        <text x="95" y="90" textAnchor="middle" fontSize="8.5" fontWeight="700" fontFamily="var(--font-jetbrains)" fill="var(--ink-2)" letterSpacing="1">309          {isCondo310            ? lang === "fr" ? "QUOTE-PART DE COPROPRIÉTÉ" : "CONDOMINIUM SHARE"311            : lang === "fr" ? "TERRAIN NON INSCRIT AU RÔLE" : "LOT NOT ON ROLL"}312        </text>313        <text x="95" y="104" textAnchor="middle" fontSize="7" fontFamily="var(--font-jetbrains)" fill="var(--ink-3)">314          {isCondo315            ? lang === "fr" ? "terrain commun indivis" : "undivided common land"316            : "—"}317        </text>318      </svg>319    );320  }321  const front = frontageM && frontageM > 0 ? frontageM : Math.sqrt(areaM2);322  const depth = areaM2 / front;323  const ratio = Math.max(0.25, Math.min(4, depth / front));324  const maxW = 150;325  const maxH = 108;326  let w = maxW;327  let h = w * ratio;328  if (h > maxH) {329    h = maxH;330    w = h / ratio;331  }332  const x = (190 - w) / 2;333  const y = 118 - h;334  // empreinte du bâtiment, à l'échelle de la superficie335  const fpFrac = footprintM2 ? Math.min(0.8, footprintM2 / areaM2) : 0;336  const fw = w * Math.sqrt(fpFrac) * 0.9;337  const fh = h * Math.sqrt(fpFrac) * 0.9;338  const fmtM = (v: number) => `${v.toLocaleString(lang === "fr" ? "fr-CA" : "en-CA", { maximumFractionDigits: 1 })} m`;339340  return (341    <svg viewBox="0 0 190 150" className="w-full max-w-[210px]" aria-label="Schéma du terrain à l'échelle">342      <defs>343        <pattern id="hatch" width="7" height="7" patternTransform="rotate(45)" patternUnits="userSpaceOnUse">344          <line x1="0" y1="0" x2="0" y2="7" stroke="var(--ink)" strokeWidth="0.8" opacity="0.18" />345        </pattern>346      </defs>347      {/* parcelle */}348      <rect x={x} y={y} width={w} height={h} fill="var(--surface-2)" stroke="var(--ink)" strokeWidth="1.6" />349      <rect x={x} y={y} width={w} height={h} fill="url(#hatch)" />350      {/* empreinte bâtiment */}351      {fpFrac > 0.005 && (352        <rect x={x + (w - fw) / 2} y={y + h - fh - h * 0.08} width={fw} height={fh} fill="var(--ink)">353          <title>{lang === "fr" ? "Empreinte approximative du bâtiment" : "Approximate building footprint"}</title>354        </rect>355      )}356      {/* cotes : frontage */}357      <line x1={x} y1={y + h + 12} x2={x + w} y2={y + h + 12} stroke="var(--ink)" strokeWidth="1" />358      <line x1={x} y1={y + h + 8} x2={x} y2={y + h + 16} stroke="var(--ink)" strokeWidth="1" />359      <line x1={x + w} y1={y + h + 8} x2={x + w} y2={y + h + 16} stroke="var(--ink)" strokeWidth="1" />360      <text x={x + w / 2} y={y + h + 24} textAnchor="middle" fontSize="9.5" fontWeight="700" fontFamily="var(--font-jetbrains)" fill="var(--ink)">361        {frontageM ? fmtM(front) : `≈ ${fmtM(front)}`}362      </text>363      {/* cotes : profondeur */}364      <line x1={x - 10} y1={y} x2={x - 10} y2={y + h} stroke="var(--ink)" strokeWidth="1" />365      <line x1={x - 14} y1={y} x2={x - 6} y2={y} stroke="var(--ink)" strokeWidth="1" />366      <line x1={x - 14} y1={y + h} x2={x - 6} y2={y + h} stroke="var(--ink)" strokeWidth="1" />367      <text x={x - 16} y={y + h / 2} textAnchor="middle" fontSize="9.5" fontWeight="700" fontFamily="var(--font-jetbrains)" fill="var(--ink)" transform={`rotate(-90 ${x - 16} ${y + h / 2})`}>368        ≈ {fmtM(depth)}369      </text>370      {/* rue */}371      <line x1="8" y1="136" x2="182" y2="136" stroke="var(--ink)" strokeWidth="1.6" />372      <text x="95" y="147" textAnchor="middle" fontSize="8.5" fontWeight="700" fontFamily="var(--font-jetbrains)" fill="var(--ink-3)" letterSpacing="3">373        {lang === "fr" ? "RUE" : "STREET"}374      </text>375    </svg>376  );377}378379/* ------------------------- composition de la valeur ------------------------- */380export function ValueSplit({381  land,382  building,383  previous,384  total,385  lang,386  labels,387}: {388  land: number | null;389  building: number | null;390  previous: number | null;391  total: number | null;392  lang: string;393  labels: { land: string; building: string; previous: string };394}) {395  const [on, setOn] = useState(false);396  useEffect(() => {397    const id = setTimeout(() => setOn(true), 80);398    return () => clearTimeout(id);399  }, []);400  const l = land ?? 0;401  const b = building ?? 0;402  const sum = l + b;403  if (sum <= 0) return null;404  const lPct = (l / sum) * 100;405  const fmt = (v: number) =>406    new Intl.NumberFormat(lang === "fr" ? "fr-CA" : "en-CA", { style: "currency", currency: "CAD", maximumFractionDigits: 0 }).format(v);407  const delta = previous && previous > 0 && total ? ((total / previous - 1) * 100) : null;408  return (409    <div>410      {/* segments séparés par un jour de 2 px (le fond fait la séparation) */}411      <div className="flex h-7 w-full gap-[2px]">412        {lPct >= 1 && (413          <div414            className="flex items-center justify-center overflow-hidden bg-[var(--chart-3)] transition-[width] duration-1000 ease-out"415            style={{ width: on ? `${lPct}%` : "2%" }}416          >417            {lPct >= 14 && (418              <span className="vp-mono px-1 text-[10px] font-bold text-white">{Math.round(lPct)} %</span>419            )}420          </div>421        )}422        {lPct <= 99 && (423          <div className="flex flex-1 items-center justify-center overflow-hidden bg-ink">424            {100 - lPct >= 14 && (425              <span className="vp-mono px-1 text-[10px] font-bold text-paper">{Math.round(100 - lPct)} %</span>426            )}427          </div>428        )}429      </div>430      <div className="vp-mono mt-2 flex flex-wrap items-center gap-x-4 gap-y-1 text-[10.5px] uppercase tracking-[0.05em]">431        <span className="flex items-center gap-1.5 text-ink-2">432          <span className="inline-block h-2.5 w-2.5 bg-[var(--chart-3)]" />433          {labels.land} {fmt(l)}434        </span>435        <span className="flex items-center gap-1.5 text-ink-2">436          <span className="inline-block h-2.5 w-2.5 bg-ink" />437          {labels.building} {fmt(b)}438        </span>439      </div>440      {delta != null && (441        <p className="vp-mono mt-2.5 text-[10.5px] uppercase tracking-[0.05em] text-ink-3">442          {labels.previous} {fmt(previous!)}{" "}443          <b className={delta >= 0 ? "ml-1 text-ink" : "ml-1 text-[var(--danger)]"}>444            {delta >= 0 ? "+" : ""}445            {delta.toFixed(1)} %446          </b>447        </p>448      )}449    </div>450  );451}452453/* -------------------------------- sparkline -------------------------------- */454export function Sparkline({455  history,456  height = 44,457}: {458  history: { year: number; value: number | null }[];459  height?: number;460}) {461  const pts = history.filter((h) => h.value != null) as { year: number; value: number }[];462  if (pts.length < 2) return null;463  const W = 132;464  const min = Math.min(...pts.map((p) => p.value));465  const max = Math.max(...pts.map((p) => p.value));466  const span = max - min || 1;467  const xy = pts.map((p, i) => [468    6 + (i / (pts.length - 1)) * (W - 12),469    height - 8 - ((p.value - min) / span) * (height - 18),470  ]);471  const line = xy.map(([x, y]) => `${x},${y}`).join(" ");472  const growth = ((pts[pts.length - 1].value / pts[0].value - 1) * 100);473  const [x2, y2] = xy[xy.length - 1];474  return (475    <div className="flex items-end gap-2">476      <svg viewBox={`0 0 ${W} ${height}`} width={W} height={height} aria-label={`Évolution ${pts[0].year}-${pts[pts.length - 1].year}`}>477        <polyline points={line} fill="none" stroke="var(--ink)" strokeWidth="1.8" strokeLinejoin="round" strokeLinecap="round" />478        <circle cx={x2} cy={y2} r="3.6" fill="var(--accent)" stroke="var(--paper)" strokeWidth="2" />479      </svg>480      <span className={`vp-mono mb-0.5 text-[10.5px] font-bold ${growth >= 0 ? "text-ink" : "text-[var(--danger)]"}`}>481        {growth >= 0 ? "+" : ""}482        {growth.toFixed(0)} %483      </span>484    </div>485  );486}487488/* ------------------------- fourchette visuelle P10-P90 ------------------------- */489/** Barre de fourchette : segment P10→P90, losange rouge = estimation, tiret = rôle. */490export function RangeBar({491  low,492  estimate,493  high,494  role,495  lang,496}: {497  low: number;498  estimate: number;499  high: number;500  role: number | null;501  lang: string;502}) {503  const [on, setOn] = useState(false);504  useEffect(() => {505    const id = setTimeout(() => setOn(true), 80);506    return () => clearTimeout(id);507  }, []);508  if (!(high > low) || !Number.isFinite(estimate)) return null;509  const lo = Math.min(low, role ?? low);510  const hi = Math.max(high, role ?? high);511  const pad = (hi - lo) * 0.09 || hi * 0.05;512  const min = lo - pad;513  const max = hi + pad;514  const X = (v: number) => Math.max(0, Math.min(100, ((v - min) / (max - min)) * 100));515  // les étiquettes (centrées, nowrap) restent dans la composition même aux extrêmes516  const clampX = (v: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, X(v)));517  const fmt = (v: number) =>518    new Intl.NumberFormat(lang === "fr" ? "fr-CA" : "en-CA", {519      style: "currency",520      currency: "CAD",521      maximumFractionDigits: 0,522      notation: v >= 1_000_000 ? "compact" : "standard",523    }).format(v);524  // l'étiquette du rôle s'efface si elle chevaucherait l'estimation ou les bornes525  const roleClose =526    role != null &&527    (Math.abs(X(role) - X(estimate)) < 9 ||528      Math.abs(X(role) - X(low)) < 15 ||529      Math.abs(X(role) - X(high)) < 15);530  return (531    <div aria-label={`${fmt(low)} – ${fmt(high)}`}>532      <div className="relative h-[62px]">533        {/* étiquette estimation */}534        <div535          className="absolute top-0 -translate-x-1/2 whitespace-nowrap transition-[left] duration-700 ease-out"536          style={{ left: `${on ? clampX(estimate, 18, 82) : 50}%` }}537        >538          <span className="vp-mono bg-ink px-1.5 py-0.5 text-[10px] font-bold text-paper">539            {lang === "fr" ? "ESTIMATION" : "ESTIMATE"} {fmt(estimate)}540          </span>541        </div>542        {/* piste hairline */}543        <div className="absolute left-0 right-0 top-[35px] h-px bg-[var(--line-strong)] opacity-40" />544        {/* segment P10-P90 — encre pleine, fine */}545        <div546          className="absolute top-[33px] h-[5px] origin-left bg-ink transition-transform duration-1000 ease-out"547          style={{548            left: `${X(low)}%`,549            width: `${Math.max(2, X(high) - X(low))}%`,550            transform: on ? "scaleX(1)" : "scaleX(0.05)",551          }}552        />553        {/* bornes : ticks */}554        <div className="absolute top-[28px] h-[15px] w-px bg-ink" style={{ left: `${X(low)}%` }} />555        <div className="absolute top-[28px] h-[15px] w-px bg-ink" style={{ left: `${X(high)}%` }} />556        {/* marqueur estimation (losange rouge signal) */}557        <div558          className="absolute top-[35px] -translate-x-1/2 -translate-y-1/2 transition-[left] duration-700 ease-out"559          style={{ left: `${on ? X(estimate) : 50}%` }}560        >561          <div className="h-[13px] w-[13px] rotate-45 border-2 border-[var(--paper)] bg-[var(--accent)]" />562        </div>563        {/* marqueur rôle */}564        {role != null && role > 0 && (565          <>566            <div567              className="absolute top-[24px] h-[23px] w-0 -translate-x-1/2 border-l border-dashed border-ink opacity-70"568              style={{ left: `${X(role)}%` }}569            />570            {!roleClose && (571              <span572                className="vp-mono absolute top-[49px] -translate-x-1/2 whitespace-nowrap text-[9px] font-medium uppercase tracking-[0.06em] text-ink-2"573                style={{ left: `${clampX(role, 11, 89)}%` }}574              >575                {lang === "fr" ? "Rôle" : "Roll"} {fmt(role)}576              </span>577            )}578          </>579        )}580        {/* bornes */}581        <span582          className="vp-mono absolute top-[49px] -translate-x-1/2 whitespace-nowrap text-[10px] font-medium text-ink-2"583          style={{ left: `${clampX(low, 11, 89)}%` }}584        >585          P10 {fmt(low)}586        </span>587        <span588          className="vp-mono absolute top-[49px] -translate-x-1/2 whitespace-nowrap text-[10px] font-medium text-ink-2"589          style={{ left: `${clampX(high, 11, 89)}%` }}590        >591          P90 {fmt(high)}592        </span>593      </div>594    </div>595  );596}597598/* ----------------------- pouls du marché (multi-séries) ----------------------- */599export interface PulseChartSeries {600  key: string;601  label: string;602  color: string; // var(--chart-1|2|3)603  series: { month: string; idx: number }[];604}605606/**607 * Comparaison des grands types sur une même échelle (base 100 au début de la608 * fenêtre). Étiquettes directes en fin de ligne + légende + crosshair tactile :609 * l'identité ne repose jamais sur la couleur seule.610 */611export function MarketPulseChart({612  data,613  lang,614  months,615}: {616  data: PulseChartSeries[];617  lang: string;618  /** Fenêtre en mois (null = tout l'historique). */619  months: number | null;620}) {621  const wrap = useRef<HTMLDivElement>(null);622  const [hi, setHi] = useState<number | null>(null);623624  // fenêtre commune : mois de la série la plus longue, tronquée à `months`625  const longest = data.reduce((a, b) => (b.series.length > a.series.length ? b : a), data[0]);626  if (!longest || longest.series.length < 2) return null;627  const windowMonths = (months ? longest.series.slice(-(months + 1)) : longest.series).map((p) => p.month);628  const n = windowMonths.length;629  if (n < 2) return null;630631  // valeurs rebasées à 100 au premier mois de la fenêtre, par série632  const rebased = data.map((s) => {633    const byMonth = new Map(s.series.map((p) => [p.month, p.idx]));634    const first = windowMonths.find((m) => byMonth.has(m));635    const base = first != null ? byMonth.get(first)! : null;636    return {637      ...s,638      vals: windowMonths.map((m) => {639        const v = byMonth.get(m);640        return v != null && base ? (v / base) * 100 : null;641      }),642    };643  });644645  const W = 720;646  const H = 264;647  const padL = 34;648  const padR = 8;649  const padT = 14;650  const padB = 40; // réserve l'espace des étiquettes directes sous la ligne de base651  const all = rebased.flatMap((s) => s.vals).filter((v): v is number => v != null);652  const min = Math.min(...all);653  const max = Math.max(...all);654  const span = max - min || 1;655  const x = (i: number) => padL + (i / (n - 1)) * (W - padL - padR);656  const y = (v: number) => padT + (1 - (v - min) / span) * (H - padT - padB);657658  // grille : 100 + min/max arrondis à 5659  const gridVals = [...new Set([Math.ceil(min / 5) * 5, 100, Math.floor(max / 5) * 5])].filter(660    (v) => v >= min - 0.5 && v <= max + 0.5661  );662  // graduations x : janvier de chaque année (ou premier/dernier si fenêtre courte)663  const yearTicks = windowMonths664    .map((m, i) => ({ i, m }))665    .filter((p) => p.m.endsWith("-01"));666667  // étiquettes directes en fin de ligne, anticollision (≥ 15 px d'écart)668  const ends = rebased669    .map((s) => {670      const lastIdx = s.vals.reduce<number>((acc, v, i) => (v != null ? i : acc), -1);671      return lastIdx >= 0 ? { s, i: lastIdx, v: s.vals[lastIdx]! } : null;672    })673    .filter((e): e is { s: (typeof rebased)[number]; i: number; v: number } => e != null)674    .sort((a, b) => y(a.v) - y(b.v));675  const labelYs: number[] = [];676  for (const e of ends) {677    let ly = y(e.v);678    const prev = labelYs[labelYs.length - 1];679    if (prev != null && ly - prev < 15) ly = prev + 15;680    labelYs.push(ly);681  }682683  const onMove = (clientX: number) => {684    const el = wrap.current;685    if (!el) return;686    const r = el.getBoundingClientRect();687    const fx = ((clientX - r.left) / r.width) * W;688    const i = Math.round(((fx - padL) / (W - padL - padR)) * (n - 1));689    setHi(Math.max(0, Math.min(n - 1, i)));690  };691692  const fmtIdx = (v: number | null) =>693    v == null ? "—" : v.toLocaleString(lang === "fr" ? "fr-CA" : "en-CA", { maximumFractionDigits: 1 });694695  return (696    <div className="relative" ref={wrap}>697      <svg698        viewBox={`0 0 ${W} ${H}`}699        className="h-auto w-full touch-pan-y select-none"700        role="img"701        aria-label={702          lang === "fr"703            ? `Indice de marché par type, ${windowMonths[0]} à ${windowMonths[n - 1]}`704            : `Market index by type, ${windowMonths[0]} to ${windowMonths[n - 1]}`705        }706        onPointerDown={(e) => onMove(e.clientX)}707        onPointerMove={(e) => onMove(e.clientX)}708        onPointerLeave={() => setHi(null)}709      >710        {/* grille hairline pleine */}711        {gridVals.map((v) => (712          <g key={v}>713            <line x1={padL} y1={y(v)} x2={W - padR} y2={y(v)} stroke="var(--ink)" strokeWidth="0.7" opacity={v === 100 ? 0.35 : 0.12} />714            <text x={padL - 6} y={y(v) + 3.5} textAnchor="end" fontSize="10" fontFamily="var(--font-jetbrains)" fill="var(--ink-3)">715              {v}716            </text>717          </g>718        ))}719        {yearTicks.map((p) => (720          <text key={p.m} x={x(p.i)} y={H - padB + 16} textAnchor="middle" fontSize="10" fontFamily="var(--font-jetbrains)" fill="var(--ink-3)">721            {p.m.slice(0, 4)}722          </text>723        ))}724        {/* crosshair */}725        {hi != null && (726          <line x1={x(hi)} y1={padT} x2={x(hi)} y2={H - padB} stroke="var(--ink)" strokeWidth="0.8" opacity="0.4" />727        )}728        {/* lignes */}729        {rebased.map((s) => {730          const pts = s.vals731            .map((v, i) => (v != null ? `${x(i).toFixed(1)},${y(v).toFixed(1)}` : null))732            .filter(Boolean)733            .join(" ");734          return (735            <polyline736              key={s.key}737              points={pts}738              fill="none"739              stroke={s.color}740              strokeWidth="2"741              strokeLinejoin="round"742              strokeLinecap="round"743            />744          );745        })}746        {/* points survolés (anneau papier) */}747        {hi != null &&748          rebased.map((s) =>749            s.vals[hi] != null ? (750              <circle key={s.key} cx={x(hi)} cy={y(s.vals[hi]!)} r="4" fill={s.color} stroke="var(--paper)" strokeWidth="2" />751            ) : null752          )}753        {/* fins de ligne : point + étiquette directe (série + valeur).754            Étiquettes masquées en mobile (SVG trop réduit) : la légende et les755            colonnes de lecture sous le graphique portent alors l'identité. */}756        {ends.map((e, k) => (757          <g key={e.s.key}>758            <circle cx={x(e.i)} cy={y(e.v)} r="3.5" fill={e.s.color} stroke="var(--paper)" strokeWidth="2" />759            <g className="hidden sm:block">760              {labelYs[k] !== y(e.v) && (761                <line x1={x(e.i)} y1={y(e.v)} x2={x(e.i) - 4} y2={labelYs[k]} stroke={e.s.color} strokeWidth="0.8" opacity="0.6" />762              )}763              <text764                x={x(e.i) - 8}765                y={labelYs[k] + 3.5}766                textAnchor="end"767                fontSize="10.5"768                fontWeight="700"769                fontFamily="var(--font-jetbrains)"770                fill="var(--ink)"771                style={{ paintOrder: "stroke", stroke: "var(--paper)", strokeWidth: 3 }}772              >773                {e.s.label} · {Math.round(e.v)}774              </text>775            </g>776          </g>777        ))}778      </svg>779      {/* infobulle : toutes les séries au mois visé */}780      {hi != null && (781        <div782          className="vv-tip"783          style={{784            left: `${Math.min(78, Math.max(2, (x(hi) / W) * 100))}%`,785            top: 0,786            transform: "translateX(-50%)",787          }}788        >789          <p className="mb-1 uppercase tracking-[0.08em] opacity-70">{fmtMonth(windowMonths[hi], lang)}</p>790          {rebased.map((s) => (791            <p key={s.key} className="row">792              <span>793                <span className="key" style={{ background: s.color === "var(--chart-1)" ? "var(--paper)" : s.color }} />794                {s.label}795              </span>796              <span className="val">{fmtIdx(s.vals[hi])}</span>797            </p>798          ))}799        </div>800      )}801    </div>802  );803}804805/* --------------------------- courbe d'indice de marché --------------------------- */806/** Indice mensuel rebasé à 100 au premier mois — la trajectoire du marché local. */807export function MarketIndexChart({808  series,809  lang,810}: {811  series: { month: string; idx: number }[];812  lang: string;813}) {814  const wrap = useRef<HTMLDivElement>(null);815  const [hi, setHi] = useState<number | null>(null);816  if (series.length < 6) return null;817  const base = series[0].idx || 1;818  const pts = series.map((p) => (p.idx / base) * 100);819  const W = 640;820  const H = 200;821  const padL = 36;822  const padR = 46;823  const padT = 14;824  const padB = 26;825  const min = Math.min(...pts);826  const max = Math.max(...pts);827  const span = max - min || 1;828  const x = (i: number) => padL + (i / (pts.length - 1)) * (W - padL - padR);829  const y = (v: number) => padT + (1 - (v - min) / span) * (H - padT - padB);830  const line = pts.map((v, i) => `${x(i).toFixed(1)},${y(v).toFixed(1)}`).join(" ");831  const area = `${x(0)},${H - padB} ${line} ${x(pts.length - 1)},${H - padB}`;832  // graduations : janvier de chaque année833  const years = series834    .map((p, i) => ({ i, month: p.month }))835    .filter((p) => p.month.endsWith("-01"));836  const gridVals = [...new Set([Math.round(min), 100, Math.round(max)])].filter(837    (v) => v >= min - 1 && v <= max + 1838  );839  const lastV = pts[pts.length - 1];840841  const onMove = (clientX: number) => {842    const el = wrap.current;843    if (!el) return;844    const r = el.getBoundingClientRect();845    const fx = ((clientX - r.left) / r.width) * W;846    const i = Math.round(((fx - padL) / (W - padL - padR)) * (pts.length - 1));847    setHi(Math.max(0, Math.min(pts.length - 1, i)));848  };849850  return (851    <div className="relative" ref={wrap}>852      <svg853        viewBox={`0 0 ${W} ${H}`}854        className="h-auto w-full touch-pan-y select-none"855        role="img"856        aria-label={857          lang === "fr"858            ? `Indice de marché ${series[0].month} à ${series[series.length - 1].month}`859            : `Market index ${series[0].month} to ${series[series.length - 1].month}`860        }861        onPointerDown={(e) => onMove(e.clientX)}862        onPointerMove={(e) => onMove(e.clientX)}863        onPointerLeave={() => setHi(null)}864      >865        {gridVals.map((v) => (866          <g key={v}>867            <line868              x1={padL}869              y1={y(v)}870              x2={W - padR}871              y2={y(v)}872              stroke="var(--ink)"873              strokeWidth="0.7"874              opacity={v === 100 ? 0.35 : 0.12}875            />876            <text877              x={padL - 6}878              y={y(v) + 3.5}879              textAnchor="end"880              fontSize="10"881              fontFamily="var(--font-jetbrains)"882              fill="var(--ink-3)"883            >884              {v}885            </text>886          </g>887        ))}888        {years.map((p) => (889          <text890            key={p.month}891            x={x(p.i)}892            y={H - 8}893            textAnchor="middle"894            fontSize="10"895            fontFamily="var(--font-jetbrains)"896            fill="var(--ink-3)"897          >898            {p.month.slice(0, 4)}899          </text>900        ))}901        <polygon points={area} fill="var(--ink)" opacity="0.05" />902        {hi != null && (903          <line x1={x(hi)} y1={padT} x2={x(hi)} y2={H - padB} stroke="var(--ink)" strokeWidth="0.8" opacity="0.4" />904        )}905        <polyline906          points={line}907          fill="none"908          stroke="var(--ink)"909          strokeWidth="2"910          strokeLinejoin="round"911          strokeLinecap="round"912        />913        {hi != null && (914          <circle cx={x(hi)} cy={y(pts[hi])} r="4" fill="var(--ink)" stroke="var(--paper)" strokeWidth="2" />915        )}916        <circle917          cx={x(pts.length - 1)}918          cy={y(lastV)}919          r="4"920          fill="var(--accent)"921          stroke="var(--paper)"922          strokeWidth="2"923        />924        <text925          x={x(pts.length - 1) + 8}926          y={y(lastV) + 4}927          fontSize="11.5"928          fontWeight="700"929          fontFamily="var(--font-jetbrains)"930          fill="var(--ink)"931        >932          {Math.round(lastV)}933        </text>934      </svg>935      {hi != null && (936        <div937          className="vv-tip"938          style={{939            left: `${Math.min(74, Math.max(4, (x(hi) / W) * 100))}%`,940            top: 0,941            transform: "translateX(-50%)",942          }}943        >944          <p className="mb-0.5 uppercase tracking-[0.08em] opacity-70">{fmtMonth(series[hi].month, lang)}</p>945          <p className="row">946            <span>{lang === "fr" ? "Indice" : "Index"}</span>947            <span className="val">948              {pts[hi].toLocaleString(lang === "fr" ? "fr-CA" : "en-CA", { maximumFractionDigits: 1 })}949            </span>950          </p>951        </div>952      )}953    </div>954  );955}956957/* ----------------------- position dans la municipalité ----------------------- */958/** Distribution stylisée (cloche) : les barres sous le percentile sont pleines. */959export function PercentileBar({960  pct,961}: {962  pct: number;963  lang?: string;964}) {965  const N = 36;966  const bars = Array.from({ length: N }, (_, i) => {967    const z = (i / (N - 1) - 0.42) / 0.24; // cloche légèrement asymétrique (droite étirée)968    return Math.exp(-0.5 * z * z) * (i / N > 0.5 ? 1 + (i / N - 0.5) * 0.35 : 1);969  });970  const maxB = Math.max(...bars);971  const p = Math.max(0, Math.min(100, pct));972  return (973    <div aria-label={`${Math.round(p)} %`}>974      <div className="relative flex h-[72px] items-end px-0.5" style={{ gap: "2px" }}>975        {bars.map((b, i) => {976          const filled = (i + 0.5) / N <= p / 100;977          return (978            <div979              key={i}980              className="min-w-0 flex-1 transition-colors"981              style={{982                height: `${8 + (b / maxB) * 88}%`,983                background: filled ? "var(--ink)" : "var(--line-soft)",984              }}985            />986          );987        })}988        <div989          className="absolute bottom-0 top-[-6px] w-0 border-l-[2px] border-[var(--accent)]"990          style={{ left: `${p}%` }}991        >992          <span className="vp-mono absolute -top-1 left-1.5 whitespace-nowrap bg-ink px-1.5 py-0.5 text-[10px] font-bold text-paper" style={p > 55 ? { left: "auto", right: "6px" } : undefined}>993            P{Math.round(p)}994          </span>995        </div>996      </div>997    </div>998  );999}10001001/* ------------------------ mini-courbe d'indice (accueil) ------------------------ */1002export function IndexSpark({1003  series,1004  width = 150,1005  height = 46,1006  color = "var(--ink)",1007}: {1008  series: { month: string; idx: number }[];1009  width?: number;1010  height?: number;1011  color?: string;1012}) {1013  if (series.length < 2) return null;1014  const base = series[0].idx || 1;1015  const pts = series.map((p) => (p.idx / base) * 100);1016  const min = Math.min(...pts);1017  const max = Math.max(...pts);1018  const span = max - min || 1;1019  const xy = pts.map((v, i) => [1020    4 + (i / (pts.length - 1)) * (width - 8),1021    height - 6 - ((v - min) / span) * (height - 14),1022  ]);1023  const line = xy.map(([x, y]) => `${x.toFixed(1)},${y.toFixed(1)}`).join(" ");1024  const [lx, ly] = xy[xy.length - 1];1025  return (1026    <svg viewBox={`0 0 ${width} ${height}`} className="h-auto w-full" aria-hidden="true">1027      <polyline points={line} fill="none" stroke={color} strokeWidth="2" strokeLinejoin="round" strokeLinecap="round" />1028      <circle cx={lx} cy={ly} r="3.2" fill="var(--accent)" stroke="var(--paper)" strokeWidth="1.8" />1029    </svg>1030  );1031}10321033/* ------------------------------ frise temporelle ------------------------------ */1034export function EraLine({ year, lang }: { year: number | null; lang: string }) {1035  if (!year || year < 1750) return null;1036  const min = Math.min(1900, Math.floor((year - 10) / 50) * 50);1037  const max = 2026;1038  const frac = Math.max(0, Math.min(1, (year - min) / (max - min)));1039  const W = 190;1040  const x = 12 + frac * (W - 24);1041  const age = 2026 - year;1042  return (1043    <svg viewBox={`0 0 ${W} 40`} className="w-full max-w-[210px]" aria-label={`Construction ${year}`}>1044      <line x1="12" y1="24" x2={W - 12} y2="24" stroke="var(--ink)" strokeWidth="1.2" />1045      {[...new Set([min, Math.round((min + max) / 2 / 50) * 50, 2000])].map((yr) => {1046        const gx = 12 + ((yr - min) / (max - min)) * (W - 24);1047        return (1048          <g key={yr}>1049            <line x1={gx} y1="20" x2={gx} y2="28" stroke="var(--ink)" strokeWidth="1" opacity="0.5" />1050            <text x={gx} y="38" textAnchor="middle" fontSize="7.5" fontFamily="var(--font-jetbrains)" fill="var(--ink-3)">1051              {yr}1052            </text>1053          </g>1054        );1055      })}1056      <g transform={`translate(${x}, 24)`}>1057        <rect x="-6" y="-6" width="12" height="12" transform="rotate(45)" fill="var(--accent)" stroke="var(--paper)" strokeWidth="1.6" />1058        <text y="-13" textAnchor="middle" fontSize="9.5" fontWeight="700" fontFamily="var(--font-jetbrains)" fill="var(--ink)">1059          {year}1060        </text>1061      </g>1062      <text x={W - 12} y="12" textAnchor="end" fontSize="7.5" fontFamily="var(--font-jetbrains)" fill="var(--ink-3)">1063        {age} {lang === "fr" ? "ANS" : "YRS"}1064      </text>1065    </svg>1066  );1067}1068
Files main
Menu

Theme