Порівняти коміти

...
Автор SHA1 Повідомлення Дата
l0ng-ai 891432c2d9 fix(diff): run editor text actions on the diff's focused side
Text actions that need only the view (Comment Line, Duplicate Line, Move
Line, Join Lines, Toggle Case, Add Selection for Next Occurrence, Clone Caret
and the like) now also run while a diff or merge editor has focus: editing ones
on its editable side, caret and selection ones on either side. Before, they
were enabled only by editorTextFocus, which the diff never sets, so their keys
did nothing or fell through as typed text. Diff panes now allow several
selections and keep the occurrence search state (search again from the top),
and ⌘D duplicates the line there instead of opening Show Diff.

Closes #4343
2026-11-19 01:16:05 +08:00
6 змінених файлів з 138 додано та 30 видалено

No files matched your search

+56 -27
Переглянути файл
@@ -109,6 +109,25 @@ function activeSlot(): EditorSlot | null {
return slot && !slot.disposed ? slot : null;
}
/**
* The text pane that has focus in a diff or merge editor (`editable`: only a side that can be
* edited). Text actions that need nothing but the view run there, as in a file editor.
*/
function focusedDiffPane(editable: boolean): EditorView | null {
const el = typeof document === "undefined" ? null : document.activeElement;
const view = el instanceof HTMLElement ? EditorView.findFromDOM(el) : null;
return view && !(editable && view.state.readOnly) ? view : null;
}
/** `run` on the focused diff pane while a diff has focus, otherwise on the active editor. */
function withTextView(run: (view: EditorView) => unknown, editable: boolean) {
return () => {
if (!getContext().diffEditorFocus) return withView(run)();
const view = focusedDiffPane(editable);
if (view) run(view);
};
}
function withView(run: (view: EditorView, slot: EditorSlot) => unknown) {
return () => {
const slot = activeSlot();
@@ -736,6 +755,16 @@ export function registerEditorActions(): () => void {
run: withView(run),
...extra,
});
/** A text action that also runs in a diff: on its editable side (`edit`) or on either side (`caret`). */
const diffText =
(editable: boolean) =>
(id: string, title: string, run: (view: EditorView) => unknown, extra: Partial<Action> = {}): Action => ({
...text(id, title, run, extra),
when: `${TEXT_WHEN} || diffEditorFocus`,
run: withTextView(run, editable),
});
const edit = diffText(true);
const caret = diffText(false);
const activePaneTab = () => {
const s = useTabs.getState();
const pane = s.panes[s.activePane];
@@ -745,13 +774,13 @@ export function registerEditorActions(): () => void {
id,
title,
category: "Edit",
when: `${TEXT_WHEN} || findBarFocus || findBarOpen && popupOpen && !toolWindowFocus`,
when: `${TEXT_WHEN} || diffEditorFocus || findBarFocus || findBarOpen && popupOpen && !toolWindowFocus`,
run: ({ arg, ctx }) => {
const view = typeof arg === "string" || ctx.findBarFocus ? findPanelTarget(arg)?.view() : null;
if (view) {
run(view);
view.focus();
} else withView(run)();
} else withTextView(run, false)();
},
});
return registerActions([
@@ -773,16 +802,16 @@ export function registerEditorActions(): () => void {
toggled: codeVisionShown,
run: () => toggleCodeVision(),
},
text("code.commentLine", "Comment with Line Comment", (v) => commentLine(v)),
text("code.commentBlock", "Comment with Block Comment", (v) => commentBlock(v)),
text("code.duplicateLine", "Duplicate Line or Selection", (v) => duplicateLineOrSelection(v)),
text("code.deleteLine", "Delete Line", (v) => deleteLine(v)),
text("code.moveLineUp", "Move Line Up", (v) => moveLineUp(v)),
text("code.moveLineDown", "Move Line Down", (v) => moveLineDown(v)),
text("code.moveElementLeft", "Move Element Left", (v) => moveElementLeft(v), {
edit("code.commentLine", "Comment with Line Comment", (v) => commentLine(v)),
edit("code.commentBlock", "Comment with Block Comment", (v) => commentBlock(v)),
edit("code.duplicateLine", "Duplicate Line or Selection", (v) => duplicateLineOrSelection(v)),
edit("code.deleteLine", "Delete Line", (v) => deleteLine(v)),
edit("code.moveLineUp", "Move Line Up", (v) => moveLineUp(v)),
edit("code.moveLineDown", "Move Line Down", (v) => moveLineDown(v)),
edit("code.moveElementLeft", "Move Element Left", (v) => moveElementLeft(v), {
keywords: ["swap argument", "move parameter"],
}),
text("code.moveElementRight", "Move Element Right", (v) => moveElementRight(v), {
edit("code.moveElementRight", "Move Element Right", (v) => moveElementRight(v), {
keywords: ["swap argument", "move parameter"],
}),
text("code.moveStatementUp", "Move Statement Up", (v, slot) => moveStatement(v, slot, true)),
@@ -818,7 +847,7 @@ export function registerEditorActions(): () => void {
category: "Edit",
keywords: ["fully qualified name", "fqn", "copy path"],
},
text("code.pasteAsPlainText", "Paste as Plain Text", (v) => pasteAsPlainText(v), {
edit("code.pasteAsPlainText", "Paste as Plain Text", (v) => pasteAsPlainText(v), {
category: "Edit",
icon: "paste",
}),
@@ -862,23 +891,23 @@ export function registerEditorActions(): () => void {
occurrence("code.addCaretNextOccurrence", "Add Selection for Next Occurrence", addNextOccurrence),
occurrence("code.selectAllOccurrences", "Select All Occurrences", selectAllOccurrences),
text("code.completeStatement", "Complete Current Statement", (v, slot) => completeCurrentStatement(v, slot)),
text("code.startNewLine", "Start New Line", (v) => startNewLine(v)),
text("code.startNewLineBefore", "Start New Line Before Current", (v) => startNewLineBefore(v)),
text("code.splitLine", "Split Line", (v) => splitLine(v)),
text("editor.scrollToCenter", "Scroll to Center", (v) => scrollToCenter(v), { category: "Editor Actions" }),
text("editor.codeBlockStart", "Move Caret to Code Block Start", (v) => cursorCodeBlockStart(v), {
edit("code.startNewLine", "Start New Line", (v) => startNewLine(v)),
edit("code.startNewLineBefore", "Start New Line Before Current", (v) => startNewLineBefore(v)),
edit("code.splitLine", "Split Line", (v) => splitLine(v)),
caret("editor.scrollToCenter", "Scroll to Center", (v) => scrollToCenter(v), { category: "Editor Actions" }),
caret("editor.codeBlockStart", "Move Caret to Code Block Start", (v) => cursorCodeBlockStart(v), {
category: "Editor Actions",
}),
text("editor.codeBlockEnd", "Move Caret to Code Block End", (v) => cursorCodeBlockEnd(v), {
caret("editor.codeBlockEnd", "Move Caret to Code Block End", (v) => cursorCodeBlockEnd(v), {
category: "Editor Actions",
}),
text(
caret(
"editor.codeBlockStartWithSelection",
"Move Caret to Code Block Start with Selection",
(v) => selectCodeBlockStart(v),
{ category: "Editor Actions" },
),
text(
caret(
"editor.codeBlockEndWithSelection",
"Move Caret to Code Block End with Selection",
(v) => selectCodeBlockEnd(v),
@@ -905,7 +934,7 @@ export function registerEditorActions(): () => void {
}),
]),
text("code.collapseBlock", "Fold Code Block", (v) => collapseBlock(v), { category: "Folding", keywords: ["fold"] }),
text("code.autoIndentLines", "Auto-Indent Lines", (v) => !v.state.readOnly && indentSelection(v), {
edit("code.autoIndentLines", "Auto-Indent Lines", (v) => !v.state.readOnly && indentSelection(v), {
keywords: ["reindent", "fix indentation"],
}),
{
@@ -927,8 +956,8 @@ export function registerEditorActions(): () => void {
// The mouse selection style owns the drag; invoking the action alone is harmless.
run: () => {},
},
text("editor.cloneCaretAbove", "Clone Caret Above", (v) => cloneCaretAbove(v), { category: "Editor Actions" }),
text("editor.cloneCaretBelow", "Clone Caret Below", (v) => cloneCaretBelow(v), { category: "Editor Actions" }),
caret("editor.cloneCaretAbove", "Clone Caret Above", (v) => cloneCaretAbove(v), { category: "Editor Actions" }),
caret("editor.cloneCaretBelow", "Clone Caret Below", (v) => cloneCaretBelow(v), { category: "Editor Actions" }),
text("editor.matchBrace", "Move Caret to Matching Brace", (v) => cursorMatchBrace(v), {
category: "Editor Actions",
// ⌃M is Show Commit Message History in the commit window.
@@ -942,9 +971,9 @@ export function registerEditorActions(): () => void {
return view ? isOverwrite(view.state) : false;
},
}),
text("code.joinLines", "Join Lines", (v) => joinLines(v)),
text("code.toggleCase", "Toggle Case", (v) => toggleCase(v), { keywords: ["upper", "lower"] }),
text("code.addCaretsToLineEnds", "Add Carets to Ends of Selected Lines", (v) => addCaretsToLineEnds(v), {
edit("code.joinLines", "Join Lines", (v) => joinLines(v)),
edit("code.toggleCase", "Toggle Case", (v) => toggleCase(v), { keywords: ["upper", "lower"] }),
caret("code.addCaretsToLineEnds", "Add Carets to Ends of Selected Lines", (v) => addCaretsToLineEnds(v), {
category: "Edit",
}),
occurrence("code.unselectOccurrence", "Unselect Occurrence", unselectOccurrence),
@@ -952,8 +981,8 @@ export function registerEditorActions(): () => void {
category: "Edit",
keywords: ["clipboard", "paste multiple"],
}),
text("code.sortLines", "Sort Lines", (v) => sortLines(v), { category: "Edit" }),
text("code.reverseLines", "Reverse Lines", (v) => reverseLines(v), { category: "Edit" }),
edit("code.sortLines", "Sort Lines", (v) => sortLines(v), { category: "Edit" }),
edit("code.reverseLines", "Reverse Lines", (v) => reverseLines(v), { category: "Edit" }),
text("code.unwrap", "Unwrap/Remove…", (_v, slot) => void unwrapAtCaret(slot), {
keywords: ["unwrap", "remove if"],
}),
+1 -1
Переглянути файл
@@ -28,7 +28,7 @@ beforeEach(async () => {
id: "vcs.showDiff",
title: "Show Diff",
when: "vcsAvailable",
keyWhen: "!editorTextFocus && !vcsLogChangesFocus && !vcsLogRevisionFocus",
keyWhen: "!editorTextFocus && !diffEditorFocus && !vcsLogChangesFocus && !vcsLogRevisionFocus",
run: showDiff,
},
{
+75
Переглянути файл
@@ -0,0 +1,75 @@
import { javascript } from "@codemirror/lang-javascript";
import { EditorSelection, EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
import { executeAction } from "@/platform/actions";
import { setContext } from "@/platform/context";
import { registerEditorActions } from "@/editor/core/actions";
import { viewerBase } from "../cm";
let dispose: () => void;
const views: EditorView[] = [];
beforeAll(() => {
dispose = registerEditorActions();
});
afterAll(() => dispose());
afterEach(() => {
setContext("diffEditorFocus", false);
for (const view of views.splice(0)) view.destroy();
});
/** A focused diff pane, as the diff editor's viewer builds it. */
function pane(doc: string, readOnly: boolean, anchor = 0, head = anchor): EditorView {
const view = new EditorView({
parent: document.body,
state: EditorState.create({
doc,
selection: EditorSelection.single(anchor, head),
extensions: [javascript(), viewerBase({ readOnly, findBar: true })],
}),
});
views.push(view);
view.contentDOM.focus();
setContext("diffEditorFocus", true);
return view;
}
describe("text actions in a diff", () => {
it("edit the focused editable side", async () => {
const view = pane("let a = 1;\nlet b = 2;", false);
expect(await executeAction("code.commentLine")).toBe(true);
expect(view.state.doc.line(1).text).toBe("//let a = 1;");
await executeAction("code.duplicateLine");
expect(view.state.doc.lines).toBe(3);
});
it("add a selection for the next occurrence on either side", async () => {
const view = pane("foo bar foo baz foo", true, 0, 3);
await executeAction("code.addCaretNextOccurrence");
await executeAction("code.addCaretNextOccurrence");
expect(view.state.selection.ranges.map((r) => [r.from, r.to])).toEqual([
[0, 3],
[8, 11],
[16, 19],
]);
});
it("search again from the top once no next occurrence is left", async () => {
const view = pane("foo bar foo", false, 8, 11);
await executeAction("code.addCaretNextOccurrence");
expect(view.state.selection.ranges).toHaveLength(1);
await executeAction("code.addCaretNextOccurrence");
expect(view.state.selection.ranges.map((r) => [r.from, r.to])).toEqual([
[0, 3],
[8, 11],
]);
});
it("leave a side that can't be edited as it is", async () => {
const view = pane("let a = 1;", true);
await executeAction("code.commentLine");
await executeAction("code.duplicateLine");
expect(view.state.doc.toString()).toBe("let a = 1;");
});
});
+1 -1
Переглянути файл
@@ -116,7 +116,7 @@ describe("File History actions", () => {
try {
expect(getAction("vcs.log.changes.showDiff")!.keyWhen).toBe("vcsLogChangesFocus || vcsLogRevisionFocus");
expect(getAction("vcs.showDiff")!.keyWhen).toBe(
"!editorTextFocus && !vcsLogChangesFocus && !vcsLogRevisionFocus",
"!editorTextFocus && !diffEditorFocus && !vcsLogChangesFocus && !vcsLogRevisionFocus",
);
window.dispatchEvent(new KeyboardEvent("keydown", { code: "KeyD", key: "d", ctrlKey: true, bubbles: true }));
await vi.waitFor(() => expect(mocks.openVcsDiff).toHaveBeenCalledOnce());
+1 -1
Переглянути файл
@@ -422,7 +422,7 @@ export function registerVcsActions(): () => void {
when: VCS,
// ⌘D duplicates the line inside a text editor; Git › Show Diff still works there.
// In the Git Log's changed files it shows the commit's diff instead.
keyWhen: "!editorTextFocus && !vcsLogChangesFocus && !vcsLogRevisionFocus",
keyWhen: "!editorTextFocus && !diffEditorFocus && !vcsLogChangesFocus && !vcsLogRevisionFocus",
run: async ({ arg, ctx }) => {
if (ctx.shelfFocus && arg === undefined) return showShelfDiff();
const line =
+4
Переглянути файл
@@ -37,6 +37,7 @@ import { search, searchKeymap } from "@codemirror/search";
import { scrollbarMarks, type ScrollbarMark } from "@/editor/api";
import { openideaHighlightStyle } from "@/editor/core/cm/highlight";
import { languageDescriptionFor, loadSupport } from "@/editor/core/cm/languages";
import { occurrenceSearch } from "@/editor/core/cm/editing";
import { findExtension } from "@/editor/core/cm/find";
import { overviewLane } from "@/editor/core/cm/lanes";
import { LINE_INSET } from "@/editor/core/cm/lineInset";
@@ -518,6 +519,9 @@ export function viewerBase(opts: {
changedLines,
EditorState.readOnly.of(opts.readOnly),
EditorView.editable.of(!opts.readOnly),
// Add Selection for Next Occurrence, Clone Caret: several carets, as in the editor.
EditorState.allowMultipleSelections.of(true),
occurrenceSearch,
// Non-editable revision panes still need keyboard selection and copy.
opts.readOnly ? EditorView.contentAttributes.of({ tabindex: "0" }) : [],
];