-
Notifications
You must be signed in to change notification settings - Fork 14
/
hpicker.js
395 lines (344 loc) · 10.8 KB
/
hpicker.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
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
import React, {Component} from "react";
import PropTypes from 'prop-types';
import {
StyleSheet,
Text,
ScrollView,
View,
Platform,
ViewPropTypes,
TouchableWithoutFeedback,
} from 'react-native';
import PropTypes from 'prop-types';
const defaultForegroundColor = '#444';
const defaultItemWidth = 30;
const loggingEnabled = false;
const itemPropTypes = {
label: PropTypes.string.isRequired,
value: PropTypes.any,
style: Text.propTypes.style,
foregroundColor: PropTypes.string,
};
const itemDefaultProps = {
foregroundColor: defaultForegroundColor,
};
function log(message, ...optionalParams) {
if (loggingEnabled) {
console.log(message, optionalParams);
}
}
class HorizontalPickerItem extends Component {
constructor(props) {
super(props);
this.state = intialState;
}
}
const propTypes = {
style: ViewPropTypes.style,
selectedValue: PropTypes.any,
children: PropTypes.array, // TODO: Make it HorizontalPicker.Item[]
itemWidth: PropTypes.number.isRequired,
onChange: PropTypes.func,
renderOverlay: PropTypes.func,
foregroundColor: PropTypes.string,
inactiveItemOpacity: PropTypes.number
};
const defaultProps = {
foregroundColor: defaultForegroundColor,
};
const intialState = {
selectedItem: null,
bounds: null,
padding: {left: 0, right: 0}
};
class HorizontalPicker extends Component {
constructor(props) {
super(props);
this.state = intialState;
this.isScrolling = false;
this.scrollX = -1;
this.ignoreNextScroll = false;
this.snapDelay = 200;
}
static Item = HorizontalPickerItem
componentWillReceiveProps(nextProps) {
log('componentWillReceiveProps (isScrolling:', this.isScrolling, ')', this.props.selectedValue, '->', nextProps.selectedValue);
const valueChanged = this.props.selectedValue !== nextProps.selectedValue;
const index = this.getIndexForValue(nextProps.selectedValue, nextProps.children);
const previousIndex = this.getIndexForValue(nextProps.selectedValue, this.props.children);
const rangeChanged = index !== previousIndex;
log('current index', index);
log('previous index', previousIndex);
log('x:', this.scrollX);
log('current value:', nextProps.selectedValue);
const visibleValue = this.getValueAt(this.scrollX);
const visualsChanged = nextProps.selectedValue !== visibleValue;
log('visible value:', visibleValue);
log('valueChanged:', valueChanged);
log('rangeChanged:', rangeChanged);
log('visualsChanged:', visualsChanged);
if (rangeChanged) {
// The given children have changed
log('rangeChanged -> resposition');
if (Platform.OS === 'android') {
// Android fix; For some reason it only scroll a small distance. Looks
// pretty awful and needs a better solution, this is just to fix the
// out-of-sync issue.
setTimeout(() => {
this.scrollToIndex(index, false);
}, 1);
} else {
this.scrollToIndex(index, false);
}
} else if (valueChanged) {
log('valueChanged -> scroll');
this.scrollToIndex(index, true);
} else if (visualsChanged) {
// Check if the current value is even possible.
// If not, we don't know where to scroll, so ignore.
const indexForSelectedValue = this.getIndexForValue(nextProps.selectedValue, nextProps.children);
log('visualsChanged -> scroll');
if (indexForSelectedValue !== -1) {
this.scrollToIndex(indexForSelectedValue, true);
}
}
}
componentDidMount() {
this.scrollToValue(this.props.selectedValue, false);
}
getItemWidth = () => this.props.itemWidth && this.props.itemWidth > 0
? this.props.itemWidth : defaultItemWidth;
getComponentWidth = () =>
this.state.bounds ? this.state.bounds.width : 0;
getValueAt = (x) => {
const child = this.getChildren()[this.getIndexAt(x)];
return child ? child.props.value : null;
}
getIndexAt = (x) => {
const dx = this.getComponentWidth() / 2 - this.state.padding.left;
return Math.floor((x + dx) / this.getItemWidth());
}
getIndexForValue = (item, children = this.getChildren()) => {
const index = children.findIndex(e => e.props.value === item);
log('getIndexForValue, value:', item, 'index:', index);
return index;
}
getChildren = (children = this.props.children) => React.Children.toArray(children);
scrollToValue = (itemValue, animated = true) => {
log('scrollToValue ->', itemValue);
const index = this.getIndexForValue(itemValue);
this.scrollToIndex(index, animated);
}
scrollToIndex = (index, animated = true, initial = false) => {
log('scrollToIndex ->', index);
if (index < 0) {
// Error; invalid index.
return;
}
this.isScrolling = true;
const snapX = index * this.getItemWidth();
// Make sure the component hasn't been unmounted
if (this.refs.scrollview) {
log('scroll ->', snapX);
this.refs.scrollview.scrollTo({x: snapX, y: 0, animated});
// iOS fix
if (!initial && Platform.OS === 'ios') {
log('ignoreNextScroll');
this.ignoreNextScroll = true;
}
}
}
onScroll = (event) => {
// Sometimes onMomentumScrollBegin event seems to be missing and onMomentumScrollEnd
// is sent twice. However, if we receive an onScroll after onMomentumScrollEnd, we
// can assume that the momentum scroll is continued.
this.isScrolling = true;
this.scrollX = event.nativeEvent.contentOffset.x;
log('onScroll, x:', this.scrollX);
this.cancelDelayedSnap();
}
onScrollBeginDrag = (event) => {
log('onScrollBeginDrag', this.scrollStart);
this.isScrolling = true;
this.scrollStart = event.nativeEvent.contentOffset.x;
this.cancelDelayedSnap();
this.ignoreNextScroll = false;
}
onScrollEndDrag = (/*event*/) => {
log('onScrollEnd');
this.isScrolling = false;
if (this.ignoreNextScroll) {
log('onScrollEnd, ignored');
this.ignoreNextScroll = false;
return;
}
this.delayedSnap();
}
onMomentumScrollBegin = (event) => {
log('onMomentumScrollBegin', event.nativeEvent);
this.isScrolling = true;
this.cancelDelayedSnap();
}
onMomentumScrollEnd = (/*event*/) => {
log('onMomentumScrollEnd');
this.isScrolling = false;
if (this.ignoreNextScroll) {
log('onMomentumScrollEnd, ignored');
this.ignoreNextScroll = false;
return;
}
this.delayedSnap();
}
delayedSnap = () => {
log('delayedSnap, cancelling previous...');
this.cancelDelayedSnap();
log('scheduling the snap');
log('delayedSnap');
this.snapNoMomentumTimeout =
setTimeout(() => {
const index = this.getIndexAt(this.scrollX);
const item = this.getChildren()[index];
log('doing the snap ->', item.props.value);
this.onChange(item.props.value);
this.scrollToIndex(index);
}, this.snapDelay);
}
cancelDelayedSnap = () => {
if (this.snapNoMomentumTimeout) {
log('cancelled the delayed snap');
log('cancelDelayedSnap');
clearTimeout(this.snapNoMomentumTimeout);
this.snapNoMomentumTimeout = null;
}
}
onChange = (itemValue) => {
log('onChange', itemValue);
if (this.props.onChange) {
this.props.onChange(itemValue);
}
}
handleItemPress = (value) => {
return () => {
if (value && this.props.onChange) {
this.props.onChange(value);
}
};
}
renderChildren = (children) => {
return children.map(this.renderChild);
}
renderChild = (child) => {
const itemValue = child.props.value;
const color = this.props.foregroundColor || defaultForegroundColor;
const opacity = this.props.inactiveItemOpacity && itemValue !== this.props.selectedValue ? this.props.inactiveItemOpacity : 1
return (
<TouchableWithoutFeedback key={itemValue} onPress={this.handleItemPress(itemValue)}>
<View style={[styles.itemContainer, {width: this.getItemWidth()}]}>
<Text style={[styles.itemText, child.props.style, {color, opacity}]}>{child.props.label}</Text>
</View>
</TouchableWithoutFeedback>
);
}
onLayout = (event) => {
log('onLayout');
const {nativeEvent: {layout: {x, y, width, height}}} = event;
const bounds = {width, height};
const leftItemWidth = this.getItemWidth();
const rightItemWidth = this.getItemWidth();
const padding = {
left: !bounds ? 0 : ((bounds.width - leftItemWidth) / 2),
right: !bounds ? 0 : ((bounds.width - rightItemWidth) / 2)
};
this.setState({
bounds,
padding
});
const index = this.getIndexForValue(this.props.selectedValue);
log('onLayout -> scrollToIndex');
this.scrollToIndex(index, false);
}
renderDefaultOverlay = () => {
const color = this.props.foregroundColor;
return (
<View style={{flex: 1}} />
);
}
render() {
const bounds = this.state.bounds;
const renderOverlay = this.props.renderOverlay || this.renderDefaultOverlay;
return (
<View style={[this.props.style]}>
<ScrollView
ref='scrollview'
decelerationRate={'fast'}
scrollEventThrottle={16}
contentContainerStyle={{paddingLeft: this.state.padding.left, paddingRight: this.state.padding.right}}
showsHorizontalScrollIndicator={false}
horizontal={true}
onScroll={this.onScroll}
onScrollBeginDrag={this.onScrollBeginDrag}
onScrollEndDrag={this.onScrollEndDrag}
onMomentumScrollBegin={this.onMomentumScrollBegin}
onMomentumScrollEnd={this.onMomentumScrollEnd}
onLayout={this.onLayout}
style={this.scrollView}>
<View style={styles.contentContainer}>
{bounds && this.renderChildren(this.props.children)}
</View>
</ScrollView>
<View style={styles.overlay} pointerEvents='none'>
<View style={[{flex: 1, width: this.getItemWidth()}]}>
{renderOverlay()}
</View>
</View>
</View>
);
}
}
var styles = StyleSheet.create({
image: {
flex: 1
},
touchArea: {
flex: 1,
alignSelf: 'stretch',
},
scrollView: {
flex: 1
},
contentContainer: {
flexDirection: 'row'
},
itemContainer: {
flexDirection: 'row',
flex: 1,
justifyContent: 'center',
alignItems: 'center'
},
item: {
flexDirection: 'column',
flex: 1,
alignItems: 'center',
justifyContent: 'flex-end',
backgroundColor: 'yellow'
},
itemText: {
fontSize: 20,
textAlign: 'center'
},
overlay: {
position: 'absolute',
left: 0,
right: 0,
top: 0,
bottom: 0,
flexDirection: 'column',
flex: 1,
alignItems: 'center'
}
});
HorizontalPickerItem.propTypes = itemPropTypes;
HorizontalPickerItem.defaultProps = itemDefaultProps;
HorizontalPicker.propTypes = propTypes;
HorizontalPicker.defaultProps = defaultProps;
export default HorizontalPicker;