@momo-kits/carousel 0.0.59-beta → 0.0.59-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CarouselV2.js ADDED
@@ -0,0 +1,1392 @@
1
+ import React from 'react';
2
+ import { Animated, I18nManager, Platform, View } from 'react-native';
3
+ // import shallowCompare from 'react-addons-shallow-compare';
4
+ import {
5
+ defaultScrollInterpolator,
6
+ stackScrollInterpolator,
7
+ tinderScrollInterpolator,
8
+ defaultAnimatedStyles,
9
+ shiftAnimatedStyles,
10
+ stackAnimatedStyles,
11
+ tinderAnimatedStyles,
12
+ } from './utils/animationsV2';
13
+ import PropTypes from 'prop-types';
14
+
15
+ // Metro doesn't support dynamic imports - i.e. require() done in the component itself
16
+ // But at the same time the following import will fail on Snack...
17
+ // TODO: find a way to get React Native's version without having to assume the file path
18
+ // import RN_PACKAGE from '../../../react-native/package.json';
19
+
20
+ const IS_ANDROID = Platform.OS === 'android';
21
+ const IS_IOS = Platform.OS === 'ios';
22
+
23
+ // React Native automatically handles RTL layouts; unfortunately, it's buggy with horizontal ScrollView
24
+ // See https://github.com/facebook/react-native/issues/11960
25
+ // NOTE: the following variable is not declared in the constructor
26
+ // otherwise it is undefined at init, which messes with custom indexes
27
+ const IS_RTL = I18nManager.isRTL;
28
+
29
+ export default class Carousel extends React.PureComponent {
30
+ constructor(props) {
31
+ super(props);
32
+
33
+ this.state = {
34
+ hideCarousel: !!props.apparitionDelay,
35
+ interpolators: [],
36
+ };
37
+
38
+ // this._RNVersionCode = this._getRNVersionCode();
39
+
40
+ // The following values are not stored in the state because 'setState()' is asynchronous
41
+ // and this results in an absolutely crappy behavior on Android while swiping (see #156)
42
+ const initialActiveItem = this._getFirstItem(props.firstItem);
43
+ this._activeItem = initialActiveItem;
44
+ this._onScrollActiveItem = initialActiveItem;
45
+ this._previousFirstItem = initialActiveItem;
46
+ this._previousItemsLength = initialActiveItem;
47
+
48
+ this._mounted = false;
49
+ this._positions = [];
50
+ this._currentScrollOffset = 0; // Store ScrollView's scroll position
51
+ this._scrollEnabled = props.scrollEnabled !== false;
52
+
53
+ this._getCellRendererComponent =
54
+ this._getCellRendererComponent.bind(this);
55
+ this._getItemLayout = this._getItemLayout.bind(this);
56
+ this._getKeyExtractor = this._getKeyExtractor.bind(this);
57
+ this._onLayout = this._onLayout.bind(this);
58
+ this._onScroll = this._onScroll.bind(this);
59
+ this._onMomentumScrollEnd = this._onMomentumScrollEnd.bind(this);
60
+ this._onTouchStart = this._onTouchStart.bind(this);
61
+ this._onTouchEnd = this._onTouchEnd.bind(this);
62
+ this._renderItem = this._renderItem.bind(this);
63
+
64
+ // WARNING: call this AFTER binding _onScroll
65
+ this._setScrollHandler(props);
66
+
67
+ // Display warnings
68
+ this._displayWarnings(props);
69
+ }
70
+
71
+ componentDidMount() {
72
+ const { apparitionDelay, autoplay, firstItem } = this.props;
73
+
74
+ this._mounted = true;
75
+ this._initPositionsAndInterpolators();
76
+
77
+ // Without 'requestAnimationFrame' or a `0` timeout, images will randomly not be rendered on Android...
78
+ this._initTimeout = setTimeout(() => {
79
+ if (!this._mounted) {
80
+ return;
81
+ }
82
+
83
+ const apparitionCallback = () => {
84
+ if (apparitionDelay) {
85
+ this.setState({ hideCarousel: false });
86
+ }
87
+ if (autoplay) {
88
+ this.startAutoplay();
89
+ }
90
+ };
91
+
92
+ // FlatList will use its own built-in prop `initialScrollIndex`
93
+ if (this._needsScrollView()) {
94
+ const _firstItem = this._getFirstItem(firstItem);
95
+ this._snapToItem(_firstItem, false, false, true);
96
+ // this._hackActiveSlideAnimation(_firstItem);
97
+ }
98
+
99
+ if (apparitionDelay) {
100
+ this._apparitionTimeout = setTimeout(() => {
101
+ apparitionCallback();
102
+ }, apparitionDelay);
103
+ } else {
104
+ apparitionCallback();
105
+ }
106
+ }, 1);
107
+ }
108
+
109
+ // shouldComponentUpdate (
110
+ // nextProps,
111
+ // nextState
112
+ // ) {
113
+ // if (this.props.shouldOptimizeUpdates === false) {
114
+ // return true;
115
+ // } else {
116
+ // return shallowCompare(this, nextProps, nextState);
117
+ // }
118
+ // }
119
+
120
+ componentDidUpdate(prevProps) {
121
+ const { interpolators } = this.state;
122
+ const { firstItem, scrollEnabled } = this.props;
123
+ const itemsLength = this._getCustomDataLength(this.props);
124
+
125
+ if (!itemsLength) {
126
+ return;
127
+ }
128
+
129
+ const nextFirstItem = this._getFirstItem(firstItem, this.props);
130
+ let nextActiveItem =
131
+ typeof this._activeItem !== 'undefined'
132
+ ? this._activeItem
133
+ : nextFirstItem;
134
+
135
+ const hasNewSize =
136
+ this.props.vertical !== prevProps.vertical ||
137
+ (this.props.vertical &&
138
+ prevProps.vertical &&
139
+ (prevProps.itemHeight !== this.props.itemHeight ||
140
+ prevProps.sliderHeight !== this.props.sliderHeight)) ||
141
+ (!this.props.vertical &&
142
+ !prevProps.vertical &&
143
+ (prevProps.itemWidth !== this.props.itemWidth ||
144
+ prevProps.sliderWidth !== this.props.sliderWidth));
145
+
146
+ // Prevent issues with dynamically removed items
147
+ if (nextActiveItem > itemsLength - 1) {
148
+ nextActiveItem = itemsLength - 1;
149
+ }
150
+
151
+ // Handle changing scrollEnabled independent of user -> carousel interaction
152
+ if (scrollEnabled !== prevProps.scrollEnabled) {
153
+ this._setScrollEnabled(scrollEnabled);
154
+ }
155
+
156
+ if (interpolators.length !== itemsLength || hasNewSize) {
157
+ this._activeItem = nextActiveItem;
158
+ this._previousItemsLength = itemsLength;
159
+
160
+ this._initPositionsAndInterpolators(this.props);
161
+
162
+ // Handle scroll issue when dynamically removing items (see #133)
163
+ // This also fixes first item's active state on Android
164
+ // Because 'initialScrollIndex' apparently doesn't trigger scroll
165
+ if (this._previousItemsLength > itemsLength) {
166
+ this._hackActiveSlideAnimation(nextActiveItem);
167
+ }
168
+
169
+ if (hasNewSize) {
170
+ this._snapToItem(nextActiveItem, false, false, true);
171
+ }
172
+ } else if (
173
+ nextFirstItem !== this._previousFirstItem &&
174
+ nextFirstItem !== this._activeItem
175
+ ) {
176
+ this._activeItem = nextFirstItem;
177
+ this._previousFirstItem = nextFirstItem;
178
+ this._snapToItem(nextFirstItem, false, true, true);
179
+ }
180
+
181
+ if (this.props.onScroll !== prevProps.onScroll) {
182
+ this._setScrollHandler(this.props);
183
+ }
184
+ }
185
+
186
+ componentWillUnmount() {
187
+ this._mounted = false;
188
+ this.stopAutoplay();
189
+ // @ts-expect-error setTimeout / clearTiemout is buggy :/
190
+ clearTimeout(this._initTimeout);
191
+ // @ts-expect-error setTimeout / clearTiemout is buggy :/
192
+ clearTimeout(this._apparitionTimeout);
193
+ // @ts-expect-error setTimeout / clearTiemout is buggy :/
194
+ clearTimeout(this._hackSlideAnimationTimeout);
195
+ // @ts-expect-error setTimeout / clearTiemout is buggy :/
196
+ clearTimeout(this._enableAutoplayTimeout);
197
+ // @ts-expect-error setTimeout / clearTiemout is buggy :/
198
+ clearTimeout(this._autoplayTimeout);
199
+ // @ts-expect-error setTimeout / clearTiemout is buggy :/
200
+ clearTimeout(this._snapNoMomentumTimeout);
201
+ // @ts-expect-error setTimeout / clearTiemout is buggy :/
202
+ clearTimeout(this._androidRepositioningTimeout);
203
+ }
204
+
205
+ get realIndex() {
206
+ return this._activeItem;
207
+ }
208
+
209
+ get currentIndex() {
210
+ return this._getDataIndex(this._activeItem);
211
+ }
212
+
213
+ get currentScrollPosition() {
214
+ return this._currentScrollOffset;
215
+ }
216
+
217
+ _setScrollHandler(props) {
218
+ // Native driver for scroll events
219
+ const scrollEventConfig = {
220
+ listener: this._onScroll,
221
+ useNativeDriver: true,
222
+ };
223
+ this._scrollPos = new Animated.Value(0);
224
+ const argMapping = props.vertical
225
+ ? [{ nativeEvent: { contentOffset: { y: this._scrollPos } } }]
226
+ : [{ nativeEvent: { contentOffset: { x: this._scrollPos } } }];
227
+
228
+ // @ts-expect-error Let's ignore for now that trick
229
+ if (props.onScroll && Array.isArray(props.onScroll._argMapping)) {
230
+ // Because of a react-native issue https://github.com/facebook/react-native/issues/13294
231
+ argMapping.pop();
232
+ // @ts-expect-error Let's ignore for now that trick
233
+ const [argMap] = props.onScroll._argMapping;
234
+ if (
235
+ argMap &&
236
+ argMap.nativeEvent &&
237
+ argMap.nativeEvent.contentOffset
238
+ ) {
239
+ // Shares the same animated value passed in props
240
+ this._scrollPos =
241
+ argMap.nativeEvent.contentOffset.x ||
242
+ argMap.nativeEvent.contentOffset.y ||
243
+ this._scrollPos;
244
+ }
245
+ // @ts-expect-error Let's ignore for now that trick
246
+ argMapping.push(...props.onScroll._argMapping);
247
+ }
248
+ this._onScrollHandler = Animated.event(argMapping, scrollEventConfig);
249
+ }
250
+
251
+ // This will return a future-proof version code number compatible with semantic versioning
252
+ // Examples: 0.59.3 -> 5903 / 0.61.4 -> 6104 / 0.62.12 -> 6212 / 1.0.2 -> 10002
253
+ // _getRNVersionCode () {
254
+ // const version = RN_PACKAGE && RN_PACKAGE.version;
255
+ // if (!version) {
256
+ // return null;
257
+ // }
258
+ // const versionSplit = version.split('.');
259
+ // if (!versionSplit || !versionSplit.length) {
260
+ // return null;
261
+ // }
262
+ // return versionSplit[0] * 10000 +
263
+ // (typeof versionSplit[1] !== 'undefined' ? versionSplit[1] * 100 : 0) +
264
+ // (typeof versionSplit[2] !== 'undefined' ? versionSplit[2] * 1 : 0);
265
+ // }
266
+
267
+ _displayWarnings(props = this.props) {
268
+ const pluginName = 'react-native-snap-carousel';
269
+ const removedProps = [
270
+ 'activeAnimationType',
271
+ 'activeAnimationOptions',
272
+ 'enableMomentum',
273
+ 'lockScrollTimeoutDuration',
274
+ 'lockScrollWhileSnapping',
275
+ 'onBeforeSnapToItem',
276
+ 'swipeThreshold',
277
+ ];
278
+
279
+ // if (this._RNVersionCode && this._RNVersionCode < 5800) {
280
+ // console.error(
281
+ // `${pluginName}: Version 4+ of the plugin is based on React Native props that were introduced in version 0.58. ` +
282
+ // 'Please downgrade to version 3.x or update your version of React Native.'
283
+ // );
284
+ // }
285
+ if (!props.vertical && (!props.sliderWidth || !props.itemWidth)) {
286
+ console.error(
287
+ `${pluginName}: You need to specify both 'sliderWidth' and 'itemWidth' for horizontal carousels`,
288
+ );
289
+ }
290
+ if (props.vertical && (!props.sliderHeight || !props.itemHeight)) {
291
+ console.error(
292
+ `${pluginName}: You need to specify both 'sliderHeight' and 'itemHeight' for vertical carousels`,
293
+ );
294
+ }
295
+
296
+ removedProps.forEach((removedProp) => {
297
+ if (removedProp in props) {
298
+ console.warn(
299
+ `${pluginName}: Prop ${removedProp} has been removed in version 4 of the plugin`,
300
+ );
301
+ }
302
+ });
303
+ }
304
+
305
+ _needsScrollView() {
306
+ const { useScrollView } = this.props;
307
+ // Android's cell renderer is buggy and has a stange overflow
308
+ // TODO: a workaround might be to pass the custom animated styles directly to it
309
+ return IS_ANDROID
310
+ ? useScrollView ||
311
+ !Animated.FlatList ||
312
+ this._shouldUseStackLayout() ||
313
+ this._shouldUseTinderLayout()
314
+ : useScrollView || !Animated.FlatList;
315
+ }
316
+
317
+ _needsRTLAdaptations() {
318
+ const { vertical } = this.props;
319
+ return IS_RTL && IS_ANDROID && !vertical;
320
+ }
321
+
322
+ _enableLoop() {
323
+ const { data, enableSnap, loop } = this.props;
324
+ return enableSnap && loop && data && data.length && data.length > 1;
325
+ }
326
+
327
+ _shouldAnimateSlides(props = this.props) {
328
+ const {
329
+ inactiveSlideOpacity,
330
+ inactiveSlideScale,
331
+ scrollInterpolator,
332
+ slideInterpolatedStyle,
333
+ } = props;
334
+ return (
335
+ inactiveSlideOpacity < 1 ||
336
+ inactiveSlideScale < 1 ||
337
+ !!scrollInterpolator ||
338
+ !!slideInterpolatedStyle ||
339
+ this._shouldUseShiftLayout() ||
340
+ this._shouldUseStackLayout() ||
341
+ this._shouldUseTinderLayout()
342
+ );
343
+ }
344
+
345
+ _shouldUseShiftLayout() {
346
+ const { inactiveSlideShift, layout } = this.props;
347
+ return layout === 'default' && inactiveSlideShift !== 0;
348
+ }
349
+
350
+ _shouldUseStackLayout() {
351
+ return this.props.layout === 'stack';
352
+ }
353
+
354
+ _shouldUseTinderLayout() {
355
+ return this.props.layout === 'tinder';
356
+ }
357
+
358
+ _shouldRepositionScroll(index) {
359
+ const { data, enableSnap, loopClonesPerSide } = this.props;
360
+ const dataLength = data && data.length;
361
+ if (
362
+ !enableSnap ||
363
+ !dataLength ||
364
+ !this._enableLoop() ||
365
+ (index >= loopClonesPerSide &&
366
+ index < dataLength + loopClonesPerSide)
367
+ ) {
368
+ return false;
369
+ }
370
+ return true;
371
+ }
372
+
373
+ _roundNumber(num, decimals = 1) {
374
+ // https://stackoverflow.com/a/41716722/
375
+ const rounder = Math.pow(10, decimals);
376
+ return Math.round((num + Number.EPSILON) * rounder) / rounder;
377
+ }
378
+
379
+ _isMultiple(x, y) {
380
+ // This prevents Javascript precision issues: https://stackoverflow.com/a/58440614/
381
+ // Required because Android viewport size can return pretty complicated decimals numbers
382
+ return Math.round(Math.round(x / y) / (1 / y)) === Math.round(x);
383
+ }
384
+
385
+ _getCustomData(props = this.props) {
386
+ const { data, loopClonesPerSide } = props;
387
+ const dataLength = data && data.length;
388
+
389
+ if (!dataLength) {
390
+ return [];
391
+ }
392
+
393
+ if (!this._enableLoop()) {
394
+ return data;
395
+ }
396
+
397
+ let previousItems = [];
398
+ let nextItems = [];
399
+
400
+ if (loopClonesPerSide > dataLength) {
401
+ const dataMultiplier = Math.floor(loopClonesPerSide / dataLength);
402
+ const remainder = loopClonesPerSide % dataLength;
403
+
404
+ for (let i = 0; i < dataMultiplier; i++) {
405
+ previousItems.push(...data);
406
+ nextItems.push(...data);
407
+ }
408
+
409
+ previousItems.unshift(...data.slice(-remainder));
410
+ nextItems.push(...data.slice(0, remainder));
411
+ } else {
412
+ previousItems = data.slice(-loopClonesPerSide);
413
+ nextItems = data.slice(0, loopClonesPerSide);
414
+ }
415
+
416
+ return previousItems.concat(data, nextItems);
417
+ }
418
+
419
+ _getCustomDataLength(props = this.props) {
420
+ const { data, loopClonesPerSide } = props;
421
+ const dataLength = data && data.length;
422
+
423
+ if (!dataLength) {
424
+ return 0;
425
+ }
426
+
427
+ return this._enableLoop()
428
+ ? dataLength + 2 * loopClonesPerSide
429
+ : dataLength;
430
+ }
431
+
432
+ _getCustomIndex(index, props = this.props) {
433
+ const itemsLength = this._getCustomDataLength(props);
434
+
435
+ if (!itemsLength || typeof index === 'undefined') {
436
+ return 0;
437
+ }
438
+
439
+ return this._needsRTLAdaptations() ? itemsLength - index - 1 : index;
440
+ }
441
+
442
+ _getDataIndex(index) {
443
+ const { data, loopClonesPerSide } = this.props;
444
+ const dataLength = data && data.length;
445
+ if (!this._enableLoop() || !dataLength) {
446
+ return index;
447
+ }
448
+
449
+ if (index >= dataLength + loopClonesPerSide) {
450
+ return loopClonesPerSide > dataLength
451
+ ? (index - loopClonesPerSide) % dataLength
452
+ : index - dataLength - loopClonesPerSide;
453
+ } else if (index < loopClonesPerSide) {
454
+ // TODO: is there a simpler way of determining the interpolated index?
455
+ if (loopClonesPerSide > dataLength) {
456
+ const baseDataIndexes = [];
457
+ const dataIndexes = [];
458
+ const dataMultiplier = Math.floor(
459
+ loopClonesPerSide / dataLength,
460
+ );
461
+ const remainder = loopClonesPerSide % dataLength;
462
+
463
+ for (let i = 0; i < dataLength; i++) {
464
+ baseDataIndexes.push(i);
465
+ }
466
+
467
+ for (let j = 0; j < dataMultiplier; j++) {
468
+ dataIndexes.push(...baseDataIndexes);
469
+ }
470
+
471
+ dataIndexes.unshift(...baseDataIndexes.slice(-remainder));
472
+ return dataIndexes[index];
473
+ } else {
474
+ return index + dataLength - loopClonesPerSide;
475
+ }
476
+ } else {
477
+ return index - loopClonesPerSide;
478
+ }
479
+ }
480
+
481
+ // Used with `snapToItem()` and 'PaginationDot'
482
+ _getPositionIndex(index) {
483
+ const { loop, loopClonesPerSide } = this.props;
484
+ return loop ? index + loopClonesPerSide : index;
485
+ }
486
+
487
+ _getSnapOffsets(props = this.props) {
488
+ const offset = this._getItemMainDimension();
489
+ return [...Array(this._getCustomDataLength(props))].map((_, i) => {
490
+ return i * offset;
491
+ });
492
+ }
493
+
494
+ _getFirstItem(index, props = this.props) {
495
+ const { loopClonesPerSide } = props;
496
+ const itemsLength = this._getCustomDataLength(props);
497
+
498
+ if (!itemsLength || index > itemsLength - 1 || index < 0) {
499
+ return 0;
500
+ }
501
+
502
+ return this._enableLoop() ? index + loopClonesPerSide : index;
503
+ }
504
+
505
+ _getWrappedRef() {
506
+ // Starting with RN 0.62, we should no longer call `getNode()` on the ref of an Animated component
507
+ if (
508
+ this._carouselRef &&
509
+ ((this._needsScrollView() && this._carouselRef.scrollTo) ||
510
+ (!this._needsScrollView() && this._carouselRef.scrollToOffset))
511
+ ) {
512
+ return this._carouselRef;
513
+ }
514
+ // https://github.com/facebook/react-native/issues/10635
515
+ // https://stackoverflow.com/a/48786374/8412141
516
+ return (
517
+ this._carouselRef &&
518
+ // @ts-expect-error This is for before 0.62
519
+ this._carouselRef.getNode &&
520
+ // @ts-expect-error This is for before 0.62
521
+ this._carouselRef.getNode()
522
+ );
523
+ }
524
+
525
+ _getScrollEnabled() {
526
+ return this._scrollEnabled;
527
+ }
528
+
529
+ _setScrollEnabled(scrollEnabled = true) {
530
+ const wrappedRef = this._getWrappedRef();
531
+
532
+ if (!wrappedRef || !wrappedRef.setNativeProps) {
533
+ return;
534
+ }
535
+
536
+ // 'setNativeProps()' is used instead of 'setState()' because the latter
537
+ // really takes a toll on Android behavior when momentum is disabled
538
+ wrappedRef.setNativeProps({ scrollEnabled });
539
+ this._scrollEnabled = scrollEnabled;
540
+ }
541
+
542
+ _getItemMainDimension() {
543
+ return this.props.vertical
544
+ ? this.props.itemHeight
545
+ : this.props.itemWidth;
546
+ }
547
+
548
+ _getItemScrollOffset(index) {
549
+ return (
550
+ this._positions &&
551
+ this._positions[index] &&
552
+ this._positions[index].start
553
+ );
554
+ }
555
+
556
+ _getItemLayout(_, index) {
557
+ const itemMainDimension = this._getItemMainDimension();
558
+ return {
559
+ index,
560
+ length: itemMainDimension,
561
+ offset: itemMainDimension * index, // + this._getContainerInnerMargin()
562
+ };
563
+ }
564
+
565
+ // This will allow us to have a proper zIndex even with a FlatList
566
+ // https://github.com/facebook/react-native/issues/18616#issuecomment-389444165
567
+ _getCellRendererComponent({ children, index, style, ...props }) {
568
+ const cellStyle = [
569
+ style,
570
+ !IS_ANDROID ? { zIndex: this._getCustomDataLength() - index } : {},
571
+ ];
572
+
573
+ return (
574
+ <View style={cellStyle} key={index} {...props}>
575
+ {children}
576
+ </View>
577
+ );
578
+ }
579
+
580
+ _getKeyExtractor(_, index) {
581
+ return this._needsScrollView()
582
+ ? `scrollview-item-${index}`
583
+ : `flatlist-item-${index}`;
584
+ }
585
+
586
+ _getScrollOffset(event) {
587
+ const { vertical } = this.props;
588
+ return (
589
+ (event &&
590
+ event.nativeEvent &&
591
+ event.nativeEvent.contentOffset &&
592
+ event.nativeEvent.contentOffset[vertical ? 'y' : 'x']) ||
593
+ 0
594
+ );
595
+ }
596
+
597
+ _getContainerInnerMargin(opposite = false) {
598
+ const { activeSlideAlignment } = this.props;
599
+
600
+ if (
601
+ (activeSlideAlignment === 'start' && !opposite) ||
602
+ (activeSlideAlignment === 'end' && opposite)
603
+ ) {
604
+ return 0;
605
+ } else if (
606
+ (activeSlideAlignment === 'end' && !opposite) ||
607
+ (activeSlideAlignment === 'start' && opposite)
608
+ ) {
609
+ return this.props.vertical
610
+ ? this.props.sliderHeight - this.props.itemHeight
611
+ : this.props.sliderWidth - this.props.itemWidth;
612
+ } else {
613
+ return this.props.vertical
614
+ ? (this.props.sliderHeight - this.props.itemHeight) / 2
615
+ : (this.props.sliderWidth - this.props.itemWidth) / 2;
616
+ }
617
+ }
618
+
619
+ _getActiveSlideOffset() {
620
+ const { activeSlideOffset } = this.props;
621
+ const itemMainDimension = this._getItemMainDimension();
622
+ const minOffset = 10;
623
+ // Make sure activeSlideOffset never prevents the active area from being at least 10 px wide
624
+ return itemMainDimension / 2 - activeSlideOffset >= minOffset
625
+ ? activeSlideOffset
626
+ : minOffset;
627
+ }
628
+
629
+ _getActiveItem(offset) {
630
+ const itemMainDimension = this._getItemMainDimension();
631
+ const center = offset + itemMainDimension / 2;
632
+ const activeSlideOffset = this._getActiveSlideOffset();
633
+ const lastIndex = this._positions.length - 1;
634
+ let itemIndex;
635
+
636
+ if (offset <= 0) {
637
+ return 0;
638
+ }
639
+
640
+ if (
641
+ this._positions[lastIndex] &&
642
+ offset >= this._positions[lastIndex].start
643
+ ) {
644
+ return lastIndex;
645
+ }
646
+
647
+ for (let i = 0; i < this._positions.length; i++) {
648
+ const { start, end } = this._positions[i];
649
+ if (
650
+ center + activeSlideOffset >= start &&
651
+ center - activeSlideOffset <= end
652
+ ) {
653
+ itemIndex = i;
654
+ break;
655
+ }
656
+ }
657
+
658
+ return itemIndex || 0;
659
+ }
660
+
661
+ _getSlideInterpolatedStyle(index, animatedValue) {
662
+ const { layoutCardOffset, slideInterpolatedStyle } = this.props;
663
+
664
+ if (slideInterpolatedStyle) {
665
+ return slideInterpolatedStyle(index, animatedValue, this.props);
666
+ } else if (this._shouldUseTinderLayout()) {
667
+ return tinderAnimatedStyles(
668
+ index,
669
+ animatedValue,
670
+ this.props,
671
+ layoutCardOffset,
672
+ );
673
+ } else if (this._shouldUseStackLayout()) {
674
+ return stackAnimatedStyles(
675
+ index,
676
+ animatedValue,
677
+ this.props,
678
+ layoutCardOffset,
679
+ );
680
+ } else if (this._shouldUseShiftLayout()) {
681
+ return shiftAnimatedStyles(index, animatedValue, this.props);
682
+ } else {
683
+ return defaultAnimatedStyles(index, animatedValue, this.props);
684
+ }
685
+ }
686
+
687
+ _initPositionsAndInterpolators(props = this.props) {
688
+ const { data, scrollInterpolator } = props;
689
+ const itemMainDimension = this._getItemMainDimension();
690
+
691
+ if (!data || !data.length) {
692
+ return;
693
+ }
694
+
695
+ const interpolators = [];
696
+ this._positions = [];
697
+
698
+ this._getCustomData(props).forEach((_itemData, index) => {
699
+ const _index = this._getCustomIndex(index, props);
700
+ let animatedValue;
701
+
702
+ this._positions[index] = {
703
+ start: index * itemMainDimension,
704
+ end: index * itemMainDimension + itemMainDimension,
705
+ };
706
+
707
+ if (!this._shouldAnimateSlides(props) || !this._scrollPos) {
708
+ animatedValue = new Animated.Value(1);
709
+ } else {
710
+ let interpolator;
711
+
712
+ if (scrollInterpolator) {
713
+ interpolator = scrollInterpolator(_index, props);
714
+ } else if (this._shouldUseStackLayout()) {
715
+ interpolator = stackScrollInterpolator(_index, props);
716
+ } else if (this._shouldUseTinderLayout()) {
717
+ interpolator = tinderScrollInterpolator(_index, props);
718
+ }
719
+
720
+ if (
721
+ !interpolator ||
722
+ !interpolator.inputRange ||
723
+ !interpolator.outputRange
724
+ ) {
725
+ interpolator = defaultScrollInterpolator(_index, props);
726
+ }
727
+
728
+ animatedValue = this._scrollPos.interpolate({
729
+ ...interpolator,
730
+ extrapolate: 'clamp',
731
+ });
732
+ }
733
+
734
+ interpolators.push(animatedValue);
735
+ });
736
+
737
+ this.setState({ interpolators });
738
+ }
739
+
740
+ _hackActiveSlideAnimation(index, scrollValue = 1) {
741
+ const offset = this._getItemScrollOffset(index);
742
+
743
+ if (
744
+ !this._mounted ||
745
+ !this._carouselRef ||
746
+ typeof offset === 'undefined'
747
+ ) {
748
+ return;
749
+ }
750
+
751
+ const multiplier = this._currentScrollOffset === 0 ? 1 : -1;
752
+ const scrollDelta = scrollValue * multiplier;
753
+
754
+ this._scrollTo({ offset: offset + scrollDelta, animated: false });
755
+
756
+ // @ts-expect-error setTimeout / clearTiemout is buggy :/
757
+ clearTimeout(this._hackSlideAnimationTimeout);
758
+ this._hackSlideAnimationTimeout = setTimeout(() => {
759
+ this._scrollTo({ offset, animated: false });
760
+ }, 1); // works randomly when set to '0'
761
+ }
762
+
763
+ _repositionScroll(index, animated = false) {
764
+ const { data, loopClonesPerSide } = this.props;
765
+ const dataLength = data && data.length;
766
+
767
+ if (
768
+ typeof index === 'undefined' ||
769
+ !this._shouldRepositionScroll(index)
770
+ ) {
771
+ return;
772
+ }
773
+
774
+ let repositionTo = index;
775
+
776
+ if (index >= dataLength + loopClonesPerSide) {
777
+ repositionTo = index - dataLength;
778
+ } else if (index < loopClonesPerSide) {
779
+ repositionTo = index + dataLength;
780
+ }
781
+
782
+ this._snapToItem(repositionTo, animated, false);
783
+ }
784
+
785
+ _scrollTo({ offset, index, animated = true }) {
786
+ const { vertical } = this.props;
787
+ const wrappedRef = this._getWrappedRef();
788
+ if (
789
+ !this._mounted ||
790
+ !wrappedRef ||
791
+ (typeof offset === 'undefined' && typeof index === 'undefined')
792
+ ) {
793
+ return;
794
+ }
795
+
796
+ let scrollToOffset;
797
+ if (typeof index !== 'undefined') {
798
+ scrollToOffset = this._getItemScrollOffset(index);
799
+ } else {
800
+ scrollToOffset = offset;
801
+ }
802
+
803
+ if (typeof scrollToOffset === 'undefined') {
804
+ return;
805
+ }
806
+
807
+ const options = this._needsScrollView()
808
+ ? {
809
+ x: vertical ? 0 : offset,
810
+ y: vertical ? offset : 0,
811
+ animated,
812
+ }
813
+ : {
814
+ offset,
815
+ animated,
816
+ };
817
+
818
+ if (this._needsScrollView()) {
819
+ wrappedRef.scrollTo(options);
820
+ } else {
821
+ wrappedRef.scrollToOffset(options);
822
+ }
823
+ }
824
+
825
+ _onTouchStart(event) {
826
+ const { onTouchStart } = this.props;
827
+
828
+ // `onTouchStart` is fired even when `scrollEnabled` is set to `false`
829
+ if (this._getScrollEnabled() !== false && this._autoplaying) {
830
+ this.pauseAutoPlay();
831
+ }
832
+
833
+ onTouchStart && onTouchStart(event);
834
+ }
835
+
836
+ _onTouchEnd(event) {
837
+ const { onTouchEnd } = this.props;
838
+
839
+ if (
840
+ this._getScrollEnabled() !== false &&
841
+ this._autoplay &&
842
+ !this._autoplaying
843
+ ) {
844
+ // This event is buggy on Android, so a fallback is provided in _onMomentumScrollEnd()
845
+ this.startAutoplay();
846
+ }
847
+
848
+ onTouchEnd && onTouchEnd(event);
849
+ }
850
+
851
+ _onScroll(event) {
852
+ const { onScroll, onScrollIndexChanged } = this.props;
853
+ const scrollOffset = event
854
+ ? this._getScrollOffset(event)
855
+ : this._currentScrollOffset;
856
+ const nextActiveItem = this._getActiveItem(scrollOffset);
857
+ const dataLength = this._getCustomDataLength();
858
+ const lastItemScrollOffset = this._getItemScrollOffset(dataLength - 1);
859
+
860
+ this._currentScrollOffset = scrollOffset;
861
+
862
+ if (nextActiveItem !== this._onScrollActiveItem) {
863
+ this._onScrollActiveItem = nextActiveItem;
864
+ onScrollIndexChanged &&
865
+ onScrollIndexChanged(this._getDataIndex(nextActiveItem));
866
+ }
867
+
868
+ if (
869
+ (IS_IOS && scrollOffset >= lastItemScrollOffset) ||
870
+ (IS_ANDROID &&
871
+ Math.floor(scrollOffset) >= Math.floor(lastItemScrollOffset))
872
+ ) {
873
+ this._activeItem = nextActiveItem;
874
+ this._repositionScroll(nextActiveItem);
875
+ }
876
+
877
+ if (typeof onScroll === 'function' && event) {
878
+ onScroll(event);
879
+ }
880
+ }
881
+
882
+ _onMomentumScrollEnd(event) {
883
+ const { autoplayDelay, onMomentumScrollEnd, onSnapToItem } = this.props;
884
+ const scrollOffset = event
885
+ ? this._getScrollOffset(event)
886
+ : this._currentScrollOffset;
887
+ const nextActiveItem = this._getActiveItem(scrollOffset);
888
+ const hasSnapped = this._isMultiple(
889
+ scrollOffset,
890
+ this.props.vertical ? this.props.itemHeight : this.props.itemWidth,
891
+ );
892
+
893
+ // WARNING: everything in this condition will probably need to be called on _snapToItem as well because:
894
+ // 1. `onMomentumScrollEnd` won't be called if the scroll isn't animated
895
+ // 2. `onMomentumScrollEnd` won't be called at all on Android when scrolling programmatically
896
+ if (nextActiveItem !== this._activeItem) {
897
+ this._activeItem = nextActiveItem;
898
+ onSnapToItem && onSnapToItem(this._getDataIndex(nextActiveItem));
899
+
900
+ if (hasSnapped && IS_ANDROID) {
901
+ this._repositionScroll(nextActiveItem);
902
+ } else if (IS_IOS) {
903
+ this._repositionScroll(nextActiveItem);
904
+ }
905
+ }
906
+
907
+ onMomentumScrollEnd && onMomentumScrollEnd(event);
908
+
909
+ // The touchEnd event is buggy on Android, so this will serve as a fallback whenever needed
910
+ // https://github.com/facebook/react-native/issues/9439
911
+ if (IS_ANDROID && this._autoplay && !this._autoplaying) {
912
+ // @ts-expect-error setTimeout / clearTiemout is buggy :/
913
+ clearTimeout(this._enableAutoplayTimeout);
914
+ this._enableAutoplayTimeout = setTimeout(() => {
915
+ this.startAutoplay();
916
+ }, autoplayDelay);
917
+ }
918
+ }
919
+
920
+ _onLayout(event) {
921
+ const { onLayout } = this.props;
922
+
923
+ // Prevent unneeded actions during the first 'onLayout' (triggered on init)
924
+ if (this._onLayoutInitDone) {
925
+ this._initPositionsAndInterpolators();
926
+ this._snapToItem(this._activeItem, false, false, true);
927
+ } else {
928
+ this._onLayoutInitDone = true;
929
+ }
930
+
931
+ onLayout && onLayout(event);
932
+ }
933
+
934
+ _snapToItem(
935
+ index,
936
+ animated = true,
937
+ fireCallback = true,
938
+ forceScrollTo = false,
939
+ ) {
940
+ const { onSnapToItem } = this.props;
941
+ const itemsLength = this._getCustomDataLength();
942
+ const wrappedRef = this._getWrappedRef();
943
+ if (!itemsLength || !wrappedRef) {
944
+ return;
945
+ }
946
+
947
+ if (!index || index < 0) {
948
+ index = 0;
949
+ } else if (itemsLength > 0 && index >= itemsLength) {
950
+ index = itemsLength - 1;
951
+ }
952
+
953
+ if (index === this._activeItem && !forceScrollTo) {
954
+ return;
955
+ }
956
+
957
+ const offset = this._getItemScrollOffset(index);
958
+
959
+ if (offset === undefined) {
960
+ return;
961
+ }
962
+
963
+ this._scrollTo({ offset, animated });
964
+
965
+ // On both platforms, `onMomentumScrollEnd` won't be triggered if the scroll isn't animated
966
+ // so we need to trigger the callback manually
967
+ // On Android `onMomentumScrollEnd` won't be triggered when scrolling programmatically
968
+ // Therefore everything critical needs to be manually called here as well, even though the timing might be off
969
+ const requiresManualTrigger = !animated || IS_ANDROID;
970
+ if (requiresManualTrigger) {
971
+ this._activeItem = index;
972
+
973
+ if (fireCallback) {
974
+ onSnapToItem && onSnapToItem(this._getDataIndex(index));
975
+ }
976
+
977
+ // Repositioning on Android
978
+ if (IS_ANDROID && this._shouldRepositionScroll(index)) {
979
+ if (animated) {
980
+ this._androidRepositioningTimeout = setTimeout(() => {
981
+ // Without scroll animation, the behavior is completely buggy...
982
+ this._repositionScroll(index, false);
983
+ }, 400); // Approximate scroll duration on Android
984
+ } else {
985
+ this._repositionScroll(index);
986
+ }
987
+ }
988
+ }
989
+ }
990
+
991
+ startAutoplay() {
992
+ const { autoplayInterval, autoplayDelay } = this.props;
993
+ this._autoplay = true;
994
+
995
+ if (this._autoplaying) {
996
+ return;
997
+ }
998
+
999
+ // @ts-expect-error setTimeout / clearTiemout is buggy :/
1000
+ clearTimeout(this._autoplayTimeout);
1001
+ this._autoplayTimeout = setTimeout(() => {
1002
+ this._autoplaying = true;
1003
+ this._autoplayInterval = setInterval(() => {
1004
+ if (this._autoplaying) {
1005
+ this.snapToNext();
1006
+ }
1007
+ }, autoplayInterval);
1008
+ }, autoplayDelay);
1009
+ }
1010
+
1011
+ pauseAutoPlay() {
1012
+ this._autoplaying = false;
1013
+ // @ts-expect-error setTimeout / clearTiemout is buggy :/
1014
+ clearTimeout(this._autoplayTimeout);
1015
+ // @ts-expect-error setTimeout / clearTiemout is buggy :/
1016
+ clearTimeout(this._enableAutoplayTimeout);
1017
+ // @ts-expect-error setTimeout / clearTiemout is buggy :/
1018
+ clearInterval(this._autoplayInterval);
1019
+ }
1020
+
1021
+ stopAutoplay() {
1022
+ this._autoplay = false;
1023
+ this.pauseAutoPlay();
1024
+ }
1025
+
1026
+ snapToItem(index, animated = true, fireCallback = true) {
1027
+ if (!index || index < 0) {
1028
+ index = 0;
1029
+ }
1030
+
1031
+ const positionIndex = this._getPositionIndex(index);
1032
+
1033
+ if (positionIndex === this._activeItem) {
1034
+ return;
1035
+ }
1036
+
1037
+ this._snapToItem(positionIndex, animated, fireCallback);
1038
+ }
1039
+
1040
+ snapToNext(animated = true, fireCallback = true) {
1041
+ const itemsLength = this._getCustomDataLength();
1042
+
1043
+ let newIndex = this._activeItem + 1;
1044
+ if (newIndex > itemsLength - 1) {
1045
+ newIndex = 0;
1046
+ }
1047
+ this._snapToItem(newIndex, animated, fireCallback);
1048
+ }
1049
+
1050
+ snapToPrev(animated = true, fireCallback = true) {
1051
+ const itemsLength = this._getCustomDataLength();
1052
+
1053
+ let newIndex = this._activeItem - 1;
1054
+ if (newIndex < 0) {
1055
+ newIndex = itemsLength - 1;
1056
+ }
1057
+ this._snapToItem(newIndex, animated, fireCallback);
1058
+ }
1059
+
1060
+ // https://github.com/facebook/react-native/issues/1831#issuecomment-231069668
1061
+ triggerRenderingHack(offset = 1) {
1062
+ this._hackActiveSlideAnimation(this._activeItem, offset);
1063
+ }
1064
+
1065
+ _renderItem({ item, index }) {
1066
+ const { interpolators } = this.state;
1067
+ const { keyExtractor, slideStyle } = this.props;
1068
+ const animatedValue = interpolators && interpolators[index];
1069
+
1070
+ if (typeof animatedValue === 'undefined') {
1071
+ return null;
1072
+ }
1073
+
1074
+ const animate = this._shouldAnimateSlides();
1075
+ const Component = animate ? Animated.View : View;
1076
+ const animatedStyle = animate
1077
+ ? this._getSlideInterpolatedStyle(index, animatedValue)
1078
+ : {};
1079
+ const dataIndex = this._getDataIndex(index);
1080
+
1081
+ const mainDimension = this.props.vertical
1082
+ ? { height: this.props.itemHeight }
1083
+ : { width: this.props.itemWidth };
1084
+ const specificProps = this._needsScrollView()
1085
+ ? {
1086
+ key: keyExtractor
1087
+ ? keyExtractor(item, index)
1088
+ : this._getKeyExtractor(item, index),
1089
+ }
1090
+ : {};
1091
+
1092
+ return (
1093
+ <Component
1094
+ style={[mainDimension, slideStyle, animatedStyle]}
1095
+ pointerEvents="box-none"
1096
+ {...specificProps}>
1097
+ {this.props.vertical
1098
+ ? this.props.renderItem(
1099
+ {
1100
+ item,
1101
+ index,
1102
+ dataIndex,
1103
+ realIndex: this._getDataIndex(index),
1104
+ activeIndex: this._getDataIndex(this._activeItem),
1105
+ },
1106
+ {
1107
+ scrollPosition: this._scrollPos,
1108
+ carouselRef: this._carouselRef,
1109
+ vertical: this.props.vertical,
1110
+ sliderHeight: this.props.sliderHeight,
1111
+ itemHeight: this.props.itemHeight,
1112
+ },
1113
+ )
1114
+ : this.props.renderItem(
1115
+ {
1116
+ item,
1117
+ index,
1118
+ dataIndex,
1119
+ realIndex: this._getDataIndex(index),
1120
+ activeIndex: this._getDataIndex(this._activeItem),
1121
+ },
1122
+ {
1123
+ scrollPosition: this._scrollPos,
1124
+ carouselRef: this._carouselRef,
1125
+ vertical: !!this.props.vertical,
1126
+ sliderWidth: this.props.sliderWidth,
1127
+ itemWidth: this.props.itemWidth,
1128
+ },
1129
+ )}
1130
+ </Component>
1131
+ );
1132
+ }
1133
+
1134
+ _getComponentOverridableProps() {
1135
+ const { hideCarousel } = this.state;
1136
+ const { loopClonesPerSide } = this.props;
1137
+ const visibleItems =
1138
+ Math.ceil(
1139
+ this.props.vertical
1140
+ ? this.props.sliderHeight / this.props.itemHeight
1141
+ : this.props.sliderWidth / this.props.itemWidth,
1142
+ ) + 1;
1143
+ const initialNumPerSide = this._enableLoop() ? loopClonesPerSide : 2;
1144
+ const initialNumToRender =
1145
+ visibleItems > 2
1146
+ ? visibleItems + initialNumPerSide * 2
1147
+ : initialNumPerSide * 2;
1148
+ const maxToRenderPerBatch = initialNumToRender;
1149
+ const windowSize = maxToRenderPerBatch;
1150
+ const specificProps = !this._needsScrollView()
1151
+ ? {
1152
+ initialNumToRender,
1153
+ maxToRenderPerBatch,
1154
+ windowSize,
1155
+ // updateCellsBatchingPeriod
1156
+ }
1157
+ : {};
1158
+
1159
+ return {
1160
+ ...specificProps,
1161
+ automaticallyAdjustContentInsets: false,
1162
+ decelerationRate: 'fast',
1163
+ directionalLockEnabled: true,
1164
+ disableScrollViewPanResponder: false, // If set to `true`, touch events will be triggered too easily
1165
+ inverted: this._needsRTLAdaptations(),
1166
+ overScrollMode: 'never',
1167
+ pinchGestureEnabled: false,
1168
+ pointerEvents: hideCarousel ? 'none' : 'auto',
1169
+ // removeClippedSubviews: !this._needsScrollView(),
1170
+ // renderToHardwareTextureAndroid: true,
1171
+ scrollsToTop: false,
1172
+ showsHorizontalScrollIndicator: false,
1173
+ showsVerticalScrollIndicator: false,
1174
+ };
1175
+ }
1176
+
1177
+ _getComponentStaticProps() {
1178
+ const { hideCarousel } = this.state;
1179
+ const {
1180
+ activeSlideAlignment,
1181
+ CellRendererComponent,
1182
+ containerCustomStyle,
1183
+ contentContainerCustomStyle,
1184
+ firstItem,
1185
+ getItemLayout,
1186
+ keyExtractor,
1187
+ style,
1188
+ useExperimentalSnap,
1189
+ disableIntervalMomentum,
1190
+ vertical,
1191
+ } = this.props;
1192
+
1193
+ const containerStyle = [
1194
+ // { overflow: 'hidden' },
1195
+ containerCustomStyle || style || {},
1196
+ hideCarousel ? { opacity: 0 } : {},
1197
+ this.props.vertical
1198
+ ? { height: this.props.sliderHeight, flexDirection: 'column' } // LTR hack; see https://github.com/facebook/react-native/issues/11960
1199
+ : // and https://github.com/facebook/react-native/issues/13100#issuecomment-328986423
1200
+ {
1201
+ width: this.props.sliderWidth,
1202
+ flexDirection: this._needsRTLAdaptations()
1203
+ ? 'row-reverse'
1204
+ : 'row',
1205
+ },
1206
+ ];
1207
+
1208
+ const innerMarginStyle = this.props.vertical
1209
+ ? {
1210
+ paddingTop: this._getContainerInnerMargin(),
1211
+ paddingBottom: this._getContainerInnerMargin(true),
1212
+ }
1213
+ : {
1214
+ paddingLeft: this._getContainerInnerMargin(),
1215
+ paddingRight: this._getContainerInnerMargin(true),
1216
+ };
1217
+
1218
+ const contentContainerStyle = [
1219
+ vertical
1220
+ ? {
1221
+ paddingTop: this._getContainerInnerMargin(),
1222
+ paddingBottom: this._getContainerInnerMargin(true),
1223
+ }
1224
+ : {
1225
+ paddingLeft: this._getContainerInnerMargin(),
1226
+ paddingRight: this._getContainerInnerMargin(true),
1227
+ },
1228
+ contentContainerCustomStyle || {},
1229
+ ];
1230
+
1231
+ // WARNING: `snapToAlignment` won't work as intended because of the following:
1232
+ // https://github.com/facebook/react-native/blob/d0871d0a9a373e1d3ac35da46c85c0d0e793116d/React/Views/ScrollView/RCTScrollView.m#L751-L755
1233
+ // - Snap points will be off
1234
+ // - Slide animations will be off
1235
+ // - Last items won't be set as active (no `onSnapToItem` callback)
1236
+ // Recommended only with large slides and `activeSlideAlignment` set to `start` for the time being
1237
+ const snapProps = useExperimentalSnap
1238
+ ? {
1239
+ disableIntervalMomentum, // Slide ± one item at a time
1240
+ snapToAlignment: activeSlideAlignment,
1241
+ snapToInterval: this._getItemMainDimension(),
1242
+ }
1243
+ : {
1244
+ snapToOffsets: this._getSnapOffsets(),
1245
+ };
1246
+
1247
+ // Flatlist specifics
1248
+ const specificProps = !this._needsScrollView()
1249
+ ? {
1250
+ CellRendererComponent:
1251
+ CellRendererComponent || this._getCellRendererComponent,
1252
+ getItemLayout: getItemLayout || this._getItemLayout,
1253
+ initialScrollIndex: this._getFirstItem(firstItem),
1254
+ keyExtractor: keyExtractor || this._getKeyExtractor,
1255
+ numColumns: 1,
1256
+ renderItem: this._renderItem,
1257
+ }
1258
+ : {};
1259
+
1260
+ return {
1261
+ ...specificProps,
1262
+ ...snapProps,
1263
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1264
+ ref: (c) => {
1265
+ this._carouselRef = c;
1266
+ },
1267
+ contentContainerStyle: contentContainerStyle,
1268
+ data: this._getCustomData(),
1269
+ horizontal: !this.props.vertical,
1270
+ scrollEventThrottle: 1,
1271
+ style: containerStyle,
1272
+ onLayout: this._onLayout,
1273
+ onMomentumScrollEnd: this._onMomentumScrollEnd,
1274
+ onScroll: this._onScrollHandler,
1275
+ onTouchStart: this._onTouchStart,
1276
+ onTouchEnd: this._onTouchEnd,
1277
+ };
1278
+ }
1279
+
1280
+ render() {
1281
+ const { data, renderItem, useScrollView } = this.props;
1282
+
1283
+ if (!data || !renderItem) {
1284
+ return null;
1285
+ }
1286
+
1287
+ const props = {
1288
+ ...this._getComponentOverridableProps(),
1289
+ ...this.props,
1290
+ ...this._getComponentStaticProps(),
1291
+ };
1292
+
1293
+ const ScrollViewComponent =
1294
+ typeof useScrollView === 'function'
1295
+ ? useScrollView
1296
+ : Animated.ScrollView;
1297
+
1298
+ return this._needsScrollView() || !Animated.FlatList ? (
1299
+ <ScrollViewComponent {...props}>
1300
+ {this._getCustomData().map((item, index) => {
1301
+ return this._renderItem({
1302
+ item,
1303
+ index,
1304
+ realIndex: this._getDataIndex(index),
1305
+ activeIndex: this._getDataIndex(this._activeItem),
1306
+ });
1307
+ })}
1308
+ </ScrollViewComponent>
1309
+ ) : (
1310
+ // @ts-expect-error Seems complicated to make TS 100% happy, while sharing that many things between
1311
+ // flatlist && scrollview implementation. I'll prob try to rewrite parts of the logic to overcome that.
1312
+ <Animated.FlatList {...props} />
1313
+ );
1314
+ }
1315
+ }
1316
+
1317
+ Carousel.propTypes = {
1318
+ data: PropTypes.array.isRequired,
1319
+ renderItem: PropTypes.func.isRequired,
1320
+ itemWidth: PropTypes.number, // required for horizontal carousel
1321
+ itemHeight: PropTypes.number, // required for vertical carousel
1322
+ sliderWidth: PropTypes.number, // required for horizontal carousel
1323
+ sliderHeight: PropTypes.number, // required for vertical carousel
1324
+ activeSlideAlignment: PropTypes.oneOf(['center', 'end', 'start']),
1325
+ activeSlideOffset: PropTypes.number,
1326
+ apparitionDelay: PropTypes.number,
1327
+ autoplay: PropTypes.bool,
1328
+ autoplayDelay: PropTypes.number,
1329
+ autoplayInterval: PropTypes.number,
1330
+ callbackOffsetMargin: PropTypes.number,
1331
+ containerCustomStyle: PropTypes.oneOfType([
1332
+ PropTypes.object,
1333
+ PropTypes.array,
1334
+ ]),
1335
+ contentContainerCustomStyle: PropTypes.oneOfType([
1336
+ PropTypes.object,
1337
+ PropTypes.array,
1338
+ ]),
1339
+ enableSnap: PropTypes.bool,
1340
+ firstItem: PropTypes.number,
1341
+ hasParallaxImages: PropTypes.bool,
1342
+ inactiveSlideOpacity: PropTypes.number,
1343
+ inactiveSlideScale: PropTypes.number,
1344
+ inactiveSlideShift: PropTypes.number,
1345
+ layout: PropTypes.oneOf(['default', 'stack', 'tinder']),
1346
+ layoutCardOffset: PropTypes.number,
1347
+ loop: PropTypes.bool,
1348
+ loopClonesPerSide: PropTypes.number,
1349
+ scrollEnabled: PropTypes.bool,
1350
+ scrollInterpolator: PropTypes.func,
1351
+ slideInterpolatedStyle: PropTypes.func,
1352
+ slideStyle: PropTypes.object,
1353
+ shouldOptimizeUpdates: PropTypes.bool,
1354
+ swipeThreshold: PropTypes.number,
1355
+ useScrollView: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]),
1356
+ vertical: PropTypes.bool,
1357
+ showsPagination: PropTypes.bool,
1358
+ isCustomScrollWidth: PropTypes.bool,
1359
+ disableIntervalMomentum: PropTypes.bool,
1360
+ useExperimentalSnap: PropTypes.bool,
1361
+ onBeforeSnapToItem: PropTypes.func,
1362
+ onSnapToItem: PropTypes.func,
1363
+ };
1364
+
1365
+ Carousel.defaultProps = {
1366
+ activeSlideAlignment: 'center',
1367
+ activeSlideOffset: 20,
1368
+ apparitionDelay: 0,
1369
+ autoplay: false,
1370
+ autoplayDelay: 1000,
1371
+ autoplayInterval: 3000,
1372
+ callbackOffsetMargin: 5,
1373
+ containerCustomStyle: {},
1374
+ contentContainerCustomStyle: {},
1375
+ enableSnap: true,
1376
+ firstItem: 0,
1377
+ hasParallaxImages: false,
1378
+ inactiveSlideOpacity: 0.7,
1379
+ inactiveSlideScale: 0.9,
1380
+ inactiveSlideShift: 0,
1381
+ layout: 'default',
1382
+ loop: false,
1383
+ loopClonesPerSide: 3,
1384
+ scrollEnabled: true,
1385
+ slideStyle: {},
1386
+ shouldOptimizeUpdates: true,
1387
+ useScrollView: !Animated.FlatList,
1388
+ vertical: false,
1389
+ isCustomScrollWidth: false,
1390
+ disableIntervalMomentum: IS_ANDROID,
1391
+ useExperimentalSnap: IS_ANDROID,
1392
+ };