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.
 
 
 
 

533 lines
17 KiB

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