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
fix(share): leave out unset OpenGraph tags and make the image address absolute
Elian Doran4634fe7c5fa1
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Sharing.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Sharing.htmlindex a12205fa12..3076cb41f5 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Sharing.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Sharing.html@@ -474,6 +474,8 @@ class="admonition note"></table></figure><h3>Customizing OpenGraph</h3>+<p>A meta-property is left out of the page when its attribute is not set.+ Without an image, link previews use a small card.</p><figure class="table"><table><thead>@@ -491,7 +493,9 @@ class="admonition note"><tr><td><code>#shareOpenGraphURL</code></td>- <td>This adjusts the <code>og:url</code> and <code>twitter:url</code> meta-properties.</td>+ <td>This adjusts the <code>og:url</code> and <code>twitter:url</code> meta-properties.+ It is also the address a relative <code>og:image</code> is completed with,+ so it should be the public address of the shared site, such as <code>https://example.com/share/</code>.</td></tr><tr><td><code>#shareOpenGraphDomain</code>@@ -502,9 +506,12 @@ class="admonition note"><td><code>#shareOpenGraphImage</code> <br><code>~shareOpenGraphImage</code></td>- <td>Can be either a label, case in which the value is passed on as-is, or- it can be a relation to an image <a class="reference-link" href="#root/_help_W8vYD3Q1zjCR">File</a>.- This controls the <code>og:image</code> meta-property.</td>+ <td>Can be either a label with the address of an image, or a relation to an+ image <a class="reference-link" href="#root/_help_W8vYD3Q1zjCR">File</a>.+ This controls the <code>og:image</code> meta-property. Sites that show a+ preview of the link load the image from their own servers, so a relative+ address, which the relation always gives, is completed with <code>#shareOpenGraphURL</code>;+ without it, the image does not show in such previews.</td></tr></tbody></table>diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Sharing/Custom share template.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Sharing/Custom share template.htmlindex e885be7971..5d923c8145 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Sharing/Custom share template.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Sharing/Custom share template.html@@ -67,7 +67,8 @@</td><td>The values of the page's <code><head></code>: <code>title</code> (thenote's title, followed by the site's), <code>description</code> (<code>#shareDescription</code>), <code>noIndex</code> (<code>#shareDisallowRobotIndexing</code>)- and <code>openGraph</code> with <code>url</code>, <code>domain</code>, <code>image</code> and <code>color</code>.</td>+ and <code>openGraph</code> with <code>url</code>, <code>domain</code>, <code>image</code>, <code>color</code> and <code>card</code> (<code>summary_large_image</code> with+ an image, <code>summary</code> without). A value whose label is not set is <code>null</code>.</td></tr><tr><td><code>logo</code>diff --git a/docs/User Guide/User Guide/Advanced Usage/Sharing.md b/docs/User Guide/User Guide/Advanced Usage/Sharing.mdindex 461c35e63c..cac46c7d2a 100644--- a/docs/User Guide/User Guide/Advanced Usage/Sharing.md+++ b/docs/User Guide/User Guide/Advanced Usage/Sharing.md@@ -303,12 +303,14 @@ It's possible to adjust the logo which is displayed on the top-left of the left### Customizing OpenGraph+A meta-property is left out of the page when its attribute is not set. Without an image, link previews use a small card.+| Attribute | Description || --- | --- || `#shareOpenGraphColor` | This adjusts the `theme-color` meta-property. |-| `#shareOpenGraphURL` | This adjusts the `og:url` and `twitter:url` meta-properties. |+| `#shareOpenGraphURL` | This adjusts the `og:url` and `twitter:url` meta-properties. It is also the address a relative `og:image` is completed with, so it should be the public address of the shared site, such as `https://example.com/share/`. || `#shareOpenGraphDomain` | Adjusts the `twitter:domain` meta-property. |-| `#shareOpenGraphImage` <br>`~shareOpenGraphImage` | Can be either a label, case in which the value is passed on as-is, or it can be a relation to an image <a class="reference-link" href="../Note%20Types/File.md">File</a>. This controls the `og:image` meta-property. |+| `#shareOpenGraphImage` <br>`~shareOpenGraphImage` | Can be either a label with the address of an image, or a relation to an image <a class="reference-link" href="../Note%20Types/File.md">File</a>. This controls the `og:image` meta-property. Sites that show a preview of the link load the image from their own servers, so a relative address, which the relation always gives, is completed with `#shareOpenGraphURL`; without it, the image does not show in such previews. |## Creditsdiff --git a/docs/User Guide/User Guide/Advanced Usage/Sharing/Custom share template.md b/docs/User Guide/User Guide/Advanced Usage/Sharing/Custom share template.mdindex bc05512710..b86031df26 100644--- a/docs/User Guide/User Guide/Advanced Usage/Sharing/Custom share template.md+++ b/docs/User Guide/User Guide/Advanced Usage/Sharing/Custom share template.md@@ -30,7 +30,7 @@ Your template is rendered with a context object exposing the note and its render| `content` | The note's already-rendered HTML content, as a string. || `header` | Extra HTML to place in the document head for this note (used by some note types). || `isEmpty` | `true` when the note has no content of its own. |-| `head` | The values of the page's `<head>`: `title` (the note's title, followed by the site's), `description` (`#shareDescription`), `noIndex` (`#shareDisallowRobotIndexing`) and `openGraph` with `url`, `domain`, `image` and `color`. |+| `head` | The values of the page's `<head>`: `title` (the note's title, followed by the site's), `description` (`#shareDescription`), `noIndex` (`#shareDisallowRobotIndexing`) and `openGraph` with `url`, `domain`, `image`, `color` and `card` (`summary_large_image` with an image, `summary` without). A value whose label is not set is `null`. || `logo` | The site logo in the header: `href` (`#shareRootLink`, otherwise the site's root page), `width` and `height`. || `navigation` | The navigation tree of the site: its visible pages, each with `title`, `href`, `isExternal`, `type`, `icon`, `isActive` (the page being shown), `isExpanded` (that page or one of its ancestors) and `children`. || `childLinks` | The links to the note's visible children, each with `title`, `href`, `isExternal` and `type`. |diff --git a/packages/share-theme/src/model/page.spec.ts b/packages/share-theme/src/model/page.spec.tsindex 246b59e397..77dce7815f 100644--- a/packages/share-theme/src/model/page.spec.ts+++ b/packages/share-theme/src/model/page.spec.ts@@ -31,7 +31,8 @@ describe("getPageHead", () => {url: "https://example.com",domain: "example.com",image: "https://example.com/cover.png",- color: "#123456"+ color: "#123456",+ card: "summary_large_image"}});});@@ -52,10 +53,46 @@ describe("getPageHead", () => {url: null,domain: null,image: "api/images/imageNote/image.png",- color: null+ color: null,+ card: "summary_large_image"}});});++ it("makes a relative image address absolute against #shareOpenGraphURL", () => {+ const image = (labels: Record<string, string>, relations: Record<string, string> = {}) => {+ const site = fakeNote({+ noteId: "site",+ labels: { shareOpenGraphURL: "https://example.com/share/site", ...labels },+ relations+ });+ return getPageHead(site, site).openGraph.image;+ };++ expect(image({}, { shareOpenGraphImage: "imageNote" }))+ .toBe("https://example.com/share/api/images/imageNote/image.png");+ expect(image({ shareOpenGraphImage: "cover.png" })).toBe("https://example.com/share/cover.png");+ expect(image({ shareOpenGraphImage: "https://cdn.example.com" })).toBe("https://cdn.example.com");+ expect(image({ shareOpenGraphImage: "cover.png", shareOpenGraphURL: "not a URL" })).toBe("cover.png");+ });++ it("leaves out the values whose labels are blank, and uses a small card without an image", () => {+ const site = fakeNote({+ noteId: "site",+ labels: {+ shareDescription: " ",+ shareOpenGraphURL: "",+ shareOpenGraphDomain: "",+ shareOpenGraphImage: " ",+ shareOpenGraphColor: ""+ }+ });++ expect(getPageHead(site, site)).toMatchObject({+ description: null,+ openGraph: { url: null, domain: null, image: null, color: null, card: "summary" }+ });+ });});describe("getHtmlSnippets", () => {diff --git a/packages/share-theme/src/model/page.ts b/packages/share-theme/src/model/page.tsindex 6b4f265a41..02ef38b6c1 100644--- a/packages/share-theme/src/model/page.ts+++ b/packages/share-theme/src/model/page.ts@@ -50,14 +50,18 @@ export interface PageLink {export interface PageHead {/** The note's title, followed by the site's unless the note is the site's root. */title: string;- description: string | null | undefined;+ /** `#shareDescription`; this and the other values are `null` when their label is blank. */+ description: string | null;/** Whether search engines are asked not to index the page (`#shareDisallowRobotIndexing`). */noIndex: boolean;openGraph: {- url: string | null | undefined;- domain: string | null | undefined;- image: string | null | undefined;- color: string | null | undefined;+ url: string | null;+ domain: string | null;+ /** Absolute when `url` is set and is a valid address, relative to the page otherwise. */+ image: string | null;+ color: string | null;+ /** The kind of Twitter card: a large picture when there is an image. */+ card: "summary_large_image" | "summary";};}@@ -69,7 +73,7 @@ export interface SiteLogo {height: number;}-/** A heading of the page's content, as core's `anchorHeadings()` finds it. */+/** A heading of the page's content, as core's `preparePageContent()` finds it. */export interface PageHeading {/** 1 for `<h1>`, up to 6 for `<h6>`. */level: number;@@ -90,29 +94,46 @@ export type HtmlSnippetLocation =/*** Returns the `<head>` values of the page of `note`, whose site starts at `siteRoot`. The- * OpenGraph values come from the site root, so that every page of a site shares them.+ * OpenGraph values come from the site root, so that every page of a site shares them. Sites that+ * show a link preview load the image from their own servers, so a relative image address is made+ * absolute against `#shareOpenGraphURL`, the only public address of the site Trilium knows.*/export function getPageHead(note: ShareNote, siteRoot: ShareNote): PageHead {const title = note.noteId === siteRoot.noteId? note.title: `${note.title} - ${siteRoot.title}`;+ const url = readLabel(siteRoot, "shareOpenGraphURL");const image = siteRoot.hasRelation("shareOpenGraphImage")? `api/images/${siteRoot.getRelationValue("shareOpenGraphImage")}/image.png`- : siteRoot.getLabelValue("shareOpenGraphImage");+ : readLabel(siteRoot, "shareOpenGraphImage");return {title,- description: note.getLabelValue("shareDescription"),+ description: readLabel(note, "shareDescription"),noIndex: note.hasLabel("shareDisallowRobotIndexing"),openGraph: {- url: siteRoot.getLabelValue("shareOpenGraphURL"),- domain: siteRoot.getLabelValue("shareOpenGraphDomain"),- image,- color: siteRoot.getLabelValue("shareOpenGraphColor")+ url,+ domain: readLabel(siteRoot, "shareOpenGraphDomain"),+ image: image && url ? toAbsoluteUrl(image, url) : image,+ color: readLabel(siteRoot, "shareOpenGraphColor"),+ card: image ? "summary_large_image" : "summary"}};}+/** Returns the trimmed value of the label, or `null` when it is missing or blank. */+function readLabel(note: ShareNote, name: string) {+ return note.getLabelValue(name)?.trim() || null;+}++/** Resolves `address` against `base` unless it is already absolute or `base` is not a URL. */+function toAbsoluteUrl(address: string, base: string) {+ if (URL.canParse(address) || !URL.canParse(base)) {+ return address;+ }+ return new URL(address, base).href;+}+/*** Returns the HTML of the `~shareHtml` snippets of `note`, joined per location. A snippet goes to* `#shareHtmlLocation`, `content:end` without one, and to the end of a location named without adiff --git a/packages/share-theme/src/templates/page.ejs b/packages/share-theme/src/templates/page.ejsindex 9549048f8a..82ef27856f 100644--- a/packages/share-theme/src/templates/page.ejs+++ b/packages/share-theme/src/templates/page.ejs@@ -18,23 +18,38 @@<% } %><title><%= head.title %></title><%- include("boot_script") %>- <!-- HTML Meta Tags -->- <meta name="description" content="<%= head.description %>">- <!-- Facebook Meta Tags -->- <meta property="og:url" content="<%= head.openGraph.url %>">+ <% const { description, openGraph } = head; %>+ <% if (description) { %>+ <meta name="description" content="<%= description %>">+ <% } %><meta property="og:type" content="website"><meta property="og:title" content="<%= head.title %>">- <meta property="og:description" content="<%= head.description %>">- <meta property="og:image" content="<%= head.openGraph.image %>">- <!-- Twitter Meta Tags -->- <meta name="twitter:card" content="summary_large_image">- <meta property="twitter:domain" content="<%= head.openGraph.domain %>">- <meta property="twitter:url" content="<%= head.openGraph.url %>">+ <% if (description) { %>+ <meta property="og:description" content="<%= description %>">+ <% } %>+ <% if (openGraph.url) { %>+ <meta property="og:url" content="<%= openGraph.url %>">+ <% } %>+ <% if (openGraph.image) { %>+ <meta property="og:image" content="<%= openGraph.image %>">+ <% } %>+ <meta name="twitter:card" content="<%= openGraph.card %>"><meta name="twitter:title" content="<%= head.title %>">- <meta name="twitter:description" content="<%= head.description %>">- <meta name="twitter:image" content="<%= head.openGraph.image %>">- <!-- Meta Tags Generated via https://opengraph.dev -->- <meta name="theme-color" content="<%= head.openGraph.color %>">+ <% if (description) { %>+ <meta name="twitter:description" content="<%= description %>">+ <% } %>+ <% if (openGraph.domain) { %>+ <meta property="twitter:domain" content="<%= openGraph.domain %>">+ <% } %>+ <% if (openGraph.url) { %>+ <meta property="twitter:url" content="<%= openGraph.url %>">+ <% } %>+ <% if (openGraph.image) { %>+ <meta name="twitter:image" content="<%= openGraph.image %>">+ <% } %>+ <% if (openGraph.color) { %>+ <meta name="theme-color" content="<%= openGraph.color %>">+ <% } %><style id="trilium-icon-packs"><%- utils.escapeInlineStylesheet(iconPackCss) %></style>diff --git a/packages/trilium-core/src/share/content_renderer.spec.ts b/packages/trilium-core/src/share/content_renderer.spec.tsindex 6fe05ee0cd..261d726afc 100644--- a/packages/trilium-core/src/share/content_renderer.spec.ts+++ b/packages/trilium-core/src/share/content_renderer.spec.ts@@ -362,6 +362,41 @@ describe("content_renderer", () => {]);});+ it("prints only the OpenGraph tags that have a value, with an absolute image", () => {+ const shareRootNote = buildShareNote({+ id: shareRoot.SHARE_ROOT_NOTE_ID,+ children: [+ { id: "plainSite", title: "Plain", content: "<p>a</p>" },+ {+ "id": "previewSite",+ "title": "Preview",+ "content": "<p>b</p>",+ "#shareOpenGraphURL": "https://example.com/share/previewSite",+ "~shareOpenGraphImage": "plainSite"+ }+ ]+ });+ const [ plainSite, previewSite ] = shareRootNote.getChildNotes();+ const metaTags = (note: SNote) => parse(String(renderNoteContent(note)))+ .querySelectorAll("head meta[content]")+ .map((meta) => [ meta.getAttribute("property") ?? meta.getAttribute("name"),+ meta.getAttribute("content") ])+ .filter(([ name ]) => name !== "viewport");++ expect(metaTags(plainSite).filter(([ , content ]) => !content)).toStrictEqual([]);+ expect(metaTags(plainSite)).toStrictEqual([+ [ "og:type", "website" ],+ [ "og:title", "Plain" ],+ [ "twitter:card", "summary" ],+ [ "twitter:title", "Plain" ]+ ]);+ expect(metaTags(previewSite)).toEqual(expect.arrayContaining([+ [ "og:url", "https://example.com/share/previewSite" ],+ [ "og:image", "https://example.com/share/api/images/plainSite/image.png" ],+ [ "twitter:card", "summary_large_image" ]+ ]));+ });+it("keeps the alt text of an image on the page", () => {const shareRootNote = buildShareNote({id: shareRoot.SHARE_ROOT_NOTE_ID,