feat(diff): Esc closes a diff tab; switch panes with ⌃⇧⇥; move a diff window back to a tab (#3517)

Close Diff Editor: Esc in a diff editor tab closes it once the find bar, a selection, completion or a popup don't take it; panels, dialogs and diff windows keep their own Esc. Select Opposite Diff Pane (⌃⇧⇥ in the IntelliJ keymaps) moves focus to the other side of a side-by-side diff and wins over the Switcher while a diff is focused. A diff window's Show Diff in Editor Tab saves its edits, opens the diff as a tab in its project window and closes the window.
This commit is contained in:
l0ng-ai
2026-11-15 18:42:16 +08:00
committed by GitHub
parent 733b6cff1d
commit 7ec0a4fed2
14 changed files with 154 additions and 12 deletions
+34 -2
View File
@@ -39,7 +39,7 @@ import { bindingsFor, normalizeBinding, shortcutLabel, strokeOf } from "@/platfo
import { tx } from "@/platform/i18n";
import { useProject } from "@/platform/project";
import { isVirtualUri } from "@/platform/virtualDocs";
import { IconButton, Select, Spinner, T, showContextMenu } from "@/ui";
import { IconButton, Select, Spinner, T, isPopupOpen, showContextMenu } from "@/ui";
import { registerSoftWrapSurface } from "@/workbench/softWrap";
import { editorService, type EditorInput } from "@/workbench/contributions";
import { changedLineGutters, diffOverview, diffWords, languageFor, viewerBase } from "./cm";
@@ -218,6 +218,10 @@ const editableExtensions = (): Extension => [history(), keymap.of(historyKeymap)
type Side = "a" | "b";
type ViewUpdateFn = (u: { docChanged: boolean; selectionSet: boolean }) => void;
/** Esc alone, not while composing text. */
const plainEscape = (e: KeyboardEvent) =>
e.key === "Escape" && !e.shiftKey && !e.altKey && !e.metaKey && !e.ctrlKey && !e.nativeEvent.isComposing;
/** Whether `e` is one of the strokes bound to `actionId`. */
function isStrokeOf(e: KeyboardEvent, actionId: string): boolean {
const stroke = strokeOf(e.nativeEvent);
@@ -229,6 +233,7 @@ export function DiffEditor({
toolbarActions,
onNeighbour,
onJumpToSource,
onClose,
}: {
input: EditorInput;
toolbarActions?: ReactNode;
@@ -240,6 +245,8 @@ export function DiffEditor({
onNeighbour?: (data: DiffData) => void;
/** Called as Jump to Source opens the file in an editor: a modal host closes, or the editor stays hidden behind it. */
onJumpToSource?: () => void;
/** Closes the diff's editor tab (Esc, IDEA's Close Diff Editor); hosts that aren't tabs leave it out. */
onClose?: () => void;
}) {
const data = input.data as DiffData;
const { path, left, right } = data;
@@ -976,6 +983,18 @@ export function DiffEditor({
closeFind();
return true;
};
/** Select Opposite Diff Pane (⌃⇧⇥): the other side keeps its own caret, as in IDEA. */
const focusOpposite = () => {
const views = viewsRef.current;
if (!views?.a) return false;
(focusedSide.current === "a" ? views.b : views.a).focus();
return true;
};
const close = () => {
if (!onClose) return false;
onClose();
return true;
};
const onKeyDown = (e: KeyboardEvent) => {
if (e.defaultPrevented) return;
if (isStrokeOf(e, "find.inFile")) openFind(false);
@@ -984,7 +1003,8 @@ export function DiffEditor({
if (!findOpen.current) findSide.current = focusedSide.current;
if (!searchAgain(findTarget, isStrokeOf(e, "find.next"))) openFind(false);
} else if (e.key === "Escape" && findOpen.current) closeFind();
else return;
// Esc that nothing in the diff took (find bar, selection, completion) closes its tab, as in IDEA.
else if (!plainEscape(e) || isPopupOpen() || !close()) return;
e.preventDefault();
e.stopPropagation();
};
@@ -1122,6 +1142,8 @@ export function DiffEditor({
applyChange,
file,
showSettings,
focusOpposite,
close,
viewer: viewerOf,
});
useLayoutEffect(() => {
@@ -1135,6 +1157,8 @@ export function DiffEditor({
applyChange,
file,
showSettings,
focusOpposite,
close,
viewer: viewerOf,
});
});
@@ -1350,6 +1374,14 @@ export function DiffEditor({
onClick={() => void executeAction("vcs.showDiffInNewWindow", data)}
/>
)}
{auxiliaryWindow()?.kind === "diff" && getAction("vcs.showDiffInEditorTab") && (
<IconButton
icon="editor-only"
title="Show Diff in Editor Tab"
size="small"
onClick={() => void executeAction("vcs.showDiffInEditorTab")}
/>
)}
<IconButton
icon="settings"
title="Settings"
+38 -9
View File
@@ -26,12 +26,14 @@ import { TitleBar } from "@/workbench/TitleBar";
import { WindowResizeHandles } from "@/workbench/WindowResizeHandles";
import { useApplyTheme, windowBackgroundHex } from "@/workbench/theme";
import { DiffEditor } from "./DiffEditor";
import { DIFF_KIND, diffInput, diffTitle, type DiffData, type DiffSide } from "./diffInput";
import { DIFF_KIND, diffInput, diffTitle, openDiff, type DiffData, type DiffSide } from "./diffInput";
import { refreshNow, useVcs } from "./store";
import styles from "./common.module.css";
/** Opens `path` in the project window's editor (DiffEditor's "Jump to Source"). */
const OPEN_SOURCE = "openidea://diff/open-source";
/** Opens a diff in an editor tab of the project window (IDEA's "Show Diff in Editor Tab"). */
const OPEN_DIFF = "openidea://diff/open-diff";
const useDiff = create<{
data: DiffData | null;
@@ -105,6 +107,24 @@ export function activateDiffWindow(parent: string): () => void {
}
},
});
// IDEA's Show Diff in Editor Tab: the diff moves to the project window, edits saved first.
const unregisterToEditor = registerAction({
id: "vcs.showDiffInEditorTab",
title: "Show Diff in Editor Tab",
category: "Git",
icon: "editor-only",
run: async () => {
const data = useDiff.getState().data;
if (!data) return;
try {
await documents.save();
await emitTo(parent, OPEN_DIFF, data);
await native.close();
} catch (error) {
showError(tx("Cannot show diff in an editor tab"), error instanceof Error ? error.message : String(error));
}
},
});
const savingReady = installDiffWindowSave(parent, documents.save).then((off) => {
if (disposed) off();
else stopSave = off;
@@ -198,6 +218,7 @@ export function activateDiffWindow(parent: string): () => void {
stopClose?.();
stopSave?.();
unregisterSave();
unregisterToEditor();
window.removeEventListener("keydown", onKey);
window.removeEventListener("keydown", onCloseShortcut, true);
};
@@ -207,23 +228,31 @@ export function activateDiffWindow(parent: string): () => void {
export function installDiffEditorHost(): () => void {
if (!isTauri()) return () => {};
let disposed = false;
let stop: (() => void) | undefined;
void getCurrentWindow()
const stops: Array<() => void> = [];
const keep = (off: () => void) => {
if (disposed) off();
else stops.push(off);
};
const native = getCurrentWindow();
void native
.listen<{ path: string; options?: OpenOptions }>(OPEN_SOURCE, ({ payload }) => {
const folder = projectFolder(useProject.getState().project, payload.path);
if (folder && payload.path.startsWith(`${folder.root}/`)) {
void editorService()
.openFile(payload.path, payload.options)
.then(() => getCurrentWindow().setFocus());
.then(() => native.setFocus());
}
})
.then((off) => {
if (disposed) off();
else stop = off;
});
.then(keep);
void native
.listen<DiffData>(OPEN_DIFF, ({ payload }) => {
if (!projectFolder(useProject.getState().project, payload.path)) return;
void openDiff(payload).then(() => native.setFocus());
})
.then(keep);
return () => {
disposed = true;
stop?.();
for (const stop of stops) stop();
};
}
+2
View File
@@ -356,6 +356,8 @@ export function MergeEditor({ input }: { input: EditorInput }) {
applyChange: () => false,
file: () => {},
showSettings: () => void actionHost.run("settings"),
focusOpposite: () => false,
close: () => false,
}));
useEffect(
() => () => {
@@ -231,3 +231,46 @@ describe("Find in the diff viewer", () => {
expect(v.state.selection.main.from).toBe(8);
});
});
describe("Esc and the opposite pane", () => {
const escape = (v: EditorView) => fireEvent.keyDown(v.contentDOM, { key: "Escape", code: "Escape", keyCode: 27 });
it("closes the tab with Esc only once nothing in the diff takes it", async () => {
useKeymap.setState({ overrides: KEYMAP });
const onClose = vi.fn();
render(<DiffEditor input={revisions} onClose={onClose} />);
const v = await press(1, "KeyF");
fireEvent.change(await screen.findByRole("textbox", { name: "Find" }), { target: { value: "foo" } });
await waitFor(() => expect(v.state.selection.main.empty).toBe(false));
v.focus();
escape(v); // closes the find bar
await waitFor(() => expect(screen.queryByRole("search")).toBeNull());
escape(v); // collapses the found match
expect(v.state.selection.main.empty).toBe(true);
expect(onClose).not.toHaveBeenCalled();
escape(v);
expect(onClose).toHaveBeenCalledOnce();
});
it("leaves Esc alone where the diff isn't a tab", async () => {
render(<DiffEditor input={revisions} />);
const v = await pane(1);
v.focus();
const event = new KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true });
v.contentDOM.dispatchEvent(event);
expect(event.defaultPrevented).toBe(false);
});
it("moves focus to the other side with Select Opposite Diff Pane", async () => {
const { focusedDiffNavigator } = await import("../diffNavigator");
render(<DiffEditor input={revisions} />);
const left = await pane(0);
const right = await pane(1);
right.focus();
await waitFor(() => expect(focusedDiffNavigator()).not.toBeNull());
expect(focusedDiffNavigator()!.focusOpposite()).toBe(true);
expect(left.hasFocus).toBe(true);
expect(focusedDiffNavigator()!.focusOpposite()).toBe(true);
expect(right.hasFocus).toBe(true);
});
});
+18
View File
@@ -175,6 +175,24 @@ export function registerCompareActions(): () => void {
when: "diffEditorFocus",
run: () => focusedDiffNavigator()?.showSettings(),
},
{
// Diff.FocusOppositePane; it beats the Switcher's ⌃⇧⇥ while a side-by-side diff is focused.
id: "diff.focusOppositePane",
title: "Select Opposite Diff Pane",
category: "Diff",
when: "diffEditorFocus",
keyWhen: "diffEditorFocus && !popupOpen",
enabled: () => (focusedDiffNavigator()?.viewer?.()?.panes().length ?? 0) > 1,
run: () => void focusedDiffNavigator()?.focusOpposite(),
},
{
// CloseDiffEditor: Esc in a diff tab that nothing in the diff takes (see DiffEditor).
id: "diff.closeEditor",
title: "Close Diff Editor",
category: "Diff",
when: "diffEditorFocus",
run: () => void focusedDiffNavigator()?.close(),
},
{
id: "diff.nextFile",
title: "Compare Next File",
+2 -1
View File
@@ -1,4 +1,4 @@
import type { EditorInput } from "@/workbench/contributions";
import { editorService, type EditorInput } from "@/workbench/contributions";
import { hideAllToolWindows, useToolWindowLayout } from "@/workbench/toolwindows/store";
import { shortcutLabel } from "@/platform/keymap";
import { IconButton } from "@/ui";
@@ -11,6 +11,7 @@ export function DiffEditorTab({ input }: { input: EditorInput }) {
return (
<DiffEditor
input={input}
onClose={() => void editorService().closeInput?.(input.key)}
toolbarActions={
<IconButton
icon={maximized ? "minimize" : "maximize"}
+4
View File
@@ -11,6 +11,10 @@ export interface DiffNavigator {
file(dir: 1 | -1): void;
/** The viewer's settings as a popup menu (⇧⌘D). */
showSettings(): void;
/** IDEA's Select Opposite Diff Pane: focus the other side of a side-by-side diff; false when there is none. */
focusOpposite(): boolean;
/** IDEA's Close Diff Editor (Esc): closes the diff's editor tab; false when the diff isn't one. */
close(): boolean;
/** The built panes, for diff viewer contributions' actions (null while loading). */
viewer?(): DiffViewerHost | null;
}
+1
View File
@@ -97,6 +97,7 @@ export const eclipseMacos: Record<string, string[]> = {
"diff.nextDifference": ["Ctrl+F7"],
"diff.prevFile": [],
"diff.nextFile": [],
"diff.focusOppositePane": [],
"navigate.nextOccurrence": [],
"editor.nextTab": ["Meta+F6", "Meta+Alt+Right"],
"db.nextResultTab": ["Meta+F6", "Meta+Alt+Right"],
+1
View File
@@ -99,6 +99,7 @@ export const eclipseWindows: Record<string, string[]> = {
"diff.nextDifference": ["Ctrl+F7"],
"diff.prevFile": ["Ctrl+Alt+Shift+Right"],
"diff.nextFile": ["Ctrl+Alt+Shift+Left"],
"diff.focusOppositePane": [],
"diff.applyLeftSide": [],
"diff.applyRightSide": [],
"navigate.nextOccurrence": [],
+1
View File
@@ -338,6 +338,7 @@ export const intellijMacos: Record<string, string[]> = {
"diff.nextFile": ["Ctrl+Shift+Right"],
"diff.prevFile": ["Ctrl+Shift+Left"],
"diff.showSettings": ["Meta+Shift+D"],
"diff.focusOppositePane": ["Ctrl+Shift+Tab"],
// After Show Diff: ⌘D is Compare With… in the project view.
"project.compareWith": ["Meta+D"],
// Editing extras, image viewer (keyWhen: image focused) and Markdown editor layouts
+1
View File
@@ -336,6 +336,7 @@ export const intellijWindows: Record<string, string[]> = {
"diff.nextFile": ["Alt+Shift+Right"],
"diff.prevFile": ["Alt+Shift+Left"],
"diff.showSettings": ["Ctrl+Shift+D"],
"diff.focusOppositePane": ["Ctrl+Shift+Tab"],
// After Show Diff: Ctrl+D is Compare With… in the project view.
"project.compareWith": ["Ctrl+D"],
// Editing extras, image viewer (keyWhen: image focused) and Markdown editor layouts
+1
View File
@@ -350,6 +350,7 @@ export const vscodeMacos: Record<string, string[]> = {
"diff.nextFile": [],
"diff.prevFile": [],
"diff.showSettings": [],
"diff.focusOppositePane": [],
"diff.prevDifference": ["Shift+F7"],
"diff.jumpToSource": [],
// HTTP Client / Database console: run the request or statement at the caret.
+4
View File
@@ -1,4 +1,8 @@
{
"Select Opposite Diff Pane": "Select Opposite Diff Pane",
"Close Diff Editor": "Close Diff Editor",
"Show Diff in Editor Tab": "Show Diff in Editor Tab",
"Cannot show diff in an editor tab": "Cannot show diff in an editor tab",
"Make configurations pinned by default": "Make configurations pinned by default",
"A finished pinned tab stays open: a later run opens a new tab instead of taking its place.": "A finished pinned tab stays open: a later run opens a new tab instead of taking its place.",
"Cannot paste the image into {name}": "Cannot paste the image into {name}",
+4
View File
@@ -1,4 +1,8 @@
{
"Select Opposite Diff Pane": "选择对侧差异窗格",
"Close Diff Editor": "关闭差异编辑器",
"Show Diff in Editor Tab": "在编辑器标签页中显示差异",
"Cannot show diff in an editor tab": "无法在编辑器标签页中显示差异",
"Make configurations pinned by default": "默认固定运行/调试标签页",
"A finished pinned tab stays open: a later run opens a new tab instead of taking its place.": "固定的标签页结束后会保留:之后的运行会打开新标签页,而不是替换它。",
"Cannot paste the image into {name}": "无法将图片粘贴为 {name}",