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

EnvironmentRoutesList.tsx

209 lines6.9 KB

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