mermaid-master

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Mermaid Master

Mermaid 图表大师

Expert guidance for creating valid, beautiful, and accessible Mermaid diagrams.
专业指导:创建合规、美观且易用的Mermaid图表。

Core Principles

核心原则

  1. Validity First: Always produce syntactically correct Mermaid code
  2. Visual Clarity: Design for immediate comprehension
  3. Accessibility: Use descriptive labels and logical flow
  4. Appropriate Complexity: Match diagram complexity to information needs
  1. 合规优先:始终生成语法正确的Mermaid代码
  2. 视觉清晰:设计需便于快速理解
  3. 易用性:使用描述性标签与逻辑化流程
  4. 复杂度适配:图表复杂度需匹配信息展示需求

Diagram Type Selection

图表类型选择

Choose the diagram type that best matches the information structure:
  • Flowchart: Processes, decisions, algorithms, workflows
  • Sequence: Time-based interactions, API calls, messaging flows
  • Class: Object-oriented designs, data structures, type hierarchies
  • State: State machines, lifecycle diagrams, status workflows
  • ER (Entity Relationship): Database schemas, data models
  • Gantt: Project timelines, schedules, resource planning
  • Pie: Proportional data, market share, budget allocation
  • Git Graph: Branch strategies, release flows, version history
  • User Journey: User experience flows, customer journeys
  • Quadrant Chart: Priority matrices, positioning maps
  • Timeline: Historical events, roadmaps
根据信息结构选择最适合的图表类型:
  • 流程图:流程、决策、算法、工作流
  • 时序图:基于时间的交互、API调用、消息流
  • 类图:面向对象设计、数据结构、类型层级
  • 状态图:状态机、生命周期图、状态工作流
  • 实体关系图(ER):数据库 schema、数据模型
  • 甘特图:项目时间线、进度计划、资源规划
  • 饼图:比例数据、市场份额、预算分配
  • Git 分支图:分支策略、发布流程、版本历史
  • 用户旅程图:用户体验流程、客户旅程
  • 四象限图:优先级矩阵、定位图
  • 时间线:历史事件、路线图

Universal Best Practices

通用最佳实践

Syntax Essentials

语法要点

Critical syntax rules:
  • Always use
    graph
    or
    flowchart
    (never
    flow
    )
  • Direction syntax:
    TD
    (top-down),
    LR
    (left-right),
    BT
    ,
    RL
  • Node IDs must be unique within a diagram
  • Avoid special characters in IDs (use
    nodeId["Label"]
    for special chars)
  • Use proper quote escaping:
    "text with \"quotes\""
  • Comments use
    %%
    prefix
Node shapes:
mermaid
A[Rectangle]
B(Rounded rectangle)
C([Stadium/Pill shape])
D[[Subroutine]]
E[(Database)]
F((Circle))
G>Flag/Asymmetric]
H{Decision diamond}
I{{Hexagon}}
J[/Parallelogram/]
K[\Reverse parallelogram\]
L[/Trapezoid\]
M[\Reverse trapezoid/]
Connection types:
  • -->
    solid arrow
  • ---
    solid line (no arrow)
  • -.->
    dotted arrow
  • -.-
    dotted line
  • ==>
    thick arrow
  • ===
    thick line
  • --text-->
    labeled arrow
  • ---|text|---
    labeled line
关键语法规则:
  • 始终使用
    graph
    flowchart
    (切勿使用
    flow
  • 方向语法:
    TD
    (从上到下)、
    LR
    (从左到右)、
    BT
    RL
  • 节点ID在图表内必须唯一
  • ID中避免使用特殊字符(如需特殊字符,使用
    nodeId["标签"]
    格式)
  • 正确转义引号:
    "包含\"引号\"的文本"
  • 注释使用
    %%
    前缀
节点形状:
mermaid
A[矩形]
B(圆角矩形)
C([体育场/胶囊形状])
D[[子程序]]
E[(数据库)]
F((圆形))
G>旗帜/不对称形状]
H{决策菱形}
I{{六边形}}
J[/平行四边形/]
K[\反向平行四边形\]
L[/梯形\]
M[\反向梯形/]
连接线类型:
  • -->
    实线箭头
  • ---
    实线(无箭头)
  • -.->
    虚线箭头
  • -.-
    虚线
  • ==>
    粗箭头
  • ===
    粗实线
  • --text-->
    带标签的箭头
  • ---|text|---
    带标签的实线

