@cloud-ru/ds-fields 2.2.3-preview-a0540d7f.0 → 2.2.4

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 (77) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/README.md +1 -3
  3. package/dist/cjs/components/FieldDate/FieldDate.js +3 -3
  4. package/dist/cjs/components/FieldDate/mask.d.ts +3 -2
  5. package/dist/cjs/components/FieldDate/mask.js +4 -3
  6. package/dist/cjs/components/FieldSelect/FieldSelect.js +43 -98
  7. package/dist/cjs/components/FieldSelect/constants.d.ts +0 -11
  8. package/dist/cjs/components/FieldSelect/constants.js +1 -20
  9. package/dist/cjs/components/FieldSelect/types.d.ts +3 -26
  10. package/dist/cjs/components/FieldSelect/utils.d.ts +19 -0
  11. package/dist/cjs/components/FieldSelect/utils.js +103 -0
  12. package/dist/cjs/components/FieldTime/FieldTime.js +2 -2
  13. package/dist/cjs/segments/useSegmentedMask.d.ts +2 -0
  14. package/dist/cjs/segments/useSegmentedMask.js +145 -56
  15. package/dist/esm/components/FieldDate/FieldDate.js +3 -3
  16. package/dist/esm/components/FieldDate/mask.d.ts +3 -2
  17. package/dist/esm/components/FieldDate/mask.js +4 -3
  18. package/dist/esm/components/FieldSelect/FieldSelect.js +45 -100
  19. package/dist/esm/components/FieldSelect/constants.d.ts +0 -11
  20. package/dist/esm/components/FieldSelect/constants.js +0 -19
  21. package/dist/esm/components/FieldSelect/types.d.ts +3 -26
  22. package/dist/esm/components/FieldSelect/utils.d.ts +19 -0
  23. package/dist/esm/components/FieldSelect/utils.js +92 -0
  24. package/dist/esm/components/FieldTime/FieldTime.js +2 -2
  25. package/dist/esm/segments/useSegmentedMask.d.ts +2 -0
  26. package/dist/esm/segments/useSegmentedMask.js +145 -56
  27. package/dist/tsconfig.cjs.tsbuildinfo +1 -1
  28. package/dist/tsconfig.esm.tsbuildinfo +1 -1
  29. package/package.json +20 -20
  30. package/src/components/FieldDate/FieldDate.tsx +3 -3
  31. package/src/components/FieldDate/mask.ts +4 -3
  32. package/src/components/FieldSelect/FieldSelect.tsx +63 -151
  33. package/src/components/FieldSelect/constants.ts +0 -22
  34. package/src/components/FieldSelect/types.ts +48 -82
  35. package/src/components/FieldSelect/utils.ts +132 -0
  36. package/src/components/FieldTime/FieldTime.tsx +2 -2
  37. package/src/segments/useSegmentedMask.ts +171 -52
  38. package/dist/cjs/components/FieldSelect/hooks.d.ts +0 -33
  39. package/dist/cjs/components/FieldSelect/hooks.js +0 -95
  40. package/dist/cjs/components/FieldSelect/utils/customOption.d.ts +0 -21
  41. package/dist/cjs/components/FieldSelect/utils/customOption.js +0 -55
  42. package/dist/cjs/components/FieldSelect/utils/extract.d.ts +0 -11
  43. package/dist/cjs/components/FieldSelect/utils/extract.js +0 -39
  44. package/dist/cjs/components/FieldSelect/utils/filter.d.ts +0 -3
  45. package/dist/cjs/components/FieldSelect/utils/filter.js +0 -40
  46. package/dist/cjs/components/FieldSelect/utils/index.d.ts +0 -6
  47. package/dist/cjs/components/FieldSelect/utils/index.js +0 -22
  48. package/dist/cjs/components/FieldSelect/utils/items.d.ts +0 -9
  49. package/dist/cjs/components/FieldSelect/utils/items.js +0 -47
  50. package/dist/cjs/components/FieldSelect/utils/selection.d.ts +0 -11
  51. package/dist/cjs/components/FieldSelect/utils/selection.js +0 -18
  52. package/dist/cjs/components/FieldSelect/utils/tagSize.d.ts +0 -4
  53. package/dist/cjs/components/FieldSelect/utils/tagSize.js +0 -5
  54. package/dist/esm/components/FieldSelect/hooks.d.ts +0 -33
  55. package/dist/esm/components/FieldSelect/hooks.js +0 -92
  56. package/dist/esm/components/FieldSelect/utils/customOption.d.ts +0 -21
  57. package/dist/esm/components/FieldSelect/utils/customOption.js +0 -48
  58. package/dist/esm/components/FieldSelect/utils/extract.d.ts +0 -11
  59. package/dist/esm/components/FieldSelect/utils/extract.js +0 -34
  60. package/dist/esm/components/FieldSelect/utils/filter.d.ts +0 -3
  61. package/dist/esm/components/FieldSelect/utils/filter.js +0 -36
  62. package/dist/esm/components/FieldSelect/utils/index.d.ts +0 -6
  63. package/dist/esm/components/FieldSelect/utils/index.js +0 -6
  64. package/dist/esm/components/FieldSelect/utils/items.d.ts +0 -9
  65. package/dist/esm/components/FieldSelect/utils/items.js +0 -41
  66. package/dist/esm/components/FieldSelect/utils/selection.d.ts +0 -11
  67. package/dist/esm/components/FieldSelect/utils/selection.js +0 -14
  68. package/dist/esm/components/FieldSelect/utils/tagSize.d.ts +0 -4
  69. package/dist/esm/components/FieldSelect/utils/tagSize.js +0 -2
  70. package/src/components/FieldSelect/hooks.ts +0 -177
  71. package/src/components/FieldSelect/utils/customOption.ts +0 -77
  72. package/src/components/FieldSelect/utils/extract.ts +0 -49
  73. package/src/components/FieldSelect/utils/filter.ts +0 -51
  74. package/src/components/FieldSelect/utils/index.ts +0 -6
  75. package/src/components/FieldSelect/utils/items.ts +0 -58
  76. package/src/components/FieldSelect/utils/selection.ts +0 -25
  77. package/src/components/FieldSelect/utils/tagSize.ts +0 -5
