Skip to content

Build your personal knowledge base with Trilium Notes

refactor(share): work out the page head before the template runs

Elian Doran122dcedb5c6b
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.html
index 2baa3962f5..446e289dab 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
@@ -62,6 +62,20 @@
</td>
<td><code>true</code> when the note has no content of its own.</td>
</tr>
+ <tr>
+ <td><code>head</code>
+ </td>
+ <td>The values of the page's <code>&lt;head&gt;</code>: <code>title</code> (the
+ note'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>
+ </tr>
+ <tr>
+ <td><code>snippets</code>
+ </td>
+ <td>The HTML of the <code>~shareHtml</code> snippets for each location, such
+ as <code>snippets["head:end"]</code>. Every location is present, empty when
+ no snippet goes there.</td>
+ </tr>
<tr>
<td><code>subRoot</code>
</td>
diff --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.md
index d3c2c09449..49a05a41b4 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,6 +30,8 @@ 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`. |
+| `snippets` | The HTML of the `~shareHtml` snippets for each location, such as `snippets["head:end"]`. Every location is present, empty when no snippet goes there. |
| `subRoot` | The root of the shared subtree as `{ note, branch }` — handy for a site-wide title or logo. |
| `cssToLoad` / `jsToLoad` | Arrays of stylesheet / script URLs the default theme would inject (includes anything added via `~shareCss` / `~shareJs`). |
| `faviconUrl` / `logoUrl` | Resolved favicon and logo URLs. |
diff --git a/packages/share-theme/package.json b/packages/share-theme/package.json
index 7980e9ad4c..ae143126d7 100644
--- a/packages/share-theme/package.json
+++ b/packages/share-theme/package.json
@@ -11,6 +11,7 @@
},
"exports": {
"./templates/*": "./src/templates/*",
+ "./model/*": "./src/model/*.ts",
"./*": "./dist/*"
},
"author": "Elian Doran <[email protected]>",
diff --git a/packages/share-theme/src/model/page.spec.ts b/packages/share-theme/src/model/page.spec.ts
new file mode 100644
index 0000000000..47042c57ad
--- /dev/null
+++ b/packages/share-theme/src/model/page.spec.ts
@@ -0,0 +1,109 @@
+import { describe, expect, it } from "vitest";
+
+import { getHtmlSnippets, getPageHead, type ShareNote } from "./page.js";
+
+describe("getPageHead", () => {
+ it("titles a page after the note and its site, and reads the site's OpenGraph labels", () => {
+ const site = fakeNote({
+ noteId: "site",
+ title: "My site",
+ labels: {
+ shareOpenGraphColor: "#123456",
+ shareOpenGraphURL: "https://example.com",
+ shareOpenGraphDomain: "example.com",
+ shareOpenGraphImage: "https://example.com/cover.png"
+ }
+ });
+ const page = fakeNote({
+ noteId: "page",
+ title: "Page",
+ labels: { shareDescription: "About the page", shareDisallowRobotIndexing: "" }
+ });
+
+ expect(getPageHead(page, site)).toStrictEqual({
+ title: "Page - My site",
+ description: "About the page",
+ noIndex: true,
+ openGraph: {
+ url: "https://example.com",
+ domain: "example.com",
+ image: "https://example.com/cover.png",
+ color: "#123456"
+ }
+ });
+ });
+
+ it("titles the site's own page after it alone and prefers an image relation to the label", () => {
+ const site = fakeNote({
+ noteId: "site",
+ title: "My site",
+ labels: { shareOpenGraphImage: "https://example.com/cover.png" },
+ relations: { shareOpenGraphImage: "imageNote" }
+ });
+
+ expect(getPageHead(site, site)).toStrictEqual({
+ title: "My site",
+ description: null,
+ noIndex: false,
+ openGraph: {
+ url: null,
+ domain: null,
+ image: "api/images/imageNote/image.png",
+ color: null
+ }
+ });
+ });
+});
+
+describe("getHtmlSnippets", () => {
+ it("joins the snippets of each location, at the end of the content by default", () => {
+ const page = fakeNote({
+ noteId: "page",
+ snippets: [
+ fakeNote({ noteId: "a", content: "<meta a>", labels: { shareHtmlLocation: "head" } }),
+ fakeNote({ noteId: "b", content: "<p>b</p>" }),
+ fakeNote({ noteId: "c", content: "<meta c>", labels: { shareHtmlLocation: "head:end" } }),
+ fakeNote({ noteId: "d", content: "<p>d</p>", labels: { shareHtmlLocation: "body:start" } }),
+ null
+ ]
+ });
+
+ expect(getHtmlSnippets(page)).toStrictEqual({
+ "head:start": "",
+ "head:end": "<meta a>\n<meta c>",
+ "body:start": "<p>d</p>",
+ "body:end": "",
+ "content:start": "",
+ "content:end": "<p>b</p>"
+ });
+ });
+
+ it("leaves every location empty without snippets", () => {
+ expect(Object.values(getHtmlSnippets(fakeNote({ noteId: "page" }))).join("")).toBe("");
+ });
+});
+
+interface FakeNoteOptions {
+ noteId: string;
+ title?: string;
+ labels?: Record<string, string>;
+ relations?: Record<string, string>;
+ snippets?: (ShareNote | null)[];
+ content?: string;
+}
+
+function fakeNote(options: FakeNoteOptions): ShareNote {
+ const labels = options.labels ?? {};
+ const relations = options.relations ?? {};
+ return {
+ noteId: options.noteId,
+ title: options.title ?? options.noteId,
+ getLabelValue: (name) => labels[name] ?? null,
+ hasLabel: (name) => name in labels,
+ getRelationValue: (name) => relations[name] ?? null,
+ hasRelation: (name) => name in relations,
+ getRelations: (name) => (name === "shareHtml" ? options.snippets ?? [] : [])
+ .map((targetNote) => ({ targetNote })),
+ getContent: () => options.content ?? ""
+ };
+}
diff --git a/packages/share-theme/src/model/page.ts b/packages/share-theme/src/model/page.ts
new file mode 100644
index 0000000000..6640aaec2a
--- /dev/null
+++ b/packages/share-theme/src/model/page.ts
@@ -0,0 +1,93 @@
+/**
+ * The values `page.ejs` prints, worked out from the note before the template runs. Custom
+ * `~shareTemplate` templates receive them too.
+ */
+
+/** The parts of a note the page model reads; core's `SNote` and `BNote` both provide them. */
+export interface ShareNote {
+ noteId: string;
+ title: string;
+ getLabelValue(name: string): string | null | undefined;
+ hasLabel(name: string): boolean;
+ getRelationValue(name: string): string | null | undefined;
+ hasRelation(name: string): boolean;
+ getRelations(name: string): { targetNote?: ShareNote | null }[];
+ getContent(): string | Uint8Array | null | undefined;
+}
+
+/** What goes into the `<head>` of a shared page, besides the stylesheets and scripts. */
+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;
+ /** 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;
+ };
+}
+
+/** Where an HTML snippet can go, as `#shareHtmlLocation` names it. */
+export type HtmlSnippetLocation =
+ `${"head" | "body" | "content"}:${"start" | "end"}`;
+
+/**
+ * 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.
+ */
+export function getPageHead(note: ShareNote, siteRoot: ShareNote): PageHead {
+ const title = note.noteId === siteRoot.noteId
+ ? note.title
+ : `${note.title} - ${siteRoot.title}`;
+ const image = siteRoot.hasRelation("shareOpenGraphImage")
+ ? `api/images/${siteRoot.getRelationValue("shareOpenGraphImage")}/image.png`
+ : siteRoot.getLabelValue("shareOpenGraphImage");
+
+ return {
+ title,
+ description: note.getLabelValue("shareDescription"),
+ noIndex: note.hasLabel("shareDisallowRobotIndexing"),
+ openGraph: {
+ url: siteRoot.getLabelValue("shareOpenGraphURL"),
+ domain: siteRoot.getLabelValue("shareOpenGraphDomain"),
+ image,
+ color: siteRoot.getLabelValue("shareOpenGraphColor")
+ }
+ };
+}
+
+/**
+ * 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 a
+ * position. Every location is present, empty when no snippet goes there.
+ */
+export function getHtmlSnippets(note: ShareNote): Record<HtmlSnippetLocation, string> {
+ const snippets: Record<string, string[]> = {
+ "head:start": [],
+ "head:end": [],
+ "body:start": [],
+ "body:end": [],
+ "content:start": [],
+ "content:end": []
+ };
+
+ for (const { targetNote } of note.getRelations("shareHtml")) {
+ if (!targetNote) {
+ continue;
+ }
+
+ let location = targetNote.getLabelValue("shareHtmlLocation") || "content:end";
+ if (!location.includes(":")) {
+ location = `${location}:end`;
+ }
+ const content = targetNote.getContent();
+ (snippets[location] ??= []).push(typeof content === "string" ? content : "");
+ }
+
+ return Object.fromEntries(Object.entries(snippets)
+ .map(([ location, contents ]) => [ location, contents.join("\n") ])
+ ) as Record<HtmlSnippetLocation, string>;
+}
diff --git a/packages/share-theme/src/templates/page.ejs b/packages/share-theme/src/templates/page.ejs
index b31326f9f4..fe3963360f 100644
--- a/packages/share-theme/src/templates/page.ejs
+++ b/packages/share-theme/src/templates/page.ejs
@@ -1,31 +1,8 @@
<!DOCTYPE html>
<html lang="en">
<head>
- <%
- const hasTree = subRoot.note.hasVisibleChildren();
-
- // Collect HTML snippets by location
- const htmlSnippetsByLocation = {};
- for (const htmlRelation of note.getRelations("shareHtml")) {
- const htmlNote = htmlRelation.targetNote;
- if (htmlNote) {
- let location = htmlNote.getLabelValue("shareHtmlLocation") || "content:end";
- // Default to :end if no position specified
- if (!location.includes(":")) {
- location = location + ":end";
- }
- if (!htmlSnippetsByLocation[location]) {
- htmlSnippetsByLocation[location] = [];
- }
- htmlSnippetsByLocation[location].push(htmlNote.getContent());
- }
- }
- const renderSnippets = (location) => {
- const snippets = htmlSnippetsByLocation[location];
- return snippets ? snippets.join("\n") : "";
- };
- %>
- <%- renderSnippets("head:start") %>
+ <% const hasTree = subRoot.note.hasVisibleChildren(); %>
+ <%- snippets["head:start"] %>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
@@ -36,24 +13,10 @@
<% for (const url of jsToLoad) { %>
<script type="module" src="<%= url %>"></script>
<% } %>
- <% if (note.hasLabel("shareDisallowRobotIndexing")) { %>
+ <% if (head.noIndex) { %>
<meta name="robots" content="noindex,follow" />
<% } %>
-
- <%
- const pageTitle = `${note.title}${note.noteId !== subRoot.note.noteId ? ` - ${subRoot.note.title}` : ""}`;
-
- // Setup some key OpenGraph variables
- const openGraphColor = subRoot.note.getLabelValue("shareOpenGraphColor");
- const openGraphURL = subRoot.note.getLabelValue("shareOpenGraphURL");
- const openGraphDomain = subRoot.note.getLabelValue("shareOpenGraphDomain");
- let openGraphImage = subRoot.note.getLabelValue("shareOpenGraphImage");
- // Relation takes priority and requires some altering
- if (subRoot.note.hasRelation("shareOpenGraphImage")) {
- openGraphImage = `api/images/${subRoot.note.getRelation("shareOpenGraphImage").value}/image.png`;
- }
- %>
- <title><%= pageTitle %></title>
+ <title><%= head.title %></title>
<script>
// Load dark/light theme as soon as possible to avoid color flashes.
let theme = localStorage.getItem("theme");
@@ -75,26 +38,26 @@
})();
</script>
<!-- HTML Meta Tags -->
- <meta name="description" content="<%= note.getLabelValue("shareDescription") %>">
+ <meta name="description" content="<%= head.description %>">
<!-- Facebook Meta Tags -->
- <meta property="og:url" content="<%= openGraphURL %>">
+ <meta property="og:url" content="<%= head.openGraph.url %>">
<meta property="og:type" content="website">
- <meta property="og:title" content="<%= pageTitle %>">
- <meta property="og:description" content="<%= note.getLabelValue("shareDescription") %>">
- <meta property="og:image" content="<%= openGraphImage %>">
+ <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="<%= openGraphDomain %>">
- <meta property="twitter:url" content="<%= openGraphURL %>">
- <meta name="twitter:title" content="<%= pageTitle %>">
- <meta name="twitter:description" content="<%= note.getLabelValue("shareDescription") %>">
- <meta name="twitter:image" content="<%= openGraphImage %>">
+ <meta property="twitter:domain" content="<%= head.openGraph.domain %>">
+ <meta property="twitter:url" content="<%= head.openGraph.url %>">
+ <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="<%= openGraphColor %>">
+ <meta name="theme-color" content="<%= head.openGraph.color %>">
<style id="trilium-icon-packs">
<%- utils.escapeInlineStylesheet(iconPackCss) %>
</style>
- <%- renderSnippets("head:end") %>
+ <%- snippets["head:end"] %>
</head>
<%
const logoWidth = subRoot.note.getLabelValue("shareLogoWidth") ?? 53;
@@ -114,7 +77,7 @@ content = content.replaceAll(headingRe, (...match) => {
});
%>
<body data-note-id="<%= note.noteId %>" class="type-<%= note.type %>" data-ancestor-note-id="<%= subRoot.note.noteId %>">
-<%- renderSnippets("body:start") %>
+<%- snippets["body:start"] %>
<div id="header">
<button aria-label="<%= t("share_theme.toggle-navigation") %>" id="left-pane-toggle-button" class="header-button"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="currentColor"><path d="M4 6h16v2H4zm0 5h16v2H4zm0 5h16v2H4z"></path></svg></button>
<a href="<%= shareRootLink %>" id="header-logo">
@@ -161,7 +124,7 @@ content = content.replaceAll(headingRe, (...match) => {
<div id="right-pane">
<div id="main">
<div id="content" class="type-<%= note.type %><% if (note.type === "text" || (note.type === "code" && note.mime === "text/x-markdown")) { %> ck-content<% } %><% if (isEmpty) { %> no-content<% } %>" data-tab-title-placeholder="<%= t("share_theme.tab-title") %>">
- <%- renderSnippets("content:start") %>
+ <%- snippets["content:start"] %>
<h1 id="title"><%= note.title %></h1>
<% if (isEmpty && (!note.hasVisibleChildren() && note.type !== "book")) { %>
<p><%= t("share_page.no-content") %></p>
@@ -171,7 +134,7 @@ content = content.replaceAll(headingRe, (...match) => {
%>
<%- content %>
<% } %>
- <%- renderSnippets("content:end") %>
+ <%- snippets["content:end"] %>
</div>
<% if (note.hasVisibleChildren() || note.type === "book") { %>
@@ -249,6 +212,6 @@ content = content.replaceAll(headingRe, (...match) => {
</div>
</div>
<div id="mobile-backdrop"></div>
-<%- renderSnippets("body:end") %>
+<%- snippets["body:end"] %>
</body>
</html>
diff --git a/packages/trilium-core/package.json b/packages/trilium-core/package.json
index 5ebbb06ec1..b11712e749 100644
--- a/packages/trilium-core/package.json
+++ b/packages/trilium-core/package.json
@@ -15,6 +15,7 @@
"@braintree/sanitize-url": "7.1.2",
"@triliumnext/commons": "workspace:*",
"@triliumnext/highlightjs": "workspace:*",
+ "@triliumnext/share-theme": "workspace:*",
"@triliumnext/turndown-plugin-gfm": "workspace:*",
"ai": "7.0.128",
"async-mutex": "0.5.0",
diff --git a/packages/trilium-core/src/share/content_renderer.spec.ts b/packages/trilium-core/src/share/content_renderer.spec.ts
index 6215a65cc9..3876eba545 100644
--- a/packages/trilium-core/src/share/content_renderer.spec.ts
+++ b/packages/trilium-core/src/share/content_renderer.spec.ts
@@ -1,4 +1,5 @@
import { trimIndentation } from "@triliumnext/commons";
+import { getHtmlSnippets, getPageHead } from "@triliumnext/share-theme/model/page";
import ejs from "ejs";
import { parse } from "node-html-parser";
import { describe, expect, it, vi } from "vitest";
@@ -1095,7 +1096,9 @@ describe("content_renderer", () => {
isStatic: false,
faviconUrl: "",
iconPackCss: "",
- iconPackSupportedPrefixes: []
+ iconPackSupportedPrefixes: [],
+ head: getPageHead(note, note),
+ snippets: getHtmlSnippets(note)
}, {
includer: (path: string) => ({
template: readShareTemplate(path)
diff --git a/packages/trilium-core/src/share/content_renderer.ts b/packages/trilium-core/src/share/content_renderer.ts
index 657f3fd855..4c822612e6 100644
--- a/packages/trilium-core/src/share/content_renderer.ts
+++ b/packages/trilium-core/src/share/content_renderer.ts
@@ -7,6 +7,7 @@ import {
import { renderToHtml as renderMarkdownToHtml } from "@triliumnext/commons/src/lib/markdown_renderer.js";
import { renderSpreadsheetToHtml } from "@triliumnext/commons/src/lib/spreadsheet/render_to_html.js";
import { getLanguage, highlight, highlightAuto, syncMimeTypes } from "@triliumnext/highlightjs";
+import { getHtmlSnippets, getPageHead } from "@triliumnext/share-theme/model/page";
import ejs from "ejs";
import escapeHtml from "escape-html";
import { t } from "i18next";
@@ -224,6 +225,8 @@ function renderNoteContentInternal(note: SNote | BNote, renderArgs: RenderArgs)
isDev: utils.isDev(),
utils,
sanitizeUrl: sanitize.sanitizeUrl,
+ head: getPageHead(note, renderArgs.subRoot.note ?? note),
+ snippets: getHtmlSnippets(note),
...renderArgs,
};
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index e870add809..67c70cc70a 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1430,6 +1430,9 @@ importers:
'@triliumnext/highlightjs':
specifier: workspace:*
version: link:../highlightjs
+ '@triliumnext/share-theme':
+ specifier: workspace:*
+ version: link:../share-theme
'@triliumnext/turndown-plugin-gfm':
specifier: workspace:*
version: link:../turndown-plugin-gfm