{% if page.mermaid and page.mermaid.enabled %}
  <script
    defer
    src="{{ site.third_party_libraries.mermaid.url.js }}"
    integrity="{{ site.third_party_libraries.mermaid.integrity.js }}"
    crossorigin="anonymous"
  ></script>
  {% if page.mermaid.zoomable %}
    <script
      defer
      src="{{ site.third_party_libraries.d3.url.js }}"
      integrity="{{ site.third_party_libraries.d3.integrity.js }}"
      crossorigin="anonymous"
    ></script>
  {% endif %}
  <script>
    let theme = determineComputedTheme();

    /* Create mermaid diagram as another node and hide the code block, appending the mermaid node after it
       this is done to enable retrieving the code again when changing theme between light/dark */
    document.onreadystatechange = () => {
      if (document.readyState === 'complete') {
        document.querySelectorAll('pre>code.language-mermaid').forEach((elem) => {
          const svgCode = elem.textContent;
          const backup = elem.parentElement;
          backup.classList.add('unloaded');
          /* create mermaid node */
          let mermaid = document.createElement('pre');
          mermaid.classList.add('mermaid');
          const text = document.createTextNode(svgCode);
          mermaid.appendChild(text);
          backup.after(mermaid);
        });

        mermaid.initialize({ theme: theme });

        /* Zoomable mermaid diagrams */
        if (typeof d3 !== 'undefined') {
          window.addEventListener('load', function () {
            var svgs = d3.selectAll('.mermaid svg');
            svgs.each(function () {
              var svg = d3.select(this);
              svg.html('<g>' + svg.html() + '</g>');
              var inner = svg.select('g');
              var zoom = d3.zoom().on('zoom', function (event) {
                inner.attr('transform', event.transform);
              });
              svg.call(zoom);
            });
          });
        }
      }
    };
  </script>
{% endif %}
