Skip to content

Commit

Permalink
Keypress handler closes #9 (#29)
Browse files Browse the repository at this point in the history
* add keypress handler

* delete on delete key too

* refactor var key -> pressedKey
  • Loading branch information
ConorSheehan1 authored Jul 16, 2023
1 parent 427b45b commit 34db31a
Showing 1 changed file with 31 additions and 1 deletion.
32 changes: 31 additions & 1 deletion src/components/Hive.vue
Original file line number Diff line number Diff line change
@@ -1,7 +1,16 @@
<script setup lang="ts">
import { ref } from "vue";
import { onMounted, onUnmounted, ref } from "vue";
import { useMainStore } from "../store";
import { shuffle } from "../utils";
import { useI18n } from "vue-i18n";
import en from "../locales/en.json";
const { t } = useI18n({
inheritLocale: true,
messages: {
en,
},
});
// `defineProps` is a compiler macro and no longer needs to be imported.
defineProps({
Expand All @@ -16,10 +25,31 @@ const otherLetters = ref(
);
let userGuess = ref("");
const onKeyPress = (e: KeyboardEvent) => {
const pressedKey = e.key.toLowerCase();
if (pressedKey === "enter")
return submitGuess({ $t: t, guess: userGuess.value });
if (["backspace", "delete"].includes(pressedKey)) {
userGuess.value = userGuess.value.slice(0, -1);
return false;
}
if (pressedKey.length === 1 && store.availableLetters.includes(pressedKey)) {
userGuess.value += pressedKey;
return true;
}
};
const submitGuess = ({ $t, guess }: { $t: Function; guess: string }) => {
userGuess.value = "";
store.submitGuess({ $t, guess });
};
onMounted(() => {
window.addEventListener("keyup", onKeyPress);
});
onUnmounted(() => {
window.removeEventListener("keyup", onKeyPress);
});
</script>

<template>
Expand Down

0 comments on commit 34db31a

Please sign in to comment.