Skip to content

Build your personal knowledge base with Trilium Notes

client: add support for bulk conversion (text notes <> Markdown notes)

Adorian Doran3fa92be63f34
diff --git a/apps/client/src/services/bulk_action.spec.ts b/apps/client/src/services/bulk_action.spec.ts
index 125054b577..0d68ad9344 100644
--- a/apps/client/src/services/bulk_action.spec.ts
+++ b/apps/client/src/services/bulk_action.spec.ts
@@ -15,6 +15,7 @@ import RenameRelationBulkAction from "../widgets/bulk_actions/relation/rename_re
import DeleteRelationBulkAction from "../widgets/bulk_actions/relation/delete_relation";
import RenameNoteBulkAction from "../widgets/bulk_actions/note/rename_note";
import MoveNoteBulkAction from "../widgets/bulk_actions/note/move_note";
+import ConvertNoteBulkAction from "../widgets/bulk_actions/note/convert_note";
import DeleteNoteBulkAction from "../widgets/bulk_actions/note/delete_note";
import DeleteRevisionsBulkAction from "../widgets/bulk_actions/note/delete_revisions";
import ExecuteScriptBulkAction from "../widgets/bulk_actions/execute_script";
@@ -71,6 +72,7 @@ describe("bulk_action service", () => {
expect(bulkActionService.ACTION_GROUPS[2].actions).toEqual([
RenameNoteBulkAction,
MoveNoteBulkAction,
+ ConvertNoteBulkAction,
DeleteNoteBulkAction,
DeleteRevisionsBulkAction
]);
diff --git a/apps/client/src/services/bulk_action.ts b/apps/client/src/services/bulk_action.ts
index 742df632f0..745266aa21 100644
--- a/apps/client/src/services/bulk_action.ts
+++ b/apps/client/src/services/bulk_action.ts
@@ -13,6 +13,7 @@ import ExecuteScriptBulkAction from "../widgets/bulk_actions/execute_script.js";
import AddLabelBulkAction from "../widgets/bulk_actions/label/add_label.js";
import AddRelationBulkAction from "../widgets/bulk_actions/relation/add_relation.js";
import RenameNoteBulkAction from "../widgets/bulk_actions/note/rename_note.js";
+import ConvertNoteBulkAction from "../widgets/bulk_actions/note/convert_note.js";
import { t } from "./i18n.js";
import type FNote from "../entities/fnote.js";
import toast from "./toast.js";
@@ -29,7 +30,7 @@ export const ACTION_GROUPS = [
},
{
title: t("bulk_actions.notes"),
- actions: [RenameNoteBulkAction, MoveNoteBulkAction, DeleteNoteBulkAction, DeleteRevisionsBulkAction]
+ actions: [RenameNoteBulkAction, MoveNoteBulkAction, ConvertNoteBulkAction, DeleteNoteBulkAction, DeleteRevisionsBulkAction]
},
{
title: t("bulk_actions.other"),
@@ -50,7 +51,8 @@ const ACTION_CLASSES = [
AddRelationBulkAction,
UpdateLabelValueBulkAction,
UpdateRelationTargetBulkAction,
- ExecuteScriptBulkAction
+ ExecuteScriptBulkAction,
+ ConvertNoteBulkAction
];
async function addAction(noteId: string, actionName: string) {
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 8bf44827ad..12741c8664 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -709,6 +709,15 @@
"clone_note_new_parent": "clone note to the new parent if note has multiple clones/branches (it's not clear which branch should be removed)",
"nothing_will_happen": "nothing will happen if note cannot be moved to the target note (i.e. this would create a tree cycle)"
},
+ "convert_note": {
+ "convert_note": "Convert",
+ "convert_note_to": "Convert note",
+ "choose_conversion": "(choose a conversion)",
+ "conversion_htmlToMarkdown": "Text Notes → Markdown Notes",
+ "conversion_markdownToHtml": "Markdown Notes → Text Notes",
+ "help_text": "The conversion is applied only to notes matching the source type; other notes are left untouched. A revision of each converted note is saved beforehand.",
+ "warning": "Some formatting may be lost when converting notes and you may need to fix a few things afterwards. A revision of each converted note will be saved beforehand so you can restore it. Do you want to continue?"
+ },
"rename_note": {
"rename_note": "Rename note",
"rename_note_title_to": "Rename note title to",
diff --git a/apps/client/src/widgets/bulk_actions/abstract_bulk_action.ts b/apps/client/src/widgets/bulk_actions/abstract_bulk_action.ts
index 42a3f8d788..70cd9c1d0d 100644
--- a/apps/client/src/widgets/bulk_actions/abstract_bulk_action.ts
+++ b/apps/client/src/widgets/bulk_actions/abstract_bulk_action.ts
@@ -15,6 +15,7 @@ export interface ActionDefinition {
labelValue?: string;
oldLabelName?: string;
newLabelName?: string;
+ conversion?: string;
}
export default abstract class AbstractBulkAction {
@@ -29,6 +30,14 @@ export default abstract class AbstractBulkAction {
// to be overridden
abstract doRender(): VNode;
+ /**
+ * An optional message shown for confirmation before the batch is executed (e.g. to warn about
+ * a lossy operation). Returning `null` (the default) means the action runs without a prompt.
+ */
+ getConfirmationMessage(): string | null {
+ return null;
+ }
+
static get actionName() {
return "";
}
diff --git a/apps/client/src/widgets/bulk_actions/note/convert_note.tsx b/apps/client/src/widgets/bulk_actions/note/convert_note.tsx
new file mode 100644
index 0000000000..efe037a43c
--- /dev/null
+++ b/apps/client/src/widgets/bulk_actions/note/convert_note.tsx
@@ -0,0 +1,56 @@
+import { NOTE_CONVERSION_IDS, NoteConversionId } from "@triliumnext/commons";
+import { useEffect, useState } from "preact/hooks";
+
+import { t } from "../../../services/i18n";
+import FormSelect from "../../react/FormSelect";
+import { useSpacedUpdate } from "../../react/hooks";
+import AbstractBulkAction, { ActionDefinition } from "../abstract_bulk_action";
+import BulkAction from "../BulkAction";
+
+/** Human-readable label for each conversion id, in the order they appear in the combo box. */
+const CONVERSION_OPTIONS: { value: NoteConversionId | ""; title: string }[] = [
+ { value: "", title: t("convert_note.choose_conversion") },
+ ...NOTE_CONVERSION_IDS.map((value) => ({ value, title: t(`convert_note.conversion_${value}`) }))
+];
+
+function ConvertNoteBulkActionComponent({ bulkAction, actionDef }: { bulkAction: AbstractBulkAction, actionDef: ActionDefinition }) {
+ const [ conversion, setConversion ] = useState<string>(actionDef.conversion ?? "");
+ const spacedUpdate = useSpacedUpdate(() => bulkAction.saveAction({ conversion }));
+ useEffect(() => spacedUpdate.scheduleUpdate(), [ conversion ]);
+
+ return (
+ <BulkAction
+ bulkAction={bulkAction}
+ label={t("convert_note.convert_note_to")}
+ helpText={<p>{t("convert_note.help_text")}</p>}
+ >
+ <FormSelect
+ values={CONVERSION_OPTIONS}
+ keyProperty="value"
+ titleProperty="title"
+ currentValue={conversion}
+ onChange={setConversion}
+ />
+ </BulkAction>
+ );
+}
+
+export default class ConvertNoteBulkAction extends AbstractBulkAction {
+
+ doRender() {
+ return <ConvertNoteBulkActionComponent bulkAction={this} actionDef={this.actionDef} />;
+ }
+
+ getConfirmationMessage() {
+ // Only warn once a conversion has actually been selected.
+ return this.actionDef.conversion ? t("convert_note.warning") : null;
+ }
+
+ static get actionName() {
+ return "convertNote";
+ }
+
+ static get actionTitle() {
+ return t("convert_note.convert_note");
+ }
+}
diff --git a/apps/client/src/widgets/dialogs/bulk_actions.tsx b/apps/client/src/widgets/dialogs/bulk_actions.tsx
index cbb04a404a..f32227c0fb 100644
--- a/apps/client/src/widgets/dialogs/bulk_actions.tsx
+++ b/apps/client/src/widgets/dialogs/bulk_actions.tsx
@@ -7,6 +7,7 @@ import server from "../../services/server";
import FormCheckbox from "../react/FormCheckbox";
import Button from "../react/Button";
import bulk_action from "../../services/bulk_action";
+import dialog from "../../services/dialog";
import toast from "../../services/toast";
import RenameNoteBulkAction from "../bulk_actions/note/rename_note";
import FNote from "../../entities/fnote";
@@ -60,6 +61,14 @@ export default function BulkActionsDialog() {
footer={<Button text={t("bulk_actions.execute_bulk_actions")} kind="primary" />}
show={shown}
onSubmit={async () => {
+ // Let actions surface a confirmation prompt (e.g. lossy conversions) before executing.
+ const confirmMessages = existingActions
+ .map((action) => action.getConfirmationMessage())
+ .filter((message): message is string => !!message);
+ if (confirmMessages.length && !await dialog.confirm(confirmMessages.join("\n\n"))) {
+ return;
+ }
+
await server.post("bulk-action/execute", {
noteIds: selectedOrActiveNoteIds,
includeDescendants
diff --git a/packages/commons/src/lib/bulk_actions.ts b/packages/commons/src/lib/bulk_actions.ts
index d80c189741..f99d7c95e0 100644
--- a/packages/commons/src/lib/bulk_actions.ts
+++ b/packages/commons/src/lib/bulk_actions.ts
@@ -1,3 +1,12 @@
+/**
+ * The available note-format conversions, shared between the client (combo box options) and the
+ * server (the `convertNote` bulk action handler). Add a new entry here, a matching option label
+ * on the client, and a registry entry on the server to introduce a new conversion.
+ */
+export const NOTE_CONVERSION_IDS = ["htmlToMarkdown", "markdownToHtml"] as const;
+
+export type NoteConversionId = (typeof NOTE_CONVERSION_IDS)[number];
+
export type ActionHandlers = {
addLabel: {
labelName: string;
@@ -39,6 +48,9 @@ export type ActionHandlers = {
},
executeScript: {
script: string;
+ },
+ convertNote: {
+ conversion: NoteConversionId;
}
};
diff --git a/packages/trilium-core/src/services/bulk_actions.spec.ts b/packages/trilium-core/src/services/bulk_actions.spec.ts
index 5fd31fe41c..cf3a7bb2fb 100644
--- a/packages/trilium-core/src/services/bulk_actions.spec.ts
+++ b/packages/trilium-core/src/services/bulk_actions.spec.ts
@@ -356,4 +356,68 @@ describe("bulk_actions service (real DB)", () => {
expect(target.note.getOwnedLabelValue("valid")).toBe("ok");
});
});
+
+ describe("convertNote", () => {
+ function createMarkdownNote(): BNote {
+ counter++;
+ return getContext().init(() =>
+ noteService.createNewNote({
+ parentNoteId: "root",
+ title: `bulk-convert-md-${counter}`,
+ content: "# Heading",
+ type: "code",
+ mime: "text/x-markdown"
+ }).note
+ );
+ }
+
+ it("converts only notes matching the conversion's source type, skipping the rest", () => {
+ const textNote = createNote("root").note;
+ const markdownNote = createMarkdownNote();
+
+ getContext().init(() =>
+ bulkActionService.executeActions(
+ [{ name: "convertNote", conversion: "htmlToMarkdown" }],
+ [textNote.noteId, markdownNote.noteId]
+ )
+ );
+
+ // The text note is converted to a Markdown code note...
+ expect(textNote.type).toBe("code");
+ expect(textNote.mime).toBe("text/x-markdown");
+ // ...while the already-Markdown note is left untouched.
+ expect(markdownNote.type).toBe("code");
+ expect(markdownNote.getContent()).toBe("# Heading");
+ });
+
+ it("converts a Markdown note back to a text note", () => {
+ const markdownNote = createMarkdownNote();
+
+ getContext().init(() =>
+ bulkActionService.executeActions(
+ [{ name: "convertNote", conversion: "markdownToHtml" }],
+ [markdownNote.noteId]
+ )
+ );
+
+ expect(markdownNote.type).toBe("text");
+ expect(markdownNote.mime).toBe("text/html");
+ expect(markdownNote.getContent()).toContain("<h2>Heading</h2>");
+ });
+
+ it("does nothing for an unknown or unset conversion", () => {
+ const textNote = createNote("root").note;
+
+ expect(() =>
+ getContext().init(() =>
+ bulkActionService.executeActions(
+ [{ name: "convertNote", conversion: "" as never }],
+ [textNote.noteId]
+ )
+ )
+ ).not.toThrow();
+
+ expect(textNote.type).toBe("text");
+ });
+ });
});
diff --git a/packages/trilium-core/src/services/bulk_actions.ts b/packages/trilium-core/src/services/bulk_actions.ts
index b06e2549b0..6a407567c7 100644
--- a/packages/trilium-core/src/services/bulk_actions.ts
+++ b/packages/trilium-core/src/services/bulk_actions.ts
@@ -6,6 +6,7 @@ import becca from "../becca/becca.js";
import type BNote from "../becca/entities/bnote.js";
import cloningService from "./cloning.js";
import { getLog } from "./log";
+import noteFormatConversionService from "./note_format_conversion.js";
import { evaluateTemplate } from "./safe_template.js";
import { executeBundle } from "./script.js";
import { assertScriptingEnabled } from "./scripting_guard.js";
@@ -107,6 +108,10 @@ const ACTION_HANDLERS: ActionHandlerMap = {
getLog().info(`Moving/cloning note ${note.noteId} to ${action.targetParentNoteId} failed with error ${JSON.stringify(res)}`);
}
},
+ convertNote: (action, note) => {
+ // Only converts notes matching the conversion's expected source type; others are skipped.
+ noteFormatConversionService.convertNoteByConversionId(note, action.conversion);
+ },
executeScript: (action, note) => {
assertScriptingEnabled();
if (!action.script || !action.script.trim()) {
diff --git a/packages/trilium-core/src/services/note_format_conversion.ts b/packages/trilium-core/src/services/note_format_conversion.ts
index d6d09396a8..022c49b521 100644
--- a/packages/trilium-core/src/services/note_format_conversion.ts
+++ b/packages/trilium-core/src/services/note_format_conversion.ts
@@ -1,3 +1,4 @@
+import type { NoteConversionId } from "@triliumnext/commons";
import { t } from "i18next";
import { ValidationError } from "../errors.js";
@@ -11,6 +12,28 @@ const MARKDOWN_TARGET_MIME = "text/x-markdown";
type SourceFormat = "html" | "markdown";
+interface NoteConversion {
+ /** Whether `note` is the expected source type for this conversion. */
+ appliesTo: (note: BNote) => boolean;
+ sourceFormat: SourceFormat;
+}
+
+/**
+ * Registry of the available directed conversions, keyed by the id shared with the client via
+ * `@triliumnext/commons`. To add a conversion, add its id to `NOTE_CONVERSION_IDS` in commons and
+ * an entry here (plus the option label on the client).
+ */
+export const NOTE_CONVERSIONS: Record<NoteConversionId, NoteConversion> = {
+ htmlToMarkdown: {
+ appliesTo: (note) => note.type === "text",
+ sourceFormat: "html"
+ },
+ markdownToHtml: {
+ appliesTo: (note) => note.isMarkdown(),
+ sourceFormat: "markdown"
+ }
+};
+
interface ConversionResult {
content: string;
type: "text" | "code";
@@ -43,8 +66,9 @@ export function convertNoteContent(sourceFormat: SourceFormat, content: string,
/**
* 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.
+ * The direction is inferred from the note's current type. 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).
*/
@@ -59,18 +83,41 @@ export function convertNoteFormat(note: BNote): { type: string } {
throw new ValidationError(`Note '${note.noteId}' content is not available; a protected session may be required.`);
}
+ performConversion(note, isMarkdown ? "markdown" : "html");
+
+ return { type: isMarkdown ? "text" : "code" };
+}
+
+/**
+ * Applies a specific directed conversion (from the {@link NOTE_CONVERSIONS} registry) to a note,
+ * used by the `convertNote` bulk action. The note is left untouched (silently skipped) if it is
+ * not the expected source type or its content is unavailable, so a batch can target a mixed set.
+ */
+export function convertNoteByConversionId(note: BNote, conversionId: string): boolean {
+ const conversion = NOTE_CONVERSIONS[conversionId as NoteConversionId];
+
+ if (!conversion || !conversion.appliesTo(note) || !note.isContentAvailable()) {
+ return false;
+ }
+
+ performConversion(note, conversion.sourceFormat);
+ return true;
+}
+
+/** Saves the pre-conversion revision, transforms the content, and switches the note's type/mime. */
+function performConversion(note: BNote, sourceFormat: SourceFormat) {
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
+ const description = sourceFormat === "markdown"
? 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);
+ const { content: newContent, type, mime } = convertNoteContent(sourceFormat, content, note.title);
// Change the type/mime before writing content so type-specific processing (link extraction
// in `updateNoteData`) runs against the new format.
@@ -79,11 +126,10 @@ export function convertNoteFormat(note: BNote): { type: string } {
note.save();
noteService.updateNoteData(note.noteId, newContent);
-
- return { type };
}
export default {
convertNoteContent,
- convertNoteFormat
+ convertNoteFormat,
+ convertNoteByConversionId
};