feat(editor): a Code Vision switch, toggle action and hint menu (#3815)

Code Vision could only be turned off one kind at a time. A master setting, editor.inlay.codeVision (Editor › Inlay Hints › Code Vision › Show Code Vision, on by default), hides usages, author and language-server lenses while keeping the per-kind choices; a Code Vision toggle action (editor.toggleCodeVision, no default shortcut) flips it; and a right-click on a hint offers Hide Usages / Hide Code Author for that hint, Hide Code Vision and Code Vision Settings…. Code Vision is kept untranslated as a product name in the catalog checks.

Closes #3785

Co-authored-by: bertyhell <1710840+bertyhell@users.noreply.github.com>
This commit is contained in:
Bert Verhelst
2026-11-17 02:36:56 +08:00
committed by GitHub
co-authored by bertyhell
parent 567e45f830
commit 2f68c83bcd
16 changed files with 250 additions and 25 deletions
+3
View File
@@ -343,6 +343,8 @@ pub struct InlayHintsSettings {
/// Hints of other kinds (chaining, closing labels…).
pub other: bool,
pub disabled_languages: Vec<String>,
/// Code vision as a whole (usages, author and language-server lenses); the switches below apply while it is on.
pub code_vision: bool,
/// Code vision: usages above declarations.
pub code_vision_usages: bool,
/// Code vision: last author of a declaration (VCS blame) beside its usages.
@@ -373,6 +375,7 @@ impl Default for InlayHintsSettings {
parameters: true,
other: true,
disabled_languages: Vec::new(),
code_vision: true,
code_vision_usages: true,
code_vision_author: true,
code_vision_no_usages: true,
+2
View File
@@ -6729,6 +6729,8 @@ export type InlayHintsSettings = {
/** Hints of other kinds (chaining, closing labels…). */
other?: boolean,
disabledLanguages?: string[],
/** Code vision as a whole (usages, author and language-server lenses); the switches below apply while it is on. */
codeVision?: boolean,
/** Code vision: usages above declarations. */
codeVisionUsages?: boolean,
/** Code vision: last author of a declaration (VCS blame) beside its usages. */
+9
View File
@@ -79,6 +79,7 @@ import { menuGroupItems, notifications } from "@/workbench/contributions";
import { togglePinSelectedContent } from "@/workbench/toolwindows/content";
import { useToolWindowLayout } from "@/workbench/toolwindows/store";
import { toggleReadOnly } from "./fileAttributes";
import { codeVisionShown, toggleCodeVision } from "./codeVision";
import { openNavBarPopup } from "./view/NavBarPopup";
import {
cachedStructureQueries,
@@ -754,6 +755,14 @@ export function registerEditorActions(): () => void {
"rainbow parentheses",
"color scheme",
]),
{
id: "editor.toggleCodeVision",
title: "Code Vision",
category: "Editor",
keywords: ["code lens", "usages", "code author", "git author", "inlay hints", "show", "hide"],
toggled: codeVisionShown,
run: () => toggleCodeVision(),
},
text("code.commentLine", "Comment with Line Comment", (v) => commentLine(v)),
text("code.commentBlock", "Comment with Block Comment", (v) => commentBlock(v)),
text("code.duplicateLine", "Duplicate Line or Selection", (v) => duplicateLineOrSelection(v)),
+11 -1
View File
@@ -2,10 +2,13 @@
* Renders `codeLenses` (editor/api) as one small hint row above the target
* line, indented like the line (IDEA "3 usages Run test" inlays), and those
* whose kind is set to "right" (`codeLensPositions`) after the end of that line.
* Right-click offers to hide the hint's kind or all of Code Vision.
*/
import { EditorState, Facet, RangeSetBuilder, type Extension } from "@codemirror/state";
import { Decoration, EditorView, WidgetType, type DecorationSet } from "@codemirror/view";
import { codeLenses, type CodeLens } from "@/editor/api";
import { showContextMenu } from "@/ui";
import { codeVisionMenuItems } from "../codeVision";
import { LINE_INSET } from "./lineInset";
/**
@@ -98,7 +101,7 @@ class LensWidget extends WidgetType {
override toDOM(view: EditorView): HTMLElement {
// The inline one shares no class with the row, so none of the row's block styles reach into the line.
const dom = document.createElement(this.inline ? "span" : "div");
const dom: HTMLElement = document.createElement(this.inline ? "span" : "div");
dom.className = this.inline ? "cm-openidea-lensInline" : "cm-openidea-lens";
// The line-end hint draws from a zero-width anchor in an absolutely positioned inner box: an
// in-flow box would wrap to the next line when the line is soft-wrapped and there is no room.
@@ -108,6 +111,12 @@ class LensWidget extends WidgetType {
dom.appendChild(host);
}
this.fill(host, view);
dom.addEventListener("contextmenu", (e) => {
e.preventDefault();
e.stopPropagation();
const item = (e.target as Element | null)?.closest?.<HTMLElement>(".cm-openidea-lensItem");
showContextMenu(e, codeVisionMenuItems(item?.dataset.kind));
});
return dom;
}
@@ -131,6 +140,7 @@ class LensWidget extends WidgetType {
const el = document.createElement(lens.run ? "button" : "span");
el.className = lens.run ? "cm-openidea-lensItem cm-openidea-lensAction" : "cm-openidea-lensItem";
if (lens.tooltip) el.title = lens.tooltip;
if (lens.kind) el.dataset.kind = lens.kind;
if (lens.icon && ICONS[lens.icon]) {
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute("viewBox", "0 0 16 16");
+65
View File
@@ -0,0 +1,65 @@
import { afterEach, describe, expect, it, vi } from "vitest";
const ipc = vi.hoisted(() => ({
settingsSet: vi.fn(async (_scope: string, key: string, value: string) => ({
status: "ok" as const,
data: { editor: { inlay: { [key.split(".").pop()!]: JSON.parse(value) } } },
})),
}));
vi.mock("@/platform/ipc", async (orig) => {
const real = await orig<typeof import("@/platform/ipc")>();
return { ...real, isTauri: () => true, commands: { ...real.commands, ...ipc } };
});
const executeAction = vi.hoisted(() => vi.fn(async () => true));
vi.mock("@/platform/actions", () => ({ executeAction }));
const { codeVisionMenuItems, codeVisionShown, toggleCodeVision } = await import("./codeVision");
const { useProject } = await import("@/platform/project");
type Item = { label?: string; kind?: string; run?: () => void };
const labels = (items: Item[]) => items.map((i) => i.label ?? i.kind);
afterEach(() => {
useProject.setState({ settings: null });
vi.clearAllMocks();
});
describe("Code Vision switch", () => {
it("toggles the global setting and keeps the per-kind choices", async () => {
useProject.setState({ settings: { editor: { inlay: { codeVisionUsages: false } } } as never });
expect(codeVisionShown()).toBe(true);
await toggleCodeVision();
expect(ipc.settingsSet).toHaveBeenLastCalledWith("global", "editor.inlay.codeVision", "false");
expect(codeVisionShown()).toBe(false);
await toggleCodeVision();
expect(ipc.settingsSet).toHaveBeenLastCalledWith("global", "editor.inlay.codeVision", "true");
expect(ipc.settingsSet).toHaveBeenCalledTimes(2);
});
});
describe("Code Vision hint menu", () => {
it("offers to hide the clicked kind, all of Code Vision, or open its settings", () => {
expect(labels(codeVisionMenuItems("usages") as Item[])).toEqual([
"Hide Usages",
"Hide Code Vision",
"separator",
"Code Vision Settings…",
]);
expect(labels(codeVisionMenuItems("author") as Item[])[0]).toBe("Hide Code Author");
expect(labels(codeVisionMenuItems(undefined) as Item[])).toEqual([
"Hide Code Vision",
"separator",
"Code Vision Settings…",
]);
});
it("writes the matching setting or opens the Inlay Hints page", () => {
const [hideAuthor, hideAll, , settings] = codeVisionMenuItems("author") as Item[];
hideAuthor!.run!();
expect(ipc.settingsSet).toHaveBeenLastCalledWith("global", "editor.inlay.codeVisionAuthor", "false");
hideAll!.run!();
expect(ipc.settingsSet).toHaveBeenLastCalledWith("global", "editor.inlay.codeVision", "false");
settings!.run!();
expect(executeAction).toHaveBeenCalledWith("file.settings", "editor.inlayHints");
});
});
+44
View File
@@ -0,0 +1,44 @@
/** Code Vision switches (Settings › Editor › Inlay Hints › Code Vision) shared by its action and its rows' menu. */
import { executeAction } from "@/platform/actions";
import { editorPrefs } from "@/platform/editorSettings";
import { call, commands } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { notifications } from "@/workbench/contributions";
import type { MenuItem } from "@/ui";
type CodeVisionKey = "codeVision" | "codeVisionUsages" | "codeVisionAuthor";
export async function setCodeVisionSetting(key: CodeVisionKey, on: boolean): Promise<void> {
try {
useProject.setState({
settings: await call(commands.settingsSet("global", `editor.inlay.${key}`, JSON.stringify(on))),
});
} catch (e) {
notifications().notify({
level: "error",
title: "Cannot change the setting",
body: e instanceof Error ? e.message : String(e),
});
}
}
export const codeVisionShown = (): boolean => editorPrefs().inlay.codeVision;
/** Shows or hides every Code Vision row and hint at once, keeping the per-kind choices. */
export const toggleCodeVision = (): Promise<void> => setCodeVisionSetting("codeVision", !codeVisionShown());
/** Right-click on a Code Vision hint (IDEA's code vision context menu). `kind` is the clicked hint's `CodeLens.kind`. */
export function codeVisionMenuItems(kind: string | undefined): MenuItem[] {
const own: MenuItem[] =
kind === "usages"
? [{ label: "Hide Usages", run: () => void setCodeVisionSetting("codeVisionUsages", false) }]
: kind === "author"
? [{ label: "Hide Code Author", run: () => void setCodeVisionSetting("codeVisionAuthor", false) }]
: [];
return [
...own,
{ label: "Hide Code Vision", run: () => void setCodeVisionSetting("codeVision", false) },
{ kind: "separator" },
{ label: "Code Vision Settings…", run: () => void executeAction("file.settings", "editor.inlayHints") },
];
}
+20
View File
@@ -119,6 +119,26 @@ describe("author hint", () => {
});
});
describe("Code Vision switch", () => {
it("hides usages and author while off and brings back the kinds still chosen", async () => {
ipc.vcsBlame.mockResolvedValue(ok([{ commit: "c1", author: "Ann", timeMs: 1, summary: "init" }]));
const inlay = (codeVision: boolean) =>
useProject.setState({
settings: { editor: { inlay: { codeVision, codeVisionUsages: true, codeVisionAuthor: true } } } as never,
});
inlay(true);
const view = editor();
await settle();
expect(view.state.facet(codeLenses).map((l) => l.kind)).toEqual(["author", "usages"]);
inlay(false);
await settle();
expect(titles(view)).toEqual([]);
inlay(true);
await settle();
expect(view.state.facet(codeLenses).map((l) => l.kind)).toEqual(["author", "usages"]);
});
});
describe("background usage counts", () => {
it("uses the server's existing scope and leaves full searches to the explicit action", async () => {
const view = editor();
+2 -2
View File
@@ -109,8 +109,8 @@ const lensField = StateField.define<CodeLens[]>({
provide: (f) => codeLenses.from(f),
});
const usagesEnabled = () => editorPrefs().inlay.codeVisionUsages;
const authorEnabled = () => editorPrefs().inlay.codeVisionAuthor;
const usagesEnabled = () => editorPrefs().inlay.codeVision && editorPrefs().inlay.codeVisionUsages;
const authorEnabled = () => editorPrefs().inlay.codeVision && editorPrefs().inlay.codeVisionAuthor;
/** The author hint runs Annotate with Git Blame: it shows the file's annotations, or closes them when shown. */
function toggleAnnotations(view: EditorView) {
+38
View File
@@ -136,3 +136,41 @@ it("keeps the shown lenses while the server is busy answering empty or failing,
await vi.advanceTimersByTimeAsync(500);
expect(view.state.facet(codeLenses)).toHaveLength(0);
});
it("hides language-server lenses while Code Vision is off and asks again when it is back on", async () => {
vi.useFakeTimers();
const { useProject } = await import("@/platform/project");
const codeVision = (on: boolean) =>
useProject.setState({ settings: { editor: { inlay: { codeVision: on } } } as never });
ipc.lspCodeLens.mockResolvedValue({
status: "ok",
data: [
{
range: { start: { line: 0, col: 0 }, end: { line: 0, col: 1 } },
command: { title: "Run test", command: "csharp.runTest", arguments: [] },
},
],
});
try {
codeVision(false);
const view = new EditorView({
state: EditorState.create({
doc: "x",
extensions: serverCodeLenses({ doc: 1, path: "/p/a.cs", language: "csharp", uiMode: null, readOnly: false }),
}),
parent: document.body,
});
views.push(view);
await vi.advanceTimersByTimeAsync(400);
expect(view.state.facet(codeLenses)).toHaveLength(0);
expect(ipc.lspCodeLens).not.toHaveBeenCalled();
codeVision(true);
await vi.advanceTimersByTimeAsync(400);
expect(view.state.facet(codeLenses).map((l) => l.title)).toEqual(["Run test"]);
codeVision(false);
await vi.advanceTimersByTimeAsync(400);
expect(view.state.facet(codeLenses)).toHaveLength(0);
} finally {
useProject.setState({ settings: null });
}
});
+13
View File
@@ -6,6 +6,8 @@ import { call, commands } from "@/platform/ipc";
import { onNavigationProvidersChanged } from "@/editor/navigationProviders";
import { posToOffset } from "./positions";
import { onLspRefresh, onServerSettled, anyServerBusy } from "./availability";
import { editorPrefs } from "@/platform/editorSettings";
import { useProject } from "@/platform/project";
/**
* A server's reference count ("3 references", csharp-ls's "3 Reference(s)"): Code Vision's
* Usages shows the same count above the declaration, under its own setting.
@@ -38,12 +40,18 @@ export function serverCodeLenses(ctx: EditorDocContext): Extension {
timer: ReturnType<typeof setTimeout> | undefined;
generation = 0;
skipped = false;
enabled = editorPrefs().inlay.codeVision;
off: () => void;
constructor() {
const offs = [
onNavigationProvidersChanged(() => this.schedule()),
onLspRefresh("codeLens", () => this.schedule()),
onServerSettled(() => this.schedule()),
// Turning Code Vision off hides these rows too, and turning it back on asks again.
useProject.subscribe((s, prev) => {
if (s.settings !== prev.settings && editorPrefs(s.settings).inlay.codeVision !== this.enabled)
this.schedule();
}),
];
this.off = () => offs.forEach((f) => f());
this.schedule();
@@ -59,6 +67,11 @@ export function serverCodeLenses(ctx: EditorDocContext): Extension {
async run() {
const gen = this.generation;
const text = view.state.doc;
this.enabled = editorPrefs().inlay.codeVision;
if (!this.enabled) {
if (view.state.field(field).length) view.dispatch({ effects: set.of([]) });
return;
}
try {
await whenSynced(view);
const result = await call(commands.lspCodeLens(ctx.doc));
+26 -19
View File
@@ -880,7 +880,7 @@ const INLAY_HINTS = editorPage({
id: "editor.inlayHints",
title: "Inlay Hints",
order: 33,
keywords: ["hints", "code vision", "usages", "parameter hints", "type hints"],
keywords: ["hints", "code vision", "code lens", "usages", "code author", "parameter hints", "type hints"],
sections: [
{ items: INLAY },
{
@@ -888,28 +888,35 @@ const INLAY_HINTS = editorPage({
items: [
{
t: "check",
key: `${P}.inlay.codeVisionUsages`,
label: "Usages",
key: `${P}.inlay.codeVision`,
label: "Show Code Vision",
children: [
{
t: "select",
key: `${P}.inlay.codeVisionUsagesPosition`,
label: "Position",
options: CODE_VISION_POSITIONS,
t: "check",
key: `${P}.inlay.codeVisionUsages`,
label: "Usages",
children: [
{
t: "select",
key: `${P}.inlay.codeVisionUsagesPosition`,
label: "Position",
options: CODE_VISION_POSITIONS,
},
{ t: "check", key: `${P}.inlay.codeVisionNoUsages`, label: "Show “no usages”" },
],
},
{ t: "check", key: `${P}.inlay.codeVisionNoUsages`, label: "Show “no usages”" },
],
},
{
t: "check",
key: `${P}.inlay.codeVisionAuthor`,
label: "Code author",
children: [
{
t: "select",
key: `${P}.inlay.codeVisionAuthorPosition`,
label: "Position",
options: CODE_VISION_POSITIONS,
t: "check",
key: `${P}.inlay.codeVisionAuthor`,
label: "Code author",
children: [
{
t: "select",
key: `${P}.inlay.codeVisionAuthorPosition`,
label: "Position",
options: CODE_VISION_POSITIONS,
},
],
},
],
},
+1
View File
@@ -181,6 +181,7 @@ export const EDITOR_EXTRA_DEFAULTS = {
parameters: true,
other: true,
disabledLanguages: [] as string[],
codeVision: true,
codeVisionUsages: true,
codeVisionAuthor: true,
codeVisionNoUsages: true,
+1
View File
@@ -261,6 +261,7 @@ describe("catalogs", () => {
"12288 MB",
"16384 MB",
"Docker",
"Code Vision",
"JUnit",
"⌘Enter",
"Fork",
+1 -1
View File
@@ -77,7 +77,7 @@ function actionTitles(): Map<string, string> {
const titles = actionTitles();
/** Product names shown as they are in every language. */
const PROPER_NAMES = new Set(["GraphQL", "Vim"]);
const PROPER_NAMES = new Set(["Code Vision", "GraphQL", "Vim"]);
it("has a Chinese entry for every literal action title, including action factory arguments", () => {
// Ensure the helper-argument regression cannot disappear through a scanner change.
+7 -1
View File
@@ -2296,5 +2296,11 @@
"This is a plain SQL dump: restore it with psql.": "This is a plain SQL dump: restore it with psql.",
"Open the commit when the inline blame is clicked": "Open the commit when the inline blame is clicked",
"Fetches the remotes of every repository in the background so incoming commits show in the Branches popup and the Project view. Auto stops checking a repository after it fails, for example on an authentication failure.": "Fetches the remotes of every repository in the background so incoming commits show in the Branches popup and the Project view. Auto stops checking a repository after it fails, for example on an authentication failure.",
"Check for incoming commits every": "Check for incoming commits every"
"Check for incoming commits every": "Check for incoming commits every",
"Show Code Vision": "Show Code Vision",
"Hide Usages": "Hide Usages",
"Hide Code Author": "Hide Code Author",
"Hide Code Vision": "Hide Code Vision",
"Code Vision Settings…": "Code Vision Settings…",
"Code Vision": "Code Vision"
}
+7 -1
View File
@@ -8680,5 +8680,11 @@
"This is a plain SQL dump: restore it with psql.": "这是纯 SQL 转储:请使用 psql 恢复。",
"Open the commit when the inline blame is clicked": "点击内联 Git Blame 时打开提交",
"Fetches the remotes of every repository in the background so incoming commits show in the Branches popup and the Project view. Auto stops checking a repository after it fails, for example on an authentication failure.": "在后台获取每个仓库的远程,以便传入的提交显示在“分支”弹出窗口和项目视图中。“自动”在某个仓库检查失败(例如身份验证失败)后停止检查该仓库。",
"Check for incoming commits every": "检查传入提交的间隔"
"Check for incoming commits every": "检查传入提交的间隔",
"Show Code Vision": "显示 Code Vision",
"Hide Usages": "隐藏用法",
"Hide Code Author": "隐藏代码作者",
"Hide Code Vision": "隐藏 Code Vision",
"Code Vision Settings…": "Code Vision 设置…",
"Code Vision": "Code Vision"
}