UNPKG

@kubit-ui-web/react-components

Version:

Kubit React Components is a customizable, accessible library of React web components, designed to enhance your application's user experience

53 lines 2.02 kB
import { useCallback, useEffect, useRef, useState } from 'react'; import { isKeyEnterPressed, isKeySpacePressed } from '../../../utils/keyboard/keyboard.utility'; export const useMediaProgressBar = ({ playingExternal, circular, currentBar, barsNum, onBarChange, onFinish, onBarClick, onBarKeyDown, }) => { //playing prop is managed between the user and the component itself const [playing, setplaying] = useState(playingExternal); const barRef = useRef(null); const progressBarRef = useRef(null); //We are checking if user has changed "playing" prop useEffect(() => { setplaying(playingExternal); }, [playingExternal]); //function called when a bar ends const handleBarEnd = useCallback(() => { if (circular || currentBar !== barsNum - 1) { onBarChange?.(currentBar + 1); } else { //If it is the last one const playingFinal = false; setplaying(playingFinal); onFinish?.(playingFinal); } }, [currentBar, barsNum, onBarChange]); const handleClickBar = (index, event) => { onBarChange?.(index, event); onBarClick?.(index, event); }; const handleKeyDownBar = (index, event) => { if (isKeySpacePressed(event.key) || isKeyEnterPressed(event.key)) { event.preventDefault(); onBarChange?.(index, event); onBarKeyDown?.(index, event); } }; useEffect(() => { //Call handleBarEnd when animation ends if (progressBarRef.current && playing) { progressBarRef.current.addEventListener('animationend', handleBarEnd); } return () => { progressBarRef.current?.removeEventListener('animationend', handleBarEnd); }; }, [playing, handleBarEnd]); return { playing, barRef, progressBarRef, handleBarEnd, handleClickBar, handleKeyDownBar, }; }; //# sourceMappingURL=useMediaProgressBar.js.map