AgentSkillsCN

mermaid-diagrams

使用 Mermaid 的文本语法,创建专业的软件架构图。适用于用户请求绘制软件架构图、可视化图表,或需要对软件架构进行文档化时使用,包括类图、序列图、流程图、ER 图、C4 架构图、状态机、Git 图,或甘特图。触发条件:“绘制图表”、“可视化”、“建模”、“梳理脉络”、“展示流程”、数据库设计、代码结构。

SKILL.md
--- frontmatter
name: mermaid-diagrams
description: "Creates professional software diagrams using Mermaid's text-based syntax. Use when users request diagrams, visualizations, or documentation of software architecture including class diagrams, sequence diagrams, flowcharts, ERDs, C4 architecture diagrams, state machines, git graphs, or gantt charts. Triggers: 'diagram', 'visualize', 'model', 'map out', 'show the flow', database design, code structure."
license: MIT
context: fork
agent: general-purpose

Mermaid Diagramming

Create professional software diagrams using Mermaid's text-based syntax.

<instructions>

Core Syntax Structure

All Mermaid diagrams follow this pattern:

mermaid
diagramType
  definition content

Key principles:

  • First line declares diagram type (e.g., classDiagram, sequenceDiagram, flowchart)
  • Use %% for comments
  • Whitespace aids readability; not required
  • Typos break diagrams silently—validate in Mermaid Live
</instructions> <diagram-types>

Diagram Type Selection Guide

Choose the right diagram type:

  1. Class Diagrams - Domain modeling, OOP design, entity relationships

    • Domain-driven design documentation
    • Object-oriented class structures
    • Entity relationships and dependencies
  2. Sequence Diagrams - Temporal interactions, message flows

    • API request/response flows
    • User authentication flows
    • System component interactions
    • Method call sequences
  3. Flowcharts - Processes, algorithms, decision trees

    • User journeys and workflows
    • Business processes
    • Algorithm logic
    • Deployment pipelines
  4. Entity Relationship Diagrams (ERD) - Database schemas

    • Table relationships
    • Data modeling
    • Schema design
  5. C4 Diagrams - Software architecture at multiple levels

    • System Context (systems and users)
    • Container (applications, databases, services)
    • Component (internal structure)
    • Code (class/interface level)
  6. State Diagrams - State machines, lifecycle states

  7. Git Graphs - Version control branching strategies

  8. Gantt Charts - Project timelines, scheduling

  9. Pie/Bar Charts - Data visualization

</diagram-types> <examples>

Quick Start Examples

Class Diagram (Domain Model)

mermaid
classDiagram
    Title -- Genre
    Title *-- Season
    Title *-- Review
    User --> Review : creates
    
    class Title {
        +string name
        +int releaseYear
        +play()
    }
    
    class Genre {
        +string name
        +getTopTitles()
    }

Sequence Diagram (API Flow)

mermaid
sequenceDiagram
    participant User
    participant API
    participant Database
    
    User->>API: POST /login
    API->>Database: Query credentials
    Database-->>API: Return user data
    alt Valid credentials
        API-->>User: 200 OK + JWT token
    else Invalid credentials
        API-->>User: 401 Unauthorized
    end

Flowchart (User Journey)

mermaid
flowchart TD
    Start([User visits site]) --> Auth{Authenticated?}
    Auth -->|No| Login[Show login page]
    Auth -->|Yes| Dashboard[Show dashboard]
    Login --> Creds[Enter credentials]
    Creds --> Validate{Valid?}
    Validate -->|Yes| Dashboard
    Validate -->|No| Error[Show error]
    Error --> Login

ERD (Database Schema)

