
Real-time streaming time series with sliding window data buffer retention.
components/tanstack-charts/line/streaming-window-preservation.tsx
import { type ChartPoint, defineChart, dot, lineY } from "@tanstack/charts";
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 { Activity, Plus } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
interface StreamDatum {
date: Date;
downloads: number;
}
type ViewportMode = "latest" | "all" | "locked";
const motionRenderer = motion({
initial: "always",
transition: { type: "spring", stiffness: 170, damping: 18, mass: 1 },
});
function generateInitialData(): StreamDatum[] {
const results: StreamDatum[] = [];
const baseDate = new Date(Date.UTC(2024, 0, 1)).getTime();
const dayMs = 24 * 60 * 60 * 1000;
for (let i = 0; i < 10; i++) {
results.push({
date: new Date(baseDate + i * dayMs),
downloads: Math.round(1200 + Math.random() * 800),
});
}
return results;
}
function shadcnTooltipContent<TDatum>(points: readonly ChartPoint<TDatum>[]) {
if (points.length === 0) return { title: "", rows: [] };
const d = points[0].datum as StreamDatum;
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", timeZone: "UTC" });
return {
title: titleStr,
rows: [{ label: "Downloads", value: `${d.downloads.toLocaleString()}`, color: "var(--chart-1)" }],
};
}
export function StreamingWindowPreservation() {
const [data, setData] = useState<StreamDatum[]>(() => generateInitialData());
const [mode, setMode] = useState<ViewportMode>("latest");
const appendSample = () => {
setData((prev) => {
const lastEntry = prev.length > 0 ? prev[prev.length - 1] : null;
const lastTime = lastEntry?.date
? lastEntry.date instanceof Date
? lastEntry.date.getTime()
: new Date(lastEntry.date).getTime()
: Date.now();
const nextDate = new Date(lastTime + 24 * 60 * 60 * 1000);
const nextVal = Math.round(1200 + Math.random() * 900);
return [...prev, { date: nextDate, downloads: nextVal }];
});
};
const visibleData = useMemo(() => {
if (mode === "latest") return data.slice(-8);
return data;
}, [data, mode]);
const domain = useMemo(() => {
if (visibleData.length === 0) return [new Date(), new Date()];
return [visibleData[0].date, visibleData[visibleData.length - 1].date];
}, [visibleData]);
const definition = useMemo(
() =>
defineChart(
{
renderer: motionRenderer,
marks: [
lineY(visibleData, {
id: "stream-line",
x: "date",
y: "downloads",
stroke: "var(--chart-1)",
strokeWidth: 2.5,
}),
dot(visibleData, {
id: "stream-points",
x: "date",
y: "downloads",
fill: "var(--chart-1)",
r: 4,
stroke: "var(--background)",
strokeWidth: 1.5,
}),
],
scales: {
x: {
scale: scaleUtc().domain(domain),
axis: {
ticks: {
format: (v: any) => {
const dateObj = v instanceof Date ? v : new Date(v);
return isNaN(dateObj.getTime())
? ""
: dateObj.toLocaleDateString("en-US", {
month: "short",
day: "numeric",
timeZone: "UTC",
});
},
},
},
},
y: {
scale: scaleLinear,
grid: true,
axis: { label: "Live Downloads" },
},
},
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),
},
},
),
[domain, visibleData],
);
return (
<Card className="w-full max-w-xl">
<CardHeader>
<CardTitle>Live Streaming Window Preservation</CardTitle>
<CardDescription>
Real-time streaming time series with sliding window viewport preservation controls
</CardDescription>
</CardHeader>
<CardContent className="space-y-3">
<div className="flex items-center gap-2">
<Button size="sm" variant="outline" className="h-8 text-xs" onClick={appendSample}>
<Plus className="mr-1 h-3.5 w-3.5" /> Append Sample
</Button>
<Button
size="sm"
variant={mode === "latest" ? "default" : "secondary"}
className="h-8 text-xs"
onClick={() => setMode("latest")}>
Follow Latest (8)
</Button>
<Button
size="sm"
variant={mode === "all" ? "default" : "secondary"}
className="h-8 text-xs"
onClick={() => setMode("all")}>
Show All ({data.length})
</Button>
</div>
<div className="h-[210px] w-full">
<Chart
definition={definition}
renderer={motionRenderer}
height={210}
ariaLabel="Live Streaming Window Preservation Chart"
/>
</div>
</CardContent>
<CardFooter className="flex-col items-start gap-2 text-sm">
<div className="flex items-center gap-2 leading-none font-medium">
Streaming buffer retains {data.length} total historical points{" "}
<Activity className="h-4 w-4 text-emerald-500" />
</div>
<div className="text-muted-foreground leading-none">
`scaleUtc().domain()` dynamically slides domain windows while maintaining animation continuity
</div>
</CardFooter>
</Card>
);
}
export default StreamingWindowPreservation;