Skip to content

Build your personal knowledge base with Trilium Notes

link previews: automatically determine the whether should default to card or inline view

Adorian Doran435ec97fc7ec
diff --git a/packages/ckeditor5/src/plugins/linkembed.spec.ts b/packages/ckeditor5/src/plugins/linkembed.spec.ts
index 0db38b9e5f..c1f2ef4f83 100644
--- a/packages/ckeditor5/src/plugins/linkembed.spec.ts
+++ b/packages/ckeditor5/src/plugins/linkembed.spec.ts
@@ -5,7 +5,9 @@ import {
BlockQuote,
ClassicEditor,
Essentials,
+ Heading,
Link,
+ List,
Paragraph,
Undo,
type ViewElement
@@ -55,7 +57,9 @@ describe("LinkEmbed", () => {
})
});
- editor = await createTestEditor([Essentials, Paragraph, BlockQuote, Link, Undo, LinkEmbed]);
+ // Heading, List and BlockQuote are loaded so the placement rules (which keep a URL inline
+ // inside a heading, list item, table cell or quote) can be exercised against a real schema.
+ editor = await createTestEditor([Essentials, Paragraph, Heading, List, BlockQuote, Link, Undo, LinkEmbed]);
});
// -----------------------------------------------------------------------
@@ -494,18 +498,101 @@ describe("LinkEmbed", () => {
expect(findElement(editor, "linkMention")).toBeDefined();
});
- it("converts an embeddable URL standing alone in its block into a block linkEmbed", async () => {
- const url = "https://youtube.com/watch?v=abc12345678";
- fetchLinkMetadata.mockResolvedValueOnce({ ...META, url, embedType: "youtube" });
+ // -----------------------------------------------------------------------
+ // Placement: what shape an auto-detected URL takes, and why
+ // -----------------------------------------------------------------------
- addLinkedText(editor, url);
- await flushFetch();
+ describe("placement", () => {
+ const PLAIN_URL = "https://example.com/article";
+ const VIDEO_URL = "https://youtube.com/watch?v=abc12345678";
- // Embeddable + alone in its block => the player, not an inline pill.
- expect(findElement(editor, "linkMention")).toBeUndefined();
- const embed = findElement(editor, "linkEmbed");
- expect(embed?.getAttribute("url")).toBe(url);
- expect(embed?.getAttribute("embedType")).toBe("youtube");
+ /** Makes the next fetch report `url` as embeddable, the way a YouTube link comes back. */
+ function embeddable(url: string) {
+ fetchLinkMetadata.mockResolvedValueOnce({ ...META, url, embedType: "youtube" });
+ }
+
+ it("turns a URL left alone on its own line into a card", async () => {
+ autoLinkIn(editor, urlLeftAloneOnItsOwnLine(PLAIN_URL), PLAIN_URL);
+ await flushFetch();
+
+ expect(findElement(editor, "linkMention")).toBeUndefined();
+ const embed = findElement(editor, "linkEmbed");
+ expect(embed?.getAttribute("url")).toBe(PLAIN_URL);
+ // "opengraph" is what the renderer shows as a card rather than a player.
+ expect(embed?.getAttribute("embedType")).toBe("opengraph");
+ });
+
+ it("turns an embeddable URL left alone on its own line into a player", async () => {
+ embeddable(VIDEO_URL);
+
+ autoLinkIn(editor, urlLeftAloneOnItsOwnLine(VIDEO_URL), VIDEO_URL);
+ await flushFetch();
+
+ expect(findElement(editor, "linkMention")).toBeUndefined();
+ expect(findElement(editor, "linkEmbed")?.getAttribute("embedType")).toBe("youtube");
+ });
+
+ it("keeps the URL inline while the caret is still on its line, embeddable or not", async () => {
+ // The user typed a space, not Enter: they may still be writing that sentence, so the URL
+ // is alone only by accident. Nothing has been *left* alone yet.
+ embeddable(VIDEO_URL);
+ addLinkedText(editor, VIDEO_URL);
+ await flushFetch();
+
+ expect(findElement(editor, "linkEmbed")).toBeUndefined();
+ expect(findElement(editor, "linkMention")?.getAttribute("url")).toBe(VIDEO_URL);
+ });
+
+ it("keeps the URL inline when text sits beside it on the line", async () => {
+ autoLinkIn(editor, `<paragraph>See ${PLAIN_URL}</paragraph><paragraph>[]</paragraph>`, PLAIN_URL);
+ await flushFetch();
+
+ expect(findElement(editor, "linkEmbed")).toBeUndefined();
+ expect(findElement(editor, "linkMention")).toBeDefined();
+ });
+
+ it("keeps the URL inline inside a list item, a quote and a heading", async () => {
+ // A block preview inside these reads as a layout accident, so they stay inline — even
+ // though the URL is alone in its block and the caret has moved on.
+ const blocks = {
+ "list item": `<paragraph listIndent="0" listItemId="a" listType="bulleted">${PLAIN_URL}</paragraph>`,
+ quote: `<blockQuote><paragraph>${PLAIN_URL}</paragraph></blockQuote>`,
+ heading: `<heading2>${PLAIN_URL}</heading2>`
+ };
+
+ for (const block of Object.values(blocks)) {
+ autoLinkIn(editor, `${block}<paragraph>[]</paragraph>`, PLAIN_URL);
+ await flushFetch();
+
+ expect(findElement(editor, "linkEmbed")).toBeUndefined();
+ expect(findElement(editor, "linkMention")).toBeDefined();
+ }
+ });
+
+ it("leaves the caret where the user moved it, even if they typed while the fetch was in flight", async () => {
+ const { resolveFetch } = useDeferredFetch();
+ autoLinkIn(editor, urlLeftAloneOnItsOwnLine(PLAIN_URL), PLAIN_URL);
+
+ // The user carries on typing on the new line while the metadata is still being fetched.
+ editor.model.change((writer) => {
+ const caret = editor.model.document.selection.getFirstPosition();
+ if (!caret) {
+ throw new Error("Expected a caret position.");
+ }
+ writer.insertText("hello", caret);
+ });
+
+ resolveFetch({ ...META, url: PLAIN_URL });
+ await flushFetch();
+
+ // The card took over the URL's paragraph without dragging the caret back into it: the
+ // typed text is intact and the caret still sits after it.
+ expect(findElement(editor, "linkEmbed")).toBeDefined();
+ expect(editor.getData()).toContain("<p>hello</p>");
+
+ const caretBlock = editor.model.document.selection.getFirstPosition()?.parent;
+ expect(caretBlock?.is("element", "paragraph")).toBe(true);
+ });
});
it("ignores a labeled link whose text differs from the href", async () => {
@@ -772,10 +859,54 @@ function findElement(editor: ClassicEditor, name: string) {
return undefined;
}
+/**
+ * Sets up `modelData` and then, in a separate change, applies `linkHref` to the text node holding
+ * `href` — exactly what AutoLink does. Where `modelData` leaves the caret *is* the gesture under
+ * test: still inside the URL's block (the user typed a space and may keep going), or in the block
+ * after it (the user pressed Enter, which splits the paragraph and carries the caret onward).
+ */
+function autoLinkIn(editor: ClassicEditor, modelData: string, href: string): void {
+ setModelData(editor.model, modelData);
+
+ editor.model.change((writer) => {
+ const root = editor.model.document.getRoot();
+ if (!root) {
+ throw new Error("Expected a document root.");
+ }
+
+ for (const item of writer.createRangeIn(root).getWalker()) {
+ if (!item.item.is("$textProxy")) continue;
+
+ // AutoLink links the URL itself, not the whole text node it happens to share with the
+ // words around it — so link exactly the URL's slice of the node.
+ const index = item.item.data.indexOf(href);
+ if (index < 0) continue;
+
+ const parent = item.item.parent;
+ if (!parent || !parent.is("element") || item.item.startOffset === null) continue;
+
+ const start = item.item.startOffset + index;
+ writer.setAttribute("linkHref", href, writer.createRange(
+ writer.createPositionAt(parent, start),
+ writer.createPositionAt(parent, start + href.length)
+ ));
+ return;
+ }
+
+ throw new Error(`No text node holds ${href}.`);
+ });
+}
+
+/** The model data for a URL left alone on its own line, with the caret carried to the next one. */
+function urlLeftAloneOnItsOwnLine(url: string): string {
+ return `<paragraph>${url}</paragraph><paragraph>[]</paragraph>`;
+}
+
/**
* Inserts text into the paragraph and applies a `linkHref` attribute to it via a
* writer change (null -> url), exactly as CKEditor's AutoLink plugin does when a
* raw URL is pasted/typed. This drives the `AutoLinkToMention` `change:data` listener.
+ * The caret is left in the block, as it is when the user types a space after the URL.
*/
function addLinkedText(editor: ClassicEditor, href: string, text = href): void {
// First insert the plain text in its own batch.
diff --git a/packages/ckeditor5/src/plugins/linkembed.ts b/packages/ckeditor5/src/plugins/linkembed.ts
index aaf70ebadd..9eaeff717d 100644
--- a/packages/ckeditor5/src/plugins/linkembed.ts
+++ b/packages/ckeditor5/src/plugins/linkembed.ts
@@ -362,13 +362,19 @@ class RemoveLinkEmbedCommand extends Command {
}
// ---------------------------------------------------------------------------
-// Auto-convert pasted URLs to link preview widgets.
+// Auto-convert typed/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 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.
+// text whose content matches the href (i.e. a raw URL, not "[label](url)"), we
+// fetch metadata and replace it with a preview widget.
+//
+// The shape follows the gesture (see chooseLinkPreviewKind):
+// * a URL left alone on its own line — sole content of a plain paragraph, then
+// Enter — becomes a block preview: a player if the URL is embeddable
+// (YouTube), a card otherwise;
+// * anything else — text either side of it, a list/table/quote/heading, or a
+// caret still in the block because the user is mid-sentence — becomes an
+// inline linkMention.
+//
// The user can Ctrl+Z to revert back to a plain link.
// ---------------------------------------------------------------------------
@@ -475,22 +481,17 @@ 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);
-
- const urlRange = writer.createRange(start, end);
- writer.setSelection(urlRange);
- editor.model.deleteContent(editor.model.document.selection);
-
- editor.model.insertContent(writer.createElement(kind === 'embed' ? 'linkEmbed' : 'linkMention', {
+ // Where the URL sits decides its shape. Evaluated here — at insertion time, not
+ // when the URL was detected — because the metadata fetch is async and the user
+ // may have kept typing meanwhile. Also before deleting anything, since deletion
+ // would empty the block and make it look like the URL was never alone.
+ const kind = chooseLinkPreviewKind(metadata.embedType, {
+ urlAloneInBlock: isUrlAloneInBlock(this._blockChildren(parentEl), url),
+ blockIsStandalone: this._isStandaloneBlock(parentEl),
+ caretLeftBlock: this._caretLeftBlock(parentEl)
+ });
+
+ const attributes = {
url: metadata.url,
embedType: metadata.embedType,
title: metadata.title,
@@ -498,7 +499,24 @@ class AutoLinkToMention extends Plugin {
favicon: metadata.favicon,
siteName: metadata.siteName,
image: metadata.image
- }));
+ };
+
+ if (kind === 'mention') {
+ const urlRange = writer.createRangeOn(item.item);
+ writer.setSelection(urlRange);
+ editor.model.deleteContent(editor.model.document.selection);
+ editor.model.insertContent(writer.createElement('linkMention', attributes));
+ return;
+ }
+
+ // A card or an embed takes over the whole paragraph, which by now holds nothing
+ // but the URL. Swapped with writer.insert/remove rather than insertContent: the
+ // caret has moved on to the next line (that is what made this a block preview in
+ // the first place) and may already be mid-word, so it must not be dragged back.
+ // 'card' vs 'embed' needs no branch here — the renderer keys off embedType,
+ // which is "opengraph" for a card and the provider's own type for an embed.
+ writer.insert(writer.createElement('linkEmbed', attributes), parentEl, 'before');
+ writer.remove(parentEl);
return;
}
});
@@ -507,6 +525,31 @@ class AutoLinkToMention extends Plugin {
});
}
+ /**
+ * True for a plain top-level paragraph — the only block a card or an embed may take over.
+ * A list item is a paragraph carrying list attributes; a table cell, a quote and every other
+ * container nest their paragraphs below the root; a heading is not a paragraph at all. In each
+ * of those the URL keeps its inline mention, since a block preview there reads as an accident.
+ */
+ private _isStandaloneBlock(blockEl: any): boolean {
+ if (blockEl.name !== 'paragraph') return false;
+ if (blockEl.hasAttribute('listItemId')) return false;
+
+ return blockEl.parent === this.editor.model.document.getRoot();
+ }
+
+ /**
+ * True when the caret is no longer in the block — which is exactly what pressing Enter after the
+ * URL does. While it is still there the user may yet type on that line, so the URL has not been
+ * *left* alone and stays an inline mention.
+ */
+ private _caretLeftBlock(blockEl: any): boolean {
+ const position = this.editor.model.document.selection.getFirstPosition();
+
+ /* v8 ignore next -- the document selection always has a position */
+ return position?.parent !== blockEl;
+ }
+
/**
* Maps a model block's children to the runtime-neutral shape consumed by
* {@link isUrlAloneInBlock}, keeping the decision logic pure and testable.
diff --git a/packages/commons/src/lib/link_embed.spec.ts b/packages/commons/src/lib/link_embed.spec.ts
index f64740eb67..3bf8bd3c74 100644
--- a/packages/commons/src/lib/link_embed.spec.ts
+++ b/packages/commons/src/lib/link_embed.spec.ts
@@ -74,12 +74,28 @@ describe("isUrlAloneInBlock", () => {
});
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");
+ /** The full gesture: a URL left alone on its own line, then Enter. */
+ const leftAloneOnItsOwnLine = {
+ urlAloneInBlock: true,
+ blockIsStandalone: true,
+ caretLeftBlock: true
+ };
+
+ it("gives a URL left alone on its own line a block preview, keyed by the URL", () => {
+ // An embeddable URL becomes a player; anything else becomes a card.
+ expect(chooseLinkPreviewKind("youtube", leftAloneOnItsOwnLine)).toBe("embed");
+ expect(chooseLinkPreviewKind("opengraph", leftAloneOnItsOwnLine)).toBe("card");
+ });
+
+ it("keeps every other placement inline, embeddable or not", () => {
+ for (const embedType of ["youtube", "opengraph"]) {
+ // Text either side of it: a block preview cannot go mid-sentence.
+ expect(chooseLinkPreviewKind(embedType, { ...leftAloneOnItsOwnLine, urlAloneInBlock: false })).toBe("mention");
+ // Inside a list, table, quote or heading.
+ expect(chooseLinkPreviewKind(embedType, { ...leftAloneOnItsOwnLine, blockIsStandalone: false })).toBe("mention");
+ // The caret is still in the block, so the user may yet type on that line — the URL has
+ // not been *left* alone, it merely happens to be alone right now.
+ expect(chooseLinkPreviewKind(embedType, { ...leftAloneOnItsOwnLine, caretLeftBlock: false })).toBe("mention");
+ }
});
});
diff --git a/packages/commons/src/lib/link_embed.ts b/packages/commons/src/lib/link_embed.ts
index 2411128caf..f9da1063ca 100644
--- a/packages/commons/src/lib/link_embed.ts
+++ b/packages/commons/src/lib/link_embed.ts
@@ -52,14 +52,39 @@ export function isUrlAloneInBlock(children: Iterable<BlockChildLike>, url: strin
return text.trim() === url;
}
-export type LinkPreviewKind = "embed" | "mention";
+export type LinkPreviewKind = "embed" | "card" | "mention";
+
+/** Where an auto-detected URL sits, and what the user did right after typing it. */
+export interface LinkPreviewPlacement {
+ /** The URL is the block's only content (see {@link isUrlAloneInBlock}). */
+ urlAloneInBlock: boolean;
+ /**
+ * The block is a plain top-level paragraph — not a list item, table cell, quote or heading.
+ * A block-level preview inside those reads as a layout accident, so they stay inline.
+ */
+ blockIsStandalone: boolean;
+ /**
+ * The caret has left the block, which is what pressing Enter does. While the caret is still
+ * there the user is plausibly mid-sentence, so the URL has not (yet) been *left* alone.
+ */
+ caretLeftBlock: boolean;
+}
/**
- * 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.
+ * Chooses how an auto-detected URL should be previewed.
+ *
+ * A URL only becomes a block-level preview when the user deliberately left it alone on its own
+ * line — sole content of a plain paragraph, then Enter. That gesture is the signal; anything else
+ * (text either side, a list/table/quote, or a caret still sitting in the block because the user is
+ * still typing) yields an unobtrusive inline mention.
+ *
+ * Given that gesture, the URL decides which block form: an embeddable one (e.g. YouTube) becomes a
+ * player, everything else a card.
*/
-export function chooseLinkPreviewKind(embedType: string, urlAloneInBlock: boolean): LinkPreviewKind {
- return embedType !== "opengraph" && urlAloneInBlock ? "embed" : "mention";
+export function chooseLinkPreviewKind(embedType: string, placement: LinkPreviewPlacement): LinkPreviewKind {
+ if (!placement.urlAloneInBlock || !placement.blockIsStandalone || !placement.caretLeftBlock) {
+ return "mention";
+ }
+
+ return embedType !== "opengraph" ? "embed" : "card";
}