Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import { sourceControlInstallHintText } from "@t3tools/client-runtime/contract-labels";
3import { isSourceControlProviderOffered } from "@t3tools/client-runtime/operations/projects";
4import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
5import {
6 readHostCredentialSettings,
7 sourceControlClients,
8 type SourceControlDefinition,
9 type SourceControlHostCredentials,
10} from "@t3tools/client-runtime/source-control-clients";
11import type {
12 EnvironmentId,
13 SettingsSecretValue,
14 SourceControlProviderDiscoveryItem,
15} from "@t3tools/contracts";
16import * as Option from "effect/Option";
17import * as Schema from "effect/Schema";
18import { useNavigation } from "@react-navigation/native";
19import { msg, useGT, useMessages } from "gt-react-native";
20import { useState } from "react";
21import { Linking, Platform, View } from "react-native";
22
23import { AppText as Text } from "../../../components/ui/AppText";
24import { Button } from "../../../components/ui/Button";
25import { SecretTextInput } from "../../../components/ui/SecretTextInput";
26import { m, type MessageResolver } from "../../../i18n/messages";
27import { useEnvironmentQuery } from "../../../state/query";
28import { serverEnvironment } from "../../../state/server";
29import { sourceControlEnvironment } from "../../../state/sourceControl";
30import { useAtomCommand } from "../../../state/use-atom-command";
31import { ConnectionFormField } from "../../connection/ConnectionFormField";
32import { SourceControlIcon } from "../../projects/SourceControlIcon";
33import type { SettingsTarget } from "../settings-environment-filter";
34import { SettingsProviderRow } from "./SettingsProviderRow";
35import { SettingsSection } from "./SettingsSection";
36
37const saveFailure = (result: Parameters<typeof squashAtomCommandFailure>[0]) => {
38 const error = squashAtomCommandFailure(result);
39 return error instanceof Error ? error.message : m(msg("The settings could not be saved."));
40};
41
42const hasToken = (token: SettingsSecretValue | undefined) =>
43 typeof token === "string" ? token.length > 0 : token !== undefined;
44
45export const sourceControlProviderReady = (item: SourceControlProviderDiscoveryItem) =>
46 item.status === "available" && item.auth.status === "authenticated";
47
48/** The line under a provider's name: whether it works on this server, and what to do if not. */
49export function sourceControlProviderSummary(
50 item: SourceControlProviderDiscoveryItem,
51 resolve: MessageResolver = m,
52): string {
53 const installHint = sourceControlInstallHintText(item.installHint, resolve);
54 if (item.status !== "available")
55 return resolve(msg("Not available on this server: {hint}", { hint: installHint }));
56 const { auth } = item;
57 const detail = Option.getOrNull(auth.detail);
58 if (auth.status === "authenticated") {
59 const account = Option.getOrNull(auth.account);
60 if (account && detail)
61 return resolve(msg("Authenticated as {account} · {detail}", { account, detail }));
62 if (account) return resolve(msg("Authenticated as {account}", { account }));
63 if (detail) return resolve(msg("Authenticated · {detail}", { detail }));
64 return resolve(msg("Authenticated"));
65 }
66 if (auth.status === "unauthenticated") {
67 if (!item.executable) return resolve(msg("Available. {hint}", { hint: installHint }));
68 if (auth.accounts?.some((entry) => entry.authenticated))
69 return (
70 detail ?? resolve(msg("Every {provider} host is turned off.", { provider: item.label }))
71 );
72 return resolve(
73 msg(
74 "Not authenticated on this server. Sign in with the {tool} tool on the server host, or save a token here.",
75 { tool: item.executable },
76 ),
77 );
78 }
79 return resolve(
80 msg("Could not verify {provider}. {detail}", {
81 provider: item.label,
82 detail: detail ?? installHint,
83 }),
84 );
85}
86
87/**
88 * Every hosting integration each selected environment knows: whether it works there, whether
89 * the project pickers offer it, and its credentials where the app can set them.
90 */
91export function SourceControlProvidersSection(props: {
92 readonly environments: readonly SettingsTarget[];
93 readonly canWrite: (environmentId: EnvironmentId) => boolean;
94}) {
95 const gt = useGT();
96 return (
97 <>
98 {props.environments.map((environment) => (
99 <EnvironmentProviders
100 key={environment.environmentId}
101 environment={environment}
102 title={
103 props.environments.length > 1
104 ? gt("Source control providers · {environment}", { environment: environment.label })
105 : gt("Source control providers")
106 }
107 disabled={!props.canWrite(environment.environmentId)}
108 />
109 ))}
110 </>
111 );
112}
113
114function EnvironmentProviders(props: {
115 readonly environment: SettingsTarget;
116 readonly title: string;
117 readonly disabled: boolean;
118}) {
119 const gt = useGT();
120 const messages = useMessages();
121 const { environment } = props;
122 const { environmentId } = environment;
123 const discovery = useEnvironmentQuery(
124 sourceControlEnvironment.discovery({ environmentId, input: {} }),
125 );
126 const canUpdate = useAtomValue(serverEnvironment.updateSettings.permissionAtom(environmentId));
127 const updateSettings = useAtomCommand(serverEnvironment.updateSettings, {
128 label: "save source control providers",
129 });
130 const navigation = useNavigation();
131 const items = discovery.data?.sourceControlProviders ?? [];
132 const offered = environment.serverConfig.settings.offeredSourceControlProviders;
133 const disabled = props.disabled || !canUpdate;
134 if (items.length === 0) {
135 return discovery.error ? (
136 <SettingsSection title={props.title} footer={discovery.error}>
137 <View className="p-4">
138 <Button label={gt("Scan again")} tone="secondary" onPress={discovery.refresh} />
139 </View>
140 </SettingsSection>
141 ) : null;
142 }
143 return (
144 <SettingsSection title={props.title}>
145 {items.map((item, index) => {
146 const definition = sourceControlClients.find(item.kind);
147 return (
148 <SettingsProviderRow
149 key={item.kind}
150 icon={
151 <SourceControlIcon
152 icon={definition?.icon ?? null}
153 size={Platform.OS === "android" ? 20 : 18}
154 colorClassName="accent-icon"
155 />
156 }
157 label={item.label}
158 detail={Option.getOrNull(item.version)}
159 description={sourceControlProviderSummary(item, messages)}
160 ready={sourceControlProviderReady(item)}
161 separated={index > 0}
162 {...(definition?.credentials || definition?.settings
163 ? {
164 onPress: () =>
165 navigation.navigate("SettingsSourceControlProvider", {
166 environmentId,
167 kind: item.kind,
168 }),
169 }
170 : {})}
171 toggle={{
172 accessibilityLabel: gt("Offer {provider} when adding or publishing a project", {
173 provider: item.label,
174 }),
175 value: isSourceControlProviderOffered(offered, item.kind),
176 disabled,
177 onValueChange: (value) =>
178 void updateSettings({
179 environmentId,
180 input: { patch: { offeredSourceControlProviders: { [item.kind]: value } } },
181 }),
182 }}
183 />
184 );
185 })}
186 </SettingsSection>
187 );
188}
189
190export function SourceControlTokenForm(props: {
191 readonly environment: SettingsTarget;
192 readonly definition: SourceControlDefinition;
193 readonly credentials: SourceControlHostCredentials;
194 readonly disabled: boolean;
195 readonly onSaved: () => void;
196}) {
197 const gt = useGT();
198 const { definition, credentials } = props;
199 const { environmentId } = props.environment;
200 // Translates the GitHub definition's English `tokenAccess`, as the web settings do.
201 const tokenAccess =
202 definition.kind === "github"
203 ? gt("read and write access to pull requests and contents")
204 : credentials.tokenAccess;
205 const { tokens } = readHostCredentialSettings(
206 props.environment.serverConfig.settings,
207 definition.kind,
208 );
209 const updateSettings = useAtomCommand(serverEnvironment.updateSettings, {
210 label: `save ${definition.label} token`,
211 });
212 const defaultHost = definition.publicHost ?? "";
213 const [host, setHost] = useState(defaultHost);
214 const [draft, setDraft] = useState("");
215 const [saving, setSaving] = useState(false);
216 const [failure, setFailure] = useState<string | null>(null);
217 const target = host.trim().toLowerCase();
218 const saved = hasToken(tokens[target]);
219 const savedHosts = Object.entries(tokens)
220 .filter(([, value]) => hasToken(value))
221 .map(([name]) => name);
222
223 const save = async (token: string) => {
224 if (!target) return;
225 setSaving(true);
226 setFailure(null);
227 const result = await updateSettings({
228 environmentId,
229 // Send the whole map; other tokens' redaction markers preserve their values.
230 input: {
231 patch: {
232 sourceControlHosts: { [definition.kind]: { tokens: { ...tokens, [target]: token } } },
233 },
234 },
235 });
236 setSaving(false);
237 if (result._tag !== "Success") {
238 setFailure(saveFailure(result));
239 return;
240 }
241 setDraft("");
242 props.onSaved();
243 };
244 const locked = props.disabled || saving;
245 return (
246 <View className="gap-3 p-4">
247 <Text className="text-xs leading-relaxed text-foreground-muted">
248 {gt(
249 "A token saved here is used before {envVar} and the {cliName} login, so {provider} works without the {cliLabel}. Give it {access}.",
250 {
251 envVar: credentials.tokenEnvVar,
252 cliName: credentials.cliName,
253 provider: definition.label,
254 cliLabel: credentials.cliLabel,
255 access: tokenAccess,
256 },
257 )}
258 </Text>
259 <ConnectionFormField
260 label={gt("Host", { $context: "source control host name field" })}
261 autoCapitalize="none"
262 autoCorrect={false}
263 keyboardType="url"
264 placeholder={defaultHost}
265 editable={!locked}
266 value={host}
267 onChangeText={setHost}
268 />
269 <SecretTextInput
270 accessibilityLabel={gt("{provider} token", { provider: definition.label })}
271 placeholder={
272 saved
273 ? gt("Saved. Enter a new token to replace it")
274 : gt("Token", { $context: "access token field" })
275 }
276 value={draft}
277 onChangeText={setDraft}
278 onSubmitEditing={(value) => {
279 if (value.trim()) void save(value.trim());
280 }}
281 editable={!locked}
282 />
283 <Text className="text-xs text-foreground-muted">
284 {savedHosts.length === 0
285 ? gt("No token saved; the server uses {envVar} or the {cliName} login.", {
286 envVar: credentials.tokenEnvVar,
287 cliName: credentials.cliName,
288 })
289 : gt("Saved for {hosts}.", { hosts: savedHosts.join(", ") })}
290 </Text>
291 {failure ? (
292 <Text selectable className="text-xs text-danger-foreground">
293 {failure}
294 </Text>
295 ) : null}
296 <View className="flex-row flex-wrap justify-end gap-2">
297 {target || defaultHost ? (
298 <Button
299 label={gt("Create a token")}
300 tone="text"
301 size="compact"
302 onPress={() =>
303 void Linking.openURL(credentials.newTokenUrl(target || defaultHost)).catch(
304 () => undefined,
305 )
306 }
307 />
308 ) : null}
309 {saved ? (
310 <Button
311 label={gt("Remove", { $context: "verb, removes a saved token" })}
312 tone="secondary"
313 size="compact"
314 disabled={locked}
315 onPress={() => void save("")}
316 />
317 ) : null}
318 <Button
319 label={gt("Save")}
320 tone="primary"
321 size="compact"
322 loading={saving}
323 disabled={locked || !target || !draft.trim()}
324 onPress={() => void save(draft.trim())}
325 />
326 </View>
327 </View>
328 );
329}
330
331type HostSettings = NonNullable<SourceControlDefinition["settings"]>;
332
333/** The fields a host declares, in its own order, with what its schema says about each. */
334function hostSettingsFields(settings: HostSettings) {
335 const order = Schema.resolveAnnotations(settings)?.providerSettingsFormSchema?.order ?? [];
336 const position = (key: string) => (order.includes(key) ? order.indexOf(key) : order.length);
337 return Object.keys(settings.fields)
338 .sort((left, right) => position(left) - position(right))
339 .flatMap((key) => {
340 const field = settings.fields[key]!;
341 const annotations = Schema.resolveAnnotationsKey(field) ?? Schema.resolveAnnotations(field);
342 const form = annotations?.providerSettingsForm ?? {};
343 if (form.hidden) return [];
344 return [
345 {
346 key,
347 label: typeof annotations?.title === "string" ? annotations.title : key,
348 description:
349 typeof annotations?.description === "string" ? annotations.description : undefined,
350 placeholder: form.placeholder,
351 secret: form.control === "password",
352 },
353 ];
354 });
355}
356
357/** Credentials for a host that names its own fields rather than one token per host. */
358export function SourceControlHostFieldsForm(props: {
359 readonly environment: SettingsTarget;
360 readonly definition: SourceControlDefinition;
361 readonly settings: HostSettings;
362 readonly disabled: boolean;
363 readonly onSaved: () => void;
364}) {
365 const gt = useGT();
366 const { definition } = props;
367 const { environmentId } = props.environment;
368 const saved: Readonly<Record<string, unknown>> =
369 props.environment.serverConfig.settings.sourceControlHosts[definition.kind] ?? {};
370 const updateSettings = useAtomCommand(serverEnvironment.updateSettings, {
371 label: `save ${definition.label} settings`,
372 });
373 const [drafts, setDrafts] = useState<Readonly<Record<string, string>>>({});
374 const [saving, setSaving] = useState(false);
375 const [failure, setFailure] = useState<string | null>(null);
376 const fields = hostSettingsFields(props.settings);
377 const isSet = (key: string) => {
378 const value = saved[key];
379 return typeof value === "string" ? value.length > 0 : value !== undefined;
380 };
381 const changed = Object.fromEntries(
382 Object.entries(drafts).flatMap(([key, value]) => (value.trim() ? [[key, value.trim()]] : [])),
383 );
384 const save = async (patch: Record<string, string>) => {
385 setSaving(true);
386 setFailure(null);
387 const result = await updateSettings({
388 environmentId,
389 input: { patch: { sourceControlHosts: { [definition.kind]: patch } } },
390 });
391 setSaving(false);
392 if (result._tag !== "Success") {
393 setFailure(saveFailure(result));
394 return;
395 }
396 setDrafts({});
397 props.onSaved();
398 };
399 const locked = props.disabled || saving;
400 const submit = () => {
401 if (Object.keys(changed).length > 0) void save(changed);
402 };
403 return (
404 <View className="gap-4 p-4">
405 {fields.map((field) => (
406 <View key={field.key} className="gap-1.5">
407 {field.secret ? (
408 <>
409 <Text className="text-2xs font-t3-bold tracking-[0.8px] uppercase text-foreground-muted">
410 {field.label}
411 </Text>
412 <SecretTextInput
413 accessibilityLabel={field.label}
414 placeholder={
415 isSet(field.key) ? gt("Saved. Enter a new value to replace it") : field.label
416 }
417 value={drafts[field.key] ?? ""}
418 onChangeText={(value) => setDrafts({ ...drafts, [field.key]: value })}
419 onSubmitEditing={submit}
420 editable={!locked}
421 />
422 </>
423 ) : (
424 <ConnectionFormField
425 label={field.label}
426 autoCapitalize="none"
427 autoCorrect={false}
428 placeholder={
429 typeof saved[field.key] === "string" && saved[field.key] !== ""
430 ? String(saved[field.key])
431 : field.placeholder
432 }
433 editable={!locked}
434 value={drafts[field.key] ?? ""}
435 onChangeText={(value) => setDrafts({ ...drafts, [field.key]: value })}
436 onSubmitEditing={submit}
437 />
438 )}
439 {field.description ? (
440 <Text className="text-xs text-foreground-muted">{field.description}</Text>
441 ) : null}
442 </View>
443 ))}
444 {failure ? (
445 <Text selectable className="text-xs text-danger-foreground">
446 {failure}
447 </Text>
448 ) : null}
449 <View className="flex-row flex-wrap justify-end gap-2">
450 {fields.some((field) => isSet(field.key)) ? (
451 <Button
452 label={gt("Remove", { $context: "verb, removes saved credentials" })}
453 tone="secondary"
454 size="compact"
455 disabled={locked}
456 onPress={() => void save(Object.fromEntries(fields.map((field) => [field.key, ""])))}
457 />
458 ) : null}
459 <Button
460 label={gt("Save")}
461 tone="primary"
462 size="compact"
463 loading={saving}
464 disabled={locked || Object.keys(changed).length === 0}
465 onPress={submit}
466 />
467 </View>
468 </View>
469 );
470}