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

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