feat(show-type): global movie/series toggle, type-aware pages and search, ?type=tv in URL

This commit is contained in:
ner committed 2026-09-24 15:40:01 +03:00
1 parent 5b41dbca10
commit 0824090c6d
21 files changed
+384 -143

No files matched your search

@@ -1,9 +1,10 @@
'use client'; 'use client';
import { FC } from 'react'; import { FC } from 'react';
import { useAtomValue } from 'jotai';
import List from '@/components/List'; import List from '@/components/List';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'; import { showTypeAtom } from '@/components/ShowTypeToggle';
import useUsersShows from '@/hooks/useUsersShows'; import useUsersShows from '@/hooks/useUsersShows';
interface Props { interface Props {
@@ -13,36 +14,18 @@ interface Props {
} }
const UsersList: FC<Props> = ({ list, label, session }) => { const UsersList: FC<Props> = ({ list, label, session }) => {
const movies = useUsersShows({ list, showType: 'movie', session, mode: 'default' }); const showType = useAtomValue(showTypeAtom);
const series = useUsersShows({ list, showType: 'tv', session, mode: 'default' }); const { shows, fetchNextPage, isFetched } = useUsersShows({ list, showType, session, mode: 'default' });
const tabs = [
{ query: movies, title: 'Movies', key: 'movie' as const },
{ query: series, title: 'Series', key: 'tv' as const }
];
if (isFetched && !shows.length) {
return ( return (
<Tabs defaultValue='movie' className='flex w-full flex-col items-center'>
<TabsList className='grid w-full 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'> <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} There are no {showType === 'tv' ? 'series' : 'movies'} in your {label}
</div> </div>
) : (
<List shows={query.shows} fetchNextPage={query.fetchNextPage} />
)}
</TabsContent>
))}
</Tabs>
); );
}
return <List shows={shows} fetchNextPage={fetchNextPage} />;
}; };
export default UsersList; export default UsersList;
+30 -6
View File
@@ -1,32 +1,56 @@
'use client'; 'use client';
import { FC } from 'react'; import { FC, useRef } from 'react';
import { useAtom } from 'jotai';
import Preview from '@/components/Preview'; import Preview from '@/components/Preview';
import { showTypeAtom } from '@/components/ShowTypeToggle';
import Trending from '@/components/Trending'; import Trending from '@/components/Trending';
import { Skeleton } from '@/components/ui/skeleton';
import { generatePage } from '@/data/queries/random';
import Carousel from './components/Carousel'; import Carousel from './components/Carousel';
import useRandomMovie from './useRandomMovie'; import useRandomMovie from './useRandomMovie';
interface Props { interface Props {
page: number; page: number;
type: Show['type'];
} }
const Container: FC<Props> = ({ page }) => { const Container: FC<Props> = ({ page, type }) => {
const { movie, movies, onIndexChange, fetchNextPage } = useRandomMovie({ page }); const [showType] = useAtom(showTypeAtom);
const pagesRef = useRef<Record<Show['type'], number>>();
if (!pagesRef.current) {
pagesRef.current = {
movie: type === 'movie' ? page : generatePage('movie'),
tv: type === 'tv' ? page : generatePage('tv')
};
}
const { show, shows, onIndexChange, fetchNextPage, isLoading } = useRandomMovie({
page: pagesRef.current[showType],
type: showType
});
return ( return (
<div className='flex flex-1 flex-col'> <div className='flex flex-1 flex-col'>
<div className='xs:mb-4'> <div className='xs:mb-4'>
{show ? (
<Preview <Preview
show={movie} show={show}
className='rounded-md bg-background' className='rounded-md bg-background'
poster={<Carousel shows={movies} onIndexChange={onIndexChange} onEndReached={fetchNextPage} />} poster={
<Carousel key={showType} shows={shows} onIndexChange={onIndexChange} onEndReached={fetchNextPage} />
}
/> />
) : (
<Skeleton className='card-aspect-ratio static-aspect-ratio mx-auto rounded-lg' />
)}
<div className='h-2 w-full' /> <div className='h-2 w-full' />
</div> </div>
<div className='hidden w-full rounded-lg xs:block'> <div className='hidden w-full rounded-lg xs:block'>
<Trending showId={movie?.id} showType={movie?.type} /> <Trending showId={show?.id} showType={show?.type} />
<div className='h-2 w-full' /> <div className='h-2 w-full' />
</div> </div>
</div> </div>
+12 -6
View File
@@ -6,30 +6,36 @@ import JsonLd from '@/components/JsonLd';
import randomQuery, { generatePage } from '@/data/queries/random'; import randomQuery, { generatePage } from '@/data/queries/random';
import { SITE_URL, TITLE } from '@/env'; import { SITE_URL, TITLE } from '@/env';
import getQueryClient from '@/lib/queryClient'; import getQueryClient from '@/lib/queryClient';
import { parseShowType } from '@/lib/showType';
import Container from './container'; import Container from './container';
interface SearchParams {
type?: string;
}
export const metadata: Metadata = { export const metadata: Metadata = {
alternates: { canonical: '/' } alternates: { canonical: '/' }
}; };
const Random = async () => { const Random = async ({ searchParams }: { searchParams: SearchParams }) => {
const queryClient = getQueryClient(); const queryClient = getQueryClient();
const page = generatePage(); const type = parseShowType(searchParams.type);
const page = generatePage(type);
await queryClient.prefetchInfiniteQuery(randomQuery({ page })); await queryClient.prefetchInfiniteQuery(randomQuery({ page, type }));
return ( return (
<HydrationBoundary state={dehydrate(queryClient)}> <HydrationBoundary state={dehydrate(queryClient)}>
<JsonLd data={{ '@context': 'https://schema.org', '@type': 'WebSite', name: TITLE, url: SITE_URL }} /> <JsonLd data={{ '@context': 'https://schema.org', '@type': 'WebSite', name: TITLE, url: SITE_URL }} />
<h1 className='sr-only'>{TITLE} — Discover Your Next Favorite Movie</h1> <h1 className='sr-only'>{TITLE} — Discover Your Next Favorite Movie</h1>
<Container page={page} /> <Container page={page} type={type} />
<section className='sr-only'> <section className='sr-only'>
<h2>Discover your next favorite movie</h2> <h2>Discover your next favorite movie</h2>
<p> <p>
{TITLE} helps you decide what to watch: spin through random movie recommendations right on this page, browse {TITLE} helps you decide what to watch: spin through random movie and series recommendations right on this
the{' '} page, browse the{' '}
<Link className='underline underline-offset-2' href='/popular'> <Link className='underline underline-offset-2' href='/popular'>
most popular movies most popular movies
</Link>{' '} </Link>{' '}
+16 -10
View File
@@ -1,6 +1,6 @@
'use client'; 'use client';
import { startTransition, useCallback, useRef } from 'react'; import { startTransition, useCallback, useEffect, useRef } from 'react';
import { atom, getDefaultStore, useAtom } from 'jotai'; import { atom, getDefaultStore, useAtom } from 'jotai';
import randomQuery from '@/data/queries/random'; import randomQuery from '@/data/queries/random';
@@ -13,32 +13,38 @@ export const useSilentIndex = () => getDefaultStore().get(indexAtom);
interface Props { interface Props {
page: number; page: number;
type: Show['type'];
} }
const useRandomMovie = ({ page }: Props) => { const useRandomMovie = ({ page, type }: Props) => {
const [index, setIndex] = useAtom(indexAtom); const [index, setIndex] = useAtom(indexAtom);
const { shows: movies, fetchNextPage } = useInfiniteList({ useEffect(() => {
...randomQuery({ page }), setIndex(0);
}, [type, setIndex]);
const { shows, fetchNextPage, isLoading } = useInfiniteList({
...randomQuery({ page, type }),
mode: 'default', mode: 'default',
list: 'random' list: 'random'
}); });
const moviesRef = useRef(movies); const showsRef = useRef(shows);
moviesRef.current = movies; showsRef.current = shows;
if (movies.length && !movies[index]) { if (shows.length && !shows[index]) {
setIndex(0); setIndex(0);
} }
return { return {
movie: movies[index], show: shows[index],
movies, shows,
isLoading,
fetchNextPage, fetchNextPage,
onIndexChange: useCallback( onIndexChange: useCallback(
(index: number) => { (index: number) => {
analytics.randomShuffled({ index, showTitle: moviesRef.current[index]?.title ?? '' }); analytics.randomShuffled({ index, showTitle: showsRef.current[index]?.title ?? '' });
startTransition(() => setIndex(index)); startTransition(() => setIndex(index));
}, },
[setIndex] [setIndex]
+27 -12
View File
@@ -6,34 +6,49 @@ import popularQuery from '@/data/queries/popular';
import { TITLE } from '@/env'; import { TITLE } from '@/env';
import { itemList } from '@/lib/jsonLd'; import { itemList } from '@/lib/jsonLd';
import getQueryClient from '@/lib/queryClient'; import getQueryClient from '@/lib/queryClient';
import { parseShowType } from '@/lib/showType';
import Container from './container'; import Container from './container';
const HEADING = 'Popular Movies'; interface SearchParams {
type?: string;
}
const DESCRIPTION = `Check out the most popular movies right now on ${TITLE}. See what’s trending and don’t miss out on the latest hits.`; const heading = (type: Show['type']) => (type === 'tv' ? 'Popular Series' : 'Popular Movies');
export const metadata: Metadata = { const description = (type: Show['type']) =>
title: `${HEADING} | ${TITLE}`, type === 'tv'
description: DESCRIPTION, ? `Check out the most popular series right now on ${TITLE}. See what’s trending and don’t miss out on the latest hits.`
: `Check out the most popular movies right now on ${TITLE}. See what’s trending and don’t miss out on the latest hits.`;
export const generateMetadata = ({ searchParams }: { searchParams: SearchParams }): Metadata => {
const type = parseShowType(searchParams.type);
const title = heading(type);
const text = description(type);
return {
title: `${title} | ${TITLE}`,
description: text,
alternates: { canonical: '/popular' }, alternates: { canonical: '/popular' },
openGraph: { openGraph: {
type: 'website', type: 'website',
siteName: TITLE, siteName: TITLE,
title: HEADING, title,
description: DESCRIPTION, description: text,
url: '/popular' url: '/popular'
}, },
twitter: { twitter: {
title: HEADING, title,
description: DESCRIPTION description: text
} }
};
}; };
const Popular = async () => { const Popular = async ({ searchParams }: { searchParams: SearchParams }) => {
const queryClient = getQueryClient(); const queryClient = getQueryClient();
const query = popularQuery(); const type = parseShowType(searchParams.type);
const query = popularQuery({ type });
await queryClient.prefetchInfiniteQuery(query); await queryClient.prefetchInfiniteQuery(query);
@@ -44,7 +59,7 @@ const Popular = async () => {
return ( return (
<HydrationBoundary state={dehydrate(queryClient)}> <HydrationBoundary state={dehydrate(queryClient)}>
{Boolean(shows?.length) && <JsonLd data={itemList(shows!)} />} {Boolean(shows?.length) && <JsonLd data={itemList(shows!)} />}
<h1 className='sr-only'>{HEADING}</h1> <h1 className='sr-only'>{heading(type)}</h1>
<Container /> <Container />
</HydrationBoundary> </HydrationBoundary>
); );
+8 -1
View File
@@ -1,8 +1,15 @@
'use client'; 'use client';
import { useAtomValue } from 'jotai';
import { showTypeAtom } from '@/components/ShowTypeToggle';
import popularQuery from '@/data/queries/popular'; import popularQuery from '@/data/queries/popular';
import useInfiniteList from '@/hooks/useInfiniteList'; import useInfiniteList from '@/hooks/useInfiniteList';
const usePopular = () => useInfiniteList({ ...popularQuery(), mode: 'default', list: 'popular' }); const usePopular = () => {
const showType = useAtomValue(showTypeAtom);
return useInfiniteList({ ...popularQuery({ type: showType }), mode: 'default', list: 'popular' });
};
export default usePopular; export default usePopular;
+27 -12
View File
@@ -6,34 +6,49 @@ import popularQuery from '@/data/queries/popular';
import { TITLE } from '@/env'; import { TITLE } from '@/env';
import { itemList } from '@/lib/jsonLd'; import { itemList } from '@/lib/jsonLd';
import getQueryClient from '@/lib/queryClient'; import getQueryClient from '@/lib/queryClient';
import { parseShowType } from '@/lib/showType';
import Container from './container'; import Container from './container';
const HEADING = 'Top Rated Movies'; interface SearchParams {
type?: string;
}
const DESCRIPTION = `Discover the top-rated movies on ${TITLE}. Find the highest-rated films and make informed viewing choices.`; const heading = (type: Show['type']) => (type === 'tv' ? 'Top Rated Series' : 'Top Rated Movies');
export const metadata: Metadata = { const description = (type: Show['type']) =>
title: `${HEADING} | ${TITLE}`, type === 'tv'
description: DESCRIPTION, ? `Discover the top-rated series on ${TITLE}. Find the highest-rated shows and make informed viewing choices.`
: `Discover the top-rated movies on ${TITLE}. Find the highest-rated films and make informed viewing choices.`;
export const generateMetadata = ({ searchParams }: { searchParams: SearchParams }): Metadata => {
const type = parseShowType(searchParams.type);
const title = heading(type);
const text = description(type);
return {
title: `${title} | ${TITLE}`,
description: text,
alternates: { canonical: '/top' }, alternates: { canonical: '/top' },
openGraph: { openGraph: {
type: 'website', type: 'website',
siteName: TITLE, siteName: TITLE,
title: HEADING, title,
description: DESCRIPTION, description: text,
url: '/top' url: '/top'
}, },
twitter: { twitter: {
title: HEADING, title,
description: DESCRIPTION description: text
} }
};
}; };
const Top = async () => { const Top = async ({ searchParams }: { searchParams: SearchParams }) => {
const queryClient = getQueryClient(); const queryClient = getQueryClient();
const query = popularQuery({ sortBy: 'vote_average.desc' }); const type = parseShowType(searchParams.type);
const query = popularQuery({ sortBy: 'vote_average.desc', type });
await queryClient.prefetchInfiniteQuery(query); await queryClient.prefetchInfiniteQuery(query);
@@ -44,7 +59,7 @@ const Top = async () => {
return ( return (
<HydrationBoundary state={dehydrate(queryClient)}> <HydrationBoundary state={dehydrate(queryClient)}>
{Boolean(shows?.length) && <JsonLd data={itemList(shows!)} />} {Boolean(shows?.length) && <JsonLd data={itemList(shows!)} />}
<h1 className='sr-only'>{HEADING}</h1> <h1 className='sr-only'>{heading(type)}</h1>
<Container /> <Container />
</HydrationBoundary> </HydrationBoundary>
); );
+12 -2
View File
@@ -1,9 +1,19 @@
'use client'; 'use client';
import { useAtomValue } from 'jotai';
import { showTypeAtom } from '@/components/ShowTypeToggle';
import popularQuery from '@/data/queries/popular'; import popularQuery from '@/data/queries/popular';
import useInfiniteList from '@/hooks/useInfiniteList'; import useInfiniteList from '@/hooks/useInfiniteList';
const useTop = () => const useTop = () => {
useInfiniteList({ ...popularQuery({ sortBy: 'vote_average.desc' }), mode: 'default', list: 'top' }); const showType = useAtomValue(showTypeAtom);
return useInfiniteList({
...popularQuery({ sortBy: 'vote_average.desc', type: showType }),
mode: 'default',
list: 'top'
});
};
export default useTop; export default useTop;
@@ -0,0 +1,9 @@
'use client';
import { FC } from 'react';
import ShowTypeToggle from '@/components/ShowTypeToggle';
const Brand: FC = () => <ShowTypeToggle />;
export default Brand;
@@ -1,10 +1,12 @@
'use client'; 'use client';
import { DropdownMenuItem } from '@radix-ui/react-dropdown-menu'; import { DropdownMenuItem } from '@radix-ui/react-dropdown-menu';
import { useAtomValue } from 'jotai';
import { Menu } from 'lucide-react'; import { Menu } from 'lucide-react';
import Link from 'next/link'; import Link from 'next/link';
import { usePathname } from 'next/navigation'; import { usePathname } from 'next/navigation';
import { showTypeAtom } from '@/components/ShowTypeToggle';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { DropdownMenu, DropdownMenuContent, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'; import { DropdownMenu, DropdownMenuContent, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
import Nav from '@/components/ui/nav'; import Nav from '@/components/ui/nav';
@@ -12,8 +14,14 @@ import { cn } from '@/lib/utils';
import { paths } from './constants'; import { paths } from './constants';
const TYPE_AWARE_PATHS = ['/', '/popular', '/top', '/favorites', '/watchlist'];
const withShowType = (path: string, type: Show['type']) =>
type === 'tv' && TYPE_AWARE_PATHS.includes(path) ? `${path}?type=tv` : path;
export const MobileNavigation = () => { export const MobileNavigation = () => {
const currentPath = usePathname(); const currentPath = usePathname();
const showType = useAtomValue(showTypeAtom);
return ( return (
<div className='flex md:hidden'> <div className='flex md:hidden'>
@@ -26,7 +34,7 @@ export const MobileNavigation = () => {
<DropdownMenuContent className='flex w-44 flex-col gap-2 rounded-none rounded-bl-lg border-none p-2'> <DropdownMenuContent className='flex w-44 flex-col gap-2 rounded-none rounded-bl-lg border-none p-2'>
{paths.map(({ path, title }) => ( {paths.map(({ path, title }) => (
<DropdownMenuItem key={path} asChild> <DropdownMenuItem key={path} asChild>
<Link href={path} prefetch={path !== '/'}> <Link href={withShowType(path, showType)} prefetch={path !== '/'}>
<div> <div>
<Button className='relative w-full' variant={currentPath === path ? 'default' : 'outline'}> <Button className='relative w-full' variant={currentPath === path ? 'default' : 'outline'}>
{title} {title}
@@ -43,12 +51,13 @@ export const MobileNavigation = () => {
export const DesktopNavigation = () => { export const DesktopNavigation = () => {
const currentPath = usePathname(); const currentPath = usePathname();
const showType = useAtomValue(showTypeAtom);
const active = paths.find(({ path }) => path === currentPath); const active = paths.find(({ path }) => path === currentPath);
return ( return (
<Nav tabs={paths} active={active}> <Nav tabs={paths} active={active}>
{({ path, title }) => ( {({ path, title }) => (
<Link href={path} prefetch={path !== '/'}> <Link href={withShowType(path, showType)} prefetch={path !== '/'}>
<div>{title}</div> <div>{title}</div>
</Link> </Link>
)} )}
+8 -37
View File
@@ -2,14 +2,15 @@
import { ChangeEvent, MutableRefObject, useRef, useState } from 'react'; import { ChangeEvent, MutableRefObject, useRef, useState } from 'react';
import { create } from 'react-modal-promise'; import { create } from 'react-modal-promise';
import { useAtomValue } from 'jotai';
import { Search as SearchIcon, X } from 'lucide-react'; import { Search as SearchIcon, X } from 'lucide-react';
import List from '@/components/List'; import List from '@/components/List';
import { showTypeAtom } from '@/components/ShowTypeToggle';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import ButtonsGroup from '@/components/ui/buttons-group'; import ButtonsGroup from '@/components/ui/buttons-group';
import { Modal } from '@/components/ui/dialog'; import { Modal } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input'; import { Input } from '@/components/ui/input';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import useDistinctUntilChanged from '@/hooks/useDistinctUntilChanged'; import useDistinctUntilChanged from '@/hooks/useDistinctUntilChanged';
import useSearch from './useSearch'; import useSearch from './useSearch';
@@ -19,13 +20,13 @@ export const showSearchModal = create(({ onResolve }) => {
const scrollRef = useRef<HTMLDivElement>(null) as MutableRefObject<HTMLDivElement>; const scrollRef = useRef<HTMLDivElement>(null) as MutableRefObject<HTMLDivElement>;
const inputRef = useRef<HTMLInputElement>(null); const inputRef = useRef<HTMLInputElement>(null);
const isFetchedRef = useRef(false); const isFetchedRef = useRef(false);
const showType = useAtomValue(showTypeAtom);
const query = useDistinctUntilChanged(title); const query = useDistinctUntilChanged(title);
const settledTitle = useDistinctUntilChanged(title, 1000); const settledTitle = useDistinctUntilChanged(title, 1000);
const settled = title === settledTitle; const settled = title === settledTitle;
const movies = useSearch({ query, type: 'movie', settled }); const search = useSearch({ query, type: showType, settled });
const series = useSearch({ query, type: 'tv', settled });
const handleChangeTitle = ({ target: { value } }: ChangeEvent<HTMLInputElement>) => setTitle(value); const handleChangeTitle = ({ target: { value } }: ChangeEvent<HTMLInputElement>) => setTitle(value);
@@ -34,12 +35,7 @@ export const showSearchModal = create(({ onResolve }) => {
inputRef.current?.focus(); inputRef.current?.focus();
}; };
const tabs = [ if (!isFetchedRef.current && search.isFetched) {
{ title: 'Movies', data: movies, type: 'movie' as const },
{ title: 'Series', data: series, type: 'tv' as const }
].filter(({ data: { shows } }) => shows.length);
if (!isFetchedRef.current && movies.isFetched && series.isFetched) {
isFetchedRef.current = true; isFetchedRef.current = true;
} }
@@ -69,39 +65,14 @@ export const showSearchModal = create(({ onResolve }) => {
</Button> </Button>
</ButtonsGroup> </ButtonsGroup>
</div> </div>
{isFetchedRef.current && ( {isFetchedRef.current && search.shows.length > 0 && (
<div className='px-2'> <div className='px-2'>
{tabs.length > 1 ? (
<Tabs defaultValue='movie'>
<TabsList className='grid w-full grid-cols-2'>
{tabs.map(({ type, title }) => (
<TabsTrigger key={type} value={type}>
{title}
</TabsTrigger>
))}
</TabsList>
{tabs.map(({ data: { shows, fetchNextPage }, type }) => (
<TabsContent value={type} key={type}>
<List <List
shows={shows} shows={search.shows}
customScrollParent={scrollRef.current} customScrollParent={scrollRef.current}
fetchNextPage={fetchNextPage} fetchNextPage={search.fetchNextPage}
onPreviewClose={onResolve} onPreviewClose={onResolve}
/> />
</TabsContent>
))}
</Tabs>
) : (
tabs.map(({ data: { shows, fetchNextPage }, type }) => (
<List
key={type}
shows={shows}
customScrollParent={scrollRef.current}
fetchNextPage={fetchNextPage}
onPreviewClose={onResolve}
/>
))
)}
</div> </div>
)} )}
</Modal> </Modal>
+2 -6
View File
@@ -1,10 +1,8 @@
import { FC } from 'react'; import { FC } from 'react';
import Link from 'next/link';
import { Badge } from '@/components/ui/badge';
import { TITLE } from '@/env';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import Brand from './components/Brand';
import { DesktopNavigation, MobileNavigation } from './components/Navigation'; import { DesktopNavigation, MobileNavigation } from './components/Navigation';
import ToggleSearch from './components/Search'; import ToggleSearch from './components/Search';
import ToggleTheme from './components/ThemeToggle'; import ToggleTheme from './components/ThemeToggle';
@@ -23,9 +21,7 @@ const Header: FC<Props> = ({ className }) => (
> >
<div className='container'> <div className='container'>
<div className='flex items-center justify-between gap-2 xs:flex-nowrap'> <div className='flex items-center justify-between gap-2 xs:flex-nowrap'>
<Link shallow href='/'> <Brand />
<Badge className='cursor-pointer whitespace-nowrap text-[15px] font-normal leading-[18px]'>{TITLE}</Badge>
</Link>
<DesktopNavigation /> <DesktopNavigation />
<div className='flex items-center gap-2'> <div className='flex items-center gap-2'>
<ToggleSearch /> <ToggleSearch />
+110
View File
@@ -0,0 +1,110 @@
'use client';
import { FC, useEffect } from 'react';
import * as DropdownMenuPrimitive from '@radix-ui/react-dropdown-menu';
import { atom, useAtom } from 'jotai';
import { Check, ChevronDown, Clapperboard, LucideIcon, Tv } from 'lucide-react';
import Link from 'next/link';
import analytics from '@/lib/analytics';
import { parseShowType } from '@/lib/showType';
import { cn } from '@/lib/utils';
export const showTypeAtom = atom<Show['type']>('movie');
interface Option {
value: Show['type'];
label: string;
icon: LucideIcon;
}
const options: Option[] = [
{ value: 'movie', label: 'Movie', icon: Clapperboard },
{ value: 'tv', label: 'Series', icon: Tv }
];
interface Props {
className?: string;
}
const ShowTypeToggle: FC<Props> = ({ className }) => {
const [value, setValue] = useAtom(showTypeAtom);
useEffect(() => {
const urlType = parseShowType(new URLSearchParams(window.location.search).get('type'));
if (urlType !== value) setValue(urlType);
}, [value, setValue]);
const current = options.find(({ value: optionValue }) => optionValue === value) ?? options[0];
const handleChange = (next: Show['type']) => {
analytics.randomTypeChanged({ type: next });
setValue(next);
const url = new URL(window.location.href);
if (next === 'tv') url.searchParams.set('type', 'tv');
else url.searchParams.delete('type');
window.history.replaceState(null, '', url);
};
return (
<DropdownMenuPrimitive.Root>
<DropdownMenuPrimitive.Trigger asChild>
<span
aria-label={`Watch Next: ${current.label}`}
className={cn(
'inline-flex h-6 cursor-pointer items-center whitespace-nowrap rounded-full bg-primary text-primary-foreground transition-opacity hover:opacity-90',
className
)}
>
<Link
href={value === 'tv' ? '/?type=tv' : '/'}
onPointerDown={(event) => event.stopPropagation()}
onClick={(event) => event.stopPropagation()}
className='pl-2.5 pr-1.5 text-[15px] font-normal leading-[18px]'
>
Watch Next
</Link>
<span aria-hidden className='h-4 w-px bg-primary-foreground/40' />
<span className='flex items-center gap-1.5 pl-1.5 pr-2.5 text-[15px] font-normal leading-[18px]'>
<span className='text-primary-foreground/70'>{current.label}</span>
<ChevronDown className='size-3.5 text-primary-foreground/70' />
</span>
</span>
</DropdownMenuPrimitive.Trigger>
<DropdownMenuPrimitive.Portal>
<DropdownMenuPrimitive.Content
align='start'
sideOffset={8}
className={cn(
'z-50 w-60 rounded-2xl border border-border/60 bg-popover p-2 text-popover-foreground shadow-xl',
'data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
'data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=top]:slide-in-from-bottom-2'
)}
>
<DropdownMenuPrimitive.RadioGroup value={value} onValueChange={(next) => handleChange(next as Show['type'])}>
{options.map(({ value: optionValue, label, icon: Icon }) => (
<DropdownMenuPrimitive.RadioItem
key={optionValue}
value={optionValue}
className={cn(
'flex w-full cursor-pointer items-center gap-3 rounded-xl px-3 py-2.5 text-lg outline-none transition-colors',
'focus:bg-secondary data-[state=checked]:bg-secondary'
)}
>
<Icon className='size-5 shrink-0' />
<span>{label}</span>
<DropdownMenuPrimitive.ItemIndicator className='ml-auto'>
<Check className='size-5' />
</DropdownMenuPrimitive.ItemIndicator>
</DropdownMenuPrimitive.RadioItem>
))}
</DropdownMenuPrimitive.RadioGroup>
</DropdownMenuPrimitive.Content>
</DropdownMenuPrimitive.Portal>
</DropdownMenuPrimitive.Root>
);
};
export default ShowTypeToggle;
+23
View File
@@ -20,3 +20,26 @@ export const tabs = [
type: 'recommendations' type: 'recommendations'
} }
]; ];
export const seriesTabs = [
{
title: 'Apple',
type: 'apple'
},
{
title: 'Netflix',
type: 'netflix'
},
{
title: 'HBO',
type: 'hbo'
},
{
title: 'Similar',
type: 'similar'
},
{
title: 'Recommendations',
type: 'recommendations'
}
];
+21 -6
View File
@@ -1,13 +1,13 @@
'use client'; 'use client';
import { FC, useState } from 'react'; import { FC, useEffect, useMemo, useState } from 'react';
import useSimilar from '@/components/Trending/useSimilar'; import useSimilar from '@/components/Trending/useSimilar';
import Nav from '@/components/ui/nav'; import Nav from '@/components/ui/nav';
import analytics from '@/lib/analytics'; import analytics from '@/lib/analytics';
import Gallery from './components/Gallery'; import Gallery from './components/Gallery';
import { tabs as initialTabs } from './constants'; import { seriesTabs, tabs as movieTabs } from './constants';
import useTrending from './useTrending'; import useTrending from './useTrending';
interface Props { interface Props {
@@ -17,13 +17,28 @@ interface Props {
} }
const Trending: FC<Props> = ({ showId, showType, preview }) => { const Trending: FC<Props> = ({ showId, showType, preview }) => {
const tabs = preview ? initialTabs.filter(({ type }) => ['similar', 'recommendations'].includes(type)) : initialTabs; const isSeries = showType === 'tv';
const tabs = useMemo(
() =>
(isSeries ? seriesTabs : movieTabs).filter(({ type }) =>
preview ? ['similar', 'recommendations'].includes(type) : true
),
[isSeries, preview]
);
const [active, setActive] = useState(tabs[0]); const [active, setActive] = useState(tabs[0]);
const streaming = useTrending({ type: 'streaming', enabled: !preview }); useEffect(() => {
setActive(tabs[0]);
}, [tabs]);
const streaming = useTrending({ type: 'streaming', enabled: !preview && !isSeries });
const trending = useTrending({ type: 'trending', enabled: active.type === 'trending' }); const trending = useTrending({ type: 'trending', enabled: active.type === 'trending' });
const theater = useTrending({ type: 'theater', enabled: active.type === 'theater' }); const theater = useTrending({ type: 'theater', enabled: active.type === 'theater' });
const apple = useTrending({ type: 'apple', enabled: isSeries && !preview });
const netflix = useTrending({ type: 'netflix', enabled: isSeries && active.type === 'netflix' });
const hbo = useTrending({ type: 'hbo', enabled: isSeries && active.type === 'hbo' });
const similar = useSimilar({ const similar = useSimilar({
showId, showId,
showType, showType,
@@ -37,10 +52,10 @@ const Trending: FC<Props> = ({ showId, showType, preview }) => {
enabled: active.type === 'recommendations' enabled: active.type === 'recommendations'
}); });
const tab = { trending, streaming, theater, similar, recommendations }[active.type]!; const tab = { streaming, trending, theater, apple, netflix, hbo, similar, recommendations }[active.type]!;
return ( return (
(streaming.isFetched || similar.isFetched) && ( (streaming.isFetched || apple.isFetched || similar.isFetched) && (
<div className='hidden md:block'> <div className='hidden md:block'>
<Nav <Nav
tabs={tabs} tabs={tabs}
+1 -1
View File
@@ -30,7 +30,7 @@ const Hint: FC<Props> = ({ lines, children, className }) => {
role='tooltip' role='tooltip'
aria-hidden={!open} aria-hidden={!open}
className={cn( className={cn(
'pointer-events-none absolute left-1/2 top-full z-10 mt-1.5 -translate-x-1/2 whitespace-nowrap rounded-md border bg-popover px-2 py-1 text-xs text-popover-foreground shadow-md transition-opacity', 'pointer-events-none absolute left-0 top-full z-10 mt-1.5 whitespace-nowrap rounded-md border bg-popover px-2 py-1 text-xs text-popover-foreground shadow-md transition-opacity md:left-1/2 md:-translate-x-1/2',
open ? 'opacity-100' : 'opacity-0' open ? 'opacity-100' : 'opacity-0'
)} )}
> >
+5 -4
View File
@@ -3,14 +3,15 @@ import mapMoviesSeriesResponseToShows from '../dto/Show';
export type PopularQueryProps = { export type PopularQueryProps = {
sortBy?: string; sortBy?: string;
type?: Show['type'];
}; };
const popularQuery = ({ sortBy = 'popularity.desc' }: PopularQueryProps = {}) => ({ const popularQuery = ({ sortBy = 'popularity.desc', type = 'movie' }: PopularQueryProps = {}) => ({
queryKey: ['popular', sortBy], queryKey: ['popular', type, sortBy],
initialPageParam: '1', initialPageParam: '1',
queryFn: ({ pageParam = '1' }: { pageParam?: string }) => queryFn: ({ pageParam = '1' }: { pageParam?: string }) =>
movieAdvisor movieAdvisor
.get<TMDBPagination<Movie>>('/discover/movie', { .get<TMDBPagination<Movie> | TMDBPagination<Series>>(`/discover/${type}`, {
params: { params: {
page: pageParam, page: pageParam,
sort_by: sortBy, sort_by: sortBy,
@@ -19,7 +20,7 @@ const popularQuery = ({ sortBy = 'popularity.desc' }: PopularQueryProps = {}) =>
'vote_average.gte': 5 'vote_average.gte': 5
} }
}) })
.then(mapMoviesSeriesResponseToShows) .then((response) => mapMoviesSeriesResponseToShows(response, type))
}); });
export default popularQuery; export default popularQuery;
+29 -11
View File
@@ -3,29 +3,47 @@ import { createUniqueRandomGenerator } from '@/lib/utils';
import movieAdvisor from '../clients/movieAdvisor'; import movieAdvisor from '../clients/movieAdvisor';
import mapMoviesSeriesResponseToShows from '../dto/Show'; import mapMoviesSeriesResponseToShows from '../dto/Show';
const TOTAL_PAGES = 400; // Pools are bounded by the discover API total_pages (movie: ~500+, tv: ~77).
const TOTAL_PAGES: Record<Show['type'], number> = { movie: 400, tv: 70 };
export const generatePage = createUniqueRandomGenerator(TOTAL_PAGES); const generators = {} as Record<Show['type'], () => number>;
const getGenerator = (type: Show['type']) => (generators[type] ??= createUniqueRandomGenerator(TOTAL_PAGES[type]));
export const generatePage = (type: Show['type'] = 'movie') => getGenerator(type)();
export type RandomQueryProps = { export type RandomQueryProps = {
page: number; page: number;
type: Show['type'];
}; };
const randomQuery = ({ page }: RandomQueryProps) => ({ const randomQuery = ({ page, type }: RandomQueryProps) => ({
queryKey: ['random-movie'], queryKey: ['random-movie', type],
initialPageParam: page.toString(), initialPageParam: page.toString(),
getNextPageParam: () => generatePage().toString(), getNextPageParam: () => generatePage(type).toString(),
queryFn: ({ pageParam }: { pageParam: string }) => queryFn: async ({ pageParam }: { pageParam: string }) => {
movieAdvisor const params = {
.get<TMDBPagination<Movie>>('/discover/movie', {
params: {
'vote_count.gte': 300, 'vote_count.gte': 300,
sort_by: 'popularity.desc', sort_by: 'popularity.desc',
with_origin_country: 'UA|GB|JP|AU|US|IT|DE|FR', with_origin_country: 'UA|GB|JP|AU|US|IT|DE|FR',
page: pageParam page: pageParam
};
const data = await movieAdvisor.get<TMDBPagination<Movie> | TMDBPagination<Series>>(`/discover/${type}`, {
params
});
if (data.results.length || !data.total_pages) {
return mapMoviesSeriesResponseToShows(data, type);
}
// Out-of-range random page: TMDB returns empty results, retry with a valid page
const fallback = await movieAdvisor.get<TMDBPagination<Movie> | TMDBPagination<Series>>(`/discover/${type}`, {
params: { ...params, page: Math.floor(Math.random() * data.total_pages) + 1 }
});
return mapMoviesSeriesResponseToShows(fallback, type);
} }
})
.then(mapMoviesSeriesResponseToShows)
}); });
export default randomQuery; export default randomQuery;
+21 -1
View File
@@ -2,14 +2,34 @@ import movieAdvisor from '../clients/movieAdvisor';
import mapMoviesSeriesResponseToShows from '../dto/Show'; import mapMoviesSeriesResponseToShows from '../dto/Show';
export type TrendingQueryProps = { export type TrendingQueryProps = {
type: 'trending' | 'streaming' | 'theater'; type: 'trending' | 'streaming' | 'theater' | 'apple' | 'netflix' | 'hbo';
enabled?: boolean; enabled?: boolean;
}; };
const TV_WATCH_PROVIDERS: Partial<Record<TrendingQueryProps['type'], number>> = {
apple: 350,
netflix: 8,
hbo: 1899
};
const trendingQuery = ({ type, enabled }: TrendingQueryProps) => ({ const trendingQuery = ({ type, enabled }: TrendingQueryProps) => ({
enabled, enabled,
queryKey: ['trending', `type-${type}`], queryKey: ['trending', `type-${type}`],
queryFn: () => { queryFn: () => {
const provider = TV_WATCH_PROVIDERS[type];
if (provider) {
return movieAdvisor
.get<TMDBPagination<Series>>('/discover/tv', {
params: {
watch_region: 'US',
with_watch_monetization_types: 'flatrate',
with_watch_providers: provider
}
})
.then((response) => mapMoviesSeriesResponseToShows(response, 'tv').results);
}
const params: Record<string, string | number> = {}; const params: Record<string, string | number> = {};
if (type !== 'trending') { if (type !== 'trending') {
+1
View File
@@ -7,6 +7,7 @@ export type AnalyticsEvents = {
person_viewed: { personId: string; personName: string }; person_viewed: { personId: string; personName: string };
list_loaded_more: { list: ListName; page: number }; list_loaded_more: { list: ListName; page: number };
random_shuffled: { index: number; showTitle: string }; random_shuffled: { index: number; showTitle: string };
random_type_changed: { type: Show['type'] };
search_performed: { query: string; showType: Show['type']; results: number }; search_performed: { query: string; showType: Show['type']; results: number };
gallery_tab_changed: { tab: string }; gallery_tab_changed: { tab: string };
+2
View File
@@ -0,0 +1,2 @@
export const parseShowType = (value: string | string[] | null | undefined): Show['type'] =>
value === 'tv' ? 'tv' : 'movie';