
Drag handles horizontally to select date domain window bounds.
components/tanstack-charts/line/brush-range-selection.tsx
import { type ChartPoint, defineChart, dot, lineY } from "@tanstack/charts";
import { brushX } from "@tanstack/charts/interaction/brush";
import { controlledSignal } from "@tanstack/charts/interaction/signal";
import { motion } from "@tanstack/charts/motion";
import { tooltip } from "@tanstack/charts/tooltip";
import { Chart } from "@tanstack/react-charts/core";
import { useMemo, useState } from "react";
import { scaleLinear, scaleUtc } from "d3-scale";
import { Sliders } from "lucide-react";
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
interface StockDatum {
date: Date;
close: number;
}
const motionRenderer = motion({
initial: "always",
transition: { type: "spring", stiffness: 170, damping: 18, mass: 1 },
});
function generateDemoData(): StockDatum[] {
const results: StockDatum[] = [];
let price = 150;
const baseDate = new Date(Date.UTC(2024, 0, 1)).getTime();
for (let i = 0; i < 24; i++) {
price += Math.sin(i * 0.4) * 6 + (Math.random() - 0.45) * 8;
results.push({
date: new Date(baseDate + i * 15 * 24 * 60 * 60 * 1000),
close: Number(Math.max(100, price).toFixed(2)),
});
}
return results;
}
function shadcnTooltipContent<TDatum>(points: readonly ChartPoint<TDatum>[]) {
if (points.length === 0) return { title: "", rows: [] };
const d = points[0].datum as StockDatum;
if (!d || !d.date) return { title: "", rows: [] };
const dateObj = d.date instanceof Date ? d.date : new Date(d.date);
const titleStr = isNaN(dateObj.getTime())
? ""
: dateObj.toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric", timeZone: "UTC" });
return {
title: titleStr,
rows: [{ label: "Close Price", value: `$${d.close.toFixed(2)}`, color: "var(--chart-1)" }],
};
}
export function BrushRangeSelection() {
const data = useMemo(() => generateDemoData(), []);
const dates = useMemo(() => data.map((d) => d.date), [data]);
const fullDomain = useMemo(() => [dates[0], dates[dates.length - 1]], [dates]);
const [range, setRange] = useState<{ start: Date; end: Date }>({
start: dates[4],
end: dates[16],
});
const rangeStats = useMemo(() => {
const startTime = range.start instanceof Date ? range.start.getTime() : new Date(range.start).getTime();
const endTime = range.end instanceof Date ? range.end.getTime() : new Date(range.end).getTime();
const sliced = data.filter((d) => {
const t = d.date instanceof Date ? d.date.getTime() : new Date(d.date).getTime();
return t >= startTime && t <= endTime;
});
if (sliced.length === 0) return { count: 0, avg: 0 };
const sum = sliced.reduce((acc, curr) => acc + curr.close, 0);
return { count: sliced.length, avg: sum / sliced.length };
}, [data, range]);
const definition = useMemo(
() =>
defineChart(
{
renderer: motionRenderer,
marks: [
lineY(data, {
id: "brush-series-line",
x: "date",
y: "close",
stroke: "var(--chart-1)",
strokeWidth: 2.5,
}),
dot(data, {
id: "brush-series-points",
x: "date",
y: "close",
fill: "var(--chart-1)",
r: 3.5,
stroke: "var(--background)",
strokeWidth: 1,
}),
],
scales: {
x: {
scale: scaleUtc().domain(fullDomain),
axis: {
ticks: {
format: (v: any) => {
const dateObj = v instanceof Date ? v : new Date(v);
return isNaN(dateObj.getTime())
? ""
: dateObj.toLocaleDateString("en-US", { month: "short", timeZone: "UTC" });
},
},
},
},
y: {
scale: scaleLinear,
grid: true,
axis: { label: "Price ($)" },
},
},
controls: [
brushX({
id: "monthly-range",
range: controlledSignal(range, (next: any) => {
if (!next) return;
setRange({
start: next.start instanceof Date ? next.start : new Date(next.start),
end: next.end instanceof Date ? next.end : new Date(next.end),
});
}),
values: dates,
ariaLabel: "Time range brush handles",
selectionStyle: {
fill: "var(--chart-1)",
fillOpacity: 0.18,
stroke: "var(--chart-1)",
strokeWidth: 1.5,
},
handleStyle: {
fill: "var(--background)",
stroke: "var(--chart-1)",
strokeWidth: 2,
},
}),
],
margin: { top: 24, right: 24, bottom: 32, left: 45 },
theme: {
foreground: "var(--muted-foreground)",
grid: "var(--border)",
background: "transparent",
},
},
{
keyboard: true,
tooltip: {
use: tooltip,
className:
"font-sans shadow-none rounded-md bg-popover text-popover-foreground border p-2 text-xs",
anchor: "pointer",
placement: "auto",
content: (points) => shadcnTooltipContent(points),
},
},
),
[data, dates, fullDomain, range],
);
const fmtDate = (d: any) => {
const dateObj = d instanceof Date ? d : new Date(d);
return isNaN(dateObj.getTime())
? ""
: dateObj.toLocaleDateString("en-US", { month: "short", day: "numeric", timeZone: "UTC" });
};
return (
<Card className="w-full max-w-xl">
<CardHeader>
<CardTitle>Dual-Handle Interactive Brush Range Selection</CardTitle>
<CardDescription>
Drag handles horizontally to select date sub-ranges and compute window aggregations
</CardDescription>
</CardHeader>
<CardContent>
<div className="h-[250px] w-full">
<Chart
definition={definition}
renderer={motionRenderer}
height={250}
ariaLabel="Dual-Handle Interactive Brush Range Selection Chart"
/>
</div>
</CardContent>
<CardFooter className="flex-col items-start gap-2 text-sm">
<div className="flex items-center gap-2 leading-none font-medium">
Selection: {fmtDate(range.start)} → {fmtDate(range.end)} ({rangeStats.count} points, Avg: $
{rangeStats.avg.toFixed(2)}) <Sliders className="h-4 w-4 text-emerald-500" />
</div>
<div className="text-muted-foreground leading-none">
`brushX` mark provides dual handles for active range selection and summary statistics
</div>
</CardFooter>
</Card>
);
}
export default BrushRangeSelection;