-
Notifications
You must be signed in to change notification settings - Fork 266
/
RNCSliderNativeComponent.web.tsx
400 lines (365 loc) · 12.1 KB
/
RNCSliderNativeComponent.web.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
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
//@ts-ignore
import ReactDOM from 'react-dom';
import React, {RefObject, useCallback} from 'react';
import {
Animated,
View,
ColorValue,
ViewStyle,
GestureResponderEvent,
LayoutChangeEvent,
Image,
} from 'react-native';
//@ts-ignore
import type {ImageSource} from 'react-native/Libraries/Image/ImageSource';
type Event = Readonly<{
nativeEvent: {
value: number;
};
}>;
type AnimationValues = {
val: Animated.Value;
min: Animated.Value;
max: Animated.Value;
diff: Animated.Value;
};
export interface Props {
value: number;
minimumValue: number;
maximumValue: number;
lowerLimit?: number;
upperLimit?: number;
step: number;
minimumTrackTintColor: ColorValue;
maximumTrackTintColor: ColorValue;
thumbTintColor: ColorValue;
thumbStyle: ViewStyle;
style: ViewStyle;
inverted: boolean;
disabled: boolean;
trackHeight: number;
thumbSize: number;
thumbImage?: ImageSource;
onRNCSliderSlidingStart: (event: Event) => void;
onRNCSliderSlidingComplete: (event: Event) => void;
onRNCSliderValueChange: (event: Event) => void;
}
const valueToEvent = (value: number): Event => ({nativeEvent: {value}});
const RCTSliderWebComponent = React.forwardRef(
(
{
value: initialValue,
minimumValue = 0,
maximumValue = 0,
lowerLimit = 0,
upperLimit = 0,
step = 1,
minimumTrackTintColor = '#009688',
maximumTrackTintColor = '#939393',
thumbTintColor = '#009688',
thumbStyle = {},
style = {},
inverted = false,
disabled = false,
trackHeight = 4,
thumbSize = 20,
thumbImage,
onRNCSliderSlidingStart = (_: Event) => {},
onRNCSliderSlidingComplete = (_: Event) => {},
onRNCSliderValueChange = (_: Event) => {},
...others
}: Props,
forwardedRef: any,
) => {
const containerSize = React.useRef({width: 0, height: 0});
const containerPositionX = React.useRef(0);
const containerRef = forwardedRef || React.createRef();
const containerPositionInvalidated = React.useRef(false);
const [value, setValue] = React.useState(initialValue || minimumValue);
const lastInitialValue = React.useRef<number>();
const animationValues = React.useRef<AnimationValues>({
val: new Animated.Value(value),
min: new Animated.Value(minimumValue),
max: new Animated.Value(maximumValue),
// make sure we never divide by 0
diff: new Animated.Value(maximumValue - minimumValue || 1),
}).current;
// update minimumValue & maximumValue animations
React.useEffect(() => {
animationValues.min.setValue(minimumValue);
animationValues.max.setValue(maximumValue);
// make sure we never divide by 0
animationValues.diff.setValue(maximumValue - minimumValue || 1);
}, [animationValues, minimumValue, maximumValue]);
// compute animated slider position based on animated value
const minPercent = React.useRef(
Animated.multiply(
new Animated.Value(100),
Animated.divide(
Animated.subtract(animationValues.val, animationValues.min),
animationValues.diff,
),
),
).current;
const maxPercent = React.useRef(
Animated.subtract(new Animated.Value(100), minPercent),
).current;
const onValueChange = useCallback(
(value: number) => {
onRNCSliderValueChange && onRNCSliderValueChange(valueToEvent(value));
},
[onRNCSliderValueChange],
);
const onSlidingStart = useCallback(
(value: number) => {
isUserInteracting.current = true;
onRNCSliderSlidingStart && onRNCSliderSlidingStart(valueToEvent(value));
},
[onRNCSliderSlidingStart],
);
const onSlidingComplete = useCallback(
(value: number) => {
isUserInteracting.current = false;
onRNCSliderSlidingComplete &&
onRNCSliderSlidingComplete(valueToEvent(value));
},
[onRNCSliderSlidingComplete],
);
// Add a ref to track user interaction
const isUserInteracting = React.useRef(false);
const updateValue = useCallback(
(newValue: number) => {
// Ensure that the value is correctly rounded
const hardRounded =
decimalPrecision.current < 20
? Number.parseFloat(newValue.toFixed(decimalPrecision.current))
: newValue;
// Ensure that the new value is still between the bounds
const withinBounds = Math.max(
minimumValue,
Math.min(hardRounded, maximumValue),
);
if (value !== withinBounds) {
setValue(withinBounds);
if (isUserInteracting.current) {
onValueChange(withinBounds);
}
return withinBounds;
}
return hardRounded;
},
[minimumValue, maximumValue, value, onValueChange],
);
React.useLayoutEffect(() => {
// we have to do this check because `initialValue` gets default to `0` by
// Slider. If we don't this will get called every time `value` changes
// as `updateValue` is mutated when value changes. The result of not
// checking this is that the value constantly gets reset to `0` in
// contexts where `value` is not managed externally.
if (initialValue !== lastInitialValue.current) {
lastInitialValue.current = initialValue;
const newValue = updateValue(initialValue);
animationValues.val.setValue(newValue);
}
}, [initialValue, updateValue, animationValues]);
React.useEffect(() => {
const invalidateContainerPosition = () => {
containerPositionInvalidated.current = true;
};
const onDocumentScroll = (e: Event) => {
const isAlreadyInvalidated = !containerPositionInvalidated.current;
if (
isAlreadyInvalidated &&
containerRef.current &&
// @ts-ignore
e.target.contains(containerRef.current)
) {
invalidateContainerPosition();
}
};
//@ts-ignore
window.addEventListener('resize', invalidateContainerPosition);
//@ts-ignore
document.addEventListener('scroll', onDocumentScroll, {capture: true});
return () => {
//@ts-ignore
window.removeEventListener('resize', invalidateContainerPosition);
//@ts-ignore
document.removeEventListener('scroll', onDocumentScroll, {
capture: true,
});
};
}, [containerRef]);
const containerStyle = [
{
flexGrow: 1,
flexShrink: 1,
flexBasis: 'auto',
flexDirection: 'row',
alignItems: 'center',
},
style,
] as ViewStyle[];
const trackStyle = {
height: trackHeight,
borderRadius: trackHeight / 2,
userSelect: 'none',
};
const minimumTrackStyle = {
...trackStyle,
backgroundColor: minimumTrackTintColor,
flexGrow: minPercent,
};
const maximumTrackStyle = {
...trackStyle,
backgroundColor: maximumTrackTintColor,
flexGrow: maxPercent,
};
const thumbViewStyle = [
{
width: thumbSize,
height: thumbSize,
backgroundColor: thumbTintColor,
zIndex: 1,
borderRadius: thumbSize / 2,
overflow: 'hidden',
},
thumbStyle,
] as ViewStyle[];
const decimalPrecision = React.useRef(
calculatePrecision(minimumValue, maximumValue, step),
);
React.useEffect(() => {
decimalPrecision.current = calculatePrecision(
minimumValue,
maximumValue,
step,
);
}, [maximumValue, minimumValue, step]);
const updateContainerPositionX = () => {
//@ts-ignore
const positionX = ReactDOM.findDOMNode(
(containerRef as RefObject<any>).current,
).getBoundingClientRect()?.x;
containerPositionX.current = positionX ?? 0;
};
const getValueFromNativeEvent = (pageX: number) => {
const adjustForThumbSize = (containerSize.current.width || 1) > thumbSize;
const width =
(containerSize.current.width || 1) -
(adjustForThumbSize ? thumbSize : 0);
if (containerPositionInvalidated.current) {
containerPositionInvalidated.current = false;
updateContainerPositionX();
}
const containerX =
containerPositionX.current + (adjustForThumbSize ? thumbSize / 2 : 0);
const lowerValue = minimumValue < lowerLimit ? lowerLimit : minimumValue;
const upperValue = maximumValue > upperLimit ? upperLimit : maximumValue;
if (pageX < containerX) {
return inverted ? upperValue : lowerValue;
} else if (pageX > containerX + width) {
return inverted ? lowerValue : upperValue;
} else {
const x = pageX - containerX;
const newValue = inverted
? maximumValue - ((maximumValue - minimumValue) * x) / width
: minimumValue + ((maximumValue - minimumValue) * x) / width;
const valueAfterStep = step
? Math.round(newValue / step) * step
: newValue;
const valueAfterLowerLimit =
valueAfterStep < lowerLimit ? lowerLimit : valueAfterStep;
const valueInLimitRange =
valueAfterLowerLimit > upperLimit ? upperLimit : valueAfterLowerLimit;
return valueInLimitRange;
}
};
const onTouchEnd = ({nativeEvent}: GestureResponderEvent) => {
const newValue = updateValue(getValueFromNativeEvent(nativeEvent.pageX));
animationValues.val.setValue(newValue);
onSlidingComplete(newValue);
};
const onMove = ({nativeEvent}: GestureResponderEvent) => {
const newValue = getValueFromNativeEvent(nativeEvent.pageX);
animationValues.val.setValue(newValue);
updateValue(newValue);
};
const accessibilityActions = (event: any) => {
const tenth = (maximumValue - minimumValue) / 10;
switch (event.nativeEvent.actionName) {
case 'increment':
updateValue(value + (step || tenth));
break;
case 'decrement':
updateValue(value - (step || tenth));
break;
}
};
React.useImperativeHandle(
forwardedRef,
() => ({
updateValue: (val: number) => {
updateValue(val);
},
}),
[updateValue],
);
return (
<View
ref={containerRef}
onLayout={({nativeEvent: {layout}}: LayoutChangeEvent) => {
containerSize.current.height = layout.height;
containerSize.current.width = layout.width;
if ((containerRef as RefObject<View>).current) {
updateContainerPositionX();
}
}}
accessibilityActions={[
{name: 'increment', label: 'increment'},
{name: 'decrement', label: 'decrement'},
]}
onAccessibilityAction={accessibilityActions}
accessible={true}
accessibilityRole={'adjustable'}
style={containerStyle}
{...others}
// NOTE: gesture responders should all fall _after_ the {...others}
// spread operator, or they may not work appropriately.
onStartShouldSetResponder={() => !disabled}
onMoveShouldSetResponder={() => !disabled}
onResponderGrant={() => onSlidingStart(value)}
onResponderRelease={onTouchEnd}
onResponderMove={onMove}>
<Animated.View pointerEvents="none" style={minimumTrackStyle} />
<View pointerEvents="none" style={thumbViewStyle}>
{thumbImage !== undefined ? (
<Image
source={thumbImage}
style={{width: '100%', height: '100%'}}
/>
) : null}
</View>
<Animated.View pointerEvents="none" style={maximumTrackStyle} />
</View>
);
},
);
// We should round number with the same precision as the min, max or step values if provided
function calculatePrecision(
minimumValue: number,
maximumValue: number,
step: number,
) {
if (!step) {
return Infinity;
} else {
// Calculate the number of decimals we can encounter in the results
const decimals = [minimumValue, maximumValue, step].map(
(value) => ((value + '').split('.').pop() || '').length,
);
return Math.max(...decimals);
}
}
RCTSliderWebComponent.displayName = 'RTCSliderWebComponent';
export default RCTSliderWebComponent;