Compare commits

...

2 Commits

Author SHA1 Message Date
copilot-swe-agent[bot]
fab108a3c1 Add comprehensive documentation explaining Mermaid's functionality and architecture
Co-authored-by: GDFaber <1912783+GDFaber@users.noreply.github.com>
2025-09-07 17:44:19 +00:00
copilot-swe-agent[bot]
8b1a12e81a Initial plan 2025-09-07 17:31:06 +00:00
4 changed files with 966 additions and 0 deletions

488
COMPONENT_EXAMPLES.md Normal file
View File

@@ -0,0 +1,488 @@
# Mermaid Key Components: Code Examples
This document provides concrete code examples demonstrating how Mermaid's key components work together.
## Diagram Type Examples
### Flowchart Diagram Structure
```typescript
// packages/mermaid/src/diagrams/flowchart/flowDiagram.ts
export const diagram = {
parser: flowParser, // JISON parser for flowchart syntax
get db() {
// Database for managing diagram state
return new FlowDB();
},
renderer, // SVG renderer function
styles: flowStyles, // CSS styles specific to flowcharts
init: (cnf: MermaidConfig) => {
if (!cnf.flowchart) {
cnf.flowchart = {};
}
// Configuration initialization
cnf.flowchart.arrowMarkerAbsolute = cnf.arrowMarkerAbsolute;
},
};
```
### Sequence Diagram Structure
```typescript
// packages/mermaid/src/diagrams/sequence/sequenceDiagram.ts
export const diagram: DiagramDefinition = {
parser, // JISON parser for sequence syntax
get db() {
return new SequenceDB(); // Manages participants, messages, loops
},
renderer, // Draws actors, lifelines, messages
styles, // Sequence-specific styling
init: (cnf: MermaidConfig) => {
if (!cnf.sequence) {
cnf.sequence = {};
}
if (cnf.wrap) {
cnf.sequence.wrap = cnf.wrap;
}
},
};
```
## Core API Examples
### Main API Usage Pattern
```typescript
// packages/mermaid/src/mermaidAPI.ts
/**
* Parse and validate diagram syntax
*/
async function parse(text: string, parseOptions?: ParseOptions): Promise<ParseResult> {
addDiagrams(); // Load all diagram types
const { code, config } = processAndSetConfigs(text);
const diagram = await getDiagramFromText(code);
return { diagramType: diagram.type, config };
}
/**
* Render diagram to SVG
*/
async function render(
id: string,
text: string,
svgContainingElement?: Element
): Promise<RenderResult> {
const { diagramType, config } = await parse(text, { suppressErrors: true });
// Create diagram instance
const diagram = new Diagram(text, {}, diagramType);
// Render to SVG
const svgCode = await diagram.renderer.draw(text, id, diagram);
return {
diagramType,
svg: svgCode,
bindFunctions: diagram.db.bindFunctions,
};
}
```
### Diagram Detection Example
```typescript
// packages/mermaid/src/diagram-api/detectType.ts
export const detectors: Record<string, DiagramDetector> = {
flowchart: {
detector: (text: string) => /^\s*graph|flowchart/.test(text),
loader: async () => {
const { diagram } = await import('../diagrams/flowchart/flowDiagram.js');
return { id: 'flowchart', diagram };
},
},
sequence: {
detector: (text: string) => /^\s*sequenceDiagram/.test(text),
loader: async () => {
const { diagram } = await import('../diagrams/sequence/sequenceDiagram.js');
return { id: 'sequence', diagram };
},
},
};
export const detectType = function (text: string, config?: MermaidConfig): string {
for (const [diagramType, { detector }] of Object.entries(detectors)) {
if (detector(text, config)) {
return diagramType;
}
}
throw new UnknownDiagramError(`No diagram type detected for text: ${text}`);
};
```
## Rendering System Examples
### Layout Algorithm Integration
```typescript
// packages/mermaid/src/rendering-util/render.ts
interface LayoutAlgorithm {
render(
layoutData: LayoutData,
svg: SVG,
helpers: InternalHelpers,
options?: RenderOptions
): Promise<void>;
}
const layoutAlgorithms: Record<string, LayoutLoaderDefinition> = {};
export const registerLayoutLoaders = (loaders: LayoutLoaderDefinition[]) => {
for (const loader of loaders) {
layoutAlgorithms[loader.name] = loader;
}
};
// Default layout loaders
const registerDefaultLayoutLoaders = () => {
registerLayoutLoaders([
{
name: 'dagre',
loader: async () => await import('./layout-algorithms/dagre/index.js'),
},
{
name: 'elk',
loader: async () => await import('./layout-algorithms/elk/index.js'),
},
]);
};
export const render = async (data4Layout: LayoutData, svg: SVG) => {
const layoutDefinition = layoutAlgorithms[data4Layout.layoutAlgorithm];
const layoutRenderer = await layoutDefinition.loader();
return layoutRenderer.render(data4Layout, svg, internalHelpers);
};
```
### Unified Renderer Example
```typescript
// packages/mermaid/src/diagrams/er/erRenderer-unified.ts
export const draw = async function (text: string, id: string, _version: string, diag: any) {
const { securityLevel, er: conf, layout } = getConfig();
// Extract data from parsed structure into Layout data format
const data4Layout = diag.db.getData() as LayoutData;
// Create the root SVG element
const svg = getDiagramElement(id, securityLevel);
// Configure layout
data4Layout.type = diag.type;
data4Layout.layoutAlgorithm = getRegisteredLayoutAlgorithm(layout);
data4Layout.config.flowchart!.nodeSpacing = conf?.nodeSpacing || 140;
data4Layout.config.flowchart!.rankSpacing = conf?.rankSpacing || 80;
data4Layout.direction = diag.db.getDirection();
data4Layout.markers = ['only_one', 'zero_or_one', 'one_or_more', 'zero_or_more'];
data4Layout.diagramId = id;
// Render using layout algorithm
await render(data4Layout, svg);
// Setup viewport
setupViewPortForSVG(svg, conf.padding, conf.useMaxWidth);
};
```
## Class Diagram Renderer Examples
### Traditional Renderer (v2)
```javascript
// packages/mermaid/src/diagrams/class/classRenderer.js
export const draw = function (text, id, _version, diagObj) {
const conf = getConfig().class;
// Create directed graph using graphlib
const g = new graphlib.Graph({
multigraph: true,
});
g.setGraph({
isMultiGraph: true,
});
// Add classes as nodes
classes.forEach(function (classDef) {
const node = svgDraw.drawClass(diagram, classDef, conf, diagObj);
idCache[node.id] = node;
g.setNode(node.id, node);
});
// Add relationships as edges
relations.forEach(function (relation) {
g.setEdge(
getGraphId(relation.id1),
getGraphId(relation.id2),
{ relation: relation },
relation.title || 'DEFAULT'
);
});
// Apply layout
dagreLayout(g);
// Position nodes
g.nodes().forEach(function (v) {
if (v !== undefined && g.node(v) !== undefined) {
root
.select('#' + (diagObj.db.lookUpDomId(v) || v))
.attr(
'transform',
'translate(' +
(g.node(v).x - g.node(v).width / 2) +
',' +
(g.node(v).y - g.node(v).height / 2) +
' )'
);
}
});
// Draw edges
g.edges().forEach(function (e) {
if (e !== undefined && g.edge(e) !== undefined) {
svgDraw.drawEdge(diagram, g.edge(e), g.edge(e).relation, conf, diagObj);
}
});
};
```
### Modern Unified Renderer (v3)
```typescript
// packages/mermaid/src/diagrams/class/classRenderer-v3-unified.ts
export const draw = async function (text: string, id: string, _version: string, diag: any) {
const { securityLevel, state: conf, layout } = getConfig();
// Extract data from parsed structure into Layout data format
const data4Layout = diag.db.getData() as LayoutData;
// Create the root SVG element
const svg = getDiagramElement(id, securityLevel);
// Configure layout settings
data4Layout.type = diag.type;
data4Layout.layoutAlgorithm = getRegisteredLayoutAlgorithm(layout);
data4Layout.nodeSpacing = conf?.nodeSpacing || 50;
data4Layout.rankSpacing = conf?.rankSpacing || 50;
data4Layout.markers = ['aggregation', 'extension', 'composition', 'dependency', 'lollipop'];
data4Layout.diagramId = id;
// Use unified rendering system
await render(data4Layout, svg);
// Add title
utils.insertTitle(
svg,
'classDiagramTitleText',
conf?.titleTopMargin ?? 25,
diag.db.getDiagramTitle()
);
setupViewPortForSVG(svg, padding, conf?.useMaxWidth);
};
```
## Configuration System Example
### Type-Safe Configuration
```typescript
// packages/mermaid/src/config.type.ts
export interface MermaidConfig {
theme?: 'default' | 'dark' | 'forest' | 'neutral';
themeVariables?: any;
startOnLoad?: boolean;
securityLevel?: 'strict' | 'loose' | 'antiscript' | 'sandbox';
deterministicIds?: boolean;
fontSize?: number;
// Diagram-specific configurations
flowchart?: FlowchartDiagramConfig;
sequence?: SequenceDiagramConfig;
class?: ClassDiagramConfig;
state?: StateDiagramConfig;
er?: ErDiagramConfig;
// ... other diagram configs
}
export interface FlowchartDiagramConfig extends BaseDiagramConfig {
diagramPadding?: number;
htmlLabels?: boolean;
nodeSpacing?: number;
rankSpacing?: number;
curve?: CurveStyle;
useMaxWidth?: boolean;
defaultRenderer?: 'dagre-d3' | 'dagre-wrapper' | 'elk';
}
```
### Configuration API
```typescript
// packages/mermaid/src/config.ts
let config: MermaidConfig = assignWithDepth({}, defaultConfig);
let directives: MermaidConfig = {};
let currentConfig: MermaidConfig = assignWithDepth({}, defaultConfig);
export const getConfig = (): MermaidConfig => currentConfig;
export const setConfig = (conf: MermaidConfig): MermaidConfig => {
updateCurrentConfig(conf);
return getConfig();
};
export const reset = (): void => {
config = assignWithDepth({}, defaultConfig);
directives = {};
updateCurrentConfig(config);
};
const updateCurrentConfig = (conf: MermaidConfig): void => {
currentConfig = assignWithDepth({}, config, directives, conf);
};
```
## Web Integration Example
### Simple Usage
```html
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js"></script>
</head>
<body>
<div class="mermaid">
graph TD A[Start] --> B{Decision} B -->|Yes| C[Action 1] B -->|No| D[Action 2]
</div>
<script>
mermaid.initialize({
startOnLoad: true,
theme: 'dark',
});
</script>
</body>
</html>
```
### Advanced Programmatic Usage
```javascript
// Advanced integration example
import mermaid from 'mermaid';
// Initialize with configuration
mermaid.initialize({
startOnLoad: false,
theme: 'default',
securityLevel: 'strict',
flowchart: {
useMaxWidth: true,
htmlLabels: true,
},
sequence: {
actorMargin: 50,
boxMargin: 10,
boxTextMargin: 5,
noteMargin: 10,
messageMargin: 35,
},
});
// Render specific diagram
async function renderDiagram(definition, element) {
try {
const { svg } = await mermaid.render('graphDiv', definition);
element.innerHTML = svg;
} catch (error) {
console.error('Error rendering diagram:', error);
}
}
// Parse and validate before rendering
async function validateAndRender(definition, element) {
try {
const parseResult = await mermaid.parse(definition);
console.log('Valid diagram type:', parseResult.diagramType);
const { svg } = await mermaid.render('graphDiv', definition);
element.innerHTML = svg;
} catch (error) {
console.error('Invalid diagram syntax:', error);
}
}
```
## Extension Example: Custom Diagram Type
### Custom Diagram Definition
```typescript
// example-diagram/exampleDiagram.ts
import type { DiagramDefinition } from '../../diagram-api/types.js';
export const diagram: DiagramDefinition = {
parser: {
parse: (text: string) => {
// Custom parsing logic
},
},
get db() {
return {
clear: () => {},
// ... other required DB methods
};
},
renderer: {
draw: async (text: string, id: string, version: string) => {
// Custom rendering logic
const svg = d3.select(`#${id}`);
// ... create SVG elements
},
},
styles: () => `
.example-class {
fill: #ff6b6b;
stroke: #333;
}
`,
};
```
### Registration and Usage
```typescript
// Register custom diagram
import { registerDiagram } from 'mermaid';
import { diagram } from './exampleDiagram.js';
registerDiagram('example', diagram, (text) => text.includes('example'));
// Now can use in text:
const diagramText = `
example
nodeA --> nodeB
`;
```
This comprehensive set of examples demonstrates how Mermaid's modular architecture enables powerful diagram generation while maintaining extensibility and type safety.

210
DEMONSTRATION.html Normal file
View File

@@ -0,0 +1,210 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Mermaid Functionality Demonstration</title>
<script src="https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js"></script>
<style>
body {
font-family: Arial, sans-serif;
max-width: 1200px;
margin: 0 auto;
padding: 20px;
background-color: #f5f5f5;
}
.demo-section {
background: white;
margin: 20px 0;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.demo-title {
color: #333;
border-bottom: 2px solid #007acc;
padding-bottom: 10px;
margin-bottom: 20px;
}
.mermaid {
text-align: center;
margin: 20px 0;
}
.code-block {
background: #f8f9fa;
border: 1px solid #e9ecef;
border-radius: 4px;
padding: 15px;
font-family: 'Courier New', monospace;
margin: 10px 0;
overflow-x: auto;
}
.header {
text-align: center;
color: #007acc;
margin-bottom: 30px;
}
</style>
</head>
<body>
<div class="header">
<h1>🧜‍♀️ Mermaid Functionality Demonstration</h1>
<p>A showcase of Mermaid's key diagram types and capabilities</p>
</div>
<div class="demo-section">
<h2 class="demo-title">1. Flowchart - Decision Flow</h2>
<p><strong>Use case:</strong> Process flows, decision trees, algorithm visualization</p>
<div class="code-block">
flowchart TD A[Start] --> B{Is it working?} B -->|Yes| C[Great!] B -->|No| D[Debug] D -->
E[Fix issues] E --> B C --> F[Deploy]
</div>
<div class="mermaid">
flowchart TD A[Start] --> B{Is it working?} B -->|Yes| C[Great!] B -->|No| D[Debug] D -->
E[Fix issues] E --> B C --> F[Deploy]
</div>
</div>
<div class="demo-section">
<h2 class="demo-title">2. Sequence Diagram - API Interaction</h2>
<p><strong>Use case:</strong> API documentation, system interactions, communication flows</p>
<div class="code-block">
sequenceDiagram participant C as Client participant S as Server participant DB as Database
C->>S: Request user data S->>DB: Query user table DB-->>S: Return user data S-->>C: JSON
response Note right of C: Client processes data
</div>
<div class="mermaid">
sequenceDiagram participant C as Client participant S as Server participant DB as Database
C->>S: Request user data S->>DB: Query user table DB-->>S: Return user data S-->>C: JSON
response Note right of C: Client processes data
</div>
</div>
<div class="demo-section">
<h2 class="demo-title">3. Class Diagram - Software Architecture</h2>
<p>
<strong>Use case:</strong> Object-oriented design, software architecture, database schemas
</p>
<div class="code-block">
classDiagram class User { +String name +String email +login() +logout() } class Order { +int
id +Date date +float total +calculate() } class Product { +String name +float price +int
stock } User ||--o{ Order : places Order }|--|| Product : contains
</div>
<div class="mermaid">
classDiagram class User { +String name +String email +login() +logout() } class Order { +int
id +Date date +float total +calculate() } class Product { +String name +float price +int
stock } User ||--o{ Order : places Order }|--|| Product : contains
</div>
</div>
<div class="demo-section">
<h2 class="demo-title">4. Git Graph - Development Workflow</h2>
<p>
<strong>Use case:</strong> Git workflow documentation, branching strategies, release
processes
</p>
<div class="code-block">
gitGraph commit id: "Initial" commit id: "Setup" branch feature checkout feature commit id:
"Feature A" commit id: "Feature B" checkout main merge feature commit id: "Release v1.0"
branch hotfix checkout hotfix commit id: "Fix bug" checkout main merge hotfix commit id:
"Release v1.1"
</div>
<div class="mermaid">
gitGraph commit id: "Initial" commit id: "Setup" branch feature checkout feature commit id:
"Feature A" commit id: "Feature B" checkout main merge feature commit id: "Release v1.0"
branch hotfix checkout hotfix commit id: "Fix bug" checkout main merge hotfix commit id:
"Release v1.1"
</div>
</div>
<div class="demo-section">
<h2 class="demo-title">5. Gantt Chart - Project Timeline</h2>
<p><strong>Use case:</strong> Project management, milestone tracking, resource planning</p>
<div class="code-block">
gantt title Development Timeline dateFormat YYYY-MM-DD section Planning Requirements :done,
req, 2024-01-01, 2024-01-07 Design :done, des, 2024-01-08, 2024-01-14 section Development
Backend API :active, api, 2024-01-15, 2024-02-15 Frontend :frontend, after api, 20d Testing
:test, after frontend, 10d section Deployment Staging :staging, after test, 3d Production
:prod, after staging, 2d
</div>
<div class="mermaid">
gantt title Development Timeline dateFormat YYYY-MM-DD section Planning Requirements :done,
req, 2024-01-01, 2024-01-07 Design :done, des, 2024-01-08, 2024-01-14 section Development
Backend API :active, api, 2024-01-15, 2024-02-15 Frontend :frontend, after api, 20d Testing
:test, after frontend, 10d section Deployment Staging :staging, after test, 3d Production
:prod, after staging, 2d
</div>
</div>
<div class="demo-section">
<h2 class="demo-title">6. State Diagram - System States</h2>
<p><strong>Use case:</strong> State machines, user workflows, system behavior modeling</p>
<div class="code-block">
stateDiagram-v2 [*] --> Idle Idle --> Loading : start_request Loading --> Success :
request_success Loading --> Error : request_failed Success --> Idle : reset Error --> Idle :
retry Error --> [*] : give_up
</div>
<div class="mermaid">
stateDiagram-v2 [*] --> Idle Idle --> Loading : start_request Loading --> Success :
request_success Loading --> Error : request_failed Success --> Idle : reset Error --> Idle :
retry Error --> [*] : give_up
</div>
</div>
<div class="demo-section">
<h2 class="demo-title">7. Pie Chart - Data Visualization</h2>
<p><strong>Use case:</strong> Data visualization, market share, resource allocation</p>
<div class="code-block">
pie title Technology Stack Usage "JavaScript" : 35 "TypeScript" : 25 "Python" : 20 "Java" :
15 "Other" : 5
</div>
<div class="mermaid">
pie title Technology Stack Usage "JavaScript" : 35 "TypeScript" : 25 "Python" : 20 "Java" :
15 "Other" : 5
</div>
</div>
<div class="demo-section">
<h2 class="demo-title">8. User Journey - UX Flow</h2>
<p>
<strong>Use case:</strong> User experience mapping, customer journeys, process optimization
</p>
<div class="code-block">
journey title User Registration Journey section Discovery Visit homepage : 5: User Read
about features : 4: User Check pricing : 3: User section Registration Click signup : 3: User
Fill form : 2: User Verify email : 1: User, System section Onboarding Complete profile : 4:
User Take tutorial : 5: User First task : 5: User
</div>
<div class="mermaid">
journey title User Registration Journey section Discovery Visit homepage : 5: User Read
about features : 4: User Check pricing : 3: User section Registration Click signup : 3: User
Fill form : 2: User Verify email : 1: User, System section Onboarding Complete profile : 4:
User Take tutorial : 5: User First task : 5: User
</div>
</div>
<script>
// Initialize Mermaid with configuration
mermaid.initialize({
startOnLoad: true,
theme: 'default',
securityLevel: 'loose',
flowchart: {
useMaxWidth: true,
htmlLabels: true,
},
sequence: {
actorMargin: 50,
width: 150,
height: 65,
boxMargin: 10,
},
gantt: {
useMaxWidth: true,
leftMargin: 75,
gridLineStartPadding: 35,
},
});
</script>
</body>
</html>

249
MERMAID_OVERVIEW.md Normal file
View File

@@ -0,0 +1,249 @@
# Mermaid: Overview of Main Functionality and Key Components
## What is Mermaid?
Mermaid is a JavaScript-based diagramming and charting tool that uses Markdown-inspired text definitions to create and modify complex diagrams. The main purpose of Mermaid is to help documentation catch up with development by enabling users to create easily modifiable diagrams that can be integrated into production scripts and documentation workflows.
**Core Philosophy**: "Doc-Rot is a Catch-22 that Mermaid helps to solve" - providing a solution to the common problem where diagramming costs precious developer time and gets outdated quickly, but not having diagrams hurts productivity and organizational learning.
## Main Functionality
### 1. **Text-to-Diagram Conversion**
- Converts Markdown-inspired text definitions into SVG diagrams
- Supports over 15+ different diagram types
- Real-time rendering and preview capabilities
- Integration with popular platforms (GitHub, GitLab, etc.)
### 2. **Interactive Diagram Creation**
- Live Editor for interactive diagram creation
- Web integration module for embedding in web pages
- Dynamic rendering and modification capabilities
### 3. **Extensible Architecture**
- Plugin system for custom diagram types
- Configurable themes and styling
- Multiple layout algorithms support
- External diagram definition loading
## Key Components
### Core Architecture
#### 1. **Entry Points & API Layer**
- **`mermaid.ts`**: Main web page integration module, provides the primary interface for users
- **`mermaidAPI.ts`**: Core API containing functions for parsing and rendering diagrams
- **`Diagram.ts`**: Main diagram abstraction class that handles diagram lifecycle
#### 2. **Configuration System**
- **`config.ts`** & **`config.type.ts`**: Centralized configuration management
- **`defaultConfig.ts`**: Default configuration values
- Supports runtime configuration updates and diagram-specific settings
#### 3. **Parser & Detection System**
- **`diagram-api/detectType.ts`**: Automatic diagram type detection from text input
- **`diagram-api/loadDiagram.ts`**: Dynamic loading and registration of diagram parsers
- **`preprocess.ts`**: Text preprocessing and directive handling
### Diagram Types (Located in `/src/diagrams/`)
Mermaid supports a comprehensive set of diagram types, each with its own parser, renderer, and styling:
#### **Core Diagram Types:**
1. **Flowchart** - Flow diagrams with nodes, edges, and decision points
2. **Sequence** - Interaction diagrams between actors over time
3. **Class** - Object-oriented modeling diagrams
4. **State** - State machine and statechart diagrams
5. **Gantt** - Project timeline and scheduling charts
6. **Git** - Git branching and merging visualizations
#### **Specialized Diagram Types:**
7. **Pie** - Data visualization pie charts
8. **User Journey** - User experience journey mapping
9. **C4** - C4 architecture diagrams (Context, Container, Component, Code)
10. **ER (Entity-Relationship)** - Database modeling diagrams
11. **Mindmap** - Hierarchical mind mapping
12. **Architecture** - System architecture diagrams
13. **Block** - Block diagrams
14. **Kanban** - Kanban board visualization
15. **Packet** - Network packet diagrams
16. **Quadrant** - Four-quadrant analysis charts
17. **Radar** - Radar/spider charts
18. **Requirement** - Requirements modeling
19. **Sankey** - Flow diagrams showing quantities
20. **Timeline** - Chronological event timelines
21. **Treemap** - Hierarchical data visualization
22. **XYChart** - Scatter plots and line charts
#### **Diagram Structure Pattern:**
Each diagram type follows a consistent structure:
```typescript
export const diagram = {
parser: parserDefinition, // JISON or custom parser
db: databaseClass, // Data management and state
renderer: rendererFunction, // SVG rendering logic
styles: stylingDefinition, // CSS styling
init: initializationFunction, // Setup and configuration
};
```
### Rendering System
#### 1. **Core Rendering (`rendering-util/`)**
- **`render.ts`**: Main rendering orchestrator with pluggable layout algorithms
- **`createGraph.ts`** & **`createText.ts`**: Basic shape and text creation
- **`insertElementsForSize.ts`**: Element sizing and positioning
- **`setupViewPortForSVG.ts`**: SVG viewport management
#### 2. **Layout Algorithms (`layout-algorithms/`)**
- **Dagre**: Default hierarchical layout algorithm
- **Elk**: Advanced layout engine with multiple algorithms
- **Cose-Bilkent**: Physics-based layout for complex graphs
- **Tidy-Tree**: Tree layout algorithm
#### 3. **Styling & Theming**
- **`themes/`**: Multiple built-in themes (default, dark, forest, neutral, etc.)
- **`styles.ts`**: CSS-in-JS styling system
- Theme inheritance and customization capabilities
### Security & Safety
#### 1. **Security Levels**
- **Sandbox Mode**: Renders diagrams in sandboxed iframes to prevent script execution
- **Loose Mode**: Standard rendering with sanitization
- **Strict Mode**: Enhanced security with limited functionality
#### 2. **Content Sanitization**
- **DOMPurify Integration**: XSS protection for user-generated content
- Input validation and sanitization
- Safe handling of external content
### Extension & Integration System
#### 1. **External Diagram Support**
- Dynamic loading of custom diagram types
- Plugin architecture for extending functionality
- External diagram definition interface
#### 2. **Layout Extension**
- Pluggable layout algorithms
- Custom layout loader registration
- Runtime algorithm selection
#### 3. **Icon System**
- **`icons.ts`**: Icon pack management
- SVG icon rendering
- Customizable icon libraries
### Package Structure (Monorepo)
The repository uses a monorepo structure with pnpm workspaces:
#### **Main Packages:**
- **`packages/mermaid/`**: Core Mermaid library
- **`packages/mermaid-example-diagram/`**: Example external diagram
- **`packages/mermaid-layout-elk/`**: Elk layout algorithm
- **`packages/mermaid-layout-tidy-tree/`**: Tidy tree layout
- **`packages/mermaid-zenuml/`**: ZenUML integration
- **`packages/parser/`**: Parser utilities
- **`packages/tiny/`**: Minimal Mermaid build
#### **Supporting Infrastructure:**
- **`docs/`**: Documentation and website content
- **`demos/`**: Example implementations
- **`cypress/`**: End-to-end testing
- **`tests/`**: Unit and integration tests
### Development & Build System
#### 1. **Build Pipeline**
- **ESBuild**: Fast JavaScript bundling
- **TypeScript**: Type checking and compilation
- **Vite**: Development server and hot reloading
#### 2. **Testing Strategy**
- **Vitest**: Unit testing framework
- **Cypress**: End-to-end visual regression testing
- **Applitools**: Visual testing integration
- **Argos**: PR visual regression testing
#### 3. **Code Quality**
- **ESLint**: JavaScript/TypeScript linting
- **Prettier**: Code formatting
- **Husky**: Git hooks for pre-commit checks
- **CSpell**: Spell checking for documentation
## Integration Ecosystem
### Official Integrations
- **Mermaid Chart**: Commercial diagram editor and collaboration platform
- **GitHub**: Native Mermaid support in GitHub Markdown
- **GitLab**: Built-in Mermaid rendering
### Community Integrations
- **Productivity Tools**: Notion, Confluence, Obsidian, etc.
- **Development Tools**: VS Code, IntelliJ, various editors
- **Documentation**: GitBook, Docusaurus, VuePress, etc.
- **Communication**: Slack, Discord, Microsoft Teams
- **CMS/Wiki Systems**: MediaWiki, TiddlyWiki, etc.
## Usage Patterns
### 1. **Direct Web Integration**
```javascript
import mermaid from 'mermaid';
mermaid.initialize({ startOnLoad: true });
```
### 2. **Programmatic API Usage**
```javascript
const { svg } = await mermaid.render('graphDiv', 'graph TD; A-->B');
```
### 3. **Configuration & Customization**
```javascript
mermaid.initialize({
theme: 'dark',
flowchart: { useMaxWidth: true },
sequence: { actorMargin: 50 },
});
```
## Future Extensibility
The architecture is designed for extensibility through:
- **Plugin System**: Easy addition of new diagram types
- **Layout Algorithms**: Pluggable layout engines
- **Theming**: Comprehensive theme customization
- **Output Formats**: Support for multiple output formats
- **Integration APIs**: Well-defined interfaces for third-party integration
This modular architecture makes Mermaid a powerful platform for diagram generation that can grow and adapt to new use cases while maintaining backward compatibility and performance.

19
server.log Normal file
View File

@@ -0,0 +1,19 @@
nohup: ignoring input
Traceback (most recent call last):
File "<frozen runpy>", line 198, in _run_module_as_main
File "<frozen runpy>", line 88, in _run_code
File "/usr/lib/python3.12/http/server.py", line 1314, in <module>
test(
File "/usr/lib/python3.12/http/server.py", line 1261, in test
with ServerClass(addr, HandlerClass) as httpd:
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/lib/python3.12/socketserver.py", line 457, in __init__
self.server_bind()
File "/usr/lib/python3.12/http/server.py", line 1308, in server_bind
return super().server_bind()
^^^^^^^^^^^^^^^^^^^^^
File "/usr/lib/python3.12/http/server.py", line 136, in server_bind
socketserver.TCPServer.server_bind(self)
File "/usr/lib/python3.12/socketserver.py", line 473, in server_bind
self.socket.bind(self.server_address)
OSError: [Errno 98] Address already in use