Skip to content

Build your personal knowledge base with Trilium Notes

fix(search): don't fetch result details for a note opened from the results (#11787)

Elian Doraneb7e746cdd06
diff --git a/apps/client/src/widgets/search_result.spec.tsx b/apps/client/src/widgets/search_result.spec.tsx
new file mode 100644
index 0000000000..1113ab7fe3
--- /dev/null
+++ b/apps/client/src/widgets/search_result.spec.tsx
@@ -0,0 +1,91 @@
+import { render } from "preact";
+import { act } from "preact/test-utils";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import type FNote from "../entities/fnote";
+
+// The widget reads the note of the tab it sits in. Like the real hook, the mock re-renders its
+// component when that note changes, which `shownNote.notify()` triggers.
+const shownNote = vi.hoisted(() => ({ current: null as FNote | null, notify: () => {} }));
+vi.mock("./react/hooks", async (importOriginal) => {
+ const { useEffect, useState } = await import("preact/hooks");
+ return {
+ ...(await importOriginal<typeof import("./react/hooks")>()),
+ useNoteContext: () => {
+ const [ note, setNote ] = useState(shownNote.current);
+ useEffect(() => {
+ shownNote.notify = () => setNote(shownNote.current);
+ }, []);
+ return { note, notePath: note?.noteId, ntxId: "ntx1" };
+ }
+ };
+});
+
+import Component from "../components/component";
+import server from "../services/server";
+import { buildNote } from "../test/easy-froca";
+import { ParentComponent } from "./react/react_utils";
+import SearchResult from "./search_result";
+
+let container: HTMLElement;
+let parent: Component;
+
+beforeEach(() => {
+ parent = new Component();
+ container = document.createElement("div");
+ document.body.appendChild(container);
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ render(null, container);
+ container.remove();
+});
+
+describe("SearchResult", () => {
+ it("does not request search result details for a result note opened in the same tab", async () => {
+ const post = vi.spyOn(server, "post").mockResolvedValue({ results: [] });
+ const searchNote = buildNote({
+ id: "searchNote",
+ title: "Search",
+ type: "search",
+ children: [
+ { id: "resultA", title: "A" },
+ { id: "resultB", title: "B" }
+ ]
+ });
+ searchNote.searchResultsLoaded = true;
+ // `useNoteViewType()` reads the shown note, so only a note in list view reaches the card list;
+ // a note in the default grid view mounts `SearchNoteList`, which fetches no details.
+ const resultNote = buildNote({ id: "listNote", title: "List", "#viewType": "list" });
+
+ shownNote.current = searchNote;
+ await mount();
+ expect(container.querySelectorAll(".search-result-card")).toHaveLength(2);
+ expect(post).toHaveBeenCalledWith("search-note/searchNote/result-details", expect.anything());
+
+ await settle(() => {
+ shownNote.current = resultNote;
+ shownNote.notify();
+ });
+ expect(post).not.toHaveBeenCalledWith("search-note/listNote/result-details", expect.anything());
+ expect(container.querySelector(".search-results-list")).toBeNull();
+ });
+});
+
+async function mount() {
+ await settle(() => {
+ render(<ParentComponent.Provider value={parent}><SearchResult /></ParentComponent.Provider>, container);
+ });
+}
+
+async function settle(change: () => void) {
+ await act(change);
+ // Each pass flushes the effects of the re-render the previous one scheduled (`useNoteIds`
+ // loading, `refresh()` updating the state, the details fetch).
+ for (let pass = 0; pass < 3; pass++) {
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ });
+ }
+}
diff --git a/apps/client/src/widgets/search_result.tsx b/apps/client/src/widgets/search_result.tsx
index 15cf84bd0b..7de74a43c7 100644
--- a/apps/client/src/widgets/search_result.tsx
+++ b/apps/client/src/widgets/search_result.tsx
@@ -2,8 +2,9 @@ import "./search_result.css";
import type { HighlightedTokenInfo } from "@triliumnext/commons";
import clsx from "clsx";
-import { useEffect, useState } from "preact/hooks";
+import { useState } from "preact/hooks";
+import type FNote from "../entities/fnote";
import { t } from "../services/i18n";
import { SearchNoteList, useNoteViewType } from "./collections/NoteList";
import SearchResultsList from "./collections/search/SearchResultsList";
@@ -20,23 +21,15 @@ enum SearchResultState {
export default function SearchResult() {
const { note, notePath, ntxId } = useNoteContext();
const viewType = useNoteViewType(note);
- const [ state, setState ] = useState<SearchResultState>();
- const [ highlightedTokens, setHighlightedTokens ] = useState<(string | HighlightedTokenInfo)[]>();
+ const [ , setRefreshCount ] = useState(0);
+ const state = getSearchResultState(note);
+ const highlightedTokens = note?.highlightedTokenInfos ?? note?.highlightedTokens;
+ // The search note is updated in place, so a re-render picks up the new results.
function refresh() {
- if (note?.type !== "search") {
- setState(undefined);
- } else if (!note?.searchResultsLoaded) {
- setState(SearchResultState.NOT_EXECUTED);
- } else if (note.getChildNoteIds().length === 0) {
- setState(SearchResultState.NO_RESULTS);
- } else {
- setState(SearchResultState.GOT_RESULTS);
- setHighlightedTokens(note.highlightedTokenInfos ?? note.highlightedTokens);
- }
+ setRefreshCount((count) => count + 1);
}
- useEffect(() => refresh(), [ note ]);
useTriliumEvent("searchRefreshed", ({ ntxId: eventNtxId }) => {
if (eventNtxId === ntxId) {
refresh();
@@ -84,3 +77,18 @@ export default function SearchResult() {
</div>
);
}
+
+/**
+ * Derives the state from the note being rendered rather than from an effect, so the results never
+ * render for a note that is not a search note, not even for the render that switches to one.
+ */
+function getSearchResultState(note: FNote | null | undefined) {
+ if (note?.type !== "search") {
+ return undefined;
+ } else if (!note.searchResultsLoaded) {
+ return SearchResultState.NOT_EXECUTED;
+ } else if (note.getChildNoteIds().length === 0) {
+ return SearchResultState.NO_RESULTS;
+ }
+ return SearchResultState.GOT_RESULTS;
+}