Files
Showy/react_frontend/src/pages/SearchPage.tsx
T
X4Lo d12d7cb627 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
2026-06-29 02:49:58 +01:00

395 lines
14 KiB
TypeScript

import {
useState,
useEffect,
useRef,
useCallback,
useMemo,
useReducer,
} from "react";
import { useSearchParams, Link } from "react-router-dom";
import { useTmdbSearch, useTmdbSearchPeople } from "@/hooks/useTmdb";
import { useLibrary } from "@/hooks/useEntries";
import { Input } from "@/components/ui/input";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
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() {
const [searchParams, setSearchParams] = useSearchParams();
const initialQuery = searchParams.get("q") || "";
const [searchInput, setSearchInput] = useState(initialQuery);
const [debouncedQuery, setDebouncedQuery] = useState(initialQuery);
const [activeTab, setActiveTab] = useState<SearchTab>("entries");
const debounceRef = useRef<ReturnType<typeof setTimeout>>(null);
useEffect(() => {
if (debounceRef.current) clearTimeout(debounceRef.current);
debounceRef.current = setTimeout(() => {
setDebouncedQuery(searchInput);
}, 400);
return () => {
if (debounceRef.current) clearTimeout(debounceRef.current);
};
}, [searchInput]);
// Sync debounced query to URL
useEffect(() => {
if (debouncedQuery) {
setSearchParams({ q: debouncedQuery }, { replace: true });
} else {
setSearchParams({}, { replace: true });
}
}, [debouncedQuery, setSearchParams]);
useLibrary();
const {
data: searchData,
isLoading: searchLoading,
fetchNextPage: fetchNextSearch,
hasNextPage: hasNextSearch,
isFetchingNextPage: fetchingNextSearch,
} = useTmdbSearch(debouncedQuery);
const peopleQuery = activeTab === "people" ? debouncedQuery : "";
const {
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;
return (
<div className="space-y-6 animate-page-enter">
{/* Search + Tabs row */}
<div className="flex items-center justify-between gap-3">
<div className="relative flex-1 max-w-xs">
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input
placeholder="Search movies, TV shows & people..."
value={searchInput}
onChange={(e) => setSearchInput(e.target.value)}
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>
{isSearching ? (
<div className="space-y-4">
{/* Movies & TV tab */}
{activeTab === "entries" && (
<>
<h2 className="text-xl font-semibold">
Results for &ldquo;{debouncedQuery}&rdquo;
</h2>
{searchEntries.length === 0 && !searchLoading ? (
<p className="text-muted-foreground">No results found.</p>
) : (
<>
<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"
>
{fetchingNextSearch ? (
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
) : entryLoadMore && hasNextSearch ? (
<Button
variant="outline"
size="sm"
onClick={() => {
spamDispatch({ type: "reset_entry" });
fetchNextSearch();
}}
>
Load more
</Button>
) : hasNextSearch ? (
<span className="text-sm text-muted-foreground">
Scroll for more
</span>
) : searchEntries.length > 0 ? (
<span className="text-sm text-muted-foreground">
All results loaded
</span>
) : null}
</div>
</>
)}
</>
)}
{/* People tab */}
{activeTab === "people" && (
<>
<h2 className="text-xl font-semibold">
People matching &ldquo;{debouncedQuery}&rdquo;
</h2>
{peopleQuery && searchPeople.length === 0 && !peopleData ? (
<div className="flex h-40 items-center justify-center">
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
</div>
) : searchPeople.length === 0 && peopleData ? (
<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 className="flex h-40 items-center justify-center text-muted-foreground">
Start typing to search...
</div>
)}
</div>
);
}