sandbox/background-move/src/components/single-touch-handler.tsx

100 lines
2.5 KiB
TypeScript
Raw Normal View History

import react, { useCallback, useState } from 'react';
import _ from 'lodash';
import { Point } from './viewport';
2022-09-09 18:24:16 +00:00
interface SingleTouchHandlerProps {
updateShift: (shiftDelta: Point) => void;
children: any;
}
2022-09-09 18:24:16 +00:00
const SingleTouchHandler: react.FC<SingleTouchHandlerProps> = (
props: SingleTouchHandlerProps
) => {
const initialTouchState = {
state: 'up',
touch: { x: -1, y: -1 },
};
const [touchState, setTouchState] = useState(initialTouchState);
2022-09-09 18:24:16 +00:00
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.updateShift({
x: touchState.touch.x - event.touches[0].pageX,
y: touchState.touch.y - event.touches[0].pageY,
});
setTouchState({
state: 'pointer',
touch: {
x: event.touches[0].pageX,
y: event.touches[0].pageY,
},
});
}
}
};
const throtteledTouchMoveHandler = useCallback(
_.throttle(touchMoveHandler, 100),
[touchState.state]
);
return (
<div
className='viewport'
onTouchStart={touchStartHandler}
onTouchMove={throtteledTouchMoveHandler}
onTouchEnd={touchEndHandler}
onTouchCancel={touchCancelHandler}
>
{props.children}
</div>
);
};
2022-09-09 18:22:20 +00:00
export default SingleTouchHandler;