client/src/components/Note.js
author Alexandre Segura <mex.zktk@gmail.com>
Fri, 23 Jun 2017 15:57:35 +0200
changeset 82 6f2999873343
parent 80 b3a02ea6d097
child 84 bf35a7737f94
permissions -rw-r--r--
Add close icon when editing note.

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import PropTypes from 'prop-types';
import { formatTimestamp } from '../utils';
import SlateEditor from './SlateEditor';
import * as notesActions from '../actions/notesActions';

class Note extends Component {

  state = {
    edit: false
  }

  enterEditMode = () => {
    const { edit } = this.state;
    if (edit) return;
    this.setState({ edit: true })
  }

  onClickDelete = (e) => {
    e.preventDefault();
    e.stopPropagation();

    this.props.notesActions.deleteNote(this.props.note);
  }

  onClickButton = (e) => {

    const plain = this.refs.editor.asPlain();
    const raw = this.refs.editor.asRaw();
    const html = this.refs.editor.asHtml();
    const categories = this.refs.editor.asCategories();

    this.props.notesActions.updateNote(this.props.note, {
      plain,
      raw,
      html,
      categories
    });

    this.setState({ edit: false })
  }

  onClickClose = (e) => {
    e.preventDefault();
    e.stopPropagation();

    this.setState({ edit: false })
  }

  renderNoteContent() {
    if (this.state.edit) {
      return (
        <div className="note-content">
          <SlateEditor ref="editor"
            onButtonClick={ this.onClickButton }
            note={ this.props.note } />
        </div>
      )
    }

    return (
      <div className="note-content" dangerouslySetInnerHTML={{ __html: this.props.note.html }} />
    )
  }

  renderNoteRight() {
    if (this.state.edit) {
      return (
        <a onClick={this.onClickClose}>
          <span className="material-icons">close</span>
        </a>
      );
    }

    return (
      <a onClick={this.onClickDelete}>
        <span className="material-icons">delete</span>
      </a>
    )
  }

  render() {
    return (
      <div id={"note-" + this.props.note._id} className="note" onClick={ this.enterEditMode }>
        <span className="start">{ formatTimestamp(this.props.note.startedAt) }</span>
        <span className="finish">{ formatTimestamp(this.props.note.finishedAt) }</span>
        { this.renderNoteContent() }
        <div className="note-margin-comment">
          <small className="text-muted">{ this.props.note.marginComment }</small>
        </div>
        { this.renderNoteRight() }
      </div>
    );
  };
}

Note.propTypes = {
  note: PropTypes.object.isRequired
};

function mapStateToProps(state, props) {
  return props;
}

function mapDispatchToProps(dispatch) {
  return {
    notesActions: bindActionCreators(notesActions, dispatch),
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(Note);