<script>
    import {onDestroy, onMount} from "svelte";
    import Trix from "trix"

    export let value = "";
    export let field;
    let editor;


    function updateValue(e) {
        value = e.target.value;
    }

    export function insertMedia(info){
        if(info.record._file.width > 0){
            var attachment = new Trix.Attachment({ content: info.html })
            editor.editor.insertAttachment(attachment)
        }else{
            editor.editor.insertHTML(`<a href="${info.originalUrl}">${info.record._file.originalName}</a>`)

        }


    }

    onMount(() => {
        editor.addEventListener("trix-file-accept", (e) => {
            e.preventDefault();
        })

        editor.addEventListener("trix-before-initialize", (e) => {
            Trix.config.blockAttributes.heading1.tagName = 'h2';
            const { toolbarElement } = e.target
            const h1Button = toolbarElement.querySelector("[data-trix-attribute=heading1]")
            h1Button.insertAdjacentHTML("afterend", `<button style="text-indent: initial;padding: 14px 10px !important;" type="button" class="trix-button trix-button--icon" data-trix-attribute="heading3" title="Heading 3" tabindex="-1" data-trix-active="">H3</button>`)
        })


    })
    // onDestroy(() => {
    //     editor.removeEventListener("trix-before-initialize")
    // })


    Trix.config.blockAttributes.default.breakOnReturn = false
    Trix.config.blockAttributes.heading3 = {
        tagName: 'h3',
        terminal: true,
        breakOnReturn: true,
        group: false
    }
    // console.log(Trix.config)

</script>

<div class="tox-wrapper">
    <input id="x-{field.name}" {value} type="hidden">
    <trix-editor
            bind:this={editor}
            class=" content"
            input="x-{field.name}"
            role="textbox"
            tabindex="0"
            on:trix-change={updateValue}

    ></trix-editor>
</div>
