Skip to content

Build your personal knowledge base with Trilium Notes

refactor(link_embed): handle rendering at client side

Elian Doranc5b73a56c8d8
diff --git a/apps/client/src/services/content_renderer_text.ts b/apps/client/src/services/content_renderer_text.ts
index 417738fb24..283340ecc2 100644
--- a/apps/client/src/services/content_renderer_text.ts
+++ b/apps/client/src/services/content_renderer_text.ts
@@ -3,6 +3,7 @@ import FNote from "../entities/fnote.js";
import { default as content_renderer, type RenderOptions } from "./content_renderer.js";
import froca from "./froca.js";
import link from "./link.js";
+import { applyLinkEmbeds } from "./link_embed.js";
import { renderMathInElement } from "./math.js";
import { getMermaidConfig } from "./mermaid.js";
import { formatCodeBlocks } from "./syntax_highlight.js";
@@ -52,6 +53,7 @@ export async function postProcessRichContent(note: FNote | FAttachment, $rendere
el.replaceChildren(innerSpan);
}));
+ applyLinkEmbeds($renderedContent[0]);
await rewriteMermaidDiagramsInContainer($renderedContent[0] as HTMLDivElement);
await formatCodeBlocks($renderedContent);
}
diff --git a/apps/client/src/services/link_embed.ts b/apps/client/src/services/link_embed.ts
index 9a33caeb21..666e40c02c 100644
--- a/apps/client/src/services/link_embed.ts
+++ b/apps/client/src/services/link_embed.ts
@@ -1,16 +1,31 @@
+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";
+export interface EmbedMetadata {
+ url: string;
+ embedType: string;
+ title?: string;
+ description?: string;
+ favicon?: string;
+ siteName?: string;
+ image?: string;
+}
+
const YOUTUBE_REGEX = /(?:youtube\.com\/watch\?.*v=|youtu\.be\/|youtube\.com\/embed\/|youtube\.com\/shorts\/)([a-zA-Z0-9_-]{11})/;
export function detectEmbedType(url: string): "youtube" | "opengraph" {
return YOUTUBE_REGEX.test(url) ? "youtube" : "opengraph";
}
+export function safeHostname(url: string): string {
+ try { return new URL(url).hostname; } catch { return url; }
+}
+
/**
* 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.
@@ -36,12 +51,152 @@ export async function fetchMetadata(url: string): Promise<EmbedMetadata> {
}
}
-export function safeHostname(url: string): string {
- try { return new URL(url).hostname; } catch { return url; }
+// ---------------------------------------------------------------------------
+// DOM renderers — render previews from stored metadata, no network requests.
+// Used by the CKEditor editing downcast (via component interface), the
+// read-only text renderer, and postProcessRichContent (tooltips, included
+// notes, markdown preview).
+// ---------------------------------------------------------------------------
+
+export function renderEmbedPreview(container: HTMLElement, meta: EmbedMetadata) {
+ const videoId = YOUTUBE_REGEX.test(meta.url)
+ ? meta.url.match(YOUTUBE_REGEX)?.[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);
+}
+
+export function renderMentionPreview(container: HTMLElement, meta: { url: string; title?: string; favicon?: string }) {
+ const anchor = document.createElement("a");
+ anchor.className = "link-embed-mention";
+ anchor.href = meta.url;
+ anchor.target = "_blank";
+ anchor.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);
+ };
+ anchor.appendChild(img);
+ } else {
+ const dot = document.createElement("span");
+ dot.className = "link-embed-mention-dot";
+ anchor.appendChild(dot);
+ }
+
+ const titleSpan = document.createElement("span");
+ titleSpan.className = "link-embed-mention-title";
+ titleSpan.textContent = meta.title || safeHostname(meta.url);
+ anchor.appendChild(titleSpan);
+
+ container.appendChild(anchor);
+}
+
+/**
+ * Processes all link embed and mention elements in a container, rendering
+ * previews from their stored data attributes. Analogous to how
+ * `link.loadReferenceLinkTitle` works for reference links.
+ */
+export function applyLinkEmbeds(container: HTMLElement) {
+ for (const embed of container.querySelectorAll<HTMLElement>("section.link-embed")) {
+ const url = embed.dataset.url;
+ if (!url) continue;
+ 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;
+ mention.innerHTML = "";
+ renderMentionPreview(mention, {
+ url,
+ title: mention.dataset.title,
+ favicon: mention.dataset.favicon
+ });
+ }
}
export default {
fetchMetadata,
detectEmbedType,
- safeHostname
+ safeHostname,
+ renderEmbedPreview,
+ renderMentionPreview,
+ applyLinkEmbeds
};
diff --git a/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx b/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx
index eca26ce9b8..e25f1d39fc 100644
--- a/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx
+++ b/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx
@@ -1,10 +1,10 @@
-import { CKTextEditor, ClassicEditor, EditorWatchdog, PopupEditor, TemplateDefinition, type EmbedMetadata, type WatchdogConfig } from "@triliumnext/ckeditor5";
+import { CKTextEditor, ClassicEditor, EditorWatchdog, PopupEditor, TemplateDefinition, type WatchdogConfig } from "@triliumnext/ckeditor5";
import { DISPLAYABLE_LOCALE_IDS } from "@triliumnext/commons";
import { HTMLProps, RefObject, useEffect, useImperativeHandle, useRef, useState } from "preact/compat";
import froca from "../../../services/froca";
import link from "../../../services/link";
-import linkEmbedService from "../../../services/link_embed";
+import linkEmbedService, { type EmbedMetadata } from "../../../services/link_embed";
import { useKeyboardShortcuts, useLegacyImperativeHandlers, useNoteContext, useSyncedRef, useTriliumOption } from "../../react/hooks";
import { buildConfig, BuildEditorOptions } from "./config";
@@ -183,6 +183,12 @@ export default function CKEditorWithWatchdog({ containerRef: externalContainerRe
},
async fetchLinkMetadata(url: string) {
return await linkEmbedService.fetchMetadata(url);
+ },
+ renderLinkEmbed(container: HTMLElement, metadata: EmbedMetadata) {
+ linkEmbedService.renderEmbedPreview(container, metadata);
+ },
+ renderLinkMention(container: HTMLElement, metadata: EmbedMetadata) {
+ linkEmbedService.renderMentionPreview(container, metadata);
}
});
diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsx
index 820b89f29b..71886be680 100644
--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx
+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx
@@ -145,6 +145,12 @@ export default function EditableText({ note, parentComponent, ntxId, noteContext
async fetchLinkMetadata(url: string) {
return await linkEmbedService.fetchMetadata(url);
},
+ renderLinkEmbed(container: HTMLElement, metadata: Parameters<typeof linkEmbedService.renderEmbedPreview>[1]) {
+ linkEmbedService.renderEmbedPreview(container, metadata);
+ },
+ renderLinkMention(container: HTMLElement, metadata: Parameters<typeof linkEmbedService.renderMentionPreview>[1]) {
+ linkEmbedService.renderMentionPreview(container, metadata);
+ },
// Creating notes in @-completion
async createNoteForReferenceLink(title: string) {
const notePath = noteContext?.notePath;
diff --git a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx
index 9c3eea71bb..b5defb99e3 100644
--- a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx
+++ b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx
@@ -1,5 +1,4 @@
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)
@@ -13,13 +12,13 @@ import appContext from "../../../components/app_context";
import FNote from "../../../entities/fnote";
import { applyInlineMermaid, rewriteMermaidDiagramsInContainer } from "../../../services/content_renderer_text";
import { getLocaleById } from "../../../services/i18n";
+import { applyLinkEmbeds } from "../../../services/link_embed";
import { renderMathInElement } from "../../../services/math";
import { formatCodeBlocks } from "../../../services/syntax_highlight";
import { useNoteBlob, useNoteLabel, useSyncedRef, useTriliumEvent, useTriliumOption, useTriliumOptionBool } from "../../react/hooks";
import { RawHtmlBlock } from "../../react/RawHtml";
import TouchBar, { TouchBarButton, TouchBarSpacer } from "../../react/TouchBar";
import { TypeWidgetProps } from "../type_widget";
-import { renderEmbedPreview, renderMentionPreview } from "@triliumnext/ckeditor5";
import { applyReferenceLinks } from "./read_only_helper";
import { loadIncludedNote, refreshIncludedNote, setupImageOpening } from "./utils";
@@ -153,34 +152,6 @@ function applyIncludedNotes(container: HTMLDivElement) {
}
}
-function applyLinkEmbeds(container: HTMLDivElement) {
- for (const embed of container.querySelectorAll<HTMLElement>("section.link-embed")) {
- const url = embed.dataset.url;
- if (!url) continue;
- 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;
- mention.innerHTML = "";
- renderMentionPreview(mention, {
- url,
- title: mention.dataset.title,
- favicon: mention.dataset.favicon
- });
- }
-}
-
function applyMath(container: HTMLDivElement) {
const equations = container.querySelectorAll("span.math-tex");
for (const equation of equations) {
diff --git a/packages/ckeditor5/src/augmentation.ts b/packages/ckeditor5/src/augmentation.ts
index c74630e27c..387dda9fae 100644
--- a/packages/ckeditor5/src/augmentation.ts
+++ b/packages/ckeditor5/src/augmentation.ts
@@ -5,11 +5,23 @@ declare global {
triggerCommand(command: string): void;
}
+ interface LinkEmbedMetadata {
+ url: string;
+ embedType: string;
+ title?: string;
+ description?: string;
+ favicon?: string;
+ siteName?: string;
+ image?: string;
+ }
+
interface EditorComponent extends Component {
loadReferenceLinkTitle($el: JQuery<HTMLElement>, href: string): Promise<void>;
createNoteForReferenceLink(title: string): Promise<string>;
loadIncludedNote(noteId: string, $el: JQuery<HTMLElement>): void;
- fetchLinkMetadata(url: string): Promise<import("./plugins/linkembed.js").EmbedMetadata>;
+ fetchLinkMetadata(url: string): Promise<LinkEmbedMetadata>;
+ renderLinkEmbed(container: HTMLElement, metadata: LinkEmbedMetadata): void;
+ renderLinkMention(container: HTMLElement, metadata: LinkEmbedMetadata): void;
}
var glob: {
diff --git a/packages/ckeditor5/src/index.ts b/packages/ckeditor5/src/index.ts
index 3b352a3191..ca51d92d7b 100644
--- a/packages/ckeditor5/src/index.ts
+++ b/packages/ckeditor5/src/index.ts
@@ -12,7 +12,6 @@ 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 9e00cab92b..34c5cae906 100644
--- a/packages/ckeditor5/src/plugins/linkembed.ts
+++ b/packages/ckeditor5/src/plugins/linkembed.ts
@@ -6,7 +6,6 @@ import { preventCKEditorHandling } from './widget_utils.js';
export const LINK_EMBED_COMMAND = 'insertLinkEmbed';
const EMBEDDABLE_URL_REGEX = /^https?:\/\/\S+$/;
-const YOUTUBE_URL_REGEX = /(?:youtube\.com|youtu\.be)/;
function isEmbeddableUrl(text: string): boolean {
return EMBEDDABLE_URL_REGEX.test(text.trim());
@@ -139,7 +138,9 @@ class LinkEmbedEditing extends Plugin {
'data-cke-ignore-events': 'true'
}, function (domDocument) {
const domElement = this.toDomElement(domDocument);
- renderEmbedPreview(domElement, { url, embedType, title, description, favicon, siteName, image });
+ const editorEl = editor.editing.view.getDomRoot();
+ const component = glob.getComponentByEl<EditorComponent>(editorEl);
+ component.renderLinkEmbed(domElement, { url, embedType, title, description, favicon, siteName, image });
preventCKEditorHandling(domElement, editor);
return domElement;
});
@@ -194,7 +195,9 @@ class LinkEmbedEditing extends Plugin {
'data-cke-ignore-events': 'true'
}, function (domDocument) {
const domElement = this.toDomElement(domDocument);
- renderMentionPreview(domElement, { url, title, favicon });
+ const editorEl = editor.editing.view.getDomRoot();
+ const component = glob.getComponentByEl<EditorComponent>(editorEl);
+ component.renderLinkMention(domElement, { url, title, favicon });
preventCKEditorHandling(domElement, editor);
return domElement;
});
@@ -206,128 +209,6 @@ 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();
@@ -548,7 +429,7 @@ class LinkEmbedPasteHandler extends Plugin {
const component = glob.getComponentByEl<EditorComponent>(editorEl);
// Fetch metadata asynchronously, then insert into the model
- component.fetchLinkMetadata(url).then((metadata: EmbedMetadata) => {
+ component.fetchLinkMetadata(url).then((metadata: LinkEmbedMetadata) => {
editor.model.change((writer) => {
const root = editor.model.document.getRoot();
if (!root) return;