Diagrams with Mermaid
This comprehensive guide demonstrates how to create diagrams in our documentation using the Mermaid library, from basic usage to advanced techniques.
Interactive Diagrams
All Mermaid diagrams are now interactive! Click on any diagram to open it in a fullscreen popup view where you can zoom in/out and download it as an SVG file.
Getting Started with Diagrams
Mermaid is a JavaScript-based diagramming and charting tool that renders Markdown-inspired text definitions to create diagrams dynamically.
Basic Syntax
To create a diagram, use the Mermaid code block syntax:
Flowchart Diagrams
Flowcharts are the most common diagram type and great for visualizing processes.
Basic Top-Down Flowchart
graph TD
A[Start] --> B{Is it working?}
B -->|Yes| C[Great!]
B -->|No| D[Debug]
D --> B Code:
Left-to-Right Flowchart
graph LR
A[Authentication] --> B[Authorization]
B --> C[Access Control]
B --> D[User Permissions]
C --> E[Resource Access]
D --> E Code:
graph LR
A[Authentication] --> B[Authorization]
B --> C[Access Control]
B --> D[User Permissions]
C --> E[Resource Access]
D --> E
Node Shapes and Styles
graph TD
A[Rectangle] --> B(Rounded Rectangle)
A --> C([Stadium Shape])
A --> D[[Subroutine]]
A --> E[(Database)]
A --> F((Circle))
A --> G>Asymmetric]
A --> H{Diamond/Decision}
A --> I{{ Hexagon }}
A --> J[/Parallelogram/]
A --> K[\Parallelogram alt\]
A --> L[/Trapezoid\]
A --> M[\Trapezoid alt/] Code:
graph TD
A[Rectangle] --> B(Rounded Rectangle)
A --> C([Stadium Shape])
A --> D[[Subroutine]]
A --> E[(Database)]
A --> F((Circle))
A --> G>Asymmetric]
A --> H{Diamond/Decision}
A --> I{{ Hexagon }}
A --> J[/Parallelogram/]
A --> K[\Parallelogram alt\]
A --> L[/Trapezoid\]
A --> M[\Trapezoid alt/]
Advanced Flowchart with Subgraphs
graph TB
subgraph "Frontend System"
A[Web Client] --> B[UI Components]
B --> C[State Management]
end
subgraph "Backend System"
D[API Gateway] --> E[Authentication]
D --> F[Business Logic]
F --> G[(Database)]
end
A --> D
C --> D
style Frontend fill:#f9f9f9,stroke:#888,stroke-width:2px
style Backend fill:#f0f0f0,stroke:#888,stroke-width:2px Code:
graph TB
subgraph "Frontend System"
A[Web Client] --> B[UI Components]
B --> C[State Management]
end
subgraph "Backend System"
D[API Gateway] --> E[Authentication]
D --> F[Business Logic]
F --> G[(Database)]
end
A --> D
C --> D
style Frontend fill:#f9f9f9,stroke:#888,stroke-width:2px
style Backend fill:#f0f0f0,stroke:#888,stroke-width:2px
Sequence Diagrams
Sequence diagrams show process flow between actors or systems over time.
Basic Sequence Diagram
sequenceDiagram
participant User
participant System
User->>System: Request Data
System->>Database: Query
Database-->>System: Return Results
System-->>User: Display Data Code:
sequenceDiagram
participant User
participant System
User->>System: Request Data
System->>Database: Query
Database-->>System: Return Results
System-->>User: Display Data
Advanced Sequence Diagram with Activation Bars and Notes
sequenceDiagram
actor Client
participant API
participant Auth
participant DB
Client->>+API: POST /login
Note over Client,API: Authentication request
API->>+Auth: Validate credentials
Auth->>+DB: Query user
DB-->>-Auth: Return user data
alt Valid credentials
Auth-->>-API: Authentication successful
API-->>-Client: 200 OK + JWT Token
else Invalid credentials
Auth-->>-API: Authentication failed
API-->>-Client: 401 Unauthorized
end
Note right of Client: User receives response Code:
sequenceDiagram
actor Client
participant API
participant Auth
participant DB
Client->>+API: POST /login
Note over Client,API: Authentication request
API->>+Auth: Validate credentials
Auth->>+DB: Query user
DB-->>-Auth: Return user data
alt Valid credentials
Auth-->>-API: Authentication successful
API-->>-Client: 200 OK + JWT Token
else Invalid credentials
Auth-->>-API: Authentication failed
API-->>-Client: 401 Unauthorized
end
Note right of Client: User receives response
Class Diagrams
Class diagrams show the structure of object-oriented systems.
Basic Class Diagram
classDiagram
class User {
+String username
+String password
+login()
+logout()
}
class Admin {
+deleteUser()
+createUser()
}
User <|-- Admin Code:
classDiagram
class User {
+String username
+String password
+login()
+logout()
}
class Admin {
+deleteUser()
+createUser()
}
User <|-- Admin
Advanced Class Diagram with Relationships
classDiagram
class Entity {
<<abstract>>
+int id
+DateTime createdAt
+bool isActive
+save()
+delete()
}
class User {
+String email
+String passwordHash
+String role
-String[] permissions
+login()
+logout()
+resetPassword()
}
class Product {
+String name
+String description
+float price
+int inventory
+addToCart()
+updateInventory()
}
class Order {
+int orderNumber
+DateTime orderDate
+String status
+float total
+process()
+cancel()
+refund()
}
Entity <|-- User
Entity <|-- Product
Entity <|-- Order
User "1" --> "*" Order : places
Order "*" o-- "*" Product : contains
note for User "Stores user authentication and authorization data"
note for Order "Tracks customer purchases" Code:
classDiagram
class Entity {
<<abstract>>
+int id
+DateTime createdAt
+bool isActive
+save()
+delete()
}
class User {
+String email
+String passwordHash
+String role
-String[] permissions
+login()
+logout()
+resetPassword()
}
class Product {
+String name
+String description
+float price
+int inventory
+addToCart()
+updateInventory()
}
class Order {
+int orderNumber
+DateTime orderDate
+String status
+float total
+process()
+cancel()
+refund()
}
Entity <|-- User
Entity <|-- Product
Entity <|-- Order
User "1" --> "*" Order : places
Order "*" o-- "*" Product : contains
note for User "Stores user authentication and authorization data"
note for Order "Tracks customer purchases"
Gantt Charts
Gantt charts are useful for project planning and tracking.
Basic Gantt Chart
gantt
title Project Timeline
dateFormat YYYY-MM-DD
section Planning
Research :done, des1, 2023-01-01, 2023-01-15
Create Plan :active, des2, 2023-01-16, 2023-01-25
section Development
Implement : des3, 2023-01-26, 2023-02-15
Test : des4, 2023-02-16, 2023-02-25
section Deployment
Deploy : des5, 2023-02-26, 2023-03-01 Code:
gantt
title Project Timeline
dateFormat YYYY-MM-DD
section Planning
Research :done, des1, 2023-01-01, 2023-01-15
Create Plan :active, des2, 2023-01-16, 2023-01-25
section Development
Implement : des3, 2023-01-26, 2023-02-15
Test : des4, 2023-02-16, 2023-02-25
section Deployment
Deploy : des5, 2023-02-26, 2023-03-01
Advanced Gantt Chart with Dependencies
gantt
title Game Development Sprint
dateFormat YYYY-MM-DD
axisFormat %m/%d
excludes weekends
section Design
Character Concepts :done, des1, 2023-06-01, 2023-06-10
Environment Art :active, des2, 2023-06-05, 2023-06-20
UI/UX Design :des3, 2023-06-15, 2023-06-30
section Programming
Core Engine Work :done, dev1, 2023-06-01, 2023-06-25
Game Mechanics :after dev1, dev2, 2023-06-25, 2023-07-15
AI Implementation :dev3, 2023-07-01, 2023-07-20
section Testing
Alpha Testing :after dev2, test1, 2023-07-15, 2023-07-25
Beta Testing :after test1, test2, 2023-07-25, 2023-08-10
section Milestone
Alpha Release :milestone, m1, 2023-07-25, 0d
Beta Release :milestone, m2, 2023-08-10, 0d
Release Candidate :milestone, m3, 2023-08-25, 0d Code:
gantt
title Game Development Sprint
dateFormat YYYY-MM-DD
axisFormat %m/%d
excludes weekends
section Design
Character Concepts :done, des1, 2023-06-01, 2023-06-10
Environment Art :active, des2, 2023-06-05, 2023-06-20
UI/UX Design :des3, 2023-06-15, 2023-06-30
section Programming
Core Engine Work :done, dev1, 2023-06-01, 2023-06-25
Game Mechanics :after dev1, dev2, 2023-06-25, 2023-07-15
AI Implementation :dev3, 2023-07-01, 2023-07-20
section Testing
Alpha Testing :after dev2, test1, 2023-07-15, 2023-07-25
Beta Testing :after test1, test2, 2023-07-25, 2023-08-10
section Milestone
Alpha Release :milestone, m1, 2023-07-25, 0d
Beta Release :milestone, m2, 2023-08-10, 0d
Release Candidate :milestone, m3, 2023-08-25, 0d
Entity Relationship Diagrams (ERD)
ERDs show database relationships and are useful for database design.
erDiagram
PLAYER ||--o{ GAME_SESSION : participates
PLAYER {
int id PK
string username
string email
timestamp created_at
int experience
}
GAME_SESSION ||--|{ ACHIEVEMENT : awards
GAME_SESSION {
int id PK
int player_id FK
timestamp start_time
timestamp end_time
int score
string difficulty
}
ACHIEVEMENT {
int id PK
int session_id FK
string name
string description
int points
timestamp unlocked_at
}
PLAYER_INVENTORY }|--|| PLAYER : belongs_to
PLAYER_INVENTORY {
int id PK
int player_id FK
int capacity
timestamp last_updated
}
ITEM }o--o{ PLAYER_INVENTORY : contains
ITEM {
int id PK
string name
string type
int value
string rarity
} Code:
erDiagram
PLAYER ||--o{ GAME_SESSION : participates
PLAYER {
int id PK
string username
string email
timestamp created_at
int experience
}
GAME_SESSION ||--|{ ACHIEVEMENT : awards
GAME_SESSION {
int id PK
int player_id FK
timestamp start_time
timestamp end_time
int score
string difficulty
}
ACHIEVEMENT {
int id PK
int session_id FK
string name
string description
int points
timestamp unlocked_at
}
PLAYER_INVENTORY }|--|| PLAYER : belongs_to
PLAYER_INVENTORY {
int id PK
int player_id FK
int capacity
timestamp last_updated
}
ITEM }o--o{ PLAYER_INVENTORY : contains
ITEM {
int id PK
string name
string type
int value
string rarity
}
State Diagrams
State diagrams show the different states of a system and the transitions between them.
stateDiagram-v2
[*] --> Idle
Idle --> Processing: Start Task
Processing --> Success: Task Completed
Processing --> Error: Task Failed
Processing --> Cancelled: User Cancelled
Success --> Idle: Reset
Error --> Idle: Retry
Cancelled --> Idle: New Task
Idle --> [*]: Exit Application
state Processing {
[*] --> Validating
Validating --> Executing: Valid Input
Validating --> Invalid: Invalid Input
Executing --> Saving: Execution Complete
Saving --> [*]: Data Saved
Invalid --> [*]: Return Error
} Code:
stateDiagram-v2
[*] --> Idle
Idle --> Processing: Start Task
Processing --> Success: Task Completed
Processing --> Error: Task Failed
Processing --> Cancelled: User Cancelled
Success --> Idle: Reset
Error --> Idle: Retry
Cancelled --> Idle: New Task
Idle --> [*]: Exit Application
state Processing {
[*] --> Validating
Validating --> Executing: Valid Input
Validating --> Invalid: Invalid Input
Executing --> Saving: Execution Complete
Saving --> [*]: Data Saved
Invalid --> [*]: Return Error
}
Pie Charts
Pie charts are useful for showing distribution and percentages.
pie title Game Revenue Distribution
"In-App Purchases" : 42.7
"Premium Downloads" : 28.4
"Advertisements" : 18.6
"Partnerships" : 10.3 Code:
pie title Game Revenue Distribution
"In-App Purchases" : 42.7
"Premium Downloads" : 28.4
"Advertisements" : 18.6
"Partnerships" : 10.3
User Journey Diagrams
User journey diagrams help visualize a user's path through a system.
journey
title User Journey for Game Purchase
section Discovery
See Advertisement: 3: User
Visit Game Website: 5: User
View Game Trailer: 4: User
section Consideration
Read Reviews: 3: User
Check System Requirements: 4: User
Compare Editions: 5: User
section Purchase
Add to Cart: 5: User
Apply Discount Code: 4: User
Complete Payment: 3: User
section Post-Purchase
Download Game: 5: User
Play Tutorial: 4: User
Join Community: 3: User Code:
journey
title User Journey for Game Purchase
section Discovery
See Advertisement: 3: User
Visit Game Website: 5: User
View Game Trailer: 4: User
section Consideration
Read Reviews: 3: User
Check System Requirements: 4: User
Compare Editions: 5: User
section Purchase
Add to Cart: 5: User
Apply Discount Code: 4: User
Complete Payment: 3: User
section Post-Purchase
Download Game: 5: User
Play Tutorial: 4: User
Join Community: 3: User
Expert Tips and Best Practices
Diagram Complexity Management
- Break complex diagrams into multiple smaller ones when possible
- Use subgraphs to group related components
- Maintain consistent naming conventions
- Add comments in your Mermaid code for future reference
Styling Guidelines
- Use consistent colors for similar components across diagrams
- Maintain readable text with appropriate contrast
- Use appropriate node shapes to convey meaning (e.g., database icons for databases)
- Keep your diagrams visually balanced
Documentation Integration
- Add explanatory text around your diagrams
- Reference diagram components in your documentation
- Consider linking between related diagrams
Troubleshooting Common Issues
- Diagram not rendering: Ensure your syntax is correct and that you're using triple backticks with the 'mermaid' tag
- Text overlapping: Try adjusting your diagram layout or adding more space between elements
- Unexpected connections: Check your syntax for arrows and connections
- Styling not applied: Verify style syntax and check for typos in element IDs
Additional Resources
- Official Mermaid Documentation
- Mermaid Live Editor - Test your diagrams in real-time
- Mermaid Cheat Sheet
Remember that any diagram can be clicked to open in fullscreen mode for better viewing, and you can download diagrams as SVG files with proper attribution.