import { useEffect } from 'react' import { useQuery } from 'react-query' import map from 'lodash/map' import isEmpty from 'lodash/isEmpty' import type { Match } from 'helpers' import { querieKeys } from 'config' import { MatchCard } from 'features/MatchCard' import { useMatchSwitchesStore } from 'features/MatchSwitches' import { LiveScore, getLiveScores } from 'requests' import { useMatchesSlider } from './hooks' import { Wrapper, Arrow, Slides, ArrowButton, } from './styled' type MatchesSliderProps = { matches: Array, } export const MatchesSlider = ({ matches }: MatchesSliderProps) => { const { isLeftArrowDisabled, isRightArrowDisabled, onScroll, onWrapperMouseEnter, onWrapperMouseLeave, showLeftArrow, showRightArrow, slideLeft, slideRight, slidesRef, } = useMatchesSlider(matches) const { isScoreHidden } = useMatchSwitchesStore() const { data: liveMatchScores } = useQuery({ queryFn: async () => { if (!isScoreHidden && matches.filter(({ live }) => live)?.length > 0) { const scores = await getLiveScores() return scores } return [] }, queryKey: querieKeys.liveMatchScores, refetchInterval: 5000, }) const scrollToMatchByIndex = (index: number) => { const offsetLeftCount = slidesRef.current!.querySelectorAll('li')[index].offsetLeft const PADDING_PARENT = 10 const offsetLeft = offsetLeftCount - PADDING_PARENT slidesRef.current!.scrollBy(offsetLeft, 0) } // скролл к лайв матчам или сегодняшней дате useEffect(() => { const matchIndexLive = matches.findIndex(({ live }) => live) if (matchIndexLive !== -1) { scrollToMatchByIndex(matchIndexLive) return } const matchIndex = matches.findIndex((item) => new Date() <= item.date) if (matchIndex !== -1) { scrollToMatchByIndex(matchIndex) return } const slidesRefClientWidth = slidesRef.current!.clientWidth const slidesRefScrollWidth = slidesRef.current!.scrollWidth slidesRef.current!.scrollBy(slidesRefScrollWidth - slidesRefClientWidth, 0) // eslint-disable-next-line react-hooks/exhaustive-deps }, []) if (isEmpty(matches)) return null return ( {showLeftArrow && ( )} {map(matches, (match) => ( match_id === match.id && sport_id === match.sportType, )} /> ))} {showRightArrow && ( )} ) }