Skip to content

Build your personal knowledge base with Trilium Notes

fix(share): keep the clicked clone of a note selected in the tree

Elian Doran064c7d766751
diff --git a/packages/share-theme/src/model/page.spec.ts b/packages/share-theme/src/model/page.spec.ts
index 0771856aeb..52c907372f 100644
--- a/packages/share-theme/src/model/page.spec.ts
+++ b/packages/share-theme/src/model/page.spec.ts
@@ -338,6 +338,22 @@ describe("getNavigationTree", () => {
expect(tree[1]).toMatchObject({ href: "https://example.com", isExternal: true });
});
+ it("marks as active only the clone of the note below its ancestors", () => {
+ // clones ─┬─ x ── c (first parent)
+ // └─ y ── c (clone)
+ const clones = fakeNote({ noteId: "clones" });
+ const [ x, y ] = [ "x", "y" ].map((noteId) => addChild(clones, fakeNote({ noteId })));
+ const c = addChild(x, fakeNote({ noteId: "c" }));
+ addChild(y, c);
+
+ const outlineOf = (ancestorIds: string[]) =>
+ outline(getNavigationTree(clones, c, ancestorIds, { sanitizeUrl: (url) => url }));
+ expect(outlineOf([ "x" ])).toStrictEqual([ [ "x+", [ "c*+" ] ], [ "y", [ "c+" ] ] ]);
+ expect(outlineOf([ "y" ])).toStrictEqual([ [ "x", [ "c+" ] ], [ "y+", [ "c*+" ] ] ]);
+ // The static export passes the path from the site root down.
+ expect(outlineOf([ "clones", "y" ])).toStrictEqual(outlineOf([ "y" ]));
+ });
+
it("passes the icon pack prefixes to the notes", () => {
const tree = getNavigationTree(site, site, [], {
sanitizeUrl: (url) => url,
diff --git a/packages/share-theme/src/model/page.ts b/packages/share-theme/src/model/page.ts
index ee5d670ab0..38f7ae01ec 100644
--- a/packages/share-theme/src/model/page.ts
+++ b/packages/share-theme/src/model/page.ts
@@ -368,23 +368,29 @@ export interface NavigationTreeOptions {
/**
* Returns the navigation tree of the site starting at `siteRoot`: its visible pages, below one
* another as in the note tree. The entries of `activeNote` and of the notes in `ancestorIds` are
- * expanded.
+ * expanded. Of a cloned `activeNote`, only the entry below exactly the notes in `ancestorIds` is
+ * the active one; their order and whether they include `siteRoot` do not matter.
*/
export function getNavigationTree(
siteRoot: ShareNote, activeNote: ShareNote, ancestorIds: string[], options: NavigationTreeOptions
): NavigationItem[] {
const expandedIds = new Set([ activeNote.noteId, ...ancestorIds ]);
- const toItem = (note: ShareNote): NavigationItem => ({
+ const activeAncestorIds = new Set(ancestorIds.filter((noteId) => noteId !== siteRoot.noteId));
+ const isActive = (note: ShareNote, path: string[]) => note.noteId === activeNote.noteId
+ && path.length === activeAncestorIds.size
+ && path.every((noteId) => activeAncestorIds.has(noteId));
+ const toItem = (note: ShareNote, path: string[]): NavigationItem => ({
...getShareLink(note, options.sanitizeUrl),
noteId: note.noteId,
title: note.title,
type: note.type,
icon: note.getIcon(options.iconPackPrefixes),
- isActive: note.noteId === activeNote.noteId,
+ isActive: isActive(note, path),
isExpanded: expandedIds.has(note.noteId),
- children: note.getVisibleChildNotes().map(toItem)
+ children: note.getVisibleChildNotes()
+ .map((child) => toItem(child, [ ...path, note.noteId ]))
});
- return siteRoot.getVisibleChildNotes().map(toItem);
+ return siteRoot.getVisibleChildNotes().map((note) => toItem(note, []));
}
/**
diff --git a/packages/share-theme/src/page/navigation.spec.ts b/packages/share-theme/src/page/navigation.spec.ts
index ee430ef653..01519b13ab 100644
--- a/packages/share-theme/src/page/navigation.spec.ts
+++ b/packages/share-theme/src/page/navigation.spec.ts
@@ -75,6 +75,7 @@ describe("setupTreeState", () => {
vi.unstubAllGlobals();
document.body.innerHTML = "";
delete document.body.dataset.ancestorNoteId;
+ delete document.body.dataset.noteId;
sessionStorage.clear();
});
@@ -122,6 +123,54 @@ describe("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();
@@ -236,3 +285,44 @@ 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.ts
index 0a18bcfcf9..c969062b50 100644
--- a/packages/share-theme/src/page/navigation.ts
+++ b/packages/share-theme/src/page/navigation.ts
@@ -56,12 +56,15 @@ 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.
- * The state is kept per site, keyed by `data-ancestor-note-id`, in `sessionStorage`.
+ * 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");
@@ -72,7 +75,7 @@ export function setupTreeState() {
const saved = readTreeState();
if (saved && saved.siteId === siteId) {
- expandItems(pane, saved.expanded);
+ restoreTree(pane, saved);
pane.scrollTop = saved.top;
}
@@ -86,10 +89,18 @@ export function setupTreeState() {
}
}
+ 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);
+ }
+ });
+
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 };
+ const state = { siteId, top: pane.scrollTop, expanded, activePath };
try {
sessionStorage.setItem(TREE_STATE_KEY, JSON.stringify(state));
} catch {
@@ -98,26 +109,96 @@ export function setupTreeState() {
});
}
-/** 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);
+/**
+ * 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)) {
- continue;
+ 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);
+ }
}
- item.classList.add("expanded");
- item.querySelector(":scope > * > .collapse-button")?.setAttribute("aria-expanded", "true");
}
+
// 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 : [] };
+ return state && {
+ ...state,
+ expanded: Array.isArray(state.expanded) ? state.expanded : [],
+ activePath: Array.isArray(state.activePath) ? state.activePath : undefined
+ };
} catch {
return null;
}