<template>
  <div class="itf-inline-edit">
    <div
      :role="editable ? 'button' : 'textbox'"
      tabindex="1"
      ref="input"
      @focus="onFocus"
      @blur="onBlur"
      @keydown.enter="onEnter"
      @keydown.esc="onCancel"
      class="notranslate"
      spellcheck="true"
      placeholder=" "
      :contenteditable="editable"
      v-html="value">
    </div>
    <itf-copy-to-clipboard :value="value" />
  </div>
</template>
<style lang="scss" scoped>
.itf-inline-edit {
  margin: -5px;
  padding: 5px;
}
.notranslate {
  border: 0 none;
  margin: 0;
  outline: 0;
  resize: none;
  background: transparent;
  max-width: 100%;
  width: 100%;
  white-space: pre-wrap;
  word-break: break-word;
  caret-color: var(--bs-body-color);
}
</style>
<script>
import { Vue, Component, Model, Prop } from 'vue-property-decorator';
import itfIcon from '../../icon/Icon.vue';
import itfTextField from '../../text-field/TextField.vue';
import itfCopyToClipboard from '../../copyToClipboard/CopyToClipboard';

export default @Component({
  name: 'itfCustomizeInlineText',
  components: {
    itfIcon,
    itfTextField,
    itfCopyToClipboard
  }
})

class itfCustomizeInlineText extends Vue {
  @Model('input') value;
  @Prop(Boolean) editable;

  mounted() {
    this.$refs.input.addEventListener('paste', function(e) {
      // cancel paste
      e.preventDefault();

      // get text representation of clipboard
      var text = (e.originalEvent || e).clipboardData.getData('text/plain');

      // insert text manually
      document.execCommand("insertHTML", false, text);
    });
  }

  onEnter(event) {
    if (event.shiftKey) {
      return;
    }
    event.preventDefault();
    event.stopPropagation();

    this.$refs.input.blur();
  }

  onBlur() {
    this.$emit('input', this.$refs.input.innerHTML);
    this.$emit('blur');
  }

  onCancel(event) {
    event.target.value = this.value;
    this.$refs.input.blur();
  }

  onFocus() {
    this.$emit('focus');
  }
}
</script>
