<template>
  <view class="ml-editor">
    <rich-text v-if="isFromReadonly" :nodes="nodes" :selectable="selectable"></rich-text>
    <rich-text v-else-if="isFormDisabled" :nodes="nodes" :selectable="selectable"></rich-text>
    <view v-else></view>
  </view>
</template>

<script>
import parseHtml from './html-parser'

export default {
  name: 'MlEditor',
  props: {
    value: String,
    readonly: Boolean,
    disabled: Boolean,
    selectable: {
      type: Boolean,
      default: true
    }
  },
  inject: {
    form: {
      from: 'mlForm',
      default: null
    },
    formItem: {
      from: 'mlFormItem',
      default: null
    }
  },
  data () {
    return {
      nodes: []
    }
  },
  computed: {
    isFromReadonly () {
      if (this.readonly) {
        return true
      }
      return this.form ? this.form.readonly : false
    },
    isFormDisabled () {
      if (this.disabled) {
        return true
      }
      return this.formItem ? this.formItem.isFormDisabled : false
    }
  },
  watch: {
    value () {
      this.load()
    }
  },
  mounted () {
    this.load()
  },
  methods: {
    load () {
      this.nodes = this.value ? parseHtml(this.value) : []
    }
  }
}
</script>

<style lang="scss">
.ml-editor {
  display: block;
  word-break: break-word;
}
</style>
