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

CloudEnvironmentRows.tsx

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