-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path03-mermaid-to-svg.qmd
126 lines (106 loc) · 2.51 KB
/
03-mermaid-to-svg.qmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
---
title: "Mermaid to SVG"
format:
html:
toc: true
toc-title: "TOC"
css: ./css/style.css
include-in-header:
text: '<script src="./js/mermaid.min.js"></script>'
include-after-body:
text: "<script>mermaid.initialize({startOnLoad:true})</script>"
---
# Mermaid Options + SVG Export
```{ojs}
viewof message = Inputs.text({label: "message", value: "hello world"})
```
```{ojs}
//| code-fold: show
//| label: fig-mermaid-test-export
//| fig-cap: "Selector: `#fig-mermaid-test-export`"
mermaid`sequenceDiagram
"Actor A" ->> "Actor B": ${message}
"Actor B" -->> "Actor A": response
`
```
```{ojs}
//| echo: false
viewof svgSelector = Inputs.text({label: "id", value: "#fig-mermaid-test-export"})
```
```{ojs}
//| echo: false
DOM.download(() => exportSVG(svgSelector), "fig-mermaid-test-export.svg", "Export as SVG")
```
## Helper Function: SVG Export
> Mod. of https://observablehq.com/@mbostock/saving-svg#serialize
```{ojs}
exportSVG = function(svgSelector) {
let domSVG = document.querySelector(svgSelector + " svg")
const xmlns = "http://www.w3.org/2000/xmlns/"
const xlinkns = "http://www.w3.org/1999/xlink"
const svgns = "http://www.w3.org/2000/svg"
domSVG = domSVG.cloneNode(true)
const fragment = window.location.href + "#"
const walker = document.createTreeWalker(domSVG, NodeFilter.SHOW_ELEMENT)
while (walker.nextNode()) {
for (const attr of walker.currentNode.attributes) {
if (attr.value.includes(fragment)) {
attr.value = attr.value.replace(fragment, "#")
}
}
}
domSVG.setAttributeNS(xmlns, "xmlns", svgns)
domSVG.setAttributeNS(xmlns, "xmlns:xlink", xlinkns)
const serializer = new window.XMLSerializer
const string = serializer.serializeToString(domSVG)
return new Blob([string], {
type: "image/svg+xml"
})
}
```
<hr>
# Mermaid Chunk Options
## Track 1: with {ojs}
```{ojs}
//| code-fold: false
mermaid`graph TD
A-->B
A-->C
B-->D
C-->D
`
```
```{ojs}
//| code-fold: show
mermaid
`
flowchart TD
A[Start] --> B{Is it?}
B -- Yes --> C[OK]
C --> D[Rethink]
D --> B
B -- No ----> E[End]
`
```
### With Input
```{ojs}
viewof message2 = Inputs.text({label: "message", value: "hello world"})
```
```{ojs}
//| code-fold: show
mermaid`sequenceDiagram
"Actor A" ->> "Actor B": ${message2}
"Actor B" -->> "Actor A": response
`
```
## Track 2: with regular Knitr chunks
```{=html}
<pre class="mermaid">
flowchart TD
A[Start] --> B{Is it?}
B -- Yes --> C[OK]
C --> D[Rethink]
D --> B
B -- No ----> E[End]
</pre>
```