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.

451 lines
14 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 '../ui/util/fullscreen';
  8. import { displayMedia } from '../../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. export default @injectIntl
  71. 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. startTime: PropTypes.number,
  80. onOpenVideo: PropTypes.func,
  81. onCloseVideo: PropTypes.func,
  82. detailed: PropTypes.bool,
  83. inline: PropTypes.bool,
  84. intl: PropTypes.object.isRequired,
  85. };
  86. state = {
  87. currentTime: 0,
  88. duration: 0,
  89. volume: 0.5,
  90. paused: true,
  91. dragging: false,
  92. containerWidth: false,
  93. fullscreen: false,
  94. hovered: false,
  95. muted: false,
  96. revealed: displayMedia !== 'hide_all' && !this.props.sensitive || displayMedia === 'show_all',
  97. };
  98. // hard coded in components.scss
  99. // any way to get ::before values programatically?
  100. volWidth = 50;
  101. volOffset = 70;
  102. volHandleOffset = v => {
  103. const offset = v * this.volWidth + this.volOffset;
  104. return (offset > 110) ? 110 : offset;
  105. }
  106. setPlayerRef = c => {
  107. this.player = c;
  108. if (c) {
  109. this.setState({
  110. containerWidth: c.offsetWidth,
  111. });
  112. }
  113. }
  114. setVideoRef = c => {
  115. this.video = c;
  116. if (this.video) {
  117. this.setState({ volume: this.video.volume, muted: this.video.muted });
  118. }
  119. }
  120. setSeekRef = c => {
  121. this.seek = c;
  122. }
  123. setVolumeRef = c => {
  124. this.volume = c;
  125. }
  126. handleClickRoot = e => e.stopPropagation();
  127. handlePlay = () => {
  128. this.setState({ paused: false });
  129. }
  130. handlePause = () => {
  131. this.setState({ paused: true });
  132. }
  133. handleTimeUpdate = () => {
  134. this.setState({
  135. currentTime: Math.floor(this.video.currentTime),
  136. duration: Math.floor(this.video.duration),
  137. });
  138. }
  139. handleVolumeMouseDown = e => {
  140. document.addEventListener('mousemove', this.handleMouseVolSlide, true);
  141. document.addEventListener('mouseup', this.handleVolumeMouseUp, true);
  142. document.addEventListener('touchmove', this.handleMouseVolSlide, true);
  143. document.addEventListener('touchend', this.handleVolumeMouseUp, true);
  144. this.handleMouseVolSlide(e);
  145. e.preventDefault();
  146. e.stopPropagation();
  147. }
  148. handleVolumeMouseUp = () => {
  149. document.removeEventListener('mousemove', this.handleMouseVolSlide, true);
  150. document.removeEventListener('mouseup', this.handleVolumeMouseUp, true);
  151. document.removeEventListener('touchmove', this.handleMouseVolSlide, true);
  152. document.removeEventListener('touchend', this.handleVolumeMouseUp, true);
  153. }
  154. handleMouseVolSlide = throttle(e => {
  155. const rect = this.volume.getBoundingClientRect();
  156. const x = (e.clientX - rect.left) / this.volWidth; //x position within the element.
  157. if(!isNaN(x)) {
  158. var slideamt = x;
  159. if(x > 1) {
  160. slideamt = 1;
  161. } else if(x < 0) {
  162. slideamt = 0;
  163. }
  164. this.video.volume = slideamt;
  165. this.setState({ volume: slideamt });
  166. }
  167. }, 60);
  168. handleMouseDown = e => {
  169. document.addEventListener('mousemove', this.handleMouseMove, true);
  170. document.addEventListener('mouseup', this.handleMouseUp, true);
  171. document.addEventListener('touchmove', this.handleMouseMove, true);
  172. document.addEventListener('touchend', this.handleMouseUp, true);
  173. this.setState({ dragging: true });
  174. this.video.pause();
  175. this.handleMouseMove(e);
  176. e.preventDefault();
  177. e.stopPropagation();
  178. }
  179. handleMouseUp = () => {
  180. document.removeEventListener('mousemove', this.handleMouseMove, true);
  181. document.removeEventListener('mouseup', this.handleMouseUp, true);
  182. document.removeEventListener('touchmove', this.handleMouseMove, true);
  183. document.removeEventListener('touchend', this.handleMouseUp, true);
  184. this.setState({ dragging: false });
  185. this.video.play();
  186. }
  187. handleMouseMove = throttle(e => {
  188. const { x } = getPointerPosition(this.seek, e);
  189. const currentTime = Math.floor(this.video.duration * x);
  190. if (!isNaN(currentTime)) {
  191. this.video.currentTime = currentTime;
  192. this.setState({ currentTime });
  193. }
  194. }, 60);
  195. togglePlay = () => {
  196. if (this.state.paused) {
  197. this.video.play();
  198. } else {
  199. this.video.pause();
  200. }
  201. }
  202. toggleFullscreen = () => {
  203. if (isFullscreen()) {
  204. exitFullscreen();
  205. } else {
  206. requestFullscreen(this.player);
  207. }
  208. }
  209. componentDidMount () {
  210. document.addEventListener('fullscreenchange', this.handleFullscreenChange, true);
  211. document.addEventListener('webkitfullscreenchange', this.handleFullscreenChange, true);
  212. document.addEventListener('mozfullscreenchange', this.handleFullscreenChange, true);
  213. document.addEventListener('MSFullscreenChange', this.handleFullscreenChange, true);
  214. }
  215. componentWillUnmount () {
  216. document.removeEventListener('fullscreenchange', this.handleFullscreenChange, true);
  217. document.removeEventListener('webkitfullscreenchange', this.handleFullscreenChange, true);
  218. document.removeEventListener('mozfullscreenchange', this.handleFullscreenChange, true);
  219. document.removeEventListener('MSFullscreenChange', this.handleFullscreenChange, true);
  220. }
  221. handleFullscreenChange = () => {
  222. this.setState({ fullscreen: isFullscreen() });
  223. }
  224. handleMouseEnter = () => {
  225. this.setState({ hovered: true });
  226. }
  227. handleMouseLeave = () => {
  228. this.setState({ hovered: false });
  229. }
  230. toggleMute = () => {
  231. this.video.muted = !this.video.muted;
  232. this.setState({ muted: this.video.muted });
  233. }
  234. toggleReveal = () => {
  235. if (this.state.revealed) {
  236. this.video.pause();
  237. }
  238. this.setState({ revealed: !this.state.revealed });
  239. }
  240. handleLoadedData = () => {
  241. if (this.props.startTime) {
  242. this.video.currentTime = this.props.startTime;
  243. this.video.play();
  244. }
  245. }
  246. handleProgress = () => {
  247. if (this.video.buffered.length > 0) {
  248. this.setState({ buffer: this.video.buffered.end(0) / this.video.duration * 100 });
  249. }
  250. }
  251. handleVolumeChange = () => {
  252. this.setState({ volume: this.video.volume, muted: this.video.muted });
  253. }
  254. handleOpenVideo = () => {
  255. const { src, preview, width, height, alt } = this.props;
  256. const media = fromJS({
  257. type: 'video',
  258. url: src,
  259. preview_url: preview,
  260. description: alt,
  261. width,
  262. height,
  263. });
  264. this.video.pause();
  265. this.props.onOpenVideo(media, this.video.currentTime);
  266. }
  267. handleCloseVideo = () => {
  268. this.video.pause();
  269. this.props.onCloseVideo();
  270. }
  271. render () {
  272. const { preview, src, inline, startTime, onOpenVideo, onCloseVideo, intl, alt, detailed, sensitive } = this.props;
  273. const { containerWidth, currentTime, duration, volume, buffer, dragging, paused, fullscreen, hovered, muted, revealed } = this.state;
  274. const progress = (currentTime / duration) * 100;
  275. const volumeWidth = (muted) ? 0 : volume * this.volWidth;
  276. const volumeHandleLoc = (muted) ? this.volHandleOffset(0) : this.volHandleOffset(volume);
  277. const playerStyle = {};
  278. let { width, height } = this.props;
  279. if (inline && containerWidth) {
  280. width = containerWidth;
  281. height = containerWidth / (16/9);
  282. playerStyle.width = width;
  283. playerStyle.height = height;
  284. }
  285. let preload;
  286. if (startTime || fullscreen || dragging) {
  287. preload = 'auto';
  288. } else if (detailed) {
  289. preload = 'metadata';
  290. } else {
  291. preload = 'none';
  292. }
  293. let warning;
  294. if (sensitive) {
  295. warning = <FormattedMessage id='status.sensitive_warning' defaultMessage='Sensitive content' />;
  296. } else {
  297. warning = <FormattedMessage id='status.media_hidden' defaultMessage='Media hidden' />;
  298. }
  299. return (
  300. <div
  301. role='menuitem'
  302. className={classNames('video-player', { inactive: !revealed, detailed, inline: inline && !fullscreen, fullscreen })}
  303. style={playerStyle}
  304. ref={this.setPlayerRef}
  305. onMouseEnter={this.handleMouseEnter}
  306. onMouseLeave={this.handleMouseLeave}
  307. onClick={this.handleClickRoot}
  308. tabIndex={0}
  309. >
  310. <video
  311. ref={this.setVideoRef}
  312. src={src}
  313. poster={preview}
  314. preload={preload}
  315. loop
  316. role='button'
  317. tabIndex='0'
  318. aria-label={alt}
  319. title={alt}
  320. width={width}
  321. height={height}
  322. volume={volume}
  323. onClick={this.togglePlay}
  324. onPlay={this.handlePlay}
  325. onPause={this.handlePause}
  326. onTimeUpdate={this.handleTimeUpdate}
  327. onLoadedData={this.handleLoadedData}
  328. onProgress={this.handleProgress}
  329. onVolumeChange={this.handleVolumeChange}
  330. />
  331. <button type='button' className={classNames('video-player__spoiler', { active: !revealed })} onClick={this.toggleReveal}>
  332. <span className='video-player__spoiler__title'>{warning}</span>
  333. <span className='video-player__spoiler__subtitle'><FormattedMessage id='status.sensitive_toggle' defaultMessage='Click to view' /></span>
  334. </button>
  335. <div className={classNames('video-player__controls', { active: paused || hovered })}>
  336. <div className='video-player__seek' onMouseDown={this.handleMouseDown} ref={this.setSeekRef}>
  337. <div className='video-player__seek__buffer' style={{ width: `${buffer}%` }} />
  338. <div className='video-player__seek__progress' style={{ width: `${progress}%` }} />
  339. <span
  340. className={classNames('video-player__seek__handle', { active: dragging })}
  341. tabIndex='0'
  342. style={{ left: `${progress}%` }}
  343. />
  344. </div>
  345. <div className='video-player__buttons-bar'>
  346. <div className='video-player__buttons left'>
  347. <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>
  348. <button type='button' aria-label={intl.formatMessage(muted ? messages.unmute : messages.mute)} onClick={this.toggleMute}><i className={classNames('fa fa-fw', { 'fa-volume-off': muted, 'fa-volume-up': !muted })} /></button>
  349. <div className='video-player__volume' onMouseDown={this.handleVolumeMouseDown} ref={this.setVolumeRef}>
  350. <div className='video-player__volume__current' style={{ width: `${volumeWidth}px` }} />
  351. <span
  352. className={classNames('video-player__volume__handle')}
  353. tabIndex='0'
  354. style={{ left: `${volumeHandleLoc}px` }}
  355. />
  356. </div>
  357. {(detailed || fullscreen) &&
  358. <span>
  359. <span className='video-player__time-current'>{formatTime(currentTime)}</span>
  360. <span className='video-player__time-sep'>/</span>
  361. <span className='video-player__time-total'>{formatTime(duration)}</span>
  362. </span>
  363. }
  364. </div>
  365. <div className='video-player__buttons right'>
  366. {!onCloseVideo && <button type='button' aria-label={intl.formatMessage(messages.hide)} onClick={this.toggleReveal}><i className='fa fa-fw fa-eye' /></button>}
  367. {(!fullscreen && onOpenVideo) && <button type='button' aria-label={intl.formatMessage(messages.expand)} onClick={this.handleOpenVideo}><i className='fa fa-fw fa-expand' /></button>}
  368. {onCloseVideo && <button type='button' aria-label={intl.formatMessage(messages.close)} onClick={this.handleCloseVideo}><i className='fa fa-fw fa-compress' /></button>}
  369. <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>
  370. </div>
  371. </div>
  372. </div>
  373. </div>
  374. );
  375. }
  376. }