mirror of
https://github.com/truewhile/MeBox.git
synced 2026-11-12 19:34:24 +08:00
优化媒体搜索页面与返回状态保留
This commit is contained in:
@@ -6,6 +6,7 @@ const HomePageLoader = () => import('./pages/HomePage').then((m) => ({ default:
|
|||||||
const LibraryPageLoader = () => import('./pages/LibraryPage').then((m) => ({ default: m.LibraryPage }))
|
const LibraryPageLoader = () => import('./pages/LibraryPage').then((m) => ({ default: m.LibraryPage }))
|
||||||
const LibrariesPageLoader = () => import('./pages/LibrariesPage').then((m) => ({ default: m.LibrariesPage }))
|
const LibrariesPageLoader = () => import('./pages/LibrariesPage').then((m) => ({ default: m.LibrariesPage }))
|
||||||
const FavouritesPageLoader = () => import('./pages/FavouritesPage').then((m) => ({ default: m.FavouritesPage }))
|
const FavouritesPageLoader = () => import('./pages/FavouritesPage').then((m) => ({ default: m.FavouritesPage }))
|
||||||
|
const MediaSearchPageLoader = () => import('./pages/MediaSearchPage').then((m) => ({ default: m.MediaSearchPage }))
|
||||||
const PlaylistsPageLoader = () => import('./pages/PlaylistsPage').then((m) => ({ default: m.PlaylistsPage }))
|
const PlaylistsPageLoader = () => import('./pages/PlaylistsPage').then((m) => ({ default: m.PlaylistsPage }))
|
||||||
const PlaylistDetailPageLoader = () =>
|
const PlaylistDetailPageLoader = () =>
|
||||||
import('./pages/PlaylistDetailPage').then((m) => ({ default: m.PlaylistDetailPage }))
|
import('./pages/PlaylistDetailPage').then((m) => ({ default: m.PlaylistDetailPage }))
|
||||||
@@ -21,6 +22,7 @@ const HomePage = lazy(HomePageLoader)
|
|||||||
const LibraryPage = lazy(LibraryPageLoader)
|
const LibraryPage = lazy(LibraryPageLoader)
|
||||||
const LibrariesPage = lazy(LibrariesPageLoader)
|
const LibrariesPage = lazy(LibrariesPageLoader)
|
||||||
const FavouritesPage = lazy(FavouritesPageLoader)
|
const FavouritesPage = lazy(FavouritesPageLoader)
|
||||||
|
const MediaSearchPage = lazy(MediaSearchPageLoader)
|
||||||
const PlaylistsPage = lazy(PlaylistsPageLoader)
|
const PlaylistsPage = lazy(PlaylistsPageLoader)
|
||||||
const PlaylistDetailPage = lazy(PlaylistDetailPageLoader)
|
const PlaylistDetailPage = lazy(PlaylistDetailPageLoader)
|
||||||
const MediaDetailPage = lazy(MediaDetailPageLoader)
|
const MediaDetailPage = lazy(MediaDetailPageLoader)
|
||||||
@@ -73,6 +75,7 @@ export function prefetchCommonRouteChunks() {
|
|||||||
LibrariesPageLoader,
|
LibrariesPageLoader,
|
||||||
LibraryPageLoader,
|
LibraryPageLoader,
|
||||||
MediaDetailPageLoader,
|
MediaDetailPageLoader,
|
||||||
|
MediaSearchPageLoader,
|
||||||
FavouritesPageLoader,
|
FavouritesPageLoader,
|
||||||
WatchHistoryPageLoader,
|
WatchHistoryPageLoader,
|
||||||
PlaylistsPageLoader,
|
PlaylistsPageLoader,
|
||||||
@@ -98,6 +101,7 @@ export type AppRoute = {
|
|||||||
|
|
||||||
export const appRoutes: AppRoute[] = [
|
export const appRoutes: AppRoute[] = [
|
||||||
{ index: true, element: <HomePage /> },
|
{ index: true, element: <HomePage /> },
|
||||||
|
{ path: 'search', element: <MediaSearchPage /> },
|
||||||
{ path: 'libraries', element: <LibrariesPage /> },
|
{ path: 'libraries', element: <LibrariesPage /> },
|
||||||
{ path: 'library/:id', element: <LibraryPage /> },
|
{ path: 'library/:id', element: <LibraryPage /> },
|
||||||
{ path: 'favourites', element: <FavouritesPage /> },
|
{ path: 'favourites', element: <FavouritesPage /> },
|
||||||
|
|||||||
@@ -25,6 +25,7 @@ function isMediaView(pathname: string, search: string): boolean {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
pathname === '/' ||
|
pathname === '/' ||
|
||||||
|
pathname === '/search' ||
|
||||||
pathname === '/libraries' ||
|
pathname === '/libraries' ||
|
||||||
pathname.startsWith('/library') ||
|
pathname.startsWith('/library') ||
|
||||||
pathname.startsWith('/media') ||
|
pathname.startsWith('/media') ||
|
||||||
|
|||||||
@@ -7,7 +7,9 @@ import { ARTWORK, imageURL } from '../api/client'
|
|||||||
import { mediaAPI } from '../api/library'
|
import { mediaAPI } from '../api/library'
|
||||||
import { readerAPI, type ReaderBook } from '../api/reader'
|
import { readerAPI, type ReaderBook } from '../api/reader'
|
||||||
import type { Media, PlayProfile, User } from '../types'
|
import type { Media, PlayProfile, User } from '../types'
|
||||||
import { favouriteMediaLink } from '../utils/mediaNavigation'
|
import { favouriteMediaLink, mediaSearchLink, mediaSearchReturnPath } from '../utils/mediaNavigation'
|
||||||
|
import { useAuthStore } from '../stores/auth'
|
||||||
|
import { usePlayProfileStore } from '../stores/playProfile'
|
||||||
import { resolveHeaderBack } from './layoutNavigation'
|
import { resolveHeaderBack } from './layoutNavigation'
|
||||||
import { LayoutThemeToggle } from './LayoutThemeToggle'
|
import { LayoutThemeToggle } from './LayoutThemeToggle'
|
||||||
import { LayoutUserMenu } from './LayoutUserMenu'
|
import { LayoutUserMenu } from './LayoutUserMenu'
|
||||||
@@ -56,7 +58,11 @@ export function LayoutHeader({
|
|||||||
pathname = '',
|
pathname = '',
|
||||||
}: LayoutHeaderProps) {
|
}: LayoutHeaderProps) {
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
const headerBack = resolveHeaderBack(pathname)
|
const location = useLocation()
|
||||||
|
const searchFrom = mediaSearchReturnPath(location.state)
|
||||||
|
const headerBack = searchFrom && (pathname.startsWith('/library/') || pathname.startsWith('/media/'))
|
||||||
|
? { to: searchFrom, label: '搜索结果' }
|
||||||
|
: resolveHeaderBack(pathname)
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<header className="relative z-30 flex h-16 shrink-0 items-center justify-between gap-2 border-b border-[var(--app-border)] bg-[var(--app-header-bg)] px-3 backdrop-blur-md sm:h-20 sm:gap-4 sm:px-4 md:px-8">
|
<header className="relative z-30 flex h-16 shrink-0 items-center justify-between gap-2 border-b border-[var(--app-border)] bg-[var(--app-header-bg)] px-3 backdrop-blur-md sm:h-20 sm:gap-4 sm:px-4 md:px-8">
|
||||||
@@ -295,7 +301,12 @@ function LayoutHeaderBookSearch() {
|
|||||||
const SEARCH_PAGE_SIZE = 8
|
const SEARCH_PAGE_SIZE = 8
|
||||||
|
|
||||||
function LayoutHeaderSearch() {
|
function LayoutHeaderSearch() {
|
||||||
const [query, setQuery] = useState('')
|
const location = useLocation()
|
||||||
|
const userId = useAuthStore((s) => s.user?.id)
|
||||||
|
const profileId = usePlayProfileStore((s) => s.activeProfileId)
|
||||||
|
const [query, setQuery] = useState(() =>
|
||||||
|
location.pathname === '/search' ? new URLSearchParams(location.search).get('q') ?? '' : '',
|
||||||
|
)
|
||||||
const [isOpen, setIsOpen] = useState(false)
|
const [isOpen, setIsOpen] = useState(false)
|
||||||
const [loading, setLoading] = useState(false)
|
const [loading, setLoading] = useState(false)
|
||||||
const [loadingMore, setLoadingMore] = useState(false)
|
const [loadingMore, setLoadingMore] = useState(false)
|
||||||
@@ -312,7 +323,6 @@ function LayoutHeaderSearch() {
|
|||||||
const resultsRef = useRef<Media[]>([])
|
const resultsRef = useRef<Media[]>([])
|
||||||
const hasMoreRef = useRef(false)
|
const hasMoreRef = useRef(false)
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
const location = useLocation()
|
|
||||||
const locationKey = `${location.pathname}${location.search}`
|
const locationKey = `${location.pathname}${location.search}`
|
||||||
const prevLocationKeyRef = useRef(locationKey)
|
const prevLocationKeyRef = useRef(locationKey)
|
||||||
|
|
||||||
@@ -392,14 +402,21 @@ function LayoutHeaderSearch() {
|
|||||||
}
|
}
|
||||||
}, 250)
|
}, 250)
|
||||||
|
|
||||||
return () => clearTimeout(timer)
|
return () => {
|
||||||
}, [query])
|
clearTimeout(timer)
|
||||||
|
// 卸载或关键词变化时,已发出的旧请求也不能覆盖当前结果。
|
||||||
|
searchSeqRef.current += 1
|
||||||
|
}
|
||||||
|
}, [query, userId, profileId])
|
||||||
|
|
||||||
useLayoutEffect(() => {
|
useLayoutEffect(() => {
|
||||||
if (prevLocationKeyRef.current === locationKey) return
|
if (prevLocationKeyRef.current === locationKey) return
|
||||||
prevLocationKeyRef.current = locationKey
|
prevLocationKeyRef.current = locationKey
|
||||||
dismissSearchRef.current(true)
|
dismissSearchRef.current(false)
|
||||||
}, [locationKey])
|
if (location.pathname === '/search') {
|
||||||
|
setQuery(new URLSearchParams(location.search).get('q') ?? '')
|
||||||
|
}
|
||||||
|
}, [locationKey, location.pathname, location.search])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
function handlePointerDown(e: PointerEvent) {
|
function handlePointerDown(e: PointerEvent) {
|
||||||
@@ -446,28 +463,34 @@ function LayoutHeaderSearch() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleSelect = (item: Media) => {
|
const openSearchPage = () => {
|
||||||
if (suppressInputRef.current) return
|
if (suppressInputRef.current) return
|
||||||
const to = favouriteMediaLink(item)
|
const trimmed = query.trim()
|
||||||
dismissSearch(true)
|
if (!trimmed) return
|
||||||
navigate(to)
|
dismissSearch(false)
|
||||||
|
navigate(mediaSearchLink(trimmed))
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleKeyDown = (e: React.KeyboardEvent) => {
|
const handleKeyDown = (e: React.KeyboardEvent) => {
|
||||||
if (e.key === 'Escape') {
|
if (e.key === 'Escape') {
|
||||||
dismissSearch(false)
|
dismissSearch(false)
|
||||||
} else if (e.key === 'Enter' && results.length > 0) {
|
} else if (e.key === 'Enter' && !e.nativeEvent.isComposing && e.keyCode !== 229) {
|
||||||
handleSelect(results[0])
|
e.preventDefault()
|
||||||
|
openSearchPage()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div ref={containerRef} className="relative w-full">
|
<div ref={containerRef} className="relative w-full">
|
||||||
<div className="relative flex items-center">
|
<div className="relative flex items-center">
|
||||||
<Search
|
<button
|
||||||
size={15}
|
type="button"
|
||||||
className="absolute left-3 text-[var(--app-muted)] pointer-events-none transition-colors group-focus-within:text-brand-500 sm:left-3.5 sm:text-[16px]"
|
onClick={openSearchPage}
|
||||||
/>
|
aria-label="搜索媒体"
|
||||||
|
className="absolute left-3 rounded text-[var(--app-muted)] transition-colors hover:text-brand-500 sm:left-3.5"
|
||||||
|
>
|
||||||
|
<Search size={15} />
|
||||||
|
</button>
|
||||||
<input
|
<input
|
||||||
ref={inputRef}
|
ref={inputRef}
|
||||||
type="text"
|
type="text"
|
||||||
@@ -488,6 +511,7 @@ function LayoutHeaderSearch() {
|
|||||||
}}
|
}}
|
||||||
onKeyDown={handleKeyDown}
|
onKeyDown={handleKeyDown}
|
||||||
placeholder="搜索媒体…"
|
placeholder="搜索媒体…"
|
||||||
|
aria-label="搜索媒体关键词"
|
||||||
className="w-full h-9 sm:h-10 pl-8 sm:pl-10 pr-8 sm:pr-9 rounded-xl sm:rounded-2xl border border-[var(--app-border)] bg-[var(--app-panel)] text-xs sm:text-sm text-[var(--app-text)] placeholder:text-[var(--app-muted)] shadow-sm outline-none transition-all duration-200 focus:border-brand-500 focus:ring-2 focus:ring-brand-500/20 focus:bg-[var(--app-panel-elevated)]"
|
className="w-full h-9 sm:h-10 pl-8 sm:pl-10 pr-8 sm:pr-9 rounded-xl sm:rounded-2xl border border-[var(--app-border)] bg-[var(--app-panel)] text-xs sm:text-sm text-[var(--app-text)] placeholder:text-[var(--app-muted)] shadow-sm outline-none transition-all duration-200 focus:border-brand-500 focus:ring-2 focus:ring-brand-500/20 focus:bg-[var(--app-panel-elevated)]"
|
||||||
/>
|
/>
|
||||||
{loading ? (
|
{loading ? (
|
||||||
@@ -498,6 +522,7 @@ function LayoutHeaderSearch() {
|
|||||||
onClick={() => {
|
onClick={() => {
|
||||||
dismissSearch(true)
|
dismissSearch(true)
|
||||||
}}
|
}}
|
||||||
|
aria-label="清空媒体搜索"
|
||||||
className="absolute right-3 text-[var(--app-muted)] hover:text-[var(--app-text)] p-0.5 rounded-lg"
|
className="absolute right-3 text-[var(--app-muted)] hover:text-[var(--app-text)] p-0.5 rounded-lg"
|
||||||
>
|
>
|
||||||
<X size={15} />
|
<X size={15} />
|
||||||
@@ -538,15 +563,11 @@ function LayoutHeaderSearch() {
|
|||||||
) : (
|
) : (
|
||||||
<div className="space-y-1">
|
<div className="space-y-1">
|
||||||
{results.map((item) => (
|
{results.map((item) => (
|
||||||
<button
|
<Link
|
||||||
key={item.id}
|
key={item.id}
|
||||||
type="button"
|
to={favouriteMediaLink(item)}
|
||||||
onPointerDown={(e) => {
|
state={{ from: locationKey }}
|
||||||
if (e.button !== 0) return
|
onClick={() => dismissSearch(false)}
|
||||||
e.preventDefault()
|
|
||||||
handleSelect(item)
|
|
||||||
}}
|
|
||||||
onClick={() => handleSelect(item)}
|
|
||||||
className="flex w-full items-center gap-3 rounded-xl p-2 text-left transition-colors hover:bg-[var(--app-hover)] group"
|
className="flex w-full items-center gap-3 rounded-xl p-2 text-left transition-colors hover:bg-[var(--app-hover)] group"
|
||||||
>
|
>
|
||||||
<div className="relative h-12 w-9 shrink-0 overflow-hidden rounded-lg bg-[var(--app-panel-soft)]">
|
<div className="relative h-12 w-9 shrink-0 overflow-hidden rounded-lg bg-[var(--app-panel-soft)]">
|
||||||
@@ -590,7 +611,7 @@ function LayoutHeaderSearch() {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</button>
|
</Link>
|
||||||
))}
|
))}
|
||||||
{loadingMore && (
|
{loadingMore && (
|
||||||
<div className="flex items-center justify-center gap-2 py-3 text-[10px] text-[var(--app-muted)]">
|
<div className="flex items-center justify-center gap-2 py-3 text-[10px] text-[var(--app-muted)]">
|
||||||
@@ -605,6 +626,15 @@ function LayoutHeaderSearch() {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
<Link
|
||||||
|
to={mediaSearchLink(query)}
|
||||||
|
onClick={() => dismissSearch(false)}
|
||||||
|
className="sticky -bottom-2 flex items-center justify-center gap-2 border-t border-[var(--app-border)] bg-[var(--app-panel)] px-3 py-3 text-xs font-bold text-brand-500 hover:bg-[var(--app-hover)]"
|
||||||
|
>
|
||||||
|
<Search size={14} />
|
||||||
|
查看全部搜索结果
|
||||||
|
<span className="hidden text-[10px] font-normal text-[var(--app-muted)] sm:inline">按回车搜索</span>
|
||||||
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -74,7 +74,7 @@ export const MOBILE_BOTTOM_NAV_ITEMS: MobileBottomNavItem[] = [
|
|||||||
},
|
},
|
||||||
]
|
]
|
||||||
|
|
||||||
const ROOT_MEDIA_PATHS = new Set(['/', '/libraries', '/favourites', '/playlists', '/history'])
|
const ROOT_MEDIA_PATHS = new Set(['/', '/search', '/libraries', '/favourites', '/playlists', '/history'])
|
||||||
|
|
||||||
/** True only for the fullscreen player route (`/play` or `/play/:id`), not `/playlists`. */
|
/** True only for the fullscreen player route (`/play` or `/play/:id`), not `/playlists`. */
|
||||||
export function isPlayerRoute(pathname: string): boolean {
|
export function isPlayerRoute(pathname: string): boolean {
|
||||||
@@ -131,7 +131,7 @@ export function resolveHeaderBack(pathname: string): HeaderBackTarget | null {
|
|||||||
if (pathname === '/history/stats') {
|
if (pathname === '/history/stats') {
|
||||||
return { to: '/history', label: '观看历史' }
|
return { to: '/history', label: '观看历史' }
|
||||||
}
|
}
|
||||||
if (pathname === '/playlists' || pathname === '/favourites' || pathname === '/history') {
|
if (pathname === '/search' || pathname === '/playlists' || pathname === '/favourites' || pathname === '/history') {
|
||||||
return { to: '/', label: '首页' }
|
return { to: '/', label: '首页' }
|
||||||
}
|
}
|
||||||
if (pathname.startsWith('/playlist/')) {
|
if (pathname.startsWith('/playlist/')) {
|
||||||
@@ -171,6 +171,7 @@ export function shouldShowMobileBottomNav(pathname: string): boolean {
|
|||||||
if (isPlayerRoute(pathname)) return false
|
if (isPlayerRoute(pathname)) return false
|
||||||
return (
|
return (
|
||||||
pathname === '/' ||
|
pathname === '/' ||
|
||||||
|
pathname === '/search' ||
|
||||||
pathname === '/libraries' ||
|
pathname === '/libraries' ||
|
||||||
pathname.startsWith('/library') ||
|
pathname.startsWith('/library') ||
|
||||||
pathname.startsWith('/media') ||
|
pathname.startsWith('/media') ||
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ function check(name: string, condition: boolean) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
check('home remembers scroll', shouldRememberScroll('/'))
|
check('home remembers scroll', shouldRememberScroll('/'))
|
||||||
|
check('media search remembers scroll', shouldRememberScroll('/search'))
|
||||||
check('library list remembers scroll', shouldRememberScroll('/libraries'))
|
check('library list remembers scroll', shouldRememberScroll('/libraries'))
|
||||||
check('library detail remembers scroll', shouldRememberScroll('/library/lib-1'))
|
check('library detail remembers scroll', shouldRememberScroll('/library/lib-1'))
|
||||||
check('library series panel remembers scroll', shouldRememberScroll('/library/lib-1'))
|
check('library series panel remembers scroll', shouldRememberScroll('/library/lib-1'))
|
||||||
|
|||||||
@@ -63,6 +63,7 @@ function writeScrollPosition(key: string, value: number): void {
|
|||||||
export function shouldRememberScroll(pathname: string): boolean {
|
export function shouldRememberScroll(pathname: string): boolean {
|
||||||
return (
|
return (
|
||||||
pathname === '/' ||
|
pathname === '/' ||
|
||||||
|
pathname === '/search' ||
|
||||||
pathname === '/libraries' ||
|
pathname === '/libraries' ||
|
||||||
pathname.startsWith('/library/') ||
|
pathname.startsWith('/library/') ||
|
||||||
pathname.startsWith('/media/')
|
pathname.startsWith('/media/')
|
||||||
|
|||||||
@@ -32,12 +32,14 @@ import { useLibrarySeriesSelection } from './useLibrarySeriesSelection'
|
|||||||
import { useLibraryAdminActions } from './useLibraryAdminActions'
|
import { useLibraryAdminActions } from './useLibraryAdminActions'
|
||||||
import { usePermission } from '../hooks/usePermission'
|
import { usePermission } from '../hooks/usePermission'
|
||||||
import { useFavourites } from '../hooks/useFavourites'
|
import { useFavourites } from '../hooks/useFavourites'
|
||||||
|
import { mediaSearchReturnPath } from '../utils/mediaNavigation'
|
||||||
|
|
||||||
export function LibraryPage() {
|
export function LibraryPage() {
|
||||||
const { id = '' } = useParams()
|
const { id = '' } = useParams()
|
||||||
const [searchParams, setSearchParams] = useSearchParams()
|
const [searchParams, setSearchParams] = useSearchParams()
|
||||||
const location = useLocation()
|
const location = useLocation()
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
|
const searchFrom = mediaSearchReturnPath(location.state)
|
||||||
const role = useAuthStore((s) => s.user?.role)
|
const role = useAuthStore((s) => s.user?.role)
|
||||||
const canFavorite = usePermission('can_favorite')
|
const canFavorite = usePermission('can_favorite')
|
||||||
const { isFavourite, toggleFavourite } = useFavourites()
|
const { isFavourite, toggleFavourite } = useFavourites()
|
||||||
@@ -358,7 +360,7 @@ export function LibraryPage() {
|
|||||||
void handleToggleFavourite(selectedSeries.rep.id)
|
void handleToggleFavourite(selectedSeries.rep.id)
|
||||||
}}
|
}}
|
||||||
seriesToolBusy={seriesToolBusy}
|
seriesToolBusy={seriesToolBusy}
|
||||||
onBack={clearSelectedSeries}
|
onBack={() => searchFrom ? navigate(searchFrom) : clearSelectedSeries()}
|
||||||
onSmartScrape={handleSeriesSmartScrape}
|
onSmartScrape={handleSeriesSmartScrape}
|
||||||
onManualScrape={() => setManualSeriesScrapeOpen(true)}
|
onManualScrape={() => setManualSeriesScrapeOpen(true)}
|
||||||
onMetadataEdit={() => setSeriesMetadataEditOpen(true)}
|
onMetadataEdit={() => setSeriesMetadataEditOpen(true)}
|
||||||
|
|||||||
@@ -0,0 +1,182 @@
|
|||||||
|
import { useEffect, useState } from 'react'
|
||||||
|
import { useSearchParams } from 'react-router-dom'
|
||||||
|
import { ChevronLeft, ChevronRight, LoaderCircle, RefreshCw, Search } from 'lucide-react'
|
||||||
|
|
||||||
|
import { mediaAPI, type MediaSearchPage as SearchPageData } from '../api/library'
|
||||||
|
import { MediaCard } from '../components/MediaCard'
|
||||||
|
import { PageBackButton } from '../components/PageBackButton'
|
||||||
|
import { normalizeListPosition } from '../hooks/useListPositionMemory'
|
||||||
|
import { useAuthStore } from '../stores/auth'
|
||||||
|
import { usePlayProfileStore } from '../stores/playProfile'
|
||||||
|
import { favouriteMediaLink, mediaSearchLink } from '../utils/mediaNavigation'
|
||||||
|
|
||||||
|
const PAGE_SIZE = 48
|
||||||
|
const CACHE_TTL_MS = 5 * 60_000
|
||||||
|
// 返回详情前的结果可立即显示;按账号、播放档案、关键词和页码隔离。
|
||||||
|
const pageCache = new Map<string, { at: number; data: SearchPageData }>()
|
||||||
|
|
||||||
|
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 userId = useAuthStore((s) => s.user?.id)
|
||||||
|
const profileId = usePlayProfileStore((s) => s.activeProfileId)
|
||||||
|
const cacheKey = JSON.stringify([userId, profileId, query, page])
|
||||||
|
|
||||||
|
const changePage = (next: number) => {
|
||||||
|
const nextParams = new URLSearchParams({ q: query })
|
||||||
|
if (next > 1) nextParams.set('page', String(next))
|
||||||
|
setParams(nextParams)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<MediaSearchResults
|
||||||
|
key={cacheKey}
|
||||||
|
cacheKey={cacheKey}
|
||||||
|
query={query}
|
||||||
|
page={page}
|
||||||
|
onPageChange={changePage}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function MediaSearchResults({ cacheKey, query, page, onPageChange }: {
|
||||||
|
cacheKey: string
|
||||||
|
query: string
|
||||||
|
page: number
|
||||||
|
onPageChange: (page: number) => void
|
||||||
|
}) {
|
||||||
|
const [data, setData] = useState(() => readCachedPage(cacheKey))
|
||||||
|
const [loading, setLoading] = useState(() => !!query && !readCachedPage(cacheKey))
|
||||||
|
const [error, setError] = useState('')
|
||||||
|
const [revision, setRevision] = useState(0)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!query) return
|
||||||
|
const cached = readCachedPage(cacheKey)
|
||||||
|
if (cached) {
|
||||||
|
setData(cached)
|
||||||
|
setLoading(false)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
let cancelled = false
|
||||||
|
setLoading(true)
|
||||||
|
setError('')
|
||||||
|
mediaAPI.searchPage(query, page, PAGE_SIZE, { groupSeries: true })
|
||||||
|
.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])
|
||||||
|
|
||||||
|
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 = mediaSearchLink(query, page)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-6">
|
||||||
|
<PageBackButton to="/" label="返回首页" compact />
|
||||||
|
<div className="flex items-start justify-between gap-4">
|
||||||
|
<div className="min-w-0 space-y-2">
|
||||||
|
<h1 className="font-display text-2xl font-bold text-[var(--app-text)] sm:text-3xl">搜索结果</h1>
|
||||||
|
<p className="break-words text-sm text-[var(--app-muted)]" aria-live="polite">
|
||||||
|
{query
|
||||||
|
? <>“{query}”{data && !loading ? ` · 共 ${total} 条结果` : ''}</>
|
||||||
|
: '在顶部搜索框输入媒体名称,按回车开始搜索'}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
{query && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={refresh}
|
||||||
|
disabled={loading}
|
||||||
|
className="inline-flex shrink-0 items-center gap-2 rounded-xl border border-[var(--app-border)] bg-[var(--app-panel)] px-3 py-2 text-xs text-[var(--app-subtle)] hover:bg-[var(--app-hover)] disabled:opacity-50"
|
||||||
|
>
|
||||||
|
<RefreshCw size={14} />
|
||||||
|
刷新结果
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{loading && (
|
||||||
|
<div role="status" className="flex items-center justify-center gap-2 py-20 text-sm text-[var(--app-muted)]">
|
||||||
|
<LoaderCircle size={18} className="animate-spin text-brand-500" />
|
||||||
|
正在搜索…
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{error && (
|
||||||
|
<div role="alert" className="rounded-2xl border border-red-400/30 bg-[var(--app-panel)] p-5 text-sm text-red-400">
|
||||||
|
{error}
|
||||||
|
<button type="button" onClick={refresh} className="ml-3 underline">重试</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{!loading && !error && query && items.length === 0 && (
|
||||||
|
<div className="flex flex-col items-center gap-3 rounded-2xl border border-[var(--app-border)] bg-[var(--app-panel)] px-6 py-16 text-center text-[var(--app-muted)]">
|
||||||
|
<Search size={28} />
|
||||||
|
<p className="break-all text-sm">未搜索到与 “{query}” 相关的媒体内容</p>
|
||||||
|
<p className="text-xs">试试其他名称或更简短的关键词</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{!loading && items.length > 0 && (
|
||||||
|
<div className="grid grid-cols-2 gap-4 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6">
|
||||||
|
{items.map((item) => (
|
||||||
|
<MediaCard key={item.id} media={item} linkTo={favouriteMediaLink(item)} linkState={{ from }} />
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{!loading && !error && query && (totalPages > 1 || page > 1) && (
|
||||||
|
<nav aria-label="搜索结果分页" className="flex items-center justify-center gap-4 py-4 text-sm">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={page <= 1}
|
||||||
|
onClick={() => onPageChange(page - 1)}
|
||||||
|
className="inline-flex items-center gap-1 rounded-xl border border-[var(--app-border)] bg-[var(--app-panel)] px-3 py-2 hover:bg-[var(--app-hover)] disabled:cursor-not-allowed disabled:opacity-40"
|
||||||
|
>
|
||||||
|
<ChevronLeft size={16} />上一页
|
||||||
|
</button>
|
||||||
|
<span className="text-[var(--app-muted)]">第 {page} / {totalPages} 页</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={page >= totalPages}
|
||||||
|
onClick={() => onPageChange(page + 1)}
|
||||||
|
className="inline-flex items-center gap-1 rounded-xl border border-[var(--app-border)] bg-[var(--app-panel)] px-3 py-2 hover:bg-[var(--app-hover)] disabled:cursor-not-allowed disabled:opacity-40"
|
||||||
|
>
|
||||||
|
下一页<ChevronRight size={16} />
|
||||||
|
</button>
|
||||||
|
</nav>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -2,6 +2,17 @@ import type { Media } from '../types'
|
|||||||
import { isRemoteEmbyID } from './remoteEmby'
|
import { isRemoteEmbyID } from './remoteEmby'
|
||||||
import { getSeriesKey, isEpisodeLike, pathLooksEpisodic } from './groupSeries'
|
import { getSeriesKey, isEpisodeLike, pathLooksEpisodic } from './groupSeries'
|
||||||
|
|
||||||
|
export function mediaSearchLink(query: string, page = 1): string {
|
||||||
|
const params = new URLSearchParams({ q: query.trim() })
|
||||||
|
if (page > 1) params.set('page', String(page))
|
||||||
|
return `/search?${params}`
|
||||||
|
}
|
||||||
|
|
||||||
|
export function mediaSearchReturnPath(state: unknown): string | undefined {
|
||||||
|
if (!state || typeof state !== 'object' || !('from' in state)) return undefined
|
||||||
|
return typeof state.from === 'string' && state.from.startsWith('/search?') ? state.from : undefined
|
||||||
|
}
|
||||||
|
|
||||||
function pathLooksLikeMovie(media: Media): boolean {
|
function pathLooksLikeMovie(media: Media): boolean {
|
||||||
const path = (media.path || media.display_library_path || media.library_path || '').toLowerCase()
|
const path = (media.path || media.display_library_path || media.library_path || '').toLowerCase()
|
||||||
return /[\\/](?:movie|movies|film|films|电影)[\\/]/i.test(path)
|
return /[\\/](?:movie|movies|film|films|电影)[\\/]/i.test(path)
|
||||||
|
|||||||
Reference in New Issue
Block a user