# Mermaid-Go A high-performance Go implementation of Mermaid diagram parsing and rendering, providing near-complete compatibility with [Mermaid.js](https://mermaid.js.org/) syntax. ## ๐ŸŽฏ Project Goals Mermaid-Go aims to provide a native Go alternative to Mermaid.js with: - **High Performance**: Fast parsing and rendering without JavaScript runtime overhead - **Native Integration**: Easy embedding in Go applications and CLI tools - **Broad Compatibility**: Support for the most commonly used Mermaid diagram types - **Extensibility**: Clean architecture for adding new diagram types and features ## ๐Ÿ“Š Current Support Status ### โœ… Fully Supported Diagram Types #### **Flowchart Diagrams** (~85% Feature Complete) - โœ… All standard node shapes (rectangle, circle, diamond, parallelogram, etc.) - โœ… Edge types (solid, dotted, thick arrows) - โœ… Subgraphs with titles and directions - โœ… Interactive features (click events, links, callbacks) - โœ… Styling (classDef, class assignments, individual node styles) - โœ… Direction control (TD, TB, BT, RL, LR) - โš ๏ธ Edge labels and animations (partial support) - โŒ Markdown text formatting #### **Class Diagrams** (~80% Feature Complete) - โœ… Class definitions with members and methods - โœ… Method parameters and return types - โœ… Visibility modifiers (+, -, #, ~) - โœ… Class relationships (inheritance, composition, aggregation, etc.) - โœ… Annotations (<>, <>, <>) - โœ… Comments (%% syntax) - โœ… Notes (general and class-specific) - โœ… Direction control - โš ๏ธ Generic types (framework ready, parsing in progress) - โŒ Click events and links ### ๐Ÿ”„ Partially Supported #### **State Diagrams** (~75% Feature Complete) - โœ… Basic state definitions and transitions - โœ… Start/end states - โœ… State actions (entry, exit, do) - โœ… Transition guards and actions - โœ… Notes and annotations - โœ… Special states (choice, fork, join, history) - โš ๏ธ Composite states (framework ready) - โš ๏ธ Parallel states (framework ready) #### **Sequence Diagrams** (~80% Feature Complete) - โœ… Basic actor interactions - โœ… Simple message flows - โœ… Multiple arrow types (->, -->, ->>, -->>, -x, --x, -), --), <->) - โœ… Activation boxes (activate/deactivate) - โœ… Loops and alternatives (loop, alt, opt) - โœ… Parallel sections (par) - โœ… Notes and comments - โœ… Participant boxes and grouping - โš ๏ธ Complex nesting (framework ready) - โŒ Auto-numbering and styling ### ๐Ÿšง Planned Support - **ER Diagrams**: Entity-relationship diagrams - **Gantt Charts**: Project timeline visualization - **User Journey**: User experience flow mapping - **Requirement Diagrams**: Requirements and relationships - **Timeline**: Chronological event visualization ## ๐ŸŒŸ Key Features - **๐Ÿš€ High Performance**: Fast parsing and rendering without JavaScript runtime overhead - **๐Ÿ‡จ๐Ÿ‡ณ Full Unicode Support**: Complete support for Chinese, Japanese, Korean and all Unicode characters - **๐Ÿ”„ Bidirectional Conversion**: Mermaid syntax โ†” Go structs (AST) โ†” Mermaid syntax - **๐Ÿ–ผ๏ธ Image Export**: High-quality SVG export with Chinese character support - **๐Ÿ—๏ธ Native Integration**: Easy embedding in Go applications and CLI tools - **๐Ÿ“Š Broad Compatibility**: Support for 24+ diagram types with intelligent auto-detection ## ๐Ÿš€ Quick Start ### Installation ```bash go get github.com/your-org/mermaid-go ``` ### Enhanced Usage with Auto-Detection ```go package main import ( "fmt" "log" "mermaid-go/pkg/ast" "mermaid-go/pkg/detector" "mermaid-go/pkg/parser" "mermaid-go/pkg/renderer" ) func main() { // Auto-detect and parse any Mermaid diagram type input := `sequenceDiagram participant U as User participant S as Server U -> S : request S --> U : response` // Create main parser with auto-detection mermaidParser := parser.NewMermaidParser() // Detect diagram type diagramType := mermaidParser.GetDiagramType(input) fmt.Printf("Detected diagram type: %s\n", diagramType) // Parse the diagram diagram, err := mermaidParser.Parse(input) if err != nil { log.Fatal(err) } // Render back to Mermaid syntax switch d := diagram.(type) { case *ast.SequenceDiagram: renderer := renderer.NewSequenceRenderer() output, _ := renderer.Render(d) fmt.Println(output) case *ast.StateDiagram: renderer := renderer.NewStateRenderer() output, _ := renderer.Render(d) fmt.Println(output) // ... handle other diagram types } } ``` ### Enhanced Sequence Diagrams ```go // Parse a complex sequence diagram with loops, alternatives, and parallel sections input := ` sequenceDiagram participant U as User participant W as WebApp participant S as Server participant D as Database U -> W : login request activate W loop Authentication W -> S : validate credentials S -> D : query user D --> S : user data end alt Valid credentials S --> W : success W --> U : login complete else Invalid credentials S --> W : failure W --> U : login failed end par User actions U -> W : browse content and Background tasks S -> D : cleanup sessions end deactivate W ` parser := parser.NewSequenceParser() diagram, err := parser.Parse(input) // ... rest of the code ``` ### Enhanced State Diagrams ```go // Parse a state diagram with guards, actions, and notes input := ` stateDiagram-v2 [*] --> Idle Idle --> Processing : start [hasData] / processData Processing --> Idle : complete [success] / cleanup Processing --> Error : fail [error] / logError note right of Processing : Main processing state note left of Error : Error handling ` parser := parser.NewStateParser() diagram, err := parser.Parse(input) // ... rest of the code ``` ## ๐ŸŽฏ Recent Enhancements ### ๐Ÿง  Intelligent Diagram Type Detection - **Auto-Detection**: Automatically detects 24+ diagram types from input text - **Priority-Based**: More specific patterns detected first (e.g., `stateDiagram-v2` before `stateDiagram`) - **Robust Parsing**: Handles comments, directives, and front matter ### ๐Ÿ”ง Enhanced Lexical Analysis - **Rich Arrow Support**: 20+ arrow types including bidirectional, dotted, crossed, and directional markers - **Special State Handling**: Proper recognition of complex diagram declarations - **Mermaid.js Compatibility**: Follows official mermaidjs lexical patterns ### ๐Ÿ—๏ธ Modular Architecture - **Detector Registry**: Extensible system for adding new diagram types - **Parser Router**: Centralized parsing with type-specific handlers - **Clean Separation**: Lexical analysis, parsing, and rendering are fully decoupled ### Chinese Character Support mermaid-go fully supports Unicode characters including Chinese, Japanese, and Korean: ```go // Chinese pie chart input := `pie showData title 2024ๅนดๅธ‚ๅœบไปฝ้ขๅˆ†ๆž "้˜ฟ้‡Œๅทดๅทด" : 35 "่…พ่ฎฏ" : 30 "็™พๅบฆ" : 20 "ๅญ—่Š‚่ทณๅŠจ" : 15` // Chinese sequence diagram input := `sequenceDiagram participant ็”จๆˆท as ็”จๆˆท็ซฏ participant ็ณป็ปŸ as ๅŽ็ซฏ็ณป็ปŸ ็”จๆˆท ->> ็ณป็ปŸ: ็™ปๅฝ•่ฏทๆฑ‚ ็ณป็ปŸ -->> ็”จๆˆท: ็™ปๅฝ•ๅ“ๅบ”` ``` ### Command Line Usage ```bash # Parse and validate a Mermaid file go run main.go parse diagram.mmd # Convert between formats go run main.go convert input.mmd output.mmd ``` ## ๐Ÿ“– Supported Syntax ### Flowchart Examples #### Basic Flowchart ```mermaid flowchart TD A[Start] --> B[Process] B --> C{Decision} C -->|Yes| D[Success] C -->|No| E[Failure] ``` #### Advanced Features ```mermaid flowchart LR subgraph "User Actions" A([Login]) --> B{Authenticated?} end subgraph "System Process" C[Process Request] --> D[Generate Response] end B -->|Yes| C B -->|No| A %% Styling classDef userClass fill:#e1f5fe,stroke:#01579b,stroke-width:2px class A,B userClass %% Interactive elements click A "https://example.com/login" "_blank" click C callback ``` #### Complex Node Shapes ```mermaid flowchart TB A([Start/End]) --> B[Rectangle] B --> C(Rounded) C --> D{Diamond} D --> E[/Parallelogram/] E --> F[\Alt Parallelogram\] F --> G>Flag] G --> H[[Subroutine]] H --> I((Circle)) ``` ### Class Diagram Examples #### Basic Class Definition ```mermaid classDiagram class Animal { +String name +int age +makeSound() void -validateAge(int age) boolean } ``` #### Advanced Class Features ```mermaid classDiagram %% Interface definition class Shape { <> +area() double +perimeter() double } %% Abstract class class AbstractShape { <> +String color +getColor() String +setColor(String color) void +area()* double } %% Relationships Shape <|-- AbstractShape AbstractShape <|-- Circle AbstractShape <|-- Rectangle %% Notes note "This is a shape hierarchy example" note for Shape "Defines the basic shape interface" ``` #### Method Parameters and Types ```mermaid classDiagram class Calculator { +add(int a, int b) int +subtract(double x, double y) double +multiply(float[] numbers) float -validateInput(Object input) boolean } ``` ## ๐Ÿ—๏ธ Architecture ``` mermaid-go/ โ”œโ”€โ”€ pkg/ โ”‚ โ”œโ”€โ”€ ast/ # Abstract Syntax Tree definitions โ”‚ โ”‚ โ”œโ”€โ”€ flowchart.go โ”‚ โ”‚ โ”œโ”€โ”€ class.go โ”‚ โ”‚ โ””โ”€โ”€ ... โ”‚ โ”œโ”€โ”€ lexer/ # Tokenization โ”‚ โ”‚ โ””โ”€โ”€ lexer.go โ”‚ โ”œโ”€โ”€ parser/ # Syntax analysis โ”‚ โ”‚ โ”œโ”€โ”€ mermaid.go โ”‚ โ”‚ โ”œโ”€โ”€ flowchart.go โ”‚ โ”‚ โ”œโ”€โ”€ class.go โ”‚ โ”‚ โ””โ”€โ”€ ... โ”‚ โ””โ”€โ”€ renderer/ # Output generation โ”‚ โ”œโ”€โ”€ mermaid.go โ”‚ โ”œโ”€โ”€ flowchart.go โ”‚ โ””โ”€โ”€ class.go โ”œโ”€โ”€ cmd/ # CLI applications โ”œโ”€โ”€ examples/ # Usage examples โ””โ”€โ”€ tests/ # Test diagrams ``` ### Key Components - **Lexer**: Tokenizes Mermaid syntax into a stream of tokens - **Parser**: Builds Abstract Syntax Trees (AST) from token streams - **AST**: Represents diagram structure in memory - **Renderer**: Converts AST back to Mermaid syntax or other formats ## ๐Ÿงช Testing ### Run Basic Tests ```bash go test ./... ``` ### Test Specific Diagram Types ```bash # Test flowcharts go run test_flowchart_advanced.go # Test class diagrams go run test_class_advanced.go ``` ### Validation Examples ```bash # Test round-trip parsing echo 'flowchart TD; A --> B' | go run main.go validate ``` ## ๐ŸŽจ Advanced Features ### Interactive Elements ```mermaid flowchart TD A[Button] --> B[Action] click A "https://example.com" "_blank" click B callback ``` ### Styling and Themes ```mermaid flowchart LR A --> B --> C classDef default fill:#f9f9f9,stroke:#333,stroke-width:2px classDef highlight fill:#ff6b6b,stroke:#c92a2a,stroke-width:3px class B highlight ``` ### Subgraphs and Organization ```mermaid flowchart TB subgraph Frontend ["Frontend Layer"] direction LR A[React App] --> B[API Client] end subgraph Backend ["Backend Services"] direction TB C[REST API] --> D[Database] end Frontend --> Backend ``` ## ๐Ÿ”ง Configuration ### Parser Options ```go parser := parser.NewMermaidParser() parser.SetStrictMode(true) // Enable strict syntax validation parser.SetDebugMode(true) // Enable detailed error messages ``` ### Renderer Options ```go renderer := renderer.NewMermaidRenderer() renderer.SetIndentation(" ") // Set custom indentation renderer.SetCompactMode(false) // Pretty-print output ``` ## ๐Ÿค Contributing We welcome contributions! Here's how to get started: 1. **Fork the repository** 2. **Create a feature branch**: `git checkout -b feature/new-diagram-type` 3. **Make your changes** and add tests 4. **Run tests**: `go test ./...` 5. **Submit a pull request** ### Adding New Diagram Types 1. **Define AST structures** in `pkg/ast/` 2. **Implement parser** in `pkg/parser/` 3. **Add renderer** in `pkg/renderer/` 4. **Write tests** and examples 5. **Update documentation** ### Current Development Priorities 1. **Complete Generic Types** support for Class Diagrams 2. **Markdown Text Formatting** for all diagram types 3. **Edge Labels and Animations** for Flowcharts 4. **ER Diagram** implementation 5. **Gantt Chart** support ## ๐Ÿ“š Examples and Tutorials ### Real-World Use Cases #### Software Architecture Documentation ```mermaid flowchart TD subgraph "Client Tier" A[Web Browser] --> B[Mobile App] end subgraph "Application Tier" C[Load Balancer] --> D[API Gateway] D --> E[Microservice 1] D --> F[Microservice 2] end subgraph "Data Tier" G[(Primary DB)] --> H[(Replica DB)] I[Cache Layer] end A --> C B --> C E --> G F --> G E --> I F --> I ``` #### Class Hierarchy Documentation ```mermaid classDiagram class Vehicle { <> +String brand +int year +start() void +stop() void +getInfo()* String } class Car { +int doors +String fuelType +getInfo() String +openTrunk() void } class Motorcycle { +boolean hasSidecar +getInfo() String +popWheelie() void } Vehicle <|-- Car Vehicle <|-- Motorcycle note for Vehicle "Base class for all vehicles" ``` ## ไธŽ mermaid.js ็š„ๅฏนๅบ”ๅ…ณ็ณป ่ฏฅ้กน็›ฎ็š„่ฎพ่ฎกไธฅๆ ผ้ตๅพช mermaid.js ็š„ๅ†…้ƒจๆžถๆž„๏ผš | mermaid.js | mermaid-go | |------------|------------| | `flow.jison` | `pkg/lexer/lexer.go` + `pkg/parser/flowchart.go` | | `flowDb.ts` | `pkg/parser/flowchart.go` (FlowDB) | | `classDiagram.jison` | `pkg/parser/class.go` | | `types.ts` | `pkg/ast/flowchart.go`, `pkg/ast/class.go` | | `flowRenderer.ts` | `pkg/renderer/flowchart.go` | ## ้กน็›ฎไฝœ่€… ็”ฑ gytmtc ๅˆ›ๅปบ๏ผŒๅŸบไบŽ mermaid.js ็š„ๆžถๆž„่ฎพ่ฎก๏ผŒ็Žฐๅทฒๆ‰ฉๅฑ•ๆ”ฏๆŒๅคš็งๅ›พ่กจ็ฑปๅž‹ๅ’Œ้ซ˜็บง็‰นๆ€งใ€‚ ## ๐Ÿ“„ License This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. ## ๐Ÿ™ Acknowledgments - [Mermaid.js](https://mermaid.js.org/) for the original specification and inspiration - The Go community for excellent parsing libraries and patterns - All contributors who help improve this project ## ๐Ÿ“ž Support - **Issues**: [GitHub Issues](https://github.com/your-org/mermaid-go/issues) - **Documentation**: [Wiki](https://github.com/your-org/mermaid-go/wiki) - **Discussions**: [GitHub Discussions](https://github.com/your-org/mermaid-go/discussions) --- **Current Version**: 0.8.0 (Alpha) **Mermaid.js Compatibility**: ~82% of core features **Status**: Active Development