status.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. import React from 'react';
  2. import ImmutablePropTypes from 'react-immutable-proptypes';
  3. import PropTypes from 'prop-types';
  4. import Avatar from './avatar';
  5. import AvatarOverlay from './avatar_overlay';
  6. import RelativeTimestamp from './relative_timestamp';
  7. import DisplayName from './display_name';
  8. import StatusContent from './status_content';
  9. import StatusActionBar from './status_action_bar';
  10. import AttachmentList from './attachment_list';
  11. import Card from '../features/status/components/card';
  12. import { injectIntl, defineMessages, FormattedMessage } from 'react-intl';
  13. import ImmutablePureComponent from 'react-immutable-pure-component';
  14. import { MediaGallery, Video, Audio } from '../features/ui/util/async-components';
  15. import { HotKeys } from 'react-hotkeys';
  16. import classNames from 'classnames';
  17. import Icon from 'mastodon/components/icon';
  18. import { displayMedia } from '../initial_state';
  19. import PictureInPicturePlaceholder from 'mastodon/components/picture_in_picture_placeholder';
  20. // We use the component (and not the container) since we do not want
  21. // to use the progress bar to show download progress
  22. import Bundle from '../features/ui/components/bundle';
  23. export const textForScreenReader = (intl, status, rebloggedByText = false) => {
  24. const displayName = status.getIn(['account', 'display_name']);
  25. const values = [
  26. displayName.length === 0 ? status.getIn(['account', 'acct']).split('@')[0] : displayName,
  27. status.get('spoiler_text') && status.get('hidden') ? status.get('spoiler_text') : status.get('search_index').slice(status.get('spoiler_text').length),
  28. intl.formatDate(status.get('created_at'), { hour: '2-digit', minute: '2-digit', month: 'short', day: 'numeric' }),
  29. status.getIn(['account', 'acct']),
  30. ];
  31. if (rebloggedByText) {
  32. values.push(rebloggedByText);
  33. }
  34. return values.join(', ');
  35. };
  36. export const defaultMediaVisibility = (status) => {
  37. if (!status) {
  38. return undefined;
  39. }
  40. if (status.get('reblog', null) !== null && typeof status.get('reblog') === 'object') {
  41. status = status.get('reblog');
  42. }
  43. return (displayMedia !== 'hide_all' && !status.get('sensitive') || displayMedia === 'show_all');
  44. };
  45. const messages = defineMessages({
  46. public_short: { id: 'privacy.public.short', defaultMessage: 'Public' },
  47. unlisted_short: { id: 'privacy.unlisted.short', defaultMessage: 'Unlisted' },
  48. private_short: { id: 'privacy.private.short', defaultMessage: 'Followers-only' },
  49. direct_short: { id: 'privacy.direct.short', defaultMessage: 'Mentioned people only' },
  50. edited: { id: 'status.edited', defaultMessage: 'Edited {date}' },
  51. });
  52. export default @injectIntl
  53. class Status extends ImmutablePureComponent {
  54. static contextTypes = {
  55. router: PropTypes.object,
  56. };
  57. static propTypes = {
  58. status: ImmutablePropTypes.map,
  59. account: ImmutablePropTypes.map,
  60. onClick: PropTypes.func,
  61. onReply: PropTypes.func,
  62. onFavourite: PropTypes.func,
  63. onReblog: PropTypes.func,
  64. onDelete: PropTypes.func,
  65. onDirect: PropTypes.func,
  66. onMention: PropTypes.func,
  67. onPin: PropTypes.func,
  68. onOpenMedia: PropTypes.func,
  69. onOpenVideo: PropTypes.func,
  70. onBlock: PropTypes.func,
  71. onEmbed: PropTypes.func,
  72. onHeightChange: PropTypes.func,
  73. onToggleHidden: PropTypes.func,
  74. onToggleCollapsed: PropTypes.func,
  75. muted: PropTypes.bool,
  76. hidden: PropTypes.bool,
  77. unread: PropTypes.bool,
  78. onMoveUp: PropTypes.func,
  79. onMoveDown: PropTypes.func,
  80. showThread: PropTypes.bool,
  81. getScrollPosition: PropTypes.func,
  82. updateScrollBottom: PropTypes.func,
  83. cacheMediaWidth: PropTypes.func,
  84. cachedMediaWidth: PropTypes.number,
  85. scrollKey: PropTypes.string,
  86. deployPictureInPicture: PropTypes.func,
  87. pictureInPicture: ImmutablePropTypes.contains({
  88. inUse: PropTypes.bool,
  89. available: PropTypes.bool,
  90. }),
  91. };
  92. // Avoid checking props that are functions (and whose equality will always
  93. // evaluate to false. See react-immutable-pure-component for usage.
  94. updateOnProps = [
  95. 'status',
  96. 'account',
  97. 'muted',
  98. 'hidden',
  99. 'unread',
  100. 'pictureInPicture',
  101. ];
  102. state = {
  103. showMedia: defaultMediaVisibility(this.props.status),
  104. statusId: undefined,
  105. forceFilter: undefined,
  106. };
  107. static getDerivedStateFromProps(nextProps, prevState) {
  108. if (nextProps.status && nextProps.status.get('id') !== prevState.statusId) {
  109. return {
  110. showMedia: defaultMediaVisibility(nextProps.status),
  111. statusId: nextProps.status.get('id'),
  112. };
  113. } else {
  114. return null;
  115. }
  116. }
  117. handleToggleMediaVisibility = () => {
  118. this.setState({ showMedia: !this.state.showMedia });
  119. }
  120. handleClick = e => {
  121. if (e && (e.button !== 0 || e.ctrlKey || e.metaKey)) {
  122. return;
  123. }
  124. if (e) {
  125. e.preventDefault();
  126. }
  127. this.handleHotkeyOpen();
  128. }
  129. handlePrependAccountClick = e => {
  130. this.handleAccountClick(e, false);
  131. }
  132. handleAccountClick = (e, proper = true) => {
  133. if (e && (e.button !== 0 || e.ctrlKey || e.metaKey)) {
  134. return;
  135. }
  136. if (e) {
  137. e.preventDefault();
  138. }
  139. this._openProfile(proper);
  140. }
  141. handleExpandedToggle = () => {
  142. this.props.onToggleHidden(this._properStatus());
  143. }
  144. handleCollapsedToggle = isCollapsed => {
  145. this.props.onToggleCollapsed(this._properStatus(), isCollapsed);
  146. }
  147. renderLoadingMediaGallery () {
  148. return <div className='media-gallery' style={{ height: '110px' }} />;
  149. }
  150. renderLoadingVideoPlayer () {
  151. return <div className='video-player' style={{ height: '110px' }} />;
  152. }
  153. renderLoadingAudioPlayer () {
  154. return <div className='audio-player' style={{ height: '110px' }} />;
  155. }
  156. handleOpenVideo = (options) => {
  157. const status = this._properStatus();
  158. this.props.onOpenVideo(status.get('id'), status.getIn(['media_attachments', 0]), options);
  159. }
  160. handleOpenMedia = (media, index) => {
  161. this.props.onOpenMedia(this._properStatus().get('id'), media, index);
  162. }
  163. handleHotkeyOpenMedia = e => {
  164. const { onOpenMedia, onOpenVideo } = this.props;
  165. const status = this._properStatus();
  166. e.preventDefault();
  167. if (status.get('media_attachments').size > 0) {
  168. if (status.getIn(['media_attachments', 0, 'type']) === 'video') {
  169. onOpenVideo(status.get('id'), status.getIn(['media_attachments', 0]), { startTime: 0 });
  170. } else {
  171. onOpenMedia(status.get('id'), status.get('media_attachments'), 0);
  172. }
  173. }
  174. }
  175. handleDeployPictureInPicture = (type, mediaProps) => {
  176. const { deployPictureInPicture } = this.props;
  177. const status = this._properStatus();
  178. deployPictureInPicture(status, type, mediaProps);
  179. }
  180. handleHotkeyReply = e => {
  181. e.preventDefault();
  182. this.props.onReply(this._properStatus(), this.context.router.history);
  183. }
  184. handleHotkeyFavourite = () => {
  185. this.props.onFavourite(this._properStatus());
  186. }
  187. handleHotkeyBoost = e => {
  188. this.props.onReblog(this._properStatus(), e);
  189. }
  190. handleHotkeyMention = e => {
  191. e.preventDefault();
  192. this.props.onMention(this._properStatus().get('account'), this.context.router.history);
  193. }
  194. handleHotkeyOpen = () => {
  195. if (this.props.onClick) {
  196. this.props.onClick();
  197. return;
  198. }
  199. const { router } = this.context;
  200. const status = this._properStatus();
  201. if (!router) {
  202. return;
  203. }
  204. router.history.push(`/@${status.getIn(['account', 'acct'])}/${status.get('id')}`);
  205. }
  206. handleHotkeyOpenProfile = () => {
  207. this._openProfile();
  208. }
  209. _openProfile = (proper = true) => {
  210. const { router } = this.context;
  211. const status = proper ? this._properStatus() : this.props.status;
  212. if (!router) {
  213. return;
  214. }
  215. router.history.push(`/@${status.getIn(['account', 'acct'])}`);
  216. }
  217. handleHotkeyMoveUp = e => {
  218. this.props.onMoveUp(this.props.status.get('id'), e.target.getAttribute('data-featured'));
  219. }
  220. handleHotkeyMoveDown = e => {
  221. this.props.onMoveDown(this.props.status.get('id'), e.target.getAttribute('data-featured'));
  222. }
  223. handleHotkeyToggleHidden = () => {
  224. this.props.onToggleHidden(this._properStatus());
  225. }
  226. handleHotkeyToggleSensitive = () => {
  227. this.handleToggleMediaVisibility();
  228. }
  229. handleUnfilterClick = e => {
  230. this.setState({ forceFilter: false });
  231. e.preventDefault();
  232. }
  233. handleFilterClick = () => {
  234. this.setState({ forceFilter: true });
  235. }
  236. _properStatus () {
  237. const { status } = this.props;
  238. if (status.get('reblog', null) !== null && typeof status.get('reblog') === 'object') {
  239. return status.get('reblog');
  240. } else {
  241. return status;
  242. }
  243. }
  244. handleRef = c => {
  245. this.node = c;
  246. }
  247. render () {
  248. let media = null;
  249. let statusAvatar, prepend, rebloggedByText;
  250. const { intl, hidden, featured, unread, showThread, scrollKey, pictureInPicture } = this.props;
  251. let { status, account, ...other } = this.props;
  252. if (status === null) {
  253. return null;
  254. }
  255. const handlers = this.props.muted ? {} : {
  256. reply: this.handleHotkeyReply,
  257. favourite: this.handleHotkeyFavourite,
  258. boost: this.handleHotkeyBoost,
  259. mention: this.handleHotkeyMention,
  260. open: this.handleHotkeyOpen,
  261. openProfile: this.handleHotkeyOpenProfile,
  262. moveUp: this.handleHotkeyMoveUp,
  263. moveDown: this.handleHotkeyMoveDown,
  264. toggleHidden: this.handleHotkeyToggleHidden,
  265. toggleSensitive: this.handleHotkeyToggleSensitive,
  266. openMedia: this.handleHotkeyOpenMedia,
  267. };
  268. if (hidden) {
  269. return (
  270. <HotKeys handlers={handlers}>
  271. <div ref={this.handleRef} className={classNames('status__wrapper', { focusable: !this.props.muted })} tabIndex='0'>
  272. <span>{status.getIn(['account', 'display_name']) || status.getIn(['account', 'username'])}</span>
  273. <span>{status.get('content')}</span>
  274. </div>
  275. </HotKeys>
  276. );
  277. }
  278. const matchedFilters = status.get('filtered') || status.getIn(['reblog', 'filtered']);
  279. if (this.state.forceFilter === undefined ? matchedFilters : this.state.forceFilter) {
  280. const minHandlers = this.props.muted ? {} : {
  281. moveUp: this.handleHotkeyMoveUp,
  282. moveDown: this.handleHotkeyMoveDown,
  283. };
  284. return (
  285. <HotKeys handlers={minHandlers}>
  286. <div className='status__wrapper status__wrapper--filtered focusable' tabIndex='0' ref={this.handleRef}>
  287. <FormattedMessage id='status.filtered' defaultMessage='Filtered' />: {matchedFilters.join(', ')}.
  288. {' '}
  289. <button className='status__wrapper--filtered__button' onClick={this.handleUnfilterClick}>
  290. <FormattedMessage id='status.show_filter_reason' defaultMessage='Show anyway' />
  291. </button>
  292. </div>
  293. </HotKeys>
  294. );
  295. }
  296. if (featured) {
  297. prepend = (
  298. <div className='status__prepend'>
  299. <div className='status__prepend-icon-wrapper'><Icon id='thumb-tack' className='status__prepend-icon' fixedWidth /></div>
  300. <FormattedMessage id='status.pinned' defaultMessage='Pinned post' />
  301. </div>
  302. );
  303. } else if (status.get('reblog', null) !== null && typeof status.get('reblog') === 'object') {
  304. const display_name_html = { __html: status.getIn(['account', 'display_name_html']) };
  305. prepend = (
  306. <div className='status__prepend'>
  307. <div className='status__prepend-icon-wrapper'><Icon id='retweet' className='status__prepend-icon' fixedWidth /></div>
  308. <FormattedMessage id='status.reblogged_by' defaultMessage='{name} boosted' values={{ name: <a onClick={this.handlePrependAccountClick} data-id={status.getIn(['account', 'id'])} href={status.getIn(['account', 'url'])} className='status__display-name muted'><bdi><strong dangerouslySetInnerHTML={display_name_html} /></bdi></a> }} />
  309. </div>
  310. );
  311. rebloggedByText = intl.formatMessage({ id: 'status.reblogged_by', defaultMessage: '{name} boosted' }, { name: status.getIn(['account', 'acct']) });
  312. account = status.get('account');
  313. status = status.get('reblog');
  314. }
  315. if (pictureInPicture.get('inUse')) {
  316. media = <PictureInPicturePlaceholder width={this.props.cachedMediaWidth} />;
  317. } else if (status.get('media_attachments').size > 0) {
  318. if (this.props.muted) {
  319. media = (
  320. <AttachmentList
  321. compact
  322. media={status.get('media_attachments')}
  323. />
  324. );
  325. } else if (status.getIn(['media_attachments', 0, 'type']) === 'audio') {
  326. const attachment = status.getIn(['media_attachments', 0]);
  327. media = (
  328. <Bundle fetchComponent={Audio} loading={this.renderLoadingAudioPlayer} >
  329. {Component => (
  330. <Component
  331. src={attachment.get('url')}
  332. alt={attachment.get('description')}
  333. poster={attachment.get('preview_url') || status.getIn(['account', 'avatar_static'])}
  334. backgroundColor={attachment.getIn(['meta', 'colors', 'background'])}
  335. foregroundColor={attachment.getIn(['meta', 'colors', 'foreground'])}
  336. accentColor={attachment.getIn(['meta', 'colors', 'accent'])}
  337. duration={attachment.getIn(['meta', 'original', 'duration'], 0)}
  338. width={this.props.cachedMediaWidth}
  339. height={110}
  340. cacheWidth={this.props.cacheMediaWidth}
  341. deployPictureInPicture={pictureInPicture.get('available') ? this.handleDeployPictureInPicture : undefined}
  342. />
  343. )}
  344. </Bundle>
  345. );
  346. } else if (status.getIn(['media_attachments', 0, 'type']) === 'video') {
  347. const attachment = status.getIn(['media_attachments', 0]);
  348. media = (
  349. <Bundle fetchComponent={Video} loading={this.renderLoadingVideoPlayer} >
  350. {Component => (
  351. <Component
  352. preview={attachment.get('preview_url')}
  353. frameRate={attachment.getIn(['meta', 'original', 'frame_rate'])}
  354. blurhash={attachment.get('blurhash')}
  355. src={attachment.get('url')}
  356. alt={attachment.get('description')}
  357. width={this.props.cachedMediaWidth}
  358. height={110}
  359. inline
  360. sensitive={status.get('sensitive')}
  361. onOpenVideo={this.handleOpenVideo}
  362. cacheWidth={this.props.cacheMediaWidth}
  363. deployPictureInPicture={pictureInPicture.get('available') ? this.handleDeployPictureInPicture : undefined}
  364. visible={this.state.showMedia}
  365. onToggleVisibility={this.handleToggleMediaVisibility}
  366. />
  367. )}
  368. </Bundle>
  369. );
  370. } else {
  371. media = (
  372. <Bundle fetchComponent={MediaGallery} loading={this.renderLoadingMediaGallery}>
  373. {Component => (
  374. <Component
  375. media={status.get('media_attachments')}
  376. sensitive={status.get('sensitive')}
  377. height={110}
  378. onOpenMedia={this.handleOpenMedia}
  379. cacheWidth={this.props.cacheMediaWidth}
  380. defaultWidth={this.props.cachedMediaWidth}
  381. visible={this.state.showMedia}
  382. onToggleVisibility={this.handleToggleMediaVisibility}
  383. />
  384. )}
  385. </Bundle>
  386. );
  387. }
  388. } else if (status.get('spoiler_text').length === 0 && status.get('card')) {
  389. media = (
  390. <Card
  391. onOpenMedia={this.handleOpenMedia}
  392. card={status.get('card')}
  393. compact
  394. cacheWidth={this.props.cacheMediaWidth}
  395. defaultWidth={this.props.cachedMediaWidth}
  396. sensitive={status.get('sensitive')}
  397. />
  398. );
  399. }
  400. if (account === undefined || account === null) {
  401. statusAvatar = <Avatar account={status.get('account')} size={48} />;
  402. } else {
  403. statusAvatar = <AvatarOverlay account={status.get('account')} friend={account} />;
  404. }
  405. const visibilityIconInfo = {
  406. 'public': { icon: 'globe', text: intl.formatMessage(messages.public_short) },
  407. 'unlisted': { icon: 'unlock', text: intl.formatMessage(messages.unlisted_short) },
  408. 'private': { icon: 'lock', text: intl.formatMessage(messages.private_short) },
  409. 'direct': { icon: 'at', text: intl.formatMessage(messages.direct_short) },
  410. };
  411. const visibilityIcon = visibilityIconInfo[status.get('visibility')];
  412. return (
  413. <HotKeys handlers={handlers}>
  414. <div className={classNames('status__wrapper', `status__wrapper-${status.get('visibility')}`, { 'status__wrapper-reply': !!status.get('in_reply_to_id'), unread, focusable: !this.props.muted })} tabIndex={this.props.muted ? null : 0} data-featured={featured ? 'true' : null} aria-label={textForScreenReader(intl, status, rebloggedByText)} ref={this.handleRef}>
  415. {prepend}
  416. <div className={classNames('status', `status-${status.get('visibility')}`, { 'status-reply': !!status.get('in_reply_to_id'), muted: this.props.muted })} data-id={status.get('id')}>
  417. <div className='status__expand' onClick={this.handleClick} role='presentation' />
  418. <div className='status__info'>
  419. <a onClick={this.handleClick} href={status.get('url')} className='status__relative-time' target='_blank' rel='noopener noreferrer'>
  420. <span className='status__visibility-icon'><Icon id={visibilityIcon.icon} title={visibilityIcon.text} /></span>
  421. <RelativeTimestamp timestamp={status.get('created_at')} />{status.get('edited_at') && <abbr title={intl.formatMessage(messages.edited, { date: intl.formatDate(status.get('edited_at'), { hour12: false, year: 'numeric', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' }) })}> *</abbr>}
  422. </a>
  423. <a onClick={this.handleAccountClick} href={status.getIn(['account', 'url'])} title={status.getIn(['account', 'acct'])} className='status__display-name' target='_blank' rel='noopener noreferrer'>
  424. <div className='status__avatar'>
  425. {statusAvatar}
  426. </div>
  427. <DisplayName account={status.get('account')} />
  428. </a>
  429. </div>
  430. <StatusContent status={status} onClick={this.handleClick} expanded={!status.get('hidden')} showThread={showThread} onExpandedToggle={this.handleExpandedToggle} collapsable onCollapsedToggle={this.handleCollapsedToggle} />
  431. {media}
  432. <StatusActionBar scrollKey={scrollKey} status={status} account={account} onFilter={matchedFilters && this.handleFilterClick} {...other} />
  433. </div>
  434. </div>
  435. </HotKeys>
  436. );
  437. }
  438. }