diff --git a/docs/en/guide/vim.mdx b/docs/en/guide/vim.mdx index 9b076a5153..f8472207a5 100644 --- a/docs/en/guide/vim.mdx +++ b/docs/en/guide/vim.mdx @@ -13,7 +13,7 @@ Use any of these: - The **Vim** widget in the status bar: click it and check **Enabled**. - **Settings › Editor › Vim** › **Enable Vim emulation**. -The setting applies to every editor in every window right away and is remembered across restarts. While Vim mode is on, the status bar widget shows the current mode: `NORMAL`, `INSERT`, `VISUAL`, `V-LINE`, `V-BLOCK` or `REPLACE`. +The setting applies to every editor in every window right away and is remembered across restarts. It also applies to the commit message and to GitHub pull request comment and review fields; there, Escape first leaves Insert or Visual mode, and an Escape in Normal mode does what it does without Vim (leave the field, cancel the comment). While Vim mode is on, the status bar widget shows the current mode: `NORMAL`, `INSERT`, `VISUAL`, `V-LINE`, `V-BLOCK` or `REPLACE`. ## What works diff --git a/docs/zh/guide/vim.mdx b/docs/zh/guide/vim.mdx index 5a1d918c85..092f904d34 100644 --- a/docs/zh/guide/vim.mdx +++ b/docs/zh/guide/vim.mdx @@ -13,7 +13,7 @@ OpenIDEA 内置了 Vim 模拟,参照的是 IntelliJ IDEA 的 IdeaVim 插件。 - 状态栏的 **Vim** 微件:单击后勾选 **已启用**。 - **设置 › 编辑器 › Vim** › **启用 Vim 模拟**。 -设置会立即应用到所有窗口的所有编辑器,重启后保持不变。Vim 模式开启时,状态栏微件显示当前模式:`NORMAL`、`INSERT`、`VISUAL`、`V-LINE`、`V-BLOCK` 或 `REPLACE`。 +设置会立即应用到所有窗口的所有编辑器,重启后保持不变。提交消息和 GitHub 拉取请求的评论、评审输入框也使用 Vim 模式:在这些输入框里 Escape 先退出插入或可视模式,在普通模式下再按 Escape 则和未开 Vim 时一样(离开输入框或取消评论)。Vim 模式开启时,状态栏微件显示当前模式:`NORMAL`、`INSERT`、`VISUAL`、`V-LINE`、`V-BLOCK` 或 `REPLACE`。 ## 支持哪些功能 diff --git a/e2e/submitReviewLayout.spec.ts b/e2e/submitReviewLayout.spec.ts index ab7c6a013d..4d381ce9ee 100644 --- a/e2e/submitReviewLayout.spec.ts +++ b/e2e/submitReviewLayout.spec.ts @@ -1,5 +1,5 @@ import type { Page } from "@playwright/test"; -import { expect, ipcCalls, stubDesktop, test } from "./fixtures"; +import { expect, fieldText, ipcCalls, stubDesktop, test } from "./fixtures"; async function seedReview(page: Page) { await stubDesktop(page); @@ -75,11 +75,11 @@ test("centers the unanchored composer, follows the editor font and reflows its r const comment = (await popup.getByRole("button", { name: "Comment", exact: true }).boundingBox())!; expect(comment.y).toBeGreaterThan(approve.y); expect(comment.x + comment.width).toBeLessThan(300); - await expect(editor).toHaveValue("Please double-check the rounding step."); + await expect.poll(() => fieldText(editor)).toBe("Please double-check the rounding step."); await editor.press("Escape"); await expect(popup).toHaveCount(0); await openReview(page); - await expect(editor).toHaveValue("Please double-check the rounding step."); + await expect.poll(() => fieldText(editor)).toBe("Please double-check the rounding step."); }); test("keeps anchored review controls and the comment visible after a long submission error", async ({ @@ -109,7 +109,7 @@ test("keeps anchored review controls and the comment visible after a long submis const error = popup.getByRole("alert"); await expect(error).toContainText("Review request failed."); await expect(button).toBeEnabled(); - await expect(editor).toHaveValue("Check the batch limit."); + await expect.poll(() => fieldText(editor)).toBe("Check the batch limit."); const box = (await popup.boundingBox())!; const buttonBox = (await button.boundingBox())!; expect(box.y + box.height).toBeLessThan(350); diff --git a/src/editor/TextField.test.tsx b/src/editor/TextField.test.tsx index 573ed48664..719f13438c 100644 --- a/src/editor/TextField.test.tsx +++ b/src/editor/TextField.test.tsx @@ -158,4 +158,66 @@ describe("TextField", () => { disposeVim(); } }); + + it("takes no edits while read-only, and reports caret moves that don't change the text", () => { + const onSelectionChange = vi.fn(); + function Holder({ readOnly }: { readOnly: boolean }) { + const [text, setText] = useState("hello"); + return ( + + ); + } + const { rerender } = render(); + const view = viewOf("Field"); + act(() => view.dispatch({ selection: { anchor: 2 } })); + expect(onSelectionChange).toHaveBeenCalledWith(2, view); + rerender(); + expect(view.state.readOnly).toBe(true); + expect(contentOf("Field").getAttribute("contenteditable")).toBe("false"); + rerender(); + expect(view.state.readOnly).toBe(false); + }); + + it("with Vim mode on, gives a key to onKeyDownFirst before Vim and to onKeyDown after it", async () => { + useVimSettings.setState({ enabled: true, handlers: {} }, true); + const disposeVim = activateVim(); + const first = vi.fn((e: KeyboardEvent) => e.key === "ArrowDown"); + const after = vi.fn((_e: KeyboardEvent) => false); + try { + function Holder() { + const [text, setText] = useState("one\ntwo"); + return ( + + ); + } + render(); + const view = await untilVim("Field"); + act(() => view.focus()); + act(() => view.dispatch({ selection: { anchor: 0 } })); + fireEvent.keyDown(view.contentDOM, { key: "ArrowDown" }); + expect(first).toHaveBeenCalledTimes(1); + expect(view.state.selection.main.head).toBe(0); + 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(after.mock.calls.some(([e]) => e.key === "Escape" && !e.defaultPrevented)).toBe(false); + } finally { + disposeVim(); + } + }); }); diff --git a/src/editor/TextField.tsx b/src/editor/TextField.tsx index 0a702e2d12..b1fe926414 100644 --- a/src/editor/TextField.tsx +++ b/src/editor/TextField.tsx @@ -6,7 +6,7 @@ * 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 { Annotation, Compartment, EditorState, Prec } from "@codemirror/state"; import { EditorView, keymap, placeholder as cmPlaceholder } from "@codemirror/view"; import { defaultKeymap, history } from "@codemirror/commands"; import { embeddedEditorExtensions } from "./api"; @@ -32,6 +32,9 @@ const FIELD_THEME = EditorView.theme({ }, }); +const readOnlyExtension = (readOnly: boolean) => + readOnly ? [EditorState.readOnly.of(true), EditorView.editable.of(false)] : []; + export interface TextFieldHandle { focus(): void; /** The live editor view, null before mount and after unmount. */ @@ -57,6 +60,12 @@ export interface TextFieldProps { onBlur?: () => void; /** Runs after Vim has had the key; return true when the key was handled. */ onKeyDown?: (event: KeyboardEvent, view: EditorView) => boolean | void; + /** Runs before Vim and the editor's keys (a completion list open at the field); true when handled. */ + onKeyDownFirst?: (event: KeyboardEvent, view: EditorView) => boolean | void; + /** The caret moved without the text changing. */ + onSelectionChange?: (head: number, view: EditorView) => void; + /** No editing (a request in flight); the text stays selectable. */ + readOnly?: boolean; className?: string; style?: CSSProperties; /** Receives the host element, to anchor popups at the field. */ @@ -77,6 +86,9 @@ export const TextField = forwardRef(function Te invalid, onBlur, onKeyDown, + onKeyDownFirst, + onSelectionChange, + readOnly = false, className, style, hostRef, @@ -86,11 +98,16 @@ export const TextField = forwardRef(function Te const host = useRef(null); const view = useRef(null); const wrapCompartment = useRef(new Compartment()); + const readOnlyCompartment = 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 onKeyDownFirstRef = useRef(onKeyDownFirst); + onKeyDownFirstRef.current = onKeyDownFirst; + const onSelectionChangeRef = useRef(onSelectionChange); + onSelectionChangeRef.current = onSelectionChange; const onBlurRef = useRef(onBlur); onBlurRef.current = onBlur; const valueRef = useRef(value); @@ -107,10 +124,19 @@ export const TextField = forwardRef(function Te history(), keymap.of(defaultKeymap), wrapCompartment.current.of(wrap ? EditorView.lineWrapping : []), + readOnlyCompartment.current.of(readOnlyExtension(readOnly)), + Prec.highest( + EditorView.domEventHandlers({ + keydown: (event, current) => onKeyDownFirstRef.current?.(event, current) === true, + }), + ), ...(placeholder ? [cmPlaceholder(placeholder)] : []), embeddedEditorExtensions(path), EditorView.updateListener.of((update) => { - if (!update.docChanged) return; + if (!update.docChanged) { + if (update.selectionSet) onSelectionChangeRef.current?.(update.state.selection.main.head, update.view); + return; + } if (update.transactions.some((tr) => tr.annotation(fieldEcho))) return; onChangeRef.current?.(update.state.doc.toString(), update.view); }), @@ -154,6 +180,10 @@ export const TextField = forwardRef(function Te view.current?.dispatch({ effects: wrapCompartment.current.reconfigure(wrap ? EditorView.lineWrapping : []) }); }, [wrap]); + useLayoutEffect(() => { + view.current?.dispatch({ effects: readOnlyCompartment.current.reconfigure(readOnlyExtension(readOnly)) }); + }, [readOnly]); + useLayoutEffect(() => { const editor = view.current; if (!editor || editor.state.doc.toString() === value) return; diff --git a/src/features/github/details/Details.module.css b/src/features/github/details/Details.module.css index daab5a1d6c..9fcf8504bd 100644 --- a/src/features/github/details/Details.module.css +++ b/src/features/github/details/Details.module.css @@ -469,22 +469,26 @@ align-items: center; gap: var(--space-1); } +/* An editor (`src/editor/TextField.tsx`) filling the popup's free height. */ .submitEditor { flex: 1; min-height: 40px; - padding: var(--space-1) var(--space-2); + overflow: hidden; border: 1px solid var(--border); border-radius: var(--radius-control); background: var(--bg-input); color: var(--fg); - font: inherit; line-height: var(--lh-code); - resize: none; - outline: none; } -.submitEditor:focus { +.submitEditor:focus-within { border-color: var(--focus-ring); } +.submitEditor :global(.cm-content) { + padding: var(--space-1) var(--space-2); +} +.submitEditor :global(.cm-editor.cm-focused) { + outline: none; +} .submitError { flex: 0 1 auto; min-height: 0; diff --git a/src/features/github/details/SubmitReviewPopup.tsx b/src/features/github/details/SubmitReviewPopup.tsx index 789116462a..1c3fc8ecc9 100644 --- a/src/features/github/details/SubmitReviewPopup.tsx +++ b/src/features/github/details/SubmitReviewPopup.tsx @@ -6,6 +6,7 @@ * it, or centred in the window. 500×200, resizable. */ import { useEffect, useState } from "react"; +import { TextField } from "@/editor/TextField"; import { Button, IconButton, Popup, Spinner, T } from "@/ui"; import { resolveMonoFont } from "@/platform/fonts"; import { useTx, tx } from "@/platform/i18n"; @@ -129,20 +130,23 @@ function SubmitReview(props: { number: number; draftKey: string; anchor: Element - { + onChange={(value) => { setError(null); - setReviewText(draftKey, e.target.value); + setReviewText(draftKey, value); }} /> {error && ( diff --git a/src/features/github/details/details.test.tsx b/src/features/github/details/details.test.tsx index 361d0a5afa..cb8cce699e 100644 --- a/src/features/github/details/details.test.tsx +++ b/src/features/github/details/details.test.tsx @@ -18,6 +18,7 @@ import { ReviewActions } from "./ReviewActions"; import { useReviewText } from "./state"; import { StatusSection } from "./StatusSection"; import { showSubmitReview } from "./SubmitReviewPopup"; +import { fieldValue, setFieldText } from "@/test/editorField"; const me: GHUser = { __typename: "User", id: "U1", login: "me", url: "", avatarUrl: "", name: null }; const bob: GHUser = { __typename: "User", id: "U2", login: "bob", url: "", avatarUrl: "", name: "Bob" }; @@ -188,7 +189,7 @@ describe("ReviewActions", () => { }); describe("Submit Review draft", () => { - const editor = () => screen.getByRole("textbox", { name: "Review comment" }); + const editor = () => screen.getByRole("textbox", { name: "Review comment" }); const close = () => fireEvent.click(screen.getByRole("button", { name: "Close" })); function open(number: number) { @@ -217,11 +218,11 @@ describe("Submit Review draft", () => { render(); open(7); - fireEvent.change(editor(), { target: { value: "Draft for org/app #7" } }); + setFieldText(editor(), "Draft for org/app #7"); close(); open(8); - expect(editor().value).toBe(""); + expect(fieldValue(editor())).toBe(""); close(); act(() => { @@ -234,17 +235,17 @@ describe("Submit Review draft", () => { }); }); open(7); - const otherRepositoryDraft = editor().value; + const otherRepositoryDraft = fieldValue(editor()); close(); act(() => useGhRepository.setState({ connection: { ...connection, currentUser: bob } })); open(7); - const otherAccountDraft = editor().value; + const otherAccountDraft = fieldValue(editor()); close(); act(() => useGhRepository.setState({ connection })); open(7); - const restoredDraft = editor().value; + const restoredDraft = fieldValue(editor()); close(); expect(otherRepositoryDraft).toBe(""); @@ -256,7 +257,7 @@ describe("Submit Review draft", () => { const connection = useGhRepository.getState().connection!; render(); open(7); - fireEvent.change(editor(), { target: { value: "Draft for me" } }); + setFieldText(editor(), "Draft for me"); act(() => useGhRepository.setState({ connection: { ...connection, currentUser: bob } })); const remainingEditor = screen.queryByRole("textbox", { name: "Review comment" }); diff --git a/src/features/github/diff/reviewDiff.test.tsx b/src/features/github/diff/reviewDiff.test.tsx index 02d2e5345d..0a9e65cfac 100644 --- a/src/features/github/diff/reviewDiff.test.tsx +++ b/src/features/github/diff/reviewDiff.test.tsx @@ -36,6 +36,7 @@ import { activateReviewDiff } from "."; import { clearNewComments, requestNewComment, useNewComments } from "./newComments"; import { newCommentLocation } from "./model"; import { setReviewDiffSettings, useReviewDiffSettings } from "./settings"; +import { setFieldText } from "@/test/editorField"; const N = 7; const PATH = "src/a.ts"; @@ -242,7 +243,7 @@ describe("review threads in a pull request diff", () => { await waitFor(() => expect(inlay("T1")).not.toBeNull()); const t1 = within(inlay("T1")!); fireEvent.click(t1.getByRole("button", { name: "Reply" })); - fireEvent.change(t1.getByRole("textbox"), { target: { value: "thanks" } }); + setFieldText(t1.getByRole("textbox"), "thanks"); const replies = t1.getAllByRole("button", { name: "Reply" }); fireEvent.click(replies[replies.length - 1]!); await waitFor(() => @@ -269,7 +270,7 @@ describe("new comments", () => { expect(document.querySelector(".cm-reviewHandle")?.title).toBe( "Drag to select several lines for commenting", ); - fireEvent.change(within(box).getByRole("textbox"), { target: { value: "Looks odd" } }); + setFieldText(within(box).getByRole("textbox"), "Looks odd"); fireEvent.click(within(box).getByRole("button", { name: "Start Review" })); await waitFor(() => expect(useNewComments.getState().comments).toHaveLength(0)); expect(calls(/addPullRequestReview\s*\(/)).toEqual([ @@ -289,7 +290,7 @@ describe("new comments", () => { const box = await newCommentBox(); // A left-side comment goes into the left pane. expect(document.querySelector(".cm-merge-a")!.contains(box)).toBe(true); - fireEvent.change(within(box).getByRole("textbox"), { target: { value: "hm" } }); + setFieldText(within(box).getByRole("textbox"), "hm"); fireEvent.click(within(box).getByRole("button", { name: "Add Single Comment" })); await waitFor(() => expect(calls(/addPullRequestReview\s*\(/)).toHaveLength(1)); expect(calls(/addPullRequestReview\s*\(/)[0]).toMatchObject({ @@ -310,7 +311,7 @@ describe("new comments", () => { .getAllByRole("button") .map((b) => b.textContent), ).toEqual(["Add Review Comment"]); - fireEvent.change(within(box).getByRole("textbox"), { target: { value: "nit" } }); + setFieldText(within(box).getByRole("textbox"), "nit"); fireEvent.click(within(box).getByRole("button", { name: "Add Review Comment" })); await waitFor(() => expect(calls(/addPullRequestReviewThread/)).toEqual([ @@ -336,7 +337,7 @@ describe("new comments", () => { expect(document.querySelector(".cm-reviewHandle")?.title).toBe( "Comment range cannot be adjusted while reviewing a single commit", ); - fireEvent.change(within(box).getByRole("textbox"), { target: { value: "here" } }); + setFieldText(within(box).getByRole("textbox"), "here"); fireEvent.click(within(box).getByRole("button", { name: "Add Review Comment" })); await waitFor(() => expect(calls(/addPullRequestReviewComment/)).toEqual([ diff --git a/src/features/github/issues/issues.test.tsx b/src/features/github/issues/issues.test.tsx index 3262870f56..d7ce4a57b1 100644 --- a/src/features/github/issues/issues.test.tsx +++ b/src/features/github/issues/issues.test.tsx @@ -21,6 +21,7 @@ import { issueSearchQuery, } from "./model"; import { loadIssueSearchHistory, loadLastIssueSearch } from "./searchHistory"; +import { fieldValue, setFieldText } from "@/test/editorField"; const repo = { owner: "acme", name: "app", host: "code.example" }; const user = (login: string, name: string | null = null): GHUser => ({ @@ -207,13 +208,13 @@ it("keeps a failed comment draft and shows the confirmed comment after retry", a .mockResolvedValueOnce({ id: "comment", body: "Confirmed locally", author: null, createdAt: issue.createdAt }); const { container } = render(); const submit = await screen.findByRole("button", { name: "Comment" }); - const field = container.querySelector("textarea")!; - fireEvent.change(field, { target: { value: "Confirmed locally" } }); + const field = container.querySelector(".cm-content")!; + setFieldText(field, "Confirmed locally"); fireEvent.click(submit); await screen.findByText("Network unavailable"); - expect(field.value).toBe("Confirmed locally"); + expect(fieldValue(field)).toBe("Confirmed locally"); fireEvent.click(submit); - await waitFor(() => expect(field.value).toBe("")); + await waitFor(() => expect(fieldValue(field)).toBe("")); expect(await screen.findByText("Confirmed locally")).toBeTruthy(); expect(post.mock.calls).toEqual([ ["issue-id", "Confirmed locally"], diff --git a/src/features/github/reviewMode/reviewMode.test.tsx b/src/features/github/reviewMode/reviewMode.test.tsx index 65dc6a3ac3..70b655e3be 100644 --- a/src/features/github/reviewMode/reviewMode.test.tsx +++ b/src/features/github/reviewMode/reviewMode.test.tsx @@ -94,6 +94,7 @@ import { import { activateReviewMode } from "."; import { setReviewModeEnabled, useReviewModeSettings } from "./settings"; import { refreshCurrentBranchPullRequest, updateReviewBranch, useReviewBranch } from "./state"; +import { setFieldText } from "@/test/editorField"; const N = 12; const PATH = "src/a.ts"; @@ -753,7 +754,7 @@ describe("review in the editor", () => { .getAllByRole("button") .map((b) => b.textContent), ).toEqual(["Add Single Comment", "Start Review"]); - fireEvent.change(within(box).getByRole("textbox"), { target: { value: "why?" } }); + setFieldText(within(box).getByRole("textbox"), "why?"); fireEvent.click(within(box).getByRole("button", { name: "Add Single Comment" })); await waitFor(() => expect(useNewComments.getState().comments).toHaveLength(0)); expect(calls(/addPullRequestReview\s*\(/)).toEqual([ @@ -776,7 +777,7 @@ describe("review in the editor", () => { expect(useNewComments.getState().comments).toHaveLength(0); act(() => editor.request({ start: 2, end: 4 })); const box = await newCommentBox(); - fireEvent.change(within(box).getByRole("textbox"), { target: { value: "block" } }); + setFieldText(within(box).getByRole("textbox"), "block"); fireEvent.click(within(box).getByRole("button", { name: "Start Review" })); await waitFor(() => expect(calls(/addPullRequestReview\s*\(/)).toHaveLength(1)); expect(calls(/addPullRequestReview\s*\(/)[0]).toEqual({ @@ -797,7 +798,7 @@ describe("review in the editor", () => { .getAllByRole("button") .map((b) => b.textContent), ).toEqual(["Add Review Comment"]); - fireEvent.change(within(box).getByRole("textbox"), { target: { value: "nit" } }); + setFieldText(within(box).getByRole("textbox"), "nit"); fireEvent.click(within(box).getByRole("button", { name: "Add Review Comment" })); await waitFor(() => expect(calls(/addPullRequestReviewThread/)).toEqual([ diff --git a/src/features/github/timeline/comments/CommentEditor.tsx b/src/features/github/timeline/comments/CommentEditor.tsx index 276d33cce0..7f357026fc 100644 --- a/src/features/github/timeline/comments/CommentEditor.tsx +++ b/src/features/github/timeline/comments/CommentEditor.tsx @@ -8,7 +8,10 @@ * replyToComment(n, id, text)} /> */ -import { useEffect, useLayoutEffect, useRef, useState, type KeyboardEvent } from "react"; +import { useEffect, useRef, useState } from "react"; +import { EditorSelection } from "@codemirror/state"; +import type { EditorView } from "@codemirror/view"; +import { TextField, type TextFieldHandle } from "@/editor/TextField"; import { tx, useTx } from "@/platform/i18n"; import { formatBinding, isMacHost } from "@/platform/keymap"; import { Button, Popup } from "@/ui"; @@ -89,22 +92,15 @@ export function CommentEditor({ // The mentionable users load once per repository, on the first editor. const mentionable = useRepositoryList("mentionableUsers").items; const matches = mention ? filterMentions(mentionable, mention.query) : []; - const ref = useRef(null); - const [field, setField] = useState(null); - - // Grow with the text, like IntelliJ's comment field. - useLayoutEffect(() => { - const el = ref.current; - if (!el) return; - el.style.height = "auto"; - el.style.height = `${el.scrollHeight + 2}px`; - }, [text]); + const field = useRef(null); + const [anchor, setAnchor] = useState(null); useEffect(() => { if (!autoFocus) return; - const el = ref.current; - el?.focus(); - el?.setSelectionRange(el.value.length, el.value.length); + const view = field.current?.view(); + if (!view) return; + view.focus(); + view.dispatch({ selection: EditorSelection.cursor(view.state.doc.length) }); }, [autoFocus, focusRequest]); const canSubmit = !busy && (allowEmpty || !!text.trim()); @@ -145,79 +141,89 @@ export function CommentEditor({ }; const pick = (u: GHUser) => { - const el = ref.current; - if (!el || !mention) return; - const r = insertMention(text, mention.start, el.selectionStart, u.login); + const view = field.current?.view(); + if (!view || !mention) return; + const r = insertMention(text, mention.start, view.state.selection.main.head, u.login); setText(r.text); onTextChange?.(r.text); setMention(null); requestAnimationFrame(() => { - el.focus(); - el.setSelectionRange(r.caret, r.caret); + const current = field.current?.view(); + if (!current) return; + current.focus(); + current.dispatch({ selection: EditorSelection.cursor(Math.min(r.caret, current.state.doc.length)) }); }); }; - const onKeyDown = (e: KeyboardEvent) => { - if (mention && matches.length) { - if (e.key === "ArrowDown" || e.key === "ArrowUp") { - e.preventDefault(); - const d = e.key === "ArrowDown" ? 1 : -1; - setActive((a) => (a + d + matches.length) % matches.length); - return; - } - if ((e.key === "Enter" && !e.metaKey && !e.ctrlKey) || e.key === "Tab") { - e.preventDefault(); - pick(matches[Math.min(active, matches.length - 1)]!); - return; - } + // Before Vim and the editor's own keys: the open @mention list takes its navigation keys. + const onKeyDownFirst = (e: KeyboardEvent) => { + if (!mention) return false; + if (matches.length && (e.key === "ArrowDown" || e.key === "ArrowUp")) { + e.preventDefault(); + const d = e.key === "ArrowDown" ? 1 : -1; + setActive((a) => (a + d + matches.length) % matches.length); + return true; + } + if (matches.length && ((e.key === "Enter" && !e.metaKey && !e.ctrlKey) || e.key === "Tab")) { + e.preventDefault(); + pick(matches[Math.min(active, matches.length - 1)]!); + return true; } if (e.key === "Escape") { - if (mention) { - e.preventDefault(); - e.stopPropagation(); - setMention(null); - } else if (onCancel) { - e.preventDefault(); - e.stopPropagation(); - onCancel(); - } - return; + e.preventDefault(); + e.stopPropagation(); + setMention(null); + return true; + } + return false; + }; + + // After Vim: an Escape Vim used (leaving Insert mode) doesn't cancel the comment. + const onKeyDown = (e: KeyboardEvent) => { + if (e.key === "Escape" && !e.defaultPrevented && onCancel) { + e.preventDefault(); + e.stopPropagation(); + onCancel(); + return true; } if (e.key === "Enter" && (isMacHost() ? e.metaKey : e.ctrlKey)) { e.preventDefault(); e.stopPropagation(); void submit(); + return true; } + return false; }; return ( {showAvatar && me && } - - + { - setText(e.target.value); - onTextChange?.(e.target.value); - updateMention(e.target.value, e.target.selectionStart); + readOnly={busy} + spellCheck + placeholder={placeholder ? t(placeholder) : undefined} + ariaLabel={placeholder ? t(placeholder) : t(submitLabel)} + onChange={(value: string, view: EditorView) => { + setText(value); + onTextChange?.(value); + updateMention(value, view.state.selection.main.head); }} - onSelect={(e) => { - const el = e.currentTarget; - if (mention) updateMention(el.value, el.selectionStart); + onSelectionChange={(head: number, view: EditorView) => { + if (mention) updateMention(view.state.doc.toString(), head); }} onBlur={() => setTimeout(() => setMention(null), 150)} + onKeyDownFirst={onKeyDownFirst} onKeyDown={onKeyDown} /> {mention && ( (".cm-editor"); + const view = dom && EditorView.findFromDOM(dom); + if (!view) throw new Error("not an editor-based field"); + return view; +} + +/** Replaces the text of an editor-based field (`src/editor/TextField.tsx`) as typing would. */ +export function setFieldText(field: HTMLElement, text: string) { + const view = viewOf(field); + act(() => { + view.dispatch({ + changes: { from: 0, to: view.state.doc.length, insert: text }, + selection: { anchor: text.length }, + userEvent: "input.type", + }); + }); +} + +/** The text of an editor-based field, as a textarea's value. */ +export function fieldValue(field: HTMLElement): string { + return viewOf(field).state.doc.toString(); +}