2021-06-06 10:50:01 +00:00
|
|
|
import { MutableRefObject, useCallback } from 'react'
|
|
|
|
import state from 'state'
|
2021-06-13 14:12:59 +00:00
|
|
|
import { fastBrushSelect, fastDrawUpdate, fastTranslate } from 'state/hacks'
|
2021-06-06 10:50:01 +00:00
|
|
|
import inputs from 'state/inputs'
|
|
|
|
import { isMobile } from 'utils/utils'
|
|
|
|
|
|
|
|
export default function useCanvasEvents(
|
|
|
|
rCanvas: MutableRefObject<SVGGElement>
|
|
|
|
) {
|
|
|
|
const handlePointerDown = useCallback((e: React.PointerEvent) => {
|
|
|
|
if (!inputs.canAccept(e.pointerId)) return
|
2021-06-10 09:49:16 +00:00
|
|
|
|
2021-06-06 10:50:01 +00:00
|
|
|
rCanvas.current.setPointerCapture(e.pointerId)
|
2021-06-10 09:49:16 +00:00
|
|
|
|
|
|
|
if (e.button === 0) {
|
|
|
|
state.send('POINTED_CANVAS', inputs.pointerDown(e, 'canvas'))
|
|
|
|
} else if (e.button === 2) {
|
|
|
|
state.send('RIGHT_POINTED', inputs.pointerDown(e, 'canvas'))
|
|
|
|
}
|
2021-06-06 10:50:01 +00:00
|
|
|
}, [])
|
|
|
|
|
|
|
|
const handleTouchStart = useCallback((e: React.TouchEvent) => {
|
|
|
|
if (isMobile()) {
|
|
|
|
if (e.touches.length === 2) {
|
|
|
|
state.send('TOUCH_UNDO')
|
|
|
|
} else state.send('TOUCHED_CANVAS')
|
|
|
|
}
|
|
|
|
}, [])
|
|
|
|
|
|
|
|
const handlePointerMove = useCallback((e: React.PointerEvent) => {
|
|
|
|
if (!inputs.canAccept(e.pointerId)) return
|
|
|
|
|
2021-06-13 14:12:59 +00:00
|
|
|
const info = inputs.pointerMove(e)
|
|
|
|
|
2021-06-06 10:50:01 +00:00
|
|
|
if (state.isIn('draw.editing')) {
|
2021-06-13 14:12:59 +00:00
|
|
|
fastDrawUpdate(info)
|
2021-06-06 10:50:01 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if (state.isIn('brushSelecting')) {
|
|
|
|
fastBrushSelect(info.point)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2021-06-13 14:12:59 +00:00
|
|
|
if (state.isIn('translatingSelection')) {
|
|
|
|
fastTranslate(info)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
state.send('MOVED_POINTER', info)
|
2021-06-06 10:50:01 +00:00
|
|
|
}, [])
|
|
|
|
|
|
|
|
const handlePointerUp = useCallback((e: React.PointerEvent) => {
|
|
|
|
if (!inputs.canAccept(e.pointerId)) return
|
|
|
|
rCanvas.current.releasePointerCapture(e.pointerId)
|
|
|
|
state.send('STOPPED_POINTING', { id: 'canvas', ...inputs.pointerUp(e) })
|
|
|
|
}, [])
|
|
|
|
|
|
|
|
return {
|
|
|
|
onPointerDown: handlePointerDown,
|
|
|
|
onTouchStart: handleTouchStart,
|
|
|
|
onPointerMove: handlePointerMove,
|
|
|
|
onPointerUp: handlePointerUp,
|
|
|
|
}
|
|
|
|
}
|