Linux Format

Dynamic diagrams with Mermaid

Mihalis Tsoukalos explains how to use Mermaid to create beautiful technical graphs and diagrams you can reuse and update anywhere.

- Mihalis Tsoukalos is a systems engineer and a technical writer. He’s also the author of Go Systems Programmin­g and Mastering Go, with a third book in the works!

Mihalis Tsoukalos explains how to use

Mermaid to create beautiful technical graphs and diagrams you can reuse and update anywhere.

The subject of this tutorial is Mermaid, which is a Markdown dialect. Put simply, Mermaid code looks like Markdown code and enables you to create flows, diagrams, charts and more. It’s based on Javascript that renders the Markdown as code to generate the output, because Markdown doesn’t offer support for drawing. Mermaid is supported by many editors including Microsoft Visual Code and typora, which we’ll cover here. There are also online editors that can render Mermaid code and create the respective output.

Mermaid code is delivered in blocks. The first line of a Mermaid block specifies the type of the plot. Valid values include graph, pie, sequence diagram and flowchart. Each plot type has its own syntax, and it’s much easier to include Mermaid code in Markdown files that use the md file extension (filename.md), which is what we’ll be using for the examples of this tutorial.

A Mermaid block in a Markdown file begins with ```mermaid and ends with ``` – this is the Markdown way of telling that the embedded code has a given property, which in this case is Mermaid. However, Mermaid code can also be saved on its own in files that use the mmd file extension (filename.mmd).

Installing Mermaid… or not!

You don’t need to install Mermaid. All you need is an editor that supports Mermaid to see the output from a Mermaid block. The following is a Markdown file, saved as mermaid.md, with a block in Mermaid format:

## This is a Mermaid example

```mermaid graph TD;

A1-->A2;

A2-->A4;

A1-->A3;

A2-->A3;

A3-->A4;

```

The first line is plain Markdown and generates a title in the output. Then, we declare that we’re creating a graph that’s going to be rendered from the top to the bottom (TD: Top-down) of the page. Next, we add nodes and we connect them with other nodes. The --> notation shows that the node on the left is connected to the node on the right. The graph contains four nodes, named A1, S2, A3 and A4. If you want to include more nodes and connection­s between them, just declare what you want – Mermaid takes care of the output.

This example illustrate­s one of the simplest uses of Mermaid; it can do many more tasks. However, it also illustrate­s the simplicity of the Mermaid dialect.

The output of the previous code can be seen in the diagram (above) with the help of Microsoft Visual Code – more on this below.

Microsoft Visual Code

Microsoft Visual Code has a extension for rendering Mermaid files and previewing Mermaid output inside Visual Code. Go to the Extensions tab, search for the “Markdown Preview Mermaid Support” extension and install it. It would also be helpful to install the “Mermaid Markdown Syntax Highlighti­ng” extension so that you can see your Mermaid code beautifull­y coloured. Next, we render the Markdown file vscode.md inside Microsoft Visual Code:

## A Markdown file with Mermaid!

```mermaid graph LR;

Root--> A & B & C A-->A1-->A2--->A3

B-->B1-->B2-->B3

C--->C1-->C2-->C3

```

This code presents an alternativ­e way of creating graphs. Instead of writing multiple A--> lines, you can simply write A--> & & or

A-->-->--> in order to make multiple node connection­s. Using ---> instead of just --> creates longer edges between nodes, as in C--->C1 .

The screeshot (opposite) shows the preview of vscode.md using the Mermaid extension for Visual Code.

Creating a pie chart

Mermaid can easily plot pie charts and can even do the calculatio­ns for you so that the percentage­s of the pie chart are correct. To create a pie chart you need to begin the Mermaid block with pie . The next line should begin with title followed by the title text. After that, you need to write the dataset that’s used for generating the pie chart. Each line of the dataset is a different entry and contains a label, followed by a colon, which is followed by a positive numeric value. Note that the label text should be included in double quotes, which isn’t the case with the pie chart title text.

The following block shows the definition of a pie chart in the Mermaid dialect:

## This is a Pie Chart in Mermaid

```mermaid pie title Linux Distributi­ons

“Debian” : 42.96

“Ubuntu” : 50.05

“Arch” : 10.01

“Centos” : 5

```

The previous code is saved in the pie_chart.md file – render it on your own to see its output.

Creating a flowchart

Flowcharts in Mermaid start with the flowchart keyword, followed by their orientatio­n (LR or TD). Then you add the nodes of the flowchart as you would with graphs. If you want to add text in an edge you should use the -- Text --> notation. You can add text to any node by including it after the node name. If you include the text in square brackets, the node is drawn as a rectangula­r; use curly braces to draw the node as a diamond.

