Skip to content

Build your personal knowledge base with Trilium Notes

refactor(anytype): split importer into model + content modules

Elian Doranc159ca334e0a
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 08593d728b..1315a38a88 100644
--- a/packages/trilium-core/src/services/import/anytype/collection.spec.ts
+++ b/packages/trilium-core/src/services/import/anytype/collection.spec.ts
@@ -1,9 +1,8 @@
import { describe, expect, it } from "vitest";
import { buildColumnDefinition, toAttributeName } from "./collection.js";
-import type { RelationInfo } from "./collection.js";
import { isCollectionObject, isPage, parseObject } from "./importer.js";
-import type { AnytypeBlock, AnytypeMark, AnytypeSnapshot } from "./importer.js";
+import type { AnytypeBlock, AnytypeMark, AnytypeSnapshot, RelationInfo } from "./model.js";
/** Wraps blocks + details into the export's snapshot shape. Details accepts arbitrary relation-key entries
* (property values are keyed by the relation's hex `relationKey`). */
diff --git a/packages/trilium-core/src/services/import/anytype/collection.ts b/packages/trilium-core/src/services/import/anytype/collection.ts
index 6c7e023618..a0d8261b6c 100644
--- a/packages/trilium-core/src/services/import/anytype/collection.ts
+++ b/packages/trilium-core/src/services/import/anytype/collection.ts
@@ -20,7 +20,7 @@ import noteService from "../../notes.js";
import { escapeHtml } from "../../utils/index.js";
import { basename } from "../../utils/path.js";
import mimeService from "../mime.js";
-import type { AnytypeBlock, AnytypeDetails, AnytypeSnapshot, ParsedObject } from "./importer.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),
* so a file property's `source` matches the key its bytes were stored under. */
@@ -320,57 +320,12 @@ export function applyFiles(note: BNote, page: ParsedObject, fileObjects: Map<str
}
}
-// #region Model
-/** 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;
-}
-
-/** A file object resolved from the `filesObjects/` folder: the attachment title, MIME and the `files/` path
- * its raw bytes live at. */
-export interface FileObjectInfo {
- title: string;
- mime: string;
- source: string;
-}
-
-/** The Trilium label types a supported Anytype property maps to (email/phone reuse `url`). */
-export type PropertyLabelType = "text" | "number" | "url" | "date" | "datetime" | "boolean";
-
-/** Whether a property holds a single value or several (a multi-select). */
-export type Multiplicity = "single" | "multi";
-
/** How a relation's values import: its Trilium label type, value count, an optional clickable scheme
* (email/phone), and whether the value is option-backed (a select / multi-select, resolved via the options
- * map). */
+ * map). Internal to {@link propertyMapping}; the shared `Parsed*` shapes live in {@link ./model.js}. */
interface PropertyMapping {
labelType: PropertyLabelType;
multiplicity: Multiplicity;
scheme?: string;
optionBacked?: boolean;
}
-
-/** One custom property value on an object: the Trilium attribute name and its (already formatted) value. */
-export interface ParsedProperty {
- name: string;
- value: string;
-}
-
-/** One collection table column: its attribute name, Trilium label type, original (alias) name and value count. */
-export interface ParsedColumn {
- name: string;
- labelType: PropertyLabelType;
- alias: string;
- 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. */
-export interface ParsedCollection {
- memberIds: string[];
- columns: ParsedColumn[];
-}
-// #endregion
diff --git a/packages/trilium-core/src/services/import/anytype/content.spec.ts b/packages/trilium-core/src/services/import/anytype/content.spec.ts
new file mode 100644
index 0000000000..c9ad6e470a
--- /dev/null
+++ b/packages/trilium-core/src/services/import/anytype/content.spec.ts
@@ -0,0 +1,309 @@
+import { describe, expect, it } from "vitest";
+
+import { renderCodeBlock, renderInlineText } from "./content.js";
+import { parseObject } from "./importer.js";
+import type { AnytypeBlock, AnytypeMark, AnytypeSnapshot, LinkResolver } from "./model.js";
+
+/** Wraps blocks + details into the export's snapshot shape. */
+function snapshot(
+ blocks: AnytypeBlock[],
+ details: { id?: string; name?: string; layout?: number; resolvedLayout?: number; createdDate?: number; lastModifiedDate?: number; links?: string[]; [key: string]: unknown },
+ sbType = "Page"
+): AnytypeSnapshot {
+ return { sbType, snapshot: { data: { blocks, details } } };
+}
+
+/** An inline mark over a `[from, to)` range. */
+function mark(from: number, to: number, type: string, param?: string): AnytypeMark {
+ return { range: { from, to }, type, param };
+}
+
+/** A list item (Marked/Numbered/Checkbox) with optional nested children, checked state and marks. */
+function listItem(id: string, style: string, text: string, childrenIds: string[] = [], checked = false, marks: AnytypeMark[] = []): AnytypeBlock {
+ return { id, text: { text, style, marks: { marks }, checked }, childrenIds };
+}
+
+/** A page whose root's direct children are `rootChildIds`; `blocks` supplies those plus any nested blocks. */
+function listDoc(rootChildIds: string[], blocks: AnytypeBlock[]): AnytypeSnapshot {
+ return snapshot([{ id: "obj", childrenIds: rootChildIds }, ...blocks], { id: "obj", name: "List" });
+}
+
+describe("lists", () => {
+ it("groups consecutive Marked items into one <ul>", () => {
+ const doc = listDoc(["m1", "m2"], [listItem("m1", "Marked", "One"), listItem("m2", "Marked", "Two")]);
+ expect(parseObject(doc).content).toBe("<ul><li>One</li><li>Two</li></ul>");
+ });
+
+ it("renders Numbered items as an <ol>", () => {
+ const doc = listDoc(["n1", "n2"], [listItem("n1", "Numbered", "One"), listItem("n2", "Numbered", "Two")]);
+ expect(parseObject(doc).content).toBe("<ol><li>One</li><li>Two</li></ol>");
+ });
+
+ it("renders Checkbox items as a CKEditor todo-list carrying the checked state", () => {
+ const doc = listDoc(["c1", "c2"], [listItem("c1", "Checkbox", "Todo", [], false), listItem("c2", "Checkbox", "Done", [], true)]);
+ expect(parseObject(doc).content).toBe(
+ '<ul class="todo-list">' +
+ '<li><label class="todo-list__label"><input type="checkbox"disabled="disabled"><span class="todo-list__label__description">Todo</span></label></li>' +
+ '<li><label class="todo-list__label"><input type="checkbox"checked="checked" disabled="disabled"><span class="todo-list__label__description">Done</span></label></li>' +
+ "</ul>"
+ );
+ });
+
+ it("nests child list items inside the parent <li>", () => {
+ const doc = listDoc(
+ ["m1", "m2"],
+ [listItem("m1", "Marked", "One", ["m1a"]), listItem("m1a", "Marked", "One-A"), listItem("m2", "Marked", "Two")]
+ );
+ expect(parseObject(doc).content).toBe("<ul><li>One<ul><li>One-A</li></ul></li><li>Two</li></ul>");
+ });
+
+ it("starts a new list when the type changes or a non-list block interrupts", () => {
+ const doc = listDoc(
+ ["m1", "n1", "p1", "m2"],
+ [
+ listItem("m1", "Marked", "Bullet"),
+ listItem("n1", "Numbered", "Number"),
+ { id: "p1", text: { text: "Para", style: "Paragraph", marks: { marks: [] } } },
+ listItem("m2", "Marked", "Again")
+ ]
+ );
+ expect(parseObject(doc).content).toBe("<ul><li>Bullet</li></ul><ol><li>Number</li></ol><p>Para</p><ul><li>Again</li></ul>");
+ });
+
+ it("applies inline marks inside list items", () => {
+ const doc = listDoc(["m1"], [listItem("m1", "Marked", "Bold item", [], false, [mark(0, 4, "Bold")])]);
+ expect(parseObject(doc).content).toBe("<ul><li><strong>Bold</strong> item</li></ul>");
+ });
+});
+
+describe("quotes", () => {
+ it("converts a Quote (Anytype's Highlight block) to a blockquote", () => {
+ const doc = listDoc(["q1"], [{ id: "q1", text: { text: "A quote", style: "Quote", marks: { marks: [] } } }]);
+ expect(parseObject(doc).content).toBe("<blockquote><p>A quote</p></blockquote>");
+ });
+
+ it("applies inline marks and renders child blocks inside the blockquote", () => {
+ const doc = listDoc(
+ ["q1"],
+ [
+ { id: "q1", text: { text: "Bold quote", style: "Quote", marks: { marks: [mark(0, 4, "Bold")] } }, childrenIds: ["q1a"] },
+ { id: "q1a", text: { text: "More", style: "Paragraph", marks: { marks: [] } } }
+ ]
+ );
+ expect(parseObject(doc).content).toBe("<blockquote><p><strong>Bold</strong> quote</p><p>More</p></blockquote>");
+ });
+});
+
+describe("callouts", () => {
+ it("converts a default-icon callout to a tip admonition (icon implied, dropped)", () => {
+ const doc = listDoc(["c1"], [{ id: "c1", text: { text: "Heads up", style: "Callout", marks: { marks: [] }, iconEmoji: "" } }]);
+ expect(parseObject(doc).content).toBe('<aside class="admonition tip"><p>Heads up</p></aside>');
+ });
+
+ it("converts a custom-emoji callout to a note admonition, keeping the emoji at the start", () => {
+ const doc = listDoc(["c1"], [{ id: "c1", text: { text: "Foggy", style: "Callout", marks: { marks: [] }, iconEmoji: "πŸ˜Άβ€πŸŒ«οΈ" } }]);
+ expect(parseObject(doc).content).toBe('<aside class="admonition note"><p>πŸ˜Άβ€πŸŒ«οΈ Foggy</p></aside>');
+ });
+
+ it("applies inline marks in the callout body and renders child blocks inside the aside", () => {
+ const doc = listDoc(
+ ["c1"],
+ [
+ { id: "c1", text: { text: "Bold note", style: "Callout", marks: { marks: [mark(0, 4, "Bold")] }, iconEmoji: "" }, childrenIds: ["c1a"] },
+ { id: "c1a", text: { text: "More", style: "Paragraph", marks: { marks: [] } } }
+ ]
+ );
+ expect(parseObject(doc).content).toBe('<aside class="admonition tip"><p><strong>Bold</strong> note</p><p>More</p></aside>');
+ });
+});
+
+describe("dividers", () => {
+ it("converts Line and Dots divider blocks to <hr>", () => {
+ const doc = listDoc(
+ ["p1", "d1", "d2", "p2"],
+ [
+ { id: "p1", text: { text: "Above", style: "Paragraph", marks: { marks: [] } } },
+ { id: "d1", div: { style: "Line" } },
+ { id: "d2", div: { style: "Dots" } },
+ { id: "p2", text: { text: "Below", style: "Paragraph", marks: { marks: [] } } }
+ ]
+ );
+ expect(parseObject(doc).content).toBe("<p>Above</p><hr><hr><p>Below</p>");
+ });
+});
+
+describe("toggles", () => {
+ it("converts a Toggle to a collapsible block, nesting its children as the collapsed body", () => {
+ const doc = listDoc(
+ ["t1", "p1"],
+ [
+ { id: "t1", text: { text: "Summary", style: "Toggle", marks: { marks: [mark(0, 7, "Bold")] } }, childrenIds: ["t1a"] },
+ { id: "t1a", text: { text: "Hidden", style: "Paragraph", marks: { marks: [] } } },
+ { id: "p1", text: { text: "After", style: "Paragraph", marks: { marks: [] } } }
+ ]
+ );
+ expect(parseObject(doc).content).toBe(
+ '<details class="trilium-collapsible"><summary><strong>Summary</strong></summary><p>Hidden</p></details><p>After</p>'
+ );
+ });
+
+ it("converts toggle headings to normal headings (h2/h3/h4), keeping their content", () => {
+ const doc = listDoc(
+ ["th1", "th2", "th3"],
+ [
+ { id: "th1", text: { text: "T1", style: "ToggleHeader1", marks: { marks: [] } }, childrenIds: ["th1a"] },
+ { id: "th1a", text: { text: "Body", style: "Paragraph", marks: { marks: [] } } },
+ { id: "th2", text: { text: "T2", style: "ToggleHeader2", marks: { marks: [] } } },
+ { id: "th3", text: { text: "T3", style: "ToggleHeader3", marks: { marks: [] } } }
+ ]
+ );
+ expect(parseObject(doc).content).toBe("<h2>T1</h2><p>Body</p><h3>T2</h3><h4>T3</h4>");
+ });
+});
+
+describe("links", () => {
+ /** A block-level "link to object" pointing at the target object's id (CID). */
+ const linkBlock = (id: string, targetCid: string): AnytypeBlock => ({ id, link: { targetBlockId: targetCid, style: "Page" }, childrenIds: [] });
+
+ it("renders a link to an imported page as a reference link and records the resolved target", () => {
+ const doc = listDoc(["l1"], [linkBlock("l1", "target-cid")]);
+ const resolve: LinkResolver = (cid) => (cid === "target-cid" ? { noteId: "noteB", title: "Target Page" } : undefined);
+
+ const result = parseObject(doc, resolve);
+ expect(result.content).toBe('<p><a class="reference-link" href="#root/noteB">Target Page</a></p>');
+ // The resolved target id is surfaced so the importer can create the internalLink relation.
+ expect(result.linkTargetIds).toEqual(["noteB"]);
+ });
+
+ it("drops a link whose target wasn't imported (a set, or an object missing from the export)", () => {
+ const doc = listDoc(["l1"], [linkBlock("l1", "missing-cid")]);
+
+ const result = parseObject(doc, () => undefined);
+ expect(result.content).toBe("");
+ expect(result.linkTargetIds).toEqual([]);
+ });
+
+ it("escapes the target title and de-duplicates repeated links to the same page", () => {
+ const doc = listDoc(["l1", "l2"], [linkBlock("l1", "t"), linkBlock("l2", "t")]);
+ const resolve: LinkResolver = () => ({ noteId: "n", title: "A & B <x>" });
+
+ const result = parseObject(doc, resolve);
+ expect(result.content).toBe(
+ '<p><a class="reference-link" href="#root/n">A &amp; B &lt;x&gt;</a></p>' +
+ '<p><a class="reference-link" href="#root/n">A &amp; B &lt;x&gt;</a></p>'
+ );
+ // Both links point at the same note, so only one relation should be recorded.
+ expect(result.linkTargetIds).toEqual(["n"]);
+ });
+
+ it("ignores link blocks when no resolver is supplied (parsing a page in isolation)", () => {
+ const doc = listDoc(["p1", "l1"], [{ id: "p1", text: { text: "Body", style: "Paragraph", marks: { marks: [] } } }, linkBlock("l1", "t")]);
+
+ const result = parseObject(doc);
+ expect(result.content).toBe("<p>Body</p>");
+ expect(result.linkTargetIds).toEqual([]);
+ });
+});
+
+describe("renderInlineText", () => {
+ it("returns escaped plain text when there are no marks", () => {
+ expect(renderInlineText("a < b & c > d", [])).toBe("a &lt; b &amp; c &gt; d");
+ });
+
+ it("wraps a single mark's range, leaving the rest untouched", () => {
+ expect(renderInlineText("Bold text", [mark(0, 4, "Bold")])).toBe("<strong>Bold</strong> text");
+ });
+
+ it("maps the five supported marks to their tags ([from, to) range)", () => {
+ expect(renderInlineText("x", [mark(0, 1, "Bold")])).toBe("<strong>x</strong>");
+ expect(renderInlineText("x", [mark(0, 1, "Italic")])).toBe("<em>x</em>");
+ expect(renderInlineText("x", [mark(0, 1, "Strikethrough")])).toBe("<s>x</s>");
+ expect(renderInlineText("x", [mark(0, 1, "Underscored")])).toBe("<u>x</u>");
+ expect(renderInlineText("x", [mark(0, 1, "Keyboard")])).toBe("<code>x</code>");
+ });
+
+ it("renders the real 'Formatting test' line, nesting coincident bold+italic+underline", () => {
+ // Verbatim text and marks from the exported page (marks intentionally unsorted, as in the export).
+ const text = "Bold Italic Strikethrough Underline Bold Italic Underline";
+ const marks = [
+ mark(12, 25, "Strikethrough"),
+ mark(5, 11, "Italic"),
+ mark(36, 57, "Italic"),
+ mark(0, 4, "Bold"),
+ mark(36, 57, "Bold"),
+ mark(26, 35, "Underscored"),
+ mark(36, 57, "Underscored")
+ ];
+ expect(renderInlineText(text, marks)).toBe(
+ "<strong>Bold</strong> <em>Italic</em> <s>Strikethrough</s> <u>Underline</u> <strong><em><u>Bold Italic Underline</u></em></strong>"
+ );
+ });
+
+ it("splits partially overlapping marks into properly nested segments", () => {
+ // Bold [0,4) and Italic [2,6) overlap only on [2,4).
+ expect(renderInlineText("abcdef", [mark(0, 4, "Bold"), mark(2, 6, "Italic")])).toBe(
+ "<strong>ab</strong><strong><em>cd</em></strong><em>ef</em>"
+ );
+ });
+
+ it("maps TextColor to a colour span and a BackgroundColor highlight to a colour + background span", () => {
+ expect(renderInlineText("Red", [mark(0, 3, "TextColor", "red")])).toBe('<span style="color:#e2400c">Red</span>');
+ // A highlight with no explicit text colour gets Anytype's default dark text (#252525) so it stays
+ // readable on dark themes β€” otherwise the theme-default white text is invisible on the pale highlight.
+ expect(renderInlineText("Red", [mark(0, 3, "BackgroundColor", "red")])).toBe(
+ '<span style="color:#252525;background-color:#fcd1c3">Red</span>'
+ );
+ });
+
+ it("combines co-occurring text + background colour into one span, nested inside structural marks", () => {
+ // An explicit text colour wins over the highlight default, and both fold into a single span.
+ expect(renderInlineText("Red", [mark(0, 3, "TextColor", "red"), mark(0, 3, "BackgroundColor", "red")])).toBe(
+ '<span style="color:#e2400c;background-color:#fcd1c3">Red</span>'
+ );
+ // A structural mark stays outermost; the colour span nests inside it.
+ expect(renderInlineText("Red", [mark(0, 3, "Bold"), mark(0, 3, "TextColor", "red")])).toBe(
+ '<strong><span style="color:#e2400c">Red</span></strong>'
+ );
+ });
+
+ it("colours each word independently across a palette line (as the page exports it)", () => {
+ expect(renderInlineText("Grey Red", [mark(0, 4, "TextColor", "grey"), mark(5, 8, "TextColor", "red")])).toBe(
+ '<span style="color:#8c9ea5">Grey</span> <span style="color:#e2400c">Red</span>'
+ );
+ });
+
+ it("ignores an unknown colour name and genuinely unsupported mark types", () => {
+ expect(renderInlineText("x", [mark(0, 1, "TextColor", "chartreuse")])).toBe("x");
+ expect(renderInlineText("@bob", [mark(0, 4, "Mention", "someObjectId")])).toBe("@bob");
+ });
+
+ it("escapes HTML inside a marked range", () => {
+ expect(renderInlineText("a<b", [mark(0, 3, "Bold")])).toBe("<strong>a&lt;b</strong>");
+ });
+
+ it("clamps out-of-range offsets and drops empty / reversed ranges", () => {
+ expect(renderInlineText("hi", [mark(0, 100, "Bold")])).toBe("<strong>hi</strong>");
+ expect(renderInlineText("hi", [mark(1, 1, "Bold")])).toBe("hi");
+ expect(renderInlineText("hi", [mark(2, 0, "Bold")])).toBe("hi");
+ });
+});
+
+describe("renderCodeBlock", () => {
+ it("wraps code in <pre><code> with the resolved language class", () => {
+ // Anytype tags C-family code as PrismJS "clike"; Trilium has no such code, so it's aliased to C.
+ expect(renderCodeBlock("int x;", "clike")).toBe('<pre><code class="language-text-x-csrc">int x;</code></pre>');
+ });
+
+ it("resolves a language code that matches a Trilium markdown name directly", () => {
+ expect(renderCodeBlock("print(1)", "python")).toBe('<pre><code class="language-text-x-python">print(1)</code></pre>');
+ });
+
+ it("falls back to auto-detect for an unknown or missing language", () => {
+ expect(renderCodeBlock("plain", "nonsense")).toBe('<pre><code class="language-text-x-trilium-auto">plain</code></pre>');
+ expect(renderCodeBlock("plain", undefined)).toBe('<pre><code class="language-text-x-trilium-auto">plain</code></pre>');
+ });
+
+ it("escapes HTML and keeps quotes literal, preserving newlines and tabs", () => {
+ expect(renderCodeBlock('a<b & c>\n\t"q"', "clike")).toBe('<pre><code class="language-text-x-csrc">a&lt;b &amp; c&gt;\n\t"q"</code></pre>');
+ });
+});
diff --git a/packages/trilium-core/src/services/import/anytype/content.ts b/packages/trilium-core/src/services/import/anytype/content.ts
new file mode 100644
index 0000000000..5454694d6e
--- /dev/null
+++ b/packages/trilium-core/src/services/import/anytype/content.ts
@@ -0,0 +1,361 @@
+/**
+ * Anytype block tree β†’ Trilium/CKEditor HTML rendering.
+ *
+ * An object's `snapshot.data.blocks` is a flat list joined into a tree by each block's `childrenIds`.
+ * {@link extractContent} walks that tree from the root in document order and converts each block to HTML β€”
+ * headings (`<h2>`/`<h3>`/`<h4>`), bullet/numbered/task lists (grouped and nested), toggles, callouts,
+ * quotes, dividers and cross-page reference links β€” applying inline marks ({@link renderInlineText}) and
+ * rendering code blocks ({@link renderCodeBlock}). It returns the HTML plus the Trilium ids of every
+ * linked-to page (for the `internalLink` relations). The structure importer (importer.ts) owns object
+ * selection and the note tree; it calls into here. Mirrors the Notion importer's `converter.ts`.
+ */
+
+import { getMimeTypeFromMarkdownName, MIME_TYPE_AUTO, normalizeMimeTypeForCKEditor } from "@triliumnext/commons/src/lib/mime_type.js";
+
+import { escapeHtml } from "../../utils/index.js";
+import type { AnytypeBlock, AnytypeMark, LinkResolver } from "./model.js";
+
+/**
+ * Converts the page's block tree to HTML. A sequence of sibling blocks is rendered in document order, with
+ * consecutive list items of the same kind grouped into a single `<ul>`/`<ol>`/todo-list and a list item's
+ * children nested inside its `<li>`. Other blocks become a code block, a heading (`<h2>`/`<h3>`/`<h4>`), a
+ * cross-page reference link or a `<p>`, with inline marks applied. The `header` subtree
+ * (title/description/featuredRelations chrome) is skipped, as are the structural Title and Description
+ * styles wherever they appear. The de-duplicated Trilium ids of every linked-to page are returned
+ * alongside the HTML so the caller can record the `internalLink` relations.
+ */
+export function extractContent(blocks: AnytypeBlock[], rootId: string, resolveLink: LinkResolver): { html: string; linkTargetIds: string[] } {
+ const byId = new Map<string, AnytypeBlock>();
+ for (const block of blocks) {
+ byId.set(block.id, block);
+ }
+
+ const root = (rootId ? byId.get(rootId) : undefined) ?? blocks[0];
+ if (!root) {
+ return { html: "", linkTargetIds: [] };
+ }
+
+ const visited = new Set<string>();
+ const linkTargetIds = new Set<string>();
+
+ // Renders a run of sibling ids, grouping consecutive same-kind list items into one list. The header
+ // chrome and already-visited blocks (a node reachable twice) are skipped.
+ function renderSequence(ids: string[]): string {
+ const parts: string[] = [];
+ let i = 0;
+ while (i < ids.length) {
+ const id = ids[i];
+ const block = id === "header" || visited.has(id) ? undefined : byId.get(id);
+ if (!block) {
+ i++;
+ continue;
+ }
+
+ const kind = listKind(block);
+ if (kind) {
+ const run: AnytypeBlock[] = [];
+ while (i < ids.length) {
+ const candidate = visited.has(ids[i]) ? undefined : byId.get(ids[i]);
+ if (!candidate || listKind(candidate) !== kind) {
+ break;
+ }
+ visited.add(ids[i]);
+ run.push(candidate);
+ i++;
+ }
+ parts.push(renderList(kind, run));
+ } else {
+ visited.add(id);
+ parts.push(renderLeaf(block));
+ i++;
+ }
+ }
+ return parts.join("");
+ }
+
+ function renderList(kind: ListKind, items: AnytypeBlock[]): string {
+ const body = items.map((item) => renderItem(kind, item)).join("");
+ if (kind === "task") {
+ return `<ul class="todo-list">${body}</ul>`;
+ }
+ return kind === "ol" ? `<ol>${body}</ol>` : `<ul>${body}</ul>`;
+ }
+
+ function renderItem(kind: ListKind, item: AnytypeBlock): string {
+ const text = renderInlineText(item.text?.text ?? "", item.text?.marks?.marks ?? []);
+ const nested = renderSequence(item.childrenIds ?? []);
+ if (kind === "task") {
+ // CKEditor's read-only todo-list markup (matches the markdown importer's checkbox output).
+ const checkbox = `<input type="checkbox"${item.text?.checked ? 'checked="checked" ' : ""}disabled="disabled">`;
+ return `<li><label class="todo-list__label">${checkbox}<span class="todo-list__label__description">${text}</span></label>${nested}</li>`;
+ }
+ return `<li>${text}${nested}</li>`;
+ }
+
+ function renderLeaf(block: AnytypeBlock): string {
+ // A divider block (Line or Dots) β€” both become a horizontal rule.
+ if (block.div) {
+ return "<hr>";
+ }
+
+ // A block-level "link to object" β†’ a reference link to the imported target note. An unresolved
+ // target (a set, or an object missing from the export) is dropped, along with its relation.
+ if (block.link) {
+ const target = block.link.targetBlockId ? resolveLink(block.link.targetBlockId) : undefined;
+ if (!target) {
+ return "";
+ }
+ linkTargetIds.add(target.noteId);
+ return `<p><a class="reference-link" href="#root/${target.noteId}">${escapeHtml(target.title)}</a></p>`;
+ }
+
+ // Use the raw text (not trimmed) so mark offsets stay aligned; only the emptiness test trims.
+ const rawText = block.text?.text ?? "";
+ const style = block.text?.style;
+ const marks = block.text?.marks?.marks ?? [];
+
+ if (style === "Toggle") {
+ // A normal toggle becomes a Trilium collapsible block: its label is the summary, its children
+ // the collapsed body. (Toggle *headings* fall through to a normal heading below, via tagForStyle.)
+ return `<details class="trilium-collapsible"><summary>${renderInlineText(rawText, marks)}</summary>${renderSequence(block.childrenIds ?? [])}</details>`;
+ }
+
+ if (style === "Quote") {
+ // Anytype's Highlight block (internal style "Quote") β†’ a blockquote; its background tint is dropped.
+ const firstPara = rawText.trim() ? `<p>${renderInlineText(rawText, marks)}</p>` : "";
+ return `<blockquote>${firstPara}${renderSequence(block.childrenIds ?? [])}</blockquote>`;
+ }
+
+ if (style === "Callout") {
+ // A callout becomes a Trilium admonition. Following the Notion importer: the default icon (no
+ // custom emoji) maps to a "tip" with the icon dropped; any custom emoji maps to a "note" with
+ // the emoji kept at the start of the body (admonitions have no per-block icon).
+ const emoji = block.text?.iconEmoji ?? "";
+ const type = emoji ? "note" : "tip";
+ const lead = [emoji, renderInlineText(rawText, marks)].filter(Boolean).join(" ");
+ const firstPara = lead ? `<p>${lead}</p>` : "";
+ return `<aside class="admonition ${type}">${firstPara}${renderSequence(block.childrenIds ?? [])}</aside>`;
+ }
+
+ let html = "";
+ if (rawText.trim() && style !== "Title" && style !== "Description") {
+ if (style === "Code") {
+ // A code block is literal: no inline marks, and its language is preserved as the MIME.
+ html = renderCodeBlock(rawText, block.fields?.lang);
+ } else {
+ const tag = tagForStyle(style);
+ html = `<${tag}>${renderInlineText(rawText, marks)}</${tag}>`;
+ }
+ }
+ // A non-list block's children (e.g. a toggle heading's collapsed content) follow as flattened siblings.
+ return html + renderSequence(block.childrenIds ?? []);
+ }
+
+ // The root block is the page container and carries no text of its own β€” start from its children.
+ const html = renderSequence(root.childrenIds ?? []);
+ return { html, linkTargetIds: [...linkTargetIds] };
+}
+
+/** The kind of list a block belongs to (bullet/ordered/task), or null when it isn't a list item. */
+type ListKind = "ul" | "ol" | "task";
+function listKind(block: AnytypeBlock): ListKind | null {
+ switch (block.text?.style) {
+ case "Marked":
+ return "ul";
+ case "Numbered":
+ return "ol";
+ case "Checkbox":
+ return "task";
+ default:
+ return null;
+ }
+}
+
+/**
+ * Maps an Anytype text-block style to the Trilium tag it becomes. Anytype's three in-body heading levels
+ * (UI-labelled Title / Heading / Subheading) map to Trilium's top three heading levels: Trilium reserves
+ * `<h1>` for the note title, so its body headings start at `<h2>`. Toggle headings collapse to the same
+ * plain headings (their toggle nature is dropped). Every other non-list style (paragraphs, quotes,
+ * callouts, …) is flattened to a paragraph for now.
+ */
+function tagForStyle(style: string | undefined): string {
+ switch (style) {
+ case "Header1":
+ case "ToggleHeader1":
+ return "h2";
+ case "Header2":
+ case "ToggleHeader2":
+ return "h3";
+ case "Header3":
+ case "ToggleHeader3":
+ return "h4";
+ default:
+ return "p";
+ }
+}
+
+// #region Inline marks
+const MARK_TAGS: Record<string, string> = {
+ Bold: "strong",
+ Italic: "em",
+ Underscored: "u",
+ Strikethrough: "s",
+ Keyboard: "code"
+};
+
+// Anytype's system colour palette (`--color-tag-*` / `--color-bg-tag-*`); marks carry the name in `param`.
+// Backgrounds are already opaque, so no flatten-over-white step is needed (unlike Notion's translucent set).
+const TEXT_COLORS: Record<string, string> = {
+ grey: "#8c9ea5", yellow: "#b2a616", orange: "#d3720d", red: "#e2400c", pink: "#ca1b8e",
+ purple: "#9e30c4", blue: "#3e58eb", ice: "#1c8bca", teal: "#0caaa3", lime: "#64b90f"
+};
+const BG_COLORS: Record<string, string> = {
+ grey: "#e3e3e3", yellow: "#f4eb91", orange: "#fcdc9c", red: "#fcd1c3", pink: "#f8c2e5",
+ purple: "#e8d0f1", blue: "#cbd2fa", ice: "#b2dff9", teal: "#a9ebe6", lime: "#c5efa3"
+};
+
+// Anytype's default (light-theme) text colour. A highlight (background) without an explicit text colour is
+// paired with this so the text stays readable on the pale highlight regardless of the Trilium theme β€”
+// otherwise a dark theme's default white text would be invisible on it.
+const DEFAULT_TEXT_COLOR = "#252525";
+
+// Outer-to-inner nesting order for the structural marks that cover the same segment β€” fixed so output is
+// deterministic. Colours are handled separately (folded into a single inner span).
+const MARK_ORDER = ["Bold", "Italic", "Underscored", "Strikethrough", "Keyboard"];
+
+interface AppliedMark {
+ type: string;
+ param: string;
+ from: number;
+ to: number;
+}
+
+/**
+ * Converts a text block's inline marks into HTML. Anytype encodes formatting as a flat list of marks, each
+ * a `[from, to)` character range (UTF-16 offsets) with a type β€” and marks may overlap freely. We turn that
+ * into valid nested HTML by splitting the text at every mark boundary, so no segment straddles a mark edge,
+ * then wrapping each segment in the tags whose range fully covers it. Adjacent segments always differ in
+ * their active set (a boundary is only created where a mark starts or ends), so output is clean without a
+ * merge pass. Links, mentions and emoji are ignored, leaving their text as plain (escaped) content.
+ */
+export function renderInlineText(text: string, marks: AnytypeMark[]): string {
+ const length = text.length;
+
+ // Keep only marks we render (known structural kind, or a known colour name), with offsets clamped to
+ // the text and empty/reversed ranges dropped.
+ const applicable: AppliedMark[] = [];
+ for (const mark of marks) {
+ const param = mark.param ?? "";
+ if (mark.type === undefined || !isRenderable(mark.type, param)) {
+ continue;
+ }
+ const from = Math.max(0, Math.min(length, mark.range?.from ?? 0));
+ const to = Math.max(0, Math.min(length, mark.range?.to ?? 0));
+ if (from < to) {
+ applicable.push({ type: mark.type, param, from, to });
+ }
+ }
+
+ if (applicable.length === 0) {
+ return escapeHtml(text);
+ }
+
+ // Split at every mark boundary so each segment is uniformly covered (or not) by each mark.
+ const boundaries = new Set<number>([0, length]);
+ for (const mark of applicable) {
+ boundaries.add(mark.from);
+ boundaries.add(mark.to);
+ }
+ const points = [...boundaries].sort((a, b) => a - b);
+
+ let html = "";
+ for (let i = 0; i < points.length - 1; i++) {
+ const start = points[i];
+ const end = points[i + 1];
+ const covering = applicable.filter((mark) => mark.from <= start && mark.to >= end);
+ html += wrapSegment(escapeHtml(text.slice(start, end)), covering);
+ }
+
+ return html;
+}
+
+/** Whether a mark is rendered: a known structural kind, or a colour with a known palette name. */
+function isRenderable(type: string, param: string): boolean {
+ if (type in MARK_TAGS) {
+ return true;
+ }
+ if (type === "TextColor") {
+ return param in TEXT_COLORS;
+ }
+ if (type === "BackgroundColor") {
+ return param in BG_COLORS;
+ }
+ return false;
+}
+
+/**
+ * Wraps one segment in the tags of the marks that fully cover it. Text and background colour fold into a
+ * single innermost `<span>` (a highlight without a text colour gets the default dark text); the structural
+ * marks then nest around it, Bold outermost per {@link MARK_ORDER}.
+ */
+function wrapSegment(segment: string, covering: AppliedMark[]): string {
+ const textColor = paletteValue(covering, "TextColor", TEXT_COLORS);
+ const bgColor = paletteValue(covering, "BackgroundColor", BG_COLORS);
+
+ const styleParts: string[] = [];
+ if (textColor) {
+ styleParts.push(`color:${textColor}`);
+ } else if (bgColor) {
+ styleParts.push(`color:${DEFAULT_TEXT_COLOR}`);
+ }
+ if (bgColor) {
+ styleParts.push(`background-color:${bgColor}`);
+ }
+ let html = styleParts.length > 0 ? `<span style="${styleParts.join(";")}">${segment}</span>` : segment;
+
+ const structural = covering.filter((mark) => mark.type in MARK_TAGS).sort((a, b) => MARK_ORDER.indexOf(a.type) - MARK_ORDER.indexOf(b.type));
+ for (let i = structural.length - 1; i >= 0; i--) {
+ const tag = MARK_TAGS[structural[i].type];
+ html = `<${tag}>${html}</${tag}>`;
+ }
+
+ return html;
+}
+
+/** The palette value for the segment's mark of the given colour type, or undefined if none covers it. */
+function paletteValue(covering: AppliedMark[], type: string, palette: Record<string, string>): string | undefined {
+ const mark = covering.find((candidate) => candidate.type === type);
+ return mark ? palette[mark.param] : undefined;
+}
+// #endregion
+
+// #region Code blocks
+// PrismJS language ids Anytype uses that don't line up with a Trilium markdown language code. Most ids
+// (javascript, python, go, rust, …) match directly; only the mismatches need listing here. `clike` is
+// PrismJS's generic C-family base, mapped to plain C as the closest concrete language.
+const LANGUAGE_ALIASES: Record<string, string> = {
+ clike: "c"
+};
+
+/**
+ * Renders an Anytype `Code`-style block as a Trilium/CKEditor code block. Anytype tags the block with a
+ * PrismJS language id in `fields.lang`; we map that to a Trilium MIME and emit it as the CKEditor
+ * code-block language class (`language-<normalized-mime>`), the same shape the markdown importer produces.
+ * Quotes are left literal (matching the markdown importer), and an unknown language falls back to
+ * auto-detect.
+ */
+export function renderCodeBlock(text: string, lang: string | undefined): string {
+ return `<pre><code class="language-${codeLanguage(lang)}">${escapeHtml(text).replace(/&quot;/g, '"')}</code></pre>`;
+}
+
+/** The CKEditor code-block language class value for an Anytype language id, or auto-detect when unknown. */
+function codeLanguage(lang: string | undefined): string {
+ if (lang) {
+ const mimeDefinition = getMimeTypeFromMarkdownName(LANGUAGE_ALIASES[lang] ?? lang);
+ if (mimeDefinition) {
+ return normalizeMimeTypeForCKEditor(mimeDefinition.mime);
+ }
+ }
+ return MIME_TYPE_AUTO;
+}
+// #endregion
diff --git a/packages/trilium-core/src/services/import/anytype/importer.spec.ts b/packages/trilium-core/src/services/import/anytype/importer.spec.ts
index 2a01c794d6..eee09c0d9f 100644
--- a/packages/trilium-core/src/services/import/anytype/importer.spec.ts
+++ b/packages/trilium-core/src/services/import/anytype/importer.spec.ts
@@ -1,7 +1,7 @@
import { describe, expect, it } from "vitest";
-import { anytypeDate, isPage, parseObject, renderCodeBlock, renderInlineText } from "./importer.js";
-import type { AnytypeBlock, AnytypeMark, AnytypeSnapshot, LinkResolver } from "./importer.js";
+import { anytypeDate, isPage, parseObject } from "./importer.js";
+import type { AnytypeBlock, AnytypeMark, AnytypeSnapshot } from "./model.js";
/** Wraps blocks + details into the export's snapshot shape. Details accepts arbitrary relation-key entries
* (property values are keyed by the relation's hex `relationKey`). */
@@ -36,16 +36,6 @@ function mark(from: number, to: number, type: string, param?: string): AnytypeMa
return { range: { from, to }, type, param };
}
-/** A list item (Marked/Numbered/Checkbox) with optional nested children, checked state and marks. */
-function listItem(id: string, style: string, text: string, childrenIds: string[] = [], checked = false, marks: AnytypeMark[] = []): AnytypeBlock {
- return { id, text: { text, style, marks: { marks }, checked }, childrenIds };
-}
-
-/** A page whose root's direct children are `rootChildIds`; `blocks` supplies those plus any nested blocks. */
-function listDoc(rootChildIds: string[], blocks: AnytypeBlock[]): AnytypeSnapshot {
- return snapshot([{ id: "obj", childrenIds: rootChildIds }, ...blocks], { id: "obj", name: "List" });
-}
-
describe("isPage", () => {
it("accepts a basic-layout Page and rejects sets and system objects", () => {
expect(isPage(page("A page", []))).toBe(true);
@@ -121,183 +111,6 @@ describe("parseObject", () => {
});
});
-describe("lists", () => {
- it("groups consecutive Marked items into one <ul>", () => {
- const doc = listDoc(["m1", "m2"], [listItem("m1", "Marked", "One"), listItem("m2", "Marked", "Two")]);
- expect(parseObject(doc).content).toBe("<ul><li>One</li><li>Two</li></ul>");
- });
-
- it("renders Numbered items as an <ol>", () => {
- const doc = listDoc(["n1", "n2"], [listItem("n1", "Numbered", "One"), listItem("n2", "Numbered", "Two")]);
- expect(parseObject(doc).content).toBe("<ol><li>One</li><li>Two</li></ol>");
- });
-
- it("renders Checkbox items as a CKEditor todo-list carrying the checked state", () => {
- const doc = listDoc(["c1", "c2"], [listItem("c1", "Checkbox", "Todo", [], false), listItem("c2", "Checkbox", "Done", [], true)]);
- expect(parseObject(doc).content).toBe(
- '<ul class="todo-list">' +
- '<li><label class="todo-list__label"><input type="checkbox"disabled="disabled"><span class="todo-list__label__description">Todo</span></label></li>' +
- '<li><label class="todo-list__label"><input type="checkbox"checked="checked" disabled="disabled"><span class="todo-list__label__description">Done</span></label></li>' +
- "</ul>"
- );
- });
-
- it("nests child list items inside the parent <li>", () => {
- const doc = listDoc(
- ["m1", "m2"],
- [listItem("m1", "Marked", "One", ["m1a"]), listItem("m1a", "Marked", "One-A"), listItem("m2", "Marked", "Two")]
- );
- expect(parseObject(doc).content).toBe("<ul><li>One<ul><li>One-A</li></ul></li><li>Two</li></ul>");
- });
-
- it("starts a new list when the type changes or a non-list block interrupts", () => {
- const doc = listDoc(
- ["m1", "n1", "p1", "m2"],
- [
- listItem("m1", "Marked", "Bullet"),
- listItem("n1", "Numbered", "Number"),
- { id: "p1", text: { text: "Para", style: "Paragraph", marks: { marks: [] } } },
- listItem("m2", "Marked", "Again")
- ]
- );
- expect(parseObject(doc).content).toBe("<ul><li>Bullet</li></ul><ol><li>Number</li></ol><p>Para</p><ul><li>Again</li></ul>");
- });
-
- it("applies inline marks inside list items", () => {
- const doc = listDoc(["m1"], [listItem("m1", "Marked", "Bold item", [], false, [mark(0, 4, "Bold")])]);
- expect(parseObject(doc).content).toBe("<ul><li><strong>Bold</strong> item</li></ul>");
- });
-});
-
-describe("quotes", () => {
- it("converts a Quote (Anytype's Highlight block) to a blockquote", () => {
- const doc = listDoc(["q1"], [{ id: "q1", text: { text: "A quote", style: "Quote", marks: { marks: [] } } }]);
- expect(parseObject(doc).content).toBe("<blockquote><p>A quote</p></blockquote>");
- });
-
- it("applies inline marks and renders child blocks inside the blockquote", () => {
- const doc = listDoc(
- ["q1"],
- [
- { id: "q1", text: { text: "Bold quote", style: "Quote", marks: { marks: [mark(0, 4, "Bold")] } }, childrenIds: ["q1a"] },
- { id: "q1a", text: { text: "More", style: "Paragraph", marks: { marks: [] } } }
- ]
- );
- expect(parseObject(doc).content).toBe("<blockquote><p><strong>Bold</strong> quote</p><p>More</p></blockquote>");
- });
-});
-
-describe("callouts", () => {
- it("converts a default-icon callout to a tip admonition (icon implied, dropped)", () => {
- const doc = listDoc(["c1"], [{ id: "c1", text: { text: "Heads up", style: "Callout", marks: { marks: [] }, iconEmoji: "" } }]);
- expect(parseObject(doc).content).toBe('<aside class="admonition tip"><p>Heads up</p></aside>');
- });
-
- it("converts a custom-emoji callout to a note admonition, keeping the emoji at the start", () => {
- const doc = listDoc(["c1"], [{ id: "c1", text: { text: "Foggy", style: "Callout", marks: { marks: [] }, iconEmoji: "πŸ˜Άβ€πŸŒ«οΈ" } }]);
- expect(parseObject(doc).content).toBe('<aside class="admonition note"><p>πŸ˜Άβ€πŸŒ«οΈ Foggy</p></aside>');
- });
-
- it("applies inline marks in the callout body and renders child blocks inside the aside", () => {
- const doc = listDoc(
- ["c1"],
- [
- { id: "c1", text: { text: "Bold note", style: "Callout", marks: { marks: [mark(0, 4, "Bold")] }, iconEmoji: "" }, childrenIds: ["c1a"] },
- { id: "c1a", text: { text: "More", style: "Paragraph", marks: { marks: [] } } }
- ]
- );
- expect(parseObject(doc).content).toBe('<aside class="admonition tip"><p><strong>Bold</strong> note</p><p>More</p></aside>');
- });
-});
-
-describe("dividers", () => {
- it("converts Line and Dots divider blocks to <hr>", () => {
- const doc = listDoc(
- ["p1", "d1", "d2", "p2"],
- [
- { id: "p1", text: { text: "Above", style: "Paragraph", marks: { marks: [] } } },
- { id: "d1", div: { style: "Line" } },
- { id: "d2", div: { style: "Dots" } },
- { id: "p2", text: { text: "Below", style: "Paragraph", marks: { marks: [] } } }
- ]
- );
- expect(parseObject(doc).content).toBe("<p>Above</p><hr><hr><p>Below</p>");
- });
-});
-
-describe("toggles", () => {
- it("converts a Toggle to a collapsible block, nesting its children as the collapsed body", () => {
- const doc = listDoc(
- ["t1", "p1"],
- [
- { id: "t1", text: { text: "Summary", style: "Toggle", marks: { marks: [mark(0, 7, "Bold")] } }, childrenIds: ["t1a"] },
- { id: "t1a", text: { text: "Hidden", style: "Paragraph", marks: { marks: [] } } },
- { id: "p1", text: { text: "After", style: "Paragraph", marks: { marks: [] } } }
- ]
- );
- expect(parseObject(doc).content).toBe(
- '<details class="trilium-collapsible"><summary><strong>Summary</strong></summary><p>Hidden</p></details><p>After</p>'
- );
- });
-
- it("converts toggle headings to normal headings (h2/h3/h4), keeping their content", () => {
- const doc = listDoc(
- ["th1", "th2", "th3"],
- [
- { id: "th1", text: { text: "T1", style: "ToggleHeader1", marks: { marks: [] } }, childrenIds: ["th1a"] },
- { id: "th1a", text: { text: "Body", style: "Paragraph", marks: { marks: [] } } },
- { id: "th2", text: { text: "T2", style: "ToggleHeader2", marks: { marks: [] } } },
- { id: "th3", text: { text: "T3", style: "ToggleHeader3", marks: { marks: [] } } }
- ]
- );
- expect(parseObject(doc).content).toBe("<h2>T1</h2><p>Body</p><h3>T2</h3><h4>T3</h4>");
- });
-});
-
-describe("links", () => {
- /** A block-level "link to object" pointing at the target object's id (CID). */
- const linkBlock = (id: string, targetCid: string): AnytypeBlock => ({ id, link: { targetBlockId: targetCid, style: "Page" }, childrenIds: [] });
-
- it("renders a link to an imported page as a reference link and records the resolved target", () => {
- const doc = listDoc(["l1"], [linkBlock("l1", "target-cid")]);
- const resolve: LinkResolver = (cid) => (cid === "target-cid" ? { noteId: "noteB", title: "Target Page" } : undefined);
-
- const result = parseObject(doc, resolve);
- expect(result.content).toBe('<p><a class="reference-link" href="#root/noteB">Target Page</a></p>');
- // The resolved target id is surfaced so the importer can create the internalLink relation.
- expect(result.linkTargetIds).toEqual(["noteB"]);
- });
-
- it("drops a link whose target wasn't imported (a set, or an object missing from the export)", () => {
- const doc = listDoc(["l1"], [linkBlock("l1", "missing-cid")]);
-
- const result = parseObject(doc, () => undefined);
- expect(result.content).toBe("");
- expect(result.linkTargetIds).toEqual([]);
- });
-
- it("escapes the target title and de-duplicates repeated links to the same page", () => {
- const doc = listDoc(["l1", "l2"], [linkBlock("l1", "t"), linkBlock("l2", "t")]);
- const resolve: LinkResolver = () => ({ noteId: "n", title: "A & B <x>" });
-
- const result = parseObject(doc, resolve);
- expect(result.content).toBe(
- '<p><a class="reference-link" href="#root/n">A &amp; B &lt;x&gt;</a></p>' +
- '<p><a class="reference-link" href="#root/n">A &amp; B &lt;x&gt;</a></p>'
- );
- // Both links point at the same note, so only one relation should be recorded.
- expect(result.linkTargetIds).toEqual(["n"]);
- });
-
- it("ignores link blocks when no resolver is supplied (parsing a page in isolation)", () => {
- const doc = listDoc(["p1", "l1"], [{ id: "p1", text: { text: "Body", style: "Paragraph", marks: { marks: [] } } }, linkBlock("l1", "t")]);
-
- const result = parseObject(doc);
- expect(result.content).toBe("<p>Body</p>");
- expect(result.linkTargetIds).toEqual([]);
- });
-});
-
describe("dates", () => {
it("converts an Anytype detail timestamp (Unix seconds) to a Trilium UTC datetime string", () => {
// Verbatim createdDate from the "Article 6 Electronic Contracts" page.
@@ -324,106 +137,3 @@ describe("dates", () => {
expect(result.dateModified).toBeUndefined();
});
});
-
-describe("renderInlineText", () => {
- it("returns escaped plain text when there are no marks", () => {
- expect(renderInlineText("a < b & c > d", [])).toBe("a &lt; b &amp; c &gt; d");
- });
-
- it("wraps a single mark's range, leaving the rest untouched", () => {
- expect(renderInlineText("Bold text", [mark(0, 4, "Bold")])).toBe("<strong>Bold</strong> text");
- });
-
- it("maps the five supported marks to their tags ([from, to) range)", () => {
- expect(renderInlineText("x", [mark(0, 1, "Bold")])).toBe("<strong>x</strong>");
- expect(renderInlineText("x", [mark(0, 1, "Italic")])).toBe("<em>x</em>");
- expect(renderInlineText("x", [mark(0, 1, "Strikethrough")])).toBe("<s>x</s>");
- expect(renderInlineText("x", [mark(0, 1, "Underscored")])).toBe("<u>x</u>");
- expect(renderInlineText("x", [mark(0, 1, "Keyboard")])).toBe("<code>x</code>");
- });
-
- it("renders the real 'Formatting test' line, nesting coincident bold+italic+underline", () => {
- // Verbatim text and marks from the exported page (marks intentionally unsorted, as in the export).
- const text = "Bold Italic Strikethrough Underline Bold Italic Underline";
- const marks = [
- mark(12, 25, "Strikethrough"),
- mark(5, 11, "Italic"),
- mark(36, 57, "Italic"),
- mark(0, 4, "Bold"),
- mark(36, 57, "Bold"),
- mark(26, 35, "Underscored"),
- mark(36, 57, "Underscored")
- ];
- expect(renderInlineText(text, marks)).toBe(
- "<strong>Bold</strong> <em>Italic</em> <s>Strikethrough</s> <u>Underline</u> <strong><em><u>Bold Italic Underline</u></em></strong>"
- );
- });
-
- it("splits partially overlapping marks into properly nested segments", () => {
- // Bold [0,4) and Italic [2,6) overlap only on [2,4).
- expect(renderInlineText("abcdef", [mark(0, 4, "Bold"), mark(2, 6, "Italic")])).toBe(
- "<strong>ab</strong><strong><em>cd</em></strong><em>ef</em>"
- );
- });
-
- it("maps TextColor to a colour span and a BackgroundColor highlight to a colour + background span", () => {
- expect(renderInlineText("Red", [mark(0, 3, "TextColor", "red")])).toBe('<span style="color:#e2400c">Red</span>');
- // A highlight with no explicit text colour gets Anytype's default dark text (#252525) so it stays
- // readable on dark themes β€” otherwise the theme-default white text is invisible on the pale highlight.
- expect(renderInlineText("Red", [mark(0, 3, "BackgroundColor", "red")])).toBe(
- '<span style="color:#252525;background-color:#fcd1c3">Red</span>'
- );
- });
-
- it("combines co-occurring text + background colour into one span, nested inside structural marks", () => {
- // An explicit text colour wins over the highlight default, and both fold into a single span.
- expect(renderInlineText("Red", [mark(0, 3, "TextColor", "red"), mark(0, 3, "BackgroundColor", "red")])).toBe(
- '<span style="color:#e2400c;background-color:#fcd1c3">Red</span>'
- );
- // A structural mark stays outermost; the colour span nests inside it.
- expect(renderInlineText("Red", [mark(0, 3, "Bold"), mark(0, 3, "TextColor", "red")])).toBe(
- '<strong><span style="color:#e2400c">Red</span></strong>'
- );
- });
-
- it("colours each word independently across a palette line (as the page exports it)", () => {
- expect(renderInlineText("Grey Red", [mark(0, 4, "TextColor", "grey"), mark(5, 8, "TextColor", "red")])).toBe(
- '<span style="color:#8c9ea5">Grey</span> <span style="color:#e2400c">Red</span>'
- );
- });
-
- it("ignores an unknown colour name and genuinely unsupported mark types", () => {
- expect(renderInlineText("x", [mark(0, 1, "TextColor", "chartreuse")])).toBe("x");
- expect(renderInlineText("@bob", [mark(0, 4, "Mention", "someObjectId")])).toBe("@bob");
- });
-
- it("escapes HTML inside a marked range", () => {
- expect(renderInlineText("a<b", [mark(0, 3, "Bold")])).toBe("<strong>a&lt;b</strong>");
- });
-
- it("clamps out-of-range offsets and drops empty / reversed ranges", () => {
- expect(renderInlineText("hi", [mark(0, 100, "Bold")])).toBe("<strong>hi</strong>");
- expect(renderInlineText("hi", [mark(1, 1, "Bold")])).toBe("hi");
- expect(renderInlineText("hi", [mark(2, 0, "Bold")])).toBe("hi");
- });
-});
-
-describe("renderCodeBlock", () => {
- it("wraps code in <pre><code> with the resolved language class", () => {
- // Anytype tags C-family code as PrismJS "clike"; Trilium has no such code, so it's aliased to C.
- expect(renderCodeBlock("int x;", "clike")).toBe('<pre><code class="language-text-x-csrc">int x;</code></pre>');
- });
-
- it("resolves a language code that matches a Trilium markdown name directly", () => {
- expect(renderCodeBlock("print(1)", "python")).toBe('<pre><code class="language-text-x-python">print(1)</code></pre>');
- });
-
- it("falls back to auto-detect for an unknown or missing language", () => {
- expect(renderCodeBlock("plain", "nonsense")).toBe('<pre><code class="language-text-x-trilium-auto">plain</code></pre>');
- expect(renderCodeBlock("plain", undefined)).toBe('<pre><code class="language-text-x-trilium-auto">plain</code></pre>');
- });
-
- it("escapes HTML and keeps quotes literal, preserving newlines and tabs", () => {
- expect(renderCodeBlock('a<b & c>\n\t"q"', "clike")).toBe('<pre><code class="language-text-x-csrc">a&lt;b &amp; c&gt;\n\t"q"</code></pre>');
- });
-});
diff --git a/packages/trilium-core/src/services/import/anytype/importer.ts b/packages/trilium-core/src/services/import/anytype/importer.ts
index f79df39a6a..9e64375101 100644
--- a/packages/trilium-core/src/services/import/anytype/importer.ts
+++ b/packages/trilium-core/src/services/import/anytype/importer.ts
@@ -21,7 +21,6 @@
* this service just builds the tree and returns its root note, like the zip/notion importers.
*/
-import { getMimeTypeFromMarkdownName, MIME_TYPE_AUTO, normalizeMimeTypeForCKEditor } from "@triliumnext/commons/src/lib/mime_type.js";
import { t } from "i18next";
import type BNote from "../../../becca/entities/bnote.js";
@@ -30,10 +29,11 @@ import noteService from "../../notes.js";
import protectedSessionService from "../../protected_session.js";
import type TaskContext from "../../task_context.js";
import date_utils from "../../utils/date.js";
-import { escapeHtml, newEntityId } from "../../utils/index.js";
+import { newEntityId } from "../../utils/index.js";
import { getZipProvider } from "../../zip_provider.js";
import { applyFiles, applyProperties, buildFileObjectMap, buildOptionMap, buildRelationMap, createCollectionNote, normalizePath, parseCollection, parseFiles, parseProperties } from "./collection.js";
-import type { FileObjectInfo, ParsedCollection, ParsedProperty, RelationInfo } from "./collection.js";
+import { extractContent } from "./content.js";
+import type { AnytypeDetails, AnytypeSnapshot, FileObjectInfo, LinkResolver, ParsedObject, RelationInfo, ResolvedLink } from "./model.js";
async function importAnytype(taskContext: TaskContext<"importNotes">, fileBuffer: Uint8Array, importRootNote: BNote): Promise<BNote> {
const { objects, relations, options, fileObjects, files } = await parseZip(fileBuffer);
@@ -206,351 +206,6 @@ export function anytypeDate(seconds: number | undefined): string | undefined {
return date_utils.utcDateTimeStr(new Date(seconds * 1000));
}
-/**
- * Converts the page's block tree to HTML. A sequence of sibling blocks is rendered in document order, with
- * consecutive list items of the same kind grouped into a single `<ul>`/`<ol>`/todo-list and a list item's
- * children nested inside its `<li>`. Other blocks become a code block, a heading (`<h2>`/`<h3>`/`<h4>`), a
- * cross-page reference link or a `<p>`, with inline marks applied. The `header` subtree
- * (title/description/featuredRelations chrome) is skipped, as are the structural Title and Description
- * styles wherever they appear. The de-duplicated Trilium ids of every linked-to page are returned
- * alongside the HTML so the caller can record the `internalLink` relations.
- */
-function extractContent(blocks: AnytypeBlock[], rootId: string, resolveLink: LinkResolver): { html: string; linkTargetIds: string[] } {
- const byId = new Map<string, AnytypeBlock>();
- for (const block of blocks) {
- byId.set(block.id, block);
- }
-
- const root = (rootId ? byId.get(rootId) : undefined) ?? blocks[0];
- if (!root) {
- return { html: "", linkTargetIds: [] };
- }
-
- const visited = new Set<string>();
- const linkTargetIds = new Set<string>();
-
- // Renders a run of sibling ids, grouping consecutive same-kind list items into one list. The header
- // chrome and already-visited blocks (a node reachable twice) are skipped.
- function renderSequence(ids: string[]): string {
- const parts: string[] = [];
- let i = 0;
- while (i < ids.length) {
- const id = ids[i];
- const block = id === "header" || visited.has(id) ? undefined : byId.get(id);
- if (!block) {
- i++;
- continue;
- }
-
- const kind = listKind(block);
- if (kind) {
- const run: AnytypeBlock[] = [];
- while (i < ids.length) {
- const candidate = visited.has(ids[i]) ? undefined : byId.get(ids[i]);
- if (!candidate || listKind(candidate) !== kind) {
- break;
- }
- visited.add(ids[i]);
- run.push(candidate);
- i++;
- }
- parts.push(renderList(kind, run));
- } else {
- visited.add(id);
- parts.push(renderLeaf(block));
- i++;
- }
- }
- return parts.join("");
- }
-
- function renderList(kind: ListKind, items: AnytypeBlock[]): string {
- const body = items.map((item) => renderItem(kind, item)).join("");
- if (kind === "task") {
- return `<ul class="todo-list">${body}</ul>`;
- }
- return kind === "ol" ? `<ol>${body}</ol>` : `<ul>${body}</ul>`;
- }
-
- function renderItem(kind: ListKind, item: AnytypeBlock): string {
- const text = renderInlineText(item.text?.text ?? "", item.text?.marks?.marks ?? []);
- const nested = renderSequence(item.childrenIds ?? []);
- if (kind === "task") {
- // CKEditor's read-only todo-list markup (matches the markdown importer's checkbox output).
- const checkbox = `<input type="checkbox"${item.text?.checked ? 'checked="checked" ' : ""}disabled="disabled">`;
- return `<li><label class="todo-list__label">${checkbox}<span class="todo-list__label__description">${text}</span></label>${nested}</li>`;
- }
- return `<li>${text}${nested}</li>`;
- }
-
- function renderLeaf(block: AnytypeBlock): string {
- // A divider block (Line or Dots) β€” both become a horizontal rule.
- if (block.div) {
- return "<hr>";
- }
-
- // A block-level "link to object" β†’ a reference link to the imported target note. An unresolved
- // target (a set, or an object missing from the export) is dropped, along with its relation.
- if (block.link) {
- const target = block.link.targetBlockId ? resolveLink(block.link.targetBlockId) : undefined;
- if (!target) {
- return "";
- }
- linkTargetIds.add(target.noteId);
- return `<p><a class="reference-link" href="#root/${target.noteId}">${escapeHtml(target.title)}</a></p>`;
- }
-
- // Use the raw text (not trimmed) so mark offsets stay aligned; only the emptiness test trims.
- const rawText = block.text?.text ?? "";
- const style = block.text?.style;
- const marks = block.text?.marks?.marks ?? [];
-
- if (style === "Toggle") {
- // A normal toggle becomes a Trilium collapsible block: its label is the summary, its children
- // the collapsed body. (Toggle *headings* fall through to a normal heading below, via tagForStyle.)
- return `<details class="trilium-collapsible"><summary>${renderInlineText(rawText, marks)}</summary>${renderSequence(block.childrenIds ?? [])}</details>`;
- }
-
- if (style === "Quote") {
- // Anytype's Highlight block (internal style "Quote") β†’ a blockquote; its background tint is dropped.
- const firstPara = rawText.trim() ? `<p>${renderInlineText(rawText, marks)}</p>` : "";
- return `<blockquote>${firstPara}${renderSequence(block.childrenIds ?? [])}</blockquote>`;
- }
-
- if (style === "Callout") {
- // A callout becomes a Trilium admonition. Following the Notion importer: the default icon (no
- // custom emoji) maps to a "tip" with the icon dropped; any custom emoji maps to a "note" with
- // the emoji kept at the start of the body (admonitions have no per-block icon).
- const emoji = block.text?.iconEmoji ?? "";
- const type = emoji ? "note" : "tip";
- const lead = [emoji, renderInlineText(rawText, marks)].filter(Boolean).join(" ");
- const firstPara = lead ? `<p>${lead}</p>` : "";
- return `<aside class="admonition ${type}">${firstPara}${renderSequence(block.childrenIds ?? [])}</aside>`;
- }
-
- let html = "";
- if (rawText.trim() && style !== "Title" && style !== "Description") {
- if (style === "Code") {
- // A code block is literal: no inline marks, and its language is preserved as the MIME.
- html = renderCodeBlock(rawText, block.fields?.lang);
- } else {
- const tag = tagForStyle(style);
- html = `<${tag}>${renderInlineText(rawText, marks)}</${tag}>`;
- }
- }
- // A non-list block's children (e.g. a toggle heading's collapsed content) follow as flattened siblings.
- return html + renderSequence(block.childrenIds ?? []);
- }
-
- // The root block is the page container and carries no text of its own β€” start from its children.
- const html = renderSequence(root.childrenIds ?? []);
- return { html, linkTargetIds: [...linkTargetIds] };
-}
-
-/** The kind of list a block belongs to (bullet/ordered/task), or null when it isn't a list item. */
-type ListKind = "ul" | "ol" | "task";
-function listKind(block: AnytypeBlock): ListKind | null {
- switch (block.text?.style) {
- case "Marked":
- return "ul";
- case "Numbered":
- return "ol";
- case "Checkbox":
- return "task";
- default:
- return null;
- }
-}
-
-/**
- * Maps an Anytype text-block style to the Trilium tag it becomes. Anytype's three in-body heading levels
- * (UI-labelled Title / Heading / Subheading) map to Trilium's top three heading levels: Trilium reserves
- * `<h1>` for the note title, so its body headings start at `<h2>`. Toggle headings collapse to the same
- * plain headings (their toggle nature is dropped). Every other non-list style (paragraphs, quotes,
- * callouts, …) is flattened to a paragraph for now.
- */
-function tagForStyle(style: string | undefined): string {
- switch (style) {
- case "Header1":
- case "ToggleHeader1":
- return "h2";
- case "Header2":
- case "ToggleHeader2":
- return "h3";
- case "Header3":
- case "ToggleHeader3":
- return "h4";
- default:
- return "p";
- }
-}
-
-// #region Inline marks
-const MARK_TAGS: Record<string, string> = {
- Bold: "strong",
- Italic: "em",
- Underscored: "u",
- Strikethrough: "s",
- Keyboard: "code"
-};
-
-// Anytype's system colour palette (`--color-tag-*` / `--color-bg-tag-*`); marks carry the name in `param`.
-// Backgrounds are already opaque, so no flatten-over-white step is needed (unlike Notion's translucent set).
-const TEXT_COLORS: Record<string, string> = {
- grey: "#8c9ea5", yellow: "#b2a616", orange: "#d3720d", red: "#e2400c", pink: "#ca1b8e",
- purple: "#9e30c4", blue: "#3e58eb", ice: "#1c8bca", teal: "#0caaa3", lime: "#64b90f"
-};
-const BG_COLORS: Record<string, string> = {
- grey: "#e3e3e3", yellow: "#f4eb91", orange: "#fcdc9c", red: "#fcd1c3", pink: "#f8c2e5",
- purple: "#e8d0f1", blue: "#cbd2fa", ice: "#b2dff9", teal: "#a9ebe6", lime: "#c5efa3"
-};
-
-// Anytype's default (light-theme) text colour. A highlight (background) without an explicit text colour is
-// paired with this so the text stays readable on the pale highlight regardless of the Trilium theme β€”
-// otherwise a dark theme's default white text would be invisible on it.
-const DEFAULT_TEXT_COLOR = "#252525";
-
-// Outer-to-inner nesting order for the structural marks that cover the same segment β€” fixed so output is
-// deterministic. Colours are handled separately (folded into a single inner span).
-const MARK_ORDER = ["Bold", "Italic", "Underscored", "Strikethrough", "Keyboard"];
-
-interface AppliedMark {
- type: string;
- param: string;
- from: number;
- to: number;
-}
-
-/**
- * Converts a text block's inline marks into HTML. Anytype encodes formatting as a flat list of marks, each
- * a `[from, to)` character range (UTF-16 offsets) with a type β€” and marks may overlap freely. We turn that
- * into valid nested HTML by splitting the text at every mark boundary, so no segment straddles a mark edge,
- * then wrapping each segment in the tags whose range fully covers it. Adjacent segments always differ in
- * their active set (a boundary is only created where a mark starts or ends), so output is clean without a
- * merge pass. Links, mentions and emoji are ignored, leaving their text as plain (escaped) content.
- */
-export function renderInlineText(text: string, marks: AnytypeMark[]): string {
- const length = text.length;
-
- // Keep only marks we render (known structural kind, or a known colour name), with offsets clamped to
- // the text and empty/reversed ranges dropped.
- const applicable: AppliedMark[] = [];
- for (const mark of marks) {
- const param = mark.param ?? "";
- if (mark.type === undefined || !isRenderable(mark.type, param)) {
- continue;
- }
- const from = Math.max(0, Math.min(length, mark.range?.from ?? 0));
- const to = Math.max(0, Math.min(length, mark.range?.to ?? 0));
- if (from < to) {
- applicable.push({ type: mark.type, param, from, to });
- }
- }
-
- if (applicable.length === 0) {
- return escapeHtml(text);
- }
-
- // Split at every mark boundary so each segment is uniformly covered (or not) by each mark.
- const boundaries = new Set<number>([0, length]);
- for (const mark of applicable) {
- boundaries.add(mark.from);
- boundaries.add(mark.to);
- }
- const points = [...boundaries].sort((a, b) => a - b);
-
- let html = "";
- for (let i = 0; i < points.length - 1; i++) {
- const start = points[i];
- const end = points[i + 1];
- const covering = applicable.filter((mark) => mark.from <= start && mark.to >= end);
- html += wrapSegment(escapeHtml(text.slice(start, end)), covering);
- }
-
- return html;
-}
-
-/** Whether a mark is rendered: a known structural kind, or a colour with a known palette name. */
-function isRenderable(type: string, param: string): boolean {
- if (type in MARK_TAGS) {
- return true;
- }
- if (type === "TextColor") {
- return param in TEXT_COLORS;
- }
- if (type === "BackgroundColor") {
- return param in BG_COLORS;
- }
- return false;
-}
-
-/**
- * Wraps one segment in the tags of the marks that fully cover it. Text and background colour fold into a
- * single innermost `<span>` (a highlight without a text colour gets the default dark text); the structural
- * marks then nest around it, Bold outermost per {@link MARK_ORDER}.
- */
-function wrapSegment(segment: string, covering: AppliedMark[]): string {
- const textColor = paletteValue(covering, "TextColor", TEXT_COLORS);
- const bgColor = paletteValue(covering, "BackgroundColor", BG_COLORS);
-
- const styleParts: string[] = [];
- if (textColor) {
- styleParts.push(`color:${textColor}`);
- } else if (bgColor) {
- styleParts.push(`color:${DEFAULT_TEXT_COLOR}`);
- }
- if (bgColor) {
- styleParts.push(`background-color:${bgColor}`);
- }
- let html = styleParts.length > 0 ? `<span style="${styleParts.join(";")}">${segment}</span>` : segment;
-
- const structural = covering.filter((mark) => mark.type in MARK_TAGS).sort((a, b) => MARK_ORDER.indexOf(a.type) - MARK_ORDER.indexOf(b.type));
- for (let i = structural.length - 1; i >= 0; i--) {
- const tag = MARK_TAGS[structural[i].type];
- html = `<${tag}>${html}</${tag}>`;
- }
-
- return html;
-}
-
-/** The palette value for the segment's mark of the given colour type, or undefined if none covers it. */
-function paletteValue(covering: AppliedMark[], type: string, palette: Record<string, string>): string | undefined {
- const mark = covering.find((candidate) => candidate.type === type);
- return mark ? palette[mark.param] : undefined;
-}
-// #endregion
-
-// #region Code blocks
-// PrismJS language ids Anytype uses that don't line up with a Trilium markdown language code. Most ids
-// (javascript, python, go, rust, …) match directly; only the mismatches need listing here. `clike` is
-// PrismJS's generic C-family base, mapped to plain C as the closest concrete language.
-const LANGUAGE_ALIASES: Record<string, string> = {
- clike: "c"
-};
-
-/**
- * Renders an Anytype `Code`-style block as a Trilium/CKEditor code block. Anytype tags the block with a
- * PrismJS language id in `fields.lang`; we map that to a Trilium MIME and emit it as the CKEditor
- * code-block language class (`language-<normalized-mime>`), the same shape the markdown importer produces.
- * Quotes are left literal (matching the markdown importer), and an unknown language falls back to
- * auto-detect.
- */
-export function renderCodeBlock(text: string, lang: string | undefined): string {
- return `<pre><code class="language-${codeLanguage(lang)}">${escapeHtml(text).replace(/&quot;/g, '"')}</code></pre>`;
-}
-
-/** The CKEditor code-block language class value for an Anytype language id, or auto-detect when unknown. */
-function codeLanguage(lang: string | undefined): string {
- if (lang) {
- const mimeDefinition = getMimeTypeFromMarkdownName(LANGUAGE_ALIASES[lang] ?? lang);
- if (mimeDefinition) {
- return normalizeMimeTypeForCKEditor(mimeDefinition.mime);
- }
- }
- return MIME_TYPE_AUTO;
-}
-// #endregion
-
/**
* Creates a fresh "Anytype import" root and the page notes beneath it. A collection becomes a `book` with a
* `table` view and one promoted-attribute definition per column; a regular page becomes a `text` note. Each
@@ -637,144 +292,4 @@ function applyDates(note: BNote, page: ParsedObject) {
}
}
-// #region Export model
-/** A `[from, to)` character range a mark applies to. Offsets are UTF-16 code units (Anytype's editor is
- * JS/Electron), so they line up with JavaScript string indexing. */
-export interface AnytypeMarkRange {
- from?: number;
- to?: number;
-}
-
-/** An inline formatting span over a text block's `text`. `type` is the kind (Bold, Italic, Strikethrough,
- * Underscored, Keyboard, TextColor, …); `param` carries extra data for some kinds (a colour name, a link
- * URL). Marks may overlap freely and are not pre-sorted. */
-export interface AnytypeMark {
- range?: AnytypeMarkRange;
- type?: string;
- param?: string;
-}
-
-/** The text payload of a text block: its `text`, `style` (Paragraph, Header1, Marked, Checkbox, Callout, …),
- * a `marks.marks` list of inline formatting spans over `text`, and per-style extras (`checked`, `iconEmoji`). */
-export interface AnytypeText {
- text?: string;
- style?: string;
- marks?: {
- marks?: AnytypeMark[];
- };
- /** Whether a `Checkbox`-style list item is ticked. */
- checked?: boolean;
- /** A `Callout`'s icon; empty for the default icon, otherwise a custom emoji. */
- iconEmoji?: string;
-}
-
-/** A single block in an object's `snapshot.data.blocks`. Non-text blocks (dividers, dataviews, …) carry
- * other keys this importer doesn't read yet; only `id`, `childrenIds`, `text`, `div`, `link` and (for code
- * blocks) `fields.lang` are needed to pull out the page's content in document order. */
-export interface AnytypeBlock {
- id: string;
- childrenIds?: string[];
- text?: AnytypeText;
- /** Per-block extras. For a `Code`-style text block, `lang` holds the PrismJS language id. */
- fields?: {
- lang?: string;
- };
- /** A divider block (`style` is "Line" or "Dots"); both become a horizontal rule. */
- div?: {
- style?: string;
- };
- /** A block-level "link to object". `targetBlockId` is the linked object's id (CID); `style` is "Page"
- * for a page link. Rendered as a reference link to the imported target note. */
- link?: {
- targetBlockId?: string;
- 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`). */
- dataview?: {
- isCollection?: boolean;
- views?: {
- relations?: {
- key?: string;
- isVisible?: boolean;
- }[];
- }[];
- };
-}
-
-/** The object's `snapshot.data.details` β€” its metadata map. `layout` distinguishes a basic page (0) from
- * a set/collection (3) and other system layouts; `name` is the title; `id` matches the root block's id.
- * `layout` is omitted when it's the default (0), so `resolvedLayout` (always present) is the reliable
- * source of the effective layout. Custom property values are carried under their relation's hex
- * `relationKey`, hence the index signature. */
-export interface AnytypeDetails {
- id?: string;
- name?: string;
- layout?: number;
- resolvedLayout?: number;
- /** Page creation time as a Unix timestamp in seconds. Omitted/`0` for system objects. */
- createdDate?: number;
- /** Page last-modification time as a Unix timestamp in seconds. */
- 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, the format code, and (for a
- * date format) whether the value includes a time component. */
- relationKey?: string;
- relationFormat?: number;
- relationFormatIncludeTime?: boolean;
- /** On a `FileObject`: the display name, file extension, MIME type and the export path of the raw bytes
- * (e.g. `files\name.ext`). */
- fileExt?: string;
- fileMimeType?: string;
- source?: string;
- /** A custom property value, keyed by its relation's hex `relationKey`. */
- [key: string]: unknown;
-}
-
-/** One exported object file: `sbType` is the smartblock kind ("Page", "Participant", "Workspace", …) and
- * `snapshot.data` holds the blocks and details. */
-export interface AnytypeSnapshot {
- sbType?: string;
- snapshot?: {
- data?: {
- blocks?: AnytypeBlock[];
- details?: AnytypeDetails;
- objectTypes?: string[];
- };
- };
-}
-
-/** A page parsed down to what the importer needs to create a Trilium note. */
-export interface ParsedObject {
- /** The object's id (the root block's id); used later to resolve cross-object links. */
- id: string;
- title: string;
- /** Body HTML built from the page's blocks. */
- content: string;
- /** De-duplicated Trilium note ids this page links to, for recording `internalLink` relations. */
- linkTargetIds: string[];
- /** Creation time as a Trilium UTC datetime string (from Anytype's `createdDate`), if available. */
- dateCreated?: string;
- /** Last-modification time as a Trilium UTC datetime string (from `lastModifiedDate`), if available. */
- dateModified?: string;
- /** The object's custom property values, applied to its note as labels. */
- properties: ParsedProperty[];
- /** File-object ids from the object's file properties; resolved to `role:"file"` attachments at import. */
- fileRefs: string[];
- /** Present when the object is a collection: its table schema and membership. */
- collection?: ParsedCollection;
-}
-
-/** The imported note a linked-to Anytype object resolved to: its Trilium id and (fallback) title. */
-export interface ResolvedLink {
- noteId: string;
- title: string;
-}
-
-/** Resolves an Anytype object id (CID) to the Trilium note it was imported as, or undefined when the
- * target wasn't imported (a set/collection, or an object missing from the export). */
-export type LinkResolver = (targetCid: string) => ResolvedLink | undefined;
-// #endregion
-
export default { importAnytype };
diff --git a/packages/trilium-core/src/services/import/anytype/model.ts b/packages/trilium-core/src/services/import/anytype/model.ts
new file mode 100644
index 0000000000..8dffd533a5
--- /dev/null
+++ b/packages/trilium-core/src/services/import/anytype/model.ts
@@ -0,0 +1,191 @@
+/**
+ * Shared types for the Anytype importer: the shape of an exported object's JSON ("any-block") and the
+ * intermediate `Parsed*` values the importer builds from it. Kept in one module so the importer, the content
+ * renderer ({@link ./content.js}) and the collection handler ({@link ./collection.js}) all depend on the
+ * types without depending on each other β€” mirroring the Notion importer's `model.ts`.
+ */
+
+// #region Export shape
+/** A `[from, to)` character range a mark applies to. Offsets are UTF-16 code units (Anytype's editor is
+ * JS/Electron), so they line up with JavaScript string indexing. */
+export interface AnytypeMarkRange {
+ from?: number;
+ to?: number;
+}
+
+/** An inline formatting span over a text block's `text`. `type` is the kind (Bold, Italic, Strikethrough,
+ * Underscored, Keyboard, TextColor, …); `param` carries extra data for some kinds (a colour name, a link
+ * URL). Marks may overlap freely and are not pre-sorted. */
+export interface AnytypeMark {
+ range?: AnytypeMarkRange;
+ type?: string;
+ param?: string;
+}
+
+/** The text payload of a text block: its `text`, `style` (Paragraph, Header1, Marked, Checkbox, Callout, …),
+ * a `marks.marks` list of inline formatting spans over `text`, and per-style extras (`checked`, `iconEmoji`). */
+export interface AnytypeText {
+ text?: string;
+ style?: string;
+ marks?: {
+ marks?: AnytypeMark[];
+ };
+ /** Whether a `Checkbox`-style list item is ticked. */
+ checked?: boolean;
+ /** A `Callout`'s icon; empty for the default icon, otherwise a custom emoji. */
+ iconEmoji?: string;
+}
+
+/** A single block in an object's `snapshot.data.blocks`. Non-text blocks (dividers, dataviews, …) carry
+ * other keys this importer doesn't read yet; only `id`, `childrenIds`, `text`, `div`, `link` and (for code
+ * blocks) `fields.lang` are needed to pull out the page's content in document order. */
+export interface AnytypeBlock {
+ id: string;
+ childrenIds?: string[];
+ text?: AnytypeText;
+ /** Per-block extras. For a `Code`-style text block, `lang` holds the PrismJS language id. */
+ fields?: {
+ lang?: string;
+ };
+ /** A divider block (`style` is "Line" or "Dots"); both become a horizontal rule. */
+ div?: {
+ style?: string;
+ };
+ /** A block-level "link to object". `targetBlockId` is the linked object's id (CID); `style` is "Page"
+ * for a page link. Rendered as a reference link to the imported target note. */
+ link?: {
+ targetBlockId?: string;
+ 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`). */
+ dataview?: {
+ isCollection?: boolean;
+ views?: {
+ relations?: {
+ key?: string;
+ isVisible?: boolean;
+ }[];
+ }[];
+ };
+}
+
+/** The object's `snapshot.data.details` β€” its metadata map. `layout` distinguishes a basic page (0) from
+ * a set/collection (3) and other system layouts; `name` is the title; `id` matches the root block's id.
+ * `layout` is omitted when it's the default (0), so `resolvedLayout` (always present) is the reliable
+ * source of the effective layout. Custom property values are carried under their relation's hex
+ * `relationKey`, hence the index signature. */
+export interface AnytypeDetails {
+ id?: string;
+ name?: string;
+ layout?: number;
+ resolvedLayout?: number;
+ /** Page creation time as a Unix timestamp in seconds. Omitted/`0` for system objects. */
+ createdDate?: number;
+ /** Page last-modification time as a Unix timestamp in seconds. */
+ 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, the format code, and (for a
+ * date format) whether the value includes a time component. */
+ relationKey?: string;
+ relationFormat?: number;
+ relationFormatIncludeTime?: boolean;
+ /** On a `FileObject`: the display name, file extension, MIME type and the export path of the raw bytes
+ * (e.g. `files\name.ext`). */
+ fileExt?: string;
+ fileMimeType?: string;
+ source?: string;
+ /** A custom property value, keyed by its relation's hex `relationKey`. */
+ [key: string]: unknown;
+}
+
+/** One exported object file: `sbType` is the smartblock kind ("Page", "Participant", "Workspace", …) and
+ * `snapshot.data` holds the blocks and details. */
+export interface AnytypeSnapshot {
+ sbType?: string;
+ snapshot?: {
+ data?: {
+ blocks?: AnytypeBlock[];
+ details?: AnytypeDetails;
+ objectTypes?: string[];
+ };
+ };
+}
+// #endregion
+
+// #region Parsed values
+/** A page parsed down to what the importer needs to create a Trilium note. */
+export interface ParsedObject {
+ /** The object's id (the root block's id); used later to resolve cross-object links. */
+ id: string;
+ title: string;
+ /** Body HTML built from the page's blocks. */
+ content: string;
+ /** De-duplicated Trilium note ids this page links to, for recording `internalLink` relations. */
+ linkTargetIds: string[];
+ /** Creation time as a Trilium UTC datetime string (from Anytype's `createdDate`), if available. */
+ dateCreated?: string;
+ /** Last-modification time as a Trilium UTC datetime string (from `lastModifiedDate`), if available. */
+ dateModified?: string;
+ /** The object's custom property values, applied to its note as labels. */
+ properties: ParsedProperty[];
+ /** File-object ids from the object's file properties; resolved to `role:"file"` attachments at import. */
+ fileRefs: string[];
+ /** Present when the object is a collection: its table schema and membership. */
+ collection?: ParsedCollection;
+}
+
+/** The imported note a linked-to Anytype object resolved to: its Trilium id and (fallback) title. */
+export interface ResolvedLink {
+ noteId: string;
+ title: string;
+}
+
+/** Resolves an Anytype object id (CID) to the Trilium note it was imported as, or undefined when the
+ * 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, Anytype format code and
+ * (for date formats) whether the value carries a time component. */
+export interface RelationInfo {
+ name: string;
+ format: number;
+ includeTime?: boolean;
+}
+
+/** A file object resolved from the `filesObjects/` folder: the attachment title, MIME and the `files/` path
+ * its raw bytes live at. */
+export interface FileObjectInfo {
+ title: string;
+ mime: string;
+ source: string;
+}
+
+/** The Trilium label types a supported Anytype property maps to (email/phone reuse `url`). */
+export type PropertyLabelType = "text" | "number" | "url" | "date" | "datetime" | "boolean";
+
+/** Whether a property holds a single value or several (a multi-select). */
+export type Multiplicity = "single" | "multi";
+
+/** One custom property value on an object: the Trilium attribute name and its (already formatted) value. */
+export interface ParsedProperty {
+ name: string;
+ value: string;
+}
+
+/** One collection table column: its attribute name, Trilium label type, original (alias) name and value count. */
+export interface ParsedColumn {
+ name: string;
+ labelType: PropertyLabelType;
+ alias: string;
+ 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. */
+export interface ParsedCollection {
+ memberIds: string[];
+ columns: ParsedColumn[];
+}
+// #endregion