
Mermaid Diagrams
- 113 installs
- 14 repo stars
- Updated March 2, 2026
- oakoss/agent-skills
Helps with ai & agent building tasks during AI-assisted development.
About
mermaid-diagrams is a Claude Code skill for ai & agent building. It helps solo builders move faster with AI-assisted coding.
- mermaid-diagrams
- AI & Agent Building
- AI-coding skill
Mermaid Diagrams by the numbers
- 113 all-time installs (skills.sh)
- +4 installs in the week ending Aug 4, 2026 (Skillselion tracking)
- Ranked #3,984 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Aug 4, 2026 (Skillselion catalog sync)
npx skills add https://github.com/oakoss/agent-skills --skill mermaid-diagramsAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 113 |
|---|---|
| repo stars | ★ 14 |
| Last updated | March 2, 2026 |
| Repository | oakoss/agent-skills ↗ |
What it does
Helps with ai & agent building tasks during AI-assisted development.
Files
Mermaid Diagrams
Overview
Mermaid is a JavaScript-based diagramming tool that renders Markdown-inspired text definitions into SVG diagrams. It supports flowcharts, sequence diagrams, ER diagrams, class diagrams, state diagrams, Gantt charts, pie charts, mindmaps, and git graphs directly inside Markdown files.
When to use: Documenting system architecture, visualizing data models, illustrating request flows, creating project timelines, embedding diagrams in GitHub/GitLab READMEs or docs sites.
When NOT to use: Pixel-perfect design mockups, interactive dashboards, diagrams requiring custom artwork or complex spatial layouts beyond hierarchical/relational structures.
Quick Reference
| Diagram | Declaration | Key Points |
|---|---|---|
| Flowchart | flowchart TD | Directions: TB, TD, BT, RL, LR. Supports subgraphs |
| Sequence | sequenceDiagram | Participants, messages, loops, alt/opt/par blocks |
| ER Diagram | erDiagram | Crow's foot notation, PK/FK/UK attributes |
| Class Diagram | classDiagram | UML relationships, visibility modifiers, annotations |
| State Diagram | stateDiagram-v2 | Transitions, composite states, forks/joins, choice |
| Gantt Chart | gantt | Sections, tasks with dates/durations, milestones |
| Pie Chart | pie | Labels with numeric values, optional title |
| Mindmap | mindmap | Indentation-based hierarchy, multiple node shapes |
| Git Graph | gitGraph | Commits, branches, merges, cherry-picks, tags |
| Architecture | architecture-beta | Services in groups, directional edges (T/B/L/R) |
| Block Diagram | block-beta | Column layout, block arrows, nested blocks |
| Timeline | timeline | Time periods with events, sections for grouping |
| Sankey | sankey-beta | Flow quantities between nodes, CSV-like data format |
| XY Chart | xychart-beta | Bar and line charts with x/y axes |
| Quadrant Chart | quadrantChart | Four-quadrant plot with labeled axes and data points |
| Kanban | kanban | Columns with task cards, assignees, priorities |
| Packet | packet-beta | Network packet structure with bit-range fields |
| Requirement | requirementDiagram | Requirements, elements, and verification links |
| C4 Diagram | C4Context | C4 model: Context, Container, Component, Deployment |
Common Mistakes
| Mistake | Correct Pattern |
|---|---|
Using graph instead of flowchart | Use flowchart for subgraph edges and newer features |
| Missing space after arrow in sequences | Alice->>Bob: msg not Alice->>Bob:msg |
| Wrong cardinality order in ER diagrams | Left cardinality, then line, then right cardinality |
Forgetting end after subgraph/loop/alt | Every block keyword requires a matching end |
| Using reserved words as node IDs | Wrap reserved words in quotes or use aliases |
| Bare code blocks without language tag | Always use `mermaid as the language specifier |
| Mixing v1 and v2 state diagram syntax | Use stateDiagram-v2 consistently for current features |
| Unquoted labels with special characters | Wrap labels containing special characters in double quotes |
Missing dateFormat in Gantt charts | Always declare dateFormat before task definitions |
| Using tabs instead of spaces for mindmaps | Mindmap indentation requires spaces, not tabs |
Delegation
- Diagram discovery and exploration: Use
Exploreagent to find existing diagrams in the codebase - Diagram review: Use
Taskagent to verify diagram accuracy against code - Architecture documentation: Use
code-revieweragent for doc quality checks
References
- Flowcharts: nodes, edges, subgraphs, directions, and styling
- Sequence diagrams: participants, messages, activations, and control flow
- Entity-relationship diagrams: entities, attributes, and cardinality
- Class diagrams: classes, methods, relationships, and annotations
- Other diagrams: Gantt, pie, mindmap, state, and git graph
- Architecture, block, timeline, Sankey, XY chart, quadrant, kanban, packet, requirement, and C4 diagrams
Class Diagrams
Declaration
classDiagram
class Animal {
+String name
+makeSound() void
}Defining Classes
Bracket Syntax
classDiagram
class BankAccount {
+String owner
+BigDecimal balance
+deposit(amount) void
+withdraw(amount) bool
}Colon Syntax
classDiagram
class BankAccount
BankAccount : +String owner
BankAccount : +BigDecimal balance
BankAccount : +deposit(amount) void
BankAccount : +withdraw(amount) boolBoth syntaxes produce identical output. Bracket syntax is preferred for readability.
Visibility Modifiers
| Symbol | Access |
|---|---|
+ | Public |
- | Private |
# | Protected |
~ | Package |
classDiagram
class User {
+String name
-String passwordHash
#int loginAttempts
~String internalId
+login(password) bool
-hashPassword(raw) String
}Method Classifiers
| Suffix | Meaning |
|---|---|
* | Abstract |
$ | Static |
classDiagram
class Shape {
+draw()* void
+getDefaultColor()$ String
}Return Types
Specify return types after the method signature.
classDiagram
class Service {
+findById(id) User
+findAll() List~User~
+delete(id) void
+count()$ int
}Generics
Use tildes to denote generic types.
classDiagram
class Repository~T~ {
+find(id) T
+findAll() List~T~
+save(entity) T
+delete(id) void
}Relationships
Eight relationship types are supported, each with distinct arrow syntax.
classDiagram
Animal <|-- Dog : Inheritance
Vehicle *-- Engine : Composition
Library o-- Book : Aggregation
Controller --> Service : Association
Service ..> Repository : Dependency
Flyable <|.. Bird : Realization
ClassA -- ClassB : Link
ClassC .. ClassD : Dashed Link| Arrow | Type | Meaning |
|---|---|---|
| `<\ | --` | Inheritance |
*-- | Composition | Part cannot exist without whole |
o-- | Aggregation | Part can exist independently |
--> | Association | Uses or references |
..> | Dependency | Depends on (weaker than association) |
| `..\ | >` | Realization |
-- | Link (solid) | General connection |
.. | Link (dashed) | General dashed connection |
Bidirectional Relationships
Combine relation types for two-way relationships.
classDiagram
Student "1..*" <--> "1..*" Course : enrollsCardinality Labels
Place cardinality on either side of the relationship.
classDiagram
Customer "1" --> "*" Order : places
Order "1" --> "1..*" LineItem : contains
LineItem "*" --> "1" Product : references| Notation | Meaning |
|---|---|
1 | Exactly one |
0..1 | Zero or one |
1..* | One or more |
* | Many |
n | N instances |
0..n | Zero to N |
Annotations
Mark classes with stereotypes.
classDiagram
class Serializable {
<<Interface>>
+serialize() String
}
class Shape {
<<Abstract>>
+area()* double
+perimeter()* double
}
class Color {
<<Enumeration>>
RED
GREEN
BLUE
}
class Logger {
<<Service>>
+log(message) void
}Available annotations: <<Interface>>, <<Abstract>>, <<Service>>, <<Enumeration>>.
Namespaces
Group related classes into namespaces.
classDiagram
namespace Domain {
class User {
+String name
+String email
}
class Order {
+int id
+Date createdAt
}
}
namespace Infrastructure {
class UserRepository {
+find(id) User
}
class OrderRepository {
+find(id) Order
}
}
UserRepository ..> User
OrderRepository ..> OrderNotes
Add notes to the diagram or to specific classes.
classDiagram
class Account {
+String id
+deposit(amount) void
}
note "Domain model for banking"
note for Account "Aggregate root"Lollipop Interfaces
Show interface implementation with a compact notation.
classDiagram
class Database
class Cache
Storable ()-- Database
Storable ()-- CacheStyling
Apply CSS-like styles to individual classes.
classDiagram
class Important {
+String data
}
class Normal {
+String data
}
style Important fill:#f9f,stroke:#333,stroke-width:2px
classDef interfaces fill:#ccf,stroke:#33f
class Serializable:::interfacesComplete Example
classDiagram
class EventEmitter {
<<Abstract>>
#List~Listener~ listeners
+on(event, callback) void
+emit(event, data) void
+off(event, callback) void
}
class HttpServer {
-int port
-Router router
+listen(port) void
+close() void
}
class Router {
-Map~String, Handler~ routes
+get(path, handler) void
+post(path, handler) void
+match(request) Handler
}
class Handler {
<<Interface>>
+handle(request) Response*
}
class Middleware {
<<Interface>>
+process(request, next) Response*
}
EventEmitter <|-- HttpServer
HttpServer *-- Router
Router o-- Handler
Handler <|.. MiddlewareEntity-Relationship Diagrams
Declaration
erDiagram
CUSTOMER ||--o{ ORDER : placesBasic Syntax
Each line follows the pattern:
<entity> [<relationship> <entity> : <label>]Only the first entity name is required. The relationship, second entity, and label are optional.
Entities
Entities are automatically created when referenced. Names should use uppercase or PascalCase by convention.
erDiagram
CUSTOMER {
int id PK
string name
string email UK
}
ORDER {
int id PK
int customer_id FK
date created_at
float total
}
CUSTOMER ||--o{ ORDER : placesAttributes
Define attributes inside entity braces with the format: type name [key] ["comment"].
erDiagram
PRODUCT {
int id PK "Auto-generated"
string name "Product display name"
string sku UK "Stock keeping unit"
float price
int category_id FK
boolean active
}| Key | Meaning |
|---|---|
PK | Primary Key |
FK | Foreign Key |
UK | Unique Key |
Keys and comments are optional. Multiple keys can appear on a single attribute.
Cardinality (Crow's Foot Notation)
Relationships use two-character markers on each side of the connecting line.
| Left | Right | Meaning |
|---|---|---|
| `\ | o` | `o\ |
| `\ | \ | ` |
}o | o{ | Zero or more |
| `}\ | ` | `\ |
Reading Cardinality
Read relationships from left entity to right entity:
CUSTOMER ||--o{ ORDER : places- Left side
||= "exactly one" CUSTOMER - Right side
o{= "zero or more" ORDERS - Reads: "One customer places zero or more orders"
Word Aliases
Mermaid supports English aliases for cardinality markers:
erDiagram
CUSTOMER one or more--one or more DELIVERY-ADDRESS : has
CUSTOMER exactly one--zero or more ORDER : placesAvailable aliases: "one or zero", "zero or one", "one or more", "one or many", "many(1)", "1+", "zero or more", "zero or many", "many(0)", "0+", "only one", "exactly one", "1".
Relationship Lines
| Syntax | Type | Visual |
|---|---|---|
-- | Identifying (solid line) | Solid line |
.. | Non-identifying (dashed) | Dashed line |
Identifying relationships mean the child entity cannot exist without the parent.
erDiagram
PERSON ||--o{ FINGERPRINT : has
PERSON ||..o{ ADDRESS : "lives at"PERSON ||--o{ FINGERPRINT= identifying (fingerprint depends on person)PERSON ||..o{ ADDRESS= non-identifying (address exists independently)
Relationship Labels
Labels describe the nature of the relationship. Wrap multi-word labels in double quotes.
erDiagram
STUDENT ||--o{ ENROLLMENT : "enrolls in"
COURSE ||--o{ ENROLLMENT : "offered through"
PROFESSOR ||--o{ COURSE : teachesComplete Example
erDiagram
USER {
int id PK
string username UK
string email UK
string password_hash
datetime created_at
}
TEAM {
int id PK
string name
string slug UK
}
TEAM_MEMBER {
int id PK
int user_id FK
int team_id FK
string role "admin, member, viewer"
}
PROJECT {
int id PK
int team_id FK
string name
string status "active, archived"
}
TASK {
int id PK
int project_id FK
int assignee_id FK "Nullable"
string title
string priority "low, medium, high, critical"
datetime due_date
}
COMMENT {
int id PK
int task_id FK
int author_id FK
text body
datetime created_at
}
USER ||--o{ TEAM_MEMBER : "belongs to"
TEAM ||--o{ TEAM_MEMBER : "has"
TEAM ||--o{ PROJECT : owns
PROJECT ||--o{ TASK : contains
USER ||--o{ TASK : "assigned to"
TASK ||--o{ COMMENT : has
USER ||--o{ COMMENT : writesTips
- Entity names cannot contain spaces; use underscores or PascalCase
- Attribute types are freeform strings (not validated against a type system)
- The colon before the relationship label is required
- Relationship labels are displayed on the connecting line
- Use identifying (
--) for strong dependencies and non-identifying (..) for loose associations
Extended Diagrams
Mermaid v11 introduced several diagram types beyond the core set. Many use -beta suffixes in their declarations.
Architecture Diagrams
Visualize system architecture with services, groups, and directional edges.
architecture-beta
group api(cloud)[API]
service db(database)[Database] in api
service server(server)[Server] in api
service disk(disk)[Storage] in api
db:R -- L:server
server:R -- L:diskKey syntax:
group name(icon)[Label]-- define a group with an iconservice name(icon)[Label] in group-- place a service in a groupservice:PORT -- PORT:service-- connect with directional edges- Ports:
T(top),B(bottom),L(left),R(right) - Icons:
cloud,database,server,disk,internet
Block Diagrams
Grid-based layout with columns, block arrows, and nested blocks.
block-beta
columns 3
Frontend blockArrowId6<[" "]>(right) Backend
space:2 down<[" "]>(down)
Disk left<[" "]>(left) Database[("Database")]Key syntax:
columns N-- set grid column countspaceorspace:N-- insert empty cellsid<["label"]>(direction)-- block arrow (up, down, left, right)- Standard node shapes from flowcharts work inside blocks
Timeline Diagrams
Display chronological events grouped by time periods.
timeline
title Project History
section 2023
Q1 : Requirements gathering
: Team formation
Q2 : MVP development
section 2024
Q1 : Beta launch
Q2 : General availabilityKey syntax:
title-- optional diagram titlesection Name-- group events by time period- Indent events under their time period
- Multiple events per period separated by
:on new lines
Sankey Diagrams
Visualize flow quantities between nodes using a CSV-like format.
sankey-beta
Agricultural "waste",Bio-conversion,124.729
Bio-conversion,Liquid,0.597
Bio-conversion,Losses,26.862
Bio-conversion,Solid,280.322
Bio-conversion,Gas,81.144Key syntax:
- Each line:
source,target,value - Values determine the width of flow connections
- Nodes are created automatically from source/target names
- Wrap node names in quotes if they contain commas
XY Charts
Bar and line charts with labeled axes.
xychart-beta
title "Monthly Revenue"
x-axis [Jan, Feb, Mar, Apr, May, Jun]
y-axis "Revenue (USD)" 4000 --> 11000
bar [5000, 6000, 7500, 8200, 9800, 10500]
line [5000, 6000, 7000, 8000, 9000, 10000]Key syntax:
x-axis [labels]orx-axis "Label" min --> maxy-axis "Label" min --> maxbar [values]-- bar chart dataline [values]-- line chart data- Multiple
barandlineseries supported
Quadrant Charts
Four-quadrant plots for comparative analysis.
quadrantChart
title Technology Radar
x-axis Low Effort --> High Effort
y-axis Low Impact --> High Impact
quadrant-1 Do First
quadrant-2 Schedule
quadrant-3 Delegate
quadrant-4 Eliminate
Component A: [0.8, 0.9]
Component B: [0.3, 0.7]
Component C: [0.6, 0.2]
Component D: [0.2, 0.3]Key syntax:
x-axisandy-axisdefine axis labels with arrows for directionquadrant-1throughquadrant-4label each quadrant- Data points:
Label: [x, y]with values 0.0 to 1.0
Kanban Diagrams
Kanban boards with columns and task cards.
kanban
Todo
[Design API schema]
[Write migration scripts]
In Progress
[Implement auth service]
Done
[Set up CI pipeline]Key syntax:
- Column names at top indentation level
- Task cards indented under columns:
[Task title] - Task metadata:
id[Title]@{ assigned: 'name', priority: 'High', ticket: 'PROJ-123' } - Configure ticket URLs:
config.kanban.ticketBaseUrl
Packet Diagrams
Visualize network packet structures with bit-range fields.
packet-beta
0-15: "Source Port"
16-31: "Destination Port"
32-63: "Sequence Number"
64-95: "Acknowledgment Number"
96-99: "Data Offset"
100-105: "Reserved"
106-111: "Flags"
112-127: "Window Size"Key syntax:
start-end: "Label"-- define a field spanning bit range+N: "Label"-- auto-increment N bits from previous position- Default row width is 32 bits (configurable)
Requirement Diagrams
Model requirements with elements and verification relationships.
requirementDiagram
requirement Login Feature {
id: 1
text: Users must authenticate via OAuth2
risk: high
verifymethod: test
}
element Auth Service {
type: microservice
}
Auth Service - satisfies -> Login FeatureRequirement types: requirement, functionalRequirement, performanceRequirement, interfaceRequirement, physicalRequirement, designConstraint.
Relationships: contains, copies, derives, satisfies, verifies, refines, traces.
C4 Diagrams
Model software architecture using the C4 model at four levels.
C4Context
title System Context Diagram
Person(user, "User", "A customer")
System(app, "Web Application", "The main system")
System_Ext(email, "Email System", "Sends notifications")
Rel(user, app, "Uses", "HTTPS")
Rel(app, email, "Sends emails", "SMTP")Diagram levels:
C4Context-- system context (people and systems)C4Container-- containers within a systemC4Component-- components within a containerC4Deployment-- deployment nodes and infrastructure
Key elements:
Person(id, "Name", "Description")System(id, "Name", "Description")/System_Extfor externalContainer(id, "Name", "Tech", "Description")/ContainerDbComponent(id, "Name", "Tech", "Description")Container_Boundary(id, "Label") { ... }for groupingRel(from, to, "Label", "Tech")for relationships
Flowcharts
Declaration and Direction
Start with flowchart followed by a direction keyword.
flowchart LR
A --> B --> C| Direction | Meaning |
|---|---|
TB | Top to bottom |
TD | Top-down (= TB) |
BT | Bottom to top |
RL | Right to left |
LR | Left to right |
Node Shapes
Nodes are defined by their ID and shape delimiters. Text inside the delimiters becomes the label.
flowchart TD
A[Rectangle]
B(Rounded)
C([Stadium])
D[[Subroutine]]
E[(Cylinder)]
F((Circle))
G>Asymmetric]
H{Diamond}
I{{Hexagon}}
J[/Parallelogram/]
K[\Parallelogram Alt\]
L[/Trapezoid\]
M[\Trapezoid Alt/]
N(((Double Circle)))Extended Shapes (v11.3.0+)
Use the @{ shape: name } syntax for additional shapes.
flowchart LR
A@{ shape: rect, label: "Rectangle" }
B@{ shape: diamond, label: "Decision" }
C@{ shape: stadium, label: "Stadium" }
D@{ shape: cylinder, label: "Database" }
E@{ shape: document, label: "Document" }Edge Types
Edges connect nodes with various line styles and terminators.
flowchart LR
A --> B
C --- D
E -.- F
G === H
I -.-> J
K ==> L
M o--o N
N x--x O| Syntax | Description |
|---|---|
--> | Arrow |
--- | Open link |
-.- | Dotted link |
=== | Thick link |
-.-> | Dotted arrow |
==> | Thick arrow |
o--o | Circle endpoints |
x--x | Cross endpoints |
<--> | Bidirectional arrow |
Edge Labels
Add text to edges using pipe syntax or inline text.
flowchart LR
A -->|Yes| B
A -->|No| C
D -- "Edge label" --> EMulti-length Edges
Add extra characters to increase edge length.
flowchart TD
A --> B
A ---> C
A ----> DSubgraphs
Group related nodes inside subgraphs. Subgraphs can be nested and can have their own direction.
flowchart TB
c1 --> a2
subgraph one [First Group]
a1 --> a2
end
subgraph two [Second Group]
direction LR
b1 --> b2
end
subgraph three [Third Group]
c1 --> c2
end
one --> twoKey rules:
- Subgraph IDs are used for edges between subgraphs
- Use
directioninside a subgraph to override parent direction - If a subgraph node links to the outside, direction is inherited from parent
- Subgraphs can be nested arbitrarily deep
Styling
Class Definitions
Define reusable styles with classDef and apply them with class or the ::: shorthand.
flowchart LR
A:::success --> B:::error
classDef success fill:#d4edda,stroke:#28a745,color:#155724
classDef error fill:#f8d7da,stroke:#dc3545,color:#721c24Inline Styles
Apply styles directly to specific nodes or links.
flowchart LR
A --> B --> C
style A fill:#f9f,stroke:#333,stroke-width:2px
style B fill:#bbf,stroke:#33f
linkStyle 0 stroke:#ff3,stroke-width:4px
linkStyle 1 stroke:#3f3,stroke-width:2pxThe linkStyle index corresponds to the order edges appear in the definition (0-based).
Default Styling
Apply a style to all nodes using the default class.
flowchart LR
A --> B --> C
classDef default fill:#f0f0f0,stroke:#333Click Interactions
Bind click events to nodes for callbacks or navigation.
flowchart LR
A --> B --> C
click A "https://example.com" "Open docs" _blank
click B callback "Trigger action"Supported targets: _self, _blank, _parent, _top.
Markdown Strings
Use double quotes with backticks for rich text formatting in labels.
flowchart LR
A["`**Bold** and *italic* text`"] --> B["`Line one
Line two`"]Markdown strings support bold, italics, and automatic text wrapping.
Comments
Add comments with %% at the start of a line.
flowchart LR
%% This is a comment
A --> BComplete Example
flowchart TD
Start([Start]) --> CheckAuth{Authenticated?}
CheckAuth -->|Yes| Dashboard[Dashboard]
CheckAuth -->|No| Login[Login Page]
Login --> Validate{Valid Credentials?}
Validate -->|Yes| Dashboard
Validate -->|No| Login
subgraph auth [Authentication Flow]
Login
Validate
end
Dashboard --> Logout([Logout])
Logout --> Login
classDef decision fill:#ffeaa7,stroke:#fdcb6e
classDef page fill:#dfe6e9,stroke:#b2bec3
classDef action fill:#55efc4,stroke:#00b894
class CheckAuth,Validate decision
class Dashboard,Login page
class Start,Logout actionOther Diagrams
Gantt Charts
Gantt charts visualize project schedules with tasks, durations, and dependencies.
Basic Structure
gantt
title Project Timeline
dateFormat YYYY-MM-DD
excludes weekends
section Planning
Requirements :done, req, 2024-01-01, 5d
Design :active, des, after req, 10d
section Development
Backend API :dev1, after des, 15d
Frontend UI :dev2, after des, 12d
Integration :dev3, after dev1, 5d
section Release
Testing :test, after dev3, 7d
Launch :milestone, launch, after test, 0dTask Modifiers
| Modifier | Effect |
|---|---|
done | Marks task as completed |
active | Marks task as in progress |
crit | Marks as critical path |
milestone | Zero-duration marker |
Date Formats
Set with dateFormat. Common formats: YYYY-MM-DD, DD-MM-YYYY, YYYY-MM-DDTHH:mm.
Duration Syntax
Tasks accept absolute dates or relative durations.
gantt
dateFormat YYYY-MM-DD
section Durations
Five days :a, 2024-01-01, 5d
24 hours :b, after a, 24h
One week :c, after b, 1w
Until date :d, after c, 2024-02-15Dependencies
Use after <task-id> to chain tasks.
gantt
dateFormat YYYY-MM-DD
A :a, 2024-01-01, 3d
B :b, after a, 2d
C :c, after a, 4d
D :d, after b c, 2dTask D starts after both B and C complete.
Pie Charts
Simple proportional data visualization.
pie title Revenue by Product
"Product A" : 45
"Product B" : 30
"Product C" : 15
"Product D" : 10Show Data Values
Display raw values alongside percentages.
pie showData
title Browser Market Share
"Chrome" : 65
"Safari" : 19
"Firefox" : 8
"Edge" : 5
"Other" : 3Values are numeric (integers or decimals). Labels must be in double quotes.
Mindmaps
Hierarchical diagrams using indentation for parent-child relationships.
Basic Structure
mindmap
root((Project))
Frontend
React
TypeScript
TailwindCSS
Backend
Node.js
PostgreSQL
Redis
Infrastructure
AWS
Docker
CI/CDNode Shapes
mindmap
root
Default shape
[Square]
(Rounded)
((Circle))
))Cloud((
{{Hexagon}}| Syntax | Shape |
|---|---|
| Plain text | Default |
[text] | Square |
(text) | Rounded square |
((text)) | Circle |
))text(( | Cloud |
{{text}} | Hexagon |
Icons and Formatting
mindmap
root((Central Topic))
::icon(fa fa-book)
**Bold text**
*Italic text*
A longer label that wrapsIcons use Font Awesome or Material Design class names with ::icon(class).
State Diagrams
Model state machines with transitions, composite states, and concurrency.
Basic States and Transitions
stateDiagram-v2
[*] --> Idle
Idle --> Processing : Submit
Processing --> Success : Complete
Processing --> Error : Fail
Error --> Idle : Retry
Success --> [*][*] represents the start state (when targeted) or end state (when sourced).
State Descriptions
stateDiagram-v2
state "Waiting for input" as Waiting
state "Processing request" as Processing
[*] --> Waiting
Waiting --> Processing : Receive
Processing --> Waiting : DoneComposite States
Nest states inside parent states.
stateDiagram-v2
[*] --> Active
state Active {
[*] --> Idle
Idle --> Running : start
Running --> Idle : stop
}
Active --> Inactive : disable
Inactive --> Active : enableChoice
Branch transitions based on conditions.
stateDiagram-v2
state check <<choice>>
[*] --> check
check --> Approved : if valid
check --> Rejected : if invalid
Approved --> [*]
Rejected --> [*]Forks and Joins
Model parallel execution paths.
stateDiagram-v2
state fork_state <<fork>>
state join_state <<join>>
[*] --> fork_state
fork_state --> TaskA
fork_state --> TaskB
TaskA --> join_state
TaskB --> join_state
join_state --> Done
Done --> [*]Concurrency
Show parallel regions within a state using --.
stateDiagram-v2
[*] --> Active
state Active {
[*] --> ProcessA
--
[*] --> ProcessB
}
Active --> [*]Notes
stateDiagram-v2
[*] --> Active
Active --> Inactive
note right of Active
This state handles
all user interactions
end note
note left of Inactive : System is pausedGit Graphs
Visualize branching, merging, and commit history.
Basic Commands
gitGraph
commit
commit
branch develop
checkout develop
commit
commit
checkout main
merge develop
commitCommit Options
gitGraph
commit id: "init"
commit id: "feat-1" tag: "v1.0.0"
branch feature
commit id: "wip"
commit id: "done" type: HIGHLIGHT
checkout main
merge feature id: "merge-feat" tag: "v1.1.0"
commit id: "hotfix" type: REVERSE| Option | Values |
|---|---|
id | Custom commit identifier (quoted) |
tag | Label displayed on commit (quoted) |
type | NORMAL, REVERSE, HIGHLIGHT |
Cherry-pick
gitGraph
commit id: "base"
branch feature
commit id: "important-fix"
checkout main
cherry-pick id: "important-fix"
commitThe cherry-picked commit must have a custom id and must exist on a different branch.
Branch Ordering
Control the visual order of branches.
gitGraph
commit
branch hotfix order: 1
branch feature order: 2
checkout feature
commit
checkout hotfix
commit
checkout main
merge hotfix
merge featureLower order values appear closer to main.
Orientation
gitGraph TB:
commit
branch develop
commit
checkout main
merge developOrientations: LR (default, left-to-right), TB (top-to-bottom), BT (bottom-to-top).
Configuration
All diagram types support frontmatter configuration.
---
config:
theme: forest
---
flowchart LR
A --> BAvailable themes: default, neutral, dark, forest, base.
Sequence Diagrams
Declaration
sequenceDiagram
Alice->>Bob: Hello Bob
Bob-->>Alice: Hi AliceParticipants and Actors
Declare participants explicitly to control ordering, or let them appear implicitly.
sequenceDiagram
participant A as Auth Service
participant B as Backend API
actor U as User
U->>A: Login request
A->>B: Validate token
B-->>A: Token valid
A-->>U: Session created| Keyword | Rendering |
|---|---|
participant | Rectangle box |
actor | Stick figure |
boundary | Boundary box |
control | Control circle |
entity | Entity underline |
database | Database icon |
collections | Stack icon |
queue | Queue icon |
Message Arrow Types
| Arrow | Description |
|---|---|
-> | Solid line, no arrowhead |
--> | Dotted line, no arrowhead |
->> | Solid line with arrowhead |
-->> | Dotted line with arrowhead |
<<->> | Solid bidirectional |
<<-->> | Dotted bidirectional |
-x | Solid line with cross |
--x | Dotted line with cross |
-) | Solid async arrow |
--) | Dotted async arrow |
Activations
Show when a participant is actively processing. Use explicit keywords or shorthand notation.
sequenceDiagram
participant C as Client
participant S as Server
C->>+S: Request
S->>+S: Process
S->>-S: Done processing
S-->>-C: ResponseThe + suffix activates and - deactivates. Multiple activations can stack on the same participant.
Explicit form:
sequenceDiagram
participant C as Client
participant S as Server
C->>S: Request
activate S
S-->>C: Response
deactivate SLoops
Repeat a block of messages.
sequenceDiagram
participant C as Client
participant S as Server
C->>S: Subscribe
loop Every 30 seconds
S-->>C: Heartbeat
endAlt / Else (Conditional)
Model branching logic with alternative paths.
sequenceDiagram
participant U as User
participant S as Server
U->>S: Login
alt Valid credentials
S-->>U: 200 OK
else Invalid credentials
S-->>U: 401 Unauthorized
endOpt (Optional)
Model an optional interaction that may or may not occur.
sequenceDiagram
participant U as User
participant S as Server
U->>S: Request data
opt Cache available
S-->>U: Cached response
end
S-->>U: Fresh responsePar (Parallel)
Show concurrent interactions.
sequenceDiagram
participant C as Client
participant A as Service A
participant B as Service B
par Request to A
C->>A: Fetch users
and Request to B
C->>B: Fetch orders
end
A-->>C: Users
B-->>C: OrdersNested par blocks are supported for deeper concurrency.
Critical Regions
Mark interactions that must succeed, with fallback options.
sequenceDiagram
participant C as Client
participant DB as Database
critical Establish connection
C->>DB: Connect
option Connection timeout
C->>C: Retry with backoff
option Connection refused
C->>C: Use fallback cache
endBreak
Exit the sequence flow when a condition is met.
sequenceDiagram
participant C as Consumer
participant Q as Queue
C->>Q: Poll message
break No messages available
Q-->>C: Empty response
end
Q-->>C: Message payloadNotes
Add annotations to specific participants.
sequenceDiagram
participant A as Alice
participant B as Bob
A->>B: Hello
Note right of B: Thinking...
Note left of A: Waiting
Note over A,B: Handshake complete
B-->>A: Hi therePositions: right of, left of, over (single or range with comma).
Background Highlighting
Use rect to highlight a region of the diagram.
sequenceDiagram
participant A as Alice
participant B as Bob
rect rgb(200, 220, 255)
A->>B: Request inside highlight
B-->>A: Response inside highlight
endParticipant Grouping
Group participants into labeled boxes.
sequenceDiagram
box Blue Frontend
participant U as User
participant UI as Browser
end
box Green Backend
participant API as API Server
participant DB as Database
end
U->>UI: Click button
UI->>API: HTTP request
API->>DB: Query
DB-->>API: Results
API-->>UI: JSON response
UI-->>U: Render dataSequence Numbers
Enable automatic numbering on all messages.
sequenceDiagram
autonumber
participant A as Alice
participant B as Bob
A->>B: First message
B-->>A: Second message
A->>B: Third messageCreate and Destroy
Dynamically create or destroy participants during the sequence.
sequenceDiagram
participant A as Alice
A->>Bob: Hello
create participant C as Charlie
Bob->>C: Introduce Alice
destroy C
C->>Bob: GoodbyeActor Menus
Add links to participant menus for interactive diagrams.
sequenceDiagram
participant A as Alice
participant B as Bob
link A: Dashboard @ https://example.com/dashboard
link B: Profile @ https://example.com/profile
A->>B: Check your profileComplete Example
sequenceDiagram
autonumber
actor U as User
participant FE as Frontend
participant GW as API Gateway
participant Auth as Auth Service
participant DB as Database
U->>FE: Submit login form
FE->>+GW: POST /auth/login
GW->>+Auth: Validate credentials
alt Valid credentials
Auth->>+DB: Lookup user
DB-->>-Auth: User record
Auth-->>-GW: JWT token
GW-->>-FE: 200 OK + token
FE-->>U: Redirect to dashboard
else Invalid credentials
Auth-->>GW: Authentication failed
GW-->>FE: 401 Unauthorized
FE-->>U: Show error message
end