Skip to content

Build your personal knowledge base with Trilium Notes

fix(editor): find text in link widgets (closes #11242)

Amp3f8ae20781c5
diff --git a/packages/ckeditor5/src/plugins.spec.ts b/packages/ckeditor5/src/plugins.spec.ts
index be009960f8..a855de4c05 100644
--- a/packages/ckeditor5/src/plugins.spec.ts
+++ b/packages/ckeditor5/src/plugins.spec.ts
@@ -9,6 +9,7 @@ import StrikethroughAsDel from "./plugins/strikethrough_as_del.js";
import { CHAT_INPUT_PLUGINS, COMMON_PLUGINS, CORE_PLUGINS, MEMO_PLUGINS, POPUP_EDITOR_PLUGINS } from "./plugins.js";
import CutToNotePlugin from "./plugins/cuttonote.js";
import Uploadfileplugin from "./plugins/file_upload/uploadfileplugin.js";
+import FindInLinkWidgets from "./plugins/find_in_link_widgets.js";
import TriliumFormatPainter from "./plugins/format_painter/format_painter.js";
import IncludeNote from "./plugins/includenote.js";
import InternalLinkPlugin from "./plugins/internallink.js";
@@ -79,6 +80,7 @@ describe("plugin lists", () => {
expect(COMMON_PLUGINS).toContain(InternalLinkPlugin);
expect(COMMON_PLUGINS).toContain(IncludeNote);
expect(COMMON_PLUGINS).toContain(LinkEmbed);
+ expect(COMMON_PLUGINS).toContain(FindInLinkWidgets);
expect(COMMON_PLUGINS).toContain(Uploadfileplugin);
});
diff --git a/packages/ckeditor5/src/plugins.ts b/packages/ckeditor5/src/plugins.ts
index d947637e77..46973f5d37 100644
--- a/packages/ckeditor5/src/plugins.ts
+++ b/packages/ckeditor5/src/plugins.ts
@@ -37,6 +37,7 @@ import ClipboardBareImage from "./plugins/clipboard_bare_image.js";
import ClipboardImageEmbed from "./plugins/clipboard_image_embed.js";
import TriliumSnippets from "./plugins/snippets/snippets.js";
import TriliumAiAssistant from "./plugins/ai_assistant/ai_assistant.js";
+import FindInLinkWidgets from "./plugins/find_in_link_widgets.js";
import CodeBlockToolbar from "./plugins/code_block_toolbar.js";
import CodeBlockLanguageDropdown from "./plugins/code_block_language_dropdown.js";
@@ -96,6 +97,7 @@ const TRILIUM_PLUGINS: typeof Plugin[] = [
ClipboardBareImage,
TriliumSnippets,
TriliumAiAssistant,
+ FindInLinkWidgets,
];
/**
diff --git a/packages/ckeditor5/src/plugins/find_in_link_widgets.spec.ts b/packages/ckeditor5/src/plugins/find_in_link_widgets.spec.ts
new file mode 100644
index 0000000000..49eaf3a6df
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/find_in_link_widgets.spec.ts
@@ -0,0 +1,188 @@
+import { safeHostname } from "@triliumnext/commons";
+import {
+ _setModelData as setModelData,
+ ClassicEditor,
+ Essentials,
+ FindAndReplaceEditing,
+ LinkEditing,
+ Paragraph,
+ type FindResultType
+} from "ckeditor5";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { createTestEditor } from "../../test/editor-kit.js";
+import { installGlobMock } from "../../test/globals-test-kit.js";
+import FindInLinkWidgets from "./find_in_link_widgets.js";
+import LinkEmbedEditing from "./link_embed/link_embed_editing.js";
+import ReferenceLink from "./referencelink.js";
+
+describe("FindInLinkWidgets", () => {
+ let editor: ClassicEditor;
+
+ beforeEach(async () => {
+ installGlobMock({
+ getComponentByEl: () => ({
+ loadReferenceLinkTitle: vi.fn((element: unknown) => {
+ if (element instanceof HTMLElement) {
+ element.textContent = "Reference match";
+ }
+ return Promise.resolve();
+ }),
+ renderLinkEmbed: vi.fn((container: HTMLElement, metadata: LinkEmbedMetadata) => {
+ if (metadata.embedType === "youtube") {
+ return;
+ }
+ appendText(
+ container,
+ metadata.title,
+ metadata.description,
+ metadata.siteName || safeHostname(metadata.url)
+ );
+ }),
+ renderLinkMention: vi.fn((container: HTMLElement, metadata: LinkEmbedMetadata) => {
+ appendText(container, metadata.title || safeHostname(metadata.url));
+ })
+ }),
+ getReferenceLinkTitle: vi.fn(async () => "Reference match"),
+ getReferenceLinkTitleSync: vi.fn(() => "Reference match")
+ });
+
+ editor = await createTestEditor([
+ Essentials,
+ Paragraph,
+ LinkEditing,
+ ReferenceLink,
+ LinkEmbedEditing,
+ FindAndReplaceEditing,
+ FindInLinkWidgets
+ ]);
+ });
+
+ it("finds text and all rendered link widgets in document order", () => {
+ setModelData(
+ editor.model,
+ '<paragraph>Plain match. <reference href="#root/ref"></reference> ' +
+ '<linkMention url="https://mention.example/" title="Mention match">' +
+ "</linkMention></paragraph>" +
+ '<linkEmbed url="https://card.example/" embedType="opengraph" title="Card match" ' +
+ 'description="Card description" siteName="Card site"></linkEmbed>'
+ );
+
+ const editingRoot = editor.editing.view.getDomRoot();
+ expect(editingRoot?.querySelector("a.reference-link")?.textContent).toBe("Reference match");
+ editor.execute("find", "match");
+
+ const state = editor.plugins.get(FindAndReplaceEditing).state;
+ expect(resultElementNames(state?.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();
+
+ editor.execute("findNext");
+ const selectedReference = editingRoot?.querySelector(
+ "a.reference-link.ck-find-result_selected"
+ );
+ expect(selectedReference).not.toBeNull();
+ });
+
+ it("matches only the text that each link widget displays", () => {
+ setModelData(
+ editor.model,
+ '<paragraph><linkMention url="https://mention-host.example/path">' +
+ "</linkMention></paragraph>" +
+ '<linkEmbed url="https://card-host.example/path" ' +
+ 'embedType="opengraph"></linkEmbed>' +
+ '<linkEmbed url="https://card.example/" embedType="opengraph" ' +
+ 'title="Exact Match Repeated" ' +
+ 'description="Description text Repeated" siteName="Site label"></linkEmbed>' +
+ '<linkEmbed url="https://www.youtube.com/watch?v=dQw4w9WgXcQ" ' +
+ 'embedType="youtube" ' +
+ 'title="Hidden metadata"></linkEmbed>'
+ );
+
+ expect(findCount(editor, "mention-host.example")).toBe(1);
+ expect(findCount(editor, "card-host.example")).toBe(1);
+ expect(findCount(editor, "Description text")).toBe(1);
+ expect(findCount(editor, "Site label")).toBe(1);
+ expect(findCount(editor, "Repeated")).toBe(1);
+ expect(findCount(editor, "Match", { matchCase: true })).toBe(1);
+ expect(findCount(editor, "match", { matchCase: true })).toBe(0);
+ expect(findCount(editor, "act", { wholeWords: true })).toBe(0);
+ expect(findCount(editor, "Hidden metadata")).toBe(0);
+ });
+
+ it("skips a widget during replacement and still replaces normal text", () => {
+ setModelData(
+ editor.model,
+ '<paragraph><reference href="#root/ref"></reference> match</paragraph>'
+ );
+ expect(editor.editing.view.getDomRoot()?.querySelector("a.reference-link")?.textContent)
+ .toBe("Reference match");
+ editor.execute("find", "match");
+
+ const state = editor.plugins.get(FindAndReplaceEditing).state;
+ expect(resultElementNames(state?.results ?? [])).toEqual([ "reference", "text" ]);
+ editor.execute("replace", "done", state?.highlightedResult);
+
+ expect(editor.getData()).toContain("match");
+ expect(resultElementNames(state?.highlightedResult ? [ state.highlightedResult ] : []))
+ .toEqual([ "text" ]);
+ editor.execute("replace", "done", state?.highlightedResult);
+ expect(editor.getData()).toContain("done");
+ expect(editor.getData()).toContain('class="reference-link"');
+
+ setModelData(
+ editor.model,
+ '<paragraph>match <reference href="#root/ref"></reference></paragraph>'
+ );
+ expect(editor.editing.view.getDomRoot()?.querySelector("a.reference-link")?.textContent)
+ .toBe("Reference match");
+ editor.execute("find", "match");
+
+ expect(state?.results.length).toBe(2);
+ editor.execute("replaceAll", "done", state?.results);
+
+ expect(editor.getData()).toContain("done");
+ expect(editor.getData()).toContain('class="reference-link"');
+ expect(state?.results.length).toBe(1);
+ expect(state?.highlightedResult).not.toBeNull();
+
+ editor.execute("replace", "broken", state?.highlightedResult);
+ expect(editor.getData()).toContain('class="reference-link"');
+ expect(editor.getData()).not.toContain("broken");
+ });
+});
+
+function findCount(
+ editor: ClassicEditor,
+ text: string,
+ options: { matchCase?: boolean; wholeWords?: boolean } = {}
+): number {
+ editor.execute("find", text, options);
+ return editor.plugins.get(FindAndReplaceEditing).state?.results.length ?? 0;
+}
+
+function resultElementNames(results: Iterable<FindResultType>): string[] {
+ const names: string[] = [];
+ for (const result of results) {
+ let name = "text";
+ for (const item of result.marker?.getRange().getItems() ?? []) {
+ if (item.is("element")) {
+ name = item.name;
+ break;
+ }
+ }
+ names.push(name);
+ }
+ return names;
+}
+
+function appendText(container: HTMLElement, ...values: Array<string | undefined>): void {
+ for (const value of values) {
+ if (value) {
+ container.append(document.createTextNode(value));
+ }
+ }
+}
diff --git a/packages/ckeditor5/src/plugins/find_in_link_widgets.ts b/packages/ckeditor5/src/plugins/find_in_link_widgets.ts
new file mode 100644
index 0000000000..7a810af646
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/find_in_link_widgets.ts
@@ -0,0 +1,187 @@
+import {
+ _sortFindResultsByMarkerPositions as sortFindResults,
+ Collection,
+ FindAndReplaceEditing,
+ FindAndReplaceUtils,
+ Plugin,
+ uid,
+ type CommandExecuteEvent,
+ type FindAttributes,
+ type FindResultType,
+ type Marker,
+ type Model,
+ type ModelElement
+} from "ckeditor5";
+
+/** Adds search results for rendered link text that is not stored as CKEditor model text. */
+export default class FindInLinkWidgets extends Plugin {
+
+ static get requires() {
+ return [ FindAndReplaceEditing ] as const;
+ }
+
+ static get pluginName() {
+ return "FindInLinkWidgets" as const;
+ }
+
+ afterInit() {
+ const findCommand = this.editor.commands.get("find");
+ findCommand?.on<CommandExecuteEvent>(
+ "execute",
+ (eventInfo, [ query, options ]) => {
+ if (typeof query !== "string" || !query || !isFindCommandResult(eventInfo.return)) {
+ return;
+ }
+
+ this._addWidgetResults(
+ query,
+ options as FindAttributes | undefined,
+ eventInfo.return.results
+ );
+ },
+ { priority: "lowest" }
+ );
+
+ const replaceCommand = this.editor.commands.get("replace");
+ replaceCommand?.on<CommandExecuteEvent>(
+ "execute",
+ (eventInfo, [ , result ]) => {
+ if (isWidgetResult(result)) {
+ eventInfo.stop();
+ this.editor.execute("findNext");
+ }
+ },
+ { priority: "high" }
+ );
+
+ const replaceAllCommand = this.editor.commands.get("replaceAll");
+ replaceAllCommand?.on<CommandExecuteEvent>(
+ "execute",
+ (_eventInfo, args) => {
+ const results = args[1];
+ if (!(results instanceof Collection)) {
+ return;
+ }
+
+ const replaceableResults = [ ...results ].filter(
+ (result) => !isWidgetResult(result)
+ );
+ if (replaceableResults.length !== results.length) {
+ args[1] = new Collection(replaceableResults);
+ }
+ },
+ { priority: "high" }
+ );
+ }
+
+ private _addWidgetResults(
+ query: string,
+ options: FindAttributes | undefined,
+ commandResults: Collection<FindResultType>
+ ) {
+ const { editor } = this;
+ const { model } = editor;
+ const state = editor.plugins.get(FindAndReplaceEditing).state;
+ const findByText = editor.plugins
+ .get(FindAndReplaceUtils)
+ .findByTextCallback(query, options ?? {});
+ if (!state) {
+ return;
+ }
+
+ for (const rootName of model.document.getRootNames()) {
+ const root = model.document.getRoot(rootName);
+ if (!root) {
+ continue;
+ }
+
+ for (const item of model.createRangeIn(root).getItems()) {
+ // 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) {
+ continue;
+ }
+
+ const markerName = `findResult:widget-${uid()}`;
+ let marker: Marker | undefined;
+ model.change((writer) => {
+ marker = writer.addMarker(markerName, {
+ usingOperation: false,
+ affectsData: false,
+ range: model.createRangeOn(item)
+ });
+ });
+ if (!marker) {
+ continue;
+ }
+
+ const result: FindResultType = { id: markerName, label: query, marker };
+ state.results.add(result, insertionIndex(model, state.results, result));
+ if (commandResults !== state.results) {
+ commandResults.add(result, insertionIndex(model, commandResults, result));
+ }
+ }
+ }
+
+ state.highlightedResult = state.results.first;
+ }
+
+}
+
+function visibleText(editor: FindInLinkWidgets["editor"], element: ModelElement): string[] {
+ if (!SEARCHABLE_WIDGETS.has(element.name)) {
+ return [];
+ }
+
+ const viewElement = editor.editing.mapper.toViewElement(element);
+ if (!viewElement) {
+ return [];
+ }
+
+ const domElement = editor.editing.view.domConverter.mapViewToDom(viewElement);
+ if (!domElement) {
+ return [];
+ }
+
+ return textNodesIn(domElement);
+}
+
+function textNodesIn(node: globalThis.Node): string[] {
+ const texts: string[] = [];
+ if (node.nodeType === globalThis.Node.TEXT_NODE) {
+ const text = node.textContent?.trim();
+ return text ? [ text ] : [];
+ }
+
+ for (const child of node.childNodes) {
+ texts.push(...textNodesIn(child));
+ }
+ return texts;
+}
+
+function insertionIndex(
+ model: Model,
+ results: Collection<FindResultType>,
+ result: FindResultType
+): number {
+ return sortFindResults(model, [ ...results, result ]).indexOf(result);
+}
+
+function isFindCommandResult(value: unknown): value is { results: Collection<FindResultType> } {
+ return typeof value === "object" && value !== null && "results" in value &&
+ value.results instanceof Collection;
+}
+
+function isWidgetResult(value: unknown): value is FindResultType {
+ if (typeof value !== "object" || value === null || !("marker" in value)) {
+ return false;
+ }
+
+ const marker = value.marker;
+ return typeof marker === "object" && marker !== null && "name" in marker &&
+ typeof marker.name === "string" && marker.name.startsWith("findResult:widget-");
+}
+
+const SEARCHABLE_WIDGETS = new Set([ "reference", "linkMention", "linkEmbed" ]);