components/tanstack-charts/line/bump-ranking.tsx
import { type ChartPoint, d3Curve, defineChart, dot, lineY, rank, select, text } 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 { scaleLinear, scaleUtc } from "d3-scale";
import { curveBumpX } from "d3-shape";
import { Trophy } from "lucide-react";
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
interface BumpDatum {
industry: string;
date: Date;
unemployed: number;
rank?: number;
}
const motionRenderer = motion({
initial: "always",
transition: { type: "spring", stiffness: 170, damping: 18, mass: 1 },
});
const industriesList = ["Trade", "Manufacturing", "Services", "Tech", "Construction"];
function generateDemoData(): BumpDatum[] {
const results: BumpDatum[] = [];
const years = [2020, 2021, 2022, 2023, 2024, 2025];
years.forEach((year) => {
industriesList.forEach((ind, idx) => {
const unemployed = 100 + Math.floor(Math.sin(year * 0.4 + idx) * 80 + Math.random() * 40);
results.push({
industry: ind,
date: new Date(Date.UTC(year, 0, 1)),
unemployed,
});
});
});
return results;
}
function shadcnTooltipContent<TDatum>(points: readonly ChartPoint<TDatum>[]) {
if (points.length === 0) return { title: "", rows: [] };
const d = points[0].datum as BumpDatum;
if (!d || !d.date) return { title: "", rows: [] };
const dateObj = d.date instanceof Date ? d.date : new Date(d.date);
const yearStr = isNaN(dateObj.getTime()) ? "" : ` (${dateObj.getUTCFullYear()})`;
return {
title: `${d.industry}${yearStr}`,
rows: [
{ label: "Rank", value: `#${d.rank}`, color: "var(--chart-1)" },
{ label: "Unemployed Count", value: `${d.unemployed}k`, color: "var(--foreground)" },
],
};
}
export function BumpRanking() {
const rawData = useMemo(() => generateDemoData(), []);
const rows = useMemo(() => {
return rank(rawData, {
by: "date",
value: "unemployed",
order: "descending",
});
}, [rawData]);
const labels = useMemo(() => {
return select(rows, {
by: "industry",
value: (datum: BumpDatum) =>
datum?.date ? (datum.date instanceof Date ? datum.date.getTime() : new Date(datum.date).getTime()) : 0,
select: "max",
});
}, [rows]);
const definition = useMemo(
() =>
defineChart(
{
renderer: motionRenderer,
marks: [
lineY(rows, {
id: "industry-ranks",
x: "date",
y: "rank",
color: "industry",
curve: d3Curve(curveBumpX),
strokeWidth: 2.5,
}),
dot(rows, {
id: "industry-rank-points",
x: "date",
y: "rank",
color: "industry",
r: 4,
}),
text(labels, {
id: "industry-labels",
x: "date",
y: "rank",
text: "industry",
color: "industry",
anchor: "start",
dx: 8,
fontSize: 10,
fontWeight: 600,
}),
],
scales: {
x: {
scale: scaleUtc,
axis: {
ticks: {
count: 6,
format: (d: any) => {
const date = d instanceof Date ? d : new Date(d);
return isNaN(date.getTime()) ? "" : `${date.getUTCFullYear()}`;
},
},
label: "Year",
},
},
y: {
scale: scaleLinear().domain([5.5, 0.5]),
grid: true,
axis: {
ticks: { count: 5, format: (v: number) => `#${v}` },
label: "Ranking Position",
},
},
},
color: {
domain: industriesList,
range: [
"var(--chart-1)",
"var(--chart-2)",
"var(--chart-3)",
"var(--chart-4)",
"var(--chart-5)",
],
},
margin: { top: 24, right: 80, 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),
},
},
),
[rows, labels],
);
return (
<Card className="w-full max-w-xl">
<CardHeader>
<CardTitle>Industry Unemployment Bump Chart</CardTitle>
<CardDescription>
Curve-bump ranking lines tracking position shifts across annual observations
</CardDescription>
</CardHeader>
<CardContent>
<div className="h-[250px] w-full">
<Chart
definition={definition}
renderer={motionRenderer}
height={250}
ariaLabel="Industry Unemployment Bump Chart"
/>
</div>
</CardContent>
<CardFooter className="flex-col items-start gap-2 text-sm">
<div className="flex items-center gap-2 leading-none font-medium">
Trade maintains top rank across recent observation years{" "}
<Trophy className="h-4 w-4 text-emerald-500" />
</div>
<div className="text-muted-foreground leading-none">
Smooth bump curves illustrate ordinal rank swaps over time
</div>
</CardFooter>
</Card>
);
}
export default BumpRanking;