Area and line chart
A dependency-free SVG chart for one or more series, drawn as smooth areas or lines in the theme's chart colours. It resizes with its container, picks clean y-axis ticks, thins x labels to fit, and shows a crosshair with one tooltip for every series. Legend items toggle series, arrow keys step through points with screen-reader announcements, and a switch shows the same data as a table.
Source
"use client";
import * as React from "react";
import { ChartSpline, Table2 } from "lucide-react";
import { cn } from "@/lib/utils";
export interface ChartSeries {
/** Key of the numeric field in each data row. */
key: string;
label: string;
/** Any CSS colour. Defaults to var(--chart-1..5) in series order. */
color?: string;
}
export interface AreaChartProps<T extends Record<string, unknown>> {
data: T[];
/** Key of the field used for the x axis (a label such as "Jan"). */
index: keyof T & string;
series: ChartSeries[];
/** Accessible name; also the table caption. */
title: string;
variant?: "area" | "line";
/** Plot height in pixels. */
height?: number;
/** Formats values in the tooltip, table and announcements. */
valueFormatter?: (value: number) => string;
/** Formats y-axis ticks. Defaults to compact notation (12K). */
tickFormatter?: (value: number) => string;
/** Column header for the index in table view. */
indexLabel?: string;
showLegend?: boolean;
/** Shows a chart/table switch. */
showTableToggle?: boolean;
className?: string;
}
const PALETTE = ["var(--chart-1)", "var(--chart-2)", "var(--chart-3)", "var(--chart-4)", "var(--chart-5)"];
const compact = new Intl.NumberFormat("en", { notation: "compact", maximumFractionDigits: 1 });
const plain = new Intl.NumberFormat("en", { maximumFractionDigits: 2 });
const round = (n: number) => Math.round(n * 100) / 100;
function niceStep(span: number, count: number) {
const raw = span / count;
const magnitude = 10 ** Math.floor(Math.log10(raw));
const normal = raw / magnitude;
return (normal <= 1 ? 1 : normal <= 2 ? 2 : normal <= 2.5 ? 2.5 : normal <= 5 ? 5 : 10) * magnitude;
}
function niceTicks(min: number, max: number, count = 4) {
if (max === min) max = min + 1;
const step = niceStep(max - min, count);
const start = Math.floor(min / step) * step;
const end = Math.ceil(max / step) * step;
const ticks: number[] = [];
for (let value = start; value <= end + step / 2; value += step) ticks.push(round(value));
return ticks;
}
/* Monotone cubic interpolation: smooth, but never overshoots the data. */
function smoothPath(points: [number, number][]) {
const n = points.length;
if (n < 3) return points.map(([x, y], i) => `${i ? "L" : "M"}${round(x)},${round(y)}`).join("");
const slopes: number[] = [];
for (let i = 0; i < n - 1; i++) slopes.push((points[i + 1][1] - points[i][1]) / (points[i + 1][0] - points[i][0]));
const tangents = [slopes[0]];
for (let i = 1; i < n - 1; i++) tangents.push(slopes[i - 1] * slopes[i] <= 0 ? 0 : (slopes[i - 1] + slopes[i]) / 2);
tangents.push(slopes[n - 2]);
let d = `M${round(points[0][0])},${round(points[0][1])}`;
for (let i = 0; i < n - 1; i++) {
const [x0, y0] = points[i];
const [x1, y1] = points[i + 1];
const h = (x1 - x0) / 3;
d += `C${round(x0 + h)},${round(y0 + tangents[i] * h)},${round(x1 - h)},${round(y1 - tangents[i + 1] * h)},${round(x1)},${round(y1)}`;
}
return d;
}
/* Measures the plot. A callback ref keeps working when the plot remounts (after table view). */
function useWidth(fallback: number) {
const [width, setWidth] = React.useState(fallback);
const observer = React.useRef<ResizeObserver | null>(null);
const ref = React.useCallback((node: HTMLDivElement | null) => {
observer.current?.disconnect();
if (!node) return;
setWidth(node.clientWidth);
observer.current = new ResizeObserver(([entry]) => setWidth(entry.contentRect.width));
observer.current.observe(node);
}, []);
return [ref, width] as const;
}
export function AreaChart<T extends Record<string, unknown>>({
data,
index,
series,
title,
variant = "area",
height = 280,
valueFormatter = (value) => plain.format(value),
tickFormatter = (value) => compact.format(value),
indexLabel = "Period",
showLegend = true,
showTableToggle = true,
className,
}: AreaChartProps<T>) {
const uid = React.useId().replace(/[^a-zA-Z0-9_-]/g, "");
const [plotRef, width] = useWidth(640);
const [hidden, setHidden] = React.useState<string[]>([]);
const [active, setActive] = React.useState<number | null>(null);
const [view, setView] = React.useState<"chart" | "table">("chart");
const [announcement, setAnnouncement] = React.useState("");
const colored = series.map((item, i) => ({ ...item, color: item.color || PALETTE[i % PALETTE.length], gradient: `${uid}-g${i}` }));
const visible = colored.filter((item) => !hidden.includes(item.key));
const valueOf = (row: T, key: string) => Number(row[key]) || 0;
// Scales. Areas start at zero; lines may start wherever the data does.
const values = data.flatMap((row) => visible.map((item) => valueOf(row, item.key)));
const dataMax = values.length ? Math.max(...values) : 1;
const dataMin = values.length ? Math.min(...values) : 0;
const ticks = niceTicks(variant === "area" ? Math.min(0, dataMin) : dataMin, dataMax, height < 220 ? 3 : 4);
const yMin = ticks[0];
const yMax = ticks[ticks.length - 1];
const longestTick = Math.max(...ticks.map((tick) => tickFormatter(tick).length));
const margin = { top: 10, right: 10, bottom: 28, left: Math.max(28, longestTick * 7 + 14) };
const innerWidth = Math.max(1, width - margin.left - margin.right);
const innerHeight = Math.max(1, height - margin.top - margin.bottom);
const x = (i: number) => margin.left + (data.length < 2 ? innerWidth / 2 : (i / (data.length - 1)) * innerWidth);
const y = (value: number) => margin.top + (1 - (value - yMin) / (yMax - yMin || 1)) * innerHeight;
const labelEvery = Math.max(1, Math.ceil(data.length / Math.max(2, Math.floor(innerWidth / 64))));
const describe = (i: number) =>
`${String(data[i][index])}: ${visible.map((item) => `${item.label} ${valueFormatter(valueOf(data[i], item.key))}`).join(", ")}`;
function pick(clientX: number, target: Element) {
const rect = target.getBoundingClientRect();
const ratio = (clientX - rect.left - margin.left) / innerWidth;
setActive(Math.min(data.length - 1, Math.max(0, Math.round(ratio * (data.length - 1)))));
}
function onKeyDown(event: React.KeyboardEvent) {
const last = data.length - 1;
const current = active ?? last;
const next =
event.key === "ArrowRight" ? Math.min(last, current + 1)
: event.key === "ArrowLeft" ? Math.max(0, current - 1)
: event.key === "Home" ? 0
: event.key === "End" ? last
: null;
if (next === null) return;
event.preventDefault();
setActive(next);
setAnnouncement(describe(next));
}
function toggleSeries(key: string) {
setHidden((current) =>
current.includes(key) ? current.filter((item) => item !== key) : current.length < series.length - 1 ? [...current, key] : current,
);
}
const tooltipLeft = active !== null && x(active) > width * 0.62;
return (
<div className={cn("w-full min-w-0", className)}>
{(showLegend && series.length > 1) || showTableToggle ? (
<div className="mb-3 flex flex-wrap items-center justify-between gap-x-4 gap-y-2">
{showLegend && series.length > 1 ? (
<ul className="flex flex-wrap items-center gap-x-1 gap-y-1" aria-label="Series">
{colored.map((item) => {
const on = !hidden.includes(item.key);
return (
<li key={item.key}>
<button
type="button"
aria-pressed={on}
onClick={() => toggleSeries(item.key)}
className={cn(
"inline-flex items-center gap-2 rounded-md px-2 py-1 text-xs font-medium outline-none transition-colors hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring",
on ? "text-foreground" : "text-muted-foreground/70 line-through",
)}
>
<span
aria-hidden
className={variant === "line" ? "h-0.5 w-3.5 rounded-full" : "size-2.5 rounded-[3px]"}
style={{ background: on ? item.color : "transparent", boxShadow: on ? undefined : `inset 0 0 0 1.5px ${item.color}` }}
/>
{item.label}
</button>
</li>
);
})}
</ul>
) : (
<span />
)}
{showTableToggle && (
<button
type="button"
onClick={() => setView(view === "chart" ? "table" : "chart")}
className="inline-flex items-center gap-1.5 rounded-md border px-2 py-1 text-xs font-medium text-muted-foreground outline-none transition-colors hover:bg-accent hover:text-accent-foreground focus-visible:ring-2 focus-visible:ring-ring"
>
{view === "chart" ? <Table2 aria-hidden className="size-3.5" /> : <ChartSpline aria-hidden className="size-3.5" />}
{view === "chart" ? "Table" : "Chart"}
</button>
)}
</div>
) : null}
{view === "table" ? (
<div className="overflow-auto rounded-lg border" style={{ maxHeight: height }}>
<table className="w-full text-sm">
<caption className="sr-only">{title}</caption>
<thead className="sticky top-0 bg-muted text-xs text-muted-foreground">
<tr>
<th scope="col" className="px-3 py-2 text-left font-medium">{indexLabel}</th>
{visible.map((item) => (
<th key={item.key} scope="col" className="px-3 py-2 text-right font-medium">{item.label}</th>
))}
</tr>
</thead>
<tbody className="divide-y">
{data.map((row, i) => (
<tr key={i} className="hover:bg-muted/50">
<th scope="row" className="px-3 py-2 text-left font-medium">{String(row[index])}</th>
{visible.map((item) => (
<td key={item.key} className="px-3 py-2 text-right tabular-nums">{valueFormatter(valueOf(row, item.key))}</td>
))}
</tr>
))}
</tbody>
</table>
</div>
) : (
<div
ref={plotRef}
role="group"
aria-roledescription="chart"
aria-label={`${title}. Use the left and right arrow keys to read values.`}
tabIndex={0}
onKeyDown={onKeyDown}
onFocus={() => active === null && data.length && setActive(data.length - 1)}
onBlur={() => setActive(null)}
onPointerMove={(event) => pick(event.clientX, event.currentTarget)}
onPointerDown={(event) => pick(event.clientX, event.currentTarget)}
onPointerLeave={(event) => event.currentTarget !== document.activeElement && setActive(null)}
className="relative touch-pan-y rounded-lg outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-4 focus-visible:ring-offset-card"
style={{ height }}
>
{data.length === 0 ? (
<p className="grid h-full place-items-center text-sm text-muted-foreground">No data</p>
) : (
<svg width={width} height={height} className="absolute inset-0 overflow-visible" aria-hidden>
<defs>
{visible.map((item) => (
<linearGradient key={item.key} id={item.gradient} x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" style={{ stopColor: item.color, stopOpacity: 0.22 }} />
<stop offset="100%" style={{ stopColor: item.color, stopOpacity: 0.01 }} />
</linearGradient>
))}
</defs>
{ticks.map((tick) => (
<g key={tick}>
<line x1={margin.left} x2={width - margin.right} y1={y(tick)} y2={y(tick)} style={{ stroke: "var(--border)" }} strokeWidth={1} shapeRendering="crispEdges" />
<text x={margin.left - 10} y={y(tick)} dy="0.32em" textAnchor="end" fontSize={11} style={{ fill: "var(--muted-foreground)", fontVariantNumeric: "tabular-nums" }}>
{tickFormatter(tick)}
</text>
</g>
))}
{data.map((row, i) =>
i % labelEvery === 0 || i === data.length - 1 ? (
i !== data.length - 1 && data.length - 1 - i < labelEvery * 0.6 ? null : (
<text
key={i}
x={x(i)}
y={height - 8}
fontSize={11}
textAnchor={i === 0 ? "start" : i === data.length - 1 ? "end" : "middle"}
style={{ fill: "var(--muted-foreground)" }}
>
{String(row[index])}
</text>
)
) : null,
)}
{visible.map((item) => {
const points = data.map((row, i) => [x(i), y(valueOf(row, item.key))] as [number, number]);
const line = smoothPath(points);
return (
<g key={item.key}>
{variant === "area" && (
<path d={`${line}L${round(x(data.length - 1))},${round(y(yMin))}L${round(x(0))},${round(y(yMin))}Z`} fill={`url(#${item.gradient})`} />
)}
<path d={line} fill="none" style={{ stroke: item.color }} strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" />
</g>
);
})}
{active !== null && (
<g>
<line x1={x(active)} x2={x(active)} y1={margin.top} y2={margin.top + innerHeight} style={{ stroke: "var(--muted-foreground)" }} strokeOpacity={0.45} strokeWidth={1} shapeRendering="crispEdges" />
{visible.map((item) => (
<circle key={item.key} cx={x(active)} cy={y(valueOf(data[active], item.key))} r={4.5} style={{ fill: item.color, stroke: "var(--card)" }} strokeWidth={2} />
))}
</g>
)}
</svg>
)}
{active !== null && data[active] && (
<div
aria-hidden
className="pointer-events-none absolute top-1 z-10 min-w-40 rounded-lg border bg-popover px-3 py-2.5 text-popover-foreground shadow-lg"
style={tooltipLeft ? { right: width - x(active) + 12 } : { left: x(active) + 12 }}
>
<p className="mb-1.5 text-xs font-medium text-muted-foreground">{String(data[active][index])}</p>
<ul className="space-y-1">
{visible.map((item) => (
<li key={item.key} className="flex items-center gap-2 text-xs">
<span className="h-0.5 w-3 shrink-0 rounded-full" style={{ background: item.color }} />
<span className="text-muted-foreground">{item.label}</span>
<span className="ml-auto pl-3 font-semibold tabular-nums">{valueFormatter(valueOf(data[active], item.key))}</span>
</li>
))}
</ul>
</div>
)}
</div>
)}
<p aria-live="polite" className="sr-only">
{announcement}
</p>
</div>
);
}
