-
Notifications
You must be signed in to change notification settings - Fork 187
/
select.tsx
1506 lines (1324 loc) · 43.7 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 React, {
ButtonHTMLAttributes,
Component,
ComponentType,
CSSProperties,
Fragment,
HTMLAttributes,
ReactNode, RefCallback,
SyntheticEvent
} from 'react';
import classNames from 'classnames';
import PropTypes from 'prop-types';
import chevronDownIcon from '@jetbrains/icons/chevron-down';
import closeIcon from '@jetbrains/icons/close-12px';
import deepEqual from 'deep-equal';
import {Anchor} from '../dropdown/dropdown';
import Avatar, {Size as AvatarSize} from '../avatar/avatar';
import Popup from '../popup/popup';
import List, {ActiveItemContext, SelectHandlerParams} from '../list/list';
import Input, {Size} from '../input/input';
import InputLabel from '../input/input-label';
import Shortcuts from '../shortcuts/shortcuts';
import Button from '../button/button';
import dataTests from '../global/data-tests';
import getUID from '../global/get-uid';
import rerenderHOC from '../global/rerender-hoc';
import fuzzyHighlight from '../global/fuzzy-highlight';
import memoize from '../global/memoize';
import {I18nContext} from '../i18n/i18n-context';
import {ListDataItem} from '../list/consts';
import {Directions} from '../popup/popup.consts';
import {isArray} from '../global/typescript-utils';
import {ControlsHeight, ControlsHeightContext} from '../global/controls-height';
import inputStyles from '../input/input.css';
import SelectPopup, {Filter, FilterFn, Multiple, Tags} from './select__popup';
import styles from './select.css';
/**
* @name Select
*/
function noop() {}
/**
* @enum {number}
*/
export enum Type {
BUTTON = 'BUTTON',
INPUT = 'INPUT',
CUSTOM = 'CUSTOM',
INLINE = 'INLINE',
INPUT_WITHOUT_CONTROLS = 'INPUT_WITHOUT_CONTROLS'
}
const ICONS_OFFSET = 5;
const ICON_WIDTH = 20;
const getStyle = memoize((iconsLength: number) => ({
paddingRight: ICONS_OFFSET + iconsLength * ICON_WIDTH
}));
const isInputMode = (type: Type) => type === Type.INPUT || type === Type.INPUT_WITHOUT_CONTROLS;
type SelectItemData<T> = T & {
key: string | number
isResetItem?: boolean | null | undefined
separator?: boolean | null | undefined
}
export type SelectItem<T = unknown> = ListDataItem<SelectItemData<T>>
function getLowerCaseLabel<T>(item: SelectItem<T>) {
if (
List.isItemType(List.ListProps.Type.SEPARATOR, item) ||
List.isItemType(List.ListProps.Type.HINT, item) ||
typeof item.label !== 'string'
) {
return null;
}
return item.label.toLowerCase();
}
function doesLabelMatch<T>(itemToCheck: SelectItem<T>, fn: (label: string) => boolean) {
const lowerCaseLabel = getLowerCaseLabel(itemToCheck);
if (lowerCaseLabel == null) {
return true;
}
return fn(lowerCaseLabel);
}
function getFilterFn<T>(filter: Filter<T> | boolean): FilterFn<T> {
if (typeof filter === 'object') {
if (filter.fn) {
return filter.fn;
}
if (filter.fuzzy) {
return (itemToCheck, checkString) =>
doesLabelMatch(itemToCheck, lowerCaseLabel =>
fuzzyHighlight(checkString, lowerCaseLabel).matched
);
}
}
return (itemToCheck, checkString) =>
doesLabelMatch(itemToCheck, lowerCaseLabel =>
lowerCaseLabel.indexOf(checkString) >= 0
);
}
function buildMultipleMap<T>(selected: SelectItem<T>[]) {
return selected.reduce((acc: Record<string, boolean>, item) => {
acc[item.key] = true;
return acc;
}, {});
}
export interface Add {
alwaysVisible?: boolean | null | undefined
regexp?: RegExp | null | undefined
minlength?: number | null | undefined
label?: ((filterString: string) => string) | string | null | undefined
prefix?: string | null | undefined
delayed?: boolean | null | undefined
}
export interface DataTestProps {
'data-test'?: string | null | undefined
}
export interface CustomAnchorProps {
wrapperProps: HTMLAttributes<HTMLElement> & DataTestProps & {ref: RefCallback<HTMLElement>}
buttonProps: Pick<ButtonHTMLAttributes<HTMLButtonElement>, 'id' | 'disabled' | 'children'> &
{onClick: () => void} &
DataTestProps,
popup: ReactNode
}
export type CustomAnchor = ((props: CustomAnchorProps) => ReactNode);
export interface BaseSelectProps<T = unknown> {
data: readonly SelectItem<T>[]
filter: boolean | Filter<T>
clear: boolean
loading: boolean
disabled: boolean
loadingMessage?: string
notFoundMessage?: string
type: Type
size: Size
hideSelected: boolean
allowAny: boolean
maxHeight: number
hideArrow: boolean
directions: readonly Directions[]
label: string | null
selectedLabel: ReactNode
inputPlaceholder: string
shortcutsEnabled: boolean
onBeforeOpen: () => void
onLoadMore: () => void
onOpen: () => void
onFilter: (value: string) => void
onFocus: (e: React.FocusEvent<HTMLInputElement>) => void
onBlur: () => void
onKeyDown: (event: React.KeyboardEvent<HTMLInputElement>) => void
onSelect: (selected: SelectItem<T> | null, event?: Event | SyntheticEvent) => void
onDeselect: (selected: SelectItem<T> | null) => void
onAdd: (value: string) => void
onDone: () => void
onReset: () => void
dir: 'ltr' | 'rtl'
renderBottomToolbar?: () => ReactNode
height?: ControlsHeight | undefined
targetElement?: HTMLElement | null | undefined
className?: string | null | undefined
buttonClassName?: string | null | undefined
id?: string | undefined
getInitial?: (() => string) | null | undefined
minWidth?: number | undefined
popupClassName?: string | null | undefined
popupStyle?: CSSProperties | undefined
top?: number | undefined
left?: number | undefined
renderOptimization?: boolean | undefined
ringPopupTarget?: string | null | undefined
error?: ReactNode | null | undefined
hint?: ReactNode
add?: Add | null | undefined
compact?: boolean | null | undefined
customAnchor?: CustomAnchor | null | undefined
disableMoveOverflow?: boolean | null | undefined
disableScrollToActive?: boolean | null | undefined
'data-test'?: string | null | undefined
}
export interface SingleSelectProps<T = unknown> extends BaseSelectProps<T> {
multiple: false
onClose: (selected: SelectItem<T> | null) => void
onChange: (selected: SelectItem<T> | null, event?: Event | SyntheticEvent) => void
selected?: SelectItem<T> | null | undefined
tags?: null | undefined
}
export interface MultipleSelectProps<T = unknown> extends BaseSelectProps<T> {
multiple: true | Multiple
selected: readonly SelectItem<T>[]
onClose: (selected: SelectItem<T>[]) => void
onChange: (selected: SelectItem<T>[], event?: Event | SyntheticEvent) => void
tags?: Tags | boolean | null | undefined
}
export type SelectProps<T = unknown> = SingleSelectProps<T> | MultipleSelectProps<T>
interface AddButton {
prefix: string | null | undefined
label: string
delayed: boolean
}
export interface SelectState<T = unknown> {
data: SelectItem<T>[]
shownData: SelectItem<T>[]
selected: SelectItem<T> | SelectItem<T>[] | null | undefined
selectedIndex: number | null
filterValue: string
shortcutsEnabled: boolean
popupShortcuts: boolean
showPopup: boolean
prevData: readonly SelectItem<T>[]
prevSelected: SelectItem<T> | readonly SelectItem<T>[] | null | undefined
prevMultiple: Multiple | boolean | null | undefined
multipleMap: Record<string, boolean>
addButton: AddButton | null
focused?: boolean
}
function getListItems<T = unknown>(
props: SelectProps<T>,
state: Partial<SelectState<T>>,
rawFilterString: string,
data = props.data
) {
let filterString = rawFilterString.trim();
if (isInputMode(props.type) && !props.allowAny && state.selected &&
!Array.isArray(state.selected) && filterString === state.selected.label) {
filterString = ''; // ignore multiple if it is exactly the selected item
}
const lowerCaseString = filterString.toLowerCase();
const filteredData = [];
let exactMatch = false;
const check = getFilterFn(props.filter);
for (let i = 0; i < data.length; i++) {
const item = {...data[i]};
if (check(item, lowerCaseString, data)) {
exactMatch = (item.label === filterString);
if (props.multiple &&
!(typeof props.multiple === 'object' && props.multiple.removeSelectedItems)) {
item.checkbox = !!state.multipleMap?.[item.key];
}
if (
props.multiple &&
typeof props.multiple === 'object' &&
props.multiple.limit &&
Array.isArray(state.selected)
) {
item.disabled = props.multiple.limit === state.selected.length &&
!state.selected.find(selectedItem => selectedItem.key === item.key);
}
// Ignore item if it's multiple and is already selected
if (
!(props.multiple &&
typeof props.multiple === 'object' &&
props.multiple.removeSelectedItems &&
state.multipleMap?.[item.key])
) {
filteredData.push(item);
}
}
}
let addButton = null;
const {add} = props;
if (
(add && filterString && !exactMatch) ||
(add && add.alwaysVisible)
) {
if (
!(add.regexp && !add.regexp.test(filterString)) &&
!(add.minlength && filterString.length < +add.minlength) ||
add.alwaysVisible
) {
let label;
if (add.label) {
label = (typeof add.label === 'function') ? add.label(filterString) : add.label;
} else {
label = filterString;
}
addButton = {
prefix: add.prefix,
label,
delayed: add.delayed ?? true
};
}
}
return {filteredData, addButton};
}
function getSelectedIndex<T>(
selected: SelectItem<T> | readonly SelectItem<T>[] | null | undefined,
data: readonly SelectItem<T>[]
) {
const firstSelected = Array.isArray(selected) ? selected[0] : selected;
if (firstSelected == null) {
return null;
}
for (let i = 0; i < data.length; i++) {
const item = data[i];
if (item.key === undefined) {
continue;
}
if (item.key === firstSelected.key) {
return i;
}
}
return null;
}
const getItemLabel = <T, >({selectedLabel, label}: SelectItem<T>): string => {
if (selectedLabel != null) {
return selectedLabel;
}
return typeof label === 'string' ? label : '';
};
const getValueForFilter = <T, >(
selected: SelectItem<T> | readonly SelectItem<T>[] | null | undefined,
type: Type,
filterValue: string
): string => (selected && !isArray(selected) && isInputMode(type)
? getItemLabel(selected)
: filterValue);
function isSameSelected<T>(prevSelected: SelectItem<T>[], selected: SelectItem<T>[]) {
if (!prevSelected || !selected || prevSelected.length !== selected.length) {
return false;
}
const keysMap = selected.reduce((result: Record<string, boolean>, item) => {
result[item.key] = true;
return result;
}, {});
return prevSelected.every(it => keysMap[it.key]);
}
/**
* @name Select
* @constructor
* @extends {Component}
*/
/**
* Displays a select.
*/
export default class Select<T = unknown> extends Component<SelectProps<T>, SelectState<T>> {
static defaultProps = {
data: [],
filter: false, // enable filter (not in INPUT modes)
multiple: false, // multiple can be an object - see demo for more information
clear: false, // enable clear button that clears the "selected" state
loading: false, // show a loading indicator while data is loading
disabled: false, // disable select
type: Type.BUTTON,
size: Size.M,
targetElement: null, // element to bind the popup to (select BUTTON or INPUT by default)
hideSelected: false, // INPUT mode: clears the input after an option is selected (useful when the selection is displayed in some custom way elsewhere)
allowAny: false, // INPUT mode: allows any value to be entered
hideArrow: false, // hide dropdown arrow icon
maxHeight: 600, // height of the options list, including the filter and the 'Add' button
directions: [
Popup.PopupProps.Directions.BOTTOM_RIGHT,
Popup.PopupProps.Directions.BOTTOM_LEFT,
Popup.PopupProps.Directions.TOP_LEFT,
Popup.PopupProps.Directions.TOP_RIGHT
],
selected: null, // current selection (item / array of items)
label: null, // BUTTON or INPUT label (nothing selected)
selectedLabel: null, // BUTTON or INPUT label (something selected)
inputPlaceholder: '', // Placeholder for input modes
hint: null, // hint text to display under the list
shortcutsEnabled: false,
onBeforeOpen: noop,
onLoadMore: noop,
onOpen: noop,
onClose: noop,
onFilter: noop, // search string as first argument
onFocus: noop,
onBlur: noop,
onKeyDown: noop,
onSelect: noop, // single + multi
onDeselect: noop, // multi
onChange: noop, // multi
onAdd: noop, // search string as first argument
onDone: noop,
onReset: noop,
tags: null,
ringPopupTarget: null,
dir: 'ltr'
};
static getDerivedStateFromProps<T = unknown>(
nextProps: SelectProps<T>,
prevState: SelectState<T>
) {
const {multiple, data, type} = nextProps;
const {prevSelected, prevData, prevMultiple, filterValue} = prevState;
const nextState: Partial<SelectState<T>> = {
prevData: data,
prevSelected: nextProps.selected,
prevMultiple: multiple
};
if ('data' in nextProps && data !== prevData) {
const {filteredData, addButton} = getListItems(nextProps, prevState, filterValue, data);
Object.assign(nextState, {shownData: filteredData, addButton});
if (prevState.selected) {
Object.assign(nextState, {
selectedIndex: getSelectedIndex(
prevState.selected,
data,
),
filterValue: getValueForFilter(prevState.selected, type, filterValue)
});
}
}
if ('selected' in nextProps && nextProps.selected !== prevSelected) {
const selected = nextProps.selected || (multiple ? [] : null);
const selectedIndex = getSelectedIndex(
selected,
data || prevData,
);
Object.assign(nextState, {
selected,
filterValue: getValueForFilter(selected, type, filterValue)
});
if (!Array.isArray(prevSelected) || !Array.isArray(selected) ||
!isSameSelected(prevSelected, selected)) {
Object.assign(nextState, {selectedIndex});
}
}
if (prevMultiple !== multiple && !deepEqual(prevMultiple, multiple)) {
nextState.selected = multiple ? [] : null;
}
if (multiple && !nextState.selected) {
nextState.selected = prevState.selected;
}
const {selected} = {...prevState, ...nextState};
if (selected && Array.isArray(selected)) {
nextState.multipleMap = buildMultipleMap(selected);
const {filteredData, addButton} = getListItems(nextProps, nextState, filterValue, data);
Object.assign(nextState, {shownData: filteredData, addButton});
}
return nextState;
}
state: SelectState<T> = {
data: [],
shownData: [],
selected: (this.props.multiple ? [] : null),
selectedIndex: null,
filterValue: this.props.filter && typeof this.props.filter === 'object' &&
this.props.filter.value || '',
shortcutsEnabled: false,
popupShortcuts: false,
showPopup: false,
prevData: this.props.data,
prevSelected: null,
prevMultiple: this.props.multiple,
multipleMap: {},
addButton: null
};
componentDidUpdate(prevProps: SelectProps<T>, prevState: SelectState<T>) {
const {showPopup, selected} = this.state;
const {onClose, onOpen, onChange, multiple} = this.props;
if (prevState.showPopup && !showPopup) {
(onClose as (s: typeof selected) => void)(selected);
} else if (!prevState.showPopup && showPopup) {
onOpen();
}
if (multiple !== prevProps.multiple && !deepEqual(multiple, prevProps.multiple)) {
(onChange as (s: typeof selected) => void)(selected);
}
}
static contextType = ControlsHeightContext;
static Type = Type;
static Size = Size;
id = getUID('select-');
shortcutsScope = this.id;
listId = `${this.id}:list`;
private _focusHandler = (e: React.FocusEvent<HTMLInputElement>) => {
this.props.onFocus(e);
this.setState({
shortcutsEnabled: true,
focused: true
});
};
private _blurHandler = () => {
this.props.onBlur();
if (this._popup && this._popup.isVisible() && !this._popup.isClickingPopup) {
window.setTimeout(() => {
this.setState({showPopup: false});
});
}
if (!this._popup?.isClickingPopup) {
this.setState({
shortcutsEnabled: false,
focused: false
});
}
};
node?: HTMLElement | null;
nodeRef = (el: HTMLElement | null) => {
this.node = el;
};
_popup: SelectPopup<SelectItemData<T>> | null = null;
onEmptyPopupEnter = () => {
if (this.state.addButton) {
this.addHandler();
}
};
private _onEnter = () => {
if (this.state.addButton && this.state.shownData.length === 0) {
this.addHandler();
}
this.props.onDone();
if (!this._popup?.isVisible() && this.props.allowAny) {
return true;
}
return undefined;
};
private _onEsc = (event: KeyboardEvent) => {
if (!this._popup?.isVisible()) {
return true;
} else if (this.props.multiple || !this.props.getInitial) {
return false;
}
const selected = {
key: Math.random(),
label: this.props.getInitial()
} as SelectItem<T>;
this.setState({
selected,
filterValue: this.getValueForFilter(selected)
}, () => {
(this.props.onChange as (s: typeof selected, e?: Event) => void)(selected, event);
this.props.onReset();
});
return undefined;
};
_inputShortcutHandler = () => {
if (this.state.focused && this._popup && !this._popup.isVisible()) {
this._clickHandler();
}
};
getValueForFilter(selected: SelectItem<T> | readonly SelectItem<T>[] | null | undefined): string {
return getValueForFilter(selected, this.props.type, this.state.filterValue);
}
_getSelectedIndex(
selected: SelectItem<T> | readonly SelectItem<T>[] | null | undefined,
data: readonly SelectItem<T>[]
) {
return getSelectedIndex(selected, data);
}
popupRef = (el: SelectPopup<SelectItemData<T>> | null) => {
this._popup = el;
};
_getResetOption(): SelectItem<T> | null {
const isOptionsSelected = Array.isArray(this.state.selected) && this.state.selected.length;
const reset = this.props.tags && typeof this.props.tags === 'object'
? this.props.tags.reset
: null;
if (!isOptionsSelected || !reset) {
return null;
}
const resetHandler = (item: SelectItem<T>, event: Event | SyntheticEvent) => {
this.clear(event);
this.clearFilter();
this.props.onFilter('');
this.setState(prevState => ({
shownData: prevState.shownData.slice(reset.separator ? 2 : 1),
multipleMap: {}
}));
this._redrawPopup();
};
return {
isResetItem: true,
separator: reset.separator,
key: reset.label,
rgItemType: List.ListProps.Type.CUSTOM,
template: (
<Button
text
className={styles.button}
data-test="ring-select-reset-tags-button"
height={ControlsHeight.S}
>
{reset.label}
</Button>
),
glyph: reset.glyph,
onClick: resetHandler
} as SelectItem<T>;
}
_prependResetOption(shownData: SelectItem<T>[]): SelectItem<T>[] {
const resetOption = this._getResetOption();
if (resetOption) {
const resetItems = [resetOption];
if (resetOption.separator) {
resetItems.push({
rgItemType: List.ListProps.Type.SEPARATOR
} as SelectItem<T>);
}
return resetItems.concat(shownData);
}
return shownData;
}
private _renderPopup() {
const anchorElement = this.props.targetElement || this.node;
const {showPopup, shownData} = this.state;
const _shownData = this._prependResetOption(shownData);
return (
<I18nContext.Consumer>
{({translate}) => {
let message;
if (this.props.loading) {
message = this.props.loadingMessage ?? translate('loading');
} else if (!shownData.length) {
message = this.props.notFoundMessage ?? translate('noOptionsFound');
}
return (
<SelectPopup<SelectItemData<T>>
data={_shownData}
message={message}
toolbar={showPopup && this.getToolbar()}
loading={this.props.loading}
activeIndex={this.state.selectedIndex}
hidden={!showPopup}
ref={this.popupRef}
maxHeight={this.props.maxHeight}
minWidth={this.props.minWidth}
directions={this.props.directions}
className={this.props.popupClassName}
style={this.props.popupStyle}
top={this.props.top}
left={this.props.left}
filter={this.isInputMode() ? false : this.props.filter} // disable popup filter in INPUT mode
multiple={this.props.multiple}
filterValue={this.state.filterValue}
anchorElement={anchorElement}
onCloseAttempt={this._onCloseAttempt}
onSelect={this._listSelectHandler}
onSelectAll={this._listSelectAllHandler}
onFilter={this._filterChangeHandler}
onClear={this.clearFilter}
onLoadMore={this.props.onLoadMore}
isInputMode={this.isInputMode()}
selected={this.state.selected}
tags={this.props.tags}
compact={this.props.compact}
renderOptimization={this.props.renderOptimization}
ringPopupTarget={this.props.ringPopupTarget}
disableMoveOverflow={this.props.disableMoveOverflow}
disableScrollToActive={this.props.disableScrollToActive}
dir={this.props.dir}
onEmptyPopupEnter={this.onEmptyPopupEnter}
listId={this.listId}
/>
);
}}
</I18nContext.Consumer>
);
}
_showPopup() {
if (!this.node) {
return;
}
const shownData = this.getListItems(this.filterValue());
this.setState({
showPopup: !!shownData.length || !this.props.allowAny,
shownData
});
}
_hidePopup(tryFocusAnchor?: boolean) {
if (this.node && this.state.showPopup) {
this.setState(prevState => ({
showPopup: false,
filterValue: this.props.allowAny ? prevState.filterValue : ''
}));
if (tryFocusAnchor) {
const focusableSelectExists = this.node &&
this.node.querySelector<HTMLElement>('[data-test~=ring-select__focus]');
const restoreFocusNode = this.props.targetElement || focusableSelectExists;
if (restoreFocusNode) {
restoreFocusNode.focus();
}
}
}
}
addHandler = () => {
const value = this.filterValue();
this._hidePopup();
this.props.onAdd(value);
};
getToolbar() {
const {hint, renderBottomToolbar} = this.props;
const {prefix, label, delayed} = this.state.addButton || {};
const isToolbarHasElements = this.state.addButton || hint || renderBottomToolbar;
if (!isToolbarHasElements) {
return null;
}
return (
<div
className={classNames({
[styles.toolbar]: Boolean(this.state.addButton || renderBottomToolbar)
})}
data-test="ring-select-toolbar"
>
{renderBottomToolbar && renderBottomToolbar()}
{this.state.addButton && (
<Button
text
delayed={delayed}
className={classNames(styles.button, styles.buttonSpaced)}
onClick={this.addHandler}
data-test="ring-select-toolbar-button"
>
{prefix ? `${prefix} ${label}` : label}
</Button>
)}
{hint && (
<List.ListHint
label={hint}
data-test="ring-select-toolbar-hint"
/>
)}
</div>
);
}
getLowerCaseLabel = getLowerCaseLabel;
doesLabelMatch = doesLabelMatch;
getFilterFn() {
return getFilterFn(this.props.filter);
}
getListItems(rawFilterString: string, data?: SelectItem<T>[]) {
const {filteredData, addButton} = getListItems(this.props, this.state, rawFilterString, data);
this.setState({addButton});
return filteredData;
}
filterValue(): string
filterValue(setValue: string): void
filterValue(setValue?: string) {
if (typeof setValue === 'string' || typeof setValue === 'number') {
this.setState({filterValue: setValue});
return undefined;
} else {
return this.state.filterValue;
}
}
isInputMode() {
return isInputMode(this.props.type);
}
_clickHandler = () => {
if (!this.props.disabled) {
if (this.state.showPopup) {
this._hidePopup();
} else {
this.props.onBeforeOpen();
this._showPopup();
}
}
};
_openPopupIfClosed = () => {
if (this.props.disabled || this.state.showPopup) {
return;
}
this.props.onBeforeOpen();
this._showPopup();
};
_filterChangeHandler = (e: React.ChangeEvent<HTMLInputElement>) => {
this._setFilter(e.currentTarget.value, e);
};
private _setFilter = (value: string, event?: SyntheticEvent) => {
if (this.isInputMode() && !this.state.focused) {
return;
}
if (value === this.state.filterValue) {
return;
}
const filterValue = value.replace(/^\s+/g, '');
this.props.onFilter(filterValue);
if (this.props.allowAny) {
const fakeSelected = {
key: Math.random(),
label: filterValue
} as SelectItem<T>;
this.setState({
selected: filterValue === '' ? null : fakeSelected,
selectedIndex: null
}, () => {
this.props.onSelect(fakeSelected, event);
(this.props.onChange as (selected: SelectItem<T>, event?: SyntheticEvent) => void)(
fakeSelected,
event
);
});
}
!this._popup?.isVisible() && this.props.onBeforeOpen();
this.setState({filterValue}, () => {
this._showPopup();
});
};
private _rebuildMultipleMap(selected: SelectItem<T> | readonly SelectItem<T>[] | null) {
if (Array.isArray(selected)) {
this.setState({multipleMap: buildMultipleMap(selected)});
}
}
_redrawPopup = () => {
if (this.props.multiple) {
setTimeout(() => { //setTimeout solves events order and bubbling issue
this.isInputMode() && this.clearFilter();
this._showPopup();
}, 0);
}
};
_listSelectHandler = (
selected: SelectItem<T>,
event?: Event,
opts: SelectHandlerParams = {}
) => {
const isItem = (item: SelectItem<T>) => List.isItemType(List.ListProps.Type.ITEM, item);
const isCustomItem = (item: SelectItem<T>) => List.isItemType(List.ListProps.Type.CUSTOM, item);
const isSelectItemEvent = event && (event.type === 'select' || event.type === 'keydown');
if (isSelectItemEvent) {
event.preventDefault();
}
if ((!isItem(selected) && !isCustomItem(selected)) ||
selected.disabled ||
selected.isResetItem) {
return;
}
if (!this.props.multiple) {
this._hidePopup(isSelectItemEvent);
this.setState({
selected,
selectedIndex: this._getSelectedIndex(selected, this.props.data)
}, () => {
const newFilterValue = this.isInputMode() && !this.props.hideSelected
? getItemLabel(selected)
: '';
this.filterValue(newFilterValue);
this.props.onFilter(newFilterValue);
this.props.onSelect(selected, event);
(this.props.onChange as (selected: SelectItem<T>, event?: Event) => void)(selected, event);
});
} else {
const {tryKeepOpen} = opts;
if (!tryKeepOpen) {
this._hidePopup(isSelectItemEvent);
}
if (selected.key == null) {
throw new Error('Multiple selection requires each item to have the "key" property');
}
this.setState(prevState => {
const currentSelection = prevState.selected as SelectItem<T>[];
let nextSelection: SelectItem<T>[];
if (!prevState.multipleMap[selected.key]) {
nextSelection = currentSelection.concat(selected);
this.props.onSelect && this.props.onSelect(selected, event);
} else {
nextSelection = currentSelection.filter(item => item.key !== selected.key);
this.props.onDeselect && this.props.onDeselect(selected);
}
(this.props.onChange as (selected: SelectItem<T>[], event?: Event) => void)(
nextSelection,
event
);
const nextState: Partial<SelectState<T>> = {
selected: nextSelection,
selectedIndex: this._getSelectedIndex(selected, this.props.data)
};
if (
typeof this.props.multiple === 'object' && this.props.multiple.limit &&
nextSelection.length === this.props.multiple.limit
) {