SPB Git

Repository Public

charts.tsx 13.2 KB 324 lines tsx

1// Graphiques SVG faits main pour les pages marché et guides (aucune bibliothèque).2// Couleurs : forêt pour la série principale, pierre pour le contexte, orange3// seulement pour la sélection. Axes fins, chiffres tabulaires, lecture au survol4// et au toucher.56import { useMemo, useRef, useState, type ReactNode } from "react";7import { cn } from "@/lib/cn";8import { fmtInt } from "@/lib/format";9import { useSeenOnce } from "@/lib/motion";1011export interface Pt {12  t: string;13  v: number;14}1516const shortDate = (iso: string) => {17  const [y, m, d] = iso.split("-").map(Number);18  if (!y || !m) return iso;19  return new Date(y, m - 1, d || 1).toLocaleDateString("fr-CA", d ? { day: "numeric", month: "short" } : { month: "short", year: "2-digit" });20};2122// --- Barres horizontales classées ------------------------------------------------23export function BarList({24  items,25  format = fmtInt,26  color = "var(--brand)",27  max,28  className,29}: {30  items: { key: string; label: ReactNode; value: number; hint?: ReactNode; to?: string }[];31  format?: (n: number) => string;32  color?: string;33  max?: number;34  className?: string;35}) {36  const top = max ?? Math.max(1, ...items.map((i) => i.value));37  // les barres s'étirent en cascade, une fois, à l'entrée dans la fenêtre38  const [ref, seen] = useSeenOnce<HTMLUListElement>();39  return (40    <ul ref={ref} data-drawn={seen ? "true" : "false"} className={cn("space-y-2.5", className)}>41      {items.map((it, i) => (42        <li key={it.key}>43          <div className="flex items-baseline justify-between gap-3 text-sm">44            <span className="min-w-0 truncate text-ink">{it.label}</span>45            <span className="shrink-0 text-ink-3">46              {it.hint && <span className="mr-2.5 text-xs">{it.hint}</span>}47              <span className="num font-medium text-ink">{format(it.value)}</span>48            </span>49          </div>50          <div className="mt-1.5 h-1 overflow-hidden rounded-full bg-surface-3">51            <div className="lk-draw-bar h-full rounded-full" style={{ width: `${Math.max(1.5, (it.value / top) * 100)}%`, background: color, ["--i" as string]: Math.min(i, 14) }} />52          </div>53        </li>54      ))}55    </ul>56  );57}5859// --- Histogramme vertical ---------------------------------------------------------60export function Histogram({61  bins,62  marker,63  height = 220,64  unit = "logements",65}: {66  bins: { label: string; short: string; count: number }[];67  /** indice de la classe à mettre en évidence (ex. celle de la médiane) */68  marker?: number;69  height?: number;70  unit?: string;71}) {72  const [hover, setHover] = useState<number | null>(null);73  const max = Math.max(1, ...bins.map((b) => b.count));74  const active = hover ?? marker ?? null;75  const total = bins.reduce((s, b) => s + b.count, 0) || 1;76  const [ref, seen] = useSeenOnce<HTMLDivElement>();77  return (78    <div ref={ref} data-drawn={seen ? "true" : "false"}>79      <div className="num mb-3 h-10 text-sm text-ink-2">80        {active != null && bins[active] ? (81          <>82            <span className="text-[1.35rem] font-semibold text-ink">{fmtInt(bins[active].count)}</span>{" "}83            {unit} · {bins[active].label}84            <span className="ml-2 text-ink-3">({Math.round((bins[active].count / total) * 100)} %)</span>85          </>86        ) : null}87      </div>88      <div className="flex items-end gap-[3px] border-b border-line-2 sm:gap-1.5" style={{ height }} onMouseLeave={() => setHover(null)}>89        {bins.map((b, i) => (90          <button91            key={b.label}92            type="button"93            aria-label={`${b.label} : ${fmtInt(b.count)} ${unit}`}94            onMouseEnter={() => setHover(i)}95            onFocus={() => setHover(i)}96            onBlur={() => setHover(null)}97            onClick={() => setHover(i)}98            onPointerDown={() => setHover(i)}99            className="group relative flex h-full min-w-0 flex-1 cursor-default items-end outline-none focus-visible:ring-2 focus-visible:ring-brand"100          >101            <span102              className="lk-draw-col w-full rounded-t-[3px]"103              style={{104                ["--i" as string]: i,105                height: `${Math.max(1.5, (b.count / max) * 100)}%`,106                background: i === hover ? "var(--accent)" : i === marker ? "var(--brand)" : "color-mix(in srgb, var(--ink-3) 46%, transparent)",107              }}108            />109          </button>110        ))}111      </div>112      <div className="mt-2 flex gap-[3px] sm:gap-1.5">113        {bins.map((b, i) => (114          <span key={b.label} className={cn("num min-w-0 flex-1 text-center text-[0.62rem] text-ink-3", i % 2 === 1 && "max-sm:invisible")}>115            {b.short}116          </span>117        ))}118      </div>119    </div>120  );121}122123// --- Courbe / aire avec lecture au survol ---------------------------------------124export function TrendChart({125  points,126  compare,127  kind = "area",128  format = fmtInt,129  color = "var(--brand)",130  height = 220,131  label,132}: {133  points: Pt[];134  compare?: Pt[];135  kind?: "area" | "bar";136  format?: (n: number) => string;137  color?: string;138  height?: number;139  label: string;140}) {141  const ref = useRef<SVGSVGElement>(null);142  // la courbe se trace une fois, à l'entrée dans la fenêtre143  const [seenRef, seen] = useSeenOnce<SVGSVGElement>();144  const [hover, setHover] = useState<number | null>(null);145  const W = 720;146  const H = height;147  const pad = { l: 6, r: 6, t: 14, b: 8 };148149  const geo = useMemo(() => {150    const all = [...points.map((p) => p.v), ...(compare ?? []).map((p) => p.v)];151    let min = Math.min(...all);152    let max = Math.max(...all);153    if (kind === "bar") min = 0;154    const span = max - min || 1;155    min = kind === "bar" ? 0 : min - span * 0.12;156    max = max + span * 0.1;157    const n = Math.max(1, points.length - 1);158    const x = (i: number) => (kind === "bar" ? pad.l + ((i + 0.5) / points.length) * (W - pad.l - pad.r) : pad.l + (i / n) * (W - pad.l - pad.r));159    const y = (v: number) => pad.t + (1 - (v - min) / (max - min || 1)) * (H - pad.t - pad.b);160    const path = (pts: Pt[]) => pts.map((p, i) => `${i ? "L" : "M"}${x(i).toFixed(1)} ${y(p.v).toFixed(1)}`).join(" ");161    return { x, y, path, base: y(min) };162  }, [points, compare, kind, H]);163164  if (points.length < 2) return <div className="grid place-items-center text-sm text-ink-3" style={{ height }}>Pas assez de données sur cette période.</div>;165166  const onMove = (e: React.PointerEvent) => {167    const r = ref.current?.getBoundingClientRect();168    if (!r) return;169    const rel = (e.clientX - r.left) / r.width;170    setHover(Math.min(points.length - 1, Math.max(0, kind === "bar" ? Math.floor(rel * points.length) : Math.round(rel * (points.length - 1)))));171  };172  const cur = hover != null ? points[hover] : points[points.length - 1];173  const bw = ((W - pad.l - pad.r) / points.length) * 0.68;174175  return (176    <div>177      <div className="mb-2 flex items-baseline justify-between gap-3">178        <div className="num">179          <span className="text-[1.35rem] font-semibold text-ink">{cur ? format(cur.v) : "—"}</span>180          <span className="ml-2 text-sm text-ink-3">{cur ? shortDate(cur.t) : ""}</span>181        </div>182        {compare && compare.length > 0 && (183          <div className="flex items-center gap-3 text-xs text-ink-3">184            <span className="inline-flex items-center gap-1.5"><span className="h-0.5 w-4 rounded" style={{ background: color }} />Période</span>185            <span className="inline-flex items-center gap-1.5"><span className="h-0.5 w-4 rounded border-t border-dashed border-ink-3" />Précédente</span>186          </div>187        )}188      </div>189      <svg190        ref={(el) => {191          ref.current = el;192          seenRef(el);193        }}194        data-drawn={seen ? "true" : "false"}195        viewBox={`0 0 ${W} ${H}`}196        preserveAspectRatio="none"197        className="w-full touch-pan-y"198        style={{ height }}199        role="img"200        aria-label={label}201        onPointerMove={onMove}202        onPointerDown={onMove}203        onPointerLeave={() => setHover(null)}204      >205        {[0.25, 0.5, 0.75].map((k) => (206          <line key={k} x1={0} x2={W} y1={pad.t + k * (H - pad.t - pad.b)} y2={pad.t + k * (H - pad.t - pad.b)} stroke="var(--line)" strokeWidth={1} vectorEffect="non-scaling-stroke" />207        ))}208        {kind === "bar" ? (209          points.map((p, i) => (210            <rect211              key={p.t}212              x={geo.x(i) - bw / 2}213              y={geo.y(p.v)}214              width={bw}215              height={Math.max(1, geo.base - geo.y(p.v))}216              rx={2}217              className="lk-draw-col"218              style={{ ["--i" as string]: Math.min(i, 40) * 0.5 }}219              fill={hover === i ? "var(--accent)" : color}220              opacity={hover == null || hover === i ? 1 : 0.55}221            />222          ))223        ) : (224          <>225            {compare && compare.length === points.length && (226              <path d={geo.path(compare)} fill="none" stroke="var(--ink-3)" strokeWidth={1.2} strokeDasharray="4 4" vectorEffect="non-scaling-stroke" opacity={0.7} />227            )}228            <path className="lk-draw-fade" d={`${geo.path(points)} L${geo.x(points.length - 1)} ${H} L${geo.x(0)} ${H} Z`} fill={color} fillOpacity={0.08} />229            <path className="lk-draw-line" pathLength={1} style={{ ["--len" as string]: 1 }} d={geo.path(points)} fill="none" stroke={color} strokeWidth={1.75} strokeLinecap="round" strokeLinejoin="round" vectorEffect="non-scaling-stroke" />230            {hover != null && points[hover] && (231              <line x1={geo.x(hover)} x2={geo.x(hover)} y1={pad.t} y2={H} stroke="var(--accent)" strokeWidth={1} vectorEffect="non-scaling-stroke" />232            )}233          </>234        )}235      </svg>236      <div className="num mt-1.5 flex justify-between text-[0.68rem] text-ink-3">237        <span>{shortDate(points[0]!.t)}</span>238        <span>{shortDate(points[Math.floor(points.length / 2)]!.t)}</span>239        <span>{shortDate(points[points.length - 1]!.t)}</span>240      </div>241    </div>242  );243}244245// --- Anneau à segments ------------------------------------------------------------246export function Donut({247  items,248  size = 190,249  stroke = 14,250  center,251}: {252  items: { label: string; value: number; color: string }[];253  size?: number;254  stroke?: number;255  center?: ReactNode;256}) {257  const total = items.reduce((s, i) => s + i.value, 0) || 1;258  const r = (size - stroke) / 2;259  const c = 2 * Math.PI * r;260  let acc = 0;261  const [ref, seen] = useSeenOnce<HTMLDivElement>();262  return (263    <div ref={ref} data-drawn={seen ? "true" : "false"} className="flex flex-wrap items-center gap-x-8 gap-y-5">264      <div className="relative shrink-0" style={{ width: size, height: size }}>265        <svg width={size} height={size} className="-rotate-90" role="img" aria-label={items.map((i) => `${i.label} ${Math.round((i.value / total) * 100)} %`).join(", ")}>266          <circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke="var(--surface-3)" strokeWidth={stroke} />267          {items.map((it) => {268            const len = (it.value / total) * c;269            const el = (270              <circle271                key={it.label}272                cx={size / 2}273                cy={size / 2}274                r={r}275                fill="none"276                stroke={it.color}277                strokeWidth={stroke}278                className="lk-draw-fade"279                style={{ transitionDelay: `${0.1 + items.indexOf(it) * 0.12}s` }}280                strokeDasharray={`${Math.max(0, len - 3)} ${c - Math.max(0, len - 3)}`}281                strokeDashoffset={-acc}282              />283            );284            acc += len;285            return el;286          })}287        </svg>288        {center && <div className="absolute inset-0 grid place-items-center text-center">{center}</div>}289      </div>290      <ul className="min-w-40 flex-1 space-y-2.5">291        {items.map((it) => (292          <li key={it.label} className="flex items-center justify-between gap-4 text-sm">293            <span className="inline-flex items-center gap-2.5 text-ink-2">294              <span className="size-2 rounded-[2px]" style={{ background: it.color }} />295              {it.label}296            </span>297            <span className="num text-ink-3">298              <span className="font-medium text-ink">{Math.round((it.value / total) * 100)} %</span>299              <span className="ml-2 text-xs">{fmtInt(it.value)}</span>300            </span>301          </li>302        ))}303      </ul>304    </div>305  );306}307308// --- Jauge linéaire en pourcentage ------------------------------------------------309export function PctMeter({ label, value, hint, color = "var(--brand)" }: { label: ReactNode; value: number | null | undefined; hint?: ReactNode; color?: string }) {310  const [ref, seen] = useSeenOnce<HTMLDivElement>();311  return (312    <div ref={ref} data-drawn={seen ? "true" : "false"}>313      <div className="flex items-baseline justify-between gap-3">314        <span className="text-[0.9rem] text-ink">{label}</span>315        <span className="num text-[0.95rem] font-medium text-ink">{value == null ? "—" : `${Math.round(value)} %`}</span>316      </div>317      <div className="mt-1.5 h-1 overflow-hidden rounded-full bg-surface-3">318        <div className="lk-draw-bar h-full rounded-full" style={{ width: `${value ?? 0}%`, background: color }} />319      </div>320      {hint && <div className="mt-1 text-xs text-ink-3">{hint}</div>}321    </div>322  );323}324
Files main
Menu

Theme