Skip to content

Build your personal knowledge base with Trilium Notes

feat(import/anytype): convert inline marks to HTML

Elian Doranc00e3a5b32b6
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 7be8e00a11..25e353da13 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
@@ -141,6 +141,46 @@ describe("Anytype importer — integration", () => {
expect(decodeUtf8(note?.getContent() ?? "")).toBe("<p>Regular text</p><h2>Title</h2><h3>Heading</h3><h4>Subheading</h4>");
});
+ it("applies inline marks end-to-end (verbatim from the 'Formatting test' page)", async () => {
+ const page = JSON.stringify({
+ sbType: "Page",
+ snapshot: {
+ data: {
+ blocks: [
+ { id: "fmt", childrenIds: ["header", "fmt-1"] },
+ { id: "header", childrenIds: ["title"] },
+ { id: "title", text: { text: "", style: "Title" } },
+ {
+ id: "fmt-1",
+ text: {
+ text: "Bold Italic Strikethrough Underline Bold Italic Underline",
+ style: "Paragraph",
+ marks: {
+ marks: [
+ { range: { from: 12, to: 25 }, type: "Strikethrough" },
+ { range: { from: 5, to: 11 }, type: "Italic" },
+ { range: { from: 36, to: 57 }, type: "Italic" },
+ { range: { from: 0, to: 4 }, type: "Bold" },
+ { range: { from: 36, to: 57 }, type: "Bold" },
+ { range: { from: 26, to: 35 }, type: "Underscored" },
+ { range: { from: 36, to: 57 }, type: "Underscored" }
+ ]
+ }
+ }
+ }
+ ],
+ details: { id: "fmt", name: "Formatting test", resolvedLayout: 0 }
+ }
+ }
+ });
+ const importRoot = await importAnytype({ "objects/fmt.pb.json": page });
+
+ const note = importRoot.getChildNotes().find((n) => n.title === "Formatting test");
+ expect(decodeUtf8(note?.getContent() ?? "")).toBe(
+ "<p><strong>Bold</strong> <em>Italic</em> <s>Strikethrough</s> <u>Underline</u> <strong><em><u>Bold Italic Underline</u></em></strong></p>"
+ );
+ });
+
it("produces an empty root when the export has no pages", async () => {
const importRoot = await importAnytype({
"types/type1.pb.json": JSON.stringify({ sbType: "STType", snapshot: { data: { details: { id: "type1", name: "Article" } } } })
diff --git a/packages/trilium-core/src/services/import/anytype/importer.spec.ts b/packages/trilium-core/src/services/import/anytype/importer.spec.ts
index 1c80c9de9a..44fc9d4708 100644
--- a/packages/trilium-core/src/services/import/anytype/importer.spec.ts
+++ b/packages/trilium-core/src/services/import/anytype/importer.spec.ts
@@ -1,16 +1,16 @@
import { describe, expect, it } from "vitest";
import { isPage, parseObject } from "./importer.js";
-import type { AnytypeBlock, AnytypeSnapshot } from "./model.js";
+import type { AnytypeBlock, AnytypeMark, AnytypeSnapshot } 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 }, sbType = "Page"): AnytypeSnapshot {
return { sbType, snapshot: { data: { blocks, details } } };
}
-/** A text block with the given style (defaults to Paragraph) and optional children. */
-function textBlock(id: string, text: string, style = "Paragraph", childrenIds: string[] = []): AnytypeBlock {
- return { id, text: { text, style }, childrenIds };
+/** A text block with the given style (defaults to Paragraph), optional children and optional marks. */
+function textBlock(id: string, text: string, style = "Paragraph", childrenIds: string[] = [], marks: AnytypeMark[] = []): AnytypeBlock {
+ return { id, text: { text, style, marks: { marks } }, childrenIds };
}
/** A typical page: a root block pointing at the header chrome plus the given content block ids. */
@@ -68,6 +68,11 @@ describe("parseObject", () => {
expect(result.content).toBe("<p>Regular text</p><h2>Title</h2><h3>Heading</h3><h4>Subheading</h4>");
});
+ it("applies inline marks inside the block's tag", () => {
+ const result = parseObject(page("Marks", [textBlock("b1", "Bold text", "Paragraph", [], [{ range: { from: 0, to: 4 }, type: "Bold" }])]));
+ expect(result.content).toBe("<p><strong>Bold</strong> text</p>");
+ });
+
it("walks nested blocks in document order (parent text before its children)", () => {
const result = parseObject(page("Nested", [textBlock("b1", "Parent", "Paragraph", ["c1"]), textBlock("c1", "Child")]));
expect(result.content).toBe("<p>Parent</p><p>Child</p>");
diff --git a/packages/trilium-core/src/services/import/anytype/importer.ts b/packages/trilium-core/src/services/import/anytype/importer.ts
index be740dc728..5be7cb351e 100644
--- a/packages/trilium-core/src/services/import/anytype/importer.ts
+++ b/packages/trilium-core/src/services/import/anytype/importer.ts
@@ -20,6 +20,7 @@ import noteService from "../../notes.js";
import protectedSessionService from "../../protected_session.js";
import type TaskContext from "../../task_context.js";
import { getZipProvider } from "../../zip_provider.js";
+import { renderInlineText } from "./marks.js";
import type { AnytypeBlock, AnytypeSnapshot, ParsedObject } from "./model.js";
async function importAnytype(taskContext: TaskContext<"importNotes">, fileBuffer: Uint8Array, importRootNote: BNote): Promise<BNote> {
@@ -91,10 +92,9 @@ export function parseObject(snapshot: AnytypeSnapshot): ParsedObject {
/**
* Walks the block tree from the root in document order, wrapping each non-empty text block in a tag chosen
- * by its style (headings → `<h2>`/`<h3>`/`<h4>`, everything else → `<p>`). The `header` subtree
- * (title/description/featuredRelations chrome) is skipped, as are the structural Title and Description
- * styles wherever they appear. Formatting (marks), links and other block kinds are ignored for now — only
- * the text is pulled out.
+ * by its style (headings → `<h2>`/`<h3>`/`<h4>`, everything else → `<p>`) with its inline marks applied.
+ * The `header` subtree (title/description/featuredRelations chrome) is skipped, as are the structural Title
+ * and Description styles wherever they appear. Links and other block kinds are ignored for now.
*/
function extractTextContent(blocks: AnytypeBlock[], rootId: string): string {
const byId = new Map<string, AnytypeBlock>();
@@ -122,11 +122,13 @@ function extractTextContent(blocks: AnytypeBlock[], rootId: string): string {
return;
}
- const text = block.text?.text?.trim();
+ // 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;
- if (text && style !== "Title" && style !== "Description") {
+ if (rawText.trim() && style !== "Title" && style !== "Description") {
const tag = tagForStyle(style);
- parts.push(`<${tag}>${escapeHtml(text)}</${tag}>`);
+ const inner = renderInlineText(rawText, block.text?.marks?.marks ?? []);
+ parts.push(`<${tag}>${inner}</${tag}>`);
}
for (const childId of block.childrenIds ?? []) {
@@ -161,10 +163,6 @@ function tagForStyle(style: string | undefined): string {
}
}
-function escapeHtml(text: string): string {
- return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
-}
-
/** Creates a fresh "Anytype import" root and a flat child note per page. */
function createNotes(importRootNote: BNote, pages: ParsedObject[], taskContext: TaskContext<"importNotes">): BNote {
/* v8 ignore next -- the protected branch needs a protected import root with an active protected session, which the in-memory test DB has no way to set up */
diff --git a/packages/trilium-core/src/services/import/anytype/marks.spec.ts b/packages/trilium-core/src/services/import/anytype/marks.spec.ts
new file mode 100644
index 0000000000..2d958e5b29
--- /dev/null
+++ b/packages/trilium-core/src/services/import/anytype/marks.spec.ts
@@ -0,0 +1,64 @@
+import { describe, expect, it } from "vitest";
+
+import { renderInlineText } from "./marks.js";
+import type { AnytypeMark } from "./model.js";
+
+function mark(from: number, to: number, type: string, param?: string): AnytypeMark {
+ return { range: { from, to }, type, param };
+}
+
+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("ignores unsupported mark types, keeping their text as plain (escaped) content", () => {
+ expect(renderInlineText("Grey", [mark(0, 4, "TextColor", "grey")])).toBe("Grey");
+ });
+
+ 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");
+ });
+});
diff --git a/packages/trilium-core/src/services/import/anytype/marks.ts b/packages/trilium-core/src/services/import/anytype/marks.ts
new file mode 100644
index 0000000000..750838943a
--- /dev/null
+++ b/packages/trilium-core/src/services/import/anytype/marks.ts
@@ -0,0 +1,77 @@
+/**
+ * Converts an Anytype 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 the output is
+ * clean without a merge pass.
+ *
+ * Only the structural text marks are rendered for now; colours, links, mentions and emoji are ignored,
+ * leaving their text as plain (escaped) content.
+ */
+
+import type { AnytypeMark } from "./model.js";
+
+const MARK_TAGS: Record<string, string> = {
+ Bold: "strong",
+ Italic: "em",
+ Underscored: "u",
+ Strikethrough: "s",
+ Keyboard: "code"
+};
+
+// Outer-to-inner nesting order for marks that cover the same segment — fixed so output is deterministic.
+const MARK_ORDER = ["Bold", "Italic", "Underscored", "Strikethrough", "Keyboard"];
+
+interface AppliedMark {
+ type: string;
+ from: number;
+ to: number;
+}
+
+export function renderInlineText(text: string, marks: AnytypeMark[]): string {
+ const length = text.length;
+
+ // Keep only marks we render, with offsets clamped to the text and empty/reversed ranges dropped.
+ const applicable: AppliedMark[] = [];
+ for (const mark of marks) {
+ if (mark.type === undefined || !(mark.type in MARK_TAGS)) {
+ 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, 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 segment = escapeHtml(text.slice(start, end));
+
+ const active = MARK_ORDER.filter((type) => applicable.some((mark) => mark.type === type && mark.from <= start && mark.to >= end));
+ const open = active.map((type) => `<${MARK_TAGS[type]}>`).join("");
+ const close = active.map((type) => `</${MARK_TAGS[type]}>`).reverse().join("");
+ html += open + segment + close;
+ }
+
+ return html;
+}
+
+function escapeHtml(text: string): string {
+ return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
+}
diff --git a/packages/trilium-core/src/services/import/anytype/model.ts b/packages/trilium-core/src/services/import/anytype/model.ts
index 587348b8bb..d666c95ef2 100644
--- a/packages/trilium-core/src/services/import/anytype/model.ts
+++ b/packages/trilium-core/src/services/import/anytype/model.ts
@@ -6,11 +6,30 @@
* minimally (or not at all) for now and will be filled in as the importer is extended.
*/
-/** The text payload of a text block. Anytype has many `style`s (Paragraph, Header1, Numbered, …); the
- * basic importer ignores them and emits every non-empty text block as a plain paragraph. */
+/** 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. Anytype has many `style`s (Paragraph, Header1, Numbered, …) and a
+ * `marks.marks` list of inline formatting spans over `text`. */
export interface AnytypeText {
text?: string;
style?: string;
+ marks?: {
+ marks?: AnytypeMark[];
+ };
}
/** A single block in an object's `snapshot.data.blocks`. Non-text blocks (links, dividers, dataviews, …)