Skip to content

Mermaid Diagrams

Gozzi has built-in support for Mermaid diagrams with client-side rendering. Write diagrams directly in your markdown using familiar Mermaid syntax.

How It Works

Client-Side Rendering (Browser):

Markdown: ```mermaid graph TD; A-->B; ```
    ↓ (Gozzi wraps in special container during build)
HTML: <pre class="mermaid">graph TD; A-->B;</pre>
    ↓ (MermaidJS runs in browser)
Rendered: Beautiful SVG diagram

Build Time vs Browser:

  • Build time: Gozzi converts mermaid code blocks to <pre class="mermaid">...</pre> HTML
  • Browser: MermaidJS library renders the diagram code as interactive SVG

What You Need:

  1. Mermaid syntax in markdown - Standard mermaid code blocks
  2. MermaidJS library - Must be included in your templates (see Setup)

What You Get:

  • ✅ Interactive diagrams with hover effects
  • ✅ Theme support (light/dark modes)
  • ✅ Pan and zoom capabilities
  • ✅ Dynamic rendering

Why Client-Side?

Mermaid uses client-side rendering because:

  • Interactive features - Hover tooltips, click events, pan/zoom
  • Theme integration - Automatically matches your site's light/dark theme
  • Simpler builds - No Node.js/Mermaid CLI dependency for building
  • Cross-platform - Works everywhere without system dependencies

Trade-off: Requires JavaScript (~200KB) but enables richer diagram interactions.

Basic Usage

Write Mermaid diagrams in standard code blocks with the mermaid language identifier:

Flowchart:

markdown
```mermaid
graph TD
    A[Start] --> B{Decision}
    B -->|Yes| C[Action 1]
    B -->|No| D[Action 2]
```

Sequence Diagram:

markdown
```mermaid
sequenceDiagram
    Alice->>Bob: Hello Bob!
    Bob-->>Alice: Hi Alice!
```

Supported Diagram Types

Gozzi supports all Mermaid diagram types:

  • Flowcharts: Process flows and decision trees
  • Sequence Diagrams: System interactions over time
  • Class Diagrams: Object-oriented relationships
  • State Diagrams: State machine representations
  • Entity Relationship: Database schemas
  • Gantt Charts: Project timelines and schedules
  • Pie Charts: Data visualization
  • Git Graphs: Branch and commit visualization
  • User Journey: User experience flows
  • And more: See Mermaid documentation for all types

Setup

To render Mermaid diagrams, you need to include the MermaidJS library in your templates.

Add to your template's <head> or before </body>:

html
<!-- Load MermaidJS from CDN -->
<script type="module">
    import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs';
    mermaid.initialize({ startOnLoad: true });
</script>

Quick setup example (templates/partials/_scripts.html):

html
<!-- MermaidJS for diagram rendering -->
<script type="module">
    import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs';
    mermaid.initialize({ 
        startOnLoad: true,
        theme: 'default' // or 'dark', 'forest', 'neutral'
    });
</script>

Benefits:

  • ✅ Always latest stable version
  • ✅ Fast CDN delivery
  • ✅ No local file management
  • ✅ Automatic caching

Option 2: Self-Hosted

For full control or offline usage, download MermaidJS:

  1. Download: Get mermaid from npm or GitHub releases

  2. Add to static directory:

    static/
      js/
        mermaid.min.js
  3. Include in template:

    html
    <script src="/js/mermaid.min.js"></script>
    <script>
        mermaid.initialize({ startOnLoad: true });
    </script>

Benefits:

  • ✅ Full version control
  • ✅ Works offline
  • ✅ No external dependencies
  • ✅ Custom build options

Verify Setup

After adding MermaidJS to your templates:

  1. Add a test diagram to any markdown file:

    markdown
    ```mermaid
    graph LR
        A[Setup] --> B[Working!]
    ```
  2. Build and serve:

    bash
    gozzi build
    gozzi serve
  3. Check browser console (F12) - should see no MermaidJS errors

If you see the diagram rendered as SVG, you're all set! If you see code blocks instead, check the Troubleshooting section.

Advanced Configuration

Customize Mermaid's behavior with initialization options:

html
<script type="module">
    import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs';
    mermaid.initialize({
        startOnLoad: true,
        theme: 'dark',
        themeVariables: {
            primaryColor: '#BB2528',
            primaryTextColor: '#fff',
            primaryBorderColor: '#7C0000',
        },
        flowchart: {
            useMaxWidth: true,
            htmlLabels: true,
            curve: 'basis',
        },
        sequence: {
            diagramMarginX: 50,
            diagramMarginY: 10,
            actorMargin: 50,
        },
    });
</script>

Common configuration options:

  • theme - Built-in themes: default, dark, forest, neutral
  • themeVariables - Custom color overrides
  • startOnLoad - Auto-render on page load (keep true)
  • logLevel - Debug level: 1 (debug), 2 (info), 3 (warn), 4 (error)

See Mermaid configuration docs for all options.

Example

Complete Example with Multiple Diagrams
markdown
# System Architecture

## User Flow

