Skip to content

Build your personal knowledge base with Trilium Notes

text editor/link previews: make the embed mode as default for autodetected YouTube links

Adorian Doranbc249cd96508
diff --git a/packages/ckeditor5/src/plugins/linkembed.ts b/packages/ckeditor5/src/plugins/linkembed.ts
index 00391a3ead..1b323a0c68 100644
--- a/packages/ckeditor5/src/plugins/linkembed.ts
+++ b/packages/ckeditor5/src/plugins/linkembed.ts
@@ -1,3 +1,4 @@
+import { type BlockChildLike, chooseLinkPreviewKind, isUrlAloneInBlock } from '@triliumnext/commons';
import { ButtonView, Command, Plugin, toWidget, Widget, type Observable } from 'ckeditor5';
import linkEmbedIcon from '../icons/link-embed.svg?raw';
import { preventCKEditorHandling } from './widget_utils.js';
@@ -323,10 +324,13 @@ class ChangeLinkDisplayCommand extends Command {
}
// ---------------------------------------------------------------------------
-// Auto-convert pasted URLs to linkMention widgets.
+// Auto-convert pasted URLs to link preview widgets.
// Piggybacks on CKEditor's AutoLink plugin: when AutoLink sets `linkHref` on
// text whose content matches the href (i.e. a raw pasted URL, not
-// "[label](url)"), we fetch metadata and replace it with a linkMention.
+// "[label](url)"), we fetch metadata and replace it with a preview widget.
+// An embeddable URL (e.g. YouTube) standing alone in its block becomes a block
+// linkEmbed (Embed mode); every other URL — including an embeddable one
+// surrounded by text — becomes an inline linkMention.
// The user can Ctrl+Z to revert back to a plain link.
// ---------------------------------------------------------------------------
@@ -375,14 +379,14 @@ class AutoLinkToMention extends Plugin {
const parent = item.item.parent;
if (!parent?.is('element')) continue;
- this._replaceWithMention(href, parent.getPath());
+ this._replaceWithPreview(href, parent.getPath());
return;
}
}
});
}
- private _replaceWithMention(url: string, parentPath: number[]) {
+ private _replaceWithPreview(url: string, parentPath: number[]) {
const editor = this.editor;
const editorEl = editor.editing.view.getDomRoot();
const component = glob.getComponentByEl<EditorComponent>(editorEl);
@@ -409,6 +413,14 @@ class AutoLinkToMention extends Plugin {
if (item.item.data.trim() !== url) continue;
if (item.item.getAttribute('linkHref') !== url) continue;
+ // An embeddable URL (YouTube) becomes a block embed only when
+ // it stands alone in its block; otherwise — or for any other
+ // URL — it becomes an inline mention. Computed before deleting
+ // (deletion would empty the block) and at insertion time, since
+ // the metadata fetch is async and the user may have typed more.
+ const alone = isUrlAloneInBlock(this._blockChildren(parentEl), url);
+ const kind = chooseLinkPreviewKind(metadata.embedType, alone);
+
const start = writer.createPositionAt(parentEl, item.item.startOffset!);
const end = writer.createPositionAt(parentEl, item.item.startOffset! + item.item.data.length);
@@ -416,7 +428,7 @@ class AutoLinkToMention extends Plugin {
writer.setSelection(urlRange);
editor.model.deleteContent(editor.model.document.selection);
- editor.model.insertContent(writer.createElement('linkMention', {
+ editor.model.insertContent(writer.createElement(kind === 'embed' ? 'linkEmbed' : 'linkMention', {
url: metadata.url,
embedType: metadata.embedType,
title: metadata.title,
@@ -432,4 +444,17 @@ class AutoLinkToMention extends Plugin {
this._converting = false;
});
}
+
+ /**
+ * Maps a model block's children to the runtime-neutral shape consumed by
+ * {@link isUrlAloneInBlock}, keeping the decision logic pure and testable.
+ */
+ private _blockChildren(blockEl: any): BlockChildLike[] {
+ const children: BlockChildLike[] = [];
+ for (const child of blockEl.getChildren()) {
+ const isText = child.is('$text');
+ children.push({ isText, data: isText ? child.data : undefined });
+ }
+ return children;
+ }
}
diff --git a/packages/commons/src/lib/link_embed.spec.ts b/packages/commons/src/lib/link_embed.spec.ts
index 8f21c400d3..f64740eb67 100644
--- a/packages/commons/src/lib/link_embed.spec.ts
+++ b/packages/commons/src/lib/link_embed.spec.ts
@@ -1,6 +1,12 @@
import { describe, expect, it } from "vitest";
-import { extractYouTubeVideoId, YOUTUBE_REGEX } from "./link_embed.js";
+import {
+ type BlockChildLike,
+ chooseLinkPreviewKind,
+ extractYouTubeVideoId,
+ isUrlAloneInBlock,
+ YOUTUBE_REGEX
+} from "./link_embed.js";
describe("extractYouTubeVideoId", () => {
it("extracts the id from a standard watch URL", () => {
@@ -39,3 +45,41 @@ describe("YOUTUBE_REGEX", () => {
expect(match?.[1]).toBe("dQw4w9WgXcQ");
});
});
+
+describe("isUrlAloneInBlock", () => {
+ const url = "https://youtu.be/dQw4w9WgXcQ";
+ const text = (data: string): BlockChildLike => ({ isText: true, data });
+ const element = (): BlockChildLike => ({ isText: false });
+
+ it("is true when the URL is the block's only content, ignoring surrounding whitespace", () => {
+ // Sole text node.
+ expect(isUrlAloneInBlock([text(url)], url)).toBe(true);
+ // Trailing space (the character that triggers auto-linking) as its own node.
+ expect(isUrlAloneInBlock([text(url), text(" ")], url)).toBe(true);
+ // Whitespace-only nodes on either side.
+ expect(isUrlAloneInBlock([text(" "), text(url), text("\n")], url)).toBe(true);
+ // Adjacent text nodes that together spell the URL.
+ expect(isUrlAloneInBlock([text("https://youtu.be/"), text("dQw4w9WgXcQ")], url)).toBe(true);
+ });
+
+ it("is false when the URL is surrounded by other text or non-text nodes", () => {
+ expect(isUrlAloneInBlock([text("Check out "), text(url)], url)).toBe(false);
+ expect(isUrlAloneInBlock([text(url), text(" today")], url)).toBe(false);
+ // A non-text node (e.g. an inline image or soft break) disqualifies it.
+ expect(isUrlAloneInBlock([text(url), element()], url)).toBe(false);
+ expect(isUrlAloneInBlock([element()], url)).toBe(false);
+ // An empty block contains nothing, let alone the URL.
+ expect(isUrlAloneInBlock([], url)).toBe(false);
+ });
+});
+
+describe("chooseLinkPreviewKind", () => {
+ it("uses a block embed only for an embeddable URL standing alone in its block", () => {
+ expect(chooseLinkPreviewKind("youtube", true)).toBe("embed");
+ // Embeddable but surrounded by text -> inline mention (a block can't go mid-sentence).
+ expect(chooseLinkPreviewKind("youtube", false)).toBe("mention");
+ // Non-embeddable URLs are always inline mentions, alone or not.
+ expect(chooseLinkPreviewKind("opengraph", true)).toBe("mention");
+ expect(chooseLinkPreviewKind("opengraph", false)).toBe("mention");
+ });
+});
diff --git a/packages/commons/src/lib/link_embed.ts b/packages/commons/src/lib/link_embed.ts
index cfae704939..1ceddac74d 100644
--- a/packages/commons/src/lib/link_embed.ts
+++ b/packages/commons/src/lib/link_embed.ts
@@ -14,3 +14,44 @@ export interface LinkEmbedMetadata {
siteName?: string;
embedType: "youtube" | "opengraph";
}
+
+/**
+ * A runtime-neutral view of a block's child node, decoupled from any editor's
+ * model types so the logic below can be unit-tested with plain objects.
+ */
+export interface BlockChildLike {
+ /** True for a text node; false for any element (image, soft break, widget, …). */
+ isText: boolean;
+ /** Text contents when `isText`; ignored otherwise. */
+ data?: string;
+}
+
+/**
+ * True when `url` is the sole content of a block — its only non-whitespace text
+ * is the URL and it holds no other elements. Surrounding whitespace (such as the
+ * trailing space that triggers auto-linking) is ignored.
+ */
+export function isUrlAloneInBlock(children: Iterable<BlockChildLike>, url: string): boolean {
+ let text = "";
+ for (const child of children) {
+ // Any non-text node (inline image, soft break, mention, …) means the
+ // URL isn't alone.
+ if (!child.isText) {
+ return false;
+ }
+ text += child.data ?? "";
+ }
+ return text.trim() === url;
+}
+
+export type LinkPreviewKind = "embed" | "mention";
+
+/**
+ * Chooses how an auto-detected URL should be previewed: a block embed (e.g. a
+ * YouTube player) only for an embeddable URL that stands alone in its block;
+ * every other URL — including an embeddable one surrounded by text — becomes an
+ * inline mention.
+ */
+export function chooseLinkPreviewKind(embedType: string, urlAloneInBlock: boolean): LinkPreviewKind {
+ return embedType !== "opengraph" && urlAloneInBlock ? "embed" : "mention";
+}