import { useEffect, useRef, useState } from 'react'; import * as api from '../plex/api'; import { useServerQuery } from '../app/queries'; import { navigate, useRouter } from '../app/router'; import type { Item } from '../plex/types'; import { LandscapeCard, PersonCard, PosterCard, Shelf } from '../ui/media'; import { EmptyState, ErrorState, Spinner } from '../ui/primitives'; import { Icon } from '../ui/Icon'; const RECENT_KEY = 'kaleido.recentSearches'; const loadRecent = (): string[] => { try { return JSON.parse(localStorage.getItem(RECENT_KEY) ?? '[]'); } catch { return []; } }; /** Plex search ranks per hub; float exact and prefix title matches to the top. */ function rank(query: string, items: Item[]): Item[] { const q = query.toLowerCase(); const score = (i: Item) => { const t = (i.type === 'episode' ? i.title : i.title).toLowerCase(); if (t === q) return 0; if (t.startsWith(q)) return 1; if (t.split(/\W+/).some((w) => w.startsWith(q))) return 2; return 3; }; return [...items].sort((a, b) => score(a) - score(b)); } export default function Search({ initial }: { initial?: string }) { const saved = useRouter((s) => s.current.state.query as string | undefined); const [query, setQuery] = useState(saved ?? initial ?? ''); const [debounced, setDebounced] = useState(query); const [recent, setRecent] = useState(loadRecent); const input = useRef(null); useEffect(() => { input.current?.focus(); }, []); useEffect(() => { const t = setTimeout(() => setDebounced(query.trim()), 250); useRouter.getState().setState({ query }); return () => clearTimeout(t); }, [query]); const results = useServerQuery(['search', debounced], (s) => api.search(s, debounced), { enabled: debounced.length > 0, staleTime: 60_000 }); const recentlyAdded = useServerQuery(['homeHubs'], (s) => api.homeHubs(s), { enabled: !debounced }); const remember = (q: string) => { const next = [q, ...recent.filter((r) => r.toLowerCase() !== q.toLowerCase())].slice(0, 8); setRecent(next); localStorage.setItem(RECENT_KEY, JSON.stringify(next)); }; const hubs = results.data?.hubs ?? []; const all = hubs.flatMap((h) => h.items); const movies = rank(debounced, all.filter((i) => i.type === 'movie')); const shows = rank(debounced, all.filter((i) => i.type === 'show')); const episodes = rank(debounced, all.filter((i) => i.type === 'episode')); const collections = all.filter((i) => i.type === 'collection'); const people = results.data?.people ?? []; const top = rank(debounced, [...movies, ...shows]).slice(0, 6); const inTop = new Set(top.map((i) => i.id)); const moreMovies = movies.filter((i) => !inTop.has(i.id)); const moreShows = shows.filter((i) => !inTop.has(i.id)); return (
setQuery(e.target.value)} onKeyDown={(e) => { if (e.key === 'Enter' && query.trim()) remember(query.trim()); if (e.key === 'Escape') { e.stopPropagation(); if (query) setQuery(''); else useRouter.getState().back(); } }} /> {results.isFetching && } {query && ( )}
{!debounced && (
{recent.length > 0 && (

Recent searches

{recent.map((r) => ( ))}
)} {recentlyAdded.data ?.filter((h) => /recent/.test(h.id)) .slice(0, 2) .map((h) => ( {h.items.map((i) => ( ))} ))}
)} {debounced && results.isError && results.refetch()} />} {debounced && results.data && !all.length && !people.length && ( Check the spelling, or search for an actor, director or episode title. )} {debounced && results.data && (
remember(debounced)}> {top.length > 0 && (

Top results

{top.map((i) => ( ))}
)} {moreMovies.length > 0 && ( {moreMovies.map((i) => ( ))} )} {moreShows.length > 0 && ( {moreShows.map((i) => ( ))} )} {episodes.length > 0 && ( {episodes.map((i) => ( ))} )} {people.length > 0 && ( {people.map((p) => ( navigate({ name: 'person', id: p.id, title: p.tag, thumb: p.thumb })} /> ))} )} {collections.length > 0 && ( {collections.map((i) => ( ))} )}
)}
); }