文档 (opens new window)

mermaid是一款开源的画流程图、甘特图、时序图工具,她提供了一种类似markdown的语法来创建各种图。

流程图(graph)

概述

graph 方向描述
    图表中的其他语句...

关键字graph表示一个流程图的开始,同时需要指定该图的方向。

其中“方向描述”为:

用词 含义
TB 从上到下
TD 和TB一样
BT 从下到上
RL 从右到左
LR 从左到右

T = TOP,B = BOTTOM,L = LEFT,R = RIGHT,D = DOWN

最常用的布局方向是TB、LR。

graph TB;
  A-->B
  B-->C
  C-->A
graph LR;
  A-->B
  B-->C
  C-->A

流程图常用符号及含义

节点形状

表述 说明 含义
id[文字] 矩形节点 表示过程,也就是整个流程中的一个环节
id(文字) 圆角矩形节点 表示开始和结束
id((文字)) 圆形节点 表示连接。为避免流程过长或有交叉,可将流程切开。成对
id{文字} 菱形节点 表示判断、决策
id>文字] 右向旗帜状节点

单向箭头线段:表示流程进行方向

id即为节点的唯一标识,A~F 是当前节点名字,类似于变量名,画图时便于引用

括号内是节点中要显示的文字,默认节点的名字和显示的文字都为A

graph TB
  A
  B(圆角矩形节点)
  C[矩形节点]
  D((圆形节点))
  E{菱形节点}
  F>右向旗帜状节点] 

补充图形

示例

连线

graph TB
  A1-->B1
  A2---B2
  A3--text---B3
  A4--text-->B4
  A5-.-B5
  A6-.->B6
  A7-.text.-B7
  A8-.text.->B8
  A9===B9
  A10==>B10
  A11==text===B11
  A12==text==>B12

补充连线

子图表

使用以下语法添加子图表

subgraph 描述
    内容
    end

补充功能

点击跳转

click A "https://www.baidu.com" _blank

注释

%%开头

样式

# 行内样式
flowchart LR
    id1(Start)-->id2(Stop)
    style id1 fill:#f9f,stroke:#333,stroke-width:4px
    style id2 fill:#bbf,stroke:#f66,stroke-width:2px,color:#fff,stroke-dasharray: 5 5
flowchart LR
    A:::someclass --> B
    classDef someclass fill:#f9f,stroke:#333,stroke-width:4px;

示例

基本流程图

graph LR
    A[Square Rect] -- Link text --> B((Circle))
    A --> C(Round Rect)
    B --> D{Rhombus}
    C --> D

带有一些样式的较大流程图

graph TB
    sq[Square shape] --> ci((Circle shape))

    subgraph A
        od>Odd shape]-- Two line<br/>edge comment --> ro
        di{Diamond with <br/> line break} -.-> ro(Rounded<br>square<br>shape)
        di==>ro2(Rounded square shape)
    end

    %% Notice that no text in shape are added here instead that is appended further down
    e --> od3>Really long text with linebreak<br>in an Odd shape]

    %% Comments after double percent signs
    e((Inner / circle<br>and some odd <br>special characters)) --> f(,.?!+-*ز)

    cyr[Cyrillic]-->cyr2((Circle shape Начало));

     classDef green fill:#9f6,stroke:#333,stroke-width:2px;
     classDef orange fill:#f96,stroke:#333,stroke-width:4px;
     class sq,e green
     class di orange

序列图(sequence diagram)

概述

sequenceDiagram 
	[参与者1][消息线][参与者2]:消息体
    ...

sequenceDiagram 为每幅时序图的固定开头

参与者(participant)

传统时序图概念中参与者有角色和类对象之分,但这里我们不做此区分,用参与者表示一切参与交互的事物,可以是人、类对象、系统等形式。中间竖直的线段从上至下表示时间的流逝。

sequenceDiagram
    participant 参与者 1
    participant 参与者 2
    ...
    participant 简称 as 参与者 3 #该语法可以在接下来的描述中使用简称来代替参与者 3

消息线(Messages)

类型 描述
-> 无箭头的实线
--> 无箭头的虚线
->> 有箭头的实线(主动发出消息)
-->> 有箭头的虚线(响应)
-x 末端为叉的实线(表示异步)
--x 末端为叉的虚线(表示异步)

处理中-激活框(activattions)

从消息接收方的时间线上标记一小段时间,表示对消息进行处理的时间间隔。

在消息线末尾增加 + ,则消息接收者进入当前消息的“处理中”状态; 在消息线末尾增加 - ,则消息接收者离开当前消息的“处理中”状态。

注解(note)

Note 位置表述 参与者: 标注文字
表述 含义
right of 右侧
left of 左侧
over 在当中,可以横跨多个参与者

循环(loop)

相当于while循环

选择(alt)

相当于ifelse

可选(opt)

相当于单个分支的 if

并行(Par)

将消息序列分成多个片段,这些片段并行执行

示例

