Skip to content

Build your personal knowledge base with Trilium Notes

feat(share): keep the tree's scroll position across the pages of a site

Elian Doranfc8ee01ef9bf
diff --git a/packages/share-theme/src/index.spec.ts b/packages/share-theme/src/index.spec.ts
index c347b3b3dc..0ce39b209d 100644
--- a/packages/share-theme/src/index.spec.ts
+++ b/packages/share-theme/src/index.spec.ts
@@ -4,6 +4,7 @@ import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
setupLayout: vi.fn(),
setupExpanders: vi.fn(),
+ setupTreeScroll: vi.fn(),
setupThemeSelector: vi.fn().mockImplementation(() => {
throw new Error("theme switch failed");
}),
@@ -18,7 +19,10 @@ const mocks = vi.hoisted(() => ({
}));
vi.mock("./page/layout.js", () => ({ default: mocks.setupLayout }));
-vi.mock("./page/navigation.js", () => ({ default: mocks.setupExpanders }));
+vi.mock("./page/navigation.js", () => ({
+ default: mocks.setupExpanders,
+ setupTreeScroll: mocks.setupTreeScroll
+}));
vi.mock("./page/theme_switch.js", () => ({ default: mocks.setupThemeSelector }));
vi.mock("./page/search.js", () => ({ default: mocks.setupSearch }));
vi.mock("./page/toc.js", () => ({ default: mocks.setupToC }));
@@ -44,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.setupLayout, mocks.setupSearch, mocks.setupFooter ]
+ mocks.setupTreeScroll, mocks.setupLayout, mocks.setupSearch, mocks.setupFooter ]
.map((setup) => setup.mock.calls.length);
loggedErrors = consoleError.mock.calls.map(([ error ]) => (error as Error).message);
});
@@ -57,7 +61,7 @@ describe("share theme entry", () => {
});
it("sets up every part of the page, logging what one throws or rejects with", () => {
- expect(pageSetupCalls).toEqual([ 1, 1, 1, 1, 1, 1 ]);
+ expect(pageSetupCalls).toEqual([ 1, 1, 1, 1, 1, 1, 1 ]);
expect(loggedErrors.sort()).toEqual([ "search failed", "theme switch failed" ]);
});
diff --git a/packages/share-theme/src/index.ts b/packages/share-theme/src/index.ts
index 30f913494f..153e635b9f 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 from "./page/navigation.js";
+import setupExpanders, { setupTreeScroll } from "./page/navigation.js";
import setupThemeSelector from "./page/theme_switch.js";
import setupSearch from "./page/search.js";
import setupToC from "./page/toc.js";
@@ -47,6 +47,7 @@ Object.assign(window, { fetchNote });
$try(setupThemeSelector);
$try(setupToC);
$try(setupExpanders);
+$try(setupTreeScroll);
$try(setupLayout);
$try(setupSearch);
$try(setupFooter);
diff --git a/packages/share-theme/src/page/navigation.spec.ts b/packages/share-theme/src/page/navigation.spec.ts
index 8ee52ea027..a05a08aa55 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 from "./navigation.js";
+import setupExpanders, { setupTreeScroll } from "./navigation.js";
describe("setupExpanders", () => {
afterEach(() => {
@@ -64,3 +64,101 @@ describe("setupExpanders", () => {
expect(document.querySelector(".expanded")).toBeNull();
});
});
+
+describe("setupTreeScroll", () => {
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ document.body.innerHTML = "";
+ delete document.body.dataset.ancestorNoteId;
+ sessionStorage.clear();
+ });
+
+ 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();
+ 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 });
+
+ renderPane("site2", { activeTop: 120 });
+ setupTreeScroll();
+ expect(pane().scrollTop).toBe(0);
+ });
+
+ it("centers the current note when it is out of view, and leaves it when it is in view", () => {
+ renderPane("site1", { activeTop: 700 });
+ setupTreeScroll();
+ // 700 - 0 - (400 - 32) / 2
+ expect(pane().scrollTop).toBe(516);
+
+ renderPane("site1", { activeTop: 380 });
+ setupTreeScroll();
+ expect(pane().scrollTop).toBe(196);
+
+ sessionStorage.setItem("share-tree-scroll", JSON.stringify({ siteId: "site1", top: 300 }));
+ renderPane("site1", { activeTop: 250 });
+ setupTreeScroll();
+ expect(pane().scrollTop).toBe(66);
+ sessionStorage.clear();
+
+ renderPane("site1", { activeTop: 368 });
+ setupTreeScroll();
+ 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();
+ expect(pane().scrollTop).toBe(0);
+
+ const blocked = () => {
+ throw new Error("Storage is blocked.");
+ };
+ vi.stubGlobal("sessionStorage", { getItem: blocked, setItem: blocked });
+ renderPane("site1");
+ setupTreeScroll();
+ expect(() => window.dispatchEvent(new Event("pagehide"))).not.toThrow();
+
+ vi.unstubAllGlobals();
+ renderPane("site1");
+ delete document.body.dataset.ancestorNoteId;
+ expect(() => setupTreeScroll()).not.toThrow();
+
+ document.body.innerHTML = "";
+ expect(() => setupTreeScroll()).not.toThrow();
+ });
+});
+
+/**
+ * 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 } = {}) {
+ 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>`;
+ const paneEl = pane();
+ Object.defineProperty(paneEl, "clientHeight", { value: 400 });
+ paneEl.getBoundingClientRect = () => new DOMRect(0, 0, 200, 400);
+ const active = paneEl.querySelector("a");
+ if (activeTop === undefined) {
+ active?.remove();
+ } else if (active) {
+ active.getBoundingClientRect = () => new DOMRect(0, activeTop - paneEl.scrollTop, 200, 32);
+ }
+}
+
+function pane() {
+ const paneEl = document.getElementById("left-pane");
+ if (!paneEl) {
+ throw new Error("The pane is missing.");
+ }
+ return paneEl;
+}
diff --git a/packages/share-theme/src/page/navigation.ts b/packages/share-theme/src/page/navigation.ts
index 3a1ec4f999..592fa7f9a4 100644
--- a/packages/share-theme/src/page/navigation.ts
+++ b/packages/share-theme/src/page/navigation.ts
@@ -46,3 +46,50 @@ export default function setupExpanders() {
});
}
}
+
+const TREE_SCROLL_KEY = "share-tree-scroll";
+
+/**
+ * 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`.
+ */
+export function setupTreeScroll() {
+ const pane = document.getElementById("left-pane");
+ if (!pane) {
+ return;
+ }
+ const siteId = document.body.dataset.ancestorNoteId;
+
+ const saved = readTreeScroll();
+ if (saved && saved.siteId === siteId) {
+ pane.scrollTop = saved.top;
+ }
+
+ const active = pane.querySelector<HTMLElement>("#menu a.active");
+ if (active) {
+ const paneRect = pane.getBoundingClientRect();
+ const activeRect = active.getBoundingClientRect();
+ if (activeRect.top < paneRect.top || activeRect.bottom > paneRect.bottom) {
+ const centered = (pane.clientHeight - activeRect.height) / 2;
+ pane.scrollTop += activeRect.top - paneRect.top - centered;
+ }
+ }
+
+ window.addEventListener("pagehide", () => {
+ try {
+ const position = JSON.stringify({ siteId, top: pane.scrollTop });
+ sessionStorage.setItem(TREE_SCROLL_KEY, position);
+ } catch {
+ // The next page then starts from the current note.
+ }
+ });
+}
+
+function readTreeScroll(): { siteId: string; top: number } | null {
+ try {
+ return JSON.parse(sessionStorage.getItem(TREE_SCROLL_KEY) ?? "null");
+ } catch {
+ return null;
+ }
+}