components/tanstack-charts/line/echarts-axis-pointer.tsx
import { type ChartPoint, defineChart, dot, lineY } from "@tanstack/charts";
import { focusGuideX } from "@tanstack/charts/focus/guide";
import { motion } from "@tanstack/charts/motion";
import { tooltip } from "@tanstack/charts/tooltip";
import { Chart } from "@tanstack/react-charts/core";
import { useMemo } from "react";
import { scaleLinear, scaleUtc } from "d3-scale";
import { Crosshair } from "lucide-react";
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
interface IndustryDatum {
industry: string;
date: Date;
unemployed: number;
}
const motionRenderer = motion({
initial: "always",
transition: { type: "spring", stiffness: 170, damping: 18, mass: 1 },
});
const industriesList = ["Trade", "Manufacturing", "Tech"];
function generateDemoData(): IndustryDatum[] {
const results: IndustryDatum[] = [];
const months = 12;
for (let m = 0; m < months; m++) {
const date = new Date(Date.UTC(2024, m, 1));
industriesList.forEach((ind, idx) => {
const base = 120 + idx * 40 + Math.sin(m * 0.5) * 35;
results.push({
industry: ind,
date,
unemployed: Math.round(base + (Math.random() - 0.5) * 15),
});
});
}
return results;
}
function shadcnTooltipContent<TDatum>(points: readonly ChartPoint<TDatum>[]) {
if (points.length === 0) return { title: "", rows: [] };
const date = (points[0].datum as IndustryDatum)?.date;
const dateObj = date ? (date instanceof Date ? date : new Date(date)) : null;
const titleText =
dateObj && !isNaN(dateObj.getTime())
? dateObj.toLocaleDateString("en-US", { month: "short", year: "numeric", timeZone: "UTC" })
: "";
const rows = points.map((p, idx) => {
const d = p.datum as IndustryDatum;
return {
label: d.industry,
value: `${d.unemployed}k`,
color: `var(--chart-${idx + 1})`,
};
});
return { title: titleText, rows };
}
export function EchartsAxisPointer() {
const data = useMemo(() => generateDemoData(), []);
const definition = useMemo(
() =>
defineChart(
{
renderer: motionRenderer,
marks: [
lineY(data, {
id: "industry-lines",
x: "date",
y: "unemployed",
z: "industry",
color: "industry",
key: (row: IndustryDatum) =>
`${row.industry}:${row?.date ? (row.date instanceof Date ? row.date.getTime() : new Date(row.date).getTime()) : 0}`,
strokeWidth: 2,
}),
dot(data, {
id: "industry-points",
x: "date",
y: "unemployed",
z: "industry",
color: "industry",
key: (row: IndustryDatum) =>
`${row.industry}:${row?.date ? (row.date instanceof Date ? row.date.getTime() : new Date(row.date).getTime()) : 0}`,
r: 3.5,
stroke: "var(--background)",
strokeWidth: 1,
}),
focusGuideX(data, {
id: "axis-pointer-guide",
x: "date",
y: "unemployed",
z: "industry",
key: (row: IndustryDatum) =>
`${row.industry}:${row?.date ? (row.date instanceof Date ? row.date.getTime() : new Date(row.date).getTime()) : 0}`,
xRule: {
stroke: "var(--muted-foreground)",
strokeWidth: 1,
strokeDasharray: "4 4",
},
}),
],
scales: {
x: {
scale: scaleUtc,
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: "Unemployed (Thousands)" },
},
},
color: {
domain: industriesList,
range: ["var(--chart-1)", "var(--chart-2)", "var(--chart-3)"],
},
focus: "group-x",
focusRing: false,
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>Snapped Axis Pointer Grouped Crosshair</CardTitle>
<CardDescription>
ECharts-style vertical snapping axis pointer grouping multi-series metrics at X timeline steps
</CardDescription>
</CardHeader>
<CardContent>
<div className="h-[250px] w-full">
<Chart
definition={definition}
renderer={motionRenderer}
height={250}
ariaLabel="Snapped Axis Pointer Grouped Crosshair 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 line snaps to exact X positions comparing all 3 industries{" "}
<Crosshair className="h-4 w-4 text-emerald-500" />
</div>
<div className="text-muted-foreground leading-none">
`focus: group-x` automatically locks pointer cursor to nearest temporal timestamp step
</div>
</CardFooter>
</Card>
);
}
export default EchartsAxisPointer;