Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(search): give the quick search the saved search's query field
Elian Doran133b224cc8db
diff --git a/apps/client/src/widgets/quick_search.spec.ts b/apps/client/src/widgets/quick_search.spec.tsindex 3f25b17034..03ecc434a7 100644--- a/apps/client/src/widgets/quick_search.spec.ts+++ b/apps/client/src/widgets/quick_search.spec.ts@@ -6,6 +6,13 @@ import linkService from "../services/link.js";import server from "../services/server.js";import QuickSearchWidget from "./quick_search.js";+// The completions fetch attribute names and values through the server; nothing here opens the popup.+vi.mock("./ribbon/search_completions", () => ({+ searchCompletionSource: () => null,+ searchCompletionIcon: () => undefined,+ searchCompletionReactivates: () => false+}));+describe("QuickSearchWidget", () => {beforeEach(() => {vi.restoreAllMocks();@@ -17,32 +24,47 @@ describe("QuickSearchWidget", () => {it("moves focus from the search box to the first result on ArrowDown", async () => {const widget = await renderAndSearch();- const $input = widget.$widget.find(".search-string");const $items = widget.$widget.find(".dropdown-menu .dropdown-item");- expect(pressArrowDown($input[0])).toBe(true);+ pressArrowDown(widget);expect(document.activeElement).toBe($items[0]);});it("leaves ArrowDown to the search box while the popup is closed or a modifier is held", async () => {const widget = await renderAndSearch();- const $input = widget.$widget.find(".search-string");const $firstItem = widget.$widget.find(".dropdown-menu .dropdown-item").first();- expect(pressArrowDown($input[0], { ctrlKey: true })).toBe(false);- expect(pressArrowDown($input[0], { shiftKey: true })).toBe(false);+ pressArrowDown(widget, { ctrlKey: true });+ pressArrowDown(widget, { shiftKey: true });expect(document.activeElement).not.toBe($firstItem[0]);widget.$widget.find(".dropdown-menu").removeClass("show");- expect(pressArrowDown($input[0])).toBe(false);+ pressArrowDown(widget);expect(document.activeElement).not.toBe($firstItem[0]);});it("leaves ArrowDown alone when the popup holds no result to focus", async () => {const widget = await renderAndSearch(0);- expect(widget.$widget.find(".dropdown-menu .dropdown-item.disabled").length).toBe(1);- expect(pressArrowDown(widget.$widget.find(".search-string")[0])).toBe(false);+ const $disabled = widget.$widget.find(".dropdown-menu .dropdown-item.disabled");+ expect($disabled.length).toBe(1);++ pressArrowDown(widget);+ expect(document.activeElement).not.toBe($disabled[0]);+ });++ it("reads the query out of the CodeMirror field, for the search and the full-search handoff", async () => {+ const triggerCommand = vi.spyOn(appContext, "triggerCommand").mockResolvedValue(undefined);+ const widget = renderWidget();+ mockResults(1);++ setSearchString(widget, "#book AND tolkien");+ await widget.search();++ expect(server.get).toHaveBeenCalledWith(`quick-search/${encodeURIComponent("#book AND tolkien")}`);++ widget.$widget.find(".show-in-full-search").trigger("click");+ expect(triggerCommand).toHaveBeenCalledWith("searchNotes", { searchString: "#book AND tolkien" });});it("keeps the full search link pinned below the scrolling results as more load", async () => {@@ -119,13 +141,29 @@ describe("QuickSearchWidget", () => {});});-/** Returns whether the widget claimed the key, which is what keeps the caret from moving. */-function pressArrowDown(element: HTMLElement, modifiers: KeyboardEventInit = {}) {- const event = new KeyboardEvent("keydown", {+/**+ * Presses ArrowDown in the search field. The editor always claims the key to move its own caret,+ * so where the focus lands is what says whether the widget stepped into the results.+ */+function pressArrowDown(widget: QuickSearchWidget, modifiers: KeyboardEventInit = {}) {+ editorOf(widget).contentDOM.dispatchEvent(new KeyboardEvent("keydown", {key: "ArrowDown", code: "ArrowDown", bubbles: true, cancelable: true, ...modifiers- });- element.dispatchEvent(event);- return event.defaultPrevented;+ }));+}++function setSearchString(widget: QuickSearchWidget, value: string) {+ const editor = editorOf(widget);+ editor.dispatch({ changes: { from: 0, to: editor.state.doc.length, insert: value } });+}++function editorOf(widget: QuickSearchWidget) {+ const editor = widget.editor;++ if (!editor) {+ throw new Error("The widget was not rendered, so it has no search field.");+ }++ return editor;}async function renderAndSearch(resultCount = 3) {@@ -147,7 +185,7 @@ async function renderAndSearch(resultCount = 3) {widget.render();// Focus only moves within the document, and `show` is the class Bootstrap opens the menu with.widget.$widget.appendTo(document.body);- widget.$widget.find(".search-string").val("hello");+ setSearchString(widget, "hello");await widget.search();widget.$widget.find(".dropdown-menu").addClass("show");@@ -157,7 +195,8 @@ async function renderAndSearch(resultCount = 3) {function renderWidget() {const widget = new QuickSearchWidget();widget.render();- widget.$widget.find(".search-string").val("hello");+ widget.$widget.appendTo(document.body);+ setSearchString(widget, "hello");return widget;}diff --git a/apps/client/src/widgets/quick_search.ts b/apps/client/src/widgets/quick_search.tsindex 330b52df34..ed7df520d3 100644--- a/apps/client/src/widgets/quick_search.ts+++ b/apps/client/src/widgets/quick_search.ts@@ -1,3 +1,4 @@+import type { FieldEditor } from "@triliumnext/codemirror/src/field_editor";import { Dropdown, Tooltip } from "bootstrap";import appContext from "../components/app_context.js";@@ -5,9 +6,10 @@ import froca from "../services/froca.js";import { t } from "../services/i18n.js";import linkService, { calculateHash, type ViewScope } from "../services/link.js";import server from "../services/server.js";-import shortcutService, { isAppShortcutChord, isIMEComposing } from "../services/shortcuts.js";+import shortcutService from "../services/shortcuts.js";import utils, { handleRightToLeftPlacement } from "../services/utils.js";import BasicWidget from "./basic_widget.js";+import { createSearchFieldEditor, SEARCH_FIELD_EDITOR_CLASS } from "./search_field_editor.js";const TPL = /*html*/`<div class="quick-search input-group input-group-sm">@@ -17,11 +19,23 @@ const TPL = /*html*/`height: 50px;}- .quick-search button, .quick-search input {+ .quick-search button, .quick-search .search-string {border: 0;font-size: 100% !important;}+ .quick-search .search-string {+ display: flex;+ align-items: center;+ min-width: 0;+ }++ /* The results list sits right below the field, so extra lines scroll inside it. */+ .quick-search .search-string .cm-editor {+ width: 100%;+ max-height: 100%;+ }+.quick-search .dropdown-menu {--quick-search-item-delimiter-color: var(--dropdown-border-color);@@ -158,7 +172,7 @@ const TPL = /*html*/`</div></div></div>- <input type="text" class="form-control form-control-sm search-string" placeholder="${t("quick-search.placeholder")}">+ <div class="form-control form-control-sm search-string ${SEARCH_FIELD_EDITOR_CLASS}"></div></div>`;const INITIAL_DISPLAYED_NOTES = 15;@@ -187,7 +201,9 @@ interface QuickSearchResponse {export default class QuickSearchWidget extends BasicWidget {private dropdown!: bootstrap.Dropdown;- private $searchString!: JQuery<HTMLElement>;+ private $searchField!: JQuery<HTMLElement>;+ /** Holds the query. The widget reads it instead of an input's value. */+ editor?: FieldEditor;private $dropdownMenu!: JQuery<HTMLElement>;private $searchResults!: JQuery<HTMLElement>;private $footer!: JQuery<HTMLElement>;@@ -204,19 +220,27 @@ export default class QuickSearchWidget extends BasicWidget {doRender() {this.$widget = $(TPL);- this.$searchString = this.$widget.find(".search-string");+ this.$searchField = this.$widget.find(".search-string");this.$dropdownMenu = this.$widget.find(".dropdown-menu");this.$searchResults = this.$dropdownMenu.find(".quick-search-results");this.$footer = this.$dropdownMenu.find(".quick-search-footer");this.dropdown = Dropdown.getOrCreateInstance(this.$widget.find("[data-bs-toggle='dropdown']")[0], {- reference: this.$searchString[0],+ reference: this.$searchField[0],popperConfig: {strategy: "fixed",placement: "bottom"}});+ this.editor = createSearchFieldEditor({+ parent: this.$searchField[0],+ placeholder: t("quick-search.placeholder"),+ onEnter: () => this.runSearch(),+ onArrowDown: () => this.focusFirstResult(),+ onEscape: () => this.closeDropdown()+ });+this.$widget.find(".input-group-prepend").on("shown.bs.dropdown", () => this.search());// Add scroll event listener for infinite scrolling@@ -228,71 +252,61 @@ export default class QuickSearchWidget extends BasicWidget {$showInFullSearchButton.on("click", () => this.showInFullSearch());shortcutService.bindElShortcut($showInFullSearchButton, "return", () => this.showInFullSearch());- if (utils.isMobile()) {- this.$searchString.keydown((e) => {- // Skip processing if IME is composing to prevent interference- // with text input in CJK languages- // Note: jQuery wraps the native event, so we access originalEvent- const originalEvent = e.originalEvent as KeyboardEvent;- if (originalEvent && isIMEComposing(originalEvent)) {- return;- }-- if (e.which === 13) {- if (this.$dropdownMenu.is(":visible")) {- this.search(); // just update already visible dropdown- } else {- this.dropdown.show();- }- e.preventDefault();- e.stopPropagation();- }- });- }+ return this.$widget;+ }- shortcutService.bindElShortcut(this.$searchString, "return", () => {- if (this.$dropdownMenu.is(":visible")) {- this.search(); // just update already visible dropdown- } else {- this.dropdown.show();- }+ cleanup() {+ this.editor?.destroy();+ this.editor = undefined;+ }- this.$searchString.focus();- });+ /** The query as it stands in the field. */+ private get searchString() {+ return this.editor?.state.doc.toString() ?? "";+ }- // Bootstrap moves between the results but ignores key events on an input, so the step from- // the search box into the list is bound here.- this.$searchString.on("keydown", (e) => {- const event = e.originalEvent as KeyboardEvent | undefined;+ /** Runs on Enter: opens the results, or refreshes them when they are already open. */+ private runSearch() {+ if (this.isDropdownOpen()) {+ void this.search();+ } else {+ this.dropdown.show();+ }- if (!event || event.key !== "ArrowDown" || !this.isDropdownOpen()) {- return;- }+ this.editor?.focus();+ }- if (isIMEComposing(event) || isAppShortcutChord(event) || event.shiftKey) {- return;- }+ /**+ * Steps from the field into the results on ArrowDown, which Bootstrap does not do on its own.+ * Searching and no-results leave only a disabled item, and the caret keeps the key.+ */+ private focusFirstResult() {+ if (!this.isDropdownOpen()) {+ return false;+ }- const $firstResult = this.$searchResults.find(".dropdown-item:not(.disabled)").first();+ const $firstResult = this.$searchResults.find(".dropdown-item:not(.disabled)").first();- // Searching and no-results leave only a disabled item, and the caret keeps the key.- if (!$firstResult.length) {- return;- }+ if (!$firstResult.length) {+ return false;+ }- e.preventDefault();- $firstResult.focus();- });+ $firstResult.focus();+ return true;+ }- shortcutService.bindElShortcut(this.$searchString, "esc", () => {- this.dropdown.hide();- });+ /** Closes the results on Escape, leaving the key to CodeMirror when they are already closed. */+ private closeDropdown() {+ if (!this.isDropdownOpen()) {+ return false;+ }- return this.$widget;+ this.dropdown.hide();+ return true;}async search() {- const searchString = String(this.$searchString.val())?.trim();+ const searchString = this.searchString.trim();if (!searchString) {this.dropdown.hide();@@ -318,7 +332,7 @@ export default class QuickSearchWidget extends BasicWidget {this.lastResultViewScope = highlightedTokens?.length ? { searchTerms: highlightedTokens } : undefined;if (error) {- const tooltip = new Tooltip(this.$searchString[0], {+ const tooltip = new Tooltip(this.$searchField[0], {trigger: "manual",title: `Search error: ${error}`,placement: handleRightToLeftPlacement("right")@@ -344,7 +358,7 @@ export default class QuickSearchWidget extends BasicWidget {await this.displayMoreResults(INITIAL_DISPLAYED_NOTES);this.$footer.removeClass("hidden-ext");- shortcutService.bindElShortcut(this.$searchResults.find(".dropdown-item:first"), "up", () => this.$searchString.focus());+ shortcutService.bindElShortcut(this.$searchResults.find(".dropdown-item:first"), "up", () => this.editor?.focus());this.dropdown.update();}@@ -463,11 +477,11 @@ export default class QuickSearchWidget extends BasicWidget {this.dropdown.hide();await appContext.triggerCommand("searchNotes", {- searchString: String(this.$searchString.val())+ searchString: this.searchString});}quickSearchEvent() {- this.$searchString.focus();+ this.editor?.focus();}}diff --git a/apps/client/src/widgets/ribbon/SearchStringEditor.tsx b/apps/client/src/widgets/ribbon/SearchStringEditor.tsxindex f4c0ae6d45..10391f61bd 100644--- a/apps/client/src/widgets/ribbon/SearchStringEditor.tsx+++ b/apps/client/src/widgets/ribbon/SearchStringEditor.tsx@@ -1,16 +1,11 @@-import "./SearchStringEditor.css";--import type { SearchLintMessages } from "@triliumnext/codemirror/src/extensions/trilium_search_lint";import type { FieldEditor } from "@triliumnext/codemirror/src/field_editor";-import type { SearchLintResponse } from "@triliumnext/commons";import clsx from "clsx";import { useEffect, useRef } from "preact/hooks";import { t } from "../../services/i18n";-import server from "../../services/server";import type { ShortcutHintDefinition } from "../../services/shortcut_hints";import { useContextualShortcutHints } from "../react/hooks";-import { searchCompletionIcon, searchCompletionReactivates, searchCompletionSource } from "./search_completions";+import { createSearchFieldEditor, SEARCH_FIELD_EDITOR_CLASS } from "../search_field_editor";interface SearchStringEditorProps {currentValue: string;@@ -40,9 +35,6 @@ const SEARCH_STRING_HINTS: ShortcutHintDefinition = [/*** Edits the `#searchString` of a saved search in a CodeMirror editor. Enter runs the search and* Shift-Enter starts a new line, so a long query can be laid out over several of them.- *- * CodeMirror loads on demand: `RibbonDefinition` imports the tab holding this component- * statically, so a static import here would put the editor in the initial bundle.*/export default function SearchStringEditor({ currentValue, noteId, placeholder, className, autoFocus, onChange, onEnter }: SearchStringEditorProps) {const parentRef = useRef<HTMLDivElement>(null);@@ -58,43 +50,29 @@ export default function SearchStringEditor({ currentValue, noteId, placeholder,useContextualShortcutHints(SEARCH_STRING_HINTS);useEffect(() => {- let editor: FieldEditor | undefined;- let cancelled = false;-- void Promise.all([- import("@triliumnext/codemirror/src/field_editor"),- import("@triliumnext/codemirror/src/extensions/trilium_search_highlighter"),- import("@triliumnext/codemirror/src/extensions/trilium_search_lint")- ]).then(([ { createFieldEditor }, { triliumSearchHighlighter }, { triliumSearchLinter } ]) => {- if (cancelled || !parentRef.current) {- return;- }-- editor = createFieldEditor({- parent: parentRef.current,- doc: propsRef.current.currentValue,- placeholder,- extensions: [ triliumSearchHighlighter, triliumSearchLinter(searchLintMessages(), validateOnServer) ],- completionSource: searchCompletionSource,- completionIcon: searchCompletionIcon,- activateOnCompletion: searchCompletionReactivates,- onChange: (value) => {- if (!isAdopting.current) {- propsRef.current.onChange(value);- }- },- onEnter: () => propsRef.current.onEnter()- });- editorRef.current = editor;+ if (!parentRef.current) {+ return;+ }- if (autoFocus) {- editor.focus();- }+ const editor = createSearchFieldEditor({+ parent: parentRef.current,+ doc: propsRef.current.currentValue,+ placeholder,+ onChange: (value) => {+ if (!isAdopting.current) {+ propsRef.current.onChange(value);+ }+ },+ onEnter: () => propsRef.current.onEnter()});+ editorRef.current = editor;++ if (autoFocus) {+ editor.focus();+ }return () => {- cancelled = true;- editor?.destroy();+ editor.destroy();editorRef.current = undefined;};// Builds the editor once; `placeholder` and `autoFocus` are read at that point.@@ -124,27 +102,5 @@ export default function SearchStringEditor({ currentValue, noteId, placeholder,}}, [ currentValue, noteId ]);- return <div ref={parentRef} className={clsx("search-string-editor form-control tn-input-field", className)} />;-}--/**- * Asks the engine to read the query without running it, for the faults the rules in the editor do- * not cover. Only reached once those rules are satisfied, so a query they already object to costs- * no request.- */-async function validateOnServer(searchString: string) {- const { error } = await server.post<SearchLintResponse>("search/lint", { searchString });-- return error;-}--/** Read once the editor is built, so the wording follows a language switched while the app runs. */-function searchLintMessages(): SearchLintMessages {- return {- relationNeedsProperty: t("search_lint.relation_needs_property"),- textNeedsContains: t("search_lint.text_needs_contains"),- contentNotOrdered: t("search_lint.content_not_ordered"),- compareTheTitle: t("search_lint.compare_the_title"),- useOperator: (operator) => t("search_lint.use_operator", { operator })- };+ return <div ref={parentRef} className={clsx(SEARCH_FIELD_EDITOR_CLASS, "form-control tn-input-field", className)} />;}diff --git a/apps/client/src/widgets/ribbon/SearchStringEditor.css b/apps/client/src/widgets/search_field_editor.csssimilarity index 100%rename from apps/client/src/widgets/ribbon/SearchStringEditor.cssrename to apps/client/src/widgets/search_field_editor.cssdiff --git a/apps/client/src/widgets/search_field_editor.ts b/apps/client/src/widgets/search_field_editor.tsnew file mode 100644index 0000000000..09e2af6a7b--- /dev/null+++ b/apps/client/src/widgets/search_field_editor.ts@@ -0,0 +1,55 @@+import "./search_field_editor.css";++import { triliumSearchHighlighter } from "@triliumnext/codemirror/src/extensions/trilium_search_highlighter";+import { type SearchLintMessages, triliumSearchLinter } from "@triliumnext/codemirror/src/extensions/trilium_search_lint";+import { createFieldEditor, type FieldEditor, type FieldEditorConfig } from "@triliumnext/codemirror/src/field_editor";+import type { SearchLintResponse } from "@triliumnext/commons";++import { t } from "../services/i18n";+import server from "../services/server";+import { searchCompletionIcon, searchCompletionReactivates, searchCompletionSource } from "./ribbon/search_completions";++/** The class the styles in `search_field_editor.css` are scoped under. */+export const SEARCH_FIELD_EDITOR_CLASS = "search-string-editor";++/** What a caller supplies; the highlighting, linting and completions are fixed. */+export type SearchFieldEditorConfig = Omit<FieldEditorConfig, "extensions" | "completionSource" | "completionIcon" | "activateOnCompletion">;++/**+ * Builds the editor a search string is written in: the query highlighter, the linter and the+ * attribute/property completions over {@link createFieldEditor}. The quick search and the saved+ * search's ribbon both use it, so a query reads and reports the same way in either field.+ *+ * The parent element needs {@link SEARCH_FIELD_EDITOR_CLASS} for the styles to apply.+ */+export function createSearchFieldEditor(config: SearchFieldEditorConfig): FieldEditor {+ return createFieldEditor({+ ...config,+ extensions: [ triliumSearchHighlighter, triliumSearchLinter(searchLintMessages(), validateOnServer) ],+ completionSource: searchCompletionSource,+ completionIcon: searchCompletionIcon,+ activateOnCompletion: searchCompletionReactivates+ });+}++/**+ * Asks the engine to read the query without running it, for the faults the rules in the editor do+ * not cover. Only reached once those rules are satisfied, so a query they already object to costs+ * no request.+ */+async function validateOnServer(searchString: string) {+ const { error } = await server.post<SearchLintResponse>("search/lint", { searchString });++ return error;+}++/** Read once the editor is built, so the wording follows a language switched while the app runs. */+function searchLintMessages(): SearchLintMessages {+ return {+ relationNeedsProperty: t("search_lint.relation_needs_property"),+ textNeedsContains: t("search_lint.text_needs_contains"),+ contentNotOrdered: t("search_lint.content_not_ordered"),+ compareTheTitle: t("search_lint.compare_the_title"),+ useOperator: (operator) => t("search_lint.use_operator", { operator })+ };+}diff --git a/packages/codemirror/src/field_editor.spec.ts b/packages/codemirror/src/field_editor.spec.tsindex 238a85cbb4..658fe7ccda 100644--- a/packages/codemirror/src/field_editor.spec.ts+++ b/packages/codemirror/src/field_editor.spec.ts@@ -1,3 +1,4 @@+import { completionStatus, startCompletion } from "@codemirror/autocomplete";import { EditorSelection } from "@codemirror/state";import { afterEach, describe, expect, it, vi } from "vitest";@@ -32,7 +33,7 @@ describe("createFieldEditor", () => {editor = build({ doc: "#book", onEnter });editor.dispatch({ selection: EditorSelection.cursor(5) });- expect(pressEnter(editor)).toBe(true);+ expect(pressKey(editor, "Enter")).toBe(true);expect(onEnter).toHaveBeenCalledOnce();expect(editor.state.doc.toString()).toBe("#book");});@@ -43,12 +44,68 @@ describe("createFieldEditor", () => {editor = build({ doc: "#book\n and #author", onEnter, onChange });editor.dispatch({ selection: EditorSelection.cursor(editor.state.doc.length) });- expect(pressEnter(editor, { shiftKey: true })).toBe(true);+ expect(pressKey(editor, "Enter", { shiftKey: true })).toBe(true);expect(onEnter).not.toHaveBeenCalled();expect(editor.state.doc.toString()).toBe("#book\n and #author\n ");expect(onChange).toHaveBeenLastCalledWith("#book\n and #author\n ");});+ it("answers ArrowDown and Escape once the completion popup has passed them on", () => {+ const onArrowDown = vi.fn().mockReturnValue(true);+ const onEscape = vi.fn().mockReturnValue(true);+ editor = build({ doc: "#book\n#year", onArrowDown, onEscape });+ editor.dispatch({ selection: EditorSelection.cursor(0) });++ expect(pressKey(editor, "ArrowDown")).toBe(true);+ expect(onArrowDown).toHaveBeenCalledOnce();+ // Claimed by the field, so the caret stayed on the first line.+ expect(editor.state.selection.main.head).toBe(0);++ expect(pressKey(editor, "Escape")).toBe(true);+ expect(onEscape).toHaveBeenCalledOnce();+ });++ it("leaves a declined ArrowDown to the caret", () => {+ const onArrowDown = vi.fn().mockReturnValue(false);+ editor = build({ doc: "#book\n#year", onArrowDown });+ editor.dispatch({ selection: EditorSelection.cursor(0) });++ pressKey(editor, "ArrowDown");++ expect(onArrowDown).toHaveBeenCalledOnce();+ expect(editor.state.selection.main.head).toBeGreaterThan(0);+ });++ it("leaves ArrowDown and Escape to the completion popup while it is open", async () => {+ const onArrowDown = vi.fn().mockReturnValue(true);+ const onEscape = vi.fn().mockReturnValue(true);+ const view = build({+ doc: "#b",+ completionSource: () => ({ from: 0, options: [ { label: "#book" }, { label: "#borrowed" } ] }),+ onArrowDown,+ onEscape+ });+ editor = view;+ view.dispatch({ selection: EditorSelection.cursor(2) });++ // The popup drops both keys for `interactionDelay` after it opens; neither may reach the+ // field in that window, since the field's own commands move focus out of the editor.+ await openCompletion(view);+ pressKey(view, "ArrowDown");+ expect(onArrowDown).not.toHaveBeenCalled();++ await openCompletion(view);+ pressKey(view, "Escape");+ expect(onEscape).not.toHaveBeenCalled();++ // Closed, so the field gets both keys back.+ expect(completionStatus(view.state)).toBe(null);+ pressKey(view, "ArrowDown");+ pressKey(view, "Escape");+ expect(onArrowDown).toHaveBeenCalledOnce();+ expect(onEscape).toHaveBeenCalledOnce();+ });+it("keeps the line breaks in inserted text", () => {const onChange = vi.fn();editor = build({ onChange });@@ -66,10 +123,16 @@ function build(config: Partial<FieldEditorConfig> = {}): FieldEditor {return createFieldEditor({ parent, ...config });}-/** Presses Enter on the editor and answers whether a binding handled it. */-function pressEnter(editor: FieldEditor, init: KeyboardEventInit = {}) {+/** Opens the completion popup and waits until it is showing. */+async function openCompletion(view: FieldEditor) {+ startCompletion(view);+ await vi.waitFor(() => expect(completionStatus(view.state)).toBe("active"));+}++/** Presses a key on the editor and answers whether a binding handled it. */+function pressKey(editor: FieldEditor, key: string, init: KeyboardEventInit = {}) {return !editor.contentDOM.dispatchEvent(new KeyboardEvent("keydown", {- key: "Enter",+ key,bubbles: true,cancelable: true,...initdiff --git a/packages/codemirror/src/field_editor.ts b/packages/codemirror/src/field_editor.tsindex 635aadbbab..1bcd5f91ed 100644--- a/packages/codemirror/src/field_editor.ts+++ b/packages/codemirror/src/field_editor.ts@@ -1,4 +1,4 @@-import { autocompletion, type Completion, type CompletionSource } from "@codemirror/autocomplete";+import { autocompletion, type Completion, completionStatus, type CompletionSource } from "@codemirror/autocomplete";import { history, historyKeymap, standardKeymap } from "@codemirror/commands";import type { Extension } from "@codemirror/state";import { EditorView, keymap, placeholder } from "@codemirror/view";@@ -32,6 +32,13 @@ export interface FieldEditorConfig {onChange?(value: string): void;/** Runs when Enter is pressed; Shift-Enter inserts a line break instead. */onEnter?(): void;+ /**+ * Runs when ArrowDown is pressed and no completion is open or pending, for a field whose+ * results are listed below it. Returns whether the key was taken; `false` moves the caret.+ */+ onArrowDown?(): boolean;+ /** Runs when Escape is pressed and no completion is open or pending. Returns as {@link onArrowDown}. */+ onEscape?(): boolean;}/** The editor {@link createFieldEditor} returns. */@@ -46,6 +53,10 @@ export type FieldEditor = EditorView;* input does. Shift-Enter, which `standardKeymap` binds to `insertNewlineAndIndent`, breaks the* line and keeps its indentation, for a value the user lays out over several of them.*+ * `onArrowDown` and `onEscape` run only while no completion is open or pending, so a key the popup+ * drops does not move focus out of the editor instead. An IME keeps Enter for as long as it is+ * composing.+ ** It sits apart from the editor in `index.ts` so a consumer that wants a plain input does not* load the language, theme and completion machinery a code note needs.*/@@ -56,12 +67,17 @@ export function createFieldEditor(config: FieldEditorConfig): FieldEditor {keymap.of([{key: "Enter",- run: () => {+ run: (view) => {+ if (view.composing) {+ return false;+ }+config.onEnter?.();return true;- },- preventDefault: true+ }},+ { key: "ArrowDown", run: (view) => keyBelongsToField(view) && !!config.onArrowDown?.() },+ { key: "Escape", run: (view) => keyBelongsToField(view) && !!config.onEscape?.() },...standardKeymap,...historyKeymap]),@@ -98,6 +114,15 @@ export function createFieldEditor(config: FieldEditorConfig): FieldEditor {});}+/**+ * Whether a navigation key the completion popup declined belongs to the field. The popup drops+ * ArrowDown and Escape for `interactionDelay` after it opens, and a key dropped that way must not+ * reach {@link FieldEditorConfig.onArrowDown}, which moves focus out of the editor entirely.+ */+function keyBelongsToField(view: EditorView) {+ return !view.composing && completionStatus(view.state) === null;+}+/** Where CodeMirror draws its own icons, which {@link FieldEditorConfig.completionIcon} takes over. */const ICON_POSITION = 20;