
<template>
  <ckeditor v-model="realValue"
            :editor="editor"
            :disabled="disabled"
            @ready="isReady=true"
            @update:modelValue="$emit('update:modelValue', $event)" />
</template>
<script>
import {ref, watch} from 'vue'
import CKEditor from '@ckeditor/ckeditor5-vue'
import editor from 'ckeditor5-build'

export default {
  setup: function(props) {
    const isReady = ref(false)
    const realValue = ref(props.modelValue)
    const tmpValue = ref(null)

    /*
    ckeditor doesnt allow to set data before its ready, Maybe a future ckeditor update will save us from this?
    see: https://github.com/ckeditor/ckeditor5-vue/issues/167
    */
    watch(() => props.modelValue, ()=>{
      if(isReady.value){
        realValue.value = props.modelValue
      } else{
        tmpValue.value = props.modelValue
      }
    })

    watch(isReady, ()=>{
      if(isReady.value && tmpValue.value !== null){
        realValue.value = tmpValue.value
      }
    })
    return {
      editor,
      isReady,
      realValue,
      tmpValue
    }
  },
  components: {
    // Use the <ckeditor> component in this view.
    ckeditor: CKEditor.component
  },
  props: {
    modelValue: {
      type: String,
      required: true
    },
    disabled: {
      type: Boolean,
      default: false
    },
  }
}
</script>
