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
fix(editor): highlight only the matching text in link widgets
Elian Doran24b160901dbe
diff --git a/packages/ckeditor5/src/plugins/find_in_link_widgets.spec.ts b/packages/ckeditor5/src/plugins/find_in_link_widgets.spec.tsindex f57c074650..a0400c6cf4 100644--- a/packages/ckeditor5/src/plugins/find_in_link_widgets.spec.ts+++ b/packages/ckeditor5/src/plugins/find_in_link_widgets.spec.ts@@ -82,24 +82,27 @@ describe("FindInLinkWidgets", () => {expect(resultElementNames(commandResult.results)).toEqual(["text", "reference", "linkMention", "linkEmbed"]);- expect(editingRoot?.querySelector("a.reference-link.ck-find-result")).not.toBeNull();- expect(editingRoot?.querySelector("span.link-mention.ck-find-result")).not.toBeNull();- expect(editingRoot?.querySelector("section.link-embed.ck-find-result")).not.toBeNull();+ // The highlight goes on the matching characters, never on the widget itself.+ expect(matchTexts(editingRoot, "a.reference-link")).toEqual([ "match" ]);+ expect(matchTexts(editingRoot, "span.link-mention")).toEqual([ "match" ]);+ expect(matchTexts(editingRoot, "section.link-embed")).toEqual([ "match" ]);+ expect(editingRoot?.querySelector(".ck-widget.ck-find-result")).toBeNull();editor.execute("findNext");const selectedReference = editingRoot?.querySelector(- "a.reference-link.ck-find-result_selected"+ "a.reference-link .ck-find-result_selected");- expect(selectedReference).not.toBeNull();+ expect(selectedReference?.textContent).toBe("match");});- it("keeps the highlight visible on anchor widgets that a theme styles", () => {+ it("highlights the matching characters of an anchor widget that a theme styles", () => {// The first two rules mirror CKEditor's find-and-replace theme; the last mirrors an// application theme that gives every link its own background.const themeStyle = document.createElement("style");themeStyle.textContent =":root { --ck-color-highlight-background: rgb(255, 255, 0); }" +".ck-find-result { background: var(--ck-color-highlight-background); }" ++ ".ck-find-result_selected { background: rgb(255, 150, 51); }" +".ck-content a { background: transparent; }";document.head.append(themeStyle);try {@@ -110,20 +113,58 @@ describe("FindInLinkWidgets", () => {editor.execute("find", "match");const reference = editor.editing.view.getDomRoot()?.querySelector("a.reference-link");- if (!reference) {- throw new Error("The test editor did not render the reference link.");+ const match = reference?.querySelector(".ck-find-result");+ if (!reference || !match) {+ throw new Error("The test editor did not highlight the reference link.");}- expect(reference.classList.contains("ck-find-result")).toBe(true);- expect(getComputedStyle(reference).backgroundColor).toBe("rgb(255, 255, 0)");+ expect(match.textContent).toBe("match");+ expect(getComputedStyle(reference).backgroundColor).toBe("rgba(0, 0, 0, 0)");+ expect(getComputedStyle(match).backgroundColor).toBe("rgb(255, 255, 0)");editor.execute("findNext");- expect(reference.classList.contains("ck-find-result_selected")).toBe(true);- expect(getComputedStyle(reference).backgroundColor).toBe("rgb(255, 150, 51)");+ const selected = reference.querySelector(".ck-find-result_selected");+ if (!selected) {+ throw new Error("The test editor did not mark the reference link as current.");+ }+ expect(selected.textContent).toBe("match");+ expect(getComputedStyle(selected).backgroundColor).toBe("rgb(255, 150, 51)");} finally {themeStyle.remove();}});+ it("wraps every match in place and restores the text when the search changes", () => {+ setModelData(+ editor.model,+ '<paragraph><reference href="#root/ref"></reference></paragraph>' ++ '<linkEmbed url="https://card.example/" embedType="opengraph" title="Card match" ' ++ 'description="Card description" siteName="Card site"></linkEmbed>'+ );++ const editingRoot = editor.editing.view.getDomRoot();+ const reference = editingRoot?.querySelector("a.reference-link");+ const card = editingRoot?.querySelector("section.link-embed");+ const title = reference?.querySelector("span");+ if (!reference || !card || !title) {+ throw new Error("The test editor did not render the link widgets.");+ }+ expect(reference.textContent).toBe("Reference match");++ // Repeated matches inside one text node, and one match in each of the card's three.+ editor.execute("find", "e");+ expect(matchTexts(editingRoot, "a.reference-link")).toEqual([ "e", "e", "e", "e" ]);+ expect(reference.textContent).toBe("Reference match");+ editor.execute("find", "Card");+ expect(matchTexts(editingRoot, "section.link-embed")).toEqual([ "Card", "Card", "Card" ]);+ expect(card.textContent).toBe("Card matchCard descriptionCard site");++ editor.execute("find", "absent");+ expect(matchTexts(editingRoot, "a.reference-link")).toEqual([]);+ expect(matchTexts(editingRoot, "section.link-embed")).toEqual([]);+ expect(reference.textContent).toBe("Reference match");+ expect(title.childNodes).toHaveLength(1);+ });+it("matches only the text that each link widget displays", () => {setModelData(editor.model,@@ -272,6 +313,21 @@ function findCount(return editor.plugins.get(FindAndReplaceEditing).state?.results.length ?? 0;}+/**+ * Returns the text of every find highlight inside the widget `selector` matches. The current+ * result carries `ck-find-result_selected` instead of `ck-find-result`, as CKEditor's widget+ * highlight stack keeps only the topmost descriptor.+ */+function matchTexts(editingRoot: HTMLElement | null | undefined, selector: string): string[] {+ const widget = editingRoot?.querySelector(selector);+ if (!widget) {+ throw new Error(`The test editor did not render ${selector}.`);+ }++ return [ ...widget.querySelectorAll(".ck-find-result, .ck-find-result_selected") ]+ .map((match) => match.textContent ?? "");+}+function resultElementNames(results: Iterable<FindResultType>): string[] {const names: string[] = [];for (const result of results) {diff --git a/packages/ckeditor5/src/plugins/find_in_link_widgets.ts b/packages/ckeditor5/src/plugins/find_in_link_widgets.tsindex c1345c3ccd..06624b9fc2 100644--- a/packages/ckeditor5/src/plugins/find_in_link_widgets.ts+++ b/packages/ckeditor5/src/plugins/find_in_link_widgets.ts@@ -1,18 +1,20 @@-import "../theme/find_in_link_widgets.css";-import {_sortFindResultsByMarkerPositions as sortFindResults,Collection,FindAndReplaceEditing,FindAndReplaceUtils,Plugin,+ setHighlightHandling,uid,type CommandExecuteEvent,+ type DowncastHighlightDescriptor,+ type DowncastInsertEvent,type FindAttributes,type FindResultType,type Marker,type Model,- type ModelElement+ type ModelItem,+ type ViewElement} from "ckeditor5";/** Adds search results for rendered link text that is not stored as CKEditor model text. */@@ -26,7 +28,15 @@ export default class FindInLinkWidgets extends Plugin {return "FindInLinkWidgets" as const;}+ /** Matches the running query against widget text, or `null` while no search is running. */+ private _findByText: FindByText | null = null;++ /** The spans wrapping each highlighted widget's matches, so they can be unwrapped again. */+ private _matchSpans = new WeakMap<ViewElement, HTMLElement[]>();+afterInit() {+ this._highlightMatchesInsteadOfWidget();+const findCommand = this.editor.commands.get("find");const replaceCommand = this.editor.commands.get("replace");const replaceAllCommand = this.editor.commands.get("replaceAll");@@ -81,6 +91,84 @@ export default class FindInLinkWidgets extends Plugin {);}+ /**+ * Replaces the class-on-the-whole-widget highlight `toWidget()` installs with one that wraps+ * only the matching characters. The rendered title lives in a `ViewUIElement`, whose DOM the+ * renderer and the mutation observer both skip, so the wrapper spans survive there.+ */+ private _highlightMatchesInsteadOfWidget() {+ const addHighlight = (element: ViewElement, descriptor: DowncastHighlightDescriptor) => {+ this._unwrapMatches(element);+ this._wrapMatches(element, descriptor);+ };+ const removeHighlight = (element: ViewElement) => this._unwrapMatches(element);++ for (const widgetName of SEARCHABLE_WIDGETS) {+ this.editor.editing.downcastDispatcher.on<DowncastInsertEvent>(+ `insert:${widgetName}`,+ (_eventInfo, data, conversionApi) => {+ /* v8 ignore next -- An insert event for a widget carries its element. */+ if (!data.item.is("element")) {+ return;+ }+ const viewElement = conversionApi.mapper.toViewElement(data.item);+ /* v8 ignore next -- The widget converter maps every element it inserts. */+ if (!viewElement) {+ return;+ }++ setHighlightHandling(+ viewElement, conversionApi.writer, addHighlight, removeHighlight+ );+ },+ { priority: "lowest" }+ );+ }+ }++ private _wrapMatches(element: ViewElement, descriptor: DowncastHighlightDescriptor) {+ const findByText = this._findByText;+ const item = this.editor.editing.mapper.toModelElement(element);+ /* v8 ignore next -- A highlighted widget is mapped and belongs to the running search. */+ if (!findByText || !item) {+ return;+ }++ const spans: HTMLElement[] = [];+ const matches = findMatches(textNodesOf(this.editor, element), item, findByText);+ // Wrap from the end so that splitting a text node leaves the earlier offsets in it valid.+ for (const { node, start, end } of matches.reverse()) {+ const match = node.splitText(start);+ match.splitText(end - start);++ const span = node.ownerDocument.createElement("span");+ span.className = [ descriptor.classes ].flat().join(" ");+ match.replaceWith(span);+ span.append(match);+ spans.push(span);+ }++ this._matchSpans.set(element, spans);+ }++ private _unwrapMatches(element: ViewElement) {+ for (const span of this._matchSpans.get(element) ?? []) {+ const parent = span.parentNode;+ /* v8 ignore next -- Spans are unwrapped once, while still in the widget's DOM. */+ if (!parent) {+ continue;+ }++ while (span.firstChild) {+ parent.insertBefore(span.firstChild, span);+ }+ span.remove();+ // Merge the split text back, so repeated searches do not fragment the widget's DOM.+ parent.normalize();+ }+ this._matchSpans.delete(element);+ }+private _addWidgetResults(query: string,options: FindAttributes | undefined,@@ -93,17 +181,21 @@ export default class FindInLinkWidgets extends Plugin {if (!state) {return;}- const findByText = editor.plugins+ this._findByText = editor.plugins.get(FindAndReplaceUtils).findByTextCallback(query, options ?? {});for (const root of model.document.getRoots()) {for (const item of model.createRangeIn(root).getItems()) {+ if (!item.is("element") || !SEARCHABLE_WIDGETS.has(item.name)) {+ continue;+ }+ const viewElement = editor.editing.mapper.toViewElement(item);// One marker identifies one atomic widget, so repeated matches remain one result.- const isMatch = item.is("element") && visibleText(editor, item).some(- (text) => findByText({ item, text }).length > 0- );- if (!isMatch) {+ const matches = viewElement+ ? findMatches(textNodesOf(editor, viewElement), item, this._findByText)+ : [];+ if (matches.length === 0) {continue;}@@ -127,16 +219,23 @@ export default class FindInLinkWidgets extends Plugin {}-function visibleText(editor: FindInLinkWidgets["editor"], element: ModelElement): string[] {- if (!SEARCHABLE_WIDGETS.has(element.name)) {- return [];- }+/** Reports every match as a character range, as `findByTextCallback()` does. */+type FindByText = (args: { item: ModelItem; text: string }) => FindResultType[];- const viewElement = editor.editing.mapper.toViewElement(element);- if (!viewElement) {- return [];+type WidgetMatch = { node: Text; start: number; end: number };++function findMatches(nodes: Text[], item: ModelItem, findByText: FindByText): WidgetMatch[] {+ const matches: WidgetMatch[] = [];+ for (const node of nodes) {+ for (const { start = 0, end = 0 } of findByText({ item, text: node.data })) {+ matches.push({ node, start, end });+ }}+ return matches;+}+/** Returns the DOM text nodes a widget displays, in the order the reader sees them. */+function textNodesOf(editor: FindInLinkWidgets["editor"], viewElement: ViewElement): Text[] {const domElement = editor.editing.view.domConverter.mapViewToDom(viewElement);if (!domElement) {return [];@@ -145,17 +244,17 @@ function visibleText(editor: FindInLinkWidgets["editor"], element: ModelElement)return textNodesIn(domElement);}-function textNodesIn(node: globalThis.Node): string[] {- const texts: string[] = [];+function textNodesIn(node: globalThis.Node): Text[] {if (node.nodeType === globalThis.Node.TEXT_NODE) {- const text = node.textContent?.trim();- return text ? [ text ] : [];+ const text = node as Text;+ return text.data.trim() ? [ text ] : [];}+ const nodes: Text[] = [];for (const child of node.childNodes) {- texts.push(...textNodesIn(child));+ nodes.push(...textNodesIn(child));}- return texts;+ return nodes;}function insertionIndex(diff --git a/packages/ckeditor5/src/theme/find_in_link_widgets.css b/packages/ckeditor5/src/theme/find_in_link_widgets.cssdeleted file mode 100644index 86b291f24b..0000000000--- a/packages/ckeditor5/src/theme/find_in_link_widgets.css+++ /dev/null@@ -1,9 +0,0 @@-/* Themes style anchors with their own background, which outranks the find highlight on the- reference link widget. Restate the CKEditor find colors at widget specificity. */-.ck-content .ck-widget.ck-find-result {- background: var(--ck-color-highlight-background);-}--.ck-content .ck-widget.ck-find-result_selected {- background: hsl(29, 100%, 60%);-}