Файли
openidea/src/features/project-tree/ProjectView.test.tsx
T
Bin 0104ed63c1 fix(project-tree): open external files on double-click only (#6993)
Single-click in the project tree opened files associated with an external application. Those now open on double-click only.

Co-authored-by: ffgenius <[email protected]>
2026-11-30 17:42:57 +08:00

1449 рядки
62 KiB
TypeScript
Неформатований Анотація Історія

Цей файл містить неоднозначні символи Юнікоду
Цей файл містить символи Юнікоду, які можна сплутати з іншими символами. Якщо ви вважаєте, що це зроблено навмисно, можете сміливо ігнорувати це попередження. Щоб показати їх, скористайтеся кнопкою Escape.
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, fireEvent, render, renderHook, screen, waitFor, within } from "@testing-library/react";
import { emitLocalIdeEvent } from "@/platform/ipc";
import { installRepeatedDoubleClick } from "@/platform/doubleClick";
import { getContext, setContext } from "@/platform/context";
import { applyKeymapSettings, installKeyboardDispatcher, useKeymap } from "@/platform/keymap";
import { usePlatform } from "@/platform/platformInfo";
import {
provideEditorService,
registerExternalFileOpenHandler,
registerProjectViewRoot,
setFileDecorations,
type EditorService,
} from "@/workbench/contributions";
import { activate } from "./index";
import { setOsClipboardForTests } from "./clipboard";
import { MemoryFs, setProjectFsForTests } from "./fs";
import { MessagesHost } from "@/workbench/messages";
import { FileRefactorDialogHost } from "./FileRefactorDialogs";
import { setRefactorBackendForTests } from "./fileRefactor";
import { ProjectView, formatFileDetails } from "./ProjectView";
import { beginNew, beginRename, canPaste } from "./operations";
import { initProjectTree, selectModel, setSelection, setViewOption, useProjectTree } from "./store";
import type { OutlineItem } from "@/bindings";
import { _emitEditorEvent, useEditorRegistry } from "@/editor/api";
import { LspPopups } from "@/editor/lsp/Popups";
import { closePopup, useLspPopup } from "@/editor/lsp/popupStore";
import { clearLineTokens } from "@/editor/lineTokens";
import { ProjectHeaderActions, useProjectHeaderMenu } from "./HeaderActions";
import { executeAction, getAction } from "@/platform/actions";
import { useProject } from "@/platform/project";
import type { MenuItem } from "@/ui";
import { loadOutline } from "./store";
const ipc = vi.hoisted(() => ({
docOpen: vi.fn(),
docClose: vi.fn(),
docOutline: vi.fn(),
settingsSet: vi.fn(),
fsReadText: vi.fn(),
}));
vi.mock("@/bindings", async (orig) => {
const real = await orig<typeof import("@/bindings")>();
return { ...real, commands: { ...real.commands, ...ipc } };
});
const dragOut = vi.hoisted(() => ({
canDragOut: vi.fn(() => false),
dragOut: vi.fn(async (_paths: readonly string[]) => true),
isDraggingOut: vi.fn(() => false),
}));
vi.mock("@/platform/dragOut", () => dragOut);
const ok = <T,>(data: T) => ({ status: "ok" as const, data });
const item = (name: string, kind: OutlineItem["kind"], line: number, children: OutlineItem[] = []): OutlineItem => {
const r = { start: { line, col: 0 }, end: { line, col: 1 } };
return { name, kind, detail: null, range: r, selection_range: r, children };
};
const deferred = <T,>() => {
let resolve!: (value: T) => void;
let reject!: (reason: Error) => void;
const promise = new Promise<T>((res, rej) => {
resolve = res;
reject = rej;
});
return { promise, resolve, reject };
};
const ROOT = "/w/acme";
const initialSettings = useProject.getState().settings;
/** Settings › Editor › General › Editor Tabs › Enable preview tab. */
const previewTabSettings = (on: boolean) => ({ editor: { tabs: { previewTab: on } } });
const setPreviewTabSetting = (on: boolean) => act(() => useProject.setState({ settings: previewTabSettings(on) }));
let fs: MemoryFs;
let openFile: ReturnType<typeof vi.fn>;
let dispose: () => void;
const initialPlatform = usePlatform.getState();
const initialKeymap = useKeymap.getState();
let uninstallDispatcher: (() => void) | null = null;
/** Presses the presets' shortcuts: the global dispatcher runs the keymap's actions. */
function dispatchViaKeymap() {
usePlatform.setState({ os: "macos" });
useKeymap.setState({ preset: "intellij-macos", overrides: {} });
// The workbench activation that publishes this in the app does not run here.
setContext("projectOpen", true);
uninstallDispatcher = installKeyboardDispatcher(window);
}
beforeEach(() => {
localStorage.clear();
fs = new MemoryFs(
{
"/w/acme/src/App.kt": "x",
"/w/acme/src/Util.kt": "x",
"/w/acme/build/out.class": "x",
"/w/acme/README.md": "x",
},
ROOT,
);
fs.ignored.add("/w/acme/build");
fs.onChange = (e) => queueMicrotask(() => emitLocalIdeEvent({ type: "fsChanged", ...e }));
setProjectFsForTests(fs, ROOT);
setRefactorBackendForTests(null);
clearLineTokens();
ipc.fsReadText.mockResolvedValue(ok("x"));
openFile = vi.fn(async () => {});
provideEditorService({ openFile, activePath: () => null } as unknown as EditorService);
dispose = activate();
initProjectTree(ROOT, "acme");
});
afterEach(() => {
act(() => closePopup());
clearLineTokens();
dispose();
useProject.setState({ settings: initialSettings });
setProjectFsForTests(null);
uninstallDispatcher?.();
uninstallDispatcher = null;
usePlatform.setState(initialPlatform);
useKeymap.setState(initialKeymap);
});
function setup() {
const rendered = render(
<>
<ProjectView />
<MessagesHost />
<FileRefactorDialogHost />
<LspPopups />
</>,
);
const tree = screen.getByRole("tree", { name: "Project" });
const rows = () =>
within(tree)
.queryAllByRole("treeitem")
.map((r) => r.textContent);
const row = (label: string) =>
within(tree)
.getAllByRole("treeitem")
.find((r) => r.textContent?.startsWith(label))!;
return { tree, rows, row, unmount: rendered.unmount };
}
describe("ProjectView", () => {
it("toggles Unity metadata and generated files independently in the rendered tree", async () => {
fs = new MemoryFs(
{
"/w/acme/Assets/Player.cs": "code",
"/w/acme/Assets/Player.cs.meta": "metadata",
"/w/acme/Library/cache": "cache",
"/w/acme/Game.sln": "",
},
ROOT,
);
setProjectFsForTests(fs, ROOT);
initProjectTree(ROOT, "Game", null, { editorVersion: "6000.0.62f1", projects: [], solutions: [] });
const { rows } = setup();
act(() => useProjectTree.setState({ expanded: new Set([ROOT, `${ROOT}/Assets`]) }));
await waitFor(() => expect(rows()).toContain("Player.cs"));
expect(rows()).not.toContain("Player.cs.meta");
expect(rows()).not.toContain("Library");
act(() => setViewOption("showUnityMeta", true));
await waitFor(() => expect(rows()).toContain("Player.cs.meta"));
expect(rows()).not.toContain("Game.sln");
act(() => setViewOption("showUnityGenerated", true));
await waitFor(() => expect(rows()).toContain("Game.sln"));
expect(rows()).toContain("Library");
act(() => setViewOption("showUnityMeta", false));
expect(rows()).not.toContain("Player.cs.meta");
expect(rows()).toContain("Library");
});
it("shows Unity version and generation guidance, then updates when project files arrive", async () => {
initProjectTree(ROOT, "Game", null, { editorVersion: "6000.0.62f1", projects: [], solutions: [] });
const { row } = setup();
expect(screen.getByText(/C# project files are missing/)).toHaveAttribute("role", "status");
await waitFor(() => expect(row("Game")).toHaveTextContent("Unity 6000.0.62f1"));
act(() => {
useProjectTree.setState({
unity: { editorVersion: "6000.0.62f1", projects: ["Assembly-CSharp.csproj"], solutions: ["Game.sln"] },
});
});
expect(screen.queryByText(/C# project files are missing/)).not.toBeInTheDocument();
});
it("shows the root with its path and loads children lazily", async () => {
const { rows, row, tree } = setup();
await waitFor(() => expect(rows()).toEqual(["acme/w/acme", "build", "src", "README.md"]));
expect(row("build").querySelector("[class*=excluded]")).not.toBeNull();
fireEvent.mouseDown(row("src"));
tree.focus();
fireEvent.keyDown(tree, { key: "ArrowRight" });
await waitFor(() => expect(rows()).toEqual(["acme/w/acme", "build", "src", "App.kt", "Util.kt", "README.md"]));
});
it("restores visible expansion across workspace roots while a compacted folder is slow", async () => {
const left = "/left/src/nested/deep";
const right = "/right/src/package";
fs = new MemoryFs({
[`${left}/New.ts`]: "new",
[`${right}/Ready.ts`]: "ready",
"/left/closed/orphan/Skipped.ts": "",
"/left/ignored/inside/Hidden.ts": "",
});
fs.ignored.add("/left/ignored");
const gate = deferred<void>();
const read = fs.readDir.bind(fs);
const spy = vi.spyOn(fs, "readDir").mockImplementation(async (path) => {
if (path === left) await gate.promise;
return read(path);
});
const { showExcluded } = useProjectTree.getState().options;
setViewOption("showExcluded", false);
try {
setProjectFsForTests(fs, ROOT);
localStorage.setItem(
`openidea.projectTree.expanded:${ROOT}`,
JSON.stringify([
"/left",
"/left/src",
"/left/src/nested",
left,
"/right",
"/right/src",
right,
"/left/closed/orphan",
"/left/ignored",
"/left/ignored/inside",
]),
);
initProjectTree(ROOT, "Workspace", ["/left", "/right"]);
const { rows } = setup();
await waitFor(() => expect(rows()).toContain("Ready.ts"));
expect(spy).toHaveBeenCalledWith(left);
expect(rows()).not.toContain("New.ts");
gate.resolve();
await waitFor(() => expect(rows()).toContain("New.ts"));
expect(spy.mock.calls.map(([path]) => path).sort()).toEqual([
"/left",
"/left/src",
"/left/src/nested",
left,
"/right",
"/right/src",
right,
]);
} finally {
gate.resolve();
act(() => setViewOption("showExcluded", showExcluded));
}
});
it("reveals ready selected folders from the toolbar while a compacted sibling waits", async () => {
const blocked = `${ROOT}/slow/nested/leaf`;
fs = new MemoryFs(
{
[`${ROOT}/fast/pkg/leaf/Ready.ts`]: "ready",
[`${blocked}/Blocked.ts`]: "blocked",
[`${ROOT}/unselected/Skipped.ts`]: "",
[`${ROOT}/README.md`]: "",
"/outside/Linked.ts": "",
},
ROOT,
{ [`${ROOT}/linked-parent/link`]: "/outside" },
);
setProjectFsForTests(fs, ROOT);
const gate = deferred<void>();
const done = deferred<void>();
const read = fs.readDir.bind(fs);
const spy = vi.spyOn(fs, "readDir").mockImplementation(async (path) => {
if (path === blocked) await gate.promise;
const entries = await read(path);
if (path === blocked) done.resolve();
return entries;
});
setContext("projectOpen", true);
render(<ProjectHeaderActions />);
const { rows, row, tree } = setup();
const button = screen.getByRole("button", { name: "Expand Selected" });
expect(button).toBeDisabled();
expect(button).toHaveAttribute("data-tooltip", "Expand Selected");
expect(getAction("project.expandSelected")?.title).toBe("Expand Selected");
expect(getAction("project.expandAll")?.title).toBe("Expand All");
expect(await executeAction("project.expandSelected")).toBe(false);
await waitFor(() => expect(rows()).toContain("fast"));
fireEvent.mouseDown(row("README.md"));
expect(button).toBeEnabled();
expect(await executeAction("project.expandSelected")).toBe(true);
expect(spy.mock.calls).toEqual([[ROOT]]);
fireEvent.mouseDown(row("fast"));
fireEvent.mouseDown(row("linked-parent"), { metaKey: true });
fireEvent.mouseDown(row("slow"), { metaKey: true });
const selection = useProjectTree.getState().selected;
expect(selection).toEqual(new Set([`${ROOT}/fast`, `${ROOT}/linked-parent`, `${ROOT}/slow`]));
tree.scrollTop = 18;
const scrollTop = tree.scrollTop;
try {
fireEvent.click(button);
await waitFor(() => expect(rows()).toContain("Ready.ts"));
expect(spy).toHaveBeenCalledWith(blocked);
expect(rows()).not.toContain("Blocked.ts");
expect(rows()).toContain("link");
expect(rows()).not.toContain("Linked.ts");
expect(spy).not.toHaveBeenCalledWith(`${ROOT}/linked-parent/link`);
expect(spy).not.toHaveBeenCalledWith(`${ROOT}/unselected`);
expect(useProjectTree.getState().selected).toBe(selection);
expect(tree.scrollTop).toBe(scrollTop);
fireEvent.mouseDown(row("Ready.ts"));
await act(async () => void (await executeAction("project.collapseAll")));
await act(async () => {
gate.resolve();
await done.promise;
});
const root = row("acme");
expect(root).toHaveAttribute("aria-expanded", "false");
expect(rows()).toEqual(["acme/w/acme"]);
expect(button).toBeDisabled();
expect(useProjectTree.getState().listings.has(blocked)).toBe(false);
const paths = spy.mock.calls.map(([path]) => path);
expect(paths).toHaveLength(new Set(paths).size);
fireEvent.mouseDown(root);
fireEvent.keyDown(tree, { key: "ArrowRight" });
expect(root).toHaveAttribute("aria-expanded", "true");
expect(rows()).toContain("README.md");
expect(rows()).not.toContain("Ready.ts");
expect(rows()).not.toContain("Blocked.ts");
} finally {
gate.resolve();
}
});
it("closes every workspace root and reopens only the chosen root", async () => {
fs = new MemoryFs({ "/left/Left.ts": "left", "/right/Right.ts": "right" });
setProjectFsForTests(fs, ROOT);
initProjectTree(ROOT, "Workspace", ["/left", "/right"]);
setContext("projectOpen", true);
render(<ProjectHeaderActions />);
const { rows, row, tree } = setup();
await waitFor(() => expect(rows()).toEqual(["left/left", "Left.ts", "right/right", "Right.ts"]));
fireEvent.click(screen.getByRole("button", { name: "Collapse All" }));
expect(rows()).toEqual(["left/left", "right/right"]);
expect(row("left")).toHaveAttribute("aria-expanded", "false");
expect(row("right")).toHaveAttribute("aria-expanded", "false");
fireEvent.mouseDown(row("right"));
fireEvent.keyDown(tree, { key: "ArrowRight" });
expect(rows()).toEqual(["left/left", "right/right", "Right.ts"]);
expect(row("left")).toHaveAttribute("aria-expanded", "false");
expect(row("right")).toHaveAttribute("aria-expanded", "true");
});
it("opens the selected file in the right split with ⇧Enter; a folder still expands", async () => {
dispatchViaKeymap();
const { tree, row, rows } = setup();
await waitFor(() => expect(rows()).toContain("README.md"));
fireEvent.mouseDown(row("README.md"));
tree.focus();
fireEvent.keyDown(tree, { key: "Enter", code: "Enter", shiftKey: true });
await waitFor(() =>
expect(openFile).toHaveBeenLastCalledWith(
"/w/acme/README.md",
expect.objectContaining({ side: true, focus: true }),
),
);
openFile.mockClear();
fireEvent.mouseDown(row("src"));
tree.focus();
fireEvent.keyDown(tree, { key: "Enter", code: "Enter", shiftKey: true });
await waitFor(() => expect(rows()).toContain("App.kt"));
expect(openFile).not.toHaveBeenCalled();
});
it("pastes the files Explorer copied into the selected folder, as copies", async () => {
dispatchViaKeymap();
// What Explorer leaves on the clipboard: a path outside the project.
fs.nodes.set("/elsewhere/Photo.png", { kind: "file", size: 3 });
setOsClipboardForTests({
files: async () => ["/elsewhere/Photo.png"],
hasFiles: async () => true,
setFiles: async () => false,
});
try {
const { tree, row, rows } = setup();
await waitFor(() => expect(rows()).toContain("README.md"));
fireEvent.mouseDown(row("src"));
tree.focus();
// ⌘ is the primary modifier here, as in the undo test below.
fireEvent.keyDown(tree, { key: "v", code: "KeyV", metaKey: true });
await waitFor(() => expect(fs.nodes.has("/w/acme/src/Photo.png")).toBe(true));
// A copy, not a move: the dropped-from path stays where it was.
expect(fs.nodes.has("/elsewhere/Photo.png")).toBe(true);
} finally {
setOsClipboardForTests(null);
}
});
it("pastes a copied keyword into the tree's speed search instead of pasting files", async () => {
dispatchViaKeymap();
// Explorer holds a file, and the user wants to paste a word they copied from somewhere else
// into the search they just opened with ⌘F.
fs.nodes.set("/elsewhere/Photo.png", { kind: "file", size: 3 });
setOsClipboardForTests({
files: async () => ["/elsewhere/Photo.png"],
hasFiles: async () => true,
setFiles: async () => false,
});
try {
const { tree, row, rows } = setup();
await waitFor(() => expect(rows()).toContain("README.md"));
fireEvent.mouseDown(row("src"));
tree.focus();
fireEvent.keyDown(tree, { key: "f", code: "KeyF", metaKey: true });
fireEvent.paste(tree, {
clipboardData: { getData: () => "Read" },
} as unknown as ClipboardEventInit);
expect(within(tree.parentElement!).getByRole("status")).toHaveTextContent("Read");
// The file Paste never ran: give a wrong one the time to land, then check the project.
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 50));
});
expect([...fs.nodes.keys()].filter((p) => p.startsWith("/w/acme/") && p.endsWith("Photo.png"))).toEqual([]);
// Closed, ⌘V is the view's file Paste again.
fireEvent.keyDown(tree, { key: "Escape", code: "Escape" });
fireEvent.keyDown(tree, { key: "v", code: "KeyV", metaKey: true });
await waitFor(() =>
expect([...fs.nodes.keys()].some((p) => p.startsWith("/w/acme/") && p.endsWith("Photo.png"))).toBe(true),
);
} finally {
setOsClipboardForTests(null);
}
});
it("clears cut dimming and disables Paste on focus after the OS clipboard becomes text", async () => {
dispatchViaKeymap();
let files: string[] = [];
setOsClipboardForTests({
files: async () => files,
hasFiles: async () => files.length > 0,
setFiles: async (paths) => {
files = paths;
return true;
},
});
try {
const { tree, row, rows } = setup();
await waitFor(() => expect(rows()).toContain("README.md"));
fireEvent.mouseDown(row("README.md"));
tree.focus();
fireEvent.keyDown(tree, { key: "x", code: "KeyX", metaKey: true });
const content = row("README.md").querySelector("[data-project-path]")!;
expect(content.className).toMatch(/cut/);
await act(async () => {
await useProjectTree.getState().clipboard?.osWrite;
});
files = [];
fireEvent.focus(window);
await waitFor(() => expect(content.className).not.toMatch(/cut/));
expect(useProjectTree.getState().clipboard).toBeNull();
expect(canPaste()).toBe(false);
fireEvent.keyDown(tree, { key: "v", code: "KeyV", metaKey: true });
expect(screen.queryByRole("dialog", { name: "Copy" })).toBeNull();
expect(screen.queryByRole("dialog", { name: "Move" })).toBeNull();
} finally {
setOsClipboardForTests(null);
}
});
it("opens files on double click and previews on single click while the editor's preview tab is on", async () => {
const { row, rows } = setup();
await waitFor(() => expect(rows()).toContain("README.md"));
const content = row("README.md").querySelector("[data-project-path]")!;
// Settings › Editor › General › Editor Tabs › Enable preview tab is on by default.
fireEvent.click(content, { detail: 1 });
expect(openFile).toHaveBeenLastCalledWith("/w/acme/README.md", { preview: true, focus: false });
openFile.mockClear();
fireEvent.click(content, { detail: 3 });
expect(openFile).not.toHaveBeenCalled();
setPreviewTabSetting(false);
fireEvent.click(content, { detail: 1 });
expect(openFile).not.toHaveBeenCalled();
fireEvent.doubleClick(row("README.md"));
expect(openFile).toHaveBeenLastCalledWith("/w/acme/README.md", { preview: undefined, focus: true });
});
it("selects a file opened externally on single click and opens it on double click", async () => {
fs = new MemoryFs({ "/w/acme/notes.docx": "x" }, ROOT);
setProjectFsForTests(fs, ROOT);
initProjectTree(ROOT, "acme");
const disposeExternal = registerExternalFileOpenHandler({
id: "test.external",
matches: (path) => path.endsWith(".docx"),
open: vi.fn(async () => true),
});
try {
const { row, rows } = setup();
await waitFor(() => expect(rows()).toContain("notes.docx"));
const content = row("notes.docx").querySelector("[data-project-path]")!;
fireEvent.click(content, { detail: 1 });
expect(openFile).not.toHaveBeenCalled();
fireEvent.doubleClick(row("notes.docx"));
expect(openFile).toHaveBeenLastCalledWith("/w/acme/notes.docx", { preview: undefined, focus: true });
} finally {
disposeExternal();
}
});
it("opens a selected file in a read-only Quick Preview with Space without creating an editor tab", async () => {
dispatchViaKeymap();
ipc.fsReadText.mockResolvedValue(ok("# Preview\n\nRead without opening a tab."));
const { tree, row, rows } = setup();
await waitFor(() => expect(rows()).toContain("README.md"));
fireEvent.mouseDown(row("README.md"));
tree.focus();
const editors = useEditorRegistry.getState().editors;
fireEvent.keyDown(tree, { key: " ", code: "Space" });
const preview = await screen.findByRole("dialog", { name: "Quick Preview" });
expect(useLspPopup.getState().popup).toMatchObject({ kind: "filePreview", path: "/w/acme/README.md" });
await waitFor(() => expect(preview.querySelector(".cm-content")).toHaveTextContent("# Preview"));
expect(preview.querySelector(".cm-content")).toHaveAttribute("contenteditable", "false");
expect(ipc.fsReadText).toHaveBeenCalledWith("/w/acme/README.md");
expect(openFile).not.toHaveBeenCalled();
expect(useEditorRegistry.getState().editors).toBe(editors);
expect(getAction("project.quickPreview")?.title).toBe("Quick Preview");
});
it("closes Quick Preview on Escape, selection, focus changes and unmount", async () => {
dispatchViaKeymap();
ipc.fsReadText.mockResolvedValue(ok("preview text"));
const view = setup();
const { tree, row, rows } = view;
await waitFor(() => expect(rows()).toContain("README.md"));
const open = async () => {
fireEvent.mouseDown(row("README.md"));
tree.focus();
await act(async () => {
await executeAction("project.quickPreview");
});
await screen.findByRole("dialog", { name: "Quick Preview" });
};
await open();
const preview = screen.getByRole("dialog", { name: "Quick Preview" });
act(() => (preview.querySelector(".cm-content") as HTMLElement).focus());
expect(screen.getByRole("dialog", { name: "Quick Preview" })).toBeInTheDocument();
fireEvent.keyDown(tree, { key: "Escape", code: "Escape" });
expect(screen.queryByRole("dialog", { name: "Quick Preview" })).toBeNull();
await waitFor(() => expect(getContext().popupOpen).toBe(false));
await open();
fireEvent.mouseDown(row("src"));
expect(screen.queryByRole("dialog", { name: "Quick Preview" })).toBeNull();
await waitFor(() => expect(getContext().popupOpen).toBe(false));
await open();
act(() => (document.activeElement as HTMLElement | null)?.blur());
expect(screen.queryByRole("dialog", { name: "Quick Preview" })).toBeNull();
await waitFor(() => expect(getContext().popupOpen).toBe(false));
await open();
view.unmount();
expect(useLspPopup.getState().popup).toBeNull();
expect(openFile).not.toHaveBeenCalled();
});
it("does not Quick Preview folders or multiple files and follows an unbound Space setting", async () => {
dispatchViaKeymap();
const { tree, row, rows } = setup();
await waitFor(() => expect(rows()).toContain("README.md"));
fireEvent.mouseDown(row("src"));
tree.focus();
fireEvent.keyDown(tree, { key: " ", code: "Space" });
expect(useLspPopup.getState().popup).toBeNull();
fireEvent.mouseDown(row("README.md"));
fireEvent.mouseDown(row("src"), { metaKey: true });
fireEvent.keyDown(tree, { key: " ", code: "Space" });
expect(useLspPopup.getState().popup).toBeNull();
fireEvent.mouseDown(row("README.md"));
applyKeymapSettings("intellij-macos", { "project.quickPreview": [] });
fireEvent.keyDown(tree, { key: " ", code: "Space" });
expect(useLspPopup.getState().popup).toBeNull();
expect(ipc.fsReadText).not.toHaveBeenCalled();
expect(openFile).not.toHaveBeenCalled();
});
it("toggles the editor's preview tab setting from the Behavior menu and its action", async () => {
ipc.settingsSet.mockImplementation(async (_scope: string, _key: string, value: string) =>
ok(previewTabSettings(JSON.parse(value) as boolean)),
);
const { result } = renderHook(() => useProjectHeaderMenu());
type Item = Extract<MenuItem, { id?: string }>;
const behavior = () => (result.current[0] as Item).submenu as Item[];
const item = () => behavior().find((i) => i.id === "previewTab")!;
expect(item().checked).toBe(true);
act(() => item().run!());
await waitFor(() => expect(item().checked).toBe(false));
expect(ipc.settingsSet).toHaveBeenLastCalledWith("global", "editor.tabs.previewTab", "false");
const action = getAction("project.option.previewTab")!;
expect(action.toggled!()).toBe(false);
act(() => void executeAction(action.id));
await waitFor(() => expect(item().checked).toBe(true));
});
it("drops the former view-only preview tab option from saved view options", () => {
localStorage.setItem("openidea.projectTree.options", JSON.stringify({ previewTab: true, singleClickOpen: true }));
vi.resetModules();
return import("./store").then(({ useProjectTree: fresh }) => {
expect(fresh.getState().options).not.toHaveProperty("previewTab");
expect(fresh.getState().options.singleClickOpen).toBe(true);
});
});
it("follows tab switches with Always Select Opened File, hiding Select Opened File", async () => {
const focusEditor = (path: string) => act(() => useEditorRegistry.setState({ active: { ctx: { path } } } as never));
const selected = () =>
screen
.getAllByRole("treeitem")
.filter((r) => r.getAttribute("aria-selected") === "true")
.map((r) => r.textContent);
try {
render(<ProjectHeaderActions />);
const { rows } = setup();
await waitFor(() => expect(rows()).toContain("README.md"));
expect(screen.getByRole("button", { name: "Select Opened File" })).toBeTruthy();
focusEditor("/w/acme/src/Util.kt");
expect(rows()).not.toContain("Util.kt");
act(() => setViewOption("autoscrollFromSource", true));
await waitFor(() => expect(selected()).toEqual(["Util.kt"]));
expect(screen.queryByRole("button", { name: "Select Opened File" })).toBeNull();
focusEditor("/w/acme/README.md");
await waitFor(() => expect(selected()).toEqual(["README.md"]));
focusEditor("/w/acme/src/App.kt");
await waitFor(() => expect(selected()).toEqual(["App.kt"]));
act(() => setViewOption("autoscrollFromSource", false));
focusEditor("/w/acme/README.md");
expect(selected()).toEqual(["App.kt"]);
expect(screen.getByRole("button", { name: "Select Opened File" })).toBeTruthy();
} finally {
act(() => useEditorRegistry.setState({ active: null }));
}
});
it("expands and collapses folders on single click only when enabled", async () => {
const { row, rows } = setup();
await waitFor(() => expect(rows()).toContain("README.md"));
const src = () => row("src").querySelector("[data-project-path]")!;
const click = (detail = 1, init: MouseEventInit = {}) => {
fireEvent.mouseDown(row("src"), { detail, ...init });
fireEvent.click(src(), { detail, ...init });
};
click();
expect(rows()).not.toContain("App.kt");
act(() => setViewOption("singleClickExpand", true));
click();
await waitFor(() => expect(rows()).toContain("App.kt"));
click();
expect(rows()).not.toContain("App.kt");
// A double click toggles once: the second click and the dblclick are ignored.
click(1);
click(2);
fireEvent.doubleClick(src());
await waitFor(() => expect(rows()).toContain("App.kt"));
// Modifier clicks only change the selection.
fireEvent.mouseDown(row("README.md"));
click(1, { metaKey: true });
expect(useProjectTree.getState().selected).toEqual(new Set(["/w/acme/README.md", "/w/acme/src"]));
click(1, { shiftKey: true });
expect(rows()).toContain("App.kt");
act(() => setViewOption("singleClickExpand", false));
});
it("toggles folders once for each rapid double-click pair", async () => {
const uninstall = installRepeatedDoubleClick();
try {
const { row, rows } = setup();
await waitFor(() => expect(rows()).toContain("README.md"));
const content = () => row("src").querySelector("[data-project-path]")!;
// WebKit fires `dblclick` only for the second click of a burst, never for the 4th or 6th.
const burst = (clicks: number) => {
for (let detail = 1; detail <= clicks; detail++) {
fireEvent.mouseDown(row("src"), { detail });
fireEvent.click(content(), { detail });
if (detail === 2) fireEvent.doubleClick(content(), { detail });
}
};
// Double-click mode toggles once per pair; single-click mode once per odd click.
let expanded = false;
for (const singleClickExpand of [false, true]) {
act(() => setViewOption("singleClickExpand", singleClickExpand));
for (const clicks of [2, 4, 6, 3, 5]) {
burst(clicks);
const toggles = singleClickExpand ? Math.ceil(clicks / 2) : Math.floor(clicks / 2);
if (toggles % 2) expanded = !expanded;
// oxlint-disable-next-line no-await-in-loop -- each click burst is asserted before the next burst is fired
await waitFor(() => expect(rows().includes("App.kt")).toBe(expanded));
}
}
} finally {
uninstall();
act(() => setViewOption("singleClickExpand", false));
}
});
it("starts a file drag only while the primary button is held", async () => {
const { row, rows } = setup();
await waitFor(() => expect(rows()).toContain("README.md"));
document.elementFromPoint = () => null; // jsdom lacks it; the drop-target lookup needs it
// The drag label repeats the file name outside the tree row.
const ghost = () => (screen.queryAllByText("README.md").length > 1 ? true : null);
const move = (buttons: number, x: number) =>
act(() => {
window.dispatchEvent(new MouseEvent("pointermove", { bubbles: true, buttons, clientX: x, clientY: 0 }));
});
const release = () => act(() => void window.dispatchEvent(new MouseEvent("pointerup", { bubbles: true })));
// jsdom has no PointerEvent, so React would see `button` undefined on a plain pointerDown.
const press = () =>
fireEvent(
row("README.md").querySelector("[data-project-path]")!,
new MouseEvent("pointerdown", { bubbles: true, button: 0 }),
);
// A macOS tap WebKit reorders: the press arrives late and no button is held.
press();
move(0, 40);
expect(ghost()).toBeNull();
release();
press();
move(1, 40);
expect(ghost()).not.toBeNull();
release();
expect(ghost()).toBeNull();
});
it("keeps the tree from scrolling sideways during a drag", async () => {
const { tree, row, rows } = setup();
await waitFor(() => expect(rows()).toContain("README.md"));
document.elementFromPoint = () => null;
fireEvent(
row("README.md").querySelector("[data-project-path]")!,
new MouseEvent("pointerdown", { bubbles: true, button: 0 }),
);
act(() => void window.dispatchEvent(new MouseEvent("pointermove", { buttons: 1, clientX: 40, clientY: 0 })));
// WebKit's autoscroll toward a pointer right of the tree.
tree.scrollLeft = 600;
fireEvent.scroll(tree);
expect(tree.scrollLeft).toBe(0);
act(() => void window.dispatchEvent(new MouseEvent("pointerup", { bubbles: true })));
});
it("hands the selected files to an OS drag once the pointer leaves the window", async () => {
const { row, rows } = setup();
await waitFor(() => expect(rows()).toContain("README.md"));
document.elementFromPoint = () => null;
const model = selectModel(useProjectTree.getState());
const keys = [`${ROOT}/README.md`, `${ROOT}/src`].map((p) => model.keyOfPath.get(p)!);
act(() => setSelection(new Set(keys), keys[0]!));
const ghost = () => screen.queryByText("2 items");
const press = () =>
fireEvent(
row("README.md").querySelector("[data-project-path]")!,
new MouseEvent("pointerdown", { bubbles: true, button: 0 }),
);
const move = (x: number) =>
act(() => {
window.dispatchEvent(new MouseEvent("pointermove", { bubbles: true, buttons: 1, clientX: x, clientY: 10 }));
});
const release = () => act(() => void window.dispatchEvent(new MouseEvent("pointerup", { bubbles: true })));
try {
// Where files can't leave (a remote project, the browser), the drag stays in the window.
press();
move(40);
move(-5);
expect(ghost()).not.toBeNull();
release();
expect(dragOut.dragOut).not.toHaveBeenCalled();
dragOut.canDragOut.mockReturnValue(true);
press();
move(40);
expect(ghost()).not.toBeNull();
expect(dragOut.dragOut).not.toHaveBeenCalled();
move(window.innerWidth + 5);
expect(dragOut.dragOut).toHaveBeenCalledExactlyOnceWith([`${ROOT}/README.md`, `${ROOT}/src`]);
// The OS drag owns the pointer now: the in-window drag is over.
expect(ghost()).toBeNull();
move(-5);
release();
expect(dragOut.dragOut).toHaveBeenCalledOnce();
} finally {
dragOut.canDragOut.mockReturnValue(false);
dragOut.dragOut.mockClear();
}
});
it("cancels a new file when its name field loses focus", async () => {
const { rows } = setup();
await waitFor(() => expect(rows()).toContain("README.md"));
await act(() => beginNew("file", ROOT));
const input = await screen.findByRole("textbox", { name: "New file name" });
fireEvent.change(input, { target: { value: "Notes.md" } });
await act(async () => void fireEvent.blur(input));
expect(useProjectTree.getState().editing).toBeNull();
expect(fs.nodes.has("/w/acme/Notes.md")).toBe(false);
});
it("publishes the focus context key", async () => {
const { tree, rows } = setup();
await waitFor(() => expect(rows()).toContain("README.md"));
fireEvent.focus(tree);
expect(getContext().projectViewFocus).toBe(true);
fireEvent.blur(tree);
expect(getContext().projectViewFocus).toBe(false);
});
it("publishes the selected folder or file parent only while the tree has focus", async () => {
const { tree, row, rows } = setup();
await waitFor(() => expect(rows()).toContain("README.md"));
fireEvent.mouseDown(row("src"));
tree.focus();
expect(getContext().focusedDirectory).toBe(`${ROOT}/src`);
fireEvent.keyDown(tree, { key: "ArrowRight" });
await waitFor(() => expect(rows()).toContain("App.kt"));
fireEvent.mouseDown(row("App.kt"));
expect(getContext().focusedDirectory).toBe(`${ROOT}/src`);
fireEvent.mouseDown(row("README.md"));
expect(getContext().focusedDirectory).toBe(ROOT);
fireEvent.blur(tree);
expect(getContext().focusedDirectory).toBeUndefined();
});
it("publishes Scratches paths through the same Project tree", async () => {
fs.nodes.set("/scratches", { kind: "dir" });
fs.nodes.set("/scratches/note.txt", { kind: "file", size: 0 });
const remove = registerProjectViewRoot({
id: "scratch-test",
path: "/scratches",
label: "Scratches",
icon: "scratches",
scope: "scratches",
});
try {
const { tree, row, rows } = setup();
await waitFor(() => expect(rows()).toContain("Scratches"));
fireEvent.mouseDown(row("Scratches"));
tree.focus();
expect(getContext().focusedDirectory).toBe("/scratches");
fireEvent.keyDown(tree, { key: "ArrowRight" });
await waitFor(() => expect(rows()).toContain("note.txt"));
fireEvent.mouseDown(row("note.txt"));
expect(getContext().focusedDirectory).toBe("/scratches");
} finally {
act(() => remove());
}
});
it("renames in IDEA's Rename dialog with Shift+F6, validating conflicts, and undoes with ⌘Z", async () => {
dispatchViaKeymap();
const { tree, row, rows } = setup();
await waitFor(() => expect(rows()).toContain("README.md"));
fireEvent.mouseDown(row("README.md"));
tree.focus();
fireEvent.keyDown(tree, { key: "F6", code: "F6", shiftKey: true });
const dialog = await screen.findByRole("dialog", { name: "Rename" });
expect(dialog).toHaveTextContent("Rename file 'README.md' and its usages to:");
expect(within(dialog).getByRole("checkbox", { name: "Search for references" })).toBeChecked();
expect(within(dialog).getByRole("checkbox", { name: "Search in comments and strings" })).toBeInTheDocument();
const input = within(dialog).getByRole("textbox", { name: "New name" });
await waitFor(() => expect((input as HTMLInputElement).selectionEnd).toBe("README".length));
fireEvent.change(input, { target: { value: "src" } });
expect(await within(dialog).findByRole("alert")).toHaveTextContent("'src' already exists");
expect(within(dialog).getByRole("button", { name: "Refactor" })).toBeDisabled();
fireEvent.change(input, { target: { value: "GUIDE.md" } });
fireEvent.click(within(dialog).getByRole("button", { name: "Refactor" }));
await waitFor(() => expect(rows()).toContain("GUIDE.md"));
expect(fs.nodes.has("/w/acme/GUIDE.md")).toBe(true);
expect(screen.queryByRole("dialog", { name: "Rename" })).toBeNull();
// ⌘Z in the project view undoes the rename.
tree.focus();
fireEvent.keyDown(tree, { key: "z", code: "KeyZ", metaKey: true });
await waitFor(() => expect(fs.nodes.has("/w/acme/README.md")).toBe(true));
expect(fs.nodes.has("/w/acme/GUIDE.md")).toBe(false);
});
it("stops renaming with Shift+F6 once Rename File is unbound, following the keymap", async () => {
dispatchViaKeymap();
// Unbinding used to leave the component's hardcoded Shift+F6 in place (issue #2801).
applyKeymapSettings("intellij-macos", { "project.rename": [] });
const { tree, row, rows } = setup();
await waitFor(() => expect(rows()).toContain("README.md"));
fireEvent.mouseDown(row("README.md"));
tree.focus();
fireEvent.keyDown(tree, { key: "F6", code: "F6", shiftKey: true });
expect(screen.queryByRole("dialog", { name: "Rename" })).toBeNull();
});
it("renames with the shortcut the keymap rebinds Rename File to", async () => {
dispatchViaKeymap();
applyKeymapSettings("intellij-macos", { "project.rename": ["F2"] });
const { tree, row, rows } = setup();
await waitFor(() => expect(rows()).toContain("README.md"));
fireEvent.mouseDown(row("README.md"));
tree.focus();
fireEvent.keyDown(tree, { key: "F6", code: "F6", shiftKey: true });
expect(screen.queryByRole("dialog", { name: "Rename" })).toBeNull();
fireEvent.keyDown(tree, { key: "F2", code: "F2" });
const dialog = await screen.findByRole("dialog", { name: "Rename" });
fireEvent.click(within(dialog).getByRole("button", { name: "Cancel" }));
});
it("moves with F6 through the Move dialog", async () => {
dispatchViaKeymap();
const { tree, row, rows } = setup();
await waitFor(() => expect(rows()).toContain("README.md"));
fireEvent.mouseDown(row("README.md"));
tree.focus();
fireEvent.keyDown(tree, { key: "F6", code: "F6" });
const dialog = await screen.findByRole("dialog", { name: "Move" });
expect(dialog).toHaveTextContent("Move file 'README.md'");
expect(within(dialog).getByRole("checkbox", { name: "Open moved files in editor" })).toBeInTheDocument();
const target = within(dialog).getByRole("textbox", { name: "Target directory" });
expect(target).toHaveValue(ROOT);
expect(within(dialog).getByRole("alert")).toHaveTextContent("Already in this directory");
fireEvent.change(target, { target: { value: "src" } });
fireEvent.click(within(dialog).getByRole("button", { name: "Refactor" }));
await waitFor(() => expect(fs.nodes.has("/w/acme/src/README.md")).toBe(true));
expect(fs.nodes.has("/w/acme/README.md")).toBe(false);
});
it("deletes the selection after confirmation", async () => {
dispatchViaKeymap();
const { tree, row, rows } = setup();
await waitFor(() => expect(rows()).toContain("README.md"));
fireEvent.mouseDown(row("README.md"));
tree.focus();
fireEvent.keyDown(tree, { key: "Delete", code: "Delete" });
const dialog = await screen.findByRole("dialog", { name: "Delete" });
expect(dialog).toHaveTextContent("Delete 'README.md'?");
fireEvent.click(within(dialog).getByRole("button", { name: "Delete" }));
await waitFor(() => expect(rows()).not.toContain("README.md"));
expect(fs.nodes.has("/w/acme/README.md")).toBe(false);
});
it("refreshes from fsChanged events keeping expansion", async () => {
const { rows } = setup();
act(() => useProjectTree.setState({ expanded: new Set([ROOT, "/w/acme/src"]) }));
await waitFor(() => expect(rows()).toContain("App.kt"));
await act(() => fs.createFile("/w/acme/src/New.kt"));
await waitFor(() =>
expect(rows()).toEqual(["acme/w/acme", "build", "src", "App.kt", "New.kt", "Util.kt", "README.md"]),
);
});
it("renders large folders virtualized", async () => {
for (let i = 0; i < 10_000; i++) fs.nodes.set(`/w/acme/big/f${i}.txt`, { kind: "file", size: 1 });
fs.nodes.set("/w/acme/big", { kind: "dir" });
const { tree } = setup();
act(() => useProjectTree.setState({ expanded: new Set([ROOT, "/w/acme/big"]) }));
await waitFor(() => expect(useProjectTree.getState().listings.get("/w/acme/big")?.length).toBe(10_000));
const rendered = within(tree).getAllByRole("treeitem").length;
expect(rendered).toBeLessThan(80);
});
describe("inline editor in a folder scrolled out of view", () => {
// jsdom has no layout: keep the scroll offset the virtualizer writes and report it back.
function scrollable(tree: HTMLElement) {
let top = 0;
Object.defineProperty(tree, "scrollTop", {
configurable: true,
get: () => top,
set: (v: number) => void (top = v),
});
tree.scrollTo = ((opts: ScrollToOptions) => {
top = opts.top ?? top;
tree.dispatchEvent(new Event("scroll"));
}) as Element["scrollTo"];
return (to: number) => act(() => tree.scrollTo({ top: to }));
}
async function scrolledBigFolder() {
for (let i = 0; i < 300; i++)
fs.nodes.set(`/w/acme/big/f${String(i).padStart(3, "0")}.txt`, { kind: "file", size: 1 });
fs.nodes.set("/w/acme/big", { kind: "dir" });
const view = setup();
const scroll = scrollable(view.tree);
act(() => useProjectTree.setState({ expanded: new Set([ROOT, "/w/acme/big"]) }));
await waitFor(() => expect(view.rows()).toContain("f000.txt"));
scroll(250 * 22);
await waitFor(() => expect(view.rows()).not.toContain("f000.txt"));
return { ...view, scroll };
}
it("brings a new file's name field into view", async () => {
await scrolledBigFolder();
await act(() => beginNew("file", "/w/acme/big"));
expect(await screen.findByRole("textbox", { name: "New file name" })).toHaveFocus();
});
it("keeps the viewport when the edited row is already in view", async () => {
const { tree, rows } = await scrolledBigFolder();
expect(rows()).toContain("f240.txt");
const top = tree.scrollTop;
act(() => beginRename(selectModel(useProjectTree.getState()).byKey.get("/w/acme/big/f240.txt")!));
expect(await screen.findByRole("textbox", { name: "New name" })).toHaveFocus();
expect(tree.scrollTop).toBe(top);
});
it("brings a renamed file's name field into view", async () => {
const { rows } = await scrolledBigFolder();
expect(rows()).not.toContain("f001.txt");
act(() => beginRename(selectModel(useProjectTree.getState()).byKey.get("/w/acme/big/f001.txt")!));
expect(await screen.findByRole("textbox", { name: "New name" })).toHaveFocus();
});
});
});
describe("Show Members", () => {
const APP = "/w/acme/src/App.kt";
const expand = (tree: HTMLElement, label: string, row: (l: string) => HTMLElement) => {
fireEvent.mouseDown(row(label));
tree.focus();
fireEvent.keyDown(tree, { key: "ArrowRight" });
};
it("shows a file's members and opens the symbol on double click", async () => {
ipc.docOpen.mockResolvedValue(ok({ id: 7 }));
ipc.docClose.mockResolvedValue(ok(null));
ipc.docOutline.mockResolvedValue(
ok([item("App", "class", 0, [item("render", "method", 4)]), item("main", "function", 10)]),
);
const { tree, row, rows } = setup();
act(() => useProjectTree.setState({ expanded: new Set([ROOT, "/w/acme/src"]) }));
await waitFor(() => expect(rows()).toContain("App.kt"));
act(() => setViewOption("showMembers", true));
expand(tree, "App.kt", row);
await waitFor(() => expect(rows()).toContain("main"));
expect(rows()).toEqual(expect.arrayContaining(["App.kt", "App", "main"]));
// Nested members appear when the member row itself is expanded.
const appMember = within(tree)
.getAllByRole("treeitem")
.find((r) => r.textContent === "App")!;
fireEvent.mouseDown(appMember);
fireEvent.keyDown(tree, { key: "ArrowRight" });
await waitFor(() => expect(rows()).toContain("render"));
// Activating a member jumps to its declaration, not the file row.
fireEvent.doubleClick(row("main"));
const [path, opts] = openFile.mock.calls.at(-1)!;
expect(path).toBe(APP);
expect(opts).toMatchObject({ focus: true, selection: { line: 10, col: 0 } });
});
it.each([true, false])(
"loads restored expanded files when Show Members becomes enabled (initially %s)",
async (enabled) => {
ipc.docOpen.mockResolvedValue(ok({ id: 7 }));
ipc.docClose.mockResolvedValue(ok(null));
ipc.docOutline.mockResolvedValue(ok([item("restored", "function", 3)]));
localStorage.setItem(`openidea.projectTree.expanded:${ROOT}`, JSON.stringify([ROOT, "/w/acme/src", APP]));
initProjectTree(ROOT, "acme");
setViewOption("showMembers", enabled);
ipc.docOutline.mockClear();
const { rows, row, tree } = setup();
await waitFor(() => expect(rows()).toContain("App.kt"));
if (!enabled) {
expect(rows()).not.toContain("Loading…");
expect(row("App.kt")).not.toHaveAttribute("aria-expanded");
expect(ipc.docOutline).not.toHaveBeenCalled();
act(() => setViewOption("showMembers", true));
}
await waitFor(() => expect(rows()).toContain("restored"));
expect(ipc.docOutline).toHaveBeenCalledTimes(1);
fireEvent.mouseDown(row("restored"));
tree.focus();
fireEvent.keyDown(tree, { key: "Enter" });
expect(openFile).toHaveBeenLastCalledWith(
APP,
expect.objectContaining({ focus: true, selection: expect.objectContaining({ line: 3 }) }),
);
act(() => setViewOption("showMembers", false));
expect(rows()).not.toContain("restored");
expect(rows()).not.toContain("Loading…");
expect(ipc.docOutline).toHaveBeenCalledTimes(1);
},
);
it.each([true, false])("autoscrolls to source with preview tabs set to %s", async (preview) => {
const { rows, row } = setup();
setPreviewTabSetting(preview);
act(() => {
setViewOption("autoscrollToSource", true);
setViewOption("singleClickOpen", false);
});
await waitFor(() => expect(rows()).toContain("README.md"));
fireEvent.mouseDown(row("README.md"));
await waitFor(() =>
expect(openFile).toHaveBeenLastCalledWith("/w/acme/README.md", { preview, focus: false, external: false }),
);
});
it("honours member single-click options and double-click focus", async () => {
ipc.docOpen.mockResolvedValue(ok({ id: 7 }));
ipc.docClose.mockResolvedValue(ok(null));
ipc.docOutline.mockResolvedValue(ok([item("main", "function", 10)]));
const { rows, row } = setup();
act(() => {
setViewOption("showMembers", true);
setViewOption("autoscrollToSource", false);
setViewOption("singleClickOpen", false);
useProject.setState({ settings: previewTabSettings(false) });
useProjectTree.setState({ expanded: new Set([ROOT, "/w/acme/src", APP]) });
});
await waitFor(() => expect(rows()).toContain("main"));
const content = () => row("main").querySelector("[data-project-key]")!;
fireEvent.click(content(), { detail: 1 });
expect(openFile).not.toHaveBeenCalled();
setPreviewTabSetting(true);
fireEvent.click(content(), { detail: 1 });
expect(openFile).toHaveBeenLastCalledWith(
APP,
expect.objectContaining({ preview: true, focus: false, selection: expect.objectContaining({ line: 10 }) }),
);
act(() => setViewOption("singleClickOpen", true));
fireEvent.click(content(), { detail: 1 });
expect(openFile).toHaveBeenLastCalledWith(
APP,
expect.objectContaining({ preview: undefined, focus: false, selection: expect.objectContaining({ line: 10 }) }),
);
openFile.mockClear();
fireEvent.click(content(), { detail: 1, metaKey: true });
fireEvent.click(content(), { detail: 2 });
expect(openFile).not.toHaveBeenCalled();
fireEvent.doubleClick(content());
expect(openFile).toHaveBeenCalledTimes(1);
expect(openFile).toHaveBeenLastCalledWith(
APP,
expect.objectContaining({ focus: true, selection: expect.objectContaining({ line: 10 }) }),
);
});
it("refreshes once per editor save and defers collapsed or disabled outlines", async () => {
ipc.docOpen.mockResolvedValue(ok({ id: 7 }));
ipc.docClose.mockResolvedValue(ok(null));
ipc.docOutline.mockResolvedValue(ok([item("main", "function", 0)]));
const { rows } = setup();
act(() => {
setViewOption("showMembers", true);
useProjectTree.setState({ expanded: new Set([ROOT, "/w/acme/src", APP]) });
});
await waitFor(() => expect(rows()).toContain("main"));
ipc.docOutline.mockClear();
ipc.docOutline.mockResolvedValue(ok([item("saved", "function", 5)]));
act(() => _emitEditorEvent({ type: "docSaved", doc: 7, path: APP }));
await waitFor(() => expect(rows()).toContain("saved"));
expect(ipc.docOutline).toHaveBeenCalledTimes(1);
act(() => useProjectTree.setState({ expanded: new Set([ROOT, "/w/acme/src"]) }));
act(() => _emitEditorEvent({ type: "docSaved", doc: 7, path: APP }));
expect(useProjectTree.getState().outlines.has(APP)).toBe(false);
expect(ipc.docOutline).toHaveBeenCalledTimes(1);
act(() => useProjectTree.setState({ expanded: new Set([ROOT, "/w/acme/src", APP]) }));
await waitFor(() => expect(rows()).toContain("saved"));
expect(ipc.docOutline).toHaveBeenCalledTimes(2);
act(() => setViewOption("showMembers", false));
act(() => _emitEditorEvent({ type: "docSaved", doc: 7, path: APP }));
expect(useProjectTree.getState().outlines.has(APP)).toBe(false);
expect(ipc.docOutline).toHaveBeenCalledTimes(2);
});
it.each([false, true])("discards an outline invalidated during loading (old request fails: %s)", async (fail) => {
ipc.docOpen.mockResolvedValue(ok({ id: 7 }));
ipc.docClose.mockResolvedValue(ok(null));
const old = deferred<ReturnType<typeof ok<OutlineItem[]>>>();
const fresh = deferred<ReturnType<typeof ok<OutlineItem[]>>>();
ipc.docOutline.mockClear();
ipc.docOutline.mockReturnValueOnce(old.promise).mockReturnValueOnce(fresh.promise);
const { rows } = setup();
act(() => {
setViewOption("showMembers", true);
useProjectTree.setState({ expanded: new Set([ROOT, "/w/acme/src", APP]) });
});
await waitFor(() => expect(ipc.docOutline).toHaveBeenCalledTimes(1));
act(() => _emitEditorEvent({ type: "docSaved", doc: 7, path: APP }));
await waitFor(() => expect(ipc.docOutline).toHaveBeenCalledTimes(2));
await act(async () => {
if (fail) old.reject(new Error("stale failure"));
else old.resolve(ok([item("stale", "function", 0)]));
});
expect(useProjectTree.getState().outlines.has(APP)).toBe(false);
// Completing the obsolete request must not remove the new request's dedupe entry.
let pending: Promise<void>;
act(() => {
pending = loadOutline(APP);
});
expect(ipc.docOutline).toHaveBeenCalledTimes(2);
await act(async () => {
fresh.resolve(ok([item("fresh", "function", 1)]));
await pending;
});
await waitFor(() => expect(rows()).toContain("fresh"));
expect(rows()).not.toContain("stale");
expect(ipc.docOutline).toHaveBeenCalledTimes(2);
});
it("collapses a file whose members cannot be read", async () => {
ipc.docOpen.mockResolvedValue(ok({ id: 7 }));
ipc.docClose.mockResolvedValue(ok(null));
ipc.docOutline.mockRejectedValue(new Error("unsupported"));
const { tree, row, rows } = setup();
await waitFor(() => expect(rows()).toContain("README.md"));
act(() => setViewOption("showMembers", true));
const chevron = () => row("README.md").querySelector("[data-tree-toggle]")!;
expect(chevron().hasChildNodes()).toBe(true);
expand(tree, "README.md", row);
await waitFor(() => expect(chevron().hasChildNodes()).toBe(false));
expect(rows()).not.toContain("main");
});
it("refreshes members when the file changes on disk", async () => {
ipc.docOpen.mockResolvedValue(ok({ id: 7 }));
ipc.docClose.mockResolvedValue(ok(null));
ipc.docOutline.mockResolvedValue(ok([item("main", "function", 0)]));
const { tree, row, rows } = setup();
act(() => useProjectTree.setState({ expanded: new Set([ROOT, "/w/acme/src"]) }));
await waitFor(() => expect(rows()).toContain("App.kt"));
act(() => setViewOption("showMembers", true));
expand(tree, "App.kt", row);
await waitFor(() => expect(rows()).toContain("main"));
ipc.docOutline.mockClear();
ipc.docOutline.mockResolvedValue(ok([item("main", "function", 0), item("helper", "function", 5)]));
// An unrelated change keeps the cached outline.
await act(() => fs.createFile("/w/acme/src/New.kt"));
expect(ipc.docOutline).not.toHaveBeenCalled();
// Modifying the file itself drops the cache and refetches while expanded.
await act(async () => void fs.onChange?.({ created: [], modified: [APP], removed: [] }));
await waitFor(() => expect(rows()).toContain("helper"));
});
});
it("sorts workspace member roots by the folder names shown in the tree", async () => {
fs = new MemoryFs({
"/a/service10/ten.txt": "",
"/z/Service2/two.txt": "",
"/m/alpha/first.txt": "",
"/workspace/.openidea/workspace.json": "{}",
});
setProjectFsForTests(fs, "/workspace");
initProjectTree("/workspace", "Workspace", ["/a/service10", "/z/Service2", "/m/alpha"]);
const { rows } = setup();
await waitFor(() =>
expect(rows()).toEqual([
"alpha/m/alpha",
"first.txt",
"Service2/z/Service2",
"two.txt",
"service10/a/service10",
"ten.txt",
]),
);
});
it("hides the path beside workspace roots when Show Root Paths is off, keeping it on hover", async () => {
fs = new MemoryFs({
"/a/service/one.txt": "",
"/b/web/two.txt": "",
"/workspace/.openidea/workspace.json": "{}",
});
setProjectFsForTests(fs, "/workspace");
initProjectTree("/workspace", "Workspace", ["/a/service", "/b/web"]);
const { rows } = setup();
await waitFor(() => expect(rows()).toContain("service/a/service"));
act(() => setViewOption("showRootPaths", false));
await waitFor(() => expect(rows()).toEqual(["service", "one.txt", "web", "two.txt"]));
const root = document.querySelector('[data-project-path="/a/service"]');
expect(root?.getAttribute("title")).toBe("/a/service");
act(() => setViewOption("showRootPaths", true));
});
describe("File Details", () => {
const modifiedAt = new Date(2026, 10, 28, 12).getTime();
const modified = "28.11.2026 12:00";
beforeEach(() => {
useProject.setState({
settings: {
general: {
dateFormat: { overrideSystem: true, pattern: "dd.MM.yyyy", use24Hour: true, pretty: false },
},
},
});
});
it("formats concise sizes and the configured modification date", () => {
expect(formatFileDetails(null)).toBeNull();
expect(formatFileDetails({ size: 0, mtimeMs: modifiedAt })).toBe(`${modified}, 0 B`);
expect(formatFileDetails({ size: 1023, mtimeMs: modifiedAt })).toBe(`${modified}, 1023 B`);
expect(formatFileDetails({ size: 1024, mtimeMs: modifiedAt })).toBe(`${modified}, 1 KB`);
expect(formatFileDetails({ size: 1536, mtimeMs: modifiedAt })).toBe(`${modified}, 1.5 KB`);
expect(formatFileDetails({ size: 1_048_575, mtimeMs: modifiedAt })).toBe(`${modified}, 1 MB`);
});
it.each([null, 0])("shows only the size when mtimeMs is %s", (mtimeMs) => {
expect(formatFileDetails({ size: 512, mtimeMs })).toBe("512 B");
});
it("toggles File Details from Appearance and persists the option", () => {
const { result } = renderHook(() => useProjectHeaderMenu());
type Item = Extract<MenuItem, { id?: string }>;
const toggle = () =>
((result.current.find((item) => "label" in item && item.label === "Appearance") as Item).submenu as Item[]).find(
(item) => item.id === "showFileDetails",
)!;
expect(toggle()).toMatchObject({ label: "File Details", checked: false });
act(() => toggle().run!());
expect(toggle().checked).toBe(true);
expect(JSON.parse(localStorage.getItem("openidea.projectTree.options")!)).toMatchObject({ showFileDetails: true });
const action = getAction("project.option.showFileDetails")!;
expect(action.toggled!()).toBe(true);
act(() => void executeAction(action.id));
expect(toggle().checked).toBe(false);
expect(JSON.parse(localStorage.getItem("openidea.projectTree.options")!)).toMatchObject({ showFileDetails: false });
});
it("renders metadata on file rows only without changing root paths", async () => {
const readDir = fs.readDir.bind(fs);
vi.spyOn(fs, "readDir").mockImplementation(async (path) =>
(await readDir(path)).map((entry) => ({
...entry,
size: entry.kind === "file" ? 1536 : 2048,
mtimeMs: modifiedAt,
})),
);
const { row, rows } = setup();
await waitFor(() => expect(rows()).toContain("README.md"));
expect(row("acme").textContent).toBe("acme/w/acme");
expect(row("src").textContent).toBe("src");
expect(row("build").textContent).toBe("build");
act(() => setViewOption("showFileDetails", true));
const detail = `${modified}, 1.5 KB`;
expect(row("README.md").textContent).toBe(`README.md${detail}`);
expect(within(row("README.md")).getByTitle(detail)).toBeInTheDocument();
expect(row("acme").textContent).toBe("acme/w/acme");
expect(row("src").textContent).toBe("src");
expect(row("build").textContent).toBe("build");
act(() => setViewOption("showFileDetails", false));
expect(row("README.md").textContent).toBe("README.md");
expect(row("acme").textContent).toBe("acme/w/acme");
});
});
it("shows a decoration's suffix after the root name, with icons and struck-out segments", async () => {
const { row } = setup();
await waitFor(() => expect(row("acme")).toBeTruthy());
act(() =>
setFileDecorations(
"test-suffix",
new Map([
[
ROOT,
{
suffixColor: "var(--accent)",
suffix: [
{ text: "main" },
{ text: "/" },
{ text: "0", strike: true, label: "Up to date with origin/main" },
{ text: "2", icon: "vcs-outgoing", label: "2 outgoing commits" },
],
},
],
]),
),
);
await waitFor(() => expect(row("acme").textContent).toContain("main/02"));
const root = row("acme");
expect(root.querySelector("s")?.textContent).toBe("0");
expect(root.querySelector("s")?.closest("[style]")?.getAttribute("style")).toContain("var(--accent)");
expect(within(root).getByLabelText("2 outgoing commits").querySelector("svg")).not.toBeNull();
expect(within(root).getByLabelText("Up to date with origin/main").textContent).toBe("0");
act(() => setFileDecorations("test-suffix", new Map()));
await waitFor(() => expect(row("acme").textContent).not.toContain("main/"));
});
it("shows a decoration's display label and icon in place of the physical name", async () => {
const { row } = setup();
await waitFor(() => expect(row("src")).toBeTruthy());
act(() => setFileDecorations("test-label", new Map([[`${ROOT}/src`, { label: "Orders", icon: "db-postgres" }]])));
await waitFor(() => expect(row("Orders")).toBeTruthy());
const content = row("Orders").querySelector("[data-project-path]");
expect(content).toHaveAttribute("data-project-path", `${ROOT}/src`);
expect(content).toHaveAttribute("data-project-icon", "db-postgres");
expect(screen.queryByText("src")).not.toBeInTheDocument();
act(() => setFileDecorations("test-label", new Map()));
await waitFor(() => expect(row("src")).toBeTruthy());
});
it("marks file and folder symlinks with the link arrow, leaving real folders and files alone", async () => {
fs = new MemoryFs(
{
"/w/acme/dir1/keep.txt": "x",
"/w/acme/dir2/keep.txt": "x",
"/w/acme/note.txt": "x",
},
ROOT,
// `ln -s dir1 link1` on macOS/Linux; the backend reports kind "symlink", size 0.
{ "/w/acme/link1": "/w/acme/dir1", "/w/acme/note-link.txt": "/w/acme/note.txt" },
);
setProjectFsForTests(fs, ROOT);
initProjectTree(ROOT, "acme");
const { row } = setup();
const iconAt = (label: string) => row(label).querySelector("[data-project-path]")?.getAttribute("data-project-icon");
await waitFor(() => expect(row("link1")).toBeTruthy());
// The link to a folder carries the arrow (IDEA's symlink badge)…
expect(within(row("link1")).getByLabelText("Symbolic link").tagName).toBe("svg");
expect(iconAt("link1")).toBe("folder");
expect(iconAt("dir1")).toBe("folder");
// …so does a link to a file, as in IDEA; real folders and files do not.
expect(within(row("note-link.txt")).getByLabelText("Symbolic link").tagName).toBe("svg");
expect(iconAt("note-link.txt")).toBe("file-text");
expect(within(row("dir1")).queryByLabelText("Symbolic link")).toBeNull();
expect(within(row("dir2")).queryByLabelText("Symbolic link")).toBeNull();
expect(within(row("note.txt")).queryByLabelText("Symbolic link")).toBeNull();
});