@cloud-ru/ds-fields 2.2.3-preview-0c4119af.0 → 2.2.3-preview-7425cb27.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 (76) hide show
  1. package/README.md +1 -3
  2. package/dist/cjs/components/FieldDate/FieldDate.js +3 -3
  3. package/dist/cjs/components/FieldDate/mask.d.ts +3 -2
  4. package/dist/cjs/components/FieldDate/mask.js +4 -3
  5. package/dist/cjs/components/FieldSelect/FieldSelect.js +41 -81
  6. package/dist/cjs/components/FieldSelect/constants.d.ts +0 -11
  7. package/dist/cjs/components/FieldSelect/constants.js +1 -20
  8. package/dist/cjs/components/FieldSelect/types.d.ts +3 -26
  9. package/dist/cjs/components/FieldSelect/utils.d.ts +19 -0
  10. package/dist/cjs/components/FieldSelect/utils.js +103 -0
  11. package/dist/cjs/components/FieldTime/FieldTime.js +2 -2
  12. package/dist/cjs/segments/useSegmentedMask.d.ts +4 -0
  13. package/dist/cjs/segments/useSegmentedMask.js +155 -56
  14. package/dist/esm/components/FieldDate/FieldDate.js +3 -3
  15. package/dist/esm/components/FieldDate/mask.d.ts +3 -2
  16. package/dist/esm/components/FieldDate/mask.js +4 -3
  17. package/dist/esm/components/FieldSelect/FieldSelect.js +42 -82
  18. package/dist/esm/components/FieldSelect/constants.d.ts +0 -11
  19. package/dist/esm/components/FieldSelect/constants.js +0 -19
  20. package/dist/esm/components/FieldSelect/types.d.ts +3 -26
  21. package/dist/esm/components/FieldSelect/utils.d.ts +19 -0
  22. package/dist/esm/components/FieldSelect/utils.js +92 -0
  23. package/dist/esm/components/FieldTime/FieldTime.js +2 -2
  24. package/dist/esm/segments/useSegmentedMask.d.ts +4 -0
  25. package/dist/esm/segments/useSegmentedMask.js +155 -56
  26. package/dist/tsconfig.cjs.tsbuildinfo +1 -1
  27. package/dist/tsconfig.esm.tsbuildinfo +1 -1
  28. package/package.json +6 -6
  29. package/src/components/FieldDate/FieldDate.tsx +3 -3
  30. package/src/components/FieldDate/mask.ts +4 -3
  31. package/src/components/FieldSelect/FieldSelect.tsx +61 -129
  32. package/src/components/FieldSelect/constants.ts +0 -22
  33. package/src/components/FieldSelect/types.ts +48 -82
  34. package/src/components/FieldSelect/utils.ts +132 -0
  35. package/src/components/FieldTime/FieldTime.tsx +2 -2
  36. package/src/segments/useSegmentedMask.ts +181 -52
  37. package/dist/cjs/components/FieldSelect/hooks.d.ts +0 -32
  38. package/dist/cjs/components/FieldSelect/hooks.js +0 -83
  39. package/dist/cjs/components/FieldSelect/utils/customOption.d.ts +0 -21
  40. package/dist/cjs/components/FieldSelect/utils/customOption.js +0 -55
  41. package/dist/cjs/components/FieldSelect/utils/extract.d.ts +0 -11
  42. package/dist/cjs/components/FieldSelect/utils/extract.js +0 -39
  43. package/dist/cjs/components/FieldSelect/utils/filter.d.ts +0 -3
  44. package/dist/cjs/components/FieldSelect/utils/filter.js +0 -40
  45. package/dist/cjs/components/FieldSelect/utils/index.d.ts +0 -6
  46. package/dist/cjs/components/FieldSelect/utils/index.js +0 -22
  47. package/dist/cjs/components/FieldSelect/utils/items.d.ts +0 -9
  48. package/dist/cjs/components/FieldSelect/utils/items.js +0 -47
  49. package/dist/cjs/components/FieldSelect/utils/selection.d.ts +0 -11
  50. package/dist/cjs/components/FieldSelect/utils/selection.js +0 -18
  51. package/dist/cjs/components/FieldSelect/utils/tagSize.d.ts +0 -4
  52. package/dist/cjs/components/FieldSelect/utils/tagSize.js +0 -5
  53. package/dist/esm/components/FieldSelect/hooks.d.ts +0 -32
  54. package/dist/esm/components/FieldSelect/hooks.js +0 -80
  55. package/dist/esm/components/FieldSelect/utils/customOption.d.ts +0 -21
  56. package/dist/esm/components/FieldSelect/utils/customOption.js +0 -48
  57. package/dist/esm/components/FieldSelect/utils/extract.d.ts +0 -11
  58. package/dist/esm/components/FieldSelect/utils/extract.js +0 -34
  59. package/dist/esm/components/FieldSelect/utils/filter.d.ts +0 -3
  60. package/dist/esm/components/FieldSelect/utils/filter.js +0 -36
  61. package/dist/esm/components/FieldSelect/utils/index.d.ts +0 -6
  62. package/dist/esm/components/FieldSelect/utils/index.js +0 -6
  63. package/dist/esm/components/FieldSelect/utils/items.d.ts +0 -9
  64. package/dist/esm/components/FieldSelect/utils/items.js +0 -41
  65. package/dist/esm/components/FieldSelect/utils/selection.d.ts +0 -11
  66. package/dist/esm/components/FieldSelect/utils/selection.js +0 -14
  67. package/dist/esm/components/FieldSelect/utils/tagSize.d.ts +0 -4
  68. package/dist/esm/components/FieldSelect/utils/tagSize.js +0 -2
  69. package/src/components/FieldSelect/hooks.ts +0 -162
  70. package/src/components/FieldSelect/utils/customOption.ts +0 -77
  71. package/src/components/FieldSelect/utils/extract.ts +0 -49
  72. package/src/components/FieldSelect/utils/filter.ts +0 -51
  73. package/src/components/FieldSelect/utils/index.ts +0 -6
  74. package/src/components/FieldSelect/utils/items.ts +0 -58
  75. package/src/components/FieldSelect/utils/selection.ts +0 -25
  76. package/src/components/FieldSelect/utils/tagSize.ts +0 -5
