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.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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.altKey) {
  17. state.send("PRESSED_ALT_KEY", getKeyboardEventInfo(e))
  18. }
  19. if (e.key === "Backspace" && !(metaKey(e) || e.shiftKey || e.altKey)) {
  20. state.send("DELETED", getKeyboardEventInfo(e))
  21. }
  22. if (e.key === "s" && metaKey(e)) {
  23. e.preventDefault()
  24. state.send("SAVED")
  25. }
  26. if (e.key === "a" && metaKey(e)) {
  27. e.preventDefault()
  28. state.send("SELECTED_ALL")
  29. }
  30. if (e.key === "v" && !(metaKey(e) || e.shiftKey || e.altKey)) {
  31. state.send("SELECTED_SELECT_TOOL", getKeyboardEventInfo(e))
  32. }
  33. if (e.key === "d" && !(metaKey(e) || e.shiftKey || e.altKey)) {
  34. state.send("SELECTED_DOT_TOOL", getKeyboardEventInfo(e))
  35. }
  36. if (e.key === "c" && !(metaKey(e) || e.shiftKey || e.altKey)) {
  37. state.send("SELECTED_CIRCLE_TOOL", getKeyboardEventInfo(e))
  38. }
  39. if (e.key === "i" && !(metaKey(e) || e.shiftKey || e.altKey)) {
  40. state.send("SELECTED_ELLIPSE_TOOL", getKeyboardEventInfo(e))
  41. }
  42. if (e.key === "l" && !(metaKey(e) || e.shiftKey || e.altKey)) {
  43. state.send("SELECTED_LINE_TOOL", getKeyboardEventInfo(e))
  44. }
  45. if (e.key === "y" && !(metaKey(e) || e.shiftKey || e.altKey)) {
  46. state.send("SELECTED_RAY_TOOL", getKeyboardEventInfo(e))
  47. }
  48. if (e.key === "p" && !(metaKey(e) || e.shiftKey || e.altKey)) {
  49. state.send("SELECTED_POLYLINE_TOOL", getKeyboardEventInfo(e))
  50. }
  51. if (e.key === "r" && !(metaKey(e) || e.shiftKey || e.altKey)) {
  52. state.send("SELECTED_RECTANGLE_TOOL", getKeyboardEventInfo(e))
  53. }
  54. }
  55. function handleKeyUp(e: KeyboardEvent) {
  56. if (e.key === "Escape") {
  57. state.send("CANCELLED")
  58. }
  59. if (e.altKey) {
  60. state.send("RELEASED_ALT_KEY")
  61. }
  62. state.send("RELEASED_KEY", getKeyboardEventInfo(e))
  63. }
  64. document.body.addEventListener("keydown", handleKeyDown)
  65. document.body.addEventListener("keyup", handleKeyUp)
  66. return () => {
  67. document.body.removeEventListener("keydown", handleKeyDown)
  68. document.body.removeEventListener("keyup", handleKeyUp)
  69. }
  70. }, [])
  71. }