Skip to content
Wei Li
Go back

Diagrams in Astro Posts: Mermaid, PlantUML and Excalidraw

Edit page
Table of Contents

Posts on this blog come in three formats: Markdown, MDX and AsciiDoc. Some of them explain things that are much easier to show than to describe, like how a request moves through a client library, or what runs at build time and what runs in the browser. So I wanted diagrams, with a few requirements:

This post covers how that works now: the three ways to add a diagram, how they’re rendered, and the problems I hit on the way. Every diagram in it is rendered by the setup it describes.

The idea: render at build time with Kroki

Kroki is a service that turns diagram source into images, for more than twenty diagram languages, behind one HTTP API. You send it the source and get back an SVG.

This site calls Kroki during the build. The SVG it returns is embedded in the page as an image, so the published HTML already contains the finished picture. Readers never contact Kroki, and no diagram library is downloaded:

Markdown and MDX posts go through a remark plugin, AsciiDoc posts through the AsciiDoc loader. Both send the diagram source to Kroki and embed the SVG it returns in the page as an image.

I considered the alternatives first:

Kroki trades those for one dependency: the build needs internet access. GitHub Actions has it, and Kroki can be self-hosted with Docker if that ever becomes a problem.

Three ways to add a diagram

1. Inline in the post

The diagram’s source goes right into the post. In Markdown and MDX, that’s a code fence whose language is mermaid or plantuml. Alt text goes after the language:

```mermaid alt="The browser requests a page from GitHub Pages"
flowchart LR
    browser["Browser"] --> pages["GitHub Pages"]
```

In AsciiDoc, it’s the syntax the asciidoctor-diagram extension uses, so the same file still works with other Asciidoctor tools:

[plantuml, request-flow, svg]
....
@startuml
Browser -> "GitHub Pages" : GET /posts/hello/
@enduml
....

The overview above is an inline Mermaid diagram. Here’s an inline PlantUML one, showing what happens to a diagram during a build:

Sequence diagram: the build finds a diagram in a post and sends its source to Kroki, which returns an SVG. The build embeds the SVG in the page as an image. Later, a reader's browser loads the page from GitHub Pages without contacting Kroki.

2. A diagram file

A diagram can also live in its own file in src/assets/diagrams/. The post refers to it like an image, with a path relative to the post. The extension says what kind of diagram it is:

DiagramExtensions
PlantUML.puml, .plantuml
Mermaid.mmd, .mermaid
Excalidraw.excalidraw
![How to choose a diagram style](../../assets/diagrams/choosing-a-diagram-style.mmd)
image::../../assets/diagrams/choosing-a-diagram-style.mmd[How to choose a diagram style]

This suits a diagram that’s used in more than one post, or one you edit with an editor that previews PlantUML or Mermaid files. Here’s that Mermaid file, which also sums up when to use which approach:

Flowchart: if the diagram should look hand-drawn, use an Excalidraw file. Otherwise, if it's reused in several posts or edited in another tool, use a diagram file. Otherwise, write it inline in the post.

3. An Excalidraw drawing

Excalidraw is a whiteboard tool with a hand-drawn style. You draw in the browser and save the drawing as an .excalidraw file, which is JSON. That makes it just another diagram file: save it to src/assets/diagrams/ and refer to it like an image. To change it later, open the file at excalidraw.com and save over it.

Kroki embeds the hand-drawn font in the SVG, so the drawing looks the same for every reader. This one is reused from Writing Blog Posts in AsciiDoc, which is exactly the case files are for:

An AsciiDoc file goes through the loader (Asciidoctor, Shiki and Kroki) into the content store as rendered HTML, and from there onto the post page.

How it’s built

There are three pieces: one shared module that talks to Kroki, and one integration for each kind of post.

Talking to Kroki

src/utils/kroki.ts sends the source to Kroki and returns the SVG as a data URI, ready to use as an image’s src. Results are cached by type and source, so astro dev doesn’t fetch an unchanged diagram again on every reload:

