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): anchor headings and build the table of contents before the template runs
Elian Doranf295b07f2597
diff --git a/packages/share-theme/src/model/page.spec.ts b/packages/share-theme/src/model/page.spec.tsindex dc47a4d2cb..87172739cb 100644--- a/packages/share-theme/src/model/page.spec.ts+++ b/packages/share-theme/src/model/page.spec.ts@@ -1,6 +1,8 @@import { describe, expect, it } from "vitest";-import { getHtmlSnippets, getPageHead, getSiteLogo, type ShareNote } from "./page.js";+import {+ getHtmlSnippets, getPageHead, getSiteLogo, getTableOfContents, type PageHeading, type ShareNote+} from "./page.js";describe("getPageHead", () => {it("titles a page after the note and its site, and reads the site's OpenGraph labels", () => {@@ -105,6 +107,33 @@ describe("getSiteLogo", () => {});});+describe("getTableOfContents", () => {+ const heading = (level: number, slug: string): PageHeading => ({ level, text: slug.toUpperCase(), slug });+ const outline = (entries: ReturnType<typeof getTableOfContents>): unknown[] =>+ entries.map((entry) => (entry.children.length+ ? [ entry.slug, outline(entry.children) ]+ : entry.slug));++ it("nests each heading under the closest heading of a higher level before it", () => {+ const toc = getTableOfContents([+ heading(2, "a"), heading(3, "a1"), heading(4, "a1x"), heading(3, "a2"),+ heading(2, "b"), heading(4, "b1"), heading(3, "b2")+ ]);++ expect(outline(toc)).toStrictEqual([+ [ "a", [ [ "a1", [ "a1x" ] ], "a2" ] ],+ [ "b", [ "b1", "b2" ] ]+ ]);+ expect(toc[0]).toMatchObject({ level: 2, text: "A", slug: "a" });+ });++ it("keeps a heading of a higher level than the first one at the top", () => {+ expect(outline(getTableOfContents([ heading(3, "x"), heading(2, "y"), heading(3, "z") ])))+ .toStrictEqual([ "x", [ "y", [ "z" ] ] ]);+ expect(getTableOfContents([])).toStrictEqual([]);+ });+});+interface FakeNoteOptions {noteId: string;title?: string;diff --git a/packages/share-theme/src/model/page.ts b/packages/share-theme/src/model/page.tsindex 29e141e869..32907837a0 100644--- a/packages/share-theme/src/model/page.ts+++ b/packages/share-theme/src/model/page.ts@@ -39,6 +39,21 @@ export interface SiteLogo {height: number;}+/** A heading of the page's content, as core's `anchorHeadings()` finds it. */+export interface PageHeading {+ /** 1 for `<h1>`, up to 6 for `<h6>`. */+ level: number;+ /** The heading's plain text. */+ text: string;+ /** The ID of the heading's anchor, unique on the page. */+ slug: string;+}++/** An entry of the table of contents, with the headings it contains. */+export interface TableOfContentsEntry extends PageHeading {+ children: TableOfContentsEntry[];+}+/** Where an HTML snippet can go, as `#shareHtmlLocation` names it. */export type HtmlSnippetLocation =`${"head" | "body" | "content"}:${"start" | "end"}`;@@ -125,3 +140,23 @@ function readPositiveNumber(value: string | null | undefined) {const number = Number(value);return value && number > 0 ? number : undefined;}++/**+ * Returns the table of contents of a page with `headings`. Each heading goes under the closest+ * heading before it of a higher level, such as an `<h3>` under the `<h2>` before it, and at the top+ * when there is none.+ */+export function getTableOfContents(headings: PageHeading[]): TableOfContentsEntry[] {+ const toc: TableOfContentsEntry[] = [];+ const open: TableOfContentsEntry[] = [];++ for (const heading of headings) {+ const entry = { ...heading, children: [] };+ while (open.length && open[open.length - 1].level >= heading.level) {+ open.pop();+ }+ (open.at(-1)?.children ?? toc).push(entry);+ open.push(entry);+ }+ return toc;+}diff --git a/packages/share-theme/src/page/toc.ts b/packages/share-theme/src/page/toc.tsindex b6a3c9a178..4edbf2fcd7 100644--- a/packages/share-theme/src/page/toc.ts+++ b/packages/share-theme/src/page/toc.ts@@ -19,13 +19,14 @@ export default function setupToC() {if (!toc || !container) return;// Get all relevant elements- const sections = document.getElementById("content")!.querySelectorAll("h2, h3, h4, h5, h6");+ const sections = [ ...document.querySelectorAll("#content .toc-anchor") ]+ .map((anchor) => anchor.parentElement);const links = toc.querySelectorAll("a");// Setup smooth scroll on clickfor (const link of links) {link.addEventListener("click", e => {- const target = document.querySelector(link.getAttribute("href")!);+ const target = document.getElementById(link.getAttribute("href")?.slice(1) ?? "");if (!target) return;e.preventDefault();e.stopPropagation();diff --git a/packages/share-theme/src/templates/page.ejs b/packages/share-theme/src/templates/page.ejsindex 7b3704f568..bb38d30c92 100644--- a/packages/share-theme/src/templates/page.ejs+++ b/packages/share-theme/src/templates/page.ejs@@ -40,19 +40,6 @@</style><%- snippets["head:end"] %></head>-<%-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-// anchor IDs and the ToC links point to the right occurrence.-const headingSlugs = utils.slugifyHeadings(headingMatches.map((m) => m[2]));-let headingIndex = 0;-content = content.replaceAll(headingRe, (...match) => {- const slug = headingSlugs[headingIndex++];- match[0] = match[0].replace(match[3], `<a id="${slug}" class="toc-anchor" name="${slug}" href="#${slug}">#</a>${match[3]}`);- return match[0];-});-%><body data-note-id="<%= note.noteId %>" class="type-<%= note.type %>" data-ancestor-note-id="<%= subRoot.note.noteId %>"><%- snippets["body:start"] %><div id="header">@@ -61,7 +48,7 @@ content = content.replaceAll(headingRe, (...match) => {<img src="<%= logoUrl %>" width="<%= logo.width %>" height="<%= logo.height %>" alt="<%= t("share_theme.logo-alt") %>" /><%= subRoot.note.title %></a>- <% if (headingMatches.length > 1) { %>+ <% if (headings.length > 1) { %><button aria-label="<%= t("share_theme.toggle-toc") %>" id="toc-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="M3 9h14V7H3v2zm0 4h14v-2H3v2zm0 4h14v-2H3v2zm16 0h2v-2h-2v2zm0-10V7h2v2h-2zm0 6h2v-2h-2v2z"></path></svg></button><% } else { %><div class="header-button-placeholder"></div>@@ -158,25 +145,7 @@ content = content.replaceAll(headingRe, (...match) => {<% } %></footer></div>- <%- if (headingMatches.length > 1) {- const level = (m) => parseInt(m[1].replace(/[<h>]+/g, ""));-- const makeEntry = (i) => ({level: level(headingMatches[i]), name: headingMatches[i][2], slug: headingSlugs[i], children: []});- const toc = [ makeEntry(0) ];- const last = (arr = toc) => arr[arr.length - 1];- const getLevelArr = (lvl, arr = toc) => {- if (arr[0].level === lvl) return arr;- const top = last(arr);- return top.children.length ? getLevelArr(lvl, top.children) : top.children;- };--- for (let m = 1; m < headingMatches.length; m++) {- const target = getLevelArr(level(headingMatches[m]));- target.push(makeEntry(m));- }- %>+ <% if (headings.length > 1) { %><div id="toc-pane"><h3><%= t("share_theme.on-this-page") %></h3><ul id="toc">diff --git a/packages/share-theme/src/templates/toc_item.ejs b/packages/share-theme/src/templates/toc_item.ejsindex 5890e0b4bf..d387b298ee 100644--- a/packages/share-theme/src/templates/toc_item.ejs+++ b/packages/share-theme/src/templates/toc_item.ejs@@ -1,17 +1,12 @@-<%-const strippedName = utils.stripTags(entry.name);-const slug = entry.slug ?? utils.slugify(strippedName);-%>-<li>- <a href="#<%= slug %>">- <span><%= strippedName %></span>+ <a href="#<%= entry.slug %>">+ <span><%= entry.text %></span></a><% if (entry.children.length) { %><ul><% for (const subentry of entry.children) { %>- <%- include('toc_item', {entry: subentry}) %>+ <%- include("toc_item", { entry: subentry }) %><% } %></ul><% } %>diff --git a/packages/trilium-core/src/share/content_renderer.spec.ts b/packages/trilium-core/src/share/content_renderer.spec.tsindex 73511892d5..244489b197 100644--- a/packages/trilium-core/src/share/content_renderer.spec.ts+++ b/packages/trilium-core/src/share/content_renderer.spec.ts@@ -9,7 +9,7 @@ import * as sanitize from "../services/sanitizer.js";import * as utils from "../services/utils/index.js";import { buildShareNote, buildShareNotes } from "../test/shaca_mocking.js";import {- ensureShareHighlighting, getContent, readShareTemplate, renderCode, renderNoteContent,+ anchorHeadings, ensureShareHighlighting, getContent, readShareTemplate, renderCode, renderNoteContent,type Result} from "./content_renderer.js";import type SNote from "./shaca/entities/snote.js";@@ -312,6 +312,11 @@ describe("content_renderer", () => {expect(page).toContain(`<h3 data-trilium-block-id="b1">Referenced`+ `<a id="referenced" class="toc-anchor"`);expect(page).toContain(`href="#referenced"`);++ const toc = parse(String(page)).querySelector("#toc");+ expect(toc?.querySelectorAll(":scope > li > a").map((link) => link.text.trim()))+ .toStrictEqual([ "Plain" ]);+ expect(toc?.querySelector("li li a")?.getAttribute("href")).toBe("#referenced");});it("leaves an include-note section untouched when the referenced note is missing", () => {@@ -903,6 +908,36 @@ describe("content_renderer", () => {expect(Object.keys(anchor?.attributes ?? {}).sort()).toEqual([ "class", "href" ]);});});+ describe("anchorHeadings", () => {+ it("anchors every heading and lists it with its level, text and unique slug", () => {+ const { content, headings } = anchorHeadings(trimIndentation`+ <h1>Intro</h1>+ <p>Text</p>+ <h2 class="x">Q&A <strong>now</strong></h2>+ <h3>Spans+ two lines</h3>+ <h2>Intro</h2>+ `);++ expect(headings).toStrictEqual([+ { level: 1, text: "Intro", slug: "intro" },+ { level: 2, text: "Q&A now", slug: "q-amp-a-now" },+ { level: 3, text: "Spans two lines", slug: "spans-two-lines" },+ { level: 2, text: "Intro", slug: "intro-1" }+ ]);+ expect(content).toContain(+ `<h2 class="x">Q&A <strong>now</strong>`+ + `<a id="q-amp-a-now" class="toc-anchor" name="q-amp-a-now" href="#q-amp-a-now">#</a></h2>`);+ expect(content).toContain(`<p>Text</p>`);+ expect(parse(content).querySelectorAll(".toc-anchor")).toHaveLength(4);+ });++ it("returns content without headings as it is", () => {+ const html = `<p>No <b>headings</b> here & there</p>`;+ expect(anchorHeadings(html)).toStrictEqual({ content: html, headings: [] });+ });+ });+describe("Tree item template", () => {it("sets a working target and rel on external tree links only", () => {const external = renderTreeItemAnchor({@@ -1099,7 +1134,9 @@ describe("content_renderer", () => {iconPackSupportedPrefixes: [],head: getPageHead(note, note),snippets: getHtmlSnippets(note),- logo: getSiteLogo(note, sanitize.sanitizeUrl)+ logo: getSiteLogo(note, sanitize.sanitizeUrl),+ headings: [],+ toc: []}, {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 73752eb693..2646b07c7c 100644--- a/packages/trilium-core/src/share/content_renderer.ts+++ b/packages/trilium-core/src/share/content_renderer.ts@@ -7,7 +7,9 @@ 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, getSiteLogo } from "@triliumnext/share-theme/model/page";+import {+ getHtmlSnippets, getPageHead, getSiteLogo, getTableOfContents, type PageHeading+} from "@triliumnext/share-theme/model/page";import ejs from "ejs";import escapeHtml from "escape-html";import { t } from "i18next";@@ -266,12 +268,41 @@ function renderNoteContentInternal(note: SNote | BNote, renderArgs: RenderArgs)}}- // Render with the default view otherwise.- return ejs.render(readShareTemplate("page"), opts, {+ // Render with the default view otherwise. Custom templates get `content` without the heading+ // anchors, which templates derived from an earlier `page.ejs` add themselves.+ const { content: anchoredContent, headings } = typeof content === "string"+ ? anchorHeadings(content)+ : { content, headings: [] };+ const pageOpts = { ...opts, content: anchoredContent, headings, toc: getTableOfContents(headings) };+ return ejs.render(readShareTemplate("page"), pageOpts, {includer: (path) => ({ template: readShareTemplate(path) })});}+/**+ * Gives every heading of `html` a `#` link to itself, with an ID made from its text that is+ * unique on the page, and returns the headings in document order. HTML without headings comes+ * back as it is.+ */+export function anchorHeadings(html: string): { content: string; headings: PageHeading[] } {+ if (!/<h[1-6][\s>]/i.test(html)) {+ return { content: html, headings: [] };+ }++ const document = parse(html, { comment: true });+ const elements = document.querySelectorAll("h1, h2, h3, h4, h5, h6");+ const slugs = utils.slugifyHeadings(elements.map((element) => element.innerHTML));+ const headings = elements.map((element, index) => {+ const slug = slugs[index];+ const text = element.text.replace(/\s+/g, " ").trim();+ const heading = { level: Number(element.tagName.slice(1)), text, slug };+ element.insertAdjacentHTML("beforeend",+ `<a id="${slug}" class="toc-anchor" name="${slug}" href="#${slug}">#</a>`);+ return heading;+ });+ return { content: document.toString(), headings };+}+/*** Returns the share theme's EJS template of that name, such as `page` or `404`. The platform* decides where it comes from: the server reads it from disk, the browser build from its bundle.