Skip to main content

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​

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);

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​

PropertyDefaultWhat it does
Theme"default"Mermaid theme: default, dark, forest, neutral or base.
Look"classic"Drawing style: classic, neo or handDrawn (a sketch-like look).
ThemeVariablesemptyMermaid's theme variables, such as primaryColor, lineColor, fontSize and darkMode.
FontFamilythemeA CSS font-family list for the diagram text.
Flowchart / SequenceemptyOptions 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.

// 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;
ThemeVariables only work with the base theme

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 fieldContent
elementTypeThe Mermaid class of the element, such as node…, edge…, cluster…, flowchart-link, actor or labelBox.
textThe text of the clicked element, or of its node when the element itself has none.
id, dataIdThe id and data-id of the clicked SVG element.
parentId, parentDataIdThe same for the enclosing node, edge or cluster.
ariaLabelFor edges, the label describing the connection, when Mermaid provides one.
button, x, yThe mouse button (0 left, 1 middle, 2 right) and the page coordinates.
mermaid.ElementClick += (s, e) =>
{
string type = e.Data?.elementType;
if (type != null && type.StartsWith("node"))
ShowDetails(e.Element);
};
Stable IDs

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:

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.");
Quiet the browser console

LogLevel defaults to Trace, Mermaid's most verbose level. Set it to MermaidLogLevel.Error in production.

Security​

SecurityLevel maps to Mermaid's securityLevel:

LevelBehavior
Strict (default)HTML tags in the diagram text are encoded, and click interactions defined in the diagram are disabled.
AntiscriptHTML is allowed, but scripts are removed.
LooseHTML and click interactions defined in the diagram are allowed.
SandboxThe diagram is rendered in a sandboxed iframe.
Untrusted diagram sources

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​

MethodResult
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.

// 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());
}
ExportToImageAsync needs Html2Canvas

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​

EventWhen
DiagramChangedDiagram or an option changes.
ElementClickThe user clicks an element of the diagram.
ErrorMermaid can't parse the current diagram.

API reference​