-
Notifications
You must be signed in to change notification settings - Fork 843
/
Copy pathcombo_box.tsx
1076 lines (954 loc) Β· 31 KB
/
combo_box.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
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
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
* Elements within EuiComboBox which would normally be tabbable (inputs, buttons) have been removed
* from the tab order with tabindex={-1} so that we can control the keyboard navigation interface.
*/
/* eslint-disable jsx-a11y/role-has-required-aria-props */
import React, {
Component,
FocusEventHandler,
HTMLAttributes,
KeyboardEventHandler,
RefCallback,
} from 'react';
import classNames from 'classnames';
import { findPopoverPosition, htmlIdGenerator, keys } from '../../services';
import { EuiPortal } from '../portal';
import { EuiComboBoxOptionsList } from './combo_box_options_list';
import {
getMatchingOptions,
flattenOptionGroups,
getSelectedOptionForSearchValue,
} from './matching_options';
import {
EuiComboBoxInputProps,
EuiComboBoxInput,
} from './combo_box_input/combo_box_input';
import { EuiComboBoxOptionsListProps } from './combo_box_options_list/combo_box_options_list';
import {
UpdatePositionHandler,
OptionHandler,
RefInstance,
EuiComboBoxOptionOption,
EuiComboBoxOptionsListPosition,
EuiComboBoxSingleSelectionShape,
} from './types';
import { EuiFilterSelectItem } from '../filter_group';
import AutosizeInput from 'react-input-autosize';
import { CommonProps } from '../common';
import { EuiFormControlLayoutProps } from '../form';
import { getElementZIndex } from '../../services/popover';
type DrillProps<T> = Pick<
EuiComboBoxOptionsListProps<T>,
'onCreateOption' | 'options' | 'renderOption' | 'selectedOptions'
>;
interface _EuiComboBoxProps<T>
extends CommonProps,
Omit<HTMLAttributes<HTMLDivElement>, 'onChange'>,
DrillProps<T> {
'data-test-subj'?: string;
/**
* Updates the list of options asynchronously
*/
async: boolean;
className?: string;
/**
* When `true` creates a shorter height input
*/
compressed: boolean;
/**
* When `true` expands to the entire width available
*/
fullWidth: boolean;
id?: string;
inputRef?: RefCallback<HTMLInputElement>;
/**
* Shows a button that quickly clears any input
*/
isClearable: boolean;
/**
* Disables the input
*/
isDisabled?: boolean;
isInvalid?: boolean;
/**
* Swaps the dropdown options for a loading spinner
*/
isLoading?: boolean;
/**
* Doesn't show the suggestions list/dropdown
*/
noSuggestions?: boolean;
onBlur?: FocusEventHandler<HTMLDivElement>;
/**
* Called every time the query in the combo box is parsed
*/
onChange?: (options: Array<EuiComboBoxOptionOption<T>>) => void;
onFocus?: FocusEventHandler<HTMLDivElement>;
onKeyDown?: KeyboardEventHandler<HTMLDivElement>;
/**
* Called every time the text query in the search box is parsed
*/
onSearchChange?: (searchValue: string, hasMatchingOptions?: boolean) => void;
/**
* Sets the placeholder of the input
*/
placeholder?: string;
/**
* Every option must be the same height and must be explicitly set if using a custom render
*/
rowHeight?: number;
/**
* When `true` only allows the user to select a single option. Set to `{ asPlainText: true }` to not render input selection as pills
*/
singleSelection: boolean | EuiComboBoxSingleSelectionShape;
/**
* Display matching options by:
* `startsWith`: moves items that start with search value to top of the list;
* `none`: don't change the sort order of initial object
*/
sortMatchesBy: 'none' | 'startsWith';
/**
* Creates an input group with element(s) coming before input. It won't show if `singleSelection` is set to `false`.
* `string` | `ReactElement` or an array of these
*/
prepend?: EuiFormControlLayoutProps['prepend'];
/**
* Creates an input group with element(s) coming after input. It won't show if `singleSelection` is set to `false`.
* `string` | `ReactElement` or an array of these
*/
append?: EuiFormControlLayoutProps['append'];
/**
* A special character to use as a value separator. Typically a comma `,`
*/
delimiter?: string;
}
/**
* Because of how TypeScript's LibraryManagedAttributes is designed to handle defaultProps (https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-0.html#support-for-defaultprops-in-jsx)
* we can't directly export the above Props definitions, as the defaulted values are not made optional
* as it isn't processed by LibraryManagedAttributes. To get around this, we:
* - remove the props which have default values applied
* - additionally re-define `options` and `selectedOptions` defaults, necessary as static members can't access generics and become never[]
* - export (Props - Defaults) & Partial<Defaults>
*/
type DefaultProps<T> = Omit<
typeof EuiComboBox['defaultProps'],
'options' | 'selectedOptions'
> & {
options: Array<EuiComboBoxOptionOption<T>>;
selectedOptions: Array<EuiComboBoxOptionOption<T>>;
};
export type EuiComboBoxProps<T> = Omit<
_EuiComboBoxProps<T>,
keyof DefaultProps<T>
> &
Partial<DefaultProps<T>>;
interface EuiComboBoxState<T> {
activeOptionIndex: number;
hasFocus: boolean;
isListOpen: boolean;
listElement?: RefInstance<HTMLDivElement>;
listPosition: EuiComboBoxOptionsListPosition;
listZIndex: number | undefined;
matchingOptions: Array<EuiComboBoxOptionOption<T>>;
searchValue: string;
width: number;
}
const initialSearchValue = '';
export class EuiComboBox<T> extends Component<
_EuiComboBoxProps<T>,
EuiComboBoxState<T>
> {
static defaultProps = {
async: false,
compressed: false,
fullWidth: false,
isClearable: true,
options: [],
selectedOptions: [],
singleSelection: false,
prepend: undefined,
append: undefined,
sortMatchesBy: 'none' as const,
};
state: EuiComboBoxState<T> = {
activeOptionIndex: -1,
hasFocus: false,
isListOpen: false,
listElement: null,
listPosition: 'bottom',
listZIndex: undefined,
matchingOptions: getMatchingOptions<T>(
this.props.options,
this.props.selectedOptions,
initialSearchValue,
this.props.async,
Boolean(this.props.singleSelection)
),
searchValue: initialSearchValue,
width: 0,
};
_isMounted = false;
rootId = htmlIdGenerator();
// Refs
comboBoxRefInstance: RefInstance<HTMLDivElement> = null;
comboBoxRefCallback: RefCallback<HTMLDivElement> = ref => {
// IE11 doesn't support the `relatedTarget` event property for blur events
// but does add it for focusout. React doesn't support `onFocusOut` so here we are.
if (this.comboBoxRefInstance) {
this.comboBoxRefInstance.removeEventListener(
'focusout',
this.onContainerBlur
);
}
this.comboBoxRefInstance = ref;
if (this.comboBoxRefInstance) {
this.comboBoxRefInstance.addEventListener(
'focusout',
this.onContainerBlur
);
const comboBoxBounds = this.comboBoxRefInstance.getBoundingClientRect();
this.setState({
width: comboBoxBounds.width,
});
}
};
autoSizeInputRefInstance: RefInstance<AutosizeInput & HTMLDivElement> = null;
autoSizeInputRefCallback: RefCallback<
AutosizeInput & HTMLDivElement
> = ref => {
this.autoSizeInputRefInstance = ref;
};
searchInputRefInstance: RefInstance<HTMLInputElement> = null;
searchInputRefCallback: RefCallback<HTMLInputElement> = ref => {
this.searchInputRefInstance = ref;
if (this.props.inputRef) this.props.inputRef(ref);
};
listRefInstance: RefInstance<HTMLDivElement> = null;
listRefCallback: RefCallback<HTMLDivElement> = ref => {
if (this.comboBoxRefInstance) {
// find the zIndex of the combobox relative to the page body
// and use that to depth-position the list box
// adds an extra `100` to provide some defense around neighboring elements' positioning
const listZIndex =
getElementZIndex(this.comboBoxRefInstance, document.body) + 100;
this.setState({ listZIndex });
}
this.listRefInstance = ref;
};
toggleButtonRefInstance: RefInstance<
HTMLButtonElement | HTMLSpanElement
> = null;
toggleButtonRefCallback: RefCallback<
HTMLButtonElement | HTMLSpanElement
> = ref => {
this.toggleButtonRefInstance = ref;
};
optionsRefInstances: Array<RefInstance<EuiFilterSelectItem>> = [];
optionRefCallback: EuiComboBoxOptionsListProps<T>['optionRef'] = (
index,
ref
) => {
this.optionsRefInstances[index] = ref;
};
openList = () => {
this.setState({
isListOpen: true,
});
};
closeList = () => {
this.clearActiveOption();
this.setState({
listZIndex: undefined,
isListOpen: false,
});
};
updatePosition: UpdatePositionHandler = (
listElement = this.state.listElement
) => {
if (!this._isMounted) {
return;
}
if (!this.state.isListOpen) {
return;
}
if (!listElement) {
return;
}
// it's possible that updateListPosition is called when listElement is becoming visible, but isn't yet
const listElementBounds = listElement.getBoundingClientRect();
if (listElementBounds.width === 0 || listElementBounds.height === 0) {
return;
}
if (!this.comboBoxRefInstance) {
return;
}
const comboBoxBounds = this.comboBoxRefInstance.getBoundingClientRect();
const { position, top } = findPopoverPosition({
allowCrossAxis: false,
anchor: this.comboBoxRefInstance,
popover: listElement,
position: 'bottom',
}) as { position: 'bottom'; top: number };
if (this.listRefInstance) {
this.listRefInstance.style.top = `${top}px`;
// listElement doesn't have its width set until after updating the position
// which means the popover service won't know about the correct width
// however, we already know where to position the element
this.listRefInstance.style.left = `${comboBoxBounds.left +
window.pageXOffset}px`;
this.listRefInstance.style.width = `${comboBoxBounds.width}px`;
}
// Cache for future calls.
this.setState({
listElement,
listPosition: position,
width: comboBoxBounds.width,
});
};
incrementActiveOptionIndex = (amount: number) => {
// If there are no options available, do nothing.
if (!this.state.matchingOptions.length) {
return;
}
this.setState(({ activeOptionIndex, matchingOptions }) => {
let nextActiveOptionIndex;
if (activeOptionIndex < 0) {
// If this is the beginning of the user's keyboard navigation of the menu, then we'll focus
// either the first or last item.
nextActiveOptionIndex = amount < 0 ? matchingOptions.length - 1 : 0;
} else {
nextActiveOptionIndex = activeOptionIndex + amount;
if (nextActiveOptionIndex < 0) {
nextActiveOptionIndex = matchingOptions.length - 1;
} else if (nextActiveOptionIndex === matchingOptions.length) {
nextActiveOptionIndex = 0;
}
}
// Group titles are included in option list but are not selectable
// Skip group title options
const direction = amount > 0 ? 1 : -1;
while (matchingOptions[nextActiveOptionIndex].isGroupLabelOption) {
nextActiveOptionIndex = nextActiveOptionIndex + direction;
if (nextActiveOptionIndex < 0) {
nextActiveOptionIndex = matchingOptions.length - 1;
} else if (nextActiveOptionIndex === matchingOptions.length) {
nextActiveOptionIndex = 0;
}
}
return { activeOptionIndex: nextActiveOptionIndex };
});
};
hasActiveOption = () => {
return (
this.state.activeOptionIndex > -1 &&
this.state.activeOptionIndex < this.state.matchingOptions.length
);
};
clearActiveOption = () => {
this.setState({
activeOptionIndex: -1,
});
};
clearSearchValue = () => {
this.onSearchChange('');
};
removeLastOption = () => {
if (!this.props.selectedOptions.length) {
return;
}
// Backspace will be used to delete the input, not a pill.
if (this.state.searchValue.length) {
return;
}
// Delete last pill.
this.onRemoveOption(
this.props.selectedOptions[this.props.selectedOptions.length - 1]
);
if (Boolean(this.props.singleSelection) && !this.state.isListOpen) {
this.openList();
}
};
addCustomOption = (isContainerBlur: boolean, searchValue: string) => {
const {
onCreateOption,
options,
selectedOptions,
singleSelection,
} = this.props;
const { matchingOptions } = this.state;
if (this.doesSearchMatchOnlyOption()) {
this.onAddOption(matchingOptions[0], isContainerBlur);
return;
}
if (!onCreateOption) {
return;
}
// Don't bother trying to create an option if the user hasn't typed anything.
if (!searchValue) {
return;
}
// Don't create the value if it's already been selected.
if (getSelectedOptionForSearchValue(searchValue, selectedOptions)) {
return;
}
// Add new custom pill if this is custom input, even if it partially matches an option..
const isOptionCreated = onCreateOption(
searchValue,
flattenOptionGroups(options)
);
// Expect the consumer to be explicit in rejecting a custom option.
if (isOptionCreated === false) {
return;
}
this.clearSearchValue();
if (
this.isSingleSelectionCustomOption() ||
(Boolean(singleSelection) && matchingOptions.length < 1)
) {
// Adding a custom option to a single select that does not appear in the list of options
this.closeList();
}
};
doesSearchMatchOnlyOption = () => {
const { searchValue } = this.state;
if (this.state.matchingOptions.length !== 1) {
return false;
}
return (
this.state.matchingOptions[0].label.toLowerCase() ===
searchValue.toLowerCase()
);
};
areAllOptionsSelected = () => {
const { options, selectedOptions, async } = this.props;
// Assume if this is async then there could be infinite options.
if (async) {
return false;
}
const flattenOptions = flattenOptionGroups(options).map(option => {
return { ...option, label: option.label.trim().toLowerCase() };
});
let numberOfSelectedOptions = 0;
selectedOptions.forEach(({ label }) => {
const trimmedLabel = label.trim().toLowerCase();
if (
flattenOptions.findIndex(option => option.label === trimmedLabel) !== -1
)
numberOfSelectedOptions += 1;
});
return flattenOptions.length === numberOfSelectedOptions;
};
isSingleSelectionCustomOption = () => {
const {
onCreateOption,
options,
selectedOptions,
singleSelection,
} = this.props;
// The selected option of a single select is custom and does not appear in the list of options
return (
Boolean(singleSelection) &&
onCreateOption &&
selectedOptions.length > 0 &&
!JSON.stringify(options).includes(JSON.stringify(selectedOptions[0]))
);
};
onComboBoxFocus: FocusEventHandler<HTMLInputElement> = event => {
if (this.props.onFocus) {
this.props.onFocus(event);
}
if (!this.isSingleSelectionCustomOption()) {
this.openList();
}
this.setState({ hasFocus: true });
};
setCustomOptions = (isContainerBlur: boolean) => {
const { searchValue } = this.state;
const { delimiter } = this.props;
if (delimiter) {
searchValue.split(delimiter).forEach((option: string) => {
if (option.length > 0) this.addCustomOption(true, option);
});
} else {
this.addCustomOption(isContainerBlur, searchValue);
}
};
onContainerBlur: EventListener = event => {
// close the options list, unless the use clicked on an option
/**
* FireFox returns `relatedTarget` as `null` for security reasons, but provides a proprietary `explicitOriginalTarget`.
* @see https://developer.mozilla.org/en-US/docs/Web/API/Event/explicitOriginalTarget
*/
const focusEvent = event as FocusEvent & {
explicitOriginalTarget: EventTarget;
};
const relatedTarget = (focusEvent.relatedTarget ||
focusEvent.explicitOriginalTarget) as Node | null;
const focusedInOptionsList =
relatedTarget &&
this.listRefInstance &&
this.listRefInstance.contains(relatedTarget);
const focusedInInput =
relatedTarget &&
this.comboBoxRefInstance &&
this.comboBoxRefInstance.contains(relatedTarget);
if (!focusedInOptionsList && !focusedInInput) {
this.closeList();
if (this.props.onBlur) {
this.props.onBlur((event as unknown) as React.FocusEvent<
HTMLDivElement
>);
}
this.setState({ hasFocus: false });
// If the user tabs away or changes focus to another element, take whatever input they've
// typed and convert it into a pill, to prevent the combo box from looking like a text input.
if (!this.hasActiveOption()) {
this.setCustomOptions(true);
}
}
};
onKeyDown: KeyboardEventHandler<HTMLDivElement> = event => {
switch (event.key) {
case keys.ARROW_UP:
event.preventDefault();
event.stopPropagation();
if (this.state.isListOpen) {
this.incrementActiveOptionIndex(-1);
} else {
this.openList();
}
break;
case keys.ARROW_DOWN:
event.preventDefault();
event.stopPropagation();
if (this.state.isListOpen) {
this.incrementActiveOptionIndex(1);
} else {
this.openList();
}
break;
case keys.BACKSPACE:
event.stopPropagation();
this.removeLastOption();
break;
case keys.ESCAPE:
event.stopPropagation();
this.closeList();
break;
case keys.ENTER:
event.preventDefault();
event.stopPropagation();
if (this.hasActiveOption()) {
this.onAddOption(
this.state.matchingOptions[this.state.activeOptionIndex]
);
} else {
this.setCustomOptions(false);
}
break;
case keys.TAB:
// Disallow tabbing when the user is navigating the options.
if (this.hasActiveOption() && this.state.isListOpen) {
event.preventDefault();
event.stopPropagation();
}
break;
default:
if (this.props.onKeyDown) {
this.props.onKeyDown(event);
}
}
};
onOptionEnterKey: OptionHandler<T> = option => {
this.onAddOption(option);
};
onOptionClick: OptionHandler<T> = option => {
this.onAddOption(option);
};
onAddOption = (
addedOption: EuiComboBoxOptionOption<T>,
isContainerBlur?: boolean
) => {
if (addedOption.disabled) {
return;
}
const {
onChange,
selectedOptions,
singleSelection: singleSelectionProp,
} = this.props;
const singleSelection = Boolean(singleSelectionProp);
const changeOptions = singleSelection
? [addedOption]
: selectedOptions.concat(addedOption);
if (onChange) {
onChange(changeOptions);
}
this.clearSearchValue();
this.clearActiveOption();
if (!isContainerBlur) {
if (this.searchInputRefInstance) {
this.searchInputRefInstance.focus();
}
}
if (singleSelection) {
requestAnimationFrame(this.closeList);
} else {
this.setState({
activeOptionIndex: this.state.matchingOptions.indexOf(addedOption),
});
}
};
onRemoveOption: OptionHandler<T> = removedOption => {
const { onChange, selectedOptions } = this.props;
if (onChange) {
onChange(selectedOptions.filter(option => option !== removedOption));
}
this.clearActiveOption();
};
clearSelectedOptions = () => {
const { onChange } = this.props;
if (onChange) {
onChange([]);
}
// Clicking the clear button will also cause it to disappear. This would result in focus
// shifting unexpectedly to the body element so we set it to the input which is more reasonable,
if (this.searchInputRefInstance) {
this.searchInputRefInstance.focus();
}
if (!this.state.isListOpen) {
this.openList();
}
};
onComboBoxClick = () => {
// When the user clicks anywhere on the box, enter the interaction state.
if (this.searchInputRefInstance) {
this.searchInputRefInstance.focus();
}
// If the user does this from a state in which an option has focus, then we need to reset it or clear it.
if (
Boolean(this.props.singleSelection) &&
this.props.selectedOptions.length === 1
) {
this.setState({
activeOptionIndex: this.state.matchingOptions.indexOf(
this.props.selectedOptions[0]
),
});
} else {
this.clearActiveOption();
}
};
onOpenListClick = () => {
if (this.searchInputRefInstance) {
this.searchInputRefInstance.focus();
}
if (!this.state.isListOpen) {
this.openList();
}
};
onOptionListScroll = () => {
if (this.searchInputRefInstance) {
this.searchInputRefInstance.focus();
}
};
onCloseListClick = () => {
this.closeList();
};
onSearchChange: NonNullable<
EuiComboBoxInputProps<T>['onChange']
> = searchValue => {
const { onSearchChange, delimiter } = this.props;
if (onSearchChange) {
const hasMatchingOptions = this.state.matchingOptions.length > 0;
onSearchChange(searchValue, hasMatchingOptions);
}
this.setState({ searchValue }, () => {
if (searchValue && this.state.isListOpen === false) this.openList();
});
if (delimiter && searchValue.endsWith(delimiter)) {
searchValue.split(delimiter).forEach(value => {
if (value.length > 0) this.addCustomOption(false, value);
});
}
};
componentDidMount() {
this._isMounted = true;
// TODO: This will need to be called once the actual stylesheet loads.
setTimeout(() => {
if (this.autoSizeInputRefInstance) {
this.autoSizeInputRefInstance.copyInputStyles();
}
}, 100);
}
static getDerivedStateFromProps<T>(
nextProps: _EuiComboBoxProps<T>,
prevState: EuiComboBoxState<T>
) {
const { options, selectedOptions, singleSelection } = nextProps;
const { activeOptionIndex, searchValue } = prevState;
// Calculate and cache the options which match the searchValue, because we use this information
// in multiple places and it would be expensive to calculate repeatedly.
const matchingOptions = getMatchingOptions(
options,
selectedOptions,
searchValue,
nextProps.async,
Boolean(singleSelection)
);
const stateUpdate: Partial<EuiComboBoxState<T>> = { matchingOptions };
if (activeOptionIndex >= matchingOptions.length) {
stateUpdate.activeOptionIndex = -1;
}
return stateUpdate;
}
updateMatchingOptionsIfDifferent = (
newMatchingOptions: Array<EuiComboBoxOptionOption<T>>
) => {
const { matchingOptions, activeOptionIndex } = this.state;
const { singleSelection, selectedOptions } = this.props;
let areOptionsDifferent = false;
if (matchingOptions.length !== newMatchingOptions.length) {
areOptionsDifferent = true;
} else {
for (let i = 0; i < matchingOptions.length; i++) {
if (matchingOptions[i].label !== newMatchingOptions[i].label) {
areOptionsDifferent = true;
break;
}
}
}
if (areOptionsDifferent) {
this.optionsRefInstances = [];
let nextActiveOptionIndex = activeOptionIndex;
// ensure that the currently selected single option is active if it is in the matchingOptions
if (Boolean(singleSelection) && selectedOptions.length === 1) {
if (newMatchingOptions.includes(selectedOptions[0])) {
nextActiveOptionIndex = newMatchingOptions.indexOf(
selectedOptions[0]
);
}
}
this.setState({
matchingOptions: newMatchingOptions,
activeOptionIndex: nextActiveOptionIndex,
});
if (!newMatchingOptions.length) {
// Prevent endless setState -> componentWillUpdate -> setState loop.
if (this.hasActiveOption()) {
this.clearActiveOption();
}
}
}
};
componentDidUpdate() {
const { options, selectedOptions, singleSelection } = this.props;
const { searchValue } = this.state;
// React 16.3 has a bug (fixed in 16.4) where getDerivedStateFromProps
// isn't called after a state change, and we track `searchValue` in state
// instead we need to react to a change in searchValue here
this.updateMatchingOptionsIfDifferent(
getMatchingOptions(
options,
selectedOptions,
searchValue,
this.props.async,
Boolean(singleSelection)
)
);
}
componentWillUnmount() {
this._isMounted = false;
}
render() {
const {
'data-test-subj': dataTestSubj,
async,
className,
compressed,
fullWidth,
id,
inputRef,
isClearable,
isDisabled,
isInvalid,
isLoading,
noSuggestions,
onBlur,
onChange,
onCreateOption,
onSearchChange,
options,
placeholder,
renderOption,
rowHeight,
selectedOptions,
singleSelection,
prepend,
sortMatchesBy,
delimiter,
append,
...rest
} = this.props;
const {
activeOptionIndex,
hasFocus,
isListOpen,
listPosition,
searchValue,
width,
matchingOptions,
} = this.state;
let newMatchingOptions = matchingOptions;
if (sortMatchesBy === 'startsWith') {
const refObj: {
startWith: Array<EuiComboBoxOptionOption<T>>;
others: Array<EuiComboBoxOptionOption<T>>;
} = { startWith: [], others: [] };
newMatchingOptions.forEach(object => {
if (
object.label
.toLowerCase()
.startsWith(searchValue.trim().toLowerCase())
) {
refObj.startWith.push(object);
} else {
refObj.others.push(object);
}
});
newMatchingOptions = [...refObj.startWith, ...refObj.others];
}
// Visually indicate the combobox is in an invalid state if it has lost focus but there is text entered in the input.
// When custom options are disabled and the user leaves the combo box after entering text that does not match any
// options, this tells the user that they've entered invalid input.
const markAsInvalid =
isInvalid ||
((hasFocus === false || isListOpen === false) && searchValue);
const classes = classNames('euiComboBox', className, {
'euiComboBox--compressed': compressed,
'euiComboBox--fullWidth': fullWidth,
'euiComboBox-isDisabled': isDisabled,
'euiComboBox-isInvalid': markAsInvalid,
'euiComboBox-isOpen': isListOpen,
});
const value = selectedOptions
.map(selectedOption => selectedOption.label)
.join(', ');
let optionsList;
if (!noSuggestions && isListOpen) {
const optionsListDataTestSubj = dataTestSubj
? `${dataTestSubj}-optionsList`
: undefined;
optionsList = (
<EuiPortal>
<EuiComboBoxOptionsList
zIndex={this.state.listZIndex}
activeOptionIndex={this.state.activeOptionIndex}
areAllOptionsSelected={this.areAllOptionsSelected()}
data-test-subj={optionsListDataTestSubj}
fullWidth={fullWidth}
isLoading={isLoading}
listRef={this.listRefCallback}
matchingOptions={newMatchingOptions}
onCloseList={this.closeList}
onCreateOption={onCreateOption}
onOptionClick={this.onOptionClick}
onOptionEnterKey={this.onOptionEnterKey}
onScroll={this.onOptionListScroll}
optionRef={this.optionRefCallback}
options={options}
position={listPosition}
singleSelection={singleSelection}