Rendering Mermaid Diagrams with Svelte
Svelte delivers a delightful low-code DX for responsive web applications.
Here’s a brief overview of the pertinent code (view on StackBlitz):
<script>
import mermaid from 'mermaid';
// The default diagram
let diagram = `\
erDiagram
CUSTOMER }|..|{ DELIVERY-ADDRESS : has
CUSTOMER ||--o{ ORDER : places
CUSTOMER ||--o{ INVOICE : "liable for"
DELIVERY-ADDRESS ||--o{ ORDER : receives
INVOICE ||--|{ ORDER : covers
ORDER ||--|{ ORDER-ITEM : includes
PRODUCT-CATEGORY ||--|{ PRODUCT : contains
PRODUCT ||--o{ ORDER-ITEM : "ordered in"`;
let container;
async function renderDiagram() {
const {svg} = await mermaid.render('mermaid', diagram)
container.innerHTML=svg;
}
$: diagram && renderDiagram()
</script>
<main>
<pre
contenteditable="true"
bind:innerHTML={diagram}
></pre>
<span bind:this={container}>
</main>
- The function renderDiagram() renders the Mermaid diagram
- The contents of the <pre> block are bound to the JavaScript variable ‘diagram’
- Whenever the ‘diagram’ variable changes and is not empty, renderDiagram() is called. This is accomplished via:
$: diagram && renderDiagram()
Would you prefer to run Elixir on the backend? This Svelte component also runs on Phoenix. Check it out!