fix(diff): navigate from the working-copy pane with the keyboard (#7961)

Go to Implementation(s), Go to Declaration or Usages, Go to Type Declaration and Super Method required an active text editor tab, so they did nothing while a diff had focus. They now run on the focused diff pane when it shows a file's document; revision panes have no document and keep them disabled. Option+Command-click focuses the clicked pane before checking whether the action is enabled.

Closes #7960

Co-authored-by: Pecnikas <[email protected]>
Цей коміт міститься в:
Ivan authored and GitHub committed 2026-12-04 16:29:18 +08:00
1 джерело 6e327e6ffc
коміт 5d26e44c0e
8 files changed
+282 -43

No files matched your search

+62 -1
Переглянути файл
@@ -1,7 +1,7 @@
import type { EditorView } from "@codemirror/view";
import type { Page } from "@playwright/test";
import type { MemoryBackend } from "../src/editor/core/backend";
import { expect, stubDesktop, test } from "./fixtures";
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
async function openChain(page: Page) {
await page.evaluate(async () => {
@@ -413,3 +413,64 @@ for (const reducedMotion of ["reduce", "no-preference"] as const) {
}
});
}
test("Go to Implementation works in the working-copy pane of a diff, by key and by Option+Command-click", async ({
workbench: page,
}) => {
await stubDesktop(page);
const path = "/dev/acme-api/Billing.kt";
const target = "/dev/acme-api/settings.gradle.kts";
await page.evaluate(
async ({ path, target }) => {
const after = "val order = service.create(req)\nprintln(order)\n";
const handlers = window.__ipc.handlers;
handlers.vcs_file_at = () => "val order = service.make(req)\nprintln(order)\n";
handlers.vcs_diff_hunks = () => [
{ kind: "modified", start: 0, lines: 1, oldStart: 0, oldLines: 1, oldText: "val order = service.make(req)\n" },
];
handlers.fs_probe = () => ({ size: after.length, binary: false, tooLarge: false });
handlers.lsp_goto_implementation = () => [
{ path: target, range: { start: { line: 20, col: 12 }, end: { line: 20, col: 17 } }, uri: null },
];
const keymap = "/src/platform/keymap.ts";
(await import(/* @vite-ignore */ keymap)).applyKeymapSettings("intellij-macos", {});
const backendPath = "/src/editor/core/backend.ts";
const { docBackend } = await import(/* @vite-ignore */ backendPath);
(docBackend() as MemoryBackend).files.set(path, after);
const storePath = "/src/features/vcs/store.ts";
const { useVcs } = await import(/* @vite-ignore */ storePath);
const status = { path, relPath: "Billing.kt", unstaged: "modified", staged: null, renamedFrom: null };
useVcs.setState({ status: [status], byPath: new Map([[path, status]]) });
const inputPath = "/src/features/vcs/diffInput.ts";
const { openDiff } = await import(/* @vite-ignore */ inputPath);
await openDiff({ path, left: { type: "rev", rev: "HEAD" }, right: { type: "worktree" }, mode: "split" });
},
{ path, target },
);
const tabs = page.getByRole("tablist", { name: "Editor tabs" });
const diffTab = tabs.getByRole("tab", { name: /Billing\.kt/ });
const right = page.locator(".cm-merge-b .cm-content");
const left = page.locator(".cm-merge-a .cm-content");
const targetTab = tabs.getByRole("tab", { name: "settings.gradle.kts", exact: true });
const requests = async () => (await ipcCalls(page, "lsp_goto_implementation")) as { doc: number; pos: unknown }[];
const symbol = right.locator(".cm-line").first();
await symbol.click({ position: { x: 90, y: 8 } });
await expect(right).toBeFocused();
await page.keyboard.press("Alt+Meta+b");
await expect(targetTab).toHaveAttribute("aria-selected", "true");
await expect(diffTab).toBeVisible();
const [first] = await requests();
expect(first).toMatchObject({ pos: { line: 0 } });
await diffTab.click();
await left.click();
await expect(left).toBeFocused();
await symbol.click({ modifiers: ["Alt", "Meta"], position: { x: 90, y: 8 } });
await expect(targetTab).toHaveAttribute("aria-selected", "true");
await expect.poll(async () => (await requests()).length).toBe(2);
const second = (await requests())[1]!;
expect(second.doc).toBe(first!.doc);
expect(second.pos).toEqual(first!.pos);
});
+11 -1
Переглянути файл
@@ -30,7 +30,7 @@ import {
type Text,
type Transaction,
} from "@codemirror/state";
import { GutterMarker, ViewPlugin, type EditorView, type ViewUpdate } from "@codemirror/view";
import { EditorView, GutterMarker, ViewPlugin, type ViewUpdate } from "@codemirror/view";
import type { LanguageDescription } from "@codemirror/language";
import type { HunkKind } from "@/bindings";
import type { CodeAction, LineEnding } from "@/platform/ipc";
@@ -279,6 +279,16 @@ export function focusedCellEditor(): EditorView | null {
return focusedCell;
}
/**
* The text pane that has focus in a diff or merge editor (`editable`: only a side that can be
* edited). Text actions that need nothing but the view run there, as in a file editor.
*/
export function focusedDiffPane(editable: boolean): EditorView | null {
const el = typeof document === "undefined" ? null : document.activeElement;
const view = el instanceof HTMLElement ? EditorView.findFromDOM(el) : null;
return view && !(editable && view.state.readOnly) ? view : null;
}
/** Published by the custom editor owning the cell editors (a notebook); `null` once none has focus. */
export function _setFocusedCellEditor(view: EditorView | null) {
focusedCell = view;
+1 -11
Переглянути файл
@@ -25,7 +25,7 @@ import { foldEffect, syntaxTree, toggleFold } from "@codemirror/language";
import { acceptCompletion, completionStatus, moveCompletionSelection } from "@codemirror/autocomplete";
import { executeAction, registerActions, type Action } from "@/platform/actions";
import { getContext } from "@/platform/context";
import { focusedCellEditor } from "@/editor/api";
import { focusedCellEditor, focusedDiffPane } from "@/editor/api";
import { focusedSoftWrapSurface } from "@/workbench/softWrap";
import { resetSurfaceFontZoom, stepFocusedSurfaceFontZoom, stepSurfaceFontZoomIn } from "@/workbench/contributions";
import { editorController, useGotoLine, useTabs } from "./controller";
@@ -206,16 +206,6 @@ function activeSlot(): EditorSlot | null {
return slot && !slot.disposed ? slot : null;
}
/**
* The text pane that has focus in a diff or merge editor (`editable`: only a side that can be
* edited). Text actions that need nothing but the view run there, as in a file editor.
*/
function focusedDiffPane(editable: boolean): EditorView | null {
const el = typeof document === "undefined" ? null : document.activeElement;
const view = el instanceof HTMLElement ? EditorView.findFromDOM(el) : null;
return view && !(editable && view.state.readOnly) ? view : null;
}
/** `run` on the focused diff pane while a diff has focus, otherwise on the active editor. */
function withTextView(run: (view: EditorView) => unknown, editable: boolean) {
return () => {
+10 -17
Переглянути файл
@@ -13,7 +13,7 @@ import {
type DocumentAttachment,
type TextEditorHandle,
} from "@/editor/api";
import { call, commands } from "@/platform/ipc";
import { call, commands, type GotoKind } from "@/platform/ipc";
import { maybeEditorService } from "@/workbench/contributions";
import { useProject } from "@/platform/project";
import { validateLanguages } from "@/platform/languageSettings";
@@ -27,7 +27,7 @@ import { showMacroExpansion } from "./macroExpansion";
import { gotoHighlightedUsage, gotoTargets, highlightUsages } from "./navigation";
import { gotoDiagnostic, showErrorDescription } from "./diagnostics";
import { applyKindSilently, applyQuickFix, runKindAction, showIntentions } from "./intentions";
import { docOf, reportLspError } from "./lsp";
import { alsoInDiff, docOf, reportLspError } from "./lsp";
import { languageSemantics } from "./semantic";
import type { GenerateEntry } from "./semantic/languages";
import { caretAnchor, openPopup } from "./popupStore";
@@ -281,6 +281,11 @@ function editorAction(
return { id, title, category, when: EDITOR_WHEN, run: withEditor(run), ...extra };
}
const gotoAction = (id: string, title: string, kind: GotoKind, extra?: Partial<Action>) => {
const run = (v: EditorView) => gotoTargets(v, kind);
return alsoInDiff(editorAction(id, title, "Navigate", run, extra), run);
};
/**
* Whether saving a `language` file formats it: Format on save, or Run on save of an external
* formatter. dprint's covers any language its configuration does (the backend decides).
@@ -468,21 +473,9 @@ export function registerLspActions(): () => void {
when: "projectOpen",
run: inFile(optimizeImports),
},
editorAction(
"navigate.declaration",
"Go to Declaration or Usages",
"Navigate",
(v) => gotoTargets(v, "definition"),
{
keywords: ["definition"],
},
),
editorAction("navigate.implementation", "Go to Implementation(s)", "Navigate", (v) =>
gotoTargets(v, "implementation"),
),
editorAction("navigate.typeDeclaration", "Go to Type Declaration", "Navigate", (v) =>
gotoTargets(v, "typeDefinition"),
),
gotoAction("navigate.declaration", "Go to Declaration or Usages", "definition", { keywords: ["definition"] }),
gotoAction("navigate.implementation", "Go to Implementation(s)", "implementation"),
gotoAction("navigate.typeDeclaration", "Go to Type Declaration", "typeDefinition"),
editorAction("navigate.sourceDefinition", "Go to Source Definition", "Navigate", gotoSourceDefinition, {
when: `${EDITOR_WHEN} && (${TYPESCRIPT_WHEN})`,
keywords: ["implementation", "javascript", "node_modules", "d.ts"],
+23 -1
Переглянути файл
@@ -1,7 +1,8 @@
/** Shared plumbing: per-editor document facet, IPC wrapper and error policy. */
import { Facet } from "@codemirror/state";
import type { EditorView } from "@codemirror/view";
import { whenAllSynced, type EditorDocContext } from "@/editor/api";
import { focusedDiffPane, whenAllSynced, type EditorDocContext } from "@/editor/api";
import type { Action } from "@/platform/actions";
import { IpcError, call, isCancelled, isTauri, unavailableText } from "@/platform/ipc";
import { hasInvokeRoute } from "@/platform/tauriCore";
import { tx } from "@/platform/i18n";
@@ -17,6 +18,27 @@ export function docOf(view: EditorView): EditorDocContext | null {
return view.state.facet(lspDoc);
}
/**
* `action` also in a diff: on its focused pane, never on the text tab behind it. A revision
* pane has no document to navigate from, so the action stays disabled there.
*/
export function alsoInDiff(action: Action, run: (view: EditorView) => unknown): Action {
return {
...action,
when: `(${action.when}) || diffEditorFocus`,
enabled: (c) => {
if (!c.ctx.diffEditorFocus) return action.enabled?.(c) ?? true;
const view = focusedDiffPane(false);
return !!view && !!docOf(view);
},
run: (c) => {
if (!c.ctx.diffEditorFocus) return action.run(c);
const view = focusedDiffPane(false);
if (view) void run(view);
},
};
}
type Result<T> = { status: "ok"; data: T } | { status: "error"; error: IdeError };
/**
+13 -8
Переглянути файл
@@ -1503,17 +1503,15 @@ const linkPlugin = ViewPlugin.fromClass(
if (isAddCaretGesture(e)) return false;
const rectangle = isRectangularSelectionGesture(e);
let middleDeclaration = false;
// The action is enabled only once this pane has focus, so the click focuses it first.
if (e.button === 0 && !rectangle && !view.hasFocus && isNavigationHoverGesture(e)) placeCaretAndFocus(view, e);
if (
dispatchMouseShortcut(e, (id) => {
if (e.button === 1 && id === "navigate.declaration") {
middleDeclaration = true;
return false;
}
const pos = view.posAtCoords({ x: e.clientX, y: e.clientY }, false);
if (pos == null) return false;
view.dispatch({ selection: EditorSelection.cursor(pos), effects: setLink.of(null) });
view.focus();
return true;
return placeCaretAndFocus(view, e) != null;
})
) {
e.preventDefault();
@@ -1535,14 +1533,21 @@ const linkPlugin = ViewPlugin.fromClass(
/** Puts the caret under the pointer and goes to the declaration there, like a ⌘/Ctrl-click. */
function navigateFromPointer(view: EditorView, e: MouseEvent): boolean {
const pos = view.posAtCoords({ x: e.clientX, y: e.clientY }, false);
const pos = placeCaretAndFocus(view, e);
if (pos == null) return false;
view.dispatch({ selection: EditorSelection.cursor(pos), effects: setLink.of(null) });
view.focus();
void gotoTargets(view, "definition", pos);
return true;
}
/** Caret first, then focus (WebKit may scroll to the old selection on focus). */
function placeCaretAndFocus(view: EditorView, e: MouseEvent): number | null {
const pos = view.posAtCoords({ x: e.clientX, y: e.clientY }, false);
if (pos == null) return null;
view.dispatch({ selection: EditorSelection.cursor(pos), effects: setLink.of(null) });
view.focus();
return pos;
}
// ---------------------------------------------------------------------------
// Document highlights
+155
Переглянути файл
@@ -0,0 +1,155 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import type { commands } from "@/platform/ipc";
import { usePlatform } from "@/platform/platformInfo";
import { resetNavigationModifier } from "@/platform/navigationModifier";
import { installKeyboardDispatcher, useKeymap } from "@/platform/keymap";
import { executeAction } from "@/platform/actions";
import { setContext } from "@/platform/context";
const lspGoto = vi.hoisted(() => vi.fn<typeof commands.lspGoto>());
const docOutline = vi.hoisted(() => vi.fn<typeof commands.docOutline>());
vi.mock("@/platform/ipc", async (orig) => {
const real = await orig<typeof import("@/platform/ipc")>();
const lspGotoImplementation: typeof commands.lspGotoImplementation = (_request, doc, pos) =>
lspGoto(doc, pos, "implementation");
return {
...real,
isTauri: () => true,
commands: {
...real.commands,
lspGoto,
lspGotoImplementation,
docOutline,
lspHighlights: vi.fn(async () => ({ status: "ok", data: [] })),
},
};
});
vi.mock("@tauri-apps/api/core", async (orig) => ({
...(await orig<object>()),
Channel: class {
onmessage = () => {};
},
}));
const { navigationExtension } = await import("./navigation");
const { lspDoc } = await import("./lsp");
const { registerLspActions } = await import("./actions");
const { registerNavigationActions } = await import("@/editor/navigation");
const { provideEditorService } = await import("@/workbench/contributions");
const openFile = vi.fn(async () => {});
provideEditorService({ openFile } as never);
const DOC = { doc: 7, path: "/p/Main.java", language: "java", uiMode: "Java", readOnly: false };
let uninstall: () => void;
let unregister: () => void;
let unregisterNav: () => void;
let wrapper: HTMLElement;
beforeEach(() => {
usePlatform.setState({ os: "macos" });
resetNavigationModifier();
vi.clearAllMocks();
useKeymap.setState({ preset: "intellij-macos", overrides: {} });
unregister = registerLspActions();
unregisterNav = registerNavigationActions();
uninstall = installKeyboardDispatcher(window);
lspGoto.mockResolvedValue({
status: "ok",
data: [{ path: "/p/Target.java", range: { start: { line: 4, col: 2 }, end: { line: 4, col: 5 } }, uri: null }],
});
docOutline.mockResolvedValue({ status: "ok", data: [] });
wrapper = document.createElement("div");
wrapper.addEventListener("focusin", () => setContext("diffEditorFocus", true));
wrapper.addEventListener("focusout", (e) => {
if (!wrapper.contains(e.relatedTarget as Node | null)) setContext("diffEditorFocus", false);
});
document.body.append(wrapper);
});
afterEach(() => {
uninstall();
unregister();
unregisterNav();
setContext("diffEditorFocus", false);
setContext("textEditorActive", false);
wrapper.remove();
resetNavigationModifier();
vi.restoreAllMocks();
});
function pane(withDoc: boolean, head = 9): EditorView {
const view = new EditorView({
parent: wrapper,
state: EditorState.create({
doc: "service.run()",
selection: { anchor: head },
extensions: withDoc ? [lspDoc.of(DOC), navigationExtension()] : [],
}),
});
return view;
}
const keyBinding = () =>
window.dispatchEvent(
new KeyboardEvent("keydown", {
code: "KeyB",
key: "b",
metaKey: true,
altKey: true,
bubbles: true,
cancelable: true,
}),
);
describe("navigation in a focused diff pane", () => {
it.each([
["navigate.declaration", "definition"],
["navigate.typeDeclaration", "typeDefinition"],
])("%s goes from the caret of the pane's document", async (id, kind) => {
const view = pane(true);
view.contentDOM.focus();
await executeAction(id);
await vi.waitFor(() => expect(openFile).toHaveBeenCalledOnce());
expect(lspGoto).toHaveBeenCalledExactlyOnceWith(7, { line: 0, col: 9 }, kind);
});
it("opens the implementation with the real Option+Command+B key", async () => {
pane(true).contentDOM.focus();
keyBinding();
await vi.waitFor(() => expect(openFile).toHaveBeenCalledOnce());
expect(lspGoto).toHaveBeenCalledExactlyOnceWith(7, { line: 0, col: 9 }, "implementation");
});
it("asks for the structure of the pane's document for Super Method", async () => {
pane(true).contentDOM.focus();
await executeAction("navigate.superMethod");
await vi.waitFor(() => expect(docOutline).toHaveBeenCalledExactlyOnceWith(7));
});
it.each(["navigate.declaration", "navigate.implementation", "navigate.typeDeclaration", "navigate.superMethod"])(
"%s does nothing in a revision pane, even with a text editor active",
async (id) => {
setContext("textEditorActive", true);
pane(false).contentDOM.focus();
expect(await executeAction(id)).toBe(false);
await new Promise((r) => setTimeout(r, 0));
expect(lspGoto).not.toHaveBeenCalled();
expect(docOutline).not.toHaveBeenCalled();
expect(openFile).not.toHaveBeenCalled();
},
);
it("navigates from the clicked position with Option+Command-click on an unfocused pane", async () => {
const view = pane(true, 0);
vi.spyOn(view, "posAtCoords").mockReturnValue(9);
expect(view.hasFocus).toBe(false);
view.contentDOM.dispatchEvent(
new MouseEvent("mousedown", { bubbles: true, cancelable: true, button: 0, metaKey: true, altKey: true }),
);
await vi.waitFor(() => expect(openFile).toHaveBeenCalledOnce());
expect(lspGoto).toHaveBeenCalledExactlyOnceWith(7, { line: 0, col: 9 }, "implementation");
expect(view.state.selection.main.head).toBe(9);
expect(view.hasFocus).toBe(true);
});
});
+7 -4
Переглянути файл
@@ -7,7 +7,7 @@
import { EditorSelection } from "@codemirror/state";
import type { EditorView } from "@codemirror/view";
import { openCodeLocation, activeEditor, editorsFor, whenSynced, type EditorDocContext } from "@/editor/api";
import { docOf, lspRequest } from "@/editor/lsp/lsp";
import { alsoInDiff, docOf, lspRequest } from "@/editor/lsp/lsp";
import { offsetToPos, posToOffset } from "@/editor/lsp/positions";
import { caretAnchor, openPopup } from "@/editor/lsp/popupStore";
import { dedupeLocations, locationItems, navigateTo } from "@/editor/lsp/navigation";
@@ -308,9 +308,12 @@ export function registerNavigationActions(): () => void {
editorAction("navigate.createTest", "Create Test…", createTest, {
keywords: ["new test", "generate test", "pytest"],
}),
editorAction("navigate.superMethod", "Super Method", superMethod, {
keywords: ["go to super", "overridden", "parent"],
}),
alsoInDiff(
editorAction("navigate.superMethod", "Super Method", superMethod, {
keywords: ["go to super", "overridden", "parent"],
}),
superMethod,
),
editorAction("navigate.nextMethod", "Next Method", (v) => gotoMethod(v, 1)),
editorAction("navigate.previousMethod", "Previous Method", (v) => gotoMethod(v, -1)),
editorAction("navigate.relatedSymbol", "Related Symbol…", gotoRelated, {