Skip to content

Build your personal knowledge base with Trilium Notes

feat(search): run a saved search when it is shown

Elian Doran2bd795ad811f
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index b3c8daa86b..ff9671e8f7 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -2860,7 +2860,8 @@
"result_count_one": "{{count}} result",
"result_count_other": "{{count}} results",
"page_size": "Per page",
- "snippet_unavailable": "No preview available."
+ "snippet_unavailable": "No preview available.",
+ "searching": "Searching..."
},
"sql_result": {
"not_executed": "The query has not been executed yet.",
diff --git a/apps/client/src/widgets/NoteDetail.spec.ts b/apps/client/src/widgets/NoteDetail.spec.ts
index 9b21b5928e..62f4c34a97 100644
--- a/apps/client/src/widgets/NoteDetail.spec.ts
+++ b/apps/client/src/widgets/NoteDetail.spec.ts
@@ -10,7 +10,8 @@ import froca from "../services/froca";
// global the test env doesn't provide. The pure function under test never touches the tree, so stub it.
vi.mock("./note_tree", () => ({ default: class {} }));
-import { getExtendedWidgetType, isContextInActiveTab, useDeferredDetailFocus } from "./NoteDetail";
+import { getExtendedWidgetType, useDeferredDetailFocus } from "./NoteDetail";
+import { isContextInActiveTab } from "./react/hooks";
const FAKE_NOTE_ID = "blob-stub-note";
diff --git a/apps/client/src/widgets/NoteDetail.tsx b/apps/client/src/widgets/NoteDetail.tsx
index 35963747e9..def48ee147 100644
--- a/apps/client/src/widgets/NoteDetail.tsx
+++ b/apps/client/src/widgets/NoteDetail.tsx
@@ -19,7 +19,7 @@ import toast from "../services/toast.js";
import { isElectron } from "../services/utils";
import { ExtendedNoteType, TYPE_MAPPINGS, TypeWidget } from "./note_types";
import Button from "./react/Button";
-import { useDelayedVisibility, useGetContextDataFrom, useNoteContext, useTriliumEvent } from "./react/hooks";
+import { useDelayedVisibility, useGetContextDataFrom, useHasTabBeenShown, useNoteContext, useTriliumEvent } from "./react/hooks";
import Icon from "./react/Icon";
import NoItems from "./react/NoItems";
import { NoteListWithLinks } from "./react/NoteList";
@@ -47,24 +47,7 @@ export default function NoteDetail() {
const widgetRequestId = useRef(0);
// Defer loading for tabs that haven't been active yet (e.g. on app refresh).
- // A tab can hold multiple splits; activating the tab makes all of them visible at once, so deferral
- // is keyed on the whole tab (the main context) rather than the individual split. Keying it on the
- // active split would leave the non-focused split of the active tab blank until it's clicked.
- // Special contexts (ntxId starting with "_", e.g. popup editor) are always considered active.
- const isSpecialContext = ntxId?.startsWith("_") ?? false;
- const isInActiveTab = () =>
- isContextInActiveTab(noteContext, appContext.tabManager.getActiveMainContext()?.ntxId);
- const [ hasTabBeenActive, setHasTabBeenActive ] = useState(() => isSpecialContext || isInActiveTab());
- useEffect(() => {
- if (!hasTabBeenActive && isInActiveTab()) {
- setHasTabBeenActive(true);
- }
- }, [ noteContext, hasTabBeenActive ]); // eslint-disable-line react-hooks/exhaustive-deps
- useTriliumEvent("activeNoteChanged", () => {
- if (!hasTabBeenActive && isInActiveTab()) {
- setHasTabBeenActive(true);
- }
- });
+ const hasTabBeenActive = useHasTabBeenShown(noteContext);
const props: TypeWidgetProps = {
note: note!,
@@ -272,20 +255,6 @@ export function useDeferredDetailFocus(isReady: boolean, replay: (data: EventDat
}, [ isReady ]);
}
-/**
- * True when the given context belongs to the active tab, identified by `activeMainNtxId` (the ntxId of
- * the active tab's main context). A tab can hold several splits, but only one of them is the "active"
- * context at a time; every split of the active tab is visible and must load eagerly, so the deferral
- * check is keyed on the tab (the main context), not the individual split.
- */
-export function isContextInActiveTab(noteContext: NoteContext | undefined, activeMainNtxId: string | null | undefined): boolean {
- if (!noteContext || activeMainNtxId == null) {
- return false;
- }
-
- return activeMainNtxId === noteContext.getMainContext().ntxId;
-}
-
/**
* Wraps a single note type widget, in order to keep it in the DOM even after the user has switched away to another note type. This allows faster loading of the same note type again. The properties are cached, so that they are updated only
* while the widget is visible, to avoid rendering in the background. When not visible, the DOM element is simply hidden.
diff --git a/apps/client/src/widgets/react/hooks.tsx b/apps/client/src/widgets/react/hooks.tsx
index 2c3b983dfa..a71129e8e8 100644
--- a/apps/client/src/widgets/react/hooks.tsx
+++ b/apps/client/src/widgets/react/hooks.tsx
@@ -524,6 +524,45 @@ function findClosestNoteContext(component: Component | null): NoteContext | unde
return undefined;
}
+/**
+ * Whether the tab holding `noteContext` has been shown since the component mounted. A tab restored or
+ * opened in the background reads `false` until the user switches to it. Every split of a tab is shown
+ * with it, so the check is keyed on the tab's main context. Special contexts (an ntxId starting with
+ * "_", such as the popup editor) always read `true`.
+ */
+export function useHasTabBeenShown(noteContext: NoteContext | undefined) {
+ const isShown = () => (noteContext?.ntxId?.startsWith("_") ?? false)
+ || isContextInActiveTab(noteContext, appContext.tabManager.getActiveMainContext()?.ntxId);
+ const [ hasBeenShown, setHasBeenShown ] = useState(isShown);
+
+ useEffect(() => {
+ if (!hasBeenShown && isShown()) {
+ setHasBeenShown(true);
+ }
+ }, [ noteContext, hasBeenShown ]); // eslint-disable-line react-hooks/exhaustive-deps
+ useTriliumEvent("activeNoteChanged", () => {
+ if (!hasBeenShown && isShown()) {
+ setHasBeenShown(true);
+ }
+ });
+
+ return hasBeenShown;
+}
+
+/**
+ * True when the given context belongs to the active tab, identified by `activeMainNtxId` (the ntxId of
+ * the active tab's main context). A tab can hold several splits, but only one of them is the "active"
+ * context at a time; every split of the active tab is visible and must load eagerly, so the deferral
+ * check is keyed on the tab (the main context), not the individual split.
+ */
+export function isContextInActiveTab(noteContext: NoteContext | undefined, activeMainNtxId: string | null | undefined): boolean {
+ if (!noteContext || activeMainNtxId == null) {
+ return false;
+ }
+
+ return activeMainNtxId === noteContext.getMainContext().ntxId;
+}
+
/**
* Similar to {@link useNoteContext}, but instead of using the note context from the split container that the component is part of, it uses the active note context instead
* (the note currently focused by the user).
diff --git a/apps/client/src/widgets/search_result.spec.tsx b/apps/client/src/widgets/search_result.spec.tsx
index 729c79d1b7..a819302688 100644
--- a/apps/client/src/widgets/search_result.spec.tsx
+++ b/apps/client/src/widgets/search_result.spec.tsx
@@ -11,6 +11,8 @@ const shownNote = vi.hoisted(() => ({
notify: () => {},
parentComponent: null as import("../components/component").default | null
}));
+const shownTab = vi.hoisted(() => ({ activeMainNtxId: "ntx1" as string | null }));
+const tabContext = vi.hoisted(() => ({ ntxId: "ntx1", getMainContext() { return tabContext; } }));
vi.mock("./react/hooks", async (importOriginal) => {
const { useEffect, useState } = await import("preact/hooks");
return {
@@ -20,7 +22,13 @@ vi.mock("./react/hooks", async (importOriginal) => {
useEffect(() => {
shownNote.notify = () => setNote(shownNote.current);
}, []);
- return { note, notePath: note?.noteId, ntxId: "ntx1", parentComponent: shownNote.parentComponent };
+ return {
+ note,
+ notePath: note?.noteId,
+ ntxId: "ntx1",
+ noteContext: tabContext,
+ parentComponent: shownNote.parentComponent
+ };
}
};
});
@@ -34,10 +42,17 @@ import { buildNote } from "../test/easy-froca";
import { ParentComponent } from "./react/react_utils";
import SearchResult from "./search_result";
+const realTabManager = appContext.tabManager;
let container: HTMLElement;
let parent: Component;
beforeEach(() => {
+ shownTab.activeMainNtxId = "ntx1";
+ // Client tests run without app start-up, which is what creates the tab manager.
+ appContext.tabManager = {
+ getActiveMainContext: () => (shownTab.activeMainNtxId ? { ntxId: shownTab.activeMainNtxId } : null)
+ } as never;
+ window.glob.TRILIUM_SAFE_MODE = false;
parent = new Component();
shownNote.parentComponent = parent;
container = document.createElement("div");
@@ -46,6 +61,7 @@ beforeEach(() => {
afterEach(() => {
vi.restoreAllMocks();
+ appContext.tabManager = realTabManager;
render(null, container);
container.remove();
});
@@ -88,6 +104,7 @@ describe("SearchResult", () => {
});
const showError = vi.spyOn(toast, "showError").mockImplementation(() => {});
const triggerEvent = vi.spyOn(parent, "triggerEvent").mockImplementation((name, data) => parent.handleEvent(name, data));
+ window.glob.TRILIUM_SAFE_MODE = true;
shownNote.current = savedSearch;
await mount();
@@ -105,6 +122,7 @@ describe("SearchResult", () => {
const result = buildNote({ id: "treeResult", title: "Result" });
vi.spyOn(server, "get").mockResolvedValue({ searchResultNoteIds: [ result.noteId ], highlightedTokens: [], error: null });
vi.spyOn(appContext, "triggerEvent").mockImplementation(async (name, data) => parent.handleEvent(name, data));
+ window.glob.TRILIUM_SAFE_MODE = true;
shownNote.current = savedSearch;
await mount();
@@ -120,6 +138,7 @@ describe("SearchResult", () => {
const savedSearch = buildNote({ id: "badSearch", title: "Bad search", type: "search", "#searchString": "#" });
vi.spyOn(froca, "loadSearchNote").mockResolvedValue({ error: "Invalid saved search" });
const showError = vi.spyOn(toast, "showError").mockImplementation(() => {});
+ window.glob.TRILIUM_SAFE_MODE = true;
shownNote.current = savedSearch;
await mount();
@@ -129,6 +148,76 @@ describe("SearchResult", () => {
});
});
+describe("running a saved search when it is shown", () => {
+ it("runs a saved search shown in the active tab, showing progress until it answers", async () => {
+ const savedSearch = buildNote({ id: "autoSearch", title: "Auto", type: "search", "#searchString": "#book" });
+ const result = buildNote({ id: "autoResult", title: "Auto result" });
+ let answer: (value: unknown) => void = () => {};
+ const get = vi.spyOn(server, "get").mockReturnValue(new Promise((resolve) => { answer = resolve; }) as never);
+ vi.spyOn(appContext, "triggerEvent").mockImplementation(async (name, data) => parent.handleEvent(name, data));
+
+ shownNote.current = savedSearch;
+ await mount();
+
+ expect(get).toHaveBeenCalledWith("search-note/autoSearch");
+ expect(container.querySelector(".no-items .bx-loader-alt")).not.toBeNull();
+ expect(container.querySelector("button")).toBeNull();
+
+ await settle(() => answer({ searchResultNoteIds: [ result.noteId ], highlightedTokens: [], error: null }));
+ expect(container.querySelector(".no-items")).toBeNull();
+ expect(container.textContent).toContain("Auto result");
+ });
+
+ it("waits for a background tab to be shown before running its saved search", async () => {
+ const savedSearch = buildNote({ id: "backgroundSearch", title: "Background", type: "search", "#searchString": "#book" });
+ const loadSearchNote = vi.spyOn(froca, "loadSearchNote").mockResolvedValue(undefined);
+ shownTab.activeMainNtxId = "otherTab";
+
+ shownNote.current = savedSearch;
+ await mount();
+ expect(loadSearchNote).not.toHaveBeenCalled();
+
+ await settle(() => {
+ shownTab.activeMainNtxId = "ntx1";
+ void parent.handleEvent("activeNoteChanged", { ntxId: "ntx1" });
+ });
+ expect(loadSearchNote).toHaveBeenCalledExactlyOnceWith("backgroundSearch");
+ });
+
+ it("leaves the search to \"Search now\" in safe mode and after a failed request", async () => {
+ const safeSearch = buildNote({ id: "safeSearch", title: "Safe", type: "search", "#searchString": "#book" });
+ const loadSearchNote = vi.spyOn(froca, "loadSearchNote").mockRejectedValue(new Error("Network down"));
+ vi.spyOn(toast, "showError").mockImplementation(() => {});
+ window.glob.TRILIUM_SAFE_MODE = true;
+
+ shownNote.current = safeSearch;
+ await mount();
+ expect(loadSearchNote).not.toHaveBeenCalled();
+ expect(container.querySelector(".no-items .bx-file-find")).not.toBeNull();
+
+ render(null, container);
+ window.glob.TRILIUM_SAFE_MODE = false;
+ const failingSearch = buildNote({ id: "failingSearch", title: "Failing", type: "search", "#searchString": "#book" });
+ shownNote.current = failingSearch;
+ await mount();
+
+ expect(loadSearchNote).toHaveBeenCalledExactlyOnceWith("failingSearch");
+ expect(container.querySelector(".no-items .bx-file-find")).not.toBeNull();
+ expect(container.querySelector("button")).not.toBeNull();
+
+ // Showing the note again, after another one, tries once more.
+ await settle(() => {
+ shownNote.current = buildNote({ id: "otherNote", title: "Other" });
+ shownNote.notify();
+ });
+ await settle(() => {
+ shownNote.current = failingSearch;
+ shownNote.notify();
+ });
+ expect(loadSearchNote).toHaveBeenCalledTimes(2);
+ });
+});
+
async function mount() {
await settle(() => {
render(<ParentComponent.Provider value={parent}><SearchResult /></ParentComponent.Provider>, container);
diff --git a/apps/client/src/widgets/search_result.tsx b/apps/client/src/widgets/search_result.tsx
index 70d34a3841..d95923dc02 100644
--- a/apps/client/src/widgets/search_result.tsx
+++ b/apps/client/src/widgets/search_result.tsx
@@ -2,7 +2,7 @@ import "./search_result.css";
import type { HighlightedTokenInfo } from "@triliumnext/commons";
import clsx from "clsx";
-import { useState } from "preact/hooks";
+import { useEffect, useRef, useState } from "preact/hooks";
import type FNote from "../entities/fnote";
import { t } from "../services/i18n";
@@ -11,7 +11,7 @@ import toast from "../services/toast";
import { SearchNoteList, useNoteViewType } from "./collections/NoteList";
import SearchResultsList from "./collections/search/SearchResultsList";
import Button from "./react/Button";
-import { useNoteContext, useTriliumEvent } from "./react/hooks";
+import { useHasTabBeenShown, useNoteContext, useTriliumEvent } from "./react/hooks";
import NoItems from "./react/NoItems";
enum SearchResultState {
@@ -21,10 +21,15 @@ enum SearchResultState {
}
export default function SearchResult() {
- const { note, notePath, ntxId, parentComponent } = useNoteContext();
+ const { note, notePath, ntxId, noteContext, parentComponent } = useNoteContext();
const viewType = useNoteViewType(note);
const [ , setRefreshCount ] = useState(0);
const state = getSearchResultState(note);
+ const { isSearching, runSearch } = useSavedSearchRun(note, state === SearchResultState.NOT_EXECUTED, {
+ noteContext,
+ ntxId,
+ parentComponent
+ });
const highlightedTokens = note?.highlightedTokenInfos ?? note?.highlightedTokens;
// The search note is updated in place, so a re-render picks up the new results.
@@ -32,17 +37,6 @@ export default function SearchResult() {
setRefreshCount((count) => count + 1);
}
- async function executeSearch() {
- if (!note?.noteId) {
- return;
- }
-
- const result = await search.runSearchNote(parentComponent, note.noteId, ntxId);
- if (result?.error) {
- toast.showError(result.error);
- }
- }
-
useTriliumEvent("searchRefreshed", ({ ntxId: eventNtxId }) => {
if (eventNtxId === ntxId) {
refresh();
@@ -56,9 +50,13 @@ export default function SearchResult() {
return (
<div className={clsx("search-result-widget", state === undefined && "hidden-ext")}>
- {state === SearchResultState.NOT_EXECUTED && (
+ {isSearching && (
+ <NoItems icon="bx bx-loader-alt bx-spin" text={t("search_result.searching")} />
+ )}
+
+ {state === SearchResultState.NOT_EXECUTED && !isSearching && (
<NoItems icon="bx bx-file-find" text={t("search_result.search_not_executed")}>
- <Button text={t("search_result.search_now")} onClick={executeSearch} />
+ <Button text={t("search_result.search_now")} onClick={runSearch} />
</NoItems>
)}
@@ -91,6 +89,58 @@ export default function SearchResult() {
);
}
+/**
+ * Runs the shown saved search through `search.runSearchNote()`, once each time it is shown in a visible
+ * tab, and reports while a run is in progress. A failed request therefore waits for `runSearch()` ("Search
+ * now") or the next showing. Safe mode runs nothing on its own, so a hanging search cannot hang every
+ * start-up.
+ */
+function useSavedSearchRun(
+ note: FNote | null | undefined,
+ hasNotRun: boolean,
+ { noteContext, ntxId, parentComponent }: Pick<ReturnType<typeof useNoteContext>, "noteContext" | "ntxId" | "parentComponent">
+) {
+ const hasTabBeenShown = useHasTabBeenShown(noteContext);
+ const [ runningNoteId, setRunningNoteId ] = useState<string>();
+ const autoRunNoteId = useRef<string | undefined>(undefined);
+
+ async function runSearch() {
+ const noteId = note?.noteId;
+ if (!noteId) {
+ return;
+ }
+
+ setRunningNoteId(noteId);
+ try {
+ const result = await search.runSearchNote(parentComponent, noteId, ntxId);
+ if (result?.error) {
+ toast.showError(result.error);
+ }
+ } finally {
+ setRunningNoteId(undefined);
+ }
+ }
+
+ const runsOnShow = hasNotRun && hasTabBeenShown && !glob.TRILIUM_SAFE_MODE
+ && !!note && autoRunNoteId.current !== note.noteId;
+ useEffect(() => {
+ if (autoRunNoteId.current !== note?.noteId) {
+ autoRunNoteId.current = undefined;
+ }
+ }, [ note?.noteId ]);
+ useEffect(() => {
+ if (!runsOnShow || !note) return;
+
+ autoRunNoteId.current = note.noteId;
+ void runSearch();
+ }, [ runsOnShow, note ]); // eslint-disable-line react-hooks/exhaustive-deps
+
+ return {
+ isSearching: hasNotRun && (runsOnShow || runningNoteId === note?.noteId),
+ runSearch
+ };
+}
+
/**
* 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.
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Safe mode.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Safe mode.html
index 87c50d2b78..93098d7e30 100644
--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Safe mode.html
+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Safe mode.html
@@ -7,6 +7,8 @@
<li>Disables <code>customWidget</code> launcher types in <code>app/widgets/containers/launcher.js</code>.</li>
<li>Disables the running of <code>mobileStartup</code> or <code>frontendStartup</code> scripts.</li>
<li>Displays the root note instead of the previously saved session.</li>
+ <li>Does not run a <a class="reference-link" href="#root/_help_m523cpzocqaD">Saved Search</a> when
+ it is opened; press <em>Search now</em> to run it.</li>
<li>Disables the running of <code>backendStartup</code>, <code>hourly</code>, <code>daily</code> scripts
and checks for the hidden subtree.</li>
</ul>
\ No newline at end of file
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Saved Search.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Saved Search.html
index ffb5504042..6ca0505622 100644
--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Saved Search.html
+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Saved Search.html
@@ -6,9 +6,14 @@ style="width:50%;">
<img style="aspect-ratio:812/585;" src="Saved Search_saved-search.gif"
width="812" height="585">
</figure>
-<p>A saved search that has not run yet shows a <em>Search now</em> button,
- which runs that search and lists its results in place. If the query has
- an error, it appears as a notification.</p>
+<p>A saved search runs when you open it, and when you expand it in the note
+ tree. A saved search in a tab that is not shown, such as a background tab
+ restored at startup, runs when you switch to that tab. Its results stay
+ until you run the search again with the <em>Search</em> button of the search
+ parameters. If the query has an error, it appears as a notification.</p>
+<p>In <a class="reference-link" href="#root/_help_64ZTlUPgEPtW">Safe mode</a>,
+ and when the request fails, the search does not run on its own. Press <em>Search now</em> to
+ run it.</p>
<h2>Location</h2>
<p>By default, saved searches are stored in the day note. However, you can
designate a different note to store saved searches by marking it with the <code>#searchHome</code> label.
diff --git a/docs/User Guide/User Guide/Advanced Usage/Safe mode.md b/docs/User Guide/User Guide/Advanced Usage/Safe mode.md
index e35be7ba13..71e580a5b0 100644
--- a/docs/User Guide/User Guide/Advanced Usage/Safe mode.md
+++ b/docs/User Guide/User Guide/Advanced Usage/Safe mode.md
@@ -8,4 +8,5 @@ What it does:
* Disables `customWidget` launcher types in `app/widgets/containers/launcher.js`.
* Disables the running of `mobileStartup` or `frontendStartup` scripts.
* Displays the root note instead of the previously saved session.
+* Does not run a <a class="reference-link" href="../Note%20Types/Saved%20Search.md">Saved Search</a> when it is opened; press _Search now_ to run it.
* Disables the running of `backendStartup`, `hourly`, `daily` scripts and checks for the hidden subtree.
\ No newline at end of file
diff --git a/docs/User Guide/User Guide/Note Types/Saved Search.md b/docs/User Guide/User Guide/Note Types/Saved Search.md
index 97af467f5c..7f4dfd9d83 100644
--- a/docs/User Guide/User Guide/Note Types/Saved Search.md
+++ b/docs/User Guide/User Guide/Note Types/Saved Search.md
@@ -3,7 +3,9 @@ Trilium allows you to save common searches as notes within the note tree. The se
<figure class="image image_resized image-style-align-center" style="width:50%;"><img style="aspect-ratio:812/585;" src="Saved Search_saved-search.gif" width="812" height="585"></figure>
-A saved search that has not run yet shows a _Search now_ button, which runs that search and lists its results in place. If the query has an error, it appears as a notification.
+A saved search runs when you open it, and when you expand it in the note tree. A saved search in a tab that is not shown, such as a background tab restored at startup, runs when you switch to that tab. Its results stay until you run the search again with the _Search_ button of the search parameters. If the query has an error, it appears as a notification.
+
+In <a class="reference-link" href="../Advanced%20Usage/Safe%20mode.md">Safe mode</a>, and when the request fails, the search does not run on its own. Press _Search now_ to run it.
## Location