Mermaid学习笔记

📚 Mermaid官方文档 - 最新、最全面的参考资料


1. Mermaid简介

Mermaid 是一款开源可视化工具,允许用户用简洁的文本语法绘制多种专业图表:

  • 纯文本驱动,类 Markdown 语法
  • 多图表类型,支持流程图、时序图、甘特图、类图等
  • 易维护,源码即文档,便于协作
  • 实时渲染,支持多平台集成

1.1 支持的图表类型

类型 关键字 应用场景
流程图 flowchart/graph 业务流程、算法逻辑
时序图 sequenceDiagram 对象交互
状态图 stateDiagram 状态转换
甘特图 gantt 项目进度
类图 classDiagram 面向对象设计
实体关系图 erDiagram 数据库设计
用户旅程图 journey 用户体验
饼图 pie 数据占比
需求图 requirementDiagram 需求追踪
git提交图 gitGraph 版本管理
C4图 C4Context 架构建模
思维导图 mindmap 头脑风暴

💡 常用类型已加粗,更多详见官方文档

1.2 Hugo中启用Mermaid

  1. 新建 layouts/_default/_markup/render-codeblock-mermaid.html
    1
    2
    3
    4
    
    <pre class="mermaid">
      {{ .Inner | htmlEscape | safeHTML }}
    </pre>
    {{ .Page.Store.Set "hasMermaid" true }}
  2. layouts/_default/baseof.html</body> 前添加:
    1
    2
    3
    4
    5
    6
    
    {{ if .Store.Get "hasMermaid" }}
      <script type="module">
        import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.esm.min.mjs';
        mermaid.initialize({ startOnLoad: true });
      </script>
    {{ end }}

2. 基本语法与嵌入方式

Markdown中嵌入Mermaid代码块:

graph TD
  Start --> Stop
不同图表类型用不同关键字(如 graphsequenceDiagramgantt 等)。


3. 常见图表类型与示例

3.1 流程图

graph TD
  A[开始] --> B{判断}
  B -- 是 --> C[处理1]
  B -- 否 --> D[处理2]
  C --> E[结束]
  D --> E
  • 节点形状:矩形a[文本]、圆角a(文本)、菱形a{条件}、圆形a((文本))
  • 布局方向:TB/TD(默认)、BT、LR、RL
  • 连线样式:--- 普通线,--> 箭头,==> 粗箭头,-.-> 虚线
  • 子图示例:
graph LR
  subgraph s
    direction BT
    a --> b
  end
  s ==> c

3.2 时序图

sequenceDiagram
  Alice->>John: Hello John, how are you?
  John-->>Alice: Great!
  Alice-)John: See you later!

3.3 类图

classDiagram
  Animal <|-- Duck
  Animal <|-- Fish
  Animal <|-- Zebra
  Animal : +int age
  Animal : +String gender
  Animal: +isMammal()
  Animal: +mate()
  class Duck{
    +String beakColor
    +swim()
    +quack()
  }
class Fish{
  -int sizeInFeet
  -canEat()
}
class Zebra{
  +bool is_wild
  +run()
}

3.4 状态图

stateDiagram-v2
  [*] --> Still
  Still --> [*]
  Still --> Moving
  Moving --> Still
  Moving --> Crash
  Crash --> [*]

3.5 关系图

