feat(github): build the pull request comment and review fields on the editor so Vim works in them (#8314)

The pull request timeline and diff-thread comment fields and the Submit Review field use the editor-based TextField the commit message uses, so Vim attaches when Vim mode is on. Escape first leaves Insert or Visual mode, and in Normal mode or with Vim off cancels the comment as before; the @mention list keeps its keys ahead of Vim. TextField gains readOnly, onSelectionChange and onKeyDownFirst.
Цей коміт міститься в:
l0ng-ai authored and GitHub committed 2026-12-06 08:15:44 +08:00
1 джерело 8be62cb895
коміт c2f984720d
14 files changed
+241 -101

No files matched your search

+1 -1
Переглянути файл
@@ -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
+1 -1
Переглянути файл
@@ -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`。
## 支持哪些功能
+4 -4
Переглянути файл
@@ -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);
+62
Переглянути файл
@@ -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 (
<TextField
path="test://field"
ariaLabel="Field"
value={text}
onChange={setText}
readOnly={readOnly}
onSelectionChange={onSelectionChange}
/>
);
}
const { rerender } = render(<Holder readOnly={false} />);
const view = viewOf("Field");
act(() => view.dispatch({ selection: { anchor: 2 } }));
expect(onSelectionChange).toHaveBeenCalledWith(2, view);
rerender(<Holder readOnly />);
expect(view.state.readOnly).toBe(true);
expect(contentOf("Field").getAttribute("contenteditable")).toBe("false");
rerender(<Holder readOnly={false} />);
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 (
<TextField
path="test://field"
ariaLabel="Field"
value={text}
onChange={setText}
onKeyDownFirst={first}
onKeyDown={after}
/>
);
}
render(<Holder />);
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();
}
});
});
+32 -2
Переглянути файл
@@ -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<TextFieldHandle, TextFieldProps>(function Te
invalid,
onBlur,
onKeyDown,
onKeyDownFirst,
onSelectionChange,
readOnly = false,
className,
style,
hostRef,
@@ -86,11 +98,16 @@ export const TextField = forwardRef<TextFieldHandle, TextFieldProps>(function Te
const host = useRef<HTMLDivElement>(null);
const view = useRef<EditorView | null>(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<TextFieldHandle, TextFieldProps>(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<TextFieldHandle, TextFieldProps>(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;
+9 -5
Переглянути файл
@@ -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;
+9 -5
Переглянути файл
@@ -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
<IconButton icon="close" size="small" title="Close" onClick={onClose} />
</div>
</div>
<textarea
data-autofocus
<TextField
autoFocus
path="openidea://github-review-comment"
className={styles.submitEditor}
placeholder={t("Review comment")}
aria-label={t("Review comment")}
ariaLabel={t("Review comment")}
spellCheck
readOnly={busy}
style={{
fontFamily: family,
fontSize: size,
lineHeight: editor?.lineHeight ? `${editor.lineHeight}px` : undefined,
}}
value={text}
onChange={(e) => {
onChange={(value) => {
setError(null);
setReviewText(draftKey, e.target.value);
setReviewText(draftKey, value);
}}
/>
{error && (
+8 -7
Переглянути файл
@@ -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<HTMLTextAreaElement>("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(<GithubDialogHost />);
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(<GithubDialogHost />);
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" });
+6 -5
Переглянути файл
@@ -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<HTMLElement>(".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<HTMLElement>(".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([
+5 -4
Переглянути файл
@@ -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(<IssueEditor input={input} />);
const submit = await screen.findByRole("button", { name: "Comment" });
const field = container.querySelector("textarea")!;
fireEvent.change(field, { target: { value: "Confirmed locally" } });
const field = container.querySelector<HTMLElement>(".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"],
+4 -3
Переглянути файл
@@ -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([
+63 -57
Переглянути файл
@@ -8,7 +8,10 @@
* <CommentEditor submitLabel="Reply" submitHint={tx`${submitShortcut()} to reply`}
* onSubmit={(text) => 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<HTMLTextAreaElement>(null);
const [field, setField] = useState<HTMLDivElement | null>(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<TextFieldHandle>(null);
const [anchor, setAnchor] = useState<HTMLDivElement | null>(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<HTMLTextAreaElement>) => {
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 (
<div className={styles.editorRow} style={{ ["--gap" as string]: variant === "full" ? "14px" : "10px" }}>
{showAvatar && me && <Avatar url={me.avatarUrl} name={me.name || me.login} size={avatarSize(variant)} />}
<div className={styles.editor}>
<div ref={setField} className={styles.field}>
<textarea
ref={ref}
<div ref={setAnchor} className={styles.field}>
<TextField
ref={field}
path="openidea://github-comment"
className={styles.textarea}
rows={1}
value={text}
disabled={busy}
placeholder={t(placeholder)}
aria-label={placeholder ? t(placeholder) : t(submitLabel)}
onChange={(e) => {
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 && (
<MentionPopup
anchor={field}
anchor={anchor}
matches={matches}
active={active}
onPick={pick}
+11 -7
Переглянути файл
@@ -163,19 +163,23 @@
.field:focus-within {
border-color: var(--focus-ring);
}
/* The comment field (an editor, `src/editor/TextField.tsx`): grows with its text up to 320px. */
.textarea {
flex: 1;
min-width: 0;
min-height: 22px;
max-height: 320px;
padding: 4px 8px;
overflow-y: auto;
border: 0;
outline: none;
background: transparent;
color: var(--fg);
font: inherit;
line-height: 1.4;
resize: none;
}
.textarea :global(.cm-scroller) {
max-height: 320px;
}
.textarea :global(.cm-content) {
padding: 4px 8px;
}
.textarea :global(.cm-editor.cm-focused) {
outline: none;
}
.editorFooter {
display: flex;
+26
Переглянути файл
@@ -0,0 +1,26 @@
import { act } from "@testing-library/react";
import { EditorView } from "@codemirror/view";
function viewOf(field: HTMLElement): EditorView {
const dom = field.closest<HTMLElement>(".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();
}