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
fix(search): open all results in tabs on their first match
Elian Doran22c6aa36ddaa
diff --git a/apps/client/src/widgets/collections/search/SearchResultCard.tsx b/apps/client/src/widgets/collections/search/SearchResultCard.tsxindex 77c3584ba2..3c128336b1 100644--- a/apps/client/src/widgets/collections/search/SearchResultCard.tsx+++ b/apps/client/src/widgets/collections/search/SearchResultCard.tsx@@ -28,9 +28,7 @@ export default function SearchResultCard({ noteId, details, loading, highlightedconst icon = note?.getIcon() ?? details?.icon ?? "bx bx-note";const breadcrumb = getBreadcrumbTitle(details?.notePathTitle);- // The words as the note spells them, so the find bar matches "ktorý" for the query "ktory".- const searchTerms = details?.matchedTerms?.length ? details.matchedTerms : toPlainSearchTerms(highlightedTokens);- const viewScope: ViewScope = { searchTerms };+ const viewScope: ViewScope = { searchTerms: searchTermsFor(details, highlightedTokens) };const href = calculateHash({ notePath: noteId, viewScope });return (@@ -76,6 +74,17 @@ export function getBreadcrumbTitle(notePathTitle: string | undefined): string {return parts.join(" › ");}+/**+ * The terms the find bar looks for in a result opened from a search: the words as the note spells+ * them, so it matches "ktorý" for the query "ktory", or the query's plain tokens without details.+ */+export function searchTermsFor(+ details: Pick<SearchResultDetails, "matchedTerms"> | undefined,+ highlightedTokens: (string | HighlightedTokenInfo)[] | null | undefined+): string[] {+ return details?.matchedTerms?.length ? details.matchedTerms : toPlainSearchTerms(highlightedTokens);+}+/** Plain tokens only (regex tokens can't round-trip as literal search terms). */export function toPlainSearchTerms(highlightedTokens: (string | HighlightedTokenInfo)[] | null | undefined): string[] {if (!highlightedTokens?.length) return [];diff --git a/apps/client/src/widgets/collections/search/SearchResultsList.spec.tsx b/apps/client/src/widgets/collections/search/SearchResultsList.spec.tsxindex 6349bcb5b6..06e0b9b31f 100644--- a/apps/client/src/widgets/collections/search/SearchResultsList.spec.tsx+++ b/apps/client/src/widgets/collections/search/SearchResultsList.spec.tsx@@ -3,7 +3,7 @@* - {@link SearchResultCard}: renders title/icon/breadcrumb/snippet/badges from server details,* the loading skeleton, the "snippet unavailable" fallback, and the bare-noteId link href.* - {@link SearchResultsToolbar}: the always-visible result count and the page-size selector.- * - the pure {@link getBreadcrumbTitle} / {@link toPlainSearchTerms} helpers.+ * - the pure {@link getBreadcrumbTitle} / {@link searchTermsFor} / {@link toPlainSearchTerms} helpers.** The lazy page fetch + stale-response guard live in `useSearchResultDetails.spec.tsx`; this file* exercises the rendering that consumes those details.@@ -24,7 +24,7 @@ import { calculateHash } from "../../../services/link";import server from "../../../services/server";import { buildNote, buildNotes } from "../../../test/easy-froca";import { ParentComponent } from "../../react/react_utils";-import SearchResultCard, { getBreadcrumbTitle, toPlainSearchTerms } from "./SearchResultCard";+import SearchResultCard, { getBreadcrumbTitle, searchTermsFor, toPlainSearchTerms } from "./SearchResultCard";import SearchResultsList, { SearchResultsToolbar } from "./SearchResultsList";function makeDetails(overrides: Partial<SearchResultDetails> = {}): SearchResultDetails {@@ -223,3 +223,12 @@ describe("toPlainSearchTerms", () => {expect(toPlainSearchTerms([])).toEqual([]);});});++describe("searchTermsFor", () => {+ it("prefers the terms the note matched and falls back to the query's plain tokens", () => {+ const tokens = [ "ktory", { token: "k.*", type: "regex" as const } ];+ expect(searchTermsFor({ matchedTerms: [ "ktorý" ] }, tokens)).toEqual([ "ktorý" ]);+ expect(searchTermsFor({ matchedTerms: [] }, tokens)).toEqual([ "ktory" ]);+ expect(searchTermsFor(undefined, tokens)).toEqual([ "ktory" ]);+ });+});diff --git a/apps/client/src/widgets/note_bars/CollectionProperties.spec.tsx b/apps/client/src/widgets/note_bars/CollectionProperties.spec.tsxindex 3e42dfa116..fea452cee6 100644--- a/apps/client/src/widgets/note_bars/CollectionProperties.spec.tsx+++ b/apps/client/src/widgets/note_bars/CollectionProperties.spec.tsx@@ -1,7 +1,11 @@-import { describe, expect, it } from "vitest";+import { act } from "preact/test-utils";+import { afterEach, describe, expect, it, vi } from "vitest";+import appContext from "../../components/app_context";import Component from "../../components/component";import NoteContext from "../../components/note_context";+import type TabManager from "../../components/tab_manager";+import server from "../../services/server";import { buildNote } from "../../test/easy-froca";import { renderInto } from "../../test/render";import { NoteContextContext, ParentComponent } from "../react/react_utils";@@ -29,4 +33,45 @@ describe("CollectionProperties", () => {await parent.handleEvent("toggleRibbonTabBookProperties", { ntxId: "ntx-split-2" });expect(document.activeElement).toBe(switcher);});++ it("opens every result with the terms the find bar looks for, as a single click does", async () => {+ const note = buildNote({+ id: "search1", title: "Search", type: "search",+ children: [ { id: "result1", title: "Kôň" }, { id: "result2", title: "Horse" } ]+ });+ note.highlightedTokens = [ "kon" ];+ vi.spyOn(server, "post").mockResolvedValue({+ results: [ { noteId: "result1", matchedTerms: [ "kôň" ] } ]+ });+ const openTab = vi.fn().mockResolvedValue(undefined);+ appContext.tabManager = { openTabWithNoteWithHoisting: openTab } as unknown as TabManager;++ const parent = new Component();+ const container = renderInto(+ <ParentComponent.Provider value={parent}>+ <NoteContextContext.Provider value={new NoteContext("ntx1")}>+ <CollectionProperties note={note} />+ </NoteContextContext.Provider>+ </ParentComponent.Provider>+ );+ const button = container.querySelector<HTMLElement>(".right-container .icon-action");+ expect(button).toBeTruthy();+ await act(async () => {+ button?.click();+ await new Promise((resolve) => setTimeout(resolve, 0));+ });++ expect(server.post).toHaveBeenCalledWith("search-note/search1/result-details", {+ noteIds: [ "result1", "result2" ]+ });+ // A result without matched terms falls back to the query's tokens.+ expect(openTab.mock.calls).toEqual([+ [ "result1", { activate: false, viewScope: { searchTerms: [ "kôň" ] } } ],+ [ "result2", { activate: true, viewScope: { searchTerms: [ "kon" ] } } ]+ ]);+ });+});++afterEach(() => {+ vi.restoreAllMocks();});diff --git a/apps/client/src/widgets/note_bars/CollectionProperties.tsx b/apps/client/src/widgets/note_bars/CollectionProperties.tsxindex 33d72022de..aa0d65755b 100644--- a/apps/client/src/widgets/note_bars/CollectionProperties.tsx+++ b/apps/client/src/widgets/note_bars/CollectionProperties.tsx@@ -1,5 +1,6 @@import "./CollectionProperties.css";+import { SearchResultDetails, SearchResultDetailsResponse } from "@triliumnext/commons";import { t } from "i18next";import { ComponentChildren } from "preact";import { useRef, useState } from "preact/hooks";@@ -7,8 +8,11 @@ import { useRef, useState } from "preact/hooks";import appContext from "../../components/app_context";import FNote from "../../entities/fnote";import dialogService from "../../services/dialog";+import server from "../../services/server";import toast from "../../services/toast";+import { getErrorMessage } from "../../services/utils";import { ViewTypeOptions } from "../collections/interface";+import { searchTermsFor } from "../collections/search/SearchResultCard";import ActionButton from "../react/ActionButton";import Dropdown from "../react/Dropdown";import { FormDropdownDivider, FormListItem } from "../react/FormList";@@ -99,11 +103,15 @@ function OpenAllButton({ note, isOpening, setIsOpening }: {setIsOpening(true);try {+ const detailsByNoteId = await getResultDetails(note, noteIds);+ const highlightedTokens = note.highlightedTokenInfos ?? note.highlightedTokens;for (let i = 0; i < noteIds.length; i++) {const noteId = noteIds[i];const isLast = i === noteIds.length - 1;+ const searchTerms = searchTermsFor(detailsByNoteId.get(noteId), highlightedTokens);await appContext.tabManager.openTabWithNoteWithHoisting(noteId, {- activate: isLast+ activate: isLast,+ viewScope: searchTerms?.length ? { searchTerms } : null});}} finally {@@ -121,6 +129,22 @@ function OpenAllButton({ note, isOpening, setIsOpening }: {);}+/**+ * The details of the results being opened, for `searchTermsFor()` to read their matched terms.+ * Empty if the request fails, so the tabs still open and fall back to the query's tokens.+ */+async function getResultDetails(searchNote: FNote, noteIds: string[]) {+ try {+ const { results } = await server.post<SearchResultDetailsResponse>(+ `search-note/${searchNote.noteId}/result-details`, { noteIds }+ );+ return new Map(results.map((details) => [ details.noteId, details ]));+ } catch (e) {+ logError(`Could not load the matched terms of search note '${searchNote.noteId}': ${getErrorMessage(e)}`);+ return new Map<string, SearchResultDetails>();+ }+}+export function useViewType(note: FNote | null | undefined) {const [ viewType, setViewType ] = useNoteLabel(note, "viewType");const defaultViewType = (note?.type === "search" ? "list" : "grid");diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Navigation/Search.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Navigation/Search.htmlindex 437a785da4..98a59a7c3c 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Navigation/Search.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Navigation/Search.html@@ -243,6 +243,10 @@To have the find bar look for a whole phrase instead, put the phrase inquotes in the search, e.g. <code>"The Lord of the Rings"</code>. In read-onlynotes, the other words of the search are highlighted as well.</li>+ <li><strong>Open all results in new tabs</strong> (the <span class="bx bx-window-open"></span> button+ above the results) opens every result in a tab of its own, up to 50. Each+ tab opens on its first match with the find bar pre-filled, as when clicking+ a result.</li><li>If a match is inside a <strong>collapsed section</strong> (for example afolded heading), that section is expanded automatically so the match isvisible.</li>diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/UI Elements/Note menu.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/UI Elements/Note menu.htmlindex d056f01ba7..5949ca944a 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/UI Elements/Note menu.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/UI Elements/Note menu.html@@ -158,23 +158,31 @@<p>The <span class="tn-icon bx bx-wrench"></span><em>Advanced</em> submenugroups the actions that are needed less often:</p><ul>- <li><span class="tn-icon bx bx-file-find"></span><em>Open note externally</em> (desktop- application only) saves the note to a temporary file and opens it in the- application that the operating system associates with it. Trilium watches- the file, and offers to upload the modified version back into the note.- It is unavailable on <a class="reference-link" href="#root/_help_GTwFsgaA0lCt">Collections</a> and <a- class="reference-link" href="#root/_help_m523cpzocqaD">Saved Search</a> notes.</li>- <li><span class="tn-icon bx bx-customize"></span><em>Open note custom</em> (desktop- application only, Windows and Linux) works like <em>Open note externally</em>,- but lets you pick the application to open the file with.</li>- <li><span class="tn-icon bx bx-code"></span><em>Note source</em> shows the <a- class="reference-link" href="#root/_help_4FahAwuGTAwC">Note source</a>,- the content of the note exactly as it is stored.</li>- <li><span class="tn-icon bx bxl-markdown"></span><em>Convert to Markdown Note</em> (on- text notes) and <em>Convert to Text Note</em> (on Markdown notes) switch- the note between rich text and Markdown. After a confirmation, Trilium- saves a revision and converts the content; the revision allows going back- if some formatting was lost. See <a class="reference-link" href="#root/_help_jludwdW7N4hg">Converting between note types</a>.</li>+ <li>+ <p><span class="tn-icon bx bx-file-find"></span><em>Open note externally</em> (desktop+ application only) saves the note to a temporary file and opens it in the+ application that the operating system associates with it. Trilium watches+ the file, and offers to upload the modified version back into the note.+ It is unavailable on <a class="reference-link" href="#root/_help_GTwFsgaA0lCt">Collections</a> and <a+ class="reference-link" href="#root/_help_m523cpzocqaD">Saved Search</a> notes.</p>+ </li>+ <li>+ <p><span class="tn-icon bx bx-customize"></span><em>Open note custom</em> (desktop+ application only, Windows and Linux) works like <em>Open note externally</em>,+ but lets you pick the application to open the file with.</p>+ </li>+ <li>+ <p><span class="tn-icon bx bx-code"></span><em>Note source</em> shows the <a+ class="reference-link" href="#root/_help_4FahAwuGTAwC">Note source</a>,+ the content of the note exactly as it is stored.</p>+ </li>+ <li>+ <p><span class="tn-icon bx bxl-markdown"></span><em>Convert to Markdown Note</em> (on+ text notes) and <em>Convert to Text Note</em> (on Markdown notes) switch+ the note between rich text and Markdown. After a confirmation, Trilium+ saves a revision and converts the content; the revision allows going back+ if some formatting was lost. See <a class="reference-link" href="#root/_help_jludwdW7N4hg">Converting between note types</a>.</p>+ </li><li><p><span class="tn-icon bx bx-collapse-alt"></span><em>Compress images</em> opensa dialog that reduces the size of the images in the note. It lists the@@ -189,13 +197,17 @@<p>Compressing cannot be undone. Images can also be compressed automaticallyon upload, see <a class="reference-link" href="#root/_help_mT0HEkOsz6i1">Images</a>.</p></li>- <li><span class="tn-icon bx bx-text"></span><em>View OCR text</em> (on image- and file notes) shows the text extracted from the note via <a class="reference-link"- href="#root/_help_TiQbQDgP8L5t">Text Extraction (OCR)</a>. If the note- has not been processed yet, the dialog offers to <em>Process OCR</em>.</li>- <li><span class="tn-icon bx bx-world"></span><em>Open note on server</em> (desktop- application only, listed when <a class="reference-link" href="#root/_help_cbkrhQjrkKrh">Synchronization</a> is- configured) opens the same note on the sync server, in the web browser.</li>+ <li>+ <p><span class="tn-icon bx bx-text"></span><em>View OCR text</em> (on image+ and file notes) shows the text extracted from the note via <a class="reference-link"+ href="#root/_help_TiQbQDgP8L5t">Text Extraction (OCR)</a>. If the note+ has not been processed yet, the dialog offers to <em>Process OCR</em>.</p>+ </li>+ <li>+ <p><span class="tn-icon bx bx-world"></span><em>Open note on server</em> (desktop+ application only, listed when <a class="reference-link" href="#root/_help_cbkrhQjrkKrh">Synchronization</a> is+ configured) opens the same note on the sync server, in the web browser.</p>+ </li></ul><h2>Deleting the note</h2><p><span class="tn-icon bx bx-trash"></span><em>Delete note</em> opens thediff --git a/docs/User Guide/User Guide/Basic Concepts and Features/Navigation/Search.md b/docs/User Guide/User Guide/Basic Concepts and Features/Navigation/Search.mdindex 634eb6b117..7768b75409 100644--- a/docs/User Guide/User Guide/Basic Concepts and Features/Navigation/Search.md+++ b/docs/User Guide/User Guide/Basic Concepts and Features/Navigation/Search.md@@ -131,6 +131,7 @@ In addition:* The **total number of results** is always shown, so you can immediately tell how broad a query is.* A **page-size selector** lets you choose how many results to display per page. Your choice is remembered and synced across your devices (stored in the `searchResultsPageSize` option), so you do not have to reset it on every device.* **Clicking a result** opens the note and jumps straight to the first match. The in-note find bar opens pre-filled with the first word of your search, so you can step through its matches with the find controls. To have the find bar look for a whole phrase instead, put the phrase in quotes in the search, e.g. `"The Lord of the Rings"`. In read-only notes, the other words of the search are highlighted as well.+* **Open all results in new tabs** (the button above the results) opens every result in a tab of its own, up to 50. Each tab opens on its first match with the find bar pre-filled, as when clicking a result.* If a match is inside a **collapsed section** (for example a folded heading), that section is expanded automatically so the match is visible.## Simple Note Search Examples