import { lazy, Suspense, useId, useLayoutEffect, useMemo, useRef } from 'react'; import { type ChartPoint, useElementWidth } from '@/components/server/console/chart'; import type { ChartSeries } from '@/components/server/console/types'; const GRID_COLOR = 'var(--border)'; const TICK_COLOR = 'var(--muted-foreground)'; const SANS_FONT = 'var(--font-sans)'; const Y_AXIS_WIDTH = 64; const MARGIN = { top: 8, right: 8, bottom: 0, left: 0 }; // How far the visible right edge trails real time; just over the ~1s stats cadence. const RIGHT_LAG_MS = 1100; // Time drawn past the visible right edge, so the plot can keep sliding while the next sample is late. const SLIDE_MS = 4000; export interface AreaChartProps { /** Samples by `t`, a performance.now() timestamp; a series value is null until its first sample. */ data: readonly ChartPoint[]; series: readonly ChartSeries[]; /** Keeps the plot sliding between samples. */ live: boolean; /** The time the plot shows, in milliseconds. */ windowMs: number; /** A y-axis maximum that grows when the data exceeds it; omit to auto-scale. */ suggestedMax?: number; tickFormatter?: (value: number) => string; height?: number; } type YDomain = [number, (dataMax: number) => number] | [number, string]; interface RechartsAreaChartContentProps { data: readonly ChartPoint[]; series: readonly ChartSeries[]; live: boolean; uid: string; width: number; height: number; windowMs: number; yDomain: YDomain; tickFormatter?: (value: number) => string; } /* * The chart is drawn in two layers. The grid and Y axis stay put; the series are drawn once per * sample, a little wider than the plot, and slid left by a transform animation until the next * sample replaces them. Moving the plot never re-renders or repaints the SVG, so its cost does not * depend on the frame rate or on how expensive the active theme makes painting. */ const LazyRechartsAreaChart = lazy(async () => { const { Area, AreaChart: RechartsAreaChart, CartesianGrid, XAxis, YAxis } = await import('recharts'); return { default: function RechartsAreaChartContent({ data, series, live, uid, width, height, windowMs, yDomain, tickFormatter, }: RechartsAreaChartContentProps) { const slider = useRef(null); const points = useMemo(() => [...data], [data]); const plotWidth = Math.max(0, width - Y_AXIS_WIDTH - MARGIN.right); const slideDistance = (plotWidth * SLIDE_MS) / windowMs; // The newest sample's arrival time is the moment the visible window ends at `anchor - RIGHT_LAG_MS`. const anchor = data.at(-1)?.t; const right = (anchor ?? 0) - RIGHT_LAG_MS; const xDomain = useMemo<[number, number]>(() => [right - windowMs, right + SLIDE_MS], [right, windowMs]); useLayoutEffect(() => { if (!slider.current || anchor === undefined) { return; } const animation = slider.current.animate( [{ transform: 'translateX(0)' }, { transform: `translateX(${-slideDistance}px)` }], { duration: SLIDE_MS, easing: 'linear', fill: 'forwards' } ); animation.currentTime = Math.min(SLIDE_MS, Math.max(0, performance.now() - anchor)); if (!live) { animation.pause(); } return () => animation.cancel(); }, [anchor, live, slideDistance]); return ( <>
{/* Undrawn copies of the series: the axis only ticks for plotted data, and matching inputs give it the same scale as the sliding layer. */} {series.map(({ dataKey }) => ( ))}
{series.map(({ dataKey, color }) => ( ))} {series.map(({ dataKey, color }) => ( ))} {series.map(({ dataKey, color }) => ( ))}
); }, }; }); /** A live time series chart drawn with the `--chart-*`, `--border` and `--muted-foreground` tokens. */ export default function AreaChart({ data, series, live, windowMs, suggestedMax, tickFormatter, height = 180, }: AreaChartProps) { const uid = useId().replaceAll(':', ''); const container = useRef(null); const width = useElementWidth(container); const yDomain = useMemo( () => (suggestedMax === undefined ? [0, 'auto'] : [0, (dataMax: number) => Math.max(suggestedMax, dataMax)]), [suggestedMax] ); return (
{width > 0 && ( )}
); }