Skip to content

Build your personal knowledge base with Trilium Notes

feat(import): preserve basic formatting in Google Keep import

Elian Doran2c0f5f453f0f
diff --git a/packages/trilium-core/src/services/import/keep/converter.spec.ts b/packages/trilium-core/src/services/import/keep/converter.spec.ts
new file mode 100644
index 0000000000..3911721f2e
--- /dev/null
+++ b/packages/trilium-core/src/services/import/keep/converter.spec.ts
@@ -0,0 +1,54 @@
+import { describe, expect, it } from "vitest";
+
+import { convertKeepHtml, convertKeepHtmlInline } from "./converter.js";
+
+/** Builds a Keep-style styled span (the export wraps every run of text in one of these). */
+function span(text: string, style: string): string {
+ return `<span style="font-size:7.2pt;font-family:'Google Sans';color:#000000;${style}">${text}</span>`;
+}
+
+describe("Google Keep converter — convertKeepHtml", () => {
+ it("converts bold / italic / underline spans to semantic tags and drops the style noise", () => {
+ const html =
+ `<p dir="ltr" style="line-height:1.38;">` +
+ span("Bold", "font-weight:700;font-style:normal;text-decoration:none;") +
+ span("italic", "font-weight:400;font-style:italic;text-decoration:none;") +
+ span("underline", "font-weight:400;font-style:normal;text-decoration:underline;-webkit-text-decoration-skip:none;") +
+ `</p>`;
+
+ expect(convertKeepHtml(html)).toBe("<p><strong>Bold</strong><i>italic</i><u>underline</u></p>");
+ });
+
+ it("nests all three when a run is bold + italic + underline (bold outermost)", () => {
+ const html = `<p>${span("all three", "font-weight:700;font-style:italic;text-decoration:underline;")}</p>`;
+
+ expect(convertKeepHtml(html)).toBe("<p><strong><i><u>all three</u></i></strong></p>");
+ });
+
+ it("preserves headings (unwrapping their unstyled spans) and leaves entities intact", () => {
+ const html =
+ `<h1 dir="ltr" style="line-height:1.38;">${span("Heading 1", "font-weight:400;")}</h1>` +
+ `<h2 dir="ltr" style="line-height:1.38;">${span("Heading 2", "font-weight:400;")}</h2>` +
+ `<p>${span("a &amp; b", "font-weight:400;font-style:normal;text-decoration:none;")}</p>`;
+
+ expect(convertKeepHtml(html)).toBe("<h1>Heading 1</h1><h2>Heading 2</h2><p>a &amp; b</p>");
+ });
+
+ it("unwraps a plain span entirely, keeping only its text", () => {
+ expect(convertKeepHtml(`<p>${span("plain", "font-weight:400;")}</p>`)).toBe("<p>plain</p>");
+ });
+});
+
+describe("Google Keep converter — convertKeepHtmlInline", () => {
+ it("unwraps the single block element Keep wraps a list item's text in", () => {
+ const html = `<p dir="ltr" style="line-height:1.38;">${span("This is a note with", "font-weight:400;")}</p>`;
+
+ expect(convertKeepHtmlInline(html)).toBe("This is a note with");
+ });
+
+ it("keeps inline formatting inside the unwrapped item", () => {
+ const html = `<p>${span("done", "font-weight:700;")}</p>`;
+
+ expect(convertKeepHtmlInline(html)).toBe("<strong>done</strong>");
+ });
+});
diff --git a/packages/trilium-core/src/services/import/keep/converter.ts b/packages/trilium-core/src/services/import/keep/converter.ts
new file mode 100644
index 0000000000..904711f3c9
--- /dev/null
+++ b/packages/trilium-core/src/services/import/keep/converter.ts
@@ -0,0 +1,90 @@
+/**
+ * Post-processes a Google Keep note's rich-text HTML (`textContentHtml` / a list item's `textHtml`) into
+ * Trilium/CKEditor-friendly markup.
+ *
+ * Keep exports Google-Docs-style HTML: semantic block tags (`<h1>`, `<h2>`, `<p>`) whose every run of text
+ * is a `<span>` carrying a large inline `style` (font, colour, and — the bits we care about — `font-weight`,
+ * `font-style`, `text-decoration`). This module keeps the block structure but converts those styled spans
+ * into `<strong>`/`<i>`/`<u>` and drops the inline-style noise. Heading-level demotion (Trilium reserves
+ * `<h1>` for the note title) and final XSS sanitization are left to the sanitizer applied downstream.
+ *
+ * Only basic formatting (bold/italic/underline) is in scope; other inline styling (colour, font size, …)
+ * is intentionally discarded.
+ */
+
+import { HTMLElement, parse } from "node-html-parser";
+
+/** Converts a Keep block-level rich-text fragment (a note's `textContentHtml`), preserving block structure. */
+export function convertKeepHtml(html: string): string {
+ const root = parse(html);
+ clean(root);
+ return root.toString();
+}
+
+/**
+ * Converts a Keep list item's `textHtml` to inline markup for a checklist label. Keep wraps each item's
+ * text in a single block element (a `<p>`); unwrap it so the result sits directly inside the label, falling
+ * back to the cleaned markup as-is when the shape is unexpected.
+ */
+export function convertKeepHtmlInline(html: string): string {
+ const root = parse(html);
+ clean(root);
+
+ const elements = root.childNodes.filter((node): node is HTMLElement => node instanceof HTMLElement);
+ return elements.length === 1 ? elements[0].innerHTML : root.toString();
+}
+
+/** Rewrites styled spans to semantic inline tags, then strips the leftover presentational attributes. */
+function clean(root: HTMLElement) {
+ convertStyledSpans(root);
+ stripNoiseAttributes(root);
+}
+
+/**
+ * Replaces each `<span>` with its content wrapped in the inline tags its style implies — `<strong>` for a
+ * bold font weight, `<i>` for italic, `<u>` for underline — dropping the span (and its style) itself. A span
+ * with no relevant styling is simply unwrapped. Processed in reverse document order so a nested span is
+ * converted before the span that contains it.
+ */
+function convertStyledSpans(root: HTMLElement) {
+ for (const span of [...root.querySelectorAll("span")].reverse()) {
+ const style = span.getAttribute("style") ?? "";
+
+ let inner = span.innerHTML;
+ if (isUnderline(style)) {
+ inner = `<u>${inner}</u>`;
+ }
+ if (isItalic(style)) {
+ inner = `<i>${inner}</i>`;
+ }
+ if (isBold(style)) {
+ inner = `<strong>${inner}</strong>`;
+ }
+
+ span.insertAdjacentHTML("beforebegin", inner);
+ span.remove();
+ }
+}
+
+/** Removes the presentational `style`/`dir` attributes Keep puts on every block, leaving clean semantic tags. */
+function stripNoiseAttributes(root: HTMLElement) {
+ for (const element of root.querySelectorAll("*")) {
+ element.removeAttribute("style");
+ element.removeAttribute("dir");
+ }
+}
+
+function isBold(style: string): boolean {
+ const weight = style.match(/font-weight:\s*(\d+)/);
+ return weight ? Number(weight[1]) >= 600 : /font-weight:\s*bold/.test(style);
+}
+
+function isItalic(style: string): boolean {
+ return /font-style:\s*italic/.test(style);
+}
+
+function isUnderline(style: string): boolean {
+ // Keep also emits `text-decoration-skip-ink`/`-webkit-text-decoration-skip`; the `text-decoration:`
+ // anchor (colon immediately after the property) matches only the real shorthand, not those.
+ return /text-decoration:\s*[^;]*underline/.test(style);
+}
diff --git a/packages/trilium-core/src/services/import/keep/importer.spec.ts b/packages/trilium-core/src/services/import/keep/importer.spec.ts
index 15761983e3..9dcb29cd60 100644
--- a/packages/trilium-core/src/services/import/keep/importer.spec.ts
+++ b/packages/trilium-core/src/services/import/keep/importer.spec.ts
@@ -56,6 +56,31 @@ describe("Google Keep importer — parseNote", () => {
);
});
+ it("prefers the rich-text body, converting basic formatting (textContentHtml over textContent)", () => {
+ const json = JSON.stringify({
+ textContent: "Bold",
+ textContentHtml: `<p dir="ltr" style="line-height:1.38;"><span style="font-weight:700;">Bold</span></p>`
+ });
+
+ const note = parseNote("note.json", json);
+
+ expect(note?.content).toBe("<p><strong>Bold</strong></p>");
+ });
+
+ it("prefers a checklist item's rich-text (textHtml over text)", () => {
+ const json = JSON.stringify({
+ listContent: [{ text: "done", textHtml: `<p><span style="font-style:italic;">done</span></p>`, isChecked: true }]
+ });
+
+ const note = parseNote("list.json", json);
+
+ expect(note?.content).toBe(
+ `<ul class="todo-list">` +
+ `<li><label class="todo-list__label"><input type="checkbox" checked="checked" disabled="disabled"><span class="todo-list__label__description"><i>done</i></span></label></li>` +
+ `</ul>`
+ );
+ });
+
it("uses distinct created/modified timestamps when both are present", () => {
const json = JSON.stringify({
textContent: "x",
diff --git a/packages/trilium-core/src/services/import/keep/importer.ts b/packages/trilium-core/src/services/import/keep/importer.ts
index cdf911b39a..e46fe21bff 100644
--- a/packages/trilium-core/src/services/import/keep/importer.ts
+++ b/packages/trilium-core/src/services/import/keep/importer.ts
@@ -18,22 +18,28 @@ import { t } from "i18next";
import type BNote from "../../../becca/entities/bnote.js";
import noteService from "../../notes.js";
import protectedSessionService from "../../protected_session.js";
+import { sanitizeHtml } from "../../sanitizer.js";
import type TaskContext from "../../task_context.js";
import dateUtils from "../../utils/date.js";
import { getZipProvider } from "../../zip_provider.js";
+import { convertKeepHtml, convertKeepHtmlInline } from "./converter.js";
/** A checklist row in a Keep note (`listContent`). */
interface KeepListItem {
text?: string;
+ /** Rich-text (basic formatting) variant of `text`; preferred when present. */
+ textHtml?: string;
isChecked?: boolean;
}
/** The subset of a Keep Takeout note JSON this iteration reads. */
interface KeepNote {
title?: string;
- /** Body of a plain-text note. */
+ /** Plain-text body of a text note; fallback when `textContentHtml` is absent. */
textContent?: string;
- /** Body of a checklist note; mutually exclusive with `textContent`. */
+ /** Rich-text (basic formatting) body of a text note; preferred when present. */
+ textContentHtml?: string;
+ /** Body of a checklist note; mutually exclusive with the text fields. */
listContent?: KeepListItem[];
/** Creation/last-edit timestamps, in microseconds since the Unix epoch. */
createdTimestampUsec?: number;
@@ -99,7 +105,11 @@ export function parseNote(path: string, json: string): ParsedNote | null {
};
}
-/** Builds a note's body HTML from its plain-text or checklist content (whichever is present). */
+/**
+ * Builds a note's body HTML from its checklist or text content (whichever is present). For both, Keep's
+ * rich-text variant (`textHtml`/`textContentHtml`, basic bold/italic/underline formatting) is preferred,
+ * falling back to the plain-text field. The result is sanitized downstream, in {@link createNotes}.
+ */
function buildContent(note: KeepNote): string {
if (note.listContent?.length) {
const items = note.listContent
@@ -107,11 +117,16 @@ function buildContent(note: KeepNote): string {
.map((item) => {
// Match the canonical CKEditor task-list serialization (checked before disabled).
const attributes = item.isChecked ? ` checked="checked" disabled="disabled"` : ` disabled="disabled"`;
- return `<li><label class="todo-list__label"><input type="checkbox"${attributes}><span class="todo-list__label__description">${escapeHtml(item.text ?? "")}</span></label></li>`;
+ const label = item.textHtml ? convertKeepHtmlInline(item.textHtml) : escapeHtml(item.text ?? "");
+ return `<li><label class="todo-list__label"><input type="checkbox"${attributes}><span class="todo-list__label__description">${label}</span></label></li>`;
});
return items.length ? `<ul class="todo-list">${items.join("")}</ul>` : "";
}
+ if (note.textContentHtml) {
+ return convertKeepHtml(note.textContentHtml);
+ }
+
if (note.textContent) {
return note.textContent
.split("\n")
@@ -136,7 +151,9 @@ function createNotes(importRootNote: BNote, notes: ParsedNote[], taskContext: Ta
const { note } = noteService.createNewNote({
parentNoteId: rootNote.noteId,
title: parsed.title,
- content: parsed.content,
+ // Keep's exported HTML is external content; sanitize before persisting (this also demotes the
+ // `<h1>` Keep uses for its top heading level, which Trilium reserves for the note title).
+ content: sanitizeHtml(parsed.content),
type: "text",
mime: "text/html",
isProtected