Skip to content

Build your personal knowledge base with Trilium Notes

fix(search): seed the find bar with the words as the note spells them (#11787)

Elian Dorana4f529af8811
diff --git a/apps/client/src/widgets/collections/search/SearchResultCard.tsx b/apps/client/src/widgets/collections/search/SearchResultCard.tsx
index 3868cbd83f..77c3584ba2 100644
--- a/apps/client/src/widgets/collections/search/SearchResultCard.tsx
+++ b/apps/client/src/widgets/collections/search/SearchResultCard.tsx
@@ -28,7 +28,8 @@ export default function SearchResultCard({ noteId, details, loading, highlighted
const icon = note?.getIcon() ?? details?.icon ?? "bx bx-note";
const breadcrumb = getBreadcrumbTitle(details?.notePathTitle);
- const searchTerms = toPlainSearchTerms(highlightedTokens);
+ // 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 href = calculateHash({ notePath: noteId, viewScope });
diff --git a/apps/client/src/widgets/collections/search/SearchResultsList.spec.tsx b/apps/client/src/widgets/collections/search/SearchResultsList.spec.tsx
index c0421e9d6d..6349bcb5b6 100644
--- a/apps/client/src/widgets/collections/search/SearchResultsList.spec.tsx
+++ b/apps/client/src/widgets/collections/search/SearchResultsList.spec.tsx
@@ -20,6 +20,7 @@ vi.mock("../../../services/i18n", () => ({
}));
import Component from "../../../components/component";
+import { calculateHash } from "../../../services/link";
import server from "../../../services/server";
import { buildNote, buildNotes } from "../../../test/easy-froca";
import { ParentComponent } from "../../react/react_utils";
@@ -99,6 +100,20 @@ describe("SearchResultCard", () => {
expect(badges[0].querySelector("b")?.textContent).toBe("open");
});
+ it("links with the words the note matched, falling back to the search tokens (#11787)", async () => {
+ const note = buildNote({ id: "note1", title: "Slovak", type: "text" });
+ await mount(
+ <SearchResultCard noteId={note.noteId} details={makeDetails({ matchedTerms: [ "Ktorý" ] })} loading={false} highlightedTokens={[ "ktory" ]} />
+ );
+ expect(container.querySelector("a.search-result-card")?.getAttribute("href"))
+ .toBe(calculateHash({ notePath: note.noteId, viewScope: { searchTerms: [ "Ktorý" ] } }));
+
+ await mount(
+ <SearchResultCard noteId={note.noteId} details={makeDetails({ matchedTerms: [] })} loading={false} highlightedTokens={[ "ktory" ]} />
+ );
+ expect(container.querySelector("a.search-result-card")?.getAttribute("href")).toBe(`#${note.noteId}?searchTerms=ktory`);
+ });
+
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(
diff --git a/packages/commons/src/lib/server_api.ts b/packages/commons/src/lib/server_api.ts
index c135dfca7f..c242bd3d03 100644
--- a/packages/commons/src/lib/server_api.ts
+++ b/packages/commons/src/lib/server_api.ts
@@ -390,6 +390,11 @@ export interface SearchResultDetails {
highlightedContentSnippet?: string;
attributeSnippet?: string;
highlightedAttributeSnippet?: string;
+ /**
+ * The text each query token matched in {@link contentSnippet}, spelled as the note has it
+ * (with its diacritics, or the word a fuzzy match found), for the find bar to look for.
+ */
+ matchedTerms?: string[];
icon: string;
}
diff --git a/packages/trilium-core/src/services/search/search_result.ts b/packages/trilium-core/src/services/search/search_result.ts
index e637ed088c..0bc5d0e7f2 100644
--- a/packages/trilium-core/src/services/search/search_result.ts
+++ b/packages/trilium-core/src/services/search/search_result.ts
@@ -96,6 +96,7 @@ class SearchResult {
highlightedContentSnippet?: string;
attributeSnippet?: string;
highlightedAttributeSnippet?: string;
+ matchedTerms?: string[];
private fuzzyScore: number; // Track fuzzy score separately
constructor(notePathArray: string[], segmentTitles?: SegmentTitleCache) {
diff --git a/packages/trilium-core/src/services/search/services/search.spec.ts b/packages/trilium-core/src/services/search/services/search.spec.ts
index 337c1200b8..1a42799d48 100644
--- a/packages/trilium-core/src/services/search/services/search.spec.ts
+++ b/packages/trilium-core/src/services/search/services/search.spec.ts
@@ -1062,6 +1062,17 @@ describe("Search", () => {
expect(detail?.highlightedContentSnippet).toContain("<b>star</b>");
});
+ it("reports the words the snippet matched, spelled as the note has them (#11787)", () => {
+ const slovak = contentNote("Slovak", "<p>Ktorý deň je dnes?</p>");
+ for (const query of [ "ktorý", "ktory" ]) {
+ expect(detailsFor(query).find((d) => d.noteId === slovak.noteId)?.matchedTerms).toEqual([ "Ktorý" ]);
+ }
+
+ // A fuzzy match reports the word that is in the note rather than the one typed.
+ const asimov = contentNote("Asimov", "<p>by American writer Isaac Asimov</p>");
+ expect(detailsFor("orbiter").find((d) => d.noteId === asimov.noteId)?.matchedTerms).toEqual([ "writer" ]);
+ });
+
it("highlights the word a fuzzy body match actually matched", () => {
// "writer" is two edits from "orbiter", which AUTO allows for a 7-character token, so
// this note is a result even though the word the user typed appears nowhere in it.
diff --git a/packages/trilium-core/src/services/search/services/search.ts b/packages/trilium-core/src/services/search/services/search.ts
index 0e6e98c6b8..935bbf8362 100644
--- a/packages/trilium-core/src/services/search/services/search.ts
+++ b/packages/trilium-core/src/services/search/services/search.ts
@@ -869,6 +869,7 @@ function buildSearchResultDetails(results: SearchResult[], searchContext: Search
: tokenInfos;
result.contentSnippet = extractContentSnippet(result.noteId, noteTokenInfos);
+ result.matchedTerms = findMatchedTerms(result.contentSnippet, noteTokenInfos);
result.attributeSnippet = extractAttributeSnippet(result.noteId, noteTokenInfos);
highlightSearchResults([ result ], noteTokenInfos, searchContext.ignoreInternalAttributes);
}
@@ -887,11 +888,13 @@ function buildSearchResultDetails(results: SearchResult[], searchContext: Search
highlightedContentSnippet: result.highlightedContentSnippet,
attributeSnippet: result.attributeSnippet,
highlightedAttributeSnippet: result.highlightedAttributeSnippet,
+ matchedTerms: result.matchedTerms,
icon: icon ?? "bx bx-note"
};
});
}
+
/**
* @param tokens the tokens to highlight, either legacy plain strings or structured
* {@link HighlightedTokenInfo}s (regex-aware). Legacy strings are treated as plain.
@@ -991,6 +994,37 @@ function tokenInfoFirstIndex(info: HighlightedTokenInfo, normalizedText: string)
return normalizedText.indexOf(normalizePreservingLength(info.token));
}
+/**
+ * The text each token matched in `snippet`, cut from the snippet as written: matching runs on the
+ * normalized text, whose positions map 1:1 onto the original. Regex tokens are left out, as the
+ * find bar looks for plain text.
+ */
+function findMatchedTerms(snippet: string | undefined, tokenInfos: HighlightedTokenInfo[]): string[] {
+ if (!snippet) {
+ return [];
+ }
+
+ const normalizedSnippet = normalizePreservingLength(snippet);
+ const terms: string[] = [];
+ for (const info of tokenInfos) {
+ if (info.type === "regex" || !info.token) {
+ continue;
+ }
+
+ const index = tokenInfoFirstIndex(info, normalizedSnippet);
+ if (index === -1) {
+ continue;
+ }
+
+ const term = snippet.slice(index, index + info.token.length);
+ if (!terms.includes(term)) {
+ terms.push(term);
+ }
+ }
+
+ return terms;
+}
+
/**
* Widens, cleans, dedupes and sorts the highlight tokens for `highlightSearchResults()`. The sort
* is longest-first so a longer match wins over a shorter one it contains.