<template>
  <div ref="editor"></div>
</template>

<script lang="ts" setup>
import {
  computed,
  onBeforeUnmount,
  onMounted,
  ref,
  watchEffect
} from 'vue'
import WangEditor from 'wangeditor'

const props = defineProps({
  value: {
    type: String,
    default: ''
  },
  disable: {
    type: Boolean,
    default: false
  }
})

const emits = defineEmits(['update:value'])

const editor = ref()

const content = computed({
  set: val => emits('update:value', val),
  get: () => props.value
})

let instance: WangEditor | null

onMounted(() => {
  instance = new WangEditor(editor.value)
  Object.assign(instance.config, {
    zIndex: 9,
    onchange: (html: string) => (content.value = html)
  })
  instance.create()

  watchEffect(() =>
    instance && props.disable ? instance.disable() : instance?.enable()
  )
})

onBeforeUnmount(() => {
  instance && instance.destroy()
  instance = null
})

</script>
