Skip to content

Build your personal knowledge base with Trilium Notes

fix(client): diacritic and regex aware search highlighting

perfectra1n87be0263a6ac
diff --git a/apps/client/src/entities/fnote.ts b/apps/client/src/entities/fnote.ts
index 5e05617846..2fa7dabc06 100644
--- a/apps/client/src/entities/fnote.ts
+++ b/apps/client/src/entities/fnote.ts
@@ -1,4 +1,4 @@
-import { getNoteIcon } from "@triliumnext/commons";
+import { getNoteIcon, HighlightedTokenInfo } from "@triliumnext/commons";
import bundleService from "../services/bundle.js";
import cssClassManager from "../services/css_class_manager.js";
@@ -74,6 +74,9 @@ export default class FNote {
// Managed by Froca.
searchResultsLoaded?: boolean;
highlightedTokens?: string[];
+ /** Structured, diacritic/regex-aware counterpart of {@link highlightedTokens}; prefer this
+ * when present. */
+ highlightedTokenInfos?: HighlightedTokenInfo[];
constructor(froca: Froca, row: FNoteRow) {
this.froca = froca;
diff --git a/apps/client/src/services/froca.spec.ts b/apps/client/src/services/froca.spec.ts
index b7a5eb9412..5bc66d6c89 100644
--- a/apps/client/src/services/froca.spec.ts
+++ b/apps/client/src/services/froca.spec.ts
@@ -303,10 +303,30 @@ describe("loadSearchNote", () => {
expect(out).toEqual({ error: null });
expect(search.searchResultsLoaded).toBe(true);
expect(search.highlightedTokens).toEqual(["token"]);
+ // No highlightedTokenInfos in the response (older/rolling-upgrade server) - derive it from the legacy field.
+ expect(search.highlightedTokenInfos).toEqual([{ token: "token", type: "plain" }]);
expect(search.children).toContain(result.noteId);
expect(search.children).not.toContain("stale");
});
+ it("stores the server's structured highlightedTokenInfos as-is when present", async () => {
+ const search = buildNote({ id: "ls-structured", title: "Search", type: "search" });
+
+ server.get = vi.fn(async () => ({
+ searchResultNoteIds: [],
+ highlightedTokens: ["ktory"],
+ highlightedTokenInfos: [{ token: "ktory", type: "plain" }, { token: "ba.", type: "regex" }],
+ error: null
+ })) as typeof server.get;
+
+ await froca.loadSearchNote(search.noteId);
+
+ expect(search.highlightedTokenInfos).toEqual([
+ { token: "ktory", type: "plain" },
+ { token: "ba.", type: "regex" }
+ ]);
+ });
+
it("tolerates the note disappearing from the cache mid-load", async () => {
const search = buildNote({ id: "ls-gone", title: "Search", type: "search" });
const result = buildNote({ id: "ls-gone-result", title: "Result", type: "text" });
diff --git a/apps/client/src/services/froca.ts b/apps/client/src/services/froca.ts
index 4be564d921..aeff8d4434 100644
--- a/apps/client/src/services/froca.ts
+++ b/apps/client/src/services/froca.ts
@@ -1,3 +1,5 @@
+import type { HighlightedTokenInfo } from "@triliumnext/commons";
+
import appContext from "../components/app_context.js";
import FAttachment, { type FAttachmentRow } from "../entities/fattachment.js";
import FAttribute, { type FAttributeRow } from "../entities/fattribute.js";
@@ -17,6 +19,9 @@ interface SubtreeResponse {
interface SearchNoteResponse {
searchResultNoteIds: string[];
highlightedTokens: string[];
+ /** Additive; absent from older cached responses (e.g. during a rolling upgrade), so fall
+ * back to {@link highlightedTokens}. */
+ highlightedTokenInfos?: HighlightedTokenInfo[];
error: string | null;
}
@@ -199,7 +204,8 @@ class FrocaImpl implements Froca {
return;
}
- const { searchResultNoteIds, highlightedTokens, error } = await server.get<SearchNoteResponse>(`search-note/${note.noteId}`);
+ const { searchResultNoteIds, highlightedTokens, highlightedTokenInfos, error } =
+ await server.get<SearchNoteResponse>(`search-note/${note.noteId}`);
if (!Array.isArray(searchResultNoteIds)) {
throw new Error(`Search note '${note.noteId}' failed: ${searchResultNoteIds}`);
@@ -233,6 +239,8 @@ class FrocaImpl implements Froca {
froca.notes[note.noteId].searchResultsLoaded = true;
froca.notes[note.noteId].highlightedTokens = highlightedTokens;
+ froca.notes[note.noteId].highlightedTokenInfos = highlightedTokenInfos
+ ?? highlightedTokens.map((token) => ({ token, type: "plain" as const }));
return { error };
}
diff --git a/apps/client/src/widgets/collections/NoteList.tsx b/apps/client/src/widgets/collections/NoteList.tsx
index dab80c2086..012f564082 100644
--- a/apps/client/src/widgets/collections/NoteList.tsx
+++ b/apps/client/src/widgets/collections/NoteList.tsx
@@ -1,6 +1,6 @@
import "./NoteList.css";
-import { WebSocketMessage } from "@triliumnext/commons";
+import { HighlightedTokenInfo, WebSocketMessage } from "@triliumnext/commons";
import { Component, VNode } from "preact";
import { lazy, Suspense } from "preact/compat";
import { useEffect, useRef, useState } from "preact/hooks";
@@ -16,7 +16,7 @@ import ViewModeStorage, { type ViewModeStorageType } from "./view_mode_storage";
interface NoteListProps {
note: FNote | null | undefined;
notePath: string | null | undefined;
- highlightedTokens?: string[] | null;
+ highlightedTokens?: (string | HighlightedTokenInfo)[] | null;
/** if set to `true` then only collection-type views are displayed such as geo-map and the calendar. The original book types grid and list will be ignored. */
displayOnlyCollections?: boolean;
isEnabled: boolean;
diff --git a/apps/client/src/widgets/collections/dashboard/index.tsx b/apps/client/src/widgets/collections/dashboard/index.tsx
index d043c1487e..9f797c4eff 100644
--- a/apps/client/src/widgets/collections/dashboard/index.tsx
+++ b/apps/client/src/widgets/collections/dashboard/index.tsx
@@ -1,6 +1,7 @@
import "./index.css";
import "gridstack/dist/gridstack.min.css";
+import type { HighlightedTokenInfo } from "@triliumnext/commons";
import { clsx } from "clsx";
import { GridStack } from "gridstack";
import { RefObject, TargetedMouseEvent } from "preact";
@@ -309,7 +310,7 @@ function useNoteTreeDropToDashboard(note: FNote, includeArchived: boolean, dropA
interface DashboardWidgetProps {
note: FNote;
parentNote: FNote;
- highlightedTokens: string[] | null | undefined;
+ highlightedTokens: (string | HighlightedTokenInfo)[] | null | undefined;
includeArchived: boolean;
showTextRepresentation?: boolean;
}
diff --git a/apps/client/src/widgets/collections/interface.ts b/apps/client/src/widgets/collections/interface.ts
index c8b9c2401a..f665948098 100644
--- a/apps/client/src/widgets/collections/interface.ts
+++ b/apps/client/src/widgets/collections/interface.ts
@@ -1,3 +1,5 @@
+import type { HighlightedTokenInfo } from "@triliumnext/commons";
+
import FNote from "../../entities/fnote";
import type { PrintReport } from "../../print";
@@ -15,7 +17,7 @@ export interface ViewModeProps<T extends object> {
* We're using noteIds so that it's not necessary to load all notes at once when paging.
*/
noteIds: string[];
- highlightedTokens: string[] | null | undefined;
+ highlightedTokens: (string | HighlightedTokenInfo)[] | null | undefined;
viewConfig: T | undefined;
saveConfig(newConfig: T): void;
media: ViewModeMedia;
diff --git a/apps/client/src/widgets/collections/legacy/ListOrGridView.tsx b/apps/client/src/widgets/collections/legacy/ListOrGridView.tsx
index 9a4cb63201..f0783682d0 100644
--- a/apps/client/src/widgets/collections/legacy/ListOrGridView.tsx
+++ b/apps/client/src/widgets/collections/legacy/ListOrGridView.tsx
@@ -1,6 +1,7 @@
import "./ListOrGridView.css";
import { Card, CardFrame, CardSection } from "../../react/Card";
+import type { HighlightedTokenInfo } from "@triliumnext/commons";
import { useCallback, useEffect, useRef, useState } from "preact/hooks";
import FNote from "../../../entities/fnote";
@@ -98,7 +99,7 @@ function ListNoteCard({ note, parentNote, highlightedTokens, currentLevel, expan
parentNote: FNote,
currentLevel: number,
expandDepth: number,
- highlightedTokens: string[] | null | undefined;
+ highlightedTokens: (string | HighlightedTokenInfo)[] | null | undefined;
includeArchived: boolean;
showTextRepresentation?: boolean;
}) {
@@ -159,7 +160,7 @@ function ListNoteCard({ note, parentNote, highlightedTokens, currentLevel, expan
interface GridNoteCardProps {
note: FNote;
parentNote: FNote;
- highlightedTokens: string[] | null | undefined;
+ highlightedTokens: (string | HighlightedTokenInfo)[] | null | undefined;
includeArchived: boolean;
showTextRepresentation?: boolean;
}
@@ -211,7 +212,7 @@ export function NoteContent({ note, trim, noChildrenList, highlightedTokens, inc
note: FNote;
trim?: boolean;
noChildrenList?: boolean;
- highlightedTokens: string[] | null | undefined;
+ highlightedTokens: (string | HighlightedTokenInfo)[] | null | undefined;
includeArchivedNotes: boolean;
showTextRepresentation?: boolean;
/** Render live interactive type widgets (e.g. web views) instead of static previews. */
@@ -295,7 +296,7 @@ function NoteChildren({ note, parentNote, highlightedTokens, currentLevel, expan
parentNote: FNote,
currentLevel: number,
expandDepth: number,
- highlightedTokens: string[] | null | undefined
+ highlightedTokens: (string | HighlightedTokenInfo)[] | null | undefined
includeArchived: boolean;
}) {
const [ childNotes, setChildNotes ] = useState<FNote[]>();
diff --git a/apps/client/src/widgets/react/NoteLink.tsx b/apps/client/src/widgets/react/NoteLink.tsx
index 55505286ea..4b5854274f 100644
--- a/apps/client/src/widgets/react/NoteLink.tsx
+++ b/apps/client/src/widgets/react/NoteLink.tsx
@@ -1,3 +1,4 @@
+import type { HighlightedTokenInfo } from "@triliumnext/commons";
import clsx from "clsx";
import { HTMLAttributes } from "preact";
import { useEffect, useRef, useState } from "preact/hooks";
@@ -16,7 +17,7 @@ interface NoteLinkOpts {
style?: Record<string, string | number>;
noPreview?: boolean;
noTnLink?: boolean;
- highlightedTokens?: string[] | null | undefined;
+ highlightedTokens?: (string | HighlightedTokenInfo)[] | null | undefined;
// Override the text of the link, otherwise the note title is used.
title?: string;
/** Inline text appended right after the link title (before the note path). */
diff --git a/apps/client/src/widgets/react/hooks.spec.tsx b/apps/client/src/widgets/react/hooks.spec.tsx
index 13843a0bf6..035a2623ba 100644
--- a/apps/client/src/widgets/react/hooks.spec.tsx
+++ b/apps/client/src/widgets/react/hooks.spec.tsx
@@ -1,10 +1,11 @@
+import type { HighlightedTokenInfo } from "@triliumnext/commons";
import { Tooltip } from "bootstrap";
import { render } from "preact";
import { useRef } from "preact/hooks";
import { act } from "preact/test-utils";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { type DelayedVisibilityPhase, useDelayedVisibility, useStaticTooltip } from "./hooks";
+import { type DelayedVisibilityPhase, useDelayedVisibility, useImperativeSearchHighlighlighting, useStaticTooltip } from "./hooks";
let currentPhase: DelayedVisibilityPhase | undefined;
@@ -126,3 +127,79 @@ describe("useStaticTooltip", () => {
expect(document.querySelector(".tooltip")).toBeNull();
});
});
+
+describe("useImperativeSearchHighlighlighting", () => {
+ let container: HTMLElement;
+ let target: HTMLElement;
+
+ beforeEach(() => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ target = document.createElement("div");
+ document.body.appendChild(target);
+ });
+
+ afterEach(() => {
+ render(null, container);
+ container.remove();
+ target.remove();
+ });
+
+ 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);
+ }
+
+ 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ý"]);
+ });
+
+ it("wraps a CJK substring match inside a larger word", () => {
+ const el = highlight(["笔记"], "<p>我的笔记本</p>");
+ expect(markedTexts(el)).toEqual(["笔记"]);
+ });
+
+ 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"]);
+ });
+
+ it("skips an invalid regex token without throwing", () => {
+ expect(() => highlight([{ token: "(unterminated", type: "regex" }], "<p>foo bar</p>")).not.toThrow();
+ expect(markedTexts(target)).toEqual([]);
+ });
+
+ it("still highlights when given legacy string[] input", () => {
+ const el = highlight(["bar"], "<p>foo bar baz</p>");
+ expect(markedTexts(el)).toEqual(["bar"]);
+ });
+
+ it("is a no-op for null or undefined tokens", () => {
+ expect(() => highlight(null, "<p>foo bar</p>")).not.toThrow();
+ expect(markedTexts(target)).toEqual([]);
+
+ expect(() => highlight(undefined, "<p>foo bar</p>")).not.toThrow();
+ expect(markedTexts(target)).toEqual([]);
+ });
+});
diff --git a/apps/client/src/widgets/react/hooks.tsx b/apps/client/src/widgets/react/hooks.tsx
index 2003a7484d..0873fed9af 100644
--- a/apps/client/src/widgets/react/hooks.tsx
+++ b/apps/client/src/widgets/react/hooks.tsx
@@ -1,5 +1,5 @@
import type { CKTextEditor } from "@triliumnext/ckeditor5";
-import { FilterLabelsByType, KeyboardActionNames, NoteType, OptionNames, RelationNames } from "@triliumnext/commons";
+import { FilterLabelsByType, HighlightedTokenInfo, KeyboardActionNames, NoteType, OptionNames, RelationNames } from "@triliumnext/commons";
import { Tooltip } from "bootstrap";
import Mark from "mark.js";
import { Ref, RefObject, VNode } from "preact";
@@ -25,7 +25,7 @@ import SpacedUpdate, { type StateCallback } from "../../services/spaced_update";
import { getEffectiveThemeStyle } from "../../services/theme";
import toast, { ToastOptions } from "../../services/toast";
import tree from "../../services/tree";
-import utils, { escapeRegExp, getErrorMessage, randomString, reloadFrontendApp } from "../../services/utils";
+import utils, { getErrorMessage, randomString, reloadFrontendApp } from "../../services/utils";
import ws from "../../services/ws";
import BasicWidget, { ReactWrappedWidget } from "../basic_widget";
import NoteContextAwareWidget from "../note_context_aware_widget";
@@ -1211,26 +1211,64 @@ export function useSyncedRef<T>(externalRef?: Ref<T>, initialValue: T | null = n
return ref;
}
-export function useImperativeSearchHighlighlighting(highlightedTokens: string[] | null | undefined) {
+/** Longer regex tokens are rejected outright rather than compiled, to avoid pathological patterns. */
+const MAX_REGEX_TOKEN_LENGTH = 1000;
+/** Caps the number of matches a single regex token can wrap, mirroring the cap mark.js's own term API implicitly applies via node-at-a-time processing. */
+const MAX_REGEX_MATCHES = 500;
+
+export function useImperativeSearchHighlighlighting(
+ highlightedTokens: (string | HighlightedTokenInfo)[] | null | undefined
+) {
const mark = useRef<Mark>();
- const highlightRegex = useMemo(() => {
+ const tokenInfos = useMemo<HighlightedTokenInfo[] | null>(() => {
if (!highlightedTokens?.length) return null;
- const regex = highlightedTokens.map((token) => escapeRegExp(token)).join("|");
- return new RegExp(regex, "gi");
+ return highlightedTokens.map((token) => (typeof token === "string" ? { token, type: "plain" as const } : token));
}, [ highlightedTokens ]);
return (el: HTMLElement | null | undefined) => {
- if (!el || !highlightRegex) return;
+ if (!el || !tokenInfos) return;
if (!mark.current) {
mark.current = new Mark(el);
}
mark.current.unmark();
- mark.current.markRegExp(highlightRegex, {
- element: "span",
- className: "ck-find-result"
- });
+
+ 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
+ });
+ }
};
}
diff --git a/apps/client/src/widgets/search_result.tsx b/apps/client/src/widgets/search_result.tsx
index af01336fb9..b97a257029 100644
--- a/apps/client/src/widgets/search_result.tsx
+++ b/apps/client/src/widgets/search_result.tsx
@@ -1,5 +1,6 @@
import "./search_result.css";
+import type { HighlightedTokenInfo } from "@triliumnext/commons";
import clsx from "clsx";
import { useEffect, useState } from "preact/hooks";
@@ -18,7 +19,7 @@ enum SearchResultState {
export default function SearchResult() {
const { note, notePath, ntxId } = useNoteContext();
const [ state, setState ] = useState<SearchResultState>();
- const [ highlightedTokens, setHighlightedTokens ] = useState<string[]>();
+ const [ highlightedTokens, setHighlightedTokens ] = useState<(string | HighlightedTokenInfo)[]>();
function refresh() {
if (note?.type !== "search") {
@@ -29,7 +30,7 @@ export default function SearchResult() {
setState(SearchResultState.NO_RESULTS);
} else {
setState(SearchResultState.GOT_RESULTS);
- setHighlightedTokens(note.highlightedTokens);
+ setHighlightedTokens(note.highlightedTokenInfos ?? note.highlightedTokens);
}
}