feat(maven): add POM artifact and managed-version navigation (#4699)

Go to Declaration on a dependency, plugin or <parent> in a POM opens the artifact's own POM (a workspace module with matching coordinates first, then the local repository), and unversioned dependencies and plugins get a gutter icon that opens the management entry supplying their version, through active profiles (including JDK-activated ones), parent POMs, imported BOMs and plugin management. Maven element values are underlined whole, and contributed definition/hover providers that decline a position let the next one answer. Review fix: a BOM import without a version no longer ends the management search.

Co-authored-by: kradme <17811095+kradme@users.noreply.github.com>
This commit is contained in:
langxp
2026-11-20 13:45:47 +08:00
committed by GitHub
co-authored by kradme
parent 96f3818bf2
commit c0b243f020
18 changed files with 1536 additions and 141 deletions
+13 -1
View File
@@ -82,11 +82,23 @@ pub fn load_linked(
maven_repo: Option<PathBuf>,
settings: &ide_core::settings::MavenSettings,
gradle_settings: &ide_core::settings::GradleSettings,
) -> BuildModel {
load_linked_with_jdk(root, cache_dir, maven_repo, settings, gradle_settings, None)
}
/// [`load_linked`] with the JDK Maven runs on, for JDK-activated Maven profiles.
pub fn load_linked_with_jdk(
root: &Path,
cache_dir: &Path,
maven_repo: Option<PathBuf>,
settings: &ide_core::settings::MavenSettings,
gradle_settings: &ide_core::settings::GradleSettings,
maven_jdk_version: Option<u32>,
) -> BuildModel {
let maven = maven::has_projects(root, settings).then(|| {
let profiles = settings.profiles(&sync::maven_profiles(cache_dir));
let repo = maven_repo.or_else(maven::default_local_repo);
let mut m = maven::load_with_linked(root, repo, &profiles, &settings.linked_projects);
let mut m = maven::load_with_linked_jdk(root, repo, &profiles, maven_jdk_version, &settings.linked_projects);
maven::UnlinkedProjects::from_model(&m, settings).filter(&mut m);
// The user settings' profiles can be chosen too (`-P` applies to them as well).
for p in maven::user_settings_file(root, settings).map(|f| maven::settings_profiles(&f)).unwrap_or_default() {
File diff suppressed because it is too large Load Diff
+118 -21
View File
@@ -8,30 +8,79 @@ use crate::{Host, Project};
use ide_command::command;
use ide_build::compile::{self, BuildEvent, BuildKind, BuildResult};
use ide_build::maven::PomGoto;
use ide_build::maven::completion::{PomCompletion, PomCompletionOption};
use ide_build::maven::{PomGoto, PomManagedDeclaration, PomNavigationOptions};
use ide_build::pom_edit::{ArtifactKey, Exclusion};
use ide_build::{BuildModel, BuildTool, SyncOptions, SyncProgress};
use ide_core::settings::Settings;
use ide_core::{DocId, FileEdit, IdeError, IdeEvent, IdeResult, Location, Pos, Range, RequestId, WorkspaceEdit};
use std::collections::HashMap;
use std::path::Path;
use std::sync::Arc;
use std::sync::{Arc, Mutex, OnceLock};
use std::time::{Duration, Instant};
fn join_err(e: tokio::task::JoinError) -> IdeError {
IdeError::internal(e.to_string())
}
/// POM gutters in several editors refresh together. A very short cache lets those
/// requests share one reactor scan without serving a stale module list after edits settle.
const MAVEN_MODULE_CACHE_TTL: Duration = Duration::from_millis(250);
type MavenModuleCache = HashMap<String, (Instant, Vec<ide_build::maven::ModulePom>)>;
static MAVEN_MODULES: OnceLock<Mutex<MavenModuleCache>> = OnceLock::new();
fn maven_modules(
project: &Project,
settings: &Settings,
options: &PomNavigationOptions,
) -> Vec<ide_build::maven::ModulePom> {
let key = format!(
"{}\0{:?}\0{:?}\0{:?}\0{:?}",
project.root.display(),
project.build_cache_dir(),
settings.languages.java.maven.linked_projects,
options.profiles,
options.jdk_version
);
let cache = MAVEN_MODULES.get_or_init(|| Mutex::new(HashMap::new()));
if let Some((_at, modules)) = cache.lock().ok().and_then(|mut cache| {
let fresh = cache.get(&key).filter(|(at, _)| at.elapsed() < MAVEN_MODULE_CACHE_TTL).cloned();
if fresh.is_none() {
cache.remove(&key);
}
fresh
}) {
return modules;
}
let model = load(&project.root, &project.build_cache_dir(), settings).maven.unwrap_or_default();
let modules = model
.projects
.into_iter()
.map(|p| ide_build::maven::ModulePom {
group_id: p.group_id,
artifact_id: p.artifact_id,
version: p.version,
pom: project.root.join(&p.pom),
})
.collect::<Vec<_>>();
if let Ok(mut cache) = cache.lock() {
cache.insert(key, (Instant::now(), modules.clone()));
}
modules
}
/// The build model with the launch settings applied: the JDK (`JAVA_HOME`), and
/// the Maven home and options from Settings › Maven.
pub fn load(root: &Path, cache: &Path, settings: &Settings) -> BuildModel {
let mut model = ide_build::load_linked(
let jdk = ide_sdk::apply::project_jdk(root, settings);
let mut model = ide_build::load_linked_with_jdk(
root,
cache,
ide_sdk::apply::maven_local_repository(root, settings),
&settings.languages.java.maven,
&settings.languages.java.gradle,
ide_sdk::apply::maven_jdk(root, settings, None).map(|jdk| jdk.major),
);
let jdk = ide_sdk::apply::project_jdk(root, settings);
if let Some(m) = &mut model.maven {
let mvn = ide_sdk::apply::maven_command(root, settings);
let options = ide_sdk::apply::maven_options(root, settings);
@@ -77,6 +126,23 @@ pub fn load(root: &Path, cache: &Path, settings: &Settings) -> BuildModel {
model
}
/// POM navigation follows the same profile choices as the last Maven sync and
/// resolves JDK-activated profiles with the project's selected Maven runtime.
fn pom_navigation_options(project: &Project, settings: &Settings) -> PomNavigationOptions {
let mut profiles = settings.languages.java.maven.profiles(&[]);
for profile in ide_build::maven_profiles(&project.build_cache_dir()) {
if !profiles.contains(&profile) {
profiles.push(profile);
}
}
PomNavigationOptions {
local_repo: ide_sdk::apply::maven_local_repository(&project.root, settings)
.or_else(ide_build::maven::default_local_repo),
profiles,
jdk_version: ide_sdk::apply::maven_jdk(&project.root, settings, None).map(|jdk| jdk.major),
}
}
/// Build and Run use the same selected toolchain and module-local runtime discovery.
fn prepare_plan(mut plan: compile::BuildPlan, root: &Path, settings: &Settings) -> compile::BuildPlan {
let kind = match plan.system {
@@ -547,8 +613,9 @@ pub async fn maven_dependency_declaration(
}
/// The go-to-declaration target at `pos` of a Maven POM: the definition of the
/// `${property}` at the caret, or the `<dependencyManagement>` / `<pluginManagement>`
/// entry providing the dependency's / plugin's version, along the parent chain.
/// `${property}` at the caret, the parent POM, or the dependency / plugin's own POM
/// (a project module first, then the local repository). A dependency without a
/// resolvable artifact POM falls back to its management entry.
#[command(trust = trusted)]
pub async fn maven_goto_declaration(host: &Host, window: &str, pom: String, pos: Pos) -> IdeResult<Option<PomGoto>> {
// `pom` is project-relative, or absolute for a parent POM opened from the local repository.
@@ -561,26 +628,55 @@ pub async fn maven_goto_declaration(host: &Host, window: &str, pom: String, pos:
let path = if given.is_absolute() { given.to_path_buf() } else { project.root.join(given) };
let text = project.text_of(&path)?;
let settings = project.settings.effective();
let repo = ide_sdk::apply::maven_local_repository(&project.root, &settings)
.or_else(ide_build::maven::default_local_repo);
let modules = || {
let model = load(&project.root, &project.build_cache_dir(), &settings).maven.unwrap_or_default();
model
.projects
.into_iter()
.map(|p| ide_build::maven::ModulePom {
group_id: p.group_id,
artifact_id: p.artifact_id,
pom: project.root.join(&p.pom),
})
.collect()
};
Ok(ide_build::maven::goto_declaration_in(&text, &path, pos, repo, modules))
let options = pom_navigation_options(&project, &settings);
let module_options = options.clone();
let modules = || maven_modules(&project, &settings, &module_options);
Ok(ide_build::maven::goto_declaration_with(&text, &path, pos, options, modules))
})
.await
.map_err(join_err)?
}
/// Gutter targets of the unversioned dependencies and plugins in a Maven POM:
/// the management declarations that actually supply their versions, including
/// parent POMs and imported BOMs. Cancel with `cancel_request(request)`.
#[command(trust = trusted)]
pub async fn maven_managed_declarations(
host: &Host,
window: &str,
pom: String,
request: RequestId,
) -> IdeResult<Vec<PomManagedDeclaration>> {
let project = host.project(window)?;
let cancel = host.begin_project_read_request(window, request);
let result = tokio::task::spawn_blocking(move || {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let given = Path::new(&pom);
let path = if given.is_absolute() { given.to_path_buf() } else { project.root.join(given) };
let text = project.text_of(&path)?;
let settings = project.settings.effective();
let options = pom_navigation_options(&project, &settings);
let cancelled = cancel.clone();
let module_options = options.clone();
let modules = || {
if cancelled.is_cancelled() {
return Vec::new();
}
maven_modules(&project, &settings, &module_options)
};
let declarations = ide_build::maven::managed_declarations_with(&text, &path, options, modules);
if cancel.is_cancelled() { Err(IdeError::cancelled()) } else { Ok(declarations) }
})
.await;
host.end_request(request);
match result {
Ok(result) => result,
Err(error) => Err(join_err(error)),
}
}
/// How long completion waits for Maven Central before answering from the local repository.
const CENTRAL_WAIT: std::time::Duration = std::time::Duration::from_secs(1);
@@ -1333,4 +1429,5 @@ ide_command::domain!(
maven_dependency_declaration,
maven_exclude_dependency,
maven_goto_declaration,
maven_managed_declarations,
);
+1
View File
@@ -375,6 +375,7 @@ maven_dependency_completion trusted project_host bin
maven_dependency_declaration trusted project_host bindings async
maven_exclude_dependency trusted project_host bindings async
maven_goto_declaration trusted project_host bindings async
maven_managed_declarations trusted project_host bindings async
mcp_agent_run_closed trusted project_host bindings sync
mcp_background_projects always project_host bindings sync
mcp_regenerate_token outside_restricted project_host bindings sync
+19 -2
View File
@@ -960,8 +960,9 @@ export const commands = {
mavenExcludeDependency: (pom: string, dependency: ArtifactKey, exclusion: ArtifactKey) => typedError<Location, IdeError>(__TAURI_INVOKE("maven_exclude_dependency", { pom, dependency, exclusion })),
/**
* The go-to-declaration target at `pos` of a Maven POM: the definition of the
* `${property}` at the caret, or the `<dependencyManagement>` / `<pluginManagement>`
* entry providing the dependency's / plugin's version, along the parent chain.
* `${property}` at the caret, the parent POM, or the dependency / plugin's own POM
* (a project module first, then the local repository). A dependency without a
* resolvable artifact POM falls back to its management entry.
*/
mavenGotoDeclaration: (pom: string, pos: Pos) => typedError<{
/**
@@ -975,6 +976,12 @@ export const commands = {
/** The declaration as named for the user (`example.version`, `com.example:example-lib`). */
label: string,
} | null, IdeError>(__TAURI_INVOKE("maven_goto_declaration", { pom, pos })),
/**
* Gutter targets of the unversioned dependencies and plugins in a Maven POM:
* the management declarations that actually supply their versions, including
* parent POMs and imported BOMs. Cancel with `cancel_request(request)`.
*/
mavenManagedDeclarations: (pom: string, request: RequestId) => typedError<PomManagedDeclaration[], IdeError>(__TAURI_INVOKE("maven_managed_declarations", { pom, request })),
/** The user closed the Run tool window tab of an agent command (`run_command`). */
mcpAgentRunClosed: (name: string) => typedError<null, IdeError>(__TAURI_INVOKE("mcp_agent_run_closed", { name })),
/**
@@ -9753,6 +9760,16 @@ export type PomGotoKind =
/** The POM of the artifact itself: a project module's, else the local repository's. */
"artifactPom";
/** A dependency or plugin whose version comes from a management declaration. */
export type PomManagedDeclaration = {
/** 0-based line of the `<dependency>` or `<plugin>` declaration. */
line: number,
/** The interpolated version the management entry provides, when it has one. */
version: string | null,
/** The management entry, possibly in a parent POM or an imported BOM. */
target: PomGoto,
};
/** A 0-based line / UTF-16 column position. */
export type Pos = {
line: number,
+15 -1
View File
@@ -490,7 +490,11 @@ export type ContributedFormatter = (
range: { from: number; to: number } | null,
) => Array<{ from: number; to: number; insert: string }>;
/** Go to Declaration / ⌘-click: `true` when it handled `pos`. */
export type ContributedDefinition = (view: EditorView, pos: number) => boolean;
export interface ContributedDefinition {
(view: EditorView, pos: number): boolean;
/** Cheap, side-effect-free eligibility for hover underline and navigation probing. */
canHandle?(state: EditorState, pos: number): boolean;
}
/** Hover and Quick Documentation: Markdown about the symbol at `pos`. */
export type ContributedHover = (
state: EditorState,
@@ -501,6 +505,16 @@ export function contributedAt<T>(state: EditorState, key: string, pos: number):
return state.languageDataAt<T>(key, pos)[0];
}
/**
* Every provider registered for a contributed language-data key at `pos`. A provider may
* be present for the document but decline this particular position (the MyBatis SQL
* provider on a Maven POM, for example), so callers that dispatch a request must not stop
* at the first entry when it returns "not handled".
*/
export function contributedAtAll<T>(state: EditorState, key: string, pos: number): readonly T[] {
return state.languageDataAt<T>(key, pos);
}
/** A context action a feature offers at the caret, listed by Show Context Actions (⌥↵). */
export interface ContributedIntention {
id: string;
+21 -5
View File
@@ -21,20 +21,36 @@ const target: Location = {
range: { start: { line: 3, col: 4 }, end: { line: 3, col: 9 } },
};
const views: EditorView[] = [];
function editor(doc = 1, language = "yaml", text = "server:\n port: 8080\n") {
function editor(doc = 1, language = "yaml", text = "server:\n port: 8080\n", path = `/p/${doc}.${language}`) {
const view = new EditorView({
state: EditorState.create({
doc: text,
extensions: [
lspDoc.of({ doc, path: `/p/${doc}.${language}`, language, uiMode: language, readOnly: false }),
navigationExtension(),
],
extensions: [lspDoc.of({ doc, path, language, uiMode: language, readOnly: false }), navigationExtension()],
}),
parent: document.body,
});
views.push(view);
return view;
}
it("uses the whole Maven element value for the navigation underline", () => {
const text = " <artifactId>cdf-parent</artifactId>\n <version>${revision}</version>";
const view = editor(1, "xml", text, "/p/pom.xml");
const parent = text.indexOf("cdf-parent");
for (const offset of [parent, parent + 3, parent + 4, parent + "cdf-parent".length]) {
const range = navigationWord(view, offset)!;
expect(view.state.sliceDoc(range.from, range.to)).toBe("cdf-parent");
}
const revision = text.indexOf("${revision}");
const range = navigationWord(view, revision + 4)!;
expect(view.state.sliceDoc(range.from, range.to)).toBe("${revision}");
const multiline = "<artifactId>\n cdf-parent\n </artifactId>";
const multilineView = editor(2, "xml", multiline, "/p/multiline/pom.xml");
const multilineRange = navigationWord(multilineView, multiline.indexOf("parent"))!;
expect(multilineView.state.sliceDoc(multilineRange.from, multilineRange.to)).toBe("cdf-parent");
});
let off: () => void;
beforeEach(() => {
vi.useFakeTimers();
+54 -2
View File
@@ -5,6 +5,7 @@
import type { Text } from "@codemirror/state";
import type { EditorView } from "@codemirror/view";
import { onEditorEvent } from "@/editor/api";
import { isMavenPom } from "@/platform/buildFiles";
import { commands, IpcError, onIdeEvent, type GotoKind, type Location } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { onServerSettled } from "./availability";
@@ -54,9 +55,60 @@ export function isConfigurationDocument(view: EditorView): boolean {
return language === "yaml" || language === "properties";
}
/** Configuration names include hyphens and dots even when the editor's
* language word rules split them. Share this range between decoration and lookup. */
const XML_VALUE_SCAN_LINES = 256;
/** The text of the XML element, trimmed to the value itself. */
function pomElementValueAt(view: EditorView, offset: number): { from: number; to: number } | null {
const doc = view.state.doc;
const line = doc.lineAt(offset);
let open = -1;
const onLine = line.text.lastIndexOf(">", offset - line.from);
if (onLine >= 0) open = line.from + onLine;
else {
for (let number = line.number - 1; number >= 1 && line.number - number <= XML_VALUE_SCAN_LINES; number--) {
const previous = doc.line(number);
const col = previous.text.lastIndexOf(">");
if (col >= 0) {
open = previous.from + col;
break;
}
}
}
if (open < 0 || offset <= open) return null;
const afterOpen = doc.lineAt(Math.min(open + 1, doc.length));
let close = -1;
for (
let number = afterOpen.number;
number <= doc.lines && number - afterOpen.number <= XML_VALUE_SCAN_LINES;
number++
) {
const current = doc.line(number);
const col = current.text.indexOf("<", number === afterOpen.number ? open + 1 - current.from : 0);
if (col >= 0) {
close = current.from + col;
break;
}
}
if (close < 0 || offset > close) return null;
let from = open + 1;
let to = close;
const raw = doc.sliceString(from, to);
from += raw.length - raw.trimStart().length;
to -= raw.length - raw.trimEnd().length;
return from < to ? { from, to } : null;
}
/** Configuration names include hyphens and dots even when the editor's language word
* rules split them. Maven element values use the whole value (`cdf-parent`, not its
* hyphenated words). Share this range between decoration and lookup. */
export function navigationWord(view: EditorView, offset: number): { from: number; to: number } | null {
const doc = docOf(view);
if (doc && isMavenPom(doc.path)) {
const value = pomElementValueAt(view, offset);
if (value) return value;
}
if (!isConfigurationDocument(view)) return view.state.wordAt(offset);
const line = view.state.doc.lineAt(offset);
const nameChar = /[\p{L}\p{N}_.$-]/u;
+3 -4
View File
@@ -35,7 +35,7 @@ import { basename } from "@/platform/project";
import { iconNode } from "@/ui/iconNode";
import { applyCodeAction, quickFixesAt } from "./intentions";
import { editorPrefs } from "@/platform/editorSettings";
import { CONTRIBUTED_HOVER, contributedAt, type ContributedHover } from "@/editor/api";
import { CONTRIBUTED_HOVER, contributedAtAll, type ContributedHover } from "@/editor/api";
import { navigationModifierHeld, onNavigationModifier, pointerTarget } from "@/platform/navigationModifier";
import { languageSemantics } from "./semantic";
@@ -47,10 +47,9 @@ function constructAt(state: EditorView["state"], pos: number, language: string |
}
export async function requestHover(view: EditorView, pos: number): Promise<Hover | null> {
const own = contributedAt<ContributedHover>(view.state, CONTRIBUTED_HOVER, pos);
if (own) {
for (const own of contributedAtAll<ContributedHover>(view.state, CONTRIBUTED_HOVER, pos)) {
const h = own(view.state, pos);
if (!h) return null;
if (!h) continue;
const range = { start: offsetToPos(view.state.doc, h.from), end: offsetToPos(view.state.doc, h.to) };
return { contents: { kind: "markdown", value: h.markdown }, range };
}
+10 -4
View File
@@ -46,8 +46,8 @@ import {
} from "@/platform/ipc";
import {
CONTRIBUTED_DEFINITION,
contributedAtAll,
activeEditor,
contributedAt,
whenSynced,
type ContributedDefinition,
type EditorDocContext,
@@ -444,8 +444,12 @@ async function gotoResolved(
done: () => void,
) {
if (kind === "definition" || kind === "declaration") {
const own = contributedAt<ContributedDefinition>(view.state, CONTRIBUTED_DEFINITION, offset);
if (own?.(view, offset)) return;
// More than one feature can attach a definition provider to the same file (the
// MyBatis SQL support and the Maven POM navigator both see XML). Providers decline
// positions they do not own, so try every one instead of letting the first false
// result hide the real target.
const own = contributedAtAll<ContributedDefinition>(view.state, CONTRIBUTED_DEFINITION, offset);
if (own.some((definition) => definition(view, offset))) return;
if (showPhpConstructDocumentation(view, offset)) return;
const before = view.state.doc;
const plugin = await contributedNavigation(view, offset).catch(() => null);
@@ -873,7 +877,9 @@ async function probeNavigation(
const plugin = await contributedNavigation(view, offset).catch(() => null);
if (plugin) return { info: null, plugin };
const doc = docOf(view);
let navigable = !!contributedAt<ContributedDefinition>(view.state, CONTRIBUTED_DEFINITION, offset);
let navigable = contributedAtAll<ContributedDefinition>(view.state, CONTRIBUTED_DEFINITION, offset).some(
(definition) => definition.canHandle?.(view.state, offset) ?? true,
);
if (!navigable && doc) {
const pos = offsetToPos(view.state.doc, offset);
let fromSyntax = false;
+50 -1
View File
@@ -1,6 +1,12 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import {
CONTRIBUTED_DEFINITION,
CONTRIBUTED_HOVER,
type ContributedDefinition,
type ContributedHover,
} from "@/editor/api";
import type { commands, Location } from "@/platform/ipc";
import { usePlatform } from "@/platform/platformInfo";
import { resetNavigationModifier } from "@/platform/navigationModifier";
@@ -18,7 +24,7 @@ vi.mock("@/platform/ipc", async (orig) => {
const { gotoTargets, navigationExtension } = await import("./navigation");
const { lspDoc } = await import("./lsp");
const { quickDefinition } = await import("./hover");
const { quickDefinition, requestHover } = await import("./hover");
const { invalidateConfigurationNavigation } = await import("./configurationNavigation");
const { closePopup } = await import("./popupStore");
const { provideEditorService } = await import("@/workbench/contributions");
@@ -97,6 +103,49 @@ afterEach(() => {
vi.restoreAllMocks();
});
it("tries a later contributed definition when an earlier provider declines", async () => {
const declined = vi.fn<ContributedDefinition>(() => false);
const handled = vi.fn<ContributedDefinition>((_view, _pos) => {
openFile("/p/Handled.java", {});
return true;
});
view = new EditorView({
state: EditorState.create({
doc: "maven",
extensions: [
EditorState.languageData.of(() => [{ [CONTRIBUTED_DEFINITION]: declined }]),
EditorState.languageData.of(() => [{ [CONTRIBUTED_DEFINITION]: handled }]),
],
}),
parent: document.body,
});
await gotoTargets(view, "definition", 0);
expect(declined).toHaveBeenCalledOnce();
expect(handled).toHaveBeenCalledOnce();
expect(openFile).toHaveBeenCalledWith("/p/Handled.java", {});
expect(lspGoto).not.toHaveBeenCalled();
});
it("tries a later contributed hover when an earlier provider declines", async () => {
const declined = vi.fn<ContributedHover>(() => null);
const handled = vi.fn<ContributedHover>(() => ({ from: 1, to: 3, markdown: "handled" }));
view = new EditorView({
state: EditorState.create({
doc: "maven",
extensions: [
EditorState.languageData.of(() => [{ [CONTRIBUTED_HOVER]: declined }]),
EditorState.languageData.of(() => [{ [CONTRIBUTED_HOVER]: handled }]),
],
}),
parent: document.body,
});
expect((await requestHover(view, 1))?.contents.value).toBe("handled");
expect(declined).toHaveBeenCalledOnce();
expect(handled).toHaveBeenCalledOnce();
});
describe.each(cases)("shared definition requests in $language", (c) => {
it("lets a click reuse the hover probe's request for the same word", async () => {
editor(c);
@@ -0,0 +1,18 @@
/* IDEA's Navigate to Managing Dependency icon in the shared editor icon area. */
.managedMarker {
width: 14px;
height: 14px;
display: flex;
align-items: center;
justify-content: center;
padding: 0;
border: 0;
border-radius: var(--radius-small);
background: transparent;
cursor: pointer;
}
.managedMarker:hover,
.managedMarker:focus-visible {
background: var(--bg-hover);
}
+87 -7
View File
@@ -1,10 +1,19 @@
import { describe, expect, it, vi } from "vitest";
import { afterEach, describe, expect, it, vi } from "vitest";
import { fireEvent } from "@testing-library/react";
const ipc = vi.hoisted(() => ({ mavenGotoDeclaration: vi.fn() }));
const ipc = vi.hoisted(() => ({
mavenGotoDeclaration: vi.fn(),
mavenManagedDeclarations: vi.fn(),
cancelRequest: vi.fn(),
}));
const workbench = vi.hoisted(() => ({ openFile: vi.fn() }));
const hints = vi.hoisted(() => ({ showHint: vi.fn() }));
vi.mock("@/platform/ipc", () => ({
isTauri: () => false,
isCancelled: () => false,
nextRequestId: () => 7,
onIdeEvent: () => () => {},
call: async (p: Promise<{ status: string; data?: unknown; error?: unknown }>) => {
const r = await p;
if (r.status !== "ok") throw r.error;
@@ -16,15 +25,25 @@ vi.mock("@/workbench/contributions", () => ({
editorService: () => workbench,
}));
vi.mock("@/editor/lsp/hint", () => ({ showHint: hints.showHint }));
vi.mock("@/editor/api", () => ({
CONTRIBUTED_DEFINITION: "openideaDefinition",
vi.mock("@/editor/api", async (importOriginal) => ({
...(await importOriginal<typeof import("@/editor/api")>()),
whenSynced: () => Promise.resolve(),
}));
import { EditorState } from "@codemirror/state";
import { inArtifactElement, pomNavigationExtension, propertyRefAt } from "./pomNavigation";
import { EditorView } from "@codemirror/view";
import { iconAreaExtension } from "@/editor/core/cm/iconArea";
import type { ContributedDefinition } from "@/editor/api";
import { inArtifactElement, placeManagedMarks, pomNavigationExtension, propertyRefAt } from "./pomNavigation";
const DEFINITION = "openideaDefinition";
let view: EditorView | null = null;
afterEach(() => {
view?.destroy();
view = null;
vi.clearAllMocks();
});
/** An editor state over `text` with the contribution for `path` installed. */
function state(text: string, path = "/p/app/pom.xml") {
@@ -32,20 +51,22 @@ function state(text: string, path = "/p/app/pom.xml") {
doc: text,
extensions: [
pomNavigationExtension({
doc: 1,
path,
language: "xml",
uiMode: "XML",
readOnly: false,
} as Parameters<typeof pomNavigationExtension>[0]),
iconAreaExtension,
],
});
}
const definitionAt = (s: ReturnType<typeof state>, pos: number) =>
s.languageDataAt<(v: { state: typeof s }, p: number) => boolean>(DEFINITION, pos)[0];
s.languageDataAt<ContributedDefinition>(DEFINITION, pos)[0];
/** The definition only reads `view.state`; a bare handle is enough. */
const run = (s: ReturnType<typeof state>, pos: number) => definitionAt(s, pos)!({ state: s }, pos);
const run = (s: ReturnType<typeof state>, pos: number) => definitionAt(s, pos)!({ state: s } as EditorView, pos);
const pom = `<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0">
@@ -130,6 +151,13 @@ describe("POM go to declaration", () => {
expect(definitionAt(s, pom.indexOf("<parent>"))).toBeUndefined();
});
it("declines non-navigation POM positions without invoking the definition", () => {
const s = state(pom);
const definition = definitionAt(s, pom.indexOf("<artifactId>other-lib"))!;
expect(definition.canHandle?.(s, pom.indexOf("<artifactId>other-lib"))).toBe(true);
expect(definition.canHandle?.(s, pom.indexOf("<modelVersion>"))).toBe(false);
});
it("opens the declaration the backend resolved", async () => {
const target = {
path: "/p/pom.xml",
@@ -152,6 +180,58 @@ describe("POM go to declaration", () => {
});
});
it("places one managed-dependency marker per backend line", () => {
const s = state(pom);
const target = {
path: "/p/pom.xml",
range: { start: { line: 1, col: 2 }, end: { line: 1, col: 8 } },
kind: "managedDependency" as const,
label: "com.example:other-lib",
};
expect(
placeManagedMarks(s.doc, [
{ line: 15, version: "1.2.3", target },
{ line: 15, version: "ignored", target },
{ line: 999, version: null, target },
]),
).toEqual([{ pos: s.doc.line(16).from, link: { line: 15, version: "1.2.3", target } }]);
});
it("opens the managing declaration from its gutter icon", async () => {
const target = {
path: "/p/pom.xml",
range: { start: { line: 4, col: 6 }, end: { line: 4, col: 14 } },
kind: "managedDependency" as const,
label: "com.example:other-lib",
};
ipc.mavenManagedDeclarations.mockResolvedValue({
status: "ok",
data: [
{ line: pom.slice(0, pom.indexOf("<artifactId>other-lib")).split("\n").length - 1, version: "1.0", target },
],
});
view = new EditorView({ state: state(pom), parent: document.body });
await vi.waitFor(() => expect(ipc.mavenManagedDeclarations).toHaveBeenCalledWith("/p/app/pom.xml", 7));
await vi.waitFor(() => expect(view!.dom.querySelector("[data-managed-dependency]")).not.toBeNull());
fireEvent.click(view.dom.querySelector("[data-managed-dependency]")!);
await vi.waitFor(() =>
expect(workbench.openFile).toHaveBeenCalledWith("/p/pom.xml", {
selection: { line: 4, col: 6, endLine: 4, endCol: 14 },
}),
);
});
it("cancels an in-flight gutter refresh when the document changes", async () => {
let finish!: (value: unknown) => void;
ipc.mavenManagedDeclarations.mockImplementation(() => new Promise((resolve) => (finish = resolve)));
view = new EditorView({ state: state(pom), parent: document.body });
await vi.waitFor(() => expect(ipc.mavenManagedDeclarations).toHaveBeenCalledOnce());
view.dispatch({ changes: { from: 0, insert: " " } });
await vi.waitFor(() => expect(ipc.cancelRequest).toHaveBeenCalledWith(7));
finish({ status: "ok", data: [] });
});
it("says so when nothing resolves, without navigating", async () => {
ipc.mavenGotoDeclaration.mockResolvedValue({ status: "ok", data: null });
const s = state(pom);
+224 -23
View File
@@ -2,21 +2,41 @@
* Go to declaration in `pom.xml`: ⌘/Ctrl-click (or ⌘B) on a `${property}` reference
* opens the `<properties>` entry that defines it — the POM's own, else one inherited
* along the parent chain (a parent POM outside the project opens from the local
* repository, read-only as a plain file) — and a dependency / plugin whose version a
* `<dependencyManagement>` / `<pluginManagement>` entry provides opens that managing
* declaration; otherwise a dependency, plugin or `<parent>` opens the artifact's own POM
* (a project module's, else the local repository's). The backend resolves both with the build model's POM reader and parent
* resolver; here only cheap eligibility is computed (a reference span, an artifact
* element), so the ⌘-hover underline stays out of the rest of the file, and nothing
* resolves to no jump at all: an unresolvable property or parent never navigates
* somewhere unrelated.
* repository, read-only as a plain file). A dependency, plugin or `<parent>` opens the
* artifact's own POM (a project module first, then the local repository). Unversioned
* declarations also get IDEA's "Navigate to managing dependency" gutter icon, which
* opens the exact `<dependencyManagement>` / `<pluginManagement>` entry — including
* one in a parent POM or imported BOM — that controls the version. The backend does
* the resolution; here only cheap eligibility is computed, so the ⌘-hover underline
* stays out of the rest of the file and no marker promises a target that does not exist.
*/
import { EditorState, type Extension } from "@codemirror/state";
import { CONTRIBUTED_DEFINITION, type ContributedDefinition, type EditorDocContext, whenSynced } from "@/editor/api";
import { EditorState, RangeSet, StateEffect, StateField, type Extension, type Text } from "@codemirror/state";
import { EditorView, GutterMarker, ViewPlugin, type ViewUpdate } from "@codemirror/view";
import {
CONTRIBUTED_DEFINITION,
iconAreaSource,
mapLineStart,
onEditorEvent,
whenSynced,
type ContributedDefinition,
type EditorDocContext,
} from "@/editor/api";
import { showHint } from "@/editor/lsp/hint";
import { isMavenPom } from "@/platform/buildFiles";
import { tx } from "@/platform/i18n";
import { call, commands } from "@/platform/ipc";
import {
call,
commands,
isCancelled,
nextRequestId,
onIdeEvent,
type PomGoto,
type PomManagedDeclaration,
type RequestId,
} from "@/platform/ipc";
import { gutterIconMarkup } from "@/ui";
import { editorService } from "@/workbench/contributions";
import styles from "./PomNavigation.module.css";
/** The `${property}` reference covering `at`, if any (clicking the `$` counts). */
export function propertyRefAt(text: string, at: number): { from: number; to: number } | null {
@@ -43,9 +63,193 @@ export function inArtifactElement(text: string, at: number): boolean {
return inside("dependency", text, at) || inside("plugin", text, at) || inside("parent", text, at);
}
export interface ManagedMark {
pos: number;
link: PomManagedDeclaration;
}
/** Places the backend's 0-based lines in a document, one icon per declaration line. */
export function placeManagedMarks(doc: Text, links: readonly PomManagedDeclaration[]): ManagedMark[] {
const seen = new Set<number>();
const out: ManagedMark[] = [];
for (const link of links) {
if (!Number.isInteger(link.line) || link.line < 0 || link.line >= doc.lines || seen.has(link.line)) continue;
seen.add(link.line);
out.push({ pos: doc.line(link.line + 1).from, link });
}
return out;
}
const setManagedMarks = StateEffect.define<ManagedMark[]>();
const managedMarksField = StateField.define<ManagedMark[]>({
create: () => [],
update(value, tr) {
for (const effect of tr.effects) if (effect.is(setManagedMarks)) return effect.value;
if (!tr.docChanged || !value.length) return value;
return value.map((mark) => ({ ...mark, pos: mapLineStart(tr, mark.pos) }));
},
});
const fileName = (path: string) => path.split(/[\\/]/).pop() || path;
function managedTitle(link: PomManagedDeclaration): string {
const location = `${fileName(link.target.path)}:${link.target.range.start.line + 1}`;
return link.version ? tx`Managed version ${link.version} in ${location}` : tx`Managed in ${location}`;
}
class ManagedMarker extends GutterMarker {
constructor(
readonly mark: ManagedMark,
readonly open: () => void,
) {
super();
}
override eq(other: GutterMarker): boolean {
const a = this.mark.link;
const b = other instanceof ManagedMarker ? other.mark.link : null;
return (
!!b &&
a.version === b.version &&
a.target.path === b.target.path &&
a.target.range.start.line === b.target.range.start.line &&
a.target.range.start.col === b.target.range.start.col
);
}
override toDOM(): Node {
const button = document.createElement("button");
button.type = "button";
button.className = styles.managedMarker ?? "";
button.dataset.managedDependency = "";
button.title = managedTitle(this.mark.link);
button.setAttribute("aria-label", button.title);
button.innerHTML = gutterIconMarkup("gutter-navigate") ?? "";
// Keep the editor caret where it was; a normal click then runs the navigation,
// so the icon also works from the keyboard.
button.addEventListener("mousedown", (event) => {
event.preventDefault();
event.stopPropagation();
});
button.addEventListener("click", (event) => {
event.preventDefault();
event.stopPropagation();
this.open();
});
return button;
}
}
function openGoto(goto: PomGoto): Promise<void> | void {
return editorService().openFile(goto.path, {
selection: {
line: goto.range.start.line,
col: goto.range.start.col,
endLine: goto.range.end.line,
endCol: goto.range.end.col,
},
});
}
function openManaged(view: EditorView, target: PomGoto): void {
void Promise.resolve(openGoto(target)).catch((e: unknown) =>
showHint(view, e instanceof Error ? e.message : String(e), { tone: "error" }),
);
}
/** The icon area is shared with run, inheritance and plugin markers; press handling is source-scoped. */
function managedGutter(ctx: EditorDocContext): Extension {
if (ctx.doc < 0) return [];
return [
managedMarksField,
ViewPlugin.fromClass(
class {
private timer: ReturnType<typeof setTimeout> | undefined;
private generation = 0;
private inFlight: RequestId | undefined;
private off: () => void;
constructor(readonly view: EditorView) {
this.schedule(0);
const offEditor = onEditorEvent((event) => {
if (
(event.type === "docChanged" || event.type === "docSaved") &&
event.path !== ctx.path &&
isMavenPom(event.path)
)
this.schedule(500);
});
const offFiles = onIdeEvent("fsChanged", (event) => {
if ([...event.created, ...event.modified, ...event.removed].some(isMavenPom)) this.schedule(500);
});
const offRoots = onIdeEvent("projectRootsChanged", () => this.schedule(300));
const offSettings = onIdeEvent("settingsChanged", (event) => {
if (event.key.startsWith("languages.java.")) this.schedule(300);
});
this.off = () => {
offEditor();
offFiles();
offRoots();
offSettings();
};
}
update(update: ViewUpdate) {
if (update.docChanged) this.schedule();
}
schedule(delay = 300) {
clearTimeout(this.timer);
if (this.inFlight !== undefined) {
void commands.cancelRequest(this.inFlight);
this.inFlight = undefined;
}
this.timer = setTimeout(() => void this.refresh(), delay);
}
async refresh() {
const generation = ++this.generation;
const current = this.view.state.doc;
const request = nextRequestId();
this.inFlight = request;
try {
await whenSynced(this.view);
if (generation !== this.generation || this.view.state.doc !== current) return;
const links = await call(commands.mavenManagedDeclarations(ctx.path, request));
if (generation !== this.generation || this.inFlight !== request || this.view.state.doc !== current) return;
this.view.dispatch({ effects: setManagedMarks.of(placeManagedMarks(current, links)) });
} catch (e) {
if (!isCancelled(e) && generation === this.generation) console.debug("[POM managed dependencies]", e);
} finally {
if (this.inFlight === request) this.inFlight = undefined;
}
}
destroy() {
this.off();
clearTimeout(this.timer);
if (this.inFlight !== undefined) void commands.cancelRequest(this.inFlight);
this.generation++;
}
},
),
iconAreaSource.of({
order: 25,
markers: (view) =>
RangeSet.of(
view.state
.field(managedMarksField)
.map((mark) => new ManagedMarker(mark, () => openManaged(view, mark.link.target)).range(mark.pos)),
true,
),
}),
];
}
/** Go to declaration in a POM of the project (or an opened parent POM of the local repository). */
export function pomNavigationExtension(ctx: EditorDocContext): Extension {
if (ctx.virtual || !/(^|\/)pom\.xml$/.test(ctx.path)) return [];
if (ctx.virtual || !isMavenPom(ctx.path)) return [];
const eligible = (state: EditorState, pos: number) => {
const text = state.doc.toString();
return propertyRefAt(text, pos) !== null || inArtifactElement(text, pos);
@@ -69,14 +273,7 @@ export function pomNavigationExtension(ctx: EditorDocContext): Extension {
return;
}
if (view.state.doc !== doc) return; // The user kept typing while the POM resolved.
void editorService().openFile(goto.path, {
selection: {
line: goto.range.start.line,
col: goto.range.start.col,
endLine: goto.range.end.line,
endCol: goto.range.end.col,
},
});
void openGoto(goto);
})
.catch((e: unknown) =>
showHint(view, e instanceof Error ? e.message : String(e), {
@@ -85,7 +282,11 @@ export function pomNavigationExtension(ctx: EditorDocContext): Extension {
);
return true;
};
return EditorState.languageData.of((state, pos) =>
eligible(state, pos) ? [{ [CONTRIBUTED_DEFINITION]: definition }] : [],
);
definition.canHandle = eligible;
return [
EditorState.languageData.of((state, pos) =>
eligible(state, pos) ? [{ [CONTRIBUTED_DEFINITION]: definition }] : [],
),
managedGutter(ctx),
];
}
+4 -1
View File
@@ -108,7 +108,7 @@ function inspections(path: string, sql: SqlText): Extension {
}
function definition(path: string, sql: SqlText): ContributedDefinition {
return (view, pos) => {
const handle: ContributedDefinition = (view, pos) => {
if (sql.at && !sql.at(view.state, pos)) return false;
const r = resolver(path, view.state, sql).resolveAt(pos);
const sym = r?.symbol;
@@ -143,6 +143,9 @@ function definition(path: string, sql: SqlText): ContributedDefinition {
return true;
}
};
const at = sql.at;
if (at) handle.canHandle = (state, pos) => at(state, pos);
return handle;
}
const code = (s: string) => `\`${s.replace(/`/g, "")}\``;
+5
View File
@@ -4,3 +4,8 @@ export function isGradleBuildInput(path: string): boolean {
path,
);
}
/** A project POM or a POM installed in the local Maven repository. */
export function isMavenPom(path: string): boolean {
return /(^|[\\/])(?:pom\.xml|[^\\/]+\.pom)$/i.test(path);
}
+3 -1
View File
@@ -2730,5 +2730,7 @@
"Caret": "Caret",
"Code Structure": "Code Structure",
"Presentation": "Presentation",
"Code Assistance": "Code Assistance"
"Code Assistance": "Code Assistance",
"Managed version {version} in {location}": "Managed version {version} in {location}",
"Managed in {location}": "Managed in {location}"
}
+3 -1
View File
@@ -9096,5 +9096,7 @@
"Remove All Watches": "移除所有监视",
"GitHub account": "GitHub 账号",
"Leave empty to use the active GitHub CLI account. OpenIDEA resolves the token at launch and never stores it.": "留空则使用 GitHub CLI 当前登录的账号。OpenIDEA 在启动时获取令牌,不会保存它。",
"github-username": "GitHub 用户名"
"github-username": "GitHub 用户名",
"Managed version {version} in {location}": "版本 {version} 由 {location} 管理",
"Managed in {location}": "由 {location} 管理"
}