-
Notifications
You must be signed in to change notification settings - Fork 10
/
index.js
302 lines (265 loc) · 8.28 KB
/
index.js
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
/**
* Starts monitoring swipes on the given element and
* emits `swipe` event when a swipe gesture is performed.
* @param {DOMElement} element Element on which to listen for swipe gestures.
* @param {Object} options Optional: Options.
* @return {Object}
*/
const SwipeListener = function (element, options) {
if (!element) return;
// CustomEvent polyfill
if (typeof window !== 'undefined') {
(function() {
if (typeof window.CustomEvent === 'function') return false;
function CustomEvent(event, params) {
params = params || { bubbles: false, cancelable: false, detail: undefined };
var evt = document.createEvent('CustomEvent');
evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
return evt;
}
CustomEvent.prototype = window.Event.prototype;
window.CustomEvent = CustomEvent;
})();
}
let defaultOpts = {
minHorizontal: 10, // Minimum number of pixels traveled to count as a horizontal swipe.
minVertical: 10, // Minimum number of pixels traveled to count as a vertical swipe.
deltaHorizontal: 3, // Delta for horizontal swipe
deltaVertical: 5, // Delta for vertical swipe
preventScroll: false, // Prevents scrolling when swiping.
lockAxis: true, // Select only one axis to be true instead of multiple.
touch: true, // Listen for touch events
mouse: true, // Listen for mouse events
};
// Set options
if (!options) {
options = {};
}
options = {
...defaultOpts,
...options
};
// Store the touches
let touches = [];
// Not dragging by default.
let dragging = false;
// When mouse-click is started, make dragging true.
const _mousedown = function (e) {
dragging = true;
}
// When mouse-click is released, make dragging false and signify end by imitating `touchend`.
const _mouseup = function (e) {
dragging = false;
_touchend(e);
}
// When mouse is moved while being clicked, imitate a `touchmove`.
const _mousemove = function (e) {
if (dragging) {
e.changedTouches = [{
clientX: e.clientX,
clientY: e.clientY
}];
_touchmove(e);
}
}
if (options.mouse) {
element.addEventListener('mousedown', _mousedown);
element.addEventListener('mouseup', _mouseup);
element.addEventListener('mousemove', _mousemove);
}
// When the swipe is completed, calculate the direction.
const _touchend = function(e) {
if (!touches.length) return;
const touch = typeof TouchEvent === 'function' && e instanceof TouchEvent;
let x = [],
y = [];
let directions = {
top: false,
right: false,
bottom: false,
left: false
};
for (let i = 0; i < touches.length; i++) {
x.push(touches[i].x);
y.push(touches[i].y);
}
const xs = x[0], xe = x[x.length - 1], // Start and end x-coords
ys = y[0], ye = y[y.length - 1]; // Start and end y-coords
const eventCoords = {
x: [xs, xe],
y: [ys, ye]
};
if (touches.length > 1) {
const swipeReleaseEventData = {
detail: {
touch,
target: e.target,
...eventCoords
},
};
let swipeReleaseEvent = new CustomEvent('swiperelease', swipeReleaseEventData);
element.dispatchEvent(swipeReleaseEvent);
}
// Determine left or right
let diff = x[0] - x[x.length - 1];
let swipe = 'none';
if (diff > 0) {
swipe = 'left';
} else {
swipe = 'right';
}
let min = Math.min(...x),
max = Math.max(...x),
_diff;
// If minimum horizontal distance was travelled
if (Math.abs(diff) >= options.minHorizontal) {
switch (swipe) {
case 'left':
_diff = Math.abs(min - x[x.length - 1]);
if (_diff <= options.deltaHorizontal) {
directions.left = true;
}
break;
case 'right':
_diff = Math.abs(max - x[x.length - 1]);
if (_diff <= options.deltaHorizontal) {
directions.right = true;
}
break;
}
}
// Determine top or bottom
diff = y[0] - y[y.length - 1];
swipe = 'none';
if (diff > 0) {
swipe = 'top';
} else {
swipe = 'bottom';
}
min = Math.min(...y);
max = Math.max(...y);
// If minimum vertical distance was travelled
if (Math.abs(diff) >= options.minVertical) {
switch (swipe) {
case 'top':
_diff = Math.abs(min - y[y.length - 1]);
if (_diff <= options.deltaVertical) {
directions.top = true;
}
break;
case 'bottom':
_diff = Math.abs(max - y[y.length - 1]);
if (_diff <= options.deltaVertical) {
directions.bottom = true;
}
break;
}
}
// Clear touches array.
touches = [];
// If there is a swipe direction, emit an event.
if (directions.top ||
directions.right ||
directions.bottom ||
directions.left) {
/**
* If lockAxis is true, determine which axis to select.
* The axis with the most travel is selected.
* TODO: Factor in for the orientation of the device
* and use it as a weight to determine the travel along an axis.
*/
if (options.lockAxis) {
if ((directions.left || directions.right) && Math.abs(xs - xe) > Math.abs(ys - ye)) {
directions.top = directions.bottom = false;
} else if ((directions.top || directions.bottom) && Math.abs(xs - xe) < Math.abs(ys - ye)) {
directions.left = directions.right = false;
}
}
const eventData = {
detail: {
directions,
touch,
target: e.target,
...eventCoords
},
};
let event = new CustomEvent('swipe', eventData);
element.dispatchEvent(event);
} else {
let cancelEvent = new CustomEvent('swipecancel', {
detail: {
touch,
target: e.target,
...eventCoords,
}
});
element.dispatchEvent(cancelEvent);
}
};
// When a swipe is performed, store the coords.
const _touchmove = function (e) {
let touch = e.changedTouches[0];
touches.push({
x: touch.clientX,
y: touch.clientY
});
// Emit a `swiping` event if there are more than one touch-points.
if (touches.length > 1) {
const xs = touches[0].x, // Start and end x-coords
xe = touches[touches.length - 1].x,
ys = touches[0].y, // Start and end y-coords
ye = touches[touches.length - 1].y,
eventData = {
detail: {
x: [xs, xe],
y: [ys, ye],
touch: typeof TouchEvent === 'function' && e instanceof TouchEvent,
target: e.target
},
};
let event = new CustomEvent('swiping', eventData);
const shouldPrevent = options.preventScroll === true ||
(typeof options.preventScroll === 'function' && options.preventScroll(event));
if(shouldPrevent) {
e.preventDefault();
}
element.dispatchEvent(event);
}
}
// Test via a getter in the options object to see if the passive property is accessed
let passiveOptions = false;
try {
const testOptions = Object.defineProperty({}, 'passive', {
get: function () {
passiveOptions = {passive: !options.preventScroll};
}
});
window.addEventListener('testPassive', null, testOptions);
window.removeEventListener('testPassive', null, testOptions);
} catch (e) {}
if (options.touch) {
element.addEventListener('touchmove', _touchmove, passiveOptions);
element.addEventListener('touchend', _touchend);
}
return {
off: function () {
element.removeEventListener('touchmove', _touchmove, passiveOptions);
element.removeEventListener('touchend', _touchend);
element.removeEventListener('mousedown', _mousedown);
element.removeEventListener('mouseup', _mouseup);
element.removeEventListener('mousemove', _mousemove);
}
}
};
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
module.exports = SwipeListener;
module.exports.default = SwipeListener;
} else {
if (typeof define === 'function' && define.amd) {
define([], function() {
return SwipeListener;
});
} else {
window.SwipeListener = SwipeListener;
}
}