export function renderDiagram(language: string, source: string) {
  const type = DIAGRAM_TYPES[language];
  const key = `${type}\n${source}`;
  let uri = cache.get(key);
  if (!uri) {
    uri = fetch(`https://kroki.io/${type}/svg`, {
      method: "POST",
      headers: { "Content-Type": "text/plain" /* plus Kroki options */ },
      body: prepareSource(type, source),
    }).then(async res => {
      if (!res.ok) throw new Error(`Kroki returned ${res.status}`);
      const svg = await res.text();
      return `data:image/svg+xml;base64,${Buffer.from(svg).toString("base64")}`;
    });
    uri.catch(() => cache.delete(key)); // retry failures on the next reload
    cache.set(key, uri);
  }
  return uri;
}

Embedding the SVG as an <img> instead of inline <svg> markup keeps each diagram self-contained: its styles and element IDs can’t clash with the page or with other diagrams.

Markdown and MDX: a remark plugin

Astro processes Markdown with remark, and MDX uses the same plugins, so one remark plugin covers both formats. It’s registered in astro.config.ts:

markdown: {
  processor: unified({
    remarkPlugins: [/* other plugins, */ remarkDiagrams],
  }),
},

The plugin walks the Markdown syntax tree looking for two kinds of node: code blocks whose language is a diagram language, and images whose path ends in a diagram file extension. It renders all of them in parallel and replaces each node with the image.

The replacement can’t be raw HTML, because MDX has no raw HTML nodes. Instead the plugin uses a node that remark turns into a specific HTML element through its data fields. This works in both formats:

{
  type: "diagram",
  data: {
    hName: "div",
    hProperties: { className: ["diagram"] },
    hChildren: [
      { type: "element", tagName: "img", properties: { src, alt }, children: [] },
    ],
  },
}

AsciiDoc: the content loader

AsciiDoc posts go through this site’s own content loader, which converts them with Asciidoctor. Diagrams have to be handled before conversion, because Asciidoctor’s HTML doesn’t record that a block was a diagram: a [plantuml] block comes out as a plain code block, just like any other.

So the loader works on Asciidoctor’s document tree instead. It finds the listing blocks styled plantuml or mermaid, and the image blocks that point at diagram files, renders them, and swaps each one for a passthrough block containing the image. Then it converts the document as usual.

What I ran into

Mermaid labels got clipped. Mermaid normally draws its labels as HTML inside the SVG and sizes the boxes by measuring that text. Kroki measures it with the fonts on its server, but the reader’s browser draws it with the fonts on the reader’s machine. Where those were wider, the ends of labels were cut off. The fix was a Kroki option that makes Mermaid use plain SVG text.

Then long names were split in the middle. Plain SVG labels wrap at 200 pixels, even inside a single word, so RestClientHttpServiceGroupConfigurer came out as three pieces. Kroki has no option for the wrapping width, so the build adds a Mermaid directive to each diagram before sending it:

%%{init: {"flowchart": {"wrappingWidth": 400}}}%%

The directive goes after the diagram’s own frontmatter, if it has any, because Mermaid requires frontmatter to come first. Posts never see it; it’s added on the way to Kroki.

Dark mode. Most diagrams are black lines on a transparent or white background, which disappears on a dark page. Every diagram therefore sits on a white card with a thin border, in both themes.

Images inside paragraphs. In Markdown, an image is part of a paragraph, and a block-level <div> isn’t allowed inside a <p>. When a diagram file is the only thing in its paragraph, the plugin replaces the whole paragraph. A diagram inside a sentence becomes an inline <span> instead.

Failures shouldn’t break the build. A typo in a diagram makes Kroki return an error. Instead of failing the build, the post shows the diagram’s source as a code block, or a diagram file’s alt text, and the build log gets a warning. A remark plugin has no access to Astro’s logger, so it writes the warning to the console, with an explicit exception to this site’s lint rule against console calls.

Stale diagrams locally. Astro caches rendered Markdown and only re-renders a post when the post’s own file changes. Editing a diagram file used by a Markdown post doesn’t count, so a local build keeps showing the old picture. Deleting .astro/data-store.json clears the cache. Deploys start from a clean checkout, so the live site is never affected.

Trade-offs

More examples on this site

About the Author

Wei Li

Wei Li is a passionate software professional who builds enterprise applications with modern technologies. The guides here come from that work: each one explains a feature and shows it in working code.

Read more on the About page, or find Wei Li on GitHub.


Edit page
Share this post:

Previous Post
Interactive Java Examples with Vue
Next Post
Canon EOS R50: A Simple Guide to Taking Photos