@@ -1,11 +0,0 @@
1
- import { ItemId } from '@cloud-ru/ds-list';
2
- import { Appearance as TagAppearance } from '@cloud-ru/ds-tag';
3
- export type WithIdContent = {
4
- id?: ItemId;
5
- content?: unknown;
6
- disabled?: boolean;
7
- appearance?: TagAppearance;
8
- };
9
- export declare function extractLabel(item: WithIdContent): string;
10
- export declare function extractSearchText(item: WithIdContent): string;
11
- export declare function extractAppearance(item?: WithIdContent): TagAppearance | undefined;
@@ -1,39 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.extractLabel = extractLabel;
4
- exports.extractSearchText = extractSearchText;
5
- exports.extractAppearance = extractAppearance;
6
- function extractLabel(item) {
7
- const { content, id } = item;
8
- if (!content) {
9
- return String(id ?? '');
10
- }
11
- if (typeof content === 'string' || typeof content === 'number') {
12
- return String(content);
13
- }
14
- if (typeof content === 'object' && content !== null && 'label' in content) {
15
- return String(content.label);
16
- }
17
- return String(id ?? '');
18
- }
19
- // Текст для поиска: лейбл (option) + caption + description — паритет с легаси `useSearch`,
20
- // который матчил запрос по всем трём полям контента, а не только по лейблу.
21
- function extractSearchText(item) {
22
- const parts = [extractLabel(item)];
23
- const { content } = item;
24
- if (content && typeof content === 'object') {
25
- const c = content;
26
- if (typeof c.caption === 'string') {
27
- parts.push(c.caption);
28
- }
29
- if (typeof c.description === 'string') {
30
- parts.push(c.description);
31
- }
32
- }
33
- return parts.join(' ');
34
- }
35
- // Цвет тега выбранного значения (multiple) — паритет с легаси `option.appearance`.
36
- // Проверка типа нужна и при типизированном поле: items часто приходят из ответа бэкенда.
37
- function extractAppearance(item) {
38
- return typeof item?.appearance === 'string' ? item.appearance : undefined;
39
- }
@@ -1,3 +0,0 @@
1
- import { FieldSelectItem } from '../types';
2
- export declare function isFuzzyMatch(haystack: string, needle: string): boolean;
3
- export declare function filterItems(items: FieldSelectItem[], query: string, fuzzy: boolean): FieldSelectItem[];
@@ -1,40 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.isFuzzyMatch = isFuzzyMatch;
4
- exports.filterItems = filterItems;
5
- const extract_1 = require("./extract");
6
- // Subsequence-fuzzy: символы запроса должны встречаться в строке в исходном порядке.
7
- // Пример: query=`lge` matches `Large` (L → r → arg → e).
8
- function isFuzzyMatch(haystack, needle) {
9
- if (!needle) {
10
- return true;
11
- }
12
- let i = 0;
13
- for (const ch of haystack) {
14
- if (ch === needle[i]) {
15
- i += 1;
16
- if (i === needle.length) {
17
- return true;
18
- }
19
- }
20
- }
21
- return false;
22
- }
23
- function filterItems(items, query, fuzzy) {
24
- if (!query) {
25
- return items;
26
- }
27
- const q = query.toLowerCase();
28
- const matches = (item) => {
29
- const text = (0, extract_1.extractSearchText)(item).toLowerCase();
30
- return fuzzy ? isFuzzyMatch(text, q) : text.includes(q);
31
- };
32
- const walk = (list) => list.flatMap(item => {
33
- if ('items' in item && Array.isArray(item.items)) {
34
- const filteredChildren = walk(item.items);
35
- return filteredChildren.length > 0 ? [{ ...item, items: filteredChildren }] : [];
36
- }
37
- return matches(item) ? [item] : [];
38
- });
39
- return walk(items);
40
- }
@@ -1,6 +0,0 @@
1
- export * from './customOption';
2
- export * from './extract';
3
- export * from './filter';
4
- export * from './items';
5
- export * from './selection';
6
- export * from './tagSize';
@@ -1,22 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("./customOption"), exports);
18
- __exportStar(require("./extract"), exports);
19
- __exportStar(require("./filter"), exports);
20
- __exportStar(require("./items"), exports);
21
- __exportStar(require("./selection"), exports);
22
- __exportStar(require("./tagSize"), exports);
@@ -1,9 +0,0 @@
1
- import { ItemId } from '@cloud-ru/ds-list';
2
- import { FieldSelectItem } from '../types';
3
- import { WithIdContent } from './extract';
4
- export declare function flatten(items: FieldSelectItem[]): WithIdContent[];
5
- export declare function findItem(items: FieldSelectItem[], id: ItemId): WithIdContent | undefined;
6
- /** Айтем для выбранного значения, которого нет в `items` (кастомная опция, ленивая подгрузка). */
7
- export declare function createPlaceholderItem(id: ItemId): FieldSelectItem;
8
- /** Выбранные id, которых нет в дереве айтемов — в дроплист их нужно добавить отдельно. */
9
- export declare function getMissingSelectedItems(selectedIds: ItemId[], allItems: FieldSelectItem[]): FieldSelectItem[];
@@ -1,47 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.flatten = flatten;
4
- exports.findItem = findItem;
5
- exports.createPlaceholderItem = createPlaceholderItem;
6
- exports.getMissingSelectedItems = getMissingSelectedItems;
7
- function flatten(items) {
8
- const out = [];
9
- for (const item of items) {
10
- out.push(item);
11
- if ('items' in item && Array.isArray(item.items)) {
12
- out.push(...flatten(item.items));
13
- }
14
- }
15
- return out;
16
- }
17
- function findItem(items, id) {
18
- for (const item of flatten(items)) {
19
- if (item.id === id) {
20
- return item;
21
- }
22
- }
23
- return undefined;
24
- }
25
- /** Айтем для выбранного значения, которого нет в `items` (кастомная опция, ленивая подгрузка). */
26
- function createPlaceholderItem(id) {
27
- return { id, content: { label: String(id) } };
28
- }
29
- /** Выбранные id, которых нет в дереве айтемов — в дроплист их нужно добавить отдельно. */
30
- function getMissingSelectedItems(selectedIds, allItems) {
31
- if (selectedIds.length === 0) {
32
- return [];
33
- }
34
- const existingIds = new Set();
35
- for (const item of flatten(allItems)) {
36
- if (item.id !== undefined) {
37
- existingIds.add(item.id);
38
- }
39
- }
40
- const missing = [];
41
- for (const id of selectedIds) {
42
- if (id !== '' && !existingIds.has(id)) {
43
- missing.push(createPlaceholderItem(id));
44
- }
45
- }
46
- return missing;
47
- }
@@ -1,11 +0,0 @@
1
- import { ItemId } from '@cloud-ru/ds-list';
2
- import { FieldSelectMultipleProps, Selection } from '../types';
3
- export declare function isMultiple(props: {
4
- selection?: Selection;
5
- }): props is FieldSelectMultipleProps;
6
- /** Выбранные id в нормализованном виде: массив и для `single`, и для `multiple`. */
7
- export declare function getSelectedIds(params: {
8
- multiple: boolean;
9
- multipleValue: ItemId[];
10
- singleValue: ItemId | undefined;
11
- }): ItemId[];
@@ -1,18 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.isMultiple = isMultiple;
4
- exports.getSelectedIds = getSelectedIds;
5
- const constants_1 = require("../constants");
6
- function isMultiple(props) {
7
- return props.selection === constants_1.SELECTION_MODE.Multiple;
8
- }
9
- /** Выбранные id в нормализованном виде: массив и для `single`, и для `multiple`. */
10
- function getSelectedIds(params) {
11
- if (params.multiple) {
12
- return params.multipleValue;
13
- }
14
- if (params.singleValue === undefined) {
15
- return [];
16
- }
17
- return [params.singleValue];
18
- }
@@ -1,4 +0,0 @@
1
- import { Size } from '@cloud-ru/ds-field-decorator';
2
- import { Size as TagSize } from '@cloud-ru/ds-tag';
3
- /** Соответствие размера поля размеру чипа выбранного значения (`selection='multiple'`). */
4
- export declare const TAG_SIZE_MAP: Record<Size, TagSize>;
@@ -1,5 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.TAG_SIZE_MAP = void 0;
4
- /** Соответствие размера поля размеру чипа выбранного значения (`selection='multiple'`). */
5
- exports.TAG_SIZE_MAP = { s: 'xs', m: 'xs', l: 's' };
@@ -1,32 +0,0 @@
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
- addOptionByEnter: boolean;
10
- multiple: boolean;
11
- inputValue: string;
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, addOptionByEnter, multiple, inputValue, 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 {};
@@ -1,80 +0,0 @@
1
- import { isBrowser } from '@cloud-ru/ds-utils';
2
- import { useCallback, useMemo, useRef } from 'react';
3
- import { ADD_CUSTOM_OPTION_TRIGGER, ADD_CUSTOM_OPTION_TRIGGERS_MULTIPLE, ADD_CUSTOM_OPTION_TRIGGERS_SINGLE, } from './constants.js';
4
- import { getCustomOptionTriggerByCode, isCustomOptionBlurInsideField, resolveAddCustomOptionTriggers, shouldCommitCustomOptionOnClose, shouldHandleCustomOptionTrigger, } from './utils/index.js';
5
- /** Фиксация произвольного ввода как выбранной опции: триггеры, blur, закрытие списка. */
6
- export function useCustomOption({ allowCustomOption, addCustomOptionTriggers, addOptionByEnter, multiple, inputValue, multipleValue, commitSingle, commitMultiple, resetSearch, inputElementRef, clearButtonRef, copyButtonRef, footerActiveElementsRefs, }) {
7
- const listRef = useRef(null);
8
- const skipCloseCommitRef = useRef(false);
9
- const resolvedTriggers = useMemo(() => resolveAddCustomOptionTriggers({
10
- allowCustomOption,
11
- addCustomOptionTriggers,
12
- addOptionByEnter,
13
- defaultTriggers: multiple ? ADD_CUSTOM_OPTION_TRIGGERS_MULTIPLE : ADD_CUSTOM_OPTION_TRIGGERS_SINGLE,
14
- }), [allowCustomOption, addCustomOptionTriggers, addOptionByEnter, multiple]);
15
- const tryCommit = useCallback((trigger) => {
16
- if (!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
- }, [resolvedTriggers, inputValue, multiple, multipleValue, commitMultiple, commitSingle, resetSearch]);
32
- const suppressCloseCommit = useCallback(() => {
33
- skipCloseCommitRef.current = true;
34
- }, []);
35
- const enableCloseCommit = useCallback(() => {
36
- skipCloseCommitRef.current = false;
37
- }, []);
38
- const tryCommitOnClose = useCallback(() => {
39
- const shouldCommit = shouldCommitCustomOptionOnClose({
40
- skip: skipCloseCommitRef.current,
41
- inputElement: inputElementRef.current,
42
- activeElement: isBrowser() ? document.activeElement : null,
43
- });
44
- skipCloseCommitRef.current = false;
45
- return shouldCommit && tryCommit(ADD_CUSTOM_OPTION_TRIGGER.Blur);
46
- }, [inputElementRef, tryCommit]);
47
- const tryCommitOnBlur = useCallback((event) => {
48
- if (isCustomOptionBlurInsideField(event.relatedTarget, [
49
- listRef.current,
50
- clearButtonRef.current,
51
- copyButtonRef.current,
52
- ...(footerActiveElementsRefs?.map(ref => ref.current) ?? []),
53
- ])) {
54
- return 'inside';
55
- }
56
- return tryCommit(ADD_CUSTOM_OPTION_TRIGGER.Blur) ? 'committed' : 'skipped';
57
- }, [clearButtonRef, copyButtonRef, footerActiveElementsRefs, tryCommit]);
58
- const tryCommitFromKeyboard = useCallback((event) => {
59
- const trigger = getCustomOptionTriggerByCode(event.code, event.key);
60
- return trigger !== undefined && tryCommit(trigger);
61
- }, [tryCommit]);
62
- const handleListSingleChange = useCallback((next) => {
63
- skipCloseCommitRef.current = true;
64
- commitSingle(next);
65
- }, [commitSingle]);
66
- const handleListMultipleChange = useCallback((next) => {
67
- skipCloseCommitRef.current = true;
68
- commitMultiple(next);
69
- }, [commitMultiple]);
70
- return {
71
- listRef,
72
- suppressCloseCommit,
73
- enableCloseCommit,
74
- tryCommitOnClose,
75
- tryCommitOnBlur,
76
- tryCommitFromKeyboard,
77
- handleListSingleChange,
78
- handleListMultipleChange,
79
- };
80
- }
@@ -1,21 +0,0 @@
1
- import { FieldSelectAddCustomOptionTrigger, FieldSelectMultipleAddCustomOptionTrigger } from '../types.js';
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,48 +0,0 @@
1
- import { ADD_CUSTOM_OPTION_TRIGGER } from '../constants.js';
2
- /**
3
- * Сопоставляет клавишу с триггером кастомной опции (`enter` / `space` / `comma`).
4
- * Сначала `KeyboardEvent.code`, затем `key` — если `code` пустой или не из словаря (`','` без `Comma`).
5
- */
6
- export function getCustomOptionTriggerByCode(code, key) {
7
- switch (code) {
8
- case 'Enter':
9
- return ADD_CUSTOM_OPTION_TRIGGER.Enter;
10
- case 'Space':
11
- return ADD_CUSTOM_OPTION_TRIGGER.Space;
12
- case 'Comma':
13
- return ADD_CUSTOM_OPTION_TRIGGER.Comma;
14
- default:
15
- break;
16
- }
17
- switch (key) {
18
- case 'Enter':
19
- return ADD_CUSTOM_OPTION_TRIGGER.Enter;
20
- case ' ':
21
- return ADD_CUSTOM_OPTION_TRIGGER.Space;
22
- case ',':
23
- return ADD_CUSTOM_OPTION_TRIGGER.Comma;
24
- default:
25
- return undefined;
26
- }
27
- }
28
- export function shouldHandleCustomOptionTrigger(trigger, availableTriggers) {
29
- return trigger !== undefined && availableTriggers.includes(trigger);
30
- }
31
- export function resolveAddCustomOptionTriggers(params) {
32
- if (params.allowCustomOption) {
33
- const source = params.addCustomOptionTriggers !== undefined ? params.addCustomOptionTriggers : params.defaultTriggers;
34
- return source.filter(trigger => params.defaultTriggers.includes(trigger));
35
- }
36
- if (params.addOptionByEnter) {
37
- return [ADD_CUSTOM_OPTION_TRIGGER.Enter];
38
- }
39
- return [];
40
- }
41
- /** Фокус ушёл на дроплист, футер или postfix — кастомную опцию на blur фиксировать не нужно. */
42
- export function isCustomOptionBlurInsideField(relatedTarget, nodes) {
43
- return relatedTarget instanceof Node && nodes.some(node => Boolean(node?.contains(relatedTarget)));
44
- }
45
- /** Клик снаружи закрывает список, не снимая фокус с input — blur не придёт. */
46
- export function shouldCommitCustomOptionOnClose(params) {
47
- return !params.skip && params.activeElement !== null && params.activeElement === params.inputElement;
48
- }
@@ -1,11 +0,0 @@
1
- import { ItemId } from '@cloud-ru/ds-list';
2
- import { Appearance as TagAppearance } from '@cloud-ru/ds-tag';
3
- export type WithIdContent = {
4
- id?: ItemId;
5
- content?: unknown;
6
- disabled?: boolean;
7
- appearance?: TagAppearance;
8
- };
9
- export declare function extractLabel(item: WithIdContent): string;
10
- export declare function extractSearchText(item: WithIdContent): string;
11
- export declare function extractAppearance(item?: WithIdContent): TagAppearance | undefined;
@@ -1,34 +0,0 @@
1
- export function extractLabel(item) {
2
- const { content, id } = item;
3
- if (!content) {
4
- return String(id ?? '');
5
- }
6
- if (typeof content === 'string' || typeof content === 'number') {
7
- return String(content);
8
- }
9
- if (typeof content === 'object' && content !== null && 'label' in content) {
10
- return String(content.label);
11
- }
12
- return String(id ?? '');
13
- }
14
- // Текст для поиска: лейбл (option) + caption + description — паритет с легаси `useSearch`,
15
- // который матчил запрос по всем трём полям контента, а не только по лейблу.
16
- export function extractSearchText(item) {
17
- const parts = [extractLabel(item)];
18
- const { content } = item;
19
- if (content && typeof content === 'object') {
20
- const c = content;
21
- if (typeof c.caption === 'string') {
22
- parts.push(c.caption);
23
- }
24
- if (typeof c.description === 'string') {
25
- parts.push(c.description);
26
- }
27
- }
28
- return parts.join(' ');
29
- }
30
- // Цвет тега выбранного значения (multiple) — паритет с легаси `option.appearance`.
31
- // Проверка типа нужна и при типизированном поле: items часто приходят из ответа бэкенда.
32
- export function extractAppearance(item) {
33
- return typeof item?.appearance === 'string' ? item.appearance : undefined;
34
- }
@@ -1,3 +0,0 @@
1
- import { FieldSelectItem } from '../types.js';
2
- export declare function isFuzzyMatch(haystack: string, needle: string): boolean;
3
- export declare function filterItems(items: FieldSelectItem[], query: string, fuzzy: boolean): FieldSelectItem[];
@@ -1,36 +0,0 @@
1
- import { extractSearchText } from './extract.js';
2
- // Subsequence-fuzzy: символы запроса должны встречаться в строке в исходном порядке.
3
- // Пример: query=`lge` matches `Large` (L → r → arg → e).
4
- export function isFuzzyMatch(haystack, needle) {
5
- if (!needle) {
6
- return true;
7
- }
8
- let i = 0;
9
- for (const ch of haystack) {
10
- if (ch === needle[i]) {
11
- i += 1;
12
- if (i === needle.length) {
13
- return true;
14
- }
15
- }
16
- }
17
- return false;
18
- }
19
- export function filterItems(items, query, fuzzy) {
20
- if (!query) {
21
- return items;
22
- }
23
- const q = query.toLowerCase();
24
- const matches = (item) => {
25
- const text = extractSearchText(item).toLowerCase();
26
- return fuzzy ? isFuzzyMatch(text, q) : text.includes(q);
27
- };
28
- const walk = (list) => list.flatMap(item => {
29
- if ('items' in item && Array.isArray(item.items)) {
30
- const filteredChildren = walk(item.items);
31
- return filteredChildren.length > 0 ? [{ ...item, items: filteredChildren }] : [];
32
- }
33
- return matches(item) ? [item] : [];
34
- });
35
- return walk(items);
36
- }
@@ -1,6 +0,0 @@
1
- export * from './customOption.js';
2
- export * from './extract.js';
3
- export * from './filter.js';
4
- export * from './items.js';
5
- export * from './selection.js';
6
- export * from './tagSize.js';
@@ -1,6 +0,0 @@
1
- export * from './customOption.js';
2
- export * from './extract.js';
3
- export * from './filter.js';
4
- export * from './items.js';
5
- export * from './selection.js';
6
- export * from './tagSize.js';
@@ -1,9 +0,0 @@
1
- import { ItemId } from '@cloud-ru/ds-list';
2
- import { FieldSelectItem } from '../types.js';
3
- import { WithIdContent } from './extract.js';
4
- export declare function flatten(items: FieldSelectItem[]): WithIdContent[];
5
- export declare function findItem(items: FieldSelectItem[], id: ItemId): WithIdContent | undefined;
6
- /** Айтем для выбранного значения, которого нет в `items` (кастомная опция, ленивая подгрузка). */
7
- export declare function createPlaceholderItem(id: ItemId): FieldSelectItem;
8
- /** Выбранные id, которых нет в дереве айтемов — в дроплист их нужно добавить отдельно. */
9
- export declare function getMissingSelectedItems(selectedIds: ItemId[], allItems: FieldSelectItem[]): FieldSelectItem[];
@@ -1,41 +0,0 @@
1
- export function flatten(items) {
2
- const out = [];
3
- for (const item of items) {
4
- out.push(item);
5
- if ('items' in item && Array.isArray(item.items)) {
6
- out.push(...flatten(item.items));
7
- }
8
- }
9
- return out;
10
- }
11
- export function findItem(items, id) {
12
- for (const item of flatten(items)) {
13
- if (item.id === id) {
14
- return item;
15
- }
16
- }
17
- return undefined;
18
- }
19
- /** Айтем для выбранного значения, которого нет в `items` (кастомная опция, ленивая подгрузка). */
20
- export function createPlaceholderItem(id) {
21
- return { id, content: { label: String(id) } };
22
- }
23
- /** Выбранные id, которых нет в дереве айтемов — в дроплист их нужно добавить отдельно. */
24
- export function getMissingSelectedItems(selectedIds, allItems) {
25
- if (selectedIds.length === 0) {
26
- return [];
27
- }
28
- const existingIds = new Set();
29
- for (const item of flatten(allItems)) {
30
- if (item.id !== undefined) {
31
- existingIds.add(item.id);
32
- }
33
- }
34
- const missing = [];
35
- for (const id of selectedIds) {
36
- if (id !== '' && !existingIds.has(id)) {
37
- missing.push(createPlaceholderItem(id));
38
- }
39
- }
40
- return missing;
41
- }
@@ -1,11 +0,0 @@
1
- import { ItemId } from '@cloud-ru/ds-list';
2
- import { FieldSelectMultipleProps, Selection } from '../types.js';
3
- export declare function isMultiple(props: {
4
- selection?: Selection;
5
- }): props is FieldSelectMultipleProps;
6
- /** Выбранные id в нормализованном виде: массив и для `single`, и для `multiple`. */
7
- export declare function getSelectedIds(params: {
8
- multiple: boolean;
9
- multipleValue: ItemId[];
10
- singleValue: ItemId | undefined;
11
- }): ItemId[];
@@ -1,14 +0,0 @@
1
- import { SELECTION_MODE } from '../constants.js';
2
- export function isMultiple(props) {
3
- return props.selection === SELECTION_MODE.Multiple;
4
- }
5
- /** Выбранные id в нормализованном виде: массив и для `single`, и для `multiple`. */
6
- export function getSelectedIds(params) {
7
- if (params.multiple) {
8
- return params.multipleValue;
9
- }
10
- if (params.singleValue === undefined) {
11
- return [];
12
- }
13
- return [params.singleValue];
14
- }
@@ -1,4 +0,0 @@
1
- import { Size } from '@cloud-ru/ds-field-decorator';
2
- import { Size as TagSize } from '@cloud-ru/ds-tag';
3
- /** Соответствие размера поля размеру чипа выбранного значения (`selection='multiple'`). */
4
- export declare const TAG_SIZE_MAP: Record<Size, TagSize>;
@@ -1,2 +0,0 @@
1
- /** Соответствие размера поля размеру чипа выбранного значения (`selection='multiple'`). */
2
- export const TAG_SIZE_MAP = { s: 'xs', m: 'xs', l: 's' };