components/tanstack-charts/bar/waffle-unit-chart.tsx
import { type ChartPoint, defineChart, waffleY } 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 { Grid3X3 } from "lucide-react";
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
interface WaffleDatum {
category: string;
value: number;
}
const motionRenderer = motion({
initial: "always",
transition: { type: "spring", stiffness: 170, damping: 18, mass: 1 },
});
function generateDemoData(): WaffleDatum[] {
return [
{ category: "React", value: 35 },
{ category: "Vue", value: 25 },
{ category: "Svelte", value: 20 },
{ category: "Angular", value: 12 },
{ category: "Solid", value: 8 },
];
}
function shadcnTooltipContent<TDatum>(points: readonly ChartPoint<TDatum>[]) {
if (points.length === 0) return { title: "", rows: [] };
const d = points[0].datum as WaffleDatum;
if (!d) return { title: "", rows: [] };
return {
title: d.category,
rows: [{ label: "Share Percentage", value: `${d.value}%`, color: "var(--chart-1)" }],
};
}
export function WaffleUnitChart() {
const data = useMemo(() => generateDemoData(), []);
const definition = useMemo(
() =>
defineChart(
{
renderer: motionRenderer,
scales: {
x: null,
y: null,
},
marks: [
waffleY(data, {
y: "value",
color: "category",
key: "category",
unit: 1,
gap: 2,
round: true,
radius: 3,
}),
],
guides: false,
color: {
domain: data.map((d) => d.category),
range: [
"var(--chart-1)",
"var(--chart-2)",
"var(--chart-3)",
"var(--chart-4)",
"var(--chart-5)",
],
},
margin: { top: 24, right: 24, bottom: 24, left: 24 },
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>Frontend Framework Market Share Waffle</CardTitle>
<CardDescription>100-cell unit square grid representing proportion breakdown</CardDescription>
</CardHeader>
<CardContent>
<div className="h-[250px] w-full">
<Chart
definition={definition}
renderer={motionRenderer}
height={250}
ariaLabel="Frontend Framework Market Share Waffle Chart"
/>
</div>
</CardContent>
<CardFooter className="flex-col items-start gap-2 text-sm">
<div className="flex items-center gap-2 leading-none font-medium">
React and Vue account for 60% of overall developer usage{" "}
<Grid3X3 className="h-4 w-4 text-emerald-500" />
</div>
<div className="text-muted-foreground leading-none">
Each rounded grid unit square represents 1% market allocation
</div>
</CardFooter>
</Card>
);
}
export default WaffleUnitChart;