-
Notifications
You must be signed in to change notification settings - Fork 353
/
Copy pathSelect.tsx
1463 lines (1397 loc) · 57.1 KB
/
Select.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
import * as React from 'react';
import styles from '@patternfly/react-styles/css/components/Select/select';
import badgeStyles from '@patternfly/react-styles/css/components/Badge/badge';
import formStyles from '@patternfly/react-styles/css/components/FormControl/form-control';
import buttonStyles from '@patternfly/react-styles/css/components/Button/button';
import { css } from '@patternfly/react-styles';
import TimesCircleIcon from '@patternfly/react-icons/dist/esm/icons/times-circle-icon';
import CheckCircleIcon from '@patternfly/react-icons/dist/esm/icons/check-circle-icon';
import ExclamationTriangleIcon from '@patternfly/react-icons/dist/esm/icons/exclamation-triangle-icon';
import ExclamationCircleIcon from '@patternfly/react-icons/dist/esm/icons/exclamation-circle-icon';
import { SelectMenu } from './SelectMenu';
import { SelectOption, SelectOptionObject } from './SelectOption';
import { SelectGroup, SelectGroupProps } from './SelectGroup';
import { SelectToggle } from './SelectToggle';
import {
SelectContext,
SelectVariant,
SelectPosition,
SelectDirection,
SelectFooterTabbableItems
} from './selectConstants';
import { ChipGroup, ChipGroupProps } from '../ChipGroup';
import { Chip } from '../Chip';
import { Spinner } from '../Spinner';
import {
keyHandler,
getNextIndex,
getOUIAProps,
OUIAProps,
getDefaultOUIAId,
PickOptional,
GenerateId
} from '../../helpers';
import { KeyTypes } from '../../helpers/constants';
import { Divider } from '../Divider';
import { ToggleMenuBaseProps, Popper } from '../../helpers/Popper/Popper';
import { createRenderableFavorites, extendItemsWithFavorite } from '../../helpers/favorites';
import { ValidatedOptions } from '../../helpers/constants';
import { findTabbableElements } from '../../helpers/util';
// seed for the aria-labelledby ID
let currentId = 0;
export interface SelectViewMoreObject {
/** View more text */
text: string;
/** Callback for when the view more button is clicked */
onClick: (event: React.MouseEvent | React.ChangeEvent) => void;
}
export interface SelectProps
extends Omit<ToggleMenuBaseProps, 'menuAppendTo'>,
Omit<React.HTMLProps<HTMLDivElement>, 'onSelect' | 'ref' | 'checked' | 'selected'>,
OUIAProps {
/** Content rendered inside the Select. Must be React.ReactElement<SelectGroupProps>[] */
children?: React.ReactElement[];
/** Classes applied to the root of the Select */
className?: string;
/** Indicates where menu will be aligned horizontally */
position?: SelectPosition | 'right' | 'left';
/** Flag specifying which direction the Select menu expands */
direction?: 'up' | 'down';
/** Flag to indicate if select is open */
isOpen?: boolean;
/** Flag to indicate if select options are grouped */
isGrouped?: boolean;
/** Display the toggle with no border or background */
isPlain?: boolean;
/** Flag to indicate if select is disabled */
isDisabled?: boolean;
/** Flag to indicate if the typeahead select allows new items */
isCreatable?: boolean;
/** Flag indicating if placeholder styles should be applied */
hasPlaceholderStyle?: boolean;
/** @beta Flag indicating if the creatable option should set its value as a SelectOptionObject */
isCreateSelectOptionObject?: boolean;
/** Value to indicate if the select is modified to show that validation state.
* If set to success, select will be modified to indicate valid state.
* If set to error, select will be modified to indicate error state.
* If set to warning, select will be modified to indicate warning state.
*/
validated?: 'success' | 'warning' | 'error' | 'default';
/** @beta Loading variant to display either the spinner or the view more text button */
loadingVariant?: 'spinner' | SelectViewMoreObject;
/** Text displayed in typeahead select to prompt the user to create an item */
createText?: string;
/** Title text of Select */
placeholderText?: string | React.ReactNode;
/** Text to display in typeahead select when no results are found */
noResultsFoundText?: string;
/** Array of selected items for multi select variants. */
selections?: string | SelectOptionObject | (string | SelectOptionObject)[];
/** Flag indicating if selection badge should be hidden for checkbox variant,default false */
isCheckboxSelectionBadgeHidden?: boolean;
/** Id for select toggle element */
toggleId?: string;
/** Adds accessible text to Select */
'aria-label'?: string;
/** Id of label for the Select aria-labelledby */
'aria-labelledby'?: string;
/** Id of div for the select aria-labelledby */
'aria-describedby'?: string;
/** Flag indicating if the select is an invalid state */
'aria-invalid'?: boolean;
/** Label for input field of type ahead select variants */
typeAheadAriaLabel?: string;
/** Id of div for input field of type ahead select variants */
typeAheadAriaDescribedby?: string;
/** Label for clear selection button of type ahead select variants */
clearSelectionsAriaLabel?: string;
/** Label for toggle of type ahead select variants */
toggleAriaLabel?: string;
/** Label for remove chip button of multiple type ahead select variant */
removeSelectionAriaLabel?: string;
/** ID list of favorited select items */
favorites?: string[];
/** Label for the favorites group */
favoritesLabel?: string;
/** Enables favorites. Callback called when a select options's favorite button is clicked */
onFavorite?: (itemId: string, isFavorite: boolean) => void;
/** Callback for selection behavior */
onSelect?: (
event: React.MouseEvent | React.ChangeEvent,
value: string | SelectOptionObject,
isPlaceholder?: boolean
) => void;
/** Callback for toggle button behavior */
onToggle: (isExpanded: boolean, event: React.MouseEvent | React.ChangeEvent | React.KeyboardEvent | Event) => void;
/** Callback for toggle blur */
onBlur?: (event?: any) => void;
/** Callback for typeahead clear button */
onClear?: (event: React.MouseEvent) => void;
/** Optional callback for custom filtering */
onFilter?: (e: React.ChangeEvent<HTMLInputElement> | null, value: string) => React.ReactElement[] | undefined;
/** Optional callback for newly created options */
onCreateOption?: (newOptionValue: string) => void;
/** Optional event handler called each time the value in the typeahead input changes. */
onTypeaheadInputChanged?: (value: string) => void;
/** Variant of rendered Select */
variant?: 'single' | 'checkbox' | 'typeahead' | 'typeaheadmulti';
/** Width of the select container as a number of px or string percentage */
width?: string | number;
/** Max height of the select container as a number of px or string percentage */
maxHeight?: string | number;
/** Icon element to render inside the select toggle */
toggleIcon?: React.ReactElement;
/** Custom content to render in the select menu. If this prop is defined, the variant prop will be ignored and the select will render with a single select toggle */
customContent?: React.ReactNode;
/** Flag indicating if select should have an inline text input for filtering */
hasInlineFilter?: boolean;
/** Placeholder text for inline filter */
inlineFilterPlaceholderText?: string;
/** Custom text for select badge */
customBadgeText?: string | number;
/** Prefix for the id of the input in the checkbox select variant*/
inputIdPrefix?: string;
/** Value for the typeahead and inline filtering input autocomplete attribute. When targeting Chrome this property should be a random string. */
inputAutoComplete?: string;
/** Optional props to pass to the chip group in the typeaheadmulti variant */
chipGroupProps?: Omit<ChipGroupProps, 'children' | 'ref'>;
/** Optional props to render custom chip group in the typeaheadmulti variant */
chipGroupComponent?: React.ReactNode;
/** Flag for retaining keyboard-entered value in typeahead text field when focus leaves input away */
isInputValuePersisted?: boolean;
/** @beta Flag for retaining filter results on blur from keyboard-entered typeahead text */
isInputFilterPersisted?: boolean;
/** Flag indicating the typeahead input value should reset upon selection */
shouldResetOnSelect?: boolean;
/** Content rendered in the footer of the select menu */
footer?: React.ReactNode;
/** The container to append the menu to. Defaults to 'inline'.
* If your menu is being cut off you can append it to an element higher up the DOM tree.
* Some examples:
* menuAppendTo="parent"
* menuAppendTo={() => document.body}
* menuAppendTo={document.getElementById('target')}
*/
menuAppendTo?: HTMLElement | (() => HTMLElement) | 'inline' | 'parent';
/** Flag for indicating that the select menu should automatically flip vertically when
* it reaches the boundary. This prop can only be used when the select component is not
* appended inline, e.g. `menuAppendTo="parent"`
*/
isFlipEnabled?: boolean;
/** @beta Opt-in for updated popper that does not use findDOMNode. */
removeFindDomNode?: boolean;
}
export interface SelectState {
focusFirstOption: boolean;
typeaheadInputValue: string | null;
typeaheadFilteredChildren: React.ReactNode[];
favoritesGroup: React.ReactNode[];
typeaheadCurrIndex: number;
creatableValue: string;
tabbedIntoFavoritesMenu: boolean;
typeaheadStoredIndex: number;
ouiaStateId: string;
viewMoreNextIndex: number;
}
export class Select extends React.Component<SelectProps & OUIAProps, SelectState> {
static displayName = 'Select';
private parentRef = React.createRef<HTMLDivElement>();
private menuComponentRef = React.createRef<HTMLElement>();
private filterRef = React.createRef<HTMLInputElement>();
private clearRef = React.createRef<HTMLButtonElement>();
private inputRef = React.createRef<HTMLInputElement>();
private refCollection: HTMLElement[][] = [[]];
private optionContainerRefCollection: HTMLElement[] = [];
private footerRef = React.createRef<HTMLDivElement>();
static defaultProps: PickOptional<SelectProps> = {
children: [] as React.ReactElement[],
className: '',
position: SelectPosition.left,
direction: SelectDirection.down,
toggleId: null as string,
isOpen: false,
isGrouped: false,
isPlain: false,
isDisabled: false,
hasPlaceholderStyle: false,
isCreatable: false,
validated: 'default',
'aria-label': '',
'aria-labelledby': '',
'aria-describedby': '',
'aria-invalid': false,
typeAheadAriaLabel: '',
typeAheadAriaDescribedby: '',
clearSelectionsAriaLabel: 'Clear all',
toggleAriaLabel: 'Options menu',
removeSelectionAriaLabel: 'Remove',
selections: [],
createText: 'Create',
placeholderText: '',
noResultsFoundText: 'No results found',
variant: SelectVariant.single,
width: '',
onClear: () => undefined as void,
onCreateOption: () => undefined as void,
toggleIcon: null as React.ReactElement,
onFilter: null,
onTypeaheadInputChanged: null,
customContent: null,
hasInlineFilter: false,
inlineFilterPlaceholderText: null,
customBadgeText: null,
inputIdPrefix: '',
inputAutoComplete: 'off',
menuAppendTo: 'inline',
favorites: [] as string[],
favoritesLabel: 'Favorites',
ouiaSafe: true,
chipGroupComponent: null,
isInputValuePersisted: false,
isInputFilterPersisted: false,
isCreateSelectOptionObject: false,
shouldResetOnSelect: true,
isFlipEnabled: false,
removeFindDomNode: false
};
state: SelectState = {
focusFirstOption: false,
typeaheadInputValue: null,
typeaheadFilteredChildren: React.Children.toArray(this.props.children),
favoritesGroup: [] as React.ReactNode[],
typeaheadCurrIndex: -1,
typeaheadStoredIndex: -1,
creatableValue: '',
tabbedIntoFavoritesMenu: false,
ouiaStateId: getDefaultOUIAId(Select.displayName, this.props.variant),
viewMoreNextIndex: -1
};
getTypeaheadActiveChild = (typeaheadCurrIndex: number) =>
this.refCollection[typeaheadCurrIndex] ? this.refCollection[typeaheadCurrIndex][0] : null;
componentDidUpdate = (prevProps: SelectProps, prevState: SelectState) => {
if (this.props.hasInlineFilter) {
this.refCollection[0][0] = this.filterRef.current;
}
// Move focus to top of the menu if state.focusFirstOption was updated to true and the menu does not have custom content
if (!prevState.focusFirstOption && this.state.focusFirstOption && !this.props.customContent) {
const firstRef = this.refCollection.find(ref => ref !== null);
if (firstRef && firstRef[0]) {
firstRef[0].focus();
}
} else if (
// if viewMoreNextIndex is not -1, view more was clicked, set focus on first newly loaded item
this.state.viewMoreNextIndex !== -1 &&
this.refCollection.length > this.state.viewMoreNextIndex &&
this.props.loadingVariant !== 'spinner' &&
this.refCollection[this.state.viewMoreNextIndex][0] &&
this.props.variant !== 'typeahead' && // do not hard focus newly added items for typeahead variants
this.props.variant !== 'typeaheadmulti'
) {
this.refCollection[this.state.viewMoreNextIndex][0].focus();
this.setState({ viewMoreNextIndex: -1 });
}
const checkUpdatedChildren = (prevChildren: React.ReactElement[], currChildren: React.ReactElement[]) =>
Array.from(prevChildren).some((prevChild: React.ReactElement, index: number) => {
const prevChildProps = prevChild.props;
const currChild = currChildren[index];
const { props: currChildProps } = currChild;
if (prevChildProps && currChildProps) {
return (
prevChildProps.value !== currChildProps.value ||
prevChildProps.label !== currChildProps.label ||
prevChildProps.isDisabled !== currChildProps.isDisabled ||
prevChildProps.isPlaceholder !== currChildProps.isPlaceholder
);
} else {
return prevChild !== currChild;
}
});
const hasUpdatedChildren =
prevProps.children.length !== this.props.children.length ||
checkUpdatedChildren(prevProps.children, this.props.children) ||
(this.props.isGrouped &&
Array.from(prevProps.children).some(
(prevChild: React.ReactElement, index: number) =>
prevChild.type === SelectGroup &&
prevChild.props.children &&
this.props.children[index].props.children &&
(prevChild.props.children.length !== this.props.children[index].props.children.length ||
checkUpdatedChildren(prevChild.props.children, this.props.children[index].props.children))
));
if (hasUpdatedChildren) {
this.updateTypeAheadFilteredChildren(prevState.typeaheadInputValue || '', null);
}
// for menus with favorites,
// if the number of favorites or typeahead filtered children has changed, the generated
// list of favorites needs to be updated
if (
this.props.onFavorite &&
(this.props.favorites.length !== prevProps.favorites.length ||
this.state.typeaheadFilteredChildren !== prevState.typeaheadFilteredChildren)
) {
const tempRenderableChildren =
this.props.variant === 'typeahead' || this.props.variant === 'typeaheadmulti'
? this.state.typeaheadFilteredChildren
: this.props.children;
const renderableFavorites = createRenderableFavorites(
tempRenderableChildren,
this.props.isGrouped,
this.props.favorites
);
const favoritesGroup = renderableFavorites.length
? [
<SelectGroup key="favorites" label={this.props.favoritesLabel}>
{renderableFavorites}
</SelectGroup>,
<Divider key="favorites-group-divider" />
]
: [];
this.setState({ favoritesGroup });
}
};
onEnter = () => {
this.setState({ focusFirstOption: true });
};
onToggle = (isExpanded: boolean, e: React.MouseEvent | React.ChangeEvent | React.KeyboardEvent | Event) => {
const { isInputValuePersisted, onSelect, onToggle, hasInlineFilter } = this.props;
if (!isExpanded && isInputValuePersisted && onSelect) {
onSelect(undefined, this.inputRef.current ? this.inputRef.current.value : '');
}
if (isExpanded && hasInlineFilter) {
this.setState({
focusFirstOption: true
});
}
onToggle(isExpanded, e);
};
onClose = () => {
const { isInputFilterPersisted } = this.props;
this.setState({
focusFirstOption: false,
typeaheadInputValue: null,
...(!isInputFilterPersisted && {
typeaheadFilteredChildren: React.Children.toArray(this.props.children)
}),
typeaheadCurrIndex: -1,
tabbedIntoFavoritesMenu: false,
viewMoreNextIndex: -1
});
};
onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
if (e.target.value.toString() !== '' && !this.props.isOpen) {
this.onToggle(true, e);
}
if (this.props.onTypeaheadInputChanged) {
this.props.onTypeaheadInputChanged(e.target.value.toString());
}
this.setState({
typeaheadCurrIndex: -1,
typeaheadInputValue: e.target.value,
creatableValue: e.target.value
});
this.updateTypeAheadFilteredChildren(e.target.value.toString(), e);
this.refCollection = [[]];
};
updateTypeAheadFilteredChildren = (typeaheadInputValue: string, e: React.ChangeEvent<HTMLInputElement> | null) => {
let typeaheadFilteredChildren: any;
const {
onFilter,
isCreatable,
onCreateOption,
createText,
noResultsFoundText,
children,
isGrouped,
isCreateSelectOptionObject,
loadingVariant
} = this.props;
if (onFilter) {
/* The updateTypeAheadFilteredChildren callback is not only called on input changes but also when the children change.
* In this case the e is null but we can get the typeaheadInputValue from the state.
*/
typeaheadFilteredChildren = onFilter(e, e ? e.target.value : typeaheadInputValue) || children;
} else {
let input: RegExp;
try {
input = new RegExp(typeaheadInputValue.toString(), 'i');
} catch (err) {
input = new RegExp(typeaheadInputValue.toString().replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'i');
}
const childrenArray = React.Children.toArray(children) as React.ReactElement<SelectGroupProps>[];
if (isGrouped) {
const childFilter = (child: React.ReactElement<SelectGroupProps>) =>
child.props.value &&
child.props.value.toString &&
this.getDisplay(child.props.value.toString(), 'text').search(input) === 0;
typeaheadFilteredChildren =
typeaheadInputValue.toString() !== ''
? React.Children.map(children, group => {
if (
React.isValidElement<React.ComponentProps<typeof SelectGroup>>(group) &&
group.type === SelectGroup
) {
const filteredGroupChildren = (React.Children.toArray(group.props.children) as React.ReactElement<
SelectGroupProps
>[]).filter(childFilter);
if (filteredGroupChildren.length > 0) {
return React.cloneElement(group, {
titleId: group.props.label && group.props.label.replace(/\W/g, '-'),
children: filteredGroupChildren as any
});
}
} else {
return (React.Children.toArray(group) as React.ReactElement<SelectGroupProps>[]).filter(childFilter);
}
})
: childrenArray;
} else {
typeaheadFilteredChildren =
typeaheadInputValue.toString() !== ''
? childrenArray.filter(child => {
const valueToCheck = child.props.value;
// Dividers don't have value and should not be filtered
if (!valueToCheck) {
return true;
}
const isSelectOptionObject =
typeof valueToCheck !== 'string' &&
(valueToCheck as SelectOptionObject).toString &&
(valueToCheck as SelectOptionObject).compareTo;
// View more option should be returned as not a match
if (loadingVariant !== 'spinner' && loadingVariant?.text === valueToCheck) {
return true;
}
// spinner should be returned as not a match
if (loadingVariant === 'spinner' && valueToCheck === 'loading') {
return true;
}
if (isSelectOptionObject) {
return (valueToCheck as SelectOptionObject).compareTo(typeaheadInputValue);
} else {
return this.getDisplay(child.props.value.toString(), 'text').search(input) === 0;
}
})
: childrenArray;
}
}
if (!typeaheadFilteredChildren) {
typeaheadFilteredChildren = [];
}
if (typeaheadFilteredChildren.length === 0) {
!isCreatable &&
typeaheadFilteredChildren.push(
<SelectOption isDisabled key="no-results" value={noResultsFoundText} isNoResultsOption />
);
}
if (isCreatable && typeaheadInputValue !== '') {
const newValue = typeaheadInputValue;
if (
!typeaheadFilteredChildren.find(
(i: React.ReactElement) =>
i.props.value && i.props.value.toString().toLowerCase() === newValue.toString().toLowerCase()
)
) {
const newOptionValue = isCreateSelectOptionObject
? ({
toString: () => newValue,
compareTo: value =>
this.toString()
.toLowerCase()
.includes(value.toString().toLowerCase())
} as SelectOptionObject)
: newValue;
typeaheadFilteredChildren.push(
<SelectOption
key={`create ${newValue}`}
value={newOptionValue}
onClick={() => onCreateOption && onCreateOption(newValue)}
>
{createText} "{newValue}"
</SelectOption>
);
}
}
this.setState({
typeaheadFilteredChildren
});
};
onClick = (e: React.MouseEvent) => {
if (!this.props.isOpen) {
this.onToggle(true, e);
}
};
clearSelection = (_e: React.MouseEvent) => {
this.setState({
typeaheadInputValue: null,
typeaheadFilteredChildren: React.Children.toArray(this.props.children),
typeaheadCurrIndex: -1
});
};
extendTypeaheadChildren(typeaheadCurrIndex: number, favoritesGroup?: React.ReactNode[]) {
const { isGrouped, onFavorite, createText } = this.props;
const typeaheadChildren = favoritesGroup
? favoritesGroup.concat(this.state.typeaheadFilteredChildren)
: this.state.typeaheadFilteredChildren;
const activeElement = this.optionContainerRefCollection[typeaheadCurrIndex];
let typeaheadActiveChild = this.getTypeaheadActiveChild(typeaheadCurrIndex);
if (typeaheadActiveChild && typeaheadActiveChild.classList.contains('pf-m-description')) {
typeaheadActiveChild = typeaheadActiveChild.firstElementChild as HTMLElement;
}
this.refCollection = [[]];
this.optionContainerRefCollection = [];
if (isGrouped) {
return React.Children.map(typeaheadChildren as React.ReactElement[], (group: React.ReactElement) => {
if (group.type === Divider) {
return group;
} else if (group.type === SelectGroup && onFavorite) {
return React.cloneElement(group, {
titleId: group.props.label && group.props.label.replace(/\W/g, '-'),
children: React.Children.map(group.props.children, (child: React.ReactElement) =>
child.type === Divider
? child
: React.cloneElement(child as React.ReactElement, {
isFocused:
activeElement &&
(activeElement.id === (child as React.ReactElement).props.id ||
(this.props.isCreatable &&
typeaheadActiveChild.textContent ===
`${createText} "${(group as React.ReactElement).props.value}"`))
})
)
});
} else if (group.type === SelectGroup) {
return React.cloneElement(group, {
titleId: group.props.label && group.props.label.replace(/\W/g, '-'),
children: React.Children.map(group.props.children, (child: React.ReactElement) =>
child.type === Divider
? child
: React.cloneElement(child as React.ReactElement, {
isFocused:
typeaheadActiveChild &&
(typeaheadActiveChild.textContent === (child as React.ReactElement).props.value.toString() ||
(this.props.isCreatable &&
typeaheadActiveChild.textContent ===
`${createText} "${(child as React.ReactElement).props.value}"`))
})
)
});
} else {
// group has been filtered down to SelectOption
return React.cloneElement(group as React.ReactElement, {
isFocused:
typeaheadActiveChild &&
(typeaheadActiveChild.textContent === group.props.value.toString() ||
(this.props.isCreatable && typeaheadActiveChild.textContent === `${createText} "${group.props.value}"`))
});
}
});
}
return typeaheadChildren.map((child: React.ReactNode, index) => {
const childElement = child as any;
return childElement.type.displayName === 'Divider'
? child
: React.cloneElement(child as React.ReactElement, {
isFocused: typeaheadActiveChild
? typeaheadActiveChild.textContent === (child as React.ReactElement).props.value.toString() ||
(this.props.isCreatable &&
typeaheadActiveChild.textContent === `${createText} "${(child as React.ReactElement).props.value}"`)
: index === typeaheadCurrIndex // fallback for view more + typeahead use cases, when the new expanded list is loaded and refCollection hasn't be updated yet
});
});
}
sendRef = (
optionRef: React.ReactNode,
favoriteRef: React.ReactNode,
optionContainerRef: React.ReactNode,
index: number
) => {
this.refCollection[index] = [(optionRef as unknown) as HTMLElement, (favoriteRef as unknown) as HTMLElement];
this.optionContainerRefCollection[index] = (optionContainerRef as unknown) as HTMLElement;
};
handleMenuKeys = (index: number, innerIndex: number, position: string) => {
keyHandler(index, innerIndex, position, this.refCollection, this.refCollection);
if (this.props.variant === SelectVariant.typeahead || this.props.variant === SelectVariant.typeaheadMulti) {
if (position !== 'tab') {
this.handleTypeaheadKeys(position);
}
}
};
moveFocus = (nextIndex: number, updateCurrentIndex: boolean = true) => {
const { isCreatable, createText } = this.props;
const hasDescriptionElm = Boolean(
this.refCollection[nextIndex][0] && this.refCollection[nextIndex][0].classList.contains('pf-m-description')
);
const isLoad = Boolean(
this.refCollection[nextIndex][0] && this.refCollection[nextIndex][0].classList.contains('pf-m-load')
);
const optionTextElm = hasDescriptionElm
? (this.refCollection[nextIndex][0].firstElementChild as HTMLElement)
: this.refCollection[nextIndex][0];
let typeaheadInputValue = '';
if (isCreatable && optionTextElm.textContent.includes(createText)) {
typeaheadInputValue = this.state.creatableValue;
} else if (optionTextElm && !isLoad) {
// !isLoad prevents the view more button text from appearing the typeahead input
typeaheadInputValue = optionTextElm.textContent;
}
this.setState(prevState => ({
typeaheadCurrIndex: updateCurrentIndex ? nextIndex : prevState.typeaheadCurrIndex,
typeaheadStoredIndex: nextIndex,
typeaheadInputValue
}));
};
switchFocusToFavoriteMenu = () => {
const { typeaheadCurrIndex, typeaheadStoredIndex } = this.state;
let indexForFocus = 0;
if (typeaheadCurrIndex !== -1) {
indexForFocus = typeaheadCurrIndex;
} else if (typeaheadStoredIndex !== -1) {
indexForFocus = typeaheadStoredIndex;
}
if (this.refCollection[indexForFocus] !== null && this.refCollection[indexForFocus][0] !== null) {
this.refCollection[indexForFocus][0].focus();
} else {
this.clearRef.current.focus();
}
this.setState({
tabbedIntoFavoritesMenu: true,
typeaheadCurrIndex: -1
});
};
moveFocusToLastMenuItem = () => {
const refCollectionLen = this.refCollection.length;
if (
refCollectionLen > 0 &&
this.refCollection[refCollectionLen - 1] !== null &&
this.refCollection[refCollectionLen - 1][0] !== null
) {
this.refCollection[refCollectionLen - 1][0].focus();
}
};
handleTypeaheadKeys = (position: string, shiftKey: boolean = false) => {
const { isOpen, onFavorite, isCreatable } = this.props;
const { typeaheadCurrIndex, tabbedIntoFavoritesMenu } = this.state;
const typeaheadActiveChild = this.getTypeaheadActiveChild(typeaheadCurrIndex);
if (isOpen) {
if (position === 'enter') {
if (
(typeaheadCurrIndex !== -1 || (isCreatable && this.refCollection.length === 1)) && // do not allow selection without moving to an initial option unless it is a single create option
(typeaheadActiveChild || (this.refCollection[0] && this.refCollection[0][0]))
) {
if (typeaheadActiveChild) {
if (!typeaheadActiveChild.classList.contains('pf-m-load')) {
const hasDescriptionElm = typeaheadActiveChild.childElementCount > 1;
const typeaheadActiveChildText = hasDescriptionElm
? (typeaheadActiveChild.firstChild as HTMLElement).textContent
: typeaheadActiveChild.textContent;
this.setState({
typeaheadInputValue: typeaheadActiveChildText
});
}
} else if (this.refCollection[0] && this.refCollection[0][0]) {
this.setState({
typeaheadInputValue: this.refCollection[0][0].textContent
});
}
if (typeaheadActiveChild) {
typeaheadActiveChild.click();
} else {
this.refCollection[0][0].click();
}
}
} else if (position === 'tab') {
if (onFavorite) {
// if the input has focus, tab to the first item or the last item that was previously focused.
if (this.inputRef.current === document.activeElement) {
// If shift is also clicked and there is a footer, tab to the last item in tabbable footer
if (this.props.footer && shiftKey) {
const tabbableItems = findTabbableElements(this.footerRef, SelectFooterTabbableItems);
if (tabbableItems.length > 0) {
if (tabbableItems[tabbableItems.length - 1]) {
tabbableItems[tabbableItems.length - 1].focus();
}
}
} else {
this.switchFocusToFavoriteMenu();
}
} else {
// focus is on menu or footer
if (this.props.footer) {
let tabbedIntoMenu = false;
const tabbableItems = findTabbableElements(this.footerRef, SelectFooterTabbableItems);
if (tabbableItems.length > 0) {
// if current element is not in footer, tab to first tabbable element in footer,
// if shift was clicked, tab to input since focus is on menu
const currentElementIndex = tabbableItems.findIndex((item: any) => item === document.activeElement);
if (currentElementIndex === -1) {
if (shiftKey) {
// currently in menu, shift back to input
this.inputRef.current.focus();
} else {
// currently in menu, tab to first tabbable item in footer
tabbableItems[0].focus();
}
} else {
// already in footer
if (shiftKey) {
// shift to previous item
if (currentElementIndex === 0) {
// on first footer item, shift back to menu
this.switchFocusToFavoriteMenu();
tabbedIntoMenu = true;
} else {
// shift to previous footer item
tabbableItems[currentElementIndex - 1].focus();
}
} else {
// tab to next tabbable item in footer or to input.
if (tabbableItems[currentElementIndex + 1]) {
tabbableItems[currentElementIndex + 1].focus();
} else {
this.inputRef.current.focus();
}
}
}
} else {
// no tabbable items in footer, tab to input
this.inputRef.current.focus();
tabbedIntoMenu = false;
}
this.setState({ tabbedIntoFavoritesMenu: tabbedIntoMenu });
} else {
this.inputRef.current.focus();
this.setState({ tabbedIntoFavoritesMenu: false });
}
}
} else {
// Close if there is no footer
if (!this.props.footer) {
this.onToggle(false, null);
this.onClose();
} else {
// has footer
const tabbableItems = findTabbableElements(this.footerRef, SelectFooterTabbableItems);
const currentElementIndex = tabbableItems.findIndex((item: any) => item === document.activeElement);
if (this.inputRef.current === document.activeElement) {
if (shiftKey) {
// close toggle if shift key and tab on input
this.onToggle(false, null);
this.onClose();
} else {
// tab to first tabbable item in footer
if (tabbableItems[0]) {
tabbableItems[0].focus();
} else {
this.onToggle(false, null);
this.onClose();
}
}
} else {
// focus is in footer
if (shiftKey) {
if (currentElementIndex === 0) {
// shift tab back to input
this.inputRef.current.focus();
} else {
// shift to previous footer item
tabbableItems[currentElementIndex - 1].focus();
}
} else {
// tab to next footer item or close tab if last item
if (tabbableItems[currentElementIndex + 1]) {
tabbableItems[currentElementIndex + 1].focus();
} else {
// no next item, close toggle
this.onToggle(false, null);
this.inputRef.current.focus();
this.onClose();
}
}
}
}
}
} else if (!tabbedIntoFavoritesMenu) {
if (this.refCollection[0][0] === null) {
return;
}
let nextIndex;
if (typeaheadCurrIndex === -1 && position === 'down') {
nextIndex = 0;
} else if (typeaheadCurrIndex === -1 && position === 'up') {
nextIndex = this.refCollection.length - 1;
} else if (position !== 'left' && position !== 'right') {
nextIndex = getNextIndex(typeaheadCurrIndex, position, this.refCollection);
} else {
nextIndex = typeaheadCurrIndex;
}
if (this.refCollection[nextIndex] === null) {
return;
}
this.moveFocus(nextIndex);
} else {
const nextIndex = this.refCollection.findIndex(
ref => ref !== undefined && (ref[0] === document.activeElement || ref[1] === document.activeElement)
);
this.moveFocus(nextIndex);
}
}
};
onClickTypeaheadToggleButton = () => {
if (this.inputRef && this.inputRef.current) {
this.inputRef.current.focus();
}
};
getDisplay = (value: string | SelectOptionObject, type: 'node' | 'text' = 'node') => {
if (!value) {
return;
}
const item = this.props.isGrouped
? (React.Children.toArray(this.props.children) as React.ReactElement[])
.reduce((acc, curr) => [...acc, ...React.Children.toArray(curr.props.children)], [])
.find(child => child.props.value.toString() === value.toString())
: React.Children.toArray(this.props.children).find(
child =>
(child as React.ReactElement).props.value &&
(child as React.ReactElement).props.value.toString() === value.toString()
);
if (item) {
if (item && item.props.children) {
if (type === 'node') {
return item.props.children;
}
return this.findText(item);
}
return item.props.value.toString();
}
return value.toString();
};
findText = (item: React.ReactNode) => {
if (typeof item === 'string') {
return item;
} else if (!React.isValidElement(item)) {
return '';
} else {
const multi: string[] = [];
React.Children.toArray(item.props.children).forEach(child => multi.push(this.findText(child)));
return multi.join('');
}
};
generateSelectedBadge = () => {
const { customBadgeText, selections } = this.props;
if (customBadgeText !== null) {
return customBadgeText;
}
if (Array.isArray(selections) && selections.length > 0) {
return selections.length;
}
return null;
};
setVieMoreNextIndex = () => {
this.setState({ viewMoreNextIndex: this.refCollection.length - 1 });
};
isLastOptionBeforeFooter = (index: any) =>
this.props.footer && index === this.refCollection.length - 1 ? true : false;
render() {
const {
children,
chipGroupProps,
chipGroupComponent,
className,
customContent,
variant,
direction,
onSelect,
onClear,
onBlur,
toggleId,
isOpen,
isGrouped,
isPlain,
isDisabled,
hasPlaceholderStyle,
validated,
selections: selectionsProp,
typeAheadAriaLabel,
typeAheadAriaDescribedby,
clearSelectionsAriaLabel,
toggleAriaLabel,
removeSelectionAriaLabel,
'aria-label': ariaLabel,
'aria-labelledby': ariaLabelledBy,
'aria-describedby': ariaDescribedby,
'aria-invalid': ariaInvalid,
placeholderText,
width,
maxHeight,
toggleIcon,
ouiaId,
ouiaSafe,
hasInlineFilter,
isCheckboxSelectionBadgeHidden,
inlineFilterPlaceholderText,
/* eslint-disable @typescript-eslint/no-unused-vars */
onFilter,
/* eslint-disable @typescript-eslint/no-unused-vars */
onTypeaheadInputChanged,
onCreateOption,
isCreatable,
onToggle,
createText,
noResultsFoundText,
customBadgeText,
inputIdPrefix,
inputAutoComplete,
/* eslint-disable @typescript-eslint/no-unused-vars */
isInputValuePersisted,
isInputFilterPersisted,
/* eslint-enable @typescript-eslint/no-unused-vars */