Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

CloudEnvironmentRows.tsx

380 lines14.2 KB

1import { useAuth } from "@clerk/expo";
2import { SymbolView } from "../../components/AppSymbol";
3import {
4 connectionStatusText,
5 type EnvironmentConnectionPhase,
6} from "@t3tools/client-runtime/connection";
7import type { EnvironmentId } from "@t3tools/contracts";
8import { useCallback, useState } from "react";
9import {
10 ActivityIndicator,
11 Pressable,
12 Switch,
13 type NativeSyntheticEvent,
14 type TextLayoutEventData,
15 View,
16} from "react-native";
17​
18import { AppText as Text } from "../../components/AppText";
19import { cn } from "../../lib/cn";
20import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
21import { useThemeColor } from "../../lib/useThemeColor";
22import type { ConnectedEnvironmentSummary } from "../../state/remote-runtime-types";
23import { availableCloudEnvironmentPresentation } from "../cloud/cloudEnvironmentPresentation";
24import { ConnectionStatusDot } from "./ConnectionStatusDot";
25import { type RelayEnvironmentView, useConnectionController } from "./useConnectionController";
26​
27/**
28 * "T3 Connect" section: every environment published to the signed-in account,
29 * with connect switches, availability status, refresh, and loading/error
30 * states. Shared between the Settings environments screen and the T3 Connect
31 * onboarding sheet.
32 */
33export function CloudEnvironmentRows(props: {
34 readonly connectedCloudEnvironments: ReadonlyArray<ConnectedEnvironmentSummary>;
35 readonly onReconnectEnvironment: (environmentId: EnvironmentId) => void;
36 readonly showcaseAvailableEnvironments?: ReadonlyArray<RelayEnvironmentView>;
37 readonly showcaseSignedIn?: boolean;
38 /**
39 * Hide the "T3 Connect" section title + refresh button for hosts that
40 * provide their own chrome (the onboarding sheet's native header and
41 * pull-to-refresh).
42 */
43 readonly showHeader?: boolean;
44}) {
45 const { isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
46 const controller = useConnectionController();
47 const iconColor = useThemeColor("--color-icon");
48 const availableCloudEnvironments =
49 props.showcaseAvailableEnvironments ?? controller.availableRelayEnvironments;
50 const [expandedErrorId, setExpandedErrorId] = useState<string | null>(null);
51 const hasCloudRows =
52 props.connectedCloudEnvironments.length > 0 || availableCloudEnvironments.length > 0;
53​
54 const handleConnectCloudEnvironment = useCallback(
55 (entry: RelayEnvironmentView) => controller.connectRelayEnvironment(entry.environment),
56 [controller],
57 );
58​
59 const handleDisconnectCloudEnvironment = useCallback(
60 (environmentId: EnvironmentId) => controller.removeEnvironment(environmentId),
61 [controller],
62 );
63​
64 const handleToggleCloudError = useCallback((environmentId: string) => {
65 setExpandedErrorId((current) => (current === environmentId ? null : environmentId));
66 }, []);
67​
68 const showHeader = props.showHeader ?? true;
69​
70 if (!(props.showcaseSignedIn ?? isSignedIn)) return null;
71​
72 return (
73 <View collapsable={false} className={cn("gap-3", showHeader && "mt-5")}>
74 {showHeader ? (
75 <View className="flex-row items-center justify-between px-1">
76 <Text className="text-sm font-t3-bold uppercase text-foreground-muted">T3 Connect</Text>
77 <Pressable
78 accessibilityRole="button"
79 disabled={controller.relayDiscovery.isRefreshing}
80 onPress={() => {
81 void controller.refreshRelayEnvironments();
82 }}
83 className="h-9 w-9 items-center justify-center rounded-full bg-subtle active:opacity-70 disabled:opacity-50"
84 >
85 {controller.relayDiscovery.isRefreshing ? (
86 <ActivityIndicator color={iconColor} size="small" />
87 ) : (
88 <SymbolView
89 name="arrow.clockwise"
90 size={14}
91 tintColor={iconColor}
92 type="monochrome"
93 />
94 )}
95 </Pressable>
96 </View>
97 ) : null}
98​
99 {hasCloudRows ? (
100 <View collapsable={false} className="overflow-hidden rounded-[24px] bg-card">
101 {props.connectedCloudEnvironments.map((environment, index) => (
102 <ConnectedCloudEnvironmentRow
103 key={environment.environmentId}
104 environment={environment}
105 borderTop={index !== 0}
106 onConnect={() => props.onReconnectEnvironment(environment.environmentId)}
107 onDisconnect={() => handleDisconnectCloudEnvironment(environment.environmentId)}
108 errorExpanded={expandedErrorId === environment.environmentId}
109 onToggleError={() => handleToggleCloudError(environment.environmentId)}
110 />
111 ))}
112 {availableCloudEnvironments.map((environment, index) => (
113 <CloudEnvironmentRow
114 key={environment.environment.environmentId}
115 environment={environment}
116 borderTop={props.connectedCloudEnvironments.length > 0 || index !== 0}
117 onConnect={() => handleConnectCloudEnvironment(environment)}
118 errorExpanded={expandedErrorId === environment.environment.environmentId}
119 onToggleError={() => handleToggleCloudError(environment.environment.environmentId)}
120 />
121 ))}
122 </View>
123 ) : controller.relayDiscovery.isRefreshing ? (
124 <View collapsable={false} className="items-center gap-3 rounded-[24px] bg-card p-6">
125 <ActivityIndicator color={iconColor} />
126 <Text className="text-center text-sm leading-normal text-foreground-muted">
127 Loading linked cloud environments.
128 </Text>
129 </View>
130 ) : controller.relayDiscovery.error ? null : (
131 <View collapsable={false} className="rounded-[24px] bg-card p-5">
132 <Text className="text-sm leading-normal text-foreground-muted">
133 No additional linked cloud environments.
134 </Text>
135 </View>
136 )}
137​
138 {/* Rendered alongside any connected rows — a failed discovery must not
139 hide behind an otherwise-healthy list. */}
140 {controller.relayDiscovery.error && !controller.relayDiscovery.isRefreshing ? (
141 <View collapsable={false} className="gap-3 rounded-[24px] bg-card p-5">
142 <Text className="text-base font-t3-bold text-foreground">
143 Could not load T3 Connect environments
144 </Text>
145 <Text className="text-sm text-foreground-muted">{controller.relayDiscovery.error}</Text>
146 {controller.relayDiscovery.errorTraceId ? (
147 <CopyTraceIdButton traceId={controller.relayDiscovery.errorTraceId} />
148 ) : null}
149 <Pressable
150 accessibilityRole="button"
151 onPress={() => {
152 void controller.refreshRelayEnvironments();
153 }}
154 className="self-start rounded-full bg-subtle px-3.5 py-2 active:opacity-70"
155 >
156 <Text className="text-xs font-t3-bold text-foreground">Try again</Text>
157 </Pressable>
158 </View>
159 ) : null}
160 </View>
161 );
163​
164function ConnectedCloudEnvironmentRow(props: {
165 readonly environment: ConnectedEnvironmentSummary;
166 readonly borderTop: boolean;
167 readonly errorExpanded: boolean;
168 readonly onConnect: () => void;
169 readonly onDisconnect: () => void;
170 readonly onToggleError: () => void;
171}) {
172 return (
173 <CloudEnvironmentRowShell
174 borderTop={props.borderTop}
175 connectionError={props.environment.connectionError}
176 connectionErrorTraceId={props.environment.connectionErrorTraceId}
177 connectionState={props.environment.connectionState}
178 errorExpanded={props.errorExpanded}
179 label={props.environment.environmentLabel}
180 onValueChange={(enabled) => {
181 if (enabled) {
182 props.onConnect();
183 return;
184 }
185 props.onDisconnect();
186 }}
187 onToggleError={props.onToggleError}
188 value={props.environment.connectionState !== "available"}
189 />
190 );
192​
193function CloudEnvironmentRow(props: {
194 readonly environment: RelayEnvironmentView;
195 readonly borderTop: boolean;
196 readonly errorExpanded: boolean;
197 readonly onConnect: () => void;
198 readonly onToggleError: () => void;
199}) {
200 const presentation = availableCloudEnvironmentPresentation({
201 isStatusPending: props.environment.availability === "checking",
202 status: props.environment.status,
203 statusError: props.environment.error,
204 statusErrorTraceId: props.environment.traceId,
205 });
206​
207 return (
208 <CloudEnvironmentRowShell
209 borderTop={props.borderTop}
210 connectionError={presentation.connectionError}
211 connectionErrorTraceId={presentation.connectionErrorTraceId}
212 connectionState={presentation.connectionState}
213 errorExpanded={props.errorExpanded}
214 label={props.environment.environment.label}
215 onValueChange={(enabled) => {
216 if (enabled) {
217 props.onConnect();
218 }
219 }}
220 onToggleError={props.onToggleError}
221 statusText={presentation.statusText}
222 value={false}
223 />
224 );
226​
227function CloudEnvironmentRowShell(props: {
228 readonly borderTop: boolean;
229 readonly connectionError: string | null;
230 readonly connectionErrorTraceId: string | null;
231 readonly connectionState: EnvironmentConnectionPhase;
232 readonly disabled?: boolean;
233 readonly errorExpanded: boolean;
234 readonly label: string;
235 readonly onToggleError: () => void;
236 readonly onValueChange: (enabled: boolean) => void;
237 readonly statusText?: string;
238 readonly value: boolean;
239}) {
240 const activeTrack = String(useThemeColor("--color-switch-active"));
241 const track = String(useThemeColor("--color-secondary-border"));
242 const chevron = useThemeColor("--color-chevron");
243 const isRetrying =
244 props.connectionState === "connecting" || props.connectionState === "reconnecting";
245 const shouldPulse = isRetrying;
246 const statusText =
247 props.statusText ??
248 connectionStatusText({
249 phase: props.connectionState,
250 error: props.connectionError,
251 traceId: props.connectionErrorTraceId,
252 });
253 const statusClassName = props.connectionError
254 ? "text-rose-500 dark:text-rose-400"
255 : "text-foreground-muted";
256 const [errorMeasurement, setErrorMeasurement] = useState<{
257 readonly text: string;
258 readonly lineCount: number;
259 } | null>(null);
260 const errorTraceId = props.connectionErrorTraceId;
261 const measuredErrorText = errorTraceId ? `${statusText} Trace ID: ${errorTraceId}` : statusText;
262 const errorLineCount =
263 errorMeasurement?.text === measuredErrorText ? errorMeasurement.lineCount : 0;
264 const errorCanExpand = props.connectionError !== null && errorLineCount > 1;
265 const isErrorExpanded = errorCanExpand && props.errorExpanded;
266 const StatusContainer = errorCanExpand ? Pressable : View;
267 const onMeasuredErrorTextLayout = useCallback(
268 (event: NativeSyntheticEvent<TextLayoutEventData>) => {
269 if (!props.connectionError) {
270 return;
271 }
272 const nextLineCount = event.nativeEvent.lines.length;
273 setErrorMeasurement((currentMeasurement) =>
274 currentMeasurement?.text === measuredErrorText &&
275 currentMeasurement.lineCount === nextLineCount
276 ? currentMeasurement
277 : { text: measuredErrorText, lineCount: nextLineCount },
278 );
279 },
280 [measuredErrorText, props.connectionError],
281 );
282 return (
283 <View
284 collapsable={false}
285 className={cn(
286 "flex-row items-center gap-3 bg-card px-4 py-3.5",
287 props.borderTop && "border-t border-border",
288 )}
289 >
290 <View className="min-w-0 flex-1 gap-0.5">
291 <View className="min-w-0 flex-row items-center gap-2">
292 <ConnectionStatusDot state={props.connectionState} pulse={shouldPulse} size={7} />
293 <Text
294 className="min-w-0 flex-shrink text-base font-t3-bold leading-snug text-foreground"
295 numberOfLines={1}
296 >
297 {props.label}
298 </Text>
299 </View>
300 {props.connectionError ? (
301 <Text
302 aria-hidden
303 onTextLayout={onMeasuredErrorTextLayout}
304 className={cn("absolute inset-x-0 -z-[1] text-xs opacity-0", statusClassName)}
305 >
306 {measuredErrorText}
307 </Text>
308 ) : null}
309 <StatusContainer
310 {...(errorCanExpand
311 ? { accessibilityRole: "button" as const, onPress: props.onToggleError }
312 : {})}
313 className="min-w-0 flex-row items-start gap-1"
314 >
315 <Text
316 className={cn("min-w-0 flex-1 text-xs", statusClassName)}
317 numberOfLines={isErrorExpanded ? undefined : 1}
318 >
319 {statusText}
320 {errorTraceId ? (
321 <>
322 {" Trace ID: "}
323 <Text
324 accessibilityHint="Copies the trace ID"
325 accessibilityRole="button"
326 className={cn("text-xs underline decoration-dotted", statusClassName)}
327 onLongPress={(event) => {
328 event.stopPropagation();
329 copyTextWithHaptic(errorTraceId, { target: "connection-trace-id" });
330 }}
331 onPress={(event) => {
332 event.stopPropagation();
333 }}
334 >
335 {errorTraceId}
336 </Text>
337 </>
338 ) : null}
339 </Text>
340 {errorCanExpand ? (
341 <SymbolView
342 name="chevron.down"
343 size={10}
344 tintColor={chevron}
345 type="monochrome"
346 style={{
347 marginTop: 3,
348 transform: [{ rotate: isErrorExpanded ? "180deg" : "0deg" }],
349 }}
350 />
351 ) : null}
352 </StatusContainer>
353 </View>
354 <Switch
355 disabled={props.disabled}
356 ios_backgroundColor={track}
357 onValueChange={props.onValueChange}
358 trackColor={{ false: track, true: activeTrack }}
359 value={props.value}
360 />
361 </View>
362 );
364​
365function CopyTraceIdButton(props: { readonly traceId: string }) {
366 const iconColor = useThemeColor("--color-icon");
367​
368 return (
369 <Pressable
370 accessibilityRole="button"
371 onPress={() => {
372 copyTextWithHaptic(props.traceId, { target: "connection-trace-id" });
373 }}
374 className="self-start flex-row items-center gap-1.5 rounded-full bg-subtle px-3 py-2 active:opacity-70"
375 >
376 <SymbolView name="doc.on.doc" size={12} tintColor={iconColor} type="monochrome" />
377 <Text className="text-xs font-t3-bold text-foreground">Copy trace ID</Text>
378 </Pressable>
379 );