feat: new nav

This commit is contained in:
ner committed 2024-08-29 12:58:49 +03:00
1 parent 5733bc0af0
commit 750d5b12c8
25 files changed
+377 -316

No files matched your search

+80
View File
@@ -0,0 +1,80 @@
'use client';
import { forwardRef, ReactNode, startTransition, useEffect, useRef, useState } from 'react';
import { StateSnapshot, Virtuoso, VirtuosoHandle, VirtuosoProps } from 'react-virtuoso';
import Card from '@/components/Movie/Card';
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' />;
})
};
export 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)}
</>
);
};
let snapshot: StateSnapshot;
export const Carousel = ({
movies,
width: initialWidth,
onIndexChange
}: {
movies?: Movie[];
width: number;
onIndexChange: (index: number) => void;
}) => {
const timeout = useRef<NodeJS.Timeout>();
const isMobile = matchMedia('(max-width: 500px)').matches;
const ref = useRef<VirtuosoHandle>(null);
const width = isMobile ? initialWidth : 300;
const height = isMobile ? (width * 3) / 2 : 450;
useEffect(() => {
const virtuoso = ref.current;
return () => virtuoso?.getState((state) => (snapshot = state));
}, []);
return (
<Virtuoso
ref={ref}
data={movies}
defaultItemHeight={height}
style={{ width, height, flexShrink: 0, margin: '0 auto' }}
totalCount={movies?.length}
horizontalDirection
context={width}
increaseViewportBy={154}
restoreStateFrom={snapshot}
components={components}
itemContent={(index) => {
clearTimeout(timeout.current);
timeout.current = setTimeout(() => {
const currentIndex = index - 1;
startTransition(() => onIndexChange(currentIndex));
}, 50);
return <Card className='snap-start' movie={movies?.[index]} />;
}}
/>
);
};
+85
View File
@@ -0,0 +1,85 @@
'use client';
import { Dispatch, SetStateAction, useRef, useState } from 'react';
import useFilters from '@/app/(site)/useFilters';
import { Card } from '@/components/ui/card';
import { Slider } from '@/components/ui/slider';
import { Toggle } from '@/components/ui/toggle';
import useUrlToMagnet from '@/hooks/useUrlToMagnet';
import useGenres from './useGenres';
export default function Filter() {
useUrlToMagnet();
const { filters, setFilters } = useFilters();
const { data: genres, isFetched } = useGenres();
const [years, setYears] = useState(filters.year || ['1990', new Date().getFullYear().toString()]);
const [scores, setScores] = useState(filters.score || ['0', '10']);
const timeout = useRef<NodeJS.Timeout>();
const handleChangeGenre = (id: number) => () => {
const genreId = id.toString();
setFilters({
name: 'genres',
value: filters.genres?.includes(genreId)
? filters.genres.filter((id) => id !== genreId)
: [...(filters.genres || []), genreId]
});
};
const handleDebouncedChange =
(setter: Dispatch<SetStateAction<Array<string>>>, key: keyof Filters) => (value: Array<number>) => {
clearTimeout(timeout.current);
timeout.current = setTimeout(() => setFilters({ name: key, value: value.map((value) => value.toString()) }), 300);
setter(value.map((value) => value.toString()));
};
if (!isFetched) return;
return (
<>
<Card className='mb-2'>
<ul className='flex gap-2 overflow-auto no-scrollbar'>
{genres?.map((genre) => (
<li key={genre.id}>
<Toggle
data-state={filters.genres?.includes(genre.id.toString()) ? 'on' : 'off'}
onClick={handleChangeGenre(genre.id)}
className='whitespace-nowrap'
>
{genre.name}
</Toggle>
</li>
))}
</ul>
</Card>
<div className='flex w-full my-4 gap-6 flex-wrap'>
<div className='grow flex items-center basis-[250px]'>
<Slider
onValueChange={handleDebouncedChange(setYears, 'year')}
value={years.map((value) => parseInt(value))}
min={1960}
max={new Date().getFullYear()}
step={1}
/>
</div>
<div className='grow flex items-center basis-[250px]'>
<Slider
onValueChange={handleDebouncedChange(setScores, 'score')}
value={scores.map((value) => parseInt(value))}
min={0}
max={10}
step={1}
/>
</div>
</div>
</>
);
}
+30 -67
View File
@@ -1,82 +1,45 @@
'use client';
import { Dispatch, SetStateAction, useRef, useState } from 'react';
import { useEffect } from 'react';
import { createPortal } from 'react-dom';
import { useAtom } from 'jotai';
import { atomWithStorage } from 'jotai/utils';
import { SlidersHorizontal } from 'lucide-react';
import useFilters from '@/app/(site)/useFilters';
import { Card } from '@/components/ui/card';
import { Slider } from '@/components/ui/slider';
import { Toggle } from '@/components/ui/toggle';
import { Button } from '@/components/ui/button';
import useMounted from '@/hooks/useMounted';
import { genres } from '@/lib/api';
import getQueryClient from '@/lib/queryClient';
import useGenres from './useGenres';
import Filter from './Filter';
export default function Filter() {
const { filters, setFilters } = useFilters();
const { data: genres, isFetched } = useGenres();
const isShowFilterAtom = atomWithStorage('is-show-filters', false);
const [years, setYears] = useState(filters.year || ['1990', new Date().getFullYear().toString()]);
const [scores, setScores] = useState(filters.score || ['0', '10']);
export default function FilterToggle() {
const [isShowFilter, setIsShowFilter] = useAtom(isShowFilterAtom);
const isMounted = useMounted();
const timeout = useRef<NodeJS.Timeout>();
useEffect(() => {
const queryClient = getQueryClient();
const handleChangeGenre = (id: number) => () => {
const genreId = id.toString();
setFilters({
name: 'genres',
value: filters.genres?.includes(genreId)
? filters.genres.filter((id) => id !== genreId)
: [...(filters.genres || []), genreId]
});
};
const handleDebouncedChange =
(setter: Dispatch<SetStateAction<Array<string>>>, key: keyof Filters) => (value: Array<number>) => {
clearTimeout(timeout.current);
timeout.current = setTimeout(() => setFilters({ name: key, value: value.map((value) => value.toString()) }), 300);
setter(value.map((value) => value.toString()));
};
if (!isFetched) return;
queryClient.prefetchQuery({ queryKey: ['genres'], queryFn: () => genres() });
}, []);
return (
<>
<Card className='mb-2'>
<ul className='flex gap-2 overflow-auto no-scrollbar'>
{genres?.map((genre) => (
<li key={genre.id}>
<Toggle
data-state={filters.genres?.includes(genre.id.toString()) ? 'on' : 'off'}
onClick={handleChangeGenre(genre.id)}
className='whitespace-nowrap'
{isShowFilter && <Filter />}
{isMounted &&
createPortal(
<Button
className='p-2'
onClick={() => setIsShowFilter((isShow) => !isShow)}
title={isShowFilter ? 'Hide filters' : 'Show filters'}
variant='ghost'
>
{genre.name}
</Toggle>
</li>
))}
</ul>
</Card>
<div className='flex w-full my-4 gap-6 flex-wrap'>
<div className='grow flex items-center basis-[250px]'>
<Slider
onValueChange={handleDebouncedChange(setYears, 'year')}
value={years.map((value) => parseInt(value))}
min={1960}
max={new Date().getFullYear()}
step={1}
/>
</div>
<div className='grow flex items-center basis-[250px]'>
<Slider
onValueChange={handleDebouncedChange(setScores, 'score')}
value={scores.map((value) => parseInt(value))}
min={0}
max={10}
step={1}
/>
</div>
</div>
<SlidersHorizontal size={19} />
</Button>,
document.getElementById('actions')!
)}
</>
);
}
+4 -120
View File
@@ -1,139 +1,23 @@
'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 { Carousel, Measurer } from './components/Carousel';
import Filter from './components/Filter';
import useRandomMovie from './useRandomMovie';
const isShowFilterAtom = atomWithStorage('is-show-filters', false);
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 { movies, movie, index, onIndexChange } = useRandomMovie();
const isMounted = useMounted();
const initialIndex = useRef(index);
useUrlToMagnet();
useEffect(() => {
const queryClient = getQueryClient();
queryClient.prefetchQuery({ queryKey: ['genres'], queryFn: () => genres() });
}, []);
const { movies, movie, onIndexChange } = useRandomMovie();
return (
<>
{isShowFilter && <Filter />}
{isMounted &&
createPortal(
<Button
className='p-2'
onClick={() => setIsShowFilter((isShow) => !isShow)}
title={isShowFilter ? 'Hide filters' : 'Show filters'}
variant='ghost'
>
<SlidersHorizontal size={19} />
</Button>,
document.getElementById('actions')!
)}
<Filter />
<Measurer>
{(width) => (
<Preview
movie={movie}
className='bg-background rounded-md'
card={<Carousel index={initialIndex.current} width={width} movies={movies} onIndexChange={onIndexChange} />}
card={<Carousel width={width} movies={movies} onIndexChange={onIndexChange} />}
/>
)}
</Measurer>
+7
View File
@@ -6,5 +6,12 @@ import List from '@/components/Movie/List';
export default function Container() {
const { pages } = useFavorites();
if (!pages[0]?.results?.length)
return (
<div className='h-40 w-full flex items-center justify-center text-xl text-muted-foreground'>
There are no items in your favorites list
</div>
);
return <List pages={pages} />;
}
+8
View File
@@ -1,5 +1,13 @@
import { Metadata } from 'next';
import Container from './container';
export const metadata: Metadata = {
title: 'My Favorite Shows - Movie Advisor',
description:
'View your favorite shows on Movie Advisor. Keep track of films you’ve added and revisit your top picks anytime.'
};
export default function Favorites() {
return <Container />;
}
+11
View File
@@ -43,4 +43,15 @@ export const useFavoritesMutation = () => {
};
};
export const useFavoriteToggle = (movie: Movie) => {
const { add, remove } = useFavoritesMutation();
const { map } = useFavorites();
const isFavorite = map.has(movie.id);
const toggle = () => (isFavorite ? remove(movie.id) : add(movie));
return { isFavorite, toggle };
};
export default useFavorites;
+1 -1
View File
@@ -1,6 +1,6 @@
import { dehydrate, HydrationBoundary } from '@tanstack/react-query';
import { randomMovies } from '@/lib/api';
import { randomMovies, trendingMovies } from '@/lib/api';
import getQueryClient from '@/lib/queryClient';
import Container from './container';
+7
View File
@@ -1,10 +1,17 @@
import { dehydrate, HydrationBoundary } from '@tanstack/react-query';
import { Metadata } from 'next';
import { popularMovies } from '@/lib/api';
import getQueryClient from '@/lib/queryClient';
import Container from './container';
export const metadata: Metadata = {
title: 'Popular Movies | Movie Advisor',
description:
'Check out the most popular movies right now on Movie Advisor. See what’s trending and don’t miss out on the latest hits.'
};
export default async function Popular() {
const queryClient = getQueryClient();
+7
View File
@@ -1,10 +1,17 @@
import { dehydrate, HydrationBoundary } from '@tanstack/react-query';
import { Metadata } from 'next';
import { topMovies } from '@/lib/api';
import getQueryClient from '@/lib/queryClient';
import Container from './container';
export const metadata: Metadata = {
title: 'Top Rated Movies | Movie Advisor',
description:
'Discover the top-rated movies on Movie Advisor. Find the highest-rated films and make informed viewing choices.'
};
export default async function Top() {
const queryClient = getQueryClient();
+2 -2
View File
@@ -1,6 +1,6 @@
'use client';
import { useCallback, useEffect, useState } from 'react';
import { startTransition, useCallback, useEffect, useState } from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import useFilters from '@/app/(site)/useFilters';
@@ -49,7 +49,7 @@ const useRandomMovie = () => {
refetch();
}
previousIndexes[JSON.stringify(filters)] = index;
setIndex(index);
startTransition(() => setIndex(index));
},
[movies, filters]
),
+4 -3
View File
@@ -8,8 +8,9 @@ import Providers from '@/providers';
import '@/styles/index.css';
export const metadata: Metadata = {
title: 'Movie advisor',
description: 'It is going to help you find a movie for evening'
title: 'Movie advisor | Discover Your Next Favorite Movie',
description:
'Explore a diverse selection of movies with Movie Advisor. Get random movie recommendations and find out top-rated, popular, and user-favorite films.'
};
export const viewport: Viewport = {
@@ -36,7 +37,7 @@ export default function RootLayout({ children }: { children: ReactNode }) {
<div className='sticky top-0 z-20'>
<Header />
</div>
<main className='px-2 max-w-[1252px] mx-auto'>{children}</main>
<main className='px-2 max-w-[1240px] mx-auto'>{children}</main>
</Providers>
</body>
</html>
@@ -2,7 +2,7 @@
import { Menu } from 'lucide-react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { usePathname, useRouter } from 'next/navigation';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
@@ -41,13 +41,15 @@ export function MobileNavigation() {
<ul className='flex flex-col gap-2 p-2'>
{paths.map(({ path, title }) => (
<li key={path}>
<Link href={path} shallow>
<div>
<DrawerClose asChild>
<Button className='w-full relative' variant={currentPath === path ? 'default' : 'outline'}>
<Link href={path} className='absolute flex items-center justify-center w-full h-full top-0 left-0'>
{title}
</Link>
</Button>
</DrawerClose>
</div>
</Link>
</li>
))}
</ul>
@@ -1,6 +1,6 @@
'use client';
import { ChangeEvent, useRef, useState } from 'react';
import { ChangeEvent, MutableRefObject, useRef, useState } from 'react';
import { create } from 'react-modal-promise';
import { Search as SearchIcon, XCircle } from 'lucide-react';
@@ -16,6 +16,7 @@ import useSearch from './useSearch';
export const showSearchModal = create(({ onResolve }) => {
const [title, setTitle] = useState('');
const [query, setQuery] = useState('');
const scrollRef = useRef<HTMLDivElement>(null) as MutableRefObject<HTMLDivElement>;
const timeout = useRef<NodeJS.Timeout>();
const inputRef = useRef<HTMLInputElement>(null);
@@ -24,6 +25,7 @@ export const showSearchModal = create(({ onResolve }) => {
hasNextPage: hasNextMoviesPage,
fetchNextPage: fetchNextMoviesPage
} = useSearch({ query, type: 'movie' });
const {
data: series,
hasNextPage: hasNextSeriesPage,
@@ -49,7 +51,7 @@ export const showSearchModal = create(({ onResolve }) => {
};
return (
<Modal className='block p-0 max-w-[940px]' onClose={handleClose}>
<Modal className='block p-0 max-w-[932px]' onClose={handleClose} scrollRef={scrollRef}>
<div className='relative p-2'>
<Input
autoFocus
@@ -82,7 +84,7 @@ export const showSearchModal = create(({ onResolve }) => {
<TabsContent value='movies'>
{Boolean(movies?.pages.length && movies?.pages?.[0]?.results?.length) && (
<List
withBottomGap
customScrollParent={scrollRef.current}
pages={movies!.pages as unknown as MovieDBResponse[]}
fetchNextPage={fetchNextMoviesPage}
hasNextPage={hasNextMoviesPage}
@@ -94,7 +96,7 @@ export const showSearchModal = create(({ onResolve }) => {
<TabsContent value='series'>
{Boolean(series?.pages.length && series?.pages?.[0]?.results?.length) && (
<List
withBottomGap
customScrollParent={scrollRef.current}
pages={series!.pages as unknown as MovieDBResponse[]}
fetchNextPage={fetchNextSeriesPage}
hasNextPage={hasNextSeriesPage}
+1 -1
View File
@@ -9,7 +9,7 @@ import ToggleTheme from './components/ThemeToggle';
const Header: FC = () => (
<header className='flex justify-center bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60 py-2'>
<div className='max-w-[1252px] w-full px-2'>
<div className='max-w-[1240px] w-full px-2'>
<div className='flex items-center justify-between gap-2 xs:flex-nowrap'>
<Link href='/' shallow legacyBehavior>
<Badge className='whitespace-nowrap cursor-pointer font-normal'>Movie advisor</Badge>
+12 -23
View File
@@ -1,12 +1,13 @@
import { FC } from 'react';
import useFavorites, { useFavoritesMutation } from '@/app/(site)/favorites/useFavorites';
import Poster from '@/components/Movie/components/Poster';
import Rating from '@/components/Movie/components/Rating';
import Title from '@/components/Movie/components/Title';
import { AspectRatio } from '@/components/ui/aspect-ratio';
import { cn } from '@/lib/utils';
import Favorite from './components/Favorite';
import Handlers from './components/Handlers';
interface Props {
movie?: Movie;
onClick?: () => void;
@@ -14,43 +15,31 @@ interface Props {
}
const Card: FC<Props> = ({ movie, onClick, className }) => {
const { add, remove } = useFavoritesMutation();
const { map } = useFavorites();
if (!movie) return null;
const isFavorite = map.has(movie.id);
const handleToggleFavorite = () => (isFavorite ? remove(movie.id) : add(movie));
return (
<div className='xs:w-[300px] xs:h-[450px] w-full h-full shrink-0'>
<AspectRatio ratio={2 / 3}>
<div
onClick={onClick}
onDoubleClick={handleToggleFavorite}
className={cn(
'h-full relative bg-card text-card-foreground shadow-sm transition-shadow hover:shadow-lg overflow-hidden rounded-lg',
className
)}
>
<div className='flex w-full h-full'>
<Poster title={movie?.name || movie.title} poster={movie.poster_path} />
<Poster title={movie.name || movie.title} poster={movie.poster_path} />
</div>
<div className='text-white absolute w-full h-full top-0 left-0 rounded-md flex flex-col justify-between p-2 card-gradient'>
<div className='grid items-center grid-cols-[1fr_50px] mt-[-5px] opacity-75'>
<Title key={movie?.name || movie.title} title={movie?.name || movie.title} />
{movie.release_date && (
<span className='flex justify-end text-lg'>{new Date(movie.release_date).getFullYear()}</span>
)}
<Handlers movie={movie} onClick={onClick} />
<div className='flex items-start justify-between text-lg opacity-75'>
<span>{movie.name || movie.title}</span>
{Boolean(movie.release_date) && <span>{new Date(movie.release_date).getFullYear()}</span>}
</div>
<div className='opacity-75 mb-[-5px]'>
<Rating
isFavorite={isFavorite}
toggleFavorite={handleToggleFavorite}
rating={movie.vote_average}
iconsFillColor='fill-white'
/>
<span className='select-none flex w-full items-center ml-auto gap-1 mt-[-8px] justify-between z-[1]'>
<Favorite movie={movie} />
<Rating rating={movie.vote_average} />
</span>
</div>
</div>
</div>
+28 -25
View File
@@ -1,5 +1,6 @@
import { FC, forwardRef, useMemo } from 'react';
import { FC, useMemo, useRef } from 'react';
import { VirtuosoGrid, VirtuosoGridProps } from 'react-virtuoso';
import { motion } from 'framer-motion';
import Card from '@/components/Movie/Card';
import { showPreviewModal } from '@/components/Movie/Preview';
@@ -9,20 +10,11 @@ interface Props {
pages: Array<MovieDBResponse>;
hasNextPage?: boolean;
fetchNextPage?: () => void;
withBottomGap?: boolean;
onPreviewClose?: () => void;
type?: ShowType;
customScrollParent?: HTMLElement;
}
const container = {
hidden: {},
visible: {
transition: {
staggerChildren: 0.15
}
}
};
const item = {
hidden: { y: -20, opacity: 0 },
visible: {
@@ -31,26 +23,31 @@ const item = {
}
};
const components: VirtuosoGridProps<Movie, { shows: Movie[]; onClick: (movie: Movie) => void }>['components'] = {
List: forwardRef(function List(props, ref) {
return <div {...props} className='flex gap-3 flex-wrap justify-center grow empty:hidden' ref={ref} />;
}),
const components: VirtuosoGridProps<
Movie,
{ shows: Movie[]; initial: boolean; onClick: (movie: Movie) => void }
>['components'] = {
Item: ({ context, 'data-index': index }) => {
const { shows, onClick } = context || {};
const movie = shows?.[index];
return <Card movie={movie} onClick={() => onClick?.(movie!)} />;
return (
<motion.div
variants={item}
initial='hidden'
animate='visible'
transition={context?.initial ? { delay: 0.15 * index } : undefined}
className='xs:w-[300px] xs:h-[450px] w-full h-full shrink-0'
>
<Card movie={movie} onClick={() => onClick?.(movie!)} />
</motion.div>
);
}
};
const List: FC<Props> = ({
pages,
hasNextPage,
fetchNextPage,
withBottomGap = true,
onPreviewClose,
type = 'movie'
}) => {
const List: FC<Props> = ({ pages, hasNextPage, fetchNextPage, onPreviewClose, type = 'movie', customScrollParent }) => {
const initial = useRef(true);
const shows = useMemo(
() =>
pages?.reduce((shows, page) => {
@@ -64,11 +61,13 @@ const List: FC<Props> = ({
const context = {
shows,
initial: initial.current,
onClick: (movie: Movie) => showPreviewModal({ movie, onClose: onPreviewClose, type })
};
const handleFetchMore = () => {
if (!hasNextPage) return;
initial.current = false;
fetchNextPage?.();
};
@@ -76,13 +75,17 @@ const List: FC<Props> = ({
<>
<VirtuosoGrid
useWindowScroll
listClassName='flex gap-2 flex-wrap justify-center grow empty:hidden'
customScrollParent={customScrollParent}
totalCount={shows.length}
initialItemCount={20}
overscan={4}
endReached={handleFetchMore}
data={shows}
context={context}
components={components}
/>
{withBottomGap && <div className='h-2 w-full' />}
<div className='h-2 w-full' />
</>
);
};
@@ -0,0 +1,23 @@
'use client';
import { FC } from 'react';
import { Heart } from 'lucide-react';
import { useFavoriteToggle } from '@/app/(site)/favorites/useFavorites';
import { cn } from '@/lib/utils';
interface Props {
movie: Movie;
}
const Favorite: FC<Props> = ({ movie }) => {
const { isFavorite, toggle } = useFavoriteToggle(movie);
return (
<span onClick={toggle} className='cursor-pointer' title={isFavorite ? 'Remove from favorites' : 'Add to favorite'}>
<Heart className={cn(isFavorite && 'fill-white')} size={20} />
</span>
);
};
export default Favorite;
@@ -0,0 +1,18 @@
'use client';
import { FC } from 'react';
import { useFavoriteToggle } from '@/app/(site)/favorites/useFavorites';
interface Props {
movie: Movie;
onClick?: () => void;
}
const Handlers: FC<Props> = ({ onClick, movie }) => {
const { toggle } = useFavoriteToggle(movie);
return <div onClick={onClick} onDoubleClick={toggle} className='absolute top-0 left-0 w-full h-full' />;
};
export default Handlers;
+1 -1
View File
@@ -14,7 +14,7 @@ const Poster: FC<Props> = ({ title, poster }) => {
alt={title}
/>
) : (
<div className={'w-full flex items-center justify-center rounded-lg grow'}>
<div className='w-full flex items-center justify-center rounded-lg grow'>
<ImageOff size={100} strokeWidth={1} color='hsl(215.4 16.3% 46.9%)' />
</div>
);
+4 -24
View File
@@ -1,35 +1,15 @@
import { FC } from 'react';
import { motion } from 'framer-motion';
import { Heart, Star } from 'lucide-react';
import { Star } from 'lucide-react';
interface Props {
isFavorite: boolean;
toggleFavorite: () => void;
iconsFillColor?: string;
rating?: number;
}
const Rating: FC<Props> = ({ isFavorite, rating, toggleFavorite, iconsFillColor = 'fill-accent-foreground' }) => {
return (
<span className='select-none flex w-full items-center ml-auto gap-1 mt-[-8px] justify-between'>
<motion.span
onTap={(event) => {
event.preventDefault();
event.stopPropagation();
toggleFavorite();
}}
className='z-[2] cursor-pointer'
title={isFavorite ? 'Remove from favorites' : 'Add to favorite'}
>
<Heart className={isFavorite ? iconsFillColor : ''} size={20} />
</motion.span>
const Rating: FC<Props> = ({ rating }) => (
<span className='flex items-center'>
<Star size={18} className={`mr-1 ${iconsFillColor}`} />
<Star size={18} className='mr-1 fill-white' />
<p className='mt-[3px]'>{rating?.toFixed(1)}</p>
</span>
</span>
);
};
);
export default Rating;
@@ -1,33 +0,0 @@
'use client';
import { FC, useState } from 'react';
import Marquee from 'react-fast-marquee';
interface Props {
title: string;
className?: string;
}
const Title: FC<Props> = ({ title, className }) => {
const [isScrollableTitle, setIsScrollableTitle] = useState(false);
return (
<Marquee
play={isScrollableTitle}
gradientWidth={10}
className={`movie-title overflow-hidden h-[30px] text-lg font-semibold ${className}`}
>
<div
ref={(element) => {
const header = element?.closest('.movie-title') as HTMLDivElement;
const isScrollableTitle = (header?.offsetWidth || 0) < (element?.offsetWidth || 0);
isScrollableTitle && setIsScrollableTitle(isScrollableTitle);
}}
>
{title}&nbsp;
</div>
</Marquee>
);
};
export default Title;
+21 -6
View File
@@ -34,12 +34,15 @@ DialogOverlay.displayName = DialogPrimitive.Overlay.displayName;
const DialogContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content> & { onClose?: () => void }
>(({ className, children, onClose, ...props }, ref) => {
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content> & {
onClose?: () => void;
scrollRef?: React.MutableRefObject<HTMLDivElement>;
}
>(({ className, children, onClose, scrollRef, ...props }, ref) => {
const position = React.useRef(0);
const close = React.useRef(false);
const wrapperRef = React.useRef<HTMLDivElement>(null);
const overlayRef = React.useRef<HTMLDivElement>(null);
const overlayRef = React.useRef<HTMLDivElement>(null) as React.MutableRefObject<HTMLDivElement>;
const contentRef = React.useRef<HTMLDivElement | null>(null);
const { delta, onScroll } = useScrollDelta();
@@ -88,7 +91,18 @@ const DialogContent = React.forwardRef<
return (
<DialogPortal>
<div className='fixed inset-0 w-full h-full bg-black/50 z-50' ref={wrapperRef}>
<DialogOverlay ref={overlayRef} onScroll={onScroll}>
<DialogOverlay
ref={(element) => {
if (!element) return;
overlayRef.current = element;
if (scrollRef) {
scrollRef.current = element;
}
}}
onScroll={onScroll}
>
<DialogPrimitive.Content
onTouchStart={handleTouchStart}
onTouchMove={handleTouchMove}
@@ -144,7 +158,8 @@ const Modal: React.FC<{
children: React.ReactNode;
className?: string;
onClose: () => void;
}> = ({ children, onClose, className }) => {
scrollRef?: React.MutableRefObject<HTMLDivElement>;
}> = ({ children, onClose, className, scrollRef }) => {
const [open, setOpen] = useState(true);
const handleClose = () => {
@@ -157,7 +172,7 @@ const Modal: React.FC<{
<DialogHeader>
<DialogTitle />
</DialogHeader>
<DialogContent forceMount onClose={handleClose} className={className}>
<DialogContent scrollRef={scrollRef} forceMount onClose={handleClose} className={className}>
{children}
</DialogContent>
</Dialog>
+8
View File
@@ -53,6 +53,14 @@ export const popularMovies = async ({ page }: { page?: string } = {}): Promise<M
});
};
export const trendingMovies = async ({ page }: { page?: string } = {}): Promise<MovieDBResponse> => {
return server.get('/trending/movie/day', {
params: {
page
}
});
};
export const topMovies = async ({
page,
starring
+4 -3
View File
@@ -1,5 +1,5 @@
class Server {
get<T>(url: string, {params}: { params?: Record<string, unknown> } = {}): Promise<T> {
get<T>(url: string, { params }: { params?: Record<string, unknown> } = {}): Promise<T> {
const base = 'https://api.themoviedb.org/3';
const serializedParams = Object.entries(params || {}).reduce((params, [key, value]) => {
@@ -11,10 +11,11 @@ class Server {
return fetch(`${base}${url}?${serializedParams}`, {
cache: 'force-cache',
next: { revalidate: 3600 },
headers: {
Authorization: `Bearer ${process.env.MOVIE_DB_TOKEN}`,
Authorization: `Bearer ${process.env.MOVIE_DB_TOKEN}`
}
}).then(response => response.json());
}).then((response) => response.json());
}
}