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

UsageProviderChart.tsx

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