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

UsageProviderChart.tsx

529 lines17.1 KB

1import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon";
2import type { UsageProviderKind } from "@t3tools/contracts";
3import { useLayoutEffect, 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";
15import { observeResize } from "~/lib/observeResize";
16​
17const VIEW_WIDTH = 960;
18const VIEW_HEIGHT = 260;
19const TICK_COUNT = 4;
20const PLOT_TOP = 8;
21const NONE_LOADING: ReadonlySet<UsageProviderKind> = new Set();
22​
23export type UsageChartMetric = "tokens" | "cost";
24​
25interface UsageProviderChartProps {
26 readonly providers: readonly UsageProviderKind[];
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;
36 readonly hour12: boolean;
38​
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​
77function monotoneTangents(points: readonly Point[]): readonly number[] {
78 const count = points.length;
79 if (count < 2) return [0];
80​
81 const slopes: number[] = [];
82 for (let index = 0; index < count - 1; index += 1) {
83 const dx = (points[index + 1]?.x ?? 0) - (points[index]?.x ?? 0);
84 const dy = (points[index + 1]?.y ?? 0) - (points[index]?.y ?? 0);
85 slopes.push(dx === 0 ? 0 : dy / dx);
86 }
87​
88 const tangents: number[] = Array.from({ length: count }, () => 0);
89 tangents[0] = slopes[0] ?? 0;
90 tangents[count - 1] = slopes[count - 2] ?? 0;
91 for (let index = 1; index < count - 1; index += 1) {
92 const previous = slopes[index - 1] ?? 0;
93 const next = slopes[index] ?? 0;
94 tangents[index] = previous * next <= 0 ? 0 : (previous + next) / 2;
95 }
96​
97 for (let index = 0; index < count - 1; index += 1) {
98 const slope = slopes[index] ?? 0;
99 if (slope === 0) {
100 tangents[index] = 0;
101 tangents[index + 1] = 0;
102 continue;
103 }
104 const a = (tangents[index] ?? 0) / slope;
105 const b = (tangents[index + 1] ?? 0) / slope;
106 const magnitude = a * a + b * b;
107 if (magnitude > 9) {
108 const scale = 3 / Math.sqrt(magnitude);
109 tangents[index] = scale * a * slope;
110 tangents[index + 1] = scale * b * slope;
111 }
112 }
113​
114 return tangents;
116​
117interface CurveSegment {
118 readonly from: Point;
119 readonly c1: Point;
120 readonly c2: Point;
121 readonly to: Point;
123​
124function smoothCurve(points: readonly Point[]): readonly CurveSegment[] {
125 if (points.length < 2) return [];
126 const tangents = monotoneTangents(points);
127 const segments: CurveSegment[] = [];
128​
129 for (let index = 0; index < points.length - 1; index += 1) {
130 const from = points[index];
131 const to = points[index + 1];
132 if (from === undefined || to === undefined) continue;
133 const dx = to.x - from.x;
134 segments.push({
135 from,
136 c1: { x: from.x + dx / 3, y: from.y + ((tangents[index] ?? 0) * dx) / 3 },
137 c2: { x: to.x - dx / 3, y: to.y - ((tangents[index + 1] ?? 0) * dx) / 3 },
138 to,
139 });
140 }
141 return segments;
143​
144function curvePath(segments: readonly CurveSegment[]): string {
145 const first = segments[0];
146 if (first === undefined) return "";
147 let path = `M${first.from.x.toFixed(2)},${first.from.y.toFixed(2)}`;
148 for (const segment of segments) {
149 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)}`;
150 }
151 return path;
153​
154function areaPath(line: string) {
155 return line === "" ? "" : `${line} L${VIEW_WIDTH},${VIEW_HEIGHT} L0,${VIEW_HEIGHT} Z`;
157​
158export function niceScale(peak: number, count: number): { max: number; ticks: readonly number[] } {
159 if (peak <= 0) return { max: 0, ticks: [0] };
160​
161 const rawStep = peak / count;
162 const magnitude = 10 ** Math.floor(Math.log10(rawStep));
163 const normalized = rawStep / magnitude;
164 const step = (normalized > 5 ? 10 : normalized > 2 ? 5 : normalized > 1 ? 2 : 1) * magnitude;
165​
166 const max = Math.ceil(peak / step) * step;
167 const ticks: number[] = [];
168 for (let value = 0; value <= max + step * 1e-6; value += step) ticks.push(value);
169 return { max, ticks };
171​
172const PLACEHOLDER_TICKS = Array.from({ length: TICK_COUNT + 1 }, (_, index) => index);
173​
174export function chartScale(
175 columns: readonly DayColumn[],
176 loadingProviders: ReadonlySet<UsageProviderKind>,
177) {
178 // Not the sum: layered series each measure from zero, so a combined peak
179 // would leave the plot permanently half empty.
180 const peak = columns.reduce(
181 (max, column) => column.bands.reduce((inner, band) => Math.max(inner, band.value), max),
182 0,
183 );
184 return peak === 0 && loadingProviders.size > 0
185 ? { max: TICK_COUNT, ticks: PLACEHOLDER_TICKS, labeled: false }
186 : { ...niceScale(peak, TICK_COUNT), labeled: true };
188​
189// Leave room above the top gridline so the constant-width stroke is not
190// clipped when a series reaches the peak.
191function valueToY(value: number, max: number) {
192 return max === 0 ? VIEW_HEIGHT : VIEW_HEIGHT - (value / max) * (VIEW_HEIGHT - PLOT_TOP);
194​
195function buildChart(
196 periods: readonly string[],
197 byPeriod: ReadonlyMap<string, DailyTotals | HourlyTotals>,
198 metric: UsageChartMetric,
199 providers: readonly UsageProviderKind[],
200 loadingProviders: ReadonlySet<UsageProviderKind>,
201) {
202 const columns = buildPeriodColumns(periods, byPeriod, metric);
203 const scale = chartScale(columns, loadingProviders);
204 const stepX = periods.length < 2 ? 0 : VIEW_WIDTH / (periods.length - 1);
205 const paths = providers.map((provider) => {
206 const slot = PROVIDER_ORDER.indexOf(provider);
207 const line = curvePath(
208 smoothCurve(
209 columns.map((column, periodIndex) => ({
210 x: periodIndex * stepX,
211 y: valueToY(column.bands[slot]?.value ?? 0, scale.max),
212 })),
213 ),
214 );
215 return {
216 provider,
217 loading: loadingProviders.has(provider),
218 total: columns.reduce((sum, column) => sum + (column.bands[slot]?.value ?? 0), 0),
219 line,
220 area: areaPath(line),
221 };
222 });
223​
224 return { columns, scale, stepX, paths: paths.toSorted((a, b) => b.total - a.total) };
226​
227function UsageChartTooltip({
228 tooltipRef,
229 label,
230 column,
231 providers,
232 loadingProviders,
233 format,
234}: {
235 readonly tooltipRef: React.Ref<HTMLDivElement>;
236 readonly label: string;
237 readonly column: DayColumn | undefined;
238 readonly providers: readonly UsageProviderKind[];
239 readonly loadingProviders: ReadonlySet<UsageProviderKind>;
240 readonly format: (value: number) => string;
241}) {
242 const partial = providers.some((provider) => loadingProviders.has(provider));
243 return (
244 <div
245 ref={tooltipRef}
246 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"
247 style={{
248 left: "var(--usage-tooltip-left, 0px)",
249 top: "var(--usage-tooltip-top, 0px)",
250 }}
251 >
252 <div className="mb-1 text-muted-foreground">{label}</div>
253 {providers.map((provider) => {
254 const { label: providerLabel, driverKind } = PROVIDER_PRESENTATION[provider];
255 return (
256 <div key={provider} className="flex items-center justify-between gap-3">
257 <span className="flex items-center gap-1.5 text-muted-foreground">
258 <ProviderInstanceIcon
259 driverKind={driverKind}
260 displayName={providerLabel}
261 iconClassName="size-3"
262 />
263 {providerLabel}
264 </span>
265 <span
266 className={cn(
267 "tabular-nums",
268 loadingProviders.has(provider) ? "text-muted-foreground" : "text-foreground",
269 )}
270 >
271 {format(column?.bands.find((band) => band.provider === provider)?.value ?? 0)}
272 </span>
273 </div>
274 );
275 })}
276 <div className="mt-1 flex items-center justify-between gap-3 border-t border-border pt-1">
277 <span className="text-muted-foreground">Total</span>
278 <span className={cn("tabular-nums", partial ? "text-muted-foreground" : "text-foreground")}>
279 {format(column?.total ?? 0)}
280 </span>
281 </div>
282 </div>
283 );
285​
286function UsageChartPlot({
287 periods,
288 columns,
289 stepX,
290 providers,
291 loadingProviders,
292 format,
293 formatTooltipPeriod,
294 ariaLabel,
295 children,
296}: {
297 readonly periods: readonly string[];
298 readonly columns: readonly DayColumn[];
299 readonly stepX: number;
300 readonly providers: readonly UsageProviderKind[];
301 readonly loadingProviders: ReadonlySet<UsageProviderKind>;
302 readonly format: (value: number) => string;
303 readonly formatTooltipPeriod: (period: string) => string;
304 readonly ariaLabel: string;
305 readonly children: React.ReactNode;
306}) {
307 const [hoverIndex, setHoverIndex] = useState<number | null>(null);
308 const plotRef = useRef<HTMLDivElement | null>(null);
309 const tooltipRef = useRef<HTMLDivElement | null>(null);
310 const hoverPositionRef = useRef<{ x: number; y: number } | null>(null);
311​
312 const positionTooltip = () => {
313 const plot = plotRef.current;
314 const tooltip = tooltipRef.current;
315 const hoverPosition = hoverPositionRef.current;
316 if (plot === null || tooltip === null || hoverPosition === null) return;
317​
318 const gap = 12;
319 const tooltipWidth = tooltip.offsetWidth;
320 const tooltipHeight = tooltip.offsetHeight;
321 const plotWidth = plot.clientWidth;
322 const plotHeight = plot.clientHeight;
323 const preferredLeft =
324 hoverPosition.x + gap + tooltipWidth <= plotWidth
325 ? hoverPosition.x + gap
326 : hoverPosition.x - gap - tooltipWidth;
327 const preferredTop =
328 hoverPosition.y + gap + tooltipHeight <= plotHeight
329 ? hoverPosition.y + gap
330 : hoverPosition.y - gap - tooltipHeight;
331 const left = Math.min(Math.max(0, preferredLeft), Math.max(0, plotWidth - tooltipWidth));
332 const top = Math.min(Math.max(0, preferredTop), Math.max(0, plotHeight - tooltipHeight));
333 plot.style.setProperty("--usage-tooltip-left", `${left}px`);
334 plot.style.setProperty("--usage-tooltip-top", `${top}px`);
335 };
336​
337 useLayoutEffect(() => {
338 if (hoverIndex === null) return;
339 positionTooltip();
340​
341 const plot = plotRef.current;
342 const tooltip = tooltipRef.current;
343 if (plot === null || tooltip === null) return;
344​
345 return observeResize([plot, tooltip], positionTooltip);
346 }, [hoverIndex, positionTooltip]);
347​
348 const handleMove = (event: React.MouseEvent<HTMLDivElement>) => {
349 const plot = plotRef.current;
350 if (plot === null || periods.length === 0) return;
351 const bounds = plot.getBoundingClientRect();
352 if (bounds.width === 0) return;
353 const localX = Math.min(bounds.width, Math.max(0, event.clientX - bounds.left));
354 const localY = Math.min(bounds.height, Math.max(0, event.clientY - bounds.top));
355 const fraction = localX / bounds.width;
356 const index = Math.round(fraction * (periods.length - 1));
357 hoverPositionRef.current = { x: localX, y: localY };
358 positionTooltip();
359 setHoverIndex(Math.min(periods.length - 1, Math.max(0, index)));
360 };
361​
362 const hoveredPeriod = hoverIndex === null ? undefined : periods[hoverIndex];
363​
364 return (
365 <div
366 ref={plotRef}
367 className="relative h-56 flex-1"
368 onMouseMove={handleMove}
369 onMouseLeave={() => {
370 hoverPositionRef.current = null;
371 setHoverIndex(null);
372 }}
373 >
374 <svg
375 className="h-full w-full"
376 viewBox={`0 0 ${VIEW_WIDTH} ${VIEW_HEIGHT}`}
377 preserveAspectRatio="none"
378 role="img"
379 aria-label={ariaLabel}
380 >
381 {children}
382 {hoverIndex === null ? null : (
383 <line
384 x1={hoverIndex * stepX}
385 x2={hoverIndex * stepX}
386 y1={PLOT_TOP}
387 y2={VIEW_HEIGHT}
388 stroke="currentColor"
389 strokeWidth={1}
390 className="text-muted-foreground"
391 vectorEffect="non-scaling-stroke"
392 />
393 )}
394 </svg>
395​
396 {hoverIndex === null || hoveredPeriod === undefined ? null : (
397 <UsageChartTooltip
398 tooltipRef={tooltipRef}
399 label={formatTooltipPeriod(hoveredPeriod)}
400 column={columns[hoverIndex]}
401 providers={providers}
402 loadingProviders={loadingProviders}
403 format={format}
404 />
405 )}
406 </div>
407 );
409​
410export function UsageProviderChart({
411 providers,
412 loadingProviders = NONE_LOADING,
413 days,
414 daily,
415 hours,
416 hourly,
417 metric,
418 referenceTime,
419 resolution,
420 timeZone,
421 hour12,
422}: UsageProviderChartProps) {
423 const periods = resolution === "hour" ? hours : days;
424 const totals: readonly (DailyTotals | HourlyTotals)[] = resolution === "hour" ? hourly : daily;
425 const byPeriod = new Map(
426 totals.map((entry) => ["hourStart" in entry ? entry.hourStart : entry.day, entry]),
427 );
428 const { columns, scale, paths, stepX } = buildChart(
429 periods,
430 byPeriod,
431 metric,
432 providers,
433 loadingProviders,
434 );
435​
436 const toY = (value: number) => valueToY(value, scale.max);
437 const seriesClassName = (loading: boolean) =>
438 cn("transition-opacity", loading && "opacity-40 delay-150");
439 const format = metric === "tokens" ? formatTokens : formatUsd;
440 const formatPeriod = (period: string) =>
441 resolution === "hour" ? formatHourShort(period, timeZone, hour12) : formatDayShort(period);
442 const formatTooltipPeriod = (period: string) =>
443 resolution === "hour" && referenceTime !== undefined
444 ? formatRelativeHourShort(period, referenceTime, timeZone, hour12)
445 : formatPeriod(period);
446​
447 return (
448 <div className="flex flex-col gap-1">
449 <div className="flex gap-2">
450 <div className="relative h-56 w-14 shrink-0">
451 {scale.labeled
452 ? scale.ticks.map((tick) => (
453 <span
454 key={tick}
455 className="absolute right-0 -translate-y-1/2 text-3xs text-muted-foreground tabular-nums"
456 style={{ top: `${(toY(tick) / VIEW_HEIGHT) * 100}%` }}
457 >
458 {tick === 0 ? "0" : format(tick)}
459 </span>
460 ))
461 : null}
462 </div>
463​
464 <UsageChartPlot
465 periods={periods}
466 columns={columns}
467 stepX={stepX}
468 providers={providers}
469 loadingProviders={loadingProviders}
470 format={format}
471 formatTooltipPeriod={formatTooltipPeriod}
472 ariaLabel={`${resolution === "hour" ? "Hourly" : "Daily"} ${metric === "tokens" ? "processed tokens" : "cost"} by provider`}
473 >
474 {scale.ticks.map((tick) => {
475 const y = toY(tick);
476 return (
477 <line
478 key={tick}
479 x1={0}
480 x2={VIEW_WIDTH}
481 y1={y}
482 y2={y}
483 stroke="currentColor"
484 strokeWidth={1}
485 className="text-border"
486 vectorEffect="non-scaling-stroke"
487 />
488 );
489 })}
490​
491 {paths.map(({ provider, loading, area }) => (
492 <path
493 key={provider}
494 d={area}
495 className={seriesClassName(loading)}
496 fill={PROVIDER_PRESENTATION[provider].color}
497 fillOpacity={0.12}
498 />
499 ))}
500 {paths.map(({ provider, loading, line }) => (
501 <path
502 key={provider}
503 d={line}
504 className={seriesClassName(loading)}
505 fill="none"
506 stroke={PROVIDER_PRESENTATION[provider].color}
507 strokeWidth={2}
508 vectorEffect="non-scaling-stroke"
509 />
510 ))}
511 </UsageChartPlot>
512 </div>
513​
514 <div className="flex justify-between pl-16 text-3xs text-muted-foreground uppercase">
515 <span>{periods[0] === undefined ? "" : formatPeriod(periods[0])}</span>
516 <span>
517 {periods[Math.floor(periods.length / 2)] === undefined
518 ? ""
519 : formatPeriod(periods[Math.floor(periods.length / 2)] ?? "")}
520 </span>
521 <span>
522 {periods[periods.length - 1] === undefined
523 ? ""
524 : formatPeriod(periods[periods.length - 1] ?? "")}
525 </span>
526 </div>
527 </div>
528 );