summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/lib/mermaid.js
blob: d621c9ddf9ed7ce8c399921f2faa2fc5d8a308e8 (plain)
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
import mermaid from 'mermaid';
import { getParameterByName } from '~/lib/utils/url_utility';

const setIframeRenderedSize = (h, w) => {
  const { origin } = window.location;
  window.parent.postMessage({ h, w }, origin);
};

const drawDiagram = (source) => {
  const element = document.getElementById('app');
  const insertSvg = (svgCode) => {
    element.innerHTML = svgCode;

    const height = parseInt(element.firstElementChild.getAttribute('height'), 10);
    const width = parseInt(element.firstElementChild.style.maxWidth, 10);
    setIframeRenderedSize(height, width);
  };
  mermaid.mermaidAPI.render('mermaid', source, insertSvg);
};

const darkModeEnabled = () => getParameterByName('darkMode') === 'true';

const initMermaid = () => {
  let theme = 'neutral';

  if (darkModeEnabled()) {
    theme = 'dark';
  }

  mermaid.initialize({
    // mermaid core options
    mermaid: {
      startOnLoad: false,
    },
    // mermaidAPI options
    theme,
    flowchart: {
      useMaxWidth: true,
      htmlLabels: true,
    },
    secure: ['secure', 'securityLevel', 'startOnLoad', 'maxTextSize', 'htmlLabels'],
    securityLevel: 'strict',
  });
};

const addListener = () => {
  window.addEventListener(
    'message',
    (event) => {
      if (event.origin !== window.location.origin) {
        return;
      }
      drawDiagram(event.data);
    },
    false,
  );
};

addListener();
initMermaid();
export default {};