SecureNotes/src/helper/swipe.tsx

77 lines
2.4 KiB
TypeScript
Executable File

import { Component, h, cloneElement } from 'preact';
export default class SwipeRecognizer extends Component<{ onSwipe?: (direction: string) => void }, { swipe: string }> {
private tolerance = 100;
private gesture = { x: [], y: [], match: '' };
componentDidMount() {
this.base.addEventListener('touchstart', this.capture);
this.base.addEventListener('touchmove', this.capture);
this.base.addEventListener('touchend', this.compute)
}
componentWillUnmount() {
this.base.removeEventListener('touchstart', this.capture);
this.base.removeEventListener('touchmove', this.capture);
this.base.removeEventListener('touchend', this.compute);
}
private capture = (event: TouchEvent) => {
// event.preventDefault()
this.gesture.x.push(event.touches[0].clientX)
this.gesture.y.push(event.touches[0].clientY)
};
private compute = (event: TouchEvent) => {
// event.preventDefault();
let xStart = this.gesture.x[0];
let yStart = this.gesture.y[0];
let xEnd = this.gesture.x.pop();
let yEnd = this.gesture.y.pop();
let xTravel = xEnd - xStart;
let yTravel = yEnd - yStart;
console.log(xTravel, yTravel);
let xTravel_b = xTravel < 0 ? xTravel * (-1) : xTravel;
let yTravel_b = yTravel < 0 ? yTravel * (-1) : yTravel;
console.log(xTravel_b, yTravel_b);
if (xTravel_b > yTravel_b) {
if (xTravel_b > this.tolerance) {
if (xTravel > 0) {
this.gesture.match = "right";
} else {
this.gesture.match = "left";
}
}
} else {
if (yTravel_b > this.tolerance) {
if (yTravel > 0) {
this.gesture.match = "down";
} else {
this.gesture.match = "up";
}
}
}
console.log(this.gesture.match);
if (this.gesture.match !== '') {
this.onSwipe(this.gesture.match);
}
this.gesture.x = []
this.gesture.y = []
this.gesture.match = '';
};
onSwipe = (direction: string) => {
if (this.props.onSwipe) {
this.props.onSwipe(direction);
}
this.setState({ swipe: direction });
};
render({ children }, state) {
return cloneElement(children[0], state);
}
}