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

ConnectCliAuthSurface.tsx

97 lines2.9 KB

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 { StandalonePage, StandalonePageHeader } from "../ui/standalone-page";
11import { resolveClerkSignInProps } from "../clerk/authRedirect";
12import { retryClerkLoad, useClerkLoadFailed } from "../clerk/clerkLoadFailure";
13import { Button } from "../ui/button";
14​
15const invalidLinkMessage = {
16 context: "Authorization request",
17 title: "This connect link is incomplete",
18 description:
19 "The link is missing its authorization request. Re-run `t3 connect` in your terminal and open the freshly printed URL.",
20} as const;
21​
22export function ConnectCliAuthorizeSurface() {
23 const [request] = useState(() => readConnectAuthorizeRequest(new URL(window.location.href)));
24 const clerk = useClerk();
25 const { isLoaded, isSignedIn } = useAuth();
26 const loadFailed = useClerkLoadFailed();
27 const signInOpened = useRef(false);
28 const redirecting = useRef(false);
29​
30 const openSignIn = () => {
31 if (!request) {
32 return;
33 }
34 clerk.openSignIn(
35 resolveClerkSignInProps(
36 connectCliSignInRedirectUrl(request, window.location.href),
37 isElectron,
38 ),
39 );
40 };
41 const openSignInOnLoad = useEffectEvent(openSignIn);
42​
43 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- opens Clerk sign-in or navigates the window to the authorize URL once Clerk has loaded
44 useEffect(() => {
45 if (!request || !isLoaded || redirecting.current) {
46 return;
47 }
48 if (!isSignedIn) {
49 if (!signInOpened.current) {
50 signInOpened.current = true;
51 openSignInOnLoad();
52 }
53 return;
54 }
55 const authorizeUrl = buildConnectCliClerkAuthorizeUrl(request);
56 if (!authorizeUrl) {
57 return;
58 }
59 redirecting.current = true;
60 window.location.assign(authorizeUrl);
61 }, [isLoaded, isSignedIn, request]);
62​
63 if (!request) {
64 return (
65 <StandalonePage>
66 <StandalonePageHeader {...invalidLinkMessage} />
67 </StandalonePage>
68 );
69 }
70​
71 return (
72 <StandalonePage>
73 <StandalonePageHeader
74 context="Browser authorization"
75 title="Connecting your terminal"
76 description={
77 isSignedIn
78 ? "Redirecting to authorize T3 Connect for your CLI…"
79 : "Sign in to continue authorizing T3 Connect for your CLI."
80 }
81 />
82 {loadFailed ? (
83 <div className="mt-6">
84 <Button type="button" onClick={retryClerkLoad}>
85 Retry sign-in
86 </Button>
87 </div>
88 ) : isLoaded && !isSignedIn ? (
89 <div className="mt-6">
90 <Button type="button" onClick={openSignIn}>
91 Sign in
92 </Button>
93 </div>
94 ) : null}
95 </StandalonePage>
96 );