Порівняти коміти

...
Автор SHA1 Повідомлення Дата
l0ng-ai f172023e4e fix(remote): browse the remote host when a setting asks for a path
In a remote window, choosePath (Project Structure libraries, SDK homes,
interpreters and the other settings that pick a file or folder) opened the
desktop's own dialog, so it showed this machine's files while the path is
used on the remote host. It now opens an in-app chooser that lists the
host's folders through fs_read_dir: a click selects, a double click or Enter
opens a folder or chooses the file, the arrow goes to the parent folder, and
the path can be typed.
2026-11-17 14:47:44 +08:00
6 змінених файлів з 352 додано та 7 видалено

No files matched your search

+24 -3
Переглянути файл
@@ -1,12 +1,33 @@
import { isTauri } from "@/platform/ipc";
import { isRemoteWindow } from "@/platform/remote";
/** File / folder chooser (Tauri dialog); null when cancelled or outside Tauri. */
export async function choosePath(opts: {
export interface ChoosePathOptions {
directory: boolean;
title: string;
defaultPath?: string;
}): Promise<string | null> {
}
type HostChooser = (opts: ChoosePathOptions) => Promise<string | null>;
let hostChooser: HostChooser | null = null;
/**
* Registers the in-app chooser that browses the remote host (the workbench's, in `inputDialogs`):
* the desktop's own dialog would show this machine's files.
*/
export function registerHostPathChooser(chooser: HostChooser): () => void {
hostChooser = chooser;
return () => {
if (hostChooser === chooser) hostChooser = null;
};
}
/**
* File / folder chooser for a path on the host this window's commands run on: the desktop's dialog
* locally, the in-app chooser in a remote window. Null when cancelled or outside Tauri.
*/
export async function choosePath(opts: ChoosePathOptions): Promise<string | null> {
if (!isTauri()) return null;
if (isRemoteWindow() && hostChooser) return hostChooser(opts);
// Lazy on purpose: loading platform/dialog starts its GTK capability probe at module load.
const { open } = await import("@/platform/dialog");
const picked = await open({
+3 -1
Переглянути файл
@@ -2333,5 +2333,7 @@
"Java Agents": "Java Agents",
"File at a Git revision (read-only).": "File at a Git revision (read-only).",
"Adjust colors for red-green vision deficiency is on, so this scheme shows its red-green colors.": "Adjust colors for red-green vision deficiency is on, so this scheme shows its red-green colors.",
"Appearance settings": "Appearance settings"
"Appearance settings": "Appearance settings",
"No such file or folder": "No such file or folder",
"Choose a folder": "Choose a folder"
}
+3 -1
Переглянути файл
@@ -8716,5 +8716,7 @@
"Java Agents": "Java 代理",
"File at a Git revision (read-only).": "Git 修订版中的文件(只读)。",
"Adjust colors for red-green vision deficiency is on, so this scheme shows its red-green colors.": "已开启「针对红绿色觉缺陷调整颜色」,此方案显示的是红绿色觉变体的颜色。",
"Appearance settings": "外观设置"
"Appearance settings": "外观设置",
"No such file or folder": "文件或文件夹不存在",
"Choose a folder": "请选择文件夹"
}
+23
Переглянути файл
@@ -60,3 +60,26 @@
.area::placeholder {
color: var(--fg-faint);
}
.pathRow {
display: flex;
align-items: center;
gap: var(--space-1);
}
.pathInput {
flex: 1;
min-width: 0;
}
.pathList {
height: 280px;
border: 1px solid var(--border);
border-radius: var(--radius-control, 4px);
}
.entryName {
overflow: hidden;
text-overflow: ellipsis;
}
.entry {
display: flex;
align-items: center;
gap: var(--space-1);
}
+165 -2
Переглянути файл
@@ -9,8 +9,11 @@
*/
import { useEffect, useRef, useState, type ReactNode } from "react";
import { create } from "zustand";
import { registerHostPathChooser, type ChoosePathOptions } from "@/platform/choosePath";
import { t, tx, VerbatimTextContext } from "@/platform/i18n";
import { Checkbox, Dialog, Given, Input, List, T } from "@/ui";
import { call, commands, type FileEntry } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { Checkbox, Dialog, Given, Icon, IconButton, Input, List, T } from "@/ui";
import styles from "./inputDialogs.module.css";
export interface PromptInputOptions {
@@ -59,7 +62,8 @@ export interface PickItemsOptions {
type Request =
| { kind: "prompt"; id: number; options: PromptInputOptions; resolve: (v: string | null) => void }
| { kind: "choose"; id: number; options: ChooseItemOptions; resolve: (v: string | null) => void }
| { kind: "pick"; id: number; options: PickItemsOptions; resolve: (v: string[] | null) => void };
| { kind: "pick"; id: number; options: PickItemsOptions; resolve: (v: string[] | null) => void }
| { kind: "path"; id: number; options: ChoosePathOptions; resolve: (v: string | null) => void };
const useInputDialogs = create<{ stack: Request[] }>(() => ({ stack: [] }));
let seq = 0;
@@ -97,6 +101,13 @@ export function pickItems(options: PickItemsOptions): Promise<string[] | null> {
return open<string[]>((id, resolve) => ({ kind: "pick", id, options, resolve }), options.signal);
}
/** A file or folder on the host this window's commands run on, browsed in the IDE (a remote window's chooser). */
export function choosePathOnHost(options: ChoosePathOptions): Promise<string | null> {
return open<string>((id, resolve) => ({ kind: "path", id, options, resolve }));
}
registerHostPathChooser(choosePathOnHost);
export function InputDialogsHost() {
const stack = useInputDialogs((s) => s.stack);
return (
@@ -108,6 +119,8 @@ export function InputDialogsHost() {
</VerbatimTextContext.Provider>
) : r.kind === "choose" ? (
<ChooseDialog key={r.id} options={r.options} done={r.resolve} />
) : r.kind === "path" ? (
<PathDialog key={r.id} options={r.options} done={r.resolve} />
) : (
<VerbatimTextContext.Provider key={r.id} value={!!r.options.verbatim}>
<PickDialog options={r.options} done={r.resolve} />
@@ -335,3 +348,153 @@ function PickDialog({ options, done }: { options: PickItemsOptions; done: (v: st
</Dialog>
);
}
/** The folder that holds `path` (either separator), or null at a root. */
export function parentPath(path: string): string | null {
if (/^(?:[\\/]+|[A-Za-z]:[\\/]*)$/.test(path)) return null;
const trimmed = path.length > 1 ? path.replace(/[\\/]+$/, "") : path;
const cut = Math.max(trimmed.lastIndexOf("/"), trimmed.lastIndexOf("\\"));
if (cut < 0) return null;
const parent = trimmed.slice(0, cut);
// `/a` → `/`; `C:\a` → `C:\`.
if (!parent || /^[A-Za-z]:$/.test(parent)) return parent + trimmed[cut];
return parent === trimmed ? null : parent;
}
function PathDialog({ options, done }: { options: ChoosePathOptions; done: (v: string | null) => void }) {
const root = useProject((s) => s.project?.root ?? null);
const [dir, setDir] = useState<string | null>(null);
const [entries, setEntries] = useState<FileEntry[]>([]);
const [active, setActive] = useState(-1);
const [value, setValue] = useState(options.defaultPath || root || "");
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
const request = useRef(0);
const isDir = (e: FileEntry) => e.kind === "dir" || (e.kind === "symlink" && e.targetKind === "dir");
const visit = async (path: string) => {
const id = ++request.current;
setLoading(true);
try {
const listed = await call(commands.fsReadDir(path));
if (id !== request.current) return true;
const shown = listed
.filter((e) => !options.directory || isDir(e))
.sort((a, b) => Number(isDir(b)) - Number(isDir(a)) || a.name.localeCompare(b.name));
setDir(path);
setEntries(shown);
setActive(-1);
setValue(path);
setError(null);
return true;
} catch (e) {
if (id === request.current) setError(e instanceof Error ? e.message : String(e));
return false;
} finally {
if (id === request.current) setLoading(false);
}
};
useEffect(() => {
const start = options.defaultPath || root || "/";
// A file path starts in its folder, with the file in the field.
void visit(start).then((ok) => {
const parent = parentPath(start);
if (!ok && parent) void visit(parent).then((found) => found && !options.directory && setValue(start));
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const choose = (entry: FileEntry) => {
if (isDir(entry)) void visit(entry.path);
else done(entry.path);
};
const submit = async () => {
const path = value.trim();
if (!path) return;
let kind: string;
try {
kind = await call(commands.fsEntryKind(path));
} catch {
return setError(tx("No such file or folder"));
}
const folder = kind === "dir";
if (options.directory) return folder ? done(path) : setError(tx("Choose a folder"));
if (folder) return void visit(path);
done(path);
};
const up = dir === null ? null : parentPath(dir);
return (
<Dialog
open
blockWorkbenchShortcuts
title={options.title}
onClose={() => done(null)}
width={520}
buttons={[
{ label: tx("OK"), role: "default", disabled: !value.trim(), onClick: () => void submit() },
{ label: t("common.cancel"), role: "cancel" },
]}
>
<form
className={styles.form}
onSubmit={(e) => {
e.preventDefault();
void submit();
}}
>
<div className={styles.pathRow}>
<IconButton
icon="arrow-up"
title={tx("Parent Folder")}
disabled={!up || loading}
onClick={() => up && void visit(up)}
/>
<Input
data-autofocus
className={styles.pathInput}
aria-label={options.title}
value={value}
invalid={!!error}
onChange={(e) => {
setValue(e.target.value);
setError(null);
}}
/>
</div>
<List
items={entries}
getKey={(e) => e.path}
activeIndex={active}
onActiveChange={(i) => {
setActive(i);
const entry = entries[i];
if (entry) setValue(entry.path);
}}
// A click selects; a double click or Enter opens the folder or chooses the file.
onActivate={(entry, _i, e) => (e.type !== "click" || e.detail > 1) && choose(entry)}
rowHeight={24}
className={styles.pathList}
aria-label={dir ?? options.title}
empty={
<div className={styles.hint}>
<T>{loading ? "Loading…" : "Empty folder"}</T>
</div>
}
renderItem={(entry, state) => (
<div className={`${state.active ? styles.activeRow : styles.row} ${styles.entry}`}>
<Icon name={isDir(entry) ? "folder" : "file"} />
<span className={styles.entryName}>{entry.name}</span>
</div>
)}
/>
{error && (
<div className={styles.error}>
<T>{error}</T>
</div>
)}
</form>
</Dialog>
);
}
+134
Переглянути файл
@@ -0,0 +1,134 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import type { FileEntry } from "@/platform/ipc";
const mocks = vi.hoisted(() => ({
readDir: vi.fn(),
entryKind: vi.fn(),
nativeOpen: vi.fn(),
}));
vi.mock("@/platform/ipc", async (importOriginal) => {
const real = await importOriginal<typeof import("@/platform/ipc")>();
return {
...real,
isTauri: () => true,
commands: { ...real.commands, fsReadDir: mocks.readDir, fsEntryKind: mocks.entryKind },
};
});
vi.mock("@tauri-apps/plugin-dialog", () => ({ open: mocks.nativeOpen, save: vi.fn() }));
import { choosePath } from "@/platform/choosePath";
import { useRemote } from "@/platform/remote";
import { InputDialogsHost, parentPath } from "./inputDialogs";
const tree: Record<string, [string, "dir" | "file"][]> = {
"/srv/app": [
["runner", "dir"],
["pom.xml", "file"],
],
"/srv/app/runner": [
["plugins", "dir"],
["server.jar", "file"],
],
"/srv": [["app", "dir"]],
};
function entry(dir: string, name: string, kind: "dir" | "file"): FileEntry {
return {
name,
path: `${dir}/${name}`,
kind,
size: 0,
mtimeMs: null,
ignored: false,
excluded: false,
hidden: false,
};
}
beforeEach(() => {
mocks.readDir.mockImplementation(async (path: string) =>
tree[path]
? { status: "ok", data: tree[path].map(([n, k]) => entry(path, n, k)) }
: { status: "error", error: { kind: "notFound", message: `${path} not found`, detail: null } },
);
mocks.entryKind.mockImplementation(async (path: string) => {
if (tree[path]) return { status: "ok", data: "dir" };
if (Object.entries(tree).some(([d, es]) => es.some(([n, k]) => k === "file" && `${d}/${n}` === path)))
return { status: "ok", data: "file" };
return { status: "error", error: { kind: "notFound", message: "not found", detail: null } };
});
useRemote.setState({ session: { root: "/srv/app", os: "linux", commands: [] } as never });
render(<InputDialogsHost />);
});
afterEach(() => {
for (const d of screen.queryAllByRole("dialog")) fireEvent.click(within(d).getByRole("button", { name: "Cancel" }));
cleanup();
useRemote.setState({ session: null });
vi.clearAllMocks();
});
const dialog = () => within(screen.getByRole("dialog"));
describe("choosePath in a remote window", () => {
it("browses the remote host instead of opening the desktop's dialog", async () => {
let result!: Promise<string | null>;
act(() => {
result = choosePath({ directory: false, title: "Select Library JAR", defaultPath: "/srv/app" });
});
await waitFor(() => expect(dialog().getByText("runner")).toBeTruthy());
expect(dialog().getByText("pom.xml")).toBeTruthy();
expect(mocks.nativeOpen).not.toHaveBeenCalled();
fireEvent.click(dialog().getByText("runner"), { detail: 2 });
await waitFor(() => expect(dialog().getByText("server.jar")).toBeTruthy());
fireEvent.mouseDown(dialog().getByText("server.jar"));
fireEvent.click(dialog().getByText("server.jar"));
expect((dialog().getByRole("textbox") as HTMLInputElement).value).toBe("/srv/app/runner/server.jar");
fireEvent.click(dialog().getByText("server.jar"), { detail: 2 });
await expect(result).resolves.toBe("/srv/app/runner/server.jar");
});
it("lists only folders when choosing one, goes up, and returns the folder shown", async () => {
let result!: Promise<string | null>;
act(() => {
result = choosePath({ directory: true, title: "Select Folder", defaultPath: "/srv/app" });
});
await waitFor(() => expect(dialog().getByText("runner")).toBeTruthy());
expect(dialog().queryByText("pom.xml")).toBeNull();
fireEvent.click(dialog().getByRole("button", { name: "Parent Folder" }));
await waitFor(() => expect(dialog().getByText("app")).toBeTruthy());
fireEvent.click(dialog().getByRole("button", { name: "OK" }));
await expect(result).resolves.toBe("/srv");
});
it("starts in a file's folder and rejects a missing path", async () => {
let result!: Promise<string | null>;
act(() => {
result = choosePath({ directory: false, title: "Select File", defaultPath: "/srv/app/pom.xml" });
});
await waitFor(() => expect(dialog().getByText("runner")).toBeTruthy());
const field = dialog().getByRole("textbox");
expect((field as HTMLInputElement).value).toBe("/srv/app/pom.xml");
fireEvent.change(field, { target: { value: "/srv/app/missing.jar" } });
fireEvent.click(dialog().getByRole("button", { name: "OK" }));
await waitFor(() => expect(dialog().getByText("No such file or folder")).toBeTruthy());
fireEvent.click(dialog().getByRole("button", { name: "Cancel" }));
await expect(result).resolves.toBeNull();
});
});
describe("parentPath", () => {
it("handles Unix and Windows paths and roots", () => {
expect(parentPath("/srv/app")).toBe("/srv");
expect(parentPath("/srv")).toBe("/");
expect(parentPath("/")).toBeNull();
expect(parentPath("C:\\Users\\me")).toBe("C:\\Users");
expect(parentPath("C:\\Users")).toBe("C:\\");
expect(parentPath("C:\\")).toBeNull();
expect(parentPath("/srv/app/")).toBe("/srv");
});
});