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 {
getMarkdownNameFromCKEditorLanguage, MIME_TYPES_DICT, normalizeMimeTypeForCKEditor,
trimIndentation
} from "@triliumnext/commons";
import { describe, expect, it } from "vitest";
import markdownExportService from "../export/markdown.js";
import markdownService from "./markdown.js";
describe("markdown", () => {
it("rewrites language of known language tags", () => {
const conversionTable = {
"nginx": "language-text-x-nginx-conf",
"diff": "language-text-x-diff",
"javascript": "language-text-javascript",
"css": "language-text-css",
"mips": "language-text-x-asm-mips",
"jsx": "language-text-jsx",
"html": "language-text-html"
};
for (const [ input, output ] of Object.entries(conversionTable)) {
const result = markdownService.renderToHtml(trimIndentation`\
\`\`\`${input}
Hi
\`\`\`
`, "title");
expect(result).toBe(trimIndentation`\
<pre><code class="${output}">Hi</code></pre>`);
}
});
it("round-trips the language of every named code block through the Markdown exporter", () => {
const languages = MIME_TYPES_DICT
.map((mimeType) => normalizeMimeTypeForCKEditor(mimeType.mime))
.filter((language) => getMarkdownNameFromCKEditorLanguage(language) !== undefined);
expect(languages).toEqual(expect.arrayContaining([
"text-plain", "text-x-csrc", "text-x-c-src", "text-typescript-jsx", "text-x-scala",
"text-jinja2", "text-x-mysql", "text-x-spreadsheet"
]));
for (const language of languages) {
const original = `<pre><code class="language-${language}">Hi</code></pre>`;
const markdown = markdownExportService.toMarkdown(original);
expect(markdownService.renderToHtml(markdown, "Title"), language)
.toStrictEqual(original);
}
});
it("rewrites language of unknown language tags", () => {
const result = markdownService.renderToHtml(trimIndentation`\
\`\`\`unknownlanguage
Hi
\`\`\`
`, "title");
expect(result).toBe(trimIndentation`\
<pre><code class="language-text-x-trilium-auto">Hi</code></pre>`);
});
it("converts h1 heading", () => {
const result = markdownService.renderToHtml(trimIndentation`\
# Hello
## world
# another one
Hello, world
`, "title");
// <h1> is reserved for the note title, so the hierarchy is shifted down one
// level rather than collapsed: the two top-level `#` become <h2> siblings and
// the nested `##` becomes <h3>, preserving the author's nesting (#8383).
expect(result).toBe(`<h2>Hello</h2><h3>world</h3><h2>another one</h2><p>Hello, world</p>`);
});
it("preserves heading hierarchy by shifting levels when content starts at H1 (#8383)", () => {
// Content authored with H1 as the top level: every heading shifts down one
// level so the parent/child relationship survives instead of flattening onto H2.
expect(markdownService.renderToHtml(trimIndentation`\
# Main Section
## Subsection A
### Detail
## Subsection B
`, "Notes")).toBe(`<h2>Main Section</h2><h3>Subsection A</h3><h4>Detail</h4><h3>Subsection B</h3>`);
// The first H1 matching the title is stripped; if a content H1 still remains,
// the rest is shifted, otherwise it is left untouched.
expect(markdownService.renderToHtml(trimIndentation`\
# Notes
# Chapter 1
## Section
`, "Notes")).toBe(`<h2>Chapter 1</h2><h3>Section</h3>`);
// Common case: title is stripped and the content already starts at H2 — no shift.
expect(markdownService.renderToHtml(trimIndentation`\
# Notes
## Section
### Sub
`, "Notes")).toBe(`<h2>Section</h2><h3>Sub</h3>`);
// Deeper levels clamp at H6 (there is no H7 to shift into).
expect(markdownService.renderToHtml(trimIndentation`\
# Top
##### Five
###### Six
`, "Notes")).toBe(`<h2>Top</h2><h6>Five</h6><h6>Six</h6>`);
});
it("parses duplicate title with escape correctly", () => {
const titles = [
"What's new",
"Node.js, Electron and `better-sqlite3`"
];
for (const title of titles) {
const result = markdownService.renderToHtml(trimIndentation`\
# ${title}
Hi there
`, title);
expect(result).toBe(`<p>Hi there</p>`);
}
});
it("trims unnecessary whitespace", () => {
const input = `\
## Heading 1
Title
\`\`\`
code block 1
second line 2
\`\`\`
* Hello
* world
1. Hello
2. World
`;
const expected = `\
<h2>Heading 1</h2><p>Title</p><pre><code class="language-text-x-trilium-auto">code block 1
second line 2</code></pre><ul><li>Hello</li><li>world</li></ul><ol><li>Hello</li><li>World</li></ol>`;
expect(markdownService.renderToHtml(input, "Troubleshooting")).toBe(expected);
});
it("imports admonitions properly", () => {
const space = " "; // editor config trimming space.
const input = trimIndentation`\
Before
> [!NOTE]
> This is a note.
> [!TIP]
> This is a tip.
> [!IMPORTANT]
> This is a very important information.
> [!CAUTION]
> This is a caution.
> [!WARNING]
> ## Title goes here
>${space}
> This is a warning.
After`;
const expected = `<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></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>`;
expect(markdownService.renderToHtml(input, "Title")).toStrictEqual(expected);
});
it("imports images with same outcome as if inserted from CKEditor", () => {
const input = "";
const expected = `<p><img src="api/attachments/YbkR3wt2zMcA/image/image"></p>`;
expect(markdownService.renderToHtml(input, "Title")).toStrictEqual(expected);
});
it("maintains code blocks with XML/HTML", () => {
const input = trimIndentation`\
Before
\`\`\`
<application
...
android:testOnly="false">
...
</application>
\`\`\`
After`;
const expected = trimIndentation`\
<p>Before</p><pre><code class="language-text-x-trilium-auto"><application
...
android:testOnly="false">
...
</application></code></pre><p>After</p>`;
expect(markdownService.renderToHtml(input, "Title")).toStrictEqual(expected);
});
it("does not escape unneeded characters", () => {
const input = `It's important to note that these examples are not natively supported by Trilium out of the box; instead, they demonstrate what you can build within Trilium.`;
const expected = `<p>It's important to note that these examples are not natively supported by Trilium out of the box; instead, they demonstrate what you can build within Trilium.</p>`;
expect(markdownService.renderToHtml(input, "Title")).toStrictEqual(expected);
});
it("preserves ", () => {
const input = `Hello world.`;
const expected = /*html*/`<p>Hello world.</p>`;
expect(markdownService.renderToHtml(input, "Title")).toStrictEqual(expected);
});
it("converts non-breaking space character to ", () => {
const input = `Hello\u00a0world.`;
const expected = /*html*/`<p>Hello world.</p>`;
expect(markdownService.renderToHtml(input, "Title")).toStrictEqual(expected);
});
it("supports normal links", () => {
const input = `[Google](https://www.google.com)`;
const expected = /*html*/`<p><a href="https://www.google.com">Google</a></p>`;
expect(markdownService.renderToHtml(input, "Title")).toStrictEqual(expected);
});
it("does not touch relative links", () => {
const input = `[Canvas](../../Canvas.html)`;
const expected = /*html*/`<p><a href="../../Canvas.html">Canvas</a></p>`;
expect(markdownService.renderToHtml(input, "Title")).toStrictEqual(expected);
});
it("imports back to reference links", () => {
const input = `<a class="reference-link" href="../../Canvas.html">Canvas</a>`;
const expected = /*html*/`<p><a class="reference-link" href="../../Canvas.html">Canvas</a></p>`;
expect(markdownService.renderToHtml(input, "Title")).toStrictEqual(expected);
});
it("imports back link previews exported as raw HTML", () => {
// The Markdown exporter emits link previews as their canonical HTML plus a fallback
// anchor; both forms must survive sanitization so the editor can upcast them again.
const block = '<section class="link-embed" data-url="https://e.com/" data-embed-type="opengraph" data-title="Example"><a href="https://e.com/">Example</a></section>';
expect(markdownService.renderToHtml(block, "Title")).toStrictEqual(block);
const inline = 'See <span class="link-mention" data-url="https://e.com/" data-title="Example"><a href="https://e.com/">Example</a></span> for details.';
expect(markdownService.renderToHtml(inline, "Title")).toStrictEqual(`<p>${inline}</p>`);
});
it("preserves figures and images with sizes", () => {
const scenarios = [
/*html*/`<figure class="image image-style-align-center image_resized" style="width:53.44%;"><img style="aspect-ratio:991/403;" src="Jump to Note_image.png" width="991" height="403"></figure>`,
/*html*/`<figure class="image image-style-align-center image_resized" style="width:53.44%;"><img style="aspect-ratio:991/403;" src="Jump to Note_image.png" width="991" height="403"></figure>`,
/*html*/`<img class="image_resized" style="aspect-ratio:853/315;width:50%;" src="6_File_image.png" width="853" height="315">`
];
for (const scenario of scenarios) {
expect(markdownService.renderToHtml(scenario, "Title")).toStrictEqual(scenario);
}
});
it("converts inline math expressions into Mathtex format", () => {
const input = `The equation is\u00a0$e=mc^{2}$.`;
const expected = /*html*/`<p>The equation is <span class="math-tex">\\(e=mc^{2}\\)</span>.</p>`;
expect(markdownService.renderToHtml(input, "Title")).toStrictEqual(expected);
});
it("converts multiple inline math expressions into Mathtex format", () => {
const input = `Energy: $e=mc^{2}$, Force: $F=ma$.`;
const expected = /*html*/`<p>Energy: <span class="math-tex">\\(e=mc^{2}\\)</span>, Force: <span class="math-tex">\\(F=ma\\)</span>.</p>`;
expect(markdownService.renderToHtml(input, "Title")).toStrictEqual(expected);
});
it("converts multi-line display math expressions into Mathtex format", () => {
const input = `$$
\\sqrt{x^{2}+1} \\
+ \\frac{1}{2}
$$`;
const expected = /*html*/`<span class="math-tex">\\[
\\sqrt{x^{2}+1} \\
+ \\frac{1}{2}
\\]</span>`;
expect(markdownService.renderToHtml(input, "Title")).toStrictEqual(expected);
});
it("escapes HTML-significant characters in display math so they survive sanitization (#10418)", () => {
// The `<` in `k<K` used to be treated as the start of an HTML tag by the
// sanitizer, which stripped everything from `<K` onwards and truncated the
// formula. Escaping `<`/`>`/`&` (matching how CKEditor serializes the math
// text node) keeps the whole equation intact.
const input = `$$
\\min_{0\\le k<K}\\|\\operatorname{grad}\\Phi(x_k)\\|^2 = O(1/K),
$$`;
const expected = /*html*/`<span class="math-tex">\\[
\\min_{0\\le k<K}\\|\\operatorname{grad}\\Phi(x_k)\\|^2 = O(1/K),
\\]</span>`;
expect(markdownService.renderToHtml(input, "Title")).toStrictEqual(expected);
});
it("escapes HTML-significant characters in inline math (#10418)", () => {
const input = `Condition: $a<b$ and $c>d$ with $x \\& y$.`;
const expected = /*html*/`<p>Condition: <span class="math-tex">\\(a<b\\)</span> and <span class="math-tex">\\(c>d\\)</span> with <span class="math-tex">\\(x \\& y\\)</span>.</p>`;
expect(markdownService.renderToHtml(input, "Title")).toStrictEqual(expected);
});
it("ignores math formulas inside code blocks and converts inline math expressions correctly", () => {
const result = markdownService.renderToHtml(trimIndentation`\
\`\`\`unknownlanguage
$$a+b$$
\`\`\`
`, "title");
expect(result).toBe(trimIndentation`\
<pre><code class="language-text-x-trilium-auto">$$a+b$$</code></pre>`);
});
it("imports dollar amounts as literal text (#5682)", () => {
const input = `Assembled Item A has an Avg cost of $15. A Raw Material has an Avg cost of $6.`;
const expected = /*html*/`<p>Assembled Item A has an Avg cost of $15. A Raw Material has an Avg cost of $6.</p>`;
expect(markdownService.renderToHtml(input, "Title")).toStrictEqual(expected);
});
it("converts specific inline math expression into Mathtex format", () => {
const input = `This is a formula: $\\mathcal{L}_{task} + \\mathcal{L}_{od}$ inside a sentence.`;
const expected = /*html*/`<p>This is a formula: <span class="math-tex">\\(\\mathcal{L}_{task} + \\mathcal{L}_{od}\\)</span> inside a sentence.</p>`;
expect(markdownService.renderToHtml(input, "Title")).toStrictEqual(expected);
});
it("converts math expressions inside list items into Mathtex format", () => {
const input = `- First item with formula: $E = mc^2$`;
const expected = /*html*/`<ul><li>First item with formula: <span class="math-tex">\\(E = mc^2\\)</span></li></ul>`;
expect(markdownService.renderToHtml(input, "Title")).toStrictEqual(expected);
});
it("converts display math expressions into Mathtex format", () => {
const input = `$$\sqrt{x^{2}+1}$$`;
const expected = /*html*/`<span class="math-tex">\\[\sqrt{x^{2}+1}\\]</span>`;
expect(markdownService.renderToHtml(input, "Title")).toStrictEqual(expected);
});
it("renders escaped math delimiters as literal dollars without rendering math (#10179)", () => {
// `\$` is a standard Markdown escape: the backslash is consumed and the dollar
// is kept literal (never treated as a formula delimiter). The escape must NOT
// leak extra backslashes into the output — the reported bug doubled them to `\\$`.
const scenarios: [input: string, expected: string][] = [
["\\$\\$\sqrt{x^{2}+1}\\$\\$", `<p>$$\sqrt{x^{2}+1}$$</p>`],
["The equation is \\$e=mc^{2}\\$.", `<p>The equation is $e=mc^{2}$.</p>`]
];
for (const [input, expected] of scenarios) {
const html = markdownService.renderToHtml(input, "Title");
expect(html).toStrictEqual(expected);
expect(html).not.toContain("math-tex");
}
});
it("preserves table with column widths", () => {
const html = /*html*/`<figure class="table" style="width:100%;"><table class="ck-table-resized"><colgroup><col style="width:2.77%;"><col style="width:33.42%;"><col style="width:63.81%;"></colgroup><thead><tr><th> </th><th> </th><th> </th></tr></thead><tbody><tr><td>1</td><td><img class="image_resized" style="aspect-ratio:562/454;width:100%;" src="1_Geo Map_image.png" width="562" height="454"></td><td>Go to any location on openstreetmap.org and right click to bring up the context menu. Select the “Show address” item.</td></tr><tr><td>2</td><td><img class="image_resized" style="aspect-ratio:696/480;width:100%;" src="Geo Map_image.png" width="696" height="480"></td><td>The address will be visible in the top-left of the screen, in the place of the search bar. <br><br>Select the coordinates and copy them into the clipboard.</td></tr><tr><td>3</td><td><img class="image_resized" style="aspect-ratio:640/276;width:100%;" src="5_Geo Map_image.png" width="640" height="276"></td><td>Simply paste the value inside the text box into the <code>#geolocation</code> attribute of a child note of the map and then it should be displayed on the map.</td></tr></tbody></table></figure>`;
expect(markdownService.renderToHtml(html, "Title")).toStrictEqual(html);
});
it("preserves table cell colspan", () => {
const html = /*html*/`<figure class="table"><table><tbody><tr><td colspan="2">Merged</td></tr><tr><td>A</td><td>B</td></tr></tbody></table></figure>`;
expect(markdownService.renderToHtml(html, "Title")).toStrictEqual(html);
});
it("preserves table cell rowspan", () => {
const html = /*html*/`<figure class="table"><table><tbody><tr><td rowspan="2">Merged</td><td>A</td></tr><tr><td>B</td></tr></tbody></table></figure>`;
expect(markdownService.renderToHtml(html, "Title")).toStrictEqual(html);
});
it("preserves colspan and rowspan together on header and body cells", () => {
const html = /*html*/`<figure class="table"><table><thead><tr><th colspan="2">Header</th></tr></thead><tbody><tr><td rowspan="2">Side</td><td>A</td></tr><tr><td>B</td></tr></tbody></table></figure>`;
expect(markdownService.renderToHtml(html, "Title")).toStrictEqual(html);
});
// The exporter keeps headerless tables (and heading-column-only tables) as raw
// HTML rather than inventing a phantom empty header row, pretty-printed across
// multiple indented lines. Confirm the import side passes that exact multi-line
// HTML through unchanged (no blank lines means it stays a single HTML block), so
// the round-trip introduces no blank row.
it("preserves a headerless table (heading columns only) without a phantom header row", () => {
// Exactly what the Markdown exporter emits for such a table.
const html = [
`<table>`,
` <tbody>`,
` <tr>`,
` <th>Heading</th>`,
` <td>Not a heading</td>`,
` </tr>`,
` <tr>`,
` <td>Heading</td>`,
` <td>Not a heading</td>`,
` </tr>`,
` </tbody>`,
`</table>`
].join("\n");
const expected = [
`<figure class="table"><table><tbody>`,
`<tr><th>Heading</th><td>Not a heading</td></tr>`,
`<tr><td>Heading</td><td>Not a heading</td></tr>`,
`</tbody></table></figure>`
].join("");
const result = markdownService.renderToHtml(html, "Title");
expect(result).toStrictEqual(expected);
// No synthesized empty header row leaked in.
expect(result).not.toContain("<thead>");
expect(result).not.toContain("<th></th>");
});
it("generates strike-through text", () => {
const input = `~~Hello~~ world.`;
const expected = /*html*/`<p><del>Hello</del> world.</p>`;
expect(markdownService.renderToHtml(input, "Title")).toStrictEqual(expected);
});
it("does not generate additional spacing when importing lists", () => {
const input = trimIndentation`\
### 🐞 Bugfixes
* [v0.90.4 docker does not read USER\_UID and USER\_GID from environment](https://github.com/TriliumNext/Trilium/issues/331)
* [Invalid CSRF token on Android phone](https://github.com/TriliumNext/Trilium/issues/318)
* [Excess spacing in lists](https://github.com/TriliumNext/Trilium/issues/341)`;
const expected = [
/*html*/`<h3>🐞 Bugfixes</h3>`,
/*html*/`<ul>`,
/*html*/`<li><a href="https://github.com/TriliumNext/Trilium/issues/331">v0.90.4 docker does not read USER_UID and USER_GID from environment</a></li>`,
/*html*/`<li><a href="https://github.com/TriliumNext/Trilium/issues/318">Invalid CSRF token on Android phone</a></li>`,
/*html*/`<li><a href="https://github.com/TriliumNext/Trilium/issues/341">Excess spacing in lists</a></li>`,
/*html*/`</ul>`
].join("");
expect(markdownService.renderToHtml(input, "Title")).toStrictEqual(expected);
});
it("imports todo lists properly", () => {
const input = trimIndentation`\
- [x] Hello
- [ ] World`;
const expected = `<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>`;
expect(markdownService.renderToHtml(input, "Title")).toStrictEqual(expected);
});
it("splits a todo list at a blank line into the lists the exporter wrote it from", () => {
// A blank line makes the list loose, so marked wraps each item in <p>. Left that
// way the checkbox lands inside the description span, where neither CKEditor's
// upcast nor `.todo-list__label > input` reaches it and the note shows a bare
// native checkbox. An empty `- [ ]` is not a task marker at all — it stays text.
const input = trimIndentation`\
Add a line break between two checkbox:
- [ ] Truc
- [ ] Machin
An empty item:
- [ ]`;
const todoList = (text: string) =>
`<ul class="todo-list"><li><label class="todo-list__label"><input type="checkbox" disabled="disabled">` +
`<span class="todo-list__label__description">${text}</span></label></li></ul>`;
const expected = [
`<p>Add a line break between two checkbox:</p>`,
todoList("Truc"),
`<p> </p>`,
todoList("Machin"),
`<p>An empty item:</p>`,
`<ul><li>[ ]</li></ul>`
].join("");
expect(markdownService.renderToHtml(input, "Title")).toStrictEqual(expected);
});
it("round-trips two todo lists separated by an empty paragraph through the Markdown exporter", () => {
const todoList = (text: string) =>
`<ul class="todo-list"><li><label class="todo-list__label"><input type="checkbox" disabled="disabled">` +
`<span class="todo-list__label__description">${text}</span></label></li></ul>`;
const original = `${todoList("Truc")}<p> </p>${todoList("Machin")}`;
expect(markdownService.renderToHtml(markdownExportService.toMarkdown(original), "Title")).toStrictEqual(original);
});
it("round-trips a list nested under a multi-digit ordered item through the Markdown exporter", () => {
for (const position of [ 9, 10, 100 ]) {
const siblings = Array.from({ length: position - 1 }, (_, index) => `<li>Item ${index + 1}</li>`).join("");
const original = `<ol>${siblings}<li>Parent<ol><li>First</li><li>Second</li></ol></li></ol>`;
expect(markdownService.renderToHtml(markdownExportService.toMarkdown(original), "Title"), `item ${position}`)
.toStrictEqual(original);
}
});
it("keeps the starting number of an ordered list, including through the Markdown exporter", () => {
const input = trimIndentation`\
3. Third
4. Fourth`;
const expected = `<ol start="3"><li>Third</li><li>Fourth</li></ol>`;
expect(markdownService.renderToHtml(input, "Title")).toStrictEqual(expected);
expect(markdownService.renderToHtml(markdownExportService.toMarkdown(expected), "Title")).toStrictEqual(expected);
});
it("imports todo list multistate markers as data-trilium-task-state and titles the <li> with the state's human name", () => {
// The `title` attribute mirrors what the CKEditor data downcast emits — it's
// the hover tooltip viewers of the shared page, the read-only preview and
// exported HTML rely on to name a custom task state.
const input = trimIndentation`\
- [/] Doing
- [-] Cancelled
- [?] Maybe`;
const expected = [
`<ul class="todo-list">`,
`<li data-trilium-task-state="doing" title="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="cancelled" title="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" title="Maybe"><label class="todo-list__label"><input type="checkbox" disabled="disabled"><span class="todo-list__label__description">Maybe</span></label></li>`,
`</ul>`
].join("");
expect(markdownService.renderToHtml(input, "Title")).toStrictEqual(expected);
});
it("supports wikilink with root-relative path", () => {
const input = `oh no my banana I bought on [[journal/monday]] has gone off! I’m taking it back to the [[other/shop]] for a refund`;
const expected = `<p>oh no my banana I bought on <a class="reference-link" href="/journal/monday">journal/monday</a> has gone off! I’m taking it back to the <a class="reference-link" href="/other/shop">other/shop</a> for a refund</p>`;
expect(markdownService.renderToHtml(input, "Title")).toStrictEqual(expected);
});
it("supports wikilink in lists", () => {
const input = `- oh no my banana I bought on [[journal/monday]] has gone off! I’m taking it back to the [[other/shop]] for a refund`;
const expected = `<ul><li>oh no my banana I bought on <a class="reference-link" href="/journal/monday">journal/monday</a> has gone off! I’m taking it back to the <a class="reference-link" href="/other/shop">other/shop</a> for a refund</li></ul>`;
expect(markdownService.renderToHtml(input, "Title")).toStrictEqual(expected);
});
it("supports wikilink with image (transclusion)", () => {
const input = `heres the handsome boy ![[assets/2025-06-20_14-05-20.jpeg]]`;
const expected = `<p>heres the handsome boy <img src="/assets/2025-06-20_14-05-20.jpeg"></p>`;
expect(markdownService.renderToHtml(input, "Title")).toStrictEqual(expected);
});
it("preserves superscript and subscript", () => {
const input = `Hello <sup>superscript</sup> <sub>subscript</sub>`;
const expected = /*html*/`<p>Hello <sup>superscript</sup> <sub>subscript</sub></p>`;
expect(markdownService.renderToHtml(input, "Title")).toStrictEqual(expected);
});
it("renders inline code as a plain <code> element", () => {
const input = `This is some inline code: \`const x = 10;\``;
const expected = /*html*/`<p>This is some inline code: <code>const x = 10;</code></p>`;
expect(markdownService.renderToHtml(input, "Title")).toStrictEqual(expected);
});
it("preserves HTML entities in list", () => {
const input = `* <note> is note.`;
const expected = /*html*/`<ul><li><note> is note.</li></ul>`;
expect(markdownService.renderToHtml(input, "Title")).toStrictEqual(expected);
});
it("keeps the trailing semicolon CKEditor writes into a style attribute", () => {
// Without it, the first save after an import rewrites every styled element in the note.
const input = `<ul style="list-style-type:disc;margin-left:0px;"><li style="margin-left:0px">Item</li></ul>`;
const expected = `<ul style="list-style-type:disc;margin-left:0px;"><li style="margin-left:0px;">Item</li></ul>`;
expect(markdownService.renderToHtml(input, "Title")).toStrictEqual(expected);
// Sanitization drops an empty attribute, so nothing comes back holding `style=";"`.
expect(markdownService.renderToHtml(`<p style="">Empty</p>`, "Title")).toStrictEqual(`<p>Empty</p>`);
});
it("brings an exported icon back in the form it left", () => {
// The User Guide is kept as Markdown and read back from it, so an icon the exporter gives
// up on is gone from the note as well on the next pass through `edit-docs`.
const cog = `<span class="tn-icon bx bx-cog"></span>`;
for (const html of [
`<p>Press ${cog} to open it.</p>`,
`<p>${cog}</p>`,
`<p>a<span style="color:rgb(255,0,0);">${cog}</span>b</p>`,
`<ul><li>In a list ${cog} here</li></ul>`
]) {
const markdown = markdownExportService.toMarkdown(html);
expect(markdownService.renderToHtml(markdown, "Title")).toStrictEqual(html);
}
});
describe("collapsible blocks", () => {
it("re-stamps the trilium-collapsible class and drops the indentation the exporter adds, so the block matches what the editor downcasts", () => {
const input = trimIndentation`\
<details>
<summary>Configuration change</summary>
<p>Set the following:</p>
<pre><code class="language-text-x-yaml">entryPoints:
web:
http: true</code></pre>
<aside class="admonition tip"><p>A tip.</p></aside>
</details>`;
const expected = [
`<details class="trilium-collapsible"><summary>Configuration change</summary><p>Set the following:</p>`,
`<pre><code class="language-text-x-yaml">entryPoints:\n web:\n http: true</code></pre>`,
`<aside class="admonition tip"><p>A tip.</p></aside></details>`
].join("");
expect(markdownService.renderToHtml(input, "Title")).toStrictEqual(expected);
});
it("writes the class before an expanded block's open attribute and strips the indentation of nested lists", () => {
const input = trimIndentation`\
<details open="">
<summary>Sum</summary>
<ol>
<li>
<span>First</span>
<ul>
<li>
<span>Nested</span>
</li>
</ul>
</li>
</ol>
</details>`;
const expected = `<details class="trilium-collapsible" open=""><summary>Sum</summary><ol><li><span>First</span><ul><li><span>Nested</span></li></ul></li></ol></details>`;
expect(markdownService.renderToHtml(input, "Title")).toStrictEqual(expected);
});
it("keeps a user-added class, adds the styling hook only once and leaves an element holding text of its own untouched", () => {
expect(markdownService.renderToHtml(`<details class="custom"><summary>S</summary><p>B</p></details>`, "Title"))
.toStrictEqual(`<details class="custom trilium-collapsible"><summary>S</summary><p>B</p></details>`);
expect(markdownService.renderToHtml(`<details class="trilium-collapsible"><summary>S</summary><p>B</p></details>`, "Title"))
.toStrictEqual(`<details class="trilium-collapsible"><summary>S</summary><p>B</p></details>`);
expect(markdownService.renderToHtml(`<details>Just some <em>text</em> here</details>`, "Title"))
.toStrictEqual(`<details class="trilium-collapsible">Just some <em>text</em> here</details>`);
});
it("round-trips a code block with blank lines inside a collapsible block or a table kept as HTML", () => {
const code = `<pre><code class="language-text-x-trilium-auto">a {\n}\n\n \n:root {\n --x: 1;\n}</code></pre>`;
for (const html of [
`<details class="trilium-collapsible"><summary>S</summary>${code}<p>After</p></details><p>Outside</p>`,
`<figure class="table"><table><tbody><tr><td>${code}</td><td>B</td></tr></tbody></table></figure><p>Outside</p>`
]) {
const markdown = markdownExportService.toMarkdown(html);
expect(markdown).toContain("<pre>");
expect(markdownService.renderToHtml(markdown, "Title")).toStrictEqual(html);
}
});
it("leaves a <details> shown inside a fenced code block as escaped sample text", () => {
const input = trimIndentation`\
\`\`\`html
<details><summary>S</summary></details>
\`\`\``;
expect(markdownService.renderToHtml(input, "Title"))
.toStrictEqual(`<pre><code class="language-text-html"><details><summary>S</summary></details></code></pre>`);
});
it("round-trips a collapsible block through the Markdown exporter unchanged", () => {
const original = [
`<details class="trilium-collapsible" open=""><summary>Configuration change</summary>`,
`<p>Set the <a href="https://example.com"><strong>static</strong> configuration</a>:</p>`,
`<pre><code class="language-text-x-yaml">entryPoints:\n web:\n http: true</code></pre>`,
`<aside class="admonition tip"><p>A tip.</p></aside></details>`
].join("");
expect(markdownService.renderToHtml(markdownExportService.toMarkdown(original), "Title")).toStrictEqual(original);
});
});
describe("tables", () => {
it("wraps a table kept as raw HTML in the figure CKEditor downcasts, and drops the indentation the exporter adds", () => {
const input = trimIndentation`\
<table class="ck-table-resized" style="border-style:none;">
<colgroup>
<col style="width:80.6%;">
<col style="width:19.4%;">
</colgroup>
<tbody>
<tr>
<td>a</td>
<td>b</td>
</tr>
</tbody>
</table>`;
const expected = [
`<figure class="table"><table class="ck-table-resized" style="border-style:none;">`,
`<colgroup><col style="width:80.6%;"><col style="width:19.4%;"></colgroup>`,
`<tbody><tr><td>a</td><td>b</td></tr></tbody></table></figure>`
].join("");
expect(markdownService.renderToHtml(input, "Title")).toStrictEqual(expected);
});
it("leaves a table the renderer already wrapped alone rather than nesting a second figure", () => {
const input = trimIndentation`\
| a | b |
| --- | --- |
| 1 | 2 |`;
const expected = [
`<figure class="table"><table><thead><tr><th>a</th><th>b</th></tr></thead>`,
`<tbody><tr><td>1</td><td>2</td></tr></tbody></table></figure>`
].join("");
expect(markdownService.renderToHtml(input, "Title")).toStrictEqual(expected);
});
it("keeps the whitespace inside a cell, which carries inline content rather than blocks", () => {
const input = `<table><tbody><tr><td>a <em>b</em> c</td><td> </td></tr></tbody></table>`;
const expected = `<figure class="table"><table><tbody><tr><td>a <em>b</em> c</td><td> </td></tr></tbody></table></figure>`;
expect(markdownService.renderToHtml(input, "Title")).toStrictEqual(expected);
});
it("round-trips a table through the Markdown exporter unchanged, whether it is kept as raw HTML or written as a pipe table", () => {
for (const original of [
`<figure class="table"><table class="ck-table-resized" style="border-style:none;"><colgroup><col style="width:80.6%;"><col style="width:19.4%;"></colgroup><thead><tr><th>a</th><th>b</th></tr></thead><tbody><tr><td><ul><li>one</li></ul></td><td>2</td></tr></tbody></table></figure>`,
`<figure class="table"><table><thead><tr><th>a</th><th>b</th></tr></thead><tbody><tr><td>1</td><td>2</td></tr></tbody></table></figure>`,
`<details class="trilium-collapsible"><summary>S</summary><figure class="table"><table class="ck-table-resized"><colgroup><col style="width:50%;"></colgroup><tbody><tr><td>x</td></tr></tbody></table></figure></details>`
]) {
const markdown = markdownExportService.toMarkdown(original);
expect(markdownService.renderToHtml(markdown, "Title")).toStrictEqual(original);
expect(markdownExportService.toMarkdown(markdownService.renderToHtml(markdown, "Title"))).toStrictEqual(markdown);
}
});
});
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("renders MkDocs tabbed sections as a tabs block, starting a new block at ===!", () => {
const input = trimIndentation`\
=== "Windows"
Run the **installer**.
=== "**Linux** <span class="tn-icon bx bxl-tux"></span>"
- One
- Two
===! "Other"
x
After.`;
expect(markdownService.renderToHtml(input, "Title")).toStrictEqual(
tabs(
tab("Windows", "<p>Run the <strong>installer</strong>.</p>"),
tab(`<strong>Linux</strong> <span class="tn-icon bx bxl-tux"></span>`, "<ul><li>One</li><li>Two</li></ul>")
) +
tabs(tab("Other", "<p>x</p>")) +
"<p>After.</p>"
);
});
it("round-trips tabs blocks through the Markdown exporter", () => {
const original =
tabs(
tab("Windows", "<p>Run the <strong>installer</strong>.</p><ul><li>One</li><li>Two</li></ul>"),
tab(" ", "<p> </p>"),
tab(`<span class="tn-icon bx bxl-chrome"></span> Chrome`, "<p>c</p>"),
tab("<strong>Bold</strong>, <em>italic</em> and <code>code</code>", "<p>f</p>"),
tab("a <b> *c* \"d\"", "<p>t</p>"),
tab("Nested", tabs(tab("A", "<p>a</p>"), tab("B", "<blockquote><p>b</p></blockquote>")))
) +
tabs(tab("Next", "<p>y</p>"));
expect(markdownService.renderToHtml(markdownExportService.toMarkdown(original), "Title"))
.toStrictEqual(original);
});
});
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>`;
const roundTrip = (html: string) =>
markdownService.renderToHtml(markdownExportService.toMarkdown(html), "Title");
it("round-trips layouts through the Markdown exporter unchanged", () => {
const table = "<figure class=\"table\"><table><tbody>" +
"<tr><td>a</td><td>b</td></tr>" +
"</tbody></table></figure>";
const collapsible = "<details class=\"trilium-collapsible\">" +
"<summary>S</summary><p>Hidden</p>" +
"</details>";
const code = "<pre><code class=\"language-text-x-yaml\">a:\n\n b: 1</code></pre>";
const original =
"<p>Before</p>" +
layout("1-3",
"<p>First <strong>column</strong></p><ul><li>One</li><li>Two</li></ul>",
`<h2>Second</h2>${code}`
) +
layout("1-1",
layout("1-2-1", "<p>Inner</p>", "<p> </p>", table),
collapsible
) +
layout("3-1", "<p> </p>", "<p> </p>") +
"<p>After</p>";
const markdown = markdownExportService.toMarkdown(original);
expect(roundTrip(original)).toStrictEqual(original);
expect(markdownExportService.toMarkdown(roundTrip(original))).toStrictEqual(markdown);
});
it("round-trips a layout inside a tab panel", () => {
const twoColumns = layout("1-1", "<p>A</p>", "<p>B</p>");
const panel = `<div class="trilium-tab-panel">${twoColumns}</div>`;
const original =
"<div class=\"trilium-tabs\"><section class=\"trilium-tab\">" +
`<p class="trilium-tab-title">T</p>${panel}` +
"</section></div>";
expect(roundTrip(original)).toStrictEqual(original);
});
});
});