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(search): shared search result details builder
perfectra1n0d6cc74f847c
diff --git a/packages/commons/src/lib/server_api.ts b/packages/commons/src/lib/server_api.tsindex cacc821b05..8b4c15b022 100644--- a/packages/commons/src/lib/server_api.ts+++ b/packages/commons/src/lib/server_api.ts@@ -242,6 +242,24 @@ export interface HighlightedTokenInfo {type: "plain" | "regex";}+/**+ * Per-note snippet + highlight details for one search result, built lazily for a+ * page of results. Snippet fields are absent when there is nothing to show (e.g.+ * protected notes without a session, or script-based searches).+ */+export interface SearchResultDetails {+ noteId: string;+ notePath: string;+ noteTitle: string;+ notePathTitle: string;+ highlightedNotePathTitle?: string;+ contentSnippet?: string;+ highlightedContentSnippet?: string;+ attributeSnippet?: string;+ highlightedAttributeSnippet?: string;+ icon: string;+}+export interface SimilarNote {score: number;notePath: string[];diff --git a/packages/trilium-core/src/routes/api/search.ts b/packages/trilium-core/src/routes/api/search.tsindex 01bab721ec..fbe6ad491f 100644--- a/packages/trilium-core/src/routes/api/search.ts+++ b/packages/trilium-core/src/routes/api/search.ts@@ -8,7 +8,6 @@ import SearchContext from "../../services/search/search_context.js";import type SearchResult from "../../services/search/search_result.js";import searchService, { EMPTY_RESULT, type SearchNoteResult } from "../../services/search/services/search.js";import { ValidationError } from "../../errors.js";-import becca_service from "../../becca/becca_service.js";import { getHoistedNoteId } from "../../services/context.js";function searchFromNote(req: Request<{ noteId: string }>): SearchNoteResult {@@ -57,39 +56,11 @@ function quickSearch(req: Request<{ searchString: string }>) {ancestorNoteId: hoistedNoteService.isHoistedInHiddenSubtree() ? "root" : hoistedNoteService.getHoistedNoteId()});- // Execute search with our context- const allSearchResults = searchService.findResultsWithQuery(searchString, searchContext);- const trimmed = allSearchResults.slice(0, 200);-- // Extract snippets using highlightedTokens from our context- for (const result of trimmed) {- result.contentSnippet = searchService.extractContentSnippet(result.noteId, searchContext.highlightedTokens);- result.attributeSnippet = searchService.extractAttributeSnippet(result.noteId, searchContext.highlightedTokens);- }-- // Highlight the results- searchService.highlightSearchResults(trimmed, searchContext.highlightedTokens, searchContext.ignoreInternalAttributes);-- // Map to API format- const searchResults = trimmed.map((result) => {- const { title, icon } = becca_service.getNoteTitleAndIcon(result.noteId);- return {- notePath: result.notePath,- noteTitle: title,- notePathTitle: result.notePathTitle,- highlightedNotePathTitle: result.highlightedNotePathTitle,- contentSnippet: result.contentSnippet,- highlightedContentSnippet: result.highlightedContentSnippet,- attributeSnippet: result.attributeSnippet,- highlightedAttributeSnippet: result.highlightedAttributeSnippet,- icon- };- });-- const resultNoteIds = searchResults.map((result) => result.notePath.split("/").pop()).filter(Boolean) as string[];+ const trimmed = searchService.findResultsWithQuery(searchString, searchContext).slice(0, 200);+ const searchResults = searchService.buildSearchResultDetails(trimmed, searchContext);return {- searchResultNoteIds: resultNoteIds,+ searchResultNoteIds: searchResults.map((result) => result.noteId),searchResults,error: searchContext.getError()};diff --git a/packages/trilium-core/src/services/search/services/search.ts b/packages/trilium-core/src/services/search/services/search.tsindex 83c0cfe53c..ce354fce70 100644--- a/packages/trilium-core/src/services/search/services/search.ts+++ b/packages/trilium-core/src/services/search/services/search.ts@@ -1,4 +1,4 @@-import type { HighlightedTokenInfo } from "@triliumnext/commons";+import type { HighlightedTokenInfo, SearchResultDetails } from "@triliumnext/commons";import { extractLlmChatText } from "@triliumnext/commons/src/lib/llm/extract_chat_text.js";import striptags from "striptags";@@ -43,46 +43,58 @@ export const EMPTY_RESULT: SearchNoteResult = {};function searchFromNote(note: BNote): SearchNoteResult {- let searchResultNoteIds;- let highlightedTokens: string[];- let highlightedTokenInfos: HighlightedTokenInfo[];+ const { searchResults, searchContext, error } = searchFromNoteWithContext(note);+ // we won't return search note's own noteId+ // also don't allow root since that would force infinite cycle+ return {+ searchResultNoteIds: searchResults+ .map((sr) => sr.noteId)+ .filter((resultNoteId) => !["root", note.noteId].includes(resultNoteId)),+ highlightedTokens: searchContext ? searchContext.highlightedTokens : [],+ highlightedTokenInfos: searchContext ? searchContext.getHighlightedTokenInfos() : [],+ error+ };+}++/**+ * Runs a saved search note, returning the raw {@link SearchResult}s together with+ * the {@link SearchContext} that produced them so callers can build snippets and+ * highlight token infos. Script-based searches (`~searchScript`) have no lexed+ * query, so `searchContext` is `null` for them (and there are no snippets/tokens).+ */+function searchFromNoteWithContext(note: BNote): {+ searchResults: SearchResult[];+ searchContext: SearchContext | null;+ error: string | null;+} {const searchScript = note.getRelationValue("searchScript");const searchString = note.getLabelValue("searchString") || "";- let error: string | null = null;if (searchScript) {- searchResultNoteIds = searchFromRelation(note, "searchScript");- highlightedTokens = [];- highlightedTokenInfos = [];- } else {- const searchContext = new SearchContext({- fastSearch: note.hasLabel("fastSearch"),- ancestorNoteId: note.getRelationValue("ancestor") || undefined,- ancestorDepth: note.getLabelValue("ancestorDepth") || undefined,- includeArchivedNotes: note.hasLabel("includeArchivedNotes"),- orderBy: note.getLabelValue("orderBy") || undefined,- orderDirection: note.getLabelValue("orderDirection") || undefined,- limit: parseInt(note.getLabelValue("limit") || "0", 10),- debug: note.hasLabel("debug"),- fuzzyAttributeSearch: false+ const searchResults = searchFromRelation(note, "searchScript").map((noteId) => {+ const notePath = becca.notes[noteId]?.getBestNotePath() ?? [noteId];+ return new SearchResult(notePath);});- searchResultNoteIds = findResultsWithQuery(searchString, searchContext).map((sr) => sr.noteId);-- highlightedTokens = searchContext.highlightedTokens;- highlightedTokenInfos = searchContext.getHighlightedTokenInfos();- error = searchContext.getError();+ return { searchResults, searchContext: null, error: null };}- // we won't return search note's own noteId- // also don't allow root since that would force infinite cycle- return {- searchResultNoteIds: searchResultNoteIds.filter((resultNoteId) => !["root", note.noteId].includes(resultNoteId)),- highlightedTokens,- highlightedTokenInfos,- error- };+ const searchContext = new SearchContext({+ fastSearch: note.hasLabel("fastSearch"),+ ancestorNoteId: note.getRelationValue("ancestor") || undefined,+ ancestorDepth: note.getLabelValue("ancestorDepth") || undefined,+ includeArchivedNotes: note.hasLabel("includeArchivedNotes"),+ orderBy: note.getLabelValue("orderBy") || undefined,+ orderDirection: note.getLabelValue("orderDirection") || undefined,+ limit: parseInt(note.getLabelValue("limit") || "0", 10),+ debug: note.hasLabel("debug"),+ fuzzyAttributeSearch: false+ });++ const searchResults = findResultsWithQuery(searchString, searchContext);++ return { searchResults, searchContext, error: searchContext.getError() };}function searchFromRelation(note: BNote, relationName: string) {@@ -712,21 +724,32 @@ function searchNotesForAutocomplete(query: string, fastSearch: boolean = true) {ancestorNoteId: hoistedNoteService.isHoistedInHiddenSubtree() ? "root" : hoistedNoteService.getHoistedNoteId()});- const allSearchResults = findResultsWithQuery(query, searchContext);+ const trimmed = findResultsWithQuery(query, searchContext).slice(0, 200);++ return buildSearchResultDetails(trimmed, searchContext);+}- const trimmed = allSearchResults.slice(0, 200);+/**+ * Shared builder for the snippet + highlight details of a page of search results.+ * Extracts content/attribute snippets using the context's structured (regex-aware)+ * highlight tokens, applies highlighting, and maps each result to the wire shape+ * (including `noteId`). Mutates the passed {@link SearchResult}s (setting their+ * snippet fields) as a side effect of extraction/highlighting.+ */+function buildSearchResultDetails(results: SearchResult[], searchContext: SearchContext): SearchResultDetails[] {+ const tokenInfos = searchContext.getHighlightedTokenInfos();- // Extract content and attribute snippets- for (const result of trimmed) {- result.contentSnippet = extractContentSnippet(result.noteId, searchContext.highlightedTokens);- result.attributeSnippet = extractAttributeSnippet(result.noteId, searchContext.highlightedTokens);+ for (const result of results) {+ result.contentSnippet = extractContentSnippet(result.noteId, tokenInfos);+ result.attributeSnippet = extractAttributeSnippet(result.noteId, tokenInfos);}- highlightSearchResults(trimmed, searchContext.highlightedTokens, searchContext.ignoreInternalAttributes);+ highlightSearchResults(results, tokenInfos, searchContext.ignoreInternalAttributes);- return trimmed.map((result) => {+ return results.map((result) => {const { title, icon } = becca_service.getNoteTitleAndIcon(result.noteId);return {+ noteId: result.noteId,notePath: result.notePath,noteTitle: title,notePathTitle: result.notePathTitle,@@ -799,7 +822,9 @@ function highlightSearchResults(searchResults: SearchResult[], tokens: Highlightexport default {searchFromNote,+ searchFromNoteWithContext,searchNotesForAutocomplete,+ buildSearchResultDetails,findResultsWithQuery,findFirstNoteWithQuery,searchNotes,diff --git a/packages/trilium-core/src/services/search/services/search_highlight.spec.ts b/packages/trilium-core/src/services/search/services/search_highlight.spec.tsindex 9314472ebb..a577933cbe 100644--- a/packages/trilium-core/src/services/search/services/search_highlight.spec.ts+++ b/packages/trilium-core/src/services/search/services/search_highlight.spec.ts@@ -5,6 +5,7 @@ import BBranch from "../../../becca/entities/bbranch.js";import BNote from "../../../becca/entities/bnote.js";import { note, NoteBuilder } from "../../../test/becca_mocking.js";import { normalizePreservingLength } from "../../utils/index.js";+import SearchContext from "../search_context.js";import SearchResult from "../search_result.js";import searchService from "./search.js";@@ -85,3 +86,44 @@ describe("highlightSearchResults", () => {expect(result.highlightedContentSnippet).toBe("plain text");});});++describe("buildSearchResultDetails", () => {+ beforeEach(() => {+ becca.reset();+ rootNote = new NoteBuilder(new BNote({ noteId: "root", title: "root", type: "text" }));+ new BBranch({ branchId: "none_root", noteId: "root", parentNoteId: "none", notePosition: 10 });+ });++ it("maps results to the wire shape including noteId, titles, icon and highlighted attribute snippet", () => {+ const child = note("Meeting notes").label("project", "phoenix");+ rootNote.child(child);+ const result = new SearchResult(["root", child.note.noteId]);++ const searchContext = new SearchContext();+ searchContext.highlightedTokens.push("phoenix");++ const [details] = searchService.buildSearchResultDetails([result], searchContext);++ expect(details.noteId).toBe(child.note.noteId);+ expect(details.noteTitle).toBe("Meeting notes");+ expect(details.notePath).toBe(`root/${child.note.noteId}`);+ expect(details.notePathTitle).toContain("Meeting notes");+ expect(details.icon).toBeTruthy();+ expect(details.attributeSnippet).toContain("phoenix");+ expect(details.highlightedAttributeSnippet).toContain("<b>phoenix</b>");+ });++ it("matches attribute values with a regex token from getHighlightedTokenInfos", () => {+ const child = note("Server config").label("env", "production");+ rootNote.child(child);+ const result = new SearchResult(["root", child.note.noteId]);++ const searchContext = new SearchContext();+ searchContext.highlightedTokens.push("prod[a-z]+");+ searchContext.regexTokens.add("prod[a-z]+");++ const [details] = searchService.buildSearchResultDetails([result], searchContext);++ expect(details.highlightedAttributeSnippet).toContain("<b>production</b>");+ });+});