feat: native carousel

This commit is contained in:
ner committed 2024-08-25 21:48:03 +03:00
1 parent 4ddaa89032
commit 5733bc0af0
20 files changed
+961 -534

No files matched your search

+91 -50
View File
@@ -1,15 +1,14 @@
'use client';
import { useEffect, useMemo, useRef } from 'react';
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 { ArrowLeft, ArrowRight, SlidersHorizontal } from 'lucide-react';
import { EffectCoverflow, Virtual } from 'swiper/modules';
import { Swiper, SwiperProps, SwiperSlide } from 'swiper/react';
import { SlidersHorizontal } from 'lucide-react';
import Card from '@/components/Movie/Card';
import Movie from '@/components/Movie/Preview';
import Preview from '@/components/Movie/Preview';
import { Button } from '@/components/ui/button';
import useMounted from '@/hooks/useMounted';
import useUrlToMagnet from '@/hooks/useUrlToMagnet';
@@ -21,22 +20,88 @@ import useRandomMovie from './useRandomMovie';
const isShowFilterAtom = atomWithStorage('is-show-filters', false);
const slideEffectProps: SwiperProps = {
effect: 'coverflow',
coverflowEffect: {
slideShadows: false,
depth: 200
},
virtual: {
addSlidesAfter: 3,
addSlidesBefore: 3
},
modules: [EffectCoverflow, Virtual]
const components: VirtuosoProps<Movie, number>['components'] = {
Item: (props) => <div {...props} className='shrink-0' style={{ ...props.style, width: props.context }} />,
List: forwardRef(function List(props, ref) {
return (
<div {...props} ref={ref} className='gap-2' style={{ ...props.style, display: 'flex', width: props.context }} />
);
}),
Scroller: forwardRef(function Scroller(props, ref) {
return <div {...props} ref={ref} className='overflow-hidden no-scrollbar snap-mandatory snap-x rounded-lg' />;
})
};
const Measurer = ({ children }: { children: (width: number) => ReactNode }) => {
const [ref, setRef] = useState<HTMLDivElement | null>(null);
const width = ref?.offsetWidth;
return (
<>
<div ref={setRef} />
{children(width || 0)}
</>
);
};
const Carousel = ({
movies,
index = 0,
width: initialWidth,
onIndexChange
}: {
movies?: Movie[];
width: number;
index: number;
onIndexChange: (index: number) => void;
}) => {
const timeout = useRef<NodeJS.Timeout>();
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 (
<Virtuoso
data={movies}
firstItemIndex={index}
style={{ width, height, flexShrink: 0 }}
totalCount={movies?.length}
horizontalDirection
context={width}
// onScroll={handleScroll}
components={components}
itemContent={(index) => {
clearTimeout(timeout.current);
timeout.current = setTimeout(() => {
console.log(index);
// onIndexChange(index);
}, 100);
return <Card className='snap-start' movie={movies?.[index]} />;
}}
/>
);
};
export default function Container() {
const [isShowFilter, setIsShowFilter] = useAtom(isShowFilterAtom);
const { ref, hasPrevious, movies, movie, next, previous, index, onDrag, onIndexChange } = useRandomMovie();
const { movies, movie, index, onIndexChange } = useRandomMovie();
const isMounted = useMounted();
const initialIndex = useRef(index);
@@ -48,29 +113,6 @@ export default function Container() {
queryClient.prefetchQuery({ queryKey: ['genres'], queryFn: () => genres() });
}, []);
const slides = useMemo(
() => (
<Swiper
onSwiper={(instance) => (ref.current = instance)}
lazyPreloadPrevNext={3}
longSwipesRatio={0.2}
speed={500}
initialSlide={initialIndex.current}
onActiveIndexChange={onIndexChange}
onTouchMove={(swiper) => onDrag(swiper)}
className='xs:w-[300px] w-full shrink-0'
{...slideEffectProps}
>
{movies?.map((movie, index) => (
<SwiperSlide key={movie.id} virtualIndex={index} className='cursor-grab active:cursor-grabbing'>
<Card fit movie={movie} />
</SwiperSlide>
))}
</Swiper>
),
[movies, onDrag, onIndexChange, ref]
);
return (
<>
{isShowFilter && <Filter />}
@@ -86,16 +128,15 @@ export default function Container() {
</Button>,
document.getElementById('actions')!
)}
<Movie movie={movie} className='bg-background rounded-md' card={slides}>
<div className='gap-2 flex w-full bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60 lg:static max-sm:z-10 max-sm:fixed max-sm:bottom-0 max-sm:left-0 max-sm:w-full max-sm:p-2 max-sm:px-2 max-sm:mb-0'>
<Button className='grow h-8' onClick={previous} disabled={!hasPrevious} title='Previous movie'>
<ArrowLeft size={24} />
</Button>
<Button className='grow h-8' onClick={next} title='Next movie'>
<ArrowRight size={24} />
</Button>
</div>
</Movie>
<Measurer>
{(width) => (
<Preview
movie={movie}
className='bg-background rounded-md'
card={<Carousel index={initialIndex.current} width={width} movies={movies} onIndexChange={onIndexChange} />}
/>
)}
</Measurer>
<div className='w-full h-2 max-sm:h-12' />
</>
);
+6 -30
View File
@@ -1,8 +1,7 @@
'use client';
import { useCallback, useEffect, useRef, useState } from 'react';
import { useCallback, useEffect, useState } from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { Swiper } from 'swiper/types';
import useFilters from '@/app/(site)/useFilters';
import { randomMovies } from '@/lib/api';
@@ -16,8 +15,6 @@ const useRandomMovie = () => {
const { filters } = useFilters();
const indexByFilter = previousIndexes[JSON.stringify(filters)];
const [index, setIndex] = useState(indexByFilter);
const ref = useRef<Swiper>();
const timeout = useRef<NodeJS.Timeout>();
const { data: movies, refetch } = useQuery({
queryKey: ['random-movie', filters],
@@ -42,42 +39,21 @@ const useRandomMovie = () => {
setIndex(indexByFilter || 0);
}, [indexByFilter]);
const previous = () => ref.current?.slidePrev();
const next = () => ref.current?.slideNext();
return {
movies,
movie: movies?.[index],
hasPrevious: index > 0,
onIndexChange: useCallback(
({ activeIndex }: Swiper) => {
if ((activeIndex && activeIndex % UPDATE_RATE === 0) || movies!.length < UPDATE_RATE) {
(index: number) => {
if ((index && index % UPDATE_RATE === 0) || movies!.length < UPDATE_RATE) {
refetch();
}
clearTimeout(timeout.current);
previousIndexes[JSON.stringify(filters)] = activeIndex;
timeout.current = setTimeout(() => {
setIndex(activeIndex);
}, 100);
previousIndexes[JSON.stringify(filters)] = index;
setIndex(index);
},
[movies, filters]
),
onDrag: useCallback(
({ activeIndex }: Swiper) => {
clearTimeout(timeout.current);
timeout.current = setTimeout(() => {
if (index === activeIndex) return;
setIndex(activeIndex);
}, 100);
},
[index]
),
next,
previous,
index,
ref
index
};
};
+6 -1
View File
@@ -27,10 +27,15 @@ export default function RootLayout({ children }: { children: ReactNode }) {
<html lang='en' className={theme}>
<head>
<meta name='theme-color' content='black' />
<link rel='preconnect' href='https://fonts.googleapis.com' />
<link rel='preconnect' href='https://fonts.gstatic.com' crossOrigin='' />
<link href='https://fonts.googleapis.com/css2?family=Moderustic&family=Poppins&display=swap' rel='stylesheet' />
</head>
<body>
<Providers theme={theme}>
<Header />
<div className='sticky top-0 z-20'>
<Header />
</div>
<main className='px-2 max-w-[1252px] mx-auto'>{children}</main>
</Providers>
</body>