-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathplugin.swipe.ts
115 lines (102 loc) · 2.67 KB
/
plugin.swipe.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
/**
* Plugin to detect the finger swipe event.
* Scope:
* - Detect swipe direction
* - Detect swipe distance
* - Detect swipe speed
* @class SwipePlugin
* @extends PluginBuilder
* @experimental
*/
import { PluginBuilder } from '../core'
import { BindResult } from '../../types'
export default class SwipePlugin extends PluginBuilder {
override key: string = 'swipe'
private touchstart: any = {
x: 0,
y: 0
}
private touchend: any = {
x: 0,
y: 0
}
private fingerCount: number = 0
private minDistance: number = 50 //Minimum distance for the swipe to work
override bind(): BindResult[] {
return [
{
name: 'swipe',
target: document,
event: 'touchstart',
callback: (event: TouchEvent) => {
return this.captureEvent(event)
}
},
{
name: 'swipe',
target: document,
event: 'touchend',
callback: (event: TouchEvent) => {
return this.captureEvent(event)
}
}
]
}
/**
* A function to capture the swipe direction, distance and speed.
* return false if the swipe is less than the minimum distance.
* return false if the touchstart
*
*/
private captureEvent(event: TouchEvent): Record<string, any> | false {
if (event.type === 'touchstart') {
this.touchstart = {
x: event.touches[0].pageX,
y: event.touches[0].pageY
}
this.fingerCount = event.touches.length
return false
} else if (event.type === 'touchend') {
this.touchend = {
x: event.changedTouches[0].pageX,
y: event.changedTouches[0].pageY
}
this.fingerCount = event.touches.length
}
if (this.fingerCount === 1 && this.touchend.x !== 0) {
let x = this.touchend.x - this.touchstart.x
let y = this.touchend.y - this.touchstart.y
let distance = Math.sqrt(x * x + y * y)
let direction = this.getDirection(x, y)
let speed = this.getSpeed(distance)
if (distance >= this.minDistance) {
return {
direction: direction,
distance: distance,
speed: speed
}
}
}
return false
}
/**
* A function to get the distance of the swipe.
* minDistance is the minimum distance for the swipe to work.
*/
/**
* A function to get the direction (up, down, left right) of the swipe.
*/
private getDirection(x: number, y: number): string {
if (Math.abs(x) > Math.abs(y)) {
return x > 0 ? 'right' : 'left'
} else {
return y > 0 ? 'down' : 'up'
}
}
/**
* A function to get the speed of the swipe.
*/
private getSpeed(distance: number): number {
return distance / 100
}
}