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
link previews: take the feature to 100% test coverage on every layer
Elian Dorane89d2ee1c291
diff --git a/apps/client/src/services/link_embed.spec.ts b/apps/client/src/services/link_embed.spec.tsindex eee17efc4b..93f9a3679e 100644--- a/apps/client/src/services/link_embed.spec.ts+++ b/apps/client/src/services/link_embed.spec.ts@@ -137,6 +137,30 @@ describe("renderEmbedPreview", () => {expect(root.querySelector("button.link-embed-video-facade")).toBeNull();});+ it("omits the player's origin param when not served from a web origin (desktop custom protocol)", async () => {+ // On desktop the renderer is served from trilium-app://app, which YouTube's player rejects+ // as an `origin` value — the param must be left out entirely there.+ const happyDOM = (window as unknown as { happyDOM: { setURL(url: string): void } }).happyDOM;+ const previousUrl = window.location.href;+ happyDOM.setURL("trilium-app://app/index.html");++ try {+ const root = makeContainer();+ renderEmbedPreview(root, {+ url: "https://www.youtube.com/watch?v=dQw4w9WgXcQ",+ embedType: "youtube"+ });+ root.querySelector<HTMLButtonElement>("button.link-embed-video-facade")?.click();+ await new Promise((resolve) => setTimeout(resolve, 0));++ const src = root.querySelector("iframe")?.getAttribute("src") ?? "";+ expect(src).toContain("youtube-nocookie.com/embed/dQw4w9WgXcQ");+ expect(src).not.toContain("origin=");+ } finally {+ happyDOM.setURL(previousUrl);+ }+ });+it("shows the facade without a thumbnail when the note stores no image", () => {const root = makeContainer();renderEmbedPreview(root, {diff --git a/apps/server/src/routes/api/link_embed.spec.ts b/apps/server/src/routes/api/link_embed.spec.tsindex 5e2560d689..60d457d104 100644--- a/apps/server/src/routes/api/link_embed.spec.ts+++ b/apps/server/src/routes/api/link_embed.spec.ts@@ -330,6 +330,134 @@ describe("link-embed getMetadata", () => {expect(result.unresolved).toBeUndefined();});+ it("drops a favicon whose stream exceeds the limit despite a smaller advertised size", async () => {+ // A lying content-length must not bypass the cap: the limit is enforced while streaming too.+ const html = `<html><head><title>Plain</title><link rel="icon" href="/liar.ico"></head></html>`;+ const chunk = Buffer.alloc(40 * 1024, 7);+ safeFetch.mockImplementation(async (url: string) => {+ if (url.includes("liar.ico")) {+ let sent = 0;+ return {+ ok: true,+ status: 200,+ // No content-type either, exercising the caller-provided default.+ headers: { get: (h: string) => (h.toLowerCase() === "content-length" ? "10" : null) },+ body: {+ getReader: () => ({+ async read() {+ if (sent >= 2) return { done: true, value: undefined };+ sent++;+ return { done: false, value: new Uint8Array(chunk) };+ },+ async cancel() {}+ })+ },+ json: async () => undefined+ };+ }+ return fakeResponse(html, { contentType: "text/html" });+ });++ const result = await linkEmbedRoute.getMetadata(req("https://example.com/page"));+ expect(result.title).toBe("Plain");+ expect(result.favicon).toBeUndefined();+ });++ it("keeps the preview when the favicon download throws or has no body", async () => {+ const html = `<html><head><title>Plain</title><link rel="icon" href="/fav.ico"></head></html>`;++ // The favicon fetch itself throws (network error): swallowed, the preview survives.+ safeFetch.mockImplementation(async (url: string) => {+ if (url.includes("fav.ico")) throw new Error("network down");+ return fakeResponse(html, { contentType: "text/html" });+ });+ let result = await linkEmbedRoute.getMetadata(req("https://example.com/page"));+ expect(result.title).toBe("Plain");+ expect(result.favicon).toBeUndefined();++ // A bodyless favicon response: nothing to stream, same graceful outcome.+ safeFetch.mockImplementation(async (url: string) => {+ if (url.includes("fav.ico")) return { ...fakeResponse(""), body: undefined };+ return fakeResponse(html, { contentType: "text/html" });+ });+ result = await linkEmbedRoute.getMetadata(req("https://example.com/page"));+ expect(result.favicon).toBeUndefined();+ });++ it("treats a bodyless or content-type-less page response as unresolved", async () => {+ // No body: there is no HTML to read, so the page names itself nowhere.+ safeFetch.mockResolvedValue({ ...fakeResponse("<html><head><title>T</title></head></html>"), body: undefined });+ let result = await linkEmbedRoute.getMetadata(req("https://example.com/page"));+ expect(result.unresolved).toBe(true);++ // No content-type header at all: not provably HTML, same as a wrong content type.+ const response = fakeResponse("<html><head><title>T</title></head></html>");+ response.headers = { get: () => null };+ safeFetch.mockResolvedValue(response);+ result = await linkEmbedRoute.getMetadata(req("https://example.com/page"));+ expect(result.unresolved).toBe(true);+ });++ it("skips icon links it cannot use, ranks a scalable 'any' icon first and dedupes the conventional path", async () => {+ const html = `<html><head><title>T</title>+ <link href="/no-rel.png">+ <link rel="stylesheet" href="/style.css">+ <link rel="icon">+ <link rel="icon" sizes="garbage" href="/undeclared.png">+ <link rel="icon" sizes="any" href="/scalable.svg">+ <link rel="apple-touch-icon" href="/apple-touch-icon.png">+ </head></html>`;+ const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><rect width="10" height="10"/></svg>`;+ // The call log is inspected below, so drop the calls accumulated by earlier tests.+ safeFetch.mockReset();+ safeFetch.mockImplementation(async (url: string) => {+ if (url.endsWith("/scalable.svg")) return fakeResponse(svg, { contentType: "image/svg+xml" });+ if (url.endsWith("/page")) return fakeResponse(html, { contentType: "text/html" });+ return fakeResponse("", { ok: false });+ });++ const result = await linkEmbedRoute.getMetadata(req("https://example.com/page"));+ // "any" declares a scalable icon — the best possible candidate, tried (and kept) first.+ expect(result.image).toMatch(/^data:image\/svg\+xml;base64,/);+ // The declared apple-touch-icon href dedupes against the conventional fallback path, so it+ // is never requested twice.+ const touchIconRequests = safeFetch.mock.calls+ .map((call) => String(call[0]))+ .filter((url) => url.includes("apple-touch-icon"));+ expect(touchIconRequests.length).toBeLessThanOrEqual(1);+ });++ it("sets no title or thumbnail override when oEmbed answers with an empty payload", async () => {+ const thumb = await makePng(120, 90, 0xff0000ff);+ safeFetch.mockImplementation(async (url: string) => {+ if (url.includes("oembed")) return fakeResponse("", { json: {} });+ if (url.includes("hqdefault.jpg")) return fakeResponse(thumb, { contentType: "image/jpeg" });+ if (url.includes("favicon")) return fakeResponse(Buffer.from([1]), { contentType: "image/x-icon" });+ return fakeResponse("", { ok: false });+ });++ const result = await linkEmbedRoute.getMetadata(req("https://youtu.be/dQw4w9WgXcQ"));+ expect(result.embedType).toBe("youtube");+ // An empty payload is not an error: nothing throws, so the generic fallback title is not+ // used either, and the thumbnail comes from the conventional hqdefault URL.+ expect(result.title).toBeUndefined();+ expect(result.description).toBeUndefined();+ expect(result.image).toMatch(/^data:image\/jpeg;base64,/);+ });++ it("ignores meta tags whose content is empty, falling back to the document title", async () => {+ const html = `<html><head>+ <meta property="og:title" content="">+ <meta name="description" content="">+ <title>Doc Title</title>+ </head></html>`;+ safeFetch.mockResolvedValue(fakeResponse(html, { contentType: "text/html" }));++ const result = await linkEmbedRoute.getMetadata(req("https://example.com/page"));+ expect(result.title).toBe("Doc Title");+ expect(result.description).toBeUndefined();+ });+it("ignores a favicon that advertises a size over the limit", async () => {const html = `<html><head><title>Plain</title><link rel="icon" href="/big.ico"></head></html>`;safeFetch.mockImplementation(async (url: string) => {diff --git a/apps/server/src/routes/api/link_embed.ts b/apps/server/src/routes/api/link_embed.tsindex 5c28e3f328..0d67bb7f91 100644--- a/apps/server/src/routes/api/link_embed.ts+++ b/apps/server/src/routes/api/link_embed.ts@@ -232,8 +232,9 @@ function collectIconCandidates(document: ReturnType<typeof parse>, pageUrl: stricandidates.sort((a, b) => b.size - a.size);const urls = candidates.map((candidate) => candidate.url);- const conventional = toAbsoluteUrl("/apple-touch-icon.png", pageUrl);- if (conventional && !urls.includes(conventional)) {+ // `pageUrl` already passed validateUrl, so resolving the conventional path against it cannot fail.+ const conventional = new URL("/apple-touch-icon.png", pageUrl).toString();+ if (!urls.includes(conventional)) {urls.push(conventional);}@@ -260,12 +261,10 @@ async function resolveFavicon(document: ReturnType<typeof parse>, pageUrl: strin|| document.querySelector('link[rel="shortcut icon"]')|| document.querySelector('link[rel="apple-touch-icon"]');- let faviconUrl = toAbsoluteUrl(faviconEl?.getAttribute("href"), pageUrl);- if (!faviconUrl) {- faviconUrl = toAbsoluteUrl("/favicon.ico", pageUrl);- }+ // `pageUrl` already passed validateUrl, so the conventional fallback always forms a URL.+ const faviconUrl = toAbsoluteUrl(faviconEl?.getAttribute("href"), pageUrl)+ ?? new URL("/favicon.ico", pageUrl).toString();- if (!faviconUrl) return undefined;return await downloadFaviconAsDataUri(faviconUrl);}diff --git a/packages/ckeditor5/src/plugins/link_embed/link_embed_commands.spec.ts b/packages/ckeditor5/src/plugins/link_embed/link_embed_commands.spec.tsindex 8e077a7135..514b11ff0e 100644--- a/packages/ckeditor5/src/plugins/link_embed/link_embed_commands.spec.ts+++ b/packages/ckeditor5/src/plugins/link_embed/link_embed_commands.spec.ts@@ -379,6 +379,50 @@ describe("LinkEmbed commands", () => {expect(editor.getData()).toBe("<p>replaced</p>");});+ it("does not convert when the link was repointed at a different URL while the metadata was being fetched", async () => {+ const url = "https://example.com/";+ let resolveFetch: (meta: unknown) => void = () => {};+ fetchLinkMetadata.mockReturnValue(new Promise((resolve) => { resolveFetch = resolve; }));+ setModelData(editor.model, `<paragraph><$text linkHref="${url}">https://exa[]mple.com/</$text></paragraph>`);++ const executed = editor.execute(CHANGE_LINK_DISPLAY_COMMAND, { value: "inline" }) as unknown as Promise<void>;+ editor.model.change((writer) => {+ const paragraph = editor.model.document.getRoot()?.getChild(0);+ if (!paragraph?.is("element")) throw new Error("Expected a paragraph.");+ writer.setAttribute("linkHref", "https://other.example.com/", writer.createRangeIn(paragraph));+ });+ resolveFetch({ ...META, url });+ await executed;++ // The text is still there but no longer carries the fetched URL: converting it would+ // attach one page's metadata to another page's link.+ expect(findElement(editor, "linkMention")).toBeUndefined();+ });++ it("still converts when the linked text survives behind an inserted element and a repointed prefix", async () => {+ const url = "https://example.com/";+ let resolveFetch: (meta: unknown) => void = () => {};+ fetchLinkMetadata.mockReturnValue(new Promise((resolve) => { resolveFetch = resolve; }));+ setModelData(editor.model, `<paragraph><$text linkHref="${url}">https://exa[]mple.com/</$text></paragraph>`);++ const executed = editor.execute(CHANGE_LINK_DISPLAY_COMMAND, { value: "inline" }) as unknown as Promise<void>;+ editor.model.change((writer) => {+ const paragraph = editor.model.document.getRoot()?.getChild(0);+ if (!paragraph?.is("element")) throw new Error("Expected a paragraph.");+ // Repoint the first five characters and wedge a soft break after them: the range+ // walker must skip both before finding text that still carries the original link.+ writer.setAttribute("linkHref", "https://other.example.com/", writer.createRange(+ writer.createPositionAt(paragraph, 0),+ writer.createPositionAt(paragraph, 5)+ ));+ writer.insertElement("softBreak", paragraph, 5);+ });+ resolveFetch({ ...META, url });+ await executed;++ expect(findElement(editor, "linkMention")?.getAttribute("url")).toBe(url);+ });+it("does nothing when executed without a selected link widget or a native link", () => {setModelData(editor.model, "<paragraph>foo[]bar</paragraph>");const before = editor.getData();diff --git a/packages/ckeditor5/src/plugins/link_embed/link_embed_commands.ts b/packages/ckeditor5/src/plugins/link_embed/link_embed_commands.tsindex 39d034c236..ec8d042f70 100644--- a/packages/ckeditor5/src/plugins/link_embed/link_embed_commands.ts+++ b/packages/ckeditor5/src/plugins/link_embed/link_embed_commands.ts@@ -321,11 +321,12 @@ function effectiveTitle(element: any): string {const title = element.getAttribute('title') as string | undefined;if (title) return title;- const url = element.getAttribute('url') as string | undefined;+ /* v8 ignore next -- every linkEmbed/linkMention is created with a url attribute (a widget without one does not even render), so the fallback arm is unreachable */+ const url = (element.getAttribute('url') ?? '') as string;try {- return new URL(url ?? '').hostname;+ return new URL(url).hostname;} catch {- return url ?? '';+ return url;}}diff --git a/packages/ckeditor5/src/plugins/link_embed/link_embed_toolbar.spec.ts b/packages/ckeditor5/src/plugins/link_embed/link_embed_toolbar.spec.tsindex aed1f98c83..c17d698817 100644--- a/packages/ckeditor5/src/plugins/link_embed/link_embed_toolbar.spec.ts+++ b/packages/ckeditor5/src/plugins/link_embed/link_embed_toolbar.spec.ts@@ -728,6 +728,32 @@ describe("LinkEmbedToolbar", () => {form.keystrokes.press({ keyCode: 27, preventDefault: () => {}, stopPropagation: () => {} } as unknown as Parameters<typeof form.keystrokes.press>[0]);expect(balloon.hasView(form)).toBe(false);});++ it("linkEmbedEditTitle guards reopening, closes on outside click, and opens blank without a widget", () => {+ const button = createButton("linkEmbedEditTitle");+ selectLinkMention();+ editor.ui.focusTracker.isFocused = true;+ editor.ui.fire("update");++ const balloon = editor.plugins.get(ContextualBalloon);+ button.fire("execute");+ const form = balloon.visibleView as LinkEmbedTitleFormView;+ expect(form).toBeInstanceOf(LinkEmbedTitleFormView);++ // A second click while the form is open is a no-op, not a second balloon entry.+ button.fire("execute");+ expect(balloon.visibleView).toBe(form);++ // A click outside the balloon dismisses the form without saving.+ document.body.dispatchEvent(new MouseEvent("mousedown", { bubbles: true }));+ expect(balloon.hasView(form)).toBe(false);+ expect(editor.model.document.selection.getSelectedElement()?.getAttribute("title")).toBe("T");++ // Fired with no widget under the selection, the form opens blank (the command reports null).+ setModelData(editor.model, "<paragraph>foo[]bar</paragraph>");+ button.fire("execute");+ expect(form.title).toBe("");+ });});});diff --git a/packages/ckeditor5/src/plugins/link_embed/link_embed_toolbar.ts b/packages/ckeditor5/src/plugins/link_embed/link_embed_toolbar.tsindex a565dc7639..7a0bf85cd9 100644--- a/packages/ckeditor5/src/plugins/link_embed/link_embed_toolbar.ts+++ b/packages/ckeditor5/src/plugins/link_embed/link_embed_toolbar.ts@@ -284,8 +284,9 @@ class LinkEmbedEditTitleButton extends Plugin {if (balloon.hasView(form)) return;// Prefill with what the preview currently shows, so a save without edits changes nothing.- const command = editor.commands.get(CHANGE_LINK_PREVIEW_TITLE_COMMAND) as (Command & { value: string | null }) | undefined;- form.reset(command?.value ?? "");+ // The command always exists: LinkEmbedEditing registers it and this plugin requires LinkEmbed.+ const command = editor.commands.get(CHANGE_LINK_PREVIEW_TITLE_COMMAND) as Command & { value: string | null };+ form.reset(command.value ?? "");balloon.add({view: form,diff --git a/packages/commons/src/lib/link_embed.spec.ts b/packages/commons/src/lib/link_embed.spec.tsindex 6ba9501f5e..d482f5fd05 100644--- a/packages/commons/src/lib/link_embed.spec.ts+++ b/packages/commons/src/lib/link_embed.spec.ts@@ -86,6 +86,8 @@ describe("isUrlAloneInBlock", () => {expect(isUrlAloneInBlock([text(" "), text(url), text("\n")], url)).toBe(true);// Adjacent text nodes that together spell the URL.expect(isUrlAloneInBlock([text("https://youtu.be/"), text("dQw4w9WgXcQ")], url)).toBe(true);+ // A text child carrying no data contributes nothing, rather than the string "undefined".+ expect(isUrlAloneInBlock([text(url), { isText: true }], url)).toBe(true);});it("is false when the URL is surrounded by other text or non-text nodes", () => {