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:
- The same diagram languages in every format. A sequence diagram shouldn’t depend on which format the post happens to be written in.
- Diagrams as source, in the repository. Text I can edit and review in a diff, not screenshots exported from some other tool.
- No JavaScript for the reader. The site is static HTML on GitHub Pages, and a diagram doesn’t change after the page loads.
- Readable in light and dark mode.
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:
I considered the alternatives first:
- Rendering in the browser with Mermaid’s own JavaScript library works, but every reader downloads and runs a diagram library to draw something that never changes. It also only covers Mermaid.
- Rendering locally during the build needs the right tool for each language: a headless browser for Mermaid, Java for PlantUML. That’s a lot of setup for a few diagrams, on my machine and in CI.
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:
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:
| Diagram | Extensions |
|---|---|
| PlantUML | .puml, .plantuml |
| Mermaid | .mmd, .mermaid |
| Excalidraw | .excalidraw |

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:
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:
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
- The build depends on kroki.io. If it’s down, diagrams fall back to their source until the next build. Self-hosting Kroki would remove that dependency.
- Diagrams are images. Their text can’t be selected or copied, and screen readers only get the alt text, so the alt text has to say what the diagram shows. I write it as a sentence or two that describes the diagram for someone who can’t see it, not a title.
- Data URIs live inside the HTML. A diagram isn’t cached separately by the browser, and a page with many diagrams gets bigger. For a handful of diagrams per post, that’s fine.
More examples on this site
- Understanding Embeddings, Vector Search, and RAG with Spring AI: seven inline PlantUML diagrams in an AsciiDoc post.
- Using Vue Components in Posts: inline Mermaid and PlantUML in MDX.
- Getting Started with Astro: a Mermaid diagram file in Markdown.
- Using Alpine.js in Astro: a PlantUML diagram file in MDX.
- Spring RestClient: A Modern Approach to HTTP Communication: a PlantUML diagram file in AsciiDoc.
About the Author
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. |