Skip to content

Build your personal knowledge base with Trilium Notes

link previews: migrate the insert link preview dialog to a CK Editor balloon form

Adorian Doranaeceab6d6be8
diff --git a/apps/client/src/components/app_context.ts b/apps/client/src/components/app_context.ts
index 107a5d3dbd..60817e2677 100644
--- a/apps/client/src/components/app_context.ts
+++ b/apps/client/src/components/app_context.ts
@@ -20,7 +20,6 @@ import { AddLinkOpts } from "../widgets/dialogs/add_link.jsx";
import type { ConfirmWithMessageOptions, ConfirmWithTitleOptions } from "../widgets/dialogs/confirm.js";
import type { ResolveOptions } from "../widgets/dialogs/delete_notes.js";
import { IncludeNoteOpts } from "../widgets/dialogs/include_note.jsx";
-import { LinkEmbedOpts } from "../widgets/dialogs/link_embed.jsx";
import type { InfoProps } from "../widgets/dialogs/info.jsx";
import type { MarkdownImportOpts } from "../widgets/dialogs/markdown_import.jsx";
import { ChooseNoteTypeCallback } from "../widgets/dialogs/note_type_chooser.jsx";
@@ -243,7 +242,6 @@ export type CommandMappings = {
showProtectedSessionPasswordDialog: CommandData;
showUploadAttachmentsDialog: CommandData & { noteId: string };
showIncludeNoteDialog: CommandData & IncludeNoteOpts;
- showLinkEmbedDialog: CommandData & LinkEmbedOpts;
showAddLinkDialog: CommandData & AddLinkOpts;
showPasteMarkdownDialog: CommandData & MarkdownImportOpts;
closeProtectedSessionPasswordDialog: CommandData;
diff --git a/apps/client/src/layouts/layout_commons.tsx b/apps/client/src/layouts/layout_commons.tsx
index 053a05e6d7..4d72861496 100644
--- a/apps/client/src/layouts/layout_commons.tsx
+++ b/apps/client/src/layouts/layout_commons.tsx
@@ -18,7 +18,6 @@ export function applyModals(rootContainer: RootContainer) {
.child(<LazyDialog triggerEvents={["editBranchPrefix"]} loader={() => import("../widgets/dialogs/branch_prefix.js")} />)
.child(<LazyDialog triggerEvents={["sortChildNotes"]} loader={() => import("../widgets/dialogs/sort_child_notes.js")} />)
.child(<LazyDialog triggerEvents={["showIncludeNoteDialog"]} loader={() => import("../widgets/dialogs/include_note.js")} />)
- .child(<LazyDialog triggerEvents={["showLinkEmbedDialog"]} loader={() => import("../widgets/dialogs/link_embed.js")} />)
.child(<LazyDialog triggerEvents={["chooseNoteType"]} loader={() => import("../widgets/dialogs/note_type_chooser.js")} />)
.child(<LazyDialog triggerEvents={["jumpToNote", "commandPalette"]} loader={() => import("../widgets/dialogs/jump_to_note.js")} />)
.child(<LazyDialog triggerEvents={["showAddLinkDialog"]} loader={() => import("../widgets/dialogs/add_link.js")} />)
diff --git a/apps/client/src/services/link_embed.tsx b/apps/client/src/services/link_embed.tsx
index d2fa15699b..6d5dc86ad0 100644
--- a/apps/client/src/services/link_embed.tsx
+++ b/apps/client/src/services/link_embed.tsx
@@ -7,9 +7,6 @@ import { useState } from "preact/hooks";
import { t } from "./i18n.js";
import server from "./server.js";
-/** Paste mode chosen by user from the floating popup. */
-export type LinkPasteMode = "mention" | "url" | "embed";
-
export interface EmbedMetadata {
url: string;
embedType: string;
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 21d0fca8b0..6963914cce 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -2450,7 +2450,14 @@
"copy_url": "Copy URL"
},
"link_embed": {
- "play_video": "Play video"
+ "play_video": "Play video",
+ "title": "Link preview",
+ "url": "URL",
+ "insert": "Insert",
+ "display": "Display",
+ "mode_inline": "Inline",
+ "mode_card": "Card",
+ "mode_embed": "Embed"
},
"link_context_menu": {
"open_note_in_new_tab": "Open note in a new tab",
diff --git a/apps/client/src/widgets/dialogs/link_embed.tsx b/apps/client/src/widgets/dialogs/link_embed.tsx
deleted file mode 100644
index 59f98aec17..0000000000
--- a/apps/client/src/widgets/dialogs/link_embed.tsx
+++ /dev/null
@@ -1,82 +0,0 @@
-import { useRef, useState } from "preact/hooks";
-import linkEmbedService from "../../services/link_embed";
-import type { LinkPasteMode } from "../../services/link_embed";
-import FormGroup from "../react/FormGroup";
-import Modal from "../react/Modal";
-import Button from "../react/Button";
-import { useTriliumEvent } from "../react/hooks";
-import type { CKEditorApi } from "../type_widgets/text/CKEditorWithWatchdog";
-
-export interface LinkEmbedOpts {
- editorApi: CKEditorApi;
-}
-
-export default function LinkEmbedDialog() {
- const editorApiRef = useRef<CKEditorApi>(null);
- const [url, setUrl] = useState("");
- const [mode, setMode] = useState<LinkPasteMode>("embed");
- const [shown, setShown] = useState(false);
- const inputRef = useRef<HTMLInputElement>(null);
-
- useTriliumEvent("showLinkEmbedDialog", ({ editorApi }) => {
- editorApiRef.current = editorApi;
- setUrl("");
- setMode("embed");
- setShown(true);
- });
-
- const handleSubmit = async () => {
- const trimmedUrl = url.trim();
- if (!trimmedUrl || !editorApiRef.current) return;
-
- if (mode === "url") {
- editorApiRef.current.addLinkToEditor(trimmedUrl, trimmedUrl);
- } else {
- const metadata = await linkEmbedService.fetchMetadata(trimmedUrl);
- if (mode === "mention") {
- editorApiRef.current.addLinkMention(metadata);
- } else {
- editorApiRef.current.addLinkEmbed(metadata);
- }
- }
- setShown(false);
- };
-
- return (
- <Modal
- className="link-embed-dialog"
- title="Insert link"
- size="lg"
- onShown={() => inputRef.current?.focus()}
- onHidden={() => setShown(false)}
- onSubmit={handleSubmit}
- footer={<Button text="Insert" keyboardShortcut="Enter" />}
- show={shown}
- >
- <FormGroup name="url" label="URL">
- <input
- ref={inputRef}
- type="url"
- className="form-control"
- placeholder="https://example.com or https://youtube.com/watch?v=..."
- value={url}
- onInput={(e) => setUrl((e.target as HTMLInputElement).value)}
- />
- </FormGroup>
- <FormGroup name="mode" label="Paste as">
- <div className="btn-group w-100">
- {(["mention", "url", "embed"] as const).map((m) => (
- <button
- key={m}
- type="button"
- className={`btn btn-sm ${mode === m ? "btn-primary" : "btn-outline-secondary"}`}
- onClick={() => setMode(m)}
- >
- {m === "mention" ? "@ Mention" : m === "url" ? "URL" : "Embed"}
- </button>
- ))}
- </div>
- </FormGroup>
- </Modal>
- );
-}
diff --git a/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx b/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx
index 6e9a6abf47..8f2b5b11db 100644
--- a/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx
+++ b/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx
@@ -19,8 +19,6 @@ export interface CKEditorApi {
addHtmlToEditor(html: string): void;
addIncludeNote(noteId: string, boxSize?: BoxSize): void;
addImage(noteId: string): Promise<void>;
- addLinkEmbed(metadata: EmbedMetadata): void;
- addLinkMention(metadata: EmbedMetadata): void;
}
interface CKEditorWithWatchdogProps extends Pick<HTMLProps<HTMLDivElement>, "className" | "tabIndex"> {
@@ -146,38 +144,6 @@ export default function CKEditorWithWatchdog({ containerRef: externalContainerRe
editor?.execute("insertImage", { source: src });
});
},
- addLinkEmbed(metadata: EmbedMetadata) {
- const editor = watchdogRef.current?.editor;
- if (!editor) return;
-
- editor.model.change((writer) => {
- editor.model.insertContent(
- writer.createElement("linkEmbed", {
- url: metadata.url,
- embedType: metadata.embedType,
- title: metadata.title,
- description: metadata.description,
- favicon: metadata.favicon,
- siteName: metadata.siteName,
- image: metadata.image
- })
- );
- });
- },
- addLinkMention(metadata: EmbedMetadata) {
- const editor = watchdogRef.current?.editor;
- if (!editor) return;
-
- editor.model.change((writer) => {
- editor.model.insertContent(
- writer.createElement("linkMention", {
- url: metadata.url,
- title: metadata.title,
- favicon: metadata.favicon
- })
- );
- });
- },
}));
useLegacyImperativeHandlers({
diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsx
index 06409c4e80..d855029b11 100644
--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx
+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx
@@ -135,13 +135,8 @@ export default function EditableText({ note, parentComponent, ntxId, noteContext
});
},
loadIncludedNote,
- // Link embed functionality
- addLinkEmbedToTextCommand() {
- if (!editorApiRef.current) return;
- parentComponent?.triggerCommand("showLinkEmbedDialog", {
- editorApi: editorApiRef.current,
- });
- },
+ // 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);
},
diff --git a/apps/client/src/widgets/type_widgets/text/LinkEmbed.css b/apps/client/src/widgets/type_widgets/text/LinkEmbed.css
index 8e314aee68..4027f4e941 100644
--- a/apps/client/src/widgets/type_widgets/text/LinkEmbed.css
+++ b/apps/client/src/widgets/type_widgets/text/LinkEmbed.css
@@ -1,94 +1,7 @@
/* ==========================================================================
- Link Embed – paste popup, mention, embed/card, loading
+ Link previews - inline mention, card, video embed
========================================================================== */
-/* ---------- Loading dots (bouncing) ---------- */
-
-.link-embed-loader {
- display: inline-flex;
- gap: 4px;
- align-items: center;
- padding: 8px 12px;
-}
-
-.link-embed-loader-dot {
- width: 6px;
- height: 6px;
- border-radius: 50%;
- background: var(--muted-text-color, #999);
- animation: link-embed-bounce 1.2s infinite ease-in-out;
-}
-
-.link-embed-loader-dot:nth-child(2) { animation-delay: 0.15s; }
-.link-embed-loader-dot:nth-child(3) { animation-delay: 0.3s; }
-
-@keyframes link-embed-bounce {
- 0%, 80%, 100% { transform: scale(0.6); opacity: 0.4; }
- 40% { transform: scale(1); opacity: 1; }
-}
-
-/* ---------- Paste popup ---------- */
-
-.link-paste-popup {
- background: var(--main-background-color, #fff);
- border: 1px solid var(--muted-text-color, #ddd);
- border-radius: 8px;
- padding: 4px;
- box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
- display: flex;
- flex-direction: column;
- min-width: 150px;
- opacity: 0;
- transform: translateY(-4px);
- transition: opacity 0.12s ease, transform 0.12s ease;
-}
-
-.link-paste-popup-visible {
- opacity: 1;
- transform: translateY(0);
-}
-
-.link-paste-popup-header {
- font-size: 0.72em;
- font-weight: 600;
- text-transform: uppercase;
- letter-spacing: 0.04em;
- color: var(--muted-text-color, #999);
- padding: 4px 10px 2px;
-}
-
-.link-paste-option {
- display: flex;
- align-items: center;
- gap: 8px;
- padding: 6px 10px;
- border: none;
- background: none;
- border-radius: 6px;
- cursor: pointer;
- font-size: 0.88em;
- color: var(--main-text-color, #333);
- transition: background-color 0.1s;
- width: 100%;
- text-align: left;
-}
-
-.link-paste-option:hover,
-.link-paste-option-active {
- background: var(--hover-item-background-color, rgba(0, 0, 0, 0.06));
-}
-
-.link-paste-option-icon {
- width: 20px;
- text-align: center;
- font-size: 1em;
- flex-shrink: 0;
-}
-
-.link-paste-option-label {
- flex: 1;
-}
-
/* ---------- Inline mention (favicon + title) ---------- */
.link-mention {
diff --git a/packages/ckeditor5/src/index.ts b/packages/ckeditor5/src/index.ts
index 5b9ae768f6..3fb4e69c2f 100644
--- a/packages/ckeditor5/src/index.ts
+++ b/packages/ckeditor5/src/index.ts
@@ -2,6 +2,7 @@ import "ckeditor5/ckeditor5.css";
// Premium features CSS loaded dynamically with the plugins
// import 'ckeditor5-premium-features/ckeditor5-premium-features.css';
import "./theme/code_block_toolbar.css";
+import "./theme/link_embed_form.css";
import { COMMON_PLUGINS, CORE_PLUGINS, POPUP_EDITOR_PLUGINS } from "./plugins.js";
import { BalloonEditor, DecoupledEditor, FindAndReplaceEditing, FindCommand } from "ckeditor5";
import "./translation_overrides.js";
diff --git a/packages/ckeditor5/src/plugins/link_embed_form.spec.ts b/packages/ckeditor5/src/plugins/link_embed_form.spec.ts
new file mode 100644
index 0000000000..8a21b65c40
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/link_embed_form.spec.ts
@@ -0,0 +1,275 @@
+import { BlockQuote, ClassicEditor, ContextualBalloon, Essentials, Link, Paragraph, Undo, _setModelData as setModelData } from "ckeditor5";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { createTestEditor } from "../../test/editor-kit.js";
+import { installGlobMock } from "../../test/globals-test-kit.js";
+import LinkEmbedFormView from "./link_embed_form.js";
+import LinkEmbed, { LINK_EMBED_COMMAND } from "./linkembed.js";
+
+const META = {
+ url: "https://example.com/",
+ embedType: "opengraph",
+ title: "Example title",
+ description: "Some description",
+ favicon: "https://example.com/favicon.ico",
+ siteName: "Example",
+ image: "https://example.com/image.png"
+};
+
+describe("LinkEmbedFormView", () => {
+ let editor: ClassicEditor;
+ let fetchLinkMetadata: 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,
+ // 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>");
+ });
+
+ /** Opens the balloon by clicking the toolbar button, and returns the form inside it. */
+ function openForm(): LinkEmbedFormView {
+ const button = editor.ui.componentFactory.create("linkEmbed") as unknown as { fire(name: string): void };
+ button.fire("execute");
+
+ const form = editor.plugins.get(ContextualBalloon).visibleView;
+ if (!(form instanceof LinkEmbedFormView)) {
+ throw new Error("The balloon does not hold the link-preview form.");
+ }
+ return form;
+ }
+
+ function isInBalloon(form: LinkEmbedFormView) {
+ return editor.plugins.get(ContextualBalloon).hasView(form);
+ }
+
+ /** Types into the URL field the way a user does, so the input event fires. */
+ function typeUrl(form: LinkEmbedFormView, url: string) {
+ const input = form.urlInputView.fieldView.element;
+ if (!input) {
+ throw new Error("The URL field is not rendered.");
+ }
+ input.value = url;
+ input.dispatchEvent(new Event("input"));
+ }
+
+ // -----------------------------------------------------------------------
+ // Structure
+ // -----------------------------------------------------------------------
+
+ it("wears CKEditor's own link-form classes, so it matches the native link balloon", () => {
+ const form = openForm();
+ const classes = form.element?.classList;
+
+ expect(classes?.contains("ck-link-form")).toBe(true);
+ expect(classes?.contains("ck-responsive-form")).toBe(true);
+ expect(form.element?.tagName).toBe("FORM");
+ });
+
+ it("holds a heading, a URL field, a display-mode selector and an Insert button — and nothing else", () => {
+ const form = openForm();
+
+ expect(form.element?.querySelector(".ck-link-embed-form__heading")?.textContent).toBe("Link preview");
+ expect(form.urlInputView.label).toBe("URL");
+ expect(form.urlInputView.fieldView.placeholder).toBe("http://");
+ expect(form.modeDropdownView.buttonView.label).toBe("Card");
+
+ // A text button, like the Insert button of the editor's own link form.
+ expect(form.insertButtonView.label).toBe("Insert");
+ expect(form.insertButtonView.withText).toBe(true);
+ expect(form.insertButtonView.element?.classList.contains("ck-button-action")).toBe(true);
+ expect(form.insertButtonView.element?.classList.contains("ck-button_with-text")).toBe(true);
+
+ // The dropdown and the button share a row below the field.
+ const actions = form.element?.querySelector(".ck-link-embed-form__actions");
+ expect(actions?.contains(form.modeDropdownView.element ?? null)).toBe(true);
+ expect(actions?.contains(form.insertButtonView.element ?? null)).toBe(true);
+ });
+
+ it("puts the caret straight in the URL field, so the user can just type", () => {
+ const form = openForm();
+
+ expect(document.activeElement).toBe(form.urlInputView.fieldView.element);
+ });
+
+ it("resolves its labels through the host's translation bridge when there is one", async () => {
+ editor = await createTestEditor(
+ [Essentials, Paragraph, Link, Undo, LinkEmbed],
+ { translate: (key: string) => `translated:${key}` } as unknown as Parameters<typeof createTestEditor>[1]
+ );
+ setModelData(editor.model, "<paragraph>[]</paragraph>");
+
+ const form = openForm();
+ expect(form.urlInputView.label).toBe("translated:link_embed.url");
+ expect(form.insertButtonView.label).toBe("translated:link_embed.insert");
+ });
+
+ // -----------------------------------------------------------------------
+ // The mode selector
+ // -----------------------------------------------------------------------
+
+ it("defaults to Card, and to Embed once the URL turns out to have a player", () => {
+ const form = openForm();
+ expect(form.mode).toBe("card");
+ expect(form.embedAvailable).toBe(false);
+
+ typeUrl(form, "https://youtube.com/watch?v=abc12345678");
+ expect(form.embedAvailable).toBe(true);
+ expect(form.mode).toBe("embed");
+
+ // Back to an ordinary page: the player is neither offered nor kept.
+ typeUrl(form, "https://example.com/article");
+ expect(form.embedAvailable).toBe(false);
+ expect(form.mode).toBe("card");
+ });
+
+ it("stops following the URL once the user picks a mode, but never leaves them on an impossible one", () => {
+ const form = openForm();
+
+ form.modeDropdownView.fire("execute", { source: { _displayMode: "inline" } });
+ form.mode = "inline";
+
+ // The user has spoken: an embeddable URL no longer overrules them.
+ typeUrl(form, "https://youtube.com/watch?v=abc12345678");
+ expect(form.mode).toBe("inline");
+
+ // But a mode that the URL cannot support falls back rather than being submitted.
+ form.mode = "embed";
+ typeUrl(form, "https://example.com/article");
+ expect(form.mode).toBe("card");
+ });
+
+ // -----------------------------------------------------------------------
+ // Submitting
+ // -----------------------------------------------------------------------
+
+ it("keeps Insert disabled until a URL is typed", () => {
+ const form = openForm();
+ expect(form.insertButtonView.isEnabled).toBe(false);
+
+ typeUrl(form, "https://example.com/article");
+ expect(form.insertButtonView.isEnabled).toBe(true);
+ });
+
+ it("inserts the preview, closes the balloon and leaves the form ready for next time", async () => {
+ const form = openForm();
+ typeUrl(form, "https://example.com/article");
+
+ form.fire("submit");
+ await vi.waitFor(() => expect(isInBalloon(form)).toBe(false));
+
+ expect(fetchLinkMetadata).toHaveBeenCalledWith("https://example.com/article");
+ expect(editor.getData()).toContain('data-url="https://example.com/article"');
+
+ // Reopening starts blank rather than showing the last URL.
+ const reopened = openForm();
+ expect(reopened.url).toBe("");
+ expect(reopened.mode).toBe("card");
+ });
+
+ it("defaults the scheme, so a bare domain is not inserted as a dead link", async () => {
+ const form = openForm();
+ typeUrl(form, "example.com/article");
+
+ form.fire("submit");
+ await vi.waitFor(() => expect(isInBalloon(form)).toBe(false));
+
+ expect(fetchLinkMetadata).toHaveBeenCalledWith("https://example.com/article");
+ });
+
+ it("does nothing when submitted with an empty URL", () => {
+ const form = openForm();
+
+ form.fire("submit");
+
+ expect(fetchLinkMetadata).not.toHaveBeenCalled();
+ expect(isInBalloon(form)).toBe(true);
+ });
+
+ it("refuses a URL that cannot be a preview, leaving the form open", async () => {
+ const form = openForm();
+ typeUrl(form, "javascript:alert(1)");
+
+ form.fire("submit");
+
+ expect(fetchLinkMetadata).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) => {
+ resolveFetch = resolve;
+ }));
+
+ const form = openForm();
+ typeUrl(form, "https://example.com/article");
+
+ form.fire("submit");
+ expect(form.isFetching).toBe(true);
+ expect(form.insertButtonView.isEnabled).toBe(false);
+ expect(form.modeDropdownView.isEnabled).toBe(false);
+
+ // A second Enter while the first fetch is in flight must not fetch again.
+ form.fire("submit");
+ expect(fetchLinkMetadata).toHaveBeenCalledTimes(1);
+
+ resolveFetch?.({ ...META, url: "https://example.com/article" });
+ await vi.waitFor(() => expect(isInBalloon(form)).toBe(false));
+ expect(form.isFetching).toBe(false);
+ });
+
+ // -----------------------------------------------------------------------
+ // Dismissing
+ // -----------------------------------------------------------------------
+
+ it("closes on Esc without inserting anything", () => {
+ const form = openForm();
+ typeUrl(form, "https://example.com/article");
+
+ const before = editor.getData();
+ form.keystrokes.press({ keyCode: 27, preventDefault: () => {}, stopPropagation: () => {} } as unknown as KeyboardEvent);
+
+ expect(isInBalloon(form)).toBe(false);
+ expect(fetchLinkMetadata).not.toHaveBeenCalled();
+ expect(editor.getData()).toBe(before);
+ });
+
+ it("closes when the user clicks away from it", () => {
+ const form = openForm();
+ expect(isInBalloon(form)).toBe(true);
+
+ // clickOutsideHandler watches for a mousedown outside the balloon.
+ document.body.dispatchEvent(new MouseEvent("mousedown", { bubbles: true }));
+
+ expect(isInBalloon(form)).toBe(false);
+ expect(fetchLinkMetadata).not.toHaveBeenCalled();
+ });
+
+ it("does not stack a second form when the button is clicked twice", () => {
+ const form = openForm();
+ openForm();
+
+ expect(editor.plugins.get(ContextualBalloon).visibleView).toBe(form);
+ });
+
+ it("only offers the insert command where a preview may go", () => {
+ const command = editor.commands.get(LINK_EMBED_COMMAND);
+ expect(command?.isEnabled).toBe(true);
+
+ editor.enableReadOnlyMode("test");
+ expect(command?.isEnabled).toBe(false);
+ editor.disableReadOnlyMode("test");
+ });
+});
diff --git a/packages/ckeditor5/src/plugins/link_embed_form.ts b/packages/ckeditor5/src/plugins/link_embed_form.ts
new file mode 100644
index 0000000000..be9ed3bb3b
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/link_embed_form.ts
@@ -0,0 +1,223 @@
+import {
+ ButtonView,
+ Collection,
+ createDropdown,
+ createLabeledInputText,
+ DropdownButtonView,
+ FocusCycler,
+ FocusTracker,
+ KeystrokeHandler,
+ LabeledFieldView,
+ type DropdownView,
+ type FocusableView,
+ type InputTextView,
+ type ListDropdownButtonDefinition,
+ type Locale,
+ addListToDropdown,
+ submitHandler,
+ View,
+ ViewCollection,
+ ViewModel
+} from "ckeditor5";
+
+import { LINK_DISPLAY_MODES, type LinkDisplayMode } from "./linkembed.js";
+
+/** Resolves a translation key, falling back to the given English text. See `translate.ts`. */
+type Translate = (key: string, fallback: string) => string;
+
+/**
+ * The balloon form behind the "Link preview" toolbar button: a URL field, a display-mode selector
+ * and an Insert button.
+ *
+ * It wears CKEditor's own `ck-link-form ck-responsive-form` classes rather than a Trilium modal, so
+ * it looks and behaves exactly like the editor's native link balloon — including its narrow-screen
+ * layout — and so inserting a preview never leaves the editor.
+ */
+export default class LinkEmbedFormView extends View {
+
+ /** The URL to preview. */
+ declare public url: string;
+ /** The shape the preview will take. */
+ declare public mode: LinkDisplayMode;
+ /** Whether the URL supports a player (a YouTube link, say); "Embed" is hidden when it does not. */
+ declare public embedAvailable: boolean;
+ /** True while the metadata is being fetched, which disables the form. */
+ declare public isFetching: boolean;
+
+ public readonly urlInputView: LabeledFieldView<InputTextView>;
+ public readonly modeDropdownView: DropdownView;
+ public readonly insertButtonView: ButtonView;
+
+ public readonly focusTracker = new FocusTracker();
+ public readonly keystrokes = new KeystrokeHandler();
+
+ private readonly _focusables = new ViewCollection<FocusableView>();
+ private readonly _focusCycler: FocusCycler;
+
+ constructor(locale: Locale, translate: Translate) {
+ super(locale);
+
+ this.set("url", "");
+ this.set("mode", "card");
+ this.set("embedAvailable", false);
+ this.set("isFetching", false);
+
+ this.urlInputView = this._createUrlInput(locale, translate);
+ this.modeDropdownView = this._createModeDropdown(locale, translate);
+ this.insertButtonView = this._createInsertButton(locale, translate);
+
+ this.setTemplate({
+ tag: "form",
+ attributes: {
+ // CKEditor's own link-balloon classes: same paddings, same responsive behaviour.
+ class: ["ck", "ck-link-form", "ck-responsive-form", "ck-link-embed-form"],
+ tabindex: "-1"
+ },
+ children: [
+ {
+ tag: "div",
+ attributes: { class: ["ck", "ck-link-embed-form__heading"] },
+ children: [{ text: translate("link_embed.title", "Link preview") }]
+ },
+ this.urlInputView,
+ {
+ tag: "div",
+ attributes: { class: ["ck", "ck-link-embed-form__actions"] },
+ children: [
+ this.modeDropdownView,
+ this.insertButtonView
+ ]
+ }
+ ]
+ });
+
+ this._focusCycler = new FocusCycler({
+ focusables: this._focusables,
+ focusTracker: this.focusTracker,
+ keystrokeHandler: this.keystrokes,
+ actions: {
+ focusPrevious: "shift + tab",
+ focusNext: "tab"
+ }
+ });
+ }
+
+ public override render(): void {
+ super.render();
+
+ // Turns a native form submit (the Enter key included) into the view's own `submit` event.
+ submitHandler({ view: this });
+
+ for (const view of [this.urlInputView, this.modeDropdownView, this.insertButtonView]) {
+ this._focusables.add(view);
+ /* v8 ignore next -- a child view rendered as part of this template always has an element */
+ if (view.element) {
+ this.focusTracker.add(view.element);
+ }
+ }
+
+ /* v8 ignore next -- super.render() has just built this view's element */
+ if (this.element) {
+ this.keystrokes.listenTo(this.element);
+ }
+ }
+
+ public override destroy(): void {
+ super.destroy();
+ this.focusTracker.destroy();
+ this.keystrokes.destroy();
+ }
+
+ /** Resets the form to a blank state, ready for the next insertion. */
+ public reset(): void {
+ this.url = "";
+ this.mode = "card";
+ this.embedAvailable = false;
+ this.isFetching = false;
+ }
+
+ public focus(): void {
+ this._focusCycler.focusFirst();
+ }
+
+ private _createUrlInput(locale: Locale, translate: Translate) {
+ const urlInput = new LabeledFieldView(locale, createLabeledInputText);
+ urlInput.label = translate("link_embed.url", "URL");
+ urlInput.fieldView.placeholder = "http://";
+
+ // Two-way: the field drives `url`, and reset() drives the field.
+ urlInput.fieldView.bind("value").to(this, "url");
+ urlInput.fieldView.on("input", () => {
+ /* v8 ignore next -- the input event can only come from a rendered element */
+ this.url = urlInput.fieldView.element?.value ?? "";
+ });
+ urlInput.bind("isEnabled").to(this, "isFetching", (isFetching) => !isFetching);
+
+ return urlInput;
+ }
+
+ private _createModeDropdown(locale: Locale, translate: Translate) {
+ const dropdown = createDropdown(locale, DropdownButtonView);
+
+ dropdown.buttonView.set({ withText: true, tooltip: true });
+ dropdown.buttonView.bind("label").to(this, "mode", (mode) => modeLabel(mode, translate));
+ dropdown.bind("isEnabled").to(this, "isFetching", (isFetching) => !isFetching);
+
+ const items = new Collection<ListDropdownButtonDefinition>();
+ for (const modeDef of LINK_DISPLAY_MODES) {
+ const definition: ListDropdownButtonDefinition = {
+ type: "button",
+ model: new ViewModel({
+ _displayMode: modeDef.value,
+ label: translate(modeDef.labelKey, modeDef.label),
+ role: "menuitemradio",
+ withText: true
+ })
+ };
+
+ definition.model.bind("isOn").to(this, "mode", (mode) => mode === modeDef.value);
+
+ // A player only exists for a URL that has one.
+ if (modeDef.value === "embed") {
+ definition.model.bind("isVisible").to(this, "embedAvailable");
+ }
+
+ items.add(definition);
+ }
+ addListToDropdown(dropdown, items);
+
+ dropdown.on("execute", (evt) => {
+ this.mode = (evt.source as unknown as { _displayMode: LinkDisplayMode })._displayMode;
+ });
+
+ return dropdown;
+ }
+
+ private _createInsertButton(locale: Locale, translate: Translate) {
+ const button = new ButtonView(locale);
+
+ // A text button, like the Insert button of the editor's own link form.
+ button.set({
+ label: translate("link_embed.insert", "Insert"),
+ withText: true,
+ type: "submit",
+ class: "ck-button-action ck-button-bold"
+ });
+
+ // A URL is required, and nothing may be submitted twice while the first fetch is in flight.
+ button.bind("isEnabled").to(
+ this, "url",
+ this, "isFetching",
+ (url, isFetching) => !!String(url).trim() && !isFetching
+ );
+
+ return button;
+ }
+}
+
+/** A display mode's label, in the user's language. */
+function modeLabel(mode: LinkDisplayMode, translate: Translate): string {
+ const found = LINK_DISPLAY_MODES.find((modeDef) => modeDef.value === mode);
+ /* v8 ignore next -- `mode` is only ever set from LINK_DISPLAY_MODES, so the fallback is unreachable */
+ return found ? translate(found.labelKey, found.label) : String(mode);
+}
diff --git a/packages/ckeditor5/src/plugins/link_embed_toolbar.ts b/packages/ckeditor5/src/plugins/link_embed_toolbar.ts
index ddcfbb3e1c..e9e94a1add 100644
--- a/packages/ckeditor5/src/plugins/link_embed_toolbar.ts
+++ b/packages/ckeditor5/src/plugins/link_embed_toolbar.ts
@@ -21,6 +21,7 @@ import LinkEmbed, {
type LinkDisplayMode
} from "./linkembed.js";
import { createCopyUrlButton } from "./copy_link_url.js";
+import { translate } from "./translate.js";
export default class LinkEmbedToolbar extends Plugin {
@@ -76,18 +77,20 @@ class LinkEmbedDisplayDropdown extends Plugin {
componentFactory.add("linkEmbedDisplayDropdown", _locale => {
const dropdownView = createDropdown(editor.locale, DropdownButtonView);
+ const displayLabel = translate(editor, "link_embed.display", "Display");
+
dropdownView.buttonView.set({
withText: true,
tooltip: true,
- label: "Display"
+ label: displayLabel
});
dropdownView.bind("isEnabled").to(command, "isEnabled");
dropdownView.buttonView.bind("label").to(command, "value", (value) => {
- if (!value) return "Display";
+ if (!value) return displayLabel;
const mode = LINK_DISPLAY_MODES.find(m => m.value === value);
- return mode?.label ?? value;
+ return mode ? translate(editor, mode.labelKey, mode.label) : value;
});
dropdownView.on("execute", evt => {
@@ -111,7 +114,7 @@ class LinkEmbedDisplayDropdown extends Plugin {
type: "button",
model: new ViewModel({
_displayMode: modeDef.value,
- label: modeDef.label,
+ label: translate(this.editor, modeDef.labelKey, modeDef.label),
role: "menuitemradio",
withText: true
})
diff --git a/packages/ckeditor5/src/plugins/linkembed.spec.ts b/packages/ckeditor5/src/plugins/linkembed.spec.ts
index 31600be221..3203add198 100644
--- a/packages/ckeditor5/src/plugins/linkembed.spec.ts
+++ b/packages/ckeditor5/src/plugins/linkembed.spec.ts
@@ -4,6 +4,7 @@ import {
_setModelData as setModelData,
BlockQuote,
ClassicEditor,
+ ContextualBalloon,
Essentials,
Heading,
Link,
@@ -16,6 +17,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import { createTestEditor } from "../../test/editor-kit.js";
import { installGlobMock } from "../../test/globals-test-kit.js";
+import LinkEmbedFormView from "./link_embed_form.js";
import LinkEmbed, { CHANGE_LINK_DISPLAY_COMMAND, LINK_EMBED_COMMAND, REMOVE_LINK_EMBED_COMMAND } from "./linkembed.js";
const META = {
@@ -73,29 +75,56 @@ describe("LinkEmbed", () => {
expect(editor.ui.componentFactory.has("linkEmbed")).toBe(true);
});
- it("binds the button to the insert command and executes it on click", () => {
+ it("binds the button to the insert command and opens the balloon form on click", () => {
+ setModelData(editor.model, "<paragraph>foo[]bar</paragraph>");
+
const view = editor.ui.componentFactory.create("linkEmbed") as unknown as {
- isOn: boolean;
isEnabled: boolean;
fire(name: string): void;
};
const command = editor.commands.get(LINK_EMBED_COMMAND);
-
expect(view.isEnabled).toBe(command?.isEnabled);
- const spy = vi.spyOn(editor, "execute");
+ const balloon = editor.plugins.get(ContextualBalloon);
+ expect(balloon.visibleView).toBeNull();
+
+ // The insert flow now happens in the editor's own balloon, not in a Trilium modal.
view.fire("execute");
- expect(spy).toHaveBeenCalledWith(LINK_EMBED_COMMAND);
+ expect(balloon.visibleView).toBeInstanceOf(LinkEmbedFormView);
});
// -----------------------------------------------------------------------
// InsertLinkEmbedCommand
// -----------------------------------------------------------------------
- it("triggers addLinkEmbedToText on the component when executed", () => {
- setModelData(editor.model, "<paragraph>foo[]bar</paragraph>");
- editor.execute(LINK_EMBED_COMMAND);
- expect(triggerCommand).toHaveBeenCalledWith("addLinkEmbedToText");
+ it("inserts a preview for a URL, storing all the metadata whatever the mode", async () => {
+ const url = "https://example.com/article";
+ setModelData(editor.model, "<paragraph>[]</paragraph>");
+
+ // An inline mention keeps the description and image it does not itself show, so switching it
+ // to a card later never has to go back to the network.
+ await editor.execute(LINK_EMBED_COMMAND, { url, mode: "inline" });
+
+ expect(fetchLinkMetadata).toHaveBeenCalledWith(url);
+ const mention = findElement(editor, "linkMention");
+ expect(mention?.getAttribute("url")).toBe(url);
+ expect(mention?.getAttribute("description")).toBe(META.description);
+ expect(mention?.getAttribute("image")).toBe(META.image);
+ expect(mention?.getAttribute("siteName")).toBe(META.siteName);
+ });
+
+ it("forces the opengraph type for a card, and keeps the detected one for an embed", async () => {
+ const url = "https://youtube.com/watch?v=abc12345678";
+ fetchLinkMetadata.mockResolvedValue({ ...META, url, embedType: "youtube" });
+
+ setModelData(editor.model, "<paragraph>[]</paragraph>");
+ await editor.execute(LINK_EMBED_COMMAND, { url, mode: "card" });
+ // A card is an embed that declines to play.
+ expect(findElement(editor, "linkEmbed")?.getAttribute("embedType")).toBe("opengraph");
+
+ setModelData(editor.model, "<paragraph>[]</paragraph>");
+ await editor.execute(LINK_EMBED_COMMAND, { url, mode: "embed" });
+ expect(findElement(editor, "linkEmbed")?.getAttribute("embedType")).toBe("youtube");
});
it("is enabled in a paragraph and disabled when read-only", () => {
@@ -488,9 +517,9 @@ describe("LinkEmbed", () => {
expect(findElement(editor, "linkMention")).toBeUndefined();
expect(editor.getData()).toContain(`<a href="${url}">${url}</a>`);
- // The dialog route is unaffected by the option.
- editor.execute(LINK_EMBED_COMMAND);
- expect(triggerCommand).toHaveBeenCalledWith("addLinkEmbedToText");
+ // Inserting a preview by hand is unaffected by the option: only auto-detection is gated.
+ await editor.execute(LINK_EMBED_COMMAND, { url, mode: "card" });
+ expect(findElement(editor, "linkEmbed")?.getAttribute("url")).toBe(url);
});
it("re-reads a getter on every detected URL, so toggling the option needs no new editor", async () => {
diff --git a/packages/ckeditor5/src/plugins/linkembed.ts b/packages/ckeditor5/src/plugins/linkembed.ts
index 17e17be84d..61879c748c 100644
--- a/packages/ckeditor5/src/plugins/linkembed.ts
+++ b/packages/ckeditor5/src/plugins/linkembed.ts
@@ -1,6 +1,8 @@
import { type BlockChildLike, chooseLinkPreviewKind, isHttpUrl, isUrlAloneInBlock } from '@triliumnext/commons';
-import { ButtonView, Command, Plugin, toWidget, viewToModelPositionOutsideModelElement, Widget, type Observable } from 'ckeditor5';
+import { ButtonView, clickOutsideHandler, Command, ContextualBalloon, Plugin, toWidget, viewToModelPositionOutsideModelElement, Widget, type Editor, type Observable } from 'ckeditor5';
import linkEmbedIcon from '../icons/link-embed.svg?raw';
+import LinkEmbedFormView from './link_embed_form.js';
+import { translate } from './translate.js';
import { preventCKEditorHandling } from './widget_utils.js';
export const LINK_EMBED_COMMAND = 'insertLinkEmbed';
@@ -8,9 +10,9 @@ export const CHANGE_LINK_DISPLAY_COMMAND = 'changeLinkDisplay';
export const REMOVE_LINK_EMBED_COMMAND = 'removeLinkEmbed';
export const LINK_DISPLAY_MODES = [
- { value: 'inline', label: 'Inline' },
- { value: 'card', label: 'Card' },
- { value: 'embed', label: 'Embed' }
+ { value: 'inline', label: 'Inline', labelKey: 'link_embed.mode_inline' },
+ { value: 'card', label: 'Card', labelKey: 'link_embed.mode_card' },
+ { value: 'embed', label: 'Embed', labelKey: 'link_embed.mode_embed' }
] as const;
export type LinkDisplayMode = typeof LINK_DISPLAY_MODES[number]['value'];
@@ -23,7 +25,21 @@ export default class LinkEmbed extends Plugin {
}
}
+/**
+ * The "Link preview" toolbar button and the balloon form it opens.
+ *
+ * The form lives inside the editor — the same balloon the native link button uses — rather than in a
+ * Trilium modal, so inserting a preview never leaves the editing surface and needs no round trip
+ * out to the app and back.
+ */
class LinkEmbedUI extends Plugin {
+
+ static get requires() {
+ return [ContextualBalloon];
+ }
+
+ private _formView: LinkEmbedFormView | null = null;
+
init() {
const editor = this.editor;
@@ -39,16 +55,140 @@ class LinkEmbedUI extends Plugin {
/* v8 ignore next -- LinkEmbedEditing always registers LINK_EMBED_COMMAND (both are required by LinkEmbed), so the no-command branch is unreachable */
if (command) {
- buttonView.bind('isOn', 'isEnabled').to(
- command as Observable & { value: boolean } & { isEnabled: boolean },
- 'value', 'isEnabled'
- );
+ buttonView.bind('isEnabled').to(command as Observable & { isEnabled: boolean }, 'isEnabled');
}
- this.listenTo(buttonView, 'execute', () => editor.execute(LINK_EMBED_COMMAND));
+ this.listenTo(buttonView, 'execute', () => this._showForm());
return buttonView;
});
}
+
+ override destroy() {
+ super.destroy();
+ this._formView?.destroy();
+ }
+
+ private _showForm() {
+ const editor = this.editor;
+ const balloon = editor.plugins.get(ContextualBalloon);
+ const form = this._getFormView();
+
+ if (balloon.hasView(form)) return;
+
+ form.reset();
+ balloon.add({
+ view: form,
+ position: {
+ target: () => {
+ const view = editor.editing.view;
+ const range = view.document.selection.getFirstRange();
+ /* v8 ignore next -- the editing view's selection always has a range while the editor is focused */
+ if (!range) return editor.ui.getEditableElement() as HTMLElement;
+ return view.domConverter.viewRangeToDom(range);
+ }
+ }
+ });
+ form.focus();
+ }
+
+ private _hideForm() {
+ const balloon = this.editor.plugins.get(ContextualBalloon);
+ const form = this._formView;
+
+ /* v8 ignore next -- the form is only ever hidden from its own handlers, so by then it exists and is shown */
+ if (!form || !balloon.hasView(form)) return;
+
+ balloon.remove(form);
+ this.editor.editing.view.focus();
+ }
+
+ private _getFormView(): LinkEmbedFormView {
+ if (this._formView) return this._formView;
+
+ const editor = this.editor;
+ const form = new LinkEmbedFormView(editor.locale, (key, fallback) => translate(editor, key, fallback));
+ this._formView = form;
+
+ // The mode selector only offers "Embed" for a URL that has a player behind it — the same
+ // question the widget toolbar's dropdown asks of an existing preview.
+ form.on('change:url', () => {
+ const embedAvailable = detectEmbedTypeFor(editor, form.url) !== 'opengraph';
+ form.embedAvailable = embedAvailable;
+
+ // Follow the URL until the user overrules it: a video wants its player, anything else a card.
+ if (!this._modePickedByUser) {
+ form.mode = embedAvailable ? 'embed' : 'card';
+ } else if (!embedAvailable && form.mode === 'embed') {
+ form.mode = 'card';
+ }
+ });
+
+ form.modeDropdownView.on('execute', () => {
+ this._modePickedByUser = true;
+ });
+
+ form.on('submit', () => {
+ void this._insert(form);
+ });
+
+ // Esc and clicking away dismiss the form, exactly as they do for the native link balloon.
+ form.keystrokes.set('Esc', (_data, cancel) => {
+ this._hideForm();
+ cancel();
+ });
+ clickOutsideHandler({
+ emitter: form,
+ activator: () => this.editor.plugins.get(ContextualBalloon).hasView(form),
+ contextElements: () => [this.editor.plugins.get(ContextualBalloon).view.element as HTMLElement],
+ callback: () => this._hideForm()
+ });
+
+ return form;
+ }
+
+ private _modePickedByUser = false;
+
+ private async _insert(form: LinkEmbedFormView) {
+ // The Insert button is disabled mid-fetch, but Enter fires `submit` on the form itself, so
+ // the guard has to live here or a second Enter would fetch and insert twice.
+ if (form.isFetching) return;
+
+ const url = normalizeUrl(form.url);
+ if (!url) return;
+
+ // The metadata fetch takes a moment (the server reads the page and downloads the image), so
+ // the form stays open and disabled meanwhile rather than vanishing into an apparent no-op.
+ form.isFetching = true;
+ try {
+ await this.editor.execute(LINK_EMBED_COMMAND, { url, mode: form.mode });
+ } finally {
+ form.isFetching = false;
+ }
+
+ this._modePickedByUser = false;
+ this._hideForm();
+ }
+}
+
+/**
+ * Makes a typed URL absolute, defaulting the scheme the way the editor's own link field does.
+ * Returns null when what was typed cannot be a link preview at all.
+ */
+function normalizeUrl(rawUrl: string): string | null {
+ const trimmed = rawUrl.trim();
+ if (!trimmed) return null;
+
+ const withScheme = /^[a-z][a-z0-9+.-]*:/i.test(trimmed) ? trimmed : `https://${trimmed}`;
+ return isHttpUrl(withScheme) ? withScheme : null;
+}
+
+/** Asks the host what kind of preview a URL supports. */
+function detectEmbedTypeFor(editor: Editor, url: string): string {
+ if (!url.trim()) return 'opengraph';
+
+ const editorEl = editor.editing.view.getDomRoot();
+ const component = glob.getComponentByEl<EditorComponent>(editorEl);
+ return component.detectEmbedType(normalizeUrl(url) ?? url);
}
// ---------------------------------------------------------------------------
@@ -238,11 +378,34 @@ class LinkEmbedEditing extends Plugin {
}
}
+/**
+ * Inserts a preview for a URL: fetches its metadata through the host, then puts the widget in.
+ *
+ * All the metadata is written onto the element whichever shape is chosen — an inline mention stores
+ * the description and image it does not itself show — so that switching modes later, via the widget
+ * toolbar's Display dropdown, never has to go back to the network.
+ */
class InsertLinkEmbedCommand extends Command {
- override execute() {
- const editorEl = this.editor.editing.view.getDomRoot();
- const component = glob.getComponentByEl(editorEl);
- component.triggerCommand('addLinkEmbedToText');
+ override async execute({ url, mode }: { url: string; mode: LinkDisplayMode }) {
+ const editor = this.editor;
+ const editorEl = editor.editing.view.getDomRoot();
+ const component = glob.getComponentByEl<EditorComponent>(editorEl);
+
+ const metadata = await component.fetchLinkMetadata(url);
+
+ editor.model.change((writer) => {
+ editor.model.insertContent(writer.createElement(mode === 'inline' ? 'linkMention' : 'linkEmbed', {
+ url: metadata.url,
+ // A card is an embed that declines to play: forcing "opengraph" is what tells the
+ // renderer to draw the static card rather than the provider's player.
+ embedType: mode === 'card' ? 'opengraph' : metadata.embedType,
+ title: metadata.title,
+ description: metadata.description,
+ favicon: metadata.favicon,
+ siteName: metadata.siteName,
+ image: metadata.image
+ }));
+ });
}
override refresh() {
diff --git a/packages/ckeditor5/src/plugins/translate.ts b/packages/ckeditor5/src/plugins/translate.ts
new file mode 100644
index 0000000000..de9f990a8a
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/translate.ts
@@ -0,0 +1,11 @@
+import type { Editor } from "ckeditor5";
+
+/**
+ * Resolves a Trilium translation key through the host-provided `translate` bridge (the client sets
+ * it in `buildConfig`). Falls back to the English text when no bridge is configured — a standalone
+ * editor, or a test — so a plugin never renders a raw translation key at the user.
+ */
+export function translate(editor: Editor, key: string, fallback: string): string {
+ const translateFn = editor.config.get("translate") as ((key: string) => string) | undefined;
+ return translateFn ? translateFn(key) : fallback;
+}
diff --git a/packages/ckeditor5/src/theme/link_embed_form.css b/packages/ckeditor5/src/theme/link_embed_form.css
new file mode 100644
index 0000000000..37ff717858
--- /dev/null
+++ b/packages/ckeditor5/src/theme/link_embed_form.css
@@ -0,0 +1,40 @@
+/*
+ * The link-preview balloon form.
+ *
+ * It wears CKEditor's own `.ck-link-form.ck-responsive-form` so the paddings, the field styling and
+ * the narrow-screen behaviour come for free. What differs is the layout: a heading, the URL field,
+ * and then the display-mode dropdown next to the Insert button on a row of their own.
+ */
+.ck.ck-link-embed-form {
+ display: flex;
+ flex-direction: column;
+ align-items: stretch;
+}
+
+.ck.ck-link-embed-form__heading {
+ font-size: var(--ck-font-size-small);
+ font-weight: bold;
+ margin-bottom: var(--ck-spacing-standard);
+}
+
+.ck.ck-link-embed-form__actions {
+ display: flex;
+ align-items: center;
+ gap: var(--ck-spacing-standard);
+ margin-top: 8px;
+
+ /* The responsive form indents its children; the row places them itself. */
+ & > .ck-dropdown {
+ margin-left: 0;
+
+ & > .ck-button {
+ /* Keep the mode names on one line ("Inline", "Card", "Embed"). */
+ white-space: nowrap;
+ }
+ }
+
+ /* Insert sits at the end of the row. */
+ & > .ck-button-action {
+ margin-left: auto;
+ }
+}