ant-design-vue/components/vc-select/utils/legacyUtil.ts

62 lines
1.8 KiB
TypeScript
Raw Normal View History

2020-10-07 14:49:01 +00:00
import { flattenChildren, isValidElement } from '../../_util/props-util';
2021-12-16 09:20:18 +00:00
import type { VNode } from 'vue';
import type { BaseOptionType, DefaultOptionType } from '../Select';
2021-12-16 09:20:18 +00:00
import type { VueNode } from '../../_util/type';
2020-10-07 14:49:01 +00:00
function convertNodeToOption<OptionType extends BaseOptionType = DefaultOptionType>(
node: VNode,
): OptionType {
2020-10-07 14:49:01 +00:00
const {
key,
children,
2020-10-24 15:52:51 +00:00
props: { value, disabled, ...restProps },
2021-08-10 07:21:13 +00:00
} = node as Omit<VNode, 'key'> & {
2020-10-07 14:49:01 +00:00
children: { default?: () => any };
2021-08-10 07:21:13 +00:00
key: string | number;
2020-10-07 14:49:01 +00:00
};
2022-04-03 02:00:48 +00:00
const child = children?.default;
2020-10-24 15:52:51 +00:00
return {
key,
value: value !== undefined ? value : key,
children: child,
disabled: disabled || disabled === '', // support <a-select-option disabled />
...(restProps as any),
2020-10-24 15:52:51 +00:00
};
2020-10-07 14:49:01 +00:00
}
export function convertChildrenToData<OptionType extends BaseOptionType = DefaultOptionType>(
nodes: VueNode[],
optionOnly = false,
): OptionType[] {
2020-10-10 09:01:39 +00:00
const dd = flattenChildren(nodes as [])
.map((node: VNode, index: number): OptionType | null => {
2020-10-07 14:49:01 +00:00
if (!isValidElement(node) || !node.type) {
return null;
}
const {
type: { isSelectOptGroup },
key,
children,
props,
} = node as VNode & {
type: { isSelectOptGroup?: boolean };
2021-03-28 12:28:08 +00:00
children: { default?: () => any; label?: () => any };
2020-10-07 14:49:01 +00:00
};
if (optionOnly || !isSelectOptGroup) {
return convertNodeToOption(node);
}
const child = children && children.default ? children.default() : undefined;
2021-03-28 12:28:08 +00:00
const label = props?.label || children.label?.() || key;
2020-10-07 14:49:01 +00:00
return {
2021-08-10 07:21:13 +00:00
key: `__RC_SELECT_GRP__${key === null ? index : String(key)}__`,
2020-10-07 14:49:01 +00:00
...props,
2021-03-28 12:28:08 +00:00
label,
2020-10-07 14:49:01 +00:00
options: convertChildrenToData(child || []),
} as any;
})
.filter(data => data);
return dd;
}