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.

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