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