Skip to content

Build your personal knowledge base with Trilium Notes

refactor(import): share collection helpers between Notion and Anytype

Elian Dorancfa1b6fad468
diff --git a/packages/trilium-core/src/services/import/anytype/collection.spec.ts b/packages/trilium-core/src/services/import/anytype/collection.spec.ts
index 1315a38a88..df4962c47b 100644
--- a/packages/trilium-core/src/services/import/anytype/collection.spec.ts
+++ b/packages/trilium-core/src/services/import/anytype/collection.spec.ts
@@ -1,6 +1,5 @@
import { describe, expect, it } from "vitest";
-import { buildColumnDefinition, toAttributeName } from "./collection.js";
import { isCollectionObject, isPage, parseObject } from "./importer.js";
import type { AnytypeBlock, AnytypeMark, AnytypeSnapshot, RelationInfo } from "./model.js";
@@ -70,31 +69,6 @@ describe("collection properties", () => {
["opt-second", "second"]
]);
- describe("toAttributeName", () => {
- it("camel-cases a column name into a valid attribute name", () => {
- expect(toAttributeName("URL")).toBe("url");
- expect(toAttributeName("Text property")).toBe("textProperty");
- expect(toAttributeName("Number prop")).toBe("numberProp");
- expect(toAttributeName("Date & Time")).toBe("dateTime");
- expect(toAttributeName(" ")).toBe("unnamed");
- });
- });
-
- describe("buildColumnDefinition", () => {
- it("builds a single-valued promoted definition keeping the original name as the alias", () => {
- expect(buildColumnDefinition("url", "URL")).toBe("promoted,single,url,alias=URL");
- expect(buildColumnDefinition("text", "Text property")).toBe("promoted,single,text,alias=Text property");
- });
-
- it("neutralizes commas, equals and control chars in the alias so the definition can't be corrupted", () => {
- expect(buildColumnDefinition("text", "a,b=c")).toBe("promoted,single,text,alias=a b c");
- });
-
- it("emits the column's multiplicity (multi for a multi-select)", () => {
- expect(buildColumnDefinition("text", "Multi-select", "multi")).toBe("promoted,multi,text,alias=Multi-select");
- });
- });
-
describe("parseObject — property values", () => {
it("maps supported property values to labels, schemes email/phone with mailto:/tel:", () => {
const details = {
diff --git a/packages/trilium-core/src/services/import/anytype/collection.ts b/packages/trilium-core/src/services/import/anytype/collection.ts
index a0d8261b6c..d7d59d3547 100644
--- a/packages/trilium-core/src/services/import/anytype/collection.ts
+++ b/packages/trilium-core/src/services/import/anytype/collection.ts
@@ -17,9 +17,8 @@ import { dayjs } from "@triliumnext/commons";
import type BNote from "../../../becca/entities/bnote.js";
import noteService from "../../notes.js";
-import { escapeHtml } from "../../utils/index.js";
import { basename } from "../../utils/path.js";
-import mimeService from "../mime.js";
+import { applyUrlScheme, attachmentReferenceLink, buildPromotedDefinition, saveFileAttachment, toAttributeName } from "../collection_utils.js";
import type { AnytypeBlock, AnytypeDetails, AnytypeSnapshot, FileObjectInfo, Multiplicity, ParsedCollection, ParsedColumn, ParsedObject, ParsedProperty, PropertyLabelType, RelationInfo } from "./model.js";
/** Normalizes a zip entry / file path to forward slashes and lower case (Windows exports use backslashes),
@@ -233,34 +232,7 @@ function formatPropertyValue(raw: unknown, labelType: PropertyLabelType, scheme:
if (!value.trim()) {
return undefined;
}
- if (scheme) {
- return value.startsWith(scheme) ? value : `${scheme}${value}`;
- }
- return value;
-}
-
-/**
- * Converts an Anytype property name to a camelCase Trilium attribute name (e.g. `Text property` →
- * `textProperty`, `URL` → `url`, `Date & Time` → `dateTime`). The original name is kept as the promoted
- * alias (see {@link buildColumnDefinition}). A name with no alphanumeric content falls back to `unnamed`.
- */
-export function toAttributeName(name: string): string {
- const words = name.match(/[\p{L}\p{N}]+/gu);
- if (!words) {
- return "unnamed";
- }
- return words.map((word, index) => (index === 0 ? word.toLowerCase() : word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())).join("");
-}
-
-/**
- * Builds a promoted-attribute definition for a collection column (e.g. `promoted,single,url,alias=URL`, or
- * `promoted,multi,text,alias=Multi-select`). The original column name is kept verbatim as the alias so its
- * spacing and casing still show in the UI; commas, equals and control characters are neutralized so they
- * can't corrupt the comma/`=`-delimited definition string.
- */
-export function buildColumnDefinition(labelType: PropertyLabelType, alias: string, multiplicity: Multiplicity = "single"): string {
- const safeAlias = alias.replace(/[\x00-\x1f,=]/g, " ").trim();
- return `promoted,${multiplicity},${labelType},alias=${safeAlias}`;
+ return scheme ? applyUrlScheme(value, scheme) : value;
}
/**
@@ -278,7 +250,7 @@ export function createCollectionNote(parentNoteId: string, page: ParsedObject, c
let position = 0;
for (const column of collection.columns) {
position += 10;
- note.addAttribute("label", `label:${column.name}`, buildColumnDefinition(column.labelType, column.alias, column.multiplicity), true, position);
+ note.addAttribute("label", `label:${column.name}`, buildPromotedDefinition({ alias: column.alias, labelType: column.labelType, multiplicity: column.multiplicity }), true, position);
}
return note;
}
@@ -303,14 +275,9 @@ export function applyFiles(note: BNote, page: ParsedObject, fileObjects: Map<str
if (!info || !bytes) {
continue;
}
- const attachment = note.saveAttachment({
- role: "file",
- mime: info.mime || mimeService.getMime(info.title) || "application/octet-stream",
- title: info.title,
- content: bytes
- });
+ const attachment = saveFileAttachment(note, info.title, bytes, info.mime);
if (attachment.attachmentId) {
- fileLinks.push(`<p><a class="reference-link" href="#root/${note.noteId}?viewMode=attachments&attachmentId=${attachment.attachmentId}">${escapeHtml(info.title)}</a></p>`);
+ fileLinks.push(`<p>${attachmentReferenceLink(note.noteId, attachment.attachmentId, info.title)}</p>`);
}
}
diff --git a/packages/trilium-core/src/services/import/notion/collection.spec.ts b/packages/trilium-core/src/services/import/collection_utils.spec.ts
similarity index 53%
rename from packages/trilium-core/src/services/import/notion/collection.spec.ts
rename to packages/trilium-core/src/services/import/collection_utils.spec.ts
index 135856e502..081e9a1a3f 100644
--- a/packages/trilium-core/src/services/import/notion/collection.spec.ts
+++ b/packages/trilium-core/src/services/import/collection_utils.spec.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
-import { toAttributeName } from "./collection.js";
+import { buildPromotedDefinition, toAttributeName } from "./collection_utils.js";
describe("toAttributeName", () => {
it("camelCases a multi-word name, lower-casing the first word", () => {
@@ -36,9 +36,34 @@ describe("toAttributeName", () => {
expect(toAttributeName("Café date")).toBe("caféDate");
});
+ it("camelCases names with mixed separators and an ampersand", () => {
+ expect(toAttributeName("Text property")).toBe("textProperty");
+ expect(toAttributeName("Number prop")).toBe("numberProp");
+ expect(toAttributeName("Date & Time")).toBe("dateTime");
+ });
+
it("falls back to 'unnamed' when there is no alphanumeric content", () => {
expect(toAttributeName("")).toBe("unnamed");
expect(toAttributeName("()")).toBe("unnamed");
expect(toAttributeName(" ")).toBe("unnamed");
});
});
+
+describe("buildPromotedDefinition", () => {
+ it("builds a single-valued promoted definition keeping the original name as the alias", () => {
+ expect(buildPromotedDefinition({ alias: "URL", labelType: "url", multiplicity: "single" })).toBe("promoted,single,url,alias=URL");
+ expect(buildPromotedDefinition({ alias: "Text property", labelType: "text", multiplicity: "single" })).toBe("promoted,single,text,alias=Text property");
+ });
+
+ it("neutralizes commas, equals and control chars in the alias so the definition can't be corrupted", () => {
+ expect(buildPromotedDefinition({ alias: "a,b=c", labelType: "text", multiplicity: "single" })).toBe("promoted,single,text,alias=a b c");
+ });
+
+ it("emits the column's multiplicity (multi for a multi-select)", () => {
+ expect(buildPromotedDefinition({ alias: "Multi-select", labelType: "text", multiplicity: "multi" })).toBe("promoted,multi,text,alias=Multi-select");
+ });
+
+ it("omits the value type for a relation column (no labelType)", () => {
+ expect(buildPromotedDefinition({ alias: "Related", multiplicity: "multi" })).toBe("promoted,multi,alias=Related");
+ });
+});
diff --git a/packages/trilium-core/src/services/import/collection_utils.ts b/packages/trilium-core/src/services/import/collection_utils.ts
new file mode 100644
index 0000000000..d69be3d9b3
--- /dev/null
+++ b/packages/trilium-core/src/services/import/collection_utils.ts
@@ -0,0 +1,58 @@
+/**
+ * Shared helpers for the structured-import path (Notion, Anytype, …): turning a database/collection's column
+ * and property data into the Trilium markup and attributes the editor expects. Each importer parses its own
+ * source format; these produce the common *output* — attribute names, promoted-attribute definitions,
+ * reference links and file attachments — so those formats stay consistent across importers.
+ */
+
+import type BNote from "../../becca/entities/bnote.js";
+import { escapeHtml } from "../utils/index.js";
+import mimeService from "./mime.js";
+
+/**
+ * Converts a column/property name to a camelCase Trilium attribute name (e.g. `Last edited by` →
+ * `lastEditedBy`, `URL` → `url`, `Multi-select` → `multiSelect`). The name is split into alphanumeric words;
+ * the first is lower-cased and the rest title-cased, so the result is always a valid attribute name. A name
+ * with no alphanumeric content falls back to `unnamed`. The original name is usually kept as the promoted
+ * alias (see {@link buildPromotedDefinition}) so its spacing and casing still show in the UI.
+ */
+export function toAttributeName(name: string): string {
+ const words = name.match(/[\p{L}\p{N}]+/gu);
+ if (!words) {
+ return "unnamed";
+ }
+ return words.map((word, index) => (index === 0 ? word.toLowerCase() : word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())).join("");
+}
+
+/**
+ * Builds a promoted-attribute definition for a database/collection column (e.g. `promoted,single,url,alias=URL`,
+ * or `promoted,multi,text,alias=Multi-select`). The alias keeps the original (pretty) name in the UI while
+ * the attribute name stays sanitized; commas, equals and control characters are neutralized so they can't
+ * corrupt the single-line, comma/`=`-delimited definition. A relation column carries no value type, so
+ * `labelType` is omitted (e.g. `promoted,multi,alias=Related`).
+ */
+export function buildPromotedDefinition({ alias, labelType, multiplicity }: { alias: string; labelType?: string; multiplicity: "single" | "multi" }): string {
+ const safeAlias = alias.replace(/[\x00-\x1f,=]/g, " ").trim();
+ const type = labelType ? `${labelType},` : "";
+ return `promoted,${multiplicity},${type}alias=${safeAlias}`;
+}
+
+/** A Trilium attachment reference-link (the chip CKEditor renders) pointing at a note's attachment. */
+export function attachmentReferenceLink(noteId: string, attachmentId: string, title: string): string {
+ return `<a class="reference-link" href="#root/${noteId}?viewMode=attachments&attachmentId=${attachmentId}">${escapeHtml(title)}</a>`;
+}
+
+/** Gives a value a clickable scheme (`mailto:` for an email, `tel:` for a phone) unless it already carries it. */
+export function applyUrlScheme(value: string, scheme: string): string {
+ return value.startsWith(scheme) ? value : `${scheme}${value}`;
+}
+
+/** Saves bytes as a `role:"file"` attachment on `note`, defaulting the MIME from the title (or octet-stream). */
+export function saveFileAttachment(note: BNote, title: string, content: Uint8Array, mime?: string) {
+ return note.saveAttachment({
+ role: "file",
+ mime: mime || mimeService.getMime(title) || "application/octet-stream",
+ title,
+ content
+ });
+}
diff --git a/packages/trilium-core/src/services/import/notion/collection.ts b/packages/trilium-core/src/services/import/notion/collection.ts
index ca4a1e1b40..5a45dd8354 100644
--- a/packages/trilium-core/src/services/import/notion/collection.ts
+++ b/packages/trilium-core/src/services/import/notion/collection.ts
@@ -13,8 +13,7 @@ import { dayjs } from "@triliumnext/commons";
import type { HTMLElement } from "node-html-parser";
import type BNote from "../../../becca/entities/bnote.js";
-import { escapeHtml } from "../../utils/index.js";
-import mimeService from "../mime.js";
+import { applyUrlScheme, attachmentReferenceLink, buildPromotedDefinition, saveFileAttachment, toAttributeName } from "../collection_utils.js";
import type { LinkTarget, NotionProperty, ParsedPage } from "./model.js";
import { getNotionId, stripNotionId } from "./notion_id.js";
import { baseName, internalPageId, ownedFolderKey, parentFolderKey, removeExtension, resolveResourcePath } from "./paths.js";
@@ -168,26 +167,6 @@ export function extractProperties(root: HTMLElement): NotionProperty[] {
return properties;
}
-/**
- * Converts a Notion column name to a Trilium attribute name in camelCase (e.g. `Last edited by` →
- * `lastEditedBy`, `Multi-select` → `multiSelect`, `URL` → `url`). The name is split into alphanumeric words on
- * every other character; the first word is lower-cased and each following word title-cased, so the result is
- * always a valid attribute name (only letters and digits). A name with no alphanumeric content falls back to
- * `unnamed`. The original column name is kept verbatim as the promoted-attribute alias (see
- * {@link buildPromotedDefinition}), so its spacing and casing still show in the UI.
- */
-export function toAttributeName(name: string): string {
- const words = name.match(/[\p{L}\p{N}]+/gu);
- if (!words) {
- return "unnamed";
- }
- return words
- .map((word, index) => index === 0
- ? word.toLowerCase()
- : word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
- .join("");
-}
-
/**
* Normalizes a Notion number cell to a bare numeric string Trilium's `number` input accepts. Notion renders
* the *formatted* value (e.g. `1,200`, `$12.00`, `12%`), so strip everything but digits, a decimal point and a
@@ -272,10 +251,10 @@ function numericFormulaValue(text: string): string | undefined {
/** Gives an email/phone href a clickable scheme (`mailto:`/`tel:`); a plain url href is returned as-is. */
function toUrlValue(type: string, href: string): string {
if (type === "email") {
- return href.startsWith("mailto:") ? href : `mailto:${href}`;
+ return applyUrlScheme(href, "mailto:");
}
if (type === "phone_number") {
- return href.startsWith("tel:") ? href : `tel:${href}`;
+ return applyUrlScheme(href, "tel:");
}
return href;
}
@@ -367,7 +346,7 @@ export function applyOwnedProperties(note: BNote, page: ParsedPage, resources: M
const fileLinks: string[] = [];
for (const property of page.properties) {
if (property.kind === "file") {
- const attachment = saveFileAttachment(note, property.value, page.path, resources);
+ const attachment = saveFileColumn(note, property.value, page.path, resources);
if (attachment?.attachmentId) {
fileLinks.push(`<p>${attachmentReferenceLink(note.noteId, attachment.attachmentId, attachment.title)}</p>`);
}
@@ -399,25 +378,13 @@ export function applyRelationProperties(note: BNote, page: ParsedPage, resolve:
* the same way page content is, so only files bundled in the export attach — an external link (or a missing
* file) is silently skipped.
*/
-function saveFileAttachment(note: BNote, href: string, pagePath: string, resources: Map<string, Uint8Array>) {
+function saveFileColumn(note: BNote, href: string, pagePath: string, resources: Map<string, Uint8Array>) {
const resourcePath = resolveResourcePath(pagePath, href);
const bytes = resources.get(resourcePath);
if (!bytes) {
return undefined;
}
-
- const title = baseName(resourcePath);
- return note.saveAttachment({
- role: "file",
- mime: mimeService.getMime(title) || "application/octet-stream",
- title,
- content: bytes
- });
-}
-
-/** Builds a Trilium attachment reference-link (the chip CKEditor renders) — the shape rewriteAttachments produces. */
-function attachmentReferenceLink(noteId: string, attachmentId: string, title: string): string {
- return `<a class="reference-link" href="#root/${noteId}?viewMode=attachments&attachmentId=${attachmentId}">${escapeHtml(title)}</a>`;
+ return saveFileAttachment(note, baseName(resourcePath), bytes);
}
/**
@@ -470,7 +437,7 @@ export function applyDatabaseSchemas(pages: ParsedPage[], noteByFolder: Map<stri
position += 10;
// A definition is always a label, but its name is `relation:<x>` for a relation column, `label:<x>` otherwise.
const definitionName = `${property.kind === "relation" ? "relation" : "label"}:${toAttributeName(property.name)}`;
- container.addAttribute("label", definitionName, buildPromotedDefinition(property), true, position);
+ container.addAttribute("label", definitionName, buildPromotedDefinition({ alias: property.name, labelType: property.labelType, multiplicity: property.multiplicity }), true, position);
}
}
}
@@ -507,13 +474,3 @@ function orderColumns(properties: NotionProperty[], csvColumns: string[] | undef
.map((entry) => entry.property);
}
-/** 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 a single-line, comma/`=`-delimited string, so neutralize those delimiters and any
- // control character (e.g. a stray newline) in the alias to avoid corrupting it.
- const alias = name.replace(/[\x00-\x1f,=]/g, " ").trim();
- // A relation has no value type; a label carries one (text/date/url/boolean/…).
- const type = labelType ? `${labelType},` : "";
- return `promoted,${multiplicity},${type}alias=${alias}`;
-}
diff --git a/packages/trilium-core/src/services/import/notion/importer.ts b/packages/trilium-core/src/services/import/notion/importer.ts
index 16d1d7f053..dcb761d0be 100644
--- a/packages/trilium-core/src/services/import/notion/importer.ts
+++ b/packages/trilium-core/src/services/import/notion/importer.ts
@@ -26,7 +26,8 @@ import type TaskContext from "../../task_context.js";
import dateUtils from "../../utils/date.js";
import { getZipProvider } from "../../zip_provider.js";
import mimeService from "../mime.js";
-import { applyDatabaseSchemas, applyOwnedProperties, applyRelationProperties, extractProperties, reconcileDateColumns, resolveDatabaseContainers, toAttributeName } from "./collection.js";
+import { toAttributeName } from "../collection_utils.js";
+import { applyDatabaseSchemas, applyOwnedProperties, applyRelationProperties, extractProperties, reconcileDateColumns, resolveDatabaseContainers } from "./collection.js";
import { convertNotionHtml } from "./converter.js";
import type { LinkTarget, ParsedPage } from "./model.js";
import { getNotionId, stripNotionId } from "./notion_id.js";