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