The best way to control Claude Code, Codex and more from any computer or phone

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