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

EnvironmentRoutesSection.tsx

362 lines13.4 KB

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