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