@true-engineering/true-react-common-ui-kit 3.8.0 → 3.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,580 +1,609 @@
1
- import {
2
- ReactNode,
3
- FocusEvent,
4
- KeyboardEvent,
5
- MouseEvent,
6
- useCallback,
7
- useEffect,
8
- useMemo,
9
- useRef,
10
- useState,
11
- SyntheticEvent,
12
- } from 'react';
13
- import { Portal } from 'react-overlays';
14
- import clsx from 'clsx';
15
- import { Styles } from 'jss';
16
- import { debounce } from 'ts-debounce';
17
- import {
18
- getTestId,
19
- isNotEmpty,
20
- isReactNodeNotEmpty,
21
- isStringNotEmpty,
22
- createFilter,
23
- } from '@true-engineering/true-react-platform-helpers';
24
- import { hasExactParent } from '../../helpers';
25
- import { useIsMounted, useOnClickOutsideWithRef, useDropdown, useTweakStyles } from '../../hooks';
26
- import { ICommonProps, IDropdownWithPopperOptions } from '../../types';
27
- import { renderIcon, IIcon } from '../Icon';
28
- import { IInputProps, Input } from '../Input';
29
- import { ISearchInputProps, SearchInput } from '../SearchInput';
30
- import { SelectList } from './components';
31
- import { ALL_OPTION_INDEX, DEFAULT_OPTION_INDEX } from './constants';
32
- import {
33
- defaultConvertFunction,
34
- defaultCompareFunction,
35
- defaultIsOptionDisabled,
36
- getDefaultConvertToIdFunction,
37
- isMultiSelectValue,
38
- } from './helpers';
39
- import { IMultipleSelectValue } from './types';
40
- import { useStyles, ISelectStyles, searchInputStyles, getInputStyles } from './Select.styles';
41
-
42
- export interface ISelectProps<Value>
43
- extends Omit<IInputProps, 'value' | 'onChange' | 'onBlur' | 'type' | 'tweakStyles'>,
44
- ICommonProps<ISelectStyles> {
45
- defaultOptionLabel?: ReactNode;
46
- allOptionsLabel?: string;
47
- noMatchesLabel?: string;
48
- loadingLabel?: ReactNode;
49
- /** @default 'normal' */
50
- optionsMode?: 'search' | 'dynamic' | 'normal';
51
- /** @default 400 */
52
- debounceTime?: number;
53
- /** @default 0 */
54
- minSymbolsCountToOpenList?: number;
55
- dropdownOptions?: IDropdownWithPopperOptions;
56
- /** @default 'chevron-down' */
57
- dropdownIcon?: IIcon;
58
- options: Value[];
59
- value: Value | undefined;
60
- /** @default true */
61
- shouldScrollToList?: boolean;
62
- isMultiSelect?: boolean;
63
- searchInput?: { shouldRenderInList: true } & Pick<ISearchInputProps, 'placeholder'>;
64
- isOptionDisabled?: (option: Value) => boolean;
65
- onChange: (value?: Value) => void; // подумать как возвращать индекс
66
- onBlur?: (event: Event | SyntheticEvent) => void;
67
- onType?: (value: string) => Promise<void>;
68
- optionsFilter?: (options: Value[], query: string) => Value[];
69
- onOpen?: () => void;
70
- compareValuesOnChange?: (v1?: Value, v2?: Value) => boolean;
71
- // Для избежания проблем юзайте useCallback на эти функции
72
- // или выносите их из компонента (чтобы не было сайдэфектов от перерендеринга их)
73
- convertValueToString?: (value: Value) => string | undefined;
74
- convertValueToReactNode?: (value: Value, isDisabled: boolean) => ReactNode;
75
- convertValueToId?: (value: Value) => string | undefined;
76
- }
77
-
78
- export interface IMultipleSelectProps<Value>
79
- extends Omit<ISelectProps<Value>, 'value' | 'onChange' | 'compareValuesOnChange'> {
80
- isMultiSelect: true;
81
- value: IMultipleSelectValue<Value> | undefined;
82
- onChange: (value?: IMultipleSelectValue<Value>) => void;
83
- compareValuesOnChange?: (
84
- v1?: IMultipleSelectValue<Value>,
85
- v2?: IMultipleSelectValue<Value>,
86
- ) => boolean;
87
- }
88
-
89
- export function Select<Value>(
90
- props: ISelectProps<Value> | IMultipleSelectProps<Value>,
91
- ): JSX.Element {
92
- const {
93
- options,
94
- value,
95
- defaultOptionLabel,
96
- allOptionsLabel,
97
- debounceTime = 400,
98
- optionsMode = 'normal',
99
- noMatchesLabel,
100
- loadingLabel,
101
- tweakStyles,
102
- testId,
103
- isReadonly,
104
- isDisabled,
105
- dropdownOptions,
106
- minSymbolsCountToOpenList = 0,
107
- dropdownIcon = 'chevron-down',
108
- shouldScrollToList = true,
109
- searchInput,
110
- iconType,
111
- onChange,
112
- onFocus,
113
- onBlur,
114
- onType,
115
- onOpen,
116
- isOptionDisabled = defaultIsOptionDisabled,
117
- compareValuesOnChange = defaultCompareFunction,
118
- convertValueToString = defaultConvertFunction,
119
- convertValueToId,
120
- convertValueToReactNode,
121
- optionsFilter,
122
- ...inputProps
123
- } = props;
124
- const classes = useStyles({ theme: tweakStyles });
125
-
126
- const shouldRenderSearchInputInList = searchInput?.shouldRenderInList === true;
127
- const hasSearchInputInList = optionsMode !== 'normal' && shouldRenderSearchInputInList;
128
- const isMultiSelect = isMultiSelectValue(props, value);
129
- const hasReadonlyInput = isReadonly || optionsMode === 'normal' || shouldRenderSearchInputInList;
130
-
131
- const tweakInputStyles = useTweakStyles({
132
- innerStyles: getInputStyles({ hasReadonlyInput, isMultiSelect }),
133
- tweakStyles,
134
- className: 'tweakInput',
135
- currentComponentName: 'Select',
136
- });
137
-
138
- const tweakSearchInputStyles = useTweakStyles({
139
- innerStyles: searchInputStyles,
140
- tweakStyles,
141
- className: 'tweakSearchInput',
142
- currentComponentName: 'Select',
143
- });
144
-
145
- const tweakSelectListStyles = useTweakStyles({
146
- tweakStyles,
147
- className: 'tweakSelectList',
148
- currentComponentName: 'Select',
149
- });
150
-
151
- const isMounted = useIsMounted();
152
- const [isListOpen, setIsListOpen] = useState(false);
153
- const [areOptionsLoading, setAreOptionsLoading] = useState(false);
154
- const hasDefaultOption = isReactNodeNotEmpty(defaultOptionLabel);
155
-
156
- const [focusedListCellIndex, setFocusedListCellIndex] = useState(DEFAULT_OPTION_INDEX);
157
- const [searchValue, setSearchValue] = useState('');
158
- // если мы ввели что то в строку поиска - то этот булеан будет отключаться
159
- // вынесен отдельно, из-за проблем с дебаунсом при динамич. опциях
160
- const [shouldShowDefaultOption, setShouldShowDefaultOption] = useState(true);
161
-
162
- const inputWrapper = useRef<HTMLDivElement>(null);
163
- const list = useRef<HTMLDivElement>(null);
164
- const input = useRef<HTMLInputElement>(null); // TODO ref снаружи?
165
-
166
- const strValue = isMultiSelect ? value?.[0] : value;
167
- const shouldShowAllOption =
168
- isMultiSelect && isStringNotEmpty(allOptionsLabel) && searchValue === '';
169
-
170
- const filteredOptions = useMemo(() => {
171
- if (optionsMode !== 'search') {
172
- return options;
173
- }
174
-
175
- const filter =
176
- optionsFilter ?? createFilter<Value>((option) => [convertValueToString(option) ?? '']);
177
-
178
- return filter(options, searchValue);
179
- }, [optionsFilter, options, convertValueToString, searchValue, optionsMode]);
180
-
181
- const availableOptions = useMemo(
182
- () => options.filter((o) => !isOptionDisabled(o)),
183
- [options, isOptionDisabled],
184
- );
185
-
186
- const areAllOptionsSelected = isMultiSelect && value?.length === availableOptions.length;
187
- const shouldShowMultiSelectCounter =
188
- isMultiSelect && isNotEmpty(value) && value.length > 1 && !areAllOptionsSelected;
189
-
190
- const optionsIndexesForNavigation = useMemo(() => {
191
- const result: number[] = [];
192
- if (shouldShowDefaultOption && hasDefaultOption) {
193
- result.push(DEFAULT_OPTION_INDEX);
194
- }
195
- if (shouldShowAllOption) {
196
- result.push(ALL_OPTION_INDEX);
197
- }
198
- return result.concat(
199
- filteredOptions.reduce((acc, cur, i) => {
200
- if (!isOptionDisabled(cur)) {
201
- acc.push(i);
202
- }
203
- return acc;
204
- }, [] as number[]),
205
- );
206
- }, [filteredOptions]);
207
-
208
- const stringValue = isNotEmpty(strValue) ? convertValueToString(strValue) : undefined;
209
- // Для мультиселекта пытаемся показать "Все опции" если выбраны все опции
210
- const showedStringValue =
211
- areAllOptionsSelected && isNotEmpty(allOptionsLabel) ? allOptionsLabel : stringValue;
212
-
213
- const convertToId = useCallback(
214
- (v: Value) => (convertValueToId ?? getDefaultConvertToIdFunction(convertValueToString))(v),
215
- [convertValueToId, convertValueToString],
216
- );
217
-
218
- const handleListClose = useCallback(
219
- (event: Event | SyntheticEvent) => {
220
- setIsListOpen(false);
221
- setSearchValue('');
222
- setShouldShowDefaultOption(true);
223
- onBlur?.(event);
224
- },
225
- [onBlur],
226
- );
227
-
228
- const handleListOpen = () => {
229
- if (!isListOpen) {
230
- setIsListOpen(true);
231
- }
232
- };
233
-
234
- const handleFocus = (event: FocusEvent<HTMLInputElement>) => {
235
- onFocus?.(event);
236
- handleListOpen();
237
- };
238
-
239
- const handleOnClick = () => {
240
- handleListOpen();
241
- };
242
-
243
- const handleBlur = (event: FocusEvent<HTMLInputElement>) => {
244
- // Когда что-то блокирует открытие листа, но блур все равно должен сработать
245
- // например minSymbolsCount
246
- if (isListOpen && !isOpen) {
247
- handleListClose(event);
248
- return;
249
- }
250
-
251
- if (
252
- !isNotEmpty(event.relatedTarget) ||
253
- !isNotEmpty(list.current) ||
254
- !isNotEmpty(inputWrapper.current)
255
- ) {
256
- return;
257
- }
258
-
259
- const isActionInsideSelect =
260
- hasExactParent(event.relatedTarget, list.current) ||
261
- hasExactParent(event.relatedTarget, inputWrapper.current);
262
-
263
- // Ниче не делаем если клик был внутри селекта
264
- if (!isActionInsideSelect) {
265
- handleListClose(event);
266
- }
267
- };
268
-
269
- const handleOnChange = useCallback(
270
- (newValue: Value | IMultipleSelectValue<Value> | undefined) => {
271
- // Тут беда с типами, сорри
272
- if (!compareValuesOnChange(value as never, newValue as never)) {
273
- onChange(newValue as (Value & IMultipleSelectValue<Value>) | undefined);
274
- }
275
- },
276
- [value, compareValuesOnChange, onChange],
277
- );
278
-
279
- const handleOptionSelect = useCallback(
280
- (index: number, event: MouseEvent<HTMLElement> | KeyboardEvent) => {
281
- handleOnChange(index === DEFAULT_OPTION_INDEX ? undefined : filteredOptions[index]);
282
- handleListClose(event);
283
- input.current?.blur();
284
- },
285
- [handleOnChange, handleListClose, filteredOptions],
286
- );
287
-
288
- // MultiSelect
289
- const handleToggleOptionCheckbox = useCallback(
290
- (index: number, isSelected: boolean) => {
291
- if (!isMultiSelect) {
292
- return;
293
- }
294
-
295
- // Если выбрана не дефолтная опция, которая сетит андеф
296
- if (index === DEFAULT_OPTION_INDEX || (index === ALL_OPTION_INDEX && !isSelected)) {
297
- handleOnChange(undefined);
298
- return;
299
- }
300
- if (index === ALL_OPTION_INDEX && isSelected) {
301
- handleOnChange(availableOptions as IMultipleSelectValue<Value>);
302
- return;
303
- }
304
- const option = filteredOptions[index];
305
- handleOnChange(
306
- isSelected
307
- ? // Добавляем
308
- ([...(value ?? []), option] as IMultipleSelectValue<Value>)
309
- : // Убираем
310
- value?.filter((o) => convertToId(o) !== convertToId(option)),
311
- );
312
- },
313
- [handleOnChange, filteredOptions, isMultiSelect, value],
314
- );
315
-
316
- const handleOnType = useCallback(
317
- async (v: string) => {
318
- if (onType === undefined) {
319
- return;
320
- }
321
- if (isMounted()) {
322
- setAreOptionsLoading(true);
323
- }
324
- await onType(v);
325
- if (isMounted()) {
326
- setAreOptionsLoading(false);
327
- }
328
- if (optionsMode === 'dynamic') {
329
- setShouldShowDefaultOption(v === '');
330
- }
331
- },
332
- [onType, optionsMode],
333
- );
334
-
335
- const debounceHandleOnType = useCallback(debounce(handleOnType, debounceTime), [
336
- handleOnType,
337
- debounceTime,
338
- ]);
339
-
340
- const handleInputChange = (v: string) => {
341
- if (onType !== undefined) {
342
- debounceHandleOnType(v);
343
- }
344
-
345
- if (optionsMode !== 'dynamic') {
346
- setShouldShowDefaultOption(v === '');
347
- }
348
-
349
- if (v === '' && !hasSearchInputInList) {
350
- handleOnChange(undefined);
351
- }
352
-
353
- setSearchValue(v);
354
- };
355
-
356
- const handleKeyDown = (event: KeyboardEvent) => {
357
- if (!isListOpen) {
358
- return;
359
- }
360
-
361
- event.stopPropagation();
362
- const curIndexInNavigation = optionsIndexesForNavigation.findIndex(
363
- (index) => index === focusedListCellIndex,
364
- );
365
-
366
- switch (event.code) {
367
- case 'Enter':
368
- case 'NumpadEnter': {
369
- let indexToSelect = focusedListCellIndex;
370
-
371
- // если осталась одна опция в списке,
372
- // то выбираем ее нажатием на enter
373
- if (indexToSelect === DEFAULT_OPTION_INDEX && filteredOptions.length === 1) {
374
- indexToSelect = 0;
375
- }
376
-
377
- if (isMultiSelect) {
378
- let isThisValueAlreadySelected: boolean;
379
- if (indexToSelect === ALL_OPTION_INDEX) {
380
- isThisValueAlreadySelected = areAllOptionsSelected;
381
- } else {
382
- // подумать над концептом реального фокуса на опциях, а не вот эти вот focusedCell
383
- const valueIdToSelect = convertToId(filteredOptions[indexToSelect]);
384
- isThisValueAlreadySelected =
385
- value?.some((opt) => convertToId(opt) === valueIdToSelect) ?? false;
386
- }
387
- handleToggleOptionCheckbox(indexToSelect, !isThisValueAlreadySelected);
388
- } else {
389
- handleOptionSelect(indexToSelect, event);
390
- }
391
- break;
392
- }
393
-
394
- case 'ArrowDown': {
395
- // чтобы убрать перемещение курсора в инпуте
396
- event.preventDefault();
397
- const targetIndexInNavigation =
398
- (curIndexInNavigation + 1) % optionsIndexesForNavigation.length;
399
- setFocusedListCellIndex(optionsIndexesForNavigation[targetIndexInNavigation]);
400
- break;
401
- }
402
-
403
- case 'ArrowUp': {
404
- // чтобы убрать перемещение курсора в инпуте
405
- event.preventDefault();
406
- const targetIndexInNavigation =
407
- (curIndexInNavigation - 1 + optionsIndexesForNavigation.length) %
408
- optionsIndexesForNavigation.length;
409
- setFocusedListCellIndex(optionsIndexesForNavigation[targetIndexInNavigation]);
410
- break;
411
- }
412
- }
413
- };
414
-
415
- const onArrowClick = () => {
416
- if (isListOpen) {
417
- input.current?.blur();
418
- } else {
419
- input.current?.focus();
420
- }
421
- };
422
-
423
- useOnClickOutsideWithRef(list, handleListClose, inputWrapper);
424
-
425
- const hasEnoughSymbolsToSearch = searchValue.trim().length >= minSymbolsCountToOpenList;
426
-
427
- const isOpen =
428
- // Пользователь пытается открыть лист
429
- isListOpen &&
430
- // Нам есть что показать:
431
- // Есть опции
432
- (filteredOptions.length > 0 ||
433
- // Дефолтная опция
434
- (defaultOptionLabel !== undefined && !hasEnoughSymbolsToSearch) ||
435
- // Текст "Загрузка..."
436
- inputProps.isLoading ||
437
- // Текст "Совпадений не найдено"
438
- noMatchesLabel !== undefined ||
439
- // У нас есть инпут с поиском внутри листа
440
- hasSearchInputInList) &&
441
- // Последняя проверка на случай, если мы че то ищем в опциях
442
- (optionsMode === 'normal' || hasEnoughSymbolsToSearch);
443
-
444
- // Эти значения ставятся в false по дефолту также в useDropdown
445
- const {
446
- shouldUsePopper = false,
447
- shouldRenderInBody = false,
448
- shouldHideOnScroll = false,
449
- } = dropdownOptions ?? {};
450
-
451
- const popperData = useDropdown({
452
- isOpen,
453
- onDropdownClose: handleListClose,
454
- referenceElement: inputWrapper.current,
455
- dropdownElement: list.current,
456
- options: dropdownOptions,
457
- dependenciesForPositionUpdating: [inputProps.isLoading, filteredOptions.length],
458
- });
459
-
460
- useEffect(() => {
461
- setFocusedListCellIndex(
462
- optionsIndexesForNavigation.find(
463
- (index) =>
464
- isNotEmpty(strValue) &&
465
- isNotEmpty(filteredOptions[index]) &&
466
- convertToId(filteredOptions[index]) === convertToId(strValue),
467
- ) ?? optionsIndexesForNavigation[0],
468
- );
469
- }, [strValue, filteredOptions, optionsIndexesForNavigation, convertToId]);
470
-
471
- useEffect(() => {
472
- if (isOpen) {
473
- onOpen?.();
474
- }
475
- }, [isOpen]);
476
-
477
- const listEl = (
478
- <div
479
- className={clsx(classes.listWrapper, {
480
- [classes.withoutPopper]: !shouldUsePopper,
481
- [classes.listWrapperInBody]: shouldRenderInBody,
482
- })}
483
- ref={list}
484
- style={popperData?.styles.popper as Styles}
485
- onBlur={handleBlur} // обработка для Tab из списка
486
- {...popperData?.attributes.popper}
487
- >
488
- {isOpen && (
489
- <SelectList
490
- options={filteredOptions}
491
- defaultOptionLabel={
492
- hasDefaultOption && shouldShowDefaultOption ? defaultOptionLabel : undefined
493
- }
494
- allOptionsLabel={shouldShowAllOption ? allOptionsLabel : undefined}
495
- areAllOptionsSelected={areAllOptionsSelected}
496
- customListHeader={
497
- hasSearchInputInList ? (
498
- <SearchInput
499
- value={searchValue}
500
- onChange={handleInputChange}
501
- tweakStyles={tweakSearchInputStyles}
502
- placeholder="Поиск"
503
- {...searchInput}
504
- />
505
- ) : undefined
506
- }
507
- noMatchesLabel={noMatchesLabel}
508
- focusedIndex={focusedListCellIndex}
509
- activeValue={value}
510
- isLoading={inputProps.isLoading}
511
- loadingLabel={loadingLabel}
512
- tweakStyles={tweakSelectListStyles}
513
- testId={getTestId(testId, 'list')}
514
- // скролл не работает с включеным поппером
515
- shouldScrollToList={shouldScrollToList && !shouldUsePopper && !shouldHideOnScroll}
516
- isOptionDisabled={isOptionDisabled}
517
- convertValueToString={convertValueToString}
518
- convertValueToReactNode={convertValueToReactNode}
519
- convertValueToId={convertToId}
520
- onOptionSelect={handleOptionSelect}
521
- onToggleCheckbox={isMultiSelect ? handleToggleOptionCheckbox : undefined}
522
- />
523
- )}
524
- </div>
525
- );
526
-
527
- const multiSelectCounterWithIcon =
528
- shouldShowMultiSelectCounter || isNotEmpty(iconType) ? (
529
- <>
530
- {shouldShowMultiSelectCounter && (
531
- <div className={classes.counter}>(+{value.length - 1})</div>
532
- )}
533
- {isNotEmpty(iconType) && <div className={classes.icon}>{renderIcon(iconType)}</div>}
534
- </>
535
- ) : undefined;
536
-
537
- return (
538
- <div className={classes.root} onKeyDown={handleKeyDown}>
539
- <div
540
- className={clsx(classes.inputWrapper, isDisabled && classes.disabled)}
541
- onClick={isDisabled ? undefined : handleOnClick}
542
- ref={inputWrapper}
543
- >
544
- <Input
545
- value={
546
- searchValue !== '' && !shouldRenderSearchInputInList ? searchValue : showedStringValue
547
- }
548
- onChange={handleInputChange}
549
- isActive={isListOpen}
550
- isReadonly={hasReadonlyInput}
551
- onFocus={handleFocus}
552
- onBlur={handleBlur}
553
- isDisabled={isDisabled}
554
- ref={input}
555
- isLoading={areOptionsLoading}
556
- tweakStyles={tweakInputStyles}
557
- testId={testId}
558
- iconType={isMultiSelect ? multiSelectCounterWithIcon : iconType}
559
- {...inputProps}
560
- />
561
- <div
562
- onMouseDown={(event: MouseEvent) => {
563
- event.preventDefault();
564
- }}
565
- onClick={onArrowClick}
566
- className={clsx(classes.arrow, isOpen && classes.activeArrow)}
567
- >
568
- {renderIcon(dropdownIcon)}
569
- </div>
570
- </div>
571
- {shouldUsePopper ? (
572
- <Portal container={shouldRenderInBody ? document.body : inputWrapper.current}>
573
- <>{listEl}</>
574
- </Portal>
575
- ) : (
576
- <>{isOpen && listEl}</>
577
- )}
578
- </div>
579
- );
580
- }
1
+ import {
2
+ ReactNode,
3
+ FocusEvent,
4
+ KeyboardEvent,
5
+ MouseEvent,
6
+ useCallback,
7
+ useEffect,
8
+ useMemo,
9
+ useRef,
10
+ useState,
11
+ SyntheticEvent,
12
+ ChangeEvent,
13
+ FormEvent,
14
+ } from 'react';
15
+ import { Portal } from 'react-overlays';
16
+ import clsx from 'clsx';
17
+ import { Styles } from 'jss';
18
+ import { debounce } from 'ts-debounce';
19
+ import {
20
+ getTestId,
21
+ isNotEmpty,
22
+ isReactNodeNotEmpty,
23
+ isStringNotEmpty,
24
+ createFilter,
25
+ } from '@true-engineering/true-react-platform-helpers';
26
+ import { hasExactParent } from '../../helpers';
27
+ import { useIsMounted, useOnClickOutsideWithRef, useDropdown, useTweakStyles } from '../../hooks';
28
+ import { ICommonProps, IDropdownWithPopperOptions } from '../../types';
29
+ import { renderIcon, IIcon } from '../Icon';
30
+ import { IInputProps, Input } from '../Input';
31
+ import { ISearchInputProps, SearchInput } from '../SearchInput';
32
+ import { SelectList } from './components';
33
+ import { ALL_OPTION_INDEX, DEFAULT_OPTION_INDEX } from './constants';
34
+ import {
35
+ defaultConvertFunction,
36
+ defaultCompareFunction,
37
+ defaultIsOptionDisabled,
38
+ getDefaultConvertToIdFunction,
39
+ isMultiSelectValue,
40
+ } from './helpers';
41
+ import { IMultipleSelectValue } from './types';
42
+ import { useStyles, ISelectStyles, searchInputStyles, getInputStyles } from './Select.styles';
43
+
44
+ export interface ISelectProps<Value>
45
+ extends Omit<IInputProps, 'value' | 'onChange' | 'onBlur' | 'type' | 'tweakStyles'>,
46
+ ICommonProps<ISelectStyles> {
47
+ defaultOptionLabel?: ReactNode;
48
+ allOptionsLabel?: string;
49
+ noMatchesLabel?: string;
50
+ loadingLabel?: ReactNode;
51
+ /** @default 'normal' */
52
+ optionsMode?: 'search' | 'dynamic' | 'normal';
53
+ /** @default 400 */
54
+ debounceTime?: number;
55
+ /** @default 0 */
56
+ minSymbolsCountToOpenList?: number;
57
+ dropdownOptions?: IDropdownWithPopperOptions;
58
+ /** @default 'chevron-down' */
59
+ dropdownIcon?: IIcon;
60
+ options: Value[] | Readonly<Value[]>;
61
+ value: Value | undefined;
62
+ /** @default true */
63
+ shouldScrollToList?: boolean;
64
+ isMultiSelect?: boolean;
65
+ searchInput?: { shouldRenderInList: true } & Pick<ISearchInputProps, 'placeholder'>;
66
+ isOptionDisabled?: (option: Value) => boolean;
67
+ onChange: (
68
+ value: Value | undefined,
69
+ event:
70
+ | MouseEvent<HTMLElement>
71
+ | KeyboardEvent
72
+ | ChangeEvent<HTMLElement>
73
+ | FormEvent<HTMLElement>,
74
+ ) => void; // подумать как возвращать индекс
75
+ onBlur?: (event: Event | SyntheticEvent) => void;
76
+ onType?: (value: string) => Promise<void>;
77
+ optionsFilter?: (options: Value[], query: string) => Value[];
78
+ onOpen?: () => void;
79
+ compareValuesOnChange?: (v1?: Value, v2?: Value) => boolean;
80
+ // Для избежания проблем юзайте useCallback на эти функции
81
+ // или выносите их из компонента (чтобы не было сайдэфектов от перерендеринга их)
82
+ convertValueToString?: (value: Value) => string | undefined;
83
+ convertValueToReactNode?: (value: Value, isDisabled: boolean) => ReactNode;
84
+ convertValueToId?: (value: Value) => string | undefined;
85
+ }
86
+
87
+ export interface IMultipleSelectProps<Value>
88
+ extends Omit<ISelectProps<Value>, 'value' | 'onChange' | 'compareValuesOnChange'> {
89
+ isMultiSelect: true;
90
+ value: IMultipleSelectValue<Value> | undefined;
91
+ onChange: (
92
+ value: IMultipleSelectValue<Value> | undefined,
93
+ event:
94
+ | MouseEvent<HTMLElement>
95
+ | KeyboardEvent
96
+ | ChangeEvent<HTMLElement>
97
+ | FormEvent<HTMLElement>,
98
+ ) => void;
99
+ compareValuesOnChange?: (
100
+ v1?: IMultipleSelectValue<Value>,
101
+ v2?: IMultipleSelectValue<Value>,
102
+ ) => boolean;
103
+ }
104
+
105
+ export function Select<Value>(
106
+ props: ISelectProps<Value> | IMultipleSelectProps<Value>,
107
+ ): JSX.Element {
108
+ const {
109
+ options,
110
+ value,
111
+ defaultOptionLabel,
112
+ allOptionsLabel,
113
+ debounceTime = 400,
114
+ optionsMode = 'normal',
115
+ noMatchesLabel,
116
+ loadingLabel,
117
+ tweakStyles,
118
+ testId,
119
+ isReadonly,
120
+ isDisabled,
121
+ dropdownOptions,
122
+ minSymbolsCountToOpenList = 0,
123
+ dropdownIcon = 'chevron-down',
124
+ shouldScrollToList = true,
125
+ searchInput,
126
+ iconType,
127
+ onChange,
128
+ onFocus,
129
+ onBlur,
130
+ onType,
131
+ onOpen,
132
+ isOptionDisabled = defaultIsOptionDisabled,
133
+ compareValuesOnChange = defaultCompareFunction,
134
+ convertValueToString = defaultConvertFunction,
135
+ convertValueToId,
136
+ convertValueToReactNode,
137
+ optionsFilter,
138
+ ...inputProps
139
+ } = props;
140
+ const classes = useStyles({ theme: tweakStyles });
141
+
142
+ const { shouldRenderInList: shouldRenderSearchInputInList = false, ...searchInputProps } =
143
+ searchInput ?? {};
144
+ const hasSearchInputInList = optionsMode !== 'normal' && shouldRenderSearchInputInList;
145
+ const isMultiSelect = isMultiSelectValue(props, value);
146
+ const hasReadonlyInput = isReadonly || optionsMode === 'normal' || shouldRenderSearchInputInList;
147
+
148
+ const tweakInputStyles = useTweakStyles({
149
+ innerStyles: getInputStyles({ hasReadonlyInput, isMultiSelect }),
150
+ tweakStyles,
151
+ className: 'tweakInput',
152
+ currentComponentName: 'Select',
153
+ });
154
+
155
+ const tweakSearchInputStyles = useTweakStyles({
156
+ innerStyles: searchInputStyles,
157
+ tweakStyles,
158
+ className: 'tweakSearchInput',
159
+ currentComponentName: 'Select',
160
+ });
161
+
162
+ const tweakSelectListStyles = useTweakStyles({
163
+ tweakStyles,
164
+ className: 'tweakSelectList',
165
+ currentComponentName: 'Select',
166
+ });
167
+
168
+ const isMounted = useIsMounted();
169
+ const [isListOpen, setIsListOpen] = useState(false);
170
+ const [areOptionsLoading, setAreOptionsLoading] = useState(false);
171
+ const hasDefaultOption = isReactNodeNotEmpty(defaultOptionLabel);
172
+
173
+ const [focusedListCellIndex, setFocusedListCellIndex] = useState(DEFAULT_OPTION_INDEX);
174
+ const [searchValue, setSearchValue] = useState('');
175
+ // если мы ввели что то в строку поиска - то этот булеан будет отключаться
176
+ // вынесен отдельно, из-за проблем с дебаунсом при динамич. опциях
177
+ const [shouldShowDefaultOption, setShouldShowDefaultOption] = useState(true);
178
+
179
+ const inputWrapper = useRef<HTMLDivElement>(null);
180
+ const list = useRef<HTMLDivElement>(null);
181
+ const input = useRef<HTMLInputElement>(null); // TODO ref снаружи?
182
+
183
+ const strValue = isMultiSelect ? value?.[0] : value;
184
+ const shouldShowAllOption =
185
+ isMultiSelect && isStringNotEmpty(allOptionsLabel) && searchValue === '';
186
+
187
+ const filteredOptions = useMemo(() => {
188
+ if (optionsMode !== 'search') {
189
+ return options;
190
+ }
191
+
192
+ const filter =
193
+ optionsFilter ?? createFilter<Value>((option) => [convertValueToString(option) ?? '']);
194
+
195
+ return filter(options as Value[], searchValue);
196
+ }, [optionsFilter, options, convertValueToString, searchValue, optionsMode]);
197
+
198
+ const availableOptions = useMemo(
199
+ () => options.filter((o) => !isOptionDisabled(o)),
200
+ [options, isOptionDisabled],
201
+ );
202
+
203
+ const areAllOptionsSelected = isMultiSelect && value?.length === availableOptions.length;
204
+ const shouldShowMultiSelectCounter =
205
+ isMultiSelect && isNotEmpty(value) && value.length > 1 && !areAllOptionsSelected;
206
+
207
+ const optionsIndexesForNavigation = useMemo(() => {
208
+ const result: number[] = [];
209
+ if (shouldShowDefaultOption && hasDefaultOption) {
210
+ result.push(DEFAULT_OPTION_INDEX);
211
+ }
212
+ if (shouldShowAllOption) {
213
+ result.push(ALL_OPTION_INDEX);
214
+ }
215
+ return result.concat(
216
+ filteredOptions.reduce((acc, cur, i) => {
217
+ if (!isOptionDisabled(cur)) {
218
+ acc.push(i);
219
+ }
220
+ return acc;
221
+ }, [] as number[]),
222
+ );
223
+ }, [
224
+ filteredOptions,
225
+ hasDefaultOption,
226
+ isOptionDisabled,
227
+ shouldShowAllOption,
228
+ shouldShowDefaultOption,
229
+ ]);
230
+
231
+ const stringValue = isNotEmpty(strValue) ? convertValueToString(strValue) : undefined;
232
+ // Для мультиселекта пытаемся показать "Все опции" если выбраны все опции
233
+ const showedStringValue =
234
+ areAllOptionsSelected && isNotEmpty(allOptionsLabel) ? allOptionsLabel : stringValue;
235
+
236
+ const convertToId = useCallback(
237
+ (v: Value) => (convertValueToId ?? getDefaultConvertToIdFunction(convertValueToString))(v),
238
+ [convertValueToId, convertValueToString],
239
+ );
240
+
241
+ const handleListClose = useCallback(
242
+ (event: Event | SyntheticEvent) => {
243
+ setIsListOpen(false);
244
+ setSearchValue('');
245
+ setShouldShowDefaultOption(true);
246
+ onBlur?.(event);
247
+ },
248
+ [onBlur],
249
+ );
250
+
251
+ const handleListOpen = () => {
252
+ if (!isListOpen) {
253
+ setIsListOpen(true);
254
+ }
255
+ };
256
+
257
+ const handleFocus = (event: FocusEvent<HTMLInputElement>) => {
258
+ onFocus?.(event);
259
+ handleListOpen();
260
+ };
261
+
262
+ const handleOnClick = () => {
263
+ handleListOpen();
264
+ };
265
+
266
+ const handleBlur = (event: FocusEvent<HTMLInputElement>) => {
267
+ // Когда что-то блокирует открытие листа, но блур все равно должен сработать
268
+ // например minSymbolsCount
269
+ if (isListOpen && !isOpen) {
270
+ handleListClose(event);
271
+ return;
272
+ }
273
+
274
+ if (
275
+ !isNotEmpty(event.relatedTarget) ||
276
+ !isNotEmpty(list.current) ||
277
+ !isNotEmpty(inputWrapper.current)
278
+ ) {
279
+ return;
280
+ }
281
+
282
+ const isActionInsideSelect =
283
+ hasExactParent(event.relatedTarget, list.current) ||
284
+ hasExactParent(event.relatedTarget, inputWrapper.current);
285
+
286
+ // Ниче не делаем если клик был внутри селекта
287
+ if (!isActionInsideSelect) {
288
+ handleListClose(event);
289
+ }
290
+ };
291
+
292
+ const handleOnChange = useCallback(
293
+ (
294
+ newValue: Value | IMultipleSelectValue<Value> | undefined,
295
+ event:
296
+ | MouseEvent<HTMLElement>
297
+ | KeyboardEvent
298
+ | ChangeEvent<HTMLElement>
299
+ | FormEvent<HTMLElement>,
300
+ ) => {
301
+ // Тут беда с типами, сорри
302
+ if (!compareValuesOnChange(value as never, newValue as never)) {
303
+ onChange(newValue as (Value & IMultipleSelectValue<Value>) | undefined, event);
304
+ }
305
+ },
306
+ [value, compareValuesOnChange, onChange],
307
+ );
308
+
309
+ const handleOptionSelect = useCallback(
310
+ (index: number, event: MouseEvent<HTMLElement> | KeyboardEvent) => {
311
+ handleOnChange(index === DEFAULT_OPTION_INDEX ? undefined : filteredOptions[index], event);
312
+ handleListClose(event);
313
+ input.current?.blur();
314
+ },
315
+ [handleOnChange, handleListClose, filteredOptions],
316
+ );
317
+
318
+ // MultiSelect
319
+ const handleToggleOptionCheckbox = useCallback(
320
+ (index: number, isSelected: boolean, event: ChangeEvent<HTMLElement> | KeyboardEvent) => {
321
+ if (!isMultiSelect) {
322
+ return;
323
+ }
324
+
325
+ // Если выбрана не дефолтная опция, которая сетит андеф
326
+ if (index === DEFAULT_OPTION_INDEX || (index === ALL_OPTION_INDEX && !isSelected)) {
327
+ handleOnChange(undefined, event);
328
+ return;
329
+ }
330
+ if (index === ALL_OPTION_INDEX && isSelected) {
331
+ handleOnChange(availableOptions as IMultipleSelectValue<Value>, event);
332
+ return;
333
+ }
334
+ const option = filteredOptions[index];
335
+ handleOnChange(
336
+ isSelected
337
+ ? // Добавляем
338
+ ([...(value ?? []), option] as IMultipleSelectValue<Value>)
339
+ : // Убираем
340
+ value?.filter((o) => convertToId(o) !== convertToId(option)),
341
+ event,
342
+ );
343
+ },
344
+ [isMultiSelect, filteredOptions, handleOnChange, value, availableOptions, convertToId],
345
+ );
346
+
347
+ const handleOnType = useCallback(
348
+ async (v: string) => {
349
+ if (onType === undefined) {
350
+ return;
351
+ }
352
+ if (isMounted()) {
353
+ setAreOptionsLoading(true);
354
+ }
355
+ await onType(v);
356
+ if (isMounted()) {
357
+ setAreOptionsLoading(false);
358
+ }
359
+ if (optionsMode === 'dynamic') {
360
+ setShouldShowDefaultOption(v === '');
361
+ }
362
+ },
363
+ [isMounted, onType, optionsMode],
364
+ );
365
+
366
+ const debounceHandleOnType = useMemo(
367
+ () => debounce(handleOnType, debounceTime),
368
+ [handleOnType, debounceTime],
369
+ );
370
+
371
+ const handleInputChange = (v: string, event: FormEvent<HTMLElement>) => {
372
+ if (onType !== undefined) {
373
+ debounceHandleOnType(v);
374
+ }
375
+
376
+ if (optionsMode !== 'dynamic') {
377
+ setShouldShowDefaultOption(v === '');
378
+ }
379
+
380
+ if (v === '' && !hasSearchInputInList) {
381
+ handleOnChange(undefined, event);
382
+ }
383
+
384
+ setSearchValue(v);
385
+ };
386
+
387
+ const handleKeyDown = (event: KeyboardEvent) => {
388
+ if (!isListOpen) {
389
+ return;
390
+ }
391
+
392
+ event.stopPropagation();
393
+ const curIndexInNavigation = optionsIndexesForNavigation.findIndex(
394
+ (index) => index === focusedListCellIndex,
395
+ );
396
+
397
+ switch (event.code) {
398
+ case 'Enter':
399
+ case 'NumpadEnter': {
400
+ let indexToSelect = focusedListCellIndex;
401
+
402
+ // если осталась одна опция в списке,
403
+ // то выбираем ее нажатием на enter
404
+ if (indexToSelect === DEFAULT_OPTION_INDEX && filteredOptions.length === 1) {
405
+ indexToSelect = 0;
406
+ }
407
+
408
+ if (isMultiSelect) {
409
+ let isThisValueAlreadySelected: boolean;
410
+ if (indexToSelect === ALL_OPTION_INDEX) {
411
+ isThisValueAlreadySelected = areAllOptionsSelected;
412
+ } else {
413
+ // подумать над концептом реального фокуса на опциях, а не вот эти вот focusedCell
414
+ const valueIdToSelect = convertToId(filteredOptions[indexToSelect]);
415
+ isThisValueAlreadySelected =
416
+ value?.some((opt) => convertToId(opt) === valueIdToSelect) ?? false;
417
+ }
418
+ handleToggleOptionCheckbox(indexToSelect, !isThisValueAlreadySelected, event);
419
+ } else {
420
+ handleOptionSelect(indexToSelect, event);
421
+ }
422
+ break;
423
+ }
424
+
425
+ case 'ArrowDown': {
426
+ // чтобы убрать перемещение курсора в инпуте
427
+ event.preventDefault();
428
+ const targetIndexInNavigation =
429
+ (curIndexInNavigation + 1) % optionsIndexesForNavigation.length;
430
+ setFocusedListCellIndex(optionsIndexesForNavigation[targetIndexInNavigation]);
431
+ break;
432
+ }
433
+
434
+ case 'ArrowUp': {
435
+ // чтобы убрать перемещение курсора в инпуте
436
+ event.preventDefault();
437
+ const targetIndexInNavigation =
438
+ (curIndexInNavigation - 1 + optionsIndexesForNavigation.length) %
439
+ optionsIndexesForNavigation.length;
440
+ setFocusedListCellIndex(optionsIndexesForNavigation[targetIndexInNavigation]);
441
+ break;
442
+ }
443
+ }
444
+ };
445
+
446
+ const onArrowClick = () => {
447
+ if (isListOpen) {
448
+ input.current?.blur();
449
+ } else {
450
+ input.current?.focus();
451
+ }
452
+ };
453
+
454
+ useOnClickOutsideWithRef(list, handleListClose, inputWrapper);
455
+
456
+ const hasEnoughSymbolsToSearch = searchValue.trim().length >= minSymbolsCountToOpenList;
457
+
458
+ const isOpen =
459
+ // Пользователь пытается открыть лист
460
+ isListOpen &&
461
+ // Нам есть что показать:
462
+ // Есть опции
463
+ (filteredOptions.length > 0 ||
464
+ // Дефолтная опция
465
+ (defaultOptionLabel !== undefined && !hasEnoughSymbolsToSearch) ||
466
+ // Текст "Загрузка..."
467
+ inputProps.isLoading ||
468
+ // Текст "Совпадений не найдено"
469
+ noMatchesLabel !== undefined ||
470
+ // У нас есть инпут с поиском внутри листа
471
+ hasSearchInputInList) &&
472
+ // Последняя проверка на случай, если мы че то ищем в опциях
473
+ (optionsMode === 'normal' || hasEnoughSymbolsToSearch);
474
+
475
+ // Эти значения ставятся в false по дефолту также в useDropdown
476
+ const {
477
+ shouldUsePopper = false,
478
+ shouldRenderInBody = false,
479
+ shouldHideOnScroll = false,
480
+ } = dropdownOptions ?? {};
481
+
482
+ const popperData = useDropdown({
483
+ isOpen,
484
+ onDropdownClose: handleListClose,
485
+ referenceElement: inputWrapper.current,
486
+ dropdownElement: list.current,
487
+ options: dropdownOptions,
488
+ dependenciesForPositionUpdating: [inputProps.isLoading, filteredOptions.length],
489
+ });
490
+
491
+ useEffect(() => {
492
+ setFocusedListCellIndex(
493
+ optionsIndexesForNavigation.find(
494
+ (index) =>
495
+ isNotEmpty(strValue) &&
496
+ isNotEmpty(filteredOptions[index]) &&
497
+ convertToId(filteredOptions[index]) === convertToId(strValue),
498
+ ) ?? optionsIndexesForNavigation[0],
499
+ );
500
+ }, [strValue, filteredOptions, optionsIndexesForNavigation, convertToId]);
501
+
502
+ useEffect(() => {
503
+ if (isOpen) {
504
+ onOpen?.();
505
+ }
506
+ }, [isOpen]);
507
+
508
+ const listEl = (
509
+ <div
510
+ className={clsx(classes.listWrapper, {
511
+ [classes.withoutPopper]: !shouldUsePopper,
512
+ [classes.listWrapperInBody]: shouldRenderInBody,
513
+ })}
514
+ ref={list}
515
+ style={popperData?.styles.popper as Styles}
516
+ onBlur={handleBlur} // обработка для Tab из списка
517
+ {...popperData?.attributes.popper}
518
+ >
519
+ {isOpen && (
520
+ <SelectList
521
+ options={filteredOptions}
522
+ defaultOptionLabel={hasDefaultOption && shouldShowDefaultOption && defaultOptionLabel}
523
+ allOptionsLabel={shouldShowAllOption && allOptionsLabel}
524
+ areAllOptionsSelected={areAllOptionsSelected}
525
+ customListHeader={
526
+ hasSearchInputInList && (
527
+ <SearchInput
528
+ value={searchValue}
529
+ onChange={handleInputChange}
530
+ tweakStyles={tweakSearchInputStyles}
531
+ placeholder="Поиск"
532
+ {...searchInputProps}
533
+ />
534
+ )
535
+ }
536
+ noMatchesLabel={noMatchesLabel}
537
+ focusedIndex={focusedListCellIndex}
538
+ activeValue={value}
539
+ isLoading={inputProps.isLoading}
540
+ loadingLabel={loadingLabel}
541
+ tweakStyles={tweakSelectListStyles}
542
+ testId={getTestId(testId, 'list')}
543
+ // скролл не работает с включеным поппером
544
+ shouldScrollToList={shouldScrollToList && !shouldUsePopper && !shouldHideOnScroll}
545
+ isOptionDisabled={isOptionDisabled}
546
+ convertValueToString={convertValueToString}
547
+ convertValueToReactNode={convertValueToReactNode}
548
+ convertValueToId={convertToId}
549
+ onOptionSelect={handleOptionSelect}
550
+ onToggleCheckbox={isMultiSelect ? handleToggleOptionCheckbox : undefined}
551
+ />
552
+ )}
553
+ </div>
554
+ );
555
+
556
+ const multiSelectCounterWithIcon =
557
+ shouldShowMultiSelectCounter || isNotEmpty(iconType) ? (
558
+ <>
559
+ {shouldShowMultiSelectCounter && (
560
+ <div className={classes.counter}>(+{value.length - 1})</div>
561
+ )}
562
+ {isNotEmpty(iconType) && <div className={classes.icon}>{renderIcon(iconType)}</div>}
563
+ </>
564
+ ) : undefined;
565
+
566
+ return (
567
+ <div className={classes.root} onKeyDown={handleKeyDown}>
568
+ <div
569
+ className={clsx(classes.inputWrapper, isDisabled && classes.disabled)}
570
+ onClick={isDisabled ? undefined : handleOnClick}
571
+ ref={inputWrapper}
572
+ >
573
+ <Input
574
+ value={
575
+ searchValue !== '' && !shouldRenderSearchInputInList ? searchValue : showedStringValue
576
+ }
577
+ onChange={handleInputChange}
578
+ isActive={isListOpen}
579
+ isReadonly={hasReadonlyInput}
580
+ onFocus={handleFocus}
581
+ onBlur={handleBlur}
582
+ isDisabled={isDisabled}
583
+ ref={input}
584
+ isLoading={areOptionsLoading}
585
+ tweakStyles={tweakInputStyles}
586
+ testId={testId}
587
+ iconType={isMultiSelect ? multiSelectCounterWithIcon : iconType}
588
+ {...inputProps}
589
+ />
590
+ <div
591
+ onMouseDown={(event: MouseEvent) => {
592
+ event.preventDefault();
593
+ }}
594
+ onClick={onArrowClick}
595
+ className={clsx(classes.arrow, isOpen && classes.activeArrow)}
596
+ >
597
+ {renderIcon(dropdownIcon)}
598
+ </div>
599
+ </div>
600
+ {shouldUsePopper ? (
601
+ <Portal container={shouldRenderInBody ? document.body : inputWrapper.current}>
602
+ <>{listEl}</>
603
+ </Portal>
604
+ ) : (
605
+ <>{isOpen && listEl}</>
606
+ )}
607
+ </div>
608
+ );
609
+ }