<style scoped>
.autogrow-text {
  display: grid;
  flex: 0 0 auto;
}
textarea, .template {
  grid-area: 1 / 1 / 1 / 1;
  resize: none;
  overflow: hidden;
  word-break: break-word;
  white-space: pre-wrap;
}
.template {
  visibility: hidden;
  color: darkred !important;
  background: transparent !important;
  z-index: 1;
  touch-action: none;
  pointer-events: none;
  opacity: 1;
}
</style>

<style module>
.element_default {
  padding: 2px;
  font-size: 15px;
  border: 1px solid rgb(133, 133, 133);
}
</style>

<template>
  <div class="autogrow-text">
    <textarea
      ref="text"
      :class="cssModule || $style.element_default"
      :tabindex="tabindex"
      :value="value"
      :placeholder="placeholder"
      :maxlength="maxlength"
      :rows="1"
      @keydown="$emit('keydown', $event)"
      @keypress="$emit('keypress', $event)"
      @change="$emit('change', $event)"
      @input="handleInput"
      @click="$emit('click', $event)"
    />
    <!-- eslint-disable-next-line vue/singleline-html-element-content-newline -->
    <div
      class="template"
      :class="cssModule || $style.element_default">{{ value }}</div>
  </div>
</template>

<script>
export default {
  name: 'AutogrowTextarea',
  props: {
    value: { type: String, default: '' },
    type: { type: String, default: 'text' },
    placeholder: { type: String, default: '' },
    maxlength: { type: Number, default: null },
    tabindex: { type: String, default: '0' },
    cssModule: { type: String, default: null },
  },
  methods: {
    focus() {
      this.$el.querySelector('textarea').focus();
    },
    handleInput(e) {
      this.$emit('update:value', e.target.value);
    },
  },
};
</script>
