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

SourceControlSignInSection.tsx

147 lines5.2 KB

1import { errorDisplayMessage } from "@t3tools/client-runtime/errors";
2import { useGT } from "gt-react-native";
3import type { SourceControlSignInPrompt } from "@t3tools/contracts";
4import {
5 readHostCredentialSettings,
6 type SourceControlAppSignIn,
7 type SourceControlDefinition,
8} from "@t3tools/client-runtime/source-control-clients";
9import * as Cause from "effect/Cause";
10import * as Clipboard from "expo-clipboard";
11import { useRef, useState } from "react";
12import { tryOpenExternalUrl } from "../../../lib/openExternalUrl";
13import { m } from "../../../i18n/messages";
14​
15import * as Dialog from "../../../components/ui/Dialog";
16import { serverEnvironment } from "../../../state/server";
17import { sourceControlEnvironment } from "../../../state/sourceControl";
18import { useAtomCommand } from "../../../state/use-atom-command";
19import type { SettingsTarget } from "../settings-environment-filter";
20import { SettingsRow } from "./SettingsRow";
21​
22const failureMessage = (cause: Cause.Cause<unknown>) => {
23 const error = Cause.squash(cause);
24 return error instanceof Error ? (errorDisplayMessage(error, m) ?? error.message) : String(error);
25};
26​
27const openUrl = (url: string) => void tryOpenExternalUrl(url, "provider-auth");
28​
29/** Signs an environment in through a forge's own app, such as T3 Code for GitHub. */
30export function AppSignInRow(props: {
31 readonly environment: SettingsTarget;
32 readonly label: string;
33 readonly definition: SourceControlDefinition;
34 readonly appSignIn: SourceControlAppSignIn;
35 readonly disabled: boolean;
36}) {
37 const gt = useGT();
38 const { environment, definition, appSignIn } = props;
39 const environmentId = environment.environmentId;
40 const host = appSignIn.hosts[0] ?? "";
41 const { signIns } = readHostCredentialSettings(
42 environment.serverConfig.settings,
43 definition.kind,
44 );
45 const signedIn = (signIns[host] ?? "").length > 0;
46 const start = useAtomCommand(sourceControlEnvironment.startSignIn, { reportFailure: false });
47 const wait = useAtomCommand(sourceControlEnvironment.waitForSignIn, { reportFailure: false });
48 const cancel = useAtomCommand(sourceControlEnvironment.cancelSignIn, { reportFailure: false });
49 // The attempt a pending `wait` belongs to; a cancel or a newer attempt makes its outcome stale.
50 const attempt = useRef<SourceControlSignInPrompt | null>(null);
51 const input = { provider: definition.kind, host };
52 const updateSettings = useAtomCommand(serverEnvironment.updateSettings, {
53 label: `sign out of ${appSignIn.appName}`,
54 });
55 const [pending, setPending] = useState<SourceControlSignInPrompt | "starting" | null>(null);
56​
57 const showCode = (prompt: SourceControlSignInPrompt) => {
58 void Clipboard.setStringAsync(prompt.userCode).catch(() => undefined);
59 Dialog.alert(
60 prompt.userCode,
61 gt`Enter this code on ${{ host: "GitHub" }}, then approve ${{ app: appSignIn.appName }}. It is copied. The server finishes signing in even if you leave the app.`,
62 [
63 {
64 text: gt`Cancel`,
65 style: "cancel",
66 onPress: () => {
67 attempt.current = null;
68 setPending(null);
69 void cancel({ environmentId, input });
70 },
71 },
72 {
73 text: gt`Open ${{ host: "GitHub" }}`,
74 onPress: () => openUrl(prompt.verificationUri),
75 },
76 ],
77 );
78 };
79​
80 const signIn = async () => {
81 setPending("starting");
82 const started = await start({ environmentId, input });
83 if (started._tag !== "Success") {
84 setPending(null);
85 Dialog.alert(gt`Could not start the sign-in`, failureMessage(started.cause));
86 return;
87 }
88 const prompt = started.value;
89 attempt.current = prompt;
90 setPending(prompt);
91 showCode(prompt);
92 const finished = await wait({ environmentId, input });
93 if (attempt.current !== prompt) return;
94 attempt.current = null;
95 setPending(null);
96 if (finished._tag !== "Success") {
97 Dialog.alert(gt`Sign-in did not finish`, failureMessage(finished.cause));
98 }
99 };
100​
101 const signOut = () =>
102 void updateSettings({
103 environmentId,
104 // Send the whole map; other hosts' redaction markers preserve their sessions.
105 input: {
106 patch: {
107 sourceControlHosts: { [definition.kind]: { signIns: { ...signIns, [host]: "" } } },
108 },
109 },
110 });
111​
112 const onPress = () => {
113 if (signedIn) {
114 Dialog.alert(
115 appSignIn.appName,
116 gt`Signed in. ${{ host: "GitHub" }} requests use the app's higher rate limit, in repositories where the app is installed.`,
117 [
118 { text: gt`Install on an organization`, onPress: () => openUrl(appSignIn.installUrl) },
119 { text: gt`Sign out`, style: "destructive", onPress: signOut },
120 { text: gt`Cancel`, style: "cancel" },
121 ],
122 );
123 } else if (pending !== null && pending !== "starting") {
124 showCode(pending);
125 } else if (pending === null) {
126 void signIn();
127 }
128 };
129​
130 return (
131 <SettingsRow
132 icon="person.crop.circle"
133 label={props.label}
134 value={
135 signedIn
136 ? gt`Signed in`
137 : pending === "starting"
138 ? gt`Starting…`
139 : pending !== null
140 ? gt`Enter ${{ code: pending.userCode }}`
141 : gt`Sign in`
142 }
143 disabled={props.disabled}
144 onPress={onPress}
145 />
146 );