Skip to content

The IDE you know, rebuilt in Rust. IntelliJ IDEA–style keymap, tool windows and search-everywhere in a fast native app: editor, code insight, debugger, Git, terminal, database and HTTP clients for 60+ languages.

fix(vcs): keep the caret visible when navigating between differences (#2395)

HandsomeXi6b4be5a15b8c
diff --git a/e2e/diff-navigation.spec.ts b/e2e/diff-navigation.spec.ts
index e297bd950..57143c786 100644
--- a/e2e/diff-navigation.spec.ts
+++ b/e2e/diff-navigation.spec.ts
@@ -1,3 +1,4 @@
+import type { EditorView } from "@codemirror/view";
import type { Page } from "@playwright/test";
import { expect, test } from "./fixtures";
@@ -96,3 +97,85 @@ test("skips binary and unchanged siblings and restores after changing preview fi
await expect(toolbar).toBeHidden();
await expect(page.getByRole("tree", { name: "Project", exact: true })).toBeVisible();
});
+
+for (const reducedMotion of ["reduce", "no-preference"] as const) {
+ test.describe(`caret navigation with reducedMotion=${reducedMotion}`, () => {
+ test.use({ reducedMotion });
+ for (const [mode, alignChanges, side] of [
+ ["split", false, 0],
+ ["split", false, 1],
+ ["split", true, 0],
+ ["split", true, 1],
+ ["unified", false, 0],
+ ] as const) {
+ test(`centres the visible caret during ${mode} navigation (aligned=${alignChanges}, pane=${side})`, async ({
+ workbench: page,
+ }) => {
+ await page.evaluate(
+ async ({ mode, alignChanges }) => {
+ const inputPath = "/src/features/vcs/diffInput.ts";
+ const { openDiff } = await import(inputPath);
+ localStorage.setItem(
+ "openidea.vcs.diffOptions",
+ JSON.stringify({ mode, alignChanges, collapse: false, syncScroll: true }),
+ );
+ const lines = Array.from({ length: 800 }, (_, i) => `const value${i} = ${i};`);
+ const right = [...lines];
+ for (const i of [100, 400, 700]) right[i] = `const changed${i} = ${i};`;
+ await openDiff({
+ path: "/dev/acme-api/navigation.ts",
+ left: { type: "text", text: lines.join("\n"), label: "Before" },
+ right: { type: "text", text: right.join("\n"), label: "After" },
+ });
+ },
+ { mode, alignChanges },
+ );
+ const toolbar = page.getByRole("toolbar", { name: "Diff", exact: true });
+ await expect(toolbar).toContainText("3 differences");
+ const pane = toolbar.locator("..").locator(".cm-editor").nth(side);
+ await pane.locator(".cm-content").focus();
+ const check = async (line: number) => {
+ await expect(pane).toHaveClass(/cm-focused/);
+ await expect
+ .poll(() =>
+ pane.locator(".cm-content").evaluate((content) => {
+ const view = (content as HTMLElement & { cmTile: { view: EditorView } }).cmTile.view;
+ const head = view.state.selection.main.head;
+ const line = view.state.doc.lineAt(head);
+ const outer = content.closest<HTMLElement>(".cm-mergeView");
+ const scroller = outer && outer.scrollHeight > outer.clientHeight ? outer : view.scrollDOM;
+ const rect = scroller.getBoundingClientRect();
+ const caret = view.coordsAtPos(head);
+ const y = caret ? (caret.top + caret.bottom) / 2 : null;
+ return {
+ line: line.number,
+ column: head - line.from,
+ centred: y !== null && Math.abs(y - rect.top - scroller.clientHeight / 2) < 3,
+ cursor: getComputedStyle(view.dom.querySelector(".cm-cursor")!).display !== "none",
+ blinking: /cm-blink/.test(getComputedStyle(view.dom.querySelector(".cm-cursorLayer")!).animationName),
+ };
+ }),
+ )
+ .toEqual({ line, column: 0, centred: true, cursor: true, blinking: true });
+ if (mode === "split" && !alignChanges) {
+ const tops = await toolbar
+ .locator("..")
+ .locator(".cm-scroller")
+ .evaluateAll((els) => els.map((el) => el.scrollTop));
+ expect(Math.abs(tops[0]! - tops[1]!)).toBeLessThan(2);
+ }
+ };
+ await toolbar.getByRole("button", { name: "Next Difference", exact: true }).click();
+ await check(101);
+ await page.keyboard.press("F7");
+ await check(401);
+ await page.keyboard.press("F7");
+ await check(701);
+ await toolbar.getByRole("button", { name: "Previous Difference", exact: true }).click();
+ await check(401);
+ await page.keyboard.press("Shift+F7");
+ await check(101);
+ });
+ }
+ });
+}
diff --git a/e2e/mergeEditor.spec.ts b/e2e/mergeEditor.spec.ts
index 4c9a94af8..c0e625900 100644
--- a/e2e/mergeEditor.spec.ts
+++ b/e2e/mergeEditor.spec.ts
@@ -1,3 +1,4 @@
+import type { EditorView } from "@codemirror/view";
import type { Locator, Page } from "@playwright/test";
import { expect, test } from "./fixtures";
@@ -205,6 +206,7 @@ test("the toolbar applies the non-conflicting changes of one side", async ({ pag
await expect(page.getByRole("button", { name: "Apply Non-Conflicting Changes from the Left Side" })).toBeDisabled();
await page.getByRole("button", { name: "Apply Non-Conflicting Changes from the Right Side" }).click();
await expect(status(page)).toHaveText("2 changes left, 2 conflicts");
+ await expect(result(page).locator(".cm-editor")).toHaveClass(/cm-focused/);
expect(await text(result(page))).toContain("\nC\n");
await expect(page.getByRole("button", { name: "Apply All Non-Conflicting Changes" })).toBeDisabled();
});
@@ -343,3 +345,59 @@ test("merge actions follow the focused instance and survive a context menu", asy
await expect(second.locator("[class*=status]").first()).toHaveText("2 changes left, 1 conflict");
await expect(status(page)).toHaveText("1 change left, 1 conflict");
});
+
+test("difference navigation focuses and centres the merge result caret with synchronized sides", async ({ page }) => {
+ const base = Array.from({ length: 800 }, (_, i) => `const value${i} = ${i};`);
+ const ours = [...base];
+ const theirs = [...base];
+ for (const i of [100, 400, 700]) {
+ ours[i] = `const ours${i} = ${i};`;
+ theirs[i] = `const theirs${i} = ${i};`;
+ }
+ await mountMerge(page, [base.join("\n"), ours.join("\n"), theirs.join("\n")]);
+ const pane = result(page);
+ const check = async (line: number) => {
+ await expect(pane.locator(".cm-editor")).toHaveClass(/cm-focused/);
+ await expect
+ .poll(() =>
+ pane.locator(".cm-content").evaluate((content) => {
+ const view = (content as HTMLElement & { cmTile: { view: EditorView } }).cmTile.view;
+ const head = view.state.selection.main.head;
+ const at = view.state.doc.lineAt(head);
+ const rect = view.scrollDOM.getBoundingClientRect();
+ const coords = view.coordsAtPos(head)!;
+ return {
+ line: at.number,
+ column: head - at.from,
+ centred: Math.abs((coords.top + coords.bottom) / 2 - rect.top - rect.height / 2) < 3,
+ cursor: getComputedStyle(view.dom.querySelector(".cm-cursor")!).display !== "none",
+ blinking: /cm-blink/.test(getComputedStyle(view.dom.querySelector(".cm-cursorLayer")!).animationName),
+ };
+ }),
+ )
+ .toEqual({ line, column: 0, centred: true, cursor: true, blinking: true });
+ await expect
+ .poll(async () => {
+ const tops = await page.locator("#merge-host .cm-content").evaluateAll(
+ (els, line) =>
+ els.map((content) => {
+ const view = (content as HTMLElement & { cmTile: { view: EditorView } }).cmTile.view;
+ return view.documentTop + view.lineBlockAt(view.state.doc.line(line).from).top;
+ }),
+ line,
+ );
+ return Math.max(...tops) - Math.min(...tops);
+ })
+ .toBeLessThan(2);
+ };
+ await page.getByRole("button", { name: "Next Change", exact: true }).click();
+ await check(101);
+ await page.keyboard.press("F7");
+ await check(401);
+ await page.keyboard.press("F7");
+ await check(701);
+ await page.getByRole("button", { name: "Previous Change", exact: true }).click();
+ await check(401);
+ await page.keyboard.press("Shift+F7");
+ await check(101);
+});
diff --git a/src/features/vcs/DiffEditor.tsx b/src/features/vcs/DiffEditor.tsx
index 39001d3d9..c27302859 100644
--- a/src/features/vcs/DiffEditor.tsx
+++ b/src/features/vcs/DiffEditor.tsx
@@ -734,14 +734,25 @@ export function DiffEditor({
(dir === 1 ? goToNextChunk : goToPreviousChunk)({
state: v.state,
dispatch: (tr) => {
- v.dispatch({ selection: tr.selection, userEvent: "select.byChunk" });
+ const selection = tr.selection ?? v.state.selection;
+ v.dispatch({
+ selection,
+ effects: EditorView.scrollIntoView(selection.main.head, { y: "center" }),
+ userEvent: "select.byChunk",
+ });
+ // CodeMirror draws the caret only in a focused editor, so a difference reached from
+ // the toolbar, a menu or F7 pressed after those would move an invisible caret.
+ v.focus();
const scroller = views.merge && !views.panes ? views.merge.dom : v.scrollDOM;
v.requestMeasure({
key: step,
read: () => {
const documentTop = v.documentTop - scroller.getBoundingClientRect().top + scroller.scrollTop;
- const lineTop = v.lineBlockAt(v.state.selection.main.head).top;
- return documentTop + lineTop - scroller.clientHeight / 3;
+ const caret = v.coordsAtPos(v.state.selection.main.head);
+ const lineTop = caret
+ ? (caret.top + caret.bottom) / 2 - v.documentTop
+ : v.lineBlockAt(v.state.selection.main.head).top;
+ return documentTop + lineTop - scroller.clientHeight / 2;
},
write: (top) => {
const options: ScrollToOptions = {
diff --git a/src/features/vcs/MergeEditor.tsx b/src/features/vcs/MergeEditor.tsx
index 010b0f9ef..69474dcd0 100644
--- a/src/features/vcs/MergeEditor.tsx
+++ b/src/features/vcs/MergeEditor.tsx
@@ -231,9 +231,14 @@ export function MergeEditor({ input }: { input: EditorInput }) {
};
}, [state, lang, path, actionHost]);
- /** Puts the caret at a change and brings it into view. */
- const moveTo = (view: EditorView, at: number) =>
+ /**
+ * Puts the caret at a change, brings it into view and focuses the pane: CodeMirror draws the
+ * caret only in a focused editor, so a move made by a toolbar button would be invisible.
+ */
+ const moveTo = (view: EditorView, at: number) => {
view.dispatch({ selection: { anchor: at }, effects: EditorView.scrollIntoView(at, { y: "center" }) });
+ view.focus();
+ };
const goto = (dir: 1 | -1) => {
const v = resultView.current;
@@ -246,7 +251,6 @@ export function MergeEditor({ input }: { input: EditorInput }) {
? (open.find((c) => c.from > head) ?? open[0]!)
: ([...open].reverse().find((c) => c.from < head) ?? open[open.length - 1]!);
moveTo(v, target.from);
- v.focus();
};
/** Runs a command on the result; `reveal` then moves to what is left to decide. */
diff --git a/src/features/vcs/__tests__/diffScroll.test.ts b/src/features/vcs/__tests__/diffScroll.test.ts
index 0b6461b59..d984f0cae 100644
--- a/src/features/vcs/__tests__/diffScroll.test.ts
+++ b/src/features/vcs/__tests__/diffScroll.test.ts
@@ -99,7 +99,7 @@ describe("unaligned side-by-side scrolling", () => {
});
});
-describe("animated synchronized scrolling", () => {
+describe("synchronized navigation scrolling", () => {
function panes(sync = true) {
const root = document.createElement("div");
const text = doc(Array.from({ length: 200 }, () => "line").join("\n"));
@@ -130,14 +130,19 @@ describe("animated synchronized scrolling", () => {
return { a, b, controller, scroll };
}
- it.each(["a", "b"] as const)("ignores delayed follower layout scrolls while %s animates", (side) => {
+ it.each([
+ ["a", "smooth"],
+ ["b", "smooth"],
+ ["a", "instant"],
+ ["b", "instant"],
+ ] as const)("keeps %s as the source during a %s jump", (side, behavior) => {
vi.useFakeTimers();
const frame = vi.spyOn(window, "requestAnimationFrame").mockReturnValue(1);
const p = panes();
try {
const leader = p[side];
const follower = p[side === "a" ? "b" : "a"];
- p.controller.scrollTo(side, { top: 2000, behavior: "smooth" });
+ p.controller.scrollTo(side, { top: 2000, behavior });
p.scroll(leader, 1000);
expect(follower.scrollDOM.scrollTop).toBe(1000);
p.scroll(follower, 200);
diff --git a/src/features/vcs/__tests__/diffToolbar.test.tsx b/src/features/vcs/__tests__/diffToolbar.test.tsx
index 719e6988a..d48acd5f6 100644
--- a/src/features/vcs/__tests__/diffToolbar.test.tsx
+++ b/src/features/vcs/__tests__/diffToolbar.test.tsx
@@ -1,4 +1,4 @@
-import { beforeEach, describe, expect, it, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import type { EditorInput } from "@/workbench/contributions";
import { Chunk, getChunks } from "@codemirror/merge";
@@ -543,3 +543,72 @@ describe("Unified Revert", () => {
});
}
});
+
+describe("Diff navigation caret", () => {
+ // @codemirror/view hides `.cm-cursor` unless its editor carries `.cm-focused`, and that class
+ // follows `view.hasFocus`, false while the document itself is unfocused. jsdom reports a
+ // focused document only when told to, so the caret these tests are about is asserted the same way.
+ let documentFocused: ReturnType<typeof vi.spyOn>;
+ beforeEach(() => {
+ localStorage.clear();
+ documentFocused = vi.spyOn(document, "hasFocus").mockReturnValue(true);
+ });
+ afterEach(() => {
+ documentFocused.mockRestore();
+ localStorage.clear();
+ });
+
+ /** One change on line 2 of the right (or only) pane. */
+ const reveal = async (mode: "split" | "unified") => {
+ localStorage.setItem("openidea.vcs.diffOptions", JSON.stringify({ mode }));
+ texts.HEAD = "a\nb\nc\n";
+ texts.abc123 = "a\nB\nc\n";
+ const mounted = render(<DiffEditor input={input} />);
+ const panes = mode === "split" ? 2 : 1;
+ await waitFor(() => expect(document.querySelectorAll(".cm-editor")).toHaveLength(panes));
+ const view = () => EditorView.findFromDOM([...document.querySelectorAll<HTMLElement>(".cm-editor")][panes - 1]!)!;
+ return { mounted, view };
+ };
+
+ it.each([
+ ["Next Difference", "split", false],
+ ["Previous Difference", "split", true],
+ ["Next Difference", "unified", false],
+ ["Previous Difference", "unified", true],
+ ] as const)("keeps the caret visible for %s in the %s viewer", async (label, mode, fromEnd) => {
+ const { mounted, view } = await reveal(mode);
+ try {
+ const button = await screen.findByRole("button", { name: label });
+ if (fromEnd) view().dispatch({ selection: { anchor: view().state.doc.length } });
+ // A click leaves focus on the button, outside the panes.
+ button.focus();
+ expect(view().hasFocus).toBe(false);
+ fireEvent.click(button);
+ expect(view().state.doc.lineAt(view().state.selection.main.head).number).toBe(2);
+ expect(view().hasFocus).toBe(true);
+ } finally {
+ mounted.unmount();
+ }
+ });
+
+ it("keeps the caret visible when F7 runs while focus is outside the panes", async () => {
+ const keymap = useKeymap.getState();
+ applyKeymapSettings("intellij-macos", {});
+ const unregister = registerCompareActions();
+ const uninstall = installKeyboardDispatcher(window);
+ const { mounted, view } = await reveal("split");
+ try {
+ const next = await screen.findByRole("button", { name: "Next Difference" });
+ next.focus();
+ expect(view().hasFocus).toBe(false);
+ next.dispatchEvent(new KeyboardEvent("keydown", { key: "F7", code: "F7", bubbles: true, cancelable: true }));
+ await waitFor(() => expect(view().state.doc.lineAt(view().state.selection.main.head).number).toBe(2));
+ expect(view().hasFocus).toBe(true);
+ } finally {
+ mounted.unmount();
+ uninstall();
+ unregister();
+ useKeymap.setState(keymap);
+ }
+ });
+});
diff --git a/src/features/vcs/diffScroll.ts b/src/features/vcs/diffScroll.ts
index c44fff902..f0d6fc2e4 100644
--- a/src/features/vcs/diffScroll.ts
+++ b/src/features/vcs/diffScroll.ts
@@ -232,7 +232,7 @@ export class UnalignedPanes {
scrollTo(side: Side, options: ScrollToOptions) {
this.interruptScroll();
- this.scrolling = this.sync && options.behavior === "smooth" ? side : null;
+ this.scrolling = this.sync ? side : null;
this.releaseScroll();
this.view(side).scrollDOM.scrollTo(options);
}
@@ -267,7 +267,7 @@ export class UnalignedPanes {
private scrolled(side: Side) {
if (this.scrolling) {
- // A follower's delayed layout scroll must not cancel the leader's animation.
+ // A follower's delayed layout scroll must not pull back the navigation source.
this.follow(this.scrolling);
this.releaseScroll();
this.schedule();