• English
  • Mermaid Diagrams

    ModernDuang includes built-in support for Mermaid, a JavaScript library that renders diagrams and charts from plain text descriptions. Use Mermaid to create flowcharts, sequence diagrams, class diagrams, Gantt charts, and more — all within your Markdown posts.

    Enabling Mermaid

    Mermaid is loaded per post to avoid unnecessary JavaScript on pages that do not use it. To enable Mermaid for a specific post, add mermaid: true to the post's frontmatter:

    ---
    title: My Architecture Overview
    date: 2025-06-15
    categories: 技术
    mermaid: true
    ---
    
    Here is a flowchart of the system architecture:
    
    ```mermaid
    flowchart TD
        A[User] --> B[Frontend]
        B --> C[API Gateway]
        C --> D[Service A]
        C --> E[Service B]
        D --> F[(Database)]
        E --> F
    
    When `mermaid: true`, the theme loads the Mermaid library **only on that post's page**. Posts without the flag will not load the Mermaid JavaScript, keeping page weight minimal.
    
    > **Important:** Mermaid code blocks use ` ```mermaid ` as the language identifier. Other identifiers (like ` ```mermaid-js ` or ` ```mmd `) are not supported.
    
    ## Lazy Loading
    
    To optimize performance, Mermaid is loaded asynchronously:
    
    1. The Mermaid library is loaded via **dynamic import** — it only begins downloading when the page detects a Mermaid code block
    2. The library loads from a **CDN** (`unpkg` or `jsdelivr` by default)
    3. Diagrams render **after DOM content is loaded**, so your post text is visible immediately — diagrams fill in as they render
    4. A subtle **loading placeholder** is shown inside each diagram block until rendering completes
    
    This approach means Mermaid adds zero cost to your site's initial load time unless a visitor opens a post that actually contains diagrams.
    
    ### Hexo Tag Syntax
    
    As an alternative to fenced code blocks, ModernDuang also supports the **Hexo tag syntax** for Mermaid diagrams:
    
    ```markdown
    {% mermaid %}
    flowchart TD
        A[User] --> B[Frontend]
        B --> C[API Gateway]
        C --> D[Service A]
        C --> E[Service B]
        D --> F[(Database)]
        E --> F
    {% endmermaid %}

    Both syntaxes are equivalent and produce identical output. The tag syntax can be more convenient when your diagram content contains special characters. Regardless of which syntax you use, you must still set mermaid: true in the post frontmatter.

    Supported Diagram Types

    ModernDuang supports all diagram types provided by Mermaid. Here are the most commonly used:

    Diagram TypeSyntaxUse Case
    Flowchartflowchart TD/LRProcess flows, decision trees
    Sequence DiagramsequenceDiagramAPI interactions, message passing
    Class DiagramclassDiagramOOP class relationships
    State DiagramstateDiagram-v2State machines, lifecycle states
    Entity RelationshiperDiagramDatabase schemas
    Gantt ChartganttProject timelines, schedules
    Pie ChartpieData distribution
    Git GraphgitGraphGit branch/commit visualizations
    MindmapmindmapHierarchical brainstorming
    TimelinetimelineChronological event sequences

    Example: Sequence Diagram

    ```mermaid
    sequenceDiagram
        participant U as User
        participant F as Frontend
        participant A as API
        participant D as Database
    
        U->>F: Click "Login"
        F->>A: POST /auth/login
        A->>D: SELECT user
        D-->>A: User record
        A-->>F: JWT token
        F-->>U: Redirect to dashboard
    ```

    Example: Gantt Chart

    ```mermaid
    gantt
        title Project Roadmap
        dateFormat  YYYY-MM-DD
        section Design
        Wireframes       :2025-01-01, 14d
        UI Design        :2025-01-15, 21d
        section Development
        Backend API      :2025-01-20, 30d
        Frontend         :2025-02-01, 28d
        section Testing
        QA               :2025-03-01, 14d
    ```

    Example: State Diagram

    ```mermaid
    stateDiagram-v2
        [*] --> Draft
        Draft --> Review: Submit
        Review --> Published: Approve
        Review --> Draft: Reject
        Published --> Archived: Archive
        Archived --> [*]
    ```

    Example: Mindmap

    ```mermaid
    mindmap
      root((My Blog))
        技术
          Frontend
            React
            Vue
          Backend
            Node.js
            Python
        生活
          读书
          旅行
          美食
        项目
          Open Source
          Side Projects
    ```

    Dark Mode Compatibility

    Mermaid diagrams automatically adapt to the current color scheme. The theme injects the Mermaid theme configuration based on whether light or dark mode is active:

    • Light mode: Mermaid renders with theme: default (dark text on white/transparent background)
    • Dark mode: Mermaid renders with theme: dark (light text on dark background)

    The theme switch happens automatically when the visitor toggles dark mode — diagrams re-render with the appropriate theme. No manual configuration is needed.

    For more details on dark mode, see the Dark Mode guide.

    Customizing Mermaid Theme

    If you need more control over diagram appearance, you can use Mermaid's %%{init}%% directive at the top of your diagram:

    ```mermaid
    %%{init: {'theme': 'forest', 'themeVariables': { 'fontSize': '16px' }}}%%
    flowchart LR
        A --> B --> C
    ```

    Mermaid supports these built-in themes: default, forest, dark, neutral, base. However, manually setting a theme will override the automatic dark mode adaptation — use this only if you want a fixed appearance regardless of the user's color scheme.

    Performance Considerations

    • Each Mermaid diagram adds a small rendering overhead (~10–50ms for typical diagrams)
    • Complex diagrams with many nodes may take longer
    • The library itself is ~1MB (gzipped ~300KB) but loads only on pages with mermaid: true
    • On slow connections, users will see loading placeholders until the library and render complete

    Enabling Mermaid Globally

    If you use Mermaid in most of your posts and do not want to set mermaid: true in every frontmatter, you could enable it globally by modifying your theme's layout. However, this is not recommended — it adds JavaScript overhead to every page, even those without diagrams. The per-post approach is the intended design.

    Troubleshooting

    Diagram renders as raw text

    • Make sure the code block uses ```mermaid (not a different identifier)
    • Verify mermaid: true is in the post frontmatter
    • Check for syntax errors in the diagram definition

    Diagram has wrong colors in dark mode

    • Refresh the page after toggling dark mode (diagrams re-render on load)
    • Avoid using %%{init}%% to set a fixed theme if you want auto-adaptation

    Diagram shows a loading spinner indefinitely

    • Check browser console for network errors (CDN might be blocked)
    • If you are in mainland China, consider configuring a domestic CDN mirror for Mermaid
    • Dark Mode — How Mermaid diagrams adapt to color scheme changes
    • Code Highlighting — Code block syntax highlighting (separate from Mermaid rendering)