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

ConnectOnboardingDialog.tsx

375 lines13.5 KB

1import { useAuth } from "@clerk/react";
2import { useAtomValue } from "@effect/atom-react";
3import { AuthRelayReadScope, AuthRelayWriteScope, type AuthSessionState } from "@t3tools/contracts";
4import { AsyncResult, Atom } from "effect/reactivity";
5import { useState } from "react";
6​
7import {
8 CONNECT_ONBOARDING_OPT_OUT_STORAGE_KEY,
9 ConnectOnboardingOptOutSchema,
10 EMPTY_CONNECT_ONBOARDING_OPT_OUT_STATE,
11} from "~/cloud/connectOnboarding";
12import { hasCloudPublicConfig } from "~/cloud/publicConfig";
13import { useCloudLinkController } from "~/cloud/useCloudLinkController";
14import { useLocalStorage } from "~/hooks/useLocalStorage";
15import { isHostedStaticApp } from "~/hostedPairing";
16import {
17 useEnvironments,
18 usePrimaryEnvironment,
19 usePrimaryEnvironmentId,
20} from "~/state/environments";
21import { environmentSession, readEnvironmentScope, useEnvironmentScope } from "~/state/session";
22import { CloudEnvironmentConnectRows } from "./CloudEnvironmentConnectList";
23import { Button } from "../ui/button";
24import { Checkbox } from "../ui/checkbox";
25import { Dialog } from "../ui/dialog";
26import { Switch } from "../ui/switch";
27import { toastManager } from "../ui/toast";
28import { WizardSteps, WizardPopup, WizardHeader, WizardPanel, WizardFooter } from "../ui/wizard";
29​
30export function ConnectOnboardingDialog() {
31 if (!hasCloudPublicConfig()) return null;
32​
33 return <ConfiguredConnectOnboardingDialog />;
35​
36type OnboardingStep = "publish" | "devices";
37​
38const EMPTY_SESSION_STATE_ATOM = Atom.make(AsyncResult.initial<AuthSessionState>());
39​
40function ConfiguredConnectOnboardingDialog() {
41 // Pending Clerk sessions must not look signed out or activation would look like a new sign-in.
42 const { isLoaded, isSignedIn, userId } = useAuth({ treatPendingAsSignedOut: false });
43 const [optOutState, setOptOutState] = useLocalStorage(
44 CONNECT_ONBOARDING_OPT_OUT_STORAGE_KEY,
45 EMPTY_CONNECT_ONBOARDING_OPT_OUT_STATE,
46 ConnectOnboardingOptOutSchema,
47 );
48​
49 const { environments, isReady: environmentsReady } = useEnvironments();
50 // The empty hosted home already adds account computers after sign-in.
51 const homeScreenAddsComputers =
52 isHostedStaticApp() && environmentsReady && environments.length === 0;
53 const primaryEnvironmentId = usePrimaryEnvironmentId();
54 const primarySessionState = useAtomValue(
55 primaryEnvironmentId === null
56 ? EMPTY_SESSION_STATE_ATOM
57 : environmentSession.sessionStateAtom(primaryEnvironmentId),
58 );
59 const canReadRelay = useEnvironmentScope(primaryEnvironmentId, AuthRelayReadScope);
60 const canWriteRelay = useEnvironmentScope(primaryEnvironmentId, AuthRelayWriteScope);
61 const canManageRelay = canReadRelay && canWriteRelay;
62 const sessionScopesKnown =
63 primaryEnvironmentId === null ? environmentsReady : primarySessionState._tag !== "Initial";
64​
65 const controller = useCloudLinkController();
66 const showPublishStep = canManageRelay && controller.linkState.target !== null;
67 const steps: ReadonlyArray<OnboardingStep> = showPublishStep
68 ? ["publish", "devices"]
69 : ["devices"];
70​
71 const [requestedAccount, setRequestedAccount] = useState<string | null>(null);
72 const [openForAccount, setOpenForAccount] = useState<string | null>(null);
73 const [step, setStep] = useState<OnboardingStep>("devices");
74 const [exposeEnvironment, setExposeEnvironment] = useState(true);
75 const [publishAgentActivity, setPublishAgentActivity] = useState(true);
76 const [dontShowAgain, setDontShowAgain] = useState(false);
77 const [isApplying, setIsApplying] = useState(false);
78 const [prefilledFromLinkState, setPrefilledFromLinkState] = useState(false);
79 // Start undefined so an existing account never looks like a fresh sign-in.
80 const [observedAccount, setObservedAccount] = useState<string | null | undefined>(undefined);
81​
82 if (step === "publish" && sessionScopesKnown && !showPublishStep && !isApplying) {
83 setStep("devices");
84 }
85​
86 const optOutAccounts = optOutState.optOutAccounts;
87​
88 // A signed-in snapshot without userId is incomplete; recording signed-out would fake a fresh sign-in.
89 if (isLoaded && !(isSignedIn && !userId)) {
90 const nextAccount = isSignedIn && userId ? userId : null;
91 if (nextAccount !== observedAccount) {
92 setObservedAccount(nextAccount);
93 if (observedAccount !== undefined && nextAccount !== null) {
94 setRequestedAccount(nextAccount);
95 }
96 }
97 }
98​
99 if (openForAccount !== null && (!isSignedIn || userId !== openForAccount)) {
100 setOpenForAccount(null);
101 }
102 if (requestedAccount !== null && (!isSignedIn || userId !== requestedAccount)) {
103 setRequestedAccount(null);
104 }
105​
106 // Wait for the publish target before opening; otherwise the wizard can freeze on devices before publish
107 // becomes available.
108 const publishStepDecided = !canManageRelay || controller.linkState.target !== null;
109​
110 if (requestedAccount !== null && openForAccount === null) {
111 if (homeScreenAddsComputers || optOutAccounts.includes(requestedAccount)) {
112 setRequestedAccount(null);
113 } else if (sessionScopesKnown && publishStepDecided) {
114 setRequestedAccount(null);
115 setPrefilledFromLinkState(false);
116 setExposeEnvironment(true);
117 setPublishAgentActivity(true);
118 setDontShowAgain(false);
119 setStep(canManageRelay && controller.linkState.target !== null ? "publish" : "devices");
120 setOpenForAccount(requestedAccount);
121 }
122 }
123​
124 const linkStateData = controller.linkState.data;
125 if (openForAccount !== null && !prefilledFromLinkState && linkStateData !== null) {
126 setPrefilledFromLinkState(true);
127 if (
128 linkStateData.linked &&
129 linkStateData.linkRevoked !== true &&
130 linkStateData.cloudUserId === openForAccount
131 ) {
132 setExposeEnvironment(linkStateData.managedTunnelActive ?? linkStateData.linked);
133 setPublishAgentActivity(linkStateData.publishAgentActivity);
134 }
135 }
136​
137 const complete = () => {
138 if (isApplying) return;
139 const account = openForAccount;
140 setOpenForAccount(null);
141 if (account !== null && dontShowAgain) {
142 setOptOutState((state) =>
143 state.optOutAccounts.includes(account)
144 ? state
145 : { optOutAccounts: [...state.optOutAccounts, account] },
146 );
147 }
148 };
149​
150 const applyPublishSelection = async () => {
151 if (isApplying) return;
152 if (
153 primaryEnvironmentId === null ||
154 !readEnvironmentScope(primaryEnvironmentId, AuthRelayReadScope) ||
155 !readEnvironmentScope(primaryEnvironmentId, AuthRelayWriteScope)
156 ) {
157 setStep("devices");
158 return;
159 }
160 if (linkStateData === null || controller.linkState.error !== null) return;
161 // Onboarding only enables links; both toggles off must preserve existing links.
162 if (!exposeEnvironment && !publishAgentActivity) {
163 setStep("devices");
164 return;
165 }
166 setIsApplying(true);
167 const ok = await controller.reconcileCloudState({
168 managedTunnel: exposeEnvironment,
169 publish: publishAgentActivity,
170 });
171 setIsApplying(false);
172 if (!ok) return;
173 toastManager.add({
174 type: "success",
175 title: "T3 Connect enabled",
176 description: exposeEnvironment
177 ? "This environment is available to your other devices through T3 Connect."
178 : "This environment publishes agent activity to your mobile clients.",
179 });
180 setStep("devices");
181 };
182​
183 return (
184 <Dialog
185 open={openForAccount !== null}
186 onOpenChange={(open) => {
187 if (!open && !isApplying) complete();
188 }}
189 >
190 <WizardPopup>
191 <WizardHeader
192 title="Set up T3 Connect"
193 description={
194 <>
195 Mesh your devices together. Publish this environment and connect the rest, all in one
196 place.
197 </>
198 }
199 >
200 {steps.length > 1 ? (
201 <WizardSteps
202 steps={steps.map((id) => STEP_LABELS[id])}
203 currentStep={steps.indexOf(step)}
204 isStepDisabled={() => isApplying}
205 onStepChange={(index) => {
206 const next = steps[index];
207 if (
208 next === "publish" &&
209 (primaryEnvironmentId === null ||
210 !readEnvironmentScope(primaryEnvironmentId, AuthRelayReadScope) ||
211 !readEnvironmentScope(primaryEnvironmentId, AuthRelayWriteScope))
212 )
213 return;
214 if (next) setStep(next);
215 }}
216 />
217 ) : null}
218 </WizardHeader>
219 <WizardPanel>
220 {step === "publish" ? (
221 <PublishStep
222 exposeEnvironment={exposeEnvironment}
223 publishAgentActivity={publishAgentActivity}
224 disabled={isApplying || !canManageRelay || linkStateData === null}
225 operationError={controller.operationError ?? controller.linkState.error}
226 onExposeEnvironmentChange={(enabled) => {
227 if (
228 primaryEnvironmentId !== null &&
229 readEnvironmentScope(primaryEnvironmentId, AuthRelayReadScope) &&
230 readEnvironmentScope(primaryEnvironmentId, AuthRelayWriteScope)
231 )
232 setExposeEnvironment(enabled);
233 }}
234 onPublishAgentActivityChange={(enabled) => {
235 if (
236 primaryEnvironmentId !== null &&
237 readEnvironmentScope(primaryEnvironmentId, AuthRelayReadScope) &&
238 readEnvironmentScope(primaryEnvironmentId, AuthRelayWriteScope)
239 )
240 setPublishAgentActivity(enabled);
241 }}
242 />
243 ) : (
244 <DevicesStep />
245 )}
246 </WizardPanel>
247 <WizardFooter
248 leading={
249 <label className="flex cursor-pointer items-center gap-2 self-start text-xs text-muted-foreground sm:self-center">
250 <Checkbox
251 checked={dontShowAgain}
252 onCheckedChange={(checked) => setDontShowAgain(checked === true)}
253 />
254 Don&apos;t show this again
255 </label>
256 }
257 >
258 {step === "publish" ? (
259 <>
260 <Button variant="ghost" disabled={isApplying} onClick={() => setStep("devices")}>
261 Not now
262 </Button>
263 <Button
264 disabled={isApplying || !canManageRelay || linkStateData === null}
265 onClick={() => void applyPublishSelection()}
266 >
267 {isApplying ? "Enabling…" : "Continue"}
268 </Button>
269 </>
270 ) : (
271 <Button disabled={isApplying} onClick={complete}>
272 Done
273 </Button>
274 )}
275 </WizardFooter>
276 </WizardPopup>
277 </Dialog>
278 );
280​
281const STEP_LABELS: Record<OnboardingStep, string> = {
282 publish: "Publish",
283 devices: "Connect devices",
284};
285​
286function PublishStep({
287 exposeEnvironment,
288 publishAgentActivity,
289 disabled,
290 operationError,
291 onExposeEnvironmentChange,
292 onPublishAgentActivityChange,
293}: {
294 readonly exposeEnvironment: boolean;
295 readonly publishAgentActivity: boolean;
296 readonly disabled: boolean;
297 readonly operationError: string | null;
298 readonly onExposeEnvironmentChange: (enabled: boolean) => void;
299 readonly onPublishAgentActivityChange: (enabled: boolean) => void;
300}) {
301 return (
302 <div className="space-y-3">
303 <div className="rounded-lg border">
304 <OnboardingToggleRow
305 title="Publish this environment"
306 description="Make this environment available to your other devices through T3 Connect."
307 checked={exposeEnvironment}
308 disabled={disabled}
309 onCheckedChange={onExposeEnvironmentChange}
310 />
311 <OnboardingToggleRow
312 title="Publish agent activity"
313 description="Send activity from this environment to your mobile clients for push notifications and Live Activities."
314 checked={publishAgentActivity}
315 disabled={disabled}
316 onCheckedChange={onPublishAgentActivityChange}
317 />
318 </div>
319 {operationError ? <p className="text-xs text-destructive">{operationError}</p> : null}
320 </div>
321 );
323​
324function OnboardingToggleRow({
325 title,
326 description,
327 checked,
328 disabled,
329 onCheckedChange,
330}: {
331 readonly title: string;
332 readonly description: string;
333 readonly checked: boolean;
334 readonly disabled: boolean;
335 readonly onCheckedChange: (enabled: boolean) => void;
336}) {
337 return (
338 <div className="flex items-start justify-between gap-4 border-t border-border/60 px-4 py-3 first:border-t-0">
339 <div className="min-w-0">
340 <p className="text-sm font-medium">{title}</p>
341 <p className="mt-1 text-xs text-muted-foreground">{description}</p>
342 </div>
343 <Switch
344 aria-label={title}
345 checked={checked}
346 disabled={disabled}
347 onCheckedChange={onCheckedChange}
348 />
349 </div>
350 );
352​
353function DevicesStep() {
354 const { environments } = useEnvironments();
355 const primaryEnvironment = usePrimaryEnvironment();
356 const savedEnvironments = environments.filter(
357 (environment) => environment.entry.target._tag !== "PrimaryConnectionTarget",
358 );
359​
360 return (
361 <div className="overflow-hidden rounded-lg border">
362 <CloudEnvironmentConnectRows
363 primaryEnvironmentId={primaryEnvironment?.environmentId ?? null}
364 savedEnvironments={savedEnvironments}
365 showSavedEnvironments
366 empty={
367 <p className="px-4 py-6 text-center text-sm text-muted-foreground">
368 No other environments are published to your account yet. Publish one from another device
369 and it will show up here.
370 </p>
371 }
372 />
373 </div>
374 );