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.

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