Skip to content

Build your personal knowledge base with Trilium Notes

fix(import): split a todo list at a blank line (closes #11129)

Elian Doran5de0ab8f08e5
diff --git a/packages/commons/src/lib/markdown_renderer.spec.ts b/packages/commons/src/lib/markdown_renderer.spec.ts
index 7744c31c18..4f806c9a67 100644
--- a/packages/commons/src/lib/markdown_renderer.spec.ts
+++ b/packages/commons/src/lib/markdown_renderer.spec.ts
@@ -231,8 +231,8 @@ describe("renderToHtml", () => {
it("renders a task list with checkbox inputs and labels", () => {
const html = render("- [ ] a\n- [x] b");
expect(html).toContain('<ul class="todo-list">');
- expect(html).toContain('<input type="checkbox"disabled="disabled">');
- expect(html).toContain('<input type="checkbox"checked="checked" disabled="disabled">');
+ expect(html).toContain('<input type="checkbox" disabled="disabled">');
+ expect(html).toContain('<input type="checkbox" checked="checked" disabled="disabled">');
expect(html).toContain('<label class="todo-list__label">');
expect(html).toContain('<span class="todo-list__label__description">a</span>');
expect(html).toContain('<span class="todo-list__label__description">b</span>');
@@ -249,51 +249,95 @@ describe("renderToHtml", () => {
expect(html).toBe("<ol><li>one</li><li>two</li></ol>");
});
- it("prepends the checkbox into the paragraph of a loose task item (text first token)", () => {
- const html = render("- [ ] first\n\n- [x] second");
- // Loose items wrap content in <p>; the checkbox is injected before the text.
- expect(html).toContain(
- '<span class="todo-list__label__description"><p><input type="checkbox"disabled="disabled">first</p></span>'
+ it("starts a new todo list at a blank line between two task items", () => {
+ // A blank line makes the list loose, which wraps each item in <p> — a form
+ // CKEditor cannot upcast. It is also what the Markdown export writes for two
+ // todo lists separated by an empty paragraph, so the import rebuilds those.
+ expect(render("- [ ] Truc\n\n- [x] Machin")).toBe(
+ '<ul class="todo-list"><li><label class="todo-list__label">' +
+ '<input type="checkbox" disabled="disabled">' +
+ '<span class="todo-list__label__description">Truc</span></label></li></ul>' +
+ "<p>&nbsp;</p>" +
+ '<ul class="todo-list"><li><label class="todo-list__label">' +
+ '<input type="checkbox" checked="checked" disabled="disabled">' +
+ '<span class="todo-list__label__description">Machin</span></label></li></ul>'
);
+ });
+
+ it("splits only where the blank line falls, keeping adjacent items in one list", () => {
+ const html = render("- [ ] A\n- [ ] B\n\n- [ ] C");
+ expect(html.match(/<ul class="todo-list">/g)).toHaveLength(2);
expect(html).toContain(
- '<span class="todo-list__label__description"><p><input type="checkbox"checked="checked" disabled="disabled">second</p></span>'
+ '<span class="todo-list__label__description">A</span></label></li>' +
+ '<li><label class="todo-list__label">'
);
+ expect(html).toContain('</ul><p>&nbsp;</p><ul class="todo-list">');
});
- it("prepends the checkbox to a loose task whose paragraph first inner token is not text", () => {
- const html = render("- [ ] ![](http://x/y.png)\n\n- [x] b");
- // The paragraph's first inner token is an image (not text), so only the
- // paragraph-level text receives the checkbox prefix.
- expect(html).toContain(
- '<span class="todo-list__label__description"><p><input type="checkbox"disabled="disabled"><img src="http://x/y.png"></p></span>'
+ it("keeps a loose item's inline markup in the description", () => {
+ expect(render("- [ ] **bold** and [link](http://x)\n\n- [ ] b")).toContain(
+ '<span class="todo-list__label__description">' +
+ '<strong>bold</strong> and <a href="http://x">link</a></span>'
);
});
- it("unshifts the checkbox as a text token for a loose task whose first token is a checkbox", () => {
- // marked emits a `checkbox` token (not a paragraph) as the first token of a
- // loose native task item — the checkbox HTML is unshifted before the body.
- const html = render("- [ ] text\n\n more");
- expect(html).toBe(
+ it("unwraps a loose item whose paragraph opens with a non-text token", () => {
+ expect(render("- [ ] ![](http://x/y.png)\n\n- [x] b")).toContain(
+ '<span class="todo-list__label__description"><img src="http://x/y.png"></span>'
+ );
+ });
+
+ it("keeps a task item's later blocks after the label, not inside the description", () => {
+ // CKEditor's multi-block todo item: the first block is the label's
+ // description, every later one is a sibling of </label>.
+ expect(render("- [ ] text\n\n more")).toBe(
'<ul class="todo-list"><li><label class="todo-list__label">' +
- '<span class="todo-list__label__description">' +
- '<input type="checkbox"disabled="disabled"><p>text</p><p>more</p>' +
- "</span></label></li></ul>"
+ '<input type="checkbox" disabled="disabled">' +
+ '<span class="todo-list__label__description">text</span></label>' +
+ "<p>more</p></li></ul>"
+ );
+ expect(render("- [x] done\n\n more body")).toContain(
+ '<input type="checkbox" checked="checked" disabled="disabled">' +
+ '<span class="todo-list__label__description">done</span></label><p>more body</p>'
);
});
- it("unshifts a checked checkbox for a loose, checked native task item", () => {
- const html = render("- [x] done\n\n more body");
- expect(html).toContain(
- '<span class="todo-list__label__description">' +
- '<input type="checkbox"checked="checked" disabled="disabled"><p>done</p><p>more body</p></span>'
+ it("keeps a nested task list after the label of its parent item", () => {
+ expect(render("- [ ] a\n - [ ] b")).toBe(
+ '<ul class="todo-list"><li><label class="todo-list__label">' +
+ '<input type="checkbox" disabled="disabled">' +
+ '<span class="todo-list__label__description">a</span></label>' +
+ '<ul class="todo-list"><li><label class="todo-list__label">' +
+ '<input type="checkbox" disabled="disabled">' +
+ '<span class="todo-list__label__description">b</span></label></li></ul></li></ul>'
+ );
+ });
+
+ it("drops the todo-list class from a split group holding no task item", () => {
+ expect(render("- [ ] a\n\n- plain")).toBe(
+ '<ul class="todo-list"><li><label class="todo-list__label">' +
+ '<input type="checkbox" disabled="disabled">' +
+ '<span class="todo-list__label__description">a</span></label></li></ul>' +
+ "<p>&nbsp;</p><ul><li><p>plain</p></li></ul>"
);
});
+ it("leaves an ordered task list as a single <ol> so its numbering survives", () => {
+ const html = render("1. [ ] a\n\n2. [ ] b");
+ expect(html).toContain("<ol>");
+ expect(html).not.toContain("<p>&nbsp;</p>");
+ });
+
+ it("renders an empty task marker as literal text, not a task item", () => {
+ // marked's task rule needs a space after `]`, so `- [ ]` alone is not a task.
+ expect(render("- [ ]")).toBe("<ul><li>[ ]</li></ul>");
+ });
+
it("prepends the checkbox directly to a tight task item body", () => {
const html = render("- [ ] one");
expect(html).toBe(
'<ul class="todo-list"><li><label class="todo-list__label">' +
- '<input type="checkbox"disabled="disabled">' +
+ '<input type="checkbox" disabled="disabled">' +
'<span class="todo-list__label__description">one</span></label></li></ul>'
);
});
@@ -304,7 +348,7 @@ describe("renderToHtml", () => {
const html = render("- [/] x", "", { taskStates: DEFAULT_TASK_STATES });
expect(html).toContain('data-trilium-task-state="doing"');
expect(html).toContain('title="Doing"');
- expect(html).toContain('<input type="checkbox"disabled="disabled">');
+ expect(html).toContain('<input type="checkbox" disabled="disabled">');
expect(html).toContain('<span class="todo-list__label__description">x</span>');
// The `[/]` marker must be stripped from the visible text.
expect(html).not.toContain("[/]");
@@ -375,7 +419,7 @@ describe("renderToHtml", () => {
const html = render("- [/] x\n\n more text\n\n- [x] b", "", { taskStates: DEFAULT_TASK_STATES });
expect(html).toContain('data-trilium-task-state="doing"');
expect(html).toContain(
- '<p><input type="checkbox"disabled="disabled">x</p><p>more text</p>'
+ '<span class="todo-list__label__description">x</span></label><p>more text</p>'
);
expect(html).not.toContain("[/]");
});
diff --git a/packages/commons/src/lib/markdown_renderer.ts b/packages/commons/src/lib/markdown_renderer.ts
index c532bccb73..907012527b 100644
--- a/packages/commons/src/lib/markdown_renderer.ts
+++ b/packages/commons/src/lib/markdown_renderer.ts
@@ -374,6 +374,18 @@ function restoreFromMap(text: string, map: Map<string, string>): string {
return text.replace(new RegExp(pattern, "g"), (match) => map.get(match) ?? match);
}
+/** Drops the checkbox marked's lexer unshifts among a loose task item's inline tokens. */
+function dropCheckboxes(tokens: Token[] | undefined): Token[] {
+ /* v8 ignore next -- defensive: marked always lexes a paragraph's inline tokens */
+ return (tokens ?? []).filter((token) => token.type !== "checkbox");
+}
+
+/** Matches an item whose raw text ends in a blank line, i.e. one the next item is spaced away from. */
+const BLANK_LINE_AT_END = /\n[ \t]*\n$/;
+
+/** What CKEditor downcasts for the empty paragraph that separates two lists. */
+const EMPTY_PARAGRAPH = "<p>&nbsp;</p>";
+
/**
* Keep renderer code up to date with https://github.com/markedjs/marked/blob/master/src/Renderer.ts.
*
@@ -427,60 +439,77 @@ export class CustomMarkdownRenderer extends Renderer {
}
override list(token: Tokens.List): string {
- let result = super.list(token)
- .replace("\n", "")
- .trimEnd();
-
- if (token.items.some((item) => item.task)) {
- result = result.replace(/^<ul>/, '<ul class="todo-list">');
+ if (!token.ordered && token.items.some((item) => item.task)) {
+ return this.#taskLists(token);
}
- return result;
+ return super.list(token)
+ .replace("\n", "")
+ .trimEnd();
}
override checkbox({ checked }: Tokens.Checkbox): string {
return `<input type="checkbox"${
- checked ? 'checked="checked" ' : ""
- }disabled="disabled">`;
+ checked ? ' checked="checked"' : ""
+ } disabled="disabled">`;
}
override listitem(item: Tokens.ListItem): string {
- if (item.task) {
- const taskState = (item as TaskListItem)._taskState;
- const dataAttr = taskState ? ` data-trilium-task-state="${taskState}"` : "";
- // Native hover tooltip on the `<li>` — matches the CKEditor data
- // downcast, so shared / read-only / exported HTML all surface the
- // state's human-readable title when the task item is hovered.
- // Skipped when the state has no definition in the current config.
- const stateDef = taskState ? this.#stateByName.get(taskState) : undefined;
- const titleText = stateDef?.title || stateDef?.name;
- const titleAttr = titleText ? ` title="${escapeHtml(titleText)}"` : "";
- let itemBody = "";
- const checkbox = this.checkbox({ checked: !!item.checked, raw: "- [ ]", type: "checkbox" });
- if (item.loose) {
- if (item.tokens[0]?.type === "paragraph") {
- item.tokens[0].text = checkbox + item.tokens[0].text;
- if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === "text") {
- item.tokens[0].tokens[0].text = checkbox + escapeHtml(item.tokens[0].tokens[0].text);
- item.tokens[0].tokens[0].escaped = true;
- }
- } else {
- item.tokens.unshift({
- type: "text",
- raw: checkbox,
- text: checkbox,
- escaped: true
- });
- }
- } else {
- itemBody += checkbox;
- }
+ if (!item.task) {
+ return super.listitem(item).trimEnd();
+ }
- itemBody += `<span class="todo-list__label__description">${this.parser.parse(item.tokens.filter((t) => t.type !== "checkbox"))}</span>`;
- return `<li${dataAttr}${titleAttr}><label class="todo-list__label">${itemBody}</label></li>`;
+ const taskState = (item as TaskListItem)._taskState;
+ const dataAttr = taskState ? ` data-trilium-task-state="${taskState}"` : "";
+ // Native hover tooltip on the `<li>` — matches the CKEditor data
+ // downcast, so shared / read-only / exported HTML all surface the
+ // state's human-readable title when the task item is hovered.
+ // Skipped when the state has no definition in the current config.
+ const stateDef = taskState ? this.#stateByName.get(taskState) : undefined;
+ const titleText = stateDef?.title || stateDef?.name;
+ const titleAttr = titleText ? ` title="${escapeHtml(titleText)}"` : "";
+ const checkbox = this.checkbox({ checked: !!item.checked, raw: "- [ ]", type: "checkbox" });
+
+ // CKEditor reads the first block as the label's description and every later block
+ // as a sibling of `</label>`. A loose item wraps that first block in a `paragraph`,
+ // whose `<p>` has to go: `todoItemInputConverter` only upcasts an `<input>` that
+ // opens the item, and `.todo-list__label > input` only styles a direct child of
+ // the label.
+ const blocks = item.tokens.filter(
+ (token) => token.type !== "checkbox" && token.type !== "space"
+ );
+ const [first, ...rest] = blocks;
+ const description = first?.type === "paragraph"
+ ? this.parser.parseInline(dropCheckboxes(first.tokens))
+ : this.parser.parse(blocks.slice(0, 1));
+
+ return `<li${dataAttr}${titleAttr}><label class="todo-list__label">${checkbox}`
+ + `<span class="todo-list__label__description">${description}</span></label>`
+ + `${rest.length > 0 ? this.parser.parse(rest) : ""}</li>`;
+ }
+
+ /**
+ * Renders an unordered list holding task items, opening a new `<ul>` at every blank
+ * line between two items. CKEditor has no loose-list form, and the Markdown export
+ * writes exactly this blank line for two todo lists separated by an empty paragraph,
+ * so importing it back rebuilds the same lists.
+ */
+ #taskLists(token: Tokens.List): string {
+ const groups: Tokens.ListItem[][] = [[]];
+ for (const item of token.items) {
+ groups[groups.length - 1].push(item);
+ if (BLANK_LINE_AT_END.test(item.raw)) {
+ groups.push([]);
+ }
}
- return super.listitem(item).trimEnd();
+ return groups
+ .filter((group) => group.length > 0)
+ .map((group) => {
+ const className = group.some((item) => item.task) ? ` class="todo-list"` : "";
+ return `<ul${className}>${group.map((item) => this.listitem(item)).join("")}</ul>`;
+ })
+ .join(EMPTY_PARAGRAPH);
}
override image(token: Tokens.Image): string {
diff --git a/packages/trilium-core/src/services/import/markdown.spec.ts b/packages/trilium-core/src/services/import/markdown.spec.ts
index 5635860a8e..798a07f558 100644
--- a/packages/trilium-core/src/services/import/markdown.spec.ts
+++ b/packages/trilium-core/src/services/import/markdown.spec.ts
@@ -405,6 +405,43 @@ $$`;
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>&nbsp;</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>&nbsp;</p>${todoList("Machin")}`;
+ expect(markdownService.renderToHtml(markdownExportService.toMarkdown(original), "Title")).toStrictEqual(original);
+ });
+
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