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

...
Автор SHA1 Повідомлення Дата
l0ng-ai 1375620b99 fix(project-view): keep the tree still when a file is dragged out of it
Dragging a file from the Project view to the terminal (or any target below
the tree) scrolled the tree on and on: WebKit autoscrolls the pressed
scroll container toward the pointer once it leaves the container. During a
drag the tree now keeps its scroll position while the pointer is outside
it, and scrolls itself only while the pointer is within 24 px of its top or
bottom edge, as IDEA's tree does when you drag toward an edge.
2026-11-17 15:10:27 +08:00
l0ng-ai 217bd29860 fix(editor): colour Kotlin soft keywords only where they act as keywords (#3921)
The Kotlin stream mode coloured every soft keyword as a keyword, so a package segment (import top.ttb.data.Model), a member (result.data) or a name (val data = ...) looked like one. A word after . or ?. is now always a name, and a soft keyword is a keyword only before a declaration or another modifier (data class, open fun, by lazy) or, for catch / finally / init / constructor / get / set, before ( or {. Refs #3447
2026-11-17 14:50:25 +08:00
l0ng-ai 25d6e8ac7c fix(remote): browse the remote host when a setting asks for a path (#3920)
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 listed 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: click selects, double click or Enter opens a folder or chooses the file, the arrow goes to the parent folder, and the path can be typed. Local windows keep the desktop dialog. Refs #3447
2026-11-17 14:48:50 +08:00
9 змінених файлів з 452 додано та 7 видалено

No files matched your search

+34
Переглянути файл
@@ -17,6 +17,40 @@ async function tokens(mode: string, source: string) {
return result;
}
describe("Kotlin soft keywords", () => {
const styleOf = (out: Awaited<ReturnType<typeof tokens>>, text: string, nth = 0) =>
out.filter((t) => t.text === text)[nth]?.style ?? "";
it("colours a soft keyword only where it acts as one", async () => {
const source = [
"import top.ttb.data.Model",
"data class Point(val x: Int)",
"open class Base { val data = result.data; private fun f() {} }",
"val open: Int get() = 1",
"fun g(data: String) = try { } catch (e: Exception) { } finally { }",
].join("\n");
const out = await tokens("Kotlin", source);
// Package path, property access and names.
expect(styleOf(out, "data", 0)).not.toContain("tok-keyword");
expect(styleOf(out, "data", 2)).not.toContain("tok-keyword");
expect(styleOf(out, "data", 3)).not.toContain("tok-keyword");
expect(styleOf(out, "data", 4)).not.toContain("tok-keyword");
expect(styleOf(out, "open", 1)).not.toContain("tok-keyword");
// Modifiers and accessors.
expect(styleOf(out, "import")).toContain("tok-keyword");
expect(styleOf(out, "data", 1)).toContain("tok-keyword");
expect(styleOf(out, "open", 0)).toContain("tok-keyword");
expect(styleOf(out, "private")).toContain("tok-keyword");
expect(styleOf(out, "get")).toContain("tok-keyword");
expect(styleOf(out, "catch")).toContain("tok-keyword");
expect(styleOf(out, "finally")).toContain("tok-keyword");
// Hard keywords stay keywords.
expect(styleOf(out, "class")).toContain("tok-keyword");
expect(styleOf(out, "val")).toContain("tok-keyword");
expect(styleOf(out, "fun")).toContain("tok-keyword");
});
});
describe("frontend string interpolation", () => {
it.each([
["Kotlin", 'println("$i + 1 = ${i + 1}")'],
+27
Переглянути файл
@@ -152,7 +152,34 @@ export function interpolationParser<S>(base: StreamParser<S>, dialect: Interpola
frame.doc = depth > 0 && doc;
return doc ? "docComment" : result;
}
if (dialect === "Kotlin" && result === "keyword" && !kotlinKeywordAt(stream.string, from, stream.pos))
return "variable";
return result;
},
};
}
/** Kotlin's hard keywords: never names, wherever they appear (except after a dot). */
const KOTLIN_HARD_KEYWORDS = new Set(
"as as? break class continue do else false for fun if in !in interface is !is null object package return super this throw true try typealias typeof val var when while".split(
" ",
),
);
/** Soft keywords that open a block or a parameter list rather than precede a name. */
const KOTLIN_BLOCK_SOFT_KEYWORDS = new Set(["catch", "finally", "init", "constructor", "get", "set"]);
/**
* Whether the word the base mode calls a keyword is one here. A word after `.` is a member or
* package name (`import a.data.b`, `result.data`). Soft keywords (`data`, `open`, `get`…) are
* keywords only where they act as one, before a declaration or another modifier (`data class`,
* `get() = …`); elsewhere they are ordinary names (`val data = …`), as IDEA colours them.
*/
function kotlinKeywordAt(line: string, from: number, to: number): boolean {
if (/\??\.\s*$/.test(line.slice(0, from))) return false;
const word = line.slice(from, to);
if (KOTLIN_HARD_KEYWORDS.has(word)) return true;
const next = line.slice(to).match(/^\s*(.)/u)?.[1];
if (next === undefined) return false;
if (/[\p{L}_`@]/u.test(next)) return true;
return KOTLIN_BLOCK_SOFT_KEYWORDS.has(word) && (next === "(" || next === "{");
}
+39
Переглянути файл
@@ -651,6 +651,37 @@ export function ProjectView() {
// uses and the editor leaves them out.
let files: DragSession | null = null;
let endDrag: (() => void) | null = null;
// While dragging, the tree scrolls only when the pointer is near its top or bottom edge
// (IDEA's DnD autoscroll). Leaving the tree toward a drop target elsewhere (the terminal,
// an editor) keeps it where it is: WebKit's own autoscroll of the pressed scroll container
// would otherwise keep scrolling it toward the pointer.
const scroller = containerRef.current?.querySelector<HTMLElement>('[role="tree"]') ?? null;
let held = scroller?.scrollTop ?? 0;
let pointer: { x: number; y: number } | null = null;
let frame = 0;
const inside = (p: { x: number; y: number }) => {
const r = scroller?.getBoundingClientRect();
return !!r && p.x >= r.left && p.x <= r.right && p.y >= r.top && p.y <= r.bottom;
};
const keep = () => {
if (!scroller) return;
if (pointer && !inside(pointer)) scroller.scrollTop = held;
else held = scroller.scrollTop;
};
const edgeScroll = () => {
frame = 0;
if (!scroller || !pointer || !inside(pointer)) return;
const r = scroller.getBoundingClientRect();
const delta = pointer.y < r.top + 24 ? -8 : pointer.y > r.bottom - 24 ? 8 : 0;
const before = scroller.scrollTop;
scroller.scrollTop = Math.max(0, Math.min(scroller.scrollHeight - scroller.clientHeight, before + delta));
held = scroller.scrollTop;
if (held !== before) {
const target = folderAt(containerRef.current, pointer.x, pointer.y);
setDropTarget(target && !paths.some((p) => target.path === p || isInside(target.path, p)) ? target.key : null);
frame = requestAnimationFrame(edgeScroll);
}
};
const move = (ev: PointerEvent) => {
// A press with no button held is a reordered macOS tap, not a drag (see pointerDrag.ts).
if (!(ev.buttons & 1)) {
@@ -673,6 +704,10 @@ export function ProjectView() {
payload: nodes.map((n) => (n.dir ? `${n.path}/` : n.path)).join("\n"),
});
}
if (!pointer) scroller?.addEventListener("scroll", keep, { passive: true });
pointer = { x: ev.clientX, y: ev.clientY };
keep();
if (!frame) frame = requestAnimationFrame(edgeScroll);
const target = folderAt(containerRef.current, ev.clientX, ev.clientY);
const valid = target && !paths.some((p) => target.path === p || isInside(target.path, p));
setDropTarget(valid ? target.key : null);
@@ -703,6 +738,10 @@ export function ProjectView() {
}
};
const cleanup = () => {
scroller?.removeEventListener("scroll", keep);
cancelAnimationFrame(frame);
frame = 0;
pointer = null;
window.removeEventListener("pointermove", move);
window.removeEventListener("pointerup", up);
window.removeEventListener("pointercancel", cleanup);
+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");
});
});