refactor: tree-select

pull/4577/head
tangjinzhou 2021-08-22 10:47:41 +08:00
parent 966c0d4358
commit 81c16aba93
9 changed files with 251 additions and 133 deletions

View File

@ -18,24 +18,34 @@ export default (
form?: ComputedRef<{ form?: ComputedRef<{
requiredMark?: RequiredMark; requiredMark?: RequiredMark;
}>; }>;
autoInsertSpaceInButton: ComputedRef<Boolean>; autoInsertSpaceInButton: ComputedRef<boolean>;
renderEmpty?: ComputedRef<(componentName?: string) => VNodeChild | JSX.Element>; renderEmpty?: ComputedRef<(componentName?: string) => VNodeChild | JSX.Element>;
virtual: ComputedRef<Boolean>; virtual: ComputedRef<boolean>;
dropdownMatchSelectWidth: ComputedRef<boolean>;
getPopupContainer: ComputedRef<ConfigProviderProps['getPopupContainer']>;
} => { } => {
const configProvider = inject<UnwrapRef<ConfigProviderProps>>( const configProvider = inject<UnwrapRef<ConfigProviderProps>>(
'configProvider', 'configProvider',
defaultConfigProvider, defaultConfigProvider,
); );
const prefixCls = computed(() => configProvider.getPrefixCls(name, props.prefixCls)); const prefixCls = computed(() => configProvider.getPrefixCls(name, props.prefixCls));
const direction = computed(() => configProvider.direction); const direction = computed(() => props.direction ?? configProvider.direction);
const autoInsertSpaceInButton = computed(() => configProvider.autoInsertSpaceInButton); const autoInsertSpaceInButton = computed(() => configProvider.autoInsertSpaceInButton);
const renderEmpty = computed(() => configProvider.renderEmpty); const renderEmpty = computed(() => configProvider.renderEmpty);
const space = computed(() => configProvider.space); const space = computed(() => configProvider.space);
const pageHeader = computed(() => configProvider.pageHeader); const pageHeader = computed(() => configProvider.pageHeader);
const form = computed(() => configProvider.form); const form = computed(() => configProvider.form);
const size = computed(() => props.size || configProvider.componentSize); const size = computed(() => props.size ?? configProvider.componentSize);
const getTargetContainer = computed(() => props.getTargetContainer); const getTargetContainer = computed(
const virtual = computed(() => props.virtual); () => props.getTargetContainer || configProvider.getTargetContainer,
);
const getPopupContainer = computed(
() => props.getPopupContainer || configProvider.getPopupContainer,
);
const virtual = computed(() => props.virtual ?? configProvider.virtual);
const dropdownMatchSelectWidth = computed<boolean>(
() => props.dropdownMatchSelectWidth ?? configProvider.dropdownMatchSelectWidth,
);
return { return {
configProvider, configProvider,
prefixCls, prefixCls,
@ -48,5 +58,7 @@ export default (
autoInsertSpaceInButton, autoInsertSpaceInButton,
renderEmpty, renderEmpty,
virtual, virtual,
dropdownMatchSelectWidth,
getPopupContainer,
}; };
}; };

View File

