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.

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