
GitHub-style 52-week activity contribution grid for API token volume built with TanStack Charts.
components/tanstack-charts/heatmap/token-usage-calendar.tsx
import { type ChartPoint, cell, defineChart } 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, scaleOrdinal } from "d3-scale";
import { CalendarDays } from "lucide-react";
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
interface CalendarCellDatum {
week: number;
weekday: string;
level: string;
dateKey: string;
tokens: number;
}
const motionRenderer = motion({
initial: "always",
transition: { type: "spring", stiffness: 170, damping: 18, mass: 1 },
});
const weekdays = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
const usageLevels = ["none", "low", "medium", "high", "max"];
const usageColors = ["var(--border)", "var(--chart-1)", "var(--chart-2)", "var(--chart-3)", "var(--chart-4)"];
const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
function generateDemoData(): CalendarCellDatum[] {
const results: CalendarCellDatum[] = [];
const baseDate = new Date(Date.UTC(2024, 0, 1));
for (let w = 0; w < 52; w++) {
for (let d = 0; d < 7; d++) {
const date = new Date(baseDate.getTime() + (w * 7 + d) * 24 * 60 * 60 * 1000);
const tokens = Math.floor(Math.random() * 120);
let level = "none";
if (tokens > 90) level = "max";
else if (tokens > 60) level = "high";
else if (tokens > 30) level = "medium";
else if (tokens > 5) level = "low";
results.push({
week: w,
weekday: weekdays[d],
level,
dateKey: date.toISOString().split("T")[0],
tokens,
});
}
}
return results;
}
function shadcnTooltipContent<TDatum>(points: readonly ChartPoint<TDatum>[]) {
if (points.length === 0) return { title: "", rows: [] };
const d = points[0].datum as CalendarCellDatum;
if (!d) return { title: "", rows: [] };
return {
title: `${d.dateKey} (${d.weekday})`,
rows: [{ label: "Token Usage", value: `${d.tokens}k tokens`, color: "var(--chart-1)" }],
};
}
export function TokenUsageCalendar() {
const data = useMemo(() => generateDemoData(), []);
const weekDomain = useMemo(() => Array.from({ length: 52 }, (_, i) => i), []);
const definition = useMemo(
() =>
defineChart(
{
renderer: motionRenderer,
marks: [
cell(data, {
id: "calendar-cells",
x: "week",
y: "weekday",
color: "level",
key: "dateKey",
radius: 2,
}),
],
scales: {
x: {
scale: scaleBand<number>().domain(weekDomain).paddingInner(0.2),
axis: {
line: false,
ticks: {
values: [0, 4, 8, 13, 17, 21, 26, 30, 34, 39, 43, 47],
format: (v: number) => months[Math.floor(v / 4.33)] || "",
},
},
},
y: {
scale: scaleBand<string>().domain(weekdays).paddingInner(0.2),
axis: {
line: false,
ticks: {
values: ["Mon", "Wed", "Fri"],
},
},
},
},
color: {
scale: scaleOrdinal<string, string>().domain(usageLevels).range(usageColors),
},
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, weekDomain],
);
return (
<Card className="w-full max-w-xl">
<CardHeader>
<CardTitle>52-Week Token Activity Calendar Heatmap Grid</CardTitle>
<CardDescription>
GitHub/GitLab contribution style matrix tracking daily API token volume
</CardDescription>
</CardHeader>
<CardContent>
<div className="h-[210px] w-full">
<Chart
definition={definition}
renderer={motionRenderer}
height={210}
ariaLabel="52-Week Token Activity Calendar Heatmap Grid Chart"
/>
</div>
</CardContent>
<CardFooter className="flex-col items-start gap-2 text-sm">
<div className="flex items-center gap-2 leading-none font-medium">
Daily token activity intensity mapped across 52 calendar weeks{" "}
<CalendarDays className="h-4 w-4 text-emerald-500" />
</div>
<div className="text-muted-foreground leading-none">
`cell` mark renders discrete categorical grid tiles scaled by ordinal levels
</div>
</CardFooter>
</Card>
);
}
export default TokenUsageCalendar;