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

ConnectionEnvironmentRow.tsx

344 lines13.4 KB

1import { errorDisplayMessage } from "@t3tools/client-runtime/errors";
2import { msg, T, useGT, useMessages } from "gt-react-native";
3import * as Dialog from "../../components/ui/Dialog";
4import { ConnectionTraceId } from "./ConnectionTraceId";
5import { SymbolView } from "../../components/ui/AppSymbol";
6import { hasSavedBearerRoute, hostFreezeNotice } from "@t3tools/client-runtime/connection";
7import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime";
8import { type EnvironmentId, resolveEnvironmentMachineKind } from "@t3tools/contracts";
9import { useAtomValue } from "@effect/atom-react";
10import * as Cause from "effect/Cause";
11import { AsyncResult } from "effect/reactivity";
12import { useState } from "react";
13import { Platform, Pressable, View } from "react-native";
14import Animated, { FadeIn, FadeOut, LinearTransition } from "react-native-reanimated";
15import { m as resolveMessage } from "../../i18n/messages";
16​
17import { AppText as Text } from "../../components/ui/AppText";
18import { EnvironmentMachineSymbol } from "../../components/EnvironmentMachineSymbol";
19import { Button } from "../../components/ui/Button";
20import { IconButton } from "../../components/ui/IconButton";
21import { ThemedSwitch } from "../../components/ui/ThemedSwitch";
22import { cn } from "../../lib/cn";
23import type { ConnectedEnvironmentSummary } from "../../state/remote-runtime-types";
24import { serverEnvironment } from "../../state/server";
25import { environmentPresentations } from "../../state/presentation";
26import { ConnectionDiagnosisDetails, useConnectionDiagnosis } from "./ConnectionDiagnosisDetails";
27import { ConnectionFormField } from "./ConnectionFormField";
28import { ConnectionStatusDot } from "./ConnectionStatusDot";
29import { environmentStatusText } from "./environmentStatusText";
30import type { MessageResolver } from "../../i18n/messages";
31​
32function connectionStatusLabel(
33 environment: ConnectedEnvironmentSummary,
34 resolve: MessageResolver,
35): string | null {
36 if (!environment.isEnabled && environment.connectionState !== "unsupported") {
37 return resolve(msg("Off", { $context: "environment is switched off" }));
38 }
39 return environmentStatusText(
40 {
41 phase: environment.connectionState,
42 error: environment.connectionError,
43 ...(environment.i18nConnectionError === undefined
44 ? {}
45 : { i18nError: environment.i18nConnectionError }),
46 traceId: environment.connectionErrorTraceId,
47 },
48 resolve,
49 );
51​
52export function ConnectionEnvironmentRow(props: {
53 readonly environment: ConnectedEnvironmentSummary;
54 readonly expanded: boolean;
55 readonly opensDetails?: boolean;
56 readonly onToggle: () => void;
57 readonly onReconnect: (environmentId: EnvironmentId) => void;
58 readonly onRemove: (environmentId: EnvironmentId) => void;
59 readonly onSetEnabled: (environmentId: EnvironmentId, enabled: boolean) => void;
60 readonly onUpdate: (
61 environmentId: EnvironmentId,
62 updates: { readonly label: string; readonly displayUrl: string },
63 ) => Promise<AtomCommandResult<unknown, unknown>>;
64}) {
65 const gt = useGT();
66 const m = useMessages();
67 const [label, setLabel] = useState(props.environment.environmentLabel);
68 const [url, setUrl] = useState(props.environment.displayUrl);
69 const serverConfig = useAtomValue(
70 serverEnvironment.configValueAtom(props.environment.environmentId),
71 );
72 const unsupported = props.environment.connectionState === "unsupported";
73 const presentation = useAtomValue(
74 environmentPresentations.presentationAtom(props.environment.environmentId),
75 );
76 const canRetry = presentation !== null && hasSavedBearerRoute(presentation.entry);
77 const { diagnosis, state: connectionState } = useConnectionDiagnosis(
78 props.environment.environmentId,
79 presentation,
80 );
81 const enabled = props.environment.isEnabled && !unsupported;
82 const statusLabel = connectionStatusLabel(props.environment, m);
83 const statusTraceId = enabled ? props.environment.connectionErrorTraceId : null;
84 const hasConnectionFailure = enabled && props.environment.connectionError !== null;
85 const freeze = enabled
86 ? hostFreezeNotice(props.environment.environmentLabel, serverConfig?.lastEventLoopStall, m)
87 : null;
88 const isRetrying =
89 enabled &&
90 (props.environment.connectionState === "connecting" ||
91 props.environment.connectionState === "reconnecting");
92 const handleSave = async () => {
93 const result = await props.onUpdate(props.environment.environmentId, {
94 label: label.trim(),
95 displayUrl: url.trim(),
96 });
97 if (AsyncResult.isSuccess(result)) {
98 props.onToggle();
99 return;
100 }
101 const error = Cause.squash(result.cause);
102 Dialog.alert(
103 gt("Could not update environment"),
104 error instanceof Error
105 ? (errorDisplayMessage(error, resolveMessage) ?? error.message)
106 : gt("The environment could not be updated."),
107 );
108 };
109​
110 const toggleLabel = props.opensDetails
111 ? gt("Manage {environment}", { environment: props.environment.environmentLabel })
112 : props.expanded
113 ? gt("Collapse details for {environment}", {
114 environment: props.environment.environmentLabel,
115 })
116 : gt("Expand details for {environment}", {
117 environment: props.environment.environmentLabel,
118 });
119​
120 return (
121 <Animated.View layout={LinearTransition.duration(250)} className="bg-grouped-card">
122 <View className="flex-row items-center gap-3 px-4 py-3.5">
123 <Pressable
124 className="min-w-0 flex-1 gap-0.5 active:opacity-70"
125 accessibilityRole="button"
126 accessibilityLabel={toggleLabel}
127 onPress={props.onToggle}
128 >
129 <View className="flex-row items-center gap-1.5">
130 <ConnectionStatusDot
131 state={enabled || unsupported ? props.environment.connectionState : "available"}
132 pulse={isRetrying}
133 size={8}
134 />
135 <EnvironmentMachineSymbol
136 kind={resolveEnvironmentMachineKind(serverConfig)}
137 size={14}
138 tintColorClassName="accent-foreground-muted"
139 />
140 <Text
141 className="min-w-0 flex-shrink text-base font-t3-bold leading-snug text-foreground"
142 numberOfLines={1}
143 >
144 {props.environment.environmentLabel}
145 </Text>
146 </View>
147 {!props.environment.isRelayManaged && props.environment.displayUrl.trim() ? (
148 <Text className="text-xs text-foreground-muted" numberOfLines={1}>
149 {props.environment.displayUrl}
150 </Text>
151 ) : null}
152 {diagnosis ? (
153 <>
154 <Text className="text-xs text-danger-foreground">{diagnosis.headline}</Text>
155 {connectionState.attempt > 0 ? (
156 <Text className="text-xs text-foreground-muted">
157 {gt("Retrying · attempt {attempt}", { attempt: connectionState.attempt })}
158 </Text>
159 ) : null}
160 </>
161 ) : statusLabel ? (
162 <Text
163 className={cn(
164 "text-xs",
165 hasConnectionFailure ? "text-danger-foreground" : "text-foreground-muted",
166 )}
167 numberOfLines={props.expanded ? undefined : 1}
168 selectable={props.expanded}
169 >
170 {statusLabel}
171 {statusTraceId ? (
172 <ConnectionTraceId
173 traceId={statusTraceId}
174 tone={hasConnectionFailure ? "danger" : "muted"}
175 activation="longPress"
176 />
177 ) : null}
178 </Text>
179 ) : null}
180 {freeze ? (
181 <Text
182 className="text-xs text-warning-foreground"
183 numberOfLines={props.expanded ? undefined : 1}
184 >
185 {`${freeze.title}. ${freeze.description}`}
186 </Text>
187 ) : null}
188 </Pressable>
189​
190 <ThemedSwitch
191 accessibilityLabel={gt("Enable {environment}", {
192 environment: props.environment.environmentLabel,
193 })}
194 style={{ alignSelf: "center" }}
195 disabled={unsupported && !canRetry}
196 onValueChange={(next) => props.onSetEnabled(props.environment.environmentId, next)}
197 value={enabled}
198 />
199 <Pressable
200 accessible={false}
201 accessibilityElementsHidden
202 importantForAccessibility="no-hide-descendants"
203 onPress={props.onToggle}
204 style={{
205 minWidth: 44,
206 minHeight: 44,
207 alignItems: "center",
208 justifyContent: "center",
209 }}
210 >
211 <SymbolView
212 name={props.opensDetails ? "chevron.right" : "chevron.down"}
213 size={12}
214 tintColorClassName="accent-icon-subtle"
215 type="monochrome"
216 style={{ transform: [{ rotate: props.expanded ? "180deg" : "0deg" }] }}
217 />
218 </Pressable>
219 </View>
220​
221 {props.expanded ? (
222 <Animated.View
223 entering={FadeIn.duration(200)}
224 exiting={FadeOut.duration(150)}
225 className="gap-3 px-4 pb-4"
226 >
227 {diagnosis ? (
228 <ConnectionDiagnosisDetails
229 hostLabel={props.environment.environmentLabel}
230 diagnosis={diagnosis}
231 />
232 ) : null}
233 {props.environment.isRelayManaged ? (
234 <Text className="text-sm text-foreground-muted">
235 {gt("Managed by {product}. Tunnel details update automatically.", {
236 product: "T3 Connect",
237 })}
238 </Text>
239 ) : (
240 <>
241 <ConnectionFormField
242 label={gt("Label", { $context: "noun, environment name field" })}
243 autoCapitalize="words"
244 autoCorrect={false}
245 placeholder={gt("My MacBook")}
246 value={label}
247 onChangeText={setLabel}
248 />
249​
250 <ConnectionFormField
251 label="URL"
252 autoCapitalize="none"
253 autoCorrect={false}
254 keyboardType="url"
255 placeholder="192.168.1.100:8080"
256 value={url}
257 onChangeText={setUrl}
258 />
259 </>
260 )}
261​
262 {Platform.OS === "android" ? (
263 <View className="flex-row items-center justify-end gap-2">
264 {props.environment.isRelayManaged ? null : (
265 <View className="flex-1">
266 <Button
267 label={gt("Save")}
268 tone="primary"
269 fullWidth
270 onPress={() => {
271 void handleSave();
272 }}
273 />
274 </View>
275 )}
276 <IconButton
277 accessibilityLabel={gt("Reconnect environment")}
278 icon="arrow.clockwise"
279 variant="tonal"
280 disabled={!enabled}
281 onPress={() => props.onReconnect(props.environment.environmentId)}
282 />
283 <IconButton
284 accessibilityLabel={gt("Remove environment")}
285 icon="trash"
286 variant="danger"
287 onPress={() => props.onRemove(props.environment.environmentId)}
288 />
289 </View>
290 ) : (
291 <View className="flex-row justify-end gap-2">
292 {props.environment.isRelayManaged ? null : (
293 <Pressable
294 className="min-h-[42px] flex-1 flex-row items-center justify-center gap-1.5 rounded-[14px] bg-primary px-3.5 py-2.5 active:opacity-70"
295 onPress={handleSave}
296 >
297 <SymbolView
298 name="checkmark"
299 size={13}
300 tintColorClassName="accent-primary-foreground"
301 type="monochrome"
302 />
303 <Text className="text-xs font-t3-bold tracking-[0.8px] uppercase text-primary-foreground">
304 <T>Save</T>
305 </Text>
306 </Pressable>
307 )}
308​
309 <Pressable
310 accessibilityRole="button"
311 accessibilityLabel={gt("Reconnect environment")}
312 accessibilityState={{ disabled: !enabled }}
313 className="h-[42px] w-[42px] items-center justify-center rounded-[14px] border border-input-border bg-input active:opacity-70 disabled:opacity-40"
314 disabled={!enabled}
315 onPress={() => props.onReconnect(props.environment.environmentId)}
316 >
317 <SymbolView
318 name="arrow.clockwise"
319 size={14}
320 tintColorClassName="accent-icon-subtle"
321 type="monochrome"
322 />
323 </Pressable>
324​
325 <Pressable
326 accessibilityRole="button"
327 accessibilityLabel={gt("Remove environment")}
328 className="h-[42px] w-[42px] items-center justify-center rounded-[14px] border border-danger-border bg-danger active:opacity-70"
329 onPress={() => props.onRemove(props.environment.environmentId)}
330 >
331 <SymbolView
332 name="trash"
333 size={14}
334 tintColorClassName="accent-danger-foreground"
335 type="monochrome"
336 />
337 </Pressable>
338 </View>
339 )}
340 </Animated.View>
341 ) : null}
342 </Animated.View>
343 );