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