feat(vcs): show a file's diff from the Rollback, Shelve and Create Patch file lists (#6417)

In the Rollback Changes dialog, double-click and Enter only toggled a file's checkbox and Show Diff did nothing. The file checklist shared by Rollback, Shelve and Create Patch now opens the file's diff in a front dialog on double-click, Enter and Show Diff, with the listed files as the next/previous chain; Space toggles the selected rows and clicking a box still toggles it. Rollback Unstaged Changes shows the index against the working copy. Closes #5295.

Co-authored-by: audichuang <[email protected]>
Цей коміт міститься в:
audichuang authored and GitHub committed 2026-11-27 16:44:28 +08:00
1 джерело c5eab0a4a3
коміт 3a1353cc0e
4 files changed
+179 -10

No files matched your search

+21
Переглянути файл
@@ -51,6 +51,27 @@ test("Rollback fits a short window and scopes its options to checked files", asy
const deleteCopies = dialog.getByRole("checkbox", { name: "Delete local copies of added files" });
const rollback = dialog.getByRole("button", { name: "Rollback", exact: true });
await expect(status).toHaveText("1 added16 modified1 deleted");
// Double-click shows the file's diff over Rollback and leaves its box alone; closing it comes back.
// Let the dialog's open animation finish so both clicks land on the same row.
await dialog.evaluate((el) => Promise.all(el.getAnimations({ subtree: true }).map((a) => a.finished)));
await tree.getByTitle("ledger/merchant-settlement-batch-1.txt", { exact: true }).dblclick();
const diff = page.getByRole("dialog", { name: "merchant-settlement-batch-1.txt (HEAD ↔ Your version)" });
await expect(diff).toBeVisible();
await page.keyboard.press("Escape");
await expect(diff).toBeHidden();
await expect(dialog).toBeVisible();
await expect(tree).toBeFocused();
await expect(status).toHaveText("1 added16 modified1 deleted");
// Space toggles the selected row, also right after clicking its box.
await page.keyboard.press("Space");
await expect(status).toHaveText("1 added15 modified1 deleted");
await page.keyboard.press("Space");
await expect(status).toHaveText("1 added16 modified1 deleted");
await tree.getByRole("checkbox", { name: "Include merchant-settlement-batch-1.txt", exact: true }).click();
await expect(status).toHaveText("1 added15 modified1 deleted");
await page.keyboard.press("Space");
await expect(status).toHaveText("1 added16 modified1 deleted");
await expect(deleteCopies).toBeEnabled();
await expect(deleteCopies).not.toBeChecked();
await deleteCopies.check();
+91 -3
Переглянути файл
@@ -1,10 +1,14 @@
import { afterEach, beforeEach, expect, it } from "vitest";
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { useState } from "react";
import type { FileStatus } from "@/bindings";
import { installKeyboardDispatcher, primaryKeyBinding } from "@/platform/keymap";
import { FileChecklist } from "../shelf";
import { useVcs } from "../store";
const openDiffDialog = vi.hoisted(() => vi.fn());
vi.mock("../diffDialog", () => ({ openDiffDialog }));
const file = (rel: string): FileStatus => ({
path: `/repo/${rel}`,
relPath: rel,
@@ -27,7 +31,10 @@ function Harness() {
const box = (name: string) => screen.getByRole("checkbox", { name: `Include ${name}` });
beforeEach(() => useVcs.setState({ root: "/repo" }));
beforeEach(() => {
useVcs.setState({ root: "/repo" });
openDiffDialog.mockReset();
});
afterEach(cleanup);
it("groups the files by directory, merging single-child chains and counting files", () => {
@@ -57,3 +64,84 @@ it("checks or clears a directory's files at once and shows a partly included one
expect(box(name)).not.toBeChecked();
expect(box("pom.xml")).toBeChecked();
});
it("shows a file's diff on double-click and ⌘D, and toggles inclusion with the box and Space", async () => {
const off = installKeyboardDispatcher();
try {
render(<Harness />);
const tree = screen.getByRole("tree", { name: "Files to shelve" });
const binding = primaryKeyBinding("vcs.showDiff");
expect(binding).toMatch(/^(Meta|Ctrl)\+D$/);
const showDiffKey = { key: "d", code: "KeyD", metaKey: binding === "Meta+D", ctrlKey: binding === "Ctrl+D" };
// Before any row is selected, Show Diff starts at the first file.
fireEvent.keyDown(tree, showDiffKey);
await waitFor(() =>
expect(openDiffDialog).toHaveBeenCalledWith(
expect.objectContaining({ path: "/repo/src/chat/config/AiConfig.java" }),
),
);
openDiffDialog.mockClear();
const pom = screen.getByText("pom.xml");
fireEvent.mouseDown(pom, { button: 0 });
fireEvent.doubleClick(pom);
await waitFor(() =>
expect(openDiffDialog).toHaveBeenCalledWith(
expect.objectContaining({
path: "/repo/pom.xml",
left: { type: "rev", rev: "HEAD" },
right: { type: "worktree" },
chain: expect.arrayContaining([expect.objectContaining({ path: "/repo/src/chat/config/AiConfig.java" })]),
}),
),
);
expect(box("pom.xml")).toBeChecked();
fireEvent.mouseDown(screen.getByText("ChatController.java"), { button: 0 });
fireEvent.keyDown(tree, showDiffKey);
await waitFor(() =>
expect(openDiffDialog).toHaveBeenLastCalledWith(
expect.objectContaining({ path: "/repo/src/chat/web/ChatController.java" }),
),
);
expect(box("ChatController.java")).toBeChecked();
fireEvent.mouseDown(screen.getByText("AiConfig.java"), { button: 0 });
fireEvent.keyDown(tree, { key: "Enter", code: "Enter" });
await waitFor(() =>
expect(openDiffDialog).toHaveBeenLastCalledWith(
expect.objectContaining({ path: "/repo/src/chat/config/AiConfig.java" }),
),
);
expect(box("AiConfig.java")).toBeChecked();
fireEvent.mouseDown(screen.getByText("ChatController.java"), { button: 0 });
fireEvent.keyDown(tree, { key: " ", code: "Space" });
expect(box("ChatController.java")).not.toBeChecked();
fireEvent.keyDown(tree, { key: " ", code: "Space" });
expect(box("ChatController.java")).toBeChecked();
openDiffDialog.mockClear();
fireEvent.click(box("pom.xml"));
fireEvent.click(box("pom.xml"));
fireEvent.doubleClick(box("pom.xml"));
expect(box("pom.xml")).toBeChecked();
await new Promise((resolve) => setTimeout(resolve, 0));
expect(openDiffDialog).not.toHaveBeenCalled();
} finally {
off();
}
});
it("compares the index with the working copy when asked for the unstaged side", async () => {
render(<FileChecklist files={files} selected={new Set()} onChange={() => {}} label="Files" diffSide="unstaged" />);
fireEvent.doubleClick(screen.getByText("pom.xml"));
await waitFor(() =>
expect(openDiffDialog).toHaveBeenCalledWith(
expect.objectContaining({
path: "/repo/pom.xml",
left: expect.objectContaining({ type: "rev", rev: ":0" }),
right: expect.objectContaining({ type: "worktree" }),
}),
),
);
});
+1
Переглянути файл
@@ -677,6 +677,7 @@ function RollbackDialog({
onChange={setSelected}
label="Files to roll back"
className={rollbackStyles.tree}
diffSide={scope === "unstaged" ? "unstaged" : undefined}
/>
<div className={rollbackStyles.summary} role="status">
{!chosen.length && <T>No files selected</T>}
+66 -7
Переглянути файл
@@ -17,8 +17,8 @@ import type {
ShelfDiffFile,
} from "@/bindings";
import { setContext } from "@/platform/context";
import { shortcutLabel } from "@/platform/keymap";
import { openDiff, openVcsDiff, withChain, type DiffData } from "./diffInput";
import { bindingsFor, normalizeBinding, registerKeyClaim, shortcutLabel } from "@/platform/keymap";
import { openDiff, openVcsDiff, withChain, workingDiffData, type DiffData } from "./diffInput";
import { showCreatePatchForShelf } from "./patches";
import { executeAction } from "@/platform/actions";
import { call, commands } from "@/platform/ipc";
@@ -174,7 +174,9 @@ function filesBelow<F>(node: FileTreeNode<F>, out: F[] = []): F[] {
/**
* A checkable tree of changed files under the repository's node, grouped by directory (Shelve,
* Unshelve, Create Patch), as IDEA's changes tree: a directory's box checks or clears every file
* below it and shows a dash when only some are included.
* below it and shows a dash when only some are included. With `diffOf`, double-click, Enter and
* Show Diff open a file's diff (the tree's files as the chain) and Space toggles the selected rows,
* as in IDEA's changes browsers.
*/
function ChangeChecklist<F>({
files,
@@ -187,6 +189,7 @@ function ChangeChecklist<F>({
onChange,
label,
className,
diffOf,
}: {
files: readonly F[];
keyOf: (f: F) => string;
@@ -199,13 +202,48 @@ function ChangeChecklist<F>({
onChange: (next: Set<string>) => void;
label: string;
className?: string;
diffOf?: (file: F) => DiffData;
}) {
const tree: FileTreeNode<F>[] = [
{ key: "r:", name: rootName, file: null, children: buildFileTree(files, relPath), count: files.length },
];
const [expanded, setExpanded] = useState<ReadonlySet<string> | null>(null);
const toggle = (node: FileTreeNode<F>) => {
const below = filesBelow(node);
const [rows, setRows] = useState<ReadonlySet<string>>(new Set());
const content = useRef<HTMLDivElement>(null);
const showDiff =
diffOf &&
((file: F) => {
const chain = filesBelow(tree[0]!);
const items = chain.map(diffOf);
void import("./diffDialog").then(({ openDiffDialog }) => {
if (content.current?.isConnected) openDiffDialog(withChain(items, chain.indexOf(file)));
});
});
const selectedNodes = () => {
const out: FileTreeNode<F>[] = [];
const walk = (list: readonly FileTreeNode<F>[]) => {
for (const n of list) {
if (rows.has(n.key)) out.push(n);
walk(n.children);
}
};
walk(tree);
return out;
};
useEffect(() => {
if (!showDiff) return;
return registerKeyClaim((event, stroke) => {
if (!(event.target instanceof Node) || !content.current?.contains(event.target)) return false;
if (!bindingsFor("vcs.showDiff").some((binding) => normalizeBinding(binding) === stroke)) return false;
event.preventDefault();
event.stopPropagation();
const file = [...selectedNodes(), tree[0]!].flatMap((n) => filesBelow(n))[0];
if (file) showDiff(file);
return true;
});
});
const toggle = (...nodes: FileTreeNode<F>[]) => {
const below = nodes.flatMap((n) => filesBelow(n));
const include = !below.every((f) => selected.has(keyOf(f)));
const next = new Set(selected);
for (const f of below) {
@@ -215,7 +253,18 @@ function ChangeChecklist<F>({
onChange(next);
};
return (
<div className={clsx(styles.fileTree, className)}>
<div
ref={content}
className={clsx(styles.fileTree, className)}
onKeyDownCapture={(e) => {
if (!showDiff || e.key !== " " || e.metaKey || e.ctrlKey || e.altKey) return;
const nodes = selectedNodes();
if (!nodes.length) return;
e.preventDefault();
e.stopPropagation();
toggle(...nodes);
}}
>
<Tree<FileTreeNode<F>>
roots={tree}
getKey={(n) => n.key}
@@ -224,7 +273,13 @@ function ChangeChecklist<F>({
isExpandable={(n) => !n.file}
expanded={expanded ?? new Set(dirKeys(tree))}
onExpandedChange={setExpanded}
onActivate={toggle}
selected={rows}
onSelectionChange={setRows}
onActivate={(n, e) => {
if (!showDiff) toggle(n);
// A double-click on the box only toggles it, through its own clicks.
else if (n.file && !(e.target instanceof Element && e.target.closest("label"))) showDiff(n.file);
}}
aria-label={label}
className={styles.fileTreeView}
renderNode={(n) => {
@@ -260,12 +315,15 @@ export function FileChecklist({
onChange,
label,
className,
diffSide,
}: {
files: readonly FileStatus[];
selected: ReadonlySet<string>;
onChange: (next: Set<string>) => void;
label: string;
className?: string;
/** The side a file's diff shows: Rollback Unstaged Changes compares the index with the working copy. */
diffSide?: "unstaged";
}) {
const root = useVcs((s) => s.root) ?? "";
return (
@@ -279,6 +337,7 @@ export function FileChecklist({
onChange={onChange}
label={label}
className={className}
diffOf={(f) => workingDiffData(f.path, undefined, diffSide, f)}
/>
);
}