The code powering m.abunchtell.com https://m.abunchtell.com
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.
 
 
 
 

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