Adding diagrams to your Astro site with MermaidJS and Playwright

Adding diagrams to your Astro site with MermaidJS and Playwright

May 01 2024 - Adding diagrams to your site can help you communicate complex ideas more effectively. In this post, we'll look at how you can use MermaidJS with Playwright to create diagrams in your Astro site.

Astro(This post belongs to a series)
25 min read

In my next round of blogs, I wanted to add more diagrams to help explain some of the more complex concepts I’ll be discussing. This site is based on Astro, so I wanted to find a way to add diagrams that would work well with Astro’s Markdown and MDX support. After some research, I found MermaidJS, a simple and flexible diagramming tool that works well with Markdown and MDX.

In this post, we’ll look at how you can use MermaidJS to create diagrams in your Astro blog. I’m going to assume you already have an Astro site set up. If you don’t, you can follow the Astro series.

Here’s a quick example of what the results of MermaidJS give us:

Adding this to your content…

Simple sequence diagram using MermaidJS text
```mermaid
sequenceDiagram
Alice->>John: Hello John, how are you?
John-->>Alice: Great!
Alice-)John: See you later!
```

… will render a simple sequence diagram with three actors (Alice, John) and three messages between them.

JohnAliceJohnAliceHello John, how are you?Great!See you later!

⚠️

The rendered images will be in the form of SVGs and Astro’s image optimization capabilities aren’t leveaged. This solution is not perfect, but it’s a good start.

Let’s get started!

Table of Contents

What is MermaidJS?

MermaidJS is a simple and flexible diagramming tool that allows you to create diagrams using text-based syntax. It supports a variety of diagram types, including flowcharts, sequence diagrams, Gantt charts, and more. It’s architecture is based on Markdown and MDX, which makes it a great fit for Astro. It’s also possible to use MermaidJS with other static site generators like Eleventy, Hugo, and Jekyll.

MermaidJs is mainly client side rendering focused, but they have added a new CLI tool that can be used to render the diagrams server side. We’re not going to use the CLI tool in this post.

Since Astro supports remark plugins, we’re going to leverage the rehype-mermaid plugin to render the diagrams server side. This will build and SVG of the diagram and include it in the final HTML.

Extra Credit: Expressive Code

Since we’re here talking about adding in visuals, I wanted to mention the expressive code plugin. This plugin allows you to add syntax highlighting to your code blocks. This is a great way to make your code examples stand out and be more readable.

While Expressive Code does have support for showing mermaid, it will understandably just show the raw text of the diagram. This is where the rehype-mermaid plugin comes in to render the diagram. I’m adding in the expressive code plugin to show you how to add syntax highlighting to your code blocks AND still render the diagram.

This is not required to make mermaid work, but it’s a nice touch to make your code examples look better.

Visit Expressive Code for more details.

Adding to your Astro site

We’re going to use rehype-mermaid and Playwright modules and not mermaid directly or the mermaid CLI.

💡

Playwright is a framework for Web Testing and Automation. We’re using it here to render the diagrams server side. This is a requirement for the rehype-mermaid plugin.

It’s a broader topic, that I won’t go into detail here, but it pretty much saves the day when it comes to rendering the diagrams server side.

To add MermaidJS and Expressive Code to your Astro site, you’ll need to install the following packages at the rooth of your Astro project:

Adding Expressive Code, MermaidJS and Playwright to your Astro site
npx astro add astro-expressive-code
npm install remark-mermaidjs
npx playwright install --with-deps chromium

After installing playwright, you may see a warning message from playwright. This is because playwright is being installed before the project’s dependencies.

I didn’t do anything else after this and all went well.

Warning message from playwright
╔═══════════════════════════════════════════════════════════════════════════════╗
║ WARNING: It looks like you are running 'npx playwright install' without first ║
║ installing your project's dependencies. ║
║ ║
║ To avoid unexpected behavior, please install your dependencies first, and ║
║ then run Playwright's install command: ║
║ ║
║ npm install ║
║ npx playwright install ║
║ ║
║ If your project does not yet depend on Playwright, first install the ║
║ applicable npm package (most commonly @playwright/test), and ║
║ then run Playwright's install command to download the browsers: ║
║ ║
║ npm install @playwright/test ║
║ npx playwright install ║
║ ║
╚═══════════════════════════════════════════════════════════════════════════════╝

If you had MDX integration before or adding it in now, you may need to adjust the order of the plugins in your astro.config.mjs file. The order of the plugins is important, as they are executed in the order they are listed in the file. The mdx plugin should be listed before the astro-expressive-code plugin, as the mdx plugin is responsible for parsing the MDX content and converting it to HTML, which the astro-expressive-code plugin then processes to add syntax highlighting.

If you’re not using MDX, you can ignore where we add and configure it below.

