feat(build): add Build › Recompile for a single Java file (#5587)

Build › Recompile '<file>.java' (Shift+Cmd+F9 / Ctrl+Shift+F9, moved from Build Module, which keeps no default shortcut) compiles only the active Java file with javac and streams its output and diagnostics to the Build tool window. The menu, editor, tab and Project view entries name the file and are enabled only for local .java files.

- Maven modules resolve the classpath of the file's scope (compile for main sources, test for test sources) through dependency:build-classpath; the probe is now cancellable.
- Gradle projects get the source set's output, compile classpath, source folders and release from an init script.
- Projects without a build tool compile against their Project Structure roots, outputs and libraries.
- In a workspace the file's member project is used.
- javac gets -g, omits an empty -cp, and uses -source/-target on JDK 8; localized javac error and warning prefixes are parsed.

Co-authored-by: RuyimgByCN <[email protected]>
Цей коміт міститься в:
RuyimgByCN authored and GitHub committed 2026-11-25 00:59:59 +08:00
1 джерело d729ae8122
коміт 748e5cee89
25 files changed
+1038 -150

No files matched your search

+4 -5
Переглянути файл
@@ -234,11 +234,10 @@ export const commands = {
/** Applies a (previewed) workspace edit, e.g. after rename confirmation. */
applyWorkspaceEdit: (edit: WorkspaceEdit) => typedError<null, IdeError>(__TAURI_INVOKE("apply_workspace_edit", { edit })),
/**
* Build › Compile File: compiles one Java source of a linked Maven module with
* `javac`, streaming the console and messages on `on_event`; cancellable with
* `cancel_request(request)`. Diagnostics of `clear` (the files of the previous
* build) are cleared first; the new messages are published as `build`
* diagnostics.
* Build › Recompile: compiles one Java source file with `javac`, streaming the
* console and messages on `on_event`; cancellable with `cancel_request(request)`.
* Diagnostics of `clear` (the files of the previous build) are cleared first;
* the new messages are published as `build` diagnostics.
*/
buildCompileFile: (file: string, request: RequestId, clear: string[], onEvent: Channel<BuildEvent>) => typedError<BuildResult, IdeError>(__TAURI_INVOKE("build_compile_file", { file, request, clear, onEvent })),
/** Maven and Gradle projects of the window's project, from the build files plus the last sync. */
+65
Переглянути файл
@@ -182,6 +182,48 @@ describe("menu state from the frontend", () => {
setContext("testMenuEditor", false);
offs.forEach((d) => d());
});
it("re-pushes menu config when switching Java files, and skips non-Java switches", async () => {
vi.useFakeTimers();
vi.spyOn(ipc, "isTauri").mockReturnValue(true);
vi.spyOn(document, "hasFocus").mockReturnValue(true);
vi.spyOn(ipc.commands, "appBuildInfo").mockRejectedValue(new Error("No build info in tests"));
const configure = vi.spyOn(ipc.commands, "menuConfigure").mockResolvedValue();
vi.spyOn(ipc.commands, "menuModel").mockResolvedValue([]);
vi.spyOn(ipc.commands, "menuSetDisabled").mockResolvedValue();
const dispose = installMenuBridge();
try {
await vi.advanceTimersByTimeAsync(120);
configure.mockClear();
setContext("editorPath", "/p/src/A.java");
await vi.advanceTimersByTimeAsync(60);
expect(configure).toHaveBeenCalledTimes(1);
expect(configure.mock.calls.at(-1)![0].labels["menu.build.compileFile"]).toBe("Recompile 'A.java'");
configure.mockClear();
setContext("editorPath", "/p/src/B.java");
await vi.advanceTimersByTimeAsync(60);
expect(configure).toHaveBeenCalledTimes(1);
expect(configure.mock.calls.at(-1)![0].labels["menu.build.compileFile"]).toBe("Recompile 'B.java'");
configure.mockClear();
setContext("editorPath", "/p/pom.xml");
await vi.advanceTimersByTimeAsync(60);
expect(configure).toHaveBeenCalledTimes(1);
expect(configure.mock.calls.at(-1)![0].labels["menu.build.compileFile"]).toBe("Recompile");
configure.mockClear();
setContext("editorPath", "/p/README.md");
await vi.advanceTimersByTimeAsync(60);
expect(configure).not.toHaveBeenCalled();
} finally {
dispose();
clearContext("editorPath");
vi.useRealTimers();
vi.restoreAllMocks();
}
});
});
afterEach(() => {
@@ -223,6 +265,7 @@ describe("menu config", () => {
const mac = buildMenuConfig("macos");
expect(mac.accelerators["file.save"]).toBe("Meta+S");
expect(mac.accelerators["navigate.gotoFile"]).toBe("Shift+Meta+O");
expect(mac.accelerators["build.compileFile"]).toBe("Shift+Meta+F9");
expect(mac.accelerators["navigate.searchEverywhere"]).toBeUndefined();
});
@@ -289,6 +332,28 @@ describe("window-scoped menu labels", () => {
expect(buildMenuConfig("macos").labels["menu.editor.toggleZen"]).toBe("Exit Distraction Free Mode");
resetDistractionFree();
});
it("formats Recompile with the active local Java filename across locales", async () => {
try {
expect(buildMenuConfig("macos").labels["menu.build.compileFile"]).toBe("Recompile");
setContext("editorPath", "/p/src/Main.java");
expect(buildMenuConfig("macos").labels["menu.build.compileFile"]).toBe("Recompile 'Main.java'");
setContext("editorPath", "/p/pom.xml");
expect(buildMenuConfig("macos").labels["menu.build.compileFile"]).toBe("Recompile");
setContext("editorPath", "jdt://contents/rt.jar/java/lang/String.java");
expect(buildMenuConfig("macos").labels["menu.build.compileFile"]).toBe("Recompile");
setContext("editorPath", "untitled:Untitled-1.java");
expect(buildMenuConfig("macos").labels["menu.build.compileFile"]).toBe("Recompile");
await setLocale("zh");
setContext("editorPath", null);
expect(buildMenuConfig("macos").labels["menu.build.compileFile"]).toBe("重新编译");
setContext("editorPath", "/p/src/Main.java");
expect(buildMenuConfig("macos").labels["menu.build.compileFile"]).toBe("重新编译 'Main.java'");
} finally {
clearContext("editorPath");
}
});
});
describe("View › Appearance check marks", () => {
+7 -7
Переглянути файл
@@ -21,7 +21,8 @@ import {
} from "@/platform/keymap";
import { useProject } from "@/platform/project";
import { useContributions, useMenuSlotItems, useStandaloneEditor } from "@/workbench/contributions";
import { isDistractionFree, useDistractionFree } from "@/workbench/distractionFree";
import { useDistractionFree } from "@/workbench/distractionFree";
import { javaFileNameOf, menuLabelParams } from "@/workbench/menuLabels";
import { orderStatusItems } from "@/workbench/StatusBar";
import { statusWidgetRows } from "@/workbench/statusBarWidgets";
import { useToolWindowLayouts } from "@/workbench/toolwindows/layouts";
@@ -101,11 +102,7 @@ export function menuAccelerator(binding: string): string | undefined {
export function buildMenuConfig(os: HostOs): MenuConfig {
const labels: Record<string, string> = {};
// Per-window state some labels follow (View › Appearance › Enter / Exit Distraction Free Mode).
const params = {
os,
distractionFree: isDistractionFree() ? "on" : "off",
toolWindows: toolWindowsRestorable() ? "hidden" : "shown",
};
const params = menuLabelParams(os);
for (const key of keysWithPrefix("menu.")) labels[key] = t(key, params);
labels["menu.layout.applyNamed"] = tx("Apply");
labels["menu.layout.restoreNamed"] = tx("Restore");
@@ -288,7 +285,10 @@ export function installMenuBridge(): () => void {
}),
useToolWindowLayouts.subscribe(push),
useMenuSlotItems.subscribe(push),
useContextKeys.subscribe(() => pushEnablement()),
useContextKeys.subscribe((s, prev) => {
pushEnablement();
if (javaFileNameOf(s.editorPath) !== javaFileNameOf(prev.editorPath)) push();
}),
useActions.subscribe(() => pushEnablement()),
// Project membership and names also change the Open Recent list.
useProject.subscribe((s, prev) => {
+96 -3
Переглянути файл
@@ -1,8 +1,8 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen } from "@testing-library/react";
import { executeAction, getAction, isActionEnabled } from "@/platform/actions";
import { getContext, setContext } from "@/platform/context";
import { bindingsFor } from "@/platform/keymap";
import { clearContext, getContext, setContext } from "@/platform/context";
import { bindingsFor, installKeyboardDispatcher } from "@/platform/keymap";
import { IpcError, type BuildEvent, type BuildMessage, type BuildResult } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import {
@@ -179,6 +179,7 @@ describe("build feature", () => {
useProject.setState({ project: null, settings: null });
setContext("projectOpen", false);
setContext("run.cmakeBuild", null);
clearContext("editorPath");
});
it("shows the CMake hammer and builds the selected target through the shared action", async () => {
@@ -205,8 +206,11 @@ describe("build feature", () => {
expect(getAction(id), id).toBeDefined();
expect(isActionEnabled(getAction(id)!)).toBe(true);
}
expect(getAction("build.compileFile")).toBeDefined();
expect(isActionEnabled(getAction("build.compileFile")!)).toBe(false);
expect(bindingsFor("build.buildProject")).toContain("Meta+F9");
expect(bindingsFor("build.buildModule")).toContain("Meta+Shift+F9");
expect(bindingsFor("build.compileFile")).toContain("Meta+Shift+F9");
expect(bindingsFor("build.buildModule")).toEqual([]);
const tw = useContributions.getState().toolWindows.get("build");
expect(tw).toMatchObject({ anchor: "bottom", stripe: "onUse", icon: "toolwindow-build" });
expect(menuGroupItems("projectView", { paths: ["/p/core"] })).toContainEqual({
@@ -569,4 +573,93 @@ describe("build feature", () => {
fake.resolve(result([], true));
});
});
it("gates Recompile to local Java files and offers context menu labels", () => {
const compileFile = getAction("build.compileFile")!;
let currentPath: string | null = "/p/core/src/A.java";
provideEditorService({
openFile,
saveAll: () => Promise.resolve(),
activePath: () => currentPath,
} as unknown as EditorService);
expect(isActionEnabled(compileFile)).toBe(true);
for (const nonTarget of [
"/p/core/pom.xml",
"jdt://contents/rt.jar/java/lang/String.class",
"untitled:Untitled-1.java",
null,
]) {
currentPath = nonTarget;
expect(isActionEnabled(compileFile), String(nonTarget)).toBe(false);
}
expect(isActionEnabled(compileFile, getContext(), "/p/core/src/Explicit.java")).toBe(true);
for (const menu of ["editor", "editorTab", "projectView"] as const) {
expect(menuGroupItems(menu, { paths: ["/p/core/src/A.java"] })).toContainEqual({
kind: "action",
action: "build.compileFile",
arg: "/p/core/src/A.java",
label: "Recompile 'A.java'",
});
expect(
menuGroupItems(menu, { paths: ["jdt://contents/rt.jar/java/lang/String.java"] }).some(
(i) => i.kind === "action" && i.action === "build.compileFile",
),
).toBe(false);
}
});
it("dispatches Shift+Cmd+F9 to Recompile for the active Java file only", async () => {
let currentPath: string | null = "/p/core/src/OnlyThis.java";
provideEditorService({
openFile,
saveAll: () => Promise.resolve(),
activePath: () => currentPath,
} as unknown as EditorService);
const uninstall = installKeyboardDispatcher(window);
try {
fireEvent.keyDown(window, { code: "F9", key: "F9", metaKey: true, shiftKey: true });
await act(async () => {});
expect(fake.calls).toEqual([{ kind: "compileFile", file: "/p/core/src/OnlyThis.java", clear: [] }]);
expect(isActionEnabled(getAction("build.compileFile")!)).toBe(false);
await act(async () => {
fake.resolve(result([], true));
});
currentPath = "/p/core/pom.xml";
fireEvent.keyDown(window, { code: "F9", key: "F9", metaKey: true, shiftKey: true });
await act(async () => {});
expect(fake.calls).toHaveLength(1);
} finally {
uninstall();
}
});
it("streams single-file compile errors to BuildView and opens the first error", async () => {
const run = startCompileFile("/p/core/src/Broken.java");
await act(async () => {});
const messages = [err("/p/core/src/Broken.java", 7, "cannot find symbol")];
await act(async () => {
fake.emit!({ kind: "started", system: "javac", title: "Compile Broken.java" });
fake.emit!({ kind: "step", command: "javac -encoding UTF-8 Broken.java", cwd: "/p/core" });
fake.emit!({ kind: "output", text: "/p/core/src/Broken.java:8: error: cannot find symbol\n", stderr: true });
fake.emit!({ kind: "message", message: messages[0]! });
await new Promise((r) => setTimeout(r, 30));
});
render(<BuildView />);
expect(screen.getByText("Compile Broken.java")).toBeInTheDocument();
await act(async () => {
fake.resolve({ ...result(messages, false), system: "javac", title: "Compile Broken.java" });
await run;
});
expect(useBuildRun.getState().status).toBe("failed");
expect(useBuildRun.getState().selected).toBe(firstError(messages)!.key);
expect(show).toHaveBeenCalledWith("build", false);
expect(openFile).toHaveBeenCalledWith(
"/p/core/src/Broken.java",
expect.objectContaining({ focus: true, selection: { line: 7, col: 4 } }),
);
expect(screen.getByRole("document", { name: "Build message" })).toHaveTextContent("cannot find symbol");
});
});
+26 -11
Переглянути файл
@@ -1,11 +1,14 @@
/**
* Build menu (Build Project ⌘F9, Build Module ⇧⌘F9, Rebuild Project, Build
* Artifacts) and the Build tool window. The backend picks the build system of
* the project or module: Maven, Gradle, Cargo, Go, TypeScript or CMake.
* Build menu (Build Project ⌘F9, Recompile '<file>.java' ⇧⌘F9, Build Module,
* Rebuild Project, Build Artifacts) and the Build tool window. The backend picks
* the build system of the project or module: Maven, Gradle, Cargo, Go,
* TypeScript, CMake or javac.
*/
import { getContext } from "@/platform/context";
import { getContext, type ContextKeys } from "@/platform/context";
import { registerActions } from "@/platform/actions";
import { useProject } from "@/platform/project";
import { tx } from "@/platform/i18n";
import { basename, useProject } from "@/platform/project";
import { isVirtualUri } from "@/platform/virtualDocs";
import {
maybeEditorService,
registerMenuGroup,
@@ -25,6 +28,17 @@ function moduleTarget(arg: unknown): string | null {
return maybeEditorService()?.activePath() ?? null;
}
/** The local Java source file to compile: the invoker's path or the active editor's file. */
function javaFileTarget(arg: unknown, ctx: ContextKeys = getContext()): string | null {
const path =
typeof arg === "string" && arg
? arg
: typeof arg === "object" && arg !== null && "target" in arg && typeof arg.target === "string"
? arg.target
: (maybeEditorService()?.activePath() ?? (typeof ctx.editorPath === "string" ? ctx.editorPath : null));
return path && !isVirtualUri(path) && /\.java$/i.test(path) ? path : null;
}
function useErrorBadge(): number | null {
return useBuildRun((s) =>
s.status === "failed" ? s.messages.filter((m) => m.severity === "error").length || null : null,
@@ -88,15 +102,16 @@ export function activate(): () => void {
},
{
id: "build.compileFile",
title: "Compile File",
title: "Recompile",
description: "Compiles the current Java file with javac, without building its module",
category: "Build",
when: WHEN,
keywords: ["javac", "single file", "recompile"],
run: ({ arg }) => {
enabled: ({ ctx, arg }) => javaFileTarget(arg, ctx) !== null,
keywords: ["compile file", "javac", "single file"],
run: ({ ctx, arg }) => {
const options = typeof arg === "object" && arg !== null ? arg : {};
const activate = !("activate" in options && options.activate === false);
const file = moduleTarget(arg);
const file = javaFileTarget(arg, ctx);
if (file) void startCompileFile(file, activate);
},
},
@@ -153,8 +168,8 @@ export function activate(): () => void {
order: 40,
items: (_menu, { paths, dirs }) => {
const path = paths.length === 1 && !dirs?.[0] ? paths[0]! : null;
if (!path || !/\.java$/i.test(path) || !useProject.getState().project) return [];
return [{ kind: "action", action: "build.compileFile", arg: path }];
if (!path || isVirtualUri(path) || !/\.java$/i.test(path) || !useProject.getState().project) return [];
return [{ kind: "action", action: "build.compileFile", arg: path, label: tx`Recompile '${basename(path)}'` }];
},
}),
useProject.subscribe((s, prev) => {
+2
Переглянути файл
@@ -87,6 +87,8 @@ describe("IDEA keymap parity", () => {
["navigate.back", ["Meta+[", "Meta+Alt+Left", "Button4", "SwipeRight"], ["Ctrl+Alt+Left", "Button4"]],
["navigate.forward", ["Meta+]", "Meta+Alt+Right", "Button5", "SwipeLeft"], ["Ctrl+Alt+Right", "Button5"]],
["file.projectStructure", ["Meta+;"], ["Ctrl+Alt+Shift+S"]],
["build.compileFile", ["Meta+Shift+F9"], ["Ctrl+Shift+F9"]],
["build.buildModule", [], []],
])("%s", (id, mac, win) => {
expect(intellijMacos[id]).toEqual(mac);
expect(intellijWindows[id]).toEqual(win);
+2 -1
Переглянути файл
@@ -258,7 +258,8 @@ export const intellijMacos: Record<string, string[]> = {
// Build
"build.buildProject": ["Meta+F9"],
"build.buildModule": ["Meta+Shift+F9"],
"build.buildModule": [],
"build.compileFile": ["Meta+Shift+F9"],
"build.rebuildProject": [],
"build.buildArtifacts": [],
+2 -1
Переглянути файл
@@ -252,7 +252,8 @@ export const intellijWindows: Record<string, string[]> = {
// Build
"build.buildProject": ["Ctrl+F9"],
"build.buildModule": ["Ctrl+Shift+F9"],
"build.buildModule": [],
"build.compileFile": ["Ctrl+Shift+F9"],
"build.rebuildProject": [],
"build.buildArtifacts": [],
+1
Переглянути файл
@@ -274,6 +274,7 @@ export const vscodeMacos: Record<string, string[]> = {
// Build (Terminal › Run Build Task)
"build.buildProject": ["Meta+Shift+B"],
"build.buildModule": [],
"build.compileFile": [],
"build.rebuildProject": [],
"build.buildArtifacts": [],
+1
Переглянути файл
@@ -413,6 +413,7 @@
"menu.build": "Build",
"menu.build.buildProject": "Build Project",
"menu.build.buildModule": "Build Module",
"menu.build.compileFile": "{compileFile, select, yes {Recompile '{compileFileName}'} other {Recompile}}",
"menu.build.rebuildProject": "Rebuild Project",
"menu.build.buildArtifacts": "Build Artifacts",
"menu.toolwindow.build": "Build",
+3 -1
Переглянути файл
@@ -3902,5 +3902,7 @@
"No tests ran. The build may skip them (skipTests, maven.test.skip, a disabled test task) or lack their engine: JUnit 4 tests on the JUnit Platform need junit-vintage-engine.": "No tests ran. The build may skip them (skipTests, maven.test.skip, a disabled test task) or lack their engine: JUnit 4 tests on the JUnit Platform need junit-vintage-engine.",
"Downloading the list of PyPI package names…": "Downloading the list of PyPI package names…",
"Could not load the list of PyPI package names. Type a package's exact name to look it up.": "Could not load the list of PyPI package names. Type a package's exact name to look it up.",
"Only the first 50 PyPI matches are listed. Type more of the name to narrow them.": "Only the first 50 PyPI matches are listed. Type more of the name to narrow them."
"Only the first 50 PyPI matches are listed. Type more of the name to narrow them.": "Only the first 50 PyPI matches are listed. Type more of the name to narrow them.",
"Recompile": "Recompile",
"Recompile '{name}'": "Recompile '{name}'"
}
+3 -1
Переглянути файл
@@ -10132,5 +10132,7 @@
"No tests ran. The build may skip them (skipTests, maven.test.skip, a disabled test task) or lack their engine: JUnit 4 tests on the JUnit Platform need junit-vintage-engine.": "没有运行任何测试。构建可能跳过了测试(skipTests、maven.test.skip、被禁用的测试任务),或缺少对应的测试引擎:在 JUnit Platform 上运行 JUnit 4 测试需要 junit-vintage-engine。",
"Downloading the list of PyPI package names…": "正在下载 PyPI 软件包名称列表…",
"Could not load the list of PyPI package names. Type a package's exact name to look it up.": "无法加载 PyPI 软件包名称列表。请输入软件包的准确名称进行查询。",
"Only the first 50 PyPI matches are listed. Type more of the name to narrow them.": "只列出前 50 个 PyPI 匹配项。请输入更完整的名称以缩小范围。"
"Only the first 50 PyPI matches are listed. Type more of the name to narrow them.": "只列出前 50 个 PyPI 匹配项。请输入更完整的名称以缩小范围。",
"Recompile": "重新编译",
"Recompile '{name}'": "重新编译 '{name}'"
}
+1
Переглянути файл
@@ -413,6 +413,7 @@
"menu.build": "构建",
"menu.build.buildProject": "构建项目",
"menu.build.buildModule": "构建模块",
"menu.build.compileFile": "{compileFile, select, yes {重新编译 '{compileFileName}'} other {重新编译}}",
"menu.build.rebuildProject": "重新构建项目",
"menu.build.buildArtifacts": "构建工件",
"menu.toolwindow.build": "构建",
+39
Переглянути файл
@@ -1,6 +1,7 @@
import { act, fireEvent, render, screen, within } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { commands, type Settings } from "@/platform/ipc";
import { clearContext, setContext } from "@/platform/context";
import { useProject } from "@/platform/project";
import { getAction, registerActions } from "@/platform/actions";
import { usePlatform } from "@/platform/platformInfo";
@@ -362,3 +363,41 @@ it.each(["windows", "linux"] as const)("renders toggle and widget checks in the
usePlatform.setState(platform);
}
});
it("shows Recompile '<file>.java' when a Java file is active and disabled Recompile otherwise", async () => {
const off = registerActions([
{
id: "build.compileFile",
title: "Recompile",
when: "projectOpen",
enabled: ({ ctx }) => typeof ctx.editorPath === "string" && ctx.editorPath.endsWith(".java"),
run: () => {},
},
]);
vi.mocked(commands.menuModel).mockResolvedValue([
{
kind: "submenu",
id: "build",
label: "Build",
children: [{ kind: "action", id: "build.compileFile", label: "Recompile", hint: null, arg: null, checked: null }],
},
]);
setContext("projectOpen", true);
setContext("editorPath", "/p/src/Main.java");
setStyle("merged");
try {
render(<MainMenu />);
await screen.findByRole("menubar");
fireEvent.click(titles().getByRole("menuitem", { name: "Build" }));
const activeItem = await screen.findByRole("menuitem", { name: /Recompile 'Main\.java'/ });
expect(activeItem).not.toHaveAttribute("aria-disabled", "true");
act(() => setContext("editorPath", "/p/pom.xml"));
const disabledItem = await screen.findByRole("menuitem", { name: /^Recompile/ });
expect(disabledItem).toHaveAttribute("aria-disabled", "true");
} finally {
off();
clearContext("projectOpen");
clearContext("editorPath");
}
});
+4 -7
Переглянути файл
@@ -1,6 +1,7 @@
/** Main menu for the frameless title bar, with hamburger and persistent title modes. */
import { useEffect, useLayoutEffect, useRef, useState, type KeyboardEvent } from "react";
import clsx from "clsx";
import { useContextKeys } from "@/platform/context";
import { useProject } from "@/platform/project";
import { lookup, t, useI18n } from "@/platform/i18n";
import { commands, type MenuNode } from "@/platform/ipc";
@@ -8,18 +9,13 @@ import { usePlatform } from "@/platform/platformInfo";
import { Icon, MenuList, Popup, type MenuItem } from "@/ui";
import { useChromeIconSize } from "@/ui/density";
import menuStyles from "@/ui/Menu.module.css";
import { isDistractionFree } from "./distractionFree";
import { toolWindowsRestorable } from "./toolwindows/store";
import { javaFileNameOf, menuLabelParams } from "./menuLabels";
import styles from "./TitleBar.module.css";
function label(id: string, fallback: string): string {
const key = `menu.${id}`;
if (lookup(key) === undefined) return fallback;
return t(key, {
os: usePlatform.getState().os,
distractionFree: isDistractionFree() ? "on" : "off",
toolWindows: toolWindowsRestorable() ? "hidden" : "shown",
});
return t(key, menuLabelParams(usePlatform.getState().os));
}
type Submenu = Extract<MenuNode, { kind: "submenu" }>;
@@ -102,6 +98,7 @@ export function MainMenu({ row = false, ...props }: MainMenuProps) {
function MainMenuBar({ merged, row, onExpandedChange }: MainMenuProps & { merged: boolean; row: boolean }) {
useI18n((s) => s.locale);
useContextKeys((s) => javaFileNameOf(s.editorPath));
const iconSize = useChromeIconSize();
const [menus, setMenus] = useState<Submenu[]>([]);
const [expanded, setExpanded] = useState(false);
+23
Переглянути файл
@@ -0,0 +1,23 @@
/** Parameters shared between the native menu bridge and the custom title bar menu. */
import { getContext } from "@/platform/context";
import { basename } from "@/platform/project";
import { isVirtualUri } from "@/platform/virtualDocs";
import { maybeEditorService } from "./contributions";
import { isDistractionFree } from "./distractionFree";
import { toolWindowsRestorable } from "./toolwindows/store";
export function javaFileNameOf(path: unknown): string | null {
if (typeof path !== "string" || !path || isVirtualUri(path) || !/\.java$/i.test(path)) return null;
return basename(path) || null;
}
export function menuLabelParams(os: string) {
const compileFileName = javaFileNameOf(getContext().editorPath ?? maybeEditorService()?.activePath());
return {
os,
distractionFree: isDistractionFree() ? "on" : "off",
toolWindows: toolWindowsRestorable() ? "hidden" : "shown",
compileFile: compileFileName ? "yes" : "no",
compileFileName: compileFileName ?? "",
};
}