uxilab / uxi

UXI Core components - https://twitter.com/uxi_lab
https://www.uxilab.eu/
5 stars 1 forks source link

Tree component in UXI #38

Closed dervalp closed 5 years ago

dervalp commented 5 years ago
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import KeyDown from 'material-ui/svg-icons/navigation/expand-more';
import KeyRight from 'material-ui/svg-icons/navigation/chevron-right';
import Checkbox from 'material-ui/Checkbox';

const TreeNodeStyle = {
  titleContainer: {
    display: 'flex',
    cursor: 'pointer',
  },
  titleIcon: {
    width: '30px',
  },
  title: {
    flex: 1,
  },
  titleH5: {
    margin: '5px',
  },
};

export default class TreeNode extends Component {
  static propTypes = {
    isChecked: PropTypes.bool.isRequired,
    onSelect: PropTypes.func.isRequired,
    node: PropTypes.shape({
      Id: PropTypes.string.isRequired,
      Name: PropTypes.string.isRequired,
      IsChecked: PropTypes.bool,
      Parent: PropTypes.any,
    }).isRequired,
  }

  constructor(props) {
    super(props);
    this.state = {
      visible: true,
      isChecked: props.isChecked || false,
    };
  }

  componentWillReceiveProps(nextProp) {
    this.setState({ isChecked: nextProp.isChecked });
  }

  toggle = () => {
    this.setState({ visible: !this.state.visible });
  }

  select = (event, isChecked) => {
    const { onSelect, node } = this.props;

    if (onSelect) {
      onSelect({
        node,
        isChecked,
      });
    }
  }

  render() {
    const {
      node,
      onSelect,
      className,
    } = this.props;

    let childNodes;
    let content;
    let mainStyle = {};

    const nodeValue = node.IsChecked || false;

    if (node.childNodes != null) {
      childNodes = node.childNodes.map(
        (n, index) => (
          <li key={index}><TreeNode onSelect={onSelect} node={n} /></li>
        )
      );

      mainStyle = {
      };
    }

    const title = node.title || node.Name;

    if (this.state.visible) {
      let icon;

      if (node.childNodes && node.childNodes.length) {
        icon = <a onClick={this.toggle} style={TreeNodeStyle.titleIcon}><KeyDown /></a>;
      }

      content = (
        <div style={TreeNodeStyle.titleContainer}>
          {icon}
          <Checkbox checked={nodeValue} onCheck={this.select.bind(this)} label={title} />
        </div>
      );
    } else {
      let iconNotVisible;

      if (node.childNodes && node.childNodes.length) {
        iconNotVisible = <a onClick={this.toggle} style={TreeNodeStyle.titleIcon}><KeyRight /></a>;
      }

      content = (
        <div style={TreeNodeStyle.titleContainer}>
          {iconNotVisible}
          <Checkbox checked={nodeValue} onCheck={this.select.bind(this)} label={title} />
        </div>
      );
    }

    return (
      <div className={className} style={mainStyle}>
        {content}
        <ul >
          {childNodes}
        </ul>
      </div>
    );
  }
}