index.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654
  1. import React from 'react';
  2. import PropTypes from 'prop-types';
  3. import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
  4. import { 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.slice(index + 1);
  77. };
  78. export default @injectIntl
  79. class Video extends React.PureComponent {
  80. static propTypes = {
  81. preview: PropTypes.string,
  82. frameRate: PropTypes.string,
  83. src: PropTypes.string.isRequired,
  84. alt: PropTypes.string,
  85. width: PropTypes.number,
  86. height: PropTypes.number,
  87. sensitive: PropTypes.bool,
  88. currentTime: PropTypes.number,
  89. onOpenVideo: PropTypes.func,
  90. onCloseVideo: PropTypes.func,
  91. detailed: PropTypes.bool,
  92. inline: PropTypes.bool,
  93. editable: PropTypes.bool,
  94. alwaysVisible: PropTypes.bool,
  95. cacheWidth: PropTypes.func,
  96. visible: PropTypes.bool,
  97. onToggleVisibility: PropTypes.func,
  98. deployPictureInPicture: PropTypes.func,
  99. intl: PropTypes.object.isRequired,
  100. blurhash: PropTypes.string,
  101. autoPlay: PropTypes.bool,
  102. volume: PropTypes.number,
  103. muted: PropTypes.bool,
  104. componentIndex: PropTypes.number,
  105. };
  106. static defaultProps = {
  107. frameRate: '25',
  108. };
  109. state = {
  110. currentTime: 0,
  111. duration: 0,
  112. volume: 0.5,
  113. paused: true,
  114. dragging: false,
  115. containerWidth: this.props.width,
  116. fullscreen: false,
  117. hovered: false,
  118. muted: false,
  119. revealed: this.props.visible !== undefined ? this.props.visible : (displayMedia !== 'hide_all' && !this.props.sensitive || displayMedia === 'show_all'),
  120. };
  121. setPlayerRef = c => {
  122. this.player = c;
  123. if (this.player) {
  124. this._setDimensions();
  125. }
  126. }
  127. _setDimensions () {
  128. const width = this.player.offsetWidth;
  129. if (this.props.cacheWidth) {
  130. this.props.cacheWidth(width);
  131. }
  132. this.setState({
  133. containerWidth: width,
  134. });
  135. }
  136. setVideoRef = c => {
  137. this.video = c;
  138. if (this.video) {
  139. this.setState({ volume: this.video.volume, muted: this.video.muted });
  140. }
  141. }
  142. setSeekRef = c => {
  143. this.seek = c;
  144. }
  145. setVolumeRef = c => {
  146. this.volume = c;
  147. }
  148. handleClickRoot = e => e.stopPropagation();
  149. handlePlay = () => {
  150. this.setState({ paused: false });
  151. this._updateTime();
  152. }
  153. handlePause = () => {
  154. this.setState({ paused: true });
  155. }
  156. _updateTime () {
  157. requestAnimationFrame(() => {
  158. if (!this.video) return;
  159. this.handleTimeUpdate();
  160. if (!this.state.paused) {
  161. this._updateTime();
  162. }
  163. });
  164. }
  165. handleTimeUpdate = () => {
  166. this.setState({
  167. currentTime: this.video.currentTime,
  168. duration:this.video.duration,
  169. });
  170. }
  171. handleVolumeMouseDown = e => {
  172. document.addEventListener('mousemove', this.handleMouseVolSlide, true);
  173. document.addEventListener('mouseup', this.handleVolumeMouseUp, true);
  174. document.addEventListener('touchmove', this.handleMouseVolSlide, true);
  175. document.addEventListener('touchend', this.handleVolumeMouseUp, true);
  176. this.handleMouseVolSlide(e);
  177. e.preventDefault();
  178. e.stopPropagation();
  179. }
  180. handleVolumeMouseUp = () => {
  181. document.removeEventListener('mousemove', this.handleMouseVolSlide, true);
  182. document.removeEventListener('mouseup', this.handleVolumeMouseUp, true);
  183. document.removeEventListener('touchmove', this.handleMouseVolSlide, true);
  184. document.removeEventListener('touchend', this.handleVolumeMouseUp, true);
  185. }
  186. handleMouseVolSlide = throttle(e => {
  187. const { x } = getPointerPosition(this.volume, e);
  188. if(!isNaN(x)) {
  189. this.setState({ volume: x }, () => {
  190. this.video.volume = x;
  191. });
  192. }
  193. }, 15);
  194. handleMouseDown = e => {
  195. document.addEventListener('mousemove', this.handleMouseMove, true);
  196. document.addEventListener('mouseup', this.handleMouseUp, true);
  197. document.addEventListener('touchmove', this.handleMouseMove, true);
  198. document.addEventListener('touchend', this.handleMouseUp, true);
  199. this.setState({ dragging: true });
  200. this.video.pause();
  201. this.handleMouseMove(e);
  202. e.preventDefault();
  203. e.stopPropagation();
  204. }
  205. handleMouseUp = () => {
  206. document.removeEventListener('mousemove', this.handleMouseMove, true);
  207. document.removeEventListener('mouseup', this.handleMouseUp, true);
  208. document.removeEventListener('touchmove', this.handleMouseMove, true);
  209. document.removeEventListener('touchend', this.handleMouseUp, true);
  210. this.setState({ dragging: false });
  211. this.video.play();
  212. }
  213. handleMouseMove = throttle(e => {
  214. const { x } = getPointerPosition(this.seek, e);
  215. const currentTime = this.video.duration * x;
  216. if (!isNaN(currentTime)) {
  217. this.setState({ currentTime }, () => {
  218. this.video.currentTime = currentTime;
  219. });
  220. }
  221. }, 15);
  222. seekBy (time) {
  223. const currentTime = this.video.currentTime + time;
  224. if (!isNaN(currentTime)) {
  225. this.setState({ currentTime }, () => {
  226. this.video.currentTime = currentTime;
  227. });
  228. }
  229. }
  230. handleVideoKeyDown = e => {
  231. // On the video element or the seek bar, we can safely use the space bar
  232. // for playback control because there are no buttons to press
  233. if (e.key === ' ') {
  234. e.preventDefault();
  235. e.stopPropagation();
  236. this.togglePlay();
  237. }
  238. }
  239. handleKeyDown = e => {
  240. const frameTime = 1 / this.getFrameRate();
  241. switch(e.key) {
  242. case 'k':
  243. e.preventDefault();
  244. e.stopPropagation();
  245. this.togglePlay();
  246. break;
  247. case 'm':
  248. e.preventDefault();
  249. e.stopPropagation();
  250. this.toggleMute();
  251. break;
  252. case 'f':
  253. e.preventDefault();
  254. e.stopPropagation();
  255. this.toggleFullscreen();
  256. break;
  257. case 'j':
  258. e.preventDefault();
  259. e.stopPropagation();
  260. this.seekBy(-10);
  261. break;
  262. case 'l':
  263. e.preventDefault();
  264. e.stopPropagation();
  265. this.seekBy(10);
  266. break;
  267. case ',':
  268. e.preventDefault();
  269. e.stopPropagation();
  270. this.seekBy(-frameTime);
  271. break;
  272. case '.':
  273. e.preventDefault();
  274. e.stopPropagation();
  275. this.seekBy(frameTime);
  276. break;
  277. }
  278. // If we are in fullscreen mode, we don't want any hotkeys
  279. // interacting with the UI that's not visible
  280. if (this.state.fullscreen) {
  281. e.preventDefault();
  282. e.stopPropagation();
  283. if (e.key === 'Escape') {
  284. exitFullscreen();
  285. }
  286. }
  287. }
  288. togglePlay = () => {
  289. if (this.state.paused) {
  290. this.setState({ paused: false }, () => this.video.play());
  291. } else {
  292. this.setState({ paused: true }, () => this.video.pause());
  293. }
  294. }
  295. toggleFullscreen = () => {
  296. if (isFullscreen()) {
  297. exitFullscreen();
  298. } else {
  299. requestFullscreen(this.player);
  300. }
  301. }
  302. componentDidMount () {
  303. document.addEventListener('fullscreenchange', this.handleFullscreenChange, true);
  304. document.addEventListener('webkitfullscreenchange', this.handleFullscreenChange, true);
  305. document.addEventListener('mozfullscreenchange', this.handleFullscreenChange, true);
  306. document.addEventListener('MSFullscreenChange', this.handleFullscreenChange, true);
  307. window.addEventListener('scroll', this.handleScroll);
  308. window.addEventListener('resize', this.handleResize, { passive: true });
  309. }
  310. componentWillUnmount () {
  311. window.removeEventListener('scroll', this.handleScroll);
  312. window.removeEventListener('resize', this.handleResize);
  313. document.removeEventListener('fullscreenchange', this.handleFullscreenChange, true);
  314. document.removeEventListener('webkitfullscreenchange', this.handleFullscreenChange, true);
  315. document.removeEventListener('mozfullscreenchange', this.handleFullscreenChange, true);
  316. document.removeEventListener('MSFullscreenChange', this.handleFullscreenChange, true);
  317. if (!this.state.paused && this.video && this.props.deployPictureInPicture) {
  318. this.props.deployPictureInPicture('video', {
  319. src: this.props.src,
  320. currentTime: this.video.currentTime,
  321. muted: this.video.muted,
  322. volume: this.video.volume,
  323. });
  324. }
  325. }
  326. componentWillReceiveProps (nextProps) {
  327. if (!is(nextProps.visible, this.props.visible) && nextProps.visible !== undefined) {
  328. this.setState({ revealed: nextProps.visible });
  329. }
  330. }
  331. componentDidUpdate (prevProps, prevState) {
  332. if (prevState.revealed && !this.state.revealed && this.video) {
  333. this.video.pause();
  334. }
  335. }
  336. handleResize = debounce(() => {
  337. if (this.player) {
  338. this._setDimensions();
  339. }
  340. }, 250, {
  341. trailing: true,
  342. });
  343. handleScroll = throttle(() => {
  344. if (!this.video) {
  345. return;
  346. }
  347. const { top, height } = this.video.getBoundingClientRect();
  348. const inView = (top <= (window.innerHeight || document.documentElement.clientHeight)) && (top + height >= 0);
  349. if (!this.state.paused && !inView) {
  350. this.video.pause();
  351. if (this.props.deployPictureInPicture) {
  352. this.props.deployPictureInPicture('video', {
  353. src: this.props.src,
  354. currentTime: this.video.currentTime,
  355. muted: this.video.muted,
  356. volume: this.video.volume,
  357. });
  358. }
  359. this.setState({ paused: true });
  360. }
  361. }, 150, { trailing: true })
  362. handleFullscreenChange = () => {
  363. this.setState({ fullscreen: isFullscreen() });
  364. }
  365. handleMouseEnter = () => {
  366. this.setState({ hovered: true });
  367. }
  368. handleMouseLeave = () => {
  369. this.setState({ hovered: false });
  370. }
  371. toggleMute = () => {
  372. const muted = !this.video.muted;
  373. this.setState({ muted }, () => {
  374. this.video.muted = muted;
  375. });
  376. }
  377. toggleReveal = () => {
  378. if (this.props.onToggleVisibility) {
  379. this.props.onToggleVisibility();
  380. } else {
  381. this.setState({ revealed: !this.state.revealed });
  382. }
  383. }
  384. handleLoadedData = () => {
  385. const { currentTime, volume, muted, autoPlay } = this.props;
  386. if (currentTime) {
  387. this.video.currentTime = currentTime;
  388. }
  389. if (volume !== undefined) {
  390. this.video.volume = volume;
  391. }
  392. if (muted !== undefined) {
  393. this.video.muted = muted;
  394. }
  395. if (autoPlay) {
  396. this.video.play();
  397. }
  398. }
  399. handleProgress = () => {
  400. const lastTimeRange = this.video.buffered.length - 1;
  401. if (lastTimeRange > -1) {
  402. this.setState({ buffer: Math.ceil(this.video.buffered.end(lastTimeRange) / this.video.duration * 100) });
  403. }
  404. }
  405. handleVolumeChange = () => {
  406. this.setState({ volume: this.video.volume, muted: this.video.muted });
  407. }
  408. handleOpenVideo = () => {
  409. this.video.pause();
  410. this.props.onOpenVideo({
  411. startTime: this.video.currentTime,
  412. autoPlay: !this.state.paused,
  413. defaultVolume: this.state.volume,
  414. componentIndex: this.props.componentIndex,
  415. });
  416. }
  417. handleCloseVideo = () => {
  418. this.video.pause();
  419. this.props.onCloseVideo();
  420. }
  421. getFrameRate () {
  422. if (this.props.frameRate && isNaN(this.props.frameRate)) {
  423. // The frame rate is returned as a fraction string so we
  424. // need to convert it to a number
  425. return this.props.frameRate.split('/').reduce((p, c) => p / c);
  426. }
  427. return this.props.frameRate;
  428. }
  429. render () {
  430. const { preview, src, inline, onOpenVideo, onCloseVideo, intl, alt, detailed, sensitive, editable, blurhash } = this.props;
  431. const { containerWidth, currentTime, duration, volume, buffer, dragging, paused, fullscreen, hovered, muted, revealed } = this.state;
  432. const progress = Math.min((currentTime / duration) * 100, 100);
  433. const playerStyle = {};
  434. let { width, height } = this.props;
  435. if (inline && containerWidth) {
  436. width = containerWidth;
  437. height = containerWidth / (16/9);
  438. playerStyle.height = height;
  439. }
  440. let preload;
  441. if (this.props.currentTime || fullscreen || dragging) {
  442. preload = 'auto';
  443. } else if (detailed) {
  444. preload = 'metadata';
  445. } else {
  446. preload = 'none';
  447. }
  448. let warning;
  449. if (sensitive) {
  450. warning = <FormattedMessage id='status.sensitive_warning' defaultMessage='Sensitive content' />;
  451. } else {
  452. warning = <FormattedMessage id='status.media_hidden' defaultMessage='Media hidden' />;
  453. }
  454. return (
  455. <div
  456. role='menuitem'
  457. className={classNames('video-player', { inactive: !revealed, detailed, inline: inline && !fullscreen, fullscreen, editable })}
  458. style={playerStyle}
  459. ref={this.setPlayerRef}
  460. onMouseEnter={this.handleMouseEnter}
  461. onMouseLeave={this.handleMouseLeave}
  462. onClick={this.handleClickRoot}
  463. onKeyDown={this.handleKeyDown}
  464. tabIndex={0}
  465. >
  466. <Blurhash
  467. hash={blurhash}
  468. className={classNames('media-gallery__preview', {
  469. 'media-gallery__preview--hidden': revealed,
  470. })}
  471. dummy={!useBlurhash}
  472. />
  473. {(revealed || editable) && <video
  474. ref={this.setVideoRef}
  475. src={src}
  476. poster={preview}
  477. preload={preload}
  478. role='button'
  479. tabIndex='0'
  480. aria-label={alt}
  481. title={alt}
  482. width={width}
  483. height={height}
  484. volume={volume}
  485. onClick={this.togglePlay}
  486. onKeyDown={this.handleVideoKeyDown}
  487. onPlay={this.handlePlay}
  488. onPause={this.handlePause}
  489. onLoadedData={this.handleLoadedData}
  490. onProgress={this.handleProgress}
  491. onVolumeChange={this.handleVolumeChange}
  492. />}
  493. <div className={classNames('spoiler-button', { 'spoiler-button--hidden': revealed || editable })}>
  494. <button type='button' className='spoiler-button__overlay' onClick={this.toggleReveal}>
  495. <span className='spoiler-button__overlay__label'>{warning}</span>
  496. </button>
  497. </div>
  498. <div className={classNames('video-player__controls', { active: paused || hovered })}>
  499. <div className='video-player__seek' onMouseDown={this.handleMouseDown} ref={this.setSeekRef}>
  500. <div className='video-player__seek__buffer' style={{ width: `${buffer}%` }} />
  501. <div className='video-player__seek__progress' style={{ width: `${progress}%` }} />
  502. <span
  503. className={classNames('video-player__seek__handle', { active: dragging })}
  504. tabIndex='0'
  505. style={{ left: `${progress}%` }}
  506. onKeyDown={this.handleVideoKeyDown}
  507. />
  508. </div>
  509. <div className='video-player__buttons-bar'>
  510. <div className='video-player__buttons left'>
  511. <button type='button' title={intl.formatMessage(paused ? messages.play : messages.pause)} aria-label={intl.formatMessage(paused ? messages.play : messages.pause)} className='player-button' onClick={this.togglePlay} autoFocus={detailed}><Icon id={paused ? 'play' : 'pause'} fixedWidth /></button>
  512. <button type='button' title={intl.formatMessage(muted ? messages.unmute : messages.mute)} aria-label={intl.formatMessage(muted ? messages.unmute : messages.mute)} className='player-button' onClick={this.toggleMute}><Icon id={muted ? 'volume-off' : 'volume-up'} fixedWidth /></button>
  513. <div className={classNames('video-player__volume', { active: this.state.hovered })} onMouseDown={this.handleVolumeMouseDown} ref={this.setVolumeRef}>
  514. <div className='video-player__volume__current' style={{ width: `${volume * 100}%` }} />
  515. <span
  516. className={classNames('video-player__volume__handle')}
  517. tabIndex='0'
  518. style={{ left: `${volume * 100}%` }}
  519. />
  520. </div>
  521. {(detailed || fullscreen) && (
  522. <span className='video-player__time'>
  523. <span className='video-player__time-current'>{formatTime(Math.floor(currentTime))}</span>
  524. <span className='video-player__time-sep'>/</span>
  525. <span className='video-player__time-total'>{formatTime(Math.floor(duration))}</span>
  526. </span>
  527. )}
  528. </div>
  529. <div className='video-player__buttons right'>
  530. {(!onCloseVideo && !editable && !fullscreen && !this.props.alwaysVisible) && <button type='button' title={intl.formatMessage(messages.hide)} aria-label={intl.formatMessage(messages.hide)} className='player-button' onClick={this.toggleReveal}><Icon id='eye-slash' fixedWidth /></button>}
  531. {(!fullscreen && onOpenVideo) && <button type='button' title={intl.formatMessage(messages.expand)} aria-label={intl.formatMessage(messages.expand)} className='player-button' onClick={this.handleOpenVideo}><Icon id='expand' fixedWidth /></button>}
  532. {onCloseVideo && <button type='button' title={intl.formatMessage(messages.close)} aria-label={intl.formatMessage(messages.close)} className='player-button' onClick={this.handleCloseVideo}><Icon id='compress' fixedWidth /></button>}
  533. <button type='button' title={intl.formatMessage(fullscreen ? messages.exit_fullscreen : messages.fullscreen)} aria-label={intl.formatMessage(fullscreen ? messages.exit_fullscreen : messages.fullscreen)} className='player-button' onClick={this.toggleFullscreen}><Icon id={fullscreen ? 'compress' : 'arrows-alt'} fixedWidth /></button>
  534. </div>
  535. </div>
  536. </div>
  537. </div>
  538. );
  539. }
  540. }