Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import {
3 type ConnectionRoute,
4 type ConnectionRouteKind,
5 connectionRouteAddress,
6 connectionRouteId,
7 connectionRouteKind,
8 connectionRouteLabel,
9 connectionRoutes,
10 isLearned,
11} from "@t3tools/client-runtime/connection";
12import type { EnvironmentId } from "@t3tools/contracts";
13import * as Option from "effect/Option";
14import { useEffect, useMemo, useRef, useState } from "react";
15import { Alert, Platform, Pressable, View } from "react-native";
16import { Gesture, GestureDetector } from "react-native-gesture-handler";
17import Reanimated, { ReduceMotion, useAnimatedStyle, withTiming } from "react-native-reanimated";
18
19import { type AppSymbolName, SymbolView } from "../../components/AppSymbol";
20import { AppText as Text } from "../../components/AppText";
21import { StatusPill } from "../../components/StatusPill";
22import { environmentCatalog } from "../../connection/catalog";
23import { cn } from "../../lib/cn";
24import { environmentSession } from "../../state/session";
25import { useAtomCommand } from "../../state/use-atom-command";
26import { connectionTone } from "../connection/connectionTone";
27import { SettingsActionRow } from "./components/SettingsActionRow";
28import { SettingsSection } from "./components/SettingsSection";
29
30const ICON_SIZE = Platform.OS === "android" ? 24 : 22;
31const REMOVE_SIZE = 20;
32
33const ROUTE_ICONS: Record<ConnectionRouteKind, AppSymbolName> = {
34 relay: "cloud",
35 loopback: "desktopcomputer",
36 lan: "wifi",
37 tailnet: "point.3.connected.trianglepath.dotted",
38 public: "globe",
39 ssh: "terminal",
40};
41
42/**
43 * The ways this device reaches an environment, preferred first. The first
44 * route that answers is used, and the connection moves back up the list when
45 * a better route is reachable again. Edit shows drag handles and remove
46 * buttons; Add route pairs this machine over another address.
47 */
48export function EnvironmentRoutesSection({
49 environmentId,
50 connected,
51 onAddRoute,
52}: {
53 readonly environmentId: EnvironmentId;
54 readonly connected: boolean;
55 readonly onAddRoute: () => void;
56}) {
57 const entry = useAtomValue(environmentCatalog.catalogValueAtom).entries.get(environmentId);
58 const prepared = useAtomValue(environmentSession.preparedConnectionValueAtom(environmentId));
59 const reorder = useAtomCommand(environmentCatalog.reorderRoutes, "route reorder");
60 const removeRoute = useAtomCommand(environmentCatalog.removeRoute, "route removal");
61 const [editing, setEditing] = useState(false);
62 const saved = entry === undefined ? [] : connectionRoutes(entry);
63 const savedIds = saved.map((route) => connectionRouteId(route.target));
64 // A dropped order shows until the catalog matches it.
65 const [pending, setPending] = useState<ReadonlyArray<string> | null>(null);
66 const order =
67 pending !== null &&
68 pending.length === savedIds.length &&
69 pending.some((id, index) => id !== savedIds[index])
70 ? pending
71 : savedIds;
72 const [drag, setDrag] = useState<{ readonly id: string; readonly translation: number } | null>(
73 null,
74 );
75 // Rows size to their content, so a drag measures how far it has moved past each one.
76 const [heights, setHeights] = useState<ReadonlyMap<string, number>>(() => new Map());
77 // Each drop remounts the rows so the new order and the cleared drag offsets
78 // land in one frame. Kept rows would show their old offsets in their new
79 // slots until the animated style catches up, and the card flashes empty.
80 const [drops, setDrops] = useState(0);
81 if (entry === undefined) return null;
82
83 const byId = new Map(saved.map((route) => [connectionRouteId(route.target), route]));
84 const routes = order.flatMap((id) => byId.get(id) ?? []);
85 const activeRouteId =
86 connected && Option.isSome(prepared) ? connectionRouteId(prepared.value.target) : null;
87
88 const commit = (next: ReadonlyArray<string>) => {
89 setPending(next);
90 void reorder({ environmentId, routeIds: next }).then((result) => {
91 if (result._tag === "Failure") setPending(null);
92 });
93 };
94 const move = (from: number, to: number) => {
95 if (to < 0 || to >= order.length || from === to) return;
96 const next = [...order];
97 const [moved] = next.splice(from, 1);
98 next.splice(to, 0, moved!);
99 commit(next);
100 };
101 // A lifted row takes a neighbour's slot once it has moved past half of that row.
102 const dropIndex = (from: number, translation: number) => {
103 const step = translation > 0 ? 1 : -1;
104 let to = from;
105 let remaining = Math.abs(translation);
106 while (to + step >= 0 && to + step < order.length) {
107 const next = heights.get(order[to + step]!) ?? 0;
108 if (next === 0 || remaining < next / 2) break;
109 remaining -= next;
110 to += step;
111 }
112 return to;
113 };
114 const confirmRemove = (route: ConnectionRoute) =>
115 Alert.alert(
116 `Remove ${connectionRouteLabel(route)}?`,
117 connectionRouteAddress(route) ?? undefined,
118 [
119 { text: "Cancel", style: "cancel" },
120 {
121 text: "Remove",
122 style: "destructive",
123 onPress: () =>
124 void removeRoute({ environmentId, routeId: connectionRouteId(route.target) }),
125 },
126 ],
127 );
128
129 const dragFrom = drag === null ? -1 : order.indexOf(drag.id);
130 const dragTo = drag === null ? -1 : dropIndex(dragFrom, drag.translation);
131
132 return (
133 <SettingsSection
134 title="Routes"
135 trailing={
136 routes.length > 1 ? (
137 <Pressable
138 accessibilityRole="button"
139 onPress={() => setEditing((value) => !value)}
140 className="px-2 py-1 active:opacity-70"
141 >
142 <Text className="text-sm font-t3-medium text-foreground android:text-primary-text">
143 {editing ? "Done" : "Edit"}
144 </Text>
145 </Pressable>
146 ) : undefined
147 }
148 >
149 {routes.map((route, index) => {
150 const id = connectionRouteId(route.target);
151 // Rows between the lifted row and its drop slot shift to make room.
152 const lifted = drag === null ? 0 : (heights.get(drag.id) ?? 0);
153 const shift =
154 dragFrom === -1 || index === dragFrom
155 ? 0
156 : dragFrom < dragTo && index > dragFrom && index <= dragTo
157 ? -lifted
158 : dragFrom > dragTo && index < dragFrom && index >= dragTo
159 ? lifted
160 : 0;
161 return (
162 <RouteRow
163 key={`${id}:${drops}`}
164 route={route}
165 position={index + 1}
166 count={routes.length}
167 inUse={id === activeRouteId}
168 editing={editing}
169 offset={index === dragFrom ? (drag?.translation ?? 0) : shift}
170 lifted={index === dragFrom}
171 onHeight={(height) =>
172 setHeights((current) =>
173 current.get(id) === height ? current : new Map(current).set(id, height),
174 )
175 }
176 onDragStart={() => setDrag({ id, translation: 0 })}
177 onDragMove={(translation) => setDrag({ id, translation })}
178 onDragEnd={(translation, cancelled) => {
179 setDrag(null);
180 setDrops((count) => count + 1);
181 if (!cancelled) move(index, dropIndex(index, translation));
182 }}
183 onStep={(direction) => move(index, direction === "up" ? index - 1 : index + 1)}
184 // The last route goes with the machine, which is "Remove" on the row.
185 // A learned route would be learned again, so it is only reordered.
186 onRemove={
187 routes.length > 1 && !isLearned(route) ? () => confirmRemove(route) : undefined
188 }
189 />
190 );
191 })}
192 <SettingsActionRow icon="plus" label="Add route" onPress={onAddRoute} />
193 </SettingsSection>
194 );
195}
196
197function RouteRow(props: {
198 readonly route: ConnectionRoute;
199 readonly position: number;
200 readonly count: number;
201 readonly inUse: boolean;
202 readonly editing: boolean;
203 readonly offset: number;
204 readonly lifted: boolean;
205 readonly onHeight: (height: number) => void;
206 readonly onDragStart: () => void;
207 readonly onDragMove: (translation: number) => void;
208 readonly onDragEnd: (translation: number, cancelled: boolean) => void;
209 readonly onStep: (direction: "up" | "down") => void;
210 readonly onRemove: (() => void) | undefined;
211}) {
212 const { route, lifted, offset } = props;
213 const label = connectionRouteLabel(route);
214 const address = connectionRouteAddress(route);
215 const style = useAnimatedStyle(() => ({
216 transform: [
217 {
218 translateY: lifted
219 ? offset
220 : withTiming(offset, { duration: 160, reduceMotion: ReduceMotion.System }),
221 },
222 ],
223 zIndex: lifted ? 1 : 0,
224 }));
225 return (
226 <Reanimated.View
227 style={style}
228 onLayout={(event) => props.onHeight(event.nativeEvent.layout.height)}
229 className={cn("flex-row items-center gap-4 pl-4", lifted && "bg-grouped-card shadow-md")}
230 >
231 {props.editing && props.onRemove ? (
232 <Pressable
233 accessibilityRole="button"
234 accessibilityLabel={`Remove ${label} route`}
235 hitSlop={8}
236 onPress={props.onRemove}
237 className="active:opacity-70"
238 >
239 <SymbolView
240 name="xmark.circle.fill"
241 size={REMOVE_SIZE}
242 tintColorClassName="accent-danger-foreground"
243 type="monochrome"
244 />
245 </Pressable>
246 ) : props.editing ? (
247 <View style={{ width: REMOVE_SIZE }} />
248 ) : null}
249 <View
250 accessible
251 accessibilityLabel={[
252 label,
253 address,
254 isLearned(route) ? "Found automatically" : null,
255 props.inUse ? "In use" : null,
256 `Route ${props.position} of ${props.count}`,
257 ]
258 .filter((part) => part !== null)
259 .join(", ")}
260 // Matches the padding of the settings rows around it.
261 className={cn(
262 "min-w-0 flex-1 flex-row items-center gap-4 py-4 android:py-3",
263 address !== null ? "android:min-h-18" : "android:min-h-14",
264 !props.editing && "pr-4",
265 )}
266 >
267 <SymbolView
268 name={ROUTE_ICONS[connectionRouteKind(route)]}
269 size={ICON_SIZE}
270 tintColorClassName="accent-icon"
271 type="monochrome"
272 weight="regular"
273 />
274 <View className="min-w-0 flex-1 gap-0.5 android:gap-1">
275 <View className="flex-row items-center gap-2">
276 <Text numberOfLines={1} className="shrink text-lg text-foreground android:text-base">
277 {label}
278 </Text>
279 {props.inUse ? (
280 <StatusPill {...connectionTone("connected")} label="In use" size="compact" />
281 ) : null}
282 </View>
283 {address !== null ? (
284 <Text numberOfLines={1} className="text-sm text-foreground-muted">
285 {isLearned(route) ? `${address} · found automatically` : address}
286 </Text>
287 ) : null}
288 </View>
289 </View>
290 {props.editing ? (
291 <DragHandle
292 title={label}
293 canMoveUp={props.position > 1}
294 canMoveDown={props.position < props.count}
295 onStart={props.onDragStart}
296 onMove={props.onDragMove}
297 onEnd={props.onDragEnd}
298 onStep={props.onStep}
299 />
300 ) : null}
301 </Reanimated.View>
302 );
303}
304
305/** Pan recognition wins over the settings scroll view only inside the handle. */
306function DragHandle(props: {
307 readonly title: string;
308 readonly canMoveUp: boolean;
309 readonly canMoveDown: boolean;
310 readonly onStart: () => void;
311 readonly onMove: (translation: number) => void;
312 readonly onEnd: (translation: number, cancelled: boolean) => void;
313 readonly onStep: (direction: "up" | "down") => void;
314}) {
315 const latest = useRef(props);
316 useEffect(() => {
317 latest.current = props;
318 });
319 const translation = useRef(0);
320 const gesture = useMemo(
321 () =>
322 Gesture.Pan()
323 .minDistance(0)
324 .shouldCancelWhenOutside(false)
325 .runOnJS(true)
326 .onStart(() => {
327 translation.current = 0;
328 latest.current.onStart();
329 })
330 .onUpdate((event) => {
331 translation.current = event.translationY;
332 latest.current.onMove(event.translationY);
333 })
334 .onFinalize((_, success) => latest.current.onEnd(translation.current, !success)),
335 [],
336 );
337 return (
338 <GestureDetector gesture={gesture}>
339 <View
340 collapsable={false}
341 accessible
342 accessibilityRole="adjustable"
343 accessibilityLabel={`Reorder ${props.title}`}
344 accessibilityActions={[
345 ...(props.canMoveUp ? [{ name: "decrement", label: "Move up" }] : []),
346 ...(props.canMoveDown ? [{ name: "increment", label: "Move down" }] : []),
347 ]}
348 onAccessibilityAction={({ nativeEvent }) => {
349 if (nativeEvent.actionName === "decrement" && props.canMoveUp) props.onStep("up");
350 if (nativeEvent.actionName === "increment" && props.canMoveDown) props.onStep("down");
351 }}
352 style={{ width: 48, alignSelf: "stretch", alignItems: "center", justifyContent: "center" }}
353 >
354 <SymbolView
355 name="line.3.horizontal"
356 size={20}
357 tintColorClassName="accent-foreground-muted"
358 />
359 </View>
360 </GestureDetector>
361 );
362}