Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

EnvironmentRoutesSection.tsx

332 lines12.0 KB

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