-
Notifications
You must be signed in to change notification settings - Fork 151
/
Carousel.js
1077 lines (964 loc) · 33.6 KB
/
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
import React, { Children } from "react";
import PropTypes from "prop-types";
import ResizeObserver from "resize-observer-polyfill";
import Only from "react-only-when";
import Track from "./Track";
import Arrow from "./Arrow";
import consts from "../consts";
import { activeIndexReducer } from "../reducers/items";
import { nextItemAction, prevItemAction } from "../actions/itemsActions";
import {
SliderContainer,
Slider,
StyledCarousel,
CarouselWrapper
} from "./styled";
import { pipe, noop, cssPrefix, numberToArray } from "../utils/helpers";
import { Pagination } from "./Pagination";
class Carousel extends React.Component {
isComponentMounted = false;
state = {
rootHeight: 0,
childHeight: 0,
sliderPosition: 0,
swipedSliderPosition: 0,
isSwiping: false,
transitioning: false,
transitionMs: this.props.transitionMs,
activeIndex: this.props.initialActiveIndex || this.props.initialFirstItem, // support deprecated initialFirstItem
pages: [],
activePage: 0,
sliderContainerWidth: 0
};
componentDidMount() {
this.isComponentMounted = true;
this.initResizeObserver();
this.updateActivePage();
this.setPages();
}
componentDidUpdate(prevProps, prevState) {
const {
enableAutoPlay,
children,
itemsToShow,
itemsToScroll,
breakPoints
} = this.props;
const { activeIndex, sliderContainerWidth } = this.state;
const nextItem = this.getNextItemIndex(activeIndex, false);
const currentChildrenLength = Children.toArray(children).length;
const prevChildrenLength = Children.toArray(prevProps.children).length;
// update pages (for pagination)
if (
prevChildrenLength !== currentChildrenLength ||
prevProps.itemsToShow !== itemsToShow ||
prevProps.itemsToScroll !== itemsToScroll ||
prevProps.breakPoints !== breakPoints ||
sliderContainerWidth !== prevState.sliderContainerWidth
) {
// we mimic a container resize to recalculate item width when itemsToShow are updated
this.onContainerResize({ contentRect: { width: sliderContainerWidth } });
this.setPages();
this.updateActivePage();
}
// autoplay update
if (activeIndex === nextItem) {
this.removeAutoPlay();
} else if (enableAutoPlay && !this.autoPlayIntervalId) {
this.setAutoPlay();
} else if (!enableAutoPlay && this.autoPlayIntervalId) {
this.removeAutoPlay();
}
if (prevChildrenLength !== currentChildrenLength) {
const {
itemsToShow: calculatedItemsToShow
} = this.getDerivedPropsFromBreakPoint();
// number of items is reduced (we don't care if number of items is increased)
// we need to check if our current index is not out of boundaries
// we need to include itemsToShow so we can fill up the slots
const lastIndex = currentChildrenLength - 1;
const isOutOfRange = activeIndex + calculatedItemsToShow > lastIndex;
if (isOutOfRange) {
// we are out of boundaries, go "back" to last item of the list (respect itemsToShow)
this.goTo(Math.max(0, currentChildrenLength - calculatedItemsToShow));
}
}
}
componentWillUnmount() {
this.isComponentMounted = false;
this.removeAutoPlay();
this.unSubscribeObserver();
}
setRef = name => ref => (this[name] = ref);
initResizeObserver = () => {
this.ro = new ResizeObserver((entries, observer) => {
for (const entry of entries) {
if (entry.target === this.sliderContainer) {
// we are using rAF because it fixes the infinite refresh with gatsby (ssr?).
// TBH, I'm not sure i fully understand why.
// see https://github.com/sag1v/react-elastic-carousel/issues/107
window.requestAnimationFrame(() => {
this.onContainerResize(entry);
});
}
if (entry.target === this.slider) {
// we are using rAF because it fixes the infinite refresh with gatsby (ssr?).
// TBH, I'm not sure i fully understand why
// see https://github.com/sag1v/react-elastic-carousel/issues/107
window.requestAnimationFrame(() => {
this.onSliderResize(entry);
});
}
}
});
this.ro.observe(this.sliderContainer);
this.ro.observe(this.slider);
};
unSubscribeObserver = () => this.ro.disconnect();
setAutoPlay = () => {
const { autoPlaySpeed } = this.getDerivedPropsFromBreakPoint();
this.autoPlayIntervalId = setInterval(() => {
if (this.isComponentMounted) {
const { transitioning } = this.state;
if (!transitioning) {
this.slideNext();
}
}
}, autoPlaySpeed);
};
removeAutoPlay = () => {
if (this.autoPlayIntervalId) {
clearInterval(this.autoPlayIntervalId);
this.autoPlayIntervalId = null;
}
};
setPages = () => {
const numOfPages = this.getNumOfPages();
const pages = numberToArray(numOfPages);
this.setState({ pages });
};
onSliderTransitionEnd = fn => {
this.slider.addEventListener("transitionend", fn);
};
removeSliderTransitionHook = fn => {
this.slider.removeEventListener("transitionend", fn);
};
getDerivedPropsFromBreakPoint = () => {
const { breakPoints, ...restOfProps } = this.props;
const { sliderContainerWidth } = this.state;
// default breakpoint from individual props
let currentBreakPoint;
// if breakpoints were added as props override the individual props
if (breakPoints && breakPoints.length > 0) {
currentBreakPoint = breakPoints
.slice() // no mutations
.reverse() // so we can find last match
.find(bp => bp.width <= sliderContainerWidth);
if (!currentBreakPoint) {
/* in case we don't have a lower width than sliderContainerWidth
* this mostly happens in initilization when sliderContainerWidth is 0
*/
currentBreakPoint = breakPoints[0];
}
}
// merge direct props with current breakpoint Props
return { ...restOfProps, ...currentBreakPoint };
};
updateSliderPosition = () => {
this.setState(state => {
const {
children,
verticalMode,
itemsToShow,
transitionMs
} = this.getDerivedPropsFromBreakPoint();
const { childHeight, activeIndex } = state;
const childWidth = this.calculateChildWidth();
const totalItems = Children.toArray(children).length;
const hiddenSlots = totalItems - itemsToShow;
let moveBy = activeIndex * -1;
const emptySlots = itemsToShow - (totalItems - activeIndex);
if (emptySlots > 0 && hiddenSlots > 0) {
moveBy = emptySlots + activeIndex * -1;
}
let sliderPosition = (verticalMode ? childHeight : childWidth) * moveBy;
const newActiveIndex =
emptySlots > 0 ? activeIndex - emptySlots : activeIndex;
// go back from 0ms to whatever set by the user
// We were at 0ms because we wanted to disable animation on resize
// see https://github.com/sag1v/react-elastic-carousel/issues/94
window.requestAnimationFrame(() => {
if (this.isComponentMounted) {
this.setState({ transitionMs });
}
});
return {
sliderPosition,
activeIndex: newActiveIndex < 0 ? 0 : newActiveIndex
};
});
};
onSliderResize = sliderNode => {
if (!this.isComponentMounted) {
return;
}
const {
verticalMode,
children,
itemsToShow
} = this.getDerivedPropsFromBreakPoint();
const { height: sliderHeight } = sliderNode.contentRect;
const nextState = {};
const childrenLength = Children.toArray(children).length;
if (verticalMode) {
const childHeight = sliderHeight / childrenLength;
// We use Math.min because we don't want to make the child smaller
// if the number of children is smaller than itemsToShow.
// (Because we do not want "empty slots")
nextState.rootHeight =
childHeight * Math.min(childrenLength, itemsToShow);
nextState.childHeight = childHeight;
} else {
nextState.rootHeight = sliderHeight;
}
this.setState(nextState);
};
calculateChildWidth = () => {
const { sliderContainerWidth } = this.state;
const {
verticalMode,
itemsToShow,
showEmptySlots,
children
} = this.getDerivedPropsFromBreakPoint();
/* based on slider container's width, get num of items to show
* and calculate child's width (and update it in state)
*/
const childrenLength = Children.toArray(children).length || 1;
let childWidth = 0;
if (verticalMode) {
childWidth = sliderContainerWidth;
} else {
// When "showEmptySlots" is false
// We use Math.min because we don't want to make the child smaller
// if the number of children is smaller than itemsToShow.
// (Because we do not want "empty slots")
childWidth =
sliderContainerWidth /
(showEmptySlots ? itemsToShow : Math.min(childrenLength, itemsToShow));
}
return childWidth;
};
onContainerResize = sliderContainerNode => {
const { width: newSliderContainerWidth } = sliderContainerNode.contentRect;
// update slider container width
// disable animation on resize see https://github.com/sag1v/react-elastic-carousel/issues/94
const {
outerSpacing,
verticalMode: initialVerticalMode
} = this.getDerivedPropsFromBreakPoint();
const containerWidth =
newSliderContainerWidth - (initialVerticalMode ? 0 : outerSpacing * 2);
if (
!this.isComponentMounted ||
this.state.sliderContainerWidth === newSliderContainerWidth
) {
// prevent infinite loop
return;
}
this.setState(
{ sliderContainerWidth: containerWidth, transitionMs: 0 },
() => {
// we must get these props inside setState (get future props because its async)
const {
onResize,
itemsToShow,
children
} = this.getDerivedPropsFromBreakPoint();
const childrenLength = Children.toArray(children).length || 1;
this.setState(
currentState => {
// We might need to change the selected index when the size of the container changes
// we are making sure the selected index is not out of boundaries and respecting itemsToShow
// This usually happens with breakpoints. see https://github.com/sag1v/react-elastic-carousel/issues/122
let activeIndex = currentState.activeIndex;
// we take the lowest, in case itemsToShow is greater than childrenLength
const maxItemsToShow = Math.min(childrenLength, itemsToShow);
const endLimit = childrenLength - maxItemsToShow;
if (activeIndex > endLimit) {
activeIndex = endLimit;
}
return { activeIndex };
},
() => {
/* Based on all of the above new data:
* update slider position
* get the new current breakpoint
* pass the current breakpoint to the consumer's callback
*/
this.updateSliderPosition();
const currentBreakPoint = this.getDerivedPropsFromBreakPoint();
onResize(currentBreakPoint);
}
);
}
);
};
tiltMovement = (position, distance = 20, duration = 150) => {
this.setState(state => {
return {
isSwiping: true,
swipedSliderPosition: position - distance
};
});
setTimeout(() => {
this.setState({
isSwiping: false,
swipedSliderPosition: 0
});
}, duration);
};
convertChildToCbObj = index => {
const { children } = this.getDerivedPropsFromBreakPoint();
// support decimal itemsToShow
const roundedIdx = Math.round(index);
const child = Children.toArray(children)[roundedIdx];
return { item: child.props, index: roundedIdx };
};
getNextItemIndex = (currentIndex, getPrev) => {
const {
children,
itemsToShow,
itemsToScroll
} = this.getDerivedPropsFromBreakPoint();
const childrenLength = Children.toArray(children).length || 1;
const notEnoughItemsToShow = itemsToShow > childrenLength;
let limit = getPrev ? 0 : childrenLength - itemsToShow;
if (notEnoughItemsToShow) {
limit = 0; // basically don't move
}
const nextAction = getPrev
? prevItemAction(0, itemsToScroll)
: nextItemAction(limit, itemsToScroll);
const nextItem = activeIndexReducer(currentIndex, nextAction);
return nextItem;
};
getNextItemObj = getPrev => {
const { children } = this.getDerivedPropsFromBreakPoint();
const { activeIndex } = this.state;
const nextItemIndex = this.getNextItemIndex(activeIndex, getPrev);
// support decimal itemsToShow
const roundedIdx = Math.round(nextItemIndex);
const asElement = Children.toArray(children)[roundedIdx];
const asObj = { item: asElement.props, index: roundedIdx };
return asObj;
};
resetSwipe = () => {
this.setState({
swipedSliderPosition: 0,
transitioning: false,
isSwiping: false
});
};
onSwiping = data => {
const { deltaX, absX, deltaY, absY, dir } = data;
this.setState(state => {
const { childHeight, activeIndex, sliderPosition } = state;
const {
itemsToShow,
verticalMode,
children,
isRTL
} = this.getDerivedPropsFromBreakPoint();
const childWidth = this.calculateChildWidth();
// determine how far can user swipe
const childrenLength = Children.toArray(children).length || 1;
const goingNext =
(!verticalMode && dir === "Left" && !isRTL) ||
(!verticalMode && dir === "Right" && isRTL) ||
(verticalMode && dir === "Up");
const goingBack =
(!verticalMode && dir === "Right" && !isRTL) ||
(!verticalMode && dir === "Left" && isRTL) ||
(verticalMode && dir === "Down");
const horizontalSwipe = dir === "Left" || dir === "Right";
const verticalSwipe = dir === "Up" || dir === "Down";
const horizontalMode = !verticalMode;
let distanceSwipe = 0;
const horizontalEdgeStoppage = childWidth / 2;
const verticalEdgeStoppage = childHeight / 2;
if (verticalMode) {
if (verticalSwipe) {
const trackSize = childrenLength * childHeight;
if (goingNext) {
distanceSwipe =
trackSize -
childHeight * activeIndex -
itemsToShow * childHeight +
verticalEdgeStoppage;
} else if (goingBack) {
distanceSwipe = childHeight * activeIndex + verticalEdgeStoppage;
}
}
} else {
if (horizontalSwipe) {
const trackSize = childrenLength * childWidth;
if (goingNext) {
distanceSwipe =
trackSize -
childWidth * activeIndex -
itemsToShow * childWidth +
horizontalEdgeStoppage;
} else if (goingBack) {
distanceSwipe = childWidth * activeIndex + horizontalEdgeStoppage;
}
}
}
const shouldHorizontalSkipUpdate =
(horizontalMode && verticalSwipe) ||
(horizontalMode && horizontalSwipe && absX > distanceSwipe);
const shouldVerticalSkipUpdate =
(verticalMode && horizontalSwipe) ||
(verticalMode && verticalSwipe && absY > distanceSwipe);
if (shouldHorizontalSkipUpdate || shouldVerticalSkipUpdate) {
// bail out of state update
return;
}
let swipedSliderPosition;
if (horizontalSwipe) {
if (isRTL) {
swipedSliderPosition = sliderPosition + deltaX;
} else {
swipedSliderPosition = sliderPosition - deltaX;
}
} else {
swipedSliderPosition = sliderPosition - deltaY;
}
return {
swipedSliderPosition,
isSwiping: true,
transitioning: true
};
});
};
onSwiped = data => {
// we need to handle all scenarios:
// 1. Horizontal mode - swipe left or right
// 2. Horizontal mode with RTL - swipe left or right
// 3. vertical mode - swipe up or down
const { absX, absY, dir } = data;
const { childHeight, activeIndex } = this.state;
const {
verticalMode,
isRTL,
itemsToScroll
} = this.getDerivedPropsFromBreakPoint();
const childWidth = this.calculateChildWidth();
let func = this.resetSwipe;
const minSwipeDistanceHorizontal = childWidth / 5;
const minSwipeDistanceVertical = childHeight / 5;
const swipedLeft = dir === "Left";
const swipedRight = dir === "Right";
const swipedUp = dir === "Up";
const swipedDown = dir === "Down";
const verticalGoSwipe =
verticalMode &&
(swipedUp || swipedDown) &&
absY > minSwipeDistanceVertical;
const horizontalGoSwipe =
!verticalMode &&
(swipedRight || swipedLeft) &&
absX > minSwipeDistanceHorizontal;
let goodToGo = false;
if (verticalGoSwipe || horizontalGoSwipe) {
goodToGo = true;
}
if (goodToGo) {
// we should go to a different item
// determine what method we need to invoke
if (verticalMode) {
// get number of slides from user's swiping
const numberOfSlidesViaSwipe = Math.ceil(
(absY - minSwipeDistanceVertical) / childHeight
);
// if user swipes more than itemsToScroll then we want to bypass itemsToScroll for a smoother scroll
const numberOfSlidesTogo = Math.max(
itemsToScroll,
numberOfSlidesViaSwipe
);
const backSlidesToGo = activeIndex - numberOfSlidesTogo;
const forwardSlideTtoGo = activeIndex + numberOfSlidesTogo;
// up or down
if (swipedDown) {
// func = this.onPrevStart;
func = () => this.goTo(backSlidesToGo);
}
if (swipedUp) {
// func = this.onNextStart;
func = () => this.goTo(forwardSlideTtoGo);
}
} else {
// get number of slides from user's swiping
const numberOfSlidesViaSwipe = Math.ceil(
(absX - minSwipeDistanceHorizontal) / childWidth
);
// if user swipes more than itemsToScroll then we want to bypass itemsToScroll for a smoother scroll
const numberOfSlidesTogo = Math.max(
itemsToScroll,
numberOfSlidesViaSwipe
);
const backSlidesToGo = activeIndex - numberOfSlidesTogo;
const forwardSlideTtoGo = activeIndex + numberOfSlidesTogo;
// horizontal mode
if (isRTL) {
// flip sides
if (swipedLeft) {
// func = this.onPrevStart;
func = () => this.goTo(backSlidesToGo);
}
if (swipedRight) {
// func = this.onNextStart;
func = () => this.goTo(forwardSlideTtoGo);
}
} else {
// normal behavior
if (swipedLeft) {
// func = this.onNextStart;
func = () => this.goTo(forwardSlideTtoGo);
}
if (swipedRight) {
// func = this.onPrevStart;
func = () => this.goTo(backSlidesToGo);
}
}
}
}
// we are not "tilting" on edges, so we need to reset isSwiping and transitioning.
// otherwise we wont slide back to edge
this.setState({ isSwiping: false, transitioning: false });
func({ skipTilt: true });
};
onNextStart = options => {
const { onNextStart } = this.getDerivedPropsFromBreakPoint();
const { activeIndex } = this.state;
const nextItemObj = this.getNextItemObj();
const prevItemObj = this.convertChildToCbObj(activeIndex);
onNextStart(prevItemObj, nextItemObj);
this.slideNext(options);
};
onPrevStart = options => {
const { onPrevStart } = this.getDerivedPropsFromBreakPoint();
const { activeIndex } = this.state;
const nextItemObj = this.getNextItemObj(true);
const prevItemObj = this.convertChildToCbObj(activeIndex);
onPrevStart(prevItemObj, nextItemObj);
this.slidePrev(options);
};
slideNext = (options = {}) => {
const { skipTilt } = options;
const { enableTilt } = this.getDerivedPropsFromBreakPoint();
const { activeIndex, sliderPosition } = this.state;
const nextItem = this.getNextItemIndex(activeIndex, false);
if (activeIndex !== nextItem) {
this.goTo(nextItem);
} else if (enableTilt && !skipTilt) {
this.tiltMovement(sliderPosition, 20, 150);
}
};
slidePrev = (options = {}) => {
const { skipTilt } = options;
const { activeIndex } = this.state;
const { enableTilt } = this.getDerivedPropsFromBreakPoint();
const prevItem = this.getNextItemIndex(activeIndex, true);
if (activeIndex !== prevItem) {
this.goTo(prevItem);
} else if (enableTilt && !skipTilt) {
this.tiltMovement(0, -20, 150);
}
};
onNextEnd = () => {
const { onNextEnd, onChange } = this.getDerivedPropsFromBreakPoint();
const { activeIndex, activePage } = this.state;
const nextItemObj = this.convertChildToCbObj(activeIndex);
this.removeSliderTransitionHook(this.onNextEnd);
this.setState({ transitioning: false });
onChange && onChange(nextItemObj, activePage);
onNextEnd(nextItemObj, activePage);
};
onPrevEnd = () => {
const { onPrevEnd, onChange } = this.getDerivedPropsFromBreakPoint();
const { activeIndex, activePage } = this.state;
const nextItemObj = this.convertChildToCbObj(activeIndex);
this.removeSliderTransitionHook(this.onPrevEnd);
this.setState({ transitioning: false });
onChange && onChange(nextItemObj, activePage);
onPrevEnd(nextItemObj, activePage);
};
generatePositionUpdater = (
direction,
nextItemId,
verticalMode,
rest
) => state => {
const { sliderPosition, childHeight, activeIndex } = state;
const childWidth = this.calculateChildWidth();
let newSliderPosition = 0;
const childSize = verticalMode ? childHeight : childWidth;
if (direction === consts.NEXT) {
newSliderPosition =
sliderPosition - childSize * (nextItemId - activeIndex);
} else {
newSliderPosition =
sliderPosition + childSize * (activeIndex - nextItemId);
}
return {
sliderPosition: newSliderPosition,
activeIndex: nextItemId,
swipedSliderPosition: 0,
isSwiping: false,
...rest
};
};
goTo = nextItemId => {
const {
children,
verticalMode,
itemsToShow
} = this.getDerivedPropsFromBreakPoint();
const { activeIndex } = this.state;
const childrenLength = Children.toArray(children).length;
let safeNextItemId = Math.max(0, nextItemId); // don't allow negative numbers
const isPrev = activeIndex > safeNextItemId;
const nextAvailableItem = this.getNextItemIndex(activeIndex, isPrev);
const noChange = nextAvailableItem === activeIndex;
const outOfBoundary = safeNextItemId + itemsToShow >= childrenLength;
if (noChange) {
return;
}
if (outOfBoundary) {
// Either go to last index (respect itemsToShow) or 0 index if we can't fill the slider
safeNextItemId = Math.max(0, childrenLength - itemsToShow);
}
let direction = consts.NEXT;
let positionEndCb = this.onNextEnd;
if (isPrev) {
direction = consts.PREV;
positionEndCb = this.onPrevEnd;
}
const stateUpdater = this.generatePositionUpdater(
direction,
safeNextItemId,
verticalMode,
{
transitioning: true
}
);
this.setState(stateUpdater, () => {
// callback
pipe(
this.updateActivePage(),
this.onSliderTransitionEnd(positionEndCb)
);
});
};
getNumOfPages = () => {
const { children, itemsToShow } = this.getDerivedPropsFromBreakPoint();
const childrenLength = Children.toArray(children).length;
const safeItemsToShow = Math.max(itemsToShow, 1);
const numOfPages = Math.ceil(childrenLength / safeItemsToShow);
return numOfPages || 1;
};
updateActivePage = () => {
this.setState(state => {
const { itemsToShow, children } = this.getDerivedPropsFromBreakPoint();
const { activeIndex, activePage } = state;
const numOfPages = this.getNumOfPages();
const childrenLength = Children.toArray(children).length;
const inRangeItemsToShow = Math.min(childrenLength, itemsToShow);
// watch out from 0 (so we wont divide by zero)
const safeItemsToShow = Math.max(inRangeItemsToShow, 1);
const newActivePage = Math.ceil(activeIndex / safeItemsToShow);
const inRangeActivePageIndex = Math.min(numOfPages - 1, newActivePage);
if (activePage !== inRangeActivePageIndex) {
return { activePage: inRangeActivePageIndex };
}
});
};
onIndicatorClick = indicatorId => {
const { itemsToShow } = this.getDerivedPropsFromBreakPoint();
const gotoIndex = indicatorId * itemsToShow;
this.setState({ activePage: indicatorId });
this.goTo(gotoIndex);
};
render() {
const {
activePage,
isSwiping,
sliderPosition,
swipedSliderPosition,
rootHeight,
pages,
activeIndex,
transitionMs
} = this.state;
const {
className,
style,
itemsToShow,
itemsToScroll,
verticalMode,
isRTL,
easing,
tiltEasing,
children,
focusOnSelect,
autoTabIndexVisibleItems,
itemPosition,
itemPadding,
outerSpacing,
enableSwipe,
enableMouseSwipe,
pagination,
showArrows,
disableArrowsOnEnd,
preventDefaultTouchmoveEvent,
renderArrow,
renderPagination
} = this.getDerivedPropsFromBreakPoint();
const childWidth = this.calculateChildWidth();
const numOfPages = this.getNumOfPages();
/** Determine if arrows should be disabled */
const canSlidePrev =
activeIndex !== this.getNextItemIndex(activeIndex, true);
const canSlideNext =
activeIndex !== this.getNextItemIndex(activeIndex, false);
const disabledPrevArrow = !canSlidePrev && disableArrowsOnEnd;
const disabledNextArrow = !canSlideNext && disableArrowsOnEnd;
return (
<CarouselWrapper
isRTL={isRTL}
className={`${cssPrefix("carousel-wrapper")} ${className}`}
style={style}
>
<StyledCarousel
className={cssPrefix("carousel")}
size={{ height: rootHeight }}
>
<Only when={showArrows}>
{renderArrow ? (
renderArrow({
type: consts.PREV,
onClick: this.onPrevStart,
isEdge: !canSlidePrev
})
) : (
<Arrow
onClick={this.onPrevStart}
direction={verticalMode ? Arrow.up : Arrow.left}
disabled={disabledPrevArrow}
/>
)}
</Only>
<SliderContainer
className={cssPrefix("slider-container")}
ref={this.setRef("sliderContainer")}
>
<Slider
verticalMode={verticalMode}
isRTL={isRTL}
easing={easing}
sliderPosition={sliderPosition}
swipedSliderPosition={swipedSliderPosition}
isSwiping={isSwiping}
transitionMs={transitionMs}
tiltEasing={tiltEasing}
className={cssPrefix("slider")}
ref={this.setRef("slider")}
outerSpacing={outerSpacing}
>
<Track
verticalMode={verticalMode}
children={Children.toArray(children)}
childWidth={childWidth}
currentItem={activeIndex}
autoTabIndexVisibleItems={autoTabIndexVisibleItems}
itemsToShow={itemsToShow}
itemsToScroll={itemsToScroll}
itemPosition={itemPosition}
itemPadding={itemPadding}
enableSwipe={enableSwipe}
enableMouseSwipe={enableMouseSwipe}
preventDefaultTouchmoveEvent={preventDefaultTouchmoveEvent}
onSwiped={this.onSwiped}
onSwiping={this.onSwiping}
onItemClick={focusOnSelect ? this.goTo : undefined}
/>
</Slider>
</SliderContainer>
<Only when={showArrows}>
{renderArrow ? (
renderArrow({
type: consts.NEXT,
onClick: this.onNextStart,
isEdge: !canSlideNext
})
) : (
<Arrow
onClick={this.onNextStart}
direction={verticalMode ? Arrow.down : Arrow.right}
disabled={disabledNextArrow}
/>
)}
</Only>
</StyledCarousel>
<Only when={pagination}>
{renderPagination ? (
renderPagination({
pages: pages,
activePage,
onClick: this.onIndicatorClick
})
) : (
<Pagination
numOfPages={numOfPages}
activePage={activePage}
onClick={this.onIndicatorClick}
/>
)}
</Only>
</CarouselWrapper>
);
}
}
Carousel.defaultProps = {
className: "",
style: {},
verticalMode: false,
isRTL: false,
initialFirstItem: 0,
initialActiveIndex: 0,
showArrows: true,
showEmptySlots: false,
disableArrowsOnEnd: true,
pagination: true,
easing: "ease",
tiltEasing: "ease",
transitionMs: 500,
enableTilt: true,
enableSwipe: true,
enableMouseSwipe: true,
preventDefaultTouchmoveEvent: false,
focusOnSelect: false,
autoTabIndexVisibleItems: true,
itemsToShow: 1,
itemsToScroll: 1,
itemPosition: consts.CENTER,
itemPadding: [0, 0, 0, 0],
outerSpacing: 0,
enableAutoPlay: false,
autoPlaySpeed: 2000,
// callbacks
onChange: noop,
onNextEnd: noop,
onPrevEnd: noop,
onNextStart: noop,
onPrevStart: noop,
onResize: noop
};
Carousel.propTypes = {
/** Items to render */
children: PropTypes.node.isRequired,
/** The css class for the root element */
className: PropTypes.string,
/** The style object for the root element */
style: PropTypes.object,
/** Display the Carousel in a vertical layout */
verticalMode: PropTypes.bool,
/** Flip right to left */
isRTL: PropTypes.bool,
/** Show dots for paging */
pagination: PropTypes.bool,
/** Animation speed */
transitionMs: PropTypes.number,
/** transition easing pattern */
easing: PropTypes.string,
/** transition easing pattern for the tilt */
tiltEasing: PropTypes.string,
/** The "bump" animation when reaching the last item */
enableTilt: PropTypes.bool,
/** Number of visible items */
itemsToShow: PropTypes.number,
/** Number of items to scroll */
itemsToScroll: PropTypes.number,
/** Collection of objects with a width, itemsToShow and itemsToScroll */
breakPoints: PropTypes.arrayOf(
PropTypes.shape({
width: PropTypes.number.isRequired,
itemsToShow: PropTypes.number,
itemsToScroll: PropTypes.number
})
),
/** The initial active index when the component mounts */
initialActiveIndex: PropTypes.number,
/** **DEPRECATED - use initialActiveIndex instead** The first items when the component mounts */
initialFirstItem: PropTypes.number,
/** Show the arrow buttons */
showArrows: PropTypes.bool,
/** Show empty slots when children.length < itemsToShow (not compatible with verticalMode yet !) */