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

nextui
Guus van Meerveld 2 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,37 +37,53 @@ export const Playlist: Component<{ data: PlaylistItem }> = ({ data }) => {
as={NextImage} as={NextImage}
unoptimized unoptimized
/> />
<p className="text-small rounded-md z-10 absolute bottom-2 right-2 bg-content2 p-1"> </NextLink>
{data.numberOfVideos} videos <p className="text-small rounded-md z-10 absolute bottom-2 right-2 bg-content2 p-1">
</p> {data.numberOfVideos} videos
</div> </p>
</div>
<div className="flex flex-col gap-2">
<div>
<h1 className="text-xl">{data.title}</h1>
<Link <div className="flex flex-col gap-2">
as={NextLink} <div>
href={channelUrl} <Link as={NextLink} href={url}>
className="flex flex-row gap-2 items-center" <h1 className="text-xl text-default-foreground">
> {data.title}
<h1 className="text-lg text-default-600"> </h1>
{data.author.name} </Link>
</h1>
</Link>
</div>
{data.videos && ( <Link
<div className="flex flex-col gap-1"> as={NextLink}
{data.videos.map((video) => ( href={channelUrl}
<h1 key={video.id}>{video.title}</h1> className="flex flex-row gap-2 items-center"
))} >
</div> <h1 className="text-lg text-default-600">{data.author.name}</h1>
)} </Link>
</div> </div>
{data.videos && (
<Listbox>
{data.videos.map((video) => (
<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>
))}
</Listbox>
)}
</div> </div>
</CardBody> </div>
</Card> </CardBody>
</NextLink> </Card>
); );
}; };

@ -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>
<div> {canSearch && (
<Filter filter={filter} setFilter={setFilter} /> <div>
</div> <Filter filter={filter} setFilter={setFilter} />
</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,32 +120,34 @@ 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">
return ( {data?.pages.map((page, i) => {
<Fragment key={i}> return (
{page.items.map((result) => { <Fragment key={i}>
switch (result.type) { {page.items.map((result) => {
case "channel": switch (result.type) {
return <Channel key={result.id} data={result} />; case "channel":
return <Channel key={result.id} data={result} />;
case "video":
return <Video key={result.id} data={result} />; case "video":
return <Video key={result.id} data={result} />;
case "playlist":
return <Playlist key={result.id} data={result} />; case "playlist":
} return <Playlist key={result.id} data={result} />;
})} }
</Fragment> })}
); </Fragment>
})} );
})}
<Loading </div>
isFetching={isFetchingNextPage} <Loading
onVisible={handleUserReachedPageEnd} isFetching={isFetchingNextPage && !isPending}
/> 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,43 +36,46 @@ export const Video: Component<{ data: VideoItem }> = ({ data }) => {
as={NextImage} as={NextImage}
unoptimized unoptimized
/> />
<p className="text-small rounded-md z-10 absolute bottom-2 right-2 bg-content2 p-1"> </NextLink>
{formatDuration(data.duration)}
<p className="text-small rounded-md z-10 absolute bottom-2 right-2 bg-content2 p-1">
{formatDuration(data.duration)}
</p>
{data.live && (
<p className="text-small rounded-md z-10 absolute bottom-2 left-2 bg-danger p-1">
LIVE
</p> </p>
{data.live && ( )}
<p className="text-small rounded-md z-10 absolute bottom-2 left-2 bg-danger p-1"> </div>
LIVE
</p>
)}
</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}>
<div className="flex flex-row gap-4 items-center font-semibold text-default-600"> <h1 className="text-xl text-default-foreground">{data.title}</h1>
<h1>{formatBigNumber(data.views)} views</h1> </Link>
{data.uploaded && <h1>{formatUploadedTime(data.uploaded)}</h1>} <div className="flex flex-row gap-4 items-center font-semibold text-default-600">
</div> <h1>{formatBigNumber(data.views)} views</h1>
<Link {data.uploaded && <h1>{formatUploadedTime(data.uploaded)}</h1>}
as={NextLink}
href={channelUrl}
className="flex flex-row gap-2 items-center"
>
{data.author.avatar && (
<Avatar
isBordered
name={data.author.name}
size="lg"
src={data.author.avatar}
alt={data.author.name}
/>
)}
<h1 className="text-lg text-default-600">{data.author.name}</h1>
</Link>
<p className="text-default-600">{data.description}</p>
</div> </div>
<Link
as={NextLink}
href={channelUrl}
className="flex flex-row gap-2 items-center"
>
{data.author.avatar && (
<Avatar
isBordered
name={data.author.name}
size="lg"
src={data.author.avatar}
alt={data.author.name}
/>
)}
<h1 className="text-lg text-default-600">{data.author.name}</h1>
</Link>
<p className="text-default-600">{data.description}</p>
</div> </div>
</CardBody> </div>
</Card> </CardBody>
</NextLink> </Card>
); );
}; };

@ -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