forked from w3c/respec-mermaid
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
59 lines (50 loc) · 1.68 KB
/
index.js
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
import mermaid from 'mermaid';
function addMermaidStyles() {
const mermaidStyles = document.createElement('style');
mermaidStyles.innerHTML += `
/* Any custom mermaid.js scripts will go here. */
}`;
document.getElementsByTagName('head')[0].appendChild(mermaidStyles);
}
function addMermaidScripts() {
const mermaidScripts = document.createElement('script');
mermaidScripts.type = 'text/javascript';
mermaidScripts.text += `
/* Any custom mermaid.js scripts will go here. */
`;
document.getElementsByTagName('head')[0].appendChild(mermaidScripts);
mermaid.mermaidAPI.initialize({startOnLoad:false});
}
async function createFigures() {
// add scripts for figures
addMermaidScripts();
// add styles for figures
addMermaidStyles();
// process every mermaid figure in the document
const mermaidFigures = document.querySelectorAll(".mermaid");
let figureNum = 1;
for(const figure of mermaidFigures) {
// extract the mermaid source code
const mermaidSource = figure.firstChild.textContent;
// try rendering the diagram
try {
await mermaid.mermaidAPI.render(
'diagram-' + figureNum, mermaidSource, (svgCode, bindFunctions) => {
const template = document.createElement('template');
const cleanedSvg = svgCode.trim().replace(/height="[0-9]*"/, '');
template.innerHTML = cleanedSvg;
figure.parentElement.prepend(template.content.firstChild);
figure.remove();
});
figureNum++;
} catch(e) {
console.error('respec-mermaid error: Failed to generate figure.',
e, mermaidSource);
continue;
}
}
}
// setup exports on window
window.respecMermaid = {
createFigures
}