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
refactor(share): work out the previous and next pages before the template runs
Elian Doran82cb12fd3887
diff --git a/packages/share-theme/src/model/page.spec.ts b/packages/share-theme/src/model/page.spec.tsindex 87172739cb..d157a7adf3 100644--- a/packages/share-theme/src/model/page.spec.ts+++ b/packages/share-theme/src/model/page.spec.ts@@ -1,7 +1,8 @@import { describe, expect, it } from "vitest";import {- getHtmlSnippets, getPageHead, getSiteLogo, getTableOfContents, type PageHeading, type ShareNote+ getHtmlSnippets, getPageHead, getPrevNextLinks, getSiteLogo, getTableOfContents, type PageHeading,+ type ShareNote} from "./page.js";describe("getPageHead", () => {@@ -134,6 +135,44 @@ describe("getTableOfContents", () => {});});+describe("getPrevNextLinks", () => {+ // share root ─┬─ elsewhere ── a2 (clone, first parent)+ // ├─ site ─┬─ a ─┬─ a1+ // │ │ └─ a2+ // │ ├─ b+ // │ └─ hidden (hidden from the tree) ── h1+ // └─ lonely (a site without pages)+ const shareRoot = fakeNote({ noteId: "shareRoot" });+ const [ elsewhere, site, lonely ] = [ "elsewhere", "site", "lonely" ]+ .map((noteId) => addChild(shareRoot, fakeNote({ noteId })));+ const a = addChild(site, fakeNote({ noteId: "a" }));+ const a1 = addChild(a, fakeNote({ noteId: "a1" }));+ const a2 = addChild(elsewhere, fakeNote({ noteId: "a2" }));+ addChild(a, a2);+ const b = addChild(site, fakeNote({ noteId: "b" }));+ const hidden = addChild(site, fakeNote({ noteId: "hidden" }), true);+ const h1 = addChild(hidden, fakeNote({ noteId: "h1" }));+ const links = (note: ShareNote, siteRoot = site) => {+ const { previous, next } = getPrevNextLinks(note, siteRoot);+ return [ previous?.title ?? null, next?.title ?? null ];+ };++ it("walks the site's pages in tree order, inside the site", () => {+ expect(links(site)).toStrictEqual([ null, "a" ]);+ expect(links(a)).toStrictEqual([ "site", "a1" ]);+ expect(links(a1)).toStrictEqual([ "a", "a2" ]);+ expect(links(a2)).toStrictEqual([ "a1", "b" ]);+ expect(links(b)).toStrictEqual([ "a2", null ]);+ expect(getPrevNextLinks(a, site).next).toStrictEqual({ title: "a1", href: "./a1-alias" });+ });++ it("gives no links to a note hidden from the tree, nor past a site without pages", () => {+ expect(links(hidden)).toStrictEqual([ null, null ]);+ expect(links(h1)).toStrictEqual([ "hidden", null ]);+ expect(links(lonely, lonely)).toStrictEqual([ null, null ]);+ });+});+interface FakeNoteOptions {noteId: string;title?: string;@@ -143,10 +182,16 @@ interface FakeNoteOptions {content?: string;}-function fakeNote(options: FakeNoteOptions): ShareNote {+function fakeNote(options: FakeNoteOptions): FakeNote {const labels = options.labels ?? {};const relations = options.relations ?? {};+ const parents: ShareNote[] = [];+ const children: { note: ShareNote; hidden: boolean }[] = [];return {+ parents,+ children,+ getParentNotes: () => parents,+ getVisibleChildNotes: () => children.filter((child) => !child.hidden).map((child) => child.note),noteId: options.noteId,shareId: `${options.noteId}-alias`,title: options.title ?? options.noteId,@@ -159,3 +204,14 @@ function fakeNote(options: FakeNoteOptions): ShareNote {getContent: () => options.content ?? ""};}++interface FakeNote extends ShareNote {+ parents: ShareNote[];+ children: { note: ShareNote; hidden: boolean }[];+}++function addChild(parent: FakeNote, child: FakeNote, hidden = false) {+ parent.children.push({ note: child, hidden });+ child.parents.push(parent);+ return child;+}diff --git a/packages/share-theme/src/model/page.ts b/packages/share-theme/src/model/page.tsindex 32907837a0..4a5f040b91 100644--- a/packages/share-theme/src/model/page.ts+++ b/packages/share-theme/src/model/page.ts@@ -14,6 +14,14 @@ export interface ShareNote {hasRelation(name: string): boolean;getRelations(name: string): { targetNote?: ShareNote | null }[];getContent(): string | Uint8Array | null | undefined;+ getParentNotes(): ShareNote[];+ getVisibleChildNotes(): ShareNote[];+}++/** A link to another page of the site. */+export interface PageLink {+ title: string;+ href: string;}/** What goes into the `<head>` of a shared page, besides the stylesheets and scripts. */@@ -160,3 +168,78 @@ export function getTableOfContents(headings: PageHeading[]): TableOfContentsEntr}return toc;}++/**+ * Returns the pages before and after `note` when the site starting at `siteRoot` is read in tree+ * order: a page, then its children, then its next sibling. A note in several places follows the+ * first parent inside the site. A note hidden from the tree has neither link.+ */+export function getPrevNextLinks(note: ShareNote, siteRoot: ShareNote) {+ const previous = getPreviousPage(note, siteRoot);+ const next = getNextPage(note, siteRoot);+ return {+ previous: previous && toPageLink(previous),+ next: next && toPageLink(next)+ };+}++function getPreviousPage(note: ShareNote, siteRoot: ShareNote) {+ const position = getSitePosition(note, siteRoot);+ if (!position) {+ return null;+ }+ if (position.index === 0) {+ return position.parent;+ }++ let previous = position.siblings[position.index - 1];+ for (let children = previous.getVisibleChildNotes(); children.length;+ children = previous.getVisibleChildNotes()) {+ previous = children[children.length - 1];+ }+ return previous;+}++function getNextPage(note: ShareNote, siteRoot: ShareNote) {+ const notePosition = getSitePosition(note, siteRoot);+ if (!notePosition && note.noteId !== siteRoot.noteId) {+ return null;+ }+ const firstChild = note.getVisibleChildNotes()[0];+ if (firstChild) {+ return firstChild;+ }++ for (let position = notePosition; position;+ position = getSitePosition(position.parent, siteRoot)) {+ const nextSibling = position.siblings[position.index + 1];+ if (nextSibling) {+ return nextSibling;+ }+ }+ return null;+}++/**+ * Returns where `note` stands among the visible children of its first parent inside the site, or+ * `null` for the site root and for a note outside the site or hidden from the tree.+ */+function getSitePosition(note: ShareNote, siteRoot: ShareNote) {+ if (note.noteId === siteRoot.noteId) {+ return null;+ }++ const parent = note.getParentNotes().find((candidate) => isInSite(candidate, siteRoot));+ const siblings = parent?.getVisibleChildNotes() ?? [];+ const index = siblings.findIndex((sibling) => sibling.noteId === note.noteId);+ return parent && index !== -1 ? { parent, siblings, index } : null;+}++function isInSite(note: ShareNote, siteRoot: ShareNote): boolean {+ return note.noteId === siteRoot.noteId+ || note.getParentNotes().some((parent) => isInSite(parent, siteRoot));+}++function toPageLink(note: ShareNote): PageLink {+ return { title: note.title, href: `./${note.shareId}` };+}diff --git a/packages/share-theme/src/templates/page.ejs b/packages/share-theme/src/templates/page.ejsindex bb38d30c92..07ae351806 100644--- a/packages/share-theme/src/templates/page.ejs+++ b/packages/share-theme/src/templates/page.ejs@@ -135,7 +135,7 @@<% } %><% if (hasTree) { %>- <%- include("prev_next", { note: note, subRoot: subRoot }) %>+ <%- include("prev_next") %><% } %><% if (showLoginInShareTheme && !isStatic) { %>diff --git a/packages/share-theme/src/templates/prev_next.ejs b/packages/share-theme/src/templates/prev_next.ejsindex 6164d32b79..a36cb0212b 100644--- a/packages/share-theme/src/templates/prev_next.ejs+++ b/packages/share-theme/src/templates/prev_next.ejs@@ -1,62 +1,4 @@-<%- // TODO: code cleanup + putting this behind a toggle/attribute- const previousNote = (() => {- // If we are at the subRoot, there is no previous- if (note.noteId === subRoot.note.noteId) return null;-- const parent = note.getParentNotes()[0];- const children = parent.getVisibleChildNotes();- const index = children.findIndex(n => n.noteId === note.noteId);-- // If we are the first child, previous goes up a level- // this is already protected by the first if statement- if (index === 0) return parent;-- // We are not the first child at this level so previous- // should go to the end of the previous tree- let candidate = children[index - 1];- while (candidate?.hasVisibleChildren()) {- const visibleChildren = candidate.getVisibleChildNotes();-- if (visibleChildren.length === 0) {- break;- }-- candidate = visibleChildren[visibleChildren.length - 1];- }-- return candidate ?? null;- })();-- const nextNote = (() => {- // If this currently active note has children, next- // should be the first child- if (note.hasVisibleChildren()) return note.getVisibleChildNotes()[0];-- let parent = note.getParentNotes()[0];- let children = parent.getVisibleChildNotes();- let index = children.findIndex(n => n.noteId === note.noteId);-- // If we are not the last of the current level, just go- // to the next sibling note- if (index !== children.length - 1) return children[index + 1];-- // We are the last sibling, we need to find the next ancestral note- while (index === children.length - 1) {- // If we are already at subRoot level, no reason trying to go higher- if (parent.noteId === subRoot.note.noteId) return null;-- const originalParent = parent;- parent = parent.getParentNotes()[0];- children = parent.getVisibleChildNotes();- index = children.findIndex(n => n.noteId === originalParent.noteId);- }-- return children[index + 1];- })();-%>-<div class="navigation">- <% if (previousNote) { %><a class="previous" href="./<%= previousNote.shareId %>"><%= previousNote.title %></a><% } %>- <% if (nextNote) { %><a class="next" href="./<%= nextNote.shareId %>"><%= nextNote.title %></a><% } %>-</div>\ No newline at end of file+ <% if (prevNext.previous) { %><a class="previous" href="<%= prevNext.previous.href %>"><%= prevNext.previous.title %></a><% } %>+ <% if (prevNext.next) { %><a class="next" href="<%= prevNext.next.href %>"><%= prevNext.next.title %></a><% } %>+</div>diff --git a/packages/trilium-core/src/share/content_renderer.spec.ts b/packages/trilium-core/src/share/content_renderer.spec.tsindex 244489b197..5b0694bb41 100644--- a/packages/trilium-core/src/share/content_renderer.spec.ts+++ b/packages/trilium-core/src/share/content_renderer.spec.ts@@ -1,5 +1,7 @@import { trimIndentation } from "@triliumnext/commons";-import { getHtmlSnippets, getPageHead, getSiteLogo } from "@triliumnext/share-theme/model/page";+import {+ getHtmlSnippets, getPageHead, getPrevNextLinks, getSiteLogo+} from "@triliumnext/share-theme/model/page";import ejs from "ejs";import { parse } from "node-html-parser";import { describe, expect, it, vi } from "vitest";@@ -319,6 +321,26 @@ describe("content_renderer", () => {expect(toc?.querySelector("li li a")?.getAttribute("href")).toBe("#referenced");});+ it("links a page to the pages before and after it in the site", () => {+ const shareRootNote = buildShareNote({+ id: shareRoot.SHARE_ROOT_NOTE_ID,+ children: [{+ id: "navSite",+ title: "Site",+ children: [+ { id: "navFirst", title: "First", content: "<p>1</p>" },+ { id: "navSecond", title: "Second", content: "<p>2</p>" }+ ]+ }]+ });++ const page = parse(String(renderNoteContent(+ shareRootNote.getChildNotes()[0].getChildNotes()[0])));++ expect(page.querySelector(".navigation .previous")?.getAttribute("href")).toBe("./navSite");+ expect(page.querySelector(".navigation .next")?.text).toBe("Second");+ });+it("leaves an include-note section untouched when the referenced note is missing", () => {const note = buildShareNote({id: "missingRefHost",@@ -1135,6 +1157,7 @@ describe("content_renderer", () => {head: getPageHead(note, note),snippets: getHtmlSnippets(note),logo: getSiteLogo(note, sanitize.sanitizeUrl),+ prevNext: getPrevNextLinks(note, note),headings: [],toc: []}, {diff --git a/packages/trilium-core/src/share/content_renderer.ts b/packages/trilium-core/src/share/content_renderer.tsindex 2646b07c7c..274d3f3329 100644--- a/packages/trilium-core/src/share/content_renderer.ts+++ b/packages/trilium-core/src/share/content_renderer.ts@@ -8,7 +8,7 @@ import { renderToHtml as renderMarkdownToHtml } from "@triliumnext/commons/src/limport { renderSpreadsheetToHtml } from "@triliumnext/commons/src/lib/spreadsheet/render_to_html.js";import { getLanguage, highlight, highlightAuto, syncMimeTypes } from "@triliumnext/highlightjs";import {- getHtmlSnippets, getPageHead, getSiteLogo, getTableOfContents, type PageHeading+ getHtmlSnippets, getPageHead, getPrevNextLinks, getSiteLogo, getTableOfContents, type PageHeading} from "@triliumnext/share-theme/model/page";import ejs from "ejs";import escapeHtml from "escape-html";@@ -231,6 +231,7 @@ function renderNoteContentInternal(note: SNote | BNote, renderArgs: RenderArgs)head: getPageHead(note, siteRoot),snippets: getHtmlSnippets(note),logo: getSiteLogo(siteRoot, sanitize.sanitizeUrl),+ prevNext: getPrevNextLinks(note, siteRoot),...renderArgs,};