Debian Codegraph @

docs/src/markdown/extras/mermaid.md

raw
1 ---
2 icon: lucide/chart-pie
3 ---
4 # Advanced Mermaid Notes
5
6 ## Overview
7
8 /// warning | Support
9 This is provided to help users get Mermaid running, but we do not officially offer technical support for Mermaid.
10 Any issues encounter will require the user to debug it themselves.
11
12 There may or may not be issues using an older or newer version of Mermaid than what we have documented here. We may
13 not be always be up to date with the latest and greatest Mermaid version.
14
15 We would be happy to accept pull requests that offer to improve things here or to correct misinformation.
16 ///
17
18 In [SuperFences](../extensions/superfences.md) we cover [custom fences](../extensions/superfences.md#custom-fences)
19 and provide an example for using [Mermaid diagrams](../extensions/superfences.md#uml-diagram-example). What we showed in
20 the example is the bare minimum required to get Mermaid working. While our example was mainly meant to instruct users on
21 how to use custom fences, it was not our intent to give an in depth explanation on how to get Mermaid setup and working
22 in the best way possible. To be honest, Mermaid is a little buggy and required some workarounds to alleviate some if its
23 quirks.
24
25 In general, we leave setting up custom fences for the user to explore, but we do get asked occasionally how to get
26 Mermaid working, and what we are doing, so we thought we'd share some additional information in case there is a strong
27 desire from any of our users to implement a robust Mermaid solution.
28
29 If you'd like to see exactly what we do, you can checkout our source code, but in this example, we will show the basics.
30
31 ## Practical Diagrams
32
33 There are a few diagrams that we feel do not work well for us, and we thought it useful to share why. The main reason is
34 that a few of the diagrams are a bit impractical to use due to sizing and scaling issues. While there may be a way to
35 massage them to work, we have not currently invested any time in workarounds for these diagrams.
36
37 Some of the less practical examples may work better if they were pre-rendered and included as an image instead. This
38 seems to be what Mermaid does in their own [documents][mermaid].
39
40 /// success | Practical
41 //// tab | Flowcharts
42
43 ```diagram
44 graph TD
45 A[Hard] -->|Text| B(Round)
46 B --> C{Decision}
47 C -->|One| D[Result 1]
48 C -->|Two| E[Result 2]
49 ```
50 ////
51
52 //// tab | Sequence Diagrams
53 ```diagram
54 sequenceDiagram
55 participant Alice
56 participant Bob
57 Alice->>John: Hello John, how are you?
58 loop Healthcheck
59 John->>John: Fight against hypochondria
60 end
61 Note right of John: Rational thoughts <br/>prevail!
62 John-->>Alice: Great!
63 John->>Bob: How about you?
64 Bob-->>John: Jolly good!
65 ```
66 ////
67
68 //// tab | Class Diagrams
69 ```diagram
70 classDiagram
71 Class01 <|-- AveryLongClass : Cool
72 Class03 *-- Class04
73 Class05 o-- Class06
74 Class07 .. Class08
75 Class09 --> C2 : Where am i?
76 Class09 --* C3
77 Class09 --|> Class07
78 Class07 : equals()
79 Class07 : Object[] elementData
80 Class01 : size()
81 Class01 : int chimp
82 Class01 : int gorilla
83 Class08 <--> C2: Cool label
84 ```
85 ////
86
87 //// tab | Entity Relationships
88 ```diagram
89 erDiagram
90 CUSTOMER ||--o{ ORDER : places
91 ORDER ||--|{ LINE-ITEM : contains
92 CUSTOMER }|..|{ DELIVERY-ADDRESS : uses
93 ```
94 ////
95
96 //// tab | State Diagrams
97 ```diagram
98 stateDiagram
99 [*] --> First
100 First --> Second
101 First --> Third
102
103 state First {
104 [*] --> fir
105 fir --> [*]
106 }
107 state Second {
108 [*] --> sec
109 sec --> [*]
110 }
111 state Third {
112 [*] --> thi
113 thi --> [*]
114 }
115 ```
116 ////
117
118 //// tab | Git Graph
119
120 ```diagram
121 gitGraph
122 commit
123 branch hotfix
124 checkout hotfix
125 commit
126 branch develop
127 checkout develop
128 commit id:"ash" tag:"abc"
129 branch featureB
130 checkout featureB
131 commit type:HIGHLIGHT
132 checkout main
133 checkout hotfix
134 commit type:NORMAL
135 checkout develop
136 commit type:REVERSE
137 checkout featureB
138 commit
139 checkout main
140 merge hotfix
141 checkout featureB
142 commit
143 checkout develop
144 branch featureA
145 commit
146 checkout develop
147 merge hotfix
148 checkout featureA
149 commit
150 checkout featureB
151 commit
152 checkout develop
153 merge featureA
154 branch release
155 checkout release
156 commit
157 checkout main
158 commit
159 checkout release
160 merge main
161 checkout develop
162 merge release
163 ```
164 ////
165
166 //// tab | Journey
167
168 ```diagram
169 journey
170 title My working day
171 section Go to work
172 Make tea: 5: Me
173 Go upstairs: 3: Me
174 Do work: 1: Me, Cat
175 section Go home
176 Go downstairs: 5: Me
177 Sit down: 5: Me
178 ```
179 ////
180
181 //// tab | Pie
182
183 ```diagram
184 pie
185 title Key elements in Product X
186 "Calcium" : 42.96
187 "Potassium" : 50.05
188 "Magnesium" : 10.01
189 "Iron" : 5
190 ```
191
192 ////
193 ///
194
195 /// failure | Impractical
196 //// tab | Gantt
197
198 Gantt charts usually are too big to render properly in a page. If the element is big enough to hold it, and the
199 chart is large, they render too small to see. If the element is not wide enough, the chart can sometimes render
200 squished and hard to read.
201
202 ```diagram
203 gantt
204 dateFormat YYYY-MM-DD
205 title Adding GANTT diagram to mermaid
206 excludes weekdays 2014-01-10
207
208 section A section
209 Completed task :done, des1, 2014-01-06,2014-01-08
210 Active task :active, des2, 2014-01-09, 3d
211 Future task : des3, after des2, 5d
212 Future task2 : des4, after des3, 5d
213 ```
214
215 ////
216
217 ///
218
219 ## Configuration
220
221 We do some configuration via the initialization API command to tweak the diagrams a little. This includes theming and
222 disabling of problematic features.
223
224 We include the Mermaid library normally, but use a custom loader as we wrap our diagrams in a non-standard way. In
225 addition, our custom loader allows us to workaround some problematic issues that arise when using Mermaid's default
226 loader.
227
228 For illustrative purposes, we've provided a basic, bare minimum configuration below that we use.
229
230 ```js
231 window.mermaidConfig = {
232 startOnLoad: false,
233 theme: "default",
234 flowchart: {
235 useMaxWidth: false
236 },
237 er: {
238 useMaxWidth: false
239 },
240 sequence: {
241 useMaxWidth: false,
242 noteFontWeight: "14px",
243 actorFontSize: "14px",
244 messageFontSize: "16px"
245 },
246 journey: {
247 useMaxWidth: false
248 },
249 gitGraph: {
250 useMaxWidth: false
251 }
252 }
253 ```
254
255 /// note | Configuration Notes
256 1. If the option is available in a diagram, we disable `useMaxWidth` as we prefer that our diagrams do not scale
257 within their parent element, we rather them overflow with a scrollbar. You can leave these enabled if you like.
258 Since we render our diagrams under a custom element with a shadow DOM, to get scrollbars, we simply enable
259 `#!css overflow: auto` on the custom `diagram-div` element (under the host DOM, not the shadow DOM).
260
261 2. We disable `startOnLoad` as we provide our own loader (for reasons we will get into later).
262
263 3. We do a quite a bit of custom theme overrides. Most of this is done through the Mermaid configuration options:
264 `theme`, `themeVariables`, and `themeCSS`. Most users would simply use one of the default themes via the `theme`
265 option, so that is what we've shown above.
266 ///
267
268 ## Custom Loader
269
270 While using Mermaid, we've found a couple of issues which we were able to solve by using our own custom loader. The
271 loader contains all the logic needed to find the Mermaid diagrams, convert them, wrap them in a shadow DOM, and insert
272 them into the current document.
273
274 In order to use the loader, it should be attached to a `DOMContentLoaded` event to execute only after the document is
275 loaded. We bind our logic to this event in our loader function that checks if the Mermaid library is loaded, and only if
276 it is, we execute the payload.
277
278 The issues we are working around withing Mermaid are found below:
279
280 /// bug | Issues
281 1. Diagrams that are found in tabbed interfaces or details, where the element may be hidden on page load, don't
282 always render at a visible size if using Mermaid's default loader.
283
284 2. Mermaid uses IDs in their SVG diagrams, and these can sometimes cause conflicts if you happen to have IDs on your
285 page that match one that they use.
286
287 3. Mermaid does not always use unique IDs. This can cause some elements of a diagram to disappear if one diagram
288 happens to have the same ID and it is hidden in a details element or a tabbed interface.
289 ///
290
291 We solve these issues doing a couple things in our own custom loader.
292
293 /// success | Solutions
294 1. Using the `#!html <body>` element as a parent, we attach a surrogate element to it and render the diagram there.
295 Once rendered, we then insert the diagram back to where the original custom fence was. This ensures it renders
296 under a visible parent, and renders at a normal size.
297
298 2. We wrap each diagram in a shadow DOM element. This prevents ID leakage from one diagram to another or to the
299 host.
300 ///
301
302 Apart from the issues we were trying to solve, we also use a custom loader for personal aesthetics as we like to render
303 our diagrams in `#!html <pre><code>` tags. This allows us to render the diagrams as normal code blocks in the rare case
304 that we cannot load the Mermaid library from the specified CDN.
305
306 ## Putting it All Together
307
308 So, putting it all together, we have the HTML generated by SuperFences. In the HTML, we include the Mermaid library
309 and provide the configuration. We also have the custom loader that is runs when the document is loaded.
310
311 /// tab | Preview
312 ![Mermaid example](../images/mermaid-diagram.png)
313 ///
314
315 /// tab | HTML
316 ```html
317 <!-- Pre/code generated by SuperFences -->
318 <pre class="mermaid"><code>graph TB
319 c1--&gt;a2
320 subgraph one
321 a1--&gt;a2
322 end
323 subgraph two
324 b1--&gt;b2
325 end
326 subgraph three
327 c1--&gt;c2
328 end</code></pre>
329
330 <!-- Include Mermaid script and user config -->
331 <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/mermaid.min.js"></script>
332 <script>
333 window.mermaidConfig = {
334 startOnLoad: false,
335 theme: "default",
336 flowchart: {
337 useMaxWidth: false
338 },
339 er: {
340 useMaxWidth: false
341 },
342 sequence: {
343 useMaxWidth: false,
344 noteFontWeight: "14px",
345 actorFontSize: "14px",
346 messageFontSize: "16px"
347 }
348 }
349 </script>
350 ```
351 ///
352
353 /// tab | JS
354 ```js {.md-max-height}
355 const uml = async className => {
356
357 // Custom element to encapsulate Mermaid content.
358 class MermaidDiv extends HTMLElement {
359
360 /**
361 * Creates a special Mermaid div shadow DOM.
362 * Works around issues of shared IDs.
363 * @return {void}
364 */
365 constructor() {
366 super()
367
368 // Create the Shadow DOM and attach style
369 const shadow = this.attachShadow({mode: "open"})
370 const style = document.createElement("style")
371 style.textContent = `
372 :host {
373 display: block;
374 line-height: initial;
375 font-size: 16px;
376 }
377 div.diagram {
378 margin: 0;
379 overflow: visible;
380 }`
381 shadow.appendChild(style)
382 }
383 }
384
385 if (typeof customElements.get("diagram-div") === "undefined") {
386 customElements.define("diagram-div", MermaidDiv)
387 }
388
389 const getFromCode = parent => {
390 // Handles <pre><code> text extraction.
391 let text = ""
392 for (let j = 0; j < parent.childNodes.length; j++) {
393 const subEl = parent.childNodes[j]
394 if (subEl.tagName.toLowerCase() === "code") {
395 for (let k = 0; k < subEl.childNodes.length; k++) {
396 const child = subEl.childNodes[k]
397 const whitespace = /^\s*$/
398 if (child.nodeName === "#text" && !(whitespace.test(child.nodeValue))) {
399 text = child.nodeValue
400 break
401 }
402 }
403 }
404 }
405 return text
406 }
407
408 // Provide a default config in case one is not specified
409 const defaultConfig = {
410 startOnLoad: false,
411 theme: "default",
412 flowchart: {
413 useMaxWidth: false
414 },
415 er: {
416 useMaxWidth: false
417 },
418 sequence: {
419 useMaxWidth: false,
420 noteFontWeight: "14px",
421 actorFontSize: "14px",
422 messageFontSize: "16px"
423 }
424 }
425
426 // Load up the config
427 mermaid.mermaidAPI.globalReset()
428 const config = (typeof mermaidConfig === "undefined") ? defaultConfig : mermaidConfig
429 mermaid.initialize(config)
430
431 // Find all of our Mermaid sources and render them.
432 const blocks = document.querySelectorAll(`pre.${className}, diagram-div`)
433 const surrogate = document.querySelector("html body")
434 for (let i = 0; i < blocks.length; i++) {
435 const block = blocks[i]
436 const parentEl = (block.tagName.toLowerCase() === "diagram-div") ?
437 block.shadowRoot.querySelector(`pre.${className}`) :
438 block
439
440 // Create a temporary element with the typeset and size we desire.
441 // Insert it at the end of our parent to render the SVG.
442 const temp = document.createElement("div")
443 temp.style.visibility = "hidden"
444 temp.style.display = "display"
445 temp.style.padding = "0"
446 temp.style.margin = "0"
447 temp.style.lineHeight = "initial"
448 temp.style.fontSize = "16px"
449 surrogate.appendChild(temp)
450
451 try {
452 const res = await mermaid.render(`_diagram_${i}`, getFromCode(parentEl), temp)
453 const content = res.svg
454 const fn = res.bindFunctions
455 const el = document.createElement("div")
456 el.className = className
457 el.innerHTML = content
458 if (fn) {
459 fn(el)
460 }
461
462 // Insert the render where we want it and remove the original text source.
463 // Mermaid will clean up the temporary element.
464 const shadow = document.createElement("diagram-div")
465 shadow.shadowRoot.appendChild(el)
466 block.parentNode.insertBefore(shadow, block)
467 parentEl.style.display = "none"
468 shadow.shadowRoot.appendChild(parentEl)
469 if (parentEl !== block) {
470 block.parentNode.removeChild(block)
471 }
472 } catch (err) {} // eslint-disable-line no-empty
473
474 if (surrogate.contains(temp)) {
475 surrogate.removeChild(temp)
476 }
477 }
478 }
479
480 // This should be run on document load
481 document.addEventListener("DOMContentLoaded", () => {uml("mermaid")})
482 ```
483 ///
484
485 /// tip | Live Example
486 For a live, working example, check out the CodePen [here](https://codepen.io/facelessuser/pen/oNeNydQ).
487 ///
488
489 ## Using in MkDocs
490
491 If you are using MkDocs, you would probably include your config, mermaid library, and then your loader:
492
493 ```yaml
494 markdown_extensions:
495 - pymdownx.superfences:
496 preserve_tabs: true
497 custom_fences:
498 # Mermaid diagrams
499 - name: mermaid
500 class: mermaid
501 format: !!python/name:pymdownx.superfences.fence_code_format
502
503 extra_javascript:
504 - optionalConfig.js
505 - https://cdn.jsdelivr.net/npm/[email protected]/dist/mermaid.min.js
506 - extra-loader.js
507 ```
508
509 Then in your documents, do something like this:
510
511 ````
512 ```mermaid
513 graph TD
514 A[Hard] -->|Text| B(Round)
515 B --> C{Decision}
516 C -->|One| D[Result 1]
517 C -->|Two| E[Result 2]
518 ```
519 ````
520
521 To get something like this directly embedded in your documents:
522
523 ```diagram
524 graph TD
525 A[Hard] -->|Text| B(Round)
526 B --> C{Decision}
527 C -->|One| D[Result 1]
528 C -->|Two| E[Result 2]
529 ```