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

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.
Files changed (117) hide show
  1. package/LICENSE +201 -201
  2. package/README.md +6 -0
  3. package/dist/components/NewMoreMenu/NewMoreMenu.d.ts +1 -1
  4. package/dist/components/WithPopup/WithPopup.d.ts +2 -0
  5. package/dist/true-react-common-ui-kit.js +62 -60
  6. package/dist/true-react-common-ui-kit.js.map +1 -1
  7. package/dist/true-react-common-ui-kit.umd.cjs +62 -60
  8. package/dist/true-react-common-ui-kit.umd.cjs.map +1 -1
  9. package/package.json +1 -1
  10. package/src/components/AccountInfo/AccountInfo.stories.tsx +32 -32
  11. package/src/components/AccountInfo/AccountInfo.tsx +80 -80
  12. package/src/components/AddButton/AddButton.stories.tsx +21 -21
  13. package/src/components/AddButton/AddButton.tsx +52 -52
  14. package/src/components/Button/Button.stories.tsx +56 -56
  15. package/src/components/Button/Button.tsx +129 -129
  16. package/src/components/Checkbox/Checkbox.stories.tsx +28 -28
  17. package/src/components/Checkbox/Checkbox.tsx +85 -85
  18. package/src/components/CloseButton/CloseButton.tsx +34 -34
  19. package/src/components/Colors/Colors.stories.tsx +7 -7
  20. package/src/components/DateInput/DateInput.tsx +90 -90
  21. package/src/components/DateInput/constants.ts +2 -2
  22. package/src/components/DatePicker/DatePicker.tsx +308 -308
  23. package/src/components/Description/Description.stories.tsx +27 -27
  24. package/src/components/Description/Description.tsx +61 -61
  25. package/src/components/FiltersPane/FiltersPane.tsx +158 -158
  26. package/src/components/FiltersPane/components/Filter/Filter.tsx +203 -203
  27. package/src/components/FiltersPane/components/FilterValueView/FilterValueView.tsx +166 -166
  28. package/src/components/FiltersPane/components/FilterWithDates/FilterWithDates.tsx +210 -210
  29. package/src/components/FiltersPane/components/FilterWithPeriod/FilterWithPeriod.tsx +177 -177
  30. package/src/components/FiltersPane/components/FilterWrapper/FilterWrapper.tsx +167 -167
  31. package/src/components/Flag/Flag.stories.tsx +29 -29
  32. package/src/components/Flag/Flag.tsx +26 -26
  33. package/src/components/Flag/augment.d.ts +1 -1
  34. package/src/components/FlexibleTable/FlexibleTable.stories.tsx +267 -267
  35. package/src/components/FlexibleTable/FlexibleTable.styles.ts +110 -110
  36. package/src/components/FlexibleTable/FlexibleTable.tsx +271 -271
  37. package/src/components/FlexibleTable/components/FlexibleTableCell/FlexibleTableCell.styles.ts +38 -38
  38. package/src/components/FlexibleTable/components/FlexibleTableCell/FlexibleTableCell.tsx +83 -83
  39. package/src/components/FlexibleTable/components/FlexibleTableRow/FlexibleTableRow.styles.ts +25 -25
  40. package/src/components/FlexibleTable/components/FlexibleTableRow/FlexibleTableRow.tsx +196 -196
  41. package/src/components/FlexibleTable/helpers.ts +13 -13
  42. package/src/components/FlexibleTable/types.ts +52 -52
  43. package/src/components/Icon/Icon.stories.tsx +86 -86
  44. package/src/components/Icon/complexIcons/augment.d.ts +1 -1
  45. package/src/components/Icon/complexIcons/avatarGreen.svg +57 -57
  46. package/src/components/Icon/complexIcons/index.ts +1 -1
  47. package/src/components/IncrementInput/IncrementInput.tsx +105 -105
  48. package/src/components/Input/Input.tsx +297 -297
  49. package/src/components/Input/types.ts +32 -32
  50. package/src/components/List/List.stories.tsx +70 -70
  51. package/src/components/List/List.tsx +33 -33
  52. package/src/components/List/components/ListItem/ListItem.tsx +57 -57
  53. package/src/components/Modal/Modal.stories.tsx +105 -105
  54. package/src/components/Modal/Modal.tsx +196 -196
  55. package/src/components/MoreMenu/MoreMenu.styles.ts +68 -68
  56. package/src/components/MultiSelect/MultiSelect.stories.tsx +46 -46
  57. package/src/components/MultiSelect/MultiSelect.tsx +106 -106
  58. package/src/components/MultiSelect/components/MultiSelectInput/MultiSelectInput.tsx +53 -53
  59. package/src/components/MultiSelectList/MultiSelectList.tsx +461 -461
  60. package/src/components/NewMoreMenu/NewMoreMenu.stories.tsx +1 -0
  61. package/src/components/NewMoreMenu/NewMoreMenu.tsx +3 -1
  62. package/src/components/Notification/Notification.stories.tsx +46 -46
  63. package/src/components/Notification/Notification.tsx +69 -69
  64. package/src/components/NumberInput/NumberInput.tsx +137 -137
  65. package/src/components/NumberInput/index.ts +1 -1
  66. package/src/components/PhoneInput/PhoneInput.tsx +214 -214
  67. package/src/components/PhoneInput/components/PhoneInputCountryList/PhoneInputCountryList.tsx +155 -155
  68. package/src/components/PhoneInput/types.ts +16 -16
  69. package/src/components/RadioButton/RadioButton.stories.tsx +46 -46
  70. package/src/components/RadioButton/RadioButton.tsx +57 -57
  71. package/src/components/ScrollIntoViewIfNeeded/index.ts +1 -1
  72. package/src/components/Select/CustomSelect.stories.tsx +217 -217
  73. package/src/components/Select/MultiSelect.stories.tsx +240 -240
  74. package/src/components/Select/Select.stories.tsx +235 -235
  75. package/src/components/Select/Select.tsx +580 -580
  76. package/src/components/Select/components/SelectList/SelectList.tsx +157 -157
  77. package/src/components/Select/components/SelectListItem/SelectListItem.tsx +68 -68
  78. package/src/components/Select/constants.ts +2 -2
  79. package/src/components/Select/types.ts +1 -1
  80. package/src/components/Selector/Selector.stories.tsx +62 -62
  81. package/src/components/Selector/Selector.styles.ts +164 -164
  82. package/src/components/Selector/Selector.tsx +115 -115
  83. package/src/components/Selector/index.ts +2 -2
  84. package/src/components/Selector/types.ts +12 -12
  85. package/src/components/Skeleton/Skeleton.stories.tsx +19 -19
  86. package/src/components/SmartInput/SmartInput.tsx +134 -134
  87. package/src/components/Status/Status.stories.tsx +73 -73
  88. package/src/components/Status/Status.styles.ts +143 -143
  89. package/src/components/Status/Status.tsx +49 -49
  90. package/src/components/Status/constants.ts +11 -11
  91. package/src/components/Status/index.ts +3 -3
  92. package/src/components/Status/types.ts +5 -5
  93. package/src/components/Switch/Switch.stories.tsx +40 -40
  94. package/src/components/Switch/Switch.tsx +75 -75
  95. package/src/components/TextArea/TextArea.tsx +180 -180
  96. package/src/components/TextButton/TextButton.stories.tsx +46 -46
  97. package/src/components/TextButton/TextButton.styles.ts +129 -129
  98. package/src/components/TextButton/TextButton.tsx +103 -103
  99. package/src/components/TextButton/index.ts +4 -4
  100. package/src/components/TextWithInfo/TextWithInfo.stories.tsx +53 -53
  101. package/src/components/TextWithInfo/TextWithInfo.tsx +62 -62
  102. package/src/components/TextWithTooltip/TextWithTooltip.stories.tsx +58 -58
  103. package/src/components/ThemedPreloader/ThemedPreloader.stories.tsx +41 -41
  104. package/src/components/ThemedPreloader/ThemedPreloader.tsx +54 -54
  105. package/src/components/ThemedPreloader/components/DefaultPreloader/index.ts +1 -1
  106. package/src/components/Toaster/Toaster.stories.tsx +30 -30
  107. package/src/components/Toaster/Toaster.tsx +108 -108
  108. package/src/components/Tooltip/Tooltip.stories.tsx +19 -19
  109. package/src/components/Tooltip/Tooltip.tsx +35 -35
  110. package/src/components/Tooltip/types.ts +1 -1
  111. package/src/components/WithPopup/WithPopup.stories.tsx +1 -0
  112. package/src/components/WithPopup/WithPopup.tsx +7 -1
  113. package/src/helpers/popper-helpers.ts +17 -17
  114. package/src/hooks/use-dropdown.ts +84 -84
  115. package/src/hooks/use-is-mounted.ts +15 -15
  116. package/src/theme/helpers.ts +76 -76
  117. package/src/vite-env.d.ts +1 -1
