You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

185 lines
6.4 KiB

  1. import React from 'react';
  2. import PropTypes from 'prop-types';
  3. import ImmutablePropTypes from 'react-immutable-proptypes';
  4. import ImmutablePureComponent from 'react-immutable-pure-component';
  5. import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
  6. import classNames from 'classnames';
  7. import { vote, fetchPoll } from 'mastodon/actions/polls';
  8. import Motion from 'mastodon/features/ui/util/optional_motion';
  9. import spring from 'react-motion/lib/spring';
  10. import escapeTextContentForBrowser from 'escape-html';
  11. import emojify from 'mastodon/features/emoji/emoji';
  12. import RelativeTimestamp from './relative_timestamp';
  13. import Icon from 'mastodon/components/icon';
  14. const messages = defineMessages({
  15. closed: { id: 'poll.closed', defaultMessage: 'Closed' },
  16. voted: { id: 'poll.voted', defaultMessage: 'You voted for this answer', description: 'Tooltip of the "voted" checkmark in polls' },
  17. });
  18. const makeEmojiMap = record => record.get('emojis').reduce((obj, emoji) => {
  19. obj[`:${emoji.get('shortcode')}:`] = emoji.toJS();
  20. return obj;
  21. }, {});
  22. export default @injectIntl
  23. class Poll extends ImmutablePureComponent {
  24. static propTypes = {
  25. poll: ImmutablePropTypes.map,
  26. intl: PropTypes.object.isRequired,
  27. dispatch: PropTypes.func,
  28. disabled: PropTypes.bool,
  29. };
  30. state = {
  31. selected: {},
  32. expired: null,
  33. };
  34. static getDerivedStateFromProps (props, state) {
  35. const { poll, intl } = props;
  36. const expired = poll.get('expired') || (new Date(poll.get('expires_at'))).getTime() < intl.now();
  37. return (expired === state.expired) ? null : { expired };
  38. }
  39. componentDidMount () {
  40. this._setupTimer();
  41. }
  42. componentDidUpdate () {
  43. this._setupTimer();
  44. }
  45. componentWillUnmount () {
  46. clearTimeout(this._timer);
  47. }
  48. _setupTimer () {
  49. const { poll, intl } = this.props;
  50. clearTimeout(this._timer);
  51. if (!this.state.expired) {
  52. const delay = (new Date(poll.get('expires_at'))).getTime() - intl.now();
  53. this._timer = setTimeout(() => {
  54. this.setState({ expired: true });
  55. }, delay);
  56. }
  57. }
  58. handleOptionChange = e => {
  59. const { target: { value } } = e;
  60. if (this.props.poll.get('multiple')) {
  61. const tmp = { ...this.state.selected };
  62. if (tmp[value]) {
  63. delete tmp[value];
  64. } else {
  65. tmp[value] = true;
  66. }
  67. this.setState({ selected: tmp });
  68. } else {
  69. const tmp = {};
  70. tmp[value] = true;
  71. this.setState({ selected: tmp });
  72. }
  73. };
  74. handleVote = () => {
  75. if (this.props.disabled) {
  76. return;
  77. }
  78. this.props.dispatch(vote(this.props.poll.get('id'), Object.keys(this.state.selected)));
  79. };
  80. handleRefresh = () => {
  81. if (this.props.disabled) {
  82. return;
  83. }
  84. this.props.dispatch(fetchPoll(this.props.poll.get('id')));
  85. };
  86. renderOption (option, optionIndex, showResults) {
  87. const { poll, disabled, intl } = this.props;
  88. const pollVotesCount = poll.get('voters_count') || poll.get('votes_count');
  89. const percent = pollVotesCount === 0 ? 0 : (option.get('votes_count') / pollVotesCount) * 100;
  90. const leading = poll.get('options').filterNot(other => other.get('title') === option.get('title')).every(other => option.get('votes_count') >= other.get('votes_count'));
  91. const active = !!this.state.selected[`${optionIndex}`];
  92. const voted = option.get('voted') || (poll.get('own_votes') && poll.get('own_votes').includes(optionIndex));
  93. let titleEmojified = option.get('title_emojified');
  94. if (!titleEmojified) {
  95. const emojiMap = makeEmojiMap(poll);
  96. titleEmojified = emojify(escapeTextContentForBrowser(option.get('title')), emojiMap);
  97. }
  98. return (
  99. <li key={option.get('title')}>
  100. {showResults && (
  101. <Motion defaultStyle={{ width: 0 }} style={{ width: spring(percent, { stiffness: 180, damping: 12 }) }}>
  102. {({ width }) =>
  103. <span className={classNames('poll__chart', { leading })} style={{ width: `${width}%` }} />
  104. }
  105. </Motion>
  106. )}
  107. <label className={classNames('poll__text', { selectable: !showResults })}>
  108. <input
  109. name='vote-options'
  110. type={poll.get('multiple') ? 'checkbox' : 'radio'}
  111. value={optionIndex}
  112. checked={active}
  113. onChange={this.handleOptionChange}
  114. disabled={disabled}
  115. />
  116. {!showResults && <span className={classNames('poll__input', { checkbox: poll.get('multiple'), active })} />}
  117. {showResults && <span className='poll__number'>
  118. {!!voted && <Icon id='check' className='poll__vote__mark' title={intl.formatMessage(messages.voted)} />}
  119. {Math.round(percent)}%
  120. </span>}
  121. <span dangerouslySetInnerHTML={{ __html: titleEmojified }} />
  122. </label>
  123. </li>
  124. );
  125. }
  126. render () {
  127. const { poll, intl } = this.props;
  128. const { expired } = this.state;
  129. if (!poll) {
  130. return null;
  131. }
  132. const timeRemaining = expired ? intl.formatMessage(messages.closed) : <RelativeTimestamp timestamp={poll.get('expires_at')} futureDate />;
  133. const showResults = poll.get('voted') || expired;
  134. const disabled = this.props.disabled || Object.entries(this.state.selected).every(item => !item);
  135. let votesCount = null;
  136. if (poll.get('voters_count') !== null && poll.get('voters_count') !== undefined) {
  137. votesCount = <FormattedMessage id='poll.total_people' defaultMessage='{count, plural, one {# person} other {# people}}' values={{ count: poll.get('voters_count') }} />;
  138. } else {
  139. votesCount = <FormattedMessage id='poll.total_votes' defaultMessage='{count, plural, one {# vote} other {# votes}}' values={{ count: poll.get('votes_count') }} />;
  140. }
  141. return (
  142. <div className='poll'>
  143. <ul>
  144. {poll.get('options').map((option, i) => this.renderOption(option, i, showResults))}
  145. </ul>
  146. <div className='poll__footer'>
  147. {!showResults && <button className='button button-secondary' disabled={disabled} onClick={this.handleVote}><FormattedMessage id='poll.vote' defaultMessage='Vote' /></button>}
  148. {showResults && !this.props.disabled && <span><button className='poll__link' onClick={this.handleRefresh}><FormattedMessage id='poll.refresh' defaultMessage='Refresh' /></button> · </span>}
  149. {votesCount}
  150. {poll.get('expires_at') && <span> · {timeRemaining}</span>}
  151. </div>
  152. </div>
  153. );
  154. }
  155. }