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

SourceControlAppSignInSettings.tsx

279 lines10.1 KB

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