diff --git a/Gruntfile.js b/Gruntfile.js index 237fc6c18c..eeb10e55e0 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -18,7 +18,23 @@ module.exports = function(grunt) { 'js/utils/**/*.js', // Views - 'js/views/**/*.js', + 'js/views/view.js', + + 'js/views/scrollView.js', + + 'js/views/actionSheetView.js', + 'js/views/checkboxView.js', + 'js/views/headerBarView.js', + 'js/views/listView.js', + 'js/views/ListViewScroll.js', + 'js/views/loadingView.js', + 'js/views/modalView.js', + 'js/views/navBarView.js', + 'js/views/popupView.js', + 'js/views/sideMenuView.js', + 'js/views/slideBox.js', + 'js/views/tabBarView.js', + 'js/views/toggleView.js', // Controllers 'js/controllers/**/*.js' diff --git a/dist/js/ionic.js b/dist/js/ionic.js index ca4d16265e..b9f2f95910 100644 --- a/dist/js/ionic.js +++ b/dist/js/ionic.js @@ -1736,27 +1736,625 @@ window.ionic = { (function(ionic) { ionic.Utils = { - /** - * extend method, - * also used for cloning when dest is an empty object - * @param {Object} dest - * @param {Object} src - * @parm {Boolean} merge do a merge - * @returns {Object} dest - */ - extend: function extend(dest, src, merge) { - for (var key in src) { - if(dest[key] !== undefined && merge) { - continue; - } - dest[key] = src[key]; + // Borrowed from Backbone.js's extend + // Helper function to correctly set up the prototype chain, for subclasses. + // Similar to `goog.inherits`, but uses a hash of prototype properties and + // class properties to be extended. + inherit: function(protoProps, staticProps) { + var parent = this; + var child; + + // The constructor function for the new subclass is either defined by you + // (the "constructor" property in your `extend` definition), or defaulted + // by us to simply call the parent's constructor. + if (protoProps && protoProps.hasOwnProperty('constructor')) { + child = protoProps.constructor; + } else { + child = function(){ return parent.apply(this, arguments); }; } - return dest; + + // Add static properties to the constructor function, if supplied. + ionic.extend(child, parent, staticProps); + + // Set the prototype chain to inherit from `parent`, without calling + // `parent`'s constructor function. + var Surrogate = function(){ this.constructor = child; }; + Surrogate.prototype = parent.prototype; + child.prototype = new Surrogate; + + // Add prototype properties (instance properties) to the subclass, + // if supplied. + if (protoProps) ionic.extend(child.prototype, protoProps); + + // Set a convenience property in case the parent's prototype is needed + // later. + child.__super__ = parent.prototype; + + return child; }, + + // Extend adapted from Underscore.js + extend: function(obj) { + var args = Array.prototype.slice.call(arguments, 1); + for(var i = 0; i < args.length; i++) { + var source = args[i]; + if (source) { + for (var prop in source) { + obj[prop] = source[prop]; + } + } + } + return obj; + } }; + + ionic.inherit = ionic.Utils.inherit; + ionic.extend = ionic.Utils.extend; + })(window.ionic); ; (function(ionic) { +'use strict'; + ionic.views.View = function() { + this.initialize.apply(this, arguments); + }; + + ionic.views.View.inherit = ionic.inherit; + + ionic.extend(ionic.views.View.prototype, { + initialize: function() {} + }); + +})(window.ionic); +; +/** + * ionic.views.Scroll. Portions adapted from the great iScroll 5, which is + * also MIT licensed. + * iScroll v5.0.5 ~ (c) 2008-2013 Matteo Spinelli ~ http://cubiq.org/license + * + * Think of ionic.views.Scroll like a Javascript version of UIScrollView or any + * scroll container in any UI library. You could just use -webkit-overflow-scrolling: touch, + * but you lose control over scroll behavior that native developers have with things + * like UIScrollView, and you don't get events after the finger stops touching the + * device (after a flick, for example) + */ +(function(ionic) { +'use strict'; + var EASING_FUNCTIONS = { + quadratic: 'cubic-bezier(0.25, 0.46, 0.45, 0.94)', + circular: 'cubic-bezier(0.1, 0.57, 0.1, 1)', + circular2: 'cubic-bezier(0.075, 0.82, 0.165, 1)', + + bounce: 'cubic-bezier(.02,.69,.67,1)', + + // It closes like a high-end toilet seat. Fast, then nice and slow. + // Thanks to our @xtheglobe for that. + toiletSeat: 'cubic-bezier(0.05, 0.60, 0.05, 0.60)' + }; + + ionic.views.Scroll = ionic.views.View.inherit({ + initialize: function(opts) { + var _this = this; + + // Extend the options with our defaults + opts = ionic.Utils.extend({ + decelerationRate: ionic.views.Scroll.prototype.DECEL_RATE_NORMAL, + dragThreshold: 10, + resistance: 2, + scrollEventName: 'momentumScrolled', + scrollEndEventName: 'momentumScrollEnd', + intertialEventInterval: 50, + mouseWheelSpeed: 20, + invertWheel: false, + isVerticalEnabled: true, + isHorizontalEnabled: false, + bounceEasing: EASING_FUNCTIONS.bounce, + bounceTime: 600 //how long to take when bouncing back in a rubber band + }, opts); + + ionic.Utils.extend(this, opts); + + this.el = opts.el; + + this.y = 0; + this.x = 0; + + // Listen for drag and release events + ionic.onGesture('drag', function(e) { + _this._handleDrag(e); + }, this.el); + ionic.onGesture('release', function(e) { + _this._handleEndDrag(e); + }, this.el); + ionic.on('mousewheel', function(e) { + _this._wheel(e); + }, this.el); + ionic.on('DOMMouseScroll', function(e) { + _this._wheel(e); + }, this.el); + ionic.on(this.scrollEndEventName, function(e) { + _this._onScrollEnd(e); + }, this.el); + ionic.on('webkitTransitionEnd', function(e) { + _this._onTransitionEnd(e); + }); + }, + + /** + * Scroll to the given X and Y point, taking + * the given amount of time, with the given + * easing function defined as a CSS3 timing function. + * + * @param {float} the x position to scroll to (CURRENTLY NOT SUPPORTED!) + * @param {float} the y position to scroll to + * @param {float} the time to take scrolling to the new position + * @param {easing} the animation function to use for easing + */ + scrollTo: function(x, y, time, easing) { + var _this = this; + + + easing = easing || 'cubic-bezier(0.1, 0.57, 0.1, 1)'; + + var ox = x, oy = y; + + var el = this.el; + + if(x !== null) { + this.x = x; + } else { + x = this.x; + } + if(y !== null) { + this.y = y; + } else { + y = this.y; + } + + el.offsetHeight; + el.style.webkitTransitionTimingFunction = easing; + el.style.webkitTransitionDuration = time; + el.style.webkitTransform = 'translate3d(' + x + 'px,' + y + 'px, 0)'; + + // Start triggering events as the element scrolls from inertia. + // This is important because we need to receive scroll events + // even after a "flick" and adjust, etc. + this._momentumStepTimeout = setTimeout(function eventNotify() { + var scrollTop = parseFloat(_this.el.style.webkitTransform.replace('translate3d(', '').split(',')[1]) || 0; + ionic.trigger(_this.scrollEventName, { + target: _this.el, + scrollTop: -scrollTop + }); + + if(_this._isDragging) { + _this._momentumStepTimeout = setTimeout(eventNotify, _this.inertialEventInterval); + } + }, this.inertialEventInterval) + + console.log('TRANSITION ADDED!'); + }, + + /** + * If the scroll position is outside the current bounds, + * animate it back. + */ + wrapScrollPosition: function(transitionTime) { + var _this = this; + + var totalWidth = _this.el.scrollWidth; + var totalHeight = _this.el.scrollHeight; + var parentWidth = _this.el.parentNode.offsetWidth; + var parentHeight = _this.el.parentNode.offsetHeight; + + var maxX = Math.min(0, (-totalWidth + parentWidth)); + var maxY = Math.min(0, (-totalHeight + parentHeight)); + + //this._execEvent('scrollEnd'); + var x = _this.x, y = _this.y; + + if (!_this.isHorizontalEnabled || _this.x > 0) { + x = 0; + } else if ( _this.x < maxX) { + x = maxX; + } + + if (!_this.isVerticalEnabled || _this.y > 0) { + y = 0; + } else if (_this.y < maxY) { + y = maxY; + } + + // No change + if (x == _this.x && y == _this.y) { + return false; + } + _this.scrollTo(x, y, transitionTime || 0, _this.bounceEasing); + + return true; + }, + + _wheel: function(e) { + var wheelDeltaX, wheelDeltaY, + newX, newY, + that = this; + + var totalWidth = this.el.scrollWidth; + var totalHeight = this.el.scrollHeight; + var parentWidth = this.el.parentNode.offsetWidth; + var parentHeight = this.el.parentNode.offsetHeight; + + var maxX = Math.min(0, (-totalWidth + parentWidth)); + var maxY = Math.min(0, (-totalHeight + parentHeight)); + + // Execute the scrollEnd event after 400ms the wheel stopped scrolling + clearTimeout(this.wheelTimeout); + this.wheelTimeout = setTimeout(function () { + ionic.trigger(this.scrollEndEventName, { + target: this.el, + scrollLeft: this.x, + scrollTop: this.y + }); + }, 400); + + e.preventDefault(); + + if('wheelDeltaX' in e) { + wheelDeltaX = e.wheelDeltaX / 120; + wheelDeltaY = e.wheelDeltaY / 120; + } else if ('wheelDelta' in e) { + wheelDeltaX = wheelDeltaY = e.wheelDelta / 120; + } else if ('detail' in e) { + wheelDeltaX = wheelDeltaY = -e.detail / 3; + } else { + return; + } + + wheelDeltaX *= this.mouseWheelSpeed; + wheelDeltaY *= this.mouseWheelSpeed; + + if(!this.isVerticalEnabled) { + wheelDeltaX = wheelDeltaY; + wheelDeltaY = 0; + } + + newX = this.x + (this.isHorizontalEnabled ? wheelDeltaX * (this.invertWheel ? -1 : 1) : 0); + newY = this.y + (this.isVerticalEnabled ? wheelDeltaY * (this.invertWheel ? -1 : 1) : 0); + + if(newX > 0) { + newX = 0; + } else if (newX < maxX) { + newX = maxX; + } + + if(newY > 0) { + newY = 0; + } else if (newY < maxY) { + newY = maxY; + } + + this.scrollTo(newX, newY, 0); + }, + + _getMomentum: function (current, start, time, lowerMargin, wrapperSize) { + var distance = current - start, + speed = Math.abs(distance) / time, + destination, + duration, + deceleration = 0.0006; + + // Calculate the final desination + destination = current + ( speed * speed ) / ( 2 * deceleration ) * ( distance < 0 ? -1 : 1 ); + duration = speed / deceleration; + + // Check if the final destination needs to be rubber banded + if ( destination < lowerMargin ) { + // We have dragged too far down, snap back to the maximum + destination = wrapperSize ? lowerMargin - ( wrapperSize / 2.5 * ( speed / 8 ) ) : lowerMargin; + distance = Math.abs(destination - current); + duration = distance / speed; + console.log("MOMENTUM TOO FAR DOWN", destination); + } else if ( destination > 0 ) { + + // We have dragged too far up, snap back to 0 + destination = wrapperSize ? wrapperSize / 2.5 * ( speed / 8 ) : 0; + distance = Math.abs(current) + destination; + duration = distance / speed; + console.log("MOMENTUM TOO FAR UP", destination); + } + + console.log('Momentum: time:', time, 'speed:',speed, 'dest:',destination, 'dur:',duration); + return { + destination: Math.round(destination), + duration: duration + }; + }, + + _onTransitionEnd: function(e) { + var _this = this; + + if (e.target != this.el) { + return; + } + + // Triggered to end scroll, once the final animation has ended + if(this._didEndScroll) { + this._didEndScroll = false; + ionic.trigger(_this.scrollEndEventName, { + target: _this.el, + scrollLeft: _this.x, + scrollTop: _this.y + }); + } + + this.el.style.webkitTransitionDuration = '0'; + + window.requestAnimationFrame(function() { + if(_this.wrapScrollPosition(_this.bounceTime)) { + _this._didEndScroll = true; + } + }); + }, + + _onScrollEnd: function() { + this._isDragging = false; + this._drag = null; + this.el.classList.remove('scroll-scrolling'); + + console.log('REMOVING TRANSITION'); + this.el.style.webkitTransitionDuration = '0'; + + clearTimeout(this._momentumStepTimeout) + }, + + + _initDrag: function() { + this._onScrollEnd(); + this._isStopped = false; + }, + + + /** + * Initialize a drag by grabbing the content area to drag, and any other + * info we might need for the dragging. + */ + _startDrag: function(e) { + var offsetX, content; + + this._initDrag(); + + var scrollLeft = parseFloat(this.el.style.webkitTransform.replace('translate3d(', '').split(',')[0]) || 0; + var scrollTop = parseFloat(this.el.style.webkitTransform.replace('translate3d(', '').split(',')[1]) || 0; + + var totalWidth = this.el.scrollWidth; + var totalHeight = this.el.scrollHeight; + var parentWidth = this.el.parentNode.offsetWidth; + var parentHeight = this.el.parentNode.offsetHeight; + + var maxX = Math.min(0, (-totalWidth + parentWidth)); + var maxY = Math.min(0, (-totalHeight + parentHeight)); + + // Check if we even have enough content to scroll, if not, don't start the drag + if((this.isHorizontalEnabled && maxX == 0) || (this.isVerticalEnabled && maxY == 0)) { + return; + } + + this.x = scrollLeft; + this.y = scrollTop; + + this._drag = { + direction: 'v', + pointX: e.gesture.touches[0].pageX, + pointY: e.gesture.touches[0].pageY, + startX: scrollLeft, + startY: scrollTop, + resist: 1, + startTime: Date.now() + }; + }, + + + + /** + * Process the drag event to move the item to the left or right. + * + * This function needs to be as fast as possible to make sure scrolling + * performance is high. + */ + _handleDrag: function(e) { + var _this = this; + + var content; + + // The drag stopped already, don't process this one + if(_this._isStopped) { + _this._initDrag(); + return; + } + + // We really aren't dragging + if(!_this._drag) { + _this._startDrag(e); + if(!_this._drag) { return; } + } + + // Stop any default events during the drag + e.preventDefault(); + + var px = e.gesture.touches[0].pageX; + var py = e.gesture.touches[0].pageY; + + var deltaX = px - _this._drag.pointX; + var deltaY = py - _this._drag.pointY; + + //console.log("Delta x", deltaX); + //console.log("Delta y", deltaY); + + _this._drag.pointX = px; + _this._drag.pointY = py; + + // Check if we should start dragging. Check if we've dragged past the threshold. + if(!_this._isDragging && + ((Math.abs(e.gesture.deltaY) > _this.dragThreshold) || + (Math.abs(e.gesture.deltaX) > _this.dragThreshold))) { + _this._isDragging = true; + } + + if(_this._isDragging) { + var drag = _this._drag; + + // Request an animation frame to batch DOM reads/writes + window.requestAnimationFrame(function() { + // We are dragging, grab the current content height + + var totalWidth = _this.el.scrollWidth; + var totalHeight = _this.el.scrollHeight; + var parentWidth = _this.el.parentNode.offsetWidth; + var parentHeight = _this.el.parentNode.offsetHeight; + var maxX = Math.min(0, (-totalWidth + parentWidth)); + var maxY = Math.min(0, (-totalHeight + parentHeight)); + + // Grab current timestamp to keep our speend, etc. + // calculations in a window + var timestamp = Date.now(); + + // Calculate the new Y point for the container + // TODO: Only enable certain axes + var newX = _this.x + deltaX; + var newY = _this.y + deltaY; + + if(newX > 0 || (-newX + parentWidth) > totalWidth) { + // Rubber band + newX = _this.x + deltaX / 3; + } + // Check if the dragging is beyond the bottom or top + if(newY > 0 || (-newY + parentHeight) > totalHeight) { + // Rubber band + newY = _this.y + deltaY / 3;//(-_this.resistance); + } + + if(!_this.isHorizontalEnabled) { + newX = 0; + } + if(!_this.isVerticalEnabled) { + newY = 0; + } + + // Update the new translated Y point of the container + _this.el.style.webkitTransform = 'translate3d(' + newX + 'px,' + newY + 'px, 0)'; + + // Store the last points + _this.x = newX; + _this.y = newY; + + console.log('Moving to', newX, newY); + + // Check if we need to reset the drag initial states if we've + // been dragging for a bit + if(timestamp - drag.startTime > 300) { + console.log('Resetting timer'); + drag.startTime = timestamp; + drag.startX = _this.x; + drag.startY = _this.y; + } + + // Trigger a scroll event + ionic.trigger(_this.scrollEventName, { + target: _this.el, + scrollLeft: -newX, + scrollTop: -newY + }); + }); + } + }, + + + + _handleEndDrag: function(e) { + // We didn't have a drag, so just init and leave + if(!this._drag) { + this._initDrag(); + return; + } + + // Set a flag in case we don't cleanup completely after the + // drag animation so we can cleanup the next time a drag starts + this._isStopped = true; + + // Animate to the finishing point + this._animateToStop(e); + + }, + + + // Find the stopping point given the current velocity and acceleration rate, and + // animate to that position + _animateToStop: function(e) { + var _this = this; + window.requestAnimationFrame(function() { + + var drag = _this._drag; + + // Calculate the viewport height and the height of the content + var totalWidth = _this.el.scrollWidth; + var totalHeight = _this.el.scrollHeight; + + // The parent bounding box helps us figure max/min scroll amounts + var parentWidth = _this.el.parentNode.offsetWidth; + var parentHeight = _this.el.parentNode.offsetHeight; + + // Calculate how long we've been dragging for, with a max of 300ms + var duration = Date.now() - _this._drag.startTime; + var time = 0; + var easing = ''; + + var newX = Math.round(_this.x); + var newY = Math.round(_this.y); + + _this.scrollTo(newX, newY); + + + // Check if we just snap back to bounds + if(_this.wrapScrollPosition(_this.bounceTime)) { + return; + } + + // If the duration is within reasonable bounds, enable momentum scrolling so we + // can "slide" to a finishing point + if(duration < 300) { + var momentumX = _this._getMomentum(_this.x, drag.startX, duration, parentWidth - totalWidth, parentWidth); + var momentumY = _this._getMomentum(_this.y, drag.startY, duration, parentHeight - totalHeight, parentHeight); + //var newX = momentumX.destination; + newX = momentumX.destination; + newY = momentumY.destination; + + // Calcualte the longest required time for the momentum animation and + // use that. + time = Math.max(momentumX.duration, momentumY.duration); + } + + // If we've moved, we will need to scroll + if(newX != _this.x || newY != _this.y) { + console.trace("SCROLL FROM", _this.x, _this.y, "TO", newX, newY); + + // If the end position is out of bounds, change the function we use for easing + // to get a different animation for the rubber banding + if ( newX > 0 || newX < (-totalWidth + parentWidth) || newY > 0 || newY < (-totalHeight + parentHeight)) { + easing = EASING_FUNCTIONS.bounce; + } + + _this.scrollTo(newX, newY, time, easing); + } + }); + } + }, { + DECEL_RATE_NORMAL: 0.998, + DECEL_RATE_FAST: 0.99, + DECEL_RATE_SLOW: 0.996, + }); + +})(ionic); +; +(function(ionic) { 'use strict'; /** * An ActionSheet is the slide up menu popularized on iOS. @@ -2326,7 +2924,6 @@ window.ionic = { (function(ionic) { 'use strict'; - var DragOp = function() {}; DragOp.prototype = { start: function(e) { @@ -2686,31 +3283,33 @@ window.ionic = { * The ListView handles a list of items. It will process drag animations, edit mode, * and other operations that are common on mobile lists or table views. */ - ionic.views.List = function(opts) { - var _this = this; + ionic.views.ListView = ionic.views.Scroll.inherit({ + initialize: function(opts) { + ionic.views.ListView.__super__.initialize.call(this, opts); + /* + var _this = this; - this.el = opts.el; + this.el = opts.el; - // The amount of dragging required to start sliding the element over (in pixels) - this.dragThresholdX = opts.dragThresholdX || 10; + // The amount of dragging required to start sliding the element over (in pixels) + this.dragThresholdX = opts.dragThresholdX || 10; - this.onRefresh = opts.onRefresh || function() {}; - this.onRefreshOpening = opts.onRefreshOpening || function() {}; - this.onRefreshHolding = opts.onRefreshHolding || function() {}; - - // Start the drag states - this._initDrag(); + this.onRefresh = opts.onRefresh || function() {}; + this.onRefreshOpening = opts.onRefreshOpening || function() {}; + this.onRefreshHolding = opts.onRefreshHolding || function() {}; + + // Start the drag states + this._initDrag(); - // Listen for drag and release events - window.ionic.onGesture('drag', function(e) { - _this._handleDrag(e); - }, this.el); - window.ionic.onGesture('release', function(e) { - _this._handleEndDrag(e); - }, this.el); - }; - - ionic.views.List.prototype = { + // Listen for drag and release events + window.ionic.onGesture('drag', function(e) { + _this._handleDrag(e); + }, this.el); + window.ionic.onGesture('release', function(e) { + _this._handleEndDrag(e); + }, this.el); + */ + }, /** * Called to tell the list to stop refreshing. This is useful * if you are refreshing the list and are done with refreshing. @@ -2721,8 +3320,10 @@ window.ionic = { }, _initDrag: function() { - this._isDragging = false; - this._dragOp = null; + ionic.views.ListView.__super__._initDrag.call(this); + + //this._isDragging = false; + //this._dragOp = null; }, // Return the list item from the given target @@ -2738,7 +3339,10 @@ window.ionic = { _startDrag: function(e) { + ionic.views.ListView.__super__._startDrag.call(this, e); + var _this = this; + /* this._isDragging = false; @@ -2751,7 +3355,9 @@ window.ionic = { this._dragOp.start(e); } } + */ + /* // Check if this is a "pull down" drag for pull to refresh else if(e.gesture.direction == 'down') { this._dragOp = new PullToRefreshDrag({ @@ -2768,16 +3374,21 @@ window.ionic = { }); this._dragOp.start(e); } + */ // Or check if this is a swipe to the side drag + /* else if(e.gesture.direction == 'left' || e.gesture.direction == 'right') { this._dragOp = new SlideDrag({ el: this.el }); this._dragOp.start(e); } + */ }, _handleEndDrag: function(e) { + ionic.views.ListView.__super__._handleEndDrag.call(this, e); + /* var _this = this; if(!this._dragOp) { @@ -2788,12 +3399,15 @@ window.ionic = { this._dragOp.end(e, function() { _this._initDrag(); }); + */ }, /** * Process the drag event to move the item to the left or right. */ _handleDrag: function(e) { + ionic.views.ListView.__super__._handleDrag.call(this, e); + /* var _this = this, content, buttons; if(!this._dragOp) { @@ -2802,8 +3416,9 @@ window.ionic = { } this._dragOp.drag(e); + */ } - }; + }); })(ionic); ; @@ -2963,553 +3578,6 @@ window.ionic = { } }; -})(ionic); -; -/** - * ionic.views.Scroll. Portions adapted from the great iScroll 5, which is - * also MIT licensed. - * iScroll v5.0.5 ~ (c) 2008-2013 Matteo Spinelli ~ http://cubiq.org/license - * - * Think of ionic.views.Scroll like a Javascript version of UIScrollView or any - * scroll container in any UI library. You could just use -webkit-overflow-scrolling: touch, - * but you lose control over scroll behavior that native developers have with things - * like UIScrollView, and you don't get events after the finger stops touching the - * device (after a flick, for example) - */ -(function(ionic) { -'use strict'; - var EASING_FUNCTIONS = { - quadratic: 'cubic-bezier(0.25, 0.46, 0.45, 0.94)', - circular: 'cubic-bezier(0.1, 0.57, 0.1, 1)', - circular2: 'cubic-bezier(0.075, 0.82, 0.165, 1)', - - bounce: 'cubic-bezier(.02,.69,.67,1)', - - // It closes like a high-end toilet seat. Fast, then nice and slow. - // Thanks to our @xtheglobe for that. - toiletSeat: 'cubic-bezier(0.05, 0.60, 0.05, 0.60)' - }; - - ionic.views.ScrollView = function(opts) { - var _this = this; - - // Extend the options with our defaults - opts = ionic.Utils.extend({ - decelerationRate: ionic.views.ScrollView.prototype.DECEL_RATE_NORMAL, - dragThreshold: 10, - resistance: 2, - scrollEventName: 'momentumScrolled', - scrollEndEventName: 'momentumScrollEnd', - intertialEventInterval: 50, - mouseWheelSpeed: 20, - invertWheel: false, - isVerticalEnabled: true, - isHorizontalEnabled: false, - bounceEasing: EASING_FUNCTIONS.bounce, - bounceTime: 600 //how long to take when bouncing back in a rubber band - }, opts); - - ionic.Utils.extend(this, opts); - - this.el = opts.el; - - this.y = 0; - this.x = 0; - - // Listen for drag and release events - ionic.onGesture('drag', function(e) { - _this._handleDrag(e); - }, this.el); - ionic.onGesture('release', function(e) { - _this._handleEndDrag(e); - }, this.el); - ionic.on('mousewheel', function(e) { - _this._wheel(e); - }, this.el); - ionic.on('DOMMouseScroll', function(e) { - _this._wheel(e); - }, this.el); - ionic.on(this.scrollEndEventName, function(e) { - _this._onScrollEnd(e); - }, this.el); - ionic.on('webkitTransitionEnd', function(e) { - _this._onTransitionEnd(e); - }); - }; - - ionic.views.ScrollView.prototype = { - DECEL_RATE_NORMAL: 0.998, - DECEL_RATE_FAST: 0.99, - DECEL_RATE_SLOW: 0.996, - - /** - * Scroll to the given X and Y point, taking - * the given amount of time, with the given - * easing function defined as a CSS3 timing function. - * - * @param {float} the x position to scroll to (CURRENTLY NOT SUPPORTED!) - * @param {float} the y position to scroll to - * @param {float} the time to take scrolling to the new position - * @param {easing} the animation function to use for easing - */ - scrollTo: function(x, y, time, easing) { - var _this = this; - - - easing = easing || 'cubic-bezier(0.1, 0.57, 0.1, 1)'; - - var ox = x, oy = y; - - var el = this.el; - - if(x !== null) { - this.x = x; - } else { - x = this.x; - } - if(y !== null) { - this.y = y; - } else { - y = this.y; - } - - el.offsetHeight; - el.style.webkitTransitionTimingFunction = easing; - el.style.webkitTransitionDuration = time; - el.style.webkitTransform = 'translate3d(' + x + 'px,' + y + 'px, 0)'; - - // Start triggering events as the element scrolls from inertia. - // This is important because we need to receive scroll events - // even after a "flick" and adjust, etc. - this._momentumStepTimeout = setTimeout(function eventNotify() { - var scrollTop = parseFloat(_this.el.style.webkitTransform.replace('translate3d(', '').split(',')[1]) || 0; - ionic.trigger(_this.scrollEventName, { - target: _this.el, - scrollTop: -scrollTop - }); - - if(_this._isDragging) { - _this._momentumStepTimeout = setTimeout(eventNotify, _this.inertialEventInterval); - } - }, this.inertialEventInterval) - - console.log('TRANSITION ADDED!'); - }, - - /** - * If the scroll position is outside the current bounds, - * animate it back. - */ - wrapScrollPosition: function(transitionTime) { - var _this = this; - - var totalWidth = _this.el.scrollWidth; - var totalHeight = _this.el.scrollHeight; - var parentWidth = _this.el.parentNode.offsetWidth; - var parentHeight = _this.el.parentNode.offsetHeight; - - var maxX = Math.min(0, (-totalWidth + parentWidth)); - var maxY = Math.min(0, (-totalHeight + parentHeight)); - - //this._execEvent('scrollEnd'); - var x = _this.x, y = _this.y; - - if (!_this.isHorizontalEnabled || _this.x > 0) { - x = 0; - } else if ( _this.x < maxX) { - x = maxX; - } - - if (!_this.isVerticalEnabled || _this.y > 0) { - y = 0; - } else if (_this.y < maxY) { - y = maxY; - } - - // No change - if (x == _this.x && y == _this.y) { - return false; - } - _this.scrollTo(x, y, transitionTime || 0, _this.bounceEasing); - - return true; - }, - - _wheel: function(e) { - var wheelDeltaX, wheelDeltaY, - newX, newY, - that = this; - - var totalWidth = this.el.scrollWidth; - var totalHeight = this.el.scrollHeight; - var parentWidth = this.el.parentNode.offsetWidth; - var parentHeight = this.el.parentNode.offsetHeight; - - var maxX = Math.min(0, (-totalWidth + parentWidth)); - var maxY = Math.min(0, (-totalHeight + parentHeight)); - - // Execute the scrollEnd event after 400ms the wheel stopped scrolling - clearTimeout(this.wheelTimeout); - this.wheelTimeout = setTimeout(function () { - ionic.trigger(this.scrollEndEventName, { - target: this.el, - scrollLeft: this.x, - scrollTop: this.y - }); - }, 400); - - e.preventDefault(); - - if('wheelDeltaX' in e) { - wheelDeltaX = e.wheelDeltaX / 120; - wheelDeltaY = e.wheelDeltaY / 120; - } else if ('wheelDelta' in e) { - wheelDeltaX = wheelDeltaY = e.wheelDelta / 120; - } else if ('detail' in e) { - wheelDeltaX = wheelDeltaY = -e.detail / 3; - } else { - return; - } - - wheelDeltaX *= this.mouseWheelSpeed; - wheelDeltaY *= this.mouseWheelSpeed; - - if(!this.isVerticalEnabled) { - wheelDeltaX = wheelDeltaY; - wheelDeltaY = 0; - } - - newX = this.x + (this.isHorizontalEnabled ? wheelDeltaX * (this.invertWheel ? -1 : 1) : 0); - newY = this.y + (this.isVerticalEnabled ? wheelDeltaY * (this.invertWheel ? -1 : 1) : 0); - - if(newX > 0) { - newX = 0; - } else if (newX < maxX) { - newX = maxX; - } - - if(newY > 0) { - newY = 0; - } else if (newY < maxY) { - newY = maxY; - } - - this.scrollTo(newX, newY, 0); - }, - - _getMomentum: function (current, start, time, lowerMargin, wrapperSize) { - var distance = current - start, - speed = Math.abs(distance) / time, - destination, - duration, - deceleration = 0.0006; - - // Calculate the final desination - destination = current + ( speed * speed ) / ( 2 * deceleration ) * ( distance < 0 ? -1 : 1 ); - duration = speed / deceleration; - - // Check if the final destination needs to be rubber banded - if ( destination < lowerMargin ) { - // We have dragged too far down, snap back to the maximum - destination = wrapperSize ? lowerMargin - ( wrapperSize / 2.5 * ( speed / 8 ) ) : lowerMargin; - distance = Math.abs(destination - current); - duration = distance / speed; - console.log("MOMENTUM TOO FAR DOWN", destination); - } else if ( destination > 0 ) { - - // We have dragged too far up, snap back to 0 - destination = wrapperSize ? wrapperSize / 2.5 * ( speed / 8 ) : 0; - distance = Math.abs(current) + destination; - duration = distance / speed; - console.log("MOMENTUM TOO FAR UP", destination); - } - - console.log('Momentum: time:', time, 'speed:',speed, 'dest:',destination, 'dur:',duration); - return { - destination: Math.round(destination), - duration: duration - }; - }, - - _onTransitionEnd: function(e) { - var _this = this; - - if (e.target != this.el) { - return; - } - - // Triggered to end scroll, once the final animation has ended - if(this._didEndScroll) { - this._didEndScroll = false; - ionic.trigger(_this.scrollEndEventName, { - target: _this.el, - scrollLeft: _this.x, - scrollTop: _this.y - }); - } - - this.el.style.webkitTransitionDuration = '0'; - - window.requestAnimationFrame(function() { - if(_this.wrapScrollPosition(_this.bounceTime)) { - _this._didEndScroll = true; - } - }); - }, - - _onScrollEnd: function() { - this._isDragging = false; - this._drag = null; - this.el.classList.remove('scroll-scrolling'); - - console.log('REMOVING TRANSITION'); - this.el.style.webkitTransitionDuration = '0'; - - clearTimeout(this._momentumStepTimeout) - }, - - - _initDrag: function() { - this._onScrollEnd(); - this._isStopped = false; - }, - - - /** - * Initialize a drag by grabbing the content area to drag, and any other - * info we might need for the dragging. - */ - _startDrag: function(e) { - var offsetX, content; - - this._initDrag(); - - var scrollLeft = parseFloat(this.el.style.webkitTransform.replace('translate3d(', '').split(',')[0]) || 0; - var scrollTop = parseFloat(this.el.style.webkitTransform.replace('translate3d(', '').split(',')[1]) || 0; - - var totalWidth = this.el.scrollWidth; - var totalHeight = this.el.scrollHeight; - var parentWidth = this.el.parentNode.offsetWidth; - var parentHeight = this.el.parentNode.offsetHeight; - - var maxX = Math.min(0, (-totalWidth + parentWidth)); - var maxY = Math.min(0, (-totalHeight + parentHeight)); - - // Check if we even have enough content to scroll, if not, don't start the drag - if((this.isHorizontalEnabled && maxX == 0) || (this.isVerticalEnabled && maxY == 0)) { - return; - } - - this.x = scrollLeft; - this.y = scrollTop; - - this._drag = { - direction: 'v', - pointX: e.gesture.touches[0].pageX, - pointY: e.gesture.touches[0].pageY, - startX: scrollLeft, - startY: scrollTop, - resist: 1, - startTime: Date.now() - }; - }, - - - - /** - * Process the drag event to move the item to the left or right. - * - * This function needs to be as fast as possible to make sure scrolling - * performance is high. - */ - _handleDrag: function(e) { - var _this = this; - - var content; - - // The drag stopped already, don't process this one - if(_this._isStopped) { - _this._initDrag(); - return; - } - - // We really aren't dragging - if(!_this._drag) { - _this._startDrag(e); - if(!_this._drag) { return; } - } - - // Stop any default events during the drag - e.preventDefault(); - - var px = e.gesture.touches[0].pageX; - var py = e.gesture.touches[0].pageY; - - var deltaX = px - _this._drag.pointX; - var deltaY = py - _this._drag.pointY; - - //console.log("Delta x", deltaX); - //console.log("Delta y", deltaY); - - _this._drag.pointX = px; - _this._drag.pointY = py; - - // Check if we should start dragging. Check if we've dragged past the threshold. - if(!_this._isDragging && - ((Math.abs(e.gesture.deltaY) > _this.dragThreshold) || - (Math.abs(e.gesture.deltaX) > _this.dragThreshold))) { - _this._isDragging = true; - } - - if(_this._isDragging) { - var drag = _this._drag; - - // Request an animation frame to batch DOM reads/writes - window.requestAnimationFrame(function() { - // We are dragging, grab the current content height - - var totalWidth = _this.el.scrollWidth; - var totalHeight = _this.el.scrollHeight; - var parentWidth = _this.el.parentNode.offsetWidth; - var parentHeight = _this.el.parentNode.offsetHeight; - var maxX = Math.min(0, (-totalWidth + parentWidth)); - var maxY = Math.min(0, (-totalHeight + parentHeight)); - - // Grab current timestamp to keep our speend, etc. - // calculations in a window - var timestamp = Date.now(); - - // Calculate the new Y point for the container - // TODO: Only enable certain axes - var newX = _this.x + deltaX; - var newY = _this.y + deltaY; - - if(newX > 0 || (-newX + parentWidth) > totalWidth) { - // Rubber band - newX = _this.x + deltaX / 3; - } - // Check if the dragging is beyond the bottom or top - if(newY > 0 || (-newY + parentHeight) > totalHeight) { - // Rubber band - newY = _this.y + deltaY / 3;//(-_this.resistance); - } - - if(!_this.isHorizontalEnabled) { - newX = 0; - } - if(!_this.isVerticalEnabled) { - newY = 0; - } - - // Update the new translated Y point of the container - _this.el.style.webkitTransform = 'translate3d(' + newX + 'px,' + newY + 'px, 0)'; - - // Store the last points - _this.x = newX; - _this.y = newY; - - console.log('Moving to', newX, newY); - - // Check if we need to reset the drag initial states if we've - // been dragging for a bit - if(timestamp - drag.startTime > 300) { - console.log('Resetting timer'); - drag.startTime = timestamp; - drag.startX = _this.x; - drag.startY = _this.y; - } - - // Trigger a scroll event - ionic.trigger(_this.scrollEventName, { - target: _this.el, - scrollLeft: -newX, - scrollTop: -newY - }); - }); - } - }, - - - - _handleEndDrag: function(e) { - // We didn't have a drag, so just init and leave - if(!this._drag) { - this._initDrag(); - return; - } - - // Set a flag in case we don't cleanup completely after the - // drag animation so we can cleanup the next time a drag starts - this._isStopped = true; - - // Animate to the finishing point - this._animateToStop(e); - - }, - - - // Find the stopping point given the current velocity and acceleration rate, and - // animate to that position - _animateToStop: function(e) { - var _this = this; - window.requestAnimationFrame(function() { - - var drag = _this._drag; - - // Calculate the viewport height and the height of the content - var totalWidth = _this.el.scrollWidth; - var totalHeight = _this.el.scrollHeight; - - // The parent bounding box helps us figure max/min scroll amounts - var parentWidth = _this.el.parentNode.offsetWidth; - var parentHeight = _this.el.parentNode.offsetHeight; - - // Calculate how long we've been dragging for, with a max of 300ms - var duration = Date.now() - _this._drag.startTime; - var time = 0; - var easing = ''; - - var newX = Math.round(_this.x); - var newY = Math.round(_this.y); - - _this.scrollTo(newX, newY); - - - // Check if we just snap back to bounds - if(_this.wrapScrollPosition(_this.bounceTime)) { - return; - } - - // If the duration is within reasonable bounds, enable momentum scrolling so we - // can "slide" to a finishing point - if(duration < 300) { - var momentumX = _this._getMomentum(_this.x, drag.startX, duration, parentWidth - totalWidth, parentWidth); - var momentumY = _this._getMomentum(_this.y, drag.startY, duration, parentHeight - totalHeight, parentHeight); - //var newX = momentumX.destination; - newX = momentumX.destination; - newY = momentumY.destination; - - // Calcualte the longest required time for the momentum animation and - // use that. - time = Math.max(momentumX.duration, momentumY.duration); - } - - // If we've moved, we will need to scroll - if(newX != _this.x || newY != _this.y) { - console.trace("SCROLL FROM", _this.x, _this.y, "TO", newX, newY); - - // If the end position is out of bounds, change the function we use for easing - // to get a different animation for the rubber banding - if ( newX > 0 || newX < (-totalWidth + parentWidth) || newY > 0 || newY < (-totalHeight + parentHeight)) { - easing = EASING_FUNCTIONS.bounce; - } - - _this.scrollTo(newX, newY, time, easing); - } - }); - } - }; - })(ionic); ; (function(ionic) { diff --git a/js/utils/utils.js b/js/utils/utils.js index cd1d4bd6c0..7ec799d2b4 100644 --- a/js/utils/utils.js +++ b/js/utils/utils.js @@ -1,22 +1,59 @@ (function(ionic) { ionic.Utils = { - /** - * extend method, - * also used for cloning when dest is an empty object - * @param {Object} dest - * @param {Object} src - * @parm {Boolean} merge do a merge - * @returns {Object} dest - */ - extend: function extend(dest, src, merge) { - for (var key in src) { - if(dest[key] !== undefined && merge) { - continue; - } - dest[key] = src[key]; + // Borrowed from Backbone.js's extend + // Helper function to correctly set up the prototype chain, for subclasses. + // Similar to `goog.inherits`, but uses a hash of prototype properties and + // class properties to be extended. + inherit: function(protoProps, staticProps) { + var parent = this; + var child; + + // The constructor function for the new subclass is either defined by you + // (the "constructor" property in your `extend` definition), or defaulted + // by us to simply call the parent's constructor. + if (protoProps && protoProps.hasOwnProperty('constructor')) { + child = protoProps.constructor; + } else { + child = function(){ return parent.apply(this, arguments); }; } - return dest; + + // Add static properties to the constructor function, if supplied. + ionic.extend(child, parent, staticProps); + + // Set the prototype chain to inherit from `parent`, without calling + // `parent`'s constructor function. + var Surrogate = function(){ this.constructor = child; }; + Surrogate.prototype = parent.prototype; + child.prototype = new Surrogate; + + // Add prototype properties (instance properties) to the subclass, + // if supplied. + if (protoProps) ionic.extend(child.prototype, protoProps); + + // Set a convenience property in case the parent's prototype is needed + // later. + child.__super__ = parent.prototype; + + return child; }, + + // Extend adapted from Underscore.js + extend: function(obj) { + var args = Array.prototype.slice.call(arguments, 1); + for(var i = 0; i < args.length; i++) { + var source = args[i]; + if (source) { + for (var prop in source) { + obj[prop] = source[prop]; + } + } + } + return obj; + } }; + + ionic.inherit = ionic.Utils.inherit; + ionic.extend = ionic.Utils.extend; + })(window.ionic); diff --git a/js/views/scrollView.js b/js/views/scrollView.js index d312b21fe3..6f016b31e6 100644 --- a/js/views/scrollView.js +++ b/js/views/scrollView.js @@ -23,57 +23,53 @@ toiletSeat: 'cubic-bezier(0.05, 0.60, 0.05, 0.60)' }; - ionic.views.ScrollView = function(opts) { - var _this = this; + ionic.views.Scroll = ionic.views.View.inherit({ + initialize: function(opts) { + var _this = this; - // Extend the options with our defaults - opts = ionic.Utils.extend({ - decelerationRate: ionic.views.ScrollView.prototype.DECEL_RATE_NORMAL, - dragThreshold: 10, - resistance: 2, - scrollEventName: 'momentumScrolled', - scrollEndEventName: 'momentumScrollEnd', - intertialEventInterval: 50, - mouseWheelSpeed: 20, - invertWheel: false, - isVerticalEnabled: true, - isHorizontalEnabled: false, - bounceEasing: EASING_FUNCTIONS.bounce, - bounceTime: 600 //how long to take when bouncing back in a rubber band - }, opts); + // Extend the options with our defaults + opts = ionic.Utils.extend({ + decelerationRate: ionic.views.Scroll.prototype.DECEL_RATE_NORMAL, + dragThreshold: 10, + resistance: 2, + scrollEventName: 'momentumScrolled', + scrollEndEventName: 'momentumScrollEnd', + intertialEventInterval: 50, + mouseWheelSpeed: 20, + invertWheel: false, + isVerticalEnabled: true, + isHorizontalEnabled: false, + bounceEasing: EASING_FUNCTIONS.bounce, + bounceTime: 600 //how long to take when bouncing back in a rubber band + }, opts); - ionic.Utils.extend(this, opts); + ionic.Utils.extend(this, opts); - this.el = opts.el; + this.el = opts.el; - this.y = 0; - this.x = 0; + this.y = 0; + this.x = 0; - // Listen for drag and release events - ionic.onGesture('drag', function(e) { - _this._handleDrag(e); - }, this.el); - ionic.onGesture('release', function(e) { - _this._handleEndDrag(e); - }, this.el); - ionic.on('mousewheel', function(e) { - _this._wheel(e); - }, this.el); - ionic.on('DOMMouseScroll', function(e) { - _this._wheel(e); - }, this.el); - ionic.on(this.scrollEndEventName, function(e) { - _this._onScrollEnd(e); - }, this.el); - ionic.on('webkitTransitionEnd', function(e) { - _this._onTransitionEnd(e); - }); - }; - - ionic.views.ScrollView.prototype = { - DECEL_RATE_NORMAL: 0.998, - DECEL_RATE_FAST: 0.99, - DECEL_RATE_SLOW: 0.996, + // Listen for drag and release events + ionic.onGesture('drag', function(e) { + _this._handleDrag(e); + }, this.el); + ionic.onGesture('release', function(e) { + _this._handleEndDrag(e); + }, this.el); + ionic.on('mousewheel', function(e) { + _this._wheel(e); + }, this.el); + ionic.on('DOMMouseScroll', function(e) { + _this._wheel(e); + }, this.el); + ionic.on(this.scrollEndEventName, function(e) { + _this._onScrollEnd(e); + }, this.el); + ionic.on('webkitTransitionEnd', function(e) { + _this._onTransitionEnd(e); + }); + }, /** * Scroll to the given X and Y point, taking @@ -541,6 +537,10 @@ } }); } - }; + }, { + DECEL_RATE_NORMAL: 0.998, + DECEL_RATE_FAST: 0.99, + DECEL_RATE_SLOW: 0.996, + }); })(ionic); diff --git a/js/views/view.js b/js/views/view.js new file mode 100644 index 0000000000..f82c31cc35 --- /dev/null +++ b/js/views/view.js @@ -0,0 +1,13 @@ +(function(ionic) { +'use strict'; + ionic.views.View = function() { + this.initialize.apply(this, arguments); + }; + + ionic.views.View.inherit = ionic.inherit; + + ionic.extend(ionic.views.View.prototype, { + initialize: function() {} + }); + +})(window.ionic); diff --git a/test/scroll.html b/test/scroll.html index 3a0a7b64a5..0c6e1076b4 100644 --- a/test/scroll.html +++ b/test/scroll.html @@ -43,7 +43,7 @@ s.firstElementChild.appendChild(li); } - var scroll = new ionic.views.ScrollView({ + var scroll = new ionic.views.Scroll({ el: s });