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

CloudEnvironmentRows.tsx

468 lines18.3 KB

1import { useAuth } from "@clerk/expo";
2import { SymbolView } from "../../components/AppSymbol";
3import {
4 connectionStatusText,
5 type EnvironmentConnectionPhase,
6} from "@t3tools/client-runtime/connection";
7import {
8 type EnvironmentId,
9 type EnvironmentMachineKind,
10 type ExecutionEnvironmentDescriptor,
11 resolveEnvironmentMachineKind,
12} from "@t3tools/contracts";
13import { useAtomValue } from "@effect/atom-react";
14import { useCallback, useState } from "react";
15import {
16 ActivityIndicator,
17 Pressable,
18 type NativeSyntheticEvent,
19 type TextLayoutEventData,
20 View,
21} from "react-native";
22​
23import { AppText as Text } from "../../components/AppText";
24import { EnvironmentMachineSymbol } from "../../components/EnvironmentMachineSymbol";
25import { ThemedSwitch } from "../../components/ThemedSwitch";
26import { cn } from "../../lib/cn";
27import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
28import type { ConnectedEnvironmentSummary } from "../../state/remote-runtime-types";
29import { serverEnvironment } from "../../state/server";
30import { availableCloudEnvironmentPresentation } from "../cloud/cloudEnvironmentPresentation";
31import { hasCloudPublicConfig } from "../cloud/publicConfig";
32import { ConnectionStatusDot } from "./ConnectionStatusDot";
33import { type RelayEnvironmentView, useConnectionController } from "./useConnectionController";
34​
35interface CloudEnvironmentRowsProps {
36 readonly connectedCloudEnvironments: ReadonlyArray<ConnectedEnvironmentSummary>;
37 readonly onSetEnvironmentEnabled: (environmentId: EnvironmentId, enabled: boolean) => void;
38 /** Long-press on a saved row. The callback owns the confirm. */
39 readonly onRemoveEnvironment: (environmentId: EnvironmentId) => void;
40 readonly showcaseAvailableEnvironments?: ReadonlyArray<RelayEnvironmentView>;
41 readonly showcaseSignedIn?: boolean;
42 /**
43 * Hide the "T3 Connect" section title + refresh button for hosts that
44 * provide their own chrome (the onboarding sheet's native header and
45 * pull-to-refresh).
46 */
47 readonly showHeader?: boolean;
49​
50/**
51 * "T3 Connect" section: every environment published to the signed-in account,
52 * with connect switches, availability status, refresh, 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} />;
74​
75function SignedInCloudEnvironmentRows(props: CloudEnvironmentRowsProps) {
76 const { isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
77 if (!isSignedIn) return <ConnectedOnlyCloudEnvironmentRows {...props} />;
78 return <CloudEnvironmentRowsContent {...props} />;
80​
81function ConnectedOnlyCloudEnvironmentRows(props: CloudEnvironmentRowsProps) {
82 if (props.connectedCloudEnvironments.length === 0) return null;
83 return <CloudEnvironmentRowsContent {...props} discoveryAvailable={false} />;
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="flex-row items-center justify-between px-1">
123 <Text className="text-sm font-t3-bold uppercase text-foreground-muted">T3 Connect</Text>
124 {discoveryAvailable ? (
125 <Pressable
126 accessibilityRole="button"
127 disabled={controller.relayDiscovery.isRefreshing}
128 onPress={() => {
129 void controller.refreshRelayEnvironments();
130 }}
131 className="h-9 w-9 items-center justify-center rounded-full bg-subtle active:opacity-70 disabled:opacity-50"
132 >
133 {controller.relayDiscovery.isRefreshing ? (
134 <ActivityIndicator colorClassName={"accent-icon"} size="small" />
135 ) : (
136 <SymbolView
137 name="arrow.clockwise"
138 size={14}
139 tintColorClassName={"accent-icon"}
140 type="monochrome"
141 />
142 )}
143 </Pressable>
144 ) : null}
145 </View>
146 ) : null}
147​
148 {hasCloudRows ? (
149 <View collapsable={false} className="overflow-hidden rounded-[24px] bg-card">
150 {props.connectedCloudEnvironments.map((environment, index) => (
151 <ConnectedCloudEnvironmentRow
152 key={environment.environmentId}
153 environment={environment}
154 descriptor={discoveredDescriptors.get(environment.environmentId)}
155 borderTop={index !== 0}
156 onSetEnabled={(enabled) =>
157 props.onSetEnvironmentEnabled(environment.environmentId, enabled)
158 }
159 onRemove={() => props.onRemoveEnvironment(environment.environmentId)}
160 errorExpanded={expandedErrorId === environment.environmentId}
161 onToggleError={() => handleToggleCloudError(environment.environmentId)}
162 />
163 ))}
164 {availableCloudEnvironments.map((environment, index) => (
165 <CloudEnvironmentRow
166 key={environment.environment.environmentId}
167 environment={environment}
168 borderTop={props.connectedCloudEnvironments.length > 0 || index !== 0}
169 onConnect={() => handleConnectCloudEnvironment(environment)}
170 errorExpanded={expandedErrorId === environment.environment.environmentId}
171 onToggleError={() => handleToggleCloudError(environment.environment.environmentId)}
172 />
173 ))}
174 </View>
175 ) : controller.relayDiscovery.isRefreshing ? (
176 <View collapsable={false} className="items-center gap-3 rounded-[24px] bg-card p-6">
177 <ActivityIndicator colorClassName={"accent-icon"} />
178 <Text className="text-center text-sm leading-normal text-foreground-muted">
179 Loading linked cloud environments.
180 </Text>
181 </View>
182 ) : controller.relayDiscovery.error ? null : (
183 <View collapsable={false} className="rounded-[24px] bg-card p-5">
184 <Text className="text-sm leading-normal text-foreground-muted">
185 No additional linked cloud environments.
186 </Text>
187 </View>
188 )}
189​
190 {/* Rendered alongside any connected rows — a failed discovery must not
191 hide behind an otherwise-healthy list. */}
192 {discoveryAvailable &&
193 controller.relayDiscovery.error &&
194 !controller.relayDiscovery.isRefreshing ? (
195 <View collapsable={false} className="gap-3 rounded-[24px] bg-card p-5">
196 <Text className="text-base font-t3-bold text-foreground">
197 Could not load T3 Connect environments
198 </Text>
199 <Text className="text-sm text-foreground-muted">{controller.relayDiscovery.error}</Text>
200 {controller.relayDiscovery.errorTraceId ? (
201 <CopyTraceIdButton traceId={controller.relayDiscovery.errorTraceId} />
202 ) : null}
203 <Pressable
204 accessibilityRole="button"
205 onPress={() => {
206 void controller.refreshRelayEnvironments();
207 }}
208 className="self-start rounded-full bg-subtle px-3.5 py-2 active:opacity-70"
209 >
210 <Text className="text-xs font-t3-bold text-foreground">Try again</Text>
211 </Pressable>
212 </View>
213 ) : null}
214 </View>
215 );
217​
218/**
219 * A saved T3 Connect environment. The switch turns it on or off; off keeps the
220 * registration and cache but drops the connection and hides its errors.
221 * Long-press removes it from this device.
222 */
223function ConnectedCloudEnvironmentRow(props: {
224 readonly environment: ConnectedEnvironmentSummary;
225 /** Discovery's view of the server, for the glyph before the first connection. */
226 readonly descriptor: ExecutionEnvironmentDescriptor | undefined;
227 readonly borderTop: boolean;
228 readonly errorExpanded: boolean;
229 readonly onSetEnabled: (enabled: boolean) => void;
230 readonly onRemove: () => void;
231 readonly onToggleError: () => void;
232}) {
233 const serverConfig = useAtomValue(
234 serverEnvironment.configValueAtom(props.environment.environmentId),
235 );
236 const unsupported = props.environment.connectionState === "unsupported";
237 const enabled = props.environment.isEnabled && !unsupported;
238 // Discovery empties its map on every refresh; hold the last descriptor seen
239 // so the glyph does not blink back to the generic one each time.
240 const [lastDescriptor, setLastDescriptor] = useState(props.descriptor);
241 if (props.descriptor !== undefined && props.descriptor !== lastDescriptor) {
242 setLastDescriptor(props.descriptor);
243 }
244 return (
245 <Pressable
246 accessibilityHint="Long press to remove from this device"
247 onLongPress={props.onRemove}
248 >
249 <CloudEnvironmentRowShell
250 borderTop={props.borderTop}
251 connectionError={enabled || unsupported ? props.environment.connectionError : null}
252 connectionErrorTraceId={enabled ? props.environment.connectionErrorTraceId : null}
253 connectionState={enabled || unsupported ? props.environment.connectionState : "available"}
254 errorExpanded={props.errorExpanded}
255 label={props.environment.environmentLabel}
256 machine={resolveEnvironmentMachineKind(
257 serverConfig ?? (lastDescriptor === undefined ? null : { environment: lastDescriptor }),
258 )}
259 onValueChange={props.onSetEnabled}
260 onToggleError={props.onToggleError}
261 disabled={unsupported}
262 {...(enabled || unsupported ? {} : { statusText: "Off" })}
263 value={enabled}
264 />
265 </Pressable>
266 );
268​
269function CloudEnvironmentRow(props: {
270 readonly environment: RelayEnvironmentView;
271 readonly borderTop: boolean;
272 readonly errorExpanded: boolean;
273 readonly onConnect: () => void;
274 readonly onToggleError: () => void;
275}) {
276 const presentation = availableCloudEnvironmentPresentation({
277 isStatusPending: props.environment.availability === "checking",
278 status: props.environment.status,
279 statusError: props.environment.error,
280 statusErrorTraceId: props.environment.traceId,
281 });
282​
283 return (
284 <CloudEnvironmentRowShell
285 borderTop={props.borderTop}
286 connectionError={presentation.connectionError}
287 connectionErrorTraceId={presentation.connectionErrorTraceId}
288 connectionState={presentation.connectionState}
289 errorExpanded={props.errorExpanded}
290 label={props.environment.environment.label}
291 machine={resolveEnvironmentMachineKind(
292 props.environment.status?.descriptor === undefined
293 ? null
294 : { environment: props.environment.status.descriptor },
295 )}
296 onValueChange={(enabled) => {
297 if (enabled) {
298 props.onConnect();
299 }
300 }}
301 onToggleError={props.onToggleError}
302 disabled={presentation.connectionState === "unsupported"}
303 statusText={presentation.statusText}
304 value={false}
305 />
306 );
308​
309function CloudEnvironmentRowShell(props: {
310 readonly borderTop: boolean;
311 readonly connectionError: string | null;
312 readonly connectionErrorTraceId: string | null;
313 readonly connectionState: EnvironmentConnectionPhase;
314 readonly disabled?: boolean;
315 readonly errorExpanded: boolean;
316 readonly label: string;
317 readonly machine: EnvironmentMachineKind;
318 readonly onToggleError: () => void;
319 readonly onValueChange: (enabled: boolean) => void;
320 readonly statusText?: string;
321 readonly value: boolean;
322}) {
323 const isRetrying =
324 props.connectionState === "connecting" || props.connectionState === "reconnecting";
325 const shouldPulse = isRetrying;
326 const statusText =
327 props.statusText ??
328 connectionStatusText({
329 phase: props.connectionState,
330 error: props.connectionError,
331 traceId: props.connectionErrorTraceId,
332 });
333 // Unsupported is a compatibility note, not a failure, so it stays muted.
334 const statusClassName =
335 props.connectionError && props.connectionState !== "unsupported"
336 ? "text-danger-foreground"
337 : "text-foreground-muted";
338 const [errorMeasurement, setErrorMeasurement] = useState<{
339 readonly text: string;
340 readonly lineCount: number;
341 } | null>(null);
342 const errorTraceId = props.connectionErrorTraceId;
343 const measuredErrorText = errorTraceId ? `${statusText} Trace ID: ${errorTraceId}` : statusText;
344 const errorLineCount =
345 errorMeasurement?.text === measuredErrorText ? errorMeasurement.lineCount : 0;
346 const errorCanExpand = props.connectionError !== null && errorLineCount > 1;
347 const isErrorExpanded = errorCanExpand && props.errorExpanded;
348 const StatusContainer = errorCanExpand ? Pressable : View;
349 const onMeasuredErrorTextLayout = useCallback(
350 (event: NativeSyntheticEvent<TextLayoutEventData>) => {
351 if (!props.connectionError) {
352 return;
353 }
354 const nextLineCount = event.nativeEvent.lines.length;
355 setErrorMeasurement((currentMeasurement) =>
356 currentMeasurement?.text === measuredErrorText &&
357 currentMeasurement.lineCount === nextLineCount
358 ? currentMeasurement
359 : { text: measuredErrorText, lineCount: nextLineCount },
360 );
361 },
362 [measuredErrorText, props.connectionError],
363 );
364 return (
365 <View
366 collapsable={false}
367 className={cn(
368 "flex-row items-center gap-3 bg-card px-4 py-3.5",
369 props.borderTop && "border-t border-border",
370 )}
371 >
372 <View className="min-w-0 flex-1 gap-0.5">
373 <View className="min-w-0 flex-row items-center gap-2">
374 <ConnectionStatusDot state={props.connectionState} pulse={shouldPulse} size={7} />
375 <EnvironmentMachineSymbol
376 kind={props.machine}
377 size={14}
378 tintColorClassName="accent-foreground-muted"
379 />
380 <Text
381 className="min-w-0 flex-shrink text-base font-t3-bold leading-snug text-foreground"
382 numberOfLines={1}
383 >
384 {props.label}
385 </Text>
386 </View>
387 {props.connectionError ? (
388 <Text
389 aria-hidden
390 onTextLayout={onMeasuredErrorTextLayout}
391 className={cn("absolute inset-x-0 -z-[1] text-xs opacity-0", statusClassName)}
392 >
393 {measuredErrorText}
394 </Text>
395 ) : null}
396 <StatusContainer
397 {...(errorCanExpand
398 ? { accessibilityRole: "button" as const, onPress: props.onToggleError }
399 : {})}
400 className="min-w-0 flex-row items-start gap-1"
401 >
402 <Text
403 className={cn("min-w-0 flex-1 text-xs", statusClassName)}
404 numberOfLines={isErrorExpanded ? undefined : 1}
405 >
406 {statusText}
407 {errorTraceId ? (
408 <>
409 {" Trace ID: "}
410 <Text
411 accessibilityHint="Copies the trace ID"
412 accessibilityRole="button"
413 className={cn("text-xs underline decoration-dotted", statusClassName)}
414 onLongPress={(event) => {
415 event.stopPropagation();
416 copyTextWithHaptic(errorTraceId, { target: "connection-trace-id" });
417 }}
418 onPress={(event) => {
419 event.stopPropagation();
420 }}
421 >
422 {errorTraceId}
423 </Text>
424 </>
425 ) : null}
426 </Text>
427 {errorCanExpand ? (
428 <SymbolView
429 name="chevron.down"
430 size={10}
431 tintColorClassName={"accent-chevron"}
432 type="monochrome"
433 style={{
434 marginTop: 3,
435 transform: [{ rotate: isErrorExpanded ? "180deg" : "0deg" }],
436 }}
437 />
438 ) : null}
439 </StatusContainer>
440 </View>
441 <ThemedSwitch
442 disabled={props.disabled}
443 onValueChange={props.onValueChange}
444 value={props.value}
445 />
446 </View>
447 );
449​
450function CopyTraceIdButton(props: { readonly traceId: string }) {
451 return (
452 <Pressable
453 accessibilityRole="button"
454 onPress={() => {
455 copyTextWithHaptic(props.traceId, { target: "connection-trace-id" });
456 }}
457 className="self-start flex-row items-center gap-1.5 rounded-full bg-subtle px-3 py-2 active:opacity-70"
458 >
459 <SymbolView
460 name="doc.on.doc"
461 size={12}
462 tintColorClassName={"accent-icon"}
463 type="monochrome"
464 />
465 <Text className="text-xs font-t3-bold text-foreground">Copy trace ID</Text>
466 </Pressable>
467 );