Файли
openidea/src/features/remote-dev/ConnectDialog.tsx
T
l0ng-ai f70f362a3d feat(ui): open New Project, Get from VCS and Remote Development in their own windows (#6208)
* feat(ui): open New Project, Get from VCS and Remote Development in their own windows

Each dialog gets a native window over its project window: a full-height
sidebar under the traffic lights, the title heading the content and the
buttons in its corner. The windows hand their result back to the project
window, which opens the created or cloned project or makes the remote
connection and reports its progress. Remote windows and the browser build
keep the dialogs in the page.

* feat(ui): show dialogs in the page as sheets without window buttons on macOS

The title heads the content instead of a title bar with drawn traffic
lights; Esc and Cancel close the dialog, and the title dims while the
window is inactive.

* fix(ui): give a macOS dialog without footer buttons a Close button

A sheet has no window buttons, so a dialog with neither buttons nor a
footer could only be closed with Esc. The Extract Interface members
table may shrink to two rows so the dialog still fits a short window
under the taller sheet title.
2026-11-27 08:59:33 +08:00

305 рядки
9.6 KiB
TypeScript

/**
* Picks an SSH configuration and a folder on that host, then opens it in this or a new window.
* In the desktop app it has its own window (`connectWindow.tsx`).
*/
import { useEffect, useState, type ReactNode } from "react";
import { executeAction } from "@/platform/actions";
import { useTx } from "@/platform/i18n";
import { call, commands, isCancelled, onIdeEvent, type RemoteEntry, type RemoteTarget } from "@/platform/ipc";
import { localGlobalSettings, useRemoteProgress } from "@/platform/remote";
import { sshLabel, type SshConfigValid, validateRemote } from "@/platform/remoteSettings";
import { Button, Dialog, Icon, Input, ProgressBar, Select, Spinner, type DialogButton } from "@/ui";
import { openRemoteProject } from "@/workbench/projectWindow";
import { windowBackgroundHex } from "@/workbench/theme";
import { WindowDialogFrame } from "@/workbench/WindowDialogFrame";
import {
browsableFolders,
closeConnectDialog,
listedDirectory,
remoteParent,
stageLabel,
useConnectDialog,
} from "./model";
import styles from "./RemoteDev.module.css";
export function ConnectHost() {
const open = useConnectDialog((s) => s.open);
return open ? <ConnectDialog /> : null;
}
const SSH_SETTINGS_PAGE = "tools.sshConfigurations";
/**
* This machine's SSH configurations: the connection is made from here. A remote project's
* window has the remote host's settings, which don't list them.
*/
function useLocalSshConfigs(): SshConfigValid[] {
const [configs, setConfigs] = useState<SshConfigValid[]>([]);
useEffect(() => {
let live = true;
const load = () =>
void localGlobalSettings().then(
(s) => live && setConfigs(validateRemote(s).ssh.configs),
() => {},
);
load();
const off = onIdeEvent("settingsChanged", load);
return () => {
live = false;
off();
};
}, []);
return configs;
}
function Frame({
standalone,
onClose,
buttons,
children,
}: {
standalone: boolean;
onClose: () => void;
buttons: readonly DialogButton[];
children: ReactNode;
}) {
const tx = useTx();
if (standalone)
return (
<WindowDialogFrame title="Remote Development" buttons={buttons} onCancel={onClose}>
{children}
</WindowDialogFrame>
);
return (
<Dialog open title={tx("Remote Development")} onClose={onClose} width={560} buttons={buttons}>
{children}
</Dialog>
);
}
/**
* `standalone`: fills the Remote Development window, whose project window connects
* (`onConnect`: true once the project is open).
*/
export function ConnectDialog({
standalone = false,
onClose = closeConnectDialog,
onConnect,
}: {
standalone?: boolean;
onClose?: () => void;
onConnect?: (target: RemoteTarget, path: string) => Promise<boolean>;
}) {
const tx = useTx();
const configs = useLocalSshConfigs();
const [picked, setSsh] = useState("");
const ssh = configs.some((c) => c.id === picked) ? picked : (configs[0]?.id ?? "");
const [kind, setKind] = useState<RemoteTarget["kind"]>("ssh");
// Installed WSL distributions; none (or no WSL at all) hides the WSL choice.
const [distros, setDistros] = useState<string[]>([]);
const [distro, setDistro] = useState("");
const [path, setPath] = useState("~");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [browse, setBrowse] = useState<{ dir: string; folders: RemoteEntry[] } | null>(null);
useEffect(() => {
let live = true;
// Detection is a convenience: any failure just leaves SSH as the only choice.
void call(commands.wslDistros())
.then((found) => {
if (!live) return;
setDistros(found);
setDistro((d) => d || (found[0] ?? ""));
})
.catch(() => {});
return () => {
live = false;
};
}, []);
const wsl = kind === "wsl";
const name = wsl ? distro : ssh;
const target: RemoteTarget = wsl ? { kind: "wsl", distro } : { kind: "ssh", config: ssh };
const list = async (dir: string) => {
setError(null);
setBusy(true);
try {
const entries = await call(commands.remoteBootstrapList(ssh, dir));
const shown = listedDirectory(dir, entries);
setBrowse({ dir: shown, folders: browsableFolders(entries) });
setPath(shown);
} catch (e) {
setError(e instanceof Error ? e.message : String(e));
} finally {
setBusy(false);
}
};
const connect = async () => {
setError(null);
setBusy(true);
try {
const dir = path.trim() || "~";
if (await (onConnect ? onConnect(target, dir) : openRemoteProject(target, dir))) onClose();
else setBusy(false);
} catch (e) {
if (!isCancelled(e)) setError(e instanceof Error ? e.message : String(e));
setBusy(false);
}
};
const options = configs.map((c) => ({
value: c.id,
verbatim: true,
verbatimDetail: true,
label: c.name.trim() || sshLabel(c),
detail: sshLabel(c),
}));
const ready = !!name && !busy && !!path.trim();
const connecting = useRemoteProgress((s) => s.progress !== null);
const configure = () =>
standalone
? void call(commands.windowOpenSettings(SSH_SETTINGS_PAGE, false, windowBackgroundHex())).catch(() => {})
: void executeAction("file.settings", SSH_SETTINGS_PAGE);
return (
<Frame
standalone={standalone}
onClose={onClose}
buttons={[
{
label: connecting ? "Connecting…" : "Open",
role: "default",
disabled: !ready,
onClick: () => void connect(),
},
{ label: "Cancel", role: "cancel" },
]}
>
<form
className={standalone ? `${styles.form} ${styles.windowForm}` : styles.form}
onSubmit={(e) => {
e.preventDefault();
if (ready) void connect();
}}
>
<p className={styles.hint}>
{tx("The project runs on the remote host; the IDE backend is installed there on first use.")}
</p>
{distros.length > 0 && (
<>
<label className={styles.label}>{tx("Connect through:")}</label>
<Select
value={kind}
options={[
{ value: "ssh", label: "SSH" },
{ value: "wsl", label: "WSL" },
]}
onChange={(k) => {
setKind(k as RemoteTarget["kind"]);
setBrowse(null);
}}
aria-label={tx("Connect through")}
/>
</>
)}
{wsl ? (
<>
<label className={styles.label}>{tx("WSL distribution:")}</label>
<Select
value={distro || null}
options={distros.map((d) => ({ value: d, verbatim: true, label: d }))}
onChange={setDistro}
aria-label={tx("WSL distribution")}
/>
</>
) : (
<>
<label className={styles.label}>{tx("SSH configuration:")}</label>
<div className={styles.row}>
<Select
className={styles.grow}
value={ssh || null}
options={options}
placeholder={tx("No SSH configurations")}
onChange={(id) => {
setSsh(id);
setBrowse(null);
}}
aria-label={tx("SSH configuration")}
/>
<Button onClick={configure}>{tx("Configure…")}</Button>
</div>
</>
)}
<label className={styles.label} htmlFor="remote-dev-path">
{tx("Project directory:")}
</label>
<div className={styles.row}>
<Input
id="remote-dev-path"
className={styles.grow}
data-autofocus
value={path}
spellCheck={false}
onChange={(e) => setPath(e.target.value)}
/>
{/* Browsing lists over SFTP; a WSL distribution has no such session before connecting. */}
{!wsl && (
<Button disabled={!ssh || busy} onClick={() => void list(path.trim() || "~")}>
{tx("Browse")}
</Button>
)}
</div>
{browse && (
<ul className={styles.folders} aria-label={tx("Remote folders")}>
{browse.dir !== "/" && (
<li>
<button type="button" className={styles.folder} onClick={() => void list(remoteParent(browse.dir))}>
<Icon name="folder" />
..
</button>
</li>
)}
{browse.folders.map((f) => (
<li key={f.path}>
<button type="button" className={styles.folder} onClick={() => void list(f.path)}>
<Icon name="folder" />
{f.name}
</button>
</li>
))}
</ul>
)}
<ConnectProgress />
{error && (
<div className={styles.error} role="alert">
{error}
</div>
)}
</form>
</Frame>
);
}
/** The stage of the connection in progress (and how far a download / upload is). */
function ConnectProgress() {
const tx = useTx();
const progress = useRemoteProgress((s) => s.progress);
if (!progress) return null;
const percent = progress.fraction == null ? null : Math.round(progress.fraction * 100);
return (
<div className={styles.progress} role="status">
<div className={styles.progressLine}>
<Spinner size={12} />
<span>{tx(stageLabel(progress.stage))}</span>
{percent != null && <span className={styles.percent}>{percent}%</span>}
</div>
<ProgressBar value={progress.fraction} aria-label={tx(stageLabel(progress.stage))} />
</div>
);
}