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

SourceControlProvidersSection.tsx

449 lines16.7 KB

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