### Complete ER Diagram Example Setup Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/docs/pages/mermaid/erdiagram/Link.mdx Sets up entities and their attributes for a complete ER diagram example, including CUSTOMER, ORDER, PRODUCT, and ORDER_ITEM. ```python from mermaid import Mermaid from mermaid.erdiagram import ERDiagram, Entity, Link # Create entities customer = Entity("CUSTOMER") customer.add_attribute("cust_id", "int", constraint="PK") customer.add_attribute("name", "string") customer.add_attribute("email", "string", constraint="UK") order = Entity("ORDER") order.add_attribute("order_id", "int", constraint="PK") order.add_attribute("cust_id", "int", constraint="FK") order.add_attribute("order_date", "datetime") order.add_attribute("total", "decimal") product = Entity("PRODUCT") product.add_attribute("prod_id", "int", constraint="PK") product.add_attribute("name", "string") product.add_attribute("price", "decimal") order_item = Entity("ORDER_ITEM") order_item.add_attribute("order_id", "int", constraint="FK PK") order_item.add_attribute("prod_id", "int", constraint="FK PK") order_item.add_attribute("quantity", "int") order_item.add_attribute("unit_price", "decimal") ``` -------------------------------- ### SaaS Application Onboarding User Journey Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/docs/pages/mermaid/userjourney/UserJourney.mdx Illustrates a user journey for SaaS application onboarding, covering signup, initial setup, and regular usage phases. This example demonstrates defining tasks and sections for a software-as-a-service product. ```python from mermaid import Mermaid from mermaid.userjourney import UserJourney, Section, Task, Actor user = Actor("New User") system = Actor("Platform") sections = [ Section("Signup", [ Task("Create account", 4, user), Task("Verify email", 3, system), Task("Set password", 4, user) ]), Section("Onboarding", [ Task("Complete profile", 3, user), Task("Take tutorial", 4, system), Task("Invite team member", 4, user) ]), Section("First Use", [ Task("Create first project", 5, user), Task("Add collaborators", 4, user), Task("Enable notifications", 3, user) ]), Section("Regular Usage", [ Task("Daily work", 5, user), Task("Collaborate", 5, user) ]) ] diagram = UserJourney( title="SaaS Platform Onboarding", sections=sections ) ``` -------------------------------- ### Install Dependencies Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/CONTRIBUTING.md Install project dependencies using the provided Makefile. ```bash make install ``` -------------------------------- ### Complete Entity Example Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/docs/pages/mermaid/erdiagram/Entity.mdx A comprehensive example showing the creation of a 'USER' entity with various attributes, constraints, and comments. ```APIDOC ## Complete Example ```python from mermaid.erdiagram import Entity # User entity user = Entity("USER") user.add_attribute("user_id", "int", constraint="PK") user.add_attribute("username", "string", constraint="UK") user.add_attribute("email", "string", constraint="UK") user.add_attribute("password_hash", "string") user.add_attribute("first_name", "string") user.add_attribute("last_name", "string") user.add_attribute("profile_image_url", "string") user.add_attribute("bio", "text", comment="User biography") user.add_attribute("created_at", "datetime") user.add_attribute("updated_at", "datetime") user.add_attribute("is_active", "boolean") ``` ``` -------------------------------- ### Complete Entity Example Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/docs/pages/mermaid/erdiagram/Entity.mdx A comprehensive example demonstrating the creation of a 'USER' entity with various attributes, including Primary Key (PK), Unique Key (UK), and comments. ```python from mermaid.erdiagram import Entity # User entity user = Entity("USER") user.add_attribute("user_id", "int", constraint="PK") user.add_attribute("username", "string", constraint="UK") user.add_attribute("email", "string", constraint="UK") user.add_attribute("password_hash", "string") user.add_attribute("first_name", "string") user.add_attribute("last_name", "string") user.add_attribute("profile_image_url", "string") user.add_attribute("bio", "text", comment="User biography") user.add_attribute("created_at", "datetime") user.add_attribute("updated_at", "datetime") user.add_attribute("is_active", "boolean") ``` -------------------------------- ### Complete Sequence Diagram Example Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/docs/pages/mermaid/sequence/SequenceDiagram.mdx A comprehensive example combining multiple elements like actors, participants, links, and notes to create a complex sequence diagram for a login process. ```python from mermaid import Mermaid from mermaid.sequence import ( SequenceDiagram, Actor, Participant, Link, ArrowTypes, Alt, Note, NotePosition ) # Create participants user = Actor("User") web_app = Participant("Web App") api_server = Participant("API Server") database = Participant("Database") # Create interactions msg1 = Link(user, web_app, ArrowTypes.SOLID_ARROW, "Login request") msg2 = Link(web_app, api_server, ArrowTypes.SOLID_ARROW, "Authenticate") msg3 = Link(api_server, database, ArrowTypes.SOLID_ARROW, "Query user") msg4 = Link(database, api_server, ArrowTypes.DOTTED_ARROW, "User record") # Add a note note = Note( "Validation check", api_server, position=NotePosition.RIGHT_OF ) # Example of adding more elements to the diagram (not fully shown in source) # msg5 = Link(api_server, web_app, ArrowTypes.DOTTED_ARROW, "Login status") # msg6 = Link(web_app, user, ArrowTypes.SOLID_ARROW, "Welcome message") # diagram = SequenceDiagram( # title="User Login Flow", # elements=[ # user, web_app, api_server, database, # msg1, msg2, msg3, msg4, note #, msg5, msg6 # ] # ) # Mermaid(diagram) ``` -------------------------------- ### Start Local Mermaid.ink Server Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/CONTRIBUTING.md Start the local mermaid.ink server for testing diagrams locally. Ensure the MERMAID_INK_SERVER environment variable is set to use this local server. ```bash make mermaid.ink/up ``` -------------------------------- ### Install Pre-commit Hooks Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/CONTRIBUTING.md Install pre-commit hooks to ensure code quality checks are run before commits. ```bash make install/pre-commit ``` -------------------------------- ### Complete Mindmap Example with Shapes and Icons Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/docs/pages/mermaid/mindmap/Mindmap.mdx Illustrates a comprehensive mindmap creation, including setting shapes for nodes and the root, and defining a multi-level structure for a product roadmap. This example showcases advanced customization options. ```python from mermaid import Mermaid from mermaid.mindmap import Mindmap, Level, LevelShape from mermaid.icon import Icon # Create mindmap structure roadmap = Mindmap( title="Product Roadmap 2024", levels=[ Level("Q1", [ Level("Feature A", shape=LevelShape.SQUARE), Level("Bug Fixes", [ Level("Critical Bugs"), Level("Minor Bugs") ]), Level("Documentation") ]), Level("Q2", [ Level("Feature B"), Level("Performance", [ Level("Optimization"), Level("Monitoring") ]), Level("DevOps") ]), Level("Q3", [ Level("Feature C"), Level("Integration"), Level("Testing") ]), Level("Q4", [ Level("Release"), Level("Support"), Level("Planning") ]) ], shape=LevelShape.ROUNDED_SQUARE ) Mermaid(roadmap) ``` -------------------------------- ### Complete Node Setup with Styles and Shapes Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/docs/pages/mermaid/flowchart/Node.mdx Demonstrates setting up nodes with custom shapes, styles, and hyperlinks for different states or actions. ```python from mermaid.flowchart import Node from mermaid.style import Style from mermaid import Direction # Define custom styles success = Style(name="success", fill="#90ee90", color="black") error = Style(name="error", fill="#ffb6c6", color="black") # Create nodes with different characteristics input_node = Node( "data_input", "Receive Data", shape="cylinder", styles=[success] ) process_node = Node( "validate", "Validate Format", shape="normal" ) decision_node = Node( "is_valid", "Valid Data?", shape="rhombus" ) error_node = Node( "log_error", "Log Error", shape="normal", href="https://logs.example.com", styles=[error] ) output_node = Node( "store", "Store Data", shape="cylinder" ) ``` -------------------------------- ### Complete Requirement Diagram Example Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/docs/pages/mermaid/reqdiagram/RequirementDiagram.mdx A comprehensive example showcasing the creation of a Requirement Diagram with multiple elements, various requirement types (functional, performance, security), and complex relationships. This example illustrates a more advanced use case. ```python from mermaid import Mermaid from mermaid.reqdiagram import ( RequirementDiagram, Requirement, Element, Link, Type, Risk, VerifyMethod ) # Define system elements ui = Element("UI_001", "User Interface", "System") api = Element("API_001", "REST API", "System") db = Element("DB_001", "Database", "Database") auth = Element("AUTH_001", "Authentication Service", "System") # Define functional requirements req_auth = Requirement( "F_001", "Authentication", "Users must be able to authenticate using credentials", Type.FUNCTIONAL, Risk.HIGH, VerifyMethod.TEST ) req_ui = Requirement( "F_002", "User Interface", "System must provide user-friendly interface", Type.INTERFACE, Risk.MEDIUM, VerifyMethod.INSPECTION ) req_perf = Requirement( "P_001", "Response Time", "API must respond within 500ms", Type.PERFORMANCE, Risk.HIGH, VerifyMethod.TEST ) req_security = Requirement( "S_001", "Data Security", "All data must be encrypted in transit", Type.DESIGN_CONSTRAINT, Risk.HIGH, VerifyMethod.INSPECTION ) # Create relationships links = [ Link(req_auth, auth, "verifies"), Link(req_ui, ui, "implements"), Link(req_perf, api, "constrains"), Link(req_security, db, "applies_to"), Link(auth, api, "uses"), Link(api, db, "queries") ] # Create diagram diagram = RequirementDiagram( title="Software Requirements Specification", elements=[ui, api, db, auth], requirements=[req_auth, req_ui, req_perf, req_security], links=links ) Mermaid(diagram) ``` -------------------------------- ### Complete State Diagram Example Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/docs/pages/mermaid/statediagram/StateDiagram.mdx A comprehensive example demonstrating the creation of a complex state diagram with various elements including styles, composite states, and choice points. This showcases advanced customization and workflow representation. ```python from mermaid import Mermaid, Direction from mermaid.statediagram import ( StateDiagram, State, Start, End, Transition, Composite, Choice ) from mermaid.style import Style # Define styles warning_style = Style(name="warning", fill="#FFB6C1", color="black") success_style = Style(name="success", fill="#90EE90", color="black") # Create states start = Start() # Main workflow states pending = State("pending", "Pending", styles=[warning_style]) processing = State("processing", "Processing") completed = State("completed", "Completed", styles=[success_style]) failed = State("failed", "Failed", styles=[warning_style]) # Sub-states for processing validate = State("validate", "Validate Input") execute = State("execute", "Execute") cleanup = State("cleanup", "Cleanup") processing_composite = Composite( "proc", "Processing", sub_states=[validate, execute, cleanup], transitions=[ Transition(validate, execute, "valid"), Transition(execute, cleanup, "done") ] ) end = End() # Choice point for results result_choice = Choice( "check_result", processing_composite, [completed, failed], ["success", "error"] ) # State transitions transitions = [ Transition(start, pending, "submit"), Transition(pending, processing_composite, "start"), result_choice, Transition(failed, pending, "retry"), Transition(completed, end) ] # Create diagram diagram = StateDiagram( title="Complex Workflow", states=[start, pending, processing_composite, completed, failed, end], transitions=transitions, direction=Direction.TOP_TO_BOTTOM ) Mermaid(diagram) ``` -------------------------------- ### Simple Entity Example Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/docs/pages/mermaid/erdiagram/Entity.mdx Demonstrates creating a simple entity with basic attributes. ```APIDOC ## Simple Entity ```python from mermaid.erdiagram import Entity product = Entity("PRODUCT", { "product_id": "int", "name": "string", "price": "decimal", "quantity": "int" }) ``` ``` -------------------------------- ### Complete FlowChart Example with Styles and Links Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/docs/pages/mermaid/flowchart/FlowChart.mdx A comprehensive example demonstrating the creation of a complex flowchart with custom styles for nodes, various link types, and a specified orientation. Imports include `Mermaid`, `Direction`, `FlowChart`, `Node`, `Link`, `LinkHead`, `LinkShape`, and `Style`. ```python from mermaid import Mermaid, Direction from mermaid.flowchart import FlowChart, Node, Link, LinkHead, LinkShape from mermaid.style import Style # Create styles success_style = Style( name="success", fill="#90EE90", color="white", stroke="#228B22" ) error_style = Style( name="error", fill="#FFB6C6", color="white", stroke="#DC143C", stroke_width="2px" ) # Create nodes start = Node("start", "Start", shape="stadium-shape") input_node = Node("input", "Input Data", shape="normal") process = Node("process", "Validate", shape="normal", styles=[success_style]) error = Node("error", "Error Handling", shape="normal", styles=[error_style]) output = Node("output", "Output", shape="normal") end = Node("end", "End", shape="stadium-shape") # Create links links = [ Link(start, input_node), Link(input_node, process), Link(process, output, message="Valid"), Link(process, error, message="Invalid", head_left=LinkHead.ARROW), Link(error, input_node), Link(output, end) ] # Create flowchart flowchart = FlowChart( title="Data Validation Flow", nodes=[start, input_node, process, error, output, end], links=links, orientation=Direction.TOP_TO_BOTTOM ) diagram = Mermaid(flowchart) diagram # Save to file flowchart.save("validation_flow.mmd") ``` -------------------------------- ### Install mermaid-py Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/docs/pages/get-started.mdx Install the mermaid-py package using pip. This command should be run in your terminal or command prompt. ```bash pip install mermaid-py ``` -------------------------------- ### Simple Link Example Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/docs/pages/mermaid/flowchart/Link.mdx Demonstrates how to create a basic link between two nodes. ```python from mermaid.flowchart import Node, Link start = Node("start", "Start") process = Node("process", "Process") # Create a simple link link = Link(start, process) print(link.to_mermaid()) ``` -------------------------------- ### Parallel Node Setup Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/docs/pages/mermaid/flowchart/Node.mdx Create a parallel node with multiple sub-nodes and specify the direction of flow. ```python parallel = Node( "parallel", "Parallel Tasks", sub_nodes=[task_a, task_b, task_c], direction=Direction.LEFT_TO_RIGHT ) ``` -------------------------------- ### Create a Project Planning Mindmap Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/docs/pages/mermaid/mindmap/Mindmap.mdx This example shows how to structure a project plan as a mindmap, breaking down a website redesign into phases like Design, Development, Testing, and Launch. It illustrates organizing project tasks and milestones. ```python project = Mindmap( title="Website Redesign", levels=[ Level("Design", [ Level("Visual Design"), Level("User Experience"), Level("Prototyping") ]), Level("Development", [ Level("Frontend", [ Level("HTML/CSS"), Level("JavaScript") ]), Level("Backend", [ Level("Database"), Level("API") ]) ]), Level("Testing", [ Level("Unit Tests"), Level("Integration Tests"), Level("User Testing") ]), Level("Launch", [ Level("Deploy"), Level("Monitor"), Level("Support") ]) ] ) ``` -------------------------------- ### One-to-One Relationship Example Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/docs/pages/mermaid/erdiagram/Link.mdx Example demonstrating how to create a one-to-one relationship between two entities using the Link class. ```APIDOC ## One-to-One Relationship Example ### Description Illustrates creating a link where one entity is related to exactly one of another entity. ### Code ```python from mermaid.erdiagram import Entity, Link user = Entity("USER", {"user_id": ["int", "PK"]}) profile = Entity("PROFILE", {"profile_id": ["int", "PK"], "user_id": ["int", "FK UK"]}) # One user has one profile link = Link( user, profile, "exactly-one", # One user "exactly-one", # Has exactly one profile label="has" ) ``` ``` -------------------------------- ### One-to-Many Relationship Example Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/docs/pages/mermaid/erdiagram/Link.mdx Example demonstrating how to create a one-to-many relationship between two entities using the Link class. ```APIDOC ## One-to-Many Relationship Example ### Description Illustrates creating a link where one entity is related to zero or more of another entity. ### Code ```python from mermaid.erdiagram import Entity, Link user = Entity("USER", {"user_id": ["int", "PK"]}) post = Entity("POST", {"post_id": ["int", "PK"], "user_id": ["int", "FK"]}) # One user creates many posts link = Link( origin=user, end=post, origin_cardinality="exactly-one", # One user end_cardinality="zero-or-more", # Creates 0 or many posts label="creates" ) ``` ``` -------------------------------- ### Start State Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/docs/pages/mermaid/statediagram/StateDiagram.mdx Represents the starting point of a state diagram. ```APIDOC ## Start State ### Description Represents the initial state, typically denoted by [*]. ### Constructor ```python Start() ``` ``` -------------------------------- ### Many-to-Many Relationship Example Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/docs/pages/mermaid/erdiagram/Link.mdx Example demonstrating how to create a many-to-many relationship between two entities using the Link class. ```APIDOC ## Many-to-Many Relationship Example ### Description Illustrates creating a link where multiple entities of one type are related to multiple entities of another type. ### Code ```python from mermaid.erdiagram import Entity, Link student = Entity("STUDENT", {"student_id": ["int", "PK"]}) course = Entity("COURSE", {"course_id": ["int", "PK"]}) # Many students enroll in many courses link = Link( student, course, "one-or-more", # Student enrolls in 1 or more courses "one-or-more", # Course has 1 or more students label="enrolls_in" ) ``` ``` -------------------------------- ### Create a Simple Sequence Diagram Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/docs/pages/mermaid/sequence/SequenceDiagram.mdx Illustrates the basic setup for creating a sequence diagram by defining actors, participants, and their interactions with various arrow types. ```python from mermaid import Mermaid from mermaid.sequence import ( SequenceDiagram, Actor, Participant, Link, ArrowTypes ) # Create participants alice = Actor("Alice") bob = Participant("Bob") server = Participant("Server") # Create interactions msg1 = Link(alice, bob, ArrowTypes.SOLID_LINE, "Hello Bob!") msg2 = Link(bob, server, ArrowTypes.SOLID_ARROW, "Process request") msg3 = Link(server, bob, ArrowTypes.DOTTED_LINE, "Response") msg4 = Link(bob, alice, ArrowTypes.SOLID_ARROW, "Hello Alice!") # Create diagram diagram = SequenceDiagram( title="Simple Interaction", elements=[alice, bob, server, msg1, msg2, msg3, msg4] ) Mermaid(diagram) ``` -------------------------------- ### Link with Message Example Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/docs/pages/mermaid/flowchart/Link.mdx Shows how to add descriptive text to a link. ```python from mermaid.flowchart import Node, Link decision = Node("check", "Valid?", shape="rhombus") success = Node("success", "Continue") error = Node("error", "Error") link_yes = Link(decision, success, message="Yes") link_no = Link(decision, error, message="No") print(link_yes.to_mermaid()) print(link_no.to_mermaid()) ``` -------------------------------- ### Reading Cardinality Example Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/docs/pages/mermaid/erdiagram/Link.mdx Provides an example of how to read and interpret cardinality symbols in an ER diagram link, translating them into a natural language description of the relationship. ```text USER ||--o{ POST : creates Read as: "One USER creates zero or more POSTs" - `||` at USER: "One user" - `--`: "creates" - `o{` at POST: "zero or more posts" ``` -------------------------------- ### Optional Relationship (Identifying Relationship) Example Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/docs/pages/mermaid/erdiagram/Link.mdx Example demonstrating how to create an identifying relationship (weak entity) using a dotted line. ```APIDOC ## Optional Relationship (Identifying Relationship) Example ### Description Illustrates creating a link for an identifying relationship, typically between a strong and a weak entity, using a dotted line. ### Code ```python from mermaid.erdiagram import Entity, Link order = Entity("ORDER", {"order_id": ["int", "PK"]}) item = Entity("ORDER_ITEM", {"order_id": ["int", "FK PK"], "item_no": ["int", "PK"]}) # Use dotted line for identifying relationships link = Link( order, item, "exactly-one", "one-or-more", label="contains", dotted=True # Indicates a weak entity relationship ) ``` ``` -------------------------------- ### One-to-One Relationship Example Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/docs/pages/mermaid/erdiagram/Link.mdx Demonstrates the creation of a one-to-one relationship between a USER entity and a PROFILE entity, where each user has exactly one profile. ```python user = Entity("USER", {"user_id": ["int", "PK"]}) profile = Entity("PROFILE", {"profile_id": ["int", "PK"], "user_id": ["int", "FK UK"]}) # One user has one profile link = Link( user, profile, "exactly-one", # One user "exactly-one", # Has exactly one profile label="has" ) ``` -------------------------------- ### Entity with Constraints Example Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/docs/pages/mermaid/erdiagram/Entity.mdx Shows how to define an entity with primary and unique key constraints. ```APIDOC ## Entity with Constraints ```python user = Entity("USER") user.add_attribute("user_id", "int", constraint="PK") user.add_attribute("email", "string", constraint="UK") user.add_attribute("username", "string", constraint="UK") user.add_attribute("password", "string") user.add_attribute("is_active", "boolean") ``` ``` -------------------------------- ### Entity with Multiple Constraints Example Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/docs/pages/mermaid/erdiagram/Entity.mdx Demonstrates an entity with attributes having multiple constraints like 'FK PK'. ```APIDOC ## Entity with Multiple Constraints ```python enrollment = Entity("ENROLLMENT") enrollment.add_attribute("student_id", "int", constraint="FK PK") enrollment.add_attribute("course_id", "int", constraint="FK PK") enrollment.add_attribute("grade", "char") enrollment.add_attribute("enrollment_date", "datetime") ``` ``` -------------------------------- ### Pie Chart Data Format Example Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/docs/pages/mermaid/piechart/PieChart.mdx Illustrates the expected dictionary format for pie chart data, where keys are category labels and values are numeric. Shows how values are converted to percentages. ```python data = { "Category A": 100, "Category B": 50, "Category C": 25, "Category D": 25 } # Results in: A=50%, B=25%, C=12.5%, D=12.5% ``` -------------------------------- ### Link with Different Shapes Example Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/docs/pages/mermaid/flowchart/Link.mdx Illustrates using different shapes for the link line. ```python from mermaid.flowchart import Node, Link, LinkShape input_node = Node("input", "Input") process = Node("process", "Processing") output = Node("output", "Output") # Different link shapes normal_link = Link(input_node, process) # Default dotted_link = Link(input_node, output, shape=LinkShape.DOTTED) thick_link = Link(process, output, shape="thick") hidden_link = Link(process, output, shape=LinkShape.HIDDEN) print(normal_link.to_mermaid()) print(dotted_link.to_mermaid()) print(thick_link.to_mermaid()) print(hidden_link.to_mermaid()) ``` -------------------------------- ### Create a Learning Path Mindmap Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/docs/pages/mermaid/mindmap/Mindmap.mdx A practical example of creating a mindmap to outline a learning path, organizing topics from fundamentals to advanced concepts. This demonstrates structuring educational content hierarchically. ```python learning = Mindmap( title="Python Learning Path", levels=[ Level("Fundamentals", [ Level("Variables"), Level("Data Types"), Level("Control Flow") ]), Level("OOP", [ Level("Classes"), Level("Inheritance"), Level("Polymorphism") ]), Level("Libraries", [ Level("NumPy"), Level("Pandas"), Level("Matplotlib") ]), Level("Advanced", [ Level("Async"), Level("Decorators"), Level("Metaclasses") ]) ] ) ``` -------------------------------- ### One-to-Many Relationship Example Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/docs/pages/mermaid/erdiagram/Link.mdx Illustrates how to create a one-to-many relationship between a USER entity and a POST entity, where one user creates zero or more posts. ```python from mermaid.erdiagram import Entity, Link user = Entity("USER", {"user_id": ["int", "PK"]}) post = Entity("POST", {"post_id": ["int", "PK"], "user_id": ["int", "FK"]}) # One user creates many posts link = Link( origin=user, end=post, origin_cardinality="exactly-one", # One user end_cardinality="zero-or-more", # Creates 0 or many posts label="creates" ) ``` -------------------------------- ### Link with Different Arrow Heads Example Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/docs/pages/mermaid/flowchart/Link.mdx Demonstrates applying various arrow or symbol types to the link ends. ```python from mermaid.flowchart import Node, Link, LinkHead node_a = Node("a", "Node A") node_b = Node("b", "Node B") node_c = Node("c", "Node C") node_d = Node("d", "Node D") # Different arrow styles link1 = Link(node_a, node_b, head_right=LinkHead.ARROW) # Standard arrow link2 = Link(node_a, node_c, head_right=LinkHead.BULLET) # Bullet point link3 = Link(node_a, node_d, head_right=LinkHead.CROSS) # Cross mark print(link1.to_mermaid()) print(link2.to_mermaid()) print(link3.to_mermaid()) ``` -------------------------------- ### Complete Blog Platform ER Diagram Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/docs/pages/mermaid/erdiagram/ERDiagram.mdx A comprehensive example demonstrating the creation of entities (USER, POST, COMMENT, TAG, POST_TAG) and their relationships (one-to-many, many-to-many with identifying) for a blog platform. It then generates and visualizes the ER diagram. ```python from mermaid import Mermaid from mermaid.erdiagram import ERDiagram, Entity, Link # Create entities user = Entity("USER") user.add_attribute("user_id", "int", constraint="PK") user.add_attribute("username", "string", constraint="UK") user.add_attribute("email", "string", constraint="UK") user.add_attribute("password", "string") user.add_attribute("created_at", "datetime") post = Entity("POST") post.add_attribute("post_id", "int", constraint="PK") post.add_attribute("user_id", "int", constraint="FK") post.add_attribute("title", "string") post.add_attribute("content", "text") post.add_attribute("created_at", "datetime") post.add_attribute("updated_at", "datetime") comment = Entity("COMMENT") comment.add_attribute("comment_id", "int", constraint="PK") comment.add_attribute("post_id", "int", constraint="FK") comment.add_attribute("user_id", "int", constraint="FK") comment.add_attribute("content", "text") comment.add_attribute("created_at", "datetime") tag = Entity("TAG") tag.add_attribute("tag_id", "int", constraint="PK") tag.add_attribute("name", "string", constraint="UK") post_tag = Entity("POST_TAG") post_tag.add_attribute("post_id", "int", constraint="FK PK") post_tag.add_attribute("tag_id", "int", constraint="FK PK") # Create relationships user_posts = Link( user, post, "exactly-one", "zero-or-more", "creates" ) posts_comments = Link( post, comment, "exactly-one", "zero-or-more", "has" ) user_comments = Link( user, comment, "exactly-one", "zero-or-more", "writes" ) post_tags = Link( post, tag, "one-or-more", "one-or-more", "tagged_with", dotted=True ) # Create diagram diagram = ERDiagram( title="Blog Platform Database", entities=[user, post, comment, tag, post_tag], links=[user_posts, posts_comments, user_comments, post_tags] ) diagram_visual = Mermaid(diagram) diagram_visual # Save diagram diagram.save("blog_schema.mmd") ``` -------------------------------- ### Dark Theme Configuration Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/docs/pages/mermaid/configuration/Config.mdx A simple configuration setting for the DARK theme. This is a minimal example of applying a predefined theme. ```python config = Config(theme=Themes.DARK) ``` -------------------------------- ### Bidirectional Arrows Example Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/docs/pages/mermaid/flowchart/Link.mdx Shows how to create links with arrows on both ends or mixed arrow types. ```python from mermaid.flowchart import Node, Link, LinkHead node_a = Node("a", "Node A") node_b = Node("b", "Node B") # Create bidirectional link bidirectional = Link( node_a, node_b, head_left=LinkHead.ARROW, head_right=LinkHead.ARROW, message="Bidirectional" ) # Link with bullet on left, arrow on right mixed = Link( node_a, node_b, head_left=LinkHead.BULLET, head_right=LinkHead.ARROW ) print(bidirectional.to_mermaid()) print(mixed.to_mermaid()) ``` -------------------------------- ### Many-to-Many Relationship Example Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/docs/pages/mermaid/erdiagram/Link.mdx Shows how to define a many-to-many relationship between STUDENT and COURSE entities, indicating that many students enroll in many courses. ```python student = Entity("STUDENT", {"student_id": ["int", "PK"]}) course = Entity("COURSE", {"course_id": ["int", "PK"]}) # Many students enroll in many courses link = Link( student, course, "one-or-more", # Student enrolls in 1 or more courses "one-or-more", # Course has 1 or more students label="enrolls_in" ) ``` -------------------------------- ### Create a Complete E-Commerce User Journey Diagram Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/docs/pages/mermaid/userjourney/UserJourney.mdx Constructs a detailed user journey for an e-commerce scenario, spanning multiple sections like Discovery, Selection, Checkout, Confirmation, and Delivery. This example showcases defining multiple tasks with different actors and scores within each section. ```python from mermaid import Mermaid from mermaid.userjourney import UserJourney, Section, Task, Actor # Create actors customer = Actor("Customer") support = Actor("Support Agent") system = Actor("System") # Section 1: Discovery discovery_tasks = [ Task("Search for products", 5, customer), Task("View search results", 4, system), Task("Read reviews", 4, customer) ] # Section 2: Selection selection_tasks = [ Task("View product details", 5, customer), Task("Check inventory", 5, system), Task("Add to cart", 5, customer) ] # Section 3: Checkout checkout_tasks = [ Task("Review cart", 4, customer), Task("Enter shipping info", 3, customer), Task("Process payment", 3, system) ] # Section 4: Confirmation confirmation_tasks = [ Task("Order confirmation", 5, customer), Task("Send confirmation email", 4, system), Task("Track shipment", 3, customer) ] # Section 5: Delivery & Support delivery_tasks = [ Task("Receive package", 5, customer), Task("Unbox product", 4, customer), Task("Contact support (if needed)", 2, [customer, support]) ] # Create sections sections = [ Section("Discovery", discovery_tasks), Section("Selection", selection_tasks), Section("Checkout", checkout_tasks), Section("Confirmation", confirmation_tasks), Section("Delivery", delivery_tasks) ] # Create diagram diagram = UserJourney( title="E-Commerce User Journey", sections=sections ) Mermaid(diagram) ``` -------------------------------- ### Customer Satisfaction Pie Chart Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/docs/pages/mermaid/piechart/PieChart.mdx An example of creating a pie chart to visualize customer satisfaction levels. Data values are displayed on the chart. ```python satisfaction = { "Very Satisfied": 45, "Satisfied": 35, "Neutral": 12, "Dissatisfied": 6, "Very Dissatisfied": 2 } pie = PieChart( title="Customer Satisfaction Survey", data=satisfaction, show_data=True ) ``` -------------------------------- ### Mermaid Diagram Syntax Example Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/docs/pages/get-started.mdx This is the Mermaid syntax that will be rendered by the Python code. It defines a top-down graph with various nodes and connections. ```mermaid graph TD; mer(Mermaid) flow(FlowChart); clas(ClassDiagram) gra(Graph) erDigram(ERDiagram) erdiagram-link(Link) entity(Entity) flow-link(Link) node(Node) mer --> flow mer --> clas mer --> gra mer --> erDigram flow --> node & flow-link erDigram --> entity & erdiagram-link ``` -------------------------------- ### Create a Mermaid Graph in Python Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/docs/pages/get-started.mdx Import necessary modules and define a graph using a Mermaid diagram syntax string. This example creates a basic flowchart. ```python import mermaid as md from mermaid.graph import Graph graph: Graph = Graph('first-graph',""" graph TD; mer(Mermaid) flow(FlowChart); clas(ClassDiagram) gra(Graph) erDigram(ERDiagram) erdiagram-link(Link) entity(Entity) flow-link(Link) node(Node) mer --> flow mer --> clas mer --> gra mer --> erDigram flow --> node & flow-link erDigram --> entity & erdiagram-link """) graphe: md.Mermaid = md.Mermaid(graph) graphe # !! note this only works in the notebook that rendered the html. ``` -------------------------------- ### Many-to-Many Relationship Example Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/docs/pages/mermaid/erdiagram/ERDiagram.mdx Defines a many-to-many relationship between 'STUDENT' and 'COURSE' entities, representing an 'enrolls_in' relationship where both sides can have one or more instances. ```python student = Entity("STUDENT", {"student_id": ["int", "PK"]}) course = Entity("COURSE", {"course_id": ["int", "PK"]}) enrollment = Link( student, course, origin_cardinality="one-or-more", end_cardinality="one-or-more", label="enrolls_in" ) ``` -------------------------------- ### Optional Relationship (Identifying Relationship) Example Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/docs/pages/mermaid/erdiagram/Link.mdx Illustrates creating an identifying relationship using a dotted line between ORDER and ORDER_ITEM entities, signifying a weak entity relationship. ```python order = Entity("ORDER", {"order_id": ["int", "PK"]}) item = Entity("ORDER_ITEM", {"order_id": ["int", "FK PK"], "item_no": ["int", "PK"]}) # Use dotted line for identifying relationships link = Link( order, item, "exactly-one", "one-or-more", label="contains", dotted=True # Indicates a weak entity relationship ) ``` -------------------------------- ### Define a Start State Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/docs/pages/mermaid/statediagram/StateDiagram.mdx Represents the initial state of a state diagram, typically denoted by '[*]'. Import `Start` from `mermaid.statediagram`. ```python from mermaid.statediagram import Start start = Start() # Represents [*] ``` -------------------------------- ### Create a Pie Chart with Data Values Displayed Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/docs/pages/mermaid/piechart/PieChart.mdx Shows how to create a pie chart and display the actual data values or percentages on the slices by setting the `show_data` parameter to `True`. ```python from mermaid import Mermaid from mermaid.piechart import PieChart budget = { "Development": 40, "Testing": 20, "Documentation": 15, "DevOps": 15, "Management": 10 } pie = PieChart( title="Project Budget Allocation", data=budget, show_data=True ) Mermaid(pie) ``` -------------------------------- ### Create a Simple Highlight Style Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/docs/pages/mermaid/configuration/Style.mdx Demonstrates creating a basic style named 'highlight' with yellow fill and black text. ```python from mermaid.style import Style highlight = Style( name="highlight", fill="#FFFF00", color="#000000" ) ``` -------------------------------- ### Create a Simple State Diagram Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/docs/pages/mermaid/statediagram/StateDiagram.mdx Demonstrates the basic creation of a state diagram with states, transitions, and a specified direction. This is useful for visualizing simple process flows. ```python from mermaid import Mermaid, Direction from mermaid.statediagram import StateDiagram, State, Start, End, Transition # Create states start = Start() active = State("active", "Active State") paused = State("paused", "Paused State") stopped = State("stopped", "Stopped State") end = End() # Create transitions transitions = [ Transition(start, active, "init"), Transition(active, paused, "pause"), Transition(paused, active, "resume"), Transition(active, stopped, "stop"), Transition(stopped, end) ] # Create diagram diagram = StateDiagram( title="Process State Machine", states=[start, active, paused, stopped, end], transitions=transitions, direction=Direction.TOP_TO_BOTTOM ) Mermaid(diagram) ``` -------------------------------- ### Node Creation with Styling and Hyperlinks Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/docs/pages/mermaid/flowchart/FlowChart.mdx Demonstrates how to create nodes with custom styles and hyperlinks for interactive elements. ```APIDOC ## Node Creation with Styling and Hyperlinks ### Description Allows for the creation of nodes with specific visual styles and clickable hyperlinks. Styles can define colors and borders, while hyperlinks direct users to external URLs. ### Node Parameters for Styling and Hyperlinks - **styles** (Optional[list[Style]]): A list of Style objects to apply to the node. - **href** (str): The URL to link to when the node is clicked. - **href_type** (str): Specifies how the link should open (e.g., 'blank', 'self', 'parent', 'top'). ``` -------------------------------- ### Graph Class Initialization and Usage Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/docs/pages/mermaid/graph.mdx Demonstrates how to initialize a Graph object with a title and script, and how to render it using the Mermaid class. ```APIDOC ## Graph Class Initialization ### Description Initializes a Graph object with a title and the script defining the diagram. ### Method `Graph(title: str, script: str)` ### Parameters - **title** (str) - Required - The title of the diagram. - **script** (str) - Required - The main script to create the diagram. ### Request Example ```python from mermaid.graph import Graph from mermaid import Mermaid graph = Graph( title='simple graph', script=""" flowchart TD A[Christmas] -->|Get money| B(Go shopping) B --> C{Let me think} C -->|One| D[Laptop] C -->|Two| E[iPhone] C -->|Three| F[fa:fa-car Car] "") Mermaid(graph) # render the graph in notebook ``` ### Response This method does not return a value but initializes the Graph object. ``` -------------------------------- ### Entity with Comments Example Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/docs/pages/mermaid/erdiagram/Entity.mdx Illustrates adding descriptive comments to entity attributes. ```APIDOC ## Entity with Comments ```python order = Entity("ORDER") order.add_attribute("order_id", "int", constraint="PK") order.add_attribute("customer_id", "int", constraint="FK", comment="References CUSTOMER table") order.add_attribute("order_date", "datetime", comment="When the order was placed") order.add_attribute("total_amount", "decimal", comment="Sum of all items in order") order.add_attribute("status", "enum", comment="pending, processing, shipped, delivered, cancelled") ``` ``` -------------------------------- ### Initialize a Simple Node Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/docs/pages/mermaid/flowchart/Node.mdx Create a basic node with a unique ID and display content. The `print` statement shows the default Mermaid syntax representation. ```python from mermaid.flowchart import Node # Create a simple node node = Node("task1", "Complete Task") print(node) # Output: task1["Complete Task"] ``` -------------------------------- ### Basic Pie Chart Creation Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/docs/pages/mermaid/piechart/PieChart.mdx Demonstrates how to create a simple pie chart with basic data. ```APIDOC ## Basic Pie Chart Creation ### Description This example shows the fundamental steps to create a pie chart using the `PieChart` class and the `Mermaid` renderer. ### Method ```python from mermaid import Mermaid from mermaid.piechart import PieChart # Define the data for the pie chart data = { "Python": 30, "JavaScript": 25, "Java": 20, "Go": 15, "Rust": 10 } # Instantiate the PieChart with a title and the data pie = PieChart( title="Programming Languages Usage", data=data ) # Render the chart using the Mermaid class Mermaid(pie) ``` ``` -------------------------------- ### Create a Simple FlowChart Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/docs/pages/mermaid/flowchart/FlowChart.mdx Demonstrates the basic creation of a flowchart with nodes, links, and a specified orientation. Ensure `Mermaid`, `Direction`, `FlowChart`, `Node`, and `Link` are imported. ```python from mermaid import Mermaid, Direction from mermaid.flowchart import FlowChart, Node, Link # Create nodes start = Node("start", "Start", shape="stadium-shape") process = Node("process", "Process Data", shape="normal") decision = Node("decision", "Is Valid?", shape="rhombus") end = Node("end", "End", shape="stadium-shape") # Create links link1 = Link(start, process) link2 = Link(process, decision) link3 = Link(decision, end, message="Yes") # Create flowchart flowchart = FlowChart( title="Data Processing Flow", nodes=[start, process, decision, end], links=[link1, link2, link3], orientation=Direction.TOP_TO_BOTTOM ) # Render Mermaid(flowchart) ``` -------------------------------- ### Create a Simple User Journey Diagram Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/docs/pages/mermaid/userjourney/UserJourney.mdx Demonstrates the basic usage of the `UserJourney` class to define actors, tasks, and sections for a simple online shopping experience. This is useful for documenting straightforward user flows. ```python from mermaid import Mermaid from mermaid.userjourney import UserJourney, Section, Task, Actor # Create actors user = Actor("User") support = Actor("Support Team") # Create tasks task1 = Task("Search Product", 5, user) task2 = Task("View Details", 4, user) task3 = Task("Add to Cart", 5, user) task4 = Task("Checkout", 3, user) # Create sections shopping = Section("Shopping", [task1, task2, task3]) payment = Section("Payment", [task4]) # Create diagram diagram = UserJourney( title="Online Shopping Experience", sections=[shopping, payment] ) Mermaid(diagram) ``` -------------------------------- ### Run Tests with Coverage Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/CONTRIBUTING.md Run the test suite and generate a coverage report. ```bash make coverage ``` -------------------------------- ### String Representation of a Link Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/docs/pages/mermaid/flowchart/Link.mdx Demonstrates how to get the Mermaid syntax string representation of a link object. ```python link = Link(node_a, node_b, message="Flow", shape=LinkShape.THICK) print(str(link)) # Output: node_a ==|"Flow"| node_b ``` -------------------------------- ### Create Authentication Logic with Alt Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/docs/pages/mermaid/sequence/SequenceDiagram.mdx Demonstrates how to use the 'Alt' object to represent conditional logic, such as valid or invalid credentials, in a sequence diagram. This helps visualize decision points in the flow. ```python auth_success = [ Link(api_server, web_app, ArrowTypes.DOTTED_ARROW, "Token"), Link(web_app, user, ArrowTypes.DOTTED_ARROW, "Welcome!") ] auth_logic = Alt({ "Credentials valid": auth_success, "Invalid credentials": [ Link(api_server, web_app, ArrowTypes.SOLID_CROSS, "Error"), Link(web_app, user, ArrowTypes.SOLID_CROSS, "Login failed") ] }) ``` -------------------------------- ### Create and Render a Simple Graph Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/docs/pages/mermaid/graph.mdx Instantiate a `Graph` object with a title and script, then use `Mermaid` to render it in a notebook environment. Ensure the `mermaid.graph` and `mermaid` modules are imported. ```python from mermaid.graph import Graph from mermaid import Mermaid graph = Graph( title='simple graph', script=""" flowchart TD A[Christmas] -->|Get money| B(Go shopping) B --> C{Let me think} C -->|One| D[Laptop] C -->|Two| E[iPhone] C -->|Three| F[fa:fa-car Car] "") Mermaid(graph) # render the graph in notebook ``` -------------------------------- ### Create a Simple Pie Chart Source: https://github.com/ouhammmourachid/mermaid-py/blob/main/docs/pages/mermaid/piechart/PieChart.mdx Demonstrates the basic creation of a pie chart with a title and data. Imports required classes from the mermaid-py library. ```python from mermaid import Mermaid from mermaid.piechart import PieChart # Create data data = { "Python": 30, "JavaScript": 25, "Java": 20, "Go": 15, "Rust": 10 } # Create pie chart pie = PieChart( title="Programming Languages Usage", data=data ) Mermaid(pie) ```