import React, { ReactElement } from 'react' import { View, ViewStyle, Text, TouchableOpacity } from 'react-native' import variables from '../../common/styles/variables' import Tree from '../../common/utils/Tree' import { Icon } from '../../components/Icon' import treeViewStyles from './styles' export interface TreeViewProps { style?: ViewStyle activeIcon?: ReactElement inactiveIcon?: ReactElement data?: any[] dataStructureType?: string fieldKeys?: any onPress?: Function } export class TreeView extends React.Component { static defaultProps = { style: {}, activeIcon: , inactiveIcon: , data: [], dataStructureType: 'nested', fieldKeys: {} } constructor (props) { super(props) this.state = { ...this.init(props) } } init (props) { const { dataStructureType, data } = props const fieldKeys = this.getFieldKeys(props) const tree = new Tree({ type: dataStructureType, ...fieldKeys, data }).getData() return { tree } } getFieldKeys(props?) { props = props || this.props const fieldKeys = props.fieldKeys || {} return { idKey: fieldKeys.idKey || 'id', pIdKey: fieldKeys.pIdKey || 'pId', labelKey: fieldKeys.labelKey || 'label', childrenKey: fieldKeys.childrenKey || 'children', activeKey: fieldKeys.activeKey || 'active', checkedKey: fieldKeys.checkedKey || 'checked', disabledKey: fieldKeys.disabledKey || 'disabled' } } handlePress = (item) => { this.props.onPress && this.props.onPress(item) const { tree } = this.state const fieldKeys = this.getFieldKeys() let index = null tree.some((treeItem, treeIndex) => { if (treeItem[fieldKeys.idKey] === item[fieldKeys.idKey]) { index = treeIndex return true } }) const tmpTree = tree.concat() tmpTree.splice(index, 1, { ...item, [fieldKeys.activeKey]: !item[fieldKeys.activeKey] }) this.setState({ tree: tmpTree }) } renderItem (data?, level?) { const { tree } = this.state const { activeIcon, inactiveIcon } = this.props const fieldKeys = this.getFieldKeys() if (!data) { data = tree.filter((item) => { return item[fieldKeys.pIdKey] == null }) } level = level || 1 return ( { data.map((item, index) => { const children = tree.filter((treeItem) => { return treeItem[fieldKeys.pIdKey] === item[fieldKeys.idKey] }) return ( { // children.length && // {item[fieldKeys.activeKey] ? activeIcon : inactiveIcon} // children.length > 0 ? ( {item[fieldKeys.activeKey] ? activeIcon : inactiveIcon} ) : null } {item[fieldKeys.labelKey]} {children.length && !!item[fieldKeys.activeKey] ? this.renderItem(children, level + 1) : null} ) }) } ) } render () { return ( {this.renderItem()} ) } }