@@ -1,461 +1,461 @@
1
- import { useEffect, useState, useMemo, useRef, useCallback, ReactNode } from 'react';
2
- import clsx from 'clsx';
3
- import { debounce } from 'ts-debounce';
4
- import { addDataAttributes } from '../../helpers';
5
- import { useIsMounted, useTweakStyles } from '../../hooks';
6
- import { ICommonProps } from '../../types';
7
- import { Button } from '../Button';
8
- import { Checkbox, ICheckboxProps } from '../Checkbox';
9
- import { SearchInput } from '../SearchInput';
10
- import { ThemedPreloader } from '../ThemedPreloader';
11
- import { DEFAULT_LOCALE, MultiSelectLocales } from './constants';
12
- import { defaultConvertFunction, getLocale } from './helpers';
13
- import { IMultiSelectListValues, IMultiSelectLocale, IMultiSelectLocaleKey } from './types';
14
- import {
15
- useStyles,
16
- IMultiSelectListStyles,
17
- checkboxStyles,
18
- searchInputStyles,
19
- clearButtonStyles,
20
- } from './MultiSelectList.styles';
21
-
22
- export interface IMultiSelectListProps<Value, Option> extends ICommonProps<IMultiSelectListStyles> {
23
- value?: Value;
24
- /** @default false */
25
- isSearchEnabled?: boolean;
26
- localeKey?: IMultiSelectLocaleKey;
27
- locale?: Partial<IMultiSelectLocale>;
28
- onClose?: () => void;
29
- onChange: (val?: Value) => void;
30
- options?: Option[];
31
- fetchOptions?: (val?: string, page?: number) => Promise<Option[]>;
32
- getValueView?: (val: Option) => ReactNode;
33
- getValueId?: (val: Option) => string;
34
- getValueString?: (val: Option) => string;
35
- /** @default по умолчанию значение совпадает с isSearchEnabled */
36
- isGroupingEnabled?: boolean;
37
- /** @default 'left' */
38
- checkboxPosition?: 'left' | 'right';
39
- pageSize?: number;
40
- searchMaxLength?: number;
41
- }
42
-
43
- export function MultiSelectList<Value extends IMultiSelectListValues<Option>, Option = string>({
44
- value,
45
- tweakStyles,
46
- data,
47
- isSearchEnabled = false,
48
- localeKey = DEFAULT_LOCALE,
49
- locale = MultiSelectLocales[localeKey],
50
- onChange,
51
- onClose,
52
- options,
53
- fetchOptions,
54
- isGroupingEnabled = isSearchEnabled,
55
- getValueView = defaultConvertFunction,
56
- getValueId = defaultConvertFunction,
57
- getValueString = defaultConvertFunction,
58
- checkboxPosition = 'left',
59
- pageSize,
60
- searchMaxLength,
61
- testId,
62
- }: IMultiSelectListProps<Value, Option>): JSX.Element {
63
- const isMounted = useIsMounted();
64
- const classes = useStyles({ theme: tweakStyles });
65
-
66
- const tweakCheckboxStyles = useTweakStyles({
67
- innerStyles: checkboxStyles,
68
- tweakStyles,
69
- className: 'tweakCheckbox',
70
- currentComponentName: 'MultiSelectList',
71
- });
72
-
73
- const tweakSearchInputStyles = useTweakStyles({
74
- innerStyles: searchInputStyles,
75
- tweakStyles,
76
- className: 'tweakSearchInput',
77
- currentComponentName: 'MultiSelectList',
78
- });
79
-
80
- const tweakClearButtonStyles = useTweakStyles({
81
- innerStyles: clearButtonStyles,
82
- tweakStyles,
83
- className: 'tweakClearButton',
84
- currentComponentName: 'MultiSelectList',
85
- });
86
-
87
- const [keyCursorOn, setKeyCursorOn] = useState(0);
88
- const [searchValue, setSearchValue] = useState('');
89
- // Опции, которые получаем с бека при изменении строки поиска
90
- const [allOptions, setAllOptions] = useState<Option[]>([]);
91
-
92
- const [isLoading, setIsLoading] = useState(false);
93
- const [isLoadingOptionsOnScroll, setLoadingOptionsOnScroll] = useState(false);
94
-
95
- const [activePage, setActivePage] = useState(0);
96
- const [isMaxPage, setIsMaxPage] = useState(false);
97
-
98
- const observer = useRef<IntersectionObserver>();
99
-
100
- const chosenValues = value?.include;
101
-
102
- const translates = useMemo(() => getLocale(localeKey, locale), [localeKey, locale]);
103
- const chosenValuesIds = useMemo(() => chosenValues?.map(getValueId), [getValueId, chosenValues]);
104
-
105
- const unchosenOptions = useMemo(
106
- () => allOptions.filter((v) => !chosenValuesIds?.includes(getValueId(v))),
107
- [getValueId, allOptions, chosenValuesIds],
108
- );
109
-
110
- const handleSearchInputChange = useCallback(
111
- async (inputValue?: string) => {
112
- if (fetchOptions === undefined) {
113
- return;
114
- }
115
- setIsLoading(true);
116
-
117
- try {
118
- const response = await fetchOptions(inputValue?.trim() ?? '');
119
- if (isMounted() && response !== undefined) {
120
- setAllOptions(response);
121
- setActivePage(0);
122
- setIsMaxPage(
123
- response.length === 0 || (pageSize !== undefined && response.length < pageSize),
124
- );
125
- }
126
- } finally {
127
- if (isMounted()) {
128
- setIsLoading(false);
129
- }
130
- }
131
- },
132
- [fetchOptions, pageSize],
133
- );
134
-
135
- const changeSearchValue = useCallback(debounce(handleSearchInputChange), [
136
- handleSearchInputChange,
137
- ]);
138
-
139
- function handleOnChange(inputValue: string) {
140
- setSearchValue(inputValue);
141
-
142
- if (fetchOptions === undefined) {
143
- if (options !== undefined) {
144
- const lowerSearchValue = inputValue.toLowerCase();
145
- setAllOptions(
146
- options.filter((o) => getValueString(o).toLowerCase().includes(lowerSearchValue)),
147
- );
148
- }
149
- } else {
150
- setIsLoading(true);
151
- changeSearchValue(inputValue);
152
- }
153
- }
154
-
155
- const handleSelectValue = (val: Option[]) => {
156
- if (val.length === 0) {
157
- onChange(undefined);
158
- return;
159
- }
160
-
161
- onChange({
162
- include: val,
163
- } as Value);
164
- };
165
-
166
- const handleClear = () => {
167
- onChange(undefined);
168
- };
169
-
170
- const onSelect: ICheckboxProps<Option>['onSelect'] = (val) => {
171
- handleSelectValue(
172
- val.isSelected
173
- ? [...(chosenValues ?? []), val.value]
174
- : chosenValues?.filter((v) => getValueId(v) !== getValueId(val.value)) ?? [],
175
- );
176
- };
177
-
178
- const handleKeyDown = (event: KeyboardEvent) => {
179
- // TODO: это все очень плохо работает
180
- if (event.code === 'Escape') {
181
- onChange(value);
182
- if (onClose) {
183
- onClose();
184
- }
185
- }
186
- if (event.code === 'ArrowDown') {
187
- if (keyCursorOn < unchosenOptions.length + (value?.include.length ?? 0) - 1) {
188
- setKeyCursorOn(keyCursorOn + 1);
189
- }
190
- }
191
- if (event.code === 'ArrowUp') {
192
- if (keyCursorOn >= 1) {
193
- setKeyCursorOn(keyCursorOn - 1);
194
- }
195
- }
196
- if (event.code === 'Enter') {
197
- if (
198
- unchosenOptions[keyCursorOn] === undefined &&
199
- (value === undefined || value.include.length === 0)
200
- ) {
201
- return;
202
- }
203
- if (value !== undefined) {
204
- if (keyCursorOn < value.include.length) {
205
- onChange({
206
- ...value,
207
- include:
208
- value.include.filter(
209
- (val) => getValueId(val) !== getValueId(value.include[keyCursorOn]),
210
- ) ?? [],
211
- });
212
- } else {
213
- onChange({
214
- ...value,
215
- include: [...value.include, unchosenOptions[keyCursorOn - value.include.length]],
216
- });
217
- }
218
- } else {
219
- onChange({
220
- include: [unchosenOptions[keyCursorOn]],
221
- } as Value);
222
- }
223
- }
224
- };
225
-
226
- const getIsValueChosen = (id: string) => chosenValues?.some((v) => getValueId(v) === id);
227
-
228
- const handleLoadItemsOnScroll = useCallback(
229
- async (inputValue?: string, page?: number) => {
230
- if (fetchOptions === undefined) {
231
- return;
232
- }
233
-
234
- setLoadingOptionsOnScroll(true);
235
-
236
- try {
237
- const response = await fetchOptions(inputValue ?? '', page ?? 0);
238
- if (isMounted()) {
239
- if (response.length > 0) {
240
- setAllOptions((prevState) => [...prevState, ...response]);
241
- }
242
- if (response.length === 0 || (pageSize !== undefined && response.length < pageSize)) {
243
- setIsMaxPage(true);
244
- }
245
- }
246
- } finally {
247
- if (isMounted()) {
248
- setLoadingOptionsOnScroll(false);
249
- }
250
- }
251
- },
252
- [fetchOptions, getValueId],
253
- );
254
-
255
- const initIntersectionObserver = useCallback(
256
- (node: HTMLDivElement) => {
257
- if (isLoadingOptionsOnScroll || isMaxPage) {
258
- return;
259
- }
260
-
261
- if (observer.current) {
262
- observer.current.disconnect();
263
- }
264
-
265
- observer.current = new IntersectionObserver(async (entries) => {
266
- if (entries[0].isIntersecting) {
267
- await handleLoadItemsOnScroll(searchValue, activePage + 1);
268
- if (isMounted()) {
269
- setActivePage((prevState) => prevState + 1);
270
- }
271
- }
272
- });
273
-
274
- if (node) {
275
- observer.current.observe(node);
276
- }
277
- },
278
- [activePage, handleLoadItemsOnScroll, isLoadingOptionsOnScroll, isMaxPage, searchValue],
279
- );
280
-
281
- useEffect(() => {
282
- if (fetchOptions === undefined) {
283
- setAllOptions(options ?? []);
284
- return;
285
- }
286
-
287
- const doFetchOptions = async () => {
288
- setIsLoading(true);
289
-
290
- try {
291
- const response = await fetchOptions('');
292
- if (response !== undefined && isMounted()) {
293
- if (response.length === 0 || (pageSize !== undefined && response.length < pageSize)) {
294
- setIsMaxPage(true);
295
- }
296
- setAllOptions(response);
297
- }
298
- } finally {
299
- if (isMounted()) {
300
- setIsLoading(false);
301
- }
302
- }
303
- };
304
- doFetchOptions();
305
- }, []);
306
-
307
- useEffect(() => {
308
- document.addEventListener('keydown', handleKeyDown, false);
309
-
310
- return () => {
311
- document.removeEventListener('keydown', handleKeyDown, false);
312
- };
313
- });
314
-
315
- const mainOptionsList = isGroupingEnabled ? unchosenOptions : allOptions;
316
-
317
- const hasSelectedOptionsGroup =
318
- isGroupingEnabled && chosenValues !== undefined && chosenValues.length > 0;
319
-
320
- const shouldShowNothingFoundMessage = !isLoading && allOptions.length === 0;
321
-
322
- const shouldShowAllOptionsLabel =
323
- isGroupingEnabled &&
324
- unchosenOptions.length > 0 &&
325
- chosenValues !== undefined &&
326
- chosenValues.length > 0;
327
-
328
- const shouldShowPreloader = isLoading || isLoadingOptionsOnScroll;
329
-
330
- const shouldShowOptionsList = !isLoading && allOptions.length !== 0;
331
-
332
- return (
333
- <div className={classes.root} {...addDataAttributes(data)}>
334
- {isSearchEnabled && (
335
- <div className={classes.dropdownInput}>
336
- <SearchInput
337
- value={searchValue}
338
- placeholder={translates.searchPlaceholder}
339
- onChange={handleOnChange}
340
- tweakStyles={tweakSearchInputStyles}
341
- maxLength={searchMaxLength}
342
- testId={testId !== undefined ? `${testId}-search` : undefined}
343
- shouldFocusOnMount
344
- />
345
- </div>
346
- )}
347
- {shouldShowOptionsList && (
348
- <div
349
- className={classes.list}
350
- data-testid={testId !== undefined ? `${testId}-list` : undefined}
351
- >
352
- {/* Выбранные */}
353
- {hasSelectedOptionsGroup && (
354
- <>
355
- <div
356
- className={clsx(
357
- classes.label,
358
- classes.labelChosen,
359
- !isSearchEnabled && classes.withoutTopGap,
360
- )}
361
- >
362
- {translates.chosen}
363
- </div>
364
- {chosenValues?.map((val) => {
365
- const id = getValueId(val);
366
- const view = getValueView(val);
367
-
368
- return (
369
- <div
370
- className={clsx(
371
- classes.item,
372
- // keyCursorOn === index && classes.selectedItem,
373
- )}
374
- key={id}
375
- >
376
- <Checkbox
377
- onSelect={onSelect}
378
- isChecked
379
- value={val}
380
- tweakStyles={tweakCheckboxStyles}
381
- labelPosition={checkboxPosition === 'left' ? 'right' : 'left'}
382
- >
383
- <div className={classes.option} data-option={id}>
384
- {view}
385
- </div>
386
- </Checkbox>
387
- </div>
388
- );
389
- })}
390
- </>
391
- )}
392
-
393
- {!isLoading && (
394
- <>
395
- {/* Не выбранные (или все если нет группировки) */}
396
- {shouldShowAllOptionsLabel && <div className={classes.label}>{translates.all}</div>}
397
-
398
- {mainOptionsList.map((val, index) => {
399
- const id = getValueId(val);
400
- const view = getValueView(val);
401
-
402
- return (
403
- <div
404
- className={clsx(
405
- classes.item,
406
- // keyCursorOn === index + (value?.include.length ?? 0) &&
407
- // classes.selectedItem,
408
- )}
409
- ref={
410
- mainOptionsList.length - 1 === index ? initIntersectionObserver : undefined
411
- }
412
- key={id}
413
- >
414
- <Checkbox
415
- onSelect={onSelect}
416
- isChecked={getIsValueChosen(id)}
417
- value={val}
418
- tweakStyles={tweakCheckboxStyles}
419
- labelPosition={checkboxPosition === 'left' ? 'right' : 'left'}
420
- >
421
- <div className={classes.option} data-option={id}>
422
- {view}
423
- </div>
424
- </Checkbox>
425
- </div>
426
- );
427
- })}
428
- </>
429
- )}
430
- </div>
431
- )}
432
-
433
- {/* Preloader */}
434
- {shouldShowPreloader && (
435
- <div className={classes.preloader}>
436
- <ThemedPreloader type="dots" />
437
- </div>
438
- )}
439
-
440
- {/* Nothing found */}
441
- {shouldShowNothingFoundMessage && (
442
- <div className={classes.nothingFound}>{translates.nothingFound}</div>
443
- )}
444
-
445
- {/* Controls */}
446
- <div className={classes.panel}>
447
- <div className={classes.clear}>
448
- <Button
449
- onClick={handleClear}
450
- size="s"
451
- view="text"
452
- testId={testId !== undefined ? `${testId}-clear-button` : undefined}
453
- tweakStyles={tweakClearButtonStyles}
454
- >
455
- {translates.clear}
456
- </Button>
457
- </div>
458
- </div>
459
- </div>
460
- );
461
- }
1
+ import { useEffect, useState, useMemo, useRef, useCallback, ReactNode } from 'react';
2
+ import clsx from 'clsx';
3
+ import { debounce } from 'ts-debounce';
4
+ import { addDataAttributes } from '../../helpers';
5
+ import { useIsMounted, useTweakStyles } from '../../hooks';
6
+ import { ICommonProps } from '../../types';
7
+ import { Button } from '../Button';
8
+ import { Checkbox, ICheckboxProps } from '../Checkbox';
9
+ import { SearchInput } from '../SearchInput';
10
+ import { ThemedPreloader } from '../ThemedPreloader';
11
+ import { DEFAULT_LOCALE, MultiSelectLocales } from './constants';
12
+ import { defaultConvertFunction, getLocale } from './helpers';
13
+ import { IMultiSelectListValues, IMultiSelectLocale, IMultiSelectLocaleKey } from './types';
14
+ import {
15
+ useStyles,
16
+ IMultiSelectListStyles,
17
+ checkboxStyles,
18
+ searchInputStyles,
19
+ clearButtonStyles,
20
+ } from './MultiSelectList.styles';
21
+
22
+ export interface IMultiSelectListProps<Value, Option> extends ICommonProps<IMultiSelectListStyles> {
23
+ value?: Value;
24
+ /** @default false */
25
+ isSearchEnabled?: boolean;
26
+ localeKey?: IMultiSelectLocaleKey;
27
+ locale?: Partial<IMultiSelectLocale>;
28
+ onClose?: () => void;
29
+ onChange: (val?: Value) => void;
30
+ options?: Option[];
31
+ fetchOptions?: (val?: string, page?: number) => Promise<Option[]>;
32
+ getValueView?: (val: Option) => ReactNode;
33
+ getValueId?: (val: Option) => string;
34
+ getValueString?: (val: Option) => string;
35
+ /** @default по умолчанию значение совпадает с isSearchEnabled */
36
+ isGroupingEnabled?: boolean;
37
+ /** @default 'left' */
38
+ checkboxPosition?: 'left' | 'right';
39
+ pageSize?: number;
40
+ searchMaxLength?: number;
41
+ }
42
+
43
+ export function MultiSelectList<Value extends IMultiSelectListValues<Option>, Option = string>({
44
+ value,
45
+ tweakStyles,
46
+ data,
47
+ isSearchEnabled = false,
48
+ localeKey = DEFAULT_LOCALE,
49
+ locale = MultiSelectLocales[localeKey],
50
+ onChange,
51
+ onClose,
52
+ options,
53
+ fetchOptions,
54
+ isGroupingEnabled = isSearchEnabled,
55
+ getValueView = defaultConvertFunction,
56
+ getValueId = defaultConvertFunction,
57
+ getValueString = defaultConvertFunction,
58
+ checkboxPosition = 'left',
59
+ pageSize,
60
+ searchMaxLength,
61
+ testId,
62
+ }: IMultiSelectListProps<Value, Option>): JSX.Element {
63
+ const isMounted = useIsMounted();
64
+ const classes = useStyles({ theme: tweakStyles });
65
+
66
+ const tweakCheckboxStyles = useTweakStyles({
67
+ innerStyles: checkboxStyles,
68
+ tweakStyles,
69
+ className: 'tweakCheckbox',
70
+ currentComponentName: 'MultiSelectList',
71
+ });
72
+
73
+ const tweakSearchInputStyles = useTweakStyles({
74
+ innerStyles: searchInputStyles,
75
+ tweakStyles,
76
+ className: 'tweakSearchInput',
77
+ currentComponentName: 'MultiSelectList',
78
+ });
79
+
80
+ const tweakClearButtonStyles = useTweakStyles({
81
+ innerStyles: clearButtonStyles,
82
+ tweakStyles,
83
+ className: 'tweakClearButton',
84
+ currentComponentName: 'MultiSelectList',
85
+ });
86
+
87
+ const [keyCursorOn, setKeyCursorOn] = useState(0);
88
+ const [searchValue, setSearchValue] = useState('');
89
+ // Опции, которые получаем с бека при изменении строки поиска
90
+ const [allOptions, setAllOptions] = useState<Option[]>([]);
91
+
92
+ const [isLoading, setIsLoading] = useState(false);
93
+ const [isLoadingOptionsOnScroll, setLoadingOptionsOnScroll] = useState(false);
94
+
95
+ const [activePage, setActivePage] = useState(0);
96
+ const [isMaxPage, setIsMaxPage] = useState(false);
97
+
98
+ const observer = useRef<IntersectionObserver>();
99
+
100
+ const chosenValues = value?.include;
101
+
102
+ const translates = useMemo(() => getLocale(localeKey, locale), [localeKey, locale]);
103
+ const chosenValuesIds = useMemo(() => chosenValues?.map(getValueId), [getValueId, chosenValues]);
104
+
105
+ const unchosenOptions = useMemo(
106
+ () => allOptions.filter((v) => !chosenValuesIds?.includes(getValueId(v))),
107
+ [getValueId, allOptions, chosenValuesIds],
108
+ );
109
+
110
+ const handleSearchInputChange = useCallback(
111
+ async (inputValue?: string) => {
112
+ if (fetchOptions === undefined) {
113
+ return;
114
+ }
115
+ setIsLoading(true);
116
+
117
+ try {
118
+ const response = await fetchOptions(inputValue?.trim() ?? '');
119
+ if (isMounted() && response !== undefined) {
120
+ setAllOptions(response);
121
+ setActivePage(0);
122
+ setIsMaxPage(
123
+ response.length === 0 || (pageSize !== undefined && response.length < pageSize),
124
+ );
125
+ }
126
+ } finally {
127
+ if (isMounted()) {
128
+ setIsLoading(false);
129
+ }
130
+ }
131
+ },
132
+ [fetchOptions, pageSize],
133
+ );
134
+
135
+ const changeSearchValue = useCallback(debounce(handleSearchInputChange), [
136
+ handleSearchInputChange,
137
+ ]);
138
+
139
+ function handleOnChange(inputValue: string) {
140
+ setSearchValue(inputValue);
141
+
142
+ if (fetchOptions === undefined) {
143
+ if (options !== undefined) {
144
+ const lowerSearchValue = inputValue.toLowerCase();
145
+ setAllOptions(
146
+ options.filter((o) => getValueString(o).toLowerCase().includes(lowerSearchValue)),
147
+ );
148
+ }
149
+ } else {
150
+ setIsLoading(true);
151
+ changeSearchValue(inputValue);
152
+ }
153
+ }
154
+
155
+ const handleSelectValue = (val: Option[]) => {
156
+ if (val.length === 0) {
157
+ onChange(undefined);
158
+ return;
159
+ }
160
+
161
+ onChange({
162
+ include: val,
163
+ } as Value);
164
+ };
165
+
166
+ const handleClear = () => {
167
+ onChange(undefined);
168
+ };
169
+
170
+ const onSelect: ICheckboxProps<Option>['onSelect'] = (val) => {
171
+ handleSelectValue(
172
+ val.isSelected
173
+ ? [...(chosenValues ?? []), val.value]
174
+ : chosenValues?.filter((v) => getValueId(v) !== getValueId(val.value)) ?? [],
175
+ );
176
+ };
177
+
178
+ const handleKeyDown = (event: KeyboardEvent) => {
179
+ // TODO: это все очень плохо работает
180
+ if (event.code === 'Escape') {
181
+ onChange(value);
182
+ if (onClose) {
183
+ onClose();
184
+ }
185
+ }
186
+ if (event.code === 'ArrowDown') {
187
+ if (keyCursorOn < unchosenOptions.length + (value?.include.length ?? 0) - 1) {
188
+ setKeyCursorOn(keyCursorOn + 1);
189
+ }
190
+ }
191
+ if (event.code === 'ArrowUp') {
192
+ if (keyCursorOn >= 1) {
193
+ setKeyCursorOn(keyCursorOn - 1);
194
+ }
195
+ }
196
+ if (event.code === 'Enter') {
197
+ if (
198
+ unchosenOptions[keyCursorOn] === undefined &&
199
+ (value === undefined || value.include.length === 0)
200
+ ) {
201
+ return;
202
+ }
203
+ if (value !== undefined) {
204
+ if (keyCursorOn < value.include.length) {
205
+ onChange({
206
+ ...value,
207
+ include:
208
+ value.include.filter(
209
+ (val) => getValueId(val) !== getValueId(value.include[keyCursorOn]),
210
+ ) ?? [],
211
+ });
212
+ } else {
213
+ onChange({
214
+ ...value,
215
+ include: [...value.include, unchosenOptions[keyCursorOn - value.include.length]],
216
+ });
217
+ }
218
+ } else {
219
+ onChange({
220
+ include: [unchosenOptions[keyCursorOn]],
221
+ } as Value);
222
+ }
223
+ }
224
+ };
225
+
226
+ const getIsValueChosen = (id: string) => chosenValues?.some((v) => getValueId(v) === id);
227
+
228
+ const handleLoadItemsOnScroll = useCallback(
229
+ async (inputValue?: string, page?: number) => {
230
+ if (fetchOptions === undefined) {
231
+ return;
232
+ }
233
+
234
+ setLoadingOptionsOnScroll(true);
235
+
236
+ try {
237
+ const response = await fetchOptions(inputValue ?? '', page ?? 0);
238
+ if (isMounted()) {
239
+ if (response.length > 0) {
240
+ setAllOptions((prevState) => [...prevState, ...response]);
241
+ }
242
+ if (response.length === 0 || (pageSize !== undefined && response.length < pageSize)) {
243
+ setIsMaxPage(true);
244
+ }
245
+ }
246
+ } finally {
247
+ if (isMounted()) {
248
+ setLoadingOptionsOnScroll(false);
249
+ }
250
+ }
251
+ },
252
+ [fetchOptions, getValueId],
253
+ );
254
+
255
+ const initIntersectionObserver = useCallback(
256
+ (node: HTMLDivElement) => {
257
+ if (isLoadingOptionsOnScroll || isMaxPage) {
258
+ return;
259
+ }
260
+
261
+ if (observer.current) {
262
+ observer.current.disconnect();
263
+ }
264
+
265
+ observer.current = new IntersectionObserver(async (entries) => {
266
+ if (entries[0].isIntersecting) {
267
+ await handleLoadItemsOnScroll(searchValue, activePage + 1);
268
+ if (isMounted()) {
269
+ setActivePage((prevState) => prevState + 1);
270
+ }
271
+ }
272
+ });
273
+
274
+ if (node) {
275
+ observer.current.observe(node);
276
+ }
277
+ },
278
+ [activePage, handleLoadItemsOnScroll, isLoadingOptionsOnScroll, isMaxPage, searchValue],
279
+ );
280
+
281
+ useEffect(() => {
282
+ if (fetchOptions === undefined) {
283
+ setAllOptions(options ?? []);
284
+ return;
285
+ }
286
+
287
+ const doFetchOptions = async () => {
288
+ setIsLoading(true);
289
+
290
+ try {
291
+ const response = await fetchOptions('');
292
+ if (response !== undefined && isMounted()) {
293
+ if (response.length === 0 || (pageSize !== undefined && response.length < pageSize)) {
294
+ setIsMaxPage(true);
295
+ }
296
+ setAllOptions(response);
297
+ }
298
+ } finally {
299
+ if (isMounted()) {
300
+ setIsLoading(false);
301
+ }
302
+ }
303
+ };
304
+ doFetchOptions();
305
+ }, []);
306
+
307
+ useEffect(() => {
308
+ document.addEventListener('keydown', handleKeyDown, false);
309
+
310
+ return () => {
311
+ document.removeEventListener('keydown', handleKeyDown, false);
312
+ };
313
+ });
314
+
315
+ const mainOptionsList = isGroupingEnabled ? unchosenOptions : allOptions;
316
+
317
+ const hasSelectedOptionsGroup =
318
+ isGroupingEnabled && chosenValues !== undefined && chosenValues.length > 0;
319
+
320
+ const shouldShowNothingFoundMessage = !isLoading && allOptions.length === 0;
321
+
322
+ const shouldShowAllOptionsLabel =
323
+ isGroupingEnabled &&
324
+ unchosenOptions.length > 0 &&
325
+ chosenValues !== undefined &&
326
+ chosenValues.length > 0;
327
+
328
+ const shouldShowPreloader = isLoading || isLoadingOptionsOnScroll;
329
+
330
+ const shouldShowOptionsList = !isLoading && allOptions.length !== 0;
331
+
332
+ return (
333
+ <div className={classes.root} {...addDataAttributes(data)}>
334
+ {isSearchEnabled && (
335
+ <div className={classes.dropdownInput}>
336
+ <SearchInput
337
+ value={searchValue}
338
+ placeholder={translates.searchPlaceholder}
339
+ onChange={handleOnChange}
340
+ tweakStyles={tweakSearchInputStyles}
341
+ maxLength={searchMaxLength}
342
+ testId={testId !== undefined ? `${testId}-search` : undefined}
343
+ shouldFocusOnMount
344
+ />
345
+ </div>
346
+ )}
347
+ {shouldShowOptionsList && (
348
+ <div
349
+ className={classes.list}
350
+ data-testid={testId !== undefined ? `${testId}-list` : undefined}
351
+ >
352
+ {/* Выбранные */}
353
+ {hasSelectedOptionsGroup && (
354
+ <>
355
+ <div
356
+ className={clsx(
357
+ classes.label,
358
+ classes.labelChosen,
359
+ !isSearchEnabled && classes.withoutTopGap,
360
+ )}
361
+ >
362
+ {translates.chosen}
363
+ </div>
364
+ {chosenValues?.map((val) => {
365
+ const id = getValueId(val);
366
+ const view = getValueView(val);
367
+
368
+ return (
369
+ <div
370
+ className={clsx(
371
+ classes.item,
372
+ // keyCursorOn === index && classes.selectedItem,
373
+ )}
374
+ key={id}
375
+ >
376
+ <Checkbox
377
+ onSelect={onSelect}
378
+ isChecked
379
+ value={val}
380
+ tweakStyles={tweakCheckboxStyles}
381
+ labelPosition={checkboxPosition === 'left' ? 'right' : 'left'}
382
+ >
383
+ <div className={classes.option} data-option={id}>
384
+ {view}
385
+ </div>
386
+ </Checkbox>
387
+ </div>
388
+ );
389
+ })}
390
+ </>
391
+ )}
392
+
393
+ {!isLoading && (
394
+ <>
395
+ {/* Не выбранные (или все если нет группировки) */}
396
+ {shouldShowAllOptionsLabel && <div className={classes.label}>{translates.all}</div>}
397
+
398
+ {mainOptionsList.map((val, index) => {
399
+ const id = getValueId(val);
400
+ const view = getValueView(val);
401
+
402
+ return (
403
+ <div
404
+ className={clsx(
405
+ classes.item,
406
+ // keyCursorOn === index + (value?.include.length ?? 0) &&
407
+ // classes.selectedItem,
408
+ )}
409
+ ref={
410
+ mainOptionsList.length - 1 === index ? initIntersectionObserver : undefined
411
+ }
412
+ key={id}
413
+ >
414
+ <Checkbox
415
+ onSelect={onSelect}
416
+ isChecked={getIsValueChosen(id)}
417
+ value={val}
418
+ tweakStyles={tweakCheckboxStyles}
419
+ labelPosition={checkboxPosition === 'left' ? 'right' : 'left'}
420
+ >
421
+ <div className={classes.option} data-option={id}>
422
+ {view}
423
+ </div>
424
+ </Checkbox>
425
+ </div>
426
+ );
427
+ })}
428
+ </>
429
+ )}
430
+ </div>
431
+ )}
432
+
433
+ {/* Preloader */}
434
+ {shouldShowPreloader && (
435
+ <div className={classes.preloader}>
436
+ <ThemedPreloader type="dots" />
437
+ </div>
438
+ )}
439
+
440
+ {/* Nothing found */}
441
+ {shouldShowNothingFoundMessage && (
442
+ <div className={classes.nothingFound}>{translates.nothingFound}</div>
443
+ )}
444
+
445
+ {/* Controls */}
446
+ <div className={classes.panel}>
447
+ <div className={classes.clear}>
448
+ <Button
449
+ onClick={handleClear}
450
+ size="s"
451
+ view="text"
452
+ testId={testId !== undefined ? `${testId}-clear-button` : undefined}
453
+ tweakStyles={tweakClearButtonStyles}
454
+ >
455
+ {translates.clear}
456
+ </Button>
457
+ </div>
458
+ </div>
459
+ </div>
460
+ );
461
+ }