Cloudinary Blog

Create Markdown Diagrams and Charts for Developers and Architects

Create Markdown Diagrams and Charts

Oftentimes, developers and architects must supplement their project documents with diagrams, charts, sequence drawings, and the like. Instead of creating them with traditional software like Microsoft Visio, I searched for a more developer-friendly alternative and found a project with just the right tool, which I was able to integrate with Cloudinary with gratifying results. This post describes the tool and the integration steps.

Note
We created a live environment for users to test the markdown diagram tool at mermaid.cloudinary.us

Visio’s Limitations

Although Visio is a viable tool, I found it difficult to use because of these limitations:

  • All team members must procure the software or establish an account with the service.
  • Artifacts are stored outside the source hierarchy.
  • Running diff to compare changes is onerous.

Additionally, I had to pinpoint the right color combinations and laboriously arrange the objects in diagrams to make them look pretty. Those chores were time-consuming and distracting from the core task of documenting a complex workflow. I wanted a tool with which I could simply “write” a markdown diagram, after which the tool would do the heavy lifting of prettying up the image with the right colors, spacing, and fonts. Guess what, I found just such a tool—in mermaid!

Webinar
How to Optimize for Page Load Speed

Mermaid’s Capabilities

Highlighted on mermaid’s repo’s page is the goal of the project:

Generate diagrams, charts, graphs, or flows from Markdown-like text via JavaScript.

You can create many types of diagrams on mermaid: flow charts, Gantt charts, sequence diagrams, class diagrams, state diagrams. Since the actual diagram is rendered in plain Markdown, you can add the source to version control so that updates are readily accessible by your team for collaboration. Also, mermaid offers a live editor, which you can download and then host the code for your team. Alternatively, you can use the publicly-hosted editor.

A Cloudinary-Mermaid Integration

I was hooked on mermaid from the start and used it heavily. However, the Scalable Vector Graphics (SVG) images it produces don’t work well for presentations. To resolve that issue, I exported the SVG format to a raster format like PNG. Below are the steps. Disclaimer: I’m not a React developer. This is my first attempt at hacking so please ignore my lack of syntactic elegance.

Step 1: Add an option to the Actions tab.

The mermaid live editor offers two options in the Actions tab: Link to View and Download SVG, which produces a .svg file.

Action to download image

I added an option called Download Image

default actions

—by adding the following code to the render method in the src/components/Preview.js file:

Copy to clipboard
<Divider type='vertical' />
          <a href='' download='' target='_blank' onClick={this.handleOnDownloadImage}>Download Image</a>

Since all my code was in a file called uploader.js, which exported a method called upload, I imported that method, like this:

Copy to clipboard
import { upload } from './uploader'

Next, I registered the handle in the constructor:

Copy to clipboard
this.handleOnDownloadImage = this.handleOnDownloadImage.bind(this)

I then added the function for the onClick handler, as follows:

Copy to clipboard
handleOnDownloadImage (event) {
    const svgObject = `data:image/svg+xml;base64,${Base64.encode(this.container.innerHTML)}`   
    event.target.href = upload(svgObject)
    // useful if you right-click and download
    event.target.download = 'mermaid.png'
  }

See the full Preview.js file for reference.

Step 2: Add the upload capability.

To add the function that handles uploads to Cloudinary, I made use of the unsigned upload method, which requires no authentication, enabling everyone to access the image. To simplify the process, I uploaded with a raw API POST request instead of working through an SDK. Here are the details of the upload request:

  • API endpoint: https://api.cloudinary.com/v1_1/mermaid/upload, where mermaid is the cloud name. If you have a Cloudinary account, replace mermaid in the code with your cloud name.

  • JSON request body:

    • file: This is a Base64-encoded string of the SVG object. *tag: This is a tag with the value mermaid. You can add more meaningful data to it, e.g., the diagram type, the diagram context, the associated project, etc.
    • upload_preset: This is the preset that is defined in your account. Below are my settings:

Upload transformation

Here’s the code for the upload function:

Copy to clipboard
var url = 'https://api.cloudinary.com/v1_1/mermaid/upload'
  var xhr = new XMLHttpRequest() 
  var fd = new FormData() 
  xhr.open('POST', url, false)
  xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest')
  // fd.append('public_id', publicId)
  fd.append('upload_preset', 'mermaid')
  fd.append('tags', 'Mermaid') 
  fd.append('file', svgImage)

