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
fix(quick_search): let Escape drop the completion list before the results
Elian Doran97ce8b1c80cd
diff --git a/apps/client/src/widgets/quick_search.spec.tsx b/apps/client/src/widgets/quick_search.spec.tsxindex 18a9ab5a85..2f730ce206 100644--- a/apps/client/src/widgets/quick_search.spec.tsx+++ b/apps/client/src/widgets/quick_search.spec.tsx@@ -1,3 +1,4 @@+import { type CompletionContext, completionStatus, startCompletion } from "@codemirror/autocomplete";import type { EditorView } from "@codemirror/view";import type { QuickSearchResponse } from "@triliumnext/commons";import { options, type VNode } from "preact";@@ -12,9 +13,13 @@ import { renderInto } from "../test/render";import QuickSearch from "./quick_search";import { ParentComponent } from "./react/react_utils";-// The completions fetch attribute names and values through the server; nothing here opens the popup.+// The completions fetch attribute names and values through the server, so a spec that opens them+// supplies its own source.+const completions = vi.hoisted(() => ({+ source: null as ((context: CompletionContext) => unknown) | null+}));vi.mock("./ribbon/search_completions", () => ({- searchCompletionSource: () => null,+ searchCompletionSource: (context: CompletionContext) => completions.source?.(context) ?? null,searchCompletionIcon: () => undefined,searchCompletionReactivates: () => false}));@@ -22,6 +27,7 @@ vi.mock("./ribbon/search_completions", () => ({describe("QuickSearch", () => {afterEach(() => {vi.restoreAllMocks();+ completions.source = null;});it("renders the search field, focuses it on the quickSearch shortcut and marks a typed query", async () => {@@ -260,6 +266,30 @@ describe("QuickSearch", () => {expect(document.activeElement).toBe(rows[29]);});+ it("drops an open completion list on Escape before the results", async () => {+ vi.spyOn(server, "get").mockResolvedValue(response(3, []));+ completions.source = () => ({ from: 0, options: [ { label: "and" }, { label: "asc" } ] });+ const { editor } = await mount();++ typeQuery(editor, "a");+ pressEnter(editor);+ await waitForResults(3);+ editor.focus();++ startCompletion(editor);+ await vi.waitFor(() => expect(completionStatus(editor.state)).toBe("active"));+ // The list drops the keys pressed within its `interactionDelay` of opening.+ await new Promise((resolve) => setTimeout(resolve, 100));++ pressKey(editor.contentDOM, "Escape");+ expect(completionStatus(editor.state)).toBe(null);+ expect(menu()).not.toBeNull();++ pressKey(editor.contentDOM, "Escape");+ await vi.waitFor(() => expect(menu()).toBeNull());+ expect(editor.hasFocus).toBe(true);+ });+it("leaves ArrowDown to the field while the results are closed or hold nothing to focus", async () => {const get = vi.spyOn(server, "get").mockResolvedValue(response(0, []));const { editor } = await mount();@@ -404,6 +434,12 @@ function pressArrowDown(editor: EditorView, modifiers: KeyboardEventInit = {}) {});}+function pressKey(target: Element, key: string) {+ act(() => {+ target.dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true }));+ });+}+function movePointer(target: HTMLElement, movement: number) {act(() => {target.dispatchEvent(new PointerEvent("pointermove", { bubbles: true, movementX: movement }));diff --git a/apps/client/src/widgets/quick_search.tsx b/apps/client/src/widgets/quick_search.tsxindex 40b04d5a1e..fc73e53299 100644--- a/apps/client/src/widgets/quick_search.tsx+++ b/apps/client/src/widgets/quick_search.tsx@@ -44,7 +44,8 @@ export default function QuickSearch() {useTriliumEvent("quickSearch", () => editorRef.current?.focus());useResultNavigation(popupRef, open, {focusField: () => editorRef.current?.focus(),- onMoved: () => setKeyboardDriven(true)+ onMoved: () => setKeyboardDriven(true),+ onEscape: close});/** Opens the results with a search for the query, or refreshes the open results. */@@ -116,6 +117,12 @@ export default function QuickSearch() {setHasQuery(value.length > 0);}}onEnter={() => void search()}+ // Reached only once the field's completion list, if open, has dropped the key.+ onEscape={() => {+ if (!open) return false;+ close();+ return true;+ }}onArrowDown={() => {const popup = popupRef.current;if (!popup || !firstResult(popup)) return false;@@ -135,6 +142,7 @@ export default function QuickSearch() {className={clsx("dropdown-menu show tn-dropdown-menu quick-search-menu",keyboardDriven && "tn-menu-keyboard")}elementRef={popupRef}+ escapeDismisses={false}onPointerMove={(e) => {if (!pointerMoved(e)) return;setKeyboardDriven(false);@@ -166,15 +174,17 @@ export default function QuickSearch() {}/**- * Moves focus between the results with Up and Down, and from the first result up to the field.- * Captured at the window, as Bootstrap's handler for keys in a `.dropdown-menu` crashes on one with- * no toggle beside it.+ * Moves focus between the results with the arrow and page keys, and from the first result up to+ * the field, and closes them on Escape. Captured at the window, as Bootstrap's handler for keys in+ * a `.dropdown-menu` crashes on one with no toggle beside it.*/function useResultNavigation(popupRef: RefObject<HTMLElement>, open: boolean, callbacks: {/** Runs for ArrowUp on the first result. */focusField(): void;/** Runs once the keys have moved focus to another result. */onMoved(): void;+ /** Runs for Escape on a result. */+ onEscape(): void;}) {const callbacksRef = useRef(callbacks);callbacksRef.current = callbacks;@@ -184,7 +194,15 @@ function useResultNavigation(popupRef: RefObject<HTMLElement>, open: boolean, caconst onKeyDown = (e: KeyboardEvent) => {const popup = popupRef.current;const target = e.target as Element;- if (!NAVIGATION_KEYS.has(e.key) || !popup?.contains(target)) return;+ if (!popup?.contains(target)) return;+ if (e.key === "Escape") {+ e.preventDefault();+ e.stopPropagation();+ callbacksRef.current.onEscape();+ return;+ }++ if (!NAVIGATION_KEYS.has(e.key)) return;e.preventDefault();e.stopPropagation();const row = target.closest<HTMLElement>(".dropdown-item");