forked from revolunet/angular-carousel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
angular-carousel.js
2091 lines (1815 loc) · 78.2 KB
/
angular-carousel.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
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Angular Carousel - Mobile friendly touch carousel for AngularJS
* @version v1.0.1 - 2016-03-05
* @link http://revolunet.github.com/angular-carousel
* @author Julien Bouquillon <[email protected]>
* @license MIT License, http://www.opensource.org/licenses/MIT
*/
/*global angular */
/*
Angular touch carousel with CSS GPU accel and slide buffering
http://github.com/revolunet/angular-carousel
*/
angular.module('angular-carousel', [
'ngTouch',
'angular-carousel.shifty'
]);
angular.module('angular-carousel')
.directive('rnCarouselAutoSlide', ['$interval', function($interval) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var stopAutoPlay = function() {
if (scope.autoSlider) {
$interval.cancel(scope.autoSlider);
scope.autoSlider = null;
}
};
var restartTimer = function() {
scope.autoSlide();
};
scope.$watch('carouselIndex', restartTimer);
if (attrs.hasOwnProperty('rnCarouselPauseOnHover') && attrs.rnCarouselPauseOnHover !== 'false'){
element.on('mouseenter', stopAutoPlay);
element.on('mouseleave', restartTimer);
}
scope.$on('$destroy', function(){
stopAutoPlay();
element.off('mouseenter', stopAutoPlay);
element.off('mouseleave', restartTimer);
});
}
};
}]);
angular.module('angular-carousel')
.directive('rnCarouselIndicators', ['$parse', function($parse) {
return {
restrict: 'A',
scope: {
slides: '=',
index: '=rnCarouselIndex'
},
templateUrl: 'carousel-indicators.html',
link: function(scope, iElement, iAttributes) {
var indexModel = $parse(iAttributes.rnCarouselIndex);
scope.goToSlide = function(index) {
indexModel.assign(scope.$parent.$parent, index);
};
}
};
}]);
angular.module('angular-carousel').run(['$templateCache', function($templateCache) {
$templateCache.put('carousel-indicators.html',
'<div class="rn-carousel-indicator">\n' +
'<span ng-repeat="slide in slides" ng-class="{active: $index==index}" ng-click="goToSlide($index)">●</span>' +
'</div>'
);
}]);
(function() {
"use strict";
angular.module('angular-carousel')
.service('DeviceCapabilities', function() {
// TODO: merge in a single function
// detect supported CSS property
function detectTransformProperty() {
var transformProperty = 'transform',
safariPropertyHack = 'webkitTransform';
if (typeof document.body.style[transformProperty] !== 'undefined') {
['webkit', 'moz', 'o', 'ms'].every(function (prefix) {
var e = '-' + prefix + '-transform';
if (typeof document.body.style[e] !== 'undefined') {
transformProperty = e;
return false;
}
return true;
});
} else if (typeof document.body.style[safariPropertyHack] !== 'undefined') {
transformProperty = '-webkit-transform';
} else {
transformProperty = undefined;
}
return transformProperty;
}
return {
transformProperty: detectTransformProperty()
};
})
.service('computeCarouselSlideStyle', ["DeviceCapabilities", function(DeviceCapabilities) {
// compute transition transform properties for a given slide and global offset
return function(slideIndex, offset, transitionType) {
var style = {
display: 'inline-block'
},
opacity,
absoluteLeft = (slideIndex * 100) + offset,
slideTransformValue = 'translate3d(' + absoluteLeft + '%, 0, 0)',
distance = ((100 - Math.abs(absoluteLeft)) / 100);
if (!DeviceCapabilities.transformProperty) {
// fallback to default slide if transformProperty is not available
style['margin-left'] = absoluteLeft + '%';
} else {
if (transitionType == 'fadeAndSlide') {
style[DeviceCapabilities.transformProperty] = slideTransformValue;
opacity = 0;
if (Math.abs(absoluteLeft) < 100) {
opacity = 0.3 + distance * 0.7;
}
style.opacity = opacity;
} else if (transitionType == 'hexagon') {
var transformFrom = 100,
degrees = 0,
maxDegrees = 60 * (distance - 1);
transformFrom = offset < (slideIndex * -100) ? 100 : 0;
degrees = offset < (slideIndex * -100) ? maxDegrees : -maxDegrees;
style[DeviceCapabilities.transformProperty] = slideTransformValue + ' ' + 'rotateY(' + degrees + 'deg)';
style[DeviceCapabilities.transformProperty + '-origin'] = transformFrom + '% 50%';
} else if (transitionType == 'zoom') {
style[DeviceCapabilities.transformProperty] = slideTransformValue;
var scale = 1;
if (Math.abs(absoluteLeft) < 100) {
scale = 1 + ((1 - distance) * 2);
}
style[DeviceCapabilities.transformProperty] += ' scale(' + scale + ')';
style[DeviceCapabilities.transformProperty + '-origin'] = '50% 50%';
opacity = 0;
if (Math.abs(absoluteLeft) < 100) {
opacity = 0.3 + distance * 0.7;
}
style.opacity = opacity;
} else {
style[DeviceCapabilities.transformProperty] = slideTransformValue;
}
}
return style;
};
}])
.service('createStyleString', function() {
return function(object) {
var styles = [];
angular.forEach(object, function(value, key) {
styles.push(key + ':' + value);
});
return styles.join(';');
};
})
.directive('rnCarousel', ['$swipe', '$window', '$document', '$parse', '$compile', '$timeout', '$interval', 'computeCarouselSlideStyle', 'createStyleString', 'Tweenable',
function($swipe, $window, $document, $parse, $compile, $timeout, $interval, computeCarouselSlideStyle, createStyleString, Tweenable) {
// internal ids to allow multiple instances
var carouselId = 0,
// in absolute pixels, at which distance the slide stick to the edge on release
rubberTreshold = 3;
var requestAnimationFrame = $window.requestAnimationFrame || $window.webkitRequestAnimationFrame || $window.mozRequestAnimationFrame;
function getItemIndex(collection, target, defaultIndex) {
var result = defaultIndex;
collection.every(function(item, index) {
if (angular.equals(item, target)) {
result = index;
return false;
}
return true;
});
return result;
}
return {
restrict: 'A',
scope: true,
compile: function(tElement, tAttributes) {
// use the compile phase to customize the DOM
var firstChild = tElement[0].querySelector('li'),
firstChildAttributes = (firstChild) ? firstChild.attributes : [],
isRepeatBased = false,
isBuffered = false,
repeatItem,
repeatCollection;
// try to find an ngRepeat expression
// at this point, the attributes are not yet normalized so we need to try various syntax
['ng-repeat', 'data-ng-repeat', 'ng:repeat', 'x-ng-repeat'].every(function(attr) {
var repeatAttribute = firstChildAttributes[attr];
if (angular.isDefined(repeatAttribute)) {
// ngRepeat regexp extracted from angular 1.2.7 src
var exprMatch = repeatAttribute.value.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?\s*$/),
trackProperty = exprMatch[3];
repeatItem = exprMatch[1];
repeatCollection = exprMatch[2];
if (repeatItem) {
if (angular.isDefined(tAttributes['rnCarouselBuffered'])) {
// update the current ngRepeat expression and add a slice operator if buffered
isBuffered = true;
repeatAttribute.value = repeatItem + ' in ' + repeatCollection + '|carouselSlice:carouselBufferIndex:carouselBufferSize';
if (trackProperty) {
repeatAttribute.value += ' track by ' + trackProperty;
}
}
isRepeatBased = true;
return false;
}
}
return true;
});
return function(scope, iElement, iAttributes, containerCtrl) {
carouselId++;
var defaultOptions = {
transitionType: iAttributes.rnCarouselTransition || 'slide',
transitionEasing: iAttributes.rnCarouselEasing || 'easeTo',
transitionDuration: parseInt(iAttributes.rnCarouselDuration, 10) || 300,
isSequential: true,
autoSlideDuration: 3,
bufferSize: 5,
/* in container % how much we need to drag to trigger the slide change */
moveTreshold: 0.1,
defaultIndex: 0
};
// TODO
var options = angular.extend({}, defaultOptions);
var pressed,
startX,
isIndexBound = false,
offset = 0,
destination,
swipeMoved = false,
//animOnIndexChange = true,
currentSlides = [],
elWidth = null,
elX = null,
animateTransitions = true,
intialState = true,
animating = false,
mouseUpBound = false,
locked = false;
//rn-swipe-disabled =true will only disable swipe events
if(iAttributes.rnSwipeDisabled !== "true") {
$swipe.bind(iElement, {
start: swipeStart,
move: swipeMove,
end: swipeEnd,
cancel: function(event) {
swipeEnd({}, event);
}
});
}
function getSlidesDOM() {
return iElement[0].querySelectorAll('ul[rn-carousel] > li');
}
function documentMouseUpEvent(event) {
// in case we click outside the carousel, trigger a fake swipeEnd
swipeMoved = true;
swipeEnd({
x: event.clientX,
y: event.clientY
}, event);
}
function updateSlidesPosition(offset) {
// manually apply transformation to carousel childrens
// todo : optim : apply only to visible items
var x = scope.carouselBufferIndex * 100 + offset;
angular.forEach(getSlidesDOM(), function(child, index) {
child.style.cssText = createStyleString(computeCarouselSlideStyle(index, x, options.transitionType));
});
}
scope.nextSlide = function(slideOptions) {
var index = scope.carouselIndex + 1;
if (index > currentSlides.length - 1) {
index = 0;
}
if (!locked) {
goToSlide(index, slideOptions);
}
};
scope.prevSlide = function(slideOptions) {
var index = scope.carouselIndex - 1;
if (index < 0) {
index = currentSlides.length - 1;
}
goToSlide(index, slideOptions);
};
function goToSlide(index, slideOptions) {
//console.log('goToSlide', arguments);
// move a to the given slide index
if (index === undefined) {
index = scope.carouselIndex;
}
slideOptions = slideOptions || {};
if (slideOptions.animate === false || options.transitionType === 'none') {
locked = false;
offset = index * -100;
scope.carouselIndex = index;
updateBufferIndex();
return;
}
locked = true;
var tweenable = new Tweenable();
tweenable.tween({
from: {
'x': offset
},
to: {
'x': index * -100
},
duration: options.transitionDuration,
easing: options.transitionEasing,
step: function(state) {
if (isFinite(state.x)) {
updateSlidesPosition(state.x);
}
},
finish: function() {
scope.$apply(function() {
scope.carouselIndex = index;
offset = index * -100;
updateBufferIndex();
$timeout(function () {
locked = false;
}, 0, false);
});
}
});
}
function getContainerWidth() {
var rect = iElement[0].getBoundingClientRect();
return rect.width ? rect.width : rect.right - rect.left;
}
function updateContainerWidth() {
elWidth = getContainerWidth();
}
function bindMouseUpEvent() {
if (!mouseUpBound) {
mouseUpBound = true;
$document.bind('mouseup', documentMouseUpEvent);
}
}
function unbindMouseUpEvent() {
if (mouseUpBound) {
mouseUpBound = false;
$document.unbind('mouseup', documentMouseUpEvent);
}
}
function swipeStart(coords, event) {
// console.log('swipeStart', coords, event);
if(!currentSlides) {
return;
}
if (locked || currentSlides.length <= 1) {
return;
}
updateContainerWidth();
elX = iElement[0].querySelector('li').getBoundingClientRect().left;
pressed = true;
startX = coords.x;
return false;
}
function swipeMove(coords, event) {
//console.log('swipeMove', coords, event);
var x, delta;
bindMouseUpEvent();
if (pressed) {
x = coords.x;
delta = startX - x;
if (delta > 2 || delta < -2) {
swipeMoved = true;
var moveOffset = offset + (-delta * 100 / elWidth);
updateSlidesPosition(moveOffset);
}
}
return false;
}
var init = true;
scope.carouselIndex = 0;
if (!isRepeatBased) {
// fake array when no ng-repeat
currentSlides = [];
angular.forEach(getSlidesDOM(), function(node, index) {
currentSlides.push({id: index});
});
}
if (iAttributes.rnCarouselControls!==undefined) {
// dont use a directive for this
var canloop = ((isRepeatBased ? scope.$eval(repeatCollection.replace('::', '')).length : currentSlides.length) > 1) ? angular.isDefined(tAttributes['rnCarouselControlsAllowLoop']) : false;
var nextSlideIndexCompareValue = isRepeatBased ? '(' + repeatCollection.replace('::', '') + ').length - 1' : currentSlides.length - 1;
var tpl = '<div class="rn-carousel-controls">\n' +
' <span class="rn-carousel-control rn-carousel-control-prev" ng-click="prevSlide()" ng-if="carouselIndex > 0 || ' + canloop + '"></span>\n' +
' <span class="rn-carousel-control rn-carousel-control-next" ng-click="nextSlide()" ng-if="carouselIndex < ' + nextSlideIndexCompareValue + ' || ' + canloop + '"></span>\n' +
'</div>';
iElement.parent().append($compile(angular.element(tpl))(scope));
}
if (iAttributes.rnCarouselAutoSlide!==undefined) {
var duration = parseInt(iAttributes.rnCarouselAutoSlide, 10) || options.autoSlideDuration;
scope.autoSlide = function() {
if (scope.autoSlider) {
$interval.cancel(scope.autoSlider);
scope.autoSlider = null;
}
scope.autoSlider = $interval(function() {
if (!locked && !pressed) {
scope.nextSlide();
}
}, duration * 1000);
};
}
if (iAttributes.rnCarouselDefaultIndex) {
var defaultIndexModel = $parse(iAttributes.rnCarouselDefaultIndex);
options.defaultIndex = defaultIndexModel(scope.$parent) || 0;
}
if (iAttributes.rnCarouselIndex) {
var updateParentIndex = function(value) {
indexModel.assign(scope.$parent, value);
};
var indexModel = $parse(iAttributes.rnCarouselIndex);
if (angular.isFunction(indexModel.assign)) {
/* check if this property is assignable then watch it */
scope.$watch('carouselIndex', function(newValue) {
updateParentIndex(newValue);
});
scope.$parent.$watch(indexModel, function(newValue, oldValue) {
if (newValue !== undefined && newValue !== null) {
if (currentSlides && currentSlides.length > 0 && newValue >= currentSlides.length) {
newValue = currentSlides.length - 1;
updateParentIndex(newValue);
} else if (currentSlides && newValue < 0) {
newValue = 0;
updateParentIndex(newValue);
}
if (!locked) {
goToSlide(newValue, {
animate: !init
});
}
init = false;
}
});
isIndexBound = true;
if (options.defaultIndex) {
goToSlide(options.defaultIndex, {
animate: !init
});
}
} else if (!isNaN(iAttributes.rnCarouselIndex)) {
/* if user just set an initial number, set it */
goToSlide(parseInt(iAttributes.rnCarouselIndex, 10), {
animate: false
});
}
} else {
goToSlide(options.defaultIndex, {
animate: !init
});
init = false;
}
if (iAttributes.rnCarouselLocked) {
scope.$watch(iAttributes.rnCarouselLocked, function(newValue, oldValue) {
// only bind swipe when it's not switched off
if(newValue === true) {
locked = true;
} else {
locked = false;
}
});
}
if (isRepeatBased) {
// use rn-carousel-deep-watch to fight the Angular $watchCollection weakness : https://github.com/angular/angular.js/issues/2621
// optional because it have some performance impacts (deep watch)
var deepWatch = (iAttributes.rnCarouselDeepWatch!==undefined);
scope[deepWatch?'$watch':'$watchCollection'](repeatCollection, function(newValue, oldValue) {
//console.log('repeatCollection', currentSlides);
currentSlides = newValue;
if(!currentSlides){
return;
}
// if deepWatch ON ,manually compare objects to guess the new position
if (!angular.isArray(currentSlides)) {
throw Error('the slides collection must be an Array');
}
if (deepWatch && angular.isArray(newValue)) {
var activeElement = oldValue[scope.carouselIndex];
var newIndex = getItemIndex(newValue, activeElement, scope.carouselIndex);
goToSlide(newIndex, {animate: false});
} else {
goToSlide(scope.carouselIndex, {animate: false});
}
}, true);
}
function swipeEnd(coords, event, forceAnimation) {
// console.log('swipeEnd', 'scope.carouselIndex', scope.carouselIndex);
// Prevent clicks on buttons inside slider to trigger "swipeEnd" event on touchend/mouseup
// console.log(iAttributes.rnCarouselOnInfiniteScroll);
if (event && !swipeMoved) {
return;
}
unbindMouseUpEvent();
pressed = false;
swipeMoved = false;
destination = startX - coords.x;
if (destination===0) {
return;
}
if (locked) {
return;
}
offset += (-destination * 100 / elWidth);
if (options.isSequential) {
var minMove = options.moveTreshold * elWidth,
absMove = -destination,
slidesMove = -Math[absMove >= 0 ? 'ceil' : 'floor'](absMove / elWidth),
shouldMove = Math.abs(absMove) > minMove;
if (currentSlides && (slidesMove + scope.carouselIndex) >= currentSlides.length) {
slidesMove = currentSlides.length - 1 - scope.carouselIndex;
}
if ((slidesMove + scope.carouselIndex) < 0) {
slidesMove = -scope.carouselIndex;
}
var moveOffset = shouldMove ? slidesMove : 0;
destination = (scope.carouselIndex + moveOffset);
goToSlide(destination);
if(iAttributes.rnCarouselOnInfiniteScrollRight!==undefined && slidesMove === 0 && scope.carouselIndex !== 0) {
$parse(iAttributes.rnCarouselOnInfiniteScrollRight)(scope)
goToSlide(0);
}
if(iAttributes.rnCarouselOnInfiniteScrollLeft!==undefined && slidesMove === 0 && scope.carouselIndex === 0 && moveOffset === 0) {
$parse(iAttributes.rnCarouselOnInfiniteScrollLeft)(scope)
goToSlide(currentSlides.length);
}
} else {
scope.$apply(function() {
scope.carouselIndex = parseInt(-offset / 100, 10);
updateBufferIndex();
});
}
}
scope.$on('$destroy', function() {
unbindMouseUpEvent();
});
scope.carouselBufferIndex = 0;
scope.carouselBufferSize = options.bufferSize;
function updateBufferIndex() {
// update and cap te buffer index
var bufferIndex = 0;
var bufferEdgeSize = (scope.carouselBufferSize - 1) / 2;
if (isBuffered) {
if (scope.carouselIndex <= bufferEdgeSize) {
// first buffer part
bufferIndex = 0;
} else if (currentSlides && currentSlides.length < scope.carouselBufferSize) {
// smaller than buffer
bufferIndex = 0;
} else if (currentSlides && scope.carouselIndex > currentSlides.length - scope.carouselBufferSize) {
// last buffer part
bufferIndex = currentSlides.length - scope.carouselBufferSize;
} else {
// compute buffer start
bufferIndex = scope.carouselIndex - bufferEdgeSize;
}
scope.carouselBufferIndex = bufferIndex;
$timeout(function() {
updateSlidesPosition(offset);
}, 0, false);
} else {
$timeout(function() {
updateSlidesPosition(offset);
}, 0, false);
}
}
function onOrientationChange() {
updateContainerWidth();
goToSlide();
}
// handle orientation change
var winEl = angular.element($window);
winEl.bind('orientationchange', onOrientationChange);
winEl.bind('resize', onOrientationChange);
scope.$on('$destroy', function() {
unbindMouseUpEvent();
winEl.unbind('orientationchange', onOrientationChange);
winEl.unbind('resize', onOrientationChange);
});
};
}
};
}
]);
})();
angular.module('angular-carousel.shifty', [])
.factory('Tweenable', function() {
/*! shifty - v1.3.4 - 2014-10-29 - http://jeremyckahn.github.io/shifty */
;(function (root) {
/*!
* Shifty Core
* By Jeremy Kahn - [email protected]
*/
var Tweenable = (function () {
'use strict';
// Aliases that get defined later in this function
var formula;
// CONSTANTS
var DEFAULT_SCHEDULE_FUNCTION;
var DEFAULT_EASING = 'linear';
var DEFAULT_DURATION = 500;
var UPDATE_TIME = 1000 / 60;
var _now = Date.now
? Date.now
: function () {return +new Date();};
var now = typeof SHIFTY_DEBUG_NOW !== 'undefined' ? SHIFTY_DEBUG_NOW : _now;
if (typeof window !== 'undefined') {
// requestAnimationFrame() shim by Paul Irish (modified for Shifty)
// http://paulirish.com/2011/requestanimationframe-for-smart-animating/
DEFAULT_SCHEDULE_FUNCTION = window.requestAnimationFrame
|| window.webkitRequestAnimationFrame
|| window.oRequestAnimationFrame
|| window.msRequestAnimationFrame
|| (window.mozCancelRequestAnimationFrame
&& window.mozRequestAnimationFrame)
|| setTimeout;
} else {
DEFAULT_SCHEDULE_FUNCTION = setTimeout;
}
function noop () {
// NOOP!
}
/*!
* Handy shortcut for doing a for-in loop. This is not a "normal" each
* function, it is optimized for Shifty. The iterator function only receives
* the property name, not the value.
* @param {Object} obj
* @param {Function(string)} fn
*/
function each (obj, fn) {
var key;
for (key in obj) {
if (Object.hasOwnProperty.call(obj, key)) {
fn(key);
}
}
}
/*!
* Perform a shallow copy of Object properties.
* @param {Object} targetObject The object to copy into
* @param {Object} srcObject The object to copy from
* @return {Object} A reference to the augmented `targetObj` Object
*/
function shallowCopy (targetObj, srcObj) {
each(srcObj, function (prop) {
targetObj[prop] = srcObj[prop];
});
return targetObj;
}
/*!
* Copies each property from src onto target, but only if the property to
* copy to target is undefined.
* @param {Object} target Missing properties in this Object are filled in
* @param {Object} src
*/
function defaults (target, src) {
each(src, function (prop) {
if (typeof target[prop] === 'undefined') {
target[prop] = src[prop];
}
});
}
/*!
* Calculates the interpolated tween values of an Object for a given
* timestamp.
* @param {Number} forPosition The position to compute the state for.
* @param {Object} currentState Current state properties.
* @param {Object} originalState: The original state properties the Object is
* tweening from.
* @param {Object} targetState: The destination state properties the Object
* is tweening to.
* @param {number} duration: The length of the tween in milliseconds.
* @param {number} timestamp: The UNIX epoch time at which the tween began.
* @param {Object} easing: This Object's keys must correspond to the keys in
* targetState.
*/
function tweenProps (forPosition, currentState, originalState, targetState,
duration, timestamp, easing) {
var normalizedPosition = (forPosition - timestamp) / duration;
var prop;
for (prop in currentState) {
if (currentState.hasOwnProperty(prop)) {
currentState[prop] = tweenProp(originalState[prop],
targetState[prop], formula[easing[prop]], normalizedPosition);
}
}
return currentState;
}
/*!
* Tweens a single property.
* @param {number} start The value that the tween started from.
* @param {number} end The value that the tween should end at.
* @param {Function} easingFunc The easing curve to apply to the tween.
* @param {number} position The normalized position (between 0.0 and 1.0) to
* calculate the midpoint of 'start' and 'end' against.
* @return {number} The tweened value.
*/
function tweenProp (start, end, easingFunc, position) {
return start + (end - start) * easingFunc(position);
}
/*!
* Applies a filter to Tweenable instance.
* @param {Tweenable} tweenable The `Tweenable` instance to call the filter
* upon.
* @param {String} filterName The name of the filter to apply.
*/
function applyFilter (tweenable, filterName) {
var filters = Tweenable.prototype.filter;
var args = tweenable._filterArgs;
each(filters, function (name) {
if (typeof filters[name][filterName] !== 'undefined') {
filters[name][filterName].apply(tweenable, args);
}
});
}
var timeoutHandler_endTime;
var timeoutHandler_currentTime;
var timeoutHandler_isEnded;
var timeoutHandler_offset;
/*!
* Handles the update logic for one step of a tween.
* @param {Tweenable} tweenable
* @param {number} timestamp
* @param {number} duration
* @param {Object} currentState
* @param {Object} originalState
* @param {Object} targetState
* @param {Object} easing
* @param {Function(Object, *, number)} step
* @param {Function(Function,number)}} schedule
*/
function timeoutHandler (tweenable, timestamp, duration, currentState,
originalState, targetState, easing, step, schedule) {
timeoutHandler_endTime = timestamp + duration;
timeoutHandler_currentTime = Math.min(now(), timeoutHandler_endTime);
timeoutHandler_isEnded =
timeoutHandler_currentTime >= timeoutHandler_endTime;
timeoutHandler_offset = duration - (
timeoutHandler_endTime - timeoutHandler_currentTime);
if (tweenable.isPlaying() && !timeoutHandler_isEnded) {
tweenable._scheduleId = schedule(tweenable._timeoutHandler, UPDATE_TIME);
applyFilter(tweenable, 'beforeTween');
tweenProps(timeoutHandler_currentTime, currentState, originalState,
targetState, duration, timestamp, easing);
applyFilter(tweenable, 'afterTween');
step(currentState, tweenable._attachment, timeoutHandler_offset);
} else if (timeoutHandler_isEnded) {
step(targetState, tweenable._attachment, timeoutHandler_offset);
tweenable.stop(true);
}
}
/*!
* Creates a usable easing Object from either a string or another easing
* Object. If `easing` is an Object, then this function clones it and fills
* in the missing properties with "linear".
* @param {Object} fromTweenParams
* @param {Object|string} easing
*/
function composeEasingObject (fromTweenParams, easing) {
var composedEasing = {};
if (typeof easing === 'string') {
each(fromTweenParams, function (prop) {
composedEasing[prop] = easing;
});
} else {
each(fromTweenParams, function (prop) {
if (!composedEasing[prop]) {
composedEasing[prop] = easing[prop] || DEFAULT_EASING;
}
});
}
return composedEasing;
}
/**
* Tweenable constructor.
* @param {Object=} opt_initialState The values that the initial tween should start at if a "from" object is not provided to Tweenable#tween.
* @param {Object=} opt_config See Tweenable.prototype.setConfig()
* @constructor
*/
function Tweenable (opt_initialState, opt_config) {
this._currentState = opt_initialState || {};
this._configured = false;
this._scheduleFunction = DEFAULT_SCHEDULE_FUNCTION;
// To prevent unnecessary calls to setConfig do not set default configuration here.
// Only set default configuration immediately before tweening if none has been set.
if (typeof opt_config !== 'undefined') {
this.setConfig(opt_config);
}
}
/**
* Configure and start a tween.
* @param {Object=} opt_config See Tweenable.prototype.setConfig()
* @return {Tweenable}
*/
Tweenable.prototype.tween = function (opt_config) {
if (this._isTweening) {
return this;
}
// Only set default config if no configuration has been set previously and none is provided now.
if (opt_config !== undefined || !this._configured) {
this.setConfig(opt_config);
}
this._timestamp = now();
this._start(this.get(), this._attachment);
return this.resume();
};
/**
* Sets the tween configuration. `config` may have the following options:
*
* - __from__ (_Object=_): Starting position. If omitted, the current state is used.
* - __to__ (_Object=_): Ending position.
* - __duration__ (_number=_): How many milliseconds to animate for.
* - __start__ (_Function(Object)_): Function to execute when the tween begins. Receives the state of the tween as the first parameter. Attachment is the second parameter.
* - __step__ (_Function(Object, *, number)_): Function to execute on every tick. Receives the state of the tween as the first parameter. Attachment is the second parameter, and the time elapsed since the start of the tween is the third parameter. This function is not called on the final step of the animation, but `finish` is.
* - __finish__ (_Function(Object, *)_): Function to execute upon tween completion. Receives the state of the tween as the first parameter. Attachment is the second parameter.
* - __easing__ (_Object|string=_): Easing curve name(s) to use for the tween.
* - __attachment__ (_Object|string|any=_): Value that is attached to this instance and passed on to the step/start/finish methods.
* @param {Object} config
* @return {Tweenable}
*/
Tweenable.prototype.setConfig = function (config) {
config = config || {};
this._configured = true;
// Attach something to this Tweenable instance (e.g.: a DOM element, an object, a string, etc.);
this._attachment = config.attachment;
// Init the internal state
this._pausedAtTime = null;
this._scheduleId = null;
this._start = config.start || noop;
this._step = config.step || noop;
this._finish = config.finish || noop;
this._duration = config.duration || DEFAULT_DURATION;
this._currentState = config.from || this.get();
this._originalState = this.get();
this._targetState = config.to || this.get();
// Aliases used below
var currentState = this._currentState;
var targetState = this._targetState;
// Ensure that there is always something to tween to.
defaults(targetState, currentState);
this._easing = composeEasingObject(
currentState, config.easing || DEFAULT_EASING);
this._filterArgs =
[currentState, this._originalState, targetState, this._easing];
applyFilter(this, 'tweenCreated');
return this;
};
/**
* Gets the current state.
* @return {Object}
*/
Tweenable.prototype.get = function () {
return shallowCopy({}, this._currentState);
};
/**
* Sets the current state.
* @param {Object} state
*/
Tweenable.prototype.set = function (state) {
this._currentState = state;
};
/**
* Pauses a tween. Paused tweens can be resumed from the point at which they were paused. This is different than [`stop()`](#stop), as that method causes a tween to start over when it is resumed.
* @return {Tweenable}
*/
Tweenable.prototype.pause = function () {
this._pausedAtTime = now();
this._isPaused = true;
return this;