@cloud-ru/ds-fields 2.5.9-preview-b543ec31.0 → 3.0.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.
Files changed (61) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +2 -1
  3. package/dist/cjs/components/FieldSelect/FieldSelect.js +136 -65
  4. package/dist/cjs/components/FieldSelect/constants.d.ts +15 -0
  5. package/dist/cjs/components/FieldSelect/constants.js +32 -1
  6. package/dist/cjs/components/FieldSelect/hooks.d.ts +32 -0
  7. package/dist/cjs/components/FieldSelect/hooks.js +94 -0
  8. package/dist/cjs/components/FieldSelect/types.d.ts +24 -8
  9. package/dist/cjs/components/FieldSelect/utils/customOption.d.ts +20 -0
  10. package/dist/cjs/components/FieldSelect/utils/customOption.js +48 -0
  11. package/dist/cjs/components/FieldSelect/utils/extract.d.ts +11 -0
  12. package/dist/cjs/components/FieldSelect/utils/extract.js +39 -0
  13. package/dist/cjs/components/FieldSelect/utils/filter.d.ts +3 -0
  14. package/dist/cjs/components/FieldSelect/utils/filter.js +40 -0
  15. package/dist/cjs/components/FieldSelect/utils/index.d.ts +6 -0
  16. package/dist/cjs/components/FieldSelect/utils/index.js +22 -0
  17. package/dist/cjs/components/FieldSelect/utils/items.d.ts +9 -0
  18. package/dist/cjs/components/FieldSelect/utils/items.js +47 -0
  19. package/dist/cjs/components/FieldSelect/utils/selection.d.ts +11 -0
  20. package/dist/cjs/components/FieldSelect/utils/selection.js +18 -0
  21. package/dist/cjs/components/FieldSelect/utils/tagSize.d.ts +4 -0
  22. package/dist/cjs/components/FieldSelect/utils/tagSize.js +5 -0
  23. package/dist/esm/components/FieldSelect/FieldSelect.js +138 -67
  24. package/dist/esm/components/FieldSelect/constants.d.ts +15 -0
  25. package/dist/esm/components/FieldSelect/constants.js +31 -0
  26. package/dist/esm/components/FieldSelect/hooks.d.ts +32 -0
  27. package/dist/esm/components/FieldSelect/hooks.js +91 -0
  28. package/dist/esm/components/FieldSelect/types.d.ts +24 -8
  29. package/dist/esm/components/FieldSelect/utils/customOption.d.ts +20 -0
  30. package/dist/esm/components/FieldSelect/utils/customOption.js +41 -0
  31. package/dist/esm/components/FieldSelect/utils/extract.d.ts +11 -0
  32. package/dist/esm/components/FieldSelect/utils/extract.js +34 -0
  33. package/dist/esm/components/FieldSelect/utils/filter.d.ts +3 -0
  34. package/dist/esm/components/FieldSelect/utils/filter.js +36 -0
  35. package/dist/esm/components/FieldSelect/utils/index.d.ts +6 -0
  36. package/dist/esm/components/FieldSelect/utils/index.js +6 -0
  37. package/dist/esm/components/FieldSelect/utils/items.d.ts +9 -0
  38. package/dist/esm/components/FieldSelect/utils/items.js +41 -0
  39. package/dist/esm/components/FieldSelect/utils/selection.d.ts +11 -0
  40. package/dist/esm/components/FieldSelect/utils/selection.js +14 -0
  41. package/dist/esm/components/FieldSelect/utils/tagSize.d.ts +4 -0
  42. package/dist/esm/components/FieldSelect/utils/tagSize.js +2 -0
  43. package/dist/tsconfig.cjs.tsbuildinfo +1 -1
  44. package/dist/tsconfig.esm.tsbuildinfo +1 -1
  45. package/package.json +20 -20
  46. package/src/components/FieldSelect/FieldSelect.tsx +190 -82
  47. package/src/components/FieldSelect/constants.ts +36 -0
  48. package/src/components/FieldSelect/hooks.ts +170 -0
  49. package/src/components/FieldSelect/types.ts +80 -53
  50. package/src/components/FieldSelect/utils/customOption.ts +69 -0
  51. package/src/components/FieldSelect/utils/extract.ts +49 -0
  52. package/src/components/FieldSelect/utils/filter.ts +51 -0
  53. package/src/components/FieldSelect/utils/index.ts +6 -0
  54. package/src/components/FieldSelect/utils/items.ts +58 -0
  55. package/src/components/FieldSelect/utils/selection.ts +25 -0
  56. package/src/components/FieldSelect/utils/tagSize.ts +5 -0
  57. package/dist/cjs/components/FieldSelect/utils.d.ts +0 -19
  58. package/dist/cjs/components/FieldSelect/utils.js +0 -103
  59. package/dist/esm/components/FieldSelect/utils.d.ts +0 -19
  60. package/dist/esm/components/FieldSelect/utils.js +0 -92
  61. package/src/components/FieldSelect/utils.ts +0 -132
@@ -3,7 +3,7 @@ import { ChevronDownSVG } from '@cloud-ru/ds-icons/interface/system';
3
3
  import { InputPrivate, useButtonNavigation, useClearButton } from '@cloud-ru/ds-input-private';
4
4
  import { Droplist } from '@cloud-ru/ds-list';
5
5
  import { Tag } from '@cloud-ru/ds-tag';
6
- import { useLayoutEffect } from '@cloud-ru/ds-utils';
6
+ import { isBrowser, useLayoutEffect } from '@cloud-ru/ds-utils';
7
7
  import cn from 'classnames';
8
8
  import mergeRefs from 'merge-refs';
9
9
  import { forwardRef, useCallback, useMemo, useRef, useState, } from 'react';
@@ -14,18 +14,24 @@ import { TEST_IDS } from '../../constants.js';
14
14
  import { useAdaptiveAutoFocus } from '../../hooks/index.js';
15
15
  import { copyTextToClipboard, getAcrylicProps, preventSlotMouseDown, stopSlotClickPropagation, toInputSize, useCopyButton, } from '../shared/index.js';
16
16
  import fieldStyles from '../shared/styles.module.css';
17
+ import { useCustomOption } from './hooks.js';
17
18
  import styles from './styles.module.css';
