You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

useKeyboardEvents.ts 827B

123456789101112131415161718192021222324252627282930
  1. import { useEffect } from "react"
  2. import state from "state"
  3. import { getKeyboardEventInfo } from "utils/utils"
  4. export default function useKeyboardEvents() {
  5. useEffect(() => {
  6. function handleKeyDown(e: KeyboardEvent) {
  7. if (e.key === "Escape") {
  8. state.send("CANCELLED")
  9. }
  10. state.send("PRESSED_KEY", getKeyboardEventInfo(e))
  11. }
  12. function handleKeyUp(e: KeyboardEvent) {
  13. if (e.key === "Escape") {
  14. state.send("CANCELLED")
  15. }
  16. state.send("RELEASED_KEY", getKeyboardEventInfo(e))
  17. }
  18. document.body.addEventListener("keydown", handleKeyDown)
  19. document.body.addEventListener("keyup", handleKeyUp)
  20. return () => {
  21. document.body.removeEventListener("keydown", handleKeyDown)
  22. document.body.removeEventListener("keyup", handleKeyUp)
  23. }
  24. }, [])
  25. }