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

ConnectCliAuthSurface.tsx

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