forked from syncfusion/ej2-javascript-ui-controls
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcarousel.ts
1626 lines (1526 loc) · 68 KB
/
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
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
/* eslint-disable @typescript-eslint/no-explicit-any */
import { Component, EventHandler, Collection, Property, Event, EmitType, formatUnit, INotifyPropertyChanged, NotifyPropertyChanges, Browser } from '@syncfusion/ej2-base';
import { ChildProperty, addClass, removeClass, setStyleAttribute, attributes, getUniqueID, compile, getInstance, L10n } from '@syncfusion/ej2-base';
import { append, closest, isNullOrUndefined, remove, classList, Touch, SwipeEventArgs, KeyboardEvents, KeyboardEventArgs, BaseEventArgs } from '@syncfusion/ej2-base';
import { Button } from '@syncfusion/ej2-buttons';
import { CarouselModel, CarouselItemModel } from './carousel-model';
// Constant variables
const CLS_CAROUSEL: string = 'e-carousel';
const CLS_ACTIVE: string = 'e-active';
const CLS_RTL: string = 'e-rtl';
const CLS_PARTIAL: string = 'e-partial';
const CLS_SWIPE: string = 'e-swipe';
const CLS_SLIDE_CONTAINER: string = 'e-carousel-slide-container';
const CLS_ITEMS: string = 'e-carousel-items';
const CLS_CLONED: string = 'e-cloned';
const CLS_ITEM: string = 'e-carousel-item';
const CLS_PREVIOUS: string = 'e-previous';
const CLS_NEXT: string = 'e-next';
const CLS_PREV_ICON: string = 'e-previous-icon';
const CLS_NEXT_ICON: string = 'e-next-icon';
const CLS_NAVIGATORS: string = 'e-carousel-navigators';
const CLS_INDICATORS: string = 'e-carousel-indicators';
const CLS_INDICATOR_BARS: string = 'e-indicator-bars';
const CLS_INDICATOR_BAR: string = 'e-indicator-bar';
const CLS_INDICATOR: string = 'e-indicator';
const CLS_ICON: string = 'e-icons';
const CLS_PLAY_PAUSE: string = 'e-play-pause';
const CLS_PLAY_ICON: string = 'e-play-icon';
const CLS_PAUSE_ICON: string = 'e-pause-icon';
const CLS_PREV_BUTTON: string = 'e-previous-button';
const CLS_NEXT_BUTTON: string = 'e-next-button';
const CLS_PLAY_BUTTON: string = 'e-play-button';
const CLS_FLAT: string = 'e-flat';
const CLS_ROUND: string = 'e-round';
const CLS_HOVER_ARROWS: string = 'e-hover-arrows';
const CLS_HOVER: string = 'e-carousel-hover';
const CLS_TEMPLATE: string = 'e-template';
const CLS_SLIDE_ANIMATION: string = 'e-carousel-slide-animation';
const CLS_FADE_ANIMATION: string = 'e-carousel-fade-animation';
const CLS_CUSTOM_ANIMATION: string = 'e-carousel-custom-animation';
const CLS_ANIMATION_NONE: string = 'e-carousel-animation-none';
const CLS_PREV_SLIDE: string = 'e-prev';
const CLS_NEXT_SLIDE: string = 'e-next';
const CLS_TRANSITION_START: string = 'e-transition-start';
const CLS_TRANSITION_END: string = 'e-transition-end';
/**
* Specifies the direction of previous/next button navigations in carousel.
* ```props
* Previous :- To determine the previous direction of carousel item transition.
* Next :- To determine the next direction of carousel item transition.
* ```
*/
export type CarouselSlideDirection = 'Previous' | 'Next';
/**
* Specifies the state of navigation buttons displayed in carousel.
* ```props
* Hidden :- Navigation buttons are hidden.
* Visible :- Navigation buttons are visible.
* VisibleOnHover :- Navigation buttons are visible only when we hover the carousel.
* ```
*/
export type CarouselButtonVisibility = 'Hidden' | 'Visible' | 'VisibleOnHover';
/**
* Specifies the animation effects of carousel slide.
* ```props
* None :- The carousel item transition happens without animation.
* Slide :- The carousel item transition happens with slide animation.
* Fade :- The Carousel item transition happens with fade animation.
* Custom :- The Carousel item transition happens with custom animation.
* ```
*/
export type CarouselAnimationEffect = 'None' | 'Slide' | 'Fade' | 'Custom';
/**
* Specifies the type of indicators.
* ```props
* Default: - Displays the indicators with a bullet design.
* Dynamic: - Applies a dynamic animation design to the indicators.
* Fraction: - Displays the slides numerically as indicators.
* Progress: - Represents the slides using a progress bar design.
* ```
*/
export type CarouselIndicatorsType = 'Default' | 'Dynamic' | 'Fraction' | 'Progress';
/**
* Specifies the action (touch & mouse) which enables the slide swiping action in carousel.
* * Touch - Enables or disables the swiping action in touch interaction.
* * Mouse - Enables or disables the swiping action in mouse interaction.
*
* @aspNumberEnum
*/
export enum CarouselSwipeMode {
/** Enables or disables the swiping action in touch interaction. */
Touch = 1 << 0,
/** Enables or disables the swiping action in mouse interaction. */
Mouse = 1 << 1
}
/** An interface that holds details when changing the slide. */
export interface SlideChangingEventArgs extends BaseEventArgs {
/** Specifies the index of current slide. */
currentIndex: number;
/** Specifies the element of current slide. */
currentSlide: HTMLElement;
/** Specifies the index of slide to be changed. */
nextIndex: number;
/** Specifies the element of slide to be changed. */
nextSlide: HTMLElement;
/** Specifies whether the slide transition occur through swiping or not. */
isSwiped: boolean;
/** Specifies the slide direction in which transition occurs. */
slideDirection: CarouselSlideDirection;
/** Specifies whether the slide transition should occur or not. */
cancel: boolean;
}
/** An interface that holds details once slide change done. */
export interface SlideChangedEventArgs extends BaseEventArgs {
/** Specifies the index of current slide. */
currentIndex: number;
/** Specifies the element of current slide. */
currentSlide: HTMLElement;
/** Specifies the index of slide from which it changed. */
previousIndex: number;
/** Specifies the element of slide from which it changed. */
previousSlide: HTMLElement;
/** Specifies whether the slide transition done through swiping or not. */
isSwiped: boolean;
/** Specifies the slide direction in which transition occurred. */
slideDirection: CarouselSlideDirection;
}
/** Specifies the carousel individual item. */
export class CarouselItem extends ChildProperty<CarouselItem> {
/**
* Accepts single/multiple classes (separated by a space) to be used for individual carousel item customization.
*
* @default null
*/
@Property()
public cssClass: string;
/**
* Accepts the interval duration in milliseconds for individual carousel item transition.
*
* @default null
*/
@Property()
public interval: number;
/**
* Accepts the template for individual carousel item.
*
* @default null
* @angularType string | object
* @reactType string | function | JSX.Element
* @vueType string | function
* @aspType string
*/
@Property()
public template: string | Function;
/**
* Accepts HTML attributes/custom attributes to add in individual carousel item.
*
* @default null
*/
@Property()
public htmlAttributes: Record<string, string>;
}
@NotifyPropertyChanges
export class Carousel extends Component<HTMLElement> implements INotifyPropertyChanged {
private autoSlideInterval: any;
private slideItems: any[];
private touchModule: Touch;
private keyModule: KeyboardEvents;
private keyConfigs: Record<string, string>;
private slideChangedEventArgs: SlideChangedEventArgs;
private localeObj: L10n;
private prevPageX: number;
private initialTranslate: number;
private itemsContainer: HTMLElement;
private isSwipe: boolean = false;
private timeStampStart: number;
/**
* Allows defining the collection of carousel item to be displayed on the Carousel.
*
* @default []
*/
@Collection<CarouselItemModel>([], CarouselItem)
public items: CarouselItemModel[];
/**
* Specifies the type of animation effects. The possible values for this property as follows
* * `None`: The carousel item transition happens without animation.
* * `Slide`: The carousel item transition happens with slide animation.
* * `Fade`: The Carousel item transition happens with fade animation.
* * `Custom`: The Carousel item transition happens with custom animation.
*
* @default 'Slide'
*/
@Property('Slide')
public animationEffect: CarouselAnimationEffect;
/**
* Accepts the template for previous navigation button.
*
* @default null
* @angularType string | object
* @reactType string | function | JSX.Element
* @vueType string | function
* @aspType string
*/
@Property()
public previousButtonTemplate: string | Function;
/**
* Accepts the template for next navigation button.
*
* @default null
* @angularType string | object
* @reactType string | function | JSX.Element
* @vueType string | function
* @aspType string
*/
@Property()
public nextButtonTemplate: string | Function;
/**
* Accepts the template for indicator buttons.
*
* @default null
* @angularType string | object
* @reactType string | function | JSX.Element
* @vueType string | function
* @aspType string
*/
@Property()
public indicatorsTemplate: string | Function;
/**
* Accepts the template for play/pause button.
*
* @default null
* @angularType string | object
* @reactType string | function | JSX.Element
* @vueType string | function
* @aspType string
*/
@Property()
public playButtonTemplate: string | Function;
/**
* Accepts single/multiple classes (separated by a space) to be used for carousel customization.
*
* @default null
*/
@Property()
public cssClass: string;
/**
* Specifies the datasource for the carousel items.
*
* @isdatamanager false
* @default []
*/
@Property([])
public dataSource: Record<string, any>[];
/**
* Specifies the template option for carousel items.
*
* @default null
* @angularType string | object
* @reactType string | function | JSX.Element
* @vueType string | function
* @aspType string
*/
@Property()
public itemTemplate: string | Function;
/**
* Specifies index of the current carousel item.
*
* @default 0
*/
@Property(0)
public selectedIndex: number;
/**
* Specifies the width of the Carousel in pixels/number/percentage. The number value is considered as pixels.
*
* @default '100%'
*/
@Property('100%')
public width: string | number;
/**
* Specifies the height of the Carousel in pixels/number/percentage. The number value is considered as pixels.
*
* @default '100%'
*/
@Property('100%')
public height: string | number;
/**
* Specifies the interval duration in milliseconds for carousel item transition.
*
* @default 5000
*/
@Property(5000)
public interval: number;
/**
* Defines whether the slide transition is automatic or manual.
*
* @default true
*/
@Property(true)
public autoPlay: boolean;
/**
* Defines whether the slide transition gets pause on hover or not.
*
* @default true
*/
@Property(true)
public pauseOnHover: boolean;
/**
* Defines whether the slide transitions loop end or not. When set to false, the transition stops at last slide.
*
* @default true
*/
@Property(true)
public loop: boolean;
/**
* Defines whether to show play button or not.
*
* @default false
*/
@Property(false)
public showPlayButton: boolean;
/**
* Defines whether to enable swipe action in touch devices or not.
*
* @default true
*/
@Property(true)
public enableTouchSwipe: boolean;
/**
* Defines whether to enable keyboard actions or not.
*
* * @remarks
* If any form input component is placed on the carousel slide, interacting with it may cause
* the left/right arrow keys to navigate to other slides. Disabling keyboard interaction helps
* prevent this unintended navigation, leading to a smoother user experience.
*
* @default true
*/
@Property(true)
public allowKeyboardInteraction: boolean;
/**
* Defines whether to show the indicator positions or not. The indicator positions allow to know the current slide position of the carousel component.
*
* @default true
*/
@Property(true)
public showIndicators: boolean;
/**
* Specifies the type of indicators. The available values for this property are:
*
* * `Default`: Displays the indicators with a bullet design.
* * `Dynamic`: Applies a dynamic animation design to the indicators.
* * `Fraction`: Displays the slides numerically as indicators.
* * `Progress`: Represents the slides using a progress bar design.
*
* @default 'Default'
*/
@Property('Default')
public indicatorsType: CarouselIndicatorsType;
/**
* Defines how to show the previous, next and play pause buttons visibility. The possible values for this property as follows
* * `Hidden`: Navigation buttons are hidden.
* * `Visible`: Navigation buttons are visible.
* * `VisibleOnHover`: Navigation buttons are visible only when we hover the carousel.
*
* @default 'Visible'
*/
@Property('Visible')
public buttonsVisibility: CarouselButtonVisibility;
/**
* Enables active slide with partial previous/next slides.
*
* Slide animation only applicable if the partialVisible is enabled.
*
* @default false
*/
@Property(false)
public partialVisible: boolean;
/**
* Specifies whether the slide transition should occur while performing swiping via touch/mouse.
* The slide swiping is enabled or disabled using bitwise operators. The swiping is disabled using ‘~’ bitwise operator.
* * Touch - Enables or disables the swiping action in touch interaction.
* * Mouse - Enables or disables the swiping action in mouse interaction.
*
* @default 'Touch'
* @aspNumberEnum
*/
@Property(CarouselSwipeMode.Touch)
public swipeMode: CarouselSwipeMode;
/**
* Accepts HTML attributes/custom attributes to add in individual carousel item.
*
* @default null
*/
@Property()
public htmlAttributes: Record<string, string>;
/**
* The event will be fired before the slide change.
*
* @event slideChanging
*/
@Event()
public slideChanging: EmitType<SlideChangingEventArgs>;
/**
* The event will be fired after the slide changed.
*
* @event slideChanged
*/
@Event()
public slideChanged: EmitType<SlideChangedEventArgs>;
/**
* Constructor for creating the Carousel widget
*
* @param {CarouselModel} options Accepts the carousel model properties to initiate the rendering
* @param {string | HTMLElement} element Accepts the DOM element reference
*/
constructor(options?: CarouselModel, element?: string | HTMLElement) {
super(options, <HTMLElement | string>element);
}
protected getModuleName(): string {
return CLS_CAROUSEL.replace('e-', '');
}
protected getPersistData(): string {
return this.addOnPersist(['selectedIndex']);
}
protected preRender(): void {
this.keyConfigs = {
home: 'home',
end: 'end',
space: 'space',
moveLeft: 'leftarrow',
moveRight: 'rightarrow',
moveUp: 'uparrow',
moveDown: 'downarrow'
};
const defaultLocale: Record<string, any> = {
nextSlide: 'Next slide',
of: 'of',
pauseSlideTransition: 'Pause slide transition',
playSlideTransition: 'Play slide transition',
previousSlide: 'Previous slide',
slide: 'Slide',
slideShow: 'Slide show'
};
this.localeObj = new L10n(this.getModuleName(), defaultLocale, this.locale);
}
protected render(): void {
this.initialize();
this.renderSlides();
this.renderNavigators();
this.renderPlayButton();
this.renderIndicators();
this.applyAnimation();
this.wireEvents();
}
public onPropertyChanged(newProp: CarouselModel, oldProp: CarouselModel): void {
let target: Element;
let rtlElement: Element[];
for (const prop of Object.keys(newProp)) {
switch (prop) {
case 'animationEffect':
this.applyAnimation();
break;
case 'cssClass':
classList(this.element, [newProp.cssClass], [oldProp.cssClass]);
break;
case 'selectedIndex':
this.setActiveSlide(this.selectedIndex, oldProp.selectedIndex > this.selectedIndex ? 'Previous' : 'Next');
this.autoSlide();
break;
case 'htmlAttributes':
if (!isNullOrUndefined(this.htmlAttributes)) {
this.setHtmlAttributes(this.htmlAttributes, this.element);
}
break;
case 'enableTouchSwipe':
if (!this.enableTouchSwipe && this.touchModule) {
this.touchModule.destroy();
}
if (this.element.querySelector(`.${CLS_ITEMS}`)) {
this.renderTouchActions();
}
break;
case 'loop':
if (this.loop && isNullOrUndefined(this.autoSlideInterval)) {
this.applySlideInterval();
}
this.handleNavigatorsActions(this.selectedIndex);
if (this.partialVisible || !(this.swipeMode === (~CarouselSwipeMode.Touch & ~CarouselSwipeMode.Mouse))) {
this.reRenderSlides();
}
break;
case 'allowKeyboardInteraction':
if (this.keyModule) {
this.keyModule.destroy();
this.keyModule = null;
}
if (newProp.allowKeyboardInteraction) {
this.renderKeyboardActions();
}
break;
case 'enableRtl':
rtlElement = [].slice.call(this.element.querySelectorAll(`.${CLS_PREV_BUTTON},
.${CLS_NEXT_BUTTON}, .${CLS_PLAY_BUTTON}`));
rtlElement.push(this.element);
if (this.enableRtl) {
addClass(rtlElement, CLS_RTL);
} else {
removeClass(rtlElement, CLS_RTL);
}
if (this.partialVisible || !(this.swipeMode === (~CarouselSwipeMode.Touch & ~CarouselSwipeMode.Mouse))) {
const cloneCount: number = this.loop ? this.getNumOfItems() : 0;
const slideWidth: number = this.itemsContainer.firstElementChild.clientWidth;
this.itemsContainer.style.transform = this.getTranslateX(slideWidth, this.selectedIndex + cloneCount);
}
break;
case 'buttonsVisibility':
target = this.element.querySelector(`.${CLS_NAVIGATORS}`);
if (target) {
switch (this.buttonsVisibility) {
case 'Hidden':
this.resetTemplates(['previousButtonTemplate', 'nextButtonTemplate']);
remove(target);
break;
case 'VisibleOnHover':
addClass([].slice.call(target.childNodes), CLS_HOVER_ARROWS);
break;
case 'Visible':
removeClass([].slice.call(target.childNodes), CLS_HOVER_ARROWS);
break;
}
} else {
this.renderNavigators();
this.renderPlayButton();
}
break;
case 'width':
setStyleAttribute(this.element, { 'width': formatUnit(this.width) });
break;
case 'height':
setStyleAttribute(this.element, { 'height': formatUnit(this.height) });
break;
case 'autoPlay':
if (this.showPlayButton && isNullOrUndefined(this.playButtonTemplate)) {
this.playButtonClickHandler(null, true);
}
this.autoSlide();
break;
case 'interval':
this.autoSlide();
break;
case 'showIndicators':
case 'indicatorsType':
target = this.element.querySelector(`.${CLS_INDICATORS}`);
if (target) {
this.resetTemplates(['indicatorsTemplate']);
remove(target);
}
this.renderIndicators();
break;
case 'showPlayButton':
target = this.element.querySelector(`.${CLS_PLAY_PAUSE}`);
if (!this.showPlayButton && target) {
remove(target);
this.resetTemplates(['playButtonTemplate']);
}
this.renderPlayButton();
break;
case 'items':
case 'dataSource': {
const selectedData: Record<string, any>[] | CarouselItem[] = prop === 'dataSource' ? this.dataSource : this.items;
if (!isNullOrUndefined(selectedData) && selectedData.length > 0 && this.selectedIndex >= selectedData.length) {
this.setActiveSlide(selectedData.length - 1, 'Previous');
this.autoSlide();
}
this.reRenderSlides();
this.reRenderIndicators();
break;
}
case 'partialVisible':
if (this.partialVisible) {
addClass([this.element], CLS_PARTIAL);
} else {
removeClass([this.element], CLS_PARTIAL);
}
this.reRenderSlides();
break;
case 'swipeMode':
EventHandler.remove(this.element, 'mousedown touchstart', this.swipeStart);
EventHandler.remove(this.element, 'mousemove touchmove', this.swiping);
EventHandler.remove(this.element, 'mouseup touchend', this.swipStop);
this.swipeModehandlers();
this.reRenderSlides();
break;
}
}
}
private reRenderSlides(): void {
const target: Element = this.element.querySelector(`.${CLS_ITEMS}`);
if (target) {
this.resetTemplates(['itemTemplate']);
remove(target);
}
this.renderSlides();
}
private reRenderIndicators(): void {
const target: Element = this.element.querySelector(`.${CLS_INDICATORS}`);
if (target) {
this.resetTemplates(['indicatorsTemplate']);
remove(target);
}
this.renderIndicators();
}
private initialize(): void {
const carouselClasses: string[] = [];
carouselClasses.push(CLS_CAROUSEL);
if (this.cssClass) {
carouselClasses.push(this.cssClass);
}
if (this.enableRtl) {
carouselClasses.push(CLS_RTL);
}
if (this.partialVisible) {
carouselClasses.push(CLS_PARTIAL);
}
if (!(this.swipeMode === (~CarouselSwipeMode.Touch & ~CarouselSwipeMode.Mouse))) {
carouselClasses.push(CLS_SWIPE);
}
addClass([this.element], carouselClasses);
setStyleAttribute(this.element, { 'width': formatUnit(this.width), 'height': formatUnit(this.height) });
attributes(this.element, { 'role': 'group', 'aria-roledescription': 'carousel', 'aria-label': this.localeObj.getConstant('slideShow') });
if (!isNullOrUndefined(this.htmlAttributes)) {
this.setHtmlAttributes(this.htmlAttributes, this.element);
}
}
private renderSlides(): void {
let slideContainer: HTMLElement = this.element.querySelector('.' + CLS_SLIDE_CONTAINER);
if (!slideContainer) {
slideContainer = this.createElement('div', { className: CLS_SLIDE_CONTAINER, attrs: { 'tabindex': '0', 'role': 'tabpanel' } });
this.element.appendChild(slideContainer);
}
this.itemsContainer = this.createElement('div', { className: CLS_ITEMS, attrs: { 'aria-live': this.autoPlay ? 'off' : 'polite' } });
slideContainer.appendChild(this.itemsContainer);
const numOfItems: number = this.getNumOfItems();
if (numOfItems > 0 && this.loop) {
if (this.items.length > 0) {
this.items.slice(-numOfItems).forEach((item: CarouselItemModel, index: number) => {
this.renderSlide(item, item.template, index, this.itemsContainer, true);
});
}
else if (!isNullOrUndefined(this.dataSource) && this.dataSource.length > 0) {
this.dataSource.slice(-numOfItems).forEach((item: Record<string, any>, index: number) => {
this.renderSlide(item, this.itemTemplate, index, this.itemsContainer, true);
});
}
}
if (this.items.length > 0) {
this.slideItems = this.items as Record<string, any>[];
this.items.forEach((item: CarouselItemModel, index: number) => {
this.renderSlide(item, item.template, index, this.itemsContainer);
});
} else if (!isNullOrUndefined(this.dataSource) && this.dataSource.length > 0) {
this.slideItems = this.dataSource;
this.dataSource.forEach((item: Record<string, any>, index: number) => {
this.renderSlide(item, this.itemTemplate, index, this.itemsContainer);
});
}
if (numOfItems > 0 && this.loop) {
if (this.items.length > 0) {
this.items.slice(0, numOfItems).forEach((item: CarouselItemModel, index: number) => {
this.renderSlide(item, item.template, index, this.itemsContainer, true);
});
}
else if (!isNullOrUndefined(this.dataSource) && this.dataSource.length > 0) {
this.dataSource.slice(0, numOfItems).forEach((item: Record<string, any>, index: number) => {
this.renderSlide(item, this.itemTemplate, index, this.itemsContainer, true);
});
}
}
this.renderTemplates();
this.itemsContainer.style.setProperty('--carousel-items-count', `${this.itemsContainer.children.length}`);
const slideWidth: number = isNullOrUndefined(this.itemsContainer.firstElementChild) ? 0 :
this.itemsContainer.firstElementChild.clientWidth;
this.itemsContainer.style.transitionProperty = 'none';
const cloneCount: number = this.loop ? numOfItems : 0;
this.itemsContainer.style.transform = this.getTranslateX(slideWidth, this.selectedIndex + cloneCount);
this.autoSlide();
this.renderTouchActions();
this.renderKeyboardActions();
}
private getTranslateX(slideWidth: number, count: number = 1): string {
return this.enableRtl ? `translateX(${(slideWidth) * (count)}px)` :
`translateX(${-(slideWidth) * (count)}px)`;
}
private renderSlide(item: Record<string, any>, itemTemplate: string | Function, index: number, container: HTMLElement,
isClone: boolean = false): void {
const itemEle: HTMLElement = this.createElement('div', {
id: getUniqueID('carousel_item'),
className: `${CLS_ITEM} ${item.cssClass ? item.cssClass : ''} ${this.selectedIndex === index && !isClone ? CLS_ACTIVE : ''}`,
attrs: {
'aria-hidden': this.selectedIndex === index && !isClone ? 'false' : 'true', 'data-index': index.toString(),
'role': 'group', 'aria-roledescription': 'slide'
}
});
if (isClone) {
itemEle.classList.add(CLS_CLONED);
}
if (!isNullOrUndefined(item.htmlAttributes)) {
this.setHtmlAttributes(item.htmlAttributes, itemEle);
}
const templateId: string = this.element.id + '_template';
const template: HTMLElement[] = this.templateParser(itemTemplate)(item, this, 'itemTemplate', templateId, false);
append(template, itemEle);
container.appendChild(itemEle);
}
private renderNavigators(): void {
if (this.buttonsVisibility === 'Hidden') {
return;
}
const navigators: HTMLElement = this.createElement('div', { className: CLS_NAVIGATORS });
const itemsContainer: HTMLElement = this.element.querySelector(`.${CLS_SLIDE_CONTAINER}`) as HTMLElement;
itemsContainer.insertAdjacentElement('afterend', navigators);
if (!isNullOrUndefined(this.slideItems) && this.slideItems.length > 1) {
this.renderNavigatorButton('Previous');
this.renderNavigatorButton('Next');
}
this.renderTemplates();
}
private renderNavigatorButton(direction: CarouselSlideDirection): void {
const buttonContainer: HTMLElement = this.createElement('div', {
className: (direction === 'Previous' ? CLS_PREVIOUS : CLS_NEXT) + ' ' + (this.buttonsVisibility === 'VisibleOnHover' ? CLS_HOVER_ARROWS : '')
});
if (direction === 'Previous' && this.previousButtonTemplate) {
addClass([buttonContainer], CLS_TEMPLATE);
const templateId: string = this.element.id + '_previousButtonTemplate';
const template: HTMLElement[] = this.templateParser(this.previousButtonTemplate)({ type: 'Previous' }, this, 'previousButtonTemplate', templateId, false);
append(template, buttonContainer);
} else if (direction === 'Next' && this.nextButtonTemplate) {
addClass([buttonContainer], CLS_TEMPLATE);
const templateId: string = this.element.id + '_nextButtonTemplate';
const template: HTMLElement[] = this.templateParser(this.nextButtonTemplate)({ type: 'Next' }, this, 'nextButtonTemplate', templateId, false);
append(template, buttonContainer);
} else {
const button: HTMLElement = this.createElement('button', {
attrs: { 'aria-label': this.localeObj.getConstant(direction === 'Previous' ? 'previousSlide' : 'nextSlide'), 'type': 'button' }
});
const buttonObj: Button = new Button({
cssClass: CLS_FLAT + ' ' + CLS_ROUND + ' ' + (direction === 'Previous' ? CLS_PREV_BUTTON : CLS_NEXT_BUTTON),
iconCss: CLS_ICON + ' ' + (direction === 'Previous' ? CLS_PREV_ICON : CLS_NEXT_ICON),
enableRtl: this.enableRtl,
disabled: !this.loop && this.selectedIndex === (direction === 'Previous' ? 0 : this.slideItems.length - 1)
});
buttonObj.appendTo(button);
buttonContainer.appendChild(button);
}
this.element.querySelector('.' + CLS_NAVIGATORS).appendChild(buttonContainer);
EventHandler.add(buttonContainer, 'click', this.navigatorClickHandler, this);
}
private renderPlayButton(): void {
if (isNullOrUndefined(this.slideItems) || this.buttonsVisibility === 'Hidden' || !this.showPlayButton || this.slideItems.length <= 1) {
return;
}
const playPauseWrap: HTMLElement = this.createElement('div', {
className: CLS_PLAY_PAUSE + ' ' + (this.buttonsVisibility === 'VisibleOnHover' ? CLS_HOVER_ARROWS : '')
});
if (this.playButtonTemplate) {
addClass([playPauseWrap], CLS_TEMPLATE);
const templateId: string = this.element.id + '_playButtonTemplate';
const template: HTMLElement[] = this.templateParser(this.playButtonTemplate)({}, this, 'playButtonTemplate', templateId, false);
append(template, playPauseWrap);
} else {
const playButton: HTMLElement = this.createElement('button', {
attrs: { 'aria-label': this.localeObj.getConstant(this.autoPlay ? 'pauseSlideTransition' : 'playSlideTransition'), 'type': 'button' }
});
const isLastSlide: boolean = this.selectedIndex === this.slideItems.length - 1 && !this.loop;
const buttonObj: Button = new Button({
cssClass: CLS_FLAT + ' ' + CLS_ROUND + ' ' + CLS_PLAY_BUTTON,
iconCss: CLS_ICON + ' ' + (this.autoPlay && !isLastSlide ? CLS_PAUSE_ICON : CLS_PLAY_ICON),
isToggle: true,
enableRtl: this.enableRtl
});
if (isLastSlide) {
this.setProperties({ autoPlay: false }, true);
playButton.setAttribute('aria-label', this.localeObj.getConstant('playSlideTransition'));
this.itemsContainer.setAttribute('aria-live', 'polite');
}
buttonObj.appendTo(playButton);
playPauseWrap.appendChild(playButton);
}
const navigators: Element = this.element.querySelector(`.${CLS_NAVIGATORS}`);
navigators.insertBefore(playPauseWrap, navigators.lastElementChild);
this.renderTemplates();
EventHandler.add(playPauseWrap, 'click', this.playButtonClickHandler, this);
}
private renderIndicators(): void {
if (!this.showIndicators || isNullOrUndefined(this.indicatorsType)) {
return;
}
let indicatorClass: string = 'e-default';
if (!this.indicatorsTemplate) {
indicatorClass = `e-${this.indicatorsType.toLowerCase()}`;
}
const indicatorWrap: HTMLElement = this.createElement('div', { className: `${CLS_INDICATORS} ${indicatorClass}` });
const indicatorBars: HTMLElement = this.createElement('div', { className: CLS_INDICATOR_BARS });
indicatorWrap.appendChild(indicatorBars);
let progress: HTMLElement;
if (this.slideItems) {
switch (this.indicatorsType) {
case 'Fraction':
if (this.indicatorsTemplate) {
this.renderIndicatorTemplate(indicatorBars, this.selectedIndex + 1);
} else {
indicatorBars.innerText = `${this.selectedIndex + 1} / ${this.slideItems.length}`;
}
break;
case 'Progress':
if (this.indicatorsTemplate) {
this.renderIndicatorTemplate(indicatorBars, this.selectedIndex + 1);
}
else {
progress = this.createElement('div', { className: CLS_INDICATOR_BAR });
progress.style.setProperty('--carousel-items-current', `${this.selectedIndex + 1}`);
progress.style.setProperty('--carousel-items-count', `${this.slideItems.length}`);
indicatorBars.appendChild(progress);
}
break;
case 'Default':
case 'Dynamic':
this.slideItems.forEach((item: Record<string, any>, index: number) => {
const indicatorBar: HTMLElement = this.createElement('div', {
className: CLS_INDICATOR_BAR + ' ' + (this.selectedIndex === index ? CLS_ACTIVE : this.selectedIndex - 1 === index ? CLS_PREV_SLIDE : this.selectedIndex + 1 === index ? CLS_NEXT_SLIDE : ''),
attrs: { 'data-index': index.toString(), 'aria-current': this.selectedIndex === index ? 'true' : 'false' }
});
indicatorBar.style.setProperty('--carousel-items-current', `${this.selectedIndex}`);
if (this.indicatorsTemplate) {
this.renderIndicatorTemplate(indicatorBar, index);
} else if (this.indicatorsType === 'Default') {
const indicator: HTMLElement = this.createElement('button', { className: CLS_INDICATOR, attrs: { 'type': 'button', 'aria-label': this.localeObj.getConstant('slide') + ' ' + (index + 1) + ' ' + this.localeObj.getConstant('of') + ' ' + this.slideItems.length } });
indicatorBar.appendChild(indicator);
indicator.appendChild(this.createElement('div', {}));
const buttonObj: Button = new Button({ cssClass: 'e-flat e-small' });
buttonObj.appendTo(indicator);
}
indicatorBars.appendChild(indicatorBar);
if (this.indicatorsType === 'Default') {
EventHandler.add(indicatorBar, 'click', this.indicatorClickHandler, this);
}
});
break;
}
}
this.element.appendChild(indicatorWrap);
}
private renderIndicatorTemplate(indicatorBar: HTMLElement, index: number = 0): void {
addClass([indicatorBar], CLS_TEMPLATE);
const templateId: string = this.element.id + '_indicatorsTemplate';
const template: HTMLElement[] = this.templateParser(this.indicatorsTemplate)({ index: index, selectedIndex: this.selectedIndex }, this, 'indicatorsTemplate', templateId, false);
append(template, indicatorBar);
}
private renderKeyboardActions(): void {
if (!this.allowKeyboardInteraction) {
return;
}
this.keyModule = new KeyboardEvents(this.element, { keyAction: this.keyHandler.bind(this), keyConfigs: this.keyConfigs });
}
private renderTouchActions(): void {
if (!this.enableTouchSwipe) {
return;
}
this.touchModule = new Touch(this.element, { swipe: this.swipeHandler.bind(this) });
}
private applyAnimation(): void {
removeClass([this.element], [CLS_CUSTOM_ANIMATION, CLS_FADE_ANIMATION, CLS_SLIDE_ANIMATION, CLS_ANIMATION_NONE]);
switch (this.animationEffect) {
case 'Slide':
addClass([this.element], CLS_SLIDE_ANIMATION);
break;
case 'Fade':
addClass([this.element], CLS_FADE_ANIMATION);
break;
case 'None':
addClass([this.element], CLS_ANIMATION_NONE);
break;
case 'Custom':
addClass([this.element], CLS_CUSTOM_ANIMATION);
break;
}
}
private autoSlide(): void {
if (isNullOrUndefined(this.slideItems) || this.slideItems.length <= 1) {
return;
}
this.resetSlideInterval();
this.applySlideInterval();
}
private autoSlideChange(): void {
const activeSlide: HTMLElement | null = this.element.querySelector(`.${CLS_ITEM}.${CLS_ACTIVE}`)
|| this.element.querySelector(`.${CLS_INDICATORS} .${CLS_ACTIVE}`) as HTMLElement;
if (isNullOrUndefined(activeSlide)) { return; }
const activeIndex: number = parseInt(activeSlide.dataset.index, 10);
if (!this.loop && activeIndex === this.slideItems.length - 1) {
this.resetSlideInterval();
} else {
const index: number = (activeIndex + 1) % this.slideItems.length;
if (!this.element.classList.contains(CLS_HOVER)) {
this.setActiveSlide(index, 'Next');
}
this.autoSlide();
}
}
private applySlideInterval(): void {
if (!this.autoPlay || this.element.classList.contains(CLS_HOVER)) {
return;
}
let itemInterval: number = this.interval;
if (this.items.length > 0 && !isNullOrUndefined(this.items[this.selectedIndex || 0].interval)) {
itemInterval = this.items[this.selectedIndex || 0].interval;
}
this.autoSlideInterval = setInterval(() => this.autoSlideChange(), itemInterval);
}
private resetSlideInterval(): void {
clearInterval(this.autoSlideInterval);
this.autoSlideInterval = null;
}
private getSlideIndex(direction: CarouselSlideDirection): number {
let currentIndex: number = this.selectedIndex || 0;
if (direction === 'Previous') {
currentIndex--;
if (currentIndex < 0) {
currentIndex = this.slideItems.length - 1;
}
} else {
currentIndex++;
if (currentIndex === this.slideItems.length) {