From f4c6b2c7894cb2d82ac69a1500a27785360b81c3 Mon Sep 17 00:00:00 2001 From: Braden Shepherdson Date: Tue, 23 Apr 2013 10:53:27 -0700 Subject: [PATCH] feat($swipe): Refactor swipe logic from ngSwipe to $swipe service. This new service is used by the ngSwipeLeft/Right directives, and by the separate ngCarousel and swipe-to-delete directives which are under development. --- Gruntfile.js | 1 + angularFiles.js | 5 +- src/ngMobile/directive/ngSwipe.js | 94 ++-------- src/ngMobile/swipe.js | 136 +++++++++++++++ test/ngMobile/swipeSpec.js | 280 ++++++++++++++++++++++++++++++ 5 files changed, 437 insertions(+), 79 deletions(-) create mode 100644 src/ngMobile/swipe.js create mode 100644 test/ngMobile/swipeSpec.js diff --git a/Gruntfile.js b/Gruntfile.js index 26fcc7435d7a..5339b1bbe2b9 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -89,6 +89,7 @@ module.exports = function(grunt) { dest: 'build/angular-mobile.js', src: util.wrap([ 'src/ngMobile/mobile.js', + 'src/ngMobile/swipe.js', 'src/ngMobile/directive/ngClick.js', 'src/ngMobile/directive/ngSwipe.js' ], 'module') diff --git a/angularFiles.js b/angularFiles.js index 0a14df0e9ff1..1ffe3310b336 100755 --- a/angularFiles.js +++ b/angularFiles.js @@ -73,6 +73,7 @@ angularFiles = { 'src/ngSanitize/filter/linky.js', 'src/ngMock/angular-mocks.js', 'src/ngMobile/mobile.js', + 'src/ngMobile/swipe.js', 'src/ngMobile/directive/ngClick.js', 'src/ngMobile/directive/ngSwipe.js', @@ -113,6 +114,7 @@ angularFiles = { 'test/ngSanitize/directive/*.js', 'test/ngSanitize/filter/*.js', 'test/ngMock/*.js', + 'test/ngMobile/*.js', 'test/ngMobile/directive/*.js', 'docs/component-spec/bootstrap/*.js', 'docs/component-spec/*.js' @@ -154,6 +156,7 @@ angularFiles = { 'src/ngCookies/cookies.js', 'src/ngResource/resource.js', 'src/ngMobile/mobile.js', + 'src/ngMobile/swipe.js', 'src/ngMobile/directive/ngClick.js', 'src/ngMobile/directive/ngSwipe.js', 'src/ngSanitize/sanitize.js', @@ -168,7 +171,7 @@ angularFiles = { 'test/ngSanitize/*.js', 'test/ngSanitize/directive/*.js', 'test/ngSanitize/filter/*.js', - 'test/ngMobile/directive/*.js' + 'test/ngMobile/**/*.js' ], 'jstdPerf': [ diff --git a/src/ngMobile/directive/ngSwipe.js b/src/ngMobile/directive/ngSwipe.js index 6de7aa572a9d..e68e45da5d68 100644 --- a/src/ngMobile/directive/ngSwipe.js +++ b/src/ngMobile/directive/ngSwipe.js @@ -55,36 +55,20 @@ */ function makeSwipeDirective(directiveName, direction) { - ngMobile.directive(directiveName, ['$parse', function($parse) { + ngMobile.directive(directiveName, ['$parse', '$swipe', function($parse, $swipe) { // The maximum vertical delta for a swipe should be less than 75px. var MAX_VERTICAL_DISTANCE = 75; // Vertical distance should not be more than a fraction of the horizontal distance. var MAX_VERTICAL_RATIO = 0.3; // At least a 30px lateral motion is necessary for a swipe. var MIN_HORIZONTAL_DISTANCE = 30; - // The total distance in any direction before we make the call on swipe vs. scroll. - var MOVE_BUFFER_RADIUS = 10; - - function getCoordinates(event) { - var touches = event.touches && event.touches.length ? event.touches : [event]; - var e = (event.changedTouches && event.changedTouches[0]) || - (event.originalEvent && event.originalEvent.changedTouches && - event.originalEvent.changedTouches[0]) || - touches[0].originalEvent || touches[0]; - - return { - x: e.clientX, - y: e.clientY - }; - } return function(scope, element, attr) { var swipeHandler = $parse(attr[directiveName]); + var startCoords, valid; - var totalX, totalY; - var lastX, lastY; - function validSwipe(event) { + function validSwipe(coords) { // Check that it's within the coordinates. // Absolute vertical distance must be within tolerances. // Horizontal distance, we take the current X - the starting X. @@ -94,7 +78,6 @@ function makeSwipeDirective(directiveName, direction) { // illegal ones a negative delta. // Therefore this delta must be positive, and larger than the minimum. if (!startCoords) return false; - var coords = getCoordinates(event); var deltaY = Math.abs(coords.y - startCoords.y); var deltaX = (coords.x - startCoords.x) * direction; return valid && // Short circuit for already-invalidated swipes. @@ -104,65 +87,20 @@ function makeSwipeDirective(directiveName, direction) { deltaY / deltaX < MAX_VERTICAL_RATIO; } - element.bind('touchstart mousedown', function(event) { - startCoords = getCoordinates(event); - valid = true; - totalX = 0; - totalY = 0; - lastX = startCoords.x; - lastY = startCoords.y; - }); - - element.bind('touchcancel', function(event) { - valid = false; - }); - - element.bind('touchmove mousemove', function(event) { - if (!valid) return; - - // Android will send a touchcancel if it thinks we're starting to scroll. - // So when the total distance (+ or - or both) exceeds 10px in either direction, - // we either: - // - On totalX > totalY, we send preventDefault() and treat this as a swipe. - // - On totalY > totalX, we let the browser handle it as a scroll. - - // Invalidate a touch while it's in progress if it strays too far away vertically. - // We don't want a scroll down and back up while drifting sideways to be a swipe just - // because you happened to end up vertically close in the end. - if (!startCoords) return; - var coords = getCoordinates(event); - - if (Math.abs(coords.y - startCoords.y) > MAX_VERTICAL_DISTANCE) { + $swipe.bind(element, { + 'start': function(coords) { + startCoords = coords; + valid = true; + }, + 'cancel': function() { valid = false; - return; - } - - totalX += Math.abs(coords.x - lastX); - totalY += Math.abs(coords.y - lastY); - - lastX = coords.x; - lastY = coords.y; - - if (totalX < MOVE_BUFFER_RADIUS && totalY < MOVE_BUFFER_RADIUS) { - return; - } - - // One of totalX or totalY has exceeded the buffer, so decide on swipe vs. scroll. - if (totalY > totalX) { - valid = false; - return; - } else { - event.preventDefault(); - } - }); - - element.bind('touchend mouseup', function(event) { - if (validSwipe(event)) { - // Prevent this swipe from bubbling up to any other elements with ngSwipes. - event.stopPropagation(); - scope.$apply(function() { - swipeHandler(scope, {$event:event}); - }); + }, + 'end': function(coords) { + if (validSwipe(coords)) { + scope.$apply(function() { + swipeHandler(scope); + }); + } } }); }; diff --git a/src/ngMobile/swipe.js b/src/ngMobile/swipe.js new file mode 100644 index 000000000000..612d65fd51d3 --- /dev/null +++ b/src/ngMobile/swipe.js @@ -0,0 +1,136 @@ +'use strict'; + + /** + * @ngdoc object + * @name ngMobile.$swipe + * + * @description + * The `$swipe` service is a service that abstracts the messier details of hold-and-drag swipe + * behavior, to make implementing swipe-related directives more convenient. + * + * It is used by the `ngSwipeLeft` and `ngSwipeRight` directives in `ngMobile`, and by + * `ngCarousel` in a separate component. + * + * # Usage + * The `$swipe` service is an object with a single method: `bind`. `bind` takes an element + * which is to be watched for swipes, and an object with four handler functions. See the + * documentation for `bind` below. + */ + +ngMobile.factory('$swipe', [function() { + // The total distance in any direction before we make the call on swipe vs. scroll. + var MOVE_BUFFER_RADIUS = 10; + + function getCoordinates(event) { + var touches = event.touches && event.touches.length ? event.touches : [event]; + var e = (event.changedTouches && event.changedTouches[0]) || + (event.originalEvent && event.originalEvent.changedTouches && + event.originalEvent.changedTouches[0]) || + touches[0].originalEvent || touches[0]; + + return { + x: e.clientX, + y: e.clientY + }; + } + + return { + /** + * @ngdoc method + * @name ngMobile.$swipe#bind + * @methodOf ngMobile.$swipe + * + * @description + * The main method of `$swipe`. It takes an element to be watched for swipe motions, and an + * object containing event handlers. + * + * The four events are `start`, `move`, `end`, and `cancel`. `start`, `move`, and `end` + * receive as a parameter a coordinates object of the form `{ x: 150, y: 310 }`. + * + * `start` is called on either `mousedown` or `touchstart`. After this event, `$swipe` is + * watching for `touchmove` or `mousemove` events. These events are ignored until the total + * distance moved in either dimension exceeds a small threshold. + * + * Once this threshold is exceeded, either the horizontal or vertical delta is greater. + * - If the horizontal distance is greater, this is a swipe and `move` and `end` events follow. + * - If the vertical distance is greater, this is a scroll, and we let the browser take over. + * A `cancel` event is sent. + * + * `move` is called on `mousemove` and `touchmove` after the above logic has determined that + * a swipe is in progress. + * + * `end` is called when a swipe is successfully completed with a `touchend` or `mouseup`. + * + * `cancel` is called either on a `touchcancel` from the browser, or when we begin scrolling + * as described above. + * + */ + bind: function(element, eventHandlers) { + // Absolute total movement, used to control swipe vs. scroll. + var totalX, totalY; + // Coordinates of the start position. + var startCoords; + // Last event's position. + var lastPos; + // Whether a swipe is active. + var active = false; + + element.bind('touchstart mousedown', function(event) { + startCoords = getCoordinates(event); + active = true; + totalX = 0; + totalY = 0; + lastPos = startCoords; + eventHandlers['start'] && eventHandlers['start'](startCoords); + }); + + element.bind('touchcancel', function(event) { + active = false; + eventHandlers['cancel'] && eventHandlers['cancel'](); + }); + + element.bind('touchmove mousemove', function(event) { + if (!active) return; + + // Android will send a touchcancel if it thinks we're starting to scroll. + // So when the total distance (+ or - or both) exceeds 10px in either direction, + // we either: + // - On totalX > totalY, we send preventDefault() and treat this as a swipe. + // - On totalY > totalX, we let the browser handle it as a scroll. + + if (!startCoords) return; + var coords = getCoordinates(event); + + totalX += Math.abs(coords.x - lastPos.x); + totalY += Math.abs(coords.y - lastPos.y); + + lastPos = coords; + + if (totalX < MOVE_BUFFER_RADIUS && totalY < MOVE_BUFFER_RADIUS) { + return; + } + + // One of totalX or totalY has exceeded the buffer, so decide on swipe vs. scroll. + if (totalY > totalX) { + // Allow native scrolling to take over. + active = false; + eventHandlers['cancel'] && eventHandlers['cancel'](); + return; + } else { + // Prevent the browser from scrolling. + event.preventDefault(); + + eventHandlers['move'] && eventHandlers['move'](coords); + } + }); + + element.bind('touchend mouseup', function(event) { + if (!active) return; + active = false; + eventHandlers['end'] && eventHandlers['end'](getCoordinates(event)); + }); + } + }; +}]); + + diff --git a/test/ngMobile/swipeSpec.js b/test/ngMobile/swipeSpec.js new file mode 100644 index 000000000000..8befcfc9e6ce --- /dev/null +++ b/test/ngMobile/swipeSpec.js @@ -0,0 +1,280 @@ +'use strict'; + +// Wrapper to abstract over using touch events or mouse events. +var swipeTests = function(description, restrictBrowsers, startEvent, moveEvent, endEvent) { + describe('$swipe with ' + description + ' events', function() { + var element; + + if (restrictBrowsers) { + // TODO(braden): Once we have other touch-friendly browsers on CI, allow them here. + // Currently Firefox and IE refuse to fire touch events. + var chrome = /chrome/.test(navigator.userAgent.toLowerCase()); + if (!chrome) { + return; + } + } + + // Skip tests on IE < 9. These versions of IE don't support createEvent(), and so + // we cannot control the (x,y) position of events. + // It works fine in IE 8 under manual testing. + var msie = +((/msie (\d+)/.exec(navigator.userAgent.toLowerCase()) || [])[1]); + if (msie < 9) { + return; + } + + beforeEach(function() { + module('ngMobile'); + }); + + afterEach(function() { + dealoc(element); + }); + + it('should trigger the "start" event', inject(function($rootScope, $swipe, $compile) { + element = $compile('
')($rootScope); + var events = { + start: jasmine.createSpy('startSpy'), + move: jasmine.createSpy('moveSpy'), + cancel: jasmine.createSpy('cancelSpy'), + end: jasmine.createSpy('endSpy') + }; + + $swipe.bind(element, events); + + expect(events.start).not.toHaveBeenCalled(); + expect(events.move).not.toHaveBeenCalled(); + expect(events.cancel).not.toHaveBeenCalled(); + expect(events.end).not.toHaveBeenCalled(); + + browserTrigger(element, startEvent, [], 100, 20); + + expect(events.start).toHaveBeenCalled(); + + expect(events.move).not.toHaveBeenCalled(); + expect(events.cancel).not.toHaveBeenCalled(); + expect(events.end).not.toHaveBeenCalled(); + })); + + it('should trigger the "move" event after a "start"', inject(function($rootScope, $swipe, $compile) { + element = $compile('
')($rootScope); + var events = { + start: jasmine.createSpy('startSpy'), + move: jasmine.createSpy('moveSpy'), + cancel: jasmine.createSpy('cancelSpy'), + end: jasmine.createSpy('endSpy') + }; + + $swipe.bind(element, events); + + expect(events.start).not.toHaveBeenCalled(); + expect(events.move).not.toHaveBeenCalled(); + expect(events.cancel).not.toHaveBeenCalled(); + expect(events.end).not.toHaveBeenCalled(); + + browserTrigger(element, startEvent, [], 100, 20); + + expect(events.start).toHaveBeenCalled(); + + expect(events.move).not.toHaveBeenCalled(); + expect(events.cancel).not.toHaveBeenCalled(); + expect(events.end).not.toHaveBeenCalled(); + + browserTrigger(element, moveEvent, [], 140, 20); + + expect(events.start).toHaveBeenCalled(); + expect(events.move).toHaveBeenCalled(); + + expect(events.cancel).not.toHaveBeenCalled(); + expect(events.end).not.toHaveBeenCalled(); + })); + + it('should not trigger a "move" without a "start"', inject(function($rootScope, $swipe, $compile) { + element = $compile('
')($rootScope); + var events = { + start: jasmine.createSpy('startSpy'), + move: jasmine.createSpy('moveSpy'), + cancel: jasmine.createSpy('cancelSpy'), + end: jasmine.createSpy('endSpy') + }; + + $swipe.bind(element, events); + + expect(events.start).not.toHaveBeenCalled(); + expect(events.move).not.toHaveBeenCalled(); + expect(events.cancel).not.toHaveBeenCalled(); + expect(events.end).not.toHaveBeenCalled(); + + browserTrigger(element, moveEvent, [], 100, 40); + + expect(events.start).not.toHaveBeenCalled(); + expect(events.move).not.toHaveBeenCalled(); + expect(events.cancel).not.toHaveBeenCalled(); + expect(events.end).not.toHaveBeenCalled(); + })); + + it('should not trigger an "end" without a "start"', inject(function($rootScope, $swipe, $compile) { + element = $compile('
')($rootScope); + var events = { + start: jasmine.createSpy('startSpy'), + move: jasmine.createSpy('moveSpy'), + cancel: jasmine.createSpy('cancelSpy'), + end: jasmine.createSpy('endSpy') + }; + + $swipe.bind(element, events); + + expect(events.start).not.toHaveBeenCalled(); + expect(events.move).not.toHaveBeenCalled(); + expect(events.cancel).not.toHaveBeenCalled(); + expect(events.end).not.toHaveBeenCalled(); + + browserTrigger(element, endEvent, [], 100, 40); + + expect(events.start).not.toHaveBeenCalled(); + expect(events.move).not.toHaveBeenCalled(); + expect(events.cancel).not.toHaveBeenCalled(); + expect(events.end).not.toHaveBeenCalled(); + })); + + it('should trigger a "start", many "move"s and an "end"', inject(function($rootScope, $swipe, $compile) { + element = $compile('
')($rootScope); + var events = { + start: jasmine.createSpy('startSpy'), + move: jasmine.createSpy('moveSpy'), + cancel: jasmine.createSpy('cancelSpy'), + end: jasmine.createSpy('endSpy') + }; + + $swipe.bind(element, events); + + expect(events.start).not.toHaveBeenCalled(); + expect(events.move).not.toHaveBeenCalled(); + expect(events.cancel).not.toHaveBeenCalled(); + expect(events.end).not.toHaveBeenCalled(); + + browserTrigger(element, startEvent, [], 100, 40); + + expect(events.start).toHaveBeenCalled(); + + expect(events.move).not.toHaveBeenCalled(); + expect(events.cancel).not.toHaveBeenCalled(); + expect(events.end).not.toHaveBeenCalled(); + + browserTrigger(element, moveEvent, [], 120, 40); + browserTrigger(element, moveEvent, [], 130, 40); + browserTrigger(element, moveEvent, [], 140, 40); + browserTrigger(element, moveEvent, [], 150, 40); + browserTrigger(element, moveEvent, [], 160, 40); + browserTrigger(element, moveEvent, [], 170, 40); + browserTrigger(element, moveEvent, [], 180, 40); + + expect(events.start).toHaveBeenCalled(); + expect(events.move.calls.length).toBe(7); + + expect(events.cancel).not.toHaveBeenCalled(); + expect(events.end).not.toHaveBeenCalled(); + + browserTrigger(element, endEvent, [], 200, 40); + + expect(events.start).toHaveBeenCalled(); + expect(events.move.calls.length).toBe(7); + expect(events.end).toHaveBeenCalled(); + + expect(events.cancel).not.toHaveBeenCalled(); + })); + + it('should not start sending "move"s until enough horizontal motion is accumulated', inject(function($rootScope, $swipe, $compile) { + element = $compile('
')($rootScope); + var events = { + start: jasmine.createSpy('startSpy'), + move: jasmine.createSpy('moveSpy'), + cancel: jasmine.createSpy('cancelSpy'), + end: jasmine.createSpy('endSpy') + }; + + $swipe.bind(element, events); + + expect(events.start).not.toHaveBeenCalled(); + expect(events.move).not.toHaveBeenCalled(); + expect(events.cancel).not.toHaveBeenCalled(); + expect(events.end).not.toHaveBeenCalled(); + + browserTrigger(element, startEvent, [], 100, 40); + + expect(events.start).toHaveBeenCalled(); + + expect(events.move).not.toHaveBeenCalled(); + expect(events.cancel).not.toHaveBeenCalled(); + expect(events.end).not.toHaveBeenCalled(); + + browserTrigger(element, moveEvent, [], 101, 40); + browserTrigger(element, moveEvent, [], 105, 40); + browserTrigger(element, moveEvent, [], 110, 40); + browserTrigger(element, moveEvent, [], 115, 40); + browserTrigger(element, moveEvent, [], 120, 40); + + expect(events.start).toHaveBeenCalled(); + expect(events.move.calls.length).toBe(3); + + expect(events.cancel).not.toHaveBeenCalled(); + expect(events.end).not.toHaveBeenCalled(); + + browserTrigger(element, endEvent, [], 200, 40); + + expect(events.start).toHaveBeenCalled(); + expect(events.move.calls.length).toBe(3); + expect(events.end).toHaveBeenCalled(); + + expect(events.cancel).not.toHaveBeenCalled(); + })); + + it('should stop sending anything after vertical motion dominates', inject(function($rootScope, $swipe, $compile) { + element = $compile('
')($rootScope); + var events = { + start: jasmine.createSpy('startSpy'), + move: jasmine.createSpy('moveSpy'), + cancel: jasmine.createSpy('cancelSpy'), + end: jasmine.createSpy('endSpy') + }; + + $swipe.bind(element, events); + + expect(events.start).not.toHaveBeenCalled(); + expect(events.move).not.toHaveBeenCalled(); + expect(events.cancel).not.toHaveBeenCalled(); + expect(events.end).not.toHaveBeenCalled(); + + browserTrigger(element, startEvent, [], 100, 40); + + expect(events.start).toHaveBeenCalled(); + + expect(events.move).not.toHaveBeenCalled(); + expect(events.cancel).not.toHaveBeenCalled(); + expect(events.end).not.toHaveBeenCalled(); + + browserTrigger(element, moveEvent, [], 101, 41); + browserTrigger(element, moveEvent, [], 105, 55); + browserTrigger(element, moveEvent, [], 110, 60); + browserTrigger(element, moveEvent, [], 115, 70); + browserTrigger(element, moveEvent, [], 120, 80); + + expect(events.start).toHaveBeenCalled(); + expect(events.cancel).toHaveBeenCalled(); + + expect(events.move).not.toHaveBeenCalled(); + expect(events.end).not.toHaveBeenCalled(); + + browserTrigger(element, endEvent, [], 200, 40); + + expect(events.start).toHaveBeenCalled(); + expect(events.cancel).toHaveBeenCalled(); + + expect(events.move).not.toHaveBeenCalled(); + expect(events.end).not.toHaveBeenCalled(); + })); + }); +} + +swipeTests('touch', true /* restrictBrowers */, 'touchstart', 'touchmove', 'touchend'); +swipeTests('mouse', false /* restrictBrowers */, 'mousedown', 'mousemove', 'mouseup'); +