
Smooth monotone curved area chart with responsive time range filter tabs.
components/tanstack-charts/area/themed-interactive-area.tsx
import { type ChartPoint, areaY, crosshair, d3Curve, defineChart, dot, lineY } from "@tanstack/charts";
import { focusGroupX } from "@tanstack/charts/focus";
import { motion } from "@tanstack/charts/motion";
import { tooltip } from "@tanstack/charts/tooltip";
import { Chart } from "@tanstack/react-charts/core";
import { useMemo, useState } from "react";
import { scaleLinear, scaleUtc } from "d3-scale";
import { curveMonotoneX } from "d3-shape";
import { TrendingUp } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
interface VisitorRow {
id: string;
date: Date;
visitors: number;
}
type RangeOption = "7d" | "30d" | "90d";
const motionRenderer = motion({
initial: "always",
transition: { type: "spring", stiffness: 170, damping: 18, mass: 1 },
});
const smoothCurve = d3Curve(curveMonotoneX);
function generateDemoData(daysCount: number): VisitorRow[] {
const results: VisitorRow[] = [];
const baseDate = new Date(Date.UTC(2024, 5, 1)).getTime();
let currentVisitors = 450;
for (let i = 0; i < daysCount; i++) {
currentVisitors += Math.floor(Math.sin(i * 0.3) * 40 + (Math.random() - 0.45) * 60);
const visitors = Math.max(150, currentVisitors);
const date = new Date(baseDate + i * 24 * 60 * 60 * 1000);
results.push({
id: `v-${i}`,
date,
visitors,
});
}
return results;
}
function shadcnTooltipContent<TDatum>(points: readonly ChartPoint<TDatum>[]) {
if (points.length === 0) return { title: "", rows: [] };
const d = points[0].datum as VisitorRow;
if (!d) return { title: "", rows: [] };
return {
title: d.date.toLocaleDateString("en-US", { month: "short", day: "numeric", timeZone: "UTC" }),
rows: [{ label: "Daily Visitors", value: `${d.visitors.toLocaleString()}`, color: "var(--chart-1)" }],
};
}
export function ThemedInteractiveArea() {
const [range, setRange] = useState<RangeOption>("30d");
const daysCount = range === "7d" ? 7 : range === "30d" ? 30 : 90;
const data = useMemo(() => generateDemoData(daysCount), [daysCount]);
const firstDate = data[0].date;
const lastDate = data[data.length - 1].date;
const yMaximum = useMemo(() => {
const max = Math.max(...data.map((d) => d.visitors));
return Math.ceil(max * 1.1);
}, [data]);
const definition = useMemo(
() =>
defineChart(
{
renderer: motionRenderer,
marks: [
areaY(data, {
id: "visitor-area",
x: "date",
y: "visitors",
key: "id",
fill: "url(#themed-area-gradient)",
fillOpacity: 1,
curve: smoothCurve,
}),
lineY(data, {
id: "visitor-line",
x: "date",
y: "visitors",
key: "id",
stroke: "var(--chart-1)",
strokeWidth: 2.5,
curve: smoothCurve,
}),
dot(data, {
id: "visitor-points",
x: "date",
y: "visitors",
key: "id",
r: 3.5,
fill: "var(--chart-1)",
stroke: "var(--background)",
strokeWidth: 1.5,
}),
crosshair<Date, number>({
id: "visitor-crosshair",
x: {
stroke: "var(--muted-foreground)",
strokeOpacity: 0.4,
strokeWidth: 1,
strokeDasharray: "3 3",
},
y: false,
}),
],
scales: {
x: {
scale: scaleUtc().domain([firstDate, lastDate]),
axis: {
ticks: {
format: (v: Date) =>
v.toLocaleDateString("en-US", {
month: "short",
day: "numeric",
timeZone: "UTC",
}),
},
},
},
y: {
scale: scaleLinear().domain([0, yMaximum]),
grid: true,
axis: { label: "Visitors" },
},
},
gradients: [
{
id: "themed-area-gradient",
x1: 0,
y1: 0,
x2: 0,
y2: 1,
stops: [
{ offset: 0, color: "var(--chart-1)", opacity: 0.35 },
{ offset: 0.7, color: "var(--chart-1)", opacity: 0.1 },
{ offset: 1, color: "var(--chart-1)", opacity: 0 },
],
},
],
focus: focusGroupX,
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, firstDate, lastDate],
);
return (
<Card className="w-full max-w-xl">
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<div>
<CardTitle>Daily Traffic & Visitors</CardTitle>
<CardDescription>
Smooth monotone curved area chart with smooth period range toggles
</CardDescription>
</div>
<div className="flex items-center space-x-1">
{(["7d", "30d", "90d"] as RangeOption[]).map((r) => (
<Button
key={r}
size="sm"
variant={range === r ? "default" : "outline"}
className="h-7 px-2 text-xs uppercase"
onClick={() => setRange(r)}>
{r}
</Button>
))}
</div>
</CardHeader>
<CardContent>
<div className="h-[230px] w-full">
<Chart
definition={definition}
renderer={motionRenderer}
height={230}
ariaLabel="Daily Traffic & Visitors Chart"
/>
</div>
</CardContent>
<CardFooter className="flex-col items-start gap-2 text-sm">
<div className="flex items-center gap-2 leading-none font-medium">
Traffic up +14.2% in selected {range} window <TrendingUp className="h-4 w-4 text-emerald-500" />
</div>
<div className="text-muted-foreground leading-none">
Gradient fill definition smoothly updates across 7d, 30d, and 90d presets
</div>
</CardFooter>
</Card>
);
}
export default ThemedInteractiveArea;