---
name: mermaid-diagrams
description: Mermaid diagram patterns cho documentation. Use for flowcharts, sequence diagrams, class diagrams, ER diagrams, system architecture, hoặc khi cần visualize processes và relationships trong markdown.
compatibility: "Mermaid JS, GitHub Markdown, VS Code"
metadata:
  author: Velik Ho
  version: "1.0"
  references: "mermaid.js.org"
---

# Mermaid Diagrams / Sơ đồ Mermaid

## When to Use This Skill / Khi Nào Sử Dụng

Use this skill when:
- Visualizing processes, workflows, decision trees / Tạo sơ đồ quy trình, cây quyết định
- Documenting API flows, service interactions / Tài liệu API flows, tương tác giữa services
- Designing database schemas / Thiết kế database schema
- Creating system architecture diagrams / Tạo sơ đồ kiến trúc hệ thống
- Project timelines and planning / Timeline dự án

## Quick Reference / Tham Chiếu Nhanh

| Loại Sơ đồ | Sử dụng cho | Keyword |
|------------|-------------|---------|
| **Flowchart** | Quy trình, cây quyết định | `flowchart TD/LR` |
| **Sequence** | API flows, request/response | `sequenceDiagram` |
| **Class** | Code structure, patterns | `classDiagram` |
| **Graph** | System architecture | `graph TD/LR` |
| **ER** | Database schema | `erDiagram` |
| **Gantt** | Timeline, scheduling | `gantt` |
| **C4** | System context | `C4Context` |

---

## Core Patterns / Mẫu Chính

### 1. Flowchart

```mermaid
flowchart TD
  Start([Start]) --> Input[Get Input]
  Input --> Check{Valid?}
  Check -->|Yes| Process[Process Data]
  Check -->|No| Error[Show Error]
  Process --> Output[Return Result]
  Output --> End([End])
  Error --> End

  style Start fill:#2C3E50,color:#ECF0F1,stroke:#34495E,stroke-width:3px
  style End fill:#27AE60,color:#ECF0F1,stroke:#229954,stroke-width:3px
  style Check fill:#E67E22,color:#ECF0F1,stroke:#D35400,stroke-width:2px
  style Error fill:#C0392B,color:#ECF0F1,stroke:#A93226,stroke-width:2px
  style Process fill:#8E44AD,color:#ECF0F1,stroke:#7D3C98,stroke-width:2px
```

**Subgraphs for grouping:**

```mermaid
flowchart LR
  A[Request] --> B{Auth?}
  B -->|No| C[401]
  B -->|Yes| D[Process]

  subgraph Processing["Request Processing"]
    D --> E[Validate]
    E --> F[Execute]
  end

  F --> G[200 OK]
```

### 2. Sequence Diagram

```mermaid
sequenceDiagram
  participant Client
  participant API
  participant Service
  participant DB

  Client->>API: POST /login
  API->>Service: authenticate(credentials)
  Service->>DB: findUser(email)
  DB-->>Service: user
  Service-->>API: JWT token
  API-->>Client: 200 OK {token}
```

**With Alt/Opt blocks:**

```mermaid
sequenceDiagram
  Client->>API: GET /users/:id
  API->>Cache: get(key)

  alt Cache Hit
    Cache-->>API: cached data
  else Cache Miss
    API->>DB: SELECT * FROM users
    DB-->>API: user data
    API->>Cache: set(key, data, ttl)
  end
  
  API-->>Client: 200 OK
```

### 3. Class Diagram

```mermaid
%%{init: {'theme':'dark'}}%%
classDiagram
  class BaseRepository {
    #prisma: PrismaClient
    +findById(id: string) T
    +create(data: CreateDto) T
    +delete(id: string) void
  }

  class UserRepository {
    +findByEmail(email: string) User
  }

  BaseRepository <|-- UserRepository
```

### 4. ER Diagram

```mermaid
%%{init: {'theme':'dark'}}%%
erDiagram
  User ||--o{ Session : has
  User ||--o{ UserRole : has
  Role ||--o{ UserRole : has

  User {
    string id PK
    string email UK
    string passwordHash
    datetime createdAt
  }

  Session {
    string id PK
    string userId FK
    string token UK
    datetime expiresAt
  }
```

### 5. System Architecture (Graph)

```mermaid
graph TD
  Client[Web Client] --> Gateway[Traefik]
  Gateway --> Auth[Auth Service]
  Gateway --> User[User Service]

  Auth --> DB[(PostgreSQL)]
  User --> DB
  Auth --> Cache[(Redis)]

  style Gateway fill:#3498DB,color:#ECF0F1,stroke:#2980B9,stroke-width:3px
  style DB fill:#34495E,color:#ECF0F1,stroke:#2C3E50,stroke-width:2px
```

---

## Dark Color Palette / Bảng Màu Tối

**LUÔN sử dụng bảng màu tối cho consistency:**

