Файли
openidea/src/features/project-tree/contextMenu.ts
T
Mansur Akhmadiтаmansur-akhmadi 61d269045b feat(vcs): Compare File with Editor action (#6364)
Adds Compare File with Editor: the file selected in the Project view (or passed as the argument) is diffed against the active editor's file, opened at the editor's caret line, with swappable sides. The Project view context menu offers it right after Compare With… for a single file other than the editor's; virtual documents, folders, multiple files and the editor's own file get an explanatory notification instead. It is unbound in the presets and mapped from imported keymaps via CompareFileWithEditor.

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-27 15:12:02 +08:00

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

Цей файл містить неоднозначні символи Юнікоду
Цей файл містить символи Юнікоду, які можна сплутати з іншими символами. Якщо ви вважаєте, що це зроблено навмисно, можете сміливо ігнорувати це попередження. Щоб показати їх, скористайтеся кнопкою Escape.
/** Context menu and "New" popup of the project view. */
import { openCopyPathChooser } from "@/editor/api";
import { executeAction, getAction } from "@/platform/actions";
import type { PathKind } from "@/platform/copyPath";
import { getContext } from "@/platform/context";
import { canOpenWithSystemApp, canRevealInFileManager, fileManagerName } from "@/platform/fileManager";
import { formatBinding, hostBinding, isMacHost, shortcutLabel } from "@/platform/keymap";
import { projectFolder, relativePath, useProject } from "@/platform/project";
import { attachedProjectOf, currentDetectedRoots, currentRoots } from "@/platform/projectRoots";
import { isVirtualUri } from "@/platform/virtualDocs";
import type { MenuItem } from "@/ui";
import { menuGroupItems, gitMenuItems, toolWindowService, type MenuGroupContext } from "@/workbench/contributions";
import type { FolderRole } from "@/platform/languageSettings";
import { directoryRole, markDirectory } from "./markDirectory";
import { fileColorMenu } from "./fileColor";
import type { ProjectNode } from "./model";
import { packageKindAt } from "./packages";
import {
beginNew,
beginNewPackage,
canPaste,
copyPaths,
copySelection,
pathsFor,
delegate,
deleteSelection,
findFileUsages,
folderOf,
openCopyDialog,
openFile,
openMoveDialog,
openRenameDialog,
openSelectionInRightSplit,
paste,
openWithAssociatedApp,
reformatNodes,
reloadFromDisk,
revealInFinder,
} from "./operations";
import { canDownload } from "./download";
import { isSameOrInside } from "./paths";
import { useProjectTree } from "./store";
import { tx, txPart } from "@/platform/i18n";
/** Keys handled by the project view itself (the default keymap has no entries for them). */
export const LOCAL_KEYS: Record<string, string> = {
"project.newMenu": "Meta+N",
"project.rename": "Shift+F6",
"project.move": "F6",
"project.delete": "Delete",
"project.copy": "Meta+C",
"project.cut": "Meta+X",
"project.paste": "Meta+V",
"project.copyAbsolutePath": "Meta+Shift+C",
"project.open": "F4",
};
export const keyLabel = (id: string) =>
shortcutLabel(id) ?? (LOCAL_KEYS[id] ? formatBinding(hostBinding(LOCAL_KEYS[id])) : undefined);
/**
* The comparison for a selection, shared by the context menu and Compare With… (⌘D): two folders,
* two files or one node. Mixed file/folder selections cannot apply.
*/
export function compareTarget(nodes: ProjectNode[]): { action: string; arg: unknown; label: string } | null {
if (nodes.length === 2 && nodes.every((n) => n.dir && !n.placeholder))
return { action: "diff.compareDirectories", arg: nodes.map((n) => n.path), label: "Compare Directories" };
if (nodes.length === 2 && nodes.every((n) => !n.dir))
return { action: "diff.compareFiles", arg: nodes.map((n) => n.path), label: "Compare Files" };
const single = nodes.length === 1 ? nodes[0]! : null;
if (!single || single.placeholder) return null;
const arg = single.dir ? { path: single.path, directory: true } : single.path;
return { action: "diff.compareWith", arg, label: "Compare With…" };
}
/**
* New › items for `parent`. `outsideTree` (⌘N in the editor): File asks for the
* name in a dialog, and the inline Directory / Package editors bring up the project view.
*/
export function newMenuItems(parent: string | null, { outsideTree = false } = {}): MenuItem[] {
const root = useProject.getState().project?.root;
const rel = parent && root ? (parent === root ? "" : relativePath(root, parent)) : null;
const pkg = rel === null ? null : packageKindAt(rel, currentRoots(), currentDetectedRoots());
const inline = (start: () => Promise<void>) => () => {
if (outsideTree) showProjectView();
void start();
};
const emptyFile = outsideTree && parent && getAction("templates.new.file");
const dir: MenuItem = {
id: "new.dir",
label: "Directory",
icon: "folder",
run: inline(() => beginNew("dir", parent)),
};
return [
emptyFile
? {
id: "new.file",
label: "File",
icon: "file",
run: () => void executeAction(emptyFile.id, { directory: parent }),
}
: { id: "new.file", label: "File", icon: "file", run: inline(() => beginNew("file", parent)) },
// IDEA offers "Package" instead of "Directory" inside a Java / Kotlin source root.
pkg === "jvm"
? { id: "new.package", label: "Package", icon: "package", run: inline(() => beginNewPackage("jvm", parent)) }
: dir,
...(pkg === "python"
? [
{
id: "new.pythonPackage",
label: "Python Package",
icon: "package",
run: inline(() => beginNewPackage("python", parent)),
},
]
: []),
...contributedNewItems(parent),
];
}
function showProjectView() {
try {
toolWindowService().show("project", false);
} catch {
/* tool window service not available (tests) */
}
}
/** File kinds contributed to the `new` menu group (templates, HTTP Request, Scratch File…). */
function contributedNewItems(parent: string | null): MenuItem[] {
const owner = parent ? projectFolder(useProject.getState().project, parent) : null;
const projectType =
parent && owner && isSameOrInside(parent, owner.root)
? useProjectTree.getState().projectTypes.get(owner.root)
: undefined;
const items = menuGroupItems("new", parent ? { paths: [parent], dirs: [true], projectType } : { paths: [] });
return items.length ? [{ kind: "separator" }, ...items] : [];
}
/** An item bound to another feature's action (resolved by the menu: hidden when missing, disabled when off). */
function act(action: string, arg?: unknown, label?: string): MenuItem | null {
return getAction(action) ? { kind: "action", action, arg, label } : null;
}
/** Runs another feature's action directly (the project view decides availability), with its shortcut. */
function delegated(
id: string,
arg: unknown,
label: string,
extra: { icon?: string; shortcut?: string } = {},
): MenuItem | null {
if (!getAction(id)) return null;
return { id, label, ...extra, shortcut: extra.shortcut ?? shortcutLabel(id), run: () => void delegate(id, arg) };
}
type Entry = MenuItem | null | false | undefined;
/** Where a menu opens; popups its items open appear there. */
type MenuPoint = { x: number; y: number } | "center";
/** A submenu of the present entries, or nothing when none is left (never an empty submenu). */
function submenu(id: string, label: string, entries: Entry[], icon?: string): MenuItem | null {
const items = entries.filter((i): i is MenuItem => !!i);
if (!items.some((i) => i.kind !== "separator" && i.kind !== "header")) return null;
return { id, label, icon, submenu: items };
}
/** Project view actions available for the selected files and directories. */
/** `at`: where the menu opens, for the popups its items open (Copy Path/Reference…). */
export function contextMenuItems(nodes: ProjectNode[], at: MenuPoint = "center"): MenuItem[] {
if (nodes.some((n) => n.readOnly))
return libraryMenuItems(
nodes.filter((n) => !n.group),
at,
);
const lead = nodes[0] ?? null;
const single = nodes.length === 1 ? lead : null;
const nonRoot = nodes.filter((n) => !n.root);
const folder = folderOf(lead);
const files = nodes.filter((n) => !n.dir);
const singleFile = single && !single.dir ? single : null;
const project = useProject.getState().project;
// Scratches and other contributed roots live outside the project: no VCS, roots or LSP usages.
const inProject = !!project && nodes.every((n) => isSameOrInside(n.path, project.root));
// Workspace members may live outside the workspace folder; they have VCS and usages too.
const memberRoots = project ? [project.root, ...(project.workspace?.projects ?? [])] : [];
const inWorkspace = nodes.every((n) => memberRoots.some((root) => isSameOrInside(n.path, root)));
const items: MenuItem[] = [];
const push = (...list: Entry[]) => list.forEach((i) => i && items.push(i));
if (
single &&
project?.workspace &&
single.path !== project.root &&
project.workspace.projects.includes(single.path)
) {
push(
{
kind: "action",
action: project.workspace.projects[0] === project.root ? "project.detach" : "workspace.removeProject",
arg: single.path,
},
{ kind: "separator" },
);
}
push(
{ id: "new", label: "New", submenu: newMenuItems(folder) },
single?.root && act("maven.importExternal", undefined, "Import Module from Existing Sources"),
{ kind: "separator" },
);
// Clipboard and opening files.
push(
{
id: "cut",
label: "Cut",
icon: "cut",
shortcut: keyLabel("project.cut"),
disabled: !nonRoot.length,
run: () => copySelection(true),
},
{
id: "copy",
label: "Copy",
icon: "copy",
shortcut: keyLabel("project.copy"),
disabled: !nonRoot.length,
run: () => copySelection(false),
},
copyPathItem(nodes, at, false),
{
id: "paste",
label: "Paste",
icon: "paste",
shortcut: keyLabel("project.paste"),
disabled: !canPaste(),
run: () => void paste(folder),
},
files.length > 0 && {
id: "jumpToSource",
label: "Jump to Source",
icon: "edit",
shortcut: keyLabel("project.open"),
run: () => files.forEach((f) => void openFile(f.path)),
},
{ kind: "separator" },
);
push(
inWorkspace &&
singleFile && {
id: "findUsages",
label: "Find Usages",
shortcut: keyLabel("project.findUsages"),
run: () => void findFileUsages(singleFile.path),
},
!!folder && delegated("find.inPath", { directory: folder }, "Find in Files…", { icon: "search" }),
!!folder && delegated("find.replaceInPath", { directory: folder }, "Replace in Files…"),
{ kind: "separator" },
);
const rename: Entry = single &&
!single.root && {
id: "rename",
label: "Rename…",
shortcut: keyLabel("project.rename"),
run: () => void openRenameDialog(single),
};
push(
rename,
submenu("refactor", "Refactor", [
rename,
nonRoot.length > 0 && {
id: "move",
label: nonRoot.length === 1 ? (nonRoot[0]!.dir ? "Move Directory…" : "Move File…") : "Move…",
shortcut: keyLabel("project.move"),
run: () => openMoveDialog(nonRoot),
},
nonRoot.length > 0 && {
id: "copy",
label: nonRoot.length === 1 ? (nonRoot[0]!.dir ? "Copy Directory…" : "Copy File…") : "Copy…",
shortcut: keyLabel("project.copyElement"),
run: () => openCopyDialog(nonRoot),
},
nonRoot.length > 0 && { kind: "separator" },
nonRoot.length > 0 && {
id: "safeDelete",
label: "Safe Delete…",
shortcut: formatBinding(isMacHost() ? "Meta+Backspace" : "Delete"),
run: () => void deleteSelection(nodes),
},
]),
{
id: "delete",
label: "Delete…",
shortcut: keyLabel("project.delete"),
disabled: !nonRoot.length,
run: () => void deleteSelection(nodes),
},
{ kind: "separator" },
);
push(
nodes.some((n) => !n.group) &&
getAction(singleFile ? "code.reformatFile" : "code.reformatFiles") && {
id: "reformat",
label: "Reformat Code",
shortcut: keyLabel("project.reformatCode"),
run: () => void reformatNodes(nodes),
},
singleFile &&
getAction("code.optimizeImportsFile") && {
id: "optimizeImports",
label: "Optimize Imports",
shortcut: keyLabel("project.optimizeImports"),
run: () => void delegate("code.optimizeImportsFile", { path: singleFile.path }),
},
{ kind: "separator" },
);
// Contributed groups (Run / Debug '…', More Run/Debug ›), each followed by a separator.
push(...menuGroupItems("projectView", menuGroupContext(nodes)));
// Open in Right Split / Open In ›
push(
files.length > 0 && openInRightSplitItem(files),
submenu("openIn", "Open In", [
canRevealInFileManager() && {
id: "finder",
label: revealLabel(),
icon: "external-link",
run: () => void revealInFinder(nodes),
},
files.length > 0 &&
canOpenWithSystemApp() && {
id: "associatedApp",
label: "Associated Application",
icon: "external-link",
run: () => void openWithAssociatedApp(files),
},
folder && getAction("terminal.openAt")
? { id: "terminal", label: "Terminal", icon: "terminal", run: () => void delegate("terminal.openAt", folder) }
: null,
{ kind: "separator" },
...menuGroupItems("openIn", menuGroupContext(nodes)),
]),
inWorkspace &&
canDownload() &&
delegated(
"project.downloadTo",
nodes.map((n) => n.path),
"Download to…",
{ icon: "download" },
),
{ kind: "separator" },
);
push(
single &&
submenu("history", "Local History", [
delegated("vcs.localHistory", single.path, "Show History"),
delegated("localHistory.putLabel", undefined, "Put Label…"),
]),
);
// Git › (`vcsAvailable` also covers repositories nested below a non-Git project root)
if (inWorkspace && (project?.isGit || getContext().vcsAvailable === true)) {
const dirs = nodes.map((n) => n.dir);
push(
submenu(
"git",
"Git",
[
// Shared with the editor and editor tab menus (IDEA keeps the per-menu groups in sync).
...gitMenuItems({
paths: nodes.map((n) => n.path),
dirs,
file: !!singleFile,
ignore: nonRoot.length === nodes.length && nodes.length > 0 && nodes.every((n) => !n.placeholder),
}),
],
"branch",
),
);
}
push(
{
id: "reload",
label: "Reload from Disk",
icon: "refresh",
shortcut: keyLabel("project.reloadFromDisk"),
run: () => void reloadFromDisk(nodes),
},
{ kind: "separator" },
);
const compare = compareTarget(nodes);
if (compare)
push(
delegated(compare.action, compare.arg, compare.label, {
icon: "diff",
shortcut: keyLabel("project.compareWith"),
}),
);
const editorPath = getContext().editorPath;
if (
single &&
!single.dir &&
!single.placeholder &&
typeof editorPath === "string" &&
editorPath &&
!isVirtualUri(editorPath) &&
editorPath !== single.path
)
push(delegated("diff.compareFileWithEditor", single.path, "Compare File with Editor", { icon: "diff" }));
push({ kind: "separator" });
// An attached project keeps its own excluded folders; its other roles aren't applied yet.
const attached = !inProject && single?.dir ? attachedProjectOf(single.path) : null;
if ((inProject || attached) && single?.dir && !single.root && !single.placeholder) {
const current = directoryRole(single.path);
const roles: Array<[FolderRole, string, string]> = (
[
["source", "Sources Root", "folder-source"],
["test", "Test Sources Root", "folder-test"],
["resources", "Resources Root", "folder-resources"],
["testResources", "Test Resources Root", "folder-test-resources"],
["excluded", "Excluded", "folder-excluded"],
] as Array<[FolderRole, string, string]>
).filter(([role]) => !attached || role === "excluded");
push({
id: "markAs",
label: "Mark Directory as",
submenu: [
...roles
.filter(([role]) => role !== current)
.map(([role, label, icon]) => ({ id: role, label, icon, run: () => void markDirectory(single.path, role) })),
...(current && (!attached || current === "excluded")
? [
{
id: "unmark",
label:
current === "excluded"
? "Cancel Exclusion"
: tx`Unmark as ${txPart(roles.find(([r]) => r === current)![1])}`,
run: () => void markDirectory(single.path, null),
},
]
: []),
],
});
}
if (inProject && single && !single.root && !single.placeholder && !single.group) {
const color = fileColorMenu(single.path, single.dir);
if (color) push(color);
}
return items;
}
function openInRightSplitItem(files: ProjectNode[]): MenuItem {
return {
id: "openInRightSplit",
label: "Open in Right Split",
icon: "split",
shortcut: keyLabel("project.openInRightSplit"),
run: () => void openSelectionInRightSplit(files),
};
}
/** Library sources (External Libraries) are read-only: copy, find and reveal only. */
function libraryMenuItems(nodes: ProjectNode[], at: MenuPoint): MenuItem[] {
if (!nodes.length) return [];
const single = nodes.length === 1 ? nodes[0]! : null;
const folder = single?.dir ? single.path : null;
const items: Entry[] = [
{ id: "copy", label: "Copy", icon: "copy", shortcut: keyLabel("project.copy"), run: () => copySelection(false) },
copyPathItem(nodes, at, true),
{ kind: "separator" },
!!folder && delegated("find.inPath", { directory: folder }, "Find in Files…", { icon: "search" }),
!!folder && { kind: "separator" },
nodes.every((n) => !n.dir) && openInRightSplitItem(nodes),
submenu("openIn", "Open In", [
canRevealInFileManager() && {
id: "finder",
label: revealLabel(),
icon: "external-link",
run: () => void revealInFinder(nodes),
},
nodes.every((n) => !n.dir) &&
canOpenWithSystemApp() && {
id: "associatedApp",
label: "Associated Application",
icon: "external-link",
run: () => void openWithAssociatedApp(nodes),
},
]),
single &&
!single.dir &&
delegated("diff.compareWith", single.path, "Compare With…", {
icon: "diff",
shortcut: keyLabel("project.compareWith"),
}),
];
return items.filter((i): i is MenuItem => !!i);
}
export function revealLabel() {
return fileManagerName();
}
/**
* Copy Path/Reference…: a chooser previewing what each way copies for the selection (several
* paths one per line), contributed links and references included. Library files have no
* content or source root.
*/
function copyPathItem(nodes: ProjectNode[], at: MenuPoint, library: boolean): Entry {
const row = (kind: PathKind, id: string, label: string) => {
const paths = pathsFor(kind, nodes);
return {
id,
label,
// A selection only partly under a source root has no source-root path.
preview: paths.length && paths.length === nodes.length ? paths.join("\n") : null,
run: () => void copyPaths(kind, nodes),
};
};
return {
id: "copyPath",
label: "Copy Path/Reference…",
run: () =>
openCopyPathChooser(
at,
[
row("absolute", "project.copyAbsolutePath", "Absolute Path"),
row("name", "project.copyFileName", "File Name"),
...(library
? []
: [
row("relative", "project.copyRelativePath", "Path From Content Root"),
row("source", "project.copySourceRootPath", "Path From Source Root"),
]),
],
menuGroupContext(nodes),
),
};
}
/** What contributed menu groups see: the selected (non-placeholder) paths. */
export function menuGroupContext(nodes: ProjectNode[]): MenuGroupContext {
const real = nodes.filter((n) => !n.placeholder);
return { paths: real.map((n) => n.path), dirs: real.map((n) => n.dir) };
}