From 750d5b12c8e3230d1dd277c610f8a9b65e5f5275 Mon Sep 17 00:00:00 2001 From: ner Date: Thu, 29 Aug 2024 12:58:49 +0300 Subject: [PATCH] feat: new nav --- app/(site)/components/Carousel/index.tsx | 80 +++++++++++ app/(site)/components/Filter/Filter.tsx | 85 ++++++++++++ app/(site)/components/Filter/index.tsx | 99 +++++--------- app/(site)/container.tsx | 124 +----------------- app/(site)/favorites/container.tsx | 7 + app/(site)/favorites/page.tsx | 8 ++ app/(site)/favorites/useFavorites.ts | 11 ++ app/(site)/page.tsx | 2 +- app/(site)/popular/page.tsx | 7 + app/(site)/top/page.tsx | 7 + app/(site)/useRandomMovie.ts | 4 +- app/layout.tsx | 7 +- .../Header/components/Navigation/index.tsx | 18 +-- components/Header/components/Search/index.tsx | 10 +- components/Header/index.tsx | 2 +- components/Movie/Card.tsx | 35 ++--- components/Movie/List.tsx | 53 ++++---- .../Movie/components/Favorite/index.tsx | 23 ++++ .../Movie/components/Handlers/index.tsx | 18 +++ components/Movie/components/Poster/index.tsx | 2 +- components/Movie/components/Rating/index.tsx | 34 +---- components/Movie/components/Title/index.tsx | 33 ----- components/ui/dialog.tsx | 27 +++- lib/api/index.ts | 8 ++ network/server.ts | 7 +- 25 files changed, 386 insertions(+), 325 deletions(-) create mode 100644 app/(site)/components/Carousel/index.tsx create mode 100644 app/(site)/components/Filter/Filter.tsx create mode 100644 components/Movie/components/Favorite/index.tsx create mode 100644 components/Movie/components/Handlers/index.tsx delete mode 100644 components/Movie/components/Title/index.tsx diff --git a/app/(site)/components/Carousel/index.tsx b/app/(site)/components/Carousel/index.tsx new file mode 100644 index 0000000..165d3d1 --- /dev/null +++ b/app/(site)/components/Carousel/index.tsx @@ -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['components'] = { + Item: (props) =>
, + List: forwardRef(function List(props, ref) { + return ( +
+ ); + }), + Scroller: forwardRef(function Scroller(props, ref) { + return
; + }) +}; + +export const Measurer = ({ children }: { children: (width: number) => ReactNode }) => { + const [ref, setRef] = useState(null); + const width = ref?.offsetWidth; + + return ( + <> +
+ {children(width || 0)} + + ); +}; + +let snapshot: StateSnapshot; + +export const Carousel = ({ + movies, + width: initialWidth, + onIndexChange +}: { + movies?: Movie[]; + width: number; + onIndexChange: (index: number) => void; +}) => { + const timeout = useRef(); + const isMobile = matchMedia('(max-width: 500px)').matches; + const ref = useRef(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 ( + { + clearTimeout(timeout.current); + + timeout.current = setTimeout(() => { + const currentIndex = index - 1; + + startTransition(() => onIndexChange(currentIndex)); + }, 50); + + return ; + }} + /> + ); +}; diff --git a/app/(site)/components/Filter/Filter.tsx b/app/(site)/components/Filter/Filter.tsx new file mode 100644 index 0000000..fd3d949 --- /dev/null +++ b/app/(site)/components/Filter/Filter.tsx @@ -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(); + + 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>>, key: keyof Filters) => (value: Array) => { + 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 ( + <> + +
    + {genres?.map((genre) => ( +
  • + + {genre.name} + +
  • + ))} +
+
+
+
+ parseInt(value))} + min={1960} + max={new Date().getFullYear()} + step={1} + /> +
+
+ parseInt(value))} + min={0} + max={10} + step={1} + /> +
+
+ + ); +} diff --git a/app/(site)/components/Filter/index.tsx b/app/(site)/components/Filter/index.tsx index 7b8bab1..df87da9 100644 --- a/app/(site)/components/Filter/index.tsx +++ b/app/(site)/components/Filter/index.tsx @@ -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(); + 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>>, key: keyof Filters) => (value: Array) => { - 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 ( <> - -
    - {genres?.map((genre) => ( -
  • - - {genre.name} - -
  • - ))} -
-
-
-
- parseInt(value))} - min={1960} - max={new Date().getFullYear()} - step={1} - /> -
-
- parseInt(value))} - min={0} - max={10} - step={1} - /> -
-
+ {isShowFilter && } + {isMounted && + createPortal( + , + document.getElementById('actions')! + )} ); } diff --git a/app/(site)/container.tsx b/app/(site)/container.tsx index 638a5da..bcaf895 100644 --- a/app/(site)/container.tsx +++ b/app/(site)/container.tsx @@ -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['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() }); - }, []); + const { movies, movie, onIndexChange } = useRandomMovie(); return ( <> - {isShowFilter && } - {isMounted && - createPortal( - , - document.getElementById('actions')! - )} + {(width) => ( } + card={} /> )} diff --git a/app/(site)/favorites/container.tsx b/app/(site)/favorites/container.tsx index 8e81192..62823c7 100644 --- a/app/(site)/favorites/container.tsx +++ b/app/(site)/favorites/container.tsx @@ -6,5 +6,12 @@ import List from '@/components/Movie/List'; export default function Container() { const { pages } = useFavorites(); + if (!pages[0]?.results?.length) + return ( +
+ There are no items in your favorites list +
+ ); + return ; } diff --git a/app/(site)/favorites/page.tsx b/app/(site)/favorites/page.tsx index 579e79e..3a5eb43 100644 --- a/app/(site)/favorites/page.tsx +++ b/app/(site)/favorites/page.tsx @@ -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 ; } diff --git a/app/(site)/favorites/useFavorites.ts b/app/(site)/favorites/useFavorites.ts index 2b50132..96d4d44 100644 --- a/app/(site)/favorites/useFavorites.ts +++ b/app/(site)/favorites/useFavorites.ts @@ -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; diff --git a/app/(site)/page.tsx b/app/(site)/page.tsx index 32b7cd5..9485ee3 100644 --- a/app/(site)/page.tsx +++ b/app/(site)/page.tsx @@ -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'; diff --git a/app/(site)/popular/page.tsx b/app/(site)/popular/page.tsx index 88f7c63..2b211eb 100644 --- a/app/(site)/popular/page.tsx +++ b/app/(site)/popular/page.tsx @@ -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(); diff --git a/app/(site)/top/page.tsx b/app/(site)/top/page.tsx index 03ec73b..5c00f1e 100644 --- a/app/(site)/top/page.tsx +++ b/app/(site)/top/page.tsx @@ -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(); diff --git a/app/(site)/useRandomMovie.ts b/app/(site)/useRandomMovie.ts index 1e3e6cb..5b06f68 100644 --- a/app/(site)/useRandomMovie.ts +++ b/app/(site)/useRandomMovie.ts @@ -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] ), diff --git a/app/layout.tsx b/app/layout.tsx index 0695763..9888688 100644 --- a/app/layout.tsx +++ b/app/layout.tsx @@ -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 }) {
-
{children}
+
{children}
diff --git a/components/Header/components/Navigation/index.tsx b/components/Header/components/Navigation/index.tsx index b7b1b42..829850e 100644 --- a/components/Header/components/Navigation/index.tsx +++ b/components/Header/components/Navigation/index.tsx @@ -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() {
    {paths.map(({ path, title }) => (
  • - - - + +
    + + + +
    +
  • ))}
diff --git a/components/Header/components/Search/index.tsx b/components/Header/components/Search/index.tsx index 9efd207..af0032a 100644 --- a/components/Header/components/Search/index.tsx +++ b/components/Header/components/Search/index.tsx @@ -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(null) as MutableRefObject; const timeout = useRef(); const inputRef = useRef(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 ( - +
{ {Boolean(movies?.pages.length && movies?.pages?.[0]?.results?.length) && ( { {Boolean(series?.pages.length && series?.pages?.[0]?.results?.length) && ( (
-
+
Movie advisor diff --git a/components/Movie/Card.tsx b/components/Movie/Card.tsx index 4401f2e..d7e40dd 100644 --- a/components/Movie/Card.tsx +++ b/components/Movie/Card.tsx @@ -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 = ({ 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 (
- +
-
- - {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> diff --git a/components/Movie/List.tsx b/components/Movie/List.tsx index 25227cf..009ffce 100644 --- a/components/Movie/List.tsx +++ b/components/Movie/List.tsx @@ -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' /> </> ); }; diff --git a/components/Movie/components/Favorite/index.tsx b/components/Movie/components/Favorite/index.tsx new file mode 100644 index 0000000..2068f10 --- /dev/null +++ b/components/Movie/components/Favorite/index.tsx @@ -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; diff --git a/components/Movie/components/Handlers/index.tsx b/components/Movie/components/Handlers/index.tsx new file mode 100644 index 0000000..f20c598 --- /dev/null +++ b/components/Movie/components/Handlers/index.tsx @@ -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; diff --git a/components/Movie/components/Poster/index.tsx b/components/Movie/components/Poster/index.tsx index e7ba63b..fc2e625 100644 --- a/components/Movie/components/Poster/index.tsx +++ b/components/Movie/components/Poster/index.tsx @@ -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> ); diff --git a/components/Movie/components/Rating/index.tsx b/components/Movie/components/Rating/index.tsx index c9f8ae2..a577825 100644 --- a/components/Movie/components/Rating/index.tsx +++ b/components/Movie/components/Rating/index.tsx @@ -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> - <span className='flex items-center'> - <Star size={18} className={`mr-1 ${iconsFillColor}`} /> - <p className='mt-[3px]'>{rating?.toFixed(1)}</p> - </span> - </span> - ); -}; +const Rating: FC<Props> = ({ rating }) => ( + <span className='flex items-center'> + <Star size={18} className='mr-1 fill-white' /> + <p className='mt-[3px]'>{rating?.toFixed(1)}</p> + </span> +); export default Rating; diff --git a/components/Movie/components/Title/index.tsx b/components/Movie/components/Title/index.tsx deleted file mode 100644 index 9c71d69..0000000 --- a/components/Movie/components/Title/index.tsx +++ /dev/null @@ -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}  - </div> - </Marquee> - ); -}; - -export default Title; diff --git a/components/ui/dialog.tsx b/components/ui/dialog.tsx index e79cae8..a180808 100644 --- a/components/ui/dialog.tsx +++ b/components/ui/dialog.tsx @@ -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> diff --git a/lib/api/index.ts b/lib/api/index.ts index 2f83ed8..165715b 100644 --- a/lib/api/index.ts +++ b/lib/api/index.ts @@ -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 diff --git a/network/server.ts b/network/server.ts index 2854fb7..5631ea4 100644 --- a/network/server.ts +++ b/network/server.ts @@ -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()); } }