@@ -0,0 +1,132 @@
1
+ import { Size } from '@cloud-ru/ds-field-decorator';
2
+ import { ItemId } from '@cloud-ru/ds-list';
3
+ import { Appearance as TagAppearance, Size as TagSize } from '@cloud-ru/ds-tag';
4
+
5
+ import { SELECTION_MODE } from './constants';
6
+ import { FieldSelectItem, FieldSelectMultipleProps, FieldSelectProps } from './types';
7
+
8
+ export const TAG_SIZE_MAP: Record<Size, TagSize> = { s: 'xs', m: 'xs', l: 's' };
9
+
10
+ export type WithIdContent = { id?: ItemId; content?: unknown; disabled?: boolean; appearance?: TagAppearance };
11
+
12
+ export function extractLabel(item: WithIdContent): string {
13
+ const { content, id } = item;
14
+
15
+ if (!content) {
16
+ return String(id ?? '');
17
+ }
18
+
19
+ if (typeof content === 'string' || typeof content === 'number') {
20
+ return String(content);
21
+ }
22
+
23
+ if (typeof content === 'object' && content !== null && 'label' in content) {
24
+ return String((content as { label: unknown }).label);
25
+ }
26
+
27
+ return String(id ?? '');
28
+ }
29
+
30
+ // Текст для поиска: лейбл (option) + caption + description — паритет с легаси `useSearch`,
31
+ // который матчил запрос по всем трём полям контента, а не только по лейблу.
32
+ export function extractSearchText(item: WithIdContent): string {
33
+ const parts = [extractLabel(item)];
34
+ const { content } = item;
35
+
36
+ if (content && typeof content === 'object') {
37
+ const c = content as { caption?: unknown; description?: unknown };
38
+
39
+ if (typeof c.caption === 'string') {
40
+ parts.push(c.caption);
41
+ }
42
+
43
+ if (typeof c.description === 'string') {
44
+ parts.push(c.description);
45
+ }
46
+ }
47
+
48
+ return parts.join(' ');
49
+ }
50
+
51
+ // Цвет тега выбранного значения (multiple) — паритет с легаси `option.appearance`.
52
+ // Проверка типа нужна и при типизированном поле: items часто приходят из ответа бэкенда.
53
+ export function extractAppearance(item?: WithIdContent): TagAppearance | undefined {
54
+ return typeof item?.appearance === 'string' ? item.appearance : undefined;
55
+ }
56
+
57
+ export function flatten(items: FieldSelectItem[]): WithIdContent[] {
58
+ const out: WithIdContent[] = [];
59
+
60
+ for (const item of items) {
61
+ out.push(item as WithIdContent);
62
+
63
+ if ('items' in item && Array.isArray(item.items)) {
64
+ out.push(...flatten(item.items as FieldSelectItem[]));
65
+ }
66
+ }
67
+
68
+ return out;
69
+ }
70
+
71
+ export function findItem(items: FieldSelectItem[], id: ItemId): WithIdContent | undefined {
72
+ for (const item of flatten(items)) {
73
+ if (item.id === id) {
74
+ return item;
75
+ }
76
+ }
77
+
78
+ return undefined;
79
+ }
80
+
81
+ // Subsequence-fuzzy: символы запроса должны встречаться в строке в исходном порядке.
82
+ // Пример: query=`lge` matches `Large` (L → r → arg → e).
83
+ export function isFuzzyMatch(haystack: string, needle: string): boolean {
84
+ if (!needle) {
85
+ return true;
86
+ }
87
+
88
+ let i = 0;
89
+
90
+ for (const ch of haystack) {
91
+ if (ch === needle[i]) {
92
+ i += 1;
93
+
94
+ if (i === needle.length) {
95
+ return true;
96
+ }
97
+ }
98
+ }
99
+
100
+ return false;
101
+ }
102
+
103
+ export function filterItems(items: FieldSelectItem[], query: string, fuzzy: boolean): FieldSelectItem[] {
104
+ if (!query) {
105
+ return items;
106
+ }
107
+
108
+ const q = query.toLowerCase();
109
+
110
+ const matches = (item: FieldSelectItem): boolean => {
111
+ const text = extractSearchText(item as WithIdContent).toLowerCase();
112
+
113
+ return fuzzy ? isFuzzyMatch(text, q) : text.includes(q);
114
+ };
115
+
116
+ const walk = (list: FieldSelectItem[]): FieldSelectItem[] =>
117
+ list.flatMap(item => {
118
+ if ('items' in item && Array.isArray(item.items)) {
119
+ const filteredChildren = walk(item.items as FieldSelectItem[]);
120
+
121
+ return filteredChildren.length > 0 ? [{ ...item, items: filteredChildren } as FieldSelectItem] : [];
122
+ }
123
+
124
+ return matches(item) ? [item] : [];
125
+ });
126
+
127
+ return walk(items);
128
+ }
129
+
130
+ export function isMultiple(props: FieldSelectProps): props is FieldSelectMultipleProps {
131
+ return props.selection === SELECTION_MODE.Multiple;
132
+ }
@@ -267,7 +267,7 @@ export const FieldTime = forwardRef<HTMLInputElement, FieldTimeProps>(function F
267
267
  [onInputKeyDown, timeSeg],
268
268
  );
