Skip to content

Build your personal knowledge base with Trilium Notes

feat(link previews): describe a page from its own opening sentence when it publishes none

Elian Doran1b6aa04404d2
diff --git a/apps/server/src/routes/api/link_embed.spec.ts b/apps/server/src/routes/api/link_embed.spec.ts
index 4ed106c19f..b5cd3a9be3 100644
--- a/apps/server/src/routes/api/link_embed.spec.ts
+++ b/apps/server/src/routes/api/link_embed.spec.ts
@@ -645,6 +645,26 @@ describe("link-embed getMetadata", () => {
expect(await describedBy("")).toBeUndefined();
});
+ it("falls back to the page's own opening sentence, but only where it says nothing itself", async () => {
+ const article = `<article><p>Fowler–Noll–Vo is a non-cryptographic hash function created by Glenn Fowler and others.</p></article>`;
+ const describedBy = async (head: string) => {
+ safeFetch.mockResolvedValue(fakeResponse(
+ `<html><head><title>T</title>${head}</head><body>${article}</body></html>`,
+ { contentType: "text/html" }
+ ));
+ return (await linkEmbedRoute.getMetadata(req("https://example.com/page"))).description;
+ };
+
+ // What a Wikipedia article offers: a title and nothing else.
+ expect(await describedBy("")).toBe("Fowler–Noll–Vo is a non-cryptographic hash function created by Glenn Fowler and others.");
+
+ // A description the site wrote for the purpose is what it wants shown, so every one of them
+ // comes first.
+ expect(await describedBy(`<meta property="og:description" content="Written for the card">`)).toBe("Written for the card");
+ expect(await describedBy(`<meta name="twitter:description" content="Written for the card">`)).toBe("Written for the card");
+ expect(await describedBy(`<meta name="description" content="Written for a search result">`)).toBe("Written for a search result");
+ });
+
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.ts
index aef843976a..c160d28908 100644
--- a/apps/server/src/routes/api/link_embed.ts
+++ b/apps/server/src/routes/api/link_embed.ts
@@ -14,6 +14,7 @@ import { parse } from "node-html-parser";
import { trimIcoToSmallestEntry } from "../../services/ico.js";
import { getImageTypeFromBuffer } from "../../services/image_codec.js";
+import { findPageDescription } from "../../services/page_description.js";
import { safeFetch, validateUrl } from "../../services/safe_fetch.js";
const MAX_RESPONSE_SIZE = 512 * 1024; // 512KB
@@ -475,7 +476,11 @@ async function fetchOpenGraphData(url: string) {
// Twitter tags are common enough to be worth the extra look. `getMeta` tries `property=`
// and `name=` in turn, so it finds the tag under either spelling — the card spec says
// `name`, and plenty of sites write `property` regardless.
- description: getMeta("og:description") || getMeta("twitter:description") || getMeta("description") || undefined,
+ // ...and the page's own opening sentence where it publishes no description at all, which a
+ // Wikipedia article does not. See findPageDescription: only ever reached when the site has
+ // said nothing, a description written for the purpose being what it wants shown.
+ description: getMeta("og:description") || getMeta("twitter:description") || getMeta("description")
+ || findPageDescription(document),
siteName: getMeta("og:site_name") || undefined,
image,
favicon
diff --git a/apps/server/src/services/page_description.spec.ts b/apps/server/src/services/page_description.spec.ts
new file mode 100644
index 0000000000..f284740a73
--- /dev/null
+++ b/apps/server/src/services/page_description.spec.ts
@@ -0,0 +1,118 @@
+import { parse } from "node-html-parser";
+import { describe, expect, it } from "vitest";
+
+import { findPageDescription } from "./page_description.js";
+
+const describedBy = (html: string) => findPageDescription(parse(html));
+
+/** A paragraph long enough to pass for a summary, in `length` characters. */
+const prose = (length: number, word = "sentence ") => word.repeat(Math.ceil(length / word.length)).slice(0, length).trim();
+
+describe("findPageDescription", () => {
+ it("takes the opening sentence of the page's own writing", () => {
+ // The case this exists for: a Wikipedia article publishes og:title and nothing else, while
+ // opening with a perfectly good sentence saying what it is about.
+ const html = `<html><body>
+ <div id="mw-content-text">
+ <p>Fowler–Noll–Vo (or FNV) is a non-cryptographic hash function created by Glenn Fowler and others.</p>
+ <p>${prose(120)}</p>
+ </div>
+ </body></html>`;
+
+ expect(describedBy(html)).toBe("Fowler–Noll–Vo (or FNV) is a non-cryptographic hash function created by Glenn Fowler and others.");
+ });
+
+ it("looks inside the article before the page at large", () => {
+ // A banner above the content is earlier in the document and long enough to pass; the
+ // article is where the page's own writing is.
+ const html = `<html><body>
+ <div class="cookie-banner"><p>${prose(150, "We value your privacy ")}</p></div>
+ <article><p>${prose(150, "The article itself ")}</p></article>
+ </body></html>`;
+
+ expect(describedBy(html)?.startsWith("The article itself")).toBe(true);
+ });
+
+ it("passes over what is too short to be a summary", () => {
+ // Captions, bylines and stray lines of chrome.
+ const html = `<html><body><article>
+ <p>By A. Writer</p>
+ <p>3 min read</p>
+ <p>${prose(120, "The actual summary ")}</p>
+ </article></body></html>`;
+
+ expect(describedBy(html)?.startsWith("The actual summary")).toBe(true);
+ });
+
+ it("passes over the furniture, wherever in the document it sits", () => {
+ for (const tag of [ "nav", "aside", "header", "footer", "figure", "table", "form" ]) {
+ const html = `<html><body>
+ <${tag}><p>${prose(150, "Furniture text ")}</p></${tag}>
+ <p>${prose(150, "The page itself ")}</p>
+ </body></html>`;
+
+ expect(describedBy(html)?.startsWith("The page itself"), tag).toBe(true);
+ }
+ });
+
+ it("passes over a paragraph that is mostly links", () => {
+ // A cookie notice, a row of breadcrumbs or a footer of policy links can each be long enough
+ // to pass for a summary. What they are not is prose.
+ const links = Array.from({ length: 12 }, (_, i) => `<a href="/p${i}">Some policy link ${i}</a>`).join(" · ");
+ const html = `<html><body>
+ <p>${links}</p>
+ <p>${prose(150, "Actual prose ")}</p>
+ </body></html>`;
+
+ expect(describedBy(html)?.startsWith("Actual prose")).toBe(true);
+ });
+
+ it("keeps a paragraph that merely contains a link", () => {
+ // The guard is about navigation, not about prose that happens to cite something.
+ const html = `<html><body><p>`
+ + `${prose(140, "Ordinary prose ")} and see <a href="/x">this page</a> for more.`
+ + `</p></body></html>`;
+
+ expect(describedBy(html)?.startsWith("Ordinary prose")).toBe(true);
+ });
+
+ it("bounds what it keeps, this ending up in the note's HTML", () => {
+ const description = describedBy(`<html><body><p>${prose(900)}</p></body></html>`) ?? "";
+
+ expect(description.length).toBeLessThanOrEqual(201);
+ expect(description.endsWith("…")).toBe(true);
+ // Cut on the text, not mid-collapse: no trailing space before the ellipsis.
+ expect(description).not.toContain(" …");
+ });
+
+ it("reads the text as it would be read, not as it is laid out", () => {
+ const html = `<html><body><p>
+ Broken across
+ several\tlines ${prose(90)}
+ </p></body></html>`;
+
+ expect(describedBy(html)?.startsWith("Broken across several lines")).toBe(true);
+ });
+
+ it("says nothing for a page that has no prose in it", () => {
+ // Hacker News, and anything else that is a list rather than a document.
+ expect(describedBy(`<html><body><table><tr><td><a href="/x">A link</a></td></tr></table></body></html>`)).toBeUndefined();
+ expect(describedBy(`<html><body><p>Too short</p></body></html>`)).toBeUndefined();
+ expect(describedBy("<html><body></body></html>")).toBeUndefined();
+ });
+
+ it("leaves the document as it found it", () => {
+ // It reads a tree already parsed for the preview's other parts, so removing the furniture
+ // would take the favicon and the icon candidates with it.
+ const document = parse(`<html><head><link rel="icon" href="/fav.ico"></head><body>
+ <nav><p>${prose(150, "Navigation ")}</p></nav>
+ <p>${prose(150, "The page itself ")}</p>
+ </body></html>`);
+
+ findPageDescription(document);
+
+ expect(document.querySelector(`link[rel="icon"]`)?.getAttribute("href")).toBe("/fav.ico");
+ expect(document.querySelectorAll("nav")).toHaveLength(1);
+ expect(document.querySelectorAll("p")).toHaveLength(2);
+ });
+});
diff --git a/apps/server/src/services/page_description.ts b/apps/server/src/services/page_description.ts
new file mode 100644
index 0000000000..12c45899b9
--- /dev/null
+++ b/apps/server/src/services/page_description.ts
@@ -0,0 +1,97 @@
+import type { HTMLElement } from "node-html-parser";
+
+/**
+ * A description read out of a page's own text, for a page that publishes none of itself.
+ *
+ * Plenty do not: a Wikipedia article carries `og:title` and `og:type` and nothing else, so a
+ * preview of one showed a bare title where the page opens with a perfectly good sentence saying
+ * what it is about. The card is worth more with that sentence than without it.
+ *
+ * Only ever a fallback. A description the site wrote for the purpose is what it wants shown, and is
+ * always preferred to anything found here.
+ */
+
+/** Below this a paragraph is a caption, a byline or a stray line of chrome rather than a summary. */
+const MIN_LENGTH = 80;
+/** What is kept. This ends up in the note's HTML, so it is bounded rather than left to the page. */
+const MAX_LENGTH = 200;
+/** Above this share of link text a paragraph is a row of navigation, whatever else it looks like. */
+const MAX_LINK_SHARE = 0.5;
+
+/**
+ * Where a page's own writing tends to live. Tried in turn before the document at large, so that a
+ * summary is taken from the article rather than from whatever prose the furniture around it holds.
+ */
+const CONTENT_SCOPES = [
+ "article",
+ "main",
+ "[role=main]",
+ // MediaWiki, which is the case this was written for.
+ "#mw-content-text",
+ "#content",
+ ".post-content",
+ ".entry-content"
+];
+
+/**
+ * Elements whose text is never a description of the page: navigation, furniture, captions, and the
+ * banners that sit above the content.
+ *
+ * Checked by walking up from each paragraph rather than by removing them, because this reads a
+ * document that has already been parsed for the preview's other parts — stripping it here would
+ * take the favicon and icon candidates with it.
+ */
+const IGNORED_ANCESTORS = new Set([
+ "nav", "aside", "header", "footer", "form", "figure", "figcaption", "table", "script", "style", "noscript", "template"
+]);
+
+export function findPageDescription(document: HTMLElement): string | undefined {
+ for (const scope of [ ...CONTENT_SCOPES.map((selector) => document.querySelector(selector)), document ]) {
+ const summary = firstSummaryParagraph(scope);
+
+ if (summary) {
+ return summary;
+ }
+ }
+
+ return undefined;
+}
+
+function firstSummaryParagraph(scope: HTMLElement | null): string | undefined {
+ for (const paragraph of scope?.querySelectorAll("p") ?? []) {
+ const text = collapseWhitespace(paragraph.textContent);
+
+ if (text.length < MIN_LENGTH || hasIgnoredAncestor(paragraph) || isMostlyLinks(paragraph, text)) {
+ continue;
+ }
+
+ return text.length > MAX_LENGTH ? `${text.slice(0, MAX_LENGTH).trimEnd()}…` : text;
+ }
+
+ return undefined;
+}
+
+function collapseWhitespace(text: string): string {
+ return text.replace(/\s+/g, " ").trim();
+}
+
+function hasIgnoredAncestor(element: HTMLElement): boolean {
+ for (let node = element.parentNode; node; node = node.parentNode) {
+ if (IGNORED_ANCESTORS.has(node.rawTagName?.toLowerCase() ?? "")) {
+ return true;
+ }
+ }
+
+ return false;
+}
+
+/**
+ * A cookie notice, a row of breadcrumbs or a footer of policy links can all be long enough to pass
+ * for a summary. What they are not is prose: nearly every word in them is a link.
+ */
+function isMostlyLinks(paragraph: HTMLElement, text: string): boolean {
+ const linked = paragraph.querySelectorAll("a")
+ .reduce((total, anchor) => total + collapseWhitespace(anchor.textContent).length, 0);
+
+ return linked > text.length * MAX_LINK_SHARE;
+}