'use client'; import { forwardRef, ReactNode, UIEvent, useEffect, useRef, useState } from 'react'; import { createPortal } from 'react-dom'; import { Virtuoso, VirtuosoProps } from 'react-virtuoso'; import { useAtom } from 'jotai'; import { atomWithStorage } from 'jotai/utils'; import { SlidersHorizontal } from 'lucide-react'; import Card from '@/components/Movie/Card'; import Preview from '@/components/Movie/Preview'; import { Button } from '@/components/ui/button'; import useMounted from '@/hooks/useMounted'; import useUrlToMagnet from '@/hooks/useUrlToMagnet'; import { genres } from '@/lib/api'; import getQueryClient from '@/lib/queryClient'; import Filter from './components/Filter'; import useRandomMovie from './useRandomMovie'; const isShowFilterAtom = atomWithStorage('is-show-filters', false); const components: VirtuosoProps['components'] = { Item: (props) =>
, List: forwardRef(function List(props, ref) { return (
); }), Scroller: forwardRef(function Scroller(props, ref) { return
; }) }; const Measurer = ({ children }: { children: (width: number) => ReactNode }) => { const [ref, setRef] = useState(null); const width = ref?.offsetWidth; return ( <>
{children(width || 0)} ); }; const Carousel = ({ movies, index = 0, width: initialWidth, onIndexChange }: { movies?: Movie[]; width: number; index: number; onIndexChange: (index: number) => void; }) => { const timeout = useRef(); const isMobile = matchMedia('(max-width: 500px)').matches; const width = isMobile ? initialWidth : 300; const height = isMobile ? (width * 3) / 2 : 450; const handleScroll = (event: UIEvent) => { clearTimeout(timeout.current); timeout.current = setTimeout(() => { const gap = 8; const item = event.target as HTMLDivElement; const itemWidth = item?.clientWidth + gap; const scrollPosition = item?.scrollLeft; const index = Math.round(scrollPosition / itemWidth); onIndexChange(index); }, 50); }; return ( { clearTimeout(timeout.current); timeout.current = setTimeout(() => { console.log(index); // onIndexChange(index); }, 100); return ; }} /> ); }; export default function Container() { const [isShowFilter, setIsShowFilter] = useAtom(isShowFilterAtom); const { movies, movie, index, onIndexChange } = useRandomMovie(); const isMounted = useMounted(); const initialIndex = useRef(index); useUrlToMagnet(); useEffect(() => { const queryClient = getQueryClient(); queryClient.prefetchQuery({ queryKey: ['genres'], queryFn: () => genres() }); }, []); return ( <> {isShowFilter && } {isMounted && createPortal( , document.getElementById('actions')! )} {(width) => ( } /> )}
); }