Basic astro.config.mjs
import { defineConfig } from 'astro/config';
import mdx from '@astrojs/mdx';
import expressiveCode from "astro-expressive-code";
import remarkMermaid from 'remark-mermaidjs'
// https://astro.build/config
export default defineConfig({
site: 'https://example.com',
markdown: {
// Applied to .md and .mdx files
remarkPlugins: [remarkMermaid],
},
integrations: [expressiveCode(), mdx()]
});

Using MermaidJS in your blog posts

Within your markdown (.md) or MDX (.mdx) files, you can use the MermaidJS syntax to create diagrams. Here’s an example of a simple flowchart:

Flowchart example using MermaidJS text
```mermaid
graph TD;
A-->B;
A-->C;
B-->D;
C-->D;
```

This will render a simple flowchart with four nodes (A, B, C, D) and three edges connecting them.

A
B
C
D

If you want to show the mermaid code and the rendered diagram on the same page like above, you’ll need to wrap the mermaid code with the md tag and provide a title. Notice the extra backticks around the md tag. This is because we’re using the md tag within a code block, so we need to escape the backticks.

Here’s an example:

````md title="Flowchart example using MermaidJS text"
```mermaid
graph TD;
A-->B;
A-->C;
B-->D;
C-->D;
```
````

Update GitHub Actions

If you’re using GitHub Actions to deploy your site, you’ll need to update your workflow to include the Playwright dependencies.

When I first added the Playwright dependencies and committed to GitHub, I received an error message in the GitHub Actions workflow.