@ -1,9 +1,4 @@
function omit<T extends object, K extends [...(keyof T)[]]>( function omit<T extends object, K extends keyof T>(obj: T, fields: K[]): Omit<T, K> {
obj: T,
fields: K,
): {
[K2 in Exclude<keyof T, K[number]>]: T[K2];
} {
// eslint-disable-next-line prefer-object-spread // eslint-disable-next-line prefer-object-spread
const shallowCopy = Object.assign({}, obj); const shallowCopy = Object.assign({}, obj);
for (let i = 0; i < fields.length; i += 1) { for (let i = 0; i < fields.length; i += 1) {

View File

@ -1,22 +1,58 @@
import type { App, Plugin } from 'vue'; import type { App, ExtractPropTypes, Plugin, PropType } from 'vue';
import { defineComponent, inject } from 'vue'; import { computed, ref, watchEffect } from 'vue';
import VcTreeSelect, { TreeNode, SHOW_ALL, SHOW_PARENT, SHOW_CHILD } from '../vc-tree-select'; import { defineComponent } from 'vue';
import VcTreeSelect, {
TreeNode,
SHOW_ALL,
SHOW_PARENT,
SHOW_CHILD,
treeSelectProps as vcTreeSelectProps,
} from '../vc-tree-select';
import classNames from '../_util/classNames'; import classNames from '../_util/classNames';
import { TreeSelectProps } from './interface';
import warning from '../_util/warning';
import { getOptionProps, getComponent, getSlot } from '../_util/props-util';
import initDefaultProps from '../_util/props-util/initDefaultProps'; import initDefaultProps from '../_util/props-util/initDefaultProps';
import { defaultConfigProvider } from '../config-provider'; import type { SizeType } from '../config-provider';
export { TreeData, TreeSelectProps } from './interface'; export { TreeData, TreeSelectProps } from './interface';
import LoadingOutlined from '@ant-design/icons-vue/LoadingOutlined'; import LoadingOutlined from '@ant-design/icons-vue/LoadingOutlined';
import CaretDownOutlined from '@ant-design/icons-vue/CaretDownOutlined'; import CaretDownOutlined from '@ant-design/icons-vue/CaretDownOutlined';
import DownOutlined from '@ant-design/icons-vue/DownOutlined'; import type { DefaultValueType, FieldNames } from '../vc-tree-select/interface';
import CloseOutlined from '@ant-design/icons-vue/CloseOutlined'; import omit from '../_util/omit';
import CloseCircleFilled from '@ant-design/icons-vue/CloseCircleFilled'; import PropTypes from '../_util/vue-types';
import omit from 'omit.js'; import useConfigInject from '../_util/hooks/useConfigInject';
import { convertChildrenToData } from './utils'; import devWarning from '../vc-util/devWarning';
import getIcons from '../select/utils/iconUtil';
import renderSwitcherIcon from '../tree/utils/iconUtil';
import type { AntTreeNodeProps } from '../tree/Tree';
const getTransitionName = (rootPrefixCls: string, motion: string, transitionName?: string) => {
if (transitionName !== undefined) {
return transitionName;
}
return `${rootPrefixCls}-${motion}`;
};
type RawValue = string | number;
export interface LabeledValue {
key?: string;
value: RawValue;
label: any;
}
export type SelectValue = RawValue | RawValue[] | LabeledValue | LabeledValue[];
export interface RefTreeSelectProps {
focus: () => void;
blur: () => void;
}
export const treeSelectProps = {
...omit(vcTreeSelectProps<DefaultValueType>(), ['showTreeIcon', 'treeMotion', 'inputIcon']),
suffixIcon: PropTypes.any,
size: { type: String as PropType<SizeType> },
bordered: { type: Boolean, default: undefined },
replaceFields: { type: Object as PropType<FieldNames> },
};
export type TreeSelectProps = Partial<ExtractPropTypes<typeof treeSelectProps>>;
const TreeSelect = defineComponent({ const TreeSelect = defineComponent({
TreeNode, TreeNode,
SHOW_ALL, SHOW_ALL,
@ -24,23 +60,166 @@ const TreeSelect = defineComponent({
SHOW_CHILD, SHOW_CHILD,
name: 'ATreeSelect', name: 'ATreeSelect',
inheritAttrs: false, inheritAttrs: false,
props: initDefaultProps(TreeSelectProps(), { props: initDefaultProps(treeSelectProps, {
transitionName: 'slide-up', transitionName: 'slide-up',
choiceTransitionName: '', choiceTransitionName: '',
listHeight: 256,
treeIcon: false,
listItemHeight: 26,
bordered: true,
}), }),
setup() { slots: ['placeholder', 'maxTagPlaceholder', 'treeIcon', 'switcherIcon', 'notFoundContent'],
return { setup(props, { attrs, slots, expose, emit }) {
vcTreeSelect: null, watchEffect(() => {
configProvider: inject('configProvider', defaultConfigProvider), devWarning(
props.multiple !== false || !props.treeCheckable,
'TreeSelect',
'`multiple` will alway be `true` when `treeCheckable` is true',
);
devWarning(
props.replaceFields === undefined,
'TreeSelect',
'`replaceFields` is deprecated, please use fieldNames instead',
);
});
const {
configProvider,
prefixCls,
renderEmpty,
direction,
virtual,
dropdownMatchSelectWidth,
size,
getPopupContainer,
} = useConfigInject('select', props);
const treePrefixCls = computed(() =>
configProvider.getPrefixCls('select-tree', props.prefixCls),
);
const treeSelectPrefixCls = computed(() =>
configProvider.getPrefixCls('tree-select', props.prefixCls),
);
const mergedDropdownClassName = computed(() =>
classNames(props.dropdownClassName, `${treeSelectPrefixCls.value}-dropdown`, {
[`${treeSelectPrefixCls.value}-dropdown-rtl`]: direction.value === 'rtl',
}),
);
const isMultiple = computed(() => !!(props.treeCheckable || props.multiple));
const treeSelectRef = ref();
expose({
focus() {
treeSelectRef.value.focus?.();
},
blur() {
treeSelectRef.value.blur?.();
},
});
const handleChange = (...args: any[]) => {
emit('update:value', args[0]);
emit('change', ...args);
};
const handleTreeExpand = (...args: any[]) => {
emit('update:treeExpandedKeys', args[0]);
emit('treeExpand', ...args);
};
const handleSearch = (...args: any[]) => {
emit('update:searchValue', args[0]);
emit('search', ...args);
};
return () => {
const {
notFoundContent = slots.notFoundContent?.(),
prefixCls: customizePrefixCls,
bordered,
listHeight,
listItemHeight,
multiple,
treeIcon,
transitionName,
choiceTransitionName,
treeLine,
switcherIcon = slots.switcherIcon?.(),
fieldNames = props.replaceFields,
} = props;
// ===================== Icons =====================
const { suffixIcon, removeIcon, clearIcon } = getIcons(
{
...props,
multiple: isMultiple.value,
prefixCls: prefixCls.value,
},
slots,
);
// ===================== Empty =====================
let mergedNotFound;
if (notFoundContent !== undefined) {
mergedNotFound = notFoundContent;
} else {
mergedNotFound = renderEmpty.value('Select');
}
// ==================== Render =====================
const selectProps = omit(props as typeof props & { itemIcon: any; switcherIcon: any }, [
'suffixIcon',
'itemIcon',
'removeIcon',
'clearIcon',
'switcherIcon',
]);
const mergedClassName = classNames(
!customizePrefixCls && treeSelectPrefixCls.value,
{
[`${prefixCls.value}-lg`]: size.value === 'large',
[`${prefixCls.value}-sm`]: size.value === 'small',
[`${prefixCls.value}-rtl`]: direction.value === 'rtl',
[`${prefixCls.value}-borderless`]: !bordered,
},
attrs.class,
);
const rootPrefixCls = configProvider.getPrefixCls();
return (
<VcTreeSelect
{...attrs}
virtual={virtual.value}
dropdownMatchSelectWidth={dropdownMatchSelectWidth.value}
{...selectProps}
fieldNames={fieldNames}
ref={treeSelectRef}
prefixCls={prefixCls.value}
class={mergedClassName}
listHeight={listHeight}
listItemHeight={listItemHeight}
inputIcon={suffixIcon}
multiple={multiple}
removeIcon={removeIcon}
clearIcon={clearIcon}
switcherIcon={(nodeProps: AntTreeNodeProps) =>
renderSwitcherIcon(treePrefixCls.value, switcherIcon, treeLine, nodeProps)
}
showTreeIcon={treeIcon as any}
notFoundContent={mergedNotFound}
getPopupContainer={getPopupContainer.value}
treeMotion={null}
dropdownClassName={mergedDropdownClassName.value}
choiceTransitionName={getTransitionName(rootPrefixCls, '', choiceTransitionName)}
transitionName={getTransitionName(rootPrefixCls, 'slide-up', transitionName)}
onChange={handleChange}
onSearch={handleSearch}
onTreeExpand={handleTreeExpand}
v-slots={{
treeCheckable: () => <span class={`${prefixCls.value}-tree-checkbox-inner`} />,
}}
children={slots.default?.()}
/>
);
}; };
}, },
created() {
warning(
this.multiple !== false || !this.treeCheckable,
'TreeSelect',
'`multiple` will alway be `true` when `treeCheckable` is true',
);
},
methods: { methods: {
saveTreeSelect(node: any) { saveTreeSelect(node: any) {
this.vcTreeSelect = node; this.vcTreeSelect = node;
@ -112,89 +291,6 @@ const TreeSelect = defineComponent({
}); });
}, },
}, },
render() {
const props: any = getOptionProps(this);
const {
prefixCls: customizePrefixCls,
size,
dropdownStyle,
dropdownClassName,
getPopupContainer,
...restProps
} = props;
const { class: className } = this.$attrs;
const { renderEmpty, getPrefixCls } = this.configProvider;
const prefixCls = getPrefixCls('select', customizePrefixCls);
const notFoundContent = getComponent(this, 'notFoundContent');
const removeIcon = getComponent(this, 'removeIcon');
const clearIcon = getComponent(this, 'clearIcon');
const { getPopupContainer: getContextPopupContainer } = this.configProvider;
const rest = omit(restProps, [
'inputIcon',
'removeIcon',
'clearIcon',
'switcherIcon',
'suffixIcon',
]);
let suffixIcon = getComponent(this, 'suffixIcon');
suffixIcon = Array.isArray(suffixIcon) ? suffixIcon[0] : suffixIcon;
let treeData = props.treeData;
if (treeData) {
treeData = this.updateTreeData(treeData);
}
const cls = {
[`${prefixCls}-lg`]: size === 'large',
[`${prefixCls}-sm`]: size === 'small',
[className as string]: className,
};
// showSearch: single - false, multiple - true
let { showSearch } = restProps;
if (!('showSearch' in restProps)) {
showSearch = !!(restProps.multiple || restProps.treeCheckable);
}
let checkable = getComponent(this, 'treeCheckable');
if (checkable) {
checkable = <span class={`${prefixCls}-tree-checkbox-inner`} />;
}
const inputIcon = suffixIcon || <DownOutlined class={`${prefixCls}-arrow-icon`} />;
const finalRemoveIcon = removeIcon || <CloseOutlined class={`${prefixCls}-remove-icon`} />;
const finalClearIcon = clearIcon || <CloseCircleFilled class={`${prefixCls}-clear-icon`} />;
const VcTreeSelectProps = {
...this.$attrs,
switcherIcon: nodeProps => this.renderSwitcherIcon(prefixCls, nodeProps),
inputIcon,
removeIcon: finalRemoveIcon,
clearIcon: finalClearIcon,
...rest,
showSearch,
getPopupContainer: getPopupContainer || getContextPopupContainer,
dropdownClassName: classNames(dropdownClassName, `${prefixCls}-tree-dropdown`),
prefixCls,
dropdownStyle: { maxHeight: '100vh', overflow: 'auto', ...dropdownStyle },
treeCheckable: checkable,
notFoundContent: notFoundContent || renderEmpty('Select'),
class: cls,
onChange: this.handleChange,
onSearch: this.handleSearch,
onTreeExpand: this.handleTreeExpand,
ref: this.saveTreeSelect,
treeData: treeData ? treeData : convertChildrenToData(getSlot(this)),
};
return (
<VcTreeSelect
{...VcTreeSelectProps}
v-slots={omit(this.$slots, ['default'])}
__propsSymbol__={[]}
/>
);
},
}); });
/* istanbul ignore next */ /* istanbul ignore next */

View File

@ -1,4 +1,5 @@
import type { PropType, ExtractPropTypes } from 'vue'; import type { PropType, ExtractPropTypes } from 'vue';
import { watchEffect } from 'vue';
import { ref } from 'vue'; import { ref } from 'vue';
import { defineComponent } from 'vue'; import { defineComponent } from 'vue';
import classNames from '../_util/classNames'; import classNames from '../_util/classNames';
@ -11,6 +12,7 @@ import { treeProps as vcTreeProps } from '../vc-tree/props';
import useConfigInject from '../_util/hooks/useConfigInject'; import useConfigInject from '../_util/hooks/useConfigInject';
import renderSwitcherIcon from './utils/iconUtil'; import renderSwitcherIcon from './utils/iconUtil';
import dropIndicatorRender from './utils/dropIndicator'; import dropIndicatorRender from './utils/dropIndicator';
import devWarning from '../vc-util/devWarning';
export interface AntdTreeNodeAttribute { export interface AntdTreeNodeAttribute {
eventKey: string; eventKey: string;
@ -160,6 +162,14 @@ export default defineComponent({
}, },
}); });
watchEffect(() => {
devWarning(
props.replaceFields === undefined,
'Tree',
'`replaceFields` is deprecated, please use fieldNames instead',
);
});
const handleCheck: TreeProps['onCheck'] = (checkedObjOrKeys, eventObj) => { const handleCheck: TreeProps['onCheck'] = (checkedObjOrKeys, eventObj) => {
emit('update:checkedKeys', checkedObjOrKeys); emit('update:checkedKeys', checkedObjOrKeys);
emit('check', checkedObjOrKeys, eventObj); emit('check', checkedObjOrKeys, eventObj);
@ -181,8 +191,7 @@ export default defineComponent({
blockNode, blockNode,
checkable, checkable,
selectable, selectable,
fieldNames, fieldNames = props.replaceFields,
replaceFields,
motion = props.openAnimation, motion = props.openAnimation,
} = props; } = props;
const newProps = { const newProps = {
@ -190,7 +199,7 @@ export default defineComponent({
...props, ...props,
showLine: Boolean(showLine), showLine: Boolean(showLine),
dropIndicatorRender, dropIndicatorRender,
fieldNames: fieldNames || (replaceFields as FieldNames), fieldNames,
icon, icon,
}; };

View File

@ -75,8 +75,14 @@ export function selectBaseProps<OptionType, ValueType>() {
mode: { type: String as PropType<Mode> }, mode: { type: String as PropType<Mode> },
// Value // Value
value: { type: [String, Number, Object, Array] as PropType<ValueType> }, value: {
defaultValue: { type: [String, Number, Object, Array] as PropType<ValueType> }, type: [String, Number, Object, Array] as PropType<ValueType>,
default: undefined as ValueType,
},
defaultValue: {
type: [String, Number, Object, Array] as PropType<ValueType>,
default: undefined as ValueType,
},
labelInValue: { type: Boolean, default: undefined }, labelInValue: { type: Boolean, default: undefined },
// Search // Search
@ -194,7 +200,7 @@ export function selectBaseProps<OptionType, ValueType>() {
onRawDeselect?: (value: RawValueType, option: OptionType, source: SelectSource) => void; onRawDeselect?: (value: RawValueType, option: OptionType, source: SelectSource) => void;
}, },
}, },
children: Array, children: { type: Array as PropType<any[]> },
}; };
} }

