<template>
  <div class="text-input">
    <label>
      <span class="label"><slot></slot></span>
      <input type="text"
             :placeholder="placeholder"
             :class="{error: error, readonly: readonly}"
             v-bind:value="value"
             v-on:input="input"
             v-on:change="change"
             v-on:keypress="keypress"
             :readonly="readonly">
    </label>
  </div>
</template>

<script>
export default {
  name: "text-input",
  props: ['value', 'placeholder', 'readonly', 'error'],
  methods: {
    clear: function () {
      this.$emit('clearError', null);
    },
    input: function (event) {
      this.clear();
      this.$emit('input', event.target.value);
    },
    change: function (event) {
      this.clear();
      this.$emit('change', event.target.value);
    },
    keypress: function (event) {
      if (event.keyCode === 13 || event.keyCode === 10)
        this.$emit('enter', event.target.value)

      this.clear();
    }
  }
}
</script>

<style scoped>
.label {
  font-size: 80%;
}

input {
  width: 100%;
}

input.error {
  background-color: rgba(255, 0, 0, 0.3);
  border-color: var(--error);
}

input.readonly {
  background-color: rgba(0, 0, 0, 0.1);
}
</style>
