status_content.jsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. import PropTypes from 'prop-types';
  2. import { PureComponent } from 'react';
  3. import { FormattedMessage, injectIntl } from 'react-intl';
  4. import classnames from 'classnames';
  5. import { Link, withRouter } from 'react-router-dom';
  6. import ImmutablePropTypes from 'react-immutable-proptypes';
  7. import { connect } from 'react-redux';
  8. import ChevronRightIcon from '@/material-icons/400-24px/chevron_right.svg?react';
  9. import { Icon } from 'mastodon/components/icon';
  10. import PollContainer from 'mastodon/containers/poll_container';
  11. import { autoPlayGif, languages as preloadedLanguages } from 'mastodon/initial_state';
  12. const MAX_HEIGHT = 706; // 22px * 32 (+ 2px padding at the top)
  13. /**
  14. *
  15. * @param {any} status
  16. * @returns {string}
  17. */
  18. export function getStatusContent(status) {
  19. return status.getIn(['translation', 'contentHtml']) || status.get('contentHtml');
  20. }
  21. class TranslateButton extends PureComponent {
  22. static propTypes = {
  23. translation: ImmutablePropTypes.map,
  24. onClick: PropTypes.func,
  25. };
  26. render () {
  27. const { translation, onClick } = this.props;
  28. if (translation) {
  29. const language = preloadedLanguages.find(lang => lang[0] === translation.get('detected_source_language'));
  30. const languageName = language ? language[2] : translation.get('detected_source_language');
  31. const provider = translation.get('provider');
  32. return (
  33. <div className='translate-button'>
  34. <div className='translate-button__meta'>
  35. <FormattedMessage id='status.translated_from_with' defaultMessage='Translated from {lang} using {provider}' values={{ lang: languageName, provider }} />
  36. </div>
  37. <button className='link-button' onClick={onClick}>
  38. <FormattedMessage id='status.show_original' defaultMessage='Show original' />
  39. </button>
  40. </div>
  41. );
  42. }
  43. return (
  44. <button className='status__content__translate-button' onClick={onClick}>
  45. <FormattedMessage id='status.translate' defaultMessage='Translate' />
  46. </button>
  47. );
  48. }
  49. }
  50. const mapStateToProps = state => ({
  51. languages: state.getIn(['server', 'translationLanguages', 'items']),
  52. });
  53. class StatusContent extends PureComponent {
  54. static contextTypes = {
  55. identity: PropTypes.object,
  56. };
  57. static propTypes = {
  58. status: ImmutablePropTypes.map.isRequired,
  59. statusContent: PropTypes.string,
  60. expanded: PropTypes.bool,
  61. onExpandedToggle: PropTypes.func,
  62. onTranslate: PropTypes.func,
  63. onClick: PropTypes.func,
  64. collapsible: PropTypes.bool,
  65. onCollapsedToggle: PropTypes.func,
  66. languages: ImmutablePropTypes.map,
  67. intl: PropTypes.object,
  68. // from react-router
  69. match: PropTypes.object.isRequired,
  70. location: PropTypes.object.isRequired,
  71. history: PropTypes.object.isRequired
  72. };
  73. state = {
  74. hidden: true,
  75. };
  76. _updateStatusLinks () {
  77. const node = this.node;
  78. if (!node) {
  79. return;
  80. }
  81. const { status, onCollapsedToggle } = this.props;
  82. const links = node.querySelectorAll('a');
  83. let link, mention;
  84. for (var i = 0; i < links.length; ++i) {
  85. link = links[i];
  86. if (link.classList.contains('status-link')) {
  87. continue;
  88. }
  89. link.classList.add('status-link');
  90. mention = this.props.status.get('mentions').find(item => link.href === item.get('url'));
  91. if (mention) {
  92. link.addEventListener('click', this.onMentionClick.bind(this, mention), false);
  93. link.setAttribute('title', `@${mention.get('acct')}`);
  94. link.setAttribute('href', `/@${mention.get('acct')}`);
  95. } else if (link.textContent[0] === '#' || (link.previousSibling && link.previousSibling.textContent && link.previousSibling.textContent[link.previousSibling.textContent.length - 1] === '#')) {
  96. link.addEventListener('click', this.onHashtagClick.bind(this, link.text), false);
  97. link.setAttribute('href', `/tags/${link.text.replace(/^#/, '')}`);
  98. } else {
  99. link.setAttribute('title', link.href);
  100. link.classList.add('unhandled-link');
  101. }
  102. }
  103. if (status.get('collapsed', null) === null && onCollapsedToggle) {
  104. const { collapsible, onClick } = this.props;
  105. const collapsed =
  106. collapsible
  107. && onClick
  108. && node.clientHeight > MAX_HEIGHT
  109. && status.get('spoiler_text').length === 0;
  110. onCollapsedToggle(collapsed);
  111. }
  112. }
  113. handleMouseEnter = ({ currentTarget }) => {
  114. if (autoPlayGif) {
  115. return;
  116. }
  117. const emojis = currentTarget.querySelectorAll('.custom-emoji');
  118. for (var i = 0; i < emojis.length; i++) {
  119. let emoji = emojis[i];
  120. emoji.src = emoji.getAttribute('data-original');
  121. }
  122. };
  123. handleMouseLeave = ({ currentTarget }) => {
  124. if (autoPlayGif) {
  125. return;
  126. }
  127. const emojis = currentTarget.querySelectorAll('.custom-emoji');
  128. for (var i = 0; i < emojis.length; i++) {
  129. let emoji = emojis[i];
  130. emoji.src = emoji.getAttribute('data-static');
  131. }
  132. };
  133. componentDidMount () {
  134. this._updateStatusLinks();
  135. }
  136. componentDidUpdate () {
  137. this._updateStatusLinks();
  138. }
  139. onMentionClick = (mention, e) => {
  140. if (this.props.history && e.button === 0 && !(e.ctrlKey || e.metaKey)) {
  141. e.preventDefault();
  142. this.props.history.push(`/@${mention.get('acct')}`);
  143. }
  144. };
  145. onHashtagClick = (hashtag, e) => {
  146. hashtag = hashtag.replace(/^#/, '');
  147. if (this.props.history && e.button === 0 && !(e.ctrlKey || e.metaKey)) {
  148. e.preventDefault();
  149. this.props.history.push(`/tags/${hashtag}`);
  150. }
  151. };
  152. handleMouseDown = (e) => {
  153. this.startXY = [e.clientX, e.clientY];
  154. };
  155. handleMouseUp = (e) => {
  156. if (!this.startXY) {
  157. return;
  158. }
  159. const [ startX, startY ] = this.startXY;
  160. const [ deltaX, deltaY ] = [Math.abs(e.clientX - startX), Math.abs(e.clientY - startY)];
  161. let element = e.target;
  162. while (element) {
  163. if (element.localName === 'button' || element.localName === 'a' || element.localName === 'label') {
  164. return;
  165. }
  166. element = element.parentNode;
  167. }
  168. if (deltaX + deltaY < 5 && e.button === 0 && this.props.onClick) {
  169. this.props.onClick();
  170. }
  171. this.startXY = null;
  172. };
  173. handleSpoilerClick = (e) => {
  174. e.preventDefault();
  175. if (this.props.onExpandedToggle) {
  176. // The parent manages the state
  177. this.props.onExpandedToggle();
  178. } else {
  179. this.setState({ hidden: !this.state.hidden });
  180. }
  181. };
  182. handleTranslate = () => {
  183. this.props.onTranslate();
  184. };
  185. setRef = (c) => {
  186. this.node = c;
  187. };
  188. render () {
  189. const { status, intl, statusContent } = this.props;
  190. const hidden = this.props.onExpandedToggle ? !this.props.expanded : this.state.hidden;
  191. const renderReadMore = this.props.onClick && status.get('collapsed');
  192. const contentLocale = intl.locale.replace(/[_-].*/, '');
  193. const targetLanguages = this.props.languages?.get(status.get('language') || 'und');
  194. const renderTranslate = this.props.onTranslate && this.context.identity.signedIn && ['public', 'unlisted'].includes(status.get('visibility')) && status.get('search_index').trim().length > 0 && targetLanguages?.includes(contentLocale);
  195. const content = { __html: statusContent ?? getStatusContent(status) };
  196. const spoilerContent = { __html: status.getIn(['translation', 'spoilerHtml']) || status.get('spoilerHtml') };
  197. const language = status.getIn(['translation', 'language']) || status.get('language');
  198. const classNames = classnames('status__content', {
  199. 'status__content--with-action': this.props.onClick && this.props.history,
  200. 'status__content--with-spoiler': status.get('spoiler_text').length > 0,
  201. 'status__content--collapsed': renderReadMore,
  202. });
  203. const readMoreButton = renderReadMore && (
  204. <button className='status__content__read-more-button' onClick={this.props.onClick} key='read-more'>
  205. <FormattedMessage id='status.read_more' defaultMessage='Read more' /><Icon id='angle-right' icon={ChevronRightIcon} />
  206. </button>
  207. );
  208. const translateButton = renderTranslate && (
  209. <TranslateButton onClick={this.handleTranslate} translation={status.get('translation')} />
  210. );
  211. const poll = !!status.get('poll') && (
  212. <PollContainer pollId={status.get('poll')} lang={language} />
  213. );
  214. if (status.get('spoiler_text').length > 0) {
  215. let mentionsPlaceholder = '';
  216. const mentionLinks = status.get('mentions').map(item => (
  217. <Link to={`/@${item.get('acct')}`} key={item.get('id')} className='status-link mention'>
  218. @<span>{item.get('username')}</span>
  219. </Link>
  220. )).reduce((aggregate, item) => [...aggregate, item, ' '], []);
  221. const toggleText = hidden ? <FormattedMessage id='status.show_more' defaultMessage='Show more' /> : <FormattedMessage id='status.show_less' defaultMessage='Show less' />;
  222. if (hidden) {
  223. mentionsPlaceholder = <div>{mentionLinks}</div>;
  224. }
  225. return (
  226. <div className={classNames} ref={this.setRef} tabIndex={0} onMouseDown={this.handleMouseDown} onMouseUp={this.handleMouseUp} onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave}>
  227. <p style={{ marginBottom: hidden && status.get('mentions').isEmpty() ? '0px' : null }}>
  228. <span dangerouslySetInnerHTML={spoilerContent} className='translate' lang={language} />
  229. {' '}
  230. <button type='button' className={`status__content__spoiler-link ${hidden ? 'status__content__spoiler-link--show-more' : 'status__content__spoiler-link--show-less'}`} onClick={this.handleSpoilerClick} aria-expanded={!hidden}>{toggleText}</button>
  231. </p>
  232. {mentionsPlaceholder}
  233. <div tabIndex={!hidden ? 0 : null} className={`status__content__text ${!hidden ? 'status__content__text--visible' : ''} translate`} lang={language} dangerouslySetInnerHTML={content} />
  234. {!hidden && poll}
  235. {translateButton}
  236. </div>
  237. );
  238. } else if (this.props.onClick) {
  239. return (
  240. <>
  241. <div className={classNames} ref={this.setRef} tabIndex={0} onMouseDown={this.handleMouseDown} onMouseUp={this.handleMouseUp} key='status-content' onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave}>
  242. <div className='status__content__text status__content__text--visible translate' lang={language} dangerouslySetInnerHTML={content} />
  243. {poll}
  244. {translateButton}
  245. </div>
  246. {readMoreButton}
  247. </>
  248. );
  249. } else {
  250. return (
  251. <div className={classNames} ref={this.setRef} tabIndex={0} onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave}>
  252. <div className='status__content__text status__content__text--visible translate' lang={language} dangerouslySetInnerHTML={content} />
  253. {poll}
  254. {translateButton}
  255. </div>
  256. );
  257. }
  258. }
  259. }
  260. export default withRouter(connect(mapStateToProps)(injectIntl(StatusContent)));