|
1 | | -import { useState } from "react"; |
| 1 | +import { useState, useRef, useEffect } from "react"; |
2 | 2 | import "./App.css"; |
3 | 3 | import { pick_random_word } from "./main.ts"; |
4 | 4 | import { get_definition } from "./main.ts"; |
5 | 5 | import { is_valid } from "./main.ts"; |
6 | 6 | import "animate.css"; |
7 | 7 |
|
8 | | - |
9 | 8 | function Square( { letter, colors, onSquareClick } ) { |
10 | 9 | let color = letter.length > 0 && colors != null ? colors[letter.charCodeAt(0) - "A".charCodeAt(0)] : ""; |
11 | 10 |
|
@@ -53,6 +52,21 @@ function Definition( { word, definition }) { |
53 | 52 | </> |
54 | 53 | } |
55 | 54 |
|
| 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 | + |
56 | 70 | function App() { |
57 | 71 | const [current_word, setCurrentWord] = useState(pick_random_word(5).toUpperCase()); |
58 | 72 | const [current_definition, setCurrentDefinition] = useState(get_definition(current_word.toLowerCase())); |
@@ -139,6 +153,23 @@ function App() { |
139 | 153 |
|
140 | 154 | console.log(current_word); |
141 | 155 |
|
| 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); |
142 | 173 |
|
143 | 174 | return ( |
144 | 175 | <> |
|
0 commit comments