feat: favorite & watch lists

This commit is contained in:
ner committed 2024-10-19 16:09:15 +03:00
1 parent 960a7a6242
commit 8858e47d38
51 files changed
+560 -289

No files matched your search

+32 -3
View File
@@ -30,15 +30,44 @@ export const account = async () => {
});
};
export const accountStates = async ({ showId, showType }: { showId: Show['id']; showType: Show['type'] }) => {
return http.get<ShowState>(`/${showType}/${showId}/account_states`, {
params: { session_id: cookies().get('session')?.value },
preventCache: true
});
};
export const updateAccountStates = async ({
showId,
showType,
list,
value
}: {
showId: Show['id'];
showType: Show['type'];
list: 'favorite' | 'watchlist';
value: boolean;
}) => {
http.post(
`/account/null/${list}`,
{ params: { session_id: cookies().get('session')?.value }, preventCache: true },
{
media_id: showId,
media_type: showType,
[list]: value
}
);
};
export const usersShows = async ({
showType,
listType
list
}: {
showType: Show['type'];
listType: 'favorites' | 'watchlist';
list: 'favorite' | 'watchlist';
}): Promise<Pagination<Show>> => {
return http
.get<TMDBPagination<Movie>>(`/account/null/${listType}/${showType === 'tv' ? 'tv' : 'movies'}`, {
.get<TMDBPagination<Movie>>(`/account/null/${list}/${showType === 'tv' ? 'tv' : 'movies'}`, {
params: { session_id: cookies().get('session')?.value },
preventCache: true
})
+3 -18
View File
@@ -1,22 +1,7 @@
'use client';
import List from '@/components/List';
import useMounted from '@/hooks/useMounted';
import UsersList from '@/components/UsersLists';
import useFavorites from './useFavorites';
const Container = () => <UsersList list='favorite' label='favorites' />;
export default function Container() {
const { shows } = useFavorites();
const isMounted = useMounted();
if (!isMounted) return null;
if (!shows.length)
return (
<div className='flex h-40 w-full items-center justify-center text-center text-xl text-muted-foreground'>
There are no items in your favorites list
</div>
);
return <List shows={shows} />;
}
export default Container;
+21 -2
View File
@@ -1,5 +1,9 @@
import { dehydrate, HydrationBoundary } from '@tanstack/react-query';
import { Metadata } from 'next';
import { usersShows } from '@/api';
import getQueryClient from '@/lib/queryClient';
import Container from './container';
export const metadata: Metadata = {
@@ -8,8 +12,23 @@ export const metadata: Metadata = {
'View your favorite shows on Movie Advisor. Keep track of films you’ve added and revisit your top picks anytime.'
};
const Favorites = () => {
return <Container />;
const Favorites = async () => {
const queryClient = getQueryClient();
const list = 'favorite';
const showType = 'movie';
await queryClient.prefetchInfiniteQuery({
queryKey: [`users-${list}`, showType],
queryFn: () => usersShows({ showType, list }),
initialPageParam: '1'
});
return (
<HydrationBoundary state={dehydrate(queryClient)}>
<Container />
</HydrationBoundary>
);
};
export default Favorites;
-46
View File
@@ -1,46 +0,0 @@
import { atom, useAtomValue, useSetAtom } from 'jotai';
import { atomWithStorage } from 'jotai/utils';
const favoritesAtom = atomWithStorage<Show[]>('favorite', [], undefined, {
unstable_getOnInit: true
});
const favoritesMapAtom = atom((get) => {
const map = new Map();
const favorites = get(favoritesAtom);
favorites.forEach((show) => map.set(show.id, show));
return map as Map<Show['id'], Show>;
});
const useFavorites = () => {
return {
shows: useAtomValue(favoritesAtom),
map: useAtomValue(favoritesMapAtom)
};
};
export const useFavoritesMutation = () => {
const setFavorites = useSetAtom(favoritesAtom);
const add = (show: Show) => setFavorites((favorites) => [show, ...favorites]);
const remove = (showId: number) => setFavorites((favorites) => favorites.filter(({ id }) => id !== showId));
return {
add,
remove
};
};
export const useFavoriteToggle = (show: Show) => {
const { add, remove } = useFavoritesMutation();
const { map } = useFavorites();
const isFavorite = map.has(show.id);
const toggle = () => (isFavorite ? remove(show.id) : add(show));
return { isFavorite, toggle };
};
export default useFavorites;
+7
View File
@@ -0,0 +1,7 @@
'use client';
import UsersList from '@/components/UsersLists';
const Container = () => <UsersList list='watchlist' label='watch' />;
export default Container;
+34
View File
@@ -0,0 +1,34 @@
import { dehydrate, HydrationBoundary } from '@tanstack/react-query';
import { Metadata } from 'next';
import { usersShows } from '@/api';
import getQueryClient from '@/lib/queryClient';
import Container from './container';
export const metadata: Metadata = {
title: 'My watch list - Movie Advisor',
description:
'View your favorite shows on Movie Advisor. Keep track of films you’ve added and revisit your top picks anytime.'
};
const WatchList = async () => {
const queryClient = getQueryClient();
const list = 'watchlist';
const showType = 'movie';
await queryClient.prefetchInfiniteQuery({
queryKey: [`users-${list}`, showType],
queryFn: () => usersShows({ showType, list }),
initialPageParam: '1'
});
return (
<HydrationBoundary state={dehydrate(queryClient)}>
<Container />
</HydrationBoundary>
);
};
export default WatchList;
+1 -2
View File
@@ -15,7 +15,6 @@ export const metadata: Metadata = {
};
export const viewport: Viewport = {
themeColor: 'black',
width: 'device-width',
initialScale: 1,
maximumScale: 1,
@@ -30,7 +29,7 @@ const RootLayout = ({ children }: { children: ReactNode }) => {
return (
<html lang='en' data-mode={theme}>
<head>
<meta name='theme-color' content='black' />
<meta name='theme-color' content={theme === 'dark' ? 'hsl(222.2 84% 4.9%)' : 'white'} />
</head>
<body style={{ '--font-family': font.style.fontFamily, ...font.style } as CSSProperties}>
<Providers theme={theme}>
@@ -2,5 +2,6 @@ export const paths = [
{ path: '/', title: 'Random' },
{ path: '/popular', title: 'Popular' },
{ path: '/top', title: 'Top rated' },
{ path: '/favorites', title: 'Favorites' }
{ path: '/favorites', title: 'Favorites' },
{ path: '/watch-list', title: 'Watch list' }
];
+1 -1
View File
@@ -11,8 +11,8 @@ import {
DropdownMenuSeparator,
DropdownMenuTrigger
} from '@/components/ui/dropdown-menu';
import useAccount from '@/hooks/useAccount';
import useAccount from './useAccount';
import useAuth from './useAuth';
import useLogOut from './useLogOut';
@@ -1,6 +1,7 @@
import { account } from '@/api';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { useSession } from './useSession';
import { account } from '@/api';
import { useSession } from '@/hooks/useSession';
const KEY = ['account'];
+1 -1
View File
@@ -16,7 +16,7 @@ interface Props {
const Header: FC<Props> = ({ className }) => (
<header
className={cn(
'flex justify-center bg-background/95 py-2 backdrop-blur supports-[backdrop-filter]:bg-background/60',
'flex justify-center bg-background/95 md:py-2 py-1 backdrop-blur supports-[backdrop-filter]:bg-background/60',
className
)}
>
+2 -2
View File
@@ -1,8 +1,8 @@
import { FC } from 'react';
import { VirtuosoGrid, VirtuosoGridProps } from 'react-virtuoso';
import Poster from '@/components/Poster';
import { showPreviewModal } from '@/components/Preview';
import Card from '@/components/Show';
interface Props {
shows: Show[];
@@ -18,7 +18,7 @@ const components: VirtuosoGridProps<Movie, { shows: Show[]; onClick: (show: Show
if (!show) return null;
return <Card show={show} onClick={() => onClick?.(show)} />;
return <Poster show={show} onClick={() => onClick?.(show)} />;
}
};
@@ -0,0 +1,24 @@
'use client';
import { FC } from 'react';
import { useMutateShowState } from '@/hooks/useShowState';
interface Props {
show: Show;
onClick?: () => void;
}
const Handlers: FC<Props> = ({ onClick, show }) => {
const { mutate } = useMutateShowState(show);
return (
<div
onClick={onClick}
onDoubleClick={() => mutate({ list: 'favorite', value: true })}
className='absolute left-0 top-0 size-full'
/>
);
};
export default Handlers;
+42
View File
@@ -0,0 +1,42 @@
import { DetailedHTMLProps, FC, HTMLAttributes } from 'react';
import { cn } from '@/lib/utils';
import Handlers from './components/Handlers';
interface Props {
show?: Show;
onClick?: () => void;
className?: string;
rounded?: string;
containerProps?: DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>;
}
const Poster: FC<Props> = ({ show, onClick, className, rounded, containerProps }) => {
if (!show) return null;
return (
<div
{...(containerProps || {})}
className={cn(
'card-aspect-ratio relative bg-card text-card-foreground overflow-hidden rounded-lg text-lg',
className,
rounded
)}
>
<div className='flex size-full'>
<img className={cn('size-full rounded-lg object-cover', rounded)} src={show.poster} alt={show.title} />
</div>
<div
className={cn(
'absolute left-0 top-0 flex size-full flex-col justify-between rounded-md bg-vignette p-2 text-white',
rounded
)}
>
<Handlers show={show} onClick={onClick} />
</div>
</div>
);
};
export default Poster;
-46
View File
@@ -1,46 +0,0 @@
'use client';
import Link from 'next/link';
import showTorrentsModal from '@/components/Show/components/Torrents';
import ToggleTrailer from '@/components/Show/components/Trailer';
import { Button } from '@/components/ui/button';
interface Props {
show: Show & Partial<Details>;
onClose?: () => void;
}
const Actions = ({ onClose, show }: Props) => (
<>
<ToggleTrailer showType={show.type} showId={show.id}>
{({ onPlay, disabled }) => (
<Button className='h-8 w-1/2 grow' onClick={onPlay} disabled={disabled}>
Trailer
</Button>
)}
</ToggleTrailer>
<Button
className='h-8 w-1/2 grow'
onClick={() =>
showTorrentsModal({
imdbID: show.imdb_id!,
title: show.title,
backdrop: show.backdrop,
year: new Date(show.release).getFullYear()
})
}
>
Torrents
</Button>
<Link
className='flex w-1/2'
href={`/similar?id=${show.id}&title=${encodeURIComponent(show.title)}&type=${show.type}`}
onClick={onClose}
>
<Button className='h-8 grow'>Similar</Button>
</Link>
</>
);
export default Actions;
@@ -0,0 +1,84 @@
'use client';
import { Bookmark, Copy, Heart, Play, Star } from 'lucide-react';
import Link from 'next/link';
import showTorrentsModal from '@/components/Preview/components/Torrents';
import { Button } from '@/components/ui/button';
import useShowState, { useMutateShowState } from '@/hooks/useShowState';
import { cn } from '@/lib/utils';
interface Props {
show: Show & Partial<Details>;
className: string;
onClose?: () => void;
}
const Actions = ({ onClose, show, className }: Props) => {
const state = useShowState({ showId: show.id, showType: show.type });
const toggle = useMutateShowState(show);
const groupClassName = 'flex bg-input gap-[1px] rounded-md md:flex-grow-0 flex-grow';
const leftClassName = 'h-8 gap-1 flex-grow border-r-0 rounded-none rounded-l-md md:px-3 px-2';
const rightClassName = 'h-8 gap-1 flex-grow border-l-0 rounded-none rounded-r-md md:px-3 px-2';
return (
<div className={cn('flex gap-2 flex-wrap md:flex-grow-0 flex-grow', className)}>
<div className={cn(groupClassName, 'pointer-events-none')}>
<Button className={leftClassName} variant='outline'>
<Star size={14} />
</Button>
<Button className={rightClassName} variant='outline'>
{show.rating.toFixed(1)}
</Button>
</div>
<div className={groupClassName}>
<Button
className={leftClassName}
variant='outline'
disabled={toggle.list === 'favorite' && toggle.isPending}
onClick={() => toggle.mutate({ list: 'favorite', value: !state?.favorite })}
>
<Heart size={14} className={cn({ 'fill-secondary-foreground': state?.favorite })} />
</Button>
<Button
className={rightClassName}
variant='outline'
disabled={toggle.list === 'watchlist' && toggle.isPending}
onClick={() => toggle.mutate({ list: 'watchlist', value: !state?.watchlist })}
>
<Bookmark size={14} className={cn({ 'fill-secondary-foreground': state?.watchlist })} />
</Button>
</div>
<div className={cn(groupClassName, 'gap-0')}>
<Link
className='flex grow'
href={`/similar?id=${show.id}&title=${encodeURIComponent(show.title)}&type=${show.type}`}
onClick={onClose}
>
<Button className={leftClassName} variant='outline'>
<Copy size={14} />
Similar
</Button>
</Link>
<Button
className={cn(rightClassName, 'bg-red-600')}
variant='destructive'
onClick={() =>
showTorrentsModal({
imdbID: show.imdb_id!,
title: show.title,
backdrop: show.backdrop,
year: new Date(show.release).getFullYear()
})
}
>
<Play size={15} />
Watch
</Button>
</div>
</div>
);
};
export default Actions;
@@ -2,7 +2,8 @@ import { create, InstanceProps } from 'react-modal-promise';
import { Modal } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { usePrefix, useSetPrefix } from '@/hooks/useMagnetHosts';
import { usePrefix, useSetPrefix } from '../../hooks/useMagnetHosts';
const showHostManagerModal = create<InstanceProps<string>>(({ onResolve, onReject }) => {
const prefix = usePrefix();
@@ -35,7 +35,7 @@ const showPlayer = create(({ onResolve, magnet, backdrop, title }: Props) => {
}
if (isFetched && !videos.length) {
toast({ description: 'This torrent doesn\'t contain any compatible video files' });
toast({ description: 'This torrent doesn’t contain any compatible video files' });
onResolve();
}
@@ -4,9 +4,9 @@ import { Cast, Copy, ListVideo, Magnet, Play } from 'lucide-react';
import { Sort } from '@/api/parsers';
import { Quality } from '@/api/parsers/yts/models';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { useCastMagnet, usePrefix } from '@/hooks/useMagnetHosts';
import { providers } from '../../constants';
import { useCastMagnet, usePrefix } from '../../hooks/useMagnetHosts';
import showHostManagerModal from '../HostManager';
import showPlayer from '../Player';
import TableHeadSortable from '../TableHeadSortable';
@@ -2,7 +2,7 @@ import { useCallback } from 'react';
import { useAtomValue, useSetAtom } from 'jotai';
import { atomWithStorage } from 'jotai/utils';
import showHostManagerModal from '@/components/Show/components/Torrents/components/HostManager';
import showHostManagerModal from '@/components/Preview/components/Torrents/components/HostManager';
const magnetPrefixAtom = atomWithStorage<string>('magnet-prefix', 'http://{host}:65220/playuri?uri=', undefined, {
unstable_getOnInit: true
@@ -60,7 +60,7 @@ const showTorrentsModal = create(({ title, year, imdbID, backdrop, onResolve }:
<Modal className='rounded-xl p-0 pb-1' onClose={onResolve}>
<div className='grid grid-cols-[1fr_auto] items-center gap-3 p-2'>
<span className='truncate text-base'>{title}</span>
<Button className='h-6 p-2' variant={withYear ? 'default' : 'ghost'} onClick={() => setWithYear((w) => w)}>
<Button className='h-6 p-2' variant={withYear ? 'default' : 'ghost'} onClick={() => setWithYear((w) => !w)}>
{year}
</Button>
</div>
+32 -17
View File
@@ -3,11 +3,10 @@
import { FC, ReactNode } from 'react';
import { create, InstanceProps } from 'react-modal-promise';
import Poster from '@/components/Poster';
import Credits from '@/components/Preview/components/Credits';
import useDetails from '@/components/Preview/useDetails';
import Card from '@/components/Show';
import Credits from '@/components/Show/components/Credits';
import { Modal } from '@/components/ui/dialog';
import { Separator } from '@/components/ui/separator';
import { cn } from '@/lib/utils';
import Actions from './components/Actions';
@@ -16,30 +15,47 @@ interface Props {
show?: Show;
className?: string;
onClose?: () => void;
children?: ReactNode;
card?: ReactNode;
poster?: ReactNode;
}
const Preview: FC<Props> = ({ show: baseShow, className, onClose, children, card }) => {
const Preview: FC<Props> = ({ show: baseShow, className, onClose, poster }) => {
const { data: detailedShow } = useDetails({ showId: baseShow?.id, showType: baseShow?.type });
if (!baseShow) return null;
const show: (Show & Partial<Details>) | undefined = detailedShow || baseShow;
const isModal = Boolean(onClose);
return (
<div className={cn('flex flex-col md:flex-row gap-2 rounded-xl', { 'p-2': Boolean(onClose) }, className)}>
{card || <Card className='mx-auto' show={show} />}
<div className='flex grow flex-col'>
{children && <div className='mb-2 flex w-full gap-2 hover-none:hidden max-sm:mb-0'>{children}</div>}
<div className='flex w-full gap-2'>
<Actions show={show} onClose={onClose} />
<div
className={cn(
'flex flex-col md:flex-row gap-2 rounded-xl',
{ 'md:pl-0 md:pt-0 md:pb-0 pl-2 pt-2 pb-2 pr-2 border-none gap-0': isModal },
className
)}
>
{poster || <Poster className='mx-auto' rounded='md:rounded-none md:rounded-l-xl' show={show} />}
<div className={cn('flex grow flex-col', { 'md:pb-2 md:pl-2 pb-0 pl-0 pt-2': isModal })}>
<span className='order-3 mb-4 text-3xl md:order-1 md:line-clamp-2'>{show.title}</span>
<div className='order-3 mb-4 flex w-full flex-wrap gap-5 whitespace-nowrap text-sm md:order-2'>
<span>{new Date(show.release).getFullYear()}</span>
{show.runtime && <span>{show.runtime} minutes</span>}
<span>
{show.genres
?.slice(0, 3)
.map(({ name }) => name)
.join(' | ')}
</span>
</div>
<Separator className='my-2' />
<p key={show.id} className='mb-3 leading-7'>
<Actions className='order-1 mb-4 mt-1 md:order-2 md:mt-0' show={show} onClose={onClose} />
<p key={show.id} className='order-4 md:order-4 md:line-clamp-3' title={show.overview}>
{show.overview}
</p>
<div className='mt-auto grid grid-cols-1 rounded-lg'>
<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} />
</div>
</div>
@@ -48,10 +64,9 @@ const Preview: FC<Props> = ({ show: baseShow, className, onClose, children, card
};
export const showPreviewModal = create(({ onResolve, onClose, show }: Props & InstanceProps<void>) => (
<Modal className='block p-0' onClose={onResolve}>
<Modal className='block max-w-[932px] p-0' onClose={onResolve}>
<Preview
show={show}
className='border-none'
onClose={() => {
window.scrollTo({ top: 0, behavior: 'smooth' });
onClose?.();
@@ -3,8 +3,8 @@
import { FC, ForwardedRef, forwardRef, useLayoutEffect, useRef } from 'react';
import { Virtuoso, VirtuosoProps } from 'react-virtuoso';
import Poster from '@/components/Poster';
import ScrollNavigation from '@/components/ScrollNavigation';
import Card from '@/components/Show';
import { cn } from '@/lib/utils';
const components: VirtuosoProps<Show, (index: number) => void>['components'] = {
@@ -36,7 +36,7 @@ const components: VirtuosoProps<Show, (index: number) => void>['components'] = {
return (
<div {...props} ref={ref} className='snap-start'>
<Card show={item} />
<Poster show={item} />
</div>
);
},
+1 -1
View File
@@ -12,7 +12,7 @@ const Random = () => {
<Preview
show={movie}
className='rounded-md bg-background'
card={<Carousel index={index} shows={movies} onIndexChange={onIndexChange} onEndReached={fetchNextPage} />}
poster={<Carousel index={index} shows={movies} onIndexChange={onIndexChange} onEndReached={fetchNextPage} />}
/>
);
};
@@ -1,29 +0,0 @@
'use client';
import { FC } from 'react';
import { Heart } from 'lucide-react';
import { useFavoriteToggle } from '@/app/(site)/favorites/useFavorites';
import useMounted from '@/hooks/useMounted';
import { cn } from '@/lib/utils';
interface Props {
show: Show;
}
const Favorite: FC<Props> = ({ show }) => {
const isMounted = useMounted();
const { isFavorite, toggle } = useFavoriteToggle(show);
return (
<span
onClick={toggle}
className='cursor-pointer'
title={isMounted && isFavorite ? 'Remove from favorites' : 'Add to favorite'}
>
<Heart className={cn(isMounted && isFavorite && 'fill-white')} size={20} />
</span>
);
};
export default Favorite;
@@ -1,18 +0,0 @@
'use client';
import { FC } from 'react';
import { useFavoriteToggle } from '@/app/(site)/favorites/useFavorites';
interface Props {
show: Show;
onClick?: () => void;
}
const Handlers: FC<Props> = ({ onClick, show }) => {
const { toggle } = useFavoriteToggle(show);
return <div onClick={onClick} onDoubleClick={toggle} className='absolute left-0 top-0 size-full' />;
};
export default Handlers;
@@ -1,15 +0,0 @@
import { FC } from 'react';
import { Star } from 'lucide-react';
interface Props {
rating?: number;
}
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;
-48
View File
@@ -1,48 +0,0 @@
import { DetailedHTMLProps, FC, HTMLAttributes } from 'react';
import Image from 'next/image';
import Rating from '@/components/Show/components/Rating';
import { cn } from '@/lib/utils';
import Favorite from './components/Favorite';
import Handlers from './components/Handlers';
interface Props {
show?: Show;
onClick?: () => void;
className?: string;
containerProps?: DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>;
}
const Show: FC<Props> = ({ show, onClick, className, containerProps }) => {
if (!show) return null;
return (
<div
{...(containerProps || {})}
className={cn(
'card-aspect-ratio relative bg-card text-card-foreground shadow-sm transition-shadow hover:shadow-lg overflow-hidden rounded-lg text-lg',
className
)}
>
<div className='flex size-full'>
<img className='size-full rounded-lg object-cover' src={show.poster} alt={show.title} />
</div>
<div className='absolute left-0 top-0 flex size-full flex-col justify-between rounded-md bg-vignette p-2 text-white'>
<Handlers show={show} onClick={onClick} />
<div className='grid grid-cols-[1fr_auto] gap-2 opacity-75'>
<span className='truncate'>{show.title}</span>
{Boolean(show.release) && <span>{new Date(show.release).getFullYear()}</span>}
</div>
<div className='mb-[-5px] opacity-75'>
<span className='z-[1] ml-auto mt-[-8px] flex w-full select-none items-center justify-between gap-1'>
<Favorite show={show} />
<Rating rating={show.rating} />
</span>
</div>
</div>
</div>
);
};
export default Show;
@@ -1,8 +1,8 @@
import { FC } from 'react';
import Poster from '@/components/Poster';
import { showPreviewModal } from '@/components/Preview';
import ScrollNavigation from '@/components/ScrollNavigation';
import Card from '@/components/Show';
interface Props {
shows: Show[];
@@ -17,7 +17,7 @@ const Gallery: FC<Props> = ({ shows }) => (
>
{shows.map((show) => (
<li key={show.id} className='snap-start'>
<Card className='!h-[350px] !w-[230px] text-sm' show={show} onClick={() => showPreviewModal({ show })} />
<Poster className='!h-[350px] !w-[230px] text-sm' show={show} onClick={() => showPreviewModal({ show })} />
</li>
))}
</ul>
+4 -4
View File
@@ -1,12 +1,12 @@
export const tabs = [
{
title: 'Trending',
type: 'trending'
},
{
title: 'Streaming',
type: 'streaming'
},
{
title: 'Trending',
type: 'trending'
},
{
title: 'In theaters',
type: 'theater'
+2 -2
View File
@@ -11,8 +11,8 @@ import useTrending from './useTrending';
const Trending: FC = () => {
const [active, setActive] = useState(tabs[0]);
const { data: trending, isFetched } = useTrending({ type: 'trending' });
const { data: streaming } = useTrending({ type: 'streaming' });
const { data: streaming, isFetched } = useTrending({ type: 'streaming' });
const { data: trending } = useTrending({ type: 'trending' });
const { data: theater } = useTrending({ type: 'theater' });
const shows = { trending, streaming, theater }[active.type] || [];
+53
View File
@@ -0,0 +1,53 @@
'use client';
import { FC } from 'react';
import List from '@/components/List';
import useMounted from '@/hooks/useMounted';
import useUsersShows from '@/hooks/useUsersShows';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs';
interface Props {
list: 'favorite' | 'watchlist';
label: string;
}
const UsersList: FC<Props> = ({ list, label }) => {
const isMounted = useMounted();
const movies = useUsersShows({ list, showType: 'movie' });
const series = useUsersShows({ list, showType: 'tv' });
const tabs = [
{ query: movies, title: 'Movies', key: 'movie' as const },
{ query: series, title: 'Series', key: 'tv' as const }
];
if (!isMounted) return null;
return (
<Tabs defaultValue='movie' className='flex w-full flex-col items-center'>
<TabsList className='grid w-[300px] grid-cols-2'>
{tabs.map(({ title, key }) => (
<TabsTrigger key={key} value={key}>
{title}
</TabsTrigger>
))}
</TabsList>
{tabs.map(({ query, key, title }) => (
<TabsContent key={key} value={key} className='w-full'>
{query.isFetched && !query.shows.length ? (
<div className='flex h-40 w-full items-center justify-center text-center text-xl text-muted-foreground'>
There are no {title.toLowerCase()} in your {label} list
</div>
) : (
<List shows={query.shows} fetchNextPage={query.fetchNextPage} />
)}
</TabsContent>
))}
</Tabs>
);
};
export default UsersList;
-21
View File
@@ -1,21 +0,0 @@
import { usersShows } from '@/api';
import useInfiniteList from './useInfiniteList';
import { useSession } from './useSession';
const useFavorites = ({
showType,
listType = 'favorites'
}: {
showType: Show['type'];
listType: 'favorites' | 'watchlist';
}) => {
const session = useSession();
return useInfiniteList({
queryKey: [`users-${listType}`, showType],
queryFn: () => usersShows({ showType, listType }),
enabled: Boolean(session)
});
};
export default useFavorites;
+78
View File
@@ -0,0 +1,78 @@
import { Atom, atom, PrimitiveAtom, useAtomValue, useSetAtom } from 'jotai';
import { atomWithStorage } from 'jotai/utils';
import { useCallback } from 'react';
type MapShow = Map<Show['id'], Show>;
const createStorage = (key: string) => {
const listAtom = atomWithStorage<Show[]>(key, [], undefined, {
unstable_getOnInit: true
});
const mapAtom = atom<MapShow>((get) => {
const map = new Map();
const list = get(listAtom);
list.forEach((show) => map.set(show.id, show));
return map;
});
return { listAtom, mapAtom };
};
const createUseShows =
({ listAtom, mapAtom }: { listAtom: PrimitiveAtom<Show[]>; mapAtom: Atom<MapShow> }) =>
() => ({
shows: useAtomValue(listAtom),
map: useAtomValue(mapAtom)
});
const createUseShowsMutation =
({ listAtom }: { listAtom: PrimitiveAtom<Show[]> }) =>
() => {
const setShows = useSetAtom(listAtom);
const add = (show: Show) => setShows((shows) => [show, ...shows]);
const remove = (showId: number) => setShows((shows) => shows.filter(({ id }) => id !== showId));
return {
add,
remove
};
};
const createUseStateToggle =
({
useShows,
useShowsMutation
}: {
useShows: ReturnType<typeof createUseShows>;
useShowsMutation: ReturnType<typeof createUseShowsMutation>;
}) =>
(show: Show) => {
const { add, remove } = useShowsMutation();
const { map } = useShows();
const active = map.has(show.id);
const toggle = useCallback(() => (active ? remove(show.id) : add(show)), [add, remove, show]);
return { active, toggle };
};
const createStorageHooks = (key: string) => {
const storage = createStorage(key);
const useShows = createUseShows(storage);
const useShowsMutation = createUseShowsMutation(storage);
const useStateToggle = createUseStateToggle({
useShows,
useShowsMutation
});
return { useShows, useShowsMutation, useStateToggle };
};
export const { useShows: useFavorites, useStateToggle: useFavoritesStateToggle } =
createStorageHooks('users-favorites');
export const { useShows: useWatchList, useStateToggle: useWatchListStateToggle } =
createStorageHooks('users-watch-list');
+69
View File
@@ -0,0 +1,69 @@
import { accountStates, updateAccountStates } from '@/api';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useFavorites, useFavoritesStateToggle, useWatchList, useWatchListStateToggle } from './useLocalUsersLists';
import { useSession } from './useSession';
import { KEY as USERS_SHOWS_KEY } from './useUsersShows';
const KEY = ['show-state'];
const useShowState = ({ showId, showType = 'movie' }: { showId?: Show['id']; showType?: Show['type'] }) => {
const session = useSession();
const { map: favorites } = useFavorites();
const { map: watchList } = useWatchList();
const query = useQuery({
enabled: Boolean(session && showId && showType),
queryKey: KEY.concat(showId!.toString(), showType),
queryFn: () => accountStates({ showId: showId!, showType }),
notifyOnChangeProps: ['data'],
staleTime: Infinity
});
return session ? query.data : { id: showId, watchlist: watchList.has(showId!), favorite: favorites.has(showId!) };
};
export const useMutateShowState = (show: Show) => {
const session = useSession();
const { toggle: toggleFavorite } = useFavoritesStateToggle(show);
const { toggle: toggleWatchList } = useWatchListStateToggle(show);
const queryClient = useQueryClient();
const mutation = useMutation({
mutationFn: updateAccountStates,
onMutate({ showId, showType, list, value }) {
const key = KEY.concat(showId.toString(), showType);
const snapshot = queryClient.getQueryData<ShowState>(key);
queryClient.setQueryData<ShowState>(key, (state) => ({ ...state, [list]: value }) as ShowState);
return snapshot;
},
onError(_, { showId, showType }, snapshot) {
const key = KEY.concat(showId.toString(), showType);
queryClient.setQueryData<ShowState>(key, snapshot);
},
onSuccess(_, { list, showType }) {
queryClient.invalidateQueries({ queryKey: USERS_SHOWS_KEY({ list, showType }) });
}
});
return {
list: mutation.variables?.list,
isPending: session ? mutation.isPending : false,
mutate: ({ list, value }: { list: 'favorite' | 'watchlist'; value: boolean }) => {
if (session) return mutation.mutate({ showId: show.id, showType: show.type, list, value });
if (list === 'favorite') return toggleFavorite();
return toggleWatchList();
}
};
};
export default useShowState;
+36
View File
@@ -0,0 +1,36 @@
import { usersShows } from '@/api';
import useInfiniteList from './useInfiniteList';
import { useSession } from './useSession';
import { useFavorites, useWatchList } from './useLocalUsersLists';
export const KEY = ({ list, showType }: { showType: Show['type']; list: 'favorite' | 'watchlist' }) => [
`users-${list}`,
showType
];
const useUsersShows = ({ showType, list = 'favorite' }: { showType: Show['type']; list: 'favorite' | 'watchlist' }) => {
const session = useSession();
const { shows: favorite } = useFavorites();
const { shows: watchlist } = useWatchList();
const query = useInfiniteList({
queryKey: KEY({ list, showType }),
queryFn: () => usersShows({ showType, list }),
enabled: Boolean(session)
});
return session
? query
: {
fetchNextPage: undefined,
isLoading: false,
isFetched: true,
shows: {
favorite: favorite.filter((show) => show.type === showType),
watchlist: watchlist.filter((show) => show.type === showType)
}[list]
};
};
export default useUsersShows;
+3
View File
@@ -22,6 +22,9 @@ const Provider: FC<Props> = ({ children, theme: initialTheme }) => {
}
document.documentElement.setAttribute('data-mode', theme);
document
.querySelector('meta[name="theme-color"]')
?.setAttribute('content', theme === 'dark' ? 'hsl(222.2 84% 4.9%)' : 'white');
Cookies.set('theme', theme);
}, [theme, setTheme]);
+7
View File
@@ -70,15 +70,22 @@ module.exports = {
fadeAsideSlideIn: {
'0%': { opacity: 0, transform: 'translate3d(-20px, 0, 0)' },
'100%': { opacity: 1, transform: 'translate3d(0, 0, 0)' }
},
glow: {
'0%': { backgroundPosition: '0 0' },
'50%': { backgroundPosition: '100% 0' },
'100%': { backgroundPosition: '0 0' }
}
},
animation: {
glow: 'glow 20s linear infinite',
'accordion-down': 'accordion-down 0.2s ease-out',
'accordion-up': 'accordion-up 0.2s ease-out',
'fade-in-slide-in': 'fadeInSlideIn 0.2s ease-in-out forwards',
'fade-aside-slide-in': 'fadeAsideSlideIn 0.2s ease-in-out forwards'
},
backgroundImage: {
glow: 'linear-gradient(45deg,rgba(255, 255, 255, 0.2),rgba(255, 255, 255, 0.2),rgba(255, 255, 255, 0.2),rgba(0, 0, 0, 0.4),rgba(0, 0, 0, 0.4),rgba(255, 255, 255, 0.2),rgba(255, 255, 255, 0.2),rgba(255, 255, 255, 0.2))',
vignette:
'linear-gradient(rgba(0, 0, 0, 0.4) 0%,rgba(0, 0, 0, 0.396) 2.83%,rgba(0, 0, 0, 0.384) 5.67%,rgba(0, 0, 0, 0.37) 8.5%,rgba(0, 0, 0, 0.34) 11.33%,rgba(0, 0, 0, 0.306) 14.17%,rgba(0, 0, 0, 0.267) 17%,rgba(0, 0, 0, 0.224) 19.83%,rgba(0, 0, 0, 0.176) 22.67%,rgba(0, 0, 0, 0.133) 25.5%,rgba(0, 0, 0, 0.094) 28.33%,rgba(0, 0, 0, 0.06) 31.17%,rgba(0, 0, 0, 0.03) 34%,rgba(0, 0, 0, 0.016) 36.83%,rgba(0, 0, 0, 0.004) 39.67%,rgba(0, 0, 0, 0) 42.5%,rgba(0, 0, 0, 0) 57.5%,rgba(0, 0, 0, 0.004) 60.33%,rgba(0, 0, 0, 0.016) 63.17%,rgba(0, 0, 0, 0.03) 66%,rgba(0, 0, 0, 0.06) 68.83%,rgba(0, 0, 0, 0.094) 71.67%,rgba(0, 0, 0, 0.133) 74.5%,rgba(0, 0, 0, 0.176) 77.33%,rgba(0, 0, 0, 0.224) 80.17%,rgba(0, 0, 0, 0.267) 83%,rgba(0, 0, 0, 0.306) 85.83%,rgba(0, 0, 0, 0.34) 88.67%,rgba(0, 0, 0, 0.37) 91.5%,rgba(0, 0, 0, 0.384) 94.33%,rgba(0, 0, 0, 0.396) 97.17%,rgba(0, 0, 0, 0.4) 100%)'
}
Vendored
+8 -1
View File
@@ -1,4 +1,4 @@
type Theme = 'light' | 'dark' | 'system';
type Theme = 'light' | 'dark';
interface TMDBPagination<T> {
page: number;
@@ -66,6 +66,13 @@ interface Show {
votes: number;
}
interface ShowState {
id: number;
favorite: boolean;
rated: boolean;
watchlist: boolean;
}
interface Person {
adult: boolean;
gender: number;