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

UsageLimitsSection.tsx

421 lines14.8 KB

1import { environmentIdsKey, resetCreditFailureText } from "@t3tools/client-runtime/state/usage";
2import * as Dialog from "../../components/ui/Dialog";
3import { RegistryContext, useAtomMount, useAtomValue } from "@effect/atom-react";
4import { normalizeProviderAccentColor } from "@t3tools/client-runtime/state/provider-instance-display";
5import {
6 AuthProvidersManageScope,
7 type EnvironmentId,
8 type ProviderConsumeResetCreditOutcome,
9 type ProviderConsumeResetCreditInput,
10 type ServerProvider,
11 type ServerProviderResetCredits,
12 type ServerProviderUsageWindow,
13} from "@t3tools/contracts";
14import {
15 type ResetCreditChoice,
16 paceOf,
17 paceRemainingPercent,
18 remainingPercent,
19 resetCountdown,
20} from "@t3tools/shared/usageLimits";
21import { formatDuration, limitsNotice, resetCreditChoices } from "@t3tools/shared/usageLimitsCopy";
22import { msg, T, useGT, useMessages, Var } from "gt-react-native";
23import { type ReactNode, use, useContext, useRef, useState } from "react";
24import { Atom } from "effect/reactivity";
25import { Pressable, View } from "react-native";
26import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
27​
28import { AppText as Text } from "../../components/ui/AppText";
29import { ProviderIcon } from "../../components/ProviderIcon";
30import { m as resolveNow, type MessageResolver } from "../../i18n/messages";
31import { environmentPresentations } from "../../state/presentation";
32import { serverEnvironment } from "../../state/server";
33import { readEnvironmentScope, useEnvironmentScope } from "../../state/session";
34import { useAtomCommand } from "../../state/use-atom-command";
35import { useNowMinuteMs } from "../../lib/clock";
36import { NativeWorkspaceTabActivityContext } from "../../native/v5-workspace-context";
37import { useAtomValueWhileVisible } from "../home/home-route-visibility";
38import {
39 limitsAutoRefreshSetAtom,
40 limitsRefreshFailuresAtom,
41 refreshEnvironmentLimits,
42} from "./usageLimitsRefresh";
43import { usageProviderKind, useProviderColors } from "./usageProviders";
44​
45const PACE_LABEL = {
46 ahead: msg("ahead of pace"),
47 on: msg("on pace"),
48 under: msg("under pace"),
49} as const;
50​
51type Driver = ServerProvider["driver"];
52​
53function useBarColor(driver: Driver): string | null {
54 const colors = useProviderColors();
55 const kind = usageProviderKind(driver);
56 return kind ? colors[kind] : null;
58​
59function WindowRow(props: {
60 readonly window: ServerProviderUsageWindow;
61 readonly color: string | null;
62 readonly now: number;
63}) {
64 const { window, now } = props;
65 const remaining = remainingPercent(window);
66 const timeLeft = paceRemainingPercent(window, now);
67 const pace = paceOf(window, now);
68 const m = useMessages();
69 const resetsIn = resetLabels(window, now, m)?.full;
70 const [barWidth, setBarWidth] = useState(0);
71 const tickX =
72 timeLeft === null || barWidth < 6
73 ? null
74 : Math.min(Math.max((barWidth * timeLeft) / 100, 3), barWidth - 3);
75 const bar = (
76 <View
77 className="h-1.5 flex-row overflow-hidden rounded-full bg-subtle"
78 style={barWidth > 0 ? { width: barWidth } : undefined}
79 >
80 <View
81 className={
82 remaining <= 10
83 ? "h-full rounded-full bg-red-500"
84 : remaining <= 30
85 ? "h-full rounded-full bg-amber-500"
86 : "h-full rounded-full bg-foreground"
87 }
88 style={[
89 { flex: remaining },
90 remaining > 30 && props.color ? { backgroundColor: props.color } : null,
91 ]}
92 />
93 <View style={{ flex: 100 - remaining }} />
94 </View>
95 );
96 return (
97 <View className="gap-1">
98 <View className="flex-row items-baseline justify-between gap-3">
99 <Text className="text-sm text-foreground">{window.label}</Text>
100 <Text className="text-sm font-t3-medium tabular-nums text-foreground">
101 <T>
102 <Var>{remaining}</Var>% left
103 </T>
104 </Text>
105 </View>
106 <View
107 className="h-3 justify-center"
108 onLayout={(event) => setBarWidth(event.nativeEvent.layout.width)}
109 >
110 {tickX === null ? (
111 bar
112 ) : (
113 <View className="h-1.5">
114 {/* Clip the same full-width bar so neither fill proportions nor corner radii change. */}
115 {(
116 [
117 [0, tickX - 3],
118 [tickX + 3, barWidth],
119 ] as const
120 ).map(([start, end]) => (
121 <View
122 key={start}
123 className="absolute top-0 bottom-0 overflow-hidden"
124 style={{ left: start, width: end - start }}
125 >
126 <View style={{ marginLeft: -start }}>{bar}</View>
127 </View>
128 ))}
129 </View>
130 )}
131 {tickX !== null ? (
132 <View
133 className="absolute top-px bottom-px w-0.5 rounded-full bg-foreground"
134 style={{ left: tickX - 1 }}
135 />
136 ) : null}
137 </View>
138 {pace || resetsIn ? (
139 <View className="flex-row justify-between gap-3">
140 <Text className="text-xs text-foreground-tertiary">
141 {pace ? m(PACE_LABEL[pace]) : ""}
142 </Text>
143 <Text className="text-xs tabular-nums text-foreground-tertiary">{resetsIn ?? ""}</Text>
144 </View>
145 ) : null}
146 </View>
147 );
149​
150function AccountInstanceLabel({ value }: { readonly value: string }) {
151 const [revealed, setRevealed] = useState(false);
152 const gt = useGT();
153 if (!value.includes("@")) {
154 return (
155 <Text className="shrink text-xs text-foreground-tertiary" numberOfLines={1}>
156 · {value}
157 </Text>
158 );
159 }
160 return (
161 <Pressable
162 className="shrink active:opacity-60"
163 accessibilityRole="button"
164 accessibilityLabel={revealed ? gt`Hide account label` : gt`Reveal account label`}
165 onPress={() => setRevealed((current) => !current)}
166 >
167 <Text className="text-xs text-foreground-tertiary" numberOfLines={1}>
168 · {revealed ? value : "••••••@••••••"}
169 </Text>
170 </Pressable>
171 );
173​
174export function AccountLimits(props: {
175 readonly driver: Driver;
176 readonly accentColor?: string | undefined;
177 readonly label: string;
178 readonly instanceLabel: string;
179 readonly detail: string | undefined;
180 readonly limits: ServerProvider["usageLimits"];
181 readonly now: number;
182 readonly first: boolean;
183 readonly dense?: boolean;
184 readonly trailing?: ReactNode;
185 readonly footer?: ReactNode;
186}) {
187 const { limits, now, dense = false } = props;
188 const providerColor = useBarColor(props.driver);
189 const color = normalizeProviderAccentColor(props.accentColor) ?? providerColor;
190 const m = useMessages();
191 if (!limits) return null;
192 const notice = limitsNotice(limits, m);
193 const externalUsage = limits.externalUsage;
194 const padding = dense ? "px-4 py-3" : "p-4";
195 return (
196 <View
197 className={
198 props.first ? `gap-3 ${padding}` : `gap-3 border-t border-border-subtle ${padding}`
199 }
200 >
201 <View className="flex-row items-center gap-2">
202 <ProviderIcon provider={props.driver} size={16} />
203 <View className="min-w-0 flex-1 flex-row items-baseline gap-2">
204 <Text className="text-base font-t3-medium text-foreground">{props.label}</Text>
205 {props.instanceLabel !== props.label ? (
206 <AccountInstanceLabel key={props.instanceLabel} value={props.instanceLabel} />
207 ) : null}
208 {props.detail ? (
209 <Text className="shrink text-sm text-foreground-muted" numberOfLines={1}>
210 · {props.detail}
211 </Text>
212 ) : null}
213 </View>
214 {props.trailing}
215 </View>
216 {notice ? (
217 <Text className="text-sm text-foreground-muted">{notice}</Text>
218 ) : (
219 <View className="gap-3">
220 {limits.windows.map((window) => (
221 <WindowRow key={window.id} window={window} color={color} now={now} />
222 ))}
223 </View>
224 )}
225 {externalUsage ? (
226 <Pressable
227 accessibilityRole="link"
228 className="min-h-11 justify-center"
229 onPress={() => void tryOpenExternalUrl(externalUsage.url)}
230 >
231 <Text className="text-sm font-t3-medium text-primary">
232 <T>Manage usage</T>
233 </Text>
234 </Pressable>
235 ) : null}
236 {props.footer}
237 </View>
238 );
240​
241const OUTCOME_TEXT: Record<ProviderConsumeResetCreditOutcome, string> = {
242 reset: msg("Reset applied. Your windows have cleared."),
243 nothingToReset: msg("Nothing to reset right now."),
244 noCredit: msg("No reset credit left."),
245 alreadyRedeemed: msg("That credit was already redeemed."),
246};
247​
248export function ResetCredits(props: {
249 readonly environmentId: EnvironmentId;
250 readonly input: ProviderConsumeResetCreditInput;
251 readonly credits: ServerProviderResetCredits;
252 readonly now: number;
253 readonly dense?: boolean;
254}) {
255 const { environmentId, input, credits, now, dense = false } = props;
256 const canManageProviders = useEnvironmentScope(environmentId, AuthProvidersManageScope);
257 const consume = useAtomCommand(serverEnvironment.consumeResetCredit, {
258 reportFailure: false,
259 });
260 const [busy, setBusy] = useState(false);
261 const [status, setStatus] = useState<string | null>(null);
262 const gt = useGT();
263 const m = useMessages();
264 if (dense && credits.availableCount === 0 && status === null) return null;
265​
266 const redeem = async (choice: ResetCreditChoice) => {
267 if (!readEnvironmentScope(environmentId, AuthProvidersManageScope)) return;
268 setBusy(true);
269 setStatus(null);
270 const result = await consume({ environmentId, input: choice.input });
271 setBusy(false);
272 if (result._tag === "Success") {
273 setStatus(result.value.warning ?? resolveNow(OUTCOME_TEXT[result.value.outcome]));
274 return;
275 }
276 setStatus(resetCreditFailureText(result, resolveNow));
277 };
278​
279 const confirm = (choice: ResetCreditChoice) => {
280 if (!readEnvironmentScope(environmentId, AuthProvidersManageScope)) return;
281 Dialog.alert(resolveNow(msg("Use a reset credit?")), choice.confirmDescription, [
282 { text: resolveNow(msg("Cancel")), style: "cancel" },
283 { text: resolveNow(msg("Use credit")), onPress: () => void redeem(choice) },
284 ]);
285 };
286​
287 return (
288 <View className="gap-1">
289 {resetCreditChoices(credits, input, now, false, m).map((choice) => (
290 <View key={choice.key} className="flex-row flex-wrap items-center gap-x-3 gap-y-1">
291 <Text className="text-xs tabular-nums text-foreground-tertiary">{choice.summary}</Text>
292 {choice.availableCount > 0 ? (
293 <Pressable
294 accessibilityRole="button"
295 accessibilityState={{ disabled: busy || !canManageProviders }}
296 disabled={busy || !canManageProviders}
297 onPress={() => confirm(choice)}
298 className={
299 dense
300 ? "rounded-full bg-subtle-strong px-2.5 py-1 disabled:opacity-[0.45]"
301 : "min-h-[44px] justify-center rounded-full bg-subtle-strong px-3 py-1.5 disabled:opacity-[0.45]"
302 }
303 >
304 <Text
305 className={
306 dense
307 ? "text-xs font-t3-medium text-foreground"
308 : "text-sm font-t3-medium text-foreground"
309 }
310 >
311 {busy ? gt({ context: "reset credit is being used" })`Using…` : choice.actionLabel}
312 </Text>
313 </Pressable>
314 ) : null}
315 </View>
316 ))}
317 {!canManageProviders ? (
318 <Text className="text-xs text-foreground-tertiary">
319 <T>This connection cannot manage provider accounts.</T>
320 </Text>
321 ) : null}
322 {status ? <Text className="text-sm text-foreground">{status}</Text> : null}
323 </View>
324 );
326​
327const IDLE_ATOM = Atom.make(undefined);
328​
329export function useRefreshLimits(
330 selectedEnvironmentIds: ReadonlySet<EnvironmentId> | null = null,
331 active = false,
332) {
333 const registry = useContext(RegistryContext);
334 // A retained Usage tab stays mounted while another tab is shown; it holds still until shown.
335 const tabActive = use(NativeWorkspaceTabActivityContext)?.active ?? true;
336 const presentations = useAtomValueWhileVisible(
337 environmentPresentations.presentationsAtom,
338 tabActive,
339 );
340 const now = useNowMinuteMs(tabActive);
341 const [refreshing, setRefreshing] = useState(false);
342 const refreshingRef = useRef(false);
343 const selected = [...presentations].filter(
344 ([environmentId]) =>
345 selectedEnvironmentIds === null || selectedEnvironmentIds.has(environmentId),
346 );
347 const connectedIds = selected
348 .filter(([, presentation]) => presentation.connection.phase === "connected")
349 .map(([environmentId]) => environmentId);
350 const connectedKey = environmentIdsKey(connectedIds);
351 useAtomMount(
352 active && tabActive && connectedKey !== "" ? limitsAutoRefreshSetAtom(connectedKey) : IDLE_ATOM,
353 );
354 const failedIds = new Set(
355 useAtomValue(limitsRefreshFailuresAtom(environmentIdsKey(selected.map(([id]) => id)))),
356 );
357 const failedLabels = selected
358 .filter(([environmentId]) => failedIds.has(environmentId))
359 .map(([, presentation]) => presentation.entry.target.label);
360​
361 const refresh = () =>
362 Promise.all(
363 connectedIds.map((environmentId) => refreshEnvironmentLimits(registry, environmentId)),
364 );
365 // Android RefreshControl needs a true-to-false cycle to stop, even with nothing to probe.
366 const refreshManually = async () => {
367 if (refreshingRef.current) return;
368 refreshingRef.current = true;
369 setRefreshing(true);
370 await refresh().finally(() => {
371 refreshingRef.current = false;
372 setRefreshing(false);
373 });
374 };
375 return {
376 now,
377 refreshing,
378 failedLabels,
379 refresh: refreshManually,
380 };
382​
383export function resetLabels(
384 window: ServerProviderUsageWindow,
385 now: number,
386 resolve: MessageResolver,
387): { readonly full: string; readonly compact: string } | null {
388 const countdown = resetCountdown(window, now);
389 if (countdown === null) return null;
390 if (countdown.kind === "now") {
391 const full = resolve(msg({ context: "usage limit" })`resets now`);
392 return { full, compact: full };
393 }
394 if (countdown.kind === "momentarily") {
395 const momentarily = resolve(msg("Resets momentarily"));
396 return { full: momentarily, compact: momentarily };
397 }
398 const duration = formatDuration(countdown.ms, resolve);
399 return { full: resolve(msg`resets in ${{ duration }}`), compact: duration };
401​
402export function refillLabel(
403 window: ServerProviderUsageWindow,
404 now: number,
405 percent: number,
406 resolve: MessageResolver,
407): string | null {
408 const countdown = resetCountdown(window, now);
409 if (countdown === null) return null;
410 if (countdown.kind === "now") {
411 return resolve(msg({ context: "usage limit refill" })`↻ +${{ percent }}% now`);
412 }
413 if (countdown.kind === "momentarily") {
414 return resolve(msg`↻ +${{ percent }}% Resets momentarily`);
415 }
416 return resolve(
417 msg({
418 context: "usage limit refill",
419 })`↻ +${{ percent }}% in ${{ duration: formatDuration(countdown.ms, resolve) }}`,
420 );