diff --git a/e2e/branchCompareLayout.spec.ts b/e2e/branchCompareLayout.spec.ts index d1a34fc794..443d8ee69a 100644 --- a/e2e/branchCompareLayout.spec.ts +++ b/e2e/branchCompareLayout.spec.ts @@ -96,17 +96,13 @@ test("Branch comparison reuses one editor tab and keeps both commit ranges indep await expect(incoming.getByRole("option")).toBeVisible(); await expect(outgoing.getByRole("option")).toBeVisible(); await page.getByRole("button", { name: "Show Branch Diff", exact: true }).click(); - await expect - .poll(() => ipcCalls(page, "window_open_comparison")) - .toMatchObject([ - { - comparison: { - from: { rev: `refs/heads/${branch}` }, - to: { rev: `refs/heads/${current}` }, - repo: "/dev/acme-api", - }, - }, - ]); + // The comparison opens as a tab of the Compare tool window, not a separate window. + await expect( + page + .getByRole("tablist", { name: "Comparisons" }) + .getByRole("tab", { name: new RegExp(`^Changes between .*${branch}`) }), + ).toBeVisible(); + expect(await ipcCalls(page, "window_open_comparison")).toEqual([]); await page.getByRole("tablist", { name: "Editor tabs" }).getByRole("button", { name: "Close Tab" }).click(); await expect(incomingPane).toHaveCount(0); await expect(outgoingPane).toHaveCount(0); diff --git a/src/features/vcs/__tests__/compareTool.test.tsx b/src/features/vcs/__tests__/compareTool.test.tsx index 77b6d04bca..2622fdd288 100644 --- a/src/features/vcs/__tests__/compareTool.test.tsx +++ b/src/features/vcs/__tests__/compareTool.test.tsx @@ -10,6 +10,8 @@ const mocks = vi.hoisted(() => ({ openTabs: vi.fn(), closeInput: vi.fn(), diffWindow: vi.fn(), + openComparison: vi.fn(), + comparePaths: vi.fn(), })); vi.mock("../DiffWindow", () => ({ showDiffWindow: mocks.diffWindow })); vi.mock("@/platform/ipc", async (original) => { @@ -21,7 +23,9 @@ vi.mock("@/platform/ipc", async (original) => { ...real.commands, vcsDiffWithWorktree: mocks.worktree, vcsDiffRevisions: mocks.revisions, + vcsComparePaths: mocks.comparePaths, jvmFilePresentations: mocks.presentations, + windowOpenComparison: mocks.openComparison, }, }; }); @@ -47,8 +51,15 @@ import { executeAction } from "@/platform/actions"; import { setContext } from "@/platform/context"; import { installKeyboardDispatcher, useKeymap } from "@/platform/keymap"; import { useProject } from "@/platform/project"; -import { ChangesBetweenDialog, comparisonDiffData, type ComparisonFile } from "../operations"; -import { CompareToolWindow, useCompareTool } from "../compareTool"; +import { useContributions } from "@/workbench/contributions"; +import { + ChangesBetweenDialog, + comparisonDiffData, + showCompareVersions, + showPathComparison, + type ComparisonFile, +} from "../operations"; +import { CompareToolWindow, showWorktreeComparison, useCompareTool } from "../compareTool"; import { registerVcsActions } from "../actions"; import { combinedDiffInput, diffInput, type DiffData } from "../diffInput"; import { useVcs } from "../store"; @@ -402,6 +413,106 @@ describe("CompareToolWindow", () => { }); }); +describe("comparison tabs", () => { + beforeEach(() => { + vi.clearAllMocks(); + mocks.openTabs.mockReturnValue([]); + mocks.openDiff.mockResolvedValue(undefined); + useProject.setState({ project: { root: "/workspace", name: "workspace" } as never }); + useVcs.setState({ available: true, root: "/workspace", roots: ["/workspace/client"], repo: "/workspace/client" }); + mocks.worktree.mockResolvedValue({ status: "ok", data: [modified] }); + mocks.revisions.mockResolvedValue({ status: "ok", data: [modified] }); + mocks.comparePaths.mockResolvedValue({ + status: "ok", + data: { skippedPaths: [], repositories: [{ root: "/workspace/client", revision: "main", files: [modified] }] }, + }); + }); + afterEach(() => { + cleanup(); + useCompareTool.getState().close(); + useProject.setState({ project: null }); + }); + + const strip = () => screen.getByRole("tablist", { name: "Comparisons" }); + + it("opens each comparison as its own tab, titled after what is compared", async () => { + useCompareTool.getState().show({ rev: "main", label: "main" }, { rev: "next", label: "next" }); + useCompareTool.getState().show({ rev: "dev", label: "dev" }, null); + render(); + const tabs = within(strip()).getAllByRole("tab"); + expect(tabs.map((t) => t.textContent)).toEqual([ + "Changes between main and next", + "Changes between dev and Local Working Tree", + ]); + // The newest tab is active: only its comparison is loaded. + expect(await screen.findByText("app.ts")).toBeInTheDocument(); + expect(mocks.worktree).toHaveBeenCalledWith("/workspace/client", "dev"); + expect(mocks.revisions).not.toHaveBeenCalled(); + }); + + it("switches between comparisons with their tabs, and closes them individually", async () => { + useCompareTool.getState().show({ rev: "main", label: "main" }, { rev: "next", label: "next" }); + useCompareTool.getState().show({ rev: "dev", label: "dev" }, null); + render(); + const tabs = () => within(strip()).getAllByRole("tab"); + fireEvent.click(tabs()[0]!); + expect(tabs()[0]).toHaveAttribute("aria-selected", "true"); + expect(await screen.findByText("app.ts")).toBeInTheDocument(); + expect(mocks.revisions).toHaveBeenCalledWith("/workspace/client", "main", "next"); + + const closeButtons = () => within(strip().parentElement!).getAllByRole("button", { name: "Close Tab" }); + // Closing the active dev tab falls back to the remaining comparison. + fireEvent.click(closeButtons()[1]!); + expect(tabs()).toHaveLength(1); + expect(tabs()[0]).toHaveAttribute("aria-selected", "true"); + expect(within(strip()).getByRole("tab", { name: "Changes between main and next" })).toBeInTheDocument(); + fireEvent.click(closeButtons()[0]!); + // The last close clears the comparison (and the tool window body) entirely. + expect(screen.queryByRole("tablist", { name: "Comparisons" })).toBeNull(); + }); + + it("shows the number of open comparisons as the Compare tool window's badge", () => { + function BadgeProbe() { + const badge = useContributions((s) => s.toolWindows.get("compare")?.useBadge); + return {badge ? badge() : "unregistered"}; + } + const renderBadge = () => render(); + showWorktreeComparison("main", "main"); + let view = renderBadge(); + expect(screen.getByTestId("badge")).toHaveTextContent("1"); + view.unmount(); + act(() => useCompareTool.getState().show({ rev: "dev", label: "dev" }, null)); + view = renderBadge(); + expect(screen.getByTestId("badge")).toHaveTextContent("2"); + view.unmount(); + act(() => useCompareTool.getState().close()); + view = renderBadge(); + // No open comparison: the stripe hides the badge. + expect(screen.getByTestId("badge")).toBeEmptyDOMElement(); + view.unmount(); + }); + + it("opens Git Log Compare Versions in the Compare tool window instead of a comparison window", async () => { + render(); + showCompareVersions({ id: "aaa11111zz" } as never, { id: "bbb22222zz" } as never); + expect(mocks.openComparison).not.toHaveBeenCalled(); + expect(await screen.findByText("app.ts")).toBeInTheDocument(); + expect(within(strip()).getByRole("tab", { name: "Changes between aaa11111 and bbb22222" })).toBeInTheDocument(); + expect(mocks.revisions).toHaveBeenCalledWith("/workspace/client", "aaa11111zz", "bbb22222zz"); + }); + + it("opens Compare with Branch… on a folder in the Compare tool window instead of a comparison window", async () => { + render(); + showPathComparison(["/workspace/client/src"], "main", null); + expect(mocks.openComparison).not.toHaveBeenCalled(); + expect(await screen.findByText("app.ts")).toBeInTheDocument(); + expect( + within(strip()).getByRole("tab", { name: "Changes between main and Local Working Tree" }), + ).toBeInTheDocument(); + expect(mocks.comparePaths).toHaveBeenCalledWith(["/workspace/client/src"], "main", null, expect.anything()); + }); +}); + // The diff actions ask the focused tree for its diff (diffSource.ts): whatever the keymap binds, // the shortcut opens the compared sides, never the file against HEAD. With ⌘D bound to Show Diff // in New Window, the Compare tool window used to open an empty diff of an unrelated file. diff --git a/src/features/vcs/compareTool.tsx b/src/features/vcs/compareTool.tsx index fc1ebd006a..42de3c71f3 100644 --- a/src/features/vcs/compareTool.tsx +++ b/src/features/vcs/compareTool.tsx @@ -1,35 +1,96 @@ /** * The Compare tool window: `Show Diff with Working Tree` shows the worktree diff * in the sidebar instead of a dialog, with Jump to Source and Swap Sides (#2442). + * Branch and revision comparisons open here too (one closable tab per comparison, + * titled after what is compared, as in IDEA's VCS changes tool window): Compare with + * Branch…/Revision… on a folder or multi-selection, two-commit Compare Versions from + * the Git Log and the branches' Show Diff between two revisions (#7813). A single + * file keeps its diff editor tab, and Compare with Current keeps the two-pane + * BranchComparisonEditor. */ import { useCallback, useEffect, useRef } from "react"; import { create } from "zustand"; -import { Button } from "@/ui"; +import { Button, Tabs, showContextMenu } from "@/ui"; +import { tx } from "@/platform/i18n"; +import { useProject } from "@/platform/project"; import { maybeEditorService, notifications, registerToolWindow, type OpenEditorTab } from "@/workbench/contributions"; import { showToolWindow } from "@/workbench/toolwindows/store"; import { COMBINED_DIFF_KIND, type CombinedDiffData } from "./allInOneDiff"; import { combinedDiffInput, DIFF_KIND, diffInput, openVcsDiff, withChain, type DiffData } from "./diffInput"; -import { ChangesBetweenDialog, comparisonDiffData, type ComparisonFile, type Revision } from "./operations"; +import { + ChangesBetweenDialog, + comparisonDiffData, + type ComparisonFile, + type Revision, + type ScopedComparison, +} from "./operations"; import { repositoryPath } from "./repositoryPaths"; import styles from "./common.module.css"; +/** One comparison open in the tool window: IDEA's closable tab of the VCS changes view. */ +export interface CompareTab { + id: number; + title: string; + from: Revision; + to: Revision | null; + repositories?: readonly string[]; + scope?: ScopedComparison; + repo?: string | null; +} + +/** The caption of a comparison, as on the comparison window's title bar. */ +export function comparisonTitle(from: Revision, to: Revision | null): string { + return to + ? tx`Changes between ${from.label} and ${to.label}` + : tx`Changes between ${from.label} and Local Working Tree`; +} + interface CompareToolState { - target: { id: number; from: Revision; to: Revision | null; repositories?: readonly string[] } | null; + tabs: CompareTab[]; + activeId: number | null; swapped: boolean; current: ComparisonFile | null; - show: (from: Revision, to: Revision | null, repositories?: readonly string[]) => void; + show: ( + from: Revision, + to: Revision | null, + repositories?: readonly string[], + scope?: ScopedComparison, + repo?: string | null, + ) => void; + activate: (id: number) => void; + closeTab: (id: number) => void; close: () => void; toggleSwapped: () => void; select: (file: ComparisonFile | null) => void; } export const useCompareTool = create()((set) => ({ - target: null, + tabs: [], + activeId: null, swapped: false, current: null, - show: (from, to, repositories) => - set((s) => ({ target: { id: (s.target?.id ?? 0) + 1, from, to, repositories }, swapped: false, current: null })), - close: () => set({ target: null, swapped: false, current: null }), + show: (from, to, repositories, scope, repo) => + set((s) => { + const id = (s.tabs.at(-1)?.id ?? 0) + 1; + return { + tabs: [...s.tabs, { id, title: comparisonTitle(from, to), from, to, repositories, scope, repo }], + activeId: id, + swapped: false, + current: null, + }; + }), + activate: (activeId) => set({ activeId }), + closeTab: (id) => { + const { tabs, activeId } = useCompareTool.getState(); + const next = tabs.filter((tab) => tab.id !== id); + set({ + tabs: next, + activeId: next.length ? (id === activeId ? next.at(-1)!.id : activeId) : null, + ...(next.length ? {} : { swapped: false, current: null }), + }); + if (!next.length) disposeCompareWindowNow(); + }, + close: () => set({ tabs: [], activeId: null, swapped: false, current: null }), toggleSwapped: () => set((s) => ({ swapped: !s.swapped })), select: (current) => set({ current }), })); @@ -44,6 +105,7 @@ function ensureCompareWindow() { anchor: "left", order: 2, component: CompareToolWindow, + useBadge: () => useCompareTool((s) => s.tabs.length || null), }); } @@ -59,6 +121,21 @@ export function showWorktreeComparison(rev: string, label: string, repositories? showToolWindow("compare", true); } +/** Branch/revision comparison as a tab of the Compare tool window (folder/multi-selection scope included). */ +export function showComparisonTab(from: Revision, to: Revision | null, scope?: ScopedComparison, repo?: string | null) { + useCompareTool.getState().show(from, to, scope?.repositories ?? undefined, scope, repo); + ensureCompareWindow(); + showToolWindow("compare", true); +} + +// The comparisons belong to a project: a switch closes the tabs and the stripe button with them. +useProject.subscribe((current, previous) => { + if (current.project !== previous.project) { + useCompareTool.setState({ tabs: [], activeId: null, swapped: false, current: null }); + disposeCompareWindowNow(); + } +}); + function openComparisonSwaps( tabs: readonly OpenEditorTab[], files: readonly ComparisonFile[], @@ -102,20 +179,24 @@ function openComparisonSwaps( } export function CompareToolWindow() { - const target = useCompareTool((s) => s.target); + const tabs = useCompareTool((s) => s.tabs); + const activeId = useCompareTool((s) => s.activeId); const swapped = useCompareTool((s) => s.swapped); const current = useCompareTool((s) => s.current); + const activate = useCompareTool((s) => s.activate); + const closeTab = useCompareTool((s) => s.closeTab); const toggleSwapped = useCompareTool((s) => s.toggleSwapped); const select = useCompareTool((s) => s.select); const close = useCompareTool((s) => s.close); + const active = tabs.find((tab) => tab.id === activeId) ?? null; const filesRef = useRef([]); const handleFiles = useCallback((files: readonly ComparisonFile[]) => { filesRef.current = files; }, []); useEffect(() => { filesRef.current = []; - }, [target?.id]); - if (!target) return null; + }, [active?.id]); + if (!active) return null; const jumpToSource = () => { if (!current || current.kind === "deleted") return; void maybeEditorService()?.openFile(repositoryPath(current.root, current.path), { focus: true }); @@ -132,16 +213,16 @@ export function CompareToolWindow() { const editor = maybeEditorService(); const tabs = editor?.openTabs?.(); if (!editor || !tabs?.length) return; - const swaps = openComparisonSwaps(tabs, filesRef.current, target.from, target.to, prevSwapped, nextSwapped); + const swaps = openComparisonSwaps(tabs, filesRef.current, active.from, active.to, prevSwapped, nextSwapped); if (!swaps.length) return; - const targetId = target.id; + const targetId = active.id; void (async () => { for (const { closeKey, next } of swaps) { - if (useCompareTool.getState().target?.id !== targetId || useCompareTool.getState().swapped !== nextSwapped) + if (useCompareTool.getState().activeId !== targetId || useCompareTool.getState().swapped !== nextSwapped) return; // oxlint-disable-next-line no-await-in-loop -- preserve active-tab order (background tabs first, active tab last) await openVcsDiff(next, { focus: false }); - if (useCompareTool.getState().target?.id === targetId && useCompareTool.getState().swapped === nextSwapped) { + if (useCompareTool.getState().activeId === targetId && useCompareTool.getState().swapped === nextSwapped) { // oxlint-disable-next-line no-await-in-loop -- close each replaced tab only after its replacement opens await editor.closeInput?.(closeKey); } @@ -156,6 +237,34 @@ export function CompareToolWindow() { }; return (
+ ({ + id: String(tab.id), + label: tab.title, + verbatim: true, + tooltip: tab.title, + closable: true, + }))} + activeId={String(active.id)} + onSelect={(id) => activate(Number(id))} + onClose={(id) => closeTab(Number(id))} + onContextMenu={(id, e) => { + const tab = tabs.find((t) => t.id === Number(id)); + if (!tab) return; + showContextMenu(e, [ + { id: "close", label: "Close Tab", run: () => closeTab(tab.id) }, + { id: "closeAll", label: "Close All Tabs", run: () => tabs.forEach((t) => closeTab(t.id)) }, + { + id: "closeOthers", + label: "Close Other Tabs", + disabled: tabs.length < 2, + run: () => tabs.forEach((t) => t.id !== tab.id && closeTab(t.id)), + }, + ]); + }} + />
); return; } - const comparison = { from, to, scope: scope ?? null, repo }; - void call(commands.windowOpenComparison(comparison, windowBackgroundHex())).catch((error) => - notifications().notify({ level: "error", title: "Could not open comparison", body: String(error) }), - ); + // A closable tab of the Compare tool window (IDEA routes these through + // CompareWithLocalDialog.showChanges / GitShowDiffWithBranchPanel.showAsTab). + showComparisonTab(from, to, scope, repo); } export interface Revision { @@ -1083,7 +1081,7 @@ export interface Revision { label: string; } -interface ScopedComparison { +export interface ScopedComparison { paths: string[]; repositories: string[] | null; } diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 76f1f6d023..a55bf8596a 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -1029,6 +1029,7 @@ "Astro Language Server needs a TypeScript language-service library. Install typescript@6 in the project or select a TypeScript lib directory in Settings.": "Astro Language Server needs a TypeScript language-service library. Install typescript@6 in the project or select a TypeScript lib directory in Settings.", "Cannot show current revision": "Cannot show current revision", "Compare": "Compare", + "Comparisons": "Comparisons", "Compare with Revision…": "Compare with Revision…", "Revision changes are still loading": "Revision changes are still loading", "Swap Sides": "Swap Sides", diff --git a/src/platform/locales/text/es.json b/src/platform/locales/text/es.json index cbdc754b0e..4d0a94ab16 100644 --- a/src/platform/locales/text/es.json +++ b/src/platform/locales/text/es.json @@ -6034,7 +6034,6 @@ "Couldn't apply the suggested change": "No se pudo aplicar el cambio sugerido", "Couldn't resolve the thread": "No se pudo resolver el hilo", "Could not close comparison": "No se pudo cerrar la comparación", - "Could not open comparison": "No se pudo abrir la comparación", "Could not show diff": "No se pudieron mostrar las diferencias", "Back to Changed Files": "Volver a Archivos modificados", "Default (the module's JDK)": "Predeterminado (el JDK del módulo)", diff --git a/src/platform/locales/text/ko.json b/src/platform/locales/text/ko.json index 70dad62f7d..a12fd0c68e 100644 --- a/src/platform/locales/text/ko.json +++ b/src/platform/locales/text/ko.json @@ -6104,7 +6104,6 @@ "Couldn't apply the suggested change": "제안된 변경 사항을 적용할 수 없습니다", "Couldn't resolve the thread": "스레드를 해결할 수 없습니다", "Could not close comparison": "비교를 닫을 수 없습니다", - "Could not open comparison": "비교를 열 수 없습니다", "Could not show diff": "Diff를 표시할 수 없습니다", "Back to Changed Files": "변경된 파일로 돌아가기", "Default (the module's JDK)": "기본값(모듈의 JDK)", diff --git a/src/platform/locales/text/pl.json b/src/platform/locales/text/pl.json index 7efc41deaa..2804725ed1 100644 --- a/src/platform/locales/text/pl.json +++ b/src/platform/locales/text/pl.json @@ -5944,7 +5944,6 @@ "Couldn't apply the suggested change": "Nie udało się zastosować sugerowanej zmiany", "Couldn't resolve the thread": "Nie udało się rozwiązać wątku", "Could not close comparison": "Nie udało się zamknąć porównania", - "Could not open comparison": "Nie udało się otworzyć porównania", "Could not show diff": "Nie udało się wyświetlić różnic (diff)", "Back to Changed Files": "Powrót do zmienionych plików", "Default (the module's JDK)": "Domyślnie (zestaw JDK modułu)", diff --git a/src/platform/locales/text/pt.json b/src/platform/locales/text/pt.json index 3eb1467356..13df206d15 100644 --- a/src/platform/locales/text/pt.json +++ b/src/platform/locales/text/pt.json @@ -5959,7 +5959,6 @@ "Couldn't apply the suggested change": "Não foi possível aplicar a alteração sugerida", "Couldn't resolve the thread": "Não foi possível resolver a conversa", "Could not close comparison": "Não foi possível fechar a comparação", - "Could not open comparison": "Não foi possível abrir a comparação", "Could not show diff": "Não foi possível exibir o diff", "Back to Changed Files": "Voltar para Arquivos alterados", "Default (the module's JDK)": "Padrão (JDK do módulo)", diff --git a/src/platform/locales/text/ru.json b/src/platform/locales/text/ru.json index b55526e3cd..b1625d70dd 100644 --- a/src/platform/locales/text/ru.json +++ b/src/platform/locales/text/ru.json @@ -7622,7 +7622,6 @@ "Couldn't apply the suggested change": "Не удалось применить предложенное изменение", "Couldn't resolve the thread": "Не удалось разрешить обсуждение", "Could not close comparison": "Не удалось закрыть сравнение", - "Could not open comparison": "Не удалось открыть сравнение", "Could not show diff": "Не удалось показать различия", "Comparison actions": "Действия сравнения", "Back to Changed Files": "Назад к изменённым файлам", diff --git a/src/platform/locales/text/tr.json b/src/platform/locales/text/tr.json index 12b6cca89f..f33c52c64b 100644 --- a/src/platform/locales/text/tr.json +++ b/src/platform/locales/text/tr.json @@ -8639,7 +8639,6 @@ "Couldn't apply the suggested change": "Önerilen değişiklik uygulanamadı", "Couldn't resolve the thread": "Yorum dizisi çözülemedi", "Could not close comparison": "Karşılaştırma kapatılamadı", - "Could not open comparison": "Karşılaştırma açılamadı", "Back to Changed Files": "Değiştirilen Dosyalara Dön", "Default (the module's JDK)": "Varsayılan (modülün JDK'sı)", "Use classpath of module": "Modülün sınıf yolunu kullan", diff --git a/src/platform/locales/text/zh-TW.json b/src/platform/locales/text/zh-TW.json index 63101aae69..cd3ab0de3d 100644 --- a/src/platform/locales/text/zh-TW.json +++ b/src/platform/locales/text/zh-TW.json @@ -7234,7 +7234,6 @@ "Couldn't apply the suggested change": "無法應用建議的更改", "Couldn't resolve the thread": "無法解決討論串", "Could not close comparison": "無法關閉比較視窗", - "Could not open comparison": "無法開啟比較視窗", "Could not show diff": "無法顯示差異", "Comparison actions": "比較操作", "Back to Changed Files": "返回更改檔案清單", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 57d2e27970..a12123d1c8 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -1713,6 +1713,7 @@ "Compact mode": "紧凑模式", "Companion object": "伴生对象", "Compare": "对比", + "Comparisons": "比较列表", "Compare Files": "比较文件", "Compare File with Editor": "将文件与编辑器比较", "Select a file in the Project view to compare with the editor": "在项目视图中选择一个要与编辑器比较的文件", @@ -8194,7 +8195,6 @@ "Couldn't apply the suggested change": "无法应用建议的更改", "Couldn't resolve the thread": "无法解决讨论串", "Could not close comparison": "无法关闭比较窗口", - "Could not open comparison": "无法打开比较窗口", "Could not show diff": "无法显示差异", "Comparison actions": "比较操作", "Back to Changed Files": "返回更改文件列表",