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