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(import): nest and merge Notion to-do lists
Elian Doran236df2735693
diff --git a/packages/trilium-core/src/services/import/notion/converter.spec.ts b/packages/trilium-core/src/services/import/notion/converter.spec.tsindex 6ebac23ea9..01ea3e3bac 100644--- a/packages/trilium-core/src/services/import/notion/converter.spec.ts+++ b/packages/trilium-core/src/services/import/notion/converter.spec.ts@@ -27,3 +27,32 @@ describe("convertNotionHtml — to-do lists", () => {expect(convertNotionHtml(input)).toBe(`<p id="x">Hello</p>`);});});++describe("convertNotionHtml — to-do nesting and merging", () => {+ // Each Notion to-do item is its own <ul class="to-do-list"> wrapped in a display:contents <div>;+ // a parent's children live in its <div class="indented">, each again its own wrapped single-item list.+ const wrap = (ulInner: string) => `<div style="display:contents" dir="auto"><ul class="to-do-list"><li>${ulInner}</li></ul></div>`;+ const off = (text: string, indented = "") => `<div class="checkbox checkbox-off"></div> <span class="to-do-children-unchecked">${text}</span><div class="indented">${indented}</div>`;+ const on = (text: string, indented = "") => `<div class="checkbox checkbox-on"></div> <span class="to-do-children-checked">${text}</span><div class="indented">${indented}</div>`;++ const item = (text: string, opts: { checked?: boolean; nested?: string } = {}) =>+ `<li><label class="todo-list__label"><input type="checkbox"${opts.checked ? ` checked="checked"` : ""} disabled="disabled"><span class="todo-list__label__description">${text}</span></label>${opts.nested ?? ""}</li>`;+ const list = (...items: string[]) => `<ul class="todo-list">${items.join("")}</ul>`;++ it("nests a parent's sub-items into a single nested todo-list inside its <li>", () => {+ const input = wrap(off("Parent", wrap(off("Child 1")) + wrap(on("Child 2"))));+ expect(convertNotionHtml(input)).toBe(+ list(item("Parent", { nested: list(item("Child 1"), item("Child 2", { checked: true })) }))+ );+ });++ it("merges adjacent top-level to-do items into one list", () => {+ const input = wrap(off("A")) + wrap(on("B"));+ expect(convertNotionHtml(input)).toBe(list(item("A"), item("B", { checked: true })));+ });++ it("does not merge to-do items separated by other content", () => {+ const input = `${wrap(off("A"))}<p>Sep</p>${wrap(off("B"))}`;+ expect(convertNotionHtml(input)).toBe(`${list(item("A"))}<p>Sep</p>${list(item("B"))}`);+ });+});diff --git a/packages/trilium-core/src/services/import/notion/converter.ts b/packages/trilium-core/src/services/import/notion/converter.tsindex a702ddc5e6..e7c554eb42 100644--- a/packages/trilium-core/src/services/import/notion/converter.ts+++ b/packages/trilium-core/src/services/import/notion/converter.ts@@ -8,7 +8,7 @@* Each feature is a small, independently-tested transform; {@link convertNotionHtml} chains them.*/-import { type HTMLElement, parse } from "node-html-parser";+import { HTMLElement, parse } from "node-html-parser";export function convertNotionHtml(html: string): string {const root = parse(html);@@ -17,28 +17,110 @@ export function convertNotionHtml(html: string): string {}/**- * Notion renders each to-do item as its own `<ul class="to-do-list">` whose `<li>` holds a- * `<div class="checkbox checkbox-on|off">`, a `<span class="to-do-children-...">` with the label, and an- * empty `<div class="indented">`. Rewrite each into CKEditor's todo-list shape, mapping checkbox-on to a- * checked input. (Nested sub-items in `.indented` are not handled yet.)+ * Notion renders every to-do item as its own `<ul class="to-do-list">` (each wrapped in a+ * `display:contents` `<div>`), whose `<li>` holds a `<div class="checkbox checkbox-on|off">`, a+ * `<span class="to-do-children-…">` label and a `<div class="indented">` carrying any sub-items.+ *+ * Rewrite each maximal run of adjacent to-do items within `container` into a single CKEditor+ * `<ul class="todo-list">`, mapping checkbox-on to a checked input. Sub-items are converted recursively+ * and emitted as a nested `<ul class="todo-list">` inside the parent `<li>`. Runs broken by other+ * content stay separate lists.*/-function convertTodoLists(root: HTMLElement) {- for (const ul of root.querySelectorAll("ul.to-do-list")) {- const items = ul.querySelectorAll("li")- .filter((li) => li.parentNode === ul)- .map((li) => buildTodoItem(li));- ul.setAttribute("class", "todo-list");- ul.set_content(items.join(""));+function convertTodoLists(container: HTMLElement) {+ for (const run of collectTodoRuns(container)) {+ const items = run.flatMap(({ ul }) => directChildren(ul, "li").map((li) => buildTodoItem(li)));+ run[0].block.insertAdjacentHTML("beforebegin", `<ul class="todo-list">${items.join("")}</ul>`);+ for (const { block } of run) {+ block.remove();+ }+ }+}++interface TodoBlock {+ /** The container's direct child to replace — the wrapping `display:contents` div, or the `ul` itself. */+ block: HTMLElement;+ ul: HTMLElement;+}++/** Groups a container's direct children into maximal runs of adjacent to-do blocks (ignoring whitespace). */+function collectTodoRuns(container: HTMLElement): TodoBlock[][] {+ const runs: TodoBlock[][] = [];+ let current: TodoBlock[] | null = null;++ for (const node of container.childNodes) {+ if (node instanceof HTMLElement) {+ const ul = todoUl(node);+ if (ul) {+ if (!current) {+ current = [];+ runs.push(current);+ }+ current.push({ block: node, ul });+ continue;+ }+ current = null;+ } else if (node.toString().trim() !== "") {+ // A non-whitespace text/comment node breaks the run; whitespace between wrappers does not, so+ // that Notion's one-item-per-list wrappers still merge.+ current = null;+ }}++ return runs;}function buildTodoItem(li: HTMLElement): string {- const checked = li.querySelector(".checkbox")?.classList.contains("checkbox-on") ?? false;- const label = li.querySelectorAll("span").find((span) =>- span.classList.contains("to-do-children-checked") || span.classList.contains("to-do-children-unchecked"));+ const checked = directChild(li, (n) => n.classList.contains("checkbox"))?.classList.contains("checkbox-on") ?? false;+ const label = directChild(li, (n) => isTag(n, "span")+ && (n.classList.contains("to-do-children-checked") || n.classList.contains("to-do-children-unchecked")));const description = label?.innerHTML ?? "";++ // A to-do item's sub-items live in its `.indented`; convert them in place and nest the result inside+ // this `<li>` (CKEditor's nested-list shape). Empty when there are none.+ const indented = directChild(li, (n) => n.classList.contains("indented"));+ let nested = "";+ if (indented) {+ convertTodoLists(indented);+ nested = indented.innerHTML.trim();+ }+// Match the canonical CKEditor data serialization (checked before disabled) so a freshly imported// note already equals what the editor would re-emit on its first save.const attributes = checked ? ` checked="checked" disabled="disabled"` : ` disabled="disabled"`;- return `<li><label class="todo-list__label"><input type="checkbox"${attributes}><span class="todo-list__label__description">${description}</span></label></li>`;+ return `<li><label class="todo-list__label"><input type="checkbox"${attributes}><span class="todo-list__label__description">${description}</span></label>${nested}</li>`;+}++/** Returns the to-do `<ul>` a container child represents — the node itself, or the one `display:contents` wraps. */+function todoUl(node: HTMLElement): HTMLElement | null {+ if (isTodoUl(node)) {+ return node;+ }+ if (isTag(node, "div") && (node.getAttribute("style") ?? "").replace(/\s/g, "").includes("display:contents")) {+ const elements = node.childNodes.filter((child): child is HTMLElement => child instanceof HTMLElement);+ if (elements.length === 1 && isTodoUl(elements[0])) {+ return elements[0];+ }+ }+ return null;+}++function isTodoUl(node: HTMLElement): boolean {+ return isTag(node, "ul") && node.classList.contains("to-do-list");+}++function isTag(node: HTMLElement, tag: string): boolean {+ return node.tagName?.toLowerCase() === tag;+}++function directChild(parent: HTMLElement, predicate: (node: HTMLElement) => boolean): HTMLElement | null {+ for (const node of parent.childNodes) {+ if (node instanceof HTMLElement && predicate(node)) {+ return node;+ }+ }+ return null;+}++function directChildren(parent: HTMLElement, tag: string): HTMLElement[] {+ return parent.childNodes.filter((node): node is HTMLElement => node instanceof HTMLElement && isTag(node, tag));}