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
test(editor): cover link-widget find command paths
Ampf7b80acd6240
diff --git a/packages/ckeditor5/src/plugins.ts b/packages/ckeditor5/src/plugins.tsindex 46973f5d37..769a6e402e 100644--- a/packages/ckeditor5/src/plugins.ts+++ b/packages/ckeditor5/src/plugins.ts@@ -22,6 +22,7 @@ import TriliumFormatPainter from "./plugins/format_painter/format_painter.js";import IncludeNote from "./plugins/includenote.js";import LinkEmbed from "./plugins/link_embed/link_embed.js";import Uploadfileplugin from "./plugins/file_upload/uploadfileplugin.js";+import FindInLinkWidgets from "./plugins/find_in_link_widgets.js";import SyntaxHighlighting from "./plugins/syntax_highlighting/index.js";import Kbd from "./plugins/keyboard_marker/keyboard_marker.js";import Mermaid from "./plugins/mermaid/mermaid.js";@@ -37,7 +38,6 @@ 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";diff --git a/packages/ckeditor5/src/plugins/find_in_link_widgets.spec.ts b/packages/ckeditor5/src/plugins/find_in_link_widgets.spec.tsindex 49eaf3a6df..99d369d7e5 100644--- a/packages/ckeditor5/src/plugins/find_in_link_widgets.spec.ts+++ b/packages/ckeditor5/src/plugins/find_in_link_widgets.spec.ts@@ -6,7 +6,8 @@ import {FindAndReplaceEditing,LinkEditing,Paragraph,- type FindResultType+ type FindResultType,+ type ModelElement} from "ckeditor5";import { beforeEach, describe, expect, it, vi } from "vitest";@@ -70,12 +71,17 @@ describe("FindInLinkWidgets", () => {const editingRoot = editor.editing.view.getDomRoot();expect(editingRoot?.querySelector("a.reference-link")?.textContent).toBe("Reference match");- editor.execute("find", "match");+ const commandResult = editor.execute("find", "match") as {+ results: Iterable<FindResultType>;+ };const state = editor.plugins.get(FindAndReplaceEditing).state;expect(resultElementNames(state?.results ?? [])).toEqual(["text", "reference", "linkMention", "linkEmbed"]);+ 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();@@ -113,6 +119,77 @@ describe("FindInLinkWidgets", () => {expect(findCount(editor, "Hidden metadata")).toBe(0);});+ it("ignores widgets that do not have a rendered DOM element", () => {+ setModelData(+ editor.model,+ '<paragraph><reference href="#root/first"></reference></paragraph>' ++ '<paragraph><reference href="#root/second"></reference></paragraph>' ++ '<paragraph><reference href="#root/third"></reference></paragraph>'+ );++ const root = editor.model.document.getRoot();+ if (!root) {+ throw new Error("The test editor has no model root.");+ }+ const references = [ ...editor.model.createRangeIn(root).getItems() ].filter(+ (item): item is ModelElement => item.is("element", "reference")+ );+ expect(references).toHaveLength(3);++ const [ first, second ] = references;+ if (!first || !second) {+ throw new Error("The test editor did not create the reference widgets.");+ }+ editor.editing.mapper.unbindModelElement(first);+ const secondView = editor.editing.mapper.toViewElement(second);+ if (!secondView) {+ throw new Error("The second reference has no view element.");+ }+ const secondDom = editor.editing.view.domConverter.mapViewToDom(secondView);+ if (!secondDom) {+ throw new Error("The second reference has no DOM element.");+ }+ editor.editing.view.domConverter.unbindDomElement(secondDom);++ expect(findCount(editor, "Reference match")).toBe(1);+ });++ it("ignores unsupported searches and blank rendered text nodes", () => {+ setModelData(+ editor.model,+ '<paragraph><linkMention url="https://mention.example/" title="Mention match">' ++ "</linkMention></paragraph>"+ );+ const mention = editor.editing.view.getDomRoot()?.querySelector("span.link-mention");+ if (!mention) {+ throw new Error("The test editor did not render the link mention.");+ }+ mention.append(document.createTextNode(" "));++ editor.execute("find", () => []);+ expect(editor.plugins.get(FindAndReplaceEditing).state?.results).toHaveLength(0);+ findCount(editor, "");+ expect(resultElementNames(editor.plugins.get(FindAndReplaceEditing).state?.results ?? []))+ .not.toContain("linkMention");+ expect(findCount(editor, "absent")).toBe(0);+ });++ it("preserves replace-all behavior when there are no widget results", () => {+ setModelData(editor.model, "<paragraph>first match</paragraph>");+ editor.execute("find", "match");++ const state = editor.plugins.get(FindAndReplaceEditing).state;+ if (!state) {+ throw new Error("FindAndReplaceEditing has no state.");+ }+ editor.execute("replaceAll", "done", state.results);+ expect(editor.getData()).toContain("first done");++ setModelData(editor.model, "<paragraph>second match</paragraph>");+ editor.execute("replaceAll", "done", "match");+ expect(editor.getData()).toContain("second done");+ });+it("skips a widget during replacement and still replaces normal text", () => {setModelData(editor.model,diff --git a/packages/ckeditor5/src/plugins/find_in_link_widgets.ts b/packages/ckeditor5/src/plugins/find_in_link_widgets.tsindex 7a810af646..5a7166edac 100644--- a/packages/ckeditor5/src/plugins/find_in_link_widgets.ts+++ b/packages/ckeditor5/src/plugins/find_in_link_widgets.ts@@ -26,27 +26,33 @@ export default class FindInLinkWidgets extends Plugin {afterInit() {const findCommand = this.editor.commands.get("find");- findCommand?.on<CommandExecuteEvent>(+ const replaceCommand = this.editor.commands.get("replace");+ const replaceAllCommand = this.editor.commands.get("replaceAll");+ /* v8 ignore next -- FindAndReplaceEditing registers all three required commands. */+ if (!findCommand || !replaceCommand || !replaceAllCommand) {+ return;+ }++ findCommand.on<CommandExecuteEvent>("execute",(eventInfo, [ query, options ]) => {- if (typeof query !== "string" || !query || !isFindCommandResult(eventInfo.return)) {+ if (typeof query !== "string" || !query) {return;}this._addWidgetResults(query,options as FindAttributes | undefined,- eventInfo.return.results+ (eventInfo.return as { results: Collection<FindResultType> }).results);},{ priority: "lowest" });- const replaceCommand = this.editor.commands.get("replace");- replaceCommand?.on<CommandExecuteEvent>(+ replaceCommand.on<CommandExecuteEvent>("execute",(eventInfo, [ , result ]) => {- if (isWidgetResult(result)) {+ if (isWidgetResult(result as MarkedFindResult)) {eventInfo.stop();this.editor.execute("findNext");}@@ -54,8 +60,7 @@ export default class FindInLinkWidgets extends Plugin {{ priority: "high" });- const replaceAllCommand = this.editor.commands.get("replaceAll");- replaceAllCommand?.on<CommandExecuteEvent>(+ replaceAllCommand.on<CommandExecuteEvent>("execute",(_eventInfo, args) => {const results = args[1];@@ -64,7 +69,7 @@ export default class FindInLinkWidgets extends Plugin {}const replaceableResults = [ ...results ].filter(- (result) => !isWidgetResult(result)+ (result) => !isWidgetResult(result as MarkedFindResult));if (replaceableResults.length !== results.length) {args[1] = new Collection(replaceableResults);@@ -82,19 +87,15 @@ export default class FindInLinkWidgets extends Plugin {const { editor } = this;const { model } = editor;const state = editor.plugins.get(FindAndReplaceEditing).state;- const findByText = editor.plugins- .get(FindAndReplaceUtils)- .findByTextCallback(query, options ?? {});+ /* v8 ignore next -- The required plugin creates its state in init(). */if (!state) {return;}+ const findByText = editor.plugins+ .get(FindAndReplaceUtils)+ .findByTextCallback(query, options ?? {});- for (const rootName of model.document.getRootNames()) {- const root = model.document.getRoot(rootName);- if (!root) {- continue;- }-+ for (const root of model.document.getRoots()) {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(@@ -105,23 +106,17 @@ export default class FindInLinkWidgets extends Plugin {}const markerName = `findResult:widget-${uid()}`;- let marker: Marker | undefined;- model.change((writer) => {- marker = writer.addMarker(markerName, {+ const marker: Marker = model.change((writer) =>+ 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));- }+ commandResults.add(result, insertionIndex(model, commandResults, result));}}@@ -169,19 +164,10 @@ function insertionIndex(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;- }+type MarkedFindResult = FindResultType & { marker: Marker };- const marker = value.marker;- return typeof marker === "object" && marker !== null && "name" in marker &&- typeof marker.name === "string" && marker.name.startsWith("findResult:widget-");+function isWidgetResult(value: MarkedFindResult): boolean {+ return value.marker.name.startsWith("findResult:widget-");}const SEARCHABLE_WIDGETS = new Set([ "reference", "linkMention", "linkEmbed" ]);