Skip to content

Build your personal knowledge base with Trilium Notes

feat(link_embed): switch to server-side handling

Elian Doran1621681551ff
diff --git a/apps/client/src/services/link_embed.spec.ts b/apps/client/src/services/link_embed.spec.ts
index a03273f77b..4f9db68b6e 100644
--- a/apps/client/src/services/link_embed.spec.ts
+++ b/apps/client/src/services/link_embed.spec.ts
@@ -1,43 +1,5 @@
import { describe, expect, it } from "vitest";
-import { extractYouTubeVideoId, detectEmbedType, safeHostname } from "./link_embed.js";
-
-describe("extractYouTubeVideoId", () => {
- it("extracts from standard watch URL", () => {
- expect(extractYouTubeVideoId("https://www.youtube.com/watch?v=dQw4w9WgXcQ")).toBe("dQw4w9WgXcQ");
- });
-
- it("extracts from youtu.be short URL", () => {
- expect(extractYouTubeVideoId("https://youtu.be/dQw4w9WgXcQ")).toBe("dQw4w9WgXcQ");
- });
-
- it("extracts from youtu.be with query params", () => {
- expect(extractYouTubeVideoId("https://youtu.be/fV16ck4Bgc0?si=bxl0pGUK2VIfUHkw")).toBe("fV16ck4Bgc0");
- });
-
- it("extracts from embed URL", () => {
- expect(extractYouTubeVideoId("https://www.youtube.com/embed/dQw4w9WgXcQ")).toBe("dQw4w9WgXcQ");
- });
-
- it("extracts from shorts URL", () => {
- expect(extractYouTubeVideoId("https://www.youtube.com/shorts/abcde_-FGHI")).toBe("abcde_-FGHI");
- });
-
- it("extracts from watch URL with extra params", () => {
- expect(extractYouTubeVideoId("https://www.youtube.com/watch?v=dQw4w9WgXcQ&list=PLrAXtmErZgOeiKm4sgNOknGvNjby9efdf")).toBe("dQw4w9WgXcQ");
- });
-
- it("returns null for non-YouTube URLs", () => {
- expect(extractYouTubeVideoId("https://example.com")).toBeNull();
- });
-
- it("returns null for empty string", () => {
- expect(extractYouTubeVideoId("")).toBeNull();
- });
-
- it("returns null for YouTube URL without video ID", () => {
- expect(extractYouTubeVideoId("https://www.youtube.com/")).toBeNull();
- });
-});
+import { detectEmbedType, safeHostname } from "./link_embed.js";
describe("detectEmbedType", () => {
it("detects YouTube URLs", () => {
diff --git a/apps/client/src/services/link_embed.ts b/apps/client/src/services/link_embed.ts
index e58f291023..9a33caeb21 100644
--- a/apps/client/src/services/link_embed.ts
+++ b/apps/client/src/services/link_embed.ts
@@ -1,193 +1,47 @@
-import "../widgets/type_widgets/text/LinkEmbed.css";
-
import type { LinkEmbedMetadata } from "@triliumnext/commons";
+import type { EmbedMetadata } from "@triliumnext/ckeditor5";
import server from "./server.js";
/** Paste mode chosen by user from the floating popup. */
export type LinkPasteMode = "mention" | "url" | "embed";
-const metadataCache = new Map<string, LinkEmbedMetadata>();
-const pendingRequests = new Map<string, Promise<LinkEmbedMetadata>>();
-
const YOUTUBE_REGEX = /(?:youtube\.com\/watch\?.*v=|youtu\.be\/|youtube\.com\/embed\/|youtube\.com\/shorts\/)([a-zA-Z0-9_-]{11})/;
-export function extractYouTubeVideoId(url: string): string | null {
- const match = url.match(YOUTUBE_REGEX);
- return match ? match[1] : null;
-}
-
export function detectEmbedType(url: string): "youtube" | "opengraph" {
- return extractYouTubeVideoId(url) ? "youtube" : "opengraph";
+ return YOUTUBE_REGEX.test(url) ? "youtube" : "opengraph";
}
-export function safeHostname(url: string): string {
+/**
+ * Fetches link metadata from the server. Called once at link creation time.
+ * The returned metadata is then stored in the note's HTML as data attributes.
+ */
+export async function fetchMetadata(url: string): Promise<EmbedMetadata> {
try {
- return new URL(url).hostname;
+ const metadata = await server.get<LinkEmbedMetadata>(`link-embed/metadata?url=${encodeURIComponent(url)}`);
+ return {
+ url: metadata.url,
+ embedType: metadata.embedType,
+ title: metadata.title,
+ description: metadata.description,
+ favicon: metadata.favicon,
+ siteName: metadata.siteName,
+ image: metadata.image
+ };
} catch {
- return url;
- }
-}
-
-export async function fetchMetadata(url: string): Promise<LinkEmbedMetadata> {
- const cached = metadataCache.get(url);
- if (cached) return cached;
-
- const pending = pendingRequests.get(url);
- if (pending) return pending;
-
- const request = server.get<LinkEmbedMetadata>(`link-embed/metadata?url=${encodeURIComponent(url)}`)
- .then((metadata) => {
- metadataCache.set(url, metadata);
- pendingRequests.delete(url);
- return metadata;
- })
- .catch(() => {
- pendingRequests.delete(url);
- const fallback: LinkEmbedMetadata = {
- url,
- title: safeHostname(url),
- embedType: detectEmbedType(url)
- };
- metadataCache.set(url, fallback);
- return fallback;
- });
-
- pendingRequests.set(url, request);
- return request;
-}
-
-// ---------------------------------------------------------------------------
-// Loading spinner (shared by all renderers)
-// ---------------------------------------------------------------------------
-
-function createLoadingEl(): JQuery<HTMLElement> {
- return $('<div class="link-embed-loader">').append(
- $('<div class="link-embed-loader-dot">'),
- $('<div class="link-embed-loader-dot">'),
- $('<div class="link-embed-loader-dot">')
- );
-}
-
-// ---------------------------------------------------------------------------
-// Mention renderer (inline: favicon + title)
-// ---------------------------------------------------------------------------
-
-export async function renderMention(url: string, $container: JQuery<HTMLElement>) {
- $container.empty().append(createLoadingEl());
-
- const metadata = await fetchMetadata(url);
- const $link = $('<a class="link-embed-mention">')
- .attr("href", metadata.url)
- .attr("target", "_blank")
- .attr("rel", "noopener noreferrer");
-
- const faviconSrc = metadata.favicon
- || `https://www.google.com/s2/favicons?domain=${encodeURIComponent(safeHostname(url))}&sz=32`;
-
- $link.append(
- $('<img class="link-embed-mention-favicon">')
- .attr("src", faviconSrc)
- .attr("width", "16")
- .attr("height", "16")
- .on("error", function () { $(this).replaceWith($('<span class="link-embed-mention-dot">')); })
- );
-
- const displayTitle = metadata.embedType === "youtube" && metadata.siteName
- ? `${metadata.siteName} - ${metadata.title || "Video"}`
- : metadata.title || safeHostname(url);
-
- $link.append($('<span class="link-embed-mention-title">').text(displayTitle));
- $container.empty().append($link);
-}
-
-// ---------------------------------------------------------------------------
-// Embed renderer (YouTube = iframe, otherwise = card)
-// ---------------------------------------------------------------------------
-
-export async function renderEmbed(url: string, embedType: string, $container: JQuery<HTMLElement>) {
- const videoId = extractYouTubeVideoId(url);
- if (videoId) {
- const origin = window.location.origin;
- $container.empty().append(
- $('<div class="link-embed-video">').append(
- $('<iframe>')
- .attr("src", `https://www.youtube-nocookie.com/embed/${videoId}?origin=${encodeURIComponent(origin)}&rel=0`)
- .attr("frameborder", "0")
- .attr("allowfullscreen", "true")
- .attr("allow", "accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share")
- .attr("referrerpolicy", "strict-origin-when-cross-origin")
- .attr("loading", "lazy")
- )
- );
- return;
- }
-
- // Non-YouTube: card preview
- $container.empty().append(createLoadingEl());
-
- const metadata = await fetchMetadata(url);
- renderCard(metadata, $container);
-}
-
-// ---------------------------------------------------------------------------
-// Card renderer (Notion-style: image left, content right)
-// ---------------------------------------------------------------------------
-
-function renderCard(metadata: LinkEmbedMetadata, $container: JQuery<HTMLElement>) {
- const $card = $('<a class="link-embed-card">')
- .attr("href", metadata.url)
- .attr("target", "_blank")
- .attr("rel", "noopener noreferrer");
-
- if (metadata.image) {
- const $imgWrap = $('<div class="link-embed-card-image-wrapper">');
- $imgWrap.append(
- $('<img class="link-embed-card-image">')
- .attr("src", metadata.image)
- .attr("alt", "")
- .attr("loading", "lazy")
- .on("error", function () {
- $imgWrap.empty().append($('<div class="link-embed-card-image-placeholder">').html("&#128279;"));
- })
- );
- $card.append($imgWrap);
- } else {
- $card.append(
- $('<div class="link-embed-card-image-wrapper">').append(
- $('<div class="link-embed-card-image-placeholder">').html(
- metadata.embedType === "youtube" ? "&#9654;" : "&#128279;"
- )
- )
- );
+ return {
+ url,
+ embedType: detectEmbedType(url),
+ title: safeHostname(url)
+ };
}
-
- const $content = $('<div class="link-embed-card-content">');
- if (metadata.title) $content.append($('<div class="link-embed-card-title">').text(metadata.title));
- if (metadata.description) $content.append($('<div class="link-embed-card-description">').text(metadata.description));
- $content.append($('<div class="link-embed-card-url">').text(metadata.siteName || safeHostname(metadata.url)));
-
- $card.append($content);
- $container.empty().append($card);
}
-/**
- * Renders the appropriate preview based on embedType.
- * Used by ReadOnlyText and share renderer for persisted elements.
- */
-export async function renderPreview(url: string, embedType: string, $container: JQuery<HTMLElement>) {
- if (embedType === "mention") {
- await renderMention(url, $container);
- } else {
- await renderEmbed(url, embedType, $container);
- }
+export function safeHostname(url: string): string {
+ try { return new URL(url).hostname; } catch { return url; }
}
export default {
fetchMetadata,
- renderPreview,
- renderMention,
- renderEmbed,
detectEmbedType,
- extractYouTubeVideoId,
safeHostname
};
diff --git a/apps/client/src/widgets/dialogs/link_embed.tsx b/apps/client/src/widgets/dialogs/link_embed.tsx
index 4731d26b99..59f98aec17 100644
--- a/apps/client/src/widgets/dialogs/link_embed.tsx
+++ b/apps/client/src/widgets/dialogs/link_embed.tsx
@@ -25,17 +25,19 @@ export default function LinkEmbedDialog() {
setShown(true);
});
- const handleSubmit = () => {
+ const handleSubmit = async () => {
const trimmedUrl = url.trim();
if (!trimmedUrl || !editorApiRef.current) return;
- if (mode === "mention") {
- editorApiRef.current.addLinkMention(trimmedUrl);
- } else if (mode === "url") {
+ if (mode === "url") {
editorApiRef.current.addLinkToEditor(trimmedUrl, trimmedUrl);
} else {
- const embedType = linkEmbedService.detectEmbedType(trimmedUrl);
- editorApiRef.current.addLinkEmbed(trimmedUrl, embedType);
+ const metadata = await linkEmbedService.fetchMetadata(trimmedUrl);
+ if (mode === "mention") {
+ editorApiRef.current.addLinkMention(metadata);
+ } else {
+ editorApiRef.current.addLinkEmbed(metadata);
+ }
}
setShown(false);
};
diff --git a/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx b/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx
index 342ff0fb23..eca26ce9b8 100644
--- a/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx
+++ b/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx
@@ -1,4 +1,4 @@
-import { CKTextEditor, ClassicEditor, EditorWatchdog, PopupEditor, TemplateDefinition,type WatchdogConfig } from "@triliumnext/ckeditor5";
+import { CKTextEditor, ClassicEditor, EditorWatchdog, PopupEditor, TemplateDefinition, type EmbedMetadata, type WatchdogConfig } from "@triliumnext/ckeditor5";
import { DISPLAYABLE_LOCALE_IDS } from "@triliumnext/commons";
import { HTMLProps, RefObject, useEffect, useImperativeHandle, useRef, useState } from "preact/compat";
@@ -19,8 +19,8 @@ export interface CKEditorApi {
addHtmlToEditor(html: string): void;
addIncludeNote(noteId: string, boxSize?: BoxSize): void;
addImage(noteId: string): Promise<void>;
- addLinkEmbed(url: string, embedType: string): void;
- addLinkMention(url: string): void;
+ addLinkEmbed(metadata: EmbedMetadata): void;
+ addLinkMention(metadata: EmbedMetadata): void;
}
interface CKEditorWithWatchdogProps extends Pick<HTMLProps<HTMLDivElement>, "className" | "tabIndex"> {
@@ -143,23 +143,35 @@ export default function CKEditorWithWatchdog({ containerRef: externalContainerRe
editor?.execute("insertImage", { source: src });
});
},
- addLinkEmbed(url: string, embedType: string) {
+ addLinkEmbed(metadata: EmbedMetadata) {
const editor = watchdogRef.current?.editor;
if (!editor) return;
editor.model.change((writer) => {
editor.model.insertContent(
- writer.createElement("linkEmbed", { url, embedType })
+ 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(url: string) {
+ addLinkMention(metadata: EmbedMetadata) {
const editor = watchdogRef.current?.editor;
if (!editor) return;
editor.model.change((writer) => {
editor.model.insertContent(
- writer.createElement("linkMention", { url })
+ writer.createElement("linkMention", {
+ url: metadata.url,
+ title: metadata.title,
+ favicon: metadata.favicon
+ })
);
});
},
@@ -169,11 +181,8 @@ export default function CKEditorWithWatchdog({ containerRef: externalContainerRe
async loadReferenceLinkTitle($el: JQuery<HTMLElement>, href: string | null = null) {
await link.loadReferenceLinkTitle($el, href);
},
- loadLinkEmbedPreview(url: string, embedType: string, $el: JQuery<HTMLElement>) {
- linkEmbedService.renderPreview(url, embedType, $el);
- },
- loadLinkMentionPreview(url: string, $el: JQuery<HTMLElement>) {
- linkEmbedService.renderMention(url, $el);
+ async fetchLinkMetadata(url: string) {
+ return await linkEmbedService.fetchMetadata(url);
}
});
diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsx
index d03c64fb83..820b89f29b 100644
--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx
+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx
@@ -1,4 +1,5 @@
import "./EditableText.css";
+import "./LinkEmbed.css";
import { CKTextEditor, EditorWatchdog, TemplateDefinition } from "@triliumnext/ckeditor5";
import { deferred } from "@triliumnext/commons";
@@ -141,11 +142,8 @@ export default function EditableText({ note, parentComponent, ntxId, noteContext
editorApi: editorApiRef.current,
});
},
- loadLinkEmbedPreview(url: string, embedType: string, $el: JQuery<HTMLElement>) {
- linkEmbedService.renderPreview(url, embedType, $el);
- },
- loadLinkMentionPreview(url: string, $el: JQuery<HTMLElement>) {
- linkEmbedService.renderMention(url, $el);
+ async fetchLinkMetadata(url: string) {
+ return await linkEmbedService.fetchMetadata(url);
},
// Creating notes in @-completion
async createNoteForReferenceLink(title: string) {
diff --git a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx
index 21357fd11f..9c3eea71bb 100644
--- a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx
+++ b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx
@@ -1,4 +1,5 @@
import "./ReadOnlyText.css";
+import "./LinkEmbed.css";
// we load CKEditor also for read only notes because they contain content styles required for correct rendering of even read only notes
// we could load just ckeditor-content.css but that causes CSS conflicts when both build CSS and this content CSS is loaded at the same time
// (see https://github.com/zadam/trilium/issues/1590 for example of such conflict)
@@ -18,7 +19,7 @@ import { useNoteBlob, useNoteLabel, useSyncedRef, useTriliumEvent, useTriliumOpt
import { RawHtmlBlock } from "../../react/RawHtml";
import TouchBar, { TouchBarButton, TouchBarSpacer } from "../../react/TouchBar";
import { TypeWidgetProps } from "../type_widget";
-import linkEmbedService from "../../../services/link_embed";
+import { renderEmbedPreview, renderMentionPreview } from "@triliumnext/ckeditor5";
import { applyReferenceLinks } from "./read_only_helper";
import { loadIncludedNote, refreshIncludedNote, setupImageOpening } from "./utils";
@@ -155,15 +156,28 @@ function applyIncludedNotes(container: HTMLDivElement) {
function applyLinkEmbeds(container: HTMLDivElement) {
for (const embed of container.querySelectorAll<HTMLElement>("section.link-embed")) {
const url = embed.dataset.url;
- const embedType = embed.dataset.embedType;
if (!url) continue;
- linkEmbedService.renderPreview(url, embedType || "opengraph", $(embed));
+ embed.innerHTML = "";
+ renderEmbedPreview(embed, {
+ url,
+ embedType: embed.dataset.embedType || "opengraph",
+ title: embed.dataset.title,
+ description: embed.dataset.description,
+ favicon: embed.dataset.favicon,
+ siteName: embed.dataset.siteName,
+ image: embed.dataset.image
+ });
}
for (const mention of container.querySelectorAll<HTMLElement>("span.link-mention")) {
const url = mention.dataset.url;
if (!url) continue;
- linkEmbedService.renderMention(url, $(mention));
+ mention.innerHTML = "";
+ renderMentionPreview(mention, {
+ url,
+ title: mention.dataset.title,
+ favicon: mention.dataset.favicon
+ });
}
}
diff --git a/apps/server/src/routes/api/link_embed.ts b/apps/server/src/routes/api/link_embed.ts
index 8a55a96396..1ae463d043 100644
--- a/apps/server/src/routes/api/link_embed.ts
+++ b/apps/server/src/routes/api/link_embed.ts
@@ -6,6 +6,7 @@ import { ValidationError } from "@triliumnext/core";
const FETCH_TIMEOUT_MS = 5000;
const MAX_RESPONSE_SIZE = 512 * 1024; // 512KB
+const MAX_FAVICON_SIZE = 64 * 1024; // 64KB
const YOUTUBE_REGEX = /(?:youtube\.com\/watch\?.*v=|youtu\.be\/|youtube\.com\/embed\/|youtube\.com\/shorts\/)([a-zA-Z0-9_-]{11})/;
@@ -49,6 +50,54 @@ function validateUrl(urlString: string): URL {
return parsed;
}
+/**
+ * Downloads a favicon and returns it as a base64 data URI.
+ * Returns undefined if the download fails or the image is too large.
+ */
+async function downloadFaviconAsDataUri(faviconUrl: string): Promise<string | undefined> {
+ try {
+ const response = await fetch(faviconUrl, {
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
+ redirect: "follow"
+ });
+
+ if (!response.ok) return undefined;
+
+ const contentType = response.headers.get("content-type") || "image/x-icon";
+ const buffer = await response.arrayBuffer();
+
+ if (buffer.byteLength > MAX_FAVICON_SIZE) return undefined;
+
+ const base64 = Buffer.from(buffer).toString("base64");
+ return `data:${contentType.split(";")[0]};base64,${base64}`;
+ } catch {
+ return undefined;
+ }
+}
+
+/**
+ * Resolves a favicon URL from the parsed HTML, then downloads it as a data URI.
+ */
+async function resolveFavicon(document: ReturnType<typeof parse>, pageUrl: string): Promise<string | undefined> {
+ const faviconEl = document.querySelector('link[rel="icon"]')
+ || document.querySelector('link[rel="shortcut icon"]')
+ || document.querySelector('link[rel="apple-touch-icon"]');
+
+ let faviconUrl: string | undefined;
+ if (faviconEl) {
+ const href = faviconEl.getAttribute("href");
+ if (href) {
+ try { faviconUrl = new URL(href, pageUrl).toString(); } catch { /* ignore */ }
+ }
+ }
+ if (!faviconUrl) {
+ try { faviconUrl = `${new URL(pageUrl).origin}/favicon.ico`; } catch { /* ignore */ }
+ }
+
+ if (!faviconUrl) return undefined;
+ return await downloadFaviconAsDataUri(faviconUrl);
+}
+
/**
* Fetches YouTube metadata via the public oEmbed endpoint.
* This works reliably unlike scraping youtube.com (which blocks bots).
@@ -57,11 +106,13 @@ async function fetchYouTubeMetadata(url: string, videoId: string): Promise<LinkE
const metadata: LinkEmbedMetadata = {
url,
image: `https://img.youtube.com/vi/${videoId}/hqdefault.jpg`,
- favicon: "https://www.youtube.com/favicon.ico",
siteName: "YouTube",
embedType: "youtube"
};
+ // Download YouTube favicon as data URI
+ metadata.favicon = await downloadFaviconAsDataUri("https://www.youtube.com/favicon.ico");
+
try {
const oembedUrl = `https://www.youtube.com/oembed?url=${encodeURIComponent(url)}&format=json`;
const response = await fetch(oembedUrl, {
@@ -106,19 +157,7 @@ async function fetchOpenGraphData(url: string) {
return undefined;
};
- const faviconEl = document.querySelector('link[rel="icon"]')
- || document.querySelector('link[rel="shortcut icon"]')
- || document.querySelector('link[rel="apple-touch-icon"]');
- let favicon: string | undefined;
- if (faviconEl) {
- const href = faviconEl.getAttribute("href");
- if (href) {
- try { favicon = new URL(href, url).toString(); } catch { /* ignore */ }
- }
- }
- if (!favicon) {
- try { favicon = `${new URL(url).origin}/favicon.ico`; } catch { /* ignore */ }
- }
+ const favicon = await resolveFavicon(document, url);
return {
title: getMeta("og:title") || document.querySelector("title")?.textContent || undefined,
diff --git a/apps/server/src/share/content_renderer.ts b/apps/server/src/share/content_renderer.ts
index 60dccb07f6..063851487a 100644
--- a/apps/server/src/share/content_renderer.ts
+++ b/apps/server/src/share/content_renderer.ts
@@ -326,18 +326,21 @@ function renderText(result: Result, note: SNote | BNote) {
};
const document = parse(result.content || "", parseOpts);
- // Process link mentions (inline).
+ // Process link mentions (inline) — metadata is stored in data attributes.
for (const mentionEl of document.querySelectorAll("span.link-mention")) {
const url = mentionEl.getAttribute("data-url");
if (!url) continue;
- const hostname = safeHostnameForShare(url);
- const favicon = `https://www.google.com/s2/favicons?domain=${encodeURIComponent(hostname)}&sz=32`;
+ const title = mentionEl.getAttribute("data-title") || safeHostnameForShare(url);
+ const favicon = mentionEl.getAttribute("data-favicon");
+ const faviconHtml = favicon
+ ? `<img class="link-embed-mention-favicon" src="${escapeHtml(favicon)}" width="16" height="16">`
+ : `<span class="link-embed-mention-dot"></span>`;
mentionEl.innerHTML = `<a class="link-embed-mention" href="${escapeHtml(url)}" target="_blank" rel="noopener noreferrer">` +
- `<img class="link-embed-mention-favicon" src="${escapeHtml(favicon)}" width="16" height="16">` +
- `<span class="link-embed-mention-title">${escapeHtml(hostname)}</span></a>`;
+ faviconHtml +
+ `<span class="link-embed-mention-title">${escapeHtml(title)}</span></a>`;
}
- // Process link embeds (block).
+ // Process link embeds (block) — metadata is stored in data attributes.
for (const embedEl of document.querySelectorAll("section.link-embed")) {
const url = embedEl.getAttribute("data-url");
const embedType = embedEl.getAttribute("data-embed-type");
@@ -349,10 +352,19 @@ function renderText(result: Result, note: SNote | BNote) {
embedEl.innerHTML = `<div class="link-embed-video"><iframe src="https://www.youtube-nocookie.com/embed/${escapeHtml(videoId)}?rel=0" frameborder="0" allowfullscreen loading="lazy" referrerpolicy="strict-origin-when-cross-origin" style="width:100%;aspect-ratio:16/9;border:none;"></iframe></div>`;
}
} else {
- const hostname = safeHostnameForShare(url);
+ const title = embedEl.getAttribute("data-title") || safeHostnameForShare(url);
+ const description = embedEl.getAttribute("data-description");
+ const image = embedEl.getAttribute("data-image");
+ const siteName = embedEl.getAttribute("data-site-name") || safeHostnameForShare(url);
+
+ const imageHtml = image
+ ? `<div class="link-embed-card-image-wrapper"><img class="link-embed-card-image" src="${escapeHtml(image)}" alt="" loading="lazy"></div>`
+ : `<div class="link-embed-card-image-wrapper"><div class="link-embed-card-image-placeholder">&#128279;</div></div>`;
+ const descHtml = description ? `<div class="link-embed-card-description">${escapeHtml(description)}</div>` : "";
+
embedEl.innerHTML = `<a class="link-embed-card" href="${escapeHtml(url)}" target="_blank" rel="noopener noreferrer">` +
- `<div class="link-embed-card-image-wrapper"><div class="link-embed-card-image-placeholder">&#128279;</div></div>` +
- `<div class="link-embed-card-content"><div class="link-embed-card-title">${escapeHtml(hostname)}</div><div class="link-embed-card-url">${escapeHtml(url)}</div></div></a>`;
+ imageHtml +
+ `<div class="link-embed-card-content"><div class="link-embed-card-title">${escapeHtml(title)}</div>${descHtml}<div class="link-embed-card-url">${escapeHtml(siteName)}</div></div></a>`;
}
}
diff --git a/packages/ckeditor5/src/augmentation.ts b/packages/ckeditor5/src/augmentation.ts
index 72b0ad14d7..c74630e27c 100644
--- a/packages/ckeditor5/src/augmentation.ts
+++ b/packages/ckeditor5/src/augmentation.ts
@@ -9,8 +9,7 @@ declare global {
loadReferenceLinkTitle($el: JQuery<HTMLElement>, href: string): Promise<void>;
createNoteForReferenceLink(title: string): Promise<string>;
loadIncludedNote(noteId: string, $el: JQuery<HTMLElement>): void;
- loadLinkEmbedPreview(url: string, embedType: string, $el: JQuery<HTMLElement>): void;
- loadLinkMentionPreview(url: string, $el: JQuery<HTMLElement>): void;
+ fetchLinkMetadata(url: string): Promise<import("./plugins/linkembed.js").EmbedMetadata>;
}
var glob: {
diff --git a/packages/ckeditor5/src/index.ts b/packages/ckeditor5/src/index.ts
index ca51d92d7b..3b352a3191 100644
--- a/packages/ckeditor5/src/index.ts
+++ b/packages/ckeditor5/src/index.ts
@@ -12,6 +12,7 @@ export type { TemplateDefinition } from "ckeditor5-premium-features";
export { default as buildExtraCommands } from "./extra_slash_commands.js";
export { default as getCkLocale } from "./i18n.js";
export * from "./utils.js";
+export { renderEmbedPreview, renderMentionPreview, type EmbedMetadata } from "./plugins/linkembed.js";
// Import with sideffects to ensure that type augmentations are present.
import "@triliumnext/ckeditor5-math";
diff --git a/packages/ckeditor5/src/plugins/linkembed.ts b/packages/ckeditor5/src/plugins/linkembed.ts
index 0d49165804..9e00cab92b 100644
--- a/packages/ckeditor5/src/plugins/linkembed.ts
+++ b/packages/ckeditor5/src/plugins/linkembed.ts
@@ -65,14 +65,14 @@ class LinkEmbedEditing extends Plugin {
schema.register('linkEmbed', {
isObject: true,
- allowAttributes: ['url', 'embedType'],
+ allowAttributes: ['url', 'embedType', 'title', 'description', 'favicon', 'siteName', 'image'],
allowWhere: '$block'
});
schema.register('linkMention', {
isInline: true,
isObject: true,
- allowAttributes: ['url'],
+ allowAttributes: ['url', 'title', 'favicon'],
allowWhere: '$text'
});
}
@@ -87,7 +87,12 @@ class LinkEmbedEditing extends Plugin {
model: (viewElement, { writer }) => {
return writer.createElement('linkEmbed', {
url: viewElement.getAttribute('data-url'),
- embedType: viewElement.getAttribute('data-embed-type')
+ embedType: viewElement.getAttribute('data-embed-type'),
+ title: viewElement.getAttribute('data-title'),
+ description: viewElement.getAttribute('data-description'),
+ favicon: viewElement.getAttribute('data-favicon'),
+ siteName: viewElement.getAttribute('data-site-name'),
+ image: viewElement.getAttribute('data-image')
});
},
view: { name: 'section', classes: 'link-embed' }
@@ -96,11 +101,19 @@ class LinkEmbedEditing extends Plugin {
conversion.for('dataDowncast').elementToElement({
model: 'linkEmbed',
view: (modelElement, { writer }) => {
- return writer.createContainerElement('section', {
+ const attrs: Record<string, string> = {
class: 'link-embed',
- 'data-url': modelElement.getAttribute('url'),
- 'data-embed-type': modelElement.getAttribute('embedType')
- });
+ 'data-url': modelElement.getAttribute('url') as string,
+ 'data-embed-type': modelElement.getAttribute('embedType') as string
+ };
+ for (const key of ['title', 'description', 'favicon', 'siteName', 'image'] as const) {
+ const val = modelElement.getAttribute(key) as string | undefined;
+ if (val) {
+ const attrName = key === 'siteName' ? 'data-site-name' : `data-${key}`;
+ attrs[attrName] = val;
+ }
+ }
+ return writer.createContainerElement('section', attrs);
}
});
@@ -109,6 +122,11 @@ class LinkEmbedEditing extends Plugin {
view: (modelElement, { writer }) => {
const url = modelElement.getAttribute('url') as string;
const embedType = modelElement.getAttribute('embedType') as string;
+ const title = modelElement.getAttribute('title') as string | undefined;
+ const description = modelElement.getAttribute('description') as string | undefined;
+ const favicon = modelElement.getAttribute('favicon') as string | undefined;
+ const siteName = modelElement.getAttribute('siteName') as string | undefined;
+ const image = modelElement.getAttribute('image') as string | undefined;
const section = writer.createContainerElement('section', {
class: 'link-embed',
@@ -121,9 +139,7 @@ class LinkEmbedEditing extends Plugin {
'data-cke-ignore-events': 'true'
}, function (domDocument) {
const domElement = this.toDomElement(domDocument);
- const editorEl = editor.editing.view.getDomRoot();
- const component = glob.getComponentByEl<EditorComponent>(editorEl);
- component.loadLinkEmbedPreview(url, embedType, $(domElement));
+ renderEmbedPreview(domElement, { url, embedType, title, description, favicon, siteName, image });
preventCKEditorHandling(domElement, editor);
return domElement;
});
@@ -138,7 +154,9 @@ class LinkEmbedEditing extends Plugin {
conversion.for('upcast').elementToElement({
model: (viewElement, { writer }) => {
return writer.createElement('linkMention', {
- url: viewElement.getAttribute('data-url')
+ url: viewElement.getAttribute('data-url'),
+ title: viewElement.getAttribute('data-title'),
+ favicon: viewElement.getAttribute('data-favicon')
});
},
view: { name: 'span', classes: 'link-mention' }
@@ -147,10 +165,15 @@ class LinkEmbedEditing extends Plugin {
conversion.for('dataDowncast').elementToElement({
model: 'linkMention',
view: (modelElement, { writer }) => {
- return writer.createContainerElement('span', {
+ const attrs: Record<string, string> = {
class: 'link-mention',
- 'data-url': modelElement.getAttribute('url')
- });
+ 'data-url': modelElement.getAttribute('url') as string
+ };
+ const title = modelElement.getAttribute('title') as string | undefined;
+ const favicon = modelElement.getAttribute('favicon') as string | undefined;
+ if (title) attrs['data-title'] = title;
+ if (favicon) attrs['data-favicon'] = favicon;
+ return writer.createContainerElement('span', attrs);
}
});
@@ -158,6 +181,8 @@ class LinkEmbedEditing extends Plugin {
model: 'linkMention',
view: (modelElement, { writer }) => {
const url = modelElement.getAttribute('url') as string;
+ const title = modelElement.getAttribute('title') as string | undefined;
+ const favicon = modelElement.getAttribute('favicon') as string | undefined;
const span = writer.createContainerElement('span', {
class: 'link-mention',
@@ -169,9 +194,7 @@ class LinkEmbedEditing extends Plugin {
'data-cke-ignore-events': 'true'
}, function (domDocument) {
const domElement = this.toDomElement(domDocument);
- const editorEl = editor.editing.view.getDomRoot();
- const component = glob.getComponentByEl<EditorComponent>(editorEl);
- component.loadLinkMentionPreview(url, $(domElement));
+ renderMentionPreview(domElement, { url, title, favicon });
preventCKEditorHandling(domElement, editor);
return domElement;
});
@@ -183,6 +206,128 @@ class LinkEmbedEditing extends Plugin {
}
}
+// ---------------------------------------------------------------------------
+// DOM renderers — render previews from stored metadata, no network requests
+// ---------------------------------------------------------------------------
+
+interface EmbedMetadata {
+ url: string;
+ embedType: string;
+ title?: string;
+ description?: string;
+ favicon?: string;
+ siteName?: string;
+ image?: string;
+}
+
+function safeHostname(url: string): string {
+ try { return new URL(url).hostname; } catch { return url; }
+}
+
+function renderEmbedPreview(container: HTMLElement, meta: EmbedMetadata) {
+ const videoId = YOUTUBE_URL_REGEX.test(meta.url)
+ ? meta.url.match(/(?:youtube\.com\/watch\?.*v=|youtu\.be\/|youtube\.com\/embed\/|youtube\.com\/shorts\/)([a-zA-Z0-9_-]{11})/)?.[1]
+ : null;
+
+ if (videoId) {
+ const origin = window.location.origin;
+ const wrapper = document.createElement('div');
+ wrapper.className = 'link-embed-video';
+ const iframe = document.createElement('iframe');
+ iframe.src = `https://www.youtube-nocookie.com/embed/${videoId}?origin=${encodeURIComponent(origin)}&rel=0`;
+ iframe.setAttribute('frameborder', '0');
+ iframe.setAttribute('allowfullscreen', 'true');
+ iframe.setAttribute('allow', 'accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share');
+ iframe.setAttribute('referrerpolicy', 'strict-origin-when-cross-origin');
+ iframe.loading = 'lazy';
+ wrapper.appendChild(iframe);
+ container.appendChild(wrapper);
+ return;
+ }
+
+ // Card preview
+ const card = document.createElement('a');
+ card.className = 'link-embed-card';
+ card.href = meta.url;
+ card.target = '_blank';
+ card.rel = 'noopener noreferrer';
+
+ const imgWrap = document.createElement('div');
+ imgWrap.className = 'link-embed-card-image-wrapper';
+ if (meta.image) {
+ const img = document.createElement('img');
+ img.className = 'link-embed-card-image';
+ img.src = meta.image;
+ img.alt = '';
+ img.loading = 'lazy';
+ img.onerror = () => {
+ imgWrap.innerHTML = '<div class="link-embed-card-image-placeholder">&#128279;</div>';
+ };
+ imgWrap.appendChild(img);
+ } else {
+ imgWrap.innerHTML = '<div class="link-embed-card-image-placeholder">&#128279;</div>';
+ }
+ card.appendChild(imgWrap);
+
+ const content = document.createElement('div');
+ content.className = 'link-embed-card-content';
+ if (meta.title) {
+ const titleEl = document.createElement('div');
+ titleEl.className = 'link-embed-card-title';
+ titleEl.textContent = meta.title;
+ content.appendChild(titleEl);
+ }
+ if (meta.description) {
+ const descEl = document.createElement('div');
+ descEl.className = 'link-embed-card-description';
+ descEl.textContent = meta.description;
+ content.appendChild(descEl);
+ }
+ const urlEl = document.createElement('div');
+ urlEl.className = 'link-embed-card-url';
+ urlEl.textContent = meta.siteName || safeHostname(meta.url);
+ content.appendChild(urlEl);
+
+ card.appendChild(content);
+ container.appendChild(card);
+}
+
+function renderMentionPreview(container: HTMLElement, meta: { url: string; title?: string; favicon?: string }) {
+ const link = document.createElement('a');
+ link.className = 'link-embed-mention';
+ link.href = meta.url;
+ link.target = '_blank';
+ link.rel = 'noopener noreferrer';
+
+ if (meta.favicon) {
+ const img = document.createElement('img');
+ img.className = 'link-embed-mention-favicon';
+ img.src = meta.favicon;
+ img.width = 16;
+ img.height = 16;
+ img.onerror = () => {
+ const dot = document.createElement('span');
+ dot.className = 'link-embed-mention-dot';
+ img.replaceWith(dot);
+ };
+ link.appendChild(img);
+ } else {
+ const dot = document.createElement('span');
+ dot.className = 'link-embed-mention-dot';
+ link.appendChild(dot);
+ }
+
+ const titleSpan = document.createElement('span');
+ titleSpan.className = 'link-embed-mention-title';
+ titleSpan.textContent = meta.title || safeHostname(meta.url);
+ link.appendChild(titleSpan);
+
+ container.appendChild(link);
+}
+
+// These are exported so the read-only renderer can reuse them.
+export { renderEmbedPreview, renderMentionPreview, type EmbedMetadata };
+
class InsertLinkEmbedCommand extends Command {
override execute() {
const editorEl = this.editor.editing.view.getDomRoot();
@@ -395,59 +540,74 @@ class LinkEmbedPasteHandler extends Plugin {
/**
* Replaces the pasted URL at the captured position with the chosen format.
- * Searches only within the specific parent element and picks the match
- * closest to the recorded child offset.
+ * Fetches metadata from the server first, then inserts with all attributes.
*/
private _convertPastedUrl(url: string, mode: 'mention' | 'embed', location: PasteLocation) {
const editor = this.editor;
+ const editorEl = editor.editing.view.getDomRoot();
+ const component = glob.getComponentByEl<EditorComponent>(editorEl);
+
+ // Fetch metadata asynchronously, then insert into the model
+ component.fetchLinkMetadata(url).then((metadata: EmbedMetadata) => {
+ editor.model.change((writer) => {
+ const root = editor.model.document.getRoot();
+ if (!root) return;
+
+ // Resolve the parent element from the captured path
+ let parentEl = root as ReturnType<typeof root.getChild>;
+ for (const idx of location.parentPath) {
+ if (!parentEl || typeof (parentEl as any).getChild !== 'function') return;
+ parentEl = (parentEl as any).getChild(idx);
+ }
+ if (!parentEl || !parentEl.is('element')) return;
- editor.model.change((writer) => {
- const root = editor.model.document.getRoot();
- if (!root) return;
-
- // Resolve the parent element from the captured path
- let parentEl = root as ReturnType<typeof root.getChild>;
- for (const idx of location.parentPath) {
- if (!parentEl || typeof (parentEl as any).getChild !== 'function') return;
- parentEl = (parentEl as any).getChild(idx);
- }
- if (!parentEl || !parentEl.is('element')) return;
-
- // Find the URL text closest to the recorded offset
- const parentRange = writer.createRangeIn(parentEl);
- let bestStart: Position | null = null;
- let bestEnd: Position | null = null;
- let bestDistance = Infinity;
+ // Find the URL text closest to the recorded offset
+ const parentRange = writer.createRangeIn(parentEl);
+ let bestStart: Position | null = null;
+ let bestEnd: Position | null = null;
+ let bestDistance = Infinity;
- for (const item of parentRange.getWalker()) {
- if (!item.item.is('$textProxy')) continue;
+ for (const item of parentRange.getWalker()) {
+ if (!item.item.is('$textProxy')) continue;
- const text = item.item.data;
- const idx = text.indexOf(url);
- if (idx === -1) continue;
+ const text = item.item.data;
+ const idx = text.indexOf(url);
+ if (idx === -1) continue;
- const startOff = item.item.startOffset! + idx;
- const distance = Math.abs(startOff - location.childOffset);
+ const startOff = item.item.startOffset! + idx;
+ const distance = Math.abs(startOff - location.childOffset);
- if (distance < bestDistance) {
- bestDistance = distance;
- bestStart = writer.createPositionAt(parentEl, startOff);
- bestEnd = writer.createPositionAt(parentEl, startOff + url.length);
+ if (distance < bestDistance) {
+ bestDistance = distance;
+ bestStart = writer.createPositionAt(parentEl, startOff);
+ bestEnd = writer.createPositionAt(parentEl, startOff + url.length);
+ }
}
- }
-
- if (!bestStart || !bestEnd) return;
- const urlRange = writer.createRange(bestStart, bestEnd);
- writer.setSelection(urlRange);
- editor.model.deleteContent(editor.model.document.selection);
-
- if (mode === 'mention') {
- editor.model.insertContent(writer.createElement('linkMention', { url }));
- } else {
- const embedType = YOUTUBE_URL_REGEX.test(url) ? 'youtube' : 'opengraph';
- editor.model.insertContent(writer.createElement('linkEmbed', { url, embedType }));
- }
+ if (!bestStart || !bestEnd) return;
+
+ const urlRange = writer.createRange(bestStart, bestEnd);
+ writer.setSelection(urlRange);
+ editor.model.deleteContent(editor.model.document.selection);
+
+ if (mode === 'mention') {
+ editor.model.insertContent(writer.createElement('linkMention', {
+ url: metadata.url,
+ title: metadata.title,
+ favicon: metadata.favicon
+ }));
+ } else {
+ 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
+ }));
+ }
+ });
});
}