The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import { RegistryContext, useAtomValue } from "@effect/atom-react"; |
| 2 | import { |
| 3 | type ConnectionRouteKind, |
| 4 | connectionRouteId, |
| 5 | connectionRouteKind, |
| 6 | connectionRouteLabelText, |
| 7 | connectionRoutes, |
| 8 | routeHttpBaseUrl, |
| 9 | } from "@t3tools/client-runtime/connection"; |
| 10 | import { |
| 11 | ANOTHER_ADDRESS, |
| 12 | linkableMachines, |
| 13 | offersLinkedEnvironments, |
| 14 | } from "@t3tools/client-runtime/link-request"; |
| 15 | import { thrownErrorMessage } from "@t3tools/client-runtime/errors"; |
| 16 | import type { PeerLinkHealth } from "@t3tools/client-runtime/state/peerLinks"; |
| 17 | import { AuthAccessWriteScope, type EnvironmentId } from "@t3tools/contracts"; |
| 18 | import * as DateTime from "effect/DateTime"; |
| 19 | import * as Option from "effect/Option"; |
| 20 | import { useGT, useMessages } from "gt-react"; |
| 21 | import { |
| 22 | AppWindowIcon, |
| 23 | ArrowUpDownIcon, |
| 24 | CheckIcon, |
| 25 | CircleHelpIcon, |
| 26 | CloudIcon, |
| 27 | GlobeIcon, |
| 28 | MaximizeIcon, |
| 29 | MinusIcon, |
| 30 | PlusIcon, |
| 31 | SearchIcon, |
| 32 | TriangleAlertIcon, |
| 33 | UnfoldVerticalIcon, |
| 34 | FoldVerticalIcon, |
| 35 | XIcon, |
| 36 | } from "lucide-react"; |
| 37 | import { |
| 38 | memo, |
| 39 | type FocusEvent, |
| 40 | type KeyboardEvent, |
| 41 | type MouseEvent, |
| 42 | type PointerEvent, |
| 43 | type ReactNode, |
| 44 | useContext, |
| 45 | useEffect, |
| 46 | useEffectEvent, |
| 47 | useRef, |
| 48 | useState, |
| 49 | } from "react"; |
| 50 | |
| 51 | import { hasCloudPublicConfig } from "~/cloud/publicConfig"; |
| 52 | import { isElectron } from "~/env"; |
| 53 | import { useLiveRefresh } from "~/hooks/useLiveRefresh"; |
| 54 | import { useNowMinute } from "~/hooks/useNowMinute"; |
| 55 | import { useStableCallback } from "~/hooks/useStableCallback"; |
| 56 | import { observeResize } from "~/lib/observeResize"; |
| 57 | import { cn } from "~/lib/utils"; |
| 58 | import { |
| 59 | type EnvironmentPresentation, |
| 60 | useEnvironments, |
| 61 | useRelayEnvironmentDiscovery, |
| 62 | useRetainedRelayEnvironments, |
| 63 | } from "~/state/environments"; |
| 64 | import { environmentIdsKey } from "~/state/environmentAtomList"; |
| 65 | import { peerLinkEnvironment, peerLinkListsAtom, usePeerLinkHosts } from "~/state/peerLinks"; |
| 66 | import { formatEnvironmentQueryError } from "~/state/query"; |
| 67 | import { relayEnvironmentDiscovery } from "~/state/relay"; |
| 68 | import { preparedConnectionsAtom, useEnvironmentsWithScope } from "~/state/session"; |
| 69 | import { useAtomCommand } from "~/state/use-atom-command"; |
| 70 | import { accessConfig } from "../auth/ConnectAgentSurface"; |
| 71 | import { connectionPhaseDotClassName } from "../ConnectionStatusDot"; |
| 72 | import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon"; |
| 73 | import { Button } from "../ui/button"; |
| 74 | import { InputGroup, InputGroupAddon, InputGroupInput } from "../ui/input-group"; |
| 75 | import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu"; |
| 76 | import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover"; |
| 77 | import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; |
| 78 | import { |
| 79 | buildFleetGraph, |
| 80 | anchorFleetView, |
| 81 | fitFleetLayout, |
| 82 | fleetCanvasHeight, |
| 83 | FLEET_CLIENT_NODE_ID, |
| 84 | fleetDrawnLinkId, |
| 85 | fleetEnvironmentNodeId, |
| 86 | fleetFocusRects, |
| 87 | fleetLinkAction, |
| 88 | fleetLinkOffer, |
| 89 | fleetMoreNodeId, |
| 90 | fleetNeighborhood, |
| 91 | fleetNodesInBox, |
| 92 | fleetSearch, |
| 93 | fleetLayoutWidth, |
| 94 | fleetShapeKey, |
| 95 | fleetStackPartial, |
| 96 | fleetStacks, |
| 97 | fleetTwoWayLinks, |
| 98 | type FleetArrow, |
| 99 | type FleetColumn, |
| 100 | type FleetDirection, |
| 101 | type FleetEnvironmentInput, |
| 102 | type FleetEnvironmentNode, |
| 103 | type FleetFocus, |
| 104 | type FleetFoldGroup, |
| 105 | type FleetGraph, |
| 106 | type FleetHeldView, |
| 107 | type FleetLayout, |
| 108 | type FleetLinkAction, |
| 109 | type FleetLinkEdge, |
| 110 | type FleetLinkOffer, |
| 111 | type FleetNode, |
| 112 | type FleetRect, |
| 113 | type FleetRouteEdge, |
| 114 | type FleetRouteState, |
| 115 | type FleetStack, |
| 116 | type FleetViewTransform, |
| 117 | isLinkEdge, |
| 118 | isRouteEdge, |
| 119 | layoutFleetGraph, |
| 120 | linkNeedsAttention, |
| 121 | linkTroubleRank, |
| 122 | worseLinkHealth, |
| 123 | zoomFleetView, |
| 124 | nextFleetNode, |
| 125 | } from "./environmentsMap.logic"; |
| 126 | import { |
| 127 | AccessMeter, |
| 128 | accessLevel, |
| 129 | FleetDetails, |
| 130 | type FleetDetailsProps, |
| 131 | HealthGlyph, |
| 132 | healthLabel, |
| 133 | healthTone, |
| 134 | } from "./EnvironmentsMapDetails"; |
| 135 | import { LinkEnvironmentDialog, type LinkEnvironmentPrefill } from "./LinkedEnvironmentsSettings"; |
| 136 | import { LinkSeveralEnvironmentsDialog } from "./LinkSeveralEnvironments"; |
| 137 | import { savedBackendStatus } from "./SavedEnvironmentRows"; |
| 138 | import { SettingsSearchTarget } from "./settingsLayout"; |
| 139 | |
| 140 | type GT = ReturnType<typeof useGT>; |
| 141 | type Messages = ReturnType<typeof useMessages>; |
| 142 | |
| 143 | /** One ordinal scale for access, read only to full access: a link's line gets heavier and darker. */ |
| 144 | const ACCESS_STROKE_WIDTHS = [1.25, 1.75, 2.25, 2.75, 3.5]; |
| 145 | const ACCESS_STROKE_OPACITIES = [0.4, 0.5, 0.62, 0.76, 0.9]; |
| 146 | /** Short maps get a short canvas; a tall one grows to this, then the fit shrinks it or it pans. */ |
| 147 | const CANVAS_HEIGHT = { min: 180, max: 840 }; |
| 148 | const ARROW_ROVE: Record<string, FleetDirection> = { |
| 149 | ArrowUp: "up", |
| 150 | ArrowDown: "down", |
| 151 | ArrowLeft: "left", |
| 152 | ArrowRight: "right", |
| 153 | }; |
| 154 | const NO_STACKS: ReadonlySet<string> = new Set(); |
| 155 | const NO_SELECTION: ReadonlySet<string> = new Set(); |
| 156 | /** Search centres a machine at a scale it can be read at, however far out the map was. */ |
| 157 | const FOUND_MIN_SCALE = 0.85; |
| 158 | |
| 159 | /** What an opened stack adds fades in over the same time the view takes to make room for it. */ |
| 160 | const APPEAR = |
| 161 | "transition-opacity duration-200 ease-out starting:opacity-0 motion-reduce:transition-none"; |
| 162 | |
| 163 | /** Dashes repeat a link's health without colour, one pattern per kind of trouble. */ |
| 164 | function healthDash(health: PeerLinkHealth): string | undefined { |
| 165 | if (health.kind === "expired") return "1 5"; |
| 166 | if (health.kind === "failing") return "8 3 1 3"; |
| 167 | return health.kind === "unreachable" ? "5 4" : undefined; |
| 168 | } |
| 169 | |
| 170 | /** Worst first: a machine several hosts link to wears the health of its most troubled link. */ |
| 171 | const byTrouble = (left: FleetLinkEdge, right: FleetLinkEdge) => |
| 172 | linkTroubleRank(left.health) - linkTroubleRank(right.health); |
| 173 | |
| 174 | /** A machine's outline carries its link's health too. */ |
| 175 | function healthBorder(health: PeerLinkHealth): string { |
| 176 | if (health.kind === "expired") return "border-dotted border-destructive/70"; |
| 177 | if (health.kind === "failing") return "border-destructive/70"; |
| 178 | if (health.kind === "unreachable") return "border-dashed border-foreground/35"; |
| 179 | return health.expiresInDays === null ? "border-border" : "border-warning/70"; |
| 180 | } |
| 181 | |
| 182 | /** How each route state is drawn: the one in use stands out, the rest stay quiet. */ |
| 183 | const ROUTE_STYLES: Record< |
| 184 | FleetRouteState, |
| 185 | { readonly wire: string; readonly width: number; readonly dash?: string; readonly pill: string } |
| 186 | > = { |
| 187 | "in-use": { |
| 188 | wire: "text-success", |
| 189 | width: 1.75, |
| 190 | pill: "border-success/70 font-medium text-foreground", |
| 191 | }, |
| 192 | standby: { wire: "text-muted-foreground/60", width: 1, pill: "border-border" }, |
| 193 | trying: { wire: "text-warning", width: 1, dash: "1 4", pill: "border-warning/60" }, |
| 194 | down: { wire: "text-muted-foreground/60", width: 1, dash: "4 4", pill: "border-dashed" }, |
| 195 | idle: { wire: "text-muted-foreground/40", width: 1, dash: "4 4", pill: "border-dashed" }, |
| 196 | refused: { |
| 197 | wire: "text-destructive/80", |
| 198 | width: 1, |
| 199 | dash: "4 4", |
| 200 | pill: "border-dashed border-destructive/60 text-destructive", |
| 201 | }, |
| 202 | offered: { wire: "text-muted-foreground/50", width: 1, dash: "1 4", pill: "border-dotted" }, |
| 203 | }; |
| 204 | |
| 205 | function routeKindLabel(kind: ConnectionRouteKind, gt: GT): string { |
| 206 | switch (kind) { |
| 207 | case "relay": |
| 208 | return "T3 Connect"; |
| 209 | case "loopback": |
| 210 | return gt("This device"); |
| 211 | case "lan": |
| 212 | return "LAN"; |
| 213 | case "tailnet": |
| 214 | return "Tailscale"; |
| 215 | case "vpn": |
| 216 | return "VPN"; |
| 217 | case "ssh": |
| 218 | return "SSH"; |
| 219 | case "public": |
| 220 | return gt("Public", { $context: "kind of network route: a public internet address" }); |
| 221 | } |
| 222 | } |
| 223 | |
| 224 | function routeStateLabel(state: FleetRouteState, gt: GT): string { |
| 225 | switch (state) { |
| 226 | case "in-use": |
| 227 | return gt("In use"); |
| 228 | case "standby": |
| 229 | return gt("Standby", { $context: "a network route that is saved but not carrying traffic" }); |
| 230 | case "trying": |
| 231 | return gt("Connecting"); |
| 232 | case "down": |
| 233 | return gt("Not connected"); |
| 234 | case "idle": |
| 235 | return gt("Not in use"); |
| 236 | case "refused": |
| 237 | return gt("Sign-in refused"); |
| 238 | case "offered": |
| 239 | return gt("Not added"); |
| 240 | } |
| 241 | } |
| 242 | |
| 243 | /** Asks T3 Connect for the account's machines once, as the list's own rows do on mount. */ |
| 244 | function useConnectMachines() { |
| 245 | const gt = useGT(); |
| 246 | const m = useMessages(); |
| 247 | const discovery = useRelayEnvironmentDiscovery(); |
| 248 | const refresh = useAtomCommand(relayEnvironmentDiscovery.refresh, { reportFailure: false }); |
| 249 | const discoverIfUnasked = useEffectEvent(() => { |
| 250 | if (hasCloudPublicConfig() && !discovery.listed && !discovery.refreshing) void refresh(); |
| 251 | }); |
| 252 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- one T3 Connect listing when the map mounts, the request the list makes on mount |
| 253 | useEffect(() => { |
| 254 | discoverIfUnasked(); |
| 255 | }, []); |
| 256 | const machines = useRetainedRelayEnvironments(); |
| 257 | // A failed listing is not an account with no machines: say so, with a way to ask again. |
| 258 | const message = discovery.refreshing |
| 259 | ? null |
| 260 | : discovery.offline && !discovery.listed |
| 261 | ? gt("You appear to be offline.") |
| 262 | : thrownErrorMessage(Option.getOrNull(discovery.error), m); |
| 263 | return { |
| 264 | machines, |
| 265 | problem: message === null ? null : { message, retry: () => void refresh() }, |
| 266 | }; |
| 267 | } |
| 268 | |
| 269 | function useFleetGraph() { |
| 270 | const gt = useGT(); |
| 271 | const m = useMessages(); |
| 272 | const { environments } = useEnvironments(); |
| 273 | const hosts = usePeerLinkHosts(); |
| 274 | const nowMinute = useNowMinute(); |
| 275 | const hostsKey = environmentIdsKey(hosts.map((host) => host.environmentId)); |
| 276 | const lists = useAtomValue(peerLinkListsAtom(hostsKey)); |
| 277 | const registry = useContext(RegistryContext); |
| 278 | // Links made from another client or the CLI bump nothing these lists read, so coming back to |
| 279 | // the window asks again, as the list view does, and so does a change in which machines can be |
| 280 | // asked. Listing probes every linked machine: too costly for a timer. |
| 281 | useLiveRefresh( |
| 282 | () => { |
| 283 | for (const host of hosts) { |
| 284 | const list = peerLinkEnvironment.list({ environmentId: host.environmentId, input: {} }); |
| 285 | if (!registry.get(list).waiting) registry.refresh(list); |
| 286 | } |
| 287 | }, |
| 288 | { key: `environments-map:${hostsKey}`, intervalMs: null, refreshOnShow: true }, |
| 289 | ); |
| 290 | const prepared = useAtomValue( |
| 291 | preparedConnectionsAtom( |
| 292 | environmentIdsKey(environments.map((environment) => environment.environmentId)), |
| 293 | ), |
| 294 | ); |
| 295 | const writable = useEnvironmentsWithScope(environments, AuthAccessWriteScope); |
| 296 | const { machines: connect, problem: connectProblem } = useConnectMachines(); |
| 297 | const machines = linkableMachines({ |
| 298 | environments, |
| 299 | threadEnvironmentId: null, |
| 300 | links: [], |
| 301 | connect, |
| 302 | }); |
| 303 | const machineById = new Map(machines.map((machine) => [machine.environmentId, machine])); |
| 304 | const listByHost = new Map(hosts.map((host, index) => [host.environmentId, lists[index]])); |
| 305 | const inputs = environments.map((environment, index): FleetEnvironmentInput => { |
| 306 | const list = listByHost.get(environment.environmentId); |
| 307 | const connected = environment.connection.phase === "connected"; |
| 308 | const active = connected ? Option.getOrNull(prepared[index] ?? Option.none()) : null; |
| 309 | const offersLinks = offersLinkedEnvironments(environment.serverConfig); |
| 310 | return { |
| 311 | environmentId: environment.environmentId, |
| 312 | label: environment.label, |
| 313 | machine: machineById.get(environment.environmentId)?.machine ?? null, |
| 314 | phase: environment.connection.phase, |
| 315 | enabled: environment.entry.enabled, |
| 316 | routes: connectionRoutes(environment.entry).map((route) => ({ |
| 317 | id: connectionRouteId(route.target), |
| 318 | kind: connectionRouteKind(route), |
| 319 | ...(connectionRouteKind(route) === "tailnet" && |
| 320 | routeHttpBaseUrl(route)?.startsWith("https:") === true |
| 321 | ? { label: connectionRouteLabelText(route, m) } |
| 322 | : {}), |
| 323 | })), |
| 324 | activeRouteId: active === null ? null : connectionRouteId(active.target), |
| 325 | refusedRouteIds: environment.refusedRouteIds, |
| 326 | offersLinks, |
| 327 | canWriteAccess: writable.has(environment.environmentId), |
| 328 | hasLinkAddress: (machineById.get(environment.environmentId)?.urls.length ?? 0) > 0, |
| 329 | outgoing: |
| 330 | list === undefined |
| 331 | ? { state: connected && !offersLinks ? "off" : "unknown" } |
| 332 | : list._tag === "Success" |
| 333 | ? { state: "loaded", links: list.value.links } |
| 334 | : list._tag === "Failure" |
| 335 | ? { state: "error", message: formatEnvironmentQueryError(list.cause, m) } |
| 336 | : { state: "loading" }, |
| 337 | }; |
| 338 | }); |
| 339 | const graph = buildFleetGraph({ |
| 340 | clientLabel: isElectron ? gt("This device") : gt("This browser"), |
| 341 | environments: inputs, |
| 342 | connectMachines: machines |
| 343 | .filter((machine) => machine.connectOnly) |
| 344 | .map((machine) => ({ |
| 345 | environmentId: machine.environmentId, |
| 346 | label: machine.label, |
| 347 | machine: machine.machine, |
| 348 | availability: connect.get(machine.environmentId)?.availability ?? "checking", |
| 349 | })), |
| 350 | now: DateTime.makeUnsafe(nowMinute), |
| 351 | }); |
| 352 | return { graph, environments, connectProblem }; |
| 353 | } |
| 354 | |
| 355 | /** |
| 356 | * The layout for the graph's current shape at the canvas's width; a health or status change |
| 357 | * reuses the last one. |
| 358 | */ |
| 359 | function useFleetLayout( |
| 360 | graph: FleetGraph, |
| 361 | stacks: ReadonlyArray<FleetStack>, |
| 362 | shapeKey: string, |
| 363 | canvasWidth: number | null, |
| 364 | ) { |
| 365 | const width = canvasWidth === null ? undefined : fleetLayoutWidth(canvasWidth); |
| 366 | const key = `${shapeKey}\n${width}`; |
| 367 | const [laid, setLaid] = useState(() => ({ key, layout: layoutFleetGraph(graph, stacks, width) })); |
| 368 | if (laid.key === key) return laid; |
| 369 | const next = { key, layout: layoutFleetGraph(graph, stacks, width) }; |
| 370 | setLaid(next); |
| 371 | return next; |
| 372 | } |
| 373 | |
| 374 | interface LinkRequest { |
| 375 | readonly serial: number; |
| 376 | readonly environmentId: EnvironmentId; |
| 377 | readonly prefill: LinkEnvironmentPrefill; |
| 378 | readonly open: boolean; |
| 379 | } |
| 380 | |
| 381 | interface BatchRequest { |
| 382 | readonly serial: number; |
| 383 | readonly environmentId: EnvironmentId; |
| 384 | readonly preset: ReadonlyArray<EnvironmentId>; |
| 385 | /** The machines were dropped on or selected for this link, so the dialog lists only them. */ |
| 386 | readonly presetOnly: boolean; |
| 387 | readonly open: boolean; |
| 388 | } |
| 389 | |
| 390 | /** A drop the client cannot link in one go, explained where it happened. */ |
| 391 | type CodeOnlyDrop = Extract<FleetLinkAction, { kind: "code-only" }>; |
| 392 | |
| 393 | /** |
| 394 | * Every machine this app knows about, how it reaches each one, and which of them are linked. |
| 395 | * Selecting a machine shows the controls the list has for it. |
| 396 | */ |
| 397 | export function EnvironmentsMap( |
| 398 | props: Pick< |
| 399 | FleetDetailsProps, |
| 400 | "renderSavedEnvironment" | "renderConnectMachine" | "onAddEnvironment" |
| 401 | > & { readonly footerId?: string }, |
| 402 | ) { |
| 403 | const { graph, environments, connectProblem } = useFleetGraph(); |
| 404 | const [expanded, setExpanded] = useState(NO_STACKS); |
| 405 | const stacks = fleetStacks(graph, expanded); |
| 406 | const key = fleetShapeKey(graph, stacks); |
| 407 | const [picked, setPicked] = useState<FleetFocus | null>(null); |
| 408 | // Machines ticked for a batch link: apart from `picked`, which is what the details show. |
| 409 | const [ticked, setTicked] = useState(NO_SELECTION); |
| 410 | // The machine a search landed on inside a stack, for the stack's list to scroll to. |
| 411 | const [found, setFound] = useState<string | null>(null); |
| 412 | const [linkRequest, setLinkRequest] = useState<LinkRequest | null>(null); |
| 413 | const [batchRequest, setBatchRequest] = useState<BatchRequest | null>(null); |
| 414 | const [dropped, setDropped] = useState<CodeOnlyDrop | null>(null); |
| 415 | const pairs = fleetTwoWayLinks(graph); |
| 416 | const present = |
| 417 | picked === null |
| 418 | ? null |
| 419 | : (picked.kind === "stack" |
| 420 | ? stacks |
| 421 | : picked.kind === "node" |
| 422 | ? graph.nodes |
| 423 | : graph.edges |
| 424 | ).some((item) => item.id === picked.id) |
| 425 | ? picked |
| 426 | : null; |
| 427 | // Either link of a two-way link selects the one line drawn for both. |
| 428 | const selection = |
| 429 | present?.kind === "edge" ? { ...present, id: fleetDrawnLinkId(pairs, present.id) } : present; |
| 430 | // A machine that left the map leaves the selection with it. |
| 431 | const selected = |
| 432 | ticked.size === 0 |
| 433 | ? NO_SELECTION |
| 434 | : new Set(graph.nodes.filter((node) => ticked.has(node.id)).map((node) => node.id)); |
| 435 | const toggleStack = (stackId: string) => |
| 436 | setExpanded((current) => { |
| 437 | const next = new Set(current); |
| 438 | if (!next.delete(stackId)) next.add(stackId); |
| 439 | return next; |
| 440 | }); |
| 441 | const tick = (ids: ReadonlyArray<string>, mode: "toggle" | "add") => |
| 442 | setTicked((current) => { |
| 443 | const next = new Set(current); |
| 444 | for (const id of ids) { |
| 445 | if (mode === "toggle" && next.delete(id)) continue; |
| 446 | next.add(id); |
| 447 | } |
| 448 | return next; |
| 449 | }); |
| 450 | const openLinkDialog = ( |
| 451 | environmentId: EnvironmentId, |
| 452 | offer: Extract<FleetLinkOffer, { kind: "link" }> | null, |
| 453 | ) => { |
| 454 | setDropped(null); |
| 455 | setLinkRequest((current) => ({ |
| 456 | serial: (current?.serial ?? 0) + 1, |
| 457 | environmentId, |
| 458 | open: true, |
| 459 | prefill: |
| 460 | offer === null |
| 461 | ? { choice: null } |
| 462 | : offer.target.kind === "machine" |
| 463 | ? { choice: offer.target.environmentId } |
| 464 | : { choice: ANOTHER_ADDRESS, address: offer.target.address ?? "" }, |
| 465 | })); |
| 466 | }; |
| 467 | /** One link from `sourceId` to `targetId`, whatever is selected. */ |
| 468 | const requestOneLink = (sourceId: string, targetId: string) => { |
| 469 | const offer = fleetLinkOffer(graph, sourceId, targetId); |
| 470 | if (offer.kind === "link") openLinkDialog(offer.sourceEnvironmentId, offer); |
| 471 | }; |
| 472 | // One way in for every gesture: the handle, a drop, the details and the toolbar. |
| 473 | const requestLink = (sourceId: string, targetId: string | null) => { |
| 474 | const action = fleetLinkAction(graph, stacks, selected, sourceId, targetId); |
| 475 | if (action === null) return; |
| 476 | if (action.kind === "code-only") { |
| 477 | setDropped(action); |
| 478 | return; |
| 479 | } |
| 480 | if (action.kind === "batch") { |
| 481 | setDropped(null); |
| 482 | setBatchRequest((current) => ({ |
| 483 | serial: (current?.serial ?? 0) + 1, |
| 484 | environmentId: action.sourceEnvironmentId, |
| 485 | preset: action.environmentIds, |
| 486 | presetOnly: true, |
| 487 | open: true, |
| 488 | })); |
| 489 | return; |
| 490 | } |
| 491 | openLinkDialog(action.sourceEnvironmentId, action.offer); |
| 492 | }; |
| 493 | const requestBatch = (sourceId: string) => { |
| 494 | const source = graph.nodes.find((node) => node.id === sourceId); |
| 495 | if (source?.kind !== "environment" || source.linking !== "ready") return; |
| 496 | const action = fleetLinkAction(graph, stacks, selected, sourceId, null); |
| 497 | setDropped(null); |
| 498 | setBatchRequest((current) => ({ |
| 499 | serial: (current?.serial ?? 0) + 1, |
| 500 | environmentId: source.environmentId, |
| 501 | preset: action?.kind === "batch" ? action.environmentIds : [], |
| 502 | presetOnly: false, |
| 503 | open: true, |
| 504 | })); |
| 505 | }; |
| 506 | const select = (focus: FleetFocus | null) => { |
| 507 | setPicked(focus); |
| 508 | setFound(null); |
| 509 | }; |
| 510 | return ( |
| 511 | <> |
| 512 | <FleetCanvas |
| 513 | graph={graph} |
| 514 | stacks={stacks} |
| 515 | shapeKey={key} |
| 516 | environments={environments} |
| 517 | selection={selection} |
| 518 | selected={selected} |
| 519 | onSelect={select} |
| 520 | onTick={tick} |
| 521 | onClearTicked={() => setTicked(NO_SELECTION)} |
| 522 | onLink={requestLink} |
| 523 | onLinkSeveral={requestBatch} |
| 524 | dropped={dropped} |
| 525 | onLinkOne={requestOneLink} |
| 526 | onDismissDropped={() => setDropped(null)} |
| 527 | onToggleStack={toggleStack} |
| 528 | onFind={(stackId, memberId) => { |
| 529 | setPicked({ kind: "stack", id: stackId }); |
| 530 | setFound(memberId); |
| 531 | }} |
| 532 | /> |
| 533 | <SettingsSearchTarget id={props.footerId}> |
| 534 | <FleetDetails |
| 535 | {...props} |
| 536 | graph={graph} |
| 537 | stacks={stacks} |
| 538 | environments={environments} |
| 539 | connectProblem={connectProblem} |
| 540 | selection={selection} |
| 541 | found={found} |
| 542 | onSelect={select} |
| 543 | onLinkFrom={(sourceId) => requestLink(sourceId, null)} |
| 544 | onLinkBack={(edge) => requestOneLink(edge.to, edge.from)} |
| 545 | onToggleStack={toggleStack} |
| 546 | /> |
| 547 | </SettingsSearchTarget> |
| 548 | {linkRequest ? ( |
| 549 | <LinkEnvironmentDialog |
| 550 | key={linkRequest.serial} |
| 551 | environmentId={linkRequest.environmentId} |
| 552 | open={linkRequest.open} |
| 553 | prefill={linkRequest.prefill} |
| 554 | onOpenChange={(open) => |
| 555 | setLinkRequest((current) => (current === null ? null : { ...current, open })) |
| 556 | } |
| 557 | /> |
| 558 | ) : null} |
| 559 | {batchRequest ? ( |
| 560 | <LinkSeveralEnvironmentsDialog |
| 561 | key={batchRequest.serial} |
| 562 | environmentId={batchRequest.environmentId} |
| 563 | open={batchRequest.open} |
| 564 | preset={batchRequest.preset} |
| 565 | presetOnly={batchRequest.presetOnly} |
| 566 | onOpenChange={(open) => |
| 567 | setBatchRequest((current) => (current === null ? null : { ...current, open })) |
| 568 | } |
| 569 | /> |
| 570 | ) : null} |
| 571 | </> |
| 572 | ); |
| 573 | } |
| 574 | |
| 575 | interface FleetSceneProps { |
| 576 | readonly graph: FleetGraph; |
| 577 | readonly stacks: ReadonlyArray<FleetStack>; |
| 578 | readonly layout: FleetLayout; |
| 579 | readonly environments: ReadonlyArray<EnvironmentPresentation>; |
| 580 | readonly selection: FleetFocus | null; |
| 581 | /** Machines ticked for a batch link. */ |
| 582 | readonly selected: ReadonlySet<string>; |
| 583 | readonly onSelect: (focus: FleetFocus | null) => void; |
| 584 | readonly onTick: (ids: ReadonlyArray<string>, mode: "toggle" | "add") => void; |
| 585 | readonly onLink: (sourceId: string, targetId: string | null) => void; |
| 586 | readonly onToggleStack: (stackId: string) => void; |
| 587 | } |
| 588 | |
| 589 | interface FleetCanvasProps extends Omit<FleetSceneProps, "layout"> { |
| 590 | /** The graph's shape. The canvas lays it out at its own width. */ |
| 591 | readonly shapeKey: string; |
| 592 | readonly onClearTicked: () => void; |
| 593 | readonly onLinkSeveral: (sourceId: string) => void; |
| 594 | readonly dropped: CodeOnlyDrop | null; |
| 595 | readonly onLinkOne: (sourceId: string, targetId: string) => void; |
| 596 | readonly onDismissDropped: () => void; |
| 597 | /** A search landed on a machine drawn only inside a stack. */ |
| 598 | readonly onFind: (stackId: string, memberId: string) => void; |
| 599 | } |
| 600 | |
| 601 | function FleetCanvas({ |
| 602 | shapeKey: graphKey, |
| 603 | onClearTicked, |
| 604 | onLinkSeveral, |
| 605 | dropped, |
| 606 | onLinkOne, |
| 607 | onDismissDropped, |
| 608 | onFind, |
| 609 | ...scene |
| 610 | }: FleetCanvasProps) { |
| 611 | const gt = useGT(); |
| 612 | const { graph, stacks, selection, selected, onSelect, onTick } = scene; |
| 613 | const [canvas, setCanvas] = useState<HTMLDivElement | null>(null); |
| 614 | const [width, setWidth] = useState<number | null>(null); |
| 615 | const { key: layoutKey, layout } = useFleetLayout(graph, stacks, graphKey, width); |
| 616 | const [query, setQuery] = useState(""); |
| 617 | // A held view lasts while the map keeps its shape, whatever the width; otherwise it fits itself. |
| 618 | const [manual, setManual] = useState<FleetHeldView | null>(null); |
| 619 | // What was last drawn, to tell a stack opening or closing from any other change of shape. |
| 620 | const [drawn, setDrawn] = useState({ graphKey, layoutKey, layout, stacks }); |
| 621 | const [dragging, setDragging] = useState(false); |
| 622 | // The selection box, in canvas pixels, while Shift is held through a drag on empty canvas. |
| 623 | const [box, setBox] = useState<FleetRect | null>(null); |
| 624 | const drag = useRef<{ |
| 625 | readonly pointerId: number; |
| 626 | readonly key: string; |
| 627 | readonly mode: "pan" | "box"; |
| 628 | readonly x: number; |
| 629 | readonly y: number; |
| 630 | readonly left: number; |
| 631 | readonly top: number; |
| 632 | readonly origin: FleetViewTransform; |
| 633 | moved: boolean; |
| 634 | } | null>(null); |
| 635 | if (drawn.layoutKey !== layoutKey) { |
| 636 | setDrawn({ graphKey, layoutKey, layout, stacks }); |
| 637 | if (drawn.graphKey !== graphKey) { |
| 638 | const toggled = stacks.find((stack) => |
| 639 | drawn.stacks.some((was) => was.id === stack.id && was.expanded !== stack.expanded), |
| 640 | ); |
| 641 | const before = toggled === undefined ? undefined : drawn.layout.stacks.get(toggled.id); |
| 642 | const after = toggled === undefined ? undefined : layout.stacks.get(toggled.id); |
| 643 | if (width !== null && before !== undefined && after !== undefined) { |
| 644 | // The stack stays where it is and the rest makes room, in the one render that opens it. |
| 645 | const was = manual?.key === drawn.graphKey ? manual : null; |
| 646 | const from = { |
| 647 | width, |
| 648 | height: was?.height ?? fleetCanvasHeight(drawn.layout, width, CANVAS_HEIGHT), |
| 649 | }; |
| 650 | setManual( |
| 651 | anchorFleetView({ |
| 652 | key: graphKey, |
| 653 | from: { |
| 654 | key: drawn.graphKey, |
| 655 | held: was, |
| 656 | view: was?.view ?? fitFleetLayout(drawn.layout, from), |
| 657 | size: from, |
| 658 | face: before.face, |
| 659 | }, |
| 660 | stack: after, |
| 661 | layout, |
| 662 | bounds: CANVAS_HEIGHT, |
| 663 | }), |
| 664 | ); |
| 665 | } else if (manual !== null && manual.key !== "") { |
| 666 | // Any other new shape drops the held view for good: returning to an old shape must |
| 667 | // fit, not restore a pan made before the map changed. |
| 668 | setManual({ ...manual, key: "" }); |
| 669 | } |
| 670 | } |
| 671 | } |
| 672 | const held = manual?.key === graphKey ? manual : null; |
| 673 | // Not measured: the height follows from the layout and the view, so it never feeds back. |
| 674 | const size = |
| 675 | width === null |
| 676 | ? null |
| 677 | : { width, height: held?.height ?? fleetCanvasHeight(layout, width, CANVAS_HEIGHT) }; |
| 678 | const view = held?.view ?? (size === null ? null : fitFleetLayout(layout, size)); |
| 679 | const glide = manual !== null && (held === null || held.glide); |
| 680 | const setView = (next: FleetViewTransform, eased: boolean) => { |
| 681 | if (size === null) return; |
| 682 | setManual({ key: graphKey, view: next, height: size.height, glide: eased, undo: null }); |
| 683 | }; |
| 684 | const zoom = ( |
| 685 | factor: number, |
| 686 | anchor?: { readonly x: number; readonly y: number }, |
| 687 | eased = true, |
| 688 | ) => { |
| 689 | if (view === null || size === null) return; |
| 690 | setView( |
| 691 | zoomFleetView( |
| 692 | view, |
| 693 | factor, |
| 694 | anchor ?? { x: size.width / 2, y: size.height / 2 }, |
| 695 | fitFleetLayout(layout, size).scale, |
| 696 | ), |
| 697 | eased, |
| 698 | ); |
| 699 | }; |
| 700 | // Keeps the entry so the scene eases back to the fit; its stale key marks it as not held. |
| 701 | const fit = () => setManual((current) => (current === null ? null : { ...current, key: "" })); |
| 702 | const onWheel = useEffectEvent((event: WheelEvent) => { |
| 703 | // Plain scrolling stays the page's; a pinch or Ctrl/Cmd + wheel zooms the map. |
| 704 | if (!event.ctrlKey && !event.metaKey) return; |
| 705 | event.preventDefault(); |
| 706 | const bounds = (event.currentTarget as HTMLElement).getBoundingClientRect(); |
| 707 | zoom( |
| 708 | Math.exp(-event.deltaY * 0.01), |
| 709 | { x: event.clientX - bounds.left, y: event.clientY - bounds.top }, |
| 710 | false, |
| 711 | ); |
| 712 | }); |
| 713 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- measures the canvas with ResizeObserver, and React's wheel listener is passive so it cannot stop the page zooming |
| 714 | useEffect(() => { |
| 715 | if (canvas === null) return; |
| 716 | const stopObserving = observeResize(canvas, ([entry]) => { |
| 717 | if (entry) setWidth(entry.contentRect.width); |
| 718 | }); |
| 719 | canvas.addEventListener("wheel", onWheel, { passive: false }); |
| 720 | return () => { |
| 721 | stopObserving(); |
| 722 | canvas.removeEventListener("wheel", onWheel); |
| 723 | }; |
| 724 | }, [canvas]); |
| 725 | |
| 726 | // Reads the view inside the updater so the scene's props stay the same while panning. |
| 727 | const reveal = useStableCallback((rect: FleetRect) => { |
| 728 | if (size === null) return; |
| 729 | setManual((current) => { |
| 730 | const shown = current?.key === graphKey ? current.view : fitFleetLayout(layout, size); |
| 731 | const left = rect.x * shown.scale + shown.x; |
| 732 | const top = rect.y * shown.scale + shown.y; |
| 733 | const inside = |
| 734 | left >= 0 && |
| 735 | top >= 0 && |
| 736 | left + rect.width * shown.scale <= size.width && |
| 737 | top + rect.height * shown.scale <= size.height; |
| 738 | if (inside) return current; |
| 739 | return { |
| 740 | key: graphKey, |
| 741 | height: size.height, |
| 742 | glide: true, |
| 743 | undo: null, |
| 744 | view: { |
| 745 | scale: shown.scale, |
| 746 | x: size.width / 2 - (rect.x + rect.width / 2) * shown.scale, |
| 747 | y: size.height / 2 - (rect.y + rect.height / 2) * shown.scale, |
| 748 | }, |
| 749 | }; |
| 750 | }); |
| 751 | }); |
| 752 | const centre = (rect: FleetRect) => { |
| 753 | if (size === null || view === null) return; |
| 754 | const scale = Math.max(view.scale, FOUND_MIN_SCALE); |
| 755 | setView( |
| 756 | { |
| 757 | scale, |
| 758 | x: size.width / 2 - (rect.x + rect.width / 2) * scale, |
| 759 | y: size.height / 2 - (rect.y + rect.height / 2) * scale, |
| 760 | }, |
| 761 | true, |
| 762 | ); |
| 763 | }; |
| 764 | |
| 765 | const matchIds = fleetSearch(graph, query); |
| 766 | const matches = query.trim() === "" ? null : new Set(matchIds); |
| 767 | const goToFirstMatch = () => { |
| 768 | const first = matchIds[0]; |
| 769 | if (first === undefined) return; |
| 770 | const rect = layout.nodes.get(first); |
| 771 | if (rect !== undefined) { |
| 772 | onSelect({ kind: "node", id: first }); |
| 773 | centre(rect); |
| 774 | canvas |
| 775 | ?.querySelector<HTMLElement>(`[data-fleet-node="${CSS.escape(first)}"]`) |
| 776 | ?.focus({ preventScroll: true }); |
| 777 | return; |
| 778 | } |
| 779 | // Folded away: its stack's list in the details scrolls to it. |
| 780 | const stack = stacks.find((entry) => entry.memberIds.includes(first)); |
| 781 | const face = stack === undefined ? undefined : layout.stacks.get(stack.id)?.face; |
| 782 | if (stack === undefined || face === undefined) return; |
| 783 | onFind(stack.id, first); |
| 784 | centre(face); |
| 785 | }; |
| 786 | |
| 787 | const onPointerDown = (event: PointerEvent<HTMLDivElement>) => { |
| 788 | // One pointer owns a drag: a second finger neither restarts it nor ends it. |
| 789 | if (event.button !== 0 || view === null || drag.current !== null) return; |
| 790 | if ((event.target as Element).closest("[data-fleet-item]")) return; |
| 791 | const bounds = event.currentTarget.getBoundingClientRect(); |
| 792 | drag.current = { |
| 793 | pointerId: event.pointerId, |
| 794 | key: layoutKey, |
| 795 | mode: event.shiftKey ? "box" : "pan", |
| 796 | x: event.clientX, |
| 797 | y: event.clientY, |
| 798 | left: bounds.left, |
| 799 | top: bounds.top, |
| 800 | origin: view, |
| 801 | moved: false, |
| 802 | }; |
| 803 | event.currentTarget.setPointerCapture(event.pointerId); |
| 804 | }; |
| 805 | const boxAt = (current: NonNullable<typeof drag.current>, event: PointerEvent): FleetRect => ({ |
| 806 | x: Math.min(current.x, event.clientX) - current.left, |
| 807 | y: Math.min(current.y, event.clientY) - current.top, |
| 808 | width: Math.abs(event.clientX - current.x), |
| 809 | height: Math.abs(event.clientY - current.y), |
| 810 | }); |
| 811 | const onPointerMove = (event: PointerEvent<HTMLDivElement>) => { |
| 812 | const current = drag.current; |
| 813 | if (current === null || current.pointerId !== event.pointerId) return; |
| 814 | // The map was laid out again mid-drag, so the origin belongs to a view that is gone. |
| 815 | if (current.key !== layoutKey) { |
| 816 | drag.current = null; |
| 817 | setDragging(false); |
| 818 | setBox(null); |
| 819 | return; |
| 820 | } |
| 821 | const dx = event.clientX - current.x; |
| 822 | const dy = event.clientY - current.y; |
| 823 | if (!current.moved && Math.hypot(dx, dy) < 4) return; |
| 824 | current.moved = true; |
| 825 | if (current.mode === "box") { |
| 826 | setBox(boxAt(current, event)); |
| 827 | return; |
| 828 | } |
| 829 | setDragging(true); |
| 830 | setView({ ...current.origin, x: current.origin.x + dx, y: current.origin.y + dy }, false); |
| 831 | }; |
| 832 | const endDrag = (event: PointerEvent<HTMLDivElement>, cancelled: boolean) => { |
| 833 | const current = drag.current; |
| 834 | if (current === null || current.pointerId !== event.pointerId) return; |
| 835 | drag.current = null; |
| 836 | setDragging(false); |
| 837 | setBox(null); |
| 838 | if (cancelled) return; |
| 839 | if (!current.moved) { |
| 840 | if (current.mode === "pan") onSelect(null); |
| 841 | return; |
| 842 | } |
| 843 | if (current.mode !== "box" || current.key !== layoutKey) return; |
| 844 | const drawn = boxAt(current, event); |
| 845 | // The box is in screen space: a zoom made mid-drag moved the map under it. |
| 846 | const origin = view ?? current.origin; |
| 847 | onTick( |
| 848 | fleetNodesInBox(layout, { |
| 849 | x: (drawn.x - origin.x) / origin.scale, |
| 850 | y: (drawn.y - origin.y) / origin.scale, |
| 851 | width: drawn.width / origin.scale, |
| 852 | height: drawn.height / origin.scale, |
| 853 | }), |
| 854 | "add", |
| 855 | ); |
| 856 | }; |
| 857 | const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => { |
| 858 | if (event.ctrlKey || event.metaKey || event.altKey) return; |
| 859 | if (event.key === "+" || event.key === "=") zoom(1.25); |
| 860 | else if (event.key === "-") zoom(0.8); |
| 861 | else if (event.key === "0") fit(); |
| 862 | else if (event.key === "Escape") onSelect(null); |
| 863 | else return; |
| 864 | event.preventDefault(); |
| 865 | }; |
| 866 | |
| 867 | const sources = graph.nodes.filter( |
| 868 | (node): node is FleetEnvironmentNode => node.kind === "environment" && node.linking === "ready", |
| 869 | ); |
| 870 | // The environment in the details is the one the user means; a lone one needs no asking. |
| 871 | const source = |
| 872 | sources.find((node) => selection?.kind === "node" && node.id === selection.id) ?? |
| 873 | (sources.length === 1 ? sources[0] : undefined); |
| 874 | const selectSeveral = gt("Shift-click or Shift-drag to select several"); |
| 875 | |
| 876 | return ( |
| 877 | <> |
| 878 | <div className="flex flex-wrap items-center gap-x-3 gap-y-1.5 rounded-t-xl border-b border-border/60 bg-background/50 px-3 py-1.5"> |
| 879 | <div className="w-48"> |
| 880 | <InputGroup> |
| 881 | <InputGroupAddon> |
| 882 | <SearchIcon aria-hidden /> |
| 883 | </InputGroupAddon> |
| 884 | <InputGroupInput |
| 885 | size="sm" |
| 886 | type="search" |
| 887 | value={query} |
| 888 | aria-label={gt("Find a machine on the map")} |
| 889 | placeholder={gt("Find a machine")} |
| 890 | spellCheck={false} |
| 891 | autoComplete="off" |
| 892 | onChange={(event) => setQuery(event.target.value)} |
| 893 | onKeyDown={(event) => { |
| 894 | if (event.key === "Enter") { |
| 895 | event.preventDefault(); |
| 896 | goToFirstMatch(); |
| 897 | } else if (event.key === "Escape" && query !== "") { |
| 898 | event.stopPropagation(); |
| 899 | setQuery(""); |
| 900 | } |
| 901 | }} |
| 902 | /> |
| 903 | </InputGroup> |
| 904 | </div> |
| 905 | <p role="status" className="min-w-0 text-2xs text-muted-foreground"> |
| 906 | {matches === null |
| 907 | ? null |
| 908 | : matchIds.length === 0 |
| 909 | ? gt("No machine by that name") |
| 910 | : gt("{count, plural, one {# match} other {# matches}}", { |
| 911 | count: matchIds.length, |
| 912 | $context: "how many machines a search by name found", |
| 913 | })} |
| 914 | </p> |
| 915 | <div className="ml-auto flex items-center gap-2"> |
| 916 | {selected.size > 0 ? ( |
| 917 | <span className="flex items-center gap-1 text-2xs text-foreground"> |
| 918 | <span role="status" className="tabular-nums"> |
| 919 | {gt("{count, plural, one {# selected} other {# selected}}", { |
| 920 | count: selected.size, |
| 921 | $context: "how many machines are selected on a map", |
| 922 | })} |
| 923 | </span> |
| 924 | <Button size="xs" variant="ghost-muted" onClick={onClearTicked}> |
| 925 | {gt("Clear", { $context: "clears the selection of machines" })} |
| 926 | </Button> |
| 927 | </span> |
| 928 | ) : null} |
| 929 | {sources.length === 0 ? null : source !== undefined ? ( |
| 930 | <Tooltip> |
| 931 | <TooltipTrigger |
| 932 | render={ |
| 933 | <Button size="xs" variant="outline" onClick={() => onLinkSeveral(source.id)}> |
| 934 | {gt("Link several…")} |
| 935 | </Button> |
| 936 | } |
| 937 | /> |
| 938 | <TooltipPopup>{selectSeveral}</TooltipPopup> |
| 939 | </Tooltip> |
| 940 | ) : ( |
| 941 | <Menu> |
| 942 | <Tooltip> |
| 943 | <TooltipTrigger |
| 944 | render={ |
| 945 | <MenuTrigger |
| 946 | render={ |
| 947 | <Button size="xs" variant="outline"> |
| 948 | {gt("Link several…")} |
| 949 | </Button> |
| 950 | } |
| 951 | /> |
| 952 | } |
| 953 | /> |
| 954 | <TooltipPopup>{selectSeveral}</TooltipPopup> |
| 955 | </Tooltip> |
| 956 | <MenuPopup align="end"> |
| 957 | {sources.map((node) => ( |
| 958 | <MenuItem key={node.id} onClick={() => onLinkSeveral(node.id)}> |
| 959 | {gt("From {source}", { |
| 960 | source: node.label, |
| 961 | $context: "menu item: link several machines from this environment", |
| 962 | })} |
| 963 | </MenuItem> |
| 964 | ))} |
| 965 | </MenuPopup> |
| 966 | </Menu> |
| 967 | )} |
| 968 | <Popover> |
| 969 | <PopoverTrigger |
| 970 | render={ |
| 971 | <Button size="icon-xs" variant="ghost" aria-label={gt("How to use the map")}> |
| 972 | <CircleHelpIcon /> |
| 973 | </Button> |
| 974 | } |
| 975 | /> |
| 976 | <PopoverPopup align="end" width="sm" padding="compact"> |
| 977 | <ul className="list-disc space-y-1 pl-4 text-xs text-muted-foreground"> |
| 978 | <li>{gt("Select a machine to manage it.")}</li> |
| 979 | {sources.length === 0 ? null : ( |
| 980 | <> |
| 981 | <li>{gt("Drag a plus onto a machine to link them.")}</li> |
| 982 | <li>{selectSeveral}</li> |
| 983 | </> |
| 984 | )} |
| 985 | <li>{gt("A link reaches one machine and stops there.")}</li> |
| 986 | </ul> |
| 987 | </PopoverPopup> |
| 988 | </Popover> |
| 989 | </div> |
| 990 | </div> |
| 991 | {dropped === null ? null : ( |
| 992 | <CodeOnlyNotice |
| 993 | graph={graph} |
| 994 | dropped={dropped} |
| 995 | onLinkOne={onLinkOne} |
| 996 | onDismiss={onDismissDropped} |
| 997 | /> |
| 998 | )} |
| 999 | <div |
| 1000 | ref={setCanvas} |
| 1001 | data-dragging={dragging || undefined} |
| 1002 | data-glide={glide || undefined} |
| 1003 | className="relative min-h-45 cursor-grab touch-none overflow-clip bg-background/50 select-none data-dragging:cursor-grabbing data-glide:transition-[height,background-size,background-position] data-glide:duration-200 data-glide:ease-out motion-reduce:transition-none" |
| 1004 | style={ |
| 1005 | view === null || size === null |
| 1006 | ? undefined |
| 1007 | : { |
| 1008 | height: size.height, |
| 1009 | backgroundImage: "radial-gradient(circle, var(--border) 1px, transparent 1.5px)", |
| 1010 | backgroundSize: `${24 * view.scale}px ${24 * view.scale}px`, |
| 1011 | backgroundPosition: `${view.x}px ${view.y}px`, |
| 1012 | } |
| 1013 | } |
| 1014 | onPointerDown={onPointerDown} |
| 1015 | onPointerMove={onPointerMove} |
| 1016 | onPointerUp={(event) => endDrag(event, false)} |
| 1017 | onPointerCancel={(event) => endDrag(event, true)} |
| 1018 | onLostPointerCapture={(event) => endDrag(event, true)} |
| 1019 | onKeyDown={onKeyDown} |
| 1020 | > |
| 1021 | {view === null ? null : ( |
| 1022 | <div |
| 1023 | data-fleet-scene |
| 1024 | className="absolute top-0 left-0 origin-top-left in-data-dragging:will-change-transform in-data-glide:transition-transform in-data-glide:duration-200 in-data-glide:ease-out motion-reduce:transition-none" |
| 1025 | style={{ |
| 1026 | width: layout.width, |
| 1027 | height: layout.height, |
| 1028 | transform: `translate(${view.x}px, ${view.y}px) scale(${view.scale})`, |
| 1029 | }} |
| 1030 | > |
| 1031 | <FleetScene {...scene} layout={layout} matches={matches} onReveal={reveal} /> |
| 1032 | </div> |
| 1033 | )} |
| 1034 | {box === null ? null : ( |
| 1035 | <div |
| 1036 | aria-hidden |
| 1037 | style={{ left: box.x, top: box.y, width: box.width, height: box.height }} |
| 1038 | className="pointer-events-none absolute rounded-sm border border-primary bg-primary/10 forced-colors:border-2" |
| 1039 | /> |
| 1040 | )} |
| 1041 | </div> |
| 1042 | {/* Below the canvas, not over it: nothing on the map can end up under the controls. */} |
| 1043 | <div className="flex items-end justify-between gap-3 bg-background/50 px-3 pb-2"> |
| 1044 | <FleetLegend twoWay={fleetTwoWayLinks(graph).size > 0} /> |
| 1045 | <div className="flex shrink-0 items-center gap-1 rounded-lg border border-border/60 bg-popover/90 p-0.5 shadow-xs/5"> |
| 1046 | <Button |
| 1047 | size="icon-xs" |
| 1048 | variant="ghost" |
| 1049 | aria-label={gt("Zoom out")} |
| 1050 | onClick={() => zoom(0.8)} |
| 1051 | > |
| 1052 | <MinusIcon /> |
| 1053 | </Button> |
| 1054 | <Button |
| 1055 | size="icon-xs" |
| 1056 | variant="ghost" |
| 1057 | aria-label={gt("Zoom in")} |
| 1058 | onClick={() => zoom(1.25)} |
| 1059 | > |
| 1060 | <PlusIcon /> |
| 1061 | </Button> |
| 1062 | <Button |
| 1063 | size="icon-xs" |
| 1064 | variant="ghost" |
| 1065 | aria-label={gt("Fit the map to view")} |
| 1066 | disabled={held === null} |
| 1067 | onClick={fit} |
| 1068 | > |
| 1069 | <MaximizeIcon /> |
| 1070 | </Button> |
| 1071 | </div> |
| 1072 | </div> |
| 1073 | </> |
| 1074 | ); |
| 1075 | } |
| 1076 | |
| 1077 | /** How the two families of line are read: routes by state, links by weight. */ |
| 1078 | function FleetLegend({ twoWay }: { readonly twoWay: boolean }) { |
| 1079 | const gt = useGT(); |
| 1080 | const sample = (state: FleetRouteState) => ( |
| 1081 | <svg aria-hidden viewBox="0 0 18 4" className={cn("h-1 w-4.5", ROUTE_STYLES[state].wire)}> |
| 1082 | <path |
| 1083 | d="M0 2H18" |
| 1084 | stroke="currentColor" |
| 1085 | strokeWidth={ROUTE_STYLES[state].width + 0.25} |
| 1086 | strokeDasharray={ROUTE_STYLES[state].dash} |
| 1087 | /> |
| 1088 | </svg> |
| 1089 | ); |
| 1090 | return ( |
| 1091 | <ul |
| 1092 | aria-label={gt("How to read the lines")} |
| 1093 | className="flex min-w-0 items-center gap-x-3 overflow-clip pb-1 text-2xs whitespace-nowrap text-muted-foreground" |
| 1094 | > |
| 1095 | <li className="flex items-center gap-1.5"> |
| 1096 | {sample("in-use")} |
| 1097 | {routeStateLabel("in-use", gt)} |
| 1098 | </li> |
| 1099 | <li className="flex items-center gap-1.5"> |
| 1100 | {sample("standby")} |
| 1101 | {routeStateLabel("standby", gt)} |
| 1102 | </li> |
| 1103 | <li className="flex items-center gap-1.5"> |
| 1104 | {sample("down")} |
| 1105 | {gt("Offline")} |
| 1106 | </li> |
| 1107 | <li className="flex items-center gap-1.5"> |
| 1108 | <svg aria-hidden viewBox="0 0 22 6" className="h-1.5 w-5.5 text-foreground/70"> |
| 1109 | <path d="M0 3L22 0.5V5.5Z" fill="currentColor" /> |
| 1110 | </svg> |
| 1111 | {gt("Link", { $context: "noun, in a map legend: a line joining two linked machines" })} |
| 1112 | </li> |
| 1113 | {twoWay ? ( |
| 1114 | <li className="flex items-center gap-1.5"> |
| 1115 | <svg aria-hidden viewBox="0 0 22 8" className="h-2 w-5.5 text-foreground/70"> |
| 1116 | <path d="M5 4H17" stroke="currentColor" strokeWidth="1.75" /> |
| 1117 | <path d="M0 4L6 0.5V7.5ZM22 4L16 0.5V7.5Z" fill="currentColor" /> |
| 1118 | </svg> |
| 1119 | {gt("Two-way", { $context: "in a map legend: a link that goes both ways" })} |
| 1120 | </li> |
| 1121 | ) : null} |
| 1122 | </ul> |
| 1123 | ); |
| 1124 | } |
| 1125 | |
| 1126 | /** A state short enough for a card. The reason behind it is in the details and the name. */ |
| 1127 | function connectionStateText( |
| 1128 | node: FleetEnvironmentNode, |
| 1129 | environment: EnvironmentPresentation | undefined, |
| 1130 | refused: boolean, |
| 1131 | gt: GT, |
| 1132 | ): string { |
| 1133 | if (!node.enabled && node.phase !== "unsupported") { |
| 1134 | return gt("Off", { $context: "environment switched off" }); |
| 1135 | } |
| 1136 | if (refused) return gt("Sign-in refused"); |
| 1137 | switch (node.phase) { |
| 1138 | case "connected": |
| 1139 | return gt("Connected"); |
| 1140 | case "connecting": |
| 1141 | return gt("Connecting…"); |
| 1142 | case "reconnecting": |
| 1143 | return environment?.connection.awaitingApproval |
| 1144 | ? gt("Waiting for approval") |
| 1145 | : gt("Reconnecting…"); |
| 1146 | case "unsupported": |
| 1147 | return gt("Client not supported"); |
| 1148 | case "error": |
| 1149 | return gt("Connection failed"); |
| 1150 | case "offline": |
| 1151 | return gt("Offline"); |
| 1152 | case "available": |
| 1153 | return gt("Not connected"); |
| 1154 | } |
| 1155 | } |
| 1156 | |
| 1157 | function environmentStatusText( |
| 1158 | node: FleetEnvironmentNode, |
| 1159 | environment: EnvironmentPresentation | undefined, |
| 1160 | refused: boolean, |
| 1161 | linkCount: number, |
| 1162 | gt: GT, |
| 1163 | ): string { |
| 1164 | if (node.phase !== "connected") return connectionStateText(node, environment, refused, gt); |
| 1165 | switch (node.outgoing) { |
| 1166 | case "loading": |
| 1167 | return gt("Loading links…"); |
| 1168 | case "error": |
| 1169 | return gt("Links could not be loaded"); |
| 1170 | case "off": |
| 1171 | return gt("Linked environments is off"); |
| 1172 | case "unknown": |
| 1173 | return gt("Links not readable from here"); |
| 1174 | case "loaded": |
| 1175 | return gt("{count, plural, =0 {No links out} one {# link out} other {# links out}}", { |
| 1176 | count: linkCount, |
| 1177 | }); |
| 1178 | } |
| 1179 | } |
| 1180 | |
| 1181 | function connectAvailabilityText( |
| 1182 | availability: Extract<FleetNode, { kind: "connect" }>["availability"], |
| 1183 | gt: GT, |
| 1184 | ): string { |
| 1185 | switch (availability) { |
| 1186 | case "online": |
| 1187 | return gt("Relay online"); |
| 1188 | case "offline": |
| 1189 | return gt("Relay offline"); |
| 1190 | case "checking": |
| 1191 | return gt("Checking relay status…"); |
| 1192 | case "error": |
| 1193 | return gt("Relay status unavailable"); |
| 1194 | } |
| 1195 | } |
| 1196 | |
| 1197 | function linkSummary(edge: FleetLinkEdge, gt: GT, m: Messages): string { |
| 1198 | return `${m(accessConfig[edge.link.access].label)}, ${healthLabel(edge.health, gt)}`; |
| 1199 | } |
| 1200 | |
| 1201 | /** A link in words, for the pointer and for assistive tech. A two-way link names each direction. */ |
| 1202 | function linkName( |
| 1203 | edge: FleetLinkEdge, |
| 1204 | back: FleetLinkEdge | undefined, |
| 1205 | labelOf: (id: string) => string, |
| 1206 | gt: GT, |
| 1207 | m: Messages, |
| 1208 | ): string { |
| 1209 | const source = labelOf(edge.from); |
| 1210 | const target = labelOf(edge.to); |
| 1211 | return back === undefined |
| 1212 | ? gt("Link from {source} to {target}: {summary}", { |
| 1213 | source, |
| 1214 | target, |
| 1215 | summary: linkSummary(edge, gt, m), |
| 1216 | }) |
| 1217 | : gt( |
| 1218 | "Two-way link between {source} and {target}, {access}. {source} to {target}: {forward}. {target} to {source}: {back}", |
| 1219 | { |
| 1220 | source, |
| 1221 | target, |
| 1222 | access: m(accessConfig[edge.link.access].label), |
| 1223 | forward: healthLabel(edge.health, gt), |
| 1224 | back: healthLabel(back.health, gt), |
| 1225 | }, |
| 1226 | ); |
| 1227 | } |
| 1228 | |
| 1229 | /** |
| 1230 | * Says in place why a drop cannot be linked in one go, and offers what works: one machine at |
| 1231 | * a time, with a pairing code from it. |
| 1232 | */ |
| 1233 | function CodeOnlyNotice({ |
| 1234 | graph, |
| 1235 | dropped, |
| 1236 | onLinkOne, |
| 1237 | onDismiss, |
| 1238 | }: { |
| 1239 | readonly graph: FleetGraph; |
| 1240 | readonly dropped: CodeOnlyDrop; |
| 1241 | readonly onLinkOne: (sourceId: string, targetId: string) => void; |
| 1242 | readonly onDismiss: () => void; |
| 1243 | }) { |
| 1244 | const gt = useGT(); |
| 1245 | const byId = new Map(graph.nodes.map((node) => [node.id, node])); |
| 1246 | const source = byId.get(dropped.sourceId); |
| 1247 | const machines = dropped.machineIds.flatMap((id) => byId.get(id) ?? []); |
| 1248 | if (source === undefined || machines.length === 0) return null; |
| 1249 | return ( |
| 1250 | <div |
| 1251 | role="status" |
| 1252 | className="flex flex-wrap items-center gap-x-3 gap-y-1.5 border-b border-border/60 bg-background/50 px-3 py-2 text-xs" |
| 1253 | > |
| 1254 | <p className="min-w-0 flex-1 basis-64 text-muted-foreground"> |
| 1255 | {needsCodeText(machines.length, gt)} |
| 1256 | </p> |
| 1257 | {/* Linking through an environment that already reaches these machines would be offered here. */} |
| 1258 | <Menu> |
| 1259 | <MenuTrigger |
| 1260 | render={ |
| 1261 | <Button size="xs" variant="outline"> |
| 1262 | {gt("Link one with a code…")} |
| 1263 | </Button> |
| 1264 | } |
| 1265 | /> |
| 1266 | <MenuPopup align="end"> |
| 1267 | {machines.map((machine) => ( |
| 1268 | <MenuItem key={machine.id} onClick={() => onLinkOne(dropped.sourceId, machine.id)}> |
| 1269 | {machine.label} |
| 1270 | </MenuItem> |
| 1271 | ))} |
| 1272 | </MenuPopup> |
| 1273 | </Menu> |
| 1274 | <Button size="icon-xs" variant="ghost" aria-label={gt("Dismiss")} onClick={onDismiss}> |
| 1275 | <XIcon /> |
| 1276 | </Button> |
| 1277 | </div> |
| 1278 | ); |
| 1279 | } |
| 1280 | |
| 1281 | const needsCodeText = (count: number, gt: GT) => |
| 1282 | gt( |
| 1283 | "{count, plural, one {# machine needs a pairing code} other {# machines each need a pairing code}}", |
| 1284 | { count }, |
| 1285 | ); |
| 1286 | |
| 1287 | function actionText(action: FleetLinkAction | null, target: string, gt: GT): string { |
| 1288 | if (action === null) return gt("Cannot link to this"); |
| 1289 | if (action.kind === "code-only") return needsCodeText(action.machineIds.length, gt); |
| 1290 | if (action.kind === "batch") { |
| 1291 | return gt("{count, plural, one {Link to # machine} other {Link to # machines}}", { |
| 1292 | count: action.environmentIds.length, |
| 1293 | }); |
| 1294 | } |
| 1295 | const { offer } = action; |
| 1296 | if (offer === null) return gt("Cannot link to this"); |
| 1297 | if (offer.path === "code-less") { |
| 1298 | return offer.renews |
| 1299 | ? gt("Renew link to {target}", { target }) |
| 1300 | : gt("Link to {target}", { target }); |
| 1301 | } |
| 1302 | return offer.renews |
| 1303 | ? gt("Renew link to {target} with a pairing code", { target }) |
| 1304 | : gt("Link to {target} with a pairing code", { target }); |
| 1305 | } |
| 1306 | |
| 1307 | function foldGroupLabel(group: FleetFoldGroup, gt: GT): string { |
| 1308 | switch (group) { |
| 1309 | case "offline": |
| 1310 | return gt("Offline"); |
| 1311 | case "off": |
| 1312 | return gt("Switched off", { $context: "environments the user has switched off in this app" }); |
| 1313 | case "update": |
| 1314 | return gt("Need an update", { |
| 1315 | $context: "environments running a version this app cannot talk to", |
| 1316 | }); |
| 1317 | case "not-added": |
| 1318 | return gt("Not added"); |
| 1319 | } |
| 1320 | } |
| 1321 | |
| 1322 | const COLUMN_TITLES = (gt: GT): Record<FleetColumn, string> => ({ |
| 1323 | client: gt("This app"), |
| 1324 | environments: gt("Environments"), |
| 1325 | targets: gt("Linked machines"), |
| 1326 | }); |
| 1327 | |
| 1328 | interface LinkDrag { |
| 1329 | readonly sourceId: string; |
| 1330 | readonly x: number; |
| 1331 | readonly y: number; |
| 1332 | readonly overId: string | null; |
| 1333 | } |
| 1334 | |
| 1335 | const FleetScene = memo(function FleetScene({ |
| 1336 | graph, |
| 1337 | stacks, |
| 1338 | layout, |
| 1339 | environments, |
| 1340 | selection, |
| 1341 | selected, |
| 1342 | matches, |
| 1343 | onSelect, |
| 1344 | onTick, |
| 1345 | onLink, |
| 1346 | onToggleStack, |
| 1347 | onReveal, |
| 1348 | }: FleetSceneProps & { |
| 1349 | /** Machines a search names; the rest step back. Null when nothing is searched for. */ |
| 1350 | readonly matches: ReadonlySet<string> | null; |
| 1351 | readonly onReveal: (rect: FleetRect) => void; |
| 1352 | }) { |
| 1353 | const gt = useGT(); |
| 1354 | const m = useMessages(); |
| 1355 | const [hover, setHover] = useState<FleetFocus | null>(null); |
| 1356 | const [roving, setRoving] = useState(FLEET_CLIENT_NODE_ID); |
| 1357 | const [linkDrag, setLinkDrag] = useState<LinkDrag | null>(null); |
| 1358 | const handleDrag = useRef<{ |
| 1359 | readonly pointerId: number; |
| 1360 | readonly x: number; |
| 1361 | readonly y: number; |
| 1362 | moved: boolean; |
| 1363 | } | null>(null); |
| 1364 | // A drag ends with a click on the handle it started from; that click must not open the dialog. |
| 1365 | const swallowClick = useRef(false); |
| 1366 | const focus = linkDrag === null ? (hover ?? selection) : null; |
| 1367 | const lit = focus === null ? null : fleetNeighborhood(graph, stacks, focus); |
| 1368 | const nodeById = new Map(graph.nodes.map((node) => [node.id, node])); |
| 1369 | const environmentById = new Map( |
| 1370 | environments.map((environment) => [ |
| 1371 | fleetEnvironmentNodeId(environment.environmentId), |
| 1372 | environment, |
| 1373 | ]), |
| 1374 | ); |
| 1375 | const links = graph.edges.filter(isLinkEdge); |
| 1376 | const pairs = fleetTwoWayLinks(graph); |
| 1377 | const labelOf = (id: string) => nodeById.get(id)?.label ?? ""; |
| 1378 | /** The other link of the two-way link `edge` is drawn for. */ |
| 1379 | const backOf = (edge: FleetLinkEdge) => pairs.get(edge.id)?.back; |
| 1380 | const routeEdges = graph.edges.filter(isRouteEdge); |
| 1381 | const focusRects = fleetFocusRects(layout); |
| 1382 | const tabStop = focusRects.has(roving) ? roving : FLEET_CLIENT_NODE_ID; |
| 1383 | const titles = COLUMN_TITLES(gt); |
| 1384 | const isSelected = (kind: FleetFocus["kind"], id: string) => |
| 1385 | selection?.kind === kind && selection.id === id; |
| 1386 | const fade = (dimmed: boolean) => |
| 1387 | cn( |
| 1388 | "transition-opacity duration-150 motion-reduce:transition-none", |
| 1389 | dimmed && "opacity-40 forced-colors:opacity-60", |
| 1390 | ); |
| 1391 | // Lines run the length of the map and cross each other, so one out of focus fades further |
| 1392 | // than a machine does. |
| 1393 | const fadeLine = (dimmed: boolean) => |
| 1394 | cn( |
| 1395 | "transition-opacity duration-150 motion-reduce:transition-none", |
| 1396 | dimmed && "opacity-25 forced-colors:opacity-40", |
| 1397 | ); |
| 1398 | // A name on a line stays solid when out of focus, so the lines under it never show through: |
| 1399 | // its text and outline step back instead. |
| 1400 | const fadeName = (dimmed: boolean) => |
| 1401 | cn( |
| 1402 | "transition-colors duration-150 motion-reduce:transition-none", |
| 1403 | dimmed && "border-border/50 font-normal text-muted-foreground/45", |
| 1404 | ); |
| 1405 | const routeLit = (edge: FleetRouteEdge) => lit === null || lit.edges.has(edge.id); |
| 1406 | // Painted last, so the routes in focus lie over the ones that are not. |
| 1407 | const routePaintOrder = |
| 1408 | lit === null ? routeEdges : routeEdges.toSorted((a, b) => +routeLit(a) - +routeLit(b)); |
| 1409 | const linkLit = (edge: FleetLinkEdge) => |
| 1410 | isSelected("edge", edge.id) || (lit?.edges.has(edge.id) ?? false); |
| 1411 | // Painted last, so the links in focus lie over the ones that are not. |
| 1412 | const paintOrder = lit === null ? links : links.toSorted((a, b) => +linkLit(a) - +linkLit(b)); |
| 1413 | const dragAction = (targetId: string) => |
| 1414 | linkDrag === null |
| 1415 | ? null |
| 1416 | : fleetLinkAction(graph, stacks, selected, linkDrag.sourceId, targetId); |
| 1417 | // A stack fades as a whole, by the links and machines it stands for. |
| 1418 | const nodeDimmed = (id: string) => |
| 1419 | layout.stacks.has(id) |
| 1420 | ? false |
| 1421 | : linkDrag !== null |
| 1422 | ? id !== linkDrag.sourceId && dragAction(id) === null |
| 1423 | : (lit !== null && !lit.nodes.has(id)) || (matches !== null && !matches.has(id)); |
| 1424 | // By the links it stands for: a host and a member can both be lit through other links. |
| 1425 | const stackLit = (stack: FleetStack) => |
| 1426 | lit === null || stack.edgeIds.some((id) => lit.edges.has(id)); |
| 1427 | const stackDimmed = (stack: FleetStack) => |
| 1428 | linkDrag !== null |
| 1429 | ? false |
| 1430 | : !stackLit(stack) || (matches !== null && !stack.memberIds.some((id) => matches.has(id))); |
| 1431 | // A machine drawn on its own can be ticked for a batch link; the client and stacks cannot. |
| 1432 | const tickable = (id: string) => id !== FLEET_CLIENT_NODE_ID && layout.nodes.has(id); |
| 1433 | // A machine shown in the details but folded into a stack marks the stack it is in. |
| 1434 | const holdsSelection = (stack: FleetStack) => |
| 1435 | selection?.kind === "node" && |
| 1436 | !layout.nodes.has(selection.id) && |
| 1437 | stack.memberIds.includes(selection.id); |
| 1438 | const hoverProps = (target: FleetFocus) => ({ |
| 1439 | onPointerEnter: () => setHover(target), |
| 1440 | onPointerLeave: () => setHover(null), |
| 1441 | }); |
| 1442 | |
| 1443 | const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => { |
| 1444 | const direction = ARROW_ROVE[event.key]; |
| 1445 | const from = (event.target as HTMLElement).closest<HTMLElement>("[data-fleet-node]"); |
| 1446 | if (event.key === " " && from !== null && tickable(from.dataset.fleetNode ?? "")) { |
| 1447 | // Space ticks the machine for a batch link; Enter still opens its details. |
| 1448 | event.preventDefault(); |
| 1449 | if (!event.repeat) onTick([from.dataset.fleetNode ?? ""], "toggle"); |
| 1450 | return; |
| 1451 | } |
| 1452 | if (direction === undefined || from === null) return; |
| 1453 | event.preventDefault(); |
| 1454 | const next = nextFleetNode(focusRects, from.dataset.fleetNode ?? "", direction); |
| 1455 | const rect = next === null ? undefined : focusRects.get(next); |
| 1456 | if (next === null || rect === undefined) return; |
| 1457 | event.currentTarget |
| 1458 | .querySelector<HTMLElement>(`[data-fleet-node="${CSS.escape(next)}"]`) |
| 1459 | ?.focus({ preventScroll: true }); |
| 1460 | onReveal(rect); |
| 1461 | }; |
| 1462 | |
| 1463 | const focusProps = (target: FleetFocus, rect: FleetRect, label: string) => ({ |
| 1464 | type: "button" as const, |
| 1465 | "data-fleet-item": "", |
| 1466 | "data-fleet-node": target.id, |
| 1467 | "aria-label": selected.has(target.id) |
| 1468 | ? gt("{label}, selected", { label, $context: "a machine ticked on a map" }) |
| 1469 | : label, |
| 1470 | "aria-pressed": isSelected(target.kind, target.id), |
| 1471 | tabIndex: target.id === tabStop ? 0 : -1, |
| 1472 | style: { left: rect.x, top: rect.y, width: rect.width, height: rect.height }, |
| 1473 | onClick: (event: MouseEvent<HTMLElement>) => { |
| 1474 | if ((event.shiftKey || event.metaKey || event.ctrlKey) && tickable(target.id)) { |
| 1475 | onTick([target.id], "toggle"); |
| 1476 | return; |
| 1477 | } |
| 1478 | onSelect(isSelected(target.kind, target.id) ? null : target); |
| 1479 | }, |
| 1480 | // The keydown ticked the machine; without this the button would also click. |
| 1481 | onKeyUp: (event: KeyboardEvent<HTMLElement>) => { |
| 1482 | if (event.key === " " && tickable(target.id)) event.preventDefault(); |
| 1483 | }, |
| 1484 | onFocus: (event: FocusEvent<HTMLElement>) => { |
| 1485 | setRoving(target.id); |
| 1486 | setHover(target); |
| 1487 | // Tabbing back in can land on a machine panned out of view; a click cannot. |
| 1488 | if (event.currentTarget.matches(":focus-visible")) onReveal(rect); |
| 1489 | }, |
| 1490 | onBlur: () => setHover(null), |
| 1491 | ...hoverProps(target), |
| 1492 | }); |
| 1493 | const nodeClass = (id: string) => |
| 1494 | cn( |
| 1495 | "absolute flex cursor-pointer items-center text-left outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset aria-pressed:ring-2 aria-pressed:ring-primary aria-pressed:ring-inset forced-colors:focus-visible:outline-2 forced-colors:aria-pressed:outline-2", |
| 1496 | fade(nodeDimmed(id)), |
| 1497 | linkDrag?.overId === id && "ring-2 ring-primary ring-inset", |
| 1498 | ); |
| 1499 | |
| 1500 | const toScene = (event: PointerEvent<HTMLElement>) => { |
| 1501 | const bounds = event.currentTarget.closest("[data-fleet-scene]")?.getBoundingClientRect(); |
| 1502 | if (!bounds || bounds.width === 0) return null; |
| 1503 | const scale = bounds.width / layout.width; |
| 1504 | return { x: (event.clientX - bounds.left) / scale, y: (event.clientY - bounds.top) / scale }; |
| 1505 | }; |
| 1506 | const dropTargetAt = (sourceId: string, event: PointerEvent<HTMLElement>) => { |
| 1507 | const over = document |
| 1508 | .elementFromPoint(event.clientX, event.clientY) |
| 1509 | ?.closest<HTMLElement>("[data-fleet-node]")?.dataset.fleetNode; |
| 1510 | return over !== undefined && fleetLinkAction(graph, stacks, selected, sourceId, over) !== null |
| 1511 | ? over |
| 1512 | : null; |
| 1513 | }; |
| 1514 | const handleProps = (sourceId: string) => ({ |
| 1515 | onPointerDown: (event: PointerEvent<HTMLButtonElement>) => { |
| 1516 | if (event.button !== 0 || handleDrag.current !== null) return; |
| 1517 | swallowClick.current = false; |
| 1518 | handleDrag.current = { |
| 1519 | pointerId: event.pointerId, |
| 1520 | x: event.clientX, |
| 1521 | y: event.clientY, |
| 1522 | moved: false, |
| 1523 | }; |
| 1524 | event.currentTarget.setPointerCapture(event.pointerId); |
| 1525 | }, |
| 1526 | onPointerMove: (event: PointerEvent<HTMLButtonElement>) => { |
| 1527 | const current = handleDrag.current; |
| 1528 | if (current === null || current.pointerId !== event.pointerId) return; |
| 1529 | if (!current.moved && Math.hypot(event.clientX - current.x, event.clientY - current.y) < 4) { |
| 1530 | return; |
| 1531 | } |
| 1532 | current.moved = true; |
| 1533 | const point = toScene(event); |
| 1534 | if (point === null) return; |
| 1535 | setLinkDrag({ sourceId, ...point, overId: dropTargetAt(sourceId, event) }); |
| 1536 | }, |
| 1537 | onPointerUp: (event: PointerEvent<HTMLButtonElement>) => { |
| 1538 | const current = handleDrag.current; |
| 1539 | if (current === null || current.pointerId !== event.pointerId) return; |
| 1540 | handleDrag.current = null; |
| 1541 | if (!current.moved) return; |
| 1542 | swallowClick.current = true; |
| 1543 | // Asked again at release: the map can move under a pointer that has stopped. |
| 1544 | const overId = dropTargetAt(sourceId, event); |
| 1545 | setLinkDrag(null); |
| 1546 | if (overId !== null) onLink(sourceId, overId); |
| 1547 | }, |
| 1548 | onLostPointerCapture: () => { |
| 1549 | if (handleDrag.current === null) return; |
| 1550 | handleDrag.current = null; |
| 1551 | setLinkDrag(null); |
| 1552 | }, |
| 1553 | onClick: () => { |
| 1554 | if (swallowClick.current) { |
| 1555 | swallowClick.current = false; |
| 1556 | return; |
| 1557 | } |
| 1558 | onLink(sourceId, null); |
| 1559 | }, |
| 1560 | }); |
| 1561 | |
| 1562 | const dragSource = linkDrag === null ? undefined : layout.handles.get(linkDrag.sourceId); |
| 1563 | const dragOver = linkDrag?.overId ?? null; |
| 1564 | |
| 1565 | return ( |
| 1566 | <div |
| 1567 | role="group" |
| 1568 | aria-label={gt("Map of your machines")} |
| 1569 | aria-description={gt( |
| 1570 | "Arrow keys move between machines. Enter opens a machine's details, with its routes and links. Space selects a machine for linking several at once. Tab from an environment reaches its link button. Plus and minus zoom, zero fits the map.", |
| 1571 | )} |
| 1572 | onKeyDown={onKeyDown} |
| 1573 | > |
| 1574 | {layout.columns.map((column) => ( |
| 1575 | <p |
| 1576 | key={column.id} |
| 1577 | aria-hidden |
| 1578 | style={{ left: column.x }} |
| 1579 | className="absolute top-0 text-2xs font-medium whitespace-nowrap text-muted-foreground" |
| 1580 | > |
| 1581 | {titles[column.id]} |
| 1582 | </p> |
| 1583 | ))} |
| 1584 | <svg |
| 1585 | width={layout.width} |
| 1586 | height={layout.height} |
| 1587 | className="absolute top-0 left-0 overflow-visible" |
| 1588 | fill="none" |
| 1589 | strokeLinecap="round" |
| 1590 | > |
| 1591 | {routePaintOrder.map((edge) => { |
| 1592 | const geometry = layout.routes.get(edge.id); |
| 1593 | if (geometry === undefined) return null; |
| 1594 | const style = ROUTE_STYLES[edge.state]; |
| 1595 | return ( |
| 1596 | <path |
| 1597 | key={edge.id} |
| 1598 | d={geometry.d} |
| 1599 | stroke="currentColor" |
| 1600 | strokeWidth={style.width} |
| 1601 | strokeDasharray={style.dash} |
| 1602 | className={cn(style.wire, fadeLine(!routeLit(edge)))} |
| 1603 | /> |
| 1604 | ); |
| 1605 | })} |
| 1606 | {stacks.map((stack) => { |
| 1607 | const geometry = layout.stacks.get(stack.id); |
| 1608 | if (geometry === undefined) return null; |
| 1609 | const onPath = stackLit(stack); |
| 1610 | return geometry.lines.map((line) => { |
| 1611 | // A folded group of environments has one wire for all its routes, none in use. |
| 1612 | if (line.access === null) { |
| 1613 | return ( |
| 1614 | <path |
| 1615 | key={`${stack.id}:routes`} |
| 1616 | d={line.d} |
| 1617 | stroke="currentColor" |
| 1618 | strokeWidth={ROUTE_STYLES.idle.width} |
| 1619 | strokeDasharray={ROUTE_STYLES.idle.dash} |
| 1620 | className={cn(ROUTE_STYLES.idle.wire, fadeLine(lit !== null && !onPath))} |
| 1621 | /> |
| 1622 | ); |
| 1623 | } |
| 1624 | const level = accessLevel(line.access); |
| 1625 | const mine = lit === null || lit.nodes.has(line.sourceId ?? ""); |
| 1626 | return ( |
| 1627 | <g |
| 1628 | key={`${stack.id}:${line.sourceId}`} |
| 1629 | className={cn("text-foreground", fadeLine(lit !== null && !(onPath && mine)))} |
| 1630 | opacity={lit !== null && onPath && mine ? 1 : ACCESS_STROKE_OPACITIES[level]} |
| 1631 | > |
| 1632 | <path d={line.d} stroke="currentColor" strokeWidth={ACCESS_STROKE_WIDTHS[level]} /> |
| 1633 | {line.arrow === null ? null : ( |
| 1634 | <path |
| 1635 | d={`M${line.arrow.x - 8} ${line.arrow.y - 4.5}L${line.arrow.x} ${line.arrow.y}L${line.arrow.x - 8} ${line.arrow.y + 4.5}Z`} |
| 1636 | fill="currentColor" |
| 1637 | /> |
| 1638 | )} |
| 1639 | </g> |
| 1640 | ); |
| 1641 | }); |
| 1642 | })} |
| 1643 | {paintOrder.map((edge) => { |
| 1644 | const geometry = layout.links.get(edge.id); |
| 1645 | if (geometry === undefined) return null; |
| 1646 | const selected = isSelected("edge", edge.id); |
| 1647 | const level = accessLevel(edge.link.access); |
| 1648 | const back = backOf(edge); |
| 1649 | // A two-way link is drawn in halves, each leading into the machine its link reaches, |
| 1650 | // so a direction in trouble shows at its own end. |
| 1651 | const parts: ReadonlyArray<readonly [string, FleetArrow, PeerLinkHealth]> = |
| 1652 | geometry.twoWay !== null && back !== undefined |
| 1653 | ? [ |
| 1654 | [geometry.twoWay.forward, geometry.arrow, edge.health], |
| 1655 | [geometry.twoWay.back, geometry.twoWay.backArrow, back.health], |
| 1656 | ] |
| 1657 | : [[geometry.d, geometry.arrow, edge.health]]; |
| 1658 | return ( |
| 1659 | <g |
| 1660 | key={edge.id} |
| 1661 | className={cn("pointer-events-none", fadeLine(lit !== null && !linkLit(edge)))} |
| 1662 | opacity={linkLit(edge) ? 1 : ACCESS_STROKE_OPACITIES[level]} |
| 1663 | > |
| 1664 | {parts.map(([d, arrow, health]) => ( |
| 1665 | <g |
| 1666 | key={d} |
| 1667 | className={ |
| 1668 | selected |
| 1669 | ? "text-primary" |
| 1670 | : linkNeedsAttention(health) |
| 1671 | ? healthTone(health) |
| 1672 | : "text-foreground" |
| 1673 | } |
| 1674 | > |
| 1675 | <path |
| 1676 | d={d} |
| 1677 | stroke="currentColor" |
| 1678 | // Selection also thickens the line, for when colour is forced. |
| 1679 | strokeWidth={(ACCESS_STROKE_WIDTHS[level] ?? 2) + (selected ? 1 : 0)} |
| 1680 | strokeDasharray={healthDash(health)} |
| 1681 | /> |
| 1682 | <path |
| 1683 | d={`M${arrow.x - arrow.dir * 7} ${arrow.y - 4}L${arrow.x} ${arrow.y}L${arrow.x - arrow.dir * 7} ${arrow.y + 4}Z`} |
| 1684 | fill="currentColor" |
| 1685 | /> |
| 1686 | </g> |
| 1687 | ))} |
| 1688 | </g> |
| 1689 | ); |
| 1690 | })} |
| 1691 | {/* Pointer shortcut only: each link is also a row in its machines' details. Kept in a |
| 1692 | fixed order apart from the painted lines, so focus never moves one under the pointer. */} |
| 1693 | {links.map((edge) => { |
| 1694 | const geometry = layout.links.get(edge.id); |
| 1695 | if (geometry === undefined) return null; |
| 1696 | const selected = isSelected("edge", edge.id); |
| 1697 | return ( |
| 1698 | <path |
| 1699 | key={edge.id} |
| 1700 | aria-hidden |
| 1701 | data-fleet-item="" |
| 1702 | d={geometry.d} |
| 1703 | stroke="transparent" |
| 1704 | strokeWidth="14" |
| 1705 | className="cursor-pointer" |
| 1706 | onClick={() => onSelect(selected ? null : { kind: "edge", id: edge.id })} |
| 1707 | {...hoverProps({ kind: "edge", id: edge.id })} |
| 1708 | > |
| 1709 | <title>{linkName(edge, backOf(edge), labelOf, gt, m)}</title> |
| 1710 | </path> |
| 1711 | ); |
| 1712 | })} |
| 1713 | {linkDrag !== null && dragSource !== undefined ? ( |
| 1714 | <path |
| 1715 | d={`M${dragSource.x} ${dragSource.y}C${dragSource.x + 48} ${dragSource.y} ${linkDrag.x - 48} ${linkDrag.y} ${linkDrag.x} ${linkDrag.y}`} |
| 1716 | stroke="currentColor" |
| 1717 | strokeWidth="1.75" |
| 1718 | strokeDasharray="5 4" |
| 1719 | className="pointer-events-none text-primary" |
| 1720 | /> |
| 1721 | ) : null} |
| 1722 | </svg> |
| 1723 | {routeEdges.map((edge) => { |
| 1724 | const geometry = layout.routes.get(edge.id); |
| 1725 | if (geometry === undefined) return null; |
| 1726 | const { pill } = geometry; |
| 1727 | return ( |
| 1728 | <span |
| 1729 | key={edge.id} |
| 1730 | aria-hidden |
| 1731 | style={{ left: pill.x, top: pill.y, width: pill.width, height: pill.height }} |
| 1732 | className={cn( |
| 1733 | "absolute flex items-center justify-center rounded-full border bg-background px-1.5 text-2xs leading-none text-muted-foreground", |
| 1734 | routeLit(edge) && ROUTE_STYLES[edge.state].pill, |
| 1735 | // Lit routes sit over the others, whose wires pass beside them on the way in. |
| 1736 | routeLit(edge) && "z-1", |
| 1737 | fadeName(!routeLit(edge)), |
| 1738 | )} |
| 1739 | > |
| 1740 | <span className="truncate"> |
| 1741 | {edge.routeLabel ?? routeKindLabel(edge.routeKind, gt)} |
| 1742 | </span> |
| 1743 | </span> |
| 1744 | ); |
| 1745 | })} |
| 1746 | {links.map((edge) => { |
| 1747 | const badge = layout.links.get(edge.id)?.badge; |
| 1748 | if (!badge) return null; |
| 1749 | const target = { kind: "edge", id: edge.id } as const; |
| 1750 | const back = backOf(edge); |
| 1751 | const health = back === undefined ? edge.health : worseLinkHealth(edge.health, back.health); |
| 1752 | // With no clear place of its own, the name shows only while its link is the one in focus. |
| 1753 | if ( |
| 1754 | badge.onDemand && |
| 1755 | !isSelected("edge", edge.id) && |
| 1756 | !(focus?.kind === "edge" && focus.id === edge.id) |
| 1757 | ) { |
| 1758 | return null; |
| 1759 | } |
| 1760 | return ( |
| 1761 | <button |
| 1762 | key={edge.id} |
| 1763 | type="button" |
| 1764 | data-fleet-item="" |
| 1765 | tabIndex={-1} |
| 1766 | aria-pressed={isSelected("edge", edge.id)} |
| 1767 | aria-label={linkName(edge, back, labelOf, gt, m)} |
| 1768 | // Hangs off its own lane and grows away from the lanes beside it. |
| 1769 | style={{ |
| 1770 | top: badge.y, |
| 1771 | height: badge.height, |
| 1772 | maxWidth: badge.width, |
| 1773 | ...(badge.side === 1 |
| 1774 | ? { left: badge.x } |
| 1775 | : { right: layout.width - badge.x - badge.width }), |
| 1776 | }} |
| 1777 | className={cn( |
| 1778 | "absolute flex cursor-pointer items-center gap-1.5 rounded-full border border-border bg-card px-1.5 text-2xs leading-none outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset aria-pressed:border-primary aria-pressed:text-primary", |
| 1779 | lit === null || lit.edges.has(edge.id) ? healthTone(health) : null, |
| 1780 | badge.onDemand && "z-10 shadow-sm/5", |
| 1781 | fadeName(lit !== null && !lit.edges.has(edge.id)), |
| 1782 | )} |
| 1783 | onClick={() => onSelect(isSelected("edge", edge.id) ? null : target)} |
| 1784 | onFocus={() => setHover(target)} |
| 1785 | onBlur={() => setHover(null)} |
| 1786 | {...hoverProps(target)} |
| 1787 | > |
| 1788 | {back === undefined ? null : ( |
| 1789 | <ArrowUpDownIcon aria-hidden className="size-3 shrink-0" /> |
| 1790 | )} |
| 1791 | <AccessMeter |
| 1792 | access={edge.link.access} |
| 1793 | className={cn(lit !== null && !lit.edges.has(edge.id) && "opacity-45")} |
| 1794 | /> |
| 1795 | <span className="truncate">{m(accessConfig[edge.link.access].label)}</span> |
| 1796 | </button> |
| 1797 | ); |
| 1798 | })} |
| 1799 | {stacks.map((stack) => { |
| 1800 | const geometry = layout.stacks.get(stack.id); |
| 1801 | if (geometry === undefined) return null; |
| 1802 | const { face, tray, more } = geometry; |
| 1803 | const count = stack.memberIds.length; |
| 1804 | const range = |
| 1805 | stack.firstLabel === stack.lastLabel |
| 1806 | ? stack.firstLabel |
| 1807 | : `${stack.firstLabel} … ${stack.lastLabel}`; |
| 1808 | const group = stack.group === null ? null : foldGroupLabel(stack.group, gt); |
| 1809 | const [only] = stack.sources; |
| 1810 | const summary = |
| 1811 | group !== null |
| 1812 | ? range |
| 1813 | : stack.sources.length === 1 && only !== undefined |
| 1814 | ? gt("{access}. {reachable} of {count} reachable", { |
| 1815 | access: m(accessConfig[only.access].label), |
| 1816 | reachable: stack.reachable, |
| 1817 | count, |
| 1818 | }) |
| 1819 | : gt("{reachable} of {count} reachable, from {sources} environments", { |
| 1820 | reachable: stack.reachable, |
| 1821 | count, |
| 1822 | sources: stack.sources.length, |
| 1823 | }); |
| 1824 | const spoken = |
| 1825 | group !== null |
| 1826 | ? gt("{group}: {count} environments with no links, {range}", { group, count, range }) |
| 1827 | : gt("{range}, {count} machines linked from {sources}. {summary}", { |
| 1828 | range, |
| 1829 | count, |
| 1830 | sources: stack.sources |
| 1831 | .map((source) => nodeById.get(source.sourceId)?.label ?? "") |
| 1832 | .join(", "), |
| 1833 | summary, |
| 1834 | }); |
| 1835 | const partial = fleetStackPartial(stack); |
| 1836 | // The room the card adds below its name when some machines do not answer. |
| 1837 | const partialBand = partial ? 20 : 0; |
| 1838 | const ToggleIcon = stack.expanded ? FoldVerticalIcon : UnfoldVerticalIcon; |
| 1839 | const hidden = count - stack.shownIds.length; |
| 1840 | return ( |
| 1841 | <div key={stack.id} className={fade(stackDimmed(stack))}> |
| 1842 | {/* The card is the same open or closed, so it does not change under the pointer. */} |
| 1843 | {[8, 4].map((lift) => ( |
| 1844 | <div |
| 1845 | key={lift} |
| 1846 | aria-hidden |
| 1847 | style={{ |
| 1848 | left: face.x + lift, |
| 1849 | top: face.y - lift, |
| 1850 | width: face.width, |
| 1851 | height: face.height, |
| 1852 | }} |
| 1853 | className={cn( |
| 1854 | "absolute rounded-lg border border-border bg-card transition-opacity duration-200 ease-out motion-reduce:transition-none", |
| 1855 | group !== null && "border-dashed", |
| 1856 | stack.expanded && "opacity-0", |
| 1857 | )} |
| 1858 | /> |
| 1859 | ))} |
| 1860 | {tray === null ? null : ( |
| 1861 | <div |
| 1862 | aria-hidden |
| 1863 | style={{ left: tray.x, top: tray.y, width: tray.width, height: tray.height }} |
| 1864 | className={cn( |
| 1865 | "absolute rounded-xl border border-border/70 bg-foreground/3", |
| 1866 | APPEAR, |
| 1867 | )} |
| 1868 | /> |
| 1869 | )} |
| 1870 | <button |
| 1871 | {...focusProps({ kind: "stack", id: stack.id }, face, spoken)} |
| 1872 | className={cn( |
| 1873 | nodeClass(stack.id), |
| 1874 | "flex-col items-stretch overflow-clip rounded-lg border bg-card hover:border-foreground/50", |
| 1875 | partialBand > 0 ? "border-warning/60" : "border-foreground/25", |
| 1876 | group !== null && "border-dashed", |
| 1877 | holdsSelection(stack) && "ring-2 ring-primary ring-inset forced-colors:outline-2", |
| 1878 | )} |
| 1879 | > |
| 1880 | <span className="flex min-h-0 min-w-0 flex-1 flex-col justify-center px-2.5 pr-8"> |
| 1881 | <span className="flex items-center gap-1.5"> |
| 1882 | <span className="truncate text-xs leading-4 font-semibold text-foreground"> |
| 1883 | {group ?? range} |
| 1884 | </span> |
| 1885 | {group === null ? null : ( |
| 1886 | <span className="shrink-0 rounded-full bg-muted px-1.5 text-2xs leading-4 text-muted-foreground tabular-nums forced-colors:border"> |
| 1887 | {count} |
| 1888 | </span> |
| 1889 | )} |
| 1890 | </span> |
| 1891 | {group !== null ? ( |
| 1892 | <span className="block truncate text-2xs leading-4 text-muted-foreground"> |
| 1893 | {range} |
| 1894 | </span> |
| 1895 | ) : ( |
| 1896 | <span className="flex items-center gap-1.5 text-2xs leading-4 text-muted-foreground"> |
| 1897 | {only !== undefined && stack.sources.length === 1 ? ( |
| 1898 | <AccessMeter access={only.access} className="text-foreground/70" /> |
| 1899 | ) : null} |
| 1900 | <span className="whitespace-nowrap tabular-nums"> |
| 1901 | {gt("{machines, plural, one {# machine} other {# machines}}", { |
| 1902 | machines: count, |
| 1903 | })} |
| 1904 | </span> |
| 1905 | </span> |
| 1906 | )} |
| 1907 | </span> |
| 1908 | {partialBand === 0 ? null : ( |
| 1909 | // The headline of a stack that is partly down: its own band, never cut short. |
| 1910 | <span |
| 1911 | style={{ height: partialBand }} |
| 1912 | className="flex shrink-0 items-center gap-1.5 border-t border-warning/30 bg-warning/16 px-2.5 text-2xs leading-none font-semibold text-warning-foreground forced-colors:border-t-2" |
| 1913 | > |
| 1914 | <TriangleAlertIcon aria-hidden className="size-3 shrink-0 text-warning" /> |
| 1915 | <span className="shrink-0 whitespace-nowrap tabular-nums"> |
| 1916 | {gt("{reachable, plural, =0 {None reachable} other {# reachable}}", { |
| 1917 | reachable: stack.reachable, |
| 1918 | $context: |
| 1919 | "on a card for a group of linked machines: how many of them answer right now", |
| 1920 | })} |
| 1921 | </span> |
| 1922 | <span className="h-1 min-w-0 flex-1 overflow-clip rounded-full bg-warning/25 forced-colors:hidden"> |
| 1923 | <span |
| 1924 | className="block h-full rounded-full bg-warning" |
| 1925 | style={{ width: `${(stack.reachable / count) * 100}%` }} |
| 1926 | /> |
| 1927 | </span> |
| 1928 | </span> |
| 1929 | )} |
| 1930 | </button> |
| 1931 | <button |
| 1932 | type="button" |
| 1933 | data-fleet-item="" |
| 1934 | tabIndex={stack.id === tabStop ? 0 : -1} |
| 1935 | aria-label={ |
| 1936 | stack.expanded |
| 1937 | ? gt("Collapse these machines") |
| 1938 | : hidden > 0 |
| 1939 | ? gt("Show the first {shown} machines on the map", { |
| 1940 | shown: stack.shownIds.length, |
| 1941 | }) |
| 1942 | : gt("Show each machine on the map") |
| 1943 | } |
| 1944 | aria-expanded={stack.expanded} |
| 1945 | style={{ |
| 1946 | left: face.x + face.width - 28, |
| 1947 | top: face.y + (face.height - partialBand) / 2 - 11, |
| 1948 | }} |
| 1949 | className="absolute flex size-5.5 cursor-pointer items-center justify-center rounded-md text-muted-foreground outline-none hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset" |
| 1950 | onClick={() => onToggleStack(stack.id)} |
| 1951 | > |
| 1952 | <ToggleIcon aria-hidden className="size-3.5" /> |
| 1953 | </button> |
| 1954 | {more === null ? null : ( |
| 1955 | // The rest are never drawn: the details list every machine, and can be searched. |
| 1956 | <button |
| 1957 | type="button" |
| 1958 | data-fleet-item="" |
| 1959 | data-fleet-node={fleetMoreNodeId(stack.id)} |
| 1960 | tabIndex={fleetMoreNodeId(stack.id) === tabStop ? 0 : -1} |
| 1961 | style={{ left: more.x, top: more.y, width: more.width, height: more.height }} |
| 1962 | className={cn( |
| 1963 | "absolute flex cursor-pointer items-center rounded-md border border-dashed border-foreground/30 px-2 text-2xs leading-none text-muted-foreground outline-none hover:border-foreground/55 hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset", |
| 1964 | APPEAR, |
| 1965 | )} |
| 1966 | onClick={() => onSelect({ kind: "stack", id: stack.id })} |
| 1967 | onFocus={() => setRoving(fleetMoreNodeId(stack.id))} |
| 1968 | > |
| 1969 | <span className="truncate"> |
| 1970 | {gt("and {count} more", { |
| 1971 | count: hidden, |
| 1972 | $context: "a card standing for the machines of a group that are not drawn", |
| 1973 | })} |
| 1974 | </span> |
| 1975 | </button> |
| 1976 | )} |
| 1977 | </div> |
| 1978 | ); |
| 1979 | })} |
| 1980 | {graph.nodes.map((node) => { |
| 1981 | const rect = layout.nodes.get(node.id); |
| 1982 | if (rect === undefined) return null; |
| 1983 | const target = { kind: "node", id: node.id } as const; |
| 1984 | if (node.kind === "client") { |
| 1985 | const ClientIcon = isElectron ? AppWindowIcon : GlobeIcon; |
| 1986 | return ( |
| 1987 | <button |
| 1988 | key={node.id} |
| 1989 | {...focusProps(target, rect, node.label)} |
| 1990 | className={cn( |
| 1991 | nodeClass(node.id), |
| 1992 | "gap-2 rounded-full border border-foreground/25 bg-card px-3.5 text-foreground hover:border-foreground/50", |
| 1993 | )} |
| 1994 | > |
| 1995 | <ClientIcon aria-hidden className="size-4 shrink-0 text-muted-foreground" /> |
| 1996 | <span className="truncate text-xs font-semibold">{node.label}</span> |
| 1997 | </button> |
| 1998 | ); |
| 1999 | } |
| 2000 | const incoming = links.filter((edge) => edge.to === node.id); |
| 2001 | if (node.kind === "target") { |
| 2002 | // One link in names its access here. Several are told apart by the one in focus: |
| 2003 | // hovering or selecting a host shows what that host may do on this machine. |
| 2004 | const focused = incoming.filter((edge) => lit?.edges.has(edge.id)); |
| 2005 | const shown = |
| 2006 | incoming.length === 1 ? incoming[0] : focused.length === 1 ? focused[0] : undefined; |
| 2007 | const first = shown ?? incoming.toSorted(byTrouble)[0]; |
| 2008 | const compact = rect.height < 32; |
| 2009 | return ( |
| 2010 | <button |
| 2011 | key={node.id} |
| 2012 | {...focusProps( |
| 2013 | target, |
| 2014 | rect, |
| 2015 | [ |
| 2016 | node.label, |
| 2017 | gt("known only through a link"), |
| 2018 | ...incoming.map((edge) => |
| 2019 | gt("from {source}: {summary}", { |
| 2020 | source: nodeById.get(edge.from)?.label ?? "", |
| 2021 | summary: linkSummary(edge, gt, m), |
| 2022 | }), |
| 2023 | ), |
| 2024 | ].join(", "), |
| 2025 | )} |
| 2026 | className={cn( |
| 2027 | nodeClass(node.id), |
| 2028 | "gap-2 border bg-card text-foreground/90 hover:border-foreground/50 hover:text-foreground", |
| 2029 | compact ? cn("rounded-md px-2", APPEAR) : "rounded-lg px-2.5", |
| 2030 | first ? healthBorder(first.health) : "border-border", |
| 2031 | )} |
| 2032 | > |
| 2033 | <span className="flex w-3 shrink-0 justify-center"> |
| 2034 | {first ? <HealthGlyph health={first.health} /> : null} |
| 2035 | </span> |
| 2036 | <span className="min-w-0 flex-1"> |
| 2037 | <span |
| 2038 | className={cn( |
| 2039 | "block truncate", |
| 2040 | compact ? "text-2xs leading-none" : "text-xs leading-4 font-medium", |
| 2041 | )} |
| 2042 | > |
| 2043 | {node.label} |
| 2044 | </span> |
| 2045 | {compact || !first ? null : ( |
| 2046 | <span |
| 2047 | className={cn( |
| 2048 | "block truncate text-2xs leading-4", |
| 2049 | first.health.kind === "reachable" && first.health.expiresInDays === null |
| 2050 | ? "text-muted-foreground" |
| 2051 | : healthTone(first.health), |
| 2052 | )} |
| 2053 | > |
| 2054 | {shown === undefined |
| 2055 | ? gt("{count, plural, one {# link in} other {# links in}}", { |
| 2056 | count: incoming.length, |
| 2057 | $context: |
| 2058 | "how many machines hold a link to this machine; pairs with '# links out'", |
| 2059 | }) |
| 2060 | : first.health.kind === "reachable" && first.health.expiresInDays === null |
| 2061 | ? m(accessConfig[first.link.access].label) |
| 2062 | : `${m(accessConfig[first.link.access].label)} · ${healthLabel(first.health, gt)}`} |
| 2063 | </span> |
| 2064 | )} |
| 2065 | </span> |
| 2066 | {compact || !shown ? null : ( |
| 2067 | <AccessMeter access={shown.link.access} className="text-foreground/70" /> |
| 2068 | )} |
| 2069 | </button> |
| 2070 | ); |
| 2071 | } |
| 2072 | if (rect.height < 32) { |
| 2073 | // Inside an open group of environments: its name and state; the details have the rest. |
| 2074 | const state = |
| 2075 | node.kind === "connect" |
| 2076 | ? connectAvailabilityText(node.availability, gt) |
| 2077 | : connectionStateText(node, environmentById.get(node.id), false, gt); |
| 2078 | return ( |
| 2079 | <button |
| 2080 | key={node.id} |
| 2081 | {...focusProps(target, rect, `${node.label}, ${state}`)} |
| 2082 | className={cn( |
| 2083 | nodeClass(node.id), |
| 2084 | "gap-1.5 rounded-md border border-dashed border-foreground/25 bg-card px-2 text-foreground/90 hover:border-foreground/50 hover:text-foreground", |
| 2085 | APPEAR, |
| 2086 | )} |
| 2087 | > |
| 2088 | <span |
| 2089 | aria-hidden |
| 2090 | className={cn( |
| 2091 | "size-2 shrink-0 rounded-full", |
| 2092 | node.kind === "environment" && node.enabled |
| 2093 | ? connectionPhaseDotClassName(node.phase) |
| 2094 | : "bg-muted-foreground/40", |
| 2095 | )} |
| 2096 | /> |
| 2097 | <span className="truncate text-2xs leading-none">{node.label}</span> |
| 2098 | </button> |
| 2099 | ); |
| 2100 | } |
| 2101 | if (node.kind === "connect") { |
| 2102 | const status = `${gt("Not added")} · ${connectAvailabilityText(node.availability, gt)}`; |
| 2103 | return ( |
| 2104 | <button |
| 2105 | key={node.id} |
| 2106 | {...focusProps( |
| 2107 | target, |
| 2108 | rect, |
| 2109 | gt("{label}, on your T3 Connect account, not added to this app. {status}", { |
| 2110 | label: node.label, |
| 2111 | status: connectAvailabilityText(node.availability, gt), |
| 2112 | }), |
| 2113 | )} |
| 2114 | className={cn( |
| 2115 | nodeClass(node.id), |
| 2116 | "gap-2 rounded-lg border border-dashed border-foreground/30 bg-card/60 px-2.5 hover:border-foreground/55", |
| 2117 | )} |
| 2118 | > |
| 2119 | <CloudIcon aria-hidden className="size-4 shrink-0 text-muted-foreground" /> |
| 2120 | <span className="min-w-0 flex-1"> |
| 2121 | <span className="block truncate text-xs leading-4 font-semibold text-foreground"> |
| 2122 | {node.label} |
| 2123 | </span> |
| 2124 | <span className="block truncate text-2xs leading-4 text-muted-foreground"> |
| 2125 | {status} |
| 2126 | </span> |
| 2127 | </span> |
| 2128 | </button> |
| 2129 | ); |
| 2130 | } |
| 2131 | const environment = environmentById.get(node.id); |
| 2132 | const routes = routeEdges.filter((edge) => edge.to === node.id); |
| 2133 | const status = environmentStatusText( |
| 2134 | node, |
| 2135 | environment, |
| 2136 | routes.length > 0 && routes.every((edge) => edge.state === "refused"), |
| 2137 | links.filter((edge) => edge.from === node.id).length, |
| 2138 | gt, |
| 2139 | ); |
| 2140 | // The card's state is short; the name carries the reason and what it leaves unknown. |
| 2141 | const spoken = |
| 2142 | node.phase === "connected" |
| 2143 | ? status |
| 2144 | : gt("{status}. Links unknown", { |
| 2145 | status: environment ? savedBackendStatus(environment, m).text : status, |
| 2146 | }); |
| 2147 | const dimmed = !node.enabled || node.phase === "unsupported"; |
| 2148 | const handle = layout.handles.get(node.id); |
| 2149 | const over = linkDrag?.overId === node.id; |
| 2150 | return ( |
| 2151 | <div key={node.id}> |
| 2152 | <button |
| 2153 | {...focusProps( |
| 2154 | target, |
| 2155 | rect, |
| 2156 | [ |
| 2157 | node.label, |
| 2158 | spoken, |
| 2159 | ...routes.map( |
| 2160 | (edge) => |
| 2161 | `${edge.routeLabel ?? routeKindLabel(edge.routeKind, gt)}: ${routeStateLabel(edge.state, gt)}`, |
| 2162 | ), |
| 2163 | ].join(", "), |
| 2164 | )} |
| 2165 | className={cn( |
| 2166 | nodeClass(node.id), |
| 2167 | "gap-2 rounded-lg border bg-card px-2.5 text-card-foreground shadow-sm/5 hover:border-foreground/45", |
| 2168 | dimmed ? "border-dashed border-foreground/25" : "border-foreground/20", |
| 2169 | over && "border-primary", |
| 2170 | )} |
| 2171 | > |
| 2172 | <span |
| 2173 | className={cn( |
| 2174 | "relative flex size-6 shrink-0 items-center justify-center rounded-md bg-muted text-foreground/80 forced-colors:border", |
| 2175 | dimmed && "opacity-60", |
| 2176 | )} |
| 2177 | > |
| 2178 | <EnvironmentMachineIcon kind={node.machine ?? "server"} className="size-3.5" /> |
| 2179 | <span |
| 2180 | aria-hidden |
| 2181 | className={cn( |
| 2182 | "absolute -right-1 -bottom-1 size-2.5 rounded-full border-2 border-card", |
| 2183 | node.enabled |
| 2184 | ? connectionPhaseDotClassName(node.phase) |
| 2185 | : "bg-muted-foreground/40", |
| 2186 | )} |
| 2187 | /> |
| 2188 | </span> |
| 2189 | <span className={cn("min-w-0 flex-1 pr-1.5", dimmed && "opacity-70")}> |
| 2190 | <span className="line-clamp-2 text-xs leading-4 font-semibold [overflow-wrap:anywhere]"> |
| 2191 | {node.label} |
| 2192 | </span> |
| 2193 | <span |
| 2194 | className={cn( |
| 2195 | "block truncate text-2xs leading-4", |
| 2196 | node.outgoing === "error" && node.phase === "connected" |
| 2197 | ? "text-destructive" |
| 2198 | : "text-muted-foreground", |
| 2199 | )} |
| 2200 | > |
| 2201 | {status} |
| 2202 | </span> |
| 2203 | </span> |
| 2204 | </button> |
| 2205 | {handle !== undefined && node.linking === "ready" ? ( |
| 2206 | <button |
| 2207 | type="button" |
| 2208 | data-fleet-item="" |
| 2209 | tabIndex={node.id === tabStop ? 0 : -1} |
| 2210 | aria-label={gt("Link {label} to another machine", { label: node.label })} |
| 2211 | style={{ left: handle.x - 9, top: handle.y - 9 }} |
| 2212 | onFocus={(event) => { |
| 2213 | // Its own bounds: it straddles the card's edge, so the card can be in view |
| 2214 | // while half the handle is not. |
| 2215 | if (event.currentTarget.matches(":focus-visible")) { |
| 2216 | onReveal({ x: handle.x - 9, y: handle.y - 9, width: 18, height: 18 }); |
| 2217 | } |
| 2218 | }} |
| 2219 | className={cn( |
| 2220 | "absolute flex size-4.5 cursor-crosshair touch-none items-center justify-center rounded-full bg-primary text-primary-foreground outline-none hover:scale-110 focus-visible:ring-2 focus-visible:ring-foreground focus-visible:ring-inset motion-safe:transition-transform motion-safe:duration-150 forced-colors:border", |
| 2221 | fade(nodeDimmed(node.id)), |
| 2222 | )} |
| 2223 | {...handleProps(node.id)} |
| 2224 | > |
| 2225 | <PlusIcon aria-hidden className="size-3" strokeWidth={2.5} /> |
| 2226 | </button> |
| 2227 | ) : null} |
| 2228 | </div> |
| 2229 | ); |
| 2230 | })} |
| 2231 | {[...selected].map((id) => { |
| 2232 | const rect = layout.nodes.get(id); |
| 2233 | if (rect === undefined) return null; |
| 2234 | return ( |
| 2235 | <span |
| 2236 | key={id} |
| 2237 | aria-hidden |
| 2238 | style={{ |
| 2239 | left: rect.x - 3, |
| 2240 | top: rect.y - 3, |
| 2241 | width: rect.width + 6, |
| 2242 | height: rect.height + 6, |
| 2243 | }} |
| 2244 | className="pointer-events-none absolute rounded-xl border-2 border-primary bg-primary/6" |
| 2245 | > |
| 2246 | <span className="absolute -top-2 -left-2 flex size-4 items-center justify-center rounded-full bg-primary text-primary-foreground forced-colors:border"> |
| 2247 | <CheckIcon className="size-2.5" strokeWidth={3} /> |
| 2248 | </span> |
| 2249 | </span> |
| 2250 | ); |
| 2251 | })} |
| 2252 | {linkDrag !== null ? ( |
| 2253 | <DragHint x={linkDrag.x} y={linkDrag.y}> |
| 2254 | {dragOver !== null |
| 2255 | ? actionText(dragAction(dragOver), nodeById.get(dragOver)?.label ?? "", gt) |
| 2256 | : gt("Drop on a machine to link")} |
| 2257 | </DragHint> |
| 2258 | ) : null} |
| 2259 | </div> |
| 2260 | ); |
| 2261 | }); |
| 2262 | |
| 2263 | function DragHint({ x, y, children }: { x: number; y: number; children: ReactNode }) { |
| 2264 | return ( |
| 2265 | <p |
| 2266 | role="status" |
| 2267 | style={{ left: x + 14, top: y + 14 }} |
| 2268 | className="pointer-events-none absolute z-10 rounded-md border border-border bg-popover px-2 py-1 text-2xs whitespace-nowrap text-popover-foreground shadow-sm/5" |
| 2269 | > |
| 2270 | {children} |
| 2271 | </p> |
| 2272 | ); |
| 2273 | } |