-
Notifications
You must be signed in to change notification settings - Fork 93
Expand file tree
/
Copy pathCascader.tsx
More file actions
300 lines (268 loc) · 9.88 KB
/
Cascader.tsx
File metadata and controls
300 lines (268 loc) · 9.88 KB
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
import { useDeepCompareEffect } from 'ahooks';
import classNames from 'classnames';
import last from 'lodash-es/last';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { CloseIcon, ChevronRightIcon } from 'tdesign-icons-react';
import useDefault from '../_util/useDefault';
import { Popup } from '../popup';
import { RadioGroup } from '../radio';
import Tabs from '../tabs';
import { StyledProps, TNode, TreeOptionData } from '../common';
import { usePrefixClass } from '../hooks/useClass';
import useDefaultProps from '../hooks/useDefaultProps';
import parseTNode from '../_util/parseTNode';
import { cascaderDefaultProps } from './defaultProps';
import { TdCascaderProps } from './type';
export interface CascaderProps extends TdCascaderProps, StyledProps {}
const Cascader: React.FC<CascaderProps> = (props) => {
const cascaderClass = usePrefixClass('cascader');
const {
className,
style,
value,
defaultValue,
visible,
title,
header,
middleContent,
placeholder,
theme,
subTitles,
options: inputOptions,
overlayProps,
keys,
checkStrictly,
closeBtn,
onChange,
onClose,
onPick,
} = useDefaultProps<CascaderProps>(props, cascaderDefaultProps);
const [internalValue, setInternalValue] = useDefault(value, defaultValue, onChange);
const [internalVisible, setInternalVisible] = useDefault(visible, false, () => ({}));
const [internalSelectedValues, setInternalSelectedValues] = useState<CascaderProps['value'][]>([]);
// 根据 inputOptions 和 key 重新构建 options
const options = useMemo(() => {
const { label = 'label', value = 'value', children = 'children', disabled = 'disabled' } = keys || {};
const convert = (options: TreeOptionData[]) =>
options.map((item) => ({
label: item[label],
value: item[value],
children: Array.isArray(item[children]) ? convert(item[children]) : false,
disabled: item[disabled],
}));
return convert(inputOptions);
}, [inputOptions, keys]);
const getOptionsList = useCallback((options: TreeOptionData[], internalSelectedValues: CascaderProps['value'][]) => {
const optionsList: TreeOptionData[][] = [options];
for (const value of internalSelectedValues) {
const lastOptions = last(optionsList);
const next = lastOptions.find((item) => item.value === value);
if (!next || !Array.isArray(next.children)) {
break;
}
optionsList.push(next.children);
}
return optionsList;
}, []);
const optionsList = useMemo(
() => getOptionsList(options, internalSelectedValues),
[getOptionsList, options, internalSelectedValues],
);
const [stepIndex, setStepIndex] = useState(0);
const labelList = useMemo(() => {
const labelList: {
label: TNode;
isPlaceholder: boolean;
}[] = [];
optionsList.forEach((options, index) => {
const value = internalSelectedValues[index];
const target = options.find((item) => item.value === value);
if (target) {
labelList.push({
label: target.label,
isPlaceholder: false,
});
return;
}
labelList.push({
label: placeholder,
isPlaceholder: true,
});
});
return labelList;
}, [optionsList, internalSelectedValues, placeholder]);
const selectedValuesByInterValue = useMemo(() => {
/**
* checkStrictly true 从外到内 匹配上就挺 返回整个链路上的value
* checkStrictly false 最后一级的 value 匹配时,返回整个链路上的value
*/
const findValues = (options: TreeOptionData[]): CascaderProps['value'][] => {
for (const item of options) {
if (checkStrictly && item.value === internalValue) {
return [item.value];
}
const isLast = !(Array.isArray(item.children) && item.children.length);
if (isLast) {
if (item.value === internalValue) {
return [item.value];
}
continue;
}
const targetValue = findValues(item.children as TreeOptionData[]);
if (targetValue.length) {
return [item.value, ...targetValue];
}
}
return [];
};
return findValues(options);
}, [options, internalValue, checkStrictly]);
// 当 selectedValuesByInterValue 深度变化 的时候再控制 selectedValues
useDeepCompareEffect(() => {
setInternalSelectedValues(selectedValuesByInterValue);
setStepIndex(selectedValuesByInterValue.length);
}, [selectedValuesByInterValue]);
useEffect(() => {
const reviseStepIndex = Math.max(Math.min(stepIndex, optionsList.length - 1), 0);
if (reviseStepIndex !== stepIndex) {
setStepIndex(reviseStepIndex);
}
}, [optionsList, stepIndex]);
// 结束了
const onFinish = useCallback(
(selectedValues: CascaderProps['value'][]) => {
const selectedOptions = [...optionsList].slice(0, selectedValues.length).map((options, index) => {
const target = options.find((item) => item.value === selectedValues[index]);
const { label = 'label', value = 'value' } = keys || {};
return {
[label]: target?.label || '',
[value]: target?.value || '',
};
});
setInternalValue(last(selectedValues), selectedOptions as any);
onClose?.('finish');
},
[onClose, optionsList, setInternalValue, keys],
);
return (
<Popup
visible={internalVisible}
placement="bottom"
overlayProps={overlayProps}
onVisibleChange={(visible, trigger) => {
setInternalVisible(visible);
onClose?.(trigger);
}}
>
<div className={classNames(cascaderClass, className)} style={style}>
<div className={`${cascaderClass}__title`}>{parseTNode(title)}</div>
<div
className={`${cascaderClass}__close-btn`}
onClick={() => {
if (checkStrictly) {
onFinish(internalSelectedValues);
return;
}
setInternalVisible(false);
onClose?.('close-btn');
}}
>
{closeBtn === true ? <CloseIcon size={24} /> : parseTNode(closeBtn)}
</div>
{parseTNode(header)}
<div className={`${cascaderClass}__content`}>
{labelList.length && (
<div>
{theme === 'step' ? (
<div className={`${cascaderClass}__steps`}>
{labelList.map((labeItem, index) => (
<div
key={index}
className={`${cascaderClass}__step`}
onClick={() => {
setStepIndex(index);
}}
>
<div
className={classNames(`${cascaderClass}__step-dot`, {
[`${cascaderClass}__step-dot--active`]: !labeItem.isPlaceholder,
[`${cascaderClass}__step-dot--last`]: index === labelList.length - 1,
})}
/>
<div
className={classNames(`${cascaderClass}__step-label`, {
[`${cascaderClass}__step-label--active`]: index === stepIndex,
})}
>
{parseTNode(labeItem.label)}
</div>
<ChevronRightIcon size={22} className={`${cascaderClass}__step-arrow`} />
</div>
))}
</div>
) : null}
{theme === 'tab' && internalVisible ? (
<Tabs
list={labelList.map((item, index) => ({
label: item.label,
value: index,
}))}
spaceEvenly={false}
value={stepIndex}
onChange={(value: number) => {
setStepIndex(value);
}}
/>
) : null}
</div>
)}
{parseTNode(middleContent)}
{subTitles[stepIndex] ? (
<div className={`${cascaderClass}__options-title`}>{subTitles[stepIndex]}</div>
) : null}
<div
className={`${cascaderClass}__options-container`}
style={{
width: `${optionsList.length}00vw`,
transform: `translateX(-${stepIndex}00vw)`,
}}
>
{optionsList.map((curOptions, index) => (
<div className={`${cascaderClass}__options`} key={index}>
<div className={`${cascaderClass}-radio-group-${index}`}>
<RadioGroup
placement="right"
icon="line"
borderless
value={internalSelectedValues[index]}
options={curOptions}
onChange={(value: string | number) => {
const targetIndex = curOptions.findIndex((item) => item.value === value);
const target = curOptions[targetIndex];
const selectedValues = [...internalSelectedValues].slice(0, index);
selectedValues.push(value);
setInternalSelectedValues(selectedValues);
setStepIndex(index + 1);
onPick?.({
value,
label: String(target?.label || ''),
index: targetIndex,
level: index,
});
if (Array.isArray(target?.children)) {
return;
}
onFinish(selectedValues);
}}
></RadioGroup>
</div>
</div>
))}
</div>
</div>
</div>
</Popup>
);
};
Cascader.displayName = 'Cascader';
export default Cascader;