2
* @license AngularJS v1.2.0-rc.3
3
* (c) 2010-2012 Google, Inc. http://angularjs.org
6
(function(window, angular, undefined) {'use strict';
15
* `ngTouch` is the name of the optional Angular module that provides touch events and other
16
* helpers for touch-enabled devices.
17
* The implementation is based on jQuery Mobile touch event handling
18
* ([jquerymobile.com](http://jquerymobile.com/))
20
* {@installModule touch}
22
* See {@link ngTouch.$swipe `$swipe`} for usage.
25
// define ngTouch module
26
var ngTouch = angular.module('ngTouch', []);
30
* @name ngTouch.$swipe
33
* The `$swipe` service is a service that abstracts the messier details of hold-and-drag swipe
34
* behavior, to make implementing swipe-related directives more convenient.
36
* Requires the {@link ngTouch `ngTouch`} module to be installed.
38
* `$swipe` is used by the `ngSwipeLeft` and `ngSwipeRight` directives in `ngTouch`, and by
39
* `ngCarousel` in a separate component.
42
* The `$swipe` service is an object with a single method: `bind`. `bind` takes an element
43
* which is to be watched for swipes, and an object with four handler functions. See the
44
* documentation for `bind` below.
47
ngTouch.factory('$swipe', [function() {
48
// The total distance in any direction before we make the call on swipe vs. scroll.
49
var MOVE_BUFFER_RADIUS = 10;
51
function getCoordinates(event) {
52
var touches = event.touches && event.touches.length ? event.touches : [event];
53
var e = (event.changedTouches && event.changedTouches[0]) ||
54
(event.originalEvent && event.originalEvent.changedTouches &&
55
event.originalEvent.changedTouches[0]) ||
56
touches[0].originalEvent || touches[0];
67
* @name ngTouch.$swipe#bind
68
* @methodOf ngTouch.$swipe
71
* The main method of `$swipe`. It takes an element to be watched for swipe motions, and an
72
* object containing event handlers.
74
* The four events are `start`, `move`, `end`, and `cancel`. `start`, `move`, and `end`
75
* receive as a parameter a coordinates object of the form `{ x: 150, y: 310 }`.
77
* `start` is called on either `mousedown` or `touchstart`. After this event, `$swipe` is
78
* watching for `touchmove` or `mousemove` events. These events are ignored until the total
79
* distance moved in either dimension exceeds a small threshold.
81
* Once this threshold is exceeded, either the horizontal or vertical delta is greater.
82
* - If the horizontal distance is greater, this is a swipe and `move` and `end` events follow.
83
* - If the vertical distance is greater, this is a scroll, and we let the browser take over.
84
* A `cancel` event is sent.
86
* `move` is called on `mousemove` and `touchmove` after the above logic has determined that
87
* a swipe is in progress.
89
* `end` is called when a swipe is successfully completed with a `touchend` or `mouseup`.
91
* `cancel` is called either on a `touchcancel` from the browser, or when we begin scrolling
95
bind: function(element, eventHandlers) {
96
// Absolute total movement, used to control swipe vs. scroll.
98
// Coordinates of the start position.
100
// Last event's position.
102
// Whether a swipe is active.
105
element.on('touchstart mousedown', function(event) {
106
startCoords = getCoordinates(event);
110
lastPos = startCoords;
111
eventHandlers['start'] && eventHandlers['start'](startCoords, event);
114
element.on('touchcancel', function(event) {
116
eventHandlers['cancel'] && eventHandlers['cancel'](event);
119
element.on('touchmove mousemove', function(event) {
122
// Android will send a touchcancel if it thinks we're starting to scroll.
123
// So when the total distance (+ or - or both) exceeds 10px in either direction,
125
// - On totalX > totalY, we send preventDefault() and treat this as a swipe.
126
// - On totalY > totalX, we let the browser handle it as a scroll.
128
if (!startCoords) return;
129
var coords = getCoordinates(event);
131
totalX += Math.abs(coords.x - lastPos.x);
132
totalY += Math.abs(coords.y - lastPos.y);
136
if (totalX < MOVE_BUFFER_RADIUS && totalY < MOVE_BUFFER_RADIUS) {
140
// One of totalX or totalY has exceeded the buffer, so decide on swipe vs. scroll.
141
if (totalY > totalX) {
142
// Allow native scrolling to take over.
144
eventHandlers['cancel'] && eventHandlers['cancel'](event);
147
// Prevent the browser from scrolling.
148
event.preventDefault();
149
eventHandlers['move'] && eventHandlers['move'](coords, event);
153
element.on('touchend mouseup', function(event) {
156
eventHandlers['end'] && eventHandlers['end'](getCoordinates(event), event);
164
* @name ngTouch.directive:ngClick
167
* A more powerful replacement for the default ngClick designed to be used on touchscreen
168
* devices. Most mobile browsers wait about 300ms after a tap-and-release before sending
169
* the click event. This version handles them immediately, and then prevents the
170
* following click event from propagating.
172
* Requires the {@link ngTouch `ngTouch`} module to be installed.
174
* This directive can fall back to using an ordinary click event, and so works on desktop
175
* browsers as well as mobile.
177
* This directive also sets the CSS class `ng-click-active` while the element is being held
178
* down (by a mouse click or touch) so you can restyle the depressed element if you wish.
181
* @param {expression} ngClick {@link guide/expression Expression} to evaluate
182
* upon tap. (Event object is available as `$event`)
187
<button ng-click="count = count + 1" ng-init="count=0">
195
ngTouch.config(['$provide', function($provide) {
196
$provide.decorator('ngClickDirective', ['$delegate', function($delegate) {
197
// drop the default ngClick directive
203
ngTouch.directive('ngClick', ['$parse', '$timeout', '$rootElement',
204
function($parse, $timeout, $rootElement) {
205
var TAP_DURATION = 750; // Shorter than 750ms is a tap, longer is a taphold or drag.
206
var MOVE_TOLERANCE = 12; // 12px seems to work in most mobile browsers.
207
var PREVENT_DURATION = 2500; // 2.5 seconds maximum from preventGhostClick call to click
208
var CLICKBUSTER_THRESHOLD = 25; // 25 pixels in any dimension is the limit for busting clicks.
210
var ACTIVE_CLASS_NAME = 'ng-click-active';
211
var lastPreventedTime;
212
var touchCoordinates;
215
// TAP EVENTS AND GHOST CLICKS
218
// Mobile browsers detect a tap, then wait a moment (usually ~300ms) to see if you're
219
// double-tapping, and then fire a click event.
221
// This delay sucks and makes mobile apps feel unresponsive.
222
// So we detect touchstart, touchmove, touchcancel and touchend ourselves and determine when
223
// the user has tapped on something.
225
// What happens when the browser then generates a click event?
226
// The browser, of course, also detects the tap and fires a click after a delay. This results in
227
// tapping/clicking twice. So we do "clickbusting" to prevent it.
230
// We attach global touchstart and click handlers, that run during the capture (early) phase.
231
// So the sequence for a tap is:
232
// - global touchstart: Sets an "allowable region" at the point touched.
233
// - element's touchstart: Starts a touch
234
// (- touchmove or touchcancel ends the touch, no click follows)
235
// - element's touchend: Determines if the tap is valid (didn't move too far away, didn't hold
236
// too long) and fires the user's tap handler. The touchend also calls preventGhostClick().
237
// - preventGhostClick() removes the allowable region the global touchstart created.
238
// - The browser generates a click event.
239
// - The global click handler catches the click, and checks whether it was in an allowable region.
240
// - If preventGhostClick was called, the region will have been removed, the click is busted.
241
// - If the region is still there, the click proceeds normally. Therefore clicks on links and
242
// other elements without ngTap on them work normally.
244
// This is an ugly, terrible hack!
245
// Yeah, tell me about it. The alternatives are using the slow click events, or making our users
246
// deal with the ghost clicks, so I consider this the least of evils. Fortunately Angular
247
// encapsulates this ugly logic away from the user.
249
// Why not just put click handlers on the element?
250
// We do that too, just to be sure. The problem is that the tap event might have caused the DOM
251
// to change, so that the click fires in the same position but something else is there now. So
252
// the handlers are global and care only about coordinates and not elements.
254
// Checks if the coordinates are close enough to be within the region.
255
function hit(x1, y1, x2, y2) {
256
return Math.abs(x1 - x2) < CLICKBUSTER_THRESHOLD && Math.abs(y1 - y2) < CLICKBUSTER_THRESHOLD;
259
// Checks a list of allowable regions against a click location.
260
// Returns true if the click should be allowed.
261
// Splices out the allowable region from the list after it has been used.
262
function checkAllowableRegions(touchCoordinates, x, y) {
263
for (var i = 0; i < touchCoordinates.length; i += 2) {
264
if (hit(touchCoordinates[i], touchCoordinates[i+1], x, y)) {
265
touchCoordinates.splice(i, i + 2);
266
return true; // allowable region
269
return false; // No allowable region; bust it.
272
// Global click handler that prevents the click if it's in a bustable zone and preventGhostClick
273
// was called recently.
274
function onClick(event) {
275
if (Date.now() - lastPreventedTime > PREVENT_DURATION) {
279
var touches = event.touches && event.touches.length ? event.touches : [event];
280
var x = touches[0].clientX;
281
var y = touches[0].clientY;
282
// Work around desktop Webkit quirk where clicking a label will fire two clicks (on the label
283
// and on the input element). Depending on the exact browser, this second click we don't want
284
// to bust has either (0,0) or negative coordinates.
285
if (x < 1 && y < 1) {
289
// Look for an allowable region containing this click.
290
// If we find one, that means it was created by touchstart and not removed by
291
// preventGhostClick, so we don't bust it.
292
if (checkAllowableRegions(touchCoordinates, x, y)) {
296
// If we didn't find an allowable region, bust the click.
297
event.stopPropagation();
298
event.preventDefault();
300
// Blur focused form elements
301
event.target && event.target.blur();
305
// Global touchstart handler that creates an allowable region for a click event.
306
// This allowable region can be removed by preventGhostClick if we want to bust it.
307
function onTouchStart(event) {
308
var touches = event.touches && event.touches.length ? event.touches : [event];
309
var x = touches[0].clientX;
310
var y = touches[0].clientY;
311
touchCoordinates.push(x, y);
313
$timeout(function() {
314
// Remove the allowable region.
315
for (var i = 0; i < touchCoordinates.length; i += 2) {
316
if (touchCoordinates[i] == x && touchCoordinates[i+1] == y) {
317
touchCoordinates.splice(i, i + 2);
321
}, PREVENT_DURATION, false);
324
// On the first call, attaches some event handlers. Then whenever it gets called, it creates a
325
// zone around the touchstart where clicks will get busted.
326
function preventGhostClick(x, y) {
327
if (!touchCoordinates) {
328
$rootElement[0].addEventListener('click', onClick, true);
329
$rootElement[0].addEventListener('touchstart', onTouchStart, true);
330
touchCoordinates = [];
333
lastPreventedTime = Date.now();
335
checkAllowableRegions(touchCoordinates, x, y);
338
// Actual linking function.
339
return function(scope, element, attr) {
340
var clickHandler = $parse(attr.ngClick),
342
tapElement, // Used to blur the element after a tap.
343
startTime, // Used to check if the tap was held too long.
347
function resetState() {
349
element.removeClass(ACTIVE_CLASS_NAME);
352
element.on('touchstart', function(event) {
354
tapElement = event.target ? event.target : event.srcElement; // IE uses srcElement.
355
// Hack for Safari, which can target text nodes instead of containers.
356
if(tapElement.nodeType == 3) {
357
tapElement = tapElement.parentNode;
360
element.addClass(ACTIVE_CLASS_NAME);
362
startTime = Date.now();
364
var touches = event.touches && event.touches.length ? event.touches : [event];
365
var e = touches[0].originalEvent || touches[0];
366
touchStartX = e.clientX;
367
touchStartY = e.clientY;
370
element.on('touchmove', function(event) {
374
element.on('touchcancel', function(event) {
378
element.on('touchend', function(event) {
379
var diff = Date.now() - startTime;
381
var touches = (event.changedTouches && event.changedTouches.length) ? event.changedTouches :
382
((event.touches && event.touches.length) ? event.touches : [event]);
383
var e = touches[0].originalEvent || touches[0];
386
var dist = Math.sqrt( Math.pow(x - touchStartX, 2) + Math.pow(y - touchStartY, 2) );
388
if (tapping && diff < TAP_DURATION && dist < MOVE_TOLERANCE) {
389
// Call preventGhostClick so the clickbuster will catch the corresponding click.
390
preventGhostClick(x, y);
392
// Blur the focused element (the button, probably) before firing the callback.
393
// This doesn't work perfectly on Android Chrome, but seems to work elsewhere.
394
// I couldn't get anything to work reliably on Android Chrome.
399
if (!angular.isDefined(attr.disabled) || attr.disabled === false) {
400
element.triggerHandler('click', [event]);
407
// Hack for iOS Safari's benefit. It goes searching for onclick handlers and is liable to click
408
// something else nearby.
409
element.onclick = function(event) { };
411
// Actual click handler.
412
// There are three different kinds of clicks, only two of which reach this point.
413
// - On desktop browsers without touch events, their clicks will always come here.
414
// - On mobile browsers, the simulated "fast" click will call this.
415
// - But the browser's follow-up slow click will be "busted" before it reaches this handler.
416
// Therefore it's safe to use this directive on both mobile and desktop.
417
element.on('click', function(event, touchend) {
418
scope.$apply(function() {
419
clickHandler(scope, {$event: (touchend || event)});
423
element.on('mousedown', function(event) {
424
element.addClass(ACTIVE_CLASS_NAME);
427
element.on('mousemove mouseup', function(event) {
428
element.removeClass(ACTIVE_CLASS_NAME);
436
* @name ngTouch.directive:ngSwipeLeft
439
* Specify custom behavior when an element is swiped to the left on a touchscreen device.
440
* A leftward swipe is a quick, right-to-left slide of the finger.
441
* Though ngSwipeLeft is designed for touch-based devices, it will work with a mouse click and drag too.
443
* Requires the {@link ngTouch `ngTouch`} module to be installed.
446
* @param {expression} ngSwipeLeft {@link guide/expression Expression} to evaluate
447
* upon left swipe. (Event object is available as `$event`)
452
<div ng-show="!showActions" ng-swipe-left="showActions = true">
453
Some list content, like an email in the inbox
455
<div ng-show="showActions" ng-swipe-right="showActions = false">
456
<button ng-click="reply()">Reply</button>
457
<button ng-click="delete()">Delete</button>
465
* @name ngTouch.directive:ngSwipeRight
468
* Specify custom behavior when an element is swiped to the right on a touchscreen device.
469
* A rightward swipe is a quick, left-to-right slide of the finger.
470
* Though ngSwipeRight is designed for touch-based devices, it will work with a mouse click and drag too.
472
* Requires the {@link ngTouch `ngTouch`} module to be installed.
475
* @param {expression} ngSwipeRight {@link guide/expression Expression} to evaluate
476
* upon right swipe. (Event object is available as `$event`)
481
<div ng-show="!showActions" ng-swipe-left="showActions = true">
482
Some list content, like an email in the inbox
484
<div ng-show="showActions" ng-swipe-right="showActions = false">
485
<button ng-click="reply()">Reply</button>
486
<button ng-click="delete()">Delete</button>
492
function makeSwipeDirective(directiveName, direction, eventName) {
493
ngTouch.directive(directiveName, ['$parse', '$swipe', function($parse, $swipe) {
494
// The maximum vertical delta for a swipe should be less than 75px.
495
var MAX_VERTICAL_DISTANCE = 75;
496
// Vertical distance should not be more than a fraction of the horizontal distance.
497
var MAX_VERTICAL_RATIO = 0.3;
498
// At least a 30px lateral motion is necessary for a swipe.
499
var MIN_HORIZONTAL_DISTANCE = 30;
501
return function(scope, element, attr) {
502
var swipeHandler = $parse(attr[directiveName]);
504
var startCoords, valid;
506
function validSwipe(coords) {
507
// Check that it's within the coordinates.
508
// Absolute vertical distance must be within tolerances.
509
// Horizontal distance, we take the current X - the starting X.
510
// This is negative for leftward swipes and positive for rightward swipes.
511
// After multiplying by the direction (-1 for left, +1 for right), legal swipes
512
// (ie. same direction as the directive wants) will have a positive delta and
513
// illegal ones a negative delta.
514
// Therefore this delta must be positive, and larger than the minimum.
515
if (!startCoords) return false;
516
var deltaY = Math.abs(coords.y - startCoords.y);
517
var deltaX = (coords.x - startCoords.x) * direction;
518
return valid && // Short circuit for already-invalidated swipes.
519
deltaY < MAX_VERTICAL_DISTANCE &&
521
deltaX > MIN_HORIZONTAL_DISTANCE &&
522
deltaY / deltaX < MAX_VERTICAL_RATIO;
525
$swipe.bind(element, {
526
'start': function(coords, event) {
527
startCoords = coords;
530
'cancel': function(event) {
533
'end': function(coords, event) {
534
if (validSwipe(coords)) {
535
scope.$apply(function() {
536
element.triggerHandler(eventName);
537
swipeHandler(scope, {$event: event});
546
// Left is negative X-coordinate, right is positive.
547
makeSwipeDirective('ngSwipeLeft', -1, 'swipeleft');
548
makeSwipeDirective('ngSwipeRight', 1, 'swiperight');
552
})(window, window.angular);