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): URL-encode heading links so authored IDs round-trip
Elian Doran2c0f50c02864
diff --git a/packages/share-theme/src/model/page.spec.ts b/packages/share-theme/src/model/page.spec.tsindex eeedf25705..739f9df83e 100644--- a/packages/share-theme/src/model/page.spec.ts+++ b/packages/share-theme/src/model/page.spec.ts@@ -192,7 +192,8 @@ describe("getSiteLogo", () => {});describe("getTableOfContents", () => {- const heading = (level: number, slug: string): PageHeading => ({ level, text: slug.toUpperCase(), slug });+ const heading = (level: number, slug: string): PageHeading =>+ ({ level, text: slug.toUpperCase(), slug, href: `#${slug}` });const outline = (entries: ReturnType<typeof getTableOfContents>): unknown[] =>entries.map((entry) => (entry.children.length? [ entry.slug, outline(entry.children) ]diff --git a/packages/share-theme/src/model/page.ts b/packages/share-theme/src/model/page.tsindex 8239c6e0d2..b7a4e83f56 100644--- a/packages/share-theme/src/model/page.ts+++ b/packages/share-theme/src/model/page.ts@@ -113,6 +113,8 @@ export interface PageHeading {text: string;/** The ID of the heading's anchor, unique on the page. */slug: string;+ /** The link to the heading: `#` and `slug`, URL-encoded. */+ href: string;}/** An entry of the table of contents, with the headings it contains. */diff --git a/packages/share-theme/src/page/toc.spec.ts b/packages/share-theme/src/page/toc.spec.tsindex e715e3a539..fd4a8f1c96 100644--- a/packages/share-theme/src/page/toc.spec.ts+++ b/packages/share-theme/src/page/toc.spec.ts@@ -25,18 +25,22 @@ describe("setupToC", () => {expect(activeEntry()).toBe("more");});- it("scrolls to the heading of a clicked entry, also when its ID starts with a digit", () => {- renderPage([ [ 2, "2024-plans", 100 ], [ 2, "later", 500 ] ]);- const scrollIntoView = vi.fn();- const heading = document.getElementById("2024-plans");- if (!heading) {- throw new Error("The heading is missing.");- }- heading.scrollIntoView = scrollIntoView;+ it("scrolls to the heading of a clicked entry, whose ID can start with a digit or hold a %", () => {+ renderPage([ [ 2, "2024-plans", 100 ], [ 2, "part%20one", 500 ] ]);++ for (const [ id, href ] of [ [ "2024-plans", "#2024-plans" ], [ "part%20one", "#part%2520one" ] ]) {+ const scrollIntoView = vi.fn();+ const heading = document.getElementById(id);+ const entry = document.querySelector<HTMLElement>(`#toc a[href="${href}"]`);+ if (!heading || !entry) {+ throw new Error(`The heading or the entry of ${id} is missing.`);+ }+ heading.scrollIntoView = scrollIntoView;- document.querySelector<HTMLElement>(`#toc a[href="#2024-plans"]`)?.click();+ entry.click();- expect(scrollIntoView).toHaveBeenCalledWith({ behavior: "smooth" });+ expect(scrollIntoView).toHaveBeenCalledWith({ behavior: "smooth" });+ }});it("leaves an entry without a heading to the browser, and a page without one alone", () => {@@ -153,7 +157,7 @@ function renderPage(headings: [ level: number, slug: string, offsetTop: number ]+ `</h${level}>`).join("")}</div><ul id="toc">- ${headings.map(([ , slug ]) => `<li><a href="#${slug}">${slug}</a></li>`).join("")}+ ${headings.map(([ , slug ]) => `<li><a href="#${encodeURIComponent(slug)}">${slug}</a></li>`).join("")}</ul></div>`;@@ -178,12 +182,12 @@ function activeEntry() {/** The link core's `preparePageContent()` gives a heading. */function anchor(slug: string) {- return `<a class="toc-anchor" href="#${slug}" aria-label="Link to This Section">`+ return `<a class="toc-anchor" href="#${encodeURIComponent(slug)}" aria-label="Link to This Section">`+ `<span class="tn-icon bx bx-link" aria-hidden="true"></span></a>`;}function headingLink(slug: string) {- const link = document.querySelector<HTMLAnchorElement>(`#content a.toc-anchor[href="#${slug}"]`);+ const link = document.querySelector<HTMLAnchorElement>(`#content a.toc-anchor[href="#${encodeURIComponent(slug)}"]`);if (!link) {throw new Error(`The link of ${slug} is missing.`);}diff --git a/packages/share-theme/src/page/toc.ts b/packages/share-theme/src/page/toc.tsindex 1c2da01292..22f12387b9 100644--- a/packages/share-theme/src/page/toc.ts+++ b/packages/share-theme/src/page/toc.ts@@ -27,7 +27,7 @@ export default function setupToC() {for (const link of links) {link.addEventListener("click", e => {- const target = document.getElementById(link.getAttribute("href")?.slice(1) ?? "");+ const target = document.getElementById(decodeURIComponent(link.hash.slice(1)));if (!target) return;e.preventDefault();e.stopPropagation();diff --git a/packages/share-theme/src/templates/toc_item.ejs b/packages/share-theme/src/templates/toc_item.ejsindex d387b298ee..fb5bf25c32 100644--- a/packages/share-theme/src/templates/toc_item.ejs+++ b/packages/share-theme/src/templates/toc_item.ejs@@ -1,5 +1,5 @@<li>- <a href="#<%= entry.slug %>">+ <a href="<%= entry.href %>"><span><%= entry.text %></span></a>diff --git a/packages/trilium-core/src/share/content_renderer.spec.ts b/packages/trilium-core/src/share/content_renderer.spec.tsindex dfe285d42a..e5b243acec 100644--- a/packages/trilium-core/src/share/content_renderer.spec.ts+++ b/packages/trilium-core/src/share/content_renderer.spec.ts@@ -368,6 +368,21 @@ describe("content_renderer", () => {]);});+ it("links the table of contents to a heading's own ID, URL-encoded", () => {+ const shareRootNote = buildShareNote({+ id: shareRoot.SHARE_ROOT_NOTE_ID,+ children: [{+ id: "encodedHeadings",+ content: `<h2 id="part%20one">Part one</h2><p>a</p><h2>Two</h2><p>b</p>`+ }]+ });++ const page = parse(String(renderNoteContent(shareRootNote.getChildNotes()[0])));++ expect(page.querySelectorAll("#toc a").map((link) => link.getAttribute("href")))+ .toStrictEqual([ "#part%2520one", "#two" ]);+ });+it("prints only the OpenGraph tags that have a value, with an absolute image", () => {const shareRootNote = buildShareNote({id: shareRoot.SHARE_ROOT_NOTE_ID,@@ -1109,10 +1124,10 @@ describe("content_renderer", () => {`);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" }+ { level: 1, text: "Intro", slug: "intro", href: "#intro" },+ { level: 2, text: "Q&A now", slug: "q-amp-a-now", href: "#q-amp-a-now" },+ { level: 3, text: "Spans two lines", slug: "spans-two-lines", href: "#spans-two-lines" },+ { level: 2, text: "Intro", slug: "intro-1", href: "#intro-1" }]);expect(content).toContain(`<h2 class="x" id="q-amp-a-now">Q&A <strong>now</strong>`@@ -1122,21 +1137,24 @@ describe("content_renderer", () => {expect(parse(content).querySelectorAll(".toc-anchor")).toHaveLength(4);});- it("keeps a heading's own ID and gives no other heading an ID already on the page", () => {+ it("keeps a heading's own ID, linked URL-encoded, and gives no other heading an ID in use", () => {const { content, headings } = prepare(trimIndentation`<h2 id="footnote-label" class="sr-only">Footnotes</h2><p><a id="footnotes">Bookmark</a> <sup><a aria-describedby="footnote-label">1</a></sup></p><h2>Footnotes</h2>+ <h3 id="part%20one">Part one</h3>`);expect(headings).toStrictEqual([- { level: 2, text: "Footnotes", slug: "footnote-label" },- { level: 2, text: "Footnotes", slug: "footnotes-1" }+ { level: 2, text: "Footnotes", slug: "footnote-label", href: "#footnote-label" },+ { level: 2, text: "Footnotes", slug: "footnotes-1", href: "#footnotes-1" },+ { level: 3, text: "Part one", slug: "part%20one", href: "#part%2520one" }]);expect(content).toContain(`<h2 id="footnote-label" class="sr-only">Footnotes`+ `<a class="toc-anchor" href="#footnote-label"`);expect(content).toContain(`<h2 id="footnotes-1">Footnotes<a class="toc-anchor" href="#footnotes-1"`);+ expect(content).toContain(`<h3 id="part%20one">Part one<a class="toc-anchor" href="#part%2520one"`);});it("gives an image without alt text the generic one and lazy loading, keeping its own", () => {diff --git a/packages/trilium-core/src/share/content_renderer.ts b/packages/trilium-core/src/share/content_renderer.tsindex 170187564c..c979a8d09f 100644--- a/packages/trilium-core/src/share/content_renderer.ts+++ b/packages/trilium-core/src/share/content_renderer.ts@@ -319,9 +319,10 @@ export function preparePageContent(const headings = elements.map((element) => {const slug = element.id || slugs[slugIndex++];const text = element.text.replace(/\s+/g, " ").trim();- const heading = { level: Number(element.tagName.slice(1)), text, slug };+ const href = `#${encodeURIComponent(slug)}`;+ const heading = { level: Number(element.tagName.slice(1)), text, slug, href };element.setAttribute("id", slug);- element.insertAdjacentHTML("beforeend", `<a class="toc-anchor" href="#${escapeHtml(slug)}"`+ element.insertAdjacentHTML("beforeend", `<a class="toc-anchor" href="${href}"`+ ` aria-label="${escapeHtml(options.headingLinkLabel)}">`+ `<span class="tn-icon bx bx-link" aria-hidden="true"></span></a>`);return heading;