Open History to see the last commit
1import type { EnvironmentId, SourceControlSignInPrompt } from "@t3tools/contracts";
2import {
3 readHostCredentialSettings,
4 sourceControlClients,
5 type SourceControlAppSignIn,
6 type SourceControlDefinition,
7} from "@t3tools/client-runtime/source-control-clients";
8import * as Cause from "effect/Cause";
9import * as Clipboard from "expo-clipboard";
10import { useRef, useState } from "react";
11import { Alert, Linking } from "react-native";
12
13import { useEnvironmentQuery } from "../../../state/query";
14import { serverEnvironment } from "../../../state/server";
15import { sourceControlEnvironment } from "../../../state/sourceControl";
16import { useAtomCommand } from "../../../state/use-atom-command";
17import type { SettingsTarget } from "../settings-environment-filter";
18import { SettingsRow } from "./SettingsRow";
19import { SettingsSection } from "./SettingsSection";
20
21const failureMessage = (cause: Cause.Cause<unknown>) => {
22 const error = Cause.squash(cause);
23 return error instanceof Error ? error.message : String(error);
24};
25
26const openUrl = (url: string) => void Linking.openURL(url).catch(() => undefined);
27
28const appSignInHosts = sourceControlClients.definitions.flatMap((definition) =>
29 definition.credentials?.appSignIn === undefined
30 ? []
31 : [{ definition, appSignIn: definition.credentials.appSignIn }],
32);
33
34/**
35 * Signing an environment in through a forge's own app, such as T3 Code for GitHub, on servers
36 * configured for it.
37 */
38export function SourceControlSignInSection(props: {
39 readonly environments: readonly SettingsTarget[];
40 readonly canWrite: (environmentId: EnvironmentId) => boolean;
41}) {
42 return (
43 <>
44 {appSignInHosts.flatMap(({ definition, appSignIn }) =>
45 props.environments.map((environment) => (
46 <OfferedAppSignIn
47 key={`${definition.kind}:${environment.environmentId}`}
48 environment={environment}
49 title={
50 props.environments.length > 1
51 ? `${definition.label} · ${environment.label}`
52 : definition.label
53 }
54 definition={definition}
55 appSignIn={appSignIn}
56 disabled={!props.canWrite(environment.environmentId)}
57 />
58 )),
59 )}
60 </>
61 );
62}
63
64function OfferedAppSignIn(props: {
65 readonly environment: SettingsTarget;
66 readonly title: string;
67 readonly definition: SourceControlDefinition;
68 readonly appSignIn: SourceControlAppSignIn;
69 readonly disabled: boolean;
70}) {
71 const discovery = useEnvironmentQuery(
72 sourceControlEnvironment.discovery({
73 environmentId: props.environment.environmentId,
74 input: {},
75 }),
76 );
77 const offered = discovery.data?.sourceControlProviders.some(
78 (item) => item.kind === props.definition.kind && item.appSignIn === true,
79 );
80 if (offered !== true) return null;
81 return (
82 <SettingsSection title={props.title}>
83 <AppSignInRow
84 environment={props.environment}
85 label={props.appSignIn.appName}
86 definition={props.definition}
87 appSignIn={props.appSignIn}
88 disabled={props.disabled}
89 />
90 </SettingsSection>
91 );
92}
93
94function AppSignInRow(props: {
95 readonly environment: SettingsTarget;
96 readonly label: string;
97 readonly definition: SourceControlDefinition;
98 readonly appSignIn: SourceControlAppSignIn;
99 readonly disabled: boolean;
100}) {
101 const { environment, definition, appSignIn } = props;
102 const environmentId = environment.environmentId;
103 const host = appSignIn.hosts[0] ?? "";
104 const { signIns } = readHostCredentialSettings(
105 environment.serverConfig.settings,
106 definition.kind,
107 );
108 const signedIn = (signIns[host] ?? "").length > 0;
109 const start = useAtomCommand(sourceControlEnvironment.startSignIn, { reportFailure: false });
110 const wait = useAtomCommand(sourceControlEnvironment.waitForSignIn, { reportFailure: false });
111 const cancel = useAtomCommand(sourceControlEnvironment.cancelSignIn, { reportFailure: false });
112 // The attempt a pending `wait` belongs to; a cancel or a newer attempt makes its outcome stale.
113 const attempt = useRef<SourceControlSignInPrompt | null>(null);
114 const input = { provider: definition.kind, host };
115 const updateSettings = useAtomCommand(serverEnvironment.updateSettings, {
116 label: `sign out of ${appSignIn.appName}`,
117 });
118 const [pending, setPending] = useState<SourceControlSignInPrompt | "starting" | null>(null);
119
120 const showCode = (prompt: SourceControlSignInPrompt) => {
121 void Clipboard.setStringAsync(prompt.userCode).catch(() => undefined);
122 Alert.alert(
123 prompt.userCode,
124 `Enter this code on GitHub, then approve ${appSignIn.appName}. It is copied. The server finishes signing in even if you leave the app.`,
125 [
126 {
127 text: "Cancel",
128 style: "cancel",
129 onPress: () => {
130 attempt.current = null;
131 setPending(null);
132 void cancel({ environmentId, input });
133 },
134 },
135 { text: "Open GitHub", onPress: () => openUrl(prompt.verificationUri) },
136 ],
137 );
138 };
139
140 const signIn = async () => {
141 setPending("starting");
142 const started = await start({ environmentId, input });
143 if (started._tag !== "Success") {
144 setPending(null);
145 Alert.alert("Could not start the sign-in", failureMessage(started.cause));
146 return;
147 }
148 const prompt = started.value;
149 attempt.current = prompt;
150 setPending(prompt);
151 showCode(prompt);
152 const finished = await wait({ environmentId, input });
153 if (attempt.current !== prompt) return;
154 attempt.current = null;
155 setPending(null);
156 if (finished._tag !== "Success") {
157 Alert.alert("Sign-in did not finish", failureMessage(finished.cause));
158 }
159 };
160
161 const signOut = () =>
162 void updateSettings({
163 environmentId,
164 // Send the whole map; other hosts' redaction markers preserve their sessions.
165 input: {
166 patch: {
167 sourceControlHosts: { [definition.kind]: { signIns: { ...signIns, [host]: "" } } },
168 },
169 },
170 });
171
172 const onPress = () => {
173 if (signedIn) {
174 Alert.alert(
175 appSignIn.appName,
176 "Signed in. GitHub requests use the app's higher rate limit, in repositories where the app is installed.",
177 [
178 { text: "Install on an organization", onPress: () => openUrl(appSignIn.installUrl) },
179 { text: "Sign out", style: "destructive", onPress: signOut },
180 { text: "Cancel", style: "cancel" },
181 ],
182 );
183 } else if (pending !== null && pending !== "starting") {
184 showCode(pending);
185 } else if (pending === null) {
186 void signIn();
187 }
188 };
189
190 return (
191 <SettingsRow
192 icon="person.crop.circle"
193 label={props.label}
194 value={
195 signedIn
196 ? "Signed in"
197 : pending === "starting"
198 ? "Starting…"
199 : pending !== null
200 ? `Enter ${pending.userCode}`
201 : "Sign in"
202 }
203 disabled={props.disabled}
204 onPress={onPress}
205 />
206 );
207}