feat(java): strike out deprecated classes in the Project view and editor tabs (#4349)

The JVM file presentation now reports whether a file's primary type is deprecated: annotated @Deprecated (Java and Kotlin), or a Java type whose Javadoc has a @deprecated tag. The Project view and editor tabs strike the name out, and an error marker on the same file still shows.

Closes #4151
This commit is contained in:
l0ng-ai
2026-11-18 23:21:04 +08:00
committed by GitHub
parent 6829022b71
commit 6bf69cfb2a
10 changed files with 99 additions and 21 deletions
+18 -1
View File
@@ -24,6 +24,8 @@ pub struct JvmPresentation {
pub kind: Option<JvmTypeKind>,
pub spring_boot: bool,
pub runnable: bool,
/// `@Deprecated`, or a Java `@deprecated` Javadoc tag.
pub deprecated: bool,
}
fn text<'a>(node: Node, source: &'a str) -> &'a str {
@@ -139,6 +141,19 @@ pub fn jvm_type_header(source: &str) -> Option<&str> {
None
}
/// The Javadoc right before `node` has a `@deprecated` block tag.
fn javadoc_deprecated(node: Node, source: &str) -> bool {
let Some(doc) = node.prev_named_sibling().filter(|n| n.kind() == "block_comment") else {
return false;
};
let doc = text(doc, source);
doc.starts_with("/**")
&& doc.lines().any(|line| {
let line = line.trim_start().trim_start_matches("/**").trim_start_matches('*').trim_start();
line.strip_prefix("@deprecated").is_some_and(|rest| !rest.starts_with(|c: char| c.is_alphanumeric()))
})
}
fn is_type(node: Node) -> bool {
matches!(
node.kind(),
@@ -221,7 +236,9 @@ impl StructureService {
})
})
});
Ok(JvmPresentation { kind: Some(kind), spring_boot, runnable })
let deprecated = modifiers.is_some_and(|m| annotation(m, snap.text, "Deprecated"))
|| cx.grammar == "java" && javadoc_deprecated(node, snap.text);
Ok(JvmPresentation { kind: Some(kind), spring_boot, runnable, deprecated })
})
}
}
+26
View File
@@ -103,3 +103,29 @@ fn a_cut_off_file_is_classified_by_its_type_header() {
let closed = format!("{}}}", jvm_type_header(cut).unwrap());
assert_eq!(presentation("java", &closed).kind, Some(AbstractClass));
}
#[test]
fn deprecated_primary_types() {
for (language, source) in [
("java", "@Deprecated public class Foo {}"),
("java", "@java.lang.Deprecated(since = \"2\") interface Foo {}"),
("java", "/**\n * Old.\n * @deprecated use Bar\n */\npublic class Foo {}"),
("java", "/** @deprecated */ class Foo {}"),
("kotlin", "@Deprecated(\"use Bar\") class Foo"),
("kotlin", "@kotlin.Deprecated(\"x\", level = DeprecationLevel.ERROR) object Foo {}"),
] {
assert!(presentation(language, source).deprecated, "{language}: {source}");
}
for (language, source) in [
("java", "public class Foo {}"),
("java", "/* @deprecated */ class Foo {}"),
("java", "// @Deprecated\nclass Foo {}"),
("java", "/** See {@link Old}; @deprecatedSince is not a tag. */ class Foo {}"),
("java", "class Foo { @Deprecated void old() {} }"),
("java", "@Deprecated class Other {} class Foo {}"),
("kotlin", "class Foo { @Deprecated(\"x\") fun old() {} }"),
("kotlin", "/** @deprecated */ class Foo"),
] {
assert!(!presentation(language, source).deprecated, "{language}: {source}");
}
}
+2
View File
@@ -7465,6 +7465,8 @@ export type JvmPresentation = {
kind: JvmTypeKind | null,
springBoot: boolean,
runnable: boolean,
/** `@Deprecated`, or a Java `@deprecated` Javadoc tag. */
deprecated: boolean,
};
export type JvmReferrer = {
@@ -101,6 +101,9 @@
color: var(--fg-muted);
margin-left: -2px;
}
.deprecated {
text-decoration-line: line-through;
}
.dupe {
color: var(--fg-faint);
margin-left: 4px;
+8 -6
View File
@@ -1,5 +1,5 @@
import { ContributedToolbar } from "@/workbench/ContributedToolbar";
import { useFilePresentationIcons } from "@/ui/filePresentation";
import { useFilePresentations } from "@/ui/filePresentation";
/**
* The editor area: split layout of panes, each with IDEA-style tabs (preview
* tab in italics, pinned tabs, modified dot, file icons coloured by file
@@ -190,8 +190,8 @@ function PaneView({ paneId }: { paneId: string }) {
const { showExtension, markModified, showCloseButton, showFileIcon, showDirectoryForNonUnique, showFullPathOnHover } =
tabPrefs;
const fileIcons = useFilePresentationIcons(
showFileIcon ? tabs.flatMap((t) => (t.input.kind === "file" && t.input.path ? [t.input.path] : [])) : [],
const files = useFilePresentations(
tabs.flatMap((t) => (t.input.kind === "file" && t.input.path ? [t.input.path] : [])),
);
const items: TabItem[] = useMemo(() => {
// A kind's title may change without the tab state (a renamed agent task).
@@ -210,18 +210,20 @@ function PaneView({ paneId }: { paneId: string }) {
: null;
const kindMark = tabTrailing(t.input, kinds);
const pin = t.pinned ? <Icon name="pin" size={11} className={styles.pin} label="Pinned" /> : null;
const file = t.input.kind === "file" && t.input.path ? files.get(t.input.path) : undefined;
const title = markModified && dirty[i] ? `*${name}` : name;
return {
id: t.id,
label: (
<>
{markModified && dirty[i] ? `*${name}` : name}
{file?.deprecated ? <span className={styles.deprecated}>{title}</span> : title}
{dupe && <span className={styles.dupe}>{dupe}</span>}
</>
),
text: dupe ? `${name} — ${dupe}` : name,
icon: showFileIcon
? t.input.kind === "file" && t.input.path
? fileIcons.get(t.input.path)
? file?.icon
: tabIcon(t.input, kinds)
: undefined,
italic: t.preview,
@@ -245,7 +247,7 @@ function PaneView({ paneId }: { paneId: string }) {
};
});
}, [
fileIcons,
files,
tabs,
kinds,
titleRevision,
@@ -56,6 +56,9 @@
.excluded {
color: var(--vcs-ignored);
}
.deprecated {
text-decoration-line: line-through;
}
.error {
text-decoration-line: underline;
text-decoration-style: wavy;
@@ -63,6 +66,10 @@
text-decoration-skip-ink: none;
text-underline-offset: 3px;
}
/* The error's wavy underline takes the text decoration; the strike-out is drawn underneath. */
.deprecated.error {
background: linear-gradient(currentColor, currentColor) 0 55% / 100% 1px no-repeat;
}
.suffix {
display: inline-flex;
flex: 0 1 auto;
@@ -347,6 +347,8 @@ const Row = memo(function Row({
// Maven / Gradle module folders are bold too, as in IDEA.
moduleFolder && styles.moduleLabel,
faded && !deco.color && styles.excluded,
// IDEA strikes out deprecated classes.
file?.deprecated && styles.deprecated,
deco.error && styles.error,
)}
style={deco.color ? { color: deco.color } : undefined}
+17 -10
View File
@@ -16,10 +16,10 @@ vi.mock("@/platform/ipc", async (original) => ({
vi.mock("@/platform/projectPresentation", () => ({
useProjectPresentation: () => ({ spring: false, modules: new Map() }),
}));
import { useFilePresentation, useFilePresentationIcons } from "./filePresentation";
import { useFilePresentation, useFilePresentations } from "./filePresentation";
const answer = (path: string, kind = "interface") => ({
path,
presentation: { kind, springBoot: false, runnable: false },
presentation: { kind, springBoot: false, runnable: false, deprecated: path.includes("Old") },
});
const tick = async () => {
await act(async () => {
@@ -39,25 +39,32 @@ describe("visible file resolver", () => {
vi.useRealTimers();
});
it("shows a plain icon immediately and batches mounted paths only", async () => {
const { result } = renderHook(() => useFilePresentationIcons(["/p/Foo.java", "/p/Bar.kt", "/p/config.yml"]));
expect(result.current.get("/p/Foo.java")).toBe("file-java");
const { result } = renderHook(() => useFilePresentations(["/p/Foo.java", "/p/Bar.kt", "/p/config.yml"]));
expect(result.current.get("/p/Foo.java")?.icon).toBe("file-java");
expect(backend.resolve).not.toHaveBeenCalled();
await tick();
expect(backend.resolve).toHaveBeenCalledOnce();
expect(backend.resolve.mock.calls[0]?.[0]).toEqual(["/p/Foo.java", "/p/Bar.kt"]);
expect(result.current.get("/p/Foo.java")).toBe("interface");
expect(result.current.get("/p/Foo.java")?.icon).toBe("interface");
expect(result.current.get("/p/Foo.java")?.deprecated).toBe(false);
});
it("marks deprecated types", async () => {
const { result } = renderHook(() => useFilePresentations(["/p/OldApi.java"]));
expect(result.current.get("/p/OldApi.java")?.deprecated).toBe(false);
await tick();
expect(result.current.get("/p/OldApi.java")?.deprecated).toBe(true);
const single = renderHook(() => useFilePresentation("/p/OldApi.java"));
expect(single.result.current.deprecated).toBe(true);
});
it("drops unmounted requests and splits large sets into bounded batches", async () => {
const dropped = renderHook(() => useFilePresentation("/p/Invisible.java"));
dropped.unmount();
const { result } = renderHook(() =>
useFilePresentationIcons(Array.from({ length: 130 }, (_, i) => `/p/F${i}.java`)),
);
const { result } = renderHook(() => useFilePresentations(Array.from({ length: 130 }, (_, i) => `/p/F${i}.java`)));
await tick();
await tick();
await tick();
expect(backend.resolve.mock.calls.map(([paths]) => paths.length)).toEqual([64, 64, 2]);
expect(result.current.get("/p/F129.java")).toBe("interface");
expect(result.current.get("/p/F129.java")?.icon).toBe("interface");
expect(backend.resolve.mock.calls.flatMap(([paths]) => paths)).not.toContain("/p/Invisible.java");
});
it("invalidates on watcher changes and rejects an in-flight stale result", async () => {
@@ -94,7 +101,7 @@ describe("visible file resolver", () => {
});
it("caches failures instead of continuously retrying visible batches", async () => {
backend.resolve.mockRejectedValue(new Error("offline"));
renderHook(() => useFilePresentationIcons(Array.from({ length: 65 }, (_, i) => `/p/F${i}.java`)));
renderHook(() => useFilePresentations(Array.from({ length: 65 }, (_, i) => `/p/F${i}.java`)));
await tick();
await tick();
await tick();
+6 -1
View File
@@ -9,7 +9,12 @@ const roots: RootFolder[] = [
{ path: "src/main/resources", kind: "resources", detectedFrom: "pom.xml" },
{ path: "src/test/resources", kind: "testResources", detectedFrom: "pom.xml" },
];
const type = (kind: JvmPresentation["kind"]): JvmPresentation => ({ kind, springBoot: false, runnable: false });
const type = (kind: JvmPresentation["kind"]): JvmPresentation => ({
kind,
springBoot: false,
runnable: false,
deprecated: false,
});
const icon = (path: string, info: JvmPresentation | null = null, spring = false) =>
presentationIcon(`/p/${path}`, info, roots, "/p", spring);
+10 -3
View File
@@ -163,11 +163,15 @@ export function useFilePresentation(path: string, mtime?: number | null) {
const root = useProject((s) => s.project?.root ?? null);
const build = useProjectPresentation();
const icon = presentationIcon(path, info, roots, root, build.spring);
return { icon, runnable: !!info?.runnable && icon !== "spring-boot" && icon !== "jvm-test" };
return {
icon,
runnable: !!info?.runnable && icon !== "spring-boot" && icon !== "jvm-test",
deprecated: !!info?.deprecated,
};
}
/** Tab strips resolve their mounted file tabs through the same batch as tree rows. */
export function useFilePresentationIcons(paths: readonly string[]) {
export function useFilePresentations(paths: readonly string[]) {
const key = JSON.stringify(paths);
useEffect(() => {
const disposers = (JSON.parse(key) as string[]).map(mount);
@@ -183,7 +187,10 @@ export function useFilePresentationIcons(paths: readonly string[]) {
new Map(
(JSON.parse(key) as string[]).map((path) => [
path,
presentationIcon(path, entries.get(path), roots, root, build.spring),
{
icon: presentationIcon(path, entries.get(path), roots, root, build.spring),
deprecated: !!entries.get(path)?.deprecated,
},
]),
),
// eslint-disable-next-line react-hooks/exhaustive-deps -- iconRevision: the file icon theme changed