Recursive HTML

These days, you're not constrained to the standard HTML components. Frameworks allow you to define your own reusable components and my favorite tool for this is svelte. It's really simple, fast, lightweight and it even plays nice with d3.

There was however also something that I didn't expect ... Svelte allows you to declare components recursively. Here's an example Tree.svelte file that does exactly this.

<script>
    import IconOpen from './IconOpen.svelte';
    import IconClosed from './IconClosed.svelte';

    export let data;
    export let expanded = false;
    export let maxtime = data['value'];
    function toggle(){
        expanded = !expanded;
    }
</script>

<p on:click={toggle}>
    {#if expanded}
        <IconOpen/>  
    {:else}
        <IconClosed/>
    {/if}
    <span class="mono pointer">{data['name']}</span>
</p>

<p style="padding-left: 30px">
    {#each data['children'] as child}
        {#if expanded}
            {#if 'children' in child}
                <svelte:self data={child} maxtime={maxtime}/>
            {:else}
                <p class="mono">{child['name']}</p>
            {/if}
        {/if}
    {/each}
</p>

This code is an subset from a expandable tree component that you can view here. The main thing that's super neat is the <svelte:self data={child} maxtime={maxtime}/>-bit. You're able to refer to itself.

It's a technique that's proven to be very useful for my pytest duration insights project. Where HTML files are static, Svelte allows you to make components a bit more like functions without overdoing it like React.