Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
refactor(share): share link previews and embed resolution with the app
Elian Doran5b6bb790aae7
diff --git a/apps/client/src/services/content_renderer_text.spec.ts b/apps/client/src/services/content_renderer_text.spec.tsindex 854b3106d0..a3768e7ff1 100644--- a/apps/client/src/services/content_renderer_text.spec.ts+++ b/apps/client/src/services/content_renderer_text.spec.ts@@ -411,6 +411,25 @@ describe("Nested embeds (single-level display vs recursive print)", () => {expect(contentEl.querySelector("a.reference-link")).toBeNull();});+ it("on print, links back to a note already expanded on the path instead of looping", async () => {+ buildNote({+ id: "cycB",+ title: "Note B",+ content: `<p>B body</p><section class="include-note" data-note-id="cycA" data-box-size="medium"> </section>`+ });+ const noteA = buildNote({+ id: "cycA",+ title: "Note A",+ content: `<p>A body</p><section class="include-note" data-note-id="cycB" data-box-size="medium"> </section>`+ });+ const contentEl = document.createElement("div");+ await renderText(noteA, $(contentEl), { expandNestedEmbeds: true });++ expect(contentEl.textContent).toContain("B body");+ expect(contentEl.querySelector('section.include-note[data-note-id="cycA"]')).toBeNull();+ expect(contentEl.querySelector("a.reference-link")?.getAttribute("href")).toBe("#root/cycA");+ });+it("on print, expands a note shared across sibling branches in each branch (not a false cycle)", async () => {// Diamond: A embeds B and C; both B and C embed D. D is not a cycle, so under recursive// expansion it must render in both branches (the ancestor path is tracked per-branch).diff --git a/apps/client/src/services/content_renderer_text.ts b/apps/client/src/services/content_renderer_text.tsindex 381da2663e..aa11c62a07 100644--- a/apps/client/src/services/content_renderer_text.ts+++ b/apps/client/src/services/content_renderer_text.ts@@ -1,4 +1,7 @@-import { encodeBlockParameter, KATEX_MACROS, sliceToBlockReference } from "@triliumnext/commons";+import {+ type ContentEmbedContext, getAttachmentEmbedHref, getEmbedKey, getNestedEmbedOptions,+ getNoteEmbedHref, KATEX_MACROS, resolveContentEmbed, sliceToBlockReference+} from "@triliumnext/commons";import FAttachment from "../entities/fattachment.js";import FNote from "../entities/fnote.js";@@ -63,12 +66,12 @@ export async function postProcessRichContent(note: FNote | FAttachment, $rendereseenNoteIds.add(getEmbedKey("noteId" in note ? note.noteId : note.attachmentId, options.block));if (options.noContentEmbeds) {$renderedContent.find(".include-note").remove();- } else if (options.embedsAsReferenceLinks) {- // This note is itself an embedded note in display mode: stop after the first level by- // degrading its own embeds to reference links instead of expanding them.- await replaceEmbedsWithReferenceLinks($renderedContent[0]);} else {- await renderContentEmbeds($renderedContent[0], seenNoteIds, options.expandNestedEmbeds ?? false);+ await renderContentEmbeds($renderedContent[0], {+ seenNoteIds,+ embedsAsReferenceLinks: options.embedsAsReferenceLinks,+ expandNestedEmbeds: options.expandNestedEmbeds+ });}if ($renderedContent.find("span.math-tex").length > 0) {@@ -103,70 +106,53 @@ export async function postProcessRichContent(note: FNote | FAttachment, $rendere}}-async function renderContentEmbeds(contentEl: HTMLElement, seenNoteIds: Set<string>, expandNested: boolean) {- // TODO: Consider duplicating with server's share/content_renderer.ts.- const embedEls = contentEl.querySelectorAll(".include-note");+/**+ * Expands each `.include-note` in `contentEl` into the note or attachment it shows, or replaces it+ * with a reference link, as `resolveContentEmbed()` decides. The reference-link pass of+ * `postProcessRichContent()` then fills in each link's title, icon and color.+ */+async function renderContentEmbeds(contentEl: HTMLElement, context: ContentEmbedContext) {+ const embeds = [ ...contentEl.querySelectorAll(".include-note") ].map((embedEl) => ({+ embedEl,+ embed: resolveContentEmbed((name) => embedEl.getAttribute(name), context)+ }));+ const noteIds = embeds.flatMap(({ embed }) => embed?.kind === "note" ? [ embed.noteId ] : []);+ await froca.getNotes(noteIds);- // Gather the list of items to load.- const noteIds: string[] = [];- for (const embedEl of embedEls) {- const noteId = embedEl.getAttribute("data-note-id");- if (noteId) {- noteIds.push(noteId);- }- }+ for (const { embedEl, embed } of embeds) {+ if (!embed) continue;- // Load the required notes.- await froca.getNotes(noteIds);+ if (embed.kind === "attachment") {+ const attachment = await froca.getAttachment(embed.attachmentId, true);+ if (!attachment) continue;- // Render and integrate the notes.- for (const embedEl of embedEls) {- // A Tiny embed shows only a title, so it links to what it shows instead of rendering it.- if (embedEl.getAttribute("data-box-size") === "tiny") {- await replaceEmbedWithReferenceLink(embedEl);+ if (embed.asLink) {+ const { ownerId, attachmentId } = attachment;+ replaceWithReferenceLink(embedEl, getAttachmentEmbedHref(ownerId, attachmentId));+ } else {+ const { $renderedContent } = await content_renderer.getRenderedContent(attachment);+ replaceEmbedContent(embedEl, $renderedContent.toArray());+ }continue;}- const attachment = await getEmbeddedAttachment(embedEl);- if (attachment) {- const { $renderedContent } = await content_renderer.getRenderedContent(attachment);- replaceEmbedContent(embedEl, $renderedContent.toArray());+ if (embed.asLink) {+ replaceWithReferenceLink(embedEl, getNoteEmbedHref(embed.noteId, embed.block));continue;}- const noteId = embedEl.getAttribute("data-note-id");- if (!noteId) continue;- const block = embedEl.getAttribute("data-block") ?? undefined;-- const note = froca.getNoteFromCache(noteId);+ const note = froca.getNoteFromCache(embed.noteId);if (!note) {- console.warn(`Unable to embed ${noteId} because it could not be found.`);- continue;- }-- if (seenNoteIds.has(getEmbedKey(noteId, block))) {- console.warn(`Skipping embedding of ${noteId} to avoid circular reference.`);- embedEl.remove();+ console.warn(`Unable to embed ${embed.noteId} because it could not be found.`);continue;}- // On display only the first level is expanded: the embedded note is rendered with its own- // embeds degraded to reference links. Printing/export keeps expanding recursively.- // Clone seenNoteIds per descent so it tracks the current ancestor path only — sibling- // branches must not pollute each other (a note embedded in two sub-trees is not a cycle).- const renderedContent = (await content_renderer.getRenderedContent(note, expandNested- ? { seenNoteIds: new Set(seenNoteIds), expandNestedEmbeds: true, block }- : { seenNoteIds: new Set(seenNoteIds), embedsAsReferenceLinks: true, block }- )).$renderedContent;- replaceEmbedContent(embedEl, renderedContent.toArray());+ const { $renderedContent } = await content_renderer.getRenderedContent(note,+ getNestedEmbedOptions(context, embed.block));+ replaceEmbedContent(embedEl, $renderedContent.toArray());}}-/** The key of an embed in `seenNoteIds`. A note can embed blocks of itself. */-function getEmbedKey(noteId: string, block: string | undefined) {- return block ? `${noteId}:${block}` : noteId;-}-/** Puts `content` in an embed, followed by the embed's caption. */function replaceEmbedContent(embedEl: Element, content: Node[]) {const caption = getEmbedCaption(embedEl);@@ -182,57 +168,13 @@ export function getEmbedCaption(embedEl: Element) {return embedEl.querySelector<HTMLElement>(":scope > figcaption");}-/**- * Replace each `.include-note` in the given content with a bare reference link to the- * embedded note, without expanding it. Used on display to stop embedding after the first level so a- * note's transitive embed graph is not rendered inline. The link's title, icon and colour are- * filled in by the reference-link post-processing pass in `postProcessRichContent` (the same pass- * that resolves reference links authored in the note), which also batch-prefetches the note.- */-async function replaceEmbedsWithReferenceLinks(contentEl: HTMLElement) {- for (const embedEl of contentEl.querySelectorAll(".include-note")) {- await replaceEmbedWithReferenceLink(embedEl);- }-}--/** Replaces `embedEl` with a bare reference link to the note or attachment it shows. */-async function replaceEmbedWithReferenceLink(embedEl: Element) {- const attachment = await getEmbeddedAttachment(embedEl);- if (attachment) {- const { ownerId, attachmentId } = attachment;- const href = `#root/${ownerId}?viewMode=attachments&attachmentId=${attachmentId}`;- const referenceLink = document.createElement("a");- referenceLink.className = "reference-link";- referenceLink.setAttribute("href", href);- embedEl.replaceWith(referenceLink);- return;- }-- const noteId = embedEl.getAttribute("data-note-id");- // Validate the ID against a note-ID allow-list before interpolating it into the href: it- // comes from note HTML, and the reference-link pass later reinterprets that href.- if (!noteId || !/^[a-zA-Z0-9_]+$/.test(noteId)) return;-- const block = embedEl.getAttribute("data-block");+function replaceWithReferenceLink(embedEl: Element, href: string) {const referenceLink = document.createElement("a");referenceLink.className = "reference-link";- referenceLink.setAttribute("href", block- ? `#root/${noteId}?block=${encodeBlockParameter(block)}`- : `#root/${noteId}`);+ referenceLink.setAttribute("href", href);embedEl.replaceWith(referenceLink);}-/** The attachment an embed shows, or `null` for an embed of a note. */-async function getEmbeddedAttachment(embedEl: Element) {- const attachmentId = embedEl.getAttribute("data-attachment-id");- // The ID comes from note HTML, so it is checked before it reaches a request or an href.- if (!attachmentId || !/^[a-zA-Z0-9_]+$/.test(attachmentId)) {- return null;- }-- return await froca.getAttachment(attachmentId, true);-}-/** Rewrite the code block from <pre><code> to <div> in order not to apply a codeblock style to it. */export async function rewriteMermaidDiagramsInContainer(container: HTMLDivElement) {const candidates = container.querySelectorAll("pre:has(code)");diff --git a/apps/client/src/services/favicon_contrast.spec.tsx b/apps/client/src/services/favicon_contrast.spec.tsxdeleted file mode 100644index decf974b47..0000000000--- a/apps/client/src/services/favicon_contrast.spec.tsx+++ /dev/null@@ -1,199 +0,0 @@-import { render } from "preact";-import { act } from "preact/test-utils";-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";--import { useFaviconContrastClass } from "./favicon_contrast.js";-import { renderMentionPreview } from "./link_embed.js";--/**- * The verdicts are cached for the life of the page — a note linking one site twenty times measures- * it once — so every test names its own icon rather than sharing one with the test before it.- */-let counter = 0;-const freshIcon = () => `api/attachments/att${++counter}/image/icon.png`;--/** The icon the browser would have loaded, with its `load`/`error` left for the test to fire. */-class FakeImage {- static instances: FakeImage[] = [];-- src = "";- private handlers: Record<string, () => void> = {};-- constructor() {- FakeImage.instances.push(this);- }-- addEventListener(type: string, handler: () => void) {- this.handlers[type] = handler;- }-- fire(type: "load" | "error") {- this.handlers[type]?.();- }-}--/**- * A canvas that answers with the pixels the test names, so a verdict can be reached at all: happy-dom- * implements no 2d context, and without one the measurement rightly declines to judge anything.- */-function stubCanvas(pixels: Uint8ClampedArray) {- const realCreateElement = document.createElement.bind(document);-- vi.spyOn(document, "createElement").mockImplementation(((tag: string, options?: ElementCreationOptions) => {- if (tag !== "canvas") {- return realCreateElement(tag, options);- }-- return {- width: 0,- height: 0,- getContext: () => ({- drawImage: () => {},- getImageData: () => ({ data: pixels })- })- } as unknown as HTMLCanvasElement;- }) as typeof document.createElement);-}--/** An icon that is a black mark on nothing — GitHub's octocat, which a dark theme has to correct. */-const BLACK_ON_NOTHING = new Uint8ClampedArray([- ...Array.from({ length: 60 }, () => [ 0, 0, 0, 0 ]).flat(),- ...Array.from({ length: 40 }, () => [ 0, 0, 0, 255 ]).flat()-]);--function Probe({ src }: { src?: string | null }) {- return <span className={useFaviconContrastClass(src) ?? "unjudged"} />;-}--const containers: HTMLDivElement[] = [];--function renderProbe(src?: string | null) {- const container = document.createElement("div");- document.body.appendChild(container);- containers.push(container);- act(() => render(<Probe src={src} />, container));-- return () => container.querySelector("span")?.className;-}--/** Lets the measurement's promise resolve and the render it schedules run. */-const settle = () => act(async () => { await Promise.resolve(); });--beforeEach(() => {- FakeImage.instances = [];- vi.stubGlobal("Image", FakeImage);- stubCanvas(BLACK_ON_NOTHING);-});--afterEach(() => {- for (const container of containers) {- act(() => render(null, container));- container.remove();- }- containers.length = 0;- vi.unstubAllGlobals();- vi.restoreAllMocks();-});--describe("useFaviconContrastClass", () => {- it("measures an icon, then hands the verdict to the theme as a class", async () => {- const src = freshIcon();- const classOf = renderProbe(src);-- // Drawn as the site drew it while the measurement runs: guessing first would mean- // occasionally correcting an icon that turns out to be fine.- expect(classOf()).toBe("unjudged");- expect(FakeImage.instances).toHaveLength(1);- expect(FakeImage.instances[0].src).toBe(src);-- FakeImage.instances[0].fire("load");- await settle();-- expect(classOf()).toBe("link-embed-favicon-dark");- });-- it("answers a second preview of the same icon without measuring it again", async () => {- const src = freshIcon();- const first = renderProbe(src);- FakeImage.instances[0].fire("load");- await settle();- expect(first()).toBe("link-embed-favicon-dark");-- // A note linking one site twenty times draws twenty of these.- const second = renderProbe(src);- await settle();-- expect(second()).toBe("link-embed-favicon-dark");- expect(FakeImage.instances).toHaveLength(1);- });-- it("shares one measurement between the previews that ask for it at once", async () => {- const src = freshIcon();- const first = renderProbe(src);- const second = renderProbe(src);-- // Both mounted before either answer arrived: one load, one measurement, one verdict.- expect(FakeImage.instances).toHaveLength(1);-- FakeImage.instances[0].fire("load");- await settle();-- expect(first()).toBe("link-embed-favicon-dark");- expect(second()).toBe("link-embed-favicon-dark");- });-- it("leaves an icon alone when there is nothing to measure", async () => {- // Nothing to draw at all.- expect(renderProbe(undefined)()).toBe("unjudged");- // A remote address, which no preview may load — the reader would be announced to whoever- // serves it. It never reaches an <img>, so it is never measured either.- expect(renderProbe("https://tracker.test/favicon.ico")()).toBe("unjudged");- expect(FakeImage.instances).toEqual([]);-- // An icon that will not load is one the preview already shows its placeholder for.- const classOf = renderProbe(freshIcon());- FakeImage.instances[0].fire("error");- await settle();- expect(classOf()).toBe("unjudged");-- // And an icon the canvas will not give up its pixels for is left as the site drew it.- vi.restoreAllMocks();- const unreadable = renderProbe(freshIcon());- FakeImage.instances[1].fire("load");- await settle();- expect(unreadable()).toBe("unjudged");- });-- it("puts the verdict on the icon a preview actually draws", async () => {- // What the class is for: the theme corrects the icon by it, so it has to arrive on the- // rendered <img> alongside the class that sizes it, rather than in place of it.- const container = document.createElement("div");- document.body.appendChild(container);- containers.push(container);-- act(() => renderMentionPreview(container, {- url: "https://example.com",- favicon: freshIcon()- }));-- FakeImage.instances[0].fire("load");- await settle();-- expect(container.querySelector("img.link-embed-mention-favicon")?.className)- .toBe("link-embed-mention-favicon link-embed-favicon-dark");- });-- it("drops the verdict of a preview that has gone before its measurement arrives", async () => {- const src = freshIcon();- const classOf = renderProbe(src);- const [ image ] = FakeImage.instances;-- // Scrolling away from a note unmounts its previews mid-measurement, which must not be a- // state update against something no longer rendered.- act(() => render(null, containers[containers.length - 1]));- image.fire("load");- await settle();-- expect(classOf()).toBeUndefined();- });-});diff --git a/apps/client/src/services/favicon_contrast.ts b/apps/client/src/services/favicon_contrast.tsdeleted file mode 100644index b44dae8bde..0000000000--- a/apps/client/src/services/favicon_contrast.ts+++ /dev/null@@ -1,108 +0,0 @@-import {- classifyFaviconContrast,- type FaviconContrast,- faviconContrastClass,- measureFaviconVisibility,- safeLinkPreviewImageSrc-} from "@triliumnext/commons";-import { useEffect, useState } from "preact/hooks";--/**- * The measured verdict for each favicon we have looked at, so a note that links one site twenty- * times measures it once. Keyed by the picture rather than by the site, since that is what was- * measured — the same attachment URL always yields the same answer.- *- * Never invalidated: the answer is a property of the icon's own pixels and does not change when the- * user switches theme. Acting on it does, which is why the verdict is handed to the stylesheets as a- * class rather than being resolved into a filter here.- */-const measured = new Map<string, FaviconContrast>();--/** Measurements still in flight, so several previews of one site share a single decode. */-const pending = new Map<string, Promise<FaviconContrast>>();--/**- * The class a favicon should carry for the theme to be able to correct it, or undefined while the- * measurement is still running and for an icon that needs no correction.- *- * Renders uncorrected first and corrects on the next frame. That is the right way round: an icon- * briefly shown as its author drew it is what every other app shows permanently, whereas guessing- * before measuring would mean occasionally inverting an icon that turns out to be fine.- */-export function useFaviconContrastClass(src: string | undefined | null): string | undefined {- const safeSrc = safeLinkPreviewImageSrc(src);- const [contrast, setContrast] = useState<FaviconContrast>(() => (safeSrc && measured.get(safeSrc)) || "neutral");-- useEffect(() => {- if (!safeSrc) {- setContrast("neutral");- return;- }-- const known = measured.get(safeSrc);- if (known) {- setContrast(known);- return;- }-- let stillMounted = true;- void faviconContrast(safeSrc).then((result) => {- if (stillMounted) {- setContrast(result);- }- });-- return () => {- stillMounted = false;- };- }, [safeSrc]);-- return faviconContrastClass(contrast);-}--/** Measures an icon, or answers from the cache. Never rejects: an unreadable icon is simply left alone. */-function faviconContrast(src: string): Promise<FaviconContrast> {- const cached = measured.get(src);- if (cached) {- return Promise.resolve(cached);- }-- const inFlight = pending.get(src);- if (inFlight) {- return inFlight;- }-- const measurement = loadAndMeasure(src).then((contrast) => {- measured.set(src, contrast);- pending.delete(src);- return contrast;- });-- pending.set(src, measurement);-- return measurement;-}--/**- * Loads the icon a second time, into an image of our own, and measures that.- *- * Deliberately not the `<img>` the preview renders: this way the measurement owes nothing to when- * that element mounts, whether it has already fired `load`, or whether it is on screen at all, and- * the same answer serves every preview of the site at once. The second load is free — the browser- * has the picture in its cache, this being the very URL it just drew.- */-function loadAndMeasure(src: string): Promise<FaviconContrast> {- return new Promise((resolve) => {- const image = new Image();-- image.addEventListener("load", () => {- const visibility = measureFaviconVisibility(image);- resolve(visibility ? classifyFaviconContrast(visibility) : "neutral");- }, { once: true });-- // An icon that will not load is one the preview is already showing its placeholder for.- image.addEventListener("error", () => resolve("neutral"), { once: true });-- image.src = src;- });-}diff --git a/apps/client/src/services/link_embed.spec.ts b/apps/client/src/services/link_embed.spec.tsindex 00b2484691..3c3a5b3cfb 100644--- a/apps/client/src/services/link_embed.spec.ts+++ b/apps/client/src/services/link_embed.spec.ts@@ -1,3 +1,4 @@+// @vitest-environment-options {"settings":{"disableIframePageLoading":true}}import { afterEach, describe, expect, it, vi } from "vitest";import {@@ -10,6 +11,8 @@ import {} from "./link_embed.js";import server from "./server.js";+vi.mock("./i18n.js", () => ({ t: (key: string) => key }));+let container: HTMLDivElement | undefined;function makeContainer() {diff --git a/apps/client/src/services/link_embed.ts b/apps/client/src/services/link_embed.tsnew file mode 100644index 0000000000..07f3d89bb0--- /dev/null+++ b/apps/client/src/services/link_embed.ts@@ -0,0 +1,128 @@+import "../widgets/type_widgets/text/LinkEmbed.css";++import {+ enhanceLinkPreviews, type LinkEmbedMetadata, type LinkPreviewData, readLinkPreviewData,+ renderLinkEmbedHtml, renderLinkMentionHtml, safeHostname, YOUTUBE_REGEX+} from "@triliumnext/commons";++import { t } from "./i18n.js";+import server from "./server.js";++export { safeHostname };++export interface EmbedMetadata {+ url: string;+ embedType: string;+ title?: string;+ description?: string;+ favicon?: string;+ siteName?: string;+ image?: string;+ /** See {@link LinkEmbedMetadata.unresolved}. Not persisted into the note's HTML. */+ unresolved?: boolean;+}+++export function detectEmbedType(url: string): "youtube" | "opengraph" {+ return YOUTUBE_REGEX.test(url) ? "youtube" : "opengraph";+}++/**+ * 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.+ *+ * Both pictures a preview carries — the cover image and the favicon — are stored by the server as+ * attachments of `ownerNoteId`, and only their `api/attachments/...` URLs come back. That is why+ * the note id is required rather than optional: the pictures have nowhere else to live, and+ * carrying them in the note's HTML instead would be 10–140KB of content for a cover and 1–10KB for+ * a favicon, synced and revisioned like anything else the note holds. A single card is enough to+ * push a note past the `autoReadonlySizeText` threshold (32KB by default) and flip it read-only;+ * favicons get there by repetition, a note that links a site once usually linking it many times.+ */+export async function fetchMetadata(url: string, ownerNoteId: string): Promise<EmbedMetadata> {+ try {+ // POSTed rather than passed in the query string: a URL can carry a one-time token or a+ // signed signature, and a query string ends up in every access log along the way.+ const metadata = await server.post<LinkEmbedMetadata>("link-embed/metadata", { url, noteId: ownerNoteId });++ return {+ url: metadata.url,+ embedType: metadata.embedType,+ title: metadata.title,+ description: metadata.description,+ favicon: metadata.favicon,+ siteName: metadata.siteName,+ image: metadata.image,+ unresolved: metadata.unresolved+ };+ } catch {+ return unresolvedMetadata(url);+ }+}++/**+ * What a URL is worth when nothing could be learned about it: the hostname, and a flag saying so.+ *+ * The caller keeps it as a plain link rather than rendering a preview that shows less than the URL+ * did. Reached when the metadata request fails, and when there is no note yet to store the+ * preview's pictures on.+ */+export function unresolvedMetadata(url: string): EmbedMetadata {+ return {+ url,+ embedType: detectEmbedType(url),+ title: safeHostname(url),+ unresolved: true+ };+}++/**+ * Draws a block link preview into `container` from stored metadata, making no network request.+ * Used by the editor for its link embed widget, with `editable` set.+ */+export function renderEmbedPreview(container: HTMLElement, meta: EmbedMetadata, editable?: boolean) {+ container.innerHTML = renderLinkEmbedHtml(meta, markupOptions(editable));+ enhanceLinkPreviews(container);+}++/** Draws an inline link mention into `container`, like {@link renderEmbedPreview}. */+export function renderMentionPreview(container: HTMLElement, meta: LinkPreviewData, editable?: boolean) {+ container.innerHTML = renderLinkMentionHtml(meta, markupOptions(editable));+ enhanceLinkPreviews(container);+}++/**+ * Draws every link embed and mention in `container` from the metadata stored in its `data-*`+ * attributes, as `link.loadReferenceLinkTitle` does for reference links.+ */+export function applyLinkEmbeds(container: HTMLElement) {+ for (const embed of container.querySelectorAll<HTMLElement>("section.link-embed")) {+ const data = readLinkPreviewData((name) => embed.getAttribute(name));+ if (data) {+ embed.innerHTML = renderLinkEmbedHtml(data, markupOptions(false));+ }+ }++ for (const mention of container.querySelectorAll<HTMLElement>("span.link-mention")) {+ const data = readLinkPreviewData((name) => mention.getAttribute(name));+ if (data) {+ mention.innerHTML = renderLinkMentionHtml(data, markupOptions(false));+ }+ }++ enhanceLinkPreviews(container);+}++function markupOptions(editable: boolean | undefined) {+ return { editable, playVideoLabel: t("link_embed.play_video") };+}++export default {+ fetchMetadata,+ unresolvedMetadata,+ detectEmbedType,+ safeHostname,+ renderEmbedPreview,+ renderMentionPreview,+ applyLinkEmbeds+};diff --git a/apps/client/src/services/link_embed.tsx b/apps/client/src/services/link_embed.tsxdeleted file mode 100644index f88586fc2b..0000000000--- a/apps/client/src/services/link_embed.tsx+++ /dev/null@@ -1,299 +0,0 @@-import "../widgets/type_widgets/text/LinkEmbed.css";--import { extractYouTubeVideoId, type LinkEmbedMetadata, safeHostname, safeLinkPreviewHref, safeLinkPreviewImageSrc, YOUTUBE_REGEX } from "@triliumnext/commons";-import { render, type VNode } from "preact";-import { useState } from "preact/hooks";--import { useFaviconContrastClass } from "./favicon_contrast.js";-import { t } from "./i18n.js";-import server from "./server.js";--export { safeHostname };--export interface EmbedMetadata {- url: string;- embedType: string;- title?: string;- description?: string;- favicon?: string;- siteName?: string;- image?: string;- /** See {@link LinkEmbedMetadata.unresolved}. Not persisted into the note's HTML. */- unresolved?: boolean;-}---export function detectEmbedType(url: string): "youtube" | "opengraph" {- return YOUTUBE_REGEX.test(url) ? "youtube" : "opengraph";-}--/**- * 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.- *- * Both pictures a preview carries — the cover image and the favicon — are stored by the server as- * attachments of `ownerNoteId`, and only their `api/attachments/...` URLs come back. That is why- * the note id is required rather than optional: the pictures have nowhere else to live, and- * carrying them in the note's HTML instead would be 10–140KB of content for a cover and 1–10KB for- * a favicon, synced and revisioned like anything else the note holds. A single card is enough to- * push a note past the `autoReadonlySizeText` threshold (32KB by default) and flip it read-only;- * favicons get there by repetition, a note that links a site once usually linking it many times.- */-export async function fetchMetadata(url: string, ownerNoteId: string): Promise<EmbedMetadata> {- try {- // POSTed rather than passed in the query string: a URL can carry a one-time token or a- // signed signature, and a query string ends up in every access log along the way.- const metadata = await server.post<LinkEmbedMetadata>("link-embed/metadata", { url, noteId: ownerNoteId });-- return {- url: metadata.url,- embedType: metadata.embedType,- title: metadata.title,- description: metadata.description,- favicon: metadata.favicon,- siteName: metadata.siteName,- image: metadata.image,- unresolved: metadata.unresolved- };- } catch {- return unresolvedMetadata(url);- }-}--/**- * What a URL is worth when nothing could be learned about it: the hostname, and a flag saying so.- *- * The caller keeps it as a plain link rather than rendering a preview that shows less than the URL- * did. Reached when the metadata request fails, and when there is no note yet to store the- * preview's pictures on.- */-export function unresolvedMetadata(url: string): EmbedMetadata {- return {- url,- embedType: detectEmbedType(url),- title: safeHostname(url),- unresolved: true- };-}--// ----------------------------------------------------------------------------// Preact components — 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).-// -----------------------------------------------------------------------------/**- * One of a preview's pictures, or what stands in for it.- *- * Both pictures make the same two decisions, so they make them in one place: load only what- * {@link safeLinkPreviewImageSrc} allows — an inline image or an attachment of this instance, so- * that opening a note never announces the reader to a third party — and fall back both when there- * is nothing to load and when loading fails. The failure half matters as much as the check: an- * attachment can be erased out from under a preview that still references it, and a broken-image- * glyph reads as a bug where an absence reads as an absence.- *- * `placeholder` is what a card's missing cover image gets, having a hole to fill; a missing favicon- * omits it, since nothing drawn in its place says as much as the title already does.- */-function PreviewPicture({ src, className, placeholder, size }: {- src?: string | null;- className: string;- placeholder?: VNode;- /** For a picture drawn at a fixed size; the card image is sized by CSS instead. */- size?: number;-}) {- const [ failed, setFailed ] = useState(false);- const safeSrc = safeLinkPreviewImageSrc(src);-- if (!safeSrc || failed) {- return placeholder ?? null;- }-- return (- <img- className={className}- src={safeSrc}- alt=""- width={size}- height={size}- loading="lazy"- draggable={false}- onError={() => setFailed(true)}- />- );-}--function ImagePlaceholder() {- return <div className="link-embed-card-image-placeholder">🔗</div>;-}--function Favicon({ src }: { src?: string }) {- // A site draws its icon for one background, and ours is not always that one — see- // favicon_contrast.ts. The verdict travels as a class so that switching theme corrects the icon- // without anything being measured again.- const contrastClass = useFaviconContrastClass(src);-- return (- <PreviewPicture- src={src}- className={contrastClass ? `link-embed-mention-favicon ${contrastClass}` : "link-embed-mention-favicon"}- size={16}- />- );-}--function CardImage({ src }: { src?: string }) {- return <PreviewPicture src={src} className="link-embed-card-image" placeholder={<ImagePlaceholder />} />;-}--/**- * A YouTube player that only contacts YouTube once the user asks it to.- *- * Until then it shows the thumbnail already stored in the note, so merely opening a note with an- * embedded video does not tell Google that the reader opened it — the note stays free of- * third-party requests, which is the whole point of embedding the metadata server-side.- */-function VideoEmbed({ meta, videoId }: { meta: EmbedMetadata; videoId: string }) {- const [playing, setPlaying] = useState(false);- const thumbnail = safeLinkPreviewImageSrc(meta.image);-- if (!playing) {- return (- <div className="link-embed-video">- <button- type="button"- className="link-embed-video-facade"- aria-label={t("link_embed.play_video")}- title={t("link_embed.play_video")}- onClick={() => setPlaying(true)}- >- {thumbnail && <img className="link-embed-video-thumbnail" src={thumbnail} alt="" draggable={false} />}- <span className="link-embed-video-play" aria-hidden="true" />- </button>- </div>- );- }-- // The `origin` param is only valid for a real web origin. On desktop the- // renderer is served from `trilium-app://app`, which YouTube's player- // rejects ("video player configuration error"), so omit it there.- const webOrigin = window.location.protocol.startsWith("http") ? window.location.origin : null;- // autoplay: the click on the facade *was* the play command; without it the user would have to- // press play a second time, inside YouTube's own player.- const embedSrc = `https://www.youtube-nocookie.com/embed/${videoId}?rel=0&autoplay=1${webOrigin ? `&origin=${encodeURIComponent(webOrigin)}` : ""}`;-- return (- <div className="link-embed-video">- <iframe- src={embedSrc}- frameBorder="0"- allowFullScreen- allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"- referrerPolicy="strict-origin-when-cross-origin"- />- </div>- );-}--function EmbedPreview({ meta, editable }: { meta: EmbedMetadata; editable?: boolean }) {- // Only show the YouTube player when embedType is not explicitly- // set to 'opengraph' (Card mode). This lets the user choose between- // an embedded player and a static card preview for YouTube links.- const videoId = meta.embedType !== "opengraph"- ? extractYouTubeVideoId(meta.url)- : null;-- if (videoId) {- return <VideoEmbed meta={meta} videoId={videoId} />;- }-- // In editing mode, omit target="_blank" so Trilium's global link handler- // (link.ts goToLinkExt) treats the <a> as inside [contenteditable] and- // only opens it on double-click or Ctrl+click.- const target = editable ? undefined : "_blank";-- return (- <a className="link-embed-card" href={safeLinkPreviewHref(meta.url)} target={target} rel="noopener noreferrer">- <div className="link-embed-card-image-wrapper">- <CardImage src={meta.image} />- </div>- <div className="link-embed-card-content">- {meta.title && <div className="link-embed-card-title">{meta.title}</div>}- {meta.description && <div className="link-embed-card-description">{meta.description}</div>}- <div className="link-embed-card-url">- {/* The same favicon the inline mention shows, read from the metadata already- stored on the element. */}- <Favicon src={meta.favicon} />- <span>{meta.siteName || safeHostname(meta.url)}</span>- </div>- </div>- </a>- );-}--function MentionPreview({ meta, editable }: { meta: { url: string; title?: string; favicon?: string }; editable?: boolean }) {- const target = editable ? undefined : "_blank";-- return (- <a className="link-embed-mention" href={safeLinkPreviewHref(meta.url)} target={target} rel="noopener noreferrer">- <Favicon src={meta.favicon} />- <span className="link-embed-mention-title">{meta.title || safeHostname(meta.url)}</span>- </a>- );-}--// ----------------------------------------------------------------------------// Imperative API — renders Preact components into DOM containers.-// -----------------------------------------------------------------------------export function renderEmbedPreview(container: HTMLElement, meta: EmbedMetadata, editable?: boolean) {- render(<EmbedPreview meta={meta} editable={editable} />, container);-}--export function renderMentionPreview(container: HTMLElement, meta: { url: string; title?: string; favicon?: string }, editable?: boolean) {- render(<MentionPreview meta={meta} editable={editable} />, container);-}--/**- * 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,- unresolvedMetadata,- detectEmbedType,- safeHostname,- renderEmbedPreview,- renderMentionPreview,- applyLinkEmbeds-};diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Include Note.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Include Note.htmlindex 02efe888f7..b1835f6503 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Include Note.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Include Note.html@@ -135,7 +135,9 @@more included notes, they will be displayed in the content of the noteas if they were part of the note itself. The caption of an include is shownunder the included content. A <em>Tiny</em> include is shown as a link to- the included note instead.</p>+ the included note instead, and so is an include that would show a note+ already shown around it, such as a note that includes itself. The same+ goes for a printed or exported note.</p><p>For this to work, the included notes must also be shared, otherwise theywill not be shown. However, the included notes can still be hidden fromthe note tree via <code>#shareHiddenFromTree</code>.</p>diff --git a/apps/server/src/assets/translations/en/server.json b/apps/server/src/assets/translations/en/server.jsonindex 25ebf20687..5a74dde5e4 100644--- a/apps/server/src/assets/translations/en/server.json+++ b/apps/server/src/assets/translations/en/server.json@@ -349,7 +349,8 @@"content_renderer": {"note-cannot-be-displayed": "This note type cannot be displayed.","included-note-requires-credentials": "This included note is password-protected and cannot be displayed here.",- "broken-block-reference": "Broken reference"+ "broken-block-reference": "Broken reference",+ "play-video": "Play video"},"onenote_import": {"root-title": "OneNote import",diff --git a/docs/User Guide/User Guide/Note Types/Text/Include Note.md b/docs/User Guide/User Guide/Note Types/Text/Include Note.mdindex 2676cc53bc..e1192c6fc7 100644--- a/docs/User Guide/User Guide/Note Types/Text/Include Note.md+++ b/docs/User Guide/User Guide/Note Types/Text/Include Note.md@@ -81,7 +81,7 @@ To replace an include with a link to the included note, select it and press the## Included notes in the share functionality-If a [shared note](../../Advanced%20Usage/Sharing.md) contains one or more included notes, they will be displayed in the content of the note as if they were part of the note itself. The caption of an include is shown under the included content. A _Tiny_ include is shown as a link to the included note instead.+If a [shared note](../../Advanced%20Usage/Sharing.md) contains one or more included notes, they will be displayed in the content of the note as if they were part of the note itself. The caption of an include is shown under the included content. A _Tiny_ include is shown as a link to the included note instead, and so is an include that would show a note already shown around it, such as a note that includes itself. The same goes for a printed or exported note.For this to work, the included notes must also be shared, otherwise they will not be shown. However, the included notes can still be hidden from the note tree via `#shareHiddenFromTree`.diff --git a/packages/commons/package.json b/packages/commons/package.jsonindex 4fbac7e83a..9a4fef7728 100644--- a/packages/commons/package.json+++ b/packages/commons/package.json@@ -23,6 +23,7 @@"numfmt": "3.2.6"},"devDependencies": {+ "happy-dom": "20.14.5","preact": "11.0.0"}}\ No newline at end of filediff --git a/packages/commons/src/index.ts b/packages/commons/src/index.tsindex 5b91f6abe9..8665ebab70 100644--- a/packages/commons/src/index.ts+++ b/packages/commons/src/index.ts@@ -31,6 +31,7 @@ export * from "./lib/onenote.js";export * from "./lib/week_utils.js";export * from "./lib/board_columns.js";export * from "./lib/block_reference.js";+export * from "./lib/content_embeds.js";export * from "./lib/builtin_attributes.js";export { default as BUILTIN_ATTRIBUTES } from "./lib/builtin_attributes.js";// The spreadsheet modules are deliberately not re-exported here: they pull in numfmt, and the@@ -45,6 +46,8 @@ export * from "./lib/standalone_api_interface.js";export * from "./lib/favicon_contrast.js";export * from "./lib/mermaid_config.js";export * from "./lib/link_embed.js";+export * from "./lib/link_embed_dom.js";+export * from "./lib/link_embed_markup.js";export * from "./lib/llm_api.js";export * from "./lib/marked_extensions.js";// The markdown renderer is deliberately not re-exported here: it pulls in marked, and the barreldiff --git a/packages/commons/src/lib/content_embeds.spec.ts b/packages/commons/src/lib/content_embeds.spec.tsnew file mode 100644index 0000000000..ff9a165873--- /dev/null+++ b/packages/commons/src/lib/content_embeds.spec.ts@@ -0,0 +1,69 @@+import { describe, expect, it } from "vitest";++import {+ type ContentEmbedContext, getAttachmentEmbedHref, getEmbedKey, getNestedEmbedOptions,+ getNoteEmbedHref, resolveContentEmbed+} from "./content_embeds.js";++const NO_PATH = { seenNoteIds: new Set<string>() };++/** Resolves an `.include-note` whose attributes are `values`. */+function resolve(values: Record<string, string>, context: ContentEmbedContext = NO_PATH) {+ return resolveContentEmbed((name) => values[name], context);+}++describe("resolveContentEmbed", () => {+ it("shows a note or a block of one, and links to it from a Tiny embed", () => {+ expect(resolve({ "data-note-id": "abc123" }))+ .toEqual({ kind: "note", noteId: "abc123", block: undefined, asLink: false });+ expect(resolve({ "data-note-id": "abc123", "data-block": "b1" }))+ .toEqual({ kind: "note", noteId: "abc123", block: "b1", asLink: false });+ expect(resolve({ "data-note-id": "abc123", "data-box-size": "tiny" }))+ .toEqual({ kind: "note", noteId: "abc123", block: undefined, asLink: true });+ });++ it("links to a note already rendered on the path, but not to another block of it", () => {+ const context = { seenNoteIds: new Set([ getEmbedKey("abc123", "b1") ]) };++ expect(resolve({ "data-note-id": "abc123", "data-block": "b1" }, context))+ .toMatchObject({ asLink: true });+ expect(resolve({ "data-note-id": "abc123", "data-block": "b2" }, context))+ .toMatchObject({ asLink: false });+ });++ it("shows an attachment, linking to it below the first level", () => {+ expect(resolve({ "data-attachment-id": "att1" }))+ .toEqual({ kind: "attachment", attachmentId: "att1", asLink: false });+ const belowFirstLevel = { ...NO_PATH, embedsAsReferenceLinks: true };+ expect(resolve({ "data-attachment-id": "att1" }, belowFirstLevel))+ .toEqual({ kind: "attachment", attachmentId: "att1", asLink: true });+ });++ it("ignores an embed that names nothing, or an ID Trilium would not generate", () => {+ expect(resolve({})).toBeNull();+ expect(resolve({ "data-note-id": "x\"><script>" })).toBeNull();+ expect(resolve({ "data-attachment-id": "../etc" })).toBeNull();+ });+});++describe("getNestedEmbedOptions", () => {+ it("copies the path, and expands below the first level only when asked to", () => {+ const seenNoteIds = new Set([ "abc123" ]);++ const shown = getNestedEmbedOptions({ seenNoteIds }, "b1");+ expect(shown).toEqual({ seenNoteIds, block: "b1", embedsAsReferenceLinks: true });+ expect(shown.seenNoteIds).not.toBe(seenNoteIds);++ expect(getNestedEmbedOptions({ seenNoteIds, expandNestedEmbeds: true }, undefined))+ .toEqual({ seenNoteIds, block: undefined, expandNestedEmbeds: true });+ });+});++describe("embed links", () => {+ it("point at the note, the block or the attachment", () => {+ expect(getNoteEmbedHref("abc123", undefined)).toBe("#root/abc123");+ expect(getNoteEmbedHref("abc123", "b 1")).toBe("#root/abc123?block=b%201");+ expect(getAttachmentEmbedHref("owner1", "att1"))+ .toBe("#root/owner1?viewMode=attachments&attachmentId=att1");+ });+});diff --git a/packages/commons/src/lib/content_embeds.ts b/packages/commons/src/lib/content_embeds.tsnew file mode 100644index 0000000000..543d97ff50--- /dev/null+++ b/packages/commons/src/lib/content_embeds.ts@@ -0,0 +1,89 @@+import { encodeBlockParameter } from "./block_reference.js";++/**+ * Where an embed sits: what has been rendered on the path down to it, and how deep embedding goes.+ * The app's read-only renderer and the share renderer pass these down when they render the content+ * an embed shows.+ */+export interface ContentEmbedContext {+ /** The notes and blocks rendered on the path to this embed, by {@link getEmbedKey}. */+ seenNoteIds: ReadonlySet<string>;+ /** Embeds become reference links: the content is itself an embed below the first level. */+ embedsAsReferenceLinks?: boolean;+ /** Embeds keep expanding at every depth, as printing and the static export do. */+ expandNestedEmbeds?: boolean;+}++/** What an `.include-note` element stands for, and whether it shows the content or links to it. */+export type ContentEmbed =+ | { kind: "attachment"; attachmentId: string; asLink: boolean }+ | { kind: "note"; noteId: string; block: string | undefined; asLink: boolean };++/** The options the content an embed shows is rendered with. */+export interface NestedEmbedOptions {+ seenNoteIds: Set<string>;+ block: string | undefined;+ expandNestedEmbeds?: true;+ embedsAsReferenceLinks?: true;+}++const ENTITY_ID = /^[a-zA-Z0-9_]+$/;++/** The key of an embed in `seenNoteIds`. A note can embed blocks of itself. */+export function getEmbedKey(noteId: string, block: string | null | undefined) {+ return block ? `${noteId}:${block}` : noteId;+}++/**+ * Reads an `.include-note` element and decides what it becomes, or `null` when it names nothing+ * valid. The IDs come from note HTML, so only an ID of the shape Trilium generates gets through.+ *+ * It becomes a link to what it shows rather than the content itself when it is a Tiny embed, which+ * shows only a title; when the content around it is itself an embed below the first level; and,+ * for a note, when the note is already being rendered on the path to it, which would otherwise+ * never end.+ */+export function resolveContentEmbed(+ getAttribute: (name: string) => string | null | undefined,+ context: ContentEmbedContext+): ContentEmbed | null {+ const asLink = !!context.embedsAsReferenceLinks || getAttribute("data-box-size") === "tiny";++ const attachmentId = getAttribute("data-attachment-id");+ if (attachmentId) {+ return ENTITY_ID.test(attachmentId) ? { kind: "attachment", attachmentId, asLink } : null;+ }++ const noteId = getAttribute("data-note-id");+ if (!noteId || !ENTITY_ID.test(noteId)) {+ return null;+ }++ const block = getAttribute("data-block") || undefined;+ const isCycle = context.seenNoteIds.has(getEmbedKey(noteId, block));+ return { kind: "note", noteId, block, asLink: asLink || isCycle };+}++/**+ * The options to render an embedded note with. Each descent gets its own copy of `seenNoteIds`, so+ * it tracks the current path only: a note embedded in two sibling sub-trees is not a cycle.+ */+export function getNestedEmbedOptions(+ context: ContentEmbedContext,+ block: string | undefined+): NestedEmbedOptions {+ const seenNoteIds = new Set(context.seenNoteIds);+ return context.expandNestedEmbeds+ ? { seenNoteIds, block, expandNestedEmbeds: true }+ : { seenNoteIds, block, embedsAsReferenceLinks: true };+}++/** The `href` of the reference link an embed of a note, or of one of its blocks, becomes. */+export function getNoteEmbedHref(noteId: string, block: string | undefined) {+ return block ? `#root/${noteId}?block=${encodeBlockParameter(block)}` : `#root/${noteId}`;+}++/** The `href` of the reference link an embed of an attachment becomes. */+export function getAttachmentEmbedHref(ownerId: string, attachmentId: string) {+ return `#root/${ownerId}?viewMode=attachments&attachmentId=${attachmentId}`;+}diff --git a/packages/commons/src/lib/link_embed_dom.spec.ts b/packages/commons/src/lib/link_embed_dom.spec.tsnew file mode 100644index 0000000000..16f581683a--- /dev/null+++ b/packages/commons/src/lib/link_embed_dom.spec.ts@@ -0,0 +1,143 @@+// @vitest-environment happy-dom+// @vitest-environment-options {"settings":{"disableIframePageLoading":true}}+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { measureFaviconVisibility } from "./favicon_contrast.js";+import { enhanceLinkPreviews } from "./link_embed_dom.js";+import { renderLinkEmbedHtml, renderLinkMentionHtml } from "./link_embed_markup.js";++vi.mock("./favicon_contrast.js", async (importOriginal) => ({+ ...await importOriginal<typeof import("./favicon_contrast.js")>(),+ measureFaviconVisibility: vi.fn()+}));++const OPTIONS = { playVideoLabel: "Play video" };++/** The icon loaded for measuring, with its `load` or `error` left for the test to fire. */+class FakeImage {+ static instances: FakeImage[] = [];++ src = "";+ private handlers: Record<string, () => void> = {};++ constructor() {+ FakeImage.instances.push(this);+ }++ addEventListener(type: string, handler: () => void) {+ this.handlers[type] = handler;+ }++ fire(type: "load" | "error") {+ this.handlers[type]();+ }+}++/**+ * Measurements are cached for the life of the page, so every test names an icon of its own rather+ * than reusing the previous test's.+ */+let iconCount = 0;+const freshIcon = () => `data:image/png;base64,ICON${++iconCount}`;++/** A preview drawn into the document and enhanced, as the app and the share theme do. */+function render(html: string) {+ const container = document.createElement("div");+ container.innerHTML = html;+ document.body.append(container);+ enhanceLinkPreviews(container);+ return container;+}++/** Lets the measurement's promise settle. */+const settle = () => new Promise((resolve) => setTimeout(resolve, 0));++beforeEach(() => {+ FakeImage.instances = [];+ vi.stubGlobal("Image", FakeImage);+});++afterEach(() => {+ vi.unstubAllGlobals();+ document.body.innerHTML = "";+});++describe("enhanceLinkPreviews", () => {+ const VIDEO = { url: "https://www.youtube.com/watch?v=dQw4w9WgXcQ", embedType: "youtube" };++ it("loads the player only once the facade is clicked, with the page's web origin", () => {+ const container = render(renderLinkEmbedHtml(VIDEO, OPTIONS));+ expect(container.querySelector("iframe")).toBeNull();++ container.querySelector<HTMLButtonElement>(".link-embed-video-facade")?.click();++ const iframe = container.querySelector("iframe");+ expect(container.querySelector(".link-embed-video-facade")).toBeNull();+ expect(iframe?.getAttribute("src")).toBe("https://www.youtube-nocookie.com/embed/dQw4w9WgXcQ"+ + `?rel=0&autoplay=1&origin=${encodeURIComponent(location.origin)}`);+ expect(iframe?.parentElement?.className).toBe("link-embed-video");+ });++ it("leaves the origin out on the desktop app's custom protocol", () => {+ const happyDOM = (window as unknown as { happyDOM: { setURL(url: string): void } }).happyDOM;+ const previousUrl = location.href;+ happyDOM.setURL("trilium-app://app/index.html");++ try {+ const container = render(renderLinkEmbedHtml(VIDEO, OPTIONS));+ container.querySelector<HTMLButtonElement>(".link-embed-video-facade")?.click();++ expect(container.querySelector("iframe")?.getAttribute("src"))+ .toBe("https://www.youtube-nocookie.com/embed/dQw4w9WgXcQ?rel=0&autoplay=1");+ } finally {+ happyDOM.setURL(previousUrl);+ }+ });++ it("replaces a broken cover with the placeholder and drops a broken favicon", () => {+ const container = render(renderLinkEmbedHtml({+ url: "https://example.com",+ embedType: "opengraph",+ image: "api/attachments/deleted1/image/broken.png",+ favicon: freshIcon()+ }, OPTIONS));++ container.querySelector("img.link-embed-card-image")?.dispatchEvent(new Event("error"));+ container.querySelector("img.link-embed-mention-favicon")?.dispatchEvent(new Event("error"));++ expect(container.querySelector("img")).toBeNull();+ expect(container.querySelector(".link-embed-card-image-placeholder")).not.toBeNull();+ expect(container.querySelector(".link-embed-card-url")?.textContent).toBe("example.com");+ });++ it("marks a favicon the page has to correct, measuring each icon once", async () => {+ vi.mocked(measureFaviconVisibility).mockReturnValue({ onDark: 0, onLight: 1, hasContent: true });+ const icon = freshIcon();+ const container = render(renderLinkMentionHtml({ url: "https://github.com", favicon: icon }, OPTIONS)+ + renderLinkMentionHtml({ url: "https://github.com/x", favicon: icon }, OPTIONS));++ expect(FakeImage.instances).toHaveLength(1);+ expect(FakeImage.instances[0].src).toBe(icon);+ FakeImage.instances[0].fire("load");+ await settle();++ for (const favicon of container.querySelectorAll("img.link-embed-mention-favicon")) {+ expect(favicon.classList.contains("link-embed-favicon-dark")).toBe(true);+ }+ });++ it("leaves a favicon alone when it reads on both backgrounds, or cannot be read", async () => {+ vi.mocked(measureFaviconVisibility).mockReturnValue(undefined);+ const unreadable = render(renderLinkMentionHtml({ url: "https://a.test", favicon: freshIcon() }, OPTIONS));+ const unloadable = render(renderLinkMentionHtml({ url: "https://b.test", favicon: freshIcon() }, OPTIONS));++ FakeImage.instances[0].fire("load");+ FakeImage.instances[1].fire("error");+ await settle();++ for (const container of [ unreadable, unloadable ]) {+ expect(container.querySelector("img.link-embed-mention-favicon")?.className)+ .toBe("link-embed-mention-favicon");+ }+ });+});diff --git a/packages/commons/src/lib/link_embed_dom.ts b/packages/commons/src/lib/link_embed_dom.tsnew file mode 100644index 0000000000..37a072c37d--- /dev/null+++ b/packages/commons/src/lib/link_embed_dom.ts@@ -0,0 +1,90 @@+import {+ classifyFaviconContrast, type FaviconContrast, faviconContrastClass, measureFaviconVisibility+} from "./favicon_contrast.js";+import { LINK_EMBED_CARD_IMAGE_PLACEHOLDER } from "./link_embed_markup.js";++/**+ * Makes the link previews in `container`, as `renderLinkEmbedHtml()` and `renderLinkMentionHtml()`+ * draw them, behave: a video facade loads the player on click, a picture that fails to load gives+ * way to what stands in for a missing one, and a favicon gets the class that lets the page correct+ * an icon drawn for the other background.+ */+export function enhanceLinkPreviews(container: ParentNode) {+ const facades = container.querySelectorAll<HTMLButtonElement>(+ "button.link-embed-video-facade[data-video-id]");+ for (const facade of facades) {+ facade.addEventListener("click", () => playVideo(facade), { once: true });+ }++ // An attachment can be erased under a preview that still references it, and a broken-image+ // glyph reads as a bug where an absence reads as an absence.+ for (const image of container.querySelectorAll<HTMLImageElement>("img.link-embed-card-image")) {+ image.addEventListener("error", () => {+ image.outerHTML = LINK_EMBED_CARD_IMAGE_PLACEHOLDER;+ }, { once: true });+ }++ const favicons = container.querySelectorAll<HTMLImageElement>("img.link-embed-mention-favicon");+ for (const favicon of favicons) {+ favicon.addEventListener("error", () => favicon.remove(), { once: true });+ void applyFaviconContrast(favicon);+ }+}++/**+ * Replaces a video facade with the YouTube player. The click was the play command, hence+ * `autoplay=1`. `origin` is valid only for a web origin: YouTube rejects the desktop app's+ * `trilium-app://` one.+ */+function playVideo(facade: HTMLButtonElement) {+ const videoId = encodeURIComponent(String(facade.dataset.videoId));+ const origin = location.protocol.startsWith("http")+ ? `&origin=${encodeURIComponent(location.origin)}`+ : "";++ const iframe = document.createElement("iframe");+ iframe.src = `https://www.youtube-nocookie.com/embed/${videoId}?rel=0&autoplay=1${origin}`;+ iframe.allow = "accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; "+ + "picture-in-picture; web-share";+ iframe.referrerPolicy = "strict-origin-when-cross-origin";+ iframe.allowFullscreen = true;+ iframe.setAttribute("frameborder", "0");+ facade.replaceWith(iframe);+}++/**+ * Measurements by icon URL, so a page that links one site twenty times measures its icon once.+ * Never invalidated: the verdict depends on the icon's pixels, not on the theme, which is why it+ * travels as a class the stylesheet acts on.+ */+const faviconContrasts = new Map<string, Promise<FaviconContrast>>();++async function applyFaviconContrast(favicon: HTMLImageElement) {+ let contrast = faviconContrasts.get(favicon.src);+ if (!contrast) {+ contrast = measureFaviconContrast(favicon.src);+ faviconContrasts.set(favicon.src, contrast);+ }++ const contrastClass = faviconContrastClass(await contrast);+ if (contrastClass) {+ favicon.classList.add(contrastClass);+ }+}++/**+ * Loads the icon into an image of its own and measures that, so the answer does not depend on when+ * the preview's `<img>` loads or whether it is on screen. The browser has the picture cached.+ * Never rejects: an icon that cannot be read is left alone.+ */+function measureFaviconContrast(src: string) {+ return new Promise<FaviconContrast>((resolve) => {+ const image = new Image();+ image.addEventListener("load", () => {+ const visibility = measureFaviconVisibility(image);+ resolve(visibility ? classifyFaviconContrast(visibility) : "neutral");+ }, { once: true });+ image.addEventListener("error", () => resolve("neutral"), { once: true });+ image.src = src;+ });+}diff --git a/packages/commons/src/lib/link_embed_markup.spec.ts b/packages/commons/src/lib/link_embed_markup.spec.tsnew file mode 100644index 0000000000..407b370b33--- /dev/null+++ b/packages/commons/src/lib/link_embed_markup.spec.ts@@ -0,0 +1,121 @@+import { describe, expect, it } from "vitest";++import {+ LINK_EMBED_CARD_IMAGE_PLACEHOLDER, readLinkPreviewData, renderLinkEmbedHtml,+ renderLinkMentionHtml+} from "./link_embed_markup.js";++const OPTIONS = { playVideoLabel: "Play \"video\"" };+const VIDEO_URL = "https://www.youtube.com/watch?v=dQw4w9WgXcQ";++describe("readLinkPreviewData", () => {+ it("reads the stored attributes, an absent embed type as a card, nothing without a URL", () => {+ const attributes: Record<string, string> = {+ "data-url": "https://example.com",+ "data-title": "Title",+ "data-site-name": "Example"+ };++ expect(readLinkPreviewData((name) => attributes[name])).toEqual({+ url: "https://example.com",+ embedType: "opengraph",+ title: "Title",+ description: undefined,+ image: undefined,+ favicon: undefined,+ siteName: "Example"+ });+ expect(readLinkPreviewData(() => null)).toBeNull();+ });+});++describe("renderLinkMentionHtml", () => {+ it("links the favicon and title, escaped, in a new tab unless editable", () => {+ expect(renderLinkMentionHtml({+ url: "https://example.com/?a=1&b=2",+ title: "<Tom & Jerry's>",+ favicon: "data:image/png;base64,AAA"+ }, OPTIONS)).toBe(+ `<a class="link-embed-mention" href="https://example.com/?a=1&b=2" target="_blank"`+ + ` rel="noopener noreferrer"><img class="link-embed-mention-favicon"`+ + ` src="data:image/png;base64,AAA" alt="" loading="lazy" draggable="false" width="16"`+ + ` height="16"><span class="link-embed-mention-title">`+ + `<Tom & Jerry's></span></a>`);++ const editable = { ...OPTIONS, editable: true };+ expect(renderLinkMentionHtml({ url: "https://fallback.example.com/x" }, editable))+ .toBe(`<a class="link-embed-mention" href="https://fallback.example.com/x"`+ + ` rel="noopener noreferrer"><span class="link-embed-mention-title">`+ + `fallback.example.com</span></a>`);+ });++ it("renders a hostile scheme inert and never loads a remote favicon", () => {+ const html = renderLinkMentionHtml({+ url: "javascript:alert(1)",+ favicon: "https://tracker.test/favicon.ico"+ }, OPTIONS);++ expect(html).toContain(`href="about:blank"`);+ expect(html).not.toContain("<img");+ });+});++describe("renderLinkEmbedHtml", () => {+ it("draws a video as a facade holding the stored thumbnail", () => {+ expect(renderLinkEmbedHtml({+ url: VIDEO_URL,+ embedType: "youtube",+ image: "data:image/jpeg;base64,AAA"+ }, OPTIONS)).toBe(+ `<div class="link-embed-video"><button type="button" class="link-embed-video-facade"`+ + ` data-video-id="dQw4w9WgXcQ" aria-label="Play "video""`+ + ` title="Play "video"">`+ + `<img class="link-embed-video-thumbnail" src="data:image/jpeg;base64,AAA" alt=""`+ + ` loading="lazy" draggable="false">`+ + `<span class="link-embed-video-play" aria-hidden="true">`+ + `</span></button></div>`);+ });++ it("draws a card for a video URL stored as a card, and for an embed that is no video", () => {+ expect(renderLinkEmbedHtml({ url: VIDEO_URL, embedType: "opengraph" }, OPTIONS))+ .toContain(`<a class="link-embed-card"`);+ expect(renderLinkEmbedHtml({ url: "https://example.com", embedType: "youtube" }, OPTIONS))+ .toContain(`<a class="link-embed-card"`);+ });++ it("draws a card with its title, description, cover and site line", () => {+ expect(renderLinkEmbedHtml({+ url: "https://example.com/page",+ embedType: "opengraph",+ title: "A title",+ description: "A description",+ image: "api/attachments/abc123/image/x.png",+ favicon: "data:image/png;base64,AAA",+ siteName: "Example"+ }, OPTIONS)).toBe(+ `<a class="link-embed-card" href="https://example.com/page" target="_blank"`+ + ` rel="noopener noreferrer"><div class="link-embed-card-image-wrapper">`+ + `<img class="link-embed-card-image" src="api/attachments/abc123/image/x.png" alt=""`+ + ` loading="lazy" draggable="false"></div><div class="link-embed-card-content">`+ + `<div class="link-embed-card-title">A title</div>`+ + `<div class="link-embed-card-description">A description</div>`+ + `<div class="link-embed-card-url"><img class="link-embed-mention-favicon"`+ + ` src="data:image/png;base64,AAA" alt="" loading="lazy" draggable="false" width="16"`+ + ` height="16"><span>Example</span></div></div></a>`);+ });++ it("leaves out what the note does not store, falling back to the host and placeholder", () => {+ const html = renderLinkEmbedHtml({+ url: "https://no-meta.example.com/page",+ embedType: "opengraph",+ image: "https://tracker.test/pixel.gif"+ }, { ...OPTIONS, editable: true });++ expect(html).toBe(+ `<a class="link-embed-card" href="https://no-meta.example.com/page"`+ + ` rel="noopener noreferrer"><div class="link-embed-card-image-wrapper">`+ + `${LINK_EMBED_CARD_IMAGE_PLACEHOLDER}</div>`+ + `<div class="link-embed-card-content"><div class="link-embed-card-url">`+ + `<span>no-meta.example.com</span></div></div></a>`);+ });+});diff --git a/packages/commons/src/lib/link_embed_markup.ts b/packages/commons/src/lib/link_embed_markup.tsnew file mode 100644index 0000000000..b73febabde--- /dev/null+++ b/packages/commons/src/lib/link_embed_markup.ts@@ -0,0 +1,137 @@+import {+ extractYouTubeVideoId, safeHostname, safeLinkPreviewHref, safeLinkPreviewImageSrc+} from "./link_embed.js";++/** A link preview as the note stores it, in the `data-*` attributes of its element. */+export interface LinkPreviewData {+ url: string;+ /** `opengraph` draws a card; anything else draws a video player when the URL is a video. */+ embedType?: string | null;+ title?: string | null;+ description?: string | null;+ image?: string | null;+ favicon?: string | null;+ siteName?: string | null;+}++export interface LinkPreviewMarkupOptions {+ /** In the editor a link opens on a double click, so it carries no `target`. */+ editable?: boolean;+ /** The accessible name of a video's play button, translated by the caller. */+ playVideoLabel: string;+}++/**+ * The preview stored on a `section.link-embed` or `span.link-mention`, or `null` when it carries no+ * URL. A missing embed type reads as `opengraph`.+ */+export function readLinkPreviewData(getAttribute: (name: string) => string | null | undefined) {+ const url = getAttribute("data-url");+ if (!url) {+ return null;+ }++ return {+ url,+ embedType: getAttribute("data-embed-type") || "opengraph",+ title: getAttribute("data-title"),+ description: getAttribute("data-description"),+ image: getAttribute("data-image"),+ favicon: getAttribute("data-favicon"),+ siteName: getAttribute("data-site-name")+ } satisfies LinkPreviewData;+}++/**+ * The markup of an inline link mention: the site's favicon and the page title, or the host when+ * the note stores no title.+ */+export function renderLinkMentionHtml(data: LinkPreviewData, options: LinkPreviewMarkupOptions) {+ return `<a class="link-embed-mention" href="${escapeHtml(safeLinkPreviewHref(data.url))}"`+ + `${targetAttribute(options)} rel="noopener noreferrer">`+ + renderFavicon(data.favicon)+ + `<span class="link-embed-mention-title">`+ + `${escapeHtml(data.title || safeHostname(data.url))}</span>`+ + `</a>`;+}++/**+ * The markup of a block link preview: a video player for a video URL, a card otherwise.+ *+ * The player starts as a facade showing the thumbnail stored in the note, so reading a note or a+ * shared page that holds a video does not contact YouTube; `enhanceLinkPreviews()` swaps in the+ * player on the reader's click.+ */+export function renderLinkEmbedHtml(data: LinkPreviewData, options: LinkPreviewMarkupOptions) {+ const videoId = data.embedType !== "opengraph" ? extractYouTubeVideoId(data.url) : null;+ if (videoId) {+ const label = escapeHtml(options.playVideoLabel);+ return `<div class="link-embed-video">`+ + `<button type="button" class="link-embed-video-facade"`+ + ` data-video-id="${escapeHtml(videoId)}"`+ + ` aria-label="${label}" title="${label}">`+ + renderPicture(data.image, "link-embed-video-thumbnail")+ + `<span class="link-embed-video-play" aria-hidden="true"></span>`+ + `</button></div>`;+ }++ const cardImage = renderPicture(data.image, "link-embed-card-image")+ || LINK_EMBED_CARD_IMAGE_PLACEHOLDER;+ const title = data.title+ ? `<div class="link-embed-card-title">${escapeHtml(data.title)}</div>`+ : "";+ const description = data.description+ ? `<div class="link-embed-card-description">${escapeHtml(data.description)}</div>`+ : "";++ return `<a class="link-embed-card" href="${escapeHtml(safeLinkPreviewHref(data.url))}"`+ + `${targetAttribute(options)} rel="noopener noreferrer">`+ // The wrapper gives the card's left column its size, so a card without a picture keeps+ // the shape of one with it.+ + `<div class="link-embed-card-image-wrapper">${cardImage}</div>`+ + `<div class="link-embed-card-content">${title}${description}`+ + `<div class="link-embed-card-url">${renderFavicon(data.favicon)}`+ + `<span>${escapeHtml(data.siteName || safeHostname(data.url))}</span></div>`+ + `</div></a>`;+}++/** What stands in for a card's missing or broken cover image. */+export const LINK_EMBED_CARD_IMAGE_PLACEHOLDER =+ `<div class="link-embed-card-image-placeholder">🔗</div>`;++function targetAttribute({ editable }: LinkPreviewMarkupOptions) {+ return editable ? "" : ` target="_blank"`;+}++/**+ * A missing favicon draws nothing: unlike a card's cover there is no hole to fill, and anything+ * drawn in its place reads as a mark of its own.+ */+function renderFavicon(src: string | null | undefined) {+ return renderPicture(src, "link-embed-mention-favicon", 16);+}++/**+ * One of a preview's pictures, or an empty string when the note stores none the page may load.+ * `safeLinkPreviewImageSrc()` allows only an inline image or an attachment of this instance, so+ * opening a note never makes a request to a third party.+ */+function renderPicture(src: string | null | undefined, className: string, size?: number) {+ const safeSrc = safeLinkPreviewImageSrc(src);+ if (!safeSrc) {+ return "";+ }++ const sizeAttributes = size ? ` width="${size}" height="${size}"` : "";+ return `<img class="${className}" src="${escapeHtml(safeSrc)}" alt="" loading="lazy"`+ + ` draggable="false"${sizeAttributes}>`;+}++function escapeHtml(value: string) {+ return value+ .replaceAll("&", "&")+ .replaceAll("<", "<")+ .replaceAll(">", ">")+ .replaceAll("\"", """)+ .replaceAll("'", "'");+}diff --git a/packages/share-theme/src/content/link_embed.ts b/packages/share-theme/src/content/link_embed.tsdeleted file mode 100644index dce99b5aad..0000000000--- a/packages/share-theme/src/content/link_embed.ts+++ /dev/null@@ -1,74 +0,0 @@-import {- classifyFaviconContrast,- faviconContrastClass,- measureFaviconVisibility-} from "@triliumnext/commons/src/lib/favicon_contrast.js";-import "./link_embed.css";--export default function setupLinkEmbeds() {- setupVideoFacades();- setupFaviconContrast();-}--/**- * Click-to-play for the link-preview video embeds.- *- * The shared page ships only the thumbnail stored in the note (see the share content renderer), so- * reading a page that contains a video does not tell YouTube that the visitor read it. The player is- * loaded here, on the visitor's own click — which doubles as the play command, hence `autoplay=1`.- */-function setupVideoFacades() {- const facades = document.querySelectorAll<HTMLButtonElement>(".link-embed-video-facade[data-video-id]");-- for (const facade of facades) {- facade.addEventListener("click", () => {- const videoId = facade.dataset.videoId;- const container = facade.parentElement;- if (!videoId || !container) {- return;- }-- const iframe = document.createElement("iframe");- iframe.src = `https://www.youtube-nocookie.com/embed/${encodeURIComponent(videoId)}?rel=0&autoplay=1`;- iframe.allow = "accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share";- iframe.referrerPolicy = "strict-origin-when-cross-origin";- iframe.allowFullscreen = true;-- container.replaceChildren(iframe);- });- }-}--/**- * Corrects link-preview favicons that would be invisible against the page.- *- * A site draws its icon for one background, usually its own: GitHub's is a black octocat on nothing,- * which disappears on the dark theme, and a mark drawn white for a dark header disappears on the- * light one. Each icon's own pixels are measured (the shared logic lives in commons, so the app and- * the shared page reach the same verdict about the same picture) and the answer is left on the- * element as a class for `link_embed.css` to act on — which is what lets the visitor's theme switch- * correct the icons with nothing measured again.- */-function setupFaviconContrast() {- for (const favicon of document.querySelectorAll<HTMLImageElement>("img.link-embed-mention-favicon")) {- // A picture already in the browser's cache is complete before this runs and will never fire- // `load`; one still arriving has to be waited for.- if (favicon.complete) {- classifyFavicon(favicon);- } else {- favicon.addEventListener("load", () => classifyFavicon(favicon), { once: true });- }- }-}--function classifyFavicon(favicon: HTMLImageElement) {- const visibility = measureFaviconVisibility(favicon);- if (!visibility) {- return;- }-- const contrastClass = faviconContrastClass(classifyFaviconContrast(visibility));- if (contrastClass) {- favicon.classList.add(contrastClass);- }-}diff --git a/packages/share-theme/src/index.ts b/packages/share-theme/src/index.tsindex f5f0674c7f..3654d82b99 100644--- a/packages/share-theme/src/index.ts+++ b/packages/share-theme/src/index.ts@@ -14,7 +14,7 @@ import "./content/footnotes.css";import "./content/external_links.css";import "./content/task_states.css";import "./content/adaptive_colors.css";-import setupLinkEmbeds from "./content/link_embed.js";+import "./content/link_embed.css";import setupMath from "./content/math.js";import setupMermaid from "./content/mermaid.js";import api from "./api.js";@@ -24,6 +24,7 @@ import "@triliumnext/ckeditor5/src/theme/tabs.css";import "@triliumnext/ckeditor5/src/theme/multicolumn.css";import { applyTabs, revealFragment } from "@triliumnext/ckeditor5/src/plugins/tabs/tabs_read_only.js";+import { enhanceLinkPreviews } from "@triliumnext/commons/src/lib/link_embed_dom.js";function $try<T extends (...a: unknown[]) => unknown>(func: T, ...args: Parameters<T>) {try {@@ -44,7 +45,7 @@ $try(setupSearch);function setupTextNote() {$try(setupMermaid);$try(setupMath);- $try(setupLinkEmbeds);+ $try(() => enhanceLinkPreviews(document.body));$try(setupTabs);}diff --git a/packages/trilium-core/src/share/content_renderer.spec.ts b/packages/trilium-core/src/share/content_renderer.spec.tsindex 0456ebbd5b..8ea4172fb3 100644--- a/packages/trilium-core/src/share/content_renderer.spec.ts+++ b/packages/trilium-core/src/share/content_renderer.spec.ts@@ -62,8 +62,8 @@ describe("content_renderer", () => {const result = getContent(note);expect(result.content).toStrictEqual(trimIndentation`\<p>Before</p>- <p>Foo</p><div>Bar</div>- <strong>Baz</strong>+ <section class="include-note" data-note-id="subnote1" data-box-size="small"><p>Foo</p><div>Bar</div></section>+ <section class="include-note" data-note-id="subnote2" data-box-size="small"><strong>Baz</strong></section><p>After</p>`);});@@ -438,10 +438,12 @@ describe("content_renderer", () => {const content = getContent(note).content as string;const src = "api/attachments/embedPic1/image/my%20photo.png";- expect(content).toContain(`<img src="${src}" alt="my photo.png">`);+ expect(content).toContain(`<section class="include-note" data-attachment-id="embedPic1">`+ + `<img src="${src}" alt="my photo.png"></section>`);+ expect(content).toContain(`<section class="include-note" data-attachment-id="embedPdf1">`+ + `<a class="reference-link attachment-link role-file"`);expect(content).toContain(`href="api/attachments/embedPdf1/download"`);expect(content).toContain("report.pdf");- expect(content).not.toContain("include-note");expect(content).not.toContain("embedGone");});@@ -605,7 +607,7 @@ describe("content_renderer", () => {const content = String(getContent(note).content);expect(content).toContain(`<div class="link-embed-card-url">`- + `<img class="link-embed-mention-favicon" src="${FAVICON}" alt="" loading="lazy" width="16" height="16">`+ + `<img class="link-embed-mention-favicon" src="${FAVICON}" alt="" loading="lazy" draggable="false" width="16" height="16">`+ `<span>Example</span></div>`);});@@ -696,7 +698,7 @@ describe("content_renderer", () => {});const content = String(getContent(note).content);- expect(content).toContain(`<img class="link-embed-mention-favicon" src="${FAVICON}" alt="" loading="lazy" width="16" height="16">`);+ expect(content).toContain(`<img class="link-embed-mention-favicon" src="${FAVICON}" alt="" loading="lazy" draggable="false" width="16" height="16">`);expect(content).toContain(`<span class="link-embed-mention-title">A title</span>`);});});diff --git a/packages/trilium-core/src/share/content_renderer.ts b/packages/trilium-core/src/share/content_renderer.tsindex 09f82d785a..44b5344bc5 100644--- a/packages/trilium-core/src/share/content_renderer.ts+++ b/packages/trilium-core/src/share/content_renderer.ts@@ -1,7 +1,8 @@import {- encodeBlockParameter, extractYouTubeVideoId, isHttpUrl, isImageAttachmentRole, MIME_TYPE_AUTO,- type MimeType, MIME_TYPES_DICT, normalizeMimeTypeForCKEditor, safeLinkPreviewHref,- safeLinkPreviewImageSrc, sliceToBlockReference+ getAttachmentEmbedHref, getEmbedKey, getNestedEmbedOptions, getNoteEmbedHref, isHttpUrl,+ isImageAttachmentRole, MIME_TYPE_AUTO, type MimeType, MIME_TYPES_DICT,+ normalizeMimeTypeForCKEditor, readLinkPreviewData, renderLinkEmbedHtml, renderLinkMentionHtml,+ resolveContentEmbed, sliceToBlockReference} from "@triliumnext/commons";import { renderToHtml as renderMarkdownToHtml } from "@triliumnext/commons/src/lib/markdown_renderer.js";import { renderSpreadsheetToHtml } from "@triliumnext/commons/src/lib/spreadsheet/render_to_html.js";@@ -394,94 +395,20 @@ function renderText(result: Result, note: SNote | BNote, options: ShareRenderOptreturn;}- // One of a preview's pictures, or what stands in for it. Every picture on a shared page makes- // the same decision, so it is made once: safeLinkPreviewImageSrc() keeps the placeholder for- // anything but an inline image or an attachment of this instance, because an <img> fires on- // load — a remote URL here would have every visitor to the shared page announce itself to a- // third party without so much as a click.- const renderPicture = (- src: string | undefined | null,- { className, placeholder, size }: { className: string; placeholder: string; size?: number }- ) => {- const safeSrc = safeLinkPreviewImageSrc(src);-- if (!safeSrc) {- return placeholder;+ // Link previews keep their metadata in `data-*` attributes and are drawn as the app draws+ // them. The share theme adds the click-to-play behavior of a video.+ const previewOptions = { playVideoLabel: t("content_renderer.play-video") };+ for (const mentionEl of document.querySelectorAll("span.link-mention")) {+ const data = readLinkPreviewData((name) => mentionEl.getAttribute(name));+ if (data) {+ mentionEl.innerHTML = renderLinkMentionHtml(data, previewOptions);}+ }- const sizeAttrs = size ? ` width="${size}" height="${size}"` : "";-- return `<img class="${className}" src="${escapeHtml(safeSrc)}" alt="" loading="lazy"${sizeAttrs}>`;- };-- // The site's favicon — shown by both the inline mention and the card's URL line, from the one- // `data-favicon` the element already carries. A site whose icon could not be had shows nothing- // in its place: unlike a card's missing cover there is no hole to fill, and anything stood there- // instead was read as a mark of its own rather than as an absent icon.- const renderFavicon = (favicon: string | undefined | null) => renderPicture(favicon, {- className: "link-embed-mention-favicon",- size: 16,- placeholder: ""- });-- // 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 title = mentionEl.getAttribute("data-title") || safeHostnameForShare(url);- // escapeHtml() makes the value safe to *place* in the attribute; it says nothing about the- // scheme. `data-*` survives the save-time sanitizer untouched, so a stored- // `data-url="javascript:…"` would otherwise become a live link on a public page.- mentionEl.innerHTML = `<a class="link-embed-mention" href="${escapeHtml(safeLinkPreviewHref(url))}" target="_blank" rel="noopener noreferrer">` +- renderFavicon(mentionEl.getAttribute("data-favicon")) +- `<span class="link-embed-mention-title">${escapeHtml(title)}</span></a>`;- }-- // 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");- if (!url) continue;-- if (embedType === "youtube") {- const videoId = extractYouTubeVideoId(url);- if (videoId) {- // Click-to-play: the shared page shows the thumbnail stored in the note and only- // loads YouTube's player once a visitor asks for it, so simply reading the page does- // not hand every visitor's IP to Google. The swap is done by the share theme's- // video_facade script, which reads data-video-id.- // No placeholder: the play button carries the facade on its own.- const thumbnailHtml = renderPicture(embedEl.getAttribute("data-image"), {- className: "link-embed-video-thumbnail",- placeholder: ""- });- embedEl.innerHTML = `<div class="link-embed-video">`- + `<button type="button" class="link-embed-video-facade" data-video-id="${escapeHtml(videoId)}" aria-label="Play video" title="Play video">`- + thumbnailHtml- + `<span class="link-embed-video-play" aria-hidden="true"></span>`- + `</button></div>`;- }- } else {- const title = embedEl.getAttribute("data-title") || safeHostnameForShare(url);- const description = embedEl.getAttribute("data-description");- const siteName = embedEl.getAttribute("data-site-name") || safeHostnameForShare(url);-- // The wrapper is there either way: it is what gives the card's left column its size, so- // a card without a picture keeps the same shape as one with it.- const imageHtml = `<div class="link-embed-card-image-wrapper">`- + renderPicture(embedEl.getAttribute("data-image"), {- className: "link-embed-card-image",- placeholder: `<div class="link-embed-card-image-placeholder">🔗</div>`- })- + `</div>`;- const descHtml = description ? `<div class="link-embed-card-description">${escapeHtml(description)}</div>` : "";- const urlHtml = `<div class="link-embed-card-url">`- + renderFavicon(embedEl.getAttribute("data-favicon"))- + `<span>${escapeHtml(siteName)}</span></div>`;-- embedEl.innerHTML = `<a class="link-embed-card" href="${escapeHtml(safeLinkPreviewHref(url))}" target="_blank" rel="noopener noreferrer">` +- imageHtml +- `<div class="link-embed-card-content"><div class="link-embed-card-title">${escapeHtml(title)}</div>${descHtml}${urlHtml}</div></a>`;+ const data = readLinkPreviewData((name) => embedEl.getAttribute(name));+ if (data) {+ embedEl.innerHTML = renderLinkEmbedHtml(data, previewOptions);}}@@ -496,30 +423,30 @@ function renderText(result: Result, note: SNote | BNote, options: ShareRenderOpt? (attachmentId: string) => becca.getAttachment(attachmentId): (attachmentId: string) => shaca.getAttachment(attachmentId);- const seenNoteIds = new Set(options.seenNoteIds);- seenNoteIds.add(getEmbedKey(note.noteId, options.block));+ const embedContext = {+ seenNoteIds: new Set(options.seenNoteIds).add(getEmbedKey(note.noteId, options.block)),+ embedsAsReferenceLinks: options.embedsAsReferenceLinks,+ expandNestedEmbeds: options.expandNestedEmbeds+ };for (const embedEl of document.querySelectorAll(".include-note")) {- // A Tiny embed shows only a title, so it links to what it shows instead of rendering it.- const asLink = !!options.embedsAsReferenceLinks- || embedEl.getAttribute("data-box-size") === "tiny";- const attachmentId = embedEl.getAttribute("data-attachment-id");- if (attachmentId) {- const attachment = getAttachment(attachmentId);- const html = attachment ? renderAttachmentEmbed(attachmentId, attachment, asLink) : "";- const embed = parse(html, parseOpts).childNodes;- if (attachment && !asLink && isImageAttachmentRole(attachment.role)) {- replaceEmbedContent(embedEl, embed);+ const embed = resolveContentEmbed((name) => embedEl.getAttribute(name), embedContext);+ if (!embed) continue;++ if (embed.kind === "attachment") {+ const attachment = getAttachment(embed.attachmentId);+ if (!attachment) {+ embedEl.remove();+ } else if (embed.asLink) {+ const link = renderAttachmentLink(embed.attachmentId, attachment);+ embedEl.replaceWith(...parse(link, parseOpts).childNodes);} else {- embedEl.replaceWith(...embed);+ const html = renderAttachmentEmbed(embed.attachmentId, attachment);+ replaceEmbedContent(embedEl, parse(html, parseOpts).childNodes);}continue;}- const noteId = embedEl.getAttribute("data-note-id");- if (!noteId) continue;- const block = embedEl.getAttribute("data-block");-- const embeddedNote = shaca.getNote(noteId);+ const embeddedNote = shaca.getNote(embed.noteId);if (!embeddedNote) continue;// An embed must not disclose what a direct request for the same note would refuse: a note@@ -530,31 +457,22 @@ function renderText(result: Result, note: SNote | BNote, options: ShareRenderOptcontinue;}- // Tiny embeds, deeper-than-first-level embeds and any cycle in the recursive path degrade- // to a reference link that the link-processing passes below resolve to the shared note.- if (asLink || seenNoteIds.has(getEmbedKey(noteId, block))) {- const query = block ? `?block=${encodeBlockParameter(block)}` : "";- const href = escapeHtml(`#root/${noteId}${query}`);+ // The link-processing passes below resolve the reference link to the shared note.+ if (embed.asLink) {+ const href = escapeHtml(getNoteEmbedHref(embed.noteId, embed.block));const title = escapeHtml(embeddedNote.title);const link = `<a class="reference-link" href="${href}">${title}</a>`;embedEl.replaceWith(...parse(link, parseOpts).childNodes);continue;}- const nestedOptions: ShareRenderOptions = {- seenNoteIds: new Set(seenNoteIds),- canAccessEmbed: options.canAccessEmbed,- block- };- const embeddedResult = getContent(embeddedNote, options.expandNestedEmbeds- ? { ...nestedOptions, expandNestedEmbeds: true }- : { ...nestedOptions, embedsAsReferenceLinks: true });+ const embeddedResult = getContent(embeddedNote, {+ ...getNestedEmbedOptions(embedContext, embed.block),+ canAccessEmbed: options.canAccessEmbed+ });if (typeof embeddedResult.content !== "string") continue;- const embeddedDocument = parse(embeddedResult.content, parseOpts).childNodes;- if (embeddedDocument) {- replaceEmbedContent(embedEl, embeddedDocument);- }+ replaceEmbedContent(embedEl, parse(embeddedResult.content, parseOpts).childNodes);}result.isEmpty = document.textContent?.trim().length === 0 && document.querySelectorAll("img").length === 0;@@ -597,45 +515,30 @@ function renderText(result: Result, note: SNote | BNote, options: ShareRenderOpt}/** The key of an embed in `seenNoteIds`. A note can embed blocks of itself. */-function getEmbedKey(noteId: string, block: string | undefined) {- return block ? `${noteId}:${block}` : noteId;-}--/**- * Puts `content` in place of an embed. An embed with a caption stays a `<figure>`, holding- * `content` and then the caption.- */+/** Puts `content` in an embed, followed by the embed's caption, as the app does. */function replaceEmbedContent(embedEl: HTMLElement, content: ParsedNode[]) {const caption = embedEl.childNodes.find((child) =>child instanceof HTMLElement && child.tagName === "FIGCAPTION");- if (caption) {- embedEl.set_content([ ...content, caption ]);- } else {- embedEl.replaceWith(...content);- }+ embedEl.set_content(caption ? [ ...content, caption ] : content);}/**- * The markup that stands in for an embedded attachment: a picture as an image, anything else as the- * attachment link that `handleAttachmentLink` then resolves.- *- * @param asLink renders a picture as a link too, for a Tiny embed or one below the first level of- * embedding.+ * What an embedded attachment shows: a picture as an image, anything else as the attachment link+ * that `handleAttachmentLink` then resolves.*/-function renderAttachmentEmbed(- attachmentId: string,- attachment: BAttachment | SAttachment,- asLink: boolean-) {- const { ownerId, title } = attachment;-- if (!asLink && isImageAttachmentRole(attachment.role)) {- const src = `api/attachments/${attachmentId}/image/${encodeURIComponent(title)}`;- return `<img src="${src}" alt="${escapeHtml(title)}">`;+function renderAttachmentEmbed(attachmentId: string, attachment: BAttachment | SAttachment) {+ if (!isImageAttachmentRole(attachment.role)) {+ return renderAttachmentLink(attachmentId, attachment);}- const href = `#root/${ownerId}?viewMode=attachments&attachmentId=${attachmentId}`;- return `<a class="reference-link" href="${href}">${escapeHtml(title)}</a>`;+ const src = `api/attachments/${attachmentId}/image/${encodeURIComponent(attachment.title)}`;+ return `<img src="${src}" alt="${escapeHtml(attachment.title)}">`;+}++/** The reference link to an attachment, which `handleAttachmentLink` then resolves. */+function renderAttachmentLink(attachmentId: string, attachment: BAttachment | SAttachment) {+ const href = escapeHtml(getAttachmentEmbedHref(attachment.ownerId, attachmentId));+ return `<a class="reference-link" href="${href}">${escapeHtml(attachment.title)}</a>`;}function handleAttachmentLink(linkEl: HTMLElement, href: string, getNote: GetNoteFunction, getAttachment: (id: string) => BAttachment | SAttachment | null) {@@ -951,10 +854,6 @@ function isFramableSource(url: string): boolean {}-function safeHostnameForShare(url: string): string {- try { return new URL(url).hostname; } catch { return url; }-}-export default {getContent};diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 9e419fef9f..e870add809 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1308,6 +1308,9 @@ importers:specifier: 3.2.6version: 3.2.6devDependencies:+ happy-dom:+ specifier: 20.14.5+ version: 20.14.5preact:specifier: 11.0.0version: 11.0.0([email protected])