<template>
    <Editor ref="editor" v-model="model" autofocus :gutters="false" />
    <iframe ref="iframe" class="w-full h-full border-0" sandbox="allow-same-origin allow-scripts"></iframe>
</template>

<script setup lang="ts">
const model = defineModel<string>();
const editor = useTemplateRef('editor'), iframe = useTemplateRef('iframe');

onMounted(() => {
    if(iframe.value && iframe.value.contentDocument && editor.value)
    {
        editor.value.$el.remove();

        iframe.value.contentDocument.documentElement.setAttribute('class', document.documentElement.getAttribute('class') ?? '');
        iframe.value.contentDocument.documentElement.setAttribute('style', document.documentElement.getAttribute('style') ?? '');

        const base = iframe.value.contentDocument.head.appendChild(iframe.value.contentDocument.createElement('base'));
        base.setAttribute('href', window.location.href);

        for(let element of document.getElementsByTagName('link'))
        {
            if(element.getAttribute('rel') === 'stylesheet')
                iframe.value.contentDocument.head.appendChild(element.cloneNode(true));
        }

        for(let element of document.getElementsByTagName('style'))
        {
            iframe.value.contentDocument.head.appendChild(element.cloneNode(true));
        }

        iframe.value.contentDocument.body.setAttribute('class', document.body.getAttribute('class') ?? '');
        iframe.value.contentDocument.body.setAttribute('style', document.body.getAttribute('style') ?? '');

        iframe.value.contentDocument.body.appendChild(editor.value.$el);

        editor.value.focus();
    }
});
</script>