import react, { useCallback, useState } from 'react'; import _ from 'lodash'; import { Transformation } from './viewport'; interface SingleTouchHandlerProps { applyTransformations: (transformations: Transformation[]) => void; children: any; } const SingleTouchHandler: react.FC = ( props: SingleTouchHandlerProps ) => { const initialTouchState = { state: 'up', touch: { x: -1, y: -1 }, }; const [touchState, setTouchState] = useState(initialTouchState); console.log('SingleTouchHandler, touchState: ' + JSON.stringify(touchState)); const genericHandler = (event: any) => { console.log('Log - Event: ' + event.type); if (event.type.startsWith('touch')) { if (event.touches.length > 0) { console.log( `Touch1 : (${event.touches[0].pageX}, ${event.touches[0].pageY})` ); } console.log('touchState: ' + JSON.stringify(touchState)); return; } }; const touchCancelHandler = (event: any) => { genericHandler(event); throtteledTouchMoveHandler.cancel(); setTouchState(initialTouchState); }; const touchStartHandler = (event: any) => { genericHandler(event); // event.preventDefault(); if (event.touches.length === 1) { setTouchState({ state: 'pointer', touch: { x: event.touches[0].pageX, y: event.touches[0].pageY }, }); } }; const touchEndHandler = (event: any) => { genericHandler(event); // event.preventDefault(); setTouchState(initialTouchState); throtteledTouchMoveHandler.cancel(); }; const touchMoveHandler = (event: any) => { // event.preventDefault(); if (touchState.state === 'pointer') { if (event.touches.length === 1) { genericHandler(event); props.applyTransformations([ { translate: { x: event.touches[0].pageX - touchState.touch.x, y: event.touches[0].pageY - touchState.touch.y, }, }, ]); setTouchState({ state: 'pointer', touch: { x: event.touches[0].pageX, y: event.touches[0].pageY, }, }); } } }; const throtteledTouchMoveHandler = useCallback( _.throttle(touchMoveHandler, 100), [touchState.state] ); return (
{props.children}
); }; export default SingleTouchHandler;