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 pendingRouteOrder,
14} from "@t3tools/client-runtime/connection";
15import { type EnvironmentId, sessionGrantsScope } from "@t3tools/contracts";
16import {
17 AUTH_SCOPE_OPTIONS,
18 sessionPermissionsUnavailableMessage,
19} from "@t3tools/shared/authScopeOptions";
20import { AsyncResult } from "effect/reactivity";
21import * as Option from "effect/Option";
22import { useState } from "react";
23import { Platform, Pressable, View } from "react-native";
24import Reanimated, { ReduceMotion, useAnimatedStyle, withTiming } from "react-native-reanimated";
25
26import { type AppSymbolName, SymbolView } from "../../components/ui/AppSymbol";
27import { AppText as Text } from "../../components/ui/AppText";
28import { StatusPill } from "../../components/StatusPill";
29import { environmentCatalog } from "../../connection/catalog";
30import { cn } from "../../lib/cn";
31import { environmentSession } from "../../state/session";
32import { useAtomCommand } from "../../state/use-atom-command";
33import { connectionTone } from "../connection/connectionTone";
34import { ListActionRow as SettingsActionRow } from "../../components/ui/ListActionRow";
35import { SettingsDragHandle } from "./components/SettingsDragHandle";
36import { SettingsSection } from "./components/SettingsSection";
37
38const ICON_SIZE = Platform.OS === "android" ? 24 : 22;
39const REMOVE_SIZE = 20;
40
41const ROUTE_ICONS: Record<ConnectionRouteKind, AppSymbolName> = {
42 relay: "cloud",
43 loopback: "desktopcomputer",
44 lan: "wifi",
45 tailnet: "point.3.connected.trianglepath.dotted",
46 vpn: { ios: "lock.shield", android: "lock" },
47 public: "globe",
48 ssh: "terminal",
49};
50
51export function EnvironmentRoutesSection({
52 environmentId,
53 connected,
54 onAddRoute,
55}: {
56 readonly environmentId: EnvironmentId;
57 readonly connected: boolean;
58 readonly onAddRoute: () => void;
59}) {
60 const entry = useAtomValue(environmentCatalog.catalogValueAtom).entries.get(environmentId);
61 const prepared = useAtomValue(environmentSession.preparedConnectionValueAtom(environmentId));
62 const sessionResult = useAtomValue(environmentSession.sessionStateAtom(environmentId));
63 const session = AsyncResult.getOrElse(sessionResult, () => null);
64 const [permissionsOpen, setPermissionsOpen] = useState(false);
65 const reorder = useAtomCommand(environmentCatalog.reorderRoutes, "route reorder");
66 const removeRoute = useAtomCommand(environmentCatalog.removeRoute, "route removal");
67 const [editing, setEditing] = useState(false);
68 const saved = entry === undefined ? [] : connectionRoutes(entry);
69 const savedIds = saved.map((route) => connectionRouteId(route.target));
70 const [pending, setPending] = useState<ReadonlyArray<string> | null>(null);
71 const shownPending = pendingRouteOrder(pending, savedIds);
72 // Dropped during render so a stale order never outlives the save it was for.
73 if (pending !== null && shownPending === null) setPending(null);
74 const order = shownPending ?? savedIds;
75 const [drag, setDrag] = useState<{ readonly id: string; readonly translation: number } | null>(
76 null,
77 );
78 const [heights, setHeights] = useState<ReadonlyMap<string, number>>(() => new Map());
79 // Remount dropped rows so data order and cleared drag offsets change together without flashing.
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 {sessionPermissionsUnavailableMessage({
169 connected: activeRouteId !== null,
170 failed: sessionResult._tag === "Failure",
171 rejected:
172 sessionResult._tag !== "Failure" &&
173 !sessionResult.waiting &&
174 session?.authenticated === false,
175 })}
176 </Text>
177 )}
178 </View>
179 ) : null}
180 {routes.map((route, index) => {
181 const id = connectionRouteId(route.target);
182 const lifted = drag === null ? 0 : (heights.get(drag.id) ?? 0);
183 const shift =
184 dragFrom === -1 || index === dragFrom
185 ? 0
186 : dragFrom < dragTo && index > dragFrom && index <= dragTo
187 ? -lifted
188 : dragFrom > dragTo && index < dragFrom && index >= dragTo
189 ? lifted
190 : 0;
191 return (
192 <RouteRow
193 key={`${id}:${drops}`}
194 route={route}
195 position={index + 1}
196 count={routes.length}
197 inUse={id === activeRouteId}
198 editing={editing}
199 offset={index === dragFrom ? (drag?.translation ?? 0) : shift}
200 lifted={index === dragFrom}
201 onHeight={(height) =>
202 setHeights((current) =>
203 current.get(id) === height ? current : new Map(current).set(id, height),
204 )
205 }
206 onDragStart={() => setDrag({ id, translation: 0 })}
207 onDragMove={(translation) => setDrag({ id, translation })}
208 onDragEnd={(translation, cancelled) => {
209 setDrag(null);
210 setDrops((count) => count + 1);
211 if (!cancelled) move(index, dropIndex(index, translation));
212 }}
213 onStep={(direction) => move(index, direction === "up" ? index - 1 : index + 1)}
214 // A learned route would be learned again, so it is only reordered.
215 onRemove={
216 routes.length > 1 && !isLearned(route) ? () => confirmRemove(route) : undefined
217 }
218 />
219 );
220 })}
221 <SettingsActionRow icon="plus" label="Add route" onPress={onAddRoute} />
222 </SettingsSection>
223 );
224}
225
226function RouteRow(props: {
227 readonly route: ConnectionRoute;
228 readonly position: number;
229 readonly count: number;
230 readonly inUse: boolean;
231 readonly editing: boolean;
232 readonly offset: number;
233 readonly lifted: boolean;
234 readonly onHeight: (height: number) => void;
235 readonly onDragStart: () => void;
236 readonly onDragMove: (translation: number) => void;
237 readonly onDragEnd: (translation: number, cancelled: boolean) => void;
238 readonly onStep: (direction: "up" | "down") => void;
239 readonly onRemove: (() => void) | undefined;
240}) {
241 const { route, lifted, offset } = props;
242 const label = connectionRouteLabel(route);
243 const address = connectionRouteAddress(route);
244 const style = useAnimatedStyle(() => ({
245 transform: [
246 {
247 translateY: lifted
248 ? offset
249 : withTiming(offset, { duration: 160, reduceMotion: ReduceMotion.System }),
250 },
251 ],
252 zIndex: lifted ? 1 : 0,
253 }));
254 return (
255 <Reanimated.View
256 style={style}
257 onLayout={(event) => props.onHeight(event.nativeEvent.layout.height)}
258 className={cn("flex-row items-center gap-4 pl-4", lifted && "bg-grouped-card shadow-md")}
259 >
260 {props.editing && props.onRemove ? (
261 <Pressable
262 accessibilityRole="button"
263 accessibilityLabel={`Remove ${label} route`}
264 hitSlop={8}
265 onPress={props.onRemove}
266 className="active:opacity-70"
267 >
268 <SymbolView
269 name="xmark.circle.fill"
270 size={REMOVE_SIZE}
271 tintColorClassName="accent-danger-foreground"
272 type="monochrome"
273 />
274 </Pressable>
275 ) : props.editing ? (
276 <View style={{ width: REMOVE_SIZE }} />
277 ) : null}
278 <View
279 accessible
280 accessibilityLabel={[
281 label,
282 address,
283 isLearned(route) ? "Found automatically" : null,
284 props.inUse ? "In use" : null,
285 `Route ${props.position} of ${props.count}`,
286 ]
287 .filter((part) => part !== null)
288 .join(", ")}
289 className={cn(
290 "min-w-0 flex-1 flex-row items-center gap-4 py-4 android:py-3",
291 address !== null ? "android:min-h-18" : "android:min-h-14",
292 !props.editing && "pr-4",
293 )}
294 >
295 <SymbolView
296 name={ROUTE_ICONS[connectionRouteKind(route)]}
297 size={ICON_SIZE}
298 tintColorClassName="accent-icon"
299 type="monochrome"
300 weight="regular"
301 />
302 <View className="min-w-0 flex-1 gap-0.5 android:gap-1">
303 <View className="flex-row items-center gap-2">
304 <Text numberOfLines={1} className="shrink text-lg text-foreground android:text-base">
305 {label}
306 </Text>
307 {props.inUse ? (
308 <StatusPill {...connectionTone("connected")} label="In use" size="compact" />
309 ) : null}
310 </View>
311 {address !== null ? (
312 <Text numberOfLines={1} className="text-sm text-foreground-muted">
313 {isLearned(route) ? `${address} · found automatically` : address}
314 </Text>
315 ) : null}
316 </View>
317 </View>
318 {props.editing ? (
319 <SettingsDragHandle
320 title={label}
321 canMoveUp={props.position > 1}
322 canMoveDown={props.position < props.count}
323 onStart={props.onDragStart}
324 onMove={props.onDragMove}
325 onEnd={props.onDragEnd}
326 onStep={props.onStep}
327 />
328 ) : null}
329 </Reanimated.View>
330 );
331}