Tldraw/hooks/useKeyboardEvents.ts

37 wiersze
1022 B
TypeScript
Czysty Zwykły widok Historia

2021-05-12 11:27:33 +00:00
import { useEffect } from "react"
import state from "state"
2021-05-13 08:34:56 +00:00
import { getKeyboardEventInfo, isDarwin } from "utils/utils"
2021-05-12 11:27:33 +00:00
export default function useKeyboardEvents() {
useEffect(() => {
function handleKeyDown(e: KeyboardEvent) {
if (e.key === "Escape") {
state.send("CANCELLED")
2021-05-13 08:34:56 +00:00
} else if (e.key === "z" && (isDarwin() ? e.metaKey : e.ctrlKey)) {
if (e.shiftKey) {
state.send("REDO")
} else {
state.send("UNDO")
}
2021-05-12 11:27:33 +00:00
}
state.send("PRESSED_KEY", getKeyboardEventInfo(e))
}
function handleKeyUp(e: KeyboardEvent) {
if (e.key === "Escape") {
state.send("CANCELLED")
}
state.send("RELEASED_KEY", getKeyboardEventInfo(e))
}
document.body.addEventListener("keydown", handleKeyDown)
document.body.addEventListener("keyup", handleKeyUp)
return () => {
document.body.removeEventListener("keydown", handleKeyDown)
document.body.removeEventListener("keyup", handleKeyUp)
}
}, [])
}