-
Notifications
You must be signed in to change notification settings - Fork 336
/
Copy pathTreeSelect.tsx
365 lines (321 loc) · 12.3 KB
/
TreeSelect.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
import React, { useCallback, useMemo, useRef, forwardRef, ElementRef, useImperativeHandle } from 'react';
import { isFunction } from 'lodash-es';
import classNames from 'classnames';
import type { TdTreeSelectProps, TreeSelectValue } from './type';
import type { StyledProps, TreeOptionData } from '../common';
import useConfig from '../hooks/useConfig';
import useControlled from '../hooks/useControlled';
import Tree, { TreeProps } from '../tree';
import SelectInput, { SelectInputProps } from '../select-input/SelectInput';
import { usePersistFn } from '../hooks/usePersistFn';
import useSwitch from '../hooks/useSwitch';
import noop from '../_util/noop';
import { useTreeSelectUtils } from './hooks/useTreeSelectUtils';
import { SelectArrow } from './SelectArrow';
import { useTreeSelectPassThroughProps } from './hooks/useTreeSelectPassthroughProps';
import { useTreeSelectLocale } from './hooks/useTreeSelectLocale';
import { treeSelectDefaultProps } from './defaultProps';
import parseTNode from '../_util/parseTNode';
import useDefaultProps from '../hooks/useDefaultProps';
import { PopupRef } from '../popup';
import { InputRef } from '../input';
export interface TreeSelectProps<DataOption extends TreeOptionData = TreeOptionData>
extends TdTreeSelectProps<DataOption>,
StyledProps {}
export interface NodeOptions {
label: string;
value: string | number;
}
const useMergeFn = <T extends any[]>(...fns: Array<(...args: T) => void>) =>
usePersistFn((...args: T) => fns.forEach((fn) => fn?.(...args)));
type TreeSelectRefType = Partial<ElementRef<typeof Tree> & PopupRef & InputRef>;
const TreeSelect = forwardRef<TreeSelectRefType, TreeSelectProps>((originalProps, ref) => {
const props = useDefaultProps<TreeSelectProps<TreeOptionData>>(originalProps, treeSelectDefaultProps);
/* ---------------------------------config---------------------------------------- */
// 国际化文本初始化
const { placeholder, empty, loadingItem } = useTreeSelectLocale(props);
const { classPrefix } = useConfig();
/* ---------------------------------state---------------------------------------- */
const {
className,
onInputChange,
readonly,
disabled,
multiple,
prefixIcon,
loading,
size,
max,
data,
panelTopContent,
panelBottomContent,
filter: rawFilter,
filterable: rawFilterable,
onClear,
valueDisplay,
treeProps,
inputProps,
valueType,
collapsedItems,
onBlur,
onFocus,
onSearch,
onRemove,
onEnter,
} = props;
const selectInputProps = useTreeSelectPassThroughProps(props);
const [value, onChange] = useControlled(props, 'value', props.onChange);
const [popupVisible, setPopupVisible] = useControlled(props, 'popupVisible', props.onPopupVisibleChange);
const [hover, hoverAction] = useSwitch();
const [filterInput, setFilterInput] = useControlled(props, 'inputValue', onInputChange);
const treeRef = useRef<ElementRef<typeof Tree>>();
const selectInputRef = useRef<Partial<PopupRef & InputRef>>();
const tKeys = useMemo(
() => ({
value: 'value',
label: 'label',
children: 'children',
...props.keys,
}),
[props.keys],
);
const passThroughDefaultStore = useMemo<TreeSelectProps>(
() => ({
data,
treeProps: {
keys: tKeys,
...treeProps,
},
valueType,
}),
[tKeys, data, treeProps, valueType],
);
const { normalizeValue, formatValue, getNodeItem } = useTreeSelectUtils(passThroughDefaultStore, treeRef);
useImperativeHandle(ref, () => ({
...(selectInputRef.current || {}),
...(treeRef.current || {}),
}));
/* ---------------------------------computed value---------------------------------------- */
const defaultFilter = (text: string, option: TreeOptionData) => {
if (!text) return true;
// 过滤时会有空节点影响判断
if (!option.label && !option.value) return false;
if (option.label && typeof option.label === 'string') {
return option.label.includes(text);
}
if (option.data.text && typeof option.data.text === 'string') {
return option.data.text.includes(text);
}
return true;
};
// priority of onSearch is higher than props.filter
const filter = onSearch ? undefined : rawFilter || defaultFilter;
const filterable = rawFilterable || !!props.filter;
const normalizedValue = useMemo(() => {
const calcValue: TreeSelectValue[] = Array.isArray(value) ? value : [value];
return calcValue.reduce<NodeOptions[]>((result, value) => {
const normalized = normalizeValue(value);
typeof normalized.value !== 'undefined' && result.push(normalized);
return result;
}, []);
// data 发生变更时,normalizedValue 也需要更新
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [normalizeValue, value, data]);
const internalInputValue = useMemo(() => {
if (multiple) return normalizedValue;
// 可筛选、单选、弹框时内容为过滤值
return filterable && popupVisible ? filterInput : normalizedValue[0] || '';
}, [multiple, normalizedValue, filterable, popupVisible, filterInput]);
// @ts-ignore TODO: remove it
const normalizedValueDisplay: SelectInputProps['valueDisplay'] = useMemo(() => {
if (!valueDisplay) {
return;
}
if (multiple) {
return ({ onClose }) =>
isFunction(valueDisplay) ? valueDisplay({ value: normalizedValue, onClose }) : valueDisplay;
}
const displayNode = isFunction(valueDisplay)
? valueDisplay({
value: normalizedValue[0] || { [tKeys.label]: '', [tKeys.value]: undefined },
onClose: noop,
})
: valueDisplay;
return normalizedValue.length ? displayNode : '';
}, [valueDisplay, multiple, normalizedValue, tKeys]);
const internalInputValueDisplay: SelectInputProps['valueDisplay'] = useMemo(() => {
// 只有单选且下拉展开时需要隐藏 valueDisplay
if (filterable && !multiple && popupVisible) {
return undefined;
}
return normalizedValueDisplay;
}, [filterable, popupVisible, multiple, normalizedValueDisplay]);
const inputPlaceholder = useMemo(() => {
// 可筛选、单选、弹框且有值时提示当前值
if (filterable && !multiple && popupVisible && normalizedValue.length) {
// 设置了 valueDisplay 时,优先展示 valueDisplay
const valueDisplayPlaceholder = normalizedValueDisplay;
if (typeof valueDisplayPlaceholder === 'string') {
return valueDisplayPlaceholder;
}
return typeof normalizedValue[0].label === 'string' ? normalizedValue[0].label : String(normalizedValue[0].value);
}
return placeholder;
}, [filterable, multiple, popupVisible, normalizedValue, placeholder, normalizedValueDisplay]);
const showLoading = !disabled && loading;
/* ---------------------------------handler---------------------------------------- */
const handleFilter = useCallback<TreeProps['filter']>(
(node) => (filterable && filter ? filter(filterInput as string, node) : true),
[filter, filterInput, filterable],
);
const handleSingleChange = usePersistFn<TreeProps['onActive']>((value, context) => {
if (value.length > 0) {
const $value = Array.isArray(value) && value.length ? value[0] : undefined;
onChange(formatValue($value, context.node.label), {
...context,
data: context.node.data,
trigger: 'check',
});
}
// 单选选择后收起弹框
setPopupVisible(false, { ...context, trigger: 'trigger-element-click' });
});
const handleMultiChange = usePersistFn<TreeProps['onChange']>((value, context) => {
if (max === 0 || value.length <= max) {
onChange(
value.map((value) => formatValue(value, getNodeItem(value)?.label)),
{
...context,
data: context.node.data,
trigger: value.length > normalizedValue.length ? 'check' : 'uncheck',
},
);
}
});
const onInnerPopupVisibleChange: SelectInputProps['onPopupVisibleChange'] = (visible, ctx) => {
setPopupVisible(visible, { e: ctx.e });
};
const handleClear = usePersistFn<SelectInputProps['onClear']>((ctx) => {
ctx.e.stopPropagation();
onChange(multiple ? [] : formatValue(undefined), {
node: null,
data: null,
trigger: 'clear',
e: ctx.e as React.MouseEvent<any, any>,
});
onClear?.(ctx);
// 清空后收起弹框
setPopupVisible(false, { trigger: 'clear' });
});
const handleTagChange = usePersistFn<SelectInputProps['onTagChange']>((tags, ctx) => {
if (ctx.trigger === 'tag-remove' || ctx.trigger === 'backspace') {
const { index, e, trigger } = ctx;
const node = getNodeItem(normalizedValue[index].value);
onChange(
normalizedValue.filter((value, i) => i !== index).map(({ value, label }) => formatValue(value, label)),
{ node, data: node.data, trigger, e },
);
onRemove?.({
value: node.value,
node,
index,
data: { value: node.value, label: node.label, ...node.data },
e,
trigger,
});
}
});
const getTreeSelectEventValue = () => {
const selectedOptions = Array.isArray(normalizedValue) ? normalizedValue : [normalizedValue];
const value = selectedOptions.map((item) => (valueType === 'object' ? item : item[tKeys.value]));
return multiple ? value : value[0];
};
const handleBlur = usePersistFn<SelectInputProps['onBlur']>((_, ctx) => {
onBlur?.({ value: getTreeSelectEventValue(), ...ctx });
});
const handleFocus = usePersistFn<SelectInputProps['onFocus']>((_, ctx) => {
onFocus?.({ value: getTreeSelectEventValue(), e: ctx.e });
});
const handleEnter = usePersistFn<SelectInputProps['onEnter']>((_, ctx) => {
onSearch?.(ctx.inputValue, { e: ctx.e });
onEnter?.({ inputValue: ctx.inputValue, e: ctx.e, value: getTreeSelectEventValue() });
});
const handleFilterChange = usePersistFn<SelectInputProps['onInputChange']>((value, ctx) => {
if (ctx.trigger === 'clear') return;
setFilterInput(value, ctx);
onSearch?.(value, { e: ctx.e });
});
/* ---------------------------------render---------------------------------------- */
const renderTree = () => {
if (readonly) return empty;
if (showLoading) return loadingItem;
return (
<>
{panelTopContent}
<Tree
ref={treeRef}
hover
transition
filter={filterInput ? handleFilter : null}
data={data}
disabled={disabled}
empty={empty}
expandOnClickNode={false}
allowFoldNodeOnFilter
keys={tKeys}
{...(multiple
? {
checkable: true,
onChange: handleMultiChange,
value: normalizedValue.map(({ value }) => value),
}
: {
activable: true,
actived: normalizedValue.map(({ value }) => value),
onActive: handleSingleChange,
})}
{...treeProps}
/>
{panelBottomContent}
</>
);
};
return (
<SelectInput
status={props.status}
tips={props.tips}
{...props.selectInputProps}
{...selectInputProps}
ref={selectInputRef}
className={classNames(`${classPrefix}-tree-select`, className)}
value={internalInputValue}
inputValue={filterInput}
panel={renderTree()}
allowInput={filterable}
inputProps={{ ...inputProps, size }}
tagInputProps={{ size, excessTagsDisplayType: 'break-line', inputProps, tagProps: props.tagProps }}
placeholder={inputPlaceholder}
popupVisible={popupVisible && !disabled}
onInputChange={handleFilterChange}
onPopupVisibleChange={onInnerPopupVisibleChange}
onFocus={useMergeFn(handleFocus)}
onBlur={useMergeFn(handleBlur)}
onClear={handleClear}
onTagChange={handleTagChange}
onEnter={handleEnter}
onMouseenter={hoverAction.on}
onMouseleave={hoverAction.off}
suffixIcon={
props.suffixIcon ||
(readonly ? null : (
<SelectArrow isActive={popupVisible} isHighlight={hover || popupVisible} disabled={disabled} />
))
}
collapsedItems={collapsedItems}
label={parseTNode(prefixIcon)}
valueDisplay={internalInputValueDisplay}
/>
);
});
TreeSelect.displayName = 'TreeSelect';
export default TreeSelect;