您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

useKeyboardEvents.ts 2.4KB

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