-
Notifications
You must be signed in to change notification settings - Fork 89
/
Draggable.js
347 lines (322 loc) · 8.71 KB
/
Draggable.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
/**
* * https://github.com/tongyy/react-native-draggable
*
*/
import React from 'react';
import {
View,
Text,
Image,
PanResponder,
Animated,
Dimensions,
TouchableOpacity,
StyleSheet,
} from 'react-native';
import PropTypes from 'prop-types';
function clamp(number, min, max) {
return Math.max(min, Math.min(number, max));
}
export default function Draggable(props) {
const {
renderText,
isCircle,
renderSize,
imageSource,
renderColor,
children,
shouldReverse,
onReverse,
disabled,
debug,
animatedViewProps,
touchableOpacityProps,
onDrag,
onShortPressRelease,
onDragRelease,
onLongPress,
onPressIn,
onPressOut,
onRelease,
x,
y,
z,
minX,
minY,
maxX,
maxY,
} = props;
// The Animated object housing our xy value so that we can spring back
const pan = React.useRef(new Animated.ValueXY());
// Always set to xy value of pan, would like to remove
const offsetFromStart = React.useRef({x: 0, y: 0});
// Width/Height of Draggable (renderSize is arbitrary if children are passed in)
const childSize = React.useRef({x: renderSize, y: renderSize});
// Top/Left/Right/Bottom location on screen from start of most recent touch
const startBounds = React.useRef();
// Whether we're currently dragging or not
const isDragging = React.useRef(false);
const getBounds = React.useCallback(() => {
const left = x + offsetFromStart.current.x;
const top = y + offsetFromStart.current.y;
return {
left,
top,
right: left + childSize.current.x,
bottom: top + childSize.current.y,
};
}, [x, y]);
const shouldStartDrag = React.useCallback(
(gs) => {
return !disabled && (Math.abs(gs.dx) > 2 || Math.abs(gs.dy) > 2);
},
[disabled],
);
const reversePosition = React.useCallback(() => {
const originalOffset = {x: 0, y: 0};
const newOffset = onReverse ? onReverse() : originalOffset;
Animated.spring(pan.current, {
toValue: newOffset || originalOffset,
useNativeDriver: false,
}).start();
}, [pan]);
const onPanResponderRelease = React.useCallback(
(e, gestureState) => {
isDragging.current = false;
if (onDragRelease) {
onDragRelease(e, gestureState, getBounds());
onRelease(e, true);
}
if (!shouldReverse) {
pan.current.flattenOffset();
} else {
reversePosition();
}
},
[onDragRelease, shouldReverse, onRelease, reversePosition, getBounds],
);
const onPanResponderGrant = React.useCallback(
(e, gestureState) => {
startBounds.current = getBounds();
isDragging.current = true;
if (!shouldReverse) {
pan.current.setOffset(offsetFromStart.current);
pan.current.setValue({x: 0, y: 0});
}
},
[getBounds, shouldReverse],
);
const handleOnDrag = React.useCallback(
(e, gestureState) => {
const {dx, dy} = gestureState;
const {top, right, left, bottom} = startBounds.current;
const far = 999999999;
const changeX = clamp(
dx,
Number.isFinite(minX) ? minX - left : -far,
Number.isFinite(maxX) ? maxX - right : far,
);
const changeY = clamp(
dy,
Number.isFinite(minY) ? minY - top : -far,
Number.isFinite(maxY) ? maxY - bottom : far,
);
pan.current.setValue({x: changeX, y: changeY});
onDrag(e, gestureState);
},
[maxX, maxY, minX, minY, onDrag],
);
const panResponder = React.useMemo(() => {
return PanResponder.create({
onMoveShouldSetPanResponder: (_, gestureState) =>
shouldStartDrag(gestureState),
onMoveShouldSetPanResponderCapture: (_, gestureState) =>
shouldStartDrag(gestureState),
onPanResponderGrant,
onPanResponderMove: Animated.event([], {
listener: handleOnDrag,
useNativeDriver: false,
}),
onPanResponderRelease,
});
}, [
handleOnDrag,
onPanResponderGrant,
onPanResponderRelease,
shouldStartDrag,
]);
// TODO Figure out a way to destroy and remove offsetFromStart entirely
React.useEffect(() => {
const curPan = pan.current; // Using an instance to avoid losing the pointer before the cleanup
if (!shouldReverse) {
curPan.addListener((c) => (offsetFromStart.current = c));
} else {
reversePosition();
}
return () => {
curPan.removeAllListeners();
};
}, [shouldReverse]);
const positionCss = React.useMemo(() => {
const Window = Dimensions.get('window');
return {
position: 'absolute',
top: 0,
left: 0,
width: Window.width,
height: Window.height,
};
}, []);
const dragItemCss = React.useMemo(() => {
const style = {
top: y,
left: x,
elevation: z,
zIndex: z,
};
if (renderColor) {
style.backgroundColor = renderColor;
}
if (isCircle) {
style.borderRadius = renderSize;
}
if (children) {
return {
...style,
alignSelf: 'baseline',
};
}
return {
...style,
justifyContent: 'center',
width: renderSize,
height: renderSize,
};
}, [children, isCircle, renderColor, renderSize, x, y, z]);
const touchableContent = React.useMemo(() => {
if (children) {
return children;
} else if (imageSource) {
return (
<Image
style={{width: renderSize, height: renderSize}}
source={imageSource}
/>
);
} else {
return <Text style={styles.text}>{renderText}</Text>;
}
}, [children, imageSource, renderSize, renderText]);
const handleOnLayout = React.useCallback((event) => {
const {height, width} = event.nativeEvent.layout;
childSize.current = {x: width, y: height};
}, []);
const handlePressOut = React.useCallback(
(event) => {
onPressOut(event);
if (!isDragging.current) {
onRelease(event, false);
}
},
[onPressOut, onRelease],
);
const getDebugView = React.useCallback(() => {
const {width, height} = Dimensions.get('window');
const far = 9999;
const constrained = minX || maxX || minY || maxY;
if (!constrained) {
return null;
} // could show other debug info here
const left = minX || -far;
const right = maxX ? width - maxX : -far;
const top = minY || -far;
const bottom = maxY ? height - maxY : -far;
return (
<View
pointerEvents="box-none"
style={{left, right, top, bottom, ...styles.debugView}}
/>
);
}, [maxX, maxY, minX, minY]);
return (
<View pointerEvents="box-none" style={positionCss}>
{debug && getDebugView()}
<Animated.View
pointerEvents="box-none"
{...animatedViewProps}
{...panResponder.panHandlers}
style={pan.current.getLayout()}>
<TouchableOpacity
{...touchableOpacityProps}
onLayout={handleOnLayout}
style={dragItemCss}
disabled={disabled}
onPress={onShortPressRelease}
onLongPress={onLongPress}
onPressIn={onPressIn}
onPressOut={handlePressOut}>
{touchableContent}
</TouchableOpacity>
</Animated.View>
</View>
);
}
/***** Default props and types */
Draggable.defaultProps = {
renderText: '+',
renderSize: 36,
shouldReverse: false,
disabled: false,
debug: false,
onDrag: () => {},
onShortPressRelease: () => {},
onDragRelease: () => {},
onLongPress: () => {},
onPressIn: () => {},
onPressOut: () => {},
onRelease: () => {},
x: 0,
y: 0,
z: 1,
};
Draggable.propTypes = {
/**** props that should probably be removed in favor of "children" */
renderText: PropTypes.string,
isCircle: PropTypes.bool,
renderSize: PropTypes.number,
imageSource: PropTypes.number,
renderColor: PropTypes.string,
/**** */
children: PropTypes.element,
shouldReverse: PropTypes.bool,
disabled: PropTypes.bool,
debug: PropTypes.bool,
animatedViewProps: PropTypes.object,
touchableOpacityProps: PropTypes.object,
onDrag: PropTypes.func,
onShortPressRelease: PropTypes.func,
onDragRelease: PropTypes.func,
onLongPress: PropTypes.func,
onPressIn: PropTypes.func,
onPressOut: PropTypes.func,
onRelease: PropTypes.func,
onReverse: PropTypes.func,
x: PropTypes.number,
y: PropTypes.number,
// z/elevation should be removed because it doesn't sync up visually and haptically
z: PropTypes.number,
minX: PropTypes.number,
minY: PropTypes.number,
maxX: PropTypes.number,
maxY: PropTypes.number,
};
const styles = StyleSheet.create({
text: {color: '#fff', textAlign: 'center'},
test: {backgroundColor: 'red'},
debugView: {
backgroundColor: '#ff000044',
position: 'absolute',
borderColor: '#fced0ecc',
borderWidth: 4,
},
});