feat: scroll navigation

This commit is contained in:
ner committed 2024-10-10 15:55:25 +03:00
1 parent eaaf46082c
commit 058ecd452f
7 files changed
+238 -132

No files matched your search

+27 -25
View File
@@ -1,8 +1,9 @@
'use client'; 'use client';
import { FC, forwardRef, useEffect, useLayoutEffect, useRef } from 'react'; import { FC, ForwardedRef, forwardRef, useLayoutEffect, useRef } from 'react';
import { Virtuoso, VirtuosoHandle, VirtuosoProps } from 'react-virtuoso'; import { Virtuoso, VirtuosoProps } from 'react-virtuoso';
import ScrollNavigation from '@/components/ScrollNavigation';
import Card from '@/components/Show'; import Card from '@/components/Show';
const components: VirtuosoProps<Show, (index: number) => void>['components'] = { const components: VirtuosoProps<Show, (index: number) => void>['components'] = {
@@ -42,8 +43,31 @@ const components: VirtuosoProps<Show, (index: number) => void>['components'] = {
return <div {...props} ref={ref} style={{ ...props.style, display: 'flex' }} className='gap-2' />; return <div {...props} ref={ref} style={{ ...props.style, display: 'flex' }} className='gap-2' />;
}), }),
Scroller: forwardRef(function Scroller({ context, ...props }, ref) { Scroller: forwardRef(function Scroller({ context, ...props }, ref) {
const handleRef =
(ref: ForwardedRef<HTMLDivElement>, setRef: (element: HTMLDivElement) => void) =>
(element: HTMLDivElement | null) => {
if (!element || !ref) return;
setRef(element);
typeof ref === 'function' ? ref(element) : (ref.current = element);
};
return ( return (
<div {...props} ref={ref} className='no-scrollbar h-full snap-x snap-mandatory overflow-hidden rounded-lg' /> <ScrollNavigation<HTMLDivElement>
className='size-full'
arrowsClassName='h-20 bg-secondary'
backClassName='rounded-none rounded-r-full'
nextClassName='rounded-none rounded-l-full'
>
{(setRef) => (
<div
{...props}
ref={handleRef(ref, setRef)}
className='no-scrollbar h-full snap-x snap-mandatory overflow-hidden rounded-lg'
/>
)}
</ScrollNavigation>
); );
}) })
}; };
@@ -56,33 +80,11 @@ interface Props {
} }
const Carousel: FC<Props> = ({ index, shows, onIndexChange, onEndReached }) => { const Carousel: FC<Props> = ({ index, shows, onIndexChange, onEndReached }) => {
const ref = useRef<VirtuosoHandle>(null);
const initialIndex = useRef(index); const initialIndex = useRef(index);
useEffect(() => {
const scrollTo = ({ key }: globalThis.KeyboardEvent) => {
if (key === 'ArrowLeft') {
if (index <= 0) return;
ref.current?.scrollIntoView({ index: index - 1, behavior: 'smooth' });
}
if (key === 'ArrowRight') {
if (index >= (shows?.length || 0) - 1) return;
ref.current?.scrollIntoView({ index: index + 1, behavior: 'smooth' });
}
};
document.addEventListener('keydown', scrollTo);
return () => {
document.removeEventListener('keydown', scrollTo);
};
}, [index, shows?.length]);
return ( return (
<div className='card-aspect-ratio mx-auto'> <div className='card-aspect-ratio mx-auto'>
<Virtuoso <Virtuoso
ref={ref}
data={shows} data={shows}
context={onIndexChange} context={onIndexChange}
endReached={onEndReached} endReached={onEndReached}
+106
View File
@@ -0,0 +1,106 @@
import { ReactNode, useEffect, useState } from 'react';
import { ChevronLeft, ChevronRight } from 'lucide-react';
import { cn } from '@/lib/utils';
interface Props<E extends HTMLElement> {
className?: string;
arrowsClassName?: string;
backClassName?: string;
nextClassName?: string;
iconClassName?: string;
children: (setScrollElement: (element: E) => void) => ReactNode;
}
function ScrollNavigation<E extends HTMLElement>({
className,
arrowsClassName,
backClassName,
nextClassName,
iconClassName,
children
}: Props<E>) {
const [scrollElement, setScrollElement] = useState<E | null>(null);
const [isShowBack, setIsShowBack] = useState(true);
const [isShowNext, setIsShowNext] = useState(true);
const [childWidth, setChildWidth] = useState(0);
useEffect(() => {
if (!scrollElement) return;
let timeout: NodeJS.Timeout;
if (scrollElement.firstChild) {
setChildWidth((scrollElement.firstChild as HTMLElement).clientWidth);
}
const handleScroll = () => {
clearTimeout(timeout);
const DELAY = 100;
timeout = setTimeout(() => {
setIsShowBack(Boolean(scrollElement.scrollLeft));
setIsShowNext(Boolean(scrollElement.scrollWidth - (scrollElement.clientWidth + scrollElement.scrollLeft)));
}, DELAY);
};
handleScroll();
scrollElement.addEventListener('scroll', handleScroll);
return () => {
scrollElement.removeEventListener('scroll', handleScroll);
};
}, [scrollElement]);
const handleScrollNext = (direction: 1 | -1) => () => {
if (!scrollElement) return;
scrollElement.scrollTo({ left: scrollElement.scrollLeft + childWidth * direction, behavior: 'smooth' });
};
return (
<div className={cn('relative group', className)}>
{children(setScrollElement)}
{[
{
Arrow: ChevronLeft,
isShow: isShowBack,
handleScroll: handleScrollNext(-1),
className: cn(
'left-0 bg-gradient-to-r from-background to-transparent justify-start rounded-l-md',
backClassName
)
},
{
Arrow: ChevronRight,
isShow: isShowNext,
handleScroll: handleScrollNext(1),
className: cn(
'right-0 bg-gradient-to-r from-transparent to-background justify-end rounded-r-md',
nextClassName
)
}
].map(({ Arrow, isShow, handleScroll, className }) => (
<div
key={className}
onClick={handleScroll}
className={cn(
'opacity-0 transition-opacity absolute top-1/2 transform -translate-y-1/2 bg-gradient-to-r h-full w-14 flex items-center cursor-pointer',
{
'group-hover:opacity-100 hover:!opacity-60': isShow,
'pointer-events-none': !isShow
},
className,
arrowsClassName
)}
>
<Arrow className={cn('text-primary', iconClassName)} size={30} />
</div>
))}
</div>
);
}
export default ScrollNavigation;
+41 -34
View File
@@ -5,6 +5,8 @@ import { User2 } from 'lucide-react';
import Image from 'next/image'; import Image from 'next/image';
import Link from 'next/link'; import Link from 'next/link';
import ScrollNavigation from '@/components/ScrollNavigation';
import useCredits from './useCredits'; import useCredits from './useCredits';
interface Props { interface Props {
@@ -18,42 +20,47 @@ const Credits: FC<Props> = ({ showId, showType = 'movie', onPersonClick }) => {
return ( return (
Boolean(credits?.length) && ( Boolean(credits?.length) && (
<ul className='no-scrollbar flex animate-fade-aside-slide-in snap-x snap-mandatory gap-2 overflow-auto rounded-lg opacity-0'> <ScrollNavigation<HTMLUListElement>>
{credits?.map((actor) => ( {(setRef) => (
<li <ul
key={`${actor.id}_${actor.cast_id}`} ref={setRef}
title={actor.name} className='no-scrollbar flex animate-fade-aside-slide-in snap-x snap-mandatory gap-2 overflow-auto rounded-lg opacity-0'
className='relative w-full max-w-[120px] shrink-0 cursor-pointer snap-start self-end bg-card text-card-foreground transition-shadow hover:shadow-lg'
> >
<Link {credits?.map((actor) => (
href={`/starring?actorId=${actor.id}&title=${encodeURIComponent(actor.name)}`} <li
onClick={() => onPersonClick?.(actor.id.toString())} key={`${actor.id}_${actor.cast_id}`}
> title={actor.name}
<div className='overflow-hidden rounded-lg'> className='relative w-full max-w-[120px] shrink-0 cursor-pointer snap-start self-end bg-card text-card-foreground transition-shadow hover:shadow-lg'
{actor.profile_path ? ( >
<Image <Link
unoptimized href={`/starring?actorId=${actor.id}&title=${encodeURIComponent(actor.name)}`}
height={180} onClick={() => onPersonClick?.(actor.id.toString())}
width={120} >
src={`https://image.tmdb.org/t/p/w500/${actor.profile_path}`} <div className='overflow-hidden rounded-lg'>
alt={actor.name} {actor.profile_path ? (
/> <Image
) : ( unoptimized
<div className='flex h-[180px] w-[120px] items-center justify-center rounded-lg'> height={180}
<User2 size={120} strokeWidth={1} /> width={120}
src={`https://image.tmdb.org/t/p/w500/${actor.profile_path}`}
alt={actor.name}
/>
) : (
<div className='flex h-[180px] w-[120px] items-center justify-center rounded-lg'>
<User2 size={120} strokeWidth={1} />
</div>
)}
</div> </div>
)} <div className='absolute left-0 top-0 flex size-full flex-col justify-between rounded-md bg-vignette p-2 py-1 text-sm text-white'>
</div> <p className=' truncate'>{actor.name}</p>
<div className='absolute left-0 top-0 flex size-full flex-col justify-between rounded-md bg-vignette p-2 py-1 text-sm text-white'> {Boolean(actor.character) && <p className='truncate'>{actor.character}</p>}
<p className=' truncate'>{actor.name}</p> </div>
{Boolean(actor.character) && ( </Link>
<p className='truncate'>{actor.character}</p> </li>
)} ))}
</div> </ul>
</Link> )}
</li> </ScrollNavigation>
))}
</ul>
) )
); );
}; };
@@ -0,0 +1,28 @@
import { FC } from 'react';
import { showPreviewModal } from '@/components/Preview';
import ScrollNavigation from '@/components/ScrollNavigation';
import Card from '@/components/Show';
interface Props {
shows: Show[];
}
const Gallery: FC<Props> = ({ shows }) => (
<ScrollNavigation<HTMLUListElement>>
{(setRef) => (
<ul
ref={setRef}
className='no-scrollbar flex animate-fade-aside-slide-in snap-x snap-mandatory gap-2 overflow-auto rounded-lg opacity-0'
>
{shows.map((show) => (
<li key={show.id} className='snap-start'>
<Card className='!h-[350px] !w-[230px] text-sm' show={show} onClick={() => showPreviewModal({ show })} />
</li>
))}
</ul>
)}
</ScrollNavigation>
);
export default Gallery;
@@ -1,20 +0,0 @@
import { FC } from 'react';
import { showPreviewModal } from '@/components/Preview';
import Card from '@/components/Show';
interface Props {
shows: Show[];
}
const Marquee: FC<Props> = ({ shows }) => (
<ul className='no-scrollbar flex animate-fade-aside-slide-in snap-x snap-mandatory gap-2 overflow-auto rounded-lg opacity-0'>
{shows.map((show) => (
<li key={show.id} className='snap-start'>
<Card className='!h-[350px] !w-[230px] text-sm' show={show} onClick={() => showPreviewModal({ show })} />
</li>
))}
</ul>
);
export default Marquee;
+2 -2
View File
@@ -4,7 +4,7 @@ import { FC, useState } from 'react';
import Nav from '@/components/ui/nav'; import Nav from '@/components/ui/nav';
import Marquee from './components/Marquee'; import Gallery from './components/Gallery';
import { tabs } from './constants'; import { tabs } from './constants';
import useTrending from './useTrending'; import useTrending from './useTrending';
@@ -22,7 +22,7 @@ const Trending: FC = () => {
isFetched && ( isFetched && (
<div> <div>
<Nav tabs={tabs} active={active} onChange={(active) => setActive(active)} className='mb-3' /> <Nav tabs={tabs} active={active} onChange={(active) => setActive(active)} className='mb-3' />
<Marquee key={active.type} shows={shows} /> <Gallery key={active.type} shows={shows} />
</div> </div>
) )
); );
+34 -51
View File
@@ -1,13 +1,13 @@
'use client' 'use client';
import * as React from 'react' import * as React from 'react';
import * as ToastPrimitives from '@radix-ui/react-toast' import * as ToastPrimitives from '@radix-ui/react-toast';
import { cva, type VariantProps } from 'class-variance-authority' import { cva, type VariantProps } from 'class-variance-authority';
import { X } from 'lucide-react' import { X } from 'lucide-react';
import { cn } from '@/lib/utils' import { cn } from '@/lib/utils';
const ToastProvider = ToastPrimitives.Provider const ToastProvider = ToastPrimitives.Provider;
const ToastViewport = React.forwardRef< const ToastViewport = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Viewport>, React.ElementRef<typeof ToastPrimitives.Viewport>,
@@ -21,39 +21,30 @@ const ToastViewport = React.forwardRef<
)} )}
{...props} {...props}
/> />
)) ));
ToastViewport.displayName = ToastPrimitives.Viewport.displayName ToastViewport.displayName = ToastPrimitives.Viewport.displayName;
const toastVariants = cva( const toastVariants = cva(
'group pointer-events-auto relative flex w-full items-center justify-between space-x-4 overflow-hidden rounded-md border p-6 pr-8 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full', 'group pointer-events-auto relative flex w-full items-center justify-between space-x-4 overflow-hidden rounded-md border p-6 pr-8 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full',
{ {
variants: { variants: {
variant: { variant: {
default: 'border bg-background text-foreground', default: 'border bg-background text-foreground'
destructive: }
'destructive group border-destructive bg-destructive text-destructive-foreground',
},
}, },
defaultVariants: { defaultVariants: {
variant: 'default', variant: 'default'
}, }
} }
) );
const Toast = React.forwardRef< const Toast = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Root>, React.ElementRef<typeof ToastPrimitives.Root>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Root> & React.ComponentPropsWithoutRef<typeof ToastPrimitives.Root> & VariantProps<typeof toastVariants>
VariantProps<typeof toastVariants>
>(({ className, variant, ...props }, ref) => { >(({ className, variant, ...props }, ref) => {
return ( return <ToastPrimitives.Root ref={ref} className={cn(toastVariants({ variant }), className)} {...props} />;
<ToastPrimitives.Root });
ref={ref} Toast.displayName = ToastPrimitives.Root.displayName;
className={cn(toastVariants({ variant }), className)}
{...props}
/>
)
})
Toast.displayName = ToastPrimitives.Root.displayName
const ToastAction = React.forwardRef< const ToastAction = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Action>, React.ElementRef<typeof ToastPrimitives.Action>,
@@ -67,8 +58,8 @@ const ToastAction = React.forwardRef<
)} )}
{...props} {...props}
/> />
)) ));
ToastAction.displayName = ToastPrimitives.Action.displayName ToastAction.displayName = ToastPrimitives.Action.displayName;
const ToastClose = React.forwardRef< const ToastClose = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Close>, React.ElementRef<typeof ToastPrimitives.Close>,
@@ -80,41 +71,33 @@ const ToastClose = React.forwardRef<
'absolute right-2 top-2 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-2 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600', 'absolute right-2 top-2 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-2 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600',
className className
)} )}
toast-close="" toast-close=''
{...props} {...props}
> >
<X className="size-4" /> <X className='size-4' />
</ToastPrimitives.Close> </ToastPrimitives.Close>
)) ));
ToastClose.displayName = ToastPrimitives.Close.displayName ToastClose.displayName = ToastPrimitives.Close.displayName;
const ToastTitle = React.forwardRef< const ToastTitle = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Title>, React.ElementRef<typeof ToastPrimitives.Title>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Title> React.ComponentPropsWithoutRef<typeof ToastPrimitives.Title>
>(({ className, ...props }, ref) => ( >(({ className, ...props }, ref) => (
<ToastPrimitives.Title <ToastPrimitives.Title ref={ref} className={cn('text-sm font-semibold', className)} {...props} />
ref={ref} ));
className={cn('text-sm font-semibold', className)} ToastTitle.displayName = ToastPrimitives.Title.displayName;
{...props}
/>
))
ToastTitle.displayName = ToastPrimitives.Title.displayName
const ToastDescription = React.forwardRef< const ToastDescription = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Description>, React.ElementRef<typeof ToastPrimitives.Description>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Description> React.ComponentPropsWithoutRef<typeof ToastPrimitives.Description>
>(({ className, ...props }, ref) => ( >(({ className, ...props }, ref) => (
<ToastPrimitives.Description <ToastPrimitives.Description ref={ref} className={cn('text-sm opacity-90', className)} {...props} />
ref={ref} ));
className={cn('text-sm opacity-90', className)} ToastDescription.displayName = ToastPrimitives.Description.displayName;
{...props}
/>
))
ToastDescription.displayName = ToastPrimitives.Description.displayName
type ToastProps = React.ComponentPropsWithoutRef<typeof Toast> type ToastProps = React.ComponentPropsWithoutRef<typeof Toast>;
type ToastActionElement = React.ReactElement<typeof ToastAction> type ToastActionElement = React.ReactElement<typeof ToastAction>;
export { export {
Toast, Toast,
@@ -125,5 +108,5 @@ export {
type ToastProps, type ToastProps,
ToastProvider, ToastProvider,
ToastTitle, ToastTitle,
ToastViewport, ToastViewport
} };