Rework SearchPage with tabs, infinite scroll, and anti-spam

- Add Movies & TV / People tabs next to search input
- Filter person results from movie/TV grid
- People tab with larger avatar cards, name always visible
- Infinite scroll with IntersectionObserver sentinel per tab
- Stop auto-scroll after 4 consecutive empty pages, show Load More button instead
This commit is contained in:
X4Lo committed 2026-06-29 02:49:58 +01:00
1 parent c09f70054c
commit d12d7cb627
1 file changed
+337 -75
+337 -75
View File
@@ -1,19 +1,33 @@
import { useState, useEffect, useRef } from "react"; import {
useState,
useEffect,
useRef,
useCallback,
useMemo,
useReducer,
} from "react";
import { useSearchParams, Link } from "react-router-dom"; import { useSearchParams, Link } from "react-router-dom";
import { useTmdbSearch, useTmdbSearchPeople } from "@/hooks/useTmdb"; import { useTmdbSearch, useTmdbSearchPeople } from "@/hooks/useTmdb";
import { useLibrary } from "@/hooks/useEntries"; import { useLibrary } from "@/hooks/useEntries";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import { Search } from "lucide-react"; import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { EntryCard } from "@/components/entries/EntryCard";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"; import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { getTmdbImageUrl } from "@/lib/api"; import { Button } from "@/components/ui/button";
import { Search, Loader2 } from "lucide-react";
import { EntryCard } from "@/components/entries/EntryCard";
import { getProfileUrl } from "@/lib/media-utils";
type SearchTab = "entries" | "people";
const MAX_EMPTY_PAGES = 4;
export function SearchPage() { export function SearchPage() {
const [searchParams, setSearchParams] = useSearchParams(); const [searchParams, setSearchParams] = useSearchParams();
const initialQuery = searchParams.get("q") || ""; const initialQuery = searchParams.get("q") || "";
const [searchInput, setSearchInput] = useState(initialQuery); const [searchInput, setSearchInput] = useState(initialQuery);
const [debouncedQuery, setDebouncedQuery] = useState(initialQuery); const [debouncedQuery, setDebouncedQuery] = useState(initialQuery);
const debounceRef = useRef<ReturnType<typeof setTimeout>>(); const [activeTab, setActiveTab] = useState<SearchTab>("entries");
const debounceRef = useRef<ReturnType<typeof setTimeout>>(null);
useEffect(() => { useEffect(() => {
if (debounceRef.current) clearTimeout(debounceRef.current); if (debounceRef.current) clearTimeout(debounceRef.current);
@@ -36,90 +50,338 @@ export function SearchPage() {
useLibrary(); useLibrary();
const searchResults = useTmdbSearch(debouncedQuery); const {
const peopleResults = useTmdbSearchPeople(debouncedQuery); data: searchData,
isLoading: searchLoading,
fetchNextPage: fetchNextSearch,
hasNextPage: hasNextSearch,
isFetchingNextPage: fetchingNextSearch,
} = useTmdbSearch(debouncedQuery);
const searchEntries = const peopleQuery = activeTab === "people" ? debouncedQuery : "";
searchResults.data?.pages.flatMap((p) => p.results) ?? [];
const searchPeople = const {
peopleResults.data?.pages.flatMap((p) => p.results) ?? []; data: peopleData,
fetchNextPage: fetchNextPeople,
hasNextPage: hasNextPeople,
isFetchingNextPage: fetchingNextPeople,
} = useTmdbSearchPeople(peopleQuery);
// Filter entries: only movies & TV (TMDB multi-search sometimes returns "person" results)
const searchEntries = useMemo(() => {
const seen = new Set<string>();
const all = searchData?.pages.flatMap((p) => p.results) ?? [];
return all
.filter((entry) => entry.media_type !== "person")
.filter((entry) => {
const key = `${entry.id}-${entry.media_type}`;
if (seen.has(key)) return false;
seen.add(key);
return true;
});
}, [searchData]);
const searchPeople = useMemo(() => {
const seen = new Set<number>();
const all = peopleData?.pages.flatMap((p) => p.results) ?? [];
return all.filter((person) => {
if (seen.has(person.id)) return false;
seen.add(person.id);
return true;
});
}, [peopleData]);
type SpamAction =
| { type: "entry_empty" }
| { type: "entry_found" }
| { type: "people_empty" }
| { type: "people_found" }
| { type: "reset_entry" }
| { type: "reset_people" }
| { type: "reset_all" };
// ── Anti-spam: stop auto-scroll after N consecutive empty pages ──
const prevEntryCountRef = useRef(0);
const prevPeopleCountRef = useRef(0);
const [spam, spamDispatch] = useReducer(
(state: { entry: number; people: number }, action: SpamAction) => {
switch (action.type) {
case "entry_empty":
return { ...state, entry: state.entry + 1 };
case "entry_found":
return { ...state, entry: 0 };
case "people_empty":
return { ...state, people: state.people + 1 };
case "people_found":
return { ...state, people: 0 };
case "reset_entry":
return { ...state, entry: 0 };
case "reset_people":
return { ...state, people: 0 };
case "reset_all":
return { entry: 0, people: 0 };
default:
return state;
}
},
{ entry: 0, people: 0 },
);
const entryLoadMore = spam.entry >= MAX_EMPTY_PAGES;
const peopleLoadMore = spam.people >= MAX_EMPTY_PAGES;
// Reset streak on new query
useEffect(() => {
prevEntryCountRef.current = 0;
prevPeopleCountRef.current = 0;
spamDispatch({ type: "reset_all" });
}, [debouncedQuery]);
// Detect empty entry fetches
useEffect(() => {
if (fetchingNextSearch || searchEntries.length === 0) return;
if (searchEntries.length === prevEntryCountRef.current) {
spamDispatch({ type: "entry_empty" });
} else {
spamDispatch({ type: "entry_found" });
}
prevEntryCountRef.current = searchEntries.length;
}, [fetchingNextSearch, searchEntries.length]);
// Detect empty people fetches
useEffect(() => {
if (fetchingNextPeople || searchPeople.length === 0) return;
if (searchPeople.length === prevPeopleCountRef.current) {
spamDispatch({ type: "people_empty" });
} else {
spamDispatch({ type: "people_found" });
}
prevPeopleCountRef.current = searchPeople.length;
}, [fetchingNextPeople, searchPeople.length]);
// ── Infinite scroll sentinels ──
const entrySentinelRef = useRef<HTMLDivElement>(null);
const peopleSentinelRef = useRef<HTMLDivElement>(null);
const handleEntryIntersect = useCallback(
(entries: IntersectionObserverEntry[]) => {
if (
entries[0]?.isIntersecting &&
hasNextSearch &&
!fetchingNextSearch &&
!entryLoadMore
) {
fetchNextSearch();
}
},
[hasNextSearch, fetchingNextSearch, fetchNextSearch, entryLoadMore],
);
const handlePeopleIntersect = useCallback(
(entries: IntersectionObserverEntry[]) => {
if (
entries[0]?.isIntersecting &&
hasNextPeople &&
!fetchingNextPeople &&
!peopleLoadMore
) {
fetchNextPeople();
}
},
[hasNextPeople, fetchingNextPeople, fetchNextPeople, peopleLoadMore],
);
useEffect(() => {
const sentinel = entrySentinelRef.current;
if (!sentinel) return;
const observer = new IntersectionObserver(handleEntryIntersect, {
rootMargin: "200px",
});
observer.observe(sentinel);
return () => observer.disconnect();
}, [handleEntryIntersect]);
useEffect(() => {
const sentinel = peopleSentinelRef.current;
if (!sentinel || activeTab !== "people") return;
const observer = new IntersectionObserver(handlePeopleIntersect, {
rootMargin: "200px",
});
observer.observe(sentinel);
return () => observer.disconnect();
}, [handlePeopleIntersect, activeTab]);
const isSearching = debouncedQuery.length > 0; const isSearching = debouncedQuery.length > 0;
return ( return (
<div className="space-y-6 animate-page-enter"> <div className="space-y-6 animate-page-enter">
{/* Search */} {/* Search + Tabs row */}
<div className="relative max-w-md"> <div className="flex items-center justify-between gap-3">
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" /> <div className="relative flex-1 max-w-xs">
<Input <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
placeholder="Search movies, TV shows & people..." <Input
value={searchInput} placeholder="Search movies, TV shows & people..."
onChange={(e) => setSearchInput(e.target.value)} value={searchInput}
className="pl-10" onChange={(e) => setSearchInput(e.target.value)}
autoFocus className="pl-10"
/> autoFocus
/>
</div>
{isSearching && (
<Tabs
value={activeTab}
onValueChange={(v) => setActiveTab(v as SearchTab)}
>
<TabsList>
<TabsTrigger value="entries">Movies & TV</TabsTrigger>
<TabsTrigger value="people">People</TabsTrigger>
</TabsList>
</Tabs>
)}
</div> </div>
{isSearching ? ( {isSearching ? (
<div className="space-y-6"> <div className="space-y-4">
{/* People results */} {/* Movies & TV tab */}
{searchPeople.length > 0 && ( {activeTab === "entries" && (
<div className="space-y-3"> <>
<h2 className="text-lg font-semibold">People</h2> <h2 className="text-xl font-semibold">
<div className="flex flex-wrap gap-3"> Results for &ldquo;{debouncedQuery}&rdquo;
{searchPeople.slice(0, 10).map((person) => ( </h2>
<Link {searchEntries.length === 0 && !searchLoading ? (
key={person.id} <p className="text-muted-foreground">No results found.</p>
to={`/people/tmdb/${person.id}`} ) : (
className="flex items-center gap-2 rounded-full bg-muted px-3 py-1.5 transition-colors hover:bg-accent" <>
<div className="grid grid-cols-2 gap-3 sm:gap-4 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 2xl:grid-cols-7">
{searchEntries.map((entry, index) => (
<div
key={`${entry.id}-${entry.media_type}`}
className="animate-card-enter"
style={{
animationDelay: `${Math.min(index * 30, 300)}ms`,
}}
>
<EntryCard tmdbEntry={entry} showTypeBadge />
</div>
))}
</div>
{/* Sentinel / Load more */}
<div
ref={entrySentinelRef}
className="flex h-20 items-center justify-center"
> >
<Avatar className="h-7 w-7"> {fetchingNextSearch ? (
<AvatarImage <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
src={ ) : entryLoadMore && hasNextSearch ? (
person.profile_path <Button
? getTmdbImageUrl(person.profile_path, "w92") variant="outline"
: undefined size="sm"
} onClick={() => {
alt={person.name} spamDispatch({ type: "reset_entry" });
/> fetchNextSearch();
<AvatarFallback className="text-xs"> }}
{person.name >
.split(" ") Load more
.map((n) => n[0]) </Button>
.join("") ) : hasNextSearch ? (
.slice(0, 2)} <span className="text-sm text-muted-foreground">
</AvatarFallback> Scroll for more
</Avatar>
<span className="text-sm font-medium">{person.name}</span>
{person.known_for_department && (
<span className="text-xs text-muted-foreground">
{person.known_for_department}
</span> </span>
)} ) : searchEntries.length > 0 ? (
</Link> <span className="text-sm text-muted-foreground">
))} All results loaded
</div> </span>
</div> ) : null}
</div>
</>
)}
</>
)} )}
{/* Entry results */} {/* People tab */}
<h2 className="text-xl font-semibold"> {activeTab === "people" && (
Search Results for &ldquo;{debouncedQuery}&rdquo; <>
</h2> <h2 className="text-xl font-semibold">
{searchEntries.length === 0 && !searchResults.isLoading ? ( People matching &ldquo;{debouncedQuery}&rdquo;
<p className="text-muted-foreground">No results found.</p> </h2>
) : ( {peopleQuery && searchPeople.length === 0 && !peopleData ? (
<div className="grid grid-cols-2 gap-3 sm:gap-4 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 2xl:grid-cols-7"> <div className="flex h-40 items-center justify-center">
{searchEntries.map((entry, index) => ( <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
<div
key={entry.id}
className="animate-card-enter"
style={{ animationDelay: `${Math.min(index * 30, 300)}ms` }}
>
<EntryCard tmdbEntry={entry} showTypeBadge />
</div> </div>
))} ) : searchPeople.length === 0 && peopleData ? (
</div> <p className="text-muted-foreground">No people found.</p>
) : (
<>
<div className="grid grid-cols-3 gap-4 sm:grid-cols-4 md:grid-cols-5 lg:grid-cols-6 xl:grid-cols-8">
{searchPeople.map((person, index) => (
<Link
key={person.id}
to={`/people/tmdb/${person.id}`}
className="group flex flex-col items-center gap-2 text-center animate-card-enter"
style={{
animationDelay: `${Math.min(index * 20, 300)}ms`,
}}
>
<div className="relative">
<Avatar className="h-28 w-28 transition-transform group-hover:scale-105 sm:h-32 sm:w-32">
<AvatarImage
src={getProfileUrl(person.profile_path)}
alt={person.name}
/>
<AvatarFallback className="text-lg">
{person.name
.split(" ")
.map((n) => n[0])
.join("")
.slice(0, 2)}
</AvatarFallback>
</Avatar>
</div>
<span className="text-sm font-medium leading-tight line-clamp-2">
{person.name}
</span>
{person.known_for_department && (
<span className="text-xs text-muted-foreground">
{person.known_for_department}
</span>
)}
</Link>
))}
</div>
{/* Sentinel / Load more */}
<div
ref={peopleSentinelRef}
className="flex h-20 items-center justify-center"
>
{fetchingNextPeople ? (
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
) : peopleLoadMore && hasNextPeople ? (
<Button
variant="outline"
size="sm"
onClick={() => {
spamDispatch({ type: "reset_people" });
fetchNextPeople();
}}
>
Load more
</Button>
) : hasNextPeople ? (
<span className="text-sm text-muted-foreground">
Scroll for more
</span>
) : searchPeople.length > 0 ? (
<span className="text-sm text-muted-foreground">
All results loaded
</span>
) : null}
</div>
</>
)}
</>
)} )}
</div> </div>
) : ( ) : (