Open History to see the last commit
1import { useAuth, useClerk } from "@clerk/react";
2import { readConnectAuthorizeRequest } from "@t3tools/shared/connectAuth";
3import { useEffect, useEffectEvent, 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 = () => {
49 if (!request) {
50 return;
51 }
52 clerk.openSignIn(
53 resolveClerkSignInProps(
54 connectCliSignInRedirectUrl(request, window.location.href),
55 isElectron,
56 ),
57 );
58 };
59 const openSignInOnLoad = useEffectEvent(openSignIn);
60
61 useEffect(() => {
62 if (!request || !isLoaded || redirecting.current) {
63 return;
64 }
65 if (!isSignedIn) {
66 if (!signInOpened.current) {
67 signInOpened.current = true;
68 openSignInOnLoad();
69 }
70 return;
71 }
72 const authorizeUrl = buildConnectCliClerkAuthorizeUrl(request);
73 if (!authorizeUrl) {
74 return;
75 }
76 redirecting.current = true;
77 window.location.assign(authorizeUrl);
78 }, [isLoaded, isSignedIn, request]);
79
80 if (!request) {
81 return (
82 <AuthSurfaceShell>
83 <ConnectCliAuthMessage {...invalidLinkMessage} />
84 </AuthSurfaceShell>
85 );
86 }
87
88 return (
89 <AuthSurfaceShell>
90 <ConnectCliAuthMessage
91 eyebrow="Browser authorization"
92 title="Connecting your terminal"
93 description={
94 isSignedIn
95 ? "Redirecting to authorize T3 Connect for your CLI…"
96 : "Sign in to continue authorizing T3 Connect for your CLI."
97 }
98 />
99 {isLoaded && !isSignedIn ? (
100 <div className="mt-6">
101 <Button type="button" onClick={openSignIn}>
102 Sign in
103 </Button>
104 </div>
105 ) : null}
106 </AuthSurfaceShell>
107 );
108}