<script>
    import { tick } from 'svelte';
    import { postToChannel } from '../apiServer';
    import { activeChannel } from '../store';

    let input;
    let value;
    let disabled;
    activeChannel.subscribe((value) => {
        disabled = !value.isSet();
        if (input && !disabled) {
            input.focus();
        }
    });

    async function handleSubmit(event) {
        disabled = true;
        // TODO try/catch:
        await postToChannel($activeChannel.get(), value);
        value = '';
        disabled = false;
        await tick();
        input.focus();
    }
</script>

<form on:submit|preventDefault={handleSubmit}>
    <div class="input-group input-group-divider grid-cols-[auto_1fr_auto]">
        <input bind:this={input} bind:value={value} disabled={disabled} type="search" />
        <button color="primary variant-filled-secondary" type="submit">&raquo;</button>
    </div>
</form>
