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
refactor(share): work out the site logo before the template runs
Elian Doran5fa8df15883c
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 36a731b1d1..2f88c479aa 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@@ -454,12 +454,15 @@ class="admonition note"><tr><td><code>#shareLogoWidth</code></td>- <td>The width (in pixels, without unit) to set for the logo. Default is <code>53</code>.</td>+ <td>The width of the logo, as a number without unit. With <code>#shareLogoHeight</code>,+ it sets the proportions of the logo, which is shown 32 pixels wide. Default+ is <code>53</code>.</td></tr><tr><td><code>#shareLogoHeight</code></td>- <td>The height (in pixels, without unit) to set for the logo. Default is <code>40</code>.</td>+ <td>The height of the logo, as a number without unit. With <code>#shareLogoWidth</code>,+ it sets the proportions of the logo. Default is <code>40</code>.</td></tr><tr><td><code>#shareRootLink</code>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 446e289dab..c111c6e316 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@@ -69,6 +69,12 @@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>logo</code>+ </td>+ <td>The site logo in the header: <code>href</code> (<code>#shareRootLink</code>,+ otherwise the site's root page), <code>width</code> and <code>height</code>.</td>+ </tr><tr><td><code>snippets</code></td>diff --git a/docs/User Guide/User Guide/Advanced Usage/Sharing.md b/docs/User Guide/User Guide/Advanced Usage/Sharing.mdindex 45a6ea926f..c5c1a68e32 100644--- a/docs/User Guide/User Guide/Advanced Usage/Sharing.md+++ b/docs/User Guide/User Guide/Advanced Usage/Sharing.md@@ -296,8 +296,8 @@ It's possible to adjust the logo which is displayed on the top-left of the left| Attribute | Description || --- | --- || `~shareLogo` | Relation set to an image to use as logo. The image must be part of the share tree (it can be hidden if needed). |-| `#shareLogoWidth` | The width (in pixels, without unit) to set for the logo. Default is `53`. |-| `#shareLogoHeight` | The height (in pixels, without unit) to set for the logo. Default is `40`. |+| `#shareLogoWidth` | The width of the logo, as a number without unit. With `#shareLogoHeight`, it sets the proportions of the logo, which is shown 32 pixels wide. Default is `53`. |+| `#shareLogoHeight` | The height of the logo, as a number without unit. With `#shareLogoWidth`, it sets the proportions of the logo. Default is `40`. || `#shareRootLink` | URL to navigate to when the logo is pressed. |### Customizing OpenGraphdiff --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 49a05a41b4..163d61a140 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@@ -31,6 +31,7 @@ Your template is rendered with a context object exposing the note and its render| `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`. |+| `logo` | The site logo in the header: `href` (`#shareRootLink`, otherwise the site's root page), `width` and `height`. || `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`). |diff --git a/packages/share-theme/src/model/page.spec.ts b/packages/share-theme/src/model/page.spec.tsindex 47042c57ad..dc47a4d2cb 100644--- a/packages/share-theme/src/model/page.spec.ts+++ b/packages/share-theme/src/model/page.spec.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";-import { getHtmlSnippets, getPageHead, type ShareNote } from "./page.js";+import { getHtmlSnippets, getPageHead, getSiteLogo, type ShareNote } from "./page.js";describe("getPageHead", () => {it("titles a page after the note and its site, and reads the site's OpenGraph labels", () => {@@ -83,6 +83,28 @@ describe("getHtmlSnippets", () => {});});+describe("getSiteLogo", () => {+ const sanitizeUrl = (url: string) => (url.startsWith("javascript:") ? "about:blank" : url);++ it("draws the logo 32 pixels wide, in the proportions of its labels", () => {+ const logo = (labels: Record<string, string>) =>+ getSiteLogo(fakeNote({ noteId: "site", labels }), sanitizeUrl);++ expect(logo({})).toStrictEqual({ href: "./site-alias", width: 32, height: 24 });+ expect(logo({ shareLogoWidth: "100", shareLogoHeight: "50" }).height).toBe(16);+ expect(logo({ shareLogoWidth: "auto", shareLogoHeight: "" }).height).toBe(24);+ expect(logo({ shareLogoWidth: "0", shareLogoHeight: "-5" }).height).toBe(24);+ });++ it("links to #shareRootLink, made safe", () => {+ const logo = (shareRootLink: string) => getSiteLogo(+ fakeNote({ noteId: "site", labels: { shareRootLink } }), sanitizeUrl);++ expect(logo("https://example.com").href).toBe("https://example.com");+ expect(logo("javascript:alert(1)").href).toBe("about:blank");+ });+});+interface FakeNoteOptions {noteId: string;title?: string;@@ -97,6 +119,7 @@ function fakeNote(options: FakeNoteOptions): ShareNote {const relations = options.relations ?? {};return {noteId: options.noteId,+ shareId: `${options.noteId}-alias`,title: options.title ?? options.noteId,getLabelValue: (name) => labels[name] ?? null,hasLabel: (name) => name in labels,diff --git a/packages/share-theme/src/model/page.ts b/packages/share-theme/src/model/page.tsindex 6640aaec2a..29e141e869 100644--- a/packages/share-theme/src/model/page.ts+++ b/packages/share-theme/src/model/page.ts@@ -6,6 +6,7 @@/** The parts of a note the page model reads; core's `SNote` and `BNote` both provide them. */export interface ShareNote {noteId: string;+ shareId: string;title: string;getLabelValue(name: string): string | null | undefined;hasLabel(name: string): boolean;@@ -30,6 +31,14 @@ export interface PageHead {};}+/** The site logo in the page header. */+export interface SiteLogo {+ /** `#shareRootLink` when set, otherwise the site's root page. */+ href: string;+ width: number;+ height: number;+}+/** Where an HTML snippet can go, as `#shareHtmlLocation` names it. */export type HtmlSnippetLocation =`${"head" | "body" | "content"}:${"start" | "end"}`;@@ -91,3 +100,28 @@ export function getHtmlSnippets(note: ShareNote): Record<HtmlSnippetLocation, st.map(([ location, contents ]) => [ location, contents.join("\n") ])) as Record<HtmlSnippetLocation, string>;}++/** The width the header draws the site logo at, in pixels. */+const LOGO_WIDTH = 32;++/**+ * Returns the site logo of the site starting at `siteRoot`. `#shareLogoWidth` and+ * `#shareLogoHeight` give the logo's proportions; a label that is not a positive number falls back+ * to the default logo's. `sanitizeUrl` makes `#shareRootLink` safe to use as a link.+ */+export function getSiteLogo(siteRoot: ShareNote, sanitizeUrl: (url: string) => string): SiteLogo {+ const width = readPositiveNumber(siteRoot.getLabelValue("shareLogoWidth")) ?? 53;+ const height = readPositiveNumber(siteRoot.getLabelValue("shareLogoHeight")) ?? 40;+ const rootLink = siteRoot.getLabelValue("shareRootLink");++ return {+ href: rootLink ? sanitizeUrl(rootLink) : `./${siteRoot.shareId}`,+ width: LOGO_WIDTH,+ height: Math.round(LOGO_WIDTH * height / width)+ };+}++function readPositiveNumber(value: string | null | undefined) {+ const number = Number(value);+ return value && number > 0 ? number : undefined;+}diff --git a/packages/share-theme/src/templates/page.ejs b/packages/share-theme/src/templates/page.ejsindex c7233953e7..7b3704f568 100644--- a/packages/share-theme/src/templates/page.ejs+++ b/packages/share-theme/src/templates/page.ejs@@ -41,10 +41,6 @@<%- snippets["head:end"] %></head><%-const logoWidth = subRoot.note.getLabelValue("shareLogoWidth") ?? 53;-const logoHeight = subRoot.note.getLabelValue("shareLogoHeight") ?? 40;-const mobileLogoHeight = logoHeight && logoWidth ? 32 / (logoWidth / logoHeight) : "";-const shareRootLink = subRoot.note.hasLabel("shareRootLink") ? sanitizeUrl(subRoot.note.getLabelValue("shareRootLink") ?? "") : `./${subRoot.note.noteId}`;const headingRe = /(<h[1-6](?:\s[^>]*)?>)(.+?)(<\/h[1-6]>)/g;const headingMatches = [...content.matchAll(headingRe)];// Unique slug per heading (in document order) so duplicate titles get distinct@@ -61,8 +57,8 @@ content = content.replaceAll(headingRe, (...match) => {<%- 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">- <img src="<%= logoUrl %>" width="32" height="<%= mobileLogoHeight %>" alt="<%= t("share_theme.logo-alt") %>" />+ <a href="<%= logo.href %>" id="header-logo">+ <img src="<%= logoUrl %>" width="<%= logo.width %>" height="<%= logo.height %>" alt="<%= t("share_theme.logo-alt") %>" /><%= subRoot.note.title %></a><% if (headingMatches.length > 1) { %>diff --git a/packages/trilium-core/src/share/content_renderer.spec.ts b/packages/trilium-core/src/share/content_renderer.spec.tsindex 3876eba545..73511892d5 100644--- a/packages/trilium-core/src/share/content_renderer.spec.ts+++ b/packages/trilium-core/src/share/content_renderer.spec.ts@@ -1,5 +1,5 @@import { trimIndentation } from "@triliumnext/commons";-import { getHtmlSnippets, getPageHead } from "@triliumnext/share-theme/model/page";+import { getHtmlSnippets, getPageHead, getSiteLogo } from "@triliumnext/share-theme/model/page";import ejs from "ejs";import { parse } from "node-html-parser";import { describe, expect, it, vi } from "vitest";@@ -1098,7 +1098,8 @@ describe("content_renderer", () => {iconPackCss: "",iconPackSupportedPrefixes: [],head: getPageHead(note, note),- snippets: getHtmlSnippets(note)+ snippets: getHtmlSnippets(note),+ logo: getSiteLogo(note, sanitize.sanitizeUrl)}, {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.tsindex 4c822612e6..73752eb693 100644--- a/packages/trilium-core/src/share/content_renderer.ts+++ b/packages/trilium-core/src/share/content_renderer.ts@@ -7,7 +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 { getHtmlSnippets, getPageHead, getSiteLogo } from "@triliumnext/share-theme/model/page";import ejs from "ejs";import escapeHtml from "escape-html";import { t } from "i18next";@@ -213,6 +213,7 @@ function renderNoteContentInternal(note: SNote | BNote, renderArgs: RenderArgs)canAccessEmbed: renderArgs.canAccessEmbed});const showLoginInShareTheme = options.getOptionBool("showLoginInShareTheme");+ const siteRoot = renderArgs.subRoot.note ?? note;const opts = {note,header,@@ -225,8 +226,9 @@ function renderNoteContentInternal(note: SNote | BNote, renderArgs: RenderArgs)isDev: utils.isDev(),utils,sanitizeUrl: sanitize.sanitizeUrl,- head: getPageHead(note, renderArgs.subRoot.note ?? note),+ head: getPageHead(note, siteRoot),snippets: getHtmlSnippets(note),+ logo: getSiteLogo(siteRoot, sanitize.sanitizeUrl),...renderArgs,};