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

CloudEnvironmentRows.tsx

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