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

CloudEnvironmentRows.tsx

446 lines17.6 KB

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