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): searchTerms view scope round-trip
perfectra1nfe1c485303b1
diff --git a/apps/client/src/services/link.spec.ts b/apps/client/src/services/link.spec.tsindex 2f0811c2e9..5cf5ebe28b 100644--- a/apps/client/src/services/link.spec.ts+++ b/apps/client/src/services/link.spec.ts@@ -175,6 +175,53 @@ describe("calculateHash", () => {});});+describe("searchTerms view scope round-trip", () => {+ it("omits the searchTerms param when the array is empty or undefined", () => {+ expect(calculateHash({ notePath: "root/aaaaaaaaaaaa", viewScope: { searchTerms: [] } } as any)).toBe("#root/aaaaaaaaaaaa");+ expect(calculateHash({ notePath: "root/aaaaaaaaaaaa", viewScope: {} } as any)).toBe("#root/aaaaaaaaaaaa");+ expect(calculateHash({ notePath: "root/aaaaaaaaaaaa" } as any)).toBe("#root/aaaaaaaaaaaa");+ });++ it("emits a searchTerms param when non-empty", () => {+ const hash = calculateHash({ notePath: "root/aaaaaaaaaaaa", viewScope: { searchTerms: ["hello"] } } as any);+ expect(hash).toContain("searchTerms=");+ });++ it("round-trips a single search term", () => {+ const hash = calculateHash({ notePath: "root/aaaaaaaaaaaa", viewScope: { searchTerms: ["hello"] } } as any);+ const { viewScope } = parseNavigationStateFromUrl(hash) as any;+ expect(viewScope.searchTerms).toEqual(["hello"]);+ });++ it("round-trips multiple search terms, preserving order", () => {+ const hash = calculateHash({ notePath: "root/aaaaaaaaaaaa", viewScope: { searchTerms: ["hello", "world", "foo"] } } as any);+ const { viewScope } = parseNavigationStateFromUrl(hash) as any;+ expect(viewScope.searchTerms).toEqual(["hello", "world", "foo"]);+ });++ it("round-trips tokens containing commas, percent signs, quotes and unicode", () => {+ const terms = ["a,b", "100% done", 'she said "hi"', "héllo wörld 日本語"];+ const hash = calculateHash({ notePath: "root/aaaaaaaaaaaa", viewScope: { searchTerms: terms } } as any);+ const { viewScope } = parseNavigationStateFromUrl(hash) as any;+ expect(viewScope.searchTerms).toEqual(terms);+ });++ it("drops malformed encoded search-term entries instead of throwing", () => {+ // Hand-craft a hash whose decoded searchTerms value is "good,%E0%A4%A" -- a well-formed+ // token followed by a truncated (invalid) percent-encoding sequence.+ const hash = `#root/aaaaaaaaaaaa?searchTerms=${encodeURIComponent("good,%E0%A4%A")}`;+ expect(() => parseNavigationStateFromUrl(hash)).not.toThrow();+ const { viewScope } = parseNavigationStateFromUrl(hash) as any;+ expect(viewScope.searchTerms).toEqual(["good"]);+ });++ it("does not touch the legacy #?searchString= branch", () => {+ const output = parseNavigationStateFromUrl("#?searchString=hello&searchTerms=world");+ // searchString short-circuits to its own dedicated return before viewScope is even considered+ expect(output).toStrictEqual({ searchString: "hello" });+ });+});+describe("getNotePathFromUrl", () => {it("extracts the note path from a hash url and returns null otherwise", () => {expect(linkService.getNotePathFromUrl("https://x.test/#root/abc_123")).toBe("root/abc_123");diff --git a/apps/client/src/services/link.ts b/apps/client/src/services/link.tsindex 72c92405f9..77c6013b12 100644--- a/apps/client/src/services/link.ts+++ b/apps/client/src/services/link.ts@@ -62,6 +62,11 @@ export interface ViewScope {tocCollapsedHeadings?: Set<string>;/** When set, scrolls to a bookmark anchor within the note after navigation. */bookmark?: string;+ /**+ * Search terms to highlight and jump to after navigating from search results; consumed once+ * by the destination type widget (mirrors `bookmark` semantics).+ */+ searchTerms?: string[];}interface CreateLinkOptions {@@ -196,7 +201,10 @@ export function calculateHash({ notePath, ntxId, hoistedNoteId, viewScope = {} }ntxId ? { ntxId } : null,hoistedNoteId && hoistedNoteId !== "root" ? { hoistedNoteId } : null,viewScope.viewMode && viewScope.viewMode !== "default" ? { viewMode: viewScope.viewMode } : null,- viewScope.attachmentId ? { attachmentId: viewScope.attachmentId } : null+ viewScope.attachmentId ? { attachmentId: viewScope.attachmentId } : null,+ viewScope.searchTerms?.length+ ? { searchTerms: viewScope.searchTerms.map(encodeURIComponent).join(",") }+ : null].filter((p) => !!p);const paramStr = params@@ -261,6 +269,21 @@ export function parseNavigationStateFromUrl(url: string | undefined) {hoistedNoteId = value;} else if (name === "searchString") {searchString = value; // supports triggering search from URL, e.g. #?searchString=blabla+ } else if (name === "searchTerms") {+ // `value` already went through one decodeURIComponent() above (undoing the generic+ // pipeline's outer encode); each comma-separated token needs its own inner decode.+ // A malformed token (corrupted URL, hand-edited link) must not break navigation for+ // the rest of the link, so drop it rather than letting decodeURIComponent throw.+ viewScope.searchTerms = value+ .split(",")+ .map((token) => {+ try {+ return decodeURIComponent(token);+ } catch {+ return null;+ }+ })+ .filter((token): token is string => token !== null);} else if (["viewMode", "attachmentId", "bookmark"].includes(name)) {(viewScope as any)[name] = value;} else if (name === "popup") {diff --git a/apps/client/src/widgets/collections/search/SearchResultCard.tsx b/apps/client/src/widgets/collections/search/SearchResultCard.tsxindex 32a104e719..cb42458690 100644--- a/apps/client/src/widgets/collections/search/SearchResultCard.tsx+++ b/apps/client/src/widgets/collections/search/SearchResultCard.tsx@@ -30,11 +30,7 @@ export default function SearchResultCard({ noteId, details, loading, highlightedconst 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 viewScope: ViewScope = { searchTerms };const href = calculateHash({ notePath: noteId, viewScope });// Set the title text imperatively so mark.js (which mutates the DOM to inject `.ck-find-result`@@ -65,9 +61,6 @@ export default function SearchResultCard({ noteId, details, loading, highlighted);}-/** 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.diff --git a/apps/client/src/widgets/collections/search/SearchResultsList.spec.tsx b/apps/client/src/widgets/collections/search/SearchResultsList.spec.tsxindex 2201524233..3c3efd232f 100644--- a/apps/client/src/widgets/collections/search/SearchResultsList.spec.tsx+++ b/apps/client/src/widgets/collections/search/SearchResultsList.spec.tsx@@ -70,7 +70,9 @@ describe("SearchResultCard", () => {);const link = container.querySelector("a.search-result-card");- expect(link?.getAttribute("href")).toBe(`#${note.noteId}`);+ // The card's href carries the highlighted plain tokens as `searchTerms` so the destination+ // type widget can highlight/jump to them once ViewScope.searchTerms is real (task 8).+ expect(link?.getAttribute("href")).toBe(`#${note.noteId}?searchTerms=sync`);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");diff --git a/apps/client/src/widgets/dialogs/jump_to_note.tsx b/apps/client/src/widgets/dialogs/jump_to_note.tsxindex b21aeb2fdc..accebf8c06 100644--- a/apps/client/src/widgets/dialogs/jump_to_note.tsx+++ b/apps/client/src/widgets/dialogs/jump_to_note.tsx@@ -164,14 +164,6 @@ export default function JumpToNoteDialogComponent() {);}-/**- * Task 8 promotes `searchTerms` onto {@link ViewScope}; widened locally until then (same- * pattern as SearchResultCard.tsx's `SearchResultViewScope`). The autocomplete response has- * no per-suggestion token list, so we pass the trimmed raw query as a single term rather than- * re-deriving a token list client-side — simple, and good enough for jump-to-match highlighting.- */-type JumpToNoteViewScope = ViewScope & { searchTerms?: string[] };-/*** Only carry search terms into the opened note when the dialog was actually used as a text* search — not the command palette, and not an untyped "recent notes" pick — since jumping@@ -179,8 +171,12 @@ type JumpToNoteViewScope = ViewScope & { searchTerms?: string[] };* the gating itself is unit-testable without rendering the dialog; the caller is responsible* for keeping `typedText` accurate (see the `actualText` ref sync in `openDialog`/`onTextChange`* and the "input"-triggering functions in note_autocomplete.ts).+ *+ * The autocomplete response has no per-suggestion token list, so we pass the trimmed raw query+ * as a single term rather than re-deriving a token list client-side — simple, and good enough+ * for jump-to-match highlighting.*/-export function deriveSearchViewScope(isCommandMode: boolean, typedText: string | undefined): JumpToNoteViewScope {+export function deriveSearchViewScope(isCommandMode: boolean, typedText: string | undefined): ViewScope {const searchString = !isCommandMode ? typedText?.trim() : "";return searchString ? { searchTerms: [searchString] } : {};}