diff --git a/e2e/commit.spec.ts b/e2e/commit.spec.ts index 3240dd880d..16984eba5a 100644 --- a/e2e/commit.spec.ts +++ b/e2e/commit.spec.ts @@ -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 "); 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 "); 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 diff --git a/e2e/commitMessageAgent.spec.ts b/e2e/commitMessageAgent.spec.ts index 392aaf3cfa..34a494d752 100644 --- a/e2e/commitMessageAgent.spec.ts +++ b/e2e/commitMessageAgent.spec.ts @@ -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"); }); diff --git a/e2e/fixtures.ts b/e2e/fixtures.ts index 25c8082556..a9a05ec3e5 100644 --- a/e2e/fixtures.ts +++ b/e2e/fixtures.ts @@ -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 { + 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[]> { return page.evaluate((cmd) => window.__ipc.calls.filter((c) => c.cmd === cmd).map((c) => c.args), cmd); } diff --git a/e2e/stagedEditor.spec.ts b/e2e/stagedEditor.spec.ts index 2f54fa1e72..92942e8c85 100644 --- a/e2e/stagedEditor.spec.ts +++ b/e2e/stagedEditor.spec.ts @@ -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"); }); diff --git a/e2e/vcsOperationsLayout.spec.ts b/e2e/vcsOperationsLayout.spec.ts index 9ebe0245f2..6ee62848ed 100644 --- a/e2e/vcsOperationsLayout.spec.ts +++ b/e2e/vcsOperationsLayout.spec.ts @@ -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 }) => { diff --git a/src/editor/TextField.test.tsx b/src/editor/TextField.test.tsx new file mode 100644 index 0000000000..573ed48664 --- /dev/null +++ b/src/editor/TextField.test.tsx @@ -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(`[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 => { + 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 ( + { + onChange(t); + setText(t); + }} + /> + ); + } + render(); + 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 ; + } + const { rerender } = render(); + return { rerender: (next: string) => rerender() }; +} + +/** 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(null); + return ( + <> + + + + ); + } + render(); +} + +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(); + } + }); +}); diff --git a/src/editor/TextField.tsx b/src/editor/TextField.tsx new file mode 100644 index 0000000000..0a702e2d12 --- /dev/null +++ b/src/editor/TextField.tsx @@ -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(); + +/** 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; +} + +/** A controlled editor field; see the module comment. */ +export const TextField = forwardRef(function TextField( + { + value, + onChange, + path, + placeholder, + ariaLabel, + spellCheck, + autoFocus, + wrap = true, + invalid, + onBlur, + onKeyDown, + className, + style, + hostRef, + }, + ref, +) { + const host = useRef(null); + const view = useRef(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 ( +
{ + host.current = el; + if (hostRef) hostRef.current = el; + }} + className={className} + style={style} + /> + ); +}); diff --git a/src/features/vcs/CommitView.module.css b/src/features/vcs/CommitView.module.css index a5c4fc5853..d8aed347c3 100644 --- a/src/features/vcs/CommitView.module.css +++ b/src/features/vcs/CommitView.module.css @@ -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; diff --git a/src/features/vcs/CommitView.tsx b/src/features/vcs/CommitView.tsx index 914358ea02..f86414ba1f 100644 --- a/src/features/vcs/CommitView.tsx +++ b/src/features/vcs/CommitView.tsx @@ -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(null); + const field = useRef(null); + const fieldAnchor = useRef(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({ 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({ )}
-