react-native-drag-sort-list 1.0.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,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,282 @@
1
+
2
+ ![1](https://github.com/user-attachments/assets/622e6699-875f-4441-a067-9554e47091cc)
3
+
4
+ # react-native-drag-sort
5
+
6
+ 一个功能强大的 React Native 拖拽排序组件库,支持单列和多列布局,提供流畅的拖拽体验和自动滚动功能。
7
+
8
+ ## 功能特性
9
+
10
+ - ✅ **长按拖拽**:长按 500ms 后开始拖拽,提供视觉反馈(缩放效果)
11
+ - ✅ **单列/多列布局**:支持自定义列数,灵活布局
12
+ - ✅ **自动滚动**:拖拽到边缘时自动触发外层 ScrollView 滚动
13
+ - ✅ **流畅动画**:使用 Animated API 实现平滑的位置切换动画
14
+ - ✅ **ScrollView 联动**:支持与外层 ScrollView 无缝集成
15
+ - ✅ **自定义间距**:支持设置行间距和列间距
16
+ - ✅ **性能优化**:使用 memo 和 lodash 进行性能优化
17
+
18
+ ## 安装
19
+
20
+ ### 前置依赖
21
+
22
+ 本组件依赖 `react-native-gesture-handler` `lodash`,请先安装:
23
+
24
+ ```bash
25
+ npm install react-native-gesture-handler
26
+ npm install lodash
27
+ # 或
28
+ yarn add react-native-gesture-handler
29
+ yarn add lodash
30
+ ```
31
+
32
+ ### iOS 安装
33
+
34
+ ```bash
35
+ cd ios && pod install && cd ..
36
+ ```
37
+
38
+ ### 使用组件
39
+
40
+ ```bash
41
+ # 将组件文件复制到你的项目中,或通过 npm link 等方式引入
42
+ ```
43
+
44
+ ## 使用方法
45
+
46
+ ### 基础用法(单列)
47
+
48
+ ```javascript
49
+ import React from 'react';
50
+ import { Dimensions, View, Text } from 'react-native';
51
+ import DragSortView from './lib/DragSortView';
52
+
53
+ const windowWidth = Dimensions.get('window').width;
54
+
55
+ const MyComponent = () => {
56
+ const [data, setData] = React.useState(['1', '2', '3', '4', '5']);
57
+
58
+ const renderItem = (item, index) => {
59
+ return (
60
+ <View style={{
61
+ width: windowWidth,
62
+ height: 50,
63
+ backgroundColor: 'red',
64
+ justifyContent: 'center',
65
+ alignItems: 'center'
66
+ }}>
67
+ <Text>{item}</Text>
68
+ </View>
69
+ );
70
+ };
71
+
72
+ return (
73
+ <DragSortView
74
+ column={1}
75
+ childrenWidth={windowWidth}
76
+ childrenHeight={50}
77
+ renderItem={renderItem}
78
+ rowSpace={10}
79
+ dataSource={data}
80
+ onDragEnd={(from, to, newData) => {
81
+ console.log('从位置', from, '移动到位置', to);
82
+ setData(newData);
83
+ }}
84
+ />
85
+ );
86
+ };
87
+ ```
88
+
89
+ ### 多列布局
90
+
91
+ ```javascript
92
+ import React from 'react';
93
+ import { Dimensions, View, Text } from 'react-native';
94
+ import DragSortView from './lib/DragSortView';
95
+
96
+ const windowWidth = Dimensions.get('window').width;
97
+
98
+ const MyComponent = () => {
99
+ const [data, setData] = React.useState(['1', '2', '3', '4', '5', '6']);
100
+
101
+ const renderItem = (item, index) => {
102
+ return (
103
+ <View style={{
104
+ width: (windowWidth - 10) / 2,
105
+ height: 50,
106
+ backgroundColor: 'blue',
107
+ justifyContent: 'center',
108
+ alignItems: 'center'
109
+ }}>
110
+ <Text>{item}</Text>
111
+ </View>
112
+ );
113
+ };
114
+
115
+ return (
116
+ <DragSortView
117
+ column={2}
118
+ childrenWidth={(windowWidth - 10) / 2}
119
+ childrenHeight={50}
120
+ renderItem={renderItem}
121
+ rowSpace={10}
122
+ columnSpace={10}
123
+ dataSource={data}
124
+ onDragEnd={(from, to, newData) => {
125
+ setData(newData);
126
+ }}
127
+ />
128
+ );
129
+ };
130
+ ```
131
+
132
+ ### 与 ScrollView 集成
133
+
134
+ 在 ScrollView 中使用时,需要提供三个 ref 来支持自动滚动功能。你可以在同一个 ScrollView 中放置多个 DragSortView:
135
+
136
+ ```javascript
137
+ import React, { useRef } from 'react';
138
+ import { Dimensions, ScrollView, Text, View } from 'react-native';
139
+ import DragSortView from './lib/DragSortView';
140
+
141
+ const windowWidth = Dimensions.get('window').width;
142
+
143
+ const MyComponent = () => {
144
+ const scrollViewRef = useRef(null); // 最外层 scrollView
145
+ const scrollYRef = useRef(0); // 已经滚动的距离
146
+ const scrollViewHeightRef = useRef(0); // 页面展示视图大小
147
+
148
+ const renderOneItem = (item, index) => {
149
+ return (
150
+ <View style={{
151
+ width: windowWidth,
152
+ height: 50,
153
+ backgroundColor: 'red',
154
+ justifyContent: 'center',
155
+ alignItems: 'center'
156
+ }}>
157
+ <Text>{item}</Text>
158
+ </View>
159
+ );
160
+ };
161
+
162
+ const renderTwoItem = (item, index) => {
163
+ return (
164
+ <View style={{
165
+ width: (windowWidth - 10) / 2,
166
+ height: 50,
167
+ backgroundColor: 'blue',
168
+ justifyContent: 'center',
169
+ alignItems: 'center'
170
+ }}>
171
+ <Text>{item}</Text>
172
+ </View>
173
+ );
174
+ };
175
+
176
+ return (
177
+ <View
178
+ onLayout={(e) => {
179
+ scrollViewHeightRef.current = e.nativeEvent.layout.height;
180
+ }}
181
+ >
182
+ <ScrollView
183
+ bounces={false}
184
+ scrollEventThrottle={16}
185
+ ref={scrollViewRef}
186
+ onScroll={(e) => {
187
+ scrollYRef.current = e.nativeEvent.contentOffset.y;
188
+ }}
189
+ >
190
+ {/* 单列拖拽列表 */}
191
+ <DragSortView
192
+ scrollYRef={scrollYRef}
193
+ scrollViewRef={scrollViewRef}
194
+ scrollViewHeightRef={scrollViewHeightRef}
195
+ column={1}
196
+ childrenWidth={windowWidth}
197
+ childrenHeight={50}
198
+ renderItem={renderOneItem}
199
+ rowSpace={10}
200
+ dataSource={['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']}
201
+ />
202
+
203
+ {/* 多列拖拽列表 */}
204
+ <DragSortView
205
+ scrollYRef={scrollYRef}
206
+ scrollViewRef={scrollViewRef}
207
+ scrollViewHeightRef={scrollViewHeightRef}
208
+ column={2}
209
+ childrenWidth={(windowWidth - 10) / 2}
210
+ childrenHeight={50}
211
+ renderItem={renderTwoItem}
212
+ rowSpace={10}
213
+ columnSpace={10}
214
+ dataSource={['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']}
215
+ />
216
+ </ScrollView>
217
+ </View>
218
+ );
219
+ };
220
+ ```
221
+
222
+ ## API 文档
223
+
224
+ ### DragSortView Props
225
+
226
+ | 属性名 | 类型 | 必填 | 默认值 | 说明 |
227
+ |--------|------|------|--------|------|
228
+ | `dataSource` | `Array` | ✅ | - | 数据源数组 |
229
+ | `renderItem` | `Function(item, index)` | ✅ | - | 渲染每个列表项的函数 |
230
+ | `childrenWidth` | `Number` | ✅ | - | 子元素宽度 |
231
+ | `childrenHeight` | `Number` | ✅ | - | 子元素高度 |
232
+ | `column` | `Number` | ❌ | `1` | 列数 |
233
+ | `rowSpace` | `Number` | ❌ | `0` | 行间距 |
234
+ | `columnSpace` | `Number` | ❌ | `0` | 列间距 |
235
+ | `keyStr` | `String` | ❌ | - | 作为列表 key 的关键字(用于优化渲染) |
236
+ | `onDragStart` | `Function()` | ❌ | - | 拖拽开始回调 |
237
+ | `onDragEnd` | `Function(from, to, newData)` | ❌ | - | 拖拽结束回调,参数:原始索引、新索引、新数据数组 |
238
+ | `parentYRef` | `Ref<Number>` | ❌ | - | 如果当前拖拽视图在一个容器中,则需要这个容器在 scrollView 的 y 位置 |
239
+ | `scrollYRef` | `Ref<Number>` | ❌ | - | 外层 ScrollView 滚动距离的 ref |
240
+ | `scrollViewRef` | `Ref<ScrollView>` | ❌ | - | 外层 ScrollView 的 ref |
241
+ | `scrollViewHeightRef` | `Ref<Number>` | ❌ | - | 外层 ScrollView 视图高度的 ref |
242
+ | `triggerTop` | `Number` | ❌ | `200` | 距离页面顶部多少距离触发自动向上滚动 |
243
+ | `triggerBottom` | `Number` | ❌ | `屏幕高度 - 200` | 距离页面顶部多少距离触发自动向下滚动 |
244
+
245
+ ### onDragEnd 回调参数
246
+
247
+ - `from` (Number): 拖拽元素的原始索引位置
248
+ - `to` (Number): 拖拽元素的新索引位置
249
+ - `newData` (Array): 重新排序后的新数据数组
250
+
251
+ ## 注意事项
252
+
253
+ 1. **手势库依赖**:确保已正确安装和配置 `react-native-gesture-handler`,并在应用入口处导入:
254
+ ```javascript
255
+ import 'react-native-gesture-handler';
256
+ ```
257
+
258
+ 2. **ScrollView 集成**:如果需要在 ScrollView 中使用,必须提供 `scrollYRef`、`scrollViewRef` 和 `scrollViewHeightRef` 三个 ref,否则自动滚动功能将无法正常工作。
259
+
260
+ 3. **性能优化**:组件内部使用 `memo` 进行优化,但建议为 `dataSource` 中的每个对象提供唯一的 `keyStr` 属性以进一步提升性能。
261
+
262
+ 4. **平台差异**:
263
+ - iOS 和 Android 的滚动速度和距离有细微差异(iOS: 10ms/2px, Android: 20ms/5px)
264
+ - 可通过修改 `DragSortView.js` 中的 `TIME` 和 `DISTANCE` 常量进行调整
265
+
266
+ 5. **长按时间**:默认长按 500ms 后开始拖拽,可通过修改 `DragItemContainer.js` 中的 `minDuration` 和 `activateAfterLongPress` 进行调整。
267
+
268
+ ## 示例项目
269
+
270
+ 项目包含两个测试文件,展示了不同的使用场景:
271
+
272
+ - `TestDragSort.js`:基础单列拖拽示例
273
+ - `TestMoreDragSort.js`:ScrollView 集成和多列布局示例
274
+
275
+ ## 许可证
276
+
277
+ ISC
278
+
279
+ ## 作者
280
+
281
+ liushun
282
+
package/index.js ADDED
@@ -0,0 +1,10 @@
1
+ /**
2
+ * @file index.js
3
+ * @description Main entry point for react-native-drag-sort
4
+ * @author liushun
5
+ */
6
+
7
+ import DragSortView from "./lib/DragSortView";
8
+
9
+ export default DragSortView;
10
+ export { DragSortView };
@@ -0,0 +1,70 @@
1
+ /**
2
+ * @file DragItemContainer.js
3
+ * @description
4
+ * @author liushun
5
+ * @created 2025/12/24 14:28
6
+ * @lastModified 2025/12/24 14:28
7
+ */
8
+
9
+
10
+
11
+ import React, {useRef} from "react";
12
+ import { Animated, Dimensions, Easing, StyleSheet, View } from 'react-native'
13
+ import { Gesture, GestureDetector, GestureHandlerRootView } from 'react-native-gesture-handler'
14
+
15
+
16
+ const DragItemContainer = (props) => {
17
+
18
+ const {x, y, childrenHeight, childrenWidth, onDragStart, onDragMove, onDragEnd} = props;
19
+ const [zIndex, setZIndex] = React.useState(0);
20
+
21
+ const itemScaleAnime = useRef(new Animated.Value(1)).current;
22
+
23
+ const isDragging = useRef(false);
24
+
25
+ //长按手势处理
26
+ const longPress = Gesture.LongPress().onStart((e)=>{
27
+ itemScaleAnime.setValue(1.1)
28
+ setZIndex(1000);
29
+ onDragStart?.(e);
30
+ isDragging.current = true;
31
+ }).minDuration(500).enabled(true);
32
+
33
+ //处理滑动和抬起手势
34
+ const pan = Gesture.Pan().onUpdate((e) => {
35
+ if(isDragging.current){
36
+ onDragMove?.(e);
37
+ }
38
+ }).onTouchesUp((e)=>{ //停止拖拽
39
+ isDragging.current = false;
40
+ itemScaleAnime.setValue(1)
41
+ setZIndex(0);
42
+ onDragEnd?.(e);
43
+ }).activateAfterLongPress(505).enabled(true);
44
+
45
+ //手势合并
46
+ const composed = Gesture.Simultaneous(longPress, pan);
47
+
48
+
49
+ return (
50
+ <GestureDetector gesture={composed}>
51
+ <Animated.View style={[
52
+ styles.container,
53
+ {zIndex},
54
+ {top: y, left: x},
55
+ {width: childrenWidth, height: childrenHeight},
56
+ {transform: [{ scale: itemScaleAnime }],}
57
+ ]}>
58
+ {props.children}
59
+ </Animated.View>
60
+ </GestureDetector>
61
+ )
62
+ }
63
+
64
+ export default DragItemContainer;
65
+
66
+ const styles = StyleSheet.create({
67
+ container: {
68
+ position: 'absolute',
69
+ }
70
+ })
@@ -0,0 +1,351 @@
1
+ /**
2
+ * @file DragSortView.js
3
+ * @description
4
+ * @author liushun
5
+ * @created 2025/12/24 14:29
6
+ * @lastModified 2025/12/24 14:29
7
+ */
8
+
9
+
10
+ import React, {useState, useEffect, useRef, useMemo, useCallback, forwardRef, useImperativeHandle, memo} from 'react'
11
+ import { Animated, Dimensions, Easing, StyleSheet, View, Platform } from 'react-native'
12
+ import { Gesture, GestureDetector, GestureHandlerRootView } from 'react-native-gesture-handler'
13
+ import DragItemContainer from "./DragItemContainer";
14
+ import _ from "lodash";
15
+
16
+ const TOP = 200; //上边距
17
+ const BOTTOM = Dimensions.get('screen').height - 200; //下边距
18
+
19
+ const TIME = Platform.OS === 'ios'?10:25; //每次滚动的时间间隔
20
+ const DISTANCE = Platform.OS === 'ios'?2:4; //每次滚动的距离
21
+
22
+ const MemoDragSortableView = (props, ref) => {
23
+
24
+ const {
25
+ keyStr, //作为列表key 的关键字
26
+ dataSource, //数组数据
27
+ childrenWidth, //子元素宽度
28
+ childrenHeight, //子元素高度
29
+ rowSpace = 0, //行间距
30
+ columnSpace = 0, //列间距
31
+ column = 1, //有几列
32
+ onDragEnd, //拖拽结束
33
+ onDragStart, //拖拽开始
34
+ parentYRef, //如果当前拖拽视图在一个容器中,则需要这个容器在 scrollView 的 y 位置
35
+ scrollYRef, //外层 scrollView 滚动的距离
36
+ scrollViewRef, //外层 scrollView 的索引
37
+ scrollViewHeightRef, //外层 scrollView 视图高度
38
+ triggerTop = TOP, // 距离页面顶部小于多少距离触发外层滚动
39
+ triggerBottom = BOTTOM, //距离页面顶部大于多少距离触发外层滚动
40
+ } = props;
41
+
42
+ const [dragSourceData, setDragSourceData] = React.useState([]);
43
+ const [totalHeight, setTotalHeight] = React.useState(0);
44
+
45
+ const scrollTimeRef = useRef(null); //外层 scrollView 自动滚动定时
46
+ const yRef = useRef(null);
47
+ const heightRef = useRef(null);
48
+
49
+ //表示当前在拖拽的元素在原始数据的索引位置,特别注释元素在原始数据的索引是不变的,变的是元素对象中的索引值
50
+ const dragCurrentRef = useRef(null);
51
+
52
+ //拖拽元素上次拖拽的位置
53
+ const lastDragY = useRef(0);
54
+
55
+ const lastScrollYRef = useRef(0);
56
+
57
+ //先构造拖拽所需数据, 由于改变位置是动画,所以不 setState 就可以改变位置
58
+ useEffect(()=>{
59
+
60
+ let arr = [];
61
+ dataSource?.forEach((item, index)=>{
62
+ const top = getTopByIndex(index);
63
+ const left = getLeftByIndex(index);
64
+ let obj = {
65
+ x: new Animated.Value(left), //拖拽中的坐标
66
+ y: new Animated.Value(top),
67
+ changeIndex: index, //拖拽变化后的位置索引
68
+ originIndex: index, //拖拽前的位置索引
69
+ yValue: top, //这个值用来外部改变拖拽元素的位置
70
+ value: item,
71
+ }
72
+ arr.push(obj);
73
+ })
74
+ setTotalHeight(getChildRealHeight()*Math.ceil(dataSource?.length/column));
75
+ setDragSourceData(arr);
76
+ },[dataSource, column])
77
+
78
+ const getChildRealHeight = () => {
79
+ return (rowSpace + childrenHeight)
80
+ }
81
+
82
+ //根据索引获取顶部距离
83
+ const getTopByIndex = (index) => {
84
+ return Math.floor(index / column) * getChildRealHeight();
85
+ }
86
+
87
+ const getChildRealWidth = () => {
88
+ return (columnSpace + childrenWidth)
89
+ }
90
+
91
+ //根据索引获取左边距离
92
+ const getLeftByIndex = (index) => {
93
+ return index%column * getChildRealWidth();
94
+ }
95
+
96
+ const clearScrollInterval = () => {
97
+ scrollTimeRef.current&&clearInterval(scrollTimeRef.current);
98
+ scrollTimeRef.current = null;
99
+ }
100
+
101
+ const startScroll = (distance) => {
102
+ if(!scrollTimeRef.current){
103
+ clearScrollInterval();
104
+ scrollTimeRef.current = setInterval(() => {
105
+ //判断是否应该滚动,还是停止滚动
106
+ if(Math.floor(scrollYRef?.current) <= Math.ceil(yRef.current + (parentYRef?parentYRef?.current:0)) && distance < 0){
107
+ stopScroll();
108
+ return;
109
+ }
110
+
111
+ if(Math.ceil(scrollYRef?.current) >= Math.floor((yRef.current + (parentYRef?parentYRef?.current:0) + heightRef.current) - scrollViewHeightRef?.current) && distance > 0){
112
+ stopScroll();
113
+ return;
114
+ }
115
+
116
+ scrollViewRef?.current.scrollTo({
117
+ y: scrollYRef?.current + distance,
118
+ animated: false,
119
+ })
120
+ setDragOffSet(scrollYRef?.current - lastScrollYRef.current);
121
+ lastScrollYRef.current = scrollYRef?.current;
122
+ },TIME)
123
+ }
124
+ }
125
+
126
+ const setDragOffSet = (distance) => {
127
+ const dragItem = dragSourceData[dragCurrentRef.current];
128
+ dragItem.yValue+=distance;
129
+ dragItem.y.setValue(dragItem.yValue)
130
+ }
131
+
132
+ const stopScroll = () => {
133
+ clearScrollInterval();
134
+ }
135
+
136
+ const isOutScrollView = () => {
137
+ return scrollViewRef?.current && scrollViewHeightRef?.current && scrollYRef?.current >= 0;
138
+ }
139
+
140
+ const onTopReached = () => {
141
+ //判断外层是否是滚动视图
142
+ if(isOutScrollView()){
143
+ startScroll(-DISTANCE)
144
+ }
145
+ }
146
+
147
+ const onBottomReached = () => {
148
+ if(isOutScrollView()){
149
+ startScroll(DISTANCE)
150
+ }
151
+ }
152
+
153
+ const onCentered = () => {
154
+ if(isOutScrollView()){
155
+ stopScroll();
156
+ }
157
+ }
158
+
159
+ const dragStart = (index, e) => {
160
+ lastScrollYRef.current = scrollYRef?.current; //这里先赋值下
161
+ dragCurrentRef.current = index;
162
+ lastDragY.current = e.absoluteY;
163
+ onDragStart?.();
164
+ }
165
+
166
+
167
+ //改变策略,通过两次 absoluteY 的值来获取每次移动距离
168
+ const dragMove = (index, e) => {
169
+
170
+ if(e.absoluteY < triggerTop){
171
+ onTopReached?.();
172
+ }else if(e.absoluteY > triggerBottom){
173
+ onBottomReached?.();
174
+ }else {
175
+ onCentered?.();
176
+ }
177
+
178
+ let dragData = dragSourceData[index];
179
+ let moveY = (e.absoluteY - lastDragY.current)+dragData.yValue;
180
+ let moveX = getLeftByIndex(dragData.originIndex);
181
+ lastDragY.current = e.absoluteY;
182
+ if(column > 1){
183
+ moveX = e.translationX+getLeftByIndex(dragData.originIndex);
184
+ }
185
+
186
+ dragData.y.setValue(moveY);
187
+ dragData.x.setValue(moveX);
188
+ dragData.yValue = moveY;
189
+ let dragIndex = dragData.changeIndex;
190
+
191
+ //注意 targetIndex 不是拖拽索引,是在总数据的索引
192
+ const targetIndex = dragSourceData.findIndex((item, i) => {
193
+ if(i === index){
194
+ return false;
195
+ }
196
+ const itemIndex = item.originIndex;
197
+ const minY = getTopByIndex(itemIndex) ;
198
+ const maxY = getTopByIndex(itemIndex) + getChildRealHeight();
199
+ const minX = getLeftByIndex(itemIndex) ;
200
+ const maxX = getLeftByIndex(itemIndex) + getChildRealWidth();
201
+
202
+ const x = moveX + childrenWidth/2;
203
+ const y = moveY + childrenHeight/2;
204
+ if( x >= minX && x <= maxX && y >= minY && y <= maxY ){
205
+ return true;
206
+ }
207
+ });
208
+
209
+ const targetItem = dragSourceData[targetIndex];
210
+
211
+ if(targetItem){ //多行拖拽交换要特殊处理下
212
+
213
+ //这里不能直接改当前拖拽的元素到被拖拽索引
214
+ const targetOriginIndex = targetItem.originIndex;
215
+ //判断是后移动还是前移动
216
+ if(dragIndex < targetItem.originIndex){ //往后移动
217
+ for(let i = dragIndex+1; i <= targetItem.originIndex; i++){
218
+ const item = dragSourceData.find(item => item.originIndex === i && item.changeIndex === i);
219
+ if(item){
220
+ item.changeIndex -= 1 ;
221
+ item.originIndex -= 1;
222
+ // item.y.setValue(getTopByIndex(item.changeIndex));
223
+ // item.x.setValue(getLeftByIndex(item.changeIndex));
224
+ item.yValue = getTopByIndex(item.changeIndex);
225
+ Animated.parallel([
226
+ Animated.timing(item.x, {
227
+ toValue: getLeftByIndex(item.changeIndex),
228
+ duration: 300,
229
+ easing: Easing.ease,
230
+ useNativeDriver: false,
231
+ }),
232
+ Animated.timing(item.y, {
233
+ toValue: getTopByIndex(item.changeIndex),
234
+ duration: 300,
235
+ easing: Easing.ease,
236
+ useNativeDriver: false,
237
+ }),
238
+ ]).start();
239
+ }
240
+ }
241
+ }else{
242
+ for(let i = dragIndex -1; i >= targetItem.originIndex; i--){
243
+ const item = dragSourceData.find(item => item.originIndex === i && item.changeIndex === i);
244
+
245
+ if(item){
246
+
247
+ item.changeIndex += 1 ;
248
+ item.originIndex += 1;
249
+ // item.y.setValue(getTopByIndex(item.changeIndex));
250
+ // item.x.setValue(getLeftByIndex(item.changeIndex));
251
+ item.yValue = getTopByIndex(item.changeIndex);
252
+ Animated.parallel([
253
+ Animated.timing(item.x, {
254
+ toValue: getLeftByIndex(item.changeIndex),
255
+ duration: 300,
256
+ easing: Easing.ease,
257
+ useNativeDriver: false,
258
+ }),
259
+ Animated.timing(item.y, {
260
+ toValue: getTopByIndex(item.changeIndex),
261
+ duration: 300,
262
+ easing: Easing.ease,
263
+ useNativeDriver: false,
264
+ }),
265
+ ]).start();
266
+ }
267
+ }
268
+ }
269
+ dragData.changeIndex = targetOriginIndex;
270
+ }
271
+
272
+
273
+ }
274
+
275
+ const dragEnd = (index, e) => {
276
+
277
+ stopScroll();
278
+ let dragData = dragSourceData[index];
279
+ //计算索引变化,将变化后数据吐出去
280
+ let arr = [];
281
+ dragSourceData?.forEach((item) => {
282
+ arr[item.changeIndex] = item.value;
283
+ })
284
+ onDragEnd?.(dragData.originIndex, dragData.changeIndex, arr);
285
+
286
+ dragData.originIndex = dragData.changeIndex;
287
+ dragData.x.setValue(getLeftByIndex(dragData.originIndex));
288
+ dragData.y.setValue(getTopByIndex(dragData.originIndex));
289
+ dragData.yValue = getTopByIndex(dragData.originIndex);
290
+
291
+ }
292
+
293
+ const renderItem = (item, index) => {
294
+ return (
295
+ <DragItemContainer
296
+ key={keyStr?item?.value?.[keyStr]:index}
297
+ x={item?.x}
298
+ y={item?.y}
299
+ childrenWidth={childrenWidth}
300
+ childrenHeight={childrenHeight}
301
+ onDragStart={(e)=>{
302
+ dragStart(index, e);
303
+ }}
304
+ onDragMove={(e)=>{
305
+ dragMove(index, e);
306
+ }}
307
+ onDragEnd={(e)=>{
308
+ dragEnd(index, e);
309
+ }}
310
+ >
311
+ {props?.renderItem?.(item.value, index)}
312
+ </DragItemContainer>
313
+ )
314
+ }
315
+
316
+ const renderList = () => {
317
+ return(
318
+ <View style={{height: totalHeight}}>
319
+ {
320
+ dragSourceData?.map((item, index) => {
321
+ return renderItem(item, index);
322
+ })
323
+ }
324
+ </View>
325
+ )
326
+ }
327
+
328
+ return(
329
+ <View onLayout={(e)=>{
330
+ yRef.current = e.nativeEvent.layout.y;
331
+ heightRef.current = e.nativeEvent.layout.height;
332
+ }}>
333
+ <GestureHandlerRootView>
334
+ {renderList()}
335
+ </GestureHandlerRootView>
336
+ </View>
337
+
338
+ )
339
+ }
340
+
341
+ const DragSortableView = memo(MemoDragSortableView, (prevProps, nextProps)=>{
342
+ prevProps = _.omitBy(prevProps, _.isFunction);
343
+ nextProps = _.omitBy(nextProps, _.isFunction);
344
+ return _.isEqual(prevProps, nextProps);
345
+ });
346
+
347
+ export default DragSortableView
348
+
349
+ const styles = StyleSheet.create({
350
+
351
+ })
package/package.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "name": "react-native-drag-sort-list",
3
+ "version": "1.0.0",
4
+ "description": "A powerful React Native drag and sort component library with support for single and multi-column layouts",
5
+ "main": "index.js",
6
+ "scripts": {
7
+ "test": "echo \"Error: no test specified\" && exit 1"
8
+ },
9
+ "keywords": [
10
+ "react-native",
11
+ "drag",
12
+ "sort",
13
+ "drag-sort",
14
+ "drag-and-drop",
15
+ "reorder",
16
+ "list",
17
+ "grid",
18
+ "gesture"
19
+ ],
20
+ "author": "liushun",
21
+ "license": "Apache-2.0",
22
+ "repository": {
23
+ "type": "git",
24
+ "url": "https://github.com/your-username/react-native-drag-sort.git"
25
+ },
26
+ "bugs": {
27
+ "url": "https://github.com/your-username/react-native-drag-sort/issues"
28
+ },
29
+ "homepage": "https://github.com/your-username/react-native-drag-sort#readme",
30
+ "peerDependencies": {
31
+ "react": ">=16.8.0",
32
+ "react-native": ">=0.60.0",
33
+ "react-native-gesture-handler": ">=2.0.0"
34
+ },
35
+ "dependencies": {
36
+ "lodash": "^4.17.21"
37
+ },
38
+ "engines": {
39
+ "node": ">=12.0.0"
40
+ }
41
+ }