loom-diagramming
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseDiagramming
图表绘制
Overview
概述
Create clear, maintainable technical diagrams using Mermaid syntax. This skill covers architecture diagrams, sequence diagrams, entity-relationship diagrams, flowcharts, and state diagrams for documenting software systems.
使用Mermaid语法创建清晰、可维护的技术图表。本技能涵盖用于软件系统文档的架构图、序列图、实体关系图、流程图和状态图。
Instructions
操作指南
1. Choose the Right Diagram Type
1. 选择合适的图表类型
| Diagram Type | Use When |
|---|---|
| Architecture/C4 | Showing system structure and components |
| Sequence | Showing interactions over time |
| ERD | Showing data models and relationships |
| Flowchart | Showing decision logic and processes |
| State | Showing state transitions |
| 图表类型 | 使用场景 |
|---|---|
| Architecture/C4 | 展示系统结构和组件 |
| Sequence | 展示随时间变化的交互过程 |
| ERD | 展示数据模型和关系 |
| Flowchart | 展示决策逻辑和流程 |
| State | 展示状态转换 |
2. Mermaid Syntax Patterns
2. Mermaid语法模式
Direction Control:
- - Top to bottom
flowchart TB - - Left to right
flowchart LR - - Automatic top-down layout
sequenceDiagram
Node Shapes:
- - Process
[Rectangle] - - Start/end
(Rounded) - - Decision
{Diamond} - - Storage
[(Database)] - - Connection point
((Circle))
Arrow Types:
- Solid line (flow)
--> - Dotted line (optional)
-.-> - Thick line (message)
->> - Dotted message
-->> - Extra thick (emphasis)
==>
Subgraphs for Grouping:
mermaid
flowchart TB
subgraph "Subsystem Name"
A --> B
end方向控制:
- - 从上到下
flowchart TB - - 从左到右
flowchart LR - - 自动从上到下布局
sequenceDiagram
节点形状:
- - 流程
[Rectangle] - - 开始/结束
(Rounded) - - 决策
{Diamond} - - 存储
[(Database)] - - 连接点
((Circle))
箭头类型:
- 实线(流程)
--> - 虚线(可选)
-.-> - 粗线(消息)
->> - 虚线消息
-->> - 特粗线(强调)
==>
用于分组的子图:
mermaid
flowchart TB
subgraph "Subsystem Name"
A --> B
end3. General Principles
3. 通用原则
- Keep diagrams focused on one concept
- Use consistent naming conventions
- Add descriptive labels to relationships
- Limit complexity (split large diagrams)
- Use comments for documentation
- 每个图表聚焦一个核心概念
- 使用一致的命名规范
- 为关系添加描述性标签
- 控制复杂度(拆分大型图表)
- 使用注释进行文档说明
Best Practices
最佳实践
- Simplicity: One diagram, one concept
- Consistency: Same naming across related diagrams
- Readability: Left-to-right or top-to-bottom flow
- Labels: Always label relationships and transitions
- Context: Include a title and brief description
- 简洁性:一个图表对应一个概念
- 一致性:相关图表使用相同命名
- 可读性:采用从左到右或从上到下的流向
- 标签:始终为关系和转换添加标签
- 上下文:包含标题和简要描述
Examples
示例
Architecture Diagrams (C4 Model)
架构图(C4模型)
The C4 model provides hierarchical system visualization:
- Level 1 (Context): System in its environment, external dependencies
- Level 2 (Container): High-level technical building blocks (apps, databases, services)
- Level 3 (Component): Internal structure of containers (classes, modules)
Use C4 for architecture documentation, onboarding new developers, and stakeholder communication.
C4模型提供分层的系统可视化:
- Level 1(上下文):系统及其运行环境、外部依赖
- Level 2(容器):高层技术构建块(应用、数据库、服务)
- Level 3(组件):容器的内部结构(类、模块)
C4模型适用于架构文档、新开发者入职培训以及与利益相关者沟通。
Context Diagram (Level 1)
上下文图(Level 1)
mermaid
C4Context
title System Context Diagram for E-Commerce Platform
Person(customer, "Customer", "A user who purchases products")
Person(admin, "Admin", "Manages products and orders")
System(ecommerce, "E-Commerce Platform", "Allows customers to browse and purchase products")
System_Ext(payment, "Payment Gateway", "Handles payment processing")
System_Ext(shipping, "Shipping Provider", "Handles order fulfillment")
System_Ext(email, "Email Service", "Sends notifications")
Rel(customer, ecommerce, "Browses, purchases")
Rel(admin, ecommerce, "Manages")
Rel(ecommerce, payment, "Processes payments")
Rel(ecommerce, shipping, "Creates shipments")
Rel(ecommerce, email, "Sends emails")mermaid
C4Context
title System Context Diagram for E-Commerce Platform
Person(customer, "Customer", "A user who purchases products")
Person(admin, "Admin", "Manages products and orders")
System(ecommerce, "E-Commerce Platform", "Allows customers to browse and purchase products")
System_Ext(payment, "Payment Gateway", "Handles payment processing")
System_Ext(shipping, "Shipping Provider", "Handles order fulfillment")
System_Ext(email, "Email Service", "Sends notifications")
Rel(customer, ecommerce, "Browses, purchases")
Rel(admin, ecommerce, "Manages")
Rel(ecommerce, payment, "Processes payments")
Rel(ecommerce, shipping, "Creates shipments")
Rel(ecommerce, email, "Sends emails")Container Diagram (Level 2)
容器图(Level 2)
mermaid
C4Container
title Container Diagram for E-Commerce Platform
Person(customer, "Customer")
Container_Boundary(ecommerce, "E-Commerce Platform") {
Container(web, "Web Application", "React", "Customer-facing UI")
Container(api, "API Gateway", "Node.js", "REST API")
Container(cart, "Cart Service", "Node.js", "Shopping cart management")
Container(catalog, "Catalog Service", "Python", "Product catalog")
Container(order, "Order Service", "Java", "Order processing")
ContainerDb(db, "Database", "PostgreSQL", "Stores all data")
ContainerQueue(queue, "Message Queue", "RabbitMQ", "Async messaging")
}
Rel(customer, web, "Uses", "HTTPS")
Rel(web, api, "Calls", "JSON/HTTPS")
Rel(api, cart, "Routes to")
Rel(api, catalog, "Routes to")
Rel(api, order, "Routes to")
Rel(cart, db, "Reads/writes")
Rel(catalog, db, "Reads")
Rel(order, db, "Reads/writes")
Rel(order, queue, "Publishes events")mermaid
C4Container
title Container Diagram for E-Commerce Platform
Person(customer, "Customer")
Container_Boundary(ecommerce, "E-Commerce Platform") {
Container(web, "Web Application", "React", "Customer-facing UI")
Container(api, "API Gateway", "Node.js", "REST API")
Container(cart, "Cart Service", "Node.js", "Shopping cart management")
Container(catalog, "Catalog Service", "Python", "Product catalog")
Container(order, "Order Service", "Java", "Order processing")
ContainerDb(db, "Database", "PostgreSQL", "Stores all data")
ContainerQueue(queue, "Message Queue", "RabbitMQ", "Async messaging")
}
Rel(customer, web, "Uses", "HTTPS")
Rel(web, api, "Calls", "JSON/HTTPS")
Rel(api, cart, "Routes to")
Rel(api, catalog, "Routes to")
Rel(api, order, "Routes to")
Rel(cart, db, "Reads/writes")
Rel(catalog, db, "Reads")
Rel(order, db, "Reads/writes")
Rel(order, queue, "Publishes events")Component Diagram (Level 3)
组件图(Level 3)
mermaid
flowchart TB
subgraph "Order Service"
controller[Order Controller]
service[Order Service]
repo[Order Repository]
validator[Order Validator]
publisher[Event Publisher]
end
subgraph "External"
db[(PostgreSQL)]
queue[RabbitMQ]
end
controller --> service
service --> validator
service --> repo
service --> publisher
repo --> db
publisher --> queuemermaid
flowchart TB
subgraph "Order Service"
controller[Order Controller]
service[Order Service]
repo[Order Repository]
validator[Order Validator]
publisher[Event Publisher]
end
subgraph "External"
db[(PostgreSQL)]
queue[RabbitMQ]
end
controller --> service
service --> validator
service --> repo
service --> publisher
repo --> db
publisher --> queueSequence Diagrams
序列图
Use for API flows, request/response cycles, distributed system interactions, and multi-service communication.
Key Patterns:
- - Define actors upfront
participant - - Add step numbers
autonumber - - Conditional flows
alt/else/end - - Repeated operations
loop/end - - Parallel operations
par/end - - Add explanatory notes
Note over A,B
适用于API流程、请求/响应周期、分布式系统交互以及多服务通信。
核心模式:
- - 预先定义参与者
participant - - 添加步骤编号
autonumber - - 条件流程
alt/else/end - - 重复操作
loop/end - - 并行操作
par/end - - 添加解释性注释
Note over A,B
Basic Request Flow
基础请求流程
mermaid
sequenceDiagram
autonumber
participant C as Client
participant G as API Gateway
participant A as Auth Service
participant S as Service
participant D as Database
C->>G: POST /api/resource
G->>A: Validate token
A-->>G: Token valid
G->>S: Forward request
S->>D: Query data
D-->>S: Return results
S-->>G: Response (200 OK)
G-->>C: Response with datamermaid
sequenceDiagram
autonumber
participant C as Client
participant G as API Gateway
participant A as Auth Service
participant S as Service
participant D as Database
C->>G: POST /api/resource
G->>A: Validate token
A-->>G: Token valid
G->>S: Forward request
S->>D: Query data
D-->>S: Return results
S-->>G: Response (200 OK)
G-->>C: Response with dataError Handling Flow
错误处理流程
mermaid
sequenceDiagram
participant C as Client
participant S as Service
participant D as Database
C->>S: POST /api/users
S->>S: Validate input
alt Validation fails
S-->>C: 400 Bad Request
else Validation passes
S->>D: INSERT user
alt Database error
D-->>S: Constraint violation
S-->>C: 409 Conflict
else Success
D-->>S: User created
S-->>C: 201 Created
end
endmermaid
sequenceDiagram
participant C as Client
participant S as Service
participant D as Database
C->>S: POST /api/users
S->>S: Validate input
alt Validation fails
S-->>C: 400 Bad Request
else Validation passes
S->>D: INSERT user
alt Database error
D-->>S: Constraint violation
S-->>C: 409 Conflict
else Success
D-->>S: User created
S-->>C: 201 Created
end
endAsync Processing
异步处理
mermaid
sequenceDiagram
participant C as Client
participant API as API
participant Q as Queue
participant W as Worker
participant N as Notification
C->>API: Submit job
API->>Q: Enqueue job
API-->>C: 202 Accepted (job ID)
Note over Q,W: Async processing
Q->>W: Dequeue job
W->>W: Process job
W->>N: Send notification
N-->>C: Job complete notificationmermaid
sequenceDiagram
participant C as Client
participant API as API
participant Q as Queue
participant W as Worker
participant N as Notification
C->>API: Submit job
API->>Q: Enqueue job
API-->>C: 202 Accepted (job ID)
Note over Q,W: Async processing
Q->>W: Dequeue job
W->>W: Process job
W->>N: Send notification
N-->>C: Job complete notificationAPI Authentication Flow
API认证流程
mermaid
sequenceDiagram
participant C as Client
participant API as API Gateway
participant Auth as Auth Service
participant Cache as Redis Cache
participant DB as User DB
C->>API: POST /login (credentials)
API->>Auth: Validate credentials
Auth->>DB: Query user
DB-->>Auth: User record
alt Valid credentials
Auth->>Auth: Generate JWT
Auth->>Cache: Store session
Cache-->>Auth: OK
Auth-->>API: Token + refresh token
API-->>C: 200 OK (tokens)
else Invalid credentials
Auth-->>API: Invalid credentials
API-->>C: 401 Unauthorized
endmermaid
sequenceDiagram
participant C as Client
participant API as API Gateway
participant Auth as Auth Service
participant Cache as Redis Cache
participant DB as User DB
C->>API: POST /login (credentials)
API->>Auth: Validate credentials
Auth->>DB: Query user
DB-->>Auth: User record
alt Valid credentials
Auth->>Auth: Generate JWT
Auth->>Cache: Store session
Cache-->>Auth: OK
Auth-->>API: Token + refresh token
API-->>C: 200 OK (tokens)
else Invalid credentials
Auth-->>API: Invalid credentials
API-->>C: 401 Unauthorized
endMicroservices Communication
微服务通信
mermaid
sequenceDiagram
participant U as User
participant API as API Gateway
participant O as Order Service
participant I as Inventory Service
participant P as Payment Service
participant Q as Message Queue
U->>API: POST /orders
API->>O: Create order
par Check inventory and process payment
O->>I: Check stock
I-->>O: Stock available
and
O->>P: Authorize payment
P-->>O: Payment authorized
end
O->>I: Reserve items
O->>P: Capture payment
alt Success
P-->>O: Payment captured
O->>Q: Publish OrderCreated event
O-->>API: Order created
API-->>U: 201 Created
else Payment failed
P-->>O: Payment failed
O->>I: Release reservation
O-->>API: Payment failed
API-->>U: 402 Payment Required
endmermaid
sequenceDiagram
participant U as User
participant API as API Gateway
participant O as Order Service
participant I as Inventory Service
participant P as Payment Service
participant Q as Message Queue
U->>API: POST /orders
API->>O: Create order
par Check inventory and process payment
O->>I: Check stock
I-->>O: Stock available
and
O->>P: Authorize payment
P-->>O: Payment authorized
end
O->>I: Reserve items
O->>P: Capture payment
alt Success
P-->>O: Payment captured
O->>Q: Publish OrderCreated event
O-->>API: Order created
API-->>U: 201 Created
else Payment failed
P-->>O: Payment failed
O->>I: Release reservation
O-->>API: Payment failed
API-->>U: 402 Payment Required
endEntity-Relationship Diagrams
实体关系图(ERD)
Use for database schema design, data model documentation, and relationship mapping.
适用于数据库架构设计、数据模型文档以及关系映射。
Basic ERD
基础ERD
mermaid
erDiagram
USER ||--o{ ORDER : places
USER {
uuid id PK
string email UK
string name
timestamp created_at
}
ORDER ||--|{ ORDER_ITEM : contains
ORDER {
uuid id PK
uuid user_id FK
decimal total
string status
timestamp created_at
}
ORDER_ITEM }|--|| PRODUCT : references
ORDER_ITEM {
uuid id PK
uuid order_id FK
uuid product_id FK
int quantity
decimal price
}
PRODUCT ||--o{ PRODUCT_CATEGORY : "belongs to"
PRODUCT {
uuid id PK
string name
text description
decimal price
int stock
}
CATEGORY ||--o{ PRODUCT_CATEGORY : contains
CATEGORY {
uuid id PK
string name
uuid parent_id FK
}
PRODUCT_CATEGORY {
uuid product_id PK,FK
uuid category_id PK,FK
}mermaid
erDiagram
USER ||--o{ ORDER : places
USER {
uuid id PK
string email UK
string name
timestamp created_at
}
ORDER ||--|{ ORDER_ITEM : contains
ORDER {
uuid id PK
uuid user_id FK
decimal total
string status
timestamp created_at
}
ORDER_ITEM }|--|| PRODUCT : references
ORDER_ITEM {
uuid id PK
uuid order_id FK
uuid product_id FK
int quantity
decimal price
}
PRODUCT ||--o{ PRODUCT_CATEGORY : "belongs to"
PRODUCT {
uuid id PK
string name
text description
decimal price
int stock
}
CATEGORY ||--o{ PRODUCT_CATEGORY : contains
CATEGORY {
uuid id PK
string name
uuid parent_id FK
}
PRODUCT_CATEGORY {
uuid product_id PK,FK
uuid category_id PK,FK
}ERD with Relationships Explained
带关系说明的ERD
mermaid
erDiagram
CUSTOMER ||--o{ ORDER : "places (1:N)"
ORDER ||--|{ LINE_ITEM : "contains (1:N, required)"
PRODUCT ||--o{ LINE_ITEM : "appears in (1:N)"
CUSTOMER }|--|| ADDRESS : "has billing (N:1, required)"
CUSTOMER }o--o{ ADDRESS : "has shipping (N:N)"Relationship notation:
- exactly one
|| - zero or one
o| - one or more
}| - zero or more
}o
mermaid
erDiagram
CUSTOMER ||--o{ ORDER : "places (1:N)"
ORDER ||--|{ LINE_ITEM : "contains (1:N, required)"
PRODUCT ||--o{ LINE_ITEM : "appears in (1:N)"
CUSTOMER }|--|| ADDRESS : "has billing (N:1, required)"
CUSTOMER }o--o{ ADDRESS : "has shipping (N:N)"关系符号说明:
- 恰好一个
|| - 零或一个
o| - 一个或多个
}| - 零或多个
}o
Flowcharts
流程图
Decision Logic
决策逻辑
mermaid
flowchart TD
A[Start: User Login] --> B{Valid credentials?}
B -->|Yes| C{2FA enabled?}
B -->|No| D[Show error message]
D --> A
C -->|Yes| E[Send 2FA code]
E --> F{Code valid?}
F -->|Yes| G[Create session]
F -->|No| H{Attempts < 3?}
H -->|Yes| E
H -->|No| I[Lock account]
C -->|No| G
G --> J[Redirect to dashboard]
J --> K[End]
I --> Kmermaid
flowchart TD
A[Start: User Login] --> B{Valid credentials?}
B -->|Yes| C{2FA enabled?}
B -->|No| D[Show error message]
D --> A
C -->|Yes| E[Send 2FA code]
E --> F{Code valid?}
F -->|Yes| G[Create session]
F -->|No| H{Attempts < 3?}
H -->|Yes| E
H -->|No| I[Lock account]
C -->|No| G
G --> J[Redirect to dashboard]
J --> K[End]
I --> KProcess Flow
流程流
mermaid
flowchart LR
subgraph "CI Pipeline"
A[Push Code] --> B[Run Tests]
B --> C{Tests Pass?}
C -->|Yes| D[Build Image]
C -->|No| E[Notify Developer]
D --> F[Push to Registry]
end
subgraph "CD Pipeline"
F --> G[Deploy to Staging]
G --> H[Run E2E Tests]
H --> I{Tests Pass?}
I -->|Yes| J[Deploy to Production]
I -->|No| K[Rollback]
endmermaid
flowchart LR
subgraph "CI Pipeline"
A[Push Code] --> B[Run Tests]
B --> C{Tests Pass?}
C -->|Yes| D[Build Image]
C -->|No| E[Notify Developer]
D --> F[Push to Registry]
end
subgraph "CD Pipeline"
F --> G[Deploy to Staging]
G --> H[Run E2E Tests]
H --> I{Tests Pass?}
I -->|Yes| J[Deploy to Production]
I -->|No| K[Rollback]
endState Diagrams
状态图
Order State Machine
订单状态机
mermaid
stateDiagram-v2
[*] --> Draft: Create order
Draft --> Pending: Submit
Draft --> Cancelled: Cancel
Pending --> Confirmed: Payment received
Pending --> Cancelled: Payment failed
Pending --> Cancelled: Timeout (24h)
Confirmed --> Processing: Begin fulfillment
Confirmed --> Cancelled: Customer cancel
Processing --> Shipped: Ship order
Processing --> Cancelled: Out of stock
Shipped --> Delivered: Delivery confirmed
Shipped --> Returned: Return initiated
Delivered --> Returned: Return requested
Delivered --> [*]: Complete
Returned --> Refunded: Process refund
Refunded --> [*]: Complete
Cancelled --> [*]: Completemermaid
stateDiagram-v2
[*] --> Draft: Create order
Draft --> Pending: Submit
Draft --> Cancelled: Cancel
Pending --> Confirmed: Payment received
Pending --> Cancelled: Payment failed
Pending --> Cancelled: Timeout (24h)
Confirmed --> Processing: Begin fulfillment
Confirmed --> Cancelled: Customer cancel
Processing --> Shipped: Ship order
Processing --> Cancelled: Out of stock
Shipped --> Delivered: Delivery confirmed
Shipped --> Returned: Return initiated
Delivered --> Returned: Return requested
Delivered --> [*]: Complete
Returned --> Refunded: Process refund
Refunded --> [*]: Complete
Cancelled --> [*]: CompleteConnection State Machine
连接状态机
mermaid
stateDiagram-v2
[*] --> Disconnected
Disconnected --> Connecting: connect()
Connecting --> Connected: success
Connecting --> Disconnected: failure
Connected --> Disconnected: disconnect()
Connected --> Reconnecting: connection lost
Reconnecting --> Connected: success
Reconnecting --> Disconnected: max retries
note right of Reconnecting
Exponential backoff
Max 5 retries
end notemermaid
stateDiagram-v2
[*] --> Disconnected
Disconnected --> Connecting: connect()
Connecting --> Connected: success
Connecting --> Disconnected: failure
Connected --> Disconnected: disconnect()
Connected --> Reconnecting: connection lost
Reconnecting --> Connected: success
Reconnecting --> Disconnected: max retries
note right of Reconnecting
Exponential backoff
Max 5 retries
end noteClass Diagrams
类图
mermaid
classDiagram
class Repository~T~ {
<<interface>>
+findById(id: string) T
+findAll() List~T~
+save(entity: T) T
+delete(id: string) void
}
class UserRepository {
-db: Database
+findById(id: string) User
+findAll() List~User~
+save(entity: User) User
+delete(id: string) void
+findByEmail(email: string) User
}
class User {
+id: string
+email: string
+name: string
+createdAt: Date
+validate() boolean
}
Repository~T~ <|.. UserRepository
UserRepository --> Usermermaid
classDiagram
class Repository~T~ {
<<interface>>
+findById(id: string) T
+findAll() List~T~
+save(entity: T) T
+delete(id: string) void
}
class UserRepository {
-db: Database
+findById(id: string) User
+findAll() List~User~
+save(entity: User) User
+delete(id: string) void
+findByEmail(email: string) User
}
class User {
+id: string
+email: string
+name: string
+createdAt: Date
+validate() boolean
}
Repository~T~ <|.. UserRepository
UserRepository --> User