Visual Design Guidelines

视觉设计指南

Layout optimization:
  • Keep diagrams focused (5-15 nodes optimal, max 25)
  • Use consistent node shapes for similar concepts
  • Place most important elements at the top or left
  • Group related nodes visually using subgraphs
  • Avoid crossing lines when possible
Label clarity:
  • Use concise, descriptive labels (2-5 words ideal)
  • Keep text under 40 characters per node
  • Use title case for major nodes, sentence case for descriptions
  • Include action verbs in process steps ("Process Payment", not "Payment")
Hierarchy and grouping:
mermaid
flowchart TD
    subgraph Frontend
        A[Web App]
        B[Mobile App]
    end
    subgraph Backend
        C[API Server]
        D[Database]
    end
    A --> C
    B --> C
    C --> D
布局优化:
  • 保持图表聚焦(最佳节点数为5-15个,最多不超过25个)
  • 同类概念使用统一的节点形状
  • 将最重要的元素放置在顶部或左侧
  • 使用子图对相关节点进行视觉分组
  • 尽可能避免线条交叉
标签清晰度:
  • 使用简洁、具有描述性的标签(理想长度为2-5个词)
  • 每个节点的文本长度不超过40个字符
  • 主要节点使用标题大小写,描述性内容使用句子大小写
  • 流程步骤中使用动作动词(如“处理付款”,而非“付款”)
层级与分组:
mermaid
flowchart TD
    subgraph 前端
        A[Web应用]
        B[移动应用]
    end
    subgraph 后端
        C[API服务器]
        D[数据库]
    end
    A --> C
    B --> C
    C --> D

Styling and Theming

样式与主题

Class-based styling:
mermaid
flowchart TD
    A[Normal Node]
    B[Important Node]
    C[Critical Node]
    
    classDef important fill:#ff9,stroke:#333,stroke-width:2px
    classDef critical fill:#f99,stroke:#333,stroke-width:4px
    
    class B important
    class C critical
Individual node styling:
mermaid
flowchart TD
    A[Start]
    B[Process]
    C[End]
    
    style A fill:#9f9,stroke:#333,stroke-width:2px
    style C fill:#f99,stroke:#333,stroke-width:2px
Recommended color schemes:
  • Neutral:
    fill:#f5f5f5,stroke:#333
  • Success/Start:
    fill:#d4edda,stroke:#28a745
  • Warning:
    fill:#fff3cd,stroke:#ffc107
  • Error/End:
    fill:#f8d7da,stroke:#dc3545
  • Info:
    fill:#d1ecf1,stroke:#17a2b8
基于类的样式设计:
mermaid
flowchart TD
    A[普通节点]
    B[重要节点]
    C[关键节点]
    
    classDef important fill:#ff9,stroke:#333,stroke-width:2px
    classDef critical fill:#f99,stroke:#333,stroke-width:4px
    
    class B important
    class C critical
单个节点样式设计:
mermaid
flowchart TD
    A[开始]
    B[处理]
    C[结束]
    
    style A fill:#9f9,stroke:#333,stroke-width:2px
    style C fill:#f99,stroke:#333,stroke-width:2px
推荐配色方案:
  • 中性色
    fill:#f5f5f5,stroke:#333
  • 成功/起始
    fill:#d4edda,stroke:#28a745
  • 警告
    fill:#fff3cd,stroke:#ffc107
  • 错误/结束
    fill:#f8d7da,stroke:#dc3545
  • 信息
    fill:#d1ecf1,stroke:#17a2b8

Diagram Type Details

各类型图表详情

Flowcharts

流程图

Structure:
mermaid
flowchart TD
    Start([Start]) --> Input[/Input Data/]
    Input --> Process{Valid?}
    Process -->|Yes| Action[Process Data]
    Process -->|No| Error[Show Error]
    Action --> Output[/Output Result/]
    Error --> Input
    Output --> End([End])
Best practices:
  • Start with a clear entry point (oval/stadium shape)
  • Use diamonds for all decisions
  • Label decision branches clearly (Yes/No, True/False)
  • End with explicit termination point
  • Use parallelograms for input/output
  • Keep decision points binary when possible
