Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

UsageProviderChart.tsx

500 lines17.6 KB

1import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon";
2import type { UsageProviderKind } from "@t3tools/contracts";
3import { useCallback, useLayoutEffect, useMemo, useRef, useState } from "react";
4​
5import type { DailyTotals, HourlyTotals } from "@t3tools/shared/usageMerge";
6import {
7 formatDayShort,
8 formatHourShort,
9 formatRelativeHourShort,
10 formatTokens,
11 formatUsd,
12} from "@t3tools/shared/usageFormat";
13import { cn } from "~/lib/utils";
14import { PROVIDER_ORDER, PROVIDER_PRESENTATION } from "./usageProviders";
15​
16const VIEW_WIDTH = 960;
17const VIEW_HEIGHT = 260;
18const TICK_COUNT = 4;
19const PLOT_TOP = 8;
20const NONE_LOADING: ReadonlySet<UsageProviderKind> = new Set();
21​
22export type UsageChartMetric = "tokens" | "cost";
23​
24interface UsageProviderChartProps {
25 readonly providers: readonly UsageProviderKind[];
26 /** Providers whose figures are still coming in: their lines are muted. */
27 readonly loadingProviders?: ReadonlySet<UsageProviderKind>;
28 readonly days: readonly string[];
29 readonly daily: readonly DailyTotals[];
30 readonly hours: readonly string[];
31 readonly hourly: readonly HourlyTotals[];
32 readonly metric: UsageChartMetric;
33 readonly referenceTime: string | undefined;
34 readonly resolution: "day" | "hour";
35 readonly timeZone: string;
37​
38/** One day's per-provider values, shared by the paths and the hover readout. */
39export interface DayColumn {
40 readonly bands: readonly {
41 readonly provider: UsageProviderKind;
42 readonly value: number;
43 }[];
44 readonly total: number;
46​
47interface Point {
48 readonly x: number;
49 readonly y: number;
51​
52function valueFor(
53 totals: DailyTotals | HourlyTotals | undefined,
54 provider: UsageProviderKind,
55 metric: UsageChartMetric,
56): number {
57 const entry = totals?.byProvider.get(provider);
58 if (entry === undefined) return 0;
59 return metric === "tokens" ? entry.totalTokens : entry.costUsd;
61​
62export function buildPeriodColumns(
63 periods: readonly string[],
64 byPeriod: ReadonlyMap<string, DailyTotals | HourlyTotals>,
65 metric: UsageChartMetric,
66): readonly DayColumn[] {
67 return periods.map((period) => {
68 const entry = byPeriod.get(period);
69 const bands = PROVIDER_ORDER.map((provider) => ({
70 provider,
71 value: valueFor(entry, provider, metric),
72 }));
73 return { bands, total: bands.reduce((sum, band) => sum + band.value, 0) };
74 });
76​
77/** Shape-preserving cubic tangents that cannot overshoot spiky usage data. */
78function monotoneTangents(points: readonly Point[]): readonly number[] {
79 const count = points.length;
80 if (count < 2) return [0];
81​
82 const slopes: number[] = [];
83 for (let index = 0; index < count - 1; index += 1) {
84 const dx = (points[index + 1]?.x ?? 0) - (points[index]?.x ?? 0);
85 const dy = (points[index + 1]?.y ?? 0) - (points[index]?.y ?? 0);
86 slopes.push(dx === 0 ? 0 : dy / dx);
87 }
88​
89 const tangents: number[] = Array.from({ length: count }, () => 0);
90 tangents[0] = slopes[0] ?? 0;
91 tangents[count - 1] = slopes[count - 2] ?? 0;
92 for (let index = 1; index < count - 1; index += 1) {
93 const previous = slopes[index - 1] ?? 0;
94 const next = slopes[index] ?? 0;
95 tangents[index] = previous * next <= 0 ? 0 : (previous + next) / 2;
96 }
97​
98 for (let index = 0; index < count - 1; index += 1) {
99 const slope = slopes[index] ?? 0;
100 if (slope === 0) {
101 tangents[index] = 0;
102 tangents[index + 1] = 0;
103 continue;
104 }
105 const a = (tangents[index] ?? 0) / slope;
106 const b = (tangents[index + 1] ?? 0) / slope;
107 const magnitude = a * a + b * b;
108 if (magnitude > 9) {
109 const scale = 3 / Math.sqrt(magnitude);
110 tangents[index] = scale * a * slope;
111 tangents[index + 1] = scale * b * slope;
112 }
113 }
114​
115 return tangents;
117​
118interface CurveSegment {
119 readonly from: Point;
120 readonly c1: Point;
121 readonly c2: Point;
122 readonly to: Point;
124​
125function smoothCurve(points: readonly Point[]): readonly CurveSegment[] {
126 if (points.length < 2) return [];
127 const tangents = monotoneTangents(points);
128 const segments: CurveSegment[] = [];
129​
130 for (let index = 0; index < points.length - 1; index += 1) {
131 const from = points[index];
132 const to = points[index + 1];
133 if (from === undefined || to === undefined) continue;
134 const dx = to.x - from.x;
135 segments.push({
136 from,
137 c1: { x: from.x + dx / 3, y: from.y + ((tangents[index] ?? 0) * dx) / 3 },
138 c2: { x: to.x - dx / 3, y: to.y - ((tangents[index + 1] ?? 0) * dx) / 3 },
139 to,
140 });
141 }
142 return segments;
144​
145function curvePath(segments: readonly CurveSegment[]): string {
146 const first = segments[0];
147 if (first === undefined) return "";
148 let path = `M${first.from.x.toFixed(2)},${first.from.y.toFixed(2)}`;
149 for (const segment of segments) {
150 path += ` C${segment.c1.x.toFixed(2)},${segment.c1.y.toFixed(2)} ${segment.c2.x.toFixed(2)},${segment.c2.y.toFixed(2)} ${segment.to.x.toFixed(2)},${segment.to.y.toFixed(2)}`;
151 }
152 return path;
154​
155function areaPath(line: string) {
156 return line === "" ? "" : `${line} L${VIEW_WIDTH},${VIEW_HEIGHT} L0,${VIEW_HEIGHT} Z`;
158​
159/**
160 * Builds a scale whose maximum is a readable 1/2/5 x 10^n step at or above the
161 * peak.
162 *
163 * Rounding the maximum *up* is the point: stopping at the last step below the
164 * peak leaves the tallest day drawn past the top of the plot, where it is
165 * clipped.
166 */
167export function niceScale(peak: number, count: number): { max: number; ticks: readonly number[] } {
168 if (peak <= 0) return { max: 0, ticks: [0] };
169​
170 const rawStep = peak / count;
171 const magnitude = 10 ** Math.floor(Math.log10(rawStep));
172 const normalized = rawStep / magnitude;
173 const step = (normalized > 5 ? 10 : normalized > 2 ? 5 : normalized > 1 ? 2 : 1) * magnitude;
174​
175 const max = Math.ceil(peak / step) * step;
176 const ticks: number[] = [];
177 for (let value = 0; value <= max + step * 1e-6; value += step) ticks.push(value);
178 return { max, ticks };
180​
181const PLACEHOLDER_TICKS = Array.from({ length: TICK_COUNT + 1 }, (_, index) => index);
182​
183/**
184 * Scales to the largest single provider-period. With nothing to show yet while
185 * providers load, unlabeled placeholder gridlines hold their usual spacing so
186 * nothing shifts on arrival.
187 */
188export function chartScale(
189 columns: readonly DayColumn[],
190 loadingProviders: ReadonlySet<UsageProviderKind>,
191) {
192 // Not the sum: layered series each measure from zero, so a combined peak
193 // would leave the plot permanently half empty.
194 const peak = columns.reduce(
195 (max, column) => column.bands.reduce((inner, band) => Math.max(inner, band.value), max),
196 0,
197 );
198 return peak === 0 && loadingProviders.size > 0
199 ? { max: TICK_COUNT, ticks: PLACEHOLDER_TICKS, labeled: false }
200 : { ...niceScale(peak, TICK_COUNT), labeled: true };
202​
203// Leave room above the top gridline so the constant-width stroke is not
204// clipped when a series reaches the peak.
205function valueToY(value: number, max: number) {
206 return max === 0 ? VIEW_HEIGHT : VIEW_HEIGHT - (value / max) * (VIEW_HEIGHT - PLOT_TOP);
208​
209/** Per-provider paths in paint order, heaviest first. */
210function buildChart(
211 periods: readonly string[],
212 byPeriod: ReadonlyMap<string, DailyTotals | HourlyTotals>,
213 metric: UsageChartMetric,
214 providers: readonly UsageProviderKind[],
215 loadingProviders: ReadonlySet<UsageProviderKind>,
216) {
217 const columns = buildPeriodColumns(periods, byPeriod, metric);
218 const scale = chartScale(columns, loadingProviders);
219 const stepX = periods.length < 2 ? 0 : VIEW_WIDTH / (periods.length - 1);
220 const paths = providers.map((provider) => {
221 const slot = PROVIDER_ORDER.indexOf(provider);
222 const line = curvePath(
223 smoothCurve(
224 columns.map((column, periodIndex) => ({
225 x: periodIndex * stepX,
226 y: valueToY(column.bands[slot]?.value ?? 0, scale.max),
227 })),
228 ),
229 );
230 return {
231 provider,
232 loading: loadingProviders.has(provider),
233 total: columns.reduce((sum, column) => sum + (column.bands[slot]?.value ?? 0), 0),
234 line,
235 area: areaPath(line),
236 };
237 });
238​
239 // Paint the heavier series first so the lighter one is not buried.
240 return { columns, scale, stepX, paths: paths.toSorted((a, b) => b.total - a.total) };
242​
243export function UsageProviderChart({
244 providers,
245 loadingProviders = NONE_LOADING,
246 days,
247 daily,
248 hours,
249 hourly,
250 metric,
251 referenceTime,
252 resolution,
253 timeZone,
254}: UsageProviderChartProps) {
255 const periods = resolution === "hour" ? hours : days;
256 const byPeriod = useMemo(
257 () =>
258 resolution === "hour"
259 ? new Map(hourly.map((entry) => [entry.hourStart, entry]))
260 : new Map(daily.map((entry) => [entry.day, entry])),
261 [daily, hourly, resolution],
262 );
263 const [hoverIndex, setHoverIndex] = useState<number | null>(null);
264 const plotRef = useRef<HTMLDivElement | null>(null);
265 const tooltipRef = useRef<HTMLDivElement | null>(null);
266 const hoverPositionRef = useRef<{ x: number; y: number } | null>(null);
267​
268 const { columns, scale, paths, stepX } = useMemo(
269 () => buildChart(periods, byPeriod, metric, providers, loadingProviders),
270 [byPeriod, loadingProviders, metric, periods, providers],
271 );
272 const toY = (value: number) => valueToY(value, scale.max);
273 // The delay keeps a quick answer from flashing, as with the page's figures.
274 const seriesClassName = (loading: boolean) =>
275 cn("transition-opacity", loading && "opacity-40 delay-150");
276​
277 const format = metric === "tokens" ? formatTokens : formatUsd;
278​
279 const positionTooltip = useCallback(() => {
280 const plot = plotRef.current;
281 const tooltip = tooltipRef.current;
282 const hoverPosition = hoverPositionRef.current;
283 if (plot === null || tooltip === null || hoverPosition === null) return;
284​
285 const gap = 12;
286 const tooltipWidth = tooltip.offsetWidth;
287 const tooltipHeight = tooltip.offsetHeight;
288 const plotWidth = plot.clientWidth;
289 const plotHeight = plot.clientHeight;
290 const preferredLeft =
291 hoverPosition.x + gap + tooltipWidth <= plotWidth
292 ? hoverPosition.x + gap
293 : hoverPosition.x - gap - tooltipWidth;
294 const preferredTop =
295 hoverPosition.y + gap + tooltipHeight <= plotHeight
296 ? hoverPosition.y + gap
297 : hoverPosition.y - gap - tooltipHeight;
298 const left = Math.min(Math.max(0, preferredLeft), Math.max(0, plotWidth - tooltipWidth));
299 const top = Math.min(Math.max(0, preferredTop), Math.max(0, plotHeight - tooltipHeight));
300 plot.style.setProperty("--usage-tooltip-left", `${left}px`);
301 plot.style.setProperty("--usage-tooltip-top", `${top}px`);
302 }, []);
303​
304 useLayoutEffect(() => {
305 if (hoverIndex === null) return;
306 positionTooltip();
307​
308 const plot = plotRef.current;
309 const tooltip = tooltipRef.current;
310 if (plot === null || tooltip === null || typeof ResizeObserver === "undefined") return;
311​
312 const observer = new ResizeObserver(positionTooltip);
313 observer.observe(plot);
314 observer.observe(tooltip);
315 return () => observer.disconnect();
316 }, [hoverIndex, positionTooltip]);
317​
318 const handleMove = useCallback(
319 (event: React.MouseEvent<HTMLDivElement>) => {
320 const plot = plotRef.current;
321 if (plot === null || periods.length === 0) return;
322 const bounds = plot.getBoundingClientRect();
323 if (bounds.width === 0) return;
324 const localX = Math.min(bounds.width, Math.max(0, event.clientX - bounds.left));
325 const localY = Math.min(bounds.height, Math.max(0, event.clientY - bounds.top));
326 const fraction = localX / bounds.width;
327 const index = Math.round(fraction * (periods.length - 1));
328 hoverPositionRef.current = { x: localX, y: localY };
329 positionTooltip();
330 setHoverIndex(Math.min(periods.length - 1, Math.max(0, index)));
331 },
332 [periods.length, positionTooltip],
333 );
334​
335 const hoveredPeriod = hoverIndex === null ? undefined : periods[hoverIndex];
336 const hoveredColumn = hoverIndex === null ? undefined : columns[hoverIndex];
337 const partial = providers.some((provider) => loadingProviders.has(provider));
338 const formatPeriod = (period: string) =>
339 resolution === "hour" ? formatHourShort(period, timeZone) : formatDayShort(period);
340 const formatTooltipPeriod = (period: string) =>
341 resolution === "hour" && referenceTime !== undefined
342 ? formatRelativeHourShort(period, referenceTime, timeZone)
343 : formatPeriod(period);
344​
345 return (
346 <div className="flex flex-col gap-1">
347 <div className="flex gap-2">
348 {/* Axis labels sit outside the plot so they stay aligned to gridlines. */}
349 <div className="relative h-56 w-14 shrink-0">
350 {scale.labeled
351 ? scale.ticks.map((tick) => (
352 <span
353 key={tick}
354 className="absolute right-0 -translate-y-1/2 text-3xs text-muted-foreground tabular-nums"
355 style={{ top: `${(toY(tick) / VIEW_HEIGHT) * 100}%` }}
356 >
357 {tick === 0 ? "0" : format(tick)}
358 </span>
359 ))
360 : null}
361 </div>
362​
363 <div
364 ref={plotRef}
365 className="relative h-56 flex-1"
366 onMouseMove={handleMove}
367 onMouseLeave={() => {
368 hoverPositionRef.current = null;
369 setHoverIndex(null);
370 }}
371 >
372 <svg
373 className="h-full w-full"
374 viewBox={`0 0 ${VIEW_WIDTH} ${VIEW_HEIGHT}`}
375 preserveAspectRatio="none"
376 role="img"
377 aria-label={`${resolution === "hour" ? "Hourly" : "Daily"} ${metric === "tokens" ? "processed tokens" : "cost"} by provider`}
378 >
379 {scale.ticks.map((tick) => {
380 const y = toY(tick);
381 return (
382 <line
383 key={tick}
384 x1={0}
385 x2={VIEW_WIDTH}
386 y1={y}
387 y2={y}
388 stroke="currentColor"
389 strokeWidth={1}
390 className="text-border"
391 vectorEffect="non-scaling-stroke"
392 />
393 );
394 })}
395​
396 {/* Fills first, then every stroke, so no series covers another's line. */}
397 {paths.map(({ provider, loading, area }) => (
398 <path
399 key={provider}
400 d={area}
401 className={seriesClassName(loading)}
402 fill={PROVIDER_PRESENTATION[provider].color}
403 fillOpacity={0.12}
404 />
405 ))}
406 {paths.map(({ provider, loading, line }) => (
407 <path
408 key={provider}
409 d={line}
410 className={seriesClassName(loading)}
411 fill="none"
412 stroke={PROVIDER_PRESENTATION[provider].color}
413 strokeWidth={2}
414 vectorEffect="non-scaling-stroke"
415 />
416 ))}
417​
418 {hoverIndex === null ? null : (
419 <line
420 x1={hoverIndex * stepX}
421 x2={hoverIndex * stepX}
422 y1={PLOT_TOP}
423 y2={VIEW_HEIGHT}
424 stroke="currentColor"
425 strokeWidth={1}
426 className="text-muted-foreground"
427 vectorEffect="non-scaling-stroke"
428 />
429 )}
430 </svg>
431​
432 {hoveredPeriod === undefined ? null : (
433 <div
434 ref={tooltipRef}
435 className="surface-glass pointer-events-none absolute z-10 min-w-36 max-w-full rounded-xl border border-border/50 px-2.5 py-2 text-xs shadow-lg"
436 style={{
437 left: "var(--usage-tooltip-left, 0px)",
438 top: "var(--usage-tooltip-top, 0px)",
439 }}
440 >
441 <div className="mb-1 text-muted-foreground">{formatTooltipPeriod(hoveredPeriod)}</div>
442 {providers.map((provider) => {
443 const { label, driverKind } = PROVIDER_PRESENTATION[provider];
444 return (
445 <div key={provider} className="flex items-center justify-between gap-3">
446 <span className="flex items-center gap-1.5 text-muted-foreground">
447 <ProviderInstanceIcon
448 driverKind={driverKind}
449 displayName={label}
450 iconClassName="size-3"
451 />
452 {label}
453 </span>
454 <span
455 className={cn(
456 "tabular-nums",
457 loadingProviders.has(provider)
458 ? "text-muted-foreground"
459 : "text-foreground",
460 )}
461 >
462 {format(
463 hoveredColumn?.bands.find((band) => band.provider === provider)?.value ?? 0,
464 )}
465 </span>
466 </div>
467 );
468 })}
469 <div className="mt-1 flex items-center justify-between gap-3 border-t border-border pt-1">
470 <span className="text-muted-foreground">Total</span>
471 <span
472 className={cn(
473 "tabular-nums",
474 partial ? "text-muted-foreground" : "text-foreground",
475 )}
476 >
477 {format(hoveredColumn?.total ?? 0)}
478 </span>
479 </div>
480 </div>
481 )}
482 </div>
483 </div>
484​
485 <div className="flex justify-between pl-16 text-3xs text-muted-foreground uppercase">
486 <span>{periods[0] === undefined ? "" : formatPeriod(periods[0])}</span>
487 <span>
488 {periods[Math.floor(periods.length / 2)] === undefined
489 ? ""
490 : formatPeriod(periods[Math.floor(periods.length / 2)] ?? "")}
491 </span>
492 <span>
493 {periods[periods.length - 1] === undefined
494 ? ""
495 : formatPeriod(periods[periods.length - 1] ?? "")}
496 </span>
497 </div>
498 </div>
499 );