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.

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