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