Compare commits

...
Author SHA1 Message Date
l0ng-ai 04880ebb9f fix(remote): use the correct filesystem for file dialogs 2026-11-23 23:20:43 +08:00
39 changed files with 416 additions and 169 deletions

No files matched your search

+3 -2
View File
@@ -52,7 +52,8 @@ import { call, commands, isErrorKind, isTauri } from "@/platform/ipc";
import { openLightweightEditor } from "./openLightweightEditor";
import { windowBackgroundHex } from "@/workbench/theme";
import { hoverActionsAt } from "@/platform/hoverActions";
import { save as saveFileDialog, type DialogFilter as SaveDialogFilter } from "@/platform/dialog";
import { chooseSavePath } from "@/platform/choosePath";
import type { DialogFilter as SaveDialogFilter } from "@/platform/dialog";
import { isUntitledUri, untitledTitle } from "@/platform/virtualDocs";
import { isRemoteWindow } from "@/platform/remote";
import { auxiliaryWindow } from "@/platform/auxWindow";
@@ -1299,7 +1300,7 @@ export class EditorController implements SlotHost {
* every tab showing it becomes a file tab.
*/
private async saveUntitled(model: import("./model/document").DocModel): Promise<boolean> {
const path = await saveFileDialog({
const path = await chooseSavePath({
title: tx("Save As"),
defaultPath: this.saveAsSuggestion(model),
filters: await languageFilters(),
+1
View File
@@ -11,6 +11,7 @@ import { VirtualBanner } from "./view/Banner";
const ipc = vi.hoisted(() => ({ support: vi.fn(), sources: vi.fn(), cancel: vi.fn(), choose: vi.fn() }));
vi.mock("@/platform/ipc", async (original) => ({
...(await original<typeof import("@/platform/ipc")>()),
isTauri: () => true,
commands: { lspCanDownloadSources: ipc.support, lspLibrarySources: ipc.sources, cancelRequest: ipc.cancel },
}));
vi.mock("@tauri-apps/plugin-dialog", () => ({ open: ipc.choose }));
+3 -2
View File
@@ -1,6 +1,7 @@
import { useEffect, useState } from "react";
import { create } from "zustand";
import { registerActions } from "@/platform/actions";
import { choosePath } from "@/platform/choosePath";
import { call, commands, isCancelled, nextRequestId, onIdeEvent, type RequestId } from "@/platform/ipc";
import { tx } from "@/platform/i18n";
import { useProject } from "@/platform/project";
@@ -26,8 +27,8 @@ async function retrieve(path: string, choose: boolean) {
try {
let sources: string | null = null;
if (choose) {
const { open } = await import("@/platform/dialog");
const selected = await open({
const selected = await choosePath({
directory: false,
title: tx("Choose Sources…"),
filters: [{ name: tx("Source archives"), extensions: ["jar", "zip"] }],
});
+1 -1
View File
@@ -679,7 +679,7 @@ function CustomAgentModal({
try {
const trimmed = name.trim();
const title = trimmed ? tx`Select ${trimmed}` : tx("Select executable");
const path = await backend.chooseExecutable(title, command);
const path = await backend.chooseExecutable(title, command, "desktop");
if (path) setCommand(path);
setError(null);
} catch (e) {
+6 -3
View File
@@ -1,5 +1,7 @@
/** Agents of the ACP Registry: listing, install / update / remove (`agent_registry_*`). */
import { open } from "@/platform/dialog";
import { choosePath } from "@/platform/choosePath";
import { readDesktopText } from "@/platform/desktopFiles";
import { Channel } from "@tauri-apps/api/core";
import type {
AcpImportOutcome,
@@ -31,7 +33,7 @@ export interface CommandsBackend {
providers(): Promise<AgentProvider[]>;
set(id: string, command: string | null): Promise<void>;
setEnv(id: string, env: Record<string, string>): Promise<void>;
chooseExecutable(title: string, current?: string): Promise<string | null>;
chooseExecutable(title: string, current?: string, location?: "desktop"): Promise<string | null>;
saveCustom(input: CustomAgentInput): Promise<void>;
removeCustom(id: string): Promise<void>;
importAcp(text: string): Promise<AcpImportOutcome[]>;
@@ -56,7 +58,8 @@ export const tauriCommands: CommandsBackend = {
updateCli: (id, offer, request) => call(commands.agentCliUpdate(id, offer, request)),
cancel: tauriRegistry.cancel,
providers: () => call(commands.agentProviders()),
chooseExecutable: async (title, current) => {
chooseExecutable: async (title, current, location) => {
if (location !== "desktop") return choosePath({ title, defaultPath: current, directory: false });
const picked = await open({ title, defaultPath: current || undefined, directory: false, multiple: false });
return typeof picked === "string" ? picked : null;
},
@@ -81,7 +84,7 @@ export const tauriCommands: CommandsBackend = {
filters: [{ name: tx("ACP config"), extensions: ["json"] }],
});
if (typeof picked !== "string") return null;
return call(commands.fsReadText(picked));
return readDesktopText(picked);
},
};
+2 -5
View File
@@ -4,7 +4,7 @@ import clsx from "clsx";
import { create } from "zustand";
import { executeAction } from "@/platform/actions";
import { tx } from "@/platform/i18n";
import { isTauri } from "@/platform/ipc";
import { choosePath } from "@/platform/choosePath";
import { EDIT_SCOPES_ACTION, useCustomScopeList } from "@/platform/search";
import { Button, IconButton, Input, Radio, Select, T } from "@/ui";
import { SCOPE_LABELS, currentFile, type ScopeChoice, type ScopeKind } from "./scope";
@@ -40,10 +40,7 @@ export function AnalysisDialogHost() {
}
async function browseDirectory(initial: string): Promise<string | null> {
if (!isTauri()) return null;
const { open } = await import("@/platform/dialog");
const picked = await open({ directory: true, multiple: false, defaultPath: initial || undefined });
return typeof picked === "string" ? picked : null;
return choosePath({ directory: true, defaultPath: initial });
}
const KINDS: ScopeKind[] = ["project", "directory", "file", "changed", "custom"];
+5 -13
View File
@@ -10,6 +10,7 @@ import { tx } from "@/platform/i18n";
import { create } from "zustand";
import { Channel } from "@tauri-apps/api/core";
import { executeAction } from "@/platform/actions";
import { choosePath, choosePaths } from "@/platform/choosePath";
import {
call,
commands,
@@ -427,15 +428,12 @@ export function classifyPickedPoms(root: string, picked: readonly string[]): { l
export async function addProjects(dialogTitle?: string) {
const root = useProject.getState().project?.root;
if (!root || useProject.getState().project?.workspace || !isTauri()) return;
const { open } = await import("@/platform/dialog");
const picked = await open({
const paths = await choosePaths({
title: dialogTitle ?? tx`Add Maven Projects`,
directory: false,
multiple: true,
defaultPath: root,
filters: [{ name: "pom.xml", extensions: ["xml"] }],
});
const paths = typeof picked === "string" ? [picked] : (picked ?? []);
if (!paths.length) return;
const { link, rejected } = classifyPickedPoms(root, paths);
if (link.length) await setLinked(root, link, true);
@@ -470,14 +468,11 @@ export async function importModuleFromExistingSources() {
} catch {
/* Tests and hosts without the tool-window service still link the POM. */
}
const { open } = await import("@/platform/dialog");
const picked = await open({
const path = await choosePath({
title: tx`Import Module from Existing Sources`,
directory: true,
multiple: false,
defaultPath: root,
});
const path = typeof picked === "string" ? picked : picked?.[0];
if (!path) return;
const pom = mavenPomForImport(path);
if (!(await directoryListsPom(pom))) {
@@ -532,16 +527,13 @@ export async function linkGradleProjects() {
!isTauri()
)
return;
const { open } = await import("@/platform/dialog");
const picked = await open({
const paths = await choosePaths({
title: tx`Link Gradle Projects`,
directory: false,
multiple: true,
defaultPath: root,
filters: [{ name: "Gradle build files", extensions: ["gradle", "kts"] }],
});
const paths = typeof picked === "string" ? [picked] : picked;
if (!paths?.length || useProject.getState().project?.root !== root || gen !== generation) return;
if (!paths.length || useProject.getState().project?.root !== root || gen !== generation) return;
const model = await call(commands.gradleLinkProjects(paths));
if (useProject.getState().project?.root !== root || gen !== generation) return;
const configs = await call(commands.runConfigs()).catch(() => useBuild.getState().configs);
+2 -4
View File
@@ -5,6 +5,7 @@
*/
import { useMemo, useState } from "react";
import { create } from "zustand";
import { choosePath } from "@/platform/choosePath";
import { call, commands, isTauri } from "@/platform/ipc";
import { basename } from "@/platform/project";
import { Dialog, Icon, List, T } from "@/ui";
@@ -28,9 +29,7 @@ import styles from "./Coverage.module.css";
const errorText = (e: unknown) => (e instanceof Error ? e.message : String(e));
async function pickReport(): Promise<string | null> {
const { open } = await import("@/platform/dialog");
const file = await open({
multiple: false,
return choosePath({
directory: false,
title: "Import Coverage Report",
filters: [
@@ -41,7 +40,6 @@ async function pickReport(): Promise<string | null> {
{ name: "All files", extensions: ["*"] },
],
});
return typeof file === "string" ? file : null;
}
/** Imports `path` (asks for a file without one) and shows it like a run's suite. */
+2 -1
View File
@@ -1,6 +1,7 @@
/** Query History (browse / paste / delete) and Import Data from File dialogs. */
import { useEffect, useMemo, useState } from "react";
import { call, commands, type DbHistoryEntry } from "@/platform/ipc";
import { readDesktopText } from "@/platform/desktopFiles";
import { editorsFor } from "@/editor/api";
import { Checkbox, Dialog, EmptyState, IconButton, Input, List, Select, T } from "@/ui";
import { notifications } from "@/workbench/contributions";
@@ -157,7 +158,7 @@ export function ImportDialog({ id, schema, table }: { id: string; schema: string
filters: [{ name: "CSV / TSV", extensions: ["csv", "tsv", "txt"] }],
});
if (typeof f !== "string") return;
const content = await call(commands.fsReadText(f));
const content = await readDesktopText(f);
setFile(f);
setText(content);
setSep(guessSeparator(content));
+3 -4
View File
@@ -1,4 +1,5 @@
import { useEffect, useState } from "react";
import { choosePaths } from "@/platform/choosePath";
import { call, commands, type DbJdbcDriver } from "@/platform/ipc";
import { useTx } from "@/platform/i18n";
import { Button, Dialog, IconButton, Input, Select, T } from "@/ui";
@@ -85,14 +86,12 @@ export function JdbcDriverProfiles({
setBusy(true);
setError(null);
try {
const { open } = await import("@/platform/dialog");
const files = await open({
const files = await choosePaths({
title: tx("Choose JDBC Driver and Dependency JARs"),
multiple: true,
directory: false,
filters: [{ name: tx("Java archives"), extensions: ["jar"] }],
});
if (files && draft) {
if (files.length && draft) {
const jars = [...new Set([...draft.jars, ...files])];
set({ jars });
const names = await call(commands.dbJdbcDriverClasses(jars));
@@ -16,6 +16,7 @@ vi.mock("@/platform/ipc", async (importOriginal) => {
(...args: unknown[]) => [name, ...args];
return {
...real,
isTauri: () => true,
call: backend.call,
commands: {
...real.commands,
+2 -3
View File
@@ -21,6 +21,7 @@ import {
type DbTxMode,
} from "@/platform/ipc";
import { executeAction } from "@/platform/actions";
import { choosePath } from "@/platform/choosePath";
import { tx, txPart, useTx, useTxTemplate } from "@/platform/i18n";
import { useProject } from "@/platform/project";
import { sshLabel as configLabel } from "@/platform/remoteSettings";
@@ -259,9 +260,7 @@ function blank(): DataSource {
}
async function pickFile(title: string): Promise<string | null> {
const { open } = await import("@/platform/dialog");
const file = await open({ multiple: false, directory: false, title });
return typeof file === "string" ? file : null;
return choosePath({ directory: false, title });
}
/** A path field with Browse…. */
+2 -1
View File
@@ -6,6 +6,7 @@
import { introspectSource } from "./introspection";
import { writeClipboardText } from "@/platform/clipboard";
import { call, commands, type DataSource, type DbDriver, type DbTableInfo } from "@/platform/ipc";
import { readDesktopText } from "@/platform/desktopFiles";
import { registerActions, type Action } from "@/platform/actions";
import { editorService, notifications, showServiceView, toolWindowService } from "@/workbench/contributions";
import { splitTarget } from "./model";
@@ -200,7 +201,7 @@ async function runScriptFile(id: string) {
});
if (typeof file !== "string") return;
try {
const text = await call(commands.fsReadText(file));
const text = await readDesktopText(file);
const statements = await call(commands.dbStatements(id, text, 0, text.length));
useDatabase.setState({ activeResult: OUTPUT_TAB });
showServiceView(RESULTS_VIEW, false);
+2 -2
View File
@@ -1,4 +1,5 @@
/** Menus of the Database tool window, laid out like IDEA's (New ▸, Copy/Paste ▸, SQL Scripts ▸ …). */
import { choosePath } from "@/platform/choosePath";
import type { MenuItem } from "@/ui";
import { notifications } from "@/workbench/contributions";
import { fileSourceName, parseSourceUrl } from "./model";
@@ -32,8 +33,7 @@ const act = (
const sep: MenuItem = { kind: "separator" };
async function sqliteFromFile() {
const { open } = await import("@/platform/dialog");
const file = await open({ multiple: false, directory: false, title: "SQLite Database File" });
const file = await choosePath({ directory: false, title: "SQLite Database File" });
if (typeof file === "string") openSourceDialog(null, { driver: "sqlite", file, name: fileSourceName(file) });
}
+4 -1
View File
@@ -19,7 +19,9 @@ vi.mock("@/ui", () => ({ copyText: vi.fn() }));
vi.mock("@/workbench/inputDialogs", () => ({ promptInput: vi.fn() }));
vi.mock("@/workbench/messages", () => ({ confirm: vi.fn() }));
vi.mock("@/platform/dialog", () => ({ open: (...args: unknown[]) => ipc.openDialog(...args) }));
vi.mock("@/platform/project", () => ({ useProject: { getState: () => ({ project: { root: "/project" } }) } }));
vi.mock("@/platform/project", () => ({
useProject: { getState: () => ({ project: { root: "/project" } }), subscribe: vi.fn() },
}));
vi.mock("@/workbench/contributions", () => ({
notifications: () => ({ notify: ipc.notify }),
projectViewSelection: () => ipc.selection(),
@@ -27,6 +29,7 @@ vi.mock("@/workbench/contributions", () => ({
}));
vi.mock("@/platform/ipc", async (original) => ({
...(await original<typeof import("@/platform/ipc")>()),
isTauri: () => true,
commands: {
deployServerRoot: ipc.root,
remoteList: ipc.list,
+2 -3
View File
@@ -1,5 +1,6 @@
/** Remote Host tool window operations: list, open, create, rename, delete and download remote files. */
import { tx, txTemplate } from "@/platform/i18n";
import { choosePath } from "@/platform/choosePath";
import { call, commands, type RemoteEntry } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { deploymentConnection, deploymentSecretKey, type DeploymentServerValid } from "@/platform/remoteSettings";
@@ -183,10 +184,8 @@ export async function downloadToProject(server: DeploymentServerValid, entries:
* the project root, preselected), without the server path above them. */
export async function downloadTo(server: DeploymentServerValid, entries: RemoteEntry[]) {
if (!entries.length) return;
const { open } = await import("@/platform/dialog");
const target = await open({
const target = await choosePath({
directory: true,
multiple: false,
title: tx("Download to"),
defaultPath: (await defaultDownloadFolder()) ?? undefined,
});
@@ -7,6 +7,7 @@ import { handleRuntimeEvent } from "../runtimeUi";
const nativeOpen = vi.hoisted(() => vi.fn());
vi.mock("@tauri-apps/plugin-dialog", () => ({ open: nativeOpen }));
vi.mock("@/platform/ipc", async (original) => ({ ...(await original<object>()), isTauri: () => true }));
const answerPrompt = vi.fn().mockResolvedValue(undefined);
let notes: Parameters<NotificationService["notify"]>[0][];
let dispose: (() => void) | undefined;
+2 -5
View File
@@ -40,6 +40,7 @@ import type {
WorkbenchEvent,
} from "@/bindings";
import { toBase64 } from "@/platform/base64";
import { choosePath } from "@/platform/choosePath";
import { tx } from "@/platform/i18n";
import { useRemote } from "@/platform/remote";
import { call, commands, IpcError, isCancelled, isTauri, nextRequestId } from "@/platform/ipc";
@@ -222,11 +223,7 @@ export const tauriPluginsBackend: PluginsBackend = {
return chosen;
},
program: (id, program, scope) => call(commands.pluginProgram(id, program, scope)),
pickProgram: async () => {
const { open } = await import("@/platform/dialog");
const picked = await open({ directory: false, multiple: false, title: tx("Choose plugin executable") });
return (Array.isArray(picked) ? picked[0] : picked) ?? null;
},
pickProgram: () => choosePath({ directory: false, title: tx("Choose plugin executable") }),
setCapability: (id, capability, granted) => call(commands.pluginSetCapability(id, capability, granted)),
revokeNetHost: (id, host) => call(commands.pluginRevokeNetHost(id, host)),
assets: (pluginId, prefix) => call(commands.pluginAssets(pluginId, prefix)),
+5 -9
View File
@@ -5,6 +5,7 @@
* batches.
*/
import { readClipboardPlainText, readClipboardPng, writeClipboardText } from "@/platform/clipboard";
import { choosePath } from "@/platform/choosePath";
import { providePluginTestParser, providePluginTestSelector } from "@/workbench/contributions";
import {
contentTabData,
@@ -512,16 +513,11 @@ async function askUser(prompt: Prompt, signal: AbortSignal): Promise<string[] |
case "pickDirectory": {
if (signal.aborted) return null;
try {
const { open } = await import("@/platform/dialog");
const path = await choosePath(
{ directory: true, title: prompt.title, defaultPath: prompt.initial ?? undefined },
signal,
);
if (signal.aborted) return null;
const selected = await open({
directory: true,
multiple: false,
title: prompt.title,
defaultPath: prompt.initial ?? undefined,
});
if (signal.aborted) return null;
const path = Array.isArray(selected) ? selected[0] : selected;
return path ? [ipcPath(path)] : null;
} catch (error) {
if (!signal.aborted)
@@ -1,6 +1,8 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { commands } from "@/platform/ipc";
import { registerHostPathChooser } from "@/platform/choosePath";
import { useRemote } from "@/platform/remote";
import { ExportTestResultsDialog, defaultExportName, loadExportOptions } from "./ExportTestResultsDialog";
import { TestResults } from "./testing";
@@ -15,6 +17,7 @@ const messages = vi.hoisted(() => ({ confirm: vi.fn(async () => true) }));
vi.mock("@/workbench/messages", async (orig) => ({ ...(await orig<object>()), confirm: messages.confirm }));
const dialog = vi.hoisted(() => ({ save: vi.fn(async (): Promise<string | null> => null) }));
vi.mock("@/platform/dialog", () => dialog);
vi.mock("@/platform/ipc", async (orig) => ({ ...(await orig<object>()), isTauri: () => true }));
const ok = { status: "ok", data: null } as const;
let onDisk: Record<string, "file" | "dir"> = {};
@@ -39,7 +42,10 @@ beforeEach(() => {
return ok;
});
});
afterEach(() => vi.restoreAllMocks());
afterEach(() => {
useRemote.setState({ session: null });
vi.restoreAllMocks();
});
function results() {
const r = new TestResults();
@@ -164,6 +170,59 @@ describe("ExportTestResultsDialog", () => {
expect(written.map((w) => w.path)).toEqual([path]);
});
it.each(["html", "xml"] as const)(
"browses the remote folder for a %s report and confirms replacement",
async (format) => {
useRemote.setState({ session: { root: "/work/app", os: "linux" } as never });
const choose = vi.fn(async () => ["/srv/reports"]);
const unregister = registerHostPathChooser(choose);
try {
const onClose = open();
if (format === "xml") fireEvent.click(screen.getByRole("radio", { name: "XML" }));
const name = `Test Results - go test _calc.${format}`;
const path = `/srv/reports/${name}`;
onDisk[path] = "file";
press("Browse…");
await waitFor(() => expect(folder()).toHaveValue("/srv/reports"));
expect(choose).toHaveBeenCalledWith(expect.objectContaining({ directory: true, defaultPath: "/work/app/" }));
expect(dialog.save).not.toHaveBeenCalled();
expect(file()).toHaveValue(name);
messages.confirm.mockResolvedValueOnce(false);
press("OK");
await waitFor(() => expect(messages.confirm).toHaveBeenCalledOnce());
await waitFor(() => expect(screen.getByRole("button", { name: "OK" })).toBeEnabled());
expect(commands.fsDelete).not.toHaveBeenCalled();
expect(written).toHaveLength(0);
press("OK");
await waitFor(() => expect(onClose).toHaveBeenCalled());
expect(written.map((w) => w.path)).toEqual([path]);
} finally {
unregister();
}
},
);
it("moves an absolute report path to the browsed remote folder", async () => {
useRemote.setState({ session: { root: "/work/app", os: "linux" } as never });
const choose = vi.fn(async () => ["/srv/reports"]);
const unregister = registerHostPathChooser(choose);
try {
const onClose = open();
fireEvent.change(file(), { target: { value: "/tmp/custom.html" } });
press("Browse…");
await waitFor(() => expect(file()).toHaveValue("custom.html"));
expect(choose).toHaveBeenCalledWith(expect.objectContaining({ defaultPath: "/tmp/" }));
fireEvent.click(screen.getByRole("checkbox", { name: "Open exported file in browser" }));
press("OK");
await waitFor(() => expect(onClose).toHaveBeenCalled());
expect(written.map((w) => w.path)).toEqual(["/srv/reports/custom.html"]);
} finally {
unregister();
}
});
it("confirms again when the destination changes after using the save dialog", async () => {
dialog.save.mockResolvedValueOnce("/tmp/picked.html");
onDisk["/work/app/reports/picked.html"] = "file";
@@ -5,8 +5,10 @@
import { useId, useState } from "react";
import { executeAction } from "@/platform/actions";
import { toBase64 } from "@/platform/base64";
import { choosePath } from "@/platform/choosePath";
import { tx } from "@/platform/i18n";
import { call, commands } from "@/platform/ipc";
import { isRemoteWindow } from "@/platform/remote";
import { Checkbox, Dialog, IconButton, Input, Radio, T } from "@/ui";
import { notifications } from "@/workbench/contributions";
import { confirm } from "@/workbench/messages";
@@ -159,6 +161,21 @@ export function ExportTestResultsDialog({
const browse = async () => {
try {
if (isRemoteWindow()) {
const current = isAbsolutePath(fileName.trim()) ? destinationFromPicker(fileName.trim()) : destination;
const initial = current.folder.trim();
const chosen = await choosePath({
directory: true,
title: "Choose Directory…",
defaultPath: !initial
? cwd
: isAbsolutePath(initial)
? initial
: resolveDestination({ folder: cwd, fileName: initial }, cwd),
});
if (chosen) setDestination({ folder: chosen, fileName: current.fileName });
return;
}
const { save } = await import("@/platform/dialog");
const chosen = await save({
defaultPath: target || folder || cwd,
+3 -10
View File
@@ -12,10 +12,11 @@ import {
import clsx from "clsx";
import { openEditorPaths, useEditorRegistry } from "@/editor/api";
import { executeAction } from "@/platform/actions";
import { choosePath } from "@/platform/choosePath";
import { setContext } from "@/platform/context";
import { t, useTxTemplate, tx, txPart } from "@/platform/i18n";
import { formatBinding, hostBinding, registerKeyClaim, shortcutLabel } from "@/platform/keymap";
import { call, commands, isTauri, onIdeEvent } from "@/platform/ipc";
import { call, commands, onIdeEvent } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { useProjectModules } from "@/platform/projectRoots";
import { EDIT_SCOPES_ACTION, useCustomScopeList } from "@/platform/search";
@@ -98,15 +99,7 @@ import styles from "./FindInFiles.module.css";
/** The Directory scope's browse button: a folder chooser opened at the current directory. */
async function chooseDirectory(current: string): Promise<string | null> {
if (!isTauri()) return null;
const { open } = await import("@/platform/dialog");
const picked = await open({
directory: true,
multiple: false,
title: tx("Select Search Directory"),
defaultPath: current || undefined,
});
return (Array.isArray(picked) ? picked[0] : picked) ?? null;
return choosePath({ directory: true, title: tx("Select Search Directory"), defaultPath: current });
}
const POPUP_MAX_MATCHES = 2000;
+3 -6
View File
@@ -9,9 +9,8 @@
import { useMemo, useRef, useState, type MouseEvent } from "react";
import clsx from "clsx";
import { allActions, useActions, type Action } from "@/platform/actions";
import { toBase64 } from "@/platform/base64";
import { defaultPreset, formatBinding, type Keymap, PRESET_TITLES, PRESETS } from "@/platform/keymap";
import { call, commands } from "@/platform/ipc";
import { readDesktopText, writeDesktopText } from "@/platform/desktopFiles";
import { notifications } from "@/workbench/contributions";
import { ask, confirm, showError } from "@/workbench/messages";
import {
@@ -258,7 +257,7 @@ export function KeymapPage() {
if (!path) return;
let parsed;
try {
parsed = parseIdeaKeymap(await call(commands.fsReadText(path)));
parsed = parseIdeaKeymap(await readDesktopText(path));
} catch (e) {
await showError(tx("Import Keymap"), e instanceof Error ? e.message : String(e));
return;
@@ -299,9 +298,7 @@ export function KeymapPage() {
draft,
);
try {
// The save dialog already confirmed replacing an existing file.
await call(commands.fsDelete(path)).catch(() => {});
await call(commands.fsCreateFileBytes(path, toBase64(new TextEncoder().encode(json))));
await writeDesktopText(path, json);
notifications().notify({
level: "info",
title: tx("Keymap exported"),
@@ -46,8 +46,7 @@ import { Row, Select } from "../../components/Form";
import { useSetting } from "../../components/context";
import styles from "./Editor.module.css";
import { executeAction, registerActions } from "@/platform/actions";
import { toBase64 } from "@/platform/base64";
import { call, commands } from "@/platform/ipc";
import { readDesktopText, writeDesktopText } from "@/platform/desktopFiles";
import { ask, confirm, showError } from "@/workbench/messages";
import { useContributions } from "@/workbench/contributions";
import { parseIcls, SchemeParseError, importScheme, deleteScheme, exportIcls } from "@/platform/icls";
@@ -1728,7 +1727,7 @@ export function ColorSchemePage({
.split(/[\\/]/)
.at(-1)
?.replace(/\.[^.]+$/, "") || "Imported scheme";
const parsed = parseIcls(await call(commands.fsReadText(path)), fallbackName);
const parsed = parseIcls(await readDesktopText(path), fallbackName);
let overwrite = false;
if (schemes.some((s) => s.name === parsed.scheme.name)) {
const canOverwrite = Object.values(customs).some((s) => s.name === parsed.scheme.name);
@@ -1759,10 +1758,7 @@ export function ColorSchemePage({
filters: [{ name: tx("IntelliJ Color Scheme"), extensions: ["icls"] }],
}));
if (!path) return;
const bytes = toBase64(new TextEncoder().encode(exportIcls(id, customs, mine)));
// The save dialog already confirmed replacing an existing file.
await call(commands.fsDelete(path)).catch(() => {});
await call(commands.fsCreateFileBytes(path, bytes));
await writeDesktopText(path, exportIcls(id, customs, mine));
setReport(tx("Scheme exported."));
},
delete: async () => {
@@ -10,6 +10,7 @@
import { useId, useState } from "react";
import { Button, Checkbox, Input, type SelectOption, T } from "@/ui";
import { commands, isTauri, type LanguageInfo_Serialize as LanguageInfo } from "@/platform/ipc";
import { choosePath } from "@/platform/choosePath";
import { ENCODING_CHOICES, lineCommentDefaults, type LanguageCodeStyle } from "@/platform/editorSettings";
import { NATIVE_TO_ASCII_ACTION } from "../../nativeToAscii";
import { FormGroup, NumberInput, Row, Select, Toggle } from "../../components/Form";
@@ -300,9 +301,8 @@ function JavaFormatter({
}) {
const id = useId();
const browse = async () => {
const { open } = await import("@/platform/dialog");
const path = await open({
multiple: false,
const path = await choosePath({
directory: false,
title: tx("Eclipse formatter XML"),
filters: [{ name: "XML", extensions: ["xml"] }],
});
+2 -3
View File
@@ -8,6 +8,7 @@ import { FontPicker } from "../components/FontPicker";
import { useEffect, useId, useRef, useState, type ReactNode } from "react";
import clsx from "clsx";
import { quotePath } from "@/platform/commandLine";
import { choosePath } from "@/platform/choosePath";
import { commands, isTauri } from "@/platform/ipc";
import {
DEFAULT_EXTERNAL_TOOL,
@@ -137,9 +138,7 @@ function ShellPathRow() {
void commands.termAvailableShells().then(setShells, () => undefined);
}, []);
const browse = async () => {
const { open: pick } = await import("@/platform/dialog");
const picked = await pick({ multiple: false, title: "Shell Path" });
const path = Array.isArray(picked) ? picked[0] : picked;
const path = await choosePath({ directory: false, title: "Shell Path" });
if (path) set(quotePath(path));
};
return (
+2 -5
View File
@@ -5,6 +5,7 @@
import { Channel } from "@tauri-apps/api/core";
import type { InstallEvent, RequestId, ToolInfo, ToolUpdate } from "@/bindings";
import { call, commands, IpcError, isTauri } from "@/platform/ipc";
import { choosePath } from "@/platform/choosePath";
export interface LanguageChoice {
id: string;
@@ -43,11 +44,7 @@ export const tauriToolsBackend: ToolsBackend = {
restartServers: async (name) => {
await call(commands.lspRestartNamed(name));
},
chooseExecutable: async (title, defaultPath) => {
const { open } = await import("@/platform/dialog");
const picked = await open({ directory: false, multiple: false, title, defaultPath: defaultPath || undefined });
return (Array.isArray(picked) ? picked[0] : picked) ?? null;
},
chooseExecutable: (title, defaultPath) => choosePath({ directory: false, title, defaultPath }),
languages: async () =>
(await commands.languages())
.map((l) => ({ id: l.id, name: l.name, extensions: l.extensions, filenames: l.filenames }))
+3 -6
View File
@@ -2,7 +2,7 @@ import { useEffect, useMemo, useRef, useState } from "react";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import type { Commit } from "@/bindings";
import { call, commands, isTauri } from "@/platform/ipc";
import { call, commands } from "@/platform/ipc";
import { tx } from "@/platform/i18n";
import { notifications, type EditorInput } from "@/workbench/contributions";
import {
@@ -26,15 +26,12 @@ import { currentRepoRoot } from "./store";
import { repositoryPath } from "./repositoryPaths";
import { firstLineOf, languageFor, viewerBase } from "./cm";
import styles from "./GitLog.module.css";
import { choosePath } from "@/platform/choosePath";
import { choosePaths } from "@/platform/choosePath";
import { openLogTab } from "./logStore";
import { openRevisionFile, type RevisionData } from "./revisionInput";
export async function openExternalLog() {
const picked = isTauri()
? await (await import("@/platform/dialog")).open({ title: tx("Open Git Log"), directory: true, multiple: true })
: await choosePath({ title: "Open Git Log", directory: true });
const paths = Array.isArray(picked) ? picked : picked ? [picked] : [];
const paths = await choosePaths({ title: tx("Open Git Log"), directory: true });
if (!paths.length) return;
try {
const roots = await Promise.all(paths.map((path) => call(commands.vcsOpenExternalLog(path))));
+5 -4
View File
@@ -2,7 +2,7 @@
import { useEffect, useRef, useState } from "react";
import { Channel } from "@tauri-apps/api/core";
import { tx } from "@/platform/i18n";
import { call, commands, isCancelled, isTauri, nextRequestId } from "@/platform/ipc";
import { callDesktop, commands, isCancelled, isTauri, nextRequestId } from "@/platform/ipc";
import { openProject } from "@/platform/project";
import { Checkbox, Dialog, Icon, IconButton, Input, ProgressBar, Select, T, showContextMenu } from "@/ui";
import { cloneSourceList, notifications, useCloneSources } from "@/workbench/contributions";
@@ -183,8 +183,9 @@ function CloneDialog({ onClose, initialUrl }: { onClose: () => void; initialUrl:
};
const cancel = () => {
if (request.current !== null) void commands.cancelRequest(request.current);
else onClose();
const id = request.current;
if (id === null) onClose();
else void callDesktop("cancel_request", { id });
};
const clone = async (picked?: string) => {
@@ -201,7 +202,7 @@ function CloneDialog({ onClose, initialUrl }: { onClose: () => void; initialUrl:
if (text) setProgress({ line: text, fraction: progressFraction(text) });
};
try {
await call(commands.vcsClone(id, cloneUrl.trim(), target, depth, channel));
await callDesktop("vcs_clone", { request: id, url: cloneUrl.trim(), dest: target, depth, onOutput: channel });
writeParent(parentOf(target));
rememberUrl(cloneUrl.trim());
onClose();
+4 -6
View File
@@ -4,6 +4,7 @@
*/
import { activeEditor } from "@/editor/api";
import { registerActions } from "@/platform/actions";
import { choosePath } from "@/platform/choosePath";
import { call, commands, isTauri } from "@/platform/ipc";
import { isRemoteWindow } from "@/platform/remote";
import { maybeEditorService, notifications, projectViewSelection } from "@/workbench/contributions";
@@ -97,16 +98,13 @@ function info(title: string) {
}
async function pickFile(near: string): Promise<string | null> {
if (!isTauri()) return null;
const { open } = await import("@/platform/dialog");
const dir = near.slice(0, near.lastIndexOf("/")) || undefined;
const picked = await open({ multiple: false, directory: false, title: "Compare With", defaultPath: dir });
return (Array.isArray(picked) ? picked[0] : picked) ?? null;
return choosePath({ directory: false, title: tx("Compare With"), defaultPath: dir });
}
/**
* The file to compare `path` against: the OS file dialog on the desktop; a
* browser file picker's contents elsewhere (remote development / `pnpm dev`),
* The file to compare `path` against: a project-host path in the app; a
* browser file picker's contents in the browser build,
* compared as text since no absolute path is available to the backend.
*/
async function pickComparison(
+2 -2
View File
@@ -1,5 +1,5 @@
/** VCS › Create Git Repository…: `git init` in a folder chosen under the project. */
import { open } from "@/platform/dialog";
import { choosePath } from "@/platform/choosePath";
import { tx } from "@/platform/i18n";
import { call, commands } from "@/platform/ipc";
import { useProject } from "@/platform/project";
@@ -8,7 +8,7 @@ import { discoverRoots } from "./store";
export async function createRepository() {
const root = useProject.getState().project?.root;
const dir = await open({ title: tx("Select Directory for Git Init"), directory: true, defaultPath: root });
const dir = await choosePath({ title: tx("Select Directory for Git Init"), directory: true, defaultPath: root });
if (typeof dir !== "string") return;
try {
await call(commands.vcsInit(dir));
+3 -7
View File
@@ -35,7 +35,7 @@ import {
} from "@/ui";
import { executeAction } from "@/platform/actions";
import { bindingsFor, normalizeBinding, registerKeyClaim, shortcutLabel } from "@/platform/keymap";
import { choosePath } from "@/platform/choosePath";
import { choosePath, chooseSavePath } from "@/platform/choosePath";
import { workflowSettings } from "@/platform/workflowSettings";
import { notifications } from "@/workbench/contributions";
import { ask } from "@/workbench/messages";
@@ -165,8 +165,7 @@ export function showCreatePatchForShelf(entry: ShelvedChangeList, path?: string)
async function browseSave(current: string): Promise<string | null> {
try {
const { save } = await import("@/platform/dialog");
return (await save({ defaultPath: current, filters: [{ name: "Patch", extensions: ["patch", "diff"] }] })) ?? null;
return await chooseSavePath({ defaultPath: current, filters: [{ name: "Patch", extensions: ["patch", "diff"] }] });
} catch {
return null;
}
@@ -414,14 +413,11 @@ export async function showApplyPatch(from: "file" | "clipboard", path?: string)
} else {
let file = path ?? null;
if (!file) {
const { open } = await import("@/platform/dialog");
const picked = await open({
multiple: false,
file = await choosePath({
directory: false,
defaultPath: useVcs.getState().root ?? undefined,
filters: [{ name: "Patch", extensions: ["patch", "diff"] }],
});
file = typeof picked === "string" ? picked : null;
}
if (!file) return;
sourcePath = file;
+3 -6
View File
@@ -4,6 +4,7 @@
* merge UI), rename and delete.
*/
import { writeClipboardText } from "@/platform/clipboard";
import { choosePaths } from "@/platform/choosePath";
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type MouseEvent } from "react";
import clsx from "clsx";
import { create } from "zustand";
@@ -581,12 +582,8 @@ export async function showShelfDiff(arg?: unknown, local = false, newTab = false
export async function importShelfPatches(paths?: string[]) {
const repo = currentRepo();
const picked =
paths ??
(await import("@/platform/dialog").then(({ open }) =>
open({ multiple: true, directory: false, filters: [{ name: "Patch", extensions: ["patch", "diff"] }] }),
));
if (!picked) return;
for (const path of typeof picked === "string" ? [picked] : picked) {
paths ?? (await choosePaths({ directory: false, filters: [{ name: "Patch", extensions: ["patch", "diff"] }] }));
for (const path of picked) {
await runOp(
tx("Import patches"),
async () => call(commands.vcsShelfImport(repo, baseName(path), await call(commands.fsReadText(path)))),
+31 -11
View File
@@ -1,13 +1,21 @@
import { isTauri } from "@/platform/ipc";
import { isRemoteWindow } from "@/platform/remote";
import type { DialogFilter, SaveDialogOptions } from "@/platform/dialog";
export interface ChoosePathOptions {
directory: boolean;
title: string;
title?: string;
defaultPath?: string;
filters?: DialogFilter[];
}
type HostChooser = (opts: ChoosePathOptions) => Promise<string | null>;
export interface HostPathOptions extends ChoosePathOptions {
multiple?: boolean;
save?: boolean;
signal?: AbortSignal;
}
type HostChooser = (opts: HostPathOptions) => Promise<string[] | null>;
let hostChooser: HostChooser | null = null;
/**
@@ -25,16 +33,28 @@ export function registerHostPathChooser(chooser: HostChooser): () => void {
* 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);
export async function choosePath(opts: ChoosePathOptions, signal?: AbortSignal): Promise<string | null> {
if (!isTauri() || signal?.aborted) return null;
if (isRemoteWindow()) return (await hostChooser?.({ ...opts, signal }))?.[0] ?? null;
// Lazy on purpose: loading platform/dialog starts its GTK capability probe at module load.
const { open } = await import("@/platform/dialog");
const picked = await open({
directory: opts.directory,
multiple: false,
title: opts.title,
defaultPath: opts.defaultPath || undefined,
});
if (signal?.aborted) return null;
const picked = await open({ ...opts, multiple: false, defaultPath: opts.defaultPath || undefined });
return (Array.isArray(picked) ? picked[0] : picked) ?? null;
}
/** Pick multiple existing paths on the project host. */
export async function choosePaths(opts: ChoosePathOptions): Promise<string[]> {
if (!isTauri()) return [];
if (isRemoteWindow()) return (await hostChooser?.({ ...opts, multiple: true })) ?? [];
const { open } = await import("@/platform/dialog");
const picked = await open({ ...opts, multiple: true });
return typeof picked === "string" ? [picked] : (picked ?? []);
}
/** Choose a destination on the project host and confirm replacement if it exists. */
export async function chooseSavePath(opts: SaveDialogOptions): Promise<string | null> {
if (isRemoteWindow()) return (await hostChooser?.({ ...opts, directory: false, save: true }))?.[0] ?? null;
const { save } = await import("@/platform/dialog");
return save(opts);
}
+40
View File
@@ -0,0 +1,40 @@
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { readDesktopText, writeDesktopText } from "./desktopFiles";
import { useRemote } from "./remote";
import { setInvokeRoute } from "./tauriCore";
const invoke = vi.fn();
const remoteInvoke = vi.fn();
beforeEach(() => {
vi.clearAllMocks();
vi.stubGlobal("__TAURI_INTERNALS__", { invoke });
useRemote.setState({ session: { root: "/srv/project", os: "linux" } as never });
setInvokeRoute(remoteInvoke);
});
afterEach(() => {
setInvokeRoute(null);
useRemote.setState({ session: null });
vi.unstubAllGlobals();
});
it("reads desktop settings or import files even when project IPC is remote", async () => {
const path = "C:\\Users\\me\\settings.xml";
invoke.mockResolvedValueOnce("<settings />");
await expect(readDesktopText(path)).resolves.toBe("<settings />");
expect(invoke.mock.calls[0]?.slice(0, 2)).toEqual(["fs_read_text", { path }]);
expect(remoteInvoke).not.toHaveBeenCalled();
});
it("checks and replaces an existing desktop file on the desktop", async () => {
const path = "C:\\Users\\me\\scheme.icls";
invoke.mockResolvedValueOnce("file").mockResolvedValueOnce(null).mockResolvedValueOnce(null);
await writeDesktopText(path, "é");
expect(invoke.mock.calls.map((args) => args.slice(0, 2))).toEqual([
["fs_entry_kind", { path }],
["fs_delete", { path }],
["fs_create_file_bytes", { path, data: "w6k=" }],
]);
expect(remoteInvoke).not.toHaveBeenCalled();
});
+24
View File
@@ -0,0 +1,24 @@
import { toBase64 } from "./base64";
import { call, callDesktop, commands, isErrorKind } from "./ipc";
import { isRemoteWindow } from "./remote";
/** Text selected in the desktop's file dialog, including in a remote window. */
export function readDesktopText(path: string): Promise<string> {
return isRemoteWindow() ? callDesktop<string>("fs_read_text", { path }) : call(commands.fsReadText(path));
}
/** Write UTF-8 to a path already confirmed in the desktop's save dialog. */
export async function writeDesktopText(path: string, text: string): Promise<void> {
const data = toBase64(new TextEncoder().encode(text));
if (!isRemoteWindow()) {
await call(commands.fsDelete(path)).catch(() => {});
await call(commands.fsCreateFileBytes(path, data));
return;
}
const kind = await callDesktop<string>("fs_entry_kind", { path }).catch((e: unknown) => {
if (!isErrorKind(e, "notFound")) throw e;
return null;
});
if (kind === "file") await callDesktop("fs_delete", { path });
await callDesktop("fs_create_file_bytes", { path, data });
}
+12
View File
@@ -9,6 +9,8 @@ import type { UnlistenFn } from "@tauri-apps/api/event";
import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow";
import { commands, type IdeError, type IdeEvent, type RequestId } from "@/bindings";
import { notifyEach } from "./listeners";
import { invokeLocal } from "./tauriCore";
import type { InvokeArgs } from "@tauri-apps/api/core";
export { commands };
export type * from "@/bindings";
@@ -43,6 +45,16 @@ export async function call<T>(result: Promise<Result<T>>): Promise<T> {
return r.data;
}
/** Run a command in the desktop process when its path came from that machine. */
export async function callDesktop<T>(command: string, args: InvokeArgs): Promise<T> {
try {
return await invokeLocal<T>(command, args);
} catch (e) {
if (e && typeof e === "object" && "kind" in e && "message" in e) throw new IpcError(e as IdeError);
throw e;
}
}
export function isCancelled(e: unknown): boolean {
return e instanceof IpcError && e.kind === "cancelled";
}
+86 -31
View File
@@ -9,11 +9,13 @@
*/
import { useEffect, useRef, useState, type ReactNode } from "react";
import { create } from "zustand";
import { registerHostPathChooser, type ChoosePathOptions } from "@/platform/choosePath";
import { registerHostPathChooser, type HostPathOptions } from "@/platform/choosePath";
import { t, tx, VerbatimTextContext } from "@/platform/i18n";
import { call, commands, type FileEntry } from "@/platform/ipc";
import { call, commands, isErrorKind, type FileEntry } from "@/platform/ipc";
import { ipcPath } from "@/platform/paths";
import { useProject } from "@/platform/project";
import { Checkbox, Dialog, Given, Icon, IconButton, Input, List, T } from "@/ui";
import { confirm } from "./messages";
import styles from "./inputDialogs.module.css";
export interface PromptInputOptions {
@@ -63,7 +65,7 @@ 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: "path"; id: number; options: ChoosePathOptions; resolve: (v: string | null) => void };
| { kind: "path"; id: number; options: HostPathOptions; resolve: (v: string[] | null) => void };
const useInputDialogs = create<{ stack: Request[] }>(() => ({ stack: [] }));
let seq = 0;
@@ -102,8 +104,8 @@ export function pickItems(options: PickItemsOptions): Promise<string[] | null> {
}
/** 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 }));
function choosePathOnHost(options: HostPathOptions): Promise<string[] | null> {
return open<string[]>((id, resolve) => ({ kind: "path", id, options, resolve }), options.signal);
}
registerHostPathChooser(choosePathOnHost);
@@ -351,8 +353,10 @@ function PickDialog({ options, done }: { options: PickItemsOptions; done: (v: st
/** 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("\\"));
const posix = path.startsWith("/") && !path.startsWith("//");
const trimmed = path.replace(posix ? /\/+$/ : /[\\/]+$/, "");
const slash = trimmed.lastIndexOf("/");
const cut = posix ? slash : Math.max(slash, trimmed.lastIndexOf("\\"));
if (cut < 0) return null;
const parent = trimmed.slice(0, cut);
// `/a` → `/`; `C:\a` → `C:\`.
@@ -360,30 +364,44 @@ export function parentPath(path: string): string | null {
return parent === trimmed ? null : parent;
}
function PathDialog({ options, done }: { options: ChoosePathOptions; done: (v: string | null) => void }) {
function PathDialog({ options, done }: { options: HostPathOptions; done: (v: string[] | null) => void }) {
const root = useProject((s) => s.project?.root ?? null);
const title =
options.title ?? (options.save ? tx("Save As") : options.directory ? tx("Choose Directory…") : tx("Choose File…"));
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 [selected, setSelected] = useState<string[]>([]);
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
const [submitting, setSubmitting] = useState(false);
const request = useRef(0);
const inDir = (dir: string, name: string) => `${ipcPath(dir).replace(/\/$/, "")}/${name}`;
const isAbsolute = (path: string) => /^(?:\/|[A-Za-z]:\/)/.test(ipcPath(path));
const isDir = (e: FileEntry) => e.kind === "dir" || (e.kind === "symlink" && e.targetKind === "dir");
const visit = async (path: string) => {
const nameOf = (path: string) => ipcPath(path).split("/").at(-1) ?? "";
const accepts = (entry: FileEntry) =>
isDir(entry) ||
(!options.directory &&
(!options.filters?.length ||
options.filters.some(({ extensions }) =>
extensions.some((ext) => ext === "*" || entry.name.toLowerCase().endsWith(`.${ext.toLowerCase()}`)),
)));
const visit = async (path: string, filename = "") => {
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))
.filter(accepts)
.sort((a, b) => Number(isDir(b)) - Number(isDir(a)) || a.name.localeCompare(b.name));
setDir(path);
setEntries(shown);
setActive(-1);
setValue(path);
setValue(filename ? inDir(path, filename) : path);
setError(null);
return true;
} catch (e) {
@@ -395,7 +413,12 @@ function PathDialog({ options, done }: { options: ChoosePathOptions; done: (v: s
};
useEffect(() => {
const start = options.defaultPath || root || "/";
const initial = options.defaultPath || root || "/";
const start = root && !isAbsolute(initial) ? inDir(root, initial) : initial;
if (options.save) {
void visit(parentPath(start) ?? root ?? "/", nameOf(start));
return;
}
// A file path starts in its folder, with the file in the field.
void visit(start).then((ok) => {
const parent = parentPath(start);
@@ -404,23 +427,42 @@ function PathDialog({ options, done }: { options: ChoosePathOptions; done: (v: s
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const move = (path: string) => visit(path, options.save && value !== dir ? nameOf(value) : "");
const toggle = (path: string) =>
setSelected((paths) => (paths.includes(path) ? paths.filter((p) => p !== path) : [...paths, path]));
const choose = (entry: FileEntry) => {
if (isDir(entry)) void visit(entry.path);
else done(entry.path);
if (isDir(entry)) void move(entry.path);
else if (options.multiple) toggle(entry.path);
else if (options.save) setValue(entry.path);
else done([entry.path]);
};
const submit = async () => {
const path = value.trim();
if (!path) return;
let kind: string;
const input = value.trim();
if (loading || submitting) return;
if (options.multiple && selected.length) return done(selected);
if (!input) return;
const path = dir && !isAbsolute(input) ? inDir(dir, input) : input;
setSubmitting(true);
try {
kind = await call(commands.fsEntryKind(path));
} catch {
return setError(tx("No such file or folder"));
const kind = await call(commands.fsEntryKind(path));
const folder = kind === "dir";
if (options.directory) return folder ? done([path]) : setError(tx("Choose a folder"));
if (folder) return void visit(path);
if (
!options.save ||
(await confirm({
title,
message: tx`File '${nameOf(path)}' already exists. Do you want to overwrite it?`,
ok: "Overwrite",
}))
)
done([path]);
} catch (e) {
if (options.save && isErrorKind(e, "notFound")) done([path]);
else setError(options.save && e instanceof Error ? e.message : tx("No such file or folder"));
} finally {
setSubmitting(false);
}
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);
@@ -428,11 +470,16 @@ function PathDialog({ options, done }: { options: ChoosePathOptions; done: (v: s
<Dialog
open
blockWorkbenchShortcuts
title={options.title}
title={title}
onClose={() => done(null)}
width={520}
buttons={[
{ label: tx("OK"), role: "default", disabled: !value.trim(), onClick: () => void submit() },
{
label: tx("OK"),
role: "default",
disabled: loading || submitting || (!value.trim() && !selected.length),
onClick: () => void submit(),
},
{ label: t("common.cancel"), role: "cancel" },
]}
>
@@ -448,12 +495,12 @@ function PathDialog({ options, done }: { options: ChoosePathOptions; done: (v: s
icon="arrow-up"
title={tx("Parent Folder")}
disabled={!up || loading}
onClick={() => up && void visit(up)}
onClick={() => up && void move(up)}
/>
<Input
data-autofocus
className={styles.pathInput}
aria-label={options.title}
aria-label={title}
value={value}
invalid={!!error}
onChange={(e) => {
@@ -469,12 +516,12 @@ function PathDialog({ options, done }: { options: ChoosePathOptions; done: (v: s
onActiveChange={(i) => {
setActive(i);
const entry = entries[i];
if (entry) setValue(entry.path);
if (entry && (!options.save || !isDir(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)}
className={styles.pathList}
aria-label={dir ?? options.title}
aria-label={dir ?? title}
empty={
<div className={styles.hint}>
<T>{loading ? "Loading…" : "Empty folder"}</T>
@@ -483,7 +530,15 @@ function PathDialog({ options, done }: { options: ChoosePathOptions; done: (v: s
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>
{options.multiple && (options.directory || !isDir(entry)) ? (
<Checkbox
label={<Given>{entry.name}</Given>}
checked={selected.includes(entry.path)}
onChange={() => toggle(entry.path)}
/>
) : (
<span className={styles.entryName}>{entry.name}</span>
)}
</div>
)}
/>
+61 -2
View File
@@ -6,6 +6,8 @@ const mocks = vi.hoisted(() => ({
readDir: vi.fn(),
entryKind: vi.fn(),
nativeOpen: vi.fn(),
nativeSave: vi.fn(),
confirm: vi.fn(),
}));
vi.mock("@/platform/ipc", async (importOriginal) => {
@@ -16,9 +18,10 @@ vi.mock("@/platform/ipc", async (importOriginal) => {
commands: { ...real.commands, fsReadDir: mocks.readDir, fsEntryKind: mocks.entryKind },
};
});
vi.mock("@tauri-apps/plugin-dialog", () => ({ open: mocks.nativeOpen, save: vi.fn() }));
vi.mock("@tauri-apps/plugin-dialog", () => ({ open: mocks.nativeOpen, save: mocks.nativeSave }));
vi.mock("./messages", async (original) => ({ ...(await original<object>()), confirm: mocks.confirm }));
import { choosePath } from "@/platform/choosePath";
import { choosePath, choosePaths, chooseSavePath } from "@/platform/choosePath";
import { useRemote } from "@/platform/remote";
import { InputDialogsHost, parentPath } from "./inputDialogs";
@@ -26,6 +29,8 @@ const tree: Record<string, [string, "dir" | "file"][]> = {
"/srv/app": [
["runner", "dir"],
["pom.xml", "file"],
["build.xml", "file"],
["README.txt", "file"],
],
"/srv/app/runner": [
["plugins", "dir"],
@@ -119,6 +124,58 @@ describe("choosePath in a remote window", () => {
fireEvent.click(dialog().getByRole("button", { name: "Cancel" }));
await expect(result).resolves.toBeNull();
});
it("selects multiple matching files on the host", async () => {
let result!: Promise<string[]>;
act(() => {
result = choosePaths({
directory: false,
title: "Add Maven Projects",
defaultPath: "/srv/app",
filters: [{ name: "XML", extensions: ["xml"] }],
});
});
fireEvent.click(await dialog().findByRole("checkbox", { name: "pom.xml" }));
fireEvent.click(dialog().getByRole("checkbox", { name: "build.xml" }));
expect(dialog().queryByText("README.txt")).toBeNull();
fireEvent.click(dialog().getByRole("button", { name: "OK" }));
await expect(result).resolves.toEqual(["/srv/app/pom.xml", "/srv/app/build.xml"]);
expect(mocks.nativeOpen).not.toHaveBeenCalled();
});
it("keeps a proposed name while browsing to a new save destination", async () => {
let result!: Promise<string | null>;
act(() => {
result = chooseSavePath({ title: "Save As", defaultPath: "/srv/app/new.txt" });
});
await dialog().findByText("runner");
expect(dialog().getByRole("textbox")).toHaveValue("/srv/app/new.txt");
fireEvent.click(dialog().getByText("runner"), { detail: 2 });
await dialog().findByText("plugins");
expect(dialog().getByRole("textbox")).toHaveValue("/srv/app/runner/new.txt");
fireEvent.click(dialog().getByRole("button", { name: "OK" }));
await expect(result).resolves.toBe("/srv/app/runner/new.txt");
expect(mocks.nativeSave).not.toHaveBeenCalled();
expect(mocks.confirm).not.toHaveBeenCalled();
});
it("asks before accepting an existing save destination", async () => {
mocks.confirm.mockResolvedValueOnce(false).mockResolvedValueOnce(true);
let result!: Promise<string | null>;
act(() => {
result = chooseSavePath({ title: "Save As", defaultPath: "/srv/app/pom.xml" });
});
await dialog().findByText("runner");
const ok = dialog().getByRole("button", { name: "OK" });
fireEvent.click(ok);
await waitFor(() => expect(mocks.confirm).toHaveBeenCalledTimes(1));
await waitFor(() => expect(ok).toBeEnabled());
fireEvent.click(ok);
await expect(result).resolves.toBe("/srv/app/pom.xml");
expect(mocks.confirm).toHaveBeenCalledWith(
expect.objectContaining({ message: expect.stringContaining("pom.xml") }),
);
});
});
describe("parentPath", () => {
@@ -127,8 +184,10 @@ describe("parentPath", () => {
expect(parentPath("/srv")).toBe("/");
expect(parentPath("/")).toBeNull();
expect(parentPath("C:\\Users\\me")).toBe("C:\\Users");
expect(parentPath("C:/Users\\me")).toBe("C:/Users");
expect(parentPath("C:\\Users")).toBe("C:\\");
expect(parentPath("C:\\")).toBeNull();
expect(parentPath("/srv/app/")).toBe("/srv");
expect(parentPath("/srv/app/file\\name")).toBe("/srv/app");
});
});