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