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(search): index reference-link titles and link-preview metadata
perfectra1n9119e66ebf9c
diff --git a/packages/trilium-core/src/services/search/expressions/note_content_fulltext.ts b/packages/trilium-core/src/services/search/expressions/note_content_fulltext.tsindex 94a9954b20..a6e74d8197 100644--- a/packages/trilium-core/src/services/search/expressions/note_content_fulltext.ts+++ b/packages/trilium-core/src/services/search/expressions/note_content_fulltext.ts@@ -237,7 +237,7 @@ class NoteContentFulltextExp extends Expression {return;}- content = preprocessContent(content, type, mime, this.raw);+ content = preprocessContent(content, type, mime, this.raw, (id) => becca.notes[id]?.title ?? null);// Apply content size validation and preprocessingconst processedContent = validateAndPreprocessContent(content, noteId);diff --git a/packages/trilium-core/src/services/search/expressions/note_content_fulltext_preprocessor.spec.ts b/packages/trilium-core/src/services/search/expressions/note_content_fulltext_preprocessor.spec.tsindex 0704a8102d..4e57ee92a0 100644--- a/packages/trilium-core/src/services/search/expressions/note_content_fulltext_preprocessor.spec.ts+++ b/packages/trilium-core/src/services/search/expressions/note_content_fulltext_preprocessor.spec.ts@@ -39,6 +39,79 @@ describe("Canvas preprocessing", () => {});});+describe("Reference-link & link-preview searchability", () => {+ const type: NoteType = "text";+ const mime = "text/html";++ it("appends the resolved title of an empty-text reference link", () => {+ // dataDowncast markup from referencelink.ts: <a href=... class="reference-link">title</a>.+ // The stored anchor text is stale/empty, so the real title must come from the resolver.+ const html = `<p>See <a href="#root/abc123DEF456" class="reference-link"></a> for details.</p>`;+ const result = preprocessContent(html, type, mime, false, (id) => (id === "abc123DEF456" ? "Special Topic" : null));+ expect(result).toContain("Special Topic");+ });++ it("also resolves plain internal links (not only reference links)", () => {+ const html = `<p>Jump to <a href="#root/parent1/target99">whatever</a>.</p>`;+ const result = preprocessContent(html, type, mime, false, (id) => (id === "target99" ? "Linked Note" : null));+ expect(result).toContain("Linked Note");+ });++ it("extracts link-embed metadata and entity-decodes attribute values", () => {+ // dataDowncast markup from link_embed_editing.ts (metadataViewAttributes): class first,+ // then META_KEYS-ordered data-* attributes.+ const html = `<section class="link-embed" data-url="https://example.com/a" data-embed-type="card" data-title="Great Article" data-description="Things & stuff" data-site-name="Example Site"><div class="link-embed-preview-wrapper"></div></section>`;+ const result = preprocessContent(html, type, mime, false);+ expect(result).toContain("https://example.com/a");+ expect(result).toContain("Great Article");+ expect(result).toContain("Things & stuff");+ expect(result).toContain("Example Site");+ });++ it("extracts link-mention metadata", () => {+ const html = `<p>a <span class="link-mention" data-url="https://example.com/x" data-title="Mentioned Thing" data-site-name="Mention Site">x</span> b</p>`;+ const result = preprocessContent(html, type, mime, false);+ expect(result).toContain("https://example.com/x");+ expect(result).toContain("Mentioned Thing");+ expect(result).toContain("Mention Site");+ });++ it("appends a repeated link target's title only once", () => {+ const html = `<p><a href="#root/dup1" class="reference-link"></a> and <a href="#root/dup1">again</a></p>`;+ let calls = 0;+ const result = preprocessContent(html, type, mime, false, (id) => {+ if (id === "dup1") {+ calls++;+ return "Repeated Target";+ }+ return null;+ });+ expect(result.match(/Repeated Target/g)?.length).toEqual(1);+ expect(calls).toEqual(1);+ });++ it("skips link targets whose resolver returns null (no crash, nothing appended)", () => {+ const html = `<p><a href="#root/missing1" class="reference-link"></a></p>`;+ const withNullResolver = preprocessContent(html, type, mime, false, () => null);+ const withoutResolver = preprocessContent(html, type, mime, false);+ // A null return appends no title, so output matches the resolver-omitted case.+ expect(withNullResolver).toEqual(withoutResolver);+ });++ it("behaves as before when no resolver is given (internal-link titles not injected)", () => {+ const html = `<p><a href="#root/abc123DEF456" class="reference-link"></a></p>`;+ const result = preprocessContent(html, type, mime, false);+ // No title is injected; the stripped anchor leaves the href-bearing tag behind.+ expect(result).not.toContain("Special Topic");+ });++ it("keeps plain external link URLs searchable (regression)", () => {+ const html = `<p>see <a href="https://example.com/x">the site</a> now</p>`;+ const result = preprocessContent(html, type, mime, false);+ expect(result).toContain("https://example.com/x");+ });+});+describe("LLM chat preprocessing", () => {const type: NoteType = "llmChat";const mime = "application/json";diff --git a/packages/trilium-core/src/services/search/expressions/note_content_fulltext_preprocessor.ts b/packages/trilium-core/src/services/search/expressions/note_content_fulltext_preprocessor.tsindex 9224e8a74d..cf8c3a4906 100644--- a/packages/trilium-core/src/services/search/expressions/note_content_fulltext_preprocessor.ts+++ b/packages/trilium-core/src/services/search/expressions/note_content_fulltext_preprocessor.ts@@ -2,15 +2,32 @@ import { extractLlmChatText } from "@triliumnext/commons/src/lib/llm/extract_chaimport { extractSpreadsheetText } from "@triliumnext/commons/src/lib/spreadsheet/extract_text.js";import striptags from "striptags";import { normalizeSearchText } from "../utils/text_utils";-import { normalize } from "../../utils/index";+import { normalize, unescapeHtml } from "../../utils/index";-export default function preprocessContent(rawContent: string | Uint8Array, type: string, mime: string, raw?: boolean) {- let content = normalize(rawContent.toString());+/**+ * Resolves a note's title by its id. Injected by the caller so this module stays+ * pure and browser-safe (no becca import here). Returns null for unknown notes.+ */+export type NoteTitleResolver = (noteId: string) => string | null;++export default function preprocessContent(rawContent: string | Uint8Array, type: string, mime: string, raw?: boolean, resolveNoteTitle?: NoteTitleResolver) {+ const originalContent = rawContent.toString();+ let content = normalize(originalContent);if (type === "text" && mime === "text/html") {if (!raw) {+ // Pull searchable text out of link previews and internal-link targets BEFORE+ // stripTags discards their data-* metadata and (stale) anchor text. Extraction+ // runs against the original, case-preserved markup so link target noteIds still+ // resolve (normalize() lowercases, which would corrupt the ids).+ const injectedText = extractLinkSearchText(originalContent, resolveNoteTitle);+// Content size already filtered at DB level, safe to processcontent = stripTags(content);++ if (injectedText) {+ content = `${content} ${injectedText}`;+ }}content = content.replace(/ /g, " ");@@ -114,6 +131,66 @@ function processCanvasContent(content: string) {return content;}+/** Metadata attributes to index from link previews, in the order they are appended. */+const LINK_PREVIEW_ATTRIBUTES = ["data-url", "data-title", "data-description", "data-site-name"] as const;++// Matches the opening tag of a link-embed section or link-mention span (serialized by+// packages/ckeditor5/src/plugins/link_embed/link_embed_editing.ts dataDowncast).+const LINK_PREVIEW_TAG_RE = /<(?:section|span)\b[^>]*\bclass=["'][^"']*\blink-(?:embed|mention)\b[^"']*["'][^>]*>/gi;++// Copy of services/notes.ts findInternalLinks: captures the target noteId of a reference+// link or plain internal link. Kept inline so the preprocessor stays free of the notes service.+const INTERNAL_LINK_RE = /href="[^"]*#root[a-zA-Z0-9_\/]*\/([a-zA-Z0-9_]+)\/?"/g;++/**+ * Builds a space-separated bag of extra searchable text from a text/html note's link+ * previews (their data-* metadata) and internal-link targets (their resolved titles).+ */+function extractLinkSearchText(content: string, resolveNoteTitle?: NoteTitleResolver): string {+ const parts: string[] = [];++ for (const tag of content.match(LINK_PREVIEW_TAG_RE) ?? []) {+ for (const attrName of LINK_PREVIEW_ATTRIBUTES) {+ const value = extractAttribute(tag, attrName);+ if (value) {+ parts.push(value);+ }+ }+ }++ if (resolveNoteTitle) {+ const seen = new Set<string>();+ let match: RegExpExecArray | null;+ INTERNAL_LINK_RE.lastIndex = 0;+ while ((match = INTERNAL_LINK_RE.exec(content)) !== null) {+ const noteId = match[1];+ if (seen.has(noteId)) {+ continue;+ }+ seen.add(noteId);++ const title = resolveNoteTitle(noteId);+ if (title) {+ parts.push(title);+ }+ }+ }++ return parts.join(" ");+}++/** Reads a single/double-quoted HTML attribute value from a tag string, entity-decoded. */+function extractAttribute(tag: string, attrName: string): string | null {+ const re = new RegExp(`\\b${attrName}=(?:"([^"]*)"|'([^']*)')`, "i");+ const match = re.exec(tag);+ if (!match) {+ return null;+ }++ const rawValue = match[1] !== undefined ? match[1] : match[2];+ return rawValue ? unescapeHtml(rawValue) : null;+}+function stripTags(content: string) {// we want to allow link to preserve URLs: https://github.com/zadam/trilium/issues/2412// we want to insert space in place of block tags (because they imply text separation)diff --git a/packages/trilium-core/src/services/search/services/search.spec.ts b/packages/trilium-core/src/services/search/services/search.spec.tsindex 6692dbeff9..8278aa7af6 100644--- a/packages/trilium-core/src/services/search/services/search.spec.ts+++ b/packages/trilium-core/src/services/search/services/search.spec.ts@@ -868,6 +868,23 @@ describe("Search", () => {expect(searchResults[fuzzyRank].score).toBeLessThan(10);});+ it("finds a note via a reference-link's resolved target title, ranked below the target (#10616)", () => {+ // Note A is the link target; note B links to it with an empty-text reference link.+ // Searching A's title must find B (its title is injected into B's searchable content)+ // and rank A (a direct title match) above B (an indirect content match).+ const target = contentNote("Special Topic", "");+ const linker = contentNote("Linker", `<p>see <a class="reference-link" href="#root/${target.noteId}"></a></p>`);++ const searchResults = searchService.findResultsWithQuery("special topic", new SearchContext());++ const targetRank = rank(searchResults, target.noteId);+ const linkerRank = rank(searchResults, linker.noteId);++ expect(targetRank).toBeGreaterThanOrEqual(0);+ expect(linkerRank).toBeGreaterThanOrEqual(0);+ expect(targetRank).toBeLessThan(linkerRank);+ });+it("skips content matching in fast search, so content scoring is a natural no-op", () => {const doc = contentNote("Doc", "please sync the database now");