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

SourceControlAppSignInSettings.tsx

294 lines10.8 KB

1import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
2import { m } from "~/i18n/messages";
3import type { EnvironmentId, SourceControlSignInPrompt } from "@t3tools/contracts";
4import {
5 readHostCredentialSettings,
6 type SourceControlAppSignIn,
7 type SourceControlDefinition,
8} from "@t3tools/client-runtime/source-control-clients";
9import { useAtomValue } from "@effect/atom-react";
10import * as Cause from "effect/Cause";
11import { msg, T, useGT, Var } from "gt-react";
12import { CheckIcon, ExternalLinkIcon, CopyIcon } from "lucide-react";
13import { useState, type ReactNode } from "react";
14​
15import { T3AppIcon } from "~/components/T3AppIcon";
16import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
17import { useClientSettings, useEnvironmentSettings } from "../../hooks/useSettings";
18import { cn } from "../../lib/utils";
19import { serverEnvironment } from "../../state/server";
20import { sourceControlEnvironment } from "../../state/sourceControl";
21import { useAtomCommand } from "../../state/use-atom-command";
22import { formatShortTimestamp } from "../../timestampFormat";
23import { Button, InlineButton } from "../ui/button";
24import { Spinner } from "../ui/spinner";
25import { RedactedSensitiveText } from "./RedactedSensitiveText";
26​
27type SignInState =
28 | { readonly status: "idle" }
29 | { readonly status: "starting" }
30 | { readonly status: "waiting"; readonly prompt: SourceControlSignInPrompt }
31 | { readonly status: "failed"; readonly message: string };
32​
33const failureMessage = (cause: Cause.Cause<unknown>) => {
34 const error = Cause.squash(cause);
35 return error instanceof Error ? (thrownErrorMessage(error, m) ?? error.message) : String(error);
36};
37​
38function ExternalLink(props: { readonly href: string; readonly children: ReactNode }) {
39 return (
40 <InlineButton render={<a href={props.href} target="_blank" rel="noreferrer noopener" />}>
41 {props.children}
42 <ExternalLinkIcon aria-hidden className="size-3" />
43 </InlineButton>
44 );
46​
47function AppMark(props: { readonly signedIn: boolean }) {
48 return (
49 <div className="relative size-10 shrink-0">
50 <T3AppIcon className="size-full" />
51 {props.signedIn ? (
52 <span className="absolute -right-1 -bottom-1 grid size-4 place-items-center rounded-full bg-success text-white ring-2 ring-card">
53 <CheckIcon aria-hidden className="size-2.5" strokeWidth={3} />
54 </span>
55 ) : null}
56 </div>
57 );
59​
60/** The device code, one cell per character, as GitHub prints it. */
61function DeviceCode(props: { readonly code: string }) {
62 return (
63 <div className="flex items-center gap-1 font-mono text-lg font-medium">
64 <span className="sr-only">{props.code}</span>
65 {Array.from(props.code, (char, index) =>
66 char === "-" ? (
67 <span key={index} aria-hidden className="px-0.5 text-muted-foreground">
68 –
69 </span>
70 ) : (
71 <span
72 key={index}
73 aria-hidden
74 className="grid h-10 w-8 place-items-center rounded-md border border-border bg-background shadow-xs"
75 >
76 {char}
77 </span>
78 ),
79 )}
80 </div>
81 );
83​
84export function SourceControlAppSignInSettings({
85 environmentId,
86 definition,
87 appSignIn,
88 account,
89 onChanged,
90}: {
91 readonly environmentId: EnvironmentId;
92 readonly definition: SourceControlDefinition;
93 readonly appSignIn: SourceControlAppSignIn;
94 /** The login discovery reports, which is the signed-in account when no token overrides it. */
95 readonly account: string | null;
96 readonly onChanged: () => void;
97}) {
98 const gt = useGT();
99 const timestampFormat = useClientSettings((settings) => settings.timestampFormat);
100 const expiryTime = (expiresAt: number) =>
101 formatShortTimestamp(new Date(expiresAt).toISOString(), timestampFormat);
102 const host = appSignIn.hosts[0] ?? "";
103 const { signIns, tokens } = useEnvironmentSettings(environmentId, (settings) =>
104 readHostCredentialSettings(settings, definition.kind),
105 );
106 const signedIn = (signIns[host] ?? "").length > 0;
107 const token = tokens[host];
108 // A token read from a secret provider overrides the sign-in like a saved one.
109 const tokenOverrides = typeof token === "string" ? token.length > 0 : token !== undefined;
110 const canSignIn = useAtomValue(
111 sourceControlEnvironment.startSignIn.permissionAtom(environmentId),
112 );
113 const start = useAtomCommand(sourceControlEnvironment.startSignIn, { reportFailure: false });
114 const wait = useAtomCommand(sourceControlEnvironment.waitForSignIn, { reportFailure: false });
115 const cancel = useAtomCommand(sourceControlEnvironment.cancelSignIn, { reportFailure: false });
116 const updateSettings = useAtomCommand(serverEnvironment.updateSettings, {
117 label: `sign out of ${appSignIn.appName}`,
118 });
119 const { copyToClipboard, isCopied } = useCopyToClipboard({
120 timeout: 1500,
121 target: {
122 target: "sign-in code",
123 unavailableMessage: msg("Clipboard API is unavailable while copying sign-in code."),
124 failureMessage: msg("Failed to copy sign-in code to the clipboard."),
125 },
126 });
127 const [state, setState] = useState<SignInState>({ status: "idle" });
128​
129 const signIn = async () => {
130 setState({ status: "starting" });
131 const input = { provider: definition.kind, host };
132 const started = await start({ environmentId, input });
133 if (started._tag !== "Success") {
134 setState({ status: "failed", message: failureMessage(started.cause) });
135 return;
136 }
137 const prompt = started.value;
138 setState({ status: "waiting", prompt });
139 const finished = await wait({ environmentId, input });
140 // A newer attempt, a cancel, or a sign-out owns the state by now.
141 setState((current) => {
142 if (current.status !== "waiting" || current.prompt !== prompt) return current;
143 return finished._tag === "Success"
144 ? { status: "idle" }
145 : { status: "failed", message: failureMessage(finished.cause) };
146 });
147 if (finished._tag === "Success") onChanged();
148 };
149​
150 const signOut = async () => {
151 setState({ status: "idle" });
152 const result = await updateSettings({
153 environmentId,
154 // Send the whole map; other hosts' redaction markers preserve their sessions.
155 input: {
156 patch: {
157 sourceControlHosts: { [definition.kind]: { signIns: { ...signIns, [host]: "" } } },
158 },
159 },
160 });
161 if (result._tag === "Success") onChanged();
162 };
163​
164 const waiting = !signedIn && state.status === "waiting" ? state.prompt : null;
165​
166 let subtitle: ReactNode;
167 let action: ReactNode;
168 if (signedIn) {
169 subtitle =
170 account !== null && !tokenOverrides ? (
171 <span className="flex min-w-0 items-center gap-1">
172 <T>
173 Signed in as
174 <RedactedSensitiveText
175 value={account}
176 ariaLabel={gt`Signed-in GitHub account`}
177 revealTooltip={gt`Show account`}
178 hideTooltip={gt`Hide account`}
179 />
180 </T>
181 </span>
182 ) : tokenOverrides ? (
183 gt`Signed in, but the token saved below is used while it can be read.`
184 ) : (
185 gt`Signed in`
186 );
187 action = (
188 <Button size="xs" variant="outline" disabled={!canSignIn} onClick={() => void signOut()}>
189 <T>Sign out</T>
190 </Button>
191 );
192 } else if (waiting !== null) {
193 subtitle = gt`Approve the app on GitHub to finish signing in.`;
194 action = (
195 <Button
196 size="xs"
197 variant="ghost"
198 onClick={() => {
199 setState({ status: "idle" });
200 void cancel({ environmentId, input: { provider: definition.kind, host } });
201 }}
202 >
203 <T>Cancel</T>
204 </Button>
205 );
206 } else {
207 subtitle = gt`A far higher GitHub API rate limit than a personal token or gh login.`;
208 action = (
209 <Button
210 size="xs"
211 disabled={!canSignIn || state.status === "starting"}
212 onClick={() => void signIn()}
213 >
214 {state.status === "starting" ? <Spinner /> : null}
215 {state.status === "failed" ? gt`Try again` : gt`Sign in with GitHub`}
216 </Button>
217 );
218 }
219​
220 return (
221 <div
222 className={cn(
223 "overflow-hidden rounded-xl border bg-card",
224 state.status === "failed" && !signedIn ? "border-destructive/40" : "border-border",
225 )}
226 >
227 <div className="flex items-center gap-3 p-3">
228 <AppMark signedIn={signedIn} />
229 <div className="min-w-0 flex-1 space-y-0.5">
230 <p className="text-sm font-medium text-foreground">{appSignIn.appName}</p>
231 <div className="text-xs text-muted-foreground">{subtitle}</div>
232 </div>
233 <div className="shrink-0">{action}</div>
234 </div>
235​
236 {waiting !== null ? (
237 <div className="grid gap-4 border-t border-border bg-muted/40 px-3 py-4 sm:grid-cols-[auto_1fr] sm:items-center sm:gap-6">
238 <div className="flex items-center gap-2">
239 <DeviceCode code={waiting.userCode} />
240 <Button
241 size="icon-xs"
242 variant="ghost"
243 aria-label={gt`Copy code`}
244 onClick={() => copyToClipboard(waiting.userCode, undefined)}
245 >
246 {isCopied ? <CheckIcon className="size-3.5" /> : <CopyIcon className="size-3.5" />}
247 </Button>
248 </div>
249 <div className="grid gap-2 sm:justify-items-end">
250 <Button
251 size="sm"
252 render={
253 <a href={waiting.verificationUri} target="_blank" rel="noreferrer noopener" />
254 }
255 onClick={() => copyToClipboard(waiting.userCode, undefined)}
256 >
257 <T>Copy code & open GitHub</T>
258 <ExternalLinkIcon aria-hidden className="size-3.5" />
259 </Button>
260 <p className="flex items-center gap-1.5 text-xs text-muted-foreground">
261 <span aria-hidden className="size-1.5 rounded-full bg-warning" />
262 <T>
263 Waiting for approval · code expires at <Var>{expiryTime(waiting.expiresAt)}</Var>
264 </T>
265 </p>
266 </div>
267 </div>
268 ) : null}
269​
270 {signedIn ? (
271 <div className="flex flex-wrap items-center gap-x-3 gap-y-1 border-t border-border bg-muted/40 px-3 py-2 text-xs text-muted-foreground">
272 <span className="min-w-0 flex-1">
273 <T>Reaches repositories in accounts and organizations that installed the app.</T>
274 </span>
275 <ExternalLink href={appSignIn.installUrl}>
276 <T>Install on an organization</T>
277 </ExternalLink>
278 <ExternalLink href={appSignIn.revokeUrl}>
279 <T>Manage on GitHub</T>
280 </ExternalLink>
281 </div>
282 ) : null}
283​
284 {state.status === "failed" && !signedIn ? (
285 <p
286 role="alert"
287 className="border-t border-destructive/20 bg-destructive/5 px-3 py-2 text-xs text-destructive"
288 >
289 {state.message}
290 </p>
291 ) : null}
292 </div>
293 );