Skip to content

Build your personal knowledge base with Trilium Notes

fix(share): give duplicate headings unique TOC anchors (closes #8318)

Elian Doran79405950f2fb
diff --git a/packages/share-theme/src/templates/page.ejs b/packages/share-theme/src/templates/page.ejs
index c39626bbf1..b569d31a75 100644
--- a/packages/share-theme/src/templates/page.ejs
+++ b/packages/share-theme/src/templates/page.ejs
@@ -103,8 +103,12 @@ 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]>)(.+?)(<\/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 = utils.slugify(utils.stripTags(match[2]));
+ 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];
});
@@ -216,25 +220,19 @@ content = content.replaceAll(headingRe, (...match) => {
if (headingMatches.length > 1) {
const level = (m) => parseInt(m[1].replace(/[<h>]+/g, ""));
- const toc = [
- {
- level: level(headingMatches[0]),
- name: headingMatches[0][2],
- children: []
- }
- ];
+ 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 makeEntry = (m) => ({level: level(m), name: m[2], children: []});
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(headingMatches[m]));
+ target.push(makeEntry(m));
}
%>
<div id="toc-pane">
diff --git a/packages/share-theme/src/templates/toc_item.ejs b/packages/share-theme/src/templates/toc_item.ejs
index 4346fe55a9..5890e0b4bf 100644
--- a/packages/share-theme/src/templates/toc_item.ejs
+++ b/packages/share-theme/src/templates/toc_item.ejs
@@ -1,6 +1,6 @@
<%
const strippedName = utils.stripTags(entry.name);
-const slug = utils.slugify(strippedName);
+const slug = entry.slug ?? utils.slugify(strippedName);
%>
<li>
diff --git a/packages/trilium-core/src/services/utils/index.spec.ts b/packages/trilium-core/src/services/utils/index.spec.ts
index 8ec68cd03b..14abd50fad 100644
--- a/packages/trilium-core/src/services/utils/index.spec.ts
+++ b/packages/trilium-core/src/services/utils/index.spec.ts
@@ -794,6 +794,29 @@ describe("#slugify", () => {
});
});
+describe("#slugifyHeadings", () => {
+ it("slugifies each heading in order", () => {
+ expect(utils.slugifyHeadings(["First Section", "Second Section"])).toStrictEqual(["first-section", "second-section"]);
+ });
+
+ it("disambiguates duplicate titles with a numeric suffix", () => {
+ expect(utils.slugifyHeadings(["Notes", "Notes", "Notes"])).toStrictEqual(["notes", "notes-1", "notes-2"]);
+ });
+
+ it("avoids colliding a suffix with an existing slug", () => {
+ // "Notes 1" naturally slugifies to "notes-1", so the second "Notes" must skip to "notes-2"
+ expect(utils.slugifyHeadings(["Notes", "Notes 1", "Notes"])).toStrictEqual(["notes", "notes-1", "notes-2"]);
+ });
+
+ it("strips HTML tags before slugifying", () => {
+ expect(utils.slugifyHeadings(["<b>Bold</b> Heading"])).toStrictEqual(["bold-heading"]);
+ });
+
+ it("returns an empty array for no headings", () => {
+ expect(utils.slugifyHeadings([])).toStrictEqual([]);
+ });
+});
+
describe("#sanitizeSvg", () => {
it("should remove script elements", () => {
const maliciousSvg = '<svg><script>alert("XSS")</script><rect width="100" height="100"/></svg>';
diff --git a/packages/trilium-core/src/services/utils/index.ts b/packages/trilium-core/src/services/utils/index.ts
index 5bcdc8325b..b36f543550 100644
--- a/packages/trilium-core/src/services/utils/index.ts
+++ b/packages/trilium-core/src/services/utils/index.ts
@@ -410,6 +410,29 @@ export function stripTags(text: string) {
return text.replace(/<(?:.|\n)*?>/gm, "");
}
+/**
+ * Generates a list of unique slugs for the given heading titles, preserving
+ * document order. Titles are stripped of HTML tags and slugified; when the same
+ * slug would be produced more than once (e.g. multiple headings sharing a
+ * title), subsequent occurrences get a numeric suffix (`foo`, `foo-1`, `foo-2`, …).
+ *
+ * This keeps anchor IDs and their table-of-contents links unique on shared
+ * pages, so clicking a duplicate heading in the ToC jumps to the right one.
+ */
+export function slugifyHeadings(titles: string[]): string[] {
+ const used = new Set<string>();
+ return titles.map((title) => {
+ const base = slugify(stripTags(title));
+ let slug = base;
+ let counter = 1;
+ while (used.has(slug)) {
+ slug = `${base}-${counter++}`;
+ }
+ used.add(slug);
+ return slug;
+ });
+}
+
export function toObject<T, K extends string | number | symbol, V>(array: T[], fn: (item: T) => [K, V]): Record<K, V> {
const obj: Record<K, V> = {} as Record<K, V>;