<script>
    let { editable = false, value = $bindable(null) } = $props();
    let editing = $state(false);

    let editValue = {source:value.source,rendered:value.rendered};

    function applyEdit(){
        value.source = editValue.source;
        value.rendered = editValue.rendered;
        editing = false;
    }

    function resetEdit(){
        editing = false;
        editValue = {source:value.source,rendered:value.rendered};
    }

    function startEdit(){
        editing = editable;
    }

    function typed(ev){
        if (ev.keyCode == 13 && ev.ctrlKey) applyEdit();
        if (ev.keyCode == 27) resetEdit();

        // TODO: start timer, send text to renderer, update editValue.rendered
    }
</script>

<style>
    textarea{
        width: 100%;
        min-height: 100px;
    }
</style>

{#if editable && editing}
<textarea bind:value={editValue.source} onkeyup={typed} autofocus></textarea>
{/if}
<div onclick={startEdit}>{@html value.rendered}</div>
