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

UsageLimitsSection.tsx

420 lines14.7 KB

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