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.

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