Skip to main content

Mermaid

Namespace: Wisej.Web.Ext.Mermaid

Assembly: Wisej.Web.Ext.Mermaid (4.1.0.0)

Represents a widget that renders Mermaid diagrams (flowcharts, sequence diagrams, class diagrams, Gantt charts, etc.) from their text definition.

public class Mermaid : Widget

The diagram is rendered in the browser by the Mermaid library. Use Diagram for the diagram source and the Look, Theme, SecurityLevel, ThemeVariables and related properties to customize the Mermaid initialization options.

Every change to Diagram or to the options re-initializes Mermaid and renders the whole diagram again. When the diagram cannot be parsed the widget displays the error text and fires the Error event.

Example:

Rendering a flowchart and changing the theme:

// Basic usage: render a flowchart.
var mermaid = new Wisej.Web.Ext.Mermaid.Mermaid()
{
Dock = Wisej.Web.DockStyle.Fill,
Diagram =
@"flowchart TD
A[Start] --> B{Valid?}
B -- Yes --> C[Continue]
B -- No --> D[Stop]"
};

// Optional: tweak Mermaid initialization options.
mermaid.Theme = "dark";
mermaid.SecurityLevel = Wisej.Web.Ext.Mermaid.MermaidSecurityLevel.Strict;

this.Controls.Add(mermaid);

Constructors​

Instance member Mermaid()​

Initializes a new instance of the Mermaid widget with an empty diagram.

The default options are: EnablePanZoom = true, DeterministicIds = true, Look = "classic", Theme = "default", SecurityLevel = Strict and LogLevel = Trace.

Example:

Creating the widget and assigning the diagram later:

var mermaid = new Wisej.Web.Ext.Mermaid.Mermaid();
mermaid.Diagram = "flowchart TD; A-->B";

Instance member Mermaid(diagram)​

Initializes a new instance of the Mermaid widget with the specified diagram.

NameTypeDescription
diagramStringInitial Mermaid diagram source text. Null is treated as an empty string.

The constructor assigns Diagram and applies the same default options as #ctor.

Example:

Creating the widget with its diagram:

var mermaid = new Wisej.Web.Ext.Mermaid.Mermaid("flowchart LR; Order-->Invoice-->Payment");
mermaid.Dock = DockStyle.Fill;
this.Controls.Add(mermaid);

Properties​

Instance member DeterministicIds​

Boolean: Returns or sets whether Mermaid generates deterministic IDs for the rendered elements. (Default: True)

Maps to Mermaid's deterministicIds option. When true (default), the same diagram always produces the same element IDs, which are also returned in Data.

Instance member Diagram​

String: Returns or sets the Mermaid diagram source text. (Default: "")

The text uses the Mermaid syntax (see syntax-reference); the first line declares the diagram type, i.e. flowchart TD, sequenceDiagram, classDiagram, gantt. Setting null is the same as setting an empty string; an empty diagram is not rendered.

Changing the value fires DiagramChanged and renders the diagram again on the client. Syntax errors are reported asynchronously through the Error event.

Example:

Assigning a sequence diagram:

mermaid.Diagram =
@"sequenceDiagram
participant A as Alice
participant B as Bob
A->>B: Hello Bob
B-->>A: Hello Alice";

Instance member EnablePanZoom​

Boolean: Returns or sets a value indicating whether pan and zoom functionality is enabled. (Default: True)

When enabled (default), the user can drag the diagram with the left mouse button and zoom it using the mouse wheel (between 0.02 and 2). The pan offset and zoom level are reset to ZoomLevel every time the diagram is rendered.

Instance member Flowchart​

