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

environments.tsx

452 lines16.8 KB

1import { useAuth } from "@clerk/expo";
2import { Stack, useRouter } from "expo-router";
3import { SymbolView } from "expo-symbols";
4import {
5 connectionStatusText,
6 type EnvironmentConnectionPhase,
7} from "@t3tools/client-runtime/connection";
8import type { EnvironmentId } from "@t3tools/contracts";
9import { useCallback, useState } from "react";
10import {
11 ActivityIndicator,
12 Pressable,
13 ScrollView,
14 Switch,
15 type NativeSyntheticEvent,
16 type TextLayoutEventData,
17 View,
18} from "react-native";
19import { useSafeAreaInsets } from "react-native-safe-area-context";
20​
21import { AppText as Text } from "../../components/AppText";
22import {
23 type RelayEnvironmentView,
24 useConnectionController,
25} from "../../features/connection/useConnectionController";
26import { hasCloudPublicConfig } from "../../features/cloud/publicConfig";
27import { availableCloudEnvironmentPresentation } from "../../features/cloud/cloudEnvironmentPresentation";
28import { ConnectionEnvironmentRow } from "../../features/connection/ConnectionEnvironmentRow";
29import { ConnectionStatusDot } from "../../features/connection/ConnectionStatusDot";
30import { splitEnvironmentSections } from "../../features/connection/environmentSections";
31import { cn } from "../../lib/cn";
32import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
33import { useThemeColor } from "../../lib/useThemeColor";
34import type { ConnectedEnvironmentSummary } from "../../state/remote-runtime-types";
35import { useRemoteConnections } from "../../state/use-remote-environment-registry";
36​
37export default function SettingsEnvironmentsRouteScreen() {
38 const {
39 connectedEnvironments,
40 onReconnectEnvironment,
41 onRemoveEnvironmentPress,
42 onUpdateEnvironment,
43 } = useRemoteConnections();
44 const router = useRouter();
45 const insets = useSafeAreaInsets();
46 const { localEnvironments, connectedCloudEnvironments } = splitEnvironmentSections({
47 connectedEnvironments,
48 cloudEnvironments: null,
49 });
50 const hasLocalEnvironments = localEnvironments.length > 0;
51 const [expandedId, setExpandedId] = useState<EnvironmentId | null>(null);
52 const accentColor = useThemeColor("--color-icon-muted");
53​
54 const handleToggle = useCallback((environmentId: EnvironmentId) => {
55 setExpandedId((prev) => (prev === environmentId ? null : environmentId));
56 }, []);
57​
58 return (
59 <View collapsable={false} className="flex-1 bg-sheet">
60 <Stack.Screen
61 options={{
62 title: "Environments",
63 }}
64 />
65 <Stack.Toolbar placement="right">
66 <Stack.Toolbar.Button
67 icon="plus"
68 onPress={() => router.push("/settings/environment-new")}
69 separateBackground
70 />
71 </Stack.Toolbar>
72 <ScrollView
73 contentInsetAdjustmentBehavior="automatic"
74 showsVerticalScrollIndicator={false}
75 style={{ flex: 1 }}
76 contentContainerStyle={{
77 paddingBottom: Math.max(insets.bottom, 18) + 18,
78 paddingHorizontal: 20,
79 paddingTop: 16,
80 }}
81 >
82 {hasLocalEnvironments ? (
83 <View collapsable={false} className="overflow-hidden rounded-[24px] bg-card">
84 {localEnvironments.map((environment, index) => (
85 <View
86 key={environment.environmentId}
87 collapsable={false}
88 style={{
89 borderTopWidth: index === 0 ? 0 : 1,
90 }}
91 className={cn(index !== 0 && "border-border")}
92 >
93 <ConnectionEnvironmentRow
94 environment={environment}
95 expanded={expandedId === environment.environmentId}
96 onToggle={() => handleToggle(environment.environmentId)}
97 onReconnect={onReconnectEnvironment}
98 onRemove={onRemoveEnvironmentPress}
99 onUpdate={onUpdateEnvironment}
100 />
101 </View>
102 ))}
103 </View>
104 ) : (
105 <View collapsable={false} className="items-center gap-3 rounded-[24px] bg-card px-6 py-8">
106 <View className="h-12 w-12 items-center justify-center rounded-[16px] bg-subtle">
107 <SymbolView
108 name="point.3.connected.trianglepath.dotted"
109 size={20}
110 tintColor={accentColor}
111 type="monochrome"
112 />
113 </View>
114 <Text className="text-center text-sm leading-[20px] text-foreground-muted">
115 No environments connected yet.{"\n"}Tap{" "}
116 <Text className="font-t3-bold text-foreground">+</Text> to add one.
117 </Text>
118 </View>
119 )}
120​
121 {hasCloudPublicConfig() ? (
122 <ConfiguredCloudEnvironmentRows
123 connectedCloudEnvironments={connectedCloudEnvironments}
124 onReconnectEnvironment={onReconnectEnvironment}
125 />
126 ) : null}
127 </ScrollView>
128 </View>
129 );
131​
132function ConfiguredCloudEnvironmentRows(props: {
133 readonly connectedCloudEnvironments: ReadonlyArray<ConnectedEnvironmentSummary>;
134 readonly onReconnectEnvironment: (environmentId: EnvironmentId) => void;
135}) {
136 const { isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
137 const controller = useConnectionController();
138 const iconColor = useThemeColor("--color-icon");
139 const availableCloudEnvironments = controller.availableRelayEnvironments;
140 const [expandedErrorId, setExpandedErrorId] = useState<string | null>(null);
141 const hasCloudRows =
142 props.connectedCloudEnvironments.length > 0 || availableCloudEnvironments.length > 0;
143​
144 const handleConnectCloudEnvironment = useCallback(
145 (entry: RelayEnvironmentView) => controller.connectRelayEnvironment(entry.environment),
146 [controller],
147 );
148​
149 const handleDisconnectCloudEnvironment = useCallback(
150 (environmentId: EnvironmentId) => controller.removeEnvironment(environmentId),
151 [controller],
152 );
153​
154 const handleToggleCloudError = useCallback((environmentId: string) => {
155 setExpandedErrorId((current) => (current === environmentId ? null : environmentId));
156 }, []);
157​
158 if (!isSignedIn) return null;
159​
160 return (
161 <View collapsable={false} className="mt-5 gap-3">
162 <View className="flex-row items-center justify-between px-1">
163 <Text className="text-sm font-t3-bold uppercase text-foreground-muted">T3 Cloud</Text>
164 <Pressable
165 accessibilityRole="button"
166 disabled={controller.relayDiscovery.isRefreshing}
167 onPress={() => {
168 void controller.refreshRelayEnvironments();
169 }}
170 className="h-9 w-9 items-center justify-center rounded-full bg-subtle active:opacity-70 disabled:opacity-50"
171 >
172 {controller.relayDiscovery.isRefreshing ? (
173 <ActivityIndicator color={iconColor} size="small" />
174 ) : (
175 <SymbolView name="arrow.clockwise" size={14} tintColor={iconColor} type="monochrome" />
176 )}
177 </Pressable>
178 </View>
179​
180 {hasCloudRows ? (
181 <View collapsable={false} className="overflow-hidden rounded-[24px] bg-card">
182 {props.connectedCloudEnvironments.map((environment, index) => (
183 <ConnectedCloudEnvironmentRow
184 key={environment.environmentId}
185 environment={environment}
186 borderTop={index !== 0}
187 onConnect={() => props.onReconnectEnvironment(environment.environmentId)}
188 onDisconnect={() => handleDisconnectCloudEnvironment(environment.environmentId)}
189 errorExpanded={expandedErrorId === environment.environmentId}
190 onToggleError={() => handleToggleCloudError(environment.environmentId)}
191 />
192 ))}
193 {availableCloudEnvironments.map((environment, index) => (
194 <CloudEnvironmentRow
195 key={environment.environment.environmentId}
196 environment={environment}
197 borderTop={props.connectedCloudEnvironments.length > 0 || index !== 0}
198 onConnect={() => handleConnectCloudEnvironment(environment)}
199 errorExpanded={expandedErrorId === environment.environment.environmentId}
200 onToggleError={() => handleToggleCloudError(environment.environment.environmentId)}
201 />
202 ))}
203 </View>
204 ) : controller.relayDiscovery.isRefreshing ? (
205 <View collapsable={false} className="items-center gap-3 rounded-[24px] bg-card p-6">
206 <ActivityIndicator color={iconColor} />
207 <Text className="text-center text-sm leading-[20px] text-foreground-muted">
208 Loading linked cloud environments.
209 </Text>
210 </View>
211 ) : controller.relayDiscovery.error ? (
212 <View collapsable={false} className="gap-3 rounded-[24px] bg-card p-5">
213 <Text className="text-base font-t3-bold text-foreground">
214 Could not load T3 Cloud environments
215 </Text>
216 <Text className="text-sm leading-[18px] text-foreground-muted">
217 {controller.relayDiscovery.error}
218 </Text>
219 {controller.relayDiscovery.errorTraceId ? (
220 <CopyTraceIdButton traceId={controller.relayDiscovery.errorTraceId} />
221 ) : null}
222 </View>
223 ) : (
224 <View collapsable={false} className="rounded-[24px] bg-card p-5">
225 <Text className="text-sm leading-[20px] text-foreground-muted">
226 No additional linked cloud environments.
227 </Text>
228 </View>
229 )}
230 </View>
231 );
233​
234function ConnectedCloudEnvironmentRow(props: {
235 readonly environment: ConnectedEnvironmentSummary;
236 readonly borderTop: boolean;
237 readonly errorExpanded: boolean;
238 readonly onConnect: () => void;
239 readonly onDisconnect: () => void;
240 readonly onToggleError: () => void;
241}) {
242 return (
243 <CloudEnvironmentRowShell
244 borderTop={props.borderTop}
245 connectionError={props.environment.connectionError}
246 connectionErrorTraceId={props.environment.connectionErrorTraceId}
247 connectionState={props.environment.connectionState}
248 errorExpanded={props.errorExpanded}
249 label={props.environment.environmentLabel}
250 onValueChange={(enabled) => {
251 if (enabled) {
252 props.onConnect();
253 return;
254 }
255 props.onDisconnect();
256 }}
257 onToggleError={props.onToggleError}
258 value={props.environment.connectionState !== "available"}
259 />
260 );
262​
263function CloudEnvironmentRow(props: {
264 readonly environment: RelayEnvironmentView;
265 readonly borderTop: boolean;
266 readonly errorExpanded: boolean;
267 readonly onConnect: () => void;
268 readonly onToggleError: () => void;
269}) {
270 const presentation = availableCloudEnvironmentPresentation({
271 isStatusPending: props.environment.availability === "checking",
272 status: props.environment.status,
273 statusError: props.environment.error,
274 statusErrorTraceId: props.environment.traceId,
275 });
276​
277 return (
278 <CloudEnvironmentRowShell
279 borderTop={props.borderTop}
280 connectionError={presentation.connectionError}
281 connectionErrorTraceId={presentation.connectionErrorTraceId}
282 connectionState={presentation.connectionState}
283 errorExpanded={props.errorExpanded}
284 label={props.environment.environment.label}
285 onValueChange={(enabled) => {
286 if (enabled) {
287 props.onConnect();
288 }
289 }}
290 onToggleError={props.onToggleError}
291 statusText={presentation.statusText}
292 value={false}
293 />
294 );
296​
297function CloudEnvironmentRowShell(props: {
298 readonly borderTop: boolean;
299 readonly connectionError: string | null;
300 readonly connectionErrorTraceId: string | null;
301 readonly connectionState: EnvironmentConnectionPhase;
302 readonly disabled?: boolean;
303 readonly errorExpanded: boolean;
304 readonly label: string;
305 readonly onToggleError: () => void;
306 readonly onValueChange: (enabled: boolean) => void;
307 readonly statusText?: string;
308 readonly value: boolean;
309}) {
310 const activeTrack = String(useThemeColor("--color-switch-active"));
311 const track = String(useThemeColor("--color-secondary-border"));
312 const chevron = useThemeColor("--color-chevron");
313 const isRetrying =
314 props.connectionState === "connecting" || props.connectionState === "reconnecting";
315 const shouldPulse = isRetrying;
316 const statusText =
317 props.statusText ??
318 connectionStatusText({
319 phase: props.connectionState,
320 error: props.connectionError,
321 traceId: props.connectionErrorTraceId,
322 });
323 const statusClassName = props.connectionError
324 ? "text-rose-500 dark:text-rose-400"
325 : "text-foreground-muted";
326 const [errorMeasurement, setErrorMeasurement] = useState<{
327 readonly text: string;
328 readonly lineCount: number;
329 } | null>(null);
330 const errorTraceId = props.connectionErrorTraceId;
331 const measuredErrorText = errorTraceId ? `${statusText} Trace ID: ${errorTraceId}` : statusText;
332 const errorLineCount =
333 errorMeasurement?.text === measuredErrorText ? errorMeasurement.lineCount : 0;
334 const errorCanExpand = props.connectionError !== null && errorLineCount > 1;
335 const isErrorExpanded = errorCanExpand && props.errorExpanded;
336 const StatusContainer = errorCanExpand ? Pressable : View;
337 const onMeasuredErrorTextLayout = useCallback(
338 (event: NativeSyntheticEvent<TextLayoutEventData>) => {
339 if (!props.connectionError) {
340 return;
341 }
342 const nextLineCount = event.nativeEvent.lines.length;
343 setErrorMeasurement((currentMeasurement) =>
344 currentMeasurement?.text === measuredErrorText &&
345 currentMeasurement.lineCount === nextLineCount
346 ? currentMeasurement
347 : { text: measuredErrorText, lineCount: nextLineCount },
348 );
349 },
350 [measuredErrorText, props.connectionError],
351 );
352 return (
353 <View
354 collapsable={false}
355 className={cn(
356 "flex-row items-center gap-3 bg-card px-4 py-3.5",
357 props.borderTop && "border-t border-border",
358 )}
359 >
360 <View className="min-w-0 flex-1 gap-0.5">
361 <View className="min-w-0 flex-row items-center gap-2">
362 <ConnectionStatusDot state={props.connectionState} pulse={shouldPulse} size={7} />
363 <Text
364 className="min-w-0 flex-shrink text-base font-t3-bold leading-[21px] text-foreground"
365 numberOfLines={1}
366 >
367 {props.label}
368 </Text>
369 </View>
370 {props.connectionError ? (
371 <Text
372 aria-hidden
373 className={cn("absolute left-0 right-0 text-xs leading-[16px]", statusClassName)}
374 onTextLayout={onMeasuredErrorTextLayout}
375 style={{ opacity: 0, zIndex: -1 }}
376 >
377 {measuredErrorText}
378 </Text>
379 ) : null}
380 <StatusContainer
381 {...(errorCanExpand
382 ? { accessibilityRole: "button" as const, onPress: props.onToggleError }
383 : {})}
384 className="min-w-0 flex-row items-start gap-1"
385 >
386 <Text
387 className={cn("min-w-0 flex-1 text-xs leading-[16px]", statusClassName)}
388 numberOfLines={isErrorExpanded ? undefined : 1}
389 >
390 {statusText}
391 {errorTraceId ? (
392 <>
393 {" Trace ID: "}
394 <Text
395 accessibilityHint="Copies the trace ID"
396 accessibilityRole="button"
397 className={cn("text-xs leading-[16px] underline", statusClassName)}
398 onLongPress={(event) => {
399 event.stopPropagation();
400 copyTextWithHaptic(errorTraceId, { target: "connection-trace-id" });
401 }}
402 onPress={(event) => {
403 event.stopPropagation();
404 }}
405 style={{ textDecorationStyle: "dotted" }}
406 >
407 {errorTraceId}
408 </Text>
409 </>
410 ) : null}
411 </Text>
412 {errorCanExpand ? (
413 <SymbolView
414 name="chevron.down"
415 size={10}
416 tintColor={chevron}
417 type="monochrome"
418 style={{
419 marginTop: 3,
420 transform: [{ rotate: isErrorExpanded ? "180deg" : "0deg" }],
421 }}
422 />
423 ) : null}
424 </StatusContainer>
425 </View>
426 <Switch
427 disabled={props.disabled}
428 ios_backgroundColor={track}
429 onValueChange={props.onValueChange}
430 trackColor={{ false: track, true: activeTrack }}
431 value={props.value}
432 />
433 </View>
434 );
436​
437function CopyTraceIdButton(props: { readonly traceId: string }) {
438 const iconColor = useThemeColor("--color-icon");
439​
440 return (
441 <Pressable
442 accessibilityRole="button"
443 onPress={() => {
444 copyTextWithHaptic(props.traceId, { target: "connection-trace-id" });
445 }}
446 className="self-start flex-row items-center gap-1.5 rounded-full bg-subtle px-3 py-2 active:opacity-70"
447 >
448 <SymbolView name="doc.on.doc" size={12} tintColor={iconColor} type="monochrome" />
449 <Text className="text-xs font-t3-bold text-foreground">Copy trace ID</Text>
450 </Pressable>
451 );