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.

463 lines
15 KiB

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