How to Add Mermaid Diagram Support for Flowcharts in the React TipTap Editor
Enable the built-in Mermaid extension in your editor configuration and set a flowchart syntax template as the default diagram code to render flowcharts as SVG images.
The reactjs-tiptap-editor repository includes a native Mermaid extension that supports sequence diagrams, class diagrams, and flowcharts without requiring additional plugins. By registering the extension in the editor store and customizing the starter template, you can seamlessly integrate interactive flowchart creation into your rich-text editing workflow.
Architecture of the Mermaid Extension
The Mermaid functionality is implemented across modular components in the src/extensions/Mermaid/ directory, with integration points in the core editor configuration.
Core Extension Logic
The src/extensions/Mermaid/Mermaid.ts file declares the TipTap node that stores diagrams as image-like blocks. It registers two essential commands: setMermaid for inserting new diagrams and setAlignImageMermaid for alignment adjustments. This file defines the schema for the mermaid node type with attributes for src, alt, width, and height.
UI Components
Three React components handle the user interface:
-
RichTextMermaid (
src/extensions/Mermaid/components/RichTextMermaid.tsx): A modal dialog that lazily loads themermaidlibrary on demand. It provides a live preview of the diagram code viarenderMermaidand callssetMermaidto insert the generated SVG when the user saves changes. -
EditMermaidBlock (
src/extensions/Mermaid/components/EditMermaidBlock.tsx): An inline editing interface that appears when users select an existing diagram node. It reuses the rendering logic fromRichTextMermaidto allow in-place modifications. -
NodeViewMermaid (
src/extensions/Mermaid/components/NodeViewMermaid/NodeViewMermaid.tsx): A React node view that renders the final SVG inside a wrapper<div class="imageMermaid">within the editor content, preserving alignment and sizing attributes.
Configuration Integration
The extension integrates with the editor through these configuration points:
-
Editor Store (
src/store/editor.ts): Instantiates the TipTapEditorand registers all enabled extensions. The Mermaid extension activates when'mermaid'appears in theextensionsNamesarray. -
Type Definitions (
src/types.ts): Extends theExtensionNameunion type to include'mermaid'as a valid extension identifier. -
Build Configuration (
vite.config.ts): Adds themermaidpackage to the Vite dependency optimization list to enable dynamic imports. -
Localization (
src/locales/en.ts): Provides tooltip text for the toolbar button via theeditor.mermaid.tooltipkey.
Step-by-Step Implementation
Follow these steps to enable flowchart support in your React TipTap editor.
-
Register the Mermaid Extension
Locate the
extensionsNamesarray insrc/store/editor.tsand add'mermaid'to the list:const extensionsNames = [ // …other extensions 'mermaid', ];The editor store automatically imports
src/extensions/Mermaid/Mermaid.tsand registers the extension with the TipTap editor instance. -
Verify Toolbar Button Visibility
The toolbar button is defined in the extension's
addOptions().buttonmethod. When the extension is enabled inextensionsNames, the button appears automatically in the toolbar with the tooltip text defined in the locale files. No additional markup is required. -
Set Flowchart as Default Template
Modify the default starter code in
src/extensions/Mermaid/components/RichTextMermaid.tsxto use flowchart syntax. Locate thedefaultCodevariable at line 22 and replace it:const defaultCode = `graph LR A[Start] --> B{Decision} B -->|Yes| C[Result] B -->|No| D[Alternative]`;This provides users with a ready-made flowchart skeleton when they open the Mermaid dialog.
-
Configure Rendering Options (Optional)
Customize the Mermaid initialization in
RichTextMermaid.tsxby adjusting themermaidInitfunction (lines 59-67). For dark-mode-aware flowcharts:mermaidInstance.initialize({ darkMode: true, theme: 'dark', startOnLoad: false, fontSize: 13, });
How Flowchart Rendering Works
When a user clicks the Mermaid toolbar button, the RichTextMermaid component opens a modal dialog. The component lazily imports the mermaid library via import('mermaid') and initializes it with the configured options.
As the user types Mermaid code, the renderMermaid function calls mermaidInstance.render, which returns an SVG string. The component displays this live via dangerouslySetInnerHTML. When the user clicks Save changes, the SVG is serialized to a data URL (or uploaded if an upload function is configured) and inserted into the document via the setMermaid command.
The resulting mermaid node stores the SVG source and original diagram code, which NodeViewMermaid renders as an <img> tag inside the editor content. To edit an existing flowchart, users select the diagram to trigger RichTextBubbleMermaid (src/components/Bubble/RichTextBubbleMermaid.tsx), which launches EditMermaidBlock for inline modifications.
Practical Code Examples
Adding the Extension Programmatically
Import the Mermaid extension directly when constructing your editor:
import { Editor } from '@tiptap/react';
import { Mermaid } from 'reactjs-tiptap-editor/mermaid';
const editor = new Editor({
extensions: [
// other extensions …
Mermaid,
],
});
Using the setMermaid Command Directly
Insert a flowchart programmatically using the command chain:
editor
.chain()
.focus()
.setMermaid({
src: 'data:image/svg+xml;base64,…', // generated SVG data URL
alt: encodeURIComponent('graph LR\nA-->B'),
width: 500,
height: 300,
})
.run();
Custom Default Flowchart Template
Replace the generic graph starter with a specific flowchart pattern in RichTextMermaid.tsx:
// src/extensions/Mermaid/components/RichTextMermaid.tsx
const defaultCode = `graph TD
A[Start] --> B(Is it working?)
B -->|Yes| C[Great!]
B -->|No| D[Debug]
D --> E[Fix Issue]
E --> B`;
Summary
- Enable the extension by adding
'mermaid'to theextensionsNamesarray insrc/store/editor.ts. - Customize the starter template in
src/extensions/Mermaid/components/RichTextMermaid.tsxat line 22 to usegraph LR,graph TD, or other flowchart-specific syntax. - Render flowcharts using the built-in
setMermaidcommand, which stores the SVG output as a node attribute. - Edit inline via
EditMermaidBlock, which provides the same live preview capabilities as the creation dialog. - Configure themes by modifying the
mermaidInitoptions to support dark mode or custom color schemes.
Frequently Asked Questions
How do I change the default flowchart direction from top-down to left-to-right?
Edit the defaultCode variable in src/extensions/Mermaid/components/RichTextMermaid.tsx at line 22. Replace graph TB (top-bottom) or graph TD (top-down) with graph LR (left-right) in the template string. This changes the starter code for all new diagrams while preserving existing flowcharts.
Can I use custom themes for my flowcharts?
Yes. Modify the mermaidInit function in src/extensions/Mermaid/components/RichTextMermaid.tsx (lines 59-67) to include theme options. Set the theme property to values like 'dark', 'forest', or 'neutral' in the initialization object passed to mermaidInstance.initialize().
Where is the Mermaid library actually loaded?
The library is dynamically imported on demand. In src/extensions/Mermaid/components/RichTextMermaid.tsx, the code uses import('mermaid') to load the package only when the user opens the Mermaid dialog. This prevents the library from bloating the initial bundle size. The vite.config.ts file ensures Vite pre-bundles the dependency for faster dynamic imports.
How do I programmatically insert a flowchart without using the toolbar?
Use the setMermaid command provided by the extension. Chain editor.chain().focus().setMermaid({ src, alt, width, height }).run(), where src is a base64-encoded SVG data URL and alt contains the URL-encoded Mermaid source code. This command creates a mermaid node type with the specified attributes.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →