Mermaid, Graph Building with Markdown

First published by : November 1 2019

Mermaid is an interesting project for creating SVG-based flow charts and other graphs using a form of Markdown. This makes it an attractive proposition for illustrating API and similar documentation.

This article's scope is to a technical writer's perspective. Developers can extend their Mermaid using APIs, etc. Review the Mermaid Documentation for full details.

Shared Learning

Flag this content to your friends, connections, and colleagues.

What is Mermaid?

Mermaid is an award-winning documentation feature created by Knut Sveidqvist. It combines  HTML and a form of Markdown with JavaScript to create SVG images of flows and other charts, which can be styled with CSS.

Keep Calm. It's only code

The code may be scary to non-digital workers with no interest in, or capacity to learn our creative medium of HTML. It isn't scary at all.

Writers using WYSIWYG text editors including for Drupal and Wordpress CMS applications will need to switch to their HTML views. Some basic HTML knowledge is needed if only to avoid breaking stuff by accident.

Why Use Mermaid?

The short answer is to implement flow charts and other graphic content into API documentation. YAML (YML) files support Markdown, so the logical connection is to employ Mermaid.

Creating diagrams is easy using Microsoft PowerPoint, or other vector image applications that output PNG or JPG. High-end applications such as Adobe Illustrator export vectors as SVG. And not everyone can.

