Kaleido-Desktop/src/screens/Search.tsx
Elijah 00d72e70f4 Create Kaleido Desktop, a cinematic Plex client for Windows
Tauri 2 shell with a React/TypeScript interface and libmpv playback composed
beneath the web view (DirectComposition on Windows). Shared code with per-OS
platform modules and configs so macOS and Linux can follow.

- Plex sign-in (browser, plex.tv/link or manual), server selection, Plex Home
- Home, Movies and TV Shows (Discover, Library, Collections), search, people
- Title pages with logos, ratings, cast, extras, seasons and episodes
- Direct play with Plex conversion fallback, tracks, markers, autoplay
- Metadata editing, artwork, fix match, refresh, analyze and deletion
- Resumable offline downloads
- App settings and Plex server administration with a live dashboard
- Signed updater feed and Forgejo CI

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 16:26:37 -07:00

191 lines
7 KiB
TypeScript

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<HTMLInputElement>(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 (
<div className="search-page page-pad top">
<div className="search-hero">
<div className="search-field">
<Icon name="search" size={22} />
<input
ref={input}
value={query}
placeholder="Search movies, shows, episodes and people"
onChange={(e) => 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 && <Spinner size={18} />}
{query && (
<button className="icon-btn" aria-label="Clear search" onClick={() => (setQuery(''), input.current?.focus())}>
<Icon name="x" size={17} />
</button>
)}
</div>
</div>
{!debounced && (
<div className="search-idle">
{recent.length > 0 && (
<div className="recent-searches">
<h3>Recent searches</h3>
<div className="chips">
{recent.map((r) => (
<button key={r} className="chip" onClick={() => setQuery(r)}>
<Icon name="clock" size={13} />
{r}
</button>
))}
<button
className="btn text"
onClick={() => {
setRecent([]);
localStorage.removeItem(RECENT_KEY);
}}
>
Clear
</button>
</div>
</div>
)}
{recentlyAdded.data
?.filter((h) => /recent/.test(h.id))
.slice(0, 2)
.map((h) => (
<Shelf key={h.id} title={h.title} className="flush">
{h.items.map((i) => (
<PosterCard key={i.id} item={i} />
))}
</Shelf>
))}
</div>
)}
{debounced && results.isError && <ErrorState error={results.error} onRetry={() => results.refetch()} />}
{debounced && results.data && !all.length && !people.length && (
<EmptyState icon="search" title={`No results for “${debounced}”`}>
Check the spelling, or search for an actor, director or episode title.
</EmptyState>
)}
{debounced && results.data && (
<div className="search-results" onClick={() => remember(debounced)}>
{top.length > 0 && (
<section className="search-top">
<h3>Top results</h3>
<div className="poster-grid auto">
{top.map((i) => (
<PosterCard key={i.id} item={i} />
))}
</div>
</section>
)}
{moreMovies.length > 0 && (
<Shelf title="More movies" className="flush">
{moreMovies.map((i) => (
<PosterCard key={i.id} item={i} />
))}
</Shelf>
)}
{moreShows.length > 0 && (
<Shelf title="More TV shows" className="flush">
{moreShows.map((i) => (
<PosterCard key={i.id} item={i} />
))}
</Shelf>
)}
{episodes.length > 0 && (
<Shelf title="Episodes" kind="landscape" className="flush">
{episodes.map((i) => (
<LandscapeCard key={i.id} item={i} />
))}
</Shelf>
)}
{people.length > 0 && (
<Shelf title="People" kind="people" className="flush">
{people.map((p) => (
<PersonCard key={p.id} name={p.tag} thumb={p.thumb} onClick={() => navigate({ name: 'person', id: p.id, title: p.tag, thumb: p.thumb })} />
))}
</Shelf>
)}
{collections.length > 0 && (
<Shelf title="Collections" className="flush">
{collections.map((i) => (
<PosterCard key={i.id} item={i} />
))}
</Shelf>
)}
</div>
)}
</div>
);
}