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