Skip to content

Build your personal knowledge base with Trilium Notes

link previews: offer the Display dropdown on native links

Elian Doran865ba2e4aa84
diff --git a/apps/client/src/widgets/type_widgets/text/config.ts b/apps/client/src/widgets/type_widgets/text/config.ts
index c3e491d354..0675c6bd2b 100644
--- a/apps/client/src/widgets/type_widgets/text/config.ts
+++ b/apps/client/src/widgets/type_widgets/text/config.ts
@@ -139,7 +139,9 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfi
link: {
defaultProtocol: "https://",
allowedProtocols: ALLOWED_PROTOCOLS,
- toolbar: ["linkPreview", "copyLinkUrl", "|", "editLink", "linkProperties", "unlink"]
+ // linkEmbedDisplayDropdown is the same Display dropdown the link-preview widget toolbar
+ // shows: on a native link it reads "Plain link" and converts to a preview shape.
+ toolbar: ["linkPreview", "copyLinkUrl", "|", "editLink", "linkProperties", "unlink", "|", "linkEmbedDisplayDropdown"]
},
bookmark: {
toolbar: [
diff --git a/packages/ckeditor5/src/plugins/link_embed_toolbar.spec.ts b/packages/ckeditor5/src/plugins/link_embed_toolbar.spec.ts
index 38d57880d3..f89cff9a03 100644
--- a/packages/ckeditor5/src/plugins/link_embed_toolbar.spec.ts
+++ b/packages/ckeditor5/src/plugins/link_embed_toolbar.spec.ts
@@ -1,4 +1,4 @@
-import { ClassicEditor, Essentials, Paragraph, WidgetToolbarRepository, _setModelData as setModelData } from "ckeditor5";
+import { ClassicEditor, Essentials, Link, Paragraph, WidgetToolbarRepository, _setModelData as setModelData } from "ckeditor5";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { createTestEditor } from "../../test/editor-kit.js";
@@ -93,7 +93,7 @@ describe("LinkEmbedToolbar", () => {
})
});
- editor = await createTestEditor([Essentials, Paragraph, LinkEmbed, LinkEmbedToolbar]);
+ editor = await createTestEditor([Essentials, Paragraph, Link, LinkEmbed, LinkEmbedToolbar]);
});
// -----------------------------------------------------------------------
@@ -371,6 +371,19 @@ describe("LinkEmbedToolbar", () => {
expect(dropdown.isEnabled).toBe(true);
});
+ it("hides itself (ck-hidden) while the command is disabled, for the native link balloon", () => {
+ // The dropdown also sits in the native link balloon, which opens for links that cannot be
+ // previewed (an internal note link, say) — there it must hide, not show permanently greyed.
+ setModelData(editor.model, "<paragraph>foo[]bar</paragraph>");
+ const dropdown = editor.ui.componentFactory.create("linkEmbedDisplayDropdown") as unknown as DropdownView;
+ expect(dropdown.isEnabled).toBe(false);
+ expect(dropdown.class).toBe("ck-hidden");
+
+ setModelData(editor.model, '<paragraph><$text linkHref="https://e.com/">https://e.[]com/</$text></paragraph>');
+ expect(dropdown.isEnabled).toBe(true);
+ expect(dropdown.class).toBe("");
+ });
+
it("button label shows 'Display' when command value is null (no widget selected)", () => {
setModelData(editor.model, "<paragraph>foo[]bar</paragraph>");
const dropdown = editor.ui.componentFactory.create("linkEmbedDisplayDropdown") as unknown as DropdownView;
diff --git a/packages/ckeditor5/src/plugins/link_embed_toolbar.ts b/packages/ckeditor5/src/plugins/link_embed_toolbar.ts
index e9e94a1add..bb1067cf43 100644
--- a/packages/ckeditor5/src/plugins/link_embed_toolbar.ts
+++ b/packages/ckeditor5/src/plugins/link_embed_toolbar.ts
@@ -86,6 +86,10 @@ class LinkEmbedDisplayDropdown extends Plugin {
});
dropdownView.bind("isEnabled").to(command, "isEnabled");
+ // The dropdown also sits in the native link balloon (see `link.toolbar` in the client
+ // config), which opens for links that cannot be previewed at all — an internal note
+ // link, say. There it hides rather than showing permanently disabled.
+ dropdownView.bind("class").to(command, "isEnabled", (isEnabled) => (isEnabled ? "" : "ck-hidden"));
dropdownView.buttonView.bind("label").to(command, "value", (value) => {
if (!value) return displayLabel;
diff --git a/packages/ckeditor5/src/plugins/linkembed.spec.ts b/packages/ckeditor5/src/plugins/linkembed.spec.ts
index 2e69498c93..abd3135c5e 100644
--- a/packages/ckeditor5/src/plugins/linkembed.spec.ts
+++ b/packages/ckeditor5/src/plugins/linkembed.spec.ts
@@ -560,6 +560,88 @@ describe("LinkEmbed", () => {
expect(editor.getData()).toBe(before);
});
+ // -----------------------------------------------------------------------
+ // ChangeLinkDisplayCommand on a native link (the link balloon's Display dropdown)
+ // -----------------------------------------------------------------------
+
+ it("offers itself on a native http(s) link, reporting 'plain' as the current mode", () => {
+ const command = changeCommand(editor);
+
+ setModelData(editor.model, "<paragraph>foo[]bar</paragraph>");
+ expect(command.isEnabled).toBe(false);
+ expect(command.value).toBeNull();
+
+ setModelData(editor.model, '<paragraph><$text linkHref="https://youtube.com/watch">https://youtube.[]com/watch</$text></paragraph>');
+ expect(command.isEnabled).toBe(true);
+ expect(command.value).toBe("plain");
+ expect(command.embedAvailable).toBe(true);
+ expect(command.url).toBe("https://youtube.com/watch");
+
+ // An internal reference link has no page to preview.
+ setModelData(editor.model, '<paragraph><$text linkHref="#root/someNoteId">some[]note</$text></paragraph>');
+ expect(command.isEnabled).toBe(false);
+ expect(command.value).toBeNull();
+ });
+
+ it("converts a labeled native link into an inline mention, keeping the surrounding text", async () => {
+ const url = "https://example.com/article";
+ setModelData(editor.model, `<paragraph>see <$text linkHref="${url}">the []article</$text> here</paragraph>`);
+
+ await editor.execute(CHANGE_LINK_DISPLAY_COMMAND, { value: "inline" });
+
+ expect(fetchLinkMetadata).toHaveBeenCalledWith(url);
+ const mention = findElement(editor, "linkMention");
+ expect(mention?.getAttribute("url")).toBe(url);
+ expect(mention?.getAttribute("title")).toBe(META.title);
+ // The label is replaced by the pill; the text around the link survives (spaces adjacent to
+ // an inline object serialize as &nbsp;), and the new widget is left selected so its toolbar
+ // — this same dropdown included — takes over from the link balloon.
+ expect(editor.getData()).toContain("<p>see&nbsp;<span");
+ expect(editor.getData()).toContain("</span>&nbsp;here</p>");
+ expect(editor.model.document.selection.getSelectedElement()).toBe(mention);
+ });
+
+ it("converts a native link to the chosen block shape: card forces opengraph, embed keeps the detected type", async () => {
+ const url = "https://youtube.com/watch?v=abc12345678";
+ fetchLinkMetadata.mockImplementation(async () => ({ ...META, url, embedType: "youtube" }));
+
+ setModelData(editor.model, `<paragraph><$text linkHref="${url}">watch [] this</$text></paragraph>`);
+ await editor.execute(CHANGE_LINK_DISPLAY_COMMAND, { value: "card" });
+ expect(findElement(editor, "linkEmbed")?.getAttribute("embedType")).toBe("opengraph");
+
+ setModelData(editor.model, `<paragraph><$text linkHref="${url}">watch [] this</$text></paragraph>`);
+ await editor.execute(CHANGE_LINK_DISPLAY_COMMAND, { value: "embed" });
+ const embed = findElement(editor, "linkEmbed");
+ expect(embed?.getAttribute("embedType")).toBe("youtube");
+ expect(editor.model.document.selection.getSelectedElement()).toBe(embed);
+ });
+
+ it("does nothing for 'plain' on a native link — it already is one", async () => {
+ setModelData(editor.model, '<paragraph><$text linkHref="https://e.com/">https://e.[]com/</$text></paragraph>');
+ const before = editor.getData();
+
+ await editor.execute(CHANGE_LINK_DISPLAY_COMMAND, { value: "plain" });
+
+ expect(fetchLinkMetadata).not.toHaveBeenCalled();
+ expect(editor.getData()).toBe(before);
+ });
+
+ it("does nothing when the linked text was deleted while the metadata was being fetched", async () => {
+ const url = "https://example.com/";
+ let resolveFetch: (meta: unknown) => void = () => {};
+ fetchLinkMetadata.mockReturnValue(new Promise((resolve) => { resolveFetch = resolve; }));
+ setModelData(editor.model, `<paragraph><$text linkHref="${url}">https://exa[]mple.com/</$text></paragraph>`);
+
+ const executed = editor.execute(CHANGE_LINK_DISPLAY_COMMAND, { value: "inline" }) as unknown as Promise<void>;
+ setModelData(editor.model, "<paragraph>replaced[]</paragraph>");
+ resolveFetch({ ...META, url });
+ await executed;
+
+ expect(findElement(editor, "linkMention")).toBeUndefined();
+ expect(findElement(editor, "linkEmbed")).toBeUndefined();
+ expect(editor.getData()).toBe("<p>replaced</p>");
+ });
+
// -----------------------------------------------------------------------
// AutoLinkToMention
// -----------------------------------------------------------------------
diff --git a/packages/ckeditor5/src/plugins/linkembed.ts b/packages/ckeditor5/src/plugins/linkembed.ts
index 0fe56c8bde..4c5fb06ff6 100644
--- a/packages/ckeditor5/src/plugins/linkembed.ts
+++ b/packages/ckeditor5/src/plugins/linkembed.ts
@@ -1,5 +1,5 @@
import { type BlockChildLike, chooseLinkPreviewKind, isHttpUrl, isUrlAloneInBlock } from '@triliumnext/commons';
-import { ButtonView, clickOutsideHandler, Command, ContextualBalloon, Plugin, toWidget, viewToModelPositionOutsideModelElement, Widget, type Editor, type Observable } from 'ckeditor5';
+import { ButtonView, clickOutsideHandler, Command, ContextualBalloon, findAttributeRange, ModelLiveRange, Plugin, toWidget, viewToModelPositionOutsideModelElement, Widget, type Editor, type Observable } from 'ckeditor5';
import linkPreviewIcon from '../icons/link-preview.svg?raw';
import LinkEmbedFormView from './link_embed_form.js';
import { translate } from './translate.js';
@@ -464,10 +464,15 @@ class ChangeLinkDisplayCommand extends Command {
this.set('url', null);
}
- override execute(options: { value: LinkDisplayMode }) {
+ override async execute(options: { value: LinkDisplayMode }) {
const model = this.editor.model;
const selected = getSelectedLinkWidget(this.editor);
- if (!selected) return;
+
+ // No widget selected means the dropdown sits in the link balloon, over a native link.
+ if (!selected) {
+ await this._convertNativeLink(options.value);
+ return;
+ }
const targetMode = options.value;
const currentMode = this._getMode(selected);
@@ -512,10 +517,10 @@ class ChangeLinkDisplayCommand extends Command {
override refresh() {
const selected = getSelectedLinkWidget(this.editor);
- this.isEnabled = !!selected;
- this.value = selected ? this._getMode(selected) : null;
if (selected) {
+ this.isEnabled = true;
+ this.value = this._getMode(selected);
const url = selected.getAttribute('url') as string;
this.embedAvailable = this._detectEmbedType(url) !== 'opengraph';
// Only ever hand out an http(s) URL. `url` comes from the stored `data-url`, which the
@@ -523,10 +528,82 @@ class ChangeLinkDisplayCommand extends Command {
// would otherwise reach the toolbar's "open link" button as a live href. Withholding it
// here disables that button (and the copy one) instead of arming them.
this.url = isHttpUrl(url) ? url : null;
- } else {
- this.embedAvailable = false;
- this.url = null;
+ return;
+ }
+
+ // A native link under the caret: the same dropdown, hosted in the link balloon this time,
+ // offers to convert it into a preview. Its current display mode is by definition "plain".
+ const href = this.editor.model.document.selection.getAttribute('linkHref');
+ if (typeof href === 'string' && EMBEDDABLE_URL_REGEX.test(href)) {
+ this.isEnabled = true;
+ this.value = 'plain';
+ this.embedAvailable = this._detectEmbedType(href) !== 'opengraph';
+ this.url = href;
+ return;
}
+
+ this.isEnabled = false;
+ this.value = null;
+ this.embedAvailable = false;
+ this.url = null;
+ }
+
+ /**
+ * Converts the native link under the caret — the one whose balloon toolbar hosts the dropdown —
+ * into the chosen preview shape: the deliberate inverse of "Plain link". Unlike auto-detection
+ * there is no gesture to interpret and no unresolved-page veto: the mode was picked outright,
+ * so the conversion always happens (Ctrl+Z brings the link back), and a labeled link's display
+ * text is replaced by the preview.
+ */
+ private async _convertNativeLink(targetMode: LinkDisplayMode) {
+ const editor = this.editor;
+ const model = editor.model;
+ const position = model.document.selection.getFirstPosition();
+ const href = model.document.selection.getAttribute('linkHref');
+ /* v8 ignore next -- refresh() disables the command unless the selection carries a linkHref */
+ if (typeof href !== 'string' || !position) return;
+ // The link already is one.
+ if (targetMode === 'plain') return;
+
+ const editorEl = editor.editing.view.getDomRoot();
+ const component = glob.getComponentByEl<EditorComponent>(editorEl);
+
+ // The linked text is tracked as a live range: the metadata fetch reads the page server-side
+ // and can take seconds, and edits made meanwhile must not shift what gets replaced.
+ const liveRange = ModelLiveRange.fromRange(findAttributeRange(position, 'linkHref', href, model));
+ const metadata = await component.fetchLinkMetadata(href);
+ const range = liveRange.toRange();
+ liveRange.detach();
+
+ model.change(writer => {
+ // The link may have been edited away while the fetch was in flight.
+ let linkStillThere = false;
+ for (const { item } of range.getWalker()) {
+ if (item.is('$textProxy') && item.getAttribute('linkHref') === href) {
+ linkStillThere = true;
+ break;
+ }
+ }
+ if (!linkStillThere) return;
+
+ const element = writer.createElement(targetMode === 'inline' ? 'linkMention' : 'linkEmbed', {
+ url: metadata.url,
+ // Same rule as the widget path below: a card is an embed that declines to play.
+ embedType: targetMode === 'card' ? 'opengraph'
+ : targetMode === 'embed' ? this._detectEmbedType(href)
+ : metadata.embedType,
+ title: metadata.title,
+ description: metadata.description,
+ favicon: metadata.favicon,
+ siteName: metadata.siteName,
+ image: metadata.image
+ });
+
+ model.insertContent(element, range);
+ // Leave the new widget selected, so its toolbar — this same dropdown included — takes
+ // over from the link balloon.
+ writer.setSelection(element, 'on');
+ });
}
private _getMode(element: any): LinkDisplayMode {