{% load static %}

{% block script %}
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        htmlTableOfContents();
    } );

    function htmlTableOfContents(documentRef) {
        var documentRef = documentRef || document;
        var toc = documentRef.getElementById("toc");
    //  Use headings inside <article> only:
    //  var headings = [].slice.call(documentRef.body.querySelectorAll('article h1, article h2, article h3, article h4, article h5, article h6'));
        {#var headings = [].slice.call(documentRef.body.querySelectorAll('h1, h2, h3, h4, h5, h6'));#}
        var article = document.querySelector("article");
        var headings = article ? [].slice.call(article.querySelectorAll( "h1, h2, h3, h4, h5, h6")) : [];
        headings.forEach(function (heading, index) {
            var ref = "toc" + index;
            var h_parent = heading.parentElement;
            if (h_parent.hasAttribute("id"))
                ref = h_parent.getAttribute( "id" );
            else
                ref = heading.textContent.replace(/\s+/g, '-').toLowerCase();
                h_parent.setAttribute("id", ref);

            var link = documentRef.createElement("a");
            link.setAttribute("href", "#" + ref);
            link.textContent = heading.textContent;

            var div = documentRef.createElement("li");
            div.setAttribute("class", `${heading.tagName.toLowerCase()} scrollspy`);
            div.appendChild(link);
            toc.appendChild(div);
        });
    }

    try {
        module.exports = htmlTableOfContents;
    } catch (e) {
        // module.exports is not defined
    }

    $(document).ready(function(){
        $('.scrollspy').scrollSpy();
    });
    </script>
{% endblock %}