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