|
import React, { Component } from 'react'; |
|
import PropTypes from 'prop-types'; |
|
|
|
import { precisionRound } from '../../utils'; |
|
|
|
import ChevronUpIcon from 'react-feather/dist/icons/chevron-up'; |
|
import ChevronDownIcon from 'react-feather/dist/icons/chevron-down'; |
|
|
|
class VoteButtons extends Component { |
|
/** an enumeration of the possible vote states for vote buttons */ |
|
static voteStates = { |
|
noVote: 0, |
|
upVote: 1, |
|
downVote: 2, |
|
} |
|
|
|
static propTypes = { |
|
initialVote: PropTypes.number, // the initial selected vote |
|
onVote: PropTypes.func, // called with voteType when user votes |
|
initialVotesCount: PropTypes.number, // the number of upvotes |
|
} |
|
|
|
static defaultProps = { |
|
initialVote: VoteButtons.voteStates.noVote, |
|
onVote: undefined, |
|
initialVotesCount: 0, |
|
} |
|
|
|
constructor(props) { |
|
super(props); |
|
|
|
this.state = { |
|
vote: this.props.initialVote, |
|
votesCount: this.props.initialVotesCount, |
|
} |
|
} |
|
|
|
/** Formats the number of votes for display |
|
* @return {string} the formatted number of votes */ |
|
formattedVoteCount = () => { |
|
const { votesCount } = this.state; |
|
|
|
if (votesCount >= 1000) { |
|
return precisionRound(votesCount / 1000, 2) + 'k'; |
|
} |
|
|
|
return votesCount + ''; |
|
} |
|
|
|
/** Called when user votes |
|
* @param {number} voteType The type of vote registered */ |
|
onClickVote(voteType) { |
|
if (this.state.vote === voteType) { |
|
this.setState({ |
|
vote: VoteButtons.voteStates.noVote, |
|
votesCount: this.props.initialVotesCount, |
|
}); |
|
} else { |
|
if (this.props.onVote) { |
|
this.props.onVote(voteType); |
|
} |
|
|
|
if (voteType === VoteButtons.voteStates.upVote) { |
|
this.setState({votesCount: this.props.initialVotesCount + 1}); |
|
} else { |
|
this.setState({votesCount: this.props.initialVotesCount - 1}); |
|
} |
|
|
|
this.setState({vote: voteType}); |
|
} |
|
} |
|
|
|
render() { |
|
return ( |
|
<div className='VoteButtons'> |
|
|
|
{/* Upvote Button */} |
|
<button className='vote-button' |
|
onClick={this.onClickVote.bind(this, VoteButtons.voteStates.upVote)}> |
|
<ChevronUpIcon |
|
color={this.state.vote === VoteButtons.voteStates.upVote ? 'red' : 'black'} |
|
/> |
|
</button> |
|
|
|
{/* Formatted Vote Count */} |
|
{this.formattedVoteCount()} |
|
|
|
{/* Downvote Button */} |
|
<button className='vote-button' |
|
onClick={this.onClickVote.bind(this, VoteButtons.voteStates.downVote)}> |
|
<ChevronDownIcon |
|
color={this.state.vote === VoteButtons.voteStates.downVote ? 'turquoise' : 'black'} |
|
/> |
|
</button> |
|
</div> |
|
); |
|
} |
|
} |
|
|
|
export default VoteButtons; |