18
- import { extractAppearance, extractLabel, filterItems, findItem, flatten, isMultiple, TAG_SIZE_MAP, } from './utils.js';
19
+ import { extractAppearance, extractLabel, filterItems, findItem, flatten, getMissingSelectedItems, getSelectedIds, isMultiple, TAG_SIZE_MAP, } from './utils/index.js';
19
20
  export const FieldSelect = forwardRef(function FieldSelect(props, ref) {
20
- const { label = '', labelTooltip, caption, hint, error, validationState = VALIDATION_STATE.Default, showHintIcon, length, required, size = SIZE.M, className, fieldClassName, items, pinTop, pinBottom, placeholder = '', iconBefore, prefix, postfix, disabled, readonly: readOnly, background = true, open: openProp, onOpenChange, placement, widthStrategy = 'eq', searchable = true, search, autocomplete = false, addOptionByEnter = false, resetSearchOnOptionSelection = true, showClearButton = true, showCopyButton = true, onCopyButtonClick, id, name, autoFocus, layoutPresets, onFocus: onFocusProp, onBlur: onBlurProp, enableFuzzySearch = true, selectedOptionFormatter, footer, footerDivider, footerActiveElementsRefs, loading, noDataState, noResultsState, errorDataState, dataError, dataFiltered, virtualized, scrollToSelectedItem, limitedScrollHeight, untouchableScrollbars, closeOnPopstate, onKeyDown: onKeyDownProp, 'data-test-id': dataTestId = TEST_IDS.fieldSelect, } = props;
21
+ const { label = '', labelTooltip, caption, hint, error, validationState = VALIDATION_STATE.Default, showHintIcon, length, required, size = SIZE.M, className, fieldClassName, items, pinTop, pinBottom, placeholder = '', iconBefore, prefix, postfix, disabled, readonly: readOnly, background = true, open: openProp, onOpenChange, placement, widthStrategy = 'eq', searchable = true, search, autocomplete = false, resetSearchOnOptionSelection = true, showClearButton = true, showCopyButton = true, onCopyButtonClick, id, name, autoFocus, layoutPresets, value, onChange, onFocus: onFocusProp, onBlur: onBlurProp, enableFuzzySearch = true, selectedOptionFormatter, footer, footerDivider, footerActiveElementsRefs, loading, noDataState, noResultsState, errorDataState, dataError, dataFiltered, virtualized, scrollToSelectedItem, limitedScrollHeight, untouchableScrollbars, closeOnPopstate, onKeyDown: onKeyDownProp, 'data-test-id': dataTestId = TEST_IDS.fieldSelect, } = props;
21
22
  const multiple = isMultiple(props);
22
23
  const chips = multiple ? (props.chips ?? true) : false;
23
24
  const removeByBackspace = multiple ? (props.removeByBackspace ?? true) : false;
24
25
  const closeDroplistOnItemClick = props.closeDroplistOnItemClick ?? !multiple;
26
+ const allowCustomOption = props.allowCustomOption === true;
27
+ const addCustomOptionTriggers = allowCustomOption ? props.addCustomOptionTriggers : undefined;
28
+ const onSingleChange = onChange;
29
+ const onMultipleChange = onChange;
25
30
  const resolvedAutoFocus = useAdaptiveAutoFocus(autoFocus, layoutPresets);
26
31
  const inputRef = useRef(null);
27
32
  // Отдельный ref на реальный <input>: `inputRef.current` перезаписывается span-обёрткой PopoverPrivate.
28
33
  const inputElementRef = useRef(null);
34
+ const restoreInputFocusRef = useRef(false);
29
35
  const clearButtonRef = useRef(null);
30
36
  const copyButtonRef = useRef(null);
31
37
  const contentRef = useRef(null);
@@ -42,41 +48,45 @@ export const FieldSelect = forwardRef(function FieldSelect(props, ref) {
42
48
  // Controlled-режим «залипает»: иначе очистка через `value: undefined` откатится на локальный стейт.
43
49
  const singleControlled = useRef(false);
44
50
  const multipleControlled = useRef(false);
45
- if (!multiple && props.value !== undefined) {
51
+ if (!multiple && value !== undefined) {
46
52
  singleControlled.current = true;
47
53
  }
48
- if (multiple && Array.isArray(props.value)) {
54
+ if (multiple && Array.isArray(value)) {
49
55
  multipleControlled.current = true;
50
56
  }
51
57
  const singleValue = useMemo(() => {
52
58
  if (multiple) {
53
59
  return undefined;
54
60
  }
55
- const raw = singleControlled.current ? props.value : singleLocal;
61
+ const raw = singleControlled.current ? value : singleLocal;
56
62
  // `''` = «значение не выбрано»: формы отдают пустое значение строкой.
57
63
  return raw === '' ? undefined : raw;
58
- }, [multiple, props.value, singleLocal]);
64
+ }, [multiple, value, singleLocal]);
59
65
  const multipleValue = useMemo(() => {
60
66
  if (!multiple) {
61
67
  return [];
62
68
  }
63
69
  if (multipleControlled.current) {
64
- return Array.isArray(props.value) ? props.value : [];
70
+ return Array.isArray(value) ? value : [];
65
71
  }
66
72
  return multipleLocal;
67
- }, [multiple, props.value, multipleLocal]);
73
+ }, [multiple, value, multipleLocal]);
68
74
  const effectiveValidationState = useMemo(() => (error ? VALIDATION_STATE.Error : validationState), [error, validationState]);
69
75
  const allItems = useMemo(() => [...(pinTop ?? []), ...items, ...(pinBottom ?? [])], [items, pinTop, pinBottom]);
76
+ const selectedIds = useMemo(() => getSelectedIds({ multiple, multipleValue, singleValue }), [multiple, multipleValue, singleValue]);
77
+ // Выбранное, которого нет в `items` (кастом по allowCustomOption, ленивая подгрузка) — в список, не только в чип.
78
+ const missingSelectedItems = useMemo(() => getMissingSelectedItems(selectedIds, allItems), [selectedIds, allItems]);
79
+ const itemsWithPlaceholders = useMemo(() => (missingSelectedItems.length > 0 ? [...missingSelectedItems, ...items] : items), [missingSelectedItems, items]);
70
80
  // Выбранное значение переживает смену `items` (серверный поиск, ленивая подгрузка).
71
81
  const seenItems = useRef(new Map());
72
82
  const resolveItem = useMemo(() => {
73
- for (const item of flatten(allItems)) {
83
+ for (const item of flatten([...missingSelectedItems, ...allItems])) {
74
84
  if (item.id !== undefined) {
75
85
  seenItems.current.set(item.id, item);
76
86
  }
77
87
  }
78
- return (id) => findItem(allItems, id) ?? seenItems.current.get(id);
79
- }, [allItems]);
88
+ return (id) => findItem(allItems, id) ?? findItem(missingSelectedItems, id) ?? seenItems.current.get(id);
89
+ }, [allItems, missingSelectedItems]);
80
90
  const selectedPairs = useMemo(() => {
81
91
  if (!multiple || multipleValue.length === 0) {
82
92
  return [];
@@ -93,6 +103,7 @@ export const FieldSelect = forwardRef(function FieldSelect(props, ref) {
93
103
  });
94
104
  }, [multiple, multipleValue, resolveItem]);
95
105
  const formatPair = useCallback((pair) => (selectedOptionFormatter ? selectedOptionFormatter(pair) : pair.label), [selectedOptionFormatter]);
106
+ const formatSelected = 'formatSelected' in props && props.formatSelected;
96
107
  const selectedLabel = useMemo(() => {
97
108
  if (!multiple) {
98
109
  if (singleValue === undefined) {
@@ -105,11 +116,11 @@ export const FieldSelect = forwardRef(function FieldSelect(props, ref) {
105
116
  if (chips) {
106
117
  return '';
107
118
  }
108
- if ('formatSelected' in props && props.formatSelected) {
109
- return props.formatSelected(selectedPairs);
119
+ if (formatSelected) {
120
+ return formatSelected(selectedPairs);
110
121
  }
111
122
  return selectedPairs.map(formatPair).join(', ');
112
- }, [multiple, singleValue, selectedPairs, chips, props, formatPair, resolveItem]);
123
+ }, [multiple, singleValue, selectedPairs, chips, formatSelected, formatPair, resolveItem]);
113
124
  const [localInput, setLocalInput] = useState(search?.defaultValue ?? selectedLabel);
114
125
  const inputValue = search?.value !== undefined ? search.value : localInput;
115
126
  const [typing, setTyping] = useState(false);
@@ -131,13 +142,13 @@ export const FieldSelect = forwardRef(function FieldSelect(props, ref) {
131
142
  syncedLabelRef.current = selectedLabel;
132
143
  setInputValue(selectedLabel);
133
144
  }, [selectedLabel, typing, resetSearchOnOptionSelection, setInputValue]);
134
- // При autocomplete фильтрует сервер — items берутся как есть.
145
+ // При autocomplete фильтрует сервер — items берутся как есть, плюс выбранное вне списка.
135
146
  const filteredItems = useMemo(() => {
136
147
  if (!searchable || autocomplete || !typing) {
137
- return items;
148
+ return itemsWithPlaceholders;
138
149
  }
139
- return filterItems(items, inputValue, enableFuzzySearch);
140
- }, [searchable, autocomplete, typing, items, inputValue, enableFuzzySearch]);
150
+ return filterItems(itemsWithPlaceholders, inputValue, enableFuzzySearch);
151
+ }, [searchable, autocomplete, typing, itemsWithPlaceholders, inputValue, enableFuzzySearch]);
141
152
  const filteredPinTop = useMemo(() => {
142
153
  if (!searchable || autocomplete || !typing || !pinTop) {
143
154
  return pinTop;
@@ -150,47 +161,84 @@ export const FieldSelect = forwardRef(function FieldSelect(props, ref) {
150
161
  }
151
162
  return filterItems(pinBottom, inputValue, enableFuzzySearch);
152
163
  }, [searchable, autocomplete, typing, pinBottom, inputValue, enableFuzzySearch]);
153
- const handleOpenChange = useCallback((next) => {
154
- // readonly/disabled поле открывать нельзя, закрывать — можно.
155
- if (next && (disabled || readOnly))
156
- return;
157
- if (openProp === undefined) {
158
- setOpenLocal(next);
159
- }
160
- onOpenChange?.(next);
161
- if (!next) {
162
- setTyping(false);
163
- if (resetSearchOnOptionSelection) {
164
- setInputValue(selectedLabel);
165
- }
166
- }
167
- }, [openProp, onOpenChange, disabled, readOnly, resetSearchOnOptionSelection, setInputValue, selectedLabel]);
168
- const handleSingleChange = (next) => {
164
+ const handleSingleChange = useCallback((next) => {
169
165
  if (multiple) {
170
166
  return;
171
167
  }
172
- if (props.value === undefined) {
168
+ if (value === undefined) {
173
169
  setSingleLocal(next);
174
170
  }
175
- props.onChange?.(next);
171
+ onSingleChange?.(next);
176
172
  setTyping(false);
177
- };
178
- const handleMultipleChange = (next) => {
173
+ }, [multiple, value, onSingleChange]);
174
+ const restoreInputFocus = useCallback(() => {
175
+ restoreInputFocusRef.current = isBrowser() && inputElementRef.current === document.activeElement;
176
+ }, []);
177
+ const handleMultipleChange = useCallback((next) => {
179
178
  if (!multiple) {
180
179
  return;
181
180
  }
182
- if (props.value === undefined) {
181
+ restoreInputFocus();
182
+ if (value === undefined) {
183
183
  setMultipleLocal(next);
184
184
  }
185
- props.onChange?.(next);
185
+ onMultipleChange?.(next);
186
186
  if (searchable) {
187
187
  setTyping(false);
188
188
  if (resetSearchOnOptionSelection) {
189
189
  setInputValue('');
190
190
  }
191
191
  }
192
- };
192
+ }, [multiple, onMultipleChange, value, searchable, resetSearchOnOptionSelection, setInputValue, restoreInputFocus]);
193
+ const resetCustomOptionSearch = useCallback(() => {
194
+ setTyping(false);
195
+ if (resetSearchOnOptionSelection) {
196
+ setInputValue(multiple ? '' : selectedLabel);
197
+ }
198
+ }, [resetSearchOnOptionSelection, setInputValue, multiple, selectedLabel]);
199
+ const { listRef, suppressCloseCommit, enableCloseCommit, tryCommitOnClose, tryCommitOnBlur, tryCommitFromKeyboard, handleListSingleChange, handleListMultipleChange, } = useCustomOption({
200
+ allowCustomOption,
201
+ addCustomOptionTriggers,
202
+ multiple,
203
+ inputValue,
204
+ typing,
205
+ multipleValue,
206
+ commitSingle: handleSingleChange,
207
+ commitMultiple: handleMultipleChange,
208
+ resetSearch: resetCustomOptionSearch,
209
+ inputElementRef,
210
+ clearButtonRef,
211
+ copyButtonRef,
212
+ footerActiveElementsRefs,
213
+ });
214
+ const handleOpenChange = useCallback((next) => {
215
+ // readonly/disabled поле открывать нельзя, закрывать — можно.
216
+ if (next && (disabled || readOnly))
217
+ return;
218
+ if (openProp === undefined) {
219
+ setOpenLocal(next);
220
+ }
221
+ onOpenChange?.(next);
222
+ if (!next) {
223
+ setTyping(false);
224
+ const committed = tryCommitOnClose();
225
+ // Кастомная опция не зафиксирована — вернуть лейбл выбранного значения.
226
+ if (resetSearchOnOptionSelection && !committed) {
227
+ setInputValue(selectedLabel);
228
+ }
229
+ }
230
+ }, [
231
+ openProp,
232
+ onOpenChange,
233
+ disabled,
234
+ readOnly,
235
+ resetSearchOnOptionSelection,
236
+ setInputValue,
237
+ selectedLabel,
238
+ tryCommitOnClose,
239
+ ]);
193
240
  const handleInputChange = (next) => {
241
+ enableCloseCommit();
194
242
  setInputValue(next);
195
243
  setTyping(true);
196
244
  if (!open) {
@@ -201,16 +249,16 @@ export const FieldSelect = forwardRef(function FieldSelect(props, ref) {
201
249
  if (multiple) {
202
250
  // Отключённые выбранные значения остаются при очистке (паритет с легаси).
203
251
  const keepDisabled = selectedPairs.filter(pair => pair.disabled).map(pair => pair.id);
204
- if (props.value === undefined) {
252
+ if (value === undefined) {
205
253
  setMultipleLocal(keepDisabled);
206
254
  }
207
- props.onChange?.(keepDisabled);
255
+ onMultipleChange?.(keepDisabled);
208
256
  }
209
257
  else {
210
- if (props.value === undefined) {
258
+ if (value === undefined) {
211
259
  setSingleLocal(undefined);
212
260
  }
213
- props.onChange?.(undefined);
261
+ onSingleChange?.(undefined);
214
262
  }
215
263
  setInputValue('');
216
264
  setTyping(false);
@@ -219,7 +267,17 @@ export const FieldSelect = forwardRef(function FieldSelect(props, ref) {
219
267
  if (required && !open) {
220
268
  handleOpenChange(true);
221
269
  }
222
- }, [multiple, props, selectedPairs, setInputValue, required, open, handleOpenChange]);
270
+ }, [
271
+ multiple,
272
+ selectedPairs,
273
+ setInputValue,
274
+ required,
275
+ open,
276
+ handleOpenChange,
277
+ value,
278
+ onSingleChange,
279
+ onMultipleChange,
280
+ ]);
223
281
  const removeChip = useCallback((id) => {
224
282
  if (!multiple) {
225
283
  return;
@@ -229,11 +287,11 @@ export const FieldSelect = forwardRef(function FieldSelect(props, ref) {
229
287
  return;
230
288
  }
231
289
  const next = multipleValue.filter(v => v !== id);
232
- if (props.value === undefined) {
290
+ if (value === undefined) {
233
291
  setMultipleLocal(next);
234
292
  }
235
- props.onChange?.(next);
236
- }, [multiple, multipleValue, props, selectedPairs]);
293
+ onMultipleChange?.(next);
294
+ }, [multiple, multipleValue, selectedPairs, value, onMultipleChange]);
237
295
  const handleRemoveChip = useCallback((id) => (e) => {
238
296
  e.stopPropagation();
239
297
  removeChip(id);
@@ -289,19 +347,12 @@ export const FieldSelect = forwardRef(function FieldSelect(props, ref) {
289
347
  }
290
348
  if (event.key === 'Escape' && open) {
291
349
  event.preventDefault();
350
+ suppressCloseCommit();
292
351
  handleOpenChange(false);
293
352
  }
294
- if (addOptionByEnter && event.key === 'Enter' && inputValue !== '') {
295
- // Введённый текст становится новым значением (создание опции «на лету»).
353
+ if (tryCommitFromKeyboard(event)) {
296
354
  event.preventDefault();
297
- if (multiple) {
298
- if (!multipleValue.includes(inputValue)) {
299
- handleMultipleChange([...multipleValue, inputValue]);
300
- }
301
- }
302
- else {
303
- handleSingleChange(inputValue);
304
- }
355
+ event.stopPropagation();
305
356
  return;
306
357
  }
307
358
  if (event.key === 'Enter' && !open) {
@@ -312,6 +363,12 @@ export const FieldSelect = forwardRef(function FieldSelect(props, ref) {
312
363
  event.preventDefault();
313
364
  const last = multipleValue[multipleValue.length - 1];
314
365
  removeChip(last);
366
+ restoreInputFocus();
367
+ }
368
+ };
369
+ const handleTriggerKeyDownCapture = (event) => {
370
+ if (event.key === 'Escape') {
371
+ suppressCloseCommit();
315
372
  }
316
373
  };
317
374
  const handleTriggerMouseEnter = useCallback(() => {
@@ -338,14 +395,28 @@ export const FieldSelect = forwardRef(function FieldSelect(props, ref) {
338
395
  }
339
396
  onFocusProp?.(event);
340
397
  }, [searchable, onFocusProp]);
341
- const handleInputBlur = useCallback((event) => {
398
+ const handleInputBlur = (event) => {
342
399
  setFocusVisible(false);
400
+ const blurResult = tryCommitOnBlur(event);
401
+ // Закрытый список не получит onOpenChange — вернуть лейбл выбранного значения.
402
+ // Клик по айтему открытого списка даёт relatedTarget === null, восстановление делает закрытие.
403
+ if (resetSearchOnOptionSelection && blurResult === 'skipped' && (!open || event.relatedTarget !== null)) {
404
+ setTyping(false);
405
+ setInputValue(selectedLabel);
406
+ }
343
407
  onBlurProp?.(event);
344
- }, [onBlurProp]);
408
+ };
345
409
  const droplistSelection = multiple
346
- ? { mode: 'multiple', value: multipleValue, onChange: handleMultipleChange }
347
- : { mode: 'single', value: singleValue, onChange: handleSingleChange };
410
+ ? { mode: 'multiple', value: multipleValue, onChange: handleListMultipleChange }
411
+ : { mode: 'single', value: singleValue, onChange: handleListSingleChange };
348
412
  const hasChips = chips && selectedPairs.length > 0;
413
+ useLayoutEffect(() => {
414
+ if (!restoreInputFocusRef.current) {
415
+ return;
416
+ }
417
+ restoreInputFocusRef.current = false;
418
+ inputElementRef.current?.focus();
419
+ }, [multipleValue.length]);
349
420
  // minWidth поискового input'а = ширина введённого текста (`.inputPlug`), но не больше строки чипов.
350
421
  // Замер до paint, иначе input мигает при вводе.
351
422
  useLayoutEffect(() => {
@@ -358,11 +429,11 @@ export const FieldSelect = forwardRef(function FieldSelect(props, ref) {
358
429
  setChipInputMinWidth(Math.min(content, Math.max(plug, SEARCH_INPUT_PLUG_MIN_WIDTH)));
359
430
  }, [hasChips, inputValue, selectedPairs.length]);
360
431
  const searchInputField = (_jsx(InputPrivate, { ref: mergeRefs(ref, inputRef, inputElementRef), className: cn(fieldStyles.fieldInput, !searchable && styles.readonlyCursor), value: inputValue, onChange: searchable ? handleInputChange : undefined, placeholder: selectedLabel || hasChips ? '' : placeholder, disabled: disabled, readonly: !searchable || readOnly, id: id, name: name, autoFocus: resolvedAutoFocus, tabIndex: inputTabIndex, onFocus: handleInputFocus, onBlur: handleInputBlur, onKeyDown: handleTriggerKeyDown, "data-test-id": TEST_IDS.fieldSelectInput }));
361
- const searchInput = hasChips ? (_jsx("div", { className: styles.inputWrapper, style: { minWidth: chipInputMinWidth }, children: searchInputField })) : (_jsx("div", { className: fieldStyles.inputArea, children: searchInputField }));
432
+ const searchInput = hasChips ? (_jsx("div", { className: styles.inputWrapper, style: { minWidth: chipInputMinWidth }, children: searchInputField }, 'search-input')) : (_jsx("div", { className: fieldStyles.inputArea, children: searchInputField }));
362
433
  const trigger = (
363
434
  // Focusable-элемент — InputPrivate внутри, обёртка только собирает combobox.
364
435
  // eslint-disable-next-line jsx-a11y/no-static-element-interactions
365
- _jsxs("div", { className: cn(fieldStyles.fieldWrapper, styles.trigger, fieldClassName), "data-size": size, "data-validation-state": effectiveValidationState, "data-disabled": disabled || undefined, "data-readonly": readOnly || undefined, "data-withbackground": background || undefined, "data-focusvisible": focusVisible || open || undefined, "data-hover": !readOnly && !disabled && hover ? true : undefined, "data-test-id": dataTestId, onMouseEnter: handleTriggerMouseEnter, onMouseLeave: handleTriggerMouseLeave, onClick: handleTriggerClick, children: [_jsxs("div", { className: fieldStyles.backgroundWrapper, children: [_jsx("div", { className: fieldStyles.materialLayer, ...getAcrylicProps({
436
+ _jsxs("div", { className: cn(fieldStyles.fieldWrapper, styles.trigger, fieldClassName), "data-size": size, "data-validation-state": effectiveValidationState, "data-disabled": disabled || undefined, "data-readonly": readOnly || undefined, "data-withbackground": background || undefined, "data-focusvisible": focusVisible || open || undefined, "data-hover": !readOnly && !disabled && hover ? true : undefined, "data-test-id": dataTestId, onMouseEnter: handleTriggerMouseEnter, onMouseLeave: handleTriggerMouseLeave, onKeyDownCapture: handleTriggerKeyDownCapture, onClick: handleTriggerClick, children: [_jsxs("div", { className: fieldStyles.backgroundWrapper, children: [_jsx("div", { className: fieldStyles.materialLayer, ...getAcrylicProps({
366
437
  validationState: effectiveValidationState,
367
438
  disabled,
368
439
  readonly: readOnly,
@@ -371,5 +442,5 @@ export const FieldSelect = forwardRef(function FieldSelect(props, ref) {
371
442
  }), children: _jsx("div", { className: fieldStyles.acrylicBg, "aria-hidden": true }) }), _jsx("div", { className: fieldStyles.borderStateLayer, "data-state": 'borderOnBackground' }), _jsx("div", { className: fieldStyles.focusLayer })] }), _jsx("div", { className: fieldStyles.fieldContainer, children: _jsxs("div", { className: fieldStyles.contentWrapper, children: [iconBefore && _jsx("div", { className: fieldStyles.iconSlot, children: iconBefore }), _jsxs("div", { className: fieldStyles.inputLine, children: [prefix && _jsx("span", { className: fieldStyles.prefix, children: prefix }), hasChips ? (_jsxs("div", { className: styles.chipsRow, ref: contentRef, "data-test-id": TEST_IDS.fieldSelectChips, children: [selectedPairs.map(pair => (_jsx(Tag, { label: formatPair(pair), size: TAG_SIZE_MAP[size], appearance: pair.appearance ?? 'neutral', onDelete: disabled || readOnly || pair.disabled ? undefined : handleRemoveChip(pair.id) }, String(pair.id)))), searchInput, _jsx("span", { ref: inputPlugRef, className: styles.inputPlug, "aria-hidden": true, children: inputValue })] })) : (searchInput), postfixButtons && (
372
443
  // eslint-disable-next-line jsx-a11y/no-static-element-interactions
373
444
  _jsx("span", { className: fieldStyles.postfixButtonsSlot, onMouseDown: preventSlotMouseDown, onClick: stopSlotClickPropagation, children: postfixButtons })), postfix && _jsx("span", { className: fieldStyles.postfix, children: postfix })] }), _jsx("div", { className: fieldStyles.iconSlot, children: _jsx("span", { className: styles.chevron, "data-open": open || undefined, "aria-hidden": true, children: _jsx(ChevronDownSVG, {}) }) })] }) })] }));
374
- return (_jsx(FieldDecorator, { className: className, label: label, labelTooltip: labelTooltip, caption: caption, hint: hint, error: error, size: size, validationState: validationState, showHintIcon: showHintIcon, length: length, required: required, labelFor: id, disabled: disabled, readonly: readOnly, children: _jsx(Droplist, { items: filteredItems, label: label, pinTop: filteredPinTop, pinBottom: filteredPinBottom, trigger: 'click', placement: placement, widthStrategy: widthStrategy, triggerElemRef: inputRef, size: size, open: open, onOpenChange: handleOpenChange, selection: droplistSelection, closeDroplistOnItemClick: closeDroplistOnItemClick, footer: footer, footerDivider: footerDivider, footerActiveElementsRefs: footerActiveElementsRefs, loading: loading, noDataState: noDataState, noResultsState: noResultsState, errorDataState: errorDataState, dataError: dataError, dataFiltered: dataFiltered ?? (searchable && typing && inputValue !== ''), virtualized: virtualized, scroll: true, scrollToSelectedItem: scrollToSelectedItem, limitedScrollHeight: limitedScrollHeight, untouchableScrollbars: untouchableScrollbars, closeOnPopstate: closeOnPopstate, "data-test-id": TEST_IDS.fieldSelectList, children: trigger }) }));
445
+ return (_jsx(FieldDecorator, { className: className, label: label, labelTooltip: labelTooltip, caption: caption, hint: hint, error: error, size: size, validationState: validationState, showHintIcon: showHintIcon, length: length, required: required, labelFor: id, disabled: disabled, readonly: readOnly, children: _jsx(Droplist, { items: filteredItems, label: label, pinTop: filteredPinTop, pinBottom: filteredPinBottom, trigger: 'click', placement: placement, widthStrategy: widthStrategy, triggerElemRef: inputRef, listRef: listRef, size: size, open: open, onOpenChange: handleOpenChange, selection: droplistSelection, closeDroplistOnItemClick: closeDroplistOnItemClick, footer: footer, footerDivider: footerDivider, footerActiveElementsRefs: footerActiveElementsRefs, loading: loading, noDataState: noDataState, noResultsState: noResultsState, errorDataState: errorDataState, dataError: dataError, dataFiltered: dataFiltered ?? (searchable && typing && inputValue !== ''), virtualized: virtualized, scroll: true, scrollToSelectedItem: scrollToSelectedItem, limitedScrollHeight: limitedScrollHeight, untouchableScrollbars: untouchableScrollbars, closeOnPopstate: closeOnPopstate, "data-test-id": TEST_IDS.fieldSelectList, children: trigger }) }));
375
446
  });
@@ -2,3 +2,18 @@ export declare const SELECTION_MODE: {
2
2
  readonly Single: "single";
3
3
  readonly Multiple: "multiple";
4
4
  };
5
+ /** События, по которым произвольный ввод фиксируется как выбранная опция. */
6
+ export declare const ADD_CUSTOM_OPTION_TRIGGER: {
7
+ readonly Enter: "enter";
8
+ readonly Blur: "blur";
9
+ readonly Space: "space";
10
+ readonly Comma: "comma";
11
+ };
12
+ /** Разрешенные триггеры для `selection='single'` при `allowCustomOption`. */
13
+ export declare const ADD_CUSTOM_OPTION_TRIGGERS_SINGLE_ALLOWED: readonly ["enter", "blur"];
14
+ /** Триггеры по умолчанию для `selection='single'` при `allowCustomOption`. */
15
+ export declare const ADD_CUSTOM_OPTION_TRIGGERS_SINGLE_DEFAULT: readonly ["enter", "blur"];
16
+ /** Разрешенные триггеры для `selection='multiple'` при `allowCustomOption`. */
17
+ export declare const ADD_CUSTOM_OPTION_TRIGGERS_MULTIPLE_ALLOWED: readonly ["enter", "blur", "space", "comma"];
18
+ /** Триггеры по умолчанию для `selection='multiple'` при `allowCustomOption`. */
19
+ export declare const ADD_CUSTOM_OPTION_TRIGGERS_MULTIPLE_DEFAULT: readonly ["enter", "blur", "space", "comma"];
@@ -2,3 +2,34 @@ export const SELECTION_MODE = {
2
2
  Single: 'single',
3
3
  Multiple: 'multiple',
4
4
  };
5
+ /** События, по которым произвольный ввод фиксируется как выбранная опция. */
6
+ export const ADD_CUSTOM_OPTION_TRIGGER = {
7
+ Enter: 'enter',
8
+ Blur: 'blur',
9
+ Space: 'space',
10
+ Comma: 'comma',
11
+ };
12
+ /** Разрешенные триггеры для `selection='single'` при `allowCustomOption`. */
13
+ export const ADD_CUSTOM_OPTION_TRIGGERS_SINGLE_ALLOWED = [
14
+ ADD_CUSTOM_OPTION_TRIGGER.Enter,
15
+ ADD_CUSTOM_OPTION_TRIGGER.Blur,
16
+ ];
17
+ /** Триггеры по умолчанию для `selection='single'` при `allowCustomOption`. */
18
+ export const ADD_CUSTOM_OPTION_TRIGGERS_SINGLE_DEFAULT = [
19
+ ADD_CUSTOM_OPTION_TRIGGER.Enter,
20
+ ADD_CUSTOM_OPTION_TRIGGER.Blur,
21
+ ];
22
+ /** Разрешенные триггеры для `selection='multiple'` при `allowCustomOption`. */
23
+ export const ADD_CUSTOM_OPTION_TRIGGERS_MULTIPLE_ALLOWED = [
24
+ ADD_CUSTOM_OPTION_TRIGGER.Enter,
25
+ ADD_CUSTOM_OPTION_TRIGGER.Blur,
26
+ ADD_CUSTOM_OPTION_TRIGGER.Space,
27
+ ADD_CUSTOM_OPTION_TRIGGER.Comma,
28
+ ];
29
+ /** Триггеры по умолчанию для `selection='multiple'` при `allowCustomOption`. */
30
+ export const ADD_CUSTOM_OPTION_TRIGGERS_MULTIPLE_DEFAULT = [
31
+ ADD_CUSTOM_OPTION_TRIGGER.Enter,
32
+ ADD_CUSTOM_OPTION_TRIGGER.Blur,
33
+ ADD_CUSTOM_OPTION_TRIGGER.Space,
34
+ ADD_CUSTOM_OPTION_TRIGGER.Comma,
35
+ ];
@@ -0,0 +1,32 @@
1
+ import { ItemId } from '@cloud-ru/ds-list';
2
+ import { FocusEvent, KeyboardEvent, RefObject } from 'react';
3
+ import { FieldSelectAddCustomOptionTrigger } from './types.js';
4
+ /** Результат blur: фокус остался внутри поля, ввод зафиксирован, или коммитить было нечего. */
5
+ type CustomOptionBlurResult = 'inside' | 'committed' | 'skipped';
6
+ type UseCustomOptionParams = {
7
+ allowCustomOption: boolean;
8
+ addCustomOptionTriggers: readonly FieldSelectAddCustomOptionTrigger[] | undefined;
9
+ multiple: boolean;
10
+ inputValue: string;
11
+ typing: boolean;
12
+ multipleValue: ItemId[];
13
+ commitSingle(value: ItemId | undefined): void;
14
+ commitMultiple(value: ItemId[]): void;
15
+ resetSearch(): void;
16
+ inputElementRef: RefObject<HTMLInputElement | null>;
17
+ clearButtonRef: RefObject<HTMLButtonElement | null>;
18
+ copyButtonRef: RefObject<HTMLButtonElement | null>;
19
+ footerActiveElementsRefs?: RefObject<HTMLElement>[];
20
+ };
21
+ /** Фиксация произвольного ввода как выбранной опции: триггеры, blur, закрытие списка. */
22
+ export declare function useCustomOption({ allowCustomOption, addCustomOptionTriggers, multiple, inputValue, typing, multipleValue, commitSingle, commitMultiple, resetSearch, inputElementRef, clearButtonRef, copyButtonRef, footerActiveElementsRefs, }: UseCustomOptionParams): {
23
+ listRef: RefObject<HTMLElement>;
24
+ suppressCloseCommit: () => void;
25
+ enableCloseCommit: () => void;
26
+ tryCommitOnClose: () => boolean;
27
+ tryCommitOnBlur: (event: FocusEvent<HTMLInputElement>) => CustomOptionBlurResult;
28
+ tryCommitFromKeyboard: (event: KeyboardEvent<HTMLInputElement>) => boolean;
29
+ handleListSingleChange: (next: ItemId | undefined) => void;
30
+ handleListMultipleChange: (next: ItemId[]) => void;
31
+ };
32
+ export {};
@@ -0,0 +1,91 @@
1
+ import { isBrowser } from '@cloud-ru/ds-utils';
2
+ import { useCallback, useMemo, useRef } from 'react';
3
+ import { ADD_CUSTOM_OPTION_TRIGGER } from './constants.js';
4
+ import { getCustomOptionTriggerByKey, isCustomOptionBlurInsideField, resolveAddCustomOptionTriggers, shouldCommitCustomOptionOnClose, shouldHandleCustomOptionTrigger, } from './utils/index.js';
5
+ /** Фиксация произвольного ввода как выбранной опции: триггеры, blur, закрытие списка. */
6
+ export function useCustomOption({ allowCustomOption, addCustomOptionTriggers, multiple, inputValue, typing, multipleValue, commitSingle, commitMultiple, resetSearch, inputElementRef, clearButtonRef, copyButtonRef, footerActiveElementsRefs, }) {
7
+ const listRef = useRef(null);
8
+ const skipCloseCommitRef = useRef(false);
9
+ const skipBlurCommitRef = useRef(false);
10
+ const resolvedTriggers = useMemo(() => resolveAddCustomOptionTriggers({
11
+ allowCustomOption,
12
+ addCustomOptionTriggers,
13
+ multiple,
14
+ }), [allowCustomOption, addCustomOptionTriggers, multiple]);
15
+ const tryCommit = useCallback((trigger) => {
16
+ if (!typing || !shouldHandleCustomOptionTrigger(trigger, resolvedTriggers) || inputValue === '') {
17
+ return false;
18
+ }
19
+ if (multiple) {
20
+ if (multipleValue.includes(inputValue)) {
21
+ resetSearch();
22
+ }
23
+ else {
24
+ commitMultiple([...multipleValue, inputValue]);
25
+ }
26
+ }
27
+ else {
28
+ commitSingle(inputValue);
29
+ }
30
+ return true;
31
+ }, [typing, resolvedTriggers, inputValue, multiple, multipleValue, commitMultiple, commitSingle, resetSearch]);
32
+ const suppressCloseCommit = useCallback(() => {
33
+ skipCloseCommitRef.current = true;
34
+ skipBlurCommitRef.current = true;
35
+ }, []);
36
+ const enableCloseCommit = useCallback(() => {
37
+ skipCloseCommitRef.current = false;
38
+ skipBlurCommitRef.current = false;
39
+ }, []);
40
+ const tryCommitOnClose = useCallback(() => {
41
+ const skipped = skipCloseCommitRef.current;
42
+ const shouldCommit = shouldCommitCustomOptionOnClose({
43
+ skip: skipped,
44
+ inputElement: inputElementRef.current,
45
+ activeElement: isBrowser() ? document.activeElement : null,
46
+ });
47
+ if (skipped) {
48
+ queueMicrotask(() => {
49
+ skipCloseCommitRef.current = false;
50
+ });
51
+ }
52
+ return shouldCommit && tryCommit(ADD_CUSTOM_OPTION_TRIGGER.Blur);
53
+ }, [inputElementRef, tryCommit]);
54
+ const tryCommitOnBlur = useCallback((event) => {
55
+ if (skipBlurCommitRef.current) {
56
+ skipBlurCommitRef.current = false;
57
+ return 'skipped';
58
+ }
59
+ if (isCustomOptionBlurInsideField(event.relatedTarget, [
60
+ listRef.current,
61
+ clearButtonRef.current,
62
+ copyButtonRef.current,
63
+ ...(footerActiveElementsRefs?.map(ref => ref.current) ?? []),
64
+ ])) {
65
+ return 'inside';
66
+ }
67
+ return tryCommit(ADD_CUSTOM_OPTION_TRIGGER.Blur) ? 'committed' : 'skipped';
68
+ }, [clearButtonRef, copyButtonRef, footerActiveElementsRefs, tryCommit]);
69
+ const tryCommitFromKeyboard = useCallback((event) => {
70
+ const trigger = getCustomOptionTriggerByKey(event.key);
71
+ return trigger !== undefined && tryCommit(trigger);
72
+ }, [tryCommit]);
73
+ const handleListSingleChange = useCallback((next) => {
74
+ skipCloseCommitRef.current = true;
75
+ commitSingle(next);
76
+ }, [commitSingle]);
77
+ const handleListMultipleChange = useCallback((next) => {
78
+ skipCloseCommitRef.current = true;
79
+ commitMultiple(next);
80
+ }, [commitMultiple]);
81
+ return {
82
+ listRef,
83
+ suppressCloseCommit,
84
+ enableCloseCommit,
85
+ tryCommitOnClose,
86
+ tryCommitOnBlur,
87
+ tryCommitFromKeyboard,
88
+ handleListSingleChange,
89
+ handleListMultipleChange,
90
+ };
91
+ }
@@ -4,9 +4,30 @@ import { Appearance as TagAppearance } from '@cloud-ru/ds-tag';
4
4
  import { ValueOf } from '@cloud-ru/ds-utils';
5
5
  import { FocusEvent, KeyboardEvent, ReactNode } from 'react';
6
6
  import { FieldLayoutPresets } from '../../hooks/index.js';
7
- import { SELECTION_MODE } from './constants.js';
7
+ import { ADD_CUSTOM_OPTION_TRIGGER, ADD_CUSTOM_OPTION_TRIGGERS_MULTIPLE_ALLOWED, ADD_CUSTOM_OPTION_TRIGGERS_SINGLE_ALLOWED, SELECTION_MODE } from './constants.js';
8
8
  /** Режим выбора FieldSelect: одно значение или несколько. */
9
9
  export type Selection = ValueOf<typeof SELECTION_MODE>;
10
+ /** Событие, по которому произвольный ввод фиксируется как выбранная опция. */
11
+ export type FieldSelectAddCustomOptionTrigger = ValueOf<typeof ADD_CUSTOM_OPTION_TRIGGER>;
12
+ /** Триггеры кастомной опции в режиме `single`. */
13
+ export type FieldSelectSingleAddCustomOptionTrigger = (typeof ADD_CUSTOM_OPTION_TRIGGERS_SINGLE_ALLOWED)[number];
14
+ /** Триггеры кастомной опции в режиме `multiple`. */
15
+ export type FieldSelectMultipleAddCustomOptionTrigger = (typeof ADD_CUSTOM_OPTION_TRIGGERS_MULTIPLE_ALLOWED)[number];
16
+ type CustomOptionProps<CustomOptionTrigger extends FieldSelectAddCustomOptionTrigger> = {
17
+ /**
18
+ * Разрешить фиксировать произвольный ввод из строки поиска как выбранную опцию
19
+ * (значение, которого нет в `items`).
20
+ * @default false
21
+ */
22
+ allowCustomOption?: boolean;
23
+ /**
24
+ * События, по которым произвольный ввод фиксируется как выбранная опция.
25
+ * Учитывается только при `allowCustomOption={true}`.
26
+ * Если не задан — используются все триггеры режима (`single`: enter, blur; `multiple`: enter, blur, space, comma).
27
+ * Триггеры, недоступные в текущем `selection`, игнорируются.
28
+ */
29
+ addCustomOptionTriggers?: CustomOptionTrigger[];
30
+ };
10
31
  type WithTagAppearance<T> = T extends {
11
32
  items: ItemProps[];
12
33
  } ? Omit<T, 'items'> & {
@@ -96,11 +117,6 @@ type CommonSelectProps = FieldSelectDecoratorProps & DroplistPassthrough & {
96
117
  * @default false
97
118
  */
98
119
  autocomplete?: boolean;
99
- /**
100
- * Зафиксировать введённый текст как новый выбор по `Enter` (создание опции «на лету»).
101
- * @default false
102
- */
103
- addOptionByEnter?: boolean;
104
120
  /**
105
121
  * Сбрасывать строку поиска к выбранному значению после выбора. `false` нужен при асинхронной
106
122
  * подгрузке (оставить введённый запрос как значение, пока данные не пришли).
@@ -154,7 +170,7 @@ type CommonSelectProps = FieldSelectDecoratorProps & DroplistPassthrough & {
154
170
  /** Тестовый id корня */
155
171
  'data-test-id'?: string;
156
172
  };
157
- export type FieldSelectSingleProps = CommonSelectProps & {
173
+ export type FieldSelectSingleProps = CommonSelectProps & CustomOptionProps<FieldSelectSingleAddCustomOptionTrigger> & {
158
174
  /** Режим выбора. По умолчанию `'single'`. */
159
175
  selection?: typeof SELECTION_MODE.Single;
160
176
  /** Управляемое значение. Пустая строка трактуется как «значение не выбрано». */
@@ -169,7 +185,7 @@ export type FieldSelectSingleProps = CommonSelectProps & {
169
185
  */
170
186
  closeDroplistOnItemClick?: boolean;
171
187
  };
172
- export type FieldSelectMultipleProps = CommonSelectProps & {
188
+ export type FieldSelectMultipleProps = CommonSelectProps & CustomOptionProps<FieldSelectMultipleAddCustomOptionTrigger> & {
173
189
  /** Режим выбора */
174
190
  selection: typeof SELECTION_MODE.Multiple;
175
191
  /** Управляемые значения */