
Hover crosshairs highlight full column band with breakdown tooltip.
components/tanstack-charts/bar/stacked-bar-band-cursor.tsx
import { type ChartPoint, barY, colorLegend, crosshair, defineChart, stack } from "@tanstack/charts";
import { motion } from "@tanstack/charts/motion";
import { tooltip } from "@tanstack/charts/tooltip";
import { Chart } from "@tanstack/react-charts/core";
import { useMemo } from "react";
import { scaleBand, scaleLinear } from "d3-scale";
import { Layers } from "lucide-react";
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
interface StackedCauseDatum {
id: string;
period: string;
cause: string;
deaths: number;
}
const motionRenderer = motion({
initial: "always",
transition: { type: "spring", stiffness: 170, damping: 18, mass: 1 },
});
const periods = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug"];
const causes = ["Zymotic", "Wounds", "Other"];
const colors = ["var(--chart-1)", "var(--chart-2)", "var(--chart-3)"];
function generateDemoData(): StackedCauseDatum[] {
const results: StackedCauseDatum[] = [];
periods.forEach((p) => {
causes.forEach((c) => {
const val = Math.floor(20 + Math.random() * 80);
results.push({
id: `${p}-${c}`,
period: p,
cause: c,
deaths: val,
});
});
});
return results;
}
function shadcnTooltipContent<TDatum>(points: readonly ChartPoint<TDatum>[]) {
if (points.length === 0) return { title: "", rows: [] };
const d = points[0].datum as StackedCauseDatum;
if (!d) return { title: "", rows: [] };
return {
title: `${d.period} - ${d.cause}`,
rows: [{ label: "Count", value: `${d.deaths} cases`, color: "var(--chart-1)" }],
};
}
export function StackedBarBandCursor() {
const data = useMemo(() => generateDemoData(), []);
const definition = useMemo(
() =>
defineChart(
{
renderer: motionRenderer,
marks: [
crosshair<string, number>({
id: "stacked-cursor-band",
x: {
band: {
fill: "var(--muted-foreground)",
fillOpacity: 0.15,
radius: 3,
},
},
y: false,
}),
barY(data, {
id: "stacked-cursor-bars",
x: "period",
y: "deaths",
z: "cause",
color: "cause",
key: "id",
layout: stack({ order: causes }),
radius: 2,
}),
crosshair<string, number>({
id: "stacked-cursor-rule",
x: false,
y: {
stroke: "var(--foreground)",
strokeOpacity: 0.7,
strokeWidth: 1,
strokeDasharray: "4 4",
},
}),
],
scales: {
x: {
scale: scaleBand<string>().domain(periods).padding(0.2),
},
y: {
scale: scaleLinear().domain([0, 300]),
grid: true,
axis: { label: "Total Cases" },
},
},
color: {
domain: causes,
range: colors,
legend: colorLegend({ label: "Cause Category" }),
},
focus: "group-x",
maxFocusDistance: Number.POSITIVE_INFINITY,
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],
);
return (
<Card className="w-full max-w-xl">
<CardHeader>
<CardTitle>Stacked Bar Chart with Dynamic Focus X-Band Cursor</CardTitle>
<CardDescription>
Hover crosshairs highlight full column bands and project horizontal segment rules
</CardDescription>
</CardHeader>
<CardContent>
<div className="h-[250px] w-full">
<Chart
definition={definition}
renderer={motionRenderer}
height={250}
ariaLabel="Stacked Bar Chart with Dynamic Focus X-Band Cursor Chart"
/>
</div>
</CardContent>
<CardFooter className="flex-col items-start gap-2 text-sm">
<div className="flex items-center gap-2 leading-none font-medium">
Crosshair band highlights active period column <Layers className="h-4 w-4 text-emerald-500" />
</div>
<div className="text-muted-foreground leading-none">
`crosshair` with `band` fill parameter tracks discrete band scale columns
</div>
</CardFooter>
</Card>
);
}
export default StackedBarBandCursor;