<script lang="ts">
    import {onMount} from 'svelte';

    let idCounter: number = 0;

    let container: HTMLElement;

    onMount(() => {
        let headers = getHeaders();
        headers.forEach(header => {
            let headerId = getHeaderId(header);
            var element = document.createElement("li");
            element.classList += "toc-level-" + getHeaderLevel(header);
            element.innerHTML = `<a href="#${headerId}">${(header as HTMLElement).innerHTML}</a>`;
            container.appendChild(element);
        });
    });

    let getHeaders = function(): NodeList {
        return document.querySelectorAll("h2, h3, h4, h5");
    }

    let getHeaderId = function(header: Node): string {
        var id = (header as HTMLElement).id;
        if (!id) {
            id = `header-${idCounter}`;
            (header as HTMLElement).id = id;
            idCounter += 1;
        }
        return id;
    }

    let getHeaderLevel = function(header: Node): string {
        switch ((header as HTMLElement).tagName) {
            case "H2":
                return "0";
            case "H3":
                return "1";
            case "H4":
                return "2";
            case "H5":
                return "3";
            default:
                return "0";
        }
    }
</script>

<div class="toc-container notched">
    <ul class="toc-list" bind:this={container}>
    </ul>
</div>

<style>
    :global {
        .toc-container {
            width: 80%;
            margin-left: auto;
            margin-right: auto;

            background-color: var(--color-background-highlight);
            padding: 16px 0;
        }

        .toc-list {
            padding: 0;
            margin: 0;
        }
        .toc-list li {
            list-style: none;
        }
        .toc-list li a {
            width: 100%;
            padding-top: 8px;
            padding-bottom: 8px;
            padding-right: 24px;
            display: inline-block;
            color: var(--color-text);
            text-decoration: none;
            transition: all 0.2s ease-in-out;
            transition-property: color background-color;
            box-sizing: border-box;
        }

        .toc-list li a:hover {
            color: var(--color-text-dark);
            background-color: var(--color-highlight);
        }

        .toc-level-0 a {
        padding-left: 44px;
        }
        .toc-level-1 a {
            padding-left: 68px;
        }
        .toc-level-2 a {
            padding-left: 92px;
        }
        .toc-level-3 a {
            padding-left: 116px;
        }
        .toc-level-1 a::before, .toc-level-2 a::before, .toc-level-3 a::before {
            content: "↳ ";
        }
    }
</style>