From 86fabc7d1bbcb953aef8e583a88d95a2070c7e98 Mon Sep 17 00:00:00 2001 From: LU XIANGRUI <1078666705@qq.com> Date: Sun, 29 Nov 2026 20:15:50 +0900 Subject: [PATCH] feat(project-structure): add Project Structure and Open Module Settings entry points (#6834) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds Project Structure… to the title bar gear menu (before Settings) and Open Module Settings to the Project view context menu (below Compare With, above Mark Directory as). Open Module Settings is offered on the project folder, Maven / Gradle / Project Structure module folders and sources / resources roots; it opens Project Structure › Modules with the innermost module holding the path selected, and F4 / Cmd+Down on a module folder opens it too. The action uses a new project-structure icon. Artifacts in Project Structure are now editable when the project has no build tool, since the IDE builds and deploys them itself; with Maven or Gradle the page stays read-only with a note. The Tomcat run configuration's "No artifacts configured" Fix opens Project Structure › Artifacts and the deployment list refreshes when artifacts change. Refs #404 Co-authored-by: wildcatDownstairs <26499420+wildcatDownstairs@users.noreply.github.com> --- src/features/project-tree/actions.ts | 10 +++- src/features/project-tree/contextMenu.test.ts | 34 +++++++++++++ src/features/project-tree/contextMenu.ts | 29 +++++++++++ src/features/run/TomcatSettings.tsx | 15 +++++- src/features/run/tomcat.test.tsx | 34 +++++++++++++ .../settings/__tests__/dialog.test.tsx | 6 ++- .../__tests__/moduleOverrides.test.tsx | 49 +++++++++++++++++-- src/features/settings/index.ts | 21 +++++++- .../languages/ProjectStructurePage.tsx | 45 ++++++++++++++--- src/features/settings/model/staging.ts | 27 +++++++++- src/platform/locales/text/en.json | 2 +- src/platform/locales/text/es.json | 3 +- src/platform/locales/text/fr.json | 3 +- src/platform/locales/text/ko.json | 3 +- src/platform/locales/text/pl.json | 3 +- src/platform/locales/text/pt.json | 3 +- src/platform/locales/text/ru.json | 5 +- src/platform/locales/text/tr.json | 5 +- src/platform/locales/text/zh-TW.json | 5 +- src/platform/locales/text/zh.json | 5 +- src/ui/expui/general/projectStructure.svg | 6 +++ .../expui/general/projectStructure_dark.svg | 6 +++ src/ui/icons.tsx | 1 + src/workbench/TitleBar.test.tsx | 9 ++-- src/workbench/TitleBar.tsx | 5 +- 25 files changed, 295 insertions(+), 39 deletions(-) create mode 100644 src/ui/expui/general/projectStructure.svg create mode 100644 src/ui/expui/general/projectStructure_dark.svg diff --git a/src/features/project-tree/actions.ts b/src/features/project-tree/actions.ts index 2c6b35a79..539d78975 100644 --- a/src/features/project-tree/actions.ts +++ b/src/features/project-tree/actions.ts @@ -9,7 +9,7 @@ import { isUntitledUri } from "@/platform/virtualDocs"; import { showContextMenu, type MenuItem } from "@/ui"; import { maybeEditorService, menuGroupItems, toolWindowService } from "@/workbench/contributions"; import { OPTION_LABELS, SORT_LABELS, flipToggle, isToggled } from "./HeaderActions"; -import { compareTarget, newMenuItems, revealLabel } from "./contextMenu"; +import { compareTarget, isModuleNode, newMenuItems, revealLabel } from "./contextMenu"; import { LABELS, setFileColor } from "./fileColor"; import { openNewPopup } from "./newPopupModel"; import type { ProjectNode } from "./model"; @@ -322,7 +322,13 @@ export function registerProjectActions(): () => void { title: "Jump to Source", category: "Project View", when: FOCUS, - run: openSelection, + run: () => { + // F4 / ⌘↓ on a module folder opens its settings instead. + const nodes = selectedNodes(); + const only = nodes.length === 1 ? nodes[0]! : null; + if (only && isModuleNode(only)) void executeAction("project.openModuleSettings", only.path); + else openSelection(); + }, }, { id: "project.quickPreview", diff --git a/src/features/project-tree/contextMenu.test.ts b/src/features/project-tree/contextMenu.test.ts index dd23a216b..4de3c1ba8 100644 --- a/src/features/project-tree/contextMenu.test.ts +++ b/src/features/project-tree/contextMenu.test.ts @@ -2,6 +2,7 @@ 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"; @@ -130,6 +131,39 @@ describe("project view context menu", () => { 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(); diff --git a/src/features/project-tree/contextMenu.ts b/src/features/project-tree/contextMenu.ts index bbbd5b9c9..66c8bb47f 100644 --- a/src/features/project-tree/contextMenu.ts +++ b/src/features/project-tree/contextMenu.ts @@ -6,6 +6,7 @@ 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 { useBuildPresentation } from "@/platform/projectPresentation"; import { attachedProjectOf, currentDetectedRoots, currentRoots } from "@/platform/projectRoots"; import { isVirtualUri } from "@/platform/virtualDocs"; import type { MenuItem } from "@/ui"; @@ -169,6 +170,24 @@ function submenu(id: string, label: string, entries: Entry[], icon?: string): Me } /** Project view actions available for the selected files and directories. */ +/** The project folder or a Maven / Gradle / Project Structure module folder below it. */ +export function isModuleNode(node: ProjectNode): boolean { + if (!node.dir || node.placeholder || node.group) return false; + if (node.root) return true; + const root = useProject.getState().project?.root; + if (!root || !isSameOrInside(node.path, root) || node.path === root) return false; + const rel = relativePath(root, node.path); + const custom = useProject.getState().settings?.projectStructure?.modules ?? {}; + return useBuildPresentation.getState().modules.has(rel) || Object.hasOwn(custom, rel); +} + +/** A sources, tests or resources root (not an excluded folder). */ +function isSourceRootNode(node: ProjectNode): boolean { + if (!node.dir || node.placeholder || node.group) return false; + const role = directoryRole(node.path); + return !!role && role !== "excluded"; +} + /** `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)) @@ -419,6 +438,16 @@ export function contextMenuItems(nodes: ProjectNode[], at: MenuPoint = "center") ) push(delegated("diff.compareFileWithEditor", single.path, "Compare File with Editor", { icon: "diff" })); + // Open Module Settings under Compare With, above Mark Directory as: on a module folder or a + // sources / resources root, where F4 / ⌘↓ (Jump to Source) opens it on a module folder. + if (inProject && single && (isModuleNode(single) || isSourceRootNode(single))) + push( + delegated("project.openModuleSettings", single.path, "Open Module Settings", { + icon: "project-structure", + shortcut: isModuleNode(single) ? keyLabel("project.open") : undefined, + }), + ); + push({ kind: "separator" }); // An attached project keeps its own excluded folders; its other roles aren't applied yet. diff --git a/src/features/run/TomcatSettings.tsx b/src/features/run/TomcatSettings.tsx index 101a55f73..e7b66cbd3 100644 --- a/src/features/run/TomcatSettings.tsx +++ b/src/features/run/TomcatSettings.tsx @@ -2,7 +2,9 @@ import { readClipboardPlainText, writeClipboardText } from "@/platform/clipboard import { useEffect, useRef, useState } from "react"; import clsx from "clsx"; import { call, commands, isTauri, type RunConfig, type TomcatInstallation, type WebArtifact } from "@/platform/ipc"; +import { executeAction } from "@/platform/actions"; import { usePlatform } from "@/platform/platformInfo"; +import { useProject } from "@/platform/project"; import { useWorkflowSettings } from "@/platform/workflowSettings"; import { isRemoteWindow } from "@/platform/remote"; import { Button, Checkbox, Dialog, Icon, IconButton, Input, Menu, Select, Tabs, T, type MenuItem } from "@/ui"; @@ -177,6 +179,15 @@ export function TomcatSettings({ config, onChange }: { config: RunConfig; onChan }) .catch(() => {}); } + return () => { + live = false; + }; + }, []); + + // Listed again when Project Structure › Artifacts changes (the warning's Fix opens it). + const structureArtifacts = useProject((s) => s.settings?.projectStructure?.artifacts); + useEffect(() => { + let live = true; void call(commands.runTomcatArtifacts()) .then((items) => { if (!live) return; @@ -190,7 +201,7 @@ export function TomcatSettings({ config, onChange }: { config: RunConfig; onChan return () => { live = false; }; - }, []); + }, [structureArtifacts]); const home = config.params?.tomcatHome ?? ""; useEffect(() => { @@ -1094,7 +1105,9 @@ export function TomcatSettings({ config, onChange }: { config: RunConfig; onChan icon="bulb-fix" onClick={() => { setActiveTab("deployment"); + // IDEA: with no artifact to deploy, Fix opens Project Structure › Artifacts. if (artifacts[0]) select(artifacts[0]); + else void executeAction("file.projectStructure", "artifacts"); }} > Fix diff --git a/src/features/run/tomcat.test.tsx b/src/features/run/tomcat.test.tsx index 20712ec25..420579e68 100644 --- a/src/features/run/tomcat.test.tsx +++ b/src/features/run/tomcat.test.tsx @@ -15,6 +15,7 @@ import { TomcatSettings } from "./TomcatSettings"; import { typeRows } from "./AddConfigPopup"; import { commands, type RunConfig } from "@/platform/ipc"; import { useProject } from "@/platform/project"; +import { registerActions } from "@/platform/actions"; vi.mock("@tauri-apps/api/core", async (original) => ({ ...(await original()), @@ -386,4 +387,37 @@ describe("several Tomcat deployments", () => { const next = change.mock.lastCall![0] as RunConfig; expect(tomcatDeployments(next).map((d) => d.artifact)).toEqual(["maven:web/pom.xml", "maven:pom.xml"]); }); + + it("opens Project Structure › Artifacts from Fix when nothing can be deployed, then deploys the new artifact", async () => { + const opened: unknown[] = []; + const dispose = registerActions([ + { id: "file.projectStructure", title: "Project Structure…", run: ({ arg }) => void opened.push(arg) }, + ]); + const artifacts = vi.mocked(commands.runTomcatArtifacts); + artifacts.mockResolvedValueOnce({ status: "ok", data: [] }); + try { + const change = vi.fn(); + render(); + await waitFor(() => expect(artifacts).toHaveBeenCalledTimes(1)); + await Promise.resolve(); + fireEvent.click(screen.getByRole("button", { name: "Fix" })); + expect(opened).toEqual(["artifacts"]); + // Applying Project Structure lists the IDE-built artifact; it becomes the deployment. + artifacts.mockResolvedValueOnce({ + status: "ok", + data: [{ id: "project:legacy:war exploded", name: "legacy", module: "", tool: "project" }], + }); + useProject.setState((s) => ({ + settings: { + ...(s.settings ?? {}), + projectStructure: { artifacts: [{ name: "legacy:war exploded", kind: "warExploded" }] }, + } as never, + })); + await waitFor(() => + expect(change.mock.calls.at(-1)?.[0].params).toMatchObject({ artifact: "project:legacy:war exploded" }), + ); + } finally { + dispose(); + } + }); }); diff --git a/src/features/settings/__tests__/dialog.test.tsx b/src/features/settings/__tests__/dialog.test.tsx index e367cb687..0f2b3dfeb 100644 --- a/src/features/settings/__tests__/dialog.test.tsx +++ b/src/features/settings/__tests__/dialog.test.tsx @@ -795,9 +795,11 @@ describe("Settings dialog", () => { // Project dependencies are supported: the checklist is live, no disabled placeholder. expect(screen.getByRole("group", { name: "The project depends on these projects" })).toBeInTheDocument(); expect(screen.getByRole("button", { name: "Add Project…" })).toBeEnabled(); + // Without a build tool the IDE packs artifacts itself (Build Artifacts, Tomcat deployment). fireEvent.click(screen.getByRole("button", { name: "Artifacts" })); - expect(screen.getByRole("button", { name: "JAR" })).toBeDisabled(); - expect(screen.getByRole("button", { name: "WAR" })).toBeDisabled(); + expect(screen.getByRole("button", { name: "JAR" })).toBeEnabled(); + expect(screen.getByRole("button", { name: "WAR" })).toBeEnabled(); + expect(screen.queryByText(/built by Maven or Gradle/)).toBeNull(); }); it("shows the selected module's source tree", async () => { diff --git a/src/features/settings/__tests__/moduleOverrides.test.tsx b/src/features/settings/__tests__/moduleOverrides.test.tsx index 9a7b440a6..5c3e5804d 100644 --- a/src/features/settings/__tests__/moduleOverrides.test.tsx +++ b/src/features/settings/__tests__/moduleOverrides.test.tsx @@ -1,6 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { act, fireEvent, render, screen } from "@testing-library/react"; -import type { Settings } from "@/platform/ipc"; +import { commands, type Settings } from "@/platform/ipc"; const open = vi.fn(); const imported = vi.fn(); @@ -16,6 +16,7 @@ vi.mock("@/platform/ipc", async (importOriginal) => { settingsSet: vi.fn(async () => ({ status: "ok", data: {} })), settingsGet: vi.fn(async () => ({})), settingsGetGlobal: vi.fn(async () => ({})), + buildModel: vi.fn(async () => ({ status: "error", error: "no build model" })), }, }; }); @@ -24,8 +25,8 @@ import { registerAction } from "@/platform/actions"; import { setContext } from "@/platform/context"; import { useProject } from "@/platform/project"; import { DEFAULT_SETTINGS } from "../model/schema"; -import { openProjectStructure, useSettingsDialog } from "../model/staging"; -import { ProjectStructureDialog } from "../languages/ProjectStructurePage"; +import { openModuleSettings, openProjectStructure, useSettingsDialog } from "../model/staging"; +import { ProjectStructureDialog, moduleOfPath } from "../languages/ProjectStructurePage"; import { useContextMenuStore } from "@/ui/Menu"; /** The Modules toolbar's + menu, then its `label` entry. */ @@ -97,4 +98,46 @@ describe("Project Structure module overrides", () => { expect(imported).toHaveBeenCalledOnce(); expect(open).not.toHaveBeenCalled(); }); + + it("selects the innermost module holding a path, like IDEA's Open Module Settings", () => { + const mods = [{ key: "." }, { key: "a" }, { key: "a/b" }, { key: "ab" }]; + expect(moduleOfPath(mods, "a/b/src/X.java")).toBe("a/b"); + expect(moduleOfPath(mods, "a/c")).toBe("a"); + expect(moduleOfPath(mods, "ab")).toBe("ab"); + expect(moduleOfPath(mods, "abc/x")).toBe("."); + expect(moduleOfPath(mods, "")).toBe("."); + }); + + it("opens Modules on the module of the given path and keeps a later manual pick", async () => { + open.mockResolvedValue("/project/mod"); + await act(async () => { + addMenuItem("Add Module Overrides…"); + }); + // Module list rows read "". + const row = (name: string) => screen.getByRole("button", { name: `${name}custom` }); + const isActive = (name: string) => /sideItemActive/.test(row(name).className); + fireEvent.click(row("demo")); + expect(isActive("demo")).toBe(true); + act(() => openModuleSettings("/project/mod/src/A.java")); + expect(useSettingsDialog.getState().projectStructureSection).toBe("modules"); + expect(isActive("mod")).toBe(true); + fireEvent.click(row("demo")); + expect(useSettingsDialog.getState().projectStructureModule).toBeNull(); + expect(isActive("demo")).toBe(true); + }); + + it("keeps Artifacts read-only when Maven or Gradle packs the project", async () => { + act(() => useSettingsDialog.setState({ projectStructureOpen: false })); + vi.mocked(commands.buildModel).mockResolvedValue({ + status: "ok", + data: { maven: { projects: [] }, gradle: [] }, + } as never); + try { + await act(async () => openProjectStructure("artifacts")); + expect(await screen.findByText(/built by Maven or Gradle/)).toBeInTheDocument(); + expect(screen.getByRole("button", { name: "JAR" })).toBeDisabled(); + } finally { + vi.mocked(commands.buildModel).mockResolvedValue({ status: "error", error: "no build model" } as never); + } + }); }); diff --git a/src/features/settings/index.ts b/src/features/settings/index.ts index 346435bc9..639ec13f2 100644 --- a/src/features/settings/index.ts +++ b/src/features/settings/index.ts @@ -26,7 +26,13 @@ import { loadBuiltinPages, unloadBuiltinPages, } from "./dialog/LazySettingsDialog"; -import { openProjectStructure, openSettings, trackPageHistoryActions, useSettingsDialog } from "./model/staging"; +import { + openModuleSettings, + openProjectStructure, + openSettings, + trackPageHistoryActions, + useSettingsDialog, +} from "./model/staging"; import { appearanceToggleActions, navigationBarActions, @@ -94,10 +100,21 @@ export function activate(): () => void { id: "file.projectStructure", title: "Project Structure…", category: "File", - icon: "folder", + icon: "project-structure", keywords: ["project structure", "sdk", "jdk", "modules", "libraries", "facets", "artifacts", "sources"], run: ({ arg }) => openProjectStructure(typeof arg === "string" ? arg : undefined), }, + { + // IDEA's Open Module Settings (F4 / ⌘↓ on a module in the Project view): Project + // Structure › Modules with the module holding `arg` (a path) selected. + id: "project.openModuleSettings", + title: "Open Module Settings", + category: "Project View", + icon: "project-structure", + when: "projectOpen", + keywords: ["module settings", "project structure", "module"], + run: ({ arg }) => openModuleSettings(typeof arg === "string" ? arg : undefined), + }, { // Search Everywhere's ⌥↵ on an action (arg: the action id). id: "settings.assignShortcut", diff --git a/src/features/settings/languages/ProjectStructurePage.tsx b/src/features/settings/languages/ProjectStructurePage.tsx index 7ad153b94..22cbd3846 100644 --- a/src/features/settings/languages/ProjectStructurePage.tsx +++ b/src/features/settings/languages/ProjectStructurePage.tsx @@ -617,6 +617,16 @@ interface DiscoveredModule { buildTool: "maven" | "gradle" | "custom"; } +/** The innermost module holding project-relative `rel` (`""` = project folder), else the root module. */ +export function moduleOfPath(modules: readonly { key: string }[], rel: string): string { + let best = "."; + for (const { key } of modules) { + if (key === "." || !(rel === key || rel.startsWith(`${key}/`))) continue; + if (best === "." || key.length > best.length) best = key; + } + return best; +} + /** One row of the Project Structure › Dependencies checklist. */ export interface DependencyCandidate { path: string; @@ -840,7 +850,20 @@ function ModulesSection() { return list; }, [projectName, model, modulesMap]); - const activeKey = modules.some((m) => m.key === selectedModule) ? selectedModule : "."; + // Open Module Settings: the innermost module holding the target path. The target stays + // until the user picks a module, so Maven / Gradle modules found later still win. + const moduleTarget = useSettingsDialog((s) => s.projectStructureModule); + const pickModule = (key: string) => { + if (moduleTarget !== null) useSettingsDialog.setState({ projectStructureModule: null }); + setSelectedModule(key); + }; + + const activeKey = + moduleTarget !== null + ? moduleOfPath(modules, moduleTarget) + : modules.some((m) => m.key === selectedModule) + ? selectedModule + : "."; const currentModuleCfg: ModuleStructureValid = modulesMap?.[activeKey] ?? { jdk: "", languageLevel: "", @@ -873,7 +896,7 @@ function ModulesSection() { [rel]: { jdk: "", languageLevel: "", compilerOutput: "", testCompilerOutput: "", dependencies: [] }, }); } - setSelectedModule(rel); + pickModule(rel); }; const removeModule = () => { @@ -881,7 +904,7 @@ function ModulesSection() { const next = { ...modulesMap }; delete next[activeKey]; setModulesMap(next); - setSelectedModule("."); + pickModule("."); }; const activeMod = modules.find((m) => m.key === activeKey) ?? modules[0]; @@ -929,7 +952,7 @@ function ModulesSection() { key={m.key} type="button" className={clsx(styles.sideItem, m.key === activeKey && styles.sideItemActive)} - onClick={() => setSelectedModule(m.key)} + onClick={() => pickModule(m.key)} > {m.name} @@ -1633,6 +1656,10 @@ function ArtifactsSection() { const artifacts = rawArtifacts ?? []; const [selectedIdx, setSelectedIdx] = useState(0); const [webArtifacts, setWebArtifacts] = useState([]); + // Maven and Gradle package their own archives; the IDE builds these only without a build tool + // (Build › Build Artifacts, and Tomcat's "Deploy at the server startup"). + const model = useBuildModelData(root); + const byBuildTool = !!model && (!!model.maven || (model.gradle?.length ?? 0) > 0); const nameId = useId(); const outId = useId(); const mainClassId = useId(); @@ -1684,10 +1711,12 @@ function ArtifactsSection() { return (
-
- Custom artifact packaging is not supported yet. Build and deploy artifacts defined by Maven or Gradle. -
-
+ {byBuildTool && ( +
+ This project is built by Maven or Gradle: build and deploy the artifacts they define. +
+ )} +
diff --git a/src/features/settings/model/staging.ts b/src/features/settings/model/staging.ts index 5f1326c92..546910a82 100644 --- a/src/features/settings/model/staging.ts +++ b/src/features/settings/model/staging.ts @@ -57,6 +57,11 @@ export interface SettingsDialogState { open: boolean; projectStructureOpen: boolean; projectStructureSection: ProjectStructureSection; + /** + * Project-relative path (`/`-separated, `""` for the project folder) Modules should select + * the module of, set by Open Module Settings; null keeps the page's own selection. + */ + projectStructureModule: string | null; pageId: string; /** What the page should select when opened as `page#focus` (an inspection id). */ focus: string | null; @@ -94,6 +99,7 @@ export const useSettingsDialog = create(() => ({ open: false, projectStructureOpen: false, projectStructureSection: "project", + projectStructureModule: null, pageId: DEFAULT_PAGE, focus: null, query: "", @@ -146,9 +152,10 @@ export function openSettings(pageId?: string, opts: { newProjects?: boolean; glo if (!opts.globalBase) void loadGlobalBase(); } -export function openProjectStructure(section?: string) { +export function openProjectStructure(section?: string, module: string | null = null) { if (useSettingsDialog.getState().projectStructureOpen) { if (section) selectProjectStructureSection(parseProjectStructureSection(section)); + if (module !== null) useSettingsDialog.setState({ projectStructureModule: module }); return; } const base = validateSettings(useProject.getState().settings); @@ -156,6 +163,7 @@ export function openProjectStructure(section?: string) { open: false, projectStructureOpen: true, projectStructureSection: parseProjectStructureSection(section), + projectStructureModule: module, base, globalBase: base, newProjects: false, @@ -169,9 +177,26 @@ export function openProjectStructure(section?: string) { void loadGlobalBase(); } +/** + * IDEA's Open Module Settings: Project Structure › Modules showing the module that holds + * `path` (absolute, inside the project); without one, the page's own selection. + */ +export function openModuleSettings(path?: string) { + const root = useProject.getState().project?.root; + let rel: string | null = null; + if (path && root) { + const norm = (p: string) => p.replace(/\\/g, "/").replace(/\/+$/, ""); + const [r, p] = [norm(root), norm(path)]; + if (p === r) rel = ""; + else if (p.startsWith(`${r}/`)) rel = p.slice(r.length + 1); + } + openProjectStructure("modules", rel); +} + export function closeProjectStructure() { useSettingsDialog.setState({ projectStructureOpen: false, + projectStructureModule: null, staged: {}, stagedSecrets: {}, stagedExternal: {}, diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index f7eae891b..50765460d 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -1435,7 +1435,7 @@ "Platform Settings": "Platform Settings", "Project Structure sections": "Project Structure sections", "Custom test output paths are not supported yet. Maven and Gradle manage their own test output.": "Custom test output paths are not supported yet. Maven and Gradle manage their own test output.", - "Custom artifact packaging is not supported yet. Build and deploy artifacts defined by Maven or Gradle.": "Custom artifact packaging is not supported yet. Build and deploy artifacts defined by Maven or Gradle.", + "This project is built by Maven or Gradle: build and deploy the artifacts they define.": "This project is built by Maven or Gradle: build and deploy the artifacts they define.", "Add Module Overrides…": "Add Module Overrides…", "Import Module from Existing Sources": "Import Module from Existing Sources", "Module overrides only apply to a directory inside the opened project. To import an existing module from outside it, use Import Module from Existing Sources.": "Module overrides only apply to a directory inside the opened project. To import an existing module from outside it, use Import Module from Existing Sources.", diff --git a/src/platform/locales/text/es.json b/src/platform/locales/text/es.json index 517a6b44c..260815cbc 100644 --- a/src/platform/locales/text/es.json +++ b/src/platform/locales/text/es.json @@ -6217,5 +6217,6 @@ "Cross-file code insight for {container} needs buildServer.json. Generate it with {tool}?": "La asistencia de código entre archivos para {container} necesita buildServer.json. ¿Generarlo con {tool}?", "Cross-file code insight for {container} needs a Build Server Protocol config. Install xcode-build-server (brew install xcode-build-server) to generate one.": "La asistencia de código entre archivos para {container} necesita una configuración de Build Server Protocol. Instala xcode-build-server (brew install xcode-build-server) para generarla.", "Check Again": "Comprobar de nuevo", - "Running {tool}…": "Ejecutando {tool}…" + "Running {tool}…": "Ejecutando {tool}…", + "Open Module Settings": "Abrir configuración del módulo" } diff --git a/src/platform/locales/text/fr.json b/src/platform/locales/text/fr.json index d289540ea..a3e264919 100644 --- a/src/platform/locales/text/fr.json +++ b/src/platform/locales/text/fr.json @@ -5862,5 +5862,6 @@ "Cross-file code insight for {container} needs buildServer.json. Generate it with {tool}?": "L’assistance au code entre fichiers pour {container} nécessite buildServer.json. Le générer avec {tool} ?", "Cross-file code insight for {container} needs a Build Server Protocol config. Install xcode-build-server (brew install xcode-build-server) to generate one.": "L’assistance au code entre fichiers pour {container} nécessite une configuration Build Server Protocol. Installez xcode-build-server (brew install xcode-build-server) pour en générer une.", "Check Again": "Vérifier à nouveau", - "Running {tool}…": "Exécution de {tool}…" + "Running {tool}…": "Exécution de {tool}…", + "Open Module Settings": "Ouvrir les paramètres du module" } diff --git a/src/platform/locales/text/ko.json b/src/platform/locales/text/ko.json index 35fe0dc20..d9b2c7c49 100644 --- a/src/platform/locales/text/ko.json +++ b/src/platform/locales/text/ko.json @@ -6327,5 +6327,6 @@ "Cross-file code insight for {container} needs buildServer.json. Generate it with {tool}?": "{container}의 파일 간 코드 인사이트에는 buildServer.json이 필요합니다. {tool}(으)로 생성할까요?", "Cross-file code insight for {container} needs a Build Server Protocol config. Install xcode-build-server (brew install xcode-build-server) to generate one.": "{container}의 파일 간 코드 인사이트에는 Build Server Protocol 설정이 필요합니다. xcode-build-server(brew install xcode-build-server)를 설치하면 생성할 수 있습니다.", "Check Again": "다시 확인", - "Running {tool}…": "{tool} 실행 중…" + "Running {tool}…": "{tool} 실행 중…", + "Open Module Settings": "모듈 설정 열기" } diff --git a/src/platform/locales/text/pl.json b/src/platform/locales/text/pl.json index 69c700b99..4391bea24 100644 --- a/src/platform/locales/text/pl.json +++ b/src/platform/locales/text/pl.json @@ -6025,5 +6025,6 @@ "Cross-file code insight for {container} needs buildServer.json. Generate it with {tool}?": "Analiza kodu między plikami dla {container} wymaga buildServer.json. Wygenerować go za pomocą {tool}?", "Cross-file code insight for {container} needs a Build Server Protocol config. Install xcode-build-server (brew install xcode-build-server) to generate one.": "Analiza kodu między plikami dla {container} wymaga konfiguracji Build Server Protocol. Zainstaluj xcode-build-server (brew install xcode-build-server), aby ją wygenerować.", "Check Again": "Sprawdź ponownie", - "Running {tool}…": "Uruchamianie {tool}…" + "Running {tool}…": "Uruchamianie {tool}…", + "Open Module Settings": "Otwórz ustawienia modułu" } diff --git a/src/platform/locales/text/pt.json b/src/platform/locales/text/pt.json index b613a7f63..789520ae9 100644 --- a/src/platform/locales/text/pt.json +++ b/src/platform/locales/text/pt.json @@ -6040,5 +6040,6 @@ "Cross-file code insight for {container} needs buildServer.json. Generate it with {tool}?": "A inteligência de código entre arquivos para {container} precisa de buildServer.json. Gerá-lo com {tool}?", "Cross-file code insight for {container} needs a Build Server Protocol config. Install xcode-build-server (brew install xcode-build-server) to generate one.": "A inteligência de código entre arquivos para {container} precisa de uma configuração do Build Server Protocol. Instale o xcode-build-server (brew install xcode-build-server) para gerá-la.", "Check Again": "Verificar novamente", - "Running {tool}…": "Executando {tool}…" + "Running {tool}…": "Executando {tool}…", + "Open Module Settings": "Abrir configurações do módulo" } diff --git a/src/platform/locales/text/ru.json b/src/platform/locales/text/ru.json index fb49ee7ae..89618d239 100644 --- a/src/platform/locales/text/ru.json +++ b/src/platform/locales/text/ru.json @@ -7860,7 +7860,7 @@ "Cannot copy the value": "Не удается скопировать значение", "The check could not run: {reason}": "Не удалось выполнить проверку: {reason}", "Custom test output paths are not supported yet. Maven and Gradle manage their own test output.": "Пользовательские пути вывода тестов пока не поддерживаются. Maven и Gradle сами управляют выводом тестов.", - "Custom artifact packaging is not supported yet. Build and deploy artifacts defined by Maven or Gradle.": "Пользовательская упаковка артефактов пока не поддерживается. Собирайте и развертывайте артефакты, определенные в Maven или Gradle.", + "This project is built by Maven or Gradle: build and deploy the artifacts they define.": "Этот проект собирается Maven или Gradle: собирайте и развертывайте определенные в них артефакты.", "Add Module Overrides…": "Добавить переопределения модуля…", "Module overrides only apply to a directory inside the opened project. To import an existing module from outside it, use Import Module from Existing Sources.": "Переопределения модуля применимы только к каталогу внутри открытого проекта. Чтобы импортировать существующий модуль извне, используйте «Импорт модуля из существующих исходников».", "Directory for production classes, relative to the project root and inside this module.": "Каталог для рабочих классов (production) относительно корня проекта и внутри этого модуля.", @@ -10255,5 +10255,6 @@ "Cross-file code insight for {container} needs buildServer.json. Generate it with {tool}?": "Для межфайловой поддержки кода в {container} нужен buildServer.json. Создать его с помощью {tool}?", "Cross-file code insight for {container} needs a Build Server Protocol config. Install xcode-build-server (brew install xcode-build-server) to generate one.": "Для межфайловой поддержки кода в {container} нужна конфигурация Build Server Protocol. Установите xcode-build-server (brew install xcode-build-server), чтобы создать её.", "Check Again": "Проверить снова", - "Running {tool}…": "Выполняется {tool}…" + "Running {tool}…": "Выполняется {tool}…", + "Open Module Settings": "Открыть настройки модуля" } diff --git a/src/platform/locales/text/tr.json b/src/platform/locales/text/tr.json index a6b02b045..3a81b26e5 100644 --- a/src/platform/locales/text/tr.json +++ b/src/platform/locales/text/tr.json @@ -774,7 +774,7 @@ "Platform Settings": "Platform Ayarları", "Project Structure sections": "Proje Yapısı bölümleri", "Custom test output paths are not supported yet. Maven and Gradle manage their own test output.": "Özel test çıktı yolları henüz desteklenmiyor. Maven ve Gradle kendi test çıktılarını yönetir.", - "Custom artifact packaging is not supported yet. Build and deploy artifacts defined by Maven or Gradle.": "Özel çıktı paketi oluşturma henüz desteklenmiyor. Maven veya Gradle tarafından tanımlanan çıktı paketlerini derleyip dağıtın.", + "This project is built by Maven or Gradle: build and deploy the artifacts they define.": "Bu proje Maven veya Gradle ile derleniyor: onların tanımladığı çıktı paketlerini derleyip dağıtın.", "Add Module Overrides…": "Modül Geçersiz Kılmaları Ekle…", "Import Module from Existing Sources": "Mevcut Kaynaklardan Modül İçe Aktar", "Module overrides only apply to a directory inside the opened project. To import an existing module from outside it, use Import Module from Existing Sources.": "Modül geçersiz kılmaları yalnızca açık projenin içindeki dizinlere uygulanır. Proje dışındaki mevcut modülleri içe aktarmak için Mevcut Kaynaklardan Modül İçe Aktar seçeneğini kullanın.", @@ -8879,5 +8879,6 @@ "Cross-file code insight for {container} needs buildServer.json. Generate it with {tool}?": "{container} için dosyalar arası kod zekâsı buildServer.json gerektirir. {tool} ile oluşturulsun mu?", "Cross-file code insight for {container} needs a Build Server Protocol config. Install xcode-build-server (brew install xcode-build-server) to generate one.": "{container} için dosyalar arası kod zekâsı bir Build Server Protocol yapılandırması gerektirir. Oluşturmak için xcode-build-server'ı yükleyin (brew install xcode-build-server).", "Check Again": "Yeniden Denetle", - "Running {tool}…": "{tool} çalıştırılıyor…" + "Running {tool}…": "{tool} çalıştırılıyor…", + "Open Module Settings": "Modül Ayarlarını Aç" } diff --git a/src/platform/locales/text/zh-TW.json b/src/platform/locales/text/zh-TW.json index 4b66606c2..b7473a22e 100644 --- a/src/platform/locales/text/zh-TW.json +++ b/src/platform/locales/text/zh-TW.json @@ -7369,7 +7369,7 @@ "Cannot copy the value": "無法複製該值", "The check could not run: {reason}": "檢查無法執行:{reason}", "Custom test output paths are not supported yet. Maven and Gradle manage their own test output.": "暫不支援自訂測試輸出路徑。測試輸出由 Maven 和 Gradle 管理。", - "Custom artifact packaging is not supported yet. Build and deploy artifacts defined by Maven or Gradle.": "暫不支援自訂製品打包。請建置和部署 Maven 或 Gradle 定義的製品。", + "This project is built by Maven or Gradle: build and deploy the artifacts they define.": "此專案由 Maven 或 Gradle 建置:請建置和部署它們定義的構件。", "Add Module Overrides…": "新增模組覆蓋設定…", "Module overrides only apply to a directory inside the opened project. To import an existing module from outside it, use Import Module from Existing Sources.": "模組覆蓋設定只適用於目前開啟專案內的目錄。要從外部匯入已有模組,請使用「匯入已有模組」。", "Directory for production classes, relative to the project root and inside this module.": "生產類別檔案目錄,相對於專案根目錄,且必須位於目前模組內。", @@ -9511,5 +9511,6 @@ "Cross-file code insight for {container} needs buildServer.json. Generate it with {tool}?": "{container} 的跨檔案程式碼智慧需要 buildServer.json。要用 {tool} 產生嗎?", "Cross-file code insight for {container} needs a Build Server Protocol config. Install xcode-build-server (brew install xcode-build-server) to generate one.": "{container} 的跨檔案程式碼智慧需要 Build Server Protocol 設定。安裝 xcode-build-server(brew install xcode-build-server)即可產生。", "Check Again": "重新檢查", - "Running {tool}…": "正在執行 {tool}…" + "Running {tool}…": "正在執行 {tool}…", + "Open Module Settings": "開啟模組設定" } diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index abcf08dbb..c6c9b2d3d 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -8259,7 +8259,7 @@ "Cannot copy the value": "无法复制该值", "The check could not run: {reason}": "检查无法运行:{reason}", "Custom test output paths are not supported yet. Maven and Gradle manage their own test output.": "暂不支持自定义测试输出路径。测试输出由 Maven 和 Gradle 管理。", - "Custom artifact packaging is not supported yet. Build and deploy artifacts defined by Maven or Gradle.": "暂不支持自定义制品打包。请构建和部署 Maven 或 Gradle 定义的制品。", + "This project is built by Maven or Gradle: build and deploy the artifacts they define.": "此项目由 Maven 或 Gradle 构建:请构建和部署它们定义的构件。", "Add Module Overrides…": "添加模块覆盖设置…", "Module overrides only apply to a directory inside the opened project. To import an existing module from outside it, use Import Module from Existing Sources.": "模块覆盖设置只适用于当前打开项目内的目录。要从外部导入已有模块,请使用「导入已有模块」。", "Directory for production classes, relative to the project root and inside this module.": "生产类文件目录,相对于项目根目录,且必须位于当前模块内。", @@ -11370,5 +11370,6 @@ "Storage options": "存储选项", "Access method": "访问方法", "Partitioning": "分区", - "fillfactor=70, autovacuum_enabled=false": "fillfactor=70, autovacuum_enabled=false" + "fillfactor=70, autovacuum_enabled=false": "fillfactor=70, autovacuum_enabled=false", + "Open Module Settings": "打开模块设置" } diff --git a/src/ui/expui/general/projectStructure.svg b/src/ui/expui/general/projectStructure.svg new file mode 100644 index 000000000..a5f8ec4a1 --- /dev/null +++ b/src/ui/expui/general/projectStructure.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/src/ui/expui/general/projectStructure_dark.svg b/src/ui/expui/general/projectStructure_dark.svg new file mode 100644 index 000000000..e54355ed6 --- /dev/null +++ b/src/ui/expui/general/projectStructure_dark.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/src/ui/icons.tsx b/src/ui/icons.tsx index b89bf04ba..d3504ca04 100644 --- a/src/ui/icons.tsx +++ b/src/ui/icons.tsx @@ -345,6 +345,7 @@ const ICONS = { refresh: "general/refresh", quote: "openidea/general/quote", settings: "general/settings", + "project-structure": "general/projectStructure", help: "openidea/general/help", "page-first": "openidea/general/pageFirst", "page-last": "openidea/general/pageLast", diff --git a/src/workbench/TitleBar.test.tsx b/src/workbench/TitleBar.test.tsx index 3dbc1d699..513801460 100644 --- a/src/workbench/TitleBar.test.tsx +++ b/src/workbench/TitleBar.test.tsx @@ -21,11 +21,12 @@ afterEach(() => { }); describe("title bar gear menu", () => { - it("lists Run Anything, Settings, Plugins, quick switches, toolbar customization and Check for Updates", () => { + it("lists Run Anything, Project Structure, Settings, Plugins, quick switches, toolbar customization and Check for Updates", () => { const items = gearMenuItems("dark", "intellij-macos", ["Mine"]); expect(items.map((i) => ("action" in i ? i.action : "label" in i ? i.label : i.kind))).toEqual([ "runAnything.show", "separator", + "file.projectStructure", "file.settings", "plugins.settings", "separator", @@ -38,13 +39,13 @@ describe("title bar gear menu", () => { "app.checkForUpdates", ]); type Sub = { submenu: Array<{ label?: string; checked?: boolean; action?: string }> }; - const theme = (items[5] as Sub).submenu; + const theme = (items[6] as Sub).submenu; expect(theme.filter((i) => i.checked).map((i) => i.label)).toEqual(["Islands Dark"]); - const keymap = (items[6] as Sub).submenu; + const keymap = (items[7] as Sub).submenu; expect(keymap.map((i) => i.label)).toContain("Mine"); expect(keymap.filter((i) => i.checked).map((i) => i.label)).toEqual(["macOS"]); // View Mode only switches the existing modes. - expect((items[7] as Sub).submenu.map((i) => i.action)).toEqual([ + expect((items[8] as Sub).submenu.map((i) => i.action)).toEqual([ "editor.toggleZen", "view.toggleZenMode", "window.toggleFullScreen", diff --git a/src/workbench/TitleBar.tsx b/src/workbench/TitleBar.tsx index 39be91730..1aca91454 100644 --- a/src/workbench/TitleBar.tsx +++ b/src/workbench/TitleBar.tsx @@ -171,8 +171,8 @@ export function customizeToolbarItems( } /** - * IDEA's main toolbar gear: Run Anything, Settings, Plugins, quick switches, toolbar customization, updates. - * With `preview`, a theme under the pointer shows as in Quick Switch. + * IDEA's main toolbar gear: Run Anything, Project Structure, Settings, Plugins, quick switches, + * toolbar customization, updates. With `preview`, a theme under the pointer shows as in Quick Switch. */ export function gearMenuItems( themeId: string, @@ -185,6 +185,7 @@ export function gearMenuItems( return [ { kind: "action", action: "runAnything.show" }, { kind: "separator" }, + { kind: "action", action: "file.projectStructure" }, { kind: "action", action: "file.settings" }, { kind: "action", action: "plugins.settings" }, { kind: "separator" },