Skip to content

Build your personal knowledge base with Trilium Notes

feat(share): remember the tree's expanded pages across the pages of a site

Elian Doran8c7b11c77f18
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 da72e6ac05..282550d095 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
@@ -17,7 +17,9 @@ class="image">
<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>
- <li>Collapsible tree with the same note icons as the application.</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>
<li>Customizable logo.</li>
<li>Quick navigation buttons (previous and next note).</li>
<li>Displaying the date of the last update of the note, written out in the
diff --git a/docs/User Guide/User Guide/Advanced Usage/Sharing.md b/docs/User Guide/User Guide/Advanced Usage/Sharing.md
index de96dc9da5..7c3dcc7cb0 100644
--- a/docs/User Guide/User Guide/Advanced Usage/Sharing.md
+++ b/docs/User Guide/User Guide/Advanced Usage/Sharing.md
@@ -8,7 +8,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.
-* Collapsible tree with the same note icons as the application.
+* 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).
* Displaying the date of the last update of the note, written out in the application's language.
diff --git a/packages/share-theme/src/index.spec.ts b/packages/share-theme/src/index.spec.ts
index 0ce39b209d..5686ff860f 100644
--- a/packages/share-theme/src/index.spec.ts
+++ b/packages/share-theme/src/index.spec.ts
@@ -4,7 +4,7 @@ import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
setupLayout: vi.fn(),
setupExpanders: vi.fn(),
- setupTreeScroll: vi.fn(),
+ setupTreeState: vi.fn(),
setupThemeSelector: vi.fn().mockImplementation(() => {
throw new Error("theme switch failed");
}),
@@ -21,7 +21,7 @@ const mocks = vi.hoisted(() => ({
vi.mock("./page/layout.js", () => ({ default: mocks.setupLayout }));
vi.mock("./page/navigation.js", () => ({
default: mocks.setupExpanders,
- setupTreeScroll: mocks.setupTreeScroll
+ setupTreeState: mocks.setupTreeState
}));
vi.mock("./page/theme_switch.js", () => ({ default: mocks.setupThemeSelector }));
vi.mock("./page/search.js", () => ({ default: mocks.setupSearch }));
@@ -48,7 +48,7 @@ describe("share theme entry", () => {
await import("./index.js");
await vi.waitFor(() => expect(consoleError).toHaveBeenCalledTimes(2));
pageSetupCalls = [ mocks.setupThemeSelector, mocks.setupToC, mocks.setupExpanders,
- mocks.setupTreeScroll, mocks.setupLayout, mocks.setupSearch, mocks.setupFooter ]
+ mocks.setupTreeState, mocks.setupLayout, mocks.setupSearch, mocks.setupFooter ]
.map((setup) => setup.mock.calls.length);
loggedErrors = consoleError.mock.calls.map(([ error ]) => (error as Error).message);
});
diff --git a/packages/share-theme/src/index.ts b/packages/share-theme/src/index.ts
index 153e635b9f..e8e781cc4f 100644
--- a/packages/share-theme/src/index.ts
+++ b/packages/share-theme/src/index.ts
@@ -3,7 +3,7 @@
import "./base.css";
import setupLayout from "./page/layout.js";
import "./page/header.css";
-import setupExpanders, { setupTreeScroll } from "./page/navigation.js";
+import setupExpanders, { setupTreeState } from "./page/navigation.js";
import setupThemeSelector from "./page/theme_switch.js";
import setupSearch from "./page/search.js";
import setupToC from "./page/toc.js";
@@ -47,7 +47,7 @@ Object.assign(window, { fetchNote });
$try(setupThemeSelector);
$try(setupToC);
$try(setupExpanders);
-$try(setupTreeScroll);
+$try(setupTreeState);
$try(setupLayout);
$try(setupSearch);
$try(setupFooter);
diff --git a/packages/share-theme/src/model/page.ts b/packages/share-theme/src/model/page.ts
index aed4316a18..ee5d670ab0 100644
--- a/packages/share-theme/src/model/page.ts
+++ b/packages/share-theme/src/model/page.ts
@@ -40,6 +40,7 @@ export interface ShareLink {
/** An entry of the navigation tree, with the entries below it. */
export interface NavigationItem extends ShareLink {
+ noteId: string;
title: string;
type: string;
icon: string;
@@ -375,6 +376,7 @@ export function getNavigationTree(
const expandedIds = new Set([ activeNote.noteId, ...ancestorIds ]);
const toItem = (note: ShareNote): NavigationItem => ({
...getShareLink(note, options.sanitizeUrl),
+ noteId: note.noteId,
title: note.title,
type: note.type,
icon: note.getIcon(options.iconPackPrefixes),
diff --git a/packages/share-theme/src/page/navigation.spec.ts b/packages/share-theme/src/page/navigation.spec.ts
index c04d60bf57..ee430ef653 100644
--- a/packages/share-theme/src/page/navigation.spec.ts
+++ b/packages/share-theme/src/page/navigation.spec.ts
@@ -1,7 +1,7 @@
// @vitest-environment happy-dom
import { afterEach, describe, expect, it, vi } from "vitest";
-import setupExpanders, { setupTreeScroll } from "./navigation.js";
+import setupExpanders, { setupTreeState } from "./navigation.js";
describe("setupExpanders", () => {
afterEach(() => {
@@ -70,7 +70,7 @@ describe("setupExpanders", () => {
});
});
-describe("setupTreeScroll", () => {
+describe("setupTreeState", () => {
afterEach(() => {
vi.unstubAllGlobals();
document.body.innerHTML = "";
@@ -80,45 +80,73 @@ describe("setupTreeScroll", () => {
it("restores the pane's position on another page of the same site only", () => {
renderPane("site1", { activeTop: 120 });
- sessionStorage.setItem("share-tree-scroll", JSON.stringify({ siteId: "site1", top: 80 }));
- setupTreeScroll();
+ sessionStorage.setItem("share-tree-state", JSON.stringify({ siteId: "site1", top: 80 }));
+ setupTreeState();
expect(pane().scrollTop).toBe(80);
pane().scrollTop = 30;
window.dispatchEvent(new Event("pagehide"));
- expect(JSON.parse(sessionStorage.getItem("share-tree-scroll") ?? "null"))
- .toStrictEqual({ siteId: "site1", top: 30 });
+ expect(JSON.parse(sessionStorage.getItem("share-tree-state") ?? "null"))
+ .toStrictEqual({ siteId: "site1", top: 30, expanded: [] });
renderPane("site2", { activeTop: 120 });
- setupTreeScroll();
+ setupTreeState();
expect(pane().scrollTop).toBe(0);
});
+ it("remembers the expanded pages of a site, also on pages that expand others", () => {
+ renderPane("site1", { menu: TREE });
+ setupExpanders();
+ setupTreeState();
+ toggle("section").click();
+ window.dispatchEvent(new Event("pagehide"));
+ expect(JSON.parse(sessionStorage.getItem("share-tree-state") ?? "null").expanded)
+ .toStrictEqual([ "chapter", "section" ]);
+
+ const collapsedChapter = TREE.replace(`"submenu-item expanded" data-note-id="chapter"`,
+ `"submenu-item" data-note-id="chapter"`);
+ renderPane("site1", { menu: collapsedChapter });
+ setupTreeState();
+ expect(expandedIds()).toStrictEqual([ "chapter", "section" ]);
+ expect([ "chapter", "section" ].map((id) => toggle(id).getAttribute("aria-expanded")))
+ .toStrictEqual([ "true", "true" ]);
+
+ renderPane("site2", { menu: TREE });
+ setupTreeState();
+ expect(expandedIds()).toStrictEqual([ "chapter" ]);
+
+ const malformed = { siteId: "site1", top: 0, expanded: "x" };
+ sessionStorage.setItem("share-tree-state", JSON.stringify(malformed));
+ renderPane("site1", { menu: TREE });
+ setupTreeState();
+ expect(expandedIds()).toStrictEqual([ "chapter" ]);
+ });
+
it("centers the current note when it is out of view, and leaves it when it is in view", () => {
renderPane("site1", { activeTop: 700 });
- setupTreeScroll();
+ setupTreeState();
// 700 - 0 - (400 - 32) / 2
expect(pane().scrollTop).toBe(516);
renderPane("site1", { activeTop: 380 });
- setupTreeScroll();
+ setupTreeState();
expect(pane().scrollTop).toBe(196);
- sessionStorage.setItem("share-tree-scroll", JSON.stringify({ siteId: "site1", top: 300 }));
+ sessionStorage.setItem("share-tree-state", JSON.stringify({ siteId: "site1", top: 300 }));
renderPane("site1", { activeTop: 250 });
- setupTreeScroll();
+ setupTreeState();
expect(pane().scrollTop).toBe(66);
sessionStorage.clear();
renderPane("site1", { activeTop: 368 });
- setupTreeScroll();
+ setupTreeState();
expect(pane().scrollTop).toBe(0);
});
it("ignores a malformed position and works with blocked storage or without a pane", () => {
renderPane("site1");
- sessionStorage.setItem("share-tree-scroll", "{");
- setupTreeScroll();
+ sessionStorage.setItem("share-tree-state", "{");
+ setupTreeState();
expect(pane().scrollTop).toBe(0);
const blocked = () => {
@@ -126,16 +154,16 @@ describe("setupTreeScroll", () => {
};
vi.stubGlobal("sessionStorage", { getItem: blocked, setItem: blocked });
renderPane("site1");
- setupTreeScroll();
+ setupTreeState();
expect(() => window.dispatchEvent(new Event("pagehide"))).not.toThrow();
vi.unstubAllGlobals();
renderPane("site1");
delete document.body.dataset.ancestorNoteId;
- expect(() => setupTreeScroll()).not.toThrow();
+ expect(() => setupTreeState()).not.toThrow();
document.body.innerHTML = "";
- expect(() => setupTreeScroll()).not.toThrow();
+ expect(() => setupTreeState()).not.toThrow();
});
});
@@ -143,16 +171,14 @@ describe("setupTreeScroll", () => {
* Renders a 400px tall pane at the top of the window, with a current note of 32px at `activeTop`
* when it is given; happy-dom has no layout, so the geometry is set by hand.
*/
-function renderPane(siteId: string, { activeTop }: { activeTop?: number } = {}) {
+function renderPane(siteId: string, options: { activeTop?: number; menu?: string } = {}) {
+ const { activeTop, menu = NOTE } = options;
document.body.dataset.ancestorNoteId = siteId;
- document.body.innerHTML = `
- <div id="left-pane">
- <nav id="menu"><ul><li><a class="active" href="./note">Note</a></li></ul></nav>
- </div>`;
+ document.body.innerHTML = `<div id="left-pane"><nav id="menu">${menu}</nav></div>`;
const paneEl = pane();
Object.defineProperty(paneEl, "clientHeight", { value: 400 });
paneEl.getBoundingClientRect = () => new DOMRect(0, 0, 200, 400);
- const active = paneEl.querySelector("a");
+ const active = paneEl.querySelector<HTMLElement>("a.active");
if (activeTop === undefined) {
active?.remove();
} else if (active) {
@@ -167,3 +193,46 @@ function pane() {
}
return paneEl;
}
+
+const NOTE = `<ul><li><a class="active" href="./note">Note</a></li></ul>`;
+
+/** A chapter the server expanded, with a section inside it and a section of another chapter. */
+const TREE = `
+ <ul>
+ <li class="submenu-item expanded" data-note-id="chapter">
+ <div class="tree-item-row">
+ <button class="collapse-button" aria-expanded="true"></button>
+ <a href="./chapter">Chapter</a>
+ </div>
+ <ul>
+ <li class="submenu-item" data-note-id="section">
+ <div class="tree-item-row">
+ <button class="collapse-button" aria-expanded="false"></button>
+ <a href="./section">Section</a>
+ </div>
+ <ul><li class="item" data-note-id="page"><a href="./page">Page</a></li></ul>
+ </li>
+ </ul>
+ </li>
+ <li class="submenu-item" data-note-id="other">
+ <div class="tree-item-row">
+ <button class="collapse-button" aria-expanded="false"></button>
+ <a href="./other">Other</a>
+ </div>
+ <ul><li class="item" data-note-id="leaf"><a href="./leaf">Leaf</a></li></ul>
+ </li>
+ </ul>`;
+
+function toggle(noteId: string) {
+ const selector = `li[data-note-id="${noteId}"] .collapse-button`;
+ const button = document.querySelector<HTMLButtonElement>(selector);
+ if (!button) {
+ throw new Error(`The tree has no button for ${noteId}.`);
+ }
+ return button;
+}
+
+function expandedIds() {
+ return [ ...document.querySelectorAll<HTMLElement>("#menu li.expanded") ]
+ .map((li) => li.dataset.noteId);
+}
diff --git a/packages/share-theme/src/page/navigation.ts b/packages/share-theme/src/page/navigation.ts
index bc1ee94392..b26787b917 100644
--- a/packages/share-theme/src/page/navigation.ts
+++ b/packages/share-theme/src/page/navigation.ts
@@ -49,22 +49,30 @@ export default function setupExpanders() {
}
}
-const TREE_SCROLL_KEY = "share-tree-scroll";
+const TREE_STATE_KEY = "share-tree-state";
+
+/** What the navigation pane keeps from one page of a site to the next. */
+interface TreeState {
+ siteId: string | undefined;
+ top: number;
+ expanded: string[];
+}
/**
- * Keeps the navigation pane's scroll position across the pages of a site, which are separate
- * documents, and brings the current note into view when that position would hide it. The position
- * is kept per site, keyed by `data-ancestor-note-id`, in `sessionStorage`.
+ * Keeps the navigation pane's expanded pages and scroll position across the pages of a site, which
+ * are separate documents, and brings the current note into view when that position would hide it.
+ * The state is kept per site, keyed by `data-ancestor-note-id`, in `sessionStorage`.
*/
-export function setupTreeScroll() {
+export function setupTreeState() {
const pane = document.getElementById("left-pane");
if (!pane) {
return;
}
const siteId = document.body.dataset.ancestorNoteId;
- const saved = readTreeScroll();
+ const saved = readTreeState();
if (saved && saved.siteId === siteId) {
+ expandItems(pane, saved.expanded);
pane.scrollTop = saved.top;
}
@@ -79,18 +87,33 @@ export function setupTreeScroll() {
}
window.addEventListener("pagehide", () => {
+ const expandedItems = pane.querySelectorAll<HTMLElement>("#menu li.expanded[data-note-id]");
+ const expanded = [ ...expandedItems ].map((item) => item.dataset.noteId);
+ const state = { siteId, top: pane.scrollTop, expanded };
try {
- const position = JSON.stringify({ siteId, top: pane.scrollTop });
- sessionStorage.setItem(TREE_SCROLL_KEY, position);
+ sessionStorage.setItem(TREE_STATE_KEY, JSON.stringify(state));
} catch {
- // The next page then starts from the current note.
+ // The next page then starts from the server's expansion and the current note.
}
});
}
-function readTreeScroll(): { siteId: string; top: number } | null {
+/** Expands the entries of the notes in `noteIds`, every clone of each, without animating. */
+function expandItems(pane: HTMLElement, noteIds: string[]) {
+ const ids = new Set(noteIds);
+ for (const item of pane.querySelectorAll<HTMLElement>("#menu li.submenu-item[data-note-id]")) {
+ if (!item.dataset.noteId || !ids.has(item.dataset.noteId)) {
+ continue;
+ }
+ item.classList.add("expanded");
+ item.querySelector(":scope > * > .collapse-button")?.setAttribute("aria-expanded", "true");
+ }
+}
+
+function readTreeState(): TreeState | null {
try {
- return JSON.parse(sessionStorage.getItem(TREE_SCROLL_KEY) ?? "null");
+ const state = JSON.parse(sessionStorage.getItem(TREE_STATE_KEY) ?? "null");
+ return state && { ...state, expanded: Array.isArray(state.expanded) ? state.expanded : [] };
} catch {
return null;
}
diff --git a/packages/share-theme/src/templates/tree_item.ejs b/packages/share-theme/src/templates/tree_item.ejs
index 892ca46270..fcf87f6149 100644
--- a/packages/share-theme/src/templates/tree_item.ejs
+++ b/packages/share-theme/src/templates/tree_item.ejs
@@ -1,6 +1,6 @@
<ul>
<% for (const item of items) { %>
- <li class="<%= item.children.length ? "submenu-item" : "item" %><%= item.isExpanded ? " expanded" : "" %>">
+ <li class="<%= item.children.length ? "submenu-item" : "item" %><%= item.isExpanded ? " expanded" : "" %>" data-note-id="<%= item.noteId %>">
<div class="tree-item-row<%= item.isActive ? " active" : "" %>">
<% if (item.children.length) { %><button type="button" class="collapse-button" aria-expanded="<%= item.isExpanded %>" aria-label="<%= t("share_theme.subpages-of", { title: item.title }) %>"><span class="tn-icon bx bx-chevron-down" aria-hidden="true"></span></button><% } %>
<a class="type-<%= item.type %> no-arrow<%= item.isActive ? " active" : "" %>" href="<%= item.href %>"<% if (item.isExternal) { %> target="_blank" rel="noopener noreferrer"<% } %>>
diff --git a/packages/trilium-core/src/share/content_renderer.spec.ts b/packages/trilium-core/src/share/content_renderer.spec.ts
index be65ae65ca..910de6730f 100644
--- a/packages/trilium-core/src/share/content_renderer.spec.ts
+++ b/packages/trilium-core/src/share/content_renderer.spec.ts
@@ -1260,6 +1260,8 @@ describe("content_renderer", () => {
const toggleAttributes = [ "type", "aria-expanded", "aria-label" ]
.map((name) => toggles[0].getAttribute(name));
expect(toggleAttributes).toStrictEqual([ "button", "true", "Subpages of Section" ]);
+ expect(menu?.querySelectorAll("li").map((item) => item.getAttribute("data-note-id")))
+ .toStrictEqual([ "treeSection", "treeShown", "treeExternal" ]);
expect(menu?.querySelectorAll("li.expanded").map((item) => item.querySelector("a")?.text.trim()))
.toStrictEqual([ "Section", "Shown" ]);
});