// TODO: Detect visibility and preload? import React from 'react'; import classNames from 'classnames'; import PlayIcon from '@moda/icons/play-60'; import PauseIcon from '@moda/icons/pause-60'; import {ButtonBase} from 'display-library/Button'; import {VideoPlayerProgressBar} from './video_player_progress_bar'; import './video_player.scss'; export interface Props extends React.HTMLProps { sources: { src: string; mime: string; }[]; } interface State { isPlaying: boolean; isPaused: boolean; isLoaded: boolean; progress: number; } type Action = | {type: 'LOADED'} | {type: 'PLAYING'} | {type: 'PAUSED'} | {type: 'PROGRESS'; payload: {progress: number}}; const reducer = (state: State, action: Action): State => { switch (action.type) { case 'LOADED': return { ...state, isLoaded: true }; case 'PLAYING': return { ...state, isPlaying: true, isPaused: false }; case 'PAUSED': return { ...state, isPlaying: false, isPaused: true }; case 'PROGRESS': return { ...state, progress: action.payload.progress }; } }; export const VideoPlayer: React.FC = ({ sources, loop = true, muted = true, playsInline = true, autoPlay = true, preload = 'auto', className, ...rest }) => { const ref = React.useRef(); const [state, dispatch] = React.useReducer(reducer, { isPlaying: false, isPaused: true, isLoaded: false, progress: 0 }); const handleLoad = React.useCallback(() => dispatch({type: 'LOADED'}), []); const handlePlay = React.useCallback(() => dispatch({type: 'PLAYING'}), []); const handlePause = React.useCallback(() => dispatch({type: 'PAUSED'}), []); const handleClick = React.useCallback(() => { state.isPlaying ? ref.current.pause() : ref.current.play(); }, [state.isPlaying]); const handleProgress = React.useCallback(() => { dispatch({ type: 'PROGRESS', payload: { progress: Math.floor( (100 / ref.current.duration) * ref.current.currentTime ) } }); }, []); React.useEffect(() => { const player = ref.current; player.addEventListener('timeupdate', handleProgress); return (): void => player.removeEventListener('timeupdate', handleProgress); }, [handleProgress]); return (
{state.isPlaying ? : }
); };