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/anytype): map collection view types and board/calendar grouping
Elian Doranc153a38fd163
diff --git a/packages/trilium-core/src/services/import/anytype/collection.spec.ts b/packages/trilium-core/src/services/import/anytype/collection.spec.tsindex 45c240d16a..1734f6906c 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,6 @@import { describe, expect, it } from "vitest";-import { synthesizeColumns } from "./collection.js";+import { mapViewType, synthesizeColumns } from "./collection.js";import { isCollectionObject, isPage, parseObject } from "./importer.js";import type { AnytypeBlock, AnytypeMark, AnytypeSnapshot, RelationInfo } from "./model.js";@@ -187,11 +187,41 @@ describe("collection properties", () => {const doc = snapshot([{ id: "obj", childrenIds: ["dv"] }, dv], { id: "obj", name: "My collection", links: ["m1", "m2"] });const result = parseObject(doc, undefined, rels);expect(result.collection).toEqual({+ viewType: "table", // no view layout given → defaults to tablememberIds: ["m1", "m2"],columns: [{ name: "url", labelType: "url", alias: "URL", multiplicity: "single" }]});});+ it("maps the first view's layout to a Trilium view type", () => {+ const collection = (type?: string) => {+ const dv: AnytypeBlock = { id: "dv", childrenIds: [], dataview: { isCollection: true, views: [{ type, relations: [] }] } };+ const doc = snapshot([{ id: "obj", childrenIds: ["dv"] }, dv], { id: "obj", name: "C", links: [] });+ return parseObject(doc, undefined, rels).collection?.viewType;+ };+ expect(collection("Gallery")).toBe("grid");+ expect(collection("List")).toBe("list");+ expect(collection("Kanban")).toBe("board");+ expect(collection("Calendar")).toBe("calendar");+ expect(collection("Table")).toBe("table");+ expect(collection(undefined)).toBe("table");+ });++ it("resolves the view's groupRelationKey to the grouping attribute, ignoring an empty or unknown key", () => {+ const groupBy = (groupRelationKey?: string) => {+ const dv: AnytypeBlock = { id: "dv", childrenIds: [], dataview: { isCollection: true, views: [{ type: "Kanban", groupRelationKey, relations: [] }] } };+ const doc = snapshot([{ id: "obj", childrenIds: ["dv"] }, dv], { id: "obj", name: "C", links: [] });+ return parseObject(doc, undefined, rels).collection?.groupByAttribute;+ };+ // The key resolves to its relation's attribute name (the same one members carry the value under).+ expect(groupBy("6a3e29e8cafa6953a4661c17")).toBe("selectProperty");+ expect(groupBy("6a3e330acafa6953a4661c6b")).toBe("date");+ // A non-grouping view (empty key) and a key with no relation in the export contribute nothing.+ expect(groupBy("")).toBeUndefined();+ expect(groupBy("6a3e0000cafa6953a4661cff")).toBeUndefined();+ expect(groupBy(undefined)).toBeUndefined();+ });+it("carries each column's multiplicity (multi for a multi-select)", () => {const dv: AnytypeBlock = {id: "dv",@@ -213,6 +243,19 @@ describe("collection properties", () => {});});+ describe("mapViewType", () => {+ it("maps each Anytype layout to its Trilium view, defaulting unknown layouts to table", () => {+ expect(mapViewType("Table")).toBe("table");+ expect(mapViewType("List")).toBe("list");+ expect(mapViewType("Gallery")).toBe("grid");+ expect(mapViewType("Calendar")).toBe("calendar");+ expect(mapViewType("Kanban")).toBe("board");+ // A layout with no Trilium equivalent (e.g. Graph) and a missing layout both fall back to table.+ expect(mapViewType("Graph")).toBe("table");+ expect(mapViewType(undefined)).toBe("table");+ });+ });+describe("synthesizeColumns", () => {it("builds the union of the members' supported custom-relation columns, de-duplicated, in first-seen order", () => {// A collection-scoped export has no view, so the columns come from the properties the members carry.diff --git a/packages/trilium-core/src/services/import/anytype/collection.ts b/packages/trilium-core/src/services/import/anytype/collection.tsindex c4c7cc696c..953a61833f 100644--- a/packages/trilium-core/src/services/import/anytype/collection.ts+++ b/packages/trilium-core/src/services/import/anytype/collection.ts@@ -19,7 +19,7 @@ import type BNote from "../../../becca/entities/bnote.js";import noteService from "../../notes.js";import { basename } from "../../utils/path.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";+import type { AnytypeBlock, AnytypeDetails, AnytypeSnapshot, CollectionViewType, 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),* so a file property's `source` matches the key its bytes were stored under. */@@ -175,8 +175,44 @@ export function parseCollection(blocks: AnytypeBlock[], details: AnytypeDetails,return undefined;}- const visibleKeys = (dataview.views?.[0]?.relations ?? []).filter((relation) => relation.isVisible).map((relation) => relation.key);- return { memberIds: details.links ?? [], columns: columnsFromKeys(visibleKeys, relations) };+ const view = dataview.views?.[0];+ const visibleKeys = (view?.relations ?? []).filter((relation) => relation.isVisible).map((relation) => relation.key);+ return {+ viewType: mapViewType(view?.type),+ groupByAttribute: resolveGroupAttribute(view?.groupRelationKey, relations),+ memberIds: details.links ?? [],+ columns: columnsFromKeys(visibleKeys, relations)+ };+}++/** Maps an Anytype dataview layout to the closest Trilium collection view (unknown layouts → a table). */+export function mapViewType(type: string | undefined): CollectionViewType {+ switch (type) {+ case "List":+ return "list";+ case "Gallery":+ return "grid";+ case "Calendar":+ return "calendar";+ case "Kanban":+ return "board";+ default: // Table, and any layout without a Trilium equivalent (e.g. Graph)+ return "table";+ }+}++/**+ * Resolves a view's `groupRelationKey` (a Kanban's grouping relation, a Calendar's date relation) to the+ * Trilium attribute name its members carry the value under — the same `toAttributeName(relation.name)` the+ * property mapping uses, so `#board:groupBy` / `#calendar:startDate` lines up with the members' labels.+ * Returns undefined when the view doesn't group (empty key) or the relation isn't in the export.+ */+function resolveGroupAttribute(groupRelationKey: string | undefined, relations: Map<string, RelationInfo>): string | undefined {+ if (!groupRelationKey) {+ return undefined;+ }+ const info = relations.get(groupRelationKey);+ return info ? toAttributeName(info.name) : undefined;}/**@@ -249,24 +285,36 @@ function formatPropertyValue(raw: unknown, labelType: PropertyLabelType, scheme:}/**- * Creates a collection's container note: an empty `book` with a `table` view whose columns are the- * collection's supported properties, each an *inheritable* promoted-attribute definition (so the table- * renders the column and every member row inherits the field, showing its own value or blank). Mirrors the- * Notion importer's database mapping.+ * Creates a collection's container note: an empty `book` in the collection's mapped view (table / list /+ * grid / calendar / board), whose columns are the collection's supported properties, each an *inheritable*+ * promoted-attribute definition (so the table renders the column and every member row inherits the field,+ * showing its own value or blank). Mirrors the Notion importer's database mapping.*/export function createCollectionNote(parentNoteId: string, page: ParsedObject, collection: ParsedCollection, noteId: string | undefined, isProtected: boolean | undefined): BNote {const { note } = noteService.createNewNote({ noteId, parentNoteId, title: page.title, content: "", type: "book", mime: "", isProtected, utcDateCreated: page.dateCreated });- applyTableView(note, collection.columns);+ applyCollectionView(note, collection.viewType, collection.columns, collection.groupByAttribute);return note;}/**- * Turns `note` into a `table`-view collection whose columns are the given properties, each an *inheritable*- * promoted-attribute definition (so the table renders the column and every child row inherits the field,- * showing its own value or blank). Used for both an imported collection and a collection-scoped export's root.+ * Turns `note` into a collection of the given view type, carrying `columns` as *inheritable* promoted-+ * attribute definitions (so a table renders them as columns and every child row inherits the field, showing+ * its own value or blank). Used for both an imported collection and a collection-scoped export's root.+ *+ * `groupByAttribute` is the member field a board groups its cards by (`#board:groupBy`) or a calendar reads+ * each event's date from (`#calendar:startDate`); other view types don't organize by a field and ignore it.*/-export function applyTableView(note: BNote, columns: ParsedColumn[]) {- note.addLabel("viewType", "table");+export function applyCollectionView(note: BNote, viewType: CollectionViewType, columns: ParsedColumn[], groupByAttribute?: string) {+ note.addLabel("viewType", viewType);++ if (groupByAttribute && viewType === "board") {+ // The board reads its grouping field from the collection note itself, so a plain (owned) label is enough.+ note.addLabel("board:groupBy", groupByAttribute);+ } else if (groupByAttribute && viewType === "calendar") {+ // The calendar resolves each event's date field per *member* (getCustomisableLabel reads `calendar:startDate`+ // off the child), so this must be inheritable for the members to pick up which attribute holds their date.+ note.addLabel("calendar:startDate", groupByAttribute, true);+ }// Increasing positions keep the columns in their stored order (the promoted-attributes UI sorts by// position, and equal positions aren't ordered deterministically).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 0776de198c..81fb828cd8 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@@ -69,8 +69,10 @@ function relationObject(key: string, name: string, format: number, includeTime =/** A collection page: a dataview block flagged `isCollection`, its members in `details.links`, and one* visible view column per supplied relation key. A collection's `resolvedLayout` is the collection layout- * (14), not the basic-page 0 — so the importer must admit it via its `isCollection` flag, not the layout. */-function collectionObject(id: string, name: string, memberIds: string[], columnKeys: string[]): string {+ * (14), not the basic-page 0 — so the importer must admit it via its `isCollection` flag, not the layout.+ * `viewType` is the Anytype view layout (Table/List/Gallery/Calendar/Kanban); omitted defaults to Table.+ * `groupRelationKey` is the relation a Kanban groups by / a Calendar dates events from. */+function collectionObject(id: string, name: string, memberIds: string[], columnKeys: string[], viewType?: string, groupRelationKey?: string): string {return JSON.stringify({sbType: "Page",snapshot: {@@ -79,7 +81,7 @@ function collectionObject(id: string, name: string, memberIds: string[], columnK{ id, childrenIds: ["header", "dataview"] },{ id: "header", childrenIds: ["title"] },{ id: "title", text: { text: "", style: "Title" } },- { id: "dataview", dataview: { isCollection: true, views: [{ relations: columnKeys.map((key) => ({ key, isVisible: true })) }] } }+ { id: "dataview", dataview: { isCollection: true, views: [{ type: viewType, groupRelationKey, relations: columnKeys.map((key) => ({ key, isVisible: true })) }] } }],details: { id, name, resolvedLayout: 14, links: memberIds }}@@ -534,6 +536,67 @@ describe("Anytype importer — integration", () => {expect(byEmail?.getOwnedLabelValue("email")).toBe("mailto:[email protected]");});+ it("maps each Anytype view layout to the matching Trilium collection view type", async () => {+ // The first view's layout (Gallery/List/Kanban/Calendar) drives the book's #viewType; Table/unknown → table.+ const layouts: [string | undefined, string][] = [+ ["Gallery", "grid"],+ ["List", "list"],+ ["Kanban", "board"],+ ["Calendar", "calendar"],+ ["Table", "table"]+ ];+ for (const [anytypeLayout, triliumView] of layouts) {+ const importRoot = await importAnytype({+ "objects/coll.pb.json": collectionObject("coll", `${anytypeLayout} collection`, [], [], anytypeLayout)+ });+ const collection = importRoot.getChildNotes()[0];+ expect(collection.type).toBe("book");+ expect(collection.getOwnedLabelValue("viewType")).toBe(triliumView);+ }+ });++ it("maps a Kanban collection's group relation to #board:groupBy", async () => {+ // Verbatim from the "Kanban collection": grouped by the system "Tag" relation (key "tag", format 11).+ const importRoot = await importAnytype({+ "objects/coll.pb.json": collectionObject("coll", "Kanban collection", [], [], "Kanban", "tag"),+ "relations/tag.pb.json": relationObject("tag", "Tag", 11)+ });++ const collection = importRoot.getChildNotes()[0];+ expect(collection.getOwnedLabelValue("viewType")).toBe("board");+ // The board groups its cards by the attribute the Tag relation resolves to.+ expect(collection.getOwnedLabelValue("board:groupBy")).toBe("tag");+ });++ it("maps a Calendar collection's date relation to #calendar:startDate, dating its members", async () => {+ // Verbatim from the Calendar collection: grouped by the custom "myDate" relation (format 4 date),+ // whose value each member carries as an epoch.+ const dateKey = "6a3e3660cafa6953a4661c94";+ const importRoot = await importAnytype({+ "objects/coll.pb.json": collectionObject("coll", "Calendar collection", ["m1"], [], "Calendar", dateKey),+ "objects/m1.pb.json": memberObject("m1", { [dateKey]: 1782118800 }),+ "relations/mydate.pb.json": relationObject(dateKey, "myDate", 4)+ });++ const collection = importRoot.getChildNotes()[0];+ expect(collection.getOwnedLabelValue("viewType")).toBe("calendar");+ // The calendar reads each event's date from the attribute the myDate relation resolves to. The config+ // must be *inheritable* because the calendar resolves it per member (off the child, not the collection).+ const startDateLabel = collection.getOwnedAttributes().find((a) => a.name === "calendar:startDate");+ expect(startDateLabel?.value).toBe("mydate");+ expect(startDateLabel?.isInheritable).toBe(true);++ // ...so the member both inherits the config and carries its own date under that attribute (local YYYY-MM-DD).+ const day = (() => {+ const d = new Date(1782118800 * 1000);+ const pad = (n: number) => String(n).padStart(2, "0");+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;+ })();+ const member = collection.getChildNotes()[0];+ expect(member.getLabelValue("calendar:startDate")).toBe("mydate"); // inherited from the collection+ expect(member.getOwnedLabelValue("mydate")).toBe(day);+ });+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";diff --git a/packages/trilium-core/src/services/import/anytype/importer.ts b/packages/trilium-core/src/services/import/anytype/importer.tsindex 65d72133ed..b71dc288d1 100644--- a/packages/trilium-core/src/services/import/anytype/importer.ts+++ b/packages/trilium-core/src/services/import/anytype/importer.ts@@ -11,10 +11,11 @@* (Anytype's block-level "link to object" → a Trilium reference link plus an `internalLink` relation, so* backlinks resolve). Each page keeps its original creation and modification timestamps.*- * Collections and their properties are handled in {@link ./collection.js}: a collection becomes a `book`- * with a `table` view whose columns are promoted-attribute definitions, its members nest beneath it, and an- * object's custom relations become labels / file attachments. Pages without a collection land as flat- * children of a fresh "Anytype import" root. Types and templates are still deferred.+ * Collections and their properties are handled in {@link ./collection.js}: a collection becomes a `book` in+ * its mapped view (table / list / grid / calendar / board) whose columns are promoted-attribute definitions,+ * its members nest beneath it, and an object's custom relations become labels / file attachments. Pages+ * without a collection land as flat children of a fresh "Anytype import" root. Types and templates are still+ * deferred.** Invoked from the shared file-import dispatcher (routes/api/import.ts) when the upload is tagged* `format=anytype`, so progress, completion and failure are reported by that dispatcher's TaskContext —@@ -32,7 +33,7 @@ import date_utils from "../../utils/date.js";import { newEntityId } from "../../utils/index.js";import { basename } from "../../utils/path.js";import { getZipProvider } from "../../zip_provider.js";-import { applyFiles, applyProperties, applyTableView, buildFileObjectMap, buildOptionMap, buildRelationMap, createCollectionNote, normalizePath, parseCollection, parseFiles, parseProperties, synthesizeColumns } from "./collection.js";+import { applyCollectionView, applyFiles, applyProperties, buildFileObjectMap, buildOptionMap, buildRelationMap, createCollectionNote, normalizePath, parseCollection, parseFiles, parseProperties, synthesizeColumns } from "./collection.js";import { extractContent } from "./content.js";import type { AnytypeDetails, AnytypeSnapshot, FileObjectInfo, LinkResolver, ParsedColumn, ParsedObject, RelationInfo, ResolvedLink } from "./model.js";@@ -260,7 +261,7 @@ function createNotes(importRootNote: BNote, pages: ParsedObject[], targets: Map<? noteService.createNewNote({ parentNoteId: importRootNote.noteId, title, content: "", type: "book", mime: "", isProtected }).note: noteService.createNewNote({ parentNoteId: importRootNote.noteId, title, content: "", type: "text", mime: "text/html", isProtected }).note;if (rootColumns) {- applyTableView(rootNote, rootColumns);+ applyCollectionView(rootNote, "table", rootColumns);}rootNote.addLabel("iconClass", "bx bx-import");diff --git a/packages/trilium-core/src/services/import/anytype/model.ts b/packages/trilium-core/src/services/import/anytype/model.tsindex 4b726624c4..bacdbbc923 100644--- a/packages/trilium-core/src/services/import/anytype/model.ts+++ b/packages/trilium-core/src/services/import/anytype/model.ts@@ -58,10 +58,15 @@ export interface AnytypeBlock {style?: string;};/** A dataview block — a set (query) or collection (manual list). `isCollection` distinguishes the two;- * `views[].relations` is the ordered, per-column display config (a column's `key` is a `relationKey`). */+ * `views[]` are its views (the first is the active one): `type` is the layout (Table/List/Gallery/+ * Calendar/Kanban), `groupRelationKey` is the relation the view organizes by (a Kanban's grouping+ * column, a Calendar's date field — empty for layouts that don't group) and `relations` the ordered,+ * per-column display config (a column's `key` is a `relationKey`). */dataview?: {isCollection?: boolean;views?: {+ type?: string;+ groupRelationKey?: string;relations?: {key?: string;isVisible?: boolean;@@ -186,9 +191,17 @@ export interface ParsedColumn {multiplicity: Multiplicity;}-/** A collection's table schema and membership. `memberIds` are Anytype object ids (its `details.links`);- * `columns` are the visible, supported columns from its dataview, in order. */+/** The Trilium collection view types an Anytype dataview layout maps to. */+export type CollectionViewType = "table" | "list" | "grid" | "calendar" | "board";++/** A collection's view type, table schema and membership. `viewType` is the Trilium view its Anytype+ * layout maps to; `memberIds` are Anytype object ids (its `details.links`); `columns` are the visible,+ * supported columns from its dataview, in order. `groupByAttribute` is the Trilium attribute name the+ * view's `groupRelationKey` resolved to — driving `#board:groupBy` for a board or `#calendar:startDate`+ * for a calendar; absent when the view doesn't group by a (resolvable) relation. */export interface ParsedCollection {+ viewType: CollectionViewType;+ groupByAttribute?: string;memberIds: string[];columns: ParsedColumn[];}