```mermaid
graph TD
    A[User] --> B[Web Browser]
    B --> C[Load Balancer]
    C --> D[Web Server]
    D --> E[Database]
    D --> F[Cache]

API Sequence

mermaid
sequenceDiagram
    participant Client
    participant API
    participant DB
    Client->>API: POST /users
    API->>DB: INSERT user
    DB-->>API: User ID
    API-->>Client: 201 Created

Data Model

mermaid
erDiagram
    USER ||--o{ POST : writes
    USER ||--o{ COMMENT : writes
    POST ||--o{ COMMENT : has

Styling

Mermaid diagrams automatically inherit your site's theme when configured properly. You can also add custom CSS:

css
/* Custom diagram container styling */
.mermaid {
    text-align: center;
    margin: 2rem 0;
    background: var(--bg-secondary);
    padding: 1rem;
    border-radius: 8px;
}

/* Responsive diagrams */
.mermaid svg {
    max-width: 100%;
    height: auto;
}

Dynamic Theme Switching

Match Mermaid theme to your site's light/dark mode:

html
<script type="module">
    import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs';
    
    // Detect theme from data attribute or media query
    const isDark = document.documentElement.getAttribute('data-theme') === 'dark' ||
                   window.matchMedia('(prefers-color-scheme: dark)').matches;
    
    mermaid.initialize({ 
        startOnLoad: true,
        theme: isDark ? 'dark' : 'default'
    });
    
    // Re-render on theme change
    document.addEventListener('themechange', (e) => {
        mermaid.initialize({ 
            startOnLoad: true, 
            theme: e.detail.theme === 'dark' ? 'dark' : 'default'
        });
        mermaid.contentLoaded();
    });
</script>

Quick Start Checklist

  1. Add MermaidJS to your templates:

    html
    <script type="module">
        import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs';
        mermaid.initialize({ startOnLoad: true });
    </script>
  2. Write diagram in markdown:

    markdown
    ```mermaid
    graph LR
        A --> B
    ```
  3. Build and view:

    bash
    gozzi build
    gozzi serve

That's it! Your diagrams will render as interactive SVG in the browser.

Troubleshooting

Diagrams don't render (show as code blocks)

Problem: You see the raw mermaid syntax in a code block instead of a rendered diagram.

Possible causes:

  1. MermaidJS not loaded - Check if script is included in your template
  2. JavaScript disabled - MermaidJS requires JavaScript to run
  3. Browser console errors - Check dev tools for loading/parsing errors

Solution:

  • Verify MermaidJS script is in your template's <head> or before </body>
  • Check browser console (F12) for error messages
  • Ensure JavaScript is enabled
  • Try a different browser (Chrome, Firefox, Safari)

Browser console shows "mermaid is not defined"

Problem: Script tag has wrong syntax or didn't load.

Solution:

Make sure you're using the correct module import syntax:

html
<!-- ✅ Correct -->
<script type="module">
    import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs';
    mermaid.initialize({ startOnLoad: true });
</script>

<!-- ❌ Wrong - missing type="module" -->
<script>
    import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs';
    mermaid.initialize({ startOnLoad: true });
</script>

Diagrams render with wrong theme

Problem: Diagrams appear in light theme when your site uses dark mode.

Solution: Update theme in mermaid configuration:

javascript
mermaid.initialize({ startOnLoad: true, theme: 'dark' });

Or dynamically detect theme (see Dynamic Theme Switching).

Diagrams flicker on page load

Problem: You see code blocks briefly before diagrams render.

Solution: Hide mermaid blocks until rendered:

css
.mermaid {
    opacity: 0;
    transition: opacity 0.3s;
}

.mermaid[data-processed='true'] {
    opacity: 1;
}

Complex diagrams cause layout issues

Problem: Large diagrams overflow or break responsive layout.

Solution: Add responsive container styling:

css
.mermaid {
    max-width: 100%;
    overflow-x: auto;
}

.mermaid svg {
    max-width: 100%;
    height: auto;
}

CDN fails to load (network issues)

Problem: Corporate firewall or network blocks CDN access.

Solution: Use self-hosted MermaidJS (see Option 2: Self-Hosted).

FAQ

Q: Why client-side rendering instead of build-time?
A: Client-side Mermaid provides:

  • Interactive features (hover, click, pan/zoom)
  • Dynamic theme switching
  • No build dependencies (Node.js, Mermaid CLI)
  • Simpler cross-platform builds
  • ~200KB JavaScript is reasonable for modern web

Q: Can I use Mermaid offline/without CDN?
A: Yes! Use the self-hosted option. Download MermaidJS and include it from your static/ directory. See Option 2: Self-Hosted.

Q: Does this work with all Mermaid diagram types?
A: Yes! Gozzi uses standard mermaid code blocks, so all Mermaid diagram types are supported.

Q: Can I customize diagram colors and styles?
A: Yes! Use themeVariables in mermaid configuration. See Advanced Configuration above.

Q: Will diagrams work for users with JavaScript disabled?
A: No, client-side Mermaid requires JavaScript. Consider adding a fallback message:

html
<noscript>
    <p>Interactive diagrams require JavaScript to display. Please enable JavaScript to view diagrams.</p>
</noscript>

Q: Can I use a specific version of MermaidJS?
A: Yes! Specify the version in the CDN URL:

html
<script type="module">
    import mermaid from 'https://cdn.jsdelivr.net/npm/[email protected]/dist/mermaid.esm.min.mjs';
    mermaid.initialize({ startOnLoad: true });
</script>

Q: How do I debug mermaid rendering issues?
A: Enable debug logging:

javascript
mermaid.initialize({ 
    startOnLoad: true, 
    logLevel: 1 // 1=debug, 2=info, 3=warn, 4=error
});

Check browser console for detailed error messages.


Real-World Example

See Mermaid diagrams in action on tduyng.com: Mermaid Support

Related:

Released under the MIT License.