Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
client: add support for converting text notes to Markdown and vice-versa
Adorian Doran62c7ad94980c
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 1641012b3f..8bf44827ad 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -908,6 +908,11 @@"convert_into_attachment_failed": "Converting note '{{title}}' failed.","convert_into_attachment_successful": "Note '{{title}}' has been converted to attachment.","convert_into_attachment_prompt": "Are you sure you want to convert note '{{title}}' into an attachment of the parent note?",+ "convert_to_markdown": "Convert to Markdown Note",+ "convert_to_text": "Convert to Text Note",+ "convert_format_warning": "Some formatting may be lost during the conversion and you may need to fix a few things afterwards. A revision of the current note will be saved beforehand so you can restore it. Do you want to continue?",+ "convert_to_markdown_successful": "Note has been converted to Markdown.",+ "convert_to_text_successful": "Note has been converted to a text note.","print_pdf": "Export as PDF...","export_as_image": "Export as image","export_as_image_png": "PNG (raster)",diff --git a/apps/client/src/widgets/ribbon/NoteActions.tsx b/apps/client/src/widgets/ribbon/NoteActions.tsxindex bd0f30147a..624b766409 100644--- a/apps/client/src/widgets/ribbon/NoteActions.tsx+++ b/apps/client/src/widgets/ribbon/NoteActions.tsx@@ -187,6 +187,8 @@ export function NoteContextMenu({ note, noteContext, itemsAtStart, itemsNearNote<CommandItem command="openNoteExternally" icon="bx bx-file-find" disabled={isSearchOrBook || !isElectron} text={t("note_actions.open_note_externally")} title={t("note_actions.open_note_externally_title")} /><CommandItem command="openNoteCustom" icon="bx bx-customize" disabled={isSearchOrBook || isMac || !isElectron} text={t("note_actions.open_note_custom")} /><CommandItem command="showNoteSource" icon="bx bx-code" disabled={!hasSource} text={t("note_actions.note_source")} />+ {(note.type === "text" || note.isMarkdown()) && isContentAvailable && !isInOptionsOrHelp &&+ <ConvertNoteFormat note={note} />}<CommandItem command="showNoteOCRText" icon="bx bx-text" disabled={!["image", "file"].includes(noteType)} text={t("note_actions.view_ocr_text")} />{(syncServerHost && isElectron) &&<CommandItem command="openNoteOnServer" icon="bx bx-world" disabled={!syncServerHost} text={t("note_actions.open_note_on_server")} />@@ -383,6 +385,27 @@ function ConvertToAttachment({ note }: { note: FNote }) {);}+function ConvertNoteFormat({ note }: { note: FNote }) {+ const isMarkdown = note.isMarkdown();++ return (+ <FormListItem+ icon="bx bxl-markdown"+ onClick={async () => {+ if (!(await dialog.confirm(t("note_actions.convert_format_warning")))) {+ return;+ }++ await server.post(`notes/${note.noteId}/convert-format`);+ await ws.waitForMaxKnownEntityChangeId();+ toast.showMessage(isMarkdown+ ? t("note_actions.convert_to_text_successful")+ : t("note_actions.convert_to_markdown_successful"));+ }}+ >{isMarkdown ? t("note_actions.convert_to_text") : t("note_actions.convert_to_markdown")}</FormListItem>+ );+}+function ExportAsImage({ ntxId, parentComponent }: { ntxId: string | null | undefined, parentComponent: Component | null | undefined }) {return (<FormDropdownSubmenudiff --git a/apps/server/src/assets/translations/en/server.json b/apps/server/src/assets/translations/en/server.jsonindex 48e09b581c..5b18df2760 100644--- a/apps/server/src/assets/translations/en/server.json+++ b/apps/server/src/assets/translations/en/server.json@@ -311,6 +311,10 @@"duplicate-note-suffix": "(dup)","duplicate-note-title": "{{- noteTitle }} {{ duplicateNoteSuffix }}"},+ "note_conversion": {+ "revision_before_markdown": "Before conversion to Markdown",+ "revision_before_text": "Before conversion to Text Note"+ },"backend_log": {"log-does-not-exist": "The backend log file '{{ fileName }}' does not exist (yet).","reading-log-failed": "Reading the backend log file '{{ fileName }}' failed."diff --git a/packages/trilium-core/src/routes/api/notes.ts b/packages/trilium-core/src/routes/api/notes.tsindex 6c6242cb75..68a731a44c 100644--- a/packages/trilium-core/src/routes/api/notes.ts+++ b/packages/trilium-core/src/routes/api/notes.ts@@ -7,6 +7,7 @@ import { ValidationError } from "../../errors.js";import becca from "../../becca/becca.js";import type BBranch from "../../becca/entities/bbranch.js";import { getLog } from "../../services/log.js";+import noteFormatConversionService from "../../services/note_format_conversion.js";import noteService from "../../services/notes.js";import { getSql } from "../../services/sql/index";import TaskContext from "../../services/task_context.js";@@ -368,6 +369,13 @@ function convertNoteToAttachment(req: Request<{ noteId: string }>) {};}+function convertNoteFormat(req: Request<{ noteId: string }>) {+ const { noteId } = req.params;+ const note = becca.getNoteOrThrow(noteId);++ return noteFormatConversionService.convertNoteFormat(note);+}+export default {getNote,getNoteBlob,@@ -385,5 +393,6 @@ export default {eraseUnusedAttachmentsNow,getDeleteNotesPreview,forceSaveRevision,- convertNoteToAttachment+ convertNoteToAttachment,+ convertNoteFormat};diff --git a/packages/trilium-core/src/routes/index.ts b/packages/trilium-core/src/routes/index.tsindex 7df95e6fed..b4a818b349 100644--- a/packages/trilium-core/src/routes/index.ts+++ b/packages/trilium-core/src/routes/index.ts@@ -67,6 +67,7 @@ export function buildSharedApiRoutes({ route, asyncRoute, apiRoute, asyncApiRoutapiRoute(GET, "/api/options/user-themes", optionsApiRoute.getUserThemes);apiRoute(PST, "/api/notes/:noteId/convert-to-attachment", notesApiRoute.convertNoteToAttachment);+ apiRoute(PST, "/api/notes/:noteId/convert-format", notesApiRoute.convertNoteFormat);apiRoute(GET, "/api/notes/:noteId", notesApiRoute.getNote);apiRoute(GET, "/api/notes/:noteId/blob", notesApiRoute.getNoteBlob);apiRoute(GET, "/api/notes/:noteId/metadata", notesApiRoute.getNoteMetadata);diff --git a/packages/trilium-core/src/services/note_format_conversion.spec.ts b/packages/trilium-core/src/services/note_format_conversion.spec.tsnew file mode 100644index 0000000000..121c691673--- /dev/null+++ b/packages/trilium-core/src/services/note_format_conversion.spec.ts@@ -0,0 +1,100 @@+import { trimIndentation } from "@triliumnext/commons";+import { describe, expect, it } from "vitest";++import { getContext } from "./context.js";+import { convertNoteContent, convertNoteFormat } from "./note_format_conversion.js";+import noteService from "./notes.js";++describe("note format conversion", () => {+ it("converts an HTML text note to a Markdown code note", () => {+ const { content, type, mime } = convertNoteContent(+ "html",+ "<h1>Title</h1><p>Some <strong>bold</strong> text.</p><ul><li>one</li><li>two</li></ul>",+ "My note"+ );++ expect(type).toBe("code");+ expect(mime).toBe("text/x-markdown");+ expect(content).toBe(trimIndentation`\+ # Title++ Some **bold** text.++ * one+ * two`);+ });++ it("converts a Markdown code note to an HTML text note", () => {+ const { content, type, mime } = convertNoteContent(+ "markdown",+ trimIndentation`\+ # Title++ Some **bold** text.`,+ "My note"+ );++ expect(type).toBe("text");+ expect(mime).toBe("text/html");+ // Trilium reserves H1 for the note title, so top-level Markdown headings render as <h2>.+ expect(content).toContain("<h2>Title</h2>");+ expect(content).toContain("<strong>bold</strong>");+ });++ it("preserves structure across an HTML -> Markdown -> HTML round-trip", () => {+ const original = "<h2>Heading</h2><p>Paragraph with a <a href=\"https://example.com\">link</a>.</p>";++ const { content: markdown } = convertNoteContent("html", original, "title");+ const { content: html } = convertNoteContent("markdown", markdown, "title");++ expect(html).toContain("<h2>Heading</h2>");+ expect(html).toContain("<a href=\"https://example.com\">link</a>");+ });+});++describe("note format conversion (real DB)", () => {+ let counter = 0;++ function createTextNote() {+ counter++;+ return getContext().init(() =>+ noteService.createNewNote({+ parentNoteId: "root",+ title: `convert-spec-${counter}`,+ content: "<h2>Heading</h2><p>Some <strong>bold</strong> text.</p>",+ type: "text"+ }).note+ );+ }++ it("flips a text note to Markdown, saves a named revision, and converts back", () => {+ const note = createTextNote();+ const revisionsBefore = note.getRevisions().length;++ getContext().init(() => convertNoteFormat(note));++ expect(note.type).toBe("code");+ expect(note.mime).toBe("text/x-markdown");+ expect(note.getContent()).toContain("## Heading");++ const revisions = note.getRevisions();+ expect(revisions.length).toBe(revisionsBefore + 1);+ const toMarkdownRevision = revisions.at(-1);+ expect(toMarkdownRevision?.source).toBe("manual");+ expect(toMarkdownRevision?.type).toBe("text"); // captured the pre-conversion state+ const markdownDescription = toMarkdownRevision?.description;++ // Convert back to a text note.+ getContext().init(() => convertNoteFormat(note));++ expect(note.type).toBe("text");+ expect(note.mime).toBe("text/html");+ expect(note.getContent()).toContain("<h2>Heading</h2>");++ // The two directions save distinctly-named revisions.+ const textDescription = note.getRevisions().at(-1)?.description;+ expect(markdownDescription).toBeTruthy();+ expect(textDescription).toBeTruthy();+ expect(textDescription).not.toBe(markdownDescription);+ });+});diff --git a/packages/trilium-core/src/services/note_format_conversion.ts b/packages/trilium-core/src/services/note_format_conversion.tsnew file mode 100644index 0000000000..d6d09396a8--- /dev/null+++ b/packages/trilium-core/src/services/note_format_conversion.ts@@ -0,0 +1,89 @@+import { t } from "i18next";++import { ValidationError } from "../errors.js";+import mdExportService from "./export/markdown.js";+import markdownImportService from "./import/markdown.js";+import noteService from "./notes.js";+import type BNote from "../becca/entities/bnote.js";++/** The MIME used for the Markdown note type, matching the note-type registry (`NOTE_TYPES`). */+const MARKDOWN_TARGET_MIME = "text/x-markdown";++type SourceFormat = "html" | "markdown";++interface ConversionResult {+ content: string;+ type: "text" | "code";+ mime: string;+}++/**+ * Pure content + type transform between an HTML text note and a Markdown code note.+ *+ * The direction is determined by `sourceFormat`. This function holds no Becca state, so it+ * can be unit-tested directly. The orchestration (revision, persistence) lives in+ * {@link convertNoteFormat}.+ */+export function convertNoteContent(sourceFormat: SourceFormat, content: string, title: string): ConversionResult {+ if (sourceFormat === "html") {+ return {+ content: mdExportService.toMarkdown(content),+ type: "code",+ mime: MARKDOWN_TARGET_MIME+ };+ }++ return {+ content: markdownImportService.renderToHtml(content, title),+ type: "text",+ mime: "text/html"+ };+}++/**+ * Converts a note in place between an HTML text note and a Markdown code note.+ *+ * A named revision capturing the pre-conversion state is saved first, so the conversion —+ * which is lossy in the HTML→Markdown direction — remains reversible.+ *+ * Must be called within a CLS context (Express routes already provide one).+ */+export function convertNoteFormat(note: BNote): { type: string } {+ const isMarkdown = note.isMarkdown();++ if (note.type !== "text" && !isMarkdown) {+ throw new ValidationError(`Note '${note.noteId}' of type '${note.type}' cannot be converted between HTML and Markdown.`);+ }++ if (!note.isContentAvailable()) {+ throw new ValidationError(`Note '${note.noteId}' content is not available; a protected session may be required.`);+ }++ const content = note.getContent();+ if (typeof content !== "string") {+ throw new ValidationError(`Note '${note.noteId}' does not have textual content.`);+ }++ // Snapshot the current (pre-conversion) state under a descriptive name.+ const description = isMarkdown+ ? t("note_conversion.revision_before_text")+ : t("note_conversion.revision_before_markdown");+ note.saveRevision({ description, source: "manual" });++ const { content: newContent, type, mime } = convertNoteContent(isMarkdown ? "markdown" : "html", content, note.title);++ // Change the type/mime before writing content so type-specific processing (link extraction+ // in `updateNoteData`) runs against the new format.+ note.type = type;+ note.mime = mime;+ note.save();++ noteService.updateNoteData(note.noteId, newContent);++ return { type };+}++export default {+ convertNoteContent,+ convertNoteFormat+};