x-movie/src/Main.jsx

421 lines
16 KiB
React
Raw Normal View History

2025-06-02 03:19:36 +08:00
import React, { useState, useEffect, useContext, useCallback, useRef } from 'react';
2023-07-04 23:47:01 +08:00
import axios from 'axios';
import Container from '@mui/material/Container';
import Grid from '@mui/material/Grid';
import Pagination from '@mui/material/Pagination';
import { Link } from 'react-router-dom';
2023-07-05 01:33:55 +08:00
import CircularProgress from '@mui/material/CircularProgress';
2025-06-02 06:20:16 +08:00
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';
2023-07-04 23:47:01 +08:00
2023-07-08 17:44:51 +08:00
import ConfigContext from './Config';
2023-07-09 05:58:33 +08:00
import MovieCard from './components/MovieCard';
import CategoryNav from './components/CategoryNav';
2023-07-04 23:47:01 +08:00
2025-06-02 03:19:36 +08:00
const categories = [
{ label: '15min', value: '15min' },
{ label: '30min', value: '30min' },
{ label: '60min', value: '60min' },
{ label: '大于60min', value: '大于60min' },
2025-06-02 06:20:16 +08:00
{ label: '最新添加', value: '最新添加' },
2025-06-02 03:19:36 +08:00
];
2025-06-02 06:20:16 +08:00
const SEARCH_CATEGORY = 'search';
2025-06-02 03:19:36 +08:00
const LIMIT = 20;
2025-06-02 06:20:16 +08:00
const DEFAULT_CATEGORY = categories[0].value;
2025-06-02 03:19:36 +08:00
2025-06-03 00:44:35 +08:00
2025-06-02 03:19:36 +08:00
const usePersistedState = (key, defaultValue) => {
const [state, setState] = useState(() => {
const stored = localStorage.getItem(key);
return stored ? JSON.parse(stored) : defaultValue;
});
useEffect(() => {
localStorage.setItem(key, JSON.stringify(state));
}, [key, state]);
return [state, setState];
};
2024-03-28 03:40:13 +08:00
const Main = () => {
const config = useContext(ConfigContext);
const [loading, setLoading] = useState(false);
2025-06-02 06:20:16 +08:00
const isFirstLoad = useRef(true);
const scrollListenerActive = useRef(false);
2025-06-03 00:44:35 +08:00
const skipScrollRestore = useRef(false);
const isPaginating = useRef(false); // New ref for pagination
2025-06-02 03:19:36 +08:00
const [params, setParams] = usePersistedState('params', {
2025-06-02 06:20:16 +08:00
lastCategory: DEFAULT_CATEGORY,
history: Object.fromEntries([
2025-06-03 00:44:35 +08:00
...categories.map(cat => [cat.value, { lastPage: 1, scrollPos: 0 }]),
[SEARCH_CATEGORY, { lastPage: 1, scrollPos: 0, searchQuery: '' }] // Ensure searchQuery is part of history for search
2025-06-02 06:20:16 +08:00
]),
2025-06-03 00:44:35 +08:00
searchQuery: '' // Global search query, might be redundant if using history.searchQuery
2024-03-28 03:40:13 +08:00
});
2023-07-04 23:47:01 +08:00
2025-06-02 03:19:36 +08:00
const [movies, setMovies] = useState([]);
const [pagination, setPagination] = useState({ page: 1, total: 0, pages: 1 });
2025-06-02 06:20:16 +08:00
const [searchInput, setSearchInput] = useState(params.searchQuery || '');
2025-06-03 00:44:35 +08:00
const currentCategory = params.lastCategory || DEFAULT_CATEGORY;
const currentCategoryHistory = params.history[currentCategory] || { lastPage: 1, scrollPos: 0 };
2025-06-02 06:20:16 +08:00
2025-06-03 00:44:35 +08:00
const handleScrollPosition = useCallback((action, category = currentCategory) => {
if (action === 'save') {
const currentScrollPos = window.scrollY;
setParams(prev => ({
...prev,
history: {
...prev.history,
[category]: {
...(prev.history[category] || { lastPage: 1 }),
scrollPos: currentScrollPos
}
}
}));
} else if (action === 'restore') {
const scrollPos = params.history?.[category]?.scrollPos || 0;
// console.log(`Attempting to restore scroll for ${category} to ${scrollPos}`);
requestAnimationFrame(() => {
// Increased timeout slightly for better rendering chance
setTimeout(() => {
window.scrollTo(0, scrollPos);
// console.log(`Scrolled to ${scrollPos} for ${category}`);
}, 150);
});
}
}, [setParams, params.history, currentCategory]);
2025-06-02 06:20:16 +08:00
2025-06-03 00:44:35 +08:00
const manageScrollListener = useCallback((action) => {
const scrollHandler = () => {
2025-06-02 06:20:16 +08:00
clearTimeout(window.scrollTimer);
2025-06-03 00:44:35 +08:00
window.scrollTimer = setTimeout(() => handleScrollPosition('save'), 200); // Debounce save
2025-06-02 06:20:16 +08:00
};
2025-06-03 00:44:35 +08:00
window.scrollHandler = scrollHandler; // Store to remove the correct one
2025-06-02 06:20:16 +08:00
2025-06-03 00:44:35 +08:00
if (action === 'setup' && !scrollListenerActive.current) {
window.addEventListener('scroll', window.scrollHandler);
scrollListenerActive.current = true;
} else if (action === 'remove' && scrollListenerActive.current) {
2025-06-02 06:20:16 +08:00
window.removeEventListener('scroll', window.scrollHandler);
scrollListenerActive.current = false;
2025-06-03 00:44:35 +08:00
clearTimeout(window.scrollTimer);
2025-06-02 06:20:16 +08:00
}
2025-06-03 00:44:35 +08:00
}, [handleScrollPosition]);
2025-06-02 06:20:16 +08:00
2025-06-03 00:44:35 +08:00
const fetchMovies = useCallback(async (category, page, search = '', options = {}) => {
if (options.skipRestore) {
skipScrollRestore.current = true;
}
setLoading(true);
2023-07-04 23:47:01 +08:00
try {
2025-06-02 06:20:16 +08:00
const isSearch = category === SEARCH_CATEGORY;
const isLatest = category === '最新添加';
2025-06-02 03:19:36 +08:00
2025-06-02 21:29:31 +08:00
let apiUrl = `/movie/list?page=${page}&limit=${LIMIT}`;
2025-06-03 00:44:35 +08:00
if (isSearch) apiUrl += `&search=${encodeURIComponent(search)}`;
else if (isLatest) apiUrl += `&sort=created_time&order=desc`;
else apiUrl += `&category=${encodeURIComponent(category)}`;
2025-06-02 06:20:16 +08:00
const response = await axios.get(apiUrl);
2025-06-03 00:44:35 +08:00
if (response.status !== 200) {
console.error("API Error:", response);
setMovies([]);
setPagination({ page, total: 0, pages: 1 });
return;
}
2025-06-02 06:20:16 +08:00
const { items, total } = response.data.data;
const totalPages = Math.ceil(total / LIMIT);
2025-06-03 00:44:35 +08:00
if (items.length === 0 && page > 1 && !isSearch) { // Don't auto-decrement page for search
2025-06-02 06:20:16 +08:00
setParams(prev => ({
...prev,
history: {
...prev.history,
2025-06-03 00:44:35 +08:00
[category]: { ...prev.history[category], lastPage: Math.max(1, page - 1) }
2025-06-02 06:20:16 +08:00
}
}));
2025-06-03 00:44:35 +08:00
// Optionally, fetch page - 1 here, or let user do it.
// For now, just update the state and show no movies.
setMovies([]);
setPagination({ page: Math.max(1, page - 1), total, pages: totalPages });
2025-06-02 06:20:16 +08:00
return;
}
setMovies(items);
setPagination({ page, total, pages: totalPages });
2025-06-03 00:44:35 +08:00
2023-07-04 23:47:01 +08:00
} catch (error) {
console.error('Error fetching movies:', error);
2025-06-03 00:44:35 +08:00
setMovies([]);
setPagination({ page, total: 0, pages: 1 });
2023-07-05 01:33:55 +08:00
} finally {
2025-06-03 00:44:35 +08:00
setLoading(false); // This will trigger the useEffect[loading]
2023-07-04 23:47:01 +08:00
}
2025-06-03 00:44:35 +08:00
}, [setParams]); // Removed currentCategory from deps as fetchMovies doesn't directly use it for scroll
2025-06-02 03:19:36 +08:00
2025-06-02 06:20:16 +08:00
2025-06-03 00:44:35 +08:00
const handleTransition = useCallback((actionCallback) => {
// console.log(`Transition: Saving scroll for ${currentCategory}`);
manageScrollListener('remove');
handleScrollPosition('save'); // Save scroll for the category we are leaving
actionCallback();
// manageScrollListener will be set up again in useEffect[loading]
}, [manageScrollListener, handleScrollPosition, currentCategory]);
2023-07-04 23:47:01 +08:00
2025-06-03 00:44:35 +08:00
// Initial Load
2023-07-04 23:47:01 +08:00
useEffect(() => {
2025-06-02 06:20:16 +08:00
if (!isFirstLoad.current) return;
2025-06-02 03:19:36 +08:00
2025-06-03 00:44:35 +08:00
const categoryToLoad = params.lastCategory || DEFAULT_CATEGORY;
const historyForCategory = params.history[categoryToLoad] || { lastPage: 1, scrollPos: 0 };
const pageToLoad = historyForCategory.lastPage;
let searchQueryToLoad = '';
if (categoryToLoad === SEARCH_CATEGORY) {
searchQueryToLoad = params.searchQuery || (historyForCategory.searchQuery || '');
setSearchInput(searchQueryToLoad); // Sync search input
2025-06-02 06:20:16 +08:00
}
2025-06-03 00:44:35 +08:00
// console.log(`Initial Load: Fetching ${categoryToLoad}, page ${pageToLoad}, search: "${searchQueryToLoad}"`);
fetchMovies(categoryToLoad, pageToLoad, searchQueryToLoad);
2025-06-02 06:20:16 +08:00
isFirstLoad.current = false;
2025-06-03 00:44:35 +08:00
}, []); // Runs only once on mount
2025-06-02 06:20:16 +08:00
2025-06-03 00:44:35 +08:00
// Scroll Management after data loading
2025-06-02 06:20:16 +08:00
useEffect(() => {
2025-06-03 00:44:35 +08:00
if (loading || isFirstLoad.current) return; // Don't run if loading or still initial phase
2025-06-02 06:20:16 +08:00
2025-06-03 00:44:35 +08:00
manageScrollListener('remove'); // Ensure no listener interference
2025-06-02 03:19:36 +08:00
2025-06-03 00:44:35 +08:00
if (isPaginating.current) {
// console.log("Pagination: Scrolling to top");
window.scrollTo(0, 0);
isPaginating.current = false;
} else if (skipScrollRestore.current) {
// console.log(`Skipping scroll restore for ${currentCategory} (e.g., after rename)`);
skipScrollRestore.current = false;
} else {
// console.log(`Restoring scroll for ${currentCategory} (normal flow)`);
handleScrollPosition('restore', currentCategory);
}
manageScrollListener('setup'); // Setup listener after scroll decision
}, [loading, currentCategory, handleScrollPosition, manageScrollListener]);
2025-06-02 06:20:16 +08:00
2025-06-03 00:44:35 +08:00
const handleCategoryChange = useCallback((newCategory) => {
handleTransition(() => {
const newCategoryHistory = params.history[newCategory] || { lastPage: 1, scrollPos: 0 };
let searchQueryForNewCategory = '';
2025-06-02 06:20:16 +08:00
if (newCategory === SEARCH_CATEGORY) {
2025-06-03 00:44:35 +08:00
searchQueryForNewCategory = params.searchQuery || (newCategoryHistory.searchQuery || '');
setSearchInput(searchQueryForNewCategory); // Sync search input
2025-06-02 06:20:16 +08:00
} else {
2025-06-03 00:44:35 +08:00
setSearchInput(''); // Clear search input if not search category
2025-06-02 06:20:16 +08:00
}
2025-06-03 00:44:35 +08:00
setParams(prev => ({ ...prev, lastCategory: newCategory }));
// console.log(`Category Change: Fetching ${newCategory}, page ${newCategoryHistory.lastPage}`);
fetchMovies(newCategory, newCategoryHistory.lastPage, searchQueryForNewCategory);
2025-06-02 03:19:36 +08:00
});
2025-06-03 00:44:35 +08:00
}, [handleTransition, setParams, fetchMovies, params.history, params.searchQuery]);
2023-07-10 00:50:11 +08:00
2025-06-02 03:19:36 +08:00
const handlePageChange = useCallback((_, page) => {
2025-06-03 00:44:35 +08:00
// Save scroll position for the current page of the current category BEFORE fetching new page data
handleScrollPosition('save', currentCategory);
isPaginating.current = true; // Signal that this is a pagination action
2023-07-10 00:50:11 +08:00
2025-06-02 03:19:36 +08:00
setParams(prev => ({
...prev,
2024-03-28 03:40:13 +08:00
history: {
2025-06-02 03:19:36 +08:00
...prev.history,
2025-06-03 00:44:35 +08:00
[currentCategory]: { ...currentCategoryHistory, lastPage: page }
2025-06-02 03:19:36 +08:00
}
}));
2025-06-03 00:44:35 +08:00
const searchQueryForPageChange = currentCategory === SEARCH_CATEGORY ? (params.searchQuery || currentCategoryHistory.searchQuery || '') : '';
// console.log(`Page Change: Fetching ${currentCategory}, page ${page}, search: "${searchQueryForPageChange}"`);
fetchMovies(currentCategory, page, searchQueryForPageChange);
// Scrolling to top will be handled by useEffect[loading] due to isPaginating.current
}, [setParams, fetchMovies, currentCategory, params.searchQuery, currentCategoryHistory, handleScrollPosition]);
2025-06-02 06:20:16 +08:00
2025-06-02 03:19:36 +08:00
2025-06-02 06:20:16 +08:00
const handleSearchSubmit = useCallback(() => {
2025-06-03 00:44:35 +08:00
const trimmedSearch = searchInput.trim();
if (!trimmedSearch) return;
2025-06-02 06:20:16 +08:00
2025-06-03 00:44:35 +08:00
handleTransition(() => {
setParams(prev => ({
2025-06-02 06:20:16 +08:00
...prev,
lastCategory: SEARCH_CATEGORY,
2025-06-03 00:44:35 +08:00
searchQuery: trimmedSearch, // Update global search query
2025-06-02 06:20:16 +08:00
history: {
...prev.history,
2025-06-03 00:44:35 +08:00
[SEARCH_CATEGORY]: { // Reset search history to page 1 for new search
lastPage: 1,
scrollPos: 0, // New search starts at top
searchQuery: trimmedSearch
2025-06-02 06:20:16 +08:00
}
2025-06-02 03:19:36 +08:00
}
2025-06-03 00:44:35 +08:00
}));
// console.log(`Search Submit: Fetching ${SEARCH_CATEGORY}, page 1, search: "${trimmedSearch}"`);
fetchMovies(SEARCH_CATEGORY, 1, trimmedSearch);
2025-06-02 06:20:16 +08:00
});
2025-06-03 00:44:35 +08:00
}, [handleTransition, setParams, fetchMovies, searchInput]);
2025-06-02 06:20:16 +08:00
const handleClearSearch = useCallback(() => {
2025-06-03 00:44:35 +08:00
if (!searchInput && currentCategory !== SEARCH_CATEGORY) return;
2025-06-02 06:20:16 +08:00
setSearchInput('');
2025-06-03 00:44:35 +08:00
// If we are currently in search results, transition to default category
2025-06-02 06:20:16 +08:00
if (currentCategory === SEARCH_CATEGORY) {
2025-06-03 00:44:35 +08:00
handleTransition(() => {
const defaultCategoryHistory = params.history[DEFAULT_CATEGORY] || { lastPage: 1, scrollPos: 0 };
setParams(prev => ({
...prev,
lastCategory: DEFAULT_CATEGORY,
searchQuery: '', // Clear global search query
// We can choose to preserve or reset params.history[SEARCH_CATEGORY].searchQuery
// For now, let's clear it in history as well if we are clearing and navigating away
history: {
...prev.history,
[SEARCH_CATEGORY]: { ...params.history[SEARCH_CATEGORY], searchQuery: '' }
}
}));
// console.log(`Clear Search (was search category): Fetching ${DEFAULT_CATEGORY}, page ${defaultCategoryHistory.lastPage}`);
fetchMovies(DEFAULT_CATEGORY, defaultCategoryHistory.lastPage);
});
2025-06-02 06:20:16 +08:00
} else {
2025-06-03 00:44:35 +08:00
// If not in search results, just clear the persisted search query
setParams(prev => ({ ...prev, searchQuery: '' }));
2025-06-02 06:20:16 +08:00
}
2025-06-03 00:44:35 +08:00
}, [currentCategory, fetchMovies, params.history, searchInput, setParams, handleTransition]);
2025-06-02 06:20:16 +08:00
2025-06-03 00:44:35 +08:00
const handleRename = useCallback(async (oldName, newName) => {
try {
const response = await axios.post('/movie/rename', { old_name: oldName, new_name: newName });
if (response.data.code === 200) {
// Refresh current view data, but skip scroll restoration
const pageToRefresh = currentCategoryHistory.lastPage;
const searchQueryForRefresh = currentCategory === SEARCH_CATEGORY ? (params.searchQuery || currentCategoryHistory.searchQuery || '') : '';
// console.log(`Rename: Refreshing ${currentCategory}, page ${pageToRefresh}, search: "${searchQueryForRefresh}" with skipRestore`);
await fetchMovies(currentCategory, pageToRefresh, searchQueryForRefresh, { skipRestore: true });
} else {
throw new Error(response.data.message || '重命名失败');
}
} catch (error) {
console.error('重命名错误:', error);
throw error; // Re-throw to allow MovieCard to handle it if needed
2025-06-02 06:20:16 +08:00
}
2025-06-03 00:44:35 +08:00
}, [fetchMovies, currentCategory, currentCategoryHistory, params.searchQuery]);
const handleMovieCardClick = useCallback(() => {
// This is a navigation, so save scroll state
// console.log(`Movie Card Click: Saving scroll for ${currentCategory} before navigating away.`);
handleScrollPosition('save', currentCategory);
// No need for manageScrollListener('remove') here as the component might unmount
// or if it's an in-app navigation, the next component will manage its own scroll.
}, [handleScrollPosition, currentCategory]);
const handleSearchChange = useCallback((e) => setSearchInput(e.target.value), []);
const handleSearchKeyDown = useCallback((e) => {
if (e.key === 'Enter') handleSearchSubmit();
2025-06-02 06:20:16 +08:00
}, [handleSearchSubmit]);
2025-06-03 00:44:35 +08:00
// Cleanup scroll listener on unmount
useEffect(() => {
return () => {
manageScrollListener('remove');
};
}, [manageScrollListener]);
2025-06-02 06:20:16 +08:00
2025-06-03 00:44:35 +08:00
const paginationComponent = movies.length > 0 && pagination.pages > 1 && (
2025-06-02 06:20:16 +08:00
<Pagination
count={pagination.pages}
page={pagination.page}
onChange={handlePageChange}
sx={{ my: 2, display: 'flex', justifyContent: 'center' }}
/>
);
2023-07-04 23:47:01 +08:00
return (
2023-07-08 03:15:48 +08:00
<Container style={{ marginTop: 20 }}>
2025-06-02 06:20:16 +08:00
<TextField
fullWidth
variant="outlined"
placeholder="搜索文件名..."
value={searchInput}
onChange={handleSearchChange}
onKeyDown={handleSearchKeyDown}
InputProps={{
2025-06-03 00:44:35 +08:00
startAdornment: <InputAdornment position="start"><SearchIcon /></InputAdornment>,
2025-06-02 06:20:16 +08:00
endAdornment: searchInput && (
<InputAdornment position="end">
2025-06-03 00:44:35 +08:00
<IconButton onClick={handleClearSearch} edge="end"><ClearIcon /></IconButton>
2025-06-02 06:20:16 +08:00
</InputAdornment>
)
}}
sx={{ mb: 2 }}
/>
2023-07-09 11:30:56 +08:00
<CategoryNav
2024-03-28 03:40:13 +08:00
categories={categories}
2025-06-03 00:44:35 +08:00
currentCategory={currentCategory === SEARCH_CATEGORY ? SEARCH_CATEGORY : currentCategory} // Pass SEARCH_CATEGORY special value
2023-07-09 11:30:56 +08:00
onCategoryChange={handleCategoryChange}
/>
2025-06-02 06:20:16 +08:00
{currentCategory === SEARCH_CATEGORY && (
<div style={{ textAlign: 'center', margin: '10px 0' }}>
2025-06-03 00:44:35 +08:00
搜索: "{params.searchQuery || currentCategoryHistory.searchQuery}" ({pagination.total} 个结果)
2025-06-02 06:20:16 +08:00
</div>
)}
{paginationComponent}
2025-06-03 00:44:35 +08:00
{loading && <CircularProgress sx={{ display: 'block', margin: '20px auto' }} />}
{!loading && movies.length === 0 && (
<div style={{ textAlign: 'center', margin: '20px 0', color: 'gray' }}>
没有找到结果
</div>
)}
{!loading && movies.length > 0 && (
2025-06-02 03:19:36 +08:00
<Grid container spacing={2} sx={{ mt: 0.5 }}>
2025-06-02 06:20:16 +08:00
{movies.map(item => (
2025-06-02 03:19:36 +08:00
<Grid item xs={6} sm={4} md={3} lg={2} key={item.filename}>
<Link
to={`/res/${item.filename}`}
2025-06-03 00:44:35 +08:00
style={{ textDecoration: 'none' }} // Removed paddingBottom, handle in Card
2025-06-02 03:19:36 +08:00
onClick={handleMovieCardClick}
>
2025-06-02 21:29:31 +08:00
<MovieCard movie={item} config={config} onRename={handleRename} />
2025-06-02 03:19:36 +08:00
</Link>
</Grid>
))}
</Grid>
)}
2025-06-02 06:20:16 +08:00
{paginationComponent}
2023-07-04 23:47:01 +08:00
</Container>
);
};
export default Main;