Skip to content

Build your personal knowledge base with Trilium Notes

feat(link previews): keep one cover image per page

Elian Doranb0300497c972
diff --git a/apps/client/src/services/link_embed.spec.ts b/apps/client/src/services/link_embed.spec.ts
index 7323294a5b..476381d09b 100644
--- a/apps/client/src/services/link_embed.spec.ts
+++ b/apps/client/src/services/link_embed.spec.ts
@@ -136,10 +136,16 @@ describe("fetchMetadata", () => {
// with the note's own images, while the favicon is the site's mark, fetched rather than
// chosen — which is what lets icons be deduplicated and kept out of the tools that
// reason about the user's own pictures.
- // The favicon is named by its site, which is the key the note reuses one by: a note
- // linking the same site many times keeps one icon rather than one per link.
+ // Each is named after the thing it is of, which is the key the note reuses one by: the
+ // favicon by its site, so linking that site many times keeps one icon; the cover by its
+ // page, so pasting the same URL twice keeps one cover.
expect(uploadImageAttachmentMock).toHaveBeenCalledWith("note1", "data:image/x-icon;base64,FAV", "favicon", "example.com");
- expect(uploadImageAttachmentMock).toHaveBeenCalledWith("note1", "data:image/jpeg;base64,IMG", "image", undefined);
+ expect(uploadImageAttachmentMock).toHaveBeenCalledWith(
+ "note1",
+ "data:image/jpeg;base64,IMG",
+ "coverImage",
+ expect.stringMatching(/^example-com-[0-9a-f]{8}$/)
+ );
// Only the attachment URLs land in the note content — inlined base64 counts against the
// auto-read-only size threshold, and a favicon pays that cost once per link rather than
// once per note.
diff --git a/apps/client/src/services/link_embed.tsx b/apps/client/src/services/link_embed.tsx
index 92a7f568b2..a4965374cf 100644
--- a/apps/client/src/services/link_embed.tsx
+++ b/apps/client/src/services/link_embed.tsx
@@ -1,6 +1,6 @@
import "../widgets/type_widgets/text/LinkEmbed.css";
-import { extractYouTubeVideoId, type ImageAttachmentRole, type LinkEmbedMetadata, safeLinkPreviewHref, safeLinkPreviewImageSrc, YOUTUBE_REGEX } from "@triliumnext/commons";
+import { extractYouTubeVideoId, type ImageAttachmentRole, type LinkEmbedMetadata, linkPreviewImageName, safeLinkPreviewHref, safeLinkPreviewImageSrc, YOUTUBE_REGEX } from "@triliumnext/commons";
import { render } from "preact";
import { useState } from "preact/hooks";
@@ -49,11 +49,12 @@ export async function fetchMetadata(url: string, ownerNoteId?: string): Promise<
const metadata = await server.post<LinkEmbedMetadata>("link-embed/metadata", { url });
// Uploaded together: they are two independent requests and a preview needs both before it
// can be stored.
- // The favicon is named by its site, which is what lets a note that links the same site many
- // times keep one icon rather than one per link.
+ // Each picture is named after the thing it is of — the favicon by its site, the cover by
+ // its page — which is what lets a note that links the same site many times keep one icon,
+ // and the same URL pasted twice keep one cover.
const [ favicon, image ] = await Promise.all([
offloadPictureToAttachment(metadata.favicon, ownerNoteId, "favicon", safeHostname(metadata.url)),
- offloadPictureToAttachment(metadata.image, ownerNoteId)
+ offloadPictureToAttachment(metadata.image, ownerNoteId, "coverImage", linkPreviewImageName(metadata.url))
]);
return {
diff --git a/apps/client/src/widgets/type_widgets/Attachment.tsx b/apps/client/src/widgets/type_widgets/Attachment.tsx
index 3a9b4d5aa3..c88dec8680 100644
--- a/apps/client/src/widgets/type_widgets/Attachment.tsx
+++ b/apps/client/src/widgets/type_widgets/Attachment.tsx
@@ -166,9 +166,9 @@ function AttachmentInfo({ attachment, isFullDetail, ownerNote, noteContext, view
// preview, OCR and link-copying purposes.
const isFileLike = attachment.role === "file" || attachment.role === "importSource";
const isPicture = isImageAttachmentRole(attachment.role);
- // A link preview's favicon is deliberately left out: it is 16 pixels of site mark, so there is
- // no text in it to find, and offering to read one is noise in every attachment list that has a
- // preview in it. The same goes for recompressing it further down.
+ // A link preview's pictures are deliberately left out: the server already sized both, and both
+ // belong to a preview rather than to the note, so reading text out of them — or offering to
+ // recompress them further down — is noise in every attachment list that holds a preview.
const supportsOcr = attachment.role === "image" || isFileLike;
// Opened in full detail, an image gets the interactive zoom/pan viewer and audio/video the full media
@@ -343,6 +343,8 @@ function AttachmentActions({ attachment, copyAttachmentReferenceToClipboard, onS
iconAction
dropdownContainerClassName="mobile-bottom-menu"
mobileBackdrop
+ // Doesn't scroll, so it keeps the working backdrop blur — see the prop's own docs.
+ noDropdownListStyle
>
<FormListItem
icon="bx bx-file-find"
diff --git a/packages/commons/src/lib/attachment_roles.ts b/packages/commons/src/lib/attachment_roles.ts
index 15d55ad21a..b0c02ef330 100644
--- a/packages/commons/src/lib/attachment_roles.ts
+++ b/packages/commons/src/lib/attachment_roles.ts
@@ -6,13 +6,14 @@
* has to be admitted to all of them at once or it half-works: served but never cleaned up, cleaned
* up but never served, listed but rendered as an unknown file.
*
- * `favicon` is separate from `image` so a link preview's site icon can be told apart from a picture
- * the user put in the note — they are created, deduplicated and replaced on completely different
- * terms, and only one of them is something the user chose. Keeping them apart also keeps icons out
- * of the places that reason about the user's images: the compression inventory has nothing to gain
- * from a 16x16 icon, and offering to recompress one is noise.
+ * `favicon` and `coverImage` are separate from `image` so the two pictures a link preview carries
+ * can be told apart from one the user put in the note — they are created, deduplicated and replaced
+ * on completely different terms, and only `image` is something the user chose. Keeping them apart
+ * also keeps them out of the places that reason about the user's own pictures: both arrive already
+ * sized by the server (a 16x16 icon, a 256px thumbnail), so the compression inventory has nothing
+ * to gain from either and offering to recompress one is noise.
*/
-export const IMAGE_ATTACHMENT_ROLES = [ "image", "favicon" ] as const;
+export const IMAGE_ATTACHMENT_ROLES = [ "image", "favicon", "coverImage" ] as const;
export type ImageAttachmentRole = typeof IMAGE_ATTACHMENT_ROLES[number];
@@ -25,20 +26,22 @@ export function isImageAttachmentRole(role: string | undefined | null): role is
* Roles that keep one attachment per title in a note, rather than one per use.
*
* Only for pictures the app fetched and named itself, where the title says which thing it is and
- * the same thing is fetched again and again: a note that links a site once usually links it many
- * times, and each link would otherwise bring its own copy of that site's icon. One row per site
- * instead of one per link is the difference between an attachment list a reader can use and a
- * wall of identical icons.
+ * the same thing is fetched again and again. A note that links a site once usually links it many
+ * times, so each link would otherwise bring its own copy of that site's icon; and pasting the same
+ * URL twice is ordinary, so each paste would bring its own copy of that page's cover. One row per
+ * thing instead of one per use is the difference between an attachment list a reader can use and a
+ * wall of identical pictures.
*
* Never for a picture the user placed. Two images they happened to give the same name are two
* images, and quietly collapsing them would lose one.
*/
-const DEDUPLICATED_ATTACHMENT_ROLES: readonly string[] = [ "favicon" ];
+const DEDUPLICATED_ATTACHMENT_ROLES: readonly string[] = [ "favicon", "coverImage" ];
/**
* Whether a second attachment of this role and title should reuse the first rather than be stored
* again. The title is the key, so for these roles it is the caller's job to make it identify the
- * thing — a site's hostname for a favicon — and the server's not to shorten it.
+ * thing — a site's hostname for a favicon, a page's URL for its cover — and the server's not to
+ * shorten it.
*/
export function isDeduplicatedAttachmentRole(role: string | undefined | null): boolean {
return !!role && DEDUPLICATED_ATTACHMENT_ROLES.includes(role);
diff --git a/packages/commons/src/lib/link_embed.spec.ts b/packages/commons/src/lib/link_embed.spec.ts
index f66e08ad27..640c78e365 100644
--- a/packages/commons/src/lib/link_embed.spec.ts
+++ b/packages/commons/src/lib/link_embed.spec.ts
@@ -7,6 +7,7 @@ import {
isHttpUrl,
isLocalPreviewImageSrc,
isUrlAloneInBlock,
+ linkPreviewImageName,
safeLinkPreviewHref,
safeLinkPreviewImageSrc,
YOUTUBE_REGEX
@@ -111,6 +112,64 @@ describe("isLocalPreviewImageSrc / safeLinkPreviewImageSrc", () => {
});
});
+describe("linkPreviewImageName", () => {
+ const wiki = "https://en.wikipedia.org/wiki/Russo-Japanese_War";
+
+ it("names the page it is a picture of, readably", () => {
+ // The attachment list shows this, where several rows of "image.jpeg" say nothing about
+ // which is which.
+ expect(linkPreviewImageName(wiki)).toMatch(/^en-wikipedia-org-Russo-Japanese-War-[0-9a-f]{8}$/);
+ });
+
+ it("gives the same URL the same name, which is what makes pasting it twice reuse one picture", () => {
+ expect(linkPreviewImageName(wiki)).toBe(linkPreviewImageName(wiki));
+ });
+
+ it("never gives two different URLs the same name, however alike they reduce to", () => {
+ // The readable part alone could not be the key: reducing a URL to filename-safe characters
+ // is lossy, and these two collapse to the same letters.
+ const slash = "https://example.com/a/b";
+ const dash = "https://example.com/a-b";
+ expect(linkPreviewImageName(slash)).not.toBe(linkPreviewImageName(dash));
+
+ // Same page, different query — a different picture as far as the site is concerned.
+ expect(linkPreviewImageName("https://example.com/p?id=1")).not.toBe(linkPreviewImageName("https://example.com/p?id=2"));
+ });
+
+ it("ignores the fragment, which never changed the picture", () => {
+ // Two links into different sections of one page show the cover they both showed anyway.
+ expect(linkPreviewImageName(`${wiki}#Background`)).toBe(linkPreviewImageName(wiki));
+ expect(linkPreviewImageName(`${wiki}#Aftermath`)).toBe(linkPreviewImageName(wiki));
+ });
+
+ it("treats the same page written two ways as one page", () => {
+ // A bare host and a trailing slash address the same thing, so they share the picture.
+ expect(linkPreviewImageName("https://example.com")).toBe(linkPreviewImageName("https://example.com/"));
+ });
+
+ it("stays a usable file name whatever the address looks like", () => {
+ const names = [
+ linkPreviewImageName("https://example.com/"),
+ linkPreviewImageName("https://exämple.com/ünïcode path/§±!"),
+ linkPreviewImageName(`https://example.com/${"very-long-segment".repeat(20)}`),
+ linkPreviewImageName("not a url at all"),
+ linkPreviewImageName("")
+ ];
+
+ for (const name of names) {
+ // Nothing a file system, a URL or an export archive would have to escape.
+ expect(name, name).toMatch(/^[a-zA-Z0-9-]+$/);
+ expect(name.startsWith("-"), name).toBe(false);
+ expect(name.endsWith("-"), name).toBe(false);
+ // Bounded, so a long path cannot crowd the attachment list out.
+ expect(name.length, name).toBeLessThanOrEqual(70);
+ }
+
+ // And these are all different addresses, so they are all different names.
+ expect(new Set(names).size).toBe(names.length);
+ });
+});
+
describe("isUrlAloneInBlock", () => {
const url = "https://youtu.be/dQw4w9WgXcQ";
const text = (data: string): BlockChildLike => ({ isText: true, data });
diff --git a/packages/commons/src/lib/link_embed.ts b/packages/commons/src/lib/link_embed.ts
index d8b18f5211..2d29347f85 100644
--- a/packages/commons/src/lib/link_embed.ts
+++ b/packages/commons/src/lib/link_embed.ts
@@ -84,6 +84,69 @@ export function safeLinkPreviewImageSrc(src: string | undefined | null): string
return isLocalPreviewImageSrc(src) ? String(src).trim() : undefined;
}
+/**
+ * The attachment title a link preview's cover image is stored under.
+ *
+ * This is the deduplication key (see `isDeduplicatedAttachmentRole`), so it has to name exactly one
+ * page: pasting a URL twice must reuse the first picture, and two different URLs must never land on
+ * the same one. It is also what a reader sees in the attachment list, where several rows of
+ * "image.jpeg" say nothing about which is which.
+ *
+ * So it is both — a readable part built from the host and the last path segment, and a short digest
+ * of the whole address. The readable part cannot be the key on its own: reducing a URL to
+ * filename-safe characters is lossy, and `.../a/b` and `.../a-b` would reduce to the same name and
+ * then to the same picture. The digest settles identity; the prefix is there to be read.
+ *
+ * The fragment is left out of both. It never reaches the server and never changes the picture, so
+ * two links into different sections of one page share the cover they both showed anyway.
+ */
+export function linkPreviewImageName(url: string): string {
+ let canonical = url;
+ let readable = url;
+
+ try {
+ const parsed = new URL(url);
+ parsed.hash = "";
+ canonical = parsed.toString();
+
+ const lastSegment = decodeURIComponent(parsed.pathname).split("/").filter(Boolean).pop() ?? "";
+ readable = `${parsed.hostname} ${lastSegment}`;
+ } catch {
+ // Not an address that can be taken apart — rare, since a preview only ever has an http(s)
+ // URL. The digest identifies it regardless; only the readable part suffers.
+ }
+
+ return `${toFileNamePart(readable) || "image"}-${shortDigest(canonical)}`;
+}
+
+/** How much of the readable part to keep, so a long path does not crowd out the attachment list. */
+const PREVIEW_NAME_MAX_READABLE = 60;
+
+function toFileNamePart(value: string): string {
+ return value
+ .replace(/[^a-zA-Z0-9]+/g, "-")
+ .slice(0, PREVIEW_NAME_MAX_READABLE)
+ .replace(/^-+|-+$/g, "");
+}
+
+/**
+ * A short digest of a string, used only to tell two addresses apart.
+ *
+ * FNV-1a, which is not a security primitive and is not asked to be one. Web Crypto is not an option
+ * here: Trilium is served over plain HTTP as often as not, and `crypto.subtle` exists only in a
+ * secure context.
+ */
+function shortDigest(value: string): string {
+ let hash = 0x811c9dc5;
+
+ for (let i = 0; i < value.length; i++) {
+ hash ^= value.charCodeAt(i);
+ hash = Math.imul(hash, 0x01000193);
+ }
+
+ return (hash >>> 0).toString(16).padStart(8, "0");
+}
+
export interface LinkEmbedMetadata {
url: string;
title?: string;
diff --git a/packages/trilium-core/src/routes/api/attachments.spec.ts b/packages/trilium-core/src/routes/api/attachments.spec.ts
index 36a33bbc2e..ae29ce2d8f 100644
--- a/packages/trilium-core/src/routes/api/attachments.spec.ts
+++ b/packages/trilium-core/src/routes/api/attachments.spec.ts
@@ -275,6 +275,21 @@ describe("Attachments API (core)", () => {
expect(attachments.map((a) => a.title).sort()).toStrictEqual([ "example.com.ico", "other.example.ico" ]);
});
+ it("reuses a cover image of the same title, which is what the same URL pasted twice gives", async () => {
+ const { noteId } = await createTextNote(api, { title: "Cover dedup target" });
+ const upload = (title: string) => api.post<{ url: string }>(
+ `/api/notes/${noteId}/attachments/upload?role=coverImage`,
+ { file: { originalname: title, mimetype: "image/jpeg", buffer: PIXEL_PNG } }
+ );
+
+ const first = await upload("en-wikipedia-org-Russo-Japanese-War-1a2b3c4d.jpeg");
+ const again = await upload("en-wikipedia-org-Russo-Japanese-War-1a2b3c4d.jpeg");
+ await upload("en-wikipedia-org-Crimean-War-5e6f7a8b.jpeg");
+
+ expect(again.body.url).toBe(first.body.url);
+ expect((await api.get<AttachmentPojo[]>(`/api/notes/${noteId}/attachments`)).body).toHaveLength(2);
+ });
+
it("does not deduplicate the user's own images, whatever they are called", async () => {
// Two pictures the user gave the same name are two pictures; collapsing them would
// lose one. Only roles the app names itself deduplicate.