结构示例:
mermaid
flowchart TD
    Start([开始]) --> Input[/输入数据/]
    Input --> Process{有效?}
    Process -->|是| Action[处理数据]
    Process -->|否| Error[显示错误]
    Action --> Output[/输出结果/]
    Error --> Input
    Output --> End([结束])
最佳实践:
  • 以清晰的入口点开始(椭圆形/胶囊形状)
  • 所有决策使用菱形节点
  • 清晰标记决策分支(是/否、真/假)
  • 以明确的终止点结束
  • 使用平行四边形表示输入/输出
  • 尽可能让决策点保持二元选项

Sequence Diagrams

时序图

Structure:
mermaid
sequenceDiagram
    participant User
    participant Frontend
    participant API
    participant Database
    
    User->>Frontend: Click Submit
    activate Frontend
    Frontend->>API: POST /api/data
    activate API
    API->>Database: INSERT query
    activate Database
    Database-->>API: Success
    deactivate Database
    API-->>Frontend: 200 OK
    deactivate API
    Frontend-->>User: Show confirmation
    deactivate Frontend
Best practices:
  • Use activate/deactivate to show execution context
  • Order participants left-to-right by interaction flow
  • Use
    -->>
    for returns/responses
  • Add
    Note
    for important context
  • Use
    loop
    ,
    alt
    ,
    opt
    ,
    par
    for control flow
  • Keep interactions focused (max 8-12 messages)
结构示例:
mermaid
sequenceDiagram
    participant User
    participant Frontend
    participant API
    participant Database
    
    User->>Frontend: 点击提交
    activate Frontend
    Frontend->>API: POST /api/data
    activate API
    API->>Database: INSERT 查询
    activate Database
    Database-->>API: 成功
    deactivate Database
    API-->>Frontend: 200 OK
    deactivate API
    Frontend-->>User: 显示确认信息
    deactivate Frontend
最佳实践:
  • 使用 activate/deactivate 标记执行上下文
  • 参与者按交互流程从左到右排序
  • 使用
    -->>
    表示返回/响应
  • 添加
    Note
    标注重要上下文
  • 使用
    loop
    alt
    opt
    par
    表示控制流
  • 保持交互聚焦(最多8-12条消息)

Class Diagrams

类图

Structure:
mermaid
classDiagram
    class Animal {
        +String name
        +int age
        +makeSound() void
    }
    class Dog {
        +String breed
        +bark() void
    }
    class Cat {
        +bool indoor
        +meow() void
    }
    
    Animal <|-- Dog
    Animal <|-- Cat
Relationships:
  • <|--
    inheritance
  • *--
    composition
  • o--
    aggregation
  • -->
    association
  • --
    link
  • ..>
    dependency
  • ..|>
    realization
结构示例:
mermaid
classDiagram
    class Animal {
        +String name
        +int age
        +makeSound() void
    }
    class Dog {
        +String breed
        +bark() void
    }
    class Cat {
        +bool indoor
        +meow() void
    }
    
    Animal <|-- Dog
    Animal <|-- Cat
关系符号:
  • <|--
    继承
  • *--
    组合
  • o--
    聚合
  • -->
    关联
  • --
    链接
  • ..>
    依赖
  • ..|>
    实现

State Diagrams

状态图

Structure:
mermaid
stateDiagram-v2
    [*] --> Draft
    Draft --> Review: Submit
    Review --> Approved: Approve
    Review --> Rejected: Reject
    Rejected --> Draft: Revise
    Approved --> Published: Publish
    Published --> Archived: Archive
    Archived --> [*]
Best practices:
  • Start with
    [*]
    initial state
  • End with
    [*]
    final state (if applicable)
  • Label all transitions clearly
  • Use composite states for complex substates
  • Include error/cancel paths
结构示例:
mermaid
stateDiagram-v2
    [*] --> 草稿
    草稿 --> 审核: 提交
    审核 --> 通过: 批准
    审核 --> 驳回: 拒绝
    驳回 --> 草稿: 修改
    通过 --> 发布: 发布
    发布 --> 归档: 归档
    归档 --> [*]
最佳实践:
  • [*]
    表示初始状态
  • 适用时以
    [*]
    表示最终状态
  • 清晰标记所有状态转换
  • 复杂子状态使用复合状态
  • 包含错误/取消路径

Entity Relationship Diagrams

实体关系图

