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(anytype): import date, date-time and checkbox properties
Elian Doran0207638989a6
diff --git a/packages/trilium-core/src/services/import/anytype/importer.integration.spec.ts b/packages/trilium-core/src/services/import/anytype/importer.integration.spec.tsindex dbdc7ca514..5c441430f3 100644--- a/packages/trilium-core/src/services/import/anytype/importer.integration.spec.ts+++ b/packages/trilium-core/src/services/import/anytype/importer.integration.spec.ts@@ -61,9 +61,10 @@ function pageObject(id: string, name: string, paragraphs: string[], opts: { layo});}-/** A relation-definition file (relations/<x>.pb.json): names and types a custom property by its key. */-function relationObject(key: string, name: string, format: number): string {- return JSON.stringify({ sbType: "STRelation", snapshot: { data: { details: { id: `rel-${key}`, relationKey: key, name, relationFormat: format } } } });+/** A relation-definition file (relations/<x>.pb.json): names and types a custom property by its key.+ * `includeTime` distinguishes a date-time relation from a plain date (both are format 4). */+function relationObject(key: string, name: string, format: number, includeTime = false): string {+ return JSON.stringify({ sbType: "STRelation", snapshot: { data: { details: { id: `rel-${key}`, relationKey: key, name, relationFormat: format, relationFormatIncludeTime: includeTime } } } });}/** A collection page: a dataview block flagged `isCollection`, its members in `details.links`, and one@@ -523,6 +524,39 @@ describe("Anytype importer — integration", () => {expect(byEmail?.getOwnedLabelValue("email")).toBe("mailto:[email protected]");});+ it("imports date, date-time and checkbox columns with correctly typed definitions and values", async () => {+ // Verbatim relation keys and member values from "My custom collection".+ const dateKey = "6a3e330acafa6953a4661c6b";+ const dateTimeKey = "6a3e3317cafa6953a4661c6e";+ const checkboxKey = "6a3e3354cafa6953a4661c73";+ const importRoot = await importAnytype({+ "objects/coll.pb.json": collectionObject("coll", "Typed", ["m1"], [dateKey, dateTimeKey, checkboxKey]),+ "objects/m1.pb.json": memberObject("m1", { [dateKey]: 1782461197, [dateTimeKey]: 1782461208, [checkboxKey]: true }),+ "relations/date.pb.json": relationObject(dateKey, "Date", 4),+ "relations/datetime.pb.json": relationObject(dateTimeKey, "Date & Time", 4, true),+ "relations/checkbox.pb.json": relationObject(checkboxKey, "Checkbox", 6)+ });++ const collection = importRoot.getChildNotes()[0];+ // A plain date, a date-time (includeTime) and a checkbox each map to their Trilium label type.+ expect(collection.getOwnedLabelValue("label:date")).toBe("promoted,single,date,alias=Date");+ expect(collection.getOwnedLabelValue("label:dateTime")).toBe("promoted,single,datetime,alias=Date & Time");+ expect(collection.getOwnedLabelValue("label:checkbox")).toBe("promoted,single,boolean,alias=Checkbox");++ // Dates are formatted in local time (computed here via native Date getters so the assertion holds in+ // any timezone); the checkbox is a boolean.+ const local = (epochSeconds: number, withTime = false) => {+ const d = new Date(epochSeconds * 1000);+ const pad = (n: number) => String(n).padStart(2, "0");+ const date = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;+ return withTime ? `${date}T${pad(d.getHours())}:${pad(d.getMinutes())}` : date;+ };+ const row = collection.getChildNotes()[0];+ expect(row.getOwnedLabelValue("date")).toBe(local(1782461197));+ expect(row.getOwnedLabelValue("dateTime")).toBe(local(1782461208, true));+ expect(row.getOwnedLabelValue("checkbox")).toBe("true");+ });+it("produces an empty root when the export has no pages", async () => {const importRoot = await importAnytype({"types/type1.pb.json": JSON.stringify({ sbType: "STType", snapshot: { data: { details: { id: "type1", name: "Article" } } } })diff --git a/packages/trilium-core/src/services/import/anytype/importer.spec.ts b/packages/trilium-core/src/services/import/anytype/importer.spec.tsindex 56cb74d13b..f763096e78 100644--- a/packages/trilium-core/src/services/import/anytype/importer.spec.ts+++ b/packages/trilium-core/src/services/import/anytype/importer.spec.ts@@ -13,9 +13,18 @@ function snapshot(return { sbType, snapshot: { data: { blocks, details } } };}-/** Builds a relation map (relationKey → name + format) from `[key, name, format]` triples. */-function relationMap(entries: [string, string, number][]): Map<string, RelationInfo> {- return new Map(entries.map(([key, name, format]) => [key, { name, format }]));+/** Builds a relation map (relationKey → info) from `[key, name, format, includeTime?]` tuples. */+function relationMap(entries: [string, string, number, boolean?][]): Map<string, RelationInfo> {+ return new Map(entries.map(([key, name, format, includeTime]) => [key, { name, format, includeTime }]));+}++/** The local-time `YYYY-MM-DD[THH:mm]` an epoch (seconds) should format to — computed via native Date+ * getters so the assertion is timezone-independent (the importer uses dayjs local formatting). */+function localDate(epochSeconds: number, withTime = false): string {+ const d = new Date(epochSeconds * 1000);+ const pad = (n: number) => String(n).padStart(2, "0");+ const date = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;+ return withTime ? `${date}T${pad(d.getHours())}:${pad(d.getMinutes())}` : date;}/** A text block with the given style (defaults to Paragraph), optional children and optional marks. */@@ -331,14 +340,17 @@ describe("dates", () => {});describe("collection properties", () => {- // The five supported property formats: 0 text, 2 number, 7 url, 8 email, 9 phone.+ // Supported property formats: 0 text, 2 number, 4 date/date-time, 6 checkbox, 7 url, 8 email, 9 phone.const rels = relationMap([["6a3e29d5cafa6953a4661c15", "Text property", 0],["6a3e29e1cafa6953a4661c16", "Number prop", 2],+ ["6a3e330acafa6953a4661c6b", "Date", 4, false], // date (no time)+ ["6a3e3317cafa6953a4661c6e", "Date & Time", 4, true], // date-time (includeTime)+ ["6a3e3354cafa6953a4661c73", "Checkbox", 6],["6a3e335dcafa6953a4661c74", "URL", 7],["6a3e336dcafa6953a4661c75", "Email", 8],["6a3e337dcafa6953a4661c76", "Phone", 9],- ["6a3e3354cafa6953a4661c73", "Checkbox", 6] // an unsupported format (skipped for now)+ ["6a3e3323cafa6953a4661c6f", "File", 5] // an unsupported format (skipped for now)]);describe("toAttributeName", () => {@@ -369,21 +381,32 @@ describe("collection properties", () => {name: "Row","6a3e29d5cafa6953a4661c15": "hello","6a3e29e1cafa6953a4661c16": 42,+ "6a3e330acafa6953a4661c6b": 1782461197, // Date (epoch seconds) → date only+ "6a3e3317cafa6953a4661c6e": 1782461208, // Date & Time → datetime+ "6a3e3354cafa6953a4661c73": true, // Checkbox → boolean"6a3e335dcafa6953a4661c74": "https://triliumnotes.org","6a3e336dcafa6953a4661c75": "[email protected]","6a3e337dcafa6953a4661c76": "12345",- "6a3e3354cafa6953a4661c73": true // checkbox — unsupported, skipped+ "6a3e3323cafa6953a4661c6f": ["log"] // File — unsupported, skipped};const result = parseObject(snapshot([{ id: "obj", childrenIds: [] }], details), undefined, rels);expect(result.properties).toEqual([{ name: "textProperty", value: "hello" },{ name: "numberProp", value: "42" },+ { name: "date", value: localDate(1782461197) },+ { name: "dateTime", value: localDate(1782461208, true) },+ { name: "checkbox", value: "true" },{ name: "url", value: "https://triliumnotes.org" },{ name: "email", value: "mailto:[email protected]" },{ name: "phone", value: "tel:12345" }]);});+ it("renders a false checkbox as boolean false (an unset value, not present, contributes nothing)", () => {+ const details = { id: "obj", "6a3e3354cafa6953a4661c73": false };+ expect(parseObject(snapshot([{ id: "obj", childrenIds: [] }], details), undefined, rels).properties).toEqual([{ name: "checkbox", value: "false" }]);+ });+it("ignores system relations (non-hex keys), unset values and an existing scheme", () => {const details = {id: "obj",@@ -429,8 +452,8 @@ describe("collection properties", () => {{relations: [{ key: "6a3e335dcafa6953a4661c74", isVisible: true }, // URL → column- { key: "name", isVisible: true }, // system column → excluded- { key: "6a3e3354cafa6953a4661c73", isVisible: true }, // Checkbox unsupported → excluded+ { key: "name", isVisible: true }, // system column (non-hex key) → excluded+ { key: "6a3e3323cafa6953a4661c6f", isVisible: true }, // File (format 5) unsupported → excluded{ key: "6a3e336dcafa6953a4661c75", isVisible: false } // Email hidden → excluded]}diff --git a/packages/trilium-core/src/services/import/anytype/importer.ts b/packages/trilium-core/src/services/import/anytype/importer.tsindex 4a79ba6d2c..ae57f6ecd3 100644--- a/packages/trilium-core/src/services/import/anytype/importer.ts+++ b/packages/trilium-core/src/services/import/anytype/importer.ts@@ -18,6 +18,7 @@* this service just builds the tree and returns its root note, like the zip/notion importers.*/+import { dayjs } from "@triliumnext/commons";import { getMimeTypeFromMarkdownName, MIME_TYPE_AUTO, normalizeMimeTypeForCKEditor } from "@triliumnext/commons/src/lib/mime_type.js";import { t } from "i18next";@@ -104,7 +105,7 @@ function buildRelationMap(relations: AnytypeSnapshot[]): Map<string, RelationInffor (const snapshot of relations) {const details = snapshot.snapshot?.data?.details;if (details?.relationKey) {- map.set(details.relationKey, { name: details.name ?? "", format: details.relationFormat ?? -1 });+ map.set(details.relationKey, { name: details.name ?? "", format: details.relationFormat ?? -1, includeTime: !!details.relationFormatIncludeTime });}}return map;@@ -172,18 +173,32 @@ function pageTitle(details: AnytypeDetails | undefined): string {// #region Collection properties/**- * The five property formats imported so far, mapped to a Trilium label type. Email and phone keep their- * value clickable with a `mailto:`/`tel:` scheme (the same convention as the Notion importer). Other Anytype- * formats (select, multi-select, date, file, checkbox, …) are deferred.+ * Maps an Anytype relation to the Trilium label type its values become, or undefined for a format not yet+ * imported (select, multi-select, file, …). Date and date-time share format 4, told apart by the relation's+ * `includeTime` flag; email and phone reuse the `url` type with a `mailto:`/`tel:` scheme (the same+ * convention as the Notion importer).*/-const PROPERTY_FORMATS: Record<number, { labelType: PropertyLabelType; scheme?: string }> = {- 0: { labelType: "text" }, // longtext- 1: { labelType: "text" }, // shorttext- 2: { labelType: "number" }, // number- 7: { labelType: "url" }, // url- 8: { labelType: "url", scheme: "mailto:" }, // email- 9: { labelType: "url", scheme: "tel:" } // phone-};+function propertyMapping(info: RelationInfo): { labelType: PropertyLabelType; scheme?: string } | undefined {+ switch (info.format) {+ case 0: // longtext+ case 1: // shorttext+ return { labelType: "text" };+ case 2: // number+ return { labelType: "number" };+ case 4: // date / date-time+ return { labelType: info.includeTime ? "datetime" : "date" };+ case 6: // checkbox+ return { labelType: "boolean" };+ case 7: // url+ return { labelType: "url" };+ case 8: // email+ return { labelType: "url", scheme: "mailto:" };+ case 9: // phone+ return { labelType: "url", scheme: "tel:" };+ default:+ return undefined;+ }+}/** A custom (user-defined) relation key is a hex id; system relations (name, type, createdDate, …) are* plain words, and must not be imported as properties. */@@ -193,7 +208,7 @@ function isCustomRelationKey(key: string): boolean {/*** Reads an object's custom property values as `{ attributeName, value }` pairs. Only the supported formats- * (see {@link PROPERTY_FORMATS}) of user-defined relations are taken; unset values are dropped, and email /+ * (see {@link propertyMapping}) of user-defined relations are taken; unset values are dropped, and email /* phone values gain a `mailto:`/`tel:` scheme so they stay clickable as url labels.*/function parseProperties(details: AnytypeDetails, relations: Map<string, RelationInfo>): ParsedProperty[] {@@ -203,7 +218,7 @@ function parseProperties(details: AnytypeDetails, relations: Map<string, Relatiocontinue;}const info = relations.get(key);- const mapping = info ? PROPERTY_FORMATS[info.format] : undefined;+ const mapping = info ? propertyMapping(info) : undefined;if (!info || !mapping) {continue;}@@ -234,7 +249,7 @@ function parseCollection(blocks: AnytypeBlock[], details: AnytypeDetails, relaticontinue;}const info = relations.get(key);- const mapping = info ? PROPERTY_FORMATS[info.format] : undefined;+ const mapping = info ? propertyMapping(info) : undefined;if (!info || !mapping) {continue;}@@ -249,14 +264,32 @@ function parseCollection(blocks: AnytypeBlock[], details: AnytypeDetails, relati}/**- * Converts a property value to its Trilium label string, or undefined when it should be dropped. A number is- * stringified (and a non-numeric value rejected); a text/url value is trimmed-checked for emptiness; an- * email/phone value is given its `mailto:`/`tel:` scheme unless it already carries one.+ * Converts a property value to its Trilium label string, or undefined when it should be dropped. A boolean+ * becomes `"true"`/`"false"`; a date (Anytype stores an epoch in *seconds*) becomes a local `YYYY-MM-DD` or+ * `YYYY-MM-DDTHH:mm` string the promoted date/datetime inputs round-trip; a number is stringified (a+ * non-numeric value rejected); a text/url value is trimmed-checked for emptiness; an email/phone value is+ * given its `mailto:`/`tel:` scheme unless it already carries one.*/function formatPropertyValue(raw: unknown, labelType: PropertyLabelType, scheme: string | undefined): string | undefined {if (raw === null || raw === undefined) {return undefined;}+ if (labelType === "boolean") {+ if (raw === true || raw === "true") {+ return "true";+ }+ return raw === false || raw === "false" ? "false" : undefined;+ }+ if (labelType === "date" || labelType === "datetime") {+ const seconds = typeof raw === "number" ? raw : Number(raw);+ if (!Number.isFinite(seconds)) {+ return undefined;+ }+ // Anytype stores the instant; format it in local time (like the Notion importer) so the date/time+ // matches the wall-clock the user saw in Anytype, in the format the promoted date/datetime inputs use.+ const local = dayjs(new Date(seconds * 1000));+ return labelType === "datetime" ? local.format("YYYY-MM-DD[T]HH:mm") : local.format("YYYY-MM-DD");+ }if (labelType === "number") {const num = typeof raw === "number" ? raw : Number(String(raw));return Number.isFinite(num) ? String(num) : undefined;@@ -845,9 +878,11 @@ export interface AnytypeDetails {lastModifiedDate?: number;/** Outgoing object links; for a collection, this is its membership. */links?: string[];- /** On a relation-definition object: the key objects carry the value under, and the format code. */+ /** On a relation-definition object: the key objects carry the value under, the format code, and (for a+ * date format) whether the value includes a time component. */relationKey?: string;relationFormat?: number;+ relationFormatIncludeTime?: boolean;/** A custom property value, keyed by its relation's hex `relationKey`. */[key: string]: unknown;}@@ -894,14 +929,16 @@ export interface ResolvedLink {* target wasn't imported (a set/collection, or an object missing from the export). */export type LinkResolver = (targetCid: string) => ResolvedLink | undefined;-/** A relation definition resolved from the `relations/` folder: its display name and Anytype format code. */+/** A relation definition resolved from the `relations/` folder: its display name, Anytype format code and+ * (for date formats) whether the value carries a time component. */export interface RelationInfo {name: string;format: number;+ includeTime?: boolean;}/** The Trilium label types a supported Anytype property maps to (email/phone reuse `url`). */-export type PropertyLabelType = "text" | "number" | "url";+export type PropertyLabelType = "text" | "number" | "url" | "date" | "datetime" | "boolean";/** One custom property value on an object: the Trilium attribute name and its (already formatted) value. */export interface ParsedProperty {