Skip to content

Build your personal knowledge base with Trilium Notes

link previews: allow editing the displayed title

Elian Dorandcc75fba4094
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 062349d482..85e6093aba 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -2459,7 +2459,10 @@
"mode_inline": "Inline",
"mode_card": "Card",
"mode_embed": "Embed",
- "mode_plain": "Plain link"
+ "mode_plain": "Plain link",
+ "edit_title": "Edit title",
+ "title_label": "Title",
+ "save": "Save"
},
"link_context_menu": {
"open_note_in_new_tab": "Open note in a new tab",
diff --git a/packages/ckeditor5/src/plugins/link_embed/link_embed.ts b/packages/ckeditor5/src/plugins/link_embed/link_embed.ts
index d59ab9ffac..052ff251bb 100644
--- a/packages/ckeditor5/src/plugins/link_embed/link_embed.ts
+++ b/packages/ckeditor5/src/plugins/link_embed/link_embed.ts
@@ -5,6 +5,7 @@ import LinkEmbedUI from './link_embed_ui.js';
export {
CHANGE_LINK_DISPLAY_COMMAND,
+ CHANGE_LINK_PREVIEW_TITLE_COMMAND,
LINK_DISPLAY_MODES,
LINK_EMBED_COMMAND,
REMOVE_LINK_EMBED_COMMAND,
diff --git a/packages/ckeditor5/src/plugins/link_embed/link_embed_commands.spec.ts b/packages/ckeditor5/src/plugins/link_embed/link_embed_commands.spec.ts
index cf2adec88d..8e077a7135 100644
--- a/packages/ckeditor5/src/plugins/link_embed/link_embed_commands.spec.ts
+++ b/packages/ckeditor5/src/plugins/link_embed/link_embed_commands.spec.ts
@@ -10,7 +10,7 @@ import {
META,
type LinkEmbedComponentMocks
} from "../../../test/link-embed-kit.js";
-import { CHANGE_LINK_DISPLAY_COMMAND, LINK_EMBED_COMMAND, REMOVE_LINK_EMBED_COMMAND } from "./link_embed_commands.js";
+import { CHANGE_LINK_DISPLAY_COMMAND, CHANGE_LINK_PREVIEW_TITLE_COMMAND, LINK_EMBED_COMMAND, REMOVE_LINK_EMBED_COMMAND } from "./link_embed_commands.js";
describe("LinkEmbed commands", () => {
let editor: ClassicEditor;
@@ -236,6 +236,67 @@ describe("LinkEmbed commands", () => {
expect(editor.getData()).toBe(before);
});
+ // -----------------------------------------------------------------------
+ // ChangeLinkPreviewTitleCommand (the widget toolbar's Edit title button)
+ // -----------------------------------------------------------------------
+
+ it("edits the displayed title, keeping every other attribute and the selection", () => {
+ setModelData(
+ editor.model,
+ '<paragraph>[<linkMention url="https://e.com/page" embedType="opengraph" title="Old | Site | Blog" favicon="F"></linkMention>]</paragraph>'
+ );
+ const command = editor.commands.get(CHANGE_LINK_PREVIEW_TITLE_COMMAND);
+ expect(command?.isEnabled).toBe(true);
+ // The stored title is what the edit form prefills with.
+ expect(command?.value).toBe("Old | Site | Blog");
+
+ editor.execute(CHANGE_LINK_PREVIEW_TITLE_COMMAND, { title: "My own words" });
+
+ const mention = findElement(editor, "linkMention");
+ expect(mention?.getAttribute("title")).toBe("My own words");
+ expect(mention?.getAttribute("url")).toBe("https://e.com/page");
+ expect(mention?.getAttribute("favicon")).toBe("F");
+ // The widget stays selected, so its toolbar stays up after the edit.
+ expect(editor.model.document.selection.getSelectedElement()).toBe(mention);
+
+ // A block card edits the same way — it is the same attribute.
+ setModelData(editor.model, '[<linkEmbed url="https://e.com/" embedType="opengraph" title="T"></linkEmbed>]');
+ editor.execute(CHANGE_LINK_PREVIEW_TITLE_COMMAND, { title: "Card title" });
+ expect(findElement(editor, "linkEmbed")?.getAttribute("title")).toBe("Card title");
+ });
+
+ it("reports the renderers' hostname fallback when no title is stored, and the raw URL when it cannot parse", () => {
+ setModelData(editor.model, '[<linkEmbed url="https://e.com/page" embedType="opengraph"></linkEmbed>]');
+ expect(editor.commands.get(CHANGE_LINK_PREVIEW_TITLE_COMMAND)?.value).toBe("e.com");
+
+ setModelData(editor.model, '[<linkEmbed url="not-a-url" embedType="opengraph"></linkEmbed>]');
+ expect(editor.commands.get(CHANGE_LINK_PREVIEW_TITLE_COMMAND)?.value).toBe("not-a-url");
+ });
+
+ it("treats an unchanged or blank title as a no-op, and is disabled without a widget", () => {
+ setModelData(editor.model, '<paragraph>[<linkMention url="https://e.com/" title="T"></linkMention>]</paragraph>');
+ const original = findElement(editor, "linkMention");
+
+ // Saving the prefilled value back, or a blank one, must not even replace the element.
+ editor.execute(CHANGE_LINK_PREVIEW_TITLE_COMMAND, { title: "T" });
+ expect(findElement(editor, "linkMention")).toBe(original);
+ editor.execute(CHANGE_LINK_PREVIEW_TITLE_COMMAND, { title: " " });
+ expect(findElement(editor, "linkMention")).toBe(original);
+
+ setModelData(editor.model, "<paragraph>foo[]bar</paragraph>");
+ const command = editor.commands.get(CHANGE_LINK_PREVIEW_TITLE_COMMAND);
+ expect(command?.isEnabled).toBe(false);
+ expect(command?.value).toBeNull();
+
+ // Command swallows execute() while disabled, so force it enabled to exercise the early return.
+ const before = editor.getData();
+ if (command) {
+ command.isEnabled = true;
+ }
+ command?.execute({ title: "anything" });
+ expect(editor.getData()).toBe(before);
+ });
+
// -----------------------------------------------------------------------
// ChangeLinkDisplayCommand on a native link (the link balloon's Display dropdown)
// -----------------------------------------------------------------------
diff --git a/packages/ckeditor5/src/plugins/link_embed/link_embed_commands.ts b/packages/ckeditor5/src/plugins/link_embed/link_embed_commands.ts
index 11154c32b6..39d034c236 100644
--- a/packages/ckeditor5/src/plugins/link_embed/link_embed_commands.ts
+++ b/packages/ckeditor5/src/plugins/link_embed/link_embed_commands.ts
@@ -4,6 +4,7 @@ import { Command, findAttributeRange, ModelLiveRange } from 'ckeditor5';
export const LINK_EMBED_COMMAND = 'insertLinkEmbed';
export const CHANGE_LINK_DISPLAY_COMMAND = 'changeLinkDisplay';
export const REMOVE_LINK_EMBED_COMMAND = 'removeLinkEmbed';
+export const CHANGE_LINK_PREVIEW_TITLE_COMMAND = 'changeLinkPreviewTitle';
export const LINK_DISPLAY_MODES = [
{ value: 'inline', label: 'Inline', labelKey: 'link_embed.mode_inline' },
@@ -267,6 +268,67 @@ export class RemoveLinkEmbedCommand extends Command {
}
}
+/**
+ * Edits the title a link preview displays — the pill text of a mention, the heading of a card.
+ * The preview counterpart of the "Displayed text" field the editor's own link form offers for
+ * native links: the fetched title is often noisy ("Article | Site | Section"), and converting a
+ * labeled link replaces the user's wording, so both need a way back to words of the user's choosing.
+ *
+ * `value` is what the preview currently shows (the stored title, or the hostname the renderers
+ * fall back to), for the edit form to prefill. As in the official form, saving it back unchanged —
+ * or blank — changes nothing.
+ */
+export class ChangeLinkPreviewTitleCommand extends Command {
+ declare value: string | null;
+
+ override execute({ title }: { title: string }) {
+ const model = this.editor.model;
+ const selected = getSelectedLinkWidget(this.editor);
+ if (!selected) return;
+
+ const newTitle = title.trim();
+ if (!newTitle || newTitle === effectiveTitle(selected)) return;
+
+ model.change(writer => {
+ const attrs: Record<string, unknown> = {};
+ for (const key of META_KEYS) {
+ const val = selected.getAttribute(key);
+ if (val != null) attrs[key] = val;
+ }
+ attrs.title = newTitle;
+
+ // Clone-replace rather than setAttribute: the editing downcast is elementToElement,
+ // which does not re-render on attribute changes — replacing does (and it is how mode
+ // switching already works). The widget stays selected, so its toolbar stays up.
+ const replacement = writer.createElement(selected.name, attrs);
+ model.insertContent(replacement, writer.createRangeOn(selected));
+ writer.setSelection(replacement, 'on');
+ });
+ }
+
+ override refresh() {
+ const selected = getSelectedLinkWidget(this.editor);
+ this.isEnabled = !!selected;
+ this.value = selected ? effectiveTitle(selected) : null;
+ }
+}
+
+/**
+ * The title a preview currently displays: its stored title, or — mirroring the renderers'
+ * fallback (see MentionPreview in the client) — the hostname of its URL.
+ */
+function effectiveTitle(element: any): string {
+ const title = element.getAttribute('title') as string | undefined;
+ if (title) return title;
+
+ const url = element.getAttribute('url') as string | undefined;
+ try {
+ return new URL(url ?? '').hostname;
+ } catch {
+ return url ?? '';
+ }
+}
+
/** Returns the currently selected linkEmbed/linkMention element, or null. */
function getSelectedLinkWidget(editor: any) {
const selected = editor.model.document.selection.getSelectedElement();
diff --git a/packages/ckeditor5/src/plugins/link_embed/link_embed_editing.ts b/packages/ckeditor5/src/plugins/link_embed/link_embed_editing.ts
index b9ceebdb8f..5dbf584c2f 100644
--- a/packages/ckeditor5/src/plugins/link_embed/link_embed_editing.ts
+++ b/packages/ckeditor5/src/plugins/link_embed/link_embed_editing.ts
@@ -2,7 +2,9 @@ import { Plugin, toWidget, viewToModelPositionOutsideModelElement, Widget } from
import { preventCKEditorHandling } from '../widget_utils.js';
import {
CHANGE_LINK_DISPLAY_COMMAND,
+ CHANGE_LINK_PREVIEW_TITLE_COMMAND,
ChangeLinkDisplayCommand,
+ ChangeLinkPreviewTitleCommand,
InsertLinkEmbedCommand,
LINK_EMBED_COMMAND,
META_KEYS,
@@ -35,6 +37,7 @@ export default class LinkEmbedEditing extends Plugin {
this.editor.commands.add(LINK_EMBED_COMMAND, new InsertLinkEmbedCommand(this.editor));
this.editor.commands.add(CHANGE_LINK_DISPLAY_COMMAND, new ChangeLinkDisplayCommand(this.editor));
this.editor.commands.add(REMOVE_LINK_EMBED_COMMAND, new RemoveLinkEmbedCommand(this.editor));
+ this.editor.commands.add(CHANGE_LINK_PREVIEW_TITLE_COMMAND, new ChangeLinkPreviewTitleCommand(this.editor));
}
_defineSchema() {
diff --git a/packages/ckeditor5/src/plugins/link_embed/link_embed_title_form.spec.ts b/packages/ckeditor5/src/plugins/link_embed/link_embed_title_form.spec.ts
new file mode 100644
index 0000000000..3472756e2e
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/link_embed/link_embed_title_form.spec.ts
@@ -0,0 +1,57 @@
+import { Locale } from "ckeditor5";
+import { describe, expect, it, vi } from "vitest";
+
+import LinkEmbedTitleFormView from "./link_embed_title_form.js";
+
+const translate = (_key: string, fallback: string) => fallback;
+
+function createForm(): LinkEmbedTitleFormView {
+ const form = new LinkEmbedTitleFormView(new Locale(), translate);
+ form.render();
+ return form;
+}
+
+describe("LinkEmbedTitleFormView", () => {
+ it("holds a heading, a Title field and a Save button, and prefills via reset()", () => {
+ const form = createForm();
+
+ expect(form.element?.querySelector(".ck-link-embed-form__heading")?.textContent).toBe("Edit title");
+ expect(form.titleInputView.label).toBe("Title");
+ expect(form.saveButtonView.label).toBe("Save");
+
+ form.reset("Current title");
+ expect(form.title).toBe("Current title");
+ expect(form.titleInputView.fieldView.value).toBe("Current title");
+
+ form.focus();
+ form.destroy();
+ });
+
+ it("enables Save only for a non-blank title, and follows typing in the field", () => {
+ const form = createForm();
+
+ form.reset("");
+ expect(form.saveButtonView.isEnabled).toBe(false);
+ form.reset(" ");
+ expect(form.saveButtonView.isEnabled).toBe(false);
+
+ const input = form.titleInputView.fieldView.element as HTMLInputElement;
+ input.value = "My words";
+ form.titleInputView.fieldView.fire("input");
+ expect(form.title).toBe("My words");
+ expect(form.saveButtonView.isEnabled).toBe(true);
+
+ form.destroy();
+ });
+
+ it("turns a native form submit into the view's own submit event", () => {
+ const form = createForm();
+ const submitted = vi.fn();
+ form.on("submit", submitted);
+
+ form.element?.dispatchEvent(new Event("submit", { cancelable: true }));
+
+ expect(submitted).toHaveBeenCalled();
+ form.destroy();
+ });
+});
diff --git a/packages/ckeditor5/src/plugins/link_embed/link_embed_title_form.ts b/packages/ckeditor5/src/plugins/link_embed/link_embed_title_form.ts
new file mode 100644
index 0000000000..21f2b28b9a
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/link_embed/link_embed_title_form.ts
@@ -0,0 +1,145 @@
+import {
+ ButtonView,
+ createLabeledInputText,
+ FocusCycler,
+ FocusTracker,
+ KeystrokeHandler,
+ LabeledFieldView,
+ submitHandler,
+ View,
+ ViewCollection,
+ type FocusableView,
+ type InputTextView,
+ type Locale
+} from "ckeditor5";
+
+/** 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 widget toolbar's "Edit title" button: a single Title field and a
+ * Save button — the preview counterpart of the "Displayed text" field the editor's own link form
+ * offers for native links.
+ *
+ * It wears the same classes as the insert form (which reuses CKEditor's own `ck-link-form`), so it
+ * looks and behaves like the editor's native link balloons.
+ */
+export default class LinkEmbedTitleFormView extends View {
+
+ /** The title being edited, prefilled with what the preview currently shows. */
+ declare public title: string;
+
+ public readonly titleInputView: LabeledFieldView<InputTextView>;
+ public readonly saveButtonView: 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("title", "");
+
+ this.titleInputView = this._createTitleInput(locale, translate);
+ this.saveButtonView = this._createSaveButton(locale, translate);
+
+ this.setTemplate({
+ tag: "form",
+ attributes: {
+ 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.edit_title", "Edit title") }]
+ },
+ this.titleInputView,
+ {
+ tag: "div",
+ attributes: { class: ["ck", "ck-link-embed-form__actions"] },
+ children: [this.saveButtonView]
+ }
+ ]
+ });
+
+ 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.titleInputView, this.saveButtonView]) {
+ 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();
+ }
+
+ /** Prefills the form with the title the preview currently shows. */
+ public reset(currentTitle: string): void {
+ this.title = currentTitle;
+ }
+
+ public focus(): void {
+ this._focusCycler.focusFirst();
+ }
+
+ private _createTitleInput(locale: Locale, translate: Translate) {
+ const titleInput = new LabeledFieldView(locale, createLabeledInputText);
+ titleInput.label = translate("link_embed.title_label", "Title");
+
+ // Two-way: the field drives `title`, and reset() drives the field.
+ titleInput.fieldView.bind("value").to(this, "title");
+ titleInput.fieldView.on("input", () => {
+ /* v8 ignore next -- the input event can only come from a rendered element */
+ this.title = titleInput.fieldView.element?.value ?? "";
+ });
+
+ return titleInput;
+ }
+
+ private _createSaveButton(locale: Locale, translate: Translate) {
+ const button = new ButtonView(locale);
+
+ button.set({
+ label: translate("link_embed.save", "Save"),
+ withText: true,
+ type: "submit",
+ class: "ck-button-action ck-button-bold"
+ });
+
+ // A blank title is never saved — clearing the field is not how a title is removed.
+ button.bind("isEnabled").to(this, "title", (title) => !!String(title).trim());
+
+ return button;
+ }
+}
diff --git a/packages/ckeditor5/src/plugins/link_embed/link_embed_toolbar.spec.ts b/packages/ckeditor5/src/plugins/link_embed/link_embed_toolbar.spec.ts
index 7663225899..aed1f98c83 100644
--- a/packages/ckeditor5/src/plugins/link_embed/link_embed_toolbar.spec.ts
+++ b/packages/ckeditor5/src/plugins/link_embed/link_embed_toolbar.spec.ts
@@ -1,9 +1,10 @@
-import { ClassicEditor, Essentials, Link, Paragraph, WidgetToolbarRepository, _setModelData as setModelData } from "ckeditor5";
+import { ClassicEditor, ContextualBalloon, Essentials, Link, Paragraph, WidgetToolbarRepository, _setModelData as setModelData } from "ckeditor5";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { createTestEditor } from "../../../test/editor-kit.js";
import { installGlobMock } from "../../../test/globals-test-kit.js";
import LinkEmbed, { CHANGE_LINK_DISPLAY_COMMAND, LINK_DISPLAY_MODES } from "./link_embed.js";
+import LinkEmbedTitleFormView from "./link_embed_title_form.js";
import LinkEmbedToolbar from "./link_embed_toolbar.js";
// ---------------------------------------------------------------------------
@@ -691,6 +692,42 @@ describe("LinkEmbedToolbar", () => {
// The widget is gone, leaving the bare URL as plain text.
expect(editor.getData()).toBe(`<p>${URL}</p>`);
});
+
+ it("linkEmbedEditTitle opens a balloon form prefilled with the current title and saves the edit", () => {
+ const button = createButton("linkEmbedEditTitle");
+ expect(button.isEnabled).toBe(false);
+
+ selectLinkMention();
+ expect(button.isEnabled).toBe(true);
+
+ // Put the widget toolbar in the balloon first, as it necessarily is when the user
+ // clicks the pencil inside it — otherwise it would stack itself over the form when
+ // focusing the form flips the UI focus tracker.
+ editor.ui.focusTracker.isFocused = true;
+ editor.ui.fire("update");
+
+ const balloon = editor.plugins.get(ContextualBalloon);
+ button.fire("execute");
+
+ const form = balloon.visibleView as LinkEmbedTitleFormView;
+ expect(form).toBeInstanceOf(LinkEmbedTitleFormView);
+ // Prefilled with what the pill currently shows, so an untouched save changes nothing.
+ expect(form.title).toBe("T");
+
+ form.title = "My words";
+ form.fire("submit");
+
+ // The form is gone and the title took: the widget re-rendered with the new title.
+ expect(balloon.hasView(form)).toBe(false);
+ const mention = editor.model.document.selection.getSelectedElement();
+ expect(mention?.getAttribute("title")).toBe("My words");
+
+ // Esc dismisses without saving: reopening prefills with the widget's current title.
+ button.fire("execute");
+ expect(form.title).toBe("My words");
+ form.keystrokes.press({ keyCode: 27, preventDefault: () => {}, stopPropagation: () => {} } as unknown as Parameters<typeof form.keystrokes.press>[0]);
+ expect(balloon.hasView(form)).toBe(false);
+ });
});
});
diff --git a/packages/ckeditor5/src/plugins/link_embed/link_embed_toolbar.ts b/packages/ckeditor5/src/plugins/link_embed/link_embed_toolbar.ts
index d2a837743c..a565dc7639 100644
--- a/packages/ckeditor5/src/plugins/link_embed/link_embed_toolbar.ts
+++ b/packages/ckeditor5/src/plugins/link_embed/link_embed_toolbar.ts
@@ -3,12 +3,15 @@ import {
WidgetToolbarRepository,
isWidget,
type ViewElement,
+ clickOutsideHandler,
Collection,
+ ContextualBalloon,
ViewModel,
createDropdown,
addListToDropdown,
ButtonView,
DropdownButtonView,
+ IconPencil,
IconUnlink,
type ListDropdownButtonDefinition,
type Locale,
@@ -16,24 +19,26 @@ import {
} from "ckeditor5";
import LinkEmbed, {
CHANGE_LINK_DISPLAY_COMMAND,
+ CHANGE_LINK_PREVIEW_TITLE_COMMAND,
LINK_DISPLAY_MODES,
REMOVE_LINK_EMBED_COMMAND,
type LinkDisplayMode
} from "./link_embed.js";
+import LinkEmbedTitleFormView from "./link_embed_title_form.js";
import { createCopyUrlButton } from "../copy_link_url.js";
import { translate } from "../translate.js";
export default class LinkEmbedToolbar extends Plugin {
static get requires() {
- return [WidgetToolbarRepository, LinkEmbed, LinkEmbedLinkButton, LinkEmbedCopyUrlButton, LinkEmbedUnlinkButton, LinkEmbedDisplayDropdown] as const;
+ return [WidgetToolbarRepository, LinkEmbed, LinkEmbedLinkButton, LinkEmbedCopyUrlButton, LinkEmbedEditTitleButton, LinkEmbedUnlinkButton, LinkEmbedDisplayDropdown] as const;
}
afterInit() {
const widgetToolbarRepository = this.editor.plugins.get(WidgetToolbarRepository);
widgetToolbarRepository.register("linkEmbed", {
- items: ["linkEmbedLink", "linkEmbedCopyUrl", "linkEmbedUnlink", "|", "linkEmbedDisplayDropdown"],
+ items: ["linkEmbedLink", "linkEmbedCopyUrl", "linkEmbedEditTitle", "linkEmbedUnlink", "|", "linkEmbedDisplayDropdown"],
balloonClassName: "ck-toolbar-container link-embed-toolbar",
getRelatedElement(selection) {
const selectedElement = selection.getSelectedElement();
@@ -230,6 +235,112 @@ class LinkEmbedUnlinkButton extends Plugin {
}
}
+/**
+ * Registers the `linkEmbedEditTitle` toolbar item: a pencil button opening a balloon form that
+ * edits the title the selected preview displays — the widget counterpart of the "Displayed text"
+ * field the editor's own link form offers for native links.
+ */
+class LinkEmbedEditTitleButton extends Plugin {
+
+ static get requires() {
+ return [LinkEmbed, ContextualBalloon] as const;
+ }
+
+ private _formView: LinkEmbedTitleFormView | null = null;
+
+ public init() {
+ const editor = this.editor;
+
+ editor.ui.componentFactory.add("linkEmbedEditTitle", (locale) => {
+ const command = editor.commands.get(CHANGE_LINK_PREVIEW_TITLE_COMMAND);
+ const button = new ButtonView(locale);
+
+ button.set({
+ label: translate(editor, "link_embed.edit_title", "Edit title"),
+ icon: IconPencil,
+ tooltip: true
+ });
+
+ /* v8 ignore next -- LinkEmbedEditing always registers CHANGE_LINK_PREVIEW_TITLE_COMMAND (this plugin requires LinkEmbed), so the no-command branch is unreachable */
+ if (command) {
+ button.bind("isEnabled").to(command, "isEnabled");
+ }
+
+ button.on("execute", () => this._showForm());
+ return button;
+ });
+ }
+
+ public 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;
+
+ // Prefill with what the preview currently shows, so a save without edits changes nothing.
+ const command = editor.commands.get(CHANGE_LINK_PREVIEW_TITLE_COMMAND) as (Command & { value: string | null }) | undefined;
+ form.reset(command?.value ?? "");
+
+ 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 a widget is selected */
+ 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(): LinkEmbedTitleFormView {
+ if (this._formView) return this._formView;
+
+ const editor = this.editor;
+ const form = new LinkEmbedTitleFormView(editor.locale, (key, fallback) => translate(editor, key, fallback));
+ this._formView = form;
+
+ form.on("submit", () => {
+ editor.execute(CHANGE_LINK_PREVIEW_TITLE_COMMAND, { title: form.title });
+ this._hideForm();
+ });
+
+ // Esc and clicking away dismiss the form, exactly as they do for the insert form.
+ 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;
+ }
+}
+
/**
* A {@link ButtonView} rendered as an `<a target="_blank">` so a click opens the
* URL in a new tab. Reuses CKEditor's `ck-link-toolbar__preview` styling for