Skip to content

Build your personal knowledge base with Trilium Notes

feat(import/anytype): render tables and Mermaid diagrams

Elian Doran968a6b2cbd96
diff --git a/packages/trilium-core/src/services/import/anytype/content.spec.ts b/packages/trilium-core/src/services/import/anytype/content.spec.ts
index c9ad6e470a..8e35f5ad53 100644
--- a/packages/trilium-core/src/services/import/anytype/content.spec.ts
+++ b/packages/trilium-core/src/services/import/anytype/content.spec.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
-import { renderCodeBlock, renderInlineText } from "./content.js";
+import { renderCodeBlock, renderInlineText, renderLatexBlock, renderTable } from "./content.js";
import { parseObject } from "./importer.js";
import type { AnytypeBlock, AnytypeMark, AnytypeSnapshot, LinkResolver } from "./model.js";
@@ -307,3 +307,87 @@ describe("renderCodeBlock", () => {
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>');
});
});
+
+describe("renderLatexBlock", () => {
+ it("renders a Mermaid block as a language-mermaid code block, escaping the diagram (the browser decodes it back)", () => {
+ // Verbatim Mermaid from the "More formatting" page; `-->` must be HTML-escaped to stay valid markup.
+ expect(renderLatexBlock("stateDiagram-v2\n [*] --> Still\n", "Mermaid")).toBe(
+ '<pre><code class="language-mermaid">stateDiagram-v2\n [*] --&gt; Still\n</code></pre>'
+ );
+ });
+
+ it("renders any non-Mermaid latex as CKEditor display math, keeping quotes literal", () => {
+ expect(renderLatexBlock("E = mc^2", undefined)).toBe('<span class="math-tex">\\[ E = mc^2 \\]</span>');
+ expect(renderLatexBlock("a < b & c", "Latex")).toBe('<span class="math-tex">\\[ a &lt; b &amp; c \\]</span>');
+ });
+
+ it("drops an empty latex block", () => {
+ expect(renderLatexBlock(" ", "Mermaid")).toBe("");
+ expect(renderLatexBlock("", undefined)).toBe("");
+ });
+});
+
+describe("tables", () => {
+ /** A table-cell text block, addressed by `${rowId}-${columnId}`. */
+ const cell = (rowId: string, columnId: string, text: string): AnytypeBlock => ({ id: `${rowId}-${columnId}`, text: { text, marks: { marks: [] } }, childrenIds: [] });
+
+ /**
+ * Builds a page whose only content is a table: a `table` block with a `TableColumns` and a `TableRows`
+ * layout, `columns` column ids, and `rows` of `[rowId, isHeader, cellTextByColumn]`. A column omitted
+ * from a row's map models an empty (un-exported) cell.
+ */
+ function tableDoc(columns: string[], rows: [string, boolean, Record<string, string>][]): AnytypeSnapshot {
+ const blocks: AnytypeBlock[] = [
+ { id: "obj", childrenIds: ["tbl"] },
+ { id: "tbl", table: {}, childrenIds: ["cols", "rows"] },
+ { id: "cols", childrenIds: columns },
+ ...columns.map((id): AnytypeBlock => ({ id, childrenIds: [] })),
+ { id: "rows", childrenIds: rows.map(([rowId]) => rowId) }
+ ];
+ for (const [rowId, isHeader, cellsByColumn] of rows) {
+ const cellIds = Object.keys(cellsByColumn).map((columnId) => `${rowId}-${columnId}`);
+ blocks.push({ id: rowId, tableRow: { isHeader }, childrenIds: cellIds });
+ for (const [columnId, text] of Object.entries(cellsByColumn)) {
+ blocks.push(cell(rowId, columnId, text));
+ }
+ }
+ return snapshot(blocks, { id: "obj", name: "Tables" });
+ }
+
+ it("renders a header row in <thead> (th scope=col) and body rows in <tbody> (td), in column order", () => {
+ const doc = tableDoc(
+ ["c1", "c2"],
+ [
+ ["r1", true, { c1: "A", c2: "B" }],
+ ["r2", false, { c1: "1", c2: "2" }]
+ ]
+ );
+ expect(parseObject(doc).content).toBe(
+ '<figure class="table"><table>' +
+ '<thead><tr><th scope="col">A</th><th scope="col">B</th></tr></thead>' +
+ "<tbody><tr><td>1</td><td>2</td></tr></tbody>" +
+ "</table></figure>"
+ );
+ });
+
+ it("renders a header-less table as all <td> rows (matching the real export), applying inline marks in cells", () => {
+ const doc = tableDoc(["c1", "c2", "c3"], [["r1", false, { c1: "A", c2: "B", c3: "C" }]]);
+ const result = parseObject(doc);
+ expect(result.content).toBe('<figure class="table"><table><tbody><tr><td>A</td><td>B</td><td>C</td></tr></tbody></table></figure>');
+ });
+
+ it("fills an omitted (empty) cell with a blank td, keeping the grid aligned to the columns", () => {
+ // r1 carries no cell for c2 — a row drops its empty cells, so column order must backfill it.
+ const doc = tableDoc(["c1", "c2"], [["r1", false, { c1: "only" }]]);
+ expect(parseObject(doc).content).toBe('<figure class="table"><table><tbody><tr><td>only</td><td></td></tr></tbody></table></figure>');
+ });
+
+ it("renderTable returns empty for a table with no columns or no rows", () => {
+ const byId = new Map<string, AnytypeBlock>([
+ ["tbl", { id: "tbl", table: {}, childrenIds: ["cols", "rows"] }],
+ ["cols", { id: "cols", childrenIds: [] }],
+ ["rows", { id: "rows", childrenIds: [] }]
+ ]);
+ expect(renderTable(byId.get("tbl") ?? { id: "x" }, byId)).toBe("");
+ });
+});
diff --git a/packages/trilium-core/src/services/import/anytype/content.ts b/packages/trilium-core/src/services/import/anytype/content.ts
index 5454694d6e..de3aa83a5f 100644
--- a/packages/trilium-core/src/services/import/anytype/content.ts
+++ b/packages/trilium-core/src/services/import/anytype/content.ts
@@ -4,10 +4,11 @@
* 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`.
+ * quotes, dividers, tables ({@link renderTable}), Mermaid diagrams / LaTeX math ({@link renderLatexBlock})
+ * 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";
@@ -109,6 +110,17 @@ export function extractContent(blocks: AnytypeBlock[], rootId: string, resolveLi
return `<p><a class="reference-link" href="#root/${target.noteId}">${escapeHtml(target.title)}</a></p>`;
}
+ // A LaTeX block — a Mermaid diagram or LaTeX math.
+ if (block.latex) {
+ return renderLatexBlock(block.latex.text ?? "", block.latex.processor);
+ }
+
+ // A table block: render its columns/rows/cells subtree directly. Returning here skips the generic
+ // child walk below, which would otherwise emit every cell's text as a stray paragraph after the table.
+ if (block.table) {
+ return renderTable(block, byId);
+ }
+
// 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;
@@ -359,3 +371,73 @@ function codeLanguage(lang: string | undefined): string {
return MIME_TYPE_AUTO;
}
// #endregion
+
+// #region LaTeX & Mermaid
+/**
+ * Renders an Anytype `latex` block. With the `Mermaid` processor it becomes a `language-mermaid` code block —
+ * Trilium's mermaid rendering keys off that class (the same convention the Notion importer uses), and the
+ * browser decodes the escaped diagram text back when reading it. Any other processor is treated as LaTeX
+ * math, emitted as a CKEditor display-math span (`<span class="math-tex">\[ … \]</span>`). Empty text is dropped.
+ */
+export function renderLatexBlock(text: string, processor: string | undefined): string {
+ if (!text.trim()) {
+ return "";
+ }
+ const escaped = escapeHtml(text).replace(/&quot;/g, '"');
+ if (processor === "Mermaid") {
+ return `<pre><code class="language-mermaid">${escaped}</code></pre>`;
+ }
+ return `<span class="math-tex">\\[ ${escaped} \\]</span>`;
+}
+// #endregion
+
+// #region Tables
+/**
+ * Renders an Anytype table block to Trilium/CKEditor table HTML. An Anytype table's two children are a
+ * `TableColumns` layout (its ordered column ids) and a `TableRows` layout (its rows); each row's cells are
+ * text blocks whose id is `${rowId}-${columnId}`, and a row omits its empty cells. We walk the columns in
+ * order and, for each row, place that column's cell (blank when absent) so the grid stays aligned. A row
+ * flagged `isHeader` becomes `<th scope="col">` in a `<thead>`; the rest are `<td>` in the `<tbody>`. The
+ * table is wrapped in `<figure class="table">`, the shape CKEditor stores (mirroring the Notion importer).
+ */
+export function renderTable(table: AnytypeBlock, byId: Map<string, AnytypeBlock>): string {
+ const [colsLayoutId, rowsLayoutId] = table.childrenIds ?? [];
+ const columnIds = (colsLayoutId ? byId.get(colsLayoutId)?.childrenIds : undefined) ?? [];
+ const rowIds = (rowsLayoutId ? byId.get(rowsLayoutId)?.childrenIds : undefined) ?? [];
+ if (columnIds.length === 0 || rowIds.length === 0) {
+ return "";
+ }
+
+ const headRows: string[] = [];
+ const bodyRows: string[] = [];
+ for (const rowId of rowIds) {
+ const row = byId.get(rowId);
+ if (!row) {
+ continue;
+ }
+ const isHeader = !!row.tableRow?.isHeader;
+ // Index this row's cells by their column-id suffix (cell id = `${rowId}-${columnId}`).
+ const cellByColumn = new Map<string, AnytypeBlock>();
+ for (const cellId of row.childrenIds ?? []) {
+ const cell = byId.get(cellId);
+ if (cell && cellId.startsWith(`${rowId}-`)) {
+ cellByColumn.set(cellId.slice(rowId.length + 1), cell);
+ }
+ }
+ const tag = isHeader ? "th" : "td";
+ const scope = isHeader ? ' scope="col"' : "";
+ const cells = columnIds
+ .map((columnId) => {
+ const cell = cellByColumn.get(columnId);
+ const content = cell ? renderInlineText(cell.text?.text ?? "", cell.text?.marks?.marks ?? []) : "";
+ return `<${tag}${scope}>${content}</${tag}>`;
+ })
+ .join("");
+ (isHeader ? headRows : bodyRows).push(`<tr>${cells}</tr>`);
+ }
+
+ const thead = headRows.length > 0 ? `<thead>${headRows.join("")}</thead>` : "";
+ const tbody = bodyRows.length > 0 ? `<tbody>${bodyRows.join("")}</tbody>` : "";
+ return `<figure class="table"><table>${thead}${tbody}</table></figure>`;
+}
+// #endregion
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.ts
index 81fb828cd8..2607b72640 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
@@ -295,6 +295,48 @@ describe("Anytype importer — integration", () => {
);
});
+ it("imports a Mermaid diagram and a table end-to-end (from the 'More formatting' page)", async () => {
+ // A latex/Mermaid block and a table (TableColumns + TableRows layouts; cells keyed `${rowId}-${columnId}`).
+ const page = JSON.stringify({
+ sbType: "Page",
+ snapshot: {
+ data: {
+ blocks: [
+ { id: "pg", childrenIds: ["header", "mmd", "tbl"] },
+ { id: "header", childrenIds: ["title"] },
+ { id: "title", text: { text: "", style: "Title" } },
+ { id: "mmd", latex: { text: "stateDiagram-v2\n [*] --> Still\n", processor: "Mermaid" } },
+ { id: "tbl", table: {}, childrenIds: ["cols", "rows"] },
+ { id: "cols", layout: { style: "TableColumns" }, childrenIds: ["c1", "c2", "c3"] },
+ { id: "c1", tableColumn: {}, childrenIds: [] },
+ { id: "c2", tableColumn: {}, childrenIds: [] },
+ { id: "c3", tableColumn: {}, childrenIds: [] },
+ { id: "rows", layout: { style: "TableRows" }, childrenIds: ["r1", "r2"] },
+ { id: "r1", tableRow: {}, childrenIds: ["r1-c1", "r1-c2", "r1-c3"] },
+ { id: "r1-c1", text: { text: "A" } },
+ { id: "r1-c2", text: { text: "B" } },
+ { id: "r1-c3", text: { text: "C" } },
+ { id: "r2", tableRow: {}, childrenIds: ["r2-c1", "r2-c2", "r2-c3"] },
+ { id: "r2-c1", text: { text: "1" } },
+ { id: "r2-c2", text: { text: "2" } },
+ { id: "r2-c3", text: { text: "3" } }
+ ],
+ details: { id: "pg", name: "More formatting", resolvedLayout: 0 }
+ }
+ }
+ });
+ const importRoot = await importAnytype({ "objects/fmt.pb.json": page });
+
+ const note = importRoot.getChildNotes().find((n) => n.title === "More formatting");
+ expect(decodeUtf8(note?.getContent() ?? "")).toBe(
+ '<pre><code class="language-mermaid">stateDiagram-v2\n [*] --&gt; Still\n</code></pre>' +
+ '<figure class="table"><table><tbody>' +
+ "<tr><td>A</td><td>B</td><td>C</td></tr>" +
+ "<tr><td>1</td><td>2</td><td>3</td></tr>" +
+ "</tbody></table></figure>"
+ );
+ });
+
it("imports nested lists end-to-end (grouping consecutive items, nesting children)", async () => {
const page = JSON.stringify({
sbType: "Page",
diff --git a/packages/trilium-core/src/services/import/anytype/model.ts b/packages/trilium-core/src/services/import/anytype/model.ts
index bacdbbc923..0d5740e473 100644
--- a/packages/trilium-core/src/services/import/anytype/model.ts
+++ b/packages/trilium-core/src/services/import/anytype/model.ts
@@ -57,6 +57,19 @@ export interface AnytypeBlock {
targetBlockId?: string;
style?: string;
};
+ /** A "latex" block — Anytype's embed for code-rendered diagrams and math. `processor` picks the renderer
+ * ("Mermaid" for a Mermaid diagram; otherwise the `text` is LaTeX math). */
+ latex?: {
+ text?: string;
+ processor?: string;
+ };
+ /** A table block (an empty marker object). Its two children are a `TableColumns` and a `TableRows`
+ * layout block; each row's cells are text blocks whose id is `${rowId}-${columnId}`. */
+ table?: Record<string, unknown>;
+ /** A table-row block (child of the `TableRows` layout); `isHeader` marks a header row. */
+ tableRow?: {
+ isHeader?: boolean;
+ };
/** A dataview block — a set (query) or collection (manual list). `isCollection` distinguishes the two;
* `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