Structure:
mermaid
erDiagram
    Customer ||--o{ Order : places
    Customer {
        string name
        string email
        int customer_id PK
    }
    Order ||--|{ OrderLine : contains
    Order {
        int order_id PK
        date order_date
        int customer_id FK
    }
    Product ||--o{ OrderLine : includes
    OrderLine {
        int order_id FK
        int product_id FK
        int quantity
    }
    Product {
        int product_id PK
        string name
        decimal price
    }
Cardinality symbols:
  • ||--||
    one-to-one
  • ||--o{
    one-to-many
  • }o--o{
    many-to-many
  • ||--||
    exactly one
  • |o--o|
    zero or one
结构示例:
mermaid
erDiagram
    Customer ||--o{ Order : 下单
    Customer {
        string name
        string email
        int customer_id PK
    }
    Order ||--|{ OrderLine : 包含
    Order {
        int order_id PK
        date order_date
        int customer_id FK
    }
    Product ||--o{ OrderLine : 包含
    OrderLine {
        int order_id FK
        int product_id FK
        int quantity
    }
    Product {
        int product_id PK
        string name
        decimal price
    }
基数符号:
  • ||--||
    一对一
  • ||--o{
    一对多
  • }o--o{
    多对多
  • ||--||
    恰好一个
  • |o--o|
    零或一个

Gantt Charts

甘特图

Structure:
mermaid
gantt
    title Project Timeline
    dateFormat YYYY-MM-DD
    section Planning
        Requirements     :done, req, 2024-01-01, 2024-01-15
        Design          :active, design, 2024-01-16, 2024-02-01
    section Development
        Frontend        :dev1, 2024-02-02, 30d
        Backend         :dev2, 2024-02-02, 30d
        Integration     :after dev1 dev2, 10d
    section Testing
        QA Testing      :test, after dev1 dev2, 15d
        UAT             :after test, 10d
Best practices:
  • Use meaningful section names
  • Include status indicators (done, active, crit)
  • Show dependencies with
    after
    keyword
  • Use consistent date format
  • Keep task names concise
结构示例:
mermaid
gantt
    title 项目时间线
    dateFormat YYYY-MM-DD
    section 规划
        需求分析     :done, req, 2024-01-01, 2024-01-15
        设计          :active, design, 2024-01-16, 2024-02-01
    section 开发
        前端开发        :dev1, 2024-02-02, 30d
        后端开发         :dev2, 2024-02-02, 30d
        集成测试     :after dev1 dev2, 10d
    section 测试
        QA测试      :test, after dev1 dev2, 15d
        用户验收测试             :after test, 10d
最佳实践:
  • 使用有意义的章节名称
  • 包含状态标记(done、active、crit)
  • 使用
    after
    关键字展示依赖关系
  • 使用统一的日期格式
  • 保持任务名称简洁

Common Pitfalls to Avoid

需规避的常见问题

Syntax errors:
  • flow TD
    → ✅
    flowchart TD
  • ❌ Unescaped quotes in labels → ✅ Use
    #quot;
    or single quotes
  • ❌ Special chars in node IDs → ✅ Use alphanumeric IDs only
  • ❌ Missing semicolons in complex flows → ✅ Use them for clarity
Design issues:
  • ❌ Too many nodes (>25) → ✅ Split into multiple diagrams
  • ❌ Unclear labels → ✅ Use descriptive, action-oriented text
  • ❌ Inconsistent node shapes → ✅ Define shape conventions
  • ❌ No visual hierarchy → ✅ Use subgraphs and styling
Accessibility issues:
  • ❌ Color-only differentiation → ✅ Also use shapes/labels
  • ❌ Tiny text in complex diagrams → ✅ Simplify or split
  • ❌ Unclear flow direction → ✅ Add explicit arrows
语法错误:
  • flow TD
    → ✅
    flowchart TD
  • ❌ 标签中未转义引号 → ✅ 使用
    #quot;
    或单引号
  • ❌ 节点ID包含特殊字符 → ✅ 仅使用字母数字ID
  • ❌ 复杂流程中缺少分号 → ✅ 添加分号以提升可读性
设计问题:
  • ❌ 节点过多(>25个)→ ✅ 拆分为多个图表
  • ❌ 标签不清晰 → ✅ 使用描述性、面向动作的文本
  • ❌ 节点形状不一致 → ✅ 定义形状规范
  • ❌ 无视觉层级 → ✅ 使用子图与样式设计
易用性问题:
  • ❌ 仅通过颜色区分元素 → ✅ 同时使用形状/标签
  • ❌ 复杂图表中文字过小 → ✅ 简化或拆分图表
  • ❌ 流程方向不清晰 → ✅ 添加明确的箭头

Advanced Techniques

高级技巧

Interactive Elements

交互元素

Add links and tooltips:
mermaid
flowchart TD
    A[Homepage]
    B[Product Page]
    C[Checkout]
    
    click A "https://example.com" "Go to homepage"
    click B "https://example.com/products" "View products"
添加链接与提示框:
mermaid
flowchart TD
    A[首页]
    B[产品页]
    C[结算页]
    
    click A "https://example.com" "前往首页"
    click B "https://example.com/products" "查看产品"

Complex Styling

复杂样式设计

Combine multiple styling approaches:
mermaid
flowchart LR
    A[Start] --> B{Decision}
    B -->|Path 1| C[Option A]
    B -->|Path 2| D[Option B]
    C --> E[End]
    D --> E
    
    classDef decision fill:#ffe6cc,stroke:#d79b00,stroke-width:2px
    classDef terminal fill:#d5e8d4,stroke:#82b366,stroke-width:2px
    
    class B decision
    class A,E terminal
组合多种样式方法:
mermaid
flowchart LR
    A[开始] --> B{决策}
    B -->|路径1| C[选项A]
    B -->|路径2| D[选项B]
    C --> E[结束]
    D --> E
    
    classDef decision fill:#ffe6cc,stroke:#d79b00,stroke-width:2px
    classDef terminal fill:#d5e8d4,stroke:#82b366,stroke-width:2px
    
    class B decision
    class A,E terminal

Subgraph Styling

子图样式设计

mermaid
flowchart TB
    subgraph cloud[Cloud Infrastructure]
        direction LR
        A[Load Balancer]
        B[App Server 1]
        C[App Server 2]
    end
    
    D[User] --> A
    A --> B
    A --> C
    
    style cloud fill:#e1f5ff,stroke:#01579b
mermaid
flowchart TB
    subgraph cloud[云基础设施]
        direction LR
        A[负载均衡器]
        B[应用服务器1]
        C[应用服务器2]
    end
    
    D[用户] --> A
    A --> B
    A --> C
    
    style cloud fill:#e1f5ff,stroke:#01579b

Workflow

工作流程

When creating a diagram:
  1. Understand the requirement: What information needs to be visualized?
  2. Select diagram type: Choose the most appropriate type
  3. Plan structure: Sketch key elements and relationships
  4. Build incrementally: Start simple, add detail progressively
  5. Apply styling: Use consistent visual design
  6. Validate syntax: Ensure code is valid Mermaid
  7. Review clarity: Can the diagram be understood quickly?
创建图表时遵循以下步骤:
  1. 理解需求:需要可视化展示哪些信息?
  2. 选择图表类型:挑选最适合的类型
  3. 规划结构:勾勒关键元素与关系
  4. 逐步构建:从简单开始,逐步添加细节
  5. 应用样式:使用统一的视觉设计
  6. 验证语法:确保代码为有效的Mermaid语法
  7. 检查清晰度:图表能否被快速理解?

Additional Resources

额外资源

For complex diagrams with many nodes or advanced patterns, see:
  • references/diagram-patterns.md: Real-world examples and templates
  • references/syntax-reference.md: Complete syntax guide for all diagram types
如需创建包含大量节点的复杂图表或使用高级模式,请参考:
  • references/diagram-patterns.md:真实场景示例与模板
  • references/syntax-reference.md:全类型图表完整语法指南

Quality Checklist

质量检查清单

Before finalizing a diagram:
  • Syntax is valid (no errors)
  • Labels are clear and concise
  • Flow direction is logical
  • Visual hierarchy guides the eye
  • Styling enhances (not distracts from) content
  • Complexity is appropriate (not overwhelming)
  • Diagram answers the original question/need
最终确定图表前,请检查:
  • 语法有效(无错误)
  • 标签清晰简洁
  • 流程方向逻辑合理
  • 视觉层级引导视线
  • 样式设计为内容增色(而非干扰)
  • 复杂度适中(不过于繁杂)
  • 图表满足原始需求/问题