Object: Returns a dynamic object with the flowchart-specific options (maps to Mermaid's flowchart configuration). (Default: null)

Add fields using the Mermaid (camel case) names, i.e. curve, htmlLabels, nodeSpacing, rankSpacing, useMaxWidth. Setting a field updates the widget.

See Flowchart Configuration in the Mermaid documentation for the complete list. Flowchart colors are set with ThemeVariables.

Example:

Changing the edge style and the spacing of a flowchart:

mermaid.Flowchart.curve = "linear";
mermaid.Flowchart.nodeSpacing = 60;
mermaid.Flowchart.rankSpacing = 80;

Instance member FontFamily​

String: Returns or sets the font family applied to the diagram text.

This maps to Mermaid's fontFamily option and accepts a CSS font-family list. When not set, the getter returns the name of the control's Font but no font is passed to Mermaid, which then uses the font of the theme. For the size, use the fontSize key in ThemeVariables.

Example:

Using a custom font stack:

mermaid.FontFamily = "\"Inter\", \"Segoe UI\", sans-serif";
mermaid.ThemeVariables.fontSize = "14px";

Instance member InitScript​

String: Returns the JavaScript code that initializes the widget on the client.

The script is loaded from the embedded startup.js resource; assigning a value has no effect.

Instance member LogLevel​

MermaidLogLevel: Returns or sets the level of the messages that Mermaid logs to the browser console (maps to Mermaid's logLevel). (Default: Trace)

The default is Trace, the most verbose level. Consider using Error in production.

Instance member Look​

String: Returns or sets the diagram look (e.g. classic, neo, handDrawn). (Default: "classic")

This maps to Mermaid's look initialization option. The default is classic.

Example:

Rendering the diagram with a sketch-like appearance:

mermaid.Look = "handDrawn";

Instance member Options​

Object: Returns or sets the dynamic options object passed to mermaid.initialize() on the client.

The typed properties (Diagram, Look, Theme, SecurityLevel, etc.) store their values in this object. You can add any other Mermaid configuration option that doesn't have a dedicated property; the names are serialized in camel case.

See config for the available options.

Example:

Setting Mermaid options that don't have a dedicated property:

mermaid.Options.maxTextSize = 100000;
mermaid.Options.fontSize = 14;

Instance member Packages​

List<Package>: Returns the script packages required by the widget.

The list contains the Mermaid library loaded from SourceURL or, when it's null, from the embedded resource. This override ensures that resource resolution happens in the correct calling assembly.

Instance member SecurityLevel​

MermaidSecurityLevel: Returns or sets the security level (maps to Mermaid's securityLevel). (Default: Strict)

The default is Strict, which encodes HTML tags in the diagram text and disables click interactions defined in the diagram. Use a less restrictive level only with trusted diagram sources.

Instance member Sequence​

Object: Returns a dynamic object with the sequence diagram specific options (maps to Mermaid's sequence configuration). (Default: null)

Add fields using the Mermaid (camel case) names, i.e. showSequenceNumbers, mirrorActors, actorMargin, wrap. Setting a field updates the widget.

See Sequence Diagram Configuration in the Mermaid documentation for the complete list. Colors such as sequenceNumberColor are set with ThemeVariables.

Example:

Numbering the messages of a sequence diagram:

mermaid.Sequence.showSequenceNumbers = true;
mermaid.Sequence.mirrorActors = false;

Static member SourceURL​

String: Returns or sets the URL from which the Mermaid library is loaded by all the Mermaid widgets.

The default (null) is to use the embedded Mermaid script resource, but you can set this property to load Mermaid from a CDN or custom location if needed. Ensure that the specified URL points to a valid Mermaid JavaScript file (UMD build that defines window.mermaid) for the widget to function correctly.

This is a static setting shared by all sessions. Set it at startup, before any Mermaid widget is created: widgets that already built their Packages list are not affected.

Example:

Loading Mermaid from a CDN when the application starts:

static void Main()
{
Wisej.Web.Ext.Mermaid.Mermaid.SourceURL = "https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.min.js";

new MainPage().Show();
}

Instance member Theme​

String: Returns or sets the Mermaid theme name (e.g. default, dark, forest, neutral, base). (Default: "default")

This maps to Mermaid's theme initialization option. Use the base theme when customizing the colors with ThemeVariables, since it's the only theme Mermaid allows to be modified.

Example:

Customizing the colors of the diagram:

mermaid.Theme = "base";
mermaid.ThemeVariables.primaryColor = "#BB2528";
mermaid.ThemeVariables.primaryTextColor = "#FFFFFF";

Instance member ThemeVariables​

Object: Returns a dynamic object with the theme variables (maps to Mermaid's themeVariables). (Default: null)

Common keys include darkMode, fontFamily, fontSize, primaryColor, lineColor. Mermaid applies the variables only when Theme is set to base. Colors must be hex values (i.e. #ff0000), not color names. Setting a field updates the widget.

See Theme Variables in the Mermaid documentation for details and examples.

Example:

Using a dark color scheme with a larger font:

mermaid.Theme = "base";
mermaid.ThemeVariables.darkMode = true;
mermaid.ThemeVariables.fontSize = "16px";

Instance member ZoomLevel​

Single: Returns or sets the initial scale factor of the rendered diagram (1 = 100%). (Default: 1)

The value is applied only when EnablePanZoom is true. Zooming with the mouse wheel changes the scale on the client only and doesn't update this property.

Example:

Showing a large diagram at half its size:

mermaid.EnablePanZoom = true;
mermaid.ZoomLevel = 0.5f;

Methods​

Instance member DownloadPdf(fileName, scale, backgroundColor, margin, quality)​

Downloads the currently rendered diagram as a PDF file.

ParameterTypeDescription
fileName optionalStringOptional file name used by the browser download (default is "diagram.pdf").
scale optionalNullable<Double>Optional scale factor for image quality (default is 2 for high DPI).
backgroundColor optionalStringOptional CSS background color for the PDF, i.e. "#f5f5f5" (default is white).
margin optionalNullable<Double>Optional margin in points around the diagram (default is 20).
quality optionalNullable<Double>Optional JPEG quality from 0.0 to 1.0 (default is 0.95).

This method rasterizes the SVG diagram to a canvas, then generates a single page PDF with the image embedded as a JPEG. The page size is the size of the diagram (1 pixel = 1 point) plus the margin . The PDF is created client-side and downloaded directly in the browser, the file is not sent to the server. Use ExportToPdfAsync to receive the PDF on the server.

Example:

Downloading the diagram as a PDF file:

// Basic usage with default options.
mermaid.DownloadPdf("flowchart.pdf");

// Custom options for higher quality and different background.
mermaid.DownloadPdf("diagram.pdf", scale: 3, backgroundColor: "#f5f5f5", margin: 30);

Instance member DownloadSvg(fileName)​

Downloads the currently rendered diagram as an SVG file.

ParameterTypeDescription
fileName optionalStringOptional file name used by the browser download. The default is "diagram.svg".

This method invokes a client-side download of the currently rendered SVG; the file is created in the browser and is not sent to the server.

Example:

Downloading the diagram from a button:

private void buttonSvg_Click(object sender, EventArgs e)
{
this.mermaid1.DownloadSvg("order-process.svg");
}

Instance member ExportToImageAsync()​

Asynchronously exports the currently rendered diagram to a PNG image.

Returns: Task<Image>. A task that represents the asynchronous operation. The task result contains the generated Image.

The image is captured in the browser using the html2canvas library loaded from the Wisej.Web.Ext.Html2Canvas extension resources, which must be deployed with the application. The pan and zoom transformation is reset during the capture and restored afterwards.

The diagram must have been rendered before calling this method.

Example:

Saving the diagram as a PNG file on the server:

private async void buttonExport_Click(object sender, EventArgs e)
{
var image = await this.mermaid1.ExportToImageAsync();
image.Save(Application.MapPath("Exports/diagram.png"), System.Drawing.Imaging.ImageFormat.Png);
}

Instance member ExportToPdfAsync(scale, backgroundColor, margin, quality)​

Exports the currently rendered diagram as a PDF and returns it as a MemoryStream.

ParameterTypeDescription
scale optionalNullable<Double>Optional scale factor for image quality (default is 2 for high DPI).
backgroundColor optionalStringOptional CSS background color for the PDF, i.e. "#f5f5f5" (default is white).
margin optionalNullable<Double>Optional margin in points around the diagram (default is 20).
quality optionalNullable<Double>Optional JPEG quality from 0.0 to 1.0 (default is 0.95).

Returns: Task<MemoryStream>. A MemoryStream containing the PDF bytes. The caller is responsible for disposing the stream.

This method converts the SVG diagram to a canvas, generates a PDF with the image embedded, and returns the PDF as a memory stream. The PDF generation happens client-side in the browser, and the bytes are transferred back to the server.

Throws:

Example:

Saving the PDF on the server or reading its bytes:

// Export to memory stream for further processing.
using (var pdfStream = await mermaid.ExportToPdfAsync())
{
// Save to file
using (var fileStream = File.Create("diagram.pdf"))
{
pdfStream.CopyTo(fileStream);
}
}

// Export with custom options.
using (var pdfStream = await mermaid.ExportToPdfAsync(scale: 3, backgroundColor: "#f5f5f5"))
{
// Send via email, save to database, etc.
byte[] pdfBytes = pdfStream.ToArray();
}

Protected member OnDiagramChanged(e)​

Raises the DiagramChanged event.

ParameterTypeDescription
eEventArgsAn EventArgs instance containing the event data.

This method is called to notify subscribers that the diagram has changed. Derived classes can override this method to provide additional behavior when the DiagramChanged event is raised. When overriding, ensure to call the base implementation to maintain event invocation.

Protected member OnElementClick(e)​

Raises the ElementClick event.

ParameterTypeDescription
eElementClickEventArgsEvent data.

Override this method to intercept element clicks before subscribers are notified.

Example:

public class MyMermaid : Wisej.Web.Ext.Mermaid.Mermaid
{
protected override void OnElementClick(Wisej.Web.Ext.Mermaid.ElementClickEventArgs e)
{
// Add logging, then forward to base to raise the event.
System.Diagnostics.Debug.WriteLine($"Clicked: {e.Element}");
base.OnElementClick(e);
}
}

Protected member OnError(e)​

Raises the Error event.

ParameterTypeDescription
eMermaidErrorEventArgsEvent data.

Override this method to intercept Mermaid errors before subscribers are notified.

Example:

public class MyMermaid : Wisej.Web.Ext.Mermaid.Mermaid
{
protected override void OnError(Wisej.Web.Ext.Mermaid.MermaidErrorEventArgs e)
{
// Add logging, then forward to base to raise the event.
System.Diagnostics.Debug.WriteLine(e?.Message);
base.OnError(e);
}
}

Protected member OnWidgetEvent(e)​

Fires the WidgetEvent event.

ParameterTypeDescription
eWidgetEventArgsA WidgetEventArgs that contains the event data.

Instance member ValidateAsync(diagram)​

Validates Mermaid syntax in the browser without rendering.

ParameterTypeDescription
diagramStringMermaid source text to validate. It doesn't need to be the current Diagram.

Returns: Task<ValidationResult>. A ValidationResult containing the validation outcome and optional error details.

Validation happens in the browser using Mermaid's parser (mermaid.parse()); the widget's diagram is not changed and the Error event is not fired. Check Valid for the outcome.

Example:

Validating user input before applying it:

var result = await mermaid.ValidateAsync(this.textBoxSource.Text);
if (result.Valid)
mermaid.Diagram = this.textBoxSource.Text;
else
Wisej.Web.MessageBox.Show(result.Message ?? "Diagram is invalid.");

Events​

Instance member DiagramChanged​

EventHandler Occurs when the diagram is modified, signaling that its state has changed.

Subscribe to this event to be notified of changes to the diagram. This can be used to update the user interface, save changes, or perform other actions in response to modifications.

Instance member ElementClick​

ElementClickEventHandler Occurs when an element in the Mermaid diagram is clicked.

This event provides information about the clicked element, including its text content, type (node, edge, cluster, etc.), IDs, and mouse button/location data.

Example:

mermaid.ElementClick += (s, e) =>
{
MessageBox.Show($"Clicked: {e.Element}\nType: {e.Data?.elementType}");
};

Instance member Error​

MermaidErrorEventHandler Occurs when the current diagram fails Mermaid validation/parsing in the browser.

This event is raised from a client-side error notification when Mermaid cannot parse/validate the diagram. If you want to proactively validate without rendering, use ValidateAsync.

Example:

mermaid.Error += (s, e) =>
{
// e.Message contains a human-readable message.
Wisej.Web.MessageBox.Show(e.Message, "Mermaid error");
};

Implements​