@vitavision/charts 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["plotArea"],"sources":["../src/Frame.tsx","../src/scale.ts","../src/LineChart.tsx","../src/BarChart.tsx","../src/Histogram.tsx","../src/LineProfile.tsx"],"sourcesContent":["/**\n * The plot frame every chart here composes: axes, ticks, grid, labels.\n *\n * Charts are drawn into a fixed `viewBox` and scaled by CSS, so one component works at\n * any panel width without measuring the DOM. The consequence is that font sizes are in\n * viewBox units and therefore scale with the chart: the *same* 10-unit label renders at\n * 9 px in a half-width panel and at 21 px across a full-width one, which looks like two\n * different design systems on one screen.\n *\n * So the viewBox is chosen to roughly match the width the chart will actually be given.\n * `panel` is for the two-column grids, `wide` for a chart that spans a panel on its own.\n * That keeps the scale factor near 1 in both, and it is why callers pick a variant rather\n * than a pixel width — the variant says where the chart is going, not how big to draw it.\n */\n\nimport type { ReactNode } from \"react\";\n\nimport { cn } from \"@vitavision/ui\";\n\nimport type { Scale } from \"./scale\";\n\n/**\n * Where a chart is going: `panel` (a 480×280 viewBox) for one column of a two-column grid,\n * `wide` (960×320) for a chart that spans a panel on its own.\n *\n * @remarks\n * Pick it by placement, not by pixel width — it keeps the chart's text at the same rendered\n * size as its neighbours'.\n */\nexport type Variant = \"panel\" | \"wide\";\n\nconst GEOMETRY = {\n panel: { width: 480, height: 280 },\n wide: { width: 960, height: 320 },\n} as const;\n\nconst MARGIN = { left: 56, right: 12, top: 12, bottom: 34 } as const;\n\n/**\n * The drawable rectangle for one variant, in that variant's viewBox units.\n *\n * @param variant - Which viewBox the chart is drawn in.\n * @returns The plot area's edges — `x0`/`x1` left to right, `y0` the bottom and `y1` the top\n * (SVG y grows downwards) — and the whole viewBox's `width`/`height`. Build scales over\n * `[x0, x1]` and `[y0, y1]`.\n */\nexport function areaFor(variant: Variant) {\n const { width, height } = GEOMETRY[variant];\n return {\n x0: MARGIN.left,\n x1: width - MARGIN.right,\n y0: height - MARGIN.bottom,\n y1: MARGIN.top,\n width,\n height,\n };\n}\n\n/** The default geometry, for callers that do not care which variant they are in. */\nexport const plotArea = areaFor(\"panel\");\n\n/** Held at the two ends of the neutral ramp, matching the design system's chrome colours. */\nconst AXIS = \"currentColor\";\n\n/** Props for {@link Frame}. */\nexport interface FrameProps {\n /** The horizontal scale, built over this variant's `x0`…`x1` (see {@link areaFor}). */\n xScale: Scale;\n /** The vertical scale, built over this variant's `y0`…`y1` (see {@link areaFor}). */\n yScale: Scale;\n /** Axis title under the x axis. Omitted: no title. */\n xLabel?: string | undefined;\n /** Axis title beside the y axis, rotated. Omitted: no title. */\n yLabel?: string | undefined;\n /** Rough number of x ticks to ask the scale for. Default 5. */\n xTicks?: number;\n /** Rough number of y ticks to ask the scale for. Default 4. */\n yTicks?: number;\n /** Drawn inside the plot area, above the grid and below nothing. */\n children?: ReactNode;\n /** Accessible name — every chart must have one; it is what the tests query on. */\n label: string;\n /** Rendered under the plot: a legend, a caption, a truncation note. */\n footer?: ReactNode;\n /** Where this chart is going, so its text renders at the same size as its neighbours. */\n variant?: Variant;\n /** Extra classes for the outer `<figure>`, merged with `cn`. */\n className?: string | undefined;\n}\n\n/**\n * The plot shell every chart here composes: grid, ticks, axes, axis titles, a footer.\n *\n * @remarks\n * Renders a `<figure>` holding an SVG with `role=\"img\"` named by `label`, and the `footer`\n * as its `<figcaption>`. `children` are drawn in viewBox units over the grid.\n */\nexport function Frame({\n xScale,\n yScale,\n xLabel,\n yLabel,\n xTicks = 5,\n yTicks = 4,\n children,\n label,\n footer,\n variant = \"panel\",\n className,\n}: FrameProps) {\n const horizontal = xScale.ticks(xTicks);\n const vertical = yScale.ticks(yTicks);\n const plotArea = areaFor(variant);\n const PLOT = GEOMETRY[variant];\n\n return (\n <figure className={cn(\"flex flex-col gap-1 text-fg-muted\", className)}>\n <svg\n role=\"img\"\n aria-label={label}\n viewBox={`0 0 ${PLOT.width} ${PLOT.height}`}\n className=\"w-full\"\n >\n {vertical.map((tick) => {\n const y = yScale.project(tick.value);\n return (\n <g key={`y-${tick.value}`}>\n <line\n x1={plotArea.x0}\n x2={plotArea.x1}\n y1={y}\n y2={y}\n stroke={AXIS}\n strokeWidth={0.5}\n opacity={0.25}\n />\n <text x={plotArea.x0 - 6} y={y + 3.5} textAnchor=\"end\" fontSize={10} fill={AXIS}>\n {tick.label}\n </text>\n </g>\n );\n })}\n\n {horizontal.map((tick) => {\n const x = xScale.project(tick.value);\n return (\n <g key={`x-${tick.value}`}>\n <line\n x1={x}\n x2={x}\n y1={plotArea.y0}\n y2={plotArea.y1}\n stroke={AXIS}\n strokeWidth={0.5}\n opacity={0.15}\n />\n <text x={x} y={plotArea.y0 + 14} textAnchor=\"middle\" fontSize={10} fill={AXIS}>\n {tick.label}\n </text>\n </g>\n );\n })}\n\n <line\n x1={plotArea.x0}\n x2={plotArea.x1}\n y1={plotArea.y0}\n y2={plotArea.y0}\n stroke={AXIS}\n strokeWidth={1}\n opacity={0.6}\n />\n <line\n x1={plotArea.x0}\n x2={plotArea.x0}\n y1={plotArea.y0}\n y2={plotArea.y1}\n stroke={AXIS}\n strokeWidth={1}\n opacity={0.6}\n />\n\n {children}\n\n {xLabel && (\n <text\n x={(plotArea.x0 + plotArea.x1) / 2}\n y={PLOT.height - 2}\n textAnchor=\"middle\"\n fontSize={10}\n fill={AXIS}\n >\n {xLabel}\n </text>\n )}\n {yLabel && (\n <text\n transform={`translate(10 ${(plotArea.y0 + plotArea.y1) / 2}) rotate(-90)`}\n textAnchor=\"middle\"\n fontSize={10}\n fill={AXIS}\n >\n {yLabel}\n </text>\n )}\n </svg>\n {footer && <figcaption className=\"text-xs\">{footer}</figcaption>}\n </figure>\n );\n}\n\n\n/** One entry of a {@link Legend}. */\nexport interface LegendItem {\n /** The series name, rendered as text — it is what a screen reader announces. */\n label: string;\n /** Any CSS colour: a `var(--series-n)` from {@link seriesColour}, or a verdict token. */\n colour: string;\n}\n\n/** Props for {@link Legend}. */\nexport interface LegendProps {\n /** Entries, in the order the series were drawn. */\n items: LegendItem[];\n /** Extra classes for the `<ul>`, merged with `cn`. */\n className?: string | undefined;\n}\n\n/**\n * A legend row. Kept beside the frame rather than inside the SVG so the swatches are real\n * text and CSS rather than a second typography in viewBox units.\n *\n * @remarks\n * The swatches are `aria-hidden`; each series is identified by its name, never by colour\n * alone.\n */\nexport function Legend({ items, className }: LegendProps) {\n return (\n <ul className={cn(\"flex flex-wrap items-center gap-x-4 gap-y-1\", className)}>\n {items.map((item) => (\n <li key={item.label} className=\"flex items-center gap-1.5\">\n <span\n aria-hidden\n className=\"inline-block h-0.5 w-4 rounded\"\n style={{ backgroundColor: item.colour }}\n />\n <span className=\"font-mono text-xs\">{item.label}</span>\n </li>\n ))}\n </ul>\n );\n}\n\n/**\n * The shared categorical series palette, as CSS paint values: `var(--series-1)` …\n * `var(--series-6)`.\n *\n * @remarks\n * The colours themselves are tokens in `@vitavision/charts/styles.css`, defined for both\n * themes, so that stylesheet must be imported after `@vitavision/ui/styles.css`. The chrome\n * carries no saturation, which makes this the one place a chart is allowed to be loud.\n *\n * Each slot keeps its hue family across the themes — cyan, orange, violet, blue, pink, then\n * a neutral grey as the sixth — and only its lightness changes, so every colour holds 3:1\n * against the panel in both. The six stay distinguishable under simulated protanopia,\n * deuteranopia and tritanopia, and none of them is a verdict colour (`--normal`,\n * `--defect`, `--warn`): a series is never read as a verdict (PLAN §5).\n *\n * Before 0.6 these were fixed hex strings; the names are unchanged.\n */\nexport const SERIES_COLOURS = [\n \"var(--series-1)\",\n \"var(--series-2)\",\n \"var(--series-3)\",\n \"var(--series-4)\",\n \"var(--series-5)\",\n \"var(--series-6)\",\n] as const;\n\n/**\n * The paint for outcomes judged normal — `var(--normal)`, the design system's verdict token.\n *\n * @remarks\n * Exported so a histogram and any caught/missed bars share one green rather than each\n * restating it: a green that means \"normal\" has to be one green. Before 0.6 this was a\n * fixed hex string.\n */\nexport const NORMAL_COLOUR = \"var(--normal)\";\n\n/**\n * The paint for outcomes judged defective — `var(--defect)`, the design system's verdict\n * token.\n *\n * @remarks\n * The partner of {@link NORMAL_COLOUR}. Before 0.6 this was a fixed hex string.\n */\nexport const DEFECT_COLOUR = \"var(--defect)\";\n\n/**\n * The series colour for the `index`-th series, cycling through {@link SERIES_COLOURS}.\n *\n * @param index - Zero-based series index. Negative or non-integer indices fall back to the\n * neutral `var(--fg-muted)`.\n * @returns A CSS paint value, usable as an SVG `fill`/`stroke` or a CSS `color`.\n */\nexport function seriesColour(index: number): string {\n return SERIES_COLOURS[index % SERIES_COLOURS.length] ?? \"var(--fg-muted)\";\n}\n","/**\n * The arithmetic behind every chart: domains, ticks, and the map from a value to a pixel.\n *\n * Hand-rolled SVG rather than a charting library: the chart types this design system needs\n * are few and simple, and a library that lags the React and Tailwind versions the lab apps\n * are deliberately on would mean either downgrading a consumer or isolating a laggard — a\n * cost that outweighs a few hundred lines of scale maths.\n *\n * Everything here is pure. That is the point: it is the part worth unit-testing, and it\n * leaves the components themselves as thin as an SVG element list.\n */\n\n/** A tick's position in domain units, with the label to draw beside it. */\nexport interface Tick {\n /** Where the tick sits, in domain units — pass it to {@link Scale.project}. */\n value: number;\n /** The text to draw beside it, formatted by {@link formatTick}. */\n label: string;\n}\n\n/**\n * A map from a numeric domain onto a pixel range, with the ticks to label it.\n *\n * @remarks\n * Built by {@link linearScale} or {@link logScale}. `project` is not clamped: a value\n * outside the domain lands outside the range.\n */\nexport interface Scale {\n /** Domain, after padding and after any log transform's guard. */\n domain: [number, number];\n /** Map one domain value onto the pixel range this scale was built for. */\n project: (value: number) => number;\n /**\n * Ticks inside the domain, in ascending order.\n *\n * @param count - Roughly how many ticks to aim for (default 5). The result may have a\n * few more or fewer: steps are \"nice\" (see {@link niceStep}), or whole decades on a log\n * scale.\n */\n ticks: (count?: number) => Tick[];\n}\n\n/** Smallest value a log scale will accept, so a zero loss cannot become `-Infinity`. */\nconst LOG_FLOOR = 1e-12;\n\nconst TICK_STEPS = [1, 2, 2.5, 5, 10];\n\n/** Past this a label is noise; anything finer is shown as an exponent instead. */\nconst MAX_DECIMALS = 6;\n\n/**\n * A \"nice\" step at or above `rough` — one of 1, 2, 2.5 or 5 times a power of ten.\n *\n * Axis labels a reader can hold in their head are the whole reason: 0.25 / 0.50 / 0.75\n * rather than 0.237 / 0.474 / 0.711.\n */\nexport function niceStep(rough: number): number {\n if (!Number.isFinite(rough) || rough <= 0) return 1;\n const magnitude = 10 ** Math.floor(Math.log10(rough));\n const normalized = rough / magnitude;\n const step = TICK_STEPS.find((candidate) => candidate >= normalized - 1e-9) ?? 10;\n return step * magnitude;\n}\n\n/**\n * How many decimals a label needs so that neighbouring ticks do not print identically.\n *\n * Derived from the step rather than fixed, because one chart here might be a loss around\n * 1e-4 and another a residual in whole pixels. Enough decimals to print the *step* exactly\n * is the right rule, and `ceil(-log10(step))` is not it: a 0.25 step gets one decimal that\n * way, and the axis reads 0.3 / 0.5 / 0.8 — three labels for four evenly spaced ticks.\n */\nfunction decimalsFor(step: number): number {\n if (!Number.isFinite(step) || step <= 0) return 0;\n for (let decimals = 0; decimals < MAX_DECIMALS; decimals += 1) {\n if (Math.abs(Number(step.toFixed(decimals)) - step) < step * 1e-6) return decimals;\n }\n return MAX_DECIMALS;\n}\n\n/**\n * The label for one tick: as many decimals as the step needs, or an exponent for a\n * magnitude below 1e-3 or from 1e6 upwards.\n *\n * @param value - The tick's value.\n * @param step - The spacing between neighbouring ticks; it decides the decimals.\n * @returns The label, or `\"\"` for a non-finite value.\n */\nexport function formatTick(value: number, step: number): string {\n if (!Number.isFinite(value)) return \"\";\n const magnitude = Math.abs(value);\n // Outside the range where a decimal reads better than an exponent. A loss of 3.2e-5 is\n // legible; 0.000032 is a row of zeroes the eye has to count.\n if (magnitude !== 0 && (magnitude < 1e-3 || magnitude >= 1e6)) {\n return value.toExponential(1);\n }\n return value.toFixed(decimalsFor(step));\n}\n\n/**\n * Widen a degenerate domain into one that can be drawn.\n *\n * A single-point series, or a constant one, has `min === max`. Left alone that divides by\n * zero and the line vanishes; widened, the point sits in the middle of a sensible axis,\n * which is what watching the first moments of a training run, or a profile with one sample\n * so far, should look like.\n */\nexport function padDomain(min: number, max: number): [number, number] {\n if (!Number.isFinite(min) || !Number.isFinite(max)) return [0, 1];\n if (min === max) {\n const margin = Math.abs(min) > 0 ? Math.abs(min) * 0.1 : 1;\n return [min - margin, max + margin];\n }\n return [min, max];\n}\n\n/**\n * The `[min, max]` of the finite values, ignoring `NaN` and infinities.\n *\n * @returns `[0, 1]` when there is no finite value, so an empty series still has an axis.\n */\nexport function extent(values: readonly number[]): [number, number] {\n const finite = values.filter((value) => Number.isFinite(value));\n if (finite.length === 0) return [0, 1];\n return [Math.min(...finite), Math.max(...finite)];\n}\n\n/** A linear scale from `domain` onto `[rangeStart, rangeEnd]` pixels. */\nexport function linearScale(\n domain: [number, number],\n rangeStart: number,\n rangeEnd: number,\n): Scale {\n const [low, high] = padDomain(domain[0], domain[1]);\n const span = high - low;\n return {\n domain: [low, high],\n project: (value) => rangeStart + ((value - low) / span) * (rangeEnd - rangeStart),\n ticks: (count = 5) => {\n const step = niceStep(span / Math.max(1, count));\n const first = Math.ceil(low / step) * step;\n const ticks: Tick[] = [];\n for (let value = first; value <= high + step * 1e-9; value += step) {\n // Re-derived from the step index rather than accumulated, so floating-point drift\n // cannot turn 0.30000000000000004 into a label.\n const exact = Math.round(value / step) * step;\n ticks.push({ value: exact, label: formatTick(exact, step) });\n }\n return ticks;\n },\n };\n}\n\n/**\n * A base-10 log scale, for series that span decades.\n *\n * A loss curve is the canonical case: three terms that span decades and start far apart\n * are a flat line along the bottom for two of the three on a linear axis. Non-positive\n * values are clamped to `LOG_FLOOR` rather than dropped: a value that reaches exactly zero\n * is a real observation, and a gap in the line would read as missing data.\n */\nexport function logScale(domain: [number, number], rangeStart: number, rangeEnd: number): Scale {\n const low = Math.log10(Math.max(domain[0], LOG_FLOOR));\n const high = Math.log10(Math.max(domain[1], LOG_FLOOR));\n const [paddedLow, paddedHigh] = padDomain(low, high);\n const span = paddedHigh - paddedLow;\n\n return {\n domain: [10 ** paddedLow, 10 ** paddedHigh],\n project: (value) => {\n const transformed = Math.log10(Math.max(value, LOG_FLOOR));\n return rangeStart + ((transformed - paddedLow) / span) * (rangeEnd - rangeStart);\n },\n ticks: (count = 5) => {\n // One tick per decade, thinned when the range covers more decades than fit.\n const stride = Math.max(1, Math.ceil(span / Math.max(1, count)));\n const ticks: Tick[] = [];\n for (\n let exponent = Math.ceil(paddedLow);\n exponent <= paddedHigh + 1e-9;\n exponent += stride\n ) {\n const value = 10 ** exponent;\n ticks.push({ value, label: formatTick(value, value) });\n }\n return ticks;\n },\n };\n}\n\n/** An SVG `d` attribute through the projected points, skipping non-finite ones. */\nexport function linePath(\n points: readonly { x: number; y: number }[],\n xScale: Scale,\n yScale: Scale,\n): string {\n const commands: string[] = [];\n let pen = \"M\";\n for (const point of points) {\n if (!Number.isFinite(point.x) || !Number.isFinite(point.y)) {\n // Lift the pen rather than bridging the gap: a straight line across missing data\n // is an assertion nobody made.\n pen = \"M\";\n continue;\n }\n commands.push(`${pen}${xScale.project(point.x).toFixed(2)} ${yScale.project(point.y).toFixed(2)}`);\n pen = \"L\";\n }\n return commands.join(\" \");\n}\n\n/**\n * Bin values into `count` equal-width buckets over their own extent.\n *\n * Used for the score histogram, where the two classes must share one set of edges or the\n * bars cannot be compared. Callers pass the shared domain in for exactly that reason.\n */\nexport function histogram(\n values: readonly number[],\n domain: [number, number],\n count: number,\n): number[] {\n const bins = new Array<number>(Math.max(1, count)).fill(0);\n const [low, high] = domain;\n const span = high - low;\n if (span <= 0) {\n bins[0] = values.length;\n return bins;\n }\n for (const value of values) {\n if (!Number.isFinite(value)) continue;\n const index = Math.min(bins.length - 1, Math.floor(((value - low) / span) * bins.length));\n if (index >= 0) bins[index] = (bins[index] ?? 0) + 1;\n }\n return bins;\n}\n","/**\n * Multi-series line chart — training curves, or any series plotted over a shared axis.\n *\n * A series with no points draws nothing but still claims its legend entry, so a term that\n * has not reported yet is visibly pending rather than silently absent. A series with one\n * point draws a dot: at the start of a run that is genuinely all there is, and an empty\n * chart would read as \"nothing is happening\".\n */\n\nimport type { ReactNode } from \"react\";\n\nimport { Frame, Legend, areaFor, seriesColour } from \"./Frame\";\nimport type { Variant } from \"./Frame\";\nimport type { Scale } from \"./scale\";\nimport { extent, linePath, linearScale, logScale } from \"./scale\";\n\n/** One line of a {@link LineChart}. */\nexport interface Series {\n /** Legend text, and the React key — unique within one chart. */\n name: string;\n /**\n * Points in draw order. A non-finite coordinate lifts the pen rather than bridging the\n * gap; a single point draws a dot; no points draws nothing but keeps the legend entry.\n */\n points: { x: number; y: number }[];\n /** Any CSS colour. Omitted: {@link seriesColour} of the series' index. */\n colour?: string;\n}\n\n/** Props for {@link LineChart}. */\nexport interface LineChartProps {\n /** The lines, drawn in order — a later series paints over an earlier one. */\n series: Series[];\n /** Accessible name of the chart (the SVG's `aria-label`). Required. */\n label: string;\n /** x-axis title. */\n xLabel?: string;\n /** y-axis title. */\n yLabel?: string;\n /** Losses span decades; a linear axis flattens two of the three onto the floor. */\n logY?: boolean;\n /** Fixed domains, for charts whose axes are known — ROC and PR are both `[0, 1]`. */\n xDomain?: [number, number];\n /** Fixed y domain. Omitted: the extent of every series' `y`. */\n yDomain?: [number, number];\n /** Drawn behind the series, in plot pixels. A chance diagonal or a tolerance band uses this. */\n underlay?: (x: Scale, y: Scale) => ReactNode;\n /** Rendered under the legend, inside the `<figcaption>`. */\n footer?: ReactNode;\n /** Show the legend row. Default `true`. */\n showLegend?: boolean;\n /** Where the chart is going (see {@link Variant}). Default `\"panel\"`. */\n variant?: Variant;\n /** Extra classes for the outer `<figure>`, merged with `cn`. */\n className?: string | undefined;\n}\n\n/**\n * A multi-series line chart over a shared x axis — training curves, ROC and PR curves.\n *\n * @remarks\n * An SVG `role=\"img\"` named by `label`, with the legend as real text under it. Series are\n * told apart by the legend's names, never by colour alone.\n */\nexport function LineChart({\n series,\n label,\n xLabel,\n yLabel,\n logY = false,\n xDomain,\n yDomain,\n underlay,\n footer,\n showLegend = true,\n variant = \"panel\",\n className,\n}: LineChartProps) {\n const allX = series.flatMap((entry) => entry.points.map((point) => point.x));\n const allY = series.flatMap((entry) => entry.points.map((point) => point.y));\n const plotArea = areaFor(variant);\n\n const xScale = linearScale(xDomain ?? extent(allX), plotArea.x0, plotArea.x1);\n const makeY = logY ? logScale : linearScale;\n const yScale = makeY(yDomain ?? extent(allY), plotArea.y0, plotArea.y1);\n\n const coloured = series.map((entry, index) => ({\n ...entry,\n colour: entry.colour ?? seriesColour(index),\n }));\n\n return (\n <Frame\n xScale={xScale}\n yScale={yScale}\n xLabel={xLabel}\n yLabel={yLabel}\n label={label}\n variant={variant}\n className={className}\n footer={\n <div className=\"flex flex-col gap-1\">\n {showLegend && (\n <Legend\n items={coloured.map((entry) => ({ label: entry.name, colour: entry.colour }))}\n />\n )}\n {footer}\n </div>\n }\n >\n {underlay?.(xScale, yScale)}\n {coloured.map((entry) =>\n entry.points.length === 1 ? (\n <circle\n key={entry.name}\n cx={xScale.project(entry.points[0]?.x ?? 0)}\n cy={yScale.project(entry.points[0]?.y ?? 0)}\n r={2.5}\n fill={entry.colour}\n />\n ) : (\n <path\n key={entry.name}\n d={linePath(entry.points, xScale, yScale)}\n fill=\"none\"\n stroke={entry.colour}\n strokeWidth={1.5}\n strokeLinejoin=\"round\"\n vectorEffect=\"non-scaling-stroke\"\n />\n ),\n )}\n </Frame>\n );\n}\n","/**\n * Horizontal stacked bars — a per-category breakdown.\n *\n * Horizontal because the categories are free text — a defect type, a part family — and a\n * vertical axis would either truncate them or turn them sideways. Stacked because the\n * usual question is \"of this category, how many landed in each outcome\", which is a\n * proportion of a known total rather than independent counts.\n */\n\nimport { cn } from \"@vitavision/ui\";\n\n/** One category of {@link StackedBars}: a label and its segments. */\nexport interface BarRow {\n /** The category, shown truncated in a fixed-width column (full text in `title`). */\n label: string;\n /** Segments in draw order, left to right. */\n segments: { name: string; value: number; colour: string }[];\n}\n\n/** Props for {@link StackedBars}. */\nexport interface StackedBarsProps {\n /** The categories, top to bottom. */\n rows: BarRow[];\n /** Accessible name of the table. Required. */\n label: string;\n /** Extra classes for the outer element, merged with `cn`. */\n className?: string | undefined;\n}\n\n/**\n * Horizontal stacked bars, one row per category, all on one shared scale (the widest row's\n * total).\n *\n * @remarks\n * Exposed as an ARIA `table`: each row has a `rowheader` (the category) and a text cell that\n * spells every non-zero segment out as `\"<value> <name>\"`, so nothing depends on colour or\n * on bar width. A row with no non-zero segment shows its total.\n */\nexport function StackedBars({ rows, label, className }: StackedBarsProps) {\n const widest = Math.max(\n 1,\n ...rows.map((row) => row.segments.reduce((total, segment) => total + segment.value, 0)),\n );\n\n return (\n <div className={cn(\"flex flex-col gap-2\", className)} role=\"table\" aria-label={label}>\n {rows.map((row) => {\n const total = row.segments.reduce((sum, segment) => sum + segment.value, 0);\n return (\n <div key={row.label} className=\"flex items-center gap-3 text-xs\" role=\"row\">\n <span className=\"w-28 shrink-0 truncate font-mono\" role=\"rowheader\" title={row.label}>\n {row.label}\n </span>\n <div\n className=\"flex h-4 flex-1 overflow-hidden rounded bg-raised\"\n role=\"cell\"\n >\n {row.segments.map((segment) =>\n segment.value === 0 ? null : (\n <div\n key={segment.name}\n className=\"h-full\"\n style={{\n width: `${(segment.value / widest) * 100}%`,\n backgroundColor: segment.colour,\n }}\n title={`${segment.name}: ${segment.value}`}\n />\n ),\n )}\n </div>\n <span className=\"w-24 shrink-0 text-right font-mono text-fg-muted\" role=\"cell\">\n {row.segments\n .filter((segment) => segment.value > 0)\n .map((segment) => `${segment.value} ${segment.name}`)\n .join(\" · \") || `${total}`}\n </span>\n </div>\n );\n })}\n </div>\n );\n}\n","/**\n * Score distribution by class, with a threshold drawn on it.\n *\n * This is the chart that makes a threshold decision legible: a confusion matrix says how\n * many were wrong, and this says *why* — two distributions that barely separate, or one\n * long normal tail crossing the line.\n *\n * Both classes share one set of bin edges, computed over the union of their scores. Binned\n * separately they would be drawn on different axes and the overlap — the only thing worth\n * looking at — would be an artefact of the binning.\n */\n\nimport { DEFECT_COLOUR, Frame, NORMAL_COLOUR, areaFor } from \"./Frame\";\nimport { extent, histogram, linearScale } from \"./scale\";\n\n// The histogram is always given a whole panel, never a column of a grid.\nconst plotArea = areaFor(\"wide\");\n\n// Green for normal, red for defect — the verdict tokens, named once in `Frame`.\nconst NORMAL_FILL = NORMAL_COLOUR;\nconst DEFECT_FILL = DEFECT_COLOUR;\n\n/** Props for {@link ScoreHistogram}. */\nexport interface HistogramProps {\n /** Anomaly scores of the samples labelled normal. */\n normal: number[];\n /** Anomaly scores of the samples labelled defective. */\n defect: number[];\n /** The decision threshold, drawn as a dashed vertical rule. Omitted or non-finite: none. */\n threshold?: number;\n /** Number of equal-width bins over the union of both classes' scores. Default 32. */\n bins?: number;\n /** Accessible name of the chart (the SVG's `aria-label`). Required. */\n label: string;\n /** Extra classes for the outer `<figure>`, merged with `cn`. */\n className?: string | undefined;\n}\n\n/**\n * Overlaid histograms of the normal and defect score distributions, with the threshold on\n * them.\n *\n * @remarks\n * Always the `wide` variant. Painted in the verdict tokens (`--normal`, `--defect`); the\n * legend names both classes with their counts, so the chart does not rely on colour alone.\n */\nexport function ScoreHistogram({\n normal,\n defect,\n threshold,\n bins = 32,\n label,\n className,\n}: HistogramProps) {\n const domain = extent([...normal, ...defect]);\n const normalBins = histogram(normal, domain, bins);\n const defectBins = histogram(defect, domain, bins);\n const tallest = Math.max(1, ...normalBins, ...defectBins);\n\n const xScale = linearScale(domain, plotArea.x0, plotArea.x1);\n const yScale = linearScale([0, tallest], plotArea.y0, plotArea.y1);\n const binWidth = (plotArea.x1 - plotArea.x0) / bins;\n\n const bars = (counts: number[], fill: string, opacity: number) =>\n counts\n .map((count, index) => ({ count, x: plotArea.x0 + index * binWidth }))\n .map(({ count, x }) =>\n count === 0 ? null : (\n <rect\n key={`${fill}-${x}`}\n x={x}\n y={yScale.project(count)}\n width={Math.max(0.5, binWidth - 0.5)}\n height={plotArea.y0 - yScale.project(count)}\n fill={fill}\n opacity={opacity}\n />\n ),\n );\n\n return (\n <Frame\n xScale={xScale}\n yScale={yScale}\n xLabel=\"anomaly score\"\n yLabel=\"samples\"\n label={label}\n variant=\"wide\"\n className={className}\n footer={\n <ul className=\"flex flex-wrap items-center gap-x-4 gap-y-1\">\n <li className=\"flex items-center gap-1.5\">\n <span\n aria-hidden\n className=\"inline-block h-2 w-3 rounded-sm\"\n style={{ backgroundColor: NORMAL_FILL, opacity: 0.75 }}\n />\n <span className=\"font-mono text-xs\">normal ({normal.length})</span>\n </li>\n <li className=\"flex items-center gap-1.5\">\n <span\n aria-hidden\n className=\"inline-block h-2 w-3 rounded-sm\"\n style={{ backgroundColor: DEFECT_FILL, opacity: 0.75 }}\n />\n <span className=\"font-mono text-xs\">defect ({defect.length})</span>\n </li>\n {threshold !== undefined && (\n <li className=\"font-mono text-xs\">threshold {threshold.toFixed(4)}</li>\n )}\n </ul>\n }\n >\n {/* Normals first and defects over them: the defect bars are the smaller population\n in every realistic split, so drawing them last keeps them from being buried. */}\n {bars(normalBins, NORMAL_FILL, 0.65)}\n {bars(defectBins, DEFECT_FILL, 0.65)}\n\n {threshold !== undefined && Number.isFinite(threshold) && (\n <line\n x1={xScale.project(threshold)}\n x2={xScale.project(threshold)}\n y1={plotArea.y0}\n y2={plotArea.y1}\n stroke=\"currentColor\"\n strokeWidth={1.25}\n strokeDasharray=\"3 2\"\n />\n )}\n </Frame>\n );\n}\n","/**\n * A 1-D profile chart — intensity or value against arc length along a scan line or a\n * caliper axis.\n *\n * Built on the same `Frame` and `scale.ts` every other chart here uses, so a profile reads\n * as part of the same visual system as a training curve or a score histogram rather than a\n * one-off. The one thing a profile chart needs that a loss curve does not is a way to mark\n * *where along x a decision landed* — a detected edge, a caliper's chosen crossing — as a\n * vertical rule with its own label, independent of the series being plotted.\n */\n\nimport type { ReactNode } from \"react\";\n\nimport { Frame, Legend, areaFor, seriesColour } from \"./Frame\";\nimport type { Variant } from \"./Frame\";\nimport { extent, linePath, linearScale } from \"./scale\";\nimport { toneColor, type MeasureTone } from \"@vitavision/ui\";\n\n/** One sampled profile of a {@link LineProfile}. */\nexport interface ProfileSeries {\n /** Legend text, and the React key — unique within one chart. */\n name: string;\n /** `x` is arc length along the scan line or caliper axis, in pixels. */\n points: { x: number; y: number }[];\n /** Any CSS colour. Omitted: {@link seriesColour} of the series' index. */\n colour?: string;\n}\n\n/** A detected edge or chosen crossing, drawn as a dashed vertical rule. */\nexport interface EdgeMark {\n /** Position along the same arc-length axis as `ProfileSeries.points[].x`. */\n position: number;\n /** Text drawn above the rule, in the rule's colour. Omitted: no text. */\n label?: string;\n /** The rule's colour, as a `@vitavision/ui` measurement tone. Default `\"signal\"`. */\n tone?: MeasureTone;\n}\n\n/** Props for {@link LineProfile}. */\nexport interface LineProfileProps {\n /** The profiles, drawn in order. */\n series: ProfileSeries[];\n /** Detected edge positions, drawn as vertical rules over the series. */\n edges?: EdgeMark[];\n /** Accessible name of the chart (the SVG's `aria-label`). Required. */\n label: string;\n /** x-axis title. Default `\"arc length (px)\"`. */\n xLabel?: string;\n /** y-axis title. Default `\"value\"`. */\n yLabel?: string;\n /** Fixed x domain. Omitted: the extent of every point's `x` and every edge's position. */\n xDomain?: [number, number];\n /** Fixed y domain. Omitted: the extent of every point's `y`. */\n yDomain?: [number, number];\n /** Rendered under the legend, inside the `<figcaption>`. */\n footer?: ReactNode;\n /** Show the legend row when there is more than one series. Default `true`. */\n showLegend?: boolean;\n /** Where the chart is going (see {@link Variant}). Default `\"wide\"`. */\n variant?: Variant;\n /** Extra classes for the outer `<figure>`, merged with `cn`. */\n className?: string | undefined;\n}\n\n/**\n * One or more series against arc length along a scan line or caliper axis, with detected\n * edges as labelled vertical rules.\n *\n * @remarks\n * An SVG `role=\"img\"` named by `label`. The legend appears only for two or more series — a\n * single profile is named by the chart's label.\n */\nexport function LineProfile({\n series,\n edges = [],\n label,\n xLabel = \"arc length (px)\",\n yLabel = \"value\",\n xDomain,\n yDomain,\n footer,\n showLegend = true,\n variant = \"wide\",\n className,\n}: LineProfileProps) {\n const allX = [...series.flatMap((entry) => entry.points.map((point) => point.x)), ...edges.map((edge) => edge.position)];\n const allY = series.flatMap((entry) => entry.points.map((point) => point.y));\n const plotArea = areaFor(variant);\n\n const xScale = linearScale(xDomain ?? extent(allX), plotArea.x0, plotArea.x1);\n const yScale = linearScale(yDomain ?? extent(allY), plotArea.y0, plotArea.y1);\n\n const coloured = series.map((entry, index) => ({\n ...entry,\n colour: entry.colour ?? seriesColour(index),\n }));\n\n return (\n <Frame\n xScale={xScale}\n yScale={yScale}\n xLabel={xLabel}\n yLabel={yLabel}\n label={label}\n variant={variant}\n className={className}\n footer={\n <div className=\"flex flex-col gap-1\">\n {showLegend && series.length > 1 && (\n <Legend\n items={coloured.map((entry) => ({ label: entry.name, colour: entry.colour }))}\n />\n )}\n {footer}\n </div>\n }\n >\n {coloured.map((entry) =>\n entry.points.length === 1 ? (\n <circle\n key={entry.name}\n cx={xScale.project(entry.points[0]?.x ?? 0)}\n cy={yScale.project(entry.points[0]?.y ?? 0)}\n r={2.5}\n fill={entry.colour}\n />\n ) : (\n <path\n key={entry.name}\n d={linePath(entry.points, xScale, yScale)}\n fill=\"none\"\n stroke={entry.colour}\n strokeWidth={1.5}\n strokeLinejoin=\"round\"\n vectorEffect=\"non-scaling-stroke\"\n />\n ),\n )}\n\n {edges.map((edge) => {\n const x = xScale.project(edge.position);\n const colour = toneColor(edge.tone, \"signal\");\n return (\n <g key={`${edge.position}-${edge.label ?? \"\"}-${edge.tone ?? \"\"}`}>\n <line\n x1={x}\n x2={x}\n y1={plotArea.y0}\n y2={plotArea.y1}\n stroke={colour}\n strokeWidth={1.25}\n strokeDasharray=\"3 2\"\n />\n {edge.label && (\n <text x={x} y={plotArea.y1 - 3} textAnchor=\"middle\" fontSize={9} fill={colour}>\n {edge.label}\n </text>\n )}\n </g>\n );\n })}\n </Frame>\n );\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B,CAAA,GACA,KAAK,SACJ,oBAAC,QAAD;IAAS;IAAG,GAAG,SAAS,KAAK;IAAG,YAAW;IAAS,UAAU;IAAG,MAAM;IACpE,UAAA,KAAK;GACF,CAAA,CAEP,EAAA,GAfK,GAAG,KAAK,SAAS,GAAG,KAAK,SAAS,GAAG,GAAG,KAAK,QAAQ,IAe1D;EAEP,CAAC,CACI;;AAEX"}
package/package.json ADDED
@@ -0,0 +1,55 @@
1
+ {
2
+ "name": "@vitavision/charts",
3
+ "version": "0.6.0",
4
+ "description": "Small SVG charts for the vitavision lab apps: histogram, line, bar, line profile, scales.",
5
+ "license": "MIT OR Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/VitalyVorobyev/lab-ui.git",
9
+ "directory": "packages/charts"
10
+ },
11
+ "homepage": "https://github.com/VitalyVorobyev/lab-ui/tree/main/packages/charts#readme",
12
+ "type": "module",
13
+ "sideEffects": [
14
+ "*.css"
15
+ ],
16
+ "files": [
17
+ "dist",
18
+ "src",
19
+ "!src/**/*.test.*",
20
+ "!src/**/*.stories.*",
21
+ "LICENSE-MIT",
22
+ "LICENSE-APACHE"
23
+ ],
24
+ "exports": {
25
+ ".": {
26
+ "@vitavision/source": "./src/index.ts",
27
+ "types": "./dist/index.d.ts",
28
+ "import": "./dist/index.js"
29
+ },
30
+ "./styles.css": "./src/styles.css",
31
+ "./package.json": "./package.json"
32
+ },
33
+ "publishConfig": {
34
+ "access": "public"
35
+ },
36
+ "scripts": {
37
+ "build": "tsdown",
38
+ "typecheck": "tsc --noEmit",
39
+ "test": "vitest run",
40
+ "api": "api-extractor run --local",
41
+ "coverage": "vitest run --coverage",
42
+ "api:check": "api-extractor run"
43
+ },
44
+ "peerDependencies": {
45
+ "react": "^19.2.0",
46
+ "react-dom": "^19.2.0"
47
+ },
48
+ "dependencies": {
49
+ "@vitavision/ui": "^0.6.0"
50
+ },
51
+ "devDependencies": {
52
+ "@storybook/react-vite": "10.6.0",
53
+ "storybook": "10.6.0"
54
+ }
55
+ }
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Horizontal stacked bars — a per-category breakdown.
3
+ *
4
+ * Horizontal because the categories are free text — a defect type, a part family — and a
5
+ * vertical axis would either truncate them or turn them sideways. Stacked because the
6
+ * usual question is "of this category, how many landed in each outcome", which is a
7
+ * proportion of a known total rather than independent counts.
8
+ */
9
+
10
+ import { cn } from "@vitavision/ui";
11
+
12
+ /** One category of {@link StackedBars}: a label and its segments. */
13
+ export interface BarRow {
14
+ /** The category, shown truncated in a fixed-width column (full text in `title`). */
15
+ label: string;
16
+ /** Segments in draw order, left to right. */
17
+ segments: { name: string; value: number; colour: string }[];
18
+ }
19
+
20
+ /** Props for {@link StackedBars}. */
21
+ export interface StackedBarsProps {
22
+ /** The categories, top to bottom. */
23
+ rows: BarRow[];
24
+ /** Accessible name of the table. Required. */
25
+ label: string;
26
+ /** Extra classes for the outer element, merged with `cn`. */
27
+ className?: string | undefined;
28
+ }
29
+
30
+ /**
31
+ * Horizontal stacked bars, one row per category, all on one shared scale (the widest row's
32
+ * total).
33
+ *
34
+ * @remarks
35
+ * Exposed as an ARIA `table`: each row has a `rowheader` (the category) and a text cell that
36
+ * spells every non-zero segment out as `"<value> <name>"`, so nothing depends on colour or
37
+ * on bar width. A row with no non-zero segment shows its total.
38
+ */
39
+ export function StackedBars({ rows, label, className }: StackedBarsProps) {
40
+ const widest = Math.max(
41
+ 1,
42
+ ...rows.map((row) => row.segments.reduce((total, segment) => total + segment.value, 0)),
43
+ );
44
+
45
+ return (
46
+ <div className={cn("flex flex-col gap-2", className)} role="table" aria-label={label}>
47
+ {rows.map((row) => {
48
+ const total = row.segments.reduce((sum, segment) => sum + segment.value, 0);
49
+ return (
50
+ <div key={row.label} className="flex items-center gap-3 text-xs" role="row">
51
+ <span className="w-28 shrink-0 truncate font-mono" role="rowheader" title={row.label}>
52
+ {row.label}
53
+ </span>
54
+ <div
55
+ className="flex h-4 flex-1 overflow-hidden rounded bg-raised"
56
+ role="cell"
57
+ >
58
+ {row.segments.map((segment) =>
59
+ segment.value === 0 ? null : (
60
+ <div
61
+ key={segment.name}
62
+ className="h-full"
63
+ style={{
64
+ width: `${(segment.value / widest) * 100}%`,
65
+ backgroundColor: segment.colour,
66
+ }}
67
+ title={`${segment.name}: ${segment.value}`}
68
+ />
69
+ ),
70
+ )}
71
+ </div>
72
+ <span className="w-24 shrink-0 text-right font-mono text-fg-muted" role="cell">
73
+ {row.segments
74
+ .filter((segment) => segment.value > 0)
75
+ .map((segment) => `${segment.value} ${segment.name}`)
76
+ .join(" · ") || `${total}`}
77
+ </span>
78
+ </div>
79
+ );
80
+ })}
81
+ </div>
82
+ );
83
+ }
package/src/Frame.tsx ADDED
@@ -0,0 +1,308 @@
1
+ /**
2
+ * The plot frame every chart here composes: axes, ticks, grid, labels.
3
+ *
4
+ * Charts are drawn into a fixed `viewBox` and scaled by CSS, so one component works at
5
+ * any panel width without measuring the DOM. The consequence is that font sizes are in
6
+ * viewBox units and therefore scale with the chart: the *same* 10-unit label renders at
7
+ * 9 px in a half-width panel and at 21 px across a full-width one, which looks like two
8
+ * different design systems on one screen.
9
+ *
10
+ * So the viewBox is chosen to roughly match the width the chart will actually be given.
11
+ * `panel` is for the two-column grids, `wide` for a chart that spans a panel on its own.
12
+ * That keeps the scale factor near 1 in both, and it is why callers pick a variant rather
13
+ * than a pixel width — the variant says where the chart is going, not how big to draw it.
14
+ */
15
+
16
+ import type { ReactNode } from "react";
17
+
18
+ import { cn } from "@vitavision/ui";
19
+
20
+ import type { Scale } from "./scale";
21
+
22
+ /**
23
+ * Where a chart is going: `panel` (a 480×280 viewBox) for one column of a two-column grid,
24
+ * `wide` (960×320) for a chart that spans a panel on its own.
25
+ *
26
+ * @remarks
27
+ * Pick it by placement, not by pixel width — it keeps the chart's text at the same rendered
28
+ * size as its neighbours'.
29
+ */
30
+ export type Variant = "panel" | "wide";
31
+
32
+ const GEOMETRY = {
33
+ panel: { width: 480, height: 280 },
34
+ wide: { width: 960, height: 320 },
35
+ } as const;
36
+
37
+ const MARGIN = { left: 56, right: 12, top: 12, bottom: 34 } as const;
38
+
39
+ /**
40
+ * The drawable rectangle for one variant, in that variant's viewBox units.
41
+ *
42
+ * @param variant - Which viewBox the chart is drawn in.
43
+ * @returns The plot area's edges — `x0`/`x1` left to right, `y0` the bottom and `y1` the top
44
+ * (SVG y grows downwards) — and the whole viewBox's `width`/`height`. Build scales over
45
+ * `[x0, x1]` and `[y0, y1]`.
46
+ */
47
+ export function areaFor(variant: Variant) {
48
+ const { width, height } = GEOMETRY[variant];
49
+ return {
50
+ x0: MARGIN.left,
51
+ x1: width - MARGIN.right,
52
+ y0: height - MARGIN.bottom,
53
+ y1: MARGIN.top,
54
+ width,
55
+ height,
56
+ };
57
+ }
58
+
59
+ /** The default geometry, for callers that do not care which variant they are in. */
60
+ export const plotArea = areaFor("panel");
61
+
62
+ /** Held at the two ends of the neutral ramp, matching the design system's chrome colours. */
63
+ const AXIS = "currentColor";
64
+
65
+ /** Props for {@link Frame}. */
66
+ export interface FrameProps {
67
+ /** The horizontal scale, built over this variant's `x0`…`x1` (see {@link areaFor}). */
68
+ xScale: Scale;
69
+ /** The vertical scale, built over this variant's `y0`…`y1` (see {@link areaFor}). */
70
+ yScale: Scale;
71
+ /** Axis title under the x axis. Omitted: no title. */
72
+ xLabel?: string | undefined;
73
+ /** Axis title beside the y axis, rotated. Omitted: no title. */
74
+ yLabel?: string | undefined;
75
+ /** Rough number of x ticks to ask the scale for. Default 5. */
76
+ xTicks?: number;
77
+ /** Rough number of y ticks to ask the scale for. Default 4. */
78
+ yTicks?: number;
79
+ /** Drawn inside the plot area, above the grid and below nothing. */
80
+ children?: ReactNode;
81
+ /** Accessible name — every chart must have one; it is what the tests query on. */
82
+ label: string;
83
+ /** Rendered under the plot: a legend, a caption, a truncation note. */
84
+ footer?: ReactNode;
85
+ /** Where this chart is going, so its text renders at the same size as its neighbours. */
86
+ variant?: Variant;
87
+ /** Extra classes for the outer `<figure>`, merged with `cn`. */
88
+ className?: string | undefined;
89
+ }
90
+
91
+ /**
92
+ * The plot shell every chart here composes: grid, ticks, axes, axis titles, a footer.
93
+ *
94
+ * @remarks
95
+ * Renders a `<figure>` holding an SVG with `role="img"` named by `label`, and the `footer`
96
+ * as its `<figcaption>`. `children` are drawn in viewBox units over the grid.
97
+ */
98
+ export function Frame({
99
+ xScale,
100
+ yScale,
101
+ xLabel,
102
+ yLabel,
103
+ xTicks = 5,
104
+ yTicks = 4,
105
+ children,
106
+ label,
107
+ footer,
108
+ variant = "panel",
109
+ className,
110
+ }: FrameProps) {
111
+ const horizontal = xScale.ticks(xTicks);
112
+ const vertical = yScale.ticks(yTicks);
113
+ const plotArea = areaFor(variant);
114
+ const PLOT = GEOMETRY[variant];
115
+
116
+ return (
117
+ <figure className={cn("flex flex-col gap-1 text-fg-muted", className)}>
118
+ <svg
119
+ role="img"
120
+ aria-label={label}
121
+ viewBox={`0 0 ${PLOT.width} ${PLOT.height}`}
122
+ className="w-full"
123
+ >
124
+ {vertical.map((tick) => {
125
+ const y = yScale.project(tick.value);
126
+ return (
127
+ <g key={`y-${tick.value}`}>
128
+ <line
129
+ x1={plotArea.x0}
130
+ x2={plotArea.x1}
131
+ y1={y}
132
+ y2={y}
133
+ stroke={AXIS}
134
+ strokeWidth={0.5}
135
+ opacity={0.25}
136
+ />
137
+ <text x={plotArea.x0 - 6} y={y + 3.5} textAnchor="end" fontSize={10} fill={AXIS}>
138
+ {tick.label}
139
+ </text>
140
+ </g>
141
+ );
142
+ })}
143
+
144
+ {horizontal.map((tick) => {
145
+ const x = xScale.project(tick.value);
146
+ return (
147
+ <g key={`x-${tick.value}`}>
148
+ <line
149
+ x1={x}
150
+ x2={x}
151
+ y1={plotArea.y0}
152
+ y2={plotArea.y1}
153
+ stroke={AXIS}
154
+ strokeWidth={0.5}
155
+ opacity={0.15}
156
+ />
157
+ <text x={x} y={plotArea.y0 + 14} textAnchor="middle" fontSize={10} fill={AXIS}>
158
+ {tick.label}
159
+ </text>
160
+ </g>
161
+ );
162
+ })}
163
+
164
+ <line
165
+ x1={plotArea.x0}
166
+ x2={plotArea.x1}
167
+ y1={plotArea.y0}
168
+ y2={plotArea.y0}
169
+ stroke={AXIS}
170
+ strokeWidth={1}
171
+ opacity={0.6}
172
+ />
173
+ <line
174
+ x1={plotArea.x0}
175
+ x2={plotArea.x0}
176
+ y1={plotArea.y0}
177
+ y2={plotArea.y1}
178
+ stroke={AXIS}
179
+ strokeWidth={1}
180
+ opacity={0.6}
181
+ />
182
+
183
+ {children}
184
+
185
+ {xLabel && (
186
+ <text
187
+ x={(plotArea.x0 + plotArea.x1) / 2}
188
+ y={PLOT.height - 2}
189
+ textAnchor="middle"
190
+ fontSize={10}
191
+ fill={AXIS}
192
+ >
193
+ {xLabel}
194
+ </text>
195
+ )}
196
+ {yLabel && (
197
+ <text
198
+ transform={`translate(10 ${(plotArea.y0 + plotArea.y1) / 2}) rotate(-90)`}
199
+ textAnchor="middle"
200
+ fontSize={10}
201
+ fill={AXIS}
202
+ >
203
+ {yLabel}
204
+ </text>
205
+ )}
206
+ </svg>
207
+ {footer && <figcaption className="text-xs">{footer}</figcaption>}
208
+ </figure>
209
+ );
210
+ }
211
+
212
+
213
+ /** One entry of a {@link Legend}. */
214
+ export interface LegendItem {
215
+ /** The series name, rendered as text — it is what a screen reader announces. */
216
+ label: string;
217
+ /** Any CSS colour: a `var(--series-n)` from {@link seriesColour}, or a verdict token. */
218
+ colour: string;
219
+ }
220
+
221
+ /** Props for {@link Legend}. */
222
+ export interface LegendProps {
223
+ /** Entries, in the order the series were drawn. */
224
+ items: LegendItem[];
225
+ /** Extra classes for the `<ul>`, merged with `cn`. */
226
+ className?: string | undefined;
227
+ }
228
+
229
+ /**
230
+ * A legend row. Kept beside the frame rather than inside the SVG so the swatches are real
231
+ * text and CSS rather than a second typography in viewBox units.
232
+ *
233
+ * @remarks
234
+ * The swatches are `aria-hidden`; each series is identified by its name, never by colour
235
+ * alone.
236
+ */
237
+ export function Legend({ items, className }: LegendProps) {
238
+ return (
239
+ <ul className={cn("flex flex-wrap items-center gap-x-4 gap-y-1", className)}>
240
+ {items.map((item) => (
241
+ <li key={item.label} className="flex items-center gap-1.5">
242
+ <span
243
+ aria-hidden
244
+ className="inline-block h-0.5 w-4 rounded"
245
+ style={{ backgroundColor: item.colour }}
246
+ />
247
+ <span className="font-mono text-xs">{item.label}</span>
248
+ </li>
249
+ ))}
250
+ </ul>
251
+ );
252
+ }
253
+
254
+ /**
255
+ * The shared categorical series palette, as CSS paint values: `var(--series-1)` …
256
+ * `var(--series-6)`.
257
+ *
258
+ * @remarks
259
+ * The colours themselves are tokens in `@vitavision/charts/styles.css`, defined for both
260
+ * themes, so that stylesheet must be imported after `@vitavision/ui/styles.css`. The chrome
261
+ * carries no saturation, which makes this the one place a chart is allowed to be loud.
262
+ *
263
+ * Each slot keeps its hue family across the themes — cyan, orange, violet, blue, pink, then
264
+ * a neutral grey as the sixth — and only its lightness changes, so every colour holds 3:1
265
+ * against the panel in both. The six stay distinguishable under simulated protanopia,
266
+ * deuteranopia and tritanopia, and none of them is a verdict colour (`--normal`,
267
+ * `--defect`, `--warn`): a series is never read as a verdict (PLAN §5).
268
+ *
269
+ * Before 0.6 these were fixed hex strings; the names are unchanged.
270
+ */
271
+ export const SERIES_COLOURS = [
272
+ "var(--series-1)",
273
+ "var(--series-2)",
274
+ "var(--series-3)",
275
+ "var(--series-4)",
276
+ "var(--series-5)",
277
+ "var(--series-6)",
278
+ ] as const;
279
+
280
+ /**
281
+ * The paint for outcomes judged normal — `var(--normal)`, the design system's verdict token.
282
+ *
283
+ * @remarks
284
+ * Exported so a histogram and any caught/missed bars share one green rather than each
285
+ * restating it: a green that means "normal" has to be one green. Before 0.6 this was a
286
+ * fixed hex string.
287
+ */
288
+ export const NORMAL_COLOUR = "var(--normal)";
289
+
290
+ /**
291
+ * The paint for outcomes judged defective — `var(--defect)`, the design system's verdict
292
+ * token.
293
+ *
294
+ * @remarks
295
+ * The partner of {@link NORMAL_COLOUR}. Before 0.6 this was a fixed hex string.
296
+ */
297
+ export const DEFECT_COLOUR = "var(--defect)";
298
+
299
+ /**
300
+ * The series colour for the `index`-th series, cycling through {@link SERIES_COLOURS}.
301
+ *
302
+ * @param index - Zero-based series index. Negative or non-integer indices fall back to the
303
+ * neutral `var(--fg-muted)`.
304
+ * @returns A CSS paint value, usable as an SVG `fill`/`stroke` or a CSS `color`.
305
+ */
306
+ export function seriesColour(index: number): string {
307
+ return SERIES_COLOURS[index % SERIES_COLOURS.length] ?? "var(--fg-muted)";
308
+ }