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.
 
 
 
 
spa_instat_tv/src/features/MultiSourcePlayer/hooks/usePlayingState.tsx

42 lines
899 B

import type { RefObject } from 'react'
import { useState, useCallback } from 'react'
import once from 'lodash/once'
import { useEventListener } from 'hooks'
export const usePlayingState = (videoRef: RefObject<HTMLVideoElement>) => {
const [playing, setPlaying] = useState(false)
const [ready, setReady] = useState(false)
const togglePlaying = useCallback(() => {
setPlaying((isPlaying) => {
const video = videoRef.current
if (!ready || !video) return false
const nextIsPlaying = !isPlaying
if (nextIsPlaying) {
video.play()
} else {
video.pause()
}
return nextIsPlaying
})
}, [videoRef, ready])
const onReady = useCallback(once(() => {
setReady(true)
}), [])
useEventListener({
callback: onReady,
event: 'canplay',
ref: videoRef,
})
return {
playing,
ready,
togglePlaying,
}
}