@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
package/CHANGELOG.md CHANGED
@@ -3,6 +3,12 @@
3
3
  All notable changes to this project will be documented in this file.
4
4
  See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
5
 
6
+ # 3.0.0 (2026-10-16)
7
+
8
+ ### BREAKING CHANGES
9
+
10
+ - **IAM-7099:** remove deprecated addOptionByEnter, allow custom options in FieldSelect via configurable triggers ([b698db6](https://github.com/cloud-ru-tech/snack-v2/commit/b698db6a2276ad901d3bc489e1be885e37f5db34))
11
+
6
12
  ## 2.5.8 (2026-10-14)
7
13
 
8
14
  **Note:** Version bump only for package @ds/fields
package/README.md CHANGED
@@ -435,7 +435,8 @@ export function Select() {
435
435
 
436
436
  | Prop | Type | Default | Description |
437
437
  |------|------|---------|-------------|
438
- | `addOptionByEnter` | `boolean` | `false` | Зафиксировать введённый текст как новый выбор по `Enter` (создание опции «на лету»). |
438
+ | `addCustomOptionTriggers` | `("enter" \| "blur")[] \| ("enter" \| "blur" \| "space" \| "comma")[]` | — | События, по которым произвольный ввод фиксируется как выбранная опция. <br/> Учитывается только при `allowCustomOption={true}`. <br/> Если не задан — используются все триггеры режима (`single`: enter, blur; `multiple`: enter, blur, space, comma). <br/> Триггеры, недоступные в текущем `selection`, игнорируются. |
439
+ | `allowCustomOption` | `boolean` | `false` | Разрешить фиксировать произвольный ввод из строки поиска как выбранную опцию <br/> (значение, которого нет в `items`). |
439
440
  | `autoFocus` | `boolean` | — | Автофокус input при монтировании. На mobile выключается адаптивно (см. `layoutPresets`) |
440
441
  | `autocomplete` | `boolean` | `false` | Не фильтровать список на клиенте — фильтрацию обеспечивает потребитель (серверный поиск). <br/> Введённый текст уходит в `search.onChange`, список берётся из `items` как есть. |
441
442
  | `background` | `boolean` | `true` | Фон поля (acrylic) |
@@ -20,18 +20,24 @@ const constants_1 = require("../../constants");
20
20
  const hooks_1 = require("../../hooks");
21
21
  const shared_1 = require("../shared");
22
22
  const styles_module_scss_1 = __importDefault(require('../shared/styles.module.css'));
23
+ const hooks_2 = require("./hooks");
23
24
  const styles_module_scss_2 = __importDefault(require('./styles.module.css'));
24
25
  const utils_2 = require("./utils");
25
26
  exports.FieldSelect = (0, react_1.forwardRef)(function FieldSelect(props, ref) {
26
- const { label = '', labelTooltip, caption, hint, error, validationState = field_decorator_1.VALIDATION_STATE.Default, showHintIcon, length, required, size = field_decorator_1.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 = constants_1.TEST_IDS.fieldSelect, } = props;
27
+ const { label = '', labelTooltip, caption, hint, error, validationState = field_decorator_1.VALIDATION_STATE.Default, showHintIcon, length, required, size = field_decorator_1.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 = constants_1.TEST_IDS.fieldSelect, } = props;
27
28
  const multiple = (0, utils_2.isMultiple)(props);
28
29
  const chips = multiple ? (props.chips ?? true) : false;
29
30
  const removeByBackspace = multiple ? (props.removeByBackspace ?? true) : false;
30
31
  const closeDroplistOnItemClick = props.closeDroplistOnItemClick ?? !multiple;
32
+ const allowCustomOption = props.allowCustomOption === true;
33
+ const addCustomOptionTriggers = allowCustomOption ? props.addCustomOptionTriggers : undefined;
34
+ const onSingleChange = onChange;
35
+ const onMultipleChange = onChange;
31
36
  const resolvedAutoFocus = (0, hooks_1.useAdaptiveAutoFocus)(autoFocus, layoutPresets);
32
37
  const inputRef = (0, react_1.useRef)(null);
33
38
  // Отдельный ref на реальный <input>: `inputRef.current` перезаписывается span-обёрткой PopoverPrivate.
34
39
  const inputElementRef = (0, react_1.useRef)(null);
40
+ const restoreInputFocusRef = (0, react_1.useRef)(false);
35
41
  const clearButtonRef = (0, react_1.useRef)(null);
36
42
  const copyButtonRef = (0, react_1.useRef)(null);
37
43
  const contentRef = (0, react_1.useRef)(null);
@@ -48,41 +54,45 @@ exports.FieldSelect = (0, react_1.forwardRef)(function FieldSelect(props, ref) {
48
54
  // Controlled-режим «залипает»: иначе очистка через `value: undefined` откатится на локальный стейт.
49
55
  const singleControlled = (0, react_1.useRef)(false);
50
56
  const multipleControlled = (0, react_1.useRef)(false);
51
- if (!multiple && props.value !== undefined) {
57
+ if (!multiple && value !== undefined) {
52
58
  singleControlled.current = true;
53
59
  }
54
- if (multiple && Array.isArray(props.value)) {
60
+ if (multiple && Array.isArray(value)) {
55
61
  multipleControlled.current = true;
56
62
  }
57
63
  const singleValue = (0, react_1.useMemo)(() => {
58
64
  if (multiple) {
59
65
  return undefined;
60
66
  }
61
- const raw = singleControlled.current ? props.value : singleLocal;
67
+ const raw = singleControlled.current ? value : singleLocal;
62
68
  // `''` = «значение не выбрано»: формы отдают пустое значение строкой.
63
69
  return raw === '' ? undefined : raw;
64
- }, [multiple, props.value, singleLocal]);
70
+ }, [multiple, value, singleLocal]);
65
71
  const multipleValue = (0, react_1.useMemo)(() => {
66
72
  if (!multiple) {
67
73
  return [];
68
74
  }
69
75
  if (multipleControlled.current) {
70
- return Array.isArray(props.value) ? props.value : [];
76
+ return Array.isArray(value) ? value : [];
71
77
  }
72
78
  return multipleLocal;
73
- }, [multiple, props.value, multipleLocal]);
79
+ }, [multiple, value, multipleLocal]);
74
80
  const effectiveValidationState = (0, react_1.useMemo)(() => (error ? field_decorator_1.VALIDATION_STATE.Error : validationState), [error, validationState]);
75
81
  const allItems = (0, react_1.useMemo)(() => [...(pinTop ?? []), ...items, ...(pinBottom ?? [])], [items, pinTop, pinBottom]);
82
+ const selectedIds = (0, react_1.useMemo)(() => (0, utils_2.getSelectedIds)({ multiple, multipleValue, singleValue }), [multiple, multipleValue, singleValue]);
83
+ // Выбранное, которого нет в `items` (кастом по allowCustomOption, ленивая подгрузка) — в список, не только в чип.
84
+ const missingSelectedItems = (0, react_1.useMemo)(() => (0, utils_2.getMissingSelectedItems)(selectedIds, allItems), [selectedIds, allItems]);
85
+ const itemsWithPlaceholders = (0, react_1.useMemo)(() => (missingSelectedItems.length > 0 ? [...missingSelectedItems, ...items] : items), [missingSelectedItems, items]);
76
86
  // Выбранное значение переживает смену `items` (серверный поиск, ленивая подгрузка).
77
87
  const seenItems = (0, react_1.useRef)(new Map());
78
88
  const resolveItem = (0, react_1.useMemo)(() => {
79
- for (const item of (0, utils_2.flatten)(allItems)) {
89
+ for (const item of (0, utils_2.flatten)([...missingSelectedItems, ...allItems])) {
80
90
  if (item.id !== undefined) {
81
91
  seenItems.current.set(item.id, item);
82
92
  }
83
93
  }
84
- return (id) => (0, utils_2.findItem)(allItems, id) ?? seenItems.current.get(id);
85
- }, [allItems]);
94
+ return (id) => (0, utils_2.findItem)(allItems, id) ?? (0, utils_2.findItem)(missingSelectedItems, id) ?? seenItems.current.get(id);
95
+ }, [allItems, missingSelectedItems]);
86
96
  const selectedPairs = (0, react_1.useMemo)(() => {
87
97
  if (!multiple || multipleValue.length === 0) {
88
98
  return [];
@@ -99,6 +109,7 @@ exports.FieldSelect = (0, react_1.forwardRef)(function FieldSelect(props, ref) {
99
109
  });
100
110
  }, [multiple, multipleValue, resolveItem]);
101
111
  const formatPair = (0, react_1.useCallback)((pair) => (selectedOptionFormatter ? selectedOptionFormatter(pair) : pair.label), [selectedOptionFormatter]);
112
+ const formatSelected = 'formatSelected' in props && props.formatSelected;
102
113
  const selectedLabel = (0, react_1.useMemo)(() => {
103
114
  if (!multiple) {
104
115
  if (singleValue === undefined) {
@@ -111,11 +122,11 @@ exports.FieldSelect = (0, react_1.forwardRef)(function FieldSelect(props, ref) {
111
122
  if (chips) {
112
123
  return '';
113
124
  }
114
- if ('formatSelected' in props && props.formatSelected) {
115
- return props.formatSelected(selectedPairs);
125
+ if (formatSelected) {
126
+ return formatSelected(selectedPairs);
116
127
  }
117
128
  return selectedPairs.map(formatPair).join(', ');
118
- }, [multiple, singleValue, selectedPairs, chips, props, formatPair, resolveItem]);
129
+ }, [multiple, singleValue, selectedPairs, chips, formatSelected, formatPair, resolveItem]);
119
130
  const [localInput, setLocalInput] = (0, react_1.useState)(search?.defaultValue ?? selectedLabel);
120
131
  const inputValue = search?.value !== undefined ? search.value : localInput;
121
132
  const [typing, setTyping] = (0, react_1.useState)(false);
@@ -137,13 +148,13 @@ exports.FieldSelect = (0, react_1.forwardRef)(function FieldSelect(props, ref) {
137
148
  syncedLabelRef.current = selectedLabel;
138
149
  setInputValue(selectedLabel);
139
150
  }, [selectedLabel, typing, resetSearchOnOptionSelection, setInputValue]);
140
- // При autocomplete фильтрует сервер — items берутся как есть.
151
+ // При autocomplete фильтрует сервер — items берутся как есть, плюс выбранное вне списка.
141
152
  const filteredItems = (0, react_1.useMemo)(() => {
142
153
  if (!searchable || autocomplete || !typing) {
143
- return items;
154
+ return itemsWithPlaceholders;
144
155
  }
145
- return (0, utils_2.filterItems)(items, inputValue, enableFuzzySearch);
146
- }, [searchable, autocomplete, typing, items, inputValue, enableFuzzySearch]);
156
+ return (0, utils_2.filterItems)(itemsWithPlaceholders, inputValue, enableFuzzySearch);
157
+ }, [searchable, autocomplete, typing, itemsWithPlaceholders, inputValue, enableFuzzySearch]);
147
158
  const filteredPinTop = (0, react_1.useMemo)(() => {
148
159
  if (!searchable || autocomplete || !typing || !pinTop) {
149
160
  return pinTop;
@@ -156,47 +167,84 @@ exports.FieldSelect = (0, react_1.forwardRef)(function FieldSelect(props, ref) {
156
167
  }
157
168
  return (0, utils_2.filterItems)(pinBottom, inputValue, enableFuzzySearch);
158
169
  }, [searchable, autocomplete, typing, pinBottom, inputValue, enableFuzzySearch]);
159
- const handleOpenChange = (0, react_1.useCallback)((next) => {
160
- // readonly/disabled поле открывать нельзя, закрывать — можно.
161
- if (next && (disabled || readOnly))
162
- return;
163
- if (openProp === undefined) {
164
- setOpenLocal(next);
165
- }
166
- onOpenChange?.(next);
167
- if (!next) {
168
- setTyping(false);
169
- if (resetSearchOnOptionSelection) {
170
- setInputValue(selectedLabel);
171
- }
172
- }
173
- }, [openProp, onOpenChange, disabled, readOnly, resetSearchOnOptionSelection, setInputValue, selectedLabel]);
174
- const handleSingleChange = (next) => {
170
+ const handleSingleChange = (0, react_1.useCallback)((next) => {
175
171
  if (multiple) {
176
172
  return;
177
173
  }
178
- if (props.value === undefined) {
174
+ if (value === undefined) {
179
175
  setSingleLocal(next);
180
176
  }
181
- props.onChange?.(next);
177
+ onSingleChange?.(next);
182
178
  setTyping(false);
183
- };
184
- const handleMultipleChange = (next) => {
179
+ }, [multiple, value, onSingleChange]);
180
+ const restoreInputFocus = (0, react_1.useCallback)(() => {
181
+ restoreInputFocusRef.current = (0, utils_1.isBrowser)() && inputElementRef.current === document.activeElement;
182
+ }, []);
183
+ const handleMultipleChange = (0, react_1.useCallback)((next) => {
185
184
  if (!multiple) {
186
185
  return;
187
186
  }
188
- if (props.value === undefined) {
187
+ restoreInputFocus();
188
+ if (value === undefined) {
189
189
  setMultipleLocal(next);
190
190
  }
191
- props.onChange?.(next);
191
+ onMultipleChange?.(next);
192
192
  if (searchable) {
193
193
  setTyping(false);
194
194
  if (resetSearchOnOptionSelection) {
195
195
  setInputValue('');
196
196
  }
197
197
  }
198
- };
198
+ }, [multiple, onMultipleChange, value, searchable, resetSearchOnOptionSelection, setInputValue, restoreInputFocus]);
199
+ const resetCustomOptionSearch = (0, react_1.useCallback)(() => {
200
+ setTyping(false);
201
+ if (resetSearchOnOptionSelection) {
202
+ setInputValue(multiple ? '' : selectedLabel);
203
+ }
204
+ }, [resetSearchOnOptionSelection, setInputValue, multiple, selectedLabel]);
205
+ const { listRef, suppressCloseCommit, enableCloseCommit, tryCommitOnClose, tryCommitOnBlur, tryCommitFromKeyboard, handleListSingleChange, handleListMultipleChange, } = (0, hooks_2.useCustomOption)({
206
+ allowCustomOption,
207
+ addCustomOptionTriggers,
208
+ multiple,
209
+ inputValue,
210
+ typing,
211
+ multipleValue,
212
+ commitSingle: handleSingleChange,
213
+ commitMultiple: handleMultipleChange,
214
+ resetSearch: resetCustomOptionSearch,
215
+ inputElementRef,
216
+ clearButtonRef,
217
+ copyButtonRef,
218
+ footerActiveElementsRefs,
219
+ });
220
+ const handleOpenChange = (0, react_1.useCallback)((next) => {
221
+ // readonly/disabled поле открывать нельзя, закрывать — можно.
222
+ if (next && (disabled || readOnly))
223
+ return;
224
+ if (openProp === undefined) {
225
+ setOpenLocal(next);
226
+ }
227
+ onOpenChange?.(next);
228
+ if (!next) {
229
+ setTyping(false);
230
+ const committed = tryCommitOnClose();
231
+ // Кастомная опция не зафиксирована — вернуть лейбл выбранного значения.
232
+ if (resetSearchOnOptionSelection && !committed) {
233
+ setInputValue(selectedLabel);
234
+ }
235
+ }
236
+ }, [
237
+ openProp,
238
+ onOpenChange,
239
+ disabled,
240
+ readOnly,
241
+ resetSearchOnOptionSelection,
242
+ setInputValue,
243
+ selectedLabel,
244
+ tryCommitOnClose,
245
+ ]);
199
246
  const handleInputChange = (next) => {
247
+ enableCloseCommit();
200
248
  setInputValue(next);
201
249
  setTyping(true);
202
250
  if (!open) {
@@ -207,16 +255,16 @@ exports.FieldSelect = (0, react_1.forwardRef)(function FieldSelect(props, ref) {
207
255
  if (multiple) {
208
256
  // Отключённые выбранные значения остаются при очистке (паритет с легаси).
209
257
  const keepDisabled = selectedPairs.filter(pair => pair.disabled).map(pair => pair.id);
210
- if (props.value === undefined) {
258
+ if (value === undefined) {
211
259
  setMultipleLocal(keepDisabled);
212
260
  }
213
- props.onChange?.(keepDisabled);
261
+ onMultipleChange?.(keepDisabled);
214
262
  }
215
263
  else {
216
- if (props.value === undefined) {
264
+ if (value === undefined) {
217
265
  setSingleLocal(undefined);
218
266
  }
219
- props.onChange?.(undefined);
267
+ onSingleChange?.(undefined);
220
268
  }
221
269
  setInputValue('');
222
270
  setTyping(false);
@@ -225,7 +273,17 @@ exports.FieldSelect = (0, react_1.forwardRef)(function FieldSelect(props, ref) {
225
273
  if (required && !open) {
226
274
  handleOpenChange(true);
227
275
  }
228
- }, [multiple, props, selectedPairs, setInputValue, required, open, handleOpenChange]);
276
+ }, [
277
+ multiple,
278
+ selectedPairs,
279
+ setInputValue,
280
+ required,
281
+ open,
282
+ handleOpenChange,
283
+ value,
284
+ onSingleChange,
285
+ onMultipleChange,
286
+ ]);
229
287
  const removeChip = (0, react_1.useCallback)((id) => {
230
288
  if (!multiple) {
231
289
  return;
@@ -235,11 +293,11 @@ exports.FieldSelect = (0, react_1.forwardRef)(function FieldSelect(props, ref) {
235
293
  return;
236
294
  }
237
295
  const next = multipleValue.filter(v => v !== id);
238
- if (props.value === undefined) {
296
+ if (value === undefined) {
239
297
  setMultipleLocal(next);
240
298
  }
241
- props.onChange?.(next);
242
- }, [multiple, multipleValue, props, selectedPairs]);
299
+ onMultipleChange?.(next);
300
+ }, [multiple, multipleValue, selectedPairs, value, onMultipleChange]);
243
301
  const handleRemoveChip = (0, react_1.useCallback)((id) => (e) => {
244
302
  e.stopPropagation();
245
303
  removeChip(id);
@@ -295,19 +353,12 @@ exports.FieldSelect = (0, react_1.forwardRef)(function FieldSelect(props, ref) {
295
353
  }
296
354
  if (event.key === 'Escape' && open) {
297
355
  event.preventDefault();
356
+ suppressCloseCommit();
298
357
  handleOpenChange(false);
299
358
  }
300
- if (addOptionByEnter && event.key === 'Enter' && inputValue !== '') {
301
- // Введённый текст становится новым значением (создание опции «на лету»).
359
+ if (tryCommitFromKeyboard(event)) {
302
360
  event.preventDefault();
303
- if (multiple) {
304
- if (!multipleValue.includes(inputValue)) {
305
- handleMultipleChange([...multipleValue, inputValue]);
306
- }
307
- }
308
- else {
309
- handleSingleChange(inputValue);
310
- }
361
+ event.stopPropagation();
311
362
  return;
312
363
  }
313
364
  if (event.key === 'Enter' && !open) {
@@ -318,6 +369,12 @@ exports.FieldSelect = (0, react_1.forwardRef)(function FieldSelect(props, ref) {
318
369
  event.preventDefault();
319
370
  const last = multipleValue[multipleValue.length - 1];
320
371
  removeChip(last);
372
+ restoreInputFocus();
373
+ }
374
+ };
375
+ const handleTriggerKeyDownCapture = (event) => {
376
+ if (event.key === 'Escape') {
377
+ suppressCloseCommit();
321
378
  }
322
379
  };
323
380
  const handleTriggerMouseEnter = (0, react_1.useCallback)(() => {
@@ -344,14 +401,28 @@ exports.FieldSelect = (0, react_1.forwardRef)(function FieldSelect(props, ref) {
344
401
  }
345
402
  onFocusProp?.(event);
346
403
  }, [searchable, onFocusProp]);
347
- const handleInputBlur = (0, react_1.useCallback)((event) => {
404
+ const handleInputBlur = (event) => {
348
405
  setFocusVisible(false);
406
+ const blurResult = tryCommitOnBlur(event);
407
+ // Закрытый список не получит onOpenChange — вернуть лейбл выбранного значения.
408
+ // Клик по айтему открытого списка даёт relatedTarget === null, восстановление делает закрытие.
409
+ if (resetSearchOnOptionSelection && blurResult === 'skipped' && (!open || event.relatedTarget !== null)) {
410
+ setTyping(false);
411
+ setInputValue(selectedLabel);
412
+ }
349
413
  onBlurProp?.(event);
350
- }, [onBlurProp]);
414
+ };
351
415
  const droplistSelection = multiple
352
- ? { mode: 'multiple', value: multipleValue, onChange: handleMultipleChange }
353
- : { mode: 'single', value: singleValue, onChange: handleSingleChange };
416
+ ? { mode: 'multiple', value: multipleValue, onChange: handleListMultipleChange }
417
+ : { mode: 'single', value: singleValue, onChange: handleListSingleChange };
354
418
  const hasChips = chips && selectedPairs.length > 0;
419
+ (0, utils_1.useLayoutEffect)(() => {
420
+ if (!restoreInputFocusRef.current) {
421
+ return;
422
+ }
423
+ restoreInputFocusRef.current = false;
424
+ inputElementRef.current?.focus();
425
+ }, [multipleValue.length]);
355
426
  // minWidth поискового input'а = ширина введённого текста (`.inputPlug`), но не больше строки чипов.
356
427
  // Замер до paint, иначе input мигает при вводе.
357
428
  (0, utils_1.useLayoutEffect)(() => {
@@ -364,11 +435,11 @@ exports.FieldSelect = (0, react_1.forwardRef)(function FieldSelect(props, ref) {
364
435
  setChipInputMinWidth(Math.min(content, Math.max(plug, SEARCH_INPUT_PLUG_MIN_WIDTH)));
365
436
  }, [hasChips, inputValue, selectedPairs.length]);
366
437
  const searchInputField = ((0, jsx_runtime_1.jsx)(input_private_1.InputPrivate, { ref: (0, merge_refs_1.default)(ref, inputRef, inputElementRef), className: (0, classnames_1.default)(styles_module_scss_1.default.fieldInput, !searchable && styles_module_scss_2.default.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": constants_1.TEST_IDS.fieldSelectInput }));
367
- const searchInput = hasChips ? ((0, jsx_runtime_1.jsx)("div", { className: styles_module_scss_2.default.inputWrapper, style: { minWidth: chipInputMinWidth }, children: searchInputField })) : ((0, jsx_runtime_1.jsx)("div", { className: styles_module_scss_1.default.inputArea, children: searchInputField }));
438
+ const searchInput = hasChips ? ((0, jsx_runtime_1.jsx)("div", { className: styles_module_scss_2.default.inputWrapper, style: { minWidth: chipInputMinWidth }, children: searchInputField }, 'search-input')) : ((0, jsx_runtime_1.jsx)("div", { className: styles_module_scss_1.default.inputArea, children: searchInputField }));
368
439
  const trigger = (
369
440
  // Focusable-элемент — InputPrivate внутри, обёртка только собирает combobox.
370
441
  // eslint-disable-next-line jsx-a11y/no-static-element-interactions
371
- (0, jsx_runtime_1.jsxs)("div", { className: (0, classnames_1.default)(styles_module_scss_1.default.fieldWrapper, styles_module_scss_2.default.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: [(0, jsx_runtime_1.jsxs)("div", { className: styles_module_scss_1.default.backgroundWrapper, children: [(0, jsx_runtime_1.jsx)("div", { className: styles_module_scss_1.default.materialLayer, ...(0, shared_1.getAcrylicProps)({
442
+ (0, jsx_runtime_1.jsxs)("div", { className: (0, classnames_1.default)(styles_module_scss_1.default.fieldWrapper, styles_module_scss_2.default.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: [(0, jsx_runtime_1.jsxs)("div", { className: styles_module_scss_1.default.backgroundWrapper, children: [(0, jsx_runtime_1.jsx)("div", { className: styles_module_scss_1.default.materialLayer, ...(0, shared_1.getAcrylicProps)({
372
443
  validationState: effectiveValidationState,
373
444
  disabled,
374
445
  readonly: readOnly,
@@ -377,5 +448,5 @@ exports.FieldSelect = (0, react_1.forwardRef)(function FieldSelect(props, ref) {
377
448
  }), children: (0, jsx_runtime_1.jsx)("div", { className: styles_module_scss_1.default.acrylicBg, "aria-hidden": true }) }), (0, jsx_runtime_1.jsx)("div", { className: styles_module_scss_1.default.borderStateLayer, "data-state": 'borderOnBackground' }), (0, jsx_runtime_1.jsx)("div", { className: styles_module_scss_1.default.focusLayer })] }), (0, jsx_runtime_1.jsx)("div", { className: styles_module_scss_1.default.fieldContainer, children: (0, jsx_runtime_1.jsxs)("div", { className: styles_module_scss_1.default.contentWrapper, children: [iconBefore && (0, jsx_runtime_1.jsx)("div", { className: styles_module_scss_1.default.iconSlot, children: iconBefore }), (0, jsx_runtime_1.jsxs)("div", { className: styles_module_scss_1.default.inputLine, children: [prefix && (0, jsx_runtime_1.jsx)("span", { className: styles_module_scss_1.default.prefix, children: prefix }), hasChips ? ((0, jsx_runtime_1.jsxs)("div", { className: styles_module_scss_2.default.chipsRow, ref: contentRef, "data-test-id": constants_1.TEST_IDS.fieldSelectChips, children: [selectedPairs.map(pair => ((0, jsx_runtime_1.jsx)(tag_1.Tag, { label: formatPair(pair), size: utils_2.TAG_SIZE_MAP[size], appearance: pair.appearance ?? 'neutral', onDelete: disabled || readOnly || pair.disabled ? undefined : handleRemoveChip(pair.id) }, String(pair.id)))), searchInput, (0, jsx_runtime_1.jsx)("span", { ref: inputPlugRef, className: styles_module_scss_2.default.inputPlug, "aria-hidden": true, children: inputValue })] })) : (searchInput), postfixButtons && (
378
449
  // eslint-disable-next-line jsx-a11y/no-static-element-interactions
379
450
  (0, jsx_runtime_1.jsx)("span", { className: styles_module_scss_1.default.postfixButtonsSlot, onMouseDown: shared_1.preventSlotMouseDown, onClick: shared_1.stopSlotClickPropagation, children: postfixButtons })), postfix && (0, jsx_runtime_1.jsx)("span", { className: styles_module_scss_1.default.postfix, children: postfix })] }), (0, jsx_runtime_1.jsx)("div", { className: styles_module_scss_1.default.iconSlot, children: (0, jsx_runtime_1.jsx)("span", { className: styles_module_scss_2.default.chevron, "data-open": open || undefined, "aria-hidden": true, children: (0, jsx_runtime_1.jsx)(system_1.ChevronDownSVG, {}) }) })] }) })] }));
380
- return ((0, jsx_runtime_1.jsx)(field_decorator_1.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: (0, jsx_runtime_1.jsx)(list_1.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": constants_1.TEST_IDS.fieldSelectList, children: trigger }) }));
451
+ return ((0, jsx_runtime_1.jsx)(field_decorator_1.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: (0, jsx_runtime_1.jsx)(list_1.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": constants_1.TEST_IDS.fieldSelectList, children: trigger }) }));
381
452
  });
@@ -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"];
@@ -1,7 +1,38 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SELECTION_MODE = void 0;
3
+ exports.ADD_CUSTOM_OPTION_TRIGGERS_MULTIPLE_DEFAULT = exports.ADD_CUSTOM_OPTION_TRIGGERS_MULTIPLE_ALLOWED = exports.ADD_CUSTOM_OPTION_TRIGGERS_SINGLE_DEFAULT = exports.ADD_CUSTOM_OPTION_TRIGGERS_SINGLE_ALLOWED = exports.ADD_CUSTOM_OPTION_TRIGGER = exports.SELECTION_MODE = void 0;
4
4
  exports.SELECTION_MODE = {
5
5
  Single: 'single',
6
6
  Multiple: 'multiple',
7
7
  };
8
+ /** События, по которым произвольный ввод фиксируется как выбранная опция. */
9
+ exports.ADD_CUSTOM_OPTION_TRIGGER = {
10
+ Enter: 'enter',
11
+ Blur: 'blur',
12
+ Space: 'space',
13
+ Comma: 'comma',
14
+ };
15
+ /** Разрешенные триггеры для `selection='single'` при `allowCustomOption`. */
16
+ exports.ADD_CUSTOM_OPTION_TRIGGERS_SINGLE_ALLOWED = [
17
+ exports.ADD_CUSTOM_OPTION_TRIGGER.Enter,
18
+ exports.ADD_CUSTOM_OPTION_TRIGGER.Blur,
19
+ ];
20
+ /** Триггеры по умолчанию для `selection='single'` при `allowCustomOption`. */
21
+ exports.ADD_CUSTOM_OPTION_TRIGGERS_SINGLE_DEFAULT = [
22
+ exports.ADD_CUSTOM_OPTION_TRIGGER.Enter,
23
+ exports.ADD_CUSTOM_OPTION_TRIGGER.Blur,
24
+ ];
25
+ /** Разрешенные триггеры для `selection='multiple'` при `allowCustomOption`. */
26
+ exports.ADD_CUSTOM_OPTION_TRIGGERS_MULTIPLE_ALLOWED = [
27
+ exports.ADD_CUSTOM_OPTION_TRIGGER.Enter,
28
+ exports.ADD_CUSTOM_OPTION_TRIGGER.Blur,
29
+ exports.ADD_CUSTOM_OPTION_TRIGGER.Space,
30
+ exports.ADD_CUSTOM_OPTION_TRIGGER.Comma,
31
+ ];
32
+ /** Триггеры по умолчанию для `selection='multiple'` при `allowCustomOption`. */
33
+ exports.ADD_CUSTOM_OPTION_TRIGGERS_MULTIPLE_DEFAULT = [
34
+ exports.ADD_CUSTOM_OPTION_TRIGGER.Enter,
35
+ exports.ADD_CUSTOM_OPTION_TRIGGER.Blur,
36
+ exports.ADD_CUSTOM_OPTION_TRIGGER.Space,
37
+ exports.ADD_CUSTOM_OPTION_TRIGGER.Comma,
38
+ ];
@@ -0,0 +1,32 @@
1
+ import { ItemId } from '@cloud-ru/ds-list';
2
+ import { FocusEvent, KeyboardEvent, RefObject } from 'react';
3
+ import { FieldSelectAddCustomOptionTrigger } from './types';
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,94 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.useCustomOption = useCustomOption;
4
+ const utils_1 = require("@cloud-ru/ds-utils");
5
+ const react_1 = require("react");
6
+ const constants_1 = require("./constants");
7
+ const utils_2 = require("./utils");
8
+ /** Фиксация произвольного ввода как выбранной опции: триггеры, blur, закрытие списка. */
9
+ function useCustomOption({ allowCustomOption, addCustomOptionTriggers, multiple, inputValue, typing, multipleValue, commitSingle, commitMultiple, resetSearch, inputElementRef, clearButtonRef, copyButtonRef, footerActiveElementsRefs, }) {
10
+ const listRef = (0, react_1.useRef)(null);
11
+ const skipCloseCommitRef = (0, react_1.useRef)(false);
12
+ const skipBlurCommitRef = (0, react_1.useRef)(false);
13
+ const resolvedTriggers = (0, react_1.useMemo)(() => (0, utils_2.resolveAddCustomOptionTriggers)({
14
+ allowCustomOption,
15
+ addCustomOptionTriggers,
16
+ multiple,
17
+ }), [allowCustomOption, addCustomOptionTriggers, multiple]);
18
+ const tryCommit = (0, react_1.useCallback)((trigger) => {
19
+ if (!typing || !(0, utils_2.shouldHandleCustomOptionTrigger)(trigger, resolvedTriggers) || inputValue === '') {
20
+ return false;
21
+ }
22
+ if (multiple) {
23
+ if (multipleValue.includes(inputValue)) {
24
+ resetSearch();
25
+ }
26
+ else {
27
+ commitMultiple([...multipleValue, inputValue]);
28
+ }
29
+ }
30
+ else {
31
+ commitSingle(inputValue);
32
+ }
33
+ return true;
34
+ }, [typing, resolvedTriggers, inputValue, multiple, multipleValue, commitMultiple, commitSingle, resetSearch]);
35
+ const suppressCloseCommit = (0, react_1.useCallback)(() => {
36
+ skipCloseCommitRef.current = true;
37
+ skipBlurCommitRef.current = true;
38
+ }, []);
39
+ const enableCloseCommit = (0, react_1.useCallback)(() => {
40
+ skipCloseCommitRef.current = false;
41
+ skipBlurCommitRef.current = false;
42
+ }, []);
43
+ const tryCommitOnClose = (0, react_1.useCallback)(() => {
44
+ const skipped = skipCloseCommitRef.current;
45
+ const shouldCommit = (0, utils_2.shouldCommitCustomOptionOnClose)({
46
+ skip: skipped,
47
+ inputElement: inputElementRef.current,
48
+ activeElement: (0, utils_1.isBrowser)() ? document.activeElement : null,
49
+ });
50
+ if (skipped) {
51
+ queueMicrotask(() => {
52
+ skipCloseCommitRef.current = false;
53
+ });
54
+ }
55
+ return shouldCommit && tryCommit(constants_1.ADD_CUSTOM_OPTION_TRIGGER.Blur);
56
+ }, [inputElementRef, tryCommit]);
57
+ const tryCommitOnBlur = (0, react_1.useCallback)((event) => {
58
+ if (skipBlurCommitRef.current) {
59
+ skipBlurCommitRef.current = false;
60
+ return 'skipped';
61
+ }
62
+ if ((0, utils_2.isCustomOptionBlurInsideField)(event.relatedTarget, [
63
+ listRef.current,
64
+ clearButtonRef.current,
65
+ copyButtonRef.current,
66
+ ...(footerActiveElementsRefs?.map(ref => ref.current) ?? []),
67
+ ])) {
68
+ return 'inside';
69
+ }
70
+ return tryCommit(constants_1.ADD_CUSTOM_OPTION_TRIGGER.Blur) ? 'committed' : 'skipped';
71
+ }, [clearButtonRef, copyButtonRef, footerActiveElementsRefs, tryCommit]);
72
+ const tryCommitFromKeyboard = (0, react_1.useCallback)((event) => {
73
+ const trigger = (0, utils_2.getCustomOptionTriggerByKey)(event.key);
74
+ return trigger !== undefined && tryCommit(trigger);
75
+ }, [tryCommit]);
76
+ const handleListSingleChange = (0, react_1.useCallback)((next) => {
77
+ skipCloseCommitRef.current = true;
78
+ commitSingle(next);
79
+ }, [commitSingle]);
80
+ const handleListMultipleChange = (0, react_1.useCallback)((next) => {
81
+ skipCloseCommitRef.current = true;
82
+ commitMultiple(next);
83
+ }, [commitMultiple]);
84
+ return {
85
+ listRef,
86
+ suppressCloseCommit,
87
+ enableCloseCommit,
88
+ tryCommitOnClose,
89
+ tryCommitOnBlur,
90
+ tryCommitFromKeyboard,
91
+ handleListSingleChange,
92
+ handleListMultipleChange,
93
+ };
94
+ }