Open History to see the last commit
1import { useAuth, useClerk } from "@clerk/react";
2import { readConnectAuthorizeRequest } from "@t3tools/shared/connectAuth";
3import { useCallback, useEffect, useRef, useState } from "react";
4
5import {
6 buildConnectCliClerkAuthorizeUrl,
7 connectCliSignInRedirectUrl,
8} from "../../cloud/connectCliAuth";
9import { isElectron } from "../../env";
10import { AuthSurfaceShell } from "../auth/AuthSurfaceShell";
11import { resolveClerkSignInProps } from "../clerk/authRedirect";
12import { Button } from "../ui/button";
13
14function ConnectCliAuthMessage({
15 eyebrow,
16 title,
17 description,
18}: {
19 readonly eyebrow?: string;
20 readonly title: string;
21 readonly description: string;
22}) {
23 return (
24 <>
25 {eyebrow ? (
26 <p className="text-3xs font-semibold tracking-widest text-primary uppercase">{eyebrow}</p>
27 ) : null}
28 <h1 className="mt-2 text-2xl font-semibold tracking-tight sm:text-3xl">{title}</h1>
29 <p className="mt-2 text-sm leading-relaxed text-muted-foreground">{description}</p>
30 </>
31 );
32}
33
34const invalidLinkMessage = {
35 eyebrow: "Authorization request",
36 title: "This connect link is incomplete",
37 description:
38 "The link is missing its authorization request. Re-run `t3 connect` in your terminal and open the freshly printed URL.",
39} as const;
40
41export function ConnectCliAuthorizeSurface() {
42 const [request] = useState(() => readConnectAuthorizeRequest(new URL(window.location.href)));
43 const clerk = useClerk();
44 const { isLoaded, isSignedIn } = useAuth();
45 const signInOpened = useRef(false);
46 const redirecting = useRef(false);
47
48 const openSignIn = useCallback(() => {
49 if (!request) {
50 return;
51 }
52 clerk.openSignIn(
53 resolveClerkSignInProps(
54 connectCliSignInRedirectUrl(request, window.location.href),
55 isElectron,
56 ),
57 );
58 }, [clerk, request]);
59
60 useEffect(() => {
61 if (!request || !isLoaded || redirecting.current) {
62 return;
63 }
64 if (!isSignedIn) {
65 if (!signInOpened.current) {
66 signInOpened.current = true;
67 openSignIn();
68 }
69 return;
70 }
71 const authorizeUrl = buildConnectCliClerkAuthorizeUrl(request);
72 if (!authorizeUrl) {
73 return;
74 }
75 redirecting.current = true;
76 window.location.assign(authorizeUrl);
77 }, [isLoaded, isSignedIn, openSignIn, request]);
78
79 if (!request) {
80 return (
81 <AuthSurfaceShell>
82 <ConnectCliAuthMessage {...invalidLinkMessage} />
83 </AuthSurfaceShell>
84 );
85 }
86
87 return (
88 <AuthSurfaceShell>
89 <ConnectCliAuthMessage
90 eyebrow="Browser authorization"
91 title="Connecting your terminal"
92 description={
93 isSignedIn
94 ? "Redirecting to authorize T3 Connect for your CLI…"
95 : "Sign in to continue authorizing T3 Connect for your CLI."
96 }
97 />
98 {isLoaded && !isSignedIn ? (
99 <div className="mt-6">
100 <Button type="button" onClick={openSignIn}>
101 Sign in
102 </Button>
103 </div>
104 ) : null}
105 </AuthSurfaceShell>
106 );
107}