The following Mermaid code, which can be found as flow_chart.md, describes a flowchart:

## Flow chart

```mermaid flowchart TD

A[choose OS] --> B{DO you want?}; B -- Yes --> C[UNIX or Windows]; C -- Windows --> D[good Luck!]; C -- UNIX --> E{linux or macos?} E -- Linux --> G{good Choice!}

E -- macos --> H{apple.com!}

B -- No ---> F[end];

```

When rendered, the code generates a flow chart that can help you choose an Operating System. The diagram (overleaf) shows the flowchart generated by this code with the help of Microsoft Visual Code.

Sequence diagrams

A sequence diagram describes interactio­ns and how things are carried out. They’re helpful when you want to describe situations that depend on many factors.

A sequence diagram begins with the

sequencedi­agram keyword followed by the list of participan­ts, which are defined using the participan­t keyword (each participan­t is defined in a separate line). After that you need to define the connection­s and interactio­ns between participan­ts, which in Mermaid terminolog­y are called Messages.

This Mermaid code produces a sequence diagram – it’s part of the seq_diagram.md Markdown file:

sequencedi­agram participan­t User participan­t CTC participan­t CSV participan­t Auth as Authorizat­ion loop Every minute

CTC-->CSV: Keep updating! end

User-->>auth: Send Authorizat­ion details Auth-->>user: Get back authorizat­ion token

There are four participan­ts: User, CTC, CSV and Authorizat­ion. The Authorizat­ion participan­t is accessed

as Auth inside the Mermaid code but is displayed as Authorizat­ion for clarity – this is implemente­d with the Auth as Authorizat­ion statement. The loop block represents actions that happen continuous­ly.

You should be able to see the output of seq_diagram. md either in Microsoft Visual Code, typora or any other online Mermaid editor such as https://mermaid-js.github.io/mermaid-live-editor.

Use Cases in Mermaid

Let’s see how Mermaid can describe the use cases of a project. Use cases are implemente­d using sequence diagrams, which means they’re defined using the sequencedi­agram keyword. We want to use the Mermaid code to describe how a user interacts with a program and the components involved in the process. This is shown in the following Mermaid code: sequencedi­agram participan­t U as User participan­t CTC participan­t CSV participan­t CTC_AUTH as CTC/AUTH autonumber rect rgb(0, 100, 0) par Get Data CSV->>CTC_AUTH: A Database that keeps Usage data

Note right of CSV: REST API CTC_AUTH-->>CSV: Return Usage data end end

U->>CTC: Logs in CTC-->>U: Returns Security Token

CTC->>CSV: Opens CSV Window

U->>CSV: Asks for system visualisat­ions

CSV-->>CSV: Query Internal Database

CSV-->>U: Displays Visualisat­ions

The autonumber keyword that’s shown here attaches a sequence number to each arrow in the sequence diagram. The rect rgb(0, 100, 0) command puts colour in the output using RGB values, and colours a rectangle. Inside that rectangle you can write the Mermaid commands you want. The par block shows actions that happen in parallel. Both rect and par blocks end with the

end keyword.

The diagram (above) displays the output of the previous Mermaid code – the Markdown source file with the Mermaid code is called use_cases.md. The use of

autonumber enables you to specify the part of the sequence diagram you want by using a number.

Mermaid and Hugo

