Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(search): draw match highlights without touching the DOM
Elian Doran019c2279d8af
diff --git a/apps/client/src/services/highlight_matches.ts b/apps/client/src/services/highlight_matches.tsindex c73cc6aa18..da528db32b 100644--- a/apps/client/src/services/highlight_matches.ts+++ b/apps/client/src/services/highlight_matches.ts@@ -1,32 +1,43 @@import { escapeRegExp } from "./utils.js";-export interface HighlightOptions {- /** The class of the `<span>` that wraps each match. */- className: string;+/**+ * The highlights of `CSS.highlights` that the client draws, which `::highlight(name)` styles, and+ * their priorities: a range in two highlights draws the one with the higher priority on top.+ */+const PRIORITIES = {+ "search-match": 0,+ "find-result-secondary": 0,+ "find-result": 1,+ "find-result-selected": 2+};++export type HighlightName = keyof typeof PRIORITIES;++export interface MatchOptions {/** Selectors of the elements whose own text is not searched. */exclude?: string[];- /** The maximum number of matches to wrap. */+ /** The maximum number of matches to return. */limit?: number;}-/** Elements whose text is never displayed, so a match inside them is never wrapped. */+/** Elements whose text is never displayed, so a match inside them is never returned. */const ALWAYS_EXCLUDED = [ "script", "style", "title", "head", "html" ];/**- * Wraps each match of `regExp` in the text under `root`, and returns the wrappers in document- * order. A match cannot span two text nodes. {@link removeHighlights} unwraps them again.+ * The ranges of the matches of `regExp` in the text under `root`, in document order. A match+ * cannot span two text nodes.*/-export function highlightRegExp(root: HTMLElement, regExp: RegExp, options: HighlightOptions) {+export function findRegExpRanges(root: HTMLElement, regExp: RegExp, options: MatchOptions = {}) {const global = regExp.global ? regExp : new RegExp(regExp.source, `${regExp.flags}g`);- return highlightRanges(root, options, (text) => findRanges(global, text));+ return findRanges(root, options, (text) => findOffsets(global, text));}/**- * Wraps each occurrence of the literal `terms` in the text under `root`, ignoring case and+ * The ranges of the occurrences of the literal `terms` in the text under `root`, ignoring case and* diacritics the way the server's `normalize()` does, so the unaccented token "ktory" still* matches "ktorý". Whitespace in a term matches any run of whitespace.*/-export function highlightTerms(root: HTMLElement, terms: string[], options: HighlightOptions) {+export function findTermRanges(root: HTMLElement, terms: string[], options: MatchOptions = {}) {const patterns = terms.map((term) => fold(term).text.trim()).filter((term) => term.length > 0)@@ -37,38 +48,86 @@ export function highlightTerms(root: HTMLElement, terms: string[], options: High}const regExp = new RegExp(patterns.join("|"), "g");- return highlightRanges(root, options, (text) => {+ return findRanges(root, options, (text) => {const folded = fold(text);- return findRanges(regExp, folded.text)- .map(([ start, end ]): Range => [ folded.starts[start], folded.ends[end - 1] ]);+ return findOffsets(regExp, folded.text)+ .map(([ start, end ]): Offsets => [ folded.starts[start], folded.ends[end - 1] ]);});}-/** Unwraps the elements that {@link highlightRegExp} and {@link highlightTerms} returned. */-export function removeHighlights(elements: Iterable<HTMLElement>) {- for (const element of elements) {- const parent = element.parentNode;- if (!parent) continue;+/** Draws `ranges` as part of the highlight `name`. Browsers without `CSS.highlights` draw nothing. */+export function addHighlights(name: HighlightName, ranges: Iterable<Range>) {+ const registry = getRegistry();+ if (!registry) return;++ let highlight = registry.get(name);+ if (!highlight) {+ highlight = new Highlight();+ highlight.priority = PRIORITIES[name];+ registry.set(name, highlight);+ }+ for (const range of ranges) {+ highlight.add(range);+ }+}++/** Stops drawing `ranges` as part of the highlight `name`, leaving its other ranges drawn. */+export function removeHighlights(name: HighlightName, ranges: Iterable<Range>) {+ const highlight = getRegistry()?.get(name);+ if (!highlight) return;- element.replaceWith(...element.childNodes);- parent.normalize();+ for (const range of ranges) {+ highlight.delete(range);+ }+}++/**+ * Scrolls each scrolling ancestor of `range`, innermost first, so that the range sits in its+ * middle. `Element.scrollIntoView()` would center the whole parent element instead, which can be+ * a code block taller than the view.+ */+export function scrollRangeIntoView(range: Range) {+ for (let element = range.startContainer.parentElement; element; element = element.parentElement) {+ if (!isScrollable(element)) continue;++ const target = range.getBoundingClientRect();+ const box = element.getBoundingClientRect();+ element.scrollBy({+ left: target.left + target.width / 2 - (box.left + box.width / 2),+ top: target.top + target.height / 2 - (box.top + box.height / 2)+ });}}-type Range = [ start: number, end: number ];+type Offsets = [ start: number, end: number ];-function highlightRanges(root: HTMLElement, options: HighlightOptions, getRanges: (text: string) => Range[]) {+function getRegistry() {+ return typeof Highlight === "undefined" ? undefined : globalThis.CSS?.highlights;+}++function isScrollable(element: Element) {+ const { overflowX, overflowY } = getComputedStyle(element);+ const scrolls = (overflow: string) => /auto|scroll|overlay/.test(overflow);+ return (element.scrollHeight > element.clientHeight && scrolls(overflowY))+ || (element.scrollWidth > element.clientWidth && scrolls(overflowX));+}++function findRanges(root: HTMLElement, options: MatchOptions, getOffsets: (text: string) => Offsets[]) {const excluded = [ ...ALWAYS_EXCLUDED, ...options.exclude ?? [] ].join(",");const limit = options.limit ?? Infinity;- const wrappers: HTMLElement[] = [];+ const ranges: Range[] = [];for (const node of getTextNodes(root, excluded)) {- const ranges = getRanges(node.data).slice(0, limit - wrappers.length);- wrappers.push(...wrapRanges(node, ranges, options.className));- if (wrappers.length >= limit) break;+ for (const [ start, end ] of getOffsets(node.data).slice(0, limit - ranges.length)) {+ const range = document.createRange();+ range.setStart(node, start);+ range.setEnd(node, end);+ ranges.push(range);+ }+ if (ranges.length >= limit) break;}- return wrappers;+ return ranges;}function getTextNodes(root: HTMLElement, excluded: string) {@@ -85,35 +144,15 @@ function getTextNodes(root: HTMLElement, excluded: string) {return nodes;}-/** The non-empty matches of the global `regExp` in `text`. */-function findRanges(regExp: RegExp, text: string) {- const ranges: Range[] = [];+/** The offsets of the non-empty matches of the global `regExp` in `text`. */+function findOffsets(regExp: RegExp, text: string) {+ const offsets: Offsets[] = [];for (const match of text.matchAll(regExp)) {if (match[0].length > 0) {- ranges.push([ match.index, match.index + match[0].length ]);+ offsets.push([ match.index, match.index + match[0].length ]);}}- return ranges;-}--function wrapRanges(node: Text, ranges: Range[], className: string) {- const wrappers: HTMLElement[] = [];- let rest = node;- let offset = 0;-- for (const [ start, end ] of ranges) {- const matched = rest.splitText(start - offset);- rest = matched.splitText(end - start);- offset = end;-- const wrapper = document.createElement("span");- wrapper.className = className;- matched.replaceWith(wrapper);- wrapper.append(matched);- wrappers.push(wrapper);- }-- return wrappers;+ return offsets;}/**diff --git a/apps/client/src/stylesheets/style.css b/apps/client/src/stylesheets/style.cssindex 43a3478c15..96f09986de 100644--- a/apps/client/src/stylesheets/style.css+++ b/apps/client/src/stylesheets/style.css@@ -386,6 +386,12 @@ div.ui-tooltip {display: block;}+/* The search terms `useImperativeSearchHighlighlighting()` finds in titles, cards and previews. */+::highlight(search-match) {+ color: var(--note-list-view-search-result-highlight-color, var(--admonition-warning-accent-color));+ text-decoration: underline;+}+/* Allow to use <kbd> elements inside the title to define shortcut hints. */.ui-menu kbd,button kbd {diff --git a/apps/client/src/stylesheets/theme-next-dark.css b/apps/client/src/stylesheets/theme-next-dark.cssindex 0c698d4598..8422efc65d 100644--- a/apps/client/src/stylesheets/theme-next-dark.css+++ b/apps/client/src/stylesheets/theme-next-dark.css@@ -362,8 +362,6 @@--note-list-view-search-result-highlight-color: var(--quick-search-result-highlight-color);--note-list-view-search-result-fuzzy-highlight-color: var(--quick-search-result-fuzzy-highlight-color);--note-list-view-content-background: rgba(0, 0, 0, .2);- --note-list-view-content-search-result-highlight-background: var(--quick-search-result-highlight-color);- --note-list-view-content-search-result-highlight-color: black;--calendar-coll-event-background-saturation: 25%;--calendar-coll-event-background-lightness: 20%;diff --git a/apps/client/src/stylesheets/theme-next-light.css b/apps/client/src/stylesheets/theme-next-light.cssindex 6ce8cc17eb..feacec82da 100644--- a/apps/client/src/stylesheets/theme-next-light.css+++ b/apps/client/src/stylesheets/theme-next-light.css@@ -361,8 +361,6 @@--note-list-view-search-result-highlight-color: var(--quick-search-result-highlight-color);--note-list-view-search-result-fuzzy-highlight-color: var(--quick-search-result-fuzzy-highlight-color);--note-list-view-content-background: #b1b1b133;- --note-list-view-content-search-result-highlight-background: var(--quick-search-result-highlight-color);- --note-list-view-content-search-result-highlight-color: white;--calendar-coll-event-background-lightness: 95%;--calendar-coll-event-background-saturation: 80%;diff --git a/apps/client/src/test/highlights.ts b/apps/client/src/test/highlights.tsnew file mode 100644index 0000000000..447b86dfce--- /dev/null+++ b/apps/client/src/test/highlights.ts@@ -0,0 +1,29 @@+/**+ * Stands in for the CSS Custom Highlight API, which happy-dom does not implement: `Highlight` is a+ * `Set` of ranges and `CSS.highlights` a `Map` of them.+ */+export function stubHighlightApi() {+ class Highlight extends Set<AbstractRange> {+ priority = 0;+ type = "highlight";++ constructor(...ranges: AbstractRange[]) {+ super(ranges);+ }+ }++ Object.assign(globalThis, { Highlight });+ // happy-dom's `CSS` getter builds a new object on each read, so the registry goes on its prototype.+ Object.defineProperty(Object.getPrototypeOf(globalThis.CSS), "highlights", { value: new Map() });+}++/** The ranges of the highlight `name` that start under `root`, in the order they were added. */+export function highlightedRanges(name: string, root: Node = document.body) {+ return [ ...CSS.highlights.get(name) ?? [] ]+ .filter((range): range is Range => range instanceof Range && root.contains(range.startContainer));+}++/** The text of {@link highlightedRanges}. */+export function highlightedTexts(name: string, root: Node = document.body) {+ return highlightedRanges(name, root).map((range) => range.toString());+}diff --git a/apps/client/src/test/setup.ts b/apps/client/src/test/setup.tsindex 33baa76c2c..47b65fddbc 100644--- a/apps/client/src/test/setup.ts+++ b/apps/client/src/test/setup.ts@@ -7,11 +7,14 @@ import { Modal } from "bootstrap";import $ from "jquery";import { afterAll, vi } from "vitest";+import { stubHighlightApi } from "./highlights";+// Top level, not in a beforeAll: vi.mock is hoisted either way, and nesting it only makes the order lie.vi.mock("../services/ws.js", mockWebsocket);vi.mock("../services/server.js", mockServer);injectGlobals();+stubHighlightApi();survivePendingModalCallbacks();deferSelectionChange();drainBootstrapTransitions();diff --git a/apps/client/src/widgets/collections/board/index.css b/apps/client/src/widgets/collections/board/index.cssindex 2e618347ef..1bdd5c3026 100644--- a/apps/client/src/widgets/collections/board/index.css+++ b/apps/client/src/widgets/collections/board/index.css@@ -566,13 +566,6 @@ body.mobile .board-view-container .board-add-column {.board-view-container .board-note > .title {display: block;padding-inline-start: calc(var(--card-title-inset) - var(--card-padding));-- /* The spans `highlightTerms()` wraps a filter's matched tokens in. Matches the search result cards. */- .ck-find-result {- background: var(--note-list-view-search-result-highlight-background);- color: var(--note-list-view-search-result-highlight-color);- text-decoration: underline;- }}/* A card carrying `boardCardRedirectTo` opens the note it points at, so its title reads as a link.diff --git a/apps/client/src/widgets/collections/board/index.spec.tsx b/apps/client/src/widgets/collections/board/index.spec.tsxindex cef402e2ad..dcedb22f48 100644--- a/apps/client/src/widgets/collections/board/index.spec.tsx+++ b/apps/client/src/widgets/collections/board/index.spec.tsx@@ -26,6 +26,7 @@ import LoadResults from "../../../services/load_results";import noteAttributeCache from "../../../services/note_attribute_cache";import searchService from "../../../services/search";import { buildNote } from "../../../test/easy-froca";+import { highlightedTexts } from "../../../test/highlights";import { ParentComponent } from "../../react/react_utils";import BoardView, { BoardViewData, loadBoardEditing } from ".";import { getNoteTypeOptions, type NoteTypeOption } from "../../../services/note_types";@@ -3980,8 +3981,8 @@ describe("Board filtering", () => {tokens: [ { token: "First", type: "plain" } ]});- const marks = [ ...container.querySelectorAll(".board-note .title .ck-find-result") ];- expect(marks.map(el => el.textContent)).toEqual([ "First" ]);+ const titles = [ ...container.querySelectorAll(".board-note .title") ];+ expect(titles.flatMap((title) => highlightedTexts("search-match", title))).toEqual([ "First" ]);});/**diff --git a/apps/client/src/widgets/collections/legacy/ListOrGridView.css b/apps/client/src/widgets/collections/legacy/ListOrGridView.cssindex dc6cd00957..62bc3705e1 100644--- a/apps/client/src/widgets/collections/legacy/ListOrGridView.css+++ b/apps/client/src/widgets/collections/legacy/ListOrGridView.css@@ -99,13 +99,6 @@font-size: 1.2em;color: var(--note-icon-custom-color, var(--note-list-view-large-icon-color));}-- .ck-find-result {- background: var(--note-list-view-search-result-highlight-background);- color: var(--note-list-view-search-result-highlight-color);- font-weight: 600;- text-decoration: underline;- }}@keyframes note-preview-show {@@ -125,13 +118,6 @@&.note-book-content-ready {display: block;}-- .ck-find-result {- outline: 2px solid var(--note-list-view-content-search-result-highlight-background);- border-radius: 4px;- background: var(--note-list-view-content-search-result-highlight-background);- color: var(--note-list-view-content-search-result-highlight-color);- }}.note-book-content {diff --git a/apps/client/src/widgets/collections/search/SearchResultsList.css b/apps/client/src/widgets/collections/search/SearchResultsList.cssindex 38ed9f4fd3..9867eaaba7 100644--- a/apps/client/src/widgets/collections/search/SearchResultsList.css+++ b/apps/client/src/widgets/collections/search/SearchResultsList.css@@ -132,9 +132,7 @@margin-top: 6px;}- /* Style the server-injected <b> highlights (snippet + attribute badges) and the client-side- .ck-find-result spans (title) identically. */- .search-result-card-title .ck-find-result,+ /* The server-injected <b> highlights of the snippet and the attribute badges. */.search-result-card-snippet b,.search-result-card-badges b {background: var(--note-list-view-search-result-highlight-background);diff --git a/apps/client/src/widgets/find.ts b/apps/client/src/widgets/find.tsindex dcdec3547c..cf79643bb7 100644--- a/apps/client/src/widgets/find.ts+++ b/apps/client/src/widgets/find.ts@@ -57,13 +57,19 @@ const TPL = /*html*/`flex-grow: 1;}- /* Muted highlight for the non-seed tokens of a multi-token jump-to-match (see- FindInHtml.highlightExtraTokens): a reduced-opacity variant of the primary- .ck-find-result highlight, so extra matches are visible without competing with the- seed match that Enter/F3 cycles. */- .find-result-secondary {+ /* The highlights of FindInHtml, in the colors CKEditor gives .ck-find-result and+ .ck-find-result_selected in an editable text note. */+ ::highlight(find-result) {+ background-color: var(--ck-color-highlight-background);+ color: var(--ck-color-text);+ }++ ::highlight(find-result-selected) {+ background-color: var(--ck-color-find-result-selected);+ }++ ::highlight(find-result-secondary) {background-color: color-mix(in srgb, var(--ck-color-find-result-background, #66ff99) 40%, transparent);- border-radius: 2px;}</style>diff --git a/apps/client/src/widgets/find_in_html.spec.ts b/apps/client/src/widgets/find_in_html.spec.tsindex f84c16c587..4eb3917eef 100644--- a/apps/client/src/widgets/find_in_html.spec.ts+++ b/apps/client/src/widgets/find_in_html.spec.ts@@ -1,6 +1,7 @@import { applyTabs } from "@triliumnext/ckeditor5/src/plugins/tabs/tabs_read_only.js";-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { afterEach, describe, expect, it, vi } from "vitest";+import { highlightedRanges, highlightedTexts } from "../test/highlights";import type FindWidget from "./find";import FindInHtml, { HtmlFindTarget, HtmlNoteFindTarget } from "./find_in_html.js";import MergedFind from "./merged_find";@@ -42,11 +43,6 @@ function setup(html: string) {}describe("FindInHtml", () => {- beforeEach(() => {- // happy-dom doesn't implement scrollIntoView; jumpTo() calls it.- (Element.prototype as any).scrollIntoView = vi.fn();- });-afterEach(() => {document.body.innerHTML = "";});@@ -58,8 +54,8 @@ describe("FindInHtml", () => {expect(result.totalFound).toBe(2);expect(result.currentFound).toBe(1);- expect(container.querySelectorAll(".ck-find-result").length).toBe(2);- expect(container.querySelectorAll(".find-result-secondary").length).toBe(0);+ expect(highlightedTexts("find-result", container)).toEqual([ "alpha", "alpha" ]);+ expect(highlightedTexts("find-result-secondary", container)).toEqual([]);});it("highlightExtraTokens marks non-seed tokens with the muted secondary class only", async () => {@@ -69,8 +65,8 @@ describe("FindInHtml", () => {await finder.highlightExtraTokens([ "beta", "gamma" ]);// Seed count is unaffected: Enter/F3 still cycles only the primary matches.- expect(container.querySelectorAll(".ck-find-result").length).toBe(1);- expect(container.querySelectorAll(".find-result-secondary").length).toBe(2);+ expect(highlightedTexts("find-result", container)).toEqual([ "alpha" ]);+ expect(highlightedTexts("find-result-secondary", container)).toEqual([ "beta", "gamma" ]);});it("findBoxClosed clears the primary and the secondary marks together", async () => {@@ -78,10 +74,14 @@ describe("FindInHtml", () => {await finder.performFind("alpha", false, false);await finder.highlightExtraTokens([ "beta" ]);- expect(container.querySelectorAll(".ck-find-result, .find-result-secondary").length).toBe(2);+ expect(highlightedTexts("find-result", container)).toEqual([ "alpha" ]);+ expect(highlightedTexts("find-result-secondary", container)).toEqual([ "beta" ]);await finder.findBoxClosed(1, 0);+ expect(highlightedTexts("find-result", container)).toEqual([]);+ expect(highlightedTexts("find-result-selected", container)).toEqual([]);+ expect(highlightedTexts("find-result-secondary", container)).toEqual([]);expect(container.innerHTML).toBe("<p>alpha beta gamma</p>");});@@ -90,7 +90,7 @@ describe("FindInHtml", () => {await finder.highlightExtraTokens([ "beta" ]);- expect(container.querySelectorAll(".find-result-secondary").length).toBe(0);+ expect(highlightedTexts("find-result-secondary", container)).toEqual([]);});it("highlightExtraTokens safely handles tokens containing regex metacharacters", async () => {@@ -100,7 +100,7 @@ describe("FindInHtml", () => {await finder.highlightExtraTokens([ "a.c", "a+c" ]);// Literal matches only, no regex injection (both literal tokens exist once each).- const secondary = Array.from(container.querySelectorAll(".find-result-secondary")).map((el) => el.textContent);+ const secondary = highlightedTexts("find-result-secondary", container);expect(secondary).toContain("a.c");expect(secondary).toContain("a+c");});@@ -135,15 +135,16 @@ describe("FindInHtml", () => {expect(await handler.performFind("needle", false, false)).toEqual({ totalFound: 3, currentFound: 1 });await handler.findNext(1, 1, 2);- const selected = content.querySelector(".ck-find-result_selected");- expect(selected?.closest("details")?.open).toBe(true);+ const [ selected ] = highlightedRanges("find-result-selected", content);+ expect(selected?.startContainer.parentElement?.closest("details")?.open).toBe(true);await handler.highlightExtraTokens([ "before", "" ]);- expect(content.querySelector(".find-result-secondary")?.textContent).toBe("before");+ expect(highlightedTexts("find-result-secondary", content)).toEqual([ "before" ]);cleanups.push(registerEmbedFindTarget(embed, new HtmlFindTarget(embed)));expect(parent.invalidateResults).toHaveBeenCalledOnce();await handler.findBoxClosed(3, 3);- expect(content.querySelector(".ck-find-result, .find-result-secondary")).toBeNull();+ expect(highlightedTexts("find-result", content)).toEqual([]);+ expect(highlightedTexts("find-result-secondary", content)).toEqual([]);cleanups.push(registerEmbedFindTarget(content, new HtmlFindTarget(content)));expect(parent.invalidateResults).toHaveBeenCalledOnce();});@@ -155,23 +156,24 @@ describe("HtmlNoteFindTarget", () => {const target = new HtmlNoteFindTarget(content);expect(await target.find("needle", OPTIONS)).toBe(3);- expect(embed.querySelectorAll(".include-note-wrapper .ck-find-result")).toHaveLength(0);+ const wrapper = embed.querySelector(".include-note-wrapper");+ expect(wrapper && highlightedTexts("find-result", wrapper)).toEqual([]);expect(target.getEmbeds()).toEqual([ embed ]);expect(target.countMatchesBefore(embed)).toBe(1);expect(target.canReplace()).toBe(false);expect(await target.replaceAll()).toBe(3);target.highlight(2);- const selected = content.querySelector(".ck-find-result_selected");- expect(selected?.textContent).toBe("needle");- expect(selected?.closest("details")?.open).toBe(true);+ const [ selected ] = highlightedRanges("find-result-selected", content);+ expect(selected?.toString()).toBe("needle");+ expect(selected?.startContainer.parentElement?.closest("details")?.open).toBe(true);expect(target.getFirstMatchBelow(-Infinity)).toBe(0);expect(target.getFirstMatchBelow(Infinity)).toBeNull();target.highlight(null);- expect(content.querySelector(".ck-find-result_selected")).toBeNull();+ expect(highlightedTexts("find-result-selected", content)).toEqual([]);expect(target.close()).toBe(false);- expect(content.querySelector(".ck-find-result")).toBeNull();+ expect(highlightedTexts("find-result", content)).toEqual([]);expect(await target.find("", OPTIONS)).toBe(0);});@@ -183,7 +185,7 @@ describe("HtmlNoteFindTarget", () => {const find = new MergedFind(new HtmlNoteFindTarget(content));expect(await find.find("needle", OPTIONS)).toBe(4);- expect(box.querySelectorAll(".ck-find-result")).toHaveLength(1);+ expect(highlightedTexts("find-result", box)).toEqual([ "needle" ]);find.highlight(1);expect(box.querySelector("details")?.open).toBe(true);diff --git a/apps/client/src/widgets/find_in_html.ts b/apps/client/src/widgets/find_in_html.tsindex f5a7a4bae7..31bd59dfa8 100644--- a/apps/client/src/widgets/find_in_html.ts+++ b/apps/client/src/widgets/find_in_html.ts@@ -1,8 +1,7 @@-// ck-find-result and ck-find-result_selected are the styles ck-editor-// uses for highlighting matches, use the same one on CodeMirror-// for consistencyimport { revealElement } from "../services/collapsible.js";-import { highlightRegExp, highlightTerms, removeHighlights } from "../services/highlight_matches.js";+import {+ addHighlights, findRegExpRanges, findTermRanges, removeHighlights, scrollRangeIntoView+} from "../services/highlight_matches.js";import utils from "../services/utils.js";import type FindWidget from "./find.js";import MergedFind, {@@ -10,12 +9,6 @@ import MergedFind, {} from "./merged_find";import { watchEmbedFindTargets } from "./type_widgets/text/content_embed_tools";-const FIND_RESULT_SELECTED_CSS_CLASSNAME = "ck-find-result_selected";-const FIND_RESULT_CSS_CLASSNAME = "ck-find-result";-// Muted highlight for the non-seed tokens of a multi-token search (jump-to-match). Styled in the-// FindWidget's style block. Deliberately distinct from FIND_RESULT_CSS_CLASSNAME so these marks are-// not counted as primary matches and Enter/F3 keeps cycling only the seed.-const FIND_RESULT_SECONDARY_CSS_CLASSNAME = "find-result-secondary";// The content of an embed searches itself, and its title row is not searched.const EMBED_EXCLUSION = [ ".include-note-wrapper", ".include-note-wrapper *" ];@@ -86,13 +79,16 @@ export default class FindInHtml {}-/** Searches rendered content, which it cannot change, by marking up its matches. */+/** Searches rendered content, which it cannot change, by highlighting the ranges of its matches. */export class HtmlFindTarget implements FindTarget {- protected matches: HTMLElement[] = [];- /** The elements that wrap the matches and the extra tokens, which `unmark()` removes. */- private markElements: HTMLElement[] = [];- private current: HTMLElement | null = null;+ protected matches: Range[] = [];+ /**+ * The ranges of the extra tokens. They are not matches, so Enter and F3 keep cycling only+ * {@link matches}.+ */+ private extraRanges: Range[] = [];+ private current: Range | null = null;/** Searches `root`, apart from the elements that the `exclude` selectors match. */constructor(readonly root: HTMLElement, private readonly exclude: string[] = []) {}@@ -108,26 +104,28 @@ export class HtmlFindTarget implements FindTarget {wholeWordChar + utils.escapeRegExp(term) + wholeWordChar,matchCase ? "g" : "gi");- this.matches = highlightRegExp(this.root, regExp, {- className: FIND_RESULT_CSS_CLASSNAME,- exclude: this.exclude- });- this.markElements.push(...this.matches);+ this.matches = findRegExpRanges(this.root, regExp, { exclude: this.exclude });+ addHighlights("find-result", this.matches);return this.matches.length;}highlight(index: number | null) {- this.current?.classList.remove(FIND_RESULT_SELECTED_CSS_CLASSNAME);+ if (this.current) {+ removeHighlights("find-result-selected", [ this.current ]);+ }this.current = index === null ? null : this.matches[index] ?? null;if (!this.current) {return;}// Reveal matches inside collapsed <details> and inactive tabs, like native find-in-page.- // Must precede scrollIntoView so the target is laid out first (#10616).- revealElement(this.current, this.root);- this.current.scrollIntoView({ block: "center", inline: "center" });- this.current.classList.add(FIND_RESULT_SELECTED_CSS_CLASSNAME);+ // Must precede scrolling so the target is laid out first (#10616).+ const parent = this.current.startContainer.parentElement;+ if (parent) {+ revealElement(parent, this.root);+ }+ scrollRangeIntoView(this.current);+ addHighlights("find-result-selected", [ this.current ]);}getFirstMatchBelow(top: number) {@@ -157,20 +155,23 @@ export class HtmlFindTarget implements FindTarget {* cycling through. The tokens match literally, so a regex metacharacter cannot inject.*/async highlightExtraTokens(tokens: string[]) {- this.markElements.push(...highlightTerms(this.root, tokens, {- className: FIND_RESULT_SECONDARY_CSS_CLASSNAME,- exclude: this.exclude- }));+ const ranges = findTermRanges(this.root, tokens, { exclude: this.exclude });+ this.extraRanges.push(...ranges);+ addHighlights("find-result-secondary", ranges);}/**- * Unwraps the elements of this target only, not those of the other targets in its root, such- * as the embeds in a note.+ * Removes the ranges of this target only, not those of the other targets in its root, such as+ * the embeds in a note.*/private unmark() {- removeHighlights(this.markElements);- this.markElements = [];+ removeHighlights("find-result", this.matches);+ removeHighlights("find-result-secondary", this.extraRanges);+ if (this.current) {+ removeHighlights("find-result-selected", [ this.current ]);+ }this.matches = [];+ this.extraRanges = [];this.current = null;}@@ -190,7 +191,7 @@ export class HtmlNoteFindTarget extends HtmlFindTarget implements HostFindTargetcountMatchesBefore(embed: HTMLElement) {return this.matches.filter(- (match) => embed.compareDocumentPosition(match) & Node.DOCUMENT_POSITION_PRECEDING+ (match) => embed.compareDocumentPosition(match.startContainer) & Node.DOCUMENT_POSITION_PRECEDING).length;}diff --git a/apps/client/src/widgets/react/RawHtml.spec.tsx b/apps/client/src/widgets/react/RawHtml.spec.tsxindex 1d93c16e2c..f8e77520e9 100644--- a/apps/client/src/widgets/react/RawHtml.spec.tsx+++ b/apps/client/src/widgets/react/RawHtml.spec.tsx@@ -2,6 +2,7 @@ import { render } from "preact";import { act } from "preact/test-utils";import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { highlightedTexts } from "../../test/highlights";import RawHtml, { getHtml, HighlightedText, RawHtmlBlock, SanitizedHtml } from "./RawHtml";let container: HTMLDivElement;@@ -88,8 +89,8 @@ describe("HighlightedText", () => {container));- const marks = () => [ ...container.querySelectorAll(".ck-find-result") ];- expect(marks().map((mark) => mark.textContent)).toEqual([ "matched" ]);+ const marks = () => highlightedTexts("search-match", container);+ expect(marks()).toEqual([ "matched" ]);act(() => render(<HighlightedText text="the matched word" highlightedTokens={null} />,@@ -110,6 +111,6 @@ describe("HighlightedText", () => {));expect(container.textContent).toBe("another match here");- expect(container.querySelectorAll(".ck-find-result")).toHaveLength(1);+ expect(highlightedTexts("search-match", container)).toEqual([ "match" ]);});});diff --git a/apps/client/src/widgets/react/RawHtml.tsx b/apps/client/src/widgets/react/RawHtml.tsxindex 278a19dce4..7643c0820d 100644--- a/apps/client/src/widgets/react/RawHtml.tsx+++ b/apps/client/src/widgets/react/RawHtml.tsx@@ -39,11 +39,7 @@ export function getHtml(html: HTMLElementLike) {};}-/**- * Renders plain text with search-match highlighting. The text is set imperatively so the highlighting,- * which injects `.ck-find-result` spans around matches, does not fight Preact's reconciliation- * of a controlled text child.- */+/** Renders plain text with search-match highlighting. */export function HighlightedText({ className, text, highlightedTokens }: {className?: string;text: string;@@ -52,16 +48,12 @@ export function HighlightedText({ className, text, highlightedTokens }: {const ref = useRef<HTMLSpanElement>(null);const highlight = useImperativeSearchHighlighlighting(highlightedTokens);- // Before the paint, so the span is not drawn empty for a frame first. `highlight` is a fresh- // closure each render, so the effect keys on the token list instead.+ // Before the paint, so the text is not drawn unhighlighted for a frame first. `highlight` is a+ // fresh closure each render, so the effect keys on the token list instead.// eslint-disable-next-line react-hooks/exhaustive-deps- useLayoutEffect(() => {- if (!ref.current) return;- ref.current.textContent = text;- highlight(ref.current);- }, [ text, highlightedTokens ]);+ useLayoutEffect(() => highlight(ref.current), [ text, highlightedTokens ]);- return <span className={className} ref={ref} />;+ return <span className={className} ref={ref}>{text}</span>;}/**diff --git a/apps/client/src/widgets/react/hooks.spec.tsx b/apps/client/src/widgets/react/hooks.spec.tsxindex 151b7d308a..18b285e6b9 100644--- a/apps/client/src/widgets/react/hooks.spec.tsx+++ b/apps/client/src/widgets/react/hooks.spec.tsx@@ -9,6 +9,7 @@ import appContext from "../../components/app_context";import type NoteContext from "../../components/note_context";import type TabManager from "../../components/tab_manager";import { buildNote } from "../../test/easy-froca";+import { highlightedTexts } from "../../test/highlights";import { setupHoldContextMenu } from "../widget_utils";import {type DelayedVisibilityPhase,@@ -649,7 +650,7 @@ describe("useImperativeSearchHighlighlighting", () => {}function markedTexts(el: HTMLElement) {- return Array.from(el.querySelectorAll("span.ck-find-result")).map((mark) => mark.textContent);+ return highlightedTexts("search-match", el);}/**@@ -717,17 +718,29 @@ describe("useImperativeSearchHighlighlighting", () => {await remount(null);liveHighlight?.(el);- expect(el.innerHTML).toBe("<p>a needle here</p>");- expect(el.querySelector("p")?.childNodes).toHaveLength(1);+ expect(markedTexts(el)).toEqual([]);el.remove();});- it("does not touch an element that was never highlighted", async () => {- await remount(null);+ it("stops drawing its highlights once unmounted", async () => {+ await remount([ "needle" ]);+ const el = content("<p>a needle here</p>");+ liveHighlight?.(el);+ expect(markedTexts(el)).toEqual([ "needle" ]);++ act(() => render(null, container));++ expect(markedTexts(el)).toEqual([]);+ el.remove();+ });++ it("leaves the DOM of the highlighted element untouched", async () => {+ await remount([ "needle" ]);const el = content("<p>a needle here</p>");liveHighlight?.(el);+ expect(markedTexts(el)).toEqual([ "needle" ]);expect(el.innerHTML).toBe("<p>a needle here</p>");el.remove();});diff --git a/apps/client/src/widgets/react/hooks.tsx b/apps/client/src/widgets/react/hooks.tsxindex 521718adf3..ce56ce6774 100644--- a/apps/client/src/widgets/react/hooks.tsx+++ b/apps/client/src/widgets/react/hooks.tsx@@ -18,7 +18,7 @@ import FNote from "../../entities/fnote";import attributes from "../../services/attributes";import { expandAncestorDetails } from "../../services/collapsible";import froca from "../../services/froca";-import { highlightRegExp, highlightTerms, removeHighlights } from "../../services/highlight_matches";+import { addHighlights, findRegExpRanges, findTermRanges, removeHighlights } from "../../services/highlight_matches";import { t } from "../../services/i18n";import keyboard_actions from "../../services/keyboard_actions";import { formatShortcut, joinShortcut } from "../../services/keyboard_shortcut_display";@@ -1776,28 +1776,31 @@ const MAX_REGEX_MATCHES = 500;export function useImperativeSearchHighlighlighting(highlightedTokens: (string | HighlightedTokenInfo)[] | null | undefined) {- const highlights = useRef<HTMLElement[]>([]);+ const ranges = useRef<Range[]>([]);const tokenInfos = useMemo<HighlightedTokenInfo[] | null>(() => {if (!highlightedTokens?.length) return null;return highlightedTokens.map((token) => (typeof token === "string" ? { token, type: "plain" as const } : token));}, [ highlightedTokens ]);+ // `CSS.highlights` keeps the ranges, and the nodes they hold, after the element is removed.+ useEffect(() => () => removeHighlights("search-match", ranges.current), []);+return (el: HTMLElement | null | undefined) => {if (!el) return;// 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.- removeHighlights(highlights.current);- highlights.current = [];+ // previous highlights, which would otherwise stay drawn for good.+ removeHighlights("search-match", ranges.current);+ ranges.current = [];if (!tokenInfos) return;- // `highlightTerms()` ignores diacritics, so an unaccented query like "ktory" (the server+ // `findTermRanges()` ignores diacritics, so an unaccented query like "ktory" (the server// strips diacritics before indexing) still highlights "ktorý" (#10616). It matches// substrings, so CJK tokens without word boundaries ("笔记" in "我的笔记本") work too.const plainTokens = tokenInfos.filter((info) => info.type === "plain").map((info) => info.token);- highlights.current.push(...highlightTerms(el, plainTokens, { className: "ck-find-result" }));+ ranges.current.push(...findTermRanges(el, plainTokens));for (const info of tokenInfos) {if (info.type !== "regex" || info.token.length > MAX_REGEX_TOKEN_LENGTH) continue;@@ -1810,16 +1813,16 @@ export function useImperativeSearchHighlighlighting(continue;}- highlights.current.push(...highlightRegExp(el, regex, {- className: "ck-find-result",- limit: MAX_REGEX_MATCHES- }));+ ranges.current.push(...findRegExpRanges(el, regex, { limit: MAX_REGEX_MATCHES }));}- // Reveal matches that landed inside collapsed <details> blocks, which are highlighted in- // the DOM but hidden until the block is expanded.- for (const match of el.querySelectorAll<HTMLElement>(".ck-find-result")) {- expandAncestorDetails(match);+ addHighlights("search-match", ranges.current);++ // Reveal matches that landed inside collapsed <details> blocks, which are highlighted but+ // hidden until the block is expanded.+ for (const range of ranges.current) {+ const parent = range.startContainer.parentElement;+ if (parent) expandAncestorDetails(parent);}};}