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