feat: virtual list of credits

This commit is contained in:
ner committed 2024-10-20 13:54:05 +03:00
1 parent dc8dde4dbb
commit 29b22f88ae
7 files changed
+145 -78

No files matched your search

+2 -4
View File
@@ -153,9 +153,7 @@ export const popularMovies = async ({ page }: { page?: string } = {}): Promise<P
sort_by: 'popularity.desc', sort_by: 'popularity.desc',
'vote_count.gte': 300, 'vote_count.gte': 300,
'vote_average.lte': 10, 'vote_average.lte': 10,
'vote_average.gte': 0, 'vote_average.gte': 5
'with_runtime.gte': 0,
'with_runtime.lte': 400
} }
}) })
.then(mapMoviesSeriesResponseToShows); .then(mapMoviesSeriesResponseToShows);
@@ -187,7 +185,7 @@ export const topMovies = async ({ page, starring }: { page?: string; starring?:
sort_by: 'vote_average.desc', sort_by: 'vote_average.desc',
'vote_count.gte': 300, 'vote_count.gte': 300,
'vote_average.lte': 10, 'vote_average.lte': 10,
'vote_average.gte': 0 'vote_average.gte': 5
} }
}) })
.then(mapMoviesSeriesResponseToShows); .then(mapMoviesSeriesResponseToShows);
+72 -24
View File
@@ -1,40 +1,60 @@
'use client'; 'use client';
import { FC } from 'react'; import { FC, ForwardedRef, forwardRef, useMemo } from 'react';
import { User2 } from 'lucide-react'; import { Virtuoso, VirtuosoProps } from 'react-virtuoso';
import Image from 'next/image';
import Link from 'next/link'; import Link from 'next/link';
import ScrollNavigation from '@/components/ScrollNavigation'; import ScrollNavigation from '@/components/ScrollNavigation';
import { cn } from '@/lib/utils';
import useCredits from './useCredits'; import useCredits from './useCredits';
interface Props { interface Context {
showId: Show['id']; onClick?: (id: string) => void;
showType?: Show['type']; width?: number;
onPersonClick?: (id: string) => void; height?: number;
gap?: number;
} }
const Credits: FC<Props> = ({ showId, showType = 'movie', onPersonClick }) => { interface Props extends Context {
showId: Show['id'];
showType?: Show['type'];
}
const Credits: FC<Props> = ({ showId, showType = 'movie', onClick, width = 120, height = 180, gap = 8 }) => {
const { data: credits } = useCredits({ showId, showType }); const { data: credits } = useCredits({ showId, showType });
const context = useMemo(() => ({ width, height, gap, onClick }), [width, height, gap, onClick]);
if (!credits?.length) return null;
return ( return (
Boolean(credits?.length) && ( <Virtuoso
<ScrollNavigation<HTMLUListElement>> style={{ height }}
{(setRef) => ( horizontalDirection
<ul initialItemCount={10}
ref={setRef} increaseViewportBy={width * 10}
className='no-scrollbar flex animate-fade-aside-slide-in snap-x snap-mandatory gap-2 overflow-auto rounded-lg opacity-0' data={credits}
> context={context}
{credits?.map((actor) => ( components={components}
<li />
key={`${actor.id}_${actor.cast_id}`} );
};
const components: VirtuosoProps<Actor, Context>['components'] = {
Item: ({ item: actor, children, context, ...props }) => {
if (!actor) return null;
return (
<div
{...props}
title={actor.name} title={actor.name}
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' style={{ width: context?.width, height: context?.height }}
className='relative shrink-0 cursor-pointer snap-start self-end bg-card text-card-foreground transition-shadow hover:shadow-lg'
> >
<Link <Link
href={`/starring?actorId=${actor.id}&title=${encodeURIComponent(actor.name)}`} href={`/starring?actorId=${actor.id}&title=${encodeURIComponent(actor.name)}`}
onClick={() => onPersonClick?.(actor.id.toString())} onClick={() => context?.onClick?.(actor.id.toString())}
> >
<div className='overflow-hidden rounded-lg'> <div className='overflow-hidden rounded-lg'>
<img height={180} width={120} src={actor.photoUrl} alt={actor.name} /> <img height={180} width={120} src={actor.photoUrl} alt={actor.name} />
@@ -44,13 +64,41 @@ const Credits: FC<Props> = ({ showId, showType = 'movie', onPersonClick }) => {
{Boolean(actor.character) && <p className='truncate'>{actor.character}</p>} {Boolean(actor.character) && <p className='truncate'>{actor.character}</p>}
</div> </div>
</Link> </Link>
</li> </div>
))} );
</ul> },
List: forwardRef(function List({ context, ...props }, ref) {
return <div {...props} ref={ref} style={{ ...props.style, display: 'flex', gap: context?.gap }} />;
}),
Scroller: forwardRef(function Scroller({ context, ...props }, ref) {
const slideWidth = (context?.width || 0) + (context?.gap || 0);
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 (
<div className='animate-fade-aside-slide-in opacity-0'>
<ScrollNavigation<HTMLDivElement> slideWidth={slideWidth}>
{({ setScrollElement, isArrowHovered }) => (
<div
{...props}
ref={handleRef(ref, setScrollElement)}
className={cn('no-scrollbar h-full overflow-hidden rounded-lg', {
'snap-x snap-mandatory': !isArrowHovered
})}
/>
)} )}
</ScrollNavigation> </ScrollNavigation>
) </div>
); );
})
}; };
export default Credits; export default Credits;
@@ -2,7 +2,6 @@ import { useState } from 'react';
import { create, InstanceProps } from 'react-modal-promise'; import { create, InstanceProps } from 'react-modal-promise';
import { Loader } from 'lucide-react'; import { Loader } from 'lucide-react';
import dynamic from 'next/dynamic'; import dynamic from 'next/dynamic';
import Image from 'next/image';
import { Modal } from '@/components/ui/dialog'; import { Modal } from '@/components/ui/dialog';
import { useToast } from '@/hooks/useToast'; import { useToast } from '@/hooks/useToast';
@@ -48,7 +47,7 @@ const showPlayer = create(({ onResolve, magnet, backdrop, title }: Props) => {
{(!isReady || isLoading) && ( {(!isReady || isLoading) && (
<div className='absolute left-0 top-0 size-full'> <div className='absolute left-0 top-0 size-full'>
<img src={backdrop} className='absolute left-0 top-0 size-full' alt={title} /> <img src={backdrop} className='absolute left-0 top-0 size-full' alt={title} />
<div className='absolute left-0 top-0 flex size-full items-center justify-center bg-black/80'> <div className='absolute left-0 top-0 flex size-full items-center justify-center bg-black/60'>
<div className='animate-spin'> <div className='animate-spin'>
<Loader color='white' /> <Loader color='white' />
</div> </div>
+1 -1
View File
@@ -56,7 +56,7 @@ const Preview: FC<Props> = ({ show: baseShow, className, onClose, poster }) => {
{show.overview} {show.overview}
</p> </p>
<div className='order-5 mt-5 grid grid-cols-1 rounded-lg md:order-5 md:mt-auto'> <div className='order-5 mt-5 grid grid-cols-1 rounded-lg md:order-5 md:mt-auto'>
<Credits showType={show.type} showId={show.id} onPersonClick={onClose} /> <Credits showType={show.type} showId={show.id} onClick={onClose} />
</div> </div>
</div> </div>
</div> </div>
+41 -37
View File
@@ -1,14 +1,46 @@
'use client'; 'use client';
import { FC, ForwardedRef, forwardRef, useLayoutEffect, useRef } from 'react'; import { FC, ForwardedRef, forwardRef, useLayoutEffect, useMemo, useRef } from 'react';
import { Virtuoso, VirtuosoProps } from 'react-virtuoso'; import { Virtuoso, VirtuosoProps } from 'react-virtuoso';
import Poster from '@/components/Poster'; import Poster from '@/components/Poster';
import ScrollNavigation from '@/components/ScrollNavigation'; import ScrollNavigation from '@/components/ScrollNavigation';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
const components: VirtuosoProps<Show, (index: number) => void>['components'] = { interface Context {
Item: ({ item, children, context: onIndexChange, ...props }) => { onIndexChange: (index: number) => void;
gap?: number;
}
interface Props extends Context {
index: number;
shows?: Show[];
onEndReached?: () => void;
}
const Carousel: FC<Props> = ({ index, shows, gap = 8, onIndexChange, onEndReached }) => {
const initialIndex = useRef(index);
const context = useMemo(() => ({ onIndexChange, gap }), [onIndexChange, gap]);
return (
<div className='card-aspect-ratio mx-auto'>
<Virtuoso
horizontalDirection
skipAnimationFrameInResizeObserver
data={shows}
context={context}
endReached={onEndReached}
initialTopMostItemIndex={initialIndex.current}
components={components}
increaseViewportBy={1000}
/>
</div>
);
};
const components: VirtuosoProps<Show, Context>['components'] = {
Item: ({ item, children, context, ...props }) => {
const ref = useRef<HTMLDivElement>(null); const ref = useRef<HTMLDivElement>(null);
const index = props['data-index']; const index = props['data-index'];
@@ -22,7 +54,7 @@ const components: VirtuosoProps<Show, (index: number) => void>['components'] = {
entries.forEach((entry) => { entries.forEach((entry) => {
if (!entry.isIntersecting) return; if (!entry.isIntersecting) return;
onIndexChange?.(index); context?.onIndexChange?.(index);
}), }),
{ {
threshold: 0.7 threshold: 0.7
@@ -32,7 +64,7 @@ const components: VirtuosoProps<Show, (index: number) => void>['components'] = {
observer.observe(container); observer.observe(container);
return () => observer.disconnect(); return () => observer.disconnect();
}, [onIndexChange, index]); }, [context, index]);
return ( return (
<div {...props} ref={ref} className='snap-start'> <div {...props} ref={ref} className='snap-start'>
@@ -41,11 +73,9 @@ const components: VirtuosoProps<Show, (index: number) => void>['components'] = {
); );
}, },
List: forwardRef(function List({ context, ...props }, ref) { List: forwardRef(function List({ context, ...props }, ref) {
return <div {...props} ref={ref} style={{ ...props.style, display: 'flex' }} className='gap-2' />; return <div {...props} ref={ref} style={{ ...props.style, display: 'flex', gap: context?.gap }} />;
}), }),
Scroller: forwardRef(function Scroller({ context, ...props }, ref) { Scroller: forwardRef(function Scroller({ context, ...props }, ref) {
const GAP_BETWEEN_SLIDES = 8; // gap-2 = 0.5rem = 8px
const handleRef = const handleRef =
(ref: ForwardedRef<HTMLDivElement>, setRef: (element: HTMLDivElement) => void) => (ref: ForwardedRef<HTMLDivElement>, setRef: (element: HTMLDivElement) => void) =>
(element: HTMLDivElement | null) => { (element: HTMLDivElement | null) => {
@@ -62,12 +92,12 @@ const components: VirtuosoProps<Show, (index: number) => void>['components'] = {
arrowsClassName='h-20 bg-secondary' arrowsClassName='h-20 bg-secondary'
backClassName='rounded-none rounded-r-full' backClassName='rounded-none rounded-r-full'
nextClassName='rounded-none rounded-l-full' nextClassName='rounded-none rounded-l-full'
gap={GAP_BETWEEN_SLIDES} gap={context?.gap}
> >
{(setRef, isArrowHovered) => ( {({ setScrollElement, isArrowHovered }) => (
<div <div
{...props} {...props}
ref={handleRef(ref, setRef)} ref={handleRef(ref, setScrollElement)}
className={cn('no-scrollbar h-full overflow-hidden rounded-lg', { className={cn('no-scrollbar h-full overflow-hidden rounded-lg', {
'snap-x snap-mandatory ': !isArrowHovered 'snap-x snap-mandatory ': !isArrowHovered
})} })}
@@ -78,30 +108,4 @@ const components: VirtuosoProps<Show, (index: number) => void>['components'] = {
}) })
}; };
interface Props {
index: number;
shows?: Show[];
onIndexChange: (index: number) => void;
onEndReached?: () => void;
}
const Carousel: FC<Props> = ({ index, shows, onIndexChange, onEndReached }) => {
const initialIndex = useRef(index);
return (
<div className='card-aspect-ratio mx-auto'>
<Virtuoso
data={shows}
context={onIndexChange}
endReached={onEndReached}
initialTopMostItemIndex={initialIndex.current}
components={components}
horizontalDirection
skipAnimationFrameInResizeObserver
increaseViewportBy={1000}
/>
</div>
);
};
export default Carousel; export default Carousel;
+26 -8
View File
@@ -9,8 +9,15 @@ interface Props<E extends HTMLElement> {
backClassName?: string; backClassName?: string;
nextClassName?: string; nextClassName?: string;
iconClassName?: string; iconClassName?: string;
slideWidth?: number;
gap?: number; gap?: number;
children: (setScrollElement: (element: E) => void, isArrowHovered: boolean) => ReactNode; children: ({
setScrollElement,
isArrowHovered
}: {
setScrollElement: (element: E) => void;
isArrowHovered: boolean;
}) => ReactNode;
} }
function ScrollNavigation<E extends HTMLElement>({ function ScrollNavigation<E extends HTMLElement>({
@@ -19,28 +26,36 @@ function ScrollNavigation<E extends HTMLElement>({
backClassName, backClassName,
nextClassName, nextClassName,
iconClassName, iconClassName,
slideWidth: initialSlideWidth,
gap = 0, gap = 0,
children children
}: Props<E>) { }: Props<E>) {
const [scrollElement, setScrollElement] = useState<E | null>(null); const [scrollElement, setScrollElement] = useState<E | null>(null);
const [isShowBack, setIsShowBack] = useState(true); const [isShowBack, setIsShowBack] = useState(true);
const [isShowNext, setIsShowNext] = useState(true); const [isShowNext, setIsShowNext] = useState(true);
const [childWidth, setChildWidth] = useState(0);
const [isArrowHovered, setIsArrowHovered] = useState(false); const [isArrowHovered, setIsArrowHovered] = useState(false);
const [childWidth, setChildWidth] = useState(0);
const slideWidth = initialSlideWidth ?? childWidth + gap;
useEffect(() => { useEffect(() => {
if (!scrollElement) return; if (!scrollElement) return;
let timeout: NodeJS.Timeout; let timeout: NodeJS.Timeout;
if (scrollElement.firstChild) { const slide = scrollElement.firstChild as HTMLElement;
setChildWidth((scrollElement.firstChild as HTMLElement).clientWidth + gap);
if (!initialSlideWidth && slide) {
setChildWidth(slide.clientWidth);
} }
const handleScroll = () => { const handleScroll = () => {
clearTimeout(timeout); clearTimeout(timeout);
const DELAY = 100; const DELAY = 50;
timeout = setTimeout(() => { timeout = setTimeout(() => {
setIsShowBack(Boolean(scrollElement.scrollLeft)); setIsShowBack(Boolean(scrollElement.scrollLeft));
@@ -55,17 +70,20 @@ function ScrollNavigation<E extends HTMLElement>({
return () => { return () => {
scrollElement.removeEventListener('scroll', handleScroll); scrollElement.removeEventListener('scroll', handleScroll);
}; };
}, [scrollElement, gap]); }, [scrollElement, initialSlideWidth]);
const handleScrollNext = (direction: 1 | -1) => () => { const handleScrollNext = (direction: 1 | -1) => () => {
if (!scrollElement) return; if (!scrollElement) return;
scrollElement.scrollTo({ left: scrollElement.scrollLeft + childWidth * direction, behavior: 'smooth' }); scrollElement.scrollTo({
left: scrollElement.scrollLeft + slideWidth * direction,
behavior: 'smooth'
});
}; };
return ( return (
<div className={cn('relative group', className)}> <div className={cn('relative group', className)}>
{children(setScrollElement, isArrowHovered)} {children({ setScrollElement, isArrowHovered })}
{[ {[
{ {
Arrow: ChevronLeft, Arrow: ChevronLeft,
@@ -10,9 +10,9 @@ interface Props {
const Gallery: FC<Props> = ({ shows }) => ( const Gallery: FC<Props> = ({ shows }) => (
<ScrollNavigation<HTMLUListElement>> <ScrollNavigation<HTMLUListElement>>
{(setRef) => ( {({ setScrollElement }) => (
<ul <ul
ref={setRef} ref={setScrollElement}
className='no-scrollbar flex animate-fade-aside-slide-in snap-x snap-mandatory gap-2 overflow-auto rounded-lg opacity-0' className='no-scrollbar flex animate-fade-aside-slide-in snap-x snap-mandatory gap-2 overflow-auto rounded-lg opacity-0'
> >
{shows.map((show) => ( {shows.map((show) => (