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.

206 lines
7.0 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 expires_at = poll.get('expires_at');
  37. const expired = poll.get('expired') || expires_at !== null && (new Date(expires_at)).getTime() < intl.now();
  38. return (expired === state.expired) ? null : { expired };
  39. }
  40. componentDidMount () {
  41. this._setupTimer();
  42. }
  43. componentDidUpdate () {
  44. this._setupTimer();
  45. }
  46. componentWillUnmount () {
  47. clearTimeout(this._timer);
  48. }
  49. _setupTimer () {
  50. const { poll, intl } = this.props;
  51. clearTimeout(this._timer);
  52. if (!this.state.expired) {
  53. const delay = (new Date(poll.get('expires_at'))).getTime() - intl.now();
  54. this._timer = setTimeout(() => {
  55. this.setState({ expired: true });
  56. }, delay);
  57. }
  58. }
  59. _toggleOption = value => {
  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. handleOptionChange = ({ target: { value } }) => {
  75. this._toggleOption(value);
  76. };
  77. handleOptionKeyPress = (e) => {
  78. if (e.key === 'Enter' || e.key === ' ') {
  79. this._toggleOption(e.target.getAttribute('data-index'));
  80. e.stopPropagation();
  81. e.preventDefault();
  82. }
  83. }
  84. handleVote = () => {
  85. if (this.props.disabled) {
  86. return;
  87. }
  88. this.props.dispatch(vote(this.props.poll.get('id'), Object.keys(this.state.selected)));
  89. };
  90. handleRefresh = () => {
  91. if (this.props.disabled) {
  92. return;
  93. }
  94. this.props.dispatch(fetchPoll(this.props.poll.get('id')));
  95. };
  96. renderOption (option, optionIndex, showResults) {
  97. const { poll, disabled, intl } = this.props;
  98. const pollVotesCount = poll.get('voters_count') || poll.get('votes_count');
  99. const percent = pollVotesCount === 0 ? 0 : (option.get('votes_count') / pollVotesCount) * 100;
  100. const leading = poll.get('options').filterNot(other => other.get('title') === option.get('title')).every(other => option.get('votes_count') >= other.get('votes_count'));
  101. const active = !!this.state.selected[`${optionIndex}`];
  102. const voted = option.get('voted') || (poll.get('own_votes') && poll.get('own_votes').includes(optionIndex));
  103. let titleEmojified = option.get('title_emojified');
  104. if (!titleEmojified) {
  105. const emojiMap = makeEmojiMap(poll);
  106. titleEmojified = emojify(escapeTextContentForBrowser(option.get('title')), emojiMap);
  107. }
  108. return (
  109. <li key={option.get('title')}>
  110. {showResults && (
  111. <Motion defaultStyle={{ width: 0 }} style={{ width: spring(percent, { stiffness: 180, damping: 12 }) }}>
  112. {({ width }) =>
  113. <span className={classNames('poll__chart', { leading })} style={{ width: `${width}%` }} />
  114. }
  115. </Motion>
  116. )}
  117. <label className={classNames('poll__text', { selectable: !showResults })}>
  118. <input
  119. name='vote-options'
  120. type={poll.get('multiple') ? 'checkbox' : 'radio'}
  121. value={optionIndex}
  122. checked={active}
  123. onChange={this.handleOptionChange}
  124. disabled={disabled}
  125. />
  126. {!showResults && (
  127. <span
  128. className={classNames('poll__input', { checkbox: poll.get('multiple'), active })}
  129. tabIndex='0'
  130. role={poll.get('multiple') ? 'checkbox' : 'radio'}
  131. onKeyPress={this.handleOptionKeyPress}
  132. aria-checked={active}
  133. aria-label={option.get('title')}
  134. data-index={optionIndex}
  135. />
  136. )}
  137. {showResults && <span className='poll__number'>
  138. {!!voted && <Icon id='check' className='poll__vote__mark' title={intl.formatMessage(messages.voted)} />}
  139. {Math.round(percent)}%
  140. </span>}
  141. <span dangerouslySetInnerHTML={{ __html: titleEmojified }} />
  142. </label>
  143. </li>
  144. );
  145. }
  146. render () {
  147. const { poll, intl } = this.props;
  148. const { expired } = this.state;
  149. if (!poll) {
  150. return null;
  151. }
  152. const timeRemaining = expired ? intl.formatMessage(messages.closed) : <RelativeTimestamp timestamp={poll.get('expires_at')} futureDate />;
  153. const showResults = poll.get('voted') || expired;
  154. const disabled = this.props.disabled || Object.entries(this.state.selected).every(item => !item);
  155. let votesCount = null;
  156. if (poll.get('voters_count') !== null && poll.get('voters_count') !== undefined) {
  157. votesCount = <FormattedMessage id='poll.total_people' defaultMessage='{count, plural, one {# person} other {# people}}' values={{ count: poll.get('voters_count') }} />;
  158. } else {
  159. votesCount = <FormattedMessage id='poll.total_votes' defaultMessage='{count, plural, one {# vote} other {# votes}}' values={{ count: poll.get('votes_count') }} />;
  160. }
  161. return (
  162. <div className='poll'>
  163. <ul>
  164. {poll.get('options').map((option, i) => this.renderOption(option, i, showResults))}
  165. </ul>
  166. <div className='poll__footer'>
  167. {!showResults && <button className='button button-secondary' disabled={disabled} onClick={this.handleVote}><FormattedMessage id='poll.vote' defaultMessage='Vote' /></button>}
  168. {showResults && !this.props.disabled && <span><button className='poll__link' onClick={this.handleRefresh}><FormattedMessage id='poll.refresh' defaultMessage='Refresh' /></button> · </span>}
  169. {votesCount}
  170. {poll.get('expires_at') && <span> · {timeRemaining}</span>}
  171. </div>
  172. </div>
  173. );
  174. }
  175. }