import { useEffect, useState } from 'react' import { useLocation, useSearchParams } from 'react-router-dom' import { ChevronLeft, ChevronRight, LoaderCircle, RefreshCw, Search } from 'lucide-react' import { mediaAPI, type MediaSearchPage as SearchPageData } from '../api/library' import { libraryAPI } from '../api/library' import { MediaCard } from '../components/MediaCard' import type { Library } from '../types' import { PageBackButton } from '../components/PageBackButton' import { normalizeListPosition } from '../hooks/useListPositionMemory' import { useAuthStore } from '../stores/auth' import { usePlayProfileStore } from '../stores/playProfile' import { favouriteMediaLink } from '../utils/mediaNavigation' const PAGE_SIZE = 48 const CACHE_TTL_MS = 5 * 60_000 // 返回详情前的结果可立即显示;按账号、播放档案、关键词和页码隔离。 const pageCache = new Map() function readCachedPage(key: string): SearchPageData | null { const cached = pageCache.get(key) if (!cached) return null if (Date.now() - cached.at >= CACHE_TTL_MS) { pageCache.delete(key) return null } return cached.data } export function MediaSearchPage() { const [params, setParams] = useSearchParams() const query = (params.get('q') ?? '').trim() const page = normalizeListPosition(params.get('page')) const filters = { libraryId: params.get('library_id') ?? '', yearMin: params.get('year_min') ?? '', yearMax: params.get('year_max') ?? '', genres: params.get('genre') ?? '', sort: params.get('sort') ?? '', } const userId = useAuthStore((s) => s.user?.id) const profileId = usePlayProfileStore((s) => s.activeProfileId) const cacheKey = JSON.stringify([userId, profileId, query, page, filters]) const changePage = (next: number) => { const nextParams = new URLSearchParams(params) nextParams.set('q', query) if (next > 1) nextParams.set('page', String(next)) else nextParams.delete('page') setParams(nextParams) } const changeFilter = (key: keyof typeof filters, value: string) => { const next = new URLSearchParams(params) const queryKey = { libraryId: 'library_id', yearMin: 'year_min', yearMax: 'year_max', genres: 'genre', sort: 'sort' }[key] if (value.trim()) next.set(queryKey, value) else next.delete(queryKey) next.delete('page') setParams(next, { replace: true }) } return ( ) } function MediaSearchResults({ cacheKey, query, page, onPageChange, filters, onFilterChange }: { cacheKey: string query: string page: number onPageChange: (page: number) => void filters: { libraryId: string; yearMin: string; yearMax: string; genres: string; sort: string } onFilterChange: (key: keyof { libraryId: string; yearMin: string; yearMax: string; genres: string; sort: string }, value: string) => void }) { const location = useLocation() const [data, setData] = useState(() => readCachedPage(cacheKey)) const [loading, setLoading] = useState(() => !!query && !readCachedPage(cacheKey)) const [error, setError] = useState('') const [revision, setRevision] = useState(0) const [libraries, setLibraries] = useState([]) useEffect(() => { void libraryAPI.list().then(setLibraries).catch(() => setLibraries([])) }, []) useEffect(() => { if (!query) { setData(null) setLoading(false) setError('') return } setError('') const cached = readCachedPage(cacheKey) if (cached) { setData(cached) setLoading(false) return } let cancelled = false setLoading(true) setData(null) mediaAPI.searchPage(query, page, PAGE_SIZE, { groupSeries: true, libraryId: filters.libraryId || undefined, yearMin: Number(filters.yearMin) || undefined, yearMax: Number(filters.yearMax) || undefined, genres: filters.genres.split(/[,,]/).map((value) => value.trim()).filter(Boolean), sort: filters.sort === 'title_asc' || filters.sort === 'year_desc' || filters.sort === 'rating_desc' ? filters.sort : undefined, }) .then((result) => { if (cancelled) return // 限制缓存大小,避免长时间搜索大量关键词后占用过多内存。 if (pageCache.size >= 20) pageCache.delete(pageCache.keys().next().value!) pageCache.set(cacheKey, { at: Date.now(), data: result }) setData(result) }) .catch(() => { if (!cancelled) setError('搜索失败,请稍后重试') }) .finally(() => { if (!cancelled) setLoading(false) }) return () => { cancelled = true } }, [cacheKey, query, page, revision, filters.libraryId, filters.yearMin, filters.yearMax, filters.genres, filters.sort]) const refresh = () => { pageCache.delete(cacheKey) setRevision((value) => value + 1) } const items = data?.items ?? [] const total = data?.total ?? items.length const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE)) const from = location.pathname + location.search return (

搜索结果

{query ? <>“{query}”{data && !loading ? ` · 共 ${total} 条结果` : ''} : '在顶部搜索框输入媒体名称,按回车开始搜索'}

{query && ( )}
{query && (
)} {loading && (
正在搜索…
)} {error && (
{error}
)} {!loading && !error && query && items.length === 0 && (

未搜索到与 “{query}” 相关的媒体内容

试试其他名称或更简短的关键词

)} {!loading && !error && query && items.length > 0 && (
{items.map((item) => ( ))}
)} {!loading && !error && query && (totalPages > 1 || page > 1) && ( )}
) }