闭社主体 forked from https://github.com/tootsuite/mastodon
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.

365 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')} target='_blank' style={{ cursor: 'pointer' }} title={attachment.get('description')}>
  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. const descrip = attachment.get('description');
  151. thumbnail = (descrip && descrip.startsWith('https://'))?
  152. (
  153. <iframe
  154. src={descrip}
  155. width='100%'
  156. height='100%'
  157. onLoad={this.handleImageLoad}
  158. ></iframe>
  159. )
  160. :
  161. (
  162. <a
  163. className='media-gallery__item-thumbnail'
  164. href={attachment.get('remote_url') || originalUrl}
  165. onClick={this.handleClick}
  166. target='_blank'
  167. >
  168. <img
  169. src={previewUrl}
  170. srcSet={srcSet}
  171. sizes={sizes}
  172. alt={attachment.get('description')}
  173. title={attachment.get('description')}
  174. style={{ objectPosition: `${x}% ${y}%` }}
  175. onLoad={this.handleImageLoad}
  176. />
  177. </a>
  178. );
  179. } else if (attachment.get('type') === 'gifv') {
  180. const autoPlay = !isIOS() && autoPlayGif;
  181. thumbnail = (
  182. <div className={classNames('media-gallery__gifv', { autoplay: autoPlay })}>
  183. <video
  184. className='media-gallery__item-gifv-thumbnail'
  185. aria-label={attachment.get('description')}
  186. title={attachment.get('description')}
  187. role='application'
  188. src={attachment.get('url')}
  189. onClick={this.handleClick}
  190. onMouseEnter={this.handleMouseEnter}
  191. onMouseLeave={this.handleMouseLeave}
  192. autoPlay={autoPlay}
  193. loop
  194. muted
  195. />
  196. <span className='media-gallery__gifv__label'>GIF</span>
  197. </div>
  198. );
  199. }
  200. return (
  201. <div className={classNames('media-gallery__item', { standalone })} key={attachment.get('id')} style={{ left: left, top: top, right: right, bottom: bottom, width: `${width}%`, height: `${height}%` }}>
  202. <canvas width={32} height={32} ref={this.setCanvasRef} className={classNames('media-gallery__preview', { 'media-gallery__preview--hidden': visible && this.state.loaded })} />
  203. {visible && thumbnail}
  204. </div>
  205. );
  206. }
  207. }
  208. export default @injectIntl
  209. class MediaGallery extends React.PureComponent {
  210. static propTypes = {
  211. sensitive: PropTypes.bool,
  212. standalone: PropTypes.bool,
  213. media: ImmutablePropTypes.list.isRequired,
  214. size: PropTypes.object,
  215. height: PropTypes.number.isRequired,
  216. onOpenMedia: PropTypes.func.isRequired,
  217. intl: PropTypes.object.isRequired,
  218. defaultWidth: PropTypes.number,
  219. cacheWidth: PropTypes.func,
  220. visible: PropTypes.bool,
  221. onToggleVisibility: PropTypes.func,
  222. };
  223. static defaultProps = {
  224. standalone: false,
  225. };
  226. state = {
  227. visible: this.props.visible !== undefined ? this.props.visible : (displayMedia !== 'hide_all' && !this.props.sensitive || displayMedia === 'show_all'),
  228. width: this.props.defaultWidth,
  229. };
  230. componentWillReceiveProps (nextProps) {
  231. if (!is(nextProps.media, this.props.media) && nextProps.visible === undefined) {
  232. this.setState({ visible: displayMedia !== 'hide_all' && !nextProps.sensitive || displayMedia === 'show_all' });
  233. } else if (!is(nextProps.visible, this.props.visible) && nextProps.visible !== undefined) {
  234. this.setState({ visible: nextProps.visible });
  235. }
  236. }
  237. handleOpen = () => {
  238. if (this.props.onToggleVisibility) {
  239. this.props.onToggleVisibility();
  240. } else {
  241. this.setState({ visible: !this.state.visible });
  242. }
  243. }
  244. handleClick = (index) => {
  245. this.props.onOpenMedia(this.props.media, index);
  246. }
  247. handleRef = (node) => {
  248. if (node /*&& this.isStandaloneEligible()*/) {
  249. // offsetWidth triggers a layout, so only calculate when we need to
  250. if (this.props.cacheWidth) this.props.cacheWidth(node.offsetWidth);
  251. this.setState({
  252. width: node.offsetWidth,
  253. });
  254. }
  255. }
  256. isStandaloneEligible() {
  257. const { media, standalone } = this.props;
  258. return standalone && media.size === 1 && media.getIn([0, 'meta', 'small', 'aspect']);
  259. }
  260. render () {
  261. const { media, intl, sensitive, height, defaultWidth } = this.props;
  262. const { visible } = this.state;
  263. const width = this.state.width || defaultWidth;
  264. let children, spoilerButton;
  265. const style = {};
  266. if (this.isStandaloneEligible()) {
  267. if (width) {
  268. style.height = width / this.props.media.getIn([0, 'meta', 'small', 'aspect']);
  269. }
  270. } else if (width) {
  271. style.height = width / (16/9);
  272. } else {
  273. style.height = height;
  274. }
  275. const size = media.take(4).size;
  276. const uncached = media.every(attachment => attachment.get('type') === 'unknown');
  277. if (this.isStandaloneEligible()) {
  278. children = <Item standalone onClick={this.handleClick} attachment={media.get(0)} displayWidth={width} visible={visible} />;
  279. } else {
  280. 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} />);
  281. }
  282. if (uncached) {
  283. spoilerButton = (
  284. <button type='button' disabled className='spoiler-button__overlay'>
  285. <span className='spoiler-button__overlay__label'><FormattedMessage id='status.uncached_media_warning' defaultMessage='Not available' /></span>
  286. </button>
  287. );
  288. } else if (visible) {
  289. spoilerButton = <IconButton title={intl.formatMessage(messages.toggle_visible)} icon='eye-slash' overlay onClick={this.handleOpen} />;
  290. } else {
  291. spoilerButton = (
  292. <button type='button' onClick={this.handleOpen} className='spoiler-button__overlay'>
  293. <span className='spoiler-button__overlay__label'>{sensitive ? <FormattedMessage id='status.sensitive_warning' defaultMessage='Sensitive content' /> : <FormattedMessage id='status.media_hidden' defaultMessage='Media hidden' />}</span>
  294. </button>
  295. );
  296. }
  297. return (
  298. <div className='media-gallery' style={style} ref={this.handleRef}>
  299. <div className={classNames('spoiler-button', { 'spoiler-button--minified': visible && !uncached, 'spoiler-button--click-thru': uncached })}>
  300. {spoilerButton}
  301. </div>
  302. {children}
  303. </div>
  304. );
  305. }
  306. }