The attraction of Mermaid is that it puts a standard graphic creation tools in the hands of workers who may not have the graphic skills, software (who doesn't have PowerPoint?), or ability to post a responsive picture formatted image array into thier products.

Important: Mermaid is not natively accessible to everyone. Discover more in the Accessibility section below.

Mermaid removes the common image issues caused by workers who are not familiar with the performance or accessibility of online products including:

  • Image file preparation and design
  • Image file scale.
  • Image file type and optimisation.
  • Alternative texts and long descriptions.

In short, Mermaid could save on resources and enable local standards controlled by the technical writing lead.

Mermaid Examples

Figure 1. A simple Mermaid
graph TD A[Web Content] -->|Orientation| B(User Task) B --> C{Let me think} C -->|One| D[Orientation] C -->|Two| E[Findability] C -->|Three| F[Usability] C -->|Four| G[Learnabillity]

The example (at Figure 1.) is encoded in the HTML as follows:

<div class="mermaid">
graph TD
A[Web Content] -->|Orientation| B(User Task)
B --> C{Let me think}
C -->|One| D[Orientation]
C -->|Two| E[Findability]
C -->|Three| F[Usability]
C -->|Four| G[Learnabillity]
<div>

The Mermaid <script> is linked to on the host page to a directory containing all the files necessary for the Markdown to work:

<script src="../resources/mermaid/mermaid.min.js"></script>
<script>mermaid.initialize({startOnLoad:true});</script>

The display is left-aligned and is not natively fluid-responsive. We can fix this with a touch of CSS to justify the content to the center, and enable scaling in narrower viewports. (See Figure 2.)

Figure 2. A (more) Responsive Mermaid
graph TD A[Web Content] -->|Orientation| B(User Task) B --> C{Let me think} C -->|One| D[Orientation] C -->|Two| E[Findability] C -->|Three| F[Usability] C -->|Four| G[Learnabillity]

As encoded:

<div class="mermaid mermaidContainer">
graph TD
A[Web Content] -->|Orientation| B(User Task)
B --> C{Let me think}
C -->|One| D[Orientation]
C -->|Two| E[Findability]
C -->|Three| F[Usability]
C -->|Four| G[Learnabillity]
<div>

And the added style.

.mermaidContainer {display:flex;justify-content: center;}

Setting Up Mermaid

Mermaid requires a number of files to be saved and then accessed from a local directory.

For playing on your local machine or webspace, the files can be downloaded from https://unpkg.com/browse/mermaid@8.4.0/dist/, where "8.4.0" is the version number. Update the version number when required.

If you "right-click" and Save As, the files may become corrupted with HTML in the process. I fixed this patiently by:

  • Opening each link individually.
  • Choosing to View Raw
  • Copy and pasting the "raw" code into a text editor.
  • Saving the file per the original file name.

See Figure 3.

Note: Take care that your text editor saves the files with the correct extentions.

Figure 3. Local Mermaid set up process
graph TD A[Create local directory] -->|Open browser| B(Find Library on Mermaid UNPKG Page) --> C{Method?} C-->|Copy and Paste| D(Open file in new tab) D --> |View Raw| F(Copy raw content) F --> G(Paste into Text Editor file) C-->|Download| H[Save with correct file name] G-->H H -->I[Saved to Directory] classDef success fill:#8DD17C,stroke:#8DD17C; classDef flow fill:#96BBFB,stroke:#96BBFB; classDef quest fill:#FABE78,stroke:#FABE78; class A,I success; class B,C,D,E,F,G,H flow; class C quest;

CMS Installaton

Consult your CMS administrator when wanting to install the Mermaid files.

Styling Your Mermaid

A full reference to styling Mermaid is available from the unpkg.com/mermaid (v0.5.6.) documentatation. By example, the background colours added to the flowchart at Figure 3 are styled as follows:

%% Set the classes.
classDef success fill:#8FD27F,stroke:#8FD27F;
classDef flow fill:#A2C3FB,stroke:#A2C3FB;
classDef quest fill:#FABE78,stroke:#FABE78;

%% Assign the classes.
class A,I success;
class B,C,D,E,F,G,H flow;
class C quest;

The syntax is to define the style declarations using a class and then to assign the class to the node or nodes.

IMPORTANT: Try to keep a contrast between the text colour and the background. Look up WCAG contrast ratios for guidance. (The contrast ratios in the styled example are just on the 7:1 ratio recommended).

Mermaid Initial Review

This Mermaid lark isn't out-of-the-box easy to create. It takes a little (and for me, much) more cognitive effort than only dragging boxes around an image editor.

Once I had created the original spider's web of a Set Up flow chart above, I pasted my Frankensteinian creation into the Mermaid Live Editor. After some faffing around and learning how to string the nodes together, re-jigging the identities, and interconnecting the ones I wanted connected, it all clicked into place.

Performance Cost

The rendered code output is not excessively heavy and is still weighty enough to look heavy. (See Figure 4).

Although the result is reasonable lightweight, the browser must make a number of HTTP requests and download a very weighty collection of resources, which can slow down page loading times when combined with other scripts needed to run the page successfully.

On a rural connection throttled to 6 MBps, this page can take several seconds to load the Mermaid graphs.

Figure 4. Compilation and Output
graph TD A[ENTER FLOW] --> |Action| B(Reaction)
graph TD
A[ENTER FLOW] --> |Action| B(Reaction)

The rendered 'weight' of the simple diagram above is 12 KB. The larger, 'Local Mermaid set up process diagram' is 20 KB. A comparable PNG or JPG file could perhpas double that. It's not a huge saving and is in any case useful.

Expand to review the 12 KB code.

 

Swimming With Mermaid

A popular flow diagram is the swim-laned process, or sequence diagram.

I recently inherited a swim laned flow and converted it into a PNG image to accommodate accessibility and its responsive rendition in a browser. Unfortunately, neither the <picture> element or inline-CSS is available to the client, so the single-file image is still not ideal. In Mermaid, we have hope.

So, let's give it a go. (See Figure 5).

Figure 5. Exploring Swim Lanes
sequenceDiagram participant Partner participant API participant credit participant boarding participant library Partner-->Partner:Get information Note right of Partner:Financial, personal,
and business info. Partner-->Partner: Complete application loop Get unsigned Documents Partner->>API:getDocuments API-->API:Collate documents API->>Partner:200: Document Pack Returned end Partner-->Partner:Capture signature loop Route to Credit Partner->>credit:Application credit-->credit:Perform checks credit->>Partner:200 Pass with token end Partner-->Partner:Collate application for boarding loop Boarding Partner->>boarding:application with token boarding-->boarding:Confirm credit token! boarding->>library:Store documents library-->library:store with UID library->>boarding:200 Complete boarding-->boarding:Board onto system boarding->>Partner:200 Done end Partner-->Partner:Complete welcome procedures

Hmmm?

Well, OK. It's a process flow diagram. And it responds badly when the viewport narrows. Quickly, the copy text gets so small we cannot even see it—never mind read it. Can we fix that?

Yes. We can! At least, sufficiently to enable its use. We can:

  1. Park the mermaid <div class="mermaid"...>inside an <article> (or other block element).
  2. Give the <article> an overflow-x:scroll; style declaration.
  3. Give the div class="mermaid" a minimum width.

When the viewport narrows and the chart reaches its narrowest allowed width, the <article> scrolls.

Here's an overview of the code used in the horizontaly scrolling sample at Figure 6:

<article class="scrollHorizontal">
  <div class="mermaid mermaidContainer">

    <!-- Graphic goes here-->

  </div>
</article>

<style> (Note: for demo purposes only)
.scrollHorizontal {
    width:100%;
    height:auto;
    overflow-x:auto;
}
.mermaidContainer {
    min-width:800px;
}
</style>
Figure 6. Responsive Mermaid

Narrow your browser viewport or view on a smaller device to experience the visual update at 800px.

"Responsive" (Scrolling) Sequence Diagram

sequenceDiagram participant Partner participant API participant credit participant boarding participant library Partner-->Partner:Get information Note right of Partner:Financial, personal,
and business info. Partner-->Partner: Complete application loop Get unsigned Documents Partner->>API:getDocuments API-->API:Collate documents API->>Partner:200: Document Pack Returned end Partner-->Partner:Capture signature loop Route to Credit Partner->>credit:Application credit-->credit:Perform checks credit->>Partner:200 Pass with token end Partner-->Partner:Collate application for boarding loop Boarding Partner->>boarding:application with token boarding-->boarding:Confirm credit token! boarding->>library:Store documents library-->library:store with UID library->>boarding:200 Complete boarding-->boarding:Board onto system boarding->>Partner:200 Done end Partner-->Partner:Complete welcome procedures

The graphic is now made available for narrow viewports on larger dipslays. However, scrolling is not always signalled by mobile device browsers. When a scrollbar is available, increased cognitive and motor effort both need considering.

As always, it depends.

Accessibility

Being compiled using JavaScript, Mermaid graphics will not display meaningfully when JavaScript is disabled.

Note: Statistically, over 400,000 of our UK users have JavaScript disabled in their browser.

Mermaid is not (very) accessible. The texts can be accessed and then the meaningful and contextual visual node connections and boxes are lost to less able users.

Solution?

A solution is to:

  1. Screen-grab the graphic and then save as a PNG or JPG file.
  2. Display the image in the Mermaid div by default.
  3. On load, hide the image using JavaScript.
  4. Offer an inline or separate 'text only' description.

Non-JavaScript browsers will now render the image. Then use JavaScript to remove the image before Mermaid scripts load.

Note: We can use the accessible and responsive <picture> to serve images most approriate to the viewport.

Alternative Access to Content

The provision of a comparable and equitable experience is too often overlooked in our digital production. Access to our content is our users' right as enshrined in modern Human Rights acts. Discover more on this from my MSc UX research blog.

A text only description must be offered for users unable to access Mermaid content. This can be within the page copy or in a separate file.

Overcoming Ableism

Our ableist design fails to offer a comparable and equitable experience.

The basic premise is that HTML is (90%) natively accessible. Our visual-biased and ableist design imposes barriers to access, which we then add accessibility adjuncts to and complicate or frustrate our less able users' experience.

Accessing Figure 3

An accessibility strategy was discussed for Mermaid graphics above. And what about providing a comparable and equitable experience? We need a strategy:

  1. Understand our able users' experience.
  2. Create a visualisation of the flow.
  3. Enhance the flow with the content.
  4. Review the content in isolation. Does it offer a comparable experience in isolation?
  5. Design strategies to close the experiencial gap.
  6. Test, where possible.
  7. Implement. And make this a standard for your product.

A hasty example is at Figure 7.

Figure 7. Local Mermaid set up process

The process flow

  1. Create a local directory.
  2. Open a browser and navigate to the Mermaid UNPKG page.
  3. Choose a method to save the code:
    1. Download. (Go to Step 4)
    2. Copy and Paste:
      1. Open a file link in a new tab.
      2. On the file's page, click View Raw.
      3. Copy the raw code content.
      4. Paste the content into a text editior.
  4. Save your file with the correct file name.
  5. Your file is saved to your directory.

The process flow diagram

graph TD A[Create a local directory] -->|Open browser| B(Open the Mermaid UNPKG page) --> C{Method?} C-->|Copy and Paste| D(Open the file in new tab) D --> |Click, View Raw| F(Copy raw content) F --> G(Paste into your text editor) C-->|Download| H[Save with the correct file name] G-->H H -->I[Saved to Directory] classDef success fill:#8DD17C,stroke:#8DD17C; classDef flow fill:#96BBFB,stroke:#96BBFB; classDef quest fill:#FABE78,stroke:#FABE78; class A,I success; class B,C,D,E,F,G,H flow; class C quest;

Summary

Mermaid is an interesting proposition that requires some knowledge and skill to implement well. It needs only minimal thought to make its content accessible and unfortunately, the procedures and techniques required may be beyond our workers' or our CMS capabilities.

All is not lost. Our workers can easily pick up a touch of HTML and within an enabled CMS environment, overcome the difficiencies and produce Mermaid graphics confident they are not discriminating our less able users.

Reference this article

Godfrey, P. (Year, Month Day). Article Heading. Retrieved Month Day, Year, from URL

❮ More Articles My Profile ❯

Testing Area

Mermaid Version
sequenceDiagram participant Partner Actions participant eBoarding API participant Credit System participant Boarding System participant Document Repository loop STEP 1. Administration Partner Actions-->Partner Actions:Gather information Note right of Partner Actions: Required
information includes
personal, business,
and financial
information, etc. Partner Actions-->Partner Actions: Complete application
form Partner Actions->>eBoarding API:getDocuments eBoarding API-->eBoarding API:Collate documents eBoarding API->>Partner Actions:200: Document Pack Partner Actions-->Partner Actions:Capture eSignatures
and consent end loop STEP 2. Complete a Credit Check Partner Actions-->Partner Actions:Prepare for
Credit Check Partner Actions->>Credit System:Perform Credit Check Credit System-->Credit System:Checks Made Credit System->>Partner Actions:200: creditCheck token end loop STEP 3. Board Merchant Partner Actions-->Partner Actions:Collate application
for boarding Partner Actions->>Credit System:Submit Application with creditCheck token Credit System-->Credit System:Confirm creditCheck token Credit System->>Boarding System:creditCheck token OK Boarding System-->Boarding System:Board customer Boarding System ->> Partner Actions: 200: Boarding complete end loop STEP 4. Store documents Partner Actions--> Partner Actions: Collate all documents Partner Actions->> Document Repository: Send documents for storage Document Repository-->Document Repository: store documents with a unique ID Document Repository->>eBoarding API:200 Complete eBoarding API->>Partner Actions:200: Documents stored Partner Actions-->Partner Actions: Complete welcome
procedures end
SVG Version
Partner ActionseBoarding APICredit SystemBoarding SystemDocuments1. AdministrationSupporting documents including personal, business, and financial information.Complete applicationgetDocumentsCollate documents200: Document Packloop[ Get unsigned Documents ]Capture eSignatureand permissionsApplicationPerform checks200: creditCheck tokenloop[ 2. Credit Check Service ]Collate applicationfor boardingApplication with creditCheck tokenConfirm creditCheck tokencreditCheck token OKBoard customer200: Boarding completeloop[ 3. Board Merchant ]Collate all documentsSend documents for storagestore documents with a unique ID200: Complete 200: Documents storedloop[ 4. Upload documents ]Complete welcomeproceduresPartner ActionseBoarding APICredit SystemBoarding SystemDocuments

Sponsored Ads