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.

useCanvasEvents.ts 1.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import { MutableRefObject, useCallback } from 'react'
  2. import state from 'state'
  3. import { fastBrushSelect, fastDrawUpdate } from 'state/hacks'
  4. import inputs from 'state/inputs'
  5. import { isMobile } from 'utils/utils'
  6. export default function useCanvasEvents(
  7. rCanvas: MutableRefObject<SVGGElement>
  8. ) {
  9. const handlePointerDown = useCallback((e: React.PointerEvent) => {
  10. if (!inputs.canAccept(e.pointerId)) return
  11. rCanvas.current.setPointerCapture(e.pointerId)
  12. if (e.button === 0) {
  13. state.send('POINTED_CANVAS', inputs.pointerDown(e, 'canvas'))
  14. } else if (e.button === 2) {
  15. state.send('RIGHT_POINTED', inputs.pointerDown(e, 'canvas'))
  16. }
  17. }, [])
  18. const handleTouchStart = useCallback((e: React.TouchEvent) => {
  19. if (isMobile()) {
  20. if (e.touches.length === 2) {
  21. state.send('TOUCH_UNDO')
  22. } else state.send('TOUCHED_CANVAS')
  23. }
  24. }, [])
  25. const handlePointerMove = useCallback((e: React.PointerEvent) => {
  26. if (!inputs.canAccept(e.pointerId)) return
  27. if (state.isIn('draw.editing')) {
  28. fastDrawUpdate(inputs.pointerMove(e))
  29. return
  30. }
  31. if (state.isIn('brushSelecting')) {
  32. const info = inputs.pointerMove(e)
  33. fastBrushSelect(info.point)
  34. return
  35. }
  36. state.send('MOVED_POINTER', inputs.pointerMove(e))
  37. }, [])
  38. const handlePointerUp = useCallback((e: React.PointerEvent) => {
  39. if (!inputs.canAccept(e.pointerId)) return
  40. rCanvas.current.releasePointerCapture(e.pointerId)
  41. state.send('STOPPED_POINTING', { id: 'canvas', ...inputs.pointerUp(e) })
  42. }, [])
  43. return {
  44. onPointerDown: handlePointerDown,
  45. onTouchStart: handleTouchStart,
  46. onPointerMove: handlePointerMove,
  47. onPointerUp: handlePointerUp,
  48. }
  49. }