Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

UsageProviderChart.tsx

452 lines15.6 KB

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;
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;
41​
42interface Point {
43 readonly x: number;
44 readonly y: number;
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;
56​
57export function 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 });
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;
112​
113interface CurveSegment {
114 readonly from: Point;
115 readonly c1: Point;
116 readonly c2: Point;
117 readonly to: Point;
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;
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;
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 };
171​
172export function UsageProviderChart({
173 providers,
174 days,
175 daily,
176 hours,
177 hourly,
178 metric,
179 referenceTime,
180 resolution,
181 timeZone,
182}: UsageProviderChartProps) {
183 const periods = resolution === "hour" ? hours : days;
184 const byPeriod = useMemo(
185 () =>
186 resolution === "hour"
187 ? new Map(hourly.map((entry) => [entry.hourStart, entry]))
188 : new Map(daily.map((entry) => [entry.day, entry])),
189 [daily, hourly, resolution],
190 );
191 const [hoverIndex, setHoverIndex] = useState<number | null>(null);
192 const plotRef = useRef<HTMLDivElement | null>(null);
193 const tooltipRef = useRef<HTMLDivElement | null>(null);
194 const hoverPositionRef = useRef<{ x: number; y: number } | null>(null);
195​
196 const { paths, ticks, stepX, toY, series } = useMemo(() => {
197 if (periods.length === 0) {
198 return {
199 paths: [],
200 series: [] as readonly DayColumn[],
201 stepX: 0,
202 ticks: [0] as readonly number[],
203 toY: () => VIEW_HEIGHT,
204 };
205 }
206​
207 const columns = buildPeriodColumns(periods, byPeriod, metric);
208 // The scale tops out at the largest single provider-period, not the sum:
209 // layered series each measure from zero, so a combined peak would leave
210 // the plot permanently half empty.
211 const peak = columns.reduce(
212 (max, column) => column.bands.reduce((inner, band) => Math.max(inner, band.value), max),
213 0,
214 );
215 const { max, ticks: tickValues } = niceScale(peak, TICK_COUNT);
216 const step = periods.length === 1 ? 0 : VIEW_WIDTH / (periods.length - 1);
217 // Leave room above the top gridline so the constant-width stroke is not
218 // clipped when a series reaches the peak.
219 const toY = (value: number) =>
220 max === 0 ? VIEW_HEIGHT : VIEW_HEIGHT - (value / max) * (VIEW_HEIGHT - PLOT_TOP);
221​
222 const built = providers.map((provider) => {
223 const providerIndex = PROVIDER_ORDER.indexOf(provider);
224 const line = curvePath(
225 smoothCurve(
226 columns.map((column, periodIndex) => ({
227 x: periodIndex * step,
228 y: toY(column.bands[providerIndex]?.value ?? 0),
229 })),
230 ),
231 );
232 return {
233 provider,
234 total: columns.reduce((sum, column) => sum + (column.bands[providerIndex]?.value ?? 0), 0),
235 area: line === "" ? "" : `${line} L${VIEW_WIDTH},${VIEW_HEIGHT} L0,${VIEW_HEIGHT} Z`,
236 line,
237 };
238 });
239​
240 // Paint the heavier series first so the lighter one is not buried.
241 return {
242 paths: built.toSorted((a, b) => b.total - a.total),
243 series: columns,
244 stepX: step,
245 ticks: tickValues,
246 toY,
247 };
248 }, [byPeriod, metric, periods, providers]);
249​
250 const format = metric === "tokens" ? formatTokens : formatUsd;
251​
252 const positionTooltip = useCallback(() => {
253 const plot = plotRef.current;
254 const tooltip = tooltipRef.current;
255 const hoverPosition = hoverPositionRef.current;
256 if (plot === null || tooltip === null || hoverPosition === null) return;
257​
258 const gap = 12;
259 const tooltipWidth = tooltip.offsetWidth;
260 const tooltipHeight = tooltip.offsetHeight;
261 const plotWidth = plot.clientWidth;
262 const plotHeight = plot.clientHeight;
263 const preferredLeft =
264 hoverPosition.x + gap + tooltipWidth <= plotWidth
265 ? hoverPosition.x + gap
266 : hoverPosition.x - gap - tooltipWidth;
267 const preferredTop =
268 hoverPosition.y + gap + tooltipHeight <= plotHeight
269 ? hoverPosition.y + gap
270 : hoverPosition.y - gap - tooltipHeight;
271 const left = Math.min(Math.max(0, preferredLeft), Math.max(0, plotWidth - tooltipWidth));
272 const top = Math.min(Math.max(0, preferredTop), Math.max(0, plotHeight - tooltipHeight));
273 plot.style.setProperty("--usage-tooltip-left", `${left}px`);
274 plot.style.setProperty("--usage-tooltip-top", `${top}px`);
275 }, []);
276​
277 useLayoutEffect(() => {
278 if (hoverIndex === null) return;
279 positionTooltip();
280​
281 const plot = plotRef.current;
282 const tooltip = tooltipRef.current;
283 if (plot === null || tooltip === null || typeof ResizeObserver === "undefined") return;
284​
285 const observer = new ResizeObserver(positionTooltip);
286 observer.observe(plot);
287 observer.observe(tooltip);
288 return () => observer.disconnect();
289 }, [hoverIndex, positionTooltip]);
290​
291 const handleMove = useCallback(
292 (event: React.MouseEvent<HTMLDivElement>) => {
293 const plot = plotRef.current;
294 if (plot === null || periods.length === 0) return;
295 const bounds = plot.getBoundingClientRect();
296 if (bounds.width === 0) return;
297 const localX = Math.min(bounds.width, Math.max(0, event.clientX - bounds.left));
298 const localY = Math.min(bounds.height, Math.max(0, event.clientY - bounds.top));
299 const fraction = localX / bounds.width;
300 const index = Math.round(fraction * (periods.length - 1));
301 hoverPositionRef.current = { x: localX, y: localY };
302 positionTooltip();
303 setHoverIndex(Math.min(periods.length - 1, Math.max(0, index)));
304 },
305 [periods.length, positionTooltip],
306 );
307​
308 const hoveredPeriod = hoverIndex === null ? undefined : periods[hoverIndex];
309 const hoveredColumn = hoverIndex === null ? undefined : series[hoverIndex];
310 const formatPeriod = (period: string) =>
311 resolution === "hour" ? formatHourShort(period, timeZone) : formatDayShort(period);
312 const formatTooltipPeriod = (period: string) =>
313 resolution === "hour" && referenceTime !== undefined
314 ? formatRelativeHourShort(period, referenceTime, timeZone)
315 : formatPeriod(period);
316​
317 return (
318 <div className="flex flex-col gap-1">
319 <div className="flex gap-2">
320 {/* Axis labels sit outside the plot so they stay aligned to gridlines. */}
321 <div className="relative h-56 w-14 shrink-0">
322 {ticks.map((tick) => (
323 <span
324 key={tick}
325 className="absolute right-0 -translate-y-1/2 text-3xs text-muted-foreground tabular-nums"
326 style={{ top: `${(toY(tick) / VIEW_HEIGHT) * 100}%` }}
327 >
328 {tick === 0 ? "0" : format(tick)}
329 </span>
330 ))}
331 </div>
332​
333 <div
334 ref={plotRef}
335 className="relative h-56 flex-1"
336 onMouseMove={handleMove}
337 onMouseLeave={() => {
338 hoverPositionRef.current = null;
339 setHoverIndex(null);
340 }}
341 >
342 <svg
343 className="h-full w-full"
344 viewBox={`0 0 ${VIEW_WIDTH} ${VIEW_HEIGHT}`}
345 preserveAspectRatio="none"
346 role="img"
347 aria-label={`${resolution === "hour" ? "Hourly" : "Daily"} ${metric === "tokens" ? "processed tokens" : "cost"} by provider`}
348 >
349 {ticks.map((tick) => {
350 const y = toY(tick);
351 return (
352 <line
353 key={tick}
354 x1={0}
355 x2={VIEW_WIDTH}
356 y1={y}
357 y2={y}
358 stroke="currentColor"
359 strokeWidth={1}
360 className="text-border"
361 vectorEffect="non-scaling-stroke"
362 />
363 );
364 })}
365​
366 {/* Fills first, then every stroke, so no series covers another's line. */}
367 {paths.map(({ provider, area }) => (
368 <path
369 key={provider}
370 d={area}
371 fill={PROVIDER_PRESENTATION[provider].color}
372 fillOpacity={0.12}
373 />
374 ))}
375 {paths.map(({ provider, line }) => (
376 <path
377 key={provider}
378 d={line}
379 fill="none"
380 stroke={PROVIDER_PRESENTATION[provider].color}
381 strokeWidth={2}
382 vectorEffect="non-scaling-stroke"
383 />
384 ))}
385​
386 {hoverIndex === null ? null : (
387 <line
388 x1={hoverIndex * stepX}
389 x2={hoverIndex * stepX}
390 y1={PLOT_TOP}
391 y2={VIEW_HEIGHT}
392 stroke="currentColor"
393 strokeWidth={1}
394 className="text-muted-foreground"
395 vectorEffect="non-scaling-stroke"
396 />
397 )}
398 </svg>
399​
400 {hoveredPeriod === undefined ? null : (
401 <div
402 ref={tooltipRef}
403 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"
404 style={{
405 left: "var(--usage-tooltip-left, 0px)",
406 top: "var(--usage-tooltip-top, 0px)",
407 }}
408 >
409 <div className="mb-1 text-muted-foreground">{formatTooltipPeriod(hoveredPeriod)}</div>
410 {providers.map((provider) => {
411 const { label, mark: Mark } = PROVIDER_PRESENTATION[provider];
412 return (
413 <div key={provider} className="flex items-center justify-between gap-3">
414 <span className="flex items-center gap-1.5 text-muted-foreground">
415 <Mark className="size-3 shrink-0" aria-hidden />
416 {label}
417 </span>
418 <span className="text-foreground tabular-nums">
419 {format(
420 hoveredColumn?.bands.find((band) => band.provider === provider)?.value ?? 0,
421 )}
422 </span>
423 </div>
424 );
425 })}
426 <div className="mt-1 flex items-center justify-between gap-3 border-t border-border pt-1">
427 <span className="text-muted-foreground">Total</span>
428 <span className="text-foreground tabular-nums">
429 {format(hoveredColumn?.total ?? 0)}
430 </span>
431 </div>
432 </div>
433 )}
434 </div>
435 </div>
436​
437 <div className="flex justify-between pl-16 text-3xs text-muted-foreground uppercase">
438 <span>{periods[0] === undefined ? "" : formatPeriod(periods[0])}</span>
439 <span>
440 {periods[Math.floor(periods.length / 2)] === undefined
441 ? ""
442 : formatPeriod(periods[Math.floor(periods.length / 2)] ?? "")}
443 </span>
444 <span>
445 {periods[periods.length - 1] === undefined
446 ? ""
447 : formatPeriod(periods[periods.length - 1] ?? "")}
448 </span>
449 </div>
450 </div>
451 );