55 lines
1.2 KiB
TypeScript
Raw Normal View History

2018-04-02 05:34:16 +00:00
export default class TouchController {
2019-11-17 09:09:39 +00:00
public leftSwipe: Function
public rightSwipe: Function
public upSwipe: Function
public downSwipe: Function
2017-07-19 16:47:17 +00:00
2019-11-17 09:09:39 +00:00
private x: number
private y: number
private threshold: number
2017-07-19 16:47:17 +00:00
constructor() {
document.addEventListener("touchstart", evt => this.handleTouchStart(evt), false)
document.addEventListener("touchmove", evt => this.handleTouchMove(evt), false)
this.downSwipe = this.upSwipe = this.rightSwipe = this.leftSwipe = () => null
2017-07-21 06:09:22 +00:00
this.threshold = 3
2019-04-19 13:12:33 +00:00
this.x = -1
this.y = -1
2017-07-19 16:47:17 +00:00
}
2019-11-17 09:09:39 +00:00
private handleTouchStart(evt) {
2017-07-19 16:47:17 +00:00
this.x = evt.touches[0].clientX
this.y = evt.touches[0].clientY
}
2019-11-17 09:09:39 +00:00
private handleTouchMove(evt) {
2019-04-19 13:12:33 +00:00
if(this.x === -1 || this.y === -1) {
2017-07-19 16:47:17 +00:00
return
}
2019-11-17 09:09:39 +00:00
const xUp = evt.touches[0].clientX
const yUp = evt.touches[0].clientY
2017-07-19 16:47:17 +00:00
2019-11-17 09:09:39 +00:00
const xDiff = this.x - xUp
const yDiff = this.y - yUp
2017-07-19 16:47:17 +00:00
if(Math.abs(xDiff) > Math.abs(yDiff)) {
if(xDiff > this.threshold) {
this.leftSwipe()
} else if(xDiff < -this.threshold) {
this.rightSwipe()
}
} else {
if(yDiff > this.threshold) {
this.upSwipe()
} else if(yDiff < -this.threshold) {
this.downSwipe()
}
}
2018-04-02 05:34:16 +00:00
2019-04-19 13:12:33 +00:00
this.x = -1
this.y = -1
2017-07-19 16:47:17 +00:00
}
2019-11-17 09:09:39 +00:00
}