Skip to content

Build your personal knowledge base with Trilium Notes

feat(share): list the page's headings in the tree on narrow screens

Elian Doran308090af40f5
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.html
index 7e5548e4cf..eed3ff39ea 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
@@ -16,7 +16,9 @@ class="image">
remembered by the browser.</li>
<li>A layout centered on wide screens, with the navigation tree and the table
of contents at either side of the content, and a mobile-friendly layout
- with sliding panes on narrow ones.</li>
+ on narrow ones. There, the navigation tree slides in from the menu button
+ in the header, and lists the headings of the current page below its entry
+ (at the top of the pane, for a page the tree does not show).</li>
<li>Collapsible tree with the same note icons as the application. It keeps
the sections the visitor expanded and its scroll position while they move
between the pages of the site, and shows the current note.</li>
diff --git a/apps/standalone/src/lightweight/share_provider.ts b/apps/standalone/src/lightweight/share_provider.ts
index 223428c24a..ca512e831c 100644
--- a/apps/standalone/src/lightweight/share_provider.ts
+++ b/apps/standalone/src/lightweight/share_provider.ts
@@ -7,6 +7,7 @@ import templatePrevNext from "@triliumnext/share-theme/templates/prev_next.ejs?r
import templateSiteLogo from "@triliumnext/share-theme/templates/site_logo.ejs?raw";
import templateTocItem from "@triliumnext/share-theme/templates/toc_item.ejs?raw";
import templateTreeItem from "@triliumnext/share-theme/templates/tree_item.ejs?raw";
+import templateTreeToc from "@triliumnext/share-theme/templates/tree_toc.ejs?raw";
/**
* The share theme's templates, bundled rather than read from disk: this build has no filesystem to
@@ -19,7 +20,8 @@ const TEMPLATES: Record<string, string> = {
prev_next: templatePrevNext,
site_logo: templateSiteLogo,
toc_item: templateTocItem,
- tree_item: templateTreeItem
+ tree_item: templateTreeItem,
+ tree_toc: templateTreeToc
};
let registered = false;
diff --git a/docs/User Guide/User Guide/Advanced Usage/Sharing.md b/docs/User Guide/User Guide/Advanced Usage/Sharing.md
index 53f8771045..67ff8b99f0 100644
--- a/docs/User Guide/User Guide/Advanced Usage/Sharing.md
+++ b/docs/User Guide/User Guide/Advanced Usage/Sharing.md
@@ -7,7 +7,7 @@ Trilium allows you to share selected notes as **publicly accessible** read-only
* Searching by note title.
* Light and dark mode, following the visitor's system setting by default, also while the page is open. The visitor can pick _Light_, _Dark_ or _System_ with the buttons at the top of the navigation pane, or on narrow screens with the button in the header, which cycles through the three; the choice is remembered by the browser.
-* A layout centered on wide screens, with the navigation tree and the table of contents at either side of the content, and a mobile-friendly layout with sliding panes on narrow ones.
+* A layout centered on wide screens, with the navigation tree and the table of contents at either side of the content, and a mobile-friendly layout on narrow ones. There, the navigation tree slides in from the menu button in the header, and lists the headings of the current page below its entry (at the top of the pane, for a page the tree does not show).
* Collapsible tree with the same note icons as the application. It keeps the sections the visitor expanded and its scroll position while they move between the pages of the site, and shows the current note.
* Customizable logo.
* Quick navigation buttons (previous and next note).
diff --git a/packages/share-theme/src/model/page.spec.ts b/packages/share-theme/src/model/page.spec.ts
index cb4d4816bb..c292e00ad7 100644
--- a/packages/share-theme/src/model/page.spec.ts
+++ b/packages/share-theme/src/model/page.spec.ts
@@ -2,7 +2,7 @@ import { describe, expect, it, vi } from "vitest";
import {
getChildLinks, getChildLinksLayout, getContentClasses, getHtmlSnippets, getLastUpdated, getNavigationTree, getPageHead, getPageLanguages,
- getPrevNextLinks, getShareLink, getSiteAncestorIds, getSiteLogo, getTableOfContents,
+ getPrevNextLinks, getShareLink, getSiteAncestorIds, getSiteLogo, getTableOfContents, hasActiveItem,
type NavigationItem, type PageHeading, type ShareNote
} from "./page.js";
@@ -318,7 +318,7 @@ describe("getNavigationTree", () => {
const site = fakeNote({ noteId: "site" });
const a = addChild(site, fakeNote({ noteId: "a", icon: "bx bx-folder" }));
const a1 = addChild(a, fakeNote({ noteId: "a1", type: "code" }));
- addChild(a, fakeNote({ noteId: "hidden" }), true);
+ const hidden = addChild(a, fakeNote({ noteId: "hidden" }), true);
const b = addChild(site, fakeNote({ noteId: "b", labels: { shareExternalLink: "https://example.com" } }));
addChild(b, fakeNote({ noteId: "b1" }));
const outline = (items: NavigationItem[]): unknown[] => items.map((item) => {
@@ -364,6 +364,14 @@ describe("getNavigationTree", () => {
expect(tree[1].icon).toBe("bx bx-note custom");
expect(outline(tree)).toStrictEqual([ [ "a", [ "a1" ] ], [ "b", [ "b1" ] ] ]);
});
+
+ it("tells whether the page has an entry, which the site root and a hidden note do not", () => {
+ const options = { sanitizeUrl: (url: string) => url };
+
+ expect(hasActiveItem(getNavigationTree(site, a1, [ "a" ], options))).toBe(true);
+ expect(hasActiveItem(getNavigationTree(site, site, [], options))).toBe(false);
+ expect(hasActiveItem(getNavigationTree(site, hidden, [ "a" ], options))).toBe(false);
+ });
});
describe("getPageLanguages", () => {
diff --git a/packages/share-theme/src/model/page.ts b/packages/share-theme/src/model/page.ts
index 52644a373d..552972a87a 100644
--- a/packages/share-theme/src/model/page.ts
+++ b/packages/share-theme/src/model/page.ts
@@ -490,6 +490,14 @@ export function getNavigationTree(
return siteRoot.getVisibleChildNotes().map((note) => toItem(note, []));
}
+/**
+ * Returns whether a navigation tree has an entry for the page being shown, which the site root
+ * and a note hidden from the tree do not.
+ */
+export function hasActiveItem(items: NavigationItem[]): boolean {
+ return items.some((item) => item.isActive || hasActiveItem(item.children));
+}
+
/**
* Returns the IDs of the notes between `note` and `siteRoot`, from its parent up, following the
* first parent inside the site.
diff --git a/packages/share-theme/src/page/toc.css b/packages/share-theme/src/page/toc.css
index 114f671374..41592a845f 100644
--- a/packages/share-theme/src/page/toc.css
+++ b/packages/share-theme/src/page/toc.css
@@ -18,7 +18,8 @@
display: none;
}
-#toc-pane h3 {
+#toc-pane h3,
+#tree-toc-title {
margin: 0 0 0.5em;
padding-inline: 8px;
font-size: 0.85em;
@@ -59,6 +60,52 @@
font-weight: bold;
}
+/* The copy of the table of contents that narrow screens show in the navigation pane: below the
+ page's entry in the tree, or at the top of the pane for a page the tree does not list. */
+.tree-toc {
+ display: none;
+}
+
+#menu .tree-toc,
+.tree-toc-children {
+ padding-inline-start: 8px;
+ border-inline-start: 1px solid var(--main-border-color);
+}
+
+#menu .tree-toc {
+ margin-block: 2px 6px;
+ margin-inline-start: 40px;
+}
+
+.tree-toc-children {
+ margin-inline-start: 12px;
+}
+
+#navigation > .tree-toc {
+ margin-bottom: 16px;
+ padding-inline: 4px;
+}
+
+#navigation .tree-toc a {
+ display: block;
+ padding: 4px 8px;
+ border-radius: 6px;
+ color: var(--tree-item-color);
+ font-size: 0.9em;
+ line-height: 1.3;
+ white-space: normal;
+ overflow-wrap: break-word;
+}
+
+#navigation .tree-toc a:hover {
+ background: var(--tree-item-hover-background);
+}
+
+#navigation .tree-toc a.active {
+ color: var(--tree-item-active-color);
+ font-weight: 600;
+}
+
#content :is(h1, h2, h3, h4, h5, h6) {
scroll-margin-top: 16px;
}
@@ -106,6 +153,14 @@
transform: translateX(0);
}
+ .tree-toc {
+ display: block;
+ }
+
+ #menu li:not(.expanded) > .tree-toc {
+ display: none;
+ }
+
#toc-pane:empty {
display: none;
}
diff --git a/packages/share-theme/src/page/toc.spec.ts b/packages/share-theme/src/page/toc.spec.ts
index fea4c55493..58bef70daf 100644
--- a/packages/share-theme/src/page/toc.spec.ts
+++ b/packages/share-theme/src/page/toc.spec.ts
@@ -23,6 +23,30 @@ describe("setupToC", () => {
expect(activeEntry()).toBe("more");
});
+ it("keeps the copy in the navigation pane in step, and closes the pane on a click", () => {
+ const scrollTo = renderPage([ [ 2, "intro", 100 ], [ 2, "details", 500 ] ]);
+ const treeEntry = (selector: string) =>
+ document.querySelector<HTMLAnchorElement>(`.tree-toc a${selector}`);
+
+ expect(treeEntry(".active")?.textContent).toBe("intro");
+ scrollTo(520);
+ expect(treeEntry(".active")?.textContent).toBe("details");
+ expect(activeEntry()).toBe("details");
+
+ const heading = document.getElementById("intro");
+ const entry = treeEntry('[href="#intro"]');
+ if (!heading || !entry) {
+ throw new Error("The heading or its entry in the navigation pane is missing.");
+ }
+ heading.scrollIntoView = vi.fn();
+ document.body.classList.add("menu-open");
+
+ entry.click();
+
+ expect(heading.scrollIntoView).toHaveBeenCalledWith({ behavior: "smooth" });
+ expect(document.body.classList.contains("menu-open")).toBe(false);
+ });
+
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 ] ]);
@@ -149,6 +173,7 @@ describe("setupToC", () => {
* scrolls the page.
*/
function renderPage(headings: [ level: number, slug: string, offsetTop: number ][]) {
+ const link = (slug: string) => `<a href="#${encodeURIComponent(slug)}">${slug}</a>`;
document.body.innerHTML = `
<div>
<div id="content">
@@ -156,8 +181,11 @@ function renderPage(headings: [ level: number, slug: string, offsetTop: number ]
+ `</h${level}>`).join("")}
</div>
<ul id="toc">
- ${headings.map(([ , slug ]) => `<li><a href="#${encodeURIComponent(slug)}">${slug}</a></li>`).join("")}
+ ${headings.map(([ , slug ]) => `<li>${link(slug)}</li>`).join("")}
</ul>
+ <nav class="tree-toc">
+ ${headings.map(([ , slug ]) => `<div>${link(slug)}</div>`).join("")}
+ </nav>
</div>
`;
let scrolled = 0;
diff --git a/packages/share-theme/src/page/toc.ts b/packages/share-theme/src/page/toc.ts
index a0db2a8612..1072ea7e70 100644
--- a/packages/share-theme/src/page/toc.ts
+++ b/packages/share-theme/src/page/toc.ts
@@ -16,15 +16,16 @@ import "./toc.css";
export default function setupToC() {
setupHeadingLinks();
- const toc = document.getElementById("toc");
- if (!toc) return;
+ // The ToC pane, and the copy in the navigation pane that narrow screens show instead.
+ const tocs = [ ...document.querySelectorAll("#toc, .tree-toc") ];
+ if (!tocs.length) return;
const sections = [ ...document.querySelectorAll("#content .toc-anchor") ]
.map((anchor) => anchor.parentElement)
.filter((heading) => heading !== null);
- const links = [ ...toc.querySelectorAll("a") ];
+ const linkLists = tocs.map((toc) => [ ...toc.querySelectorAll("a") ]);
- for (const link of links) {
+ for (const link of linkLists.flat()) {
link.addEventListener("click", e => {
const target = document.getElementById(decodeURIComponent(link.hash.slice(1)));
if (!target) return;
@@ -44,8 +45,10 @@ export default function setupToC() {
// Walk back to the last section scrolled past.
}
- for (const [ linkIndex, link ] of links.entries()) {
- link.classList.toggle("active", linkIndex === index);
+ for (const links of linkLists) {
+ for (const [ linkIndex, link ] of links.entries()) {
+ link.classList.toggle("active", linkIndex === index);
+ }
}
};
diff --git a/packages/share-theme/src/page/tree_state.spec.ts b/packages/share-theme/src/page/tree_state.spec.ts
index 18f7fa9c37..6efaf974fe 100644
--- a/packages/share-theme/src/page/tree_state.spec.ts
+++ b/packages/share-theme/src/page/tree_state.spec.ts
@@ -155,6 +155,28 @@ describe("setupTreeState", () => {
expect(event.preventDefault).not.toHaveBeenCalled();
});
+ it("moves the page's table of contents with the selection, and leaves its links alone", () => {
+ const toc = `<nav class="tree-toc"><div><a class="active" href="#missing">Missing</a></div></nav>`;
+ const selectedLink = `<a class="active" href="./c">C</a></div>`;
+ renderPane("site1", { activeTop: 50, menu: CLONES.replace(selectedLink, selectedLink + toc) });
+ document.body.dataset.noteId = "c";
+ setupTreeState();
+ const tocLink = document.querySelector<HTMLElement>(".tree-toc a");
+ if (!tocLink) {
+ throw new Error("The table of contents is missing.");
+ }
+
+ const event = new MouseEvent("click", { bubbles: true, cancelable: true });
+ tocLink.dispatchEvent(event);
+ expect(event.defaultPrevented).toBe(false);
+
+ cloneLink("y").click();
+ const tocParent = document.querySelector(".tree-toc")?.parentElement;
+ expect(tocParent?.parentElement?.closest<HTMLElement>("li")?.dataset.noteId).toBe("y");
+ expect(tocParent?.firstElementChild).toBe(cloneLink("y").parentElement);
+ expect(tocLink.classList.contains("active")).toBe(true);
+ });
+
it("centers the current note when it is out of view, and leaves it when it is in view", () => {
renderPane("site1", { activeTop: 700 });
setupTreeState();
diff --git a/packages/share-theme/src/page/tree_state.ts b/packages/share-theme/src/page/tree_state.ts
index 2a3bbd851c..d002a90c7c 100644
--- a/packages/share-theme/src/page/tree_state.ts
+++ b/packages/share-theme/src/page/tree_state.ts
@@ -44,7 +44,8 @@ export default function setupTreeState() {
}
pane.addEventListener("click", (e) => {
- const item = e.target instanceof Element && e.target.closest("#menu a")?.closest("li");
+ const link = e.target instanceof Element && e.target.closest("#menu a");
+ const item = link && !link.closest(".tree-toc") && link.closest("li");
if (!item) {
return;
}
@@ -110,15 +111,21 @@ function restoreTree(pane: HTMLElement, state: TreeState) {
return clicked ? path : undefined;
}
-/** Moves the current note's card to `item`, one of its entries. */
+/** Moves the current note's card and its table of contents to `item`, one of its entries. */
function selectItem(pane: HTMLElement, item: Element) {
for (const selected of pane.querySelectorAll("#menu .active")) {
- selected.classList.remove("active");
+ if (!selected.closest(".tree-toc")) {
+ selected.classList.remove("active");
+ }
}
const rowAndLink = ":scope > .tree-item-row, :scope > * > a, :scope > a";
for (const selected of item.querySelectorAll(rowAndLink)) {
selected.classList.add("active");
}
+ const toc = pane.querySelector("#menu .tree-toc");
+ if (toc) {
+ item.querySelector(":scope > .tree-item-row")?.after(toc);
+ }
}
function expandItem(item: Element) {
diff --git a/packages/share-theme/src/templates/page.ejs b/packages/share-theme/src/templates/page.ejs
index ac62204cca..068ae97e56 100644
--- a/packages/share-theme/src/templates/page.ejs
+++ b/packages/share-theme/src/templates/page.ejs
@@ -39,9 +39,6 @@
<span class="theme-cycle-option" data-theme="dark" title="<%= t("share_theme.theme-dark") %>"><span class="tn-icon bx bx-moon" aria-hidden="true"></span><span class="visually-hidden"><%= t("share_theme.theme-current", { theme: t("share_theme.theme-dark") }) %></span></span>
<span class="theme-cycle-option" data-theme="system" title="<%= t("share_theme.theme-system") %>"><span class="tn-icon bx bx-desktop" aria-hidden="true"></span><span class="visually-hidden"><%= t("share_theme.theme-current", { theme: t("share_theme.theme-system") }) %></span></span>
</button>
- <% if (headings.length > 1) { %>
- <button aria-label="<%= t("share_theme.toggle-toc") %>" id="toc-pane-toggle-button" class="header-button"><span class="tn-icon bx bx-list-ul" aria-hidden="true"></span></button>
- <% } %>
</div>
</div>
<div id="split-pane">
@@ -66,6 +63,12 @@
</div>
<% } %>
</div>
+ <% if (headings.length > 1 && !isPageInNavigation) { %>
+ <nav class="tree-toc" aria-labelledby="tree-toc-title">
+ <h3 id="tree-toc-title"><%= t("share_theme.on-this-page") %></h3>
+ <%- include("tree_toc", { entries: toc }) %>
+ </nav>
+ <% } %>
<% if (navigation.length) { %>
<nav id="menu">
<%- include("tree_item", { items: navigation }) %>
diff --git a/packages/share-theme/src/templates/tree_item.ejs b/packages/share-theme/src/templates/tree_item.ejs
index fcf87f6149..2f1ff9e2b2 100644
--- a/packages/share-theme/src/templates/tree_item.ejs
+++ b/packages/share-theme/src/templates/tree_item.ejs
@@ -7,6 +7,11 @@
<span class="tn-icon <%= item.icon %>" aria-hidden="true"></span><span class="tree-item-title"><%= item.title %></span>
</a>
</div>
+ <% if (item.isActive && headings.length > 1) { %>
+ <nav class="tree-toc" aria-label="<%= t("share_theme.on-this-page") %>">
+ <%- include("tree_toc", { entries: toc }) %>
+ </nav>
+ <% } %>
<% if (item.children.length) { %>
<%- include("tree_item", { items: item.children }) %>
<% } %>
diff --git a/packages/share-theme/src/templates/tree_toc.ejs b/packages/share-theme/src/templates/tree_toc.ejs
new file mode 100644
index 0000000000..8bede2ccd7
--- /dev/null
+++ b/packages/share-theme/src/templates/tree_toc.ejs
@@ -0,0 +1,10 @@
+<% for (const entry of entries) { %>
+ <div class="tree-toc-entry">
+ <a href="<%= entry.href %>"><%= entry.text %></a>
+ <% if (entry.children.length) { %>
+ <div class="tree-toc-children">
+ <%- include("tree_toc", { entries: entry.children }) %>
+ </div>
+ <% } %>
+ </div>
+<% } %>
diff --git a/packages/trilium-core/src/share/content_renderer.spec.ts b/packages/trilium-core/src/share/content_renderer.spec.ts
index ce0e368ced..d64f3382b6 100644
--- a/packages/trilium-core/src/share/content_renderer.spec.ts
+++ b/packages/trilium-core/src/share/content_renderer.spec.ts
@@ -372,7 +372,7 @@ describe("content_renderer", () => {
]);
});
- it("keeps an empty table of contents pane, and its toggle out, for fewer than two headings", () => {
+ it("keeps an empty table of contents pane, and none in the tree, for fewer than two headings", () => {
const shareRootNote = buildShareNote({
id: shareRoot.SHARE_ROOT_NOTE_ID,
children: [{ id: "oneHeading", content: `<h2>Only</h2><p>a</p>` }]
@@ -381,7 +381,40 @@ describe("content_renderer", () => {
const page = parse(String(renderNoteContent(shareRootNote.getChildNotes()[0])));
expect(page.querySelector("#toc-pane")?.innerHTML).toBe("");
+ expect(page.querySelector(".tree-toc") === null).toBe(true);
+ });
+
+ it("lists the table of contents in the tree below the page, or above it for the site's page", () => {
+ const shareRootNote = buildShareNote({
+ id: shareRoot.SHARE_ROOT_NOTE_ID,
+ children: [{
+ id: "tocSite",
+ title: "Site",
+ content: `<h2>Site one</h2><p>a</p><h2>Site two</h2><p>b</p>`,
+ children: [{
+ id: "tocPage",
+ title: "Page",
+ content: `<h2>One</h2><p>a</p><h3>Two</h3><p>b</p>`
+ }]
+ }]
+ });
+ const site = shareRootNote.getChildNotes()[0];
+ const tocLinks = (page: ReturnType<typeof parse>, toc: string) => page
+ .querySelectorAll(`${toc} a`).map((link) => link.getAttribute("href"));
+
+ const page = parse(String(renderNoteContent(site.getChildNotes()[0])));
+ const pageToc = "#menu li[data-note-id=\"tocPage\"] > .tree-toc";
+ expect(tocLinks(page, pageToc)).toStrictEqual([ "#one", "#two" ]);
+ expect(tocLinks(page, `${pageToc} .tree-toc-children`)).toStrictEqual([ "#two" ]);
+ expect(page.querySelectorAll(".tree-toc")).toHaveLength(1);
expect(page.querySelector("#toc-pane-toggle-button") === null).toBe(true);
+
+ const sitePage = parse(String(renderNoteContent(site)));
+ expect(tocLinks(sitePage, "#navigation > .tree-toc"))
+ .toStrictEqual([ "#site-one", "#site-two" ]);
+ expect(sitePage.querySelector("#navigation > .tree-toc > #tree-toc-title")?.text)
+ .toBe(t("share_theme.on-this-page"));
+ expect(sitePage.querySelectorAll(".tree-toc")).toHaveLength(1);
});
it("links the table of contents to a heading's own ID, URL-encoded", () => {
@@ -1469,7 +1502,8 @@ describe("content_renderer", () => {
language: { page: { lang: "en", dir: "ltr" }, content: null },
lastUpdated: null,
headings: [],
- toc: []
+ toc: [],
+ isPageInNavigation: false
}, {
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 aa968f5e26..a11ef869cb 100644
--- a/packages/trilium-core/src/share/content_renderer.ts
+++ b/packages/trilium-core/src/share/content_renderer.ts
@@ -9,7 +9,7 @@ import { renderSpreadsheetToHtml } from "@triliumnext/commons/src/lib/spreadshee
import { getLanguage, highlight, highlightAuto, syncMimeTypes } from "@triliumnext/highlightjs";
import {
getChildLinks, getChildLinksLayout, getContentClasses, getHtmlSnippets, getLastUpdated, getNavigationTree, getPageHead, getPageLanguages,
- getPrevNextLinks, getShareLink, getSiteAncestorIds, getSiteLogo, getTableOfContents,
+ getPrevNextLinks, getShareLink, getSiteAncestorIds, getSiteLogo, getTableOfContents, hasActiveItem,
type NavigationItem, type PageHeading
} from "@triliumnext/share-theme/model/page";
import ejs from "ejs";
@@ -335,7 +335,13 @@ function renderNoteContentInternal(note: SNote | BNote, renderArgs: RenderArgs)
headingLinkLabel: t("share_theme.heading-link")
})
: { content, headings: [] };
- const pageOpts = { ...opts, content: pageContent, headings, toc: getTableOfContents(headings) };
+ const pageOpts = {
+ ...opts,
+ content: pageContent,
+ headings,
+ toc: getTableOfContents(headings),
+ isPageInNavigation: hasActiveItem(navigation)
+ };
return ejs.render(readShareTemplate("page"), pageOpts, {
includer: (path) => ({ template: readShareTemplate(path) })
});