forked from alcoceba/ngCarouselDirective
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnativescript-ng2-carousel.ts
484 lines (427 loc) · 14.7 KB
/
nativescript-ng2-carousel.ts
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
import {Directive, ElementRef, AfterViewInit, Input} from '@angular/core';
import {AnimationCurve} from "tns-core-modules/ui/enums";
import {Image} from "tns-core-modules/ui/image";
import {StackLayout} from "tns-core-modules/ui/layouts/stack-layout";
import {GridLayout, ItemSpec} from "tns-core-modules/ui/layouts/grid-layout";
import {GridUnitType} from "tns-core-modules/ui/layouts/grid-layout";
import {HorizontalAlignment} from "tns-core-modules/ui/enums";
import {Label} from "tns-core-modules/ui/label";
import {GestureTypes} from "tns-core-modules/ui/gestures";
import {View} from "tns-core-modules/ui/core/view";
import {Visibility} from "tns-core-modules/ui/enums";
import {fromFile} from "tns-core-modules/image-source";
import {fromResource} from "tns-core-modules/image-source";
@Directive({
selector: '[carousel]'
})
export class CarouselDirective implements AfterViewInit {
private static animationSpeedDefault: number = 400; // in ms
private static autoPlaySpeedDefault: number = 0; // in ms
private container: GridLayout;
private carouselSlides: GridLayout;
private totalItems: number = 0;
private autoPlayIntervalId: number;
private autoPlayTimeoutId: number;
private arrowType: number = CarouselArrowTypes.NORMAL;
// Private control attributes
private direction: CarouselDirections = null;
private currentImage: number = 0;
private movingImages: boolean = false;
private indexMoveLeft: number = null;
private indexMoveRight: number = null;
private indexMoveCenter: number = null;
// Options
@Input() carousel: any;
@Input() carouselSpeed: number; // autoplay speed (ms)
@Input() carouselArrows: string; // arrows type
@Input() carouselLabelOverlay: boolean; // title over image (bool)
@Input() carouselAnimationSpeed: number; // animation speed
constructor(private elem: ElementRef) {
this.container = elem.nativeElement;
}
ngAfterViewInit() {
this.initOptions();
this.initContainer();
this.initImagesLayout();
this.initSlides();
this.initControls();
this.initAutoPlay();
}
/**
* Get and set options from directive
*/
private initOptions() {
// Animation duration (in ms)
if (this.carouselAnimationSpeed && CarouselDirective.isNumeric(this.carouselAnimationSpeed)) {
this.carouselAnimationSpeed = +this.carouselAnimationSpeed;
}
else {
this.carouselAnimationSpeed = CarouselDirective.animationSpeedDefault;
}
// Autoplay (in ms) + animation duration
if (this.carouselSpeed && CarouselDirective.isNumeric(this.carouselSpeed)) {
this.carouselSpeed = +(this.carouselSpeed);
}
else {
this.carouselSpeed = CarouselDirective.autoPlaySpeedDefault;
}
// Set arrow type
if (this.carouselArrows) {
switch (this.carouselArrows) {
case 'none':
this.arrowType = CarouselArrowTypes.NONE;
break;
case 'small':
this.arrowType = CarouselArrowTypes.SMALL;
break;
case 'normal':
this.arrowType = CarouselArrowTypes.NORMAL;
break;
case 'bold':
this.arrowType = CarouselArrowTypes.BOLD;
break;
case 'narrow':
this.arrowType = CarouselArrowTypes.NARROW;
break;
}
}
}
/**
* Init carousel layout
*/
private initContainer() {
this.container.horizontalAlignment = "center";
this.container.addRow(new ItemSpec(1, "auto"));
this.container.addColumn(new ItemSpec(1, "star"));
this.container.addColumn(new ItemSpec(1, "star"));
}
/**
* Init sliders layout
*/
private initImagesLayout() {
this.totalItems = this.carousel.length;
this.carouselSlides = new GridLayout();
GridLayout.setColumnSpan(this.carouselSlides, 2);
this.container.addChild(this.carouselSlides);
}
/**
* Init carousel sliders provided in "carousel" directive attribute
*/
private initSlides() {
this.carousel.forEach((slide: CarouselSlide, i: number) => {
let gridLayout = new GridLayout();
gridLayout.addRow(new ItemSpec(1, "auto"));
gridLayout.visibility = i == 0 ? "visible" : "collapse";
if (slide.url) {
let image: Image = CarouselDirective.generateImageSliderFromUrl(slide.url);
gridLayout.addChild(image);
}
if (slide.file && slide.file.indexOf('res://') !== 0) {
let image: Image = CarouselDirective.generateImageSliderFromFile(slide.file);
gridLayout.addChild(image);
}
if (slide.file && slide.file.indexOf('res://') === 0) {
let image: Image = CarouselDirective.generateImageSliderFromResource(slide.file);
gridLayout.addChild(image);
}
if (slide.title) {
let title: Label = CarouselDirective.generateTitleSlider(slide.title);
if (this.carouselLabelOverlay) {
gridLayout.addRow(new ItemSpec(1, "auto"));
GridLayout.setRow(title, 1);
}
gridLayout.addChild(title);
}
this.carouselSlides.addChild(gridLayout);
});
}
/**
* Load images from URL
* @param src
* @returns {Image}
*/
private static generateImageSliderFromUrl(src: string): Image {
let image: Image = new Image();
image.src = src;
image.className = "slider-image";
return image;
}
/**
* Load images from file
* @param path
* @returns {Image}
*/
private static generateImageSliderFromFile(path: string): Image {
let image: Image = new Image();
image.imageSource = fromFile(path);
image.className = "slider-image";
return image;
}
/**
* Load images from file
* @param path
* @returns {Image}
*/
private static generateImageSliderFromResource(path: string): Image {
let image: Image = new Image();
let pathRaw: string = path.replace('res://', '');
image.imageSource = fromResource(pathRaw);
image.className = "slider-image";
return image;
}
/**
* Generate title slider element
* @param title
* @returns {Label}
*/
private static generateTitleSlider(title: string): Label {
let label = new Label();
label.text = title;
label.textWrap = true;
label.className = 'slider-title';
return label;
}
/**
* Init carousel controls
*/
private initControls() {
if (this.totalItems > 1) {
// Get Arrow type
let arrowType = this.getArrowType();
// Left arrow label
let lLabel = new Label();
lLabel.text = String.fromCharCode(parseInt(arrowType.l, 16));
// Left arrow layout
let lStackLayout = new StackLayout();
lStackLayout.addChild(lLabel);
lStackLayout.horizontalAlignment = "left";
lStackLayout.on(GestureTypes.tap, () => {
this.stopStartAutoplay();
this.swipe(CarouselDirections.DIRECTION_LEFT);
});
lStackLayout.className = 'arrow arrow-left';
GridLayout.setColumn(lStackLayout, 0);
this.container.addChild(lStackLayout);
// Right arrow label
let rLabel = new Label();
rLabel.text = String.fromCharCode(parseInt(arrowType.r, 16));
// Left arrow layout
let rStackLayout = new StackLayout();
rStackLayout.addChild(rLabel);
rStackLayout.horizontalAlignment = "right";
rStackLayout.on(GestureTypes.tap, () => {
this.stopStartAutoplay();
this.swipe(CarouselDirections.DIRECTION_RIGHT);
});
rStackLayout.className = 'arrow arrow-right';
GridLayout.setColumn(rStackLayout, 1);
this.container.addChild(rStackLayout);
}
}
/**
* Init caroussel autoplay
*/
private initAutoPlay() {
if (this.carouselSpeed && CarouselDirective.isNumeric(this.carouselSpeed)) {
clearInterval(this.autoPlayIntervalId);
this.autoPlayIntervalId = setInterval(() => {
this.swipe(CarouselDirections.DIRECTION_RIGHT);
}, this.carouselSpeed + this.carouselAnimationSpeed);
}
}
/**
* Stop on gesture detected, resume after 4 seconds
*/
private stopStartAutoplay() {
if (this.autoPlayIntervalId) {
clearTimeout(this.autoPlayTimeoutId);
clearInterval(this.autoPlayIntervalId);
this.autoPlayTimeoutId = setTimeout(() => {
this.swipe(CarouselDirections.DIRECTION_RIGHT);
this.initAutoPlay();
}, 4000)
}
}
/**
* Animate right to left or left to right
* @param direction
* @returns {boolean}
*/
private swipe(direction: CarouselDirections) {
// Do nothing, hay solo una imagen...
if (this.totalItems < 2 || this.movingImages) {
return false;
}
// Animate slides
this.direction = direction;
this.movingImages = true;
this.setDirectionValues();
this.animateSlides();
// Reset all after animation
setTimeout(() => this.resetAnimationValues(), this.carouselAnimationSpeed);
}
/**
* Animate slides
*/
private animateSlides() {
for (let i = 0; i < this.carouselSlides.getChildrenCount(); i++) {
// Get view
let view: View = this.carouselSlides.getChildAt(i);
// Get element width + image visibility
let elementWidth = this.elem.nativeElement.getActualSize().width;
view.visibility = [this.indexMoveCenter, this.indexMoveLeft, this.indexMoveRight].indexOf(i) > -1 ? "visible" : "collapse";
// Perfrom animation
this.checkCL(view, i, elementWidth);
this.checkCR(view, i, elementWidth);
this.checkRC(view, i, elementWidth);
this.checkLC(view, i, elementWidth);
}
}
/**
* Move image center -> left
* @param view
* @param index
* @param elementWidth
*/
private checkCL(view: View, index: number, elementWidth: number) {
if (this.indexMoveLeft == index) {
view.translateX = 0;
view.animate({
translate: {x: elementWidth, y: 0},
duration: this.carouselAnimationSpeed,
curve: AnimationCurve.easeIn
});
}
}
/**
* Move image right -> center
* @param view
* @param index
* @param elementWidth
*/
private checkRC(view: View, index: number, elementWidth: number) {
if (this.indexMoveCenter == index && this.direction == CarouselDirections.DIRECTION_LEFT) {
view.translateX = -elementWidth;
view.animate({
translate: {x: 0, y: 0},
duration: this.carouselAnimationSpeed,
curve: AnimationCurve.easeOut
});
}
}
/**
* Move image center -> right
* @param view
* @param index
* @param elementWidth
*/
private checkCR(view: View, index: number, elementWidth: number) {
if (this.indexMoveRight == index) {
view.translateX = 0;
view.animate({
translate: {x: -elementWidth, y: 0},
duration: this.carouselAnimationSpeed,
curve: AnimationCurve.easeIn
});
}
}
/**
* Move image left -> center
* @param view
* @param index
* @param elementWidth
*/
private checkLC(view: View, index: number, elementWidth: number) {
if (this.indexMoveCenter == index && this.direction == CarouselDirections.DIRECTION_RIGHT) {
view.translateX = elementWidth;
view.animate({
translate: {x: 0, y: 0},
duration: this.carouselAnimationSpeed,
curve: AnimationCurve.easeOut
});
}
}
/**
* Set values to perform the animation
*/
private setDirectionValues() {
switch (this.direction) {
// right to left
case CarouselDirections.DIRECTION_LEFT:
this.indexMoveLeft = this.currentImage;
this.currentImage = ((this.currentImage == 0 ? this.totalItems : this.currentImage) - 1) % this.totalItems;
this.indexMoveCenter = this.currentImage;
break;
// left to right
case CarouselDirections.DIRECTION_RIGHT:
this.indexMoveRight = this.currentImage;
this.currentImage = (this.currentImage + 1) % this.totalItems;
this.indexMoveCenter = this.currentImage;
break;
}
}
/**
* Reset values after animation
*/
private resetAnimationValues() {
this.indexMoveLeft = null;
this.indexMoveRight = null;
this.indexMoveCenter = null;
this.movingImages = false;
}
/**
* Get arrow type to be displayed in frontend
* @returns {{l: string, r: string}}
*/
private getArrowType() {
let ret = {l: '', r: ''};
switch (this.arrowType) {
case CarouselArrowTypes.NONE:
ret.l = '';
ret.r = '';
break;
case CarouselArrowTypes.SMALL:
ret.l = '2039';
ret.r = '203A';
break;
default:
case CarouselArrowTypes.NORMAL:
ret.l = '276E';
ret.r = '276F';
break;
case CarouselArrowTypes.BOLD:
ret.l = '2770';
ret.r = '2771';
break;
case CarouselArrowTypes.NARROW:
ret.l = '2329';
ret.r = '232A';
break;
}
return ret;
}
/**
* Check if numeric value
* @param value
* @returns {boolean}
*/
private static isNumeric(value: any) {
return !isNaN(value - parseFloat(value));
}
}
enum CarouselArrowTypes {
NONE,
SMALL,
NARROW,
NORMAL,
BOLD
}
enum CarouselDirections {
DIRECTION_LEFT,
DIRECTION_RIGHT
}
export class CarouselSlide {
url?: string;
file?: string;
title?: string;
}