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
chore(search): use for...of and drop the em-dash asides
Elian Dorand894fd344128
diff --git a/apps/client/src/services/bookmark_jump.ts b/apps/client/src/services/bookmark_jump.tsindex b7ce68827d..92a43377af 100644--- a/apps/client/src/services/bookmark_jump.ts+++ b/apps/client/src/services/bookmark_jump.ts@@ -6,18 +6,17 @@ import type { ViewScope } from "./link.js";* content container: expands any closed collapsible ancestor of the target, scrolls to it,* and clears the bookmark so it fires only once (mirrors `consumeSearchTerms`).*- * When `container` is null/undefined the bookmark is left untouched — the content is not- * rendered yet, and a later call (after the content commit) must still find it. A bookmark- * whose anchor does not exist in the content is consumed without scrolling, so a dangling- * id does not re-fire on every content reload.+ * A null `container` leaves the bookmark untouched, because the content is not rendered yet and+ * the call that follows the content commit must still find it. An anchor that does not exist in+ * the content is consumed without scrolling, so a dangling id does not re-fire on every reload.*/export function consumeBookmark(container: ParentNode | null | undefined, viewScope: ViewScope | null | undefined) {if (!viewScope?.bookmark || !container) {return;}- // Exact id comparison instead of an interpolated attribute selector — bookmark names are- // user text and may contain quotes/brackets that break CSS selector parsing.+ // Exact id comparison rather than an interpolated attribute selector, because bookmark names+ // are user text and can contain quotes or brackets that break CSS selector parsing.const bookmark = viewScope.bookmark;const el = [...container.querySelectorAll("[id]")].find((candidate) => candidate.id === bookmark);if (el) {diff --git a/apps/client/src/services/search_jump.spec.ts b/apps/client/src/services/search_jump.spec.tsindex c3c8cc2c79..7098bce1b8 100644--- a/apps/client/src/services/search_jump.spec.ts+++ b/apps/client/src/services/search_jump.spec.ts@@ -92,7 +92,7 @@ describe("consumeSearchTerms", () => {expect(triggerCommand).toHaveBeenCalledTimes(1);// Simulates the belt-and-suspenders double trigger (content-ready effect + noteSwitched- // listener) — the terms are gone, so nothing fires again.+ // listener). The terms are gone, so nothing fires again.consumeSearchTerms(ctx, "ntx1");flushRaf();expect(triggerCommand).toHaveBeenCalledTimes(1);diff --git a/apps/client/src/widgets/collections/search/SearchResultCard.tsx b/apps/client/src/widgets/collections/search/SearchResultCard.tsxindex cb42458690..3a1d2ca7b2 100644--- a/apps/client/src/widgets/collections/search/SearchResultCard.tsx+++ b/apps/client/src/widgets/collections/search/SearchResultCard.tsx@@ -33,9 +33,9 @@ export default function SearchResultCard({ noteId, details, loading, highlightedconst 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`- // spans) doesn't fight Preact's reconciliation of a controlled text child — the same reason- // NoteLink renders its title imperatively.+ // Set the title text imperatively so mark.js, which injects `.ck-find-result` spans into the+ // DOM, does not fight Preact's reconciliation of a controlled text child. NoteLink renders its+ // title imperatively for the same reason.const titleRef = useRef<HTMLSpanElement>(null);const highlightTitle = useImperativeSearchHighlighlighting(highlightedTokens);useEffect(() => {diff --git a/apps/client/src/widgets/collections/search/SearchResultsList.spec.tsx b/apps/client/src/widgets/collections/search/SearchResultsList.spec.tsxindex 45203f2f25..9d9ba254cb 100644--- a/apps/client/src/widgets/collections/search/SearchResultsList.spec.tsx+++ b/apps/client/src/widgets/collections/search/SearchResultsList.spec.tsx@@ -14,7 +14,7 @@ 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.+// 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)}));diff --git a/apps/client/src/widgets/collections/search/useSearchResultDetails.ts b/apps/client/src/widgets/collections/search/useSearchResultDetails.tsindex 8f33f03bcb..889ec642d1 100644--- a/apps/client/src/widgets/collections/search/useSearchResultDetails.ts+++ b/apps/client/src/widgets/collections/search/useSearchResultDetails.ts@@ -19,7 +19,7 @@ export interface SearchResultDetailsState {* 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+ * incrementing sequence ref guards against a stale response clobbering a newer one, the same* pattern `useNoteIds` uses for its own refreshes.*/export function useSearchResultDetails(diff --git a/apps/client/src/widgets/find_in_html.spec.ts b/apps/client/src/widgets/find_in_html.spec.tsindex bf8d16364b..e3aa2da308 100644--- a/apps/client/src/widgets/find_in_html.spec.ts+++ b/apps/client/src/widgets/find_in_html.spec.ts@@ -47,7 +47,7 @@ describe("FindInHtml", () => {await finder.performFind("alpha", false, false);await finder.highlightExtraTokens([ "beta", "gamma" ]);- // Seed count is unaffected — Enter/F3 still cycles only the primary matches.+ // Seed count is unaffected: Enter/F3 still cycles only the primary matches.expect(container.querySelectorAll(".ck-find-result").length).toBe(1);expect(container.querySelectorAll(".find-result-secondary").length).toBe(2);});@@ -84,7 +84,7 @@ describe("FindInHtml", () => {await finder.performFind("value", false, false);await finder.highlightExtraTokens([ "a.c", "a+c" ]);- // Literal matches only — no regex injection (both literal tokens exist once each).+ // Literal matches only, no regex injection (both literal tokens exist once each).const secondary = Array.from(container.querySelectorAll(".find-result-secondary")).map((el) => el.textContent);expect(secondary).toContain("a.c");expect(secondary).toContain("a+c");diff --git a/apps/client/src/widgets/find_in_html.ts b/apps/client/src/widgets/find_in_html.tsindex b10735f961..fd4163ab0a 100644--- a/apps/client/src/widgets/find_in_html.ts+++ b/apps/client/src/widgets/find_in_html.ts@@ -88,10 +88,9 @@ export default class FindInHtml {* only the primary (seed) matches counted by {@link performFind}.** Only this read-only HTML handler supports the multi-token pass; the editable CKEditor and- * CodeMirror handlers stay seed-only (their find engines highlight a single term). These marks- * reuse the same mark.js instance created by {@link performFind}, so {@link findBoxClosed}'s- * `unmark()` — and any subsequent manual re-search's `unmark()` — clears them too. mark.js- * escapes each keyword internally, so regex metacharacters in a token can't inject.+ * CodeMirror handlers stay seed-only, because their find engines highlight a single term. These+ * marks reuse the mark.js instance created by {@link performFind}, so any later `unmark()`+ * clears them too. mark.js escapes each keyword, so a regex metacharacter cannot inject.*/async highlightExtraTokens(tokens: string[]) {const mark = this.mark;diff --git a/apps/client/src/widgets/react/hooks.tsx b/apps/client/src/widgets/react/hooks.tsxindex 62d4b2fcc5..4ac5e40cec 100644--- a/apps/client/src/widgets/react/hooks.tsx+++ b/apps/client/src/widgets/react/hooks.tsx@@ -1490,8 +1490,8 @@ export function useImperativeSearchHighlighlighting(});}- // Reveal matches that landed inside collapsed <details> blocks — they are highlighted- // in the DOM but hidden until the block is expanded.+ // Reveal matches that landed inside collapsed <details> blocks, which are highlighted in+ // the DOM but hidden until the block is expanded.el.querySelectorAll<HTMLElement>(".ck-find-result").forEach(expandAncestorDetails);};}diff --git a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.spec.tsx b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.spec.tsxindex 5e61997fd6..94001ff9d9 100644--- a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.spec.tsx+++ b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.spec.tsx@@ -9,7 +9,7 @@* (which carries the saving component's id) is misclassified as a foreign change. The* hidden widget then refetches the whole blob after every save and publishes* `contentLoad: "loading"` to the shared note context, which makes the note-detail- * loading overlay cover the visible editor — the content "disappears and reappears"+ * loading overlay cover the visible editor, so the content "disappears and reappears"* while typing.** These tests assert the *correct* behavior, so they are red while the bug exists and@@ -134,7 +134,7 @@ describe("ReadOnlyText reacting to content changes (#10575)", () => {// save carries the shared parent component's id.await harness.fireContentChange(harness.parent.componentId);- // The change originated here — refetching the whole blob is pure waste...+ // The change originated here, so refetching the whole blob is pure waste...expect(harness.getBlobSpy).toHaveBeenCalledTimes(1);// ...and publishing "loading" makes the note-detail overlay cover the editor mid-typing.expect(harness.contentLoadStates).toEqual([]);@@ -223,7 +223,7 @@ describe("ReadOnlyText ?bookmark= handling", () => {);});- // The mount effect ran against an empty container — it must not consume the bookmark+ // The mount effect ran against an empty container, so it must not consume the bookmark// yet, or the post-load pass has nothing left to reveal.expect(noteContext.viewScope?.bookmark).toBe("deep-anchor");diff --git a/packages/trilium-core/src/services/search/docs_examples.spec.ts b/packages/trilium-core/src/services/search/docs_examples.spec.tsindex 6056179ea0..d6ff8f978d 100644--- a/packages/trilium-core/src/services/search/docs_examples.spec.ts+++ b/packages/trilium-core/src/services/search/docs_examples.spec.ts@@ -10,7 +10,7 @@* docs/User Guide/User Guide/Basic Concepts and Features/Navigation/Quick search.md** When adding a docs example, add its test here first (TDD). If a documented- * claim does not hold, DO NOT bend the doc or the test — the engine is the+ * claim does not hold, DO NOT bend the doc or the test. The engine is the* authority and the mismatch is a bug to report.*/import { describe, it, expect, beforeEach } from "vitest";@@ -61,8 +61,8 @@ describe("Search documentation examples", () => {return results.findIndex((result) => result.noteId === noteId);}- describe('Default matching — no prefix: substring + fuzzy, relevance-ranked', () => {- // Docs: Search.md § "The three matching modes" — default mode example+ describe('Default matching (no prefix): substring + fuzzy, relevance-ranked', () => {+ // Docs: Search.md § "The three matching modes", default mode exampleit("`sync` finds the substring `synchronize`, but ranks the exact word `sync` higher", () => {const exactWord = contentNote("Guide", "please sync the folders");const substring = contentNote("Manual", "synchronize the database now");@@ -76,8 +76,8 @@ describe("Search documentation examples", () => {});});- describe('Exact match prefix (=) — whole word / phrase, punctuation-insensitive, no fuzzy/substring', () => {- // Docs: Search.md § "Exact match prefix (=)" — example 1+ describe('Exact match prefix (=): whole word / phrase, punctuation-insensitive, no fuzzy/substring', () => {+ // Docs: Search.md § "Exact match prefix (=)", example 1it("`=sync` matches the whole word even wrapped in punctuation; not a substring, not a typo", () => {const paren = contentNote("Paren", "see (sync) mode");const comma = contentNote("Comma", "in sync, then continue");@@ -97,7 +97,7 @@ describe("Search documentation examples", () => {expect(results.length).toEqual(3);});- // Docs: Search.md § "Exact match prefix (=)" — example 3 (quoted phrase)+ // Docs: Search.md § "Exact match prefix (=)", example 3 (quoted phrase)it('`="project plan"` matches the exact phrase in title or content, including across punctuation', () => {const titlePhrase = contentNote("Project Plan", "");const bodyPhrase = contentNote("Roadmap", "the (project plan) is ready to share");@@ -113,7 +113,7 @@ describe("Search documentation examples", () => {});});- describe('Attribute / property equality (=, !=) — strict full-value, case/diacritic-insensitive', () => {+ describe('Attribute / property equality (=, !=): strict full-value, case/diacritic-insensitive', () => {function buildCapitals() {const austria = note("Austria").label("capital", "Vienna");const somewhere = note("Somewhere").label("capital", "Vienna Austria");@@ -122,7 +122,7 @@ describe("Search documentation examples", () => {rootNote.child(austria).child(somewhere).child(czech).child(swiss);}- // Docs: Search.md § "Attribute and property equality" — example 4+ // Docs: Search.md § "Attribute and property equality", example 4it("`#capital=Vienna` matches the whole value `Vienna`, but NOT `Vienna Austria`", () => {buildCapitals();@@ -133,7 +133,7 @@ describe("Search documentation examples", () => {expect(results.length).toEqual(1);});- // Docs: Search.md § "Attribute and property equality" — example 4 (quoted full value)+ // Docs: Search.md § "Attribute and property equality", example 4 (quoted full value)it('`#capital="Vienna Austria"` matches the full multi-word value', () => {buildCapitals();@@ -144,7 +144,7 @@ describe("Search documentation examples", () => {expect(results.length).toEqual(1);});- // Docs: Search.md § "Attribute and property equality" — example 4 (inversion)+ // Docs: Search.md § "Attribute and property equality", example 4 (inversion)it("`#capital!=Vienna` inverts the equality: every capital label except `Vienna`", () => {buildCapitals();@@ -157,7 +157,7 @@ describe("Search documentation examples", () => {expect(results.length).toEqual(3);});- // Docs: Search.md § "Attribute and property equality" — example 4 (diacritic-insensitive)+ // Docs: Search.md § "Attribute and property equality", example 4 (diacritic-insensitive)it("`#capital=Zurich` matches the diacritic value `Zürich` (equality is diacritic-insensitive)", () => {buildCapitals();@@ -167,7 +167,7 @@ describe("Search documentation examples", () => {expect(results.length).toEqual(1);});- // Docs: Search.md § "Attribute and property equality" — quick-search caveat.+ // Docs: Search.md § "Attribute and property equality", quick-search caveat.// Quick search / autocomplete run with fuzzyAttributeSearch, which rewrites attribute `=`// to `*=*` (contains); the same `#capital=Vienna` that is strict in full search also// matches the substring value `Vienna Austria` there.@@ -185,7 +185,7 @@ describe("Search documentation examples", () => {});describe('Fuzzy operators (~= fuzzy-equals, ~* fuzzy-contains)', () => {- // Docs: Search.md § "Fuzzy operators" — example 5+ // Docs: Search.md § "Fuzzy operators", example 5it("`note.title ~= boks` finds title `Books`; `#author ~= tolkein` finds label value `tolkien`", () => {const books = note("Books").label("author", "Tolkien");rootNote.child(books);@@ -196,7 +196,7 @@ describe("Search documentation examples", () => {expect(findNoteByTitle(search("#author ~= tolkein"), "Books")).toBeTruthy();});- // Docs: Search.md § "Fuzzy operators" — example 6+ // Docs: Search.md § "Fuzzy operators", example 6it("`note.content ~* progr` and `~* programing` both find content `programming`", () => {const prog = contentNote("Prog", "learn programming today");@@ -207,23 +207,23 @@ describe("Search documentation examples", () => {});});- describe('Fuzzy tolerance (AUTO) — token length decides allowed edits', () => {- // Docs: Search.md § "Fuzzy tolerance (AUTO)" — length-3-to-5 tier (1 edit)- it("`cat` (length 3) finds `car` — one edit is allowed for 3-5 character tokens", () => {+ describe('Fuzzy tolerance (AUTO): token length decides allowed edits', () => {+ // Docs: Search.md § "Fuzzy tolerance (AUTO)", length-3-to-5 tier (1 edit)+ it("`cat` (length 3) finds `car`: one edit is allowed for 3-5 character tokens", () => {const car = contentNote("Vehicle", "a bright red car");expect(rank(search("cat"), car.noteId)).toBeGreaterThanOrEqual(0);});- // Docs: Search.md § "Fuzzy tolerance (AUTO)" — length-3-to-5 tier rejects 2 edits- it("`ceck` (length 4) does NOT find `tech` — two edits exceed the 1-edit budget", () => {+ // Docs: Search.md § "Fuzzy tolerance (AUTO)", length-3-to-5 tier rejects 2 edits+ it("`ceck` (length 4) does NOT find `tech`: two edits exceed the 1-edit budget", () => {const tech = contentNote("News", "the latest tech trends");expect(rank(search("ceck"), tech.noteId)).toEqual(-1);});- // Docs: Search.md § "Fuzzy tolerance (AUTO)" — length-6+ tier (2 edits)- it("`combinef` (length 8) finds `combined` — two edits are allowed for 6+ character tokens", () => {+ // Docs: Search.md § "Fuzzy tolerance (AUTO)", length-6+ tier (2 edits)+ it("`combinef` (length 8) finds `combined`: two edits are allowed for 6+ character tokens", () => {const combined = contentNote("Build", "the values were combined together");expect(rank(search("combinef"), combined.noteId)).toBeGreaterThanOrEqual(0);@@ -231,7 +231,7 @@ describe("Search documentation examples", () => {});describe('Phrase and proximity ranking', () => {- // Docs: Search.md § "Relevance ranking" — example 8+ // Docs: Search.md § "Relevance ranking", example 8it("`you and me` ranks the exact phrase above scattered words", () => {const phrase = contentNote("Alpha", "I like you and me as a phrase");const scattered = contentNote("Beta", "the menu is here and you know it");@@ -247,8 +247,8 @@ describe("Search documentation examples", () => {});});- describe('Link and reference indexing — reference-link target titles are searchable', () => {- // Docs: Search.md § "What is searchable" — example 9+ describe('Link and reference indexing: reference-link target titles are searchable', () => {+ // Docs: Search.md § "What is searchable", example 9it("a note that only reference-links to `Special Topic` is found by `special topic`; the target ranks first", () => {const target = contentNote("Special Topic", "");const linker = contentNote(@@ -267,7 +267,7 @@ describe("Search documentation examples", () => {expect(targetRank).toBeLessThan(linkerRank);});- // Docs: Search.md § "What is searchable" — example 9 (single word)+ // Docs: Search.md § "What is searchable", example 9 (single word)it("a single word `special` from the target's title still finds the reference-linking note", () => {const target = contentNote("Special Topic", "");const linker = contentNote(@@ -281,7 +281,7 @@ describe("Search documentation examples", () => {expect(rank(results, linker.noteId)).toBeGreaterThanOrEqual(0);});- // Docs: Search.md § "What is searchable" — example 9 (diacritic-insensitive)+ // Docs: Search.md § "What is searchable", example 9 (diacritic-insensitive)it("`zurich` finds a note reference-linking to a note titled `Zürich` (diacritics normalized)", () => {const target = contentNote("Zürich", "");const linker = contentNote(@@ -295,8 +295,8 @@ describe("Search documentation examples", () => {});});- describe('Diacritics — normalization strips accents on both sides', () => {- // Docs: Search.md § "Diacritics" — example 10+ describe('Diacritics: normalization strips accents on both sides', () => {+ // Docs: Search.md § "Diacritics", example 10it("`ktory` finds `ktorý`, and `ktorý` finds `ktory`", () => {const accented = contentNote("Slovak", "slovo ktorý znamena nieco");const plain = contentNote("Plain", "the word ktory appears here");@@ -307,7 +307,7 @@ describe("Search documentation examples", () => {});describe('Regular expressions (%=)', () => {- // Docs: Search.md § "Regular expressions" — example 11+ // Docs: Search.md § "Regular expressions", example 11it("`note.content %= 'colou?r'` finds both `color` and `colour`", () => {const us = contentNote("US spelling", "my favorite color of all");const uk = contentNote("UK spelling", "my favourite colour of all");@@ -323,11 +323,11 @@ describe("Search documentation examples", () => {// ------------------------------------------------------------------// Legacy reference examples (pre-existing docs sections). Each of the// example strings already present in Search.md is validated here so the- // whole document — not only the newly-authored sections — is covered.+ // whole document is covered, not only the newly-authored sections.// ------------------------------------------------------------------describe('Legacy: Simple Note Search Examples', () => {- // Docs: Search.md § "Simple Note Search Examples" — `rings tolkien`+ // Docs: Search.md § "Simple Note Search Examples", `rings tolkien`it("`rings tolkien` finds a note containing both words, not one with only `rings`", () => {contentNote("Both", "the rings by tolkien are legendary");contentNote("OnlyRings", "the rings saga continues");@@ -339,7 +339,7 @@ describe("Search documentation examples", () => {expect(results.length).toEqual(1);});- // Docs: Search.md § "Simple Note Search Examples" — `"The Lord of the Rings" Tolkien`+ // Docs: Search.md § "Simple Note Search Examples", `"The Lord of the Rings" Tolkien`it('`"The Lord of the Rings" Tolkien` requires the exact phrase plus the word', () => {contentNote("Book", "The Lord of the Rings was written by Tolkien");contentNote("Scrambled", "the rings lord of the tolkien mixed up");@@ -351,7 +351,7 @@ describe("Search documentation examples", () => {expect(results.length).toEqual(1);});- // Docs: Search.md § "Simple Note Search Examples" — `note.content *=* rings OR note.content *=* tolkien`+ // Docs: Search.md § "Simple Note Search Examples", `note.content *=* rings OR note.content *=* tolkien`it("`note.content *=* rings OR note.content *=* tolkien` matches either substring", () => {contentNote("RingsOnly", "many rings here");contentNote("TolkienOnly", "written by tolkien");@@ -365,7 +365,7 @@ describe("Search documentation examples", () => {expect(results.length).toEqual(2);});- // Docs: Search.md § "Simple Note Search Examples" — `towers #book`, `towers #book or #author`, `towers #!book`+ // Docs: Search.md § "Simple Note Search Examples", `towers #book`, `towers #book or #author`, `towers #!book`it("combines full-text `towers` with label filters `#book`, `#book or #author`, `#!book`", () => {rootNote.child(note("Two Towers").label("book"))@@ -393,7 +393,7 @@ describe("Search documentation examples", () => {expect(results.length).toEqual(2);});- // Docs: Search.md § "Simple Note Search Examples" — `#book #publicationYear = 1954`,+ // Docs: Search.md § "Simple Note Search Examples", `#book #publicationYear = 1954`,// `#book #publicationYear >= 1950 #publicationYear < 1960`, `#publicationYear %= '19[0-9]{2}'`it("filters by exact, numeric-range and regex label values on `publicationYear`", () => {rootNote@@ -421,7 +421,7 @@ describe("Search documentation examples", () => {expect(results.length).toEqual(3);});- // Docs: Search.md § "Simple Note Search Examples" — `#genre *=* fan`+ // Docs: Search.md § "Simple Note Search Examples", `#genre *=* fan`it("`#genre *=* fan` matches a label value containing the substring `fan`", () => {rootNote.child(note("Fantasy Novel").label("genre", "fantasy"))@@ -434,7 +434,7 @@ describe("Search documentation examples", () => {expect(results.length).toEqual(1);});- // Docs: Search.md § "Simple Note Search Examples" — `#dateNote >= TODAY-30`+ // Docs: Search.md § "Simple Note Search Examples", `#dateNote >= TODAY-30`it("`#dateNote >= TODAY-30` matches a recent date but not an old one (smart date)", () => {rootNote.child(note("Recent").label("dateNote", dateUtils.localNowDate()))@@ -447,7 +447,7 @@ describe("Search documentation examples", () => {expect(results.length).toEqual(1);});- // Docs: Search.md § "Simple Note Search Examples" — `~author.title *=* Tolkien`+ // Docs: Search.md § "Simple Note Search Examples", `~author.title *=* Tolkien`it("`~author.title *=* Tolkien` matches via the related author note's title", () => {const tolkien = note("J. R. R. Tolkien");const herbert = note("Frank Herbert");@@ -464,7 +464,7 @@ describe("Search documentation examples", () => {expect(results.length).toEqual(1);});- // Docs: Search.md § "Simple Note Search Examples" — `note.content %= '\d{2}:\d{2} (PM|AM)'`+ // Docs: Search.md § "Simple Note Search Examples", `note.content %= '\d{2}:\d{2} (PM|AM)'`// NOTE: the docs render the backslashes as `\\d` (a literal backslash must be// escaped in the query); in JS source that literal `\\` is written `\\\\`.it("`note.content %= '\\\\d{2}:\\\\d{2} (PM|AM)'` matches note content mentioning a time", () => {@@ -480,7 +480,7 @@ describe("Search documentation examples", () => {});describe('Legacy: Advanced Use Cases', () => {- // Docs: Search.md § "Advanced Use Cases" — `~author.relations.son.title = 'Christopher Tolkien'`+ // Docs: Search.md § "Advanced Use Cases", `~author.relations.son.title = 'Christopher Tolkien'`it("`~author.relations.son.title = 'Christopher Tolkien'` traverses two relation hops", () => {const christopher = note("Christopher Tolkien");const brian = note("Brian Herbert");@@ -501,7 +501,7 @@ describe("Search documentation examples", () => {expect(results.length).toEqual(1);});- // Docs: Search.md § "Advanced Use Cases" — boolean expression with grouping parentheses+ // Docs: Search.md § "Advanced Use Cases", boolean expression with grouping parenthesesit("`~author.title *= Tolkien OR (#publicationDate >= 1954 AND #publicationDate <= 1960)` groups clauses", () => {const tolkien = note("J. R. R. Tolkien");rootNote@@ -518,7 +518,7 @@ describe("Search documentation examples", () => {expect(results.length).toEqual(2);});- // Docs: Search.md § "Advanced Use Cases" — `note.parents.title`, `note.parents.parents.title`, `note.ancestors.title`+ // Docs: Search.md § "Advanced Use Cases", `note.parents.title`, `note.parents.parents.title`, `note.ancestors.title`it("filters by parent, grandparent and ancestor title against a `Books` subtree", () => {const lotr = note("Lord of the Rings");const fiction = note("Fiction").child(lotr);@@ -535,7 +535,7 @@ describe("Search documentation examples", () => {expect(findNoteByTitle(results, "Lord of the Rings")).toBeTruthy();expect(results.length).toEqual(1);- // any ancestor named Books — note the filter is subtree-inclusive: it+ // any ancestor named Books. The filter is subtree-inclusive: it// returns the "Books" note itself as well as its descendants.results = search("note.ancestors.title = 'Books'");expect(findNoteByTitle(results, "Fiction")).toBeTruthy();@@ -545,7 +545,7 @@ describe("Search documentation examples", () => {expect(results.length).toEqual(3);});- // Docs: Search.md § "Advanced Use Cases" — `note.children.title = 'sub-note'`+ // Docs: Search.md § "Advanced Use Cases", `note.children.title = 'sub-note'`it("`note.children.title = 'sub-note'` matches a note that has such a child", () => {rootNote.child(note("Parent Note").child(note("sub-note")))@@ -560,7 +560,7 @@ describe("Search documentation examples", () => {});describe('Legacy: Note Properties', () => {- // Docs: Search.md § "Search with Note Properties" — `note.type = code AND note.mime = 'application/json'`+ // Docs: Search.md § "Search with Note Properties", `note.type = code AND note.mime = 'application/json'`it("`note.type = code AND note.mime = 'application/json'` filters by type and mime", () => {rootNote.child(note("Config", { type: "code", mime: "application/json" }))@@ -577,7 +577,7 @@ describe("Search documentation examples", () => {});describe('Legacy: Order by and Limit', () => {- // Docs: Search.md § "Order by and Limit" — `#author=Tolkien orderBy #publicationDate desc, note.title limit 10`+ // Docs: Search.md § "Order by and Limit", `#author=Tolkien orderBy #publicationDate desc, note.title limit 10`it("orders by publication date descending with a title tie-breaker, limited", () => {rootNote.child(note("The Hobbit").label("author", "Tolkien").label("publicationDate", "1937"))@@ -597,7 +597,7 @@ describe("Search documentation examples", () => {});describe('Legacy: Negation', () => {- // Docs: Search.md § "Negation" — `#book AND not(note.ancestors.title = 'Tolkien')`+ // Docs: Search.md § "Negation", `#book AND not(note.ancestors.title = 'Tolkien')`// NOTE: the docs previously wrote the singular `note.ancestor.title`, which is an// unrecognized property specifier and returns garbage; corrected to the plural// `note.ancestors.title` (see task report).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 ef0c68c49b..073f9fd335 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@@ -211,9 +211,8 @@ class NoteContentFulltextExp extends Expression {}// For flatText, also check if the phrase appears in attribute values.- // Attributes in flatText appear as "#name=value" or "~name=value", so we- // look for "=phrase" against the raw string — this depends on the- // #name=value structure and must stay a raw-string scan.+ // Attributes in flatText appear as "#name=value" or "~name=value", so this looks for+ // "=phrase" against the raw string and must stay a raw-string scan.if (checkFlatTextAttributes && normalizedContent.includes(`=${phrase}`)) {return true;}@@ -271,8 +270,8 @@ class NoteContentFulltextExp extends Expression {});} else if (!negation) {// Record how well the content matched so scoring can rank body matches.- // Negation (!=) matches are added because content does NOT contain the- // query — there is no positive content match to record.+ // A negation (!=) match means the content does not contain the query, so there is+ // no positive content match to record for it.this.recordContentMatchQuality(noteId, content, searchContext);}}diff --git a/packages/trilium-core/src/services/search/match_quality.ts b/packages/trilium-core/src/services/search/match_quality.tsindex 31cd090fa7..bfbe01c7ba 100644--- a/packages/trilium-core/src/services/search/match_quality.ts+++ b/packages/trilium-core/src/services/search/match_quality.ts@@ -52,10 +52,9 @@ export function betterQuality(a: ContentMatchQuality, b: ContentMatchQuality): C* already-tokenized content words, returning the best tier plus how many distinct* tokens matched (at any tier). Returns null when nothing matched.*- * This is a pure function: tokens and contentWords must already be normalized and- * tokenized (e.g. via {@link tokenizeIntoWords}) by the caller. It never computes- * edit distances — the "fuzzy" tier is recorded by callers when only fuzzy matching- * succeeded.+ * Pure: the caller must normalize and tokenize `tokens` and `contentWords` first, via+ * `tokenizeIntoWords()`. It never computes edit distances, so callers record the "fuzzy" tier+ * themselves when only fuzzy matching succeeded.*/export function classifyContentMatch(tokens: string[], contentWords: string[]): ContentMatchQuality | null {if (tokens.length === 0 || contentWords.length === 0) {@@ -71,14 +70,14 @@ export function classifyContentMatch(tokens: string[], contentWords: string[]):// Map each exact content word to its sorted positions for proximity/phrase checks.const wordPositions = new Map<string, number[]>();- contentWords.forEach((word, index) => {+ for (const [ index, word ] of contentWords.entries()) {const positions = wordPositions.get(word);if (positions) {positions.push(index);} else {wordPositions.set(word, [index]);}- });+ }let anyExact = false;let anyPrefix = false;@@ -137,11 +136,11 @@ export function classifyContentMatch(tokens: string[], contentWords: string[]):*/function withinProximityWindow(positionLists: number[][], maxSpan: number): boolean {const merged: { position: number; listIndex: number }[] = [];- positionLists.forEach((positions, listIndex) => {+ for (const [ listIndex, positions ] of positionLists.entries()) {for (const position of positions) {merged.push({ position, listIndex });}- });+ }merged.sort((a, b) => a.position - b.position);const need = positionLists.length;diff --git a/packages/trilium-core/src/services/search/search_result.spec.ts b/packages/trilium-core/src/services/search/search_result.spec.tsindex 14b1ce6795..c527003398 100644--- a/packages/trilium-core/src/services/search/search_result.spec.ts+++ b/packages/trilium-core/src/services/search/search_result.spec.ts@@ -157,7 +157,7 @@ describe("SearchResult", () => {rootNote.child(target);// "(sync)" tokenizes to the word "sync", so it must score as an exact- // token match — identical to an unwrapped "sync" chunk — rather than a+ // token match, identical to an unwrapped "sync" chunk, rather than a// weaker contains match.const wrapped = new SearchResult(["root", target.note.noteId]);wrapped.addScoreForStrings(["sync"], "(sync) notes", 1, false);diff --git a/packages/trilium-core/src/services/search/services/build_comparator.ts b/packages/trilium-core/src/services/search/services/build_comparator.tsindex e1838d0b79..b36ec36034 100644--- a/packages/trilium-core/src/services/search/services/build_comparator.ts+++ b/packages/trilium-core/src/services/search/services/build_comparator.ts@@ -13,10 +13,10 @@ function getRegex(str: string) {type Comparator<T> = (comparedValue: T) => (val: string) => boolean;const stringComparators: Record<string, Comparator<string>> = {- // Strict normalized full-value equality: the whole value must equal the whole- // compared value (case- and diacritic-insensitive). This is the documented- // label-equality semantics — e.g. #capital=Vienna matches "vienna" but NOT- // "Vienna Austria". Word/phrase matching lives in the internal "word=" operator.+ // Strict normalized full-value equality: the whole value must equal the whole compared value,+ // ignoring case and diacritics. This is the documented label-equality semantics, so+ // #capital=Vienna matches "vienna" but not "Vienna Austria". Word and phrase matching lives+ // in the internal "word=" operator."=": (comparedValue) => (val) => normalizeSearchText(val) === normalizeSearchText(comparedValue),"!=": (comparedValue) => (val) => normalizeSearchText(val) !== normalizeSearchText(comparedValue),// Internal operator (not user-typable): word/phrase match used by the leading-"="diff --git a/packages/trilium-core/src/services/search/services/progressive_search.spec.ts b/packages/trilium-core/src/services/search/services/progressive_search.spec.tsindex ba5c5080af..c2e2cada87 100644--- a/packages/trilium-core/src/services/search/services/progressive_search.spec.ts+++ b/packages/trilium-core/src/services/search/services/progressive_search.spec.ts@@ -256,7 +256,7 @@ describe("Progressive Search Strategy", () => {for (let i = 0; i < 5; i++) {contentNote(`Note ${i}`, `this document section ${i}`);}- // Body typo of "document" — reachable only via the phase-2 fuzzy fallback.+ // Body typo of "document", reachable only via the phase-2 fuzzy fallback.const typo = contentNote("Typo", "this documnt section");const searchResults = searchService.findResultsWithQuery("document", new SearchContext());diff --git a/packages/trilium-core/src/services/search/services/search.spec.ts b/packages/trilium-core/src/services/search/services/search.spec.tsindex f157b45aa9..492140f95a 100644--- a/packages/trilium-core/src/services/search/services/search.spec.ts+++ b/packages/trilium-core/src/services/search/services/search.spec.ts@@ -395,7 +395,7 @@ describe("Search", () => {it("exact word search matches a content word wrapped in punctuation (#10616)", () => {// The note body contains "(sync)" (parenthesised). Exact-word search for- // "sync" must still find it — content tokenization strips boundary+ // "sync" must still find it, because content tokenization strips boundary// punctuation so "(sync)" tokenizes to the word "sync". The title// deliberately omits the word so the match comes from the body.const guide = getContext().init(() => noteService.createNewNote({@@ -729,7 +729,7 @@ describe("Search", () => {it("test attribute group AND-ed with a note property, then ordered", () => {// The shape the Content Manager builds when its filter box is used: an OR chain of attribute// filters grouped in parens, AND-ed with a title match, with `orderBy` still at top level.- // The title condition leads deliberately — a query *starting* with "(" is mis-lexed, since+ // The title condition leads deliberately: a query *starting* with "(" is mis-lexed, since// the paren is swallowed into the fulltext portion before any token ends it.const alpha = note("Alpha script").label("run", "hourly");const beta = note("Beta script").label("run", "daily");@@ -951,7 +951,7 @@ describe("Search", () => {it("finds a note by a SINGLE word from a reference-link's target title, as a phase-1 exact match", () => {// The injected title is normalized like the body, so a single lowercased query token- // hits it via the default *=* content includes() in phase 1 — not only via phase-2+ // hits it via the default *=* content includes() in phase 1, not only via phase-2// fuzzy (where it would rank last, or be dropped entirely once phase 1 is sufficient).const target = contentNote("Special Topic", "");const linker = contentNote("Linker", `<p>see <a class="reference-link" href="#root/${target.noteId}"></a></p>`);diff --git a/packages/trilium-core/src/services/search/utils/text_utils.spec.ts b/packages/trilium-core/src/services/search/utils/text_utils.spec.tsindex 9d55518181..5d998ea7e3 100644--- a/packages/trilium-core/src/services/search/utils/text_utils.spec.ts+++ b/packages/trilium-core/src/services/search/utils/text_utils.spec.ts@@ -54,7 +54,7 @@ describe('Fuzzy Search Core', () => {expect(fuzzyMatchWord('hello', 'helo')).toBe(true);// wrold/tset are transpositions (Levenshtein d=2). Under length-scaled// distance, <=5-char tokens only allow d=1, so these no longer match.- // (Old behavior allowed a flat d=2 for any length — too loose, #10616.)+ // (Old behavior allowed a flat d=2 for any length, which was too loose, #10616.)expect(fuzzyMatchWord('world', 'wrold')).toBe(false);expect(fuzzyMatchWord('test', 'tset')).toBe(false);expect(fuzzyMatchWord('test', 'xyz')).toBe(false);@@ -76,7 +76,7 @@ describe('Fuzzy Search Core', () => {});it('keeps connector/symbol chars and inner punctuation', () => {- // "+" is a math symbol (Sm), "_" is a connector (Pc) — both deliberately kept.+ // "+" is a math symbol (Sm), "_" is a connector (Pc); both are deliberately kept.expect(stripWordPunctuation('c++')).toBe('c++');expect(stripWordPunctuation('_private')).toBe('_private');// Inner apostrophe is preserved; only leading/trailing punctuation is stripped.diff --git a/packages/trilium-core/src/services/utils/index.ts b/packages/trilium-core/src/services/utils/index.tsindex 75ef0c7a35..f36b82c3bb 100644--- a/packages/trilium-core/src/services/utils/index.ts+++ b/packages/trilium-core/src/services/utils/index.ts@@ -89,11 +89,10 @@ export function normalize(str: string) {* snippet/highlight index math relies on: it finds match offsets on the normalized* text but inserts markers into (or slices) the original text at the same offsets.*- * Each character (Unicode code point) is transformed individually; when the- * transformed result is not the same code-unit length as the source character —- * a bare combining mark that would vanish, or (hypothetically) a ligature that- * would expand — the original character is kept instead. This trades perfect- * folding of already-decomposed content for a hard length invariant.+ * Each character (Unicode code point) is transformed individually, and the original character is+ * kept whenever the transformed result is a different code-unit length: a bare combining mark that+ * would vanish, or a ligature that would expand. This trades perfect folding of already-decomposed+ * content for a hard length invariant.*/export function normalizePreservingLength(str: string) {let result = "";