269
269
 
270
- // value ведёт сегментный движок (keydown); нативный onChange input'а игнорируем.
270
+ // value ведёт сегментный движок (useSegmentedMask); нативный onChange input'а игнорируем.
271
271
  const handleInputChange = useCallback(() => undefined, []);
272
272
 
273
273
  const handleInputFocus = useCallback(
@@ -323,7 +323,7 @@ export const FieldTime = forwardRef<HTMLInputElement, FieldTimeProps>(function F
323
323
  <div className={fieldStyles.inputLine}>
324
324
  <div className={fieldStyles.inputArea}>
325
325
  <InputPrivate
326
- ref={mergeRefs(ref, localRef)}
326
+ ref={mergeRefs(ref, localRef, timeSeg.nativeInputRef)}
327
327
  className={fieldStyles.fieldInput}
328
328
  value={inputValue}
329
329
  onChange={handleInputChange}
@@ -1,6 +1,19 @@
1
+ import { useEventHandler } from '@cloud-ru/ds-utils';
1
2
  import { ClipboardEvent, KeyboardEvent, MouseEvent, RefObject, useCallback, useRef } from 'react';
2
3
 
3
- import { SlotMeta } from './segments';
4
+ import { SegmentKey, SlotMeta } from './segments';
5
+
6
+ const RESET_TYPED_KEYS = new Set([
7
+ 'ArrowLeft',
8
+ 'ArrowRight',
9
+ 'ArrowUp',
10
+ 'ArrowDown',
11
+ 'Backspace',
12
+ 'Delete',
13
+ 'Enter',
14
+ 'Tab',
15
+ 'Escape',
16
+ ]);
4
17
 
5
18
  type UseSegmentedMaskParams = {
6
19
  inputRef: RefObject<HTMLInputElement | null>;
@@ -32,6 +45,7 @@ type UseSegmentedMaskParams = {
32
45
  * Сегментный ввод даты/времени (порт `useDateField` из @snack-uikit/fields). Каретка ходит по
33
46
  * сегментам (`setSelectionRange` подсвечивает текущий), цифры заполняют сегмент с авто-переходом,
34
47
  * стрелки двигают по сегментам, Backspace очищает сегмент до плейсхолдера.
48
+ * `nativeInputRef` передаётся в `ref` того же input'а: значение правится через нативные `beforeinput`/`input`.
35
49
  */
36
50
  export function useSegmentedMask({
37
51
  inputRef,
@@ -174,74 +188,71 @@ export function useSegmentedMask({
174
188
  [clearSlot, isValidDate, lastSlot, nextSlot, selectSlot, slots, tryToComplete],
175
189
  );
176
190
 
191
+ // Цифры сегмента храним отдельно от текста: по `01` в поле не отличить `1` от `0` + `1`.
192
+ const typedRef = useRef<{ key: SegmentKey; digits: string } | null>(null);
193
+ const resetTyped = useCallback(() => {
194
+ typedRef.current = null;
195
+ }, []);
196
+
177
197
  const typeDigit = useCallback(
178
198
  (slot: SlotMeta, key: string) => {
179
- const text = getSlotText(slot);
180
- const numberValue = Number(text) || 0;
181
- const digit = Number(key);
182
- const slotValue = parseInt(numberValue.toString() + key, 10) || 0;
183
- const valueLength = slotValue.toString().length;
184
199
  const maxLength = slot.max.toString().length;
185
- const isTheLastInput = /^0+$/.test(text) && maxLength === 2 && digit === 0;
186
-
187
- if (valueLength < maxLength) {
188
- if (slotValue || slotValue >= slot.min) {
189
- updateSlot(slot, slotValue);
190
- if (isTheLastInput) checkInputAndGoNext(slot);
191
- }
192
- if (slotValue * 10 > slot.max) {
193
- checkInputAndGoNext(slot);
194
- }
195
- } else if (valueLength > maxLength) {
196
- if (digit * 10 > slot.max) {
197
- updateSlot(slot, key);
198
- checkInputAndGoNext(slot);
199
- } else if (digit || digit >= slot.min) {
200
- updateSlot(slot, key);
201
- }
202
- } else if (slotValue <= slot.max) {
203
- updateSlot(slot, slotValue);
204
- checkInputAndGoNext(slot);
205
- } else if (digit * 10 > slot.max) {
206
- updateSlot(slot, key);
207
- checkInputAndGoNext(slot);
208
- } else if (digit || digit >= slot.min) {
209
- updateSlot(slot, key);
200
+ const prev = typedRef.current?.key === slot.key ? typedRef.current.digits : '';
201
+ const appended = prev + key;
202
+ const overflow = Number(appended) > slot.max;
203
+ const digits = overflow ? key : appended;
204
+ const value = Number(digits);
205
+ const complete = overflow || digits.length >= maxLength || value * 10 > slot.max;
206
+ const accepted = value >= slot.min;
207
+
208
+ if (accepted) updateSlot(slot, value);
209
+
210
+ if (!complete) {
211
+ typedRef.current = { key: slot.key, digits };
212
+ return;
210
213
  }
214
+
215
+ typedRef.current = null;
216
+ if (accepted) checkInputAndGoNext(slot);
211
217
  },
212
- [checkInputAndGoNext, getSlotText, updateSlot],
218
+ [checkInputAndGoNext, updateSlot],
213
219
  );
214
220
 
215
221
  const handleFocus = useCallback(() => {
216
222
  if (readonly || disabled) return;
223
+ resetTyped();
217
224
  ensureMask();
218
225
  // На фокус всегда выбираем ПЕРВЫЙ сегмент (паритет с легаси). При клике мышью `handleClick`
219
226
  // отработает следом и перевыберет сегмент под кареткой; при Tab остаётся первый.
220
227
  selectSlot(firstSlot);
221
- }, [disabled, ensureMask, firstSlot, readonly, selectSlot]);
228
+ }, [disabled, ensureMask, firstSlot, readonly, resetTyped, selectSlot]);
222
229
 
223
230
  const handleClick = useCallback(
224
231
  (event: MouseEvent<HTMLInputElement>) => {
225
232
  if (readonly || disabled) return;
233
+ resetTyped();
226
234
  ensureMask();
227
235
  selectSlot(slotFromIndex(event.currentTarget.selectionStart));
228
236
  },
229
- [disabled, ensureMask, readonly, selectSlot, slotFromIndex],
237
+ [disabled, ensureMask, readonly, resetTyped, selectSlot, slotFromIndex],
230
238
  );
231
239
 
232
240
  const handleBlur = useCallback(() => {
241
+ resetTyped();
233
242
  const input = inputRef.current;
234
243
  if (input && input.value === mask) {
235
244
  input.value = '';
236
245
  setValue('');
237
246
  }
238
- }, [inputRef, mask, setValue]);
247
+ }, [inputRef, mask, resetTyped, setValue]);
239
248
 
240
249
  const handleKeyDown = useCallback(
241
250
  (event: KeyboardEvent<HTMLInputElement>) => {
242
251
  const input = inputRef.current;
243
252
  if (!input || readonly || disabled) return;
244
253
 
254
+ if (RESET_TYPED_KEYS.has(event.key)) resetTyped();
255
+
245
256
  // Tab уводит фокус из поля — не перехватываем.
246
257
  if (event.key === 'Tab') return;
247
258
 
@@ -258,8 +269,14 @@ export function useSegmentedMask({
258
269
  return;
259
270
  }
260
271
 
272
+ // Копирование и вставку не блокируем: правку поля перехватит beforeinput.
273
+ if (event.ctrlKey || event.metaKey || event.altKey) return;
274
+
261
275
  onEdit?.();
262
276
 
277
+ // Экранные клавиатуры присылают `Unidentified` вместо цифры, её данные есть только в beforeinput.
278
+ if (/^\d$/.test(event.key) || event.key === 'Unidentified') return;
279
+
263
280
  if (event.key === 'Escape') {
264
281
  event.preventDefault();
265
282
  onEscape?.();
@@ -297,11 +314,6 @@ export function useSegmentedMask({
297
314
  if (event.key === 'Enter') {
298
315
  tryToComplete();
299
316
  emit();
300
- return;
301
- }
302
- if (/^\d$/.test(event.key)) {
303
- typeDigit(slot, event.key);
304
- emit();
305
317
  }
306
318
  },
307
319
  [
@@ -318,22 +330,16 @@ export function useSegmentedMask({
318
330
  onEscape,
319
331
  prevSlot,
320
332
  readonly,
333
+ resetTyped,
321
334
  selectSlot,
322
335
  slotFromIndex,
323
336
  tryToComplete,
324
- typeDigit,
325
337
  ],
326
338
  );
327
339
 
328
- // Вставка (Ctrl+V) полной строки даты/времени: вытаскиваем цифры и заполняем сегменты
329
- // слева направо. Нативный onChange у поля игнорируется (движок controlled), поэтому без
330
- // этого обработчика вставка не работала бы вовсе.
331
- const handlePaste = useCallback(
332
- (event: ClipboardEvent<HTMLInputElement>) => {
333
- if (readonly || disabled) return;
334
- event.preventDefault();
335
- const digits = event.clipboardData.getData('text').replace(/\D/g, '');
336
- if (!digits) return;
340
+ const fillFromDigits = useCallback(
341
+ (digits: string) => {
342
+ resetTyped();
337
343
  ensureMask();
338
344
 
339
345
  let cursor = 0;
@@ -352,10 +358,123 @@ export function useSegmentedMask({
352
358
  } else if (lastFilled) {
353
359
  selectSlot(nextSlot(lastFilled));
354
360
  }
361
+ },
362
+ [ensureMask, lastSlot, nextSlot, resetTyped, selectSlot, slots, tryToComplete, updateSlot],
363
+ );
364
+
365
+ const handlePaste = useCallback(
366
+ (event: ClipboardEvent<HTMLInputElement>) => {
367
+ if (readonly || disabled) return;
368
+ event.preventDefault();
369
+ const digits = event.clipboardData.getData('text').replace(/\D/g, '');
370
+ if (!digits) return;
371
+ fillFromDigits(digits);
372
+ emit();
373
+ },
374
+ [disabled, emit, fillFromDigits, readonly],
375
+ );
376
+
377
+ const applyEdit = useCallback(
378
+ (inputType: string, text: string) => {
379
+ const input = inputRef.current;
380
+ if (!input) return;
381
+ onEdit?.();
382
+
383
+ if (inputType.startsWith('delete')) {
384
+ resetTyped();
385
+ clearSlot(slotFromIndex(input.selectionStart));
386
+ emit();
387
+ return;
388
+ }
389
+
390
+ const digits = text.replace(/\D/g, '');
391
+ if (!inputType.startsWith('insert') || !digits) return;
392
+
393
+ // Автозаполнение, `fill` и drop присылают строку целиком.
394
+ if (text.length > 1) {
395
+ fillFromDigits(digits);
396
+ } else {
397
+ typeDigit(slotFromIndex(input.selectionStart), digits);
398
+ }
355
399
  emit();
356
400
  },
357
- [disabled, emit, ensureMask, lastSlot, nextSlot, readonly, selectSlot, slots, tryToComplete, updateSlot],
401
+ [clearSlot, emit, fillFromDigits, inputRef, onEdit, resetTyped, slotFromIndex, typeDigit],
402
+ );
403
+
404
+ // Композицию IME браузер не даёт отменить — откатываем её в input.
405
+ const pendingEditRef = useRef<{ value: string; start: number; end: number } | null>(null);
406
+
407
+ const handleBeforeInput = useCallback(
408
+ (event: InputEvent) => {
409
+ const input = inputRef.current;
410
+ if (!input || readonly || disabled) return;
411
+ ensureMask();
412
+
413
+ if (!event.cancelable) {
414
+ pendingEditRef.current = { value: input.value, start: input.selectionStart ?? 0, end: input.selectionEnd ?? 0 };
415
+ return;
416
+ }
417
+
418
+ event.preventDefault();
419
+ applyEdit(event.inputType, event.data ?? event.dataTransfer?.getData('text') ?? '');
420
+ },
421
+ [applyEdit, disabled, ensureMask, inputRef, readonly],
422
+ );
423
+
424
+ const handleInput = useCallback(
425
+ (event: Event) => {
426
+ const input = inputRef.current;
427
+ if (!input || readonly || disabled) return;
428
+ const pending = pendingEditRef.current;
429
+ pendingEditRef.current = null;
430
+
431
+ if (pending) {
432
+ const inputType = event instanceof InputEvent ? event.inputType : '';
433
+ const inserted = input.value.slice(pending.start, input.value.length - (pending.value.length - pending.end));
434
+ input.value = pending.value;
435
+ setValue(pending.value);
436
+ input.setSelectionRange(pending.start, pending.end);
437
+ // Цифру композиции вводит её фиксация (insertText), иначе цифра запишется дважды.
438
+ if (!inputType.includes('Composition')) applyEdit(inputType, inserted);
439
+ return;
440
+ }
441
+
442
+ // Автозаполнение меняет значение без beforeinput.
443
+ const digits = input.value.replace(/\D/g, '');
444
+ input.value = mask;
445
+ setValue(mask);
446
+ fillFromDigits(digits);
447
+ emit();
448
+ },
449
+ [applyEdit, disabled, emit, fillFromDigits, inputRef, mask, readonly, setValue],
450
+ );
451
+
452
+ // React 18 не отдаёт `inputType` в `onBeforeInput`, поэтому слушаем нативные события.
453
+ const onNativeBeforeInput = useEventHandler(handleBeforeInput);
454
+ const onNativeInput = useEventHandler(handleInput);
455
+ const attachedInputRef = useRef<HTMLInputElement | null>(null);
456
+ const nativeInputRef = useCallback(
457
+ (node: HTMLInputElement | null) => {
458
+ /* eslint-disable @cloud-ru/ssr-safe-react/domApi -- callback-ref вызывается только в браузере */
459
+ attachedInputRef.current?.removeEventListener('beforeinput', onNativeBeforeInput);
460
+ attachedInputRef.current?.removeEventListener('input', onNativeInput);
461
+ attachedInputRef.current = node;
462
+ node?.addEventListener('beforeinput', onNativeBeforeInput);
463
+ node?.addEventListener('input', onNativeInput);
464
+ /* eslint-enable @cloud-ru/ssr-safe-react/domApi */
465
+ },
466
+ [onNativeBeforeInput, onNativeInput],
358
467
  );
359
468
 
360
- return { handleKeyDown, handleClick, handleFocus, handleBlur, handlePaste, selectSlot, firstSlot, lastSlot };
469
+ return {
470
+ handleKeyDown,
471
+ handleClick,
472
+ handleFocus,
473
+ handleBlur,
474
+ handlePaste,
475
+ nativeInputRef,
476
+ selectSlot,
477
+ firstSlot,
478
+ lastSlot,
479
+ };
361
480
  }
@@ -1,33 +0,0 @@
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
- addOptionByEnter: boolean;
10
- multiple: boolean;
11
- inputValue: string;
12
- typing: boolean;
13
- multipleValue: ItemId[];
14
- commitSingle(value: ItemId | undefined): void;
15
- commitMultiple(value: ItemId[]): void;
16
- resetSearch(): void;
17
- inputElementRef: RefObject<HTMLInputElement | null>;
18
- clearButtonRef: RefObject<HTMLButtonElement | null>;
19
- copyButtonRef: RefObject<HTMLButtonElement | null>;
20
- footerActiveElementsRefs?: RefObject<HTMLElement>[];
21
- };
22
- /** Фиксация произвольного ввода как выбранной опции: триггеры, blur, закрытие списка. */
23
- export declare function useCustomOption({ allowCustomOption, addCustomOptionTriggers, addOptionByEnter, multiple, inputValue, typing, multipleValue, commitSingle, commitMultiple, resetSearch, inputElementRef, clearButtonRef, copyButtonRef, footerActiveElementsRefs, }: UseCustomOptionParams): {
24
- listRef: RefObject<HTMLElement>;
25
- suppressCloseCommit: () => void;
26
- enableCloseCommit: () => void;
27
- tryCommitOnClose: () => boolean;
28
- tryCommitOnBlur: (event: FocusEvent<HTMLInputElement>) => CustomOptionBlurResult;
29
- tryCommitFromKeyboard: (event: KeyboardEvent<HTMLInputElement>) => boolean;
30
- handleListSingleChange: (next: ItemId | undefined) => void;
31
- handleListMultipleChange: (next: ItemId[]) => void;
32
- };
33
- export {};
@@ -1,95 +0,0 @@
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, addOptionByEnter, 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
- addOptionByEnter,
17
- defaultTriggers: multiple ? constants_1.ADD_CUSTOM_OPTION_TRIGGERS_MULTIPLE : constants_1.ADD_CUSTOM_OPTION_TRIGGERS_SINGLE,
18
- }), [allowCustomOption, addCustomOptionTriggers, addOptionByEnter, multiple]);
19
- const tryCommit = (0, react_1.useCallback)((trigger) => {
20
- if (!typing || !(0, utils_2.shouldHandleCustomOptionTrigger)(trigger, resolvedTriggers) || inputValue === '') {
21
- return false;
22
- }
23
- if (multiple) {
24
- if (multipleValue.includes(inputValue)) {
25
- resetSearch();
26
- }
27
- else {
28
- commitMultiple([...multipleValue, inputValue]);
29
- }
30
- }
31
- else {
32
- commitSingle(inputValue);
33
- }
34
- return true;
35
- }, [typing, resolvedTriggers, inputValue, multiple, multipleValue, commitMultiple, commitSingle, resetSearch]);
36
- const suppressCloseCommit = (0, react_1.useCallback)(() => {
37
- skipCloseCommitRef.current = true;
38
- skipBlurCommitRef.current = true;
39
- }, []);
40
- const enableCloseCommit = (0, react_1.useCallback)(() => {
41
- skipCloseCommitRef.current = false;
42
- skipBlurCommitRef.current = false;
43
- }, []);
44
- const tryCommitOnClose = (0, react_1.useCallback)(() => {
45
- const skipped = skipCloseCommitRef.current;
46
- const shouldCommit = (0, utils_2.shouldCommitCustomOptionOnClose)({
47
- skip: skipped,
48
- inputElement: inputElementRef.current,
49
- activeElement: (0, utils_1.isBrowser)() ? document.activeElement : null,
50
- });
51
- if (skipped) {
52
- queueMicrotask(() => {
53
- skipCloseCommitRef.current = false;
54
- });
55
- }
56
- return shouldCommit && tryCommit(constants_1.ADD_CUSTOM_OPTION_TRIGGER.Blur);
57
- }, [inputElementRef, tryCommit]);
58
- const tryCommitOnBlur = (0, react_1.useCallback)((event) => {
59
- if (skipBlurCommitRef.current) {
60
- skipBlurCommitRef.current = false;
61
- return 'skipped';
62
- }
63
- if ((0, utils_2.isCustomOptionBlurInsideField)(event.relatedTarget, [
64
- listRef.current,
65
- clearButtonRef.current,
66
- copyButtonRef.current,
67
- ...(footerActiveElementsRefs?.map(ref => ref.current) ?? []),
68
- ])) {
69
- return 'inside';
70
- }
71
- return tryCommit(constants_1.ADD_CUSTOM_OPTION_TRIGGER.Blur) ? 'committed' : 'skipped';
72
- }, [clearButtonRef, copyButtonRef, footerActiveElementsRefs, tryCommit]);
73
- const tryCommitFromKeyboard = (0, react_1.useCallback)((event) => {
74
- const trigger = (0, utils_2.getCustomOptionTriggerByCode)(event.code, event.key);
75
- return trigger !== undefined && tryCommit(trigger);
76
- }, [tryCommit]);
77
- const handleListSingleChange = (0, react_1.useCallback)((next) => {
78
- skipCloseCommitRef.current = true;
79
- commitSingle(next);
80
- }, [commitSingle]);
81
- const handleListMultipleChange = (0, react_1.useCallback)((next) => {
82
- skipCloseCommitRef.current = true;
83
- commitMultiple(next);
84
- }, [commitMultiple]);
85
- return {
86
- listRef,
87
- suppressCloseCommit,
88
- enableCloseCommit,
89
- tryCommitOnClose,
90
- tryCommitOnBlur,
91
- tryCommitFromKeyboard,
92
- handleListSingleChange,
93
- handleListMultipleChange,
94
- };
95
- }
@@ -1,21 +0,0 @@
1
- import { FieldSelectAddCustomOptionTrigger, FieldSelectMultipleAddCustomOptionTrigger } from '../types';
2
- /**
3
- * Сопоставляет клавишу с триггером кастомной опции (`enter` / `space` / `comma`).
4
- * Сначала `KeyboardEvent.code`, затем `key` — если `code` пустой или не из словаря (`','` без `Comma`).
5
- */
6
- export declare function getCustomOptionTriggerByCode(code: string, key?: string): FieldSelectMultipleAddCustomOptionTrigger | undefined;
7
- export declare function shouldHandleCustomOptionTrigger(trigger: FieldSelectAddCustomOptionTrigger | undefined, availableTriggers: readonly FieldSelectAddCustomOptionTrigger[]): trigger is FieldSelectAddCustomOptionTrigger;
8
- export declare function resolveAddCustomOptionTriggers(params: {
9
- allowCustomOption: boolean;
10
- addCustomOptionTriggers: readonly FieldSelectAddCustomOptionTrigger[] | undefined;
11
- addOptionByEnter: boolean;
12
- defaultTriggers: readonly FieldSelectAddCustomOptionTrigger[];
13
- }): FieldSelectAddCustomOptionTrigger[];
14
- /** Фокус ушёл на дроплист, футер или postfix — кастомную опцию на blur фиксировать не нужно. */
15
- export declare function isCustomOptionBlurInsideField(relatedTarget: EventTarget | null, nodes: (Node | null | undefined)[]): boolean;
16
- /** Клик снаружи закрывает список, не снимая фокус с input — blur не придёт. */
17
- export declare function shouldCommitCustomOptionOnClose(params: {
18
- skip: boolean;
19
- inputElement: Element | null;
20
- activeElement: Element | null;
21
- }): boolean;
@@ -1,55 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getCustomOptionTriggerByCode = getCustomOptionTriggerByCode;
4
- exports.shouldHandleCustomOptionTrigger = shouldHandleCustomOptionTrigger;
5
- exports.resolveAddCustomOptionTriggers = resolveAddCustomOptionTriggers;
6
- exports.isCustomOptionBlurInsideField = isCustomOptionBlurInsideField;
7
- exports.shouldCommitCustomOptionOnClose = shouldCommitCustomOptionOnClose;
8
- const constants_1 = require("../constants");
9
- /**
10
- * Сопоставляет клавишу с триггером кастомной опции (`enter` / `space` / `comma`).
11
- * Сначала `KeyboardEvent.code`, затем `key` — если `code` пустой или не из словаря (`','` без `Comma`).
12
- */
13
- function getCustomOptionTriggerByCode(code, key) {
14
- switch (code) {
15
- case 'Enter':
16
- return constants_1.ADD_CUSTOM_OPTION_TRIGGER.Enter;
17
- case 'Space':
18
- return constants_1.ADD_CUSTOM_OPTION_TRIGGER.Space;
19
- case 'Comma':
20
- return constants_1.ADD_CUSTOM_OPTION_TRIGGER.Comma;
21
- default:
22
- break;
23
- }
24
- switch (key) {
25
- case 'Enter':
26
- return constants_1.ADD_CUSTOM_OPTION_TRIGGER.Enter;
27
- case ' ':
28
- return constants_1.ADD_CUSTOM_OPTION_TRIGGER.Space;
29
- case ',':
30
- return constants_1.ADD_CUSTOM_OPTION_TRIGGER.Comma;
31
- default:
32
- return undefined;
33
- }
34
- }
35
- function shouldHandleCustomOptionTrigger(trigger, availableTriggers) {
36
- return trigger !== undefined && availableTriggers.includes(trigger);
37
- }
38
- function resolveAddCustomOptionTriggers(params) {
39
- if (params.allowCustomOption) {
40
- const source = params.addCustomOptionTriggers !== undefined ? params.addCustomOptionTriggers : params.defaultTriggers;
41
- return source.filter(trigger => params.defaultTriggers.includes(trigger));
42
- }
43
- if (params.addOptionByEnter) {
44
- return [constants_1.ADD_CUSTOM_OPTION_TRIGGER.Enter];
45
- }
46
- return [];
47
- }
48
- /** Фокус ушёл на дроплист, футер или postfix — кастомную опцию на blur фиксировать не нужно. */
49
- function isCustomOptionBlurInsideField(relatedTarget, nodes) {
50
- return relatedTarget instanceof Node && nodes.some(node => Boolean(node?.contains(relatedTarget)));
51
- }
52
- /** Клик снаружи закрывает список, не снимая фокус с input — blur не придёт. */
53
- function shouldCommitCustomOptionOnClose(params) {
54
- return !params.skip && params.activeElement !== null && params.activeElement === params.inputElement;
55
- }