Skip to content

Build your personal knowledge base with Trilium Notes

link previews: split linkembed.ts into a link_embed plugin directory

Elian Doranb01ef18190fd
diff --git a/packages/ckeditor5/src/plugins.spec.ts b/packages/ckeditor5/src/plugins.spec.ts
index 93aef29468..76d58863cc 100644
--- a/packages/ckeditor5/src/plugins.spec.ts
+++ b/packages/ckeditor5/src/plugins.spec.ts
@@ -7,7 +7,7 @@ import CutToNotePlugin from "./plugins/cuttonote.js";
import Uploadfileplugin from "./plugins/file_upload/uploadfileplugin.js";
import IncludeNote from "./plugins/includenote.js";
import InternalLinkPlugin from "./plugins/internallink.js";
-import LinkEmbed from "./plugins/linkembed.js";
+import LinkEmbed from "./plugins/link_embed/link_embed.js";
import MentionCustomization from "./plugins/mention_customization.js";
import ReferenceLink from "./plugins/referencelink.js";
diff --git a/packages/ckeditor5/src/plugins.ts b/packages/ckeditor5/src/plugins.ts
index dbc14cb846..d3314ba02a 100644
--- a/packages/ckeditor5/src/plugins.ts
+++ b/packages/ckeditor5/src/plugins.ts
@@ -14,7 +14,7 @@ import IndentBlockShortcutPlugin from "./plugins/indent_block_shortcut.js";
import MarkdownImportPlugin from "./plugins/markdownimport.js";
import MentionCustomization from "./plugins/mention_customization.js";
import IncludeNote from "./plugins/includenote.js";
-import LinkEmbed from "./plugins/linkembed.js";
+import LinkEmbed from "./plugins/link_embed/link_embed.js";
import Uploadfileplugin from "./plugins/file_upload/uploadfileplugin.js";
import SyntaxHighlighting from "./plugins/syntax_highlighting/index.js";
import { Kbd } from "@triliumnext/ckeditor5-keyboard-marker";
@@ -42,7 +42,7 @@ import AdmonitionTypeDropdown from "./plugins/admonition_type_dropdown.js";
import AdmonitionToolbar from "./plugins/admonition_toolbar.js";
import IncludeNoteBoxSizeDropdown from "./plugins/include_note_box_size_dropdown.js";
import IncludeNoteToolbar from "./plugins/include_note_toolbar.js";
-import LinkEmbedToolbar from "./plugins/link_embed_toolbar.js";
+import LinkEmbedToolbar from "./plugins/link_embed/link_embed_toolbar.js";
import TodoListMultistate from "./plugins/todo_list_multistate/todo_list_multistate.js";
import TodoListUncheckOnEnter from "./plugins/todo_list_uncheck_on_enter.js";
import CollapsibleListItems from "./plugins/collapsible_list_items.js";
diff --git a/packages/ckeditor5/src/plugins/include_note_toolbar.spec.ts b/packages/ckeditor5/src/plugins/include_note_toolbar.spec.ts
index 2d87c7ec7e..601775269f 100644
--- a/packages/ckeditor5/src/plugins/include_note_toolbar.spec.ts
+++ b/packages/ckeditor5/src/plugins/include_note_toolbar.spec.ts
@@ -6,7 +6,7 @@ import { installGlobMock } from "../../test/globals-test-kit.js";
import IncludeNote from "./includenote.js";
import IncludeNoteBoxSizeDropdown from "./include_note_box_size_dropdown.js";
import IncludeNoteToolbar from "./include_note_toolbar.js";
-import LinkEmbed from "./linkembed.js";
+import LinkEmbed from "./link_embed/link_embed.js";
// ---------------------------------------------------------------------------
// Minimal inline plugin that registers a section widget WITHOUT a class
diff --git a/packages/ckeditor5/src/plugins/link_embed/link_embed.spec.ts b/packages/ckeditor5/src/plugins/link_embed/link_embed.spec.ts
new file mode 100644
index 0000000000..dfc5f406c1
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/link_embed/link_embed.spec.ts
@@ -0,0 +1,23 @@
+import type { ClassicEditor } from "ckeditor5";
+import { beforeEach, describe, expect, it } from "vitest";
+
+import { createTestEditor, installLinkEmbedComponentMock, LINK_EMBED_TEST_PLUGINS } from "../../../test/link-embed-kit.js";
+import LinkEmbed from "./link_embed.js";
+import { CHANGE_LINK_DISPLAY_COMMAND, LINK_EMBED_COMMAND, REMOVE_LINK_EMBED_COMMAND } from "./link_embed_commands.js";
+
+describe("LinkEmbed", () => {
+ let editor: ClassicEditor;
+
+ beforeEach(async () => {
+ installLinkEmbedComponentMock();
+ editor = await createTestEditor(LINK_EMBED_TEST_PLUGINS);
+ });
+
+ it("loads the plugin, registers the commands and the toolbar button", () => {
+ expect(editor.plugins.get(LinkEmbed)).toBeInstanceOf(LinkEmbed);
+ expect(editor.commands.get(LINK_EMBED_COMMAND)).toBeDefined();
+ expect(editor.commands.get(CHANGE_LINK_DISPLAY_COMMAND)).toBeDefined();
+ expect(editor.commands.get(REMOVE_LINK_EMBED_COMMAND)).toBeDefined();
+ expect(editor.ui.componentFactory.has("linkEmbed")).toBe(true);
+ });
+});
diff --git a/packages/ckeditor5/src/plugins/link_embed/link_embed.ts b/packages/ckeditor5/src/plugins/link_embed/link_embed.ts
new file mode 100644
index 0000000000..d59ab9ffac
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/link_embed/link_embed.ts
@@ -0,0 +1,30 @@
+import { Plugin } from 'ckeditor5';
+import AutoLinkToMention from './link_embed_autodetect.js';
+import LinkEmbedEditing from './link_embed_editing.js';
+import LinkEmbedUI from './link_embed_ui.js';
+
+export {
+ CHANGE_LINK_DISPLAY_COMMAND,
+ LINK_DISPLAY_MODES,
+ LINK_EMBED_COMMAND,
+ REMOVE_LINK_EMBED_COMMAND,
+ type LinkDisplayMode
+} from './link_embed_commands.js';
+
+/**
+ * Link previews: rich widgets for external URLs, in three shapes — an inline mention (favicon +
+ * title pill), a block card (thumbnail, title, description) and a block embed (a player, for URLs
+ * that have one). A fourth mode, "Plain link", converts back to an ordinary link.
+ *
+ * The feature is assembled from:
+ * - {@link LinkEmbedEditing} — schema, converters and the commands ({@link module:link_embed_commands});
+ * - {@link LinkEmbedUI} — the toolbar button and its balloon form;
+ * - {@link AutoLinkToMention} — auto-conversion of typed/pasted URLs;
+ * - LinkEmbedToolbar (loaded separately by the host) — the widget toolbar, whose Display dropdown
+ * also serves the native link balloon.
+ */
+export default class LinkEmbed extends Plugin {
+ static get requires() {
+ return [LinkEmbedEditing, LinkEmbedUI, AutoLinkToMention];
+ }
+}
diff --git a/packages/ckeditor5/src/plugins/link_embed/link_embed_autodetect.spec.ts b/packages/ckeditor5/src/plugins/link_embed/link_embed_autodetect.spec.ts
new file mode 100644
index 0000000000..55c817863b
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/link_embed/link_embed_autodetect.spec.ts
@@ -0,0 +1,410 @@
+import { _setModelData as setModelData, type ClassicEditor } from "ckeditor5";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import {
+ addLinkedText,
+ autoLinkIn,
+ createTestEditor,
+ findElement,
+ flushFetch,
+ hostConfig,
+ installLinkEmbedComponentMock,
+ LINK_EMBED_TEST_PLUGINS,
+ META,
+ urlLeftAloneOnItsOwnLine,
+ useDeferredFetch,
+ type LinkEmbedComponentMocks
+} from "../../../test/link-embed-kit.js";
+import { LINK_EMBED_COMMAND } from "./link_embed_commands.js";
+
+describe("AutoLinkToMention", () => {
+ let editor: ClassicEditor;
+ let fetchLinkMetadata: LinkEmbedComponentMocks["fetchLinkMetadata"];
+
+ beforeEach(async () => {
+ ({ fetchLinkMetadata } = installLinkEmbedComponentMock());
+ editor = await createTestEditor(LINK_EMBED_TEST_PLUGINS);
+ });
+
+ it("converts a bare linked URL into a linkMention after fetching metadata", async () => {
+ const url = "https://example.com/article";
+ addLinkedText(editor, url);
+
+ await flushFetch();
+
+ expect(fetchLinkMetadata).toHaveBeenCalledWith(url);
+ const mention = findElement(editor, "linkMention");
+ expect(mention).toBeDefined();
+ expect(mention?.getAttribute("url")).toBe(url);
+ expect(mention?.getAttribute("title")).toBe(META.title);
+ });
+
+ it("leaves the plain link untouched when the metadata could not be resolved, and says why", async () => {
+ const url = "https://blocked.example.com/article";
+ fetchLinkMetadata.mockResolvedValueOnce({ url, embedType: "opengraph", title: "blocked.example.com", unresolved: true });
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+
+ addLinkedText(editor, url);
+ await flushFetch();
+
+ expect(fetchLinkMetadata).toHaveBeenCalledWith(url);
+ expect(findElement(editor, "linkMention")).toBeUndefined();
+ expect(findElement(editor, "linkEmbed")).toBeUndefined();
+ // The link AutoLink created is still there, as plain linked text.
+ expect(editor.getData()).toContain(`<a href="${url}">${url}</a>`);
+ // The warning says what happened but never names the URL: a console gets screenshotted and
+ // pasted into bug reports, and a pasted link can carry a one-time token.
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining("Link preview dropped"));
+ expect(warn).not.toHaveBeenCalledWith(expect.stringContaining(url));
+
+ warn.mockRestore();
+ });
+
+ it("does not auto-convert when autoLinkPreviewsEnabled is false, but still offers the insert command", async () => {
+ const url = "https://example.com/article";
+ editor = await createTestEditor(LINK_EMBED_TEST_PLUGINS, hostConfig({ autoLinkPreviewsEnabled: false }));
+
+ addLinkedText(editor, url);
+ await flushFetch();
+
+ // The URL is not even looked up: the check runs before the metadata request.
+ expect(fetchLinkMetadata).not.toHaveBeenCalled();
+ expect(findElement(editor, "linkMention")).toBeUndefined();
+ expect(editor.getData()).toContain(`<a href="${url}">${url}</a>`);
+
+ // Inserting a preview by hand is unaffected by the option: only auto-detection is gated.
+ await editor.execute(LINK_EMBED_COMMAND, { url, mode: "card" });
+ expect(findElement(editor, "linkEmbed")?.getAttribute("url")).toBe(url);
+ });
+
+ it("re-reads a getter on every detected URL, so toggling the option needs no new editor", async () => {
+ let enabled = false;
+ editor = await createTestEditor(LINK_EMBED_TEST_PLUGINS, hostConfig({ autoLinkPreviewsEnabled: () => enabled }));
+
+ addLinkedText(editor, "https://example.com/off");
+ await flushFetch();
+ expect(findElement(editor, "linkMention")).toBeUndefined();
+
+ // Flip the option on the same editor instance — the next detected URL converts.
+ enabled = true;
+ addLinkedText(editor, "https://example.com/on");
+ await flushFetch();
+ expect(findElement(editor, "linkMention")).toBeDefined();
+ });
+
+ // -----------------------------------------------------------------------
+ // Placement: what shape an auto-detected URL takes, and why
+ // -----------------------------------------------------------------------
+
+ describe("placement", () => {
+ const PLAIN_URL = "https://example.com/article";
+ const VIDEO_URL = "https://youtube.com/watch?v=abc12345678";
+
+ /** Makes the next fetch report `url` as embeddable, the way a YouTube link comes back. */
+ function embeddable(url: string) {
+ fetchLinkMetadata.mockResolvedValueOnce({ ...META, url, embedType: "youtube" });
+ }
+
+ it("turns a URL left alone on its own line into a card", async () => {
+ autoLinkIn(editor, urlLeftAloneOnItsOwnLine(PLAIN_URL), PLAIN_URL);
+ await flushFetch();
+
+ expect(findElement(editor, "linkMention")).toBeUndefined();
+ const embed = findElement(editor, "linkEmbed");
+ expect(embed?.getAttribute("url")).toBe(PLAIN_URL);
+ // "opengraph" is what the renderer shows as a card rather than a player.
+ expect(embed?.getAttribute("embedType")).toBe("opengraph");
+ });
+
+ it("turns an embeddable URL left alone on its own line into a player", async () => {
+ embeddable(VIDEO_URL);
+
+ autoLinkIn(editor, urlLeftAloneOnItsOwnLine(VIDEO_URL), VIDEO_URL);
+ await flushFetch();
+
+ expect(findElement(editor, "linkMention")).toBeUndefined();
+ expect(findElement(editor, "linkEmbed")?.getAttribute("embedType")).toBe("youtube");
+ });
+
+ it("keeps the URL inline while the caret is still on its line, embeddable or not", async () => {
+ // The user typed a space, not Enter: they may still be writing that sentence, so the URL
+ // is alone only by accident. Nothing has been *left* alone yet.
+ embeddable(VIDEO_URL);
+ addLinkedText(editor, VIDEO_URL);
+ await flushFetch();
+
+ expect(findElement(editor, "linkEmbed")).toBeUndefined();
+ expect(findElement(editor, "linkMention")?.getAttribute("url")).toBe(VIDEO_URL);
+ });
+
+ it("keeps the URL inline when text sits beside it on the line", async () => {
+ autoLinkIn(editor, `<paragraph>See ${PLAIN_URL}</paragraph><paragraph>[]</paragraph>`, PLAIN_URL);
+ await flushFetch();
+
+ expect(findElement(editor, "linkEmbed")).toBeUndefined();
+ expect(findElement(editor, "linkMention")).toBeDefined();
+ });
+
+ it("keeps the URL inline inside a list item, a quote and a heading", async () => {
+ // A block preview inside these reads as a layout accident, so they stay inline — even
+ // though the URL is alone in its block and the caret has moved on.
+ const blocks = {
+ "list item": `<paragraph listIndent="0" listItemId="a" listType="bulleted">${PLAIN_URL}</paragraph>`,
+ quote: `<blockQuote><paragraph>${PLAIN_URL}</paragraph></blockQuote>`,
+ heading: `<heading2>${PLAIN_URL}</heading2>`
+ };
+
+ for (const block of Object.values(blocks)) {
+ autoLinkIn(editor, `${block}<paragraph>[]</paragraph>`, PLAIN_URL);
+ await flushFetch();
+
+ expect(findElement(editor, "linkEmbed")).toBeUndefined();
+ expect(findElement(editor, "linkMention")).toBeDefined();
+ }
+ });
+
+ it("leaves the caret where the user moved it, even if they typed while the fetch was in flight", async () => {
+ const { resolveFetch } = useDeferredFetch(fetchLinkMetadata);
+ autoLinkIn(editor, urlLeftAloneOnItsOwnLine(PLAIN_URL), PLAIN_URL);
+
+ // The user carries on typing on the new line while the metadata is still being fetched.
+ editor.model.change((writer) => {
+ const caret = editor.model.document.selection.getFirstPosition();
+ if (!caret) {
+ throw new Error("Expected a caret position.");
+ }
+ writer.insertText("hello", caret);
+ });
+
+ resolveFetch({ ...META, url: PLAIN_URL });
+ await flushFetch();
+
+ // The card took over the URL's paragraph without dragging the caret back into it: the
+ // typed text is intact and the caret still sits after it.
+ expect(findElement(editor, "linkEmbed")).toBeDefined();
+ expect(editor.getData()).toContain("<p>hello</p>");
+
+ const caretBlock = editor.model.document.selection.getFirstPosition()?.parent;
+ expect(caretBlock?.is("element", "paragraph")).toBe(true);
+ });
+ });
+
+ it("ignores a labeled link whose text differs from the href", async () => {
+ addLinkedText(editor, "https://example.com/article", "click here");
+
+ await flushFetch();
+
+ expect(findElement(editor, "linkMention")).toBeUndefined();
+ expect(fetchLinkMetadata).not.toHaveBeenCalled();
+ });
+
+ it("ignores non-http(s) links that fail the embeddable URL regex", async () => {
+ addLinkedText(editor, "mailto:[email protected]");
+
+ await flushFetch();
+
+ expect(findElement(editor, "linkMention")).toBeUndefined();
+ expect(fetchLinkMetadata).not.toHaveBeenCalled();
+ });
+
+ it("skips non-text items in the affected range before reaching the URL text", async () => {
+ const url = "https://example.com/break";
+
+ // Put a softBreak (an inline element, not a text proxy) before the URL text so
+ // the range walker yields a non-$textProxy item first, then the matching text.
+ setModelData(editor.model, "<paragraph>[]</paragraph>");
+ editor.model.change((writer) => {
+ const paragraph = editor.model.document.getRoot()?.getChild(0);
+ if (!paragraph?.is("element")) {
+ throw new Error("Expected a paragraph block.");
+ }
+ writer.insertElement("softBreak", paragraph, 0);
+ writer.insertText(url, paragraph, "end");
+ });
+ editor.model.change((writer) => {
+ const paragraph = editor.model.document.getRoot()?.getChild(0);
+ if (paragraph?.is("element")) {
+ writer.setAttribute("linkHref", url, writer.createRangeIn(paragraph));
+ }
+ });
+
+ await flushFetch();
+
+ expect(fetchLinkMetadata).toHaveBeenCalledWith(url);
+ expect(findElement(editor, "linkMention")).toBeDefined();
+ });
+
+ it("ignores undo batches that carry no linkHref attribute change", async () => {
+ // Type plain text, then undo it: the undo batch is flagged isUndo but its diff is
+ // an insert/remove change, exercising the non-attribute skip in the undo branch.
+ setModelData(editor.model, "<paragraph>[]</paragraph>");
+ editor.model.change((writer) => {
+ const paragraph = editor.model.document.getRoot()?.getChild(0);
+ if (paragraph?.is("element")) {
+ writer.insertText("hello", paragraph, 0);
+ }
+ });
+
+ editor.execute("undo");
+ await flushFetch();
+
+ expect(fetchLinkMetadata).not.toHaveBeenCalled();
+ });
+
+ it("records the URL on undo and does not re-convert it afterwards", async () => {
+ const url = "https://example.com/again";
+
+ // Apply the link to a LABELED link (text != href) so no conversion happens yet.
+ setModelData(editor.model, "<paragraph>click here[]</paragraph>");
+ editor.model.change((writer) => {
+ const paragraph = editor.model.document.getRoot()?.getChild(0);
+ if (paragraph?.is("element")) {
+ writer.setAttribute("linkHref", url, writer.createRangeIn(paragraph));
+ }
+ });
+ await flushFetch();
+
+ // Undo (linkHref url -> null): handler sees an undo batch with a non-string new
+ // value, so nothing is recorded. Redo (null -> url): the undo batch carries a
+ // string linkHref, so the handler records the URL as dismissed.
+ editor.execute("undo");
+ editor.execute("redo");
+ await flushFetch();
+
+ // Now a BARE link with the same URL must be skipped because it was dismissed.
+ addLinkedText(editor, url);
+ await flushFetch();
+
+ expect(fetchLinkMetadata).not.toHaveBeenCalled();
+ expect(findElement(editor, "linkMention")).toBeUndefined();
+ });
+
+ it("ignores attribute modifications where the old linkHref value was not null", async () => {
+ const url = "https://example.com/changed";
+ editor.setData(`<p><a href="https://old.example.com/">${url}</a></p>`);
+
+ // Change the existing href: old value is non-null, so the handler skips it.
+ editor.model.change((writer) => {
+ const paragraph = editor.model.document.getRoot()?.getChild(0);
+ if (paragraph?.is("element")) {
+ writer.setAttribute("linkHref", url, writer.createRangeIn(paragraph));
+ }
+ });
+
+ await flushFetch();
+
+ expect(findElement(editor, "linkMention")).toBeUndefined();
+ expect(fetchLinkMetadata).not.toHaveBeenCalled();
+ });
+
+ // The following tests exercise the defensive re-resolution guards in
+ // _replaceWithPreview: the model can change between when the fetch starts and
+ // when it resolves, so the path/text are re-resolved and bail out gracefully.
+
+ it("bails out when the parent block was removed before the fetch resolved", async () => {
+ const { resolveFetch } = useDeferredFetch(fetchLinkMetadata);
+ const url = "https://example.com/gone";
+
+ // The URL lives in the SECOND paragraph (stored parent path [1]).
+ setModelData(editor.model, `<paragraph>first</paragraph><paragraph>${url}[]</paragraph>`);
+ editor.model.change((writer) => {
+ const paragraph = editor.model.document.getRoot()?.getChild(1);
+ if (paragraph?.is("element")) {
+ writer.setAttribute("linkHref", url, writer.createRangeIn(paragraph));
+ }
+ });
+ await flushFetch();
+
+ // Remove the second paragraph: the stored path [1] now resolves to undefined.
+ editor.model.change((writer) => {
+ const paragraph = editor.model.document.getRoot()?.getChild(1);
+ if (paragraph) {
+ writer.remove(paragraph);
+ }
+ });
+
+ resolveFetch({ ...META, url });
+ await flushFetch();
+
+ expect(findElement(editor, "linkMention")).toBeUndefined();
+ });
+
+ it("bails out when an intermediate path segment no longer resolves", async () => {
+ const { resolveFetch } = useDeferredFetch(fetchLinkMetadata);
+ const url = "https://example.com/nested";
+
+ // Nest the URL two block-quotes deep so the stored parent path has depth 3
+ // ([outerQuote, innerQuote, paragraph]).
+ editor.setData(`<blockquote><blockquote><p>${url}</p></blockquote></blockquote>`);
+ editor.model.change((writer) => {
+ const outer = editor.model.document.getRoot()?.getChild(0);
+ const inner = outer?.is("element") ? outer.getChild(0) : undefined;
+ const paragraph = inner?.is("element") ? inner.getChild(0) : undefined;
+ if (paragraph?.is("element")) {
+ writer.setAttribute("linkHref", url, writer.createRangeIn(paragraph));
+ }
+ });
+ await flushFetch();
+
+ // Remove the inner block-quote: both quotes collapse, leaving an auto-paragraph
+ // at root[0]. Re-resolving the stored path [0,0,0] yields undefined at the second
+ // segment, so the third iteration sees a falsy parentEl and bails.
+ editor.model.change((writer) => {
+ const outer = editor.model.document.getRoot()?.getChild(0);
+ const inner = outer?.is("element") ? outer.getChild(0) : undefined;
+ if (inner?.is("element")) {
+ writer.remove(inner);
+ }
+ });
+
+ resolveFetch({ ...META, url });
+ await flushFetch();
+
+ expect(findElement(editor, "linkMention")).toBeUndefined();
+ });
+
+ it("skips non-matching text and bails when the URL text lost its linkHref", async () => {
+ const { resolveFetch } = useDeferredFetch(fetchLinkMetadata);
+ const url = "https://example.com/edited";
+
+ // Paragraph holds a non-matching text node followed by the URL text. Only the
+ // URL text gets the linkHref, so the handler starts the deferred conversion.
+ setModelData(editor.model, "<paragraph>[]</paragraph>");
+ editor.model.change((writer) => {
+ const paragraph = editor.model.document.getRoot()?.getChild(0);
+ if (!paragraph?.is("element")) {
+ throw new Error("Expected a paragraph block.");
+ }
+ writer.insertText("other ", paragraph, 0);
+ writer.insertText(url, paragraph, "end");
+ });
+ editor.model.change((writer) => {
+ const paragraph = editor.model.document.getRoot()?.getChild(0);
+ if (paragraph?.is("element")) {
+ const start = writer.createPositionAt(paragraph, 6); // after "other "
+ const end = writer.createPositionAt(paragraph, "end");
+ writer.setAttribute("linkHref", url, writer.createRange(start, end));
+ }
+ });
+ await flushFetch();
+
+ // Before the fetch resolves, point the URL text's linkHref at a different URL.
+ // The inner walker now sees the non-matching "other " text (data != url) and
+ // then the URL text whose linkHref no longer matches, so neither converts.
+ // Keeping a distinct linkHref (rather than removing it) prevents the two text
+ // nodes from merging, so both walker branches are exercised.
+ editor.model.change((writer) => {
+ const paragraph = editor.model.document.getRoot()?.getChild(0);
+ if (paragraph?.is("element")) {
+ const start = writer.createPositionAt(paragraph, 6); // after "other "
+ const end = writer.createPositionAt(paragraph, "end");
+ writer.setAttribute("linkHref", "https://other.example.com/", writer.createRange(start, end));
+ }
+ });
+
+ resolveFetch({ ...META, url });
+ await flushFetch();
+
+ expect(findElement(editor, "linkMention")).toBeUndefined();
+ });
+});
diff --git a/packages/ckeditor5/src/plugins/link_embed/link_embed_autodetect.ts b/packages/ckeditor5/src/plugins/link_embed/link_embed_autodetect.ts
new file mode 100644
index 0000000000..aede20ff74
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/link_embed/link_embed_autodetect.ts
@@ -0,0 +1,210 @@
+import { chooseLinkPreviewKind, isUrlAloneInBlock, type BlockChildLike } from '@triliumnext/commons';
+import { Plugin } from 'ckeditor5';
+import { EMBEDDABLE_URL_REGEX } from './link_embed_commands.js';
+
+/**
+ * Auto-converts typed/pasted URLs to link preview widgets.
+ *
+ * Piggybacks on CKEditor's AutoLink plugin: when AutoLink sets `linkHref` on text whose content
+ * matches the href (i.e. a raw URL, not "[label](url)"), we fetch metadata and replace it with a
+ * preview widget.
+ *
+ * The shape follows the gesture (see chooseLinkPreviewKind):
+ * - a URL left alone on its own line — sole content of a plain paragraph, then Enter — becomes a
+ * block preview: a player if the URL is embeddable (YouTube), a card otherwise;
+ * - anything else — text either side of it, a list/table/quote/heading, or a caret still in the
+ * block because the user is mid-sentence — becomes an inline linkMention.
+ *
+ * The user can Ctrl+Z to revert back to a plain link.
+ */
+export default class AutoLinkToMention extends Plugin {
+ /** Guard against re-entrant changes triggered by our own model writes. */
+ private _converting = false;
+ /** URLs that were undone — don't re-convert these. */
+ private _dismissed = new Set<string>();
+
+ init() {
+ const editor = this.editor;
+
+ editor.model.document.on('change:data', (_evt, batch) => {
+ if (this._converting) return;
+ if (!this._autoDetectEnabled()) return;
+
+ // When the user undoes our conversion, the undo batch re-inserts
+ // the original linked text. Record its URL so we don't re-convert.
+ if (batch.isUndo) {
+ for (const change of editor.model.document.differ.getChanges()) {
+ if (change.type !== 'attribute' || change.attributeKey !== 'linkHref') continue;
+ if (typeof change.attributeNewValue === 'string') {
+ this._dismissed.add(change.attributeNewValue);
+ }
+ }
+ return;
+ }
+
+ // Detect AutoLink setting `linkHref` on existing text (paste + Space).
+ // AutoLink calls writer.setAttribute('linkHref', url, range) which
+ // shows up as an attribute change, not a text insertion.
+ for (const change of editor.model.document.differ.getChanges()) {
+ if (change.type !== 'attribute' || change.attributeKey !== 'linkHref') continue;
+ // Only react to newly added links (null → url), not modifications.
+ if (change.attributeOldValue !== null) continue;
+
+ const href = change.attributeNewValue as string;
+ if (!EMBEDDABLE_URL_REGEX.test(href)) continue;
+ if (this._dismissed.has(href)) continue;
+
+ // Walk the affected range to verify the text IS the URL
+ // (raw pasted URL, not a labeled link like "click here").
+ for (const item of change.range.getWalker()) {
+ if (!item.item.is('$textProxy')) continue;
+ if (item.item.data.trim() !== href) continue;
+
+ const parent = item.item.parent;
+ /* v8 ignore next -- a $textProxy always has an element parent, so this guard never fires */
+ if (!parent?.is('element')) continue;
+
+ this._replaceWithPreview(href, parent.getPath());
+ return;
+ }
+ }
+ });
+ }
+
+ /**
+ * Whether auto-detection is on (Options → Text Notes → Features). Consulted on every detected
+ * URL rather than once at startup, so the host can supply a getter and have the option apply to
+ * already-open editors. A plain boolean is honoured too, and an absent config means enabled.
+ *
+ * Only auto-detection is gated: inserting a preview from the toolbar dialog goes through
+ * InsertLinkEmbedCommand and stays available either way.
+ */
+ private _autoDetectEnabled(): boolean {
+ const setting = this.editor.config.get('autoLinkPreviewsEnabled') as boolean | (() => boolean) | undefined;
+ return (typeof setting === 'function' ? setting() : setting) !== false;
+ }
+
+ private _replaceWithPreview(url: string, parentPath: number[]) {
+ const editor = this.editor;
+ const editorEl = editor.editing.view.getDomRoot();
+ const component = glob.getComponentByEl<EditorComponent>(editorEl);
+
+ component.fetchLinkMetadata(url).then((metadata: LinkEmbedMetadata) => {
+ // The page told us nothing (bot challenge, network error, no title of its own): leave the
+ // plain link AutoLink already created. A preview built from a hostname placeholder would
+ // show strictly less than the URL it replaced.
+ if (metadata.unresolved) {
+ // The URL is left out on purpose — a browser console gets screenshotted and pasted
+ // into bug reports too, and the link is right there in the note anyway.
+ console.warn('Link preview dropped: no metadata could be read from the page (the link was kept as a plain link).');
+ return;
+ }
+
+ // Restored in the `finally`: were a model change ever to throw, a flag left raised would
+ // silently switch auto-detection off for the rest of the session.
+ this._converting = true;
+
+ try {
+ editor.model.change((writer) => {
+ const root = editor.model.document.getRoot();
+ /* v8 ignore next -- the document always has a root once the editor is created */
+ if (!root) return;
+
+ // Re-resolve the parent from the stored path.
+ let parentEl: any = root;
+ for (const idx of parentPath) {
+ if (!parentEl || typeof parentEl.getChild !== 'function') return;
+ parentEl = parentEl.getChild(idx);
+ }
+ if (!parentEl || !parentEl.is('element')) return;
+
+ // Find the text node that still contains the URL.
+ const range = writer.createRangeIn(parentEl);
+ for (const item of range.getWalker()) {
+ if (!item.item.is('$textProxy')) continue;
+ if (item.item.data.trim() !== url) continue;
+ if (item.item.getAttribute('linkHref') !== url) continue;
+
+ // Where the URL sits decides its shape. Evaluated here — at insertion time, not
+ // when the URL was detected — because the metadata fetch is async and the user
+ // may have kept typing meanwhile. Also before deleting anything, since deletion
+ // would empty the block and make it look like the URL was never alone.
+ const kind = chooseLinkPreviewKind(metadata.embedType, {
+ urlAloneInBlock: isUrlAloneInBlock(this._blockChildren(parentEl), url),
+ blockIsStandalone: this._isStandaloneBlock(parentEl),
+ caretLeftBlock: this._caretLeftBlock(parentEl)
+ });
+
+ const attributes = {
+ url: metadata.url,
+ embedType: metadata.embedType,
+ title: metadata.title,
+ description: metadata.description,
+ favicon: metadata.favicon,
+ siteName: metadata.siteName,
+ image: metadata.image
+ };
+
+ if (kind === 'mention') {
+ const urlRange = writer.createRangeOn(item.item);
+ writer.setSelection(urlRange);
+ editor.model.deleteContent(editor.model.document.selection);
+ editor.model.insertContent(writer.createElement('linkMention', attributes));
+ return;
+ }
+
+ // A card or an embed takes over the whole paragraph, which by now holds nothing
+ // but the URL. Swapped with writer.insert/remove rather than insertContent: the
+ // caret has moved on to the next line (that is what made this a block preview in
+ // the first place) and may already be mid-word, so it must not be dragged back.
+ // 'card' vs 'embed' needs no branch here — the renderer keys off embedType,
+ // which is "opengraph" for a card and the provider's own type for an embed.
+ writer.insert(writer.createElement('linkEmbed', attributes), parentEl, 'before');
+ writer.remove(parentEl);
+ return;
+ }
+ });
+ } finally {
+ this._converting = false;
+ }
+ });
+ }
+
+ /**
+ * True for a plain top-level paragraph — the only block a card or an embed may take over.
+ * A list item is a paragraph carrying list attributes; a table cell, a quote and every other
+ * container nest their paragraphs below the root; a heading is not a paragraph at all. In each
+ * of those the URL keeps its inline mention, since a block preview there reads as an accident.
+ */
+ private _isStandaloneBlock(blockEl: any): boolean {
+ if (blockEl.name !== 'paragraph') return false;
+ if (blockEl.hasAttribute('listItemId')) return false;
+
+ return blockEl.parent === this.editor.model.document.getRoot();
+ }
+
+ /**
+ * True when the caret is no longer in the block — which is exactly what pressing Enter after the
+ * URL does. While it is still there the user may yet type on that line, so the URL has not been
+ * *left* alone and stays an inline mention.
+ */
+ private _caretLeftBlock(blockEl: any): boolean {
+ const position = this.editor.model.document.selection.getFirstPosition();
+
+ /* v8 ignore next -- the document selection always has a position */
+ return position?.parent !== blockEl;
+ }
+
+ /**
+ * Maps a model block's children to the runtime-neutral shape consumed by
+ * {@link isUrlAloneInBlock}, keeping the decision logic pure and testable.
+ */
+ private _blockChildren(blockEl: any): BlockChildLike[] {
+ const children: BlockChildLike[] = [];
+ for (const child of blockEl.getChildren()) {
+ const isText = child.is('$text');
+ children.push({ isText, data: isText ? child.data : undefined });
+ }
+ return children;
+ }
+}
diff --git a/packages/ckeditor5/src/plugins/link_embed/link_embed_commands.spec.ts b/packages/ckeditor5/src/plugins/link_embed/link_embed_commands.spec.ts
new file mode 100644
index 0000000000..cf2adec88d
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/link_embed/link_embed_commands.spec.ts
@@ -0,0 +1,336 @@
+import { _setModelData as setModelData, type ClassicEditor } from "ckeditor5";
+import { beforeEach, describe, expect, it } from "vitest";
+
+import {
+ changeCommand,
+ createTestEditor,
+ findElement,
+ installLinkEmbedComponentMock,
+ LINK_EMBED_TEST_PLUGINS,
+ META,
+ type LinkEmbedComponentMocks
+} from "../../../test/link-embed-kit.js";
+import { CHANGE_LINK_DISPLAY_COMMAND, LINK_EMBED_COMMAND, REMOVE_LINK_EMBED_COMMAND } from "./link_embed_commands.js";
+
+describe("LinkEmbed commands", () => {
+ let editor: ClassicEditor;
+ let fetchLinkMetadata: LinkEmbedComponentMocks["fetchLinkMetadata"];
+
+ beforeEach(async () => {
+ ({ fetchLinkMetadata } = installLinkEmbedComponentMock());
+ editor = await createTestEditor(LINK_EMBED_TEST_PLUGINS);
+ });
+
+ // -----------------------------------------------------------------------
+ // InsertLinkEmbedCommand
+ // -----------------------------------------------------------------------
+
+ it("inserts a preview for a URL, storing all the metadata whatever the mode", async () => {
+ const url = "https://example.com/article";
+ setModelData(editor.model, "<paragraph>[]</paragraph>");
+
+ // An inline mention keeps the description and image it does not itself show, so switching it
+ // to a card later never has to go back to the network.
+ await editor.execute(LINK_EMBED_COMMAND, { url, mode: "inline" });
+
+ expect(fetchLinkMetadata).toHaveBeenCalledWith(url);
+ const mention = findElement(editor, "linkMention");
+ expect(mention?.getAttribute("url")).toBe(url);
+ expect(mention?.getAttribute("description")).toBe(META.description);
+ expect(mention?.getAttribute("image")).toBe(META.image);
+ expect(mention?.getAttribute("siteName")).toBe(META.siteName);
+ });
+
+ it("forces the opengraph type for a card, and keeps the detected one for an embed", async () => {
+ const url = "https://youtube.com/watch?v=abc12345678";
+ fetchLinkMetadata.mockResolvedValue({ ...META, url, embedType: "youtube" });
+
+ setModelData(editor.model, "<paragraph>[]</paragraph>");
+ await editor.execute(LINK_EMBED_COMMAND, { url, mode: "card" });
+ // A card is an embed that declines to play.
+ expect(findElement(editor, "linkEmbed")?.getAttribute("embedType")).toBe("opengraph");
+
+ setModelData(editor.model, "<paragraph>[]</paragraph>");
+ await editor.execute(LINK_EMBED_COMMAND, { url, mode: "embed" });
+ expect(findElement(editor, "linkEmbed")?.getAttribute("embedType")).toBe("youtube");
+ });
+
+ it("inserts an ordinary link for the 'plain' mode, without fetching any metadata", async () => {
+ const url = "https://example.com/article";
+ setModelData(editor.model, "<paragraph>[]</paragraph>");
+
+ await editor.execute(LINK_EMBED_COMMAND, { url, mode: "plain" });
+
+ expect(fetchLinkMetadata).not.toHaveBeenCalled();
+ expect(findElement(editor, "linkMention")).toBeUndefined();
+ expect(findElement(editor, "linkEmbed")).toBeUndefined();
+ expect(editor.getData()).toBe(`<p><a href="${url}">${url}</a></p>`);
+ });
+
+ it("is enabled in a paragraph and disabled when read-only", () => {
+ setModelData(editor.model, "<paragraph>foo[]bar</paragraph>");
+ const command = editor.commands.get(LINK_EMBED_COMMAND);
+ expect(command?.isEnabled).toBe(true);
+
+ editor.enableReadOnlyMode("test");
+ expect(command?.isEnabled).toBe(false);
+ editor.disableReadOnlyMode("test");
+ });
+
+ // -----------------------------------------------------------------------
+ // ChangeLinkDisplayCommand
+ // -----------------------------------------------------------------------
+
+ it("is disabled with no link widget selected and reports a null value", () => {
+ setModelData(editor.model, "<paragraph>foo[]bar</paragraph>");
+ const command = changeCommand(editor);
+ expect(command.isEnabled).toBe(false);
+ expect(command.value).toBeNull();
+ expect(command.embedAvailable).toBe(false);
+ });
+
+ it("reports 'inline' for a selected linkMention and exposes embed availability", () => {
+ setModelData(
+ editor.model,
+ '<paragraph>[<linkMention url="https://youtube.com/watch" embedType="web"></linkMention>]</paragraph>'
+ );
+
+ const command = changeCommand(editor);
+ expect(command.isEnabled).toBe(true);
+ expect(command.value).toBe("inline");
+ // detectEmbedType returns "youtube" (not "opengraph") => embeddable.
+ expect(command.embedAvailable).toBe(true);
+ });
+
+ it("exposes an http(s) URL but withholds a hostile one, so the toolbar cannot arm it", () => {
+ setModelData(editor.model, '[<linkEmbed url="https://e.com/page" embedType="opengraph"></linkEmbed>]');
+ expect(changeCommand(editor).url).toBe("https://e.com/page");
+
+ // `url` comes from the stored data-url, which the sanitizers keep verbatim. Withholding it
+ // leaves the "open link in new tab" and copy buttons disabled rather than armed.
+ setModelData(editor.model, '[<linkEmbed url="javascript:alert(document.cookie)" embedType="opengraph"></linkEmbed>]');
+ expect(changeCommand(editor).url).toBeNull();
+ });
+
+ it("reports 'card' for an opengraph linkEmbed and 'embed' otherwise", () => {
+ setModelData(editor.model, '[<linkEmbed url="https://e.com/" embedType="opengraph"></linkEmbed>]');
+ expect(changeCommand(editor).value).toBe("card");
+
+ setModelData(editor.model, '[<linkEmbed url="https://e.com/" embedType="web"></linkEmbed>]');
+ expect(changeCommand(editor).value).toBe("embed");
+ });
+
+ it("converts a linkMention to an embed via the command, picking the detected type", () => {
+ setModelData(
+ editor.model,
+ '<paragraph>[<linkMention url="https://youtube.com/watch" embedType="web" title="T"></linkMention>]</paragraph>'
+ );
+
+ editor.execute(CHANGE_LINK_DISPLAY_COMMAND, { value: "embed" });
+
+ const embed = findElement(editor, "linkEmbed");
+ expect(embed).toBeDefined();
+ expect(embed?.getAttribute("embedType")).toBe("youtube");
+ expect(embed?.getAttribute("url")).toBe("https://youtube.com/watch");
+ expect(embed?.getAttribute("title")).toBe("T");
+ });
+
+ it("converts a linkMention to a card, forcing the opengraph embed type", () => {
+ setModelData(
+ editor.model,
+ '<paragraph>[<linkMention url="https://youtube.com/watch" embedType="web"></linkMention>]</paragraph>'
+ );
+
+ editor.execute(CHANGE_LINK_DISPLAY_COMMAND, { value: "card" });
+
+ const embed = findElement(editor, "linkEmbed");
+ expect(embed?.getAttribute("embedType")).toBe("opengraph");
+ });
+
+ it("converts a linkEmbed back to an inline linkMention", () => {
+ setModelData(editor.model, '[<linkEmbed url="https://e.com/" embedType="opengraph" title="T"></linkEmbed>]');
+
+ editor.execute(CHANGE_LINK_DISPLAY_COMMAND, { value: "inline" });
+
+ const mention = findElement(editor, "linkMention");
+ expect(mention).toBeDefined();
+ expect(mention?.getAttribute("url")).toBe("https://e.com/");
+ expect(mention?.getAttribute("title")).toBe("T");
+ });
+
+ it("converts a link widget to a plain, ordinary link — and never re-converts it", async () => {
+ setModelData(editor.model, '<paragraph>[<linkMention url="https://e.com/" title="T"></linkMention>]</paragraph>');
+
+ editor.execute(CHANGE_LINK_DISPLAY_COMMAND, { value: "plain" });
+
+ expect(findElement(editor, "linkMention")).toBeUndefined();
+ expect(editor.getData()).toBe('<p><a href="https://e.com/">https://e.com/</a></p>');
+
+ // The linked text arrives as an insertion, not a linkHref attribute change, so
+ // AutoLinkToMention must not have kicked in and fetched the preview straight back.
+ await Promise.resolve();
+ expect(fetchLinkMetadata).not.toHaveBeenCalled();
+
+ // A block preview converts the same way, gaining a wrapping paragraph.
+ setModelData(editor.model, '[<linkEmbed url="https://e.com/" embedType="opengraph"></linkEmbed>]');
+ editor.execute(CHANGE_LINK_DISPLAY_COMMAND, { value: "plain" });
+ expect(editor.getData()).toBe('<p><a href="https://e.com/">https://e.com/</a></p>');
+ });
+
+ it("degrades a non-http(s) URL to bare text when converting to a plain link", () => {
+ // A data-url the sanitizers pass through verbatim must not become a live href
+ // (same rule as the toolbar's open-link button; see isHttpUrl).
+ setModelData(editor.model, '[<linkEmbed url="javascript:alert(1)" embedType="opengraph"></linkEmbed>]');
+
+ editor.execute(CHANGE_LINK_DISPLAY_COMMAND, { value: "plain" });
+
+ expect(editor.getData()).toBe("<p>javascript:alert(1)</p>");
+ });
+
+ it("does nothing when the target mode equals the current mode", () => {
+ setModelData(editor.model, '[<linkEmbed url="https://e.com/" embedType="opengraph"></linkEmbed>]');
+ const before = editor.getData();
+
+ editor.execute(CHANGE_LINK_DISPLAY_COMMAND, { value: "card" }); // current mode is already "card"
+
+ expect(findElement(editor, "linkMention")).toBeUndefined();
+ expect(editor.getData()).toBe(before);
+ });
+
+ // -----------------------------------------------------------------------
+ // RemoveLinkEmbedCommand (the toolbar's unlink button)
+ // -----------------------------------------------------------------------
+
+ it("unlinks a selected linkMention, leaving the bare URL as plain text", () => {
+ setModelData(editor.model, '<paragraph>[<linkMention url="https://e.com/" title="T"></linkMention>]</paragraph>');
+
+ editor.execute(REMOVE_LINK_EMBED_COMMAND);
+
+ expect(findElement(editor, "linkMention")).toBeUndefined();
+ // Mirrors the default link's unlink: the URL survives as plain, non-linked text.
+ expect(editor.getData()).toBe("<p>https://e.com/</p>");
+ });
+
+ it("unlinks a selected block linkEmbed the same way", () => {
+ setModelData(editor.model, '[<linkEmbed url="https://e.com/" embedType="youtube"></linkEmbed>]');
+
+ editor.execute(REMOVE_LINK_EMBED_COMMAND);
+
+ expect(findElement(editor, "linkEmbed")).toBeUndefined();
+ expect(editor.getData()).toBe("<p>https://e.com/</p>");
+ });
+
+ it("is disabled with no link widget selected, and does nothing if executed anyway", () => {
+ setModelData(editor.model, "<paragraph>foo[]bar</paragraph>");
+ const before = editor.getData();
+
+ const command = editor.commands.get(REMOVE_LINK_EMBED_COMMAND);
+ expect(command?.isEnabled).toBe(false);
+
+ // Command swallows execute() while disabled, so force it enabled to exercise the early return.
+ if (command) {
+ command.isEnabled = true;
+ }
+ command?.execute();
+
+ expect(editor.getData()).toBe(before);
+ });
+
+ // -----------------------------------------------------------------------
+ // ChangeLinkDisplayCommand on a native link (the link balloon's Display dropdown)
+ // -----------------------------------------------------------------------
+
+ it("offers itself on a native http(s) link, reporting 'plain' as the current mode", () => {
+ const command = changeCommand(editor);
+
+ setModelData(editor.model, "<paragraph>foo[]bar</paragraph>");
+ expect(command.isEnabled).toBe(false);
+ expect(command.value).toBeNull();
+
+ setModelData(editor.model, '<paragraph><$text linkHref="https://youtube.com/watch">https://youtube.[]com/watch</$text></paragraph>');
+ expect(command.isEnabled).toBe(true);
+ expect(command.value).toBe("plain");
+ expect(command.embedAvailable).toBe(true);
+ expect(command.url).toBe("https://youtube.com/watch");
+
+ // An internal reference link has no page to preview.
+ setModelData(editor.model, '<paragraph><$text linkHref="#root/someNoteId">some[]note</$text></paragraph>');
+ expect(command.isEnabled).toBe(false);
+ expect(command.value).toBeNull();
+ });
+
+ it("converts a labeled native link into an inline mention, keeping the surrounding text", async () => {
+ const url = "https://example.com/article";
+ setModelData(editor.model, `<paragraph>see <$text linkHref="${url}">the []article</$text> here</paragraph>`);
+
+ await editor.execute(CHANGE_LINK_DISPLAY_COMMAND, { value: "inline" });
+
+ expect(fetchLinkMetadata).toHaveBeenCalledWith(url);
+ const mention = findElement(editor, "linkMention");
+ expect(mention?.getAttribute("url")).toBe(url);
+ expect(mention?.getAttribute("title")).toBe(META.title);
+ // The label is replaced by the pill; the text around the link survives (spaces adjacent to
+ // an inline object serialize as &nbsp;), and the new widget is left selected so its toolbar
+ // — this same dropdown included — takes over from the link balloon.
+ expect(editor.getData()).toContain("<p>see&nbsp;<span");
+ expect(editor.getData()).toContain("</span>&nbsp;here</p>");
+ expect(editor.model.document.selection.getSelectedElement()).toBe(mention);
+ });
+
+ it("converts a native link to the chosen block shape: card forces opengraph, embed keeps the detected type", async () => {
+ const url = "https://youtube.com/watch?v=abc12345678";
+ fetchLinkMetadata.mockImplementation(async () => ({ ...META, url, embedType: "youtube" }));
+
+ setModelData(editor.model, `<paragraph><$text linkHref="${url}">watch [] this</$text></paragraph>`);
+ await editor.execute(CHANGE_LINK_DISPLAY_COMMAND, { value: "card" });
+ expect(findElement(editor, "linkEmbed")?.getAttribute("embedType")).toBe("opengraph");
+
+ setModelData(editor.model, `<paragraph><$text linkHref="${url}">watch [] this</$text></paragraph>`);
+ await editor.execute(CHANGE_LINK_DISPLAY_COMMAND, { value: "embed" });
+ const embed = findElement(editor, "linkEmbed");
+ expect(embed?.getAttribute("embedType")).toBe("youtube");
+ expect(editor.model.document.selection.getSelectedElement()).toBe(embed);
+ });
+
+ it("does nothing for 'plain' on a native link — it already is one", async () => {
+ setModelData(editor.model, '<paragraph><$text linkHref="https://e.com/">https://e.[]com/</$text></paragraph>');
+ const before = editor.getData();
+
+ await editor.execute(CHANGE_LINK_DISPLAY_COMMAND, { value: "plain" });
+
+ expect(fetchLinkMetadata).not.toHaveBeenCalled();
+ expect(editor.getData()).toBe(before);
+ });
+
+ it("does nothing when the linked text was deleted while the metadata was being fetched", async () => {
+ const url = "https://example.com/";
+ let resolveFetch: (meta: unknown) => void = () => {};
+ fetchLinkMetadata.mockReturnValue(new Promise((resolve) => { resolveFetch = resolve; }));
+ setModelData(editor.model, `<paragraph><$text linkHref="${url}">https://exa[]mple.com/</$text></paragraph>`);
+
+ const executed = editor.execute(CHANGE_LINK_DISPLAY_COMMAND, { value: "inline" }) as unknown as Promise<void>;
+ setModelData(editor.model, "<paragraph>replaced[]</paragraph>");
+ resolveFetch({ ...META, url });
+ await executed;
+
+ expect(findElement(editor, "linkMention")).toBeUndefined();
+ expect(findElement(editor, "linkEmbed")).toBeUndefined();
+ expect(editor.getData()).toBe("<p>replaced</p>");
+ });
+
+ it("does nothing when executed without a selected link widget or a native link", () => {
+ setModelData(editor.model, "<paragraph>foo[]bar</paragraph>");
+ const before = editor.getData();
+
+ // The command is disabled with no widget selected, and CKEditor's Command
+ // swallows execute() while disabled. Force it enabled so the override body
+ // runs and we exercise the early return for "no selected link widget".
+ const command = editor.commands.get(CHANGE_LINK_DISPLAY_COMMAND);
+ if (command) {
+ command.isEnabled = true;
+ }
+ command?.execute({ value: "embed" });
+
+ expect(editor.getData()).toBe(before);
+ });
+});
diff --git a/packages/ckeditor5/src/plugins/link_embed/link_embed_commands.ts b/packages/ckeditor5/src/plugins/link_embed/link_embed_commands.ts
new file mode 100644
index 0000000000..11154c32b6
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/link_embed/link_embed_commands.ts
@@ -0,0 +1,277 @@
+import { isHttpUrl } from '@triliumnext/commons';
+import { Command, findAttributeRange, ModelLiveRange } from 'ckeditor5';
+
+export const LINK_EMBED_COMMAND = 'insertLinkEmbed';
+export const CHANGE_LINK_DISPLAY_COMMAND = 'changeLinkDisplay';
+export const REMOVE_LINK_EMBED_COMMAND = 'removeLinkEmbed';
+
+export const LINK_DISPLAY_MODES = [
+ { value: 'inline', label: 'Inline', labelKey: 'link_embed.mode_inline' },
+ { value: 'card', label: 'Card', labelKey: 'link_embed.mode_card' },
+ { value: 'embed', label: 'Embed', labelKey: 'link_embed.mode_embed' },
+ // The way out of the preview system: an ordinary <a> link, no widget. Offered in the same
+ // dropdowns as the real modes so "back to a normal URL" is found where the user looks for it.
+ { value: 'plain', label: 'Plain link', labelKey: 'link_embed.mode_plain' }
+] as const;
+
+export type LinkDisplayMode = typeof LINK_DISPLAY_MODES[number]['value'];
+
+/**
+ * What a URL must look like before any conversion — automatic or command-driven — considers turning
+ * it into a preview: http(s) and free of whitespace. Everything else (an internal `#root/…` note
+ * reference, a mailto:, a mid-edit fragment) has no page behind it to preview.
+ */
+export const EMBEDDABLE_URL_REGEX = /^https?:\/\/\S+$/;
+
+/** Every piece of fetched metadata a linkEmbed/linkMention element stores as a model attribute. */
+export const META_KEYS = ['url', 'embedType', 'title', 'description', 'favicon', 'siteName', 'image'] as const;
+
+export type MetaKey = (typeof META_KEYS)[number];
+
+/**
+ * Inserts a preview for a URL: fetches its metadata through the host, then puts the widget in.
+ *
+ * All the metadata is written onto the element whichever shape is chosen — an inline mention stores
+ * the description and image it does not itself show — so that switching modes later, via the widget
+ * toolbar's Display dropdown, never has to go back to the network.
+ */
+export class InsertLinkEmbedCommand extends Command {
+ override async execute({ url, mode }: { url: string; mode: LinkDisplayMode }) {
+ const editor = this.editor;
+
+ // A plain link is not a preview at all, so no metadata is fetched: the URL becomes an
+ // ordinary link, exactly as the editor's own link balloon would have inserted it.
+ if (mode === 'plain') {
+ editor.model.change((writer) => {
+ editor.model.insertContent(writer.createText(url, { linkHref: url }));
+ });
+ return;
+ }
+
+ const editorEl = editor.editing.view.getDomRoot();
+ const component = glob.getComponentByEl<EditorComponent>(editorEl);
+
+ const metadata = await component.fetchLinkMetadata(url);
+
+ editor.model.change((writer) => {
+ editor.model.insertContent(writer.createElement(mode === 'inline' ? 'linkMention' : 'linkEmbed', {
+ url: metadata.url,
+ // A card is an embed that declines to play: forcing "opengraph" is what tells the
+ // renderer to draw the static card rather than the provider's player.
+ embedType: mode === 'card' ? 'opengraph' : metadata.embedType,
+ title: metadata.title,
+ description: metadata.description,
+ favicon: metadata.favicon,
+ siteName: metadata.siteName,
+ image: metadata.image
+ }));
+ });
+ }
+
+ override refresh() {
+ const model = this.editor.model;
+ const selection = model.document.selection;
+ const firstPosition = selection.getFirstPosition();
+ const allowedIn = firstPosition && model.schema.findAllowedParent(firstPosition, 'linkEmbed');
+ this.isEnabled = allowedIn !== null;
+ }
+}
+
+export class ChangeLinkDisplayCommand extends Command {
+ declare value: LinkDisplayMode | null;
+ /** Whether the selected link supports embed mode (e.g. YouTube). */
+ declare embedAvailable: boolean;
+ /** URL of the selected link widget, exposed for the toolbar's open-link button. */
+ declare url: string | null;
+
+ constructor(editor: any) {
+ super(editor);
+ // Register as observables so CKEditor's bind().to() works.
+ this.set('embedAvailable', false);
+ this.set('url', null);
+ }
+
+ override async execute(options: { value: LinkDisplayMode }) {
+ const model = this.editor.model;
+ const selected = getSelectedLinkWidget(this.editor);
+
+ // No widget selected means the dropdown sits in the link balloon, over a native link.
+ if (!selected) {
+ await this._convertNativeLink(options.value);
+ return;
+ }
+
+ const targetMode = options.value;
+ const currentMode = this._getMode(selected);
+ if (targetMode === currentMode) return;
+
+ // Collect all metadata from the current element.
+ const attrs: Record<string, unknown> = {};
+ for (const key of META_KEYS) {
+ const val = selected.getAttribute(key);
+ if (val != null) attrs[key] = val;
+ }
+
+ const url = attrs.url as string;
+
+ // "Plain link" leaves the preview system: the widget becomes an ordinary link whose text is
+ // the URL. Inserted as new content (not an attribute change), so AutoLinkToMention does not
+ // see it and immediately convert it back. A URL we would never link to (see the isHttpUrl
+ // note in refresh()) degrades to bare text instead, as the unlink button does.
+ if (targetMode === 'plain') {
+ model.change(writer => {
+ const text = isHttpUrl(url) ? writer.createText(url, { linkHref: url }) : writer.createText(url);
+ model.insertContent(text, writer.createRangeOn(selected));
+ });
+ return;
+ }
+
+ // Detect the actual embed type from the URL via the client service.
+ const detectedType = this._detectEmbedType(url);
+
+ model.change(writer => {
+ if (targetMode === 'inline') {
+ const mention = writer.createElement('linkMention', attrs);
+ model.insertContent(mention, writer.createRangeOn(selected));
+ } else {
+ // 'card' forces opengraph; 'embed' uses detected type.
+ attrs.embedType = targetMode === 'card' ? 'opengraph' : detectedType;
+ const embed = writer.createElement('linkEmbed', attrs);
+ model.insertContent(embed, writer.createRangeOn(selected));
+ }
+ });
+ }
+
+ override refresh() {
+ const selected = getSelectedLinkWidget(this.editor);
+
+ if (selected) {
+ this.isEnabled = true;
+ this.value = this._getMode(selected);
+ const url = selected.getAttribute('url') as string;
+ this.embedAvailable = this._detectEmbedType(url) !== 'opengraph';
+ // Only ever hand out an http(s) URL. `url` comes from the stored `data-url`, which the
+ // HTML sanitizers pass through unexamined, so a note carrying `data-url="javascript:…"`
+ // would otherwise reach the toolbar's "open link" button as a live href. Withholding it
+ // here disables that button (and the copy one) instead of arming them.
+ this.url = isHttpUrl(url) ? url : null;
+ return;
+ }
+
+ // A native link under the caret: the same dropdown, hosted in the link balloon this time,
+ // offers to convert it into a preview. Its current display mode is by definition "plain".
+ const href = this.editor.model.document.selection.getAttribute('linkHref');
+ if (typeof href === 'string' && EMBEDDABLE_URL_REGEX.test(href)) {
+ this.isEnabled = true;
+ this.value = 'plain';
+ this.embedAvailable = this._detectEmbedType(href) !== 'opengraph';
+ this.url = href;
+ return;
+ }
+
+ this.isEnabled = false;
+ this.value = null;
+ this.embedAvailable = false;
+ this.url = null;
+ }
+
+ /**
+ * Converts the native link under the caret — the one whose balloon toolbar hosts the dropdown —
+ * into the chosen preview shape: the deliberate inverse of "Plain link". Unlike auto-detection
+ * there is no gesture to interpret and no unresolved-page veto: the mode was picked outright,
+ * so the conversion always happens (Ctrl+Z brings the link back), and a labeled link's display
+ * text is replaced by the preview.
+ */
+ private async _convertNativeLink(targetMode: LinkDisplayMode) {
+ const editor = this.editor;
+ const model = editor.model;
+ const position = model.document.selection.getFirstPosition();
+ const href = model.document.selection.getAttribute('linkHref');
+ /* v8 ignore next -- refresh() disables the command unless the selection carries a linkHref */
+ if (typeof href !== 'string' || !position) return;
+ // The link already is one.
+ if (targetMode === 'plain') return;
+
+ const editorEl = editor.editing.view.getDomRoot();
+ const component = glob.getComponentByEl<EditorComponent>(editorEl);
+
+ // The linked text is tracked as a live range: the metadata fetch reads the page server-side
+ // and can take seconds, and edits made meanwhile must not shift what gets replaced.
+ const liveRange = ModelLiveRange.fromRange(findAttributeRange(position, 'linkHref', href, model));
+ const metadata = await component.fetchLinkMetadata(href);
+ const range = liveRange.toRange();
+ liveRange.detach();
+
+ model.change(writer => {
+ // The link may have been edited away while the fetch was in flight.
+ let linkStillThere = false;
+ for (const { item } of range.getWalker()) {
+ if (item.is('$textProxy') && item.getAttribute('linkHref') === href) {
+ linkStillThere = true;
+ break;
+ }
+ }
+ if (!linkStillThere) return;
+
+ const element = writer.createElement(targetMode === 'inline' ? 'linkMention' : 'linkEmbed', {
+ url: metadata.url,
+ // Same rule as the widget path above: a card is an embed that declines to play.
+ embedType: targetMode === 'card' ? 'opengraph'
+ : targetMode === 'embed' ? this._detectEmbedType(href)
+ : metadata.embedType,
+ title: metadata.title,
+ description: metadata.description,
+ favicon: metadata.favicon,
+ siteName: metadata.siteName,
+ image: metadata.image
+ });
+
+ model.insertContent(element, range);
+ // Leave the new widget selected, so its toolbar — this same dropdown included — takes
+ // over from the link balloon.
+ writer.setSelection(element, 'on');
+ });
+ }
+
+ private _getMode(element: any): LinkDisplayMode {
+ if (element.name === 'linkMention') return 'inline';
+ const embedType = element.getAttribute('embedType') as string;
+ return embedType === 'opengraph' ? 'card' : 'embed';
+ }
+
+ /** Delegates to the client service to avoid duplicating URL detection logic. */
+ private _detectEmbedType(url: string): string {
+ const editorEl = this.editor.editing.view.getDomRoot();
+ const component = glob.getComponentByEl<EditorComponent>(editorEl);
+ return component.detectEmbedType(url);
+ }
+}
+
+export class RemoveLinkEmbedCommand extends Command {
+ override execute() {
+ const model = this.editor.model;
+ const selected = getSelectedLinkWidget(this.editor);
+ if (!selected) return;
+
+ const url = selected.getAttribute('url') as string;
+
+ // Mirror the default link's unlink: drop the link entirely, leaving the
+ // bare URL as plain (non-linked) text.
+ model.change(writer => {
+ model.insertContent(writer.createText(url), writer.createRangeOn(selected));
+ });
+ }
+
+ override refresh() {
+ this.isEnabled = !!getSelectedLinkWidget(this.editor);
+ }
+}
+
+/** Returns the currently selected linkEmbed/linkMention element, or null. */
+function getSelectedLinkWidget(editor: any) {
+ const selected = editor.model.document.selection.getSelectedElement();
+ if (selected && (selected.name === 'linkMention' || selected.name === 'linkEmbed')) {
+ return selected;
+ }
+ return null;
+}
diff --git a/packages/ckeditor5/src/plugins/link_embed/link_embed_editing.spec.ts b/packages/ckeditor5/src/plugins/link_embed/link_embed_editing.spec.ts
new file mode 100644
index 0000000000..9bc5edbb4e
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/link_embed/link_embed_editing.spec.ts
@@ -0,0 +1,251 @@
+import { _getViewData as getViewData, _setModelData as setModelData, type ClassicEditor, type ViewElement } from "ckeditor5";
+import { beforeEach, describe, expect, it } from "vitest";
+
+import { createTestEditor, installLinkEmbedComponentMock, LINK_EMBED_TEST_PLUGINS, type LinkEmbedComponentMocks } from "../../../test/link-embed-kit.js";
+
+describe("LinkEmbedEditing", () => {
+ let editor: ClassicEditor;
+ let renderLinkEmbed: LinkEmbedComponentMocks["renderLinkEmbed"];
+ let renderLinkMention: LinkEmbedComponentMocks["renderLinkMention"];
+
+ beforeEach(async () => {
+ ({ renderLinkEmbed, renderLinkMention } = installLinkEmbedComponentMock());
+ editor = await createTestEditor(LINK_EMBED_TEST_PLUGINS);
+ });
+
+ // -----------------------------------------------------------------------
+ // Schema + converters (block linkEmbed)
+ // -----------------------------------------------------------------------
+
+ it("registers linkEmbed (block) and linkMention (inline) in the schema", () => {
+ const schema = editor.model.schema;
+ expect(schema.isRegistered("linkEmbed")).toBe(true);
+ expect(schema.isObject("linkEmbed")).toBe(true);
+ expect(schema.isRegistered("linkMention")).toBe(true);
+ expect(schema.isInline("linkMention")).toBe(true);
+ expect(schema.isObject("linkMention")).toBe(true);
+ });
+
+ it("upcasts a <section.link-embed> with all data attributes into a linkEmbed", () => {
+ editor.setData(
+ '<section class="link-embed" data-url="https://e.com/" data-embed-type="web"' +
+ ' data-title="T" data-description="D" data-favicon="F" data-site-name="S" data-image="I"></section>'
+ );
+
+ const root = editor.model.document.getRoot();
+ const embed = root?.getChild(0);
+ expect(embed?.is("element")).toBe(true);
+ if (embed?.is("element")) {
+ expect(embed.name).toBe("linkEmbed");
+ expect(embed.getAttribute("url")).toBe("https://e.com/");
+ expect(embed.getAttribute("embedType")).toBe("web");
+ expect(embed.getAttribute("title")).toBe("T");
+ expect(embed.getAttribute("siteName")).toBe("S");
+ expect(embed.getAttribute("image")).toBe("I");
+ }
+
+ // The editing downcast UIElement callback ran and rendered the embed.
+ expect(renderLinkEmbed).toHaveBeenCalled();
+ const [, metadata, editable] = renderLinkEmbed.mock.calls[0];
+ expect(metadata.url).toBe("https://e.com/");
+ expect(editable).toBe(true);
+ });
+
+ it("data-downcasts a fully-populated linkEmbed, omitting empty optional attributes", () => {
+ setModelData(
+ editor.model,
+ '<linkEmbed url="https://e.com/" embedType="web" title="T" description="D"' +
+ ' favicon="F" siteName="S" image="I"></linkEmbed>'
+ );
+
+ const data = editor.getData();
+ expect(data).toContain('class="link-embed"');
+ expect(data).toContain('data-url="https://e.com/"');
+ expect(data).toContain('data-embed-type="web"');
+ expect(data).toContain('data-title="T"');
+ expect(data).toContain('data-site-name="S"');
+ expect(data).toContain('data-image="I"');
+ });
+
+ it("data-downcasts a minimal linkEmbed without the optional attributes", () => {
+ setModelData(editor.model, '<linkEmbed url="https://e.com/" embedType="web"></linkEmbed>');
+
+ const data = editor.getData();
+ expect(data).toContain('data-url="https://e.com/"');
+ expect(data).not.toContain("data-title");
+ expect(data).not.toContain("data-site-name");
+ expect(data).not.toContain("data-image");
+ });
+
+ it("editing-downcasts a linkEmbed to a widget and renders it via the component", () => {
+ setModelData(
+ editor.model,
+ '<linkEmbed url="https://e.com/" embedType="web" title="T" description="D"' +
+ ' favicon="F" siteName="S" image="I"></linkEmbed>'
+ );
+
+ const view = getViewData(editor.editing.view);
+ expect(view).toContain("link-embed");
+ expect(view).toContain("ck-widget");
+ // The block preview carries CKEditor's own drag handle (as tables do), so the whole widget
+ // moves as one instead of the user tearing its image and text apart.
+ expect(view).toContain("ck-widget_with-selection-handle");
+
+ // The editing wrapper must carry the full metadata, not just the URL: a copy that starts
+ // inside the rendered preview bypasses CKEditor's clipboard pipeline and serializes the
+ // editing DOM, and upcast rebuilds the widget purely from these attributes.
+ expect(view).toContain('data-title="T"');
+ expect(view).toContain('data-description="D"');
+ expect(view).toContain('data-favicon="F"');
+ expect(view).toContain('data-site-name="S"');
+ expect(view).toContain('data-image="I"');
+
+ expect(renderLinkEmbed).toHaveBeenCalled();
+ const [container, metadata, editable] = renderLinkEmbed.mock.calls[0];
+ expect(container).toBeInstanceOf(HTMLElement);
+ expect(metadata).toMatchObject({ url: "https://e.com/", embedType: "web", title: "T" });
+ expect(editable).toBe(true);
+ });
+
+ // -----------------------------------------------------------------------
+ // Schema + converters (inline linkMention)
+ // -----------------------------------------------------------------------
+
+ it("upcasts a <span.link-mention> into a linkMention", () => {
+ editor.setData(
+ '<p><span class="link-mention" data-url="https://e.com/" data-embed-type="web"' +
+ ' data-title="T" data-description="D" data-favicon="F" data-site-name="S" data-image="I">x</span></p>'
+ );
+
+ const paragraph = editor.model.document.getRoot()?.getChild(0);
+ const mention = paragraph?.is("element") ? paragraph.getChild(0) : undefined;
+ expect(mention?.is("element")).toBe(true);
+ if (mention?.is("element")) {
+ expect(mention.name).toBe("linkMention");
+ expect(mention.getAttribute("url")).toBe("https://e.com/");
+ expect(mention.getAttribute("favicon")).toBe("F");
+ }
+
+ expect(renderLinkMention).toHaveBeenCalled();
+ });
+
+ it("data-downcasts a fully-populated linkMention, omitting empty optional attributes", () => {
+ setModelData(
+ editor.model,
+ '<paragraph><linkMention url="https://e.com/" embedType="web" title="T" description="D"' +
+ ' favicon="F" siteName="S" image="I"></linkMention></paragraph>'
+ );
+
+ const data = editor.getData();
+ expect(data).toContain('class="link-mention"');
+ expect(data).toContain('data-url="https://e.com/"');
+ expect(data).toContain('data-embed-type="web"');
+ expect(data).toContain('data-title="T"');
+ expect(data).toContain('data-site-name="S"');
+ expect(data).toContain('data-image="I"');
+ });
+
+ it("data-downcasts a minimal linkMention without the optional attributes", () => {
+ setModelData(editor.model, '<paragraph><linkMention url="https://e.com/"></linkMention></paragraph>');
+
+ const data = editor.getData();
+ expect(data).toContain('data-url="https://e.com/"');
+ expect(data).not.toContain("data-embed-type");
+ expect(data).not.toContain("data-title");
+ expect(data).not.toContain("data-site-name");
+ });
+
+ it("upcasts link previews carrying the Markdown-export fallback anchor, dropping the anchor", () => {
+ // The Markdown exporter injects an <a> child into the otherwise empty elements so the
+ // export stays readable outside Trilium; on reimport the anchor must vanish into the
+ // widget instead of leaking as stray text.
+ editor.setData(
+ '<section class="link-embed" data-url="https://e.com/" data-embed-type="opengraph" data-title="T">' +
+ '<a href="https://e.com/">T</a></section>' +
+ '<p>See <span class="link-mention" data-url="https://e.com/" data-title="T">' +
+ '<a href="https://e.com/">T</a></span> for details.</p>'
+ );
+
+ const root = editor.model.document.getRoot();
+ expect(root?.childCount).toBe(2);
+
+ const embed = root?.getChild(0);
+ expect(embed?.is("element", "linkEmbed")).toBe(true);
+ if (embed?.is("element")) {
+ expect(embed.getAttribute("url")).toBe("https://e.com/");
+ expect(embed.childCount).toBe(0);
+ }
+
+ const paragraph = root?.getChild(1);
+ const mention = paragraph?.is("element") ? paragraph.getChild(1) : undefined;
+ expect(mention?.is("element", "linkMention")).toBe(true);
+
+ // Saving again produces the canonical childless elements — the anchor does not survive,
+ // let alone accumulate.
+ const data = editor.getData();
+ expect(data).not.toContain("<a");
+ expect(data).toContain('data-url="https://e.com/"');
+ });
+
+ it("editing-downcasts a linkMention to an inline widget and renders it via the component", () => {
+ setModelData(
+ editor.model,
+ '<paragraph><linkMention url="https://e.com/" embedType="web" title="T" description="D"' +
+ ' favicon="F" siteName="S" image="I"></linkMention></paragraph>'
+ );
+
+ const view = getViewData(editor.editing.view);
+ expect(view).toContain("link-mention");
+
+ // Same rationale as for the block embed: a native browser copy of the editing DOM (a copy
+ // starting inside the rendered preview) must round-trip the metadata through upcast, so the
+ // wrapper carries all of it — this is what used to drop the favicon/title of a pasted mention.
+ expect(view).toContain('data-embed-type="web"');
+ expect(view).toContain('data-title="T"');
+ expect(view).toContain('data-description="D"');
+ expect(view).toContain('data-favicon="F"');
+ expect(view).toContain('data-site-name="S"');
+ expect(view).toContain('data-image="I"');
+
+ expect(renderLinkMention).toHaveBeenCalled();
+ const [container, metadata, editable] = renderLinkMention.mock.calls[0];
+ expect(container).toBeInstanceOf(HTMLElement);
+ expect(metadata).toMatchObject({ url: "https://e.com/", title: "T", favicon: "F" });
+ expect(editable).toBe(true);
+ });
+
+ it("maps a view position inside the rendered linkMention to a model position OUTSIDE the object", () => {
+ // linkMention is an empty inline object whose editing view holds a UIElement child. Without
+ // the viewToModelPositionOutsideModelElement mapper registered in LinkEmbedEditing, a view
+ // position inside the rendered widget resolves to a degenerate model position *inside* the
+ // atomic object; the mapper must instead resolve it just after the mention.
+ setModelData(
+ editor.model,
+ '<paragraph>foo<linkMention url="https://e.com/" title="T"></linkMention>bar</paragraph>'
+ );
+
+ const root = editor.editing.view.document.getRoot();
+ let mentionView: ViewElement | undefined;
+ if (root) {
+ for (const { item } of editor.editing.view.createRangeIn(root)) {
+ if (item.is("element") && item.hasClass("link-mention")) {
+ mentionView = item;
+ break;
+ }
+ }
+ }
+ expect(mentionView).toBeDefined();
+ if (!mentionView) {
+ return;
+ }
+
+ const viewPosition = editor.editing.view.createPositionAt(mentionView, "end");
+ const modelPosition = editor.editing.mapper.toModelPosition(viewPosition);
+
+ // Must land just after the mention (paragraph offset 4 = "foo"(3) + linkMention(1)),
+ // not inside the atomic linkMention element.
+ expect(modelPosition.parent.is("element", "linkMention")).toBe(false);
+ expect(modelPosition.parent.is("element", "paragraph")).toBe(true);
+ expect(modelPosition.offset).toBe(4);
+ });
+});
diff --git a/packages/ckeditor5/src/plugins/link_embed/link_embed_editing.ts b/packages/ckeditor5/src/plugins/link_embed/link_embed_editing.ts
new file mode 100644
index 0000000000..b9ceebdb8f
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/link_embed/link_embed_editing.ts
@@ -0,0 +1,217 @@
+import { Plugin, toWidget, viewToModelPositionOutsideModelElement, Widget } from 'ckeditor5';
+import { preventCKEditorHandling } from '../widget_utils.js';
+import {
+ CHANGE_LINK_DISPLAY_COMMAND,
+ ChangeLinkDisplayCommand,
+ InsertLinkEmbedCommand,
+ LINK_EMBED_COMMAND,
+ META_KEYS,
+ REMOVE_LINK_EMBED_COMMAND,
+ RemoveLinkEmbedCommand,
+ type MetaKey
+} from './link_embed_commands.js';
+
+/**
+ * Schema, converters and command registration for linkEmbed (block) and linkMention (inline).
+ */
+export default class LinkEmbedEditing extends Plugin {
+ static get requires() {
+ return [Widget];
+ }
+
+ init() {
+ this._defineSchema();
+ this._defineConverters();
+
+ // linkMention is an empty inline object whose editing view holds a UIElement child, so a
+ // view position inside the rendered widget would otherwise resolve to a degenerate model
+ // position *inside* the atomic element. Map it just outside the mention instead (mirrors
+ // ReferenceLink). The block linkEmbed is a $block object and needs no such mapping.
+ this.editor.editing.mapper.on(
+ 'viewToModelPosition',
+ viewToModelPositionOutsideModelElement(this.editor.model, viewElement => viewElement.hasClass('link-mention'))
+ );
+
+ this.editor.commands.add(LINK_EMBED_COMMAND, new InsertLinkEmbedCommand(this.editor));
+ this.editor.commands.add(CHANGE_LINK_DISPLAY_COMMAND, new ChangeLinkDisplayCommand(this.editor));
+ this.editor.commands.add(REMOVE_LINK_EMBED_COMMAND, new RemoveLinkEmbedCommand(this.editor));
+ }
+
+ _defineSchema() {
+ const schema = this.editor.model.schema;
+
+ schema.register('linkEmbed', {
+ isObject: true,
+ allowAttributes: ['url', 'embedType', 'title', 'description', 'favicon', 'siteName', 'image'],
+ allowWhere: '$block'
+ });
+
+ schema.register('linkMention', {
+ isInline: true,
+ isObject: true,
+ // Stores all metadata so we can switch to card/embed without re-fetching.
+ allowAttributes: ['url', 'embedType', 'title', 'description', 'favicon', 'siteName', 'image'],
+ allowWhere: '$text'
+ });
+ }
+
+ _defineConverters() {
+ const editor = this.editor;
+ const conversion = editor.conversion;
+
+ // ===== linkEmbed (block) =====
+
+ conversion.for('upcast').elementToElement({
+ model: (viewElement, { writer }) => {
+ return writer.createElement('linkEmbed', {
+ url: viewElement.getAttribute('data-url'),
+ embedType: viewElement.getAttribute('data-embed-type'),
+ title: viewElement.getAttribute('data-title'),
+ description: viewElement.getAttribute('data-description'),
+ favicon: viewElement.getAttribute('data-favicon'),
+ siteName: viewElement.getAttribute('data-site-name'),
+ image: viewElement.getAttribute('data-image')
+ });
+ },
+ view: { name: 'section', classes: 'link-embed' }
+ });
+
+ conversion.for('dataDowncast').elementToElement({
+ model: 'linkEmbed',
+ view: (modelElement, { writer }) => {
+ return writer.createContainerElement(
+ 'section',
+ metadataViewAttributes(modelElement, 'link-embed', ['url', 'embedType'])
+ );
+ }
+ });
+
+ conversion.for('editingDowncast').elementToElement({
+ model: 'linkEmbed',
+ view: (modelElement, { writer }) => {
+ const url = modelElement.getAttribute('url') as string;
+ const embedType = modelElement.getAttribute('embedType') as string;
+ const title = modelElement.getAttribute('title') as string | undefined;
+ const description = modelElement.getAttribute('description') as string | undefined;
+ const favicon = modelElement.getAttribute('favicon') as string | undefined;
+ const siteName = modelElement.getAttribute('siteName') as string | undefined;
+ const image = modelElement.getAttribute('image') as string | undefined;
+
+ const section = writer.createContainerElement(
+ 'section',
+ metadataViewAttributes(modelElement, 'link-embed', ['url', 'embedType'])
+ );
+
+ const preview = writer.createUIElement('div', {
+ class: 'link-embed-preview-wrapper',
+ 'data-cke-ignore-events': 'true'
+ }, function (domDocument) {
+ const domElement = this.toDomElement(domDocument);
+ const editorEl = editor.editing.view.getDomRoot();
+ const component = glob.getComponentByEl<EditorComponent>(editorEl);
+ component.renderLinkEmbed(domElement, { url, embedType, title, description, favicon, siteName, image }, true);
+ preventCKEditorHandling(domElement, editor);
+ return domElement;
+ });
+
+ writer.insert(writer.createPositionAt(section, 0), preview);
+ // hasSelectionHandle gives the block preview (both card and video) CKEditor's own
+ // widget drag handle — the same one tables use. Without a handle the user grabs the
+ // preview's own content and the browser's native drag tears the image and text apart;
+ // the handle moves the whole widget atomically instead.
+ return toWidget(section, writer, { label: 'link embed widget', hasSelectionHandle: true });
+ }
+ });
+
+ // ===== linkMention (inline) =====
+
+ conversion.for('upcast').elementToElement({
+ model: (viewElement, { writer }) => {
+ return writer.createElement('linkMention', {
+ url: viewElement.getAttribute('data-url'),
+ embedType: viewElement.getAttribute('data-embed-type'),
+ title: viewElement.getAttribute('data-title'),
+ description: viewElement.getAttribute('data-description'),
+ favicon: viewElement.getAttribute('data-favicon'),
+ siteName: viewElement.getAttribute('data-site-name'),
+ image: viewElement.getAttribute('data-image')
+ });
+ },
+ view: { name: 'span', classes: 'link-mention' }
+ });
+
+ conversion.for('dataDowncast').elementToElement({
+ model: 'linkMention',
+ view: (modelElement, { writer }) => {
+ return writer.createContainerElement(
+ 'span',
+ metadataViewAttributes(modelElement, 'link-mention', ['url'])
+ );
+ }
+ });
+
+ conversion.for('editingDowncast').elementToElement({
+ model: 'linkMention',
+ view: (modelElement, { writer }) => {
+ const url = modelElement.getAttribute('url') as string;
+ const title = modelElement.getAttribute('title') as string | undefined;
+ const favicon = modelElement.getAttribute('favicon') as string | undefined;
+
+ const span = writer.createContainerElement(
+ 'span',
+ metadataViewAttributes(modelElement, 'link-mention', ['url'])
+ );
+
+ const inner = writer.createUIElement('span', {
+ class: 'link-mention-inner',
+ 'data-cke-ignore-events': 'true'
+ }, function (domDocument) {
+ const domElement = this.toDomElement(domDocument);
+ const editorEl = editor.editing.view.getDomRoot();
+ const component = glob.getComponentByEl<EditorComponent>(editorEl);
+ component.renderLinkMention(domElement, { url, title, favicon }, true);
+ preventCKEditorHandling(domElement, editor);
+ return domElement;
+ });
+
+ writer.insert(writer.createPositionAt(span, 0), inner);
+ return toWidget(span, writer, { label: 'link mention widget', hasSelectionHandle: false });
+ }
+ });
+ }
+}
+
+const DATA_ATTR_NAMES: Record<MetaKey, string> = {
+ url: 'data-url',
+ embedType: 'data-embed-type',
+ title: 'data-title',
+ description: 'data-description',
+ favicon: 'data-favicon',
+ siteName: 'data-site-name',
+ image: 'data-image'
+};
+
+/**
+ * Builds the widget wrapper's class + `data-*` attributes from a linkEmbed/linkMention element.
+ *
+ * Shared by the data AND the editing downcast on purpose: a copy gesture that starts inside the
+ * rendered preview (a `data-cke-ignore-events` subtree, which CKEditor's clipboard pipeline
+ * deliberately ignores) is handled natively by the browser and puts the *editing* markup on the
+ * clipboard. Since upcast rebuilds the widget purely from the wrapper's `data-*` attributes, any
+ * metadata missing from the editing wrapper would be silently lost on paste — historically the
+ * favicon and title of a copied mention.
+ */
+function metadataViewAttributes(
+ modelElement: { getAttribute(key: string): unknown },
+ className: string,
+ requiredKeys: readonly MetaKey[]
+): Record<string, string> {
+ const attrs: Record<string, string> = { class: className };
+ for (const key of META_KEYS) {
+ const val = modelElement.getAttribute(key) as string | undefined;
+ if (val || requiredKeys.includes(key)) {
+ attrs[DATA_ATTR_NAMES[key]] = val as string;
+ }
+ }
+ return attrs;
+}
diff --git a/packages/ckeditor5/src/plugins/link_embed_form.spec.ts b/packages/ckeditor5/src/plugins/link_embed/link_embed_form.spec.ts
similarity index 98%
rename from packages/ckeditor5/src/plugins/link_embed_form.spec.ts
rename to packages/ckeditor5/src/plugins/link_embed/link_embed_form.spec.ts
index 8a21b65c40..7969e02ba0 100644
--- a/packages/ckeditor5/src/plugins/link_embed_form.spec.ts
+++ b/packages/ckeditor5/src/plugins/link_embed/link_embed_form.spec.ts
@@ -1,10 +1,10 @@
import { BlockQuote, ClassicEditor, ContextualBalloon, Essentials, Link, Paragraph, Undo, _setModelData as setModelData } 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 { createTestEditor } from "../../../test/editor-kit.js";
+import { installGlobMock } from "../../../test/globals-test-kit.js";
+import LinkEmbed, { LINK_EMBED_COMMAND } from "./link_embed.js";
import LinkEmbedFormView from "./link_embed_form.js";
-import LinkEmbed, { LINK_EMBED_COMMAND } from "./linkembed.js";
const META = {
url: "https://example.com/",
diff --git a/packages/ckeditor5/src/plugins/link_embed_form.ts b/packages/ckeditor5/src/plugins/link_embed/link_embed_form.ts
similarity index 99%
rename from packages/ckeditor5/src/plugins/link_embed_form.ts
rename to packages/ckeditor5/src/plugins/link_embed/link_embed_form.ts
index be9ed3bb3b..35c8424c1a 100644
--- a/packages/ckeditor5/src/plugins/link_embed_form.ts
+++ b/packages/ckeditor5/src/plugins/link_embed/link_embed_form.ts
@@ -20,7 +20,7 @@ import {
ViewModel
} from "ckeditor5";
-import { LINK_DISPLAY_MODES, type LinkDisplayMode } from "./linkembed.js";
+import { LINK_DISPLAY_MODES, type LinkDisplayMode } from "./link_embed_commands.js";
/** Resolves a translation key, falling back to the given English text. See `translate.ts`. */
type Translate = (key: string, fallback: string) => string;
diff --git a/packages/ckeditor5/src/plugins/link_embed_toolbar.spec.ts b/packages/ckeditor5/src/plugins/link_embed/link_embed_toolbar.spec.ts
similarity index 99%
rename from packages/ckeditor5/src/plugins/link_embed_toolbar.spec.ts
rename to packages/ckeditor5/src/plugins/link_embed/link_embed_toolbar.spec.ts
index f89cff9a03..7663225899 100644
--- a/packages/ckeditor5/src/plugins/link_embed_toolbar.spec.ts
+++ b/packages/ckeditor5/src/plugins/link_embed/link_embed_toolbar.spec.ts
@@ -1,10 +1,10 @@
import { ClassicEditor, Essentials, Link, Paragraph, WidgetToolbarRepository, _setModelData as setModelData } 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 { createTestEditor } from "../../../test/editor-kit.js";
+import { installGlobMock } from "../../../test/globals-test-kit.js";
+import LinkEmbed, { CHANGE_LINK_DISPLAY_COMMAND, LINK_DISPLAY_MODES } from "./link_embed.js";
import LinkEmbedToolbar from "./link_embed_toolbar.js";
-import LinkEmbed, { CHANGE_LINK_DISPLAY_COMMAND, LINK_DISPLAY_MODES } from "./linkembed.js";
// ---------------------------------------------------------------------------
// Helpers
diff --git a/packages/ckeditor5/src/plugins/link_embed_toolbar.ts b/packages/ckeditor5/src/plugins/link_embed/link_embed_toolbar.ts
similarity index 98%
rename from packages/ckeditor5/src/plugins/link_embed_toolbar.ts
rename to packages/ckeditor5/src/plugins/link_embed/link_embed_toolbar.ts
index bb1067cf43..d2a837743c 100644
--- a/packages/ckeditor5/src/plugins/link_embed_toolbar.ts
+++ b/packages/ckeditor5/src/plugins/link_embed/link_embed_toolbar.ts
@@ -19,9 +19,9 @@ import LinkEmbed, {
LINK_DISPLAY_MODES,
REMOVE_LINK_EMBED_COMMAND,
type LinkDisplayMode
-} from "./linkembed.js";
-import { createCopyUrlButton } from "./copy_link_url.js";
-import { translate } from "./translate.js";
+} from "./link_embed.js";
+import { createCopyUrlButton } from "../copy_link_url.js";
+import { translate } from "../translate.js";
export default class LinkEmbedToolbar extends Plugin {
diff --git a/packages/ckeditor5/src/plugins/link_embed/link_embed_ui.spec.ts b/packages/ckeditor5/src/plugins/link_embed/link_embed_ui.spec.ts
new file mode 100644
index 0000000000..accd89e88e
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/link_embed/link_embed_ui.spec.ts
@@ -0,0 +1,33 @@
+import { ContextualBalloon, type ClassicEditor, _setModelData as setModelData } from "ckeditor5";
+import { beforeEach, describe, expect, it } from "vitest";
+
+import { createTestEditor, installLinkEmbedComponentMock, LINK_EMBED_TEST_PLUGINS } from "../../../test/link-embed-kit.js";
+import { LINK_EMBED_COMMAND } from "./link_embed_commands.js";
+import LinkEmbedFormView from "./link_embed_form.js";
+
+describe("LinkEmbedUI", () => {
+ let editor: ClassicEditor;
+
+ beforeEach(async () => {
+ installLinkEmbedComponentMock();
+ editor = await createTestEditor(LINK_EMBED_TEST_PLUGINS);
+ });
+
+ it("binds the button to the insert command and opens the balloon form on click", () => {
+ setModelData(editor.model, "<paragraph>foo[]bar</paragraph>");
+
+ const view = editor.ui.componentFactory.create("linkEmbed") as unknown as {
+ isEnabled: boolean;
+ fire(name: string): void;
+ };
+ const command = editor.commands.get(LINK_EMBED_COMMAND);
+ expect(view.isEnabled).toBe(command?.isEnabled);
+
+ const balloon = editor.plugins.get(ContextualBalloon);
+ expect(balloon.visibleView).toBeNull();
+
+ // The insert flow now happens in the editor's own balloon, not in a Trilium modal.
+ view.fire("execute");
+ expect(balloon.visibleView).toBeInstanceOf(LinkEmbedFormView);
+ });
+});
diff --git a/packages/ckeditor5/src/plugins/link_embed/link_embed_ui.ts b/packages/ckeditor5/src/plugins/link_embed/link_embed_ui.ts
new file mode 100644
index 0000000000..774dc52673
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/link_embed/link_embed_ui.ts
@@ -0,0 +1,172 @@
+import { isHttpUrl } from '@triliumnext/commons';
+import { ButtonView, clickOutsideHandler, ContextualBalloon, Plugin, type Editor, type Observable } from 'ckeditor5';
+import linkPreviewIcon from '../../icons/link-preview.svg?raw';
+import { translate } from '../translate.js';
+import { LINK_EMBED_COMMAND } from './link_embed_commands.js';
+import LinkEmbedFormView from './link_embed_form.js';
+
+/**
+ * The "Link preview" toolbar button and the balloon form it opens.
+ *
+ * The form lives inside the editor — the same balloon the native link button uses — rather than in a
+ * Trilium modal, so inserting a preview never leaves the editing surface and needs no round trip
+ * out to the app and back.
+ */
+export default class LinkEmbedUI extends Plugin {
+
+ static get requires() {
+ return [ContextualBalloon];
+ }
+
+ private _formView: LinkEmbedFormView | null = null;
+
+ init() {
+ const editor = this.editor;
+
+ editor.ui.componentFactory.add('linkEmbed', locale => {
+ const command = editor.commands.get(LINK_EMBED_COMMAND);
+ const buttonView = new ButtonView(locale);
+
+ buttonView.set({
+ label: editor.t('Link preview'),
+ icon: linkPreviewIcon,
+ tooltip: true
+ });
+
+ /* v8 ignore next -- LinkEmbedEditing always registers LINK_EMBED_COMMAND (both are required by LinkEmbed), so the no-command branch is unreachable */
+ if (command) {
+ buttonView.bind('isEnabled').to(command as Observable & { isEnabled: boolean }, 'isEnabled');
+ }
+
+ this.listenTo(buttonView, 'execute', () => this._showForm());
+ return buttonView;
+ });
+ }
+
+ override destroy() {
+ super.destroy();
+ this._formView?.destroy();
+ }
+
+ private _showForm() {
+ const editor = this.editor;
+ const balloon = editor.plugins.get(ContextualBalloon);
+ const form = this._getFormView();
+
+ if (balloon.hasView(form)) return;
+
+ form.reset();
+ balloon.add({
+ view: form,
+ position: {
+ target: () => {
+ const view = editor.editing.view;
+ const range = view.document.selection.getFirstRange();
+ /* v8 ignore next -- the editing view's selection always has a range while the editor is focused */
+ if (!range) return editor.ui.getEditableElement() as HTMLElement;
+ return view.domConverter.viewRangeToDom(range);
+ }
+ }
+ });
+ form.focus();
+ }
+
+ private _hideForm() {
+ const balloon = this.editor.plugins.get(ContextualBalloon);
+ const form = this._formView;
+
+ /* v8 ignore next -- the form is only ever hidden from its own handlers, so by then it exists and is shown */
+ if (!form || !balloon.hasView(form)) return;
+
+ balloon.remove(form);
+ this.editor.editing.view.focus();
+ }
+
+ private _getFormView(): LinkEmbedFormView {
+ if (this._formView) return this._formView;
+
+ const editor = this.editor;
+ const form = new LinkEmbedFormView(editor.locale, (key, fallback) => translate(editor, key, fallback));
+ this._formView = form;
+
+ // The mode selector only offers "Embed" for a URL that has a player behind it — the same
+ // question the widget toolbar's dropdown asks of an existing preview.
+ form.on('change:url', () => {
+ const embedAvailable = detectEmbedTypeFor(editor, form.url) !== 'opengraph';
+ form.embedAvailable = embedAvailable;
+
+ // Follow the URL until the user overrules it: a video wants its player, anything else a card.
+ if (!this._modePickedByUser) {
+ form.mode = embedAvailable ? 'embed' : 'card';
+ } else if (!embedAvailable && form.mode === 'embed') {
+ form.mode = 'card';
+ }
+ });
+
+ form.modeDropdownView.on('execute', () => {
+ this._modePickedByUser = true;
+ });
+
+ form.on('submit', () => {
+ void this._insert(form);
+ });
+
+ // Esc and clicking away dismiss the form, exactly as they do for the native link balloon.
+ form.keystrokes.set('Esc', (_data, cancel) => {
+ this._hideForm();
+ cancel();
+ });
+ clickOutsideHandler({
+ emitter: form,
+ activator: () => this.editor.plugins.get(ContextualBalloon).hasView(form),
+ contextElements: () => [this.editor.plugins.get(ContextualBalloon).view.element as HTMLElement],
+ callback: () => this._hideForm()
+ });
+
+ return form;
+ }
+
+ private _modePickedByUser = false;
+
+ private async _insert(form: LinkEmbedFormView) {
+ // The Insert button is disabled mid-fetch, but Enter fires `submit` on the form itself, so
+ // the guard has to live here or a second Enter would fetch and insert twice.
+ if (form.isFetching) return;
+
+ const url = normalizeUrl(form.url);
+ if (!url) return;
+
+ // The metadata fetch takes a moment (the server reads the page and downloads the image), so
+ // the form stays open and disabled meanwhile rather than vanishing into an apparent no-op.
+ form.isFetching = true;
+ try {
+ await this.editor.execute(LINK_EMBED_COMMAND, { url, mode: form.mode });
+ } finally {
+ form.isFetching = false;
+ }
+
+ this._modePickedByUser = false;
+ this._hideForm();
+ }
+}
+
+/**
+ * Makes a typed URL absolute, defaulting the scheme the way the editor's own link field does.
+ * Returns null when what was typed cannot be a link preview at all.
+ */
+function normalizeUrl(rawUrl: string): string | null {
+ const trimmed = rawUrl.trim();
+ if (!trimmed) return null;
+
+ const withScheme = /^[a-z][a-z0-9+.-]*:/i.test(trimmed) ? trimmed : `https://${trimmed}`;
+ return isHttpUrl(withScheme) ? withScheme : null;
+}
+
+/** Asks the host what kind of preview a URL supports. */
+function detectEmbedTypeFor(editor: Editor, url: string): string {
+ if (!url.trim()) return 'opengraph';
+
+ const editorEl = editor.editing.view.getDomRoot();
+ const component = glob.getComponentByEl<EditorComponent>(editorEl);
+ return component.detectEmbedType(normalizeUrl(url) ?? url);
+}
diff --git a/packages/ckeditor5/src/plugins/linkembed.spec.ts b/packages/ckeditor5/src/plugins/linkembed.spec.ts
deleted file mode 100644
index abd3135c5e..0000000000
--- a/packages/ckeditor5/src/plugins/linkembed.spec.ts
+++ /dev/null
@@ -1,1155 +0,0 @@
-import type { LinkEmbedMetadata } from "@triliumnext/commons";
-import {
- _getViewData as getViewData,
- _setModelData as setModelData,
- BlockQuote,
- ClassicEditor,
- ContextualBalloon,
- Essentials,
- Heading,
- Link,
- List,
- Paragraph,
- Undo,
- type ViewElement
-} 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 LinkEmbedFormView from "./link_embed_form.js";
-import LinkEmbed, { CHANGE_LINK_DISPLAY_COMMAND, LINK_EMBED_COMMAND, REMOVE_LINK_EMBED_COMMAND } from "./linkembed.js";
-
-const META = {
- url: "https://example.com/",
- // The host only ever reports "youtube" or "opengraph". It matters here that this is the real
- // thing: chooseLinkPreviewKind() treats anything other than "opengraph" as embeddable, so a made-up
- // type would send a URL standing alone in its block down the block-embed path instead of the mention one.
- embedType: "opengraph",
- title: "Example title",
- description: "Some description",
- favicon: "https://example.com/favicon.ico",
- siteName: "Example",
- image: "https://example.com/image.png"
-} satisfies LinkEmbedMetadata;
-
-describe("LinkEmbed", () => {
- let editor: ClassicEditor;
- let triggerCommand: ReturnType<typeof vi.fn>;
- let renderLinkEmbed: ReturnType<typeof vi.fn>;
- let renderLinkMention: ReturnType<typeof vi.fn>;
- let fetchLinkMetadata: ReturnType<typeof vi.fn>;
- let detectEmbedType: ReturnType<typeof vi.fn>;
-
- beforeEach(async () => {
- triggerCommand = vi.fn();
- renderLinkEmbed = vi.fn();
- renderLinkMention = vi.fn();
- fetchLinkMetadata = vi.fn(async (url: string) => ({ ...META, url }));
- // YouTube-like URLs => "youtube" (embeddable); everything else => "opengraph".
- detectEmbedType = vi.fn((url: string) => (url.includes("youtube") ? "youtube" : "opengraph"));
-
- installGlobMock({
- getComponentByEl: () => ({
- triggerCommand,
- renderLinkEmbed,
- renderLinkMention,
- fetchLinkMetadata,
- detectEmbedType
- })
- });
-
- // Heading, List and BlockQuote are loaded so the placement rules (which keep a URL inline
- // inside a heading, list item, table cell or quote) can be exercised against a real schema.
- editor = await createTestEditor([Essentials, Paragraph, Heading, List, BlockQuote, Link, Undo, LinkEmbed]);
- });
-
- // -----------------------------------------------------------------------
- // Plugin / UI registration
- // -----------------------------------------------------------------------
-
- it("loads the plugin, registers the commands and the toolbar button", () => {
- expect(editor.plugins.get(LinkEmbed)).toBeInstanceOf(LinkEmbed);
- expect(editor.commands.get(LINK_EMBED_COMMAND)).toBeDefined();
- expect(editor.commands.get(CHANGE_LINK_DISPLAY_COMMAND)).toBeDefined();
- expect(editor.ui.componentFactory.has("linkEmbed")).toBe(true);
- });
-
- it("binds the button to the insert command and opens the balloon form on click", () => {
- setModelData(editor.model, "<paragraph>foo[]bar</paragraph>");
-
- const view = editor.ui.componentFactory.create("linkEmbed") as unknown as {
- isEnabled: boolean;
- fire(name: string): void;
- };
- const command = editor.commands.get(LINK_EMBED_COMMAND);
- expect(view.isEnabled).toBe(command?.isEnabled);
-
- const balloon = editor.plugins.get(ContextualBalloon);
- expect(balloon.visibleView).toBeNull();
-
- // The insert flow now happens in the editor's own balloon, not in a Trilium modal.
- view.fire("execute");
- expect(balloon.visibleView).toBeInstanceOf(LinkEmbedFormView);
- });
-
- // -----------------------------------------------------------------------
- // InsertLinkEmbedCommand
- // -----------------------------------------------------------------------
-
- it("inserts a preview for a URL, storing all the metadata whatever the mode", async () => {
- const url = "https://example.com/article";
- setModelData(editor.model, "<paragraph>[]</paragraph>");
-
- // An inline mention keeps the description and image it does not itself show, so switching it
- // to a card later never has to go back to the network.
- await editor.execute(LINK_EMBED_COMMAND, { url, mode: "inline" });
-
- expect(fetchLinkMetadata).toHaveBeenCalledWith(url);
- const mention = findElement(editor, "linkMention");
- expect(mention?.getAttribute("url")).toBe(url);
- expect(mention?.getAttribute("description")).toBe(META.description);
- expect(mention?.getAttribute("image")).toBe(META.image);
- expect(mention?.getAttribute("siteName")).toBe(META.siteName);
- });
-
- it("forces the opengraph type for a card, and keeps the detected one for an embed", async () => {
- const url = "https://youtube.com/watch?v=abc12345678";
- fetchLinkMetadata.mockResolvedValue({ ...META, url, embedType: "youtube" });
-
- setModelData(editor.model, "<paragraph>[]</paragraph>");
- await editor.execute(LINK_EMBED_COMMAND, { url, mode: "card" });
- // A card is an embed that declines to play.
- expect(findElement(editor, "linkEmbed")?.getAttribute("embedType")).toBe("opengraph");
-
- setModelData(editor.model, "<paragraph>[]</paragraph>");
- await editor.execute(LINK_EMBED_COMMAND, { url, mode: "embed" });
- expect(findElement(editor, "linkEmbed")?.getAttribute("embedType")).toBe("youtube");
- });
-
- it("inserts an ordinary link for the 'plain' mode, without fetching any metadata", async () => {
- const url = "https://example.com/article";
- setModelData(editor.model, "<paragraph>[]</paragraph>");
-
- await editor.execute(LINK_EMBED_COMMAND, { url, mode: "plain" });
-
- expect(fetchLinkMetadata).not.toHaveBeenCalled();
- expect(findElement(editor, "linkMention")).toBeUndefined();
- expect(findElement(editor, "linkEmbed")).toBeUndefined();
- expect(editor.getData()).toBe(`<p><a href="${url}">${url}</a></p>`);
- });
-
- it("is enabled in a paragraph and disabled when read-only", () => {
- setModelData(editor.model, "<paragraph>foo[]bar</paragraph>");
- const command = editor.commands.get(LINK_EMBED_COMMAND);
- expect(command?.isEnabled).toBe(true);
-
- editor.enableReadOnlyMode("test");
- expect(command?.isEnabled).toBe(false);
- editor.disableReadOnlyMode("test");
- });
-
- // -----------------------------------------------------------------------
- // Schema + converters (block linkEmbed)
- // -----------------------------------------------------------------------
-
- it("registers linkEmbed (block) and linkMention (inline) in the schema", () => {
- const schema = editor.model.schema;
- expect(schema.isRegistered("linkEmbed")).toBe(true);
- expect(schema.isObject("linkEmbed")).toBe(true);
- expect(schema.isRegistered("linkMention")).toBe(true);
- expect(schema.isInline("linkMention")).toBe(true);
- expect(schema.isObject("linkMention")).toBe(true);
- });
-
- it("upcasts a <section.link-embed> with all data attributes into a linkEmbed", () => {
- editor.setData(
- '<section class="link-embed" data-url="https://e.com/" data-embed-type="web"' +
- ' data-title="T" data-description="D" data-favicon="F" data-site-name="S" data-image="I"></section>'
- );
-
- const root = editor.model.document.getRoot();
- const embed = root?.getChild(0);
- expect(embed?.is("element")).toBe(true);
- if (embed?.is("element")) {
- expect(embed.name).toBe("linkEmbed");
- expect(embed.getAttribute("url")).toBe("https://e.com/");
- expect(embed.getAttribute("embedType")).toBe("web");
- expect(embed.getAttribute("title")).toBe("T");
- expect(embed.getAttribute("siteName")).toBe("S");
- expect(embed.getAttribute("image")).toBe("I");
- }
-
- // The editing downcast UIElement callback ran and rendered the embed.
- expect(renderLinkEmbed).toHaveBeenCalled();
- const [, metadata, editable] = renderLinkEmbed.mock.calls[0];
- expect(metadata.url).toBe("https://e.com/");
- expect(editable).toBe(true);
- });
-
- it("data-downcasts a fully-populated linkEmbed, omitting empty optional attributes", () => {
- setModelData(
- editor.model,
- '<linkEmbed url="https://e.com/" embedType="web" title="T" description="D"' +
- ' favicon="F" siteName="S" image="I"></linkEmbed>'
- );
-
- const data = editor.getData();
- expect(data).toContain('class="link-embed"');
- expect(data).toContain('data-url="https://e.com/"');
- expect(data).toContain('data-embed-type="web"');
- expect(data).toContain('data-title="T"');
- expect(data).toContain('data-site-name="S"');
- expect(data).toContain('data-image="I"');
- });
-
- it("data-downcasts a minimal linkEmbed without the optional attributes", () => {
- setModelData(editor.model, '<linkEmbed url="https://e.com/" embedType="web"></linkEmbed>');
-
- const data = editor.getData();
- expect(data).toContain('data-url="https://e.com/"');
- expect(data).not.toContain("data-title");
- expect(data).not.toContain("data-site-name");
- expect(data).not.toContain("data-image");
- });
-
- it("editing-downcasts a linkEmbed to a widget and renders it via the component", () => {
- setModelData(
- editor.model,
- '<linkEmbed url="https://e.com/" embedType="web" title="T" description="D"' +
- ' favicon="F" siteName="S" image="I"></linkEmbed>'
- );
-
- const view = getViewData(editor.editing.view);
- expect(view).toContain("link-embed");
- expect(view).toContain("ck-widget");
- // The block preview carries CKEditor's own drag handle (as tables do), so the whole widget
- // moves as one instead of the user tearing its image and text apart.
- expect(view).toContain("ck-widget_with-selection-handle");
-
- // The editing wrapper must carry the full metadata, not just the URL: a copy that starts
- // inside the rendered preview bypasses CKEditor's clipboard pipeline and serializes the
- // editing DOM, and upcast rebuilds the widget purely from these attributes.
- expect(view).toContain('data-title="T"');
- expect(view).toContain('data-description="D"');
- expect(view).toContain('data-favicon="F"');
- expect(view).toContain('data-site-name="S"');
- expect(view).toContain('data-image="I"');
-
- expect(renderLinkEmbed).toHaveBeenCalled();
- const [container, metadata, editable] = renderLinkEmbed.mock.calls[0];
- expect(container).toBeInstanceOf(HTMLElement);
- expect(metadata).toMatchObject({ url: "https://e.com/", embedType: "web", title: "T" });
- expect(editable).toBe(true);
- });
-
- // -----------------------------------------------------------------------
- // Schema + converters (inline linkMention)
- // -----------------------------------------------------------------------
-
- it("upcasts a <span.link-mention> into a linkMention", () => {
- editor.setData(
- '<p><span class="link-mention" data-url="https://e.com/" data-embed-type="web"' +
- ' data-title="T" data-description="D" data-favicon="F" data-site-name="S" data-image="I">x</span></p>'
- );
-
- const paragraph = editor.model.document.getRoot()?.getChild(0);
- const mention = paragraph?.is("element") ? paragraph.getChild(0) : undefined;
- expect(mention?.is("element")).toBe(true);
- if (mention?.is("element")) {
- expect(mention.name).toBe("linkMention");
- expect(mention.getAttribute("url")).toBe("https://e.com/");
- expect(mention.getAttribute("favicon")).toBe("F");
- }
-
- expect(renderLinkMention).toHaveBeenCalled();
- });
-
- it("data-downcasts a fully-populated linkMention, omitting empty optional attributes", () => {
- setModelData(
- editor.model,
- '<paragraph><linkMention url="https://e.com/" embedType="web" title="T" description="D"' +
- ' favicon="F" siteName="S" image="I"></linkMention></paragraph>'
- );
-
- const data = editor.getData();
- expect(data).toContain('class="link-mention"');
- expect(data).toContain('data-url="https://e.com/"');
- expect(data).toContain('data-embed-type="web"');
- expect(data).toContain('data-title="T"');
- expect(data).toContain('data-site-name="S"');
- expect(data).toContain('data-image="I"');
- });
-
- it("data-downcasts a minimal linkMention without the optional attributes", () => {
- setModelData(editor.model, '<paragraph><linkMention url="https://e.com/"></linkMention></paragraph>');
-
- const data = editor.getData();
- expect(data).toContain('data-url="https://e.com/"');
- expect(data).not.toContain("data-embed-type");
- expect(data).not.toContain("data-title");
- expect(data).not.toContain("data-site-name");
- });
-
- it("upcasts link previews carrying the Markdown-export fallback anchor, dropping the anchor", () => {
- // The Markdown exporter injects an <a> child into the otherwise empty elements so the
- // export stays readable outside Trilium; on reimport the anchor must vanish into the
- // widget instead of leaking as stray text.
- editor.setData(
- '<section class="link-embed" data-url="https://e.com/" data-embed-type="opengraph" data-title="T">' +
- '<a href="https://e.com/">T</a></section>' +
- '<p>See <span class="link-mention" data-url="https://e.com/" data-title="T">' +
- '<a href="https://e.com/">T</a></span> for details.</p>'
- );
-
- const root = editor.model.document.getRoot();
- expect(root?.childCount).toBe(2);
-
- const embed = root?.getChild(0);
- expect(embed?.is("element", "linkEmbed")).toBe(true);
- if (embed?.is("element")) {
- expect(embed.getAttribute("url")).toBe("https://e.com/");
- expect(embed.childCount).toBe(0);
- }
-
- const paragraph = root?.getChild(1);
- const mention = paragraph?.is("element") ? paragraph.getChild(1) : undefined;
- expect(mention?.is("element", "linkMention")).toBe(true);
-
- // Saving again produces the canonical childless elements — the anchor does not survive,
- // let alone accumulate.
- const data = editor.getData();
- expect(data).not.toContain("<a");
- expect(data).toContain('data-url="https://e.com/"');
- });
-
- it("editing-downcasts a linkMention to an inline widget and renders it via the component", () => {
- setModelData(
- editor.model,
- '<paragraph><linkMention url="https://e.com/" embedType="web" title="T" description="D"' +
- ' favicon="F" siteName="S" image="I"></linkMention></paragraph>'
- );
-
- const view = getViewData(editor.editing.view);
- expect(view).toContain("link-mention");
-
- // Same rationale as for the block embed: a native browser copy of the editing DOM (a copy
- // starting inside the rendered preview) must round-trip the metadata through upcast, so the
- // wrapper carries all of it — this is what used to drop the favicon/title of a pasted mention.
- expect(view).toContain('data-embed-type="web"');
- expect(view).toContain('data-title="T"');
- expect(view).toContain('data-description="D"');
- expect(view).toContain('data-favicon="F"');
- expect(view).toContain('data-site-name="S"');
- expect(view).toContain('data-image="I"');
-
- expect(renderLinkMention).toHaveBeenCalled();
- const [container, metadata, editable] = renderLinkMention.mock.calls[0];
- expect(container).toBeInstanceOf(HTMLElement);
- expect(metadata).toMatchObject({ url: "https://e.com/", title: "T", favicon: "F" });
- expect(editable).toBe(true);
- });
-
- it("maps a view position inside the rendered linkMention to a model position OUTSIDE the object", () => {
- // linkMention is an empty inline object whose editing view holds a UIElement child. Without
- // the viewToModelPositionOutsideModelElement mapper registered in LinkEmbedEditing, a view
- // position inside the rendered widget resolves to a degenerate model position *inside* the
- // atomic object; the mapper must instead resolve it just after the mention.
- setModelData(
- editor.model,
- '<paragraph>foo<linkMention url="https://e.com/" title="T"></linkMention>bar</paragraph>'
- );
-
- const root = editor.editing.view.document.getRoot();
- let mentionView: ViewElement | undefined;
- if (root) {
- for (const { item } of editor.editing.view.createRangeIn(root)) {
- if (item.is("element") && item.hasClass("link-mention")) {
- mentionView = item;
- break;
- }
- }
- }
- expect(mentionView).toBeDefined();
- if (!mentionView) {
- return;
- }
-
- const viewPosition = editor.editing.view.createPositionAt(mentionView, "end");
- const modelPosition = editor.editing.mapper.toModelPosition(viewPosition);
-
- // Must land just after the mention (paragraph offset 4 = "foo"(3) + linkMention(1)),
- // not inside the atomic linkMention element.
- expect(modelPosition.parent.is("element", "linkMention")).toBe(false);
- expect(modelPosition.parent.is("element", "paragraph")).toBe(true);
- expect(modelPosition.offset).toBe(4);
- });
-
- // -----------------------------------------------------------------------
- // ChangeLinkDisplayCommand
- // -----------------------------------------------------------------------
-
- it("is disabled with no link widget selected and reports a null value", () => {
- setModelData(editor.model, "<paragraph>foo[]bar</paragraph>");
- const command = changeCommand(editor);
- expect(command.isEnabled).toBe(false);
- expect(command.value).toBeNull();
- expect(command.embedAvailable).toBe(false);
- });
-
- it("reports 'inline' for a selected linkMention and exposes embed availability", () => {
- setModelData(
- editor.model,
- '<paragraph>[<linkMention url="https://youtube.com/watch" embedType="web"></linkMention>]</paragraph>'
- );
-
- const command = changeCommand(editor);
- expect(command.isEnabled).toBe(true);
- expect(command.value).toBe("inline");
- // detectEmbedType returns "youtube" (not "opengraph") => embeddable.
- expect(command.embedAvailable).toBe(true);
- });
-
- it("exposes an http(s) URL but withholds a hostile one, so the toolbar cannot arm it", () => {
- setModelData(editor.model, '[<linkEmbed url="https://e.com/page" embedType="opengraph"></linkEmbed>]');
- expect(changeCommand(editor).url).toBe("https://e.com/page");
-
- // `url` comes from the stored data-url, which the sanitizers keep verbatim. Withholding it
- // leaves the "open link in new tab" and copy buttons disabled rather than armed.
- setModelData(editor.model, '[<linkEmbed url="javascript:alert(document.cookie)" embedType="opengraph"></linkEmbed>]');
- expect(changeCommand(editor).url).toBeNull();
- });
-
- it("reports 'card' for an opengraph linkEmbed and 'embed' otherwise", () => {
- setModelData(editor.model, '[<linkEmbed url="https://e.com/" embedType="opengraph"></linkEmbed>]');
- expect(changeCommand(editor).value).toBe("card");
-
- setModelData(editor.model, '[<linkEmbed url="https://e.com/" embedType="web"></linkEmbed>]');
- expect(changeCommand(editor).value).toBe("embed");
- });
-
- it("converts a linkMention to an embed via the command, picking the detected type", () => {
- setModelData(
- editor.model,
- '<paragraph>[<linkMention url="https://youtube.com/watch" embedType="web" title="T"></linkMention>]</paragraph>'
- );
-
- editor.execute(CHANGE_LINK_DISPLAY_COMMAND, { value: "embed" });
-
- const embed = findElement(editor, "linkEmbed");
- expect(embed).toBeDefined();
- expect(embed?.getAttribute("embedType")).toBe("youtube");
- expect(embed?.getAttribute("url")).toBe("https://youtube.com/watch");
- expect(embed?.getAttribute("title")).toBe("T");
- });
-
- it("converts a linkMention to a card, forcing the opengraph embed type", () => {
- setModelData(
- editor.model,
- '<paragraph>[<linkMention url="https://youtube.com/watch" embedType="web"></linkMention>]</paragraph>'
- );
-
- editor.execute(CHANGE_LINK_DISPLAY_COMMAND, { value: "card" });
-
- const embed = findElement(editor, "linkEmbed");
- expect(embed?.getAttribute("embedType")).toBe("opengraph");
- });
-
- it("converts a linkEmbed back to an inline linkMention", () => {
- setModelData(editor.model, '[<linkEmbed url="https://e.com/" embedType="opengraph" title="T"></linkEmbed>]');
-
- editor.execute(CHANGE_LINK_DISPLAY_COMMAND, { value: "inline" });
-
- const mention = findElement(editor, "linkMention");
- expect(mention).toBeDefined();
- expect(mention?.getAttribute("url")).toBe("https://e.com/");
- expect(mention?.getAttribute("title")).toBe("T");
- });
-
- it("converts a link widget to a plain, ordinary link — and never re-converts it", async () => {
- setModelData(editor.model, '<paragraph>[<linkMention url="https://e.com/" title="T"></linkMention>]</paragraph>');
-
- editor.execute(CHANGE_LINK_DISPLAY_COMMAND, { value: "plain" });
-
- expect(findElement(editor, "linkMention")).toBeUndefined();
- expect(editor.getData()).toBe('<p><a href="https://e.com/">https://e.com/</a></p>');
-
- // The linked text arrives as an insertion, not a linkHref attribute change, so
- // AutoLinkToMention must not have kicked in and fetched the preview straight back.
- await Promise.resolve();
- expect(fetchLinkMetadata).not.toHaveBeenCalled();
-
- // A block preview converts the same way, gaining a wrapping paragraph.
- setModelData(editor.model, '[<linkEmbed url="https://e.com/" embedType="opengraph"></linkEmbed>]');
- editor.execute(CHANGE_LINK_DISPLAY_COMMAND, { value: "plain" });
- expect(editor.getData()).toBe('<p><a href="https://e.com/">https://e.com/</a></p>');
- });
-
- it("degrades a non-http(s) URL to bare text when converting to a plain link", () => {
- // A data-url the sanitizers pass through verbatim must not become a live href
- // (same rule as the toolbar's open-link button; see isHttpUrl).
- setModelData(editor.model, '[<linkEmbed url="javascript:alert(1)" embedType="opengraph"></linkEmbed>]');
-
- editor.execute(CHANGE_LINK_DISPLAY_COMMAND, { value: "plain" });
-
- expect(editor.getData()).toBe("<p>javascript:alert(1)</p>");
- });
-
- it("does nothing when the target mode equals the current mode", () => {
- setModelData(editor.model, '[<linkEmbed url="https://e.com/" embedType="opengraph"></linkEmbed>]');
- const before = editor.getData();
-
- editor.execute(CHANGE_LINK_DISPLAY_COMMAND, { value: "card" }); // current mode is already "card"
-
- expect(findElement(editor, "linkMention")).toBeUndefined();
- expect(editor.getData()).toBe(before);
- });
-
- it("does nothing when executed without a selected link widget", () => {
- setModelData(editor.model, "<paragraph>foo[]bar</paragraph>");
- const before = editor.getData();
-
- // The command is disabled with no widget selected, and CKEditor's Command
- // swallows execute() while disabled. Force it enabled so the override body
- // runs and we exercise the early return for "no selected link widget".
- const command = editor.commands.get(CHANGE_LINK_DISPLAY_COMMAND);
- if (command) {
- command.isEnabled = true;
- }
- command?.execute({ value: "embed" });
-
- expect(editor.getData()).toBe(before);
- });
-
- // -----------------------------------------------------------------------
- // RemoveLinkEmbedCommand (the toolbar's unlink button)
- // -----------------------------------------------------------------------
-
- it("unlinks a selected linkMention, leaving the bare URL as plain text", () => {
- setModelData(editor.model, '<paragraph>[<linkMention url="https://e.com/" title="T"></linkMention>]</paragraph>');
-
- editor.execute(REMOVE_LINK_EMBED_COMMAND);
-
- expect(findElement(editor, "linkMention")).toBeUndefined();
- // Mirrors the default link's unlink: the URL survives as plain, non-linked text.
- expect(editor.getData()).toBe("<p>https://e.com/</p>");
- });
-
- it("unlinks a selected block linkEmbed the same way", () => {
- setModelData(editor.model, '[<linkEmbed url="https://e.com/" embedType="youtube"></linkEmbed>]');
-
- editor.execute(REMOVE_LINK_EMBED_COMMAND);
-
- expect(findElement(editor, "linkEmbed")).toBeUndefined();
- expect(editor.getData()).toBe("<p>https://e.com/</p>");
- });
-
- it("is disabled with no link widget selected, and does nothing if executed anyway", () => {
- setModelData(editor.model, "<paragraph>foo[]bar</paragraph>");
- const before = editor.getData();
-
- const command = editor.commands.get(REMOVE_LINK_EMBED_COMMAND);
- expect(command?.isEnabled).toBe(false);
-
- // Command swallows execute() while disabled, so force it enabled to exercise the early return.
- if (command) {
- command.isEnabled = true;
- }
- command?.execute();
-
- expect(editor.getData()).toBe(before);
- });
-
- // -----------------------------------------------------------------------
- // ChangeLinkDisplayCommand on a native link (the link balloon's Display dropdown)
- // -----------------------------------------------------------------------
-
- it("offers itself on a native http(s) link, reporting 'plain' as the current mode", () => {
- const command = changeCommand(editor);
-
- setModelData(editor.model, "<paragraph>foo[]bar</paragraph>");
- expect(command.isEnabled).toBe(false);
- expect(command.value).toBeNull();
-
- setModelData(editor.model, '<paragraph><$text linkHref="https://youtube.com/watch">https://youtube.[]com/watch</$text></paragraph>');
- expect(command.isEnabled).toBe(true);
- expect(command.value).toBe("plain");
- expect(command.embedAvailable).toBe(true);
- expect(command.url).toBe("https://youtube.com/watch");
-
- // An internal reference link has no page to preview.
- setModelData(editor.model, '<paragraph><$text linkHref="#root/someNoteId">some[]note</$text></paragraph>');
- expect(command.isEnabled).toBe(false);
- expect(command.value).toBeNull();
- });
-
- it("converts a labeled native link into an inline mention, keeping the surrounding text", async () => {
- const url = "https://example.com/article";
- setModelData(editor.model, `<paragraph>see <$text linkHref="${url}">the []article</$text> here</paragraph>`);
-
- await editor.execute(CHANGE_LINK_DISPLAY_COMMAND, { value: "inline" });
-
- expect(fetchLinkMetadata).toHaveBeenCalledWith(url);
- const mention = findElement(editor, "linkMention");
- expect(mention?.getAttribute("url")).toBe(url);
- expect(mention?.getAttribute("title")).toBe(META.title);
- // The label is replaced by the pill; the text around the link survives (spaces adjacent to
- // an inline object serialize as &nbsp;), and the new widget is left selected so its toolbar
- // — this same dropdown included — takes over from the link balloon.
- expect(editor.getData()).toContain("<p>see&nbsp;<span");
- expect(editor.getData()).toContain("</span>&nbsp;here</p>");
- expect(editor.model.document.selection.getSelectedElement()).toBe(mention);
- });
-
- it("converts a native link to the chosen block shape: card forces opengraph, embed keeps the detected type", async () => {
- const url = "https://youtube.com/watch?v=abc12345678";
- fetchLinkMetadata.mockImplementation(async () => ({ ...META, url, embedType: "youtube" }));
-
- setModelData(editor.model, `<paragraph><$text linkHref="${url}">watch [] this</$text></paragraph>`);
- await editor.execute(CHANGE_LINK_DISPLAY_COMMAND, { value: "card" });
- expect(findElement(editor, "linkEmbed")?.getAttribute("embedType")).toBe("opengraph");
-
- setModelData(editor.model, `<paragraph><$text linkHref="${url}">watch [] this</$text></paragraph>`);
- await editor.execute(CHANGE_LINK_DISPLAY_COMMAND, { value: "embed" });
- const embed = findElement(editor, "linkEmbed");
- expect(embed?.getAttribute("embedType")).toBe("youtube");
- expect(editor.model.document.selection.getSelectedElement()).toBe(embed);
- });
-
- it("does nothing for 'plain' on a native link — it already is one", async () => {
- setModelData(editor.model, '<paragraph><$text linkHref="https://e.com/">https://e.[]com/</$text></paragraph>');
- const before = editor.getData();
-
- await editor.execute(CHANGE_LINK_DISPLAY_COMMAND, { value: "plain" });
-
- expect(fetchLinkMetadata).not.toHaveBeenCalled();
- expect(editor.getData()).toBe(before);
- });
-
- it("does nothing when the linked text was deleted while the metadata was being fetched", async () => {
- const url = "https://example.com/";
- let resolveFetch: (meta: unknown) => void = () => {};
- fetchLinkMetadata.mockReturnValue(new Promise((resolve) => { resolveFetch = resolve; }));
- setModelData(editor.model, `<paragraph><$text linkHref="${url}">https://exa[]mple.com/</$text></paragraph>`);
-
- const executed = editor.execute(CHANGE_LINK_DISPLAY_COMMAND, { value: "inline" }) as unknown as Promise<void>;
- setModelData(editor.model, "<paragraph>replaced[]</paragraph>");
- resolveFetch({ ...META, url });
- await executed;
-
- expect(findElement(editor, "linkMention")).toBeUndefined();
- expect(findElement(editor, "linkEmbed")).toBeUndefined();
- expect(editor.getData()).toBe("<p>replaced</p>");
- });
-
- // -----------------------------------------------------------------------
- // AutoLinkToMention
- // -----------------------------------------------------------------------
-
- it("converts a bare linked URL into a linkMention after fetching metadata", async () => {
- const url = "https://example.com/article";
- addLinkedText(editor, url);
-
- await flushFetch();
-
- expect(fetchLinkMetadata).toHaveBeenCalledWith(url);
- const mention = findElement(editor, "linkMention");
- expect(mention).toBeDefined();
- expect(mention?.getAttribute("url")).toBe(url);
- expect(mention?.getAttribute("title")).toBe(META.title);
- });
-
- it("leaves the plain link untouched when the metadata could not be resolved, and says why", async () => {
- const url = "https://blocked.example.com/article";
- fetchLinkMetadata.mockResolvedValueOnce({ url, embedType: "opengraph", title: "blocked.example.com", unresolved: true });
- const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
-
- addLinkedText(editor, url);
- await flushFetch();
-
- expect(fetchLinkMetadata).toHaveBeenCalledWith(url);
- expect(findElement(editor, "linkMention")).toBeUndefined();
- expect(findElement(editor, "linkEmbed")).toBeUndefined();
- // The link AutoLink created is still there, as plain linked text.
- expect(editor.getData()).toContain(`<a href="${url}">${url}</a>`);
- // The warning says what happened but never names the URL: a console gets screenshotted and
- // pasted into bug reports, and a pasted link can carry a one-time token.
- expect(warn).toHaveBeenCalledWith(expect.stringContaining("Link preview dropped"));
- expect(warn).not.toHaveBeenCalledWith(expect.stringContaining(url));
-
- warn.mockRestore();
- });
-
- it("does not auto-convert when autoLinkPreviewsEnabled is false, but still offers the insert command", async () => {
- const url = "https://example.com/article";
- editor = await createTestEditor(
- [Essentials, Paragraph, BlockQuote, Link, Undo, LinkEmbed],
- hostConfig({ autoLinkPreviewsEnabled: false })
- );
-
- addLinkedText(editor, url);
- await flushFetch();
-
- // The URL is not even looked up: the check runs before the metadata request.
- expect(fetchLinkMetadata).not.toHaveBeenCalled();
- expect(findElement(editor, "linkMention")).toBeUndefined();
- expect(editor.getData()).toContain(`<a href="${url}">${url}</a>`);
-
- // Inserting a preview by hand is unaffected by the option: only auto-detection is gated.
- await editor.execute(LINK_EMBED_COMMAND, { url, mode: "card" });
- expect(findElement(editor, "linkEmbed")?.getAttribute("url")).toBe(url);
- });
-
- it("re-reads a getter on every detected URL, so toggling the option needs no new editor", async () => {
- let enabled = false;
- editor = await createTestEditor(
- [Essentials, Paragraph, BlockQuote, Link, Undo, LinkEmbed],
- hostConfig({ autoLinkPreviewsEnabled: () => enabled })
- );
-
- addLinkedText(editor, "https://example.com/off");
- await flushFetch();
- expect(findElement(editor, "linkMention")).toBeUndefined();
-
- // Flip the option on the same editor instance — the next detected URL converts.
- enabled = true;
- addLinkedText(editor, "https://example.com/on");
- await flushFetch();
- expect(findElement(editor, "linkMention")).toBeDefined();
- });
-
- // -----------------------------------------------------------------------
- // Placement: what shape an auto-detected URL takes, and why
- // -----------------------------------------------------------------------
-
- describe("placement", () => {
- const PLAIN_URL = "https://example.com/article";
- const VIDEO_URL = "https://youtube.com/watch?v=abc12345678";
-
- /** Makes the next fetch report `url` as embeddable, the way a YouTube link comes back. */
- function embeddable(url: string) {
- fetchLinkMetadata.mockResolvedValueOnce({ ...META, url, embedType: "youtube" });
- }
-
- it("turns a URL left alone on its own line into a card", async () => {
- autoLinkIn(editor, urlLeftAloneOnItsOwnLine(PLAIN_URL), PLAIN_URL);
- await flushFetch();
-
- expect(findElement(editor, "linkMention")).toBeUndefined();
- const embed = findElement(editor, "linkEmbed");
- expect(embed?.getAttribute("url")).toBe(PLAIN_URL);
- // "opengraph" is what the renderer shows as a card rather than a player.
- expect(embed?.getAttribute("embedType")).toBe("opengraph");
- });
-
- it("turns an embeddable URL left alone on its own line into a player", async () => {
- embeddable(VIDEO_URL);
-
- autoLinkIn(editor, urlLeftAloneOnItsOwnLine(VIDEO_URL), VIDEO_URL);
- await flushFetch();
-
- expect(findElement(editor, "linkMention")).toBeUndefined();
- expect(findElement(editor, "linkEmbed")?.getAttribute("embedType")).toBe("youtube");
- });
-
- it("keeps the URL inline while the caret is still on its line, embeddable or not", async () => {
- // The user typed a space, not Enter: they may still be writing that sentence, so the URL
- // is alone only by accident. Nothing has been *left* alone yet.
- embeddable(VIDEO_URL);
- addLinkedText(editor, VIDEO_URL);
- await flushFetch();
-
- expect(findElement(editor, "linkEmbed")).toBeUndefined();
- expect(findElement(editor, "linkMention")?.getAttribute("url")).toBe(VIDEO_URL);
- });
-
- it("keeps the URL inline when text sits beside it on the line", async () => {
- autoLinkIn(editor, `<paragraph>See ${PLAIN_URL}</paragraph><paragraph>[]</paragraph>`, PLAIN_URL);
- await flushFetch();
-
- expect(findElement(editor, "linkEmbed")).toBeUndefined();
- expect(findElement(editor, "linkMention")).toBeDefined();
- });
-
- it("keeps the URL inline inside a list item, a quote and a heading", async () => {
- // A block preview inside these reads as a layout accident, so they stay inline — even
- // though the URL is alone in its block and the caret has moved on.
- const blocks = {
- "list item": `<paragraph listIndent="0" listItemId="a" listType="bulleted">${PLAIN_URL}</paragraph>`,
- quote: `<blockQuote><paragraph>${PLAIN_URL}</paragraph></blockQuote>`,
- heading: `<heading2>${PLAIN_URL}</heading2>`
- };
-
- for (const block of Object.values(blocks)) {
- autoLinkIn(editor, `${block}<paragraph>[]</paragraph>`, PLAIN_URL);
- await flushFetch();
-
- expect(findElement(editor, "linkEmbed")).toBeUndefined();
- expect(findElement(editor, "linkMention")).toBeDefined();
- }
- });
-
- it("leaves the caret where the user moved it, even if they typed while the fetch was in flight", async () => {
- const { resolveFetch } = useDeferredFetch();
- autoLinkIn(editor, urlLeftAloneOnItsOwnLine(PLAIN_URL), PLAIN_URL);
-
- // The user carries on typing on the new line while the metadata is still being fetched.
- editor.model.change((writer) => {
- const caret = editor.model.document.selection.getFirstPosition();
- if (!caret) {
- throw new Error("Expected a caret position.");
- }
- writer.insertText("hello", caret);
- });
-
- resolveFetch({ ...META, url: PLAIN_URL });
- await flushFetch();
-
- // The card took over the URL's paragraph without dragging the caret back into it: the
- // typed text is intact and the caret still sits after it.
- expect(findElement(editor, "linkEmbed")).toBeDefined();
- expect(editor.getData()).toContain("<p>hello</p>");
-
- const caretBlock = editor.model.document.selection.getFirstPosition()?.parent;
- expect(caretBlock?.is("element", "paragraph")).toBe(true);
- });
- });
-
- it("ignores a labeled link whose text differs from the href", async () => {
- addLinkedText(editor, "https://example.com/article", "click here");
-
- await flushFetch();
-
- expect(findElement(editor, "linkMention")).toBeUndefined();
- expect(fetchLinkMetadata).not.toHaveBeenCalled();
- });
-
- it("ignores non-http(s) links that fail the embeddable URL regex", async () => {
- addLinkedText(editor, "mailto:[email protected]");
-
- await flushFetch();
-
- expect(findElement(editor, "linkMention")).toBeUndefined();
- expect(fetchLinkMetadata).not.toHaveBeenCalled();
- });
-
- it("skips non-text items in the affected range before reaching the URL text", async () => {
- const url = "https://example.com/break";
-
- // Put a softBreak (an inline element, not a text proxy) before the URL text so
- // the range walker yields a non-$textProxy item first, then the matching text.
- setModelData(editor.model, "<paragraph>[]</paragraph>");
- editor.model.change((writer) => {
- const paragraph = editor.model.document.getRoot()?.getChild(0);
- if (!paragraph?.is("element")) {
- throw new Error("Expected a paragraph block.");
- }
- writer.insertElement("softBreak", paragraph, 0);
- writer.insertText(url, paragraph, "end");
- });
- editor.model.change((writer) => {
- const paragraph = editor.model.document.getRoot()?.getChild(0);
- if (paragraph?.is("element")) {
- writer.setAttribute("linkHref", url, writer.createRangeIn(paragraph));
- }
- });
-
- await flushFetch();
-
- expect(fetchLinkMetadata).toHaveBeenCalledWith(url);
- expect(findElement(editor, "linkMention")).toBeDefined();
- });
-
- it("ignores undo batches that carry no linkHref attribute change", async () => {
- // Type plain text, then undo it: the undo batch is flagged isUndo but its diff is
- // an insert/remove change, exercising the non-attribute skip in the undo branch.
- setModelData(editor.model, "<paragraph>[]</paragraph>");
- editor.model.change((writer) => {
- const paragraph = editor.model.document.getRoot()?.getChild(0);
- if (paragraph?.is("element")) {
- writer.insertText("hello", paragraph, 0);
- }
- });
-
- editor.execute("undo");
- await flushFetch();
-
- expect(fetchLinkMetadata).not.toHaveBeenCalled();
- });
-
- it("records the URL on undo and does not re-convert it afterwards", async () => {
- const url = "https://example.com/again";
-
- // Apply the link to a LABELED link (text != href) so no conversion happens yet.
- setModelData(editor.model, "<paragraph>click here[]</paragraph>");
- editor.model.change((writer) => {
- const paragraph = editor.model.document.getRoot()?.getChild(0);
- if (paragraph?.is("element")) {
- writer.setAttribute("linkHref", url, writer.createRangeIn(paragraph));
- }
- });
- await flushFetch();
-
- // Undo (linkHref url -> null): handler sees an undo batch with a non-string new
- // value, so nothing is recorded. Redo (null -> url): the undo batch carries a
- // string linkHref, so the handler records the URL as dismissed.
- editor.execute("undo");
- editor.execute("redo");
- await flushFetch();
-
- // Now a BARE link with the same URL must be skipped because it was dismissed.
- addLinkedText(editor, url);
- await flushFetch();
-
- expect(fetchLinkMetadata).not.toHaveBeenCalled();
- expect(findElement(editor, "linkMention")).toBeUndefined();
- });
-
- it("ignores attribute modifications where the old linkHref value was not null", async () => {
- const url = "https://example.com/changed";
- editor.setData(`<p><a href="https://old.example.com/">${url}</a></p>`);
-
- // Change the existing href: old value is non-null, so the handler skips it.
- editor.model.change((writer) => {
- const paragraph = editor.model.document.getRoot()?.getChild(0);
- if (paragraph?.is("element")) {
- writer.setAttribute("linkHref", url, writer.createRangeIn(paragraph));
- }
- });
-
- await flushFetch();
-
- expect(findElement(editor, "linkMention")).toBeUndefined();
- expect(fetchLinkMetadata).not.toHaveBeenCalled();
- });
-
- // The following tests exercise the defensive re-resolution guards in
- // _replaceWithMention: the model can change between when the fetch starts and
- // when it resolves, so the path/text are re-resolved and bail out gracefully.
-
- it("bails out when the parent block was removed before the fetch resolved", async () => {
- const { resolveFetch } = useDeferredFetch();
- const url = "https://example.com/gone";
-
- // The URL lives in the SECOND paragraph (stored parent path [1]).
- setModelData(editor.model, `<paragraph>first</paragraph><paragraph>${url}[]</paragraph>`);
- editor.model.change((writer) => {
- const paragraph = editor.model.document.getRoot()?.getChild(1);
- if (paragraph?.is("element")) {
- writer.setAttribute("linkHref", url, writer.createRangeIn(paragraph));
- }
- });
- await flushFetch();
-
- // Remove the second paragraph: the stored path [1] now resolves to undefined.
- editor.model.change((writer) => {
- const paragraph = editor.model.document.getRoot()?.getChild(1);
- if (paragraph) {
- writer.remove(paragraph);
- }
- });
-
- resolveFetch({ ...META, url });
- await flushFetch();
-
- expect(findElement(editor, "linkMention")).toBeUndefined();
- });
-
- it("bails out when an intermediate path segment no longer resolves", async () => {
- const { resolveFetch } = useDeferredFetch();
- const url = "https://example.com/nested";
-
- // Nest the URL two block-quotes deep so the stored parent path has depth 3
- // ([outerQuote, innerQuote, paragraph]).
- editor.setData(`<blockquote><blockquote><p>${url}</p></blockquote></blockquote>`);
- editor.model.change((writer) => {
- const outer = editor.model.document.getRoot()?.getChild(0);
- const inner = outer?.is("element") ? outer.getChild(0) : undefined;
- const paragraph = inner?.is("element") ? inner.getChild(0) : undefined;
- if (paragraph?.is("element")) {
- writer.setAttribute("linkHref", url, writer.createRangeIn(paragraph));
- }
- });
- await flushFetch();
-
- // Remove the inner block-quote: both quotes collapse, leaving an auto-paragraph
- // at root[0]. Re-resolving the stored path [0,0,0] yields undefined at the second
- // segment, so the third iteration sees a falsy parentEl and bails.
- editor.model.change((writer) => {
- const outer = editor.model.document.getRoot()?.getChild(0);
- const inner = outer?.is("element") ? outer.getChild(0) : undefined;
- if (inner?.is("element")) {
- writer.remove(inner);
- }
- });
-
- resolveFetch({ ...META, url });
- await flushFetch();
-
- expect(findElement(editor, "linkMention")).toBeUndefined();
- });
-
- it("skips non-matching text and bails when the URL text lost its linkHref", async () => {
- const { resolveFetch } = useDeferredFetch();
- const url = "https://example.com/edited";
-
- // Paragraph holds a non-matching text node followed by the URL text. Only the
- // URL text gets the linkHref, so the handler starts the deferred conversion.
- setModelData(editor.model, "<paragraph>[]</paragraph>");
- editor.model.change((writer) => {
- const paragraph = editor.model.document.getRoot()?.getChild(0);
- if (!paragraph?.is("element")) {
- throw new Error("Expected a paragraph block.");
- }
- writer.insertText("other ", paragraph, 0);
- writer.insertText(url, paragraph, "end");
- });
- editor.model.change((writer) => {
- const paragraph = editor.model.document.getRoot()?.getChild(0);
- if (paragraph?.is("element")) {
- const start = writer.createPositionAt(paragraph, 6); // after "other "
- const end = writer.createPositionAt(paragraph, "end");
- writer.setAttribute("linkHref", url, writer.createRange(start, end));
- }
- });
- await flushFetch();
-
- // Before the fetch resolves, point the URL text's linkHref at a different URL.
- // The inner walker now sees the non-matching "other " text (data != url) and
- // then the URL text whose linkHref no longer matches, so neither converts.
- // Keeping a distinct linkHref (rather than removing it) prevents the two text
- // nodes from merging, so both walker branches are exercised.
- editor.model.change((writer) => {
- const paragraph = editor.model.document.getRoot()?.getChild(0);
- if (paragraph?.is("element")) {
- const start = writer.createPositionAt(paragraph, 6); // after "other "
- const end = writer.createPositionAt(paragraph, "end");
- writer.setAttribute("linkHref", "https://other.example.com/", writer.createRange(start, end));
- }
- });
-
- resolveFetch({ ...META, url });
- await flushFetch();
-
- expect(findElement(editor, "linkMention")).toBeUndefined();
- });
-
- function useDeferredFetch() {
- let resolveFetch: (metadata: LinkEmbedMetadata) => void = () => {};
- fetchLinkMetadata.mockImplementation(
- () => new Promise<LinkEmbedMetadata>((resolve) => {
- resolveFetch = resolve;
- })
- );
- return { resolveFetch: (metadata: LinkEmbedMetadata) => resolveFetch(metadata) };
- }
-});
-
-function changeCommand(editor: ClassicEditor): {
- isEnabled: boolean;
- value: string | null;
- embedAvailable: boolean;
- url: string | null;
-} {
- const command = editor.commands.get(CHANGE_LINK_DISPLAY_COMMAND);
- if (!command) {
- throw new Error("changeLinkDisplay command is not registered.");
- }
- return command as unknown as { isEnabled: boolean; value: string | null; embedAvailable: boolean; url: string | null };
-}
-
-/**
- * Editor config entries the host supplies but the CKEditor config type does not declare — the host
- * sets them through the same kind of cast (see the client's `buildConfig`).
- */
-function hostConfig(entries: Record<string, unknown>): Parameters<typeof createTestEditor>[1] {
- return entries as Parameters<typeof createTestEditor>[1];
-}
-
-function findElement(editor: ClassicEditor, name: string) {
- const root = editor.model.document.getRoot();
- if (!root) {
- return undefined;
- }
- const range = editor.model.createRangeIn(root);
- for (const item of range.getWalker()) {
- if (item.item.is("element", name)) {
- return item.item;
- }
- }
- return undefined;
-}
-
-/**
- * Sets up `modelData` and then, in a separate change, applies `linkHref` to the text node holding
- * `href` — exactly what AutoLink does. Where `modelData` leaves the caret *is* the gesture under
- * test: still inside the URL's block (the user typed a space and may keep going), or in the block
- * after it (the user pressed Enter, which splits the paragraph and carries the caret onward).
- */
-function autoLinkIn(editor: ClassicEditor, modelData: string, href: string): void {
- setModelData(editor.model, modelData);
-
- editor.model.change((writer) => {
- const root = editor.model.document.getRoot();
- if (!root) {
- throw new Error("Expected a document root.");
- }
-
- for (const item of writer.createRangeIn(root).getWalker()) {
- if (!item.item.is("$textProxy")) continue;
-
- // AutoLink links the URL itself, not the whole text node it happens to share with the
- // words around it — so link exactly the URL's slice of the node.
- const index = item.item.data.indexOf(href);
- if (index < 0) continue;
-
- const parent = item.item.parent;
- if (!parent || !parent.is("element") || item.item.startOffset === null) continue;
-
- const start = item.item.startOffset + index;
- writer.setAttribute("linkHref", href, writer.createRange(
- writer.createPositionAt(parent, start),
- writer.createPositionAt(parent, start + href.length)
- ));
- return;
- }
-
- throw new Error(`No text node holds ${href}.`);
- });
-}
-
-/** The model data for a URL left alone on its own line, with the caret carried to the next one. */
-function urlLeftAloneOnItsOwnLine(url: string): string {
- return `<paragraph>${url}</paragraph><paragraph>[]</paragraph>`;
-}
-
-/**
- * Inserts text into the paragraph and applies a `linkHref` attribute to it via a
- * writer change (null -> url), exactly as CKEditor's AutoLink plugin does when a
- * raw URL is pasted/typed. This drives the `AutoLinkToMention` `change:data` listener.
- * The caret is left in the block, as it is when the user types a space after the URL.
- */
-function addLinkedText(editor: ClassicEditor, href: string, text = href): void {
- // First insert the plain text in its own batch.
- setModelData(editor.model, `<paragraph>${text}[]</paragraph>`);
- // Then, in a SEPARATE change, apply the linkHref attribute (null -> url).
- // AutoLink does exactly this, producing an attribute diff (not a text insert)
- // which is what AutoLinkToMention listens for.
- editor.model.change((writer) => {
- const paragraph = editor.model.document.getRoot()?.getChild(0);
- if (!paragraph?.is("element")) {
- throw new Error("Expected a paragraph block.");
- }
- writer.setAttribute("linkHref", href, writer.createRangeIn(paragraph));
- });
-}
-
-/**
- * Lets the `fetchLinkMetadata().then(...)` chain resolve and the resulting model change apply.
- * A task turn is awaited rather than a fixed number of microtasks: the latter is a guess at the
- * chain's depth that silently under-waits, which makes a conversion test fail and — worse — makes a
- * test asserting that NO conversion happened pass for the wrong reason.
- */
-async function flushFetch(): Promise<void> {
- await new Promise((resolve) => setTimeout(resolve, 0));
-}
diff --git a/packages/ckeditor5/src/plugins/linkembed.ts b/packages/ckeditor5/src/plugins/linkembed.ts
deleted file mode 100644
index 4c5fb06ff6..0000000000
--- a/packages/ckeditor5/src/plugins/linkembed.ts
+++ /dev/null
@@ -1,850 +0,0 @@
-import { type BlockChildLike, chooseLinkPreviewKind, isHttpUrl, isUrlAloneInBlock } from '@triliumnext/commons';
-import { ButtonView, clickOutsideHandler, Command, ContextualBalloon, findAttributeRange, ModelLiveRange, Plugin, toWidget, viewToModelPositionOutsideModelElement, Widget, type Editor, type Observable } from 'ckeditor5';
-import linkPreviewIcon from '../icons/link-preview.svg?raw';
-import LinkEmbedFormView from './link_embed_form.js';
-import { translate } from './translate.js';
-import { preventCKEditorHandling } from './widget_utils.js';
-
-export const LINK_EMBED_COMMAND = 'insertLinkEmbed';
-export const CHANGE_LINK_DISPLAY_COMMAND = 'changeLinkDisplay';
-export const REMOVE_LINK_EMBED_COMMAND = 'removeLinkEmbed';
-
-export const LINK_DISPLAY_MODES = [
- { value: 'inline', label: 'Inline', labelKey: 'link_embed.mode_inline' },
- { value: 'card', label: 'Card', labelKey: 'link_embed.mode_card' },
- { value: 'embed', label: 'Embed', labelKey: 'link_embed.mode_embed' },
- // The way out of the preview system: an ordinary <a> link, no widget. Offered in the same
- // dropdowns as the real modes so "back to a normal URL" is found where the user looks for it.
- { value: 'plain', label: 'Plain link', labelKey: 'link_embed.mode_plain' }
-] as const;
-
-export type LinkDisplayMode = typeof LINK_DISPLAY_MODES[number]['value'];
-
-const EMBEDDABLE_URL_REGEX = /^https?:\/\/\S+$/;
-
-export default class LinkEmbed extends Plugin {
- static get requires() {
- return [LinkEmbedEditing, LinkEmbedUI, AutoLinkToMention];
- }
-}
-
-/**
- * The "Link preview" toolbar button and the balloon form it opens.
- *
- * The form lives inside the editor — the same balloon the native link button uses — rather than in a
- * Trilium modal, so inserting a preview never leaves the editing surface and needs no round trip
- * out to the app and back.
- */
-class LinkEmbedUI extends Plugin {
-
- static get requires() {
- return [ContextualBalloon];
- }
-
- private _formView: LinkEmbedFormView | null = null;
-
- init() {
- const editor = this.editor;
-
- editor.ui.componentFactory.add('linkEmbed', locale => {
- const command = editor.commands.get(LINK_EMBED_COMMAND);
- const buttonView = new ButtonView(locale);
-
- buttonView.set({
- label: editor.t('Link preview'),
- icon: linkPreviewIcon,
- tooltip: true
- });
-
- /* v8 ignore next -- LinkEmbedEditing always registers LINK_EMBED_COMMAND (both are required by LinkEmbed), so the no-command branch is unreachable */
- if (command) {
- buttonView.bind('isEnabled').to(command as Observable & { isEnabled: boolean }, 'isEnabled');
- }
-
- this.listenTo(buttonView, 'execute', () => this._showForm());
- return buttonView;
- });
- }
-
- override destroy() {
- super.destroy();
- this._formView?.destroy();
- }
-
- private _showForm() {
- const editor = this.editor;
- const balloon = editor.plugins.get(ContextualBalloon);
- const form = this._getFormView();
-
- if (balloon.hasView(form)) return;
-
- form.reset();
- balloon.add({
- view: form,
- position: {
- target: () => {
- const view = editor.editing.view;
- const range = view.document.selection.getFirstRange();
- /* v8 ignore next -- the editing view's selection always has a range while the editor is focused */
- if (!range) return editor.ui.getEditableElement() as HTMLElement;
- return view.domConverter.viewRangeToDom(range);
- }
- }
- });
- form.focus();
- }
-
- private _hideForm() {
- const balloon = this.editor.plugins.get(ContextualBalloon);
- const form = this._formView;
-
- /* v8 ignore next -- the form is only ever hidden from its own handlers, so by then it exists and is shown */
- if (!form || !balloon.hasView(form)) return;
-
- balloon.remove(form);
- this.editor.editing.view.focus();
- }
-
- private _getFormView(): LinkEmbedFormView {
- if (this._formView) return this._formView;
-
- const editor = this.editor;
- const form = new LinkEmbedFormView(editor.locale, (key, fallback) => translate(editor, key, fallback));
- this._formView = form;
-
- // The mode selector only offers "Embed" for a URL that has a player behind it — the same
- // question the widget toolbar's dropdown asks of an existing preview.
- form.on('change:url', () => {
- const embedAvailable = detectEmbedTypeFor(editor, form.url) !== 'opengraph';
- form.embedAvailable = embedAvailable;
-
- // Follow the URL until the user overrules it: a video wants its player, anything else a card.
- if (!this._modePickedByUser) {
- form.mode = embedAvailable ? 'embed' : 'card';
- } else if (!embedAvailable && form.mode === 'embed') {
- form.mode = 'card';
- }
- });
-
- form.modeDropdownView.on('execute', () => {
- this._modePickedByUser = true;
- });
-
- form.on('submit', () => {
- void this._insert(form);
- });
-
- // Esc and clicking away dismiss the form, exactly as they do for the native link balloon.
- form.keystrokes.set('Esc', (_data, cancel) => {
- this._hideForm();
- cancel();
- });
- clickOutsideHandler({
- emitter: form,
- activator: () => this.editor.plugins.get(ContextualBalloon).hasView(form),
- contextElements: () => [this.editor.plugins.get(ContextualBalloon).view.element as HTMLElement],
- callback: () => this._hideForm()
- });
-
- return form;
- }
-
- private _modePickedByUser = false;
-
- private async _insert(form: LinkEmbedFormView) {
- // The Insert button is disabled mid-fetch, but Enter fires `submit` on the form itself, so
- // the guard has to live here or a second Enter would fetch and insert twice.
- if (form.isFetching) return;
-
- const url = normalizeUrl(form.url);
- if (!url) return;
-
- // The metadata fetch takes a moment (the server reads the page and downloads the image), so
- // the form stays open and disabled meanwhile rather than vanishing into an apparent no-op.
- form.isFetching = true;
- try {
- await this.editor.execute(LINK_EMBED_COMMAND, { url, mode: form.mode });
- } finally {
- form.isFetching = false;
- }
-
- this._modePickedByUser = false;
- this._hideForm();
- }
-}
-
-/**
- * Makes a typed URL absolute, defaulting the scheme the way the editor's own link field does.
- * Returns null when what was typed cannot be a link preview at all.
- */
-function normalizeUrl(rawUrl: string): string | null {
- const trimmed = rawUrl.trim();
- if (!trimmed) return null;
-
- const withScheme = /^[a-z][a-z0-9+.-]*:/i.test(trimmed) ? trimmed : `https://${trimmed}`;
- return isHttpUrl(withScheme) ? withScheme : null;
-}
-
-/** Asks the host what kind of preview a URL supports. */
-function detectEmbedTypeFor(editor: Editor, url: string): string {
- if (!url.trim()) return 'opengraph';
-
- const editorEl = editor.editing.view.getDomRoot();
- const component = glob.getComponentByEl<EditorComponent>(editorEl);
- return component.detectEmbedType(normalizeUrl(url) ?? url);
-}
-
-// ---------------------------------------------------------------------------
-// Schema + converters for linkEmbed (block) and linkMention (inline)
-// ---------------------------------------------------------------------------
-
-class LinkEmbedEditing extends Plugin {
- static get requires() {
- return [Widget];
- }
-
- init() {
- this._defineSchema();
- this._defineConverters();
-
- // linkMention is an empty inline object whose editing view holds a UIElement child, so a
- // view position inside the rendered widget would otherwise resolve to a degenerate model
- // position *inside* the atomic element. Map it just outside the mention instead (mirrors
- // ReferenceLink). The block linkEmbed is a $block object and needs no such mapping.
- this.editor.editing.mapper.on(
- 'viewToModelPosition',
- viewToModelPositionOutsideModelElement(this.editor.model, viewElement => viewElement.hasClass('link-mention'))
- );
-
- this.editor.commands.add(LINK_EMBED_COMMAND, new InsertLinkEmbedCommand(this.editor));
- this.editor.commands.add(CHANGE_LINK_DISPLAY_COMMAND, new ChangeLinkDisplayCommand(this.editor));
- this.editor.commands.add(REMOVE_LINK_EMBED_COMMAND, new RemoveLinkEmbedCommand(this.editor));
- }
-
- _defineSchema() {
- const schema = this.editor.model.schema;
-
- schema.register('linkEmbed', {
- isObject: true,
- allowAttributes: ['url', 'embedType', 'title', 'description', 'favicon', 'siteName', 'image'],
- allowWhere: '$block'
- });
-
- schema.register('linkMention', {
- isInline: true,
- isObject: true,
- // Stores all metadata so we can switch to card/embed without re-fetching.
- allowAttributes: ['url', 'embedType', 'title', 'description', 'favicon', 'siteName', 'image'],
- allowWhere: '$text'
- });
- }
-
- _defineConverters() {
- const editor = this.editor;
- const conversion = editor.conversion;
-
- // ===== linkEmbed (block) =====
-
- conversion.for('upcast').elementToElement({
- model: (viewElement, { writer }) => {
- return writer.createElement('linkEmbed', {
- url: viewElement.getAttribute('data-url'),
- embedType: viewElement.getAttribute('data-embed-type'),
- title: viewElement.getAttribute('data-title'),
- description: viewElement.getAttribute('data-description'),
- favicon: viewElement.getAttribute('data-favicon'),
- siteName: viewElement.getAttribute('data-site-name'),
- image: viewElement.getAttribute('data-image')
- });
- },
- view: { name: 'section', classes: 'link-embed' }
- });
-
- conversion.for('dataDowncast').elementToElement({
- model: 'linkEmbed',
- view: (modelElement, { writer }) => {
- return writer.createContainerElement('section', metadataViewAttributes(modelElement, 'link-embed', ['url', 'embedType']));
- }
- });
-
- conversion.for('editingDowncast').elementToElement({
- model: 'linkEmbed',
- view: (modelElement, { writer }) => {
- const url = modelElement.getAttribute('url') as string;
- const embedType = modelElement.getAttribute('embedType') as string;
- const title = modelElement.getAttribute('title') as string | undefined;
- const description = modelElement.getAttribute('description') as string | undefined;
- const favicon = modelElement.getAttribute('favicon') as string | undefined;
- const siteName = modelElement.getAttribute('siteName') as string | undefined;
- const image = modelElement.getAttribute('image') as string | undefined;
-
- const section = writer.createContainerElement('section', metadataViewAttributes(modelElement, 'link-embed', ['url', 'embedType']));
-
- const preview = writer.createUIElement('div', {
- class: 'link-embed-preview-wrapper',
- 'data-cke-ignore-events': 'true'
- }, function (domDocument) {
- const domElement = this.toDomElement(domDocument);
- const editorEl = editor.editing.view.getDomRoot();
- const component = glob.getComponentByEl<EditorComponent>(editorEl);
- component.renderLinkEmbed(domElement, { url, embedType, title, description, favicon, siteName, image }, true);
- preventCKEditorHandling(domElement, editor);
- return domElement;
- });
-
- writer.insert(writer.createPositionAt(section, 0), preview);
- // hasSelectionHandle gives the block preview (both card and video) CKEditor's own
- // widget drag handle — the same one tables use. Without a handle the user grabs the
- // preview's own content and the browser's native drag tears the image and text apart;
- // the handle moves the whole widget atomically instead.
- return toWidget(section, writer, { label: 'link embed widget', hasSelectionHandle: true });
- }
- });
-
- // ===== linkMention (inline) =====
-
- conversion.for('upcast').elementToElement({
- model: (viewElement, { writer }) => {
- return writer.createElement('linkMention', {
- url: viewElement.getAttribute('data-url'),
- embedType: viewElement.getAttribute('data-embed-type'),
- title: viewElement.getAttribute('data-title'),
- description: viewElement.getAttribute('data-description'),
- favicon: viewElement.getAttribute('data-favicon'),
- siteName: viewElement.getAttribute('data-site-name'),
- image: viewElement.getAttribute('data-image')
- });
- },
- view: { name: 'span', classes: 'link-mention' }
- });
-
- conversion.for('dataDowncast').elementToElement({
- model: 'linkMention',
- view: (modelElement, { writer }) => {
- return writer.createContainerElement('span', metadataViewAttributes(modelElement, 'link-mention', ['url']));
- }
- });
-
- conversion.for('editingDowncast').elementToElement({
- model: 'linkMention',
- view: (modelElement, { writer }) => {
- const url = modelElement.getAttribute('url') as string;
- const title = modelElement.getAttribute('title') as string | undefined;
- const favicon = modelElement.getAttribute('favicon') as string | undefined;
-
- const span = writer.createContainerElement('span', metadataViewAttributes(modelElement, 'link-mention', ['url']));
-
- const inner = writer.createUIElement('span', {
- class: 'link-mention-inner',
- 'data-cke-ignore-events': 'true'
- }, function (domDocument) {
- const domElement = this.toDomElement(domDocument);
- const editorEl = editor.editing.view.getDomRoot();
- const component = glob.getComponentByEl<EditorComponent>(editorEl);
- component.renderLinkMention(domElement, { url, title, favicon }, true);
- preventCKEditorHandling(domElement, editor);
- return domElement;
- });
-
- writer.insert(writer.createPositionAt(span, 0), inner);
- return toWidget(span, writer, { label: 'link mention widget', hasSelectionHandle: false });
- }
- });
- }
-}
-
-/**
- * Inserts a preview for a URL: fetches its metadata through the host, then puts the widget in.
- *
- * All the metadata is written onto the element whichever shape is chosen — an inline mention stores
- * the description and image it does not itself show — so that switching modes later, via the widget
- * toolbar's Display dropdown, never has to go back to the network.
- */
-class InsertLinkEmbedCommand extends Command {
- override async execute({ url, mode }: { url: string; mode: LinkDisplayMode }) {
- const editor = this.editor;
-
- // A plain link is not a preview at all, so no metadata is fetched: the URL becomes an
- // ordinary link, exactly as the editor's own link balloon would have inserted it.
- if (mode === 'plain') {
- editor.model.change((writer) => {
- editor.model.insertContent(writer.createText(url, { linkHref: url }));
- });
- return;
- }
-
- const editorEl = editor.editing.view.getDomRoot();
- const component = glob.getComponentByEl<EditorComponent>(editorEl);
-
- const metadata = await component.fetchLinkMetadata(url);
-
- editor.model.change((writer) => {
- editor.model.insertContent(writer.createElement(mode === 'inline' ? 'linkMention' : 'linkEmbed', {
- url: metadata.url,
- // A card is an embed that declines to play: forcing "opengraph" is what tells the
- // renderer to draw the static card rather than the provider's player.
- embedType: mode === 'card' ? 'opengraph' : metadata.embedType,
- title: metadata.title,
- description: metadata.description,
- favicon: metadata.favicon,
- siteName: metadata.siteName,
- image: metadata.image
- }));
- });
- }
-
- override refresh() {
- const model = this.editor.model;
- const selection = model.document.selection;
- const firstPosition = selection.getFirstPosition();
- const allowedIn = firstPosition && model.schema.findAllowedParent(firstPosition, 'linkEmbed');
- this.isEnabled = allowedIn !== null;
- }
-}
-
-const META_KEYS = ['url', 'embedType', 'title', 'description', 'favicon', 'siteName', 'image'] as const;
-
-type MetaKey = (typeof META_KEYS)[number];
-
-const DATA_ATTR_NAMES: Record<MetaKey, string> = {
- url: 'data-url',
- embedType: 'data-embed-type',
- title: 'data-title',
- description: 'data-description',
- favicon: 'data-favicon',
- siteName: 'data-site-name',
- image: 'data-image'
-};
-
-/**
- * Builds the widget wrapper's class + `data-*` attributes from a linkEmbed/linkMention element.
- *
- * Shared by the data AND the editing downcast on purpose: a copy gesture that starts inside the
- * rendered preview (a `data-cke-ignore-events` subtree, which CKEditor's clipboard pipeline
- * deliberately ignores) is handled natively by the browser and puts the *editing* markup on the
- * clipboard. Since upcast rebuilds the widget purely from the wrapper's `data-*` attributes, any
- * metadata missing from the editing wrapper would be silently lost on paste — historically the
- * favicon and title of a copied mention.
- */
-function metadataViewAttributes(
- modelElement: { getAttribute(key: string): unknown },
- className: string,
- requiredKeys: readonly MetaKey[]
-): Record<string, string> {
- const attrs: Record<string, string> = { class: className };
- for (const key of META_KEYS) {
- const val = modelElement.getAttribute(key) as string | undefined;
- if (val || requiredKeys.includes(key)) {
- attrs[DATA_ATTR_NAMES[key]] = val as string;
- }
- }
- return attrs;
-}
-
-/** Returns the currently selected linkEmbed/linkMention element, or null. */
-function getSelectedLinkWidget(editor: any) {
- const selected = editor.model.document.selection.getSelectedElement();
- if (selected && (selected.name === 'linkMention' || selected.name === 'linkEmbed')) {
- return selected;
- }
- return null;
-}
-
-class ChangeLinkDisplayCommand extends Command {
- declare value: LinkDisplayMode | null;
- /** Whether the selected link supports embed mode (e.g. YouTube). */
- declare embedAvailable: boolean;
- /** URL of the selected link widget, exposed for the toolbar's open-link button. */
- declare url: string | null;
-
- constructor(editor: any) {
- super(editor);
- // Register as observables so CKEditor's bind().to() works.
- this.set('embedAvailable', false);
- this.set('url', null);
- }
-
- override async execute(options: { value: LinkDisplayMode }) {
- const model = this.editor.model;
- const selected = getSelectedLinkWidget(this.editor);
-
- // No widget selected means the dropdown sits in the link balloon, over a native link.
- if (!selected) {
- await this._convertNativeLink(options.value);
- return;
- }
-
- const targetMode = options.value;
- const currentMode = this._getMode(selected);
- if (targetMode === currentMode) return;
-
- // Collect all metadata from the current element.
- const attrs: Record<string, unknown> = {};
- for (const key of META_KEYS) {
- const val = selected.getAttribute(key);
- if (val != null) attrs[key] = val;
- }
-
- const url = attrs.url as string;
-
- // "Plain link" leaves the preview system: the widget becomes an ordinary link whose text is
- // the URL. Inserted as new content (not an attribute change), so AutoLinkToMention does not
- // see it and immediately convert it back. A URL we would never link to (see the isHttpUrl
- // note in refresh()) degrades to bare text instead, as the unlink button does.
- if (targetMode === 'plain') {
- model.change(writer => {
- const text = isHttpUrl(url) ? writer.createText(url, { linkHref: url }) : writer.createText(url);
- model.insertContent(text, writer.createRangeOn(selected));
- });
- return;
- }
-
- // Detect the actual embed type from the URL via the client service.
- const detectedType = this._detectEmbedType(url);
-
- model.change(writer => {
- if (targetMode === 'inline') {
- const mention = writer.createElement('linkMention', attrs);
- model.insertContent(mention, writer.createRangeOn(selected));
- } else {
- // 'card' forces opengraph; 'embed' uses detected type.
- attrs.embedType = targetMode === 'card' ? 'opengraph' : detectedType;
- const embed = writer.createElement('linkEmbed', attrs);
- model.insertContent(embed, writer.createRangeOn(selected));
- }
- });
- }
-
- override refresh() {
- const selected = getSelectedLinkWidget(this.editor);
-
- if (selected) {
- this.isEnabled = true;
- this.value = this._getMode(selected);
- const url = selected.getAttribute('url') as string;
- this.embedAvailable = this._detectEmbedType(url) !== 'opengraph';
- // Only ever hand out an http(s) URL. `url` comes from the stored `data-url`, which the
- // HTML sanitizers pass through unexamined, so a note carrying `data-url="javascript:…"`
- // would otherwise reach the toolbar's "open link" button as a live href. Withholding it
- // here disables that button (and the copy one) instead of arming them.
- this.url = isHttpUrl(url) ? url : null;
- return;
- }
-
- // A native link under the caret: the same dropdown, hosted in the link balloon this time,
- // offers to convert it into a preview. Its current display mode is by definition "plain".
- const href = this.editor.model.document.selection.getAttribute('linkHref');
- if (typeof href === 'string' && EMBEDDABLE_URL_REGEX.test(href)) {
- this.isEnabled = true;
- this.value = 'plain';
- this.embedAvailable = this._detectEmbedType(href) !== 'opengraph';
- this.url = href;
- return;
- }
-
- this.isEnabled = false;
- this.value = null;
- this.embedAvailable = false;
- this.url = null;
- }
-
- /**
- * Converts the native link under the caret — the one whose balloon toolbar hosts the dropdown —
- * into the chosen preview shape: the deliberate inverse of "Plain link". Unlike auto-detection
- * there is no gesture to interpret and no unresolved-page veto: the mode was picked outright,
- * so the conversion always happens (Ctrl+Z brings the link back), and a labeled link's display
- * text is replaced by the preview.
- */
- private async _convertNativeLink(targetMode: LinkDisplayMode) {
- const editor = this.editor;
- const model = editor.model;
- const position = model.document.selection.getFirstPosition();
- const href = model.document.selection.getAttribute('linkHref');
- /* v8 ignore next -- refresh() disables the command unless the selection carries a linkHref */
- if (typeof href !== 'string' || !position) return;
- // The link already is one.
- if (targetMode === 'plain') return;
-
- const editorEl = editor.editing.view.getDomRoot();
- const component = glob.getComponentByEl<EditorComponent>(editorEl);
-
- // The linked text is tracked as a live range: the metadata fetch reads the page server-side
- // and can take seconds, and edits made meanwhile must not shift what gets replaced.
- const liveRange = ModelLiveRange.fromRange(findAttributeRange(position, 'linkHref', href, model));
- const metadata = await component.fetchLinkMetadata(href);
- const range = liveRange.toRange();
- liveRange.detach();
-
- model.change(writer => {
- // The link may have been edited away while the fetch was in flight.
- let linkStillThere = false;
- for (const { item } of range.getWalker()) {
- if (item.is('$textProxy') && item.getAttribute('linkHref') === href) {
- linkStillThere = true;
- break;
- }
- }
- if (!linkStillThere) return;
-
- const element = writer.createElement(targetMode === 'inline' ? 'linkMention' : 'linkEmbed', {
- url: metadata.url,
- // Same rule as the widget path below: a card is an embed that declines to play.
- embedType: targetMode === 'card' ? 'opengraph'
- : targetMode === 'embed' ? this._detectEmbedType(href)
- : metadata.embedType,
- title: metadata.title,
- description: metadata.description,
- favicon: metadata.favicon,
- siteName: metadata.siteName,
- image: metadata.image
- });
-
- model.insertContent(element, range);
- // Leave the new widget selected, so its toolbar — this same dropdown included — takes
- // over from the link balloon.
- writer.setSelection(element, 'on');
- });
- }
-
- private _getMode(element: any): LinkDisplayMode {
- if (element.name === 'linkMention') return 'inline';
- const embedType = element.getAttribute('embedType') as string;
- return embedType === 'opengraph' ? 'card' : 'embed';
- }
-
- /** Delegates to the client service to avoid duplicating URL detection logic. */
- private _detectEmbedType(url: string): string {
- const editorEl = this.editor.editing.view.getDomRoot();
- const component = glob.getComponentByEl<EditorComponent>(editorEl);
- return component.detectEmbedType(url);
- }
-}
-
-class RemoveLinkEmbedCommand extends Command {
- override execute() {
- const model = this.editor.model;
- const selected = getSelectedLinkWidget(this.editor);
- if (!selected) return;
-
- const url = selected.getAttribute('url') as string;
-
- // Mirror the default link's unlink: drop the link entirely, leaving the
- // bare URL as plain (non-linked) text.
- model.change(writer => {
- model.insertContent(writer.createText(url), writer.createRangeOn(selected));
- });
- }
-
- override refresh() {
- this.isEnabled = !!getSelectedLinkWidget(this.editor);
- }
-}
-
-// ---------------------------------------------------------------------------
-// Auto-convert typed/pasted URLs to link preview widgets.
-// Piggybacks on CKEditor's AutoLink plugin: when AutoLink sets `linkHref` on
-// text whose content matches the href (i.e. a raw URL, not "[label](url)"), we
-// fetch metadata and replace it with a preview widget.
-//
-// The shape follows the gesture (see chooseLinkPreviewKind):
-// * a URL left alone on its own line — sole content of a plain paragraph, then
-// Enter — becomes a block preview: a player if the URL is embeddable
-// (YouTube), a card otherwise;
-// * anything else — text either side of it, a list/table/quote/heading, or a
-// caret still in the block because the user is mid-sentence — becomes an
-// inline linkMention.
-//
-// The user can Ctrl+Z to revert back to a plain link.
-// ---------------------------------------------------------------------------
-
-class AutoLinkToMention extends Plugin {
- /** Guard against re-entrant changes triggered by our own model writes. */
- private _converting = false;
- /** URLs that were undone — don't re-convert these. */
- private _dismissed = new Set<string>();
-
- init() {
- const editor = this.editor;
-
- editor.model.document.on('change:data', (_evt, batch) => {
- if (this._converting) return;
- if (!this._autoDetectEnabled()) return;
-
- // When the user undoes our conversion, the undo batch re-inserts
- // the original linked text. Record its URL so we don't re-convert.
- if (batch.isUndo) {
- for (const change of editor.model.document.differ.getChanges()) {
- if (change.type !== 'attribute' || change.attributeKey !== 'linkHref') continue;
- if (typeof change.attributeNewValue === 'string') {
- this._dismissed.add(change.attributeNewValue);
- }
- }
- return;
- }
-
- // Detect AutoLink setting `linkHref` on existing text (paste + Space).
- // AutoLink calls writer.setAttribute('linkHref', url, range) which
- // shows up as an attribute change, not a text insertion.
- for (const change of editor.model.document.differ.getChanges()) {
- if (change.type !== 'attribute' || change.attributeKey !== 'linkHref') continue;
- // Only react to newly added links (null → url), not modifications.
- if (change.attributeOldValue !== null) continue;
-
- const href = change.attributeNewValue as string;
- if (!EMBEDDABLE_URL_REGEX.test(href)) continue;
- if (this._dismissed.has(href)) continue;
-
- // Walk the affected range to verify the text IS the URL
- // (raw pasted URL, not a labeled link like "click here").
- for (const item of change.range.getWalker()) {
- if (!item.item.is('$textProxy')) continue;
- if (item.item.data.trim() !== href) continue;
-
- const parent = item.item.parent;
- /* v8 ignore next -- a $textProxy always has an element parent, so this guard never fires */
- if (!parent?.is('element')) continue;
-
- this._replaceWithPreview(href, parent.getPath());
- return;
- }
- }
- });
- }
-
- /**
- * Whether auto-detection is on (Options → Text Notes → Features). Consulted on every detected
- * URL rather than once at startup, so the host can supply a getter and have the option apply to
- * already-open editors. A plain boolean is honoured too, and an absent config means enabled.
- *
- * Only auto-detection is gated: inserting a preview from the toolbar dialog goes through
- * {@link InsertLinkEmbedCommand} and stays available either way.
- */
- private _autoDetectEnabled(): boolean {
- const setting = this.editor.config.get('autoLinkPreviewsEnabled') as boolean | (() => boolean) | undefined;
- return (typeof setting === 'function' ? setting() : setting) !== false;
- }
-
- private _replaceWithPreview(url: string, parentPath: number[]) {
- const editor = this.editor;
- const editorEl = editor.editing.view.getDomRoot();
- const component = glob.getComponentByEl<EditorComponent>(editorEl);
-
- component.fetchLinkMetadata(url).then((metadata: LinkEmbedMetadata) => {
- // The page told us nothing (bot challenge, network error, no title of its own): leave the
- // plain link AutoLink already created. A preview built from a hostname placeholder would
- // show strictly less than the URL it replaced.
- if (metadata.unresolved) {
- // The URL is left out on purpose — a browser console gets screenshotted and pasted
- // into bug reports too, and the link is right there in the note anyway.
- console.warn('Link preview dropped: no metadata could be read from the page (the link was kept as a plain link).');
- return;
- }
-
- // Restored in the `finally`: were a model change ever to throw, a flag left raised would
- // silently switch auto-detection off for the rest of the session.
- this._converting = true;
-
- try {
- editor.model.change((writer) => {
- const root = editor.model.document.getRoot();
- /* v8 ignore next -- the document always has a root once the editor is created */
- if (!root) return;
-
- // Re-resolve the parent from the stored path.
- let parentEl: any = root;
- for (const idx of parentPath) {
- if (!parentEl || typeof parentEl.getChild !== 'function') return;
- parentEl = parentEl.getChild(idx);
- }
- if (!parentEl || !parentEl.is('element')) return;
-
- // Find the text node that still contains the URL.
- const range = writer.createRangeIn(parentEl);
- for (const item of range.getWalker()) {
- if (!item.item.is('$textProxy')) continue;
- if (item.item.data.trim() !== url) continue;
- if (item.item.getAttribute('linkHref') !== url) continue;
-
- // Where the URL sits decides its shape. Evaluated here — at insertion time, not
- // when the URL was detected — because the metadata fetch is async and the user
- // may have kept typing meanwhile. Also before deleting anything, since deletion
- // would empty the block and make it look like the URL was never alone.
- const kind = chooseLinkPreviewKind(metadata.embedType, {
- urlAloneInBlock: isUrlAloneInBlock(this._blockChildren(parentEl), url),
- blockIsStandalone: this._isStandaloneBlock(parentEl),
- caretLeftBlock: this._caretLeftBlock(parentEl)
- });
-
- const attributes = {
- url: metadata.url,
- embedType: metadata.embedType,
- title: metadata.title,
- description: metadata.description,
- favicon: metadata.favicon,
- siteName: metadata.siteName,
- image: metadata.image
- };
-
- if (kind === 'mention') {
- const urlRange = writer.createRangeOn(item.item);
- writer.setSelection(urlRange);
- editor.model.deleteContent(editor.model.document.selection);
- editor.model.insertContent(writer.createElement('linkMention', attributes));
- return;
- }
-
- // A card or an embed takes over the whole paragraph, which by now holds nothing
- // but the URL. Swapped with writer.insert/remove rather than insertContent: the
- // caret has moved on to the next line (that is what made this a block preview in
- // the first place) and may already be mid-word, so it must not be dragged back.
- // 'card' vs 'embed' needs no branch here — the renderer keys off embedType,
- // which is "opengraph" for a card and the provider's own type for an embed.
- writer.insert(writer.createElement('linkEmbed', attributes), parentEl, 'before');
- writer.remove(parentEl);
- return;
- }
- });
- } finally {
- this._converting = false;
- }
- });
- }
-
- /**
- * True for a plain top-level paragraph — the only block a card or an embed may take over.
- * A list item is a paragraph carrying list attributes; a table cell, a quote and every other
- * container nest their paragraphs below the root; a heading is not a paragraph at all. In each
- * of those the URL keeps its inline mention, since a block preview there reads as an accident.
- */
- private _isStandaloneBlock(blockEl: any): boolean {
- if (blockEl.name !== 'paragraph') return false;
- if (blockEl.hasAttribute('listItemId')) return false;
-
- return blockEl.parent === this.editor.model.document.getRoot();
- }
-
- /**
- * True when the caret is no longer in the block — which is exactly what pressing Enter after the
- * URL does. While it is still there the user may yet type on that line, so the URL has not been
- * *left* alone and stays an inline mention.
- */
- private _caretLeftBlock(blockEl: any): boolean {
- const position = this.editor.model.document.selection.getFirstPosition();
-
- /* v8 ignore next -- the document selection always has a position */
- return position?.parent !== blockEl;
- }
-
- /**
- * Maps a model block's children to the runtime-neutral shape consumed by
- * {@link isUrlAloneInBlock}, keeping the decision logic pure and testable.
- */
- private _blockChildren(blockEl: any): BlockChildLike[] {
- const children: BlockChildLike[] = [];
- for (const child of blockEl.getChildren()) {
- const isText = child.is('$text');
- children.push({ isText, data: isText ? child.data : undefined });
- }
- return children;
- }
-}
diff --git a/packages/ckeditor5/test/link-embed-kit.ts b/packages/ckeditor5/test/link-embed-kit.ts
new file mode 100644
index 0000000000..a5ec1b42da
--- /dev/null
+++ b/packages/ckeditor5/test/link-embed-kit.ts
@@ -0,0 +1,186 @@
+import type { LinkEmbedMetadata } from "@triliumnext/commons";
+import { BlockQuote, ClassicEditor, Essentials, Heading, Link, List, Paragraph, Undo, _setModelData as setModelData } from "ckeditor5";
+import { vi } from "vitest";
+
+import LinkEmbed, { CHANGE_LINK_DISPLAY_COMMAND } from "../src/plugins/link_embed/link_embed.js";
+import { createTestEditor } from "./editor-kit.js";
+import { installGlobMock } from "./globals-test-kit.js";
+
+export { createTestEditor } from "./editor-kit.js";
+
+/**
+ * Shared fixtures for the link_embed specs: the mocked host component, the editor plugin list, and
+ * the model-manipulation helpers that simulate what AutoLink does.
+ */
+
+export const META = {
+ url: "https://example.com/",
+ // The host only ever reports "youtube" or "opengraph". It matters here that this is the real
+ // thing: chooseLinkPreviewKind() treats anything other than "opengraph" as embeddable, so a made-up
+ // type would send a URL standing alone in its block down the block-embed path instead of the mention one.
+ embedType: "opengraph",
+ title: "Example title",
+ description: "Some description",
+ favicon: "https://example.com/favicon.ico",
+ siteName: "Example",
+ image: "https://example.com/image.png"
+} satisfies LinkEmbedMetadata;
+
+export interface LinkEmbedComponentMocks {
+ triggerCommand: ReturnType<typeof vi.fn>;
+ renderLinkEmbed: ReturnType<typeof vi.fn>;
+ renderLinkMention: ReturnType<typeof vi.fn>;
+ fetchLinkMetadata: ReturnType<typeof vi.fn>;
+ detectEmbedType: ReturnType<typeof vi.fn>;
+}
+
+/**
+ * Installs the glob mock every link_embed editor resolves its host component from, and returns the
+ * individual mocks for assertions. Call from `beforeEach`, before creating the editor.
+ */
+export function installLinkEmbedComponentMock(): LinkEmbedComponentMocks {
+ const mocks: LinkEmbedComponentMocks = {
+ triggerCommand: vi.fn(),
+ renderLinkEmbed: vi.fn(),
+ renderLinkMention: vi.fn(),
+ fetchLinkMetadata: vi.fn(async (url: string) => ({ ...META, url })),
+ // YouTube-like URLs => "youtube" (embeddable); everything else => "opengraph".
+ detectEmbedType: vi.fn((url: string) => (url.includes("youtube") ? "youtube" : "opengraph"))
+ };
+
+ installGlobMock({
+ getComponentByEl: () => mocks
+ });
+
+ return mocks;
+}
+
+/**
+ * The plugin list the link_embed specs build their editors from. Heading, List and BlockQuote are
+ * loaded so the placement rules (which keep a URL inline inside a heading, list item, table cell or
+ * quote) can be exercised against a real schema.
+ */
+export const LINK_EMBED_TEST_PLUGINS = [Essentials, Paragraph, Heading, List, BlockQuote, Link, Undo, LinkEmbed];
+
+/**
+ * Editor config entries the host supplies but the CKEditor config type does not declare — the host
+ * sets them through the same kind of cast (see the client's `buildConfig`).
+ */
+export function hostConfig(entries: Record<string, unknown>): Parameters<typeof createTestEditor>[1] {
+ return entries as Parameters<typeof createTestEditor>[1];
+}
+
+export function changeCommand(editor: ClassicEditor): {
+ isEnabled: boolean;
+ value: string | null;
+ embedAvailable: boolean;
+ url: string | null;
+} {
+ const command = editor.commands.get(CHANGE_LINK_DISPLAY_COMMAND);
+ if (!command) {
+ throw new Error("changeLinkDisplay command is not registered.");
+ }
+ return command as unknown as { isEnabled: boolean; value: string | null; embedAvailable: boolean; url: string | null };
+}
+
+export function findElement(editor: ClassicEditor, name: string) {
+ const root = editor.model.document.getRoot();
+ if (!root) {
+ return undefined;
+ }
+ const range = editor.model.createRangeIn(root);
+ for (const item of range.getWalker()) {
+ if (item.item.is("element", name)) {
+ return item.item;
+ }
+ }
+ return undefined;
+}
+
+/**
+ * Sets up `modelData` and then, in a separate change, applies `linkHref` to the text node holding
+ * `href` — exactly what AutoLink does. Where `modelData` leaves the caret *is* the gesture under
+ * test: still inside the URL's block (the user typed a space and may keep going), or in the block
+ * after it (the user pressed Enter, which splits the paragraph and carries the caret onward).
+ */
+export function autoLinkIn(editor: ClassicEditor, modelData: string, href: string): void {
+ setModelData(editor.model, modelData);
+
+ editor.model.change((writer) => {
+ const root = editor.model.document.getRoot();
+ if (!root) {
+ throw new Error("Expected a document root.");
+ }
+
+ for (const item of writer.createRangeIn(root).getWalker()) {
+ if (!item.item.is("$textProxy")) continue;
+
+ // AutoLink links the URL itself, not the whole text node it happens to share with the
+ // words around it — so link exactly the URL's slice of the node.
+ const index = item.item.data.indexOf(href);
+ if (index < 0) continue;
+
+ const parent = item.item.parent;
+ if (!parent || !parent.is("element") || item.item.startOffset === null) continue;
+
+ const start = item.item.startOffset + index;
+ writer.setAttribute("linkHref", href, writer.createRange(
+ writer.createPositionAt(parent, start),
+ writer.createPositionAt(parent, start + href.length)
+ ));
+ return;
+ }
+
+ throw new Error(`No text node holds ${href}.`);
+ });
+}
+
+/** The model data for a URL left alone on its own line, with the caret carried to the next one. */
+export function urlLeftAloneOnItsOwnLine(url: string): string {
+ return `<paragraph>${url}</paragraph><paragraph>[]</paragraph>`;
+}
+
+/**
+ * Inserts text into the paragraph and applies a `linkHref` attribute to it via a
+ * writer change (null -> url), exactly as CKEditor's AutoLink plugin does when a
+ * raw URL is pasted/typed. This drives the `AutoLinkToMention` `change:data` listener.
+ * The caret is left in the block, as it is when the user types a space after the URL.
+ */
+export function addLinkedText(editor: ClassicEditor, href: string, text = href): void {
+ // First insert the plain text in its own batch.
+ setModelData(editor.model, `<paragraph>${text}[]</paragraph>`);
+ // Then, in a SEPARATE change, apply the linkHref attribute (null -> url).
+ // AutoLink does exactly this, producing an attribute diff (not a text insert)
+ // which is what AutoLinkToMention listens for.
+ editor.model.change((writer) => {
+ const paragraph = editor.model.document.getRoot()?.getChild(0);
+ if (!paragraph?.is("element")) {
+ throw new Error("Expected a paragraph block.");
+ }
+ writer.setAttribute("linkHref", href, writer.createRangeIn(paragraph));
+ });
+}
+
+/**
+ * Lets the `fetchLinkMetadata().then(...)` chain resolve and the resulting model change apply.
+ * A task turn is awaited rather than a fixed number of microtasks: the latter is a guess at the
+ * chain's depth that silently under-waits, which makes a conversion test fail and — worse — makes a
+ * test asserting that NO conversion happened pass for the wrong reason.
+ */
+export async function flushFetch(): Promise<void> {
+ await new Promise((resolve) => setTimeout(resolve, 0));
+}
+
+/**
+ * Replaces the fetch mock's implementation with one that hangs until the returned resolver is
+ * called, so a test can interleave model edits between the fetch starting and resolving.
+ */
+export function useDeferredFetch(fetchLinkMetadata: ReturnType<typeof vi.fn>) {
+ let resolveFetch: (metadata: LinkEmbedMetadata) => void = () => {};
+ fetchLinkMetadata.mockImplementation(
+ () => new Promise<LinkEmbedMetadata>((resolve) => {
+ resolveFetch = resolve;
+ })
+ );
+ return { resolveFetch: (metadata: LinkEmbedMetadata) => resolveFetch(metadata) };
+}