添加搜索功能
This commit is contained in:
380
src/Main.jsx
380
src/Main.jsx
@@ -5,6 +5,11 @@ import Grid from '@mui/material/Grid';
|
||||
import Pagination from '@mui/material/Pagination';
|
||||
import { Link } from 'react-router-dom';
|
||||
import CircularProgress from '@mui/material/CircularProgress';
|
||||
import TextField from '@mui/material/TextField';
|
||||
import InputAdornment from '@mui/material/InputAdornment';
|
||||
import IconButton from '@mui/material/IconButton';
|
||||
import SearchIcon from '@mui/icons-material/Search';
|
||||
import ClearIcon from '@mui/icons-material/Clear';
|
||||
|
||||
import ConfigContext from './Config';
|
||||
import MovieCard from './components/MovieCard';
|
||||
@@ -15,9 +20,13 @@ const categories = [
|
||||
{ label: '30min', value: '30min' },
|
||||
{ label: '60min', value: '60min' },
|
||||
{ label: '大于60min', value: '大于60min' },
|
||||
{ label: '最新添加', value: '最新添加' },
|
||||
];
|
||||
|
||||
// 新增搜索类别常量
|
||||
const SEARCH_CATEGORY = 'search';
|
||||
const LIMIT = 20;
|
||||
const DEFAULT_CATEGORY = categories[0].value;
|
||||
|
||||
const usePersistedState = (key, defaultValue) => {
|
||||
const [state, setState] = useState(() => {
|
||||
@@ -35,56 +44,113 @@ const usePersistedState = (key, defaultValue) => {
|
||||
const Main = () => {
|
||||
const config = useContext(ConfigContext);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const scrollRef = useRef(0);
|
||||
const isFirstLoad = useRef(true);
|
||||
const scrollListenerActive = useRef(false);
|
||||
|
||||
// 初始化状态,直接使用 categories 中的 value 值
|
||||
// 初始化状态 - 添加搜索相关状态
|
||||
const [params, setParams] = usePersistedState('params', {
|
||||
lastCategory: categories[0].value, // 直接使用 '15min' 这样的值
|
||||
history: categories.reduce((acc, category) => ({
|
||||
...acc,
|
||||
[category.value]: { lastPage: 1, scrollPos: 0 } // 使用 category.value 作为键
|
||||
}), {})
|
||||
lastCategory: DEFAULT_CATEGORY,
|
||||
history: Object.fromEntries([
|
||||
...categories.map(cat => [
|
||||
cat.value,
|
||||
{ lastPage: 1, scrollPos: 0 }
|
||||
]),
|
||||
// 为搜索添加单独的历史记录
|
||||
[SEARCH_CATEGORY, { lastPage: 1, scrollPos: 0 }]
|
||||
]),
|
||||
// 新增搜索查询状态
|
||||
searchQuery: ''
|
||||
});
|
||||
|
||||
const [movies, setMovies] = useState([]);
|
||||
const [pagination, setPagination] = useState({ page: 1, total: 0, pages: 1 });
|
||||
const currentCategory = params.lastCategory || DEFAULT_CATEGORY;
|
||||
|
||||
const fetchMovies = useCallback(async (category, page) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
// 直接使用 category 值,不需要转换
|
||||
const response = await axios.get(
|
||||
`/movie/?page=${page}&limit=${LIMIT}&category=${encodeURIComponent(category)}`
|
||||
);
|
||||
// 新增搜索输入状态
|
||||
const [searchInput, setSearchInput] = useState(params.searchQuery || '');
|
||||
|
||||
if (response.status === 200) {
|
||||
const { items, total } = response.data.data;
|
||||
// 滚动位置处理
|
||||
const saveScrollPosition = useCallback((category = currentCategory) => {
|
||||
const currentScrollPos = window.scrollY;
|
||||
|
||||
if (items.length === 0 && page > 1) {
|
||||
setParams(prev => ({
|
||||
...prev,
|
||||
history: {
|
||||
...prev.history,
|
||||
[category]: {
|
||||
...(prev.history[category] || { lastPage: 1, scrollPos: 0 }),
|
||||
lastPage: page - 1
|
||||
}
|
||||
}
|
||||
}));
|
||||
return;
|
||||
setParams(prev => {
|
||||
const updatedHistory = {
|
||||
...prev.history,
|
||||
[category]: {
|
||||
...(prev.history[category] || { lastPage: 1, scrollPos: 0 }),
|
||||
scrollPos: currentScrollPos
|
||||
}
|
||||
};
|
||||
|
||||
setMovies(items);
|
||||
setPagination({
|
||||
page,
|
||||
total,
|
||||
pages: Math.ceil(total / LIMIT)
|
||||
});
|
||||
return { ...prev, history: updatedHistory };
|
||||
});
|
||||
}, [setParams, currentCategory]);
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
window.scrollTo(0, scrollRef.current);
|
||||
});
|
||||
const setupScrollListener = useCallback(() => {
|
||||
if (scrollListenerActive.current) return;
|
||||
|
||||
const handleScroll = () => {
|
||||
clearTimeout(window.scrollTimer);
|
||||
window.scrollTimer = setTimeout(() => saveScrollPosition(), 100);
|
||||
};
|
||||
|
||||
window.addEventListener('scroll', handleScroll);
|
||||
scrollListenerActive.current = true;
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('scroll', handleScroll);
|
||||
clearTimeout(window.scrollTimer);
|
||||
scrollListenerActive.current = false;
|
||||
};
|
||||
}, [saveScrollPosition]);
|
||||
|
||||
const removeScrollListener = useCallback(() => {
|
||||
if (scrollListenerActive.current) {
|
||||
window.removeEventListener('scroll', window.scrollHandler);
|
||||
scrollListenerActive.current = false;
|
||||
}
|
||||
}, []);
|
||||
|
||||
// 修改fetchMovies以支持搜索
|
||||
const fetchMovies = useCallback(async (category, page, search = '') => {
|
||||
setLoading(true);
|
||||
|
||||
try {
|
||||
const isSearch = category === SEARCH_CATEGORY;
|
||||
const isLatest = category === '最新添加';
|
||||
|
||||
let apiUrl = `/movie?page=${page}&limit=${LIMIT}`;
|
||||
|
||||
if (isSearch) {
|
||||
// 搜索请求
|
||||
apiUrl += `&search=${encodeURIComponent(search)}`;
|
||||
} else if (isLatest) {
|
||||
// 最新添加请求
|
||||
apiUrl += `&sort=created_time&order=desc`;
|
||||
} else {
|
||||
// 分类请求
|
||||
apiUrl += `&category=${encodeURIComponent(category)}`;
|
||||
}
|
||||
|
||||
const response = await axios.get(apiUrl);
|
||||
if (response.status !== 200) return;
|
||||
|
||||
const { items, total } = response.data.data;
|
||||
const totalPages = Math.ceil(total / LIMIT);
|
||||
|
||||
if (items.length === 0 && page > 1) {
|
||||
setParams(prev => ({
|
||||
...prev,
|
||||
history: {
|
||||
...prev.history,
|
||||
[category]: { ...prev.history[category], lastPage: page - 1 }
|
||||
}
|
||||
}));
|
||||
return;
|
||||
}
|
||||
|
||||
setMovies(items);
|
||||
setPagination({ page, total, pages: totalPages });
|
||||
} catch (error) {
|
||||
console.error('Error fetching movies:', error);
|
||||
} finally {
|
||||
@@ -92,98 +158,221 @@ const Main = () => {
|
||||
}
|
||||
}, [setParams]);
|
||||
|
||||
const getCurrentCategoryAndPage = useCallback(() => {
|
||||
// 直接从 params 中获取 lastCategory,确保它是 categories 中的 value 值
|
||||
const lastCategory = params.lastCategory || categories[0].value;
|
||||
const categoryHistory = params.history[lastCategory] || { lastPage: 1, scrollPos: 0 };
|
||||
return {
|
||||
category: lastCategory,
|
||||
page: categoryHistory.lastPage
|
||||
};
|
||||
}, [params]);
|
||||
// 恢复滚动位置
|
||||
const restoreScrollPosition = useCallback((category) => {
|
||||
const scrollPos = params.history?.[category]?.scrollPos || 0;
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
setTimeout(() => window.scrollTo(0, scrollPos), 100);
|
||||
});
|
||||
}, [params.history]);
|
||||
|
||||
// 初始加载
|
||||
useEffect(() => {
|
||||
const { category, page } = getCurrentCategoryAndPage();
|
||||
scrollRef.current = params.history[category]?.scrollPos || 0;
|
||||
fetchMovies(category, page);
|
||||
}, [getCurrentCategoryAndPage, fetchMovies, params.history]);
|
||||
if (!isFirstLoad.current) return;
|
||||
|
||||
const handleCategoryChange = useCallback((category) => {
|
||||
scrollRef.current = window.scrollY;
|
||||
const currentCategory = params.lastCategory || categories[0].value;
|
||||
const category = currentCategory;
|
||||
const categoryHistory = params.history[category] || { lastPage: 1 };
|
||||
|
||||
// 如果是搜索类别,传递搜索查询
|
||||
if (category === SEARCH_CATEGORY) {
|
||||
fetchMovies(category, categoryHistory.lastPage, params.searchQuery);
|
||||
} else {
|
||||
fetchMovies(category, categoryHistory.lastPage);
|
||||
}
|
||||
|
||||
isFirstLoad.current = false;
|
||||
}, [fetchMovies, currentCategory, params.history, params.searchQuery]);
|
||||
|
||||
// 数据加载完成后处理
|
||||
useEffect(() => {
|
||||
if (loading || isFirstLoad.current) return;
|
||||
restoreScrollPosition(currentCategory);
|
||||
setupScrollListener();
|
||||
}, [loading, restoreScrollPosition, currentCategory, setupScrollListener]);
|
||||
|
||||
// 类别切换处理 - 修改以支持搜索类别
|
||||
const handleCategoryChange = useCallback((newCategory) => {
|
||||
removeScrollListener();
|
||||
saveScrollPosition();
|
||||
|
||||
setParams(prev => {
|
||||
const newHistory = {
|
||||
...prev.history,
|
||||
[currentCategory]: {
|
||||
...(prev.history[currentCategory] || { lastPage: 1, scrollPos: 0 }),
|
||||
scrollPos: scrollRef.current
|
||||
},
|
||||
[category]: {
|
||||
...(prev.history[category] || { lastPage: 1, scrollPos: 0 })
|
||||
}
|
||||
};
|
||||
const categoryHistory = prev.history[newCategory] || { lastPage: 1 };
|
||||
|
||||
// 如果是搜索类别,使用保存的搜索查询
|
||||
if (newCategory === SEARCH_CATEGORY) {
|
||||
fetchMovies(newCategory, categoryHistory.lastPage, prev.searchQuery);
|
||||
} else {
|
||||
fetchMovies(newCategory, categoryHistory.lastPage);
|
||||
}
|
||||
|
||||
return {
|
||||
...prev,
|
||||
lastCategory: category, // 直接存储传入的 category 值
|
||||
history: newHistory
|
||||
lastCategory: newCategory
|
||||
};
|
||||
});
|
||||
}, [params.lastCategory, setParams]);
|
||||
}, [removeScrollListener, saveScrollPosition, setParams, fetchMovies]);
|
||||
|
||||
// 分页处理 - 修改以支持搜索
|
||||
const handlePageChange = useCallback((_, page) => {
|
||||
scrollRef.current = window.scrollY;
|
||||
const lastCategory = params.lastCategory || categories[0].value;
|
||||
removeScrollListener();
|
||||
saveScrollPosition();
|
||||
|
||||
setParams(prev => ({
|
||||
...prev,
|
||||
history: {
|
||||
...prev.history,
|
||||
[lastCategory]: {
|
||||
...(prev.history[lastCategory] || { lastPage: 1, scrollPos: 0 }),
|
||||
lastPage: page
|
||||
[currentCategory]: {
|
||||
...prev.history[currentCategory],
|
||||
lastPage: page,
|
||||
scrollPos: 0
|
||||
}
|
||||
}
|
||||
}));
|
||||
}, [params.lastCategory, setParams]);
|
||||
|
||||
// 如果是搜索类别,传递搜索查询
|
||||
if (currentCategory === SEARCH_CATEGORY) {
|
||||
fetchMovies(currentCategory, page, params.searchQuery);
|
||||
} else {
|
||||
fetchMovies(currentCategory, page);
|
||||
}
|
||||
|
||||
window.scrollTo(0, 0);
|
||||
}, [removeScrollListener, saveScrollPosition, setParams, fetchMovies, currentCategory, params.searchQuery]);
|
||||
|
||||
// 电影卡片点击处理
|
||||
const handleMovieCardClick = useCallback(() => {
|
||||
scrollRef.current = window.scrollY;
|
||||
const lastCategory = params.lastCategory || categories[0].value;
|
||||
removeScrollListener();
|
||||
saveScrollPosition();
|
||||
}, [removeScrollListener, saveScrollPosition]);
|
||||
|
||||
setParams(prev => ({
|
||||
...prev,
|
||||
history: {
|
||||
...prev.history,
|
||||
[lastCategory]: {
|
||||
...(prev.history[lastCategory] || { lastPage: 1, scrollPos: 0 }),
|
||||
scrollPos: scrollRef.current
|
||||
// 新增:处理搜索提交
|
||||
const handleSearchSubmit = useCallback(() => {
|
||||
if (!searchInput.trim()) return;
|
||||
|
||||
removeScrollListener();
|
||||
saveScrollPosition();
|
||||
|
||||
setParams(prev => {
|
||||
// 更新搜索查询并切换到搜索类别
|
||||
const updatedParams = {
|
||||
...prev,
|
||||
lastCategory: SEARCH_CATEGORY,
|
||||
searchQuery: searchInput.trim(),
|
||||
history: {
|
||||
...prev.history,
|
||||
[SEARCH_CATEGORY]: {
|
||||
...prev.history[SEARCH_CATEGORY],
|
||||
lastPage: 1 // 新搜索总是从第一页开始
|
||||
}
|
||||
}
|
||||
}
|
||||
}));
|
||||
}, [params.lastCategory, setParams]);
|
||||
};
|
||||
|
||||
// 执行搜索请求
|
||||
fetchMovies(SEARCH_CATEGORY, 1, searchInput.trim());
|
||||
|
||||
return updatedParams;
|
||||
});
|
||||
}, [removeScrollListener, saveScrollPosition, setParams, fetchMovies, searchInput]);
|
||||
|
||||
// 新增:清除搜索
|
||||
const handleClearSearch = useCallback(() => {
|
||||
if (!searchInput) return;
|
||||
|
||||
setSearchInput('');
|
||||
|
||||
// 如果当前在搜索类别,则清除后切换到默认类别
|
||||
if (currentCategory === SEARCH_CATEGORY) {
|
||||
setParams(prev => ({
|
||||
...prev,
|
||||
lastCategory: DEFAULT_CATEGORY,
|
||||
searchQuery: ''
|
||||
}));
|
||||
|
||||
// 获取默认类别的数据
|
||||
const categoryHistory = params.history[DEFAULT_CATEGORY] || { lastPage: 1 };
|
||||
fetchMovies(DEFAULT_CATEGORY, categoryHistory.lastPage);
|
||||
} else {
|
||||
// 不在搜索类别,只清除输入框
|
||||
setParams(prev => ({
|
||||
...prev,
|
||||
searchQuery: ''
|
||||
}));
|
||||
}
|
||||
}, [currentCategory, fetchMovies, params.history, searchInput, setParams]);
|
||||
|
||||
// 新增:处理搜索输入变化
|
||||
const handleSearchChange = useCallback((e) => {
|
||||
setSearchInput(e.target.value);
|
||||
}, []);
|
||||
|
||||
// 新增:处理搜索输入键盘事件
|
||||
const handleSearchKeyDown = useCallback((e) => {
|
||||
if (e.key === 'Enter') {
|
||||
handleSearchSubmit();
|
||||
}
|
||||
}, [handleSearchSubmit]);
|
||||
|
||||
// 组件卸载清理
|
||||
useEffect(() => removeScrollListener, [removeScrollListener]);
|
||||
|
||||
// 分页组件复用
|
||||
const paginationComponent = (
|
||||
<Pagination
|
||||
count={pagination.pages}
|
||||
page={pagination.page}
|
||||
onChange={handlePageChange}
|
||||
sx={{ my: 2, display: 'flex', justifyContent: 'center' }}
|
||||
/>
|
||||
);
|
||||
|
||||
return (
|
||||
<Container style={{ marginTop: 20 }}>
|
||||
{/* 添加搜索框 */}
|
||||
<TextField
|
||||
fullWidth
|
||||
variant="outlined"
|
||||
placeholder="搜索文件名..."
|
||||
value={searchInput}
|
||||
onChange={handleSearchChange}
|
||||
onKeyDown={handleSearchKeyDown}
|
||||
InputProps={{
|
||||
startAdornment: (
|
||||
<InputAdornment position="start">
|
||||
<SearchIcon />
|
||||
</InputAdornment>
|
||||
),
|
||||
endAdornment: searchInput && (
|
||||
<InputAdornment position="end">
|
||||
<IconButton onClick={handleClearSearch}>
|
||||
<ClearIcon />
|
||||
</IconButton>
|
||||
</InputAdornment>
|
||||
)
|
||||
}}
|
||||
sx={{ mb: 2 }}
|
||||
/>
|
||||
|
||||
<CategoryNav
|
||||
categories={categories}
|
||||
currentCategory={params.lastCategory || categories[0].value}
|
||||
currentCategory={currentCategory === SEARCH_CATEGORY ? '' : currentCategory}
|
||||
onCategoryChange={handleCategoryChange}
|
||||
/>
|
||||
|
||||
<Pagination
|
||||
count={pagination.pages}
|
||||
page={pagination.page}
|
||||
onChange={handlePageChange}
|
||||
sx={{ my: 2, display: 'flex', justifyContent: 'center' }}
|
||||
/>
|
||||
{/* 显示当前搜索状态 */}
|
||||
{currentCategory === SEARCH_CATEGORY && (
|
||||
<div style={{ textAlign: 'center', margin: '10px 0' }}>
|
||||
搜索: "{params.searchQuery}" ({pagination.total} 个结果)
|
||||
</div>
|
||||
)}
|
||||
|
||||
{paginationComponent}
|
||||
|
||||
{loading ? (
|
||||
<CircularProgress sx={{ display: 'block', margin: '20px auto' }} />
|
||||
) : (
|
||||
<Grid container spacing={2} sx={{ mt: 0.5 }}>
|
||||
{movies.map((item) => (
|
||||
{movies.map(item => (
|
||||
<Grid item xs={6} sm={4} md={3} lg={2} key={item.filename}>
|
||||
<Link
|
||||
to={`/res/${item.filename}`}
|
||||
@@ -197,12 +386,7 @@ const Main = () => {
|
||||
</Grid>
|
||||
)}
|
||||
|
||||
<Pagination
|
||||
count={pagination.pages}
|
||||
page={pagination.page}
|
||||
onChange={handlePageChange}
|
||||
sx={{ my: 2, display: 'flex', justifyContent: 'center' }}
|
||||
/>
|
||||
{paginationComponent}
|
||||
</Container>
|
||||
);
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user