erDiagram
  CUSTOMER ||--o{ ORDER : places
  ORDER ||--|{ LINE-ITEM : contains
  CUSTOMER }|..|{ DELIVERY-ADDRESS : uses

3.6 旅程图

journey
  title My working day
  section Go to work
  Make tea: 5: Me
  Go upstairs: 3: Me
  Do work: 1: Me, Cat
  section Go home
  Go downstairs: 5: Me
  Sit down: 5: Me

3.7 甘特图

gantt
  title 项目进度示例
  dateFormat YYYY-MM-DD
  section 项目A
  任务1 :done, a1, 2023-03-01, 3d
  任务2 :active, a2, after a1, 2023-03-08
  里程碑 :milestone, a3, 2023-03-07, 1d
  section 项目B
  任务1 :b1, 2023-03-07, 4000m
  任务2 :crit, b2, after a2, 15h
  • 主要参数:dateFormataxisFormatexcludestickIntervaltodayMarker
  • 任务状态:done已完成、active进行中、crit关键任务、milestone里程碑

3.8 饼图

pie title Pets adopted by volunteers
  "Dogs" : 386
  "Cats" : 85
  "Rats" : 15

3.9 需求图

requirementDiagram
  requirement test_req {
    id: 1
    text: the test text.
    risk: high
    verifymethod: test
  }
  element test_entity {
    type: simulation
  }
  test_entity - satisfies -> test_req

3.10 git提交图

gitGraph
   commit
   commit
   branch develop
   checkout develop
   commit
   commit
   checkout main
   merge develop
   commit
   commit

3.11 C4图

C4Context
  title System Context diagram for Internet Banking System
    Enterprise_Boundary(b0, "BankBoundary0") {
      Person(customerA, "Banking Customer A", "A customer of the bank, with personal bank accounts.")
      Person(customerB, "Banking Customer B")
      Person_Ext(customerC, "Banking Customer C", "desc")
      Person(customerD, "Banking Customer D", "A customer of the bank, 
with personal bank accounts.") System(SystemAA, "Internet Banking System", "Allows customers to view information about their bank accounts, and make payments.") Enterprise_Boundary(b1, "BankBoundary") { SystemDb_Ext(SystemE, "Mainframe Banking System", "Stores all of the core banking information about customers, accounts, transactions, etc.") System_Boundary(b2, "BankBoundary2") { System(SystemA, "Banking System A") System(SystemB, "Banking System B", "A system of the bank, with personal bank accounts. next line.") } System_Ext(SystemC, "E-mail system", "The internal Microsoft Exchange e-mail system.") SystemDb(SystemD, "Banking System D Database", "A system of the bank, with personal bank accounts.") Boundary(b3, "BankBoundary3", "boundary") { SystemQueue(SystemF, "Banking System F Queue", "A system of the bank.") SystemQueue_Ext(SystemG, "Banking System G Queue", "A system of the bank, with personal bank accounts.") } } } BiRel(customerA, SystemAA, "Uses") BiRel(SystemAA, SystemE, "Uses") Rel(SystemAA, SystemC, "Sends e-mails", "SMTP") Rel(SystemC, customerA, "Sends e-mails to") UpdateElementStyle(customerA, $fontColor="red", $bgColor="grey", $borderColor="red") UpdateRelStyle(customerA, SystemAA, $textColor="blue", $lineColor="blue", $offsetX="5") UpdateRelStyle(SystemAA, SystemE, $textColor="blue", $lineColor="blue", $offsetY="-10") UpdateRelStyle(SystemAA, SystemC, $textColor="blue", $lineColor="blue", $offsetY="-40", $offsetX="-50") UpdateRelStyle(SystemC, customerA, $textColor="red", $lineColor="red", $offsetX="-50", $offsetY="20") UpdateLayoutConfig($c4ShapeInRow="3", $c4BoundaryInRow="1")

3.12 思维导图

mindmap
  root((mindmap))
    Origins
      Long history
      ::icon(fa fa-book)
      Popularisation
        British popular psychology author Tony Buzan
    Research
      On effectiveness
and features On Automatic creation Uses Creative techniques Strategic planning Argument mapping Tools Pen and paper Mermaid

4. 进阶用法与技巧

4.1 布局与方向控制

  • 子图(subgraph)嵌套与组织,分解复杂流程
  • 四种方向:TB(上到下)、BT(下到上)、LR(左到右)、RL(右到左)
  • 子图可独立设置方向:
flowchart TB
  subgraph 订单系统[direction:LR]
    支付 --> 物流
  end
  subgraph 风控系统[direction:RL]
    反欺诈 --> 信用评估
  end
  物流 --> 信用评估
  • %%{init}%% 指令优化布局:
    %%{init: {"flowchart": {"curve": "stepAfter"}}}%%
      graph LR
      A --> B --> C --> D
    

4.2 样式定制

  • classDef 定义样式类,自定义节点/连线外观
  • 常用属性:fillstrokestroke-widthcolorfont-sizefont-familyfont-weighttext-align
  • 示例:
graph LR
  A[开始]:::blueBox --> B{判断}:::diamond
  classDef blueBox fill:#B0E0E6,stroke:#4682B4
  classDef diamond stroke:#FF6B6B,stroke-width:2px

4.3 高级特性

  • 节点超链接:
    graph LR;
      A-->B;
      B-->C;
      click A "http://www.github.com" _blank
      click B "http://www.github.com" "Open this in a new tab" _blank
    
  • 动态图表生成、主题切换、交互功能

4.4 最佳实践

  • 模块化设计、复杂图表分层、样式复用
  • 节点过多时建议拆分子模块,突出关键信息
  • 保持节点间距适中,减少连线交叉

5. 参考与致谢