client/src/components/CategoriesTooltip.js
author Alexandre Segura <mex.zktk@gmail.com>
Thu, 29 Jun 2017 12:05:09 +0200
changeset 105 0a1d6560acac
parent 25 e04714a1d4eb
child 143 cfcbf4bc66f1
permissions -rw-r--r--
Introduce authenticated routes.

import React, { Component } from 'react';
import { FormGroup, FormControl, Button } from 'react-bootstrap';

class CategoriesTooltip extends Component {

  state = {
    activeCategory: null,
    showCommentControl: false
  }

  componentDidUpdate = () => {
    if (this.state.showCommentControl) {
      this.commentControl.focus();
    }
  }

  isCategoryActive = (category) => {
    return this.state.activeCategory && this.state.activeCategory.key === category.key
  }

  onButtonClick = (category) => {
    if (category.hasOwnProperty('hasComment') && category.hasComment === true) {
      this.setState({
        activeCategory: this.state.activeCategory ? null : category,
        showCommentControl: !this.state.showCommentControl
      })
    } else {
      if (typeof this.props.onCategoryClick === 'function') {
        this.props.onCategoryClick(category)
      }
    }
  }

  onSubmit = (e) => {
    e.preventDefault();
    if (this.state.showCommentControl) {
      const comment = this.commentControl.value;
      const { activeCategory } = this.state;
      Object.assign(activeCategory, { comment: comment });
      if (typeof this.props.onCategoryClick === 'function') {
        this.props.onCategoryClick(activeCategory)
      }
    }
  }

  render() {
    return (
      <div className="categories-tooltip">
        <form onSubmit={ this.onSubmit }>
          <FormGroup className="buttons">
          {this.props.categories.map((category) =>
            <Button
              key={ category.name }
              bsStyle="primary"
              style={{ backgroundColor: category.color }}
              active={ this.isCategoryActive(category)  }
              onClick={ this.onButtonClick.bind(this, category) }>{ category.name }</Button>
          )}
          </FormGroup>
          {this.state.showCommentControl &&
          <FormGroup>
            <FormControl inputRef={(ref) => { this.commentControl = ref; }} />
          </FormGroup>}
        </form>
      </div>
    );
  }
}

export default CategoriesTooltip