-
Notifications
You must be signed in to change notification settings - Fork 4.1k
/
Select.js
1825 lines (1683 loc) · 52.6 KB
/
Select.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
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
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// @flow
import React, { Component, type ElementRef, type Node } from 'react';
import memoizeOne from 'memoize-one';
import { MenuPlacer } from './components/Menu';
import isEqual from './internal/react-fast-compare';
import { createFilter } from './filters';
import {
A11yText,
DummyInput,
ScrollBlock,
ScrollCaptor,
} from './internal/index';
import {
valueFocusAriaMessage,
optionFocusAriaMessage,
resultsAriaMessage,
valueEventAriaMessage,
instructionsAriaMessage,
type InstructionsContext,
type ValueEventContext,
} from './accessibility/index';
import {
classNames,
cleanValue,
isTouchCapable,
isMobileDevice,
noop,
scrollIntoView,
isDocumentElement,
} from './utils';
import {
formatGroupLabel,
getOptionLabel,
getOptionValue,
isOptionDisabled,
} from './builtins';
import {
defaultComponents,
type PlaceholderOrValue,
type SelectComponents,
type SelectComponentsConfig,
} from './components/index';
import { defaultStyles, type StylesConfig } from './styles';
import { defaultTheme, type ThemeConfig } from './theme';
import type {
ActionMeta,
ActionTypes,
FocusDirection,
FocusEventHandler,
GroupType,
InputActionMeta,
KeyboardEventHandler,
MenuPlacement,
MenuPosition,
OptionsType,
OptionType,
ValueType,
} from './types';
type MouseOrTouchEvent =
| SyntheticMouseEvent<HTMLElement>
| SyntheticTouchEvent<HTMLElement>;
type FormatOptionLabelContext = 'menu' | 'value';
type FormatOptionLabelMeta = {
context: FormatOptionLabelContext,
inputValue: string,
selectValue: ValueType,
};
export type Props = {
/* Aria label (for assistive tech) */
'aria-label'?: string,
/* HTML ID of an element that should be used as the label (for assistive tech) */
'aria-labelledby'?: string,
/* Focus the control when it is mounted */
autoFocus?: boolean,
/* Remove the currently focused option when the user presses backspace */
backspaceRemovesValue: boolean,
/* Remove focus from the input when the user selects an option (handy for dismissing the keyboard on touch devices) */
blurInputOnSelect: boolean,
/* When the user reaches the top/bottom of the menu, prevent scroll on the scroll-parent */
captureMenuScroll: boolean,
/* Sets a className attribute on the outer component */
className?: string,
/*
If provided, all inner components will be given a prefixed className attribute.
This is useful when styling via CSS classes instead of the Styles API approach.
*/
classNamePrefix?: string | null,
/* Close the select menu when the user selects an option */
closeMenuOnSelect: boolean,
/*
If `true`, close the select menu when the user scrolls the document/body.
If a function, takes a standard javascript `ScrollEvent` you return a boolean:
`true` => The menu closes
`false` => The menu stays open
This is useful when you have a scrollable modal and want to portal the menu out,
but want to avoid graphical issues.
*/
closeMenuOnScroll: boolean | EventListener,
/*
This complex object includes all the compositional components that are used
in `react-select`. If you wish to overwrite a component, pass in an object
with the appropriate namespace.
If you only wish to restyle a component, we recommend using the `styles` prop
instead. For a list of the components that can be passed in, and the shape
that will be passed to them, see [the components docs](/components)
*/
components: SelectComponentsConfig,
/* Whether the value of the select, e.g. SingleValue, should be displayed in the control. */
controlShouldRenderValue: boolean,
/* Delimiter used to join multiple values into a single HTML Input value */
delimiter?: string,
/* Clear all values when the user presses escape AND the menu is closed */
escapeClearsValue: boolean,
/* Custom method to filter whether an option should be displayed in the menu */
filterOption: ((Object, string) => boolean) | null,
/*
Formats group labels in the menu as React components
An example can be found in the [Replacing builtins](/advanced#replacing-builtins) documentation.
*/
formatGroupLabel: typeof formatGroupLabel,
/* Formats option labels in the menu and control as React components */
formatOptionLabel?: (OptionType, FormatOptionLabelMeta) => Node,
/* Resolves option data to a string to be displayed as the label by components */
getOptionLabel: typeof getOptionLabel,
/* Resolves option data to a string to compare options and specify value attributes */
getOptionValue: typeof getOptionValue,
/* Hide the selected option from the menu */
hideSelectedOptions: boolean,
/* The id to set on the SelectContainer component. */
id?: string,
/* The value of the search input */
inputValue: string,
/* The id of the search input */
inputId?: string,
/* Define an id prefix for the select components e.g. {your-id}-value */
instanceId?: number | string,
/* Is the select value clearable */
isClearable?: boolean,
/* Is the select disabled */
isDisabled: boolean,
/* Is the select in a state of loading (async) */
isLoading: boolean,
/*
Override the built-in logic to detect whether an option is disabled
An example can be found in the [Replacing builtins](/advanced#replacing-builtins) documentation.
*/
isOptionDisabled: (OptionType, OptionsType) => boolean | false,
/* Override the built-in logic to detect whether an option is selected */
isOptionSelected?: (OptionType, OptionsType) => boolean,
/* Support multiple selected options */
isMulti: boolean,
/* Is the select direction right-to-left */
isRtl: boolean,
/* Whether to enable search functionality */
isSearchable: boolean,
/* Async: Text to display when loading options */
loadingMessage: ({ inputValue: string }) => string | null,
/* Minimum height of the menu before flipping */
minMenuHeight: number,
/* Maximum height of the menu before scrolling */
maxMenuHeight: number,
/* Whether the menu is open */
menuIsOpen: boolean,
/* Default placement of the menu in relation to the control. 'auto' will flip
when there isn't enough space below the control. */
menuPlacement: MenuPlacement,
/* The CSS position value of the menu, when "fixed" extra layout management is required */
menuPosition: MenuPosition,
/*
Whether the menu should use a portal, and where it should attach
An example can be found in the [Portaling](/advanced#portaling) documentation
*/
menuPortalTarget?: HTMLElement,
/* Whether to block scroll events when the menu is open */
menuShouldBlockScroll: boolean,
/* Whether the menu should be scrolled into view when it opens */
menuShouldScrollIntoView: boolean,
/* Name of the HTML Input (optional - without this, no input will be rendered) */
name?: string,
/* Text to display when there are no options */
noOptionsMessage: ({ inputValue: string }) => string | null,
/* Handle blur events on the control */
onBlur?: FocusEventHandler,
/* Handle change events on the select */
onChange: (ValueType, ActionMeta) => void,
/* Handle focus events on the control */
onFocus?: FocusEventHandler,
/* Handle change events on the input */
onInputChange: (string, InputActionMeta) => void,
/* Handle key down events on the select */
onKeyDown?: KeyboardEventHandler,
/* Handle the menu opening */
onMenuOpen: () => void,
/* Handle the menu closing */
onMenuClose: () => void,
/* Fired when the user scrolls to the top of the menu */
onMenuScrollToTop?: (SyntheticEvent<HTMLElement>) => void,
/* Fired when the user scrolls to the bottom of the menu */
onMenuScrollToBottom?: (SyntheticEvent<HTMLElement>) => void,
/* Allows control of whether the menu is opened when the Select is focused */
openMenuOnFocus: boolean,
/* Allows control of whether the menu is opened when the Select is clicked */
openMenuOnClick: boolean,
/* Array of options that populate the select menu */
options: OptionsType,
/* Number of options to jump in menu when page{up|down} keys are used */
pageSize: number,
/* Placeholder text for the select value */
placeholder: string,
/* Status to relay to screen readers */
screenReaderStatus: ({ count: number }) => string,
/*
Style modifier methods
A basic example can be found at the bottom of the [Replacing builtins](/advanced#replacing-builtins) documentation.
*/
styles: StylesConfig,
/* Theme modifier method */
theme?: ThemeConfig,
/* Sets the tabIndex attribute on the input */
tabIndex: string,
/* Select the currently focused option when the user presses tab */
tabSelectsValue: boolean,
/* The value of the select; reflected by the selected option */
value: ValueType,
};
export const defaultProps = {
backspaceRemovesValue: true,
blurInputOnSelect: isTouchCapable(),
captureMenuScroll: !isTouchCapable(),
closeMenuOnSelect: true,
closeMenuOnScroll: false,
components: {},
controlShouldRenderValue: true,
escapeClearsValue: false,
filterOption: createFilter(),
formatGroupLabel: formatGroupLabel,
getOptionLabel: getOptionLabel,
getOptionValue: getOptionValue,
isDisabled: false,
isLoading: false,
isMulti: false,
isRtl: false,
isSearchable: true,
isOptionDisabled: isOptionDisabled,
loadingMessage: () => 'Loading...',
maxMenuHeight: 300,
minMenuHeight: 140,
menuIsOpen: false,
menuPlacement: 'bottom',
menuPosition: 'absolute',
menuShouldBlockScroll: false,
menuShouldScrollIntoView: !isMobileDevice(),
noOptionsMessage: () => 'No options',
openMenuOnFocus: false,
openMenuOnClick: true,
options: [],
pageSize: 5,
placeholder: 'Select...',
screenReaderStatus: ({ count }: { count: number }) =>
`${count} result${count !== 1 ? 's' : ''} available`,
styles: {},
tabIndex: '0',
tabSelectsValue: true,
};
type MenuOptions = {
render: Array<OptionType>,
focusable: Array<OptionType>,
};
type State = {
ariaLiveSelection: string,
ariaLiveContext: string,
inputIsHidden: boolean,
isFocused: boolean,
isComposing: boolean,
focusedOption: OptionType | null,
focusedValue: OptionType | null,
menuOptions: MenuOptions,
selectValue: OptionsType,
};
type ElRef = ElementRef<*>;
let instanceId = 1;
export default class Select extends Component<Props, State> {
static defaultProps = defaultProps;
state = {
ariaLiveSelection: '',
ariaLiveContext: '',
focusedOption: null,
focusedValue: null,
inputIsHidden: false,
isFocused: false,
isComposing: false,
menuOptions: { render: [], focusable: [] },
selectValue: [],
};
// Misc. Instance Properties
// ------------------------------
blockOptionHover: boolean = false;
clearFocusValueOnUpdate: boolean = false;
commonProps: any; // TODO
components: SelectComponents;
hasGroups: boolean = false;
initialTouchX: number = 0;
initialTouchY: number = 0;
inputIsHiddenAfterUpdate: ?boolean;
instancePrefix: string = '';
openAfterFocus: boolean = false;
scrollToFocusedOptionOnUpdate: boolean = false;
userIsDragging: ?boolean;
// Refs
// ------------------------------
controlRef: ElRef = null;
getControlRef = (ref: HTMLElement) => {
this.controlRef = ref;
};
focusedOptionRef: ElRef = null;
getFocusedOptionRef = (ref: HTMLElement) => {
this.focusedOptionRef = ref;
};
menuListRef: ElRef = null;
getMenuListRef = (ref: HTMLElement) => {
this.menuListRef = ref;
};
inputRef: ElRef = null;
getInputRef = (ref: HTMLElement) => {
this.inputRef = ref;
};
// Lifecycle
// ------------------------------
constructor(props: Props) {
super(props);
const { value } = props;
this.cacheComponents = memoizeOne(this.cacheComponents, isEqual).bind(this);
this.cacheComponents(props.components);
this.instancePrefix =
'react-select-' + (this.props.instanceId || ++instanceId);
const selectValue = cleanValue(value);
const menuOptions = this.buildMenuOptions(props, selectValue);
this.state.menuOptions = menuOptions;
this.state.selectValue = selectValue;
}
componentDidMount() {
this.startListeningComposition();
this.startListeningToTouch();
if (this.props.closeMenuOnScroll && document && document.addEventListener) {
// Listen to all scroll events, and filter them out inside of 'onScroll'
document.addEventListener('scroll', this.onScroll, true);
}
if (this.props.autoFocus) {
this.focusInput();
}
}
componentWillReceiveProps(nextProps: Props) {
const { options, value, inputValue } = this.props;
// re-cache custom components
this.cacheComponents(nextProps.components);
// rebuild the menu options
if (
nextProps.value !== value ||
nextProps.options !== options ||
nextProps.inputValue !== inputValue
) {
const selectValue = cleanValue(nextProps.value);
const menuOptions = this.buildMenuOptions(nextProps, selectValue);
const focusedValue = this.getNextFocusedValue(selectValue);
const focusedOption = this.getNextFocusedOption(menuOptions.focusable);
this.setState({ menuOptions, selectValue, focusedOption, focusedValue });
}
// some updates should toggle the state of the input visibility
if (this.inputIsHiddenAfterUpdate != null) {
this.setState({
inputIsHidden: this.inputIsHiddenAfterUpdate,
});
delete this.inputIsHiddenAfterUpdate;
}
}
componentDidUpdate(prevProps: Props) {
const { isDisabled, menuIsOpen } = this.props;
const { isFocused } = this.state;
if (
// ensure focus is restored correctly when the control becomes enabled
(isFocused && !isDisabled && prevProps.isDisabled) ||
// ensure focus is on the Input when the menu opens
(isFocused && menuIsOpen && !prevProps.menuIsOpen)
) {
this.focusInput();
}
// scroll the focused option into view if necessary
if (
this.menuListRef &&
this.focusedOptionRef &&
this.scrollToFocusedOptionOnUpdate
) {
scrollIntoView(this.menuListRef, this.focusedOptionRef);
}
this.scrollToFocusedOptionOnUpdate = false;
}
componentWillUnmount() {
this.stopListeningComposition();
this.stopListeningToTouch();
document.removeEventListener('scroll', this.onScroll, true);
}
cacheComponents = (components: SelectComponents) => {
this.components = defaultComponents({ components });
};
// ==============================
// Consumer Handlers
// ==============================
onMenuOpen() {
this.props.onMenuOpen();
}
onMenuClose() {
const { isSearchable, isMulti } = this.props;
this.announceAriaLiveContext({
event: 'input',
context: { isSearchable, isMulti },
});
this.onInputChange('', { action: 'menu-close' });
this.props.onMenuClose();
}
onInputChange(newValue: string, actionMeta: InputActionMeta) {
this.props.onInputChange(newValue, actionMeta);
}
// ==============================
// Methods
// ==============================
focusInput() {
if (!this.inputRef) return;
this.inputRef.focus();
}
blurInput() {
if (!this.inputRef) return;
this.inputRef.blur();
}
// aliased for consumers
focus = this.focusInput;
blur = this.blurInput;
openMenu(focusOption: 'first' | 'last') {
const { menuOptions, selectValue } = this.state;
const { isMulti } = this.props;
let openAtIndex =
focusOption === 'first' ? 0 : menuOptions.focusable.length - 1;
if (!isMulti) {
const selectedIndex = menuOptions.focusable.indexOf(selectValue[0]);
if (selectedIndex > -1) {
openAtIndex = selectedIndex;
}
}
this.scrollToFocusedOptionOnUpdate = true;
this.inputIsHiddenAfterUpdate = false;
this.onMenuOpen();
this.setState({
focusedValue: null,
focusedOption: menuOptions.focusable[openAtIndex],
});
this.announceAriaLiveContext({ event: 'menu' });
}
focusValue(direction: 'previous' | 'next') {
const { isMulti, isSearchable } = this.props;
const { selectValue, focusedValue } = this.state;
// Only multiselects support value focusing
if (!isMulti) return;
this.setState({
focusedOption: null,
});
let focusedIndex = selectValue.indexOf(focusedValue);
if (!focusedValue) {
focusedIndex = -1;
this.announceAriaLiveContext({ event: 'value' });
}
const lastIndex = selectValue.length - 1;
let nextFocus = -1;
if (!selectValue.length) return;
switch (direction) {
case 'previous':
if (focusedIndex === 0) {
// don't cycle from the start to the end
nextFocus = 0;
} else if (focusedIndex === -1) {
// if nothing is focused, focus the last value first
nextFocus = lastIndex;
} else {
nextFocus = focusedIndex - 1;
}
break;
case 'next':
if (focusedIndex > -1 && focusedIndex < lastIndex) {
nextFocus = focusedIndex + 1;
}
break;
}
if (nextFocus === -1) {
this.announceAriaLiveContext({
event: 'input',
context: { isSearchable, isMulti },
});
}
this.setState({
inputIsHidden: nextFocus === -1 ? false : true,
focusedValue: selectValue[nextFocus],
});
}
focusOption(direction: FocusDirection = 'first') {
const { pageSize } = this.props;
const { focusedOption, menuOptions } = this.state;
const options = menuOptions.focusable;
if (!options.length) return;
let nextFocus = 0; // handles 'first'
let focusedIndex = options.indexOf(focusedOption);
if (!focusedOption) {
focusedIndex = -1;
this.announceAriaLiveContext({ event: 'menu' });
}
if (direction === 'up') {
nextFocus = focusedIndex > 0 ? focusedIndex - 1 : options.length - 1;
} else if (direction === 'down') {
nextFocus = (focusedIndex + 1) % options.length;
} else if (direction === 'pageup') {
nextFocus = focusedIndex - pageSize;
if (nextFocus < 0) nextFocus = 0;
} else if (direction === 'pagedown') {
nextFocus = focusedIndex + pageSize;
if (nextFocus > options.length - 1) nextFocus = options.length - 1;
} else if (direction === 'last') {
nextFocus = options.length - 1;
}
this.scrollToFocusedOptionOnUpdate = true;
this.setState({
focusedOption: options[nextFocus],
focusedValue: null,
});
}
onChange = (newValue: ValueType, actionMeta: ActionMeta) => {
const { onChange, name } = this.props;
onChange(newValue, { ...actionMeta, name });
};
setValue = (
newValue: ValueType,
action: ActionTypes = 'set-value',
option?: OptionType
) => {
const { closeMenuOnSelect, isMulti } = this.props;
this.onInputChange('', { action: 'set-value' });
if (closeMenuOnSelect) {
this.inputIsHiddenAfterUpdate = !isMulti;
this.onMenuClose();
}
// when the select value should change, we should reset focusedValue
this.clearFocusValueOnUpdate = true;
this.onChange(newValue, { action, option });
};
selectOption = (newValue: OptionType) => {
const { blurInputOnSelect, isMulti } = this.props;
if (isMulti) {
const { selectValue } = this.state;
if (this.isOptionSelected(newValue, selectValue)) {
const candidate = this.getOptionValue(newValue);
this.setValue(
selectValue.filter(i => this.getOptionValue(i) !== candidate),
'deselect-option',
newValue
);
this.announceAriaLiveSelection({
event: 'deselect-option',
context: { value: this.getOptionLabel(newValue) },
});
} else {
this.setValue([...selectValue, newValue], 'select-option', newValue);
this.announceAriaLiveSelection({
event: 'select-option',
context: { value: this.getOptionLabel(newValue) },
});
}
} else {
this.setValue(newValue, 'select-option');
this.announceAriaLiveSelection({
event: 'select-option',
context: { value: this.getOptionLabel(newValue) },
});
}
if (blurInputOnSelect) {
this.blurInput();
}
};
removeValue = (removedValue: OptionType) => {
const { selectValue } = this.state;
const candidate = this.getOptionValue(removedValue);
this.onChange(selectValue.filter(i => this.getOptionValue(i) !== candidate), {
action: 'remove-value',
removedValue,
});
this.announceAriaLiveSelection({
event: 'remove-value',
context: {
value: removedValue ? this.getOptionLabel(removedValue) : undefined,
},
});
this.focusInput();
};
clearValue = () => {
const { isMulti } = this.props;
this.onChange(isMulti ? [] : null, { action: 'clear' });
};
popValue = () => {
const { selectValue } = this.state;
const lastSelectedValue = selectValue[selectValue.length - 1];
this.announceAriaLiveSelection({
event: 'pop-value',
context: {
value: lastSelectedValue
? this.getOptionLabel(lastSelectedValue)
: undefined,
},
});
this.onChange(selectValue.slice(0, selectValue.length - 1), {
action: 'pop-value',
removedValue: lastSelectedValue,
});
};
// ==============================
// Getters
// ==============================
getTheme() {
// Use the default theme if there are no customizations.
if (!this.props.theme) {
return defaultTheme;
}
// If the theme prop is a function, assume the function
// knows how to merge the passed-in default theme with
// its own modifications.
if (typeof this.props.theme === 'function') {
return this.props.theme(defaultTheme);
}
// Otherwise, if a plain theme object was passed in,
// overlay it with the default theme.
return {
...defaultTheme,
...this.props.theme,
};
}
getCommonProps() {
const { clearValue, getStyles, setValue, selectOption, props } = this;
const { classNamePrefix, isMulti, isRtl, options } = props;
const { selectValue } = this.state;
const hasValue = this.hasValue();
const getValue = () => selectValue;
let cxPrefix = classNamePrefix;
const cx = classNames.bind(null, cxPrefix);
return {
cx,
clearValue,
getStyles,
getValue,
hasValue,
isMulti,
isRtl,
options,
selectOption,
setValue,
selectProps: props,
theme: this.getTheme(),
};
}
getNextFocusedValue(nextSelectValue: OptionsType) {
if (this.clearFocusValueOnUpdate) {
this.clearFocusValueOnUpdate = false;
return null;
}
const { focusedValue, selectValue: lastSelectValue } = this.state;
const lastFocusedIndex = lastSelectValue.indexOf(focusedValue);
if (lastFocusedIndex > -1) {
const nextFocusedIndex = nextSelectValue.indexOf(focusedValue);
if (nextFocusedIndex > -1) {
// the focused value is still in the selectValue, return it
return focusedValue;
} else if (lastFocusedIndex < nextSelectValue.length) {
// the focusedValue is not present in the next selectValue array by
// reference, so return the new value at the same index
return nextSelectValue[lastFocusedIndex];
}
}
return null;
}
getNextFocusedOption(options: OptionsType) {
const { focusedOption: lastFocusedOption } = this.state;
return lastFocusedOption && options.indexOf(lastFocusedOption) > -1
? lastFocusedOption
: options[0];
}
getOptionLabel = (data: OptionType): string => {
return this.props.getOptionLabel(data);
};
getOptionValue = (data: OptionType): string => {
return this.props.getOptionValue(data);
};
getStyles = (key: string, props: {}): {} => {
const base = defaultStyles[key](props);
base.boxSizing = 'border-box';
const custom = this.props.styles[key];
return custom ? custom(base, props) : base;
};
getElementId = (element: 'group' | 'input' | 'listbox' | 'option') => {
return `${this.instancePrefix}-${element}`;
};
getActiveDescendentId = () => {
const { menuIsOpen } = this.props;
const { menuOptions, focusedOption } = this.state;
if (!focusedOption || !menuIsOpen) return undefined;
const index = menuOptions.focusable.indexOf(focusedOption);
const option = menuOptions.render[index];
return option && option.key;
};
// ==============================
// Helpers
// ==============================
announceAriaLiveSelection = ({
event,
context,
}: {
event: string,
context: ValueEventContext,
}) => {
this.setState({
ariaLiveSelection: valueEventAriaMessage(event, context),
});
};
announceAriaLiveContext = ({
event,
context,
}: {
event: string,
context?: InstructionsContext,
}) => {
this.setState({
ariaLiveContext: instructionsAriaMessage(event, {
...context,
label: this.props['aria-label'],
}),
});
};
hasValue() {
const { selectValue } = this.state;
return selectValue.length > 0;
}
hasOptions() {
return !!this.state.menuOptions.render.length;
}
countOptions() {
return this.state.menuOptions.focusable.length;
}
isClearable(): boolean {
const { isClearable, isMulti } = this.props;
// single select, by default, IS NOT clearable
// multi select, by default, IS clearable
if (isClearable === undefined) return isMulti;
return isClearable;
}
isOptionDisabled(option: OptionType, selectValue: OptionsType): boolean {
return typeof this.props.isOptionDisabled === 'function'
? this.props.isOptionDisabled(option, selectValue)
: false;
}
isOptionSelected(option: OptionType, selectValue: OptionsType): boolean {
if (selectValue.indexOf(option) > -1) return true;
if (typeof this.props.isOptionSelected === 'function') {
return this.props.isOptionSelected(option, selectValue);
}
const candidate = this.getOptionValue(option);
return selectValue.some(i => this.getOptionValue(i) === candidate);
}
filterOption(option: {}, inputValue: string) {
return this.props.filterOption
? this.props.filterOption(option, inputValue)
: true;
}
formatOptionLabel(data: OptionType, context: FormatOptionLabelContext): Node {
if (typeof this.props.formatOptionLabel === 'function') {
const { inputValue } = this.props;
const { selectValue } = this.state;
return this.props.formatOptionLabel(data, {
context,
inputValue,
selectValue,
});
} else {
return this.getOptionLabel(data);
}
}
formatGroupLabel(data: GroupType) {
return this.props.formatGroupLabel(data);
}
// ==============================
// Mouse Handlers
// ==============================
onMenuMouseDown = (event: SyntheticMouseEvent<HTMLElement>) => {
if (event.button !== 0) {
return;
}
event.stopPropagation();
event.preventDefault();
this.focusInput();
};
onMenuMouseMove = (event: SyntheticMouseEvent<HTMLElement>) => {
this.blockOptionHover = false;
};
onControlMouseDown = (event: MouseOrTouchEvent) => {
const { openMenuOnClick } = this.props;
if (!this.state.isFocused) {
if (openMenuOnClick) {
this.openAfterFocus = true;
}
this.focusInput();
} else if (!this.props.menuIsOpen) {
this.openMenu('first');
} else {
// $FlowFixMe HTMLElement type does not have tagName property
if (event.target.tagName !== 'INPUT') {
this.onMenuClose();
}
}
// $FlowFixMe HTMLElement type does not have tagName property
if (event.target.tagName !== 'INPUT') {
event.preventDefault();
}
};
onDropdownIndicatorMouseDown = (event: MouseOrTouchEvent) => {
// ignore mouse events that weren't triggered by the primary button
if (event && event.type === 'mousedown' && event.button !== 0) {
return;
}
if (this.props.isDisabled) return;
const { isMulti, menuIsOpen } = this.props;
this.focusInput();
if (menuIsOpen) {
this.inputIsHiddenAfterUpdate = !isMulti;
this.onMenuClose();
} else {
this.openMenu('first');
}
event.preventDefault();
event.stopPropagation();
};
onClearIndicatorMouseDown = (event: MouseOrTouchEvent) => {
// ignore mouse events that weren't triggered by the primary button
if (event && event.type === 'mousedown' && event.button !== 0) {
return;
}
this.clearValue();
event.stopPropagation();
this.openAfterFocus = false;
setTimeout(() => this.focusInput());
};
onScroll = (event: Event) => {
if (typeof this.props.closeMenuOnScroll === 'boolean') {
if (
event.target instanceof HTMLElement &&
isDocumentElement(event.target)
) {
this.props.onMenuClose();
}
} else if (typeof this.props.closeMenuOnScroll === 'function') {
if (this.props.closeMenuOnScroll(event)) {
this.props.onMenuClose();
}
}
};
// ==============================
// Composition Handlers
// ==============================
startListeningComposition() {
if (document && document.addEventListener) {
document.addEventListener(
'compositionstart',
this.onCompositionStart,
false
);
document.addEventListener('compositionend', this.onCompositionEnd, false);
}
}
stopListeningComposition() {
if (document && document.removeEventListener) {
document.removeEventListener('compositionstart', this.onCompositionStart);
document.removeEventListener('compositionend', this.onCompositionEnd);
}
}
onCompositionStart = () => {
this.setState({
isComposing: true,
});
};
onCompositionEnd = () => {
this.setState({
isComposing: false,
});
};
// ==============================
// Touch Handlers
// ==============================
startListeningToTouch() {
if (document && document.addEventListener) {
document.addEventListener('touchstart', this.onTouchStart, false);
document.addEventListener('touchmove', this.onTouchMove, false);
document.addEventListener('touchend', this.onTouchEnd, false);
}
}
stopListeningToTouch() {
if (document && document.removeEventListener) {
document.removeEventListener('touchstart', this.onTouchStart);
document.removeEventListener('touchmove', this.onTouchMove);
document.removeEventListener('touchend', this.onTouchEnd);
}
}
onTouchStart = ({ touches }: TouchEvent) => {
const touch = touches.item(0);
if (!touch) {
return;
}
this.initialTouchX = touch.clientX;
this.initialTouchY = touch.clientY;
this.userIsDragging = false;
};
onTouchMove = ({ touches }: TouchEvent) => {