Open History to see the last commit
1import {
2 DndContext,
3 type DragEndEvent,
4 KeyboardSensor,
5 PointerSensor,
6 closestCenter,
7 useSensor,
8 useSensors,
9} from "@dnd-kit/core";
10import { restrictToParentElement, restrictToVerticalAxis } from "@dnd-kit/modifiers";
11import {
12 SortableContext,
13 arrayMove,
14 sortableKeyboardCoordinates,
15 useSortable,
16 verticalListSortingStrategy,
17} from "@dnd-kit/sortable";
18import { CSS } from "@dnd-kit/utilities";
19import {
20 type ConnectionRoute,
21 connectionRouteAddress,
22 connectionRouteId,
23 connectionRouteLabel,
24 connectionRoutes,
25 isLearned,
26} from "@t3tools/client-runtime/connection";
27import { GripVerticalIcon, PlusIcon, XIcon } from "lucide-react";
28import { useState } from "react";
29
30import { requestConfirmDialog } from "~/confirmDialog";
31import { environmentCatalog } from "~/connection/catalog";
32import { cn } from "~/lib/utils";
33import type { EnvironmentPresentation } from "~/state/environments";
34import { usePreparedConnection } from "~/state/session";
35import { useAtomCommand } from "~/state/use-atom-command";
36import { Button } from "../ui/button";
37import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
38
39export function EnvironmentRoutesList({
40 environment,
41 onAddRoute,
42}: {
43 readonly environment: EnvironmentPresentation;
44 readonly onAddRoute: () => void;
45}) {
46 const saved = connectionRoutes(environment.entry);
47 const savedIds = saved.map((route) => connectionRouteId(route.target));
48 const [pending, setPending] = useState<ReadonlyArray<string> | null>(null);
49 const order: Array<string> =
50 pending !== null &&
51 pending.length === savedIds.length &&
52 pending.some((id, index) => id !== savedIds[index])
53 ? [...pending]
54 : savedIds;
55 const byId = new Map(saved.map((route) => [connectionRouteId(route.target), route]));
56 const routes = order.flatMap((id) => byId.get(id) ?? []);
57
58 const prepared = usePreparedConnection(environment.environmentId);
59 const activeRouteId =
60 prepared._tag === "Some" && environment.connection.phase === "connected"
61 ? connectionRouteId(prepared.value.target)
62 : null;
63 const reorder = useAtomCommand(environmentCatalog.reorderRoutes, "Reorder routes");
64 const removeRoute = useAtomCommand(environmentCatalog.removeRoute, "Remove route");
65 const sensors = useSensors(
66 useSensor(PointerSensor, { activationConstraint: { distance: 4 } }),
67 useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),
68 );
69
70 const confirmRemove = async (route: ConnectionRoute) => {
71 const address = connectionRouteAddress(route);
72 const confirmed = await requestConfirmDialog(
73 `Remove ${connectionRouteLabel(route)} route?${address === null ? "" : `\n${address}`}`,
74 { variant: "destructive" },
75 );
76 if (confirmed !== true) return;
77 await removeRoute({
78 environmentId: environment.environmentId,
79 routeId: connectionRouteId(route.target),
80 });
81 };
82
83 const handleDragEnd = (event: DragEndEvent) => {
84 if (event.over === null || event.active.id === event.over.id) return;
85 const next = arrayMove(
86 order,
87 order.indexOf(String(event.active.id)),
88 order.indexOf(String(event.over.id)),
89 );
90 setPending(next);
91 void reorder({ environmentId: environment.environmentId, routeIds: next }).then((result) => {
92 if (result._tag === "Failure") setPending(null);
93 });
94 };
95
96 return (
97 <div className="mt-2 border-t border-border/50 py-2">
98 <DndContext
99 sensors={sensors}
100 collisionDetection={closestCenter}
101 modifiers={[restrictToVerticalAxis, restrictToParentElement]}
102 onDragEnd={handleDragEnd}
103 >
104 <SortableContext items={order} strategy={verticalListSortingStrategy}>
105 <ol aria-label={`Routes to ${environment.label}, preferred first`}>
106 {routes.map((route, index) => (
107 <SortableRouteRow
108 key={connectionRouteId(route.target)}
109 route={route}
110 position={index + 1}
111 inUse={connectionRouteId(route.target) === activeRouteId}
112 removable={routes.length > 1 && !isLearned(route)}
113 onRemove={() => void confirmRemove(route)}
114 />
115 ))}
116 </ol>
117 </SortableContext>
118 </DndContext>
119 <div className="-ml-1.5 pt-1">
120 <Button size="xs" variant="ghost-muted" onClick={onAddRoute}>
121 <PlusIcon className="size-3" />
122 Add route
123 </Button>
124 </div>
125 </div>
126 );
127}
128
129function SortableRouteRow({
130 route,
131 position,
132 inUse,
133 removable,
134 onRemove,
135}: {
136 readonly route: ConnectionRoute;
137 readonly position: number;
138 readonly inUse: boolean;
139 readonly removable: boolean;
140 readonly onRemove: () => void;
141}) {
142 const id = connectionRouteId(route.target);
143 const label = connectionRouteLabel(route);
144 const address = connectionRouteAddress(route);
145 const {
146 attributes,
147 listeners,
148 setNodeRef,
149 setActivatorNodeRef,
150 transform,
151 transition,
152 isDragging,
153 } = useSortable({ id });
154
155 return (
156 <li
157 ref={setNodeRef}
158 style={{ transform: CSS.Translate.toString(transform), transition }}
159 className={cn(
160 "flex items-center gap-2 py-2",
161 isDragging && "relative z-10 rounded-md bg-background shadow-md",
162 )}
163 >
164 <div className="min-w-0 flex-1">
165 <p className="flex items-center gap-1.5 text-xs font-medium text-foreground">
166 {label}
167 {inUse ? (
168 <span className="rounded-sm bg-success/12 px-1 text-2xs font-normal text-success-foreground">
169 In use
170 </span>
171 ) : null}
172 </p>
173 {address !== null ? (
174 <p className="truncate text-2xs text-muted-foreground">
175 {address}
176 {isLearned(route) ? " · found automatically" : ""}
177 </p>
178 ) : null}
179 </div>
180 <button
181 type="button"
182 ref={setActivatorNodeRef}
183 {...attributes}
184 {...listeners}
185 aria-label={`Reorder ${label}, position ${position}`}
186 className="flex size-6 shrink-0 cursor-grab touch-none items-center justify-center rounded text-muted-foreground/70 outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring active:cursor-grabbing"
187 >
188 <GripVerticalIcon className="size-3.5" />
189 </button>
190 {removable ? (
191 <Tooltip>
192 <TooltipTrigger
193 render={
194 <Button
195 type="button"
196 variant="ghost-muted"
197 size="icon-xs"
198 aria-label={`Remove ${label} route`}
199 onClick={onRemove}
200 />
201 }
202 >
203 <XIcon className="size-3" />
204 </TooltipTrigger>
205 <TooltipPopup side="top">Remove route</TooltipPopup>
206 </Tooltip>
207 ) : null}
208 </li>
209 );
210}