Repository Public
1import type { ReactNode } from "react";2import { area as d3area, line as d3line } from "d3-shape";3import type { Locale } from "@/schema";4import { t } from "../i18n";5import { plainMath } from "../mathtext";6import { V, toneVar } from "../tone";7import { measureText, wrapText } from "../diagram/text-measure";8import { TICK_FONT, chartGeometry } from "./scales";9import type { ChartSpec } from "./types";1011export interface ChartSvgProps {12 chart: ChartSpec; locale: Locale; width?: number; height?: number; idPrefix?: string;13 /** Accessible name; defaults to the chart title. */14 label?: string; desc?: string; className?: string;15}1617const r1 = (n: number): number => Math.round(n * 10) / 10;18const axisTitle = (axis: { label: string; unit?: string }): string => plainMath(axis.unit ? `${axis.label} (${axis.unit})` : axis.label);1920/** The small label that states what kind of numbers a picture shows. Drawn right-aligned at (right, y). */21export function DataKindBadge({ kind, locale, right, y }: { kind: ChartSpec["dataKind"]; locale: Locale; right: number; y: number }) {22 const label = t(locale, kind).toUpperCase();23 const w = Math.ceil(measureText(label, 9.5, 650) * 1.07) + 22;24 const tone = kind === "empirical" ? "teal" : kind === "synthetic" ? "violet" : "amber";25 return (26 <g data-kind={kind}>27 <rect x={right - w} y={y} width={w} height={18} rx={9} fill={V.surface} stroke={toneVar(tone)} strokeWidth={1} />28 <circle cx={right - w + 9.5} cy={y + 9} r={3} fill={kind === "illustrative" ? "none" : toneVar(tone)} stroke={toneVar(tone)} strokeWidth={1.4} />29 <text x={right - w + 17} y={y + 12.4} fontSize={9.5} fontWeight={650} letterSpacing="0.06em" fill={toneVar(tone)}>{label}</text>30 </g>31 );32}33export const badgeWidth = (kind: ChartSpec["dataKind"], locale: Locale): number => Math.ceil(measureText(t(locale, kind).toUpperCase(), 9.5, 650) * 1.07) + 22;3435/** Pure SVG chart (no hooks, no browser API): usable in server components, client components and static export. */36export function ChartSvg({ chart, locale, width = 720, height = 400, idPrefix = "chart", label, desc, className }: ChartSvgProps) {37 // Header row: legend (when there are several series) on the left, data-kind badge on the right.38 const legendItems = chart.series.length > 1 ? chart.series.map((s) => ({ name: s.name, tone: s.tone, w: Math.ceil(measureText(s.name, 12, 500)) + 30 })) : [];39 const bw = badgeWidth(chart.dataKind, locale);40 const legendRows: (typeof legendItems)[] = [];41 {42 let row: typeof legendItems = [], used = 0;43 for (const item of legendItems) {44 const limit = width - 64 - (legendRows.length === 0 ? bw + 14 : 0);45 if (row.length && used + item.w > limit) { legendRows.push(row); row = []; used = 0; }46 row.push(item); used += item.w;47 }48 if (row.length) legendRows.push(row);49 }50 const headerHeight = Math.max(1, legendRows.length) * 20 + 6;51 const g = chartGeometry(chart, width, height, locale, headerHeight);52 const { plot, x, y } = g;53 const clipId = `${idPrefix}-clip`;54 const marks: ReactNode[] = [];55 const nSeries = chart.series.length;5657 chart.series.forEach((s, si) => {58 const color = toneVar(s.tone);59 const pts = s.points.map((p) => ({ px: x.position(p.x), py: y.position(p.y), lo: p.lo !== undefined ? y.position(p.lo) : null, hi: p.hi !== undefined ? y.position(p.hi) : null }))60 .filter((p): p is { px: number; py: number; lo: number | null; hi: number | null } => p.px !== null && p.py !== null);61 const key = `s${si}`;62 const errorBar = (p: { px: number; lo: number | null; hi: number | null }, cx: number, i: number) => p.lo !== null && p.hi !== null63 ? <path key={`${key}-e${i}`} d={`M${r1(cx)} ${r1(p.lo)}V${r1(p.hi)}M${r1(cx - 3.5)} ${r1(p.lo)}h7M${r1(cx - 3.5)} ${r1(p.hi)}h7`} fill="none" stroke={V.ink} strokeWidth={1.2} strokeOpacity={0.75} />64 : null;6566 if (chart.kind === "bar") {67 const inner = x.bandwidth / nSeries, barW = Math.max(1, inner - (nSeries > 1 ? 2 : 0));68 pts.forEach((p, i) => {69 const left = p.px - x.bandwidth / 2 + si * inner + (inner - barW) / 2;70 const top = Math.min(p.py, y.baseline), h = Math.abs(p.py - y.baseline);71 marks.push(<rect key={`${key}-b${i}`} x={r1(left)} y={r1(top)} width={r1(barW)} height={r1(Math.max(h, 0.5))} rx={Math.min(3, barW / 4)} fill={color} />);72 marks.push(errorBar(p, left + barW / 2, i));73 });74 } else if (chart.kind === "histogram") {75 const w = g.histogramBinWidth ?? (x.bandwidth || 8);76 pts.forEach((p, i) => {77 const top = Math.min(p.py, y.baseline), h = Math.abs(p.py - y.baseline);78 marks.push(<rect key={`${key}-h${i}`} x={r1(p.px - w / 2 + 0.5)} y={r1(top)} width={r1(Math.max(1, w - 1))} height={r1(Math.max(h, 0.5))} fill={color} fillOpacity={nSeries > 1 ? 0.55 : 0.85} stroke={color} strokeWidth={0.75} />);79 });80 } else if (chart.kind === "scatter") {81 pts.forEach((p, i) => {82 marks.push(errorBar(p, p.px, i));83 marks.push(<circle key={`${key}-c${i}`} cx={r1(p.px)} cy={r1(p.py)} r={pts.length > 200 ? 2.4 : 3.6} fill={color} fillOpacity={0.72} stroke={V.surface} strokeWidth={0.8} />);84 });85 } else {86 // line / area — straight segments between the given points, no smoothing.87 const banded = pts.filter((p): p is { px: number; py: number; lo: number; hi: number } => p.lo !== null && p.hi !== null);88 if (banded.length > 1) {89 const band = d3area<{ px: number; lo: number; hi: number }>().x((p) => r1(p.px)).y0((p) => r1(p.lo)).y1((p) => r1(p.hi))(banded);90 if (band) marks.push(<path key={`${key}-band`} d={band} fill={color} fillOpacity={0.16} stroke="none" />);91 } else banded.forEach((p, i) => marks.push(errorBar(p, p.px, i)));92 if (chart.kind === "area") {93 const fill = d3area<{ px: number; py: number }>().x((p) => r1(p.px)).y0(r1(y.baseline)).y1((p) => r1(p.py))(pts);94 if (fill) marks.push(<path key={`${key}-area`} d={fill} fill={color} fillOpacity={0.18} stroke="none" />);95 }96 const d = d3line<{ px: number; py: number }>().x((p) => r1(p.px)).y((p) => r1(p.py))(pts);97 if (d && pts.length > 1) marks.push(<path key={`${key}-line`} d={d} fill="none" stroke={color} strokeWidth={2} strokeLinejoin="round" strokeLinecap="round" />);98 if (pts.length <= 40) pts.forEach((p, i) => marks.push(<circle key={`${key}-p${i}`} cx={r1(p.px)} cy={r1(p.py)} r={pts.length === 1 ? 4 : 3} fill={V.surface} stroke={color} strokeWidth={1.8} />));99 }100 });101102 const annotations = (chart.annotations ?? []).map((a, i) => {103 const ax = a.x !== undefined ? x.position(a.x) : null, ay = a.y !== undefined ? y.position(a.y) : null;104 const lines = wrapText(plainMath(a.label), Math.min(180, plot.width * 0.5), 11.5, { weight: 500, maxLines: 2 });105 const lw = Math.max(...lines.map((l) => measureText(l, 11.5, 500)));106 const text = (tx: number, ty: number, anchor: "start" | "end") => (107 <text fontSize={11.5} fontWeight={500} fill={V.ink} textAnchor={anchor} stroke={V.surface} strokeWidth={3} paintOrder="stroke" strokeLinejoin="round">108 {lines.map((l, k) => <tspan key={k} x={r1(tx)} y={r1(ty + k * 14)}>{l}</tspan>)}109 </text>110 );111 if (ax !== null && ay !== null) {112 const flip = ax + 10 + lw > plot.right;113 return <g key={i} data-annotation="point"><circle cx={r1(ax)} cy={r1(ay)} r={6} fill="none" stroke={V.ink} strokeWidth={1.4} />{text(flip ? ax - 10 : ax + 10, Math.max(plot.top + 12, ay - 8), flip ? "end" : "start")}</g>;114 }115 if (ax !== null) {116 const flip = ax + 6 + lw > plot.right;117 return <g key={i} data-annotation="x"><path d={`M${r1(ax)} ${plot.top}V${plot.bottom}`} stroke={V.ink} strokeWidth={1} strokeDasharray="4 3" strokeOpacity={0.7} />{text(flip ? ax - 6 : ax + 6, plot.top + 12 + i * 4, flip ? "end" : "start")}</g>;118 }119 if (ay !== null) return <g key={i} data-annotation="y"><path d={`M${plot.left} ${r1(ay)}H${plot.right}`} stroke={V.ink} strokeWidth={1} strokeDasharray="4 3" strokeOpacity={0.7} />{text(plot.right - 4, ay - 6, "end")}</g>;120 if (a.x === undefined && a.y === undefined) return <g key={i} data-annotation="note">{text(plot.left + 8, plot.top + 14 + i * 16, "start")}</g>;121 return null;122 });123124 const name = label ?? chart.title ?? t(locale, "chart");125 const maxTick = x.type === "band" && x.ticks.length ? Math.max(24, (plot.width / x.ticks.length) - 6) : 80;126 return (127 <svg className={className ?? "sh-chart-svg"} viewBox={`0 0 ${width} ${height}`} width={width} height={height} role="img" aria-label={name} fontFamily={V.fontBody}>128 <title>{name}</title>129 {desc ? <desc>{desc}</desc> : null}130 <defs><clipPath id={clipId}><rect x={plot.left - 5} y={plot.top - 5} width={plot.width + 10} height={plot.height + 10} /></clipPath></defs>131 {/* grid */}132 <g stroke={V.grid} strokeWidth={1}>133 {y.ticks.map((tick, i) => <path key={i} d={`M${plot.left} ${r1(tick.pos)}H${plot.right}`} />)}134 {chart.kind === "scatter" ? x.ticks.map((tick, i) => <path key={`x${i}`} d={`M${r1(tick.pos)} ${plot.top}V${plot.bottom}`} />) : null}135 </g>136 {/* axes */}137 <g fontSize={TICK_FONT} fill={V.muted}>138 {y.ticks.map((tick, i) => <text key={i} x={plot.left - 8} y={r1(tick.pos + 4)} textAnchor="end">{tick.label}</text>)}139 {x.ticks.map((tick, i) => (140 <g key={i}>141 <path d={`M${r1(tick.pos)} ${plot.bottom}v4`} stroke={V.line} strokeWidth={1} />142 <text x={r1(tick.pos)} y={plot.bottom + 17} textAnchor="middle">{x.type === "band" ? wrapText(tick.label, maxTick, TICK_FONT, { maxLines: 1 })[0] : tick.label}</text>143 </g>144 ))}145 </g>146 <path d={`M${plot.left} ${plot.bottom}H${plot.right}`} stroke={V.faint} strokeWidth={1.2} />147 {y.baseline < plot.bottom - 0.5 ? <path d={`M${plot.left} ${r1(y.baseline)}H${plot.right}`} stroke={V.faint} strokeWidth={1} /> : null}148 <text x={(plot.left + plot.right) / 2} y={height - 8} textAnchor="middle" fontSize={12} fontWeight={550} fill={V.ink}>{axisTitle(chart.x)}</text>149 <text transform={`translate(13 ${(plot.top + plot.bottom) / 2}) rotate(-90)`} textAnchor="middle" fontSize={12} fontWeight={550} fill={V.ink}>{axisTitle(chart.y)}</text>150 {/* marks */}151 <g clipPath={`url(#${clipId})`}>{marks}</g>152 <g>{annotations}</g>153 {/* header: legend + data kind */}154 {legendRows.map((row, ri) => {155 let cx = plot.left;156 return <g key={ri} fontSize={12} fontWeight={500} fill={V.ink}>{row.map((item, i) => {157 const at = cx; cx += item.w;158 return <g key={i}>159 {chart.kind === "line" ? <path d={`M${at} ${ri * 20 + 12}h14`} stroke={toneVar(item.tone)} strokeWidth={2.4} strokeLinecap="round" /> : <rect x={at} y={ri * 20 + 6} width={12} height={12} rx={chart.kind === "scatter" ? 6 : 3} fill={toneVar(item.tone)} />}160 <text x={at + 19} y={ri * 20 + 16}>{plainMath(item.name)}</text>161 </g>;162 })}</g>;163 })}164 <DataKindBadge kind={chart.dataKind} locale={locale} right={width - 4} y={3} />165 </svg>166 );167}168