refactoring: improvements for lighthouse

This commit is contained in:
ner committed 2024-10-21 15:35:08 +03:00
1 parent f2f242a684
commit 38aebcbe28
27 files changed
+132 -93

No files matched your search

+1 -1
View File
@@ -213,7 +213,7 @@ export const credits = async ({
showId,
showType = 'movie'
}: {
showId: Show['id'];
showId?: Show['id'];
showType?: Show['type'];
}): Promise<Array<Actor>> => {
return http
+1 -1
View File
@@ -10,7 +10,7 @@ const Random = async () => {
await queryClient.prefetchInfiniteQuery({
queryKey: ['random-movie'],
queryFn: () => randomMovies(),
queryFn: randomMovies,
initialPageParam: '1'
});
+1 -1
View File
@@ -3,6 +3,6 @@
import { popularMovies } from '@/api';
import useInfiniteList from '@/hooks/useInfiniteList';
const usePopular = () => useInfiniteList({ queryKey: ['popular'], queryFn: popularMovies });
const usePopular = () => useInfiniteList({ suspense: true, queryKey: ['popular'], queryFn: popularMovies });
export default usePopular;
+1
View File
@@ -10,6 +10,7 @@ interface Props {
const useSimilar = ({ showId, showType = 'movie' }: Props) =>
useInfiniteList({
suspense: true,
enabled: Boolean(showId),
queryKey: ['similar', showId, showType],
queryFn: ({ page }) => similarShows({ page, showId, showType })
+1
View File
@@ -5,6 +5,7 @@ import useInfiniteList from '@/hooks/useInfiniteList';
const useStarring = ({ actorId }: { actorId?: string }) =>
useInfiniteList({
suspense: true,
queryKey: ['starring', actorId],
enabled: Boolean(actorId),
queryFn: ({ page }) => topMovies({ page, starring: actorId })
+1 -1
View File
@@ -3,6 +3,6 @@
import { topMovies } from '@/api';
import useInfiniteList from '@/hooks/useInfiniteList';
const useTop = () => useInfiniteList({ queryKey: ['top'], queryFn: topMovies });
const useTop = () => useInfiniteList({ suspense: true, queryKey: ['top'], queryFn: topMovies });
export default useTop;
+1 -4
View File
@@ -15,10 +15,7 @@ export const metadata: Metadata = {
};
export const viewport: Viewport = {
width: 'device-width',
initialScale: 1,
maximumScale: 1,
userScalable: false
width: 'device-width'
};
const font = Poppins({ subsets: ['latin'], weight: ['400', '500', '600'] });
@@ -18,7 +18,7 @@ export const MobileNavigation = () => {
<div className='flex md:hidden'>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant='ghost' size='icon'>
<Button aria-label='Navigation toggle' variant='ghost' size='icon'>
<Menu size={19} />
</Button>
</DropdownMenuTrigger>
@@ -106,7 +106,7 @@ export const showSearchModal = create(({ onResolve }) => {
});
const ToggleSearch = () => (
<Button variant='ghost' size='icon' onClick={() => showSearchModal()}>
<Button aria-label='Search show' variant='ghost' size='icon' onClick={() => showSearchModal()}>
<SearchIcon size={19} />
</Button>
);
@@ -10,6 +10,7 @@ const ThemeToggle = () => {
return (
<Button
aria-label='Toggle theme'
variant='ghost'
size='icon'
onClick={() => setTheme(theme === 'dark' ? 'light' : 'dark')}
+1 -1
View File
@@ -26,7 +26,7 @@ const User = () => {
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant='ghost' size='icon'>
<Button aria-label='Account menu' variant='ghost' size='icon'>
<UserRound size={20} />
</Button>
</DropdownMenuTrigger>
@@ -25,7 +25,7 @@ const Actions = ({ onClose, show, className }: Props) => {
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'>
<Button aria-label='Show rating' className={leftClassName} variant='outline'>
<Star size={14} />
</Button>
<Button className={rightClassName} variant='outline'>
@@ -34,6 +34,7 @@ const Actions = ({ onClose, show, className }: Props) => {
</div>
<div className={groupClassName}>
<Button
aria-label='Toggle favorite'
className={leftClassName}
variant='outline'
disabled={toggle.list === 'favorite' && toggle.isPending}
@@ -42,6 +43,7 @@ const Actions = ({ onClose, show, className }: Props) => {
<Heart size={14} className={cn({ 'fill-secondary-foreground': state?.favorite })} />
</Button>
<Button
aria-label='Toggle watch list'
className={rightClassName}
variant='outline'
disabled={toggle.list === 'watchlist' && toggle.isPending}
@@ -56,12 +58,13 @@ const Actions = ({ onClose, show, className }: Props) => {
href={`/similar?id=${show.id}&title=${encodeURIComponent(show.title)}&type=${show.type}`}
onClick={onClose}
>
<Button className={leftClassName} variant='outline'>
<Button aria-label='Similar show' className={leftClassName} variant='outline'>
<Copy size={14} />
Similar
</Button>
</Link>
<Button
aria-label='Watch show'
className={cn(rightClassName, 'bg-red-600')}
variant='destructive'
onClick={() =>
@@ -53,6 +53,7 @@ const components: VirtuosoProps<Actor, Context>['components'] = {
className='relative shrink-0 cursor-pointer snap-start self-end bg-card text-card-foreground transition-shadow hover:shadow-lg'
>
<Link
prefetch={false}
href={`/starring?actorId=${actor.id}&title=${encodeURIComponent(actor.name)}`}
onClick={() => context?.onClick?.(actor.id.toString())}
>
@@ -3,13 +3,15 @@ import { useQuery } from '@tanstack/react-query';
import { credits } from '@/api';
interface Props {
showId: Show['id'];
showId?: Show['id'];
showType?: Show['type'];
}
export const KEY = ({ showId, showType }: Props) => ['credits', showId, showType];
const useCredits = ({ showId, showType }: Props) => {
return useQuery({
queryKey: ['credits', showId, showType],
queryKey: KEY({ showId, showType }),
queryFn: () => credits({ showId, showType }),
enabled: Boolean(showId)
});
@@ -19,6 +19,9 @@ import CaptionsMenu from './components/CaptionsMenu';
import VideosMenu from './components/VideosMenu';
import useSource from './useSource';
import '@vidstack/react/player/styles/base.css';
import '@vidstack/react/player/styles/plyr/theme.css';
interface Props {
magnet: string;
subtitles: Source[];
+9 -2
View File
@@ -2,10 +2,17 @@ import { useQuery } from '@tanstack/react-query';
import { details } from '@/api';
const useDetails = ({ showId, showType = 'movie' }: { showId?: Show['id']; showType?: Show['type'] }) =>
interface Props {
showId?: Show['id'];
showType?: Show['type'];
}
export const KEY = ({ showId, showType = 'movie' }: Props) => ['details', showId, showType];
const useDetails = ({ showId, showType = 'movie' }: Props) =>
useQuery({
enabled: Boolean(showId && showType),
queryKey: ['details', showId, showType],
queryKey: KEY({ showId, showType }),
queryFn: () => details({ showId: showId!, showType })
});
+32 -20
View File
@@ -1,43 +1,55 @@
'use client';
import { FC, ForwardedRef, forwardRef, useLayoutEffect, useMemo, useRef } from 'react';
import { ForwardedRef, forwardRef, memo, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { Virtuoso, VirtuosoProps } from 'react-virtuoso';
import Poster from '@/components/Poster';
import ScrollNavigation from '@/components/ScrollNavigation';
import { cn } from '@/lib/utils';
import { useSilentIndex } from '../../useRandomMovie';
interface Context {
onIndexChange: (index: number) => void;
gap?: number;
}
interface Props extends Context {
index: number;
shows?: Show[];
onEndReached?: () => void;
}
const Carousel: FC<Props> = ({ index, shows, gap = 8, onIndexChange, onEndReached }) => {
const initialIndex = useRef(index);
const Carousel = memo(
function Carousel({ shows, gap = 8, onIndexChange, onEndReached }: Props) {
const index = useSilentIndex();
const context = useMemo(() => ({ onIndexChange, gap }), [onIndexChange, gap]);
const [isFirstRender, setIsFirstRender] = useState(true);
return (
<div className='card-aspect-ratio mx-auto'>
<Virtuoso
horizontalDirection
skipAnimationFrameInResizeObserver
data={shows}
context={context}
endReached={onEndReached}
initialTopMostItemIndex={initialIndex.current}
components={components}
increaseViewportBy={1000}
/>
</div>
);
};
const context = useMemo(() => ({ onIndexChange, gap }), [onIndexChange, gap]);
return (
<div className='card-aspect-ratio relative mx-auto'>
{isFirstRender && (
<div className='absolute left-0 top-0 size-full'>
<Poster show={shows?.[index]} />
</div>
)}
<Virtuoso
horizontalDirection
skipAnimationFrameInResizeObserver
data={shows}
itemsRendered={() => isFirstRender && setIsFirstRender(false)}
context={context}
endReached={onEndReached}
initialTopMostItemIndex={index}
components={components}
increaseViewportBy={1000}
/>
</div>
);
},
(prev, next) => prev.shows === next.shows
);
const components: VirtuosoProps<Show, Context>['components'] = {
Item: ({ item, children, context, ...props }) => {
+2 -2
View File
@@ -6,13 +6,13 @@ import Carousel from './components/Carousel';
import useRandomMovie from './useRandomMovie';
const Random = () => {
const { movies, movie, index, onIndexChange, fetchNextPage } = useRandomMovie();
const { movie, movies, onIndexChange, fetchNextPage } = useRandomMovie();
return (
<Preview
show={movie}
className='rounded-md bg-background'
poster={<Carousel index={index} shows={movies} onIndexChange={onIndexChange} onEndReached={fetchNextPage} />}
poster={<Carousel shows={movies} onIndexChange={onIndexChange} onEndReached={fetchNextPage} />}
/>
);
};
+11 -10
View File
@@ -1,36 +1,37 @@
'use client';
import { startTransition, useCallback, useState } from 'react';
import { startTransition, useCallback } from 'react';
import { atom, getDefaultStore, useAtom } from 'jotai';
import { randomMovies } from '@/api';
import useInfiniteList from '@/hooks/useInfiniteList';
import useSessionRef from '@/hooks/useSessionRef';
const indexAtom = atom(0);
export const useSilentIndex = () => getDefaultStore().get(indexAtom);
const useRandomMovie = () => {
const [indexRef, setIndexRef] = useSessionRef('random-movie-index', 0);
const [index, setIndex] = useState(indexRef.current);
const [index, setIndex] = useAtom(indexAtom);
const { shows: movies, fetchNextPage } = useInfiniteList({
suspense: true,
queryKey: ['random-movie'],
queryFn: () => randomMovies()
queryFn: randomMovies
});
if (movies.length && !movies[index]) {
setIndex(0);
setIndexRef(0);
}
return {
index,
movies,
movie: movies[index],
movies,
fetchNextPage,
onIndexChange: useCallback(
(index: number) => {
setIndexRef(index);
startTransition(() => setIndex(index));
},
[setIndexRef]
[setIndex]
)
};
};
+6 -3
View File
@@ -1,14 +1,17 @@
import { useMemo } from 'react';
import { QueryKey, useInfiniteQuery } from '@tanstack/react-query';
import { QueryKey, useInfiniteQuery, useSuspenseInfiniteQuery } from '@tanstack/react-query';
interface Props {
suspense?: boolean;
queryKey: QueryKey;
enabled?: boolean;
queryFn: ({ page }: { page: string }) => Promise<Pagination<Show>>;
}
const useInfiniteList = ({ queryKey, queryFn, enabled }: Props) => {
const { data, hasNextPage, fetchNextPage, isFetched, isLoading } = useInfiniteQuery({
const useInfiniteList = ({ queryKey, queryFn, enabled, suspense }: Props) => {
const { data, hasNextPage, fetchNextPage, isFetched, isLoading } = (
suspense ? useSuspenseInfiniteQuery : useInfiniteQuery
)({
enabled,
queryKey,
queryFn: ({ pageParam }) => queryFn({ page: pageParam }),
-33
View File
@@ -1,33 +0,0 @@
import { MutableRefObject, useCallback, useEffect, useRef, useState } from 'react';
const useSessionRef = <T>(key: string, initialValue: T): [MutableRefObject<T>, (value: T) => void] => {
const [state] = useState(() => {
if (typeof window === 'undefined') return initialValue;
const storedValue = sessionStorage.getItem(key);
return storedValue ? JSON.parse(storedValue) : initialValue;
});
const ref = useRef(state);
useEffect(() => {
const listener = () => sessionStorage.removeItem(key);
window.addEventListener('beforeunload', listener);
return () => window.removeEventListener('beforeunload', listener);
}, [key]);
const setter = useCallback(
(value: T) => {
sessionStorage.setItem(key, JSON.stringify(value));
ref.current = value;
},
[key]
);
return [ref, setter];
};
export default useSessionRef;
+4 -3
View File
@@ -1,8 +1,9 @@
import { accountStates, updateAccountStates } from '@/api';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { accountStates, updateAccountStates } from '@/api';
import { useFavorites, useFavoritesStateToggle, useWatchList, useWatchListStateToggle } from './useLocalUsersLists';
import { useSession } from './useSession';
import { KEY as USERS_SHOWS_KEY } from './useUsersShows';
const KEY = ['show-state'];
@@ -49,7 +50,7 @@ export const useMutateShowState = (show: Show) => {
queryClient.setQueryData<ShowState>(key, snapshot);
},
onSuccess(_, { list, showType }) {
queryClient.invalidateQueries({ queryKey: USERS_SHOWS_KEY({ list, showType }) });
queryClient.invalidateQueries({ queryKey: USERS_SHOWS_KEY({ list, showType }), refetchType: 'all' });
}
});
+2 -2
View File
@@ -4,10 +4,10 @@ const makeQueryClient = () => {
return new QueryClient({
defaultOptions: {
queries: {
refetchOnWindowFocus: false,
staleTime: Infinity,
refetchOnReconnect: false,
refetchOnMount: false
refetchOnMount: false,
refetchOnWindowFocus: false
},
dehydrate: {
shouldDehydrateQuery: (query) => defaultShouldDehydrateQuery(query) || query.state.status === 'pending'
+39
View File
@@ -17,6 +17,7 @@
"@radix-ui/react-toast": "^1.2.2",
"@radix-ui/react-toggle": "^1.0.3",
"@tanstack/react-query": "^5.59.15",
"@tanstack/react-query-devtools": "^5.59.15",
"@vidstack/react": "^1.12.11",
"axios": "^1.4.0",
"class-variance-authority": "^0.7.0",
@@ -2548,6 +2549,15 @@
"url": "https://github.com/sponsors/tannerlinsley"
}
},
"node_modules/@tanstack/query-devtools": {
"version": "5.58.0",
"resolved": "https://registry.npmjs.org/@tanstack/query-devtools/-/query-devtools-5.58.0.tgz",
"integrity": "sha512-iFdQEFXaYYxqgrv63ots+65FGI+tNp5ZS5PdMU1DWisxk3fez5HG3FyVlbUva+RdYS5hSLbxZ9aw3yEs97GNTw==",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/tannerlinsley"
}
},
"node_modules/@tanstack/react-query": {
"version": "5.59.15",
"resolved": "https://registry.npmjs.org/@tanstack/react-query/-/react-query-5.59.15.tgz",
@@ -2564,6 +2574,22 @@
"react": "^18 || ^19"
}
},
"node_modules/@tanstack/react-query-devtools": {
"version": "5.59.15",
"resolved": "https://registry.npmjs.org/@tanstack/react-query-devtools/-/react-query-devtools-5.59.15.tgz",
"integrity": "sha512-rX28KTivkA2XEn3Fj9ckDtnTPY8giWYgssySSAperpVol4+th+NCij/MhLylfB+Mfg2JfCxOcwnM/fwzS8iSog==",
"dependencies": {
"@tanstack/query-devtools": "5.58.0"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/tannerlinsley"
},
"peerDependencies": {
"@tanstack/react-query": "^5.59.15",
"react": "^18 || ^19"
}
},
"node_modules/@types/js-cookie": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/@types/js-cookie/-/js-cookie-3.0.3.tgz",
@@ -8952,6 +8978,11 @@
"resolved": "https://registry.npmjs.org/@tanstack/query-core/-/query-core-5.59.13.tgz",
"integrity": "sha512-Oou0bBu/P8+oYjXsJQ11j+gcpLAMpqW42UlokQYEz4dE7+hOtVO9rVuolJKgEccqzvyFzqX4/zZWY+R/v1wVsQ=="
},
"@tanstack/query-devtools": {
"version": "5.58.0",
"resolved": "https://registry.npmjs.org/@tanstack/query-devtools/-/query-devtools-5.58.0.tgz",
"integrity": "sha512-iFdQEFXaYYxqgrv63ots+65FGI+tNp5ZS5PdMU1DWisxk3fez5HG3FyVlbUva+RdYS5hSLbxZ9aw3yEs97GNTw=="
},
"@tanstack/react-query": {
"version": "5.59.15",
"resolved": "https://registry.npmjs.org/@tanstack/react-query/-/react-query-5.59.15.tgz",
@@ -8960,6 +8991,14 @@
"@tanstack/query-core": "5.59.13"
}
},
"@tanstack/react-query-devtools": {
"version": "5.59.15",
"resolved": "https://registry.npmjs.org/@tanstack/react-query-devtools/-/react-query-devtools-5.59.15.tgz",
"integrity": "sha512-rX28KTivkA2XEn3Fj9ckDtnTPY8giWYgssySSAperpVol4+th+NCij/MhLylfB+Mfg2JfCxOcwnM/fwzS8iSog==",
"requires": {
"@tanstack/query-devtools": "5.58.0"
}
},
"@types/js-cookie": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/@types/js-cookie/-/js-cookie-3.0.3.tgz",
+1
View File
@@ -19,6 +19,7 @@
"@radix-ui/react-toast": "^1.2.2",
"@radix-ui/react-toggle": "^1.0.3",
"@tanstack/react-query": "^5.59.15",
"@tanstack/react-query-devtools": "^5.59.15",
"@vidstack/react": "^1.12.11",
"axios": "^1.4.0",
"class-variance-authority": "^0.7.0",
+2
View File
@@ -3,6 +3,7 @@
import { FC, ReactNode } from 'react';
import ModalContainer from 'react-modal-promise';
import { QueryClientProvider } from '@tanstack/react-query';
import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
import { Toaster } from '@/components/ui/toaster';
import getQueryClient from '@/lib/queryClient';
@@ -22,6 +23,7 @@ const Providers: FC<Props> = ({ children, theme }) => {
<ThemeProvider theme={theme}>{children}</ThemeProvider>
<ModalContainer exitTimeout={500} enterTimeout={0} />
<Toaster />
<ReactQueryDevtools initialIsOpen={true} />
</QueryClientProvider>
);
};
-3
View File
@@ -2,9 +2,6 @@
@tailwind components;
@tailwind utilities;
@import '@vidstack/react/player/styles/base.css';
@import '@vidstack/react/player/styles/plyr/theme.css';
@layer base {
:root {
--background: 0 0% 100%;