-
Notifications
You must be signed in to change notification settings - Fork 196
/
Copy pathTreeSelect.tsx
741 lines (646 loc) · 21.4 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
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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
import type { BaseSelectPropsWithoutPrivate, BaseSelectRef } from '@rc-component/select';
import { BaseSelect } from '@rc-component/select';
import useId from '@rc-component/select/lib/hooks/useId';
import type { IconType } from 'rc-tree/lib/interface';
import type { ExpandAction } from 'rc-tree/lib/Tree';
import { conductCheck } from 'rc-tree/lib/utils/conductUtil';
import useMergedState from '@rc-component/util/lib/hooks/useMergedState';
import * as React from 'react';
import useCache from './hooks/useCache';
import useCheckedKeys from './hooks/useCheckedKeys';
import useDataEntities from './hooks/useDataEntities';
import useFilterTreeData from './hooks/useFilterTreeData';
import useRefFunc from './hooks/useRefFunc';
import useTreeData from './hooks/useTreeData';
import LegacyContext from './LegacyContext';
import OptionList from './OptionList';
import TreeNode from './TreeNode';
import type { TreeSelectContextProps } from './TreeSelectContext';
import TreeSelectContext from './TreeSelectContext';
import { fillAdditionalInfo, fillLegacyProps } from './utils/legacyUtil';
import type { CheckedStrategy } from './utils/strategyUtil';
import { formatStrategyValues, SHOW_ALL, SHOW_CHILD, SHOW_PARENT } from './utils/strategyUtil';
import { fillFieldNames, isNil, toArray } from './utils/valueUtil';
import warningProps from './utils/warningPropsUtil';
import type {
LabeledValueType,
SafeKey,
Key,
DataNode,
SimpleModeConfig,
ChangeEventExtra,
SelectSource,
DefaultValueType,
FieldNames,
LegacyDataNode,
} from './interface';
export interface TreeSelectProps<ValueType = any, OptionType extends DataNode = DataNode>
extends Omit<BaseSelectPropsWithoutPrivate, 'mode'> {
prefixCls?: string;
id?: string;
children?: React.ReactNode;
// >>> Value
value?: ValueType;
defaultValue?: ValueType;
onChange?: (value: ValueType, labelList: React.ReactNode[], extra: ChangeEventExtra) => void;
// >>> Search
searchValue?: string;
/** @deprecated Use `searchValue` instead */
inputValue?: string;
onSearch?: (value: string) => void;
autoClearSearchValue?: boolean;
filterTreeNode?: boolean | ((inputValue: string, treeNode: DataNode) => boolean);
treeNodeFilterProp?: string;
// >>> Select
onSelect?: (value: ValueType, option: OptionType) => void;
onDeselect?: (value: ValueType, option: OptionType) => void;
// >>> Selector
showCheckedStrategy?: CheckedStrategy;
treeNodeLabelProp?: string;
// >>> Field Names
fieldNames?: FieldNames;
// >>> Mode
multiple?: boolean;
treeCheckable?: boolean | React.ReactNode;
treeCheckStrictly?: boolean;
labelInValue?: boolean;
maxCount?: number;
// >>> Data
treeData?: OptionType[];
treeDataSimpleMode?: boolean | SimpleModeConfig;
loadData?: (dataNode: LegacyDataNode) => Promise<unknown>;
treeLoadedKeys?: SafeKey[];
onTreeLoad?: (loadedKeys: SafeKey[]) => void;
// >>> Expanded
treeDefaultExpandAll?: boolean;
treeExpandedKeys?: SafeKey[];
treeDefaultExpandedKeys?: SafeKey[];
onTreeExpand?: (expandedKeys: SafeKey[]) => void;
treeExpandAction?: ExpandAction;
// >>> Options
virtual?: boolean;
listHeight?: number;
listItemHeight?: number;
listItemScrollOffset?: number;
onPopupVisibleChange?: (open: boolean) => void;
treeTitleRender?: (node: OptionType) => React.ReactNode;
// >>> Tree
treeLine?: boolean;
treeIcon?: IconType;
showTreeIcon?: boolean;
switcherIcon?: IconType;
treeMotion?: any;
}
function isRawValue(value: SafeKey | LabeledValueType): value is SafeKey {
return !value || typeof value !== 'object';
}
const TreeSelect = React.forwardRef<BaseSelectRef, TreeSelectProps>((props, ref) => {
const {
id,
prefixCls = 'rc-tree-select',
// Value
value,
defaultValue,
onChange,
onSelect,
onDeselect,
// Search
searchValue,
inputValue,
onSearch,
autoClearSearchValue = true,
filterTreeNode,
treeNodeFilterProp = 'value',
// Selector
showCheckedStrategy,
treeNodeLabelProp,
// Mode
multiple,
treeCheckable,
treeCheckStrictly,
labelInValue,
maxCount,
// FieldNames
fieldNames,
// Data
treeDataSimpleMode,
treeData,
children,
loadData,
treeLoadedKeys,
onTreeLoad,
// Expanded
treeDefaultExpandAll,
treeExpandedKeys,
treeDefaultExpandedKeys,
onTreeExpand,
treeExpandAction,
// Options
virtual,
listHeight = 200,
listItemHeight = 20,
listItemScrollOffset = 0,
onPopupVisibleChange,
popupMatchSelectWidth = true,
// Tree
treeLine,
treeIcon,
showTreeIcon,
switcherIcon,
treeMotion,
treeTitleRender,
onPopupScroll,
...restProps
} = props;
const mergedId = useId(id);
const treeConduction = treeCheckable && !treeCheckStrictly;
const mergedCheckable = treeCheckable || treeCheckStrictly;
const mergedLabelInValue = treeCheckStrictly || labelInValue;
const mergedMultiple = mergedCheckable || multiple;
const [internalValue, setInternalValue] = useMergedState(defaultValue, { value });
// `multiple` && `!treeCheckable` should be show all
const mergedShowCheckedStrategy = React.useMemo(() => {
if (!treeCheckable) {
return SHOW_ALL;
}
return showCheckedStrategy || SHOW_CHILD;
}, [showCheckedStrategy, treeCheckable]);
// ========================== Warning ===========================
if (process.env.NODE_ENV !== 'production') {
warningProps(props);
}
// ========================= FieldNames =========================
const mergedFieldNames: FieldNames = React.useMemo(
() => fillFieldNames(fieldNames),
/* eslint-disable react-hooks/exhaustive-deps */
[JSON.stringify(fieldNames)],
/* eslint-enable react-hooks/exhaustive-deps */
);
// =========================== Search ===========================
const [mergedSearchValue, setSearchValue] = useMergedState('', {
value: searchValue !== undefined ? searchValue : inputValue,
postState: search => search || '',
});
const onInternalSearch = searchText => {
setSearchValue(searchText);
onSearch?.(searchText);
};
// ============================ Data ============================
// `useTreeData` only do convert of `children` or `simpleMode`.
// Else will return origin `treeData` for perf consideration.
// Do not do anything to loop the data.
const mergedTreeData = useTreeData(treeData, children, treeDataSimpleMode);
const { keyEntities, valueEntities } = useDataEntities(mergedTreeData, mergedFieldNames);
/** Get `missingRawValues` which not exist in the tree yet */
const splitRawValues = React.useCallback(
(newRawValues: SafeKey[]) => {
const missingRawValues = [];
const existRawValues = [];
// Keep missing value in the cache
newRawValues.forEach(val => {
if (valueEntities.has(val)) {
existRawValues.push(val);
} else {
missingRawValues.push(val);
}
});
return { missingRawValues, existRawValues };
},
[valueEntities],
);
// Filtered Tree
const filteredTreeData = useFilterTreeData(mergedTreeData, mergedSearchValue, {
fieldNames: mergedFieldNames,
treeNodeFilterProp,
filterTreeNode,
});
// =========================== Label ============================
const getLabel = React.useCallback(
(item: DataNode) => {
if (item) {
if (treeNodeLabelProp) {
return item[treeNodeLabelProp];
}
// Loop from fieldNames
const { _title: titleList } = mergedFieldNames;
for (let i = 0; i < titleList.length; i += 1) {
const title = item[titleList[i]];
if (title !== undefined) {
return title;
}
}
}
},
[mergedFieldNames, treeNodeLabelProp],
);
// ========================= Wrap Value =========================
const toLabeledValues = React.useCallback((draftValues: DefaultValueType) => {
const values = toArray(draftValues);
return values.map(val => {
if (isRawValue(val)) {
return { value: val };
}
return val;
});
}, []);
const convert2LabelValues = React.useCallback(
(draftValues: DefaultValueType) => {
const values = toLabeledValues(draftValues);
return values.map(item => {
let { label: rawLabel } = item;
const { value: rawValue, halfChecked: rawHalfChecked } = item;
let rawDisabled: boolean | undefined;
const entity = valueEntities.get(rawValue);
// Fill missing label & status
if (entity) {
rawLabel = treeTitleRender
? treeTitleRender(entity.node)
: (rawLabel ?? getLabel(entity.node));
rawDisabled = entity.node.disabled;
} else if (rawLabel === undefined) {
// We try to find in current `labelInValue` value
const labelInValueItem = toLabeledValues(internalValue).find(
labeledItem => labeledItem.value === rawValue,
);
rawLabel = labelInValueItem.label;
}
return {
label: rawLabel,
value: rawValue,
halfChecked: rawHalfChecked,
disabled: rawDisabled,
};
});
},
[valueEntities, getLabel, toLabeledValues, internalValue],
);
// =========================== Values ===========================
const rawMixedLabeledValues = React.useMemo(
() => toLabeledValues(internalValue === null ? [] : internalValue),
[toLabeledValues, internalValue],
);
// Split value into full check and half check
const [rawLabeledValues, rawHalfLabeledValues] = React.useMemo(() => {
const fullCheckValues: LabeledValueType[] = [];
const halfCheckValues: LabeledValueType[] = [];
rawMixedLabeledValues.forEach(item => {
if (item.halfChecked) {
halfCheckValues.push(item);
} else {
fullCheckValues.push(item);
}
});
return [fullCheckValues, halfCheckValues];
}, [rawMixedLabeledValues]);
// const [mergedValues] = useCache(rawLabeledValues);
const rawValues = React.useMemo(
() => rawLabeledValues.map(item => item.value),
[rawLabeledValues],
);
// Convert value to key. Will fill missed keys for conduct check.
const [rawCheckedValues, rawHalfCheckedValues] = useCheckedKeys(
rawLabeledValues,
rawHalfLabeledValues,
treeConduction,
keyEntities,
);
// Convert rawCheckedKeys to check strategy related values
const displayValues = React.useMemo(() => {
// Collect keys which need to show
const displayKeys = formatStrategyValues(
rawCheckedValues as SafeKey[],
mergedShowCheckedStrategy,
keyEntities,
mergedFieldNames,
);
// Convert to value and filled with label
const values = displayKeys.map(key => keyEntities[key]?.node?.[mergedFieldNames.value] ?? key);
// Back fill with origin label
const labeledValues = values.map(val => {
const targetItem = rawLabeledValues.find(item => item.value === val);
const label = labelInValue ? targetItem?.label : treeTitleRender?.(targetItem);
return {
value: val,
label,
};
});
const rawDisplayValues = convert2LabelValues(labeledValues);
const firstVal = rawDisplayValues[0];
if (!mergedMultiple && firstVal && isNil(firstVal.value) && isNil(firstVal.label)) {
return [];
}
return rawDisplayValues.map(item => ({
...item,
label: item.label ?? item.value,
}));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [
mergedFieldNames,
mergedMultiple,
rawCheckedValues,
rawLabeledValues,
convert2LabelValues,
mergedShowCheckedStrategy,
keyEntities,
]);
const [cachedDisplayValues] = useCache(displayValues);
// ========================== MaxCount ==========================
const mergedMaxCount = React.useMemo(() => {
if (
mergedMultiple &&
(mergedShowCheckedStrategy === 'SHOW_CHILD' || treeCheckStrictly || !treeCheckable)
) {
return maxCount;
}
return null;
}, [maxCount, mergedMultiple, treeCheckStrictly, mergedShowCheckedStrategy, treeCheckable]);
// =========================== Change ===========================
const triggerChange = useRefFunc(
(
newRawValues: SafeKey[],
extra: { triggerValue?: SafeKey; selected?: boolean },
source: SelectSource,
) => {
const formattedKeyList = formatStrategyValues(
newRawValues,
mergedShowCheckedStrategy,
keyEntities,
mergedFieldNames,
);
// Not allow pass with `maxCount`
if (mergedMaxCount && formattedKeyList.length > mergedMaxCount) {
return;
}
const labeledValues = convert2LabelValues(newRawValues);
setInternalValue(labeledValues);
// Clean up if needed
if (autoClearSearchValue) {
setSearchValue('');
}
// Generate rest parameters is costly, so only do it when necessary
if (onChange) {
let eventValues: SafeKey[] = newRawValues;
if (treeConduction) {
eventValues = formattedKeyList.map(key => {
const entity = valueEntities.get(key);
return entity ? entity.node[mergedFieldNames.value] : key;
});
}
const { triggerValue, selected } = extra || {
triggerValue: undefined,
selected: undefined,
};
let returnRawValues: (LabeledValueType | SafeKey)[] = eventValues;
// We need fill half check back
if (treeCheckStrictly) {
const halfValues = rawHalfLabeledValues.filter(item => !eventValues.includes(item.value));
returnRawValues = [...returnRawValues, ...halfValues];
}
const returnLabeledValues = convert2LabelValues(returnRawValues);
const additionalInfo = {
// [Legacy] Always return as array contains label & value
preValue: rawLabeledValues,
triggerValue,
} as ChangeEventExtra;
// [Legacy] Fill legacy data if user query.
// This is expansive that we only fill when user query
// https://github.com/react-component/tree-select/blob/fe33eb7c27830c9ac70cd1fdb1ebbe7bc679c16a/src/Select.jsx
let showPosition = true;
if (treeCheckStrictly || (source === 'selection' && !selected)) {
showPosition = false;
}
fillAdditionalInfo(
additionalInfo,
triggerValue,
newRawValues,
mergedTreeData,
showPosition,
mergedFieldNames,
);
if (mergedCheckable) {
additionalInfo.checked = selected;
} else {
additionalInfo.selected = selected;
}
const returnValues = mergedLabelInValue
? returnLabeledValues
: returnLabeledValues.map(item => item.value);
onChange(
mergedMultiple ? returnValues : returnValues[0],
mergedLabelInValue ? null : returnLabeledValues.map(item => item.label),
additionalInfo,
);
}
},
);
// ========================== Options ===========================
/** Trigger by option list */
const onOptionSelect = React.useCallback(
(selectedKey: SafeKey, { selected, source }: { selected: boolean; source: SelectSource }) => {
const entity = keyEntities[selectedKey];
const node = entity?.node;
const selectedValue = node?.[mergedFieldNames.value] ?? selectedKey;
// Never be falsy but keep it safe
if (!mergedMultiple) {
// Single mode always set value
triggerChange([selectedValue], { selected: true, triggerValue: selectedValue }, 'option');
} else {
let newRawValues = selected
? [...rawValues, selectedValue]
: rawCheckedValues.filter(v => v !== selectedValue);
// Add keys if tree conduction
if (treeConduction) {
// Should keep missing values
const { missingRawValues, existRawValues } = splitRawValues(newRawValues);
const keyList = existRawValues.map(val => valueEntities.get(val).key);
// Conduction by selected or not
let checkedKeys: Key[];
if (selected) {
({ checkedKeys } = conductCheck(keyList, true, keyEntities));
} else {
({ checkedKeys } = conductCheck(
keyList,
{ checked: false, halfCheckedKeys: rawHalfCheckedValues },
keyEntities,
));
}
// Fill back of keys
newRawValues = [
...missingRawValues,
...checkedKeys.map(key => keyEntities[key as SafeKey].node[mergedFieldNames.value]),
];
}
triggerChange(newRawValues, { selected, triggerValue: selectedValue }, source || 'option');
}
// Trigger select event
if (selected || !mergedMultiple) {
onSelect?.(selectedValue, fillLegacyProps(node));
} else {
onDeselect?.(selectedValue, fillLegacyProps(node));
}
},
[
splitRawValues,
valueEntities,
keyEntities,
mergedFieldNames,
mergedMultiple,
rawValues,
triggerChange,
treeConduction,
onSelect,
onDeselect,
rawCheckedValues,
rawHalfCheckedValues,
maxCount,
],
);
// ========================== Dropdown ==========================
const onInternalPopupVisibleChange = React.useCallback(
(open: boolean) => {
if (onPopupVisibleChange) {
onPopupVisibleChange(open);
}
},
[onPopupVisibleChange],
);
// ====================== Display Change ========================
const onDisplayValuesChange = useRefFunc((newValues, info) => {
const newRawValues = newValues.map(item => item.value);
if (info.type === 'clear') {
triggerChange(newRawValues, {}, 'selection');
return;
}
// TreeSelect only have multiple mode which means display change only has remove
if (info.values.length) {
onOptionSelect(info.values[0].value, { selected: false, source: 'selection' });
}
});
// ========================== Context ===========================
const treeSelectContext = React.useMemo<TreeSelectContextProps>(() => {
return {
virtual,
popupMatchSelectWidth,
listHeight,
listItemHeight,
listItemScrollOffset,
treeData: filteredTreeData,
fieldNames: mergedFieldNames,
onSelect: onOptionSelect,
treeExpandAction,
treeTitleRender,
onPopupScroll,
leftMaxCount: maxCount === undefined ? null : maxCount - cachedDisplayValues.length,
leafCountOnly:
mergedShowCheckedStrategy === 'SHOW_CHILD' && !treeCheckStrictly && !!treeCheckable,
valueEntities,
};
}, [
virtual,
popupMatchSelectWidth,
listHeight,
listItemHeight,
listItemScrollOffset,
filteredTreeData,
mergedFieldNames,
onOptionSelect,
treeExpandAction,
treeTitleRender,
onPopupScroll,
maxCount,
cachedDisplayValues.length,
mergedShowCheckedStrategy,
treeCheckStrictly,
treeCheckable,
valueEntities,
]);
// ======================= Legacy Context =======================
const legacyContext = React.useMemo(
() => ({
checkable: mergedCheckable,
loadData,
treeLoadedKeys,
onTreeLoad,
checkedKeys: rawCheckedValues,
halfCheckedKeys: rawHalfCheckedValues,
treeDefaultExpandAll,
treeExpandedKeys,
treeDefaultExpandedKeys,
onTreeExpand,
treeIcon,
treeMotion,
showTreeIcon,
switcherIcon,
treeLine,
treeNodeFilterProp,
keyEntities,
}),
[
mergedCheckable,
loadData,
treeLoadedKeys,
onTreeLoad,
rawCheckedValues,
rawHalfCheckedValues,
treeDefaultExpandAll,
treeExpandedKeys,
treeDefaultExpandedKeys,
onTreeExpand,
treeIcon,
treeMotion,
showTreeIcon,
switcherIcon,
treeLine,
treeNodeFilterProp,
keyEntities,
],
);
// =========================== Render ===========================
return (
<TreeSelectContext.Provider value={treeSelectContext}>
<LegacyContext.Provider value={legacyContext}>
<BaseSelect
ref={ref}
{...restProps}
// >>> MISC
id={mergedId}
prefixCls={prefixCls}
mode={mergedMultiple ? 'multiple' : undefined}
// >>> Display Value
displayValues={cachedDisplayValues}
onDisplayValuesChange={onDisplayValuesChange}
// >>> Search
searchValue={mergedSearchValue}
onSearch={onInternalSearch}
// >>> Options
OptionList={OptionList}
emptyOptions={!mergedTreeData.length}
onPopupVisibleChange={onInternalPopupVisibleChange}
popupMatchSelectWidth={popupMatchSelectWidth}
/>
</LegacyContext.Provider>
</TreeSelectContext.Provider>
);
});
// Assign name for Debug
if (process.env.NODE_ENV !== 'production') {
TreeSelect.displayName = 'TreeSelect';
}
const GenericTreeSelect = TreeSelect as unknown as (<
ValueType = any,
OptionType extends DataNode = DataNode,
>(
props: React.PropsWithChildren<TreeSelectProps<ValueType, OptionType>> & {
ref?: React.Ref<BaseSelectRef>;
},
) => React.ReactElement) & {
TreeNode: typeof TreeNode;
SHOW_ALL: typeof SHOW_ALL;
SHOW_PARENT: typeof SHOW_PARENT;
SHOW_CHILD: typeof SHOW_CHILD;
};
GenericTreeSelect.TreeNode = TreeNode;
GenericTreeSelect.SHOW_ALL = SHOW_ALL;
GenericTreeSelect.SHOW_PARENT = SHOW_PARENT;
GenericTreeSelect.SHOW_CHILD = SHOW_CHILD;
export default GenericTreeSelect;