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
Embed partial-export inline databases as include-notes too
Elian Doran419a7d24dbf6
diff --git a/packages/trilium-core/src/services/import/notion/converter.spec.ts b/packages/trilium-core/src/services/import/notion/converter.spec.tsindex 17da366878..b16f2cf60c 100644--- a/packages/trilium-core/src/services/import/notion/converter.spec.ts+++ b/packages/trilium-core/src/services/import/notion/converter.spec.ts@@ -439,6 +439,32 @@ describe("convertNotionHtml — code blocks", () => {});});+describe("convertNotionHtml — inline databases", () => {+ const dbId = "38ac5eca1b8b808babeaf10c0980fa5b";+ const placeholder = `<section class="include-note" data-notion-id="${dbId}" data-box-size="medium"> </section>`;++ it("replaces a rendered inline-database table (partial export) with an include-note placeholder", () => {+ const input =+ `<div style="display:contents" dir="ltr"><div id="38ac5eca-1b8b-808b-abea-f10c0980fa5b" class="collection-content"><h4 class="collection-title">Database title</h4>` ++ `<div class="collection-content-wrapper"><table class="collection-content"><thead><tr><th>Name</th></tr></thead><tbody>` ++ `<tr id="38ac5eca-1b8b-8069-afb5-c9fe40e53c42"><td class="cell-title"><a href="Inline%20database%20test/Database%20title/First%2038ac5eca1b8b8069afb5c9fe40e53c42.html">First</a></td></tr>` ++ `</tbody></table></div></div></div>`;+ expect(convertNotionHtml(input)).toBe(placeholder);+ });++ it("replaces an inline-database CSV link (full/workspace export) with the same placeholder", () => {+ const input =+ `<div style="display:contents" dir="ltr"><div id="38ac5eca-1b8b-808b-abea-f10c0980fa5b" class="collection-content"><h4 class="collection-title">Database title</h4>` ++ `<a href="Inline%20database%20test/Database%20title%20${dbId}.csv"><code>x</code></a></div></div>`;+ expect(convertNotionHtml(input)).toBe(placeholder);+ });++ it("leaves a collection-content block without an id untouched", () => {+ const input = `<div class="collection-content"><h4 class="collection-title">No id</h4></div>`;+ expect(convertNotionHtml(input)).toBe(input);+ });+});+describe("convertNotionHtml — link-to-page blocks", () => {it("unwraps a link-to-page figure into a paragraph link (href left for the importer to resolve)", () => {const input = `<div style="display:contents" dir="ltr"><figure id="386c5eca" class="link-to-page"><a href="Formatting%20test/Subpage%20386c5eca1b8b802a90d8d891c7e62cd5.html">Subpage</a></figure></div>`;diff --git a/packages/trilium-core/src/services/import/notion/converter.ts b/packages/trilium-core/src/services/import/notion/converter.tsindex 2efd91f2de..e54d6d887c 100644--- a/packages/trilium-core/src/services/import/notion/converter.ts+++ b/packages/trilium-core/src/services/import/notion/converter.ts@@ -12,6 +12,8 @@import { getMimeTypeFromMarkdownName, MIME_TYPE_AUTO, normalizeMimeTypeForCKEditor } from "@triliumnext/commons";import { HTMLElement, parse } from "node-html-parser";+import { getNotionId } from "./notion_id.js";+export function convertNotionHtml(html: string): string {const root = parse(html);convertMath(root);@@ -21,6 +23,7 @@ export function convertNotionHtml(html: string): string {convertToggleHeadings(root);dropTableOfContents(root);unwrapDisplayContents(root);+ convertInlineDatabases(root);mergeFragmentedLists(root);convertColumns(root);convertTables(root);@@ -292,6 +295,28 @@ function unwrapDisplayContents(root: HTMLElement) {}// #endregion+// #region Inline databases (collections)+/**+ * Notion renders an inline database as `<div class="collection-content" id="<db-id>">` — holding either a+ * rendered `<table class="collection-content">` (a partial export) or a bare link to the separately-exported+ * CSV (a full/workspace export). Either way the database is imported as its own collection note, so replace+ * the whole block with a Trilium include-note placeholder carrying the database's Notion id. The id is read+ * from the div's `id` (which the sanitizer later strips), and the importer resolves `data-notion-id` to the+ * collection note's id once every note exists; the `data-notion-id`/`data-box-size` attributes and the+ * `section` survive sanitization. A block without a resolvable id is left untouched.+ */+function convertInlineDatabases(root: HTMLElement) {+ for (const block of root.querySelectorAll("div.collection-content")) {+ const notionId = getNotionId(block.getAttribute("id") ?? "");+ if (!notionId) {+ continue;+ }+ block.insertAdjacentHTML("beforebegin", `<section class="include-note" data-notion-id="${notionId}" data-box-size="medium"> </section>`);+ block.remove();+ }+}+// #endregion+// #region List fragmentation/*** Notion exports each list item as its own single-item `<ul>`/`<ol>` (so a three-item list is three lists),diff --git a/packages/trilium-core/src/services/import/notion/importer.integration.spec.ts b/packages/trilium-core/src/services/import/notion/importer.integration.spec.tsindex c01072478f..27e2b57920 100644--- a/packages/trilium-core/src/services/import/notion/importer.integration.spec.ts+++ b/packages/trilium-core/src/services/import/notion/importer.integration.spec.ts@@ -141,17 +141,12 @@ describe("Notion importer — integration", () => {expect(importRoot.getChildNotes().map((note) => note.title).sort()).toEqual(["Page A", "Page B"]);});- it("embeds a full-export inline database as an include-note pointing at the imported collection", async () => {- // A workspace ("database-wide") export renders an inline database as a link to its separately-exported- // CSV (not a table). The database is imported as a child collection; the link must become an- // include-note embedding it, rather than a dangling reference to a `.csv` file.+ // Both Notion export shapes of an inline database — a full/workspace export's link to the separately-+ // exported CSV, and a partial export's rendered table — must resolve to an include-note embedding the+ // imported collection. Each shares the same CSV + rows; only the in-page `collectionBlock` differs.+ const expectInlineDatabaseEmbedded = async (collectionBlock: string) => {const pageId = "38ac5eca1b8b8075b965f506658aeb1f";const dbId = "38ac5eca1b8b808babeaf10c0980fa5b";- // Faithful to the real export: the block is wrapped in a display:contents div and carries the- // database id on the (sanitizer-stripped) div id, with the resolvable id living in the .csv href.- const collectionBlock =- `<div style="display:contents" dir="ltr"><div id="38ac5eca-1b8b-808b-abea-f10c0980fa5b" class="collection-content"><h4 class="collection-title">Database title</h4>` +- `<a href="Inline%20database%20test/Database%20title%20${dbId}.csv"><code>Inline database test/Database title ${dbId}.csv</code></a></div></div>`;const importRoot = await importNotion({[`Inline database test ${pageId}.html`]:`<html><head><title>Inline database test</title></head><body><div id="${pageId}"><div class="page-body"><p>Before</p>${collectionBlock}<p>After</p></div></div></body></html>`,@@ -165,11 +160,32 @@ describe("Notion importer — integration", () => {// The database imported as a table collection with its rows nested under it.expect(database?.type).toBe("book");expect(database?.getChildNotes().map((note) => note.title).sort()).toEqual(["First", "Second"]);- // The page body embeds that collection inline and no longer references the raw CSV.- const content = page?.getContent();- expect(content).toContain(`<section class="include-note" data-note-id="${database?.noteId}" data-box-size="medium">`);+ // The page body embeds that collection inline and no longer references the raw CSV or the table.+ const content = page?.getContent() ?? "";+ expect(content).toContain(`class="include-note"`);+ expect(content).toContain(`data-note-id="${database?.noteId}"`);+ expect(content).toContain(`data-box-size="medium"`);+ expect(content).not.toContain("data-notion-id");expect(content).not.toContain(".csv");expect(content).not.toContain("collection-content");+ };++ it("embeds a full-export inline database (CSV link) as an include-note for the imported collection", async () => {+ const dbId = "38ac5eca1b8b808babeaf10c0980fa5b";+ await expectInlineDatabaseEmbedded(+ `<div style="display:contents" dir="ltr"><div id="38ac5eca-1b8b-808b-abea-f10c0980fa5b" class="collection-content"><h4 class="collection-title">Database title</h4>` ++ `<a href="Inline%20database%20test/Database%20title%20${dbId}.csv"><code>Inline database test/Database title ${dbId}.csv</code></a></div></div>`+ );+ });++ it("embeds a partial-export inline database (rendered table) as an include-note for the imported collection", async () => {+ await expectInlineDatabaseEmbedded(+ `<div style="display:contents" dir="ltr"><div id="38ac5eca-1b8b-808b-abea-f10c0980fa5b" class="collection-content"><h4 class="collection-title">Database title</h4>` ++ `<div class="collection-content-wrapper"><table class="collection-content"><thead><tr><th>Name</th></tr></thead><tbody>` ++ `<tr id="38ac5eca-1b8b-8069-afb5-c9fe40e53c42"><td class="cell-title"><a href="Inline%20database%20test/Database%20title/First%2038ac5eca1b8b8069afb5c9fe40e53c42.html">First</a></td></tr>` ++ `<tr id="38ac5eca-1b8b-8025-bf73-d86d81713eb3"><td class="cell-title"><a href="Inline%20database%20test/Database%20title/Second%2038ac5eca1b8b8025bf73d86d81713eb3.html">Second</a></td></tr>` ++ `</tbody></table></div></div></div>`+ );});it("groups a CSV-only database's rows under a container note, instead of orphaning them to the root", async () => {diff --git a/packages/trilium-core/src/services/import/notion/importer.spec.ts b/packages/trilium-core/src/services/import/notion/importer.spec.tsindex 53e0204924..4dd3e1ccad 100644--- a/packages/trilium-core/src/services/import/notion/importer.spec.ts+++ b/packages/trilium-core/src/services/import/notion/importer.spec.ts@@ -53,26 +53,21 @@ describe("rewriteCollectionIncludes", () => {const resolveDatabase = (notionId: string): LinkTarget | null =>notionId === dbId ? { noteId: "dbNote123", title: "Database title" } : null;- // The full-export inline-database shape: a div linking to the separately-exported CSV.- const block = (id: string) =>- `<div class="collection-content"><h4 class="collection-title">Database title</h4>` +- `<a href="Inline%20database%20test/Database%20title%20${id}.csv"><code>x</code></a></div>`;-- it("replaces an inline-database CSV reference with an include-note for the imported collection", () => {- const input = `<p>Before</p>${block(dbId)}<p>After</p>`;- expect(rewriteCollectionIncludes(input, resolveDatabase)).toBe(- `<p>Before</p><section class="include-note" data-note-id="dbNote123" data-box-size="medium"> </section><p>After</p>`- );+ it("resolves an inline-database placeholder to the imported collection note's id", () => {+ const input = `<p>Before</p><section class="include-note" data-notion-id="${dbId}" data-box-size="medium"> </section><p>After</p>`;+ const output = rewriteCollectionIncludes(input, resolveDatabase);+ expect(output).toContain(`data-note-id="dbNote123"`);+ expect(output).toContain(`data-box-size="medium"`);+ expect(output).not.toContain("data-notion-id");});- it("leaves the block untouched when the referenced database wasn't imported", () => {- const input = block("ffffffffffffffffffffffffffffffff");- expect(rewriteCollectionIncludes(input, resolveDatabase)).toBe(input);+ it("drops a placeholder whose database wasn't imported", () => {+ const input = `<p>x</p><section class="include-note" data-notion-id="ffffffffffffffffffffffffffffffff"> </section>`;+ expect(rewriteCollectionIncludes(input, resolveDatabase)).toBe(`<p>x</p>`);});- it("ignores a rendered collection table (the partial-export shape)", () => {- // A partial export inlines the actual rows as a <table>, which has no CSV to resolve and is kept.- const table = `<table class="collection-content"><tbody><tr><td>Foo</td></tr></tbody></table>`;- expect(rewriteCollectionIncludes(table, resolveDatabase)).toBe(table);+ it("leaves an ordinary include-note (no placeholder id) untouched", () => {+ const input = `<section class="include-note" data-note-id="abc"> </section>`;+ expect(rewriteCollectionIncludes(input, resolveDatabase)).toBe(input);});});diff --git a/packages/trilium-core/src/services/import/notion/importer.ts b/packages/trilium-core/src/services/import/notion/importer.tsindex 1150b0ee4f..16d1d7f053 100644--- a/packages/trilium-core/src/services/import/notion/importer.ts+++ b/packages/trilium-core/src/services/import/notion/importer.ts@@ -353,52 +353,35 @@ export function rewriteLinks(html: string, resolve: (notionId: string) => LinkTa}/**- * Replaces a full-export inline-database reference with a Trilium include-note embedding the imported- * collection. Notion's workspace ("database-wide") export renders an inline database not as a table but as- * `<div class="collection-content"><h4 class="collection-title">Name</h4><a href="…<id>.csv">…</a></div>` —- * a bare link to the separately-exported CSV. That database is imported as a collection note (built from its- * CSV plus rows folder), so resolve it from the id in the `.csv` href and embed it inline, dropping the link.- * A partial export inlines the rendered `<table class="collection-content">` instead, which is left untouched.+ * Resolves the inline-database include-note placeholders the converter emits — `<section class="include-note"+ * data-notion-id="…">` — to the imported collection note. Notion renders an inline database inside a page as+ * a rendered table (a partial export) or a bare link to its separately-exported CSV (a full/workspace+ * export); the converter normalizes both to this placeholder carrying the database's Notion id. The database+ * itself is imported as a collection note (built from its CSV plus rows folder), so swap that id for the+ * note's id. A placeholder whose database wasn't imported is dropped rather than left as a dangling include.*/export function rewriteCollectionIncludes(html: string, resolve: (notionId: string) => LinkTarget | null): string {const root = parse(html);let changed = false;- for (const block of root.querySelectorAll("div.collection-content")) {- const notionId = collectionCsvId(block);- const target = notionId ? resolve(notionId) : null;- if (!target) {+ for (const section of root.querySelectorAll("section.include-note")) {+ const notionId = section.getAttribute("data-notion-id");+ if (!notionId) {continue;}-- block.insertAdjacentHTML("beforebegin", `<section class="include-note" data-note-id="${target.noteId}" data-box-size="medium"> </section>`);- block.remove();+ section.removeAttribute("data-notion-id");+ const target = resolve(notionId);+ if (target) {+ section.setAttribute("data-note-id", target.noteId);+ } else {+ section.remove();+ }changed = true;}return changed ? root.toString() : html;}-/** The Notion id of the `.csv` an inline-database `collection-content` block links to, or null. */-function collectionCsvId(block: HTMLElement): string | null {- for (const anchor of block.querySelectorAll("a")) {- const href = anchor.getAttribute("href");- if (!href) {- continue;- }- let path = href;- try {- path = decodeURIComponent(href);- } catch {- // Leave malformed percent-encoding as-is rather than throwing.- }- if (path.split(/[?#]/)[0].toLowerCase().endsWith(".csv")) {- return getNotionId(path) ?? null;- }- }- return null;-}-/*** Reads a Notion property-row timestamp (created/last-edited) from the page's properties table and* converts it to Trilium's UTC DB format. Returns undefined when the row, the <time> element or the