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

CloudEnvironmentRows.tsx

443 lines17.4 KB

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