sequenceDiagram
    Alice ->> Bob: Hello Bob, how are you?
    Bob-->>John: How about you John?
    Bob--x Alice: I am good thanks!
    Bob-x John: I am good thanks!
    Note right of John: Bob thinks a long<br/>long time, so long<br/>that the text does<br/>not fit on a row.

    Bob-->Alice: Checking with John...
    Alice->John: Yes... John, how are you?

类图(class diagram)

语法

UML 类图 ,包含属性和方法

classDiagram
    class BankAccount
    BankAccount : +String owner
    BankAccount : +Bigdecimal balance
    BankAccount : +deposit(amount)
    BankAccount : +withdrawl(amount)

定义类

两种定义方式:

  • 显式定义: class Animal,用关键字class定义
  • 隐式定义: Vehicle <|-- Car 通过它们之间的关系定义两个类

示例:

classDiagram
    class Animal
    Vehicle <|-- Car

定义类的成员

根据括号()是否存在来区分属性和函数/方法。带有()的将被视为函数/方法,其他将被视为属性

 classDiagram
 class BankAccount
 BankAccount : +String owner
 BankAccount : +BigDecimal balance
 BankAccount : +deposit(amount)
 BankAccount : +withdrawal(amount)

:号 后面加属性或方法

使用{}括号关联类的成员,其中成员分组在花括号内。适用于同时定义多个成员。

classDiagram
class BankAccount{
    +String owner
    +BigDecimal balance
    +deposit(amount)
    +withdrawl(amount)
}

返回值

在方法)后面加返回值 ,注意用空格隔开

classDiagram
class BankAccount{
    +String owner
    +BigDecimal balance
    +deposit(amount) bool
    +withdrawl(amount) int
}

泛型

支持List<int>泛型 ,使用~符号 ,不支持嵌套类型List<List<int>>

classDiagram
class Square~Shape~{
    int id
    List~int~ position
    setPoints(List~int~ points)
    getPoints() List~int~
}
Square : -List~string~ messages
Square : +setMessages(List~string~ messages)
Square : +getMessages() List~string~

可见度

  • + Public
  • - Private
  • # Protected
  • ~ Package/Internal

定义关系

支持的关系

类型 描述 描述
<|-- 泛化 用来表示继承的关系
*-- 组合 组合是一种整体与部分的关系,即contains-a的关系,比聚合更强
o-- 聚合 聚合是整体和个体之间的关系,即has-a的关系
--> 关联 类的全局变量引用了另一个类,就表示关联了这个类
..> 依赖 是一种使用的关系,即一个类的实现需要另一个类的协助
..|> 实现 实现是一种类与接口的关系
-- Link (Solid)
.. Link (Dashed)
classDiagram
classA <|-- classB
classC *-- classD
classE o-- classF
classG <-- classH
classI -- classJ
classK <.. classL
classM <|.. classN
classO .. classP

箭头也可以换方向,也可以给关系加标签

classDiagram
classA --|> classB : Inheritance
classC --* classD : Composition
classE --o classF : Aggregation
classG --> classH : Association
classI -- classJ : Link(Solid)
classK ..> classL : Dependency
classM ..|> classN : Realization
classO .. classP : Link(Dashed)

双向关系

箭头两边都写就行了 ,Link不支持双向关系

classDiagram
    Animal <|--|> Zebra

关系的基数/多重性

  • 1 只有1
  • 0..1 0或1
  • 1..* 1或更多
  • * 全部
  • n n{其中n>1}
  • 0..n 0到n{其中n>1}
  • 1..n 1到n{其中n>1}

示例:

classDiagram
    Customer "1" --> "*" Ticket
    Student "1" --> "1..*" Course
    Galaxy --> "many" Star : Contains

类的注解

可以使用特定的标记文本对类进行注释

  • <<Interface>> 接口
  • <<abstract>> 抽象类
  • <<Service>> 服务类
  • <<enumeration>> 枚举

定义类后的单独一行

classDiagram
class Shape
<<interface>> Shape
Shape : noOfVertices
Shape : draw()

在嵌套结构和类定义中

classDiagram
class Shape{
    <<interface>>
    noOfVertices
    draw()
}
class Color{
    <<enumeration>>
    RED
    BLUE
    GREEN
    WHITE
    BLACK
}

注释

%%开头

classDiagram
%% This whole line is a comment classDiagram class Shape <<interface>>
class Shape{
    <<interface>>
    noOfVertices
    draw()
}

设置图表的方向

classDiagram
  direction RL
  class Student {
    -idCard : IdCard
  }
  class IdCard{
    -id : int
    -name : string
  }
  class Bike{
    -id : int
    -name : string
  }
  Student "1" --o "1" IdCard : carries
  Student "1" --o "1" Bike : rides

示例

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()
      }
      link Zebra "http://www.github.com" "This is a link"

其他图形及示例

饼图(Pie Chart)

语法如下,title标题可不写,选项数值为正数值(最多支持两位小数)