mermaid
erDiagram
    USER ||--o{ ORDER : places
    ORDER ||--|{ LINE_ITEM : contains
    PRODUCT ||--o{ LINE_ITEM : includes
    
    USER {
        int id PK
        string email UK
        string name
        datetime created_at
    }
    
    ORDER {
        int id PK
        int user_id FK
        decimal total
        datetime created_at
    }
</examples> <references>

Detailed References

For in-depth guidance on specific diagram types, see:

</references> <best-practices>

Best Practices

  1. Draft core entities first - Add 3-5 main nodes, then connect. Add attributes and detail in a second pass.
  2. Label every node and edge - Unlabelled arrows force readers to guess the relationship.
  3. Add %% comments above complex sections - Explain why, not what. Future editors read comments before syntax.
  4. Split at 15 nodes - Diagrams with more than 15 nodes lose clarity. Break into focused views linked by a parent diagram.
  5. Store .mmd files next to the code they describe - Keep diagrams and source in the same PR so they stay in sync.
  6. Set a title on every diagram - Use the title keyword or a Markdown heading directly above the code block.
  7. Test in Mermaid Live before committing - Paste the diagram into mermaid.live to catch silent failures.
  8. Check colour contrast - Verify foreground/background pairs meet WCAG AA (4.5:1 ratio). Do not rely on colour alone to convey meaning.
</best-practices> <validation>

Validation Loop (Required)

Every diagram passes through this generate-validate-repair cycle before output.

Step 1: Generate

Write the diagram using strict Mermaid syntax. Apply these rules during generation:

RuleWrongCorrectWhy
Escape parentheses in labelsnode[Node (example)]node["Node (example)"]Bare parentheses crash the parser
Quote text with special charactersA[Price: $100]A["Price: $100"]$, %, &, <, > break parsing
Quote the reserved word endA --> endA --> End["end"]Unquoted end silently breaks diagrams
Use HTML entities when quotes failA["alert()"]A["alert&lpar;&rpar;"]Nested parens inside quotes still fail
Avoid {} in comments%% config: {dark}%% config dark themeCurly braces in comments break parsing
Use unique node IDsReusing A across subgraphsA1, A2 for distinct nodesDuplicate IDs cause silent overwrites

Step 2: Validate

Self-check the generated diagram against these failure patterns:

  1. Scan all node labels for unescaped special characters: ( ) { } $ % & < > #
  2. Check for bare end used as a node name or label (not as a block closer)
  3. Verify arrow syntax matches the diagram type (e.g., --> for flowchart, ->> for sequence)
  4. Confirm diagram type keyword is spelled correctly on line 1
  5. Check participant/actor names for spaces (wrap in quotes if present)

If any issue is found, fix it before output. Do not ask the user to fix syntax.

Step 3: Render verification

After outputting the diagram, recommend the user verify rendering:

  • Quick check: paste into Mermaid Live
  • CLI validation: npx @mermaid-js/mermaid-cli -i diagram.mmd -o test.png
  • MCP tools: if a Mermaid MCP server is available, use it for in-session validation

Step 4: Repair (if rendering fails)

If the user reports a rendering failure:

  1. Read the error message (if available) and identify the failing line
  2. Check the syntax rules table above for the matching pattern
  3. Fix and re-output the corrected diagram
  4. Never output the same broken syntax twice
</validation>

Configuration and Theming

Configure diagrams using frontmatter:

mermaid
---
config:
  theme: base
  themeVariables:
    primaryColor: "#ff6b6b"
---
flowchart LR
    A --> B

Available themes: default (recommended), forest, dark, neutral, base (for full colour control)

Layout options:

  • layout: dagre (default) - Classic balanced layout
  • layout: elk - Advanced layout for complex diagrams (requires integration)

Look options:

  • look: classic - Traditional Mermaid style
  • look: handDrawn - Sketch-like appearance

Exporting and Rendering

Native support (with caveats):

  • GitHub README/Issues - Renders in Markdown. Wiki rendering is broken. C4 diagrams often fail.
  • GitLab - Renders reliably. May need cache refresh after adding new diagrams.
  • VS Code - With Markdown Mermaid extension. Known bug with "No diagram type detected" on first open.
  • Obsidian - Desktop works. iOS rendering fails entirely. Pie charts render as empty boxes.
  • Notion, Confluence - Built-in support. Feature coverage varies by Mermaid version.
  • Azure DevOps - Requires ::: mermaid syntax instead of ```mermaid backticks.

Export options:

  • Mermaid Live Editor - Online editor with PNG/SVG export
  • Mermaid CLI - npm install -g @mermaid-js/mermaid-cli then mmdc -i input.mmd -o output.png
  • Docker - docker run --rm -v $(pwd):/data minlag/mermaid-cli -i /data/input.mmd -o /data/output.png

Common Pitfalls

Syntax failures (most frequent):

  • Unescaped special characters - Parentheses, brackets, $, % in node labels crash the parser. Always quote labels containing these characters.
  • Reserved word end - Using end as a node name breaks diagrams silently. Wrap in quotes or rename.
  • Misspelled diagram types - classDiagram not classdiagram. Case matters for the type keyword.
  • Wrong arrow syntax - Each diagram type uses different arrows. Flowcharts use -->, sequence uses ->>, class uses ..>.

Platform-specific failures:

  • GitHub Wiki - Mermaid rendering is broken despite documentation claiming support. Use README or Pages instead.
  • Azure DevOps - Requires ::: mermaid syntax, not standard ```mermaid backticks.
  • Obsidian iOS - Mermaid fails to render entirely on iOS. Desktop works.
  • C4 diagrams on GitHub - C4 is experimental in Mermaid. Renders in mermaid.live but often fails on GitHub.
  • PDF export - Most tools render Mermaid as plain text. Export as PNG/SVG from mermaid.live first.

Structural issues:

  • Overcomplexity - Split diagrams with more than 15 nodes into multiple focused views.
  • Nested subgraphs - Deep nesting fails on some platforms. Keep to 2 levels maximum.
  • Missing relationships - Document all important connections between entities.

When to Create Diagrams

Always diagram when:

  • Starting new projects or features
  • Documenting complex systems
  • Explaining architecture decisions
  • Designing database schemas
  • Planning refactoring efforts
  • Onboarding new team members

Use diagrams to:

  • Align stakeholders on technical decisions
  • Document domain models collaboratively
  • Visualize data flows and system interactions
  • Plan before coding
  • Create living documentation that evolves with code