Skip to content

Build your personal knowledge base with Trilium Notes

refactor(share): work out the navigation tree and share links before the template runs

Elian Dorand33631346278
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 2f88c479aa..a12205fa12 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
@@ -332,6 +332,7 @@ for (const attr of parentNote.attributes) {
page. This applies to:</p>
<ul>
<li>the listing produced by the <code>#shareIndex</code> label;</li>
+ <li>the navigation tree of the shared site;</li>
<li>the "Subpages" list shown under a parent note;</li>
<li>inline links to this note from within other shared notes.</li>
</ul>
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Sharing/Custom share template.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Sharing/Custom share template.html
index c111c6e316..e885be7971 100644
--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Sharing/Custom share template.html
+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Sharing/Custom share template.html
@@ -75,6 +75,24 @@
<td>The site logo in the header: <code>href</code> (<code>#shareRootLink</code>,
otherwise the site's root page), <code>width</code> and <code>height</code>.</td>
</tr>
+ <tr>
+ <td><code>navigation</code>
+ </td>
+ <td>The navigation tree of the site: its visible pages, each with <code>title</code>, <code>href</code>, <code>isExternal</code>, <code>type</code>, <code>icon</code>, <code>isActive</code> (the
+ page being shown), <code>isExpanded</code> (that page or one of its ancestors)
+ and <code>children</code>.</td>
+ </tr>
+ <tr>
+ <td><code>childLinks</code>
+ </td>
+ <td>The links to the note's visible children, each with <code>title</code>, <code>href</code>, <code>isExternal</code> and <code>type</code>.</td>
+ </tr>
+ <tr>
+ <td><code>prevNext</code>
+ </td>
+ <td>The pages before and after the note in the navigation tree, as <code>previous</code> and <code>next</code>,
+ each with <code>title</code> and <code>href</code>, or <code>null</code>.</td>
+ </tr>
<tr>
<td><code>snippets</code>
</td>
diff --git a/docs/User Guide/User Guide/Advanced Usage/Sharing.md b/docs/User Guide/User Guide/Advanced Usage/Sharing.md
index c5c1a68e32..461c35e63c 100644
--- a/docs/User Guide/User Guide/Advanced Usage/Sharing.md
+++ b/docs/User Guide/User Guide/Advanced Usage/Sharing.md
@@ -220,6 +220,7 @@ Sometimes it's useful to include a link to an external website alongside your sh
Any link pointing to this note will then redirect to the external website and open in a new browser tab, instead of opening the note's own shared page. This applies to:
* the listing produced by the `#shareIndex` label;
+* the navigation tree of the shared site;
* the "Subpages" list shown under a parent note;
* inline links to this note from within other shared notes.
diff --git a/docs/User Guide/User Guide/Advanced Usage/Sharing/Custom share template.md b/docs/User Guide/User Guide/Advanced Usage/Sharing/Custom share template.md
index 163d61a140..bc05512710 100644
--- a/docs/User Guide/User Guide/Advanced Usage/Sharing/Custom share template.md
+++ b/docs/User Guide/User Guide/Advanced Usage/Sharing/Custom share template.md
@@ -32,6 +32,9 @@ Your template is rendered with a context object exposing the note and its render
| `isEmpty` | `true` when the note has no content of its own. |
| `head` | The values of the page's `<head>`: `title` (the note's title, followed by the site's), `description` (`#shareDescription`), `noIndex` (`#shareDisallowRobotIndexing`) and `openGraph` with `url`, `domain`, `image` and `color`. |
| `logo` | The site logo in the header: `href` (`#shareRootLink`, otherwise the site's root page), `width` and `height`. |
+| `navigation` | The navigation tree of the site: its visible pages, each with `title`, `href`, `isExternal`, `type`, `icon`, `isActive` (the page being shown), `isExpanded` (that page or one of its ancestors) and `children`. |
+| `childLinks` | The links to the note's visible children, each with `title`, `href`, `isExternal` and `type`. |
+| `prevNext` | The pages before and after the note in the navigation tree, as `previous` and `next`, each with `title` and `href`, or `null`. |
| `snippets` | The HTML of the `~shareHtml` snippets for each location, such as `snippets["head:end"]`. Every location is present, empty when no snippet goes there. |
| `subRoot` | The root of the shared subtree as `{ note, branch }` — handy for a site-wide title or logo. |
| `cssToLoad` / `jsToLoad` | Arrays of stylesheet / script URLs the default theme would inject (includes anything added via `~shareCss` / `~shareJs`). |
diff --git a/packages/share-theme/src/model/page.spec.ts b/packages/share-theme/src/model/page.spec.ts
index d157a7adf3..246b59e397 100644
--- a/packages/share-theme/src/model/page.spec.ts
+++ b/packages/share-theme/src/model/page.spec.ts
@@ -1,8 +1,8 @@
import { describe, expect, it } from "vitest";
import {
- getHtmlSnippets, getPageHead, getPrevNextLinks, getSiteLogo, getTableOfContents, type PageHeading,
- type ShareNote
+ getChildLinks, getHtmlSnippets, getNavigationTree, getPageHead, getPrevNextLinks, getShareLink, getSiteAncestorIds,
+ getSiteLogo, getTableOfContents, type NavigationItem, type PageHeading, type ShareNote
} from "./page.js";
describe("getPageHead", () => {
@@ -173,6 +173,102 @@ describe("getPrevNextLinks", () => {
});
});
+describe("getShareLink", () => {
+ const sanitizeUrl = (url: string) => (url.startsWith("javascript:") ? "about:blank" : url);
+ const link = (labels: Record<string, string>) =>
+ getShareLink(fakeNote({ noteId: "page", labels }), sanitizeUrl);
+
+ it("links to the page itself without an external link", () => {
+ expect(link({})).toStrictEqual({ href: "./page-alias", isExternal: false });
+ expect(link({ shareExternal: "" })).toStrictEqual({ href: "./page-alias", isExternal: false });
+ expect(link({ shareExternalLink: " " }).isExternal).toBe(false);
+ });
+
+ it("links to the first non-empty external link, #shareExternalLink first, made safe", () => {
+ const external = (href: string) => ({ href, isExternal: true });
+
+ expect(link({ shareExternal: "https://example.com/legacy" }))
+ .toStrictEqual(external("https://example.com/legacy"));
+ expect(link({
+ shareExternal: "https://example.com/legacy",
+ shareExternalLink: "https://example.com/documented"
+ })).toStrictEqual(external("https://example.com/documented"));
+ expect(link({ shareExternal: "https://example.com/legacy", shareExternalLink: " " }))
+ .toStrictEqual(external("https://example.com/legacy"));
+ expect(link({ shareExternalLink: " javascript:alert(1) " })).toStrictEqual(external("about:blank"));
+ });
+});
+
+describe("getNavigationTree", () => {
+ // site ─┬─ a ─┬─ a1
+ // │ └─ hidden (hidden from the tree)
+ // └─ b (external) ── b1
+ const site = fakeNote({ noteId: "site" });
+ const a = addChild(site, fakeNote({ noteId: "a", icon: "bx bx-folder" }));
+ const a1 = addChild(a, fakeNote({ noteId: "a1", type: "code" }));
+ addChild(a, fakeNote({ noteId: "hidden" }), true);
+ const b = addChild(site, fakeNote({ noteId: "b", labels: { shareExternalLink: "https://example.com" } }));
+ addChild(b, fakeNote({ noteId: "b1" }));
+ const outline = (items: NavigationItem[]): unknown[] => items.map((item) => {
+ const flags = `${item.isActive ? "*" : ""}${item.isExpanded ? "+" : ""}`;
+ return item.children.length
+ ? [ item.title + flags, outline(item.children) ]
+ : item.title + flags;
+ });
+
+ it("lists the visible pages below the site root, expanding the active one and its ancestors", () => {
+ const tree = getNavigationTree(site, a1, [ "a" ], { sanitizeUrl: (url) => url });
+
+ expect(outline(tree)).toStrictEqual([ [ "a+", [ "a1*+" ] ], [ "b", [ "b1" ] ] ]);
+ expect(tree[0]).toMatchObject({
+ type: "text", icon: "bx bx-folder", href: "./a-alias", isExternal: false
+ });
+ expect(tree[0].children[0].type).toBe("code");
+ expect(tree[1]).toMatchObject({ href: "https://example.com", isExternal: true });
+ });
+
+ it("passes the icon pack prefixes to the notes", () => {
+ const tree = getNavigationTree(site, site, [], {
+ sanitizeUrl: (url) => url,
+ iconPackPrefixes: [ "custom" ]
+ });
+
+ expect(tree[1].icon).toBe("bx bx-note custom");
+ expect(outline(tree)).toStrictEqual([ [ "a", [ "a1" ] ], [ "b", [ "b1" ] ] ]);
+ });
+});
+
+describe("getChildLinks", () => {
+ it("links to the visible children of a note, in order", () => {
+ const parent = fakeNote({ noteId: "parent" });
+ addChild(parent, fakeNote({ noteId: "x", type: "book" }));
+ addChild(parent, fakeNote({ noteId: "hidden" }), true);
+ addChild(parent, fakeNote({ noteId: "y", labels: { shareExternal: "https://example.com" } }));
+
+ expect(getChildLinks(parent, (url) => url)).toStrictEqual([
+ { href: "./x-alias", isExternal: false, title: "x", type: "book" },
+ { href: "https://example.com", isExternal: true, title: "y", type: "text" }
+ ]);
+ });
+});
+
+describe("getSiteAncestorIds", () => {
+ // elsewhere ── deep (clone, first parent)
+ // site ── a ── b ── deep
+ const elsewhere = fakeNote({ noteId: "elsewhere" });
+ const site = fakeNote({ noteId: "site" });
+ const a = addChild(site, fakeNote({ noteId: "a" }));
+ const b = addChild(a, fakeNote({ noteId: "b" }));
+ const deep = addChild(elsewhere, fakeNote({ noteId: "deep" }));
+ addChild(b, deep);
+
+ it("lists the parents up to the site root, following the first parent inside the site", () => {
+ expect(getSiteAncestorIds(deep, site)).toStrictEqual([ "b", "a" ]);
+ expect(getSiteAncestorIds(a, site)).toStrictEqual([]);
+ expect(getSiteAncestorIds(site, site)).toStrictEqual([]);
+ });
+});
+
interface FakeNoteOptions {
noteId: string;
title?: string;
@@ -180,6 +276,8 @@ interface FakeNoteOptions {
relations?: Record<string, string>;
snippets?: (ShareNote | null)[];
content?: string;
+ type?: string;
+ icon?: string;
}
function fakeNote(options: FakeNoteOptions): FakeNote {
@@ -195,6 +293,8 @@ function fakeNote(options: FakeNoteOptions): FakeNote {
noteId: options.noteId,
shareId: `${options.noteId}-alias`,
title: options.title ?? options.noteId,
+ type: options.type ?? "text",
+ getIcon: (prefixes) => [ options.icon ?? "bx bx-note", ...prefixes ?? [] ].join(" "),
getLabelValue: (name) => labels[name] ?? null,
hasLabel: (name) => name in labels,
getRelationValue: (name) => relations[name] ?? null,
diff --git a/packages/share-theme/src/model/page.ts b/packages/share-theme/src/model/page.ts
index 4a5f040b91..6b4f265a41 100644
--- a/packages/share-theme/src/model/page.ts
+++ b/packages/share-theme/src/model/page.ts
@@ -16,6 +16,28 @@ export interface ShareNote {
getContent(): string | Uint8Array | null | undefined;
getParentNotes(): ShareNote[];
getVisibleChildNotes(): ShareNote[];
+ type: string;
+ /** The icon's CSS classes, among the icon packs whose prefixes are given. */
+ getIcon(iconPackPrefixes?: string[]): string;
+}
+
+/** Where a link to a note goes: its page, or the address of its external link. */
+export interface ShareLink {
+ href: string;
+ /** Whether the link goes to `#shareExternalLink` or `#shareExternal`. */
+ isExternal: boolean;
+}
+
+/** An entry of the navigation tree, with the entries below it. */
+export interface NavigationItem extends ShareLink {
+ title: string;
+ type: string;
+ icon: string;
+ /** Whether the entry is the page being shown. */
+ isActive: boolean;
+ /** Whether the entry is the page being shown or one of its ancestors. */
+ isExpanded: boolean;
+ children: NavigationItem[];
}
/** A link to another page of the site. */
@@ -169,6 +191,69 @@ export function getTableOfContents(headings: PageHeading[]): TableOfContentsEntr
return toc;
}
+/**
+ * Returns where a link to `note` goes: the first of `#shareExternalLink` and `#shareExternal` that
+ * is not blank, made safe by `sanitizeUrl`, otherwise the note's page.
+ */
+export function getShareLink(note: ShareNote, sanitizeUrl: (url: string) => string): ShareLink {
+ const externalLink = note.getLabelValue("shareExternalLink")?.trim()
+ || note.getLabelValue("shareExternal")?.trim();
+ return externalLink
+ ? { href: sanitizeUrl(externalLink), isExternal: true }
+ : { href: `./${note.shareId}`, isExternal: false };
+}
+
+/** Returns the links to the visible children of `note`, for its list of subpages. */
+export function getChildLinks(note: ShareNote, sanitizeUrl: (url: string) => string) {
+ return note.getVisibleChildNotes().map((child) => ({
+ ...getShareLink(child, sanitizeUrl),
+ title: child.title,
+ type: child.type
+ }));
+}
+
+/** What {@link getNavigationTree} needs besides the notes. */
+export interface NavigationTreeOptions {
+ sanitizeUrl: (url: string) => string;
+ /** The prefixes of the icon packs available to the page, for the notes' icons. */
+ iconPackPrefixes?: string[];
+}
+
+/**
+ * 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.
+ */
+export function getNavigationTree(
+ siteRoot: ShareNote, activeNote: ShareNote, ancestorIds: string[], options: NavigationTreeOptions
+): NavigationItem[] {
+ const expandedIds = new Set([ activeNote.noteId, ...ancestorIds ]);
+ const toItem = (note: ShareNote): NavigationItem => ({
+ ...getShareLink(note, options.sanitizeUrl),
+ title: note.title,
+ type: note.type,
+ icon: note.getIcon(options.iconPackPrefixes),
+ isActive: note.noteId === activeNote.noteId,
+ isExpanded: expandedIds.has(note.noteId),
+ children: note.getVisibleChildNotes().map(toItem)
+ });
+ return siteRoot.getVisibleChildNotes().map(toItem);
+}
+
+/**
+ * Returns the IDs of the notes between `note` and `siteRoot`, from its parent up, following the
+ * first parent inside the site.
+ */
+export function getSiteAncestorIds(note: ShareNote, siteRoot: ShareNote) {
+ const ancestorIds: string[] = [];
+ for (let position = getSitePosition(note, siteRoot);
+ position && position.parent.noteId !== siteRoot.noteId;
+ position = getSitePosition(position.parent, siteRoot)) {
+ ancestorIds.push(position.parent.noteId);
+ }
+ return ancestorIds;
+}
+
/**
* 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
diff --git a/packages/share-theme/src/templates/page.ejs b/packages/share-theme/src/templates/page.ejs
index 07ae351806..c866845ea3 100644
--- a/packages/share-theme/src/templates/page.ejs
+++ b/packages/share-theme/src/templates/page.ejs
@@ -80,7 +80,7 @@
</div>
<% if (hasTree) { %>
<nav id="menu">
- <%- include("tree_item", {note: subRoot.note, activeNote: note, subRoot: subRoot, ancestors}) %>
+ <%- include("tree_item", { items: navigation }) %>
</nav>
<% } %>
</div>
@@ -108,18 +108,9 @@
<% } %>
<ul>
- <%
- for (const childNote of note.getVisibleChildNotes()) {
- const externalHref = childNote
- .getLabelValue("shareExternalLink")?.trim()
- || childNote.getLabelValue("shareExternal")?.trim();
- const isExternalLink = !!externalHref;
- const linkHref = isExternalLink
- ? sanitizeUrl(externalHref)
- : `./${childNote.shareId}`;
- %>
+ <% for (const child of childLinks) { %>
<li>
- <a class="type-<%= childNote.type %>" href="<%= linkHref %>"<% if (isExternalLink) { %> target="_blank" rel="noopener noreferrer"<% } %>><%= childNote.title %></a>
+ <a class="type-<%= child.type %>" href="<%= child.href %>"<% if (child.isExternal) { %> target="_blank" rel="noopener noreferrer"<% } %>><%= child.title %></a>
</li>
<% } %>
</ul>
diff --git a/packages/share-theme/src/templates/tree_item.ejs b/packages/share-theme/src/templates/tree_item.ejs
index d093ceb0b9..71fdb8a502 100644
--- a/packages/share-theme/src/templates/tree_item.ejs
+++ b/packages/share-theme/src/templates/tree_item.ejs
@@ -1,36 +1,13 @@
-<%
-const linkClass = `type-${note.type}` + (activeNote.noteId === note.noteId ? " active" : "");
-const externalHref = note.getLabelValue("shareExternalLink")?.trim()
- || note.getLabelValue("shareExternal")?.trim();
-const isExternalLink = !!externalHref;
-let linkHref;
-
-if (isExternalLink) {
- linkHref = sanitizeUrl(externalHref);
-} else if (note.shareId) {
- linkHref = `./${note.shareId}`;
-}
-%>
-
- <% if (note.noteId !== subRoot.note.noteId) { %>
- <a class="<%= linkClass %>" href="<%= linkHref %>"<% if (isExternalLink) { %> target="_blank" rel="noopener noreferrer"<% } %>>
- <% if (note.hasVisibleChildren()) { %><button class="collapse-button" aria-label="<%= t("share_theme.expand") %>"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="svg-icon right-triangle"><path d="M3 8L12 17L21 8"></path></svg></button><% } %>
- <span><i class="<%= note.getIcon(iconPackSupportedPrefixes) %>"></i> <%= note.title %></span>
- </a>
-<% } %>
-
-
-<% if (note.hasVisibleChildren()) { %>
<ul>
- <% note.getVisibleChildNotes().forEach(function (childNote) { %>
- <%
- const hasChildren = childNote.hasVisibleChildren();
- const isAncestorOfActive = ancestors.some(p => p === childNote.noteId);
- const expandedClass = childNote.noteId === activeNote.noteId || isAncestorOfActive ? " expanded" : "";
- %>
- <li class="<% if (hasChildren) { %>submenu-<% } %>item<%= expandedClass %>">
- <%- include('tree_item', {note: childNote, subRoot: subRoot}) %>
+ <% for (const item of items) { %>
+ <li class="<%= item.children.length ? "submenu-item" : "item" %><%= item.isExpanded ? " expanded" : "" %>">
+ <a class="type-<%= item.type %><%= item.isActive ? " active" : "" %>" href="<%= item.href %>"<% if (item.isExternal) { %> target="_blank" rel="noopener noreferrer"<% } %>>
+ <% if (item.children.length) { %><button class="collapse-button" aria-label="<%= t("share_theme.expand") %>"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="svg-icon right-triangle"><path d="M3 8L12 17L21 8"></path></svg></button><% } %>
+ <span><i class="<%= item.icon %>"></i> <%= item.title %></span>
+ </a>
+ <% if (item.children.length) { %>
+ <%- include("tree_item", { items: item.children }) %>
+ <% } %>
</li>
- <% }) %>
+ <% } %>
</ul>
-<% } %>
diff --git a/packages/trilium-core/src/share/content_renderer.spec.ts b/packages/trilium-core/src/share/content_renderer.spec.ts
index 5b0694bb41..9c87a7fcf2 100644
--- a/packages/trilium-core/src/share/content_renderer.spec.ts
+++ b/packages/trilium-core/src/share/content_renderer.spec.ts
@@ -1,6 +1,6 @@
import { trimIndentation } from "@triliumnext/commons";
import {
- getHtmlSnippets, getPageHead, getPrevNextLinks, getSiteLogo
+ getChildLinks, getHtmlSnippets, getPageHead, getPrevNextLinks, getSiteLogo
} from "@triliumnext/share-theme/model/page";
import ejs from "ejs";
import { parse } from "node-html-parser";
@@ -929,6 +929,26 @@ describe("content_renderer", () => {
expect(anchor?.getAttribute("href")).toBe(`./my alias"x`);
expect(Object.keys(anchor?.attributes ?? {}).sort()).toEqual([ "class", "href" ]);
});
+
+ it("points an entry with either external link label at that link, in a new tab", () => {
+ buildShareNote({
+ id: shareRoot.SHARE_ROOT_NOTE_ID,
+ children: [
+ { "id": "legacyExternal", "#shareExternal": "https://example.com/legacy" },
+ { "id": "documentedExternal", "#shareExternalLink": " https://example.com/doc " }
+ ]
+ });
+ const note = buildShareNote({ "id": "indexNote2", "content": "<p>Index</p>", "#shareIndex": "" });
+
+ const anchors = parse(String(getContent(note).content)).querySelectorAll("#index a");
+
+ expect(anchors.map((anchor) => anchor.getAttribute("href")))
+ .toStrictEqual([ "https://example.com/legacy", "https://example.com/doc" ]);
+ for (const anchor of anchors) {
+ expect(anchor.getAttribute("target")).toBe("_blank");
+ expect(anchor.getAttribute("rel")).toBe("noopener noreferrer");
+ }
+ });
});
describe("anchorHeadings", () => {
it("anchors every heading and lists it with its level, text and unique slug", () => {
@@ -960,91 +980,37 @@ describe("content_renderer", () => {
});
});
- describe("Tree item template", () => {
- it("sets a working target and rel on external tree links only", () => {
- const external = renderTreeItemAnchor({
- "id": "external1",
- "#shareExternal": "https://example.com/page"
- });
-
- expect(external?.getAttribute("href")).toBe("https://example.com/page");
- expect(external?.getAttribute("target")).toBe("_blank");
- expect(external?.getAttribute("rel")).toBe("noopener noreferrer");
- expect(Object.keys(external?.attributes ?? {}).sort())
- .toEqual([ "class", "href", "rel", "target" ]);
-
- const internal = renderTreeItemAnchor({ id: "internal1" });
-
- expect(internal?.getAttribute("href")).toBe("./internal1");
- expect(Object.keys(internal?.attributes ?? {}).sort()).toEqual([ "class", "href" ]);
- });
-
- it("links to the first non-empty value of either external link label", () => {
- const documented = renderTreeItemAnchor({
- "id": "external2",
- "#shareExternalLink": "https://example.com/page"
- });
- const bothLabels = renderTreeItemAnchor({
- "id": "external3",
- "#shareExternal": "",
- "#shareExternalLink": "https://example.com/page"
- });
-
- for (const anchor of [ documented, bothLabels ]) {
- expect(anchor?.getAttribute("href")).toBe("https://example.com/page");
- expect(anchor?.getAttribute("target")).toBe("_blank");
- expect(anchor?.getAttribute("rel")).toBe("noopener noreferrer");
- expect(Object.keys(anchor?.attributes ?? {}).sort())
- .toEqual([ "class", "href", "rel", "target" ]);
- }
-
- const noUrl = renderTreeItemAnchor({ "id": "external4", "#shareExternal": "" });
-
- expect(noUrl?.getAttribute("href")).toBe("./external4");
- expect(Object.keys(noUrl?.attributes ?? {}).sort()).toEqual([ "class", "href" ]);
-
- const twoUrls = renderTreeItemAnchor({
- "id": "external5",
- "#shareExternal": "https://example.com/legacy",
- "#shareExternalLink": "https://example.com/documented"
- });
-
- expect(twoUrls?.getAttribute("href")).toBe("https://example.com/documented");
-
- const whitespaceWithLegacy = renderTreeItemAnchor({
- "id": "external6",
- "#shareExternal": "https://example.com/legacy2",
- "#shareExternalLink": " "
- });
-
- expect(whitespaceWithLegacy?.getAttribute("href")).toBe("https://example.com/legacy2");
-
- const whitespaceOnly = renderTreeItemAnchor({
- "id": "external7",
- "#shareExternalLink": " "
+ describe("Navigation tree", () => {
+ it("links each page of the site, expanding the way to the page shown", () => {
+ const shareRootNote = buildShareNote({
+ id: shareRoot.SHARE_ROOT_NOTE_ID,
+ children: [{
+ id: "treeSite",
+ title: "Site",
+ children: [
+ {
+ id: "treeSection",
+ title: "Section",
+ children: [ { id: "treeShown", title: "Shown", content: "<p>x</p>" } ]
+ },
+ { "id": "treeExternal", "title": "External", "#shareExternal": "https://example.com/page" }
+ ]
+ }]
});
-
- expect(whitespaceOnly?.getAttribute("href")).toBe("./external7");
- expect(Object.keys(whitespaceOnly?.attributes ?? {}).sort())
- .toEqual([ "class", "href" ]);
+ const shown = shareRootNote.getChildNotes()[0].getChildNotes()[0].getChildNotes()[0];
+
+ const menu = parse(String(renderNoteContent(shown))).querySelector("#menu");
+ const anchors = menu?.querySelectorAll("a") ?? [];
+
+ expect(anchors.map((anchor) => anchor.getAttribute("href")))
+ .toStrictEqual([ "./treeSection", "./treeShown", "https://example.com/page" ]);
+ expect(Object.keys(anchors[0].attributes).sort()).toEqual([ "class", "href" ]);
+ expect(anchors[1].classList.contains("active")).toBe(true);
+ expect(anchors[2].getAttribute("target")).toBe("_blank");
+ expect(anchors[2].getAttribute("rel")).toBe("noopener noreferrer");
+ expect(menu?.querySelectorAll("li.expanded").map((item) => item.querySelector("a")?.text.trim()))
+ .toStrictEqual([ "Section", "Shown" ]);
});
-
- function renderTreeItemAnchor(noteDef: Parameters<typeof buildShareNote>[0]) {
- const note = buildShareNote(noteDef);
- const subRootNote = buildShareNote({ id: `subRoot-${noteDef.id}` });
-
- const html = ejs.render(readShareTemplate("tree_item"), {
- note,
- activeNote: subRootNote,
- subRoot: { note: subRootNote },
- ancestors: [],
- sanitizeUrl: sanitize.sanitizeUrl,
- iconPackSupportedPrefixes: [],
- t: (key: string) => key
- });
-
- return parse(html).querySelector("a");
- }
});
describe("Subpage list template", () => {
it("sets a working target and rel on external subpage links only", () => {
@@ -1158,6 +1124,8 @@ describe("content_renderer", () => {
snippets: getHtmlSnippets(note),
logo: getSiteLogo(note, sanitize.sanitizeUrl),
prevNext: getPrevNextLinks(note, note),
+ navigation: [],
+ childLinks: getChildLinks(note, sanitize.sanitizeUrl),
headings: [],
toc: []
}, {
diff --git a/packages/trilium-core/src/share/content_renderer.ts b/packages/trilium-core/src/share/content_renderer.ts
index 274d3f3329..48c5afd435 100644
--- a/packages/trilium-core/src/share/content_renderer.ts
+++ b/packages/trilium-core/src/share/content_renderer.ts
@@ -8,7 +8,8 @@ import { renderToHtml as renderMarkdownToHtml } from "@triliumnext/commons/src/l
import { renderSpreadsheetToHtml } from "@triliumnext/commons/src/lib/spreadsheet/render_to_html.js";
import { getLanguage, highlight, highlightAuto, syncMimeTypes } from "@triliumnext/highlightjs";
import {
- getHtmlSnippets, getPageHead, getPrevNextLinks, getSiteLogo, getTableOfContents, type PageHeading
+ getChildLinks, getHtmlSnippets, getNavigationTree, getPageHead, getPrevNextLinks, getShareLink,
+ getSiteAncestorIds, getSiteLogo, getTableOfContents, type PageHeading
} from "@triliumnext/share-theme/model/page";
import ejs from "ejs";
import escapeHtml from "escape-html";
@@ -129,16 +130,7 @@ export function renderNoteForExport(note: BNote, parentBranch: BBranch, basePath
export function renderNoteContent(note: SNote, canAccessEmbed?: CanAccessEmbed) {
const subRoot = getSharedSubTreeRoot(note);
- const ancestors: string[] = [];
- let notePointer = note;
- while (notePointer.parents[0]?.noteId !== subRoot.note?.noteId) {
- const pointerParent = notePointer.parents[0];
- if (!pointerParent) {
- break;
- }
- ancestors.push(pointerParent.noteId);
- notePointer = pointerParent;
- }
+ const ancestors = subRoot.note ? getSiteAncestorIds(note, subRoot.note) : [];
// Determine CSS to load.
const cssToLoad: string[] = [];
@@ -232,6 +224,11 @@ function renderNoteContentInternal(note: SNote | BNote, renderArgs: RenderArgs)
snippets: getHtmlSnippets(note),
logo: getSiteLogo(siteRoot, sanitize.sanitizeUrl),
prevNext: getPrevNextLinks(note, siteRoot),
+ navigation: getNavigationTree(siteRoot, note, renderArgs.ancestors, {
+ sanitizeUrl: sanitize.sanitizeUrl,
+ iconPackPrefixes: renderArgs.iconPackSupportedPrefixes
+ }),
+ childLinks: getChildLinks(note, sanitize.sanitizeUrl),
...renderArgs,
};
@@ -395,11 +392,10 @@ function renderIndex(result: Result) {
const rootNote = shaca.getNote(shareRoot.SHARE_ROOT_NOTE_ID);
for (const childNote of rootNote.getChildNotes()) {
- const isExternalLink = childNote.hasLabel("shareExternalLink");
- const rawHref = childNote.getLabelValue("shareExternalLink") ?? "";
- const href = escapeHtml(isExternalLink ? sanitize.sanitizeUrl(rawHref) : `./${childNote.shareId}`);
- const target = isExternalLink ? `target="_blank" rel="noopener noreferrer"` : "";
- result.content += `<li><a class="${childNote.type}" href="${href}" ${target}>${childNote.escapedTitle}</a></li>`;
+ const link = getShareLink(childNote, sanitize.sanitizeUrl);
+ const target = link.isExternal ? ` target="_blank" rel="noopener noreferrer"` : "";
+ result.content += `<li><a class="${childNote.type}" href="${escapeHtml(link.href)}"${target}>`
+ + `${childNote.escapedTitle}</a></li>`;
}
result.content += "</ul>";