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
perf(share): render-block only the tree's restore, not the whole theme script
Elian Doran4e211b2cee3b
diff --git a/.claude/skills/developing-share-pages/SKILL.md b/.claude/skills/developing-share-pages/SKILL.mdindex e6419c8be7..67e2286a10 100644--- a/.claude/skills/developing-share-pages/SKILL.md+++ b/.claude/skills/developing-share-pages/SKILL.md@@ -30,7 +30,8 @@ packages/share-theme/src/page/ page chrome: one script next to its CSS (layout, header, navigation,search, toc, theme_switch, footer)src/content/ content enhancements (math, mermaid) and content CSS- scripts/build.ts esbuild → dist/scripts.js + dist/scripts.css (run by tsx)+ scripts/build.ts esbuild → dist/scripts.js + dist/scripts.css, and dist/tree.js on its own+ (no code splitting, so it loads as one file) (run by tsx)````packages/share-theme/package.json` exports `./templates/*` and `./model/*` **from source** (core@@ -53,7 +54,9 @@ imports the model as `@triliumnext/share-theme/model/page`); everything else resthe content as it is. The default `page.ejs` additionally gets the output of`preparePageContent()`: content with heading anchors and image `alt`/`loading`, `headings` and`toc`.-5. **Browser** — `scripts.js` wires the tree, search, ToC scroll tracking, theme switch, footer+5. **Browser** — `tree.js`, the first entry of `jsToLoad` and the only `blocking="render"` one,+ restores the tree's expansion, scroll position and clicked clone before the first paint.+ `scripts.js` then wires the expand buttons, search, ToC scroll tracking, theme switch, footerdate, math, Mermaid, link previews and tabs. `boot_script.ejs` runs inline in `<head>` before thefirst paint (theme class, collapsed panes, `window.glob`).@@ -107,6 +110,9 @@ template* page of the User Guide. So:- **No inline scripts besides `boot_script.ejs`.** Top-level `const`/`let` in a classic inlinescript is a global binding shared with `~shareHtml` snippets — keep everything inside the IIFE.`boot_script.spec.ts` enforces both and that `page.ejs` has no `<script>`.+- Code that must run before the first paint and needs the DOM goes in `tree.ts`'s bundle, which is+ render-blocking; keep it small, since every page waits for it. Everything else stays in+ `scripts.js`, and `~shareJs` scripts never block.- Anything needed before the first paint is driven from the root class the boot script sets(`theme-dark`/`theme-light`, `left-pane-collapsed`) — the theme switch is styled from it, notfrom `:checked`, so it needs no script to look right.diff --git a/packages/share-theme/scripts/build.ts b/packages/share-theme/scripts/build.tsindex 6b8fb81e73..5f4c9615ab 100644--- a/packages/share-theme/scripts/build.ts+++ b/packages/share-theme/scripts/build.ts@@ -93,11 +93,22 @@ async function runBuild(watch: boolean) {metafile: true,minify: process.argv.includes("--minify")};+ // `tree.js` runs before the page is first drawn, so it is built without splitting: the code it+ // shares with `scripts.js` is inlined rather than moved into a chunk it would wait for.+ const treeOpts: esbuild.BuildOptions = {+ entryPoints: [ { in: path.join(rootDir, "src", "tree.ts"), out: "tree" } ],+ bundle: true,+ outdir: outDir,+ format: "esm",+ target: opts.target,+ logLevel: "info",+ minify: opts.minify+ };if (watch) {- const ctx = esbuild.context(opts);- (await ctx).watch();+ const contexts = await Promise.all([ esbuild.context(opts), esbuild.context(treeOpts) ]);+ await Promise.all(contexts.map((context) => context.watch()));} else {- const result = await esbuild.build(opts);+ const [ result ] = await Promise.all([ esbuild.build(opts), esbuild.build(treeOpts) ]);const after = performance.now();writeFileSync("meta.json", JSON.stringify(result.metafile, null, 2));console.log(`Build actually took ${(after - before).toFixed(2)}ms`);diff --git a/packages/share-theme/src/index.spec.ts b/packages/share-theme/src/index.spec.tsindex 84c6e706c3..6e47fab8b7 100644--- a/packages/share-theme/src/index.spec.ts+++ b/packages/share-theme/src/index.spec.ts@@ -4,7 +4,6 @@ import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";const mocks = vi.hoisted(() => ({setupLayout: vi.fn(),setupExpanders: vi.fn(),- setupTreeState: vi.fn(),setupThemeSelector: vi.fn().mockImplementation(() => {throw new Error("theme switch failed");}),@@ -21,10 +20,7 @@ const mocks = vi.hoisted(() => ({}));vi.mock("./page/layout.js", () => ({ default: mocks.setupLayout }));-vi.mock("./page/navigation.js", () => ({- default: mocks.setupExpanders,- setupTreeState: mocks.setupTreeState-}));+vi.mock("./page/navigation.js", () => ({ default: mocks.setupExpanders }));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 }));@@ -55,7 +51,7 @@ describe("share theme entry", () => {await import("./index.js");await vi.waitFor(() => expect(consoleError).toHaveBeenCalledTimes(2));pageSetupCalls = [ mocks.setupThemeSelector, mocks.setupToC, mocks.setupExpanders,- mocks.setupTreeState, mocks.setupLayout, mocks.setupSearch, mocks.setupFooter,+ mocks.setupLayout, mocks.setupSearch, mocks.setupFooter,mocks.setupSpeculation ].map((setup) => setup.mock.calls.length);deferredSetups = mocks.whenActivated.mock.calls.length;@@ -70,9 +66,9 @@ 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, 1, 1 ]);- // The theme and the tree's state wait for a prerendered page to be shown.- expect(deferredSetups).toBe(2);+ expect(pageSetupCalls).toEqual([ 1, 1, 1, 1, 1, 1, 1 ]);+ // The theme waits for a prerendered page to be shown.+ expect(deferredSetups).toBe(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.tsindex 23dd8c8e1b..40de05f566 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, { setupTreeState } from "./page/navigation.js";+import setupExpanders from "./page/navigation.js";import setupThemeSelector from "./page/theme_switch.js";import setupSearch from "./page/search.js";import setupToC from "./page/toc.js";@@ -45,11 +45,11 @@ async function fetchNote(noteId: string | null = null) {}Object.assign(window, { fetchNote });-// A prerendered page reads the theme and the tree's state once it is shown, not while prerendering.+// A prerendered page reads the theme once it is shown, not while prerendering. `tree.ts` restores+// the tree, before the page is first drawn.whenActivated(() => $try(setupThemeSelector));$try(setupToC);$try(setupExpanders);-whenActivated(() => $try(setupTreeState));$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.tsindex 6c7dd6e268..1276d2bf3a 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-domimport { afterEach, describe, expect, it, vi } from "vitest";-import setupExpanders, { setupTreeState } from "./navigation.js";+import setupExpanders from "./navigation.js";describe("setupExpanders", () => {afterEach(() => {@@ -69,284 +69,3 @@ describe("setupExpanders", () => {expect(document.querySelector(".expanded")).toBeNull();});});--describe("setupTreeState", () => {- afterEach(() => {- vi.unstubAllGlobals();- document.body.innerHTML = "";- delete document.body.dataset.ancestorNoteId;- delete document.body.dataset.noteId;- sessionStorage.clear();- });-- it("restores the pane's position on another page of the same site only", () => {- renderPane("site1", { activeTop: 120 });- 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-state") ?? "null"))- .toStrictEqual({ siteId: "site1", top: 30, expanded: [] });-- renderPane("site2", { activeTop: 120 });- setupTreeState();- expect(pane().scrollTop).toBe(0);- });-- it("saves the pane's state before a prerendered page replaces this one", () => {- renderPane("site1", { activeTop: 120 });- setupTreeState();- pane().scrollTop = 40;- window.dispatchEvent(new Event("pageswap"));-- expect(JSON.parse(sessionStorage.getItem("share-tree-state") ?? "null"))- .toMatchObject({ siteId: "site1", top: 40 });- });-- 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("selects the clone of the current note that was clicked, on its own way down", () => {- const stayHere = (e: Event) => e.preventDefault();- document.addEventListener("click", stayHere);- renderPane("site1", { activeTop: 50, menu: CLONES });- document.body.dataset.noteId = "c";- setupTreeState();- pane().click();- cloneLink("y").click();- window.dispatchEvent(new Event("pagehide"));- document.removeEventListener("click", stayHere);- expect(JSON.parse(sessionStorage.getItem("share-tree-state") ?? "null").activePath)- .toStrictEqual([ "y", "c" ]);-- renderPane("site1", { activeTop: 50, menu: CLONES });- setupTreeState();- expect(selected()).toStrictEqual([ "y/row", "y/link" ]);- expect(expandedIds()).toStrictEqual([ "x", "c", "y", "c" ]);- expect(toggle("y").getAttribute("aria-expanded")).toBe("true");-- // The server's way to its own clone opens nothing above the clicked one that was closed.- const fromY = { siteId: "site1", top: 0, expanded: [ "y" ], activePath: [ "y", "c" ] };- sessionStorage.setItem("share-tree-state", JSON.stringify(fromY));- renderPane("site1", { activeTop: 50, menu: CLONES });- setupTreeState();- expect(selected()).toStrictEqual([ "y/row", "y/link" ]);- expect(expandedIds()).toStrictEqual([ "y", "c" ]);- expect(toggle("x").getAttribute("aria-expanded")).toBe("false");-- // The next page is another note, or the way no longer leads to a clone of it.- for (const activePath of [ [ "y", "d" ], [ "z", "c" ] ]) {- const state = { siteId: "site1", top: 0, expanded: [], activePath };- sessionStorage.setItem("share-tree-state", JSON.stringify(state));- renderPane("site1", { activeTop: 50, menu: CLONES });- setupTreeState();- expect(selected()).toStrictEqual([ "x/row", "x/link" ]);- }-- // A `tree_item` partial copied from an earlier theme gives its entries no note ID.- renderPane("site1", { activeTop: 50 });- document.addEventListener("click", stayHere);- setupTreeState();- document.querySelector<HTMLElement>("#menu a")?.click();- window.dispatchEvent(new Event("pagehide"));- document.removeEventListener("click", stayHere);- expect(JSON.parse(sessionStorage.getItem("share-tree-state") ?? "null").activePath)- .toStrictEqual([ "" ]);- });-- it("centers the current note when it is out of view, and leaves it when it is in view", () => {- renderPane("site1", { activeTop: 700 });- setupTreeState();- // 700 - 0 - (400 - 32) / 2- expect(pane().scrollTop).toBe(516);-- renderPane("site1", { activeTop: 380 });- setupTreeState();- expect(pane().scrollTop).toBe(196);-- sessionStorage.setItem("share-tree-state", JSON.stringify({ siteId: "site1", top: 300 }));- renderPane("site1", { activeTop: 250 });- setupTreeState();- expect(pane().scrollTop).toBe(66);- sessionStorage.clear();-- renderPane("site1", { activeTop: 368 });- setupTreeState();- expect(pane().scrollTop).toBe(0);-- // Below the pane's top but behind its 100px sticky header: 60 - 100 - (300 - 32) / 2- renderPane("site1", { activeTop: 60, headerHeight: 100 });- setupTreeState();- expect(pane().scrollTop).toBe(-174);- });-- it("ignores a malformed position and works with blocked storage or without a pane", () => {- renderPane("site1");- sessionStorage.setItem("share-tree-state", "{");- setupTreeState();- expect(pane().scrollTop).toBe(0);-- const blocked = () => {- throw new Error("Storage is blocked.");- };- vi.stubGlobal("sessionStorage", { getItem: blocked, setItem: blocked });- renderPane("site1");- setupTreeState();- expect(() => window.dispatchEvent(new Event("pagehide"))).not.toThrow();-- vi.unstubAllGlobals();- renderPane("site1");- delete document.body.dataset.ancestorNoteId;- expect(() => setupTreeState()).not.toThrow();-- document.body.innerHTML = "";- expect(() => setupTreeState()).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, options: { activeTop?: number; menu?: string; headerHeight?: number } = {}-) {- const { activeTop, menu = NOTE, headerHeight } = options;- document.body.dataset.ancestorNoteId = siteId;- document.body.innerHTML = `- <div id="left-pane"><div id="site-header"></div><nav id="menu">${menu}</nav></div>`;- const paneEl = pane();- const header = document.getElementById("site-header");- if (headerHeight === undefined) {- header?.remove();- } else if (header) {- header.getBoundingClientRect = () => new DOMRect(0, 0, 200, headerHeight);- }- Object.defineProperty(paneEl, "clientHeight", { value: 400 });- paneEl.getBoundingClientRect = () => new DOMRect(0, 0, 200, 400);- const active = paneEl.querySelector<HTMLElement>("a.active");- 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;-}--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);-}--/** A note cloned into two pages; the server selected the clone below `x`. */-const CLONES = `- <ul>- <li class="submenu-item expanded" data-note-id="x">- <div class="tree-item-row">- <button class="collapse-button" aria-expanded="true"></button><a>X</a>- </div>- <ul>- <li class="item expanded" data-note-id="c">- <div class="tree-item-row active"><a class="active" href="./c">C</a></div>- </li>- </ul>- </li>- <li class="submenu-item" data-note-id="y">- <div class="tree-item-row">- <button class="collapse-button" aria-expanded="false"></button><a>Y</a>- </div>- <ul>- <li class="item expanded" data-note-id="c">- <div class="tree-item-row"><a href="./c">C</a></div>- </li>- </ul>- </li>- </ul>`;--function cloneLink(parentId: string) {- const link = document.querySelector<HTMLElement>(`li[data-note-id="${parentId}"] li a`);- if (!link) {- throw new Error(`The tree has no clone below ${parentId}.`);- }- return link;-}--/** The selected rows and links, as the parent of their clone and what they are. */-function selected() {- return [ ...document.querySelectorAll<HTMLElement>("#menu .active") ].map((el) => {- const parent = el.closest("li")?.parentElement?.closest<HTMLElement>("li")?.dataset.noteId;- return `${parent}/${el.tagName === "A" ? "link" : "row"}`;- });-}diff --git a/packages/share-theme/src/page/navigation.ts b/packages/share-theme/src/page/navigation.tsindex 47ddb5eca2..81b68c132b 100644--- a/packages/share-theme/src/page/navigation.ts+++ b/packages/share-theme/src/page/navigation.ts@@ -48,165 +48,3 @@ export default function setupExpanders() {});}}--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[];- /** The note IDs from the top of the tree down to the entry that was clicked. */- activePath?: string[];-}--/**- * 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.- * Of a cloned note, the entry that was clicked stays the selected one. The state is kept per site,- * keyed by `data-ancestor-note-id`, in `sessionStorage`.- */-export function setupTreeState() {- const pane = document.getElementById("left-pane");- if (!pane) {- return;- }- const siteId = document.body.dataset.ancestorNoteId;-- const saved = readTreeState();- if (saved && saved.siteId === siteId) {- restoreTree(pane, saved);- pane.scrollTop = saved.top;- }-- const active = pane.querySelector<HTMLElement>("#menu a.active");- if (active) {- const paneRect = pane.getBoundingClientRect();- const activeRect = active.getBoundingClientRect();- // The sticky `#site-header` covers the top of the pane.- const visibleTop = pane.querySelector("#site-header")?.getBoundingClientRect().bottom- ?? paneRect.top;- if (activeRect.top < visibleTop || activeRect.bottom > paneRect.bottom) {- const visibleHeight = pane.clientHeight - (visibleTop - paneRect.top);- const centered = (visibleHeight - activeRect.height) / 2;- pane.scrollTop += activeRect.top - visibleTop - centered;- }- }-- let activePath: string[] | undefined;- pane.addEventListener("click", (e) => {- const item = e.target instanceof Element && e.target.closest("#menu a")?.closest("li");- if (item) {- activePath = getItemPath(item);- }- });-- // `pageswap` fires before a prerendered page is shown, `pagehide` only once this one unloads.- const saveState = () => {- 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, activePath };- try {- sessionStorage.setItem(TREE_STATE_KEY, JSON.stringify(state));- } catch {- // The next page then starts from the server's expansion and the current note.- }- };- window.addEventListener("pageswap", saveState);- window.addEventListener("pagehide", saveState);-}--/**- * Expands the saved entries, every clone of each, and selects the clicked entry of the current- * note, all without animating.- */-function restoreTree(pane: HTMLElement, state: TreeState) {- pane.classList.add("tree-restoring");-- const ids = new Set(state.expanded);- for (const item of pane.querySelectorAll<HTMLElement>("#menu li.submenu-item[data-note-id]")) {- if (item.dataset.noteId && ids.has(item.dataset.noteId)) {- expandItem(item);- }- }-- const path = state.activePath;- const clicked = path?.at(-1) === document.body.dataset.noteId && path && findItem(pane, path);- if (clicked) {- for (const selected of pane.querySelectorAll("#menu .active")) {- selected.classList.remove("active");- }- const rowAndLink = ":scope > .tree-item-row, :scope > * > a, :scope > a";- for (const selected of clicked.querySelectorAll(rowAndLink)) {- selected.classList.add("active");- }- const ancestors = getAncestorItems(clicked);- for (const ancestor of ancestors) {- expandItem(ancestor);- }- // The server expands the way to another clone, which would push the clicked one down.- for (const item of pane.querySelectorAll<HTMLElement>("#menu li.expanded[data-note-id]")) {- const keep = item === clicked || ancestors.includes(item)- || ids.has(String(item.dataset.noteId));- if (!keep) {- collapseItem(item);- }- }- }-- // Applies the expanded styles while transitions are off, so the chevrons do not rotate.- void pane.offsetHeight;- pane.classList.remove("tree-restoring");-}--function expandItem(item: Element) {- item.classList.add("expanded");- item.querySelector(":scope > * > .collapse-button")?.setAttribute("aria-expanded", "true");-}--function collapseItem(item: Element) {- item.classList.remove("expanded");- item.querySelector(":scope > * > .collapse-button")?.setAttribute("aria-expanded", "false");-}--/** Returns the note IDs from the top of the tree down to `item`. */-function getItemPath(item: Element) {- return [ ...getAncestorItems(item).reverse(), item ]- .map((entry) => entry.getAttribute("data-note-id") ?? "");-}--/** Returns the entries that contain `item`, from its parent up. */-function getAncestorItems(item: Element) {- const ancestors: Element[] = [];- let entry = item.parentElement?.closest("li");- while (entry) {- ancestors.push(entry);- entry = entry.parentElement?.closest("li");- }- return ancestors;-}--/** Returns the entry that `path` leads to from the top of the tree, if the tree has it. */-function findItem(pane: HTMLElement, path: string[]) {- let item: Element | undefined;- let list = pane.querySelector("#menu > ul");- for (const noteId of path) {- const children = [ ...list?.children ?? [] ];- item = children.find((child) => child.getAttribute("data-note-id") === noteId);- list = item?.querySelector(":scope > ul") ?? null;- }- return item;-}--function readTreeState(): TreeState | null {- try {- const state = JSON.parse(sessionStorage.getItem(TREE_STATE_KEY) ?? "null");- return state && {- ...state,- expanded: Array.isArray(state.expanded) ? state.expanded : [],- activePath: Array.isArray(state.activePath) ? state.activePath : undefined- };- } catch {- return null;- }-}diff --git a/packages/share-theme/src/page/tree_state.spec.ts b/packages/share-theme/src/page/tree_state.spec.tsnew file mode 100644index 0000000000..8c13d34c4e--- /dev/null+++ b/packages/share-theme/src/page/tree_state.spec.ts@@ -0,0 +1,286 @@+// @vitest-environment happy-dom+import { afterEach, describe, expect, it, vi } from "vitest";++import setupExpanders from "./navigation.js";+import setupTreeState from "./tree_state.js";++describe("setupTreeState", () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ document.body.innerHTML = "";+ delete document.body.dataset.ancestorNoteId;+ delete document.body.dataset.noteId;+ sessionStorage.clear();+ });++ it("restores the pane's position on another page of the same site only", () => {+ renderPane("site1", { activeTop: 120 });+ 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-state") ?? "null"))+ .toStrictEqual({ siteId: "site1", top: 30, expanded: [] });++ renderPane("site2", { activeTop: 120 });+ setupTreeState();+ expect(pane().scrollTop).toBe(0);+ });++ it("saves the pane's state before a prerendered page replaces this one", () => {+ renderPane("site1", { activeTop: 120 });+ setupTreeState();+ pane().scrollTop = 40;+ window.dispatchEvent(new Event("pageswap"));++ expect(JSON.parse(sessionStorage.getItem("share-tree-state") ?? "null"))+ .toMatchObject({ siteId: "site1", top: 40 });+ });++ 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("selects the clone of the current note that was clicked, on its own way down", () => {+ const stayHere = (e: Event) => e.preventDefault();+ document.addEventListener("click", stayHere);+ renderPane("site1", { activeTop: 50, menu: CLONES });+ document.body.dataset.noteId = "c";+ setupTreeState();+ pane().click();+ cloneLink("y").click();+ window.dispatchEvent(new Event("pagehide"));+ document.removeEventListener("click", stayHere);+ expect(JSON.parse(sessionStorage.getItem("share-tree-state") ?? "null").activePath)+ .toStrictEqual([ "y", "c" ]);++ renderPane("site1", { activeTop: 50, menu: CLONES });+ setupTreeState();+ expect(selected()).toStrictEqual([ "y/row", "y/link" ]);+ expect(expandedIds()).toStrictEqual([ "x", "c", "y", "c" ]);+ expect(toggle("y").getAttribute("aria-expanded")).toBe("true");++ // The server's way to its own clone opens nothing above the clicked one that was closed.+ const fromY = { siteId: "site1", top: 0, expanded: [ "y" ], activePath: [ "y", "c" ] };+ sessionStorage.setItem("share-tree-state", JSON.stringify(fromY));+ renderPane("site1", { activeTop: 50, menu: CLONES });+ setupTreeState();+ expect(selected()).toStrictEqual([ "y/row", "y/link" ]);+ expect(expandedIds()).toStrictEqual([ "y", "c" ]);+ expect(toggle("x").getAttribute("aria-expanded")).toBe("false");++ // The next page is another note, or the way no longer leads to a clone of it.+ for (const activePath of [ [ "y", "d" ], [ "z", "c" ] ]) {+ const state = { siteId: "site1", top: 0, expanded: [], activePath };+ sessionStorage.setItem("share-tree-state", JSON.stringify(state));+ renderPane("site1", { activeTop: 50, menu: CLONES });+ setupTreeState();+ expect(selected()).toStrictEqual([ "x/row", "x/link" ]);+ }++ // A `tree_item` partial copied from an earlier theme gives its entries no note ID.+ renderPane("site1", { activeTop: 50 });+ document.addEventListener("click", stayHere);+ setupTreeState();+ document.querySelector<HTMLElement>("#menu a")?.click();+ window.dispatchEvent(new Event("pagehide"));+ document.removeEventListener("click", stayHere);+ expect(JSON.parse(sessionStorage.getItem("share-tree-state") ?? "null").activePath)+ .toStrictEqual([ "" ]);+ });++ it("centers the current note when it is out of view, and leaves it when it is in view", () => {+ renderPane("site1", { activeTop: 700 });+ setupTreeState();+ // 700 - 0 - (400 - 32) / 2+ expect(pane().scrollTop).toBe(516);++ renderPane("site1", { activeTop: 380 });+ setupTreeState();+ expect(pane().scrollTop).toBe(196);++ sessionStorage.setItem("share-tree-state", JSON.stringify({ siteId: "site1", top: 300 }));+ renderPane("site1", { activeTop: 250 });+ setupTreeState();+ expect(pane().scrollTop).toBe(66);+ sessionStorage.clear();++ renderPane("site1", { activeTop: 368 });+ setupTreeState();+ expect(pane().scrollTop).toBe(0);++ // Below the pane's top but behind its 100px sticky header: 60 - 100 - (300 - 32) / 2+ renderPane("site1", { activeTop: 60, headerHeight: 100 });+ setupTreeState();+ expect(pane().scrollTop).toBe(-174);+ });++ it("ignores a malformed position and works with blocked storage or without a pane", () => {+ renderPane("site1");+ sessionStorage.setItem("share-tree-state", "{");+ setupTreeState();+ expect(pane().scrollTop).toBe(0);++ const blocked = () => {+ throw new Error("Storage is blocked.");+ };+ vi.stubGlobal("sessionStorage", { getItem: blocked, setItem: blocked });+ renderPane("site1");+ setupTreeState();+ expect(() => window.dispatchEvent(new Event("pagehide"))).not.toThrow();++ vi.unstubAllGlobals();+ renderPane("site1");+ delete document.body.dataset.ancestorNoteId;+ expect(() => setupTreeState()).not.toThrow();++ document.body.innerHTML = "";+ expect(() => setupTreeState()).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, options: { activeTop?: number; menu?: string; headerHeight?: number } = {}+) {+ const { activeTop, menu = NOTE, headerHeight } = options;+ document.body.dataset.ancestorNoteId = siteId;+ document.body.innerHTML = `+ <div id="left-pane"><div id="site-header"></div><nav id="menu">${menu}</nav></div>`;+ const paneEl = pane();+ const header = document.getElementById("site-header");+ if (headerHeight === undefined) {+ header?.remove();+ } else if (header) {+ header.getBoundingClientRect = () => new DOMRect(0, 0, 200, headerHeight);+ }+ Object.defineProperty(paneEl, "clientHeight", { value: 400 });+ paneEl.getBoundingClientRect = () => new DOMRect(0, 0, 200, 400);+ const active = paneEl.querySelector<HTMLElement>("a.active");+ 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;+}++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);+}++/** A note cloned into two pages; the server selected the clone below `x`. */+const CLONES = `+ <ul>+ <li class="submenu-item expanded" data-note-id="x">+ <div class="tree-item-row">+ <button class="collapse-button" aria-expanded="true"></button><a>X</a>+ </div>+ <ul>+ <li class="item expanded" data-note-id="c">+ <div class="tree-item-row active"><a class="active" href="./c">C</a></div>+ </li>+ </ul>+ </li>+ <li class="submenu-item" data-note-id="y">+ <div class="tree-item-row">+ <button class="collapse-button" aria-expanded="false"></button><a>Y</a>+ </div>+ <ul>+ <li class="item expanded" data-note-id="c">+ <div class="tree-item-row"><a href="./c">C</a></div>+ </li>+ </ul>+ </li>+ </ul>`;++function cloneLink(parentId: string) {+ const link = document.querySelector<HTMLElement>(`li[data-note-id="${parentId}"] li a`);+ if (!link) {+ throw new Error(`The tree has no clone below ${parentId}.`);+ }+ return link;+}++/** The selected rows and links, as the parent of their clone and what they are. */+function selected() {+ return [ ...document.querySelectorAll<HTMLElement>("#menu .active") ].map((el) => {+ const parent = el.closest("li")?.parentElement?.closest<HTMLElement>("li")?.dataset.noteId;+ return `${parent}/${el.tagName === "A" ? "link" : "row"}`;+ });+}diff --git a/packages/share-theme/src/page/tree_state.ts b/packages/share-theme/src/page/tree_state.tsnew file mode 100644index 0000000000..d863598816--- /dev/null+++ b/packages/share-theme/src/page/tree_state.ts@@ -0,0 +1,161 @@+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[];+ /** The note IDs from the top of the tree down to the entry that was clicked. */+ activePath?: string[];+}++/**+ * 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.+ * Of a cloned note, the entry that was clicked stays the selected one. The state is kept per site,+ * keyed by `data-ancestor-note-id`, in `sessionStorage`.+ */+export default function setupTreeState() {+ const pane = document.getElementById("left-pane");+ if (!pane) {+ return;+ }+ const siteId = document.body.dataset.ancestorNoteId;++ const saved = readTreeState();+ if (saved && saved.siteId === siteId) {+ restoreTree(pane, saved);+ pane.scrollTop = saved.top;+ }++ const active = pane.querySelector<HTMLElement>("#menu a.active");+ if (active) {+ const paneRect = pane.getBoundingClientRect();+ const activeRect = active.getBoundingClientRect();+ // The sticky `#site-header` covers the top of the pane.+ const visibleTop = pane.querySelector("#site-header")?.getBoundingClientRect().bottom+ ?? paneRect.top;+ if (activeRect.top < visibleTop || activeRect.bottom > paneRect.bottom) {+ const visibleHeight = pane.clientHeight - (visibleTop - paneRect.top);+ const centered = (visibleHeight - activeRect.height) / 2;+ pane.scrollTop += activeRect.top - visibleTop - centered;+ }+ }++ let activePath: string[] | undefined;+ pane.addEventListener("click", (e) => {+ const item = e.target instanceof Element && e.target.closest("#menu a")?.closest("li");+ if (item) {+ activePath = getItemPath(item);+ }+ });++ // `pageswap` fires before a prerendered page is shown, `pagehide` only once this one unloads.+ const saveState = () => {+ 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, activePath };+ try {+ sessionStorage.setItem(TREE_STATE_KEY, JSON.stringify(state));+ } catch {+ // The next page then starts from the server's expansion and the current note.+ }+ };+ window.addEventListener("pageswap", saveState);+ window.addEventListener("pagehide", saveState);+}++/**+ * Expands the saved entries, every clone of each, and selects the clicked entry of the current+ * note, all without animating.+ */+function restoreTree(pane: HTMLElement, state: TreeState) {+ pane.classList.add("tree-restoring");++ const ids = new Set(state.expanded);+ for (const item of pane.querySelectorAll<HTMLElement>("#menu li.submenu-item[data-note-id]")) {+ if (item.dataset.noteId && ids.has(item.dataset.noteId)) {+ expandItem(item);+ }+ }++ const path = state.activePath;+ const clicked = path?.at(-1) === document.body.dataset.noteId && path && findItem(pane, path);+ if (clicked) {+ for (const selected of pane.querySelectorAll("#menu .active")) {+ selected.classList.remove("active");+ }+ const rowAndLink = ":scope > .tree-item-row, :scope > * > a, :scope > a";+ for (const selected of clicked.querySelectorAll(rowAndLink)) {+ selected.classList.add("active");+ }+ const ancestors = getAncestorItems(clicked);+ for (const ancestor of ancestors) {+ expandItem(ancestor);+ }+ // The server expands the way to another clone, which would push the clicked one down.+ for (const item of pane.querySelectorAll<HTMLElement>("#menu li.expanded[data-note-id]")) {+ const keep = item === clicked || ancestors.includes(item)+ || ids.has(String(item.dataset.noteId));+ if (!keep) {+ collapseItem(item);+ }+ }+ }++ // Applies the expanded styles while transitions are off, so the chevrons do not rotate.+ void pane.offsetHeight;+ pane.classList.remove("tree-restoring");+}++function expandItem(item: Element) {+ item.classList.add("expanded");+ item.querySelector(":scope > * > .collapse-button")?.setAttribute("aria-expanded", "true");+}++function collapseItem(item: Element) {+ item.classList.remove("expanded");+ item.querySelector(":scope > * > .collapse-button")?.setAttribute("aria-expanded", "false");+}++/** Returns the note IDs from the top of the tree down to `item`. */+function getItemPath(item: Element) {+ return [ ...getAncestorItems(item).reverse(), item ]+ .map((entry) => entry.getAttribute("data-note-id") ?? "");+}++/** Returns the entries that contain `item`, from its parent up. */+function getAncestorItems(item: Element) {+ const ancestors: Element[] = [];+ let entry = item.parentElement?.closest("li");+ while (entry) {+ ancestors.push(entry);+ entry = entry.parentElement?.closest("li");+ }+ return ancestors;+}++/** Returns the entry that `path` leads to from the top of the tree, if the tree has it. */+function findItem(pane: HTMLElement, path: string[]) {+ let item: Element | undefined;+ let list = pane.querySelector("#menu > ul");+ for (const noteId of path) {+ const children = [ ...list?.children ?? [] ];+ item = children.find((child) => child.getAttribute("data-note-id") === noteId);+ list = item?.querySelector(":scope > ul") ?? null;+ }+ return item;+}++function readTreeState(): TreeState | null {+ try {+ const state = JSON.parse(sessionStorage.getItem(TREE_STATE_KEY) ?? "null");+ return state && {+ ...state,+ expanded: Array.isArray(state.expanded) ? state.expanded : [],+ activePath: Array.isArray(state.activePath) ? state.activePath : undefined+ };+ } catch {+ return null;+ }+}diff --git a/packages/share-theme/src/tree.spec.ts b/packages/share-theme/src/tree.spec.tsnew file mode 100644index 0000000000..86564f5ab5--- /dev/null+++ b/packages/share-theme/src/tree.spec.ts@@ -0,0 +1,14 @@+import { expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ setupTreeState: vi.fn(),+ whenActivated: vi.fn()+}));++vi.mock("./page/tree_state.js", () => ({ default: mocks.setupTreeState }));+vi.mock("./page/speculation.js", () => ({ whenActivated: mocks.whenActivated }));++it("restores the tree once the page is shown", async () => {+ await import("./tree.js");+ expect(mocks.whenActivated).toHaveBeenCalledWith(mocks.setupTreeState);+});diff --git a/packages/share-theme/src/tree.ts b/packages/share-theme/src/tree.tsnew file mode 100644index 0000000000..fc5dae0b57--- /dev/null+++ b/packages/share-theme/src/tree.ts@@ -0,0 +1,10 @@+/**+ * The script a shared page runs before it is first drawn, as the render-blocking first entry of+ * `jsToLoad`: it restores the navigation tree, so the page never shows it at another position.+ * It is built apart from `index.ts`, without code splitting, so it loads as one small file.+ */+import { whenActivated } from "./page/speculation.js";+import setupTreeState from "./page/tree_state.js";++// A prerendered page reads the tree's state once it is shown, not while prerendering.+whenActivated(setupTreeState);diff --git a/packages/trilium-core/src/share/content_renderer.spec.ts b/packages/trilium-core/src/share/content_renderer.spec.tsindex 690f7f4a72..85e13e56e6 100644--- a/packages/trilium-core/src/share/content_renderer.spec.ts+++ b/packages/trilium-core/src/share/content_renderer.spec.ts@@ -1480,9 +1480,10 @@ describe("content_renderer pages", () => {page.querySelectorAll(selector).map((element) => element.getAttribute(attribute));expect(urls("link[rel=stylesheet]", "href")).toStrictEqual([ "api/notes/pageCss/download" ]);expect(urls("script[src]", "src"))- .toStrictEqual([ "assets/scripts.js", "api/notes/pageJs/download" ]);- // The theme's script restores the tree before the first paint; the page's own scripts wait.- expect(urls("script[src]", "blocking")).toStrictEqual([ "render", undefined ]);+ .toStrictEqual([ "assets/tree.js", "assets/scripts.js", "api/notes/pageJs/download" ]);+ // The tree is restored before the first paint; the rest of the theme and the page's own+ // scripts wait.+ expect(urls("script[src]", "blocking")).toStrictEqual([ "render", undefined, undefined ]);expect(urls("link[rel='shortcut icon']", "href")).toStrictEqual([ "api/notes/pageIcon/download" ]);});@@ -1698,7 +1699,9 @@ describe("content_renderer pages", () => {expect(page.querySelectorAll("link[rel=stylesheet]").map((tag) => tag.getAttribute("href"))).toStrictEqual([ "../assets/scripts.css" ]);expect(page.querySelectorAll("script[src]").map((tag) => tag.getAttribute("src")))- .toStrictEqual([ "../assets/scripts.js", "api/notes/exportJs/download" ]);+ .toStrictEqual([+ "../assets/tree.js", "../assets/scripts.js", "api/notes/exportJs/download"+ ]);expect(page.querySelector("#trilium-icon-packs")?.text).toContain("../assets/icon-pack-bx.");const [ other, file ] = page.querySelectorAll("#content a");diff --git a/packages/trilium-core/src/share/content_renderer.ts b/packages/trilium-core/src/share/content_renderer.tsindex 7bf41c901c..15a6df5c2d 100644--- a/packages/trilium-core/src/share/content_renderer.ts+++ b/packages/trilium-core/src/share/content_renderer.ts@@ -100,6 +100,7 @@ export function renderNoteForExport(note: BNote, parentBranch: BBranch, basePath// Determine JS to load.const jsToLoad: string[] = [+ `${basePath}assets/tree.js`,`${basePath}assets/scripts.js`];for (const jsRelation of note.getRelations("shareJs")) {@@ -141,7 +142,9 @@ export function renderNoteContent(note: SNote, canAccessEmbed?: CanAccessEmbed)}// Determine JS to load.+ // `page.ejs` makes the first one, which restores the tree, block the page's first paint.const jsToLoad: string[] = [+ "assets/tree.js","assets/scripts.js"];for (const jsRelation of note.getRelations("shareJs")) {