forked from revolunet/angular-carousel
-
Notifications
You must be signed in to change notification settings - Fork 1
/
angular-carousel.js
executable file
·605 lines (523 loc) · 25.7 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
/**
* Angular Carousel - Mobile friendly touch carousel for AngularJS
* @version v0.2.4 - 2014-07-25
* @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.module('angular-carousel')
.directive('rnCarouselAutoSlide', ['$timeout', function($timeout) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var delay = Math.round(parseFloat(attrs.rnCarouselAutoSlide) * 1000),
timer = increment = false, slidesCount = element.children().length;
if(!scope.carouselExposedIndex){
scope.carouselExposedIndex = 0;
}
stopAutoplay = function () {
if (angular.isDefined(timer)) {
$timeout.cancel(timer);
}
timer = undefined;
};
increment = function () {
if (scope.carouselExposedIndex < slidesCount - 1) {
scope.carouselExposedIndex = scope.carouselExposedIndex + 1;
} else {
scope.carouselExposedIndex = 0;
}
};
restartTimer = function (){
stopAutoplay();
timer = $timeout(increment, delay);
};
scope.$watch('carouselIndex', function(){
restartTimer();
});
restartTimer();
if (attrs.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('rnCarouselControls', [function() {
return {
restrict: 'A',
replace: true,
scope: {
items: '=',
index: '=',
loop: '='
},
link: function(scope, element, attrs) {
scope.prev = function() {
scope.index = !scope.index ? scope.items.length : scope.index - 1;
};
scope.next = function() {
scope.index = (scope.index + 1) % scope.items.length;
};
},
templateUrl: 'carousel-controls.html'
};
}]);
angular.module('angular-carousel').run(['$templateCache', function($templateCache) {
$templateCache.put('carousel-controls.html',
'<div class="rn-carousel-controls">\n' +
' <span class="rn-carousel-control rn-carousel-control-prev" ng-click="prev();$event.stopPropagation();" ng-if="items.length > 1 && (index > 0 || loop)"></span>\n' +
' <span class="rn-carousel-control rn-carousel-control-next" ng-click="next();$event.stopPropagation();" ng-if="items.length > 1 && (index < items.length - 1 || loop)"></span>\n' +
'</div>'
);
}]);
angular.module('angular-carousel')
.directive('rnCarouselIndicators', [function() {
return {
restrict: 'A',
replace: true,
scope: {
items: '=',
index: '='
},
templateUrl: 'carousel-indicators.html'
};
}]);
angular.module('angular-carousel').run(['$templateCache', function($templateCache) {
$templateCache.put('carousel-indicators.html',
'<div class="rn-carousel-indicator">\n' +
' <span ng-repeat="item in items" ng-click="$parent.index=$index" ng-class="{active: $index==$parent.index}"></span>\n' +
'</div>'
);
}]);
(function() {
"use strict";
angular.module('angular-carousel')
.directive('rnCarousel', ['$swipe', '$window', '$document', '$parse', '$compile', '$rootScope', function($swipe, $window, $document, $parse, $compile, $rootScope) {
// internal ids to allow multiple instances
var carouselId = 0,
// used to compute the sliding speed
timeConstant = 75,
// in container % how much we need to drag to trigger the slide change
moveTreshold = 0.05,
// in absolute pixels, at which distance the slide stick to the edge on release
rubberTreshold = 3;
var requestAnimationFrame = $window.requestAnimationFrame || $window.webkitRequestAnimationFrame || $window.mozRequestAnimationFrame;
return {
restrict: 'A',
scope: true,
compile: function(tElement, tAttributes) {
// use the compile phase to customize the DOM
var firstChildAttributes = tElement.children()[0].attributes,
isRepeatBased = false,
isBuffered = false,
slidesCount = 0,
isIndexBound = false,
loop = angular.isDefined(tAttributes['rnCarouselLoop']),
repeatItem,
repeatCollection;
// add CSS classes
tElement.addClass('rn-carousel-slides');
tElement.children().addClass('rn-carousel-slide');
// 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', '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++;
scope.loop = loop;
var containerWidth,
transformProperty,
pressed,
startX,
amplitude,
offset = 0,
destination,
slidesCount = 0,
swipeMoved = false,
animOnIndexChange = true,
// javascript based animation easing
timestamp;
// add a wrapper div that will hide the overflow
var carousel = iElement.wrap("<div id='carousel-" + carouselId +"' class='rn-carousel-container'></div>"),
container = carousel.parent();
// if indicator or controls, setup the watch
if (angular.isDefined(iAttributes.rnCarouselIndicator) || angular.isDefined(iAttributes.rnCarouselControl)) {
updateIndicatorArray();
scope.$watch('carouselIndex', function(newValue) {
scope.indicatorIndex = newValue;
scope.carouselExposedIndex = newValue;
});
scope.$watch('indicatorIndex', function(newValue) {
goToSlide(newValue, true);
});
}
if (angular.isDefined(iAttributes.rnCarouselPreventAnimation)) {
animOnIndexChange = false;
}
scope.$watch('carouselExposedIndex', function(newValue) {
goToSlide(newValue, true);
});
// enable carousel indicator
if (angular.isDefined(iAttributes.rnCarouselIndicator)) {
var indicator = $compile("<div id='carousel-" + carouselId +"-indicator' index='indicatorIndex' items='carouselIndicatorArray' rn-carousel-indicators class='rn-carousel-indicator'></div>")(scope);
container.append(indicator);
}
// enable carousel controls
if (angular.isDefined(iAttributes.rnCarouselControl)) {
var controls = $compile("<div id='carousel-" + carouselId +"-controls' index='indicatorIndex' loop=" + loop + " items='carouselIndicatorArray' rn-carousel-controls class='rn-carousel-controls'></div>")(scope);
container.append(controls);
}
scope.carouselBufferIndex = 0;
scope.carouselBufferSize = 5;
scope.carouselIndex = 0;
// handle index databinding
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.carouselIndex = indexModel(scope);
scope.$parent.$watch(indexModel, function(newValue, oldValue) {
if (newValue!==undefined) {
if (newValue >= slidesCount) {
newValue = slidesCount - 1;
updateParentIndex(newValue);
} else if (newValue < 0) {
newValue = 0;
updateParentIndex(newValue);
}
goToSlide(newValue, animOnIndexChange);
}
});
isIndexBound = true;
} else if (!isNaN(iAttributes.rnCarouselIndex)) {
/* if user just set an initial number, set it */
scope.carouselIndex = parseInt(iAttributes.rnCarouselIndex, 10);
}
}
// watch the given collection
if (isRepeatBased) {
scope.$watchCollection(repeatCollection, function(newValue, oldValue) {
slidesCount = 0;
if (angular.isArray(newValue)) {
slidesCount = newValue.length;
} else if (angular.isObject(newValue)) {
slidesCount = Object.keys(newValue).length;
}
updateIndicatorArray();
if (!containerWidth) updateContainerWidth();
goToSlide(scope.carouselIndex);
});
} else {
slidesCount = iElement.children().length;
updateIndicatorArray();
updateContainerWidth();
}
function updateIndicatorArray() {
// generate an array to be used by the indicators
var items = [];
for (var i = 0; i < slidesCount; i++) items[i] = i;
scope.carouselIndicatorArray = items;
}
function getCarouselWidth() {
// container.css('width', 'auto');
var slides = carousel.children();
if (slides.length === 0) {
containerWidth = carousel[0].getBoundingClientRect().width;
} else {
containerWidth = slides[0].getBoundingClientRect().width;
}
// console.log('getCarouselWidth', containerWidth);
return containerWidth;
}
function updateContainerWidth() {
// force the carousel container width to match the first slide width
container.css('width', '100%');
var width = getCarouselWidth();
if (width) {
container.css('width', width + 'px');
}
}
function scroll(x) {
// use CSS 3D transform to move the carousel
if (isNaN(x)) {
x = scope.carouselIndex * containerWidth;
}
offset = x;
var move = -Math.round(offset);
move += (scope.carouselBufferIndex * containerWidth);
if(!is3dAvailable) {
carousel[0].style[transformProperty] = 'translate(' + move + 'px, 0)';
} else {
carousel[0].style[transformProperty] = 'translate3d(' + move + 'px, 0, 0)';
}
}
function autoScroll() {
// scroll smoothly to "destination" until we reach it
// using requestAnimationFrame
var elapsed, delta;
if (amplitude) {
elapsed = Date.now() - timestamp;
delta = amplitude * Math.exp(-elapsed / timeConstant);
if (delta > rubberTreshold || delta < -rubberTreshold) {
scroll(destination - delta);
/* We are using raf.js, a requestAnimationFrame polyfill, so
this will work on IE9 */
requestAnimationFrame(autoScroll);
} else {
goToSlide(destination / containerWidth);
}
}
}
function capIndex(idx) {
// ensure given index it inside bounds
return (idx >= slidesCount) ? slidesCount: (idx <= 0) ? 0 : idx;
}
function updateBufferIndex() {
// update and cap te buffer index
var bufferIndex = 0;
var bufferEdgeSize = (scope.carouselBufferSize - 1) / 2;
if (isBuffered) {
if (scope.carouselIndex <= bufferEdgeSize) {
bufferIndex = 0;
} else if (slidesCount < scope.carouselBufferSize) {
bufferIndex = 0;
} else if (scope.carouselIndex > slidesCount - scope.carouselBufferSize) {
bufferIndex = slidesCount - scope.carouselBufferSize;
} else {
bufferIndex = scope.carouselIndex - bufferEdgeSize;
}
}
scope.carouselBufferIndex = bufferIndex;
}
function goToSlide(i, animate) {
if (isNaN(i)) {
i = scope.carouselIndex;
}
if (animate) {
// simulate a swipe so we have the standard animation
// used when external binding index is updated or touch canceed
offset = (i * containerWidth);
swipeEnd(null, null, true);
return;
}
scope.carouselIndex = capIndex(i);
updateBufferIndex();
// if outside of angular scope, trigger angular digest cycle
// use local digest only for perfs if no index bound
if ($rootScope.$$phase!=='$apply' && $rootScope.$$phase!=='$digest') {
if (isIndexBound) {
scope.$apply();
} else {
scope.$digest();
}
}
scroll();
}
function getAbsMoveTreshold() {
// return min pixels required to move a slide
return moveTreshold * containerWidth;
}
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 capPosition(x) {
// limit position if start or end of slides
var position = x;
if (scope.carouselIndex===0) {
position = Math.max(-getAbsMoveTreshold(), position);
} else if (scope.carouselIndex===slidesCount-1) {
position = Math.min(((slidesCount-1)*containerWidth + getAbsMoveTreshold()), position);
}
return position;
}
function swipeStart(coords, event) {
//console.log('swipeStart', coords, event);
$document.bind('mouseup', documentMouseUpEvent);
pressed = true;
startX = coords.x;
amplitude = 0;
timestamp = Date.now();
return false;
}
function swipeMove(coords, event) {
//console.log('swipeMove', coords, event);
var x, delta;
if (pressed) {
x = coords.x;
delta = startX - x;
if (delta > 2 || delta < -2) {
swipeMoved = true;
startX = x;
/* We are using raf.js, a requestAnimationFrame polyfill, so
this will work on IE9 */
requestAnimationFrame(function() {
scroll(capPosition(offset + delta));
});
}
}
return false;
}
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
if(event && !swipeMoved) {
return;
}
$document.unbind('mouseup', documentMouseUpEvent);
pressed = false;
swipeMoved = false;
destination = offset;
var minMove = getAbsMoveTreshold(),
currentOffset = (scope.carouselIndex * containerWidth),
absMove = currentOffset - destination,
slidesMove = -Math[absMove>=0?'ceil':'floor'](absMove / containerWidth),
shouldMove = Math.abs(absMove) > minMove;
if ((slidesMove + scope.carouselIndex) >= slidesCount ) {
slidesMove = slidesCount - 1 - scope.carouselIndex;
}
if ((slidesMove + scope.carouselIndex) < 0) {
slidesMove = -scope.carouselIndex;
}
var moveOffset = shouldMove?slidesMove:0;
destination = (moveOffset + scope.carouselIndex) * containerWidth;
amplitude = destination - offset;
timestamp = Date.now();
if (forceAnimation) {
amplitude = offset - currentOffset;
}
/* We are using raf.js, a requestAnimationFrame polyfill, so
this will work on IE9 */
requestAnimationFrame(autoScroll);
return false;
}
iAttributes.$observe('rnCarouselSwipe', function(newValue, oldValue) {
// only bind swipe when it's not switched off
if(newValue !== 'false' && newValue !== 'off') {
$swipe.bind(carousel, {
start: swipeStart,
move: swipeMove,
end: swipeEnd,
cancel: function(event) {
swipeEnd({}, event);
}
});
} else {
// unbind swipe when it's switched off
carousel.unbind();
}
});
// initialise first slide only if no binding
// if so, the binding will trigger the first init
if (!isIndexBound) {
goToSlide(scope.carouselIndex);
}
// detect supported CSS property
transformProperty = 'transform';
['webkit', 'Moz', 'O', 'ms'].every(function (prefix) {
var e = prefix + 'Transform';
if (typeof document.body.style[e] !== 'undefined') {
transformProperty = e;
return false;
}
return true;
});
//Detect support of translate3d
function detect3dSupport(){
var el = document.createElement('p'),
has3d,
transforms = {
'webkitTransform':'-webkit-transform',
'msTransform':'-ms-transform',
'transform':'transform'
};
// Add it to the body to get the computed style
document.body.insertBefore(el, null);
for(var t in transforms){
if( el.style[t] !== undefined ){
el.style[t] = 'translate3d(1px,1px,1px)';
has3d = window.getComputedStyle(el).getPropertyValue(transforms[t]);
}
}
document.body.removeChild(el);
return (has3d !== undefined && has3d.length > 0 && has3d !== "none");
}
var is3dAvailable = detect3dSupport();
function onOrientationChange() {
updateContainerWidth();
goToSlide();
}
// handle orientation change
var winEl = angular.element($window);
winEl.bind('orientationchange', onOrientationChange);
winEl.bind('resize', onOrientationChange);
scope.$on('$destroy', function() {
$document.unbind('mouseup', documentMouseUpEvent);
winEl.unbind('orientationchange', onOrientationChange);
winEl.unbind('resize', onOrientationChange);
});
};
}
};
}]);
})();
(function() {
"use strict";
angular.module('angular-carousel')
.filter('carouselSlice', function() {
return function(collection, start, size) {
if (angular.isArray(collection)) {
return collection.slice(start, start + size);
} else if (angular.isObject(collection)) {
// dont try to slice collections :)
return collection;
}
};
});
})();