SPB Git

Repository Public

Plot.tsx 6.7 KB 110 lines tsx

1import { scaleLinear } from "d3-scale";2import type { Locale, Tone } from "@/schema";3import { plainMath } from "@/renderer/mathtext";4import { decimalsOf, fmt, px } from "./format";56/**7 * A small SVG plot that can mix layers (points, lines with gaps, bands, reference lines). Used where the shared8 * chart component cannot express the picture (scatter + fitted line + band, 20 paths, curves with gaps).9 * Pure: no hooks, no browser API.10 */11export type PlotLayer =12  | { type: "line"; points: { x: number; y: number | null }[]; tone: Tone; name?: string; dashed?: boolean; width?: number; opacity?: number }13  | { type: "band"; points: { x: number; lo: number; hi: number }[]; tone: Tone; name?: string; opacity?: number }14  | { type: "points"; points: { x: number; y: number }[]; tone: Tone; name?: string; r?: number; opacity?: number }15  | { type: "vline"; x: number; tone: Tone; label?: string }16  | { type: "hline"; y: number; tone: Tone; label?: string };1718export interface PlotSpec { title: string; xLabel: string; yLabel: string; layers: PlotLayer[]; xDomain?: [number, number]; yDomain?: [number, number]; yFromZero?: boolean }1920function extent(values: number[], fallback: [number, number]): [number, number] {21  let lo = Infinity, hi = -Infinity;22  for (const v of values) if (Number.isFinite(v)) { if (v < lo) lo = v; if (v > hi) hi = v; }23  if (lo > hi) return fallback;24  if (lo === hi) return [lo - 1, hi + 1];25  return [lo, hi];26}2728const tone = (t: Tone) => `var(--sh-t-${t})`;2930export function Plot({ spec, locale, idPrefix, width = 560, height = 340 }: { spec: PlotSpec; locale: Locale; idPrefix: string; width?: number; height?: number }) {31  const m = { l: 56, r: 14, t: 12, b: 44 };32  const xs: number[] = [], ys: number[] = [];33  for (const l of spec.layers) {34    if (l.type === "line") for (const p of l.points) { xs.push(p.x); if (p.y !== null) ys.push(p.y); }35    else if (l.type === "points") for (const p of l.points) { xs.push(p.x); ys.push(p.y); }36    else if (l.type === "band") for (const p of l.points) { xs.push(p.x); ys.push(p.lo, p.hi); }37    else if (l.type === "hline") ys.push(l.y);38  }39  const xDomain = spec.xDomain ?? extent(xs, [0, 1]);40  let yDomain = spec.yDomain;41  if (!yDomain) {42    const [lo, hi] = extent(ys, [0, 1]);43    const pad = 0.06 * (hi - lo);44    yDomain = [spec.yFromZero && lo >= 0 ? 0 : lo - pad, hi + pad];45  }46  const x = scaleLinear().domain(xDomain).range([m.l, width - m.r]);47  const y = scaleLinear().domain(yDomain).range([height - m.b, m.t]);48  const sx = (v: number) => px(x(v));49  const sy = (v: number) => px(Math.max(-2000, Math.min(2000 + height, y(v))));50  const xt = x.ticks(6), yt = y.ticks(5);51  const dx = xt.length > 1 ? decimalsOf(Math.abs(xt[1] - xt[0])) : 2;52  const dy = yt.length > 1 ? decimalsOf(Math.abs(yt[1] - yt[0])) : 2;53  const clip = `${idPrefix}-clip`;54  const legend = spec.layers.filter((l): l is Exclude<PlotLayer, { type: "vline" } | { type: "hline" }> => (l.type === "line" || l.type === "band" || l.type === "points") && l.name !== undefined);5556  const linePath = (pts: { x: number; y: number | null }[]): string => {57    let d = "", pen = false;58    for (const p of pts) {59      if (p.y === null || !Number.isFinite(p.y) || !Number.isFinite(p.x)) { pen = false; continue; }60      d += `${pen ? "L" : "M"}${sx(p.x)} ${sy(p.y)}`;61      pen = true;62    }63    return d;64  };65  const bandPath = (pts: { x: number; lo: number; hi: number }[]): string => {66    if (!pts.length) return "";67    const up = pts.map((p, i) => `${i ? "L" : "M"}${sx(p.x)} ${sy(p.hi)}`).join("");68    const down = [...pts].reverse().map((p) => `L${sx(p.x)} ${sy(p.lo)}`).join("");69    return `${up}${down}Z`;70  };7172  return (73    <div className="sim-plot">74      <svg viewBox={`0 0 ${width} ${height}`} role="img" aria-label={spec.title} className="sim-svg">75        <defs><clipPath id={clip}><rect x={m.l} y={m.t} width={width - m.l - m.r} height={height - m.t - m.b} /></clipPath></defs>76        <g className="sim-grid">77          {yt.map((t) => <line key={`gy${t}`} x1={m.l} x2={width - m.r} y1={sy(t)} y2={sy(t)} />)}78          {xt.map((t) => <line key={`gx${t}`} x1={sx(t)} x2={sx(t)} y1={m.t} y2={height - m.b} />)}79        </g>80        <g clipPath={`url(#${clip})`}>81          {spec.layers.map((l, i) => {82            if (l.type === "band") return <path key={i} d={bandPath(l.points)} fill={tone(l.tone)} fillOpacity={l.opacity ?? 0.16} stroke="none" />;83            if (l.type === "line") return <path key={i} d={linePath(l.points)} fill="none" stroke={tone(l.tone)} strokeWidth={l.width ?? 2} strokeOpacity={l.opacity ?? 1} strokeDasharray={l.dashed ? "6 5" : undefined} strokeLinejoin="round" strokeLinecap="round" />;84            if (l.type === "points") return <g key={i} fill={tone(l.tone)} fillOpacity={l.opacity ?? 0.7}>{l.points.map((p, j) => <circle key={j} cx={sx(p.x)} cy={sy(p.y)} r={l.r ?? 3} />)}</g>;85            if (l.type === "vline") return <line key={i} x1={sx(l.x)} x2={sx(l.x)} y1={m.t} y2={height - m.b} stroke={tone(l.tone)} strokeWidth={1.5} strokeDasharray="4 4" />;86            return <line key={i} x1={m.l} x2={width - m.r} y1={sy(l.y)} y2={sy(l.y)} stroke={tone(l.tone)} strokeWidth={1.5} strokeDasharray="4 4" />;87          })}88        </g>89        {spec.layers.map((l, i) => {90          if (l.type === "vline" && l.label && l.x >= xDomain[0] && l.x <= xDomain[1]) return <text key={i} x={sx(l.x) + 4} y={m.t + 12} className="sim-tick" fill={tone(l.tone)}>{plainMath(l.label)}</text>;91          if (l.type === "hline" && l.label && l.y >= yDomain[0] && l.y <= yDomain[1]) return <text key={i} x={width - m.r - 4} y={sy(l.y) - 5} textAnchor="end" className="sim-tick" fill={tone(l.tone)}>{plainMath(l.label)}</text>;92          return null;93        })}94        <rect x={m.l} y={m.t} width={width - m.l - m.r} height={height - m.t - m.b} fill="none" className="sim-frame" />95        {xt.map((t) => <text key={`tx${t}`} x={sx(t)} y={height - m.b + 16} textAnchor="middle" className="sim-tick">{fmt(locale, t, dx)}</text>)}96        {yt.map((t) => <text key={`ty${t}`} x={m.l - 7} y={sy(t) + 4} textAnchor="end" className="sim-tick">{fmt(locale, t, dy)}</text>)}97        <text x={(m.l + width - m.r) / 2} y={height - 6} textAnchor="middle" className="sim-axis-label">{plainMath(spec.xLabel)}</text>98        <text transform={`translate(13 ${(m.t + height - m.b) / 2}) rotate(-90)`} textAnchor="middle" className="sim-axis-label">{plainMath(spec.yLabel)}</text>99      </svg>100      {legend.length ? (101        <ul className="sim-legend">102          {legend.map((l, i) => (103            <li key={i}><span className="sim-swatch" data-shape={l.type} style={{ background: l.type === "line" && l.dashed ? "none" : tone(l.tone), borderColor: tone(l.tone), opacity: l.type === "band" ? 0.35 : 1 }} />{plainMath(l.name ?? "")}</li>104          ))}105        </ul>106      ) : null}107    </div>108  );109}110
Files main
Menu

Theme