Mermaid
The Mermaid extension turns a text definition into a diagram. Assign Mermaid source such as flowchart TD; A-->B to the Diagram property and the browser draws it as SVG. All of Mermaid's diagram types work: flowcharts, sequence, class, state and entity-relationship diagrams, Gantt charts, pie charts, mind maps, timelines and more.
Because the source is plain text, diagrams are easy to generate from data: a workflow's states, an order's history, a database schema, or the output of an AI model. The widget adds what an application needs around them: pan and zoom, server-side click events, syntax validation, and export to SVG, PNG and PDF.
It bundles Mermaid 11.12.2 and Panzoom 4.6.1.
Installation
dotnet add package Wisej-4-Mermaid
The package targets .NET Framework 4.8 and .NET 8 (including the -windows, Android, iOS and Mac Catalyst targets). After a rebuild, Mermaid appears in the Visual Studio toolbox. The scripts are embedded in the assembly, so no CDN is needed.
Getting started
- C#
- VB.NET
using Wisej.Web.Ext.Mermaid;
var mermaid = new Mermaid
{
Dock = DockStyle.Fill,
Diagram =
@"flowchart TD
A[Start] --> B{Valid?}
B -- Yes --> C[Continue]
B -- No --> D[Stop]"
};
this.Controls.Add(mermaid);
Imports Wisej.Web.Ext.Mermaid
Dim mermaid As New Mermaid With {
.Dock = DockStyle.Fill,
.Diagram =
"flowchart TD
A[Start] --> B{Valid?}
B -- Yes --> C[Continue]
B -- No --> D[Stop]"
}
Me.Controls.Add(mermaid)
The first line of the source declares the diagram type (flowchart TD, sequenceDiagram, classDiagram, gantt and so on). The Mermaid syntax reference covers every type. You can also pass the source to the constructor: new Mermaid("flowchart LR; Order-->Invoice-->Payment").
Every change to Diagram, or to any option, makes Mermaid render the whole diagram again and fires DiagramChanged. An empty diagram isn't rendered.
Appearance
| Property | Default | What it does |
|---|---|---|
Theme | "default" | Mermaid theme: default, dark, forest, neutral or base. |
Look | "classic" | Drawing style: classic, neo or handDrawn (a sketch-like look). |
ThemeVariables | empty | Mermaid's theme variables, such as primaryColor, lineColor, fontSize and darkMode. |
FontFamily | theme | A CSS font-family list for the diagram text. |
Flowchart / Sequence | empty | Options for those two diagram types, such as curve, nodeSpacing or showSequenceNumbers, using Mermaid's camel-case names. |
ThemeVariables, Flowchart and Sequence are dynamic objects: add fields with the names Mermaid uses, and each assignment updates the widget.
- C#
- VB.NET
// Custom colors need the "base" theme.
mermaid.Theme = "base";
mermaid.ThemeVariables.primaryColor = "#4F46E5";
mermaid.ThemeVariables.primaryTextColor = "#FFFFFF";
mermaid.ThemeVariables.lineColor = "#94A3B8";
mermaid.ThemeVariables.fontSize = "14px";
// Straight edges and more room between nodes.
mermaid.Flowchart.curve = "linear";
mermaid.Flowchart.nodeSpacing = 60;
mermaid.Flowchart.rankSpacing = 80;
' Custom colors need the "base" theme.
' Setting fields on the dynamic objects requires Option Strict Off.
mermaid.Theme = "base"
mermaid.ThemeVariables.primaryColor = "#4F46E5"
mermaid.ThemeVariables.primaryTextColor = "#FFFFFF"
mermaid.ThemeVariables.lineColor = "#94A3B8"
mermaid.ThemeVariables.fontSize = "14px"
' Straight edges and more room between nodes.
mermaid.Flowchart.curve = "linear"
mermaid.Flowchart.nodeSpacing = 60
mermaid.Flowchart.rankSpacing = 80
Mermaid applies theme variables only when Theme is "base", and the colors must be hex values (#ff0000), not color names. With any other theme, the variables are silently ignored.
Any other Mermaid configuration option can go on Options, the object passed to mermaid.initialize(), for example mermaid.Options.maxTextSize = 100000.
Pan and zoom
With EnablePanZoom on (the default), the user drags the diagram with the left mouse button and zooms with the mouse wheel, between 2% and 200%. ZoomLevel sets the starting scale (1 = 100%): 0.5f fits a large diagram into a small panel.
The pan offset and zoom go back to ZoomLevel every time the diagram is rendered again. Zooming with the wheel doesn't change ZoomLevel on the server.
Clicks on diagram elements
ElementClick fires when the user clicks a node, an edge, a cluster (subgraph) or a sequence-diagram actor. ElementClickEventArgs gives the element's text in Element, and a dynamic Data object with details from the browser:
Data field | Content |
|---|---|
elementType | The Mermaid class of the element, such as node…, edge…, cluster…, flowchart-link, actor or labelBox. |
text | The text of the clicked element, or of its node when the element itself has none. |
id, dataId | The id and data-id of the clicked SVG element. |
parentId, parentDataId | The same for the enclosing node, edge or cluster. |
ariaLabel | For edges, the label describing the connection, when Mermaid provides one. |
button, x, y | The mouse button (0 left, 1 middle, 2 right) and the page coordinates. |
- C#
- VB.NET
mermaid.ElementClick += (s, e) =>
{
string type = e.Data?.elementType;
if (type != null && type.StartsWith("node"))
ShowDetails(e.Element);
};
AddHandler mermaid.ElementClick,
Sub(s, e)
Dim type As String = e.Data?.elementType
If type IsNot Nothing AndAlso type.StartsWith("node") Then ShowDetails(e.Element)
End Sub
With DeterministicIds on (the default), the same diagram always produces the same element IDs. You can then map parentId back to your own data reliably, even after the diagram is rendered again.
The widget reports clicks on its own, so you don't need Mermaid's click directives. Those stay blocked by the default security level anyway, as explained below.
Errors and validation
When Mermaid can't parse the diagram, the widget shows the error text in place of the diagram and fires Error with a readable Message. To check source before showing it, for example text typed by a user or produced by a model, call ValidateAsync. It runs Mermaid's parser in the browser without rendering or changing the current diagram:
- C#
- VB.NET
var result = await mermaid.ValidateAsync(this.textBoxSource.Text);
if (result.Valid)
mermaid.Diagram = this.textBoxSource.Text;
else
MessageBox.Show(result.Message ?? "The diagram is not valid.");
Dim result = Await mermaid.ValidateAsync(Me.TextBoxSource.Text)
If result.Valid Then
mermaid.Diagram = Me.TextBoxSource.Text
Else
MessageBox.Show(If(result.Message, "The diagram is not valid."))
End If
LogLevel defaults to Trace, Mermaid's most verbose level. Set it to MermaidLogLevel.Error in production.
Security
SecurityLevel maps to Mermaid's securityLevel:
| Level | Behavior |
|---|---|
Strict (default) | HTML tags in the diagram text are encoded, and click interactions defined in the diagram are disabled. |
Antiscript | HTML is allowed, but scripts are removed. |
Loose | HTML and click interactions defined in the diagram are allowed. |
Sandbox | The diagram is rendered in a sandboxed iframe. |
Keep Strict whenever any part of the diagram text comes from users, imported files or an AI model. Loose and Antiscript let diagram text inject HTML into the page. Use them only for diagrams your own code builds from trusted data.
Exporting
| Method | Result |
|---|---|
DownloadSvg(fileName) | The browser downloads the rendered SVG (diagram.svg by default). |
DownloadPdf(fileName, scale, backgroundColor, margin, quality) | The browser builds a one-page PDF and downloads it. |
ExportToPdfAsync(...) | The same PDF, returned to the server as a MemoryStream. |
ExportToImageAsync() | A PNG of the diagram, returned to the server as an Image. |
The downloads never pass through the server. The PDF is built in the browser: the SVG is rasterized and embedded as a JPEG. The page is sized to the diagram (1 pixel = 1 point) plus margin (20 by default). scale (default 2) sets the resolution and quality (default 0.95) the JPEG quality.
- C#
- VB.NET
// A sharper PDF on a light grey page, attached to an e-mail.
using (var pdf = await mermaid.ExportToPdfAsync(scale: 3, backgroundColor: "#f5f5f5"))
{
SendReport(pdf.ToArray());
}
' A sharper PDF on a light grey page, attached to an e-mail.
Using pdf = Await mermaid.ExportToPdfAsync(scale:=3, backgroundColor:="#f5f5f5")
SendReport(pdf.ToArray())
End Using
ExportToImageAsync captures the diagram with the html2canvas script, which it loads from the Html2Canvas extension's resources. Add the Wisej-4-Html2Canvas package to the project, or the export can't run. All the export methods need a diagram that has already been rendered.
Loading Mermaid from elsewhere
The widget uses the Mermaid build embedded in the assembly. To use another version, set the static SourceURL to a UMD build that defines window.mermaid. Set it once at startup, before any Mermaid widget is created. It applies to every session.
static void Main()
{
Wisej.Web.Ext.Mermaid.Mermaid.SourceURL = "https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.min.js";
new MainPage().Show();
}
Events
| Event | When |
|---|---|
DiagramChanged | Diagram or an option changes. |
ElementClick | The user clicks an element of the diagram. |
Error | Mermaid can't parse the current diagram. |
API reference
MermaidElementClickEventArgsandMermaidErrorEventArgsValidationResultMermaidSecurityLevelandMermaidLogLevel- The whole
Wisej.Web.Ext.Mermaidnamespace