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

UsageProviderChart.tsx

395 lines14.1 KB

1import type { UsageProviderKind } from "@t3tools/contracts";
2import { useCallback, useMemo, useRef, useState } from "react";
3​
4import type { DailyTotals } from "@t3tools/shared/usageMerge";
5import { formatDayShort, formatTokens, formatUsd } from "@t3tools/shared/usageFormat";
6import { PROVIDER_COLOR, PROVIDER_LABEL, PROVIDER_MARK, PROVIDER_ORDER } from "./usageProviders";
7​
8const VIEW_WIDTH = 960;
9const VIEW_HEIGHT = 260;
10const TICK_COUNT = 4;
11const PLOT_TOP = 8;
12​
13export type UsageChartMetric = "tokens" | "cost";
14​
15interface UsageProviderChartProps {
16 readonly days: readonly string[];
17 readonly daily: readonly DailyTotals[];
18 readonly metric: UsageChartMetric;
20​
21/** One day's per-provider values, shared by the paths and the hover readout. */
22export interface DayColumn {
23 readonly bands: readonly {
24 readonly provider: UsageProviderKind;
25 readonly value: number;
26 }[];
27 readonly total: number;
29​
30interface Point {
31 readonly x: number;
32 readonly y: number;
34​
35function valueFor(
36 daily: DailyTotals | undefined,
37 provider: UsageProviderKind,
38 metric: UsageChartMetric,
39): number {
40 const entry = daily?.byProvider.get(provider);
41 if (entry === undefined) return 0;
42 return metric === "tokens" ? entry.totalTokens : entry.costUsd;
44​
45/**
46 * Monotone cubic tangents (Fritsch-Carlson).
47 *
48 * Plain cubic smoothing overshoots on spiky daily data and would dip the area
49 * below zero between points, which reads as negative spend. This variant is
50 * shape-preserving, so a smoothed series never leaves the range of its samples.
51 */
52function monotoneTangents(points: readonly Point[]): readonly number[] {
53 const count = points.length;
54 if (count < 2) return [0];
55​
56 const slopes: number[] = [];
57 for (let index = 0; index < count - 1; index += 1) {
58 const dx = (points[index + 1]?.x ?? 0) - (points[index]?.x ?? 0);
59 const dy = (points[index + 1]?.y ?? 0) - (points[index]?.y ?? 0);
60 slopes.push(dx === 0 ? 0 : dy / dx);
61 }
62​
63 const tangents: number[] = Array.from({ length: count }, () => 0);
64 tangents[0] = slopes[0] ?? 0;
65 tangents[count - 1] = slopes[count - 2] ?? 0;
66 for (let index = 1; index < count - 1; index += 1) {
67 const previous = slopes[index - 1] ?? 0;
68 const next = slopes[index] ?? 0;
69 tangents[index] = previous * next <= 0 ? 0 : (previous + next) / 2;
70 }
71​
72 for (let index = 0; index < count - 1; index += 1) {
73 const slope = slopes[index] ?? 0;
74 if (slope === 0) {
75 tangents[index] = 0;
76 tangents[index + 1] = 0;
77 continue;
78 }
79 const a = (tangents[index] ?? 0) / slope;
80 const b = (tangents[index + 1] ?? 0) / slope;
81 const magnitude = a * a + b * b;
82 if (magnitude > 9) {
83 const scale = 3 / Math.sqrt(magnitude);
84 tangents[index] = scale * a * slope;
85 tangents[index + 1] = scale * b * slope;
86 }
87 }
88​
89 return tangents;
91​
92/** One cubic segment of a smoothed boundary. */
93interface CurveSegment {
94 readonly from: Point;
95 readonly c1: Point;
96 readonly c2: Point;
97 readonly to: Point;
99​
100/** Smoothed polyline through `points`, as explicit cubic control points. */
101function smoothCurve(points: readonly Point[]): readonly CurveSegment[] {
102 if (points.length < 2) return [];
103 const tangents = monotoneTangents(points);
104 const segments: CurveSegment[] = [];
105​
106 for (let index = 0; index < points.length - 1; index += 1) {
107 const from = points[index];
108 const to = points[index + 1];
109 if (from === undefined || to === undefined) continue;
110 const dx = to.x - from.x;
111 segments.push({
112 from,
113 c1: { x: from.x + dx / 3, y: from.y + ((tangents[index] ?? 0) * dx) / 3 },
114 c2: { x: to.x - dx / 3, y: to.y - ((tangents[index + 1] ?? 0) * dx) / 3 },
115 to,
116 });
117 }
118 return segments;
120​
121function curvePath(segments: readonly CurveSegment[], startCommand: "M" | "L"): string {
122 const first = segments[0];
123 if (first === undefined) return "";
124 let path = `${startCommand}${first.from.x.toFixed(2)},${first.from.y.toFixed(2)}`;
125 for (const segment of segments) {
126 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)}`;
127 }
128 return path;
130​
131/**
132 * Builds a scale whose maximum is a readable 1/2/5 x 10^n step at or above the
133 * peak.
134 *
135 * Rounding the maximum *up* is the point: stopping at the last step below the
136 * peak leaves the tallest day drawn past the top of the plot, where it is
137 * clipped.
138 */
139export function niceScale(peak: number, count: number): { max: number; ticks: readonly number[] } {
140 if (peak <= 0) return { max: 0, ticks: [0] };
141​
142 const rawStep = peak / count;
143 const magnitude = 10 ** Math.floor(Math.log10(rawStep));
144 const normalized = rawStep / magnitude;
145 const step = (normalized > 5 ? 10 : normalized > 2 ? 5 : normalized > 1 ? 2 : 1) * magnitude;
146​
147 const max = Math.ceil(peak / step) * step;
148 const ticks: number[] = [];
149 for (let value = 0; value <= max + step * 1e-6; value += step) ticks.push(value);
150 return { max, ticks };
152​
153/**
154 * Turns the merged daily totals into one column per day.
155 *
156 * Values are absolute, not cumulative: the series are layered from a shared
157 * zero baseline rather than stacked. A stacked chart puts whichever provider is
158 * drawn last permanently above the other, which reads as "that one is bigger"
159 * even on days where it is not.
160 *
161 * The chart paths and the hover readout both consume this, so the number under
162 * the cursor is by construction the number that was plotted rather than a
163 * second derivation that can drift from it.
164 */
165export function buildDayColumns(
166 days: readonly string[],
167 byDay: ReadonlyMap<string, DailyTotals>,
168 metric: UsageChartMetric,
169): readonly DayColumn[] {
170 return days.map((day) => {
171 const entry = byDay.get(day);
172 const bands = PROVIDER_ORDER.map((provider) => ({
173 provider,
174 value: valueFor(entry, provider, metric),
175 }));
176 return { bands, total: bands.reduce((sum, band) => sum + band.value, 0) };
177 });
179​
180export function UsageProviderChart({ days, daily, metric }: UsageProviderChartProps) {
181 const byDay = useMemo(() => new Map(daily.map((entry) => [entry.day, entry])), [daily]);
182 const [hoverIndex, setHoverIndex] = useState<number | null>(null);
183 const plotRef = useRef<HTMLDivElement | null>(null);
184​
185 const { paths, ticks, stepX, toY, series } = useMemo(() => {
186 if (days.length === 0) {
187 return {
188 paths: [],
189 ticks: [0] as readonly number[],
190 stepX: 0,
191 toY: () => VIEW_HEIGHT,
192 series: [] as readonly DayColumn[],
193 };
194 }
195​
196 const columns = buildDayColumns(days, byDay, metric);
197​
198 // The scale tops out at the largest single provider-day, not the largest
199 // sum: layered series each measure from zero, so a combined peak would
200 // leave the plot permanently half empty.
201 const peak = columns.reduce(
202 (max, column) => column.bands.reduce((inner, band) => Math.max(inner, band.value), max),
203 0,
204 );
205 const { max, ticks: tickValues } = niceScale(peak, TICK_COUNT);
206 const step = days.length === 1 ? 0 : VIEW_WIDTH / (days.length - 1);
207 // Reserve a sliver above the top gridline so the series stroke, which is
208 // drawn at constant screen width, is not shaved off at a peak.
209 const toY = (value: number) =>
210 max === 0 ? VIEW_HEIGHT : VIEW_HEIGHT - (value / max) * (VIEW_HEIGHT - PLOT_TOP);
211​
212 const built = PROVIDER_ORDER.map((provider, providerIndex) => {
213 const curve = smoothCurve(
214 columns.map((column, dayIndex) => ({
215 x: dayIndex * step,
216 y: toY(column.bands[providerIndex]?.value ?? 0),
217 })),
218 );
219 const line = curvePath(curve, "M");
220 return {
221 provider,
222 total: columns.reduce((sum, column) => sum + (column.bands[providerIndex]?.value ?? 0), 0),
223 area: line === "" ? "" : `${line} L${VIEW_WIDTH},${VIEW_HEIGHT} L0,${VIEW_HEIGHT} Z`,
224 line,
225 };
226 });
227​
228 // Paint the heavier series first so the lighter one is never buried under
229 // it. The fills are faint enough that the order barely shows, but the
230 // strokes are drawn in a second pass regardless, so neither can be hidden.
231 const ordered = [...built].sort((a, b) => b.total - a.total);
232​
233 return { paths: ordered, ticks: tickValues, stepX: step, toY, series: columns };
234 }, [byDay, days, metric]);
235​
236 const format = metric === "tokens" ? formatTokens : formatUsd;
237​
238 const handleMove = useCallback(
239 (event: React.MouseEvent<HTMLDivElement>) => {
240 const bounds = plotRef.current?.getBoundingClientRect();
241 if (bounds === undefined || bounds.width === 0 || days.length === 0) return;
242 const fraction = (event.clientX - bounds.left) / bounds.width;
243 const index = Math.round(fraction * (days.length - 1));
244 setHoverIndex(Math.min(days.length - 1, Math.max(0, index)));
245 },
246 [days.length],
247 );
248​
249 const hoveredDay = hoverIndex === null ? undefined : days[hoverIndex];
250 const hoveredColumn = hoverIndex === null ? undefined : series[hoverIndex];
251 const hoverLeft = days.length <= 1 ? 0 : ((hoverIndex ?? 0) / (days.length - 1)) * 100;
252​
253 return (
254 <div className="flex flex-col gap-1">
255 <div className="flex gap-2">
256 {/* Axis labels sit outside the plot so they stay aligned to gridlines. */}
257 <div className="relative h-56 w-14 shrink-0">
258 {ticks.map((tick) => (
259 <span
260 key={tick}
261 className="absolute right-0 -translate-y-1/2 text-[10px] text-muted-foreground tabular-nums"
262 style={{ top: `${(toY(tick) / VIEW_HEIGHT) * 100}%` }}
263 >
264 {tick === 0 ? "0" : format(tick)}
265 </span>
266 ))}
267 </div>
268​
269 <div
270 ref={plotRef}
271 className="relative h-56 flex-1"
272 onMouseMove={handleMove}
273 onMouseLeave={() => setHoverIndex(null)}
274 >
275 <svg
276 className="h-full w-full"
277 viewBox={`0 0 ${VIEW_WIDTH} ${VIEW_HEIGHT}`}
278 preserveAspectRatio="none"
279 role="img"
280 aria-label={`Daily ${metric === "tokens" ? "processed tokens" : "cost"} by provider`}
281 >
282 {ticks.map((tick) => {
283 const y = toY(tick);
284 return (
285 <line
286 key={tick}
287 x1={0}
288 x2={VIEW_WIDTH}
289 y1={y}
290 y2={y}
291 stroke="currentColor"
292 strokeWidth={1}
293 className="text-border"
294 vectorEffect="non-scaling-stroke"
295 />
296 );
297 })}
298​
299 {/* Fills first, then every stroke, so no series covers another's line. */}
300 {paths.map(({ provider, area }) => (
301 <path key={provider} d={area} fill={PROVIDER_COLOR[provider]} fillOpacity={0.12} />
302 ))}
303 {paths.map(({ provider, line }) => (
304 <path
305 key={provider}
306 d={line}
307 fill="none"
308 stroke={PROVIDER_COLOR[provider]}
309 strokeWidth={2}
310 vectorEffect="non-scaling-stroke"
311 />
312 ))}
313​
314 {hoverIndex === null ? null : (
315 <line
316 x1={hoverIndex * stepX}
317 x2={hoverIndex * stepX}
318 y1={PLOT_TOP}
319 y2={VIEW_HEIGHT}
320 stroke="currentColor"
321 strokeWidth={1}
322 className="text-muted-foreground"
323 vectorEffect="non-scaling-stroke"
324 />
325 )}
326 </svg>
327​
328 {hoveredDay === undefined ? null : (
329 <div
330 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"
331 style={{
332 left: `${hoverLeft}%`,
333 transform: hoverLeft > 60 ? "translateX(-100%)" : "translateX(0)",
334 }}
335 >
336 <div className="mb-1 text-muted-foreground">{formatDayShort(hoveredDay)}</div>
337 {PROVIDER_ORDER.map((provider) => {
338 const Mark = PROVIDER_MARK[provider];
339 return (
340 <div key={provider} className="flex items-center justify-between gap-3">
341 <span className="flex items-center gap-1.5 text-muted-foreground">
342 <Mark className="size-3 shrink-0" aria-hidden />
343 {PROVIDER_LABEL[provider]}
344 </span>
345 <span className="text-foreground tabular-nums">
346 {format(
347 hoveredColumn?.bands.find((band) => band.provider === provider)?.value ?? 0,
348 )}
349 </span>
350 </div>
351 );
352 })}
353 <div className="mt-1 flex items-center justify-between gap-3 border-t border-border pt-1">
354 <span className="text-muted-foreground">Total</span>
355 <span className="text-foreground tabular-nums">
356 {format(hoveredColumn?.total ?? 0)}
357 </span>
358 </div>
359 </div>
360 )}
361 </div>
362 </div>
363​
364 <div className="flex justify-between pl-16 text-[10px] text-muted-foreground uppercase">
365 <span>{days[0] === undefined ? "" : formatDayShort(days[0])}</span>
366 <span>
367 {days[Math.floor(days.length / 2)] === undefined
368 ? ""
369 : formatDayShort(days[Math.floor(days.length / 2)] ?? "")}
370 </span>
371 <span>
372 {days[days.length - 1] === undefined ? "" : formatDayShort(days[days.length - 1] ?? "")}
373 </span>
374 </div>
375 </div>
376 );
378​
379export function UsageChartLegend() {
380 return (
381 <div className="flex items-center gap-4">
382 {PROVIDER_ORDER.map((provider) => {
383 // The marks carry the same fills as the bands, so they key the chart
384 // just as a colour swatch would.
385 const Mark = PROVIDER_MARK[provider];
386 return (
387 <span key={provider} className="flex items-center gap-1.5 text-xs text-muted-foreground">
388 <Mark className="size-3.5 shrink-0" aria-hidden />
389 {PROVIDER_LABEL[provider]}
390 </span>
391 );
392 })}
393 </div>
394 );