Chart foundations
Scales, ticks, smooth paths, colour slots, number formatting, and the size and keyboard-cursor hooks every Thrum chart draws through. No dependencies beyond React.
Install
npx shadcn@latest add https://thrumui.dev/r/thrum-chart.jsonAdds lib/thrum-chart.ts. Nothing else in your project changes.
import { scaleLinear } from "@/lib/thrum-chart";Source
/**
* Chart foundations: scales, ticks, smooth paths, colour slots, and two small hooks
* (container size, keyboard cursor). Every chart component in the library draws through this file.
* The maths is pure and has no dependencies; the hooks need React and run in the browser only.
*/
import { useCallback, useEffect, useRef, useState, useSyncExternalStore, type KeyboardEvent, type RefObject } from "react";
export type Point = { x: number; y: number };
export type Scale = {
(value: number): number;
invert(px: number): number;
domain: readonly [number, number];
range: readonly [number, number];
};
const isNum = (v: unknown): v is number => typeof v === "number" && Number.isFinite(v);
/** Round to 2 decimals so path strings stay short and stable. */
const r = (n: number) => Math.round(n * 100) / 100;
/** Map a value in `domain` to a position in `range`. A zero-width domain maps to the middle of the range. */
export function scaleLinear(domain: readonly [number, number], range: readonly [number, number]): Scale {
const [d0, d1] = domain;
const [r0, r1] = range;
const span = d1 - d0;
const scale = ((value: number) => (span === 0 ? (r0 + r1) / 2 : r0 + ((value - d0) / span) * (r1 - r0))) as Scale;
scale.invert = (px: number) => (r1 === r0 ? d0 : d0 + ((px - r0) / (r1 - r0)) * span);
scale.domain = domain;
scale.range = range;
return scale;
}
/** Min and max of the finite values. Empty input gives [0, 1]; flat input is padded so it has height. */
export function extent(values: readonly (number | null | undefined)[]): [number, number] {
let min = Infinity;
let max = -Infinity;
for (const v of values) {
if (!isNum(v)) continue;
if (v < min) min = v;
if (v > max) max = v;
}
if (min === Infinity) return [0, 1];
if (min === max) {
const pad = Math.abs(min) * 0.1 || 1;
return [min - pad, max + pad];
}
return [min, max];
}
/** A step of 1, 2 or 5 times a power of ten that splits `span` into roughly `count` parts. */
function niceStep(span: number, count: number): number {
const raw = span / Math.max(1, count);
const pow = 10 ** Math.floor(Math.log10(raw));
const err = raw / pow;
return (err >= 7.5 ? 10 : err >= 3.5 ? 5 : err >= 1.5 ? 2 : 1) * pow;
}
/** Decimal places needed to print a step without float noise (0.1 + 0.2 problems). */
function decimals(step: number): number {
return Math.max(0, -Math.floor(Math.log10(step) + 1e-9));
}
/** Round, human-friendly tick values inside [min, max]. */
export function niceTicks(min: number, max: number, count = 5): number[] {
if (!isNum(min) || !isNum(max)) return [];
if (min > max) [min, max] = [max, min];
if (min === max) return [min];
const step = niceStep(max - min, count);
const places = decimals(step);
const ticks: number[] = [];
const start = Math.ceil(min / step - 1e-9);
const end = Math.floor(max / step + 1e-9);
for (let i = start; i <= end; i++) ticks.push(Number((i * step).toFixed(places)));
return ticks;
}
/**
* Widen [min, max] outwards to nice tick values. `niceTicks` over the result, with the same `count`,
* starts on its first value and ends on its last: no data sits beyond the outermost grid line.
*/
export function niceDomain(min: number, max: number, count = 5): [number, number] {
if (!isNum(min) || !isNum(max)) return [0, 1];
if (min > max) [min, max] = [max, min];
if (min === max) return extent([min]);
// Widening can call for a larger step, which can call for widening again. It settles within a few rounds.
for (let round = 0; round < 8; round++) {
const step = niceStep(max - min, count);
const places = decimals(step);
const lo = Number((Math.floor(min / step + 1e-9) * step).toFixed(places));
const hi = Number((Math.ceil(max / step - 1e-9) * step).toFixed(places));
if (lo === min && hi === max) break;
[min, max] = [lo, hi];
}
return [min, max];
}
/** Tangent slopes that keep the curve monotone between points (Steffen's method). */
function tangents(pts: readonly Point[]): number[] {
const n = pts.length;
const m = new Array<number>(n).fill(0);
if (n < 2) return m;
const slope = (i: number) => {
const dx = pts[i + 1].x - pts[i].x;
return dx === 0 ? 0 : (pts[i + 1].y - pts[i].y) / dx;
};
if (n === 2) {
m[0] = m[1] = slope(0);
return m;
}
for (let i = 1; i < n - 1; i++) {
const h0 = pts[i].x - pts[i - 1].x;
const h1 = pts[i + 1].x - pts[i].x;
const s0 = slope(i - 1);
const s1 = slope(i);
const p = h0 + h1 === 0 ? 0 : (s0 * h1 + s1 * h0) / (h0 + h1);
m[i] = (Math.sign(s0) + Math.sign(s1)) * Math.min(Math.abs(s0), Math.abs(s1), 0.5 * Math.abs(p)) || 0;
}
m[0] = (3 * slope(0) - m[1]) / 2;
m[n - 1] = (3 * slope(n - 2) - m[n - 2]) / 2;
return m;
}
function segment(pts: readonly Point[]): string {
if (pts.length === 0) return "";
let d = `M${r(pts[0].x)},${r(pts[0].y)}`;
if (pts.length === 1) return d;
const m = tangents(pts);
for (let i = 0; i < pts.length - 1; i++) {
const a = pts[i];
const b = pts[i + 1];
const dx = (b.x - a.x) / 3;
d += `C${r(a.x + dx)},${r(a.y + dx * m[i])} ${r(b.x - dx)},${r(b.y - dx * m[i + 1])} ${r(b.x)},${r(b.y)}`;
}
return d;
}
/** Split at null or non-finite points, so missing data leaves a gap in the line. */
function runs(points: readonly (Point | null | undefined)[]): Point[][] {
const out: Point[][] = [];
let cur: Point[] = [];
for (const p of points) {
if (p && isNum(p.x) && isNum(p.y)) cur.push(p);
else if (cur.length) {
out.push(cur);
cur = [];
}
}
if (cur.length) out.push(cur);
return out;
}
/**
* Smooth SVG path through the points, sorted by x. It never overshoots the data.
* The same number of points always gives the same command structure, so two paths can be morphed.
*/
export function linePath(points: readonly (Point | null | undefined)[]): string {
return runs(points).map(segment).join("");
}
/** The same curve, closed down to the baseline `y0` for an area fill. */
export function areaPath(points: readonly (Point | null | undefined)[], y0: number): string {
return runs(points)
.map((run) => `${segment(run)}L${r(run[run.length - 1].x)},${r(y0)}L${r(run[0].x)},${r(y0)}Z`)
.join("");
}
/** Index of the value in ascending `xs` closest to `x`, or -1 when `xs` is empty. */
export function nearestIndex(xs: readonly number[], x: number): number {
if (xs.length === 0) return -1;
let lo = 0;
let hi = xs.length - 1;
while (hi - lo > 1) {
const mid = (lo + hi) >> 1;
if (xs[mid] <= x) lo = mid;
else hi = mid;
}
return x - xs[lo] <= xs[hi] - x ? lo : hi;
}
/**
* SVG arc from angle `start` to `end`, in degrees clockwise from 12 o'clock.
* A full turn is drawn as just under 360 degrees so the arc never collapses to nothing.
*/
export function arcPath(cx: number, cy: number, radius: number, start: number, end: number): string {
const sweep = Math.max(-359.99, Math.min(359.99, end - start));
const at = (deg: number): [number, number] => {
const a = ((deg - 90) * Math.PI) / 180;
return [cx + radius * Math.cos(a), cy + radius * Math.sin(a)];
};
const [x0, y0] = at(start);
const [x1, y1] = at(start + sweep);
return `M${r(x0)},${r(y0)}A${r(radius)},${r(radius)} 0 ${Math.abs(sweep) > 180 ? 1 : 0} ${sweep >= 0 ? 1 : 0} ${r(x1)},${r(y1)}`;
}
const COMPACT: Intl.NumberFormatOptions = { notation: "compact", maximumFractionDigits: 1 };
const formatters = new Map<string, Intl.NumberFormat>();
/**
* Format a number with `Intl.NumberFormat` options. Options are plain data, so a server component
* can pass them to a chart. The locale defaults to US English so server and browser print the same text.
* Anything that is not a finite number prints as a dash.
*/
export function formatValue(value: number | null | undefined, options: Intl.NumberFormatOptions = COMPACT, locale = "en-US"): string {
if (!isNum(value)) return "–";
const key = locale + JSON.stringify(options);
let formatter = formatters.get(key);
if (!formatter) formatters.set(key, (formatter = new Intl.NumberFormat(locale, options)));
return formatter.format(value);
}
/** Short, readable number: 12831 becomes "12.8K". */
export function formatCompact(value: number): string {
return formatValue(value);
}
// ---------------------------------------------------------------------------------------------
// Colour. Components read the host project's theme variables and never hard-code a palette.
/**
* Colour for series `index` (from 0). Slots are assigned in order and never cycled:
* a seventh series is drawn in the neutral colour and should be grouped as "Other".
*/
export function seriesColor(index: number): string {
if (index >= 0 && index < 5) return `var(--chart-${index + 1})`;
return index === 5 ? "var(--chart-6, var(--muted-foreground))" : "var(--muted-foreground)";
}
/**
* Series slots (from 0) for a ring of `count` slices, where the last slice touches the first.
* The order keeps every touching pair easy to tell apart for red-green colour blindness.
*/
export function ringSlots(count: number): number[] {
const order: Record<number, number[]> = { 1: [0], 2: [0, 3], 3: [0, 3, 5], 4: [0, 1, 2, 3], 5: [0, 1, 2, 3, 5] };
return order[count] ?? Array.from({ length: Math.max(0, count) }, (_, i) => Math.min(i, 6));
}
/** Status colours. `success` and `warning` come from the theme when it defines them. */
export const STATUS = {
normal: "var(--foreground)",
ok: "var(--success, #1f9d55)",
warn: "var(--warning, #b87a00)",
alarm: "var(--destructive)",
} as const;
/** Cartesian and polar gridline stroke that stays legible over solid and frosted glass surfaces. */
export const GRID_STROKE = "color-mix(in srgb, var(--foreground) 16%, transparent)";
/** Solid page background colour, unaffected by translucent `[data-surface]` overrides, for halos and cell ramps. */
export const BASE_BG = "var(--thrum-base-background, var(--background))";
// ---------------------------------------------------------------------------------------------
// Hooks.
export type Size = { width: number; height: number };
/** Measures an element. Width and height are 0 until the first measurement in the browser. */
export function useSize<T extends Element>(): [RefObject<T | null>, Size] {
const ref = useRef<T>(null);
const [size, setSize] = useState<Size>({ width: 0, height: 0 });
useEffect(() => {
const el = ref.current;
if (!el) return;
const observer = new ResizeObserver(([entry]) => {
const width = Math.round(entry.contentRect.width);
const height = Math.round(entry.contentRect.height);
setSize((prev) => (prev.width === width && prev.height === height ? prev : { width, height }));
});
observer.observe(el);
return () => observer.disconnect();
}, []);
return [ref, size];
}
function watchRoot(notify: () => void): () => void {
const observer = new MutationObserver(notify);
observer.observe(document.documentElement, { attributes: true, attributeFilter: ["style", "class"] });
return () => observer.disconnect();
}
/**
* The rounding for a small mark that is drawn as a path (a bar end): the project's `--radius`, never more than `cap` pixels.
* It is 0 in a project with square corners. A mark that is an element uses the class `rounded-[min(var(--radius),2px)]` instead.
*/
export function useMarkRadius(cap = 2): number {
return useSyncExternalStore(
watchRoot,
() => {
const value = getComputedStyle(document.documentElement).getPropertyValue("--radius").trim();
const size = parseFloat(value) * (value.endsWith("rem") ? parseFloat(getComputedStyle(document.documentElement).fontSize) : 1);
return Number.isFinite(size) ? Math.min(cap, Math.max(0, size)) : cap; // no --radius, or a formula: keep the default
},
() => cap,
);
}
/**
* The reading cursor of a chart: which point is active, moved by pointer or keyboard.
* `cursorProps` makes one element the chart's single tab stop. It is exposed as a slider,
* so arrow keys, Home and End work and a screen reader speaks `valueText` as the cursor moves.
*/
export function useChartCursor(count: number, onChange?: (index: number | null) => void) {
const [active, setActive] = useState<number | null>(null);
const activeRef = useRef<number | null>(null);
// Always call the newest `onChange` without making `move` change identity on every render.
const onChangeRef = useRef(onChange);
useEffect(() => {
onChangeRef.current = onChange;
});
const move = useCallback(
(next: number | null) => {
const clamped = next === null || count === 0 ? null : Math.max(0, Math.min(count - 1, next));
if (clamped === activeRef.current) return;
activeRef.current = clamped;
setActive(clamped);
onChangeRef.current?.(clamped);
},
[count],
);
// Data can shrink under an active cursor.
useEffect(() => {
if (activeRef.current !== null && activeRef.current >= count) move(count ? count - 1 : null);
}, [count, move]);
const cursorProps = (label: string, valueText: string) => ({
tabIndex: 0,
role: "slider" as const,
// Tells a chart cursor from a slider control: both carry the slider role.
"data-chart-cursor": "",
"aria-label": label,
"aria-orientation": "horizontal" as const,
"aria-valuemin": 0,
"aria-valuemax": Math.max(0, count - 1),
"aria-valuenow": active ?? Math.max(0, count - 1),
"aria-valuetext": valueText,
onKeyDown: (event: KeyboardEvent) => {
const current = activeRef.current;
const target: Record<string, number> = {
ArrowRight: (current ?? -1) + 1,
ArrowUp: (current ?? -1) + 1,
ArrowLeft: (current ?? count) - 1,
ArrowDown: (current ?? count) - 1,
Home: 0,
End: count - 1,
};
if (event.key in target) {
event.preventDefault();
move(target[event.key]);
} else if (event.key === "Escape") move(null);
},
onFocus: () => {
if (activeRef.current === null) move(count - 1);
},
onBlur: () => move(null),
});
return { active, move, cursorProps };
}Files and dependencies
- Adds
lib/thrum-chart.ts- Packages
- None
- Brings along
- Nothing
Changelog
- 1.0.0 · 2026-12-02First release.