SPB Git

Repository Public

Chart.tsx 6.6 KB 107 lines tsx

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : KA Maps Engine8 * File             : studio/web/src/Chart.tsx9 * Module           : studio10 * Repository       : https://git.spboucher.ai/ka-maps-engine11 * Created          : 2026-12-0112 * Last Modified    : 2026-12-0113 *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: support@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// Courbes temporelles en SVG : un seul axe par graphique, traits fins, grille discrète, légende dès43// deux séries, réticule et infobulle au survol, tableau de données accessible en repli.44import { useMemo, useRef, useState } from 'react';45import { fmtNum } from './api.ts';4647export type Series = { name: string; color: string; points: [number, number][] };48export const SERIES_COLORS = ['#1f6fb2', '#c2571a', '#7a4fb0']; // validées (daltonisme, contraste) sur fond #fbfaf74950const W = 520, H = 190, L = 46, R = 12, T = 10, B = 24;5152function niceMax(v: number): number {53  if (v <= 0) return 1;54  const p = 10 ** Math.floor(Math.log10(v));55  for (const m of [1, 2, 2.5, 5, 10]) if (v <= m * p) return m * p;56  return 10 * p;57}5859export function LineChart({ title, unit, series, range, max }: { title: string; unit: string; series: Series[]; range: [number, number]; max?: number }) {60  const ref = useRef<HTMLDivElement>(null);61  const [hover, setHover] = useState<{ t: number; x: number } | null>(null);62  const all = series.flatMap((s) => s.points);63  const yMax = max ?? niceMax(Math.max(0, ...all.map((p) => p[1])));64  const x = (t: number) => L + ((t - range[0]) / Math.max(1, range[1] - range[0])) * (W - L - R);65  const y = (v: number) => T + (1 - Math.min(v, yMax) / yMax) * (H - T - B);66  const times = useMemo(() => [...new Set(all.map((p) => p[0]))].sort((a, b) => a - b), [series]);67  const ticks = [0, 0.25, 0.5, 0.75, 1].map((f) => f * yMax);68  const span = range[1] - range[0];69  const tfmt = (t: number) => new Date(t).toLocaleString('fr-CA', span > 36 * 3600e3 ? { month: 'short', day: 'numeric' } : { hour: '2-digit', minute: '2-digit' });70  const xticks = Array.from({ length: 5 }, (_, i) => range[0] + (i / 4) * span);71  const onMove = (e: React.MouseEvent<SVGSVGElement>) => {72    if (!times.length) return;73    const r = e.currentTarget.getBoundingClientRect();74    const px = ((e.clientX - r.left) / r.width) * W;75    const t = range[0] + ((px - L) / (W - L - R)) * span;76    const near = times.reduce((a, b) => (Math.abs(b - t) < Math.abs(a - t) ? b : a));77    setHover({ t: near, x: (x(near) / W) * r.width });78  };79  const at = (s: Series, t: number) => s.points.find((p) => p[0] === t)?.[1];80  return (81    <div className="chart" ref={ref}>82      <h3>{title} <span className="faint small" style={{ fontWeight: 400 }}>{unit}</span></h3>83      {series.length > 1 ? <div className="legend">{series.map((s) => <span key={s.name}><i style={{ background: s.color }} />{s.name}</span>)}</div> : null}84      {all.length === 0 ? <p className="muted small" style={{ height: 120, display: 'grid', placeItems: 'center' }}>Aucune mesure sur la période.</p> : (85        <svg viewBox={`0 0 ${W} ${H}`} role="img" aria-label={`${title} — ${series.map((s) => s.name).join(', ')}`} onMouseMove={onMove} onMouseLeave={() => setHover(null)}>86          {ticks.map((v) => <g key={v}><line x1={L} x2={W - R} y1={y(v)} y2={y(v)} stroke="#e4ddd0" strokeWidth={1} /><text x={L - 6} y={y(v) + 4} textAnchor="end" fontSize={11} fill="#8c857a">{fmtNum(v)}</text></g>)}87          {xticks.map((t, i) => <text key={i} x={x(t)} y={H - 6} textAnchor={i === 0 ? 'start' : i === 4 ? 'end' : 'middle'} fontSize={11} fill="#8c857a">{tfmt(t)}</text>)}88          {series.map((s) => s.points.length === 189            ? <circle key={s.name} cx={x(s.points[0][0])} cy={y(s.points[0][1])} r={4} fill={s.color} />90            : <polyline key={s.name} fill="none" stroke={s.color} strokeWidth={2} strokeLinejoin="round" strokeLinecap="round" points={s.points.map((p) => `${x(p[0]).toFixed(1)},${y(p[1]).toFixed(1)}`).join(' ')} />)}91          {hover ? <g><line x1={x(hover.t)} x2={x(hover.t)} y1={T} y2={H - B} stroke="#5e584f" strokeWidth={1} />{series.map((s) => { const v = at(s, hover.t); return v === undefined ? null : <circle key={s.name} cx={x(hover.t)} cy={y(v)} r={4} fill={s.color} stroke="#fbfaf7" strokeWidth={2} />; })}</g> : null}92        </svg>93      )}94      {hover ? (95        <div className="tip" style={{ left: Math.min(hover.x + 22, (ref.current?.clientWidth ?? 400) - 170), top: 44 }}>96          {new Date(hover.t).toLocaleString('fr-CA', { dateStyle: 'short', timeStyle: 'short' })}97          {series.map((s) => { const v = at(s, hover.t); return v === undefined ? null : <div key={s.name}><i style={{ display: 'inline-block', width: 8, height: 8, background: s.color, marginRight: 6 }} />{series.length > 1 ? `${s.name} : ` : ''}{fmtNum(v)} {unit}</div>; })}98        </div>99      ) : null}100      <details className="small"><summary className="faint">Données</summary>101        <div className="table-wrap" style={{ maxHeight: 180, overflowY: 'auto' }}><table><thead><tr><th>Heure</th>{series.map((s) => <th key={s.name} className="num">{s.name}</th>)}</tr></thead>102          <tbody>{times.slice(-200).reverse().map((t) => <tr key={t}><td>{new Date(t).toLocaleString('fr-CA', { dateStyle: 'short', timeStyle: 'short' })}</td>{series.map((s) => <td key={s.name} className="num">{at(s, t) === undefined ? '—' : fmtNum(at(s, t)!)}</td>)}</tr>)}</tbody></table></div>103      </details>104    </div>105  );106}107
Files main
Menu

Theme