VPasCode Docs
Mermaid.js State Diagram Syntax Guide
What is a State Diagram? A State Diagram (also known as a Statechart) is a behavioral UML diagram that models the finite lifecycle of a single object or subsystem. Recognized as a core UML diagram type, it illustrates the discrete conditions (states) an entity can occupy, the external events or triggers that force a shift between those conditions (transitions), and the conditional rule forks that alter execution pathways. This mapping is essential for tracking complex object lifecycles, such as an order’s progression from fulfillment to delivery, a user session timeout sequence, or an embedded hardware switch loop. With Mermaid.js, you can define your reactive state machines using a declarative, text-driven schema. The parsing engine automatically calculates optimal layout spacing, handles recursive looping arrows, and scales state container boundaries smoothly. Core Syntax Guide: Elements and Constructs To design an accurate, standards-compliant UML state diagram in Mermaid, you must master entry/exit markers, transition strings, composite nesting, and conditional choice blocks. 1. Defining Entry, Exit, and Standard States You initialize a state canvas on line one using the stateDiagram-v2 keyword. Lifecycles require explicit starting and stopping points, which are represented by a solid circle symbol ([*]): Initial State (Entry): [*] –> StateName (Marks where the lifecycle starts). Terminal State (Exit): StateName –> [*] (Marks where the lifecycle concludes). Mermaid Edit Mermaid in VPasCode stateDiagram-v2 [*] –> Idle Idle –> [*] Edit Mermaid in VPasCode 2. Configuring Transition Triggers and Event Labels To map a state change, connect your defined state tokens using a standard arrow line (–>). To document the exact event, API response, or button click that causes this transition, append a colon (:) followed by your descriptive text string: Mermaid Edit Mermaid in VPasCode stateDiagram-v2 Active –> Suspended : PaymentFailed Suspended –> Active : InvoiceSettled Edit Mermaid in VPasCode 3. Implementing Conditional Choice Blocks To handle branching evaluation loops, use the <<choice>> stereotype. This creates a clear diamond shape on the canvas that splits a single inbound transition path into multiple distinct outbound paths based on runtime logic checks: Mermaid Edit Mermaid in VPasCode stateDiagram-v2 state check_status <<choice>> [*] –> check_status check_status –> PremiumUser : if balance >= 100 check_status –> StandardUser : if balance < 100 Edit Mermaid in VPasCode 4. Structuring Composite (Nested) States When modeling a complex system, a single high-level state can contain its own independent inner lifecycle. You can create a nested sub-state layout by defining a parent state followed by a body block wrapped in curly braces: Mermaid Edit Mermaid in VPasCode stateDiagram-v2 state OrderProcessing { [*] –> Packaging Packaging –> Labeling } Edit Mermaid in VPasCode Best Practices for Clean State Machine Layouts Keep State Tokens Short: Use brief CamelCase text strings for your internal state tokens (e.g., AwaitingRefund). If you need a long descriptive title on the canvas, use the state “Descriptive Text Block” as Token syntax to create an explicit alias. Enforce a Single Entry Point: Always start your diagram from a single [*] node. Having multiple starting points can confuse users trying to track the root initialization path of the system. Always Use stateDiagram-v2: Always choose the stateDiagram-v2 keyword over the legacy stateDiagram flag. The v2 rendering engine uses an updated layout algorithm that provides cleaner line routing and better nested box alignments. Real-World Mermaid.js State Diagram Examples Example 1: Digital Wallet Transaction Lifecycle (Choice Branches & Failure Loops) This functional blueprint models the lifecycle of a digital payment transaction, showing how a transaction moves from an initial submission point through a fraud check fork into finalized ledger states. Mermaid Edit Mermaid in VPasCode stateDiagram-v2 state fraud_check <<choice>> [*] –> TransSubmitted TransSubmitted –> fraud_check : ExecuteRiskAssessment fraud_check –> TransApproved : Risk Score Low fraud_check –> TransFlagged : Risk Score Elevated TransFlagged –> TransApproved : ManualManagerOverride TransFlagged –> TransDeclined : SecurityTimeout TransApproved –> SettlementPending : CommitLedger SettlementPending –> TransCompleted : BankSettlementSuccess TransDeclined –> [*] TransCompleted –> [*] Edit Mermaid in VPasCode Syntax Breakdown: This workflow utilizes a <<choice>> block to evaluate safety scores right at the start. The transaction transitions along distinct pathways based on these scores, with clear event names (like ExecuteRiskAssessment) documented directly on the transition arrows. Example 2: E-Commerce Order Fulfillment Pipeline (Composite Nested Systems) This advanced enterprise blueprint outlines a complete shipping and order management lifecycle, using nested composite blocks to show the internal operations happening within the fulfillment phase. Mermaid Edit Mermaid in VPasCode stateDiagram-v2 [*] –> OrderPlaced OrderPlaced –> InFulfillment : PaymentCaptured state InFulfillment { [*] –> ItemPicking ItemPicking –> QualityAudit : BatchPicked QualityAudit –> SecureBoxPacking : AuditPassed SecureBoxPacking –> CarrierManifest Generated : LabelPrinted } InFulfillment –> Shipped : CarrierHandshake Shipped –> Delivered : OutForDeliveryConfirmed Delivered –> [*] Edit Mermaid in VPasCode Syntax Breakdown: By wrapping steps inside the state InFulfillment {…} body block, you create a clear structural boundary on the canvas. The engine treats this block as a single consolidated parent state while rendering its internal workflow steps sequentially, making complex multi-layered lifecycles easy to navigate.
Mermaid.js Mind Map Syntax Guide
What is a Mind Map? A Mind Map is a hierarchical tree-based visualization used to capture, organize, and structure complex information flows, brainstormed ideas, or project taxonomies. Unlike flowcharts that dictate linear procedural steps, mind maps represent connections between a central core concept and its various sub-nodes, making them ideal for high-level roadmap planning, feature breakdown structures, or knowledge management. With Mermaid.js, you define your hierarchical structure using standard Markdown list indentation. The engine automatically handles node positioning, calculates tree growth, and applies distinct node shapes based on the hierarchy level, allowing you to visualize hundreds of interconnected nodes without manual pixel alignment. Core Syntax Guide: Elements and Constructs Designing a valid, production-grade Mind Map in Mermaid requires mastering root node definition, indentation-based level nesting, and visual decorative tokens. 1. Initializing the Mind Map Root You initialize a mind map canvas on line one using the mindmap keyword. The structure is built by defining a root node (the center of your map) and then nesting sub-nodes beneath it using standard space-based indentation: Mermaid Edit Mermaid in VPasCode mindmap root((Central Core Concept)) Level 1 Node Level 2 Sub-node Edit Mermaid in VPasCode 2. Controlling Node Geometry Just like in Flowcharts, you can inject visual context by enclosing your text in specific bracket tokens. This is highly recommended for differentiating between primary categories, secondary tasks, and actionable items: (Text) — Rounded node (Default). ((Text)) — Double-rounded node (Usually reserved for the root). [Text] — Square node. )Text( — Convex/Asymmetric node. {Text} — Hexagonal/Bracket node. 3. Integrating Icons and External Formatting You can enhance node legibility by adding visual icons directly inside the text string using the ::icon(…) syntax. This allows you to quickly distinguish between different types of nodes (e.g., people, software, hardware, or external APIs) at a glance: Mermaid Edit Mermaid in VPasCode mindmap root((System Architecture)) (UI Layer) ::icon(fa fa-desktop) [Web App] (Data Layer) ::icon(fa fa-database) [Primary DB] Edit Mermaid in VPasCode Best Practices for Clear Hierarchy Layouts Keep Node Text Brief: Mind maps should be used for rapid scanning. Keep your node labels to three words or less so the text does not stretch the tree branches beyond the screen width. Use Consistent Geometry: Maintain a strict logic for shapes across your entire tree (e.g., use Square nodes for code components, Hexagonal nodes for API endpoints, and Rounded nodes for physical infrastructure). This consistency makes the map much easier to process. Limit Nesting Depth: Try to keep your map nested no deeper than four or five levels. If a branch requires deeper nesting, consider breaking it out into its own dedicated mind map to keep the overall canvas size manageable. Real-World Mermaid.js Mind Map Examples & Boilerplates Example 1: Software Development Lifecycle (SDLC) Taxonomy This functional blueprint organizes the standard SDLC phases into a categorized tree, using icons to visually highlight the nature of each task grouping. Mermaid Edit Mermaid in VPasCode mindmap root((SDLC Phases)) (Planning) ::icon(fa fa-tasks) [Requirements] [Feasibility] (Development) ::icon(fa fa-code) [Architecture] [Implementation] (Quality) ::icon(fa fa-bug) [Unit Tests] [Integration Tests] (Deployment) ::icon(fa fa-cloud) [CI/CD Pipelines] [Monitoring] Edit Mermaid in VPasCode Syntax Breakdown: By using the root node in the center and indentation for levels, the engine generates branches symmetrically. The ::icon(fa fa-…) syntax injects FontAwesome-compatible glyphs, turning abstract phases into visually distinct, scannable nodes. Example 2: Enterprise Microservice Feature Breakdown This advanced blueprint breaks down an e-commerce platform into technical feature sets, using geometric shapes to distinguish between infrastructure modules and customer-facing interfaces. Mermaid Edit Mermaid in VPasCode mindmap root((E-Commerce Platform)) (User Interface) [Mobile App] [Web Dashboard] (Service Layer) [Auth API] [Order API] (Infrastructure) ((Primary Cloud Provider)) [Redis Cache] [PostgreSQL Instance] Edit Mermaid in VPasCode Syntax Breakdown: This map explicitly uses different shapes to denote logical system components. This clear visual hierarchy allows stakeholders to distinguish between high-level services and underlying data foundations instantly.
Mermaid.js Gantt Chart Syntax Guide
What is a Gantt Chart? A Gantt Chart is a project management visualization tool used to map project schedules, task durations, and critical path milestones along a horizontal timeline. By representing work packages as bars and structural dependencies as sequential flows, it allows teams to track progress, identify potential bottlenecks, and communicate deadlines effectively. With Mermaid.js, you define your project schedule using a declarative, text-based syntax. The engine automatically calculates relative bar offsets, handles date-based grid axis scaling, and renders completion percentages, allowing you to generate professional project roadmaps directly inside your documentation. Core Syntax Guide: Elements and Constructs To design a valid, fully runnable project schedule in Mermaid, you must master the timeline configuration, task declarations, section grouping, and milestone markers. 1. Initializing the Gantt Timeline You initialize a Gantt canvas on line one using the gantt keyword. Every Gantt chart requires a title, a date format definition, and a specific start date to anchor the timeline grid. Mermaid Edit Mermaid in VPasCode gantt title Project Alpha Schedule dateFormat YYYY-MM-DD axisFormat %Y-%m-%d excludes weekends Edit Mermaid in VPasCode 2. Defining Tasks and Durations Tasks are defined by their status (active, done, or crit), a display label, an internal ID, and a time duration. You can specify a duration using days (d), hours (h), or specific start/end dates. done: Completed work package. active: Current, in-progress work. crit: Critical path task (renders in a distinct highlight color). Mermaid Edit Mermaid in VPasCode gantt section Planning Initial Discovery :done, des1, 2026-06-01, 5d Requirement Gathering :active, des2, after des1, 7d Edit Mermaid in VPasCode 3. Implementing Milestones and Dependencies Milestones are zero-duration points that mark significant project achievements. Dependencies are established using the task ID, ensuring that the visual bars align correctly when a predecessor finishes. Mermaid Edit Mermaid in VPasCode gantt section Release Beta Launch :milestone, m1, 2026-07-15, 0d Final QA :crit, qa1, after m1, 10d Edit Mermaid in VPasCode Best Practices for Project Schedules Use Descriptive Section Names: Use the section keyword to group your tasks into logical project phases (e.g., Development, Testing, Deployment). This creates a vertically segmented grid that is much easier to read than a single long list. Leverage the ‘after’ Keyword: Instead of manually calculating dates, use the after [task_id] syntax. This ensures that if the project start date shifts, your entire timeline updates automatically without manual editing. Exclude Non-Working Days: If your project follows a standard business week, include the excludes weekends directive. This keeps your timeline realistic and prevents unrealistic “weekend” work predictions. Real-World Mermaid Gantt Chart Examples Example 1: Software Infrastructure Migration Roadmap This functional blueprint models a multi-stage cloud migration project, utilizing sections to divide architecture planning from implementation and testing. Mermaid Edit Mermaid in VPasCode gantt title Cloud Infrastructure Migration Roadmap dateFormat YYYY-MM-DD axisFormat %m-%d excludes weekends section Architecture Cloud Design :done, a1, 2026-06-01, 10d Security Audit :active, a2, after a1, 5d section Migration Data Transfer :crit, m1, after a2, 15d App Re-deploy :m2, after m1, 8d section Milestones Production Go-Live :milestone, m3, after m2, 0d Edit Mermaid in VPasCode Syntax Breakdown: This chart clearly separates planning, execution, and project milestones. By tagging the `Data Transfer` task as crit, it receives a distinct highlight, drawing the viewer’s attention to the most high-risk phase of the migration.
Mermaid.js Quadrant Chart Syntax Guide
What is a Quadrant Chart? A Quadrant Chart is a strategic visualization tool used to categorize items into four distinct zones based on two continuous variables (e.g., Effort vs. Impact, or Importance vs. Urgency). By placing data points onto a 2D coordinate plane divided by X and Y axes, you can clearly distinguish high-priority “quick wins” from low-priority “distractions” or long-term “strategic bets.” With Mermaid.js, you can define your quadrants, axis titles, and data point positions using a simple declarative block, allowing you to generate professional decision matrices instantly. Core Syntax Guide: Elements and Constructs To design a valid, fully runnable quadrant chart in Mermaid, you must master the coordinate system, axis labeling, and data point placement. 1. Initializing the Quadrant Canvas You initialize a quadrant chart canvas on line one using the quadrantChart keyword. You then define the labels for your four quadrants and the titles for your X and Y axes. Mermaid Edit Mermaid in VPasCode quadrantChart title Project Prioritization Matrix x-axis “Low Effort” –> “High Effort” y-axis “Low Impact” –> “High Impact” quadrant-1 “Strategic Bets” quadrant-2 “Quick Wins” quadrant-3 “Distractions” quadrant-4 “Major Projects” Edit Mermaid in VPasCode 2. Placing Data Points You add items to the chart by providing their display name followed by their X and Y coordinates (normalized between 0 and 1). 0.0 is the start of the axis. 1.0 is the end of the axis. Mermaid Edit Mermaid in VPasCode quadrantChart title Impact vs Effort Matrix x-axis “Low Effort” –> “High Effort” y-axis “Low Impact” –> “High Impact” quadrant-1 “Strategic Bets” quadrant-2 “Quick Wins” quadrant-3 “Distractions” quadrant-4 “Major Projects” “Task A”: [0.2, 0.8] “Task B”: [0.7, 0.2] Edit Mermaid in VPasCode Best Practices for Matrix Mapping Normalize Your Data: Since Mermaid coordinates are scaled from 0.0 to 1.0, map your raw data values into this percentage range before plugging them into the script. Clear Axis Labels: Always include descriptive axis labels that explicitly define what the X and Y axes represent (e.g., “Cost” vs. “ROI”). A matrix without defined axes is just a random scatter plot. Limit Point Density: If you have more than 15-20 points on a single quadrant chart, it will become cluttered and unreadable. If you have a larger data set, consider breaking it into multiple thematic charts. Real-World Mermaid.js Quadrant Chart Examples Example: Product Feature Prioritization Matrix This functional blueprint helps product teams categorize features based on their development effort and potential business impact. Mermaid Edit Mermaid in VPasCode quadrantChart title Product Feature Prioritization x-axis “Low Effort” –> “High Effort” y-axis “Low Impact” –> “High Impact” quadrant-1 “Long-term Bets” quadrant-2 “Quick Wins” quadrant-3 “Low Priority” quadrant-4 “Major Initiatives” “Login API”: [0.1, 0.9] “Theme Customizer”: [0.8, 0.3] “Payment Gateway”: [0.6, 0.8] “Dark Mode”: [0.2, 0.2] Edit Mermaid in VPasCode Syntax Breakdown: By assigning `[0.1, 0.9]` to “Login API”, we place it in the top-left quadrant (high impact, low effort), marking it as a “Quick Win.” This allows stakeholders to instantly visualize the development roadmap priorities.
Mermaid.js Timeline Syntax Guide
What is a Timeline Diagram? A Timeline Diagram is a chronological visualization tool used to map events or project milestones along a linear temporal path. While Gantt charts handle complex task dependencies and durations, the Timeline diagram focuses on the when—providing a clear, scannable narrative of a project’s evolution or a system’s release cycle. With Mermaid.js, you can define your timeline using a simple, hierarchical text format. The engine automatically handles spacing, formatting of dates or period labels, and the alignment of event markers along the central temporal axis. Core Syntax Guide To design a valid, runnable timeline, you must define the axis period and map events to specific sections. 1. Initializing the Timeline You initialize the canvas using the timeline keyword. The structure is built by defining sections (which act as groupings) and mapping events (or dates) to those sections. Mermaid Edit Mermaid in VPasCode timeline title System Development History section 2025 Q1 : Alpha Launch section 2026 Q2 : Beta Release Edit Mermaid in VPasCode 2. Adding Details to Events You can add multiple details to a single time marker by using a colon-separated list. This is useful for summarizing key outcomes or version numbers associated with a specific date or period. Mermaid Edit Mermaid in VPasCode timeline section Q3 2026 Release : v1.0.0 : Performance Improvements : Security Patches Edit Mermaid in VPasCode Real-World Mermaid.js Timing Diagram Example: Product Release Roadmap This blueprint models a multi-year product roadmap, grouping releases by fiscal year and highlighting key deliverables for each cycle. Mermaid Edit Mermaid in VPasCode timeline title Product Roadmap 2026-2027 section 2026 Q1 : Discovery Phase : Stakeholder Interviews Q2 : MVP Development : Core API Design Q3 : Beta Release : User Feedback Loops section 2027 Q1 : Full Launch : Global Scaling Edit Mermaid in VPasCode Best Practices for Timelines Keep Categories Concise: Use section to denote high-level groupings (like years or major phases), keeping the actual events underneath specific and actionable. Consistent Date Formatting: Ensure your timeline events are in chronological order in the code, as the Mermaid engine follows your script’s sequence to determine layout placement. Use Details for Context: Don’t crowd the central axis with too much text. Use the multi-line event format to break down “what happened” rather than making the date label itself too long.
Mermaid.js Flowchart Syntax Guide
What is a Flowchart? A Flowchart is a foundational behavioral map that visualizes a step-by-step operational workflow, algorithmic procedure, or sequential business logic. By representing system actions as distinct geometric shapes and charting the control flow with directional arrows, a flowchart makes it easy for software engineers and systems architects to trace conditional execution paths, isolate single-point-of-failure blocks, and analyze system logic loops before writing actual backend code. With Mermaid.js, you don’t have to spend hours dragging boxes, micro-managing grid lines, or recalculating padding variables. The layout engine computes node coordinates dynamically from your raw declarative scripts, letting you focus entirely on your system’s underlying logic. Core Syntax Guide: Elements and Constructs To design an elegant, highly scannable flowchart in Mermaid, you must master canvas direction indicators, geometric node enclosures, link wiring variables, and structural subgraphs. 1. Setting Canvas Directions The orientation of your flowchart is determined directly on line one by the keyword pairing applied to the graph or flowchart wrapper. You can control the visual scaling direction of your layout using four primary orientation keys: flowchart TD (Top to Down / Vertical orientation) flowchart BU (Bottom to Up orientation) flowchart LR (Left to Right / Horizontal orientation) flowchart RL (Right to Left orientation) 2. Customizing Node Geometry (Shapes) By default, a plain ID declaration renders as a sharp rectangular box. To make your diagrams easier to scan, use Mermaid’s specialized enclosing brackets to inject instant visual context into different workflow steps. Every single definition block must be preceded by a directional layout token to parse correctly: Round Edges: id(Text) — Represents a general process step. Stadium/Capsule Shape: id([Text]) — Standard marker for start and stop boundary milestones. Subroutine/Predefined Process: id[[Text]] — Represents an encapsulated system routine or external class script. Cylinder/Database: id[(Text)] — Represents database persistence, caches, or data warehouses. Rhombus/Decision Diamond: id{Text} — Represents conditional switches, if/else forks, or evaluation points. Parallelogram: id[/Text/] or id[\Text\] — Renders skewed boundaries to represent explicit data Input/Output (I/O). Mermaid Edit Mermaid in VPasCode flowchart TD start_node([Start Execution]) query_db[(PostgreSQL Instance)] validate_check{Is Authorized?} Edit Mermaid in VPasCode 3. Link Wiring Rules and Inlined Labels You can adjust your connector lines to represent different structural relationships and communication styles. To keep your charts clean, inject descriptive labels directly onto your link paths: Mermaid Edit Mermaid in VPasCode flowchart TD %% Standard connector arrow with text label A –> |”JSON Payload”| B %% Dotted/Asynchronous line with text label B -.-> |”Async Event”| C %% Thick bolded line with text label C ==> |”Critical Write”| D Edit Mermaid in VPasCode 4. Modular Isolation via Subgraphs To establish clean network perimeters, group microservices, or isolate team responsibilities, group your elements inside structural subgraph wrappers. You define a subgraph by giving it an internal ID, an optional display title, and closing it with an end tag: Mermaid Edit Mermaid in VPasCode flowchart TD subgraph auth_sub[“Security Boundary”] gateway[API Gateway] –> auth_worker(Token Validator) end Edit Mermaid in VPasCode Best Practices for Clean Flowcharts Decouple Layouts Horizontally: For long, multi-step engineering pipelines, choose a flowchart LR direction. This scales much cleaner on standard widescreen landscape monitors than a long vertical layout. Isolate Complex Loops: If a workflow contains a heavy repetition loop, label the reverse connector clearly (e.g., retry –> |”Attempt Reset”| start) to prevent readers from confusing the loop with a standard forward path. Avoid Mixing Graph Types: Stick to the modern flowchart keyword over the legacy graph flag when rendering complex maps. The flowchart engine uses an updated layout algorithm that supports advanced arrow combinations and cleaner path routing. Real-World Mermaid.js Flowchart Examples Example 1: Microservice Event-Driven Ingestion Mesh (Left-to-Right Architecture) This functional blueprint models a web telemetry ingestion service. It demonstrates how to combine data inputs, decision diamonds, and cloud database shapes across a crisp horizontal canvas. Mermaid Edit Mermaid in VPasCode flowchart LR %% Define element nodes with explicit geometry shapes init([Webhook Fired]) –> input_io[/Capture HTTP Request/] input_io –> auth_check{Validate Token} auth_check –> |”Invalid Token”| err_stop([Return 401 Unauthorized]) auth_check –> |”Valid JWT”| write_queue[[Publish to Kafka Queue]] write_queue –> worker_proc(Consumer Daemon) worker_proc –> db_store[(TimescaleDB Cluster)] db_store –> term([Terminated Flow]) %% Quick custom style overrides style auth_check fill:#fff3cd,stroke:#ffc107,stroke-width:2px style err_stop fill:#f8d7da,stroke:#dc3545,stroke-width:1px Edit Mermaid in VPasCode Syntax Breakdown: This diagram flows smoothly from left to right. The validation step uses a yellow decision diamond shape (auth_check{Validate Token}), which splits the execution path cleanly into two distinct outcomes. The data stores are instantly recognizable thanks to their custom database cylinders ([(TimescaleDB Cluster)]) and parallelogram inputs. Example 2: Enterprise Multi-Tier User Registration Engine (Vertical with Nested Subgraphs) This advanced enterprise blueprint maps out an application registration pipeline. It organizes steps vertically across three separate structural subgraphs to represent distinct architectural layers. Mermaid Edit Mermaid in VPasCode flowchart TD subgraph Client_Tier[“Presentation UI Layer”] app[Mobile App UI] web[Web SPA Frontend] end subgraph Service_Tier[“Core Gateway Router”] proxy[[Nginx Ingress Reverse Proxy]] auth_svc(Auth Service Worker) end subgraph Persistence_Tier[“Secured Data Center”] main_db[(User Accounts Primary DB)] cache_node[(Redis Session Cache)] end %% Define communication pipelines across subsystem layers app — “HTTPS Request” –> proxy web — “HTTPS Request” –> proxy proxy –> |”Route /v1/auth”| auth_svc auth_svc –> |”Verify Session”| cache_node auth_svc –> |”Commit Account”| main_db Edit Mermaid in VPasCode Syntax Breakdown: The top-to-down orientation indicator (flowchart TD) forces the layout engine to stack components cleanly from top to bottom. Bounding blocks group related components into distinct layers (Client, Service, and Persistence), giving the overall architecture an intuitive, highly structured feel.