SPB Git

Repository Public

MatrixSvg.tsx 6.3 KB 98 lines tsx

1import { plainMath } from "../mathtext";2import type { BlockOf, Locale } from "@/schema";3import { DataKindBadge, badgeWidth } from "../chart/ChartSvg";4import { measureText, wrapText } from "../diagram/text-measure";5import { formatNumber, t } from "../i18n";6import { V, mix } from "../tone";78export type MatrixSpec = Pick<BlockOf<"matrix">, "rowLabels" | "colLabels" | "values" | "scale" | "showValues" | "decimals" | "dataKind"> & { title?: string };910/**11 * Share of the tone in the darkest/lightest cells. The ceiling is chosen so that the value printed in --sh-ink keeps12 * a WCAG AA contrast (≥ 4.5) on every cell, in every theme and for every tone — asserted in the unit tests against13 * the palettes. Without printed values the full range is used.14 */15export const HEAT_MIN = 5, HEAT_MAX_WITH_TEXT = 34, HEAT_MAX = 88;1617export interface MatrixCellPaint { percent: number; negative: boolean }18/** Colour intensity of a value. Sequential: min → max. Diverging: symmetric around zero. */19export function heatOf(value: number, min: number, max: number, scale: MatrixSpec["scale"], ceiling: number): MatrixCellPaint {20  if (scale === "none") return { percent: 0, negative: false };21  if (scale === "diverging") {22    const m = Math.max(Math.abs(min), Math.abs(max));23    const k = m === 0 ? 0 : Math.abs(value) / m;24    return { percent: k === 0 ? 0 : HEAT_MIN + k * (ceiling - HEAT_MIN), negative: value < 0 };25  }26  const k = max === min ? 0.5 : (value - min) / (max - min);27  return { percent: HEAT_MIN + k * (ceiling - HEAT_MIN), negative: false };28}2930const CELL_H = 36, LABEL_FONT = 12, VALUE_FONT = 12;3132export function matrixSize(m: MatrixSpec, locale: Locale): { width: number; height: number; cellW: number; rowW: number; top: number; rotate: boolean } {33  const texts = m.showValues ? m.values.flat().map((v) => formatNumber(v, locale, m.decimals)) : [];34  const valueW = texts.reduce((a, s) => Math.max(a, measureText(s, VALUE_FONT, 550)), 0);35  const cellW = Math.round(Math.max(40, Math.min(92, valueW + 16)));36  const rowW = Math.ceil(Math.min(150, m.rowLabels.reduce((a, s) => Math.max(a, measureText(s, LABEL_FONT, 500)), 0))) + 12;37  const colW = m.colLabels.reduce((a, s) => Math.max(a, measureText(s, LABEL_FONT, 500)), 0);38  const rotate = colW > cellW - 6;39  const colH = rotate ? Math.min(96, Math.ceil(colW * 0.72) + 14) : 20;40  const top = 26 + colH;41  const gridW = m.colLabels.length * cellW;42  const width = Math.max(rowW + gridW + (rotate ? Math.min(70, Math.ceil(colW * 0.72)) : 8), badgeWidth(m.dataKind, locale) + 8, 240);43  const height = top + m.rowLabels.length * CELL_H + (m.scale === "none" ? 8 : 38);44  return { width, height, cellW, rowW, top, rotate };45}4647/** Heat-map grid. Pure SVG, no hooks. Colours are mixes of the accent (and its contrast tone) with the surface. */48export function MatrixSvg({ matrix, locale, label, desc, width, height, className }: { matrix: MatrixSpec; locale: Locale; label?: string; desc?: string; width?: number; height?: number; className?: string }) {49  const size = matrixSize(matrix, locale);50  const flat = matrix.values.flat();51  const min = Math.min(...flat), max = Math.max(...flat);52  const ceiling = matrix.showValues ? HEAT_MAX_WITH_TEXT : HEAT_MAX;53  const fill = (p: MatrixCellPaint): string => (p.percent <= 0 ? V.surface : mix(p.negative ? "var(--sh-contra)" : V.accent, p.percent, V.surface));54  const name = label ?? matrix.title ?? t(locale, "matrix");55  const gridBottom = size.top + matrix.rowLabels.length * CELL_H;56  const ramp = matrix.scale === "diverging" ? [-1, -0.5, 0, 0.5, 1] : [0, 0.25, 0.5, 0.75, 1];57  const lo = matrix.scale === "diverging" ? -Math.max(Math.abs(min), Math.abs(max)) : min, hi = matrix.scale === "diverging" ? Math.max(Math.abs(min), Math.abs(max)) : max;58  return (59    <svg className={className ?? "sh-matrix-svg"} viewBox={`0 0 ${size.width} ${size.height}`} width={width ?? size.width} height={height ?? size.height} role="img" aria-label={name} fontFamily={V.fontBody}>60      <title>{name}</title>61      {desc ? <desc>{desc}</desc> : null}62      <DataKindBadge kind={matrix.dataKind} locale={locale} right={size.width - 2} y={2} />63      <g fontSize={LABEL_FONT} fontWeight={500} fill={V.muted}>64        {matrix.colLabels.map((c, j) => {65          const cx = size.rowW + j * size.cellW + size.cellW / 2;66          return size.rotate67            ? <text key={j} transform={`translate(${cx - 2} ${size.top - 8}) rotate(-45)`}>{wrapText(plainMath(c), 130, LABEL_FONT, { maxLines: 1 })[0]}</text>68            : <text key={j} x={cx} y={size.top - 8} textAnchor="middle">{plainMath(c)}</text>;69        })}70        {matrix.rowLabels.map((r, i) => <text key={i} x={size.rowW - 10} y={size.top + i * CELL_H + CELL_H / 2 + 4} textAnchor="end">{wrapText(plainMath(r), 140, LABEL_FONT, { maxLines: 1 })[0]}</text>)}71      </g>72      {matrix.values.map((row, i) => row.map((v, j) => {73        const p = heatOf(v, min, max, matrix.scale, ceiling);74        const x = size.rowW + j * size.cellW, y = size.top + i * CELL_H;75        return (76          <g key={`${i}-${j}`}>77            <rect x={x + 1} y={y + 1} width={size.cellW - 2} height={CELL_H - 2} rx={4} fill={fill(p)} stroke={V.line} strokeWidth={matrix.scale === "none" || p.percent <= 0 ? 1 : 0} />78            {matrix.showValues ? <text x={x + size.cellW / 2} y={y + CELL_H / 2 + 4.2} textAnchor="middle" fontSize={VALUE_FONT} fontWeight={550} fill={V.ink}>{formatNumber(v, locale, matrix.decimals)}</text> : null}79          </g>80        );81      }))}82      {matrix.scale !== "none" ? (() => {83        const loText = formatNumber(lo, locale, matrix.decimals), x0 = 2 + Math.ceil(measureText(loText, 10.5)) + 6;84        return (85          <g fontSize={10.5} fill={V.muted}>86            <text x={2} y={gridBottom + 27}>{loText}</text>87            {ramp.map((k, i) => {88              const p = matrix.scale === "diverging" ? { percent: k === 0 ? 0 : HEAT_MIN + Math.abs(k) * (ceiling - HEAT_MIN), negative: k < 0 } : { percent: HEAT_MIN + k * (ceiling - HEAT_MIN), negative: false };89              return <rect key={i} x={x0 + i * 22} y={gridBottom + 16} width={21} height={12} rx={2} fill={fill(p)} stroke={V.line} strokeWidth={0.75} />;90            })}91            <text x={x0 + ramp.length * 22 + 6} y={gridBottom + 27}>{formatNumber(hi, locale, matrix.decimals)}</text>92          </g>93        );94      })() : null}95    </svg>96  );97}98
Files main
Menu

Theme