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

CloudEnvironmentRows.tsx

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