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' infinite scroll
Elian Doran58126d31ff42
diff --git a/apps/client/src/widgets/quick_search.spec.tsx b/apps/client/src/widgets/quick_search.spec.tsxindex c041a97013..01ef5acb99 100644--- a/apps/client/src/widgets/quick_search.spec.tsx+++ b/apps/client/src/widgets/quick_search.spec.tsx@@ -210,6 +210,36 @@ describe("QuickSearch", () => {expect(editor.hasFocus).toBe(true);});+ it("shows more results as the list is scrolled to its end, and starts over on a new search", async () => {+ vi.spyOn(server, "get").mockResolvedValue(response(30, []));+ const { editor } = await mount();++ typeQuery(editor, "hello");+ pressEnter(editor);+ await waitForResults(15);++ const scroller = menu()?.querySelector<HTMLElement>(".quick-search-results");+ if (!scroller) throw new Error("The results did not render.");+ const scrollTo = (scrollTop: number) => act(() => {+ setScrollMetrics(scroller, { scrollTop, clientHeight: 400, scrollHeight: 1000 });+ scroller.dispatchEvent(new Event("scroll"));+ });++ scrollTo(500);+ expect(resultItems()).toHaveLength(15);++ // Within 50px of the end.+ scrollTo(560);+ await waitForResults(25);+ scrollTo(600);+ await waitForResults(30);+ scrollTo(600);+ expect(resultItems()).toHaveLength(30);++ pressEnter(editor);+ await waitForResults(15);+ });+it("leaves the open results alone while the query is typed", async () => {vi.spyOn(server, "get").mockResolvedValue(response(15, []));const { editor } = await mount();@@ -307,6 +337,13 @@ function pressArrowDown(editor: EditorView, modifiers: KeyboardEventInit = {}) {});}+/** Gives `element` the scroll metrics happy-dom, which lays nothing out, leaves at 0. */+function setScrollMetrics(element: HTMLElement, metrics: { scrollTop: number, clientHeight: number, scrollHeight: number }) {+ for (const [ name, value ] of Object.entries(metrics)) {+ Object.defineProperty(element, name, { configurable: true, get: () => value });+ }+}+/** The popup is portaled to `<body>`, outside the rendered container. */function menu() {return document.querySelector<HTMLElement>(".quick-search-menu");diff --git a/apps/client/src/widgets/quick_search.tsx b/apps/client/src/widgets/quick_search.tsxindex 9ffe1ac1fc..53a4df12f3 100644--- a/apps/client/src/widgets/quick_search.tsx+++ b/apps/client/src/widgets/quick_search.tsx@@ -18,6 +18,9 @@ import RawHtml, { RawHtmlBlock } from "./react/RawHtml";import SearchStringEditor from "./ribbon/SearchStringEditor";const INITIAL_DISPLAYED_NOTES = 15;+const LOAD_MORE_BATCH_SIZE = 10;+/** How close to the end of the list, in pixels, scrolling shows the next batch. */+const LOAD_MORE_THRESHOLD = 50;type SearchState =| { status: "searching" }@@ -29,6 +32,7 @@ export default function QuickSearch() {const [ hasQuery, setHasQuery ] = useState(false);const [ searchState, setSearchState ] = useState<SearchState>();const [ open, setOpen ] = useState(false);+ const [ displayedCount, setDisplayedCount ] = useState(INITIAL_DISPLAYED_NOTES);const editorRef = useRef<FieldEditor>();const boxRef = useRef<HTMLDivElement>(null);const popupRef = useRef<HTMLDivElement | null>(null);@@ -54,6 +58,7 @@ export default function QuickSearch() {);if (requestId !== requestIdRef.current) return;+ setDisplayedCount(INITIAL_DISPLAYED_NOTES);setSearchState({status: "done",results: searchResults,@@ -62,6 +67,16 @@ export default function QuickSearch() {});}+ /** Shows the next batch of results once `scroller` is scrolled near its end. */+ function showMoreAtEnd(scroller: HTMLElement) {+ const total = searchState?.status === "done" ? searchState.results.length : 0;+ const { scrollTop, clientHeight, scrollHeight } = scroller;+ const nearEnd = scrollTop + clientHeight >= scrollHeight - LOAD_MORE_THRESHOLD;+ if (displayedCount >= total || !nearEnd) return;+ // From the rendered count, so scroll events before the next render ask for the same one.+ setDisplayedCount(displayedCount + LOAD_MORE_BATCH_SIZE);+ }+function close() {// Focus on a result goes back to the field, rather than to the page's body.if (popupRef.current?.contains(document.activeElement)) editorRef.current?.focus();@@ -109,8 +124,15 @@ export default function QuickSearch() {elementRef={popupRef}onDismiss={close}>- <div className="quick-search-results">- <QuickSearchResults searchState={searchState} onOpenResult={close} />+ <div+ className="quick-search-results"+ onScroll={(e) => showMoreAtEnd(e.currentTarget)}+ >+ <QuickSearchResults+ searchState={searchState}+ displayedCount={displayedCount}+ onOpenResult={close}+ /></div></Popup>)}@@ -156,8 +178,9 @@ function firstResult(popup: HTMLElement) {return popup.querySelector(".dropdown-item:not(.disabled)");}-function QuickSearchResults({ searchState, onOpenResult }: {+function QuickSearchResults({ searchState, displayedCount, onOpenResult }: {searchState: SearchState | undefined;+ displayedCount: number;onOpenResult(): void;}) {if (!searchState) return null;@@ -175,7 +198,7 @@ function QuickSearchResults({ searchState, onOpenResult }: {return <span className="dropdown-item disabled">{t("quick-search.no-results")}</span>;}- return searchState.results.slice(0, INITIAL_DISPLAYED_NOTES).map((result) => (+ return searchState.results.slice(0, displayedCount).map((result) => (<QuickSearchResultkey={result.notePath}result={result}diff --git a/apps/client/src/widgets/quick_search_old.spec.ts b/apps/client/src/widgets/quick_search_old.spec.tsindex 41813763eb..9118f38189 100644--- a/apps/client/src/widgets/quick_search_old.spec.ts+++ b/apps/client/src/widgets/quick_search_old.spec.ts@@ -27,29 +27,20 @@ describe("QuickSearchWidget", () => {expect(triggerCommand).toHaveBeenCalledWith("searchNotes", { searchString: "#book AND tolkien" });});- it("keeps the full search link pinned below the scrolling results as more load", async () => {+ it("keeps the full search link pinned below the scrolling results", async () => {const widget = renderWidget();mockResults(30);await widget.search();const $menu = widget.$widget.find(".dropdown-menu");- const $results = $menu.find(".quick-search-results");const $footer = $menu.find(".quick-search-footer");// The results scroll on their own, so the footer stays visible at the bottom of the menu.- expect($results.children(".dropdown-item").length).toBe(15);- expect($results.find(".show-in-full-search").length).toBe(0);+ expect($menu.find(".quick-search-results .show-in-full-search").length).toBe(0);expect($menu.children().last().is($footer)).toBe(true);expect($footer.hasClass("hidden-ext")).toBe(false);expect($footer.find(".show-in-full-search").length).toBe(1);-- // happy-dom reports zero scroll metrics, which reads as "scrolled to the bottom".- $results.trigger("scroll");- await vi.waitFor(() => expect($results.children(".dropdown-item").length).toBe(25));-- expect($menu.children().last().is($footer)).toBe(true);- expect($footer.find(".show-in-full-search").length).toBe(1);});it("hides the full search link while searching and when nothing matches", async () => {@@ -66,7 +57,6 @@ describe("QuickSearchWidget", () => {await search;expect($footer.hasClass("hidden-ext")).toBe(true);- expect(widget.$widget.find(".quick-search-results .dropdown-item.disabled").length).toBe(1);});it("runs the full search from the pinned link, by click and by Enter", async () => {diff --git a/apps/client/src/widgets/quick_search_old.ts b/apps/client/src/widgets/quick_search_old.tsindex 43023ec882..a566d886ee 100644--- a/apps/client/src/widgets/quick_search_old.ts+++ b/apps/client/src/widgets/quick_search_old.ts@@ -1,12 +1,11 @@-import type { QuickSearchResponse, SearchResultDetails } from "@triliumnext/commons";+import type { QuickSearchResponse } from "@triliumnext/commons";import { Dropdown, Tooltip } from "bootstrap";import appContext from "../components/app_context.js";import { t } from "../services/i18n.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";+import { handleRightToLeftPlacement } from "../services/utils.js";import BasicWidget from "./basic_widget.js";const TPL = /*html*/`@@ -25,32 +24,16 @@ const TPL = /*html*/`</div></div>`;-const INITIAL_DISPLAYED_NOTES = 15;-const LOAD_MORE_BATCH_SIZE = 10;-export default class QuickSearchWidget extends BasicWidget {private dropdown!: bootstrap.Dropdown;/** The query, set by the field that holds it. */searchString = "";- private $dropdownMenu!: JQuery<HTMLElement>;- private $searchResults!: JQuery<HTMLElement>;private $footer!: JQuery<HTMLElement>;- // State for infinite scrolling- private allSearchResults: SearchResultDetails[] = [];- private currentDisplayedCount: number = 0;- private isLoadingMore: boolean = false;-- // Attached to each result link so the opened note jumps to the first match; undefined when the- // last search highlighted nothing, which keeps the links at a plain `#notePath`.- private lastResultViewScope: ViewScope | undefined;-doRender() {this.$widget = $(TPL);- this.$dropdownMenu = this.$widget.find(".dropdown-menu");- this.$searchResults = this.$dropdownMenu.find(".quick-search-results");- this.$footer = this.$dropdownMenu.find(".quick-search-footer");+ this.$footer = this.$widget.find(".quick-search-footer");this.dropdown = Dropdown.getOrCreateInstance(this.$widget.find("[data-bs-toggle='dropdown']")[0], {popperConfig: {@@ -59,11 +42,6 @@ export default class QuickSearchWidget extends BasicWidget {}});- // Add scroll event listener for infinite scrolling- this.$searchResults.on("scroll", () => {- this.handleScroll();- });-const $showInFullSearchButton = this.$footer.find(".show-in-full-search");$showInFullSearchButton.on("click", () => this.showInFullSearch());shortcutService.bindElShortcut($showInFullSearchButton, "return", () => this.showInFullSearch());@@ -79,22 +57,9 @@ export default class QuickSearchWidget extends BasicWidget {return;}- // Reset state for new search- this.allSearchResults = [];- this.currentDisplayedCount = 0;- this.isLoadingMore = false;-this.$footer.addClass("hidden-ext");- this.$searchResults.empty();- this.$searchResults.append(`- <span class="dropdown-item disabled">- <span class="bx bx-loader bx-spin"></span>- ${t("quick-search.searching")}- </span>`);-- const { searchResults, highlightedTokens, error } = await server.get<QuickSearchResponse>(`quick-search/${encodeURIComponent(searchString)}`);- this.lastResultViewScope = highlightedTokens.length ? { searchTerms: highlightedTokens } : undefined;+ const { searchResults, error } = await server.get<QuickSearchResponse>(`quick-search/${encodeURIComponent(searchString)}`);if (error) {const tooltip = new Tooltip(this.$widget[0], {@@ -108,93 +73,8 @@ export default class QuickSearchWidget extends BasicWidget {setTimeout(() => tooltip.dispose(), 4000);}- // Store all results for infinite scrolling- this.allSearchResults = searchResults;-- this.$searchResults.empty();-- if (this.allSearchResults.length === 0) {- this.$searchResults.append(`<span class="dropdown-item disabled">${t("quick-search.no-results")}</span>`);- return;- }-- // Display initial batch- await this.displayMoreResults(INITIAL_DISPLAYED_NOTES);-- this.$footer.removeClass("hidden-ext");-- this.dropdown.update();- }-- private async displayMoreResults(batchSize: number) {- if (this.isLoadingMore) return;- this.isLoadingMore = true;-- 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);- }-- this.currentDisplayedCount = endIndex;-- this.isLoadingMore = false;- }-- private handleScroll() {- if (this.isLoadingMore) return;-- const results = this.$searchResults[0];- const scrollTop = results.scrollTop;- const scrollHeight = results.scrollHeight;- const clientHeight = results.clientHeight;-- // Trigger loading more when user scrolls near the bottom (within 50px)- if (scrollTop + clientHeight >= scrollHeight - 50) {- if (this.currentDisplayedCount < this.allSearchResults.length) {- this.displayMoreResults(LOAD_MORE_BATCH_SIZE).then(() => this.dropdown.update());- }+ if (searchResults.length) {+ this.$footer.removeClass("hidden-ext");}}