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