SkilVaultSign inStart free

Catalogue / mermaid-diagram-syntax

mermaid-diagram-syntax

Older skill: source not recordedSignedWrites Mermaid diagrams of every core family — flowcharts, sequence, class, ER, state, Gantt, pie, journey, mindmap and gitGraph — with correct notation, node shapes, edge labels, cardinality markers, styling and a safe React rendering component. Use when the user asks for "a flowchart of this proce…
---
name: mermaid-diagram-syntax
description: >-
  Writes Mermaid diagrams of every core family — flowcharts, sequence, class,
  ER, state, Gantt, pie, journey, mindmap and gitGraph — with correct notation,
  node shapes, edge labels, cardinality markers, styling and a safe React
  rendering component. Use when the user asks for "a flowchart of this
  process", "a sequence diagram for this API call", "an ER diagram of our
  schema", "a Gantt chart of the roadmap", or wants Mermaid embedded in docs or
  a React app. Not for image editing, for non-Mermaid diagram tools, or for
  rendering untrusted diagram input with relaxed security.
---

Mermaid Diagram Syntax

Mermaid diagrams live in Markdown fences tagged mermaid:

``mermaid flowchart LR A --> B ``

Nothing here writes files or touches a network unless the user asks; diagram text is produced in the conversation.

1. Pick the right family

| Question to answer | Family | |---|---| | How does control flow between steps? | flowchart | | How do actors exchange messages over time? | sequenceDiagram | | How does one object's lifecycle change? | stateDiagram-v2 | | What code structure exists? | classDiagram | | What data is stored and how is it related? | erDiagram | | When does scheduled work happen? | gantt | | How do proportions compare? | pie | | How satisfactory is each step of an experience? | journey | | How does a topic decompose? | mindmap | | How did branches evolve (illustrative only)? | gitGraph |

2. Flowcharts

Direction: TD/TB (top-down), LR, RL, BT.

| Shape | Syntax | Meaning | |---|---|---| | Rectangle | A[Step] | Process step | | Rounded | A(Step) | Start/end, soft step | | Diamond | A{Choice?} | Decision | | Subroutine | A[[Step]] | Named routine | | Cylinder | A[(Store)] | Storage | | Circle | A((Point)) | Connector | | Flag | A>Label] | Asymmetric marker |

| Edge | Meaning | |---|---| | --> | Directed arrow | | --- | Plain line | | -.-> | Dotted arrow | | ==> | Thick (emphasized) arrow | | --text--> or -->|text| | Labeled edge |

Group stages with subgraph <name> … end. Example — a community tool library's reservation path:

flowchart TD
    subgraph Front desk
        R[Request form] --> V{Member verified?}
    end
    V -->|Yes| H[Reserve item]:::ok
    V -->|No| J[Ask to sign up] -.-> R
    H ==> C[Hand over at desk]
    H --- L[("Loan register")]
    classDef ok fill:#22c55e,color:#fff

3. Sequence diagrams

Participants take aliases (participant U as Customer). Message arrows:

| Arrow | Meaning | |---|---| | ->> | Solid with filled arrow | | -->> | Dotted with filled arrow (reply) | | -) | Solid open arrow | | --) | Dotted open arrow |

activate X / deactivate X bracket a lifetime; Note over A,B: and Note right of A: annotate; alt/else, loop, opt wrap alternatives, repetition and optional exchanges.

sequenceDiagram
    participant P as Patron
    participant A as App
    participant L as Loans API

    P->>A: Tap renew
    A->>L: POST /loans/renew
    activate L
    L->>L: Check hold queue
    alt No holds
        L-->>A: 200, new due date
        A-->>P: Renewed confirmation
    else Item on hold
        L-->>A: 409, hold exists
        A-->>P: Renewal declined
    end
    deactivate L

4. State diagrams

[*] marks entry and exit; transitions carry labels.

stateDiagram-v2
    [*] --> Available
    Available --> OnLoan: checkout
    OnLoan --> Available: returned
    OnLoan --> Overdue: due date passes
    Overdue --> Available: returned with fine
    Overdue --> Lost: 30 days overdue
    Lost --> [*]

5. Class diagrams

Visibility prefixes: + public, - private, # protected, ~ package.

| Relation | Syntax | |---|---| | Inheritance | A <|-- B | | Composition | A *-- B | | Aggregation | A o-- B | | Association | A --> B | | Dependency | A ..> B | | Realization | A ..|> B |

