Goodbye Ugly Charts: How to Render Professional SVGs and Terminal Graphics with Beautiful Mermaid
In modern development and product workflows, diagrams are more than just auxiliary tools; they are a universal language for communicating complex logic. Beautiful Mermaid is a powerful tool designed to render Mermaid diagrams into stunning SVGs or ASCII art. It not only resolves the aesthetic and dependency pain points of traditional renderers but also perfectly adapts to various scenarios—from rich web interfaces to pure terminal environments—thanks to its extreme speed, zero DOM dependencies, and powerful theming system.
This article delves into the core features, technical implementation details, and practical use cases of Beautiful Mermaid, helping you completely revolutionize the presentation of your diagrams.
Why Do We Need a New Mermaid Renderer?
Core Question: What are the critical flaws in existing Mermaid rendering solutions that compel us to rebuild a rendering engine?
Although Mermaid has become the de facto standard for text-based diagrams, its default rendering solutions have gradually shown limitations in actual enterprise applications and AI-assisted programming scenarios. These issues primarily focus on aesthetics, customization costs, output environment compatibility, and performance overhead.
1. Limitations of Aesthetic Perspective
For products that strive for ultimate user experience, default diagram styles often appear unprofessional. This is not merely a matter of aesthetic preference but a challenge of brand consistency. Many teams find that adjusting default styles to match their design system requires a disproportionate amount of effort. We want charts that look professional, refined, and seamlessly integrated into modern UI design, rather than appearing jarring or rudimentary.
2. Complex Theme Customization Logic
Traditional Mermaid theming relies on wrestling with CSS classes. Developers must deeply understand the internal DOM structure and override numerous CSS classes to achieve basic color adjustments. This approach is not only cumbersome but also extremely fragile; customized styles easily break if the underlying structure updates. We need a more intuitive, modern frontend development-friendly theme configuration method.
3. Lack of Terminal Output Capabilities
With the rise of AI-assisted programming, much interaction happens within terminals or chat interfaces. However, standard Mermaid renderers cannot generate ASCII or Unicode character art, meaning users cannot visually see data flows, state machines, or system architectures in CLI tools or pure text environments. This is a significant functional gap for developers who need visual feedback inside the terminal.
4. Heavy Dependency Baggage
To render a simple diagram, traditional solutions often pull in a massive amount of dependency code. For modern applications that pursue extreme performance and bundle size optimization, this redundancy is unacceptable. We need a lightweight, high-performance, zero-dependency solution that ensures it runs in any JavaScript environment—whether it’s a browser, Node.js, or an edge computing environment.
Image Source: Unsplash
Core Capabilities Breakdown: Dual Output and Extreme Performance
Core Question: How can we enable a single piece of diagram code to adapt perfectly to both high-end web interfaces and minimalist terminal environments?
The most significant technical highlight of Beautiful Mermaid is its dual-mode output capability. It utilizes a rendering engine implemented in pure TypeScript to output high-quality SVG vector graphics and ASCII/Unicode character art from a single data source.
1. SVG Output: Built for Rich UIs
For web applications, documentation sites, or dashboards, SVG is the best choice. It supports lossless scaling, CSS style injection, and interactive events. The SVGs generated by Beautiful Mermaid are not just images; they are semantically structured programmable objects.
Application Scenario Example:
Imagine you are building an AI-based code review tool. When the code contains complex Mermaid flowchart comments, you can call the rendering interface to render a high-fidelity SVG chart in real-time on the web sidebar. Since it supports live theme switching, when users toggle the editor’s “Dark Mode” or “Light Mode,” the chart colors can update synchronously without re-requesting server-side rendering.
2. ASCII Output: Filling the Terminal Visualization Gap
In CLI tools, IDE terminals, or text-based AI chat interfaces, graphics are usually difficult to display. Beautiful Mermaid’s built-in ASCII rendering engine (ported from mermaid-ascii, rewritten in TypeScript, and extended) solves this problem. It supports Unicode box-drawing characters, making charts look clear and beautiful even in the terminal.
Technical Details:
By default, the renderer uses Unicode characters (like ┌───┐ and │) to draw connecting lines and borders, which looks visually better and smoother than traditional ASCII characters (+---+ and |). However, a pure ASCII mode is also provided for compatibility with older terminal environments that do not support Unicode.
Code Implementation Example:
import { renderMermaidAscii } from 'beautiful-mermaid'
// Use default Unicode mode
const unicode = renderMermaidAscii(`graph LR; A --> B --> C`)
console.log(unicode)
// Output effect:
// ┌───┐ ┌───┐ ┌───┐
// │ │ │ │ │ │
// │ A │────►│ B │────►│ C │
// │ │ │ │ │ │
// └───┘ └───┘ └───┘
3. Performance Profile: Ultra-Fast Rendering
Thanks to its zero DOM dependency design, Beautiful Mermaid renders with extreme speed. In benchmarks, it can render over 100 diagrams in under 500ms. This performance level makes it ideal for batch rendering tasks, such as generating hundreds or thousands of charts in one go when building documentation sites.
Deep Dive into the Theming System: From Two-Color Foundation to Shiki Integration
Core Question: How can we achieve visually appealing and highly customizable chart themes with the absolute minimum configuration code?
The theming system of Beautiful Mermaid is the core of its competitiveness. It abandons the complex CSS override logic in favor of a modern solution based on CSS variables and color math derivation.
1. Mono Mode: The Elegant Binary Aesthetic
Often, we don’t need colorful charts; we just need clear, professional black-and-white (or primary-secondary) contrast. The system proposes the concept of a “Two-Color Foundation”: You only define bg (background color) and fg (foreground color), and the system automatically uses CSS’s color-mix() function to derive the colors for all other elements in the chart.
Color Derivation Logic Table:
| Element | Derivation Algorithm Logic | Visual Effect |
|---|---|---|
| Primary Text | --fg (100%) |
Clearest information |
| Secondary Text / Notes | --fg mixed into --bg (60%) |
De-emphasized, not distracting |
| Connecting Lines | --fg mixed into --bg (30%) |
Very faint connections, guiding the eye |
| Arrow Heads | --fg mixed into --bg (50%) |
Moderate emphasis |
| Node Fill Background | --fg mixed into --bg (3%) |
Very faint tint to distinguish areas |
| Node Border | --fg mixed into --bg (20%) |
Clear outline but not harsh |
This design means you never have to worry about color conflicts. As long as you choose a background and text color, the entire chart automatically presents a harmonious visual effect.
2. Live Theme Switching: The Power of CSS Variables
The generated SVG elements use CSS custom properties internally. This brings a huge advantage: switching themes without re-rendering the SVG.
Scenario Explanation:
Assume your web application has a theme toggle button. In traditional tools, clicking “Switch Dark Mode” usually requires re-rendering the chart to change colors. But in Beautiful Mermaid, you only need to modify the CSS variables on the SVG element via JavaScript, and the chart colors change instantly, offering a silky-smooth experience.
// Assume svg is the rendered DOM element
svg.style.setProperty('--bg', '#282a36')
svg.style.setProperty('--fg', '#f8f8f2')
// The chart updates immediately without recalculating layout
3. Enriched Mode: Fine-Grained Control
If the two-color mode doesn’t meet your needs, you can introduce “enrichment colors” to override the automatic derivations. This incremental configuration approach is very flexible; you can override only the parts you care about (e.g., making arrows red) while letting other parts remain auto-derived.
4. Full Shiki Compatibility
For developer tools, maintaining consistency between code highlighting and chart style is crucial. Beautiful Mermaid provides the fromShikiTheme function, which can directly read VS Code’s Shiki theme configuration and map it to diagram colors.
Mapping Logic Table:
| VS Code Editor Color Property | Diagram Role | Description |
|---|---|---|
editor.background |
bg |
Base background color |
editor.foreground |
fg |
Base foreground color |
editorLineNumber.foreground |
line |
Connector color (unobtrusive like line numbers) |
focusBorder or keyword |
accent |
Accent color (for arrows, highlights) |
comment |
muted |
Auxiliary text color |
editor.selectionBackground |
surface |
Node fill color (like selection blocks) |
editorWidget.border |
border |
Node border color |
This integration ensures charts blend perfectly into the visual environment of the code editor, as if the chart is part of the code itself.
Image Source: Unsplash
Installation Configuration and Practical Code
Core Question: How can developers quickly integrate Beautiful Mermaid into existing frontend, Node.js, or pure HTML projects?
The installation and usage process is designed to be as simple as possible, supporting major package managers and providing native support for browser environments.
1. Environment Installation
Whether you are using npm, bun, or pnpm, just one command completes the installation:
npm install beautiful-mermaid
# or
bun add beautiful-mermaid
# or
pnpm add beautiful-mermaid
2. Basic SVG Rendering Example
In TypeScript or JavaScript environments, you can use the renderMermaid function. This is an asynchronous function that returns the generated SVG string.
import { renderMermaid } from 'beautiful-mermaid'
async function generateDiagram() {
const mermaidCode = `
graph TD
A[Start] --> B{Decision}
B -->|Yes| C[Action]
B -->|No| D[End]
C --> D
`
// Render using an inline theme object
const svg = await renderMermaid(mermaidCode, {
bg: '#1a1b26',
fg: '#a9b1d6'
})
console.log(svg)
}
3. Direct Browser Reference
For scenarios where you don’t want to use a bundler, you can import the global package directly via CDN. This is especially suitable for rapid prototyping or integration into CMS systems.
<script src="https://unpkg.com/beautiful-mermaid/dist/beautiful-mermaid.browser.global.js"></script>
<script>
// Access the global object beautifulMermaid
const { renderMermaid, THEMES } = beautifulMermaid;
renderMermaid('graph TD; A-->B').then(svg => {
document.body.innerHTML = svg;
});
</script>
4. ASCII Rendering and Configuration
For terminal output, use renderMermaidAscii. This is a synchronous function and provides precise spacing control options.
import { renderMermaidAscii } from 'beautiful-mermaid'
const diagram = `graph LR; A[Server] --> B[Client]`
const ascii = renderMermaidAscii(diagram, {
useAscii: false, // false = Unicode (default), true = Pure ASCII
paddingX: 5, // Horizontal node spacing
paddingY: 5, // Vertical node spacing
boxBorderPadding: 1 // Padding inside node boxes
})
console.log(ascii)
Supported Diagram Types and Practical Applications
Core Question: Which diagram types does Beautiful Mermaid currently support, and what business problems are they suitable for solving?
Although it currently supports 5 core diagram types, this covers the vast majority of engineering architecture and business process description needs.
1. Flowcharts
Flowcharts are the go-to tool for describing algorithm logic, business processes, or approval chains. Beautiful Mermaid supports all directions: TD (Top-Down), LR (Left-Right), BT (Bottom-Top), RL (Right-Left).
-
Use Case: Describing CI/CD pipeline steps or the status flow of an e-commerce order.
2. State Diagrams
Used to describe the transition of different states in a system lifecycle.
-
Use Case: In IoT device firmware development, describing the state machine changes of a device from “Idle” to “Connecting” to “Transferring Data.”
3. Sequence Diagrams
Shows the order of interaction between objects, particularly suitable for timing descriptions in microservice architectures.
-
Use Case: Analyzing API call latency between backend services or demonstrating the WebSocket handshake process between frontend and backend.
4. Class Diagrams
UML class diagrams are used to display class structures and their relationships in object-oriented design.
-
Use Case: When refactoring legacy code, intuitively presenting the current system’s coupling level via class diagrams to help plan decoupling strategies.
5. ER Diagrams
Entity-Relationship diagrams are used for database modeling.
-
Use Case: Visually displaying the one-to-many or many-to-many relationships between User, Order, and Product tables when designing a new database Schema.
Reflections and Technical Insights
After deeply studying the design and implementation of Beautiful Mermaid, I have a few profound realizations.
First, “Less is More” still applies in engineering tools. The library’s “Two-Color Mode” design is a stroke of genius. In many tool libraries, developers are often drowned in hundreds of configuration options, yet Beautiful Mermaid proves that as long as the core logic (like color mixing) is intelligent enough, users only need to provide the most basic input to achieve professional results. This design philosophy drastically lowers the barrier to entry.
Second, the return of the terminal experience deserves attention. With the rise of DevOps and AI coding assistants, the terminal is no longer just a command line; it is evolving into a powerful graphical (even if it’s character-art graphics) interactive interface. Beautiful Mermaid敏锐ly captured this point, making ASCII rendering a core feature, which gives it a unique advantage when building CLI tools or Serverless AI Agents.
Finally, Zero DOM dependency architecture is the future trend. Traditional visualization libraries often heavily rely on browser DOM APIs, making them difficult to run in Node.js server-side or Worker threads. Beautiful Mermaid implements logic in pure TypeScript, separating rendering from output. This decoupled design gives it extreme environmental adaptability.
Practical Summary / Action Checklist
To help you get started quickly, here are the key steps and decision points for integrating Beautiful Mermaid into your project:
-
Choose Output Mode: -
If for Web/Docs display, use renderMermaidto generate SVG. -
If for CLI/Terminal logs, use renderMermaidAsciito generate character art.
-
-
Configure Themes: -
Quick Start: Use built-in themes directly (e.g., THEMES['tokyo-night']). -
Minimalist Style: Define only bgandfgto enable Mono Mode. -
Brand Adaptation: Utilize CSS variables to dynamically modify SVG’s --bgand--fgwithout redrawing. -
Editor Sync: Import shikiand usefromShikiThemeto auto-extract colors.
-
-
Environment Integration: -
Frontend Projects: Import via npm installand render asynchronously. -
Non-Engineered: Use the <script>tag to import CDN resources.
-
-
Performance Optimization: -
Leverage its “Zero DOM” nature to perform batch rendering in Web Workers, avoiding blocking the main thread.
-
One-page Summary
| Feature | Description | Best For |
|---|---|---|
| Dual Output | Supports SVG and ASCII/Unicode rendering modes | Web UI / CLI Tools / AI Chat |
| Smart Theming | Two-color based derivation system, supports CSS variable hot-swapping | Dynamic Skins / Dark Mode |
| High Performance | Pure TypeScript implementation, Zero DOM dependencies, ultra-fast rendering | Server-Side Rendering / Batch Generation |
| Shiki Integration | Directly reads VS Code theme configurations | Developer Tools / Code Editor Plugins |
| Multi-Type Support | Covers Flowchart, State, Sequence, Class, ER diagrams (5 types) | Architecture Design / Code Docs / Data Modeling |
Frequently Asked Questions (FAQ)
1. What is the fundamental difference between Beautiful Mermaid and native Mermaid.js?
Native Mermaid.js focuses on rendering in the browser via DOM, is heavy on dependencies, and theming is complex; Beautiful Mermaid is a pure TypeScript rewrite focused on controllable output (SVG/ASCII), minimalist theme configuration, and high-performance performance in non-browser environments.
2. How do I dynamically modify colors on an already generated SVG?
Simply get the SVG DOM element and modify the CSS custom properties via style.setProperty('--bg', 'newColor'). There is no need to call the render function again.
3. Does ASCII rendering support all types of Mermaid charts?
Currently, it primarily supports Flowcharts, State Diagrams, Sequence Diagrams, Class Diagrams, and ER Diagrams. This covers the vast majority of common technical diagramming needs.
4. Can I use custom fonts?
Yes. When calling renderMermaid, you can pass the font property (such as 'Inter' or 'Fira Code') via the options parameter, and the rendered SVG will apply that font.
5. Can I use it in a Node.js environment?
Absolutely. Due to its “Zero DOM dependency” nature, it runs perfectly in Node.js environments, making it very suitable for generating static documentation sites or performing server-side diagram rendering.
6. How do I ensure the generated SVG isn’t glaring on a dark background?
Use Mono Mode: set bg to your dark background value and fg to a light gray text value. The system will automatically calculate low-contrast borders and fills to ensure visual comfort.
