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/notion): define database columns as inheritable promoted attributes
Elian Doran155100f2ef24
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 251067372a..64e0541a87 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@@ -349,6 +349,55 @@ describe("Notion importer — integration", () => {expect(note?.hasOwnedLabel("Empty")).toBe(false);});+ it("defines text columns as inheritable promoted attributes on the container, inherited by every row", async () => {+ const dbId = "388c5eca1b8b8078a20fd18330d81306";+ const fooId = "388c5eca1b8b80929a78da7c68154bd7";+ const barId = "388c5eca1b8b80e5903ef480b0523eb1";+ const props = (rows: string) => `<table class="properties"><tbody>${rows}</tbody></table>`;+ const importRoot = await importNotion({+ "My DB 388c5eca1b8b8078a20fd18330d81306.html":+ `<html><head><title>My DB</title></head><body><div id="${dbId}"><div class="page-body"></div></div></body></html>`,+ "My DB/Foo 388c5eca1b8b80929a78da7c68154bd7.html":+ `<html><head><title>Foo</title></head><body><div id="${fooId}">${props(`<tr class="property-row property-row-text"><th><span class="icon property-icon"><img src="x.svg"/></span>Text column</th><td>Basic text</td></tr>`)}<div class="page-body"><p>x</p></div></div></body></html>`,+ "My DB/Bar 388c5eca1b8b80e5903ef480b0523eb1.html":+ `<html><head><title>Bar</title></head><body><div id="${barId}">${props(`<tr class="property-row property-row-text"><th>Other note</th><td>Hi</td></tr>`)}<div class="page-body"><p>y</p></div></div></body></html>`+ });++ const db = importRoot.getChildNotes().find((n) => n.title === "My DB");+ // The container owns one inheritable definition per column seen across all rows (the schema union).+ const textDef = db?.getOwnedLabel("label:Text_column");+ expect(textDef?.value).toBe("promoted,single,text,alias=Text column");+ expect(textDef?.isInheritable).toBe(true);+ expect(db?.getOwnedLabel("label:Other_note")?.value).toBe("promoted,single,text,alias=Other note");++ const foo = db?.getChildNotes().find((n) => n.title === "Foo");+ const bar = db?.getChildNotes().find((n) => n.title === "Bar");+ // Each row inherits the whole schema (including a column it has no value for) without owning a copy.+ expect(foo?.getOwnedLabel("label:Other_note")).toBeNull();+ expect(foo?.getLabelValue("label:Other_note")).toBe("promoted,single,text,alias=Other note");+ // Only the row that had the value owns it; the other inherits an empty field.+ expect(foo?.getOwnedLabelValue("Text_column")).toBe("Basic text");+ expect(foo?.getOwnedLabelValue("Other_note")).toBeNull();+ expect(bar?.getOwnedLabelValue("Other_note")).toBe("Hi");+ expect(bar?.getOwnedLabelValue("Text_column")).toBeNull();+ });++ it("neutralizes commas in a column name so the alias can't corrupt the definition", async () => {+ const dbId = "388c5eca1b8b8078a20fd18330d81306";+ const rowId = "388c5eca1b8b80929a78da7c68154bd7";+ const props = `<table class="properties"><tbody><tr class="property-row property-row-text"><th>Weight, kg</th><td>5</td></tr></tbody></table>`;+ const importRoot = await importNotion({+ "DB 388c5eca1b8b8078a20fd18330d81306.html":+ `<html><head><title>DB</title></head><body><div id="${dbId}"><div class="page-body"></div></div></body></html>`,+ "DB/Row 388c5eca1b8b80929a78da7c68154bd7.html":+ `<html><head><title>Row</title></head><body><div id="${rowId}">${props}<div class="page-body"><p>x</p></div></div></body></html>`+ });++ const db = importRoot.getChildNotes().find((n) => n.title === "DB");+ // The comma in "Weight, kg" becomes a space in the alias, so the definition keeps exactly four tokens.+ expect(db?.getOwnedLabel("label:Weight__kg")?.value).toBe("promoted,single,text,alias=Weight kg");+ });+it("saves a bundled image as an attachment and rewrites its src; leaves external/srcless images alone", async () => {const id = "2c6c5eca1b8b80f7b9eaf4f396b755dc";const pngBytes = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);diff --git a/packages/trilium-core/src/services/import/notion/importer.ts b/packages/trilium-core/src/services/import/notion/importer.tsindex 46a50435b1..bb57d41685 100644--- a/packages/trilium-core/src/services/import/notion/importer.ts+++ b/packages/trilium-core/src/services/import/notion/importer.ts@@ -12,6 +12,7 @@* this service just builds the tree and returns its root note, like the zip/enex importers.*/+import type { LabelType, Multiplicity } from "@triliumnext/commons";import { t } from "i18next";import { HTMLElement, parse } from "node-html-parser";@@ -33,6 +34,10 @@ interface NotionProperty {/** The column name, taken verbatim from the property row's `<th>` (sanitized only when made a label). */name: string;value: string;+ /** Trilium promoted-attribute type the column's definition uses (e.g. "text"). */+ labelType: LabelType;+ /** Whether the column holds one value or many (e.g. multi-select); sets the definition's multiplicity. */+ multiplicity: Multiplicity;}interface ParsedPage {@@ -171,7 +176,7 @@ function createNotes(importRootNote: BNote, pages: ParsedPage[], resources: Map<const rootNote = noteService.createNewNote({ parentNoteId: importRootNote.noteId, title: t("notion_import.root-title"), content: "", type: "text", mime: "text/html", isProtected }).note;rootNote.addLabel("iconClass", "bx bx-import");- const noteIdByFolder = new Map<string, string>();+ const noteByFolder = new Map<string, BNote>();const targetByPageId = new Map<string, LinkTarget>();const created: { note: BNote; content: string; page: ParsedPage }[] = [];const ordered = [...pages].sort((a, b) => folderDepth(a.path) - folderDepth(b.path));@@ -179,7 +184,7 @@ function createNotes(importRootNote: BNote, pages: ParsedPage[], resources: Map<// First pass: create every note (so cross-page links can resolve in the second pass) and save its// referenced images as attachments. Content is only rewritten/saved once, in the second pass.for (const page of ordered) {- const targetParentId = noteIdByFolder.get(parentFolderKey(page.path)) ?? rootNote.noteId;+ const targetParentId = noteByFolder.get(parentFolderKey(page.path))?.noteId ?? rootNote.noteId;const { note } = noteService.createNewNote({parentNoteId: targetParentId,@@ -189,7 +194,7 @@ function createNotes(importRootNote: BNote, pages: ParsedPage[], resources: Map<mime: "text/html",isProtected});- noteIdByFolder.set(ownedFolderKey(page.path), note.noteId);+ noteByFolder.set(ownedFolderKey(page.path), note);targetByPageId.set(page.id, { noteId: note.noteId, title: page.title });// Carry the page's Notion database properties over as Trilium labels (e.g. a "Text column" → #Text_column).@@ -204,6 +209,9 @@ function createNotes(importRootNote: BNote, pages: ParsedPage[], resources: Map<taskContext.increaseProgressCount();}+ // Now that every container and its rows exist, define the database schema once per container.+ applyDatabaseSchemas(pages, noteByFolder);+// Second pass: now that every page has a note, resolve cross-page links and persist the final content.for (const { note, content, page } of created) {const finalContent = rewriteLinks(content, (notionId) => targetByPageId.get(notionId) ?? null);@@ -221,6 +229,53 @@ function createNotes(importRootNote: BNote, pages: ParsedPage[], resources: Map<return rootNote;}+/**+ * A Notion database's columns are a schema shared by every row, so each column becomes a single+ * *inheritable* promoted-attribute definition on the row's container note (the database) — not a copy on+ * each row. Rows carry only the values (added in the first pass) and inherit the definition, so a row with+ * no value shows the field empty, mirroring how a Notion property added from any row appears on all of them.+ *+ * A row's container is its parent note, looked up by the same folder key that drives parenting. Each+ * container's schema is the union of its rows' property columns — a column present on only one row still+ * defines the field for the whole database — keeping the first occurrence's type/multiplicity.+ */+function applyDatabaseSchemas(pages: ParsedPage[], noteByFolder: Map<string, BNote>) {+ const schemaByContainer = new Map<BNote, Map<string, NotionProperty>>();++ for (const page of pages) {+ const container = noteByFolder.get(parentFolderKey(page.path));+ if (!container || page.properties.length === 0) {+ continue;+ }++ let schema = schemaByContainer.get(container);+ if (!schema) {+ schema = new Map();+ schemaByContainer.set(container, schema);+ }+ for (const property of page.properties) {+ const labelName = sanitizeAttributeName(property.name);+ if (!schema.has(labelName)) {+ schema.set(labelName, property);+ }+ }+ }++ for (const [container, schema] of schemaByContainer) {+ for (const [labelName, property] of schema) {+ container.addLabel(`label:${labelName}`, buildPromotedDefinition(property), true);+ }+ }+}++/** Builds a promoted-attribute definition value (e.g. `promoted,single,text,alias=Text column`). */+function buildPromotedDefinition({ name, labelType, multiplicity }: NotionProperty): string {+ // The alias keeps the original (pretty) column name in the UI while the attribute name stays sanitized.+ // The definition is comma/`=`-delimited, so neutralize those characters in the alias to avoid corrupting it.+ const alias = name.replace(/[,=]/g, " ").trim();+ return `promoted,${multiplicity},${labelType},alias=${alias}`;+}+/*** Saves each in-zip image a page references as an attachment on `note` and rewrites the `<img src>` to* point at it. References that don't resolve to a bundled file (e.g. external image URLs) are left as-is.@@ -436,7 +491,7 @@ function extractProperties(root: HTMLElement): NotionProperty[] {const name = row.querySelector("th")?.textContent?.trim();const value = row.querySelector("td")?.textContent?.trim();if (name && value) {- properties.push({ name, value });+ properties.push({ name, value, labelType: "text", multiplicity: "single" });}}return properties;