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
Merge remote-tracking branch 'origin/main' into feat/search-overhaul
perfectra1n5ecaa2eae4a9
diff --cc apps/client/src/services/link.spec.tsindex 5cf5ebe28b,5621188160..02361d45f7--- a/apps/client/src/services/link.spec.ts+++ b/apps/client/src/services/link.spec.ts@@@ -175,53 -183,141 +183,188 @@@ 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("calculateExtraWindowUrl", () => {+ it("marks the window as extra and appends the target hash", () => {+ const url = calculateExtraWindowUrl({ notePath: "root/abc123" }, new URL("http://localhost:8080/"));+ expect(url).toBe("http://localhost:8080/?extraWindow=1#root/abc123");+ });++ it("keeps the deployment sub-path, so a standalone build under a prefix still resolves", () => {+ const url = calculateExtraWindowUrl({ notePath: "root/abc123" }, new URL("https://notes.test/trilium/"));+ expect(url).toBe("https://notes.test/trilium/?extraWindow=1#root/abc123");+ });++ it("carries the current query string over instead of replacing it", () => {+ // In standalone the query *is* the environment (`?safeMode`, `?startNoteId` — see+ // QUERY_TO_ENV in the standalone platform provider). A window that dropped it would boot+ // with different settings than the one it was torn from, and would apply those to every+ // other window once it inherited the database lock.+ const url = calculateExtraWindowUrl({ notePath: "root/abc123" }, new URL("http://localhost:8080/?safeMode=1"));+ const { searchParams } = new URL(url);+ expect(searchParams.get("safeMode")).toBe("1");+ expect(searchParams.get("extraWindow")).toBe("1");+ });++ it("produces a URL the receiving window can still navigate from", () => {+ const url = calculateExtraWindowUrl(+ { notePath: "root/abc123", hoistedNoteId: "h1" },+ new URL("http://localhost:8080/?safeMode=1")+ );+ expect(parseNavigationStateFromUrl(url)).toMatchObject({+ notePath: "root/abc123",+ noteId: "abc123",+ hoistedNoteId: "h1"+ });+ });++ it("omits the hash when there is no target, as when opening a blank window", () => {+ const url = calculateExtraWindowUrl({ notePath: "", hoistedNoteId: "root" }, new URL("http://localhost:8080/"));+ expect(url).toBe("http://localhost:8080/?extraWindow=1");+ });+ });++ describe("split panes in the hash", () => {+ const A = "root/aaaaaaaaaaaa";+ const B = "root/bbbbbbbbbbbb";+ const C = "root/cccccccccccc";++ /** Wraps a bare hash in the address a detached window boots from. */+ const asExtraWindowUrl = (hash: string) => `http://localhost:8080/?extraWindow=1${hash}`;++ it("round-trips a tab's panes, keeping their order, hoisting and view scope", () => {+ const hash = calculateHash({+ notePath: A,+ splits: [+ { notePath: B, viewScope: { viewMode: "source" } },+ { notePath: C, hoistedNoteId: "h1" }+ ],+ activeSplit: 1+ });++ // each pane is a hash body of its own, comma-joined and encoded as a single parameter+ expect(hash).toBe(+ `#${A}?splits=root%2Fbbbbbbbbbbbb%3FviewMode%3Dsource%2Croot%2Fcccccccccccc%3FhoistedNoteId%3Dh1&activeSplit=1`+ );++ expect(parseNavigationStateFromUrl(asExtraWindowUrl(hash))).toMatchObject({+ notePath: A,+ activeSplit: 1,+ splits: [+ { notePath: B, hoistedNoteId: null, viewScope: { viewMode: "source" } },+ { notePath: C, hoistedNoteId: "h1", viewScope: { viewMode: "default" } }+ ]+ });+ });++ it("honours splits only when booting a detached window", () => {+ // The same parser backs every link click inside a note. Were splits read there, any note —+ // including an imported or synced one — could rearrange the panes of the window reading it.+ const hash = calculateHash({ notePath: A, splits: [{ notePath: B }] });++ expect(parseNavigationStateFromUrl(`http://localhost:8080/${hash}`)).toMatchObject({+ notePath: A,+ splits: null+ });+ });++ it("keeps the layout of a tab whose first pane held no note", () => {+ const hash = calculateHash({ notePath: null, splits: [{ notePath: B }] });++ expect(hash).toBe("#?splits=root%2Fbbbbbbbbbbbb");+ expect(parseNavigationStateFromUrl(asExtraWindowUrl(hash))).toMatchObject({+ notePath: "",+ noteId: null,+ splits: [{ notePath: B }]+ });++ // without splits an empty note path still means "nothing to navigate to"+ expect(parseNavigationStateFromUrl(asExtraWindowUrl("#"))).toStrictEqual({});+ });++ it("keeps empty panes, drops malformed ones and caps how many it will open", () => {+ const parse = (splits: string) =>+ parseNavigationStateFromUrl(asExtraWindowUrl(`#${A}?splits=${splits}`));++ // an empty entry is a pane that held no note — kept, so the pane count survives+ expect(parse(encodeURIComponent(`${B},,${C}`))).toMatchObject({+ splits: [{ notePath: B }, { notePath: null }, { notePath: C }]+ });++ // a hand-written address shouldn't be able to open a pane on garbage, nor hundreds of them+ expect(parse(encodeURIComponent(`${B},zz,${C}`))).toMatchObject({+ splits: [{ notePath: B }, { notePath: C }]+ });+ expect(parse(encodeURIComponent(Array(20).fill(B).join(",")))).toMatchObject({+ splits: Array(8).fill({ notePath: B })+ });+ });++ it("shrugs off an active index that is not a number, and a parameter carrying no value", () => {+ // Both reach the parser straight off the address bar, where anything at all may be typed.+ expect(parseNavigationStateFromUrl(+ asExtraWindowUrl(`#${A}?splits=${encodeURIComponent(B)}&activeSplit=whichever`)+ )).toMatchObject({ activeSplit: 0, splits: [{ notePath: B }] });++ // `popup` is a flag, so it is written bare — there is no `=` to split on.+ expect(parseNavigationStateFromUrl(`#${A}?popup`)).toMatchObject({ openInPopup: true });+ });++ it("ignores parameters that describe a window rather than a pane", () => {+ const nested = encodeURIComponent(`${B}?ntxId=n1&splits=${encodeURIComponent(C)}`);+ const parsed = parseNavigationStateFromUrl(asExtraWindowUrl(`#${A}?splits=${nested}`));++ expect(parsed).toMatchObject({ splits: [{ notePath: B, viewScope: { viewMode: "default" } }] });+ expect((parsed as any).splits[0]).not.toHaveProperty("ntxId");+ });+ });+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 --cc apps/client/src/services/link.tsindex 77c6013b12,8420ff0b8d..31049fcbb8--- a/apps/client/src/services/link.ts+++ b/apps/client/src/services/link.ts@@@ -62,13 -70,30 +70,35 @@@ export interface ViewScopetocCollapsedHeadings?: 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[];}+ /**+ * The state of a single split pane, as carried by the `splits` hash parameter when a tab is+ * moved or copied into a window of its own.+ */+ export interface HashPane {+ notePath?: string | null;+ hoistedNoteId?: string | null;+ viewScope?: ViewScope;+ }++ /** A note path as it may appear in a hash: slash-separated note ids. */+ const NOTE_PATH_PATTERN = /^[_a-z0-9]{4,}(\/[_a-z0-9]{4,})*$/i;++ /**+ * How many extra panes a hash is allowed to carry. Well beyond any layout a user would build by+ * hand, but low enough that a hand-written address can't ask the app to open hundreds of panes.+ */+ const MAX_SPLIT_PANES_IN_HASH = 8;++ /** Hash parameters that belong to a pane's view scope rather than to the window as a whole. */+ const VIEW_SCOPE_PARAMS = ["viewMode", "attachmentId", "bookmark"];+interface CreateLinkOptions {title?: string;showTooltip?: boolean;@@@ -202,9 -229,8 +234,11 @@@ export function calculateHashhoistedNoteId && hoistedNoteId !== "root" ? { hoistedNoteId } : null,viewScope.viewMode && viewScope.viewMode !== "default" ? { viewMode: viewScope.viewMode } : null,viewScope.attachmentId ? { attachmentId: viewScope.attachmentId } : null,+ viewScope.searchTerms?.length+ ? { searchTerms: viewScope.searchTerms.map(encodeURIComponent).join(",") }- : null++ : null,+ splits?.length ? { splits: splits.map(encodeSplitPane).join(",") } : null,+ splits?.length && activeSplit ? { activeSplit: String(activeSplit) } : null].filter((p) => !!p);const paramStr = params@@@ -256,41 -324,29 +332,44 @@@ export function parseNavigationStateFrolet hoistedNoteId: string | null = null;let searchString: string | null = null;let openInPopup = false;-- if (paramString) {- for (const pair of paramString.split("&")) {- let [name, value] = pair.split("=");- name = decodeURIComponent(name);- value = decodeURIComponent(value);-- if (name === "ntxId") {- ntxId = value;- } else if (name === "hoistedNoteId") {- 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") {- openInPopup = true;- } else {- console.warn(`Unrecognized hash parameter '${name}'.`);- }+ let splits: HashPane[] | null = null;+ let activeSplit = 0;++ for (const [name, value] of parseHashParams(paramString)) {+ if (name === "ntxId") {+ ntxId = value;+ } else if (name === "hoistedNoteId") {+ 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() in parseHashParams (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 (VIEW_SCOPE_PARAMS.includes(name)) {+ (viewScope as any)[name] = value;+ } else if (name === "popup") {+ openInPopup = true;+ } else if (name === "splits") {+ // Splits lay out the whole window, so they are honoured only while booting a+ // detached one. A link inside a note reaches this same parser, and no note should+ // be able to rearrange the panes of the window it is read in.+ splits = isExtraWindow ? parseSplitPanes(value) : null;+ } else if (name === "activeSplit") {+ activeSplit = Number.parseInt(value, 10) || 0;+ } else {+ console.warn(`Unrecognized hash parameter '${name}'.`);}}diff --cc apps/client/src/widgets/collections/Pagination.spec.tsxindex 8b0b9efdf2,0000000000..984a8b9b3emode 100644,000000..100644--- a/apps/client/src/widgets/collections/Pagination.spec.tsx+++ b/apps/client/src/widgets/collections/Pagination.spec.tsx@@@ -1,109 -1,0 +1,109 @@@+/**+ * Tests for the additive `defaultPageSize` parameter added to {@link usePagination} for C7:+ * the caller-provided default (e.g. the synced `searchResultsPageSize` option) drives the page size+ * when the note has no explicit `#pageSize` label, but an explicit label always keeps winning.+ */+import { render } from "preact";+import { act } from "preact/test-utils";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import Component from "../../components/component";+import type FNote from "../../entities/fnote";+import froca from "../../services/froca";+import { buildNote, buildNotes } from "../../test/easy-froca";+import { ParentComponent } from "../react/react_utils";+import { usePagination } from "./Pagination";++let observed: { pageSize: number; pageCount: number; page: number; pageNotes?: FNote[]; setPage?: (page: number) => void } | undefined;++// 25 real froca notes so usePagination's froca.getNotes() slice never round-trips to the server.+const NOTE_IDS = buildNotes(Array.from({ length: 25 }, (_, i) => ({ id: `pag-${i}`, title: `N${i}` })));++function Harness({ note, noteIds = NOTE_IDS, defaultPageSize }: { note: FNote; noteIds?: string[]; defaultPageSize?: number }) {- const { page, setPage, pageNotes, pageSize, pageCount } = usePagination(note, noteIds, defaultPageSize);++ const { page, setPage, pageNotes, pageSize, pageCount } = usePagination(note, noteIds, { defaultPageSize });+ observed = { pageSize, pageCount, page, pageNotes, setPage };+ return null;+}++describe("usePagination default page size", () => {+ let container: HTMLElement | undefined;++ beforeEach(() => {+ observed = undefined;+ });++ afterEach(() => {+ if (container) {+ render(null, container);+ container.remove();+ container = undefined;+ }+ });++ async function mount(note: FNote, defaultPageSize?: number) {+ const parent = new Component();+ // Capture in a local const so the type stays narrowed to HTMLElement inside the act() closure.+ const el = document.createElement("div");+ container = el;+ document.body.appendChild(el);+ await act(async () => {+ render(+ <ParentComponent.Provider value={parent}>+ <Harness note={note} defaultPageSize={defaultPageSize} />+ </ParentComponent.Provider>,+ el+ );+ });+ }++ it("uses the provided default page size when the note has no #pageSize label", async () => {+ const note = buildNote({ title: "Search", type: "search" });+ await mount(note, 10);+ expect(observed?.pageSize).toBe(10);+ expect(observed?.pageCount).toBe(3); // 25 items / 10+ });++ it("lets an explicit #pageSize label override the provided default", async () => {+ const note = buildNote({ title: "Search", type: "search", "#pageSize": "5" });+ await mount(note, 50);+ expect(observed?.pageSize).toBe(5);+ expect(observed?.pageCount).toBe(5); // 25 items / 5+ });++ it("falls back to 20 when neither a label nor a positive default is given", async () => {+ const note = buildNote({ title: "Search", type: "search" });+ await mount(note, Number.NaN);+ expect(observed?.pageSize).toBe(20);+ });++ it("discards a stale note load that resolves after a newer page's load", async () => {+ // Take over froca.getNotes with manually-resolved deferreds so resolution order can be+ // inverted: rapid page flips issue overlapping loads, and the older one must not win.+ const pending: Array<{ ids: string[]; resolve: (notes: FNote[]) => void }> = [];+ const getNotesSpy = vi.spyOn(froca, "getNotes").mockImplementation((ids) =>+ new Promise((resolve) => pending.push({ ids: ids as string[], resolve }))+ );+ try {+ const note = buildNote({ title: "Search", type: "search" });+ await mount(note, 10);++ // Initial load for page 1, then flip to page 2 and quickly on to page 3.+ expect(pending.length).toBe(1);+ await act(async () => observed?.setPage?.(2));+ await act(async () => observed?.setPage?.(3));+ expect(pending.length).toBe(3);++ const [ , page2Load, page3Load ] = pending;+ const toNotes = (ids: string[]) => ids.map((id) => froca.notes[id]).filter((n): n is FNote => Boolean(n));++ // Newest (page 3) resolves first, then the stale page-2 load arrives late.+ await act(async () => page3Load.resolve(toNotes(page3Load.ids)));+ await act(async () => page2Load.resolve(toNotes(page2Load.ids)));++ expect(observed?.page).toBe(3);+ expect(observed?.pageNotes?.map((n) => n.noteId)).toEqual(page3Load.ids);+ } finally {+ getNotesSpy.mockRestore();+ }+ });+});diff --cc apps/client/src/widgets/collections/Pagination.tsxindex 72079111ff,f328f23fe1..62e0d26491--- a/apps/client/src/widgets/collections/Pagination.tsx+++ b/apps/client/src/widgets/collections/Pagination.tsx@@@ -122,17 -122,18 +122,32 @@@ function createSegment(start: number, lreturn children;}- export function usePagination(note: FNote, noteIds: string[], defaultPageSize = 20): PaginationContext {-/**- * @param pageSizeOverride page size to use instead of the note's `#pageSize` label, for callers that- * list notes which aren't the children of a collection the user can label.- */-export function usePagination(note: FNote, noteIds: string[], pageSizeOverride?: number): PaginationContext {++interface PaginationOptions {++ /**++ * Page size to use *instead of* the note's `#pageSize` label, for callers that list notes which++ * aren't the children of a collection the user can label.++ */++ pageSizeOverride?: number;++ /**++ * Page size to fall back to when the note carries no `#pageSize` label (e.g. the synced++ * `searchResultsPageSize` option). An explicit label always wins over this.++ */++ defaultPageSize?: number;++}++++export function usePagination(++ note: FNote,++ noteIds: string[],++ { pageSizeOverride, defaultPageSize = 20 }: PaginationOptions = {}++): PaginationContext {const [ page, setPage ] = useState(1);const [ pageNotes, setPageNotes ] = useState<FNote[]>();- // Parse page size. An explicit `#pageSize` label always wins; otherwise fall back to the- // caller-supplied default (e.g. the synced `searchResultsPageSize` option), and finally to 20- // when neither yields a usable positive size.- // Parse page size.++ // Parse page size. An explicit override wins outright; otherwise a `#pageSize` label wins over++ // the caller-supplied default, and 20 stands in when none of them yields a usable positive size.const [ labelPageSize ] = useNoteLabelInt(note, "pageSize");- const normalizedPageSize = (labelPageSize && labelPageSize > 0)- ? labelPageSize- : (defaultPageSize > 0 ? defaultPageSize : 20);- const pageSize = pageSizeOverride ?? labelPageSize;++ const pageSize = pageSizeOverride ?? (labelPageSize && labelPageSize > 0 ? labelPageSize : defaultPageSize);+ const normalizedPageSize = (pageSize && pageSize > 0 ? pageSize : 20);// Calculate start/end index.const startIdx = (page - 1) * normalizedPageSize;diff --cc apps/client/src/widgets/collections/legacy/ListOrGridView.tsxindex f0783682d0,ac30f1ba8a..7968008af4--- a/apps/client/src/widgets/collections/legacy/ListOrGridView.tsx+++ b/apps/client/src/widgets/collections/legacy/ListOrGridView.tsx@@@ -24,15 -23,61 +24,61 @@@ import { ComponentChildren, TargetedMouconst contentSizeObserver = new ResizeObserver(onContentResized);- export function ListView({ note, noteIds: unfilteredNoteIds, highlightedTokens, showTextRepresentation }: ViewModeProps<{}>) {- const expandDepth = useExpansionDepth(note);+ /**+ * Opt-in adjustments for callers that reuse the list outside a collection note. Every field is+ * optional and defaults to the collection behaviour, so existing views are unaffected.+ */+ export interface ListViewOptions {+ /** Heading shown at the top of the list's card. */+ title?: string;+ /**+ * Lays the items out the way search results are shown — the note's path under its title, and a+ * path that addresses the note directly rather than through the parent. Search notes always use+ * this layout; set it when the parent isn't the notes' real parent.+ */+ searchResultsLayout?: boolean;+ /** Omits the nested subnote tree, leaving only each note's own content preview. */+ hideSubNotes?: boolean;+ /**+ * Supplies a row's nested notes, replacing its real child notes. Lets a caller present its own+ * hierarchy — grouping scattered notes by where they live — through the same nesting UI.+ */+ resolveChildren?: (note: FNote) => FNote[];+ /**+ * Decides per row whether its content preview is rendered inline; previews show for every row by+ * default. Useful when a caller inserts rows of its own, whose content is not the point.+ *+ * A row without an inline preview gets the hover preview tooltip on its link instead, so the+ * content stays reachable — the two are alternatives, never both at once.+ */+ showPreview?: (note: FNote) => boolean;+ /**+ * Decides per row whether the note's path is shown under its title, overriding+ * {@link searchResultsLayout}. Only the display is affected: the path is still *resolved* flat,+ * so links keep addressing the note directly.+ */+ showNotePath?: (note: FNote) => boolean;+ /** Overrides how many levels start expanded, otherwise read from the parent's `#expanded`. */+ expandDepth?: number;+ /** Overrides the number of notes per page, otherwise read from the parent's `#pageSize`. */+ pageSize?: number;+ /** Rendered on the title row in place of the note's attributes. */+ renderItemActions?: (note: FNote) => ComponentChildren;+ /** Rendered in place of the item's "..." menu, for lists offering their own actions. */+ renderItemMenu?: (note: FNote) => ComponentChildren;+ }++ export function ListView({ note, noteIds: unfilteredNoteIds, highlightedTokens, showTextRepresentation, listOptions }: ViewModeProps<{}> & { listOptions?: ListViewOptions }) {+ const labelExpandDepth = useExpansionDepth(note);const noteIds = useFilteredNoteIds(note, unfilteredNoteIds);- const { pageNotes, ...pagination } = usePagination(note, noteIds);- const { pageNotes, ...pagination } = usePagination(note, noteIds, listOptions?.pageSize);++ const { pageNotes, ...pagination } = usePagination(note, noteIds, { pageSizeOverride: listOptions?.pageSize });const [ includeArchived ] = useNoteLabelBoolean(note, "includeArchived");const noteType = useNoteProperty(note, "type");+ const searchResultsLayout = (noteType === "search") || !!listOptions?.searchResultsLayout;+ const expandDepth = listOptions?.expandDepth ?? labelExpandDepth;return <NoteList note={note} viewMode="list-view" noteIds={noteIds} pagination={pagination}>- <Card className={clsx("nested-note-list", {"search-results": (noteType === "search")})}>+ <Card heading={listOptions?.title} className={clsx("nested-note-list", {"search-results": searchResultsLayout})}>{pageNotes?.map(childNote => (<ListNoteCardkey={childNote.noteId}@@@ -99,13 -151,19 +152,19 @@@ function ListNoteCard({ note, parentNotparentNote: FNote,currentLevel: number,expandDepth: number,- highlightedTokens: string[] | null | undefined;+ highlightedTokens: (string | HighlightedTokenInfo)[] | null | undefined;includeArchived: boolean;showTextRepresentation?: boolean;- }) {+ } & Pick<ListViewOptions, "searchResultsLayout" | "hideSubNotes" | "resolveChildren" | "showPreview" | "showNotePath" | "renderItemActions" | "renderItemMenu">) {const [ isExpanded, setExpanded ] = useState(currentLevel <= expandDepth);- const notePath = getNotePath(parentNote, note);+ const notePath = getNotePath(parentNote, note, searchResultsLayout);+ // The hover tooltip stands in for the inline preview, so exactly one of the two is offered.+ const showsPreview = showPreview?.(note) ?? true;+ const showsNotePath = showNotePath?.(note) ?? searchResultsLayout;+ // Whether expanding would reveal anything at all. Collections always have a preview to show, so+ // only callers that suppress it can produce a row with nothing underneath.+ const isExpandable = showsPreview || hasNestedNotes(note, hideSubNotes, resolveChildren);// Reset expand state if switching to another note, or if user manually toggled expansion state.useEffect(() => setExpanded(currentLevel <= expandDepth), [ note, currentLevel, expandDepth ]);@@@ -296,9 -371,9 +372,9 @@@ function NoteChildren({ note, parentNotparentNote: FNote,currentLevel: number,expandDepth: number,- highlightedTokens: string[] | null | undefined+ highlightedTokens: (string | HighlightedTokenInfo)[] | null | undefinedincludeArchived: boolean;- }) {+ } & Pick<ListViewOptions, "searchResultsLayout" | "resolveChildren" | "showPreview" | "showNotePath" | "renderItemActions" | "renderItemMenu">) {const [ childNotes, setChildNotes ] = useState<FNote[]>();useEffect(() => {diff --cc apps/client/src/widgets/collections/search/SearchResultsList.tsxindex 130b5bbef3,0000000000..f4276ea1d7mode 100644,000000..100644--- a/apps/client/src/widgets/collections/search/SearchResultsList.tsx+++ b/apps/client/src/widgets/collections/search/SearchResultsList.tsx@@@ -1,111 -1,0 +1,111 @@@+import "./SearchResultsList.css";++import type { HighlightedTokenInfo } from "@triliumnext/commons";+import { useMemo } from "preact/hooks";++import type FNote from "../../../entities/fnote";+import { t } from "../../../services/i18n";+import CollectionProperties from "../../note_bars/CollectionProperties";+import FormSelect from "../../react/FormSelect";+import { useTriliumOptionInt } from "../../react/hooks";+import { ViewModeMedia } from "../interface";+import { useNoteIds } from "../NoteList";+import { Pager, usePagination } from "../Pagination";+import SearchResultCard from "./SearchResultCard";+import { useSearchResultDetails } from "./useSearchResultDetails";++interface SearchResultsListProps {+ note: FNote | null | undefined;+ notePath: string | null | undefined;+ ntxId: string | null | undefined;+ highlightedTokens?: (string | HighlightedTokenInfo)[] | null;+ media: ViewModeMedia;+}++/**+ * Google-style snippet-card view for the results of a search note (issues #5667, #6225). Used only+ * for the "list" view type; other view types keep going through the legacy `SearchNoteList` path.+ *+ * Composition mirrors the legacy list view's collection bar (`CollectionProperties` with a centered+ * pager) but adds an always-visible result count and a page-size selector, then renders one+ * {@link SearchResultCard} per note on the current page plus a bottom pager. The per-note snippet+ * details are fetched lazily, one page at a time, via {@link useSearchResultDetails}.+ */+export default function SearchResultsList({ note, ntxId, highlightedTokens }: SearchResultsListProps) {+ // The results view only mounts for an executed search note; guard here so the inner component+ // (and the collection hooks it drives) can rely on a non-null note.+ if (!note) return null;+ return <SearchResultsListInner note={note} ntxId={ntxId} highlightedTokens={highlightedTokens} />;+}++// Only the props the card view actually consumes; `media`/`notePath` from the shared collection-view+// shape are unused here, so they are not threaded into the inner component.+interface SearchResultsListInnerProps {+ note: FNote;+ ntxId: string | null | undefined;+ highlightedTokens?: (string | HighlightedTokenInfo)[] | null;+}++function SearchResultsListInner({ note, ntxId, highlightedTokens }: SearchResultsListInnerProps) {+ const [ pageSize, setPageSize ] = useTriliumOptionInt("searchResultsPageSize");+ const noteIds = useNoteIds(note, "list", ntxId);- const pagination = usePagination(note, noteIds, pageSize);++ const pagination = usePagination(note, noteIds, { defaultPageSize: pageSize });+ const pageNoteIds = useMemo(() => {+ const start = (pagination.page - 1) * pagination.pageSize;+ return noteIds.slice(start, start + pagination.pageSize);+ }, [ noteIds, pagination.page, pagination.pageSize ]);+ const { detailsByNoteId, loading } = useSearchResultDetails(note, pageNoteIds, ntxId);++ return (+ <div className="search-results-list">+ <CollectionProperties+ note={note}+ centerChildren={<Pager className="search-results-list-top-pager" {...pagination} />}+ rightChildren={+ <SearchResultsToolbar+ count={pagination.totalNotes}+ pageSize={pagination.pageSize}+ setPageSize={setPageSize}+ />+ }+ />++ <div className="search-results-list-cards">+ {pageNoteIds.map((noteId) => (+ <SearchResultCard+ key={noteId}+ noteId={noteId}+ details={detailsByNoteId.get(noteId)}+ loading={loading}+ highlightedTokens={highlightedTokens}+ />+ ))}+ </div>++ <Pager className="search-results-list-bottom-pager" {...pagination} />+ </div>+ );+}++const PAGE_SIZE_OPTIONS = [ 10, 20, 50, 100 ].map((value) => ({ value: String(value) }));++export function SearchResultsToolbar({ count, pageSize, setPageSize }: {+ count: number;+ pageSize: number;+ setPageSize: (value: number) => void | Promise<void>;+}) {+ return (+ <div className="search-results-list-toolbar">+ <span className="search-results-list-count">{t("search_result.result_count", { count })}</span>+ <label className="search-results-list-page-size">+ <span className="search-results-list-page-size-label">{t("search_result.page_size")}</span>+ <FormSelect+ values={PAGE_SIZE_OPTIONS}+ keyProperty="value"+ currentValue={String(pageSize)}+ onChange={(value) => void setPageSize(parseInt(value, 10))}+ />+ </label>+ </div>+ );+}diff --cc apps/client/src/widgets/react/hooks.spec.tsxindex f5200b2688,aa9d4a6bda..e6442b5d78--- a/apps/client/src/widgets/react/hooks.spec.tsx+++ b/apps/client/src/widgets/react/hooks.spec.tsx@@@ -5,7 -4,36 +5,40 @@@ import { useRef } from "preact/hooks"import { act } from "preact/test-utils";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";- import { type DelayedVisibilityPhase, useDelayedVisibility, useImperativeSearchHighlighlighting, useStaticTooltip } from "./hooks";+ import { type DelayedVisibilityPhase, useDelayedVisibility, useImperativeSearchHighlighlighting, useStaticTooltip, useTooltip } from "./hooks";++ /**+ * mark.js delegating to the real implementation, so marking still works, while recording the calls+ * `unmark()` receives — its DOM effect cannot be observed under happy-dom, where it removes nothing.+ */+ const markSpies = vi.hoisted(() => ({ unmark: vi.fn() }));++ vi.mock("mark.js", async (importOriginal) => {+ const actual = await importOriginal<{ default: new (ctx: unknown) => Record<string, (...args: unknown[]) => unknown> }>();++ return {+ default: class {+ private inner: Record<string, (...args: unknown[]) => unknown>;++ constructor(ctx: unknown) {+ this.inner = new actual.default(ctx);+ }+++ mark(...args: unknown[]) {++ return this.inner.mark(...args);++ }+++ markRegExp(...args: unknown[]) {+ return this.inner.markRegExp(...args);+ }++ unmark(...args: unknown[]) {+ markSpies.unmark(...args);+ return this.inner.unmark(...args);+ }+ }+ };+ });let currentPhase: DelayedVisibilityPhase | undefined;@@@ -130,7 -374,12 +379,8 @@@ describe("useTooltip", () =>describe("useImperativeSearchHighlighlighting", () => {let container: HTMLElement;- let highlight: ((el: HTMLElement | null | undefined) => void) | undefined;-- function Probe({ tokens }: { tokens: string[] | null | undefined }) {- highlight = useImperativeSearchHighlighlighting(tokens);- return null;- }+ let target: HTMLElement;++ let liveHighlight: ((el: HTMLElement | null | undefined) => void) | undefined;beforeEach(() => {container = document.createElement("div");@@@ -142,80 -389,81 +392,132 @@@afterEach(() => {render(null, container);container.remove();- highlight = undefined;+ target.remove();++ liveHighlight = undefined;});- 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;+ }++ /** 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;+ }++ function markedTexts(el: HTMLElement) {+ return Array.from(el.querySelectorAll("span.ck-find-result")).map((mark) => mark.textContent);+ }+++ /**++ * Re-renders the *same* hook instance with new tokens, unlike {@link highlight}, which remounts.++ * Keeping the instance alive is the point: its `Mark` has to survive into the next call for the++ * clear-on-empty behaviour to be observable at all.++ */++ async function remount(tokens: (string | HighlightedTokenInfo)[] | null | undefined) {++ await act(async () => {++ render(<Probe tokens={tokens} onReady={(fn) => { liveHighlight = fn; }} />, container);++ });+ }+++ /** A detached element to highlight into, so it outlives a {@link remount}. */+ function content(html: string): HTMLElement {+ const el = document.createElement("div");+ el.innerHTML = html;+ document.body.appendChild(el);+ return el;+ }+- 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>");-- 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("clears previous highlights once the tokens are cleared", async () => {+ // Callers that keep the same element and merely drop the tokens — emptying a filter box —+ // rely on this, or the old highlights stay in the DOM for good.+ //+ // The removal itself is asserted through mark.js rather than the DOM: its `unmark()` is a+ // no-op under happy-dom (it removes nothing even from a fresh instance), so only the call+ // can be observed here.- await mount([ "needle" ]);- const target = content("<p>a needle here</p>");- highlight?.(target);- expect(target.querySelectorAll(".ck-find-result").length).toBeGreaterThan(0);++ await remount([ "needle" ]);++ const el = content("<p>a needle here</p>");++ liveHighlight?.(el);++ expect(el.querySelectorAll(".ck-find-result").length).toBeGreaterThan(0);+ markSpies.unmark.mockClear();+- await mount(null);- highlight?.(target);++ await remount(null);++ liveHighlight?.(el);++ expect(markSpies.unmark).toHaveBeenCalled();- target.remove();++ el.remove();+ });++ it("does not touch an element that was never highlighted", async () => {- await mount(null);- const target = content("<p>a needle here</p>");++ await remount(null);++ const el = content("<p>a needle here</p>");+ markSpies.unmark.mockClear();+- highlight?.(target);++ liveHighlight?.(el);++ expect(markSpies.unmark).not.toHaveBeenCalled();- expect(target.innerHTML).toBe("<p>a needle here</p>");- target.remove();++ expect(el.innerHTML).toBe("<p>a needle here</p>");++ el.remove();+ });+- 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.tsxindex 79d079a617,c4eac0f804..393ac5680b--- a/apps/client/src/widgets/react/hooks.tsx+++ b/apps/client/src/widgets/react/hooks.tsx@@@ -1280,53 -1389,31 +1418,61 @@@ export function useImperativeSearchHigh}, [ highlightedTokens ]);return (el: HTMLElement | null | undefined) => {- if (!el || !tokenInfos) return;+ if (!el) return;++ // Nothing has ever been highlighted here, so there is also nothing to clear.- if (!mark.current && !highlightRegex) return;++ if (!mark.current && !tokenInfos) return;if (!mark.current) {mark.current = new Mark(el);}+ // Clearing comes first and happens even with no tokens left: callers that keep the same+ // element and merely drop the tokens (e.g. emptying a filter box) rely on this to remove the+ // previous highlights, which would otherwise stay in the DOM for good.mark.current.unmark();- if (!highlightRegex) return;++ if (!tokenInfos) return;+++ 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;- 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);+ 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/EditableText.tsxindex 5f3694e8e5,066afb37ab..8cecb4e556--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx@@@ -12,14 -11,14 +12,15 @@@ import { t } from "../../../services/i1import link, { parseNavigationStateFromUrl } from "../../../services/link";import note_create from "../../../services/note_create";import options from "../../../services/options";+import { consumeSearchTerms } from "../../../services/search_jump";import toast from "../../../services/toast";import utils, { isMobile } from "../../../services/utils";-import { useEditorSpacedUpdate, useLegacyImperativeHandlers, useNoteLabel, useTriliumEvent, useTriliumOption, useTriliumOptionBool } from "../../react/hooks";+import { useEditorSpacedUpdate, useLegacyImperativeHandlers, useNoteLabel, useSearchTermsConsumer, useTriliumEvent, useTriliumOption, useTriliumOptionBool } from "../../react/hooks";import { TypeWidgetProps } from "../type_widget";- import CKEditorWithWatchdog, { CKEditorApi } from "./CKEditorWithWatchdog";+ import CKEditorWithWatchdog, { CKEditorApi, NotificationEventData, NotificationEventInfo } from "./CKEditorWithWatchdog";import getTemplates, { updateTemplateCache } from "./snippets.js";import linkEmbedService from "../../../services/link_embed";+ import { usesClassicToolbar } from "./toolbar";import { loadIncludedNote, refreshIncludedNote, setupImageOpening } from "./utils";/**diff --cc apps/client/src/widgets/type_widgets/text/ReadOnlyText.spec.tsxindex 908a0dbc48,5ed15d1f5e..5e61997fd6--- a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.spec.tsx+++ b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.spec.tsx@@@ -172,61 -177,37 +177,96 @@@ describe("ReadOnlyText reacting to cont});});+describe("ReadOnlyText ?bookmark= handling", () => {+ let cleanupContainer: HTMLElement | undefined;++ afterEach(() => {+ 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 () => {+ 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(+ <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 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");++ // 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(noteContext.viewScope?.bookmark).toBeUndefined();+ });+});+++ /**+ * The direction is resolved from the note's `#language` label and handed to the content+ * element as `dir`, which is what the RTL rules in the content stylesheets key off (they+ * match on the `.ck-content` ancestor carrying it). The editor sets it via CKEditor's own+ * `language.content` config, so a read-only note that drops it flips back to LTR the moment+ * editing is disabled.+ */+ describe("ReadOnlyText text direction", () => {+ let cleanupContainer: HTMLElement | undefined;++ afterEach(() => {+ if (cleanupContainer) {+ render(null, cleanupContainer);+ cleanupContainer.remove();+ cleanupContainer = undefined;+ }+ });++ async function mountWithLanguage(language?: string) {+ const harness = setupHarness({ isVisible: true, language });+ cleanupContainer = harness.container;+ await harness.mount();+ return harness.container.querySelector(".note-detail-readonly-text-content");+ }++ it("marks the content right-to-left for a note in an RTL language", async () => {+ expect((await mountWithLanguage("he"))?.getAttribute("dir")).toBe("rtl");+ });++ it("marks the content left-to-right otherwise", async () => {+ expect((await mountWithLanguage("en"))?.getAttribute("dir")).toBe("ltr");+ expect((await mountWithLanguage(undefined))?.getAttribute("dir")).toBe("ltr");+ });+ });diff --cc apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsxindex 6ef6b3b83a,2a707f98cb..7b12fd5a0f--- a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx+++ b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx@@@ -10,15 -10,13 +10,15 @@@ import { useEffect, useLayoutEffect, usimport appContext from "../../../components/app_context";import FNote from "../../../entities/fnote";+import { consumeBookmark } from "../../../services/bookmark_jump";import { applyInlineMermaid, rewriteMermaidDiagramsInContainer } from "../../../services/content_renderer_text";- import { getLocaleById } from "../../../services/i18n";import { applyLinkEmbeds } from "../../../services/link_embed";import { renderMathInElement } from "../../../services/math";import { trackPendingRender } from "../../../services/pending_renders";+import { consumeSearchTerms } from "../../../services/search_jump";import { formatCodeBlocks } from "../../../services/syntax_highlight";+ import { isContentRightToLeft } from "../../../utils/formatters";-import { useNoteBlob, useNoteLabel, useSyncedRef, useTriliumEvent, useTriliumOption, useTriliumOptionBool } from "../../react/hooks";+import { useNoteBlob, useNoteLabel, useSearchTermsConsumer, useSyncedRef, useTriliumEvent, useTriliumOption, useTriliumOptionBool } from "../../react/hooks";import { RawHtmlBlock } from "../../react/RawHtml";import { TypeWidgetProps } from "../type_widget";import { applyReferenceLinks } from "./read_only_helper";diff --cc packages/commons/src/lib/server_api.tsindex 56cc35ac52,4740fb07d9..5d656e6bfd--- a/packages/commons/src/lib/server_api.ts+++ b/packages/commons/src/lib/server_api.ts@@@ -232,47 -334,402 +334,443 @@@ export interface SubtreeSizeResponsesubTreeSize: number;}+/**+ * A single token to highlight in search results, tagged with how it should be+ * matched. `plain` tokens are matched literally (case-insensitively); `regex`+ * tokens (produced by the `%=` operator) are compiled to a regular expression.+ */+export interface HighlightedTokenInfo {+ token: string;+ type: "plain" | "regex";+}++/** Request body for `POST /api/search-note/:noteId/result-details` (max 100 noteIds). */+export interface SearchResultDetailsRequest {+ noteIds: string[];+}++/**+ * Per-note snippet + highlight details for one search result, built lazily for a+ * page of results. Snippet fields are absent when there is nothing to show (e.g.+ * protected notes without a session, or script-based searches).+ */+export interface SearchResultDetails {+ noteId: string;+ notePath: string;+ noteTitle: string;+ notePathTitle: string;+ highlightedNotePathTitle?: string;+ contentSnippet?: string;+ highlightedContentSnippet?: string;+ attributeSnippet?: string;+ highlightedAttributeSnippet?: string;+ icon: string;+}++/** Response for `POST /api/search-note/:noteId/result-details`. */+export interface SearchResultDetailsResponse {+ /** Requested-order details; requested ids not in the result set are omitted. */+ results: SearchResultDetails[];+ highlightedTokenInfos: HighlightedTokenInfo[];+ error: string | null;+}++ /**+ * How far an on-demand image compression run should go. Every field is optional, and what is left+ * out falls back to the corresponding option — so an empty request compresses exactly the way the+ * automatic import-time shrinking would, only without needing that shrinking to be enabled.+ *+ * Unlike the `compressImages` option, this is always a deliberate act by the user on one note or+ * one image, so it runs whether or not automatic compression is switched on.+ */+ /** The three things that can become of a lossless image; see {@link ImageCompressionOptions}. */+ export const IMAGE_PNG_HANDLINGS = [ "keep", "optimize", "jpeg" ] as const;++ export type ImagePngHandling = (typeof IMAGE_PNG_HANDLINGS)[number];++ /** The two things that can become of an already-lossy image; see {@link ImageCompressionOptions}. */+ export const IMAGE_JPEG_HANDLINGS = [ "keep", "compress" ] as const;++ export type ImageJpegHandling = (typeof IMAGE_JPEG_HANDLINGS)[number];++ /**+ * The formats a compression run can act on at all. Named once and read by both the encoder that+ * enforces it and the inventory that reports against it, so the two cannot come to disagree about+ * which images are worth offering to compress.+ */+ export const IMAGE_COMPRESSIBLE_FORMATS = [ "jpg", "png" ] as const;++ export type ImageCompressibleFormat = (typeof IMAGE_COMPRESSIBLE_FORMATS)[number];++ /**+ * What one image is, read from its own bytes.+ *+ * Every measurement is nullable and null means one thing throughout: the format does not state it,+ * or the file is too damaged to. Nothing here is a default standing in for something unread.+ */+ export interface ImageInfoResponse {+ entityType: "note" | "attachment";+ entityId: string;+ title: string;+ /** The mime it is stored under, which is not always what the bytes turn out to say. */+ mime: string;+ /** What the bytes say it is: "jpg", "png", "gif", "webp", "bmp", "svg", "unknown". */+ format: string;+ /** The mime that format implies, for comparing against {@link mime}. */+ detectedMime: string;+ /** Bytes on disk. */+ size: number;+ width: number | null;+ height: number | null;+ /** Bits per channel — 8 for almost everything, 16 for a deep PNG. */+ bitDepth: number | null;+ /** Channels per pixel: 1 greyscale or indexed, 3 colour, 4 colour with alpha or CMYK. */+ channels: number | null;+ /** Whether the format stores an alpha channel; not whether any pixel actually uses it. */+ hasAlpha: boolean | null;+ /** Stored as a palette rather than colour per pixel — already quantized, in other words. */+ indexed: boolean | null;+ /** For a JPEG, the quality it appears to have been written at; null for anything else. */+ quality: number | null;+ /** Whether a compression run could act on it at all. */+ compressible: boolean;+ }++ /** A count of images and what they weigh between them. */+ export interface ImageInventoryTally {+ count: number;+ /** Bytes, summed over the images counted. */+ size: number;+ }++ export interface ImageInventoryFormat extends ImageInventoryTally {+ /** Read from the content rather than the mime: "jpg", "png", "gif", "webp", "bmp", "svg". */+ format: string;+ }++ /**+ * What images a note holds, and what compressing them could reach.+ *+ * Measured over exactly the images a compression run with the same `recursive` setting would visit,+ * so the two never describe different sets — see `getNoteImageInventory`.+ */+ export interface ImageInventoryResponse {+ /** The note the reading was taken on, so a caller need not look it up to name it. */+ title: string;+ /** How many notes it covered: the note alone, or it and its descendants when descending. */+ noteCount: number;+ /** Every image found, whatever its format. */+ total: ImageInventoryTally;+ /**+ * Those a run could actually act on: a supported format, and not one of the generated pictures+ * a canvas or spreadsheet note keeps, which are rebuilt on save and so left alone.+ */+ compressible: ImageInventoryTally;+ /** Compressible images whose longest edge exceeds {@link maxWidthHeight}. */+ oversized: ImageInventoryTally;+ /** Every format found, heaviest first. */+ formats: ImageInventoryFormat[];+ /**+ * The formats among which at least one image could actually be compressed, in the same order.+ *+ * Narrower than filtering {@link formats} by what the encoder supports: a note whose only PNG is+ * the picture it regenerates on save holds a PNG that nothing will act on, and offering to+ * configure one would be offering a setting with nothing to apply it to.+ */+ compressibleFormats: ImageCompressibleFormat[];+ /** What {@link oversized} was measured against. */+ maxWidthHeight: number;+ /** Images whose content could not be read — protected, with no session open. Counted nowhere else. */+ unreadable: number;+ }++ export interface ImageCompressionOptions {+ /**+ * Whether an image larger than {@link maxWidthHeight} is scaled down to fit. On its own this+ * reaches only oversized images; one already within the bound is left exactly as it is.+ *+ * Defaults to on, as does {@link reencode}: the endpoint is only ever invoked deliberately, and+ * a request that asked for compression and got a no-op would be the surprising answer.+ */+ resize?: boolean;+ /** Longest edge in pixels. Omitted, it falls back to the `imageMaxWidthHeight` option. */+ maxWidthHeight?: number;+ /**+ * What is done with an image that is *already* lossy — a JPEG:+ *+ * - `keep` leaves its encoding alone. Scaling still has to write a JPEG back, but at a quality+ * high enough not to be a further deliberate degradation.+ * - `compress` recompresses it at {@link quality}, whatever its size. It costs quality every+ * time it runs, on an image that has already paid that cost once.+ *+ * Says nothing about lossless sources, which is {@link pngHandling}'s to answer: squeezing the+ * JPEGs harder is no reason to stop a PNG being a PNG. Defaults to `compress`.+ */+ jpegHandling?: ImageJpegHandling;+ /**+ * What is done with a lossless image — a PNG. Only ever one of the three, since a PNG either+ * survives as it is, survives smaller, or stops being a PNG:+ *+ * - `keep` leaves it entirely alone; scaling is then the only thing that can reach it.+ * - `optimize` reduces it to a palette and writes it back as a PNG. Lossy, but gently so — the+ * saving comes from storing an index per pixel rather than 24-bit colour — and it keeps the+ * alpha channel, so it reaches transparent images too.+ * - `jpeg` re-encodes it as a JPEG at {@link conversionQuality}, which usually saves the most+ * but costs the format. A transparent image cannot be converted, JPEG having no alpha channel+ * to keep it in, so it is optimized instead: the best that can be done for it.+ *+ * Defaults to `optimize`, the choice that shrinks an image without changing what it is.+ */+ pngHandling?: ImagePngHandling;+ /**+ * JPEG quality, 10 to 100, used when recompressing an image that is *already* lossy — so only+ * where {@link jpegHandling} is `compress`. A JPEG merely being scaled is written back at a+ * near-lossless quality of the implementation's own instead, `keep` meaning what it says.+ *+ * Omitted, it falls back to the `imageJpegQuality` option (75 by default).+ */+ quality?: number;+ /**+ * JPEG quality, 10 to 100, used when converting a lossless image — {@link pngHandling} of+ * `jpeg` — rather than when recompressing one that was lossy already.+ *+ * Its own setting because the two are not the same trade. Converting is a one-time transition+ * away from a pristine original, where every byte of quality given up is detail that genuinely+ * was there; recompressing works on an image that has already been through an encoder once, so+ * spending quality on it largely buys back nothing. Defaults higher than {@link quality}+ * accordingly.+ */+ conversionQuality?: number;+ /**+ * Whether the run visits the note's whole subtree rather than the note alone. Off by default,+ * and opt-in for a reason: a descendant may be a clone, so compressing it degrades an image+ * that other notes show too.+ *+ * Each note is visited once however many placements it has. Archived notes are included, the+ * hidden subtree is not, and a search note's results are left to whatever holds them — the run+ * follows the tree, not what a query happens to match.+ *+ * Only the note endpoint reads this; an attachment has no subtree to descend into.+ */+ recursive?: boolean;+ /**+ * Names a task to report progress against, so a caller watching a long run can be told how far+ * it has got. Left out, the run reports only when it finishes.+ */+ taskId?: string;+ }++ /**+ * Why a particular image was left exactly as it was. Every image the run visited is reported, so+ * "nothing happened" always comes with the reason it didn't.+ */+ export type ImageCompressionSkipReason =+ /** Not a format that can be recompressed — SVG, an unrecognised buffer, GIF, WebP, BMP … */+ | "unsupported-format"+ /** Animated (APNG, animated GIF/WebP): recompressing would flatten it to a single frame. */+ | "animated"+ /** The rendered picture of a canvas/mermaid/mind map/spreadsheet note, regenerated on save. */+ | "generated"+ /** Protected, with no protected session open to decrypt it. */+ | "protected"+ /**+ * Nothing was asked of this image that would change it — an image within the bound with+ * re-encoding off, or both switched off — or compressing it produced nothing smaller.+ */+ | "no-gain"+ /** This build has no image compression at all (the standalone/WASM runtime). */+ | "unsupported-platform"+ /**+ * Too many pixels to decode within the memory a single image is allowed. Read off the header,+ * so the image is refused before the attempt rather than after it has failed part-way.+ */+ | "too-large"+ /**+ * The image was replaced while it was being re-encoded — by another request, or by a+ * synchronisation update — so the result was derived from content that no longer exists. Writing+ * it would have put the superseded picture back; the newer one is kept instead.+ */+ | "changed"+ /**+ * The run was called off before reaching this image. Nothing was read and nothing weighed, so+ * it reports no size — it is here to be counted, so that a run stopped half way says so rather+ * than reporting the part it did as the whole.+ */+ | "cancelled"+ /** Compression failed; the original was kept and the failure logged. */+ | "error";++ /** One image visited by a compression run, whether or not it ended up compressed. */+ export interface ImageCompressionItem {+ entityType: "note" | "attachment";+ /** The `noteId` of an image note, or the `attachmentId` of an image attachment. */+ entityId: string;+ title: string;+ /** The mime after the run: the new one when compressed, the untouched one otherwise. */+ mime: string;+ originalSize: number;+ /** Equal to {@link originalSize} whenever the image was left alone. */+ newSize: number;+ compressed: boolean;+ /** Present exactly when {@link compressed} is false. */+ skipReason?: ImageCompressionSkipReason;+ }++ export interface ImageCompressionResponse {+ /** Every image the run visited, skipped ones included, in the order they were visited. */+ items: ImageCompressionItem[];+ compressedCount: number;+ skippedCount: number;+ /** Summed over {@link items}, so skipped images weigh the same on both sides. */+ originalSize: number;+ newSize: number;+ /** `originalSize - newSize`; never negative, an image is only replaced when it got smaller. */+ savedSize: number;+ }++ /**+ * The size components of a single note. Revisions are always reported separately so a client can+ * include or exclude them without another request.+ */+ export interface SpaceUsageSizes {+ /** Size of the note's own body. */+ ownSize: number;+ /** Combined size of the attachments owned by the note. */+ attachmentsSize: number;+ /** Combined size of the note's revisions, including attachments owned by those revisions. */+ revisionsSize: number;+ }++ export interface SpaceUsageOverviewNote extends SpaceUsageSizes {+ noteId: string;+ /**+ * Note IDs from a top-level note down to this note, following each note's canonical placement+ * (see the space usage service); the root itself is omitted.+ */+ notePath: string[];+ }++ /** An aggregate over notes that are not listed individually. */+ export interface SpaceUsageBucket {+ /** Note bodies plus attachments; revisions are in {@link revisionsSize}. */+ size: number;+ revisionsSize: number;+ noteCount: number;+ }++ /**+ * Space still held by deleted entities whose blobs have not been erased yet.+ *+ * {@link size} covers all of them at once — deleted notes, deleted attachments (whose owning note+ * may well be alive) and the history of deleted notes — so it is reported alongside both counts:+ * either one on its own reads as the whole story, and neither is.+ */+ export interface SpaceUsageDeletedNotes {+ size: number;+ /** Deleted notes whose body blob still exists; erased notes no longer count. */+ noteCount: number;+ /** Deleted attachments whose blob still exists, however their owning note is doing. */+ attachmentCount: number;+ }++ /**+ * Space held by attachments a live note still owns but no longer references from its content —+ * an image or file inserted and then removed. Saving the note schedules those for erasure, and the+ * scheduled cleanup erases them once `eraseUnusedAttachmentsAfterSeconds` has passed.+ *+ * Every scheduled attachment counts, not only those already past that delay, so the figure is what+ * erasing unused attachments *now* would remove.+ */+ export interface SpaceUsageUnusedAttachments {+ /**+ * What erasing them would actually reclaim: their blobs, counted once, minus any still held by+ * a live note body, a still-referenced attachment or a revision.+ */+ size: number;+ /** Attachments scheduled for erasure, whether or not something else shares their content. */+ attachmentCount: number;+ }++ /**+ * What the live content actually occupies — every blob referenced by a live note, attachment or+ * revision, hidden subtree included, counted once however many entities share it through+ * deduplication. The breakdown attributes each blob to exactly one tier — bodies first, then+ * attachments, then revisions — so the parts sum to {@link size} and each reads as "the space only+ * this category holds". The per-note numbers elsewhere intentionally count per entity instead, so+ * a note's reported size never depends on duplicates elsewhere.+ */+ export interface SpaceUsageContent {+ /** The whole live content; the "database size" figure. */+ size: number;+ /** Live notes, hidden ones included. */+ noteCount: number;+ /** Space only note-owned attachments hold: their blobs minus those shared with note bodies. */+ attachmentsSize: number;+ /** Space only revisions hold (snapshot attachments included): their blobs minus those shared+ * with live bodies or live attachments. */+ revisionsSize: number;+ }++ export interface SpaceUsageOverviewResponse {+ content: SpaceUsageContent;+ /** The largest notes first, ranked by body + attachments (+ revisions when requested). */+ notes: SpaceUsageOverviewNote[];+ /** The remaining notes of the visible tree, below the ranking cutoff. */+ otherNotes: SpaceUsageBucket;+ /** Notes reachable only through the hidden subtree, plus any note not reachable at all. */+ hiddenNotes: SpaceUsageBucket;+ deletedNotes: SpaceUsageDeletedNotes;+ unusedAttachments: SpaceUsageUnusedAttachments;+ /** Every note of the visible tree: {@link notes} and {@link otherNotes} combined. */+ total: SpaceUsageBucket;+ }++ export interface SpaceUsageChild {+ noteId: string;+ /** Bodies plus attachments of the child's whole canonical subtree; revisions are left out. */+ subtreeSize: number;+ subtreeNoteCount: number;+ }++ export interface SpaceUsageAttachment {+ attachmentId: string;+ title: string;+ role: string;+ size: number;+ }++ export interface SpaceUsageNoteResponse extends SpaceUsageSizes {+ noteId: string;+ /**+ * What the note alone actually occupies — body, attachments and revisions, each shared blob+ * counted once. Smaller than the per-entity components sum whenever revisions still share the+ * note's blob or attachments repeat content.+ */+ noteContentSize: number;+ /** Like {@link noteContentSize}, over the note's whole canonical subtree. */+ subtreeContentSize: number;+ /**+ * An estimate of what trimming the subtree's history would reclaim: blobs held only by the+ * snapshots that would go, each counted once, and none that a live body, a note attachment or a+ * surviving snapshot still shares. Tiered like the database-wide figure, so the two are+ * comparable — unlike the per-entity {@link revisionsSize}, which counts a shared snapshot at+ * every entity holding it.+ *+ * How far that trimming goes is the request's own {@link EraseExcessRevisionsOptions}: by+ * default every snapshot goes, which is the whole history. The limit asked for stands for every+ * note at once, so a note whose `#versioningLimit` keeps more than that frees less than this+ * figure allows for — an estimate reading high, not a promise.+ */+ subtreeRevisionsContentSize: number;+ attachments: SpaceUsageAttachment[];+ /** Canonical children only: a cloned child is listed under its canonical parent alone. */+ children: SpaceUsageChild[];+ /** Only present on the root, deleted notes having no place in the tree. */+ deletedNotes?: SpaceUsageDeletedNotes;+ /** Only present on the root: a database-wide figure, like the deleted one beside it. */+ unusedAttachments?: SpaceUsageUnusedAttachments;+ }+export interface SimilarNote {score: number;notePath: string[];diff --cc packages/trilium-core/src/routes/api/options.tsindex 8d02b55233,10b7a1f9d5..72e54358cd--- a/packages/trilium-core/src/routes/api/options.ts+++ b/packages/trilium-core/src/routes/api/options.ts@@@ -118,9 -141,10 +141,11 @@@ const ALLOWED_OPTIONS = new Set<OptionN"layoutOrientation","backgroundEffects","allowedHtmlTags",+ "cleanupToolOptions",+ "imageCompressionToolOptions","searchEnableFuzzyMatching","searchAutocompleteFuzzy",+ "searchResultsPageSize","redirectBareDomain","showLoginInShareTheme","splitEditorOrientation",diff --cc packages/trilium-core/src/routes/api/search.spec.tsindex b525816f2d,85dd5c7b18..539bff71cb--- a/packages/trilium-core/src/routes/api/search.spec.ts+++ b/packages/trilium-core/src/routes/api/search.spec.ts@@@ -1,4 -1,4 +1,4 @@@- import type { SearchResultDetailsResponse } from "@triliumnext/commons";-import { dayjs, type TemplatesResponse } from "@triliumnext/commons";++import { dayjs, type SearchResultDetailsResponse, type TemplatesResponse } from "@triliumnext/commons";import { beforeAll, describe, expect, it } from "vitest";import { createTextNote } from "../../test/api_fixtures";@@@ -122,111 -100,29 +123,136 @@@ describe("Search API (core)", () =>const res = await api.post("/api/search-and-execute-note/root");expect(res.status).toBe(400);});++ describe("result-details endpoint", () => {+ it("returns snippet details in requested order with highlightedTokenInfos", async () => {+ const token = "ZzDetailsUniqueQwerty";+ const alpha = await createTextNote(api, {+ title: `${token} Alpha`,+ content: `<p>${token} shows up in the alpha body text</p>`+ });+ const beta = await createTextNote(api, {+ title: `${token} Beta`,+ content: `<p>${token} shows up in the beta body text</p>`+ });+ await api.post(`/api/notes/${alpha.noteId}/attributes`, {+ body: { type: "label", name: token, value: "" }+ });++ const searchNoteId = await createSearchNote(token);++ // Request in the reverse of natural order to prove requested-order preservation.+ const res = await api.post<SearchResultDetailsResponse>(+ `/api/search-note/${searchNoteId}/result-details`,+ { body: { noteIds: [beta.noteId, alpha.noteId] } }+ );++ expect(res.status).toBe(200);+ expect(res.body.results.map((r) => r.noteId)).toEqual([beta.noteId, alpha.noteId]);+ expect(res.body.error).toBeNull();++ const alphaDetail = res.body.results.find((r) => r.noteId === alpha.noteId);+ expect(alphaDetail?.noteTitle).toContain(token);+ expect(alphaDetail?.notePath).toContain(alpha.noteId);+ expect(alphaDetail?.icon).toBeTruthy();+ expect(alphaDetail?.contentSnippet).toContain(token);+ expect(alphaDetail?.highlightedContentSnippet).toContain(`<b>${token}</b>`);+ expect(alphaDetail?.attributeSnippet).toContain(token);++ expect(+ res.body.highlightedTokenInfos.some(+ (t) => t.token.toLowerCase() === token.toLowerCase() && t.type === "plain"+ )+ ).toBe(true);+ });++ it("omits requested ids that are not in the result set", async () => {+ const token = "ZzOmitUniqueQwerty";+ const inScope = await createTextNote(api, { title: `${token} note`, content: `<p>${token}</p>` });+ const outOfScope = await createTextNote(api, { title: "Unrelated note", content: "<p>nothing here</p>" });++ const searchNoteId = await createSearchNote(token);++ const res = await api.post<SearchResultDetailsResponse>(+ `/api/search-note/${searchNoteId}/result-details`,+ { body: { noteIds: [inScope.noteId, outOfScope.noteId, "nonexistentNoteId"] } }+ );++ expect(res.status).toBe(200);+ expect(res.body.results.map((r) => r.noteId)).toEqual([inScope.noteId]);+ });++ it("400s on a note that is not a search note", async () => {+ const res = await api.post("/api/search-note/root/result-details", { body: { noteIds: [] } });+ expect(res.status).toBe(400);+ });++ it("400s when more than 100 noteIds are requested", async () => {+ const searchNoteId = await createSearchNote("anything");+ const noteIds = Array.from({ length: 101 }, (_, i) => `note${i}`);++ const res = await api.post(`/api/search-note/${searchNoteId}/result-details`, {+ body: { noteIds }+ });+ expect(res.status).toBe(400);+ });++ it("400s when noteIds is not a string array", async () => {+ const searchNoteId = await createSearchNote("anything");++ const res = await api.post(`/api/search-note/${searchNoteId}/result-details`, {+ body: { noteIds: "not-an-array" }+ });+ expect(res.status).toBe(400);+ });++ it("produces a regex token info and a match-centered snippet for a %= query", async () => {+ const marker = "ZzRegexHaystackQwerty";+ const target = await createTextNote(api, {+ title: "Regex target",+ content: `<p>${"padding words ".repeat(30)}${marker}${" trailing words".repeat(30)}</p>`+ });++ const searchNoteId = await createSearchNote(`note.content %= '${marker}'`);++ const res = await api.post<SearchResultDetailsResponse>(+ `/api/search-note/${searchNoteId}/result-details`,+ { body: { noteIds: [target.noteId] } }+ );++ expect(res.status).toBe(200);+ expect(res.body.highlightedTokenInfos.some((t) => t.type === "regex")).toBe(true);++ const detail = res.body.results.find((r) => r.noteId === target.noteId);+ expect(detail?.contentSnippet).toContain(marker);+ expect(detail?.highlightedContentSnippet).toContain(`<b>${marker}</b>`);+ // Match-centered: the padding-heavy head is trimmed to an ellipsis, not shown from index 0.+ expect(detail?.contentSnippet?.startsWith("padding words padding")).toBe(false);+ });+ });});++ describe("isNewTemplate", () => {+ const ROOT_CREATED = "2026-01-01 00:00:00.000Z";+ const utc = (date: dayjs.Dayjs) => date.format("YYYY-MM-DD HH:mm:ss.SSS[Z]");++ it("marks recent templates as new and leaves older ones alone", () => {+ expect(isNewTemplate(utc(dayjs.utc().subtract(1, "day")), ROOT_CREATED)).toBe(true);+ expect(isNewTemplate(utc(dayjs.utc().subtract(4, "day")), ROOT_CREATED)).toBe(false);+ expect(isNewTemplate(null, ROOT_CREATED)).toBe(false);+ });++ it("never marks the predefined templates set up alongside the root note", () => {+ const root = dayjs.utc().subtract(1, "hour");+ // Created together with the database: within the grace period, so not new+ // despite being only an hour old.+ expect(isNewTemplate(utc(root.add(10, "second")), utc(root))).toBe(false);+ // Added later on, e.g. by an upgrade.+ expect(isNewTemplate(utc(root.add(1, "minute")), utc(root))).toBe(true);+ });++ it("falls back to the age check when the root creation date is unknown", () => {+ expect(isNewTemplate(utc(dayjs.utc()), null)).toBe(true);+ expect(isNewTemplate(utc(dayjs.utc().subtract(4, "day")), undefined)).toBe(false);+ });+ });diff --cc packages/trilium-core/src/routes/api/search.tsindex 4d85eeca32,795f796e80..457552358f--- a/packages/trilium-core/src/routes/api/search.ts+++ b/packages/trilium-core/src/routes/api/search.ts@@@ -1,4 -1,4 +1,4 @@@- import type { SearchResultDetails, SearchResultDetailsRequest, SearchResultDetailsResponse } from "@triliumnext/commons";-import { dayjs, type TemplatesResponse } from "@triliumnext/commons";++import { dayjs, type SearchResultDetails, type SearchResultDetailsRequest, type SearchResultDetailsResponse, type TemplatesResponse } from "@triliumnext/commons";import type { Request } from "express";import becca from "../../becca/becca.js";@@@ -10,8 -9,15 +10,14 @@@ import SearchContext from "../../servicimport type SearchResult from "../../services/search/search_result.js";import searchService, { EMPTY_RESULT, type SearchNoteResult } from "../../services/search/services/search.js";import { ValidationError } from "../../errors.js";-import becca_service from "../../becca/becca_service.js";import { getHoistedNoteId } from "../../services/context.js";+ /** The maximum age in days for a template to be marked as new. */+ const NEW_TEMPLATE_MAX_AGE = 3;++ /** The number of seconds after the root note's creation during which templates count as predefined. */+ const INITIAL_SETUP_GRACE_PERIOD = 30;+function searchFromNote(req: Request<{ noteId: string }>): SearchNoteResult {const note = becca.getNoteOrThrow(req.params.noteId);diff --cc packages/trilium-core/src/services/search/expressions/note_content_fulltext_preprocessor.spec.tsindex 94b26ec6b6,889f0f99af..f552f5cfbe--- 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,91 -39,54 +39,139 @@@ 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.+ // The appended title is normalized (lowercased) to match the normalized body.+ 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("normalizes injected link text so a lowercased single-token query matches", () => {+ // Extraction runs against the case-preserved original (so link-target noteIds resolve),+ // but the APPENDED text must be lowercased and diacritic-stripped: the default single-token+ // content match lowercases the query token and does a raw includes(), so `zurich` must hit+ // a linked "Zürich" (and `special` a linked "Special Topic") in phase 1, not only via fuzzy.+ const html = `<p><a href="#root/city1" class="reference-link"></a></p>`;+ const result = preprocessContent(html, type, mime, false, (id) => (id === "city1" ? "Zürich" : null));+ expect(result).toContain("zurich");+ expect(result).not.toContain("Zürich");+ });++ 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. Injected metadata is normalized (lowercased).+ 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("Spreadsheet preprocessing", () => {+ const type: NoteType = "spreadsheet";+ const mime = "application/json";++ it("supports empty / invalid JSON", () => {+ expect(preprocessContent("{}", type, mime)).toEqual("");+ expect(preprocessContent("", type, mime)).toEqual("");+ });++ it("reads visible cell values", () => {+ const workbook = JSON.stringify({+ workbook: {+ sheets: {+ s1: { cellData: { 0: { 0: { v: "Revenue" }, 1: { v: 42 } } } }+ }+ }+ });+ expect(preprocessContent(workbook, type, mime)).toEqual("revenue 42");+ });+ });++ describe("Text (HTML) preprocessing", () => {+ const type: NoteType = "text";+ const mime = "text/html";++ it("surfaces link-preview title, url and description from data attributes", () => {+ const content = `<section class="link-embed" data-url="https://en.wikipedia.org/wiki/The_Terminator" data-title="The Terminator - Wikipedia" data-description="A 1984 science fiction film."> </section>`;+ const result = preprocessContent(content, type, mime);++ expect(result).toContain("the terminator - wikipedia");+ expect(result).toContain("https://en.wikipedia.org/wiki/the_terminator");+ expect(result).toContain("a 1984 science fiction film.");+ });++ it("keeps the markup but still unescapes entities when raw is requested", () => {+ const result = preprocessContent("<p>Hello world</p>", type, mime, true);+ expect(result).toEqual("<p>hello world</p>");+ });+ });++ describe("Unhandled type/mime combinations", () => {+ it("returns the normalized content untouched", () => {+ // Neither the type nor the mime matches any branch, so no extractor runs.+ expect(preprocessContent("Plain Text", "code", "text/plain")).toEqual("plain text");+ expect(preprocessContent("{}", "llmChat", "text/plain")).toEqual("{}");+ });+ });+describe("LLM chat preprocessing", () => {const type: NoteType = "llmChat";const mime = "application/json";diff --cc packages/trilium-core/src/services/search/services/search.spec.tsindex 40cffa1c40,7eb1a774ac..f157b45aa9--- a/packages/trilium-core/src/services/search/services/search.spec.ts+++ b/packages/trilium-core/src/services/search/services/search.spec.ts@@@ -5,10 -5,12 +5,14 @@@ import BBranch from "../../../becca/entimport SearchContext from "../search_context.js";import dateUtils from "../../utils/date.js";import becca from "../../../becca/becca.js";+import { getContext } from "../../context.js";+import noteService from "../../notes.js";+ import protectedSessionService from "../../protected_session.js";+ import { encodeUtf8 } from "../../utils/binary.js";import { findNoteByTitle, note, NoteBuilder } from "../../../test/becca_mocking.js";+ const PROTECTED_KEY = encodeUtf8("0123456789abcdef"); // exactly 16 bytes+describe("Search", () => {let rootNote: any;diff --cc packages/trilium-core/src/services/search/services/search.tsindex e8e4684362,d5290ee1da..ed49364f52--- a/packages/trilium-core/src/services/search/services/search.ts+++ b/packages/trilium-core/src/services/search/services/search.ts@@@ -5,12 -5,12 +5,12 @@@ import striptags from "striptags"import becca from "../../../becca/becca.js";import becca_service from "../../../becca/becca_service.js";import type BNote from "../../../becca/entities/bnote.js";+ import blobService from "../../blob.js";import hoistedNoteService from "../../hoisted_note.js";import { getLog } from "../../log.js";- import protectedSessionService from "../../protected_session.js";import scriptService from "../../script.js";import { isScriptingEnabled } from "../../scripting_guard.js";- import { escapeHtml, escapeRegExp, normalizePreservingLength } from "../../utils/index.js";-import { escapeHtml, escapeRegExp, unescapeHtml } from "../../utils/index.js";++import { escapeHtml, escapeRegExp, normalizePreservingLength, unescapeHtml } from "../../utils/index.js";import type Expression from "../expressions/expression.js";import SearchContext from "../search_context.js";import SearchResult from "../search_result.js";@@@ -770,22 -729,29 +773,24 @@@ function buildSearchResultDetails(resul}/**+ * @param tokens the tokens to highlight, either legacy plain strings or structured+ * {@link HighlightedTokenInfo}s (regex-aware). Legacy strings are treated as plain.* @param ignoreInternalAttributes whether to ignore certain attributes from the search such as ~internalLink.*/-function highlightSearchResults(searchResults: SearchResult[], highlightedTokens: string[], ignoreInternalAttributes = false) {- highlightedTokens = Array.from(new Set(highlightedTokens));-- // { and } are used for marking <b> and </b> tags (to avoid matches on a single 'b' character),- // so a token containing either would overwrite the markers already placed in the text.- highlightedTokens = highlightedTokens.map((token) => token.replace(/[{}]/g, "")).filter((token) => !!token?.trim());-- // sort by the longest, so we first highlight the longest matches- highlightedTokens.sort((a, b) => (a.length > b.length ? -1 : 1));+function highlightSearchResults(searchResults: SearchResult[], tokens: HighlightedTokenInfo[] | string[], ignoreInternalAttributes = false) {+ const tokenInfos = normalizeHighlightTokens(tokens);+ // Highlighting runs on the text as written, and the result is escaped afterwards. Escaping+ // first would let a token match inside an entity (searching for "lt" would cut < in half),+ // and stripping the offending characters instead would silently mangle the text - a title+ // like "Issues caused by <div>" would lose its opening bracket.+ // The only characters that have to go are the { } markers themselves.for (const result of searchResults) {- result.highlightedNotePathTitle = result.notePathTitle.replace(/[<{}]/g, "");+ result.highlightedNotePathTitle = result.notePathTitle.replace(/[{}]/g, "");- // Initialize highlighted content snippet+ // Initialize highlighted content snippet, preserving newlines for later conversion to <br>if (result.contentSnippet) {- // Escape HTML but preserve newlines for later conversion to <br>- result.highlightedContentSnippet = escapeHtml(result.contentSnippet);- // Remove any stray < { } that might interfere with our highlighting markers- result.highlightedContentSnippet = result.highlightedContentSnippet.replace(/[<{}]/g, "");+ result.highlightedContentSnippet = result.contentSnippet.replace(/[{}]/g, "");}// Initialize highlighted attribute snippet@@@ -838,109 -841,3 +838,114 @@@ export defaultextractAttributeSnippet,highlightSearchResults};++/** Widens a legacy `string[]` (all plain) or a structured token-info list to token infos. */+function toTokenInfos(tokens: HighlightedTokenInfo[] | string[]): HighlightedTokenInfo[] {+ return tokens.map((token) => (typeof token === "string" ? { token, type: "plain" } : token));+}++/** Index of the first match of a token within already-normalized text, or -1 if none. */+function tokenInfoFirstIndex(info: HighlightedTokenInfo, normalizedText: string): number {+ if (info.type === "regex") {+ try {+ const match = new RegExp(info.token, "gi").exec(normalizedText);+ return match ? match.index : -1;+ } catch {+ return -1; // Skip invalid regex patterns.+ }+ }++ return normalizedText.indexOf(normalizePreservingLength(info.token));+}++/** Whether a token matches anywhere within already-normalized text. */+function tokenInfoMatches(info: HighlightedTokenInfo, normalizedText: string): boolean {+ return tokenInfoFirstIndex(info, normalizedText) !== -1;+}++/**+ * Normalizes the highlight token input for {@link highlightSearchResults}: widens+ * legacy strings to plain token infos, strips marker/angle characters from plain+ * tokens (regex patterns are kept verbatim), drops blanks, dedupes, and sorts+ * longest-first so longer matches win before shorter ones.+ */+function normalizeHighlightTokens(tokens: HighlightedTokenInfo[] | string[]): HighlightedTokenInfo[] {+ const seen = new Set<string>();+ const result: HighlightedTokenInfo[] = [];++ for (const info of toTokenInfos(tokens)) {+ // { } are used as <b>/</b> markers and < can break the surrounding HTML, so we+ // strip them from plain tokens; regex patterns keep them (e.g. `a{2}` quantifiers).+ const token = info.type === "regex" ? info.token : info.token.replace(/[<>{}]/g, "");++ if (!token.trim() || seen.has(token)) {+ continue;+ }++ seen.add(token);+ result.push({ token, type: info.type });+ }++ result.sort((a, b) => (a.token.length > b.token.length ? -1 : 1));++ return result;+}++/** Builds the case-insensitive matching regex for a token, or null for an invalid regex pattern. */+function buildHighlightRegex(info: HighlightedTokenInfo): RegExp | null {+ if (info.type === "regex") {+ try {+ return new RegExp(info.token, "gi");+ } catch {+ return null; // Skip invalid regex patterns.+ }+ }++ return new RegExp(escapeRegExp(info.token), "gi");+}++/**+ * Wraps every match of one token in a single field with `{`/`}` markers (later+ * turned into `<b>`/`</b>`). Match positions are found on a length-preserving+ * normalization so they align 1:1 with the original field. The wrap count is+ * capped to bound pathological regex patterns, and zero-width matches break the+ * loop rather than spin forever.+ */+function highlightField(field: string | undefined, info: HighlightedTokenInfo): string | undefined {+ if (!field) {+ return field;+ }++ const regex = buildHighlightRegex(info);+ if (!regex) {+ return field;+ }++ let match: RegExpExecArray | null;+ let wraps = 0;+ while ((match = regex.exec(normalizePreservingLength(field))) !== null) {+ const matchLength = match[0].length;+ if (matchLength === 0) {+ break; // Zero-width match can't be highlighted; avoid an infinite loop.+ }++ field = wrapText(field, match.index, matchLength, "{", "}");+ // Two marker characters were inserted, so advance past them as well.+ regex.lastIndex += 2;++ if (++wraps >= MAX_HIGHLIGHT_WRAPS) {+ break;+ }+ }++ return field;+}++function wrapText(text: string, start: number, length: number, prefix: string, suffix: string) {+ return text.substring(0, start) + prefix + text.substr(start, length) + suffix + text.substring(start + length);+}++++/** Escapes the text for display, then turns the { } markers into the <b> tags they stand for. */++function renderHighlights(text: string) {++ return escapeHtml(text).replace(/{/g, "<b>").replace(/}/g, "</b>");++}