<script>
    import { messages } from '$lib/store';
    import MessageRun from './MessageRun.svelte';

    export let channel = null;
    $: messageList = channel !== null ? $messages.inChannel(channel) : [];

    function *chunkBy(xs, fn) {
        let chunk;
        let key;
        for (let x of xs) {
            let newKey = fn(x);
            if (key !== newKey) {
                if (chunk !== undefined) {
                    yield [key, chunk];
                }

                chunk = [x];
                key = newKey;
            } else {
                chunk.push(x);
            }
        }
        if (chunk !== undefined) {
            yield [key, chunk];
        }
    }
</script>

<div class="container">
    {#each chunkBy(messageList, msg => msg.sender) as [sender, messages]}
        <div>
            <MessageRun {sender} {messages} />
        </div>
    {/each}
</div>

<style>
    .container {
        overflow: auto;
    }
</style>
