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.

372 lines
11 KiB

  1. import React from 'react';
  2. import ImmutablePropTypes from 'react-immutable-proptypes';
  3. import PropTypes from 'prop-types';
  4. import { is } from 'immutable';
  5. import IconButton from './icon_button';
  6. import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
  7. import classNames from 'classnames';
  8. import { autoPlayGif, cropImages, displayMedia, useBlurhash } from '../initial_state';
  9. import { debounce } from 'lodash';
  10. import Blurhash from 'mastodon/components/blurhash';
  11. const messages = defineMessages({
  12. toggle_visible: { id: 'media_gallery.toggle_visible', defaultMessage: '{number, plural, one {Hide image} other {Hide images}}' },
  13. });
  14. class Item extends React.PureComponent {
  15. static propTypes = {
  16. attachment: ImmutablePropTypes.map.isRequired,
  17. lang: PropTypes.string,
  18. standalone: PropTypes.bool,
  19. index: PropTypes.number.isRequired,
  20. size: PropTypes.number.isRequired,
  21. onClick: PropTypes.func.isRequired,
  22. displayWidth: PropTypes.number,
  23. visible: PropTypes.bool.isRequired,
  24. autoplay: PropTypes.bool,
  25. };
  26. static defaultProps = {
  27. standalone: false,
  28. index: 0,
  29. size: 1,
  30. };
  31. state = {
  32. loaded: false,
  33. };
  34. handleMouseEnter = (e) => {
  35. if (this.hoverToPlay()) {
  36. e.target.play();
  37. }
  38. };
  39. handleMouseLeave = (e) => {
  40. if (this.hoverToPlay()) {
  41. e.target.pause();
  42. e.target.currentTime = 0;
  43. }
  44. };
  45. getAutoPlay() {
  46. return this.props.autoplay || autoPlayGif;
  47. }
  48. hoverToPlay () {
  49. const { attachment } = this.props;
  50. return !this.getAutoPlay() && attachment.get('type') === 'gifv';
  51. }
  52. handleClick = (e) => {
  53. const { index, onClick } = this.props;
  54. if (e.button === 0 && !(e.ctrlKey || e.metaKey)) {
  55. if (this.hoverToPlay()) {
  56. e.target.pause();
  57. e.target.currentTime = 0;
  58. }
  59. e.preventDefault();
  60. onClick(index);
  61. }
  62. e.stopPropagation();
  63. };
  64. handleImageLoad = () => {
  65. this.setState({ loaded: true });
  66. };
  67. render () {
  68. const { attachment, lang, index, size, standalone, displayWidth, visible } = this.props;
  69. let width = 50;
  70. let height = 100;
  71. let top = 'auto';
  72. let left = 'auto';
  73. let bottom = 'auto';
  74. let right = 'auto';
  75. if (size === 1) {
  76. width = 100;
  77. }
  78. if (size === 4 || (size === 3 && index > 0)) {
  79. height = 50;
  80. }
  81. if (size === 2) {
  82. if (index === 0) {
  83. right = '2px';
  84. } else {
  85. left = '2px';
  86. }
  87. } else if (size === 3) {
  88. if (index === 0) {
  89. right = '2px';
  90. } else if (index > 0) {
  91. left = '2px';
  92. }
  93. if (index === 1) {
  94. bottom = '2px';
  95. } else if (index > 1) {
  96. top = '2px';
  97. }
  98. } else if (size === 4) {
  99. if (index === 0 || index === 2) {
  100. right = '2px';
  101. }
  102. if (index === 1 || index === 3) {
  103. left = '2px';
  104. }
  105. if (index < 2) {
  106. bottom = '2px';
  107. } else {
  108. top = '2px';
  109. }
  110. }
  111. let thumbnail = '';
  112. if (attachment.get('type') === 'unknown') {
  113. return (
  114. <div className={classNames('media-gallery__item', { standalone })} key={attachment.get('id')} style={{ left: left, top: top, right: right, bottom: bottom, width: `${width}%`, height: `${height}%` }}>
  115. <a className='media-gallery__item-thumbnail' href={attachment.get('remote_url') || attachment.get('url')} style={{ cursor: 'pointer' }} title={attachment.get('description')} lang={lang} target='_blank' rel='noopener noreferrer'>
  116. <Blurhash
  117. hash={attachment.get('blurhash')}
  118. className='media-gallery__preview'
  119. dummy={!useBlurhash}
  120. />
  121. </a>
  122. </div>
  123. );
  124. } else if (attachment.get('type') === 'image') {
  125. const previewUrl = attachment.get('preview_url');
  126. const previewWidth = attachment.getIn(['meta', 'small', 'width']);
  127. const originalUrl = attachment.get('url');
  128. const originalWidth = attachment.getIn(['meta', 'original', 'width']);
  129. const hasSize = typeof originalWidth === 'number' && typeof previewWidth === 'number';
  130. const srcSet = hasSize ? `${originalUrl} ${originalWidth}w, ${previewUrl} ${previewWidth}w` : null;
  131. const sizes = hasSize && (displayWidth > 0) ? `${displayWidth * (width / 100)}px` : null;
  132. const focusX = attachment.getIn(['meta', 'focus', 'x']) || 0;
  133. const focusY = attachment.getIn(['meta', 'focus', 'y']) || 0;
  134. const x = ((focusX / 2) + .5) * 100;
  135. const y = ((focusY / -2) + .5) * 100;
  136. thumbnail = (
  137. <a
  138. className='media-gallery__item-thumbnail'
  139. href={attachment.get('remote_url') || originalUrl}
  140. onClick={this.handleClick}
  141. target='_blank'
  142. rel='noopener noreferrer'
  143. >
  144. <img
  145. src={previewUrl}
  146. srcSet={srcSet}
  147. sizes={sizes}
  148. alt={attachment.get('description')}
  149. title={attachment.get('description')}
  150. lang={lang}
  151. style={{ objectPosition: `${x}% ${y}%` }}
  152. onLoad={this.handleImageLoad}
  153. />
  154. </a>
  155. );
  156. } else if (attachment.get('type') === 'gifv') {
  157. const autoPlay = this.getAutoPlay();
  158. thumbnail = (
  159. <div className={classNames('media-gallery__gifv', { autoplay: autoPlay })}>
  160. <video
  161. className='media-gallery__item-gifv-thumbnail'
  162. aria-label={attachment.get('description')}
  163. title={attachment.get('description')}
  164. lang={lang}
  165. role='application'
  166. src={attachment.get('url')}
  167. onClick={this.handleClick}
  168. onMouseEnter={this.handleMouseEnter}
  169. onMouseLeave={this.handleMouseLeave}
  170. autoPlay={autoPlay}
  171. playsInline
  172. loop
  173. muted
  174. />
  175. <span className='media-gallery__gifv__label'>GIF</span>
  176. </div>
  177. );
  178. }
  179. return (
  180. <div className={classNames('media-gallery__item', { standalone })} key={attachment.get('id')} style={{ left: left, top: top, right: right, bottom: bottom, width: `${width}%`, height: `${height}%` }}>
  181. <Blurhash
  182. hash={attachment.get('blurhash')}
  183. dummy={!useBlurhash}
  184. className={classNames('media-gallery__preview', {
  185. 'media-gallery__preview--hidden': visible && this.state.loaded,
  186. })}
  187. />
  188. {visible && thumbnail}
  189. </div>
  190. );
  191. }
  192. }
  193. class MediaGallery extends React.PureComponent {
  194. static propTypes = {
  195. sensitive: PropTypes.bool,
  196. standalone: PropTypes.bool,
  197. media: ImmutablePropTypes.list.isRequired,
  198. lang: PropTypes.string,
  199. size: PropTypes.object,
  200. height: PropTypes.number.isRequired,
  201. onOpenMedia: PropTypes.func.isRequired,
  202. intl: PropTypes.object.isRequired,
  203. defaultWidth: PropTypes.number,
  204. cacheWidth: PropTypes.func,
  205. visible: PropTypes.bool,
  206. autoplay: PropTypes.bool,
  207. onToggleVisibility: PropTypes.func,
  208. };
  209. static defaultProps = {
  210. standalone: false,
  211. };
  212. state = {
  213. visible: this.props.visible !== undefined ? this.props.visible : (displayMedia !== 'hide_all' && !this.props.sensitive || displayMedia === 'show_all'),
  214. width: this.props.defaultWidth,
  215. };
  216. componentDidMount () {
  217. window.addEventListener('resize', this.handleResize, { passive: true });
  218. }
  219. componentWillUnmount () {
  220. window.removeEventListener('resize', this.handleResize);
  221. }
  222. componentWillReceiveProps (nextProps) {
  223. if (!is(nextProps.media, this.props.media) && nextProps.visible === undefined) {
  224. this.setState({ visible: displayMedia !== 'hide_all' && !nextProps.sensitive || displayMedia === 'show_all' });
  225. } else if (!is(nextProps.visible, this.props.visible) && nextProps.visible !== undefined) {
  226. this.setState({ visible: nextProps.visible });
  227. }
  228. }
  229. handleResize = debounce(() => {
  230. if (this.node) {
  231. this._setDimensions();
  232. }
  233. }, 250, {
  234. trailing: true,
  235. });
  236. handleOpen = () => {
  237. if (this.props.onToggleVisibility) {
  238. this.props.onToggleVisibility();
  239. } else {
  240. this.setState({ visible: !this.state.visible });
  241. }
  242. };
  243. handleClick = (index) => {
  244. this.props.onOpenMedia(this.props.media, index);
  245. };
  246. handleRef = c => {
  247. this.node = c;
  248. if (this.node) {
  249. this._setDimensions();
  250. }
  251. };
  252. _setDimensions () {
  253. const width = this.node.offsetWidth;
  254. // offsetWidth triggers a layout, so only calculate when we need to
  255. if (this.props.cacheWidth) {
  256. this.props.cacheWidth(width);
  257. }
  258. this.setState({
  259. width: width,
  260. });
  261. }
  262. isFullSizeEligible() {
  263. const { media } = this.props;
  264. return media.size === 1 && media.getIn([0, 'meta', 'small', 'aspect']);
  265. }
  266. render () {
  267. const { media, lang, intl, sensitive, height, defaultWidth, standalone, autoplay } = this.props;
  268. const { visible } = this.state;
  269. const width = this.state.width || defaultWidth;
  270. let children, spoilerButton;
  271. const style = {};
  272. if (this.isFullSizeEligible() && (standalone || !cropImages)) {
  273. if (width) {
  274. style.height = width / this.props.media.getIn([0, 'meta', 'small', 'aspect']);
  275. }
  276. } else if (width) {
  277. style.height = width / (16/9);
  278. } else {
  279. style.height = height;
  280. }
  281. const size = media.take(4).size;
  282. const uncached = media.every(attachment => attachment.get('type') === 'unknown');
  283. if (standalone && this.isFullSizeEligible()) {
  284. children = <Item standalone autoplay={autoplay} onClick={this.handleClick} attachment={media.get(0)} lang={lang} displayWidth={width} visible={visible} />;
  285. } else {
  286. children = media.take(4).map((attachment, i) => <Item key={attachment.get('id')} autoplay={autoplay} onClick={this.handleClick} attachment={attachment} index={i} lang={lang} size={size} displayWidth={width} visible={visible || uncached} />);
  287. }
  288. if (uncached) {
  289. spoilerButton = (
  290. <button type='button' disabled className='spoiler-button__overlay'>
  291. <span className='spoiler-button__overlay__label'><FormattedMessage id='status.uncached_media_warning' defaultMessage='Not available' /></span>
  292. </button>
  293. );
  294. } else if (visible) {
  295. spoilerButton = <IconButton title={intl.formatMessage(messages.toggle_visible, { number: size })} icon='eye-slash' overlay onClick={this.handleOpen} ariaHidden />;
  296. } else {
  297. spoilerButton = (
  298. <button type='button' onClick={this.handleOpen} className='spoiler-button__overlay'>
  299. <span className='spoiler-button__overlay__label'>{sensitive ? <FormattedMessage id='status.sensitive_warning' defaultMessage='Sensitive content' /> : <FormattedMessage id='status.media_hidden' defaultMessage='Media hidden' />}</span>
  300. </button>
  301. );
  302. }
  303. return (
  304. <div className='media-gallery' style={style} ref={this.handleRef}>
  305. <div className={classNames('spoiler-button', { 'spoiler-button--minified': visible && !uncached, 'spoiler-button--click-thru': uncached })}>
  306. {spoilerButton}
  307. </div>
  308. {children}
  309. </div>
  310. );
  311. }
  312. }
  313. export default injectIntl(MediaGallery);