/
valueUtil.ts
311 lines (267 loc) · 7.74 KB
/
valueUtil.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
import warning from 'rc-util/lib/warning';
import {
OptionsType as SelectOptionsType,
OptionData,
OptionGroupData,
FlattenOptionData,
} from '../interface';
import {
LabelValueType,
FilterFunc,
RawValueType,
GetLabeledValue,
DefaultValueType,
} from '../interface/generator';
import { toArray } from './commonUtil';
function getKey(data: OptionData | OptionGroupData, index: number) {
const { key } = data;
let value: RawValueType;
if ('value' in data) {
({ value } = data);
}
if (key !== null && key !== undefined) {
return key;
}
if (value !== undefined) {
return value;
}
return `rc-index-key-${index}`;
}
/**
* Flat options into flatten list.
* We use `optionOnly` here is aim to avoid user use nested option group.
* Here is simply set `key` to the index if not provided.
*/
export function flattenOptions(options: SelectOptionsType): FlattenOptionData[] {
const flattenList: FlattenOptionData[] = [];
function dig(list: SelectOptionsType, isGroupOption: boolean) {
list.forEach(data => {
if (isGroupOption || !('options' in data)) {
// Option
flattenList.push({
key: getKey(data, flattenList.length),
groupOption: isGroupOption,
data,
});
} else {
// Option Group
flattenList.push({
key: getKey(data, flattenList.length),
group: true,
data,
});
dig(data.options, true);
}
});
}
dig(options, false);
return flattenList;
}
/**
* Inject `props` into `option` for legacy usage
*/
function injectPropsWithOption<T>(option: T): T {
const newOption = { ...option };
if (!('props' in newOption)) {
Object.defineProperty(newOption, 'props', {
get() {
warning(
false,
'Return type is option instead of Option instance. Please read value directly instead of reading from `props`.',
);
return newOption;
},
});
}
return newOption;
}
export function findValueOption(
values: RawValueType[],
options: FlattenOptionData[],
{ prevValueOptions = [] }: { prevValueOptions?: OptionData[] } = {},
): OptionData[] {
const optionMap: Map<RawValueType, OptionData> = new Map();
options.forEach(flattenItem => {
if (!flattenItem.group) {
const data = flattenItem.data as OptionData;
// Check if match
optionMap.set(data.value, data);
}
});
return values.map(val => {
let option = optionMap.get(val);
// Fallback to try to find prev options
if (!option) {
option = {
// eslint-disable-next-line no-underscore-dangle
...prevValueOptions.find(opt => opt._INTERNAL_OPTION_VALUE_ === val),
};
}
return injectPropsWithOption(option);
});
}
export const getLabeledValue: GetLabeledValue<FlattenOptionData[]> = (
value,
{ options, prevValue, labelInValue, optionLabelProp },
) => {
const item = findValueOption([value], options)[0];
const result: LabelValueType = {
value,
};
let prevValItem: LabelValueType;
const prevValues = toArray<RawValueType | LabelValueType>(prevValue);
if (labelInValue) {
prevValItem = prevValues.find((prevItem: LabelValueType) => {
if (typeof prevItem === 'object' && 'value' in prevItem) {
return prevItem.value === value;
}
// [Legacy] Support `key` as `value`
return prevItem.key === value;
}) as LabelValueType;
}
if (prevValItem && typeof prevValItem === 'object' && 'label' in prevValItem) {
result.label = prevValItem.label;
if (
item &&
typeof prevValItem.label === 'string' &&
typeof item[optionLabelProp] === 'string' &&
prevValItem.label.trim() !== item[optionLabelProp].trim()
) {
warning(false, '`label` of `value` is not same as `label` in Select options.');
}
} else if (item && optionLabelProp in item) {
result.label = item[optionLabelProp];
} else {
result.label = value;
}
// Used for motion control
result.key = result.value;
return result;
};
function toRawString(content: React.ReactNode): string {
return toArray(content).join('');
}
/** Filter single option if match the search text */
function getFilterFunction(optionFilterProp: string) {
return (searchValue: string, option: OptionData | OptionGroupData) => {
const lowerSearchText = searchValue.toLowerCase();
// Group label search
if ('options' in option) {
return toRawString(option.label)
.toLowerCase()
.includes(lowerSearchText);
}
// Option value search
const rawValue = option[optionFilterProp];
const value = toRawString(rawValue).toLowerCase();
return value.includes(lowerSearchText);
};
}
/** Filter options and return a new options by the search text */
export function filterOptions(
searchValue: string,
options: SelectOptionsType,
{
optionFilterProp,
filterOption,
}: { optionFilterProp: string; filterOption: boolean | FilterFunc<SelectOptionsType[number]> },
) {
const filteredOptions: SelectOptionsType = [];
let filterFunc: FilterFunc<SelectOptionsType[number]>;
if (filterOption === false) {
return [...options];
}
if (typeof filterOption === 'function') {
filterFunc = filterOption;
} else {
filterFunc = getFilterFunction(optionFilterProp);
}
options.forEach(item => {
// Group should check child options
if ('options' in item) {
// Check group first
const matchGroup = filterFunc(searchValue, item);
if (matchGroup) {
filteredOptions.push(item);
} else {
// Check option
const subOptions = item.options.filter(subItem => filterFunc(searchValue, subItem));
if (subOptions.length) {
filteredOptions.push({
...item,
options: subOptions,
});
}
}
return;
}
if (filterFunc(searchValue, injectPropsWithOption(item))) {
filteredOptions.push(item);
}
});
return filteredOptions;
}
export function getSeparatedContent(text: string, tokens: string[]): string[] {
if (!tokens || !tokens.length) {
return null;
}
let match = false;
function separate(str: string, [token, ...restTokens]: string[]) {
if (!token) {
return [str];
}
const list = str.split(token);
match = match || list.length > 1;
return list
.reduce((prevList, unitStr) => [...prevList, ...separate(unitStr, restTokens)], [])
.filter(unit => unit);
}
const list = separate(text, tokens);
return match ? list : null;
}
export function isValueDisabled(value: RawValueType, options: FlattenOptionData[]): boolean {
const option = findValueOption([value], options)[0];
return option.disabled;
}
/**
* `tags` mode should fill un-list item into the option list
*/
export function fillOptionsWithMissingValue(
options: SelectOptionsType,
value: DefaultValueType,
optionLabelProp: string,
labelInValue: boolean,
): SelectOptionsType {
const values = toArray<RawValueType | LabelValueType>(value)
.slice()
.sort();
const cloneOptions = [...options];
// Convert options value to set
const optionValues = new Set<RawValueType>();
options.forEach(opt => {
if (opt.options) {
opt.options.forEach((subOpt: OptionData) => {
optionValues.add(subOpt.value);
});
} else {
optionValues.add((opt as OptionData).value);
}
});
// Fill missing value
values.forEach(item => {
const val: RawValueType = labelInValue
? (item as LabelValueType).value
: (item as RawValueType);
if (!optionValues.has(val)) {
cloneOptions.push(
labelInValue
? {
[optionLabelProp]: (item as LabelValueType).label,
value: val,
}
: { value: val },
);
}
});
return cloneOptions;
}