| Màu | Hex | Sử dụng cho | Border |
|-----|-----|-------------|--------|
| **Primary** | `#2C3E50` | Start, main nodes | `#34495E` |
| **Data** | `#34495E` | Database, Cache | `#2C3E50` |
| **Success** | `#27AE60` | End, confirmation | `#229954` |
| **Warning** | `#E67E22` | Decision nodes | `#D35400` |
| **Error** | `#C0392B` | Error, failure | `#A93226` |
| **Process** | `#8E44AD` | Processing steps | `#7D3C98` |
| **Info** | `#3498DB` | Gateway, API | `#2980B9` |
| **Neutral** | `#7F8C8D` | Neutral nodes | `#5D6D7E` |

**Màu chữ:** `#ECF0F1` (light text for contrast)

### Style Templates

```markdown
<!-- Start/End -->
style Start fill:#2C3E50,color:#ECF0F1,stroke:#34495E,stroke-width:3px
style End fill:#27AE60,color:#ECF0F1,stroke:#229954,stroke-width:3px

<!-- Decision -->
style Decision fill:#E67E22,color:#ECF0F1,stroke:#D35400,stroke-width:2px

<!-- Error -->
style Error fill:#C0392B,color:#ECF0F1,stroke:#A93226,stroke-width:2px

<!-- Processing -->
style Process fill:#8E44AD,color:#ECF0F1,stroke:#7D3C98,stroke-width:2px

<!-- Database/Cache -->
style DB fill:#34495E,color:#ECF0F1,stroke:#2C3E50,stroke-width:2px

<!-- Gateway/API -->
style Gateway fill:#3498DB,color:#ECF0F1,stroke:#2980B9,stroke-width:3px
```

---

## Common Mistakes / Lỗi Thường Gặp

### 1. Arrow Syntax

```markdown
❌ SAI: A -> B     (single dash)
✅ ĐÚNG: A --> B  (double dash)
```

### 2. Missing Line Break

```markdown
❌ SAI: flowchart TD A --> B
✅ ĐÚNG:
flowchart TD
  A --> B
```

### 3. Duplicate Node IDs

```markdown
❌ SAI:
graph TD
  A[Start]
  A[Process]  <!-- Trùng ID -->

✅ ĐÚNG:
graph TD
  A[Start]
  B[Process]
```

### 4. Style Syntax

```markdown
❌ SAI: style Node fill:#2C3E50  <!-- Thiếu dấu phẩy -->
✅ ĐÚNG: style Node fill:#2C3E50,color:#ECF0F1
```

### 5. Subgraph Format

```markdown
❌ SAI: subgraph "My Group"
✅ ĐÚNG: subgraph MyGroup["My Group"]
```

### 6. Special Characters in Labels

```markdown
❌ SAI: A[Label (with parens)]  <!-- Có thể gây lỗi -->
✅ ĐÚNG: A["Label (with parens)"]  <!-- Quote labels có ký tự đặc biệt -->
```

---

## Visual Indicators / Emoji Indicators

| Emoji | Meaning | Use in |
|-------|---------|--------|
| 🚀 | Start/Launch | Start nodes |
| ✅ | Success | Success/End nodes |
| ❌ | Error/Failed | Error nodes |
| ⚠️ | Warning | Decision nodes |
| 🔐 | Security/Auth | Auth steps |
| 💾 | Database | Data nodes |
| ⚙️ | Processing | Process nodes |
| 🌐 | API/Network | External calls |

**Example:**

```mermaid
flowchart TD
  Start(["🚀 Bắt đầu"]) --> Auth{"🔐 Xác thực?"}
  Auth -->|"Có"| Process["⚙️ Xử lý"]
  Auth -->|"Không"| Error["❌ Lỗi"]
  Process --> DB[("💾 Database")]
  DB --> Success["✅ Thành công"]
```

---

## Diagram Selection Matrix / Ma Trận Chọn Sơ đồ

| Mục đích | Loại sơ đồ |
|----------|------------|
| Quy trình, workflow | **Flowchart** |
| API calls, request/response | **Sequence** |
| Code structure, OOP | **Class** |
| System architecture | **Graph** |
| Database schema | **ER Diagram** |
| Project timeline | **Gantt** |
| High-level context | **C4** |

---

## Testing Diagrams / Kiểm Tra

```bash
# Install mermaid-cli
npm install -g @mermaid-js/mermaid-cli

# Test render (SVG)
mmdc -i your-doc.md -o test.svg

# Render PNG với dark theme
mmdc -i your-doc.md -o test.png -b black -t dark -s 3
```

---

## Troubleshooting Checklist

- [ ] Có xuống dòng sau `flowchart TD`?
- [ ] Arrow sử dụng `-->` không phải `->`?
- [ ] Không có Node ID trùng lặp?
- [ ] Style có dấu phẩy giữa các thuộc tính?
- [ ] Subgraph format: `subgraph ID["Label"]`?
- [ ] Hex color có dấu `#`?
- [ ] Labels đặc biệt được quote?

---

## Resources / Tài Nguyên

- [Mermaid Official Documentation](https://mermaid.js.org/)
- [Mermaid Live Editor](https://mermaid.live/)
- [Mermaid CheatSheet](https://jojozhuang.github.io/tutorial/mermaid-cheat-sheet/)
- [Documentation Skill](../documentation/SKILL.md) - Documentation guidelines
