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