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
46export function EnvironmentRoutesSection({
47 environmentId,
48 connected,
49 onAddRoute,
50}: {
51 readonly environmentId: EnvironmentId;
52 readonly connected: boolean;
53 readonly onAddRoute: () => void;
54}) {
55 const entry = useAtomValue(environmentCatalog.catalogValueAtom).entries.get(environmentId);
56 const prepared = useAtomValue(environmentSession.preparedConnectionValueAtom(environmentId));
57 const sessionResult = useAtomValue(environmentSession.sessionStateAtom(environmentId));
58 const session = Option.getOrNull(AsyncResult.value(sessionResult));
59 const [permissionsOpen, setPermissionsOpen] = useState(false);
60 const reorder = useAtomCommand(environmentCatalog.reorderRoutes, "route reorder");
61 const removeRoute = useAtomCommand(environmentCatalog.removeRoute, "route removal");
62 const [editing, setEditing] = useState(false);
63 const saved = entry === undefined ? [] : connectionRoutes(entry);
64 const savedIds = saved.map((route) => connectionRouteId(route.target));
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 const [heights, setHeights] = useState<ReadonlyMap<string, number>>(() => new Map());
76 // Each drop remounts the rows so the new order and the cleared drag offsets
77 // land in one frame. Kept rows would show their old offsets in their new
78 // slots until the animated style catches up, and the card flashes empty.
79 const [drops, setDrops] = useState(0);
80 if (entry === undefined) return null;
81
82 const byId = new Map(saved.map((route) => [connectionRouteId(route.target), route]));
83 const routes = order.flatMap((id) => byId.get(id) ?? []);
84 const activeRouteId =
85 connected && Option.isSome(prepared) ? connectionRouteId(prepared.value.target) : null;
86
87 const commit = (next: ReadonlyArray<string>) => {
88 setPending(next);
89 void reorder({ environmentId, routeIds: next }).then((result) => {
90 if (result._tag === "Failure") setPending(null);
91 });
92 };
93 const move = (from: number, to: number) => {
94 if (to < 0 || to >= order.length || from === to) return;
95 const next = [...order];
96 const [moved] = next.splice(from, 1);
97 next.splice(to, 0, moved!);
98 commit(next);
99 };
100 const dropIndex = (from: number, translation: number) => {
101 const step = translation > 0 ? 1 : -1;
102 let to = from;
103 let remaining = Math.abs(translation);
104 while (to + step >= 0 && to + step < order.length) {
105 const next = heights.get(order[to + step]!) ?? 0;
106 if (next === 0 || remaining < next / 2) break;
107 remaining -= next;
108 to += step;
109 }
110 return to;
111 };
112 const confirmRemove = (route: ConnectionRoute) =>
113 Dialog.alert(
114 `Remove ${connectionRouteLabel(route)}?`,
115 connectionRouteAddress(route) ?? undefined,
116 [
117 { text: "Cancel", style: "cancel" },
118 {
119 text: "Remove",
120 style: "destructive",
121 onPress: () =>
122 void removeRoute({ environmentId, routeId: connectionRouteId(route.target) }),
123 },
124 ],
125 );
126
127 const dragFrom = drag === null ? -1 : order.indexOf(drag.id);
128 const dragTo = drag === null ? -1 : dropIndex(dragFrom, drag.translation);
129
130 return (
131 <SettingsSection
132 title="Routes"
133 trailing={
134 routes.length > 1 ? (
135 <Pressable
136 accessibilityRole="button"
137 onPress={() => setEditing((value) => !value)}
138 className="px-2 py-1 active:opacity-70"
139 >
140 <Text className="text-sm font-t3-medium text-foreground android:text-primary-text">
141 {editing ? "Done" : "Edit"}
142 </Text>
143 </Pressable>
144 ) : undefined
145 }
146 >
147 <SettingsActionRow
148 icon="checkmark.circle"
149 label="Your permissions"
150 onPress={() => setPermissionsOpen((open) => !open)}
151 />
152 {permissionsOpen ? (
153 <View className="gap-2 px-4 py-3">
154 {activeRouteId !== null &&
155 sessionResult._tag !== "Failure" &&
156 !sessionResult.waiting &&
157 session?.authenticated ? (
158 <>
159 <Text className="text-sm text-foreground-muted">
160 Applies to the route marked In use. Other routes may have different permissions and
161 have not been checked.
162 </Text>
163 {AUTH_SCOPE_OPTIONS.map(({ scope, title }) => (
164 <Text key={scope} className="text-sm text-foreground">
165 {title}: {sessionGrantsScope(session, scope) ? "Allowed" : "Not granted"}
166 </Text>
167 ))}
168 </>
169 ) : (
170 <Text className="text-sm text-foreground-muted">
171 Permissions not checked. Connect to this environment to view this session’s
172 permissions.
173 </Text>
174 )}
175 </View>
176 ) : null}
177 {routes.map((route, index) => {
178 const id = connectionRouteId(route.target);
179 const lifted = drag === null ? 0 : (heights.get(drag.id) ?? 0);
180 const shift =
181 dragFrom === -1 || index === dragFrom
182 ? 0
183 : dragFrom < dragTo && index > dragFrom && index <= dragTo
184 ? -lifted
185 : dragFrom > dragTo && index < dragFrom && index >= dragTo
186 ? lifted
187 : 0;
188 return (
189 <RouteRow
190 key={`${id}:${drops}`}
191 route={route}
192 position={index + 1}
193 count={routes.length}
194 inUse={id === activeRouteId}
195 editing={editing}
196 offset={index === dragFrom ? (drag?.translation ?? 0) : shift}
197 lifted={index === dragFrom}
198 onHeight={(height) =>
199 setHeights((current) =>
200 current.get(id) === height ? current : new Map(current).set(id, height),
201 )
202 }
203 onDragStart={() => setDrag({ id, translation: 0 })}
204 onDragMove={(translation) => setDrag({ id, translation })}
205 onDragEnd={(translation, cancelled) => {
206 setDrag(null);
207 setDrops((count) => count + 1);
208 if (!cancelled) move(index, dropIndex(index, translation));
209 }}
210 onStep={(direction) => move(index, direction === "up" ? index - 1 : index + 1)}
211 // A learned route would be learned again, so it is only reordered.
212 onRemove={
213 routes.length > 1 && !isLearned(route) ? () => confirmRemove(route) : undefined
214 }
215 />
216 );
217 })}
218 <SettingsActionRow icon="plus" label="Add route" onPress={onAddRoute} />
219 </SettingsSection>
220 );
221}
222
223function RouteRow(props: {
224 readonly route: ConnectionRoute;
225 readonly position: number;
226 readonly count: number;
227 readonly inUse: boolean;
228 readonly editing: boolean;
229 readonly offset: number;
230 readonly lifted: boolean;
231 readonly onHeight: (height: number) => void;
232 readonly onDragStart: () => void;
233 readonly onDragMove: (translation: number) => void;
234 readonly onDragEnd: (translation: number, cancelled: boolean) => void;
235 readonly onStep: (direction: "up" | "down") => void;
236 readonly onRemove: (() => void) | undefined;
237}) {
238 const { route, lifted, offset } = props;
239 const label = connectionRouteLabel(route);
240 const address = connectionRouteAddress(route);
241 const style = useAnimatedStyle(() => ({
242 transform: [
243 {
244 translateY: lifted
245 ? offset
246 : withTiming(offset, { duration: 160, reduceMotion: ReduceMotion.System }),
247 },
248 ],
249 zIndex: lifted ? 1 : 0,
250 }));
251 return (
252 <Reanimated.View
253 style={style}
254 onLayout={(event) => props.onHeight(event.nativeEvent.layout.height)}
255 className={cn("flex-row items-center gap-4 pl-4", lifted && "bg-grouped-card shadow-md")}
256 >
257 {props.editing && props.onRemove ? (
258 <Pressable
259 accessibilityRole="button"
260 accessibilityLabel={`Remove ${label} route`}
261 hitSlop={8}
262 onPress={props.onRemove}
263 className="active:opacity-70"
264 >
265 <SymbolView
266 name="xmark.circle.fill"
267 size={REMOVE_SIZE}
268 tintColorClassName="accent-danger-foreground"
269 type="monochrome"
270 />
271 </Pressable>
272 ) : props.editing ? (
273 <View style={{ width: REMOVE_SIZE }} />
274 ) : null}
275 <View
276 accessible
277 accessibilityLabel={[
278 label,
279 address,
280 isLearned(route) ? "Found automatically" : null,
281 props.inUse ? "In use" : null,
282 `Route ${props.position} of ${props.count}`,
283 ]
284 .filter((part) => part !== null)
285 .join(", ")}
286 className={cn(
287 "min-w-0 flex-1 flex-row items-center gap-4 py-4 android:py-3",
288 address !== null ? "android:min-h-18" : "android:min-h-14",
289 !props.editing && "pr-4",
290 )}
291 >
292 <SymbolView
293 name={ROUTE_ICONS[connectionRouteKind(route)]}
294 size={ICON_SIZE}
295 tintColorClassName="accent-icon"
296 type="monochrome"
297 weight="regular"
298 />
299 <View className="min-w-0 flex-1 gap-0.5 android:gap-1">
300 <View className="flex-row items-center gap-2">
301 <Text numberOfLines={1} className="shrink text-lg text-foreground android:text-base">
302 {label}
303 </Text>
304 {props.inUse ? (
305 <StatusPill {...connectionTone("connected")} label="In use" size="compact" />
306 ) : null}
307 </View>
308 {address !== null ? (
309 <Text numberOfLines={1} className="text-sm text-foreground-muted">
310 {isLearned(route) ? `${address} · found automatically` : address}
311 </Text>
312 ) : null}
313 </View>
314 </View>
315 {props.editing ? (
316 <SettingsDragHandle
317 title={label}
318 canMoveUp={props.position > 1}
319 canMoveDown={props.position < props.count}
320 onStart={props.onDragStart}
321 onMove={props.onDragMove}
322 onEnd={props.onDragEnd}
323 onStep={props.onStep}
324 />
325 ) : null}
326 </Reanimated.View>
327 );
328}