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
import { HIGHLIGHT_BACKGROUND, HIGHLIGHT_STYLE, trimIndentation } from "@triliumnext/commons";
import { describe, expect,it } from "vitest";
import markdownExportService, { DEFAULT_ADMONITION_TYPE } from "./markdown.js";
describe("Markdown export", () => {
it("exports correct language tag for known languages", () => {
const conversionTable = {
"language-text-x-nginx-conf": "nginx",
"language-text-x-diff": "diff",
"language-application-javascript-env-frontend": "javascript",
"language-application-javascript-env-backend": "javascript",
"language-text-x-asm-mips": "mips",
"language-text-jsx": "jsx",
"language-text-html": "html",
"language-text-plain": "plaintext",
"language-text-x-csrc": "c",
"language-text-x-c-src": "cpp",
"language-text-x-rustsrc": "rust",
"language-text-typescript-jsx": "tsx",
"language-text-x-toml": "toml",
"language-text-x-scala": "scala",
"language-text-jinja2": "jinja",
"language-text-x-literate-haskell": "literate-haskell",
"language-text-x-mysql": "mysql",
"language-text-x-mssql": "tsql"
};
for (const [ input, output ] of Object.entries(conversionTable)) {
const html = trimIndentation`\
<p>A diff:</p>
<pre><code class="${input}">Hello
-world
+worldy
</code></pre>`;
const expected = trimIndentation`\
A diff:
\`\`\`${output}
Hello
-world
+worldy
\`\`\``;
expect(markdownExportService.toMarkdown(html)).toBe(expected);
}
});
it("removes auto tag for code blocks", () => {
const html = trimIndentation`\
<pre><code class="language-text-x-trilium-auto">Hello
-world
+worldy
</code></pre>`;
const expected = trimIndentation`\
\`\`\`
Hello
-world
+worldy
\`\`\``;
expect(markdownExportService.toMarkdown(html)).toBe(expected);
});
it("supports code block with no language tag", () => {
const html = trimIndentation`\
<pre><code>Hello</code></pre>`;
const expected = trimIndentation`\
\`\`\`
Hello
\`\`\``;
expect(markdownExportService.toMarkdown(html)).toBe(expected);
});
it("exports link previews as raw HTML with a fallback anchor", () => {
// Block card/embed: kept as a section (the importer + editor upcast round-trip it), with a
// fallback link inside so external Markdown renderers show something instead of nothing.
expect(markdownExportService.toMarkdown(
'<p>before</p>' +
'<section class="link-embed" data-url="https://e.com/" data-embed-type="opengraph" data-title="Example"></section>' +
'<p>after</p>'
)).toBe(
'before\n\n' +
'<section class="link-embed" data-url="https://e.com/" data-embed-type="opengraph" data-title="Example"><a href="https://e.com/">Example</a></section>' +
'\n\nafter'
);
// Video embeds share the same element; without a title the URL doubles as the link text.
expect(markdownExportService.toMarkdown(
'<section class="link-embed" data-url="https://www.youtube.com/watch?v=abc" data-embed-type="youtube"></section>'
)).toBe(
'<section class="link-embed" data-url="https://www.youtube.com/watch?v=abc" data-embed-type="youtube">' +
'<a href="https://www.youtube.com/watch?v=abc">https://www.youtube.com/watch?v=abc</a></section>'
);
// Inline mention: stays inline within the sentence.
expect(markdownExportService.toMarkdown(
'<p>See <span class="link-mention" data-url="https://e.com/" data-title="Example"></span> for details.</p>'
)).toBe(
'See <span class="link-mention" data-url="https://e.com/" data-title="Example"><a href="https://e.com/">Example</a></span> for details.'
);
});
it("replaces an existing link preview fallback anchor instead of accumulating it", () => {
// Content imported from Markdown (and never re-saved by the editor) already carries the
// fallback anchor, so the element is non-blank and goes through the rule instead of
// blankReplacement. The anchor is regenerated from the (possibly edited) data attributes.
const exported = markdownExportService.toMarkdown(
'<section class="link-embed" data-url="https://e.com/" data-embed-type="opengraph" data-title="New title">' +
'<a href="https://e.com/">Stale title</a></section>'
);
expect(exported).toBe(
'<section class="link-embed" data-url="https://e.com/" data-embed-type="opengraph" data-title="New title">' +
'<a href="https://e.com/">New title</a></section>'
);
});
it("escapes HTML in link preview fallback anchors", () => {
const exported = markdownExportService.toMarkdown(
'<section class="link-embed" data-url="https://e.com/?a=1&b=2" data-embed-type="opengraph" data-title="A & B <x>"></section>'
);
// The fallback anchor is generated from the data attributes, so its href and title must be
// HTML-escaped or a title like `A & B <x>` would break the exported markup. This escaping is
// done deterministically with `escapeHtml()`, so it holds under both test environments.
expect(exported).toContain('<a href="https://e.com/?a=1&b=2">A & B <x></a>');
// The section wrapper and its data attributes survive so the preview re-imports losslessly.
// The escaping of `<`/`>` inside data-title is left to Turnish's serializer and is not asserted,
// since the escaped and raw forms decode to the same value.
expect(exported).toContain('<section class="link-embed" data-url="https://e.com/?a=1&b=2" data-embed-type="opengraph"');
});
it("renders a hostile-scheme link preview URL inert in the fallback anchor", () => {
// `data-url` reaches export unsanitized (the sanitizers pass `data-*` through untouched), so a
// stored `javascript:` scheme must not become a live anchor in the exported Markdown.
// `safeLinkPreviewHref` maps it to `about:blank`; the escaping asserted in the test above still
// guards a valid http(s) URL that happens to contain a quote.
const exported = markdownExportService.toMarkdown(
'<section class="link-embed" data-url="javascript:alert(1)" data-embed-type="opengraph" data-title="Evil"></section>'
);
// The live fallback href is neutralised. The original scheme survives only in the inert
// `data-url` attribute (which round-trips losslessly on reimport), never as a linkable href.
expect(exported).toContain('<a href="about:blank">Evil</a>');
expect(exported).not.toContain('href="javascript:');
});
it("preserves a link preview that has no data-url, and still drops ordinary blank nodes", () => {
// Without a data-url there is nothing to build a fallback anchor from, so the element stays
// blank and only the blank-node handling can keep it from being dropped along with its metadata.
expect(markdownExportService.toMarkdown(
'<section class="link-embed" data-embed-type="opengraph" data-title="Example"></section>'
)).toBe('<section class="link-embed" data-embed-type="opengraph" data-title="Example"></section>');
// The trailing space is collapsed away here, because turndown assumes an empty inline element
// renders as nothing; a mention with a URL keeps it thanks to the injected fallback anchor.
expect(markdownExportService.toMarkdown(
'<p>See <span class="link-mention" data-title="Example"></span> for details.</p>'
)).toBe('See <span class="link-mention" data-title="Example"></span>for details.');
// Every other blank node keeps upstream's behaviour: a paragraph break for a block element,
// nothing at all for an inline one.
expect(markdownExportService.toMarkdown("<p>a</p><p></p><p>b</p>")).toBe("a\n\nb");
expect(markdownExportService.toMarkdown("<p>a<span></span>b</p>")).toBe("ab");
});
it("exports strikethrough text correctly", () => {
const html = "<s>hello</s>Hello <s>world</s>";
const expected = "~~hello~~Hello ~~world~~";
expect(markdownExportService.toMarkdown(html)).toBe(expected);
});
it("exports headings properly", () => {
const html = trimIndentation`\
<h1>Heading 1</h1>
<h2>Heading 2</h2>
<h3>Heading 3</h3>
<h4>Heading 4</h4>
<h5>Heading 5</h5>
<h6>Heading 6</h6>
`;
const expected = trimIndentation`\
# Heading 1
## Heading 2
### Heading 3
#### Heading 4
##### Heading 5
###### Heading 6`;
expect(markdownExportService.toMarkdown(html)).toBe(expected);
});
it("rewrites image URL with spaces", () => {
const html = `<img src="Hello world .png"/>`;
const expected = ``;
expect(markdownExportService.toMarkdown(html)).toBe(expected);
});
it("supports keyboard shortcuts", () => {
const html = "<kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>Delete</kbd>";
expect(markdownExportService.toMarkdown(html)).toBe(html);
});
it("keeps an icon, the space beside it and the colour around it", () => {
// Turndown drops an element holding nothing before it consults a single rule, and
// collapses the space beside it away with it, so the icon is given something to hold.
const cog = `<span class="tn-icon bx bx-cog"></span>`;
const star = `<span class="tn-icon bx bx-star"></span>`;
const red = `<span style="color:rgb(255,0,0);">`;
expect(markdownExportService.toMarkdown(`<p>Press ${cog} to open it.</p>`))
.toBe(`Press ${cog} to open it.`);
expect(markdownExportService.toMarkdown(`<p>Two ${cog}${star} in a row.</p>`))
.toBe(`Two ${cog}${star} in a row.`);
expect(markdownExportService.toMarkdown(`<p>a${red}${cog}</span>b</p>`))
.toBe(`a${red}${cog}</span>b`);
// A note that only talks about the class is returned as it came, not re-serialized.
expect(markdownExportService.toMarkdown(`<p>The <code>tn-icon</code> class.</p>`))
.toBe("The `tn-icon` class.");
});
it("exports admonitions properly", () => {
const html = trimIndentation`\
<p>
Before
</p>
<aside class="admonition note">
<p>
This is a note.
</p>
</aside>
<aside class="admonition tip">
<p>
This is a tip.
</p>
</aside>
<aside class="admonition important">
<p>
This is a very important information.
</p>
<figure class="table">
<table>
<tbody>
<tr>
<td>
1
</td>
<td>
2
</td>
</tr>
<tr>
<td>
3
</td>
<td>
4
</td>
</tr>
</tbody>
</table>
</figure>
</aside>
<aside class="admonition caution">
<p>
This is a caution.
</p>
</aside>
<aside class="admonition warning">
<h2>
Title goes here
</h2>
<p>
This is a warning.
</p>
</aside>
<p>
After
</p>
`;
const space = " "; // editor config trimming space.
const expected = trimIndentation`\
Before
> [!NOTE]
> This is a note.
> [!TIP]
> This is a tip.
> [!IMPORTANT]
> This is a very important information.
>${space}
> <table>
> <tbody>
> <tr>
> <td>1</td>
> <td>2</td>
> </tr>
> <tr>
> <td>3</td>
> <td>4</td>
> </tr>
> </tbody>
> </table>
> [!CAUTION]
> This is a caution.
> [!WARNING]
> ## Title goes here
>${space}
> This is a warning.
After`;
expect(markdownExportService.toMarkdown(html)).toBe(expected);
});
it("falls back to the default admonition type for an unrecognized class", () => {
// Markdown alerts only define a fixed set of types, so anything Trilium can't map (a stale or
// hand-written class) degrades to the default rather than emitting an invalid alert.
const html = /*html*/`<aside class="admonition something-else"><p>Body</p></aside>`;
expect(markdownExportService.toMarkdown(html)).toBe(`> [!${DEFAULT_ADMONITION_TYPE}]\n> Body`);
});
it("exports code in tables properly", () => {
const html = trimIndentation`\
<table>
<tr>
<td>
Row 1
</td>
<td>
<p>Allows displaying the value of one or more attributes in the calendar
like this: </p>
<p>
<img src="13_Calendar View_image.png" alt="">
</p>
<pre><code class="language-text-x-trilium-auto">#weight="70"
#Mood="Good"
#calendar:displayedAttributes="weight,Mood"</code></pre>
<p>It can also be used with relations, case in which it will display the
title of the target note:</p><pre><code class="language-text-x-trilium-auto">~assignee=@My assignee
#calendar:displayedAttributes="assignee"</code></pre>
</td>
</tr>
</table>
`;
// Structural tags are indented for readability; cell contents (including the
// <pre> code with its own newlines and indentation) are emitted verbatim.
const expected = `<table>
<tbody>
<tr>
<td>Row 1</td>
<td><p>Allows displaying the value of one or more attributes in the calendar like this: </p><p><img src="13_Calendar View_image.png" alt=""></p><pre><code class="language-text-x-trilium-auto">#weight="70"
#Mood="Good"
#calendar:displayedAttributes="weight,Mood"</code></pre><p>It can also be used with relations, case in which it will display the title of the target note:</p><pre><code class="language-text-x-trilium-auto">~assignee=@My assignee
#calendar:displayedAttributes="assignee"</code></pre></td>
</tr>
</tbody>
</table>`;
expect(markdownExportService.toMarkdown(html)).toBe(expected);
});
it("converts to character", () => {
const html = /*html*/`<p>Hello world.</p>`;
const expected = `Hello\u00a0world.`;
expect(markdownExportService.toMarkdown(html)).toBe(expected);
});
it("preserves non-breaking space character", () => {
const html = /*html*/`<p>Hello\u00adworld.</p>`;
const expected = `Hello\u00adworld.`;
expect(markdownExportService.toMarkdown(html)).toBe(expected);
});
it("exports normal links verbatim", () => {
const html = /*html*/`<p><a href="https://www.google.com">Google</a></p>`;
const expected = `[Google](https://www.google.com)`;
expect(markdownExportService.toMarkdown(html)).toBe(expected);
});
it("keeps the link title, escaping quotes inside it", () => {
const html = /*html*/`<p><a href="https://www.google.com" title='a "quoted" title'>Google</a></p>`;
expect(markdownExportService.toMarkdown(html)).toBe(String.raw`[Google](https://www.google.com "a \"quoted\" title")`);
});
it("exports reference links verbatim", () => {
const html = /*html*/`<p><a class="reference-link" href="../../Canvas.html">Canvas</a></p>`;
const expected = `<a class="reference-link" href="../../Canvas.html">Canvas</a>`;
expect(markdownExportService.toMarkdown(html)).toBe(expected);
});
it("converts image if it has no custom properties", () => {
const html = /*html*/`<p><img src="Include Note_image.png"></p>`;
const expected = ``;
expect(markdownExportService.toMarkdown(html)).toBe(expected);
});
it("preserves image verbatim if it has a width or height attribute", () => {
const scenarios = [
/*html*/`<img src="Include Note_image.png" width="16" height="16">`,
/*html*/`<img src="Include Note_image.png" width="16">`,
/*html*/`<img src="Include Note_image.png" height="16">`,
/*html*/`<img class="image_resized" style="aspect-ratio:853/315;width:50%;" src="6_File_image.png" width="853" height="315">`
];
for (const expected of scenarios) {
const html = /*html*/`<p>${expected}</p>`;
expect(markdownExportService.toMarkdown(html)).toBe(expected);
}
});
it("escapes markdown syntax in the image alt text and quotes in its title", () => {
// Unescaped, these would be re-parsed as emphasis/link syntax on reimport.
expect(markdownExportService.toMarkdown(/*html*/`<img src="a.png" alt="a*b_c[d]">`))
.toBe(String.raw`![a\*b\_c\[d\]](a.png)`);
// The trailing-pattern branch: a leading number followed by a dot would start a list.
expect(markdownExportService.toMarkdown(/*html*/`<img src="a.png" alt="1. first">`))
.toBe(String.raw``);
// A quote in the title would otherwise close the title string early.
expect(markdownExportService.toMarkdown(/*html*/`<img src="a.png" title='He said "hi"'>`))
.toBe(String.raw``);
});
it("drops an image with no source", () => {
expect(markdownExportService.toMarkdown(/*html*/`<p>before<img alt="x">after</p>`)).toBe("beforeafter");
});
it("preserves figures", () => {
const html = /*html*/trimIndentation`\
<figure class="image" style="width:53.44%;">
<img style="aspect-ratio:991/403;" src="Jump to Note_image.png" width="991"
height="403">
</figure>
`;
const expected = `<figure class="image" style="width:53.44%;"><img style="aspect-ratio:991/403;" src="Jump to Note_image.png" width="991" height="403"></figure>`;
expect(markdownExportService.toMarkdown(html)).toBe(expected);
});
it("preserves collapsible details blocks as pretty-printed raw HTML, dropping the trilium-collapsible class", () => {
const html = /*html*/`<details class="trilium-collapsible"><summary>Click to expand</summary><p>Body content</p></details>`;
// Kept as raw HTML (Markdown has no disclosure syntax) but pretty-printed one
// child per line, mirroring how raw-HTML tables are serialized. The Trilium-only
// styling hook is stripped; it still round-trips through the markdown importer.
const expected = trimIndentation`\
<details>
<summary>Click to expand</summary>
<p>Body content</p>
</details>`;
expect(markdownExportService.toMarkdown(html)).toBe(expected);
});
it("keeps user-added classes on a details block while dropping trilium-collapsible", () => {
const html = /*html*/`<details class="custom trilium-collapsible"><summary>S</summary><p>B</p></details>`;
const expected = trimIndentation`\
<details class="custom">
<summary>S</summary>
<p>B</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("numbers an ordered list from its start attribute", () => {
const html = /*html*/`<ol start="3"><li>Third</li><li>Fourth</li></ol>`;
const expected = trimIndentation`\
3. Third
4. Fourth`;
expect(markdownExportService.toMarkdown(html)).toBe(expected);
});
it("indents a nested list to the content column of its item, however wide the number", () => {
const html = /*html*/`<ol start="9"><li>Ninth<ol><li>A</li></ol></li><li>Tenth<ol><li>B</li><li>C</li></ol></li></ol>`;
const expected = trimIndentation`\
9. Ninth
1. A
10. Tenth
1. B
2. C`;
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}}$`;
expect(markdownExportService.toMarkdown(html)).toBe(expected);
});
it("converts display 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}}$$`;
expect(markdownExportService.toMarkdown(html)).toBe(expected);
});
it("trims the spaces inside inline math delimiters, so the import reads it back as math", () => {
const html = /*html*/String.raw`<p>Area: <span class="math-tex">\( \pi r^2 \)</span></p>`;
expect(markdownExportService.toMarkdown(html)).toBe(String.raw`Area: $\pi r^2$`);
});
it("keeps a math expression without delimiters verbatim", () => {
// Neither \( \) nor \[ \] — nothing can be inferred, so the raw text is passed through
// rather than guessed into the wrong math mode.
const html = /*html*/`<span class="math-tex">E = mc^2</span>`;
expect(markdownExportService.toMarkdown(html)).toBe("E = mc^2");
});
it("does not generate additional spacing when exporting lists with paragraph", () => {
const html = trimIndentation`\
<ul>
<li><a href="https://github.com/JYC333">@JYC333</a> made their first contribution
in <a href="https://github.com/TriliumNext/Trilium/pull/294">#294</a>
</li>
<li>
<p><a href="https://github.com/TriliumNext/Trilium/issues/375">Note Tooltip isn't removed when clicking on internal trilium link in read-only mode</a>
</p>
</li>
<li>
<p><a href="https://github.com/TriliumNext/Trilium/issues/384">Calendar dropdown won't close if click/right-click other button that open notes from launcher bar</a>
</p>
</li>
</ul>
`;
const expected = trimIndentation`\
* [@JYC333](https://github.com/JYC333) made their first contribution in [#294](https://github.com/TriliumNext/Trilium/pull/294)
* [Note Tooltip isn't removed when clicking on internal trilium link in read-only mode](https://github.com/TriliumNext/Trilium/issues/375)
* [Calendar dropdown won't close if click/right-click other button that open notes from launcher bar](https://github.com/TriliumNext/Trilium/issues/384)`;
expect(markdownExportService.toMarkdown(html)).toBe(expected);
});
it("preserves include note", () => {
const html = /*html*/`<section class="include-note" data-note-id="i4A5g9iOg9I0" data-box-size="full"> </section>`;
const expected = /*markdown*/`<section class="include-note" data-note-id="i4A5g9iOg9I0" data-box-size="full"> </section>`;
expect(markdownExportService.toMarkdown(html)).toBe(expected);
});
it("preserves an include note figure, with or without its caption", () => {
const start = `<figure class="include-note" data-note-id="i4A5g9iOg9I0"`
+ ` data-box-size="full">`;
const blank = `${start} </figure>`;
const captioned = `${start}<figcaption>A <strong>caption</strong></figcaption></figure>`;
expect(markdownExportService.toMarkdown(blank)).toBe(blank);
expect(markdownExportService.toMarkdown(`<p>Before</p>${captioned}<p>After</p>`))
.toBe(`Before\n\n${captioned}\n\nAfter`);
});
it("preserves a video saved with its caption, with the fallback link of the video", () => {
const url = "https://www.youtube.com/watch?v=abc";
const section = `<section class="link-embed" data-url="${url}" data-embed-type="youtube">`;
const figure = (content: string) => `<figure class="captioned-content-embed">${section}`
+ `${content}</section><figcaption>A <strong>caption</strong></figcaption></figure>`;
expect(markdownExportService.toMarkdown(`<p>Before</p>${figure("")}<p>After</p>`))
.toBe(`Before\n\n${figure(`<a href="${url}">${url}</a>`)}\n\nAfter`);
});
it("exports todo lists properly", () => {
const html = trimIndentation/*html*/`\
<ul class="todo-list">
<li>
<label class="todo-list__label">
<input type="checkbox" checked="checked" disabled="disabled"><span class="todo-list__label__description">Hello</span>
</label>
</li>
<li>
<label class="todo-list__label">
<input type="checkbox" disabled="disabled"><span class="todo-list__label__description">World</span>
</label>
</li>
</ul>
`;
const expected = trimIndentation`\
- [x] Hello
- [ ] World`;
expect(markdownExportService.toMarkdown(html)).toBe(expected);
});
it("exports todo list multistate markers from data-trilium-task-state", () => {
const html = trimIndentation/*html*/`\
<ul class="todo-list">
<li data-trilium-task-state="doing">
<label class="todo-list__label">
<input type="checkbox" disabled="disabled"><span class="todo-list__label__description">Doing</span>
</label>
</li>
<li data-trilium-task-state="done">
<label class="todo-list__label">
<input type="checkbox" checked="checked" disabled="disabled"><span class="todo-list__label__description">Done</span>
</label>
</li>
<li data-trilium-task-state="cancelled">
<label class="todo-list__label">
<input type="checkbox" disabled="disabled"><span class="todo-list__label__description">Cancelled</span>
</label>
</li>
<li data-trilium-task-state="maybe">
<label class="todo-list__label">
<input type="checkbox" disabled="disabled"><span class="todo-list__label__description">Maybe</span>
</label>
</li>
</ul>
`;
const expected = trimIndentation`\
- [/] Doing
- [x] Done
- [-] Cancelled
- [?] Maybe`;
expect(markdownExportService.toMarkdown(html)).toBe(expected);
});
// A table with no heading row can't be expressed as a GFM table without
// inventing a phantom empty header (which would reimport as a blank row), so
// it is kept as raw HTML to round-trip faithfully.
it("keeps a table with no heading row as HTML", () => {
const html = trimIndentation/*html*/`\
<figure class="table">
<table>
<tbody>
<tr>
<td>
Hi
</td>
<td>
there
</td>
</tr>
<tr>
<td>
Hi
</td>
<td>
there
</td>
</tr>
</tbody>
</table>
</figure>
`;
const expected = `<table>
<tbody>
<tr>
<td>Hi</td>
<td>there</td>
</tr>
<tr>
<td>Hi</td>
<td>there</td>
</tr>
</tbody>
</table>`;
expect(markdownExportService.toMarkdown(html)).toBe(expected);
});
// The clipboard's "copy as markdown" never reimports, so it accepts the phantom header the
// note export refuses: a copied subset of body cells still comes out as a markdown table.
it("renders a headerless table under a blank header with headerlessTables: emptyHeader", () => {
const html = trimIndentation/*html*/`\
<figure class="table">
<table>
<tbody>
<tr><td>a1</td><td>b1</td></tr>
<tr><td>a2</td><td>b2</td></tr>
</tbody>
</table>
</figure>
`;
const expected = "| | |\n| --- | --- |\n| a1 | b1 |\n| a2 | b2 |";
expect(markdownExportService.toMarkdown(html, { headerlessTables: "emptyHeader" }))
.toBe(expected);
// The mode is per call, not sticky converter state.
expect(markdownExportService.toMarkdown(html)).toContain("<table>");
});
it("keeps a real heading row as the header under headerlessTables: emptyHeader", () => {
const html = "<table><thead><tr><th>h1</th><th>h2</th></tr></thead>"
+ "<tbody><tr><td>a1</td><td>b1</td></tr></tbody></table>";
const expected = "| h1 | h2 |\n| --- | --- |\n| a1 | b1 |";
expect(markdownExportService.toMarkdown(html, { headerlessTables: "emptyHeader" }))
.toBe(expected);
});
// Admonitions are block content, and GFM table cells can only hold inline
// content. Flattening the admonition into a cell produces unrenderable
// `> [!NOTE]<br>...` noise, so a table containing one is kept as raw HTML to
// degrade gracefully and round-trip faithfully.
it("keeps a table containing an admonition as HTML", () => {
const html = trimIndentation/*html*/`\
<figure class="table">
<table>
<thead>
<tr>
<th>Hello</th>
<th>world</th>
</tr>
</thead>
<tbody>
<tr>
<td>This is a table</td>
<td></td>
</tr>
<tr>
<td><aside class="admonition note"><p>With an admonition inside it</p></aside></td>
<td></td>
</tr>
</tbody>
</table>
</figure>
`;
const expected = `<table>
<thead>
<tr>
<th>Hello</th>
<th>world</th>
</tr>
</thead>
<tbody>
<tr>
<td>This is a table</td>
<td></td>
</tr>
<tr>
<td><aside class="admonition note"><p>With an admonition inside it</p></aside></td>
<td></td>
</tr>
</tbody>
</table>`;
expect(markdownExportService.toMarkdown(html)).toBe(expected);
});
it("preserves superscript and subscript", () => {
const html = /*html*/`<p>Hello <sup><strong>superscript</strong></sup> <sub><strong>subscript</strong></sub></p>`;
const expected = `Hello <sup><strong>superscript</strong></sup> <sub><strong>subscript</strong></sub>`;
expect(markdownExportService.toMarkdown(html)).toBe(expected);
});
it("maintains escaped HTML tags", () => {
const html = /*html*/`<p><div>Hello World</div></p>`;
const expected = `\\<div\\>Hello World\\</div\\>`;
expect(markdownExportService.toMarkdown(html)).toBe(expected);
});
it("escapes HTML tags inside list", () => {
const html = trimIndentation/*html*/`\
<ul>
<li data-list-item-id="e07fda078f7dd7103a3b9017f49eb1589">
<note> is note.
</li>
</ul>
`;
const expected = trimIndentation`\
* \\<note\\> is note.`;
expect(markdownExportService.toMarkdown(html)).toBe(expected);
});
it("keeps bookmarks as HTML anchors, so links to them still resolve after an import", () => {
const html = `<h3><a id="schema-note"></a><code>Note</code></h3>`
+ `<p>See <a href="#schema-note">the note</a>.<a id="end"></a></p>`
+ `<p><a id="say-"hi""></a>Quoted</p>`;
expect(markdownExportService.toMarkdown(html)).toBe(trimIndentation`\
### <a id="schema-note"></a>\`Note\`
See [the note](#schema-note).<a id="end"></a>
<a id="say-"hi""></a>Quoted`);
});
it("drops the block ids of a text note, which Markdown has no syntax for", () => {
const html = `<h2 data-trilium-block-id="h1">Title</h2>`
+ `<p data-trilium-block-id="p1">Text</p>`;
expect(markdownExportService.toMarkdown(html)).toBe("## Title\n\nText");
});
it("drops data-trilium-collapsed but keeps the collapsed item's children as bullets", () => {
// Collapsing is editor-only UI state (the nested items live in the content, hidden via
// CSS), and Markdown has no syntax for it — so the attribute is dropped on export while
// the nested structure still round-trips as ordinary bullets.
const html = trimIndentation/*html*/`\
<ul>
<li data-trilium-collapsed="true">
Parent
<ul>
<li>
Child
</li>
</ul>
</li>
<li>
Sibling
</li>
</ul>
`;
const expected = trimIndentation`\
* Parent
* Child
* Sibling`;
expect(markdownExportService.toMarkdown(html)).toBe(expected);
});
it("exports jQuery code in table properly", () => {
const html = trimIndentation`\
<figure class="table">
<table>
<thead>
<tr>
<th>
Code
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<pre>
<code class="language-text-x-trilium-auto">this.$widget = $("<div>");</code>
</pre>
</td>
</tr>
</tbody>
</table>
</figure>
`;
const expected = `<table>
<thead>
<tr>
<th>Code</th>
</tr>
</thead>
<tbody>
<tr>
<td><pre><code class="language-text-x-trilium-auto">this.$widget = $("<div>");</code>
</pre></td>
</tr>
</tbody>
</table>`;
expect(markdownExportService.toMarkdown(html)).toBe(expected);
});
it("renders emphasis with underscore", () => {
const html = /*html*/`<p>This is <em>underlined</em> text.</p>`;
const expected = `This is _underlined_ text.`;
expect(markdownExportService.toMarkdown(html)).toBe(expected);
});
describe("highlights and coloured text", () => {
it("renders a default-yellow highlight and a bare <mark> as ==text==", () => {
expect(markdownExportService.toMarkdown(
/*html*/`<p>A <span style="background-color:hsl(60, 75%, 60%);">highlight</span> here.</p>`
)).toBe("A ==highlight== here.");
// The same colour however the sanitizer or the editor spaced it out.
expect(markdownExportService.toMarkdown(
/*html*/`<p><span style="BACKGROUND-COLOR: hsl(60,75%,60%)">highlight</span></p>`
)).toBe("==highlight==");
expect(markdownExportService.toMarkdown(/*html*/`<p>A <mark>highlight</mark> here.</p>`))
.toBe("A ==highlight== here.");
});
it("renders the palette yellow as ==text==, ignoring its theme-adaptive variable", () => {
const yellow = `<span style="background-color:${HIGHLIGHT_BACKGROUND};">a</span>`;
expect(markdownExportService.toMarkdown(`<p>${yellow}</p>`)).toBe("==a==");
const withVariable = `<span style="${HIGHLIGHT_STYLE}">b</span>`;
expect(markdownExportService.toMarkdown(`<p>${withVariable}</p>`)).toBe("==b==");
// Another colour keeps its colour and its variable.
const red = `<span style="background-color:#e64d4d;--tn-background:#e64d4d;">c</span>`;
expect(markdownExportService.toMarkdown(`<p>${red}</p>`)).toBe(red);
});
it("keeps any other colour as inline HTML rather than repainting it yellow", () => {
// A different background colour...
expect(markdownExportService.toMarkdown(
/*html*/`<p>A <span style="background-color:rgb(0, 255, 0)">green</span> one.</p>`
)).toBe(`A <span style="background-color:rgb(0, 255, 0)">green</span> one.`);
// ...a foreground colour, which used to be dropped entirely...
expect(markdownExportService.toMarkdown(/*html*/`<p><span style="color:#ff0000">red</span></p>`))
.toBe(`<span style="color:#ff0000">red</span>`);
// ...and both at once.
expect(markdownExportService.toMarkdown(
/*html*/`<p><span style="color:#ffffff;background-color:#000000">both</span></p>`
)).toBe(`<span style="color:#ffffff;background-color:#000000">both</span>`);
expect(markdownExportService.toMarkdown(
/*html*/`<mark style="background-color:rgb(0, 255, 0)">green</mark>`
)).toBe(`<mark style="background-color:rgb(0, 255, 0)">green</mark>`);
});
it("keeps a default-yellow highlight whole when it carries anything ==…== cannot", () => {
// A second declaration would be lost by `==…==`, so the element is kept as-is.
expect(markdownExportService.toMarkdown(
/*html*/`<p><span style="background-color:hsl(60, 75%, 60%);font-family:serif">y</span></p>`
)).toBe(`<span style="background-color:hsl(60, 75%, 60%);font-family:serif">y</span>`);
expect(markdownExportService.toMarkdown(
/*html*/`<p><span class="tag" style="background-color:hsl(60, 75%, 60%)">y</span></p>`
)).toBe(`<span class="tag" style="background-color:hsl(60, 75%, 60%)">y</span>`);
});
it("converts the content to Markdown inside a preserved colour", () => {
expect(markdownExportService.toMarkdown(
/*html*/`<p><span style="color:#ff0000"><strong>bold</strong> and <em>italic</em></span></p>`
)).toBe(`<span style="color:#ff0000">**bold** and _italic_</span>`);
});
it("keeps inline formatting inside and around a highlight", () => {
expect(markdownExportService.toMarkdown(
/*html*/`<p><span style="background-color:hsl(60, 75%, 60%)"><strong>bold</strong></span></p>`
)).toBe("==**bold**==");
expect(markdownExportService.toMarkdown(
/*html*/`<p><strong><span style="background-color:hsl(60, 75%, 60%)">bold</span></strong></p>`
)).toBe("**==bold==**");
});
it("hoists whitespace out of the delimiters so the result parses back", () => {
expect(markdownExportService.toMarkdown(
/*html*/`<p>a<span style="background-color:hsl(60, 75%, 60%)"> hi </span>b</p>`
)).toBe("a ==hi== b");
});
it("leaves a coloured block and a highlighted formula alone", () => {
// Only inline colours are handled; a coloured block would wrap its whole text.
expect(markdownExportService.toMarkdown(/*html*/`<p style="background-color:yellow">para</p>`))
.toBe("para");
expect(markdownExportService.toMarkdown(
/*html*/`<p><span class="math-tex" style="background-color:yellow">\\(x^2\\)</span></p>`
)).toBe("$x^2$");
});
it("ignores a border colour, which is not a text colour", () => {
expect(markdownExportService.toMarkdown(
/*html*/`<p><span style="border-color:#ff0000">plain</span></p>`
)).toBe("plain");
});
it("emits no delimiters for a highlight with no text of its own", () => {
expect(markdownExportService.toMarkdown(
/*html*/`<p>a<span style="background-color:hsl(60, 75%, 60%)"><br></span>b</p>`
)).not.toContain("==");
});
it("does not touch == inside a code block", () => {
const html = /*html*/`<pre><code class="language-text-x-trilium-auto">a ==b== c</code></pre>`;
expect(markdownExportService.toMarkdown(html)).toBe("```\na ==b== c\n```");
});
});
describe("tabs blocks", () => {
const tab = (title: string, panel: string) =>
`<section class="trilium-tab"><p class="trilium-tab-title">${title}</p><div class="trilium-tab-panel">${panel}</div></section>`;
const tabs = (...items: string[]) => `<div class="trilium-tabs">${items.join("")}</div>`;
it("exports each tab as a MkDocs tabbed section with its panel indented four spaces", () => {
const html = tabs(
tab("Windows", "<p>Run the <strong>installer</strong>.</p><pre><code class=\"language-text-x-sh\">setup.exe</code></pre>"),
tab("Say \"hi\"", "<ul><li>One</li><li>Two</li></ul>")
);
expect(markdownExportService.toMarkdown(html)).toBe(trimIndentation`\
=== "Windows"
Run the **installer**.
\`\`\`sh
setup.exe
\`\`\`
=== "Say "hi""
* One
* Two`);
});
it("indents nested tabs once more and starts a block that follows another one with ===!", () => {
const html = tabs(tab("Outer", tabs(tab("Inner", "<p>x</p>")))) + tabs(tab("Next", "<p>y</p>"));
expect(markdownExportService.toMarkdown(html)).toBe(trimIndentation`\
=== "Outer"
=== "Inner"
x
===! "Next"
y`);
});
it("drops the tab alignment, which MkDocs content tabs cannot express", () => {
const html = "<div class=\"trilium-tabs\" data-trilium-tab-alignment=\"bottom\">" +
`${tab("Windows", "<p>a</p>")}</div>`;
expect(markdownExportService.toMarkdown(html)).toBe(trimIndentation`\
=== "Windows"
a`);
});
it("exports the icons and formatting of a tab title as inline Markdown", () => {
const html = tabs(
tab(`<span class="tn-icon bx bxl-chrome"></span> Chrome`, "<p>a</p>"),
tab("<strong>Bold</strong> and <code>code</code>", "<p>b</p>")
);
const markdown = markdownExportService.toMarkdown(html);
expect(markdown).not.toContain("");
expect(markdown).toBe(trimIndentation`\
=== "<span class="tn-icon bx bxl-chrome"></span>${"\u00A0"}Chrome"
a
=== "**Bold** and \`code\`"
b`);
});
});
describe("multicolumn layouts", () => {
const column = (content: string) =>
`<div class="trilium-multicolumn-column">${content}</div>`;
const layout = (ratios: string, ...columns: string[]) =>
`<div class="trilium-multicolumn-layout" data-trilium-column-ratios="${ratios}">` +
`${columns.map(column).join("")}</div>`;
it("writes each column as Markdown between the HTML tags of the layout", () => {
const html = `<p>Before</p>${layout("1-3",
"<p>First <strong>column</strong></p><ul><li>One</li></ul>",
"<h2>Second</h2><p>Text</p>"
)}<p>After</p>`;
expect(markdownExportService.toMarkdown(html)).toBe(trimIndentation`\
Before
<div class="trilium-multicolumn-layout" data-trilium-column-ratios="1-3">
<div class="trilium-multicolumn-column">
First **column**
* One
</div>
<div class="trilium-multicolumn-column">
## Second
Text
</div>
</div>
After`);
});
it("keeps a nested layout and the empty columns that Turndown would drop", () => {
const html = layout("1-1",
layout("1-2-1", "<p>Inner</p>", "<p> </p>", "<p> </p>"),
"<p>Outer</p>"
) + layout("3-1", "<p> </p>", "<p> </p>");
expect(markdownExportService.toMarkdown(html)).toBe(trimIndentation`\
<div class="trilium-multicolumn-layout" data-trilium-column-ratios="1-1">
<div class="trilium-multicolumn-column">
<div class="trilium-multicolumn-layout" data-trilium-column-ratios="1-2-1">
<div class="trilium-multicolumn-column">
Inner
</div>
<div class="trilium-multicolumn-column">
</div>
<div class="trilium-multicolumn-column">
</div>
</div>
</div>
<div class="trilium-multicolumn-column">
Outer
</div>
</div>
<div class="trilium-multicolumn-layout" data-trilium-column-ratios="3-1">
<div class="trilium-multicolumn-column">
</div>
<div class="trilium-multicolumn-column">
</div>
</div>`);
});
});
});