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
refactor(quick_search): port the results dropdown
Elian Doran0a33aeaa8f02
diff --git a/apps/client/src/widgets/quick_search.css b/apps/client/src/widgets/quick_search.cssindex 445aee4406..1631ec124a 100644--- a/apps/client/src/widgets/quick_search.css+++ b/apps/client/src/widgets/quick_search.css@@ -1,4 +1,5 @@.quick-search {+ display: flex;padding: 10px 10px 10px 0px;height: 50px;@@ -9,6 +10,7 @@.search-string {display: flex;+ flex: 1 1 auto;align-items: center;min-width: 0;@@ -21,22 +23,23 @@white-space: pre;}}+}- .dropdown-menu {- --quick-search-item-delimiter-color: var(--dropdown-border-color);+/* The popup is portaled to `<body>`, outside `.quick-search`. */+.dropdown-menu.quick-search-menu {+ --quick-search-item-delimiter-color: var(--dropdown-border-color);- max-height: 80vh;- min-width: 400px;- max-width: 720px;- overflow: hidden;- text-overflow: ellipsis;- box-shadow: -30px 50px 93px -50px black;+ max-height: 80vh;+ min-width: 400px;+ max-width: 720px;+ overflow: hidden;+ text-overflow: ellipsis;+ box-shadow: -30px 50px 93px -50px black;- /* Bootstrap opens the menu by setting `display`, so the column layout applies only to `.show`. */- &.show {- display: flex;- flex-direction: column;- }+ /* Outranks Bootstrap's `.dropdown-menu.show { display: block }`. */+ &.show {+ display: flex;+ flex-direction: column;}.quick-search-results {diff --git a/apps/client/src/widgets/quick_search.spec.tsx b/apps/client/src/widgets/quick_search.spec.tsxindex b1119f1b0c..ca9138be1b 100644--- a/apps/client/src/widgets/quick_search.spec.tsx+++ b/apps/client/src/widgets/quick_search.spec.tsx@@ -1,7 +1,11 @@+import type { EditorView } from "@codemirror/view";+import type { QuickSearchResponse } from "@triliumnext/commons";import { act } from "preact/test-utils";-import { describe, expect, it, vi } from "vitest";+import { afterEach, describe, expect, it, vi } from "vitest";import Component from "../components/component";+import { calculateHash } from "../services/link";+import server from "../services/server";import { renderInto } from "../test/render";import QuickSearch from "./quick_search";import { ParentComponent } from "./react/react_utils";@@ -14,6 +18,10 @@ vi.mock("./ribbon/search_completions", () => ({}));describe("QuickSearch", () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });+it("renders the search field and focuses it on the quickSearch shortcut", async () => {const host = new Component();const { container, editor } = await mount(host);@@ -26,10 +34,97 @@ describe("QuickSearch", () => {});expect(editor.hasFocus).toBe(true);});++ it("searches on Enter and lists the first results with their highlighted snippets", async () => {+ const get = vi.spyOn(server, "get").mockResolvedValue(response(30, [ "hello" ]));+ const { editor } = await mount();++ typeQuery(editor, " hello ");+ pressEnter(editor);++ expect(get).toHaveBeenCalledWith("quick-search/hello");+ const [ first ] = await waitForResults(15);++ expect(first.getAttribute("href")).toBe(calculateHash({+ notePath: "root/note0",+ viewScope: { searchTerms: [ "hello" ] }+ }));+ expect(first.querySelector(".quick-search-item-icon")?.classList.contains("bx-note")).toBe(true);+ expect(first.querySelector(".search-result-title")?.innerHTML).toBe("<b>Note</b> 0");+ expect(first.querySelector(".search-result-attributes")?.innerHTML).toBe("#year=1954 #author=tolkien");+ expect(first.querySelector(".search-result-content")?.innerHTML).toBe("about <b>hello</b>");+ });++ it("links to the plain note path when the search highlighted nothing", async () => {+ vi.spyOn(server, "get").mockResolvedValue(response(1, []));+ const { editor } = await mount();++ typeQuery(editor, "#book");+ pressEnter(editor);++ const [ first ] = await waitForResults(1);+ expect(first.getAttribute("href")).toBe(calculateHash({ notePath: "root/note0" }));+ });++ it("shows progress while searching, then says when nothing matches", async () => {+ const pending = deferred<QuickSearchResponse>();+ vi.spyOn(server, "get").mockReturnValue(pending.promise as never);+ const { editor } = await mount();++ typeQuery(editor, "nothing");+ pressEnter(editor);++ await vi.waitFor(() => expect(placeholderItems()).toHaveLength(1));+ expect(placeholderItems()[0].querySelector(".bx-loader")).not.toBeNull();++ await act(async () => pending.resolve(response(0, [])));+ await vi.waitFor(() => expect(placeholderItems()[0]?.querySelector(".bx-loader")).toBeNull());+ expect(placeholderItems()).toHaveLength(1);+ expect(resultItems()).toHaveLength(0);+ });++ it("keeps the results of the latest search when an earlier one answers last", async () => {+ const earlier = deferred<QuickSearchResponse>();+ const later = deferred<QuickSearchResponse>();+ vi.spyOn(server, "get")+ .mockReturnValueOnce(earlier.promise as never)+ .mockReturnValueOnce(later.promise as never);+ const { editor } = await mount();++ typeQuery(editor, "first");+ pressEnter(editor);+ await vi.waitFor(() => expect(menu()).not.toBeNull());++ // Enter on open results runs the search again.+ typeQuery(editor, "second");+ pressEnter(editor);++ await act(async () => later.resolve(response(2, [])));+ await act(async () => earlier.resolve(response(5, [])));+ await waitForResults(2);+ });++ it("leaves the results closed for an empty query, and closes them when one is opened", async () => {+ const get = vi.spyOn(server, "get").mockResolvedValue(response(3, []));+ const { editor } = await mount();++ typeQuery(editor, " ");+ pressEnter(editor);+ await act(async () => {});+ expect(get).not.toHaveBeenCalled();+ expect(menu()).toBeNull();++ typeQuery(editor, "hello");+ pressEnter(editor);+ const [ first ] = await waitForResults(3);++ await act(async () => first.click());+ await vi.waitFor(() => expect(menu()).toBeNull());+ });});/** Renders the component and waits for the CodeMirror modules it imports on demand. */-async function mount(host: Component) {+async function mount(host = new Component()) {let container: HTMLDivElement | undefined;act(() => {container = renderInto(@@ -43,7 +138,7 @@ async function mount(host: Component) {}const { EditorView } = await import("@codemirror/view");- let editor: InstanceType<typeof EditorView> | null = null;+ let editor: EditorView | null = null;for (let attempt = 0; attempt < 50 && !editor; attempt++) {await new Promise((resolve) => setTimeout(resolve, 1));const dom = container.querySelector(".cm-editor");@@ -56,3 +151,67 @@ async function mount(host: Component) {return { container, editor };}++function typeQuery(editor: EditorView, value: string) {+ act(() => {+ editor.dispatch({ changes: { from: 0, to: editor.state.doc.length, insert: value } });+ });+}++function pressEnter(editor: EditorView) {+ act(() => {+ editor.contentDOM.dispatchEvent(new KeyboardEvent("keydown", {+ key: "Enter", code: "Enter", bubbles: true, cancelable: true+ }));+ });+}++/** The popup is portaled to `<body>`, outside the rendered container. */+function menu() {+ return document.querySelector<HTMLElement>(".quick-search-menu");+}++function resultItems() {+ return Array.from(menu()?.querySelectorAll<HTMLAnchorElement>(".quick-search-results > a.dropdown-item") ?? []);+}++async function waitForResults(count: number) {+ return vi.waitFor(() => {+ const items = resultItems();+ expect(items).toHaveLength(count);+ return items;+ });+}++/** The disabled row that stands in for results while searching, or when nothing matches. */+function placeholderItems() {+ return Array.from(menu()?.querySelectorAll(".dropdown-item.disabled") ?? []);+}++function response(count: number, highlightedTokens: string[]): QuickSearchResponse {+ const searchResults = Array.from({ length: count }, (_, index) => ({+ noteId: `note${index}`,+ notePath: `root/note${index}`,+ noteTitle: `Note ${index}`,+ notePathTitle: `Note ${index}`,+ highlightedNotePathTitle: `<b>Note</b> ${index}`,+ highlightedAttributeSnippet: "#year=1954<br>#author=tolkien",+ highlightedContentSnippet: "about <b>hello</b>",+ icon: "bx bx-note"+ }));++ return {+ searchResultNoteIds: searchResults.map((result) => result.noteId),+ searchResults,+ highlightedTokens,+ error: null+ };+}++function deferred<T>() {+ let resolve: (value: T) => void = () => {};+ const promise = new Promise<T>((r) => {+ resolve = r;+ });+ return { promise, resolve };+}diff --git a/apps/client/src/widgets/quick_search.tsx b/apps/client/src/widgets/quick_search.tsxindex 4c0ce3a2d1..761366a6a7 100644--- a/apps/client/src/widgets/quick_search.tsx+++ b/apps/client/src/widgets/quick_search.tsx@@ -1,20 +1,84 @@import "./quick_search.css";import type { FieldEditor } from "@triliumnext/codemirror/src/field_editor";+import type { QuickSearchResponse, SearchResultDetails } from "@triliumnext/commons";import { useRef, useState } from "preact/hooks";import { t } from "../services/i18n";+import { calculateHash, type ViewScope } from "../services/link";+import server from "../services/server";+import { DropdownPanel, type DropdownHandle } from "./react/Dropdown";import { useTriliumEvent } from "./react/hooks";+import Icon from "./react/Icon";+import RawHtml, { RawHtmlBlock } from "./react/RawHtml";import SearchStringEditor from "./ribbon/SearchStringEditor";+const INITIAL_DISPLAYED_NOTES = 15;++type SearchState =+ | { status: "searching" }+ | { status: "done", results: SearchResultDetails[], viewScope: ViewScope | undefined };+export default function QuickSearch() {const [ searchString, setSearchString ] = useState("");+ const [ searchState, setSearchState ] = useState<SearchState>();const editorRef = useRef<FieldEditor>();+ const dropdownRef = useRef<DropdownHandle | null>(null);+ const isOpenRef = useRef(false);+ // Each search takes a number, so a slower earlier response cannot overwrite a later one.+ const requestIdRef = useRef(0);useTriliumEvent("quickSearch", () => editorRef.current?.focus());+ async function search() {+ const query = searchString.trim();+ if (!query) {+ dropdownRef.current?.hide();+ return;+ }++ const requestId = ++requestIdRef.current;+ setSearchState({ status: "searching" });+ const { searchResults, highlightedTokens } = await server.get<QuickSearchResponse>(+ `quick-search/${encodeURIComponent(query)}`+ );+ if (requestId !== requestIdRef.current) return;++ setSearchState({+ status: "done",+ results: searchResults,+ // Opens the note at its first match; with nothing highlighted, at the plain path.+ viewScope: highlightedTokens.length ? { searchTerms: highlightedTokens } : undefined+ });+ }+return (<div className="quick-search">+ <DropdownPanel+ className="quick-search-toggle"+ buttonClassName="search-button"+ dropdownContainerClassName="quick-search-menu"+ text={<Icon icon="bx bx-search" />}+ hideToggleArrow+ noSelectButtonStyle+ placement="bottom-start"+ dropdownRef={dropdownRef}+ onShown={() => {+ isOpenRef.current = true;+ void search();+ }}+ onHidden={() => {+ isOpenRef.current = false;+ }}+ >+ <div className="quick-search-results">+ <QuickSearchResults+ searchState={searchState}+ onOpenResult={() => dropdownRef.current?.hide()}+ />+ </div>+ </DropdownPanel>+<SearchStringEditorclassName="search-string"currentValue={searchString}@@ -22,8 +86,90 @@ export default function QuickSearch() {singleLineeditorRef={editorRef}onChange={setSearchString}- onEnter={() => {}}+ onEnter={() => {+ // Opening the results runs the search; open results are refreshed.+ if (isOpenRef.current) {+ void search();+ } else {+ dropdownRef.current?.show();+ }+ editorRef.current?.focus();+ }}+ onEscape={() => {+ if (!isOpenRef.current) return false;+ dropdownRef.current?.hide();+ return true;+ }}/></div>);}++function QuickSearchResults({ searchState, onOpenResult }: {+ searchState: SearchState | undefined;+ onOpenResult(): void;+}) {+ if (!searchState) return null;++ if (searchState.status === "searching") {+ return (+ <span className="dropdown-item disabled">+ <Icon icon="bx bx-loader bx-spin" />+ {t("quick-search.searching")}+ </span>+ );+ }++ if (!searchState.results.length) {+ return <span className="dropdown-item disabled">{t("quick-search.no-results")}</span>;+ }++ return searchState.results.slice(0, INITIAL_DISPLAYED_NOTES).map((result) => (+ <QuickSearchResult+ key={result.notePath}+ result={result}+ viewScope={searchState.viewScope}+ onOpen={onOpenResult}+ />+ ));+}++function QuickSearchResult({ result, viewScope, onOpen }: {+ result: SearchResultDetails;+ viewScope: ViewScope | undefined;+ onOpen(): void;+}) {+ return (+ <a+ className="dropdown-item"+ tabIndex={0}+ href={calculateHash({ notePath: result.notePath, viewScope })}+ onAuxClick={onOpen}+ >+ <div className="quick-search-item">+ <div className="quick-search-item-header">+ <Icon icon={result.icon} className="quick-search-item-icon" />+ <RawHtml+ className="search-result-title"+ html={result.highlightedNotePathTitle ?? result.notePathTitle}+ />+ </div>++ {result.highlightedAttributeSnippet && (+ // The attributes share one line, so the line breaks between them become spaces.+ <RawHtmlBlock+ className="search-result-attributes"+ html={result.highlightedAttributeSnippet.replace(/<br\s?\/?>/g, " ")}+ />+ )}++ {result.highlightedContentSnippet && (+ <RawHtmlBlock+ className="search-result-content"+ html={result.highlightedContentSnippet}+ />+ )}+ </div>+ </a>+ );+}diff --git a/apps/client/src/widgets/quick_search_old.spec.ts b/apps/client/src/widgets/quick_search_old.spec.tsindex 738b1158e5..749c648c35 100644--- a/apps/client/src/widgets/quick_search_old.spec.ts+++ b/apps/client/src/widgets/quick_search_old.spec.ts@@ -1,8 +1,6 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import appContext from "../components/app_context.js";-import froca from "../services/froca.js";-import linkService from "../services/link.js";import server from "../services/server.js";import QuickSearchWidget from "./quick_search_old.js";@@ -108,22 +106,6 @@ describe("QuickSearchWidget", () => {$link[0].dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", code: "Enter", bubbles: true }));expect(triggerCommand).toHaveBeenCalledWith("searchNotes", { searchString: "hello" });});-- it("puts the results of a search the server did not highlight in the same scroller", async () => {- const widget = renderWidget();- vi.spyOn(server, "get").mockResolvedValue({- searchResultNoteIds: [ "note0", "note1" ],- error: ""- } as never);- vi.spyOn(froca, "getNotes").mockResolvedValue([ { noteId: "note0" }, { noteId: "note1" } ] as never);- vi.spyOn(linkService, "createLink").mockImplementation(async (notePath) => $("<span>").text(String(notePath)));-- await widget.search();-- const $menu = widget.$widget.find(".dropdown-menu");- expect($menu.find(".quick-search-results > .dropdown-item").length).toBe(2);- expect($menu.children().last().hasClass("quick-search-footer")).toBe(true);- });});async function renderAndSearch(resultCount = 3) {@@ -138,6 +120,7 @@ async function renderAndSearch(resultCount = 3) {vi.spyOn(server, "get").mockResolvedValue({searchResultNoteIds: searchResults.map((result) => result.notePath),searchResults,+ highlightedTokens: [],error: ""} as never);diff --git a/apps/client/src/widgets/quick_search_old.ts b/apps/client/src/widgets/quick_search_old.tsindex 8ec9881518..36b8c1f7c5 100644--- a/apps/client/src/widgets/quick_search_old.ts+++ b/apps/client/src/widgets/quick_search_old.ts@@ -1,9 +1,9 @@+import type { QuickSearchResponse, SearchResultDetails } from "@triliumnext/commons";import { Dropdown, Tooltip } from "bootstrap";import appContext from "../components/app_context.js";-import froca from "../services/froca.js";import { t } from "../services/i18n.js";-import linkService, { calculateHash, type ViewScope } from "../services/link.js";+import { calculateHash, type ViewScope } from "../services/link.js";import server from "../services/server.js";import shortcutService from "../services/shortcuts.js";import utils, { handleRightToLeftPlacement } from "../services/utils.js";@@ -28,26 +28,6 @@ const TPL = /*html*/`const INITIAL_DISPLAYED_NOTES = 15;const LOAD_MORE_BATCH_SIZE = 10;--// TODO: Deduplicate with server.-interface QuickSearchResponse {- searchResultNoteIds: string[];- searchResults?: Array<{- notePath: string;- noteTitle: string;- notePathTitle: string;- highlightedNotePathTitle: string;- contentSnippet?: string;- highlightedContentSnippet?: string;- attributeSnippet?: string;- highlightedAttributeSnippet?: string;- icon: string;- }>;- /** Plain search tokens the server highlighted; consumed by jump-to-match producers. */- highlightedTokens?: string[];- error: string;-}-export default class QuickSearchWidget extends BasicWidget {private dropdown!: bootstrap.Dropdown;@@ -58,8 +38,7 @@ export default class QuickSearchWidget extends BasicWidget {private $footer!: JQuery<HTMLElement>;// State for infinite scrolling- private allSearchResults: Array<any> = [];- private allSearchResultNoteIds: string[] = [];+ private allSearchResults: SearchResultDetails[] = [];private currentDisplayedCount: number = 0;private isLoadingMore: boolean = false;@@ -80,8 +59,6 @@ export default class QuickSearchWidget extends BasicWidget {}});- this.$widget.find(".input-group-prepend").on("shown.bs.dropdown", () => this.search());-// Add scroll event listener for infinite scrollingthis.$searchResults.on("scroll", () => {this.handleScroll();@@ -94,15 +71,6 @@ export default class QuickSearchWidget extends BasicWidget {return this.$widget;}- /** Runs on Enter: opens the results, or refreshes them when they are already open. */- runSearch() {- if (this.isDropdownOpen()) {- void this.search();- } else {- this.dropdown.show();- }- }-/*** 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.@@ -122,16 +90,6 @@ export default class QuickSearchWidget extends BasicWidget {return true;}- /** Closes the results on Escape, leaving the key to CodeMirror when they are already closed. */- closeDropdown() {- if (!this.isDropdownOpen()) {- return false;- }-- this.dropdown.hide();- return true;- }-async search() {const searchString = this.searchString.trim();@@ -142,7 +100,6 @@ export default class QuickSearchWidget extends BasicWidget {// Reset state for new searchthis.allSearchResults = [];- this.allSearchResultNoteIds = [];this.currentDisplayedCount = 0;this.isLoadingMore = false;@@ -154,9 +111,9 @@ export default class QuickSearchWidget extends BasicWidget {${t("quick-search.searching")}</span>`);- const { searchResultNoteIds, searchResults, highlightedTokens, error } = await server.get<QuickSearchResponse>(`quick-search/${encodeURIComponent(searchString)}`);+ const { searchResults, highlightedTokens, error } = await server.get<QuickSearchResponse>(`quick-search/${encodeURIComponent(searchString)}`);- this.lastResultViewScope = highlightedTokens?.length ? { searchTerms: highlightedTokens } : undefined;+ this.lastResultViewScope = highlightedTokens.length ? { searchTerms: highlightedTokens } : undefined;if (error) {const tooltip = new Tooltip(this.$widget[0], {@@ -171,12 +128,11 @@ export default class QuickSearchWidget extends BasicWidget {}// Store all results for infinite scrolling- this.allSearchResults = searchResults || [];- this.allSearchResultNoteIds = searchResultNoteIds || [];+ this.allSearchResults = searchResults;this.$searchResults.empty();- if (this.allSearchResults.length === 0 && this.allSearchResultNoteIds.length === 0) {+ if (this.allSearchResults.length === 0) {this.$searchResults.append(`<span class="dropdown-item disabled">${t("quick-search.no-results")}</span>`);return;}@@ -193,86 +149,55 @@ export default class QuickSearchWidget extends BasicWidget {if (this.isLoadingMore) return;this.isLoadingMore = true;- // Use highlighted search results if available, otherwise fall back to basic display- if (this.allSearchResults.length > 0) {- const startIndex = this.currentDisplayedCount;- const endIndex = Math.min(startIndex + batchSize, this.allSearchResults.length);- const resultsToDisplay = this.allSearchResults.slice(startIndex, endIndex);-- for (const result of resultsToDisplay) {- if (!result.notePath) continue;-- // Set the href with .attr() rather than interpolating it into the HTML string, so- // the query separators are not parsed as HTML entities.- const $item = $(`<a class="dropdown-item" tabindex="0">`);- $item.attr("href", calculateHash({ notePath: result.notePath, viewScope: this.lastResultViewScope }));-- // Build the display HTML with content snippet below the title- let itemHtml = `<div class="quick-search-item">- <div class="quick-search-item-header">- <span class="quick-search-item-icon ${utils.escapeHtml(result.icon)}"></span>- <span class="search-result-title">${result.highlightedNotePathTitle}</span>- </div>`;-- // Add attribute snippet (tags/attributes) below the title if available- if (result.highlightedAttributeSnippet) {- // Replace <br> with a blank space to join the atributes on the same single line- const snippet = (result.highlightedAttributeSnippet as string).replace(/<br\s?\/?>/g, " ");- itemHtml += `<div class="search-result-attributes">${snippet}</div>`;- }-- // Add content snippet below the attributes if available- if (result.highlightedContentSnippet) {- itemHtml += `<div class="search-result-content">${result.highlightedContentSnippet}</div>`;- }-- itemHtml += `</div>`;-- $item.html(itemHtml);-- $item.on("click auxclick", () => {- this.dropdown.hide();- });-- shortcutService.bindElShortcut($item, "return", () => {- this.dropdown.hide();- $item[0].click();- });-- this.$searchResults.append($item);+ const startIndex = this.currentDisplayedCount;+ const endIndex = Math.min(startIndex + batchSize, this.allSearchResults.length);+ const resultsToDisplay = this.allSearchResults.slice(startIndex, endIndex);++ for (const result of resultsToDisplay) {+ if (!result.notePath) continue;++ // Set the href with .attr() rather than interpolating it into the HTML string, so+ // the query separators are not parsed as HTML entities.+ const $item = $(`<a class="dropdown-item" tabindex="0">`);+ $item.attr("href", calculateHash({ notePath: result.notePath, viewScope: this.lastResultViewScope }));++ // Build the display HTML with content snippet below the title+ let itemHtml = `<div class="quick-search-item">+ <div class="quick-search-item-header">+ <span class="quick-search-item-icon ${utils.escapeHtml(result.icon)}"></span>+ <span class="search-result-title">${result.highlightedNotePathTitle}</span>+ </div>`;++ // Add attribute snippet (tags/attributes) below the title if available+ if (result.highlightedAttributeSnippet) {+ // Replace <br> with a blank space to join the atributes on the same single line+ const snippet = (result.highlightedAttributeSnippet as string).replace(/<br\s?\/?>/g, " ");+ itemHtml += `<div class="search-result-attributes">${snippet}</div>`;}- this.currentDisplayedCount = endIndex;- } else {- // Fallback to original behavior if no highlighted results- const startIndex = this.currentDisplayedCount;- const endIndex = Math.min(startIndex + batchSize, this.allSearchResultNoteIds.length);- const noteIdsToDisplay = this.allSearchResultNoteIds.slice(startIndex, endIndex);-- for (const note of await froca.getNotes(noteIdsToDisplay)) {- const $link = await linkService.createLink(note.noteId, { showNotePath: true, showNoteIcon: true, viewScope: this.lastResultViewScope });- $link.addClass("dropdown-item");- $link.attr("tabIndex", "0");- $link.on("click auxclick", (e) => {- this.dropdown.hide();-- if (!e.target || (e.target as HTMLElement).nodeName !== "A") {- // click on the <a> is handled by the global goToLink handler,- // but we want the whole item clickable- $link.find("a")[0]?.dispatchEvent(new MouseEvent(e.type, e.originalEvent as MouseEventInit));- }- });- shortcutService.bindElShortcut($link, "return", () => {- this.dropdown.hide();- $link.find("a")[0]?.click();- });-- this.$searchResults.append($link);+ // Add content snippet below the attributes if available+ if (result.highlightedContentSnippet) {+ itemHtml += `<div class="search-result-content">${result.highlightedContentSnippet}</div>`;}- this.currentDisplayedCount = endIndex;+ itemHtml += `</div>`;++ $item.html(itemHtml);++ $item.on("click auxclick", () => {+ this.dropdown.hide();+ });++ shortcutService.bindElShortcut($item, "return", () => {+ this.dropdown.hide();+ $item[0].click();+ });++ this.$searchResults.append($item);}+ this.currentDisplayedCount = endIndex;+this.isLoadingMore = false;}@@ -286,9 +211,7 @@ export default class QuickSearchWidget extends BasicWidget {// Trigger loading more when user scrolls near the bottom (within 50px)if (scrollTop + clientHeight >= scrollHeight - 50) {- const totalResults = this.allSearchResults.length > 0 ? this.allSearchResults.length : this.allSearchResultNoteIds.length;-- if (this.currentDisplayedCount < totalResults) {+ if (this.currentDisplayedCount < this.allSearchResults.length) {this.displayMoreResults(LOAD_MORE_BATCH_SIZE).then(() => this.dropdown.update());}}diff --git a/packages/commons/src/lib/server_api.ts b/packages/commons/src/lib/server_api.tsindex 3f24aed5a4..71c1cd69a5 100644--- a/packages/commons/src/lib/server_api.ts+++ b/packages/commons/src/lib/server_api.ts@@ -389,6 +389,15 @@ export interface SearchResultDetails {icon: string;}+/** Response for `GET /api/quick-search/:searchString`. */+export interface QuickSearchResponse {+ searchResultNoteIds: string[];+ searchResults: SearchResultDetails[];+ /** Plain search tokens the server highlighted, for jumping to the first match. */+ highlightedTokens: string[];+ error: string | null;+}+/** Response for `POST /api/search-note/:noteId/result-details`. */export interface SearchResultDetailsResponse {/** Requested-order details; requested ids not in the result set are omitted. */diff --git a/packages/trilium-core/src/routes/api/search.ts b/packages/trilium-core/src/routes/api/search.tsindex 558b6902c6..e4bf33883a 100644--- a/packages/trilium-core/src/routes/api/search.ts+++ b/packages/trilium-core/src/routes/api/search.ts@@ -1,7 +1,7 @@import {- dayjs, type SearchLintRequest, type SearchLintResponse, type SearchResultDetails,- type SearchResultDetailsRequest, type SearchResultDetailsResponse, type SearchWithTokensResponse,- type TemplatesResponse+ dayjs, type QuickSearchResponse, type SearchLintRequest, type SearchLintResponse,+ type SearchResultDetails, type SearchResultDetailsRequest, type SearchResultDetailsResponse,+ type SearchWithTokensResponse, type TemplatesResponse} from "@triliumnext/commons";import type { Request } from "../../http_interface";@@ -126,7 +126,7 @@ function lintSearchString(req: Request): SearchLintResponse {return { error: searchService.validateSearchQuery(searchString) };}-function quickSearch(req: Request<{ searchString: string }>) {+function quickSearch(req: Request<{ searchString: string }>): QuickSearchResponse {const { searchString } = req.params;const searchContext = new SearchContext({