import { useEffect, useRef, useState } from "react"; import { Check, ChevronUp, CircleAlert, Laptop, Loader2, Search, Server, Settings2, X } from "lucide-react"; import { useTranslation } from "react-i18next"; import { Button } from "@/components/ui/button"; import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip"; import { ConnectionBadge } from "@/components/ConnectionBadge"; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"; import { cn } from "@/lib/utils"; import type { ConnectionStatus } from "@/lib/types"; import type { HostAnchor } from "./host-bridge"; import type { HostPicker, EmbeddedPicker } from "./host-navigation"; import { HostConnectionStatus } from "./HostConnectionStatus"; function HostMenuContent({ picker, portalContainer }: { picker: HostPicker; portalContainer?: HTMLElement | null }) { return { if (event.isComposing) event.preventDefault(); }} onCloseAutoFocus={(event) => { event.preventDefault(); picker.restoreFocus(); }}> ; } /** Mounted with the menu so every opening starts with a fresh, stable list. */ function HostMenuItems({ picker }: { picker: HostPicker }) { const { t } = useTranslation(); const [searchable] = useState(() => picker.profiles.length > 5); const [query, setQuery] = useState(""); const [order] = useState(() => [picker.currentId, ...picker.recentIds]); const search = useRef(null); const list = useRef(null); const needle = query.trim().toLocaleLowerCase(); const matches = (...values: string[]) => values.some((value) => value.toLocaleLowerCase().includes(needle)); const showLocal = matches(t("remote.local"), picker.localName); const profiles = picker.profiles.filter(({ name, host }) => matches(name, host)); if (searchable) { const rank = (id: string) => { const index = order.indexOf(id); return index < 0 ? order.length : index; }; profiles.sort((a, b) => rank(a.id) - rank(b.id)); } useEffect(() => { // Don't summon the software keyboard when opening the picker on a touch device. if (!searchable || window.matchMedia("(pointer: coarse)").matches) return; const frame = requestAnimationFrame(() => search.current?.focus({ preventScroll: true })); return () => cancelAnimationFrame(frame); }, [searchable]); return { if (document.activeElement === search.current) event.preventDefault(); }} onPointerOutCapture={(event) => { if (document.activeElement === search.current) event.preventDefault(); }} onKeyDownCapture={(event) => { if (!searchable) return; if (event.nativeEvent.isComposing) { event.stopPropagation(); return; } const items = Array.from(event.currentTarget.querySelectorAll('[role="menuitem"]')); if (event.target === search.current) { // Keep spaces and IME input out of Radix's menu typeahead. if (event.key !== "Escape") event.stopPropagation(); if (event.key === "ArrowDown" || event.key === "ArrowUp" || event.key === "Tab") { event.preventDefault(); (event.key === "ArrowUp" || event.shiftKey ? items.at(-1) : items[0])?.focus(); } else if (event.key === "Enter") { event.preventDefault(); if (needle) list.current?.querySelector('[role="menuitem"]')?.click(); } } else if (event.key === "Tab" || (event.key === "ArrowUp" && event.target === items[0])) { event.preventDefault(); event.stopPropagation(); search.current?.focus(); } }}> {searchable ? setQuery(event.target.value)} autoComplete="off" spellCheck={false} className="touch-text-input h-7 min-w-0 flex-1 bg-transparent text-[13px] outline-none placeholder:text-muted-foreground" /> : {t("remote.switchHost")}} {showLocal && picker.select(null)} className="gap-2.5" aria-current={!picker.currentId || undefined}> {t("remote.local")}{picker.localName} {!picker.currentId && } } {showLocal && !!profiles.length && } {profiles.map((profile) => picker.select(profile.id)} className="gap-2.5" aria-label={`${profile.name} ${profile.host}`} aria-describedby={`host-state-${profile.id}`} title={`${profile.name}\n${profile.host}`} aria-current={picker.currentId === profile.id || undefined}> {profile.name}{profile.host} {picker.currentId === profile.id && } )} {!showLocal && !profiles.length && {t("remote.noMatchingHosts")}} {picker.pending && <>{t("remote.cancelSwitch")}>} {picker.error && {picker.error}{t("common.close")} } {t("remote.manageConnections")} ; } /** Shared sidebar control. Remote frames can only open the trusted shell's menu. */ export function HostSwitcherView({ picker, status, collapsed = false, portalContainer }: { picker: HostPicker | EmbeddedPicker | null; status: ConnectionStatus; collapsed?: boolean; portalContainer?: HTMLElement | null; }) { const { t } = useTranslation(); const buttonRef = useRef(null); if (!picker) return ; const shell = picker.kind === "shell" ? picker : null; const remote = picker.kind === "embedded" || !!shell?.currentId; const pendingName = picker.kind === "shell" ? picker.pending?.name : picker.pendingName; const currentStatus = shell?.currentId ? (shell.pending?.id === shell.currentId || shell.profiles.find((profile) => profile.id === shell.currentId)?.state === "connecting" ? "connecting" : shell.offline ? "closed" : "open") : status; // A failed switch describes the destination, not the still-active connection. const failed = !!shell?.offline || currentStatus === "error" || currentStatus === "closed"; const waiting = !!pendingName || currentStatus === "connecting" || currentStatus === "reconnecting"; // The old host stays interactive until the new one is ready. Keep its identity // visible; progress belongs to the target's row and the accessible status. const label = picker.name; const currentLabel = failed ? shell?.offlineLabel || t("remote.offline") : t(`connection.${currentStatus}`); const identity = picker.name === picker.hostname ? picker.name : `${picker.name}, ${picker.hostname}`; const current = `${identity}, ${currentLabel}`; const detail = pendingName ? `${current}. ${t("remote.preparing", { name: pendingName })}` : current; const button = { const rect = buttonRef.current?.getBoundingClientRect(); if (rect) picker.open({ left: rect.left, top: rect.top, width: rect.width, height: rect.height }); } : undefined}> {waiting ? : failed ? : remote ? : } {!waiting && !failed && } {!collapsed && <>{label}>} {detail} ; const trigger = {button}; // The mobile sidebar already owns the modal lock; a nested lock can outlive it on navigation. return {shell ? {trigger} : trigger} {picker.name} {picker.hostname !== picker.name ? {picker.hostname} : null} {currentLabel} {pendingName ? {t("remote.preparing", { name: pendingName })} : null} {picker.error ? {picker.error} : null} ; } /** Parent-owned menu anchored to the active remote sidebar, never inside its DOM. */ export function RemoteHostMenu({ picker, anchor, onClose }: { picker: HostPicker; anchor: HostAnchor | null; onClose: () => void }) { return { if (!open) onClose(); }}> ; }
{t("remote.noMatchingHosts")}
{picker.name}
{picker.hostname}
{currentLabel}
{t("remote.preparing", { name: pendingName })}
{picker.error}