From 6fbbab6c6f6d2afe9f2d0b2068886bfa3e4969fa Mon Sep 17 00:00:00 2001 From: LU XIANGRUI <1078666705@qq.com> Date: Fri, 4 Dec 2026 03:00:01 +0900 Subject: [PATCH] fix(vcs): show the file's diff to the right of file history (#7744) Fixes #6406 Git > Show History for a file now keeps the revisions and their commit details on the left (details below the revisions) and shows the selected revision's diff of that file on the right. Directory history keeps the repository log layout. The diff follows Show Diff Preview and file history's own Diff Preview Location (Right by default; Bottom puts it below; Editor leaves it out and Show Diff opens a tab). The split is remembered per location. The details pane's change loading and preview are shared with the new pane, and the rename-aware matching of the history file's changes moved to historyFileChanges so Show Diff and the pane agree. Co-authored-by: wildcatDownstairs <26499420+wildcatDownstairs@users.noreply.github.com> --- e2e/gitFileHistoryLayout.spec.ts | 8 +- src/features/vcs/GitLog.tsx | 66 ++++-- .../vcs/__tests__/fileHistoryLayout.test.tsx | 215 ++++++++++++++++++ src/features/vcs/log/CommitDetails.tsx | 170 +++++++------- .../vcs/log/FileHistoryDiffPreview.tsx | 57 +++++ src/features/vcs/logChanges.ts | 18 ++ src/features/vcs/logOptions.ts | 15 +- src/features/vcs/logPaneActions.ts | 14 +- 8 files changed, 450 insertions(+), 113 deletions(-) create mode 100644 src/features/vcs/__tests__/fileHistoryLayout.test.tsx create mode 100644 src/features/vcs/log/FileHistoryDiffPreview.tsx diff --git a/e2e/gitFileHistoryLayout.spec.ts b/e2e/gitFileHistoryLayout.spec.ts index 55e8c9b96f..c8d3d0e65c 100644 --- a/e2e/gitFileHistoryLayout.spec.ts +++ b/e2e/gitFileHistoryLayout.spec.ts @@ -1,6 +1,6 @@ import { expect, stubDesktop, test } from "./fixtures"; -test("file history puts commit details below the revisions and keeps directory history in the log layout", async ({ +test("file history puts commit details below the revisions, the file's diff to the right, and keeps directory history in the log layout", async ({ workbench: page, }) => { await page.setViewportSize({ width: 1100, height: 760 }); @@ -59,6 +59,11 @@ test("file history puts commit details below the revisions and keeps directory h const newest = revisions.getByRole("option", { name: /Update the reviewed totals/ }); await expect(newest).toBeVisible(); await expect(separator).toHaveAttribute("aria-orientation", "horizontal"); + // IDEA's file history: the file's diff to the right of the revisions and their details. + const diffSeparator = page.getByRole("separator", { name: "Diff", exact: true }); + await expect(diffSeparator).toHaveAttribute("aria-orientation", "vertical"); + const diffEdge = (await diffSeparator.boundingBox())!.x; + expect((await revisions.boundingBox())!.x + (await revisions.boundingBox())!.width).toBeLessThanOrEqual(diffEdge + 1); await expect(page.getByRole("toolbar", { name: "Branches", exact: true })).toHaveCount(0); await expect(page.getByRole("button", { name: "Show Branches", exact: true })).toHaveCount(0); @@ -87,6 +92,7 @@ test("file history puts commit details below the revisions and keeps directory h await expect(git.getByRole("tab", { name: /History: src/ })).toHaveAttribute("aria-selected", "true"); await expect(page.getByRole("toolbar", { name: "Branches", exact: true })).toBeVisible(); await expect(separator).toHaveCount(0); + await expect(diffSeparator).toHaveCount(0); await historyTab.click(); await expect(earlier).toHaveAttribute("aria-selected", "true"); diff --git a/src/features/vcs/GitLog.tsx b/src/features/vcs/GitLog.tsx index 59eac7d554..bb9f4a720e 100644 --- a/src/features/vcs/GitLog.tsx +++ b/src/features/vcs/GitLog.tsx @@ -23,8 +23,9 @@ import styles from "./GitLog.module.css"; import { WorktreesPanel } from "./WorktreesPanel"; import { gitTabs, shownTab } from "./gitTabs"; import { BranchesPanel } from "./log/BranchesPanel"; -import { CommitDetails } from "./log/CommitDetails"; +import { CommitDetails, useDiffLocation } from "./log/CommitDetails"; import { CommitList } from "./log/CommitList"; +import { FileHistoryDiffPreview } from "./log/FileHistoryDiffPreview"; import { FilterBar } from "./log/FilterBar"; import { useLogRepositories, useReadOnlyLog } from "./log/logHooks"; import { PANE_STYLE } from "./log/shared"; @@ -157,6 +158,10 @@ export function LogView() { const comparison = useGitLog((s) => !!s.logTabs.find((t) => t.id === (scope ?? s.shownLog))?.comparison); const showBranches = useLogOptions((s) => s.showBranches) && !comparison; const showDetails = useLogOptions((s) => s.showDetails); + // IDEA's file history shows the file's diff beside the revisions; "Editor" opens it in a tab instead. + const diffPreview = useLogOptions((s) => s.diffPreview); + const diffLocation = useDiffLocation(true); + const historyDiff = diffPreview && diffLocation !== "editor" ? diffLocation : null; const historyPath = useGitLog((s) => { const tab = s.logTabs.find((t) => t.id === (scope ?? s.shownLog)); return tab?.kind === "history" && stripSlash(tab.target) !== tab.repo ? tab.target : null; @@ -260,27 +265,46 @@ export function LogView() { if (historyPath && historyPath === filePath) return ( -
- - - - - - {showDetails && ( - <> - - - + // Its own layout per preview location, so each keeps its sizes (IDEA: vcs.history.diff.splitter.proportion). + + +
+ + + + - - )} - -
+ {showDetails && ( + <> + + + + + + )} +
+
+ + {historyDiff && ( + <> + + + + + + )} + ); return ( diff --git a/src/features/vcs/__tests__/fileHistoryLayout.test.tsx b/src/features/vcs/__tests__/fileHistoryLayout.test.tsx new file mode 100644 index 0000000000..56691d3034 --- /dev/null +++ b/src/features/vcs/__tests__/fileHistoryLayout.test.tsx @@ -0,0 +1,215 @@ +import { render, screen, waitFor, within } from "@testing-library/react"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +const api = vi.hoisted(() => ({ + kind: "file" as "file" | "dir", + files: [{ path: "main.go", kind: "modified", oldPath: null }] as Array<{ + path: string; + kind: string; + oldPath: string | null; + }>, + commit: (id: string) => ({ + id, + shortId: id, + parents: [] as string[], + refs: [] as string[], + author: "Author", + email: "a@example.com", + summary: id, + message: id, + timeMs: 0, + }), +})); +vi.mock("@/platform/ipc", async (original) => { + const real = await original(); + const ok = (data: T) => Promise.resolve({ status: "ok" as const, data }); + return { + ...real, + commands: { + ...real.commands, + fsEntryKind: () => ok(api.kind), + vcsLog: () => ok([api.commit("tip"), api.commit("base")]), + vcsLogRefs: () => ok({}), + vcsBranches: () => ok([]), + vcsTags: () => ok([]), + vcsBranchInfo: () => ok({ upstream: null }), + vcsConfigGet: () => ok(null), + vcsCommitFiles: () => ok(api.files), + vcsLogDetails: () => ok({ message: "tip", containingBranches: ["main"] }), + vcsDiffNumstat: () => ok([]), + }, + }; +}); +// The diff itself is the DiffEditor's business: show which file it was given. +vi.mock("../DiffEditor", () => ({ + DiffEditor: ({ input }: { input: { path: string } }) =>
{input.path}
, +})); + +import { LogView } from "../GitLog"; +import { LogScope } from "../LogScope"; +import { historyFileChanges } from "../logChanges"; +import { DEFAULT_LOG_OPTIONS, type DiffLocation, parseLogOptions, useLogOptions } from "../logOptions"; +import { emptyFilters, useGitLog } from "../logStore"; +import { useVcs } from "../store"; + +const TAB = "history:/repo/main.go"; + +async function openHistory(target: string, selection = ["/repo\0tip"]) { + useGitLog.setState({ + shownLog: TAB, + tab: TAB, + logTabs: [{ id: TAB, kind: "history", target, repo: "/repo" }], + commits: [ + { ...api.commit("tip"), repo: "/repo" }, + { ...api.commit("base"), repo: "/repo" }, + ], + done: true, + filters: { ...emptyFilters(), path: target }, + selection, + selected: selection[0] ?? null, + loading: false, + generation: useGitLog.getState().generation + 1, + }); + render( + + + , + ); + const list = await screen.findByRole("listbox", { name: "Commits" }); + await waitFor(() => expect(within(list).getAllByRole("option")).toHaveLength(2)); +} + +const panel = (id: string) => document.querySelector(`[data-panel][id="${id}"]`); + +/** The panels of the group `id` sits in, and its orientation (`aria-orientation` of its separator). */ +function splitAround(id: string) { + const group = panel(id)?.parentElement; + const children = [...(group?.children ?? [])]; + return { + panels: children.filter((el) => el.hasAttribute("data-panel")).map((el) => el.id), + orientation: children.find((el) => el.getAttribute("role") === "separator")?.getAttribute("aria-orientation"), + }; +} + +const withPreview = (historyDiffLocation: DiffLocation, diffPreview = true) => + useLogOptions.setState({ historyDiffLocation, diffPreview }); + +beforeEach(() => { + api.kind = "file"; + api.files = [{ path: "main.go", kind: "modified", oldPath: null }]; + localStorage.clear(); + useVcs.setState({ + root: "/repo", + repo: "/repo", + roots: ["/repo"], + available: true, + branchesLoaded: true, + branches: [], + branch: { head: "main", headCommit: "tip", upstream: null, ahead: 0, behind: 0, operation: null }, + }); + useLogOptions.setState({ ...DEFAULT_LOG_OPTIONS, showBranches: false, showDetails: true }); +}); + +afterEach(() => { + useGitLog.setState({ shownLog: "log", tab: "log", logTabs: [], commits: [], selection: [], selected: null }); +}); + +describe("file history layout", () => { + it("keeps the commit details below the revisions", async () => { + await openHistory("/repo/main.go"); + await waitFor(() => expect(panel("details")).toBeTruthy()); + // A horizontal separator divides stacked panels. + expect(splitAround("revisions")).toEqual({ panels: ["revisions", "details"], orientation: "horizontal" }); + }); + + it("shows the selected revision's diff of the file to the right", async () => { + withPreview("right"); + await openHistory("/repo/main.go"); + expect(splitAround("history")).toEqual({ panels: ["history", "diff"], orientation: "vertical" }); + expect(await within(panel("diff")!).findByTestId("file-diff")).toHaveTextContent("main.go"); + // The revisions and their details stay together on the left. + expect(panel("history")!.contains(panel("details"))).toBe(true); + // No second preview inside the details. + expect(panel("preview")).toBeNull(); + }); + + it("puts the diff below the history with the Bottom location", async () => { + withPreview("bottom"); + await openHistory("/repo/main.go"); + expect(splitAround("history")).toEqual({ panels: ["history", "diff"], orientation: "horizontal" }); + expect(await within(panel("diff")!).findByTestId("file-diff")).toHaveTextContent("main.go"); + }); + + it("shows the diff to the right by default, whatever the repository log's preview location", async () => { + useLogOptions.setState({ diffLocation: "editor" }); + await openHistory("/repo/main.go"); + expect(splitAround("history")).toEqual({ panels: ["history", "diff"], orientation: "vertical" }); + expect(await within(panel("diff")!).findByTestId("file-diff")).toHaveTextContent("main.go"); + }); + + it.each<[string, DiffLocation, boolean]>([ + ["the Editor location", "editor", true], + ["the diff preview off", "right", false], + ])("leaves the diff out of the history with %s", async (_, location, on) => { + withPreview(location, on); + await openHistory("/repo/main.go"); + expect(panel("diff")).toBeNull(); + expect(splitAround("revisions").panels).toEqual(["revisions", "details"]); + }); + + it("says the revision did not change the file", async () => { + withPreview("right"); + api.files = [{ path: "README.md", kind: "modified", oldPath: null }]; + await openHistory("/repo/main.go"); + expect(await within(panel("diff")!).findByText("No changes")).toBeTruthy(); + }); + + it("asks for a single revision when several are selected", async () => { + withPreview("right"); + await openHistory("/repo/main.go", ["/repo\0tip", "/repo\0base"]); + expect(within(panel("diff")!).getByText("Select a commit to view changes")).toBeTruthy(); + }); + + it("restores the sizes saved for the diff split", async () => { + withPreview("right"); + localStorage.setItem("openidea.vcs.fileHistoryDiffSplit.right", JSON.stringify({ history: 45, diff: 55 })); + await openHistory("/repo/main.go"); + await waitFor(() => expect(panel("diff")!.style.flexGrow).toBe("55")); + }); + + it("keeps directory history on the repository log layout", async () => { + withPreview("right"); + api.kind = "dir"; + await openHistory("/repo/src"); + await waitFor(() => expect(panel("commits")).toBeTruthy()); + expect(panel("revisions")).toBeNull(); + expect(panel("diff")).toBeNull(); + }); +}); + +describe("historyFileChanges", () => { + const changes = [ + { path: "src/new.go", oldPath: "src/old.go" }, + { path: "README.md", oldPath: null }, + ]; + it("finds the file by its current name or the name it had at that revision", () => { + const commit = { ...api.commit("tip"), repo: "/repo" }; + expect(historyFileChanges(commit, "/repo/src/new.go", changes)).toEqual([changes[0]]); + expect(historyFileChanges({ ...commit, historyPath: "src/old.go" }, "/repo/src/renamed.go", changes)).toEqual([ + changes[0], + ]); + expect(historyFileChanges(commit, "/repo/main.go", changes)).toEqual([]); + }); +}); + +describe("file history diff location option", () => { + it("defaults to Right and keeps a saved location apart from the repository log's", () => { + expect(parseLogOptions({}).historyDiffLocation).toBe("right"); + expect(parseLogOptions({ diffLocation: "bottom" }).historyDiffLocation).toBe("right"); + expect(parseLogOptions({ historyDiffLocation: "editor" })).toMatchObject({ + historyDiffLocation: "editor", + diffLocation: "editor", + }); + expect(parseLogOptions({ historyDiffLocation: "left" }).historyDiffLocation).toBe("right"); + }); +}); diff --git a/src/features/vcs/log/CommitDetails.tsx b/src/features/vcs/log/CommitDetails.tsx index 6ca7f7cb5a..bd6118db04 100644 --- a/src/features/vcs/log/CommitDetails.tsx +++ b/src/features/vcs/log/CommitDetails.tsx @@ -1,4 +1,4 @@ -import type { ChangedFile, Commit, LinkTarget } from "@/bindings"; +import type { ChangedFile, Commit, LinkTarget, VcsKind } from "@/bindings"; import { executeAction } from "@/platform/actions"; import { setContext } from "@/platform/context"; import { tx } from "@/platform/i18n"; @@ -54,10 +54,10 @@ import { type LogChange, } from "../logChanges"; import { LogIdContext } from "../logContext"; -import { logOptions, useLogOptions } from "../logOptions"; +import { logOptions, useLogOptions, type DiffLocation } from "../logOptions"; import { openLogTab, updateLogOptions, useGitLog } from "../logStore"; import { KIND_COLOR, dirName, fileCount, renameFrom, type EffectiveKind } from "../model"; -import { commitKey, commitRepo } from "../multiRoot"; +import { commitKey, commitRepo, type RepoCommit } from "../multiRoot"; import { currentRepo, repoName, useVcsKind } from "../store"; import { CommitMessage } from "./CommitMessage"; import { useDropdownMenu, useReadOnlyLog } from "./logHooks"; @@ -86,6 +86,89 @@ function keyPrefixed(nodes: readonly FileTreeNode[], prefix: string): File return nodes.map((n) => ({ ...n, key: `${prefix}${n.key}`, children: keyPrefixed(n.children, prefix) })); } +/** The changed files of the chosen commits, as the details pane lists them. */ +export async function loadLogChanges( + chosen: readonly RepoCommit[], + opts: { + kind: VcsKind; + commitRoot: string | null | undefined; + readOnly: boolean; + fromParents: boolean; + parentIndex: number; + }, +): Promise { + const { kind, commitRoot, readOnly, fromParents, parentIndex } = opts; + const many = chosen.length > 1; + if (many || kind === "subversion") { + const roots = [...new Set(chosen.map(commitRepo))]; + return ( + await Promise.all( + roots.map(async (repo) => { + const group = chosen.filter((c) => commitRepo(c) === repo); + const files = await call(commands.vcsCommitsChanges(repo ?? currentRepo(), group.map((c) => c.id).reverse())); + return toLogChanges(files, null, repo, readOnly); + }), + ) + ).flat(); + } + const c = chosen[0]!; + if (c.parents.length > 1) { + const groups = await Promise.all( + c.parents.map(async (id) => { + const files = await call(commands.vcsDiffRevisions(commitRoot ?? currentRepo(), id, c.id)); + return toLogChanges(files, { ...c, parents: [id] }, commitRoot, readOnly); + }), + ); + // A merge's combined changes are files changed against every parent. + const merged = groups[0]! + .filter((f) => groups.every((group) => group.some((x) => x.path === f.path))) + .map((f) => ({ + ...f, + mergeParents: c.parents + .slice(0, 2) + .map((rev, i) => ({ rev, path: groups[i]!.find((x) => x.path === f.path)?.oldPath ?? f.path })), + })); + if (!fromParents) return merged; + // IDEA's Show Changes to Parents: the merge's own changes, then "Changes to " for each parent. + return [ + ...merged, + ...groups.flatMap((files, index) => + parentIndex < 0 || parentIndex === index ? files.map((f) => ({ ...f, group: c.parents[index]! })) : [], + ), + ]; + } + const files = await call(commands.vcsCommitFiles(commitRoot ?? currentRepo(), c.id)); + return toLogChanges(files, c, commitRoot, readOnly); +} + +/** Where the diff preview shows. The modal commit interface keeps diffs out of editor tabs (#1863): the "Editor" preview shows beside the changes instead. */ +export function useDiffLocation(fileHistory = false): DiffLocation { + const saved = useLogOptions((s) => (fileHistory ? s.historyDiffLocation : s.diffLocation)); + const modal = useWorkflowSettings((s) => !s.vcs.commit.nonModal); + return modal && saved === "editor" ? "right" : saved; +} + +/** The diff of one changed file, as the embedded preview shows it. */ +export function ChangePreview({ change }: { change: LogChange | undefined }) { + if (!change) + return ( + + Select a file to preview its changes + + ); + if (change.mergeParents?.length === 2 && change.after) + return ( + + ); + return ; +} + /** * The selected commits' changes: one commit's files against its first parent, or, for several * (IDEA), their combined changes with every selected commit listed below. @@ -118,11 +201,9 @@ export function CommitDetails({ commits, fileHistory = false }: { commits: Commi const fromParents = useLogOptions((s) => s.changesFromParents); const onlyAffected = useLogOptions((s) => s.showOnlyAffected); const preview = useLogOptions((s) => s.diffPreview); - const savedLocation = useLogOptions((s) => s.diffLocation); - // The modal commit interface keeps diffs out of editor tabs (#1863): the "Editor" - // preview shows beside the changes instead. - const modal = useWorkflowSettings((s) => !s.vcs.commit.nonModal); - const diffLocation = modal && savedLocation === "editor" ? "right" : savedLocation; + const locationKey = fileHistory ? "historyDiffLocation" : "diffLocation"; + const savedLocation = useLogOptions((s) => s[locationKey]); + const diffLocation = useDiffLocation(fileHistory); const showLineStats = useLogOptions((s) => s.showLineStats); const filters = useGitLog((s) => s.filters); const filesKey = JSON.stringify([idsKey, fromParents, parentIndex, commitRoot, kind, showLineStats]); @@ -132,50 +213,7 @@ export function CommitDetails({ commits, fileHistory = false }: { commits: Commi useEffect(() => { if (!idsKey) return; let alive = true; - const load = (async () => { - if (many || kind === "subversion") { - const roots = [...new Set(chosen.map(commitRepo))]; - return ( - await Promise.all( - roots.map(async (repo) => { - const group = chosen.filter((c) => commitRepo(c) === repo); - const files = await call( - commands.vcsCommitsChanges(repo ?? currentRepo(), group.map((c) => c.id).reverse()), - ); - return toLogChanges(files, null, repo, readOnly); - }), - ) - ).flat(); - } - const c = chosen[0]!; - if (c.parents.length > 1) { - const groups = await Promise.all( - c.parents.map(async (id) => { - const files = await call(commands.vcsDiffRevisions(commitRoot ?? currentRepo(), id, c.id)); - return toLogChanges(files, { ...c, parents: [id] }, commitRoot, readOnly); - }), - ); - // A merge's combined changes are files changed against every parent. - const merged = groups[0]! - .filter((f) => groups.every((group) => group.some((x) => x.path === f.path))) - .map((f) => ({ - ...f, - mergeParents: c.parents - .slice(0, 2) - .map((rev, i) => ({ rev, path: groups[i]!.find((x) => x.path === f.path)?.oldPath ?? f.path })), - })); - if (!fromParents) return merged; - // IDEA's Show Changes to Parents: the merge's own changes, then "Changes to " for each parent. - return [ - ...merged, - ...groups.flatMap((files, index) => - parentIndex < 0 || parentIndex === index ? files.map((f) => ({ ...f, group: c.parents[index]! })) : [], - ), - ]; - } - const files = await call(commands.vcsCommitFiles(commitRoot ?? currentRepo(), c.id)); - return toLogChanges(files, c, commitRoot, readOnly); - })(); + const load = loadLogChanges(chosen, { kind, commitRoot, readOnly, fromParents, parentIndex }); load .then((files) => (showLineStats ? withLineStats(files).catch(() => files) : files)) .then((files) => alive && setResult({ key: filesKey, files, error: null })) @@ -347,7 +385,7 @@ export function CommitDetails({ commits, fileHistory = false }: { commits: Commi submenu: (["editor", "right", "bottom"] as const).map((location) => ({ label: location === "editor" ? "Editor" : location === "right" ? "Right" : "Bottom", checked: savedLocation === location, - run: () => updateLogOptions({ diffLocation: location }), + run: () => updateLogOptions({ [locationKey]: location }), })), }, ]); @@ -534,7 +572,8 @@ export function CommitDetails({ commits, fileHistory = false }: { commits: Commi )} ); - const embedded = preview && diffLocation !== "editor"; + // File history shows its file's diff beside the whole history instead (FileHistoryDiffPreview). + const embedded = preview && diffLocation !== "editor" && !fileHistory; const selectedChange = chosenChanges.length === 1 ? chosenChanges[0] : undefined; return (
@@ -550,28 +589,7 @@ export function CommitDetails({ commits, fileHistory = false }: { commits: Commi - {selectedChange ? ( - selectedChange.mergeParents?.length === 2 && selectedChange.after ? ( - - ) : ( - - ) - ) : ( - - Select a file to preview its changes - - )} + ) : ( diff --git a/src/features/vcs/log/FileHistoryDiffPreview.tsx b/src/features/vcs/log/FileHistoryDiffPreview.tsx new file mode 100644 index 0000000000..17c020d09f --- /dev/null +++ b/src/features/vcs/log/FileHistoryDiffPreview.tsx @@ -0,0 +1,57 @@ +import type { Commit } from "@/bindings"; +import { EmptyState, Spinner, T } from "@/ui"; +import { useEffect, useState } from "react"; +import styles from "../GitLog.module.css"; +import { historyFileChanges, type LogChange } from "../logChanges"; +import { useGitLog } from "../logStore"; +import { commitKey, commitRepo } from "../multiRoot"; +import { useVcsKind } from "../store"; +import { ChangePreview, loadLogChanges } from "./CommitDetails"; +import { useReadOnlyLog } from "./logHooks"; + +/** + * IDEA's file history diff preview (FileHistoryPanel's FrameDiffPreview): the selected + * revision's change to the file, beside the revisions and their details. + */ +export function FileHistoryDiffPreview({ commits, target }: { commits: Commit[]; target: string }) { + const selection = useGitLog((s) => s.selection); + const commit = selection.length === 1 ? commits.find((c) => commitKey(c) === selection[0]) : undefined; + const commitRoot = commit ? commitRepo(commit) : null; + const kind = useVcsKind(commitRoot); + const readOnly = useReadOnlyLog(); + const key = commit ? `${commitKey(commit)}\0${kind}\0${target}` : null; + const [result, setResult] = useState<{ key: string; change?: LogChange; error?: string } | null>(null); + + useEffect(() => { + if (!commit || !key) return; + let alive = true; + loadLogChanges([commit], { kind, commitRoot, readOnly, fromParents: false, parentIndex: -1 }) + .then((all) => alive && setResult({ key, change: historyFileChanges(commit, target, all)[0] })) + .catch((e: unknown) => alive && setResult({ key, error: e instanceof Error ? e.message : String(e) })); + return () => { + alive = false; + }; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [key]); + + if (!commit) + return ( + + Select a commit to view changes + + ); + if (result?.key !== key) + return ( +
+ +
+ ); + if (result.error) return
{result.error}
; + if (!result.change) + return ( + + No changes + + ); + return ; +} diff --git a/src/features/vcs/logChanges.ts b/src/features/vcs/logChanges.ts index 3ba9b60d45..4ac4ad37e6 100644 --- a/src/features/vcs/logChanges.ts +++ b/src/features/vcs/logChanges.ts @@ -8,6 +8,7 @@ import type { ChangedFile, Commit, FileLineStats, LinkTarget, RevisionChange } f import { call, commands } from "@/platform/ipc"; import { editorService } from "@/workbench/contributions"; import { tx } from "@/platform/i18n"; +import { relativePath } from "@/platform/project"; import { workflowSettings } from "@/platform/workflowSettings"; import { combinedOf } from "./allInOneDiff"; import { @@ -483,3 +484,20 @@ export async function applySelectedChanges(changes: readonly LogChange[]) { ); if (outcome) await reportApply(outcome, tx("Changes applied")); } + +/** The changes of `commit` to the file whose history shows `target` (its name at that revision, after a rename). */ +export function historyFileChanges>( + commit: Commit & { repo?: string | null; historyPath?: string | null }, + target: string, + changes: readonly T[], +): T[] { + const root = commitRepo(commit) ?? currentRepoRoot(); + const targetPath = root ? relativePath(root, target) : target; + const historyPath = typeof commit.historyPath === "string" ? commit.historyPath : null; + return changes.filter( + (change) => + change.path === targetPath || + change.oldPath === targetPath || + (historyPath !== null && (change.path === historyPath || change.oldPath === historyPath)), + ); +} diff --git a/src/features/vcs/logOptions.ts b/src/features/vcs/logOptions.ts index ecb2338368..a56277d18b 100644 --- a/src/features/vcs/logOptions.ts +++ b/src/features/vcs/logOptions.ts @@ -8,6 +8,8 @@ import { LogOptionsContext } from "./logContext"; export type LogSort = "date" | "topo" | "standard"; +export type DiffLocation = "editor" | "right" | "bottom"; + export interface LogOptions { sort: LogSort; firstParent: boolean; @@ -42,7 +44,9 @@ export interface LogOptions { showRepository: boolean; showOnlyAffected: boolean; changesFromParents: boolean; - diffLocation: "editor" | "right" | "bottom"; + diffLocation: DiffLocation; + /** File history keeps its own location (IDEA's FileHistoryUiProperties): its file's diff beside the revisions. */ + historyDiffLocation: DiffLocation; columnOrder: string[]; columnWidths: Record; linearizeMerges: boolean; @@ -78,6 +82,7 @@ export const DEFAULT_LOG_OPTIONS: LogOptions = { showOnlyAffected: false, changesFromParents: false, diffLocation: "editor", + historyDiffLocation: "right", columnOrder: ["author", "date", "hash"], columnWidths: {}, linearizeMerges: false, @@ -99,6 +104,7 @@ const APPLICATION_LOG_OPTION_KEYS = [ "diffPreview", "changesFromParents", "diffLocation", + "historyDiffLocation", "columnOrder", ] as const satisfies readonly (keyof LogOptions)[]; @@ -112,9 +118,10 @@ export function parseLogOptions(raw: unknown): LogOptions { for (const k of Object.keys(out) as Array) { if (k === "sort") out.sort = o.sort === "standard" || o.sort === "topo" || o.sort === "date" ? o.sort : DEFAULT_LOG_OPTIONS.sort; - else if (k === "diffLocation") - out.diffLocation = o.diffLocation === "right" || o.diffLocation === "bottom" ? o.diffLocation : "editor"; - else if (k === "columnOrder") + else if (k === "diffLocation" || k === "historyDiffLocation") { + const v = o[k]; + out[k] = v === "editor" || v === "right" || v === "bottom" ? v : DEFAULT_LOG_OPTIONS[k]; + } else if (k === "columnOrder") out.columnOrder = Array.isArray(o.columnOrder) ? [...new Set(o.columnOrder.filter((v): v is string => typeof v === "string"))] : [...DEFAULT_LOG_OPTIONS.columnOrder]; diff --git a/src/features/vcs/logPaneActions.ts b/src/features/vcs/logPaneActions.ts index 39a692bc83..85a28670a1 100644 --- a/src/features/vcs/logPaneActions.ts +++ b/src/features/vcs/logPaneActions.ts @@ -6,7 +6,6 @@ import { create } from "zustand"; import { gateByVcsKind } from "./vcsKind"; import type { Branch, Commit } from "@/bindings"; import { executeAction, registerActions, type Action } from "@/platform/actions"; -import { relativePath } from "@/platform/project"; import { notifications, toolWindowService } from "@/workbench/contributions"; import { deleteBranches, @@ -24,6 +23,7 @@ import { changesArg, compareChangesWithLocal, getFromRevision, + historyFileChanges, openChangeSource, revertSelectedChanges, showChangesDiff, @@ -32,7 +32,7 @@ import { } from "./logChanges"; import { logOptions } from "./logOptions"; import { goToRef, selectedCommits, toggleCherryHighlight, updateLogOptions, useGitLog } from "./logStore"; -import { commitKey, commitRepo } from "./multiRoot"; +import { commitKey } from "./multiRoot"; import { dropSelectedChanges, extractSelectedChanges } from "./rebase"; import { copyLogChangesAsPatch, showCreatePatchForLogChanges } from "./patches"; import { openRevisionFile } from "./revisionInput"; @@ -68,15 +68,7 @@ function showFocusedHistoryDiff() { return; } - const root = commitRepo(commit) ?? currentRepoRoot(); - const targetPath = root ? relativePath(root, tab.target) : tab.target; - const historyPath = "historyPath" in commit && typeof commit.historyPath === "string" ? commit.historyPath : null; - const relevant = changes.all.filter( - (change) => - change.path === targetPath || - change.oldPath === targetPath || - (historyPath !== null && (change.path === historyPath || change.oldPath === historyPath)), - ); + const relevant = historyFileChanges(commit, tab.target, changes.all); if (relevant.length) void showChangesDiff(relevant, false, relevant); }