This function obtains the SVG image data from Preview.js, invokes the upload function, and picks up the URL for the uploaded SVG image. I added the following Cloudinary transformations to enhance the image:

  1. Convert the image format from SVG to PNG.
  2. Apply three transformations:

Cloudinary then returns the final URL and the browser opens the image in a new tab. Here’s the complete code of the uploader. The diagram below image explains the workflow.

Diagram

Here’s the markup for the sequence diagram:

Copy to clipboard
sequenceDiagram
User-->>Mermaid: Create a diagram
Mermaid-->>Mermaid: Generate SVG
Note over User, Mermaid: Update diagram as it is being edited
User-->>Mermaid: Click Download Image
Mermaid-->>Uploader: Pass SVG data
Uploader-->>Uploader: Build unsigned upload POST request
Uploader-->>Cloudinary: Upload SVG
Cloudinary-->>Uploader: Generate Cloudinary URL
Uploader-->>Uploader: Build transformed PNG URL
Note over Uploader,Mermaid: Change format, transparency, overlay
Uploader-->>Mermaid: Respond with Cloudinary PNG URL
Mermaid-->>User: Display image

Image Security

Recall that the integration makes use of the simple unsigned upload method. For tighter security, switch to the signed upload method instead. Also, to prevent unauthorized users from uploading images to your account, do not turn on unsigned upload. You could also lock down access to your images. For details on the various ways of securing digital assets, read this Cloudinary Support article. Would this Cloudinary-mermaid integration be of use to you? If so, do give it a try.

About Cloudinary

Cloudinary provides easy-to-use, cloud-based media management solutions for the world’s top brands. With offices in the US, UK and Israel, Cloudinary has quickly become the de facto solution used by developers and marketers at major companies around the world to streamline rich media management and deliver optimal end-user experiences.

For more information, visit www.cloudinary.com or follow us on Twitter

Recent Blog Posts

Automation Frees Up PetRescue’s Staff to Help Pets Find Their Forever Homes

As we spend more time at home, many of us are adopting pets for the joy, companionship and a surprising range of health benefits. In Australia, where our nonprofit customer PetRescue is located, there’s a shortage of pets to adopt. Last August, the Guardian reported that dog shelters in Australia emptied and adoption fees for puppies were running as high as $AUS1800.

Read more
Cloudinary and Contentful Make Modern Content Management Easier

I am pleased to share that Cloudinary and Contentful have joined forces to further streamline the creation, processing, and delivery of online content through Cloudinary’s digital asset management (DAM) solution and advanced transformation and delivery capabilities for images and video. What’s more, the partnership delivers a headless approach to DAM. By leveraging APIs for media management tasks, marketers and developers alike benefit from an integrated stack of optimized assets for optimization and automation. As a result, page loads are fast and beautiful, and at scale—with less overhead and effort.

Read more
Introducing Cloudinary's Nuxt Module

Since its initial release in October 2016 by the Chopin brothers as a server-side framework that runs on top of Vue.js, Nuxt (aka Nuxt.js) has gained prominence in both intuitiveness and performance. The framework offers numerous built-in features based on a modular architecture, bringing ease and simplicity to web development. Not surprisingly, Nuxt.js has seen remarkable growth in adoption by the developer community along with accolades galore. At this writing, Nuxt has earned over 30K stars on GitHub and 96 active modules with over a million downloads per month. And the upward trend is ongoing.

Read more
How Quality and Quantity can go Hand in Hand

When it comes to quality versus quantity, you’ll often hear people say, “It’s the quality that counts, not the quantity”. While that’s true in many situations, there are also cases where you want both quality and quantity. You may have thousands of images on your website and you want them all to look great. This is especially important if your website allows users to upload their own content, for example, to sell their own products or services. You don't want their poor quality images to reflect badly on your brand.

Read more
Product Videos 101: What Makes Them Great?

A product’s benefits and usage, including its value proposition, features, and instructive details, are best demonstrated through video. Product-video types vary, depending on the funnel, channel, and audience, the most popular ones being demos, reviews, installation, and how-tos.

Read more