Skip to content

Build your personal knowledge base with Trilium Notes

feat(text): spike a Mermaid diagram embed, the counterpart of the drawing canvas

Elian Dorandf3b3385dc6f
diff --git a/apps/client/src/services/content_renderer.ts b/apps/client/src/services/content_renderer.ts
index e430a13980..ab3a77d3ca 100644
--- a/apps/client/src/services/content_renderer.ts
+++ b/apps/client/src/services/content_renderer.ts
@@ -168,6 +168,7 @@ const ATTACHED_CODE_MIME_TYPES = new Set([
*/
const PREVIEWED_TYPES = new Set([
"book", "search", "text", "markdown", "code", "iconPack", "image", "canvas", "canvasDrawing",
+ "mermaidDiagram",
"mindMap", "spreadsheet", "office", "pdf", "audio", "video", "mermaid", "render", "doc",
"llmChat"
]);
@@ -208,6 +209,8 @@ export async function getRenderedContent(this: {} | { ctx: string }, entity: FNo
await renderIconPack(entity, $renderedContent, options);
} else if (type === "canvasDrawing") {
await renderCanvasDrawing(entity, $renderedContent, options);
+ } else if (type === "mermaidDiagram") {
+ await renderMermaidDiagram(entity, $renderedContent, options);
} else if (type === "image" && options.mediaEnvironment === "embedded") {
await renderImageViewer(entity, $renderedContent);
} else if (["image", "canvas", "mermaid", "mindMap", "spreadsheet"].includes(type)) {
@@ -292,6 +295,7 @@ export const CONTENT_RENDERERS = {
image: () => import("../widgets/react/ImageViewer"),
file: {
canvasDrawing: () => import("../widgets/type_widgets/canvas/CanvasDrawing"),
+ mermaidDiagram: () => import("../widgets/type_widgets/mermaid/MermaidDiagram"),
pdf: () => import("../widgets/type_widgets/file/PdfViewer"),
media: () => import("../widgets/type_widgets/file/MediaPreview")
},
@@ -586,6 +590,27 @@ async function renderCanvasDrawing(
}
}
+/**
+ * Renders a Mermaid diagram kept in a file or an attachment, in a zoom/pan viewer. Interactive
+ * content of an attachment is edited beside the diagram while the Editable toggle of its embed is on.
+ */
+async function renderMermaidDiagram(
+ entity: FNote | FAttachment,
+ $renderedContent: JQuery<HTMLElement>,
+ options: RenderOptions
+) {
+ const { default: MermaidDiagram } = await CONTENT_RENDERERS.file.mermaidDiagram();
+ const editor = options.interactive ? getContentEditor(entity, options) : undefined;
+ const content = editor?.getUnsavedContent() ?? (await entity.getBlob())?.content ?? "";
+
+ const $container = $('<div class="mermaid-diagram-embed">');
+ const container = $container.get(0);
+ if (container) {
+ await mountInteractiveWidget(h(MermaidDiagram, { entity, editor, content }), container);
+ }
+ $renderedContent.append($container);
+}
+
function getImageUrl(entity: FNote | FAttachment) {
if (entity instanceof FNote) {
return getNoteImageUrl(entity.noteId, entity.title, String(Math.random()));
diff --git a/apps/client/src/services/mermaid.ts b/apps/client/src/services/mermaid.ts
index 6e598f76c7..dc645681e0 100644
--- a/apps/client/src/services/mermaid.ts
+++ b/apps/client/src/services/mermaid.ts
@@ -6,6 +6,25 @@ export function getMermaidConfig(): MermaidConfig {
return getSharedMermaidConfig(parseMermaidTheme(documentStyle.getPropertyValue("--mermaid-theme")));
}
+let renderId = 0;
+
+/** Renders the Mermaid `source` to an SVG string, or `""` for empty source. Throws on bad syntax. */
+export async function renderMermaidSvg(source: string) {
+ if (!source.trim()) {
+ return "";
+ }
+
+ const mermaid = (await import("mermaid")).default;
+ mermaid.initialize({
+ startOnLoad: false,
+ ...(getMermaidConfig() as any),
+ });
+
+ renderId++;
+ const { svg } = await mermaid.render(`mermaid-graph-${renderId}`, source);
+ return postprocessMermaidSvg(svg);
+}
+
/**
* Processes the output of a Mermaid SVG render before it should be delivered to the user.
*
diff --git a/apps/client/src/stylesheets/style.css b/apps/client/src/stylesheets/style.css
index a5ea9e24ea..2f1e0fbba3 100644
--- a/apps/client/src/stylesheets/style.css
+++ b/apps/client/src/stylesheets/style.css
@@ -1115,7 +1115,8 @@ body.mobile .modal-content-with-sidebar > .modal-main > .modal-header > .modal-t
/* Media takes a resized height inside the border and padding, as with the edge-to-edge types. */
.include-note[data-box-size] .include-note-content:is(
- .type-image, .type-canvas, .type-canvasDrawing, .type-mindMap, .type-spreadsheet, .type-mermaid,
+ .type-image, .type-canvas, .type-canvasDrawing, .type-mermaidDiagram, .type-mindMap,
+ .type-spreadsheet, .type-mermaid,
.type-video
) {
box-sizing: content-box;
@@ -1373,6 +1374,7 @@ body.mobile .modal-content-with-sidebar > .modal-main > .modal-header > .modal-t
.include-note-content.type-video,
.include-note-content.type-canvas,
.include-note-content.type-canvasDrawing,
+.include-note-content.type-mermaidDiagram,
.include-note-content.type-webView,
.include-note-content.type-book:has(.note-list-widget.full-height),
.include-note-content.type-search:has(.note-list-widget.full-height) {
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 10c3d5542a..fbb528f2bb 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -4526,6 +4526,8 @@
"drawing-canvas": "Drawing canvas",
"editable": "Editable",
"insert-a-canvas-to-draw-on": "Insert a canvas to draw on.",
+ "mermaid-diagram-embedded": "Mermaid diagram (embedded)",
+ "insert-a-mermaid-diagram-stored-as-an-attachment": "Insert a Mermaid diagram stored as an attachment.",
"tabs": "Tabs",
"tab-title": "Tab title",
"tab-0": "Tab %0",
diff --git a/apps/client/src/widgets/type_widgets/code/CodeEmbed.tsx b/apps/client/src/widgets/type_widgets/code/CodeEmbed.tsx
index f135308f2c..32ef40d8c4 100644
--- a/apps/client/src/widgets/type_widgets/code/CodeEmbed.tsx
+++ b/apps/client/src/widgets/type_widgets/code/CodeEmbed.tsx
@@ -92,9 +92,9 @@ function SaveStatus({ rootRef, editor, isShown }: SaveStatusProps) {
* Shows the content of `entity` each time it saves, also when another embed of it saved it.
* Unsaved changes made in the embed are kept, and replace that content when they save.
*/
-function useSavedContent(
+export function useSavedContent(
entity: FNote | FAttachment,
- editor: ContentEditor,
+ editor: ContentEditor | undefined,
setContent: (content: string) => void
) {
const noteBlob = useNoteBlob(entity instanceof FNote ? entity : null);
@@ -116,7 +116,7 @@ function useSavedContent(
});
useEffect(() => {
- if (content !== undefined && editor.getUnsavedContent() === undefined) {
+ if (content !== undefined && editor?.getUnsavedContent() === undefined) {
setContent(content);
}
}, [ content ]);
diff --git a/apps/client/src/widgets/type_widgets/code/CodeEmbedEditor.tsx b/apps/client/src/widgets/type_widgets/code/CodeEmbedEditor.tsx
index e587778f6d..4f9b82b43b 100644
--- a/apps/client/src/widgets/type_widgets/code/CodeEmbedEditor.tsx
+++ b/apps/client/src/widgets/type_widgets/code/CodeEmbedEditor.tsx
@@ -15,11 +15,15 @@ export interface CodeEmbedEditorProps {
mime: string;
/** Receives the edited content when the editor goes away. */
onClose: (content: string) => void;
+ /** Receives the content as it is edited. */
+ onChange?: (content: string) => void;
+ /** Called with CodeMirror once it mounts, for extensions such as a linter. */
+ onReady?: (view: VanillaCodeMirror) => void;
}
/** CodeMirror over the content of a code embed, which `editor` saves as it changes. */
export default function CodeEmbedEditor({
- note, editor, content, mime, onClose
+ note, editor, content, mime, onClose, onChange, onReady
}: CodeEmbedEditorProps) {
const viewRef = useRef<VanillaCodeMirror>(null);
const isLoadingRef = useRef(false);
@@ -40,6 +44,12 @@ export default function CodeEmbedEditor({
view.clearHistory();
}, [ content ]);
+ useEffect(() => {
+ if (viewRef.current) {
+ onReady?.(viewRef.current);
+ }
+ }, []);
+
// A layout cleanup runs during the unmount, before CodeMirror is destroyed.
useLayoutEffect(() => () => {
const text = viewRef.current?.getText();
@@ -59,6 +69,7 @@ export default function CodeEmbedEditor({
onContentChanged={() => {
if (!isLoadingRef.current) {
editor.scheduleSave(() => viewRef.current?.getText() ?? "");
+ onChange?.(viewRef.current?.getText() ?? "");
}
}}
{...(noteTabWidth != null && { indentSize: noteTabWidth })}
diff --git a/apps/client/src/widgets/type_widgets/mermaid/Mermaid.tsx b/apps/client/src/widgets/type_widgets/mermaid/Mermaid.tsx
index 19be7b050e..56f91018bd 100644
--- a/apps/client/src/widgets/type_widgets/mermaid/Mermaid.tsx
+++ b/apps/client/src/widgets/type_widgets/mermaid/Mermaid.tsx
@@ -3,33 +3,14 @@ import { NOTE_TYPE_IMAGE_ATTACHMENTS } from "@triliumnext/commons";
import { useCallback } from "preact/hooks";
import { t } from "../../../services/i18n";
-import { getMermaidConfig, postprocessMermaidSvg } from "../../../services/mermaid";
+import { renderMermaidSvg } from "../../../services/mermaid";
import NoteContentSwitcher from "../../layout/NoteContentSwitcher";
import SvgSplitEditor from "../helpers/SvgSplitEditor";
import { TypeWidgetProps } from "../type_widget";
import mermaidLinter from "../linters/mermaid";
import SAMPLE_DIAGRAMS from "./sample_diagrams";
-let idCounter = 1;
-
export default function Mermaid(props: TypeWidgetProps) {
- const renderSvg = useCallback(async (content: string) => {
- const mermaid = (await import("mermaid")).default;
-
- if (!content.trim()) {
- return "";
- }
-
- mermaid.initialize({
- startOnLoad: false,
- ...(getMermaidConfig() as any),
- });
-
- idCounter++;
- const { svg } = await mermaid.render(`mermaid-graph-${idCounter}`, content);
- return postprocessMermaidSvg(svg);
- }, []);
-
// Attach the Mermaid lint extension once the underlying CodeMirror editor is ready.
const setupEditor = useCallback((editor: CodeMirror | null) => {
editor?.setNamedExtension("mermaid-lint", mermaidLinter());
@@ -38,7 +19,7 @@ export default function Mermaid(props: TypeWidgetProps) {
return (
<SvgSplitEditor
attachmentTitle={NOTE_TYPE_IMAGE_ATTACHMENTS.mermaid}
- renderSvg={renderSvg}
+ renderSvg={renderMermaidSvg}
editorRef={setupEditor}
noteType="mermaid"
extraContent={(
diff --git a/apps/client/src/widgets/type_widgets/mermaid/MermaidDiagram.css b/apps/client/src/widgets/type_widgets/mermaid/MermaidDiagram.css
new file mode 100644
index 0000000000..1bd274e06a
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/mermaid/MermaidDiagram.css
@@ -0,0 +1,71 @@
+.mermaid-diagram {
+ display: flex;
+ height: var(--include-note-height, 20em);
+ text-align: start;
+
+ > .mermaid-diagram-source {
+ flex: 1 1 50%;
+ min-width: 0;
+ overflow: auto;
+ border-inline-end: 1px solid var(--main-border-color);
+
+ pre.code-embed-editor {
+ height: 100%;
+ margin: 0;
+ padding: 0;
+ }
+ }
+
+ > .mermaid-diagram-preview {
+ position: relative;
+ flex: 1 1 50%;
+ min-width: 0;
+ outline: none;
+ }
+
+ .mermaid-diagram-viewport,
+ .mermaid-diagram-content,
+ .render-container {
+ width: 100%;
+ height: 100%;
+ }
+
+ .render-container svg {
+ width: 100%;
+ height: 100%;
+ max-width: 100% !important;
+ }
+
+ .mermaid-diagram-preview.on-error .render-container {
+ opacity: 0.4;
+ }
+
+ .mermaid-diagram-error {
+ position: absolute;
+ inset-block-end: 0;
+ inset-inline: 0;
+ margin: 0.5em;
+ padding: 0.5em 0.75em;
+ max-height: 50%;
+ overflow: auto;
+ border-radius: 6px;
+ background-color: var(--main-background-color);
+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
+ font-family: var(--monospace-font-family);
+ font-size: 0.85em;
+ white-space: pre-wrap;
+ }
+}
+
+.include-note-content:fullscreen .mermaid-diagram {
+ height: 100%;
+}
+
+body.mobile .mermaid-diagram.editing {
+ flex-direction: column;
+
+ > .mermaid-diagram-source {
+ border-inline-end: none;
+ border-block-end: 1px solid var(--main-border-color);
+ }
+}
diff --git a/apps/client/src/widgets/type_widgets/mermaid/MermaidDiagram.tsx b/apps/client/src/widgets/type_widgets/mermaid/MermaidDiagram.tsx
new file mode 100644
index 0000000000..3011a4d695
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/mermaid/MermaidDiagram.tsx
@@ -0,0 +1,268 @@
+import "./MermaidDiagram.css";
+
+import type VanillaCodeMirror from "@triliumnext/codemirror";
+import { MERMAID_ATTACHMENT_MIME } from "@triliumnext/commons";
+import fullscreenIcon from "boxicons/svg/regular/bx-fullscreen.svg?raw";
+import zoomInIcon from "boxicons/svg/regular/bx-zoom-in.svg?raw";
+import zoomOutIcon from "boxicons/svg/regular/bx-zoom-out.svg?raw";
+import clsx from "clsx";
+import type { RefObject } from "preact";
+import { lazy, Suspense } from "preact/compat";
+import { useCallback, useEffect, useRef, useState } from "preact/hooks";
+import { TransformComponent, TransformWrapper } from "react-zoom-pan-pinch";
+
+import type FAttachment from "../../../entities/fattachment";
+import FNote from "../../../entities/fnote";
+import type { ContentEditor } from "../../../services/content_renderer";
+import { t } from "../../../services/i18n";
+import { renderMermaidSvg } from "../../../services/mermaid";
+import OverlayControlGroup, { ZoomControls } from "../../react/OverlayControlGroup";
+import { RawHtmlBlock } from "../../react/RawHtml";
+import { useZoomPanPinch, useZoomPanWheel } from "../../react/zoom_pan";
+import { useZoomPanKeyboard, ZOOM_PAN_VIEWPORT_CLASS } from "../../react/zoom_pan_keyboard";
+import { useSavedContent } from "../code/CodeEmbed";
+import mermaidLinter from "../linters/mermaid";
+import {
+ type ContentEmbedTool,
+ type ContentEmbedToolbarItem,
+ type ContentEmbedToolProvider,
+ showContentEmbedFullscreen
+} from "../text/content_embed_tools";
+import { useEditableEmbed } from "../text/editable_embed";
+
+const CodeEmbedEditor = lazy(() => import("../code/CodeEmbedEditor"));
+
+interface MermaidDiagramProps {
+ entity: FNote | FAttachment;
+ /** Saves the changes. Without it the diagram is read-only. */
+ editor?: ContentEditor;
+ /** The source shown first. */
+ content: string;
+}
+
+/**
+ * A Mermaid diagram in an embed, shown in a zoom/pan viewer, and edited in CodeMirror beside it
+ * while the Editable toggle of its embed is on. The zoom and fullscreen are buttons of the toolbar
+ * of the embed.
+ */
+export default function MermaidDiagram({ entity, editor, content: initialContent }: MermaidDiagramProps) {
+ const rootRef = useRef<HTMLDivElement>(null);
+ const [ previewEl, setPreviewEl ] = useState<HTMLDivElement | null>(null);
+ const [ source, setSource ] = useState(initialContent);
+ const { svg, error } = useMermaidRender(source);
+
+ const zoom = useZoomPanPinch({ minScale: MIN_ZOOM, maxScale: MAX_ZOOM });
+ const [ tools ] = useState(() => new MermaidDiagramTools(rootRef));
+ tools.setZoom(zoom);
+ const { canEdit, isEditing } = useEditableEmbed(rootRef, {
+ editor,
+ note: entity instanceof FNote ? entity : null,
+ tools,
+ focusTarget: ".cm-content"
+ });
+
+ useSavedContent(entity, editor, setSource);
+ useZoomPanKeyboard(zoom.ref, previewEl);
+ useZoomPanWheel(zoom.ref, previewEl, true);
+
+ const setupEditor = useCallback((view: VanillaCodeMirror) => {
+ view.setNamedExtension("mermaid-lint", mermaidLinter());
+ }, []);
+
+ const preview = (
+ <div
+ ref={setPreviewEl}
+ tabIndex={0}
+ role="group"
+ aria-label={t("svg.preview")}
+ className={clsx("mermaid-diagram-preview", ZOOM_PAN_VIEWPORT_CLASS, error && "on-error")}
+ >
+ <TransformWrapper
+ ref={zoom.ref}
+ minScale={MIN_ZOOM}
+ maxScale={MAX_ZOOM}
+ centerOnInit
+ centerZoomedOut
+ wheel={zoom.wheel}
+ doubleClick={{ mode: "reset" }}
+ onTransform={zoom.onTransform}
+ >
+ <TransformComponent
+ wrapperClass="mermaid-diagram-viewport"
+ contentClass="mermaid-diagram-content"
+ >
+ <RawHtmlBlock className="render-container" html={svg} />
+ </TransformComponent>
+ </TransformWrapper>
+ {error && <div className="mermaid-diagram-error">{error}</div>}
+ {!canEdit && (
+ <OverlayControlGroup className="mermaid-diagram-controls" placement="bottom-end">
+ <ZoomControls
+ percent={zoom.scale * 100}
+ canZoomIn={zoom.canZoomIn}
+ canZoomOut={zoom.canZoomOut}
+ onZoomIn={zoom.zoomIn}
+ onZoomOut={zoom.zoomOut}
+ onReset={zoom.reset}
+ />
+ </OverlayControlGroup>
+ )}
+ </div>
+ );
+
+ return (
+ <div ref={rootRef} className={clsx("mermaid-diagram", isEditing && "editing")}>
+ {isEditing && editor && (
+ <div className="mermaid-diagram-source">
+ <Suspense fallback={null}>
+ <CodeEmbedEditor
+ note={null}
+ editor={editor}
+ content={source}
+ mime={MERMAID_ATTACHMENT_MIME}
+ onClose={setSource}
+ onChange={setSource}
+ onReady={setupEditor}
+ />
+ </Suspense>
+ </div>
+ )}
+ {preview}
+ </div>
+ );
+}
+
+/**
+ * The SVG of the Mermaid `source`, rendered a moment after it stops changing. While the source
+ * fails to render, `error` holds why and `svg` keeps the last diagram that rendered.
+ */
+function useMermaidRender(source: string) {
+ const [ svg, setSvg ] = useState("");
+ const [ error, setError ] = useState<string | null>(null);
+ const isFirstRender = useRef(true);
+
+ useEffect(() => {
+ let isCurrent = true;
+ const delay = isFirstRender.current ? 0 : RENDER_DELAY;
+ isFirstRender.current = false;
+
+ const timeout = setTimeout(async () => {
+ try {
+ const rendered = await renderMermaidSvg(source);
+ if (!isCurrent) return;
+ setSvg(rendered);
+ setError(null);
+ } catch (e) {
+ if (!isCurrent) return;
+ setError((e as Error)?.message ?? String(e));
+ }
+ }, delay);
+
+ return () => {
+ isCurrent = false;
+ clearTimeout(timeout);
+ };
+ }, [ source ]);
+
+ return { svg, error };
+}
+
+type ZoomState = ReturnType<typeof useZoomPanPinch>;
+
+/** The zoom and fullscreen of a Mermaid diagram, as buttons of the toolbar of its embed. */
+class MermaidDiagramTools implements ContentEmbedToolProvider {
+ readonly hiddenToolbarItems: readonly ContentEmbedToolbarItem[] = [
+ "contentEmbedBoxSizeDropdown", "toggleContentEmbedTitle", "convertEmbedToLink"
+ ];
+ readonly hasEditableFlag = true;
+ private zoom: ZoomState | null = null;
+ private listeners = new Set<() => void>();
+ private shownTools = "";
+
+ constructor(private readonly rootRef: RefObject<HTMLElement | null>) {}
+
+ /** Follows the zoom state of the latest render. */
+ setZoom(zoom: ZoomState) {
+ this.zoom = zoom;
+ // Notifies after the render, as a listener updates the toolbar of the editor.
+ queueMicrotask(() => this.update());
+ }
+
+ getTools(): ContentEmbedTool[] {
+ const zoom = this.zoom;
+ if (!zoom) return [];
+
+ return [
+ {
+ id: "zoomOut",
+ label: t("zoom_controls.zoom_out"),
+ icon: zoomOutIcon,
+ isEnabled: zoom.canZoomOut,
+ group: "zoom"
+ },
+ {
+ id: "resetZoom",
+ label: t("zoom_controls.reset"),
+ text: `${Math.round(zoom.scale * 100)}%`,
+ group: "zoom"
+ },
+ {
+ id: "zoomIn",
+ label: t("zoom_controls.zoom_in"),
+ icon: zoomInIcon,
+ isEnabled: zoom.canZoomIn,
+ group: "zoom"
+ },
+ ...this.getFullscreenTools()
+ ];
+ }
+
+ execute(id: string) {
+ const zoom = this.zoom;
+ if (id === "fullscreen") {
+ showContentEmbedFullscreen(this.rootRef.current);
+ } else if (id === "zoomOut") {
+ zoom?.zoomOut();
+ } else if (id === "zoomIn") {
+ zoom?.zoomIn();
+ } else if (id === "resetZoom") {
+ zoom?.reset();
+ }
+ }
+
+ subscribe(callback: () => void) {
+ this.listeners.add(callback);
+ return () => {
+ this.listeners.delete(callback);
+ };
+ }
+
+ /** Fullscreen, while the title row of the embed, which has a button for it, is hidden. */
+ private getFullscreenTools(): ContentEmbedTool[] {
+ const embed = this.rootRef.current?.closest<HTMLElement>(".include-note");
+ const { hideTitle, boxSize } = embed?.dataset ?? {};
+ if (hideTitle !== "true" || (boxSize !== "medium" && boxSize !== "full")) {
+ return [];
+ }
+
+ return [
+ { id: "fullscreen", label: t("common.fullscreen"), icon: fullscreenIcon, group: "zoom" }
+ ];
+ }
+
+ private update() {
+ const shownTools = JSON.stringify(this.getTools());
+ if (shownTools !== this.shownTools) {
+ this.shownTools = shownTools;
+ for (const listener of this.listeners) {
+ listener();
+ }
+ }
+ }
+}
+
+/** Zoom bounds, as a multiple of the diagram fitted to the viewer. */
+const MIN_ZOOM = 0.5;
+const MAX_ZOOM = 10;
+/** How long the source has to stay unchanged before the diagram renders again, in milliseconds. */
+const RENDER_DELAY = 300;
diff --git a/apps/client/src/widgets/type_widgets/text/toolbar.spec.ts b/apps/client/src/widgets/type_widgets/text/toolbar.spec.ts
index 78c851bc84..0d67131cac 100644
--- a/apps/client/src/widgets/type_widgets/text/toolbar.spec.ts
+++ b/apps/client/src/widgets/type_widgets/text/toolbar.spec.ts
@@ -54,7 +54,7 @@ describe("CKEditor config", () => {
});
describe("the Insert group", () => {
- it("offers the drawing canvas above the Mermaid diagram, on both toolbars", () => {
+ it("offers the drawing canvas and the embedded Mermaid diagram above the Mermaid diagram, on both toolbars", () => {
const toolbars = [
buildClassicToolbar(false, true).toolbar.items,
buildFloatingToolbar(true).blockToolbar
@@ -64,7 +64,8 @@ describe("the Insert group", () => {
&& "label" in item && item.label === "text-editor.toolbar-groups.insert");
const groupItems = (group as { items: string[] } | undefined)?.items ?? [];
const index = groupItems.indexOf("drawingCanvas");
- expect(groupItems.slice(index, index + 2)).toEqual([ "drawingCanvas", "mermaid" ]);
+ expect(groupItems.slice(index, index + 3))
+ .toEqual([ "drawingCanvas", "mermaidDiagram", "mermaid" ]);
expect(items).not.toContain("drawingCanvas");
}
});
diff --git a/apps/client/src/widgets/type_widgets/text/toolbar.ts b/apps/client/src/widgets/type_widgets/text/toolbar.ts
index 470d0941a2..842efb85c1 100644
--- a/apps/client/src/widgets/type_widgets/text/toolbar.ts
+++ b/apps/client/src/widgets/type_widgets/text/toolbar.ts
@@ -106,7 +106,7 @@ export function buildClassicToolbar(multilineToolbar: boolean, aiAssistant: bool
"footnote",
{
...buildInsertGroup(),
- items: ["link", "linkEmbed", "bookmark", "internallink", "contentEmbed", "|", "collapsible", "tabs", "multicolumnLayout", "math", "drawingCanvas", "mermaid", "horizontalLine", "pageBreak", "|", "dateTime", "specialCharacters", "emoji", "insertIcon"]
+ items: ["link", "linkEmbed", "bookmark", "internallink", "contentEmbed", "|", "collapsible", "tabs", "multicolumnLayout", "math", "drawingCanvas", "mermaidDiagram", "mermaid", "horizontalLine", "pageBreak", "|", "dateTime", "specialCharacters", "emoji", "insertIcon"]
},
"|",
buildAlignmentToolbar(),
@@ -177,7 +177,7 @@ export function buildFloatingToolbar(aiAssistant: boolean) {
"footnote",
{
...buildInsertGroup(),
- items: ["link", "linkEmbed", "bookmark", "internallink", "contentEmbed", "|", "collapsible", "tabs", "multicolumnLayout", "math", "drawingCanvas", "mermaid", "horizontalLine", "pageBreak", "dateTime"]
+ items: ["link", "linkEmbed", "bookmark", "internallink", "contentEmbed", "|", "collapsible", "tabs", "multicolumnLayout", "math", "drawingCanvas", "mermaidDiagram", "mermaid", "horizontalLine", "pageBreak", "dateTime"]
},
"|",
buildAlignmentToolbar(),
diff --git a/packages/ckeditor5/src/plugins/file_upload/file_upload_ui.ts b/packages/ckeditor5/src/plugins/file_upload/file_upload_ui.ts
index e3823fe514..6d4b61857a 100644
--- a/packages/ckeditor5/src/plugins/file_upload/file_upload_ui.ts
+++ b/packages/ckeditor5/src/plugins/file_upload/file_upload_ui.ts
@@ -1,7 +1,10 @@
import {
CANVAS_ATTACHMENT_MIME,
CANVAS_ATTACHMENT_TITLE,
- EMPTY_CANVAS_CONTENT
+ EMPTY_CANVAS_CONTENT,
+ MERMAID_ATTACHMENT_MIME,
+ MERMAID_ATTACHMENT_TITLE,
+ NEW_MERMAID_CONTENT
} from "@triliumnext/commons";
import {
ButtonView,
@@ -18,6 +21,7 @@ import {
type Locale
} from "ckeditor5";
import bxLink from "boxicons/svg/regular/bx-link.svg?raw";
+import bxNetworkChart from "boxicons/svg/regular/bx-network-chart.svg?raw";
import bxPen from "boxicons/svg/regular/bx-pen.svg?raw";
import bxShapeSquare from "boxicons/svg/regular/bx-shape-square.svg?raw";
@@ -28,7 +32,7 @@ import type { FileUploadOptions } from "./fileuploadcommand.js";
* the list also offers to link them. In an editor without embeds, the button links them.
*
* Also registers the `drawingCanvas` button, which attaches an empty canvas drawing and embeds it,
- * editable.
+ * editable, and the `mermaidDiagram` button, which does the same with a new Mermaid diagram.
*/
export default class FileUploadUI extends Plugin {
static get pluginName() {
@@ -94,17 +98,19 @@ export default class FileUploadUI extends Plugin {
editor.ui.componentFactory.add("drawingCanvas", (locale) => {
const button = new ButtonView(locale);
button.set({ label: t("Drawing canvas"), icon: bxPen, tooltip: true });
+ bindToEmbedUpload(editor, button);
+ button.on("execute", () => insertDrawingCanvas(editor));
- const uploadCommand = editor.commands.get("fileUpload");
- const embedCommand = editor.commands.get("insertContentEmbed");
- if (uploadCommand && embedCommand) {
- button.bind("isEnabled").to(uploadCommand, "isEnabled", embedCommand, "isEnabled",
- (canUpload, canEmbed) => canUpload && canEmbed);
- } else {
- button.isEnabled = false;
- }
+ return button;
+ });
- button.on("execute", () => insertDrawingCanvas(editor));
+ editor.ui.componentFactory.add("mermaidDiagram", (locale) => {
+ const button = new ButtonView(locale);
+ button.set({
+ label: t("Mermaid diagram (embedded)"), icon: bxNetworkChart, tooltip: true
+ });
+ bindToEmbedUpload(editor, button);
+ button.on("execute", () => insertMermaidDiagram(editor));
return button;
});
@@ -142,9 +148,35 @@ export default class FileUploadUI extends Plugin {
* the `drawingCanvas` button does.
*/
export function insertDrawingCanvas(editor: Editor) {
- const file = new File([ EMPTY_CANVAS_CONTENT ], CANVAS_ATTACHMENT_TITLE, {
+ insertEditableEmbed(editor, new File([ EMPTY_CANVAS_CONTENT ], CANVAS_ATTACHMENT_TITLE, {
type: CANVAS_ATTACHMENT_MIME
- });
+ }));
+}
+
+/**
+ * Attaches a new Mermaid diagram and embeds it, editable and untitled, with the focus in it, as the
+ * `mermaidDiagram` button does.
+ */
+export function insertMermaidDiagram(editor: Editor) {
+ insertEditableEmbed(editor, new File([ NEW_MERMAID_CONTENT ], MERMAID_ATTACHMENT_TITLE, {
+ type: MERMAID_ATTACHMENT_MIME
+ }));
+}
+
+/** Enables `button` while a file can be attached and embedded at the selection. */
+function bindToEmbedUpload(editor: Editor, button: ButtonView) {
+ const uploadCommand = editor.commands.get("fileUpload");
+ const embedCommand = editor.commands.get("insertContentEmbed");
+ if (uploadCommand && embedCommand) {
+ button.bind("isEnabled").to(uploadCommand, "isEnabled", embedCommand, "isEnabled",
+ (canUpload, canEmbed) => canUpload && canEmbed);
+ } else {
+ button.isEnabled = false;
+ }
+}
+
+/** Attaches `file` and embeds it, editable and untitled, with the focus in it. */
+function insertEditableEmbed(editor: Editor, file: File) {
editor.execute("fileUpload", {
file: [ file ],
asEmbed: true,
diff --git a/packages/ckeditor5/src/plugins/mention/slash_commands.ts b/packages/ckeditor5/src/plugins/mention/slash_commands.ts
index c865fdbfbc..3f1ab28642 100644
--- a/packages/ckeditor5/src/plugins/mention/slash_commands.ts
+++ b/packages/ckeditor5/src/plugins/mention/slash_commands.ts
@@ -46,7 +46,7 @@ import { ADMONITION_TYPE_NAMES, type AdmonitionType } from "../admonition/admoni
import { getAdmonitionTitle } from "../admonition/admonition_ui.js";
import aiIcon from "../ai_assistant/theme/icons/ai.svg?raw";
import { COMMAND_NAME as CONTENT_EMBED_COMMAND } from "../content_embed/content_embed.js";
-import { insertDrawingCanvas } from "../file_upload/file_upload_ui.js";
+import { insertDrawingCanvas, insertMermaidDiagram } from "../file_upload/file_upload_ui.js";
import { INSERT_ICON_COMMAND } from "../inline_icon/inline_icon_editing.js";
import InlineIconUI from "../inline_icon/inline_icon_ui.js";
import InsertDateTimePlugin, { COMMAND_NAME as INSERT_DATE_TIME_COMMAND, getDateTimeFormatOptions } from "../insert_date_time.js";
@@ -345,6 +345,16 @@ export function buildTriliumSlashCommands(editor: Editor): SlashCommandDefinitio
isEnabled: canEmbedFiles,
execute: insertDrawingCanvas
},
+ {
+ id: "mermaid-diagram-embed",
+ title: t("Mermaid diagram (embedded)"),
+ description: t("Insert a Mermaid diagram stored as an attachment."),
+ aliases: [ "mermaid", "diagram", "flowchart" ],
+ icon: bxNetworkChart,
+ commandName: "fileUpload",
+ isEnabled: canEmbedFiles,
+ execute: insertMermaidDiagram
+ },
...buildMermaidSlashCommands(editor),
{
id: "ai-assistant",
diff --git a/packages/commons/src/lib/notes.ts b/packages/commons/src/lib/notes.ts
index 234376914c..73f0933475 100644
--- a/packages/commons/src/lib/notes.ts
+++ b/packages/commons/src/lib/notes.ts
@@ -80,6 +80,15 @@ export const EMPTY_CANVAS_CONTENT = JSON.stringify({
appState: {}
});
+/** The media type of a Mermaid diagram saved in an attachment, such as one in a text note. */
+export const MERMAID_ATTACHMENT_MIME = "text/vnd.mermaid";
+
+/** The title of the attachment a new Mermaid diagram is saved in. */
+export const MERMAID_ATTACHMENT_TITLE = "Diagram.mmd";
+
+/** The content of a new Mermaid diagram. */
+export const NEW_MERMAID_CONTENT = "flowchart LR\n A --> B\n";
+
/**
* The media type of a file attached under `fileName`: {@link CANVAS_ATTACHMENT_MIME} for an
* Excalidraw file, so that it shows as a canvas drawing, else `mime`.
@@ -122,7 +131,8 @@ const FILE_MIME_MAPPINGS: Record<string, string> = {
"application/vnd.oasis.opendocument.spreadsheet": "bx bx-spreadsheet",
"application/vnd.ms-excel": "bx bx-spreadsheet",
"text/csv": "bx bx-spreadsheet",
- [CANVAS_ATTACHMENT_MIME]: NOTE_TYPE_ICONS.canvas
+ [CANVAS_ATTACHMENT_MIME]: NOTE_TYPE_ICONS.canvas,
+ [MERMAID_ATTACHMENT_MIME]: NOTE_TYPE_ICONS.mermaid
};
const IMAGE_MIME_MAPPINGS: Record<string, string> = {
@@ -309,6 +319,7 @@ export function getNoteContentType(type: string, mime: string, hasIconPackLabel:
export function getFileContentType(type: string, mime: string) {
if (type === "file" && mime === "application/pdf") return "pdf";
if (type === "file" && mime === CANVAS_ATTACHMENT_MIME) return "canvasDrawing";
+ if (type === "file" && mime === MERMAID_ATTACHMENT_MIME) return "mermaidDiagram";
if ((type === "file" || type === "viewConfig") && mime === "application/json") return "code";
if (type === "file" && mime.startsWith("audio/")) return "audio";
if (type === "file" && mime.startsWith("video/")) return "video";
@@ -327,6 +338,7 @@ export const CONTENT_RENDERER_GROUPS: Readonly<Record<string, string>> = {
markdown: "markdown",
image: "image",
canvasDrawing: "file",
+ mermaidDiagram: "file",
pdf: "file",
audio: "file",
video: "file",