Add multiplicities in quotes ("1" --> "*").

classDiagram
    class Member {
        +String id
        +String name
        +borrow(item)
        +return(item)
    }
    class Loan {
        +Date dueDate
        +renew()
    }
    class Item {
        +String callNumber
        +Number lateFeePerDay
    }
    Member "1" --> "*" Loan : places
    Loan "*" --> "1" Item : covers

6. Entity-relationship diagrams

Declare typed fields with PK, FK, UK markers.

| Cardinality | Notation | |---|---| | Exactly one to exactly one | \|\|--\|\| | | One to zero-or-more | \|\|--o{ | | One to one-or-more | \|\|--\|{ | | Many to many | }o--o{ |

erDiagram
    MEMBER ||--o{ LOAN : takes
    LOAN ||--|{ LOAN_LINE : includes
    ITEM ||--o{ LOAN_LINE : "appears in"

    MEMBER {
        string id PK
        string email UK
        string name
    }
    LOAN {
        string id PK
        string member_id FK
        datetime checked_out
    }
    LOAN_LINE {
        string id PK
        string loan_id FK
        string item_id FK
        int renewal_count
    }

7. Gantt charts

A Gantt needs title, dateFormat, sections, task ids, start dates or after dependencies, durations, and milestone entries.

gantt
    title Podcast season launch
    dateFormat YYYY-MM-DD
    section Prep
    Topic research   :p1, 2026-03-02, 5d
    Guest booking    :p2, after p1, 10d
    section Production
    Recording        :r1, after p2, 7d
    Editing          :r2, after r1, 6d
    section Launch
    Publishing       :milestone, after r2, 0d

8. Pie, journey, mindmap, gitGraph

pie title Support tickets by channel
    "Email" : 52
    "Chat" : 31
    "Phone" : 12
    "Forum" : 5
journey
    title New member onboarding
    section Sign-up
        Fill form: 4: New member
        Verify email: 3: New member, System
    section First visit
        Get card: 5: New member, Staff
        Borrow first item: 5: New member
mindmap
    root((Bakery))
        Bread
            Sourdough
            Rye
        Pastry
            Croissant
            Danish
        Drinks
            Espresso
            Tea
gitGraph
    commit
    branch promo-banner
    checkout promo-banner
    commit
    commit
    checkout main
    merge promo-banner
    commit

A rendered gitGraph illustrates history; it never runs git or changes a repository.

9. Styling and readability

flowchart LR
    A[Queue]:::hot --> B[Worker]:::cool --> C[(Archive)]:::dim
    classDef hot fill:#ef4444,color:#fff
    classDef cool fill:#3b82f6,color:#fff
    classDef dim fill:#94a3b8,color:#fff
  • %% starts a comment for maintainers.
  • Quote labels containing punctuation: A["Paid (incl. tax)"].
  • <br/> breaks a label across lines.
  • Check contrast; themes are default, dark, forest, neutral.

10. Rendering in React

Initialize once, render per instance with a unique id, and never trust diagram text:

import mermaid from 'mermaid';
import { useEffect, useRef } from 'react';

mermaid.initialize({ startOnLoad: false, theme: 'neutral' }); // securityLevel stays strict

function Mermaid({ chart }: { chart: string }) {
  const box = useRef<HTMLDivElement>(null);
  useEffect(() => {
    let stale = false;
    const id = `mmd-${Math.random().toString(36).slice(2)}`;
    mermaid.render(id, chart).then(({ svg }) => {
      if (!stale && box.current) box.current.innerHTML = svg;
    }).catch((err) => { if (!stale) console.error('diagram failed to render', err); });
    return () => { stale = true; };
  }, [chart]);
  return <div ref={box} />;
}

Key points: disable startOnLoad for controlled rendering, use a fresh render id per call (never a shared fixed id), ignore completions from stale renders after updates or unmount, and keep securityLevel strict — diagram markup can arrive from users or models and is untrusted input. Give every diagram an adjacent text description for accessibility, and verify the notation subset the destination supports (GitHub accepts a subset of families natively). The official live editor is handy, but pasting a private diagram into it sends it off-machine — ask before suggesting that.

Never

  • Render untrusted diagram text with securityLevel: 'loose'
  • Invent entities, relationships or dates the user has not described
  • Suggest uploading a private diagram to a public editor without asking
  • Claim a diagram family shows evidence it does not (a gitGraph is illustrative, not history)