-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathindex.tsx
561 lines (513 loc) · 13.2 KB
/
index.tsx
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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
import { useIntl } from '@ant-design/pro-provider';
import {
compatibleBorder,
nanoid,
objectToMap,
proFieldParsingText,
ProFieldRequestData,
ProFieldValueEnumType,
ProSchemaValueEnumObj,
RequestOptionsType,
useDebounceValue,
useDeepCompareEffect,
useDeepCompareMemo,
useMountMergeState,
useRefFunction,
useStyle,
} from '@ant-design/pro-utils';
import type { SelectProps } from 'antd';
import { ConfigProvider, Spin } from 'antd';
import type { ReactNode } from 'react';
import React, {
useContext,
useEffect,
useImperativeHandle,
useMemo,
useRef,
useState,
} from 'react';
import useSWR from 'swr';
import type { ProFieldFC, ProFieldLightProps } from '../../index';
import LightSelect from './LightSelect';
import SearchSelect from './SearchSelect';
// 兼容代码-----------
import 'antd/lib/select/style';
//------------
type SelectOptionType = Partial<RequestOptionsType>[];
export type FieldSelectProps<FieldProps = any> = {
text: string;
/** 值的枚举,如果存在枚举,Search 中会生成 select */
valueEnum?: ProFieldValueEnumType;
/** 防抖动时间 默认10 单位ms */
debounceTime?: number;
/** 从服务器读取选项 */
request?: ProFieldRequestData;
/** 重新触发的时机 */
params?: any;
/** 组件的全局设置 */
fieldProps?: FieldProps;
bordered?: boolean;
id?: string;
children?: ReactNode;
/** 默认搜素条件 */
defaultKeyWords?: string;
} & ProFieldLightProps;
const Highlight: React.FC<{
label: string;
words: string[];
}> = ({ label, words }) => {
const { getPrefixCls } = useContext(ConfigProvider.ConfigContext);
const lightCls = getPrefixCls('pro-select-item-option-content-light');
const optionCls = getPrefixCls('pro-select-item-option-content');
// css
const { wrapSSR } = useStyle('Highlight', (token) => {
return {
[`.${lightCls}`]: {
color: token.colorPrimary,
},
[`.${optionCls}`]: {
flex: 'auto',
overflow: 'hidden',
whiteSpace: 'nowrap',
textOverflow: 'ellipsis',
},
};
});
const matchKeywordsRE = new RegExp(
words
.map((word) => word.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&'))
.join('|'),
'gi',
);
let matchText = label;
const elements: React.ReactNode[] = [];
while (matchText.length) {
const match = matchKeywordsRE.exec(matchText);
if (!match) {
elements.push(matchText);
break;
}
const start = match.index;
const matchLength = match[0].length + start;
elements.push(
matchText.slice(0, start),
React.createElement(
'span',
{
className: lightCls,
},
matchText.slice(start, matchLength),
),
);
matchText = matchText.slice(matchLength);
}
return wrapSSR(
React.createElement(
'div',
{
title: label,
className: optionCls,
},
...elements,
),
);
};
/**
* 递归筛选 item
*
* @param item
* @param keyWords
* @returns
*/
function filerByItem(
item: {
label: string;
value: string;
optionType: string;
children: any[];
options: any[];
},
keyWords?: string,
) {
if (!keyWords) return true;
if (
item?.label?.toString().toLowerCase().includes(keyWords.toLowerCase()) ||
item?.value?.toString().toLowerCase().includes(keyWords.toLowerCase())
) {
return true;
}
if (item.children || item.options) {
const findItem = [...(item.children || []), item.options || []].find(
(mapItem) => {
return filerByItem(mapItem, keyWords);
},
);
if (findItem) return true;
}
return false;
}
/**
* 把 value 的枚举转化为数组
*
* @param valueEnum
*/
export const proFieldParsingValueEnumToArray = (
valueEnumParams: ProFieldValueEnumType,
): SelectOptionType => {
const enumArray: Partial<
RequestOptionsType & {
text: string;
/** 是否禁用 */
disabled?: boolean;
}
>[] = [];
const valueEnum = objectToMap(valueEnumParams);
valueEnum.forEach((_, key) => {
const value = (valueEnum.get(key) || valueEnum.get(`${key}`)) as {
text: string;
disabled?: boolean;
};
if (!value) {
return;
}
if (typeof value === 'object' && value?.text) {
enumArray.push({
text: value?.text as unknown as string,
value: key,
label: value?.text as unknown as string,
disabled: value.disabled,
});
return;
}
enumArray.push({
text: value as unknown as string,
value: key,
});
});
return enumArray;
};
export const useFieldFetchData = (
props: FieldSelectProps & {
proFieldKey?: React.Key;
defaultKeyWords?: string;
cacheForSwr?: boolean;
},
): [boolean, SelectOptionType, (keyWord?: string) => void, () => void] => {
const { cacheForSwr, fieldProps } = props;
const [keyWords, setKeyWords] = useState<string | undefined>(
props.defaultKeyWords,
);
/** Key 是用来缓存请求的,如果不在是有问题 */
const [cacheKey] = useState(() => {
if (props.proFieldKey) {
return props.proFieldKey.toString();
}
if (props.request) {
return nanoid();
}
return 'no-fetch';
});
const proFieldKeyRef = useRef(cacheKey);
const getOptionsFormValueEnum = useRefFunction(
(coverValueEnum: ProFieldValueEnumType) => {
return proFieldParsingValueEnumToArray(objectToMap(coverValueEnum)).map(
({ value, text, ...rest }) => ({
label: text,
value,
key: value,
...rest,
}),
);
},
);
const defaultOptions = useDeepCompareMemo(() => {
if (!fieldProps) return undefined;
const data = fieldProps?.options || fieldProps?.treeData;
if (!data) return undefined;
const { children, label, value } = fieldProps.fieldNames || {};
const traverseFieldKey = (
_options: typeof options,
type: 'children' | 'label' | 'value',
) => {
if (!_options?.length) return;
const length = _options.length;
let i = 0;
while (i < length) {
const cur = _options[i++];
if (cur[children] || cur[label] || cur[value]) {
cur[type] =
cur[
type === 'children' ? children : type === 'label' ? label : value
];
traverseFieldKey(cur[children], type);
}
}
};
if (children) traverseFieldKey(data, 'children');
if (label) traverseFieldKey(data, 'label');
if (value) traverseFieldKey(data, 'value');
return data;
}, [fieldProps]);
const [options, setOptions] = useMountMergeState<SelectOptionType>(
() => {
if (props.valueEnum) {
return getOptionsFormValueEnum(props.valueEnum);
}
return [];
},
{
value: defaultOptions,
},
);
useDeepCompareEffect(() => {
// 优先使用 fieldProps?.options
if (
!props.valueEnum ||
props.fieldProps?.options ||
props.fieldProps?.treeData
)
return;
setOptions(getOptionsFormValueEnum(props.valueEnum));
}, [props.valueEnum]);
const swrKey = useDebounceValue(
[proFieldKeyRef.current, props.params, keyWords] as const,
props.debounceTime ?? props?.fieldProps?.debounceTime ?? 0,
[props.params, keyWords],
);
const {
data,
mutate: setLocaleData,
isValidating,
} = useSWR(
() => {
if (!props.request) {
return null;
}
return swrKey;
},
([, params, kw]) =>
props.request!(
{
...params,
keyWords: kw,
},
props,
),
{
revalidateIfStale: !cacheForSwr,
// 打开 cacheForSwr 的时候才应该支持两个功能
revalidateOnReconnect: cacheForSwr,
shouldRetryOnError: false,
// @todo 这个功能感觉应该搞个API出来
revalidateOnFocus: false,
},
);
const resOptions = useMemo(() => {
const opt = options?.map((item) => {
if (typeof item === 'string') {
return {
label: item,
value: item,
};
}
if (item.children || item.options) {
const childrenOptions = [
...(item.children || []),
...(item.options || []),
].filter((mapItem) => {
return filerByItem(mapItem, keyWords);
});
return {
...item,
children: childrenOptions,
options: childrenOptions,
};
}
return item;
});
// filterOption 为 true 时 filter数据, filterOption 默认为true
if (
props.fieldProps?.filterOption === true ||
props.fieldProps?.filterOption === undefined
) {
return opt?.filter((item) => {
if (!item) return false;
if (!keyWords) return true;
return filerByItem(item as any, keyWords);
});
}
return opt;
}, [options, keyWords, props.fieldProps?.filterOption]);
return [
isValidating,
props.request ? (data as SelectOptionType) : resOptions,
(fetchKeyWords?: string) => {
setKeyWords(fetchKeyWords);
},
() => {
setKeyWords(undefined);
setLocaleData([], false);
},
];
};
/**
* 可以根据 valueEnum 来进行类型的设置
*
* @param
*/
const FieldSelect: ProFieldFC<
FieldSelectProps & Pick<SelectProps, 'fieldNames' | 'style' | 'className'>
> = (props, ref) => {
const {
mode,
valueEnum,
render,
renderFormItem,
request,
fieldProps,
plain,
children,
light,
proFieldKey,
params,
label,
bordered,
id,
lightLabel,
labelTrigger,
...rest
} = props;
const inputRef = useRef();
const intl = useIntl();
const keyWordsRef = useRef<string>('');
const { fieldNames } = fieldProps;
useEffect(() => {
keyWordsRef.current = fieldProps?.searchValue;
}, [fieldProps?.searchValue]);
const [loading, options, fetchData, resetData] = useFieldFetchData(props);
const { componentSize } = ConfigProvider?.useConfig?.() || {
componentSize: 'middle',
};
useImperativeHandle(
ref,
() => ({
...(inputRef.current || {}),
fetchData: (keyWord: string) => fetchData(keyWord),
}),
[fetchData],
);
const optionsValueEnum = useMemo(() => {
if (mode !== 'read') return;
const {
label: labelPropsName = 'label',
value: valuePropsName = 'value',
options: optionsPropsName = 'options',
} = fieldNames || {};
const valuesMap = new Map();
const traverseOptions = (_options: typeof options) => {
if (!_options?.length) {
return valuesMap;
}
const length = _options.length;
let i = 0;
while (i < length) {
const cur = _options[i++];
valuesMap.set(cur[valuePropsName], cur[labelPropsName]);
traverseOptions(cur[optionsPropsName]);
}
return valuesMap;
};
return traverseOptions(options);
}, [fieldNames, mode, options]);
if (mode === 'read') {
const dom = (
<>
{proFieldParsingText(
rest.text,
objectToMap(
valueEnum || optionsValueEnum,
) as unknown as ProSchemaValueEnumObj,
)}
</>
);
if (render) {
return render(dom, { mode, ...fieldProps }, dom) ?? null;
}
return dom;
}
if (mode === 'edit' || mode === 'update') {
const renderDom = () => {
if (light) {
return (
<LightSelect
{...compatibleBorder(bordered)}
id={id}
loading={loading}
ref={inputRef}
allowClear
size={componentSize}
options={options}
label={label}
placeholder={intl.getMessage(
'tableForm.selectPlaceholder',
'请选择',
)}
lightLabel={lightLabel}
labelTrigger={labelTrigger}
fetchData={fetchData}
{...fieldProps}
/>
);
}
return (
<SearchSelect
key="SearchSelect"
className={rest.className}
style={{
minWidth: 100,
...rest.style,
}}
{...compatibleBorder(bordered)}
id={id}
loading={loading}
ref={inputRef}
allowClear
defaultSearchValue={props.defaultKeyWords}
notFoundContent={
loading ? <Spin size="small" /> : fieldProps?.notFoundContent
}
fetchData={(keyWord) => {
keyWordsRef.current = keyWord ?? '';
fetchData(keyWord);
}}
resetData={resetData}
optionItemRender={(item) => {
if (typeof item.label === 'string' && keyWordsRef.current) {
return (
<Highlight label={item.label} words={[keyWordsRef.current]} />
);
}
return item.label;
}}
placeholder={intl.getMessage('tableForm.selectPlaceholder', '请选择')}
label={label}
{...fieldProps}
options={options}
/>
);
};
const dom = renderDom();
if (renderFormItem) {
return (
renderFormItem(
rest.text,
{ mode, ...fieldProps, options, loading },
dom,
) ?? null
);
}
return dom;
}
return null;
};
export default React.forwardRef(FieldSelect);