Skip to content

Build your personal knowledge base with Trilium Notes

chore(text): pass link preview services through editor config

Elian Doran5c3617f6845f
diff --git a/.claude/skills/ckeditor5-testing/references/patterns.md b/.claude/skills/ckeditor5-testing/references/patterns.md
index dcad434ffd..fb909729b6 100644
--- a/.claude/skills/ckeditor5-testing/references/patterns.md
+++ b/.claude/skills/ckeditor5-testing/references/patterns.md
@@ -35,9 +35,15 @@ standalone packages (and legacy specs mid-migration) still hand-roll the scaffol
## Stubbing the Trilium glue (`glob` / `navigator.clipboard` / jQuery `$`)
-Many in-aggregate plugins reach for a global `glob` (the Trilium bridge — typed in
-`packages/ckeditor5/src/augmentation.ts` with `getComponentByEl`, `getReferenceLinkTitle`,
-`getReferenceLinkTitleSync`, `getActiveContextNote`, `getHeaders`), some buttons hit
+Host services that need no component come through the editor config, so a spec passes them to
+`createTestEditor( plugins, { … } )` instead of mocking `glob`: `formatDateTime` (date/time),
+`referenceLink: { getTitle, getTitleSync }` (reference links) and `linkEmbed` (link previews —
+`createLinkEmbedHost()` in `test/link-embed-kit.ts` builds the mocked entry). Each falls back to a
+placeholder when left out, so a spec that does not assert on it can omit it.
+
+Many in-aggregate plugins still reach for a global `glob` (the Trilium bridge — typed in
+`packages/ckeditor5/src/augmentation.ts` with `getComponentByEl`, `getActiveContextNote`,
+`getHeaders`, `getLocalUpload`), some buttons hit
`navigator.clipboard`, and some converters call jQuery `$(...)` (e.g. the `editingDowncast`
converter in `packages/ckeditor5/src/plugins/referencelink.ts`). Use the globals kit
(`test/globals-test-kit.ts`) so each stub **tears itself down** after the test — never hand-roll
diff --git a/apps/client/src/widgets/type_widgets/text/CKEditor.tsx b/apps/client/src/widgets/type_widgets/text/CKEditor.tsx
index 272a11e695..8dad20d8f9 100644
--- a/apps/client/src/widgets/type_widgets/text/CKEditor.tsx
+++ b/apps/client/src/widgets/type_widgets/text/CKEditor.tsx
@@ -8,7 +8,6 @@ import { useEffect, useImperativeHandle, useRef, useState } from "preact/hooks";
import froca from "../../../services/froca";
import link from "../../../services/link";
-import linkEmbedService, { type EmbedMetadata } from "../../../services/link_embed";
import { useKeyboardShortcuts, useLegacyImperativeHandlers, useNoteContext, useSyncedRef, useTriliumOption, useTriliumOptionBool } from "../../react/hooks";
import type { AiNoteLocation } from "./ai_assistant_stream";
import { useAiMenuFooter, useAiQuickActions } from "./ai_quick_actions";
@@ -133,6 +132,8 @@ export default function CKEditor({ containerRef: externalContainerRef, contentLa
// note would name whichever one happened to be open when the editor was built.
const noteLocationRef = useRef<AiNoteLocation | null>(null);
noteLocationRef.current = note ? { title: note.title, notePath } : null;
+ const noteIdRef = useRef<string | undefined>(undefined);
+ noteIdRef.current = note?.noteId;
useKeyboardShortcuts("text-detail", containerRef, parentComponent, ntxId);
@@ -252,26 +253,6 @@ export default function CKEditor({ containerRef: externalContainerRef, contentLa
) {
await link.loadReferenceLinkTitle($el, href, note?.noteId, storedTitle);
},
- async fetchLinkMetadata(url: string) {
- // The preview's pictures are stored as attachments of the note being edited, so there
- // is nothing to fetch into before the note context has resolved one. Answering as
- // unresolved leaves the URL a plain link, which is what the editor does with any
- // preview it could not build.
- if (!note) {
- return linkEmbedService.unresolvedMetadata(url);
- }
-
- return await linkEmbedService.fetchMetadata(url, note.noteId);
- },
- detectEmbedType(url: string) {
- return linkEmbedService.detectEmbedType(url);
- },
- renderLinkEmbed(container: HTMLElement, metadata: EmbedMetadata) {
- linkEmbedService.renderEmbedPreview(container, metadata, true);
- },
- renderLinkMention(container: HTMLElement, metadata: EmbedMetadata) {
- linkEmbedService.renderMentionPreview(container, metadata, true);
- }
});
async function destroyEditor() {
@@ -303,7 +284,8 @@ export default function CKEditor({ containerRef: externalContainerRef, contentLa
uiLanguage: uiLanguage as DISPLAYABLE_LOCALE_IDS,
contentLanguage: contentLanguage ?? null,
templates: templatesRef.current,
- getNoteLocation: () => noteLocationRef.current
+ getNoteLocation: () => noteLocationRef.current,
+ getNoteId: () => noteIdRef.current
});
if (isStale) {
diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsx
index 42c306d208..6fd9b10ab5 100644
--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx
+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx
@@ -47,7 +47,6 @@ import { enterContentEmbed, getContentEmbedTools } from "./content_embed_tools";
import { useEmbedEditors } from "./editable_embed";
import EmbedHistories from "./embed_history";
import getTemplates, { updateTemplateCache } from "./snippets.js";
-import linkEmbedService from "../../../services/link_embed";
import { usesClassicToolbar } from "./toolbar";
import {
getAttachmentHref,
@@ -339,20 +338,6 @@ export default function EditableText({
copyTabReference: () => void copyReference(copyTabReference),
getContentEmbedTools,
enterContentEmbed,
- // Link preview functionality. The insert flow itself lives in the editor (a balloon form),
- // so the host only has to supply the metadata and the rendering.
- async fetchLinkMetadata(url: string) {
- return await linkEmbedService.fetchMetadata(url, note.noteId);
- },
- detectEmbedType(url: string) {
- return linkEmbedService.detectEmbedType(url);
- },
- renderLinkEmbed(container, metadata, editable) {
- linkEmbedService.renderEmbedPreview(container, metadata, editable);
- },
- renderLinkMention(container, metadata, editable) {
- linkEmbedService.renderMentionPreview(container, metadata, editable);
- },
// Keyboard shortcut
async followLinkUnderCursorCommand() {
const editor = await waitForEditor();
diff --git a/apps/client/src/widgets/type_widgets/text/config.spec.ts b/apps/client/src/widgets/type_widgets/text/config.spec.ts
index 62a9b6c909..e8134f4cef 100644
--- a/apps/client/src/widgets/type_widgets/text/config.spec.ts
+++ b/apps/client/src/widgets/type_widgets/text/config.spec.ts
@@ -94,6 +94,10 @@ vi.mock("../../../services/dialog.js", () => ({
}));
vi.mock("@triliumnext/highlightjs", () => ({ default: { name: "hljs-stub" } }));
vi.mock("../../../services/math.js", () => ({ default: { name: "katex-stub" } }));
+vi.mock("../../../services/link_embed.js", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../../../services/link_embed.js")>()),
+ fetchMetadata: vi.fn(async (url: string, ownerNoteId: string) => ({ url, embedType: "opengraph", title: ownerNoteId }))
+}));
function baseOpts(overrides: Partial<BuildEditorOptions> = {}): BuildEditorOptions {
return {
@@ -347,6 +351,18 @@ describe("CK config - tables", () => {
expect(formatDateTime?.(date)).toBe("25.09.2026 10:30");
});
+ it("fetches link previews for the open note, and none without one", async () => {
+ let noteId: string | undefined = "noteAbc";
+ const linkEmbed = (await buildConfig(baseOpts({ getNoteId: () => noteId }))).linkEmbed;
+
+ expect(await linkEmbed?.fetchMetadata?.("https://a.example/"))
+ .toStrictEqual({ url: "https://a.example/", embedType: "opengraph", title: "noteAbc" });
+
+ noteId = undefined;
+ expect(await linkEmbed?.fetchMetadata?.("https://a.example/")).toMatchObject({ unresolved: true });
+ expect(linkEmbed?.detectEmbedType?.("https://youtube.com/watch?v=abc12345678")).toBe("youtube");
+ });
+
it("titles reference links through the link service", async () => {
expect((await buildConfig(baseOpts())).referenceLink).toStrictEqual({
getTitle: linkService.getReferenceLinkTitle,
diff --git a/apps/client/src/widgets/type_widgets/text/config.ts b/apps/client/src/widgets/type_widgets/text/config.ts
index 259851c133..f2752ed29b 100644
--- a/apps/client/src/widgets/type_widgets/text/config.ts
+++ b/apps/client/src/widgets/type_widgets/text/config.ts
@@ -1,4 +1,4 @@
-import { type EditorConfig, getCkLocale, SnippetDefinition, type TextTransformationConfig } from "@triliumnext/ckeditor5";
+import { type EditorConfig, getCkLocale, type LinkEmbedHost, SnippetDefinition, type TextTransformationConfig } from "@triliumnext/ckeditor5";
import emojiDefinitionsUrl from "@triliumnext/ckeditor5/src/emoji_definitions/en.json?url";
import { ALLOWED_PROTOCOLS, DISPLAYABLE_LOCALE_IDS, formatShortcut, IMAGE_UPLOAD_SUBTYPES, joinShortcut, KATEX_MACROS, MIME_TYPE_AUTO, normalizeMimeTypeForCKEditor } from "@triliumnext/commons";
import i18next from "i18next";
@@ -9,6 +9,7 @@ import { t } from "../../../services/i18n.js";
import imageService from "../../../services/image.js";
import { getNoteImageSourceToLoad } from "../../../services/image_urls.js";
import linkService from "../../../services/link.js";
+import { detectEmbedType, fetchMetadata, renderEmbedPreview, renderMentionPreview, unresolvedMetadata } from "../../../services/link_embed.js";
import { default as mimeTypesService, getHighlightJsNameForMime } from "../../../services/mime_types.js";
import options from "../../../services/options.js";
import { sanitizeNoteContentHtml } from "../../../services/sanitize_content.js";
@@ -47,6 +48,8 @@ export interface BuildEditorOptions {
* here would name the note that happened to be open when it was built.
*/
getNoteLocation?: AiNoteLocationProvider;
+ /** The ID of the note the editor is open on. A getter for the same reason as `getNoteLocation`. */
+ getNoteId?: () => string | undefined;
}
export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfig> {
@@ -203,6 +206,7 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfi
getTitle: linkService.getReferenceLinkTitle,
getTitleSync: linkService.getReferenceLinkTitleSync
},
+ linkEmbed: buildLinkEmbedHost(opts.getNoteId),
slashCommand: {
// Drop CKEditor's built-in list slash commands, whose Title Case titles the palette
// re-defines in sentence case.
@@ -340,6 +344,21 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfi
};
}
+/** The link preview services of the editor, for the note `getNoteId()` names. */
+function buildLinkEmbedHost(getNoteId?: () => string | undefined): LinkEmbedHost {
+ return {
+ async fetchMetadata(url) {
+ // The pictures of a preview are stored as attachments of the note being edited, so
+ // without a note the URL stays a plain link, as for any preview that cannot be built.
+ const noteId = getNoteId?.();
+ return noteId ? await fetchMetadata(url, noteId) : unresolvedMetadata(url);
+ },
+ detectEmbedType,
+ renderEmbed: renderEmbedPreview,
+ renderMention: renderMentionPreview
+ };
+}
+
/**
* Which as-you-type replacements the editor runs, expressed as deltas against CKEditor's own default
* set rather than by restating it.
diff --git a/packages/ckeditor5/src/augmentation.ts b/packages/ckeditor5/src/augmentation.ts
index 604a33df98..33a4d92901 100644
--- a/packages/ckeditor5/src/augmentation.ts
+++ b/packages/ckeditor5/src/augmentation.ts
@@ -181,15 +181,6 @@ declare global {
* attachment, or `null` when that fails. Hosts without drawings leave it out.
*/
convertImageToDrawing?(src: string): Promise<string | null>;
- /**
- * Reads a page's preview metadata through the host. Never rejects: any failure — network
- * error, HTTP error, unparseable page — resolves as `{ unresolved: true }` with
- * hostname-derived placeholders, so callers branch on `unresolved` instead of catching.
- */
- fetchLinkMetadata(url: string): Promise<LinkEmbedMetadata>;
- detectEmbedType(url: string): string;
- renderLinkEmbed(container: HTMLElement, metadata: LinkEmbedMetadata, editable?: boolean): void;
- renderLinkMention(container: HTMLElement, metadata: Pick<LinkEmbedMetadata, "url" | "title" | "favicon">, editable?: boolean): void;
}
type LocalUpload = NonNullable<StandaloneApi["localUpload"]>;
diff --git a/packages/ckeditor5/src/index.ts b/packages/ckeditor5/src/index.ts
index edd6f51320..1acd03cc56 100644
--- a/packages/ckeditor5/src/index.ts
+++ b/packages/ckeditor5/src/index.ts
@@ -36,6 +36,7 @@ export type { ToolbarGroupMenuEntry, ToolbarGroupMenuHost, ToolbarGroupMenuItem,
export type { default as TextFormattingToolbar } from "./plugins/text_formatting_toolbar.js";
export type { default as ContextToolbar } from "./plugins/context_toolbar.js";
export type { default as MobileToolbarItems } from "./plugins/mobile_toolbar_items.js";
+export type { LinkEmbedHost } from "./plugins/link_embed/link_embed_commands.js";
export type { ColorMenuHost, ColorMenuRequest, ColorMenuTarget } from "./plugins/color_menu.js";
export { default as TriliumSnippets } from "./plugins/snippets/snippets.js";
export type { SnippetDefinition } from "./plugins/snippets/snippetsconfig.js";
diff --git a/packages/ckeditor5/src/plugins/content_embed/content_embed.spec.ts b/packages/ckeditor5/src/plugins/content_embed/content_embed.spec.ts
index 616bbb4968..f42bf17a0c 100644
--- a/packages/ckeditor5/src/plugins/content_embed/content_embed.spec.ts
+++ b/packages/ckeditor5/src/plugins/content_embed/content_embed.spec.ts
@@ -388,9 +388,7 @@ describe("ContentEmbed", () => {
installGlobMock({
getComponentByEl: () => ({
triggerCommand,
- loadEmbeddedNote,
- renderLinkMention: vi.fn(),
- detectEmbedType: vi.fn(() => "opengraph")
+ loadEmbeddedNote
})
});
const linkEditor = await createTestEditor([
diff --git a/packages/ckeditor5/src/plugins/content_embed/content_embed_toolbar.spec.ts b/packages/ckeditor5/src/plugins/content_embed/content_embed_toolbar.spec.ts
index 47a07e44ff..d3169809d8 100644
--- a/packages/ckeditor5/src/plugins/content_embed/content_embed_toolbar.spec.ts
+++ b/packages/ckeditor5/src/plugins/content_embed/content_embed_toolbar.spec.ts
@@ -219,19 +219,7 @@ describe("isContentEmbedWidget — real non-include-note widgets", () => {
const loadEmbeddedNote = vi.fn();
installGlobMock({
getComponentByEl: () => ({
- loadEmbeddedNote,
- renderLinkEmbed: vi.fn(),
- renderLinkMention: vi.fn(),
- fetchLinkMetadata: async () => ({
- url: "https://example.com",
- embedType: "opengraph",
- title: "Example",
- description: "",
- favicon: "",
- siteName: "",
- image: ""
- }),
- detectEmbedType: () => "opengraph"
+ loadEmbeddedNote
})
});
diff --git a/packages/ckeditor5/src/plugins/context_toolbar.spec.ts b/packages/ckeditor5/src/plugins/context_toolbar.spec.ts
index f86479523c..ee1fa94379 100644
--- a/packages/ckeditor5/src/plugins/context_toolbar.spec.ts
+++ b/packages/ckeditor5/src/plugins/context_toolbar.spec.ts
@@ -8,7 +8,6 @@ import bxPencil from "boxicons/svg/regular/bx-pencil.svg?raw";
import { describe, expect, it, vi } from "vitest";
import { createTestEditor } from "../../test/editor-kit.js";
-import { installGlobMock } from "../../test/globals-test-kit.js";
import ContextToolbar from "./context_toolbar.js";
import ImagePosition from "./image_position.js";
import LinkEmbedToolbar from "./link_embed/link_embed_toolbar.js";
@@ -406,7 +405,6 @@ describe("ContextToolbar", () => {
});
it("names the toolbar of a link preview after the link it is", async () => {
- installGlobMock({ getComponentByEl: () => ({ renderLinkMention: vi.fn(), detectEmbedType: () => "opengraph" }) });
const editor = await createTestEditor([Essentials, Paragraph, LinkEmbedToolbar, ContextToolbar], {
toolbar: ["contextToolbar"]
});
diff --git a/packages/ckeditor5/src/plugins/find_in_link_widgets.spec.ts b/packages/ckeditor5/src/plugins/find_in_link_widgets.spec.ts
index 3777559946..3269dfc358 100644
--- a/packages/ckeditor5/src/plugins/find_in_link_widgets.spec.ts
+++ b/packages/ckeditor5/src/plugins/find_in_link_widgets.spec.ts
@@ -28,20 +28,6 @@ describe("FindInLinkWidgets", () => {
element.textContent = "Reference match";
}
return Promise.resolve();
- }),
- renderLinkEmbed: vi.fn((container: HTMLElement, metadata: LinkEmbedMetadata) => {
- if (metadata.embedType === "youtube") {
- return;
- }
- appendText(
- container,
- metadata.title,
- metadata.description,
- metadata.siteName || safeHostname(metadata.url)
- );
- }),
- renderLinkMention: vi.fn((container: HTMLElement, metadata: LinkEmbedMetadata) => {
- appendText(container, metadata.title || safeHostname(metadata.url));
})
})
});
@@ -58,6 +44,22 @@ describe("FindInLinkWidgets", () => {
referenceLink: {
getTitle: vi.fn(async () => "Reference match"),
getTitleSync: vi.fn(() => "Reference match")
+ },
+ linkEmbed: {
+ renderEmbed: vi.fn((container: HTMLElement, metadata: LinkEmbedMetadata) => {
+ if (metadata.embedType === "youtube") {
+ return;
+ }
+ appendText(
+ container,
+ metadata.title,
+ metadata.description,
+ metadata.siteName || safeHostname(metadata.url)
+ );
+ }),
+ renderMention: vi.fn((container: HTMLElement, metadata: LinkEmbedMetadata) => {
+ appendText(container, metadata.title || safeHostname(metadata.url));
+ })
}
});
});
diff --git a/packages/ckeditor5/src/plugins/link_embed/link_embed.spec.ts b/packages/ckeditor5/src/plugins/link_embed/link_embed.spec.ts
index dfc5f406c1..6959ae5725 100644
--- a/packages/ckeditor5/src/plugins/link_embed/link_embed.spec.ts
+++ b/packages/ckeditor5/src/plugins/link_embed/link_embed.spec.ts
@@ -1,7 +1,7 @@
-import type { ClassicEditor } from "ckeditor5";
+import { _setModelData as setModelData, 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 { createLinkEmbedHost, createTestEditor, findElement, 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";
@@ -9,8 +9,7 @@ describe("LinkEmbed", () => {
let editor: ClassicEditor;
beforeEach(async () => {
- installLinkEmbedComponentMock();
- editor = await createTestEditor(LINK_EMBED_TEST_PLUGINS);
+ editor = await createTestEditor(LINK_EMBED_TEST_PLUGINS, { linkEmbed: createLinkEmbedHost() });
});
it("loads the plugin, registers the commands and the toolbar button", () => {
@@ -20,4 +19,21 @@ describe("LinkEmbed", () => {
expect(editor.commands.get(REMOVE_LINK_EMBED_COMMAND)).toBeDefined();
expect(editor.ui.componentFactory.has("linkEmbed")).toBe(true);
});
+
+ it("shows previews as their title or URL, and inserts unresolved cards, without linkEmbed", async () => {
+ const plainEditor = await createTestEditor(LINK_EMBED_TEST_PLUGINS);
+ setModelData(plainEditor.model, "<paragraph>"
+ + "<linkMention url=\"https://a.example/\" title=\"A\"></linkMention>"
+ + "<linkMention url=\"https://b.example/\"></linkMention>[]</paragraph>"
+ + "<linkEmbed url=\"https://c.example/\" embedType=\"opengraph\"></linkEmbed>");
+
+ const domRoot = plainEditor.editing.view.getDomRoot();
+ expect([ ...domRoot?.querySelectorAll(".link-mention-inner") ?? [] ].map((el) => el.textContent))
+ .toEqual([ "A", "https://b.example/" ]);
+ expect(domRoot?.querySelector(".link-embed-preview-wrapper")?.textContent).toBe("https://c.example/");
+
+ setModelData(plainEditor.model, "<paragraph>[]</paragraph>");
+ await plainEditor.execute(LINK_EMBED_COMMAND, { url: "https://youtube.com/watch?v=x", mode: "embed" });
+ expect(findElement(plainEditor, "linkEmbed")?.getAttribute("embedType")).toBe("opengraph");
+ });
});
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
index 69c81282c4..31cb5f5008 100644
--- a/packages/ckeditor5/src/plugins/link_embed/link_embed_autodetect.spec.ts
+++ b/packages/ckeditor5/src/plugins/link_embed/link_embed_autodetect.spec.ts
@@ -4,26 +4,28 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import {
addLinkedText,
autoLinkIn,
+ createLinkEmbedHost,
createTestEditor,
findElement,
flushFetch,
hostConfig,
- installLinkEmbedComponentMock,
LINK_EMBED_TEST_PLUGINS,
META,
urlLeftAloneOnItsOwnLine,
useDeferredFetch,
- type LinkEmbedComponentMocks
+ type LinkEmbedHostMocks
} from "../../../test/link-embed-kit.js";
import { LINK_EMBED_COMMAND } from "./link_embed_commands.js";
describe("AutoLinkToMention", () => {
let editor: ClassicEditor;
- let fetchLinkMetadata: LinkEmbedComponentMocks["fetchLinkMetadata"];
+ let host: LinkEmbedHostMocks;
+ let fetchMetadata: LinkEmbedHostMocks["fetchMetadata"];
beforeEach(async () => {
- ({ fetchLinkMetadata } = installLinkEmbedComponentMock());
- editor = await createTestEditor(LINK_EMBED_TEST_PLUGINS);
+ host = createLinkEmbedHost();
+ ({ fetchMetadata } = host);
+ editor = await createTestEditor(LINK_EMBED_TEST_PLUGINS, { linkEmbed: host });
});
it("converts a bare linked URL into a linkMention after fetching metadata", async () => {
@@ -32,7 +34,7 @@ describe("AutoLinkToMention", () => {
await flushFetch();
- expect(fetchLinkMetadata).toHaveBeenCalledWith(url);
+ expect(fetchMetadata).toHaveBeenCalledWith(url);
const mention = findElement(editor, "linkMention");
expect(mention).toBeDefined();
expect(mention?.getAttribute("url")).toBe(url);
@@ -41,13 +43,13 @@ describe("AutoLinkToMention", () => {
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 });
+ fetchMetadata.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(fetchMetadata).toHaveBeenCalledWith(url);
expect(findElement(editor, "linkMention")).toBeUndefined();
expect(findElement(editor, "linkEmbed")).toBeUndefined();
// The link AutoLink created is still there, as plain linked text.
@@ -62,13 +64,13 @@ describe("AutoLinkToMention", () => {
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 }));
+ editor = await createTestEditor(LINK_EMBED_TEST_PLUGINS, hostConfig({ linkEmbed: host, 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(fetchMetadata).not.toHaveBeenCalled();
expect(findElement(editor, "linkMention")).toBeUndefined();
expect(editor.getData()).toContain(`<a href="${url}">${url}</a>`);
@@ -79,7 +81,7 @@ describe("AutoLinkToMention", () => {
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 }));
+ editor = await createTestEditor(LINK_EMBED_TEST_PLUGINS, hostConfig({ linkEmbed: host, autoLinkPreviewsEnabled: () => enabled }));
addLinkedText(editor, "https://example.com/off");
await flushFetch();
@@ -102,7 +104,7 @@ describe("AutoLinkToMention", () => {
/** 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" });
+ fetchMetadata.mockResolvedValueOnce({ ...META, url, embedType: "youtube" });
}
it("turns a URL left alone on its own line into a card", async () => {
@@ -164,7 +166,7 @@ describe("AutoLinkToMention", () => {
});
it("leaves the caret where the user moved it, even if they typed while the fetch was in flight", async () => {
- const { resolveFetch } = useDeferredFetch(fetchLinkMetadata);
+ const { resolveFetch } = useDeferredFetch(fetchMetadata);
autoLinkIn(editor, urlLeftAloneOnItsOwnLine(PLAIN_URL), PLAIN_URL);
// The user carries on typing on the new line while the metadata is still being fetched.
@@ -189,7 +191,7 @@ describe("AutoLinkToMention", () => {
});
it("does not drag the caret back when an inline mention lands mid-typing", async () => {
- const { resolveFetch } = useDeferredFetch(fetchLinkMetadata);
+ const { resolveFetch } = useDeferredFetch(fetchMetadata);
// Text beside the URL makes this a mention; the caret has already moved to the next line.
autoLinkIn(editor, `<paragraph>see ${PLAIN_URL}</paragraph><paragraph>[]</paragraph>`, PLAIN_URL);
@@ -221,7 +223,7 @@ describe("AutoLinkToMention", () => {
await flushFetch();
expect(findElement(editor, "linkMention")).toBeUndefined();
- expect(fetchLinkMetadata).not.toHaveBeenCalled();
+ expect(fetchMetadata).not.toHaveBeenCalled();
});
it("ignores non-http(s) links that fail the embeddable URL regex", async () => {
@@ -230,7 +232,7 @@ describe("AutoLinkToMention", () => {
await flushFetch();
expect(findElement(editor, "linkMention")).toBeUndefined();
- expect(fetchLinkMetadata).not.toHaveBeenCalled();
+ expect(fetchMetadata).not.toHaveBeenCalled();
});
it("skips non-text items in the affected range before reaching the URL text", async () => {
@@ -256,7 +258,7 @@ describe("AutoLinkToMention", () => {
await flushFetch();
- expect(fetchLinkMetadata).toHaveBeenCalledWith(url);
+ expect(fetchMetadata).toHaveBeenCalledWith(url);
expect(findElement(editor, "linkMention")).toBeDefined();
});
@@ -274,7 +276,7 @@ describe("AutoLinkToMention", () => {
editor.execute("undo");
await flushFetch();
- expect(fetchLinkMetadata).not.toHaveBeenCalled();
+ expect(fetchMetadata).not.toHaveBeenCalled();
});
it("records the URL on undo and does not re-convert it afterwards", async () => {
@@ -301,7 +303,7 @@ describe("AutoLinkToMention", () => {
addLinkedText(editor, url);
await flushFetch();
- expect(fetchLinkMetadata).not.toHaveBeenCalled();
+ expect(fetchMetadata).not.toHaveBeenCalled();
expect(findElement(editor, "linkMention")).toBeUndefined();
});
@@ -320,7 +322,7 @@ describe("AutoLinkToMention", () => {
await flushFetch();
expect(findElement(editor, "linkMention")).toBeUndefined();
- expect(fetchLinkMetadata).not.toHaveBeenCalled();
+ expect(fetchMetadata).not.toHaveBeenCalled();
});
// The following tests exercise the defensive re-resolution guards in
@@ -328,7 +330,7 @@ describe("AutoLinkToMention", () => {
// 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 { resolveFetch } = useDeferredFetch(fetchMetadata);
const url = "https://example.com/gone";
// The URL lives in the SECOND paragraph (stored parent path [1]).
@@ -356,7 +358,7 @@ describe("AutoLinkToMention", () => {
});
it("bails out when an intermediate path segment no longer resolves", async () => {
- const { resolveFetch } = useDeferredFetch(fetchLinkMetadata);
+ const { resolveFetch } = useDeferredFetch(fetchMetadata);
const url = "https://example.com/nested";
// Nest the URL two block-quotes deep so the stored parent path has depth 3
@@ -390,7 +392,7 @@ describe("AutoLinkToMention", () => {
});
it("skips non-matching text and bails when the URL text lost its linkHref", async () => {
- const { resolveFetch } = useDeferredFetch(fetchLinkMetadata);
+ const { resolveFetch } = useDeferredFetch(fetchMetadata);
const url = "https://example.com/edited";
// Paragraph holds a non-matching text node followed by the URL text. Only the
diff --git a/packages/ckeditor5/src/plugins/link_embed/link_embed_autodetect.ts b/packages/ckeditor5/src/plugins/link_embed/link_embed_autodetect.ts
index 62835fa20a..0e40f88e34 100644
--- a/packages/ckeditor5/src/plugins/link_embed/link_embed_autodetect.ts
+++ b/packages/ckeditor5/src/plugins/link_embed/link_embed_autodetect.ts
@@ -1,6 +1,6 @@
import { chooseLinkPreviewKind, isUrlAloneInBlock, type BlockChildLike } from '@triliumnext/commons';
import { Plugin } from 'ckeditor5';
-import { EMBEDDABLE_URL_REGEX } from './link_embed_commands.js';
+import { EMBEDDABLE_URL_REGEX, getLinkEmbedHost } from './link_embed_commands.js';
/**
* Auto-converts typed/pasted URLs to link preview widgets.
@@ -86,10 +86,8 @@ export default class AutoLinkToMention extends Plugin {
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) => {
+ getLinkEmbedHost(editor).fetchMetadata(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.
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
index 514b11ff0e..2a6036e4a5 100644
--- a/packages/ckeditor5/src/plugins/link_embed/link_embed_commands.spec.ts
+++ b/packages/ckeditor5/src/plugins/link_embed/link_embed_commands.spec.ts
@@ -3,22 +3,23 @@ import { beforeEach, describe, expect, it } from "vitest";
import {
changeCommand,
+ createLinkEmbedHost,
createTestEditor,
findElement,
- installLinkEmbedComponentMock,
LINK_EMBED_TEST_PLUGINS,
META,
- type LinkEmbedComponentMocks
+ type LinkEmbedHostMocks
} from "../../../test/link-embed-kit.js";
import { CHANGE_LINK_DISPLAY_COMMAND, CHANGE_LINK_PREVIEW_TITLE_COMMAND, LINK_EMBED_COMMAND, REMOVE_LINK_EMBED_COMMAND } from "./link_embed_commands.js";
describe("LinkEmbed commands", () => {
let editor: ClassicEditor;
- let fetchLinkMetadata: LinkEmbedComponentMocks["fetchLinkMetadata"];
+ let fetchMetadata: LinkEmbedHostMocks["fetchMetadata"];
beforeEach(async () => {
- ({ fetchLinkMetadata } = installLinkEmbedComponentMock());
- editor = await createTestEditor(LINK_EMBED_TEST_PLUGINS);
+ const host = createLinkEmbedHost();
+ ({ fetchMetadata } = host);
+ editor = await createTestEditor(LINK_EMBED_TEST_PLUGINS, { linkEmbed: host });
});
// -----------------------------------------------------------------------
@@ -33,7 +34,7 @@ describe("LinkEmbed commands", () => {
// 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);
+ expect(fetchMetadata).toHaveBeenCalledWith(url);
const mention = findElement(editor, "linkMention");
expect(mention?.getAttribute("url")).toBe(url);
expect(mention?.getAttribute("description")).toBe(META.description);
@@ -43,7 +44,7 @@ describe("LinkEmbed commands", () => {
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" });
+ fetchMetadata.mockResolvedValue({ ...META, url, embedType: "youtube" });
setModelData(editor.model, "<paragraph>[]</paragraph>");
await editor.execute(LINK_EMBED_COMMAND, { url, mode: "card" });
@@ -61,7 +62,7 @@ describe("LinkEmbed commands", () => {
await editor.execute(LINK_EMBED_COMMAND, { url, mode: "plain" });
- expect(fetchLinkMetadata).not.toHaveBeenCalled();
+ expect(fetchMetadata).not.toHaveBeenCalled();
expect(findElement(editor, "linkMention")).toBeUndefined();
expect(findElement(editor, "linkEmbed")).toBeUndefined();
expect(editor.getData()).toBe(`<p><a href="${url}">${url}</a></p>`);
@@ -169,7 +170,7 @@ describe("LinkEmbed commands", () => {
// 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();
+ expect(fetchMetadata).not.toHaveBeenCalled();
// A block preview converts the same way, gaining a wrapping paragraph.
setModelData(editor.model, '[<linkEmbed url="https://e.com/" embedType="opengraph"></linkEmbed>]');
@@ -326,7 +327,7 @@ describe("LinkEmbed commands", () => {
await editor.execute(CHANGE_LINK_DISPLAY_COMMAND, { value: "inline" });
- expect(fetchLinkMetadata).toHaveBeenCalledWith(url);
+ expect(fetchMetadata).toHaveBeenCalledWith(url);
const mention = findElement(editor, "linkMention");
expect(mention?.getAttribute("url")).toBe(url);
expect(mention?.getAttribute("title")).toBe(META.title);
@@ -340,7 +341,7 @@ describe("LinkEmbed commands", () => {
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" }));
+ fetchMetadata.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" });
@@ -359,14 +360,14 @@ describe("LinkEmbed commands", () => {
await editor.execute(CHANGE_LINK_DISPLAY_COMMAND, { value: "plain" });
- expect(fetchLinkMetadata).not.toHaveBeenCalled();
+ expect(fetchMetadata).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; }));
+ fetchMetadata.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>;
@@ -382,7 +383,7 @@ describe("LinkEmbed commands", () => {
it("does not convert when the link was repointed at a different URL while the metadata was being fetched", async () => {
const url = "https://example.com/";
let resolveFetch: (meta: unknown) => void = () => {};
- fetchLinkMetadata.mockReturnValue(new Promise((resolve) => { resolveFetch = resolve; }));
+ fetchMetadata.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>;
@@ -402,7 +403,7 @@ describe("LinkEmbed commands", () => {
it("still converts when the linked text survives behind an inserted element and a repointed prefix", async () => {
const url = "https://example.com/";
let resolveFetch: (meta: unknown) => void = () => {};
- fetchLinkMetadata.mockReturnValue(new Promise((resolve) => { resolveFetch = resolve; }));
+ fetchMetadata.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>;
diff --git a/packages/ckeditor5/src/plugins/link_embed/link_embed_commands.ts b/packages/ckeditor5/src/plugins/link_embed/link_embed_commands.ts
index 094d3f7191..46112e263a 100644
--- a/packages/ckeditor5/src/plugins/link_embed/link_embed_commands.ts
+++ b/packages/ckeditor5/src/plugins/link_embed/link_embed_commands.ts
@@ -1,5 +1,5 @@
import { isHttpUrl } from '@triliumnext/commons';
-import { Command, findAttributeRange, ModelLiveRange } from 'ckeditor5';
+import { Command, type Editor, findAttributeRange, ModelLiveRange } from 'ckeditor5';
export const LINK_EMBED_COMMAND = 'insertLinkEmbed';
export const CHANGE_LINK_DISPLAY_COMMAND = 'changeLinkDisplay';
@@ -75,10 +75,7 @@ export class InsertLinkEmbedCommand extends Command {
return;
}
- const editorEl = editor.editing.view.getDomRoot();
- const component = glob.getComponentByEl<EditorComponent>(editorEl);
-
- const metadata = await component.fetchLinkMetadata(url);
+ const metadata = await getLinkEmbedHost(editor).fetchMetadata(url);
editor.model.change((writer) => {
editor.model.insertContent(writer.createElement(mode === 'inline' ? 'linkMention' : 'linkEmbed', {
@@ -219,13 +216,10 @@ export class ChangeLinkDisplayCommand extends Command {
// 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 metadata = await getLinkEmbedHost(editor).fetchMetadata(href);
const range = liveRange.toRange();
liveRange.detach();
@@ -266,11 +260,9 @@ export class ChangeLinkDisplayCommand extends Command {
return embedType === 'opengraph' ? 'card' : 'embed';
}
- /** Delegates to the client service to avoid duplicating URL detection logic. */
+ /** Delegates to the host 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);
+ return getLinkEmbedHost(this.editor).detectEmbedType(url);
}
}
@@ -364,3 +356,43 @@ function getSelectedLinkWidget(editor: any) {
}
return null;
}
+
+/**
+ * The link preview services of the `linkEmbed` config entry. A service the host leaves out falls
+ * back to a placeholder: metadata that is unresolved, the `opengraph` type, and a preview that
+ * shows the title or the URL as text.
+ */
+export function getLinkEmbedHost(editor: Editor): LinkEmbedHost {
+ return { ...FALLBACK_HOST, ...editor.config.get('linkEmbed') };
+}
+
+/** The services the host provides for link previews, through the `linkEmbed` config entry. */
+export interface LinkEmbedHost {
+ /**
+ * Reads a page's preview metadata. Never rejects: any failure (network error, HTTP error,
+ * unparseable page) resolves as `{ unresolved: true }` with hostname-derived placeholders, so
+ * callers branch on `unresolved` instead of catching.
+ */
+ fetchMetadata(url: string): Promise<LinkEmbedMetadata>;
+ /** The kind of preview `url` supports: `opengraph` for a card, anything else for a player. */
+ detectEmbedType(url: string): string;
+ renderEmbed(container: HTMLElement, metadata: LinkEmbedMetadata, editable?: boolean): void;
+ renderMention(container: HTMLElement, metadata: Pick<LinkEmbedMetadata, 'url' | 'title' | 'favicon'>, editable?: boolean): void;
+}
+
+const FALLBACK_HOST: LinkEmbedHost = {
+ fetchMetadata: async (url) => ({ url, embedType: 'opengraph', unresolved: true }),
+ detectEmbedType: () => 'opengraph',
+ renderEmbed: renderAsText,
+ renderMention: renderAsText
+};
+
+function renderAsText(container: HTMLElement, { url, title }: Pick<LinkEmbedMetadata, 'url' | 'title'>) {
+ container.textContent = title || url;
+}
+
+declare module 'ckeditor5' {
+ interface EditorConfig {
+ linkEmbed?: Partial<LinkEmbedHost>;
+ }
+}
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
index f74d4864cf..10446245b2 100644
--- a/packages/ckeditor5/src/plugins/link_embed/link_embed_editing.spec.ts
+++ b/packages/ckeditor5/src/plugins/link_embed/link_embed_editing.spec.ts
@@ -1,16 +1,17 @@
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";
+import { createLinkEmbedHost, createTestEditor, LINK_EMBED_TEST_PLUGINS, type LinkEmbedHostMocks } from "../../../test/link-embed-kit.js";
describe("LinkEmbedEditing", () => {
let editor: ClassicEditor;
- let renderLinkEmbed: LinkEmbedComponentMocks["renderLinkEmbed"];
- let renderLinkMention: LinkEmbedComponentMocks["renderLinkMention"];
+ let renderEmbed: LinkEmbedHostMocks["renderEmbed"];
+ let renderMention: LinkEmbedHostMocks["renderMention"];
beforeEach(async () => {
- ({ renderLinkEmbed, renderLinkMention } = installLinkEmbedComponentMock());
- editor = await createTestEditor(LINK_EMBED_TEST_PLUGINS);
+ const host = createLinkEmbedHost();
+ ({ renderEmbed, renderMention } = host);
+ editor = await createTestEditor(LINK_EMBED_TEST_PLUGINS, { linkEmbed: host });
});
// -----------------------------------------------------------------------
@@ -52,8 +53,8 @@ describe("LinkEmbedEditing", () => {
}
// The editing downcast UIElement callback ran and rendered the embed.
- expect(renderLinkEmbed).toHaveBeenCalled();
- const [, metadata, editable] = renderLinkEmbed.mock.calls[0];
+ expect(renderEmbed).toHaveBeenCalled();
+ const [, metadata, editable] = renderEmbed.mock.calls[0];
expect(metadata.url).toBe("https://e.com/");
expect(editable).toBe(true);
});
@@ -107,8 +108,8 @@ describe("LinkEmbedEditing", () => {
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(renderEmbed).toHaveBeenCalled();
+ const [container, metadata, editable] = renderEmbed.mock.calls[0];
expect(container).toBeInstanceOf(HTMLElement);
expect(metadata).toMatchObject({ url: "https://e.com/", embedType: "web", title: "T" });
expect(editable).toBe(true);
@@ -133,7 +134,7 @@ describe("LinkEmbedEditing", () => {
expect(mention.getAttribute("favicon")).toBe("F");
}
- expect(renderLinkMention).toHaveBeenCalled();
+ expect(renderMention).toHaveBeenCalled();
});
it("data-downcasts a fully-populated linkMention, omitting empty optional attributes", () => {
@@ -214,8 +215,8 @@ describe("LinkEmbedEditing", () => {
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(renderMention).toHaveBeenCalled();
+ const [container, metadata, editable] = renderMention.mock.calls[0];
expect(container).toBeInstanceOf(HTMLElement);
expect(metadata).toMatchObject({ url: "https://e.com/", title: "T", favicon: "F" });
expect(editable).toBe(true);
diff --git a/packages/ckeditor5/src/plugins/link_embed/link_embed_editing.ts b/packages/ckeditor5/src/plugins/link_embed/link_embed_editing.ts
index 359568dfa6..778cdbfc41 100644
--- a/packages/ckeditor5/src/plugins/link_embed/link_embed_editing.ts
+++ b/packages/ckeditor5/src/plugins/link_embed/link_embed_editing.ts
@@ -5,6 +5,7 @@ import {
CHANGE_LINK_PREVIEW_TITLE_COMMAND,
ChangeLinkDisplayCommand,
ChangeLinkPreviewTitleCommand,
+ getLinkEmbedHost,
InsertLinkEmbedCommand,
LINK_EMBED_COMMAND,
META_KEYS,
@@ -113,9 +114,7 @@ export default class LinkEmbedEditing extends Plugin {
'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);
+ getLinkEmbedHost(editor).renderEmbed(domElement, { url, embedType, title, description, favicon, siteName, image }, true);
preventCKEditorHandling(domElement, editor);
return domElement;
});
@@ -175,9 +174,7 @@ export default class LinkEmbedEditing extends Plugin {
'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);
+ getLinkEmbedHost(editor).renderMention(domElement, { url, title, favicon }, true);
preventCKEditorHandling(domElement, editor);
return domElement;
});
diff --git a/packages/ckeditor5/src/plugins/link_embed/link_embed_form.spec.ts b/packages/ckeditor5/src/plugins/link_embed/link_embed_form.spec.ts
index 805423b482..771aef4e1f 100644
--- a/packages/ckeditor5/src/plugins/link_embed/link_embed_form.spec.ts
+++ b/packages/ckeditor5/src/plugins/link_embed/link_embed_form.spec.ts
@@ -2,7 +2,6 @@ import { BlockQuote, ClassicEditor, ContextualBalloon, Essentials, Link, Paragra
import { beforeEach, describe, expect, it, vi } from "vitest";
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";
@@ -18,23 +17,20 @@ const META = {
describe("LinkEmbedFormView", () => {
let editor: ClassicEditor;
- let fetchLinkMetadata: ReturnType<typeof vi.fn>;
+ let fetchMetadata: ReturnType<typeof vi.fn>;
beforeEach(async () => {
- fetchLinkMetadata = vi.fn(async (url: string) => ({ ...META, url }));
-
- installGlobMock({
- getComponentByEl: () => ({
- triggerCommand: vi.fn(),
- renderLinkEmbed: vi.fn(),
- renderLinkMention: vi.fn(),
- fetchLinkMetadata,
+ fetchMetadata = vi.fn(async (url: string) => ({ ...META, url }));
+
+ editor = await createTestEditor([Essentials, Paragraph, BlockQuote, Link, Undo, LinkEmbed], {
+ linkEmbed: {
+ renderEmbed: vi.fn(),
+ renderMention: vi.fn(),
+ fetchMetadata,
// YouTube-like URLs are embeddable; everything else is not.
detectEmbedType: (url: string) => (url.includes("youtube") ? "youtube" : "opengraph")
- })
+ }
});
-
- editor = await createTestEditor([Essentials, Paragraph, BlockQuote, Link, Undo, LinkEmbed]);
setModelData(editor.model, "<paragraph>[]</paragraph>");
});
@@ -170,7 +166,7 @@ describe("LinkEmbedFormView", () => {
form.fire("submit");
await vi.waitFor(() => expect(isInBalloon(form)).toBe(false));
- expect(fetchLinkMetadata).toHaveBeenCalledWith("https://example.com/article");
+ expect(fetchMetadata).toHaveBeenCalledWith("https://example.com/article");
expect(editor.getData()).toContain('data-url="https://example.com/article"');
// Reopening starts blank rather than showing the last URL.
@@ -186,7 +182,7 @@ describe("LinkEmbedFormView", () => {
form.fire("submit");
await vi.waitFor(() => expect(isInBalloon(form)).toBe(false));
- expect(fetchLinkMetadata).toHaveBeenCalledWith("https://example.com/article");
+ expect(fetchMetadata).toHaveBeenCalledWith("https://example.com/article");
});
it("does nothing when submitted with an empty URL", () => {
@@ -194,7 +190,7 @@ describe("LinkEmbedFormView", () => {
form.fire("submit");
- expect(fetchLinkMetadata).not.toHaveBeenCalled();
+ expect(fetchMetadata).not.toHaveBeenCalled();
expect(isInBalloon(form)).toBe(true);
});
@@ -204,13 +200,13 @@ describe("LinkEmbedFormView", () => {
form.fire("submit");
- expect(fetchLinkMetadata).not.toHaveBeenCalled();
+ expect(fetchMetadata).not.toHaveBeenCalled();
expect(isInBalloon(form)).toBe(true);
});
it("disables the form while the metadata is being fetched, so it cannot be submitted twice", async () => {
let resolveFetch: ((metadata: unknown) => void) | undefined;
- fetchLinkMetadata.mockImplementation(() => new Promise((resolve) => {
+ fetchMetadata.mockImplementation(() => new Promise((resolve) => {
resolveFetch = resolve;
}));
@@ -224,7 +220,7 @@ describe("LinkEmbedFormView", () => {
// A second Enter while the first fetch is in flight must not fetch again.
form.fire("submit");
- expect(fetchLinkMetadata).toHaveBeenCalledTimes(1);
+ expect(fetchMetadata).toHaveBeenCalledTimes(1);
resolveFetch?.({ ...META, url: "https://example.com/article" });
await vi.waitFor(() => expect(isInBalloon(form)).toBe(false));
@@ -243,7 +239,7 @@ describe("LinkEmbedFormView", () => {
form.keystrokes.press({ keyCode: 27, preventDefault: () => {}, stopPropagation: () => {} } as unknown as KeyboardEvent);
expect(isInBalloon(form)).toBe(false);
- expect(fetchLinkMetadata).not.toHaveBeenCalled();
+ expect(fetchMetadata).not.toHaveBeenCalled();
expect(editor.getData()).toBe(before);
});
@@ -271,7 +267,7 @@ describe("LinkEmbedFormView", () => {
document.body.dispatchEvent(new MouseEvent("mousedown", { bubbles: true }));
expect(isInBalloon(form)).toBe(false);
- expect(fetchLinkMetadata).not.toHaveBeenCalled();
+ expect(fetchMetadata).not.toHaveBeenCalled();
});
it("does not stack a second form when the button is clicked twice", () => {
diff --git a/packages/ckeditor5/src/plugins/link_embed/link_embed_toolbar.spec.ts b/packages/ckeditor5/src/plugins/link_embed/link_embed_toolbar.spec.ts
index 530865ae51..f17057fe36 100644
--- a/packages/ckeditor5/src/plugins/link_embed/link_embed_toolbar.spec.ts
+++ b/packages/ckeditor5/src/plugins/link_embed/link_embed_toolbar.spec.ts
@@ -2,7 +2,6 @@ import { ClassicEditor, ContextualBalloon, Essentials, Link, Paragraph, WidgetTo
import { beforeEach, describe, expect, it, vi } from "vitest";
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 LinkEmbedTitleFormView from "./link_embed_title_form.js";
import LinkEmbedToolbar from "./link_embed_toolbar.js";
@@ -77,23 +76,6 @@ describe("LinkEmbedToolbar", () => {
let editor: ClassicEditor;
beforeEach(async () => {
- installGlobMock({
- getComponentByEl: () => ({
- renderLinkEmbed: vi.fn(),
- renderLinkMention: vi.fn(),
- fetchLinkMetadata: async () => ({
- url: "https://example.com",
- embedType: "opengraph",
- title: "Example",
- description: "",
- favicon: "",
- siteName: "",
- image: ""
- }),
- detectEmbedType: () => "opengraph"
- })
- });
-
editor = await createTestEditor([Essentials, Paragraph, Link, LinkEmbed, LinkEmbedToolbar]);
});
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
index accd89e88e..621b11d8ca 100644
--- a/packages/ckeditor5/src/plugins/link_embed/link_embed_ui.spec.ts
+++ b/packages/ckeditor5/src/plugins/link_embed/link_embed_ui.spec.ts
@@ -1,7 +1,7 @@
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 { createLinkEmbedHost, createTestEditor, 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";
@@ -9,8 +9,7 @@ describe("LinkEmbedUI", () => {
let editor: ClassicEditor;
beforeEach(async () => {
- installLinkEmbedComponentMock();
- editor = await createTestEditor(LINK_EMBED_TEST_PLUGINS);
+ editor = await createTestEditor(LINK_EMBED_TEST_PLUGINS, { linkEmbed: createLinkEmbedHost() });
});
it("binds the button to the insert command and opens the balloon form on click", () => {
diff --git a/packages/ckeditor5/src/plugins/link_embed/link_embed_ui.ts b/packages/ckeditor5/src/plugins/link_embed/link_embed_ui.ts
index 4bfc700984..c1d942771b 100644
--- a/packages/ckeditor5/src/plugins/link_embed/link_embed_ui.ts
+++ b/packages/ckeditor5/src/plugins/link_embed/link_embed_ui.ts
@@ -1,7 +1,7 @@
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 { LINK_EMBED_COMMAND } from './link_embed_commands.js';
+import { getLinkEmbedHost, LINK_EMBED_COMMAND } from './link_embed_commands.js';
import LinkEmbedFormView from './link_embed_form.js';
/**
@@ -167,7 +167,5 @@ function normalizeUrl(rawUrl: string): string | null {
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);
+ return getLinkEmbedHost(editor).detectEmbedType(normalizeUrl(url) ?? url);
}
diff --git a/packages/ckeditor5/test/link-embed-kit.ts b/packages/ckeditor5/test/link-embed-kit.ts
index a5ec1b42da..d6095d6e64 100644
--- a/packages/ckeditor5/test/link-embed-kit.ts
+++ b/packages/ckeditor5/test/link-embed-kit.ts
@@ -4,13 +4,12 @@ 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.
+ * Shared fixtures for the link_embed specs: the mocked `linkEmbed` config entry, the editor plugin
+ * list, and the model-manipulation helpers that simulate what AutoLink does.
*/
export const META = {
@@ -26,33 +25,25 @@ export const META = {
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>;
+export interface LinkEmbedHostMocks {
+ renderEmbed: ReturnType<typeof vi.fn>;
+ renderMention: ReturnType<typeof vi.fn>;
+ fetchMetadata: 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.
+ * A mocked `linkEmbed` config entry, to pass to the editor as `{ linkEmbed: host }` and to assert
+ * on.
*/
-export function installLinkEmbedComponentMock(): LinkEmbedComponentMocks {
- const mocks: LinkEmbedComponentMocks = {
- triggerCommand: vi.fn(),
- renderLinkEmbed: vi.fn(),
- renderLinkMention: vi.fn(),
- fetchLinkMetadata: vi.fn(async (url: string) => ({ ...META, url })),
+export function createLinkEmbedHost(): LinkEmbedHostMocks {
+ return {
+ renderEmbed: vi.fn(),
+ renderMention: vi.fn(),
+ fetchMetadata: 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;
}
/**
@@ -162,7 +153,7 @@ export function addLinkedText(editor: ClassicEditor, href: string, text = href):
}
/**
- * Lets the `fetchLinkMetadata().then(...)` chain resolve and the resulting model change apply.
+ * Lets the `fetchMetadata().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.
@@ -175,9 +166,9 @@ export async function flushFetch(): Promise<void> {
* 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>) {
+export function useDeferredFetch(fetchMetadata: ReturnType<typeof vi.fn>) {
let resolveFetch: (metadata: LinkEmbedMetadata) => void = () => {};
- fetchLinkMetadata.mockImplementation(
+ fetchMetadata.mockImplementation(
() => new Promise<LinkEmbedMetadata>((resolve) => {
resolveFetch = resolve;
})