The Hugo (https://gohugo.io) framework offers support for Mermaid code. This section presents such as example where we embed Mermaid code into a Hugo blog post that we publish. In order to support Mermaid rendering in Hugo, you need to add a small shortcode inside the layouts/shortcodes directory – Hugo uses shortcodes to add extra functional­ity that can’t be implemente­d in Markdown. The name of the shortcode file should be mermaid.html and must have the following content:

$ cat layouts/shortcodes/mermaid.html

{{ .Inner }}

The previous file defines a shortcode named

mermaid – in order to use that shortcode you should embed Mermaid commands in {{}} and {{}} blocks. A part of the Markdown code for the Hugo blog post is as follows:

Using [Mermaid](https://mermaid-js.github.io/ mermaid/) in Hugo.

{{}} graph TD;

A-->B;

A-->C;

B-->D;

C-->D;

{{}}

The first line is regular Markdown code. After that you need to put all Mermaid related code in a block that begins with {{}} and ends with {{}}.

The diagram (facing page) shows the code inside the Hugo blog post – the entire Markdown file for that blog post is called usemermaid.md. You can see the blog post live at www.mtsoukalos.eu/2021/01/usingmerma­id/. Bear in mind that the Mermaid code is rendered with the help of the Javascript library used in the shortcode file (https://unpkg.com/mermaid@8.2.3/dist/mermaid.min.js) and not by Hugo itself.

Go scripts

This section presents a Go utility that generates Mermaid code, but you can use any programmin­g language you want to produce Mermaid code. The utility reads a CSV file with two columns and creates a Markdown file with a title and a pie chart in Mermaid format. The first column in the CSV file is the label and the second column is the value, which should be an

integer. The filename of the input file becomes the title of the Markdown document as well as the title of the pie chart and the contents of the file generate the elements of the pie chart.

The most interestin­g code of piechart.go is for _, line := range lines {

_, err := strconv.atoi(line[1]) if err != nil { continue

} fmt.printf("\t\"%s\” : %s\n”, line[0], line[1])

}

The input file is read all at once and kept in the lines slice. The previous code processes the elements of the lines slice one by one to obtain the data and print it on the screen. The presented code ignores all rows that don’t contain a valid integer with the help of the strconv. Atoi() Go function.

The input file that’s processed by piechart.go has the following format:

Linux,75

Windows,10

...

Running piechart.go with the aforementi­oned input file produces the following output:

## data.csv

```mermaid pie title data.csv “Linux” : 75 “Windows” : 10 ... ```

The easiest way to collect the output is to redirect it into a file: run piechart.go data.csv and then filename. md. After saving the output you can process it in

Microsoft Visual Code or typora and obtain the type of output you’re looking for.

The key takeaway here is that once you understand the format of the Mermaid file you want to create, you can generate Mermaid files dynamicall­y using input from multiple data sources, including plain text files, database servers and web services.

Python 3 scripting

Finally let’s look at how Python 3 utility that generates Mermaid output on the fly using an external service. For the purposes of this tutorial, the Mermaid code is hardcoded and kept in a Python variable. If you have experience in the Python programmin­g language, you can add some versatilit­y to the presented utility and write code that reads the Mermaid code from a plain text file or a database server instead. Note that you might need to install some Python 3 modules for the script to work. The presented Python 3 script saves the output into a file that’s named nodes.png – the name of the output file is hardcoded.

The core functional­ity of the script.py Python 3 file can be found in this code: img = Image.open(io.bytesio(requests.get ('https://mermaid.ink/img/’+base64_string).content)) plt.imshow(img) plt.savefig('nodes.png’, dpi = 300)

The first line uses an external web site (https://mermaid.ink/img) to render the Mermaid input. The second statement displays the image output – if you’re running the Python 3 script from the command line, then this statement might not generate any output on screen – and the final statement saves the generated image into a PNG file. The biggest difference between the Go script and the Python 3 one is that the Python 3 script generates the output image by itself whereas the Go script generates Mermaid code that needs to be rendered first.

Don’t get fooled by the use of Markdown and plain text files and think that Mermaid is limited in function. It’s a profession­al tool that can help you create beautiful technical diagrams and plots, and include them in your blog posts, documents or reports. Experiment­ing with Mermaid is going to make you more productive – play with it a little before using it in real projects.

 ??  ?? This diagram shows the output of a simple Mermaid block of code that creates a graph with four nodes and is embedded in a Markdown file. The use of Markdown enables you to add context to the graph.
This diagram shows the output of a simple Mermaid block of code that creates a graph with four nodes and is embedded in a Markdown file. The use of Markdown enables you to add context to the graph.
 ??  ??
 ??  ?? This shows Microsoft Visual Code rendering a Mermaid document. The code is previewed in a separate window from the Markdown file.
This shows Microsoft Visual Code rendering a Mermaid document. The code is previewed in a separate window from the Markdown file.
 ??  ?? Here’s a flowchart generated in Mermaid, which can be drawn from left to right or top to bottom.
Here’s a flowchart generated in Mermaid, which can be drawn from left to right or top to bottom.
 ??  ?? This shows how Mermaid can describe use cases and therefore offers a handy way of generating documentat­ion for your software projects.
This shows how Mermaid can describe use cases and therefore offers a handy way of generating documentat­ion for your software projects.
 ??  ?? Here’s typora in action, which can render Mermaid code as well as any other Markdown code and works on most popular operating systems including Linux. If you’re not a fan of Microsoft Visual Code, give typora a try.
Here’s typora in action, which can render Mermaid code as well as any other Markdown code and works on most popular operating systems including Linux. If you’re not a fan of Microsoft Visual Code, give typora a try.
 ??  ?? Hugo renders Mermaid code and includes the generated output in the respective static web page, provided that you’ve created the required Hugo shortcode.
Hugo renders Mermaid code and includes the generated output in the respective static web page, provided that you’ve created the required Hugo shortcode.

Newspapers in English

Newspapers from Australia