<template>
  <div
    ref="text"
    class="c-text"
    :style="styles"
    :contenteditable="contenteditable"
    @blur="onBlur"
    v-text="node.text"
  />
</template>

<script>
import { WidgetType } from '../constant'

export default {
  name: WidgetType.TEXT,
  props: {
    node: {
      type: Object,
      default: null
    },
    editable: {
      type: [Boolean, String],
      default: false
    }
  },
  computed: {
    styles () {
      const {
        width,
        height,
        color,
        fontSize,
        fontWeight,
        textAlign,
        backgroundColor
      } = this.node
      return {
        width: `${width}px`,
        height: `${height}px`,
        color,
        'font-size': `${fontSize}px`,
        'font-weight': fontWeight,
        'text-align': textAlign,
        'background-color': backgroundColor
      }
    },
    contenteditable () {
      return this.editable ? 'plaintext-only' : false
    }
  },
  methods: {
    onBlur () {
      this.node.text = this.$refs.text.innerText
      this.$nextTick(() => {
        this.$refs.text.scrollTop = 0
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.c-text {
  position: relative;
  display: inline-block;
  word-wrap: break-word;
  white-space: pre-wrap;
  overflow: hidden;

  &[contenteditable="plaintext-only"] {
    cursor: text;
  }
}
</style>
