feat(vcs): build the commit message field on the editor so Vim works in it (#8283)

The commit message field was a textarea, outside Vim mode, and its Esc always blurred. It is now a reusable editor-based TextField (src/editor/TextField.tsx) carrying the embedded editor contributions, so Vim attaches when Vim mode is on. Margin guide, wrap at margin, subject counter, blank-line inspection, message history, Meta+Enter and the activation focus keep working. Vim claims Escape in a tool window's Vim field outside Normal mode, so Esc leaves Insert or Visual mode before the tool window's Focus Editor runs; in Normal mode Esc moves the focus as before. The field sets data-autofocus before paint and ignores the blur of a view being destroyed. The Commit dialog shares the field.

Co-authored-by: Inf1mum <[email protected]>
Цей коміт міститься в:
Vadim LazukтаInf1mum authored and GitHub committed 2026-12-06 04:25:56 +08:00
1 джерело 201ab6f54b
коміт d1afd0ae9f
13 files changed
+577 -66

No files matched your search

+20 -19
Переглянути файл
@@ -4,7 +4,7 @@
*/
import type { Page } from "@playwright/test";
import type { PartialCommitFile } from "../src/bindings";
import { expect, ipcCalls, openFromTree, stubDesktop, test } from "./fixtures";
import { expect, fieldText, ipcCalls, openFromTree, stubDesktop, test } from "./fixtures";
const ROOT = "/dev/acme-api";
@@ -357,7 +357,7 @@ test("Commit reviews a paused cherry-pick without collecting unrelated changes o
await expect(author).toHaveValue("Original Author <[email protected]>");
await expect(review.getByRole("list", { name: "Staged Changes" }).getByRole("button")).toHaveText("build.gradle.kts");
await review.getByRole("button", { name: "Cancel", exact: true }).click();
await expect(draft).toHaveValue("Unrelated and shared draft");
await expect.poll(() => fieldText(draft)).toBe("Unrelated and shared draft");
await local.click();
await draft.fill("Commit panel draft for the pick");
await panel.getByRole("button", { name: "Commit Options", exact: true }).click();
@@ -392,7 +392,7 @@ test("Commit reviews a paused cherry-pick without collecting unrelated changes o
},
]);
expect(await ipcCalls(page, "vcs_commit")).toEqual([]);
await expect(draft).toHaveValue("");
await expect.poll(() => fieldText(draft)).toBe("");
});
test("continuing a resolved operation applies commit modifications to the reviewed staging snapshot", async ({
@@ -965,7 +965,7 @@ test("opening a TODO review from the modal commit leaves the draft available", a
const todo = page.getByRole("region", { name: "TODO", exact: true });
await expect(todo.getByRole("tree").getByText("TODO from the commit dialog")).toBeVisible();
await page.keyboard.press("Meta+k");
await expect(dialog.getByRole("textbox", { name: "Commit message" })).toHaveValue("Keep this draft");
await expect.poll(() => fieldText(dialog.getByRole("textbox", { name: "Commit message" }))).toBe("Keep this draft");
expect(await ipcCalls(page, "vcs_commit")).toEqual([]);
});
@@ -1132,7 +1132,7 @@ test("the Commit tool window restores the draft and author options for the inclu
await page.keyboard.press("Escape");
await base.click();
await feature.click();
await expect(message).toHaveValue("Message from the changelist");
await expect.poll(() => fieldText(message)).toBe("Message from the changelist");
await message.fill("Feature draft");
await gear.click();
await expect(author).toHaveValue("");
@@ -1141,13 +1141,13 @@ test("the Commit tool window restores the draft and author options for the inclu
await date.fill(featureDate);
await page.keyboard.press("Escape");
await feature.click();
await expect(message).toHaveValue("Default draft");
await expect.poll(() => fieldText(message)).toBe("Default draft");
await gear.click();
await expect(author).toHaveValue("Default Author <[email protected]>");
await expect(date).toHaveValue(baseDate);
await page.keyboard.press("Escape");
await feature.click();
await expect(message).toHaveValue("Feature draft");
await expect.poll(() => fieldText(message)).toBe("Feature draft");
await panel.getByRole("button", { name: "Commit", exact: true }).click();
await expect
.poll(() => ipcCalls(page, "vcs_commit"))
@@ -1155,7 +1155,7 @@ test("the Commit tool window restores the draft and author options for the inclu
const [committed] = await ipcCalls(page, "vcs_commit");
const expectedDate = await page.evaluate((local) => new Date(local).toISOString(), featureDate);
expect(new Date((committed!.options as { authorDate: string }).authorDate).toISOString()).toBe(expectedDate);
await expect(message).toHaveValue("Default draft");
await expect.poll(() => fieldText(message)).toBe("Default draft");
});
test("commit message history shows compact message previews above the editor", async ({ workbench: page }) => {
@@ -1181,7 +1181,8 @@ test("commit message history shows compact message previews above the editor", a
const menu = page.getByRole("menu", { name: "Recent commit messages" });
const row = menu.getByRole("menuitem", { name: /Update inventory.*Review settlement totals/ });
await expect(row).toBeVisible();
const messageBox = (await message.boundingBox())!;
// The field's box: the editor's host, around its content.
const messageBox = (await message.locator("xpath=ancestor::div[contains(@class, 'cm-editor')]/..").boundingBox())!;
const menuBox = (await menu.locator("..").boundingBox())!;
const rowBox = (await row.boundingBox())!;
expect(messageBox.y - menuBox.y - menuBox.height).toBeCloseTo(3, 0);
@@ -1193,7 +1194,7 @@ test("commit message history shows compact message previews above the editor", a
await row.press("Escape");
await expect(menu).toBeHidden();
await expect(message).toHaveValue("Draft");
await expect.poll(() => fieldText(message)).toBe("Draft");
await history.click();
await row.press("Home");
await expect(row).toBeFocused();
@@ -1201,7 +1202,7 @@ test("commit message history shows compact message previews above the editor", a
const second = menu.getByRole("menuitem", { name: /Update inventory.*Reconcile export records/ });
await expect(second).toBeFocused();
await page.keyboard.press("Enter");
await expect(message).toHaveValue("Update inventory\n\nReconcile export records");
await expect.poll(() => fieldText(message)).toBe("Update inventory\n\nReconcile export records");
await expect(message).toBeFocused();
});
@@ -1364,7 +1365,7 @@ test("Amend sizes the chooser for long subjects while keeping the last commit ac
await expect(list).toBeHidden();
await page.setViewportSize({ width: 1040, height: 700 });
await page.keyboard.press("Meta+k");
await expect(panel.getByRole("textbox", { name: "Commit message" })).toHaveValue(earlier);
await expect.poll(() => fieldText(panel.getByRole("textbox", { name: "Commit message" }))).toBe(earlier);
});
test("Amend can select an earlier commit before protected history", async ({ workbench: page }) => {
@@ -1381,14 +1382,14 @@ test("Amend can select an earlier commit before protected history", async ({ wor
await expect(picker.getByText("Published commit", { exact: true })).toHaveCount(0);
await expect(picker.getByText("Before published commit", { exact: true })).toHaveCount(0);
await earlier.click();
await expect(message).toHaveValue("Earlier local commit");
await expect.poll(() => fieldText(message)).toBe("Earlier local commit");
await expect(panel.getByRole("treeitem", { name: /Earlier local commit 1 file/ })).toBeVisible();
await expect(panel.getByRole("treeitem", { name: "earlier.txt", exact: true })).toBeVisible();
await choose.click();
await picker.getByRole("option", { name: /^Amend Last Commit/ }).click();
await expect(message).toHaveValue("Last local commit");
await expect.poll(() => fieldText(message)).toBe("Last local commit");
await panel.getByRole("checkbox", { name: "Amend", exact: true }).uncheck();
await expect(message).toHaveValue("Draft");
await expect.poll(() => fieldText(message)).toBe("Draft");
await choose.click();
await earlier.click();
@@ -1454,7 +1455,7 @@ test("Amend filters commit subjects while loading and supports keyboard selectio
await search.press("Escape");
await expect(picker).toBeHidden();
await expect(choose).toBeFocused();
await expect(message).toHaveValue("Draft");
await expect.poll(() => fieldText(message)).toBe("Draft");
await choose.press("ArrowDown");
await expect(search).toHaveValue("");
@@ -1470,7 +1471,7 @@ test("Amend filters commit subjects while loading and supports keyboard selectio
await search.dispatchEvent("keydown", { key: "Enter", isComposing: true });
await expect(search).toBeFocused();
await search.press("Enter");
await expect(message).toHaveValue("Improve local docs");
await expect.poll(() => fieldText(message)).toBe("Improve local docs");
await choose.press("ArrowDown");
await expect(docs).toHaveAttribute("aria-selected", "true");
@@ -1503,7 +1504,7 @@ for (const editDraft of [false, true]) {
await panel.getByRole("button", { name: "Choose Commit to Amend", exact: true }).click();
await page.getByRole("option", { name: "Earlier local commit", exact: true }).click();
const message = panel.getByRole("textbox", { name: "Commit message" });
await expect(message).toHaveValue("Earlier local commit");
await expect.poll(() => fieldText(message)).toBe("Earlier local commit");
await panel.getByRole("button", { name: "Amend Commit", exact: true }).click();
const keep = page.getByRole("button", { name: "Create Amend Commit Anyway", exact: true });
@@ -1514,7 +1515,7 @@ for (const editDraft of [false, true]) {
await expect.poll(() => ipcCalls(page, "vcs_keep_amend_commit")).toEqual([{ repo: ROOT, commit: "prepared" }]);
await expect(page.getByText("Amend commit created", { exact: true })).toBeVisible();
expect(await ipcCalls(page, "vcs_commit")).toHaveLength(1);
await expect(message).toHaveValue(editDraft ? "New draft after conflict" : "Earlier local commit");
await expect.poll(() => fieldText(message)).toBe(editDraft ? "New draft after conflict" : "Earlier local commit");
await expect(panel.getByRole("checkbox", { name: "Amend", exact: true })).not.toBeChecked();
if (editDraft)
await expect
+4 -4
Переглянути файл
@@ -3,7 +3,7 @@
* latest task write the message. The agent and git are stubbed at the IPC layer.
*/
import type { Page } from "@playwright/test";
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
import { expect, fieldText, ipcCalls, stubDesktop, test } from "./fixtures";
const ROOT = "/dev/acme-api";
const PATCH =
@@ -110,11 +110,11 @@ test("the agent of the latest task writes the commit message of the included cha
await page.keyboard.press("Meta+k");
const panel = page.getByRole("region", { name: "Commit", exact: true });
const message = panel.getByRole("textbox", { name: "Commit message" });
await expect(message).toHaveValue("");
await expect.poll(() => fieldText(message)).toBe("");
await panel.getByRole("button", { name: "Generate Commit Message with Agent" }).click();
await expect(message).toHaveValue("Update the Gradle build\n\nBump the Kotlin plugin.");
await expect.poll(() => fieldText(message)).toBe("Update the Gradle build\n\nBump the Kotlin plugin.");
const [request] = await ipcCalls(page, "agent_create");
const created = request!.request as {
provider: string;
@@ -153,5 +153,5 @@ test("a message typed while the agent works is not overwritten", async ({ workbe
await message.fill("My own message");
await expect(page.getByText("Commit message not replaced")).toBeVisible();
await expect(message).toHaveValue("My own message");
await expect.poll(() => fieldText(message)).toBe("My own message");
});
+14 -1
Переглянути файл
@@ -1,5 +1,5 @@
/** Shared helpers: open the workbench with the injected sample project and fail on page errors. */
import { expect, test as base, type Page } from "@playwright/test";
import { expect, test as base, type Locator, type Page } from "@playwright/test";
export const PROJECT = "acme-api";
@@ -146,6 +146,19 @@ export async function stubSettingsWrites(page: Page) {
}
/** The commands the page has invoked so far under `stubDesktop`, by name. */
/** The text of an editor-based field (`src/editor/TextField.tsx`), as a textarea's value: one line per row, placeholder left out. */
export async function fieldText(field: Locator): Promise<string> {
return field.evaluate((el) =>
[...el.querySelectorAll(".cm-line")]
.map((line) => {
const copy = line.cloneNode(true) as Element;
for (const hint of copy.querySelectorAll(".cm-placeholder")) hint.remove();
return copy.textContent ?? "";
})
.join("\n"),
);
}
export async function ipcCalls(page: Page, cmd: string): Promise<Record<string, unknown>[]> {
return page.evaluate((cmd) => window.__ipc.calls.filter((c) => c.cmd === cmd).map((c) => c.args), cmd);
}
+3 -3
Переглянути файл
@@ -1,6 +1,6 @@
import type { Page } from "@playwright/test";
import type { EditorView } from "@codemirror/view";
import { expect, ipcCalls, openFromTree, stubDesktop, test } from "./fixtures";
import { expect, fieldText, ipcCalls, openFromTree, stubDesktop, test } from "./fixtures";
test("edits the staged version and keeps an unsaved draft when the index changes", async ({ workbench: page }) => {
const root = "/dev/acme-api";
@@ -907,7 +907,7 @@ test("Amend previews the original commit independently of the staged changes", a
const changes = panel.getByRole("tree", { name: "Changes", exact: true });
await message.fill("Unsent draft");
await amend.check();
await expect(message).toHaveValue("Original commit\n\nDescription");
await expect.poll(() => fieldText(message)).toBe("Original commit\n\nDescription");
await expect(changes.getByRole("treeitem", { name: /Original commit 1 file/ })).toHaveAttribute(
"aria-expanded",
"true",
@@ -930,5 +930,5 @@ test("Amend previews the original commit independently of the staged changes", a
await expect(await ipcCalls(page, "vcs_commit")).toHaveLength(0);
await amend.uncheck();
await expect(changes.getByText("Original commit", { exact: true })).toHaveCount(0);
await expect(message).toHaveValue("Unsent draft");
await expect.poll(() => fieldText(message)).toBe("Unsent draft");
});
+2 -2
Переглянути файл
@@ -1,4 +1,4 @@
import { expect, openFromTree, test } from "./fixtures";
import { expect, fieldText, openFromTree, test } from "./fixtures";
test("VCS Operations keeps its centered title visible in a short window", async ({ workbench: page }) => {
await page.setViewportSize({ width: 640, height: 320 });
@@ -45,7 +45,7 @@ test("VCS Operations keeps its centered title visible in a short window", async
await expect(commitWindow).toBeVisible();
const message = commitWindow.getByRole("textbox", { name: "Commit message" });
await expect(message).toBeFocused();
expect(await message.evaluate((el) => (el instanceof HTMLTextAreaElement ? el.value : el.textContent))).toBe("");
expect(await fieldText(message)).toBe("");
});
test("VCS Operations offers repository setup and Local History outside Git", async ({ workbench: page }) => {
+161
Переглянути файл
@@ -0,0 +1,161 @@
/** The editor-based text field: Vim goes first on Escape, the field stays controlled. */
import { afterEach, describe, expect, it, vi } from "vitest";
import { act, fireEvent, render } from "@testing-library/react";
import { useRef, useState } from "react";
import { EditorView } from "@codemirror/view";
import { activate as activateVim } from "@/features/vim";
import { useVimSettings } from "@/features/vim/settings";
import { TextField, type TextFieldHandle } from "./TextField";
const contentOf = (label: string) => {
const el = document.querySelector<HTMLElement>(`[aria-label="${label}"]`);
if (!el) throw new Error("field not rendered");
return el;
};
const viewOf = (label: string): EditorView => {
const view = EditorView.findFromDOM(contentOf(label));
if (!view) throw new Error("not an editor field");
return view;
};
/** Waits until Vim mode's contribution has reached the field (the engine loads lazily). */
const untilVim = async (label: string): Promise<EditorView> => {
const view = viewOf(label);
await vi.waitFor(() => expect(view.dom.getAttribute("data-openidea-vim")).toBeTruthy(), { timeout: 5000 });
return view;
};
/** Parent stores the text, like the commit message store does. */
function renderControlled(label: string, initial: string) {
const onChange = vi.fn();
function Holder() {
const [text, setText] = useState(initial);
return (
<TextField
path="test://field"
ariaLabel={label}
value={text}
onChange={(t) => {
onChange(t);
setText(t);
}}
/>
);
}
render(<Holder />);
return { onChange };
}
/** Parent owns the value outright: rerender replaces it from the outside. */
function renderStatic(label: string, initial: string) {
const onChange = vi.fn();
function Holder({ text }: { text: string }) {
return <TextField path="test://field" ariaLabel={label} value={text} onChange={onChange} />;
}
const { rerender } = render(<Holder text={initial} />);
return { rerender: (next: string) => rerender(<Holder text={next} />) };
}
/** A controlled field exposing the handle, for focus and view assertions. */
function renderHandleField(label: string, initial: string) {
function Holder() {
const [text, setText] = useState(initial);
const ref = useRef<TextFieldHandle>(null);
return (
<>
<TextField path="test://field" ariaLabel={label} value={text} onChange={setText} ref={ref} />
<button onClick={() => ref.current?.focus()}>focus field</button>
</>
);
}
render(<Holder />);
}
afterEach(() => {
useVimSettings.setState({ enabled: false, handlers: {} }, true);
});
describe("TextField", () => {
it("is a focusable editor textbox that reports typed text", () => {
const { onChange } = renderControlled("Field", "");
const view = viewOf("Field");
expect(contentOf("Field").getAttribute("role")).toBe("textbox");
act(() => {
view.focus();
view.dispatch(view.state.replaceSelection("typed"), { userEvent: "input.type" });
});
expect(view.state.doc.toString()).toBe("typed");
expect(onChange).toHaveBeenLastCalledWith("typed");
});
it("follows an external value change", () => {
const { rerender } = renderStatic("Field", "first");
const view = viewOf("Field");
expect(view.state.doc.toString()).toBe("first");
rerender("second");
expect(view.state.doc.toString()).toBe("second");
});
it("keeps the focus in the field while Vim is off and Esc still leaves it", () => {
renderHandleField("Field", "text");
const view = viewOf("Field");
act(() => view.focus());
expect(document.activeElement).toBe(view.contentDOM);
fireEvent.keyDown(view.contentDOM, { key: "Escape" });
expect(document.activeElement).not.toBe(view.contentDOM);
});
it("with Vim mode on, Esc leaves Insert mode and keeps the focus in the field", async () => {
useVimSettings.setState({ enabled: true, handlers: {} }, true);
const disposeVim = activateVim();
try {
renderHandleField("Field", "hello");
const view = await untilVim("Field");
act(() => view.focus());
fireEvent.keyDown(view.contentDOM, { key: "i" });
expect(view.dom.getAttribute("data-vim-mode")).toBe("insert");
fireEvent.keyDown(view.contentDOM, { key: "Escape" });
expect(view.dom.getAttribute("data-vim-mode")).toBe("normal");
expect(document.activeElement).toBe(view.contentDOM);
} finally {
disposeVim();
}
});
it("with Vim mode on, a further Esc in Normal mode returns the focus (explicit)", async () => {
useVimSettings.setState({ enabled: true, handlers: {} }, true);
const disposeVim = activateVim();
try {
renderHandleField("Field", "hello");
const view = await untilVim("Field");
act(() => view.focus());
fireEvent.keyDown(view.contentDOM, { key: "i" });
fireEvent.keyDown(view.contentDOM, { key: "Escape" });
expect(view.dom.getAttribute("data-vim-mode")).toBe("normal");
fireEvent.keyDown(view.contentDOM, { key: "Escape" });
expect(document.activeElement).not.toBe(view.contentDOM);
} finally {
disposeVim();
}
});
it("with Vim mode on, operators edit the field's text (dd)", async () => {
useVimSettings.setState({ enabled: true, handlers: {} }, true);
const disposeVim = activateVim();
try {
const { onChange } = renderControlled("Field", "subject\nbody");
const view = await untilVim("Field");
act(() => {
view.focus();
view.dispatch({ selection: { anchor: 0 } });
});
fireEvent.keyDown(view.contentDOM, { key: "d" });
fireEvent.keyDown(view.contentDOM, { key: "d" });
expect(view.state.doc.toString()).toBe("body");
expect(onChange).toHaveBeenLastCalledWith("body");
} finally {
disposeVim();
}
});
});
+194
Переглянути файл
@@ -0,0 +1,194 @@
/**
* A multi-line text field built on the code editor: Vim and every other `embedded`
* editor contribution apply through the shared embedded-editor mechanism
* (`embeddedEditorExtensions`) and are reconfigured live, so with Vim mode on
* `Esc` goes to Vim first and only moves the focus when Vim does not use it.
* The commit message field is the first user (#7024).
*/
import { forwardRef, useImperativeHandle, useLayoutEffect, useRef, type CSSProperties, type RefObject } from "react";
import { Annotation, Compartment, EditorState } from "@codemirror/state";
import { EditorView, keymap, placeholder as cmPlaceholder } from "@codemirror/view";
import { defaultKeymap, history } from "@codemirror/commands";
import { embeddedEditorExtensions } from "./api";
/** Marks a transaction the field itself made (an external value or a host echo): no `onChange`. */
export const fieldEcho = Annotation.define<boolean>();
/** Created once: every `EditorView.theme` call mounts new CSS rules into the document. */
const FIELD_THEME = EditorView.theme({
"&": { height: "100%", backgroundColor: "transparent" },
".cm-scroller": {
backgroundColor: "transparent",
fontFamily: "inherit",
fontWeight: "inherit",
lineHeight: "inherit",
},
".cm-content": { padding: "6px var(--pad, 10px)" },
".cm-line": { padding: "0" },
".cm-placeholder": {
color: "var(--fg-subtle)",
fontFamily: "var(--font-ui)",
fontSize: "var(--fs-ui)",
},
});
export interface TextFieldHandle {
focus(): void;
/** The live editor view, null before mount and after unmount. */
view(): EditorView | null;
}
export interface TextFieldProps {
value: string;
/** Text typed or deleted in the field; not called for the field's own echo transactions. */
onChange: (text: string, view: EditorView) => void;
/** A stable pseudo document path; embedded editor contributions and their events use it. */
path: string;
placeholder?: string;
ariaLabel?: string;
spellCheck?: boolean;
/** Marks the editor as its tool window's late-focus target (`data-autofocus`). */
autoFocus?: boolean;
/** Whether long lines wrap (a textarea-like field always does). */
wrap?: boolean;
/** Reported on the editor as `aria-invalid` (a failed check at the field). */
invalid?: boolean;
/** The editor's content lost the focus. */
onBlur?: () => void;
/** Runs after Vim has had the key; return true when the key was handled. */
onKeyDown?: (event: KeyboardEvent, view: EditorView) => boolean | void;
className?: string;
style?: CSSProperties;
/** Receives the host element, to anchor popups at the field. */
hostRef?: RefObject<HTMLDivElement | null>;
}
/** A controlled editor field; see the module comment. */
export const TextField = forwardRef<TextFieldHandle, TextFieldProps>(function TextField(
{
value,
onChange,
path,
placeholder,
ariaLabel,
spellCheck,
autoFocus,
wrap = true,
invalid,
onBlur,
onKeyDown,
className,
style,
hostRef,
},
ref,
) {
const host = useRef<HTMLDivElement>(null);
const view = useRef<EditorView | null>(null);
const wrapCompartment = useRef(new Compartment());
// The handlers change every render; the view is built once and reads them through refs.
const onChangeRef = useRef(onChange);
onChangeRef.current = onChange;
const onKeyDownRef = useRef(onKeyDown);
onKeyDownRef.current = onKeyDown;
const onBlurRef = useRef(onBlur);
onBlurRef.current = onBlur;
const valueRef = useRef(value);
valueRef.current = value;
useLayoutEffect(() => {
if (!host.current) return;
const editor = new EditorView({
parent: host.current,
state: EditorState.create({
doc: valueRef.current,
extensions: [
FIELD_THEME,
history(),
keymap.of(defaultKeymap),
wrapCompartment.current.of(wrap ? EditorView.lineWrapping : []),
...(placeholder ? [cmPlaceholder(placeholder)] : []),
embeddedEditorExtensions(path),
EditorView.updateListener.of((update) => {
if (!update.docChanged) return;
if (update.transactions.some((tr) => tr.annotation(fieldEcho))) return;
onChangeRef.current?.(update.state.doc.toString(), update.view);
}),
EditorView.domEventHandlers({
keydown(event, current) {
if (onKeyDownRef.current && onKeyDownRef.current(event, current) === true) return true;
// Vim had the key first (its handlers run at highest precedence);
// only an Escape Vim does not use moves the focus, as the textarea's did.
if (event.key === "Escape" && !event.defaultPrevented && !current.composing) {
current.contentDOM.blur();
return true;
}
return false;
},
blur(_event, current) {
// A view being destroyed (unmount, or React re-running the effect) blurs on removal:
// only the live field's blur counts.
if (view.current === current) onBlurRef.current?.();
return false;
},
}),
EditorView.contentAttributes.of({
"aria-label": ariaLabel ?? "",
"aria-multiline": "true",
role: "textbox",
spellcheck: spellCheck ? "true" : "false",
}),
],
}),
});
view.current = editor;
return () => {
view.current = null;
editor.destroy();
};
// The field is created once; `path` identifies it for its lifetime.
// eslint-disable-next-line react-hooks/exhaustive-deps -- placeholder/aria are stable per field
}, []);
useLayoutEffect(() => {
view.current?.dispatch({ effects: wrapCompartment.current.reconfigure(wrap ? EditorView.lineWrapping : []) });
}, [wrap]);
useLayoutEffect(() => {
const editor = view.current;
if (!editor || editor.state.doc.toString() === value) return;
editor.dispatch({
changes: { from: 0, to: editor.state.doc.length, insert: value },
selection: { anchor: value.length },
annotations: fieldEcho.of(true),
});
}, [value]);
// `data-autofocus` moves at runtime (the Commit window takes the activation focus
// only when Commit… asked for the message), like the textarea attribute did. Set before
// paint: the tool window looks for it in the next animation frame.
useLayoutEffect(() => {
const el = view.current?.contentDOM;
if (!el) return;
if (invalid) el.setAttribute("aria-invalid", "true");
else el.removeAttribute("aria-invalid");
if (autoFocus) el.setAttribute("data-autofocus", "true");
else el.removeAttribute("data-autofocus");
}, [invalid, autoFocus]);
useImperativeHandle(ref, () => ({
focus: () => view.current?.focus(),
view: () => view.current,
}));
return (
<div
ref={(el) => {
host.current = el;
if (hostRef) hostRef.current = el;
}}
className={className}
style={style}
/>
);
});
+2 -10
Переглянути файл
@@ -193,16 +193,13 @@
flex: 1;
min-height: 40px;
margin: 0;
padding: 6px var(--pad);
resize: none;
border: 0;
border-top: 1px solid var(--border);
outline: none;
color: var(--fg-strong);
line-height: var(--lh-code);
-webkit-user-select: text;
user-select: text;
/* Right margin guide at the subject length limit. */
/* Right margin guide at the subject length limit; the editor's content
carries the same 6px / var(--pad) padding (src/editor/TextField.tsx). */
background:
linear-gradient(
to right,
@@ -214,11 +211,6 @@
no-repeat,
var(--bg-island, var(--bg-app));
}
.message::placeholder {
color: var(--fg-subtle);
font-family: var(--font-ui);
font-size: var(--fs-ui);
}
.commitAuthor {
display: flex;
align-items: baseline;
+37 -23
Переглянути файл
@@ -18,6 +18,8 @@ import {
} from "react";
import { tx, txPart, txTemplate } from "@/platform/i18n";
import clsx from "clsx";
import { EditorSelection } from "@codemirror/state";
import { TextField, fieldEcho, type TextFieldHandle } from "@/editor/TextField";
import { executeAction } from "@/platform/actions";
import { fontWeightOf } from "@/platform/editorSettings";
import { resolveMonoFont } from "@/platform/fonts";
@@ -1562,7 +1564,8 @@ export function CommitMessageField({
const amend = useCommit((s) => s.amend);
const focusTick = useCommit((s) => s.focusTick);
const messageFocus = useCommit((s) => s.messageFocus);
const ref = useRef<HTMLTextAreaElement>(null);
const field = useRef<TextFieldHandle>(null);
const fieldAnchor = useRef<HTMLDivElement>(null);
const [historyOpen, setHistoryOpen] = useState(false);
const historyTick = useCommit((s) => s.historyTick);
const { emptyError } = runner;
@@ -1570,7 +1573,7 @@ export function CommitMessageField({
const hasAvailableRepo = useVcs((s) => s.roots.length > 0 || s.unavailableRoots.length === 0);
useEffect(() => {
if (focusTick) ref.current?.focus();
if (focusTick) field.current?.focus();
}, [focusTick]);
// Show Commit Message History (⌃M) asks through the store.
const [seenHistoryTick, setSeenHistoryTick] = useState(historyTick);
@@ -1613,7 +1616,7 @@ export function CommitMessageField({
<Popup
open={historyOpen}
onClose={() => setHistoryOpen(false)}
anchor={ref}
anchor={fieldAnchor}
placement="top-start"
offset={3}
role="presentation"
@@ -1631,7 +1634,7 @@ export function CommitMessageField({
verbatim: true,
run: () => {
useCommit.setState({ message: m });
ref.current?.focus();
field.current?.focus();
},
}))}
/>
@@ -1644,14 +1647,12 @@ export function CommitMessageField({
</span>
)}
</div>
<textarea
ref={ref}
data-autofocus={!focusOnRequest || messageFocus || undefined}
onBlur={() => {
if (useCommit.getState().messageFocus) useCommit.setState({ messageFocus: false });
}}
<TextField
ref={field}
hostRef={fieldAnchor}
path="openidea://commit-message"
className={clsx(styles.message, !showMargin && styles.noMargin, emptyError && styles.messageError)}
aria-invalid={emptyError || undefined}
invalid={emptyError}
style={{
["--guide" as string]: `${margin}ch`,
...messageFont,
@@ -1659,23 +1660,34 @@ export function CommitMessageField({
}}
value={message}
placeholder={tx("Commit Message")}
aria-label={tx("Commit message")}
ariaLabel={tx("Commit message")}
spellCheck
onChange={(e) => {
const el = e.target;
autoFocus={!focusOnRequest || messageFocus || false}
onBlur={() => {
if (useCommit.getState().messageFocus) useCommit.setState({ messageFocus: false });
}}
wrap
onChange={(text, view) => {
const wrapped =
cfg.limitBody && cfg.wrapAtMargin ? wrapAtMargin(el.value, el.selectionStart, cfg.bodyLimit) : null;
useCommit.setState({ message: wrapped?.text ?? el.value });
cfg.limitBody && cfg.wrapAtMargin
? wrapAtMargin(text, view.state.selection.main.head, cfg.bodyLimit)
: null;
useCommit.setState({ message: wrapped?.text ?? text });
runner.clearEmptyError();
if (wrapped) requestAnimationFrame(() => el.setSelectionRange(wrapped.caret, wrapped.caret));
if (wrapped)
view.dispatch({
changes: { from: 0, to: view.state.doc.length, insert: wrapped.text },
selection: EditorSelection.cursor(wrapped.caret),
annotations: fieldEcho.of(true),
});
}}
onKeyDown={(e) => {
if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
e.preventDefault();
if (runner.canCommit) void runner.run(e.altKey);
} else if (e.key === "Escape") {
e.currentTarget.blur();
return true;
}
return false;
}}
/>
{emptyError && (
@@ -1694,12 +1706,14 @@ export function CommitMessageField({
type="button"
className={styles.inspectionFix}
onClick={() => {
const el = ref.current;
const caret = el ? el.selectionStart + (el.selectionStart > first.length ? 1 : 0) : 0;
const view = field.current?.view();
const head = view?.state.selection.main.head ?? 0;
const caret = head + (head > first.length ? 1 : 0);
useCommit.setState({ message: addBlankLineAfterSubject(message) });
requestAnimationFrame(() => {
el?.focus();
el?.setSelectionRange(caret, caret);
field.current?.focus();
const editor = field.current?.view();
editor?.dispatch({ selection: EditorSelection.cursor(Math.min(caret, editor.state.doc.length)) });
});
}}
>
+111
Переглянути файл
@@ -0,0 +1,111 @@
/** The commit message field on an editor: Vim works in it, Esc goes to Vim first (#7024). */
import { act, fireEvent, render } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { EditorView } from "@codemirror/view";
import { activate as activateVim } from "@/features/vim";
import { useVimSettings } from "@/features/vim/settings";
import { CommitMessageField, type CommitRunner } from "../CommitView";
import { useCommit } from "../commitStore";
import { useVcs } from "../store";
const runnerOf = (): CommitRunner & { run: (push: boolean) => Promise<void> } => ({
emptyError: false,
clearEmptyError: vi.fn(),
canCommit: true,
run: vi.fn(async () => {}),
});
const contentOf = () => {
const el = document.querySelector<HTMLElement>('[aria-label="Commit message"]');
if (!el) throw new Error("message field not rendered");
return el;
};
const viewOf = (): EditorView => {
const view = EditorView.findFromDOM(contentOf());
if (!view) throw new Error("message field is not an editor");
return view;
};
/** Waits until Vim mode's contribution has reached the field (the engine loads lazily). */
const untilVim = async (): Promise<EditorView> => {
const view = viewOf();
await vi.waitFor(() => expect(view.dom.getAttribute("data-openidea-vim")).toBeTruthy(), { timeout: 5000 });
return view;
};
describe("Commit message field on an editor (#7024)", () => {
beforeEach(() => {
localStorage.clear();
useVcs.setState({ available: true, root: "/p", repo: "/p", roots: ["/p"], status: [] });
useCommit.setState({ message: "", amend: false, amendPreview: null, author: "" });
});
afterEach(() => {
useVimSettings.setState({ enabled: false, handlers: {} }, true);
});
it("is an editor textbox with the field's name and placeholder", () => {
render(<CommitMessageField runner={runnerOf()} />);
expect(contentOf().getAttribute("role")).toBe("textbox");
expect(contentOf().getAttribute("placeholder")).toBeNull();
expect(document.querySelector(".cm-placeholder")?.textContent).toBe("Commit Message");
});
it("with Vim mode off, Esc leaves the field for the editor, as before", () => {
const runner = runnerOf();
render(<CommitMessageField runner={runner} />);
const view = viewOf();
act(() => view.focus());
expect(document.activeElement).toBe(view.contentDOM);
fireEvent.keyDown(view.contentDOM, { key: "Escape" });
expect(document.activeElement).not.toBe(view.contentDOM);
});
it("Meta+Enter commits from the field", () => {
const runner = runnerOf();
render(<CommitMessageField runner={runner} />);
const view = viewOf();
act(() => view.focus());
fireEvent.keyDown(view.contentDOM, { key: "Enter", metaKey: true });
expect(runner.run).toHaveBeenCalledWith(false);
});
it("with Vim mode on, Esc leaves Insert mode in the field and keeps the focus", async () => {
useVimSettings.setState({ enabled: true, handlers: {} }, true);
const dispose = activateVim();
try {
act(() => useCommit.setState({ message: "hello" }));
render(<CommitMessageField runner={runnerOf()} />);
const view = await untilVim();
act(() => view.focus());
fireEvent.keyDown(view.contentDOM, { key: "i" });
expect(view.dom.getAttribute("data-vim-mode")).toBe("insert");
fireEvent.keyDown(view.contentDOM, { key: "Escape" });
expect(view.dom.getAttribute("data-vim-mode")).toBe("normal");
expect(document.activeElement).toBe(view.contentDOM);
// An operator acts on the message itself (dd deletes the first line).
fireEvent.keyDown(view.contentDOM, { key: "d" });
fireEvent.keyDown(view.contentDOM, { key: "d" });
expect(useCommit.getState().message).toBe("");
} finally {
dispose();
}
});
it("with Vim mode on, a further Esc in Normal mode returns the focus to the editor", async () => {
useVimSettings.setState({ enabled: true, handlers: {} }, true);
const dispose = activateVim();
try {
render(<CommitMessageField runner={runnerOf()} />);
const view = await untilVim();
act(() => view.focus());
fireEvent.keyDown(view.contentDOM, { key: "i" });
fireEvent.keyDown(view.contentDOM, { key: "Escape" });
expect(document.activeElement).toBe(view.contentDOM);
fireEvent.keyDown(view.contentDOM, { key: "Escape" });
expect(document.activeElement).not.toBe(view.contentDOM);
} finally {
dispose();
}
});
});
+5 -3
Переглянути файл
@@ -94,7 +94,7 @@ describe("Commit tool window Preview Diff (#1599)", () => {
// Side by side with the changes: the splitter between the panels is vertical.
expect(previewHandle()).toBeTruthy();
expect(screen.getByTestId("diff-preview")).toHaveAttribute("data-path", "/p/a.ts");
expect(screen.getByPlaceholderText("Commit Message")).toBeTruthy();
expect(screen.getByText("Commit Message")).toBeTruthy();
});
it("previews the selected file and follows the selection", () => {
@@ -118,7 +118,7 @@ describe("Commit tool window Preview Diff (#1599)", () => {
act(() => setCommitDiffPreview(true));
expect(screen.getByTestId("diff-preview")).toBeTruthy();
expect(screen.getByRole("tree", { name: "Changes" })).toBeTruthy();
expect(screen.getByPlaceholderText("Commit Message")).toBeTruthy();
expect(screen.getByText("Commit Message")).toBeTruthy();
expect(screen.getByRole("button", { name: "Commit" })).toBeTruthy();
});
@@ -181,7 +181,9 @@ it("follows the active working diff without following other revisions or taking
status: [modified("/p/a.ts"), modified("/p/b.ts")],
});
render(<CommitToolWindow />);
const message = screen.getByPlaceholderText("Commit Message");
// The field is an editor; its focusable element is the CodeMirror content.
const message = document.querySelector<HTMLElement>('[aria-label="Commit message"]');
if (!message) throw new Error("message field not rendered");
message.focus();
act(() => editor.follow?.(diffInput(workingDiffData("/p/b.ts"))));
expect(useCommit.getState().selection).toEqual(["/p/b.ts"]);
+12
Переглянути файл
@@ -166,4 +166,16 @@ describe("keyboard dispatcher with Vim mode", () => {
expect(esc).toHaveBeenCalledOnce();
expect(e.defaultPrevented).toBe(false);
});
it("leaves Escape to a Vim field of a tool window until it is in Normal mode", async () => {
document.body.innerHTML = `<section data-toolwindow="commit"><div class="cm-editor" ${VIM_EDITOR_ATTR}="true" ${VIM_MODE_ATTR}="insert"><div class="cm-content" tabindex="0"></div></div></section>`;
const field = document.querySelector<HTMLElement>(".cm-content")!;
press(field, "Escape", { key: "Escape" });
await Promise.resolve();
expect(esc).not.toHaveBeenCalled();
field.parentElement!.setAttribute(VIM_MODE_ATTR, "normal");
press(field, "Escape", { key: "Escape" });
await Promise.resolve();
expect(esc).toHaveBeenCalledOnce();
});
});
+12 -1
Переглянути файл
@@ -167,6 +167,16 @@ function lookupStroke(
return !!view && completionStatus(view.state) === "active";
}
/**
* Escape in a Vim field of a tool window (the commit message) outside Normal mode: Vim leaves
* Insert or Visual mode, as in the editor, before the tool window's Escape (Focus Editor) can move
* the focus. In Normal mode the tool window keeps it.
*/
function toolWindowEscape(e: KeyboardEvent, stroke: string, mode: string | null): boolean {
if (normalizeBinding(stroke) !== "Escape" || !mode || mode === "normal") return false;
return !!(e.target as Element | null)?.closest?.("[data-toolwindow]");
}
/**
* Dispatcher claim: keystrokes whose handler is Vim go to a focused Vim editor. A stroke the
* mode gives to the IDE is claimed too: the editor runs that IDE action itself, so an unrelated
@@ -181,7 +191,8 @@ export function vimKeyClaim(settings: () => VimSettings): KeyClaim {
inVimEditor(e.target) &&
(handlerFor(stroke, s.handlers, mode) === "vim" ||
modeMovedToIde(stroke, s.handlers, mode) ||
lookupStroke(e, stroke, s.handlers, mode))
lookupStroke(e, stroke, s.handlers, mode) ||
toolWindowEscape(e, stroke, mode))
);
};
}