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

SettingsProviderAccountsRouteScreen.tsx

368 lines14.1 KB

1import * as Dialog from "../../components/ui/Dialog";
2import {
3 isAtomCommandInterrupted,
4 squashAtomCommandFailure,
5 type AtomCommandResult,
6} from "@t3tools/client-runtime/state/runtime";
7import type { ProviderAuthResponse, ServerProvider } from "@t3tools/contracts";
8import { useAtomValue } from "@effect/atom-react";
9import { useRef, useState } from "react";
10import { Linking, Pressable, ScrollView, TextInput, View } from "react-native";
11import { useSafeAreaInsets } from "react-native-safe-area-context";
12​
13import { AppText as Text } from "../../components/ui/AppText";
14import { ScreenScrollView } from "../../components/ui/ScreenScrollView";
15import { environmentPresentations } from "../../state/presentation";
16import { useEnvironmentQuery } from "../../state/query";
17import { serverEnvironment } from "../../state/server";
18import { useAtomCommand } from "../../state/use-atom-command";
19import { SettingsActionRow } from "./components/SettingsActionRow";
20import {
21 AndroidSettingsEnvironmentFilter,
22 SettingsEnvironmentFilterHeader,
23} from "./components/SettingsEnvironmentFilterHeader";
24import { SettingsScreen } from "./components/SettingsScreen";
25import { SettingsSection } from "./components/SettingsSection";
26import { useSettingsEnvironmentFilter, type SettingsTarget } from "./settings-environment-filter";
27​
28export function SettingsProviderAccountsRouteScreen() {
29 const { selectedTargets } = useSettingsEnvironmentFilter();
30 const providersByEnvironment = useAtomValue(environmentPresentations.providersByEnvironmentAtom);
31 const insets = useSafeAreaInsets();
32 return (
33 <>
34 <SettingsEnvironmentFilterHeader />
35 <SettingsScreen title="Provider accounts" trailing={<AndroidSettingsEnvironmentFilter />}>
36 <ScreenScrollView
37 className="flex-1"
38 contentInsetAdjustmentBehavior="automatic"
39 contentContainerClassName="gap-6 px-5 pt-4"
40 contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}
41 >
42 {selectedTargets.length === 0 ? (
43 <Text className="text-foreground-muted">Select a connected environment.</Text>
44 ) : (
45 selectedTargets.map((environment) => (
46 <SettingsSection key={environment.environmentId} title={environment.label}>
47 {(providersByEnvironment.get(environment.environmentId) ?? [])
48 .filter(
49 (provider) =>
50 provider.setup?.canAuthenticate ||
51 (provider.driver === "acpRegistry" && provider.installed),
52 )
53 .map((provider) => (
54 <ProviderAccount
55 key={provider.instanceId}
56 environment={environment}
57 provider={provider}
58 />
59 ))}
60 {!(providersByEnvironment.get(environment.environmentId) ?? []).some(
61 (provider) =>
62 provider.setup?.canAuthenticate ||
63 (provider.driver === "acpRegistry" && provider.installed),
64 ) ? (
65 <Text className="p-4 text-foreground-muted">
66 Configure a provider with in-app sign-in in web or desktop Settings.
67 </Text>
68 ) : null}
69 </SettingsSection>
70 ))
71 )}
72 </ScreenScrollView>
73 </SettingsScreen>
74 </>
75 );
77​
78function ProviderAccount({
79 environment,
80 provider,
81}: {
82 readonly environment: SettingsTarget;
83 readonly provider: ServerProvider;
84}) {
85 const environmentId = environment.environmentId;
86 const instanceId = provider.instanceId;
87 const target = { environmentId, input: { instanceId } };
88 const auth = useEnvironmentQuery(serverEnvironment.providerAuthState(target));
89 const options = { reportFailure: false, reportDefect: false };
90 const start = useAtomCommand(serverEnvironment.startProviderAuth, options);
91 const respond = useAtomCommand(serverEnvironment.respondProviderAuth, options);
92 const complete = useAtomCommand(serverEnvironment.completeProviderAuth, options);
93 const cancel = useAtomCommand(serverEnvironment.cancelProviderAuth, options);
94 const logout = useAtomCommand(serverEnvironment.logoutProviderAuth, options);
95 const [pending, setPending] = useState(false);
96 const [choosingMethod, setChoosingMethod] = useState(false);
97 const pendingRef = useRef(false);
98 const [error, setError] = useState<string | null>(null);
99 const [draft, setDraft] = useState({ id: "", values: {} as Record<string, string> });
100 const state = auth.data;
101 const interaction = state?.interaction;
102 const draftId = `${state?.flowId ?? ""}:${interaction?.id ?? ""}`;
103 const values = draft.id === draftId ? draft.values : {};
104 const active =
105 state?.phase === "starting" || state?.phase === "waiting" || state?.phase === "verifying";
106 const signedIn =
107 provider.auth.status === "authenticated" ||
108 (provider.auth.status === "unknown" && state?.phase === "succeeded");
109 const isDiscovering =
110 provider.driver === "acpRegistry" &&
111 !active &&
112 !signedIn &&
113 !auth.error &&
114 state?.methods === undefined;
115 const needsExternalSetup =
116 !active &&
117 !signedIn &&
118 (provider.setup?.canAuthenticate === false ||
119 (provider.driver === "acpRegistry" && state?.methods?.length === 0));
120 const url =
121 interaction?.type === "browser" || interaction?.type === "deviceCode"
122 ? interaction.url
123 : state?.authorizationUrl;
124 const disabled = pending || auth.error !== null || isDiscovering;
125 async function run(command: () => Promise<AtomCommandResult<unknown, unknown>>) {
126 if (pendingRef.current) return false;
127 pendingRef.current = true;
128 setPending(true);
129 setError(null);
130 const result = await command();
131 pendingRef.current = false;
132 setPending(false);
133 if (result._tag === "Success") return true;
134 if (!isAtomCommandInterrupted(result)) {
135 const failure = squashAtomCommandFailure(result);
136 setError(failure instanceof Error ? failure.message : "Could not update provider sign-in.");
137 }
138 return false;
139 }
140 function send(response: ProviderAuthResponse) {
141 if (!state?.flowId || !interaction) return Promise.resolve(false);
142 return run(() =>
143 respond({
144 environmentId,
145 input: { instanceId, flowId: state.flowId!, interactionId: interaction.id, response },
146 }),
147 );
148 }
149 function field(name: string, label: string, secret: boolean) {
150 return (
151 <TextInput
152 accessibilityLabel={label}
153 className="rounded-lg border border-border-subtle px-3 py-2 text-base text-foreground"
154 placeholderTextColorClassName="accent-foreground-muted"
155 placeholder={label}
156 secureTextEntry={secret}
157 autoCapitalize="none"
158 autoCorrect={false}
159 editable={!disabled}
160 maxLength={secret && interaction?.type === "terminal" ? 4_095 : 16_384}
161 value={values[name] ?? ""}
162 onChangeText={(value) => setDraft({ id: draftId, values: { ...values, [name]: value } })}
163 />
164 );
165 }
166 function chooseMethod() {
167 const methods = state?.methods ?? [];
168 if (methods.length <= 1) {
169 void run(() => start(target));
170 return;
171 }
172 setChoosingMethod(true);
173 }
174 return (
175 <View className="border-b border-border-subtle">
176 <View className="gap-2 p-4">
177 <Text className="text-lg font-semibold text-foreground">
178 {provider.displayName ?? provider.driver}
179 </Text>
180 <Text accessibilityLiveRegion="polite" className="text-sm text-foreground-muted">
181 {active || state?.phase === "failed" || state?.phase === "cancelled"
182 ? state.message
183 : signedIn
184 ? "Signed in."
185 : isDiscovering
186 ? "Discovering sign-in methods…"
187 : needsExternalSetup
188 ? "No in-app sign-in advertised. Follow the provider's docs to finish setup."
189 : "Connect this provider."}
190 </Text>
191 {signedIn && !active && provider.auth.email?.trim() ? (
192 <ProviderAccountEmail key={provider.auth.email} email={provider.auth.email} />
193 ) : null}
194 {interaction?.type === "deviceCode" ? (
195 <Text selectable className="text-foreground">
196 Enter code {interaction.userCode} on the sign-in page.
197 </Text>
198 ) : null}
199 {interaction?.type === "terminal" ? (
200 <>
201 <ScrollView className="max-h-64" nestedScrollEnabled>
202 <Text selectable className="font-mono text-sm text-foreground">
203 {interaction.output.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, "")}
204 </Text>
205 </ScrollView>
206 {field("input", "Terminal response", true)}
207 <SettingsActionRow
208 icon="arrow.up"
209 label="Send response"
210 disabled={disabled}
211 onPress={() => {
212 void send({ type: "terminal", data: `${values.input ?? ""}\r` }).then((sent) => {
213 if (sent) setDraft({ id: "", values: {} });
214 });
215 }}
216 />
217 </>
218 ) : null}
219 {interaction?.type === "credentials" ? (
220 <>
221 {interaction.fields.map((entry) => (
222 <View key={entry.name}>{field(entry.name, entry.label, entry.secret)}</View>
223 ))}
224 <SettingsActionRow
225 icon="person.crop.circle"
226 label="Connect"
227 disabled={disabled}
228 onPress={() => {
229 void send({ type: "credentials", values }).then((sent) => {
230 if (sent) setDraft({ id: "", values: {} });
231 });
232 }}
233 />
234 </>
235 ) : null}
236 {url && (interaction?.type === "browser" ? interaction.acceptsCallback : !interaction) ? (
237 <>
238 {field("callback", "Final localhost URL", false)}
239 <SettingsActionRow
240 icon="arrow.right"
241 label="Continue"
242 disabled={disabled || !values.callback?.trim()}
243 onPress={() => {
244 if (!state?.flowId) return;
245 void run(() =>
246 complete({
247 environmentId,
248 input: { instanceId, flowId: state.flowId!, callbackUrl: values.callback! },
249 }),
250 ).then((sent) => {
251 if (sent) setDraft({ id: "", values: {} });
252 });
253 }}
254 />
255 </>
256 ) : null}
257 {error || auth.error ? (
258 <Text accessibilityRole="alert" className="text-danger-foreground">
259 {error ?? auth.error}
260 </Text>
261 ) : null}
262 </View>
263 {choosingMethod && !active ? (
264 <View>
265 {state?.methods?.map((method) => (
266 <SettingsActionRow
267 key={method.id}
268 icon="person.crop.circle"
269 label={method.name}
270 disabled={disabled}
271 onPress={() => {
272 setChoosingMethod(false);
273 void run(() =>
274 start({ environmentId, input: { instanceId, methodId: method.id } }),
275 );
276 }}
277 />
278 ))}
279 <SettingsActionRow icon="xmark" label="Cancel" onPress={() => setChoosingMethod(false)} />
280 </View>
281 ) : null}
282 {url ? (
283 <SettingsActionRow
284 icon="globe"
285 label="Open sign-in page"
286 disabled={disabled}
287 onPress={() => {
288 void (async () => {
289 if (
290 interaction?.type === "browser" &&
291 interaction.requiresConsent &&
292 !(await send({ type: "browser", action: "accept" }))
293 )
294 return;
295 await Linking.openURL(url);
296 })().catch(() => setError("Could not open the sign-in page."));
297 }}
298 />
299 ) : null}
300 {needsExternalSetup && provider.setup?.documentationUrl ? (
301 <SettingsActionRow
302 icon="globe"
303 label="Open docs"
304 onPress={() => {
305 void Linking.openURL(provider.setup!.documentationUrl!).catch(() =>
306 setError("Could not open the provider docs."),
307 );
308 }}
309 />
310 ) : active && state?.flowId ? (
311 <SettingsActionRow
312 icon="xmark"
313 label="Cancel sign-in"
314 disabled={disabled}
315 onPress={() => {
316 void run(() => cancel({ environmentId, input: { instanceId, flowId: state.flowId! } }));
317 }}
318 />
319 ) : !active && !needsExternalSetup && provider.setup?.canAuthenticate !== false ? (
320 <SettingsActionRow
321 icon="person.crop.circle"
322 label={signedIn ? "Change account" : "Sign in"}
323 disabled={disabled || !provider.enabled || !provider.installed || state === null}
324 loading={pending}
325 onPress={chooseMethod}
326 />
327 ) : null}
328 {!active && signedIn && (provider.auth.canLogout ?? provider.setup?.canAuthenticate) ? (
329 <SettingsActionRow
330 icon="person.crop.circle"
331 label="Sign out"
332 tone="danger"
333 disabled={disabled || state === null}
334 onPress={() =>
335 Dialog.alert(
336 "Sign out?",
337 `Running threads sharing this sign-in on ${environment.label} will stop. Thread history is kept.`,
338 [
339 { text: "Cancel", style: "cancel" },
340 {
341 text: "Sign out",
342 style: "destructive",
343 onPress: () => {
344 void run(() => logout(target));
345 },
346 },
347 ],
348 )
349 }
350 />
351 ) : null}
352 </View>
353 );
355​
356function ProviderAccountEmail({ email }: { readonly email: string }) {
357 const [revealed, setRevealed] = useState(false);
358 return (
359 <Pressable
360 accessibilityRole="button"
361 accessibilityLabel={revealed ? "Hide account email" : "Reveal account email"}
362 onPress={() => setRevealed((value) => !value)}
363 className="min-h-[44px] justify-center"
364 >
365 <Text className="text-sm text-foreground-muted">{revealed ? email : "••••••@••••••"}</Text>
366 </Pressable>
367 );