fix(vcs): show the focused view's diff for Show Diff and Show Diff in New Window (#6752)

With a key bound to Show Diff in New Window, the Compare tool window opened an empty diff: the diff actions could not ask the focused view what it shows, so they diffed the Project view's or the editor's file against HEAD, and the shelf, stash, patch and review trees only claimed Show Diff's own key. Views now register a diff source on their element (diffSource.ts) and both diff actions ask the one around the focused element first, whatever runs them (shortcut, menu, Find Action). Covered: Compare trees (tool window, comparison window, Push, rebase plan), shelf checklist and panel, Stash view and Unstash dialog, Apply Patch list, Local Changes review dialog and the Git Log's changed files. A guessed file without local changes now shows "No local changes in X" instead of an empty diff.

Fixes #6751

Co-authored-by: albince-mi <[email protected]>
Цей коміт міститься в:
Albince Paliakkara authored and GitHub committed 2026-11-28 23:10:17 +08:00
1 джерело 9aa0718cf9
коміт 633bef2e69
19 files changed
+514 -128

No files matched your search

+31 -2
Переглянути файл
@@ -1,6 +1,7 @@
import { useState, type ReactNode } from "react";
import { useRef, useState, type ReactNode } from "react";
import { Icon, Tree, fileIconName, lazyComponent } from "@/ui";
import { diffInput, openVcsDiff, withChain, type DiffData } from "./diffInput";
import { useDiffSource } from "./diffSource";
import { dirKeys, type FileTreeNode } from "./fileTree";
import { filesUnder } from "./logChanges";
import styles from "./common.module.css";
@@ -38,6 +39,7 @@ export function ComparisonTree<F>({
onOpen,
inlineDiff = true,
openDiff = defaultOpenDiff,
onShowDiff,
}: {
tree: FileTreeNode<F>[];
current: F | null;
@@ -53,13 +55,40 @@ export function ComparisonTree<F>({
inlineDiff?: boolean;
/** With `openOnActivate`: where a double-clicked file's diff opens (default: an editor tab). */
openDiff?: (diff: DiffData) => void;
/**
* Show Diff on the tree's selection, as the owner's Show Diff button does. Without it the
* file's diff, with the tree's files as its chain, goes to `openDiff`. Show Diff in New
* Window opens that diff in a diff window either way (the tree is a {@link useDiffSource}).
*/
onShowDiff?: (file: F) => void;
}) {
const [selected, setSelected] = useState<ReadonlySet<string>>(new Set());
const root = useRef<HTMLDivElement>(null);
// The lead file, else the first file under the selected rows, else the tree's first file.
const pick = (): F | undefined => {
const all = filesUnder(tree);
return (current !== null && all.includes(current) ? current : undefined) ?? filesUnder(tree, selected)[0] ?? all[0];
};
useDiffSource(root, {
diff: () => {
const file = pick();
return file === undefined ? null : chainedDiff(tree, file, diffFor);
},
show: () => {
const file = pick();
if (file === undefined) return;
if (onShowDiff) return onShowDiff(file);
const diff = chainedDiff(tree, file, diffFor);
if (!diff) return;
openDiff(diff);
onOpen?.();
},
});
const [expanded, setExpanded] = useState<ReadonlySet<string> | null>(null);
const data = inlineDiff && current && diffFor(current);
const input = data ? diffInput(data) : null;
return (
<div className={`${styles.comparison} ${input ? styles.comparisonWithDiff : ""}`}>
<div ref={root} className={`${styles.comparison} ${input ? styles.comparisonWithDiff : ""}`}>
<Tree<FileTreeNode<F>>
roots={tree}
getKey={(n) => n.key}
+17 -16
Переглянути файл
@@ -5,7 +5,8 @@ import { Button, Dialog, Icon, IconButton, T, Tree, fileIconName, showContextMen
import { showRollbackDialog } from "./changeOps";
import { isNestedRepoEntry } from "./submoduleRollback";
import { groupOf, isPartiallyStaged } from "./changes";
import { workingDiffData, withChain } from "./diffInput";
import { workingDiffData, withChain, type DiffData } from "./diffInput";
import { useDiffSource } from "./diffSource";
import { openDialog } from "./dialogs";
import { dirKeys, type FileTreeNode } from "./fileTree";
import { filesUnder } from "./logChanges";
@@ -124,8 +125,9 @@ function LocalChangesReviewDialog({
Array.from(new Map(rows.flatMap(({ status }) => (status ? [[status.path, status] as const] : []))).values());
const chosen = uniqueChanges(picked.length ? picked : files.slice(0, 1));
const showDiff = (selection: readonly FileStatus[]) => {
if (!selection.length) return;
/** `selection`'s diff with the dialog's files as the chain; a partly staged file shows each side. */
const reviewDiff = (selection: readonly FileStatus[]): DiffData | null => {
if (!selection.length) return null;
const chain = selection.length > 1 ? selection : uniqueChanges(files);
const items = chain.flatMap((file) => {
const worktree = workingDiffData(file.path);
@@ -134,9 +136,13 @@ function LocalChangesReviewDialog({
return [{ ...staged, left: worktree.left }, workingDiffData(file.path, undefined, "unstaged")];
});
const index = items.findIndex((item) => item.path === selection[0]?.path);
if (index < 0) return;
return index < 0 ? null : withChain(items, index);
};
const showDiff = (selection: readonly FileStatus[]) => {
const diff = reviewDiff(selection);
if (!diff) return;
void import("./diffDialog").then(({ openDiffDialog }) => {
if (content.current?.isConnected) openDiffDialog(withChain(items, index));
if (content.current?.isConnected) openDiffDialog(diff);
});
};
@@ -152,19 +158,14 @@ function LocalChangesReviewDialog({
useEffect(() =>
registerKeyClaim((event, stroke) => {
if (rollingBack || !(event.target instanceof Node) || !content.current?.contains(event.target)) return false;
for (const [action, run] of [
["vcs.showDiff", () => showDiff(chosen)],
["vcs.rollback", () => void rollback()],
] as const) {
if (!bindingsFor(action).some((binding) => normalizeBinding(binding) === stroke)) continue;
event.preventDefault();
event.stopPropagation();
run();
return true;
}
return false;
if (!bindingsFor("vcs.rollback").some((binding) => normalizeBinding(binding) === stroke)) return false;
event.preventDefault();
event.stopPropagation();
void rollback();
return true;
}),
);
useDiffSource(content, rollingBack ? null : { diff: () => reviewDiff(chosen), show: () => showDiff(chosen) });
const blocked = files.length > 0;
const text = operationText[operation === "checkout" ? "checkout" : "merge"];
+14 -30
Переглянути файл
@@ -3,7 +3,6 @@ import type { Stash } from "@/bindings";
import { executeAction } from "@/platform/actions";
import { tx } from "@/platform/i18n";
import { call, commands } from "@/platform/ipc";
import { bindingsFor, normalizeBinding, registerKeyClaim } from "@/platform/keymap";
import { dirname } from "@/platform/project";
import { useWorkflowSettings } from "@/platform/workflowSettings";
import { Dialog, IconButton, Tree, fileIconName, showContextMenu } from "@/ui";
@@ -14,7 +13,8 @@ import { vcsDiffInFront } from "./diffInput";
import type { FileTreeNode } from "./fileTree";
import { canApplySelectedChanges, filesUnder, flatFileNodes, toLogChanges, type LogChange } from "./logChanges";
import { KIND_COLOR } from "./model";
import { focusStashDiff, showStashDiff, type StashDiffRequest } from "./stashDiff";
import { showStashDiff, stashDiffData, type StashDiffRequest } from "./stashDiff";
import { useDiffSource } from "./diffSource";
import styles from "./CommitView.module.css";
export type StashEntry = Stash & { repo: string | null };
@@ -61,7 +61,6 @@ export function StashChanges({ stash, dialogLifetime }: { stash: StashEntry; dia
const [files, setFiles] = useState<Awaited<ReturnType<typeof stashFiles>>>();
const [error, setError] = useState<string>();
const [selected, setSelected] = useState<ReadonlySet<string>>(new Set());
const [focused, setFocused] = useState(false);
const previewTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
const previewRequest = useRef<AbortController | null>(null);
const content = useRef<HTMLDivElement>(null);
@@ -100,25 +99,17 @@ export function StashChanges({ stash, dialogLifetime }: { stash: StashEntry; dia
const all = useMemo(() => filesUnder(roots), [roots]);
const selection = useMemo(() => filesUnder(roots, selected), [roots, selected]);
useEffect(() => {
const request = {
index: stash.index,
changes: selection.length ? selection : all,
chain: selection.length > 1 ? selection : all,
dialogLifetime,
};
if (dialogLifetime) {
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();
void executeAction("vcs.stash.showDiff", request);
return true;
});
}
if (focused) return focusStashDiff(request);
}, [focused, stash.index, selection, all, dialogLifetime]);
const request: StashDiffRequest = {
index: stash.index,
changes: selection.length ? selection : all,
chain: selection.length > 1 ? selection : all,
dialogLifetime,
};
useDiffSource(content, {
// The modal stash review compares with local, as its Show Diff does.
diff: () => stashDiffData(request, dialogLifetime ? "local" : target),
show: () => void executeAction("vcs.stash.showDiff", request),
});
const diffSelection = (changes: LogChange[]): StashDiffRequest => ({
index: stash.index,
@@ -133,14 +124,7 @@ export function StashChanges({ stash, dialogLifetime }: { stash: StashEntry; dia
};
return (
<div
ref={content}
className={styles.changes}
onFocusCapture={() => setFocused(true)}
onBlurCapture={(event) => {
if (!event.currentTarget.contains(event.relatedTarget)) setFocused(false);
}}
>
<div ref={content} className={styles.changes}>
<div className={styles.toolbar} role="toolbar" aria-label={tx("Changed files")}>
<IconButton
icon="diff"
+122 -1
Переглянути файл
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, cleanup, fireEvent, render, screen, within } from "@testing-library/react";
import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
const mocks = vi.hoisted(() => ({
worktree: vi.fn(),
@@ -7,7 +7,9 @@ const mocks = vi.hoisted(() => ({
presentations: vi.fn(),
openDiff: vi.fn(),
openFile: vi.fn(),
diffWindow: vi.fn(),
}));
vi.mock("../DiffWindow", () => ({ showDiffWindow: mocks.diffWindow }));
vi.mock("@/platform/ipc", async (original) => {
const real = await original<typeof import("@/platform/ipc")>();
return {
@@ -36,9 +38,13 @@ vi.mock("@/workbench/contributions", async (original) => {
const real = await original<typeof import("@/workbench/contributions")>();
return { ...real, maybeEditorService: () => ({ openFile: mocks.openFile }) };
});
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 { registerVcsActions } from "../actions";
import type { DiffData } from "../diffInput";
import { useVcs } from "../store";
@@ -284,3 +290,118 @@ describe("CompareToolWindow", () => {
);
});
});
// 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.
describe("the Compare trees' Show Diff shortcuts", () => {
const ctrlD = { key: "d", code: "KeyD", ctrlKey: true };
const cleanups: (() => void)[] = [];
const original = useKeymap.getState().overrides;
const bind = (overrides: Record<string, string[]>) =>
useKeymap.setState({ overrides: { ...original, "vcs.showDiff": [], "vcs.showDiffInNewWindow": [], ...overrides } });
/** Selects `name` in the tree and presses Ctrl+D with the focus on the tree. */
const pressOn = async (name: string) => {
fireEvent.mouseDown(await screen.findByText(name), { button: 0 });
const tree = screen.getByRole("tree", { name: "Changed files" });
tree.focus();
fireEvent.keyDown(tree, ctrlD);
};
beforeEach(() => {
vi.clearAllMocks();
useProject.setState({ project: { root: "/workspace", name: "workspace" } as never });
useVcs.setState({ available: true, root: "/workspace", roots: ["/workspace/client"], repo: "/workspace/client" });
setContext("vcsAvailable", true);
mocks.worktree.mockResolvedValue({
status: "ok",
data: [
modified,
{ path: "src/new.ts", kind: "added", oldPath: null, root: "/workspace/client", revision: "aaa" },
],
});
mocks.openDiff.mockResolvedValue(undefined);
useCompareTool.getState().show(from, null);
cleanups.push(registerVcsActions(), installKeyboardDispatcher());
});
afterEach(() => {
while (cleanups.length) cleanups.pop()!();
cleanup();
setContext("vcsAvailable", false);
useKeymap.setState({ overrides: original });
useCompareTool.getState().close();
useProject.setState({ project: null });
});
it("opens the compared sides of the selected file in a new window, not its diff against HEAD", async () => {
bind({ "vcs.showDiffInNewWindow": ["Ctrl+D"] });
render(<CompareToolWindow />);
await pressOn("app.ts");
await waitFor(() => expect(mocks.diffWindow).toHaveBeenCalledOnce());
const data = mocks.diffWindow.mock.calls[0]![0] as DiffData;
expect(data).toMatchObject({
path: "/workspace/client/src/app.ts",
left: { type: "rev", rev: "main", label: "main" },
right: { type: "worktree" },
});
expect(data.chain?.map((d) => d.path)).toEqual(["/workspace/client/src/app.ts", "/workspace/client/src/new.ts"]);
fireEvent.click(screen.getByRole("button", { name: "Swap Sides" }));
await pressOn("app.ts");
await waitFor(() => expect(mocks.diffWindow).toHaveBeenCalledTimes(2));
expect(mocks.diffWindow.mock.calls[1]![0]).toMatchObject({
left: { type: "worktree" },
right: { type: "rev", rev: "main" },
});
expect(mocks.openDiff).not.toHaveBeenCalled();
});
it("shows the selected file's comparison diff as the Show Diff button does", async () => {
bind({ "vcs.showDiff": ["Ctrl+D"] });
render(<CompareToolWindow />);
await pressOn("new.ts");
await waitFor(() => expect(mocks.openDiff).toHaveBeenCalledOnce());
expect(mocks.openDiff.mock.calls[0]![0]).toMatchObject({
path: "/workspace/client/src/new.ts",
left: { type: "text", label: "(does not exist)" },
right: { type: "worktree" },
});
expect(mocks.diffWindow).not.toHaveBeenCalled();
});
it("hands the comparison window's revisions to its Show Diff", async () => {
bind({ "vcs.showDiff": ["Ctrl+D"] });
mocks.revisions.mockResolvedValue({ status: "ok", data: [modified] });
const onShowDiff = vi.fn();
render(
<ChangesBetweenDialog
from={from}
to={{ rev: "next", label: "next" }}
onClose={() => {}}
onShowDiff={onShowDiff}
native
/>,
);
await pressOn("app.ts");
await waitFor(() =>
expect(onShowDiff).toHaveBeenCalledWith(
expect.objectContaining({
path: "/workspace/client/src/app.ts",
left: { type: "rev", rev: "main", label: "main", path: undefined },
right: { type: "rev", rev: "next", label: "next" },
}),
),
);
});
it("reaches the same diff when the action runs without a key (menu, Find Action)", async () => {
render(<CompareToolWindow />);
fireEvent.mouseDown(await screen.findByText("app.ts"), { button: 0 });
screen.getByRole("tree", { name: "Changed files" }).focus();
await executeAction("vcs.showDiffInNewWindow");
expect(mocks.diffWindow.mock.calls[0]![0]).toMatchObject({
path: "/workspace/client/src/app.ts",
left: { type: "rev", rev: "main" },
});
});
});
+67
Переглянути файл
@@ -0,0 +1,67 @@
import { afterEach, expect, it } from "vitest";
import { readdirSync, readFileSync, statSync } from "node:fs";
import { join } from "node:path";
import { focusedDiffSource, registerDiffSource, type DiffSource } from "../diffSource";
afterEach(() => {
document.body.innerHTML = "";
});
const view = () => {
const outer = document.createElement("div");
const inner = document.createElement("div");
const row = document.createElement("button");
inner.append(row);
outer.append(inner);
document.body.append(outer);
return { outer, inner, row };
};
it("answers with the innermost registered view around the focus, and nothing outside", () => {
const { outer, inner, row } = view();
const panel: DiffSource = { show: () => {} };
const tree: DiffSource = { show: () => {} };
const offPanel = registerDiffSource(outer, panel);
const offTree = registerDiffSource(inner, tree);
const elsewhere = document.createElement("button");
document.body.append(elsewhere);
row.focus();
expect(focusedDiffSource()).toBe(tree);
offTree();
expect(focusedDiffSource()).toBe(panel);
elsewhere.focus();
expect(focusedDiffSource()).toBeNull();
offPanel();
});
it("keeps a newer registration when an older one of the same element unregisters", () => {
const { outer, row } = view();
const first: DiffSource = { show: () => {} };
const second: DiffSource = { show: () => {} };
const offFirst = registerDiffSource(outer, first);
const offSecond = registerDiffSource(outer, second);
offFirst();
row.focus();
expect(focusedDiffSource()).toBe(second);
offSecond();
expect(focusedDiffSource()).toBeNull();
});
/** Source files under `dir`, tests excluded. */
function sources(dir: string): string[] {
return readdirSync(dir).flatMap((name) => {
const path = join(dir, name);
if (statSync(path).isDirectory()) return name === "__tests__" ? [] : sources(path);
return /\.tsx?$/.test(name) && !/\.test\.tsx?$/.test(name) ? [path] : [];
});
}
it("leaves the diff actions' keys to the keymap: views register a diff source instead", () => {
// A view claiming Show Diff's key misses a key the user bound to Show Diff in New Window,
// and menus and Find Action never pass through key claims.
const claims = sources(join(__dirname, "../../..")).filter((path) =>
/bindingsFor\(\s*"vcs\.(showDiff|showDiffInNewWindow)"\s*\)/.test(readFileSync(path, "utf8")),
);
expect(claims).toEqual([]);
});
+41 -2
Переглянути файл
@@ -2,12 +2,16 @@ 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 { setContext } from "@/platform/context";
import { installKeyboardDispatcher, primaryKeyBinding, useKeymap } from "@/platform/keymap";
import { registerVcsActions } from "../actions";
import { FileChecklist } from "../shelf";
import { useVcs } from "../store";
const openDiffDialog = vi.hoisted(() => vi.fn());
vi.mock("../diffDialog", () => ({ openDiffDialog }));
const showDiffWindow = vi.hoisted(() => vi.fn());
vi.mock("../DiffWindow", () => ({ showDiffWindow }));
const file = (rel: string): FileStatus => ({
path: `/repo/${rel}`,
@@ -66,10 +70,18 @@ it("checks or clears a directory's files at once and shows a partly included one
});
it("shows a file's diff on double-click and ⌘D, and toggles inclusion with the box and Space", async () => {
const off = installKeyboardDispatcher();
setContext("vcsAvailable", true);
const offActions = registerVcsActions();
const offKeys = installKeyboardDispatcher();
const off = () => {
offKeys();
offActions();
setContext("vcsAvailable", false);
};
try {
render(<Harness />);
const tree = screen.getByRole("tree", { name: "Files to shelve" });
tree.focus();
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" };
@@ -145,3 +157,30 @@ it("compares the index with the working copy when asked for the unstaged side",
),
);
});
it("opens the tree's diff when the user binds the key to Show Diff in New Window", async () => {
const original = useKeymap.getState().overrides;
useKeymap.setState({ overrides: { ...original, "vcs.showDiff": [], "vcs.showDiffInNewWindow": ["Ctrl+D"] } });
setContext("vcsAvailable", true);
const offActions = registerVcsActions();
const offKeys = installKeyboardDispatcher();
try {
render(<Harness />);
const tree = screen.getByRole("tree", { name: "Files to shelve" });
fireEvent.mouseDown(screen.getByText("pom.xml"), { button: 0 });
tree.focus();
fireEvent.keyDown(tree, { key: "d", code: "KeyD", ctrlKey: true });
await waitFor(() =>
expect(showDiffWindow).toHaveBeenCalledWith(
expect.objectContaining({ path: "/repo/pom.xml", left: { type: "rev", rev: "HEAD" } }),
expect.any(Function),
),
);
expect(openDiffDialog).not.toHaveBeenCalled();
} finally {
offKeys();
offActions();
setContext("vcsAvailable", false);
useKeymap.setState({ overrides: original });
}
});
+11 -5
Переглянути файл
@@ -33,7 +33,7 @@ vi.mock("@/ui", async (original) => ({
import { StashesPanel } from "../StashesPanel";
import { useProject } from "@/platform/project";
import { useCommit } from "../commitStore";
import { focusedStashDiff } from "../stashDiff";
import { focusedDiffSource } from "../diffSource";
import { useVcs } from "../store";
beforeEach(() => {
@@ -159,11 +159,17 @@ it("routes Show Diff to the selected stash file while its tree has focus", async
render(<StashesPanel />);
const file = await screen.findByText("app.ts");
const tree = screen.getByRole("tree", { name: "Changed files" });
fireEvent.focus(tree);
fireEvent.mouseDown(file, { button: 0 });
expect(focusedStashDiff()).toMatchObject({ index: 0, changes: [{ repo: "/p/front", after: "/p/front-stash" }] });
fireEvent.blur(tree, { relatedTarget: document.body });
expect(focusedStashDiff()).toBeNull();
tree.focus();
await focusedDiffSource()!.show!();
expect(action).toHaveBeenLastCalledWith("vcs.stash.showDiff", {
index: 0,
changes: [expect.objectContaining({ repo: "/p/front", after: "/p/front-stash" })],
chain: expect.any(Array),
dialogLifetime: undefined,
});
tree.blur();
expect(focusedDiffSource()).toBeNull();
});
it("passes a multi-file selection to diff, compare and apply actions", async () => {
+4
Переглянути файл
@@ -242,6 +242,10 @@ describe("shelf scope and diffs", () => {
expect(intellijMacos[action.id]).toEqual(["Meta+D"]);
expect(isActionKeyEnabled(action, { vcsAvailable: true, shelfFocus: true })).toBe(true);
expect(isActionKeyEnabled(action, { vcsAvailable: true, editorTextFocus: true })).toBe(false);
// The shelf panel is the diff source while the focus is inside it.
render(<ShelfPanel />);
await waitFor(() => expect(screen.getByText("Work")).toBeTruthy());
screen.getAllByRole("tree")[0]!.focus();
await action.run({ ctx: { shelfFocus: true } });
expect(mocks.openDiff).toHaveBeenCalledWith(expect.objectContaining({ path: "/repo/a.txt" }), { preview: true });
} finally {
+23
Переглянути файл
@@ -16,8 +16,10 @@ const diffWindow = vi.hoisted(() => vi.fn());
const separateWindow = vi.hoisted(() => vi.fn());
const project = vi.hoisted(() => ({ paths: [] as string[] }));
const active = vi.hoisted(() => ({ path: null as string | null }));
const notify = vi.hoisted(() => vi.fn());
vi.mock("@/workbench/contributions", async (original) => ({
...(await original<typeof import("@/workbench/contributions")>()),
notifications: () => ({ notify }),
editorService: () => ({ openInput: opened }),
maybeEditorService: () => (active.path ? { activePath: () => active.path } : undefined),
projectViewSelection: () => project.paths,
@@ -45,6 +47,7 @@ beforeEach(() => {
opened.mockClear();
diffWindow.mockClear();
separateWindow.mockClear();
notify.mockClear();
project.paths = [];
active.path = null;
setContext("activeToolWindow", "");
@@ -271,3 +274,23 @@ it.each<DiffData>([
await getAction("vcs.showDiffInNewWindow")!.run({ arg: data, ctx: { vcsAvailable: true } });
expect(separateWindow.mock.calls[0]![0]).toBe(data);
});
describe("a guessed file without local changes", () => {
// The diff actions guess the Project view's or the editor's file when no view around the
// focus has a diff of its own: an unchanged guess says so rather than open an empty diff.
it("tells Show Diff and Show Diff in New Window instead of opening an identical diff", async () => {
active.path = "/repo/clean.ts";
await getAction("vcs.showDiff")!.run({ arg: undefined, ctx: { vcsAvailable: true } });
await getAction("vcs.showDiffInNewWindow")!.run({ arg: undefined, ctx: { vcsAvailable: true } });
expect(opened).not.toHaveBeenCalled();
expect(separateWindow).not.toHaveBeenCalled();
expect(notify).toHaveBeenCalledTimes(2);
expect(notify).toHaveBeenLastCalledWith(expect.objectContaining({ title: "No local changes in /repo/clean.ts" }));
});
it("still opens a file the action is given, changed or not", async () => {
await getAction("vcs.showDiffInNewWindow")!.run({ arg: "/repo/clean.ts", ctx: { vcsAvailable: true } });
expect(separateWindow.mock.calls[0]![0]).toMatchObject({ path: "/repo/clean.ts" });
expect(notify).not.toHaveBeenCalled();
});
});
+1
Переглянути файл
@@ -195,6 +195,7 @@ it("reviews the selected stash against local files and returns to the unstash op
const binding = primaryKeyBinding("vcs.showDiff");
expect(binding).toMatch(/^(Meta|Ctrl)\+D$/);
fireEvent.mouseDown(file, { button: 0 });
tree.focus();
fireEvent.keyDown(tree, {
key: "d",
code: "KeyD",
+41 -6
Переглянути файл
@@ -1,4 +1,3 @@
import { showShelfDiff } from "./shelf";
import type { Stash } from "@/bindings";
import { commitRepo } from "./multiRoot";
/** VCS actions (ids match keymaps/intellij-macos.ts where bound). */
@@ -126,7 +125,9 @@ import {
stagingAreaOn,
} from "./staging";
import { stagingRange } from "./stagingRange";
import { focusedStashDiff, showStashDiff, type StashDiffRequest } from "./stashDiff";
import { showStashDiff, type StashDiffRequest } from "./stashDiff";
import { focusedDiffSource, type DiffSource } from "./diffSource";
import { displayPath } from "./compareData";
import { showStashChanges, type StashEntry } from "./StashChanges";
import { showSyncCommitsForCurrent } from "./SyncCommitsPopup";
import { tx } from "@/platform/i18n";
@@ -292,6 +293,34 @@ function selectedPaths(arg: unknown, project = projectViewSelection()): string[]
return project.length ? project : contextPaths(arg);
}
function notifySelectChangedFile() {
notifications().notify({ group: "vcs", level: "info", title: "Select a changed file to show its diff" });
}
/**
* A file the diff actions guessed (the Project view's or the editor's) that has no local
* changes: say so rather than open an empty diff against HEAD.
*/
function notifyNoLocalChanges(path: string) {
notifications().notify({ group: "vcs", level: "info", title: tx`No local changes in ${displayPath(path)}` });
}
/** Show Diff in the focused view: its own way, else its selection's diff in the editor. */
async function showSourceDiff(source: DiffSource) {
if (source.show) return source.show();
const data = await source.diff?.();
if (data) await openVcsDiff(data, { preview: true });
else notifySelectChangedFile();
}
/** Show Diff in New Window in the focused view; a view without a plain diff shows its own. */
async function showSourceDiffInNewWindow(source: DiffSource) {
const data = await source.diff?.();
if (data) showDiffWindow(data, () => void openDiff(data, { preview: true }));
else if (source.show) await source.show();
else notifySelectChangedFile();
}
/**
* Like {@link selectedPaths}, but the Project view's selection counts only while the tree has
* focus or owns the context: over the editor the active file wins.
@@ -786,9 +815,9 @@ export function registerVcsActions(): () => void {
// In the Git Log's changed files it shows the commit's diff instead.
keyWhen: "!editorTextFocus && !diffEditorFocus && !vcsLogChangesFocus && !vcsLogRevisionFocus",
run: async ({ arg, ctx }) => {
if (ctx.shelfFocus && arg === undefined) return showShelfDiff();
const stash = arg === undefined ? focusedStashDiff() : null;
if (stash) return showStashDiff(stash, workflowSettings().vcs.git.stashDiffTarget);
// A view with changes of its own (two revisions, a shelf, a stash) shows its selection.
const source = arg === undefined ? focusedDiffSource() : null;
if (source) return showSourceDiff(source);
if (arg === undefined && getContext().activeToolWindow === "commit") {
const { amend, amendPreview, groupByDir, selectionKeys } = useCommit.getState();
if (amend && amendPreview && selectionKeys.some((key) => key.startsWith("amend:"))) {
@@ -806,6 +835,7 @@ export function registerVcsActions(): () => void {
return;
}
if (await showDirectoryWorkingDiff(paths)) return;
if (arg === undefined && !paths.some((path) => statusOf(path))) return notifyNoLocalChanges(paths[0]!);
const tree = currentChangeTree();
// The selected rows while the tree has focus: a file under Staged or Unstaged diffs that side.
const targets = showDiffTargets(tree, paths, !argPaths(arg)?.length && commitWindowFocused());
@@ -841,8 +871,13 @@ export function registerVcsActions(): () => void {
keyWhen: "!editorTextFocus",
run: ({ arg, ctx }) => {
const requested = arg && typeof arg === "object" && "left" in arg && "right" in arg ? (arg as DiffData) : null;
// A view with changes of its own (two revisions, a shelf, a stash) shows its selection.
const source = arg === undefined ? focusedDiffSource() : null;
if (source) return showSourceDiffInNewWindow(source);
const viewed = requested ?? focusedDiffNavigator()?.viewer?.()?.data;
const path = focusedSelection(arg, ctx)[0];
const data = requested ?? focusedDiffNavigator()?.viewer?.()?.data ?? (path ? workingDiffData(path) : null);
if (!viewed && arg === undefined && path && !statusOf(path)) return notifyNoLocalChanges(path);
const data = viewed ?? (path ? workingDiffData(path) : null);
if (!data) {
notifications().notify({ group: "vcs", level: "info", title: "Select a changed file to show its diff" });
return;
+55
Переглянути файл
@@ -0,0 +1,55 @@
/**
* The diff of the focused view's selection, for Show Diff and Show Diff in New Window (IDEA's
* data context with `VcsDataKeys.CHANGES`).
*
* A view that lists changes of its own (two revisions, a shelf, a stash, a patch, a commit in the
* log) registers its element with {@link useDiffSource}. The diff actions ask the source around
* the focused element first, and guess a file's local changes only when there is none. So every
* way in reaches the view's diff, whatever the keymap binds: a shortcut, a menu, Find Action.
*
* Views don't claim the diff actions' keystrokes themselves (`registerKeyClaim` on Show Diff's
* bindings): such a claim misses a key the user bound to a sibling action (Show Diff in New
* Window), and the action then diffed an unrelated file against HEAD. A test guards this.
*/
import { useEffect, type RefObject } from "react";
import type { DiffData } from "./diffInput";
export interface DiffSource {
/**
* The selection's diff with the view's files as its chain, for Show Diff in New Window;
* null (or absent) when the view shows its diffs another way, then {@link show} stands in.
*/
diff?(): DiffData | null | Promise<DiffData | null>;
/** Show Diff the view's own way (a diff in front of a dialog, its own window); default: {@link diff} in the editor. */
show?(): void | Promise<void>;
}
const sources = new Map<Element, DiffSource>();
/** Makes `source` the diff of `element`'s selection while the focus is inside it; returns the unregister. */
export function registerDiffSource(element: Element, source: DiffSource): () => void {
sources.set(element, source);
return () => {
if (sources.get(element) === source) sources.delete(element);
};
}
/** The source of the innermost registered view around the focused element, if any. */
export function focusedDiffSource(
active: Element | null = typeof document === "undefined" ? null : document.activeElement,
): DiffSource | null {
for (let el = active; el; el = el.parentElement) {
const source = sources.get(el);
if (source) return source;
}
return null;
}
/** Registers `source` (the latest render's) for the element `ref` holds; `null` registers nothing. */
export function useDiffSource(ref: RefObject<Element | null>, source: DiffSource | null) {
useEffect(() => {
const element = ref.current;
if (!element || !source) return;
return registerDiffSource(element, source);
});
}
+10
Переглянути файл
@@ -35,11 +35,14 @@ import {
type MouseEvent as ReactMouseEvent,
} from "react";
import { DIFF_KIND, diffInput } from "../diffInput";
import { useDiffSource } from "../diffSource";
import { buildFileTree, dirKeys, type FileTreeNode } from "../fileTree";
import styles from "../GitLog.module.css";
import {
canApplySelectedChanges,
absolutePath,
changesArg,
changesDiffData,
filesUnder,
flatFileNodes,
showChangesDiff,
@@ -309,6 +312,12 @@ export function CommitDetails({ commits, fileHistory = false }: { commits: Commi
[scope],
);
useEffect(() => () => setContext("vcsLogChangesFocus", false), []);
// Show Diff in New Window (and Show Diff, whatever key runs it) diffs the selected changes.
const filesPane = useRef<HTMLDivElement>(null);
useDiffSource(filesPane, {
diff: () => changesDiffData(changesArg(undefined)),
show: () => void executeAction("vcs.log.changes.showDiff"),
});
if (!commit)
return (
@@ -386,6 +395,7 @@ export function CommitDetails({ commits, fileHistory = false }: { commits: Commi
minSize={fileHistory ? "25%" : "60px"}
>
<div
ref={filesPane}
className={styles.filesPane}
onFocusCapture={() => setContext("vcsLogChangesFocus", true)}
onBlurCapture={(e) => {
+18 -5
Переглянути файл
@@ -224,6 +224,23 @@ export function changesArg(arg: unknown): LogChange[] {
return useLogChanges.getState().selected;
}
/**
* The first file's diff with every file of the pane in the chain (F7 moves along); null without
* files, or for a merge commit's file, which shows a merge diff of its own.
*/
export function changesDiffData(
changes: readonly LogChange[],
chainChanges: readonly LogChange[] = useLogChanges.getState().all,
): DiffData | null {
const first = changes[0];
if (!first || (first.mergeParents?.length === 2 && first.after)) return null;
const chain = chainChanges.includes(first) ? chainChanges : [...changes];
return withChain(
chain.map((c) => c.diff),
Math.max(0, chain.indexOf(first)),
);
}
/**
* Show Diff: the first file, with every file of the pane in the chain (F7 moves along), in the
* editor's preview tab, so looking through a commit's files reuses one tab.
@@ -251,11 +268,7 @@ export async function showChangesDiff(
else await editorService().openInput(input, { preview: true, focus: !preview });
return;
}
const chain = chainChanges.includes(first) ? chainChanges : [...changes];
const data = withChain(
chain.map((c) => c.diff),
Math.max(0, chain.indexOf(first)),
);
const data = changesDiffData(changes, chainChanges)!;
// Selection preview stays a preview tab even under the modal interface; an explicit
// diff opens where the commit interface puts it. With "Open diff as editor tab" off
// (and no all-in-one diff) that is a separate window, so there is no tab to preview in.
+6 -3
Переглянути файл
@@ -1275,9 +1275,8 @@ export function ChangesBetweenDialog({
useEffect(() => {
if (native) onCaption?.(caption);
}, [native, onCaption, caption]);
const showDiff = () => {
if (!current) return;
const data = chainedDiff(tree, current, diffFor) ?? diffFor(current);
const showFileDiff = (file: ComparisonFile) => {
const data = chainedDiff(tree, file, diffFor) ?? diffFor(file);
if (onShowDiff) onShowDiff(data);
else {
void openVcsDiff(data);
@@ -1285,6 +1284,9 @@ export function ChangesBetweenDialog({
if (!vcsDiffInFront()) onClose();
}
};
const showDiff = () => {
if (current) showFileDiff(current);
};
const contents = (
<>
{error && (
@@ -1331,6 +1333,7 @@ export function ChangesBetweenDialog({
ariaLabel="Changed files"
inlineDiff={!listOnly}
openOnActivate={listOnly}
onShowDiff={showFileDiff}
renderDetails={(n) =>
n.file ? (
<>
+4 -18
Переглянути файл
@@ -34,7 +34,7 @@ import {
type MenuItem,
} from "@/ui";
import { executeAction } from "@/platform/actions";
import { bindingsFor, normalizeBinding, registerKeyClaim, shortcutLabel } from "@/platform/keymap";
import { shortcutLabel } from "@/platform/keymap";
import { choosePath, chooseSavePath } from "@/platform/choosePath";
import { workflowSettings } from "@/platform/workflowSettings";
import { notifications } from "@/workbench/contributions";
@@ -63,6 +63,7 @@ import styles from "./common.module.css";
import { tx, useTx } from "@/platform/i18n";
import previewStyles from "./ApplyPatch.module.css";
import type { PatchDiffRequest } from "./patchDiff";
import { useDiffSource } from "./diffSource";
export type PatchOrigin =
| { kind: "changes"; files: FileStatus[]; staging?: readonly StagingPatchEntry[] }
@@ -677,23 +678,8 @@ function ApplyPatchDialog({
},
[base, files, mapped, patch, placements, repo],
);
useEffect(
() =>
registerKeyClaim((event, stroke) => {
if (
!activeFile ||
!(event.target instanceof Element) ||
!fileList.current?.contains(event.target.closest('[role="tree"]')) ||
!bindingsFor("vcs.showDiff").some((binding) => normalizeBinding(binding) === stroke)
)
return false;
event.preventDefault();
event.stopPropagation();
showDiff(activeFile);
return true;
}),
[activeFile, showDiff],
);
// A patch's diff shows in its own dialog, also for Show Diff in New Window.
useDiffSource(fileList, activeFile ? { show: () => showDiff(activeFile) } : null);
const count = files?.length ?? 0;
const needsDirectory = (file: PatchFile) =>
file.missingBase || (!!placements.get(file.path)?.error && directoryMatches.has(file.path));
+33 -19
Переглянути файл
@@ -17,8 +17,9 @@ import type {
ShelfDiffFile,
} from "@/bindings";
import { setContext } from "@/platform/context";
import { bindingsFor, normalizeBinding, registerKeyClaim, shortcutLabel } from "@/platform/keymap";
import { shortcutLabel } from "@/platform/keymap";
import { openDiff, openVcsDiff, withChain, workingDiffData, type DiffData } from "./diffInput";
import { useDiffSource } from "./diffSource";
import { showCreatePatchForShelf } from "./patches";
import { executeAction } from "@/platform/actions";
import { call, commands } from "@/platform/ipc";
@@ -230,18 +231,24 @@ function ChangeChecklist<F>({
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 lead = () => [...selectedNodes(), tree[0]!].flatMap((n) => filesBelow(n))[0];
useDiffSource(
content,
diffOf
? {
diff: () => {
const file = lead();
if (!file) return null;
const chain = filesBelow(tree[0]!);
return withChain(chain.map(diffOf), chain.indexOf(file));
},
show: () => {
const file = lead();
if (file) showDiff?.(file);
},
}
: null,
);
const toggle = (...nodes: FileTreeNode<F>[]) => {
const below = nodes.flatMap((n) => filesBelow(n));
const include = !below.every((f) => selected.has(keyOf(f)));
@@ -610,13 +617,14 @@ export function shelfDiffs(target: ShelfTarget, local = false): DiffData[] {
}));
}
export async function showShelfDiff(arg?: unknown, local = false, newTab = false) {
/** The shelved diff of `arg` (the shelf's selection when omitted), its files as the chain. */
async function shelfDiffData(arg?: unknown, local = false): Promise<DiffData | null> {
const target = shelfTarget(arg);
if (!target) return;
if (!target) return null;
if (!useShelf.getState().diffs[target.entry.id]) {
const root = useVcs.getState().root;
const files = await call(commands.vcsShelfDiff(target.entry.id));
if (useVcs.getState().root !== root) return;
if (useVcs.getState().root !== root) return null;
useShelf.setState((s) => ({ diffs: { ...s.diffs, [target.entry.id]: files } }));
}
let items = shelfDiffs({ id: target.entry.id, path: target.path }, local);
@@ -633,10 +641,15 @@ export async function showShelfDiff(arg?: unknown, local = false, newTab = false
);
items = items.filter((_, i) => supported[i]);
}
if (!items.length) return;
return items.length ? withChain(items, 0) : null;
}
export async function showShelfDiff(arg?: unknown, local = false, newTab = false) {
const data = await shelfDiffData(arg, local);
if (!data) return;
// "Show Diff in a New Tab" asks for an editor tab whatever the commit interface.
if (newTab) await openDiff(withChain(items, 0), { preview: false });
else await openVcsDiff(withChain(items, 0), { preview: true });
if (newTab) await openDiff(data, { preview: false });
else await openVcsDiff(data, { preview: true });
}
export async function importShelfPatches(paths?: string[]) {
@@ -791,6 +804,7 @@ export function ShelfPanel() {
void loadShelves().catch(() => undefined);
return () => setContext("shelfFocus", false);
}, [root]);
useDiffSource(panelRef, { diff: () => shelfDiffData(), show: () => showShelfDiff() });
const selectedId = selectedShelf?.split("\u0000", 1)[0];
const entry = shelves.find((s) => s.id === selectedId);
const patches = useMemo<ShelfNode[]>(() => shelves.map((s) => ({ key: s.id, entry: s })), [shelves]);
+14 -20
Переглянути файл
@@ -12,19 +12,6 @@ export interface StashDiffRequest {
dialogLifetime?: AbortSignal;
}
let focusedStash: StashDiffRequest | null = null;
export function focusedStashDiff(): StashDiffRequest | null {
return focusedStash;
}
export function focusStashDiff(request: StashDiffRequest): () => void {
focusedStash = request;
return () => {
if (focusedStash === request) focusedStash = null;
};
}
async function hasWorkingFile(path: string): Promise<boolean> {
if (editorsFor(path).length) return true;
return call(commands.fsEntryKind(path)).then(
@@ -51,25 +38,32 @@ async function stashFileDiff(change: LogChange, label: string, target: StashDiff
return { path, left, right };
}
/** The stash's diff chain, with a local side that follows the editor buffer. */
export async function showStashDiff(request: StashDiffRequest, target: StashDiffTarget, preview?: AbortSignal) {
/** The stash's diff chain, with a local side that follows the editor buffer; null when no file has one. */
export async function stashDiffData(request: StashDiffRequest, target: StashDiffTarget): Promise<DiffData | null> {
const { changes, chain, dialogLifetime } = request;
const signal = dialogLifetime ?? preview;
if (!changes.length || signal?.aborted) return;
if (!changes.length) return null;
const files = chain.includes(changes[0]!) ? chain : changes;
const saved = `stash@{${request.index}}`;
const results = await Promise.all(
files.map(async (file) => ({ file, diff: await stashFileDiff(file, saved, dialogLifetime ? "local" : target) })),
);
if (signal?.aborted) return;
const ready = results.flatMap(({ file, diff }) => (diff ? [{ file, diff }] : []));
const selected = new Set(changes);
const index = ready.findIndex(({ file }) => selected.has(file));
if (index < 0) return;
const diff = withChain(
if (index < 0) return null;
return withChain(
ready.map((item) => item.diff),
index,
);
}
/** Shows the stash's diff chain: in front of the modal stash review, else in the editor. */
export async function showStashDiff(request: StashDiffRequest, target: StashDiffTarget, preview?: AbortSignal) {
const { dialogLifetime } = request;
const signal = dialogLifetime ?? preview;
if (signal?.aborted) return;
const diff = await stashDiffData(request, target);
if (!diff || signal?.aborted) return;
if (dialogLifetime) {
const { openDiffDialog } = await import("./diffDialog");
if (!dialogLifetime.aborted) openDiffDialog(diff);
+2 -1
Переглянути файл
@@ -10970,5 +10970,6 @@
"Keep Index": "保留索引",
"SQLite cannot drop the index of a primary key or unique constraint.": "SQLite 无法删除主键或唯一约束的索引。",
"Cannot list the manage.py commands": "无法列出 manage.py 命令",
"Install django-types into this project's virtual environment to complete Django model fields and managers": "将 django-types 安装到此项目的虚拟环境,以补全 Django 模型字段和管理器"
"Install django-types into this project's virtual environment to complete Django model fields and managers": "将 django-types 安装到此项目的虚拟环境,以补全 Django 模型字段和管理器",
"No local changes in {path}": "{path} 中没有本地更改"
}