import { Children, isValidElement, ReactNode } from 'react' import { TreeNode, Props, NodeData } from './TreeNode' import { RcNodeData } from './Tree' import { isDev } from '../utils' // 将 children( 组)转为 treeData export function children2TreeData(node: ReactNode): NodeData[] { const treeData: NodeData[] = [] Children.toArray(node).filter(isValidElement).forEach( ({ type, props }) => { if (type !== TreeNode) { if (isDev) { // eslint-disable-next-line no-console console.warn('Unknown element type, expected ``, while got', type) } return } const { children, ...rest } = props as Props const nodeData: NodeData = rest const childrenData = children2TreeData(children) if (childrenData.length) { nodeData.children = childrenData } treeData.push(nodeData) } ) return treeData } export function treeData2RcTreeData(treeData: T[]): RcNodeData[] { const rcTreeData: RcNodeData[] = [] treeData.forEach(node => { const { children, nodeKey, checkboxDisabled, ...rest } = node const rcNode: RcNodeData = { key: nodeKey, nodeKey, ...rest } if (checkboxDisabled !== undefined) { rcNode.disableCheckbox = checkboxDisabled } if (children?.length) { rcNode.children = treeData2RcTreeData(children) } rcTreeData.push(rcNode) }) return rcTreeData }