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

UsageLimitsPooled.tsx

571 lines19.7 KB

1import {
2 collectLimitAccounts,
3 collectLimitNotices,
4 collectLimitPools,
5 formatDuration,
6 formatResetsIn,
7 type LimitAccount,
8 type LimitPool,
9 type LimitPoolMember,
10 type LimitPoolWindow,
11 remainingPercent,
12} from "@t3tools/shared/usageLimits";
13import { TicketIcon } from "lucide-react";
14import { type ReactNode, useState } from "react";
15​
16import { usePrimarySettings } from "../../hooks/useSettings";
17import { cn } from "../../lib/utils";
18import { formatUpcomingTimestamp } from "../../timestampFormat";
19import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon";
20import { getDriverOption } from "../settings/providerDriverMeta";
21import { RedactedSensitiveText } from "../settings/RedactedSensitiveText";
22import { Button } from "../ui/button";
23import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
24import {
25 PaceIcon,
26 ResetCreditDialog,
27 barColor,
28 resetCreditsSummary,
29 useResetCredit,
30} from "./UsageLimits";
31​
32/** `someone@example.com` → `SE`: enough to tell accounts apart, too little to identify one. */
33function accountInitials(email: string): string {
34 const [local = "", domain = ""] = email.split("@");
35 return `${local[0] ?? ""}${domain[0] ?? ""}`.toUpperCase() || "?";
37​
38/** A stable hue per email, so the same account gets the same chip on every visit. */
39function accountHue(email: string): number {
40 let hash = 0;
41 for (let index = 0; index < email.length; index += 1) {
42 hash = (hash * 31 + email.charCodeAt(index)) | 0;
43 }
44 return Math.abs(hash) % 360;
46​
47/** The two-letter chip for an email, coloured by a stable hue per address. */
48function AccountChip({ email }: { readonly email: string }) {
49 const hue = accountHue(email);
50 return (
51 <span
52 role="img"
53 aria-label={`Account ${accountInitials(email)}`}
54 className="inline-flex size-4 shrink-0 items-center justify-center rounded-full text-[9px] leading-none font-semibold"
55 style={{ backgroundColor: `oklch(0.85 0.08 ${hue})`, color: `oklch(0.35 0.1 ${hue})` }}
56 >
57 {accountInitials(email)}
58 </span>
59 );
61​
62/**
63 * The same mark the model picker uses for a native instance (provider glyph,
64 * initials badge, accent); hub accounts have no instance, so they get the chip.
65 */
66function AccountAvatar({
67 account,
68 className,
69}: {
70 readonly account: LimitAccount;
71 readonly className?: string;
72}) {
73 if (account.redeem) {
74 return (
75 <ProviderInstanceIcon
76 driverKind={account.driver}
77 displayName={
78 account.displayName ?? getDriverOption(account.driver)?.label ?? String(account.driver)
79 }
80 accentColor={account.accentColor}
81 showBadge={Boolean(account.displayName)}
82 indicatorBackground="var(--popover)"
83 className={cn("size-5", className)}
84 iconClassName="size-4 text-foreground/80"
85 />
86 );
87 }
88 return account.email ? <AccountChip email={account.email} /> : null;
90​
91/**
92 * Who an account is, without printing the email: the instance name when there
93 * is one, else a two-letter chip. The address itself is revealed on demand in
94 * the segment's popover.
95 */
96function AccountName({
97 account,
98 className,
99}: {
100 readonly account: LimitAccount;
101 readonly className?: string;
102}) {
103 if (account.displayName) return <span className={className}>{account.displayName}</span>;
104 if (account.email) {
105 return (
106 <span className={cn("inline-flex min-w-0 items-center", className)}>
107 <AccountChip email={account.email} />
108 </span>
109 );
110 }
111 return (
112 <span className={className}>
113 {getDriverOption(account.driver)?.label ?? String(account.driver)}
114 </span>
115 );
117​
118function Row({ label, children }: { readonly label: string; readonly children: ReactNode }) {
119 return (
120 <div className="grid grid-cols-[4.5rem_minmax(0,1fr)] gap-x-3">
121 <span className="text-muted-foreground">{label}</span>
122 <span className="min-w-0 text-foreground tabular-nums">{children}</span>
123 </div>
124 );
126​
127/**
128 * Everything about one account in one window: plan, where it is signed in,
129 * the email on request, reset time and share of the pool it restores, and the
130 * reset-credit action. Opens on hover for a glance, on click to act.
131 */
132function SegmentPopover({
133 account,
134 window,
135 reset,
136 now,
137 redeem,
138 onRedeem,
139}: {
140 readonly account: LimitAccount;
141 readonly window: LimitPoolMember["window"];
142 readonly reset: LimitPoolWindow["resets"][number] | undefined;
143 readonly now: number;
144 /** Redeem state owned by the segment, since the confirm lives outside this popover. */
145 readonly redeem: ReturnType<typeof useResetCredit> | null;
146 readonly onRedeem: () => void;
147}) {
148 const timestampFormat = usePrimarySettings((settings) => settings.timestampFormat);
149 const remaining = remainingPercent(window);
150 const resetsIn = formatResetsIn(window, now);
151 const where =
152 account.environments.length > 0
153 ? account.environments.map((environment) => environment.label).join(", ")
154 : account.sourceLabel;
155 const credits =
156 redeem && account.limits.resetCredits?.availableCount ? account.limits.resetCredits : null;
157 return (
158 <div className="flex w-72 max-w-[calc(100vw-3rem)] flex-col gap-2.5 text-xs">
159 <div className="flex min-w-0 flex-col gap-0.5">
160 <span className="flex items-center gap-2 text-sm font-medium text-foreground">
161 <AccountAvatar account={account} />
162 <span className="truncate">
163 {account.displayName ?? getDriverOption(account.driver)?.label ?? account.driver}
164 </span>
165 </span>
166 {account.email ? (
167 <RedactedSensitiveText
168 value={account.email}
169 ariaLabel="Toggle account email visibility"
170 revealTooltip="Click to reveal email"
171 hideTooltip="Click to hide email"
172 className="w-fit"
173 />
174 ) : null}
175 </div>
176 <div className="flex flex-col gap-1 border-t border-border/60 pt-2.5">
177 {account.plan ? <Row label="Plan">{account.plan}</Row> : null}
178 {where ? (
179 <Row label={account.environments.length > 0 ? "Signed in" : "Via"}>{where}</Row>
180 ) : null}
181 </div>
182 <div className="flex flex-col gap-1 border-t border-border/60 pt-2.5">
183 <Row label="Left">{remaining}%</Row>
184 {window.resetsAt ? (
185 <Row label="Resets">
186 {formatUpcomingTimestamp(window.resetsAt, timestampFormat, now)}
187 {resetsIn ? ` · ${resetsIn.replace("resets in ", "in ")}` : ""}
188 </Row>
189 ) : null}
190 {reset && reset.restoresPercent > 0 ? (
191 <Row label="Restores">+{reset.restoresPercent}% of pool</Row>
192 ) : null}
193 </div>
194 {credits && redeem ? (
195 <div className="border-t border-border/60 pt-2.5 text-muted-foreground">
196 <span className="flex items-center gap-3">
197 <span className="tabular-nums">{resetCreditsSummary(credits, now, true)}</span>
198 <Button
199 size="xs"
200 variant="outline"
201 disabled={redeem.busy}
202 className="ms-auto"
203 onClick={onRedeem}
204 >
205 {redeem.busy ? "Using…" : "Use reset"}
206 </Button>
207 </span>
208 </div>
209 ) : null}
210 </div>
211 );
213​
214/**
215 * One account's share of one pooled window: the segment, its popover, and the
216 * reset confirm. The confirm is a sibling of the popover, not a child: dialogs
217 * stack under popovers, and the popover closes as the confirm opens.
218 */
219function PoolSegment({
220 account,
221 window,
222 reset,
223 color,
224 now,
225 index,
226}: {
227 readonly account: LimitAccount;
228 readonly window: LimitPoolMember["window"];
229 readonly reset: LimitPoolWindow["resets"][number] | undefined;
230 readonly color: string;
231 readonly now: number;
232 /** 1-based position in the bar, shown on the strip and its legend row to tie them together. */
233 readonly index: number;
234}) {
235 const [open, setOpen] = useState(false);
236 const remaining = remainingPercent(window);
237 const resetsIn = formatResetsIn(window, now);
238 const credits = account.limits.resetCredits?.availableCount ?? 0;
239 return (
240 <Popover open={open} onOpenChange={setOpen}>
241 <PopoverTrigger
242 openOnHover
243 render={
244 <button
245 type="button"
246 style={{ gridColumn: index, gridRow: 1 }}
247 aria-label={`${account.displayName ?? (account.email ? accountInitials(account.email) : account.driver)}: ${remaining}% left${resetsIn ? `, ${resetsIn}` : ""}${credits ? `, ${credits} reset ${credits === 1 ? "credit" : "credits"} banked` : ""}`}
248 className="relative h-5 min-w-0 cursor-pointer overflow-hidden rounded-md bg-muted text-start outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background data-[popup-open]:ring-1 data-[popup-open]:ring-border @2xl/pool:h-8"
249 />
250 }
251 >
252 {/* Translucent so the label reads over the fill for any provider colour and theme. */}
253 <div
254 aria-hidden
255 className="absolute inset-y-0 left-0 rounded-md opacity-35"
256 style={{ width: `${remaining}%`, backgroundColor: color }}
257 />
258 {/* The spent share is hatched, not blank: it is what the countdown restores. */}
259 {remaining < 100 && reset ? (
260 <div
261 aria-hidden
262 className="absolute inset-y-0 right-0 opacity-20"
263 style={{
264 width: `${100 - remaining}%`,
265 backgroundImage: `repeating-linear-gradient(135deg, ${color} 0 1px, transparent 1px 5px)`,
266 }}
267 />
268 ) : null}
269 <span
270 aria-hidden
271 className="absolute inset-0 flex items-center justify-center text-[10px] leading-none font-semibold text-foreground/80 tabular-nums @2xl/pool:hidden"
272 >
273 {index}
274 </span>
275 <div className="relative hidden h-full min-w-0 items-center gap-1.5 px-2 text-xs @2xl/pool:flex">
276 <AccountName account={account} className="min-w-0 truncate font-medium text-foreground" />
277 <span className="shrink-0 font-semibold text-foreground tabular-nums">{remaining}%</span>
278 {/* Countdown and badge get their own plate: fill and hatching run under them otherwise. */}
279 <span className="ms-auto flex shrink-0 items-center gap-1.5 rounded-sm bg-background/85 px-1.5 py-0.5 text-[11px] text-foreground tabular-nums">
280 {resetsIn?.replace("resets in ", "↻ ") ?? ""}
281 {credits ? (
282 <>
283 {resetsIn ? (
284 <span aria-hidden className="text-muted-foreground">
285 ·
286 </span>
287 ) : null}
288 <span aria-hidden className="inline-flex items-center gap-0.5 font-semibold">
289 <TicketIcon className="size-3" aria-hidden />
290 {credits}
291 </span>
292 </>
293 ) : null}
294 </span>
295 </div>
296 </PopoverTrigger>
297 <LegendRow account={account} window={window} color={color} now={now} index={index} />
298 {account.redeem ? (
299 <RedeemableSegmentPopup
300 account={account}
301 window={window}
302 reset={reset}
303 now={now}
304 redeemAt={account.redeem}
305 closePopover={() => setOpen(false)}
306 />
307 ) : (
308 <PopoverPopup side="top" sideOffset={6}>
309 <SegmentPopover
310 account={account}
311 window={window}
312 reset={reset}
313 now={now}
314 redeem={null}
315 onRedeem={() => {}}
316 />
317 </PopoverPopup>
318 )}
319 </Popover>
320 );
322​
323/**
324 * Below the strip at narrow widths: one row per account in bar order, carrying
325 * the text the segment has no room for. Tapping a row opens the same popover
326 * as its segment, so the two are one control with two handles.
327 */
328function LegendRow({
329 account,
330 window,
331 color,
332 now,
333 index,
334}: {
335 readonly account: LimitAccount;
336 readonly window: LimitPoolMember["window"];
337 readonly color: string;
338 readonly now: number;
339 readonly index: number;
340}) {
341 const remaining = remainingPercent(window);
342 const resetsIn = formatResetsIn(window, now);
343 const credits = account.limits.resetCredits?.availableCount ?? 0;
344 return (
345 <PopoverTrigger
346 style={{ gridColumn: "1 / -1", gridRow: index + 1 }}
347 className="flex min-h-7 min-w-0 cursor-pointer items-center gap-2 rounded-md px-1 py-0.5 text-start text-xs outline-none focus-visible:ring-2 focus-visible:ring-ring @2xl/pool:hidden"
348 >
349 <span className="relative inline-flex size-4 shrink-0 items-center justify-center rounded-sm text-[10px] leading-none font-semibold text-foreground/80 tabular-nums">
350 <span
351 aria-hidden
352 className="absolute inset-0 rounded-sm opacity-35"
353 style={{ backgroundColor: color }}
354 />
355 <span className="sr-only">Segment </span>
356 <span className="relative">{index}</span>
357 </span>
358 <AccountName account={account} className="min-w-0 truncate font-medium text-foreground" />
359 <span className="shrink-0 font-semibold text-foreground tabular-nums">{remaining}%</span>
360 <span className="ms-auto flex shrink-0 items-center gap-1.5 text-[11px] text-muted-foreground tabular-nums">
361 {resetsIn?.replace("resets in ", "↻ ") ?? ""}
362 {credits ? (
363 <>
364 {resetsIn ? <span aria-hidden>·</span> : null}
365 <span
366 aria-hidden
367 className="inline-flex items-center gap-0.5 font-semibold text-foreground"
368 >
369 <TicketIcon className="size-3" aria-hidden />
370 {credits}
371 </span>
372 <span className="sr-only">
373 {credits} reset {credits === 1 ? "credit" : "credits"} banked
374 </span>
375 </>
376 ) : null}
377 </span>
378 </PopoverTrigger>
379 );
381​
382/** Split out so the redeem hook only runs for accounts that can redeem. */
383function RedeemableSegmentPopup({
384 account,
385 window,
386 reset,
387 now,
388 redeemAt,
389 closePopover,
390}: {
391 readonly account: LimitAccount;
392 readonly window: LimitPoolMember["window"];
393 readonly reset: LimitPoolWindow["resets"][number] | undefined;
394 readonly now: number;
395 readonly redeemAt: NonNullable<LimitAccount["redeem"]>;
396 readonly closePopover: () => void;
397}) {
398 const redeem = useResetCredit(redeemAt.environmentId, redeemAt.input);
399 return (
400 <>
401 <PopoverPopup side="top" sideOffset={6}>
402 <SegmentPopover
403 account={account}
404 window={window}
405 reset={reset}
406 now={now}
407 redeem={redeem}
408 onRedeem={() => {
409 closePopover();
410 redeem.setConfirming(true);
411 }}
412 />
413 </PopoverPopup>
414 <ResetCreditDialog
415 open={redeem.confirming}
416 onOpenChange={redeem.setConfirming}
417 onConfirm={() => void redeem.redeem()}
418 />
419 {/* The popover closed before the confirm, so the outcome needs a home outside it. */}
420 {redeem.status ? (
421 <span role="status" className="col-span-full text-xs text-muted-foreground">
422 <AccountName account={account} className="font-medium text-foreground" /> {redeem.status}
423 </span>
424 ) : null}
425 </>
426 );
428​
429/**
430 * One pooled window as equal-width segments, one per account, each filled by
431 * the share of that account's quota still open. Equal widths are honest: every
432 * account contributes the same share of the pool, whatever its plan.
433 *
434 * Wide, each segment carries its own label. Narrow, the bar is a bare strip
435 * and a legend below lists the accounts in the same order; both open the
436 * same popover.
437 */
438function PoolBar({
439 pool,
440 color,
441 now,
442}: {
443 readonly pool: LimitPoolWindow;
444 readonly color: string;
445 readonly now: number;
446}) {
447 const restores = new Map(pool.resets.map((reset) => [reset.member.account.key, reset]));
448 return (
449 <div className="@container/pool min-w-0">
450 <div
451 className="grid gap-x-1 gap-y-1"
452 style={{ gridTemplateColumns: `repeat(${pool.columns.length}, minmax(0, 1fr))` }}
453 >
454 {pool.columns.map((member, position) =>
455 member.window ? (
456 <PoolSegment
457 key={member.account.key}
458 account={member.account}
459 window={member.window}
460 reset={restores.get(member.account.key)}
461 color={color}
462 now={now}
463 index={position + 1}
464 />
465 ) : null,
466 )}
467 </div>
468 </div>
469 );
471​
472/**
473 * Big pooled number and the segment bar. Accounts keep the same column across
474 * windows; each segment's popover shows its own reset time and share restored.
475 */
476function PoolWindowCard({
477 pool,
478 color,
479 now,
480}: {
481 readonly pool: LimitPoolWindow;
482 readonly color: string;
483 readonly now: number;
484}) {
485 // The soonest reset that hands anything back; an untouched account resets to no effect.
486 const nextRefill = pool.resets.find((reset) => reset.restoresPercent > 0);
487 return (
488 <div className="grid items-center gap-x-6 gap-y-3 rounded-lg border border-border/60 p-4 md:grid-cols-[11rem_minmax(0,1fr)]">
489 <div className="flex flex-col gap-1">
490 <span className="text-sm font-medium text-foreground">{pool.label}</span>
491 <span className="flex items-baseline gap-2">
492 <span className="text-3xl font-semibold text-foreground tabular-nums">
493 {pool.remainingPercent}%
494 </span>
495 <span className="text-sm text-muted-foreground">left</span>
496 {pool.pace ? <PaceIcon pace={pool.pace} /> : null}
497 </span>
498 {nextRefill ? (
499 <span className="text-xs text-muted-foreground tabular-nums">
500 <span className="font-medium text-foreground">↻ +{nextRefill.restoresPercent}%</span>{" "}
501 {nextRefill.at <= now ? "now" : `in ${formatDuration(nextRefill.at - now)}`}
502 </span>
503 ) : null}
504 </div>
505 <PoolBar pool={pool} color={color} now={now} />
506 </div>
507 );
509​
510function PoolSection({ pool, now }: { readonly pool: LimitPool; readonly now: number }) {
511 const color = barColor(pool.driver);
512 const label = getDriverOption(pool.driver)?.label ?? String(pool.driver);
513 return (
514 <section className="flex flex-col gap-3">
515 <h2 className="flex items-center gap-2 text-sm font-medium text-foreground">
516 <ProviderInstanceIcon
517 driverKind={pool.driver}
518 displayName={label}
519 indicatorBackground="var(--background)"
520 className="size-5"
521 iconClassName="size-4 text-foreground/80"
522 />
523 {label}
524 </h2>
525 {pool.windows.map((window) => (
526 <PoolWindowCard key={`${window.kind}:${window.id}`} pool={window} color={color} now={now} />
527 ))}
528 </section>
529 );
531​
532/**
533 * Accounts pooled per provider: what is open across all of them, who resets
534 * next, and how much of the pool that hands back. Answers "can I keep going"
535 * before "on which account".
536 */
537export function UsageLimitsPooled({
538 presentations,
539 now,
540}: {
541 readonly presentations: Parameters<typeof collectLimitAccounts>[0];
542 readonly now: number;
543}) {
544 const pools = collectLimitPools(collectLimitAccounts(presentations), now);
545 const notices = collectLimitNotices(presentations);
546 return (
547 <div className="flex flex-col gap-8">
548 {pools.length === 0 ? (
549 <p className="text-sm text-muted-foreground">
550 No provider on the selected environments reports subscription limits.
551 </p>
552 ) : null}
553 {pools.map((pool) => (
554 <PoolSection key={pool.driver} pool={pool} now={now} />
555 ))}
556 <LimitNotices notices={notices} />
557 </div>
558 );
560​
561/** Sources and providers that could not be read, so a missing bar is not mistaken for a full one. */
562function LimitNotices({ notices }: { readonly notices: readonly string[] }) {
563 if (notices.length === 0) return null;
564 return (
565 <ul className="flex flex-col gap-1 text-xs text-muted-foreground">
566 {notices.map((notice) => (
567 <li key={notice}>{notice}</li>
568 ))}
569 </ul>
570 );