Eduard Kuzmenko
4 years ago
5 changed files with 109 additions and 107 deletions
@ -0,0 +1,61 @@ |
|||||||
|
export type GrabEvent = {x: number, y: number, isTouch?: boolean}; |
||||||
|
|
||||||
|
export default function attachGrabListeners(element: HTMLElement, onStart: (position: GrabEvent) => void, onMove: (position: GrabEvent) => void, onEnd: (position: GrabEvent) => void) { |
||||||
|
// * Mouse
|
||||||
|
const onMouseMove = (event: MouseEvent) => { |
||||||
|
onMove({x: event.pageX, y: event.pageY}); |
||||||
|
}; |
||||||
|
|
||||||
|
const onMouseUp = (event: MouseEvent) => { |
||||||
|
document.removeEventListener('mousemove', onMouseMove); |
||||||
|
element.addEventListener('mousedown', onMouseDown, {once: true}); |
||||||
|
onEnd && onEnd({x: event.pageX, y: event.pageY}); |
||||||
|
}; |
||||||
|
|
||||||
|
const onMouseDown = (event: MouseEvent) => { |
||||||
|
if(event.button !== 0) { |
||||||
|
element.addEventListener('mousedown', onMouseDown, {once: true}); |
||||||
|
return; |
||||||
|
} |
||||||
|
|
||||||
|
onStart({x: event.pageX, y: event.pageY}); |
||||||
|
onMouseMove(event); |
||||||
|
|
||||||
|
document.addEventListener('mousemove', onMouseMove); |
||||||
|
document.addEventListener('mouseup', onMouseUp, {once: true}); |
||||||
|
}; |
||||||
|
|
||||||
|
element.addEventListener('mousedown', onMouseDown, {once: true}); |
||||||
|
|
||||||
|
// * Touch
|
||||||
|
const onTouchMove = (event: TouchEvent) => { |
||||||
|
event.preventDefault(); |
||||||
|
onMove({x: event.touches[0].clientX, y: event.touches[0].clientY, isTouch: true}); |
||||||
|
}; |
||||||
|
|
||||||
|
const onTouchEnd = (event: TouchEvent) => { |
||||||
|
document.removeEventListener('touchmove', onTouchMove); |
||||||
|
element.addEventListener('touchstart', onTouchStart, {passive: true, once: true}); |
||||||
|
onEnd && onEnd({x: event.touches[0].clientX, y: event.touches[0].clientY, isTouch: true}); |
||||||
|
}; |
||||||
|
|
||||||
|
const onTouchStart = (event: TouchEvent) => { |
||||||
|
onStart({x: event.touches[0].clientX, y: event.touches[0].clientY, isTouch: true}); |
||||||
|
onTouchMove(event); |
||||||
|
|
||||||
|
document.addEventListener('touchmove', onTouchMove, {passive: false}); |
||||||
|
document.addEventListener('touchend', onTouchEnd, {passive: true, once: true}); |
||||||
|
}; |
||||||
|
|
||||||
|
element.addEventListener('touchstart', onTouchStart, {passive: true, once: true}); |
||||||
|
|
||||||
|
return () => { |
||||||
|
element.removeEventListener('mousedown', onMouseDown); |
||||||
|
document.removeEventListener('mousemove', onMouseMove); |
||||||
|
document.removeEventListener('mouseup', onMouseUp); |
||||||
|
|
||||||
|
element.removeEventListener('touchstart', onTouchStart); |
||||||
|
document.removeEventListener('touchmove', onTouchMove); |
||||||
|
document.removeEventListener('touchend', onTouchEnd); |
||||||
|
}; |
||||||
|
} |
Loading…
Reference in new issue