-
Notifications
You must be signed in to change notification settings - Fork 13.5k
/
tap.js
622 lines (522 loc) · 20.2 KB
/
tap.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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
/**
* @ngdoc page
* @name tap
* @module ionic
* @description
* On touch devices such as a phone or tablet, some browsers implement a 300ms delay between
* the time the user stops touching the display and the moment the browser executes the
* click. This delay was initially introduced so the browser can know whether the user wants to
* double-tap to zoom in on the webpage. Basically, the browser waits roughly 300ms to see if
* the user is double-tapping, or just tapping on the display once.
*
* Out of the box, Ionic automatically removes the 300ms delay in order to make Ionic apps
* feel more "native" like. Resultingly, other solutions such as
* [fastclick](https://github.com/ftlabs/fastclick) and Angular's
* [ngTouch](https://docs.angularjs.org/api/ngTouch) should not be included, to avoid conflicts.
*
* Some browsers already remove the delay with certain settings, such as the CSS property
* `touch-events: none` or with specific meta tag viewport values. However, each of these
* browsers still handle clicks differently, such as when to fire off or cancel the event
* (like scrolling when the target is a button, or holding a button down).
* For browsers that already remove the 300ms delay, consider Ionic's tap system as a way to
* normalize how clicks are handled across the various devices so there's an expected response
* no matter what the device, platform or version. Additionally, Ionic will prevent
* ghostclicks which even browsers that remove the delay still experience.
*
* In some cases, third-party libraries may also be working with touch events which can interfere
* with the tap system. For example, mapping libraries like Google or Leaflet Maps often implement
* a touch detection system which conflicts with Ionic's tap system.
*
* ### Disabling the tap system
*
* To disable the tap for an element and all of its children elements,
* add the attribute `data-tap-disabled="true"`.
*
* ```html
* <div data-tap-disabled="true">
* <div id="google-map"></div>
* </div>
* ```
*
* ### Additional Notes:
*
* - Ionic tap works with Ionic's JavaScript scrolling
* - Elements can come and go from the DOM and Ionic tap doesn't keep adding and removing
* listeners
* - No "tap delay" after the first "tap" (you can tap as fast as you want, they all click)
* - Minimal events listeners, only being added to document
* - Correct focus in/out on each input type (select, textearea, range) on each platform/device
* - Shows and hides virtual keyboard correctly for each platform/device
* - Works with labels surrounding inputs
* - Does not fire off a click if the user moves the pointer too far
* - Adds and removes an 'activated' css class
* - Multiple [unit tests](https://github.com/driftyco/ionic/blob/master/test/unit/utils/tap.unit.js) for each scenario
*
*/
/*
IONIC TAP
---------------
- Both touch and mouse events are added to the document.body on DOM ready
- If a touch event happens, it does not use mouse event listeners
- On touchend, if the distance between start and end was small, trigger a click
- In the triggered click event, add a 'isIonicTap' property
- The triggered click receives the same x,y coordinates as as the end event
- On document.body click listener (with useCapture=true), only allow clicks with 'isIonicTap'
- Triggering clicks with mouse events work the same as touch, except with mousedown/mouseup
- Tapping inputs is disabled during scrolling
*/
var tapDoc; // the element which the listeners are on (document.body)
var tapActiveEle; // the element which is active (probably has focus)
var tapEnabledTouchEvents;
var tapMouseResetTimer;
var tapPointerMoved;
var tapPointerStart;
var tapTouchFocusedInput;
var tapLastTouchTarget;
var tapTouchMoveListener = 'touchmove';
// how much the coordinates can be off between start/end, but still a click
var TAP_RELEASE_TOLERANCE = 12; // default tolerance
var TAP_RELEASE_BUTTON_TOLERANCE = 50; // button elements should have a larger tolerance
var tapEventListeners = {
'click': tapClickGateKeeper,
'mousedown': tapMouseDown,
'mouseup': tapMouseUp,
'mousemove': tapMouseMove,
'touchstart': tapTouchStart,
'touchend': tapTouchEnd,
'touchcancel': tapTouchCancel,
'touchmove': tapTouchMove,
'pointerdown': tapTouchStart,
'pointerup': tapTouchEnd,
'pointercancel': tapTouchCancel,
'pointermove': tapTouchMove,
'MSPointerDown': tapTouchStart,
'MSPointerUp': tapTouchEnd,
'MSPointerCancel': tapTouchCancel,
'MSPointerMove': tapTouchMove,
'focusin': tapFocusIn,
'focusout': tapFocusOut
};
ionic.tap = {
register: function(ele) {
tapDoc = ele;
tapEventListener('click', true, true);
tapEventListener('mouseup');
tapEventListener('mousedown');
if (window.navigator.pointerEnabled) {
tapEventListener('pointerdown');
tapEventListener('pointerup');
tapEventListener('pointercancel');
tapTouchMoveListener = 'pointermove';
} else if (window.navigator.msPointerEnabled) {
tapEventListener('MSPointerDown');
tapEventListener('MSPointerUp');
tapEventListener('MSPointerCancel');
tapTouchMoveListener = 'MSPointerMove';
} else {
tapEventListener('touchstart');
tapEventListener('touchend');
tapEventListener('touchcancel');
}
tapEventListener('focusin');
tapEventListener('focusout');
return function() {
for (var type in tapEventListeners) {
tapEventListener(type, false);
}
tapDoc = null;
tapActiveEle = null;
tapEnabledTouchEvents = false;
tapPointerMoved = false;
tapPointerStart = null;
};
},
ignoreScrollStart: function(e) {
return (e.defaultPrevented) || // defaultPrevented has been assigned by another component handling the event
(/^(file|range)$/i).test(e.target.type) ||
(e.target.dataset ? e.target.dataset.preventScroll : e.target.getAttribute('data-prevent-scroll')) == 'true' || // manually set within an elements attributes
(!!(/^(object|embed)$/i).test(e.target.tagName)) || // flash/movie/object touches should not try to scroll
ionic.tap.isElementTapDisabled(e.target); // check if this element, or an ancestor, has `data-tap-disabled` attribute
},
isTextInput: function(ele) {
return !!ele &&
(ele.tagName == 'TEXTAREA' ||
ele.contentEditable === 'true' ||
(ele.tagName == 'INPUT' && !(/^(radio|checkbox|range|file|submit|reset|color|image|button)$/i).test(ele.type)));
},
isDateInput: function(ele) {
return !!ele &&
(ele.tagName == 'INPUT' && (/^(date|time|datetime-local|month|week)$/i).test(ele.type));
},
isVideo: function(ele) {
return !!ele &&
(ele.tagName == 'VIDEO');
},
isKeyboardElement: function(ele) {
if ( !ionic.Platform.isIOS() || ionic.Platform.isIPad() ) {
return ionic.tap.isTextInput(ele) && !ionic.tap.isDateInput(ele);
} else {
return ionic.tap.isTextInput(ele) || ( !!ele && ele.tagName == "SELECT");
}
},
isLabelWithTextInput: function(ele) {
var container = tapContainingElement(ele, false);
return !!container &&
ionic.tap.isTextInput(tapTargetElement(container));
},
containsOrIsTextInput: function(ele) {
return ionic.tap.isTextInput(ele) || ionic.tap.isLabelWithTextInput(ele);
},
cloneFocusedInput: function(container) {
if (ionic.tap.hasCheckedClone) return;
ionic.tap.hasCheckedClone = true;
ionic.requestAnimationFrame(function() {
var focusInput = container.querySelector(':focus');
if (ionic.tap.isTextInput(focusInput) && !ionic.tap.isDateInput(focusInput)) {
var clonedInput = focusInput.cloneNode(true);
clonedInput.value = focusInput.value;
clonedInput.classList.add('cloned-text-input');
clonedInput.readOnly = true;
if (focusInput.isContentEditable) {
clonedInput.contentEditable = focusInput.contentEditable;
clonedInput.innerHTML = focusInput.innerHTML;
}
focusInput.parentElement.insertBefore(clonedInput, focusInput);
focusInput.classList.add('previous-input-focus');
clonedInput.scrollTop = focusInput.scrollTop;
}
});
},
hasCheckedClone: false,
removeClonedInputs: function(container) {
ionic.tap.hasCheckedClone = false;
ionic.requestAnimationFrame(function() {
var clonedInputs = container.querySelectorAll('.cloned-text-input');
var previousInputFocus = container.querySelectorAll('.previous-input-focus');
var x;
for (x = 0; x < clonedInputs.length; x++) {
clonedInputs[x].parentElement.removeChild(clonedInputs[x]);
}
for (x = 0; x < previousInputFocus.length; x++) {
previousInputFocus[x].classList.remove('previous-input-focus');
previousInputFocus[x].style.top = '';
if ( ionic.keyboard.isOpen && !ionic.keyboard.isClosing ) previousInputFocus[x].focus();
}
});
},
requiresNativeClick: function(ele) {
if (ionic.Platform.isWindowsPhone() && (ele.tagName == 'A' || ele.tagName == 'BUTTON' || ele.hasAttribute('ng-click') || (ele.tagName == 'INPUT' && (ele.type == 'button' || ele.type == 'submit')))) {
return true; //Windows Phone edge case, prevent ng-click (and similar) events from firing twice on this platform
}
if (!ele || ele.disabled || (/^(file|range)$/i).test(ele.type) || (/^(object|video)$/i).test(ele.tagName) || ionic.tap.isLabelContainingFileInput(ele)) {
return true;
}
return ionic.tap.isElementTapDisabled(ele);
},
isLabelContainingFileInput: function(ele) {
var lbl = tapContainingElement(ele);
if (lbl.tagName !== 'LABEL') return false;
var fileInput = lbl.querySelector('input[type=file]');
if (fileInput && fileInput.disabled === false) return true;
return false;
},
isElementTapDisabled: function(ele) {
if (ele && ele.nodeType === 1) {
var element = ele;
while (element) {
if ((element.dataset ? element.dataset.tapDisabled : element.getAttribute && element.getAttribute('data-tap-disabled')) == 'true') {
return true;
}
element = element.parentElement;
}
}
return false;
},
setTolerance: function(releaseTolerance, releaseButtonTolerance) {
TAP_RELEASE_TOLERANCE = releaseTolerance;
TAP_RELEASE_BUTTON_TOLERANCE = releaseButtonTolerance;
},
cancelClick: function() {
// used to cancel any simulated clicks which may happen on a touchend/mouseup
// gestures uses this method within its tap and hold events
tapPointerMoved = true;
},
pointerCoord: function(event) {
// This method can get coordinates for both a mouse click
// or a touch depending on the given event
var c = { x: 0, y: 0 };
if (event) {
var touches = event.touches && event.touches.length ? event.touches : [event];
var e = (event.changedTouches && event.changedTouches[0]) || touches[0];
if (e) {
c.x = e.clientX || e.pageX || 0;
c.y = e.clientY || e.pageY || 0;
}
}
return c;
}
};
function tapEventListener(type, enable, useCapture) {
if (enable !== false) {
tapDoc.addEventListener(type, tapEventListeners[type], useCapture);
} else {
tapDoc.removeEventListener(type, tapEventListeners[type]);
}
}
function tapClick(e) {
// simulate a normal click by running the element's click method then focus on it
var container = tapContainingElement(e.target);
var ele = tapTargetElement(container);
if (ionic.tap.requiresNativeClick(ele) || tapPointerMoved) return false;
var c = ionic.tap.pointerCoord(e);
//console.log('tapClick', e.type, ele.tagName, '('+c.x+','+c.y+')');
triggerMouseEvent('click', ele, c.x, c.y);
// if it's an input, focus in on the target, otherwise blur
tapHandleFocus(ele);
}
function triggerMouseEvent(type, ele, x, y) {
// using initMouseEvent instead of MouseEvent for our Android friends
var clickEvent = document.createEvent("MouseEvents");
clickEvent.initMouseEvent(type, true, true, window, 1, 0, 0, x, y, false, false, false, false, 0, null);
clickEvent.isIonicTap = true;
ele.dispatchEvent(clickEvent);
}
function tapClickGateKeeper(e) {
//console.log('click ' + Date.now() + ' isIonicTap: ' + (e.isIonicTap ? true : false));
if (e.target.type == 'submit' && e.detail === 0) {
// do not prevent click if it came from an "Enter" or "Go" keypress submit
return null;
}
// do not allow through any click events that were not created by ionic.tap
if ((ionic.scroll.isScrolling && ionic.tap.containsOrIsTextInput(e.target)) ||
(!e.isIonicTap && !ionic.tap.requiresNativeClick(e.target))) {
//console.log('clickPrevent', e.target.tagName);
e.stopPropagation();
if (!ionic.tap.isLabelWithTextInput(e.target)) {
// labels clicks from native should not preventDefault othersize keyboard will not show on input focus
e.preventDefault();
}
return false;
}
}
// MOUSE
function tapMouseDown(e) {
//console.log('mousedown ' + Date.now());
if (e.isIonicTap || tapIgnoreEvent(e)) return null;
if (tapEnabledTouchEvents) {
//console.log('mousedown', 'stop event');
e.stopPropagation();
if (!ionic.Platform.isEdge() && (!ionic.tap.isTextInput(e.target) || tapLastTouchTarget !== e.target) &&
!isSelectOrOption(e.target.tagName) && !ionic.tap.isVideo(e.target)) {
// If you preventDefault on a text input then you cannot move its text caret/cursor.
// Allow through only the text input default. However, without preventDefault on an
// input the 300ms delay can change focus on inputs after the keyboard shows up.
// The focusin event handles the chance of focus changing after the keyboard shows.
// Windows Phone - if you preventDefault on a video element then you cannot operate
// its native controls.
e.preventDefault();
}
return false;
}
tapPointerMoved = false;
tapPointerStart = ionic.tap.pointerCoord(e);
tapEventListener('mousemove');
ionic.activator.start(e);
}
function tapMouseUp(e) {
//console.log("mouseup " + Date.now());
if (tapEnabledTouchEvents) {
e.stopPropagation();
e.preventDefault();
return false;
}
if (tapIgnoreEvent(e) || isSelectOrOption(e.target.tagName)) return false;
if (!tapHasPointerMoved(e)) {
tapClick(e);
}
tapEventListener('mousemove', false);
ionic.activator.end();
tapPointerMoved = false;
}
function tapMouseMove(e) {
if (tapHasPointerMoved(e)) {
tapEventListener('mousemove', false);
ionic.activator.end();
tapPointerMoved = true;
return false;
}
}
// TOUCH
function tapTouchStart(e) {
//console.log("touchstart " + Date.now());
if (tapIgnoreEvent(e)) return;
tapPointerMoved = false;
tapEnableTouchEvents();
tapPointerStart = ionic.tap.pointerCoord(e);
tapEventListener(tapTouchMoveListener);
ionic.activator.start(e);
if (ionic.Platform.isIOS() && ionic.tap.isLabelWithTextInput(e.target)) {
// if the tapped element is a label, which has a child input
// then preventDefault so iOS doesn't ugly auto scroll to the input
// but do not prevent default on Android or else you cannot move the text caret
// and do not prevent default on Android or else no virtual keyboard shows up
var textInput = tapTargetElement(tapContainingElement(e.target));
if (textInput !== tapActiveEle) {
// don't preventDefault on an already focused input or else iOS's text caret isn't usable
//console.log('Would prevent default here');
e.preventDefault();
}
}
}
function tapTouchEnd(e) {
//console.log('touchend ' + Date.now());
if (tapIgnoreEvent(e)) return;
tapEnableTouchEvents();
if (!tapHasPointerMoved(e)) {
tapClick(e);
if (isSelectOrOption(e.target.tagName)) {
e.preventDefault();
}
}
tapLastTouchTarget = e.target;
tapTouchCancel();
}
function tapTouchMove(e) {
if (tapHasPointerMoved(e)) {
tapPointerMoved = true;
tapEventListener(tapTouchMoveListener, false);
ionic.activator.end();
return false;
}
}
function tapTouchCancel() {
tapEventListener(tapTouchMoveListener, false);
ionic.activator.end();
tapPointerMoved = false;
}
function tapEnableTouchEvents() {
tapEnabledTouchEvents = true;
clearTimeout(tapMouseResetTimer);
tapMouseResetTimer = setTimeout(function() {
tapEnabledTouchEvents = false;
}, 600);
}
function tapIgnoreEvent(e) {
if (e.isTapHandled) return true;
e.isTapHandled = true;
if(ionic.tap.isElementTapDisabled(e.target)) {
return true;
}
if (ionic.scroll.isScrolling && ionic.tap.containsOrIsTextInput(e.target)) {
e.preventDefault();
return true;
}
}
function tapHandleFocus(ele) {
tapTouchFocusedInput = null;
var triggerFocusIn = false;
if (ele.tagName == 'SELECT') {
// trick to force Android options to show up
triggerMouseEvent('mousedown', ele, 0, 0);
ele.focus && ele.focus();
triggerFocusIn = true;
} else if (tapActiveElement() === ele) {
// already is the active element and has focus
triggerFocusIn = true;
} else if ((/^(input|textarea|ion-label)$/i).test(ele.tagName) || ele.isContentEditable) {
triggerFocusIn = true;
ele.focus && ele.focus();
ele.value = ele.value;
if (tapEnabledTouchEvents) {
tapTouchFocusedInput = ele;
}
} else {
tapFocusOutActive();
}
if (triggerFocusIn) {
tapActiveElement(ele);
ionic.trigger('ionic.focusin', {
target: ele
}, true);
}
}
function tapFocusOutActive() {
var ele = tapActiveElement();
if (ele && ((/^(input|textarea|select)$/i).test(ele.tagName) || ele.isContentEditable)) {
//console.log('tapFocusOutActive', ele.tagName);
ele.blur();
}
tapActiveElement(null);
}
function tapFocusIn(e) {
//console.log('focusin ' + Date.now());
// Because a text input doesn't preventDefault (so the caret still works) there's a chance
// that its mousedown event 300ms later will change the focus to another element after
// the keyboard shows up.
if (tapEnabledTouchEvents &&
ionic.tap.isTextInput(tapActiveElement()) &&
ionic.tap.isTextInput(tapTouchFocusedInput) &&
tapTouchFocusedInput !== e.target) {
// 1) The pointer is from touch events
// 2) There is an active element which is a text input
// 3) A text input was just set to be focused on by a touch event
// 4) A new focus has been set, however the target isn't the one the touch event wanted
//console.log('focusin', 'tapTouchFocusedInput');
tapTouchFocusedInput.focus();
tapTouchFocusedInput = null;
}
ionic.scroll.isScrolling = false;
}
function tapFocusOut() {
//console.log("focusout");
tapActiveElement(null);
}
function tapActiveElement(ele) {
if (arguments.length) {
tapActiveEle = ele;
}
return tapActiveEle || document.activeElement;
}
function tapHasPointerMoved(endEvent) {
if (!endEvent || endEvent.target.nodeType !== 1 || !tapPointerStart || (tapPointerStart.x === 0 && tapPointerStart.y === 0)) {
return false;
}
var endCoordinates = ionic.tap.pointerCoord(endEvent);
var hasClassList = !!(endEvent.target.classList && endEvent.target.classList.contains &&
typeof endEvent.target.classList.contains === 'function');
var releaseTolerance = hasClassList && endEvent.target.classList.contains('button') ?
TAP_RELEASE_BUTTON_TOLERANCE :
TAP_RELEASE_TOLERANCE;
return Math.abs(tapPointerStart.x - endCoordinates.x) > releaseTolerance ||
Math.abs(tapPointerStart.y - endCoordinates.y) > releaseTolerance;
}
function tapContainingElement(ele, allowSelf) {
var climbEle = ele;
for (var x = 0; x < 6; x++) {
if (!climbEle) break;
if (climbEle.tagName === 'LABEL') return climbEle;
climbEle = climbEle.parentElement;
}
if (allowSelf !== false) return ele;
}
function tapTargetElement(ele) {
if (ele && ele.tagName === 'LABEL') {
if (ele.control) return ele.control;
// older devices do not support the "control" property
if (ele.querySelector) {
var control = ele.querySelector('input,textarea,select');
if (control) return control;
}
}
return ele;
}
function isSelectOrOption(tagName){
return (/^(select|option)$/i).test(tagName);
}
ionic.DomUtil.ready(function() {
var ng = typeof angular !== 'undefined' ? angular : null;
//do nothing for e2e tests
if (!ng || (ng && !ng.scenario)) {
ionic.tap.register(document);
}
});