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.

512 lines
16 KiB

  1. import React from 'react';
  2. import PropTypes from 'prop-types';
  3. import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
  4. import { fromJS, is } from 'immutable';
  5. import { throttle } from 'lodash';
  6. import classNames from 'classnames';
  7. import { isFullscreen, requestFullscreen, exitFullscreen } from '../ui/util/fullscreen';
  8. import { displayMedia, useBlurhash } from '../../initial_state';
  9. import Icon from 'mastodon/components/icon';
  10. import { decode } from 'blurhash';
  11. const messages = defineMessages({
  12. play: { id: 'video.play', defaultMessage: 'Play' },
  13. pause: { id: 'video.pause', defaultMessage: 'Pause' },
  14. mute: { id: 'video.mute', defaultMessage: 'Mute sound' },
  15. unmute: { id: 'video.unmute', defaultMessage: 'Unmute sound' },
  16. hide: { id: 'video.hide', defaultMessage: 'Hide video' },
  17. expand: { id: 'video.expand', defaultMessage: 'Expand video' },
  18. close: { id: 'video.close', defaultMessage: 'Close video' },
  19. fullscreen: { id: 'video.fullscreen', defaultMessage: 'Full screen' },
  20. exit_fullscreen: { id: 'video.exit_fullscreen', defaultMessage: 'Exit full screen' },
  21. download: { id: 'video.download', defaultMessage: 'Download file' },
  22. });
  23. export const formatTime = secondsNum => {
  24. let hours = Math.floor(secondsNum / 3600);
  25. let minutes = Math.floor((secondsNum - (hours * 3600)) / 60);
  26. let seconds = secondsNum - (hours * 3600) - (minutes * 60);
  27. if (hours < 10) hours = '0' + hours;
  28. if (minutes < 10) minutes = '0' + minutes;
  29. if (seconds < 10) seconds = '0' + seconds;
  30. return (hours === '00' ? '' : `${hours}:`) + `${minutes}:${seconds}`;
  31. };
  32. export const findElementPosition = el => {
  33. let box;
  34. if (el.getBoundingClientRect && el.parentNode) {
  35. box = el.getBoundingClientRect();
  36. }
  37. if (!box) {
  38. return {
  39. left: 0,
  40. top: 0,
  41. };
  42. }
  43. const docEl = document.documentElement;
  44. const body = document.body;
  45. const clientLeft = docEl.clientLeft || body.clientLeft || 0;
  46. const scrollLeft = window.pageXOffset || body.scrollLeft;
  47. const left = (box.left + scrollLeft) - clientLeft;
  48. const clientTop = docEl.clientTop || body.clientTop || 0;
  49. const scrollTop = window.pageYOffset || body.scrollTop;
  50. const top = (box.top + scrollTop) - clientTop;
  51. return {
  52. left: Math.round(left),
  53. top: Math.round(top),
  54. };
  55. };
  56. export const getPointerPosition = (el, event) => {
  57. const position = {};
  58. const box = findElementPosition(el);
  59. const boxW = el.offsetWidth;
  60. const boxH = el.offsetHeight;
  61. const boxY = box.top;
  62. const boxX = box.left;
  63. let pageY = event.pageY;
  64. let pageX = event.pageX;
  65. if (event.changedTouches) {
  66. pageX = event.changedTouches[0].pageX;
  67. pageY = event.changedTouches[0].pageY;
  68. }
  69. position.y = Math.max(0, Math.min(1, (pageY - boxY) / boxH));
  70. position.x = Math.max(0, Math.min(1, (pageX - boxX) / boxW));
  71. return position;
  72. };
  73. export default @injectIntl
  74. class Video extends React.PureComponent {
  75. static propTypes = {
  76. preview: PropTypes.string,
  77. src: PropTypes.string.isRequired,
  78. alt: PropTypes.string,
  79. width: PropTypes.number,
  80. height: PropTypes.number,
  81. sensitive: PropTypes.bool,
  82. startTime: PropTypes.number,
  83. onOpenVideo: PropTypes.func,
  84. onCloseVideo: PropTypes.func,
  85. detailed: PropTypes.bool,
  86. inline: PropTypes.bool,
  87. editable: PropTypes.bool,
  88. cacheWidth: PropTypes.func,
  89. visible: PropTypes.bool,
  90. onToggleVisibility: PropTypes.func,
  91. intl: PropTypes.object.isRequired,
  92. blurhash: PropTypes.string,
  93. link: PropTypes.node,
  94. };
  95. state = {
  96. currentTime: 0,
  97. duration: 0,
  98. volume: 0.5,
  99. paused: true,
  100. dragging: false,
  101. containerWidth: this.props.width,
  102. fullscreen: false,
  103. hovered: false,
  104. muted: false,
  105. revealed: this.props.visible !== undefined ? this.props.visible : (displayMedia !== 'hide_all' && !this.props.sensitive || displayMedia === 'show_all'),
  106. };
  107. // hard coded in components.scss
  108. // any way to get ::before values programatically?
  109. volWidth = 50;
  110. volOffset = 70;
  111. volHandleOffset = v => {
  112. const offset = v * this.volWidth + this.volOffset;
  113. return (offset > 110) ? 110 : offset;
  114. }
  115. setPlayerRef = c => {
  116. this.player = c;
  117. if (c) {
  118. if (this.props.cacheWidth) this.props.cacheWidth(this.player.offsetWidth);
  119. this.setState({
  120. containerWidth: c.offsetWidth,
  121. });
  122. }
  123. }
  124. setVideoRef = c => {
  125. this.video = c;
  126. if (this.video) {
  127. this.setState({ volume: this.video.volume, muted: this.video.muted });
  128. }
  129. }
  130. setSeekRef = c => {
  131. this.seek = c;
  132. }
  133. setVolumeRef = c => {
  134. this.volume = c;
  135. }
  136. setCanvasRef = c => {
  137. this.canvas = c;
  138. }
  139. handleClickRoot = e => e.stopPropagation();
  140. handlePlay = () => {
  141. this.setState({ paused: false });
  142. }
  143. handlePause = () => {
  144. this.setState({ paused: true });
  145. }
  146. handleTimeUpdate = () => {
  147. this.setState({
  148. currentTime: Math.floor(this.video.currentTime),
  149. duration: Math.floor(this.video.duration),
  150. });
  151. }
  152. handleVolumeMouseDown = e => {
  153. document.addEventListener('mousemove', this.handleMouseVolSlide, true);
  154. document.addEventListener('mouseup', this.handleVolumeMouseUp, true);
  155. document.addEventListener('touchmove', this.handleMouseVolSlide, true);
  156. document.addEventListener('touchend', this.handleVolumeMouseUp, true);
  157. this.handleMouseVolSlide(e);
  158. e.preventDefault();
  159. e.stopPropagation();
  160. }
  161. handleVolumeMouseUp = () => {
  162. document.removeEventListener('mousemove', this.handleMouseVolSlide, true);
  163. document.removeEventListener('mouseup', this.handleVolumeMouseUp, true);
  164. document.removeEventListener('touchmove', this.handleMouseVolSlide, true);
  165. document.removeEventListener('touchend', this.handleVolumeMouseUp, true);
  166. }
  167. handleMouseVolSlide = throttle(e => {
  168. const rect = this.volume.getBoundingClientRect();
  169. const x = (e.clientX - rect.left) / this.volWidth; //x position within the element.
  170. if(!isNaN(x)) {
  171. var slideamt = x;
  172. if(x > 1) {
  173. slideamt = 1;
  174. } else if(x < 0) {
  175. slideamt = 0;
  176. }
  177. this.video.volume = slideamt;
  178. this.setState({ volume: slideamt });
  179. }
  180. }, 60);
  181. handleMouseDown = e => {
  182. document.addEventListener('mousemove', this.handleMouseMove, true);
  183. document.addEventListener('mouseup', this.handleMouseUp, true);
  184. document.addEventListener('touchmove', this.handleMouseMove, true);
  185. document.addEventListener('touchend', this.handleMouseUp, true);
  186. this.setState({ dragging: true });
  187. this.video.pause();
  188. this.handleMouseMove(e);
  189. e.preventDefault();
  190. e.stopPropagation();
  191. }
  192. handleMouseUp = () => {
  193. document.removeEventListener('mousemove', this.handleMouseMove, true);
  194. document.removeEventListener('mouseup', this.handleMouseUp, true);
  195. document.removeEventListener('touchmove', this.handleMouseMove, true);
  196. document.removeEventListener('touchend', this.handleMouseUp, true);
  197. this.setState({ dragging: false });
  198. this.video.play();
  199. }
  200. handleMouseMove = throttle(e => {
  201. const { x } = getPointerPosition(this.seek, e);
  202. const currentTime = Math.floor(this.video.duration * x);
  203. if (!isNaN(currentTime)) {
  204. this.video.currentTime = currentTime;
  205. this.setState({ currentTime });
  206. }
  207. }, 60);
  208. togglePlay = () => {
  209. if (this.state.paused) {
  210. this.video.play();
  211. } else {
  212. this.video.pause();
  213. }
  214. }
  215. toggleFullscreen = () => {
  216. if (isFullscreen()) {
  217. exitFullscreen();
  218. } else {
  219. requestFullscreen(this.player);
  220. }
  221. }
  222. componentDidMount () {
  223. document.addEventListener('fullscreenchange', this.handleFullscreenChange, true);
  224. document.addEventListener('webkitfullscreenchange', this.handleFullscreenChange, true);
  225. document.addEventListener('mozfullscreenchange', this.handleFullscreenChange, true);
  226. document.addEventListener('MSFullscreenChange', this.handleFullscreenChange, true);
  227. if (this.props.blurhash) {
  228. this._decode();
  229. }
  230. }
  231. componentWillUnmount () {
  232. document.removeEventListener('fullscreenchange', this.handleFullscreenChange, true);
  233. document.removeEventListener('webkitfullscreenchange', this.handleFullscreenChange, true);
  234. document.removeEventListener('mozfullscreenchange', this.handleFullscreenChange, true);
  235. document.removeEventListener('MSFullscreenChange', this.handleFullscreenChange, true);
  236. }
  237. componentWillReceiveProps (nextProps) {
  238. if (!is(nextProps.visible, this.props.visible) && nextProps.visible !== undefined) {
  239. this.setState({ revealed: nextProps.visible });
  240. }
  241. }
  242. componentDidUpdate (prevProps, prevState) {
  243. if (prevState.revealed && !this.state.revealed && this.video) {
  244. this.video.pause();
  245. }
  246. if (prevProps.blurhash !== this.props.blurhash && this.props.blurhash) {
  247. this._decode();
  248. }
  249. }
  250. _decode () {
  251. if (!useBlurhash) return;
  252. const hash = this.props.blurhash;
  253. const pixels = decode(hash, 32, 32);
  254. if (pixels) {
  255. const ctx = this.canvas.getContext('2d');
  256. const imageData = new ImageData(pixels, 32, 32);
  257. ctx.putImageData(imageData, 0, 0);
  258. }
  259. }
  260. handleFullscreenChange = () => {
  261. this.setState({ fullscreen: isFullscreen() });
  262. }
  263. handleMouseEnter = () => {
  264. this.setState({ hovered: true });
  265. }
  266. handleMouseLeave = () => {
  267. this.setState({ hovered: false });
  268. }
  269. toggleMute = () => {
  270. this.video.muted = !this.video.muted;
  271. this.setState({ muted: this.video.muted });
  272. }
  273. toggleReveal = () => {
  274. if (this.props.onToggleVisibility) {
  275. this.props.onToggleVisibility();
  276. } else {
  277. this.setState({ revealed: !this.state.revealed });
  278. }
  279. }
  280. handleLoadedData = () => {
  281. if (this.props.startTime) {
  282. this.video.currentTime = this.props.startTime;
  283. this.video.play();
  284. }
  285. }
  286. handleProgress = () => {
  287. if (this.video.buffered.length > 0) {
  288. this.setState({ buffer: this.video.buffered.end(0) / this.video.duration * 100 });
  289. }
  290. }
  291. handleVolumeChange = () => {
  292. this.setState({ volume: this.video.volume, muted: this.video.muted });
  293. }
  294. handleOpenVideo = () => {
  295. const { src, preview, width, height, alt } = this.props;
  296. const media = fromJS({
  297. type: 'video',
  298. url: src,
  299. preview_url: preview,
  300. description: alt,
  301. width,
  302. height,
  303. });
  304. this.video.pause();
  305. this.props.onOpenVideo(media, this.video.currentTime);
  306. }
  307. handleCloseVideo = () => {
  308. this.video.pause();
  309. this.props.onCloseVideo();
  310. }
  311. render () {
  312. const { preview, src, inline, startTime, onOpenVideo, onCloseVideo, intl, alt, detailed, sensitive, link, editable } = this.props;
  313. const { containerWidth, currentTime, duration, volume, buffer, dragging, paused, fullscreen, hovered, muted, revealed } = this.state;
  314. const progress = (currentTime / duration) * 100;
  315. const volumeWidth = (muted) ? 0 : volume * this.volWidth;
  316. const volumeHandleLoc = (muted) ? this.volHandleOffset(0) : this.volHandleOffset(volume);
  317. const playerStyle = {};
  318. let { width, height } = this.props;
  319. if (inline && containerWidth) {
  320. width = containerWidth;
  321. height = containerWidth / (16/9);
  322. playerStyle.height = height;
  323. }
  324. let preload;
  325. if (startTime || fullscreen || dragging) {
  326. preload = 'auto';
  327. } else if (detailed) {
  328. preload = 'metadata';
  329. } else {
  330. preload = 'none';
  331. }
  332. let warning;
  333. if (sensitive) {
  334. warning = <FormattedMessage id='status.sensitive_warning' defaultMessage='Sensitive content' />;
  335. } else {
  336. warning = <FormattedMessage id='status.media_hidden' defaultMessage='Media hidden' />;
  337. }
  338. return (
  339. <div
  340. role='menuitem'
  341. className={classNames('video-player', { inactive: !revealed, detailed, inline: inline && !fullscreen, fullscreen, editable })}
  342. style={playerStyle}
  343. ref={this.setPlayerRef}
  344. onMouseEnter={this.handleMouseEnter}
  345. onMouseLeave={this.handleMouseLeave}
  346. onClick={this.handleClickRoot}
  347. tabIndex={0}
  348. >
  349. <canvas width={32} height={32} ref={this.setCanvasRef} className={classNames('media-gallery__preview', { 'media-gallery__preview--hidden': revealed })} />
  350. {(revealed || editable) && <video
  351. ref={this.setVideoRef}
  352. src={src}
  353. poster={preview}
  354. preload={preload}
  355. loop
  356. role='button'
  357. tabIndex='0'
  358. aria-label={alt}
  359. title={alt}
  360. width={width}
  361. height={height}
  362. volume={volume}
  363. onClick={this.togglePlay}
  364. onPlay={this.handlePlay}
  365. onPause={this.handlePause}
  366. onTimeUpdate={this.handleTimeUpdate}
  367. onLoadedData={this.handleLoadedData}
  368. onProgress={this.handleProgress}
  369. onVolumeChange={this.handleVolumeChange}
  370. />}
  371. <div className={classNames('spoiler-button', { 'spoiler-button--hidden': revealed || editable })}>
  372. <button type='button' className='spoiler-button__overlay' onClick={this.toggleReveal}>
  373. <span className='spoiler-button__overlay__label'>{warning}</span>
  374. </button>
  375. </div>
  376. <div className={classNames('video-player__controls', { active: paused || hovered })}>
  377. <div className='video-player__seek' onMouseDown={this.handleMouseDown} ref={this.setSeekRef}>
  378. <div className='video-player__seek__buffer' style={{ width: `${buffer}%` }} />
  379. <div className='video-player__seek__progress' style={{ width: `${progress}%` }} />
  380. <span
  381. className={classNames('video-player__seek__handle', { active: dragging })}
  382. tabIndex='0'
  383. style={{ left: `${progress}%` }}
  384. />
  385. </div>
  386. <div className='video-player__buttons-bar'>
  387. <div className='video-player__buttons left'>
  388. <button type='button' aria-label={intl.formatMessage(paused ? messages.play : messages.pause)} onClick={this.togglePlay}><Icon id={paused ? 'play' : 'pause'} fixedWidth /></button>
  389. <button type='button' aria-label={intl.formatMessage(muted ? messages.unmute : messages.mute)} onClick={this.toggleMute}><Icon id={muted ? 'volume-off' : 'volume-up'} fixedWidth /></button>
  390. <div className='video-player__volume' onMouseDown={this.handleVolumeMouseDown} ref={this.setVolumeRef}>
  391. &nbsp;
  392. <div className='video-player__volume__current' style={{ width: `${volumeWidth}px` }} />
  393. <span
  394. className={classNames('video-player__volume__handle')}
  395. tabIndex='0'
  396. style={{ left: `${volumeHandleLoc}px` }}
  397. />
  398. </div>
  399. {(detailed || fullscreen) && (
  400. <span>
  401. <span className='video-player__time-current'>{formatTime(currentTime)}</span>
  402. <span className='video-player__time-sep'>/</span>
  403. <span className='video-player__time-total'>{formatTime(duration)}</span>
  404. </span>
  405. )}
  406. {link && <span className='video-player__link'>{link}</span>}
  407. </div>
  408. <div className='video-player__buttons right'>
  409. {(!onCloseVideo && !editable) && <button type='button' aria-label={intl.formatMessage(messages.hide)} onClick={this.toggleReveal}><Icon id='eye-slash' fixedWidth /></button>}
  410. {(!fullscreen && onOpenVideo) && <button type='button' aria-label={intl.formatMessage(messages.expand)} onClick={this.handleOpenVideo}><Icon id='expand' fixedWidth /></button>}
  411. {onCloseVideo && <button type='button' aria-label={intl.formatMessage(messages.close)} onClick={this.handleCloseVideo}><Icon id='compress' fixedWidth /></button>}
  412. <button type='button' aria-label={intl.formatMessage(messages.download)}>
  413. <a className='video-player__download__icon' href={this.props.src} download>
  414. <Icon id={'download'} fixedWidth />
  415. </a>
  416. </button>
  417. <button type='button' aria-label={intl.formatMessage(fullscreen ? messages.exit_fullscreen : messages.fullscreen)} onClick={this.toggleFullscreen}><Icon id={fullscreen ? 'compress' : 'arrows-alt'} fixedWidth /></button>
  418. </div>
  419. </div>
  420. </div>
  421. </div>
  422. );
  423. }
  424. }