Skip to content

Build your personal knowledge base with Trilium Notes

feat(import/anytype): convert text/background colours to spans

Elian Doran7b0e21f65e51
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 25e353da13..2101351411 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
@@ -181,6 +181,42 @@ describe("Anytype importer — integration", () => {
);
});
+ it("applies text and background colours end-to-end, giving a highlight without a text colour readable default text", async () => {
+ const page = JSON.stringify({
+ sbType: "Page",
+ snapshot: {
+ data: {
+ blocks: [
+ { id: "clr", childrenIds: ["header", "clr-1"] },
+ { id: "header", childrenIds: ["title"] },
+ { id: "title", text: { text: "", style: "Title" } },
+ {
+ id: "clr-1",
+ text: {
+ text: "Grey Red",
+ style: "Paragraph",
+ marks: {
+ marks: [
+ // "Grey" is highlighted only (no text colour) — the third-row case.
+ { range: { from: 0, to: 4 }, type: "BackgroundColor", param: "grey" },
+ { range: { from: 5, to: 8 }, type: "TextColor", param: "red" }
+ ]
+ }
+ }
+ }
+ ],
+ details: { id: "clr", name: "Colours", resolvedLayout: 0 }
+ }
+ }
+ });
+ const importRoot = await importAnytype({ "objects/clr.pb.json": page });
+
+ const note = importRoot.getChildNotes().find((n) => n.title === "Colours");
+ expect(decodeUtf8(note?.getContent() ?? "")).toBe(
+ '<p><span style="color:#252525;background-color:#e3e3e3">Grey</span> <span style="color:#e2400c">Red</span></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/marks.spec.ts b/packages/trilium-core/src/services/import/anytype/marks.spec.ts
index 2d958e5b29..db2bca1f6d 100644
--- a/packages/trilium-core/src/services/import/anytype/marks.spec.ts
+++ b/packages/trilium-core/src/services/import/anytype/marks.spec.ts
@@ -48,8 +48,35 @@ describe("renderInlineText", () => {
);
});
- it("ignores unsupported mark types, keeping their text as plain (escaped) content", () => {
- expect(renderInlineText("Grey", [mark(0, 4, "TextColor", "grey")])).toBe("Grey");
+ 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", () => {
diff --git a/packages/trilium-core/src/services/import/anytype/marks.ts b/packages/trilium-core/src/services/import/anytype/marks.ts
index 750838943a..561bcbdae2 100644
--- a/packages/trilium-core/src/services/import/anytype/marks.ts
+++ b/packages/trilium-core/src/services/import/anytype/marks.ts
@@ -6,8 +6,8 @@
* 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.
+ * Structural marks (bold/italic/…) and text/background colours are rendered; links, mentions and emoji
+ * are ignored for now, leaving their text as plain (escaped) content.
*/
import type { AnytypeMark } from "./model.js";
@@ -20,11 +20,29 @@ const MARK_TAGS: Record<string, string> = {
Keyboard: "code"
};
-// Outer-to-inner nesting order for marks that cover the same segment — fixed so output is deterministic.
+// 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;
}
@@ -32,16 +50,18 @@ interface AppliedMark {
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.
+ // 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) {
- if (mark.type === undefined || !(mark.type in MARK_TAGS)) {
+ 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, from, to });
+ applicable.push({ type: mark.type, param, from, to });
}
}
@@ -61,17 +81,62 @@ export function renderInlineText(text: string, marks: AnytypeMark[]): string {
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 covering = applicable.filter((mark) => mark.from <= start && mark.to >= end);
+ html += wrapSegment(escapeHtml(text.slice(start, end)), covering);
+ }
- 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;
+}
+
+/** 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;
+}
+
function escapeHtml(text: string): string {
return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
}