components/tanstack-charts/line/focus-context-window.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 { Maximize2 } 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 = 120;
for (let m = 0; m < 36; m++) {
const date = new Date(Date.UTC(2022, m, 1));
price += Math.sin(m * 0.3) * 5 + (Math.random() - 0.45) * 8;
results.push({ Date: date, Close: Number(Math.max(80, 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", year: "numeric", timeZone: "UTC" });
return {
title: titleStr,
rows: [{ label: "Closing Price", value: `$${d.Close.toFixed(2)}`, color: "var(--chart-1)" }],
};
}
export function FocusContextWindow() {
const data = useMemo(() => generateDemoData(), []);
const fullDates = useMemo(() => data.map((d) => d.Date), [data]);
const fullDomain = useMemo(() => [fullDates[0], fullDates[fullDates.length - 1]], [fullDates]);
const [range, setRange] = useState<{ start: Date; end: Date }>({
start: fullDates[12],
end: fullDates[24],
});
const filteredDetailData = 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();
return data.filter((d) => {
const t = d.Date instanceof Date ? d.Date.getTime() : new Date(d.Date).getTime();
return t >= startTime && t <= endTime;
});
}, [data, range]);
const detailDefinition = useMemo(
() =>
defineChart(
{
renderer: motionRenderer,
marks: [
lineY(filteredDetailData, {
id: "detail-line",
x: "Date",
y: "Close",
stroke: "var(--chart-1)",
strokeWidth: 2.5,
}),
dot(filteredDetailData, {
id: "detail-points",
x: "Date",
y: "Close",
fill: "var(--chart-1)",
r: 3.5,
}),
],
scales: {
x: {
scale: scaleUtc().domain([
range.start instanceof Date ? range.start : new Date(range.start),
range.end instanceof Date ? range.end : new Date(range.end),
]),
axis: { label: "Focus Zoomed Window" },
},
y: {
scale: scaleLinear,
grid: true,
axis: { label: "Stock Close ($)" },
},
},
margin: { top: 16, 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),
},
},
),
[filteredDetailData, range],
);
const overviewDefinition = useMemo(
() =>
defineChart(
{
renderer: motionRenderer,
marks: [
lineY(data, {
id: "overview-line",
x: "Date",
y: "Close",
stroke: "var(--chart-1)",
strokeWidth: 1.5,
}),
],
scales: {
x: {
scale: scaleUtc().domain(fullDomain),
axis: {
ticks: {
count: 4,
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, axis: false },
},
controls: [
brushX({
id: "focus-window",
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: fullDates,
ariaLabel: "Time window brush selector",
selectionStyle: {
fill: "var(--chart-1)",
fillOpacity: 0.2,
stroke: "var(--chart-1)",
strokeWidth: 1.5,
},
handleStyle: { fill: "var(--chart-1)", fillOpacity: 0.9 },
}),
],
margin: { top: 8, right: 24, bottom: 20, left: 45 },
theme: {
foreground: "var(--muted-foreground)",
grid: "var(--border)",
background: "transparent",
},
},
{ keyboard: false },
),
[data, fullDates, fullDomain, range],
);
return (
<Card className="w-full max-w-xl">
<CardHeader>
<CardTitle>Dual Focus + Context Brush Zoom Window</CardTitle>
<CardDescription>
Drag and resize the overview brush region to pan and zoom detailed line series view
</CardDescription>
</CardHeader>
<CardContent className="space-y-3">
<div className="h-[180px] w-full">
<Chart
definition={detailDefinition}
renderer={motionRenderer}
height={180}
ariaLabel="Detail Focus Window View"
/>
</div>
<div className="h-[75px] w-full">
<Chart
definition={overviewDefinition}
renderer={motionRenderer}
height={75}
ariaLabel="Overview Context Window View"
/>
</div>
</CardContent>
<CardFooter className="flex-col items-start gap-2 text-sm">
<div className="flex items-center gap-2 leading-none font-medium">
Overview brush coordinates update detail zoom domain live{" "}
<Maximize2 className="h-4 w-4 text-emerald-500" />
</div>
<div className="text-muted-foreground leading-none">
`brushX` mark provides interactive handle dragging for smooth temporal pan/zoom
</div>
</CardFooter>
</Card>
);
}
export default FocusContextWindow;