Skip to content

Build your personal knowledge base with Trilium Notes

Merge origin/main into feat/search-overhaul

perfectra1n1bfbf79b2a2a
diff --cc apps/client/src/services/bookmark_jump.ts
index da6bc2a5c5,0000000000..b7ce68827d
mode 100644,000000..100644
--- a/apps/client/src/services/bookmark_jump.ts
+++ b/apps/client/src/services/bookmark_jump.ts
@@@ -1,28 -1,0 +1,28 @@@
- import { expandCollapsedAncestors } from "./collapsibles.js";
++import { expandAncestorDetails } from "./collapsible.js";
+import type { ViewScope } from "./link.js";
+
+/**
+ * Consumes `viewScope.bookmark` (the `?bookmark=` link parameter) against a rendered note
+ * 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.
+ */
+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.
+ const bookmark = viewScope.bookmark;
+ const el = [...container.querySelectorAll("[id]")].find((candidate) => candidate.id === bookmark);
+ if (el) {
- expandCollapsedAncestors(el);
++ expandAncestorDetails(el);
+ el.scrollIntoView({ behavior: "smooth", block: "center" });
+ }
+ viewScope.bookmark = undefined;
+}
diff --cc apps/client/src/services/collapsible.spec.ts
index 0000000000,3a8f9c935d..58f0729d3d
mode 000000,100644..100644
--- a/apps/client/src/services/collapsible.spec.ts
+++ b/apps/client/src/services/collapsible.spec.ts
@@@ -1,0 -1,44 +1,67 @@@
+ import { describe, expect, it } from "vitest";
+ import { expandAncestorDetails } from "./collapsible.js";
+
+ /** Build a DOM tree from an HTML string and return the element matching `selector`. */
+ function mount(html: string, selector: string): HTMLElement {
+ const container = document.createElement("div");
+ container.innerHTML = html;
+ const el = container.querySelector<HTMLElement>(selector);
+ if (!el) {
+ throw new Error(`No element matched ${selector}`);
+ }
+ return el;
+ }
+
+ describe("expandAncestorDetails", () => {
+ it("opens a single collapsed ancestor", () => {
+ const match = mount(`<details><summary>t</summary><span class="m">hit</span></details>`, ".m");
+ expandAncestorDetails(match);
+ expect(match.closest("details")?.open).toBe(true);
+ });
+
+ it("opens every level of nested collapsed ancestors", () => {
+ const match = mount(`
+ <details class="outer"><summary>o</summary>
+ <details class="inner"><summary>i</summary><span class="m">hit</span></details>
+ </details>`, ".m");
+ expandAncestorDetails(match);
+ const outer = match.closest("details.outer");
+ const inner = match.closest("details.inner");
+ expect(outer instanceof HTMLDetailsElement && outer.open).toBe(true);
+ expect(inner instanceof HTMLDetailsElement && inner.open).toBe(true);
+ });
+
+ it("leaves an already-open ancestor open", () => {
+ const match = mount(`<details open><summary>t</summary><span class="m">hit</span></details>`, ".m");
+ expandAncestorDetails(match);
+ expect(match.closest("details")?.open).toBe(true);
+ });
+
+ it("is a no-op when there is no <details> ancestor", () => {
+ const match = mount(`<p><span class="m">hit</span></p>`, ".m");
+ expect(() => expandAncestorDetails(match)).not.toThrow();
+ });
++
++ it("opens only the closed ancestors in a mixed open/closed chain", () => {
++ const match = mount(`
++ <details class="outer"><summary>o</summary>
++ <details class="middle" open><summary>m</summary>
++ <details class="inner"><summary>i</summary><span class="m">hit</span></details>
++ </details>
++ </details>`, ".m");
++ expandAncestorDetails(match);
++ for (const cls of [ "outer", "middle", "inner" ]) {
++ const details = match.closest(`details.${cls}`);
++ expect(details instanceof HTMLDetailsElement && details.open).toBe(true);
++ }
++ });
++
++ it("expands the element itself when it is a closed <details>", () => {
++ const match = mount(`<details class="outer"><summary>o</summary><details class="m"><summary>i</summary>x</details></details>`, ".m");
++ expandAncestorDetails(match);
++ const self = match.closest("details.m");
++ const outer = match.closest("details.outer");
++ expect(self instanceof HTMLDetailsElement && self.open).toBe(true);
++ expect(outer instanceof HTMLDetailsElement && outer.open).toBe(true);
++ });
+ });
diff --cc apps/client/src/services/collapsible.ts
index 0000000000,2afb230120..7efbfeb2c1
mode 000000,100644..100644
--- a/apps/client/src/services/collapsible.ts
+++ b/apps/client/src/services/collapsible.ts
@@@ -1,0 -1,10 +1,10 @@@
+ /** Open every collapsed `<details>` ancestor of `el` so content inside it becomes visible. */
-export function expandAncestorDetails(el: HTMLElement) {
++export function expandAncestorDetails(el: Element) {
+ let details = el.closest("details");
+ while (details) {
+ if (!details.open) {
+ details.open = true;
+ }
+ details = details.parentElement?.closest("details") ?? null;
+ }
+ }
diff --cc apps/client/src/widgets/find_in_html.ts
index 3ba5b89203,1d71e22a3b..b10735f961
--- a/apps/client/src/widgets/find_in_html.ts
+++ b/apps/client/src/widgets/find_in_html.ts
@@@ -120,10 -86,9 +120,9 @@@ export default class FindInHtml
if (this.$results?.length) {
const $current = this.$results.eq(this.currentIndex);
this.$results.removeClass(FIND_RESULT_SELECTED_CSS_CLASSNAME);
- // Reveal the match if it's hidden inside a closed <details> (e.g. a collapsed
- // CKEditor collapsible block) before scrolling to it, otherwise scrollIntoView is a
- // no-op for content that isn't actually visible (#10616).
- expandCollapsedAncestors($current[0]);
+ // Reveal matches inside collapsed <details>, like native find-in-page.
- // Must precede scrollIntoView so the target is laid out first.
++ // Must precede scrollIntoView so the target is laid out first (#10616).
+ expandAncestorDetails($current[0]);
$current[0].scrollIntoView({ block: 'center', inline: 'center'});
$current.addClass(FIND_RESULT_SELECTED_CSS_CLASSNAME);
}
diff --cc apps/client/src/widgets/react/hooks.spec.tsx
index 035a2623ba,e22f496171..f5200b2688
--- a/apps/client/src/widgets/react/hooks.spec.tsx
+++ b/apps/client/src/widgets/react/hooks.spec.tsx
@@@ -142,64 -144,49 +142,80 @@@ describe("useImperativeSearchHighlighli
afterEach(() => {
render(null, container);
container.remove();
- highlight = undefined;
+ target.remove();
});
- async function mount(tokens: string[] | null | undefined) {
- await act(async () => render(<Probe tokens={tokens} />, container));
+ function Probe({ tokens, onReady }: {
+ tokens: (string | HighlightedTokenInfo)[] | null | undefined;
+ onReady: (fn: (el: HTMLElement | null | undefined) => void) => void;
+ }) {
+ const highlight = useImperativeSearchHighlighlighting(tokens);
+ onReady(highlight);
+ return null;
}
- function content(html: string): HTMLElement {
- const el = document.createElement("div");
- el.innerHTML = html;
- document.body.appendChild(el);
- return el;
+ /** Mounts a fresh hook instance (so each call gets its own `Mark` instance) and applies it to `target`. */
+ function highlight(tokens: (string | HighlightedTokenInfo)[] | null | undefined, html: string) {
+ target.innerHTML = html;
+ render(null, container);
+ let highlightFn: ((el: HTMLElement | null | undefined) => void) | undefined;
+ act(() => {
+ render(<Probe tokens={tokens} onReady={(fn) => { highlightFn = fn; }} />, container);
+ });
+ highlightFn?.(target);
+ return target;
}
- it("highlights matches and opens the collapsed <details> that contains them", async () => {
- await mount([ "needle" ]);
- const target = content("<details><summary>t</summary><p>a needle here</p></details>");
+ function markedTexts(el: HTMLElement) {
+ return Array.from(el.querySelectorAll("span.ck-find-result")).map((mark) => mark.textContent);
+ }
- highlight?.(target);
+ it("wraps a diacritic match when searching a plain, unaccented token (#10616)", () => {
+ const el = highlight(["ktory"], "<p>Aký ktorý</p>");
+ expect(markedTexts(el)).toEqual(["ktorý"]);
+ });
- expect(target.querySelectorAll(".ck-find-result").length).toBeGreaterThan(0);
- expect(target.querySelector("details")?.open).toBe(true);
- target.remove();
+ it("wraps a CJK substring match inside a larger word", () => {
+ const el = highlight(["笔记"], "<p>我的笔记本</p>");
+ expect(markedTexts(el)).toEqual(["笔记"]);
});
- it("leaves a collapsed block closed when it holds no match", async () => {
- await mount([ "needle" ]);
- const target = content("<details><summary>t</summary><p>nothing relevant</p></details>");
+ it("wraps every match of a regex-typed token (#5332)", () => {
+ const el = highlight([{ token: "ba.", type: "regex" }], "<p>foo bar baz qux</p>");
+ expect(markedTexts(el)).toEqual(["bar", "baz"]);
+ });
- highlight?.(target);
+ it("skips an invalid regex token without throwing", () => {
+ expect(() => highlight([{ token: "(unterminated", type: "regex" }], "<p>foo bar</p>")).not.toThrow();
+ expect(markedTexts(target)).toEqual([]);
+ });
- expect(target.querySelector("details")?.open).toBe(false);
- target.remove();
+ it("still highlights when given legacy string[] input", () => {
+ const el = highlight(["bar"], "<p>foo bar baz</p>");
+ expect(markedTexts(el)).toEqual(["bar"]);
});
- it("does nothing without tokens", async () => {
- await mount([]);
- const target = content("<details><summary>t</summary><p>needle</p></details>");
+ it("is a no-op for null or undefined tokens", () => {
+ expect(() => highlight(null, "<p>foo bar</p>")).not.toThrow();
+ expect(markedTexts(target)).toEqual([]);
- highlight?.(target);
+ expect(() => highlight(undefined, "<p>foo bar</p>")).not.toThrow();
+ expect(markedTexts(target)).toEqual([]);
+
- expect(target.querySelectorAll(".ck-find-result").length).toBe(0);
++ highlight([], "<details><summary>t</summary><p>needle</p></details>");
++ expect(markedTexts(target)).toEqual([]);
+ expect(target.querySelector("details")?.open).toBe(false);
- target.remove();
++ });
++
++ it("highlights matches and opens the collapsed <details> that contains them", () => {
++ const el = highlight(["needle"], "<details><summary>t</summary><p>a needle here</p></details>");
++ expect(markedTexts(el)).toEqual(["needle"]);
++ expect(el.querySelector("details")?.open).toBe(true);
++ });
++
++ it("leaves a collapsed block closed when it holds no match", () => {
++ const el = highlight(["needle"], "<details><summary>t</summary><p>nothing relevant</p></details>");
++ expect(markedTexts(el)).toEqual([]);
++ expect(el.querySelector("details")?.open).toBe(false);
});
});
diff --cc apps/client/src/widgets/react/hooks.tsx
index 8dfbd9c6b7,406443ac20..79d079a617
--- a/apps/client/src/widgets/react/hooks.tsx
+++ b/apps/client/src/widgets/react/hooks.tsx
@@@ -1256,42 -1258,15 +1287,46 @@@ export function useImperativeSearchHigh
}
mark.current.unmark();
- mark.current.markRegExp(highlightRegex, {
- element: "span",
- className: "ck-find-result",
- // Reveal matches that landed inside collapsed <details> blocks — they
- // are highlighted in the DOM but hidden until the block is expanded.
- done: () => {
- el.querySelectorAll<HTMLElement>(".ck-find-result").forEach(expandAncestorDetails);
+
+ const plainTokens = tokenInfos.filter((info) => info.type === "plain").map((info) => info.token);
+ if (plainTokens.length) {
+ // Term API (not markRegExp): its diacritics map lets an unaccented query like "ktory"
+ // (the server strips diacritics before indexing) still highlight "ktorý" (#10616).
+ // separateWordSearch: false keeps a multi-word token as one literal phrase; the default
+ // "partially" accuracy keeps plain substring matching, so CJK tokens without word
+ // boundaries (e.g. "笔记" inside "我的笔记本") keep working.
+ mark.current.mark(plainTokens, {
+ separateWordSearch: false,
+ diacritics: true,
+ caseSensitive: false,
+ element: "span",
+ className: "ck-find-result"
+ });
+ }
+
+ for (const info of tokenInfos) {
+ if (info.type !== "regex" || info.token.length > MAX_REGEX_TOKEN_LENGTH) continue;
+
+ let regex: RegExp;
+ try {
+ regex = new RegExp(info.token, "gi");
+ } catch {
+ // Invalid regex (e.g. from a malformed %= search) - skip rather than crash the render.
+ continue;
}
- });
+
+ mark.current.markRegExp(regex, {
+ element: "span",
+ className: "ck-find-result",
+ // markRegExp's filter is called as (node, match, totalCounter so far); returning
+ // false once the cap is hit stops further matches from being wrapped.
+ filter: (_node, _match, totalCounter) => totalCounter < MAX_REGEX_MATCHES
+ });
+ }
++
++ // Reveal matches that landed inside collapsed <details> blocks — they are highlighted
++ // in the DOM but hidden until the block is expanded.
++ el.querySelectorAll<HTMLElement>(".ck-find-result").forEach(expandAncestorDetails);
};
}
diff --cc apps/client/src/widgets/type_widgets/text/ReadOnlyText.spec.tsx
index 5415274b5d,e4638867d6..908a0dbc48
--- a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.spec.tsx
@@@ -1,87 -1,173 +1,232 @@@
+ /**
+ * Regression tests for https://github.com/TriliumNext/Trilium/issues/10575
+ * ("on bigger notes. The content of the note tends to 'refresh'").
+ *
+ * When a big text note opens in auto-read-only mode and the user temporarily enables
+ * editing, the `ReadOnlyText` widget stays mounted (hidden) behind the editor. It reads
+ * the note content via `useNoteBlob(note, undefined, { reportLoadStateTo: noteContext })`:
+ * because no componentId is passed, the WS echo of the user's *own* spaced-update save
+ * (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"
+ * while typing.
+ *
+ * These tests assert the *correct* behavior, so they are red while the bug exists and
+ * become the regression suite once it is fixed:
+ * - an entity change originating from the widget's own component must trigger neither
+ * a blob refetch nor a `contentLoad` publish;
+ * - a foreign change may refetch, but a hidden widget must never publish `contentLoad`
+ * (the overlay would cover the editor the user is typing into).
+ */
import { render } from "preact";
import { act } from "preact/test-utils";
- import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+ import { afterEach, describe, expect, it, vi } from "vitest";
- // Imported by ReadOnlyText only for its content styles — irrelevant (and heavy) under happy-dom.
- vi.mock("@triliumnext/ckeditor5", () => ({}));
- vi.mock("../../../services/content_renderer_text", () => ({
- applyInlineMermaid: vi.fn(async () => {}),
- rewriteMermaidDiagramsInContainer: vi.fn(async () => {})
- }));
- vi.mock("../../../services/link_embed", () => ({ applyLinkEmbeds: vi.fn(async () => {}) }));
- vi.mock("../../../services/math", () => ({ renderMathInElement: vi.fn() }));
- vi.mock("../../../services/syntax_highlight", () => ({ formatCodeBlocks: vi.fn(async () => {}) }));
- vi.mock("../../../services/search_jump", () => ({ consumeSearchTerms: vi.fn() }));
- vi.mock("./read_only_helper", () => ({ applyReferenceLinks: vi.fn(async () => {}) }));
- vi.mock("./utils", () => ({
- loadIncludedNote: vi.fn(async () => {}),
- refreshIncludedNote: vi.fn(),
- setupImageOpening: vi.fn()
- }));
-
- import type NoteContext from "../../../components/note_context";
- import type FNote from "../../../entities/fnote";
- import type { ViewScope } from "../../../services/link";
+ import Component from "../../../components/component";
+ import NoteContext from "../../../components/note_context";
+ import LoadResults from "../../../services/load_results";
+ import { buildNote } from "../../../test/easy-froca";
+ import { ParentComponent } from "../../react/react_utils";
import ReadOnlyText from "./ReadOnlyText";
- function makeNote(blobPromise: Promise<unknown>) {
- return {
- noteId: "note1",
- getBlob: () => blobPromise,
- getLabelValue: () => null
- } as unknown as FNote;
+ // Imported by ReadOnlyText only for its content styles; irrelevant (and heavy) in happy-dom.
+ vi.mock("@triliumnext/ckeditor5", () => ({}));
+
+ vi.stubGlobal("logError", vi.fn());
+ vi.stubGlobal("logInfo", vi.fn());
+
+ function setupHarness({ isVisible: initialIsVisible }: { isVisible: boolean }) {
+ const note = buildNote({ title: "Big note", type: "text", content: "<p>hello</p>" });
+
+ // Count blob fetches without changing what they resolve to.
+ const originalGetBlob = note.getBlob.bind(note);
+ const getBlobSpy = vi.fn(originalGetBlob);
+ note.getBlob = getBlobSpy;
+
+ const parent = new Component();
+ const noteContext = new NoteContext("ro-ntx");
+
+ // Record every contentLoad state published to the shared note context.
+ const contentLoadStates: string[] = [];
+ const originalSetContextData = noteContext.setContextData.bind(noteContext);
+ noteContext.setContextData = ((key, value) => {
+ if (key === "contentLoad" && value && typeof value === "object" && "state" in value) {
+ contentLoadStates.push(String(value.state));
+ }
+ return originalSetContextData(key, value);
+ }) as typeof noteContext.setContextData;
+
+ const container = document.createElement("div");
+ document.body.appendChild(container);
+
+ async function mount(isVisible = initialIsVisible) {
+ await act(async () => {
+ render(
+ <ParentComponent.Provider value={parent}>
+ <ReadOnlyText
+ note={note}
+ noteContext={noteContext}
+ ntxId={noteContext.ntxId}
+ parentComponent={parent}
+ viewScope={undefined}
+ isVisible={isVisible}
+ />
+ </ParentComponent.Provider>,
+ container
+ );
+ });
+ // The blob resolves on a microtask after the first effect flush; a second act
+ // cycle lets useNoteBlob's state update land and deliver the content.
+ await act(async () => {});
+ }
+
+ async function fireContentChange(componentId: string) {
+ const loadResults = new LoadResults([]);
+ loadResults.addNoteContent(note.noteId, componentId);
+ await act(async () => {
+ await parent.handleEvent("entitiesReloaded", { loadResults });
+ });
+ await act(async () => {});
+ }
+
+ return { note, parent, noteContext, contentLoadStates, getBlobSpy, container, mount, fireContentChange };
}
- describe("ReadOnlyText ?bookmark= handling", () => {
- let container: HTMLDivElement;
+ describe("ReadOnlyText reacting to content changes (#10575)", () => {
+ let cleanupContainer: HTMLElement | undefined;
- beforeEach(() => {
- Element.prototype.scrollIntoView = vi.fn();
- container = document.createElement("div");
- document.body.appendChild(container);
+ afterEach(() => {
+ if (cleanupContainer) {
+ render(null, cleanupContainer);
+ cleanupContainer.remove();
+ cleanupContainer = undefined;
+ }
+ });
+
+ it("loads and renders the content on mount, reporting the load state", async () => {
+ const harness = setupHarness({ isVisible: true });
+ cleanupContainer = harness.container;
+
+ await harness.mount();
+
+ expect(harness.container.textContent).toContain("hello");
+ expect(harness.getBlobSpy).toHaveBeenCalledTimes(1);
+ // The initial fetch is exactly what the loading overlay exists for.
+ expect(harness.contentLoadStates).toEqual([ "loading", "loaded" ]);
});
+ it("ignores the echo of a save made by its own component (no refetch, no overlay)", async () => {
+ const harness = setupHarness({ isVisible: false });
+ cleanupContainer = harness.container;
+
+ await harness.mount();
+ expect(harness.getBlobSpy).toHaveBeenCalledTimes(1); // sanity: initial load only
+
+ harness.contentLoadStates.length = 0;
+
+ // The user types into EditableText in the same split; the WS echo of the spaced-update
+ // 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...
+ expect(harness.getBlobSpy).toHaveBeenCalledTimes(1);
+ // ...and publishing "loading" makes the note-detail overlay cover the editor mid-typing.
+ expect(harness.contentLoadStates).toEqual([]);
+ });
+
+ it("does not publish a load state while hidden, even for foreign changes", async () => {
+ const harness = setupHarness({ isVisible: false });
+ cleanupContainer = harness.container;
+
+ await harness.mount();
+ harness.contentLoadStates.length = 0;
+
+ // A change from elsewhere (another split, another device via sync). A hidden widget
+ // may refresh its content, but it must not drive the shared loading overlay.
+ await harness.fireContentChange("ReactWrappedWidget-remote");
+
+ expect(harness.contentLoadStates).not.toContain("loading");
+ });
+
+ it("catches up on skipped own-component changes when displayed again, but only then", async () => {
+ const harness = setupHarness({ isVisible: false });
+ cleanupContainer = harness.container;
+
+ await harness.mount();
+ expect(harness.getBlobSpy).toHaveBeenCalledTimes(1);
+
+ // Becoming visible without having missed anything must not refetch (the user just
+ // toggles between read-only and editable without editing).
+ await harness.mount(true);
+ expect(harness.getBlobSpy).toHaveBeenCalledTimes(1);
+
+ // The user edits in the editable view (own-component echo while hidden)...
+ await harness.mount(false);
+ await harness.fireContentChange(harness.parent.componentId);
+ expect(harness.getBlobSpy).toHaveBeenCalledTimes(1); // still skipped
+
+ // ...and re-locks the note: the read-only view must not show stale content.
+ await harness.mount(true);
+ expect(harness.getBlobSpy).toHaveBeenCalledTimes(2);
+ });
+ });
++
++describe("ReadOnlyText ?bookmark= handling", () => {
++ let cleanupContainer: HTMLElement | undefined;
++
+ afterEach(() => {
- render(null, container);
- container.remove();
++ if (cleanupContainer) {
++ render(null, cleanupContainer);
++ cleanupContainer.remove();
++ cleanupContainer = undefined;
++ }
+ });
+
+ it("keeps the bookmark until the content renders, then expands the collapsible and consumes it", async () => {
- let resolveBlob!: (blob: unknown) => void;
- const note = makeNote(new Promise((resolve) => { resolveBlob = resolve; }));
- const viewScope: ViewScope = { bookmark: "deep-anchor" };
- const noteContext = {
- viewScope,
- setContextData: vi.fn()
- } as unknown as NoteContext;
++ Element.prototype.scrollIntoView = vi.fn();
++ const note = buildNote({
++ title: "Collapsible note",
++ type: "text",
++ content:
++ `<details class="trilium-collapsible"><summary>Hidden</summary>` +
++ `<p><a id="deep-anchor"></a>target</p></details>`
++ });
++ const parent = new Component();
++ const noteContext = new NoteContext("bm-ntx");
++ noteContext.viewScope = { bookmark: "deep-anchor" };
++
++ const container = document.createElement("div");
++ document.body.appendChild(container);
++ cleanupContainer = container;
+
++ // First act cycle only: the blob resolves on a microtask after the first effect flush
++ // (see setupHarness.mount), so this mounts with the content still loading.
+ await act(async () => {
+ render(
- <ReadOnlyText
- note={note}
- noteContext={noteContext}
- ntxId={null}
- viewScope={viewScope}
- parentComponent={undefined}
- />,
++ <ParentComponent.Provider value={parent}>
++ <ReadOnlyText
++ note={note}
++ noteContext={noteContext}
++ ntxId={noteContext.ntxId}
++ parentComponent={parent}
++ viewScope={noteContext.viewScope}
++ isVisible={true}
++ />
++ </ParentComponent.Provider>,
+ container
+ );
+ });
+
- // The mount effect runs while the blob is still loading (empty container) — it must not
- // consume the bookmark yet, or the post-load pass has nothing left to reveal.
- expect(viewScope.bookmark).toBe("deep-anchor");
++ // The mount effect ran against an empty container — it must not consume the bookmark
++ // yet, or the post-load pass has nothing left to reveal.
++ expect(noteContext.viewScope?.bookmark).toBe("deep-anchor");
+
- await act(async () => {
- resolveBlob({
- content:
- `<details class="trilium-collapsible"><summary>Hidden</summary>` +
- `<p><a id="deep-anchor"></a>target</p></details>`
- });
- });
++ // Second act cycle: the blob lands, the content commits, and the [blob] effect fires.
++ await act(async () => {});
+
+ const details = container.querySelector("details");
+ expect(details?.open).toBe(true);
- expect(viewScope.bookmark).toBeUndefined();
++ expect(noteContext.viewScope?.bookmark).toBeUndefined();
+ });
+});
diff --cc packages/trilium-core/src/services/search/services/search.spec.ts
index 6272c1beb8,db92d715b4..40cffa1c40
--- a/packages/trilium-core/src/services/search/services/search.spec.ts
+++ b/packages/trilium-core/src/services/search/services/search.spec.ts
@@@ -809,129 -769,26 +809,148 @@@ describe("Search", () =>
expect(lastExactIndex).toBeLessThan(firstFuzzyIndex);
});
+ describe("content-aware ranking (search-overhaul)", () => {
+ function contentNote(title: string, content: string) {
+ return getContext().init(() => noteService.createNewNote({
+ parentNoteId: "root",
+ title,
+ content,
+ type: "text"
+ }).note);
+ }
+
+ function rank(searchResults: Array<{ noteId: string }>, noteId: string) {
+ return searchResults.findIndex((result) => result.noteId === noteId);
+ }
+
+ it("ranks a body phrase match above scattered word matches (#10616)", () => {
+ const phrase = contentNote("Alpha", "I like you and me as a phrase");
+ const scattered = contentNote("Beta", "the menu is here and you know it");
+
+ const searchResults = searchService.findResultsWithQuery("you and me", new SearchContext());
+
+ const phraseRank = rank(searchResults, phrase.noteId);
+ const scatteredRank = rank(searchResults, scattered.noteId);
+
+ expect(phraseRank).toBeGreaterThanOrEqual(0);
+ expect(scatteredRank).toBeGreaterThanOrEqual(0);
+ expect(phraseRank).toBeLessThan(scatteredRank);
+ });
+
+ it("ranks a title match above a content-only match for the same query", () => {
+ const titled = contentNote("sync stuff", "");
+ const bodyOnly = contentNote("Docs", "please sync now");
+
+ const searchResults = searchService.findResultsWithQuery("sync", new SearchContext());
+
+ const titledRank = rank(searchResults, titled.noteId);
+ const bodyRank = rank(searchResults, bodyOnly.noteId);
+
+ expect(titledRank).toBeGreaterThanOrEqual(0);
+ expect(bodyRank).toBeGreaterThanOrEqual(0);
+ expect(titledRank).toBeLessThan(bodyRank);
+ });
+
+ it("finds a body typo via phase-2 fuzzy fallback, ranked below exact matches (combinef -> combined)", () => {
+ const exact = contentNote("ExactNote", "the combinef marker is set");
+ const fuzzy = contentNote("FuzzyNote", "the values were combined together");
+
+ const searchResults = searchService.findResultsWithQuery("combinef", new SearchContext());
+
+ const exactRank = rank(searchResults, exact.noteId);
+ const fuzzyRank = rank(searchResults, fuzzy.noteId);
+
+ expect(exactRank).toBeGreaterThanOrEqual(0);
+ expect(fuzzyRank).toBeGreaterThanOrEqual(0);
+ expect(exactRank).toBeLessThan(fuzzyRank);
+ // A fuzzy-only body match (weight 5) stays below the quality threshold (10),
+ // so it never suppresses the fuzzy phase.
+ 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("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
+ // 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>`);
+
+ const context = new SearchContext();
+ const searchResults = searchService.findResultsWithQuery("special", context);
+
+ expect(rank(searchResults, linker.noteId)).toBeGreaterThanOrEqual(0);
+ // exact_word (not "fuzzy") proves the injected title matched in phase 1, not the fallback.
+ expect(context.contentMatches.get(linker.noteId)?.tier).toBe("exact_word");
+ });
+
+ it("finds a note via a reference-link target title with diacritics (zurich -> Zürich), as an exact match", () => {
+ // Normalization strips diacritics on the injected title too, so `zurich` matches a
+ // linked "Zürich"; without normalizing the injected text this only surfaced via fuzzy.
+ const target = contentNote("Zürich", "");
+ const linker = contentNote("Linker", `<p>see <a class="reference-link" href="#root/${target.noteId}"></a></p>`);
+
+ const context = new SearchContext();
+ const searchResults = searchService.findResultsWithQuery("zurich", context);
+
+ expect(rank(searchResults, linker.noteId)).toBeGreaterThanOrEqual(0);
+ expect(context.contentMatches.get(linker.noteId)?.tier).toBe("exact_word");
+ });
+
+ it("skips content matching in fast search, so content scoring is a natural no-op", () => {
+ const doc = contentNote("Doc", "please sync the database now");
+
+ // Fast search builds no NoteContentFulltextExp, so the body is never
+ // scanned: no content match is recorded and the body-only note is absent.
+ const fast = new SearchContext({ fastSearch: true });
+ const fastResults = searchService.findResultsWithQuery("sync", fast);
+ expect(fast.contentMatches.size).toBe(0);
+ expect(rank(fastResults, doc.noteId)).toBe(-1);
+
+ // A normal search does scan the body and records the content match.
+ const full = new SearchContext();
+ const fullResults = searchService.findResultsWithQuery("sync", full);
+ expect(full.contentMatches.get(doc.noteId)?.tier).toBe("exact_word");
+ expect(rank(fullResults, doc.noteId)).toBeGreaterThanOrEqual(0);
+ });
+ });
+
+ it("breaks a collapsible summary onto its own line in the quick-search snippet", () => {
+ // striptags concatenates block text with no separator, which would merge a
+ // collapsible's summary straight into its body ("Summary TitleBody text").
+ const noteBuilder = note("Collapsible note");
+ noteBuilder.note.getContent = () => "<details class=\"trilium-collapsible\"><summary>Summary Title</summary><p>Body text here</p></details><p>After the block</p>";
+ rootNote.child(noteBuilder);
+
+ // The snippet gets a newline at the summary boundary and after the whole block, so
+ // neither the summary nor the body runs into the surrounding text.
+ const snippet = searchService.extractContentSnippet(noteBuilder.note.noteId, [ "body" ]);
+ expect(snippet.split("\n")).toEqual([ "Summary Title", "Body text here", "After the block" ]);
+
+ // ...which the quick-search route (extractContentSnippet -> highlightSearchResults)
+ // turns into <br> tags in the HTML the dropdown renders.
+ const result: any = { notePathTitle: "Collapsible note", contentSnippet: snippet, attributeSnippet: "" };
+ searchService.highlightSearchResults([ result ], [ "body" ]);
+ expect(result.highlightedContentSnippet).toBe("Summary Title<br><b>Body</b> text here<br>After the block");
+ });
+
// FIXME: test what happens when we order without any filter criteria
// it("comparison between labels", () => {