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 unsupported = props.environment.connectionState === "unsupported";
223 const enabled = props.environment.isEnabled && !unsupported;
224 return (
225 <Pressable
226 accessibilityHint="Long press to remove from this device"
227 onLongPress={props.onRemove}
228 >
229 <CloudEnvironmentRowShell
230 borderTop={props.borderTop}
231 connectionError={enabled || unsupported ? props.environment.connectionError : null}
232 connectionErrorTraceId={enabled ? props.environment.connectionErrorTraceId : null}
233 connectionState={enabled || unsupported ? props.environment.connectionState : "available"}
234 errorExpanded={props.errorExpanded}
235 label={props.environment.environmentLabel}
236 machine={resolveEnvironmentMachineKind(serverConfig)}
237 onValueChange={props.onSetEnabled}
238 onToggleError={props.onToggleError}
239 disabled={unsupported}
240 {...(enabled || unsupported ? {} : { statusText: "Off" })}
241 value={enabled}
242 />
243 </Pressable>
244 );
245}
246
247function CloudEnvironmentRow(props: {
248 readonly environment: RelayEnvironmentView;
249 readonly borderTop: boolean;
250 readonly errorExpanded: boolean;
251 readonly onConnect: () => void;
252 readonly onToggleError: () => void;
253}) {
254 const presentation = availableCloudEnvironmentPresentation({
255 isStatusPending: props.environment.availability === "checking",
256 status: props.environment.status,
257 statusError: props.environment.error,
258 statusErrorTraceId: props.environment.traceId,
259 });
260
261 return (
262 <CloudEnvironmentRowShell
263 borderTop={props.borderTop}
264 connectionError={presentation.connectionError}
265 connectionErrorTraceId={presentation.connectionErrorTraceId}
266 connectionState={presentation.connectionState}
267 errorExpanded={props.errorExpanded}
268 label={props.environment.environment.label}
269 onValueChange={(enabled) => {
270 if (enabled) {
271 props.onConnect();
272 }
273 }}
274 onToggleError={props.onToggleError}
275 disabled={presentation.connectionState === "unsupported"}
276 statusText={presentation.statusText}
277 value={false}
278 />
279 );
280}
281
282function CloudEnvironmentRowShell(props: {
283 readonly borderTop: boolean;
284 readonly connectionError: string | null;
285 readonly connectionErrorTraceId: string | null;
286 readonly connectionState: EnvironmentConnectionPhase;
287 readonly disabled?: boolean;
288 readonly errorExpanded: boolean;
289 readonly label: string;
290 /** Absent for environments the relay lists but this device has not connected to. */
291 readonly machine?: EnvironmentMachineKind;
292 readonly onToggleError: () => void;
293 readonly onValueChange: (enabled: boolean) => void;
294 readonly statusText?: string;
295 readonly value: boolean;
296}) {
297 const isRetrying =
298 props.connectionState === "connecting" || props.connectionState === "reconnecting";
299 const shouldPulse = isRetrying;
300 const statusText =
301 props.statusText ??
302 connectionStatusText({
303 phase: props.connectionState,
304 error: props.connectionError,
305 traceId: props.connectionErrorTraceId,
306 });
307 const statusClassName = props.connectionError
308 ? "text-danger-foreground"
309 : "text-foreground-muted";
310 const [errorMeasurement, setErrorMeasurement] = useState<{
311 readonly text: string;
312 readonly lineCount: number;
313 } | null>(null);
314 const errorTraceId = props.connectionErrorTraceId;
315 const measuredErrorText = errorTraceId ? `${statusText} Trace ID: ${errorTraceId}` : statusText;
316 const errorLineCount =
317 errorMeasurement?.text === measuredErrorText ? errorMeasurement.lineCount : 0;
318 const errorCanExpand = props.connectionError !== null && errorLineCount > 1;
319 const isErrorExpanded = errorCanExpand && props.errorExpanded;
320 const StatusContainer = errorCanExpand ? Pressable : View;
321 const onMeasuredErrorTextLayout = useCallback(
322 (event: NativeSyntheticEvent<TextLayoutEventData>) => {
323 if (!props.connectionError) {
324 return;
325 }
326 const nextLineCount = event.nativeEvent.lines.length;
327 setErrorMeasurement((currentMeasurement) =>
328 currentMeasurement?.text === measuredErrorText &&
329 currentMeasurement.lineCount === nextLineCount
330 ? currentMeasurement
331 : { text: measuredErrorText, lineCount: nextLineCount },
332 );
333 },
334 [measuredErrorText, props.connectionError],
335 );
336 return (
337 <View
338 collapsable={false}
339 className={cn(
340 "flex-row items-center gap-3 bg-card px-4 py-3.5",
341 props.borderTop && "border-t border-border",
342 )}
343 >
344 <View className="min-w-0 flex-1 gap-0.5">
345 <View className="min-w-0 flex-row items-center gap-2">
346 <ConnectionStatusDot state={props.connectionState} pulse={shouldPulse} size={7} />
347 {props.machine ? (
348 <EnvironmentMachineSymbol
349 kind={props.machine}
350 size={14}
351 tintColorClassName="accent-foreground-muted"
352 />
353 ) : null}
354 <Text
355 className="min-w-0 flex-shrink text-base font-t3-bold leading-snug text-foreground"
356 numberOfLines={1}
357 >
358 {props.label}
359 </Text>
360 </View>
361 {props.connectionError ? (
362 <Text
363 aria-hidden
364 onTextLayout={onMeasuredErrorTextLayout}
365 className={cn("absolute inset-x-0 -z-[1] text-xs opacity-0", statusClassName)}
366 >
367 {measuredErrorText}
368 </Text>
369 ) : null}
370 <StatusContainer
371 {...(errorCanExpand
372 ? { accessibilityRole: "button" as const, onPress: props.onToggleError }
373 : {})}
374 className="min-w-0 flex-row items-start gap-1"
375 >
376 <Text
377 className={cn("min-w-0 flex-1 text-xs", statusClassName)}
378 numberOfLines={isErrorExpanded ? undefined : 1}
379 >
380 {statusText}
381 {errorTraceId ? (
382 <>
383 {" Trace ID: "}
384 <Text
385 accessibilityHint="Copies the trace ID"
386 accessibilityRole="button"
387 className={cn("text-xs underline decoration-dotted", statusClassName)}
388 onLongPress={(event) => {
389 event.stopPropagation();
390 copyTextWithHaptic(errorTraceId, { target: "connection-trace-id" });
391 }}
392 onPress={(event) => {
393 event.stopPropagation();
394 }}
395 >
396 {errorTraceId}
397 </Text>
398 </>
399 ) : null}
400 </Text>
401 {errorCanExpand ? (
402 <SymbolView
403 name="chevron.down"
404 size={10}
405 tintColorClassName={"accent-chevron"}
406 type="monochrome"
407 style={{
408 marginTop: 3,
409 transform: [{ rotate: isErrorExpanded ? "180deg" : "0deg" }],
410 }}
411 />
412 ) : null}
413 </StatusContainer>
414 </View>
415 <ThemedSwitch
416 disabled={props.disabled}
417 onValueChange={props.onValueChange}
418 value={props.value}
419 />
420 </View>
421 );
422}
423
424function CopyTraceIdButton(props: { readonly traceId: string }) {
425 return (
426 <Pressable
427 accessibilityRole="button"
428 onPress={() => {
429 copyTextWithHaptic(props.traceId, { target: "connection-trace-id" });
430 }}
431 className="self-start flex-row items-center gap-1.5 rounded-full bg-subtle px-3 py-2 active:opacity-70"
432 >
433 <SymbolView
434 name="doc.on.doc"
435 size={12}
436 tintColorClassName={"accent-icon"}
437 type="monochrome"
438 />
439 <Text className="text-xs font-t3-bold text-foreground">Copy trace ID</Text>
440 </Pressable>
441 );
442}