From 1f4ac3afbb68c06111ae3ce3344569adc9eef7be Mon Sep 17 00:00:00 2001 From: LU XIANGRUI <1078666705@qq.com> Date: Sat, 5 Dec 2026 17:13:35 +0900 Subject: [PATCH] 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 <26499420+wildcatDownstairs@users.noreply.github.com> --- src/features/vcs/DiffEditor.module.css | 37 ++++++ src/features/vcs/DiffEditor.tsx | 40 ++++++ src/features/vcs/DiffFilesPopup.tsx | 117 ++++++++++++++++++ .../vcs/__tests__/diffToolbar.test.tsx | 27 +++- .../vcs/__tests__/show-diff-chain.test.ts | 17 +++ src/features/vcs/actions.tsx | 34 +++-- src/features/vcs/diffInput.ts | 13 ++ src/platform/locales/text/en.json | 3 +- src/platform/locales/text/zh.json | 3 +- 9 files changed, 273 insertions(+), 18 deletions(-) create mode 100644 src/features/vcs/DiffFilesPopup.tsx diff --git a/src/features/vcs/DiffEditor.module.css b/src/features/vcs/DiffEditor.module.css index 2284ff4e85..02fe16656c 100644 --- a/src/features/vcs/DiffEditor.module.css +++ b/src/features/vcs/DiffEditor.module.css @@ -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; +} diff --git a/src/features/vcs/DiffEditor.tsx b/src/features/vcs/DiffEditor.tsx index 04ff3f24af..93d7c47b92 100644 --- a/src/features/vcs/DiffEditor.tsx +++ b/src/features/vcs/DiffEditor.tsx @@ -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 ; @@ -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(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(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 && ( + + )} + {position && filesAnchor && input_.chain && ( + void showChainFile(entry)} + onClose={() => setFilesAnchor(null)} + /> + )} 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(); + 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>(() => new Set(folderKeys)); + const tree = useRef(null); + const pick = (node: ChainNode) => { + if (!node.data) return; + onClose(); + onPick(node.data); + }; + return ( + +
+ setExpanded(new Set(folderKeys))} + /> + setExpanded(new Set())} /> +
+ + 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 + /> +
+ ); +} diff --git a/src/features/vcs/__tests__/diffToolbar.test.tsx b/src/features/vcs/__tests__/diffToolbar.test.tsx index f092a47094..2078e5dfd4 100644 --- a/src/features/vcs/__tests__/diffToolbar.test.tsx +++ b/src/features/vcs/__tests__/diffToolbar.test.tsx @@ -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(); + 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(); 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(); }); }); diff --git a/src/features/vcs/__tests__/show-diff-chain.test.ts b/src/features/vcs/__tests__/show-diff-chain.test.ts index 498e18b3bf..2fc4317973 100644 --- a/src/features/vcs/__tests__/show-diff-chain.test.ts +++ b/src/features/vcs/__tests__/show-diff-chain.test.ts @@ -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"; diff --git a/src/features/vcs/actions.tsx b/src/features/vcs/actions.tsx index a6b75df465..13a792694d 100644 --- a/src/features/vcs/actions.tsx +++ b/src/features/vcs/actions.tsx @@ -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; diff --git a/src/features/vcs/diffInput.ts b/src/features/vcs/diffInput.ts index 8a8e0ee570..af65afcda6 100644 --- a/src/features/vcs/diffInput.ts +++ b/src/features/vcs/diffInput.ts @@ -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; diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 7c87d51bdd..e0ae45e9d4 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -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" } diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 451fa5604d..b094456e3c 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -12746,5 +12746,6 @@ "1 file": "1 个文件", "1 image": "1 张图片", "{imageCount} images": "{imageCount} 张图片", - "{title} actions": "{title} 操作" + "{title} actions": "{title} 操作", + "{n}/{count} files": "{n}/{count} 个文件" }