refactoring: first render improvements

This commit is contained in:
ner committed 2024-10-21 18:57:49 +03:00
1 parent 38aebcbe28
commit 0cface89bf
13 files changed
+38 -33

No files matched your search

+2 -2
View File
@@ -8,7 +8,7 @@ export const mapMovieSeriesToShow = (
rating: vote_average, rating: vote_average,
votes: vote_count, votes: vote_count,
backdrop: backdrop_path ? `https://image.tmdb.org/t/p/w1280/${backdrop_path}` : '', backdrop: backdrop_path ? `https://image.tmdb.org/t/p/w1280/${backdrop_path}` : '',
poster: poster_path ? `https://image.tmdb.org/t/p/w500/${poster_path}` : '', poster: poster_path ? `https://image.tmdb.org/t/p/w342/${poster_path}` : '',
release: 'release_date' in item ? item.release_date : item.first_air_date, release: 'release_date' in item ? item.release_date : item.first_air_date,
title: 'release_date' in item ? item.title : item.name title: 'release_date' in item ? item.title : item.name
}); });
@@ -20,7 +20,7 @@ const mapMoviesSeriesResponseToShows = (
page, page,
total: total_pages, total: total_pages,
results: results results: results
.map(show => mapMovieSeriesToShow(show, type)) .map((show) => mapMovieSeriesToShow(show, type))
.filter((show) => show.votes && show.release && show.backdrop && show.poster) .filter((show) => show.votes && show.release && show.backdrop && show.poster)
}); });
+7 -5
View File
@@ -10,6 +10,8 @@ import yts from './parsers/yts';
import http from './Http'; import http from './Http';
import { Sort } from './parsers'; import { Sort } from './parsers';
const session = () => cookies().get('session')?.value;
export const createRequestToken = async () => { export const createRequestToken = async () => {
return http.get<RequestToken>('/authentication/token/new', { preventCache: true }).then(({ request_token }) => ({ return http.get<RequestToken>('/authentication/token/new', { preventCache: true }).then(({ request_token }) => ({
redirectUrl: `https://www.themoviedb.org/authenticate/${request_token}`, redirectUrl: `https://www.themoviedb.org/authenticate/${request_token}`,
@@ -26,14 +28,14 @@ export const createSession = async ({ requestToken }: { requestToken: string })
export const account = async () => { export const account = async () => {
return http.get<Account>('/account/null', { return http.get<Account>('/account/null', {
params: { session_id: cookies().get('session')?.value }, params: { session_id: session() },
preventCache: true preventCache: true
}); });
}; };
export const accountStates = async ({ showId, showType }: { showId: Show['id']; showType: Show['type'] }) => { export const accountStates = async ({ showId, showType }: { showId: Show['id']; showType: Show['type'] }) => {
return http.get<ShowState>(`/${showType}/${showId}/account_states`, { return http.get<ShowState>(`/${showType}/${showId}/account_states`, {
params: { session_id: cookies().get('session')?.value }, params: { session_id: session() },
preventCache: true preventCache: true
}); });
}; };
@@ -51,7 +53,7 @@ export const updateAccountStates = async ({
}) => { }) => {
http.post( http.post(
`/account/null/${list}`, `/account/null/${list}`,
{ params: { session_id: cookies().get('session')?.value }, preventCache: true }, { params: { session_id: session() }, preventCache: true },
{ {
media_id: showId, media_id: showId,
media_type: showType, media_type: showType,
@@ -71,7 +73,7 @@ export const usersShows = async ({
}): Promise<Pagination<Show>> => { }): Promise<Pagination<Show>> => {
return http return http
.get<TMDBPagination<Movie>>(`/account/null/${list}/${showType === 'tv' ? 'tv' : 'movies'}`, { .get<TMDBPagination<Movie>>(`/account/null/${list}/${showType === 'tv' ? 'tv' : 'movies'}`, {
params: { page, sort_by: 'created_at.desc', session_id: cookies().get('session')?.value }, params: { page, sort_by: 'created_at.desc', session_id: session() },
preventCache: true preventCache: true
}) })
.then((response) => mapMoviesSeriesResponseToShows(response, showType)); .then((response) => mapMoviesSeriesResponseToShows(response, showType));
@@ -224,7 +226,7 @@ export const credits = async ({
return cast return cast
.filter((person) => person.profile_path) .filter((person) => person.profile_path)
.map((actor) => { .map((actor) => {
const photoUrl = `https://image.tmdb.org/t/p/w500/${actor.profile_path}`; const photoUrl = `https://image.tmdb.org/t/p/w185${actor.profile_path}`;
if ('character' in actor) return { ...actor, photoUrl }; if ('character' in actor) return { ...actor, photoUrl };
+2 -2
View File
@@ -5,10 +5,10 @@ import getQueryClient from '@/lib/queryClient';
import Container from './container'; import Container from './container';
const Random = async () => { const Random = () => {
const queryClient = getQueryClient(); const queryClient = getQueryClient();
await queryClient.prefetchInfiniteQuery({ queryClient.prefetchInfiniteQuery({
queryKey: ['random-movie'], queryKey: ['random-movie'],
queryFn: randomMovies, queryFn: randomMovies,
initialPageParam: '1' initialPageParam: '1'
+2 -2
View File
@@ -12,10 +12,10 @@ export const metadata: Metadata = {
'Check out the most popular movies right now on Movie Advisor. See what’s trending and don’t miss out on the latest hits.' 'Check out the most popular movies right now on Movie Advisor. See what’s trending and don’t miss out on the latest hits.'
}; };
const Popular = async () => { const Popular = () => {
const queryClient = getQueryClient(); const queryClient = getQueryClient();
await queryClient.prefetchInfiniteQuery({ queryClient.prefetchInfiniteQuery({
queryKey: ['popular'], queryKey: ['popular'],
queryFn: () => popularMovies(), queryFn: () => popularMovies(),
initialPageParam: '1' initialPageParam: '1'
+2 -2
View File
@@ -5,12 +5,12 @@ import getQueryClient from '@/lib/queryClient';
import Container from './container'; import Container from './container';
const Similar = async ({ searchParams }: { searchParams: Record<string, string> }) => { const Similar = ({ searchParams }: { searchParams: Record<string, string> }) => {
const queryClient = getQueryClient(); const queryClient = getQueryClient();
const { id, type } = searchParams || {}; const { id, type } = searchParams || {};
await queryClient.prefetchInfiniteQuery({ queryClient.prefetchInfiniteQuery({
queryKey: ['similar', id, type], queryKey: ['similar', id, type],
queryFn: () => similarShows({ showId: id, showType: type as Show['type'] }), queryFn: () => similarShows({ showId: id, showType: type as Show['type'] }),
initialPageParam: '1' initialPageParam: '1'
+2 -2
View File
@@ -5,12 +5,12 @@ import getQueryClient from '@/lib/queryClient';
import Container from './container'; import Container from './container';
const Starring = async ({ searchParams }: { searchParams: Record<string, string> }) => { const Starring = ({ searchParams }: { searchParams: Record<string, string> }) => {
const queryClient = getQueryClient(); const queryClient = getQueryClient();
const { actorId } = searchParams || {}; const { actorId } = searchParams || {};
await queryClient.prefetchInfiniteQuery({ queryClient.prefetchInfiniteQuery({
queryKey: ['starring', actorId], queryKey: ['starring', actorId],
queryFn: () => topMovies({ starring: actorId }), queryFn: () => topMovies({ starring: actorId }),
initialPageParam: '1' initialPageParam: '1'
+2 -2
View File
@@ -12,10 +12,10 @@ export const metadata: Metadata = {
'Discover the top-rated movies on Movie Advisor. Find the highest-rated films and make informed viewing choices.' 'Discover the top-rated movies on Movie Advisor. Find the highest-rated films and make informed viewing choices.'
}; };
const Top = async () => { const Top = () => {
const queryClient = getQueryClient(); const queryClient = getQueryClient();
await queryClient.prefetchInfiniteQuery({ queryClient.prefetchInfiniteQuery({
queryKey: ['top'], queryKey: ['top'],
queryFn: () => topMovies(), queryFn: () => topMovies(),
initialPageParam: '1' initialPageParam: '1'
+8 -2
View File
@@ -9,10 +9,11 @@ interface Props {
onClick?: () => void; onClick?: () => void;
className?: string; className?: string;
rounded?: string; rounded?: string;
lazy?: boolean;
containerProps?: DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>; containerProps?: DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>;
} }
const Poster: FC<Props> = ({ show, onClick, className, rounded, containerProps }) => { const Poster: FC<Props> = ({ show, onClick, className, rounded, containerProps, lazy = true }) => {
if (!show) return null; if (!show) return null;
return ( return (
@@ -21,7 +22,12 @@ const Poster: FC<Props> = ({ show, onClick, className, rounded, containerProps }
className={cn('card-aspect-ratio relative bg-black overflow-hidden rounded-lg text-lg', className, rounded)} className={cn('card-aspect-ratio relative bg-black overflow-hidden rounded-lg text-lg', className, rounded)}
> >
<div className='flex size-full'> <div className='flex size-full'>
<img className={cn('size-full rounded-lg object-cover', rounded)} src={show.poster} alt={show.title} /> <img
className={cn('size-full rounded-lg object-cover', rounded)}
loading={lazy ? 'lazy' : 'eager'}
src={show.poster}
alt={show.title}
/>
</div> </div>
<div <div
className={cn( className={cn(
@@ -65,7 +65,7 @@ const Actions = ({ onClose, show, className }: Props) => {
</Link> </Link>
<Button <Button
aria-label='Watch show' aria-label='Watch show'
className={cn(rightClassName, 'bg-red-600')} className={cn(rightClassName, 'bg-red-700')}
variant='destructive' variant='destructive'
onClick={() => onClick={() =>
showTorrentsModal({ showTorrentsModal({
@@ -58,7 +58,7 @@ const components: VirtuosoProps<Actor, Context>['components'] = {
onClick={() => context?.onClick?.(actor.id.toString())} onClick={() => context?.onClick?.(actor.id.toString())}
> >
<div className='overflow-hidden rounded-lg'> <div className='overflow-hidden rounded-lg'>
<img height={180} width={120} src={actor.photoUrl} alt={actor.name} /> <img height={180} width={120} loading='lazy' src={actor.photoUrl} alt={actor.name} />
</div> </div>
<div className='absolute left-0 top-0 flex size-full flex-col justify-between rounded-md bg-vignette p-2 py-1 text-sm text-white'> <div className='absolute left-0 top-0 flex size-full flex-col justify-between rounded-md bg-vignette p-2 py-1 text-sm text-white'>
<p className=' truncate'>{actor.name}</p> <p className=' truncate'>{actor.name}</p>
@@ -1,6 +1,6 @@
'use client'; 'use client';
import { ForwardedRef, forwardRef, memo, useLayoutEffect, useMemo, useRef, useState } from 'react'; import { ForwardedRef, forwardRef, memo, useLayoutEffect, useMemo, useRef } from 'react';
import { Virtuoso, VirtuosoProps } from 'react-virtuoso'; import { Virtuoso, VirtuosoProps } from 'react-virtuoso';
import Poster from '@/components/Poster'; import Poster from '@/components/Poster';
@@ -23,22 +23,15 @@ const Carousel = memo(
function Carousel({ shows, gap = 8, onIndexChange, onEndReached }: Props) { function Carousel({ shows, gap = 8, onIndexChange, onEndReached }: Props) {
const index = useSilentIndex(); const index = useSilentIndex();
const [isFirstRender, setIsFirstRender] = useState(true);
const context = useMemo(() => ({ onIndexChange, gap }), [onIndexChange, gap]); const context = useMemo(() => ({ onIndexChange, gap }), [onIndexChange, gap]);
return ( return (
<div className='card-aspect-ratio relative mx-auto'> <div className='card-aspect-ratio relative mx-auto'>
{isFirstRender && (
<div className='absolute left-0 top-0 size-full'>
<Poster show={shows?.[index]} />
</div>
)}
<Virtuoso <Virtuoso
initialItemCount={1}
horizontalDirection horizontalDirection
skipAnimationFrameInResizeObserver skipAnimationFrameInResizeObserver
data={shows} data={shows}
itemsRendered={() => isFirstRender && setIsFirstRender(false)}
context={context} context={context}
endReached={onEndReached} endReached={onEndReached}
initialTopMostItemIndex={index} initialTopMostItemIndex={index}
@@ -80,7 +73,7 @@ const components: VirtuosoProps<Show, Context>['components'] = {
return ( return (
<div {...props} ref={ref} className='snap-start'> <div {...props} ref={ref} className='snap-start'>
<Poster show={item} /> <Poster lazy={false} show={item} />
</div> </div>
); );
}, },
+3 -2
View File
@@ -1,3 +1,5 @@
'use client';
import { usersShows } from '@/api'; import { usersShows } from '@/api';
import useInfiniteList from './useInfiniteList'; import useInfiniteList from './useInfiniteList';
@@ -17,8 +19,7 @@ const useUsersShows = ({ showType, list = 'favorite' }: { showType: Show['type']
const query = useInfiniteList({ const query = useInfiniteList({
queryKey: KEY({ list, showType }), queryKey: KEY({ list, showType }),
queryFn: ({ page }) => usersShows({ showType, list, page }), queryFn: ({ page }) => usersShows({ showType, list, page })
enabled: Boolean(session)
}); });
return session return session
+3
View File
@@ -2,6 +2,9 @@
@tailwind components; @tailwind components;
@tailwind utilities; @tailwind utilities;
@import '@vidstack/react/player/styles/base.css';
@import '@vidstack/react/player/styles/plyr/theme.css';
@layer base { @layer base {
:root { :root {
--background: 0 0% 100%; --background: 0 0% 100%;