forked from jwohlfert23/react-native-tag-input
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
497 lines (455 loc) · 12.7 KB
/
index.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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
// @flow
import type {
StyleObj,
} from 'react-native/Libraries/StyleSheet/StyleSheetTypes';
import * as React from 'react';
import PropTypes from 'prop-types';
import {
View,
Text,
TextInput,
StyleSheet,
TouchableOpacity,
Dimensions,
TouchableWithoutFeedback,
ScrollView,
ViewPropTypes,
Platform,
} from 'react-native';
import invariant from 'invariant';
const windowWidth = Dimensions.get('window').width;
type RequiredProps<T> = {
/**
* A handler to be called when array of tags change.
* When new tags are added, they are appended as strings. If you use a
* non-string item type, make sure to either translate the strings to your
* item type before passing this value on to the "value" prop, or otherwise
* make sure your labelExtractor can handle both your item type and strings.
*/
onChange: (items: $ReadOnlyArray<T | string>) => void,
/**
* An array of tags, which can be any type, as long as labelExtractor below
* can extract a string from it.
*/
value: $ReadOnlyArray<T>,
/**
* Function to extract string value for label from item
*/
labelExtractor: (tagData: T) => string,
};
type OptionalProps = {
/**
* An array of characters to use as tag separators
*/
separators: $ReadOnlyArray<string>,
/**
* A RegExp to test tags after enter, space, or a comma is pressed
*/
regex: RegExp,
/**
* Background color of tags
*/
tagColor: string,
/**
* Text color of tags
*/
tagTextColor: string,
/**
* Styling override for container surrounding tag text
*/
tagContainerStyle?: StyleObj,
/**
* Styling override for tag's text component
*/
tagTextStyle?: StyleObj,
/**
* Color of text input
*/
inputColor: string,
/**
* Any misc. TextInput props (autoFocus, placeholder, returnKeyType, etc.)
*/
inputProps?: $PropertyType<TextInput, 'props'>,
/**
* Max height of the tag input on screen (will scroll if max height reached)
*/
maxHeight: number,
/**
* Callback that gets passed the new component height when it changes
*/
onHeightChange?: (height: number) => void,
/**
* Whether to treat a blur event as a separator entry (iOS-only)
*/
parseOnBlur: bool,
};
type Props<T> = RequiredProps<T> & OptionalProps;
type State = {
text: string,
inputWidth: number,
wrapperHeight: number,
};
const DEFAULT_SEPARATORS = [',', ' ', ';', '\n'];
const DEFAULT_TAG_REGEX = /(.+)/gi;
class TagInput<T> extends React.PureComponent<Props<T>, State> {
static propTypes = {
onChange: PropTypes.func.isRequired,
value: PropTypes.array.isRequired,
labelExtractor: PropTypes.func.isRequired,
separators: PropTypes.arrayOf(PropTypes.string),
regex: PropTypes.object,
tagColor: PropTypes.string,
tagTextColor: PropTypes.string,
tagContainerStyle: ViewPropTypes.style,
tagTextStyle: Text.propTypes.style,
inputColor: PropTypes.string,
// $FlowFixMe(>=0.49.0): https://github.com/facebook/react-native/pull/16437
inputProps: PropTypes.shape(TextInput.propTypes),
maxHeight: PropTypes.number,
onHeightChange: PropTypes.func,
parseOnBlur: PropTypes.bool,
};
props: Props<T>;
state: State = {
text: '',
inputWidth: 120,
wrapperHeight: 36,
};
wrapperWidth = windowWidth;
spaceLeft = 0;
// scroll to bottom
contentHeight = 0;
scrollViewHeight = 0;
// refs
tagInput: ?TextInput = null;
scrollView: ?ScrollView = null;
static defaultProps = {
separators: DEFAULT_SEPARATORS,
regex: DEFAULT_TAG_REGEX,
tagColor: '#dddddd',
tagTextColor: '#777777',
inputColor: '#777777',
maxHeight: 75,
parseOnBlur: false,
};
static inputWidth(text: string, spaceLeft: number, wrapperWidth: number) {
if (text === "") {
return 120;
} else if (spaceLeft >= 130) {
return spaceLeft - 10;
} else {
return wrapperWidth;
}
}
componentWillReceiveProps(nextProps: Props<T>) {
const wrapperHeight = Math.min(
nextProps.maxHeight,
this.contentHeight,
);
if (wrapperHeight !== this.state.wrapperHeight) {
this.setState({ wrapperHeight });
}
}
componentWillUpdate(nextProps: Props<T>, nextState: State) {
const inputWidth = TagInput.inputWidth(
nextState.text,
this.spaceLeft,
this.wrapperWidth,
);
if (inputWidth !== this.state.inputWidth) {
this.setState({ inputWidth });
}
if (
this.props.onHeightChange &&
nextState.wrapperHeight !== this.state.wrapperHeight
) {
this.props.onHeightChange(nextState.wrapperHeight);
}
}
measureWrapper = (event: { nativeEvent: { layout: { width: number } } }) => {
this.wrapperWidth = event.nativeEvent.layout.width;
const inputWidth = TagInput.inputWidth(
this.state.text,
this.spaceLeft,
this.wrapperWidth,
);
if (inputWidth !== this.state.inputWidth) {
this.setState({ inputWidth });
}
}
onChangeText = (text: string) => {
this.setState({ text: text });
const lastTyped = text.charAt(text.length - 1);
const parseWhen = this.props.separators;
if (parseWhen.indexOf(lastTyped) > -1) {
this.parseTags();
}
}
onBlur = (event: { nativeEvent: { text: string } }) => {
if (Platform.OS === "ios" && this.props.parseOnBlur) {
this.setState({ text: event.nativeEvent.text }, this.parseTags);
} else if (Platform.OS === "ios") {
this.setState({ text: event.nativeEvent.text });
} else if (this.props.parseOnBlur) {
this.parseTags();
}
}
parseTags = () => {
const { text } = this.state;
const { value } = this.props;
const regex = this.props.regex;
const results = text.match(regex);
if (results && results.length > 0) {
this.setState({ text: '' });
this.props.onChange([...new Set([...value, ...results])]);
}
}
onKeyPress = (event: { nativeEvent: { key: string } }) => {
if (this.state.text !== '' || event.nativeEvent.key !== 'Backspace') {
return;
}
const tags = [...this.props.value];
tags.pop();
this.props.onChange(tags);
this.focus();
}
focus = () => {
invariant(this.tagInput, "should be set");
this.tagInput.focus();
}
removeIndex = (index: number) => {
const tags = [...this.props.value];
tags.splice(index, 1);
this.props.onChange(tags);
}
scrollToBottom = () => {
const y = this.contentHeight - this.scrollViewHeight;
if (y <= 0) {
return;
}
const scrollView = this.scrollView;
invariant(
scrollView,
"this.scrollView ref should exist before scrollToBottom called",
);
scrollView.scrollTo({ y, animated: true });
}
render() {
const { text } = this.state;
const { inputColor } = this.props;
const tags = this.props.value.map((tag, index) => (
<Tag
index={index}
label={this.props.labelExtractor(tag)}
isLastTag={this.props.value.length === index + 1}
onLayoutLastTag={this.onLayoutLastTag}
removeIndex={this.removeIndex}
tagColor={this.props.tagColor}
tagTextColor={this.props.tagTextColor}
tagContainerStyle={this.props.tagContainerStyle}
tagTextStyle={this.props.tagTextStyle}
key={index}
/>
));
return (
<TouchableWithoutFeedback
onPress={this.focus}
style={styles.container}
onLayout={this.measureWrapper}
>
<View style={[styles.wrapper, { height: this.state.wrapperHeight }]}>
<ScrollView
ref={this.scrollViewRef}
style={styles.tagInputContainerScroll}
onContentSizeChange={this.onScrollViewContentSizeChange}
onLayout={this.onScrollViewLayout}
keyboardShouldPersistTaps="handled"
>
<View style={styles.tagInputContainer}>
{tags}
<View style={[
styles.textInputContainer,
]}>
<TextInput
ref={this.tagInputRef}
blurOnSubmit={false}
onKeyPress={this.onKeyPress}
value={text}
style={[styles.textInput, {
color: inputColor,
}]}
onBlur={this.onBlur}
onChangeText={this.onChangeText}
onSubmitEditing={this.parseTags}
autoCapitalize="none"
autoCorrect={false}
placeholder="Start typing"
returnKeyType="done"
keyboardType="default"
underlineColorAndroid="rgba(0,0,0,0)"
{...this.props.inputProps}
/>
</View>
</View>
</ScrollView>
</View>
</TouchableWithoutFeedback>
)
}
tagInputRef = (tagInput: ?React.ElementRef<typeof TextInput>) => {
invariant(typeof tagInput === "object", "TextInput ref is object");
this.tagInput = tagInput;
}
scrollViewRef = (scrollView: ?React.ElementRef<typeof ScrollView>) => {
invariant(typeof scrollView === "object", "ScrollView ref is object");
this.scrollView = scrollView;
}
onScrollViewContentSizeChange = (w: number, h: number) => {
if (this.contentHeight === h) {
return;
}
const nextWrapperHeight = Math.min(this.props.maxHeight, h);
if (nextWrapperHeight !== this.state.wrapperHeight) {
this.setState(
{ wrapperHeight: nextWrapperHeight },
this.contentHeight < h ? this.scrollToBottom : undefined,
);
} else if (this.contentHeight < h) {
this.scrollToBottom();
}
this.contentHeight = h;
}
onScrollViewLayout = (
event: { nativeEvent: { layout: { height: number } } },
) => {
this.scrollViewHeight = event.nativeEvent.layout.height;
}
onLayoutLastTag = (endPosOfTag: number) => {
const margin = 3;
this.spaceLeft = this.wrapperWidth - endPosOfTag - margin - 10;
const inputWidth = TagInput.inputWidth(
this.state.text,
this.spaceLeft,
this.wrapperWidth,
);
if (inputWidth !== this.state.inputWidth) {
this.setState({ inputWidth });
}
}
}
type TagProps = {
index: number,
label: string,
isLastTag: bool,
onLayoutLastTag: (endPosOfTag: number) => void,
removeIndex: (index: number) => void,
tagColor: string,
tagTextColor: string,
tagContainerStyle?: StyleObj,
tagTextStyle?: StyleObj,
};
class Tag extends React.PureComponent<TagProps> {
props: TagProps;
static propTypes = {
index: PropTypes.number.isRequired,
label: PropTypes.string.isRequired,
isLastTag: PropTypes.bool.isRequired,
onLayoutLastTag: PropTypes.func.isRequired,
removeIndex: PropTypes.func.isRequired,
tagColor: PropTypes.string.isRequired,
tagTextColor: PropTypes.string.isRequired,
tagContainerStyle: ViewPropTypes.style,
tagTextStyle: Text.propTypes.style,
};
curPos: ?number = null;
componentWillReceiveProps(nextProps: TagProps) {
if (
!this.props.isLastTag &&
nextProps.isLastTag &&
this.curPos !== null &&
this.curPos !== undefined
) {
this.props.onLayoutLastTag(this.curPos);
}
}
render() {
return (
<TouchableOpacity
onPress={this.onPress}
onLayout={this.onLayoutLastTag}
style={[
styles.tag,
{ backgroundColor: this.props.tagColor },
this.props.tagContainerStyle,
]}
>
<Text style={[
styles.tagText,
{ color: this.props.tagTextColor },
this.props.tagTextStyle,
]}>
{this.props.label}
×
</Text>
</TouchableOpacity>
);
}
onPress = () => {
this.props.removeIndex(this.props.index);
}
onLayoutLastTag = (
event: { nativeEvent: { layout: { x: number, width: number } } },
) => {
const layout = event.nativeEvent.layout;
this.curPos = layout.width + layout.x;
if (this.props.isLastTag) {
this.props.onLayoutLastTag(this.curPos);
}
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
wrapper: {
flex: 1,
flexDirection: 'row',
marginTop: 3,
marginBottom: 2,
alignItems: 'flex-start',
},
tagInputContainerScroll: {
flex: 1,
},
tagInputContainer: {
flex: 1,
flexDirection: 'row',
flexWrap: 'wrap',
alignItems: 'center',
},
textInput: {
height: 36,
fontSize: 16,
flex: .6,
padding: 0,
},
textInputContainer: {
height: 36,
flexDirection: 'column',
justifyContent : 'center'
},
tag: {
justifyContent: 'center',
marginTop: 6,
marginRight: 3,
padding: 8,
height: 24,
borderRadius: 2,
},
tagText: {
padding: 0,
margin: 0,
},
});
export default TagInput;
export { DEFAULT_SEPARATORS, DEFAULT_TAG_REGEX }