<template>
  <span @click="toggleFocus" v-if="!focus">
    {{value}}
    <span class="empty-tip" v-if="!value">(empty)</span>
  </span>
  <el-input ref="ctl" v-model="inputVal" @blur="handleBlur" v-else></el-input>
</template>

<script>
export default {
  name: 'editable-input',
  props: [
    'value',
  ],
  data () {
    return {
      focus: false,
      inputVal: undefined,
    }
  },
  mounted () {
    if (!window['__editable-blur']) {
      window['__editable-blur'] = () => {}
    }
  },
  methods: {
    toggleFocus () {
      window['__editable-blur']()
      window['__editable-blur'] = this.handleBlur.bind(this)

      this.focus = true
      this.inputVal = this.value
      this.$nextTick(() => {
        if (this.$refs.ctl) this.$refs.ctl.focus()
      })
    },
    handleBlur() {
      this.focus = false

      if (this.inputVal != this.value) {
        this.$emit('change', this.inputVal )
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.empty-tip {
  font-size: 0.8em;
  color: #aaa;
}
</style>

