Open History to see the last commit
1import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon";
2import type { UsageProviderKind } from "@t3tools/contracts";
3import { T, useGT, useLocale, useMessages } from "gt-react";
4import { useLayoutEffect, useRef, useState } from "react";
5
6import type { DailyTotals, HourlyTotals } from "@t3tools/shared/usageMerge";
7import {
8 formatDayShort,
9 formatHourShort,
10 formatTokens,
11 formatUsd,
12} from "@t3tools/shared/usageFormat";
13import { formatRelativeHourShort } from "@t3tools/shared/usageFormatCopy";
14import { cn } from "~/lib/utils";
15import { PROVIDER_ORDER, PROVIDER_PRESENTATION } from "./usageProviders";
16import { observeResize } from "~/lib/observeResize";
17
18const VIEW_WIDTH = 960;
19const VIEW_HEIGHT = 260;
20const TICK_COUNT = 4;
21const PLOT_TOP = 8;
22const NONE_LOADING: ReadonlySet<UsageProviderKind> = new Set();
23
24export type UsageChartMetric = "tokens" | "cost";
25
26interface UsageProviderChartProps {
27 readonly providers: readonly UsageProviderKind[];
28 readonly loadingProviders?: ReadonlySet<UsageProviderKind>;
29 readonly days: readonly string[];
30 readonly daily: readonly DailyTotals[];
31 readonly hours: readonly string[];
32 readonly hourly: readonly HourlyTotals[];
33 readonly metric: UsageChartMetric;
34 readonly referenceTime: string | undefined;
35 readonly resolution: "day" | "hour";
36 readonly timeZone: string;
37 readonly hour12: boolean;
38}
39
40export interface DayColumn {
41 readonly bands: readonly {
42 readonly provider: UsageProviderKind;
43 readonly value: number;
44 }[];
45 readonly total: number;
46}
47
48interface Point {
49 readonly x: number;
50 readonly y: number;
51}
52
53function valueFor(
54 totals: DailyTotals | HourlyTotals | undefined,
55 provider: UsageProviderKind,
56 metric: UsageChartMetric,
57): number {
58 const entry = totals?.byProvider.get(provider);
59 if (entry === undefined) return 0;
60 return metric === "tokens" ? entry.totalTokens : entry.costUsd;
61}
62
63export function buildPeriodColumns(
64 periods: readonly string[],
65 byPeriod: ReadonlyMap<string, DailyTotals | HourlyTotals>,
66 metric: UsageChartMetric,
67): readonly DayColumn[] {
68 return periods.map((period) => {
69 const entry = byPeriod.get(period);
70 const bands = PROVIDER_ORDER.map((provider) => ({
71 provider,
72 value: valueFor(entry, provider, metric),
73 }));
74 return { bands, total: bands.reduce((sum, band) => sum + band.value, 0) };
75 });
76}
77
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;
116}
117
118interface CurveSegment {
119 readonly from: Point;
120 readonly c1: Point;
121 readonly c2: Point;
122 readonly to: Point;
123}
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;
143}
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;
153}
154
155function areaPath(line: string) {
156 return line === "" ? "" : `${line} L${VIEW_WIDTH},${VIEW_HEIGHT} L0,${VIEW_HEIGHT} Z`;
157}
158
159function niceScale(
160 peak: number,
161 count: number,
162 minStep: number,
163): { max: number; ticks: readonly number[] } {
164 if (peak <= 0) return { max: 0, ticks: [0] };
165
166 const rawStep = peak / count;
167 const magnitude = 10 ** Math.floor(Math.log10(rawStep));
168 const normalized = rawStep / magnitude;
169 const step = Math.max(
170 (normalized > 5 ? 10 : normalized > 2 ? 5 : normalized > 1 ? 2 : 1) * magnitude,
171 minStep,
172 );
173
174 const max = Math.ceil(peak / step) * step;
175 const ticks: number[] = [];
176 for (let value = 0; value <= max + step * 1e-6; value += step) ticks.push(value);
177 return { max, ticks };
178}
179
180const PLACEHOLDER_TICKS = Array.from({ length: TICK_COUNT + 1 }, (_, index) => index);
181
182function chartScale(
183 columns: readonly DayColumn[],
184 loadingProviders: ReadonlySet<UsageProviderKind>,
185 minStep: number,
186) {
187 // Layered series each start at zero; summing peaks would waste plot height.
188 const peak = columns.reduce(
189 (max, column) => column.bands.reduce((inner, band) => Math.max(inner, band.value), max),
190 0,
191 );
192 return peak === 0 && loadingProviders.size > 0
193 ? { max: TICK_COUNT, ticks: PLACEHOLDER_TICKS, labeled: false }
194 : { ...niceScale(peak, TICK_COUNT, minStep), labeled: true };
195}
196
197function valueToY(value: number, max: number) {
198 return max === 0 ? VIEW_HEIGHT : VIEW_HEIGHT - (value / max) * (VIEW_HEIGHT - PLOT_TOP);
199}
200
201export function buildChart(
202 periods: readonly string[],
203 byPeriod: ReadonlyMap<string, DailyTotals | HourlyTotals>,
204 metric: UsageChartMetric,
205 providers: readonly UsageProviderKind[],
206 loadingProviders: ReadonlySet<UsageProviderKind>,
207) {
208 const columns = buildPeriodColumns(periods, byPeriod, metric);
209 // Labels show whole tokens or whole cents, so finer steps would repeat a label.
210 const scale = chartScale(columns, loadingProviders, metric === "tokens" ? 1 : 0.01);
211 const stepX = periods.length < 2 ? 0 : VIEW_WIDTH / (periods.length - 1);
212 const paths = providers.map((provider) => {
213 const slot = PROVIDER_ORDER.indexOf(provider);
214 const line = curvePath(
215 smoothCurve(
216 columns.map((column, periodIndex) => ({
217 x: periodIndex * stepX,
218 y: valueToY(column.bands[slot]?.value ?? 0, scale.max),
219 })),
220 ),
221 );
222 return {
223 provider,
224 loading: loadingProviders.has(provider),
225 total: columns.reduce((sum, column) => sum + (column.bands[slot]?.value ?? 0), 0),
226 line,
227 area: areaPath(line),
228 };
229 });
230
231 return { columns, scale, stepX, paths: paths.toSorted((a, b) => b.total - a.total) };
232}
233
234function UsageChartTooltip({
235 tooltipRef,
236 label,
237 column,
238 providers,
239 loadingProviders,
240 format,
241}: {
242 readonly tooltipRef: React.Ref<HTMLDivElement>;
243 readonly label: string;
244 readonly column: DayColumn | undefined;
245 readonly providers: readonly UsageProviderKind[];
246 readonly loadingProviders: ReadonlySet<UsageProviderKind>;
247 readonly format: (value: number) => string;
248}) {
249 const partial = providers.some((provider) => loadingProviders.has(provider));
250 return (
251 <div
252 ref={tooltipRef}
253 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"
254 style={{
255 left: "var(--usage-tooltip-left, 0px)",
256 top: "var(--usage-tooltip-top, 0px)",
257 }}
258 >
259 <div className="mb-1 text-muted-foreground">{label}</div>
260 {providers.map((provider) => {
261 const { label: providerLabel, driverKind } = PROVIDER_PRESENTATION[provider];
262 return (
263 <div key={provider} className="flex items-center justify-between gap-3">
264 <span className="flex items-center gap-1.5 text-muted-foreground">
265 <ProviderInstanceIcon
266 driverKind={driverKind}
267 displayName={providerLabel}
268 iconClassName="size-3"
269 />
270 {providerLabel}
271 </span>
272 <span
273 className={cn(
274 "tabular-nums",
275 loadingProviders.has(provider) ? "text-muted-foreground" : "text-foreground",
276 )}
277 >
278 {format(column?.bands.find((band) => band.provider === provider)?.value ?? 0)}
279 </span>
280 </div>
281 );
282 })}
283 <div className="mt-1 flex items-center justify-between gap-3 border-t border-border pt-1">
284 <span className="text-muted-foreground">
285 <T>Total</T>
286 </span>
287 <span className={cn("tabular-nums", partial ? "text-muted-foreground" : "text-foreground")}>
288 {format(column?.total ?? 0)}
289 </span>
290 </div>
291 </div>
292 );
293}
294
295function UsageChartPlot({
296 periods,
297 columns,
298 stepX,
299 providers,
300 loadingProviders,
301 format,
302 formatTooltipPeriod,
303 children,
304}: {
305 readonly periods: readonly string[];
306 readonly columns: readonly DayColumn[];
307 readonly stepX: number;
308 readonly providers: readonly UsageProviderKind[];
309 readonly loadingProviders: ReadonlySet<UsageProviderKind>;
310 readonly format: (value: number) => string;
311 readonly formatTooltipPeriod: (period: string) => string;
312 readonly children: React.ReactNode;
313}) {
314 // The pointer's x as a fraction of the plot, so a period change re-derives the hovered bucket.
315 const [hoverFraction, setHoverFraction] = useState<number | null>(null);
316 const plotRef = useRef<HTMLDivElement | null>(null);
317 const tooltipRef = useRef<HTMLDivElement | null>(null);
318 const hoverPositionRef = useRef<{ x: number; y: number } | null>(null);
319 const hoverIndex =
320 hoverFraction === null || periods.length === 0
321 ? null
322 : Math.min(periods.length - 1, Math.round(hoverFraction * (periods.length - 1)));
323
324 const positionTooltip = () => {
325 const plot = plotRef.current;
326 const tooltip = tooltipRef.current;
327 const hoverPosition = hoverPositionRef.current;
328 if (plot === null || tooltip === null || hoverPosition === null) return;
329
330 const gap = 12;
331 const tooltipWidth = tooltip.offsetWidth;
332 const tooltipHeight = tooltip.offsetHeight;
333 const plotWidth = plot.clientWidth;
334 const plotHeight = plot.clientHeight;
335 const preferredLeft =
336 hoverPosition.x + gap + tooltipWidth <= plotWidth
337 ? hoverPosition.x + gap
338 : hoverPosition.x - gap - tooltipWidth;
339 const preferredTop =
340 hoverPosition.y + gap + tooltipHeight <= plotHeight
341 ? hoverPosition.y + gap
342 : hoverPosition.y - gap - tooltipHeight;
343 const left = Math.min(Math.max(0, preferredLeft), Math.max(0, plotWidth - tooltipWidth));
344 const top = Math.min(Math.max(0, preferredTop), Math.max(0, plotHeight - tooltipHeight));
345 plot.style.setProperty("--usage-tooltip-left", `${left}px`);
346 plot.style.setProperty("--usage-tooltip-top", `${top}px`);
347 };
348
349 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- positions the hover tooltip through plot CSS variables before paint and on ResizeObserver
350 useLayoutEffect(() => {
351 if (hoverIndex === null) return;
352 positionTooltip();
353
354 const plot = plotRef.current;
355 const tooltip = tooltipRef.current;
356 if (plot === null || tooltip === null) return;
357
358 return observeResize([plot, tooltip], positionTooltip);
359 }, [hoverIndex, positionTooltip]);
360
361 const handleMove = (event: React.MouseEvent<HTMLDivElement>) => {
362 const plot = plotRef.current;
363 if (plot === null || periods.length === 0) return;
364 const bounds = plot.getBoundingClientRect();
365 if (bounds.width === 0) return;
366 const localX = Math.min(bounds.width, Math.max(0, event.clientX - bounds.left));
367 const localY = Math.min(bounds.height, Math.max(0, event.clientY - bounds.top));
368 hoverPositionRef.current = { x: localX, y: localY };
369 positionTooltip();
370 setHoverFraction(localX / bounds.width);
371 };
372
373 const hoveredPeriod = hoverIndex === null ? undefined : periods[hoverIndex];
374
375 return (
376 <div
377 ref={plotRef}
378 className="relative h-56 flex-1"
379 onMouseMove={handleMove}
380 onMouseLeave={() => {
381 hoverPositionRef.current = null;
382 setHoverFraction(null);
383 }}
384 >
385 <svg
386 className="h-full w-full"
387 viewBox={`0 0 ${VIEW_WIDTH} ${VIEW_HEIGHT}`}
388 preserveAspectRatio="none"
389 aria-hidden
390 >
391 {children}
392 {hoverIndex === null ? null : (
393 <line
394 x1={hoverIndex * stepX}
395 x2={hoverIndex * stepX}
396 y1={PLOT_TOP}
397 y2={VIEW_HEIGHT}
398 stroke="currentColor"
399 strokeWidth={1}
400 className="text-muted-foreground"
401 vectorEffect="non-scaling-stroke"
402 />
403 )}
404 </svg>
405
406 {hoverIndex === null || hoveredPeriod === undefined ? null : (
407 <UsageChartTooltip
408 tooltipRef={tooltipRef}
409 label={formatTooltipPeriod(hoveredPeriod)}
410 column={columns[hoverIndex]}
411 providers={providers}
412 loadingProviders={loadingProviders}
413 format={format}
414 />
415 )}
416 </div>
417 );
418}
419
420export function UsageProviderChart({
421 providers,
422 loadingProviders = NONE_LOADING,
423 days,
424 daily,
425 hours,
426 hourly,
427 metric,
428 referenceTime,
429 resolution,
430 timeZone,
431 hour12,
432}: UsageProviderChartProps) {
433 const gt = useGT();
434 const locale = useLocale();
435 const m = useMessages();
436 const periods = resolution === "hour" ? hours : days;
437 const totals: readonly (DailyTotals | HourlyTotals)[] = resolution === "hour" ? hourly : daily;
438 const byPeriod = new Map(
439 totals.map((entry) => ["hourStart" in entry ? entry.hourStart : entry.day, entry]),
440 );
441 const { columns, scale, paths, stepX } = buildChart(
442 periods,
443 byPeriod,
444 metric,
445 providers,
446 loadingProviders,
447 );
448
449 const toY = (value: number) => valueToY(value, scale.max);
450 const seriesClassName = (loading: boolean) =>
451 cn("transition-opacity", loading && "opacity-40 delay-150");
452 const format = metric === "tokens" ? formatTokens : (value: number) => formatUsd(value, locale);
453 const formatPeriod = (period: string) =>
454 resolution === "hour"
455 ? formatHourShort(period, timeZone, hour12, locale)
456 : formatDayShort(period, locale);
457 const formatTooltipPeriod = (period: string) =>
458 resolution === "hour" && referenceTime !== undefined
459 ? formatRelativeHourShort(period, referenceTime, timeZone, hour12, m, locale)
460 : formatPeriod(period);
461
462 return (
463 <div className="flex flex-col gap-1">
464 <div className="flex gap-2">
465 <div aria-hidden className="relative h-56 w-14 shrink-0">
466 {scale.labeled
467 ? scale.ticks.map((tick) => (
468 <span
469 key={tick}
470 className="absolute right-0 -translate-y-1/2 text-3xs text-muted-foreground tabular-nums"
471 style={{ top: `${(toY(tick) / VIEW_HEIGHT) * 100}%` }}
472 >
473 {tick === 0 ? "0" : format(tick)}
474 </span>
475 ))
476 : null}
477 </div>
478
479 <UsageChartPlot
480 periods={periods}
481 columns={columns}
482 stepX={stepX}
483 providers={providers}
484 loadingProviders={loadingProviders}
485 format={format}
486 formatTooltipPeriod={formatTooltipPeriod}
487 >
488 {scale.ticks.map((tick) => {
489 const y = toY(tick);
490 return (
491 <line
492 key={tick}
493 x1={0}
494 x2={VIEW_WIDTH}
495 y1={y}
496 y2={y}
497 stroke="currentColor"
498 strokeWidth={1}
499 className="text-border"
500 vectorEffect="non-scaling-stroke"
501 />
502 );
503 })}
504
505 {paths.map(({ provider, loading, area }) => (
506 <path
507 key={provider}
508 d={area}
509 className={seriesClassName(loading)}
510 fill={PROVIDER_PRESENTATION[provider].color}
511 fillOpacity={0.12}
512 />
513 ))}
514 {paths.map(({ provider, loading, line }) => (
515 <path
516 key={provider}
517 d={line}
518 className={seriesClassName(loading)}
519 fill="none"
520 stroke={PROVIDER_PRESENTATION[provider].color}
521 strokeWidth={2}
522 vectorEffect="non-scaling-stroke"
523 />
524 ))}
525 </UsageChartPlot>
526 </div>
527
528 <div
529 aria-hidden
530 className="flex justify-between pl-16 text-3xs text-muted-foreground uppercase"
531 >
532 <span>{periods[0] === undefined ? "" : formatPeriod(periods[0])}</span>
533 <span>
534 {periods[Math.floor(periods.length / 2)] === undefined
535 ? ""
536 : formatPeriod(periods[Math.floor(periods.length / 2)] ?? "")}
537 </span>
538 <span>
539 {periods[periods.length - 1] === undefined
540 ? ""
541 : formatPeriod(periods[periods.length - 1] ?? "")}
542 </span>
543 </div>
544
545 {/* The plot and its axes are hover-only; this carries the same figures for screen readers.
546 sr-only sits on a wrapper: Firefox does not clip a table's caption by the table's own box. */}
547 <div className="sr-only">
548 <table>
549 <caption>
550 {resolution === "hour"
551 ? metric === "tokens"
552 ? gt`Hourly processed tokens by provider`
553 : gt`Hourly cost by provider`
554 : metric === "tokens"
555 ? gt`Daily processed tokens by provider`
556 : gt`Daily cost by provider`}
557 </caption>
558 <thead>
559 <tr>
560 <th scope="col">{resolution === "hour" ? gt`Hour` : gt`Day`}</th>
561 {providers.map((provider) => (
562 <th key={provider} scope="col">
563 {PROVIDER_PRESENTATION[provider].label}
564 </th>
565 ))}
566 {providers.length > 1 ? (
567 <th scope="col">
568 <T>Total</T>
569 </th>
570 ) : null}
571 </tr>
572 </thead>
573 <tbody>
574 {periods.map((period, index) => {
575 const column = columns[index];
576 return (
577 <tr key={period}>
578 <th scope="row">{formatTooltipPeriod(period)}</th>
579 {providers.map((provider) => (
580 <td key={provider}>
581 {format(column?.bands.find((band) => band.provider === provider)?.value ?? 0)}
582 </td>
583 ))}
584 {providers.length > 1 ? <td>{format(column?.total ?? 0)}</td> : null}
585 </tr>
586 );
587 })}
588 </tbody>
589 </table>
590 </div>
591 </div>
592 );
593}