<script context="module">
    import { onMount } from 'svelte';
    import { formatDate } from './datefmt.js';
    import { makeSlug } from '$lib/slug.js';
    import Link from './Link.svelte';
    export { Link as a };
</script>

<script>
    export let title, date;

    // deal with sidenote collisions
    function tileNotes() {
        const minNoteGap = 15;
        // let sidenotes = Array.from(document.getElementsByClassName('sidenote'));
        let notes = document.querySelectorAll('.sidenote');
        if (window.getComputedStyle(notes[0]).position === 'fixed') {
            // fixed position means we are in mobile territory, so 
            // get rid of the overflow stuff and then exit
            for (let note of notes) {
                note.style.top = '';
            }
            return;
        }

        let labels = document.querySelectorAll('label.counter');
        var prev = 0;
        for (var i=0; i < notes.length; i++) {
            let labelTop = labels[i].getBoundingClientRect().y + window.scrollY;
            let noteHeight = notes[i].getBoundingClientRect().height;
            if (labelTop < prev + minNoteGap) {
                // there is a collision
                notes[i].style.top = `${prev + minNoteGap}px`;
                prev = prev + minNoteGap + noteHeight;
            }
            else {
                // no collision
                notes[i].style.top = `${labelTop}px`;
                prev = labelTop + noteHeight;
            }
        }
    }

    onMount(async () => {
        tileNotes();
        window.addEventListener('resize', tileNotes);
    });
</script>

<svelte:head>
    <title>{title}</title>
</svelte:head>

<div id="post">
    <h1 id="{makeSlug(title)}">{title}</h1>
    <p><em>{formatDate(date)}</em></p>
    <slot></slot>
</div>
