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
feat(export): pretty-print details blocks in Markdown output
Elian Doran881b05283c20
diff --git a/packages/trilium-core/src/services/export/markdown.spec.ts b/packages/trilium-core/src/services/export/markdown.spec.tsindex c3d96497b4..e814abb498 100644--- a/packages/trilium-core/src/services/export/markdown.spec.ts+++ b/packages/trilium-core/src/services/export/markdown.spec.ts@@ -299,12 +299,46 @@ describe("Markdown export", () => {expect(markdownExportService.toMarkdown(html)).toBe(expected);});- it("preserves collapsible details blocks as raw HTML", () => {+ it("preserves collapsible details blocks as pretty-printed raw HTML", () => {const html = /*html*/`<details class="trilium-collapsible"><summary>Click to expand</summary><p>Body content</p></details>`;- // Passthrough — round-trips losslessly through the markdown importer.+ // Kept as raw HTML (Markdown has no disclosure syntax) but pretty-printed one+ // child per line, mirroring how raw-HTML tables are serialized. Still+ // round-trips losslessly through the markdown importer.+ const expected = trimIndentation`\+ <details class="trilium-collapsible">+ <summary>Click to expand</summary>+ <p>Body content</p>+ </details>`;+ expect(markdownExportService.toMarkdown(html)).toBe(expected);+ });++ it("keeps a text-only details block verbatim so its content is not dropped", () => {+ const html = /*html*/`<details>Just some text</details>`;expect(markdownExportService.toMarkdown(html)).toBe(html);});+ it("indents nested lists inside a details block", () => {+ const html = /*html*/`<details><summary>Sum</summary><ol><li><span>First</span></li><li><span>Second</span><ul><li><span>Nested</span></li></ul></li></ol></details>`;+ const expected = trimIndentation`\+ <details>+ <summary>Sum</summary>+ <ol>+ <li>+ <span>First</span>+ </li>+ <li>+ <span>Second</span>+ <ul>+ <li>+ <span>Nested</span>+ </li>+ </ul>+ </li>+ </ol>+ </details>`;+ expect(markdownExportService.toMarkdown(html)).toBe(expected);+ });+it("converts inline math expressions into proper Markdown syntax", () => {const html = /*html*/String.raw`<span class="math-tex">\(H(X, Y) = \sum_{i=1}^{M} \sum_{j=1}^{L} p(x_i, y_j) \log_2 \frac{1}{p(x_i, y_j)} = - \sum_{i=1}^{M} \sum_{j=1}^{L} p(x_i, y_j) \log_2 p(x_i, y_j) \frac{\text{bits}}{\text{symbol}}\)</span></span>`;const expected = String.raw`$H(X, Y) = \sum_{i=1}^{M} \sum_{j=1}^{L} p(x_i, y_j) \log_2 \frac{1}{p(x_i, y_j)} = - \sum_{i=1}^{M} \sum_{j=1}^{L} p(x_i, y_j) \log_2 p(x_i, y_j) \frac{\text{bits}}{\text{symbol}}$`;diff --git a/packages/trilium-core/src/services/export/markdown.ts b/packages/trilium-core/src/services/export/markdown.tsindex dcb4316b96..2d297ea6a4 100644--- a/packages/trilium-core/src/services/export/markdown.ts+++ b/packages/trilium-core/src/services/export/markdown.ts@@ -1,6 +1,6 @@import { type TaskStateDef } from "@triliumnext/commons";import { ADMONITION_TYPE_MAPPINGS } from "@triliumnext/commons/src/lib/markdown_renderer.js";-import { gfm } from "@triliumnext/turndown-plugin-gfm";+import { gfm, serializeStructuralHtml } from "@triliumnext/turndown-plugin-gfm";import Turnish, { type Rule } from "turnish";import { getTaskStates } from "../task_states.js";@@ -229,14 +229,26 @@ function buildFigureFilter(): Rule {* We match on tag name only (not on the trilium-collapsible class) so any* pasted/imported <details> is preserved too; stripping it to plain text* would silently lose structure.+ *+ * The block is pretty-printed (one child per line, indented) with the same+ * serializer the GFM plugin uses for raw-HTML tables, so it stays readable in+ * the exported Markdown. The block-level containers below are recursed into so+ * nested lists indent too; inline wrappers (<summary>, list-item <span>s, etc.)+ * are emitted verbatim on a single line, and a node holding direct text is kept+ * verbatim as well so its content is never dropped.*/function buildDetailsFilter(): Rule {+ // Block containers whose children are themselves blocks. Inline-content+ // elements (P, SUMMARY, SPAN, headings) are deliberately excluded so their+ // formatting stays on one line.+ const DETAILS_CONTAINER_TAGS = ["DETAILS", "UL", "OL", "LI", "BLOCKQUOTE"];+return {filter(node) {return node.nodeName === "DETAILS";},replacement(_content, node) {- return `\n\n${(node as HTMLElement).outerHTML}\n\n`;+ return `\n\n${serializeStructuralHtml(node as HTMLElement, DETAILS_CONTAINER_TAGS)}\n\n`;}};}diff --git a/packages/turndown-plugin-gfm/src/lib/gfm.ts b/packages/turndown-plugin-gfm/src/lib/gfm.tsindex 984f1413d4..634096ce60 100644--- a/packages/turndown-plugin-gfm/src/lib/gfm.ts+++ b/packages/turndown-plugin-gfm/src/lib/gfm.ts@@ -1,6 +1,7 @@import type Turnish from "turnish";import highlightedCodeBlock from './highlighted-code-block.js'+import { serializeStructuralHtml } from './serialize-structural-html.js'import strikethrough from './strikethrough.js'import tables from './tables.js'import taskListItems from './task-list-items.js'@@ -14,4 +15,4 @@ function gfm (turndownService: Turnish) {])}-export { gfm, highlightedCodeBlock, strikethrough, tables, taskListItems }+export { gfm, highlightedCodeBlock, serializeStructuralHtml, strikethrough, tables, taskListItems }diff --git a/packages/turndown-plugin-gfm/src/lib/serialize-structural-html.ts b/packages/turndown-plugin-gfm/src/lib/serialize-structural-html.tsnew file mode 100644index 0000000000..152123fe95--- /dev/null+++ b/packages/turndown-plugin-gfm/src/lib/serialize-structural-html.ts@@ -0,0 +1,50 @@+// Serializes an element into indented, multi-line HTML so raw-HTML blocks that+// Markdown has no native syntax for (tables kept as HTML, <details> disclosure+// widgets) stay readable inside the exported Markdown file.+//+// `containerTags` lists the tag names that are recursed into and laid out one+// child per line; every other element is a leaf whose inner HTML is emitted+// verbatim on a single line, so whitespace-significant content such as <pre>+// code survives untouched. No blank lines are produced, so the result stays a+// single raw-HTML block on reimport. Inter-element whitespace text nodes are+// dropped, which makes the output stable across repeated export/import cycles.+export function serializeStructuralHtml(node: Element, containerTags: string[], depth = 0): string {+ const indent = ' '.repeat(depth);+ const closeTag = '</' + node.nodeName.toLowerCase() + '>';++ // Use the DOM's own serializer for the opening tag so attribute quoting/escaping+ // matches the rest of the output. A shallow clone has no children, so its+ // outerHTML is exactly the opening tag plus (for non-void elements) the closing tag.+ const shallowHtml = (node.cloneNode(false) as Element).outerHTML;+ const isVoid = !shallowHtml.endsWith(closeTag);+ const openTag = isVoid ? shallowHtml : shallowHtml.slice(0, shallowHtml.length - closeTag.length);++ // A container with significant direct text (e.g. a pasted <details>text</details>)+ // is emitted verbatim so the text is not dropped when we recurse over elements only.+ const hasDirectText = hasSignificantTextChild(node);++ if (containerTags.indexOf(node.nodeName) === -1 || hasDirectText) {+ // Leaf element (td/th/caption/col, or a <details> body child): keep it on one line.+ return isVoid ? indent + openTag : indent + openTag + node.innerHTML.trim() + closeTag;+ }++ const lines = [indent + openTag];+ for (let i = 0; i < node.childNodes.length; i++) {+ const child = node.childNodes[i];+ if (child.nodeType === 1) { // ELEMENT_NODE — whitespace-only text nodes are skipped+ lines.push(serializeStructuralHtml(child as Element, containerTags, depth + 1));+ }+ }+ lines.push(indent + closeTag);+ return lines.join('\n');+}++function hasSignificantTextChild(node: Element): boolean {+ for (let i = 0; i < node.childNodes.length; i++) {+ const child = node.childNodes[i];+ if (child.nodeType === 3 && (child.textContent || '').trim() !== '') { // TEXT_NODE+ return true;+ }+ }+ return false;+}diff --git a/packages/turndown-plugin-gfm/src/lib/tables.ts b/packages/turndown-plugin-gfm/src/lib/tables.tsindex cf5e95eb71..35cc061c7a 100644--- a/packages/turndown-plugin-gfm/src/lib/tables.ts+++ b/packages/turndown-plugin-gfm/src/lib/tables.ts@@ -1,6 +1,8 @@import type Turnish from "turnish";import type { Rule, TurnishOptions } from "turnish";+import { serializeStructuralHtml } from "./serialize-structural-html.js";+var indexOf = Array.prototype.indexOfvar every = Array.prototype.everyvar rules: Record<string, Rule> = {}@@ -296,34 +298,7 @@ var TABLE_CONTAINER_TAGS = ['TABLE', 'THEAD', 'TBODY', 'TFOOT', 'TR', 'COLGROUP'// Inter-element whitespace text nodes are dropped, which makes the output stable// across repeated export/import cycles.function prettyPrintTable(node: Element): string {- return serializeStructuralNode(node, 0);-}--function serializeStructuralNode(node: Element, depth: number): string {- const indent = ' '.repeat(depth);- const closeTag = '</' + node.nodeName.toLowerCase() + '>';-- // Use the DOM's own serializer for the opening tag so attribute quoting/escaping- // matches the rest of the output. A shallow clone has no children, so its- // outerHTML is exactly the opening tag plus (for non-void elements) the closing tag.- const shallowHtml = (node.cloneNode(false) as Element).outerHTML;- const isVoid = !shallowHtml.endsWith(closeTag);- const openTag = isVoid ? shallowHtml : shallowHtml.slice(0, shallowHtml.length - closeTag.length);-- if (TABLE_CONTAINER_TAGS.indexOf(node.nodeName) === -1) {- // Leaf structural element (td/th/caption/col): keep its content on one line.- return isVoid ? indent + openTag : indent + openTag + node.innerHTML.trim() + closeTag;- }-- const lines = [indent + openTag];- for (let i = 0; i < node.childNodes.length; i++) {- const child = node.childNodes[i];- if (child.nodeType === 1) { // ELEMENT_NODE — whitespace-only text nodes are skipped- lines.push(serializeStructuralNode(child as Element, depth + 1));- }- }- lines.push(indent + closeTag);- return lines.join('\n');+ return serializeStructuralHtml(node, TABLE_CONTAINER_TAGS);}export default function tables (turndownService: Turnish) {