Open History to see the last commit
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}
37
38export interface DayColumn {
39 readonly bands: readonly {
40 readonly provider: UsageProviderKind;
41 readonly value: number;
42 }[];
43 readonly total: number;
44}
45
46interface Point {
47 readonly x: number;
48 readonly y: number;
49}
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;
59}
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 });
74}
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;
114}
115
116interface CurveSegment {
117 readonly from: Point;
118 readonly c1: Point;
119 readonly c2: Point;
120 readonly to: Point;
121}
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;
141}
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;
151}
152
153function areaPath(line: string) {
154 return line === "" ? "" : `${line} L${VIEW_WIDTH},${VIEW_HEIGHT} L0,${VIEW_HEIGHT} Z`;
155}
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 };
169}
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 };
186}
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);
192}
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) };
224}
225
226// Rebuilding the chart walks every period and provider; keep it cached across hover renders.
227function useChart(
228 periods: readonly string[],
229 totals: readonly DailyTotals[] | readonly HourlyTotals[],
230 metric: UsageChartMetric,
231 providers: readonly UsageProviderKind[],
232 loadingProviders: ReadonlySet<UsageProviderKind>,
233) {
234 "use memo";
235 const byPeriod = new Map<string, DailyTotals | HourlyTotals>(
236 totals.map((entry) => ["hourStart" in entry ? entry.hourStart : entry.day, entry]),
237 );
238 return buildChart(periods, byPeriod, metric, providers, loadingProviders);
239}
240
241export function UsageProviderChart({
242 providers,
243 loadingProviders = NONE_LOADING,
244 days,
245 daily,
246 hours,
247 hourly,
248 metric,
249 referenceTime,
250 resolution,
251 timeZone,
252}: UsageProviderChartProps) {
253 const periods = resolution === "hour" ? hours : days;
254 const { columns, scale, paths, stepX } = useChart(
255 periods,
256 resolution === "hour" ? hourly : daily,
257 metric,
258 providers,
259 loadingProviders,
260 );
261 const [hoverIndex, setHoverIndex] = useState<number | null>(null);
262 const plotRef = useRef<HTMLDivElement | null>(null);
263 const tooltipRef = useRef<HTMLDivElement | null>(null);
264 const hoverPositionRef = useRef<{ x: number; y: number } | null>(null);
265
266 const toY = (value: number) => valueToY(value, scale.max);
267 const seriesClassName = (loading: boolean) =>
268 cn("transition-opacity", loading && "opacity-40 delay-150");
269
270 const format = metric === "tokens" ? formatTokens : formatUsd;
271
272 const positionTooltip = () => {
273 const plot = plotRef.current;
274 const tooltip = tooltipRef.current;
275 const hoverPosition = hoverPositionRef.current;
276 if (plot === null || tooltip === null || hoverPosition === null) return;
277
278 const gap = 12;
279 const tooltipWidth = tooltip.offsetWidth;
280 const tooltipHeight = tooltip.offsetHeight;
281 const plotWidth = plot.clientWidth;
282 const plotHeight = plot.clientHeight;
283 const preferredLeft =
284 hoverPosition.x + gap + tooltipWidth <= plotWidth
285 ? hoverPosition.x + gap
286 : hoverPosition.x - gap - tooltipWidth;
287 const preferredTop =
288 hoverPosition.y + gap + tooltipHeight <= plotHeight
289 ? hoverPosition.y + gap
290 : hoverPosition.y - gap - tooltipHeight;
291 const left = Math.min(Math.max(0, preferredLeft), Math.max(0, plotWidth - tooltipWidth));
292 const top = Math.min(Math.max(0, preferredTop), Math.max(0, plotHeight - tooltipHeight));
293 plot.style.setProperty("--usage-tooltip-left", `${left}px`);
294 plot.style.setProperty("--usage-tooltip-top", `${top}px`);
295 };
296
297 useLayoutEffect(() => {
298 if (hoverIndex === null) return;
299 positionTooltip();
300
301 const plot = plotRef.current;
302 const tooltip = tooltipRef.current;
303 if (plot === null || tooltip === null) return;
304
305 return observeResize([plot, tooltip], positionTooltip);
306 }, [hoverIndex, positionTooltip]);
307
308 const handleMove = (event: React.MouseEvent<HTMLDivElement>) => {
309 const plot = plotRef.current;
310 if (plot === null || periods.length === 0) return;
311 const bounds = plot.getBoundingClientRect();
312 if (bounds.width === 0) return;
313 const localX = Math.min(bounds.width, Math.max(0, event.clientX - bounds.left));
314 const localY = Math.min(bounds.height, Math.max(0, event.clientY - bounds.top));
315 const fraction = localX / bounds.width;
316 const index = Math.round(fraction * (periods.length - 1));
317 hoverPositionRef.current = { x: localX, y: localY };
318 positionTooltip();
319 setHoverIndex(Math.min(periods.length - 1, Math.max(0, index)));
320 };
321
322 const hoveredPeriod = hoverIndex === null ? undefined : periods[hoverIndex];
323 const hoveredColumn = hoverIndex === null ? undefined : columns[hoverIndex];
324 const partial = providers.some((provider) => loadingProviders.has(provider));
325 const formatPeriod = (period: string) =>
326 resolution === "hour" ? formatHourShort(period, timeZone) : formatDayShort(period);
327 const formatTooltipPeriod = (period: string) =>
328 resolution === "hour" && referenceTime !== undefined
329 ? formatRelativeHourShort(period, referenceTime, timeZone)
330 : formatPeriod(period);
331
332 return (
333 <div className="flex flex-col gap-1">
334 <div className="flex gap-2">
335 <div className="relative h-56 w-14 shrink-0">
336 {scale.labeled
337 ? scale.ticks.map((tick) => (
338 <span
339 key={tick}
340 className="absolute right-0 -translate-y-1/2 text-3xs text-muted-foreground tabular-nums"
341 style={{ top: `${(toY(tick) / VIEW_HEIGHT) * 100}%` }}
342 >
343 {tick === 0 ? "0" : format(tick)}
344 </span>
345 ))
346 : null}
347 </div>
348
349 <div
350 ref={plotRef}
351 className="relative h-56 flex-1"
352 onMouseMove={handleMove}
353 onMouseLeave={() => {
354 hoverPositionRef.current = null;
355 setHoverIndex(null);
356 }}
357 >
358 <svg
359 className="h-full w-full"
360 viewBox={`0 0 ${VIEW_WIDTH} ${VIEW_HEIGHT}`}
361 preserveAspectRatio="none"
362 role="img"
363 aria-label={`${resolution === "hour" ? "Hourly" : "Daily"} ${metric === "tokens" ? "processed tokens" : "cost"} by provider`}
364 >
365 {scale.ticks.map((tick) => {
366 const y = toY(tick);
367 return (
368 <line
369 key={tick}
370 x1={0}
371 x2={VIEW_WIDTH}
372 y1={y}
373 y2={y}
374 stroke="currentColor"
375 strokeWidth={1}
376 className="text-border"
377 vectorEffect="non-scaling-stroke"
378 />
379 );
380 })}
381
382 {paths.map(({ provider, loading, area }) => (
383 <path
384 key={provider}
385 d={area}
386 className={seriesClassName(loading)}
387 fill={PROVIDER_PRESENTATION[provider].color}
388 fillOpacity={0.12}
389 />
390 ))}
391 {paths.map(({ provider, loading, line }) => (
392 <path
393 key={provider}
394 d={line}
395 className={seriesClassName(loading)}
396 fill="none"
397 stroke={PROVIDER_PRESENTATION[provider].color}
398 strokeWidth={2}
399 vectorEffect="non-scaling-stroke"
400 />
401 ))}
402
403 {hoverIndex === null ? null : (
404 <line
405 x1={hoverIndex * stepX}
406 x2={hoverIndex * stepX}
407 y1={PLOT_TOP}
408 y2={VIEW_HEIGHT}
409 stroke="currentColor"
410 strokeWidth={1}
411 className="text-muted-foreground"
412 vectorEffect="non-scaling-stroke"
413 />
414 )}
415 </svg>
416
417 {hoveredPeriod === undefined ? null : (
418 <div
419 ref={tooltipRef}
420 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"
421 style={{
422 left: "var(--usage-tooltip-left, 0px)",
423 top: "var(--usage-tooltip-top, 0px)",
424 }}
425 >
426 <div className="mb-1 text-muted-foreground">{formatTooltipPeriod(hoveredPeriod)}</div>
427 {providers.map((provider) => {
428 const { label, driverKind } = PROVIDER_PRESENTATION[provider];
429 return (
430 <div key={provider} className="flex items-center justify-between gap-3">
431 <span className="flex items-center gap-1.5 text-muted-foreground">
432 <ProviderInstanceIcon
433 driverKind={driverKind}
434 displayName={label}
435 iconClassName="size-3"
436 />
437 {label}
438 </span>
439 <span
440 className={cn(
441 "tabular-nums",
442 loadingProviders.has(provider)
443 ? "text-muted-foreground"
444 : "text-foreground",
445 )}
446 >
447 {format(
448 hoveredColumn?.bands.find((band) => band.provider === provider)?.value ?? 0,
449 )}
450 </span>
451 </div>
452 );
453 })}
454 <div className="mt-1 flex items-center justify-between gap-3 border-t border-border pt-1">
455 <span className="text-muted-foreground">Total</span>
456 <span
457 className={cn(
458 "tabular-nums",
459 partial ? "text-muted-foreground" : "text-foreground",
460 )}
461 >
462 {format(hoveredColumn?.total ?? 0)}
463 </span>
464 </div>
465 </div>
466 )}
467 </div>
468 </div>
469
470 <div className="flex justify-between pl-16 text-3xs text-muted-foreground uppercase">
471 <span>{periods[0] === undefined ? "" : formatPeriod(periods[0])}</span>
472 <span>
473 {periods[Math.floor(periods.length / 2)] === undefined
474 ? ""
475 : formatPeriod(periods[Math.floor(periods.length / 2)] ?? "")}
476 </span>
477 <span>
478 {periods[periods.length - 1] === undefined
479 ? ""
480 : formatPeriod(periods[periods.length - 1] ?? "")}
481 </span>
482 </div>
483 </div>
484 );
485}