Skip to content
Snippets Groups Projects
KeyboardDisplay.vue 1.32 KiB
Newer Older
<template>
  <div>
    <button type="button" v-on:mouseup="addChar('a')">
      Insert character "a"
    </button>
    <button type="button" v-on:mouseup="addChar('b')">
      Insert character "b"
    </button>
    <a v-if="optionsModal" href="#">Options</a>
  </div>
</template>

<script>
export default {
  props: {
    inputField: {
      type: [HTMLInputElement, HTMLTextAreaElement],
      required: true,
    },
    optionsModal: {
      type: Boolean,
      default: false,
    },
  },
  data: () => ({
    keysSwitch: { a: "b" },
  }),
  mounted() {
    this.inputField.onkeydown = (e) => {
      const character = this.keysSwitch[e.key];
      if (!character) return;
      this.addChar(character);
      return false;
    };
  },
  methods: {
    addChar(char) {
      // Add a character to the input depending on the cursor selection
      const start = this.inputField.selectionStart;
      const value = this.inputField.value;
      this.inputField.value =
        value.slice(0, start) +
        char +
        value.slice(this.inputField.selectionEnd);
      // Reset the input caret after modifying the input value
      this.inputField.selectionStart = this.inputField.selectionEnd = start + 1;
    },
  },
};
</script>

<style scoped>
.virtual-keyboard {
  position: absolute;
  display: flex;
}
button {
  padding: 1rem;
}
</style>