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