Skip to content

Build your personal knowledge base with Trilium Notes

refactor(quick_search): port the search field

Elian Doran6998dd1641cc
diff --git a/apps/client/src/widgets/quick_search.spec.tsx b/apps/client/src/widgets/quick_search.spec.tsx
new file mode 100644
index 0000000000..b1119f1b0c
--- /dev/null
+++ b/apps/client/src/widgets/quick_search.spec.tsx
@@ -0,0 +1,58 @@
+import { act } from "preact/test-utils";
+import { describe, expect, it, vi } from "vitest";
+
+import Component from "../components/component";
+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.
+vi.mock("./ribbon/search_completions", () => ({
+ searchCompletionSource: () => null,
+ searchCompletionIcon: () => undefined,
+ searchCompletionReactivates: () => false
+}));
+
+describe("QuickSearch", () => {
+ it("renders the search field and focuses it on the quickSearch shortcut", async () => {
+ const host = new Component();
+ const { container, editor } = await mount(host);
+
+ expect(container.querySelector(".quick-search .search-string .cm-editor")).not.toBeNull();
+
+ expect(editor.hasFocus).toBe(false);
+ await act(async () => {
+ await host.handleEvent("quickSearch", {});
+ });
+ expect(editor.hasFocus).toBe(true);
+ });
+});
+
+/** Renders the component and waits for the CodeMirror modules it imports on demand. */
+async function mount(host: Component) {
+ let container: HTMLDivElement | undefined;
+ act(() => {
+ container = renderInto(
+ <ParentComponent.Provider value={host}>
+ <QuickSearch />
+ </ParentComponent.Provider>
+ );
+ });
+ if (!container) {
+ throw new Error("The component did not render.");
+ }
+
+ const { EditorView } = await import("@codemirror/view");
+ let editor: InstanceType<typeof EditorView> | null = null;
+ for (let attempt = 0; attempt < 50 && !editor; attempt++) {
+ await new Promise((resolve) => setTimeout(resolve, 1));
+ const dom = container.querySelector(".cm-editor");
+ editor = dom instanceof HTMLElement ? EditorView.findFromDOM(dom) : null;
+ }
+
+ if (!editor) {
+ throw new Error(`The editor did not mount: ${container.innerHTML}`);
+ }
+
+ return { container, editor };
+}
diff --git a/apps/client/src/widgets/quick_search.tsx b/apps/client/src/widgets/quick_search.tsx
index 92c931373d..4c0ce3a2d1 100644
--- a/apps/client/src/widgets/quick_search.tsx
+++ b/apps/client/src/widgets/quick_search.tsx
@@ -1,5 +1,29 @@
import "./quick_search.css";
+import type { FieldEditor } from "@triliumnext/codemirror/src/field_editor";
+import { useRef, useState } from "preact/hooks";
+
+import { t } from "../services/i18n";
+import { useTriliumEvent } from "./react/hooks";
+import SearchStringEditor from "./ribbon/SearchStringEditor";
+
export default function QuickSearch() {
- return <div className="quick-search">Hello world</div>;
+ const [ searchString, setSearchString ] = useState("");
+ const editorRef = useRef<FieldEditor>();
+
+ useTriliumEvent("quickSearch", () => editorRef.current?.focus());
+
+ return (
+ <div className="quick-search">
+ <SearchStringEditor
+ className="search-string"
+ currentValue={searchString}
+ placeholder={t("quick-search.placeholder")}
+ singleLine
+ editorRef={editorRef}
+ onChange={setSearchString}
+ onEnter={() => {}}
+ />
+ </div>
+ );
}
diff --git a/apps/client/src/widgets/quick_search_old.spec.ts b/apps/client/src/widgets/quick_search_old.spec.ts
index f33fbd57bc..738b1158e5 100644
--- a/apps/client/src/widgets/quick_search_old.spec.ts
+++ b/apps/client/src/widgets/quick_search_old.spec.ts
@@ -6,13 +6,6 @@ import linkService from "../services/link.js";
import server from "../services/server.js";
import QuickSearchWidget from "./quick_search_old.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();
@@ -22,25 +15,17 @@ describe("QuickSearchWidget", () => {
document.body.innerHTML = "";
});
- it("moves focus from the search box to the first result on ArrowDown", async () => {
- const widget = await renderAndSearch();
- const $items = widget.$widget.find(".dropdown-menu .dropdown-item");
-
- 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 () => {
+ it("moves focus to the first result on ArrowDown, only while the popup is open", async () => {
const widget = await renderAndSearch();
const $firstItem = widget.$widget.find(".dropdown-menu .dropdown-item").first();
- pressArrowDown(widget, { ctrlKey: true });
- pressArrowDown(widget, { shiftKey: true });
- expect(document.activeElement).not.toBe($firstItem[0]);
-
widget.$widget.find(".dropdown-menu").removeClass("show");
- pressArrowDown(widget);
+ expect(widget.focusFirstResult()).toBe(false);
expect(document.activeElement).not.toBe($firstItem[0]);
+
+ widget.$widget.find(".dropdown-menu").addClass("show");
+ expect(widget.focusFirstResult()).toBe(true);
+ expect(document.activeElement).toBe($firstItem[0]);
});
it("leaves ArrowDown alone when the popup holds no result to focus", async () => {
@@ -49,16 +34,16 @@ describe("QuickSearchWidget", () => {
const $disabled = widget.$widget.find(".dropdown-menu .dropdown-item.disabled");
expect($disabled.length).toBe(1);
- pressArrowDown(widget);
+ expect(widget.focusFirstResult()).toBe(false);
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 () => {
+ it("searches for the query and hands it to the full search", async () => {
const triggerCommand = vi.spyOn(appContext, "triggerCommand").mockResolvedValue(undefined);
const widget = renderWidget();
mockResults(1);
- setSearchString(widget, "#book AND tolkien");
+ widget.searchString = "#book AND tolkien";
await widget.search();
expect(server.get).toHaveBeenCalledWith(`quick-search/${encodeURIComponent("#book AND tolkien")}`);
@@ -141,31 +126,6 @@ describe("QuickSearchWidget", () => {
});
});
-/**
- * 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
- }));
-}
-
-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) {
const searchResults = Array.from({ length: resultCount }, (_, index) => ({
notePath: `note${index}`,
@@ -185,7 +145,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);
- setSearchString(widget, "hello");
+ widget.searchString = "hello";
await widget.search();
widget.$widget.find(".dropdown-menu").addClass("show");
@@ -196,7 +156,7 @@ function renderWidget() {
const widget = new QuickSearchWidget();
widget.render();
widget.$widget.appendTo(document.body);
- setSearchString(widget, "hello");
+ widget.searchString = "hello";
return widget;
}
diff --git a/apps/client/src/widgets/quick_search_old.ts b/apps/client/src/widgets/quick_search_old.ts
index 650e4cf0f1..8ec9881518 100644
--- a/apps/client/src/widgets/quick_search_old.ts
+++ b/apps/client/src/widgets/quick_search_old.ts
@@ -1,4 +1,3 @@
-import type { FieldEditor } from "@triliumnext/codemirror/src/field_editor";
import { Dropdown, Tooltip } from "bootstrap";
import appContext from "../components/app_context.js";
@@ -9,7 +8,6 @@ import server from "../services/server.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">
@@ -25,7 +23,6 @@ const TPL = /*html*/`
</div>
</div>
</div>
- <div class="form-control form-control-sm search-string ${SEARCH_FIELD_EDITOR_CLASS}"></div>
</div>`;
const INITIAL_DISPLAYED_NOTES = 15;
@@ -54,9 +51,8 @@ interface QuickSearchResponse {
export default class QuickSearchWidget extends BasicWidget {
private dropdown!: bootstrap.Dropdown;
- private $searchField!: JQuery<HTMLElement>;
- /** Holds the query. The widget reads it instead of an input's value. */
- editor?: FieldEditor;
+ /** The query, set by the field that holds it. */
+ searchString = "";
private $dropdownMenu!: JQuery<HTMLElement>;
private $searchResults!: JQuery<HTMLElement>;
private $footer!: JQuery<HTMLElement>;
@@ -73,28 +69,17 @@ export default class QuickSearchWidget extends BasicWidget {
doRender() {
this.$widget = $(TPL);
- 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.$searchField[0],
popperConfig: {
strategy: "fixed",
placement: "bottom"
}
});
- this.editor = createSearchFieldEditor({
- parent: this.$searchField[0],
- placeholder: t("quick-search.placeholder"),
- singleLine: true,
- 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
@@ -109,32 +94,20 @@ export default class QuickSearchWidget extends BasicWidget {
return this.$widget;
}
- cleanup() {
- this.editor?.destroy();
- this.editor = undefined;
- }
-
- /** The query as it stands in the field. */
- private get searchString() {
- return this.editor?.state.doc.toString() ?? "";
- }
-
/** Runs on Enter: opens the results, or refreshes them when they are already open. */
- private runSearch() {
+ runSearch() {
if (this.isDropdownOpen()) {
void this.search();
} else {
this.dropdown.show();
}
-
- this.editor?.focus();
}
/**
* 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() {
+ focusFirstResult() {
if (!this.isDropdownOpen()) {
return false;
}
@@ -150,7 +123,7 @@ export default class QuickSearchWidget extends BasicWidget {
}
/** Closes the results on Escape, leaving the key to CodeMirror when they are already closed. */
- private closeDropdown() {
+ closeDropdown() {
if (!this.isDropdownOpen()) {
return false;
}
@@ -186,7 +159,7 @@ export default class QuickSearchWidget extends BasicWidget {
this.lastResultViewScope = highlightedTokens?.length ? { searchTerms: highlightedTokens } : undefined;
if (error) {
- const tooltip = new Tooltip(this.$searchField[0], {
+ const tooltip = new Tooltip(this.$widget[0], {
trigger: "manual",
title: `Search error: ${error}`,
placement: handleRightToLeftPlacement("right")
@@ -212,7 +185,6 @@ 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.editor?.focus());
this.dropdown.update();
}
@@ -334,8 +306,4 @@ export default class QuickSearchWidget extends BasicWidget {
searchString: this.searchString
});
}
-
- quickSearchEvent() {
- this.editor?.focus();
- }
}
diff --git a/apps/client/src/widgets/ribbon/SearchStringEditor.tsx b/apps/client/src/widgets/ribbon/SearchStringEditor.tsx
index ff1c1ee78f..91d2239045 100644
--- a/apps/client/src/widgets/ribbon/SearchStringEditor.tsx
+++ b/apps/client/src/widgets/ribbon/SearchStringEditor.tsx
@@ -10,8 +10,8 @@ import { createSearchFieldEditor, SEARCH_FIELD_EDITOR_CLASS } from "../search_fi
interface SearchStringEditorProps {
currentValue: string;
- /** The note `currentValue` belongs to. A change to it replaces the document. */
- noteId: string;
+ /** The note `currentValue` belongs to, if any. A change to it replaces the document. */
+ noteId?: string;
placeholder?: string;
/** Names the field where the placeholder is a hint rather than a name for it. */
ariaLabel?: string;