Skip to content

Commit 4e9caa3

Browse files
committed
add shortcuts + keydown listener
1 parent 84f120f commit 4e9caa3

File tree

1 file changed

+33
-2
lines changed

1 file changed

+33
-2
lines changed

client/src/App.tsx

Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,10 @@
1-
import { useState } from "react";
1+
import { useState, useRef, useEffect } from "react";
22
import "./App.css";
33
import { pick_random_word } from "./main.ts";
44
import { get_definition } from "./main.ts";
55
import { is_valid } from "./main.ts";
66
import "animate.css";
77

8-
98
function Square( { letter, colors, onSquareClick } ) {
109
let color = letter.length > 0 && colors != null ? colors[letter.charCodeAt(0) - "A".charCodeAt(0)] : "";
1110

@@ -53,6 +52,21 @@ function Definition( { word, definition }) {
5352
</>
5453
}
5554

55+
const useEventListener = (eventName, handler, element = window) => {
56+
const savedHandler = useRef();
57+
useEffect(() => {
58+
savedHandler.current = handler;
59+
}, [handler]);
60+
useEffect(() => {
61+
const eventListener = (event) => savedHandler.current(event);
62+
element.addEventListener(eventName, eventListener);
63+
return () => {
64+
element.removeEventListener(eventName, eventListener);
65+
};
66+
}, [eventName, element]);
67+
};
68+
69+
5670
function App() {
5771
const [current_word, setCurrentWord] = useState(pick_random_word(5).toUpperCase());
5872
const [current_definition, setCurrentDefinition] = useState(get_definition(current_word.toLowerCase()));
@@ -139,6 +153,23 @@ function App() {
139153

140154
console.log(current_word);
141155

156+
const handler = ({ key }) => {
157+
console.log("Key Pressed: " + String(key));
158+
if (current_attempt.length < current_word.length && (letters.includes(key) || letters.includes(key.toUpperCase()))) {
159+
setCurrentAttempt(current_attempt + key.toUpperCase())
160+
}
161+
else if (key == "Backspace" && !success) {
162+
if (current_attempt.length > 0)
163+
setCurrentAttempt(current_attempt.substring(0, current_attempt.length - 1))
164+
}
165+
else if (key == "Enter") {
166+
checkAttempt();
167+
}
168+
else if (key == "Escape") {
169+
restart();
170+
}
171+
};
172+
useEventListener("keydown", handler);
142173

143174
return (
144175
<>

0 commit comments

Comments
 (0)