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 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import { useEffect } from "react"
  2. import state from "state"
  3. import { getKeyboardEventInfo, isDarwin, metaKey } 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. } else if (e.key === "z" && metaKey(e)) {
  10. if (e.shiftKey) {
  11. state.send("REDO")
  12. } else {
  13. state.send("UNDO")
  14. }
  15. }
  16. if (e.key === "Backspace" && !(metaKey(e) || e.shiftKey || e.altKey)) {
  17. state.send("DELETED", getKeyboardEventInfo(e))
  18. }
  19. if (e.key === "v" && !(metaKey(e) || e.shiftKey || e.altKey)) {
  20. state.send("SELECTED_SELECT_TOOL", getKeyboardEventInfo(e))
  21. }
  22. if (e.key === "d" && !(metaKey(e) || e.shiftKey || e.altKey)) {
  23. state.send("SELECTED_DOT_TOOL", getKeyboardEventInfo(e))
  24. }
  25. if (e.key === "c" && !(metaKey(e) || e.shiftKey || e.altKey)) {
  26. state.send("SELECTED_CIRCLE_TOOL", getKeyboardEventInfo(e))
  27. }
  28. if (e.key === "i" && !(metaKey(e) || e.shiftKey || e.altKey)) {
  29. state.send("SELECTED_ELLIPSE_TOOL", getKeyboardEventInfo(e))
  30. }
  31. if (e.key === "l" && !(metaKey(e) || e.shiftKey || e.altKey)) {
  32. state.send("SELECTED_LINE_TOOL", getKeyboardEventInfo(e))
  33. }
  34. if (e.key === "y" && !(metaKey(e) || e.shiftKey || e.altKey)) {
  35. state.send("SELECTED_RAY_TOOL", getKeyboardEventInfo(e))
  36. }
  37. if (e.key === "p" && !(metaKey(e) || e.shiftKey || e.altKey)) {
  38. state.send("SELECTED_POLYLINE_TOOL", getKeyboardEventInfo(e))
  39. }
  40. if (e.key === "r" && !(metaKey(e) || e.shiftKey || e.altKey)) {
  41. state.send("SELECTED_RECTANGLE_TOOL", getKeyboardEventInfo(e))
  42. }
  43. }
  44. function handleKeyUp(e: KeyboardEvent) {
  45. if (e.key === "Escape") {
  46. state.send("CANCELLED")
  47. }
  48. state.send("RELEASED_KEY", getKeyboardEventInfo(e))
  49. }
  50. document.body.addEventListener("keydown", handleKeyDown)
  51. document.body.addEventListener("keyup", handleKeyUp)
  52. return () => {
  53. document.body.removeEventListener("keydown", handleKeyDown)
  54. document.body.removeEventListener("keyup", handleKeyUp)
  55. }
  56. }, [])
  57. }