import { clearContext, setContext } from "@/platform/context"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { registerActions } from "@/platform/actions"; import { useProject } from "@/platform/project"; import { useBuildPresentation } from "@/platform/projectPresentation"; import { useProjectRoots } from "@/platform/projectRoots"; import { useRemote } from "@/platform/remote"; import { resolveMenuItems, type MenuItem } from "@/ui"; import { registerMenuGroup } from "@/workbench/contributions"; import { contextMenuItems, keyLabel, revealLabel } from "./contextMenu"; import type { ProjectNode } from "./model"; import { useProjectTree } from "./store"; import { closePopup, useLspPopup } from "@/editor/lsp/popupStore"; import { _provideCopyPathChooser } from "@/editor/api"; import { openCopyPathChooser } from "@/editor/core/copyPathChooser"; _provideCopyPathChooser(openCopyPathChooser); vi.mock("@/platform/ipc", async (importOriginal) => ({ ...(await importOriginal()), isTauri: () => true, })); const ROOT = "/p"; const SCRATCHES = "/config/scratches"; const node = (path: string, dir = false, root = false): ProjectNode => ({ key: path, path, chain: [path], label: path.slice(path.lastIndexOf("/") + 1), dir, root, entry: null, ignored: false, excluded: false, symlink: false, }); /** Labels as the menu shows them ("-" for separators). */ const labels = (items: MenuItem[]) => resolveMenuItems(items).map((r) => (r.kind === "separator" ? "-" : r.label)); const sub = (items: MenuItem[], label: string) => { const item = resolveMenuItems(items).find((r) => r.label === label); return item?.submenu ? labels(item.submenu) : undefined; }; const OTHER_ACTIONS = [ "find.inPath", "find.replaceInPath", "code.reformatFile", "code.optimizeImportsFile", "terminal.openAt", "vcs.localHistory", "localHistory.putLabel", "diff.compareWith", "diff.compareFiles", "diff.compareDirectories", "diff.compareFileWithEditor", "vcs.commit", "vcs.addToVcs", "vcs.annotate", "vcs.showDiff", "vcs.compareWithBranch", "vcs.compareWithRevision", "vcs.showCurrentRevision", "vcs.rollback", "vcs.push", ]; let disposers: Array<() => void> = []; beforeEach(() => { useProjectTree.setState({ root: ROOT }); useProject.setState({ project: { name: "p", root: ROOT, trusted: true, isGit: true, settings: {} } as never, settings: {} as never, }); disposers = [ registerActions(OTHER_ACTIONS.map((id) => ({ id, title: id, run: () => undefined }))), registerMenuGroup({ id: "test.run", menus: ["projectView"], items: (_menu, ctx) => ctx.paths.length === 1 && !ctx.dirs?.[0] ? [{ label: "Run 'a'", icon: "run", run: () => undefined }] : [], }), ]; }); afterEach(() => { closePopup(); disposers.forEach((d) => d()); useProject.setState({ project: null, settings: null }); useProjectTree.setState({ root: null }); useProjectRoots.setState({ root: null, detected: [] }); useRemote.setState({ session: null }); }); describe("project view context menu", () => { it("offers directory comparison only for two folders and Compare With for a single folder", () => { expect(labels(contextMenuItems([node("/p/left", true), node("/p/right", true)]))).toContain("Compare Directories"); expect(labels(contextMenuItems([node("/p/left", true)]))).toContain("Compare With…"); const mixed = labels(contextMenuItems([node("/p/left", true), node("/p/a.txt")])); for (const label of ["Compare Directories", "Compare Files", "Compare With…"]) expect(mixed).not.toContain(label); expect(labels(contextMenuItems([node("/p/a.txt"), node("/p/b.txt")]))).toContain("Compare Files"); }); it("offers Compare File with Editor for a single file other than the editor's", () => { const label = "Compare File with Editor"; expect(labels(contextMenuItems([node("/p/a.txt")]))).not.toContain(label); setContext("editorPath", "/p/b.txt"); try { const items = labels(contextMenuItems([node("/p/a.txt")])); expect(items.indexOf(label)).toBe(items.indexOf("Compare With…") + 1); expect(labels(contextMenuItems([node("/p/b.txt")]))).not.toContain(label); expect(labels(contextMenuItems([node("/p/left", true)]))).not.toContain(label); expect(labels(contextMenuItems([node("/p/a.txt"), node("/p/c.txt")]))).not.toContain(label); setContext("editorPath", "git-revision:7b22/a.txt"); expect(labels(contextMenuItems([node("/p/a.txt")]))).not.toContain(label); } finally { clearContext("editorPath"); } }); it("shows Compare With…'s shortcut on every comparison it runs (#3806)", () => { const shortcut = (nodes: ProjectNode[], label: string) => resolveMenuItems(contextMenuItems(nodes)).find((r) => r.label === label)?.shortcut; const expected = keyLabel("project.compareWith"); expect(expected).toBeTruthy(); expect(shortcut([node("/p/a.txt"), node("/p/b.txt")], "Compare Files")).toBe(expected); expect(shortcut([node("/p/left", true), node("/p/right", true)], "Compare Directories")).toBe(expected); expect(shortcut([node("/p/left", true)], "Compare With…")).toBe(expected); }); it("offers Open Module Settings on modules and source roots, above Mark Directory as, with F4 / ⌘↓ on a module", () => { const opened: unknown[] = []; const dispose = registerActions([ { id: "project.openModuleSettings", title: "Open Module Settings", run: ({ arg }) => void opened.push(arg) }, ]); useProjectRoots.setState({ root: ROOT, detected: [{ path: "app/src", kind: "source", detectedFrom: "maven" }] }); useBuildPresentation.setState({ modules: new Map([["app", "maven"]]) }); try { const find = (n: ProjectNode) => resolveMenuItems(contextMenuItems([n])).find((r) => r.label === "Open Module Settings"); // The project folder and a module folder: F4 / ⌘↓ opens it there. expect(find(node("/p", true, true))?.shortcut).toBe(keyLabel("project.open")); expect(find(node("/p/app", true))?.shortcut).toBe(keyLabel("project.open")); // A sources root: listed, without the shortcut, above Mark Directory as. const srcItems = labels(contextMenuItems([node("/p/app/src", true)])); expect(srcItems.indexOf("Open Module Settings")).toBeGreaterThan(-1); expect(srcItems.indexOf("Open Module Settings")).toBeLessThan(srcItems.indexOf("Mark Directory as")); expect(find(node("/p/app/src", true))?.shortcut).toBeUndefined(); find(node("/p/app/src", true))?.run?.(); expect(opened).toEqual(["/p/app/src"]); // Not for plain folders, files, several nodes or outside the project. expect(find(node("/p/docs", true))).toBeUndefined(); expect(find(node("/p/app/src/A.java"))).toBeUndefined(); expect(labels(contextMenuItems([node("/p", true, true), node("/p/app", true)]))).not.toContain( "Open Module Settings", ); expect(labels(contextMenuItems([node(`${SCRATCHES}/s.txt`)]))).not.toContain("Open Module Settings"); } finally { useBuildPresentation.setState({ modules: new Map() }); dispose(); } }); it("offers Git for repositories found below a non-Git project root", () => { useProject.setState({ project: { name: "p", root: ROOT, trusted: true, isGit: false, settings: {} } as never }); expect(sub(contextMenuItems([node("/p/a.py")]), "Git")).toBeUndefined(); setContext("vcsAvailable", true); try { expect(sub(contextMenuItems([node("/p/a.py")]), "Git")).toContain("Commit File…"); } finally { clearContext("vcsAvailable"); } }); it("passes the selected Project view directory to Commit…", () => { const items = contextMenuItems([node("/p/module", true)]); const git = items.find((item) => item.kind !== "separator" && item.kind !== "header" && item.label === "Git"); const commit = git && "submenu" in git ? git.submenu?.find((item) => item.kind !== "separator" && item.kind !== "header" && item.label === "Commit…") : undefined; expect(commit).toMatchObject({ kind: "action", action: "vcs.commit", arg: "/p/module" }); }); it("offers the GitHub group in the Git menu, like the editor menus do", () => { const dispose = registerActions( ["github.pullRequests", "github.createPullRequest", "github.checkoutPullRequest", "github.openInBrowser"].map( (id) => ({ id, title: id, when: "projectOpen", run: () => undefined }), ), ); try { const git = resolveMenuItems(contextMenuItems([node(`${ROOT}/a.py`)])).find((r) => r.label === "Git")!; const isLabelled = (i: MenuItem): i is Extract => "label" in i; const subs = git.submenu!.filter(isLabelled).find((i) => i.label === "GitHub")?.submenu; expect(subs && resolveMenuItems(subs).map((i) => i.key)).toEqual([ "github.pullRequests", "github.createPullRequest", "github.checkoutPullRequest", "github.openInBrowser", ]); } finally { dispose(); } }); /** Runs Copy Path/Reference… and returns the chooser's rows as `label: preview`. */ const chooser = (items: MenuItem[]) => { const item = resolveMenuItems(items).find((r) => r.label === "Copy Path/Reference…"); expect(item?.submenu).toBeUndefined(); item!.run!(); const popup = useLspPopup.getState().popup; return popup?.kind === "list" ? popup.items.map((i) => `${i.label}: ${i.preview}`) : undefined; }; it("previews each way Copy Path/Reference… copies the selection, contributed links included", () => { disposers.push( registerMenuGroup({ id: "test.link", menus: ["copyPath"], items: (_menu, ctx) => [ { id: "test.link", label: "Link", verbatim: true, preview: `${ctx.paths.join()} ${ctx.dirs?.join()}`, run: () => undefined, }, // Without a preview a contribution has nothing to show in the chooser. { id: "test.bare", label: "Bare", run: () => undefined }, ], }), ); expect(chooser(contextMenuItems([node("/p/src", true), node("/p/src/a.ts")], { x: 10, y: 20 }))).toEqual([ "Absolute Path: /p/src\n/p/src/a.ts", "File Name: src\na.ts", "Path From Content Root: src\nsrc/a.ts", "Link: /p/src,/p/src/a.ts true,false", ]); expect(useLspPopup.getState().popup).toMatchObject({ layout: "copyPath", anchor: { x: 10, y: 20 } }); }); it("offers the fully qualified name of Java classes and packages in Copy Path/Reference…", () => { useProjectRoots.setState({ root: ROOT, detected: [ { path: "src/main/java", kind: "source", detectedFrom: "pom.xml" }, { path: "src/test/java", kind: "test", detectedFrom: "pom.xml" }, { path: "web/src", kind: "source", detectedFrom: "web/package.json" }, ], }); const reference = (nodes: ProjectNode[]) => chooser(contextMenuItems(nodes))?.filter((r) => r.startsWith("Reference:")); expect( reference([node("/p/src/main/java/com/example/App.java"), node("/p/src/main/java/com/example", true)]), ).toEqual(["Reference: com.example.App\ncom.example"]); expect(reference([node("/p/src/main/java/Main.java")])).toEqual(["Reference: Main"]); expect(reference([node("/p/src/test/java/com/example/AppTest.java")])).toEqual(["Reference: com.example.AppTest"]); // Not a Java class or package: the source root itself, other files, non-JVM roots, a mixed selection. for (const nodes of [ [node("/p/src/main/java", true)], [node("/p/src/main/java/com/example/app.properties")], [node("/p/src/main/java/com/example/package-info.java")], [node("/p/src/main/java/module-info.java")], [node("/p/src/main/java/com/my-app", true)], [node("/p/src/main/java/com/my-app/App.java")], [node("/p/web/src/App.java")], [node("/p/web/src/lib", true)], [node("/p/src/main/java/com/example/App.java"), node("/p/README.md")], ]) expect(reference(nodes)).toEqual([]); }); it("offers no content root paths for library files in Copy Path/Reference…", () => { disposers.push( registerMenuGroup({ id: "test.link", menus: ["copyPath"], items: (_menu, ctx) => [ { id: "test.link", label: "Link", verbatim: true, preview: ctx.paths.join(), run: () => undefined }, ], }), ); expect(chooser(contextMenuItems([{ ...node("/root/.m2/lib.jar"), readOnly: true }]))).toEqual([ "Absolute Path: /root/.m2/lib.jar", "File Name: lib.jar", "Link: /root/.m2/lib.jar", ]); }); it("groups clipboard, search, file changes, formatting and history actions for a file", () => { const items = contextMenuItems([node(`${ROOT}/src/a.py`)]); expect(labels(items)).toEqual([ "New", "-", "Cut", "Copy", "Copy Path/Reference…", "Paste", "Jump to Source", "-", "Find Usages", "Find in Files…", "Replace in Files…", "-", "Rename…", "Refactor", "Delete…", "-", "Reformat Code", "Optimize Imports", "-", "Run 'a'", "-", "Open in Right Split", "Open In", "-", "Local History", "Git", "Reload from Disk", "-", "Compare With…", "-", "File Color", ]); expect(sub(items, "Refactor")).toEqual(["Rename…", "Move File…", "Copy File…", "-", "Safe Delete…"]); expect(sub(items, "File Color")).toEqual([ "Blue", "Green", "Orange", "Rose", "Violet", "Yellow", "Gray", "-", "Edit File Colors…", ]); expect(sub(items, "Open In")).toEqual([revealLabel(), "Associated Application", "Terminal"]); expect(sub(items, "Git")?.slice(0, 4)).toEqual(["Commit File…", "Add", "-", "Annotate with Git Blame"]); }); it("offers both ignore destinations for files, directories and multi-selection, separately from IDE exclusion", () => { const dispose = registerActions( ["vcs.ignoreShared", "vcs.ignoreLocal"].map((id) => ({ id, title: id, run: () => undefined })), ); try { for (const nodes of [[node("/p/a")], [node("/p/dir", true)], [node("/p/a"), node("/p/dir", true)]]) { const git = resolveMenuItems(contextMenuItems(nodes)).find((item) => item.label === "Git")!; expect(sub(git.submenu!, "Add to .gitignore")).toEqual([".gitignore", ".git/info/exclude"]); } const root = resolveMenuItems(contextMenuItems([node("/p", true, true)])).find((item) => item.label === "Git")!; expect(labels(root.submenu!)).not.toContain("Add to .gitignore"); const folder = contextMenuItems([node("/p/dir", true)]); expect(sub(folder, "Mark Directory as")).toContain("Excluded"); } finally { dispose(); } }); it("hides the OS file manager in an SSH or dev-container window, whose files are not on this desktop", () => { const library = { ...node("/root/.m2/lib.jar"), readOnly: true }; expect(sub(contextMenuItems([library]), "Open In")).toEqual([revealLabel(), "Associated Application"]); for (const target of [ { kind: "ssh", config: "box" }, { kind: "devContainer", folder: "/Users/me/app", config: "" }, ] as const) { useRemote.setState({ session: { target, root: ROOT, host: "h", os: "linux", commands: [] } }); expect(sub(contextMenuItems([node(`${ROOT}/src/a.py`)]), "Open In")).toEqual(["Terminal"]); expect(labels(contextMenuItems([library]))).not.toContain("Open In"); } }); it("offers Download to… for remote project files only (#4718)", () => { const off = registerActions([{ id: "project.downloadTo", title: "Download to…", run: () => undefined }]); try { const files = [node(`${ROOT}/src`, true), node(`${ROOT}/a.py`)]; expect(labels(contextMenuItems(files))).not.toContain("Download to…"); useRemote.setState({ session: { target: { kind: "ssh", config: "box" }, root: ROOT, host: "h", os: "linux", commands: [] }, }); const l = labels(contextMenuItems(files)); expect(l.indexOf("Download to…")).toBe(l.indexOf("Open In") + 1); expect(labels(contextMenuItems([node(`${SCRATCHES}/s.py`)]))).not.toContain("Download to…"); } finally { off(); } }); it("offers file revision actions only for a single file", () => { expect(sub(contextMenuItems([node("/p/a.py")]), "Git")).toEqual( expect.arrayContaining(["Compare with Revision…", "Show Current Revision"]), ); for (const nodes of [[node("/p/src", true)], [node("/p/a.py"), node("/p/b.py")]]) { expect(sub(contextMenuItems(nodes), "Git")).not.toContain("Compare with Revision…"); expect(sub(contextMenuItems(nodes), "Git")).not.toContain("Show Current Revision"); } }); it("offers branch comparison for files, folders, their union and the project root", () => { for (const nodes of [ [node("/p/a.py")], [node("/p/src", true)], [node("/p/src", true), node("/p/lib", true)], [node("/p", true, true)], ]) { expect(sub(contextMenuItems(nodes), "Git")).toContain("Compare with Branch…"); } }); it("offers Show History for files, directories, multi-selection and the project root", () => { const dispose = registerActions([{ id: "vcs.showHistory", title: "Show History", run: () => undefined }]); try { for (const nodes of [ [node("/p/a.py")], [node("/p/src", true)], [node("/p/a.py"), node("/p/src", true)], [node("/p", true, true)], ]) { expect(sub(contextMenuItems(nodes), "Git")).toContain("Show History"); } } finally { dispose(); } }); it("shows Mark Directory as for folders, without file-only items", () => { const l = labels(contextMenuItems([node(`${ROOT}/src`, true)])); expect(l.slice(l.indexOf("Rename…"), l.indexOf("Rename…") + 4)).toEqual(["Rename…", "Refactor", "Delete…", "-"]); expect(l.slice(-4)).toEqual(["Compare With…", "-", "Mark Directory as", "File Color"]); expect(sub(contextMenuItems([node(`${ROOT}/src`, true)]), "Refactor")).toContain("Move Directory…"); for (const fileOnly of ["Find Usages", "Optimize Imports", "Run 'a'", "Open in Right Split"]) expect(l).not.toContain(fileOnly); }); it("offers Reformat Code for a directory and a multiple selection, through the Reformat Code dialog", () => { const calls: Array<[string, unknown]> = []; disposers.push( registerActions( ["code.reformatFile", "code.reformatFiles"].map((id) => ({ id, title: id, run: ({ arg }) => void calls.push([id, arg]), })), ), ); const reformat = (nodes: ProjectNode[]) => { const item = resolveMenuItems(contextMenuItems(nodes)).find((r) => r.label === "Reformat Code"); item?.run?.(); return calls.pop(); }; expect(reformat([node("/p/a.py")])).toEqual(["code.reformatFile", { path: "/p/a.py" }]); expect(reformat([node("/p/bin", true)])).toEqual(["code.reformatFiles", { files: [], directories: ["/p/bin"] }]); expect(reformat([node("/p/a.sh"), node("/p/b.sh")])).toEqual([ "code.reformatFiles", { files: ["/p/a.sh", "/p/b.sh"], directories: [] }, ]); expect(reformat([node("/p/a.sh"), node("/p/lib", true)])).toEqual([ "code.reformatFiles", { files: ["/p/a.sh"], directories: ["/p/lib"] }, ]); expect(reformat([node(ROOT, true, true)])).toEqual(["code.reformatFiles", { files: [], directories: [ROOT] }]); }); it("offers Import Module from Existing Sources on the project root only", () => { const off = registerActions([ { id: "maven.importExternal", title: "Import Module from Existing Sources", run: () => undefined }, ]); try { expect(labels(contextMenuItems([node(ROOT, true, true)]))).toContain("Import Module from Existing Sources"); expect(labels(contextMenuItems([node(`${ROOT}/src`, true)]))).not.toContain( "Import Module from Existing Sources", ); } finally { off(); } }); it("keeps the project root menu short and disables what cannot apply", () => { const items = contextMenuItems([node(ROOT, true, true)]); const l = labels(items); expect(l).not.toContain("Rename…"); expect(l).not.toContain("Refactor"); expect(l).not.toContain("Mark Directory as"); const resolved = resolveMenuItems(items); for (const label of ["Cut", "Copy", "Delete…"]) expect(resolved.find((r) => r.label === label)?.disabled).toBe(true); }); it("drops project-only groups for scratch files", () => { const l = labels(contextMenuItems([node(`${SCRATCHES}/s.py`)])); expect(l).not.toContain("Git"); expect(l).not.toContain("Find Usages"); expect(l).toContain("Refactor"); expect(l).toContain("Reload from Disk"); }); it("offers Compare Files for two files", () => { const l = labels(contextMenuItems([node(`${ROOT}/a.py`), node(`${ROOT}/b.py`)])); expect(l).not.toContain("Rename…"); expect(l).toContain("Compare Files"); expect(l).not.toContain("Compare With…"); }); it("offers Compare With… in a non-git project too", () => { useProject.setState({ project: { name: "p", root: ROOT, trusted: true, isGit: false, settings: {} } as never, settings: {} as never, }); const l = labels(contextMenuItems([node(`${ROOT}/a.py`)])); expect(l).not.toContain("Git"); expect(l).toContain("Compare With…"); expect(labels(contextMenuItems([node(`${ROOT}/a.py`), node(`${ROOT}/b.py`)]))).toContain("Compare Files"); }); it("never shows an empty submenu", () => { disposers.forEach((d) => d()); disposers = []; useProject.setState({ project: { name: "p", root: ROOT, trusted: true, isGit: true, settings: {} } as never, settings: {} as never, }); const l = labels(contextMenuItems([node(`${ROOT}/a.py`)])); expect(l).not.toContain("Git"); expect(l).not.toContain("Local History"); expect(l).not.toContain("Find in Files…"); }); }); it("offers workspace removal for every member root", () => { useProject.setState({ project: { root: "/workspace", name: "A", settings: {}, trusted: true, isGit: false, workspace: { version: 1, name: "A", projects: ["/a", "/b"] }, }, }); const removal = { kind: "action", action: "workspace.removeProject", arg: "/b", }; expect(contextMenuItems([node("/b", true, true)])).toContainEqual(removal); expect(contextMenuItems([node("/a", true, true)])).toContainEqual( expect.objectContaining({ action: "workspace.removeProject" }), ); expect(contextMenuItems([node("/b/src", true)])).not.toContainEqual( expect.objectContaining({ action: "workspace.removeProject" }), ); }); it("offers Git and Find Usages in workspace members outside the workspace folder", () => { useProject.setState({ project: { root: "/work/workspaces/demo", name: "demo", settings: {}, trusted: true, isGit: false, workspace: { version: 1, name: "demo", projects: ["/work/repos/a", "/work/repos/b"] }, }, }); setContext("vcsAvailable", true); try { for (const target of [node("/work/repos/a", true, true), node("/work/repos/a/src", true)]) expect(sub(contextMenuItems([target]), "Git")).toContain("Commit…"); expect(sub(contextMenuItems([node("/work/repos/a/x.py")]), "Git")).toContain("Annotate with Git Blame"); expect(labels(contextMenuItems([node("/work/repos/a/x.py")]))).toContain("Find Usages"); // Project structure is the workspace folder's: its roots can't name a folder outside it. expect(labels(contextMenuItems([node("/work/repos/a/src", true)]))).not.toContain("Mark Directory as"); // Scratches stay outside. expect(sub(contextMenuItems([node("/config/scratches/s.py")]), "Git")).toBeUndefined(); } finally { clearContext("vcsAvailable"); } }); it("does not offer removal on the attached primary", () => { useProject.setState({ project: { root: "/a", name: "A", displayName: "A, b", trusted: true, isGit: false, settings: {}, workspace: { version: 1, name: "A", projects: ["/a", "/b"] }, }, }); expect(contextMenuItems([node("/a", true, true)])).not.toContainEqual( expect.objectContaining({ action: "project.detach" }), ); expect(contextMenuItems([node("/b", true, true)])).toContainEqual( expect.objectContaining({ action: "project.detach" }), ); });