Open History to see the last commit
1import { useAuth } from "@clerk/expo";
2import { SymbolView } from "../../components/AppSymbol";
3import {
4 connectionStatusText,
5 type EnvironmentConnectionPhase,
6} from "@t3tools/client-runtime/connection";
7import {
8 type EnvironmentId,
9 type EnvironmentMachineKind,
10 resolveEnvironmentMachineKind,
11} from "@t3tools/contracts";
12import { useAtomValue } from "@effect/atom-react";
13import { useCallback, useState } from "react";
14import {
15 ActivityIndicator,
16 Pressable,
17 type NativeSyntheticEvent,
18 type TextLayoutEventData,
19 View,
20} from "react-native";
21
22import { AppText as Text } from "../../components/AppText";
23import { EnvironmentMachineSymbol } from "../../components/EnvironmentMachineSymbol";
24import { ThemedSwitch } from "../../components/ThemedSwitch";
25import { cn } from "../../lib/cn";
26import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
27import type { ConnectedEnvironmentSummary } from "../../state/remote-runtime-types";
28import { serverEnvironment } from "../../state/server";
29import { ProviderSetupLink } from "../settings/ProviderSetupLink";
30import type { ProviderSetupRouteParams } from "../settings/SettingsProviderSetupRouteScreen";
31import { availableCloudEnvironmentPresentation } from "../cloud/cloudEnvironmentPresentation";
32import { hasCloudPublicConfig } from "../cloud/publicConfig";
33import { ConnectionStatusDot } from "./ConnectionStatusDot";
34import { type RelayEnvironmentView, useConnectionController } from "./useConnectionController";
35
36interface CloudEnvironmentRowsProps {
37 readonly connectedCloudEnvironments: ReadonlyArray<ConnectedEnvironmentSummary>;
38 readonly onReconnectEnvironment: (environmentId: EnvironmentId) => void;
39 readonly onSetupProvider?: (target: ProviderSetupRouteParams) => void;
40 readonly showcaseAvailableEnvironments?: ReadonlyArray<RelayEnvironmentView>;
41 readonly showcaseSignedIn?: boolean;
42 /**
43 * Hide the "T3 Connect" section title + refresh button for hosts that
44 * provide their own chrome (the onboarding sheet's native header and
45 * pull-to-refresh).
46 */
47 readonly showHeader?: boolean;
48}
49
50/**
51 * "T3 Connect" section: every environment published to the signed-in account,
52 * with connect switches, availability status, refresh, and loading/error
53 * states. Shared between the Settings environments screen and the T3 Connect
54 * onboarding sheet.
55 *
56 * Already-connected relay environments render even without cloud config or a
57 * signed-in account — they are registered on this device and must stay
58 * reachable and removable. Only discovery (the available list, refresh, and
59 * its errors) requires a signed-in session.
60 */
61export function CloudEnvironmentRows(props: CloudEnvironmentRowsProps) {
62 // Showcase captures run without a Clerk publishable key, so `ClerkProvider`
63 // is never mounted and any `useAuth` call throws — the fixture states whether
64 // the rows are signed in instead of asking Clerk.
65 if (props.showcaseSignedIn !== undefined) {
66 return props.showcaseSignedIn ? <CloudEnvironmentRowsContent {...props} /> : null;
67 }
68 // No cloud config means no `ClerkProvider` either, so `useAuth` would throw.
69 if (!hasCloudPublicConfig()) {
70 return <ConnectedOnlyCloudEnvironmentRows {...props} />;
71 }
72 return <SignedInCloudEnvironmentRows {...props} />;
73}
74
75function SignedInCloudEnvironmentRows(props: CloudEnvironmentRowsProps) {
76 const { isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
77 if (!isSignedIn) return <ConnectedOnlyCloudEnvironmentRows {...props} />;
78 return <CloudEnvironmentRowsContent {...props} />;
79}
80
81function ConnectedOnlyCloudEnvironmentRows(props: CloudEnvironmentRowsProps) {
82 if (props.connectedCloudEnvironments.length === 0) return null;
83 return <CloudEnvironmentRowsContent {...props} discoveryAvailable={false} />;
84}
85
86function CloudEnvironmentRowsContent(
87 props: CloudEnvironmentRowsProps & { readonly discoveryAvailable?: boolean },
88) {
89 const controller = useConnectionController();
90 const discoveryAvailable = props.discoveryAvailable ?? true;
91 const availableCloudEnvironments = discoveryAvailable
92 ? (props.showcaseAvailableEnvironments ?? controller.availableRelayEnvironments)
93 : [];
94 const [expandedErrorId, setExpandedErrorId] = useState<string | null>(null);
95 const hasCloudRows =
96 props.connectedCloudEnvironments.length > 0 || availableCloudEnvironments.length > 0;
97
98 const handleConnectCloudEnvironment = useCallback(
99 (entry: RelayEnvironmentView) => controller.connectRelayEnvironment(entry.environment),
100 [controller],
101 );
102
103 const handleDisconnectCloudEnvironment = useCallback(
104 (environmentId: EnvironmentId) => controller.removeEnvironment(environmentId),
105 [controller],
106 );
107
108 const handleToggleCloudError = useCallback((environmentId: string) => {
109 setExpandedErrorId((current) => (current === environmentId ? null : environmentId));
110 }, []);
111
112 const showHeader = props.showHeader ?? true;
113
114 return (
115 <View collapsable={false} className={cn("gap-3", showHeader && "mt-5")}>
116 {showHeader ? (
117 <View className="flex-row items-center justify-between px-1">
118 <Text className="text-sm font-t3-bold uppercase text-foreground-muted">T3 Connect</Text>
119 {discoveryAvailable ? (
120 <Pressable
121 accessibilityRole="button"
122 disabled={controller.relayDiscovery.isRefreshing}
123 onPress={() => {
124 void controller.refreshRelayEnvironments();
125 }}
126 className="h-9 w-9 items-center justify-center rounded-full bg-subtle active:opacity-70 disabled:opacity-50"
127 >
128 {controller.relayDiscovery.isRefreshing ? (
129 <ActivityIndicator colorClassName={"accent-icon"} size="small" />
130 ) : (
131 <SymbolView
132 name="arrow.clockwise"
133 size={14}
134 tintColorClassName={"accent-icon"}
135 type="monochrome"
136 />
137 )}
138 </Pressable>
139 ) : null}
140 </View>
141 ) : null}
142
143 {hasCloudRows ? (
144 <View collapsable={false} className="overflow-hidden rounded-[24px] bg-card">
145 {props.connectedCloudEnvironments.map((environment, index) => (
146 <ConnectedCloudEnvironmentRow
147 key={environment.environmentId}
148 environment={environment}
149 borderTop={index !== 0}
150 onConnect={() => props.onReconnectEnvironment(environment.environmentId)}
151 onDisconnect={() => handleDisconnectCloudEnvironment(environment.environmentId)}
152 errorExpanded={expandedErrorId === environment.environmentId}
153 onToggleError={() => handleToggleCloudError(environment.environmentId)}
154 onSetupProvider={props.onSetupProvider}
155 />
156 ))}
157 {availableCloudEnvironments.map((environment, index) => (
158 <CloudEnvironmentRow
159 key={environment.environment.environmentId}
160 environment={environment}
161 borderTop={props.connectedCloudEnvironments.length > 0 || index !== 0}
162 onConnect={() => handleConnectCloudEnvironment(environment)}
163 errorExpanded={expandedErrorId === environment.environment.environmentId}
164 onToggleError={() => handleToggleCloudError(environment.environment.environmentId)}
165 />
166 ))}
167 </View>
168 ) : controller.relayDiscovery.isRefreshing ? (
169 <View collapsable={false} className="items-center gap-3 rounded-[24px] bg-card p-6">
170 <ActivityIndicator colorClassName={"accent-icon"} />
171 <Text className="text-center text-sm leading-normal text-foreground-muted">
172 Loading linked cloud environments.
173 </Text>
174 </View>
175 ) : controller.relayDiscovery.error ? null : (
176 <View collapsable={false} className="rounded-[24px] bg-card p-5">
177 <Text className="text-sm leading-normal text-foreground-muted">
178 No additional linked cloud environments.
179 </Text>
180 </View>
181 )}
182
183 {/* Rendered alongside any connected rows — a failed discovery must not
184 hide behind an otherwise-healthy list. */}
185 {discoveryAvailable &&
186 controller.relayDiscovery.error &&
187 !controller.relayDiscovery.isRefreshing ? (
188 <View collapsable={false} className="gap-3 rounded-[24px] bg-card p-5">
189 <Text className="text-base font-t3-bold text-foreground">
190 Could not load T3 Connect environments
191 </Text>
192 <Text className="text-sm text-foreground-muted">{controller.relayDiscovery.error}</Text>
193 {controller.relayDiscovery.errorTraceId ? (
194 <CopyTraceIdButton traceId={controller.relayDiscovery.errorTraceId} />
195 ) : null}
196 <Pressable
197 accessibilityRole="button"
198 onPress={() => {
199 void controller.refreshRelayEnvironments();
200 }}
201 className="self-start rounded-full bg-subtle px-3.5 py-2 active:opacity-70"
202 >
203 <Text className="text-xs font-t3-bold text-foreground">Try again</Text>
204 </Pressable>
205 </View>
206 ) : null}
207 </View>
208 );
209}
210
211function ConnectedCloudEnvironmentRow(props: {
212 readonly environment: ConnectedEnvironmentSummary;
213 readonly borderTop: boolean;
214 readonly errorExpanded: boolean;
215 readonly onConnect: () => void;
216 readonly onDisconnect: () => void;
217 readonly onToggleError: () => void;
218 readonly onSetupProvider?: (target: ProviderSetupRouteParams) => void;
219}) {
220 const serverConfig = useAtomValue(
221 serverEnvironment.configValueAtom(props.environment.environmentId),
222 );
223 return (
224 <View>
225 <CloudEnvironmentRowShell
226 borderTop={props.borderTop}
227 connectionError={props.environment.connectionError}
228 connectionErrorTraceId={props.environment.connectionErrorTraceId}
229 connectionState={props.environment.connectionState}
230 errorExpanded={props.errorExpanded}
231 label={props.environment.environmentLabel}
232 machine={resolveEnvironmentMachineKind(serverConfig)}
233 onValueChange={(enabled) => {
234 if (enabled) {
235 props.onConnect();
236 return;
237 }
238 props.onDisconnect();
239 }}
240 onToggleError={props.onToggleError}
241 value={props.environment.connectionState !== "available"}
242 />
243 {props.onSetupProvider
244 ? serverConfig?.providers
245 .filter((provider) => provider.setup?.canAuthenticate || provider.setup?.canInstall)
246 .map((provider) => (
247 <ProviderSetupLink
248 key={provider.instanceId}
249 provider={provider}
250 disabled={props.environment.connectionState !== "connected"}
251 onPress={() =>
252 props.onSetupProvider?.({
253 environmentId: props.environment.environmentId,
254 instanceId: provider.instanceId,
255 })
256 }
257 />
258 ))
259 : null}
260 </View>
261 );
262}
263
264function CloudEnvironmentRow(props: {
265 readonly environment: RelayEnvironmentView;
266 readonly borderTop: boolean;
267 readonly errorExpanded: boolean;
268 readonly onConnect: () => void;
269 readonly onToggleError: () => void;
270}) {
271 const presentation = availableCloudEnvironmentPresentation({
272 isStatusPending: props.environment.availability === "checking",
273 status: props.environment.status,
274 statusError: props.environment.error,
275 statusErrorTraceId: props.environment.traceId,
276 });
277
278 return (
279 <CloudEnvironmentRowShell
280 borderTop={props.borderTop}
281 connectionError={presentation.connectionError}
282 connectionErrorTraceId={presentation.connectionErrorTraceId}
283 connectionState={presentation.connectionState}
284 errorExpanded={props.errorExpanded}
285 label={props.environment.environment.label}
286 onValueChange={(enabled) => {
287 if (enabled) {
288 props.onConnect();
289 }
290 }}
291 onToggleError={props.onToggleError}
292 statusText={presentation.statusText}
293 value={false}
294 />
295 );
296}
297
298function CloudEnvironmentRowShell(props: {
299 readonly borderTop: boolean;
300 readonly connectionError: string | null;
301 readonly connectionErrorTraceId: string | null;
302 readonly connectionState: EnvironmentConnectionPhase;
303 readonly disabled?: boolean;
304 readonly errorExpanded: boolean;
305 readonly label: string;
306 /** Absent for environments the relay lists but this device has not connected to. */
307 readonly machine?: EnvironmentMachineKind;
308 readonly onToggleError: () => void;
309 readonly onValueChange: (enabled: boolean) => void;
310 readonly statusText?: string;
311 readonly value: boolean;
312}) {
313 const isRetrying =
314 props.connectionState === "connecting" || props.connectionState === "reconnecting";
315 const shouldPulse = isRetrying;
316 const statusText =
317 props.statusText ??
318 connectionStatusText({
319 phase: props.connectionState,
320 error: props.connectionError,
321 traceId: props.connectionErrorTraceId,
322 });
323 const statusClassName = props.connectionError
324 ? "text-adaptive-rose-500-400"
325 : "text-foreground-muted";
326 const [errorMeasurement, setErrorMeasurement] = useState<{
327 readonly text: string;
328 readonly lineCount: number;
329 } | null>(null);
330 const errorTraceId = props.connectionErrorTraceId;
331 const measuredErrorText = errorTraceId ? `${statusText} Trace ID: ${errorTraceId}` : statusText;
332 const errorLineCount =
333 errorMeasurement?.text === measuredErrorText ? errorMeasurement.lineCount : 0;
334 const errorCanExpand = props.connectionError !== null && errorLineCount > 1;
335 const isErrorExpanded = errorCanExpand && props.errorExpanded;
336 const StatusContainer = errorCanExpand ? Pressable : View;
337 const onMeasuredErrorTextLayout = useCallback(
338 (event: NativeSyntheticEvent<TextLayoutEventData>) => {
339 if (!props.connectionError) {
340 return;
341 }
342 const nextLineCount = event.nativeEvent.lines.length;
343 setErrorMeasurement((currentMeasurement) =>
344 currentMeasurement?.text === measuredErrorText &&
345 currentMeasurement.lineCount === nextLineCount
346 ? currentMeasurement
347 : { text: measuredErrorText, lineCount: nextLineCount },
348 );
349 },
350 [measuredErrorText, props.connectionError],
351 );
352 return (
353 <View
354 collapsable={false}
355 className={cn(
356 "flex-row items-center gap-3 bg-card px-4 py-3.5",
357 props.borderTop && "border-t border-border",
358 )}
359 >
360 <View className="min-w-0 flex-1 gap-0.5">
361 <View className="min-w-0 flex-row items-center gap-2">
362 <ConnectionStatusDot state={props.connectionState} pulse={shouldPulse} size={7} />
363 {props.machine ? (
364 <EnvironmentMachineSymbol
365 kind={props.machine}
366 size={14}
367 tintColorClassName="accent-foreground-muted"
368 />
369 ) : null}
370 <Text
371 className="min-w-0 flex-shrink text-base font-t3-bold leading-snug text-foreground"
372 numberOfLines={1}
373 >
374 {props.label}
375 </Text>
376 </View>
377 {props.connectionError ? (
378 <Text
379 aria-hidden
380 onTextLayout={onMeasuredErrorTextLayout}
381 className={cn("absolute inset-x-0 -z-[1] text-xs opacity-0", statusClassName)}
382 >
383 {measuredErrorText}
384 </Text>
385 ) : null}
386 <StatusContainer
387 {...(errorCanExpand
388 ? { accessibilityRole: "button" as const, onPress: props.onToggleError }
389 : {})}
390 className="min-w-0 flex-row items-start gap-1"
391 >
392 <Text
393 className={cn("min-w-0 flex-1 text-xs", statusClassName)}
394 numberOfLines={isErrorExpanded ? undefined : 1}
395 >
396 {statusText}
397 {errorTraceId ? (
398 <>
399 {" Trace ID: "}
400 <Text
401 accessibilityHint="Copies the trace ID"
402 accessibilityRole="button"
403 className={cn("text-xs underline decoration-dotted", statusClassName)}
404 onLongPress={(event) => {
405 event.stopPropagation();
406 copyTextWithHaptic(errorTraceId, { target: "connection-trace-id" });
407 }}
408 onPress={(event) => {
409 event.stopPropagation();
410 }}
411 >
412 {errorTraceId}
413 </Text>
414 </>
415 ) : null}
416 </Text>
417 {errorCanExpand ? (
418 <SymbolView
419 name="chevron.down"
420 size={10}
421 tintColorClassName={"accent-chevron"}
422 type="monochrome"
423 style={{
424 marginTop: 3,
425 transform: [{ rotate: isErrorExpanded ? "180deg" : "0deg" }],
426 }}
427 />
428 ) : null}
429 </StatusContainer>
430 </View>
431 <ThemedSwitch
432 disabled={props.disabled}
433 onValueChange={props.onValueChange}
434 value={props.value}
435 />
436 </View>
437 );
438}
439
440function CopyTraceIdButton(props: { readonly traceId: string }) {
441 return (
442 <Pressable
443 accessibilityRole="button"
444 onPress={() => {
445 copyTextWithHaptic(props.traceId, { target: "connection-trace-id" });
446 }}
447 className="self-start flex-row items-center gap-1.5 rounded-full bg-subtle px-3 py-2 active:opacity-70"
448 >
449 <SymbolView
450 name="doc.on.doc"
451 size={12}
452 tintColorClassName={"accent-icon"}
453 type="monochrome"
454 />
455 <Text className="text-xs font-t3-bold text-foreground">Copy trace ID</Text>
456 </Pressable>
457 );
458}