fix: random movie index preservation
This commit is contained in:
1 parent
9dc731299f
commit
9e4e1d62fd
7 files changed
+78
-74
No files matched your search
@@ -1,30 +1,23 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { forwardRef, useEffect, useLayoutEffect, useRef } from 'react';
|
import { forwardRef, useEffect, useLayoutEffect, useRef } from 'react';
|
||||||
import { StateSnapshot, Virtuoso, VirtuosoHandle, VirtuosoProps } from 'react-virtuoso';
|
import { Virtuoso, VirtuosoHandle, VirtuosoProps } from 'react-virtuoso';
|
||||||
|
|
||||||
import Card from '@/components/Movie/Card';
|
import Card from '@/components/Movie/Card';
|
||||||
|
|
||||||
let snapshot: StateSnapshot;
|
|
||||||
|
|
||||||
const Carousel = ({
|
const Carousel = ({
|
||||||
index,
|
index,
|
||||||
movies,
|
movies,
|
||||||
onIndexChange
|
onIndexChange,
|
||||||
|
onEndReached
|
||||||
}: {
|
}: {
|
||||||
index: number;
|
index: number;
|
||||||
movies?: Movie[];
|
movies?: Movie[];
|
||||||
onIndexChange: (index: number) => void;
|
onIndexChange: (index: number) => void;
|
||||||
|
onEndReached: () => void;
|
||||||
}) => {
|
}) => {
|
||||||
const ref = useRef<VirtuosoHandle>(null);
|
const ref = useRef<VirtuosoHandle>(null);
|
||||||
|
const initialIndex = useRef(index);
|
||||||
useEffect(() => {
|
|
||||||
const virtuoso = ref.current;
|
|
||||||
|
|
||||||
if (!virtuoso) return;
|
|
||||||
|
|
||||||
return () => virtuoso.getState((state) => (snapshot = state));
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const scrollTo = ({ key }: globalThis.KeyboardEvent) => {
|
const scrollTo = ({ key }: globalThis.KeyboardEvent) => {
|
||||||
@@ -52,11 +45,12 @@ const Carousel = ({
|
|||||||
ref={ref}
|
ref={ref}
|
||||||
data={movies}
|
data={movies}
|
||||||
context={onIndexChange}
|
context={onIndexChange}
|
||||||
horizontalDirection
|
endReached={onEndReached}
|
||||||
|
initialTopMostItemIndex={initialIndex.current}
|
||||||
components={components}
|
components={components}
|
||||||
|
horizontalDirection
|
||||||
skipAnimationFrameInResizeObserver
|
skipAnimationFrameInResizeObserver
|
||||||
increaseViewportBy={1000}
|
increaseViewportBy={1000}
|
||||||
restoreStateFrom={snapshot}
|
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -6,14 +6,14 @@ import Carousel from './components/Carousel';
|
|||||||
import useRandomMovie from './useRandomMovie';
|
import useRandomMovie from './useRandomMovie';
|
||||||
|
|
||||||
export default function Container() {
|
export default function Container() {
|
||||||
const { movies, movie, index, onIndexChange } = useRandomMovie();
|
const { movies, movie, index, onIndexChange, fetchNextPage } = useRandomMovie();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<Preview
|
<Preview
|
||||||
movie={movie}
|
movie={movie}
|
||||||
className='bg-background rounded-md'
|
className='bg-background rounded-md'
|
||||||
card={<Carousel index={index} movies={movies} onIndexChange={onIndexChange} />}
|
card={<Carousel index={index} movies={movies} onIndexChange={onIndexChange} onEndReached={fetchNextPage} />}
|
||||||
/>
|
/>
|
||||||
<div className='w-full h-2' />
|
<div className='w-full h-2' />
|
||||||
</>
|
</>
|
||||||
|
|||||||
+5
-1
@@ -8,7 +8,11 @@ import Container from './container';
|
|||||||
export default async function Random() {
|
export default async function Random() {
|
||||||
const queryClient = getQueryClient();
|
const queryClient = getQueryClient();
|
||||||
|
|
||||||
await queryClient.prefetchQuery({ queryKey: ['random-movie'], queryFn: () => randomMovies({ filters: {} }) });
|
await queryClient.prefetchInfiniteQuery({
|
||||||
|
queryKey: ['random-movie'],
|
||||||
|
queryFn: () => randomMovies(),
|
||||||
|
initialPageParam: '1'
|
||||||
|
});
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<HydrationBoundary state={dehydrate(queryClient)}>
|
<HydrationBoundary state={dehydrate(queryClient)}>
|
||||||
|
|||||||
@@ -1,52 +1,43 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { startTransition, useCallback, useState } from 'react';
|
import { startTransition, useCallback, useMemo, useState } from 'react';
|
||||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
import { useInfiniteQuery } from '@tanstack/react-query';
|
||||||
|
|
||||||
|
import useSessionRef from '@/hooks/useSessionRef';
|
||||||
import { randomMovies } from '@/lib/api';
|
import { randomMovies } from '@/lib/api';
|
||||||
|
|
||||||
const UPDATE_RATE = 10;
|
|
||||||
|
|
||||||
let previousIndex: number = 0;
|
|
||||||
|
|
||||||
const useRandomMovie = () => {
|
const useRandomMovie = () => {
|
||||||
const queryClient = useQueryClient();
|
const [indexRef, setIndexRef] = useSessionRef('random-movie-index', 0);
|
||||||
const [index, setIndex] = useState(previousIndex);
|
const [index, setIndex] = useState(indexRef.current);
|
||||||
|
|
||||||
const { data: movies, refetch } = useQuery({
|
const { data, fetchNextPage } = useInfiniteQuery({
|
||||||
queryKey: ['random-movie'],
|
queryKey: ['random-movie'],
|
||||||
queryFn: () => randomMovies({ filters: {} }),
|
queryFn: () => randomMovies(),
|
||||||
structuralSharing(_, newData) {
|
getNextPageParam: () => '',
|
||||||
const uniqueIds: Record<string, number> = {};
|
initialPageParam: ''
|
||||||
const current = queryClient.getQueryData<Movie[]>(['random-movie']) || [];
|
|
||||||
const next = Array.isArray(newData) ? newData : [newData];
|
|
||||||
|
|
||||||
return [...current, ...next].reduce((unique, movie) => {
|
|
||||||
if (uniqueIds[movie.id]) return unique;
|
|
||||||
|
|
||||||
uniqueIds[movie.id] = movie.id;
|
|
||||||
unique.push(movie);
|
|
||||||
|
|
||||||
return unique;
|
|
||||||
}, [] as Movie[]);
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const movies = useMemo(
|
||||||
|
() =>
|
||||||
|
data?.pages.reduce((movies, page) => {
|
||||||
|
movies.push(...page);
|
||||||
|
return movies;
|
||||||
|
}, []),
|
||||||
|
[data]
|
||||||
|
);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
index,
|
||||||
movies,
|
movies,
|
||||||
movie: movies?.[index],
|
movie: movies?.[index],
|
||||||
hasPrevious: index > 0,
|
fetchNextPage,
|
||||||
onIndexChange: useCallback(
|
onIndexChange: useCallback(
|
||||||
(index: number) => {
|
(index: number) => {
|
||||||
if ((index && index % UPDATE_RATE === 0) || movies!.length < UPDATE_RATE) {
|
setIndexRef(index);
|
||||||
refetch();
|
|
||||||
}
|
|
||||||
previousIndex = index;
|
|
||||||
startTransition(() => setIndex(index));
|
startTransition(() => setIndex(index));
|
||||||
},
|
},
|
||||||
[movies]
|
[setIndexRef]
|
||||||
),
|
)
|
||||||
index
|
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
+1
-2
@@ -6,7 +6,6 @@ import { cookies } from 'next/headers';
|
|||||||
const poppins = Poppins({ subsets: ['latin'], weight: '400' });
|
const poppins = Poppins({ subsets: ['latin'], weight: '400' });
|
||||||
|
|
||||||
import Header from '@/components/Header';
|
import Header from '@/components/Header';
|
||||||
import { cn } from '@/lib/utils';
|
|
||||||
import Providers from '@/providers';
|
import Providers from '@/providers';
|
||||||
|
|
||||||
import '@/styles/index.css';
|
import '@/styles/index.css';
|
||||||
@@ -38,7 +37,7 @@ export default function RootLayout({ children }: { children: ReactNode }) {
|
|||||||
<div className='sticky top-0 z-20'>
|
<div className='sticky top-0 z-20'>
|
||||||
<Header />
|
<Header />
|
||||||
</div>
|
</div>
|
||||||
<main className='px-2 max-w-[1240px] mx-auto'>{children}</main>
|
<main className='px-2 mx-auto max-w-[1240px]'>{children}</main>
|
||||||
</Providers>
|
</Providers>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+21
-23
@@ -3,6 +3,7 @@
|
|||||||
import server from '@/network/server';
|
import server from '@/network/server';
|
||||||
|
|
||||||
import filterUnknownMovies from '../filterUnknownMovies';
|
import filterUnknownMovies from '../filterUnknownMovies';
|
||||||
|
import { createUniqueRandomGenerator } from '../utils';
|
||||||
|
|
||||||
import pirateBay from './parsers/pirate-bay';
|
import pirateBay from './parsers/pirate-bay';
|
||||||
|
|
||||||
@@ -23,13 +24,15 @@ export const search = async ({
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
export const randomMovies = async ({ filters }: { filters: Partial<Filters> }): Promise<Movie[]> => {
|
const generatePage = createUniqueRandomGenerator(500);
|
||||||
|
|
||||||
|
export const randomMovies = async ({ filters }: { filters: Partial<Filters> } = { filters: {} }): Promise<Movie[]> => {
|
||||||
return server
|
return server
|
||||||
.get<MovieDBResponse>('/discover/movie', {
|
.get<MovieDBResponse>('/discover/movie', {
|
||||||
params: {
|
params: {
|
||||||
sort_by: 'popularity.desc',
|
sort_by: 'popularity.desc',
|
||||||
with_origin_country: 'UA|GB|AU|US|IT|DE|FR',
|
with_origin_country: 'UA|GB|JP|AU|US|IT|DE|FR',
|
||||||
page: Math.floor(Math.random() * 499) + 1,
|
page: generatePage(),
|
||||||
with_genres: filters.genres?.join('|'),
|
with_genres: filters.genres?.join('|'),
|
||||||
'vote_average.gte': filters.score?.[0],
|
'vote_average.gte': filters.score?.[0],
|
||||||
'vote_average.lte': filters.score?.[1],
|
'vote_average.lte': filters.score?.[1],
|
||||||
@@ -96,7 +99,7 @@ export const similarMovies = async ({
|
|||||||
};
|
};
|
||||||
|
|
||||||
export const genres = async (): Promise<IDName[]> => {
|
export const genres = async (): Promise<IDName[]> => {
|
||||||
return server.get('/genre/movie/list').then((response) => (response as unknown as { genres: IDName[] }).genres);
|
return server.get<{ genres: IDName[] }>('/genre/movie/list').then((data) => data.genres);
|
||||||
};
|
};
|
||||||
|
|
||||||
export const credits = async ({
|
export const credits = async ({
|
||||||
@@ -106,24 +109,21 @@ export const credits = async ({
|
|||||||
movieId: number;
|
movieId: number;
|
||||||
type?: ShowType;
|
type?: ShowType;
|
||||||
}): Promise<Array<Actor>> => {
|
}): Promise<Array<Actor>> => {
|
||||||
'use server';
|
return server
|
||||||
|
.get<{ cast: Array<unknown> }>(`/${type}/${movieId}/${type === 'tv' ? 'aggregate_credits' : 'credits'}`)
|
||||||
return server.get(`/${type}/${movieId}/${type === 'tv' ? 'aggregate_credits' : 'credits'}`).then((response) => {
|
.then((data) => {
|
||||||
const data = (response as unknown as { cast: Array<unknown> }).cast;
|
if (type === 'tv') {
|
||||||
if (type === 'tv') {
|
return data.cast.map((item) => {
|
||||||
return data.map((item) => {
|
const actor = item as AggregatedActor;
|
||||||
const actor = item as AggregatedActor;
|
const [role] = actor.roles || [{}];
|
||||||
const [role] = actor.roles || [{}];
|
return { ...actor, ...role } as unknown as Actor;
|
||||||
return { ...actor, ...role } as unknown as Actor;
|
});
|
||||||
});
|
}
|
||||||
}
|
return data.cast as Array<Actor>;
|
||||||
return data as Array<Actor>;
|
});
|
||||||
});
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const torrents = async ({ query, order, seeders }: { query: string; seeders?: number; order: number }) => {
|
export const torrents = async ({ query, order, seeders }: { query: string; seeders?: number; order: number }) => {
|
||||||
'use server';
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const torrents = await pirateBay.search({
|
const torrents = await pirateBay.search({
|
||||||
query,
|
query,
|
||||||
@@ -136,13 +136,11 @@ export const torrents = async ({ query, order, seeders }: { query: string; seede
|
|||||||
};
|
};
|
||||||
|
|
||||||
export const trailers = async ({ movieId, type }: { movieId: number; type?: ShowType }): Promise<Trailer[]> => {
|
export const trailers = async ({ movieId, type }: { movieId: number; type?: ShowType }): Promise<Trailer[]> => {
|
||||||
'use server';
|
|
||||||
|
|
||||||
return server
|
return server
|
||||||
.get(`/${type}/${movieId}/videos`, {
|
.get<{ id: number; results: Trailer[] }>(`/${type}/${movieId}/videos`, {
|
||||||
params: {
|
params: {
|
||||||
language: 'en-US'
|
language: 'en-US'
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.then((response) => (response as unknown as { id: number; results: Trailer[] }).results);
|
.then((data) => data.results);
|
||||||
};
|
};
|
||||||
@@ -15,3 +15,21 @@ export const mapFilters = (filters: Record<string, string>) => {
|
|||||||
return {};
|
return {};
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const createUniqueRandomGenerator = (max: number) => {
|
||||||
|
const numbers = Array.from({ length: max }, (_, i) => i + 1);
|
||||||
|
|
||||||
|
for (let i = numbers.length - 1; i > 0; i--) {
|
||||||
|
const j = Math.floor(Math.random() * (i + 1));
|
||||||
|
[numbers[i], numbers[j]] = [numbers[j], numbers[i]];
|
||||||
|
}
|
||||||
|
|
||||||
|
let index = 0;
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
if (index >= numbers.length) {
|
||||||
|
index = 0;
|
||||||
|
}
|
||||||
|
return numbers[index++];
|
||||||
|
};
|
||||||
|
};
|
||||||
Reference in new issue
Block a user