pie
title 标题
"选项1" : 11.11
"选项2" : 22.22
"选项3" : 33.33

用户旅行图(User Journey Diagram)

任务语法

Task name: <score>: <comma separated list of actors>
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

甘特图(Gantt)

语法

gantt
    dateFormat  YYYY-MM-DD
    title       Adding GANTT diagram functionality to mermaid
    excludes    weekends
    %% (`excludes` accepts specific dates in YYYY-MM-DD format, days of the week ("sunday") or "weekends", but not the word "weekdays".)

    section A section
    Completed task            :done,    des1, 2014-01-06,2014-01-08
    Active task               :active,  des2, 2014-01-09, 3d
    Future task               :         des3, after des2, 5d
    Future task2              :         des4, after des3, 5d

    section Critical tasks
    Completed task in the critical line :crit, done, 2014-01-06,24h
    Implement parser and jison          :crit, done, after des1, 2d
    Create tests for parser             :crit, active, 3d
    Future task in critical line        :crit, 5d
    Create tests for renderer           :2d
    Add to mermaid                      :1d
    Functionality added                 :milestone, 2014-01-25, 0d

    section Documentation
    Describe gantt syntax               :active, a1, after des1, 3d
    Add gantt diagram to demo page      :after a1  , 20h
    Add another diagram to demo page    :doc1, after a1  , 48h

    section Last section
    Describe gantt syntax               :after doc1, 3d
    Add gantt diagram to demo page      :20h
    Add another diagram to demo page    :48h

标题

title标题是可选项,用于描述整个图表

章节说明

可以将不同的部分区分开来

section后面接描述 ,描述必填

里程碑

gantt 
dateFormat HH:mm
axisFormat %H:%M
Initial milestone : milestone, m1, 17:49,2min
taska2 : 2min
taska3 : 6min 
Final milestone : milestone, m2,17:59, 2min

设置时间

输入时间
dateFormat YYYY-MM-DD
Input       Example             Description:
YYYY        2014                4 digit year
YY          14                  2 digit year
Q           1..4                Quarter of year. Sets month to first month in quarter.
M MM        1..12               Month number
MMM MMMM    January..Dec        Month name in locale set by moment.locale()
D DD        1..31               Day of month
Do          1st..31st           Day of month with ordinal
DDD DDDD    1..365              Day of year
X           1410715640.579      Unix timestamp
x           1410715640579       Unix ms timestamp
H HH        0..23               24 hour time
h hh        1..12               12 hour time used with a A.
a A         am pm               Post or ante meridiem
m mm        0..59               Minutes
s ss        0..59               Seconds
S           0..9                Tenths of a second
SS          0..99               Hundreds of a second
SSS         0..999              Thousandths of a second
Z ZZ        +12:00              Offset from UTC as +-HH:mm, +-HHmm, or Z
输出时间
axisFormat  %Y-%m-%d
%a - abbreviated weekday name.
%A - full weekday name.
%b - abbreviated month name.
%B - full month name.
%c - date and time, as "%a %b %e %H:%M:%S %Y".
%d - zero-padded day of the month as a decimal number [01,31].
%e - space-padded day of the month as a decimal number [ 1,31]; equivalent to %_d.
%H - hour (24-hour clock) as a decimal number [00,23].
%I - hour (12-hour clock) as a decimal number [01,12].
%j - day of the year as a decimal number [001,366].
%m - month as a decimal number [01,12].
%M - minute as a decimal number [00,59].
%L - milliseconds as a decimal number [000, 999].
%p - either AM or PM.
%S - second as a decimal number [00,61].
%U - week number of the year (Sunday as the first day of the week) as a decimal number [00,53].
%w - weekday as a decimal number [0(Sunday),6].
%W - week number of the year (Monday as the first day of the week) as a decimal number [00,53].
%x - date, as "%m/%d/%Y".
%X - time, as "%H:%M:%S".
%y - year without century as a decimal number [00,99].
%Y - year with century as a decimal number.
%Z - time zone offset, such as "-0700".
%% - a literal "%" character.

状态图(State diagrams)

stateDiagram后面的-v2是v2版的 ,可以去掉

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

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

语法

开始和停止用[*]表示 ,流程用-->表示

选择

如果需要在多个中选择使用<<choice>>

stateDiagram-v2
    state if_state <<choice>>
    [*] --> IsPositive
    IsPositive --> if_state
    if_state --> False: if n < 0
    if_state --> True : if n >= 0

Forks

使用状态<<fork>> <<join>>

stateDiagram-v2
    state fork_state <<fork>>
      [*] --> fork_state
      fork_state --> State2
      fork_state --> State3

      state join_state <<join>>
      State2 --> join_state
      State3 --> join_state
      join_state --> State4
      State4 --> [*]

便签

添加便签 right of 或者left of

    stateDiagram-v2
        State1: The state with a note
        note right of State1
            Important information! You can write
            notes.
        end note
        State1 --> State2
        note left of State2 : This is the note to the left.