components/tanstack-charts/line/select-extrema.tsx
import { type ChartPoint, defineChart, dot, lineY, select, text } from "@tanstack/charts";
import { decorative } from "@tanstack/charts/mark/decorative";
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 { ArrowUpRight } from "lucide-react";
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
interface StockDatum {
Date: Date;
Close: number;
}
const motionRenderer = motion({
initial: "always",
transition: { type: "spring", stiffness: 170, damping: 18, mass: 1 },
});
function generateDemoData(): StockDatum[] {
const results: StockDatum[] = [];
let price = 140;
for (let d = 0; d < 60; d++) {
const date = new Date(Date.UTC(2024, 0, 1 + d));
price += Math.sin(d * 0.15) * 3 + (Math.random() - 0.48) * 4;
price = Math.max(100, Math.min(220, price));
results.push({ Date: date, Close: Number(price.toFixed(2)) });
}
return results;
}
function shadcnTooltipContent<TDatum>(points: readonly ChartPoint<TDatum>[]) {
if (points.length === 0) return { title: "", rows: [] };
const d = points[0].datum as StockDatum;
if (!d || !d.Date) return { title: "", rows: [] };
const dateObj = d.Date instanceof Date ? d.Date : new Date(d.Date);
const titleStr = isNaN(dateObj.getTime())
? ""
: dateObj.toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric", timeZone: "UTC" });
return {
title: titleStr,
rows: [{ label: "Closing Price", value: `$${d.Close.toFixed(2)}`, color: "var(--chart-1)" }],
};
}
export function SelectExtrema() {
const data = useMemo(() => generateDemoData(), []);
const minimumPoint = useMemo(
() =>
select(data, {
value: "Close",
select: "min",
}),
[data],
);
const maximumPoint = useMemo(
() =>
select(data, {
value: "Close",
select: "max",
}),
[data],
);
const definition = useMemo(
() =>
defineChart(
{
renderer: motionRenderer,
marks: [
lineY(data, {
id: "close-line",
x: "Date",
y: "Close",
key: (row: StockDatum) =>
row?.Date
? row.Date instanceof Date
? row.Date.getTime()
: new Date(row.Date).getTime()
: 0,
stroke: "var(--chart-1)",
strokeWidth: 2.25,
}),
dot(minimumPoint, {
id: "minimum-point",
x: "Date",
y: "Close",
fill: "var(--destructive)",
r: 5,
}),
dot(maximumPoint, {
id: "maximum-point",
x: "Date",
y: "Close",
fill: "var(--emerald-500, #10b981)",
r: 5,
}),
decorative(
text(minimumPoint, {
id: "minimum-label",
x: "Date",
y: "Close",
text: ({ Close }: StockDatum) => `Low $${Close.toFixed(2)}`,
fill: "var(--destructive)",
anchor: "middle",
dy: 15,
fontSize: 10,
fontWeight: 700,
}),
),
decorative(
text(maximumPoint, {
id: "maximum-label",
x: "Date",
y: "Close",
text: ({ Close }: StockDatum) => `High $${Close.toFixed(2)}`,
fill: "var(--emerald-500, #10b981)",
anchor: "middle",
dy: -15,
fontSize: 10,
fontWeight: 700,
}),
),
],
scales: {
x: { scale: scaleUtc, axis: { label: "Date Timeline" } },
y: {
scale: scaleLinear,
grid: true,
axis: { label: "Stock Closing Price ($ USD)" },
},
},
margin: { top: 28, 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, minimumPoint, maximumPoint],
);
return (
<Card className="w-full max-w-xl">
<CardHeader>
<CardTitle>Automatic Extrema High/Low Annotations</CardTitle>
<CardDescription>
Line chart automatically pinpointing and annotating global min & max points
</CardDescription>
</CardHeader>
<CardContent>
<div className="h-[250px] w-full">
<Chart
definition={definition}
renderer={motionRenderer}
height={250}
ariaLabel="Automatic Extrema High/Low Annotations Chart"
/>
</div>
</CardContent>
<CardFooter className="flex-col items-start gap-2 text-sm">
<div className="flex items-center gap-2 leading-none font-medium">
Automatic select reducer isolates high/low extrema values{" "}
<ArrowUpRight className="h-4 w-4 text-emerald-500" />
</div>
<div className="text-muted-foreground leading-none">
Decorative text marks position callout badges dynamically at extreme coordinates
</div>
</CardFooter>
</Card>
);
}
export default SelectExtrema;