react-native-reorderable-list 0.3.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2021 Omar Mahili
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,138 @@
1
+ # React Native Reorderable List
2
+
3
+ A reorderable list for React Native applications, powered by Reanimated 2 🚀
4
+
5
+ ![Example](https://media.giphy.com/media/EVQOjtGx61QS8s9Y0z/giphy.gif)
6
+
7
+ ## Install
8
+
9
+ ### Npm
10
+
11
+ ```
12
+ npm install --save react-native-reorderable-list
13
+ ```
14
+
15
+ ### Yarn
16
+
17
+ ```
18
+ yarn add react-native-reorderable-list
19
+ ```
20
+
21
+ Then you need to install these two peer dependencies:
22
+
23
+ - [**React Native Reanimated**](https://docs.swmansion.com/react-native-reanimated/docs/fundamentals/installation) >=2.2.0
24
+ - [**React Native Gesture Handler**](https://docs.swmansion.com/react-native-gesture-handler/docs/#installation) >=1.10.0
25
+
26
+ So head down to their docs and follow their instructions.
27
+
28
+ ## API
29
+
30
+ This component uses a [FlatList](https://reactnative.dev/docs/flatlist) and it extends its props. See [Known Limitations](#known-limitations) for unsupported props.
31
+
32
+ Additional props:
33
+
34
+ | Prop | Type | Required | Default | Description |
35
+ |---------------------------|---------------------------------------|------------|-----------|-------------------------------------------------------|
36
+ | renderItem | `(info: {item: T, index: number, separators: ItemSeparators, drag?: () => void, isDragged?: boolean}) => ReactElement` | yes | | Renders into the list an item from data. The function `drag` needs to be called when the drag gesture should be enabled, for example `onLongPress` event. The property `isDragged` becomes true for the dragged item. |
37
+ | onReorder | `(event: {fromIndex: number, toIndex: number}) => void` | yes | | Function called when an item is released and the list is reordered. |
38
+ | containerStyle | `StyleProp<ViewStyle>` | no | | Style for the FlatList container. |
39
+ | scrollAreaSize | `number` | no | `0.1` | Portion at the extremeties of the list which triggers scrolling when dragging an item. Accepts a value between `0` and `0.5`. |
40
+ | scrollSpeed | `number` | no | `2` | Speed at which the list scrolls. |
41
+ | dragScale | `number` | no | `1` | Size ratio to which an item scales when dragged. |
42
+
43
+ ## Known Limitations
44
+
45
+ At the moment it doesn't support these FlatList props:
46
+
47
+ - ```horizontal```
48
+ - ```onScroll```
49
+ - ```scrollEventThrottle```
50
+
51
+ ## Usage
52
+
53
+ ```typescript
54
+ import React, {useState} from 'react';
55
+ import {Pressable, StyleSheet, Text} from 'react-native';
56
+ import ReorderableList, {
57
+ ReorderableListRenderItemInfo,
58
+ ReorderableListReorderEvent,
59
+ } from 'react-native-reorderable-list';
60
+
61
+ interface CardInfo {
62
+ id: string;
63
+ color: string;
64
+ height: number;
65
+ }
66
+
67
+ interface CardProps extends CardInfo {
68
+ drag?: () => void;
69
+ isDragged?: boolean;
70
+ }
71
+
72
+ const list: CardInfo[] = [
73
+ {id: '0', color: 'red', height: 100},
74
+ {id: '1', color: 'blue', height: 150},
75
+ {id: '2', color: 'green', height: 80},
76
+ {id: '3', color: 'violet', height: 100},
77
+ {id: '4', color: 'orange', height: 120},
78
+ {id: '5', color: 'coral', height: 100},
79
+ {id: '6', color: 'purple', height: 110},
80
+ {id: '7', color: 'chocolate', height: 80},
81
+ {id: '8', color: 'crimson', height: 90},
82
+ {id: '9', color: 'seagreen', height: 90},
83
+ ];
84
+
85
+ const Card: React.FC<CardProps> = React.memo(
86
+ ({id, color, height, drag, isDragged}) => (
87
+ <Pressable
88
+ style={[styles.card, isDragged && styles.dragged, {height}]}
89
+ onLongPress={drag}>
90
+ <Text style={[styles.text, {color}]}>Card {id}</Text>
91
+ </Pressable>
92
+ ),
93
+ );
94
+
95
+ const App = () => {
96
+ const [data, setData] = useState(list);
97
+
98
+ const renderItem = (
99
+ {item, ...rest}: ReorderableListRenderItemInfo<CardInfo>,
100
+ ) => <Card {...item} {...rest} />;
101
+
102
+ const handleReorder = ({fromIndex, toIndex}: ReorderableListReorderEvent) => {
103
+ const newData = [...data];
104
+ newData.splice(toIndex, 0, newData.splice(fromIndex, 1)[0]);
105
+ setData(newData);
106
+ };
107
+
108
+ return (
109
+ <ReorderableList
110
+ data={data}
111
+ onReorder={handleReorder}
112
+ renderItem={renderItem}
113
+ keyExtractor={(item: CardInfo) => item.id}
114
+ dragScale={1.025}
115
+ />
116
+ );
117
+ };
118
+
119
+ const styles = StyleSheet.create({
120
+ card: {
121
+ justifyContent: 'center',
122
+ alignItems: 'center',
123
+ margin: 6,
124
+ borderRadius: 5,
125
+ backgroundColor: 'white',
126
+ borderWidth: 1,
127
+ borderColor: '#ddd',
128
+ },
129
+ dragged: {
130
+ opacity: 0.7,
131
+ },
132
+ text: {
133
+ fontSize: 20,
134
+ },
135
+ });
136
+
137
+ export default App;
138
+ ```
@@ -0,0 +1,7 @@
1
+ import React from 'react';
2
+ import { FlatListProps } from 'react-native';
3
+ import { ReorderableListProps } from '../types/props';
4
+ declare const _default: <T>(props: ReorderableListProps<T> & {
5
+ ref?: React.ForwardedRef<FlatListProps<T>> | undefined;
6
+ }) => React.ReactElement;
7
+ export default _default;
@@ -0,0 +1,311 @@
1
+ var __rest = (this && this.__rest) || function (s, e) {
2
+ var t = {};
3
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
4
+ t[p] = s[p];
5
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
6
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
7
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
8
+ t[p[i]] = s[p[i]];
9
+ }
10
+ return t;
11
+ };
12
+ import React, { useEffect, useRef, useState, useCallback } from 'react';
13
+ import { FlatList, StatusBar, unstable_batchedUpdates, } from 'react-native';
14
+ import { NativeViewGestureHandler, PanGestureHandler, State, } from 'react-native-gesture-handler';
15
+ import Animated, { useAnimatedGestureHandler, useSharedValue, useAnimatedReaction, runOnJS, useAnimatedStyle, useAnimatedRef, useAnimatedScrollHandler, scrollTo, withTiming, Easing, runOnUI, } from 'react-native-reanimated';
16
+ import composeRefs from '@seznam/compose-react-refs';
17
+ import memoize from 'fast-memoize';
18
+ import ReorderableListItem from './ReorderableListItem';
19
+ import useAnimatedSharedValues from '../hooks/useAnimatedSharedValues';
20
+ import { ReorderableListState } from '../types/misc';
21
+ const AnimatedFlatList = Animated.createAnimatedComponent(FlatList);
22
+ const ReorderableList = (_a, ref) => {
23
+ var { data, containerStyle, scrollAreaSize = 0.1, scrollSpeed = 2, dragScale = 1, renderItem, onLayout, onReorder, keyExtractor } = _a, rest = __rest(_a, ["data", "containerStyle", "scrollAreaSize", "scrollSpeed", "dragScale", "renderItem", "onLayout", "onReorder", "keyExtractor"]);
24
+ const container = useAnimatedRef();
25
+ const flatList = useAnimatedRef();
26
+ const nativeHandler = useRef(null);
27
+ const itemSeparators = useRef([]);
28
+ const gestureState = useSharedValue(State.UNDETERMINED);
29
+ const currentY = useSharedValue(0);
30
+ const startY = useSharedValue(0);
31
+ const containerPositionX = useSharedValue(0);
32
+ const containerPositionY = useSharedValue(0);
33
+ const scrollOffset = useSharedValue(0);
34
+ const itemOffsets = useAnimatedSharedValues(() => ({ length: 0, offset: 0 }), data.length);
35
+ const topMoveThreshold = useSharedValue(0);
36
+ const bottomMoveThreshold = useSharedValue(0);
37
+ const flatListHeight = useSharedValue(0);
38
+ const offsetY = useSharedValue(0);
39
+ const draggedTranslateY = useSharedValue(null);
40
+ const currentIndex = useSharedValue(-1);
41
+ const draggedIndex = useSharedValue(-1);
42
+ const draggedInfoIndex = useSharedValue(-1);
43
+ const state = useSharedValue(ReorderableListState.IDLE);
44
+ const autoScrollOffset = useSharedValue(-1);
45
+ const autoScrollSpeed = useSharedValue(Math.max(0, scrollSpeed));
46
+ const enabledOpacity = useSharedValue(false);
47
+ const draggedItemScale = useSharedValue(1);
48
+ const [dragged, setDragged] = useState(false);
49
+ const relativeToContainer = (y, x) => {
50
+ 'worklet';
51
+ return {
52
+ y: y - containerPositionY.value - (StatusBar.currentHeight || 0),
53
+ x: x - containerPositionX.value,
54
+ };
55
+ };
56
+ const handleGestureEvent = useAnimatedGestureHandler({
57
+ onStart: (e, ctx) => {
58
+ if (state.value !== ReorderableListState.RELEASING) {
59
+ const { y } = relativeToContainer(e.absoluteY, e.absoluteX);
60
+ ctx.startY = y;
61
+ startY.value = y;
62
+ currentY.value = y;
63
+ gestureState.value = e.state;
64
+ }
65
+ },
66
+ onActive: (e, ctx) => {
67
+ if (state.value !== ReorderableListState.RELEASING) {
68
+ currentY.value = ctx.startY + e.translationY;
69
+ gestureState.value = e.state;
70
+ }
71
+ },
72
+ onEnd: (e) => (gestureState.value = e.state),
73
+ onFinish: (e) => (gestureState.value = e.state),
74
+ onCancel: (e) => (gestureState.value = e.state),
75
+ onFail: (e) => (gestureState.value = e.state),
76
+ });
77
+ useEffect(() => {
78
+ if (!dragged) {
79
+ runOnUI(() => {
80
+ 'worklet';
81
+ state.value = ReorderableListState.IDLE;
82
+ })();
83
+ }
84
+ }, [dragged, state, enabledOpacity]);
85
+ useEffect(() => {
86
+ runOnUI(() => {
87
+ 'worklet';
88
+ enabledOpacity.value = dragged;
89
+ if (dragged) {
90
+ draggedItemScale.value = withTiming(dragScale, {
91
+ duration: 100,
92
+ easing: Easing.out(Easing.ease),
93
+ });
94
+ }
95
+ })();
96
+ }, [dragged, draggedItemScale, enabledOpacity, dragScale]);
97
+ const enableDragged = useCallback((enabled) => {
98
+ flatList.current.setNativeProps({ scrollEnabled: !enabled });
99
+ setDragged(enabled);
100
+ }, [setDragged, flatList]);
101
+ const reorder = (fromIndex, toIndex) => {
102
+ if (fromIndex !== toIndex) {
103
+ unstable_batchedUpdates(() => {
104
+ onReorder({ fromIndex, toIndex });
105
+ enableDragged(false);
106
+ });
107
+ }
108
+ else {
109
+ enableDragged(false);
110
+ }
111
+ };
112
+ const endDrag = () => {
113
+ 'worklet';
114
+ const draggedIndexTemp = draggedIndex.value;
115
+ const currentIndexTemp = currentIndex.value;
116
+ draggedIndex.value = -1;
117
+ currentIndex.value = -1;
118
+ enabledOpacity.value = false;
119
+ draggedInfoIndex.value = currentIndexTemp;
120
+ runOnJS(reorder)(draggedIndexTemp, currentIndexTemp);
121
+ };
122
+ const getIndexFromY = (y, scrollY) => {
123
+ 'worklet';
124
+ const maxOffset = itemOffsets[itemOffsets.length - 1].value;
125
+ const relativeY = Math.max(0, Math.min((scrollY || scrollOffset.value) + y, maxOffset.offset + maxOffset.length));
126
+ const index = itemOffsets.findIndex((x, i) => ((x === null || x === void 0 ? void 0 : x.value.offset) && i === 0 && relativeY < x.value.offset) ||
127
+ (i === itemOffsets.length - 1 && relativeY > x.value.offset) ||
128
+ (relativeY >= x.value.offset &&
129
+ relativeY <= x.value.offset + x.value.length));
130
+ return { index, relativeY };
131
+ };
132
+ useAnimatedReaction(() => gestureState.value, () => {
133
+ if (gestureState.value !== State.ACTIVE &&
134
+ gestureState.value !== State.BEGAN &&
135
+ (state.value === ReorderableListState.DRAGGING ||
136
+ state.value === ReorderableListState.AUTO_SCROLL)) {
137
+ state.value = ReorderableListState.RELEASING;
138
+ const offsetCorrection = currentIndex.value > draggedIndex.value
139
+ ? itemOffsets[currentIndex.value].value.length -
140
+ itemOffsets[draggedIndex.value].value.length
141
+ : 0;
142
+ const newTopPosition = itemOffsets[currentIndex.value].value.offset +
143
+ offsetCorrection -
144
+ scrollOffset.value;
145
+ const duration = 100;
146
+ draggedItemScale.value = withTiming(1, {
147
+ duration,
148
+ easing: Easing.out(Easing.ease),
149
+ }, () => {
150
+ if (draggedTranslateY.value === newTopPosition) {
151
+ endDrag();
152
+ }
153
+ });
154
+ if (draggedTranslateY.value !== newTopPosition) {
155
+ draggedTranslateY.value = withTiming(newTopPosition, {
156
+ duration,
157
+ easing: Easing.out(Easing.ease),
158
+ }, () => {
159
+ endDrag();
160
+ });
161
+ }
162
+ }
163
+ });
164
+ useAnimatedReaction(() => currentY.value, (y) => {
165
+ if (state.value === ReorderableListState.DRAGGING ||
166
+ state.value === ReorderableListState.AUTO_SCROLL) {
167
+ draggedTranslateY.value = y - offsetY.value;
168
+ const { index } = getIndexFromY(y);
169
+ currentIndex.value = index;
170
+ if (y <= topMoveThreshold.value || y >= bottomMoveThreshold.value) {
171
+ state.value = ReorderableListState.AUTO_SCROLL;
172
+ autoScrollOffset.value = scrollOffset.value;
173
+ }
174
+ else {
175
+ state.value = ReorderableListState.DRAGGING;
176
+ autoScrollOffset.value = -1;
177
+ }
178
+ }
179
+ });
180
+ useAnimatedReaction(() => autoScrollOffset.value, () => {
181
+ if (state.value === ReorderableListState.AUTO_SCROLL) {
182
+ let speed = 0;
183
+ if (currentY.value <= topMoveThreshold.value) {
184
+ speed = -autoScrollSpeed.value;
185
+ }
186
+ else if (currentY.value >= bottomMoveThreshold.value) {
187
+ speed = autoScrollSpeed.value;
188
+ }
189
+ if (speed !== 0) {
190
+ scrollTo(flatList, 0, autoScrollOffset.value + speed, true);
191
+ autoScrollOffset.value += speed;
192
+ }
193
+ const { index } = getIndexFromY(currentY.value, autoScrollOffset.value);
194
+ currentIndex.value = index;
195
+ }
196
+ });
197
+ const scrollHandler = useAnimatedScrollHandler({
198
+ onScroll: (e) => {
199
+ scrollOffset.value = e.contentOffset.y;
200
+ },
201
+ });
202
+ const handleItemLayout = useCallback(memoize((index) => (e) => {
203
+ itemOffsets[index].value = {
204
+ offset: e.nativeEvent.layout.y,
205
+ length: e.nativeEvent.layout.height,
206
+ };
207
+ }), [itemOffsets]);
208
+ const drag = useCallback(memoize((index) => () => runOnUI(() => {
209
+ 'worklet';
210
+ offsetY.value =
211
+ startY.value -
212
+ (itemOffsets[index].value.offset - scrollOffset.value);
213
+ draggedTranslateY.value = startY.value - offsetY.value;
214
+ draggedIndex.value = index;
215
+ draggedInfoIndex.value = index;
216
+ currentIndex.value = index;
217
+ state.value = ReorderableListState.DRAGGING;
218
+ runOnJS(enableDragged)(true);
219
+ })()), [
220
+ offsetY,
221
+ startY,
222
+ scrollOffset,
223
+ draggedTranslateY,
224
+ draggedIndex,
225
+ draggedInfoIndex,
226
+ currentIndex,
227
+ state,
228
+ itemOffsets,
229
+ enableDragged,
230
+ ]);
231
+ const renderAnimatedCell = useCallback((_a) => {
232
+ var { index, children } = _a, cellProps = __rest(_a, ["index", "children"]);
233
+ return (React.createElement(ReorderableListItem, { key: cellProps.keyExtractor
234
+ ? cellProps.keyExtractor(cellProps.data[index], index)
235
+ : index, index: index, currentIndex: currentIndex, draggedIndex: draggedIndex, itemOffsets: itemOffsets, enabledOpacity: enabledOpacity, onLayout: handleItemLayout(index) }, children));
236
+ }, [currentIndex, draggedIndex, itemOffsets, enabledOpacity, handleItemLayout]);
237
+ const renderDraggableItem = useCallback((info) => {
238
+ itemSeparators.current[info.index] = info.separators;
239
+ return renderItem(Object.assign(Object.assign({}, info), { drag: drag(info.index) }));
240
+ }, [renderItem, drag]);
241
+ const handleContainerLayout = () => {
242
+ container.current.measureInWindow((x, y) => {
243
+ containerPositionX.value = x;
244
+ containerPositionY.value = y;
245
+ });
246
+ };
247
+ const handleFlatListLayout = useCallback((e) => {
248
+ const { height } = e.nativeEvent.layout;
249
+ const portion = height * Math.max(0, Math.min(scrollAreaSize, 0.5));
250
+ topMoveThreshold.value = portion;
251
+ bottomMoveThreshold.value = height - portion;
252
+ flatListHeight.value = height;
253
+ if (onLayout) {
254
+ onLayout(e);
255
+ }
256
+ }, [
257
+ bottomMoveThreshold,
258
+ topMoveThreshold,
259
+ flatListHeight,
260
+ onLayout,
261
+ scrollAreaSize,
262
+ ]);
263
+ const draggedItemStyle = useAnimatedStyle(() => {
264
+ if (draggedTranslateY.value !== null) {
265
+ return {
266
+ transform: [
267
+ { translateY: draggedTranslateY.value },
268
+ { scale: draggedItemScale.value },
269
+ ],
270
+ };
271
+ }
272
+ return {};
273
+ });
274
+ const draggedItemInfo = {
275
+ index: draggedInfoIndex.value,
276
+ item: data[draggedInfoIndex.value],
277
+ separators: itemSeparators.current[draggedInfoIndex.value],
278
+ isDragged: true,
279
+ };
280
+ const draggedItemFallbackStyle = {
281
+ transform: itemOffsets[draggedInfoIndex.value]
282
+ ? [
283
+ {
284
+ translateY: itemOffsets[draggedInfoIndex.value].value.offset -
285
+ scrollOffset.value,
286
+ },
287
+ ]
288
+ : undefined,
289
+ };
290
+ return (React.createElement(PanGestureHandler, { maxPointers: 1, onGestureEvent: handleGestureEvent, onHandlerStateChange: handleGestureEvent, simultaneousHandlers: nativeHandler },
291
+ React.createElement(Animated.View, { ref: container, style: containerStyle, onLayout: handleContainerLayout },
292
+ React.createElement(NativeViewGestureHandler, { ref: nativeHandler },
293
+ React.createElement(AnimatedFlatList, Object.assign({}, rest, { ref: composeRefs(flatList, ref), data: data, CellRendererComponent: renderAnimatedCell, renderItem: renderDraggableItem, onLayout: handleFlatListLayout, onScroll: scrollHandler, keyExtractor: keyExtractor, scrollEventThrottle: 1, horizontal: false }))),
294
+ dragged && (React.createElement(Animated.View, { style: [
295
+ styles.draggedItem,
296
+ draggedItemFallbackStyle,
297
+ draggedItemStyle,
298
+ ] }, renderItem(draggedItemInfo))))));
299
+ };
300
+ const styles = {
301
+ draggedItem: {
302
+ position: 'absolute',
303
+ left: 0,
304
+ right: 0,
305
+ top: 0,
306
+ },
307
+ dragged: {
308
+ opacity: 0,
309
+ },
310
+ };
311
+ export default React.memo(React.forwardRef(ReorderableList));
@@ -0,0 +1,14 @@
1
+ import React from 'react';
2
+ import { ViewProps } from 'react-native';
3
+ import Animated from 'react-native-reanimated';
4
+ import { ItemOffset } from '../types/misc';
5
+ interface ReorderableListItemProps extends Animated.AnimateProps<ViewProps> {
6
+ index: number;
7
+ itemOffsets: Animated.SharedValue<ItemOffset>[];
8
+ draggedIndex: Animated.SharedValue<number>;
9
+ currentIndex: Animated.SharedValue<number>;
10
+ enabledOpacity: Animated.SharedValue<boolean>;
11
+ children: React.ReactNode;
12
+ }
13
+ declare const ReorderableListItem: React.FC<ReorderableListItemProps>;
14
+ export default ReorderableListItem;
@@ -0,0 +1,57 @@
1
+ var __rest = (this && this.__rest) || function (s, e) {
2
+ var t = {};
3
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
4
+ t[p] = s[p];
5
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
6
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
7
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
8
+ t[p[i]] = s[p[i]];
9
+ }
10
+ return t;
11
+ };
12
+ import React from 'react';
13
+ import Animated, { useAnimatedStyle, withTiming, Easing, useSharedValue, useAnimatedReaction, } from 'react-native-reanimated';
14
+ const ReorderableListItem = (_a) => {
15
+ var { index, itemOffsets, draggedIndex, currentIndex, enabledOpacity, children } = _a, rest = __rest(_a, ["index", "itemOffsets", "draggedIndex", "currentIndex", "enabledOpacity", "children"]);
16
+ const translateY = useSharedValue(0);
17
+ const opacity = useSharedValue(1);
18
+ useAnimatedReaction(() => currentIndex.value, () => {
19
+ if (currentIndex.value >= 0 && draggedIndex.value >= 0) {
20
+ const moveDown = currentIndex.value > draggedIndex.value;
21
+ const startMove = Math.min(draggedIndex.value, currentIndex.value);
22
+ const endMove = Math.max(draggedIndex.value, currentIndex.value);
23
+ let newValue = 0;
24
+ if (index === draggedIndex.value) {
25
+ for (let i = startMove; i < endMove; i++) {
26
+ newValue = moveDown
27
+ ? newValue + itemOffsets[i].value.length
28
+ : newValue - itemOffsets[i].value.length;
29
+ }
30
+ const offsetCorrection = moveDown
31
+ ? itemOffsets[currentIndex.value].value.length -
32
+ itemOffsets[draggedIndex.value].value.length
33
+ : 0;
34
+ newValue += offsetCorrection;
35
+ }
36
+ else if (index >= startMove && index <= endMove) {
37
+ const draggedHeight = itemOffsets[draggedIndex.value].value.length;
38
+ newValue = moveDown ? -draggedHeight : draggedHeight;
39
+ }
40
+ if (newValue !== translateY.value) {
41
+ translateY.value = withTiming(newValue, {
42
+ duration: 100,
43
+ easing: Easing.out(Easing.ease),
44
+ });
45
+ }
46
+ }
47
+ });
48
+ useAnimatedReaction(() => enabledOpacity.value, (enabled) => {
49
+ opacity.value = enabled && index === draggedIndex.value ? 0 : 1;
50
+ }, [index]);
51
+ const animatedStyle = useAnimatedStyle(() => ({
52
+ transform: [{ translateY: translateY.value }],
53
+ opacity: opacity.value,
54
+ }));
55
+ return (React.createElement(Animated.View, Object.assign({}, rest, { style: [rest.style, animatedStyle] }), children));
56
+ };
57
+ export default ReorderableListItem;
@@ -0,0 +1,3 @@
1
+ import Animated from 'react-native-reanimated';
2
+ declare function useAnimatedSharedValues<T>(initFunc: (index: number) => T, size: number, shrink?: boolean): Animated.SharedValue<T>[];
3
+ export default useAnimatedSharedValues;
@@ -0,0 +1,33 @@
1
+ import { useEffect, useRef } from 'react';
2
+ import { cancelAnimation, makeMutable } from 'react-native-reanimated';
3
+ function useAnimatedSharedValues(initFunc, size, shrink = true) {
4
+ const ref = useRef([]);
5
+ if (size !== 0 && ref.current.length === 0) {
6
+ ref.current = [];
7
+ for (let i = 0; i < size; i++) {
8
+ ref.current[i] = makeMutable(initFunc(i));
9
+ }
10
+ }
11
+ useEffect(() => {
12
+ if (size > ref.current.length) {
13
+ for (let i = ref.current.length; i < size; i++) {
14
+ ref.current[i] = makeMutable(initFunc(i));
15
+ }
16
+ }
17
+ else if (shrink && size < ref.current.length) {
18
+ for (let i = size; i < ref.current.length; i++) {
19
+ cancelAnimation(ref.current[i]);
20
+ }
21
+ ref.current.splice(size, ref.current.length - size);
22
+ }
23
+ }, [size, initFunc, shrink]);
24
+ useEffect(() => {
25
+ return () => {
26
+ for (let i = 0; i < ref.current.length; i++) {
27
+ cancelAnimation(ref.current[i]);
28
+ }
29
+ };
30
+ }, []);
31
+ return ref.current;
32
+ }
33
+ export default useAnimatedSharedValues;
@@ -0,0 +1,4 @@
1
+ import ReorderableList from './components/ReorderableList';
2
+ import { ReorderableListProps, ReorderableListRenderItemInfo, ReorderableListReorderEvent } from './types/props';
3
+ export { ReorderableListProps, ReorderableListRenderItemInfo, ReorderableListReorderEvent, };
4
+ export default ReorderableList;
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ import ReorderableList from './components/ReorderableList';
2
+ export default ReorderableList;
@@ -0,0 +1,15 @@
1
+ export interface ItemOffset {
2
+ length: number;
3
+ offset: number;
4
+ }
5
+ export interface ItemSeparators {
6
+ highlight: () => void;
7
+ unhighlight: () => void;
8
+ updateProps: (select: 'leading' | 'trailing', newProps: any) => void;
9
+ }
10
+ export declare enum ReorderableListState {
11
+ IDLE = 0,
12
+ DRAGGING = 1,
13
+ RELEASING = 2,
14
+ AUTO_SCROLL = 3
15
+ }
@@ -0,0 +1,7 @@
1
+ export var ReorderableListState;
2
+ (function (ReorderableListState) {
3
+ ReorderableListState[ReorderableListState["IDLE"] = 0] = "IDLE";
4
+ ReorderableListState[ReorderableListState["DRAGGING"] = 1] = "DRAGGING";
5
+ ReorderableListState[ReorderableListState["RELEASING"] = 2] = "RELEASING";
6
+ ReorderableListState[ReorderableListState["AUTO_SCROLL"] = 3] = "AUTO_SCROLL";
7
+ })(ReorderableListState || (ReorderableListState = {}));
@@ -0,0 +1,27 @@
1
+ /// <reference types="react" />
2
+ import { FlatListProps, ListRenderItemInfo, StyleProp, ViewStyle } from 'react-native';
3
+ import Animated from 'react-native-reanimated';
4
+ export interface CellProps<T> extends FlatListProps<T> {
5
+ index: number;
6
+ children?: React.ReactElement;
7
+ data: T[];
8
+ }
9
+ export interface ReorderableListRenderItemInfo<T> extends ListRenderItemInfo<T> {
10
+ drag?: () => void;
11
+ isDragged?: boolean;
12
+ }
13
+ export interface ReorderableListReorderEvent {
14
+ fromIndex: number;
15
+ toIndex: number;
16
+ }
17
+ declare type UnsupportedProps = 'horizontal' | 'onScroll' | 'scrollEventThrottle';
18
+ export interface ReorderableListProps<T> extends Omit<FlatListProps<T>, UnsupportedProps> {
19
+ data: T[];
20
+ containerStyle?: StyleProp<Animated.AnimateStyle<StyleProp<ViewStyle>>>;
21
+ scrollAreaSize?: number;
22
+ scrollSpeed?: number;
23
+ dragScale?: number;
24
+ renderItem: (info: ReorderableListRenderItemInfo<T>) => React.ReactElement;
25
+ onReorder: (event: ReorderableListReorderEvent) => void;
26
+ }
27
+ export {};
@@ -0,0 +1 @@
1
+ export {};
package/package.json ADDED
@@ -0,0 +1,56 @@
1
+ {
2
+ "name": "react-native-reorderable-list",
3
+ "version": "0.3.0",
4
+ "description": "Reorderable list for React Native applications, powered by Reanimated 2",
5
+ "scripts": {
6
+ "lint": "eslint ./src --ext .ts,.tsx",
7
+ "build": "tsc && tsc-alias"
8
+ },
9
+ "main": "dist/index.js",
10
+ "types": "dist/index.d.ts",
11
+ "files": [
12
+ "dist/*"
13
+ ],
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "https://github.com/omahili/react-native-reorderable-list.git"
17
+ },
18
+ "author": "Omar Mahili",
19
+ "license": "MIT",
20
+ "bugs": {
21
+ "url": "https://github.com/omahili/react-native-reorderable-list/issues"
22
+ },
23
+ "homepage": "https://github.com/omahili/react-native-reorderable-list#readme",
24
+ "dependencies": {
25
+ "@seznam/compose-react-refs": "^1.0.6",
26
+ "fast-memoize": "^2.5.2"
27
+ },
28
+ "devDependencies": {
29
+ "@react-native-community/eslint-config": "^3.0.1",
30
+ "@types/react": "^17.0.34",
31
+ "@types/react-native": "^0.66.2",
32
+ "@typescript-eslint/eslint-plugin": "^5.3.0",
33
+ "eslint": "^7.32.0",
34
+ "eslint-config-prettier": "^7.2.0",
35
+ "eslint-plugin-eslint-comments": "^3.1.2",
36
+ "eslint-plugin-flowtype": "2.50.3",
37
+ "eslint-plugin-import": "^2.25.2",
38
+ "eslint-plugin-jest": "22.4.1",
39
+ "eslint-plugin-prettier": "3.1.2",
40
+ "eslint-plugin-react": "^7.20.0",
41
+ "eslint-plugin-react-hooks": "^4.0.7",
42
+ "eslint-plugin-react-native": "^3.10.0",
43
+ "prettier": "^2.4.1",
44
+ "react": "^17.0.2",
45
+ "react-native": "^0.66.1",
46
+ "react-native-gesture-handler": "^1.10.3",
47
+ "react-native-reanimated": "^2.2.3",
48
+ "tsc-alias": "^1.4.0",
49
+ "typescript": "^4.4.4"
50
+ },
51
+ "peerDependencies": {
52
+ "react-native": ">=0.62.0",
53
+ "react-native-gesture-handler": ">=1.10.0",
54
+ "react-native-reanimated": ">=2.2.0"
55
+ }
56
+ }