forked from Tencent/tdesign-vue
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathselect.tsx
More file actions
566 lines (531 loc) · 18.1 KB
/
select.tsx
File metadata and controls
566 lines (531 loc) · 18.1 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
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
import {
computed,
defineComponent,
ref,
SetupContext,
toRefs,
watch,
nextTick,
getCurrentInstance,
provide,
} from '@vue/composition-api';
import isFunction from 'lodash/isFunction';
import debounce from 'lodash/debounce';
import get from 'lodash/get';
import cloneDeep from 'lodash/cloneDeep';
import isArray from 'lodash/isArray';
import useDefaultValue from '../hooks/useDefaultValue';
import { useTNodeJSX } from '../hooks/tnode';
import { useConfig, usePrefixClass } from '../config-provider/useConfig';
import { TdSelectProps, SelectValue, TdOptionProps } from './type';
import props from './props';
import TLoading from '../loading';
import Popup, { PopupVisibleChangeContext } from '../popup';
import TInput from '../input/index';
import Tag from '../tag/index';
import SelectInput, {
SelectInputValue,
SelectInputChangeContext,
SelectInputValueChangeContext,
} from '../select-input';
import FakeArrow from '../common-components/fake-arrow';
import Option from './option';
import SelectPanel from './select-panel';
import { getSingleContent, getMultipleContent, getNewMultipleValue } from './util';
import useSelectOptions from './hooks/useSelectOptions';
export type OptionInstance = InstanceType<typeof Option>;
export default defineComponent({
name: 'TSelect',
props: { ...props },
components: {
TInput,
TLoading,
Tag,
Popup,
TOption: Option,
FakeArrow,
SelectPanel,
},
setup(props: TdSelectProps, context: SetupContext) {
const { t, global } = useConfig('select');
const renderTNode = useTNodeJSX();
const instance = getCurrentInstance();
const selectInputRef = ref<HTMLElement>(null);
const popupOpenTime = ref(250);
const formDisabled = ref();
const COMPONENT_NAME = usePrefixClass('select');
const { classPrefix } = useConfig('classPrefix');
const {
valueType,
disabled,
size,
value: valueProps,
multiple,
placeholder,
loading,
max,
reserveKeyword,
inputValue,
popupVisible,
minCollapsedNum,
} = toRefs(props);
const keys = computed(() => ({
label: props.keys?.label || 'label',
value: props.keys?.value || 'value',
}));
const { options: innerOptions, optionsMap, optionsList } = useSelectOptions(props, context, keys);
const [value, setValue] = useDefaultValue(valueProps, props.defaultValue, props.onChange, 'value', 'change');
const innerValue = computed(() => {
if (valueType.value === 'object') {
return multiple.value
? (value.value as SelectValue[]).map((option) => option[keys.value.value])
: value.value[keys.value.value];
}
return value.value;
});
const setInnerValue: TdSelectProps['onChange'] = (newVal: SelectValue | SelectValue[], e) => {
if (valueType.value === 'object') {
const { value: valueOfKeys, label: labelOfKeys } = keys.value;
// 若为多选情况,将历史 value 加入 option 待取列表,兼容远程搜索改变 options 数组后旧选项无法找到的问题
const oldValueMap = new Map<SelectValue, TdOptionProps>();
if (multiple.value) {
(value.value as TdOptionProps[]).forEach((option) => {
oldValueMap.set(option[valueOfKeys], option);
});
}
const getOption = (val: SelectValue) => {
const option = optionsMap.value.get(val) || oldValueMap.get(val);
return {
[valueOfKeys]: get(option, valueOfKeys),
[labelOfKeys]: get(option, labelOfKeys),
};
};
// eslint-disable-next-line no-param-reassign
newVal = multiple.value ? (newVal as SelectValue[]).map((val) => getOption(val)) : getOption(newVal);
}
if (newVal === value.value) return;
setValue(newVal, e);
};
const [tInputValue, setTInputValue] = useDefaultValue(
inputValue,
props.defaultInputValue || '',
props.onInputChange,
'inputValue',
'input-change',
);
const [innerPopupVisible, setInnerPopupVisible] = useDefaultValue(
popupVisible,
false,
(visible: boolean, context: PopupVisibleChangeContext) => {
props.onPopupVisibleChange?.(visible, context);
props.onVisibleChange?.(visible);
instance.emit('visible-change', visible);
},
'popupVisible',
'popup-visible-change',
);
const isDisabled = computed(() => formDisabled.value || disabled.value);
const isLoading = computed(() => loading.value && !isDisabled.value);
// 是否支持筛选
const isFilterable = computed(() => Boolean(props.filterable || global.value.filterable || isFunction(props.filter)));
// 选中项是否已达最大数量 max 限制
const isReachMaxLimit = computed(
() => multiple.value && max.value !== 0 && max.value <= (innerValue.value as SelectValue[]).length,
);
const placeholderText = computed(
() => ((!multiple.value
&& innerPopupVisible.value
&& ((valueType.value === 'object' && value.value[keys.value.label])
|| getSingleContent(innerValue.value, optionsList.value)))
|| placeholder.value)
?? t(global.value.placeholder),
);
const displayText = computed(() => {
if (multiple.value) {
if (valueType.value === 'object') {
return (value.value as SelectValue[]).map((v) => v[keys.value.label]);
}
return getMultipleContent(innerValue.value as SelectValue[], optionsList.value);
}
if (valueType.value === 'object' && value.value[keys.value.label]) {
return value.value[keys.value.label];
}
return getSingleContent(innerValue.value, optionsList.value);
});
const valueDisplayParams = computed(() => {
const val = multiple.value
? (innerValue.value as SelectValue[]).map((value) => ({
value,
label: optionsMap.value.get(value)?.label,
}))
: innerValue.value;
return {
value: val,
onClose: multiple.value ? (index: number) => removeTag(index) : () => {},
};
});
const collapsedItemsParams = computed(() => multiple.value
? {
value: innerValue.value,
collapsedSelectedItems: innerValue.value.slice(minCollapsedNum.value),
count: innerValue.value.length - minCollapsedNum.value,
}
: {});
const removeTag = (index: number, context?: { e?: MouseEvent | KeyboardEvent }) => {
const { e } = context || {};
e?.stopPropagation();
if (isDisabled.value) {
return;
}
const selectValue = cloneDeep(innerValue.value) as SelectValue[];
const value = selectValue[index];
selectValue.splice(index, 1);
setInnerValue(selectValue, { e, trigger: 'tag-remove' });
const evtObj = {
value: value as string | number,
data: optionsMap.value.get(value),
e,
};
instance.emit('remove', evtObj);
props.onRemove?.(evtObj);
};
const handleCreate = () => {
if (!tInputValue.value) return;
const createVal = tInputValue.value;
setTInputValue('');
instance.emit('create', createVal);
props.onCreate?.(createVal);
};
const handleClear = ({ e }: { e: MouseEvent }) => {
e?.stopPropagation();
if (multiple.value) {
setInnerValue([], { trigger: 'clear', e });
} else {
setInnerValue('', { trigger: 'clear', e });
}
instance.emit('clear', { e });
props.onClear?.({ e });
};
const handleTInputValueChange = (val: string, context: SelectInputValueChangeContext) => {
if (context.trigger === 'blur' || !innerPopupVisible.value) return;
setTInputValue(val);
debounceSearch();
};
const handleTagChange = (currentTags: SelectInputValue, context: SelectInputChangeContext) => {
const { trigger, index, e } = context;
if (trigger === 'clear') {
setInnerValue([], { trigger: 'tag-remove', e });
}
if (['tag-remove', 'backspace'].includes(trigger)) {
removeTag(index);
}
};
const handleFocus = (value: string, context: { e: FocusEvent }) => {
instance.emit('focus', { value, e: context?.e });
props.onFocus?.({ value, e: context?.e });
};
const handleBlur = (value: string, context: { e: FocusEvent | KeyboardEvent }) => {
instance.emit('blur', { value, e: context?.e });
props.onBlur?.({ value, e: context?.e });
};
const handleEnter = (value: string, context: { e: KeyboardEvent }) => {
instance.emit('enter', { value, e: context?.e, inputValue: tInputValue.value });
props.onEnter?.({ value, e: context?.e, inputValue: tInputValue.value.toString() });
handleCreate();
};
const debounceSearch = debounce(() => {
instance.emit('search', tInputValue.value);
props.onSearch?.(tInputValue.value.toString());
}, 300);
const getOverlayElm = (): HTMLElement => {
let r;
try {
const popupRefs = (context.refs.selectInputRef as any).$refs.selectInputRef.$refs;
r = popupRefs.overlay || popupRefs.component.$refs.overlay;
} catch (e) {
console.warn('TDesign Warn:', e);
}
return r;
};
const updateScrollTop = (content: HTMLDivElement) => {
// 虚拟滚动不支持移动定位到选中项
if (props.scroll?.type === 'virtual') return;
const overlayEl = getOverlayElm();
if (!overlayEl) return;
const firstSelectedNode: HTMLDivElement = overlayEl?.querySelector(`.${classPrefix.value}-is-selected`);
nextTick(() => {
if (firstSelectedNode && content) {
const { paddingBottom } = getComputedStyle(firstSelectedNode);
const { marginBottom } = getComputedStyle(content);
const elementBottomHeight = parseInt(paddingBottom, 10) + parseInt(marginBottom, 10);
// 小于0时不需要特殊处理,会被设为0
const updateValue = firstSelectedNode.offsetTop
- content.offsetTop
- (content.clientHeight - firstSelectedNode.clientHeight)
+ elementBottomHeight;
// eslint-disable-next-line no-param-reassign
content.scrollTop = updateValue;
}
});
};
// 键盘操作逻辑相关
const hoverIndex = ref(-1);
const keydownEvent = (e: KeyboardEvent) => {
const optionsListLength = optionsList.value.length;
const arrowDownOption = () => {
let count = 0;
while (hoverIndex.value < optionsListLength) {
if (!optionsList.value[hoverIndex.value]?.disabled) {
break;
}
if (hoverIndex.value === optionsListLength - 1) {
hoverIndex.value = 0;
} else {
hoverIndex.value += 1;
}
count += 1;
if (count >= optionsListLength) break;
}
};
const arrowUpOption = () => {
let count = 0;
while (hoverIndex.value > -1) {
if (!optionsList.value[hoverIndex.value]?.disabled) {
break;
}
if (hoverIndex.value === 0) {
hoverIndex.value = optionsListLength - 1;
} else {
hoverIndex.value -= 1;
}
count += 1;
if (count >= optionsListLength) break;
}
};
if (optionsListLength === 0) return;
const preventKeys = ['ArrowDown', 'ArrowUp', 'Enter', 'Escape', 'Tab'];
if (preventKeys.includes(e.code)) {
e.preventDefault();
}
switch (e.code) {
case 'ArrowDown':
if (hoverIndex.value === -1) {
hoverIndex.value = 0;
return;
}
if (hoverIndex.value < optionsListLength - 1) {
hoverIndex.value += 1;
arrowDownOption();
} else {
hoverIndex.value = 0;
arrowDownOption();
}
break;
case 'ArrowUp':
if (hoverIndex.value === -1) {
hoverIndex.value = 0;
return;
}
if (hoverIndex.value > 0) {
hoverIndex.value -= 1;
arrowUpOption();
} else {
hoverIndex.value = optionsListLength - 1;
arrowUpOption();
}
break;
case 'Enter':
if (hoverIndex.value === -1) return;
if (!multiple.value) {
setInnerValue(optionsList.value[hoverIndex.value].value, {
e,
trigger: 'check',
});
setInnerPopupVisible(false, { e });
} else {
if (hoverIndex.value === -1) return;
const optionValue = optionsList.value[hoverIndex.value]?.value;
if (!optionValue) return;
const newValue = getNewMultipleValue(innerValue.value, optionValue);
setInnerValue(newValue.value, { e, trigger: newValue.isCheck ? 'check' : 'uncheck' });
}
break;
case 'Escape':
case 'Tab':
setInnerPopupVisible(false, { trigger: 'keydown-esc', e });
setTInputValue('');
break;
}
};
const checkValueInvalid = () => {
// 参数类型检测与修复
if (!multiple.value && isArray(value.value)) {
value.value = '';
}
if (multiple.value && !isArray(value.value)) {
value.value = [];
}
};
watch(
value,
() => {
checkValueInvalid();
},
{
immediate: true,
},
);
// 为 eventListener 加单独的 sync watch,以防组件在卸载的时候未能正常清除监听 (https://github.com/Tencent/tdesign-vue/issues/1170)
watch(
innerPopupVisible,
(val) => {
val && document.addEventListener('keydown', keydownEvent);
!val && document.removeEventListener('keydown', keydownEvent);
},
{
flush: 'sync',
},
);
// 其余逻辑使用默认 pre watch
watch(innerPopupVisible, (value) => {
if (value) {
// 显示 popup 的时候重置 hover 选项下标
hoverIndex.value = -1;
} else {
tInputValue.value && setTInputValue('');
}
});
provide('tSelect', {
size,
multiple,
popupOpenTime,
hoverIndex,
selectValue: innerValue,
reserveKeyword,
isReachMaxLimit,
getOverlayElm,
handleCreate,
handleValueChange: setInnerValue,
handlerInputChange: setTInputValue,
handlePopupVisibleChange: setInnerPopupVisible,
});
return {
isFilterable,
isDisabled,
isLoading,
innerOptions,
placeholderText,
selectInputRef,
innerPopupVisible,
displayText,
tInputValue,
collapsedItemsParams,
valueDisplayParams,
handleFocus,
handleBlur,
handleEnter,
handleClear,
handleTagChange,
handleTInputValueChange,
setInnerPopupVisible,
removeTag,
renderTNode,
updateScrollTop,
componentName: COMPONENT_NAME,
};
},
methods: {
renderSuffixIcon() {
const {
isLoading, showArrow, innerPopupVisible, isDisabled,
} = this;
if (isLoading) {
return (
<t-loading class={[`${this.componentName}__right-icon`, `${this.componentName}__active-icon`]} size="small" />
);
}
return showArrow ? (
<fake-arrow
overlayClassName={`${this.componentName}__right-icon`}
isActive={innerPopupVisible && !isDisabled}
/>
) : null;
},
},
render() {
const { renderTNode } = this;
const prefixIcon = () => renderTNode('prefixIcon');
const valueDisplay = () => renderTNode('valueDisplay', { params: this.valueDisplayParams });
const collapsedItems = () => renderTNode('collapsedItems', { params: this.collapsedItemsParams });
const { overlayClassName, ...restPopupProps } = this.popupProps || {};
return (
<div ref="select" class={`${this.componentName}__wrap`}>
<SelectInput
ref="selectInputRef"
class={this.componentName}
autoWidth={this.autoWidth}
borderless={this.borderless || !this.bordered}
readonly={this.readonly}
allowInput={this.isFilterable}
multiple={this.multiple}
keys={this.keys}
status={this.status}
tips={this.tips}
value={this.displayText}
valueDisplay={valueDisplay}
clearable={this.clearable}
disabled={this.isDisabled}
label={prefixIcon}
suffixIcon={this.renderSuffixIcon}
placeholder={this.placeholderText}
inputValue={this.tInputValue}
inputProps={{
size: this.size,
...this.inputProps,
}}
tagInputProps={{
autoWidth: true,
...this.tagInputProps,
}}
tagProps={this.tagProps}
minCollapsedNum={this.minCollapsedNum}
collapsedItems={collapsedItems}
popupVisible={this.innerPopupVisible}
popupProps={{
overlayClassName: [`${this.componentName}__dropdown`, overlayClassName],
...restPopupProps,
}}
on={{
focus: this.handleFocus,
blur: this.handleBlur,
enter: this.handleEnter,
clear: this.handleClear,
'input-change': this.handleTInputValueChange,
'popup-visible-change': this.setInnerPopupVisible,
'tag-change': this.handleTagChange,
}}
{...this.selectInputProps}
updateScrollTop={this.updateScrollTop}
>
<select-panel
slot="panel"
scopedSlots={this.$scopedSlots}
size={this.size}
options={this.innerOptions}
inputValue={this.tInputValue}
multiple={this.multiple}
empty={this.empty}
filter={this.filter}
filterable={this.isFilterable}
creatable={this.creatable}
scroll={this.scroll}
loading={this.isLoading}
loadingText={this.loadingText}
panelTopContent={this.panelTopContent}
panelBottomContent={this.panelBottomContent}
/>
</SelectInput>
</div>
);
},
});