Open History to see the last commit
1import { Button } from "../../components/ui/Button";
2import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
3import { ConnectionTraceId } from "./ConnectionTraceId";
4import { useAuth } from "@clerk/expo";
5import { SymbolView } from "../../components/ui/AppSymbol";
6import {
7 hasSavedBearerRoute,
8 type EnvironmentConnectionPhase,
9} from "@t3tools/client-runtime/connection";
10import {
11 type EnvironmentId,
12 type EnvironmentMachineKind,
13 type ExecutionEnvironmentDescriptor,
14 resolveEnvironmentMachineKind,
15} from "@t3tools/contracts";
16import { useAtomValue } from "@effect/atom-react";
17import { useCallback, useState } from "react";
18import { Pressable, type TextLayoutEvent, View } from "react-native";
19
20import { AppText as Text } from "../../components/ui/AppText";
21import { EnvironmentMachineSymbol } from "../../components/EnvironmentMachineSymbol";
22import { ThemedSwitch } from "../../components/ui/ThemedSwitch";
23import { cn } from "../../lib/cn";
24import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
25import type { ConnectedEnvironmentSummary } from "../../state/remote-runtime-types";
26import { serverEnvironment } from "../../state/server";
27import { environmentPresentations } from "../../state/presentation";
28import { availableCloudEnvironmentPresentation } from "../cloud/cloudEnvironmentPresentation";
29import { hasCloudPublicConfig } from "../cloud/publicConfig";
30import { ConnectionStatusDot } from "./ConnectionStatusDot";
31import { useConnectionDiagnosis } from "./ConnectionDiagnosisDetails";
32import { environmentStatusText } from "./environmentStatusText";
33import { type RelayEnvironmentView, useConnectionController } from "./useConnectionController";
34
35interface CloudEnvironmentRowsProps {
36 readonly connectedCloudEnvironments: ReadonlyArray<ConnectedEnvironmentSummary>;
37 readonly onOpenEnvironment?: (environmentId: EnvironmentId) => void;
38 readonly onSetEnvironmentEnabled: (environmentId: EnvironmentId, enabled: boolean) => void;
39 readonly onRemoveEnvironment: (environmentId: EnvironmentId) => void;
40 readonly showcaseAvailableEnvironments?: ReadonlyArray<RelayEnvironmentView>;
41 readonly showcaseSignedIn?: boolean;
42 readonly showHeader?: boolean;
43}
44
45export function CloudEnvironmentRows(props: CloudEnvironmentRowsProps) {
46 // Showcase lacks ClerkProvider; use fixture auth state to avoid a throwing useAuth call.
47 if (props.showcaseSignedIn !== undefined) {
48 return props.showcaseSignedIn ? <CloudEnvironmentRowsContent {...props} /> : null;
49 }
50 // No cloud config means no `ClerkProvider` either, so `useAuth` would throw.
51 if (!hasCloudPublicConfig()) {
52 return <ConnectedOnlyCloudEnvironmentRows {...props} />;
53 }
54 return <SignedInCloudEnvironmentRows {...props} />;
55}
56
57function SignedInCloudEnvironmentRows(props: CloudEnvironmentRowsProps) {
58 const { isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
59 if (!isSignedIn) return <ConnectedOnlyCloudEnvironmentRows {...props} />;
60 return <CloudEnvironmentRowsContent {...props} />;
61}
62
63function ConnectedOnlyCloudEnvironmentRows(props: CloudEnvironmentRowsProps) {
64 if (props.connectedCloudEnvironments.length === 0) return null;
65 return <CloudEnvironmentRowsContent {...props} discoveryAvailable={false} />;
66}
67
68function CloudEnvironmentRowsContent(
69 props: CloudEnvironmentRowsProps & { readonly discoveryAvailable?: boolean },
70) {
71 const controller = useConnectionController();
72 const discoveryAvailable = props.discoveryAvailable ?? true;
73 const availableCloudEnvironments = discoveryAvailable
74 ? (props.showcaseAvailableEnvironments ?? controller.availableRelayEnvironments)
75 : [];
76 const [expandedErrorId, setExpandedErrorId] = useState<string | null>(null);
77 const hasCloudRows =
78 props.connectedCloudEnvironments.length > 0 || availableCloudEnvironments.length > 0;
79
80 const handleConnectCloudEnvironment = useCallback(
81 (entry: RelayEnvironmentView) => controller.connectRelayEnvironment(entry.environment),
82 [controller],
83 );
84
85 const discoveredDescriptors = new Map(
86 controller.relayEnvironments.flatMap((entry) =>
87 entry.status?.descriptor === undefined
88 ? []
89 : [[entry.environment.environmentId, entry.status.descriptor] as const],
90 ),
91 );
92
93 const handleToggleCloudError = useCallback((environmentId: string) => {
94 setExpandedErrorId((current) => (current === environmentId ? null : environmentId));
95 }, []);
96
97 const showHeader = props.showHeader ?? true;
98
99 return (
100 <View collapsable={false} className={cn("gap-3", showHeader && "mt-5")}>
101 {showHeader ? (
102 <View className="px-1">
103 <Text className="text-sm font-t3-bold uppercase text-foreground-muted">T3 Connect</Text>
104 </View>
105 ) : null}
106
107 {hasCloudRows ? (
108 <View collapsable={false} className="overflow-hidden rounded-[24px] bg-grouped-card">
109 {props.connectedCloudEnvironments.map((environment) => (
110 <ConnectedCloudEnvironmentRow
111 key={environment.environmentId}
112 environment={environment}
113 descriptor={discoveredDescriptors.get(environment.environmentId)}
114 onSetEnabled={(enabled) =>
115 props.onSetEnvironmentEnabled(environment.environmentId, enabled)
116 }
117 onRemove={() => props.onRemoveEnvironment(environment.environmentId)}
118 onOpen={
119 props.onOpenEnvironment
120 ? () => props.onOpenEnvironment?.(environment.environmentId)
121 : undefined
122 }
123 errorExpanded={expandedErrorId === environment.environmentId}
124 onToggleError={() => handleToggleCloudError(environment.environmentId)}
125 />
126 ))}
127 {availableCloudEnvironments.map((environment) => (
128 <CloudEnvironmentRow
129 key={environment.environment.environmentId}
130 environment={environment}
131 showChevron={props.onOpenEnvironment !== undefined}
132 onConnect={() => handleConnectCloudEnvironment(environment)}
133 errorExpanded={expandedErrorId === environment.environment.environmentId}
134 onToggleError={() => handleToggleCloudError(environment.environment.environmentId)}
135 />
136 ))}
137 </View>
138 ) : controller.relayDiscovery.isRefreshing ? (
139 <View collapsable={false} className="items-center gap-3 rounded-[24px] bg-grouped-card p-6">
140 <AppActivityIndicator colorClassName={"accent-icon"} />
141 <Text className="text-center text-sm leading-normal text-foreground-muted">
142 Loading linked cloud environments.
143 </Text>
144 </View>
145 ) : controller.relayDiscovery.error ? null : (
146 <View collapsable={false} className="rounded-[24px] bg-grouped-card p-5">
147 <Text className="text-sm leading-normal text-foreground-muted">
148 No additional linked cloud environments.
149 </Text>
150 </View>
151 )}
152
153 {discoveryAvailable &&
154 controller.relayDiscovery.error &&
155 !controller.relayDiscovery.isRefreshing ? (
156 <View collapsable={false} className="gap-3 rounded-[24px] bg-grouped-card p-5">
157 <Text className="text-base font-t3-bold text-foreground">
158 Could not load T3 Connect environments
159 </Text>
160 <Text className="text-sm text-foreground-muted">{controller.relayDiscovery.error}</Text>
161 {controller.relayDiscovery.errorTraceId ? (
162 <CopyTraceIdButton traceId={controller.relayDiscovery.errorTraceId} />
163 ) : null}
164 <Button
165 label="Try again"
166 tone="secondary"
167 onPress={() => {
168 void controller.refreshRelayEnvironments();
169 }}
170 />
171 </View>
172 ) : null}
173 </View>
174 );
175}
176
177function ConnectedCloudEnvironmentRow(props: {
178 readonly environment: ConnectedEnvironmentSummary;
179 readonly descriptor: ExecutionEnvironmentDescriptor | undefined;
180 readonly errorExpanded: boolean;
181 readonly onSetEnabled: (enabled: boolean) => void;
182 readonly onRemove: () => void;
183 readonly onOpen?: (() => void) | undefined;
184 readonly onToggleError: () => void;
185}) {
186 const serverConfig = useAtomValue(
187 serverEnvironment.configValueAtom(props.environment.environmentId),
188 );
189 const unsupported = props.environment.connectionState === "unsupported";
190 const presentation = useAtomValue(
191 environmentPresentations.presentationAtom(props.environment.environmentId),
192 );
193 const canRetry = presentation !== null && hasSavedBearerRoute(presentation.entry);
194 const enabled = props.environment.isEnabled && !unsupported;
195 const { diagnosis } = useConnectionDiagnosis(props.environment.environmentId, presentation);
196 const [lastDescriptor, setLastDescriptor] = useState(props.descriptor);
197 if (props.descriptor !== undefined && props.descriptor !== lastDescriptor) {
198 setLastDescriptor(props.descriptor);
199 }
200 return (
201 <CloudEnvironmentRowShell
202 opensDetails={props.onOpen !== undefined}
203 onOpen={props.onOpen}
204 onRemove={props.onRemove}
205 connectionError={enabled || unsupported ? props.environment.connectionError : null}
206 connectionErrorTraceId={enabled ? props.environment.connectionErrorTraceId : null}
207 connectionState={enabled || unsupported ? props.environment.connectionState : "available"}
208 errorExpanded={props.errorExpanded}
209 label={props.environment.environmentLabel}
210 machine={resolveEnvironmentMachineKind(
211 serverConfig ?? (lastDescriptor === undefined ? null : { environment: lastDescriptor }),
212 )}
213 onValueChange={props.onSetEnabled}
214 onToggleError={props.onToggleError}
215 disabled={unsupported && !canRetry}
216 {...(enabled || unsupported
217 ? diagnosis
218 ? { statusText: diagnosis.headline }
219 : {}
220 : { statusText: "Off" })}
221 value={enabled}
222 />
223 );
224}
225
226function CloudEnvironmentRow(props: {
227 readonly environment: RelayEnvironmentView;
228 readonly showChevron: boolean;
229 readonly errorExpanded: boolean;
230 readonly onConnect: () => void;
231 readonly onToggleError: () => void;
232}) {
233 const presentation = availableCloudEnvironmentPresentation({
234 isStatusPending: props.environment.availability === "checking",
235 status: props.environment.status,
236 statusError: props.environment.error,
237 statusErrorTraceId: props.environment.traceId,
238 });
239
240 return (
241 <CloudEnvironmentRowShell
242 showChevron={props.showChevron}
243 connectionError={presentation.connectionError}
244 connectionErrorTraceId={presentation.connectionErrorTraceId}
245 connectionState={presentation.connectionState}
246 errorExpanded={props.errorExpanded}
247 label={props.environment.environment.label}
248 machine={resolveEnvironmentMachineKind(
249 props.environment.status?.descriptor === undefined
250 ? null
251 : { environment: props.environment.status.descriptor },
252 )}
253 onValueChange={(enabled) => {
254 if (enabled) {
255 props.onConnect();
256 }
257 }}
258 onToggleError={props.onToggleError}
259 disabled={presentation.connectionState === "unsupported"}
260 statusText={presentation.statusText}
261 value={false}
262 />
263 );
264}
265
266function CloudEnvironmentRowShell(props: {
267 readonly showChevron?: boolean;
268 readonly opensDetails?: boolean;
269 readonly onOpen?: (() => void) | undefined;
270 readonly onRemove?: (() => void) | undefined;
271 readonly connectionError: string | null;
272 readonly connectionErrorTraceId: string | null;
273 readonly connectionState: EnvironmentConnectionPhase;
274 readonly disabled?: boolean;
275 readonly errorExpanded: boolean;
276 readonly label: string;
277 readonly machine: EnvironmentMachineKind;
278 readonly onToggleError: () => void;
279 readonly onValueChange: (enabled: boolean) => void;
280 readonly statusText?: string;
281 readonly value: boolean;
282}) {
283 const isRetrying =
284 props.connectionState === "connecting" || props.connectionState === "reconnecting";
285 const shouldPulse = isRetrying;
286 const statusText =
287 props.statusText ??
288 environmentStatusText({
289 phase: props.connectionState,
290 error: props.connectionError,
291 traceId: props.connectionErrorTraceId,
292 });
293 const statusClassName =
294 props.connectionError && props.connectionState !== "unsupported"
295 ? "text-danger-foreground"
296 : "text-foreground-muted";
297 const [errorMeasurement, setErrorMeasurement] = useState<{
298 readonly text: string;
299 readonly lineCount: number;
300 } | null>(null);
301 const errorTraceId = props.connectionErrorTraceId;
302 const measuredErrorText = errorTraceId ? `${statusText} Trace ID: ${errorTraceId}` : statusText;
303 const errorLineCount =
304 errorMeasurement?.text === measuredErrorText ? errorMeasurement.lineCount : 0;
305 const errorCanExpand = props.connectionError !== null && errorLineCount > 1;
306 const isErrorExpanded = errorCanExpand && props.errorExpanded;
307 const StatusContainer = errorCanExpand ? Pressable : View;
308 const ContentContainer = props.onOpen || props.onRemove ? Pressable : View;
309 const ChevronContainer = props.onOpen || props.onRemove ? Pressable : View;
310 const onMeasuredErrorTextLayout = useCallback(
311 (event: TextLayoutEvent) => {
312 if (!props.connectionError) {
313 return;
314 }
315 const nextLineCount = event.nativeEvent.lines.length;
316 setErrorMeasurement((currentMeasurement) =>
317 currentMeasurement?.text === measuredErrorText &&
318 currentMeasurement.lineCount === nextLineCount
319 ? currentMeasurement
320 : { text: measuredErrorText, lineCount: nextLineCount },
321 );
322 },
323 [measuredErrorText, props.connectionError],
324 );
325 return (
326 <View collapsable={false} className="flex-row items-center gap-3 bg-grouped-card px-4 py-3.5">
327 <ContentContainer
328 className="min-w-0 flex-1 gap-0.5"
329 accessibilityHint={props.onRemove ? "Long press to remove from this device" : undefined}
330 accessibilityRole={props.onOpen ? "button" : undefined}
331 accessibilityLabel={
332 props.onOpen
333 ? `Manage ${props.label}`
334 : props.onRemove
335 ? `Remove ${props.label} from this device`
336 : undefined
337 }
338 onPress={props.onOpen}
339 onLongPress={props.onRemove}
340 >
341 <View className="min-w-0 flex-row items-center gap-2">
342 <ConnectionStatusDot state={props.connectionState} pulse={shouldPulse} size={7} />
343 <EnvironmentMachineSymbol
344 kind={props.machine}
345 size={14}
346 tintColorClassName="accent-foreground-muted"
347 />
348 <Text
349 className="min-w-0 flex-shrink text-base font-t3-bold leading-snug text-foreground"
350 numberOfLines={1}
351 >
352 {props.label}
353 </Text>
354 </View>
355 {props.connectionError ? (
356 <Text
357 aria-hidden
358 onTextLayout={onMeasuredErrorTextLayout}
359 className={cn("absolute inset-x-0 -z-[1] text-xs opacity-0", statusClassName)}
360 >
361 {measuredErrorText}
362 </Text>
363 ) : null}
364 <StatusContainer
365 {...(errorCanExpand
366 ? { accessibilityRole: "button" as const, onPress: props.onToggleError }
367 : {})}
368 className="min-w-0 flex-row items-start gap-1"
369 >
370 <Text
371 className={cn("min-w-0 flex-1 text-xs", statusClassName)}
372 numberOfLines={isErrorExpanded ? undefined : 1}
373 >
374 {statusText}
375 {errorTraceId ? (
376 <ConnectionTraceId
377 traceId={errorTraceId}
378 tone={
379 props.connectionError && props.connectionState !== "unsupported"
380 ? "danger"
381 : "muted"
382 }
383 activation="longPress"
384 />
385 ) : null}
386 </Text>
387 {errorCanExpand ? (
388 <SymbolView
389 name="chevron.down"
390 size={10}
391 tintColorClassName={"accent-chevron"}
392 type="monochrome"
393 style={{
394 marginTop: 3,
395 transform: [{ rotate: isErrorExpanded ? "180deg" : "0deg" }],
396 }}
397 />
398 ) : null}
399 </StatusContainer>
400 </ContentContainer>
401 <ThemedSwitch
402 accessibilityLabel={`Enable ${props.label}`}
403 style={{ alignSelf: "center" }}
404 disabled={props.disabled}
405 onValueChange={props.onValueChange}
406 value={props.value}
407 />
408 {props.opensDetails || props.showChevron ? (
409 <ChevronContainer
410 accessibilityRole={props.onOpen ? "button" : undefined}
411 accessibilityLabel={
412 props.onOpen
413 ? `Manage ${props.label}`
414 : props.onRemove
415 ? `Remove ${props.label} from this device`
416 : undefined
417 }
418 accessibilityHint={props.onRemove ? "Long press to remove from this device" : undefined}
419 onPress={props.onOpen}
420 onLongPress={props.onRemove}
421 style={{
422 opacity: props.opensDetails ? 1 : 0.4,
423 minWidth: 44,
424 minHeight: 44,
425 alignItems: "center",
426 justifyContent: "center",
427 }}
428 >
429 <SymbolView name="chevron.right" size={12} tintColorClassName="accent-icon-subtle" />
430 </ChevronContainer>
431 ) : null}
432 </View>
433 );
434}
435
436function CopyTraceIdButton(props: { readonly traceId: string }) {
437 return (
438 <Button
439 label="Copy trace ID"
440 tone="secondary"
441 onPress={() => {
442 copyTextWithHaptic(props.traceId, { target: "connection-trace-id" });
443 }}
444 icon="doc.on.doc"
445 />
446 );
447}