import { h, Component } from 'preact'; import api from 'common/api'; import { url } from 'common/settings'; import store from 'common/store'; import Input from 'components/input'; export default class Comment extends Component { constructor(props) { super(props); this.state = { isInputVisible: false, }; this.updateScoreState(props); this.decreaseScore = this.decreaseScore.bind(this); this.increaseScore = this.increaseScore.bind(this); this.onReplyClick = this.onReplyClick.bind(this); this.onReply = this.onReply.bind(this); } componentWillReceiveProps(nextProps) { this.updateScoreState(nextProps); } updateScoreState(props) { const { score = 0, votes = [] } = props.data; const userId = store.get('user').id; this.setState({ score: score, scoreIncreased: userId in votes && votes[userId], scoreDecreased: userId in votes && !votes[userId], }); } onReplyClick() { const { isInputVisible } = this.state; this.setState({ isInputVisible: !isInputVisible }); } increaseScore() { const { score, scoreIncreased, scoreDecreased } = this.state; const { id } = this.props.data; if (scoreIncreased) return; this.setState({ scoreIncreased: !scoreDecreased, scoreDecreased: false, score: score + 1, }); api.vote({ id, url, value: 1 }).then(() => { api.getComment({ id }).then(comment => store.replaceComment(comment)); }); } decreaseScore() { const { score, scoreIncreased, scoreDecreased } = this.state; const { id } = this.props.data; if (scoreDecreased) return; this.setState({ scoreDecreased: !scoreIncreased, scoreIncreased: false, score: score - 1, }); api.vote({ id, url, value: -1 }).then(() => { api.getComment({ id }).then(comment => store.replaceComment(comment)); }); } onReply(...rest) { this.props.onReply(...rest); this.setState({ isInputVisible: false }); } render(props, { score, scoreIncreased, scoreDecreased, isInputVisible }) { const { data, mix, mods = {} } = props; const time = new Date(data.time); // TODO: which format for datetime should we choose? // TODO: add smth that will count 'hours ago' (mb this: https://github.com/catamphetamine/javascript-time-ago) // TODO: check out stash's impl; // TODO: don't forget about optional locales, m? const timeStr = `${time.toLocaleDateString([], { month: 'short', day: 'numeric' })}, ${time.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}`; const o = { ...data, time: timeStr, score: { value: Math.abs(score), sign: score > 0 ? '+' : (score < 0 ? '−' : ''), }, }; return ( // TODO: add default view mod or don't?
{o.user.name} vote up {o.score.sign} {o.score.value} vote down {o.time} reply
{ isInputVisible && ( ) }
); } }