ant-design-vue/components/vc-select/OptionList.tsx

394 lines
13 KiB
Vue
Raw Normal View History

2020-09-30 08:21:04 +00:00
import TransBtn from './TransBtn';
2020-09-30 08:21:04 +00:00
import KeyCode from '../_util/KeyCode';
import classNames from '../_util/classNames';
import pickAttrs from '../_util/pickAttrs';
import { isValidElement } from '../_util/props-util';
import createRef from '../_util/createRef';
2022-03-20 08:42:00 +00:00
import { computed, defineComponent, nextTick, reactive, toRaw, watch } from 'vue';
2021-12-23 15:23:01 +00:00
import List from '../vc-virtual-list';
2021-06-22 05:26:19 +00:00
import useMemo from '../_util/hooks/useMemo';
2021-11-03 08:22:02 +00:00
import { isPlatformMac } from './utils/platformUtil';
3.0 ready (#4523) * refactor: transfer、tooltip (#4306) * refactor(transfer): use composition api (#4135) * refactor(transfer): use composition api * fix: remove console * refactor(tooltip): use composition api (#4059) * refactor(tooltip): use composition api * chore: useConfigInject * fix: remove useless * style: format code * refactor: transfer * refactor: tooltip Co-authored-by: ajuner <106791576@qq.com> * Refactor mentions (#4341) * refactor(mentions): use compositionAPI (#4313) * refactor: mentions * refactor: mentions Co-authored-by: ajuner <106791576@qq.com> * Refactor progress (#4358) * fix: timepicker error border not show #4331 * fix(UploadDragger): fix UploadDrager no export (#4334) * refactor(switch): support customize checked value #4329 (#4332) * refactor(switch): support customize checked value #4329 * test: add test case * refactor: update props name * refactor: update ts * refactor: optimize * style: uncheckedValue to unCheckedValue * test: update snap * feat: udpate switch ts * docs: remove ie11 * fix: tree-select throw error when use slot title * fix: TypeScript definition of Table interface for typescript 4.3.5 (#4353) * fix type for typescript 4.3.5 * Update interface.ts close #4296 * fix: dropdown submenu style error #4351 close #4351 * fix(notification): 完善notification类型 (#4346) * refactor(progress): use composition API (#4355) * refactor(progress): use composition API * refactor(vc-progress): update * refactor: progress * refactor: progress * fix: timepicker error border not show #4331 * fix(UploadDragger): fix UploadDrager no export (#4334) * refactor(switch): support customize checked value #4329 (#4332) * refactor(switch): support customize checked value #4329 * test: add test case * refactor: update props name * refactor: update ts * refactor: optimize * style: uncheckedValue to unCheckedValue * test: update snap * feat: udpate switch ts * docs: remove ie11 * fix: tree-select throw error when use slot title * fix: TypeScript definition of Table interface for typescript 4.3.5 (#4353) * fix type for typescript 4.3.5 * Update interface.ts close #4296 * fix: dropdown submenu style error #4351 close #4351 * fix(notification): 完善notification类型 (#4346) * refactor(progress): use composition API (#4355) * refactor(progress): use composition API * refactor(vc-progress): update * refactor: progress * refactor: progress Co-authored-by: Jarvis <35361626+fanhaoyuan@users.noreply.github.com> Co-authored-by: John <John60676@qq.com> Co-authored-by: 艾斯特洛 <axetroy.dev@gmail.com> Co-authored-by: zanllp <qc@zanllp.cn> * docs: add changelog * refactor: tree * refactor: tree * style: lint * refactor: tree * 热factor: tree * refactor: tree * refactor: tree * refactor: tree * refactor: directory tree * refactor: tree * refactor: tree-select * refactor: tree-select * refactor: tree-select * refactor: tree-select * refactor: tree-select * style: lint format * refactor: tree-select * refactor: tree-select * refactor: tree-select * refactor: tree-select * refactor: tree-select * refactor: tree-select * fix: upload ts error * fix: update tree title render & switchIcon * test: update tree test * feat: add VirtualScroll tree * refactor: datePicker & calendar & trigger (#4522) * style: update * test: update calendar test * test: update test * test: update test * refactor: slider * feat: update slider css * refactor: slider to ts * refactor: slider to ts * perf: update default itemHeight * test: update * fix: uddate ts type * fix: update skeleton * fix: update skeleton * refactor: update vc-pagination * refactor: pagination * refactor: timeline * refactor: steps * refactor: collapse * refactor: collapse * refactor: popconfirm * refactor: popover * refactor: dropdown * doc: merge doc * chore: vite for dev (#4602) * style: js to jsx * doc: add site * style: lint * style: format ts type * doc: update * style: format code * style: format site * doc: update * style: dmeo * style: format scripts * chore: remove sub-modules * chore: update vite * site: add site build * test: update snap * doc(select): add tip (#4606) * refactor: table (#4641) * refactor: table * refactor: table * refactor: table * refactor: table * refactor: table * refactor: table * refactor: table * refactor: table * refactor: table * fix: column not pass to cell * doc: uppate table * fix: update bodyCell headerCell * doc: remove examples * refactor: table * fix: table title not work * fix: table selection * fix: table checkStrictly * refactor: table * fix: table template error * feat: table support summary * test: update snap * perf: table * docs(table): fix ajax demo (#4639) * test: update table * refactor: remove old table * doc: update table doc * doc: update doc * doc: update select * doc: update summary Co-authored-by: John <John60676@qq.com> * doc: update doc * fix: menu arrow not work * test: update * doc: add next site * style: format * doc: update * doc: update site script * fix: expand icon not fixed * feat: use renderSlot * test: update table snap * feat: confirm support reactively * feat: configProvider.config * feat: message support configprovider.config * feat: notification support configprovider.config * doc: update doc * fix: typescript compile error * style: add import eslint * doc: update demo * chore: set transpileOnly true * style: fix eslint error * test: update snap * doc: update * test: mock date * test: update snap * chore: remove gulp-typescript (#4675) * feat: V3 form (#4678) * chore: update husky * perf: update formItem * perf: useInjectFormItemContext * fix: table ts error * doc: add Customized Form Controls demo * feat: export useInjectFormItemContext * doc: update form doc * doc: update doc * doc: update doc * feat: autocomplete support option slot * doc: update * feat: add form item rest * style: remove omit.js * refactor: autocomplete * doc: add changelog to site * doc: update site anchor * doc: update doc layout * test: update table test * doc: update * chore: udpate gulp script * chore: udpate gulp script * doc: add changelog * doc: update * test: ignore some test wait vue-test-utils * fix: form id error #4582 close #4582 * doc: add select Responsive demo * doc: remove temp doc Co-authored-by: ajuner <106791576@qq.com> Co-authored-by: Jarvis <35361626+fanhaoyuan@users.noreply.github.com> Co-authored-by: John <John60676@qq.com> Co-authored-by: 艾斯特洛 <axetroy.dev@gmail.com> Co-authored-by: zanllp <qc@zanllp.cn> Co-authored-by: Amour1688 <lcz_1996@foxmail.com>
2021-09-25 08:51:32 +00:00
import type { EventHandler } from '../_util/EventInterface';
2021-11-03 08:22:02 +00:00
import omit from '../_util/omit';
import useBaseProps from './hooks/useBaseProps';
import type { RawValueType } from './Select';
import useSelectProps from './SelectContext';
2022-04-23 05:28:00 +00:00
import type { ScrollConfig } from '../vc-virtual-list/List';
export interface RefOptionListProps {
onKeydown: (e?: KeyboardEvent) => void;
onKeyup: (e?: KeyboardEvent) => void;
scrollTo?: (index: number | ScrollConfig) => void;
}
function isTitleType(content: any) {
return typeof content === 'string' || typeof content === 'number';
}
// export interface OptionListProps<OptionsType extends object[]> {
export type OptionListProps = Record<string, never>;
2020-09-30 08:21:04 +00:00
/**
* Using virtual list of option display.
* Will fallback to dom if use customize render.
*/
const OptionList = defineComponent({
compatConfig: { MODE: 3 },
2020-09-30 08:21:04 +00:00
name: 'OptionList',
inheritAttrs: false,
setup(_, { expose, slots }) {
const baseProps = useBaseProps();
const props = useSelectProps();
const itemPrefixCls = computed(() => `${baseProps.prefixCls}-item`);
2020-09-30 08:21:04 +00:00
2021-06-22 05:26:19 +00:00
const memoFlattenOptions = useMemo(
() => props.flattenOptions,
[() => baseProps.open, () => props.flattenOptions],
2021-06-24 03:03:02 +00:00
next => next[0],
2021-06-22 05:26:19 +00:00
);
2020-09-30 08:21:04 +00:00
// =========================== List ===========================
const listRef = createRef();
const onListMouseDown: EventHandler = event => {
2020-09-30 08:21:04 +00:00
event.preventDefault();
};
2022-04-23 05:28:00 +00:00
const scrollIntoView = (args: number | ScrollConfig) => {
2020-09-30 08:21:04 +00:00
if (listRef.current) {
2022-04-23 05:28:00 +00:00
listRef.current.scrollTo(typeof args === 'number' ? { index: args } : args);
2020-09-30 08:21:04 +00:00
}
};
// ========================== Active ==========================
2020-10-07 14:49:01 +00:00
const getEnabledActiveIndex = (index: number, offset = 1) => {
2021-06-22 05:26:19 +00:00
const len = memoFlattenOptions.value.length;
2020-09-30 08:21:04 +00:00
for (let i = 0; i < len; i += 1) {
const current = (index + i * offset + len) % len;
2021-06-22 05:26:19 +00:00
const { group, data } = memoFlattenOptions.value[current];
if (!group && !data.disabled) {
2020-09-30 08:21:04 +00:00
return current;
}
}
return -1;
};
const state = reactive({
activeIndex: getEnabledActiveIndex(0),
});
2020-10-07 14:49:01 +00:00
const setActive = (index: number, fromKeyboard = false) => {
2020-09-30 08:21:04 +00:00
state.activeIndex = index;
2020-10-07 14:49:01 +00:00
const info = { source: fromKeyboard ? ('keyboard' as const) : ('mouse' as const) };
2020-09-30 08:21:04 +00:00
// Trigger active event
2021-06-22 05:26:19 +00:00
const flattenItem = memoFlattenOptions.value[index];
2020-09-30 08:21:04 +00:00
if (!flattenItem) {
props.onActiveValue(null, -1, info);
return;
}
2022-04-23 05:28:00 +00:00
props.onActiveValue(flattenItem.value, index, info);
2020-09-30 08:21:04 +00:00
};
// Auto active first item when list length or searchValue changed
2020-10-07 14:49:01 +00:00
watch(
[() => memoFlattenOptions.value.length, () => baseProps.searchValue],
2020-10-07 14:49:01 +00:00
() => {
setActive(props.defaultActiveFirstOption !== false ? getEnabledActiveIndex(0) : -1);
},
2020-10-08 14:51:09 +00:00
{ immediate: true },
2020-10-07 14:49:01 +00:00
);
2020-09-30 08:21:04 +00:00
2022-04-23 05:28:00 +00:00
// https://github.com/ant-design/ant-design/issues/34975
const isSelected = (value: RawValueType) =>
props.rawValues.has(value) && baseProps.mode !== 'combobox';
// Auto scroll to item position in single mode
2020-10-07 14:49:01 +00:00
watch(
[() => baseProps.open, () => baseProps.searchValue],
2020-10-07 14:49:01 +00:00
() => {
if (!baseProps.multiple && baseProps.open && props.rawValues.size === 1) {
const value = Array.from(props.rawValues)[0];
2022-03-20 08:42:00 +00:00
const index = toRaw(memoFlattenOptions.value).findIndex(
({ data }) => data[props.fieldNames.value] === value,
2022-03-20 08:42:00 +00:00
);
2021-11-03 08:22:02 +00:00
if (index !== -1) {
setActive(index);
nextTick(() => {
scrollIntoView(index);
});
}
2020-11-05 10:09:02 +00:00
}
2020-11-04 10:59:08 +00:00
// Force trigger scrollbar visible when open
if (baseProps.open) {
2020-11-05 10:09:02 +00:00
nextTick(() => {
2020-11-04 10:59:08 +00:00
listRef.current?.scrollTo(undefined);
2020-11-05 10:09:02 +00:00
});
2020-11-04 10:59:08 +00:00
}
2020-10-07 14:49:01 +00:00
},
2020-11-05 10:09:02 +00:00
{ immediate: true, flush: 'post' },
2020-10-07 14:49:01 +00:00
);
2020-09-30 08:21:04 +00:00
// ========================== Values ==========================
2020-10-07 14:49:01 +00:00
const onSelectValue = (value?: RawValueType) => {
2020-09-30 08:21:04 +00:00
if (value !== undefined) {
props.onSelect(value, { selected: !props.rawValues.has(value) });
2020-09-30 08:21:04 +00:00
}
// Single mode should always close by select
if (!baseProps.multiple) {
baseProps.toggleOpen(false);
2020-09-30 08:21:04 +00:00
}
};
const getLabel = (item: Record<string, any>) =>
typeof item.label === 'function' ? item.label() : item.label;
2020-10-07 14:49:01 +00:00
function renderItem(index: number) {
2021-06-22 05:26:19 +00:00
const item = memoFlattenOptions.value[index];
2020-09-30 08:21:04 +00:00
if (!item) return null;
const itemData = item.data || {};
const { value } = itemData;
const { group } = item;
2020-09-30 08:21:04 +00:00
const attrs = pickAttrs(itemData, true);
const mergedLabel = getLabel(item);
2020-09-30 08:21:04 +00:00
return item ? (
<div
aria-label={typeof mergedLabel === 'string' && !group ? mergedLabel : null}
2020-09-30 08:21:04 +00:00
{...attrs}
key={index}
role={group ? 'presentation' : 'option'}
id={`${baseProps.id}_list_${index}`}
2022-04-23 05:28:00 +00:00
aria-selected={isSelected(value)}
2020-09-30 08:21:04 +00:00
>
{value}
</div>
) : null;
}
const onKeydown = (event: KeyboardEvent) => {
const { which, ctrlKey } = event;
switch (which) {
// >>> Arrow keys & ctrl + n/p on Mac
case KeyCode.N:
case KeyCode.P:
case KeyCode.UP:
case KeyCode.DOWN: {
let offset = 0;
if (which === KeyCode.UP) {
offset = -1;
} else if (which === KeyCode.DOWN) {
offset = 1;
} else if (isPlatformMac() && ctrlKey) {
if (which === KeyCode.N) {
2020-09-30 08:21:04 +00:00
offset = 1;
} else if (which === KeyCode.P) {
offset = -1;
2020-09-30 08:21:04 +00:00
}
}
2020-09-30 08:21:04 +00:00
if (offset !== 0) {
const nextActiveIndex = getEnabledActiveIndex(state.activeIndex + offset, offset);
scrollIntoView(nextActiveIndex);
setActive(nextActiveIndex, true);
2020-09-30 08:21:04 +00:00
}
break;
}
2020-09-30 08:21:04 +00:00
// >>> Select
case KeyCode.ENTER: {
// value
const item = memoFlattenOptions.value[state.activeIndex];
if (item && !item.data.disabled) {
2022-04-23 05:28:00 +00:00
onSelectValue(item.value);
} else {
onSelectValue(undefined);
}
2020-09-30 08:21:04 +00:00
if (baseProps.open) {
event.preventDefault();
2020-09-30 08:21:04 +00:00
}
break;
}
// >>> Close
case KeyCode.ESC: {
baseProps.toggleOpen(false);
if (baseProps.open) {
event.stopPropagation();
2020-09-30 08:21:04 +00:00
}
}
}
};
const onKeyup = () => {};
2020-09-30 08:21:04 +00:00
const scrollTo = (index: number) => {
scrollIntoView(index);
2020-09-30 08:21:04 +00:00
};
expose({
onKeydown,
onKeyup,
scrollTo,
});
return () => {
// const {
// renderItem,
// listRef,
// onListMouseDown,
// itemPrefixCls,
// setActive,
// onSelectValue,
// memoFlattenOptions,
// $slots,
// } = this as any;
const { id, notFoundContent, onPopupScroll } = baseProps;
2022-04-23 05:28:00 +00:00
const { menuItemSelectedIcon, fieldNames, virtual, listHeight, listItemHeight } = props;
const renderOption = slots.option;
const { activeIndex } = state;
const omitFieldNameList = Object.keys(fieldNames).map(key => fieldNames[key]);
// ========================== Render ==========================
if (memoFlattenOptions.value.length === 0) {
return (
<div
role="listbox"
id={`${id}_list`}
class={`${itemPrefixCls.value}-empty`}
onMousedown={onListMouseDown}
>
{notFoundContent}
</div>
);
}
2020-09-30 08:21:04 +00:00
return (
<>
<div role="listbox" id={`${id}_list`} style={{ height: 0, width: 0, overflow: 'hidden' }}>
{renderItem(activeIndex - 1)}
{renderItem(activeIndex)}
{renderItem(activeIndex + 1)}
</div>
<List
itemKey="key"
ref={listRef}
data={memoFlattenOptions.value}
height={listHeight}
itemHeight={listItemHeight}
fullHeight={false}
onMousedown={onListMouseDown}
onScroll={onPopupScroll}
virtual={virtual}
v-slots={{
default: (item, itemIndex) => {
const { group, groupOption, data, value } = item;
const { key } = data;
const label = typeof item.label === 'function' ? item.label() : item.label;
// Group
if (group) {
2022-04-23 05:28:00 +00:00
const groupTitle = data.title ?? (isTitleType(label) && label);
return (
2022-04-23 05:28:00 +00:00
<div
class={classNames(itemPrefixCls.value, `${itemPrefixCls.value}-group`)}
title={groupTitle}
>
{renderOption ? renderOption(data) : label !== undefined ? label : key}
</div>
);
}
const {
disabled,
title,
children,
style,
class: cls,
className,
...otherProps
} = data;
const passedProps = omit(otherProps, omitFieldNameList);
// Option
2022-04-23 05:28:00 +00:00
const selected = isSelected(value);
const optionPrefixCls = `${itemPrefixCls.value}-option`;
const optionClassName = classNames(
itemPrefixCls.value,
optionPrefixCls,
cls,
className,
{
[`${optionPrefixCls}-grouped`]: groupOption,
[`${optionPrefixCls}-active`]: activeIndex === itemIndex && !disabled,
[`${optionPrefixCls}-disabled`]: disabled,
[`${optionPrefixCls}-selected`]: selected,
},
);
const mergedLabel = getLabel(item);
const iconVisible =
!menuItemSelectedIcon || typeof menuItemSelectedIcon === 'function' || selected;
2022-04-23 05:28:00 +00:00
// https://github.com/ant-design/ant-design/issues/34145
const content =
typeof mergedLabel === 'number' ? mergedLabel : mergedLabel || value;
// https://github.com/ant-design/ant-design/issues/26717
2022-04-23 05:28:00 +00:00
let optionTitle = isTitleType(content) ? content.toString() : undefined;
if (title !== undefined) {
optionTitle = title;
}
2021-12-23 15:23:01 +00:00
return (
<div
{...passedProps}
aria-selected={selected}
class={optionClassName}
title={optionTitle}
onMousemove={e => {
if (otherProps.onMousemove) {
otherProps.onMousemove(e);
}
if (activeIndex === itemIndex || disabled) {
return;
}
setActive(itemIndex);
}}
onClick={e => {
if (!disabled) {
onSelectValue(value);
}
if (otherProps.onClick) {
otherProps.onClick(e);
}
}}
style={style}
>
<div class={`${optionPrefixCls}-content`}>
{renderOption ? renderOption(data) : content}
</div>
{isValidElement(menuItemSelectedIcon) || selected}
{iconVisible && (
<TransBtn
class={`${itemPrefixCls.value}-option-state`}
customizeIcon={menuItemSelectedIcon}
customizeIconProps={{ isSelected: selected }}
>
{selected ? '✓' : null}
</TransBtn>
)}
2021-12-23 15:23:01 +00:00
</div>
);
},
}}
></List>
</>
);
};
2020-09-30 08:21:04 +00:00
},
2020-10-03 07:54:52 +00:00
});
2020-09-30 08:21:04 +00:00
export default OptionList;