-
Notifications
You must be signed in to change notification settings - Fork 973
/
Copy pathselect.component.tsx
581 lines (526 loc) · 17.6 KB
/
select.component.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
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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
/**
* @license
* Copyright Akveo. All Rights Reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*/
import React, { ReactNode } from 'react';
import {
Animated,
GestureResponderEvent,
ImageProps,
ListRenderItemInfo,
NativeSyntheticEvent,
Platform,
StyleSheet,
TargetedEvent,
TextProps,
TextStyle,
View,
ViewProps,
TextInput,
} from 'react-native';
import {
ChildrenWithProps,
EvaInputSize,
EvaStatus,
FalsyFC,
FalsyText,
IndexPath,
RenderProp,
TouchableWeb,
TouchableWebElement,
TouchableWebProps,
Overwrite,
LiteralUnion,
} from '../../devsupport';
import {
Interaction,
styled,
StyledComponentProps,
StyleType,
} from '../../theme';
import { List } from '../list/list.component';
import { Popover } from '../popover/popover.component';
import { ChevronDown } from '../shared/chevronDown.component';
import { SelectGroupProps } from './selectGroup.component';
import {
SelectItemElement,
SelectItemProps,
} from './selectItem.component';
import {
SelectItemDescriptor,
SelectService,
} from './select.service';
type SelectStyledProps = Overwrite<StyledComponentProps, {
appearance?: LiteralUnion<'default'>;
}>;
export interface SelectProps extends TouchableWebProps, SelectStyledProps {
children?: ChildrenWithProps<SelectItemProps | SelectGroupProps>;
selectedIndex?: IndexPath | IndexPath[];
onSelect?: (index: IndexPath | IndexPath[]) => void;
value?: RenderProp<TextProps> | React.ReactText;
multiSelect?: boolean;
placeholder?: RenderProp<TextProps> | React.ReactText;
label?: RenderProp<TextProps> | React.ReactText;
caption?: RenderProp<TextProps> | React.ReactText;
accessoryLeft?: RenderProp<Partial<ImageProps>>;
accessoryRight?: RenderProp<Partial<ImageProps>>;
status?: EvaStatus;
size?: EvaInputSize;
}
export type SelectElement = React.ReactElement<SelectProps>;
interface State {
listVisible: boolean;
searchQuery: string;
filteredOptions: string[];
}
const CHEVRON_DEG_COLLAPSED = -180;
const CHEVRON_DEG_EXPANDED = 0;
const CHEVRON_ANIM_DURATION = 200;
/**
* A dropdown menu for displaying selectable options.
* Select should contain SelectItem or SelectGroup components to provide a useful component.
*
* @extends React.Component
*
* @method {() => void} focus - Focuses input field and sets options list visible.
*
* @method {() => void} blur - Removes focus from input field and sets options list invisible.
*
* @method {() => boolean} isFocused - Whether input field is currently focused and options list is visible.
*
* @method {() => void} clear - Removes all text from the Select.
*
* @property {ReactElement<SelectItemProps> | ReactElement<SelectItemProps>[]} children -
* Items to be rendered within options list.
*
* @property {IndexPath | IndexPath[]} selectedIndex - Index or array of indices of selected options.
* IndexPath `row: number, section?: number` - position of element in sectioned list.
* Select becomes sectioned when SelectGroup is rendered within children.
*
* @property {(IndexPath | IndexPath[]) => void} onSelect - Called when option is pressed.
* Called with `row: number` for non-grouped items.
* Called with `row: number, section: number` for items rendered within group,
* where row - index of item in group, section - index of group in list.
* Called with array if *multiSelect* was set to true.
*
* @property {ReactText | ReactElement | (TextProps) => ReactElement} value - String, number or a function component
* to render for the selected options.
* By default, calls *toString()* for each index in selectedIndex property.
* If it is a function, expected to return a Text.
*
* @property {boolean} multiSelect - Whether multiple options can be selected.
* If true, calls onSelect with IndexPath[] in arguments.
* Otherwise, with IndexPath in arguments.
*
* @property {ReactText | ReactElement | (TextProps) => ReactElement} placeholder - String, number or a function
* component to render when there is no selected option.
* If it is a function, expected to return a Text.
*
* @property {ReactText | ReactElement | (TextProps) => ReactElement} label - String, number or a function component
* to render above input field.
* If it is a function, expected to return a Text.
*
* @property {ReactText | ReactElement | (TextProps) => ReactElement} caption - String, number or a function component
* to render below the input field.
* If it is a function, expected to return a Text.
*
* @property {ReactElement | (ImageProps) => ReactElement} accessoryLeft - Function component
* to render to start of the text.
* Expected to return an Image.
*
* @property {ReactElement | (ImageProps) => ReactElement} accessoryRight - Function component
* to render to end of the text.
* Expected to return an Image.
*
* @property {string} status - Status of the component.
* Can be `basic`, `primary`, `success`, `info`, `warning`, `danger` or `control`.
* Defaults to *basic*.
* Use *control* status when needed to display within a contrast container.
*
* @property {string} size - Size of the component.
* Can be `small`, `medium` or `large`.
* Defaults to *medium*.
*
* @property {() => void} onFocus - Called when options list becomes visible.
*
* @property {() => void} onBlur - Called when options list becomes invisible.
*
* @property {TouchableOpacityProps} ...TouchableOpacityProps - Any props applied to TouchableOpacity component.
*
* @overview-example SelectSimpleUsage
*
* @overview-example SelectIndexType
* Select works with special index object - IndexPath.
* For non-grouped items in select, there is only a `row` property.
* Otherwise, `row` is an index of option within the group, section - index of group in options list.
* ```
* interface IndexPath {
* row: number;
* section?: number;
* }
* ```
*
* @overview-example SelectMultiSelect
* Multiple options can be selected if `multiSelect` property is configured.
* For multiple options, `onSelect` function is called with array if indices.
*
* @overview-example SelectWithGroups
* Options may be grouped within `SelectGroup` component.
*
* @overview-example SelectDisplayValue
* By default, Select displays a value by building strings for selected indices.
* For a real-word examples, a `value` property should be configured.
*
* @overview-example SelectStates
* Select can be disabled with `disabled` property.
*
* @overview-example SelectDisabledOptions
* Same for options.
*
* @overview-example SelectStatus
* It also may be marked with `status` property, which is useful within forms validation.
* An extra status is `control`, which is designed to be used on high-contrast backgrounds.
*
* @overview-example SelectAccessories
* Select may contain labels, captions and inner views by configuring `accessoryLeft` or `accessoryRight` properties.
* Within Eva, Select accessories are expected to be images or [svg icons](guides/icon-packages).
*
* @overview-example SelectSize
* To resize Select, a `size` property may be used.
*
* @overview-example SelectStyling
* Select and it's inner views can be styled by passing them as function components.
* ```
* import { Select, SelectItem, Text } from '@ui-kitten/components';
*
* <Select
* label={evaProps => <Text {...evaProps}>Label</Text>}
* caption={evaProps => <Text {...evaProps}>Caption</Text>}>
* <SelectItem title={evaProps => <Text {...evaProps}>Option 1</Text>} />
* </Select>
* ```
*
* @overview-example SelectTheming
* In most cases this is redundant, if [custom theme is configured](guides/branding).
*/
@styled('Select')
export class Select extends React.Component<SelectProps, State> {
static defaultProps = {
placeholder: 'Select Option',
selectedIndex: [],
};
public state: State = {
listVisible: false,
searchQuery: '',
filteredOptions: []
};
private service: SelectService = new SelectService();
private expandAnimation: Animated.Value = new Animated.Value(0);
private get isMultiSelect(): boolean {
return this.props.multiSelect;
}
private get data(): Array<Exclude<ReactNode, boolean | null | undefined>> {
const options = React.Children.toArray(this.props.children || []);
if (this.state.searchQuery) {
return options.filter((option) =>
option.toString().toLowerCase().includes(this.state.searchQuery.toLowerCase())
);
}
return options;
}
private get selectedIndices(): IndexPath[] {
if (!this.props.selectedIndex) {
return [];
}
return Array.isArray(this.props.selectedIndex) ? this.props.selectedIndex : [this.props.selectedIndex];
}
private get expandToRotateInterpolation(): Animated.AnimatedInterpolation<string> {
return this.expandAnimation.interpolate({
inputRange: [CHEVRON_DEG_COLLAPSED, CHEVRON_DEG_EXPANDED],
outputRange: [`${CHEVRON_DEG_COLLAPSED}deg`, `${CHEVRON_DEG_EXPANDED}deg`],
});
}
public focus = (): void => {
this.setOptionsListVisible();
};
public blur = (): void => {
this.setOptionsListInvisible();
};
public isFocused = (): boolean => {
return this.state.listVisible;
};
public onSearch = (): void => {
const { searchQuery, filteredOptions } = this.state;
const filtered = filteredOptions.filter((option: string) =>
option.toLowerCase().includes(searchQuery.toLowerCase())
);
this.setState({ filteredOptions: filtered });
};
public handleSearch = (query: string): void => {
this.setState({ searchQuery: query }, this.onSearch);
};
public clear = (): void => {
this.props.onSelect?.(null);
};
private onMouseEnter = (event: NativeSyntheticEvent<TargetedEvent>): void => {
this.props.eva.dispatch([Interaction.HOVER]);
this.props.onMouseEnter?.(event);
};
private onMouseLeave = (event: NativeSyntheticEvent<TargetedEvent>): void => {
this.props.eva.dispatch([]);
this.props.onMouseLeave?.(event);
};
private onPress = (): void => {
this.setOptionsListVisible();
};
private onPressIn = (event: GestureResponderEvent): void => {
this.props.eva.dispatch([Interaction.ACTIVE]);
this.props.onPressIn?.(event);
};
private onPressOut = (event: GestureResponderEvent): void => {
this.props.eva.dispatch([]);
this.props.onPressOut?.(event);
};
private onItemPress = (descriptor: SelectItemDescriptor): void => {
if (this.props.onSelect) {
const selectedIndices = this.service.selectItem(this.isMultiSelect, descriptor, this.selectedIndices);
!this.isMultiSelect && this.setOptionsListInvisible();
this.props.onSelect(selectedIndices);
}
};
private onBackdropPress = (): void => {
this.setOptionsListInvisible();
};
private onListVisible = (): void => {
this.props.eva.dispatch([Interaction.ACTIVE]);
this.createExpandAnimation(-CHEVRON_DEG_COLLAPSED).start(() => {
this.props.onFocus?.(null);
});
};
private onListInvisible = (): void => {
this.props.eva.dispatch([]);
this.createExpandAnimation(CHEVRON_DEG_EXPANDED).start(() => {
this.props.onBlur?.(null);
});
};
private getComponentStyle = (style: StyleType): StyleType => {
const {
textMarginHorizontal,
textFontFamily,
textFontSize,
textFontWeight,
textColor,
placeholderColor,
placeholderFontSize,
placeholderFontWeight,
placeholderFontFamily,
iconWidth,
iconHeight,
iconMarginHorizontal,
iconTintColor,
labelColor,
labelFontSize,
labelMarginBottom,
labelFontWeight,
labelFontFamily,
captionColor,
captionFontSize,
captionFontWeight,
captionFontFamily,
captionIconWidth,
captionIconHeight,
captionIconMarginRight,
captionIconTintColor,
popoverMaxHeight,
popoverBorderRadius,
popoverBorderColor,
popoverBorderWidth,
...inputParameters
} = style;
return {
input: inputParameters,
text: {
marginHorizontal: textMarginHorizontal,
fontFamily: textFontFamily,
fontSize: textFontSize,
fontWeight: textFontWeight,
color: textColor,
},
placeholder: {
marginHorizontal: textMarginHorizontal,
fontSize: placeholderFontSize,
fontWeight: placeholderFontWeight,
fontFamily: placeholderFontFamily,
color: placeholderColor,
},
icon: {
width: iconWidth,
height: iconHeight,
marginHorizontal: iconMarginHorizontal,
tintColor: iconTintColor,
},
label: {
marginBottom: labelMarginBottom,
fontSize: labelFontSize,
fontWeight: labelFontWeight,
fontFamily: labelFontFamily,
color: labelColor,
},
caption: {
fontSize: captionFontSize,
fontWeight: captionFontWeight,
fontFamily: captionFontFamily,
color: captionColor,
},
popover: {
maxHeight: popoverMaxHeight,
borderRadius: popoverBorderRadius,
borderWidth: popoverBorderWidth,
borderColor: popoverBorderColor,
},
};
};
private setOptionsListVisible = (): void => {
const hasData: boolean = this.data.length > 0;
hasData && this.setState({ listVisible: true }, this.onListVisible);
};
private setOptionsListInvisible = (): void => {
this.setState({ listVisible: false }, this.onListInvisible);
};
private createExpandAnimation = (toValue: number): Animated.CompositeAnimation => {
return Animated.timing(this.expandAnimation, {
toValue,
duration: CHEVRON_ANIM_DURATION,
useNativeDriver: Platform.OS !== 'web',
});
};
private cloneItemWithProps = (el: SelectItemElement, props: SelectItemProps): SelectItemElement => {
const nestedElements = React.Children.map(el.props.children, (nestedEl: SelectItemElement, index: number) => {
const descriptor = this.service.createDescriptorForNestedElement(nestedEl, props.descriptor, index);
const selected: boolean = this.service.isSelected(descriptor, this.selectedIndices);
return this.cloneItemWithProps(nestedEl, { ...props, descriptor, selected, disabled: false });
});
return React.cloneElement(el, { ...props, ...el.props }, nestedElements);
};
private renderItem = (info: ListRenderItemInfo<SelectItemElement>): SelectItemElement => {
const descriptor = this.service.createDescriptorForElement(info.item, this.isMultiSelect, info.index);
const selected: boolean = this.service.isSelected(descriptor, this.selectedIndices);
const disabled: boolean = this.service.isDisabled(descriptor);
return this.cloneItemWithProps(info.item, { descriptor, selected, disabled, onPress: this.onItemPress });
};
private renderDefaultIconElement = (evaStyle): React.ReactElement => {
const { tintColor, ...svgStyle } = evaStyle;
return (
<Animated.View style={{ transform: [{ rotate: this.expandToRotateInterpolation }] }}>
<ChevronDown
style={svgStyle}
fill={tintColor}
/>
</Animated.View>
);
};
private renderInputElement = (props: SelectProps, evaStyle): TouchableWebElement => {
const value = props.value || this.service.toStringSelected(this.selectedIndices);
const textStyle: TextStyle = value && evaStyle.text;
return (
<TouchableWeb
testID={props.testID}
style={[styles.input, evaStyle.input]}
onPress={this.onPress}
onMouseEnter={this.onMouseEnter}
onMouseLeave={this.onMouseLeave}
onPressIn={this.onPressIn}
onPressOut={this.onPressOut}
disabled={props.disabled}
>
<FalsyFC
style={evaStyle.icon}
component={props.accessoryLeft}
/>
<FalsyText
style={[styles.text, evaStyle.placeholder, textStyle]}
numberOfLines={1}
ellipsizeMode='tail'
component={value || props.placeholder}
/>
<FalsyFC
style={evaStyle.icon}
component={props.accessoryRight}
fallback={this.renderDefaultIconElement(evaStyle.icon)}
/>
</TouchableWeb>
);
};
private renderSearchInput = (): React.ReactElement => {
return (
<TextInput
style={styles.searchInput}
placeholder="Search..."
value={this.state.searchQuery}
onChangeText={this.handleSearch}
/>
);
};
public render(): React.ReactElement<ViewProps> {
const { eva, style, label, caption, children, ...touchableProps } = this.props;
const evaStyle = this.getComponentStyle(eva.style);
return (
<View style={style}>
<FalsyText
style={[styles.label, evaStyle.label]}
component={label}
/>
<Popover
style={[styles.popover, evaStyle.popover]}
visible={this.state.listVisible}
fullWidth={true}
anchor={() => this.renderInputElement(touchableProps, evaStyle)}
onBackdropPress={this.onBackdropPress}
>
<>
{this.renderSearchInput()}
<List
style={styles.list}
data={this.data}
bounces={false}
renderItem={this.renderItem}
/>
</>
</Popover>
<FalsyText
style={[styles.caption, evaStyle.caption]}
component={caption}
/>
</View>
);
}
}
const styles = StyleSheet.create({
input: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
},
popover: {
overflow: 'hidden',
},
list: {
flexGrow: 0,
},
text: {
flex: 1,
textAlign: 'left',
},
label: {
textAlign: 'left',
},
caption: {
textAlign: 'left',
},
searchInput: {
padding: 10,
borderBottomWidth: 1,
borderBottomColor: '#e0e0e0',
},
});