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

UsageLimits.tsx

394 lines14.1 KB

1import {
2 AuthProvidersManageScope,
3 type EnvironmentId,
4 type ProviderConsumeResetCreditOutcome,
5 ProviderConsumeResetCreditInput,
6 ServerProvider,
7 ServerProviderResetCredits,
8 ServerProviderUsageWindow,
9 UsageProviderKind,
10} from "@t3tools/contracts";
11import { useAtomValue } from "@effect/atom-react";
12import { normalizeProviderAccentColor } from "@t3tools/client-runtime/state/provider-instance-display";
13import {
14 formatResetsIn,
15 type LimitPace,
16 paceOf,
17 paceRemainingPercent,
18 remainingPercent,
19 type ResetCreditChoice,
20 resetCreditChoices,
21} from "@t3tools/shared/usageLimits";
22import { GaugeIcon, TrendingDownIcon, TrendingUpIcon } from "lucide-react";
23import { Fragment, useLayoutEffect, useState } from "react";
24​
25import { usePrimarySettings } from "../../hooks/useSettings";
26import { observeResize } from "../../lib/observeResize";
27import { environmentPresentations } from "../../state/presentation";
28import { useEnvironmentScope, readEnvironmentScope } from "../../state/session";
29import { serverEnvironment } from "../../state/server";
30import { useAtomCommand } from "../../state/use-atom-command";
31import { formatUpcomingTimestamp } from "../../timestampFormat";
32import {
33 AlertDialog,
34 AlertDialogClose,
35 AlertDialogDescription,
36 AlertDialogFooter,
37 AlertDialogHeader,
38 AlertDialogPopup,
39 AlertDialogTitle,
40} from "../ui/alert-dialog";
41import { Button } from "../ui/button";
42import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
43import { UsageLimitsPooled } from "./UsageLimitsPooled";
44import { PROVIDER_PRESENTATION } from "./usageProviders";
45​
46const PACE: Record<LimitPace, { readonly label: string; readonly icon: typeof GaugeIcon }> = {
47 ahead: { label: "Ahead of pace: spending faster than the window elapses", icon: TrendingUpIcon },
48 on: { label: "On pace with the window", icon: GaugeIcon },
49 under: { label: "Under pace: headroom left for the rest of the window", icon: TrendingDownIcon },
50};
51​
52export function barColor(driver: ServerProvider["driver"]): string {
53 const presentation = Object.values(PROVIDER_PRESENTATION).find(
54 (entry) => entry.driverKind === driver,
55 );
56 return presentation?.color ?? "var(--foreground)";
58​
59export function PaceIcon({ pace }: { readonly pace: LimitPace }) {
60 const Icon = PACE[pace].icon;
61 return (
62 <Tooltip>
63 <TooltipTrigger
64 render={
65 <span
66 role="img"
67 aria-label={PACE[pace].label}
68 className="inline-flex text-muted-foreground"
69 />
70 }
71 >
72 <Icon className="size-3.5" aria-hidden />
73 </TooltipTrigger>
74 <TooltipPopup side="top">{PACE[pace].label}</TooltipPopup>
75 </Tooltip>
76 );
78​
79// The tick sits in a transparent gap cut from the bar, clamped so it stays inside at 0% and 100%.
80// The gap is a clip-path slot rather than a mask: a mask composites its layer and re-antialiases
81// the bar's rounded ends, and the polygon reaches 1px past the box so only the slot edges clip.
82function paceMarkStyles(timeLeft: number | null) {
83 if (timeLeft === null) return null;
84 const at = `clamp(3px, ${timeLeft}%, calc(100% - 3px))`;
85 const [left, right] = [`calc(${at} - 3px)`, `calc(${at} + 3px)`];
86 const [near, far] = ["-1px", "calc(100% + 1px)"];
87 return {
88 tick: { left: at },
89 gap: {
90 clipPath: `polygon(${near} ${near}, ${left} ${near}, ${left} ${far}, ${right} ${far}, ${right} ${near}, ${far} ${near}, ${far} ${far}, ${near} ${far})`,
91 },
92 // For a track painted on an element that also draws focus rings, which a clip would cut.
93 gappedTrack: {
94 backgroundColor: "transparent",
95 backgroundImage: `linear-gradient(to right, var(--color-muted) ${left}, transparent ${left}, transparent ${right}, var(--color-muted) ${right})`,
96 },
97 };
99​
100/**
101 * Pace mark styles for the bar given the returned ref. Below 6px there is no room for the gap
102 * and tick, so the bar draws neither, as the mobile bars do.
103 */
104export function usePaceMark(timeLeft: number | null) {
105 const [bar, setBar] = useState<HTMLElement | null>(null);
106 const [roomy, setRoomy] = useState(false);
107 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- measures the bar DOM width before paint and remeasures through a ResizeObserver
108 useLayoutEffect(() => {
109 if (!bar) return;
110 const measure = () => setRoomy(bar.getBoundingClientRect().width >= 6);
111 measure();
112 return observeResize(bar, measure);
113 }, [bar]);
114 return [setBar, roomy ? paceMarkStyles(timeLeft) : null] as const;
116​
117function WindowBar({
118 color,
119 window,
120 now,
121}: {
122 readonly color: string;
123 readonly window: ServerProviderUsageWindow;
124 readonly now: number;
125}) {
126 const timestampFormat = usePrimarySettings((settings) => settings.timestampFormat);
127 const remaining = remainingPercent(window);
128 const timeLeft = paceRemainingPercent(window, now);
129 const [barRef, paceMark] = usePaceMark(timeLeft);
130 const resetsIn = formatResetsIn(window, now);
131 const resetsAt = window.resetsAt
132 ? formatUpcomingTimestamp(window.resetsAt, timestampFormat, now)
133 : null;
134 const summary = `${window.label}: ${remaining}% left${
135 timeLeft === null ? "" : `, ${timeLeft}% of the window left`
136 }${resetsIn ? `, ${resetsIn}` : ""}`;
137​
138 return (
139 <Tooltip>
140 <TooltipTrigger
141 render={
142 <div
143 ref={barRef}
144 role="img"
145 aria-label={summary}
146 tabIndex={0}
147 className="relative h-6 cursor-default rounded-full outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background"
148 />
149 }
150 >
151 {/* Clip both layers so the gap exposes even a translucent composer surface. */}
152 <div className="absolute inset-0" style={paceMark?.gap}>
153 <div className="absolute inset-x-0 inset-y-1.5 rounded-full bg-muted" />
154 {remaining > 0 ? (
155 <div
156 className="absolute inset-y-1.5 left-0 rounded-full"
157 style={{ width: `${remaining}%`, backgroundColor: color }}
158 />
159 ) : null}
160 </div>
161 {paceMark ? (
162 <span
163 aria-hidden
164 className="absolute inset-y-1 w-0.5 -translate-x-1/2 rounded-full bg-foreground"
165 style={paceMark.tick}
166 />
167 ) : null}
168 </TooltipTrigger>
169 <TooltipPopup side="top">
170 <div className="flex flex-col gap-0.5">
171 <span className="text-foreground">
172 {remaining}% left{timeLeft !== null ? ` · ${timeLeft}% of the window left` : ""}
173 </span>
174 {timeLeft !== null ? (
175 <span className="text-muted-foreground">The line is where even spending would be.</span>
176 ) : null}
177 {resetsAt ? (
178 <span className="text-muted-foreground">
179 Resets {resetsAt}
180 {resetsIn ? ` · ${resetsIn}` : ""}
181 </span>
182 ) : null}
183 </div>
184 </TooltipPopup>
185 </Tooltip>
186 );
188​
189export function LimitWindows({
190 driver,
191 accentColor,
192 windows,
193 now,
194 compact = false,
195}: {
196 readonly driver: ServerProvider["driver"];
197 readonly accentColor?: string | undefined;
198 readonly windows: ReadonlyArray<ServerProviderUsageWindow>;
199 readonly now: number;
200 readonly compact?: boolean;
201}) {
202 const color = normalizeProviderAccentColor(accentColor) ?? barColor(driver);
203 return (
204 <div
205 className={
206 compact
207 ? "grid grid-cols-[minmax(0,9rem)_minmax(3rem,1fr)_auto] gap-x-3 gap-y-0.5"
208 : "grid grid-cols-[11rem_minmax(0,1fr)_7rem] gap-x-4 gap-y-1"
209 }
210 >
211 {windows.map((window) => {
212 const pace = paceOf(window, now);
213 const resetsIn = formatResetsIn(window, now);
214 return (
215 <Fragment key={window.id}>
216 <span className="flex min-w-0 items-center gap-2 text-xs">
217 <span className="truncate text-muted-foreground">{window.label}</span>
218 <span className="ms-auto shrink-0 font-medium text-foreground tabular-nums">
219 {remainingPercent(window)}% left
220 </span>
221 </span>
222 <WindowBar color={color} window={window} now={now} />
223 <span className="flex items-center gap-2 text-xs whitespace-nowrap text-muted-foreground tabular-nums">
224 {pace ? <PaceIcon pace={pace} /> : null}
225 <span className="ms-auto shrink-0">{resetsIn ?? ""}</span>
226 </span>
227 </Fragment>
228 );
229 })}
230 </div>
231 );
233​
234const OUTCOME_TEXT: Record<ProviderConsumeResetCreditOutcome, string> = {
235 reset: "Reset applied. Your windows have cleared.",
236 nothingToReset: "Nothing to reset right now.",
237 noCredit: "No reset credit left.",
238 alreadyRedeemed: "That credit was already redeemed.",
239};
240​
241export function useResetCredit(environmentId: EnvironmentId) {
242 const canManageProviders = useEnvironmentScope(environmentId, AuthProvidersManageScope);
243 const consume = useAtomCommand(serverEnvironment.consumeResetCredit, { reportFailure: false });
244 // Kept after close so the dialog's text survives its exit animation.
245 const [choice, setChoice] = useState<ResetCreditChoice | null>(null);
246 const [confirming, setConfirming] = useState(false);
247 const [busy, setBusy] = useState(false);
248 const [status, setStatus] = useState<string | null>(null);
249​
250 const redeem = async () => {
251 setConfirming(false);
252 if (!choice || !readEnvironmentScope(environmentId, AuthProvidersManageScope)) return;
253 setBusy(true);
254 setStatus(null);
255 const result = await consume({ environmentId, input: choice.input });
256 setBusy(false);
257 if (result._tag === "Success") {
258 setStatus(result.value.warning ?? OUTCOME_TEXT[result.value.outcome]);
259 return;
260 }
261 setStatus(
262 "error" in result.cause && result.cause.error instanceof Error
263 ? result.cause.error.message
264 : "Could not use the reset credit.",
265 );
266 };
267​
268 const confirm = (next: ResetCreditChoice) => {
269 if (!readEnvironmentScope(environmentId, AuthProvidersManageScope)) return;
270 setChoice(next);
271 setConfirming(true);
272 };
273​
274 return { canManageProviders, choice, confirming, setConfirming, confirm, busy, status, redeem };
276​
277/** Require confirmation because redemption spends credits. Mount outside popovers, which stack above
278 * dialogs and unmount on close. */
279export function ResetCreditDialog({
280 open,
281 onOpenChange,
282 choice,
283 onConfirm,
284 disabled = false,
285}: {
286 readonly open: boolean;
287 readonly onOpenChange: (open: boolean) => void;
288 readonly choice: ResetCreditChoice | null;
289 readonly onConfirm: () => void;
290 readonly disabled?: boolean;
291}) {
292 return (
293 <AlertDialog open={open} onOpenChange={onOpenChange}>
294 <AlertDialogPopup>
295 <AlertDialogHeader>
296 <AlertDialogTitle>Use a reset credit?</AlertDialogTitle>
297 <AlertDialogDescription>{choice?.confirmDescription}</AlertDialogDescription>
298 </AlertDialogHeader>
299 <AlertDialogFooter>
300 <AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>
301 <Button disabled={disabled} onClick={onConfirm}>
302 Use credit
303 </Button>
304 </AlertDialogFooter>
305 </AlertDialogPopup>
306 </AlertDialog>
307 );
309​
310export function ResetCredits({
311 environmentId,
312 input,
313 credits,
314 now,
315}: {
316 readonly environmentId: EnvironmentId;
317 readonly input: ProviderConsumeResetCreditInput;
318 readonly credits: ServerProviderResetCredits;
319 readonly now: number;
320}) {
321 const { canManageProviders, choice, confirming, setConfirming, confirm, busy, status, redeem } =
322 useResetCredit(environmentId);
323 if (credits.availableCount === 0 && status === null) return null;
324 return (
325 <div className="flex flex-col gap-1 text-xs text-muted-foreground">
326 {resetCreditChoices(credits, input, now).map((choice) => (
327 <div key={choice.key} className="flex flex-wrap items-center gap-x-3 gap-y-1">
328 <span className="tabular-nums">{choice.summary}</span>
329 {choice.availableCount > 0 ? (
330 <Button
331 size="xs"
332 variant="outline"
333 disabled={busy || !canManageProviders}
334 onClick={() => confirm(choice)}
335 >
336 {busy ? "Using…" : choice.actionLabel}
337 </Button>
338 ) : null}
339 </div>
340 ))}
341 {status ? <span className="text-foreground">{status}</span> : null}
342 <ResetCreditDialog
343 open={confirming}
344 onOpenChange={setConfirming}
345 choice={choice}
346 onConfirm={() => void redeem()}
347 disabled={!canManageProviders}
348 />
349 </div>
350 );
352​
353/** Advance now only on explicit refresh to avoid page repaints from ticking. */
354export function UsageLimitsSection({
355 selectedEnvironmentIds,
356 hiddenProviders,
357 now,
358}: {
359 readonly selectedEnvironmentIds: ReadonlySet<EnvironmentId> | null;
360 readonly hiddenProviders: ReadonlySet<UsageProviderKind>;
361 readonly now: number;
362}) {
363 const presentations = useAtomValue(environmentPresentations.presentationsWithProvidersAtom);
364 const hiddenDrivers = new Set<ServerProvider["driver"]>(
365 [...hiddenProviders].map((provider) => PROVIDER_PRESENTATION[provider].driverKind),
366 );
367 const isVisible = (driver: ServerProvider["driver"]) => !hiddenDrivers.has(driver);
368 const selected = new Map(
369 [...presentations].flatMap(([id, presentation]) => {
370 if (selectedEnvironmentIds !== null && !selectedEnvironmentIds.has(id)) return [];
371 const config = presentation.serverConfig;
372 if (hiddenDrivers.size === 0 || config === null) return [[id, presentation] as const];
373 return [
374 [
375 id,
376 {
377 ...presentation,
378 serverConfig: {
379 ...config,
380 providers: config.providers.filter((provider) => isVisible(provider.driver)),
381 usageLimitSources: config.usageLimitSources?.flatMap((source) => {
382 const accounts = source.accounts.filter((account) => isVisible(account.driver));
383 return accounts.length === 0 && source.accounts.length > 0
384 ? []
385 : [{ ...source, accounts }];
386 }),
387 },
388 },
389 ] as const,
390 ];
391 }),
392 );
393 return <UsageLimitsPooled presentations={selected} now={now} />;