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

UsageProviderChart.tsx

477 lines16.5 KB

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