Vulcan/packages/nova-base-components/lib/common/Vote.jsx

90 lines
2.5 KiB
React
Raw Normal View History

2016-08-08 11:18:21 +09:00
import Telescope from 'meteor/nova:lib';
import React, { PropTypes, Component } from 'react';
import classNames from 'classnames';
2016-06-23 15:00:58 +09:00
import Users from 'meteor/nova:users';
2016-11-11 18:29:49 +09:00
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { withVoteMutation } from 'meteor/nova:base-containers';
2016-11-15 18:33:16 +01:00
import { withCurrentUser } from 'meteor/nova:core';
2016-03-21 10:50:22 +09:00
class Vote extends Component {
constructor() {
super();
this.upvote = this.upvote.bind(this);
this.startLoading = this.startLoading.bind(this);
this.stopLoading = this.stopLoading.bind(this);
this.state = {
loading: false
}
}
startLoading() {
this.setState({ loading: true });
}
stopLoading() {
this.setState({ loading: false });
}
upvote(e) {
e.preventDefault();
this.startLoading();
const post = this.props.post;
2016-11-15 18:33:16 +01:00
const user = this.props.currentUser;
if(!user){
this.props.flash("Please log in first");
} else {
const voteType = Users.hasUpvoted(user, post) ? "cancelUpvote" : "upvote";
2016-11-15 18:33:16 +01:00
this.props.vote({post, voteType, currentUser: this.props.currentUser}).then(result => {
this.stopLoading();
});
}
}
render() {
2016-03-21 10:46:00 +09:00
const post = this.props.post;
2016-11-15 18:33:16 +01:00
const user = this.props.currentUser;
const hasUpvoted = Users.hasUpvoted(user, post);
const hasDownvoted = Users.hasDownvoted(user, post);
const actionsClass = classNames(
"vote",
{voted: hasUpvoted || hasDownvoted},
{upvoted: hasUpvoted},
{downvoted: hasDownvoted}
);
return (
<div className={actionsClass}>
<a className="upvote-button" onClick={this.upvote}>
{this.state.loading ? <Telescope.components.Icon name="spinner" /> : <Telescope.components.Icon name="upvote" /> }
2016-03-24 16:03:30 +09:00
<div className="sr-only">Upvote</div>
2016-03-25 10:45:28 +09:00
<div className="vote-count">{post.baseScore || 0}</div>
</a>
</div>
)
}
}
Vote.propTypes = {
post: React.PropTypes.object.isRequired, // the current post
vote: React.PropTypes.func, // mutate function with callback inside
2016-11-15 18:33:16 +01:00
currentUser: React.PropTypes.object,
};
Vote.contextTypes = {
actions: React.PropTypes.object,
events: React.PropTypes.object,
};
2016-11-11 18:29:49 +09:00
// redux state + actions for messages
const mapStateToProps = state => ({ messages: state.messages });
const mapDispatchToProps = dispatch => bindActionCreators(Telescope.actions.messages, dispatch);
Telescope.registerComponent('Vote', Vote, withCurrentUser, connect(mapStateToProps, mapDispatchToProps), withVoteMutation);