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
fix(text): render only first-level include notes on display (closes #9682)
Elian Doran09eabcf83b79
diff --git a/apps/client/src/print.spec.tsx b/apps/client/src/print.spec.tsxindex 9ad272142b..135ec7284c 100644--- a/apps/client/src/print.spec.tsx+++ b/apps/client/src/print.spec.tsx@@ -173,7 +173,8 @@ describe("SingleNoteRenderer", () => {errorImg.dispatchEvent(new Event("error"));expect(onReady).toHaveBeenCalledWith({ type: "single-note" });});- expect(h.getRenderedContent).toHaveBeenCalledWith(note, { noChildrenList: true });+ // Printing preserves full include-note nesting via expandNestedIncludes.+ expect(h.getRenderedContent).toHaveBeenCalledWith(note, { noChildrenList: true, expandNestedIncludes: true });});it("renders a non-text, non-spreadsheet note via the content renderer", async () => {@@ -182,7 +183,8 @@ describe("SingleNoteRenderer", () => {renderInto(<SingleNoteRenderer note={note} onReady={onReady} onProgressChanged={() => {}} />);await vi.waitFor(() => expect(onReady).toHaveBeenCalledWith({ type: "single-note" }));- expect(h.getRenderedContent).toHaveBeenCalledWith(note, { noChildrenList: true });+ // Printing preserves full include-note nesting via expandNestedIncludes.+ expect(h.getRenderedContent).toHaveBeenCalledWith(note, { noChildrenList: true, expandNestedIncludes: true });});});diff --git a/apps/client/src/print.tsx b/apps/client/src/print.tsxindex 8ac7f24ba6..8a3409fac9 100644--- a/apps/client/src/print.tsx+++ b/apps/client/src/print.tsx@@ -110,7 +110,8 @@ export function SingleNoteRenderer({ note, onReady }: RendererProps) {if (note.type === "text") {await import("@triliumnext/ckeditor5/src/theme/ck-content.css");}- const { $renderedContent } = await content_renderer.getRenderedContent(note, { noChildrenList: true });+ // Printing preserves full include-note nesting (see expandNestedIncludes).+ const { $renderedContent } = await content_renderer.getRenderedContent(note, { noChildrenList: true, expandNestedIncludes: true });container.replaceChildren(...$renderedContent);// Wait for all images to load.diff --git a/apps/client/src/services/content_renderer.ts b/apps/client/src/services/content_renderer.tsindex 681f18e906..d3bed12cd0 100644--- a/apps/client/src/services/content_renderer.ts+++ b/apps/client/src/services/content_renderer.ts@@ -28,6 +28,19 @@ export interface RenderOptions {noChildrenList?: boolean;/** If enabled, it will prevent rendering of included notes. */noIncludedNotes?: boolean;+ /**+ * Keep expanding include-note sections recursively at every depth. Used for printing/export,+ * which preserves full nesting. When false (the default for on-screen display), only the first+ * level of inclusion is rendered and deeper include-note sections are replaced with a reference+ * link (see {@link includesAsReferenceLinks}).+ */+ expandNestedIncludes?: boolean;+ /**+ * Internal: render this note's own include-note sections as reference links instead of expanding+ * them. Set when rendering a note that is itself already an included note in display mode, so that+ * inclusion stops after the first level.+ */+ includesAsReferenceLinks?: boolean;/** If enabled, it will include archived notes when rendering children list. */includeArchivedNotes?: boolean;/** Set of note IDs that have already been seen during rendering to prevent infinite recursion. */diff --git a/apps/client/src/services/content_renderer_text.spec.ts b/apps/client/src/services/content_renderer_text.spec.tsindex 7ebd6d2c1b..7a966ad66c 100644--- a/apps/client/src/services/content_renderer_text.spec.ts+++ b/apps/client/src/services/content_renderer_text.spec.ts@@ -247,6 +247,71 @@ describe("Text content renderer", () => {});});+describe("Nested include notes (single-level display vs recursive print)", () => {+ function buildIncludeChain() {+ // C (leaf) ← included by B ← included by A. Distinctive bodies so we can+ // assert which levels were expanded vs. replaced with a reference link.+ const noteC = buildNote({ id: "nestC", title: "Note C", content: "<p>C body</p>" });+ const noteB = buildNote({+ id: "nestB",+ title: "Note B",+ content: trimIndentation`+ <p>B body</p>+ <section class="include-note" data-note-id="nestC" data-box-size="medium"> </section>+ `+ });+ const noteA = buildNote({+ id: "nestA",+ title: "Note A",+ content: trimIndentation`+ <p>A body</p>+ <section class="include-note" data-note-id="nestB" data-box-size="medium"> </section>+ `+ });+ return { noteA, noteB, noteC };+ }++ it("on display, renders only the first level and replaces the nested include with a reference link", async () => {+ const { noteA } = buildIncludeChain();+ const contentEl = document.createElement("div");+ await renderText(noteA, $(contentEl));++ // First level (B) is expanded — its body is present.+ expect(contentEl.textContent).toContain("B body");+ // Second level (C) is NOT expanded — its body must be absent.+ expect(contentEl.textContent).not.toContain("C body");+ // The nested include section for C is gone, replaced by a reference link to C.+ expect(contentEl.querySelector('section.include-note[data-note-id="nestC"]')).toBeNull();+ const refLink = contentEl.querySelector("a.reference-link");+ expect(refLink).not.toBeNull();+ expect(refLink?.getAttribute("href")).toContain("nestC");+ });++ it("on print (expandNestedIncludes), keeps expanding nested includes recursively", async () => {+ const { noteA } = buildIncludeChain();+ const contentEl = document.createElement("div");+ await renderText(noteA, $(contentEl), { expandNestedIncludes: true });++ // Both levels expanded, all bodies present, no reference-link placeholder.+ expect(contentEl.textContent).toContain("B body");+ expect(contentEl.textContent).toContain("C body");+ expect(contentEl.querySelector("a.reference-link")).toBeNull();+ });++ it("renders a note's own includes as reference links when includesAsReferenceLinks is set", async () => {+ // This mirrors how an already-included note (e.g. the editor include widget) is rendered:+ // its content shows, but its own includes degrade to reference links.+ const { noteB } = buildIncludeChain();+ const contentEl = document.createElement("div");+ await renderText(noteB, $(contentEl), { includesAsReferenceLinks: true });++ expect(contentEl.textContent).toContain("B body");+ expect(contentEl.textContent).not.toContain("C body");+ expect(contentEl.querySelector('section.include-note[data-note-id="nestC"]')).toBeNull();+ expect(contentEl.querySelector("a.reference-link")?.getAttribute("href")).toContain("nestC");+ });+});+describe("renderIncludedNotes via postProcessRichContent", () => {it("warns and skips an include-note section whose note cannot be found", async () => {const warn = vi.spyOn(console, "warn").mockImplementation(() => {});diff --git a/apps/client/src/services/content_renderer_text.ts b/apps/client/src/services/content_renderer_text.tsindex 06db074dd7..0af66524d1 100644--- a/apps/client/src/services/content_renderer_text.ts+++ b/apps/client/src/services/content_renderer_text.ts@@ -35,10 +35,14 @@ export default async function renderText(note: FNote | FAttachment, $renderedConexport async function postProcessRichContent(note: FNote | FAttachment, $renderedContent: JQuery<HTMLElement>, options: RenderOptions = {}) {const seenNoteIds = options.seenNoteIds ?? new Set<string>();seenNoteIds.add("noteId" in note ? note.noteId : note.attachmentId);- if (!options.noIncludedNotes) {- await renderIncludedNotes($renderedContent[0], seenNoteIds);- } else {+ if (options.noIncludedNotes) {$renderedContent.find("section.include-note").remove();+ } else if (options.includesAsReferenceLinks) {+ // This note is itself an included note in display mode: stop after the first level by+ // degrading its own includes to reference links instead of expanding them.+ await replaceIncludesWithReferenceLinks($renderedContent[0]);+ } else {+ await renderIncludedNotes($renderedContent[0], seenNoteIds, options.expandNestedIncludes ?? false);}if ($renderedContent.find("span.math-tex").length > 0) {@@ -67,7 +71,7 @@ export async function postProcessRichContent(note: FNote | FAttachment, $rendereawait formatCodeBlocks($renderedContent);}-async function renderIncludedNotes(contentEl: HTMLElement, seenNoteIds: Set<string>) {+async function renderIncludedNotes(contentEl: HTMLElement, seenNoteIds: Set<string>, expandNested: boolean) {// TODO: Consider duplicating with server's share/content_renderer.ts.const includeNoteEls = contentEl.querySelectorAll("section.include-note");@@ -100,13 +104,35 @@ async function renderIncludedNotes(contentEl: HTMLElement, seenNoteIds: Set<stricontinue;}- const renderedContent = (await content_renderer.getRenderedContent(note, {- seenNoteIds- })).$renderedContent;+ // On display only the first level is expanded: the included note is rendered with its own+ // includes degraded to reference links. Printing/export keeps expanding recursively.+ const renderedContent = (await content_renderer.getRenderedContent(note, expandNested+ ? { seenNoteIds, expandNestedIncludes: true }+ : { seenNoteIds, includesAsReferenceLinks: true }+ )).$renderedContent;includeNoteEl.replaceChildren(...renderedContent);}}+/**+ * Replace each `section.include-note` in the given content with a reference link to the included+ * note, without expanding it. Used on display to stop inclusion after the first level so a note's+ * transitive include graph is not rendered inline.+ */+async function replaceIncludesWithReferenceLinks(contentEl: HTMLElement) {+ for (const includeNoteEl of contentEl.querySelectorAll("section.include-note")) {+ const noteId = includeNoteEl.getAttribute("data-note-id");+ if (!noteId) continue;++ const $referenceLink = await link.createLink(noteId, {+ referenceLink: true,+ showNoteIcon: true,+ showTooltip: false+ });+ includeNoteEl.replaceWith(...$referenceLink);+ }+}+/** Rewrite the code block from <pre><code> to <div> in order not to apply a codeblock style to it. */export async function rewriteMermaidDiagramsInContainer(container: HTMLDivElement) {const mermaidBlocks = container.querySelectorAll('pre:has(code[class="language-mermaid"])');diff --git a/apps/client/src/widgets/collections/legacy/ListOrGridView.tsx b/apps/client/src/widgets/collections/legacy/ListOrGridView.tsxindex 2b5df1d495..9a4cb63201 100644--- a/apps/client/src/widgets/collections/legacy/ListOrGridView.tsx+++ b/apps/client/src/widgets/collections/legacy/ListOrGridView.tsx@@ -247,6 +247,7 @@ export function NoteContent({ note, trim, noChildrenList, highlightedTokens, inccontent_renderer.getRenderedContent(note, {trim,noChildrenList,+ // The note list is a lightweight preview: don't render included notes at all.noIncludedNotes: true,includeArchivedNotes,showTextRepresentation,diff --git a/apps/client/src/widgets/collections/legacy/ListPrintView.tsx b/apps/client/src/widgets/collections/legacy/ListPrintView.tsxindex 57646d947b..c063a7c69e 100644--- a/apps/client/src/widgets/collections/legacy/ListPrintView.tsx+++ b/apps/client/src/widgets/collections/legacy/ListPrintView.tsx@@ -32,7 +32,9 @@ export function ListPrintView({ note, noteIds: unfilteredNoteIds, onReady, onProif (isNotePrintable(note)) {const content = await content_renderer.getRenderedContent(note, {trim: false,- noChildrenList: true+ noChildrenList: true,+ // Printing preserves full include-note nesting (see expandNestedIncludes).+ expandNestedIncludes: true});const contentEl = content.$renderedContent[0];diff --git a/apps/client/src/widgets/type_widgets/text/utils.ts b/apps/client/src/widgets/type_widgets/text/utils.tsindex 67bfb3468f..9b423985c6 100644--- a/apps/client/src/widgets/type_widgets/text/utils.ts+++ b/apps/client/src/widgets/type_widgets/text/utils.ts@@ -34,7 +34,9 @@ export async function loadIncludedNote(noteId: string, $el: JQuery<HTMLElement>,$titleRow.append($toggle, $title);$wrapper.append($titleRow);- const { $renderedContent, type } = await content_renderer.getRenderedContent(note, { interactive: true });+ // The include widget itself is the first level of inclusion, so the included note's own+ // includes are rendered as reference links rather than expanded (see includesAsReferenceLinks).+ const { $renderedContent, type } = await content_renderer.getRenderedContent(note, { interactive: true, includesAsReferenceLinks: true });const $content = $(`<div class="include-note-content type-${type}" style="display: none;">`).append($renderedContent);$wrapper.append($content);@@ -50,7 +52,9 @@ export async function loadIncludedNote(noteId: string, $el: JQuery<HTMLElement>,// Standard display$wrapper.append($('<h4 class="include-note-title">').append($link));- const { $renderedContent, type } = await content_renderer.getRenderedContent(note, { interactive: true });+ // The include widget itself is the first level of inclusion, so the included note's own+ // includes are rendered as reference links rather than expanded (see includesAsReferenceLinks).+ const { $renderedContent, type } = await content_renderer.getRenderedContent(note, { interactive: true, includesAsReferenceLinks: true });$wrapper.append($(`<div class="include-note-content type-${type}">`).append($renderedContent));}diff --git a/apps/server/src/share/content_renderer.spec.ts b/apps/server/src/share/content_renderer.spec.tsindex 45a8c00d05..1e8381606e 100644--- a/apps/server/src/share/content_renderer.spec.ts+++ b/apps/server/src/share/content_renderer.spec.ts@@ -59,6 +59,60 @@ describe("content_renderer", () => {`);});+ it("renders only the first level of nested includes on the share view (nested include becomes a reference link)", () => {+ buildShareNote({ id: "nestC2", title: "Note C", content: "<p>C body</p>" });+ buildShareNote({+ id: "nestB2",+ title: "Note B",+ content: `<p>B body</p><section class="include-note" data-note-id="nestC2" data-box-size="medium"> </section>`+ });+ const noteA = buildShareNote({+ id: "nestA2",+ content: `<p>A body</p><section class="include-note" data-note-id="nestB2" data-box-size="medium"> </section>`+ });+ const result = getContent(noteA);+ if (typeof result.content !== "string") throw new Error("expected string content");+ // First level (B) expanded; second level (C) replaced with a reference link, not expanded.+ expect(result.content).toContain("B body");+ expect(result.content).not.toContain("C body");+ expect(result.content).toContain("reference-link");+ expect(result.content).toContain("Note C");+ });++ it("expands nested includes recursively when exporting (expandNestedIncludes)", () => {+ buildShareNote({ id: "expC", title: "Note C", content: "<p>C body</p>" });+ buildShareNote({+ id: "expB",+ content: `<p>B body</p><section class="include-note" data-note-id="expC" data-box-size="medium"> </section>`+ });+ const noteA = buildShareNote({+ id: "expA",+ content: `<p>A body</p><section class="include-note" data-note-id="expB" data-box-size="medium"> </section>`+ });+ const result = getContent(noteA, { expandNestedIncludes: true });+ if (typeof result.content !== "string") throw new Error("expected string content");+ expect(result.content).toContain("B body");+ expect(result.content).toContain("C body");+ expect(result.content).not.toContain("reference-link");+ });++ it("does not loop on a circular include chain when expanding recursively", () => {+ buildShareNote({+ id: "cycB",+ content: `<p>B body</p><section class="include-note" data-note-id="cycA" data-box-size="medium"> </section>`+ });+ const noteA = buildShareNote({+ id: "cycA",+ content: `<p>A body</p><section class="include-note" data-note-id="cycB" data-box-size="medium"> </section>`+ });+ const result = getContent(noteA, { expandNestedIncludes: true });+ if (typeof result.content !== "string") throw new Error("expected string content");+ // A expands B; B's re-include of A is broken by the cycle guard (reference link), no hang.+ expect(result.content).toContain("A body");+ expect(result.content).toContain("B body");+ expect(result.content).toContain("reference-link");+ });+it("renders an included large code note without hanging or re-parsing it as HTML (#9717)", () => {// ~2 MiB of angle-bracket-heavy code that previously exploded node-html-parser.const codeLine = `const x: Array<Map<string, List<number>>> = a < b && c > d; // <div>\n`;diff --git a/apps/server/src/share/content_renderer.ts b/apps/server/src/share/content_renderer.tsindex e7d893eebb..72989a6355 100644--- a/apps/server/src/share/content_renderer.ts+++ b/apps/server/src/share/content_renderer.ts@@ -198,7 +198,8 @@ function renderNoteContentInternal(note: SNote | BNote, renderArgs: RenderArgs)return note.getContent() ?? "";}- const { header, content, isEmpty } = getContent(note);+ // Static export preserves full include-note nesting; the live share view renders only the first level.+ const { header, content, isEmpty } = getContent(note, { expandNestedIncludes: renderArgs.isStatic });const showLoginInShareTheme = options.getOptionBool("showLoginInShareTheme");const opts = {note,@@ -277,7 +278,21 @@ export function readTemplate(path: string) {return templateString;}-export function getContent(note: SNote | BNote) {+export interface ShareRenderOptions {+ /**+ * Keep expanding include-note sections recursively at every depth. Used for static export, which+ * preserves full nesting. When false (the default for the on-screen share view), only the first+ * level of inclusion is rendered and deeper include-note sections are replaced with a reference+ * link.+ */+ expandNestedIncludes?: boolean;+ /** Internal: render this note's own include-note sections as reference links instead of expanding. */+ includesAsReferenceLinks?: boolean;+ /** Internal: note IDs already rendered on the current include path, used as a recursion cycle guard. */+ seenNoteIds?: Set<string>;+}++export function getContent(note: SNote | BNote, options: ShareRenderOptions = {}) {if (note.isProtected) {return {header: "",@@ -293,7 +308,7 @@ export function getContent(note: SNote | BNote) {};if (note.type === "text") {- renderText(result, note);+ renderText(result, note, options);} else if (note.type === "code" && note.mime === "text/x-markdown") {renderMarkdown(result, note);} else if (note.type === "code") {@@ -333,7 +348,7 @@ function renderIndex(result: Result) {result.content += "</ul>";}-function renderText(result: Result, note: SNote | BNote) {+function renderText(result: Result, note: SNote | BNote, options: ShareRenderOptions = {}) {if (typeof result.content !== "string") return;const parseOpts: Partial<Options> = {blockTextElements: {}@@ -382,15 +397,28 @@ function renderText(result: Result, note: SNote | BNote) {}}- // Process include notes.+ // Process include notes. The share view renders only the first level of inclusion; static export+ // (expandNestedIncludes) keeps expanding recursively. A shared seenNoteIds set guards the+ // recursive path against cycles that would otherwise loop forever.+ const seenNoteIds = options.seenNoteIds ?? new Set<string>();+ seenNoteIds.add(note.noteId);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 includedNote = shaca.getNote(noteId);+ if (!includedNote) continue;++ // Deeper-than-first-level includes (and any cycle in the recursive path) degrade to a+ // reference link that the link-processing passes below resolve to the shared note.+ if (options.includesAsReferenceLinks || seenNoteIds.has(noteId)) {+ includeNoteEl.replaceWith(...parse(`<a class="reference-link" href="#root/${noteId}">${escapeHtml(includedNote.title)}</a>`, parseOpts).childNodes);+ continue;+ }- const includedResult = getContent(note);+ const includedResult = getContent(includedNote, options.expandNestedIncludes+ ? { expandNestedIncludes: true, seenNoteIds }+ : { includesAsReferenceLinks: true, seenNoteIds });if (typeof includedResult.content !== "string") continue;const includedDocument = parse(includedResult.content, parseOpts).childNodes;