import { useCallback } from 'react' import type { SetPartialState } from 'hooks' import type { Chapters } from '../types' import type { PlayerState } from '.' import { findChapterByProgress } from '../helpers' type Args = { chapters: Chapters, duration: number, setPlayerState: SetPartialState, } export const useProgressChangeHandler = ({ chapters, duration, setPlayerState, }: Args) => { const onProgressChange = useCallback((progress: number, seeking: boolean) => { setPlayerState((state) => { // значение новой позиции ползунка в миллисекундах const progressMs = progress * duration const chapterIndex = findChapterByProgress(chapters, progressMs) const chapter = chapters[chapterIndex] const isProgressOnDifferentChapter = ( chapterIndex !== -1 && chapterIndex !== state.activeChapterIndex ) const nextChapter = isProgressOnDifferentChapter ? chapterIndex : state.activeChapterIndex // отнимаем начало эпизода на котором остановились от общего прогресса // чтобы получить прогресс текущего эпизода const chapterProgressMs = (progressMs - chapter.startMs) const seekMs = chapterProgressMs + chapter.startOffsetMs return { activeChapterIndex: nextChapter, playedProgress: chapterProgressMs, seek: seekMs / 1000, seeking, } }) }, [duration, chapters, setPlayerState]) return onProgressChange }