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
Merge remote-tracking branch 'origin/main' into feature/export_with_share_theme
Elian Doranea53665e645d
diff --cc apps/client/src/translations/en/translation.jsonindex dd02af8ef4,1949d3357e..6af1a18c44--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@@ -110,15 -104,13 +104,14 @@@"export_status": "Export status","export_in_progress": "Export in progress: {{progressCount}}","export_finished_successfully": "Export finished successfully.",- "format_pdf": "PDF - for printing or sharing purposes."+ "format_pdf": "PDF - for printing or sharing purposes.",+ "share-format": "HTML for web publishing - uses the same theme that is used shared notes, but can be published as a static website."},"help": {- "fullDocumentation": "Help (full documentation is available <a class=\"external\" href=\"https://triliumnext.github.io/Docs/\">online</a>)",- "close": "Close",+ "title": "Cheatsheet","noteNavigation": "Note navigation",- "goUpDown": "<kbd>UP</kbd>, <kbd>DOWN</kbd> - go up/down in the list of notes",- "collapseExpand": "<kbd>LEFT</kbd>, <kbd>RIGHT</kbd> - collapse/expand node",+ "goUpDown": "go up/down in the list of notes",+ "collapseExpand": "collapse/expand node","notSet": "not set","goBackForwards": "go back / forwards in the history","showJumpToNoteDialog": "show <a class=\"external\" href=\"https://triliumnext.github.io/Docs/Wiki/note-navigation.html#jump-to-note\">\"Jump to\" dialog</a>",diff --cc apps/client/src/widgets/dialogs/export.tsxindex 0000000000,dded326243..068a5cbd2cmode 000000,100644..100644--- a/apps/client/src/widgets/dialogs/export.tsx+++ b/apps/client/src/widgets/dialogs/export.tsx@@@ -1,0 -1,158 +1,159 @@@+ import { useState } from "preact/hooks";+ import { t } from "../../services/i18n";+ import tree from "../../services/tree";+ import Button from "../react/Button";+ import FormRadioGroup from "../react/FormRadioGroup";+ import Modal from "../react/Modal";+ import "./export.css";+ import ws from "../../services/ws";+ import toastService, { ToastOptions } from "../../services/toast";+ import utils from "../../services/utils";+ import open from "../../services/open";+ import froca from "../../services/froca";+ import { useTriliumEvent } from "../react/hooks";++ interface ExportDialogProps {+ branchId?: string | null;+ noteTitle?: string;+ defaultType?: "subtree" | "single";+ }++ export default function ExportDialog() {+ const [ opts, setOpts ] = useState<ExportDialogProps>();+ const [ exportType, setExportType ] = useState<string>(opts?.defaultType ?? "subtree");+ const [ subtreeFormat, setSubtreeFormat ] = useState("html");+ const [ singleFormat, setSingleFormat ] = useState("html");+ const [ opmlVersion, setOpmlVersion ] = useState("2.0");+ const [ shown, setShown ] = useState(false);++ useTriliumEvent("showExportDialog", async ({ notePath, defaultType }) => {+ const { noteId, parentNoteId } = tree.getNoteIdAndParentIdFromUrl(notePath);+ if (!parentNoteId) {+ return;+ }++ const branchId = await froca.getBranchId(parentNoteId, noteId);++ setOpts({+ noteTitle: noteId && await tree.getNoteTitle(noteId),+ defaultType,+ branchId+ });+ setShown(true);+ });++ return (+ <Modal+ className="export-dialog"+ title={`${t("export.export_note_title")} ${opts?.noteTitle ?? ""}`}+ size="lg"+ onSubmit={() => {+ if (!opts || !opts.branchId) {+ return;+ }++ const format = (exportType === "subtree" ? subtreeFormat : singleFormat);+ const version = (format === "opml" ? opmlVersion : "1.0");+ exportBranch(opts.branchId, exportType, format, version);+ setShown(false);+ }}+ onHidden={() => setShown(false)}+ footer={<Button className="export-button" text={t("export.export")} primary />}+ show={shown}+ >++ <FormRadioGroup+ name="export-type"+ currentValue={exportType} onChange={setExportType}+ values={[{+ value: "subtree",+ label: t("export.export_type_subtree")+ }]}+ />++ { exportType === "subtree" &&+ <div className="export-subtree-formats format-choice">+ <FormRadioGroup+ name="export-subtree-format"+ currentValue={subtreeFormat} onChange={setSubtreeFormat}+ values={[+ { value: "html", label: t("export.format_html_zip") },+ { value: "markdown", label: t("export.format_markdown") },- { value: "opml", label: t("export.format_opml") }++ { value: "opml", label: t("export.format_opml") },++ { value: "share", label: t("export.share-format") }+ ]}+ />++ { subtreeFormat === "opml" &&+ <div className="opml-versions">+ <FormRadioGroup+ name="opml-version"+ currentValue={opmlVersion} onChange={setOpmlVersion}+ values={[+ { value: "1.0", label: t("export.opml_version_1") },+ { value: "2.0", label: t("export.opml_version_2") }+ ]}+ />+ </div>+ }+ </div>+ }++ <FormRadioGroup+ name="export-type"+ currentValue={exportType} onChange={setExportType}+ values={[{+ value: "single",+ label: t("export.export_type_single")+ }]}+ />++ { exportType === "single" &&+ <div class="export-single-formats format-choice">+ <FormRadioGroup+ name="export-single-format"+ currentValue={singleFormat} onChange={setSingleFormat}+ values={[+ { value: "html", label: t("export.format_html") },+ { value: "markdown", label: t("export.format_markdown") }+ ]}+ />+ </div>+ }++ </Modal>+ );+ }++ function exportBranch(branchId: string, type: string, format: string, version: string) {+ const taskId = utils.randomString(10);+ const url = open.getUrlForDownload(`api/branches/${branchId}/export/${type}/${format}/${version}/${taskId}`);+ open.download(url);+ }++ ws.subscribeToMessages(async (message) => {+ function makeToast(id: string, message: string): ToastOptions {+ return {+ id: id,+ title: t("export.export_status"),+ message: message,+ icon: "export"+ };+ }++ if (!("taskType" in message) || message.taskType !== "export") {+ return;+ }++ if (message.type === "taskError") {+ toastService.closePersistent(message.taskId);+ toastService.showError(message.message);+ } else if (message.type === "taskProgressCount") {+ toastService.showPersistent(makeToast(message.taskId, t("export.export_in_progress", { progressCount: message.progressCount })));+ } else if (message.type === "taskSucceeded") {+ const toast = makeToast(message.taskId, t("export.export_finished_successfully"));+ toast.closeAfter = 5000;++ toastService.showPersistent(toast);+ }+ });diff --cc apps/server/src/becca/entities/bnote.tsindex e6563f2dbc,1a724b1b06..dd05fd9746--- a/apps/server/src/becca/entities/bnote.ts+++ b/apps/server/src/becca/entities/bnote.ts@@@ -1758,26 -1758,41 +1758,61 @@@ class BNote extends AbstractBeccaEntityreturn childBranches;}+ get encodedTitle() {+ return encodeURIComponent(this.title);+ }++ getVisibleChildBranches() {+ return this.getChildBranches().filter((branch) => !branch.getNote().isLabelTruthy("shareHiddenFromTree"));+ }++ getVisibleChildNotes() {+ return this.getVisibleChildBranches().map((branch) => branch.getNote());+ }++ hasVisibleChildren() {+ return this.getVisibleChildNotes().length > 0;+ }++ get shareId() {+ return this.noteId;+ }++ /**+ * Return an attribute by it's attributeId. Requires the attribute cache to be available.+ * @param attributeId - the id of the attribute owned by this note+ * @returns - the BAttribute with the given id or undefined if not found.+ */+ getAttributeById(attributeId : string): BAttribute | undefined {+ this.__ensureAttributeCacheIsAvailable();++ if (!this.__attributeCache) {+ throw new Error("Attribute cache not available.");+ }++ return this.__attributeCache.find((attr) => attr.attributeId === attributeId);+ }++ /**+ * Sets an attribute's value by it's attributeId.+ * @param attributeId - the id of the attribute owned by this note+ * @param value - the new value to replace+ */+ setAttributeValueById(attributeId : string, value? : string) {+ const attributes = this.getOwnedAttributes();+ const attr = attributes.find((attr) => attr.attributeId === attributeId);++ value = value?.toString() || "";++ if (attr) {+ if (attr.value !== value) {+ attr.value = value;+ attr.save();+ }+ } else {+ throw new Error(`Attribute with id ${attributeId} not found.`);+ }+ }}export default BNote;diff --cc apps/server/src/routes/api/export.tsindex b2909f2881,4bc0c21773..944eee841c--- a/apps/server/src/routes/api/export.ts+++ b/apps/server/src/routes/api/export.ts@@@ -23,10 -23,10 +23,10 @@@ function exportBranch(req: Request, resreturn;}- const taskContext = new TaskContext(taskId, "export");+ const taskContext = new TaskContext(taskId, "export", null);try {- if (type === "subtree" && (format === "html" || format === "markdown")) {+ if (type === "subtree" && (format === "html" || format === "markdown" || format === "share")) {zipExportService.exportToZip(taskContext, branch, format, res);} else if (type === "single") {if (format !== "html" && format !== "markdown") {diff --cc apps/server/src/services/export/single.tsindex 2748c88506,678fb39e50..16d36807e8--- a/apps/server/src/services/export/single.ts+++ b/apps/server/src/services/export/single.ts@@@ -9,9 -9,8 +9,9 @@@ import type TaskContext from "../task_cimport type BBranch from "../../becca/entities/bbranch.js";import type { Response } from "express";import type BNote from "../../becca/entities/bnote.js";+import type { ExportFormat } from "./zip/abstract_provider.js";- function exportSingleNote(taskContext: TaskContext, branch: BBranch, format: ExportFormat, res: Response) {-function exportSingleNote(taskContext: TaskContext<"export">, branch: BBranch, format: "html" | "markdown", res: Response) {++function exportSingleNote(taskContext: TaskContext<"export">, branch: BBranch, format: ExportFormat, res: Response) {const note = branch.getNote();if (note.type === "image" || note.type === "file") {@@@ -31,10 -30,10 +31,10 @@@res.send(payload);taskContext.increaseProgressCount();- taskContext.taskSucceeded();+ taskContext.taskSucceeded(null);}-export function mapByNoteType(note: BNote, content: string | Buffer<ArrayBufferLike>, format: "html" | "markdown") {+export function mapByNoteType(note: BNote, content: string | Buffer<ArrayBufferLike>, format: ExportFormat) {let payload, extension, mime;if (typeof content !== "string") {diff --cc apps/server/src/services/export/zip.tsindex 58df003afe,116a841b25..0ad0d7f22a--- a/apps/server/src/services/export/zip.ts+++ b/apps/server/src/services/export/zip.ts@@@ -1,9 -1,12 +1,9 @@@"use strict";-import html from "html";import dateUtils from "../date_utils.js";import path from "path";-import mimeTypes from "mime-types";-import mdService from "./markdown.js";import packageInfo from "../../../package.json" with { type: "json" };- import { getContentDisposition } from "../utils.js";+ import { getContentDisposition, escapeHtml, getResourceDir, isDev } from "../utils.js";import protectedSessionService from "../protected_session.js";import sanitize from "sanitize-filename";import fs from "fs";@@@ -15,18 -18,30 +15,18 @@@ import ValidationError from "../../erroimport type NoteMeta from "../meta/note_meta.js";import type AttachmentMeta from "../meta/attachment_meta.js";import type AttributeMeta from "../meta/attribute_meta.js";-import type BBranch from "../../becca/entities/bbranch.js";+import BBranch from "../../becca/entities/bbranch.js";import type { Response } from "express";import type { NoteMetaFile } from "../meta/note_meta.js";--type RewriteLinksFn = (content: string, noteMeta: NoteMeta) => string;--export interface AdvancedExportOptions {- /**- * If `true`, then only the note's content will be kept. If `false` (default), then each page will have its own <html> template.- */- skipHtmlTemplate?: boolean;-- /**- * Provides a custom function to rewrite the links found in HTML or Markdown notes. This method is called for every note imported, if it's of the right type.- *- * @param originalRewriteLinks the original rewrite links function. Can be used to access the default behaviour without having to reimplement it.- * @param getNoteTargetUrl the method to obtain a note's target URL, used internally by `originalRewriteLinks` but can be used here as well.- * @returns a function to rewrite the links in HTML or Markdown notes.- */- customRewriteLinks?: (originalRewriteLinks: RewriteLinksFn, getNoteTargetUrl: (targetNoteId: string, sourceMeta: NoteMeta) => string | null) => RewriteLinksFn;-}--async function exportToZip(taskContext: TaskContext<"export">, branch: BBranch, format: "html" | "markdown", res: Response | fs.WriteStream, setHeaders = true, zipExportOptions?: AdvancedExportOptions) {- if (!["html", "markdown"].includes(format)) {+import HtmlExportProvider from "./zip/html.js";+import { AdvancedExportOptions, type ExportFormat, ZipExportProviderData } from "./zip/abstract_provider.js";+import MarkdownExportProvider from "./zip/markdown.js";+import ShareThemeExportProvider from "./zip/share_theme.js";+import type BNote from "../../becca/entities/bnote.js";+import { NoteType } from "@triliumnext/commons";+- async function exportToZip(taskContext: TaskContext, branch: BBranch, format: ExportFormat, res: Response | fs.WriteStream, setHeaders = true, zipExportOptions?: AdvancedExportOptions) {++async function exportToZip(taskContext: TaskContext<"export">, branch: BBranch, format: ExportFormat, res: Response | fs.WriteStream, setHeaders = true, zipExportOptions?: AdvancedExportOptions) {+ if (!["html", "markdown", "share"].includes(format)) {throw new ValidationError(`Only 'html' and 'markdown' allowed as export format, '${format}' given`);}@@@ -78,8 -72,11 +78,11 @@@}}- function getDataFileName(type: string | null, mime: string, baseFileName: string, existingFileNames: Record<string, number>): string {+ function getDataFileName(type: NoteType | null, mime: string, baseFileName: string, existingFileNames: Record<string, number>): string {let fileName = baseFileName.trim();+ if (!fileName) {+ fileName = "note";+ }// Crop fileName to avoid its length exceeding 30 and prevent cutting into the extension.if (fileName.length > 30) {@@@ -374,69 -429,205 +377,99 @@@}}- function saveNavigation(rootMeta: NoteMeta, navigationMeta: NoteMeta) {- if (!navigationMeta.dataFileName) {- return;- }-- function saveNavigationInner(meta: NoteMeta) {- let html = "<li>";-- const escapedTitle = escapeHtml(`${meta.prefix ? `${meta.prefix} - ` : ""}${meta.title}`);-- if (meta.dataFileName && meta.noteId) {- const targetUrl = getNoteTargetUrl(meta.noteId, rootMeta);-- html += `<a href="${targetUrl}" target="detail">${escapedTitle}</a>`;- } else {- html += escapedTitle;- }-- if (meta.children && meta.children.length > 0) {- html += "<ul>";-- for (const child of meta.children) {- html += saveNavigationInner(child);- }-- html += "</ul>";- }-- return `${html}</li>`;- }-- const fullHtml = `<html>-<head>- <meta charset="utf-8">- <link rel="stylesheet" href="style.css">-</head>-<body>- <ul>${saveNavigationInner(rootMeta)}</ul>-</body>-</html>`;- const prettyHtml = fullHtml.length < 100_000 ? html.prettyPrint(fullHtml, { indent_size: 2 }) : fullHtml;-- archive.append(prettyHtml, { name: navigationMeta.dataFileName });- }-- function saveIndex(rootMeta: NoteMeta, indexMeta: NoteMeta) {- let firstNonEmptyNote;- let curMeta = rootMeta;-- if (!indexMeta.dataFileName) {- return;- }-- while (!firstNonEmptyNote) {- if (curMeta.dataFileName && curMeta.noteId) {- firstNonEmptyNote = getNoteTargetUrl(curMeta.noteId, rootMeta);- }-- if (curMeta.children && curMeta.children.length > 0) {- curMeta = curMeta.children[0];- } else {- break;- }- }-- const fullHtml = `<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">-<html>-<head>- <meta charset="utf-8">- <meta name="viewport" content="width=device-width, initial-scale=1">-</head>-<frameset cols="25%,75%">- <frame name="navigation" src="navigation.html">- <frame name="detail" src="${firstNonEmptyNote}">-</frameset>-</html>`;-- archive.append(fullHtml, { name: indexMeta.dataFileName });+ const existingFileNames: Record<string, number> = format === "html" ? { navigation: 0, index: 1 } : {};+ const rootMeta = createNoteMeta(branch, { notePath: [] }, existingFileNames);+ if (!rootMeta) {+ throw new Error("Unable to create root meta.");}- function saveCss(rootMeta: NoteMeta, cssMeta: NoteMeta) {- if (!cssMeta.dataFileName) {- return;- }-- const cssFile = isDev- ? path.join(__dirname, "../../../../../node_modules/ckeditor5/dist/ckeditor5-content.css")- : path.join(getResourceDir(), "ckeditor5-content.css");+ const metaFile: NoteMetaFile = {+ formatVersion: 2,+ appVersion: packageInfo.version,+ files: [rootMeta]+ };- archive.append(fs.readFileSync(cssFile, "utf-8"), { name: cssMeta.dataFileName });- }+ provider.prepareMeta(metaFile);- for (const noteMeta of Object.values(noteIdToMeta)) {- // filter out relations which are not inside this export- noteMeta.attributes = (noteMeta.attributes || []).filter((attr) => {- if (attr.type !== "relation") {- return true;- } else if (attr.value in noteIdToMeta) {- return true;- } else if (attr.value === "root" || attr.value?.startsWith("_")) {- // relations to "named" noteIds can be preserved- return true;- } else {- return false;+ try {- const existingFileNames: Record<string, number> = format === "html" ? { navigation: 0, index: 1 } : {};- const rootMeta = createNoteMeta(branch, { notePath: [] }, existingFileNames);- if (!rootMeta) {- throw new Error("Unable to create root meta.");- }-- const metaFile: NoteMetaFile = {- formatVersion: 2,- appVersion: packageInfo.version,- files: [rootMeta]- };-- let navigationMeta: NoteMeta | null = null;- let indexMeta: NoteMeta | null = null;- let cssMeta: NoteMeta | null = null;-- if (format === "html") {- navigationMeta = {- noImport: true,- dataFileName: "navigation.html"- };-- metaFile.files.push(navigationMeta);-- indexMeta = {- noImport: true,- dataFileName: "index.html"- };-- metaFile.files.push(indexMeta);-- cssMeta = {- noImport: true,- dataFileName: "style.css"- };-- metaFile.files.push(cssMeta);- }-+ for (const noteMeta of Object.values(noteIdToMeta)) {+ // filter out relations which are not inside this export+ noteMeta.attributes = (noteMeta.attributes || []).filter((attr) => {+ if (attr.type !== "relation") {+ return true;+ } else if (attr.value in noteIdToMeta) {+ return true;+ } else if (attr.value === "root" || attr.value?.startsWith("_")) {+ // relations to "named" noteIds can be preserved+ return true;+ } else {+ return false;+ }+ });+ }++ if (!rootMeta) {+ // corner case of disabled export for exported note+ if ("sendStatus" in res) {+ res.sendStatus(400);}- });- }+ return;+ }++ const metaFileJson = JSON.stringify(metaFile, null, "\t");++ archive.append(metaFileJson, { name: "!!!meta.json" });++ saveNote(rootMeta, "");+- if (format === "html") {- if (!navigationMeta || !indexMeta || !cssMeta) {- throw new Error("Missing meta.");- }-- saveNavigation(rootMeta, navigationMeta);- saveIndex(rootMeta, indexMeta);- saveCss(rootMeta, cssMeta);- }-+ const note = branch.getNote();+ const zipFileName = `${branch.prefix ? `${branch.prefix} - ` : ""}${note.getTitleOrProtected() || "note"}.zip`;++ if (setHeaders && "setHeader" in res) {+ res.setHeader("Content-Disposition", getContentDisposition(zipFileName));+ res.setHeader("Content-Type", "application/zip");+ }++ archive.pipe(res);+ await archive.finalize();+ taskContext.taskSucceeded(null);+ } catch (e: unknown) {+ const message = `Export failed with error: ${e instanceof Error ? e.message : String(e)}`;+ log.error(message);+ taskContext.reportError(message);- if (!rootMeta) {- // corner case of disabled export for exported noteif ("sendStatus" in res) {- res.sendStatus(400);+ res.removeHeader("Content-Disposition");+ res.removeHeader("Content-Type");+ res.status(500).send(message);}- return;}++ const metaFileJson = JSON.stringify(metaFile, null, "\t");++ archive.append(metaFileJson, { name: "!!!meta.json" });++ saveNote(rootMeta, "");++ provider.afterDone(rootMeta);++ const note = branch.getNote();+ const zipFileName = `${branch.prefix ? `${branch.prefix} - ` : ""}${note.getTitleOrProtected()}.zip`;++ if (setHeaders && "setHeader" in res) {+ res.setHeader("Content-Disposition", getContentDisposition(zipFileName));+ res.setHeader("Content-Type", "application/zip");+ }++ archive.pipe(res);+ await archive.finalize();+- taskContext.taskSucceeded();++ taskContext.taskSucceeded(null);}-async function exportToZipFile(noteId: string, format: "markdown" | "html", zipFilePath: string, zipExportOptions?: AdvancedExportOptions) {+async function exportToZipFile(noteId: string, format: ExportFormat, zipFilePath: string, zipExportOptions?: AdvancedExportOptions) {const fileOutputStream = fs.createWriteStream(zipFilePath);- const taskContext = new TaskContext("no-progress-reporting");+ const taskContext = new TaskContext("no-progress-reporting", "export", null);const note = becca.getNote(noteId);diff --cc apps/server/src/share/content_renderer.tsindex 167bdb7163,83ddfde2e5..31c3896c6a--- a/apps/server/src/share/content_renderer.ts+++ b/apps/server/src/share/content_renderer.ts@@@ -1,24 -1,10 +1,24 @@@- import { JSDOM } from "jsdom";+ import { parse, HTMLElement, TextNode } from "node-html-parser";import shaca from "./shaca/shaca.js";-import assetPath from "../services/asset_path.js";+import assetPath, { assetUrlFragment } from "../services/asset_path.js";import shareRoot from "./share_root.js";import escapeHtml from "escape-html";import type SNote from "./shaca/entities/snote.js";+import BNote from "../becca/entities/bnote.js";+import type BBranch from "../becca/entities/bbranch.js";import { t } from "i18next";+import SBranch from "./shaca/entities/sbranch.js";+import options from "../services/options.js";- import { getResourceDir, isDev, safeExtractMessageAndStackFromError } from "../services/utils.js";++import utils, { getResourceDir, isDev, safeExtractMessageAndStackFromError } from "../services/utils.js";+import app_path from "../services/app_path.js";+import ejs from "ejs";+import log from "../services/log.js";+import { join } from "path";+import { readFileSync } from "fs";++const shareAdjustedAssetPath = isDev ? assetPath : `../${assetPath}`;+const shareAdjustedAppPath = isDev ? app_path : `../${app_path}`;+const templateCache: Map<string, string> = new Map();/*** Represents the output of the content renderer.@@@ -30,185 -16,7 +30,186 @@@ export interface ResultisEmpty?: boolean;}-export function getContent(note: SNote) {+interface Subroot {+ note?: SNote | BNote;+ branch?: SBranch | BBranch+}++function getSharedSubTreeRoot(note: SNote | BNote | undefined): Subroot {+ if (!note || note.noteId === shareRoot.SHARE_ROOT_NOTE_ID) {+ // share root itself is not shared+ return {};+ }++ // every path leads to share root, but which one to choose?+ // for the sake of simplicity, URLs are not note paths+ const parentBranch = note.getParentBranches()[0];++ if (note instanceof BNote) {+ return {+ note,+ branch: parentBranch+ }+ }++ if (parentBranch.parentNoteId === shareRoot.SHARE_ROOT_NOTE_ID) {+ return {+ note,+ branch: parentBranch+ };+ }++ return getSharedSubTreeRoot(parentBranch.getParentNote());+}++export function renderNoteForExport(note: BNote, parentBranch: BBranch, basePath: string, ancestors: string[]) {+ const subRoot: Subroot = {+ branch: parentBranch,+ note: parentBranch.getNote()+ };++ return renderNoteContentInternal(note, {+ subRoot,+ rootNoteId: parentBranch.noteId,+ cssToLoad: [+ `${basePath}style.css`,+ `${basePath}boxicons.css`+ ],+ jsToLoad: [+ `${basePath}script.js`+ ],+ logoUrl: `${basePath}icon-color.svg`,+ ancestors+ });+}++export function renderNoteContent(note: SNote) {+ 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;+ }++ // Determine CSS to load.+ const cssToLoad: string[] = [];+ if (!isDev && !note.isLabelTruthy("shareOmitDefaultCss")) {+ cssToLoad.push(`${shareAdjustedAssetPath}/src/share.css`);+ cssToLoad.push(`${shareAdjustedAssetPath}/src/boxicons.css`);+ }+ for (const cssRelation of note.getRelations("shareCss")) {+ cssToLoad.push(`api/notes/${cssRelation.value}/download`);+ }++ // Determine JS to load.+ const jsToLoad: string[] = [+ `${shareAdjustedAppPath}/share.js`+ ];+ for (const jsRelation of note.getRelations("shareJs")) {+ jsToLoad.push(`api/notes/${jsRelation.value}/download`);+ }++ const customLogoId = note.getRelation("shareLogo")?.value;+ const logoUrl = customLogoId ? `api/images/${customLogoId}/image.png` : `../${assetUrlFragment}/images/icon-color.svg`;++ return renderNoteContentInternal(note, {+ subRoot,+ rootNoteId: "_share",+ cssToLoad,+ jsToLoad,+ logoUrl,+ ancestors+ });+}++interface RenderArgs {+ subRoot: Subroot;+ rootNoteId: string;+ cssToLoad: string[];+ jsToLoad: string[];+ logoUrl: string;+ ancestors: string[];+}++function renderNoteContentInternal(note: SNote | BNote, renderArgs: RenderArgs) {+ const { header, content, isEmpty } = getContent(note);+ const showLoginInShareTheme = options.getOption("showLoginInShareTheme");+ const opts = {+ note,+ header,+ content,+ isEmpty,+ assetPath: shareAdjustedAssetPath,+ assetUrlFragment,+ appPath: shareAdjustedAppPath,+ showLoginInShareTheme,+ t,+ isDev,++ utils,+ ...renderArgs+ };++ // Check if the user has their own template.+ if (note.hasRelation("shareTemplate")) {+ // Get the template note and content+ const templateId = note.getRelation("shareTemplate")?.value;+ const templateNote = templateId && shaca.getNote(templateId);++ // Make sure the note type is correct+ if (templateNote && templateNote.type === "code" && templateNote.mime === "application/x-ejs") {+ // EJS caches the result of this so we don't need to pre-cache+ const includer = (path: string) => {+ const childNote = templateNote.children.find((n) => path === n.title);+ if (!childNote) throw new Error(`Unable to find child note: ${path}.`);+ if (childNote.type !== "code" || childNote.mime !== "application/x-ejs") throw new Error("Incorrect child note type.");++ const template = childNote.getContent();+ if (typeof template !== "string") throw new Error("Invalid template content type.");++ return { template };+ };++ // Try to render user's template, w/ fallback to default view+ try {+ const content = templateNote.getContent();+ if (typeof content === "string") {+ return ejs.render(content, opts, { includer });+ }+ } catch (e: unknown) {+ const [errMessage, errStack] = safeExtractMessageAndStackFromError(e);+ log.error(`Rendering user provided share template (${templateId}) threw exception ${errMessage} with stacktrace: ${errStack}`);+ }+ }+ }++ // Render with the default view otherwise.+ const templatePath = join(getResourceDir(), "share-theme", "templates", "page.ejs");+ return ejs.render(readTemplate(templatePath), opts, {+ includer: (path) => {+ const templatePath = join(getResourceDir(), "share-theme", "templates", `${path}.ejs`);+ return { template: readTemplate(templatePath) };+ }+ });+}++function readTemplate(path: string) {+ const cachedTemplate = templateCache.get(path);+ if (cachedTemplate) {+ return cachedTemplate;+ }++ const templateString = readFileSync(path, "utf-8");+ templateCache.set(path, templateString);+ return templateString;+}+- function getContent(note: SNote | BNote) {++export function getContent(note: SNote | BNote) {if (note.isProtected) {return {header: "",@@@ -257,10 -65,28 +258,28 @@@ function renderIndex(result: Result)result.content += "</ul>";}-function renderText(result: Result, note: SNote) {+function renderText(result: Result, note: SNote | BNote) {- const document = new JSDOM(result.content || "").window.document;+ if (typeof result.content !== "string") return;+ const document = parse(result.content || "");- result.isEmpty = document.body.textContent?.trim().length === 0 && document.querySelectorAll("img").length === 0;+ // Process include notes.+ for (const includeNoteEl of document.querySelectorAll("section.include-note")) {+ const noteId = includeNoteEl.getAttribute("data-note-id");+ if (!noteId) continue;++ const note = shaca.getNote(noteId);+ if (!note) continue;++ const includedResult = getContent(note);+ if (typeof includedResult.content !== "string") continue;++ const includedDocument = parse(includedResult.content).childNodes;+ if (includedDocument) {+ includeNoteEl.replaceWith(...includedDocument);+ }+ }++ result.isEmpty = document.textContent?.trim().length === 0 && document.querySelectorAll("img").length === 0;if (!result.isEmpty) {for (const linkEl of document.querySelectorAll("a")) {diff --cc apps/server/src/share/routes.tsindex ceaeedb1bb,77f542ba2d..275474c2d1--- a/apps/server/src/share/routes.ts+++ b/apps/server/src/share/routes.ts@@@ -4,12 -4,41 +4,12 @@@ import type { Request, Response, Routeimport shaca from "./shaca/shaca.js";import shacaLoader from "./shaca/shaca_loader.js";-import shareRoot from "./share_root.js";-import contentRenderer from "./content_renderer.js";-import assetPath, { assetUrlFragment } from "../services/asset_path.js";-import appPath from "../services/app_path.js";import searchService from "../services/search/services/search.js";import SearchContext from "../services/search/search_context.js";-import log from "../services/log.js";import type SNote from "./shaca/entities/snote.js";-import type SBranch from "./shaca/entities/sbranch.js";import type SAttachment from "./shaca/entities/sattachment.js";- import utils from "../services/utils.js";-import utils, { isDev, safeExtractMessageAndStackFromError } from "../services/utils.js";-import options from "../services/options.js";-import { t } from "i18next";-import ejs from "ejs";-import { join } from "path";--function getSharedSubTreeRoot(note: SNote): { note?: SNote; branch?: SBranch } {- if (note.noteId === shareRoot.SHARE_ROOT_NOTE_ID) {- // share root itself is not shared- return {};- }-- // every path leads to share root, but which one to choose?- // for the sake of simplicity, URLs are not note paths- const parentBranch = note.getParentBranches()[0];-- if (parentBranch.parentNoteId === shareRoot.SHARE_ROOT_NOTE_ID) {- return {- note,- branch: parentBranch- };- }-- return getSharedSubTreeRoot(parentBranch.getParentNote());-}+import { renderNoteContent } from "./content_renderer.js";++import utils from "../services/utils.js";function addNoIndexHeader(note: SNote, res: Response) {if (note.isLabelTruthy("shareDisallowRobotIndexing")) {diff --cc packages/share-theme/src/templates/page.ejsindex 10a6c474a7,2fd07c8a7c..0196bfddce--- a/packages/share-theme/src/templates/page.ejs+++ b/packages/share-theme/src/templates/page.ejs@@@ -47,8 -77,11 +71,9 @@@<meta name="twitter:image" content="<%= openGraphImage %>"><!-- Meta Tags Generated via https://opengraph.dev --><meta name="theme-color" content="<%= openGraphColor %>">+ <%- renderSnippets("head:end") %></head><%-const customLogoId = subRoot.note.getRelation("shareLogo")?.value;-const logoUrl = customLogoId ? `api/images/${customLogoId}/image.png` : `../${assetUrlFragment}/images/icon-color.svg`;const logoWidth = subRoot.note.getLabelValue("shareLogoWidth") ?? 53;const logoHeight = subRoot.note.getLabelValue("shareLogoHeight") ?? 40;const mobileLogoHeight = logoHeight && logoWidth ? 32 / (logoWidth / logoHeight) : "";