feat(diff): files counter and change list in the diff window (#8183)

A diff opened in its own window had no way to move to the next changed file: Show Diff in New Window built a single-file diff without the change set, and neither the window nor diff tabs had a files counter. Show Diff in New Window now builds its diff the same way as Show Diff (one selected change brings its whole changelist, several bring exactly those; a diff tab's own data still wins), so Compare Previous/Next File appear. A "2/5 files" counter between them opens the chain's files grouped by folder, with Expand All / Collapse All and speed search; Enter or a double-click shows that file in place, saving a staged draft first.

Refs #7433

Co-authored-by: wildcatDownstairs <[email protected]>
Цей коміт міститься в:
LU XIANGRUIтаwildcatDownstairs authored and GitHub committed 2026-12-05 16:13:35 +08:00
1 джерело 7a20b20b2d
коміт 1f4ac3afbb
9 files changed
+273 -18

No files matched your search

+37
Переглянути файл
@@ -526,3 +526,40 @@
.fit .host :global(.cm-mergeViewEditors) {
min-height: 0;
}
/* IntelliJ's files counter between Compare Previous File and Compare Next File ("2/5 files"). */
.filesCounter {
border: 0;
padding: 0 var(--space-1);
background: none;
color: var(--fg-secondary);
font: inherit;
font-size: var(--fs-small);
border-radius: var(--radius-small);
cursor: pointer;
}
.filesCounter:hover,
.filesCounter[aria-expanded="true"] {
background: var(--bg-hover);
color: var(--fg-strong);
}
.filesCounter:focus-visible {
outline: 2px solid var(--focus-ring);
outline-offset: -2px;
}
.filesPopup {
display: flex;
flex-direction: column;
width: 380px;
height: 320px;
}
.filesPopupToolbar {
display: flex;
gap: var(--space-0-5);
padding: var(--space-1);
border-bottom: 1px solid var(--border);
}
.filesPopupTree {
flex: 1 1 auto;
min-height: 0;
}
+40
Переглянути файл
@@ -44,6 +44,7 @@ import { call, commands } from "@/platform/ipc";
import { reducedMotion } from "@/platform/motion";
import { bindingsFor, normalizeBinding, registerKeyClaim, shortcutLabel, strokeOf } from "@/platform/keymap";
import { tx } from "@/platform/i18n";
import { DiffFilesPopup } from "./DiffFilesPopup";
import { useProject } from "@/platform/project";
import { isVirtualUri } from "@/platform/virtualDocs";
import { isRemoteWindow } from "@/platform/remote";
@@ -86,7 +87,9 @@ import {
type IgnorePolicy,
} from "./diffOptions";
import {
chainEntry,
chainNeighbour,
chainPosition,
diffTitle,
detectLineEnding,
hasGitlink,
@@ -406,6 +409,9 @@ export interface DiffEditorProps {
onFirstChangeShown?: () => void;
}
/** IntelliJ's files counter: the shown file's place in its chain. */
const filesCounter = (n: number, count: number) => tx`${n}/${count} files`;
export function DiffEditor(props: DiffEditorProps) {
const diff = useGitDiffEntries(props.input.data as DiffData);
return <ResolvedDiffEditor {...props} diff={diff} />;
@@ -1649,6 +1655,20 @@ function TwoPaneDiff({
const file = (dir: 1 | -1) => {
void openNeighbour(dir);
};
// IntelliJ's files counter between Compare Previous File and Compare Next File ("2/5 files"):
// it opens the chain's files to show any of them.
const position = chainPosition(input_);
const [filesAnchor, setFilesAnchor] = useState<HTMLElement | null>(null);
const showChainFile = async (entry: DiffData) => {
try {
await indexDoc?.save();
} catch {
return; // A failed save keeps the staged draft in this diff.
}
const target = chainEntry(input_, entry);
if (onNeighbour) onNeighbour(target);
else await openDiff(target, { preview: true });
};
const toolbarRef = useRef<HTMLDivElement | null>(null);
/** The viewer settings menu, under the toolbar's gear (`from`) or its start. */
const showSettings = (from?: HTMLElement) => {
@@ -1924,6 +1944,26 @@ function TwoPaneDiff({
disabled={!chainNeighbour(input_, -1)}
onClick={() => file(-1)}
/>
{position && (
<button
type="button"
className={styles.filesCounter}
aria-haspopup="dialog"
aria-expanded={!!filesAnchor}
onClick={(e) => setFilesAnchor(e.currentTarget)}
>
{position.count === 1 ? tx("1 file") : filesCounter(position.index + 1, position.count)}
</button>
)}
{position && filesAnchor && input_.chain && (
<DiffFilesPopup
chain={input_.chain}
current={position.index}
anchor={filesAnchor}
onPick={(entry) => void showChainFile(entry)}
onClose={() => setFilesAnchor(null)}
/>
)}
<IconButton
icon="arrow-right"
title="Compare Next File"
+117
Переглянути файл
@@ -0,0 +1,117 @@
/**
* The files counter's popup of a diff chain ("2/5 files"), as IntelliJ's `GoToChangePopupUtil`:
* the chain's files grouped by folder, with Expand All / Collapse All and speed search. Picking
* one shows it in place of the current diff.
*/
import { useMemo, useRef, useState } from "react";
import { tx } from "@/platform/i18n";
import { fileIconName, IconButton, Popup, Tree, type PopupAnchor, type TreeHandle } from "@/ui";
import { diffTitle, type DiffData } from "./diffInput";
import styles from "./DiffEditor.module.css";
export interface ChainNode {
key: string;
label: string;
/** A file of the chain; folders have `children`. */
data?: DiffData;
children?: ChainNode[];
}
const dirOf = (path: string) => path.slice(0, Math.max(0, path.lastIndexOf("/")));
const nameOf = (path: string) => path.slice(path.lastIndexOf("/") + 1);
/** The folders the chain's files share: the common parent of all of them. */
function commonDir(paths: readonly string[]): string {
const dirs = paths.map(dirOf);
let common = dirs[0] ?? "";
for (const dir of dirs) while (common && dir !== common && !dir.startsWith(`${common}/`)) common = dirOf(common);
return common;
}
/**
* `chain` as IntelliJ's go-to-change tree with directory grouping: one node per folder (its path
* from the folder all files share, the shared one itself as "."), its files in chain order.
*/
export function chainTree(chain: readonly DiffData[]): ChainNode[] {
const base = commonDir(chain.map((d) => d.path.replace(/\\/g, "/")));
const folders = new Map<string, ChainNode>();
chain.forEach((data, i) => {
const path = data.path.replace(/\\/g, "/");
const dir = dirOf(path);
const label = dir === base ? "." : dir.slice(base ? base.length + 1 : 0);
let folder = folders.get(dir);
if (!folder) {
folder = { key: `dir:${dir}`, label, children: [] };
folders.set(dir, folder);
}
folder.children!.push({ key: `file:${i}`, label: nameOf(path), data });
});
return [...folders.values()];
}
export function DiffFilesPopup({
chain,
current,
anchor,
onPick,
onClose,
}: {
chain: readonly DiffData[];
current: number;
anchor: PopupAnchor;
onPick: (data: DiffData) => void;
onClose: () => void;
}) {
const roots = useMemo(() => chainTree(chain), [chain]);
const folderKeys = useMemo(() => roots.map((r) => r.key), [roots]);
const [expanded, setExpanded] = useState<ReadonlySet<string>>(() => new Set(folderKeys));
const tree = useRef<TreeHandle>(null);
const pick = (node: ChainNode) => {
if (!node.data) return;
onClose();
onPick(node.data);
};
return (
<Popup
open
anchor={anchor}
placement="bottom-start"
onClose={onClose}
className={styles.filesPopup}
role="dialog"
aria-label={tx("Changed files")}
resizable="both"
minWidth={280}
minHeight={160}
>
<div className={styles.filesPopupToolbar} role="toolbar" aria-label={tx("Changed files")}>
<IconButton
icon="expand-all"
title="Expand All"
size="small"
onClick={() => setExpanded(new Set(folderKeys))}
/>
<IconButton icon="collapse-all" title="Collapse All" size="small" onClick={() => setExpanded(new Set())} />
</div>
<Tree<ChainNode>
handleRef={tree}
className={styles.filesPopupTree}
aria-label={tx("Changed files")}
roots={roots}
getKey={(n) => n.key}
getLabel={(n) => n.label}
getChildren={(n) => n.children}
isExpandable={(n) => !!n.children}
getIcon={(n, open) => (n.children ? (open ? "folder-open" : "folder") : fileIconName(n.label, n.data?.path))}
getTooltip={(n) => (n.data ? diffTitle(n.data) : n.label)}
expanded={expanded}
onExpandedChange={(next) => setExpanded(next)}
defaultSelected={[`file:${current}`]}
onActivate={(n) => pick(n)}
speedSearch
speedSearchMode="filter"
autoFocus
/>
</Popup>
);
}
+24 -3
Переглянути файл
@@ -557,9 +557,9 @@ describe("Compare Previous / Next File buttons (#2492)", () => {
expect(
within(toolbar)
.getAllByRole("button")
.slice(0, 4)
.map((b) => b.getAttribute("aria-label")),
).toEqual(["Previous Difference", "Next Difference", "Compare Previous File", "Compare Next File"]);
.slice(0, 5)
.map((b) => b.getAttribute("aria-label") ?? b.textContent),
).toEqual(["Previous Difference", "Next Difference", "Compare Previous File", "2/3 files", "Compare Next File"]);
fireEvent.click(fileButtons()[1]!);
await waitFor(() => expect(openInput).toHaveBeenCalledOnce());
expect(openInput.mock.calls[0]![0].data).toMatchObject({
@@ -577,10 +577,31 @@ describe("Compare Previous / Next File buttons (#2492)", () => {
expect(fileButtons().map((b) => b.hasAttribute("disabled"))).toEqual(disabled);
});
it("lists the change set's files under the files counter, as IntelliJ's diff window does", async () => {
render(<DiffEditor input={chained(0)} />);
fireEvent.click(screen.getByRole("button", { name: "1/3 files" }));
const popup = await screen.findByRole("dialog", { name: "Changed files" });
const tree = within(popup).getByRole("tree", { name: "Changed files" });
// Grouped by folder (all three share /p), the shown file selected.
expect(
within(tree)
.getAllByRole("treeitem")
.map((row) => row.textContent),
).toEqual([".", "a.ts", "b.ts", "c.ts"]);
expect(within(tree).getByRole("treeitem", { name: /a\.ts/ })).toHaveAttribute("aria-selected", "true");
fireEvent.doubleClick(within(tree).getByText("c.ts"));
await waitFor(() => expect(openInput).toHaveBeenCalledOnce());
const shown = openInput.mock.calls[0]![0].data as DiffData;
expect(shown).toMatchObject({ path: "/p/c.ts", reveal: "first" });
expect(shown.chain?.map((d) => d.path)).toEqual(["/p/a.ts", "/p/b.ts", "/p/c.ts"]);
expect(screen.queryByRole("dialog", { name: "Changed files" })).toBeNull();
});
it("has no file buttons for a single diff", () => {
render(<DiffEditor input={input} />);
expect(screen.queryByRole("button", { name: "Compare Next File" })).toBeNull();
expect(screen.queryByRole("button", { name: "Compare Previous File" })).toBeNull();
expect(screen.queryByRole("button", { name: /files?$/ })).toBeNull();
});
});
+17
Переглянути файл
@@ -152,6 +152,23 @@ it("opens the active editor file, not a Project view selection kept from earlier
expect(separateWindow.mock.calls[0]![0]).toMatchObject({ path: "/repo/b.ts" });
});
it("opens the new window with the files of the change set it was opened from (issue #7433)", async () => {
// From the editor: the file's changelist, as Show Diff.
active.path = "/repo/b.ts";
await getAction("vcs.showDiffInNewWindow")!.run({ arg: undefined, ctx: { vcsAvailable: true } });
const fromEditor = separateWindow.mock.calls[0]![0] as DiffData;
expect(fromEditor.path).toBe("/repo/b.ts");
expect(fromEditor.chain?.map((d) => d.path)).toEqual(["/repo/a.ts", "/repo/b.ts", "/repo/z.ts"]);
// From the Commit window's selection of several files: those files.
active.path = null;
setContext("activeToolWindow", "commit");
useCommit.setState({ selection: ["/repo/z.ts", "/repo/other.ts"] });
await getAction("vcs.showDiffInNewWindow")!.run({ arg: undefined, ctx: { vcsAvailable: true } });
const fromSelection = separateWindow.mock.calls[1]![0] as DiffData;
expect(fromSelection.chain?.map((d) => d.path)).toEqual(["/repo/z.ts", "/repo/other.ts"]);
});
it("closes the front diff dialog once the diff moved to a window", async () => {
modal();
active.path = "/repo/b.ts";
+21 -13
Переглянути файл
@@ -222,6 +222,20 @@ function groupDiffData(tree: readonly ChangeNode[], path: string): DiffData {
);
}
/**
* One diff of Show Diff's `targets`: several as one chain; one with the other files of its
* group (IntelliJ's chain of the change's changelist), as the diff window shows them.
*/
function targetsDiffData(tree: readonly ChangeNode[], targets: readonly (ChangeNode | string)[]): DiffData {
const [first] = targets;
if (targets.length > 1)
return withChain(
targets.map((t) => (typeof t === "string" ? workingDiffData(t) : changeNodeDiff(t))),
0,
);
return typeof first === "string" ? groupDiffData(tree, first) : changeNodeDiffData(tree, first!);
}
/**
* Show Diff's files as tree nodes where the side of the index is known: the changes
* tree's selected file nodes, else the nodes of `paths` the tree lists once. A
@@ -922,17 +936,7 @@ export function registerVcsActions(): () => void {
// The modal interface has one front diff window (#1863): a file with its group
// as the F7 chain, or several selected files as the chain.
if (isModalCommit()) {
const [first] = targets;
const data =
targets.length > 1
? withChain(
targets.map((t) => (typeof t === "string" ? workingDiffData(t) : changeNodeDiff(t))),
0,
)
: typeof first === "string"
? groupDiffData(tree, first)
: changeNodeDiffData(tree, first!);
await openVcsDiff({ ...data, line });
await openVcsDiff({ ...targetsDiffData(tree, targets), line });
return;
}
// Several selected changed files (a changelist node) open as one diff chain,
@@ -967,9 +971,13 @@ export function registerVcsActions(): () => void {
const source = arg === undefined ? focusedDiffSource() : null;
if (source) return showSourceDiffInNewWindow(source);
const viewed = requested ?? focusedDiffNavigator()?.viewer?.()?.data;
const path = focusedSelection(arg, ctx)[0];
const paths = focusedSelection(arg, ctx);
const path = paths[0];
if (!viewed && arg === undefined && path && !statusOf(path)) return notifyNoLocalChanges(path);
const data = viewed ?? (path ? workingDiffData(path) : null);
// As Show Diff: the window gets the files of the change set it was opened from.
const tree = currentChangeTree();
const fromTree = !argPaths(arg)?.length && commitWindowFocused();
const data = viewed ?? (path ? targetsDiffData(tree, showDiffTargets(tree, paths, fromTree)) : null);
if (!data) {
notifications().notify({ group: "vcs", level: "info", title: "Select a changed file to show its diff" });
return;
+13
Переглянути файл
@@ -182,6 +182,19 @@ export function withChain(items: readonly DiffData[], index: number): DiffData {
return { ...items[index]!, chain };
}
/** Where `data` is in its chain: the files counter of the diff toolbar ("2/5 files"). */
export function chainPosition(data: DiffData): { index: number; count: number } | null {
const chain = data.chain;
if (!chain) return null;
const index = chain.findIndex((d) => diffKey(d) === diffKey(data));
return index < 0 ? null : { index, count: chain.length };
}
/** `entry` of `data`'s chain, to show in its place. */
export function chainEntry(data: DiffData, entry: DiffData): DiffData {
return { ...entry, chain: data.chain, reveal: "first" };
}
/** The neighbour of `data` in its chain (`dir` 1: next, -1: previous), revealing the nearest difference. */
export function chainNeighbour(data: DiffData, dir: 1 | -1): DiffData | null {
const chain = data.chain;
+2 -1
Переглянути файл
@@ -5856,5 +5856,6 @@
"{count} files": "{count} files",
"1 image": "1 image",
"{imageCount} images": "{imageCount} images",
"{title} actions": "{title} actions"
"{title} actions": "{title} actions",
"{n}/{count} files": "{n}/{count} files"
}
+2 -1
Переглянути файл
@@ -12746,5 +12746,6 @@
"1 file": "1 个文件",
"1 image": "1 张图片",
"{imageCount} images": "{imageCount} 张图片",
"{title} actions": "{title} 操作"
"{title} actions": "{title} 操作",
"{n}/{count} files": "{n}/{count} 个文件"
}