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
feat(client): snippet-card search results view
perfectra1n7af9839c66e9
diff --git a/apps/client/src/services/content_renderer.ts b/apps/client/src/services/content_renderer.tsindex 71ee7a210e..0922da9a83 100644--- a/apps/client/src/services/content_renderer.ts+++ b/apps/client/src/services/content_renderer.ts@@ -576,7 +576,7 @@ async function renderCollection(note: FNote, $renderedContent: JQuery<HTMLElemennotePath: note.getBestNotePathString(),ntxId: undefined,media: "screen",- highlightedTokens: note.highlightedTokens,+ highlightedTokens: note.highlightedTokenInfos ?? note.highlightedTokens,// Search results get text-representation (highlighted snippets); books don't.showTextRepresentation: note.type === "search"}), container);diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 67f90bfe24..dd3c29e37d 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -2328,7 +2328,11 @@"search_result": {"no_notes_found": "No notes have been found for given search parameters.","search_not_executed": "Search has not been executed yet.",- "search_now": "Search now"+ "search_now": "Search now",+ "result_count_one": "{{count}} result",+ "result_count_other": "{{count}} results",+ "page_size": "Per page",+ "snippet_unavailable": "No preview available."},"sql_result": {"not_executed": "The query has not been executed yet.",diff --git a/apps/client/src/widgets/collections/search/SearchResultCard.tsx b/apps/client/src/widgets/collections/search/SearchResultCard.tsxnew file mode 100644index 0000000000..32a104e719--- /dev/null+++ b/apps/client/src/widgets/collections/search/SearchResultCard.tsx@@ -0,0 +1,121 @@+import type { HighlightedTokenInfo, SearchResultDetails } from "@triliumnext/commons";+import { useEffect, useRef } from "preact/hooks";++import { t } from "../../../services/i18n";+import { calculateHash, type ViewScope } from "../../../services/link";+import { Badge } from "../../react/Badge";+import { useImperativeSearchHighlighlighting, useNote, useNoteTitle } from "../../react/hooks";+import Icon from "../../react/Icon";+import RawHtml, { RawHtmlBlock } from "../../react/RawHtml";++interface SearchResultCardProps {+ noteId: string;+ details: SearchResultDetails | undefined;+ loading: boolean;+ highlightedTokens: (string | HighlightedTokenInfo)[] | null | undefined;+}++/**+ * A single Google-style snippet card. The title/icon render immediately from froca, while the+ * server-built snippet and attribute badges fill in from {@link SearchResultDetails} (a snippet+ * skeleton shows while the page's details are still loading).+ */+export default function SearchResultCard({ noteId, details, loading, highlightedTokens }: SearchResultCardProps) {+ const note = useNote(noteId);+ // Search-note children are addressed by bare noteId (a non-search path), matching how the legacy+ // list/grid cards compute their href for a search parent.+ const liveTitle = useNoteTitle(noteId, undefined);+ const title = liveTitle ?? details?.noteTitle ?? note?.title ?? "";+ const icon = note?.getIcon() ?? details?.icon ?? "bx bx-note";+ const breadcrumb = getBreadcrumbTitle(details?.notePathTitle);++ const searchTerms = toPlainSearchTerms(highlightedTokens);+ // Task 8 adds `searchTerms` to ViewScope and teaches calculateHash to encode it. Until then we+ // attach it through a locally-widened view scope so the card link already carries the plain+ // terms; calculateHash ignores unknown viewScope fields today, so this is harmless and+ // forward-compatible.+ const viewScope: SearchResultViewScope = { searchTerms };+ const href = calculateHash({ notePath: noteId, viewScope });++ // Set the title text imperatively so mark.js (which mutates the DOM to inject `.ck-find-result`+ // spans) doesn't fight Preact's reconciliation of a controlled text child — the same reason+ // NoteLink renders its title imperatively.+ const titleRef = useRef<HTMLSpanElement>(null);+ const highlightTitle = useImperativeSearchHighlighlighting(highlightedTokens);+ useEffect(() => {+ if (titleRef.current) {+ titleRef.current.textContent = title;+ highlightTitle(titleRef.current);+ }+ // highlightTitle is a fresh closure each render; keying on the token list (as the legacy+ // cards do) avoids re-running on every render.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [ title, highlightedTokens ]);++ return (+ <a className="search-result-card" href={href}>+ <div className="search-result-card-header">+ <Icon className="search-result-card-icon" icon={icon} />+ <span className="search-result-card-title" ref={titleRef} />+ {breadcrumb && <span className="search-result-card-path">{breadcrumb}</span>}+ </div>+ <SearchResultSnippet details={details} loading={loading} />+ <SearchResultBadges snippet={details?.highlightedAttributeSnippet} />+ </a>+ );+}++/** Task 8 promotes `searchTerms` onto {@link ViewScope}; widened locally until then. */+type SearchResultViewScope = ViewScope & { searchTerms?: string[] };++function SearchResultSnippet({ details, loading }: { details: SearchResultDetails | undefined; loading: boolean }) {+ if (!details) {+ // Details for this page haven't arrived yet: show a skeleton, or nothing once settled.+ return loading ? <div className="search-result-card-snippet skeleton" /> : null;+ }++ if (!details.contentSnippet) {+ // Details exist but there is no snippet to show (e.g. protected notes without a session).+ return <div className="search-result-card-snippet unavailable">{t("search_result.snippet_unavailable")}</div>;+ }++ // Server snippet is pre-escaped with only <b>/<br> injected (same trust level as quick search).+ return <RawHtmlBlock className="search-result-card-snippet" html={details.highlightedContentSnippet ?? ""} />;+}++function SearchResultBadges({ snippet }: { snippet: string | undefined }) {+ if (!snippet) return null;++ const lines = snippet.split(/<br\s*\/?>/i).map((line) => line.trim()).filter(Boolean);+ if (lines.length === 0) return null;++ return (+ <div className="search-result-card-badges">+ {lines.map((line, index) => (+ <Badge key={index} outline text={<RawHtml html={line} />} />+ ))}+ </div>+ );+}++/** The breadcrumb shows the ancestor path only, i.e. the note-path title minus the note's own title. */+export function getBreadcrumbTitle(notePathTitle: string | undefined): string {+ if (!notePathTitle) return "";+ const parts = notePathTitle.split(" › ");+ parts.pop();+ return parts.join(" › ");+}++/** 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 [];+ const terms: string[] = [];+ for (const token of highlightedTokens) {+ if (typeof token === "string") {+ terms.push(token);+ } else if (token.type === "plain") {+ terms.push(token.token);+ }+ }+ return terms;+}diff --git a/apps/client/src/widgets/collections/search/SearchResultsList.css b/apps/client/src/widgets/collections/search/SearchResultsList.cssnew file mode 100644index 0000000000..0e9ed8dae5--- /dev/null+++ b/apps/client/src/widgets/collections/search/SearchResultsList.css@@ -0,0 +1,143 @@+.search-results-list {+ display: flex;+ flex-direction: column;+ min-width: 0;++ .search-results-list-toolbar {+ display: flex;+ align-items: center;+ gap: 12px;+ white-space: nowrap;+ }++ .search-results-list-count {+ opacity: 0.7;+ font-size: 0.9em;+ }++ .search-results-list-page-size {+ display: flex;+ align-items: center;+ gap: 6px;+ margin: 0;+ }++ .search-results-list-page-size-label {+ opacity: 0.7;+ font-size: 0.9em;+ }++ .search-results-list-page-size .form-select {+ width: auto;+ }++ .search-results-list-cards {+ display: flex;+ flex-direction: column;+ gap: 8px;+ padding: 8px 0;+ margin-inline: var(--content-margin-inline);+ min-width: 0;+ }++ .search-result-card {+ display: block;+ min-width: 0;+ padding: 10px 14px;+ border: 1px solid var(--main-border-color);+ border-radius: 8px;+ background: var(--accented-background-color);+ color: inherit;+ text-decoration: none;+ transition: background 0.15s ease, border-color 0.15s ease;+ }++ .search-result-card:hover {+ background: var(--hover-item-background-color);+ border-color: var(--main-border-color);+ text-decoration: none;+ }++ .search-result-card-header {+ display: flex;+ align-items: baseline;+ flex-wrap: wrap;+ gap: 4px 8px;+ min-width: 0;+ }++ .search-result-card-icon {+ flex: 0 0 auto;+ align-self: center;+ }++ .search-result-card-title {+ flex: 1 1 auto;+ min-width: 0;+ font-weight: 600;+ overflow-wrap: anywhere;+ }++ .search-result-card-path {+ flex: 0 1 auto;+ min-width: 0;+ margin-inline-start: auto;+ opacity: 0.6;+ font-size: 0.85em;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ }++ .search-result-card-snippet {+ margin-top: 4px;+ line-height: 1.4;+ color: var(--muted-text-color);+ overflow-wrap: anywhere;+ }++ .search-result-card-snippet.unavailable {+ font-style: italic;+ opacity: 0.7;+ }++ .search-result-card-snippet.skeleton {+ height: 2.6em;+ border-radius: 4px;+ background: linear-gradient(+ 90deg,+ var(--main-border-color) 25%,+ var(--accented-background-color) 37%,+ var(--main-border-color) 63%+ );+ background-size: 400% 100%;+ animation: search-result-skeleton 1.4s ease infinite;+ }++ .search-result-card-badges {+ display: flex;+ flex-wrap: wrap;+ gap: 4px;+ margin-top: 6px;+ }++ /* Style the server-injected <b> highlights (snippet + attribute badges) and the client-side+ mark.js .ck-find-result spans (title) identically. */+ .search-result-card-title .ck-find-result,+ .search-result-card-snippet b,+ .search-result-card-badges b {+ background: var(--note-list-view-search-result-highlight-background);+ color: var(--note-list-view-search-result-highlight-color);+ font-weight: 600;+ text-decoration: underline;+ }+}++@keyframes search-result-skeleton {+ from {+ background-position: 100% 0;+ }+ to {+ background-position: 0 0;+ }+}diff --git a/apps/client/src/widgets/collections/search/SearchResultsList.spec.tsx b/apps/client/src/widgets/collections/search/SearchResultsList.spec.tsxnew file mode 100644index 0000000000..2201524233--- /dev/null+++ b/apps/client/src/widgets/collections/search/SearchResultsList.spec.tsx@@ -0,0 +1,158 @@+/**+ * Tests for the snippet-card search results view. Split across its composable pieces:+ * - {@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 lazy page fetch + stale-response guard live in `useSearchResultDetails.spec.tsx`; this file+ * exercises the rendering that consumes those details.+ */+import type { SearchResultDetails } from "@triliumnext/commons";+import { render } from "preact";+import { act } from "preact/test-utils";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++// i18next isn't initialized under test (t() would echo the key), so stub it to surface interpolated+// values — mirroring RenderErrorCard.spec — so the result-count assertion can see the count.+vi.mock("../../../services/i18n", () => ({+ t: (key: string, opts?: Record<string, unknown>) => (opts && "count" in opts ? `${key}:${opts.count}` : key)+}));++import Component from "../../../components/component";+import { buildNote } from "../../../test/easy-froca";+import { ParentComponent } from "../../react/react_utils";+import SearchResultCard, { getBreadcrumbTitle, toPlainSearchTerms } from "./SearchResultCard";+import { SearchResultsToolbar } from "./SearchResultsList";++function makeDetails(overrides: Partial<SearchResultDetails> = {}): SearchResultDetails {+ return {+ noteId: "note1",+ notePath: "note1",+ noteTitle: "Meeting notes",+ notePathTitle: "Work › 2026 › Meeting notes",+ contentSnippet: "the calendar sync failed twice",+ highlightedContentSnippet: "the calendar <b>sync</b> failed twice",+ attributeSnippet: "#status=open\n#priority=high",+ highlightedAttributeSnippet: "#status=<b>open</b><br>#priority=high",+ icon: "bx bx-calendar",+ ...overrides+ };+}++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();+});++async function mount(element: preact.VNode) {+ await act(async () => {+ render(<ParentComponent.Provider value={parent}>{element}</ParentComponent.Provider>, container);+ await Promise.resolve();+ });+}++describe("SearchResultCard", () => {+ it("renders the title, breadcrumb, snippet HTML, badges, and a bare-noteId link", async () => {+ const note = buildNote({ id: "note1", title: "Meeting notes", type: "text" });+ await mount(+ <SearchResultCard noteId={note.noteId} details={makeDetails()} loading={false} highlightedTokens={["sync"]} />+ );++ const link = container.querySelector("a.search-result-card");+ expect(link?.getAttribute("href")).toBe(`#${note.noteId}`);+ expect(container.querySelector(".search-result-card-title")?.textContent).toBe("Meeting notes");+ // Breadcrumb is the note-path title minus the note's own (last) segment.+ expect(container.querySelector(".search-result-card-path")?.textContent).toBe("Work › 2026");++ const snippet = container.querySelector(".search-result-card-snippet");+ expect(snippet?.innerHTML).toContain("<b>sync</b>");+ expect(snippet?.classList.contains("skeleton")).toBe(false);++ // Attribute snippet is split on <br> into one outline badge per line.+ const badges = container.querySelectorAll(".search-result-card-badges .ext-badge");+ expect(badges.length).toBe(2);+ expect(badges[0].classList.contains("outline")).toBe(true);+ expect(badges[0].textContent).toContain("status=open");+ expect(badges[0].querySelector("b")?.textContent).toBe("open");+ });++ it("shows a snippet skeleton while the page's details are still loading", async () => {+ const note = buildNote({ id: "note1", title: "Meeting notes", type: "text" });+ await mount(+ <SearchResultCard noteId={note.noteId} details={undefined} loading={true} highlightedTokens={null} />+ );++ expect(container.querySelector(".search-result-card-snippet.skeleton")).not.toBeNull();+ // Title still renders immediately (from froca) even before details arrive.+ expect(container.querySelector(".search-result-card-title")?.textContent).toBe("Meeting notes");+ });++ it("shows the snippet-unavailable line when details exist but there is no content snippet", async () => {+ const note = buildNote({ id: "note1", title: "Protected", type: "text" });+ await mount(+ <SearchResultCard+ noteId={note.noteId}+ details={makeDetails({ contentSnippet: "", highlightedContentSnippet: "", attributeSnippet: "", highlightedAttributeSnippet: "" })}+ loading={false}+ highlightedTokens={null}+ />+ );++ const snippet = container.querySelector(".search-result-card-snippet");+ expect(snippet?.classList.contains("unavailable")).toBe(true);+ expect(snippet?.textContent).toBe("search_result.snippet_unavailable");+ expect(container.querySelector(".search-result-card-snippet.skeleton")).toBeNull();+ expect(container.querySelector(".search-result-card-badges")).toBeNull();+ });+});++describe("SearchResultsToolbar", () => {+ it("always renders the result count, including for a single page", async () => {+ await mount(<SearchResultsToolbar count={1} pageSize={20} setPageSize={() => {}} />);+ expect(container.querySelector(".search-results-list-count")?.textContent).toBe("search_result.result_count:1");+ });++ it("renders the current page size and reports the parsed value on change", async () => {+ const setPageSize = vi.fn();+ await mount(<SearchResultsToolbar count={42} pageSize={20} setPageSize={setPageSize} />);++ const select = container.querySelector<HTMLSelectElement>(".search-results-list-page-size select");+ expect(select?.value).toBe("20");++ if (!select) throw new Error("select not rendered");+ await act(async () => {+ select.value = "50";+ select.dispatchEvent(new Event("change", { bubbles: true }));+ });+ expect(setPageSize).toHaveBeenCalledWith(50);+ });+});++describe("getBreadcrumbTitle", () => {+ it("drops the note's own segment and keeps the ancestor path", () => {+ expect(getBreadcrumbTitle("Work › 2026 › Meeting notes")).toBe("Work › 2026");+ expect(getBreadcrumbTitle("Austria")).toBe(""); // single segment: no ancestors+ expect(getBreadcrumbTitle(undefined)).toBe("");+ });+});++describe("toPlainSearchTerms", () => {+ it("keeps plain tokens (and legacy strings) but drops regex tokens", () => {+ expect(+ toPlainSearchTerms(["sync", { token: "backup", type: "plain" }, { token: "re?ge", type: "regex" }])+ ).toEqual(["sync", "backup"]);+ expect(toPlainSearchTerms(null)).toEqual([]);+ expect(toPlainSearchTerms([])).toEqual([]);+ });+});diff --git a/apps/client/src/widgets/collections/search/SearchResultsList.tsx b/apps/client/src/widgets/collections/search/SearchResultsList.tsxnew file mode 100644index 0000000000..3f4eda0477--- /dev/null+++ b/apps/client/src/widgets/collections/search/SearchResultsList.tsx@@ -0,0 +1,103 @@+import "./SearchResultsList.css";++import type { HighlightedTokenInfo } from "@triliumnext/commons";+import { useMemo } from "preact/hooks";++import type FNote from "../../../entities/fnote";+import { t } from "../../../services/i18n";+import CollectionProperties from "../../note_bars/CollectionProperties";+import FormSelect from "../../react/FormSelect";+import { useTriliumOptionInt } from "../../react/hooks";+import { ViewModeMedia } from "../interface";+import { useNoteIds } from "../NoteList";+import { Pager, usePagination } from "../Pagination";+import SearchResultCard from "./SearchResultCard";+import { useSearchResultDetails } from "./useSearchResultDetails";++interface SearchResultsListProps {+ note: FNote | null | undefined;+ notePath: string | null | undefined;+ ntxId: string | null | undefined;+ highlightedTokens?: (string | HighlightedTokenInfo)[] | null;+ media: ViewModeMedia;+}++/**+ * Google-style snippet-card view for the results of a search note (issues #5667, #6225). Used only+ * for the "list" view type; other view types keep going through the legacy `SearchNoteList` path.+ *+ * Composition mirrors the legacy list view's collection bar (`CollectionProperties` with a centered+ * pager) but adds an always-visible result count and a page-size selector, then renders one+ * {@link SearchResultCard} per note on the current page plus a bottom pager. The per-note snippet+ * details are fetched lazily, one page at a time, via {@link useSearchResultDetails}.+ */+export default function SearchResultsList({ note, ...rest }: SearchResultsListProps) {+ // The results view only mounts for an executed search note; guard here so the inner component+ // (and the collection hooks it drives) can rely on a non-null note.+ if (!note) return null;+ return <SearchResultsListInner note={note} {...rest} />;+}++function SearchResultsListInner({ note, ntxId, highlightedTokens }: SearchResultsListProps & { note: FNote }) {+ const [ pageSize, setPageSize ] = useTriliumOptionInt("searchResultsPageSize");+ const noteIds = useNoteIds(note, "list", ntxId);+ const pagination = usePagination(note, noteIds, pageSize);+ const pageNoteIds = useMemo(() => {+ const start = (pagination.page - 1) * pagination.pageSize;+ return noteIds.slice(start, start + pagination.pageSize);+ }, [ noteIds, pagination.page, pagination.pageSize ]);+ const { detailsByNoteId, loading } = useSearchResultDetails(note, pageNoteIds, ntxId);++ return (+ <div className="search-results-list">+ <CollectionProperties+ note={note}+ centerChildren={<Pager className="search-results-list-top-pager" {...pagination} />}+ rightChildren={+ <SearchResultsToolbar+ count={pagination.totalNotes}+ pageSize={pagination.pageSize}+ setPageSize={setPageSize}+ />+ }+ />++ <div className="search-results-list-cards">+ {pageNoteIds.map((noteId) => (+ <SearchResultCard+ key={noteId}+ noteId={noteId}+ details={detailsByNoteId.get(noteId)}+ loading={loading}+ highlightedTokens={highlightedTokens}+ />+ ))}+ </div>++ <Pager className="search-results-list-bottom-pager" {...pagination} />+ </div>+ );+}++const PAGE_SIZE_OPTIONS = [ 10, 20, 50, 100 ].map((value) => ({ value: String(value) }));++export function SearchResultsToolbar({ count, pageSize, setPageSize }: {+ count: number;+ pageSize: number;+ setPageSize: (value: number) => void | Promise<void>;+}) {+ return (+ <div className="search-results-list-toolbar">+ <span className="search-results-list-count">{t("search_result.result_count", { count })}</span>+ <label className="search-results-list-page-size">+ <span className="search-results-list-page-size-label">{t("search_result.page_size")}</span>+ <FormSelect+ values={PAGE_SIZE_OPTIONS}+ keyProperty="value"+ currentValue={String(pageSize)}+ onChange={(value) => void setPageSize(parseInt(value, 10))}+ />+ </label>+ </div>+ );+}diff --git a/apps/client/src/widgets/collections/search/useSearchResultDetails.spec.tsx b/apps/client/src/widgets/collections/search/useSearchResultDetails.spec.tsxnew file mode 100644index 0000000000..06fa837399--- /dev/null+++ b/apps/client/src/widgets/collections/search/useSearchResultDetails.spec.tsx@@ -0,0 +1,143 @@+/**+ * Tests for {@link useSearchResultDetails}: the per-page snippet fetch backing the snippet-card+ * search results view. Covers the happy path (details indexed by noteId, `loading` transitions),+ * the stale-response guard (an older in-flight response must not clobber a newer one), and the+ * re-execution refetch triggered by `searchRefreshed` for the matching ntxId.+ */+import { deferred } from "@triliumnext/commons";+import type { SearchResultDetailsResponse } from "@triliumnext/commons";+import { render } from "preact";+import { act } from "preact/test-utils";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import Component from "../../../components/component";+import type FNote from "../../../entities/fnote";+import server from "../../../services/server";+import { buildNote } from "../../../test/easy-froca";+import { ParentComponent } from "../../react/react_utils";+import { useSearchResultDetails } from "./useSearchResultDetails";++function makeResponse(noteIds: string[]): SearchResultDetailsResponse {+ return {+ results: noteIds.map((noteId) => ({+ noteId,+ notePath: noteId,+ noteTitle: `Title ${noteId}`,+ notePathTitle: `Root › Title ${noteId}`,+ contentSnippet: `snippet ${noteId}`,+ highlightedContentSnippet: `snippet <b>${noteId}</b>`,+ icon: "bx bx-note"+ })),+ highlightedTokenInfos: [],+ error: null+ };+}++let observed: ReturnType<typeof useSearchResultDetails> | undefined;++function Harness({ note, pageNoteIds, ntxId }: { note: FNote; pageNoteIds: string[]; ntxId: string }) {+ observed = useSearchResultDetails(note, pageNoteIds, ntxId);+ return null;+}++describe("useSearchResultDetails", () => {+ let container: HTMLElement | undefined;+ let parent: Component;++ beforeEach(() => {+ observed = undefined;+ parent = new Component();+ container = document.createElement("div");+ document.body.appendChild(container);+ });++ afterEach(() => {+ vi.restoreAllMocks();+ if (container) {+ render(null, container);+ container.remove();+ container = undefined;+ }+ });++ async function renderHarness(props: { note: FNote; pageNoteIds: string[]; ntxId: string }) {+ const el = container;+ if (!el) throw new Error("container not initialized");+ await act(async () => {+ render(+ <ParentComponent.Provider value={parent}>+ <Harness {...props} />+ </ParentComponent.Provider>,+ el+ );+ });+ }++ it("fetches details for the page and indexes them by noteId", async () => {+ const post = vi.spyOn(server, "post").mockResolvedValue(makeResponse(["a", "b"]));+ const note = buildNote({ title: "Search", type: "search" });++ await renderHarness({ note, pageNoteIds: ["a", "b"], ntxId: "ntx-1" });+ expect(post).toHaveBeenCalledWith(+ `search-note/${note.noteId}/result-details`,+ { noteIds: ["a", "b"] }+ );++ await act(async () => { await Promise.resolve(); });++ expect(observed?.loading).toBe(false);+ expect(observed?.detailsByNoteId.get("a")?.noteTitle).toBe("Title a");+ expect(observed?.detailsByNoteId.get("b")?.highlightedContentSnippet).toBe("snippet <b>b</b>");+ });++ it("discards a stale response that resolves after a newer one", async () => {+ const first = deferred<SearchResultDetailsResponse>();+ const second = deferred<SearchResultDetailsResponse>();+ const post = vi.spyOn(server, "post")+ .mockReturnValueOnce(first as unknown as Promise<unknown>)+ .mockReturnValueOnce(second as unknown as Promise<unknown>);+ const note = buildNote({ title: "Search", type: "search" });++ // First page fetch.+ await renderHarness({ note, pageNoteIds: ["a"], ntxId: "ntx-1" });+ // Navigate to the next page before the first response lands: a second fetch is issued.+ await renderHarness({ note, pageNoteIds: ["b"], ntxId: "ntx-1" });+ expect(post).toHaveBeenCalledTimes(2);++ // The newer (second) response resolves first...+ await act(async () => {+ second.resolve(makeResponse(["b"]));+ await Promise.resolve();+ });+ // ...then the stale (first) response resolves and must NOT clobber it.+ await act(async () => {+ first.resolve(makeResponse(["a"]));+ await Promise.resolve();+ });++ expect(observed?.detailsByNoteId.has("a")).toBe(false);+ expect(observed?.detailsByNoteId.get("b")?.noteTitle).toBe("Title b");+ });++ it("refetches when the search note re-executes for the matching ntxId", async () => {+ const post = vi.spyOn(server, "post").mockResolvedValue(makeResponse(["a"]));+ const note = buildNote({ title: "Search", type: "search" });++ await renderHarness({ note, pageNoteIds: ["a"], ntxId: "ntx-1" });+ await act(async () => { await Promise.resolve(); });+ expect(post).toHaveBeenCalledTimes(1);++ // A re-execution with an unrelated ntxId must be ignored.+ await act(async () => {+ await parent.handleEvent("searchRefreshed", { ntxId: "other" });+ });+ expect(post).toHaveBeenCalledTimes(1);++ // A re-execution for our ntxId refetches even though the page ids are unchanged.+ await act(async () => {+ await parent.handleEvent("searchRefreshed", { ntxId: "ntx-1" });+ await Promise.resolve();+ });+ expect(post).toHaveBeenCalledTimes(2);+ });+});diff --git a/apps/client/src/widgets/collections/search/useSearchResultDetails.ts b/apps/client/src/widgets/collections/search/useSearchResultDetails.tsnew file mode 100644index 0000000000..8f33f03bcb--- /dev/null+++ b/apps/client/src/widgets/collections/search/useSearchResultDetails.ts@@ -0,0 +1,71 @@+import type { SearchResultDetails, SearchResultDetailsResponse } from "@triliumnext/commons";+import { useEffect, useRef, useState } from "preact/hooks";++import type FNote from "../../../entities/fnote";+import server from "../../../services/server";+import { useTriliumEvent } from "../../react/hooks";++export interface SearchResultDetailsState {+ detailsByNoteId: Map<string, SearchResultDetails>;+ loading: boolean;+}++/**+ * Fetches the lazy per-note snippet/highlight details for a single page of search results.+ *+ * The fetch keys on the page's note-id list (encoded as a string so a freshly sliced array with the+ * same ids doesn't re-trigger it), so paging naturally refetches. That covers re-executions where+ * the matched set changes; a `searchRefreshed` for our `ntxId` additionally forces a refetch so a+ * re-execution that yields the *same* ids but updated content still refreshes the snippets.+ *+ * Responses can land out of order (a slow first page resolving after the user has paged on), so an+ * incrementing sequence ref guards against a stale response clobbering a newer one — the same+ * pattern `useNoteIds` uses for its own refreshes.+ */+export function useSearchResultDetails(+ note: FNote | null | undefined,+ pageNoteIds: string[],+ ntxId: string | null | undefined+): SearchResultDetailsState {+ const [ detailsByNoteId, setDetailsByNoteId ] = useState<Map<string, SearchResultDetails>>(new Map());+ const [ loading, setLoading ] = useState(false);+ const seqRef = useRef(0);+ const [ refreshToken, setRefreshToken ] = useState(0);++ const noteId = note?.noteId;+ const pageKey = pageNoteIds.join(",");++ useEffect(() => {+ if (!noteId || pageNoteIds.length === 0) {+ // Nothing to fetch: drop any stale details and mark the newest issued fetch as this one+ // so a still-pending older response can't land later.+ seqRef.current++;+ setDetailsByNoteId(new Map());+ setLoading(false);+ return;+ }++ const seq = ++seqRef.current;+ setLoading(true);+ server.post<SearchResultDetailsResponse>(`search-note/${noteId}/result-details`, { noteIds: pageNoteIds })+ .then((response) => {+ if (seq !== seqRef.current) return; // superseded by a newer fetch+ setDetailsByNoteId(new Map(response.results.map((result) => [ result.noteId, result ])));+ setLoading(false);+ })+ .catch(() => {+ if (seq !== seqRef.current) return;+ setDetailsByNoteId(new Map());+ setLoading(false);+ });+ // pageKey stands in for the pageNoteIds array identity; refreshToken forces a re-execution refetch.+ }, [ noteId, pageKey, refreshToken ]);++ useTriliumEvent("searchRefreshed", ({ ntxId: eventNtxId }) => {+ if (eventNtxId === ntxId) {+ setRefreshToken((token) => token + 1);+ }+ });++ return { detailsByNoteId, loading };+}diff --git a/apps/client/src/widgets/search_result.tsx b/apps/client/src/widgets/search_result.tsxindex b97a257029..15cf84bd0b 100644--- a/apps/client/src/widgets/search_result.tsx+++ b/apps/client/src/widgets/search_result.tsx@@ -5,7 +5,8 @@ import clsx from "clsx";import { useEffect, useState } from "preact/hooks";import { t } from "../services/i18n";-import { SearchNoteList } from "./collections/NoteList";+import { SearchNoteList, useNoteViewType } from "./collections/NoteList";+import SearchResultsList from "./collections/search/SearchResultsList";import Button from "./react/Button";import { useNoteContext, useTriliumEvent } from "./react/hooks";import NoItems from "./react/NoItems";@@ -18,6 +19,7 @@ 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)[]>();@@ -59,13 +61,25 @@ export default function SearchResult() {)}{state === SearchResultState.GOT_RESULTS && (- <SearchNoteList- media="screen"- note={note}- notePath={notePath}- highlightedTokens={highlightedTokens}- ntxId={ntxId}- />+ viewType === "list"+ ? (+ <SearchResultsList+ media="screen"+ note={note}+ notePath={notePath}+ highlightedTokens={highlightedTokens}+ ntxId={ntxId}+ />+ )+ : (+ <SearchNoteList+ media="screen"+ note={note}+ notePath={notePath}+ highlightedTokens={highlightedTokens}+ ntxId={ntxId}+ />+ ))}</div>);