Skip to content

Build your personal knowledge base with Trilium Notes

chore(text): render content embeds through editor config

Elian Doraneb13fed93290
diff --git a/.claude/skills/ckeditor5-testing/references/patterns.md b/.claude/skills/ckeditor5-testing/references/patterns.md
index 732cb3b15d..fe77778d3f 100644
--- a/.claude/skills/ckeditor5-testing/references/patterns.md
+++ b/.claude/skills/ckeditor5-testing/references/patterns.md
@@ -41,7 +41,8 @@ Host services that need no component come through the editor config, so a spec p
`createLinkEmbedHost()` in `test/link-embed-kit.ts` builds the mocked entry), and `getNoteId` plus
`attachmentUpload: { getHeaders, getLocalUpload, getEmbedBoxSize }` (uploads), and the dialogs a
button hands over to the host: `internalLink: { openDialog }`, `markdownImport: { open }`,
-`contentEmbed: { pickNote }`, `cutToNote: { cut, saveNow }`, `inlineIcon: { showPicker }`,
+`contentEmbed` (`pickNote`, the `load…` renderers, `getTools`, `enter` and the rest of
+`ContentEmbedHost`), `cutToNote: { cut, saveNow }`, `inlineIcon: { showPicker }`,
`blockReference: { openHandleMenu, copyReference }` and `tabs: { copyReference }`. Each falls
back to a placeholder or a no-op when left out (an upload without `getNoteId` is rejected), so
a spec that does not assert on it can omit it. A spec sharing one editor across tests can swap
diff --git a/.claude/skills/developing-content-embeds/SKILL.md b/.claude/skills/developing-content-embeds/SKILL.md
index 126fc0dc26..f5c4d2e263 100644
--- a/.claude/skills/developing-content-embeds/SKILL.md
+++ b/.claude/skills/developing-content-embeds/SKILL.md
@@ -1,7 +1,7 @@
---
name: developing-content-embeds
description: >-
- Use when building or changing an embed in a text note — an included note, an attachment embed such as a canvas drawing (`CanvasDrawing`), or a source embed such as a Mermaid diagram (`MermaidDiagram`, `SOURCE_EMBED_TYPES`) — or adding an embed kind. Covers the storage forms (`data-note-id`, `data-attachment-id`, inline `<pre><code class="language-…">`), the editor plugin (`packages/ckeditor5/src/plugins/content_embed/`: `content_embed.ts`, `inline_source.ts`, toolbar, box-size dropdown), the host contract (`loadEmbeddedAttachment()`, `loadInlineEmbed()`), the client box (`ContentEmbed`, `text/utils.ts`), the content component contract (`useEditableEmbed()`, `ContentEmbedToolProvider`, Editable, display modes, fullscreen), reusing the note type's component as canvas and Mermaid do, the read-only paths (AI chat, Markdown preview, print, share), and traps hit (detached content, CodeMirror read-only fixed at creation, the CKEditor `:first-child` separator rule, untitled box sizes, class clashes).
+ Use when building or changing an embed in a text note — an included note, an attachment embed such as a canvas drawing (`CanvasDrawing`), or a source embed such as a Mermaid diagram (`MermaidDiagram`, `SOURCE_EMBED_TYPES`) — or adding an embed kind. Covers the storage forms (`data-note-id`, `data-attachment-id`, inline `<pre><code class="language-…">`), the editor plugin (`packages/ckeditor5/src/plugins/content_embed/`: `content_embed.ts`, `inline_source.ts`, toolbar, box-size dropdown), the host contract (`contentEmbed.loadAttachment()`, `contentEmbed.loadInline()`), the client box (`ContentEmbed`, `text/utils.ts`), the content component contract (`useEditableEmbed()`, `ContentEmbedToolProvider`, Editable, display modes, fullscreen), reusing the note type's component as canvas and Mermaid do, the read-only paths (AI chat, Markdown preview, print, share), and traps hit (detached content, CodeMirror read-only fixed at creation, the CKEditor `:first-child` separator rule, untitled box sizes, class clashes).
---
# Developing content embeds
@@ -71,10 +71,12 @@ All three carry `boxSize`, `hideTitle`, `editable`, `displayMode` (`data-box-siz
`content_embed_toolbar.ts` lists the toolbar items; `content_embed_tools.ts` turns the
content's tools into buttons; `content_embed_box_size_dropdown.ts` the size menu. The editing
view renders an `.include-note-wrapper` and asks the **host** to fill it.
-2. **Host contract** (`packages/ckeditor5/src/augmentation.ts`, implemented in
- `apps/client/src/widgets/type_widgets/text/EditableText.tsx`): `loadEmbeddedNote()`,
- `loadEmbeddedAttachment()`, `loadInlineEmbed(source, $el, boxSize, { isFocused })`,
- `focusContentEmbed()`, `openContentEmbedMenu()`. The plugin never imports client code.
+2. **Host contract** (`ContentEmbedHost` in `content_embed.ts`, read from the editor config
+ as `contentEmbed`): `loadNote()`, `loadAttachment()`,
+ `loadInline(source, wrapper, boxSize, { isFocused })`, `focusAttachment()`, `openMenu()`,
+ `getTools()`, `enter()` and `getAttachmentHref()`. `EditableText.tsx` implements them as
+ `contentEmbedHandlers`, which `CKEditor.tsx` hands to `buildConfig()` through a getter. The
+ plugin never imports client code.
3. **Box** (`text/utils.ts`). `loadEmbeddedAttachment()` / `loadInlineEmbed()` render the content
with `content_renderer`, wrap it in `ContentEmbed` (`text/ContentEmbed.tsx`: title row,
fullscreen, exit-fullscreen overlay) and `mountEmbedBox()`. Content that left the page while it
@@ -234,7 +236,7 @@ editors of one note in several tabs reload each other's saves and mix up the res
| Where | Path | What an embed gets |
|---|---|---|
-| Read-only note, AI chat replies, tool results | `ReadOnlyTextContent` (`text/ReadOnlyText.tsx`) | `applyContentEmbeds()` → `loadEmbedded*()`; `applySourceEmbeds()` → `loadInlineEmbed()` with a fixed read-only source. Same box and component as the editor. |
+| Read-only note, AI chat replies, tool results | `ReadOnlyTextContent` (`text/ReadOnlyText.tsx`) | `applyContentEmbeds()` → `loadEmbedded*()`; `applySourceEmbeds()` → `loadInlineEmbed()` (`text/utils.ts`) with a fixed read-only source. Same box and component as the editor. |
| Markdown note preview, a chat reply while streaming | `ReadOnlyTextContent` with `isChanging` | Diagrams drawn in place (`rewriteMermaidDiagramsInContainer()` + `applyInlineMermaid()`), which keep the last drawing while the next renders; a box would remount on every update. |
| Print (`glob.device === "print"`), included notes, previews | `postProcessRichContent()` in `services/content_renderer_text.ts` | Drawn in place; printing snapshots before a box would draw. |
| Share pages | server `share/content_renderer.ts`, share theme `content/mermaid.ts` | Static: the drawing's picture as `<img>`, Mermaid drawn over its code block. No box. |
diff --git a/apps/client/src/widgets/type_widgets/text/CKEditor.tsx b/apps/client/src/widgets/type_widgets/text/CKEditor.tsx
index 339bc9b7a2..3b370fa711 100644
--- a/apps/client/src/widgets/type_widgets/text/CKEditor.tsx
+++ b/apps/client/src/widgets/type_widgets/text/CKEditor.tsx
@@ -13,7 +13,7 @@ import { useKeyboardShortcuts, useLegacyImperativeHandlers, useNoteContext, useS
import IconPicker from "../../react/IconPicker";
import type { AiNoteLocation } from "./ai_assistant_stream";
import { useAiMenuFooter, useAiQuickActions } from "./ai_quick_actions";
-import { buildConfig, BuildEditorOptions } from "./config";
+import { buildConfig, BuildEditorOptions, type ContentEmbedHandlers } from "./config";
export type BoxSize = "tiny" | "small" | "medium" | "full" | "expandable";
@@ -66,9 +66,11 @@ interface CKEditorProps extends Pick<HTMLAttributes<HTMLDivElement>, "className"
/** Rebuilds the editor each time it changes, e.g. to recover from an error. */
rebuildKey?: number;
containerRef?: RefObject<HTMLDivElement | null>;
+ /** What renders the embeds of the editor and acts on them. Editors without embeds leave it out. */
+ contentEmbedHandlers?: ContentEmbedHandlers;
}
-export default function CKEditor({ containerRef: externalContainerRef, contentLanguage, className, tabIndex, isClassicEditor, editorRef: externalEditorRef, onNotificationWarning, onNotificationInfo, onEditorError, onChange, onEditorInitialized, editorApi, templates, rebuildKey }: CKEditorProps) {
+export default function CKEditor({ containerRef: externalContainerRef, contentLanguage, className, tabIndex, isClassicEditor, editorRef: externalEditorRef, onNotificationWarning, onNotificationInfo, onEditorError, onChange, onEditorInitialized, editorApi, templates, rebuildKey, contentEmbedHandlers }: CKEditorProps) {
const containerRef = useSyncedRef<HTMLDivElement>(externalContainerRef, null);
const editorRef = useRef<CKTextEditor>(null);
const stopReportingErrorsRef = useRef<() => void>(undefined);
@@ -136,6 +138,8 @@ export default function CKEditor({ containerRef: externalContainerRef, contentLa
noteLocationRef.current = note ? { title: note.title, notePath } : null;
const noteRef = useRef(note);
noteRef.current = note;
+ const contentEmbedHandlersRef = useRef(contentEmbedHandlers);
+ contentEmbedHandlersRef.current = contentEmbedHandlers;
/** The open icon picker request and its balloon container, or `null` when none is open. */
const [ iconPickerRequest, setIconPickerRequest ] = useState<IconPickerRequest | null>(null);
@@ -310,7 +314,8 @@ export default function CKEditor({ containerRef: externalContainerRef, contentLa
getNote: () => noteRef.current,
getNotePath: () => noteLocationRef.current?.notePath,
save: () => parentComponent?.triggerCommand("saveNoteDetailNow")
- }
+ },
+ getContentEmbedHandlers: () => contentEmbedHandlersRef.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 2fb7b53e68..6dec31cc32 100644
--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx
+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx
@@ -7,7 +7,6 @@ import {
CKTextEditor,
type FileUploadData,
type FileUploadEvent,
- type InlineEmbedSource,
SnippetDefinition
} from "@triliumnext/ckeditor5";
import { deferred, formatBlockRange, parseBlockRange } from "@triliumnext/commons";
@@ -35,6 +34,7 @@ import { convertImageToDrawing } from "../canvas/image_to_drawing";
import { TypeWidgetProps } from "../type_widget";
import AttachmentSaves, { InlineSourceSaves, useNoteEditor } from "./attachment_saves";
import CKEditor, { CKEditorApi, NotificationEventData, NotificationEventInfo } from "./CKEditor";
+import type { ContentEmbedHandlers } from "./config";
import { enterContentEmbed, getContentEmbedTools } from "./content_embed_tools";
import { useEmbedEditors } from "./editable_embed";
import EmbedHistories from "./embed_history";
@@ -209,6 +209,40 @@ export default function EditableText({
editor.editing.view.focus();
});
+ const contentEmbedHandlers: ContentEmbedHandlers = {
+ loadNote(noteId, wrapper, boxSize, embedBlock, onEmbedBlockChange) {
+ void loadEmbeddedNote(noteId, $(wrapper), boxSize, {
+ noteEditor: embedNoteEditor,
+ histories,
+ block: embedBlock,
+ onBlockChange: onEmbedBlockChange
+ });
+ },
+ loadAttachment(attachmentId, wrapper, boxSize) {
+ const isFocused = focusedAttachmentIdRef.current === attachmentId;
+ if (isFocused) {
+ focusedAttachmentIdRef.current = undefined;
+ }
+ void loadEmbeddedAttachment(attachmentId, $(wrapper), boxSize, {
+ attachmentEditor: embedAttachmentEditor,
+ histories,
+ isFocused
+ });
+ },
+ loadInline(source, wrapper, boxSize, options) {
+ void loadInlineEmbed(source, $(wrapper), boxSize, {
+ ...options, saves: inlineSourceSaves, histories
+ });
+ },
+ focusAttachment(attachmentId) {
+ focusedAttachmentIdRef.current = attachmentId;
+ },
+ getAttachmentHref,
+ openMenu: (embed, anchor) => void openContentEmbedMenu(embed, anchor),
+ getTools: getContentEmbedTools,
+ enter: enterContentEmbed
+ };
+
useLegacyImperativeHandlers({
addLinkToTextCommand() {
if (!editorApiRef.current) return;
@@ -244,51 +278,9 @@ export default function EditableText({
sizeEditable: true
});
},
- loadEmbeddedNote(
- noteId: string,
- $el: JQuery<HTMLElement>,
- boxSize?: string,
- embedBlock?: string,
- onBlockChange?: (block: string) => void
- ) {
- return loadEmbeddedNote(noteId, $el, boxSize, {
- noteEditor: embedNoteEditor,
- histories,
- block: embedBlock,
- onBlockChange
- });
- },
- loadEmbeddedAttachment(attachmentId: string, $el: JQuery<HTMLElement>, boxSize?: string) {
- const isFocused = focusedAttachmentIdRef.current === attachmentId;
- if (isFocused) {
- focusedAttachmentIdRef.current = undefined;
- }
- return loadEmbeddedAttachment(attachmentId, $el, boxSize, {
- attachmentEditor: embedAttachmentEditor,
- histories,
- isFocused
- });
- },
- loadInlineEmbed(
- source: InlineEmbedSource,
- $el: JQuery<HTMLElement>,
- boxSize: string | undefined,
- options: { isFocused: boolean }
- ) {
- return loadInlineEmbed(source, $el, boxSize, {
- ...options, saves: inlineSourceSaves, histories
- });
- },
- focusContentEmbed(attachmentId: string) {
- focusedAttachmentIdRef.current = attachmentId;
- },
convertImageToDrawing(src: string) {
return convertImageToDrawing(note.noteId, src, parentComponent?.componentId);
},
- getAttachmentHref,
- openContentEmbedMenu,
- getContentEmbedTools,
- enterContentEmbed,
// Keyboard shortcut
async followLinkUnderCursorCommand() {
const editor = await waitForEditor();
@@ -524,6 +516,7 @@ export default function EditableText({
onNotificationInfo={onNotificationInfo}
onEditorError={(error) => reportEditorError(error, reloadEditor)}
rebuildKey={editorRebuildKey}
+ contentEmbedHandlers={contentEmbedHandlers}
onChange={() => {
spacedUpdate.scheduleUpdate();
const editor = editorRef.current;
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 d33c2bef88..f80371430d 100644
--- a/apps/client/src/widgets/type_widgets/text/config.spec.ts
+++ b/apps/client/src/widgets/type_widgets/text/config.spec.ts
@@ -1,4 +1,4 @@
-import type { EditorConfig } from "@triliumnext/ckeditor5";
+import type { EditorConfig, InlineEmbedSource } from "@triliumnext/ckeditor5";
import { DISPLAYABLE_LOCALE_IDS, IMAGE_MIMES, LOCALES, SANITIZER_DEFAULT_ALLOWED_TAGS } from "@triliumnext/commons";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
@@ -433,6 +433,53 @@ describe("CK config - tables", () => {
expect(bare.tabs).toBeUndefined();
});
+ it("hands embeds to the content embed handlers of the moment, and falls back without any", async () => {
+ const tools = { getTools: () => [], execute: vi.fn(), subscribe: () => () => {} };
+ const first = {
+ loadNote: vi.fn(),
+ loadAttachment: vi.fn(),
+ loadInline: vi.fn(),
+ focusAttachment: vi.fn(),
+ getAttachmentHref: vi.fn(async () => "#root/n1?viewMode=attachments&attachmentId=a1"),
+ openMenu: vi.fn(),
+ getTools: vi.fn(() => tools),
+ enter: vi.fn(() => true)
+ };
+ const second = { ...first, loadNote: vi.fn() };
+ let handlers: typeof first | undefined = first;
+ const embed = document.createElement("figure");
+ const wrapper = document.createElement("div");
+ const source = {} as InlineEmbedSource;
+ const onBlockChange = vi.fn();
+ const host = (await buildConfig(baseOpts({ getContentEmbedHandlers: () => handlers })))
+ .contentEmbed;
+
+ host?.loadNote?.("n1", wrapper, "small", "b1", onBlockChange);
+ handlers = second;
+ host?.loadNote?.("n2", wrapper, undefined, undefined, onBlockChange);
+ host?.loadAttachment?.("a1", wrapper, "medium");
+ host?.loadInline?.(source, wrapper, "full", { isFocused: true });
+ host?.focusAttachment?.("a1");
+ host?.openMenu?.(embed, wrapper);
+
+ expect(first.loadNote).toHaveBeenCalledExactlyOnceWith("n1", wrapper, "small", "b1", onBlockChange);
+ expect(second.loadNote).toHaveBeenCalledExactlyOnceWith("n2", wrapper, undefined, undefined, onBlockChange);
+ expect(first.loadAttachment).toHaveBeenCalledWith("a1", wrapper, "medium");
+ expect(first.loadInline).toHaveBeenCalledWith(source, wrapper, "full", { isFocused: true });
+ expect(first.focusAttachment).toHaveBeenCalledWith("a1");
+ expect(first.openMenu).toHaveBeenCalledWith(embed, wrapper);
+ expect(await host?.getAttachmentHref?.("a1")).toBe("#root/n1?viewMode=attachments&attachmentId=a1");
+ expect(host?.getTools?.(embed)).toBe(tools);
+ expect(host?.enter?.(embed, "end")).toBe(true);
+ expect(first.enter).toHaveBeenCalledWith(embed, "end");
+
+ handlers = undefined;
+ expect(await host?.getAttachmentHref?.("a1")).toBeNull();
+ expect(host?.getTools?.(embed)).toBeNull();
+ expect(host?.enter?.(embed, "start")).toBe(false);
+ expect(() => host?.loadNote?.("n1", wrapper, undefined, undefined, onBlockChange)).not.toThrow();
+ });
+
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 eae9789a7a..9d46b81ddd 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 AttachmentUploadHost, type EditorConfig, getCkLocale, type IconPickerRequest, type LinkEmbedHost, SnippetDefinition, type TextTransformationConfig } from "@triliumnext/ckeditor5";
+import { type AttachmentUploadHost, type ContentEmbedHost, type EditorConfig, getCkLocale, type IconPickerRequest, 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";
@@ -62,8 +62,17 @@ export interface BuildEditorOptions {
showIconPicker?: (request: IconPickerRequest) => (() => void) | null;
/** The note that the block and tab references the editor copies point to. */
referenceSource?: ReferenceSource;
+ /**
+ * What renders the embeds of the editor and acts on them. A getter: the handlers hold the
+ * state of the component that hosts the editor, which changes as it renders.
+ */
+ getContentEmbedHandlers?: () => ContentEmbedHandlers | undefined;
}
+/** The members of `contentEmbed` that the component hosting the editor implements. */
+export type ContentEmbedHandlers =
+ Omit<ContentEmbedHost, "pickNote" | "inlineLanguages" | "renderInlinePreview">;
+
export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfig> {
// `undefined` when the AI features are off or no LLM provider is configured. Decided once:
// it both disables the assistant's command and keeps its entries off the toolbar.
@@ -95,7 +104,8 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfi
inlineLanguages: SOURCE_EMBED_TYPES.map((type) => type.language),
renderInlinePreview: (language, source, container) => {
void getSourceEmbedTypeByLanguage(language)?.renderPreview(source, container);
- }
+ },
+ ...bindContentEmbedHandlers(opts.getContentEmbedHandlers)
},
image: {
styles: {
@@ -367,6 +377,23 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfi
};
}
+/** The `contentEmbed` members that call the handlers `getHandlers()` returns at the time. */
+function bindContentEmbedHandlers(
+ getHandlers: () => ContentEmbedHandlers | undefined = () => undefined
+): ContentEmbedHandlers {
+ return {
+ loadNote: (...args) => getHandlers()?.loadNote(...args),
+ loadAttachment: (...args) => getHandlers()?.loadAttachment(...args),
+ loadInline: (...args) => getHandlers()?.loadInline(...args),
+ focusAttachment: (attachmentId) => getHandlers()?.focusAttachment(attachmentId),
+ getAttachmentHref: async (attachmentId) =>
+ (await getHandlers()?.getAttachmentHref(attachmentId)) ?? null,
+ openMenu: (embed, anchor) => getHandlers()?.openMenu(embed, anchor),
+ getTools: (embed) => getHandlers()?.getTools(embed) ?? null,
+ enter: (embed, edge) => getHandlers()?.enter(embed, edge) ?? false
+ };
+}
+
/** A callback that triggers `command` on the component that hosts the editor, and waits for it. */
function bindHostCommand(opts: BuildEditorOptions, command: CommandNames) {
return async () => {
diff --git a/packages/ckeditor5/src/augmentation.ts b/packages/ckeditor5/src/augmentation.ts
index e98ce865ea..20cde65b20 100644
--- a/packages/ckeditor5/src/augmentation.ts
+++ b/packages/ckeditor5/src/augmentation.ts
@@ -1,7 +1,5 @@
import "ckeditor5";
-import type { InlineEmbedSource } from "./plugins/content_embed/inline_source.js";
-
declare global {
interface LinkEmbedMetadata {
url: string;
@@ -91,54 +89,6 @@ declare global {
* starting from `storedTitle`, and calls `fix()` with the new href.
*/
fixReferenceLink?(storedTitle: string, fix: (href: string) => void): void;
- /**
- * Fills an embed with the note, or with the `block` of it, a `block` link parameter. An
- * editor of those blocks calls `onBlockChange()` once the blocks at its edges change.
- */
- loadEmbeddedNote(
- noteId: string,
- $el: JQuery<HTMLElement>,
- boxSize?: string,
- block?: string,
- onBlockChange?: (block: string) => void
- ): void;
- loadEmbeddedAttachment(
- attachmentId: string,
- $el: JQuery<HTMLElement>,
- boxSize?: string
- ): void;
- /**
- * Fills an embed box with what `source` shows, for an embed that keeps its content in the
- * note. Hosts without such embeds leave it out.
- */
- loadInlineEmbed?(
- source: InlineEmbedSource,
- $el: JQuery<HTMLElement>,
- boxSize: string | undefined,
- options: { isFocused: boolean }
- ): void;
- /** The href of a reference link to the attachment, or `null` once it is deleted. */
- getAttachmentHref(attachmentId: string): Promise<string | null>;
- /**
- * Opens the context menu of what `embed` shows, below `anchor`. Hosts without embeds
- * leave it out.
- */
- openContentEmbedMenu?(embed: HTMLElement, anchor: HTMLElement): void;
- /**
- * The buttons that what `embed` shows adds to the toolbar of the embed, or `null`. Hosts
- * without embeds leave it out.
- */
- getContentEmbedTools?(embed: HTMLElement): ContentEmbedToolProvider | null;
- /**
- * Focuses the editor that `embed` shows, with the caret at `edge` of its content, and
- * returns whether it did. Hosts without embeds leave it out.
- */
- enterContentEmbed?(embed: HTMLElement, edge: "start" | "end"): boolean;
- /**
- * Gives the focus to what the embed of the attachment shows, once it renders. Hosts
- * without embeds leave it out.
- */
- focusContentEmbed?(attachmentId: string): void;
/**
* Attaches a drawing canvas that shows the image at `src`, and answers with the ID of its
* attachment, or `null` when that fails. Hosts without drawings leave it out.
diff --git a/packages/ckeditor5/src/index.ts b/packages/ckeditor5/src/index.ts
index c2d12c609a..fd43af7215 100644
--- a/packages/ckeditor5/src/index.ts
+++ b/packages/ckeditor5/src/index.ts
@@ -27,6 +27,7 @@ export type {
EmbedHistoryEntry, EmbedHistoryStep
} from "./plugins/content_embed/embed_history.js";
export type { InlineEmbedSource } from "./plugins/content_embed/inline_source.js";
+export type { ContentEmbedHost } from "./plugins/content_embed/content_embed.js";
export type { AttachmentLinkChange } from "./plugins/referencelink.js";
export { getLinkAtSelection, replaceLinkAtSelection } from "./plugins/internallink.js";
export type { default as TriliumEmojiMention, EmojiSuggestion } from "./plugins/mention/emoji_mention.js";
diff --git a/packages/ckeditor5/src/plugins/containers/container_keyboard.spec.ts b/packages/ckeditor5/src/plugins/containers/container_keyboard.spec.ts
index ad905a3d5e..232ec30c8f 100644
--- a/packages/ckeditor5/src/plugins/containers/container_keyboard.spec.ts
+++ b/packages/ckeditor5/src/plugins/containers/container_keyboard.spec.ts
@@ -5,10 +5,9 @@ import {
Essentials,
Paragraph
} from "ckeditor5";
-import { describe, expect, it, vi } from "vitest";
+import { describe, expect, it } from "vitest";
import { createTestEditor, pressKey as press } from "../../../test/editor-kit.js";
-import { installGlobMock } from "../../../test/globals-test-kit.js";
import ContentEmbed from "../content_embed/content_embed.js";
import Multicolumn from "../multicolumn/multicolumn.js";
import Tabs from "../tabs/tabs.js";
@@ -48,7 +47,6 @@ describe("container keyboard shortcuts", () => {
});
it("leave the keys pressed in an embed to the editor of the embed", async () => {
- installGlobMock({ getComponentByEl: () => ({ loadEmbeddedNote: vi.fn() }) });
const editor = await createTestEditor([Essentials, Paragraph, Multicolumn, ContentEmbed]);
const data = columns(p("a[]"), EMBED);
setModelData(editor.model, data);
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 b81b688520..f6947fa3e4 100644
--- a/packages/ckeditor5/src/plugins/content_embed/content_embed.spec.ts
+++ b/packages/ckeditor5/src/plugins/content_embed/content_embed.spec.ts
@@ -51,12 +51,8 @@ describe("ContentEmbed", () => {
beforeEach(async () => {
pickNote = vi.fn();
loadEmbeddedNote = vi.fn();
- installGlobMock({
- getComponentByEl: () => ({ loadEmbeddedNote })
- });
-
editor = await createTestEditor([Essentials, Paragraph, Widget, ContentEmbed], {
- contentEmbed: { pickNote }
+ contentEmbed: { pickNote, loadNote: loadEmbeddedNote }
});
});
@@ -176,6 +172,18 @@ describe("ContentEmbed", () => {
expect(reloadCall?.[2]).toBe("expandable");
});
+ it("leaves the embeds empty without a host to render them", async () => {
+ const bareEditor = await createTestEditor([ Essentials, Paragraph, Widget, ContentEmbed ]);
+ bareEditor.setData("<figure class=\"include-note\" data-note-id=\"n1\" data-box-size=\"small\">"
+ + "</figure><figure class=\"include-note\" data-attachment-id=\"a1\" data-box-size=\"small\">"
+ + "</figure>");
+
+ const wrappers = bareEditor.editing.view.getDomRoot()?.querySelectorAll("div.include-note-wrapper");
+
+ expect(wrappers).toHaveLength(2);
+ expect([ ...wrappers ?? [] ].map((wrapper) => wrapper.childElementCount)).toEqual([ 0, 0 ]);
+ });
+
it("handles a boxSize change from an empty old value (no class to remove)", () => {
// Insert an contentEmbed whose boxSize is empty so the attribute-change converter
// hits the falsy `oldBoxSize` branch when the value is set for the first time.
@@ -387,11 +395,6 @@ describe("ContentEmbed", () => {
});
it("keeps the renderer's focus off for a press on a link preview", async () => {
- installGlobMock({
- getComponentByEl: () => ({
- loadEmbeddedNote
- })
- });
const linkEditor = await createTestEditor([
Essentials, Paragraph, Widget, ContentEmbed, LinkEmbed
]);
@@ -801,9 +804,6 @@ describe("ContentEmbed with attachments", () => {
getAttachmentHref = vi.fn(async () => LINK_HREF);
installGlobMock({
getComponentByEl: () => ({
- loadEmbeddedNote,
- loadEmbeddedAttachment,
- getAttachmentHref,
loadReferenceLinkTitle: vi.fn(async () => undefined)
})
});
@@ -811,7 +811,12 @@ describe("ContentEmbed with attachments", () => {
editor = await createTestEditor([
Essentials, Paragraph, Undo, Widget, LinkEditing, ReferenceLink, ContentEmbed
], {
- referenceLink: { getTitle: async () => "report.pdf", getTitleSync: () => "report.pdf" }
+ referenceLink: { getTitle: async () => "report.pdf", getTitleSync: () => "report.pdf" },
+ contentEmbed: {
+ loadNote: loadEmbeddedNote,
+ loadAttachment: loadEmbeddedAttachment,
+ getAttachmentHref
+ }
});
});
@@ -1183,13 +1188,9 @@ describe("ContentEmbed captions", () => {
beforeEach(async () => {
loadEmbeddedNote = vi.fn();
- installGlobMock({
- getComponentByEl: () => ({ loadEmbeddedNote })
- });
-
editor = await createTestEditor([
Essentials, Paragraph, Bold, Undo, Widget, ContentEmbed
- ]);
+ ], { contentEmbed: { loadNote: loadEmbeddedNote } });
});
function getCommand() {
@@ -1381,11 +1382,9 @@ describe("ContentEmbed title", () => {
beforeEach(async () => {
loadEmbeddedNote = vi.fn();
openContentEmbedMenu = vi.fn();
- installGlobMock({
- getComponentByEl: () => ({ loadEmbeddedNote, openContentEmbedMenu })
+ editor = await createTestEditor([ Essentials, Paragraph, Undo, Widget, ContentEmbed ], {
+ contentEmbed: { loadNote: loadEmbeddedNote, openMenu: openContentEmbedMenu }
});
-
- editor = await createTestEditor([ Essentials, Paragraph, Undo, Widget, ContentEmbed ]);
});
function getCommand() {
@@ -1505,11 +1504,9 @@ describe("ContentEmbed code view", () => {
beforeEach(async () => {
loadEmbeddedAttachment = vi.fn();
- installGlobMock({
- getComponentByEl: () => ({ loadEmbeddedNote: vi.fn(), loadEmbeddedAttachment })
+ editor = await createTestEditor([ Essentials, Paragraph, Undo, Widget, ContentEmbed ], {
+ contentEmbed: { loadAttachment: loadEmbeddedAttachment }
});
-
- editor = await createTestEditor([ Essentials, Paragraph, Undo, Widget, ContentEmbed ]);
});
function getCommand() {
@@ -1605,11 +1602,9 @@ describe("ContentEmbed editable flag", () => {
beforeEach(async () => {
loadEmbeddedNote = vi.fn();
getContentEmbedTools = vi.fn(() => ({ hasEditableFlag: true }));
- installGlobMock({
- getComponentByEl: () => ({ loadEmbeddedNote, getContentEmbedTools })
+ editor = await createTestEditor([ Essentials, Paragraph, Undo, Widget, ContentEmbed ], {
+ contentEmbed: { loadNote: loadEmbeddedNote, getTools: getContentEmbedTools }
});
-
- editor = await createTestEditor([ Essentials, Paragraph, Undo, Widget, ContentEmbed ]);
});
function getCommand() {
@@ -1690,7 +1685,7 @@ describe("ContentEmbed editable flag", () => {
editor.ui.update();
expect(getCommand().isEnabled).toBe(false);
- installGlobMock({ getComponentByEl: () => ({ loadEmbeddedNote }) });
+ editor.config.set("contentEmbed", { getTools: undefined });
editor.ui.update();
expect(getCommand().isEnabled).toBe(false);
});
@@ -1758,13 +1753,9 @@ describe("ContentEmbed display mode", () => {
beforeEach(async () => {
getContentEmbedTools = vi.fn(() => ({ hasDisplayModes: true }));
- installGlobMock({
- getComponentByEl: () => ({
- loadEmbeddedAttachment: vi.fn(), loadEmbeddedNote: vi.fn(), getContentEmbedTools
- })
+ editor = await createTestEditor([ Essentials, Paragraph, Undo, Widget, ContentEmbed ], {
+ contentEmbed: { getTools: getContentEmbedTools }
});
-
- editor = await createTestEditor([ Essentials, Paragraph, Undo, Widget, ContentEmbed ]);
});
function getCommand() {
@@ -1919,7 +1910,6 @@ describe("ContentEmbed resizing", () => {
let editor: ClassicEditor;
beforeEach(async () => {
- installGlobMock({ getComponentByEl: () => ({ loadEmbeddedNote: vi.fn() }) });
editor = await createTestEditor([ Essentials, Paragraph, Undo, Widget, ContentEmbed ]);
});
diff --git a/packages/ckeditor5/src/plugins/content_embed/content_embed.ts b/packages/ckeditor5/src/plugins/content_embed/content_embed.ts
index 0eb5ff6652..dc34955928 100644
--- a/packages/ckeditor5/src/plugins/content_embed/content_embed.ts
+++ b/packages/ckeditor5/src/plugins/content_embed/content_embed.ts
@@ -33,8 +33,9 @@ import { encodeBlockParameter, parseBlockRange } from '@triliumnext/commons';
import { getAttachmentId, getNoteId } from '../referencelink.js';
import ResizableWidgets, { SIZE_ATTRIBUTES } from '../resizable_widgets/resizable_widgets.js';
import { restoreRendererFocusOnInput } from '../widget_utils.js';
+import type { EmbedEdge } from './content_embed_caret.js';
import EmbedHistory from './embed_history.js';
-import ContentEmbedInlineSource, { isInlineSourceEmbed } from './inline_source.js';
+import ContentEmbedInlineSource, { type InlineEmbedSource, isInlineSourceEmbed } from './inline_source.js';
import './nested_editor_events.js';
export const COMMAND_NAME = 'insertContentEmbed';
@@ -1078,11 +1079,9 @@ class ConvertEmbedToLinkCommand extends Command {
return;
}
- const editorEl = editor.editing.view.getDomRoot();
- const component = glob.getComponentByEl<EditorComponent>( editorEl );
const blockQuery = block ? `?block=${ encodeBlockParameter( block ) }` : '';
const href = attachmentId
- ? await component.getAttachmentHref( attachmentId )
+ ? await editor.config.get( 'contentEmbed' )?.getAttachmentHref?.( attachmentId )
: `#root/${ noteId }${ blockQuery }`;
// The embed can be removed while the host looks the link up.
@@ -1361,9 +1360,7 @@ function getEmbedTools(
return null;
}
- const component: EditorComponent | undefined =
- glob.getComponentByEl<EditorComponent>( editor.editing.view.getDomRoot() );
- return component?.getContentEmbedTools?.( domElement ) ?? null;
+ return editor.config.get( 'contentEmbed' )?.getTools?.( domElement ) ?? null;
}
/** Has the host open the context menu of the selected embed, below `anchor`. */
@@ -1373,8 +1370,7 @@ function openContentEmbedMenu( editor: Editor, anchor: HTMLElement | null ) {
return;
}
- const component = glob.getComponentByEl<EditorComponent>( editor.editing.view.getDomRoot() );
- component.openContentEmbedMenu?.( domElement, anchor );
+ editor.config.get( 'contentEmbed' )?.openMenu?.( domElement, anchor );
}
/** The rendered `<figure>` of `embed`, or `null`. */
@@ -1474,17 +1470,15 @@ function loadEmbeddedContent(
return;
}
- const $wrapper = $( wrapper );
- const editorEl = editor.editing.view.getDomRoot();
- const component = glob.getComponentByEl<EditorComponent>( editorEl );
+ const host = editor.config.get( 'contentEmbed' );
const attachmentId = element.getAttribute( 'attachmentId' ) as string | undefined;
const noteId = element.getAttribute( 'noteId' ) as string | undefined;
if ( attachmentId ) {
- component.loadEmbeddedAttachment( attachmentId, $wrapper, boxSize );
+ host?.loadAttachment?.( attachmentId, wrapper, boxSize );
} else if ( noteId ) {
const block = element.getAttribute( 'block' ) as string | undefined;
- component.loadEmbeddedNote( noteId, $wrapper, boxSize, block, newBlock => {
+ host?.loadNote?.( noteId, wrapper, boxSize, block, newBlock => {
setEmbedBlock( editor, element, wrapper, newBlock );
} );
}
@@ -1666,23 +1660,59 @@ declare module 'ckeditor5' {
}
interface EditorConfig {
- contentEmbed?: {
- /** Opens the dialog that picks a note to include at the selection. */
- pickNote?: () => void;
- /**
- * The languages whose `<pre><code class="language-…">` code blocks show as embeds of
- * their source, rendered by the host's `loadInlineEmbed()`.
- */
- inlineLanguages?: string[];
- /**
- * Renders the `source` of an inline language into `container`, outside an embed, as
- * the AI assistant previews a response.
- */
- renderInlinePreview?: ( language: string, source: string, container: HTMLElement ) => void;
- };
+ contentEmbed?: Partial<ContentEmbedHost>;
}
}
+/** What the host of the editor renders into embeds, and does with them. */
+export interface ContentEmbedHost {
+ /** Opens the dialog that picks a note to include at the selection. */
+ pickNote(): void;
+ /**
+ * The languages whose `<pre><code class="language-…">` code blocks show as embeds of their
+ * source, rendered by `loadInline()`.
+ */
+ inlineLanguages: string[];
+ /**
+ * Renders the `source` of an inline language into `container`, outside an embed, as the AI
+ * assistant previews a response.
+ */
+ renderInlinePreview( language: string, source: string, container: HTMLElement ): void;
+ /**
+ * Fills `wrapper` with the note, or with the `block` of it, a `block` link parameter. An
+ * editor of those blocks calls `onBlockChange()` once the blocks at its edges change.
+ */
+ loadNote(
+ noteId: string,
+ wrapper: HTMLElement,
+ boxSize: string | undefined,
+ block: string | undefined,
+ onBlockChange: ( block: string ) => void
+ ): void;
+ /** Fills `wrapper` with the attachment. */
+ loadAttachment( attachmentId: string, wrapper: HTMLElement, boxSize: string | undefined ): void;
+ /** Fills `wrapper` with the source of an inline embed, focused if `isFocused`. */
+ loadInline(
+ source: InlineEmbedSource,
+ wrapper: HTMLElement,
+ boxSize: string | undefined,
+ options: { isFocused: boolean }
+ ): void;
+ /** Gives the focus to what the embed of the attachment shows, once it renders. */
+ focusAttachment( attachmentId: string ): void;
+ /** The href of a reference link to the attachment, or `null` once it is deleted. */
+ getAttachmentHref( attachmentId: string ): Promise<string | null>;
+ /** Opens the context menu of what `embed` shows, below `anchor`. */
+ openMenu( embed: HTMLElement, anchor: HTMLElement ): void;
+ /** The buttons that what `embed` shows adds to the toolbar of the embed, or `null`. */
+ getTools( embed: HTMLElement ): ContentEmbedToolProvider | null;
+ /**
+ * Focuses the editor that `embed` shows, with the caret at `edge` of its content, and
+ * returns whether it did.
+ */
+ enter( embed: HTMLElement, edge: EmbedEdge ): boolean;
+}
+
/** A toolbar separator that shows only while `isVisible`, as the items on both sides do. */
class ToolbarItemSeparatorView extends View {
declare public isVisible: boolean;
diff --git a/packages/ckeditor5/src/plugins/content_embed/content_embed_box_size_dropdown.spec.ts b/packages/ckeditor5/src/plugins/content_embed/content_embed_box_size_dropdown.spec.ts
index 91fc0fc0f3..94fc7f1fc8 100644
--- a/packages/ckeditor5/src/plugins/content_embed/content_embed_box_size_dropdown.spec.ts
+++ b/packages/ckeditor5/src/plugins/content_embed/content_embed_box_size_dropdown.spec.ts
@@ -2,7 +2,6 @@ import { ClassicEditor, Essentials, Paragraph, Widget, _setModelData as setModel
import { beforeEach, describe, expect, it, vi } from "vitest";
import { createTestEditor } from "../../../test/editor-kit.js";
-import { installGlobMock } from "../../../test/globals-test-kit.js";
import ContentEmbedBoxSizeDropdown from "./content_embed_box_size_dropdown.js";
import ContentEmbed, { BOX_SIZE_COMMAND_NAME, BOX_SIZES } from "./content_embed.js";
@@ -10,11 +9,6 @@ describe("ContentEmbedBoxSizeDropdown", () => {
let editor: ClassicEditor;
beforeEach(async () => {
- const loadEmbeddedNote = vi.fn();
- installGlobMock({
- getComponentByEl: () => ({ loadEmbeddedNote })
- });
-
editor = await createTestEditor([Essentials, Paragraph, Widget, ContentEmbed, ContentEmbedBoxSizeDropdown]);
});
@@ -83,12 +77,7 @@ describe("ContentEmbedBoxSizeDropdown", () => {
execute: () => {},
subscribe: () => () => {}
};
- installGlobMock({
- getComponentByEl: () => ({
- loadEmbeddedNote: vi.fn(),
- getContentEmbedTools: () => provider
- })
- });
+ editor.config.set("contentEmbed", { getTools: () => provider });
const dropdownView = editor.ui.componentFactory.create("contentEmbedBoxSizeDropdown") as unknown as {
buttonView: { icon?: string; label: string; withText: boolean; tooltip: boolean };
};
diff --git a/packages/ckeditor5/src/plugins/content_embed/content_embed_caret.spec.ts b/packages/ckeditor5/src/plugins/content_embed/content_embed_caret.spec.ts
index 979314f19e..914b104075 100644
--- a/packages/ckeditor5/src/plugins/content_embed/content_embed_caret.spec.ts
+++ b/packages/ckeditor5/src/plugins/content_embed/content_embed_caret.spec.ts
@@ -10,10 +10,9 @@ import {
Table,
Widget
} from "ckeditor5";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { beforeEach, describe, expect, it, vi } from "vitest";
-import { createTestEditor, destroyTrackedEditors, pressKey } from "../../../test/editor-kit.js";
-import { installGlobMock } from "../../../test/globals-test-kit.js";
+import { createTestEditor, pressKey } from "../../../test/editor-kit.js";
import TriliumMentionUI from "../mention/trilium_mention_ui.js";
import type { MentionHostedList } from "../mention/types.js";
import ContentEmbed from "./content_embed.js";
@@ -37,10 +36,9 @@ describe("ContentEmbedCaret entering an embed", () => {
beforeEach(async () => {
enterContentEmbed = vi.fn(() => true);
- installGlobMock({
- getComponentByEl: () => ({ loadEmbeddedNote: vi.fn(), enterContentEmbed })
+ editor = await createTestEditor(TEXT_PLUGINS, {
+ contentEmbed: { enter: enterContentEmbed }
});
- editor = await createTestEditor(TEXT_PLUGINS);
});
it("enters the embed beside the caret with Left and Right", () => {
@@ -139,7 +137,7 @@ describe("ContentEmbedCaret entering an embed", () => {
expect(pressKey(editor, "ArrowRight")).toBe(false);
expect(enterContentEmbed).toHaveBeenCalledOnce();
- installGlobMock({ getComponentByEl: () => ({ loadEmbeddedNote: vi.fn() }) });
+ editor.config.set("contentEmbed", { enter: undefined });
expect(pressKey(editor, "ArrowRight")).toBe(false);
});
@@ -177,7 +175,10 @@ describe("ContentEmbedCaret entering an embed", () => {
});
it("follows the screen in right-to-left content", async () => {
- const rtlEditor = await createTestEditor(TEXT_PLUGINS, { language: { content: "ar" } });
+ const rtlEditor = await createTestEditor(TEXT_PLUGINS, {
+ language: { content: "ar" },
+ contentEmbed: { enter: enterContentEmbed }
+ });
setModelData(rtlEditor.model, `<paragraph>ab[]</paragraph>${EMBED}`);
expect(pressKey(rtlEditor, "ArrowRight")).toBe(false);
expect(pressKey(rtlEditor, "ArrowLeft")).toBe(true);
@@ -190,15 +191,10 @@ describe("ContentEmbedCaret leaving an embed", () => {
let plugin: ContentEmbedCaret;
beforeEach(async () => {
- installGlobMock({ getComponentByEl: () => ({ loadEmbeddedNote: vi.fn() }) });
editor = await createTestEditor(TEXT_PLUGINS);
plugin = editor.plugins.get(ContentEmbedCaret);
});
- // Destroying a focused editor with an embed selected reads the `glob` mock, which the global
- // cleanups remove first.
- afterEach(() => destroyTrackedEditors());
-
it("focuses the editor with the caret in the text beside the embed", () => {
setModelData(editor.model, `<paragraph>ab</paragraph>${EMBED}<paragraph>cd</paragraph>`);
expect(plugin.leaveEmbed(getEmbedContent(editor), "end")).toBe(true);
@@ -222,14 +218,12 @@ describe("ContentEmbedCaret leaving an embed", () => {
});
it("scrolls to the fake caret below an embed taller than the window", () => {
- installGlobMock({
- getComponentByEl: () => ({
- loadEmbeddedNote: (_noteId: string, wrapper: HTMLElement) => {
- const content = document.createElement("div");
- content.style.height = `${window.innerHeight * 3}px`;
- wrapper.append(content);
- }
- })
+ editor.config.set("contentEmbed", {
+ loadNote: (_noteId: string, wrapper: HTMLElement) => {
+ const content = document.createElement("div");
+ content.style.height = `${window.innerHeight * 3}px`;
+ wrapper.append(content);
+ }
});
setModelData(editor.model, AB + EMBED);
// As after reading down to the end of the embed, its top is above the window.
@@ -268,7 +262,6 @@ describe("ContentEmbedCaret as the editor of an embed", () => {
let plugin: ContentEmbedCaret;
beforeEach(async () => {
- installGlobMock({ getComponentByEl: () => ({ loadEmbeddedNote: vi.fn() }) });
editor = await createTestEditor(TEXT_PLUGINS);
plugin = editor.plugins.get(ContentEmbedCaret);
});
diff --git a/packages/ckeditor5/src/plugins/content_embed/content_embed_caret.ts b/packages/ckeditor5/src/plugins/content_embed/content_embed_caret.ts
index aed7b1962e..a4d92f644c 100644
--- a/packages/ckeditor5/src/plugins/content_embed/content_embed_caret.ts
+++ b/packages/ckeditor5/src/plugins/content_embed/content_embed_caret.ts
@@ -23,7 +23,7 @@ export type EmbedEdge = "start" | "end";
* Moves the caret between the text and the editors in embeds with the arrow keys.
*
* When an arrow key reaches an embed, the host focuses the editor of the embed at its near edge,
- * through `enterContentEmbed()`. In the editor of an embed, `focusAt()` and `getEdgeLeftBy()`
+ * through `contentEmbed.enter()`. In the editor of an embed, `focusAt()` and `getEdgeLeftBy()`
* do the same for its own content, and `leaveEmbed()` of the editor around it takes the caret back.
*/
export default class ContentEmbedCaret extends Plugin {
@@ -187,8 +187,7 @@ export default class ContentEmbedCaret extends Plugin {
private enterEmbed(embed: ModelElement, edge: EmbedEdge) {
const editor = this.editor;
const domElement = getContentEmbedDom(editor, embed);
- const component = glob.getComponentByEl<EditorComponent>(editor.editing.view.getDomRoot());
- return !!domElement && !!component?.enterContentEmbed?.(domElement, edge);
+ return !!domElement && !!editor.config.get("contentEmbed")?.enter?.(domElement, edge);
}
/**
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 d3169809d8..e72ebbfe64 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
@@ -1,8 +1,7 @@
import { ClassicEditor, Essentials, Paragraph, Plugin, toWidget, Widget, WidgetToolbarRepository, _setModelData as setModelData } from "ckeditor5";
-import { beforeEach, describe, expect, it, vi } from "vitest";
+import { beforeEach, describe, expect, it } from "vitest";
import { createTestEditor } from "../../../test/editor-kit.js";
-import { installGlobMock } from "../../../test/globals-test-kit.js";
import LinkEmbed from "../link_embed/link_embed.js";
import ContentEmbed, {
CONVERT_EMBED_TO_LINK_COMMAND,
@@ -82,11 +81,6 @@ describe("ContentEmbedToolbar", () => {
let editor: ClassicEditor;
beforeEach(async () => {
- const loadEmbeddedNote = vi.fn();
- installGlobMock({
- getComponentByEl: () => ({ loadEmbeddedNote })
- });
-
editor = await createTestEditor([Essentials, Paragraph, Widget, ContentEmbed, ContentEmbedBoxSizeDropdown, ContentEmbedToolbar]);
});
@@ -183,11 +177,6 @@ describe("isContentEmbedWidget — widget without a class attribute", () => {
let editor: ClassicEditor;
beforeEach(async () => {
- const loadEmbeddedNote = vi.fn();
- installGlobMock({
- getComponentByEl: () => ({ loadEmbeddedNote })
- });
-
editor = await createTestEditor([Essentials, Paragraph, Widget, ContentEmbed, ContentEmbedBoxSizeDropdown, ContentEmbedToolbar, SectionNoClassWidget]);
});
@@ -216,13 +205,6 @@ describe("isContentEmbedWidget — real non-include-note widgets", () => {
let editor: ClassicEditor;
beforeEach(async () => {
- const loadEmbeddedNote = vi.fn();
- installGlobMock({
- getComponentByEl: () => ({
- loadEmbeddedNote
- })
- });
-
editor = await createTestEditor([Essentials, Paragraph, Widget, ContentEmbed, ContentEmbedBoxSizeDropdown, ContentEmbedToolbar, LinkEmbed]);
});
diff --git a/packages/ckeditor5/src/plugins/content_embed/content_embed_tools.spec.ts b/packages/ckeditor5/src/plugins/content_embed/content_embed_tools.spec.ts
index 83fcb2bf13..061cb95c3d 100644
--- a/packages/ckeditor5/src/plugins/content_embed/content_embed_tools.spec.ts
+++ b/packages/ckeditor5/src/plugins/content_embed/content_embed_tools.spec.ts
@@ -5,7 +5,6 @@ import {
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { createTestEditor } from "../../../test/editor-kit.js";
-import { installGlobMock } from "../../../test/globals-test-kit.js";
import ReferenceLink from "../referencelink.js";
import ContentEmbed from "./content_embed.js";
import ContentEmbedBoxSizeDropdown from "./content_embed_box_size_dropdown.js";
@@ -57,14 +56,10 @@ describe("ContentEmbedTools", () => {
beforeEach(async () => {
provider = createProvider([ SELECTION, RECTANGLE ]);
getContentEmbedTools = vi.fn(() => provider);
- installGlobMock({
- getComponentByEl: () => ({ loadEmbeddedNote: vi.fn(), getContentEmbedTools })
- });
-
editor = await createTestEditor([
Essentials, Paragraph, Widget, LinkEditing, ReferenceLink, ContentEmbed,
ContentEmbedBoxSizeDropdown, ContentEmbedTools
- ]);
+ ], { contentEmbed: { getTools: getContentEmbedTools } });
});
afterEach(() => {
@@ -283,13 +278,9 @@ describe("ContentEmbedTools", () => {
selectEmbed();
expect(tools.isVisible).toBe(false);
- installGlobMock({ getComponentByEl: () => ({ loadEmbeddedNote: vi.fn() }) });
+ editor.config.set("contentEmbed", { getTools: undefined });
selectEmbed();
expect(tools.isVisible).toBe(false);
-
- installGlobMock({ getComponentByEl: () => undefined });
- editor.ui.update();
- expect(tools.isVisible).toBe(false);
});
it("runs a tool without taking the focus", () => {
diff --git a/packages/ckeditor5/src/plugins/content_embed/content_embed_tools.ts b/packages/ckeditor5/src/plugins/content_embed/content_embed_tools.ts
index f3068414d9..50e3edd032 100644
--- a/packages/ckeditor5/src/plugins/content_embed/content_embed_tools.ts
+++ b/packages/ckeditor5/src/plugins/content_embed/content_embed_tools.ts
@@ -13,7 +13,7 @@ export const CONTENT_EMBED_TOOLS = "contentEmbedTools";
/**
* Shows the buttons that the content of the selected embed adds to the embed's toolbar, such as
- * the tools of a canvas drawing. The host supplies them through `getContentEmbedTools()`.
+ * the tools of a canvas drawing. The host supplies them through `contentEmbed.getTools()`.
*/
export default class ContentEmbedTools extends Plugin {
diff --git a/packages/ckeditor5/src/plugins/content_embed/inline_source.spec.ts b/packages/ckeditor5/src/plugins/content_embed/inline_source.spec.ts
index ca9e002b8d..98cedc63cd 100644
--- a/packages/ckeditor5/src/plugins/content_embed/inline_source.spec.ts
+++ b/packages/ckeditor5/src/plugins/content_embed/inline_source.spec.ts
@@ -14,7 +14,6 @@ import {
import { beforeEach, describe, expect, it, vi } from "vitest";
import { createTestEditor } from "../../../test/editor-kit.js";
-import { installGlobMock } from "../../../test/globals-test-kit.js";
import { SIZE_ATTRIBUTES } from "../resizable_widgets/resizable_widgets.js";
import ContentEmbedBoxSizeDropdown, {
CONTENT_EMBED_BOX_SIZE_DROPDOWN
@@ -36,16 +35,10 @@ describe("ContentEmbedInlineSource", () => {
beforeEach(async () => {
loadInlineEmbed = vi.fn();
- installGlobMock({
- getComponentByEl: () => ({
- loadEmbeddedNote: vi.fn(), loadInlineEmbed
- })
- });
-
editor = await createTestEditor([
Essentials, Paragraph, Undo, Widget, ContentEmbed, ContentEmbedBoxSizeDropdown
], {
- contentEmbed: { inlineLanguages: [ "mermaid" ] }
+ contentEmbed: { inlineLanguages: [ "mermaid" ], loadInline: loadInlineEmbed }
});
});
@@ -146,12 +139,11 @@ describe("ContentEmbedInlineSource", () => {
editor.setData(`<pre><code class="language-mermaid">graph TD;</code></pre>`);
expect(loadInlineEmbed).toHaveBeenCalledOnce();
- const [ source, $el, boxSize, options ] = loadInlineEmbed.mock.calls[0];
+ const [ source, wrapper, boxSize, options ] = loadInlineEmbed.mock.calls[0];
expect(source.language).toBe("mermaid");
expect(source.getSource()).toBe("graph TD;");
expect(source.isReadOnly()).toBe(false);
- // `test/setup.ts` stubs jQuery as the identity, so the wrapper arrives as is.
- expect(($el as HTMLElement).classList.contains("include-note-wrapper")).toBe(true);
+ expect((wrapper as HTMLElement).classList.contains("include-note-wrapper")).toBe(true);
expect(boxSize).toBe("medium");
expect(options).toEqual({ isFocused: false });
diff --git a/packages/ckeditor5/src/plugins/content_embed/inline_source.ts b/packages/ckeditor5/src/plugins/content_embed/inline_source.ts
index 3eddc8667b..2856051f2e 100644
--- a/packages/ckeditor5/src/plugins/content_embed/inline_source.ts
+++ b/packages/ckeditor5/src/plugins/content_embed/inline_source.ts
@@ -63,7 +63,7 @@ const SIZE_PROPERTIES = [
* attributes, and is saved as the code block, with its box size, flags and size on the `<pre>`,
* so that anything reading the note sees a plain code block.
*
- * The content renders through the host's `loadInlineEmbed()`, which receives an
+ * The content renders through the host's `contentEmbed.loadInline()`, which receives an
* {@link InlineEmbedSource} rather than an ID.
*/
export default class ContentEmbedInlineSource extends Plugin {
@@ -102,9 +102,8 @@ export default class ContentEmbedInlineSource extends Plugin {
/** Has the host render the source of `embed` into `wrapper`. */
load( embed: ModelElement, wrapper: HTMLElement, boxSize: string | undefined ) {
const editor = this.editor;
- const component = glob.getComponentByEl<EditorComponent>( editor.editing.view.getDomRoot() );
const isFocused = this.focusedEmbeds.delete( embed );
- component.loadInlineEmbed?.( this.getSource( embed ), $( wrapper ), boxSize, { isFocused } );
+ editor.config.get( 'contentEmbed' )?.loadInline?.( this.getSource( embed ), wrapper, boxSize, { isFocused } );
}
/** Marks `embed` for its content to take the focus once it renders. */
diff --git a/packages/ckeditor5/src/plugins/file_upload/fileuploadediting.spec.ts b/packages/ckeditor5/src/plugins/file_upload/fileuploadediting.spec.ts
index 75e98f942f..a64fda11f8 100644
--- a/packages/ckeditor5/src/plugins/file_upload/fileuploadediting.spec.ts
+++ b/packages/ckeditor5/src/plugins/file_upload/fileuploadediting.spec.ts
@@ -20,7 +20,6 @@ import {
import { beforeEach, describe, expect, it, vi } from "vitest";
import { createTestEditor } from "../../../test/editor-kit.js";
-import { installGlobMock } from "../../../test/globals-test-kit.js";
import ContentEmbed from "../content_embed/content_embed.js";
import FileUploadEditing, {
isHtmlIncluded,
@@ -605,16 +604,16 @@ describe("FileUploadEditing with embeds", () => {
it("completes an embed placeholder with the attachment it uploaded", async () => {
const loadEmbeddedAttachment = vi.fn();
const focusContentEmbed = vi.fn();
- installGlobMock({
- getComponentByEl: () => ({
- loadEmbeddedAttachment,
- focusContentEmbed
- })
- });
const editor = await createTestEditor([
Essentials, Paragraph, FileRepository, Notification, Clipboard, ReferenceSchema,
ContentEmbed, FileUploadEditing
- ], { attachmentUpload: { getEmbedBoxSize: () => "small" } });
+ ], {
+ attachmentUpload: { getEmbedBoxSize: () => "small" },
+ contentEmbed: {
+ loadAttachment: loadEmbeddedAttachment,
+ focusAttachment: focusContentEmbed
+ }
+ });
const controls = installUploadAdapter(editor);
setModelData(editor.model, "<paragraph>[]</paragraph>");
@@ -635,16 +634,15 @@ describe("FileUploadEditing with embeds", () => {
it("asks the host to focus the embed of a focus upload, before it renders", async () => {
const calls: string[] = [];
- installGlobMock({
- getComponentByEl: () => ({
- loadEmbeddedAttachment: (id: string) => calls.push(`load ${id}`),
- focusContentEmbed: (id: string) => calls.push(`focus ${id}`)
- })
- });
const editor = await createTestEditor([
Essentials, Paragraph, FileRepository, Notification, Clipboard, ReferenceSchema,
ContentEmbed, FileUploadEditing
- ]);
+ ], {
+ contentEmbed: {
+ loadAttachment: (id: string) => calls.push(`load ${id}`),
+ focusAttachment: (id: string) => calls.push(`focus ${id}`)
+ }
+ });
const controls = installUploadAdapter(editor);
setModelData(editor.model, "<paragraph>[]</paragraph>");
diff --git a/packages/ckeditor5/src/plugins/file_upload/fileuploadediting.ts b/packages/ckeditor5/src/plugins/file_upload/fileuploadediting.ts
index 32ba1a0d01..758798a3a8 100644
--- a/packages/ckeditor5/src/plugins/file_upload/fileuploadediting.ts
+++ b/packages/ckeditor5/src/plugins/file_upload/fileuploadediting.ts
@@ -149,8 +149,7 @@ export default class FileUploadEditing extends Plugin {
// Before `attachmentId` is set: setting it makes the host render the embed.
const isEmbed = fileElement.is( 'element', 'contentEmbed' );
if ( attachmentId && isEmbed && isFocusUpload( loader ) ) {
- glob.getComponentByEl<EditorComponent>( editor.editing.view.getDomRoot() )
- .focusContentEmbed?.( attachmentId );
+ editor.config.get( 'contentEmbed' )?.focusAttachment?.( attachmentId );
}
model.enqueueChange( { isUndoable: false }, writer => {
diff --git a/packages/ckeditor5/src/plugins/image_to_drawing.spec.ts b/packages/ckeditor5/src/plugins/image_to_drawing.spec.ts
index fd85d13890..a8cba81ec2 100644
--- a/packages/ckeditor5/src/plugins/image_to_drawing.spec.ts
+++ b/packages/ckeditor5/src/plugins/image_to_drawing.spec.ts
@@ -36,15 +36,18 @@ describe("ImageToDrawing", () => {
});
installGlobMock({
getComponentByEl: () => ({
- convertImageToDrawing,
- focusContentEmbed: (id: string) => calls.push(`focus ${id}`),
- loadEmbeddedAttachment: (id: string) => calls.push(`load ${id}`)
+ convertImageToDrawing
})
});
editor = await createTestEditor([
Essentials, Paragraph, Image, ImageBlock, ImageInline, ImageCaption, ContentEmbed,
ImageToDrawing
- ]);
+ ], {
+ contentEmbed: {
+ focusAttachment: (id: string) => calls.push(`focus ${id}`),
+ loadAttachment: (id: string) => calls.push(`load ${id}`)
+ }
+ });
});
/** Holds the next conversion until the returned function finishes it with an attachment ID. */
diff --git a/packages/ckeditor5/src/plugins/image_to_drawing.ts b/packages/ckeditor5/src/plugins/image_to_drawing.ts
index 584c732584..8bfe2dd62d 100644
--- a/packages/ckeditor5/src/plugins/image_to_drawing.ts
+++ b/packages/ckeditor5/src/plugins/image_to_drawing.ts
@@ -76,7 +76,7 @@ export class ConvertImageToDrawingCommand extends Command {
}
if (!attachmentId || !isInDocument(image)) return;
- host.focusContentEmbed?.(attachmentId);
+ editor.config.get("contentEmbed")?.focusAttachment?.(attachmentId);
// CKEditor's renderer draws a figure that replaces another in the same render twice, so
// the embed goes in and the image out in two changes, of one batch for a single undo.
const model = editor.model;
diff --git a/packages/ckeditor5/src/plugins/mermaid/README.md b/packages/ckeditor5/src/plugins/mermaid/README.md
index f6c37be4e6..790dc1d52f 100644
--- a/packages/ckeditor5/src/plugins/mermaid/README.md
+++ b/packages/ckeditor5/src/plugins/mermaid/README.md
@@ -13,8 +13,9 @@ template in `mermaid.samples`. Load the `Mermaid` glue plugin; it pulls in `Merm
This package has no Mermaid editing or rendering of its own. A diagram is a `contentEmbed` that
keeps its source in the note (`content_embed/inline_source.ts`): it is saved as
`<pre><code class="language-mermaid">…</code></pre>`, with the box size, flags and size of the
-embed on the `<pre>`, and the host renders and edits it through `loadInlineEmbed()`. The host must
-list `mermaid` in `contentEmbed.inlineLanguages`, or a diagram loads as a plain code block.
+embed on the `<pre>`, and the host renders and edits it through `contentEmbed.loadInline()`. The
+host must list `mermaid` in `contentEmbed.inlineLanguages`, or a diagram loads as a plain code
+block.
## Provenance
diff --git a/packages/ckeditor5/src/plugins/mermaid/mermaid_ui.spec.ts b/packages/ckeditor5/src/plugins/mermaid/mermaid_ui.spec.ts
index 2c0381d2f2..6dbf7afc0c 100644
--- a/packages/ckeditor5/src/plugins/mermaid/mermaid_ui.spec.ts
+++ b/packages/ckeditor5/src/plugins/mermaid/mermaid_ui.spec.ts
@@ -10,10 +10,9 @@ import {
SplitButtonView,
Widget
} from "ckeditor5";
-import { beforeEach, describe, expect, it, vi } from "vitest";
+import { beforeEach, describe, expect, it } from "vitest";
import { createTestEditor } from "../../../test/editor-kit.js";
-import { installGlobMock } from "../../../test/globals-test-kit.js";
import ContentEmbed from "../content_embed/content_embed.js";
import Mermaid from "./mermaid.js";
@@ -26,12 +25,6 @@ describe("MermaidUI", () => {
let editor: ClassicEditor;
beforeEach(async () => {
- installGlobMock({
- getComponentByEl: () => ({
- loadEmbeddedNote: vi.fn(), loadInlineEmbed: vi.fn()
- })
- });
-
editor = await createTestEditor([ Essentials, Paragraph, Widget, ContentEmbed, Mermaid ], {
contentEmbed: { inlineLanguages: [ "mermaid" ] },
mermaid: { samples: SAMPLES }