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

99 lines
2.7 KiB
React
Raw Normal View History

import { Components, registerComponent } from 'meteor/nova:lib';
import React, { PropTypes, Component } from 'react';
import classNames from 'classnames';
import { withCurrentUser, withMessages } from 'meteor/nova:core';
2016-11-29 18:52:13 +09:00
import { withVote, hasUpvoted, hasDownvoted } from 'meteor/nova:voting';
2016-03-21 10:50:22 +09:00
class Vote extends Component {
constructor() {
super();
this.upvote = this.upvote.bind(this);
2017-01-14 18:03:35 +09:00
this.getActionClass = this.getActionClass.bind(this);
// this.startLoading = this.startLoading.bind(this);
// this.stopLoading = this.stopLoading.bind(this);
this.state = {
loading: false
}
}
/*
note: with optimisitc UI, loading functions are not needed
also, setState triggers issues when the component is unmounted
before the vote mutation returns.
*/
// startLoading() {
// this.setState({ loading: true });
// }
// stopLoading() {
// this.setState({ loading: false });
// }
upvote(e) {
e.preventDefault();
// this.startLoading();
const document = this.props.document;
const collection = this.props.collection;
2016-11-15 18:33:16 +01:00
const user = this.props.currentUser;
if(!user){
this.props.flash("Please log in first");
// this.stopLoading();
} else {
2017-01-14 18:03:35 +09:00
const voteType = hasUpvoted(user, document) ? "cancelUpvote" : "upvote";
this.props.vote({document, voteType, collection, currentUser: this.props.currentUser}).then(result => {
// this.stopLoading();
});
}
}
2017-01-14 18:03:35 +09:00
getActionClass() {
const document = this.props.document;
2016-11-15 18:33:16 +01:00
const user = this.props.currentUser;
2017-01-14 18:03:35 +09:00
const isUpvoted = hasUpvoted(user, document);
const isDownvoted = hasDownvoted(user, document);
const actionsClass = classNames(
2017-01-14 18:03:35 +09:00
'vote',
{voted: isUpvoted || isDownvoted},
{upvoted: isUpvoted},
{downvoted: isDownvoted}
);
2017-01-14 18:03:35 +09:00
return actionsClass;
}
render() {
return (
2017-01-14 18:03:35 +09:00
<div className={this.getActionClass()}>
<a className="upvote-button" onClick={this.upvote}>
{this.state.loading ? <Components.Icon name="spinner" /> : <Components.Icon name="upvote" /> }
2016-03-24 16:03:30 +09:00
<div className="sr-only">Upvote</div>
2017-01-14 18:03:35 +09:00
<div className="vote-count">{this.props.document.baseScore || 0}</div>
</a>
</div>
)
}
}
Vote.propTypes = {
document: React.PropTypes.object.isRequired, // the document to upvote
collection: React.PropTypes.object.isRequired, // the collection containing the document
vote: React.PropTypes.func.isRequired, // mutate function with callback inside
2017-01-23 10:30:58 +09:00
currentUser: React.PropTypes.object, // user might not be logged in, so don't make it required
};
Vote.contextTypes = {
actions: React.PropTypes.object,
events: React.PropTypes.object,
};
registerComponent('Vote', Vote, withMessages, withVote);