Open History to see the last commit
1import type { UsageProviderKind } from "@t3tools/contracts";
2import { useCallback, 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/**
72 * Monotone cubic tangents (Fritsch-Carlson).
73 *
74 * Plain cubic smoothing overshoots on spiky daily data and would dip the area
75 * below zero between points, which reads as negative spend. This variant is
76 * shape-preserving, so a smoothed series never leaves the range of its samples.
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
118/** One cubic segment of a smoothed boundary. */
119interface CurveSegment {
120 readonly from: Point;
121 readonly c1: Point;
122 readonly c2: Point;
123 readonly to: Point;
124}
125
126/** Smoothed polyline through `points`, as explicit cubic control points. */
127function smoothCurve(points: readonly Point[]): readonly CurveSegment[] {
128 if (points.length < 2) return [];
129 const tangents = monotoneTangents(points);
130 const segments: CurveSegment[] = [];
131
132 for (let index = 0; index < points.length - 1; index += 1) {
133 const from = points[index];
134 const to = points[index + 1];
135 if (from === undefined || to === undefined) continue;
136 const dx = to.x - from.x;
137 segments.push({
138 from,
139 c1: { x: from.x + dx / 3, y: from.y + ((tangents[index] ?? 0) * dx) / 3 },
140 c2: { x: to.x - dx / 3, y: to.y - ((tangents[index + 1] ?? 0) * dx) / 3 },
141 to,
142 });
143 }
144 return segments;
145}
146
147function curvePath(segments: readonly CurveSegment[], startCommand: "M" | "L"): string {
148 const first = segments[0];
149 if (first === undefined) return "";
150 let path = `${startCommand}${first.from.x.toFixed(2)},${first.from.y.toFixed(2)}`;
151 for (const segment of segments) {
152 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)}`;
153 }
154 return path;
155}
156
157/**
158 * Builds a scale whose maximum is a readable 1/2/5 x 10^n step at or above the
159 * peak.
160 *
161 * Rounding the maximum *up* is the point: stopping at the last step below the
162 * peak leaves the tallest day drawn past the top of the plot, where it is
163 * clipped.
164 */
165export function niceScale(peak: number, count: number): { max: number; ticks: readonly number[] } {
166 if (peak <= 0) return { max: 0, ticks: [0] };
167
168 const rawStep = peak / count;
169 const magnitude = 10 ** Math.floor(Math.log10(rawStep));
170 const normalized = rawStep / magnitude;
171 const step = (normalized > 5 ? 10 : normalized > 2 ? 5 : normalized > 1 ? 2 : 1) * magnitude;
172
173 const max = Math.ceil(peak / step) * step;
174 const ticks: number[] = [];
175 for (let value = 0; value <= max + step * 1e-6; value += step) ticks.push(value);
176 return { max, ticks };
177}
178
179/**
180 * Turns the merged daily totals into one column per day.
181 *
182 * Values are absolute, not cumulative: the series are layered from a shared
183 * zero baseline rather than stacked. A stacked chart puts whichever provider is
184 * drawn last permanently above the other, which reads as "that one is bigger"
185 * even on days where it is not.
186 *
187 * The chart paths and the hover readout both consume this, so the number under
188 * the cursor is by construction the number that was plotted rather than a
189 * second derivation that can drift from it.
190 */
191export function buildDayColumns(
192 days: readonly string[],
193 byDay: ReadonlyMap<string, DailyTotals>,
194 metric: UsageChartMetric,
195): readonly DayColumn[] {
196 return buildPeriodColumns(days, byDay, metric);
197}
198
199export function UsageProviderChart({
200 days,
201 daily,
202 hours,
203 hourly,
204 metric,
205 referenceTime,
206 resolution,
207 timeZone,
208}: UsageProviderChartProps) {
209 const periods = resolution === "hour" ? hours : days;
210 const byPeriod = useMemo(
211 () =>
212 resolution === "hour"
213 ? new Map(hourly.map((entry) => [entry.hourStart, entry]))
214 : new Map(daily.map((entry) => [entry.day, entry])),
215 [daily, hourly, resolution],
216 );
217 const [hoverIndex, setHoverIndex] = useState<number | null>(null);
218 const plotRef = useRef<HTMLDivElement | null>(null);
219
220 const { paths, ticks, stepX, toY, series } = useMemo(() => {
221 if (periods.length === 0) {
222 return {
223 paths: [],
224 ticks: [0] as readonly number[],
225 stepX: 0,
226 toY: () => VIEW_HEIGHT,
227 series: [] as readonly DayColumn[],
228 };
229 }
230
231 const columns = buildPeriodColumns(periods, byPeriod, metric);
232
233 // The scale tops out at the largest single provider-day, not the largest
234 // sum: layered series each measure from zero, so a combined peak would
235 // leave the plot permanently half empty.
236 const peak = columns.reduce(
237 (max, column) => column.bands.reduce((inner, band) => Math.max(inner, band.value), max),
238 0,
239 );
240 const { max, ticks: tickValues } = niceScale(peak, TICK_COUNT);
241 const step = periods.length === 1 ? 0 : VIEW_WIDTH / (periods.length - 1);
242 // Reserve a sliver above the top gridline so the series stroke, which is
243 // drawn at constant screen width, is not shaved off at a peak.
244 const toY = (value: number) =>
245 max === 0 ? VIEW_HEIGHT : VIEW_HEIGHT - (value / max) * (VIEW_HEIGHT - PLOT_TOP);
246
247 const built = PROVIDER_ORDER.map((provider, providerIndex) => {
248 const curve = smoothCurve(
249 columns.map((column, dayIndex) => ({
250 x: dayIndex * step,
251 y: toY(column.bands[providerIndex]?.value ?? 0),
252 })),
253 );
254 const line = curvePath(curve, "M");
255 return {
256 provider,
257 total: columns.reduce((sum, column) => sum + (column.bands[providerIndex]?.value ?? 0), 0),
258 area: line === "" ? "" : `${line} L${VIEW_WIDTH},${VIEW_HEIGHT} L0,${VIEW_HEIGHT} Z`,
259 line,
260 };
261 });
262
263 // Paint the heavier series first so the lighter one is never buried under
264 // it. The fills are faint enough that the order barely shows, but the
265 // strokes are drawn in a second pass regardless, so neither can be hidden.
266 const ordered = [...built].sort((a, b) => b.total - a.total);
267
268 return { paths: ordered, ticks: tickValues, stepX: step, toY, series: columns };
269 }, [byPeriod, metric, periods]);
270
271 const format = metric === "tokens" ? formatTokens : formatUsd;
272
273 const handleMove = useCallback(
274 (event: React.MouseEvent<HTMLDivElement>) => {
275 const bounds = plotRef.current?.getBoundingClientRect();
276 if (bounds === undefined || bounds.width === 0 || periods.length === 0) return;
277 const fraction = (event.clientX - bounds.left) / bounds.width;
278 const index = Math.round(fraction * (periods.length - 1));
279 setHoverIndex(Math.min(periods.length - 1, Math.max(0, index)));
280 },
281 [periods.length],
282 );
283
284 const hoveredPeriod = hoverIndex === null ? undefined : periods[hoverIndex];
285 const hoveredColumn = hoverIndex === null ? undefined : series[hoverIndex];
286 const hoverLeft = periods.length <= 1 ? 0 : ((hoverIndex ?? 0) / (periods.length - 1)) * 100;
287 const formatPeriod = (period: string) =>
288 resolution === "hour" ? formatHourShort(period, timeZone) : formatDayShort(period);
289 const formatTooltipPeriod = (period: string) =>
290 resolution === "hour" && referenceTime !== undefined
291 ? formatRelativeHourShort(period, referenceTime, timeZone)
292 : formatPeriod(period);
293
294 return (
295 <div className="flex flex-col gap-1">
296 <div className="flex gap-2">
297 {/* Axis labels sit outside the plot so they stay aligned to gridlines. */}
298 <div className="relative h-56 w-14 shrink-0">
299 {ticks.map((tick) => (
300 <span
301 key={tick}
302 className="absolute right-0 -translate-y-1/2 text-[10px] text-muted-foreground tabular-nums"
303 style={{ top: `${(toY(tick) / VIEW_HEIGHT) * 100}%` }}
304 >
305 {tick === 0 ? "0" : format(tick)}
306 </span>
307 ))}
308 </div>
309
310 <div
311 ref={plotRef}
312 className="relative h-56 flex-1"
313 onMouseMove={handleMove}
314 onMouseLeave={() => setHoverIndex(null)}
315 >
316 <svg
317 className="h-full w-full"
318 viewBox={`0 0 ${VIEW_WIDTH} ${VIEW_HEIGHT}`}
319 preserveAspectRatio="none"
320 role="img"
321 aria-label={`${resolution === "hour" ? "Hourly" : "Daily"} ${metric === "tokens" ? "processed tokens" : "cost"} by provider`}
322 >
323 {ticks.map((tick) => {
324 const y = toY(tick);
325 return (
326 <line
327 key={tick}
328 x1={0}
329 x2={VIEW_WIDTH}
330 y1={y}
331 y2={y}
332 stroke="currentColor"
333 strokeWidth={1}
334 className="text-border"
335 vectorEffect="non-scaling-stroke"
336 />
337 );
338 })}
339
340 {/* Fills first, then every stroke, so no series covers another's line. */}
341 {paths.map(({ provider, area }) => (
342 <path
343 key={provider}
344 d={area}
345 fill={PROVIDER_PRESENTATION[provider].color}
346 fillOpacity={0.12}
347 />
348 ))}
349 {paths.map(({ provider, line }) => (
350 <path
351 key={provider}
352 d={line}
353 fill="none"
354 stroke={PROVIDER_PRESENTATION[provider].color}
355 strokeWidth={2}
356 vectorEffect="non-scaling-stroke"
357 />
358 ))}
359
360 {hoverIndex === null ? null : (
361 <line
362 x1={hoverIndex * stepX}
363 x2={hoverIndex * stepX}
364 y1={PLOT_TOP}
365 y2={VIEW_HEIGHT}
366 stroke="currentColor"
367 strokeWidth={1}
368 className="text-muted-foreground"
369 vectorEffect="non-scaling-stroke"
370 />
371 )}
372 </svg>
373
374 {hoveredPeriod === undefined ? null : (
375 <div
376 className="pointer-events-none absolute top-0 z-10 min-w-36 border border-border bg-background/95 px-2 py-1.5 text-xs"
377 style={{
378 left: `${hoverLeft}%`,
379 transform: hoverLeft > 60 ? "translateX(-100%)" : "translateX(0)",
380 }}
381 >
382 <div className="mb-1 text-muted-foreground">{formatTooltipPeriod(hoveredPeriod)}</div>
383 {PROVIDER_ORDER.map((provider) => {
384 const { label, mark: Mark } = PROVIDER_PRESENTATION[provider];
385 return (
386 <div key={provider} className="flex items-center justify-between gap-3">
387 <span className="flex items-center gap-1.5 text-muted-foreground">
388 <Mark className="size-3 shrink-0" aria-hidden />
389 {label}
390 </span>
391 <span className="text-foreground tabular-nums">
392 {format(
393 hoveredColumn?.bands.find((band) => band.provider === provider)?.value ?? 0,
394 )}
395 </span>
396 </div>
397 );
398 })}
399 <div className="mt-1 flex items-center justify-between gap-3 border-t border-border pt-1">
400 <span className="text-muted-foreground">Total</span>
401 <span className="text-foreground tabular-nums">
402 {format(hoveredColumn?.total ?? 0)}
403 </span>
404 </div>
405 </div>
406 )}
407 </div>
408 </div>
409
410 <div className="flex justify-between pl-16 text-[10px] text-muted-foreground uppercase">
411 <span>{periods[0] === undefined ? "" : formatPeriod(periods[0])}</span>
412 <span>
413 {periods[Math.floor(periods.length / 2)] === undefined
414 ? ""
415 : formatPeriod(periods[Math.floor(periods.length / 2)] ?? "")}
416 </span>
417 <span>
418 {periods[periods.length - 1] === undefined
419 ? ""
420 : formatPeriod(periods[periods.length - 1] ?? "")}
421 </span>
422 </div>
423 </div>
424 );
425}
426
427export function UsageChartLegend() {
428 return (
429 <div className="flex items-center gap-4">
430 {PROVIDER_ORDER.map((provider) => {
431 // Brand marks keep monochrome providers identifiable even when their
432 // chart series use distinct colors.
433 const { label, mark: Mark } = PROVIDER_PRESENTATION[provider];
434 return (
435 <span key={provider} className="flex items-center gap-1.5 text-xs text-muted-foreground">
436 <Mark className="size-3.5 shrink-0" aria-hidden />
437 {label}
438 </span>
439 );
440 })}
441 </div>
442 );
443}