Error message in GitHub Actions
15:58:06 [build] Building static entrypoints...
Error: 2 [ERROR] [vite] x Build failed in 5.67s
[@mdx-js/rollup] browserType.launch: Executable doesn't exist at /home/runner/.cache/ms-playwright/chromium-1112/chrome-linux/chrome
╔═════════════════════════════════════════════════════════════════════════╗
║ Looks like Playwright Test or Playwright was just installed or updated. ║
║ Please run the following command to download new browsers: ║
║ ║
║ npx playwright install ║
║ ║
║ <3 Playwright Team ║
╚═════════════════════════════════════════════════════════════════════════╝
file: /home/runner/work/agramont.net/agramont.net/src/content/blogs/diagraming-with-mermaidjs-astro.mdx:undefined:undefined
Stack trace:
at Object.transform (file:///home/runner/work/agramont.net/agramont.net/node_modules/@astrojs/mdx/dist/index.js:107:27)
at async ModuleLoader.addModuleSource (file:///home/runner/work/agramont.net/agramont.net/node_modules/rollup/dist/es/shared/node-entry.js:18715:36)
Error: Process completed with exit code 1.

To make this work I needed to add the Playwright install command to the GitHub Actions workflow. This followed the documentation from Playwright: Playwright: CI GitHub Actions

You’ll want to install Playwright and the browsers before running the build.

⚠️

Updated 5/7/2024: After this post was published, I ran into the following error message and adjusted the YAML accordingly.

browserType.launch: Executable doesn’t exist at /home/runner/.cache/ms-playwright/chromium-1112/chrome-linux/chrome

Here’s an example of how you can do this in your GitHub Actions workflow file (This is NOT the complete YAML file):

.github/workflows/deploy.yml
Build_and_deploy_job:
permissions:
contents: read # for actions/checkout to fetch code
pull-requests: write # for Azure/static-web-apps-deploy to comment on PRs
if: github.event_name == 'push' || (github.event_name == 'pull_request' && github.event.action != 'closed')
runs-on: ubuntu-latest
name: Build and Deploy Job
steps:
- uses: actions/checkout@v3
with:
submodules: true
- uses: actions/setup-node@v3
with:
node-version: 18.17.x
cache: 'npm'
- name: Install dependencies
run: npm install
- name: Install Playwright
run: npm install -D @playwright/test@latest
- name: Install Playwright Browsers
run: npx playwright install --with-deps
- name: Build Astro Production
run: npm run build -mode production
- name: Build And Deploy
id: builddeploy
uses: Azure/static-web-apps-deploy@v1
with:
azure_static_web_apps_api_token: ${{ env.AZURE_STATIC_WEB_APPS_API_TOKEN }} # secret containing api token for app
repo_token: ${{ secrets.GITHUB_TOKEN }} # Used for Github integrations (i.e. PR comments)
action: "upload"
###### Repository/Build Configurations - These values can be configured to match you app requirements. ######
# For more information regarding Static Web App workflow configurations, please visit: https://aka.ms/swaworkflowconfig
app_location: ${{ env.APP_LOCATION }}
# api_location: ${{ env.API_LOCATION }}
skip_app_build: true
skip_api_build: true
app_artifact_location: ${{ env.APP_ARTIFACT_LOCATION }}
output_location: ${{ env.OUTPUT_LOCATION }}
###### End of Repository/Build Configurations ######

Starlight

If you’re using Starlight, a special Astro template that focuses on building great documentation sites, this same approach will work for you!

Starlight already has built-in support for MDX and syntax highlighting with Expressive Code. The only thing you need to install are remark-mermaidjs and playwright, then update the astro.config.mjs file to include the remark-mermaidjs plugin.

Here is an example of a basic astro.config.mjs file for Starlight:

Basic astro.config.mjs for Starlight
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';
import remarkMermaid from 'remark-mermaidjs'
// https://astro.build/config
export default defineConfig({
markdown: {
// Applied to .md and .mdx files
remarkPlugins: [remarkMermaid],
},
integrations: [
starlight({
title: 'My Docs',
social: {
github: 'https://github.com/withastro/starlight',
},
sidebar: [
{
label: 'Guides',
items: [
// Each item here is one entry in the navigation menu.
{ label: 'Example Guide', link: '/guides/example/' },
],
},
{
label: 'Reference',
autogenerate: { directory: 'reference' },
},
],
}),
],
});

Here is a screenshot a rendered diagram in Starlight based on updating an example page:

image

This was the text in Markdown that generated the diagram:

```mermaid
sequenceDiagram
participant Alice
participant John
rect rgb(191, 223, 255)
note right of Alice: Alice calls John.
Alice->>+John: Hello John, how are you?
rect rgb(200, 150, 255)
Alice->>+John: John, can you hear me?
John-->>-Alice: Hi Alice, I can hear you!
end
John-->>-Alice: I feel great!
end
Alice ->>+ John: Did you want to go to the game tonight?
John -->>- Alice: Yeah! See you there.
```

Mermaid Examples

To help inspire, the following are a few more examples of MermaidJS diagrams and links to where I found them:

User Journey Diagram

From: Mermaid.js.org: Diagram Syntax | User Journey Diagram

CatMe
Go to work
Go to work
Me
Make tea
Make tea
Me
Go upstairs
Go upstairs
MeCat
Do work
Do work
Go home
Go home
Me
Go downstairs
Go downstairs
Me
Sit down
Sit down
My working day

Gantt diagrams

From: Mermaid.js.org: Diagram Syntax | Gantt diagrams

2014-01-072014-01-092014-01-112014-01-132014-01-152014-01-172014-01-192014-01-212014-01-232014-01-252014-01-27Completed task Completed task in the critical line Implement parser and jison Describe gantt syntax Active task Create tests for parser Add gantt diagram to demo page Add another diagram to demo page Future task Future task in critical line Describe gantt syntax Add gantt diagram to demo page Add another diagram to demo page Future task2 Create tests for renderer Add to mermaid Functionality added A sectionCritical tasksDocumentationLast section Adding GANTT diagram functionality to mermaid

Semantic Kernel/OpenAI

From: How to visualize Semantic Kernel & Azure OpenAI plans using Mermaid

OrderHistoryPlugin_OrderHistoryLookupWebAppOpenAIOrderHistoryPlugin_OrderHistoryLookupWebAppOpenAIsystemuserassistant - P:858/C:22/T:880assistanttoolSystem: You are a customer support chatbot. You should answer the question posed by the user. Ground your answers based upon the user's purchase history. Make sure and look up any needed context for the specific user that is making the request. If you don't know the answer, respond saying you don't know. Only use the plugins that are registered to help you answer the question.  Username: dkschrute  Current Date: Jan-10-2024Will my sleeping bag work for my trip to Patagonia next month?OrderHistoryPlugin_OrderHistoryLookup - {  "username": "dkschrute"}{  "username": "dkschrute"}{"orderId":"1","customerId":"dkschrute","orderDate":"2021-01-01","orderTotal":"10","orderStatus":"Shipped","orderItems":[{"productId":"12345","productName":"Eco Elite Sleeping Bag","productPrice":"10","productQuantity":"1"}]}OrderHistoryPlugin_OrderHistoryLookup {"orderId":"1","customerId":"dkschrute","orderDate":"2021-01-01","orderTotal":"10","orderStatus":"Shipped","orderItems":[{"productId":"12345","productName":"Eco Elite Sleeping Bag","productPrice":"10","productQuantity":"1"}]}

Additional Resources

The following are additional links to resources that you may find helpful:

Conclusion

Adding diagrams to your site can help you communicate complex ideas more effectively. In this post, we looked at how you can use MermaidJS to create diagrams in your Astro site.

Using the MermaidJS live editor can help you create and test your diagrams before adding them to your site.

I hope this post has been helpful. If you used this to add diagrams to your site, I’d love to see them. Share them in the comments below!

Series: Astro

This post is part of a series.

Comments

Feel free to leave a comment below. Keep in mind that all comments are moderated and will be approved before being published.