Mermaid
Mermaid text diagrams drawn in your theme colours, loaded on demand and safe for untrusted sources.
c2-mermaid draws a Mermaid diagram (flowchart, sequence, class, state, ER, gantt, pie and the rest) from its text source. Put the source in value, or in a <script type="text/mermaid"> child so the browser leaves it alone.
Colours. They come from the element’s --c2-mermaid… variables, which map onto the @c2n/theme tokens, so diagrams follow light and dark mode. A diagram re-renders whenever one of those colours changes, whether from a theme switch or an override on one element.
Loading. Mermaid itself is large, so it loads with the first diagram on the page, not with the element. Until then, and on the server, the source shows as code.
Untrusted sources. Diagrams written by a model or a user are safe to render:
- Mermaid runs at
securityLevel: 'strict'with plain-text labels, and a diagram’s%%{init}%%directive cannot change those settings or the theme. - The SVG is parsed and stripped of scripts, embedded HTML, event handlers, links and external
url()andhrefreferences before it is shown.
A source that does not parse keeps its text, shows the message and fires mermaid-error.
Import
import '@c2n/components/mermaid'Mermaid itself is an optional peer dependency, so apps that draw no diagram do not download it. Install it next to @c2n/components; without it, a diagram shows its source and a message saying so.
npm install mermaidUsage
flowchart LR
Cart[Cart] --> Checkout{Payment ok?}
Checkout -- yes --> Paid([Order paid])
Checkout -- no --> Retry[Retry card]
Retry --> Checkout
sequenceDiagram participant App participant API App->>API: POST /orders API-->>App: 201 Created App->>API: GET /orders/42 API-->>App: 200 OK
flowchart LR A --> --> B
Export the drawn diagram:
const diagram = document.querySelector('c2-mermaid')!
diagram.addEventListener('mermaid-render', () => {
const markup = new XMLSerializer().serializeToString(diagram.svgElement!)
download(new Blob([markup], { type: 'image/svg+xml' }), 'diagram.svg')
})