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

SourceControlTokenSettings.tsx

168 lines6.2 KB

1import {
2 isSecretReference,
3 type EnvironmentId,
4 type SecretReference,
5 type SettingsSecretValue,
6} from "@t3tools/contracts";
7import { ExternalLinkIcon } from "lucide-react";
8import { useState } from "react";
9​
10import { useEnvironmentSettings } from "../../hooks/useSettings";
11import {
12 readHostCredentialSettings,
13 type SourceControlDefinition,
14 type SourceControlHostCredentials,
15} from "@t3tools/client-runtime/source-control-clients";
16import { serverEnvironment } from "../../state/server";
17import { useAtomCommand } from "../../state/use-atom-command";
18import { Button, InlineButton } from "../ui/button";
19import { Input } from "../ui/input";
20import { Label } from "../ui/label";
21import { SecretSourceInput, useSecretSources } from "./SecretSourceInput";
22​
23const hasToken = (token: SettingsSecretValue | undefined) =>
24 typeof token === "string" ? token.length > 0 : token !== undefined;
25​
26export function SourceControlTokenSettings({
27 environmentId,
28 definition,
29 credentials,
30 onSaved,
31}: {
32 readonly environmentId: EnvironmentId;
33 readonly definition: SourceControlDefinition;
34 readonly credentials: SourceControlHostCredentials;
35 readonly onSaved: () => void;
36}) {
37 const { tokens } = useEnvironmentSettings(environmentId, (settings) =>
38 readHostCredentialSettings(settings, definition.kind),
39 );
40 const updateSettings = useAtomCommand(serverEnvironment.updateSettings, {
41 label: `save ${definition.label} token`,
42 });
43 const defaultHost = definition.publicHost ?? "";
44 const [host, setHost] = useState(defaultHost);
45 const secretSources = useSecretSources(environmentId);
46 const [pending, setPending] = useState<{
47 readonly key: string;
48 readonly draft: string | SecretReference;
49 } | null>(null);
50 const [saving, setSaving] = useState(false);
51 const normalizedHost = host.trim().toLowerCase();
52 const savedToken = tokens[normalizedHost];
53 const isSaved = hasToken(savedToken);
54 const savedHosts = Object.entries(tokens)
55 .filter(([, value]) => hasToken(value))
56 .map(([saved]) => saved);
57 const sourceKey = JSON.stringify([normalizedHost, savedToken ?? ""]);
58 const draft =
59 pending?.key === sourceKey ? pending.draft : isSecretReference(savedToken) ? savedToken : "";
60 const submission = typeof draft === "string" ? draft.trim() : draft;
61​
62 const save = async (target: string, token: SettingsSecretValue) => {
63 setSaving(true);
64 const result = await updateSettings({
65 environmentId,
66 // Send the whole map; other tokens' redaction markers preserve their values.
67 input: {
68 patch: {
69 sourceControlHosts: { [definition.kind]: { tokens: { ...tokens, [target]: token } } },
70 },
71 },
72 });
73 setSaving(false);
74 if (result._tag === "Success") {
75 setPending(null);
76 onSaved();
77 }
78 };
79​
80 return (
81 <form
82 className="grid gap-3"
83 onSubmit={(event) => {
84 event.preventDefault();
85 if (normalizedHost && submission !== "") void save(normalizedHost, submission);
86 }}
87 >
88 {/* Locked while saving: a successful save clears the draft, which would drop edits made mid-request. */}
89 <fieldset disabled={saving} className="contents">
90 <p className="max-w-2xl text-xs leading-relaxed text-muted-foreground">
91 A token saved here is used before{" "}
92 <code className="rounded bg-muted px-1 py-px text-2xs">{credentials.tokenEnvVar}</code>{" "}
93 and the{" "}
94 <code className="rounded bg-muted px-1 py-px text-2xs">{credentials.cliName}</code> login,
95 so {definition.label} works without the {credentials.cliLabel}. Give it{" "}
96 {credentials.tokenAccess}.{" "}
97 {normalizedHost || defaultHost ? (
98 <InlineButton
99 render={
100 <a
101 href={credentials.newTokenUrl(normalizedHost || defaultHost)}
102 target="_blank"
103 rel="noreferrer noopener"
104 />
105 }
106 >
107 Create a token
108 <ExternalLinkIcon aria-hidden className="size-3" />
109 </InlineButton>
110 ) : null}
111 </p>
112 <div className="grid gap-3 sm:grid-cols-[12rem_1fr]">
113 <div className="grid gap-1.5">
114 <Label htmlFor={`${definition.kind}-token-host-${environmentId}`}>Host</Label>
115 <Input
116 id={`${definition.kind}-token-host-${environmentId}`}
117 autoComplete="off"
118 size="sm"
119 placeholder={defaultHost}
120 value={host}
121 onChange={(event) => setHost(event.target.value)}
122 />
123 </div>
124 <div className="grid gap-1.5">
125 <Label htmlFor={`${definition.kind}-token-${environmentId}`}>Token</Label>
126 <SecretSourceInput
127 id={`${definition.kind}-token-${environmentId}`}
128 size="sm"
129 aria-label={`${definition.label} token`}
130 environmentId={environmentId}
131 configured={isSaved && !isSecretReference(savedToken)}
132 value={draft}
133 sources={secretSources}
134 onChange={(event) => setPending({ key: sourceKey, draft: event.target.value })}
135 onSecretChange={(secret) => setPending({ key: sourceKey, draft: secret ?? "" })}
136 />
137 </div>
138 </div>
139 <div className="flex items-center justify-between gap-3">
140 <p className="text-xs text-muted-foreground">
141 {savedHosts.length === 0
142 ? `No token saved; the server uses ${credentials.tokenEnvVar} or the ${credentials.cliName} login.`
143 : `Saved for ${savedHosts.join(", ")}.`}
144 </p>
145 <div className="flex shrink-0 gap-2">
146 {isSaved ? (
147 <Button
148 size="xs"
149 variant="outline"
150 disabled={saving}
151 onClick={() => void save(normalizedHost, "")}
152 >
153 Remove
154 </Button>
155 ) : null}
156 <Button
157 type="submit"
158 size="xs"
159 disabled={!normalizedHost || submission === "" || saving}
160 >
161 Save
162 </Button>
163 </div>
164 </div>
165 </fieldset>
166 </form>
167 );