search: improved state handling and removed not need fetches
continuous-integration/drone/push Build is passing Details

nextui
Guus van Meerveld 8 months ago
parent 6423bae178
commit ff694c15c5

@ -6,8 +6,10 @@ import NextLink from "next/link";
import { Card, CardBody } from "@nextui-org/card"; import { Card, CardBody } from "@nextui-org/card";
import { Image } from "@nextui-org/image"; import { Image } from "@nextui-org/image";
import { Link } from "@nextui-org/link"; import { Link } from "@nextui-org/link";
import { Listbox, ListboxItem } from "@nextui-org/listbox";
import { PlaylistItem } from "@/client/typings/item"; import { PlaylistItem } from "@/client/typings/item";
import { videoUrl } from "@/utils/urls";
import { videoSize } from "@/utils/videoSize"; import { videoSize } from "@/utils/videoSize";
import { Component } from "@/typings/component"; import { Component } from "@/typings/component";
@ -16,14 +18,16 @@ export const Playlist: Component<{ data: PlaylistItem }> = ({ data }) => {
const url = `/playlist/${data.id}`; const url = `/playlist/${data.id}`;
const channelUrl = `/channel/${data.author.id}`; const channelUrl = `/channel/${data.author.id}`;
const [width, height] = videoSize([16, 9], 30); const [width, height] = videoSize(30);
const [playlistItemWidth, playlistItemHeight] = videoSize(5);
return ( return (
<NextLink href={url}>
<Card> <Card>
<CardBody> <CardBody>
<div className="flex flex-col lg:flex-row gap-4"> <div className="flex flex-col lg:flex-row gap-4">
<div className="relative"> <div className="relative">
<NextLink href={url}>
<Image <Image
width={width} width={width}
height={height} height={height}
@ -33,6 +37,7 @@ export const Playlist: Component<{ data: PlaylistItem }> = ({ data }) => {
as={NextImage} as={NextImage}
unoptimized unoptimized
/> />
</NextLink>
<p className="text-small rounded-md z-10 absolute bottom-2 right-2 bg-content2 p-1"> <p className="text-small rounded-md z-10 absolute bottom-2 right-2 bg-content2 p-1">
{data.numberOfVideos} videos {data.numberOfVideos} videos
</p> </p>
@ -40,30 +45,45 @@ export const Playlist: Component<{ data: PlaylistItem }> = ({ data }) => {
<div className="flex flex-col gap-2"> <div className="flex flex-col gap-2">
<div> <div>
<h1 className="text-xl">{data.title}</h1> <Link as={NextLink} href={url}>
<h1 className="text-xl text-default-foreground">
{data.title}
</h1>
</Link>
<Link <Link
as={NextLink} as={NextLink}
href={channelUrl} href={channelUrl}
className="flex flex-row gap-2 items-center" className="flex flex-row gap-2 items-center"
> >
<h1 className="text-lg text-default-600"> <h1 className="text-lg text-default-600">{data.author.name}</h1>
{data.author.name}
</h1>
</Link> </Link>
</div> </div>
{data.videos && ( {data.videos && (
<div className="flex flex-col gap-1"> <Listbox>
{data.videos.map((video) => ( {data.videos.map((video) => (
<h1 key={video.id}>{video.title}</h1> <ListboxItem
as={NextLink}
startContent={
<Image
alt={video.title}
src={video.thumbnail}
height={playlistItemHeight}
width={playlistItemWidth}
/>
}
key={video.id}
href={videoUrl(video.id)}
>
{video.title}
</ListboxItem>
))} ))}
</div> </Listbox>
)} )}
</div> </div>
</div> </div>
</CardBody> </CardBody>
</Card> </Card>
</NextLink>
); );
}; };

@ -45,13 +45,14 @@ export const Search: Component = () => {
return new Error(`The provided filter \`${filter}\` is invalid`); return new Error(`The provided filter \`${filter}\` is invalid`);
}, [filter]); }, [filter]);
const canSearch = !(!!invalidQuery || !!invalidFilter);
const { const {
data, data,
error: fetchError, error: fetchError,
fetchNextPage, fetchNextPage,
// hasNextPage,
refetch, refetch,
isFetching, isPending,
isFetchingNextPage isFetchingNextPage
} = useInfiniteQuery({ } = useInfiniteQuery({
queryKey: ["search", query, filter], queryKey: ["search", query, filter],
@ -61,12 +62,12 @@ export const Search: Component = () => {
type: filter type: filter
}); });
}, },
enabled: !!invalidQuery || !!invalidFilter, enabled: canSearch,
initialPageParam: "", initialPageParam: "",
getNextPageParam: (lastPage) => lastPage.nextCursor getNextPageParam: (lastPage) => lastPage.nextCursor
}); });
const error = invalidQuery ?? invalidFilter ?? fetchError ?? undefined; const error = invalidFilter ?? fetchError ?? undefined;
const searchFor = useSearch(); const searchFor = useSearch();
@ -84,6 +85,13 @@ export const Search: Component = () => {
[isFetchingNextPage, fetchNextPage] [isFetchingNextPage, fetchNextPage]
); );
const hasLoadedData =
canSearch && data?.pages.flat().length
? data?.pages.flat().length !== 0
: false;
const isLoadingInitialData = canSearch && !isFetchingNextPage && isPending;
return ( return (
<> <>
<Container> <Container>
@ -91,12 +99,13 @@ export const Search: Component = () => {
<div className="flex-1"> <div className="flex-1">
<SearchInput initialQueryValue={query ?? undefined} /> <SearchInput initialQueryValue={query ?? undefined} />
</div> </div>
{canSearch && (
<div> <div>
<Filter filter={filter} setFilter={setFilter} /> <Filter filter={filter} setFilter={setFilter} />
</div> </div>
)}
</div> </div>
<Spacer y={4} /> {isLoadingInitialData && <LoadingPage />}
{isFetching && !error && <LoadingPage />}
{error && ( {error && (
<div className="flex-1 flex items-center justify-center"> <div className="flex-1 flex items-center justify-center">
<div className="text-center"> <div className="text-center">
@ -111,9 +120,10 @@ export const Search: Component = () => {
</div> </div>
</div> </div>
)} )}
<div className="flex flex-col gap-4"> {hasLoadedData && (
{!error && <>
data?.pages.map((page, i) => { <div className="flex flex-col gap-4 mt-4">
{data?.pages.map((page, i) => {
return ( return (
<Fragment key={i}> <Fragment key={i}>
{page.items.map((result) => { {page.items.map((result) => {
@ -131,12 +141,13 @@ export const Search: Component = () => {
</Fragment> </Fragment>
); );
})} })}
</div>
<Loading <Loading
isFetching={isFetchingNextPage} isFetching={isFetchingNextPage && !isPending}
onVisible={handleUserReachedPageEnd} onVisible={handleUserReachedPageEnd}
/> />
</div> </>
)}
</Container> </Container>
</> </>
); );

@ -20,14 +20,14 @@ export const Video: Component<{ data: VideoItem }> = ({ data }) => {
const url = `/watch?v=${data.id}`; const url = `/watch?v=${data.id}`;
const channelUrl = `/channel/${data.author.id}`; const channelUrl = `/channel/${data.author.id}`;
const [width, height] = videoSize([16, 9], 30); const [width, height] = videoSize(30);
return ( return (
<NextLink href={url}>
<Card> <Card>
<CardBody> <CardBody>
<div className="flex flex-row gap-4"> <div className="flex flex-row gap-4">
<div className="relative"> <div className="relative">
<NextLink href={url}>
<Image <Image
width={width} width={width}
height={height} height={height}
@ -36,6 +36,8 @@ export const Video: Component<{ data: VideoItem }> = ({ data }) => {
as={NextImage} as={NextImage}
unoptimized unoptimized
/> />
</NextLink>
<p className="text-small rounded-md z-10 absolute bottom-2 right-2 bg-content2 p-1"> <p className="text-small rounded-md z-10 absolute bottom-2 right-2 bg-content2 p-1">
{formatDuration(data.duration)} {formatDuration(data.duration)}
</p> </p>
@ -47,7 +49,9 @@ export const Video: Component<{ data: VideoItem }> = ({ data }) => {
</div> </div>
<div className="flex flex-col gap-2"> <div className="flex flex-col gap-2">
<h1 className="text-xl">{data.title}</h1> <Link as={NextLink} href={url}>
<h1 className="text-xl text-default-foreground">{data.title}</h1>
</Link>
<div className="flex flex-row gap-4 items-center font-semibold text-default-600"> <div className="flex flex-row gap-4 items-center font-semibold text-default-600">
<h1>{formatBigNumber(data.views)} views</h1> <h1>{formatBigNumber(data.views)} views</h1>
{data.uploaded && <h1>{formatUploadedTime(data.uploaded)}</h1>} {data.uploaded && <h1>{formatUploadedTime(data.uploaded)}</h1>}
@ -73,6 +77,5 @@ export const Video: Component<{ data: VideoItem }> = ({ data }) => {
</div> </div>
</CardBody> </CardBody>
</Card> </Card>
</NextLink>
); );
}; };

@ -70,11 +70,11 @@ export const Trending: Component = ({}) => {
return ( return (
<> <>
<Container> <Container>
<div className="flex items-center"> <div className="flex flex-row items-center gap-4">
<RegionSwitcher currentRegion={region} regions={validRegions} /> <RegionSwitcher currentRegion={region} regions={validRegions} />
<Spacer x={4} />
<h1 className="text-xl">Trending</h1> <h1 className="text-xl">Trending</h1>
</div> </div>
{isLoading && !data && <LoadingPage />} {isLoading && !data && <LoadingPage />}
{error && ( {error && (
<div className="flex-1 flex items-center justify-center"> <div className="flex-1 flex items-center justify-center">

@ -1,6 +1,7 @@
import { NextPage } from "next"; import { NextPage } from "next";
import { Suspense } from "react"; import { Suspense } from "react";
import { Container } from "@/components/Container";
import { LoadingPage } from "@/components/LoadingPage"; import { LoadingPage } from "@/components/LoadingPage";
import { Trending } from "./Trending"; import { Trending } from "./Trending";
@ -8,7 +9,13 @@ import { Trending } from "./Trending";
const Page: NextPage = () => { const Page: NextPage = () => {
return ( return (
<> <>
<Suspense fallback={<LoadingPage />}> <Suspense
fallback={
<Container>
<LoadingPage />
</Container>
}
>
<Trending /> <Trending />
</Suspense> </Suspense>
</> </>

@ -14,6 +14,8 @@ import { highlight, ItemType } from "@/utils/highlight";
import { Component } from "@/typings/component"; import { Component } from "@/typings/component";
const shortenedDescriptionLength = 200;
export const Description: Component<{ data: string }> = ({ data }) => { export const Description: Component<{ data: string }> = ({ data }) => {
const [expandedDescription, setExpandedDescription] = useState(false); const [expandedDescription, setExpandedDescription] = useState(false);
@ -32,7 +34,7 @@ export const Description: Component<{ data: string }> = ({ data }) => {
() => () =>
expandedDescription expandedDescription
? sanitizedDescription ? sanitizedDescription
: sanitizedDescription?.substring(0, 200) + "...", : sanitizedDescription.substring(0, shortenedDescriptionLength) + "...",
[sanitizedDescription, expandedDescription] [sanitizedDescription, expandedDescription]
); );

@ -10,8 +10,6 @@ import {
NavbarItem NavbarItem
} from "@nextui-org/navbar"; } from "@nextui-org/navbar";
// import { Search } from "./Search";
export const navHeight = 64; export const navHeight = 64;
export const Nav: FC<{ pathname: string }> = ({ pathname }) => { export const Nav: FC<{ pathname: string }> = ({ pathname }) => {
@ -20,6 +18,10 @@ export const Nav: FC<{ pathname: string }> = ({ pathname }) => {
title: "Trending", title: "Trending",
link: "/trending" link: "/trending"
}, },
{
title: "Search",
link: "/results"
},
{ {
title: "Subscriptions", title: "Subscriptions",
link: "/subscriptions" link: "/subscriptions"

@ -3,7 +3,7 @@
import { useDebounce } from "use-debounce"; import { useDebounce } from "use-debounce";
import { useQuery } from "@tanstack/react-query"; import { useQuery } from "@tanstack/react-query";
import { useMemo, useState } from "react"; import { FC, useMemo, useState } from "react";
import { FiSearch as SearchIcon } from "react-icons/fi"; import { FiSearch as SearchIcon } from "react-icons/fi";
import { Autocomplete, AutocompleteItem } from "@nextui-org/autocomplete"; import { Autocomplete, AutocompleteItem } from "@nextui-org/autocomplete";
@ -11,9 +11,7 @@ import { Autocomplete, AutocompleteItem } from "@nextui-org/autocomplete";
import { useClient } from "@/hooks/useClient"; import { useClient } from "@/hooks/useClient";
import { useSearch } from "@/hooks/useSearch"; import { useSearch } from "@/hooks/useSearch";
import { Component } from "@/typings/component"; export const Search: FC<{
export const Search: Component<{
initialQueryValue?: string; initialQueryValue?: string;
}> = ({ initialQueryValue }) => { }> = ({ initialQueryValue }) => {
const client = useClient(); const client = useClient();
@ -73,7 +71,7 @@ export const Search: Component<{
required required
type="text" type="text"
label="Search" label="Search"
variant="flat" variant="bordered"
placeholder="Search for videos" placeholder="Search for videos"
> >
{(suggestion) => ( {(suggestion) => (

@ -25,7 +25,7 @@ export const Video: Component<{ data: VideoProps; size?: number }> = ({
}) => { }) => {
const url = videoUrl(data.id); const url = videoUrl(data.id);
const [width, height] = videoSize([16, 9], size); const [width, height] = videoSize(size);
const menuItems = useMemo(() => { const menuItems = useMemo(() => {
const items: ContextMenuItem[] = [ const items: ContextMenuItem[] = [

@ -19,8 +19,6 @@ const itemPatterns: ItemPattern[] = [
regex: regex:
/https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g, /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g,
convert: (match): Link => { convert: (match): Link => {
console.log(match);
return { return {
type: ItemType.Link, type: ItemType.Link,
href: match[0], href: match[0],

@ -1,6 +1,6 @@
export const videoSize = ( export const videoSize = (
aspectRatio: [number, number], size: number,
size: number aspectRatio: [number, number] = [16, 9]
): [number, number] => { ): [number, number] => {
return [aspectRatio[0] * size, aspectRatio[1] * size]; return [aspectRatio[0] * size, aspectRatio[1] * size];
}; };

Loading…
Cancel
Save