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

CloudEnvironmentRows.tsx

412 lines16.3 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 <Pressable
195 accessibilityHint="Long press to remove from this device"
196 accessibilityRole={props.onOpen ? "button" : undefined}
197 accessibilityLabel={props.onOpen ? `Manage ${props.environment.environmentLabel}` : undefined}
198 onPress={props.onOpen}
199 onLongPress={props.onRemove}
200 >
201 <CloudEnvironmentRowShell
202 opensDetails={props.onOpen !== undefined}
203 connectionError={enabled || unsupported ? props.environment.connectionError : null}
204 connectionErrorTraceId={enabled ? props.environment.connectionErrorTraceId : null}
205 connectionState={enabled || unsupported ? props.environment.connectionState : "available"}
206 errorExpanded={props.errorExpanded}
207 label={props.environment.environmentLabel}
208 machine={resolveEnvironmentMachineKind(
209 serverConfig ?? (lastDescriptor === undefined ? null : { environment: lastDescriptor }),
210 )}
211 onValueChange={props.onSetEnabled}
212 onToggleError={props.onToggleError}
213 disabled={unsupported}
214 {...(enabled || unsupported ? {} : { statusText: "Off" })}
215 value={enabled}
216 />
217 </Pressable>
218 );
220​
221function CloudEnvironmentRow(props: {
222 readonly environment: RelayEnvironmentView;
223 readonly showChevron: boolean;
224 readonly errorExpanded: boolean;
225 readonly onConnect: () => void;
226 readonly onToggleError: () => void;
227}) {
228 const presentation = availableCloudEnvironmentPresentation({
229 isStatusPending: props.environment.availability === "checking",
230 status: props.environment.status,
231 statusError: props.environment.error,
232 statusErrorTraceId: props.environment.traceId,
233 });
234​
235 return (
236 <CloudEnvironmentRowShell
237 showChevron={props.showChevron}
238 connectionError={presentation.connectionError}
239 connectionErrorTraceId={presentation.connectionErrorTraceId}
240 connectionState={presentation.connectionState}
241 errorExpanded={props.errorExpanded}
242 label={props.environment.environment.label}
243 machine={resolveEnvironmentMachineKind(
244 props.environment.status?.descriptor === undefined
245 ? null
246 : { environment: props.environment.status.descriptor },
247 )}
248 onValueChange={(enabled) => {
249 if (enabled) {
250 props.onConnect();
251 }
252 }}
253 onToggleError={props.onToggleError}
254 disabled={presentation.connectionState === "unsupported"}
255 statusText={presentation.statusText}
256 value={false}
257 />
258 );
260​
261function CloudEnvironmentRowShell(props: {
262 readonly showChevron?: boolean;
263 readonly opensDetails?: boolean;
264 readonly connectionError: string | null;
265 readonly connectionErrorTraceId: string | null;
266 readonly connectionState: EnvironmentConnectionPhase;
267 readonly disabled?: boolean;
268 readonly errorExpanded: boolean;
269 readonly label: string;
270 readonly machine: EnvironmentMachineKind;
271 readonly onToggleError: () => void;
272 readonly onValueChange: (enabled: boolean) => void;
273 readonly statusText?: string;
274 readonly value: boolean;
275}) {
276 const isRetrying =
277 props.connectionState === "connecting" || props.connectionState === "reconnecting";
278 const shouldPulse = isRetrying;
279 const statusText =
280 props.statusText ??
281 environmentStatusText({
282 phase: props.connectionState,
283 error: props.connectionError,
284 traceId: props.connectionErrorTraceId,
285 });
286 const statusClassName =
287 props.connectionError && props.connectionState !== "unsupported"
288 ? "text-danger-foreground"
289 : "text-foreground-muted";
290 const [errorMeasurement, setErrorMeasurement] = useState<{
291 readonly text: string;
292 readonly lineCount: number;
293 } | null>(null);
294 const errorTraceId = props.connectionErrorTraceId;
295 const measuredErrorText = errorTraceId ? `${statusText} Trace ID: ${errorTraceId}` : statusText;
296 const errorLineCount =
297 errorMeasurement?.text === measuredErrorText ? errorMeasurement.lineCount : 0;
298 const errorCanExpand = props.connectionError !== null && errorLineCount > 1;
299 const isErrorExpanded = errorCanExpand && props.errorExpanded;
300 const StatusContainer = errorCanExpand ? Pressable : View;
301 const onMeasuredErrorTextLayout = useCallback(
302 (event: TextLayoutEvent) => {
303 if (!props.connectionError) {
304 return;
305 }
306 const nextLineCount = event.nativeEvent.lines.length;
307 setErrorMeasurement((currentMeasurement) =>
308 currentMeasurement?.text === measuredErrorText &&
309 currentMeasurement.lineCount === nextLineCount
310 ? currentMeasurement
311 : { text: measuredErrorText, lineCount: nextLineCount },
312 );
313 },
314 [measuredErrorText, props.connectionError],
315 );
316 return (
317 <View collapsable={false} className="flex-row items-center gap-3 bg-grouped-card px-4 py-3.5">
318 <View className="min-w-0 flex-1 gap-0.5">
319 <View className="min-w-0 flex-row items-center gap-2">
320 <ConnectionStatusDot state={props.connectionState} pulse={shouldPulse} size={7} />
321 <EnvironmentMachineSymbol
322 kind={props.machine}
323 size={14}
324 tintColorClassName="accent-foreground-muted"
325 />
326 <Text
327 className="min-w-0 flex-shrink text-base font-t3-bold leading-snug text-foreground"
328 numberOfLines={1}
329 >
330 {props.label}
331 </Text>
332 </View>
333 {props.connectionError ? (
334 <Text
335 aria-hidden
336 onTextLayout={onMeasuredErrorTextLayout}
337 className={cn("absolute inset-x-0 -z-[1] text-xs opacity-0", statusClassName)}
338 >
339 {measuredErrorText}
340 </Text>
341 ) : null}
342 <StatusContainer
343 {...(errorCanExpand
344 ? { accessibilityRole: "button" as const, onPress: props.onToggleError }
345 : {})}
346 className="min-w-0 flex-row items-start gap-1"
347 >
348 <Text
349 className={cn("min-w-0 flex-1 text-xs", statusClassName)}
350 numberOfLines={isErrorExpanded ? undefined : 1}
351 >
352 {statusText}
353 {errorTraceId ? (
354 <ConnectionTraceId
355 traceId={errorTraceId}
356 tone={
357 props.connectionError && props.connectionState !== "unsupported"
358 ? "danger"
359 : "muted"
360 }
361 activation="longPress"
362 />
363 ) : null}
364 </Text>
365 {errorCanExpand ? (
366 <SymbolView
367 name="chevron.down"
368 size={10}
369 tintColorClassName={"accent-chevron"}
370 type="monochrome"
371 style={{
372 marginTop: 3,
373 transform: [{ rotate: isErrorExpanded ? "180deg" : "0deg" }],
374 }}
375 />
376 ) : null}
377 </StatusContainer>
378 </View>
379 <ThemedSwitch
380 style={{ alignSelf: "center" }}
381 disabled={props.disabled}
382 onValueChange={props.onValueChange}
383 value={props.value}
384 />
385 {props.opensDetails || props.showChevron ? (
386 <View style={{ opacity: props.opensDetails ? 1 : 0.4 }}>
387 <SymbolView name="chevron.right" size={12} tintColorClassName="accent-icon-subtle" />
388 </View>
389 ) : null}
390 </View>
391 );
393​
394function CopyTraceIdButton(props: { readonly traceId: string }) {
395 return (
396 <Pressable
397 accessibilityRole="button"
398 onPress={() => {
399 copyTextWithHaptic(props.traceId, { target: "connection-trace-id" });
400 }}
401 className="self-start flex-row items-center gap-1.5 rounded-full bg-subtle px-3 py-2 active:opacity-70"
402 >
403 <SymbolView
404 name="doc.on.doc"
405 size={12}
406 tintColorClassName={"accent-icon"}
407 type="monochrome"
408 />
409 <Text className="text-xs font-t3-bold text-foreground">Copy trace ID</Text>
410 </Pressable>
411 );