View File

@ -3,8 +3,9 @@ import Select from './Select';
import Option from './Option'; import Option from './Option';
import OptGroup from './OptGroup'; import OptGroup from './OptGroup';
import { selectBaseProps } from './generate'; import { selectBaseProps } from './generate';
import type { ExtractPropTypes } from 'vue';
export type SelectProps<T = any> = ExportedSelectProps<T>; export type SelectProps<T = any> = Partial<ExtractPropTypes<ExportedSelectProps<T>>>;
export { Option, OptGroup, selectBaseProps }; export { Option, OptGroup, selectBaseProps };
export default Select; export default Select;

View File

@ -1,8 +1,6 @@
import generate, { TreeSelectProps } from './generate'; import generate from './generate';
import OptionList from './OptionList'; import OptionList from './OptionList';
const TreeSelect = generate({ prefixCls: 'vc-tree-select', optionList: OptionList as any }); const TreeSelect = generate({ prefixCls: 'vc-tree-select', optionList: OptionList as any });
export { TreeSelectProps };
export default TreeSelect; export default TreeSelect;

View File

@ -91,7 +91,7 @@ export default function generate(config: {
return defineComponent({ return defineComponent({
name: 'TreeSelect', name: 'TreeSelect',
props: treeSelectProps(), props: treeSelectProps(),
slots: ['placeholder', 'maxTagPlaceholder', 'treeIcon', 'switcherIcon'], slots: ['placeholder', 'maxTagPlaceholder', 'treeIcon', 'switcherIcon', 'notFoundContent'],
TreeNode, TreeNode,
SHOW_ALL, SHOW_ALL,
SHOW_PARENT, SHOW_PARENT,
@ -488,7 +488,7 @@ export default function generate(config: {
mode={mergedMultiple.value ? 'multiple' : null} mode={mergedMultiple.value ? 'multiple' : null}
{...props} {...props}
{...selectProps} {...selectProps}
value={selectValues} value={selectValues.value}
// We will handle this ourself since we need calculate conduction // We will handle this ourself since we need calculate conduction
labelInValue labelInValue
options={mergedTreeData.value} options={mergedTreeData.value}

View File

@ -1,7 +1,8 @@
import TreeSelect, { TreeSelectProps } from './TreeSelect'; import TreeSelect from './TreeSelect';
import TreeNode from './TreeNode'; import TreeNode from './TreeNode';
import { SHOW_ALL, SHOW_CHILD, SHOW_PARENT } from './utils/strategyUtil'; import { SHOW_ALL, SHOW_CHILD, SHOW_PARENT } from './utils/strategyUtil';
import { TreeSelectProps, treeSelectProps } from './props';
export { TreeNode, SHOW_ALL, SHOW_CHILD, SHOW_PARENT, TreeSelectProps }; export { TreeNode, SHOW_ALL, SHOW_CHILD, SHOW_PARENT, TreeSelectProps, treeSelectProps };
export default TreeSelect; export default TreeSelect;