fix(vcs): activate diff hunk buttons with the keyboard (#4311)

Diff hunk buttons (arrows, hover Revert, unified Revert) apply the change on click, so Enter and Space work as well as the pointer; a pointer press still keeps editor focus. The unified Revert test added since now activates the button with a click.
This commit is contained in:
l0ng-ai
2026-11-18 22:55:57 +08:00
committed by GitHub
parent 7ec0d3dbec
commit 82ff84e69e
4 changed files with 75 additions and 34 deletions
+3 -5
View File
@@ -53,7 +53,7 @@ import {
languageFor,
viewerBase,
} from "./cm";
import { applyChunk, arrowControls, chunkAt, hoverRevert, revertUnifiedChunk } from "./diffControls";
import { applyChunk, arrowControls, chunkAt, hoverRevert, onHunkButtonClick, revertUnifiedChunk } from "./diffControls";
import {
HIGHLIGHT_OPTIONS,
IGNORE_OPTIONS,
@@ -681,16 +681,14 @@ export function DiffEditor({
mergeControls: editableB
? (type) => {
const btn = document.createElement("button");
btn.type = "button";
if (type === "accept") {
btn.hidden = true;
return btn;
}
btn.textContent = "Revert";
btn.title = "Revert this change";
btn.onmousedown = (event) => {
event.preventDefault();
revertUnifiedChunk(view, view.posAtDOM(btn));
};
onHunkButtonClick(btn, () => revertUnifiedChunk(view, view.posAtDOM(btn)));
return btn;
}
: false,
+56 -18
View File
@@ -1,8 +1,9 @@
import { describe, expect, it } from "vitest";
import { describe, expect, it, vi } from "vitest";
import userEvent from "@testing-library/user-event";
import { Chunk, MergeView, unifiedMergeView } from "@codemirror/merge";
import { ChangeSet, Text } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { applyChunk, arrowControls } from "../diffControls";
import { applyChunk, arrowControls, hoverRevert } from "../diffControls";
import {
DEFAULT_DIFF_OPTIONS,
parseDiffOptions,
@@ -418,7 +419,12 @@ describe("diff options", () => {
expect(a.replace(toA.from, toA.to, Text.of(toA.insert.split("\n"))).toString()).toBe("x\nnew\nnewer\ny\n");
});
it("applies chunks in a merge view through the arrow controls", () => {
it.each([
["a-to-b", "right", "{Enter}"],
["b-to-a", "left", " "],
["a-to-b", "right", "click"],
["b-to-a", "left", "click"],
] as const)("applies a chunk %s to the %s (%j)", async (direction, side, activation) => {
const parent = document.createElement("div");
document.body.appendChild(parent);
let mv: MergeView | null = null;
@@ -429,21 +435,53 @@ describe("diff options", () => {
revertControls: "a-to-b",
renderRevertControl: arrowControls(() => mv, { toA: true, toB: true }),
});
const holder = arrowControls(() => mv, { toA: true, toB: true })();
expect([...holder.querySelectorAll("button")].map((b) => b.getAttribute("aria-label"))).toEqual([
expect.stringContaining("right"),
expect.stringContaining("left"),
]);
// "<<": the right side's text replaces the left chunk.
holder.dataset.chunk = "0";
holder.querySelectorAll("button")[1]!.dispatchEvent(new MouseEvent("mousedown", { bubbles: true }));
expect(mv.a.state.doc.toString()).toBe("1\nright\n3\n");
expect(mv.chunks).toHaveLength(0);
mv.a.dispatch({ changes: { from: 2, to: 7, insert: "LEFT" } });
applyChunk(mv, 0, "a");
expect(mv.b.state.doc.toString()).toBe("1\nLEFT\n3\n");
mv.destroy();
parent.remove();
try {
const arrow = await vi.waitFor(() => {
const button = parent.querySelector<HTMLButtonElement>(`.cm-diffArrow-${direction}`);
expect(button).not.toBeNull();
return button!;
});
expect(arrow.getAttribute("aria-label")).toContain(side);
const user = userEvent.setup();
if (activation === "click") {
mv.b.focus();
await user.click(arrow);
expect(document.activeElement).toBe(mv.b.contentDOM);
} else {
arrow.focus();
await user.keyboard(activation);
}
const expected = direction === "a-to-b" ? "1\nleft\n3\n" : "1\nright\n3\n";
expect(mv.a.state.doc.toString()).toBe(expected);
expect(mv.b.state.doc.toString()).toBe(expected);
expect(mv.chunks).toHaveLength(0);
} finally {
mv.destroy();
parent.remove();
}
});
it("reverts a hovered chunk when its button is activated by the keyboard", async () => {
const parent = document.createElement("div");
document.body.appendChild(parent);
const diff = new MergeView({
a: { doc: "1\nleft\n3\n" },
b: { doc: "1\nright\n3\n", extensions: hoverRevert((_view, index) => applyChunk(diff, index, "a")) },
parent,
});
try {
vi.spyOn(diff.b, "posAtCoords").mockReturnValue(2);
diff.b.contentDOM.dispatchEvent(new MouseEvent("mousemove", { bubbles: true }));
const button = parent.querySelector<HTMLButtonElement>(".cm-diffHoverRevert");
expect(button).not.toBeNull();
button!.focus();
await userEvent.setup().keyboard("{Enter}");
expect(diff.b.state.doc.toString()).toBe("1\nleft\n3\n");
} finally {
diff.destroy();
parent.remove();
}
});
});
@@ -712,7 +712,7 @@ describe("Unified Revert", () => {
await waitFor(() => expect(button).not.toBeDisabled());
fireEvent.click(button);
} else {
fireEvent.mouseDown(await screen.findByRole("button", { name: /^Revert$/ }));
fireEvent.click(await screen.findByRole("button", { name: /^Revert$/ }));
}
await waitFor(() => expect(view.state.doc.toString()).toBe(original));
} finally {
+15 -10
View File
@@ -27,6 +27,18 @@ export function revertUnifiedChunk(view: EditorView, pos: number) {
});
}
export function onHunkButtonClick(button: HTMLButtonElement, apply: () => void) {
button.addEventListener("mousedown", (event) => {
// Keep editor focus and suppress MergeView's delegated one-directional revert.
event.preventDefault();
event.stopPropagation();
});
button.addEventListener("click", (event) => {
event.stopPropagation();
apply();
});
}
/** A ">>" / "<<" button; the chunk index comes from the nearest `data-chunk` (itself included). */
export function arrowButton(dir: "a-to-b" | "b-to-a", run: (chunkIndex: number) => void): HTMLButtonElement {
const btn = document.createElement("button");
@@ -36,11 +48,8 @@ export function arrowButton(dir: "a-to-b" | "b-to-a", run: (chunkIndex: number)
btn.setAttribute("aria-label", label);
btn.title = label;
btn.innerHTML = iconMarkup(dir === "a-to-b" ? "diff-arrow-right" : "diff-arrow-left", 14) ?? "";
btn.addEventListener("mousedown", (e) => {
// Handled here rather than by MergeView's own (one-directional) revert handler.
e.preventDefault();
e.stopPropagation();
const holder = (e.currentTarget as HTMLElement).closest<HTMLElement>("[data-chunk]");
onHunkButtonClick(btn, () => {
const holder = btn.closest<HTMLElement>("[data-chunk]");
const index = Number(holder?.dataset.chunk);
if (Number.isInteger(index)) run(index);
});
@@ -83,11 +92,7 @@ class RevertWidget extends WidgetType {
btn.title = "Revert this change";
btn.setAttribute("aria-label", "Revert this change");
btn.innerHTML = `${iconMarkup("revert", 12) ?? ""}<span>Revert</span>`;
btn.addEventListener("mousedown", (e) => {
e.preventDefault();
e.stopPropagation();
this.onRevert(view, this.index);
});
onHunkButtonClick(btn, () => this.onRevert(view, this.index));
return btn;
}
ignoreEvent() {