-
Notifications
You must be signed in to change notification settings - Fork 97
/
WithGestureHandler.tsx
310 lines (282 loc) · 10.9 KB
/
WithGestureHandler.tsx
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
// NOTE: this is a quick fix for the case https://github.com/gusgard/react-native-swiper-flatlist/issues/169
// TODO: delete this file and refactor the code in SwiperFlatList to support the gesture handler without using "require"
import React from 'react';
import {
FlatList as RNFlatList,
FlatListProps,
I18nManager,
Platform,
useWindowDimensions,
} from 'react-native';
let FlatList = RNFlatList;
import { Pagination } from './src/components/Pagination/Pagination';
import {
SwiperFlatListProps,
SwiperFlatListRefProps,
} from './src/components/SwiperFlatList/SwiperFlatListProps';
const MILLISECONDS = 1000;
const FIRST_INDEX = 0;
const ITEM_VISIBLE_PERCENT_THRESHOLD = 60;
// TODO: figure out how to use forwardRef with generics
type T1 = any;
type ScrollToIndex = { index: number; animated?: boolean };
// const SwiperFlatList = React.forwardRef<RefProps, SwiperFlatListProps<SwiperType>>(
export const SwiperFlatListWithGestureHandler = React.forwardRef(
// <T1 extends any>(
(
{
vertical = false,
children,
data = [],
renderItem,
renderAll = false,
index = I18nManager.isRTL ? data.length - 1 : FIRST_INDEX,
useReactNativeGestureHandler = false,
// Pagination
showPagination = false,
PaginationComponent = Pagination,
paginationActiveColor,
paginationDefaultColor,
paginationStyle,
paginationStyleItem,
paginationStyleItemActive,
paginationStyleItemInactive,
onPaginationSelectedIndex,
paginationTapDisabled = false,
// Autoplay
autoplayDelay = 3,
autoplay = false,
autoplayLoop = false,
autoplayLoopKeepAnimation = false,
autoplayInvertDirection = I18nManager.isRTL,
// Functions
onChangeIndex,
onMomentumScrollEnd,
onViewableItemsChanged,
viewabilityConfig = {},
disableGesture = false,
e2eID,
...props
}: SwiperFlatListProps<T1>,
ref: React.Ref<SwiperFlatListRefProps>,
) => {
let _data: unknown[] = [];
let _renderItem: FlatListProps<any>['renderItem'];
if (children) {
// github.com/gusgard/react-native-swiper-flatlist/issues/40
_data = Array.isArray(children) ? children : [children];
_renderItem = ({ item }) => item;
} else if (data) {
_data = data;
_renderItem = renderItem;
} else {
console.error('Invalid props, `data` or `children` is required');
}
const size = _data.length;
// Items to render in the initial batch.
const _initialNumToRender = renderAll ? size : 1;
const [currentIndexes, setCurrentIndexes] = React.useState({ index, prevIndex: index });
const [ignoreOnMomentumScrollEnd, setIgnoreOnMomentumScrollEnd] = React.useState(false);
const flatListElement = React.useRef<RNFlatList<unknown>>(null);
const [scrollEnabled, setScrollEnabled] = React.useState(!disableGesture);
React.useEffect(() => {
setScrollEnabled(!disableGesture);
}, [disableGesture]);
const _onChangeIndex = React.useCallback(
({ index: _index, prevIndex: _prevIndex }: { index: number; prevIndex: number }) => {
if (_index !== _prevIndex) {
onChangeIndex?.({ index: _index, prevIndex: _prevIndex });
}
},
[onChangeIndex],
);
const _scrollToIndex = React.useCallback(
(params: ScrollToIndex) => {
const { index: indexToScroll, animated = true } = params;
const newParams = { animated, index: indexToScroll };
setIgnoreOnMomentumScrollEnd(true);
const next = {
index: indexToScroll,
prevIndex: currentIndexes.index,
};
if (currentIndexes.index !== next.index && currentIndexes.prevIndex !== next.prevIndex) {
setCurrentIndexes({ index: next.index, prevIndex: next.prevIndex });
} else if (currentIndexes.index !== next.index) {
setCurrentIndexes((prevState) => ({ ...prevState, index: next.index }));
} else if (currentIndexes.prevIndex !== next.prevIndex) {
setCurrentIndexes((prevState) => ({ ...prevState, prevIndex: next.prevIndex }));
}
// When execute "scrollToIndex", we ignore the method "onMomentumScrollEnd"
// because it not working on Android
// https://github.com/facebook/react-native/issues/21718
flatListElement?.current?.scrollToIndex(newParams);
},
[currentIndexes.index, currentIndexes.prevIndex],
);
// change the index when the user swipe the items
React.useEffect(() => {
_onChangeIndex({ index: currentIndexes.index, prevIndex: currentIndexes.prevIndex });
}, [_onChangeIndex, currentIndexes.index, currentIndexes.prevIndex]);
React.useImperativeHandle(ref, () => ({
scrollToIndex: (item: ScrollToIndex) => {
setScrollEnabled(true);
_scrollToIndex(item);
setScrollEnabled(!disableGesture);
},
getCurrentIndex: () => currentIndexes.index,
getPrevIndex: () => currentIndexes.prevIndex,
goToLastIndex: () => {
setScrollEnabled(true);
_scrollToIndex({ index: I18nManager.isRTL ? FIRST_INDEX : size - 1 });
setScrollEnabled(!disableGesture);
},
goToFirstIndex: () => {
setScrollEnabled(true);
_scrollToIndex({ index: I18nManager.isRTL ? size - 1 : FIRST_INDEX });
setScrollEnabled(!disableGesture);
},
}));
React.useEffect(() => {
const isLastIndexEnd = autoplayInvertDirection
? currentIndexes.index === FIRST_INDEX
: currentIndexes.index === _data.length - 1;
const shouldContinuoWithAutoplay = autoplay && !isLastIndexEnd;
let autoplayTimer: ReturnType<typeof setTimeout>;
if (shouldContinuoWithAutoplay || autoplayLoop) {
autoplayTimer = setTimeout(() => {
if (_data.length < 1) {
// avoid nextIndex being set to NaN
return;
}
if (!autoplay) {
// disabled if autoplay is off
return;
}
const nextIncrement = autoplayInvertDirection ? -1 : +1;
let nextIndex = (currentIndexes.index + nextIncrement) % _data.length;
if (autoplayInvertDirection && nextIndex < FIRST_INDEX) {
nextIndex = _data.length - 1;
}
// Disable end loop animation unless `autoplayLoopKeepAnimation` prop configured
const animate = !isLastIndexEnd || autoplayLoopKeepAnimation;
_scrollToIndex({ index: nextIndex, animated: animate });
}, autoplayDelay * MILLISECONDS);
}
// https://upmostly.com/tutorials/settimeout-in-react-components-using-hooks
return () => clearTimeout(autoplayTimer);
}, [
autoplay,
currentIndexes.index,
_data.length,
autoplayInvertDirection,
autoplayLoop,
autoplayDelay,
autoplayLoopKeepAnimation,
_scrollToIndex,
]);
const _onMomentumScrollEnd: FlatListProps<unknown>['onMomentumScrollEnd'] = (event) => {
// NOTE: Method not executed when call "flatListElement?.current?.scrollToIndex"
if (ignoreOnMomentumScrollEnd) {
setIgnoreOnMomentumScrollEnd(false);
return;
}
onMomentumScrollEnd?.({ index: currentIndexes.index }, event);
};
const _onViewableItemsChanged = React.useMemo<FlatListProps<unknown>['onViewableItemsChanged']>(
() => (params) => {
const { changed } = params;
const newItem = changed?.[FIRST_INDEX];
if (newItem !== undefined) {
const nextIndex = newItem.index as number;
if (newItem.isViewable) {
setCurrentIndexes((prevState) => ({ ...prevState, index: nextIndex }));
} else {
setCurrentIndexes((prevState) => ({ ...prevState, prevIndex: nextIndex }));
}
}
onViewableItemsChanged?.(params);
},
[onViewableItemsChanged],
);
const flatListProps: FlatListProps<unknown> & { ref: React.RefObject<RNFlatList<unknown>> } = {
scrollEnabled,
ref: flatListElement,
keyExtractor: (_item, _index) => {
const item = _item as { key?: string; id?: string };
const key = item?.key ?? item?.id ?? _index.toString();
return key;
},
horizontal: !vertical,
showsHorizontalScrollIndicator: false,
showsVerticalScrollIndicator: false,
pagingEnabled: true,
...props,
onMomentumScrollEnd: _onMomentumScrollEnd,
onScrollToIndexFailed: (info) =>
setTimeout(() => _scrollToIndex({ index: info.index, animated: false })),
data: _data,
renderItem: _renderItem,
initialNumToRender: _initialNumToRender,
initialScrollIndex: index, // used with onScrollToIndexFailed
viewabilityConfig: {
// https://facebook.github.io/react-native/docs/flatlist#minimumviewtime
minimumViewTime: 200,
itemVisiblePercentThreshold: ITEM_VISIBLE_PERCENT_THRESHOLD,
...viewabilityConfig,
},
onViewableItemsChanged: _onViewableItemsChanged,
// debug: true, // for debug
testID: e2eID,
};
const { width, height } = useWindowDimensions();
if (props.getItemLayout === undefined) {
const itemDimension = vertical ? height : width;
flatListProps.getItemLayout = (__data, ItemIndex: number) => ({
length: itemDimension,
offset: itemDimension * ItemIndex,
index: ItemIndex,
});
}
if (Platform.OS === 'web') {
// TODO: do we need this anymore? check 3.1.0
(flatListProps as any).dataSet = { 'paging-enabled-fix': true };
}
if (useReactNativeGestureHandler) {
try {
FlatList = require('react-native-gesture-handler').FlatList;
} catch (error) {
console.warn(
"react-native-gesture-handler isn't installed, please install it or remove `useReactNativeGestureHandler`",
);
}
}
return (
<React.Fragment>
<FlatList {...flatListProps} />
{showPagination ? (
<PaginationComponent
size={size}
paginationIndex={currentIndexes.index}
scrollToIndex={(params: ScrollToIndex) => {
_scrollToIndex(params);
}}
paginationActiveColor={paginationActiveColor}
paginationDefaultColor={paginationDefaultColor}
paginationStyle={paginationStyle}
paginationStyleItem={paginationStyleItem}
paginationStyleItemActive={paginationStyleItemActive}
paginationStyleItemInactive={paginationStyleItemInactive}
onPaginationSelectedIndex={onPaginationSelectedIndex}
paginationTapDisabled={paginationTapDisabled}
e2eID={e2eID}
/>
) : null}
</React.Fragment>
);
},
);
// https://gist.github.com/Venryx/7cff24b17867da305fff12c6f8ef6f96
type Handle<T> = T extends React.ForwardRefExoticComponent<React.RefAttributes<infer T2>>
? T2
: never;
export type SwiperFlatList = Handle<typeof SwiperFlatListWithGestureHandler>;