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