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