Diagramas
Markdown permite crear varios tipos de diagramas y flujos usando la sintaxis Mermaid, proporcionando expresión visual para tu documentación.
Introducción a Mermaid
Mermaid es una herramienta de generación de diagramas basada en texto que soporta múltiples tipos de diagramas:
- Diagrama de flujo
- Diagrama de secuencia
- Diagrama de Gantt
- Diagrama de clases
- Diagrama de estados
- Gráfico circular (Pie Chart)
- User Journey
- Git Graph
Sintaxis Básica
Diagrama de Flujo
markdown
```mermaid
flowchart TD
A[Inicio] --> B{¿Conectado?}
B -->|Sí| C[Mostrar Inicio]
B -->|No| D[Mostrar Login]
C --> E[Fin]
D --> F[Usuario Login]
F --> G{¿Login Exitoso?}
G -->|Sí| C
G -->|No| H[Mostrar Error]
H --> D
**Visualización Renderizada:**
```mermaid
flowchart TD
A[Inicio] --> B{¿Conectado?}
B -->|Sí| C[Mostrar Inicio]
B -->|No| D[Mostrar Login]
C --> E[Fin]
D --> F[Usuario Login]
F --> G{¿Login Exitoso?}
G -->|Sí| C
G -->|No| H[Mostrar Error]
H --> D
Diagrama de Secuencia
markdown
```mermaid
sequenceDiagram
participant Usuario
participant Frontend
participant Backend
participant BaseDeDatos
Usuario->>Frontend: Solicitud de Login
Frontend->>Backend: Validar Usuario
Backend->>BaseDeDatos: Consultar Datos de Usuario
BaseDeDatos-->>Backend: Retornar Info de Usuario
Backend-->>Frontend: Resultado de Validación
Frontend-->>Usuario: Respuesta de Login
**Visualización Renderizada:**
```mermaid
sequenceDiagram
participant Usuario
participant Frontend
participant Backend
participant BaseDeDatos
Usuario->>Frontend: Solicitud de Login
Frontend->>Backend: Validar Usuario
Backend->>BaseDeDatos: Consultar Datos de Usuario
BaseDeDatos-->>Backend: Retornar Info de Usuario
Backend-->>Frontend: Resultado de Validación
Frontend-->>Usuario: Respuesta de Login
Detalles del Diagrama de Flujo
Tipos de Nodo
markdown
```mermaid
flowchart LR
A[Nodo Rectangular]
B(Nodo Redondeado)
C((Nodo Circular))
D{Nodo Diamante}
E[[Subrutina]]
F[(Base de Datos)]
G>Nodo Etiqueta]
**Visualización Renderizada:**
```mermaid
flowchart LR
A[Nodo Rectangular]
B(Nodo Redondeado)
C((Nodo Circular))
D{Nodo Diamante}
E[[Subrutina]]
F[(Base de Datos)]
G>Nodo Etiqueta]
Tipos de Borde
markdown
```mermaid
flowchart TD
A --> B
C --- D
E -.-> F
G ==> H
I --o J
K --x L
**Visualización Renderizada:**
```mermaid
flowchart TD
A --> B
C --- D
E -.-> F
G ==> H
I --o J
K --x L
Control de Dirección
markdown
<!-- De arriba a abajo -->
```mermaid
flowchart TD
A --> B
mermaid
flowchart BT
A --> B
mermaid
flowchart LR
A --> B
mermaid
flowchart RL
A --> B
### Ejemplo de Diagrama de Flujo Complejo
```markdown
```mermaid
flowchart TD
Start([Inicio del Proyecto]) --> Analysis[Análisis de Requisitos]
Analysis --> Design[Diseño del Sistema]
Design --> Dev{Etapa de Desarrollo}
Dev --> Frontend[Desarrollo Frontend]
Dev --> Backend[Desarrollo Backend]
Dev --> BaseDeDatos[Diseño de Base de Datos]
Frontend --> FrontTest[Prueba Frontend]
Backend --> BackTest[Prueba Backend]
BaseDeDatos --> DataTest[Prueba de Datos]
FrontTest --> Integration[Prueba de Integración]
BackTest --> Integration
DataTest --> Integration
Integration --> Deploy{Preparación de Despliegue}
Deploy -->|Pasa| Production[Producción]
Deploy -->|Falla| Bug[Corregir Problemas]
Bug --> Integration
Production --> Monitor[Monitoreo]
Monitor --> End([Proyecto Completo])
style Start fill:#e1f5fe
style End fill:#e8f5e8
style Bug fill:#ffebee
**Visualización Renderizada:**
```mermaid
flowchart TD
Start([Inicio del Proyecto]) --> Analysis[Análisis de Requisitos]
Analysis --> Design[Diseño del Sistema]
Design --> Dev{Etapa de Desarrollo}
Dev --> Frontend[Desarrollo Frontend]
Dev --> Backend[Desarrollo Backend]
Dev --> BaseDeDatos[Diseño de Base de Datos]
Frontend --> FrontTest[Prueba Frontend]
Backend --> BackTest[Prueba Backend]
BaseDeDatos --> DataTest[Prueba de Datos]
FrontTest --> Integration[Prueba de Integración]
BackTest --> Integration
DataTest --> Integration
Integration --> Deploy{Preparación de Despliegue}
Deploy -->|Pasa| Production[Producción]
Deploy -->|Falla| Bug[Corregir Problemas]
Bug --> Integration
Production --> Monitor[Monitoreo]
Monitor --> End([Proyecto Completo])
style Start fill:#e1f5fe
style End fill:#e8f5e8
style Bug fill:#ffebee
Detalles del Diagrama de Secuencia
Sintaxis Básica
mermaid
sequenceDiagram
Alice->>Bob: Hello Bob, how are you?
Bob-->>Alice: I'm good, thanks!
Alice-)Bob: Goodbye!
Visualización Renderizada:
mermaid
sequenceDiagram
Alice->>Bob: Hello Bob, how are you?
Bob-->>Alice: I'm good, thanks!
Alice-)Bob: Goodbye!
Barras de Activación y Líneas de Vida
mermaid
sequenceDiagram
participant A as Client
participant B as Server
A->>+B: Request Data
Note right of B: Processing Request
B-->>-A: Return Data
A->>+B: Another Request
B->>+B: Internal Processing
B-->>-B: Processing Done
B-->>-A: Return Result
Visualización Renderizada:
mermaid
sequenceDiagram
participant A as Client
participant B as Server
A->>+B: Request Data
Note right of B: Processing Request
B-->>-A: Return Data
A->>+B: Another Request
B->>+B: Internal Processing
B-->>-B: Processing Done
B-->>-A: Return Result
Bucles y Condiciones
mermaid
sequenceDiagram
participant U as User
participant S as System
U->>S: Login Request
alt Username Exists
S->>S: Validate Password
alt Password Correct
S-->>U: Login Success
else Password Incorrect
S-->>U: Wrong Password
end
else Username Not Found
S-->>U: User Not Found
end
opt Remember Me
S->>S: Save Login State
end
Visualización Renderizada:
mermaid
sequenceDiagram
participant U as User
participant S as System
U->>S: Login Request
alt Username Exists
S->>S: Validate Password
alt Password Correct
S-->>U: Login Success
else Password Incorrect
S-->>U: Wrong Password
end
else Username Not Found
S-->>U: User Not Found
end
opt Remember Me
S->>S: Save Login State
end
Diagrama de Clase
mermaid
classDiagram
class Animal {
+String name
+int age
+eat()
+sleep()
}
class Dog {
+String breed
+bark()
+wagTail()
}
class Cat {
+String color
+meow()
+purr()
}
Animal <|-- Dog
Animal <|-- Cat
class Owner {
+String name
+feedPet()
}
Owner --> Animal : owns
Visualización Renderizada:
mermaid
classDiagram
class Animal {
+String name
+int age
+eat()
+sleep()
}
class Dog {
+String breed
+bark()
+wagTail()
}
class Cat {
+String color
+meow()
+purr()
}
Animal <|-- Dog
Animal <|-- Cat
class Owner {
+String name
+feedPet()
}
Owner --> Animal : owns
Diagrama de Estado
mermaid
stateDiagram-v2
[*] --> Idle
Idle --> Running : Start
Running --> Paused : Pause
Running --> Finished : End
Paused --> Running : Resume
Paused --> Stopped : Stop
Stopped --> Idle : Reset
Finished --> Idle : Reset
Finished --> [*]
state Running {
[*] --> Init
Init --> Processing
Processing --> Validate
Validate --> [*]
}
Visualización Renderizada:
mermaid
stateDiagram-v2
[*] --> Idle
Idle --> Running : Start
Running --> Paused : Pause
Running --> Finished : End
Paused --> Running : Resume
Paused --> Stopped : Stop
Stopped --> Idle : Reset
Finished --> Idle : Reset
Finished --> [*]
state Running {
[*] --> Init
Init --> Processing
Processing --> Validate
Validate --> [*]
}
Diagrama de Gantt
mermaid
gantt
title Project Development Timeline
dateFormat YYYY-MM-DD
section Requirement Analysis
Requirement Collection :done, des1, 2024-01-01,2024-01-05
Requirement Analysis :done, des2, after des1, 5d
Requirement Review :done, des3, after des2, 2d
section Design Phase
System Design :active, design1, 2024-01-12, 7d
UI Design : design2, after design1, 5d
Database Design : design3, after design1, 3d
section Development Phase
Frontend Development : dev1, after design2, 10d
Backend Development : dev2, after design3, 12d
Testing : test1, after dev1, 5d
Gráfico Circular
mermaid
pie title Website Traffic Sources
"Search Engine" : 45
"Social Media" : 25
"Direct" : 20
"Email Marketing" : 7
"Other" : 3
Viaje del Usuario
mermaid
journey
title User Shopping Journey
section Discovery
Visit Homepage: 3: User
Browse Products: 4: User
Search Products: 4: User
section Consideration
View Details: 4: User
Compare Prices: 3: User
Read Reviews: 5: User
section Purchase
Add to Cart: 4: User
Checkout: 3: User
Pay: 2: User
section Use
Receive Product: 5: User
Use Product: 4: User
Write Review: 4: User
Gráfico de Git
mermaid
gitgraph
commit id: "Initial Commit"
commit id: "Add User Module"
branch feature/auth
commit id: "Add Login Feature"
commit id: "Add Register Feature"
checkout main
commit id: "Fix Home Bug"
merge feature/auth
commit id: "v1.0 Release"
branch hotfix
commit id: "Urgent Fix"
checkout main
merge hotfix
commit id: "v1.0.1 Release"
Escenarios Reales
Diagrama de Arquitectura del Sistema
mermaid
flowchart TB
subgraph "User Layer"
Web[Web Browser]
Mobile[Mobile App]
API[API Client]
end
subgraph "Gateway Layer"
Gateway[API Gateway]
Auth[Auth Service]
end
subgraph "Service Layer"
UserService[User Service]
OrderService[Order Service]
PaymentService[Payment Service]
NotificationService[Notification Service]
end
subgraph "Data Layer"
UserDB[(User DB)]
OrderDB[(Order DB)]
Cache[(Redis Cache)]
Queue[Message Queue]
end
Web --> Gateway
Mobile --> Gateway
API --> Gateway
Gateway --> Auth
Gateway --> UserService
Gateway --> OrderService
Gateway --> PaymentService
UserService --> UserDB
OrderService --> OrderDB
PaymentService --> Queue
NotificationService --> Queue
UserService --> Cache
OrderService --> Cache
style Gateway fill:#e1f5fe
style Auth fill:#fff3e0
style Cache fill:#f3e5f5
Flujo de Llamadas a la API
mermaid
sequenceDiagram
participant C as Client
participant G as API Gateway
participant A as Auth Service
participant U as User Service
participant D as Database
participant R as Redis
C->>G: Request User Info
G->>A: Validate Token
A->>R: Check Token Cache
R-->>A: Token Valid
A-->>G: Auth Success
G->>U: Get User Info
U->>R: Check User Cache
alt Cache Exists
R-->>U: Return User Data
else Cache Miss
U->>D: Query Database
D-->>U: Return User Info
U->>R: Update Cache
end
U-->>G: Return User Info
G-->>C: Respond User Data
Flujo de Negocio
mermaid
flowchart TD
Start([User Order]) --> Check{Check Stock}
Check -->|In Stock| Reserve[Reserve Stock]
Check -->|Out of Stock| OutOfStock[Out of Stock]
OutOfStock --> Notify[Notify User]
Notify --> End1([End])
Reserve --> Payment{Payment Processing}
Payment -->|Success| ConfirmOrder[Confirm Order]
Payment -->|Fail| ReleaseStock[Release Stock]
ReleaseStock --> PaymentFailed[Payment Failed]
PaymentFailed --> End2([End])
ConfirmOrder --> UpdateInventory[Update Inventory]
UpdateInventory --> SendNotification[Send Notification]
SendNotification --> Logistics[Arrange Logistics]
Logistics --> End3([Order Complete])
style Start fill:#e8f5e8
style End1 fill:#ffebee
style End2 fill:#ffebee
style End3 fill:#e8f5e8
style OutOfStock fill:#ffebee
style PaymentFailed fill:#ffebee
Estilos y Temas
Estilos de Nodo
mermaid
flowchart LR
A[Estilo por Defecto] --> B[Estilo 1]
A --> C[Estilo 2]
A --> D[Estilo 3]
style B fill:#f9f,stroke:#333,stroke-width:4px
style C fill:#bbf,stroke:#f66,stroke-width:2px,color:#fff,stroke-dasharray: 5 5
style D fill:#f96,stroke:#333,stroke-width:4px,color:#fff
Estilos de Clase
mermaid
flowchart LR
A[Nodo A]:::classA --> B[Nodo B]:::classB
A --> C[Nodo C]:::classC
classDef classA fill:#e1f5fe,stroke:#01579b,stroke-width:2px
classDef classB fill:#f3e5f5,stroke:#4a148c,stroke-width:2px
classDef classC fill:#e8f5e8,stroke:#1b5e20,stroke-width:2px
Configuración y Compatibilidad
Configuración de VitePress
javascript
// .vitepress/config.js
export default {
markdown: {
mermaid: true
}
}
Soporte de GitHub
GitHub soporta Mermaid nativamente, puedes usarlo directamente en archivos Markdown:
markdown
```mermaid
graph LR
A --> B
### Soporte en Otras Plataformas
| Plataforma | Soporte | Requisito de Configuración |
|--------------|--------------|-------------------|
| **GitHub** | ✅ Nativo | Ninguno |
| **GitLab** | ✅ Nativo | Ninguno |
| **VitePress**| ✅ Plugin | Requiere configuración |
| **Jekyll** | ✅ Plugin | Requiere plugin |
| **Hugo** | ✅ Tema | Depende del tema |
## Mejores Prácticas
### Consejos de Diseño
```markdown
✅ Recomendado:
1. **Manténlo simple:**
- Evita diagramas demasiado complejos
- Usa etiquetas claras y conexiones
2. **Diseño lógico:**
- Elige el diagrama de dirección apropiada
- Mantén el flujo lógico claro
3. **Estilo consistente:**
- Usa un tema de color consistente
- Mantén el estilo del diagrama unificado
4. **Añade explicaciones:**
- Añade títulos para diagramas complejos
- Proporciona explicaciones de texto necesarias
❌ Evita:
1. Diagramas demasiado complejos para entender
2. Muchas líneas cruzadas
3. Etiquetas vagas
4. Leyes ausentes
Consideraciones de Rendimiento
markdown
- **Optimización de diagramas grandes:**
- Considera dividir diagramas complejos
- Usa subgrafos para la organización
- **Rendimiento de carga:**
- Evita muchos diagramas en una sola página
- Considera el cargado perezoso
- **Adaptación móvil:**
- Asegúrate de que los diagramas sean legibles en pantallas pequeñas
- Considera el desplazamiento horizontal
Sintaxis Relacionada
- Incrustar HTML - Mejoras de HTML
- Fórmulas Matemáticas - Expresiones LaTeX
- Mejores Prácticas - Consejos de escritura
Herramientas y Recursos
Editores en Línea
- Mermaid Live Editor: Editor en línea oficial
- Draw.io: Herramienta de diagrama general
- Lucidchart: Plataforma de diagrama profesional
- Excalidraw: Diagramas estilo a mano
Herramientas de Desarrollo
- Mermaid CLI: Herramienta de línea de comandos
- VS Code Mermaid: Extensión de Visual Studio Code
- Atom Mermaid: Extensión de editor Atom
- IntelliJ Mermaid: Extensión de IDE de JetBrains
Referencias
- Documentación Oficial de Mermaid: Referencia completa de sintaxis
- Biblioteca de Ejemplos de Mermaid: Diversos ejemplos de diagramas
- GitHub Mermaid: Uso en GitHub
- Awesome Mermaid: Colección de recursos
Al dominar la sintaxis de diagrama de flujo, puedes crear diagramas visuales profesionales en tu documentación, mejorando la claridad y expresividad.