mirror of
https://github.com/zimplexing/OrionTV.git
synced 2026-02-04 03:36:29 +08:00
Refactor components to use Zustand for state management
- Updated EpisodeSelectionModal to utilize Zustand for episode selection state. - Refactored PlayerControls to manage playback state and controls using Zustand. - Simplified SettingsModal to handle settings state with Zustand. - Introduced homeStore for managing home screen categories and content data. - Created playerStore for managing video playback and episode details. - Added settingsStore for managing API settings and modal visibility. - Updated package.json to include Zustand as a dependency. - Cleaned up code formatting and improved readability across components.
This commit is contained in:
@@ -1,16 +1,11 @@
|
||||
import {
|
||||
DarkTheme,
|
||||
DefaultTheme,
|
||||
ThemeProvider,
|
||||
} from "@react-navigation/native";
|
||||
import { useFonts } from "expo-font";
|
||||
import { Stack } from "expo-router";
|
||||
import * as SplashScreen from "expo-splash-screen";
|
||||
import { useEffect } from "react";
|
||||
import { Platform } from "react-native";
|
||||
import { DarkTheme, DefaultTheme, ThemeProvider } from '@react-navigation/native';
|
||||
import { useFonts } from 'expo-font';
|
||||
import { Stack } from 'expo-router';
|
||||
import * as SplashScreen from 'expo-splash-screen';
|
||||
import { useEffect } from 'react';
|
||||
import { Platform, useColorScheme } from 'react-native';
|
||||
|
||||
import { useColorScheme } from "@/hooks/useColorScheme";
|
||||
import { initializeApi } from "@/services/api";
|
||||
import { useSettingsStore } from '@/stores/settingsStore';
|
||||
|
||||
// Prevent the splash screen from auto-hiding before asset loading is complete.
|
||||
SplashScreen.preventAutoHideAsync();
|
||||
@@ -18,8 +13,13 @@ SplashScreen.preventAutoHideAsync();
|
||||
export default function RootLayout() {
|
||||
const colorScheme = useColorScheme();
|
||||
const [loaded, error] = useFonts({
|
||||
SpaceMono: require("../assets/fonts/SpaceMono-Regular.ttf"),
|
||||
SpaceMono: require('../assets/fonts/SpaceMono-Regular.ttf'),
|
||||
});
|
||||
const initializeSettings = useSettingsStore(state => state.loadSettings);
|
||||
|
||||
useEffect(() => {
|
||||
initializeSettings();
|
||||
}, [initializeSettings]);
|
||||
|
||||
useEffect(() => {
|
||||
if (loaded || error) {
|
||||
@@ -30,22 +30,16 @@ export default function RootLayout() {
|
||||
}
|
||||
}, [loaded, error]);
|
||||
|
||||
useEffect(() => {
|
||||
initializeApi();
|
||||
}, []);
|
||||
|
||||
if (!loaded && !error) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<ThemeProvider value={colorScheme === "dark" ? DarkTheme : DefaultTheme}>
|
||||
<ThemeProvider value={colorScheme === 'dark' ? DarkTheme : DefaultTheme}>
|
||||
<Stack>
|
||||
<Stack.Screen name="index" options={{ headerShown: false }} />
|
||||
<Stack.Screen name="detail" options={{ headerShown: false }} />
|
||||
{Platform.OS !== "web" && (
|
||||
<Stack.Screen name="play" options={{ headerShown: false }} />
|
||||
)}
|
||||
{Platform.OS !== 'web' && <Stack.Screen name="play" options={{ headerShown: false }} />}
|
||||
<Stack.Screen name="search" options={{ headerShown: false }} />
|
||||
<Stack.Screen name="+not-found" />
|
||||
</Stack>
|
||||
|
||||
198
app/index.tsx
198
app/index.tsx
@@ -1,50 +1,15 @@
|
||||
import React, { useState, useEffect, useCallback, useRef } from 'react';
|
||||
import React, { useEffect, useCallback, useRef } from 'react';
|
||||
import { View, StyleSheet, ActivityIndicator, FlatList, Pressable, Dimensions } from 'react-native';
|
||||
import { ThemedView } from '@/components/ThemedView';
|
||||
import { ThemedText } from '@/components/ThemedText';
|
||||
import { api } from '@/services/api';
|
||||
import { SearchResult } from '@/services/api';
|
||||
import { PlayRecord } from '@/services/storage';
|
||||
|
||||
export type RowItem = (SearchResult | PlayRecord) & {
|
||||
id: string;
|
||||
source: string;
|
||||
title: string;
|
||||
poster: string;
|
||||
progress?: number;
|
||||
lastPlayed?: number;
|
||||
episodeIndex?: number;
|
||||
sourceName?: string;
|
||||
totalEpisodes?: number;
|
||||
year?: string;
|
||||
rate?: string;
|
||||
};
|
||||
import VideoCard from '@/components/VideoCard.tv';
|
||||
import { PlayRecordManager } from '@/services/storage';
|
||||
import { useFocusEffect, useRouter } from 'expo-router';
|
||||
import { useColorScheme } from 'react-native';
|
||||
import { Search, Settings } from 'lucide-react-native';
|
||||
import { SettingsModal } from '@/components/SettingsModal';
|
||||
|
||||
// --- 类别定义 ---
|
||||
interface Category {
|
||||
title: string;
|
||||
type?: 'movie' | 'tv' | 'record';
|
||||
tag?: string;
|
||||
}
|
||||
|
||||
const initialCategories: Category[] = [
|
||||
{ title: '最近播放', type: 'record' },
|
||||
{ title: '热门剧集', type: 'tv', tag: '热门' },
|
||||
{ title: '综艺', type: 'tv', tag: '综艺' },
|
||||
{ title: '热门电影', type: 'movie', tag: '热门' },
|
||||
{ title: '豆瓣 Top250', type: 'movie', tag: 'top250' },
|
||||
{ title: '儿童', type: 'movie', tag: '少儿' },
|
||||
{ title: '美剧', type: 'tv', tag: '美剧' },
|
||||
{ title: '韩剧', type: 'tv', tag: '韩剧' },
|
||||
{ title: '日剧', type: 'tv', tag: '日剧' },
|
||||
{ title: '日漫', type: 'tv', tag: '日本动画' },
|
||||
];
|
||||
import useHomeStore, { RowItem, Category } from '@/stores/homeStore';
|
||||
import { useSettingsStore } from '@/stores/settingsStore';
|
||||
|
||||
const NUM_COLUMNS = 5;
|
||||
const { width } = Dimensions.get('window');
|
||||
@@ -53,146 +18,40 @@ const ITEM_WIDTH = width / NUM_COLUMNS - 24;
|
||||
export default function HomeScreen() {
|
||||
const router = useRouter();
|
||||
const colorScheme = useColorScheme();
|
||||
|
||||
const [categories, setCategories] = useState<Category[]>(initialCategories);
|
||||
const [selectedCategory, setSelectedCategory] = useState<Category>(categories[0]);
|
||||
const [contentData, setContentData] = useState<RowItem[]>([]);
|
||||
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [loadingMore, setLoadingMore] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [isSettingsVisible, setSettingsVisible] = useState(false);
|
||||
|
||||
const [pageStart, setPageStart] = useState(0);
|
||||
const [hasMore, setHasMore] = useState(true);
|
||||
|
||||
const flatListRef = useRef<FlatList>(null);
|
||||
|
||||
// --- 数据获取逻辑 ---
|
||||
const fetchPlayRecords = async () => {
|
||||
const records = await PlayRecordManager.getAll();
|
||||
return Object.entries(records)
|
||||
.map(([key, record]) => {
|
||||
const [source, id] = key.split('+');
|
||||
return {
|
||||
id,
|
||||
source,
|
||||
title: record.title,
|
||||
poster: record.cover,
|
||||
progress: record.play_time / record.total_time,
|
||||
lastPlayed: record.save_time,
|
||||
episodeIndex: record.index,
|
||||
sourceName: record.source_name,
|
||||
totalEpisodes: record.total_episodes,
|
||||
} as RowItem;
|
||||
})
|
||||
.filter(record => record.progress !== undefined && record.progress > 0 && record.progress < 1)
|
||||
.sort((a, b) => (b.lastPlayed || 0) - (a.lastPlayed || 0));
|
||||
};
|
||||
const {
|
||||
categories,
|
||||
selectedCategory,
|
||||
contentData,
|
||||
loading,
|
||||
loadingMore,
|
||||
error,
|
||||
fetchInitialData,
|
||||
loadMoreData,
|
||||
selectCategory,
|
||||
refreshPlayRecords,
|
||||
} = useHomeStore();
|
||||
|
||||
const fetchData = async (category: Category, start: number, preloadedRecords?: RowItem[]) => {
|
||||
if (category.type === 'record') {
|
||||
const records = preloadedRecords ?? (await fetchPlayRecords());
|
||||
if (records.length === 0 && categories.some(c => c.type === 'record')) {
|
||||
// 如果没有播放记录,则移除"最近播放"分类并选择第一个真实分类
|
||||
const newCategories = categories.filter(c => c.type !== 'record');
|
||||
setCategories(newCategories);
|
||||
if (newCategories.length > 0) {
|
||||
handleCategorySelect(newCategories[0]);
|
||||
}
|
||||
} else {
|
||||
setContentData(records);
|
||||
setHasMore(false);
|
||||
}
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
const showSettingsModal = useSettingsStore(state => state.showModal);
|
||||
|
||||
if (!category.type || !category.tag) return;
|
||||
|
||||
setLoadingMore(start > 0);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const result = await api.getDoubanData(category.type, category.tag, 20, start);
|
||||
|
||||
if (result.list.length === 0) {
|
||||
setHasMore(false);
|
||||
} else {
|
||||
const newItems = result.list.map(item => ({
|
||||
...item,
|
||||
id: item.title, // 临时ID
|
||||
source: 'douban',
|
||||
})) as RowItem[];
|
||||
|
||||
setContentData(prev => (start === 0 ? newItems : [...prev, ...newItems]));
|
||||
setPageStart(prev => prev + result.list.length);
|
||||
setHasMore(true);
|
||||
}
|
||||
} catch (err: any) {
|
||||
if (err.message === 'API_URL_NOT_SET') {
|
||||
setError('请点击右上角设置按钮,配置您的 API 地址');
|
||||
} else {
|
||||
setError('加载失败,请重试');
|
||||
}
|
||||
} finally {
|
||||
setLoading(false);
|
||||
setLoadingMore(false);
|
||||
}
|
||||
};
|
||||
|
||||
// --- Effects ---
|
||||
useFocusEffect(
|
||||
useCallback(() => {
|
||||
const manageRecordCategory = async () => {
|
||||
const records = await fetchPlayRecords();
|
||||
const hasRecords = records.length > 0;
|
||||
|
||||
setCategories(currentCategories => {
|
||||
const recordCategoryExists = currentCategories.some(c => c.type === 'record');
|
||||
if (hasRecords && !recordCategoryExists) {
|
||||
// Add 'Recent Plays' if records exist and the tab doesn't
|
||||
return [initialCategories[0], ...currentCategories];
|
||||
}
|
||||
return currentCategories;
|
||||
});
|
||||
|
||||
// If 'Recent Plays' is selected, always refresh its data.
|
||||
// This will also handle removing the tab if records have disappeared.
|
||||
if (selectedCategory.type === 'record') {
|
||||
loadInitialData(records);
|
||||
}
|
||||
};
|
||||
|
||||
manageRecordCategory();
|
||||
}, [selectedCategory])
|
||||
refreshPlayRecords();
|
||||
}, [refreshPlayRecords])
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
loadInitialData();
|
||||
}, [selectedCategory]);
|
||||
|
||||
const loadInitialData = (records?: RowItem[]) => {
|
||||
setLoading(true);
|
||||
setContentData([]);
|
||||
setPageStart(0);
|
||||
setHasMore(true);
|
||||
fetchInitialData();
|
||||
flatListRef.current?.scrollToOffset({ animated: false, offset: 0 });
|
||||
fetchData(selectedCategory, 0, records);
|
||||
};
|
||||
|
||||
const loadMoreData = () => {
|
||||
if (loading || loadingMore || !hasMore || selectedCategory.type === 'record') return;
|
||||
fetchData(selectedCategory, pageStart);
|
||||
};
|
||||
}, [selectedCategory, fetchInitialData]);
|
||||
|
||||
const handleCategorySelect = (category: Category) => {
|
||||
setSelectedCategory(category);
|
||||
selectCategory(category);
|
||||
};
|
||||
|
||||
// --- 渲染组件 ---
|
||||
const renderCategory = ({ item }: { item: Category }) => {
|
||||
const isSelected = selectedCategory.title === item.title;
|
||||
const isSelected = selectedCategory?.title === item.title;
|
||||
return (
|
||||
<Pressable
|
||||
style={({ focused }) => [
|
||||
@@ -221,7 +80,7 @@ export default function HomeScreen() {
|
||||
sourceName={item.sourceName}
|
||||
totalEpisodes={item.totalEpisodes}
|
||||
api={api}
|
||||
onRecordDeleted={loadInitialData} // For "Recent Plays"
|
||||
onRecordDeleted={fetchInitialData} // For "Recent Plays"
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
@@ -245,7 +104,7 @@ export default function HomeScreen() {
|
||||
</Pressable>
|
||||
<Pressable
|
||||
style={({ focused }) => [styles.searchButton, focused && styles.searchButtonFocused]}
|
||||
onPress={() => setSettingsVisible(true)}
|
||||
onPress={showSettingsModal}
|
||||
>
|
||||
<Settings color={colorScheme === 'dark' ? 'white' : 'black'} size={24} />
|
||||
</Pressable>
|
||||
@@ -293,14 +152,7 @@ export default function HomeScreen() {
|
||||
}
|
||||
/>
|
||||
)}
|
||||
<SettingsModal
|
||||
visible={isSettingsVisible}
|
||||
onCancel={() => setSettingsVisible(false)}
|
||||
onSave={() => {
|
||||
setSettingsVisible(false);
|
||||
loadInitialData();
|
||||
}}
|
||||
/>
|
||||
<SettingsModal />
|
||||
</ThemedView>
|
||||
);
|
||||
}
|
||||
|
||||
156
app/play.tsx
156
app/play.tsx
@@ -1,49 +1,52 @@
|
||||
import React, { useState, useRef } from "react";
|
||||
import {
|
||||
View,
|
||||
StyleSheet,
|
||||
TouchableOpacity,
|
||||
ActivityIndicator,
|
||||
} from "react-native";
|
||||
import { useRouter } from "expo-router";
|
||||
import { Video, ResizeMode } from "expo-av";
|
||||
import { useKeepAwake } from "expo-keep-awake";
|
||||
import { ThemedView } from "@/components/ThemedView";
|
||||
import { PlayerControls } from "@/components/PlayerControls";
|
||||
import { EpisodeSelectionModal } from "@/components/EpisodeSelectionModal";
|
||||
import { NextEpisodeOverlay } from "@/components/NextEpisodeOverlay";
|
||||
import { LoadingOverlay } from "@/components/LoadingOverlay";
|
||||
import { usePlaybackManager } from "@/hooks/usePlaybackManager";
|
||||
import { useTVRemoteHandler } from "@/hooks/useTVRemoteHandler";
|
||||
import React, { useEffect, useRef } from 'react';
|
||||
import { View, StyleSheet, TouchableOpacity, ActivityIndicator } from 'react-native';
|
||||
import { useLocalSearchParams } from 'expo-router';
|
||||
import { Video, ResizeMode } from 'expo-av';
|
||||
import { useKeepAwake } from 'expo-keep-awake';
|
||||
import { ThemedView } from '@/components/ThemedView';
|
||||
import { PlayerControls } from '@/components/PlayerControls';
|
||||
import { EpisodeSelectionModal } from '@/components/EpisodeSelectionModal';
|
||||
import { NextEpisodeOverlay } from '@/components/NextEpisodeOverlay';
|
||||
import { LoadingOverlay } from '@/components/LoadingOverlay';
|
||||
import usePlayerStore from '@/stores/playerStore';
|
||||
import { useTVRemoteHandler } from '@/hooks/useTVRemoteHandler';
|
||||
|
||||
export default function PlayScreen() {
|
||||
const router = useRouter();
|
||||
const videoRef = useRef<Video>(null);
|
||||
useKeepAwake();
|
||||
const { source, id, episodeIndex } = useLocalSearchParams<{ source: string; id: string; episodeIndex: string }>();
|
||||
|
||||
const {
|
||||
detail,
|
||||
episodes,
|
||||
currentEpisodeIndex,
|
||||
status,
|
||||
isLoading,
|
||||
setIsLoading,
|
||||
showControls,
|
||||
showEpisodeModal,
|
||||
showNextEpisodeOverlay,
|
||||
setVideoRef,
|
||||
loadVideo,
|
||||
playEpisode,
|
||||
togglePlayPause,
|
||||
seek,
|
||||
handlePlaybackStatusUpdate,
|
||||
setShowControls,
|
||||
setShowEpisodeModal,
|
||||
setShowNextEpisodeOverlay,
|
||||
} = usePlaybackManager(videoRef);
|
||||
reset,
|
||||
} = usePlayerStore();
|
||||
|
||||
const [showControls, setShowControls] = useState(true);
|
||||
const [showEpisodeModal, setShowEpisodeModal] = useState(false);
|
||||
const [episodeGroupSize] = useState(30);
|
||||
const [selectedEpisodeGroup, setSelectedEpisodeGroup] = useState(
|
||||
Math.floor(currentEpisodeIndex / episodeGroupSize)
|
||||
);
|
||||
useEffect(() => {
|
||||
setVideoRef(videoRef);
|
||||
if (source && id) {
|
||||
loadVideo(source, id, parseInt(episodeIndex || '0', 10));
|
||||
}
|
||||
return () => {
|
||||
reset(); // Reset state when component unmounts
|
||||
};
|
||||
}, [source, id, episodeIndex, setVideoRef, loadVideo, reset]);
|
||||
|
||||
const { currentFocus, setCurrentFocus } = useTVRemoteHandler({
|
||||
const { setCurrentFocus } = useTVRemoteHandler({
|
||||
showControls,
|
||||
setShowControls,
|
||||
showEpisodeModal,
|
||||
@@ -57,46 +60,6 @@ export default function PlayScreen() {
|
||||
},
|
||||
});
|
||||
|
||||
const [isSeeking, setIsSeeking] = useState(false);
|
||||
const [seekPosition, setSeekPosition] = useState(0);
|
||||
const [progressPosition, setProgressPosition] = useState(0);
|
||||
|
||||
const formatTime = (milliseconds: number) => {
|
||||
if (!milliseconds) return "00:00";
|
||||
const totalSeconds = Math.floor(milliseconds / 1000);
|
||||
const minutes = Math.floor(totalSeconds / 60);
|
||||
const seconds = totalSeconds % 60;
|
||||
return `${minutes.toString().padStart(2, "0")}:${seconds
|
||||
.toString()
|
||||
.padStart(2, "0")}`;
|
||||
};
|
||||
|
||||
const handleSeekStart = () => setIsSeeking(true);
|
||||
|
||||
const handleSeekMove = (event: { nativeEvent: { locationX: number } }) => {
|
||||
if (!status?.isLoaded || !status.durationMillis) return;
|
||||
const { locationX } = event.nativeEvent;
|
||||
const progressBarWidth = 300;
|
||||
const progress = Math.max(0, Math.min(locationX / progressBarWidth, 1));
|
||||
setSeekPosition(progress);
|
||||
};
|
||||
|
||||
const handleSeekRelease = (event: { nativeEvent: { locationX: number } }) => {
|
||||
if (!videoRef.current || !status?.isLoaded || !status.durationMillis)
|
||||
return;
|
||||
const wasPlaying = status.isPlaying;
|
||||
const { locationX } = event.nativeEvent;
|
||||
const progressBarWidth = 300;
|
||||
const progress = Math.max(0, Math.min(locationX / progressBarWidth, 1));
|
||||
const newPosition = progress * status.durationMillis;
|
||||
videoRef.current.setPositionAsync(newPosition).then(() => {
|
||||
if (wasPlaying) {
|
||||
videoRef.current?.playAsync();
|
||||
}
|
||||
});
|
||||
setIsSeeking(false);
|
||||
};
|
||||
|
||||
if (!detail && isLoading) {
|
||||
return (
|
||||
<ThemedView style={[styles.container, styles.centered]}>
|
||||
@@ -106,8 +69,6 @@ export default function PlayScreen() {
|
||||
}
|
||||
|
||||
const currentEpisode = episodes[currentEpisodeIndex];
|
||||
const videoTitle = detail?.videoInfo?.title || "";
|
||||
const hasNextEpisode = currentEpisodeIndex < episodes.length - 1;
|
||||
|
||||
return (
|
||||
<ThemedView style={styles.container}>
|
||||
@@ -124,67 +85,28 @@ export default function PlayScreen() {
|
||||
style={styles.videoPlayer}
|
||||
source={{ uri: currentEpisode?.url }}
|
||||
resizeMode={ResizeMode.CONTAIN}
|
||||
onPlaybackStatusUpdate={(s) => {
|
||||
handlePlaybackStatusUpdate(s);
|
||||
if (s.isLoaded && !isSeeking) {
|
||||
setProgressPosition(s.positionMillis / (s.durationMillis || 1));
|
||||
}
|
||||
}}
|
||||
onLoad={() => setIsLoading(false)}
|
||||
onLoadStart={() => setIsLoading(true)}
|
||||
onPlaybackStatusUpdate={handlePlaybackStatusUpdate}
|
||||
onLoad={() => usePlayerStore.setState({ isLoading: false })}
|
||||
onLoadStart={() => usePlayerStore.setState({ isLoading: true })}
|
||||
useNativeControls={false}
|
||||
shouldPlay
|
||||
/>
|
||||
|
||||
{showControls && (
|
||||
<PlayerControls
|
||||
videoTitle={videoTitle}
|
||||
currentEpisodeTitle={currentEpisode?.title}
|
||||
status={status}
|
||||
isSeeking={isSeeking}
|
||||
seekPosition={seekPosition}
|
||||
progressPosition={progressPosition}
|
||||
currentFocus={currentFocus}
|
||||
hasNextEpisode={hasNextEpisode}
|
||||
onSeekStart={handleSeekStart}
|
||||
onSeekMove={handleSeekMove}
|
||||
onSeekRelease={handleSeekRelease}
|
||||
onSeek={seek}
|
||||
onTogglePlayPause={togglePlayPause}
|
||||
onPlayNextEpisode={() => playEpisode(currentEpisodeIndex + 1)}
|
||||
onShowEpisodes={() => setShowEpisodeModal(true)}
|
||||
formatTime={formatTime}
|
||||
/>
|
||||
)}
|
||||
{showControls && <PlayerControls />}
|
||||
|
||||
<LoadingOverlay visible={isLoading} />
|
||||
|
||||
<NextEpisodeOverlay
|
||||
visible={showNextEpisodeOverlay}
|
||||
onCancel={() => setShowNextEpisodeOverlay(false)}
|
||||
/>
|
||||
<NextEpisodeOverlay visible={showNextEpisodeOverlay} onCancel={() => setShowNextEpisodeOverlay(false)} />
|
||||
</TouchableOpacity>
|
||||
|
||||
<EpisodeSelectionModal
|
||||
visible={showEpisodeModal}
|
||||
episodes={episodes}
|
||||
currentEpisodeIndex={currentEpisodeIndex}
|
||||
episodeGroupSize={episodeGroupSize}
|
||||
selectedEpisodeGroup={selectedEpisodeGroup}
|
||||
setSelectedEpisodeGroup={setSelectedEpisodeGroup}
|
||||
onSelectEpisode={(index) => {
|
||||
playEpisode(index);
|
||||
setShowEpisodeModal(false);
|
||||
}}
|
||||
onClose={() => setShowEpisodeModal(false)}
|
||||
/>
|
||||
<EpisodeSelectionModal />
|
||||
</ThemedView>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: { flex: 1, backgroundColor: "black" },
|
||||
centered: { flex: 1, justifyContent: "center", alignItems: "center" },
|
||||
container: { flex: 1, backgroundColor: 'black' },
|
||||
centered: { flex: 1, justifyContent: 'center', alignItems: 'center' },
|
||||
videoContainer: {
|
||||
...StyleSheet.absoluteFillObject,
|
||||
},
|
||||
|
||||
@@ -1,74 +1,56 @@
|
||||
import React from "react";
|
||||
import {
|
||||
View,
|
||||
Text,
|
||||
StyleSheet,
|
||||
Modal,
|
||||
FlatList,
|
||||
Pressable,
|
||||
TouchableOpacity,
|
||||
} from "react-native";
|
||||
import React from 'react';
|
||||
import { View, Text, StyleSheet, Modal, FlatList, Pressable, TouchableOpacity } from 'react-native';
|
||||
|
||||
import usePlayerStore from '@/stores/playerStore';
|
||||
import { useState } from 'react';
|
||||
|
||||
interface Episode {
|
||||
title?: string;
|
||||
url: string;
|
||||
}
|
||||
|
||||
interface EpisodeSelectionModalProps {
|
||||
visible: boolean;
|
||||
episodes: Episode[];
|
||||
currentEpisodeIndex: number;
|
||||
episodeGroupSize: number;
|
||||
selectedEpisodeGroup: number;
|
||||
setSelectedEpisodeGroup: (group: number) => void;
|
||||
onSelectEpisode: (index: number) => void;
|
||||
onClose: () => void;
|
||||
}
|
||||
interface EpisodeSelectionModalProps {}
|
||||
|
||||
export const EpisodeSelectionModal: React.FC<EpisodeSelectionModalProps> = () => {
|
||||
const { showEpisodeModal, episodes, currentEpisodeIndex, playEpisode, setShowEpisodeModal } = usePlayerStore();
|
||||
|
||||
const [episodeGroupSize] = useState(30);
|
||||
const [selectedEpisodeGroup, setSelectedEpisodeGroup] = useState(Math.floor(currentEpisodeIndex / episodeGroupSize));
|
||||
|
||||
const onSelectEpisode = (index: number) => {
|
||||
playEpisode(index);
|
||||
setShowEpisodeModal(false);
|
||||
};
|
||||
|
||||
const onClose = () => {
|
||||
setShowEpisodeModal(false);
|
||||
};
|
||||
|
||||
export const EpisodeSelectionModal: React.FC<EpisodeSelectionModalProps> = ({
|
||||
visible,
|
||||
episodes,
|
||||
currentEpisodeIndex,
|
||||
episodeGroupSize,
|
||||
selectedEpisodeGroup,
|
||||
setSelectedEpisodeGroup,
|
||||
onSelectEpisode,
|
||||
onClose,
|
||||
}) => {
|
||||
return (
|
||||
<Modal
|
||||
visible={visible}
|
||||
transparent={true}
|
||||
animationType="slide"
|
||||
onRequestClose={onClose}
|
||||
>
|
||||
<Modal visible={showEpisodeModal} transparent={true} animationType="slide" onRequestClose={onClose}>
|
||||
<View style={styles.modalContainer}>
|
||||
<View style={styles.modalContent}>
|
||||
<Text style={styles.modalTitle}>选择剧集</Text>
|
||||
|
||||
{episodes.length > episodeGroupSize && (
|
||||
<View style={styles.episodeGroupContainer}>
|
||||
{Array.from(
|
||||
{ length: Math.ceil(episodes.length / episodeGroupSize) },
|
||||
(_, groupIndex) => (
|
||||
<TouchableOpacity
|
||||
key={groupIndex}
|
||||
style={[
|
||||
styles.episodeGroupButton,
|
||||
selectedEpisodeGroup === groupIndex &&
|
||||
styles.episodeGroupButtonSelected,
|
||||
]}
|
||||
onPress={() => setSelectedEpisodeGroup(groupIndex)}
|
||||
>
|
||||
<Text style={styles.episodeGroupButtonText}>
|
||||
{`${groupIndex * episodeGroupSize + 1}-${Math.min(
|
||||
(groupIndex + 1) * episodeGroupSize,
|
||||
episodes.length
|
||||
)}`}
|
||||
</Text>
|
||||
</TouchableOpacity>
|
||||
)
|
||||
)}
|
||||
{Array.from({ length: Math.ceil(episodes.length / episodeGroupSize) }, (_, groupIndex) => (
|
||||
<TouchableOpacity
|
||||
key={groupIndex}
|
||||
style={[
|
||||
styles.episodeGroupButton,
|
||||
selectedEpisodeGroup === groupIndex && styles.episodeGroupButtonSelected,
|
||||
]}
|
||||
onPress={() => setSelectedEpisodeGroup(groupIndex)}
|
||||
>
|
||||
<Text style={styles.episodeGroupButtonText}>
|
||||
{`${groupIndex * episodeGroupSize + 1}-${Math.min(
|
||||
(groupIndex + 1) * episodeGroupSize,
|
||||
episodes.length
|
||||
)}`}
|
||||
</Text>
|
||||
</TouchableOpacity>
|
||||
))}
|
||||
</View>
|
||||
)}
|
||||
<FlatList
|
||||
@@ -77,39 +59,27 @@ export const EpisodeSelectionModal: React.FC<EpisodeSelectionModalProps> = ({
|
||||
(selectedEpisodeGroup + 1) * episodeGroupSize
|
||||
)}
|
||||
numColumns={5}
|
||||
keyExtractor={(_, index) =>
|
||||
`episode-${selectedEpisodeGroup * episodeGroupSize + index}`
|
||||
}
|
||||
keyExtractor={(_, index) => `episode-${selectedEpisodeGroup * episodeGroupSize + index}`}
|
||||
renderItem={({ item, index }) => {
|
||||
const absoluteIndex =
|
||||
selectedEpisodeGroup * episodeGroupSize + index;
|
||||
const absoluteIndex = selectedEpisodeGroup * episodeGroupSize + index;
|
||||
return (
|
||||
<Pressable
|
||||
style={({ focused }) => [
|
||||
styles.episodeItem,
|
||||
currentEpisodeIndex === absoluteIndex &&
|
||||
styles.episodeItemSelected,
|
||||
currentEpisodeIndex === absoluteIndex && styles.episodeItemSelected,
|
||||
focused && styles.focusedButton,
|
||||
]}
|
||||
onPress={() => onSelectEpisode(absoluteIndex)}
|
||||
hasTVPreferredFocus={currentEpisodeIndex === absoluteIndex}
|
||||
>
|
||||
<Text style={styles.episodeItemText}>
|
||||
{item.title || `第 ${absoluteIndex + 1} 集`}
|
||||
</Text>
|
||||
<Text style={styles.episodeItemText}>{item.title || `第 ${absoluteIndex + 1} 集`}</Text>
|
||||
</Pressable>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
|
||||
<Pressable
|
||||
style={({ focused }) => [
|
||||
styles.closeButton,
|
||||
focused && styles.focusedButton,
|
||||
]}
|
||||
onPress={onClose}
|
||||
>
|
||||
<Text style={{ color: "white" }}>关闭</Text>
|
||||
<Pressable style={({ focused }) => [styles.closeButton, focused && styles.focusedButton]} onPress={onClose}>
|
||||
<Text style={{ color: 'white' }}>关闭</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
</View>
|
||||
@@ -120,69 +90,69 @@ export const EpisodeSelectionModal: React.FC<EpisodeSelectionModalProps> = ({
|
||||
const styles = StyleSheet.create({
|
||||
modalContainer: {
|
||||
flex: 1,
|
||||
flexDirection: "row",
|
||||
justifyContent: "flex-end",
|
||||
backgroundColor: "transparent",
|
||||
flexDirection: 'row',
|
||||
justifyContent: 'flex-end',
|
||||
backgroundColor: 'transparent',
|
||||
},
|
||||
modalContent: {
|
||||
width: 400,
|
||||
height: "100%",
|
||||
backgroundColor: "rgba(0, 0, 0, 0.85)",
|
||||
height: '100%',
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.85)',
|
||||
padding: 20,
|
||||
},
|
||||
modalTitle: {
|
||||
color: "white",
|
||||
color: 'white',
|
||||
marginBottom: 20,
|
||||
textAlign: "center",
|
||||
textAlign: 'center',
|
||||
fontSize: 18,
|
||||
fontWeight: "bold",
|
||||
fontWeight: 'bold',
|
||||
},
|
||||
episodeItem: {
|
||||
backgroundColor: "#333",
|
||||
backgroundColor: '#333',
|
||||
paddingVertical: 12,
|
||||
borderRadius: 8,
|
||||
margin: 4,
|
||||
flex: 1,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
},
|
||||
episodeItemSelected: {
|
||||
backgroundColor: "#007bff",
|
||||
backgroundColor: '#007bff',
|
||||
},
|
||||
episodeItemText: {
|
||||
color: "white",
|
||||
color: 'white',
|
||||
fontSize: 14,
|
||||
},
|
||||
episodeGroupContainer: {
|
||||
flexDirection: "row",
|
||||
flexWrap: "wrap",
|
||||
justifyContent: "center",
|
||||
flexDirection: 'row',
|
||||
flexWrap: 'wrap',
|
||||
justifyContent: 'center',
|
||||
marginBottom: 15,
|
||||
paddingHorizontal: 10,
|
||||
},
|
||||
episodeGroupButton: {
|
||||
backgroundColor: "#444",
|
||||
backgroundColor: '#444',
|
||||
paddingHorizontal: 12,
|
||||
paddingVertical: 6,
|
||||
borderRadius: 15,
|
||||
margin: 5,
|
||||
},
|
||||
episodeGroupButtonSelected: {
|
||||
backgroundColor: "#007bff",
|
||||
backgroundColor: '#007bff',
|
||||
},
|
||||
episodeGroupButtonText: {
|
||||
color: "white",
|
||||
color: 'white',
|
||||
fontSize: 12,
|
||||
},
|
||||
closeButton: {
|
||||
backgroundColor: "#333",
|
||||
backgroundColor: '#333',
|
||||
padding: 15,
|
||||
borderRadius: 8,
|
||||
alignItems: "center",
|
||||
alignItems: 'center',
|
||||
marginTop: 20,
|
||||
},
|
||||
focusedButton: {
|
||||
backgroundColor: "rgba(119, 119, 119, 0.9)",
|
||||
backgroundColor: 'rgba(119, 119, 119, 0.9)',
|
||||
transform: [{ scale: 1.1 }],
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1,76 +1,58 @@
|
||||
import React from "react";
|
||||
import {
|
||||
View,
|
||||
Text,
|
||||
StyleSheet,
|
||||
TouchableOpacity,
|
||||
Pressable,
|
||||
} from "react-native";
|
||||
import { useRouter } from "expo-router";
|
||||
import { AVPlaybackStatus } from "expo-av";
|
||||
import {
|
||||
ArrowLeft,
|
||||
Pause,
|
||||
Play,
|
||||
SkipForward,
|
||||
List,
|
||||
ChevronsRight,
|
||||
ChevronsLeft,
|
||||
} from "lucide-react-native";
|
||||
import { ThemedText } from "@/components/ThemedText";
|
||||
import { MediaButton } from "@/components/MediaButton";
|
||||
import React from 'react';
|
||||
import { View, Text, StyleSheet, TouchableOpacity, Pressable } from 'react-native';
|
||||
import { useRouter } from 'expo-router';
|
||||
import { AVPlaybackStatus } from 'expo-av';
|
||||
import { ArrowLeft, Pause, Play, SkipForward, List, ChevronsRight, ChevronsLeft } from 'lucide-react-native';
|
||||
import { ThemedText } from '@/components/ThemedText';
|
||||
import { MediaButton } from '@/components/MediaButton';
|
||||
|
||||
interface PlayerControlsProps {
|
||||
videoTitle: string;
|
||||
currentEpisodeTitle?: string;
|
||||
status: AVPlaybackStatus | null;
|
||||
isSeeking: boolean;
|
||||
seekPosition: number;
|
||||
progressPosition: number;
|
||||
currentFocus: string | null;
|
||||
hasNextEpisode: boolean;
|
||||
onSeekStart: () => void;
|
||||
onSeekMove: (event: { nativeEvent: { locationX: number } }) => void;
|
||||
onSeekRelease: (event: { nativeEvent: { locationX: number } }) => void;
|
||||
onSeek: (forward: boolean) => void;
|
||||
onTogglePlayPause: () => void;
|
||||
onPlayNextEpisode: () => void;
|
||||
onShowEpisodes: () => void;
|
||||
formatTime: (time: number) => string;
|
||||
}
|
||||
import usePlayerStore from '@/stores/playerStore';
|
||||
|
||||
export const PlayerControls: React.FC<PlayerControlsProps> = ({
|
||||
videoTitle,
|
||||
currentEpisodeTitle,
|
||||
status,
|
||||
isSeeking,
|
||||
seekPosition,
|
||||
progressPosition,
|
||||
currentFocus,
|
||||
hasNextEpisode,
|
||||
onSeekStart,
|
||||
onSeekMove,
|
||||
onSeekRelease,
|
||||
onSeek,
|
||||
onTogglePlayPause,
|
||||
onPlayNextEpisode,
|
||||
onShowEpisodes,
|
||||
formatTime,
|
||||
}) => {
|
||||
interface PlayerControlsProps {}
|
||||
|
||||
export const PlayerControls: React.FC<PlayerControlsProps> = () => {
|
||||
const router = useRouter();
|
||||
const {
|
||||
detail,
|
||||
currentEpisodeIndex,
|
||||
status,
|
||||
isSeeking,
|
||||
seekPosition,
|
||||
progressPosition,
|
||||
seek,
|
||||
togglePlayPause,
|
||||
playEpisode,
|
||||
setShowEpisodeModal,
|
||||
} = usePlayerStore();
|
||||
|
||||
const videoTitle = detail?.videoInfo?.title || '';
|
||||
const currentEpisode = detail?.episodes[currentEpisodeIndex];
|
||||
const currentEpisodeTitle = currentEpisode?.title;
|
||||
const hasNextEpisode = currentEpisodeIndex < (detail?.episodes.length || 0) - 1;
|
||||
|
||||
const formatTime = (milliseconds: number) => {
|
||||
if (!milliseconds) return '00:00';
|
||||
const totalSeconds = Math.floor(milliseconds / 1000);
|
||||
const minutes = Math.floor(totalSeconds / 60);
|
||||
const seconds = totalSeconds % 60;
|
||||
return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
|
||||
};
|
||||
|
||||
const onPlayNextEpisode = () => {
|
||||
if (hasNextEpisode) {
|
||||
playEpisode(currentEpisodeIndex + 1);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<View style={styles.controlsOverlay}>
|
||||
<View style={styles.topControls}>
|
||||
<TouchableOpacity
|
||||
style={styles.controlButton}
|
||||
onPress={() => router.back()}
|
||||
>
|
||||
<TouchableOpacity style={styles.controlButton} onPress={() => router.back()}>
|
||||
<ArrowLeft color="white" size={24} />
|
||||
</TouchableOpacity>
|
||||
|
||||
<Text style={styles.controlTitle}>
|
||||
{videoTitle} {currentEpisodeTitle ? `- ${currentEpisodeTitle}` : ""}
|
||||
{videoTitle} {currentEpisodeTitle ? `- ${currentEpisodeTitle}` : ''}
|
||||
</Text>
|
||||
</View>
|
||||
|
||||
@@ -81,40 +63,25 @@ export const PlayerControls: React.FC<PlayerControlsProps> = ({
|
||||
style={[
|
||||
styles.progressBarFilled,
|
||||
{
|
||||
width: `${
|
||||
(isSeeking ? seekPosition : progressPosition) * 100
|
||||
}%`,
|
||||
width: `${(isSeeking ? seekPosition : progressPosition) * 100}%`,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
<Pressable
|
||||
style={styles.progressBarTouchable}
|
||||
onPressIn={onSeekStart}
|
||||
onTouchMove={onSeekMove}
|
||||
onTouchEnd={onSeekRelease}
|
||||
/>
|
||||
<Pressable style={styles.progressBarTouchable} />
|
||||
</View>
|
||||
|
||||
<ThemedText style={{ color: "white", marginTop: 5 }}>
|
||||
<ThemedText style={{ color: 'white', marginTop: 5 }}>
|
||||
{status?.isLoaded
|
||||
? `${formatTime(status.positionMillis)} / ${formatTime(
|
||||
status.durationMillis || 0
|
||||
)}`
|
||||
: "00:00 / 00:00"}
|
||||
? `${formatTime(status.positionMillis)} / ${formatTime(status.durationMillis || 0)}`
|
||||
: '00:00 / 00:00'}
|
||||
</ThemedText>
|
||||
|
||||
<View style={styles.bottomControls}>
|
||||
<MediaButton
|
||||
onPress={() => onSeek(false)}
|
||||
isFocused={currentFocus === "skipBack"}
|
||||
>
|
||||
<MediaButton onPress={() => seek(false)}>
|
||||
<ChevronsLeft color="white" size={24} />
|
||||
</MediaButton>
|
||||
|
||||
<MediaButton
|
||||
onPress={onTogglePlayPause}
|
||||
isFocused={currentFocus === "playPause"}
|
||||
>
|
||||
<MediaButton onPress={togglePlayPause}>
|
||||
{status?.isLoaded && status.isPlaying ? (
|
||||
<Pause color="white" size={24} />
|
||||
) : (
|
||||
@@ -122,25 +89,15 @@ export const PlayerControls: React.FC<PlayerControlsProps> = ({
|
||||
)}
|
||||
</MediaButton>
|
||||
|
||||
<MediaButton
|
||||
onPress={onPlayNextEpisode}
|
||||
isFocused={currentFocus === "nextEpisode"}
|
||||
isDisabled={!hasNextEpisode}
|
||||
>
|
||||
<SkipForward color={hasNextEpisode ? "white" : "#666"} size={24} />
|
||||
<MediaButton onPress={onPlayNextEpisode} isDisabled={!hasNextEpisode}>
|
||||
<SkipForward color={hasNextEpisode ? 'white' : '#666'} size={24} />
|
||||
</MediaButton>
|
||||
|
||||
<MediaButton
|
||||
onPress={() => onSeek(true)}
|
||||
isFocused={currentFocus === "skipForward"}
|
||||
>
|
||||
<MediaButton onPress={() => seek(true)}>
|
||||
<ChevronsRight color="white" size={24} />
|
||||
</MediaButton>
|
||||
|
||||
<MediaButton
|
||||
onPress={onShowEpisodes}
|
||||
isFocused={currentFocus === "episodes"}
|
||||
>
|
||||
<MediaButton onPress={() => setShowEpisodeModal(true)}>
|
||||
<List color="white" size={24} />
|
||||
</MediaButton>
|
||||
</View>
|
||||
@@ -152,58 +109,58 @@ export const PlayerControls: React.FC<PlayerControlsProps> = ({
|
||||
const styles = StyleSheet.create({
|
||||
controlsOverlay: {
|
||||
...StyleSheet.absoluteFillObject,
|
||||
backgroundColor: "rgba(0, 0, 0, 0.4)",
|
||||
justifyContent: "space-between",
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.4)',
|
||||
justifyContent: 'space-between',
|
||||
padding: 20,
|
||||
},
|
||||
topControls: {
|
||||
flexDirection: "row",
|
||||
justifyContent: "space-between",
|
||||
alignItems: "center",
|
||||
flexDirection: 'row',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
},
|
||||
controlTitle: {
|
||||
color: "white",
|
||||
color: 'white',
|
||||
fontSize: 16,
|
||||
fontWeight: "bold",
|
||||
fontWeight: 'bold',
|
||||
flex: 1,
|
||||
textAlign: "center",
|
||||
textAlign: 'center',
|
||||
marginHorizontal: 10,
|
||||
},
|
||||
bottomControlsContainer: {
|
||||
width: "100%",
|
||||
alignItems: "center",
|
||||
width: '100%',
|
||||
alignItems: 'center',
|
||||
},
|
||||
bottomControls: {
|
||||
flexDirection: "row",
|
||||
justifyContent: "center",
|
||||
alignItems: "center",
|
||||
flexDirection: 'row',
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
gap: 10,
|
||||
flexWrap: "wrap",
|
||||
flexWrap: 'wrap',
|
||||
marginTop: 15,
|
||||
},
|
||||
progressBarContainer: {
|
||||
width: "100%",
|
||||
width: '100%',
|
||||
height: 8,
|
||||
position: "relative",
|
||||
position: 'relative',
|
||||
marginTop: 10,
|
||||
},
|
||||
progressBarBackground: {
|
||||
position: "absolute",
|
||||
position: 'absolute',
|
||||
left: 0,
|
||||
right: 0,
|
||||
height: 8,
|
||||
backgroundColor: "rgba(255, 255, 255, 0.3)",
|
||||
backgroundColor: 'rgba(255, 255, 255, 0.3)',
|
||||
borderRadius: 4,
|
||||
},
|
||||
progressBarFilled: {
|
||||
position: "absolute",
|
||||
position: 'absolute',
|
||||
left: 0,
|
||||
height: 8,
|
||||
backgroundColor: "#ff0000",
|
||||
backgroundColor: '#ff0000',
|
||||
borderRadius: 4,
|
||||
},
|
||||
progressBarTouchable: {
|
||||
position: "absolute",
|
||||
position: 'absolute',
|
||||
left: 0,
|
||||
right: 0,
|
||||
height: 30,
|
||||
@@ -212,20 +169,20 @@ const styles = StyleSheet.create({
|
||||
},
|
||||
controlButton: {
|
||||
padding: 10,
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
},
|
||||
topRightContainer: {
|
||||
padding: 10,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
minWidth: 44, // Match TouchableOpacity default size for alignment
|
||||
},
|
||||
resolutionText: {
|
||||
color: "white",
|
||||
color: 'white',
|
||||
fontSize: 16,
|
||||
fontWeight: "bold",
|
||||
backgroundColor: "rgba(0,0,0,0.5)",
|
||||
fontWeight: 'bold',
|
||||
backgroundColor: 'rgba(0,0,0,0.5)',
|
||||
paddingHorizontal: 8,
|
||||
paddingVertical: 4,
|
||||
borderRadius: 6,
|
||||
|
||||
@@ -1,38 +1,28 @@
|
||||
import React, { useState, useEffect, useRef } from 'react';
|
||||
import { Modal, View, Text, TextInput, StyleSheet, Pressable, useColorScheme } from 'react-native';
|
||||
import { SettingsManager } from '@/services/storage';
|
||||
import { api } from '@/services/api';
|
||||
import { ThemedText } from './ThemedText';
|
||||
import { ThemedView } from './ThemedView';
|
||||
import { useSettingsStore } from '@/stores/settingsStore';
|
||||
|
||||
interface SettingsModalProps {
|
||||
visible: boolean;
|
||||
onCancel: () => void;
|
||||
onSave: () => void;
|
||||
}
|
||||
export const SettingsModal: React.FC = () => {
|
||||
const { isModalVisible, hideModal, apiBaseUrl, setApiBaseUrl, saveSettings, loadSettings } = useSettingsStore();
|
||||
|
||||
export const SettingsModal: React.FC<SettingsModalProps> = ({ visible, onCancel, onSave }) => {
|
||||
const [apiUrl, setApiUrl] = useState('');
|
||||
const [isInputFocused, setIsInputFocused] = useState(false);
|
||||
const colorScheme = useColorScheme();
|
||||
const inputRef = useRef<TextInput>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (visible) {
|
||||
SettingsManager.get().then(settings => {
|
||||
setApiUrl(settings.apiBaseUrl);
|
||||
});
|
||||
if (isModalVisible) {
|
||||
loadSettings();
|
||||
const timer = setTimeout(() => {
|
||||
inputRef.current?.focus();
|
||||
}, 200);
|
||||
return () => clearTimeout(timer);
|
||||
}
|
||||
}, [visible]);
|
||||
}, [isModalVisible, loadSettings]);
|
||||
|
||||
const handleSave = async () => {
|
||||
await SettingsManager.save({ apiBaseUrl: apiUrl });
|
||||
api.setBaseUrl(apiUrl);
|
||||
onSave();
|
||||
const handleSave = () => {
|
||||
saveSettings();
|
||||
};
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
@@ -107,15 +97,15 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ visible, onCancel,
|
||||
});
|
||||
|
||||
return (
|
||||
<Modal animationType="fade" transparent={true} visible={visible} onRequestClose={onCancel}>
|
||||
<Modal animationType="fade" transparent={true} visible={isModalVisible} onRequestClose={hideModal}>
|
||||
<View style={styles.modalContainer}>
|
||||
<ThemedView style={styles.modalContent}>
|
||||
<ThemedText style={styles.title}>设置</ThemedText>
|
||||
<TextInput
|
||||
ref={inputRef}
|
||||
style={[styles.input, isInputFocused && styles.inputFocused]}
|
||||
value={apiUrl}
|
||||
onChangeText={setApiUrl}
|
||||
value={apiBaseUrl}
|
||||
onChangeText={setApiBaseUrl}
|
||||
placeholder="输入 API 地址"
|
||||
placeholderTextColor={colorScheme === 'dark' ? '#888' : '#555'}
|
||||
autoCapitalize="none"
|
||||
@@ -126,7 +116,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ visible, onCancel,
|
||||
<View style={styles.buttonContainer}>
|
||||
<Pressable
|
||||
style={({ focused }) => [styles.button, styles.buttonCancel, focused && styles.focusedButton]}
|
||||
onPress={onCancel}
|
||||
onPress={hideModal}
|
||||
>
|
||||
<Text style={styles.buttonText}>取消</Text>
|
||||
</Pressable>
|
||||
|
||||
@@ -50,7 +50,8 @@
|
||||
"react-native-safe-area-context": "4.10.1",
|
||||
"react-native-screens": "3.31.1",
|
||||
"react-native-svg": "^15.12.0",
|
||||
"react-native-web": "~0.19.10"
|
||||
"react-native-web": "~0.19.10",
|
||||
"zustand": "^5.0.6"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/core": "^7.20.0",
|
||||
|
||||
146
stores/homeStore.ts
Normal file
146
stores/homeStore.ts
Normal file
@@ -0,0 +1,146 @@
|
||||
import { create } from 'zustand';
|
||||
import { api, SearchResult, PlayRecord } from '@/services/api';
|
||||
import { PlayRecordManager } from '@/services/storage';
|
||||
|
||||
export type RowItem = (SearchResult | PlayRecord) & {
|
||||
id: string;
|
||||
source: string;
|
||||
title: string;
|
||||
poster: string;
|
||||
progress?: number;
|
||||
lastPlayed?: number;
|
||||
episodeIndex?: number;
|
||||
sourceName?: string;
|
||||
totalEpisodes?: number;
|
||||
year?: string;
|
||||
rate?: string;
|
||||
};
|
||||
|
||||
export interface Category {
|
||||
title: string;
|
||||
type?: 'movie' | 'tv' | 'record';
|
||||
tag?: string;
|
||||
}
|
||||
|
||||
const initialCategories: Category[] = [
|
||||
{ title: '最近播放', type: 'record' },
|
||||
{ title: '热门剧集', type: 'tv', tag: '热门' },
|
||||
{ title: '综艺', type: 'tv', tag: '综艺' },
|
||||
{ title: '热门电影', type: 'movie', tag: '热门' },
|
||||
{ title: '豆瓣 Top250', type: 'movie', tag: 'top250' },
|
||||
{ title: '儿童', type: 'movie', tag: '少儿' },
|
||||
{ title: '美剧', type: 'tv', tag: '美剧' },
|
||||
{ title: '韩剧', type: 'tv', tag: '韩剧' },
|
||||
{ title: '日剧', type: 'tv', tag: '日剧' },
|
||||
{ title: '日漫', type: 'tv', tag: '日本动画' },
|
||||
];
|
||||
|
||||
interface HomeState {
|
||||
categories: Category[];
|
||||
selectedCategory: Category;
|
||||
contentData: RowItem[];
|
||||
loading: boolean;
|
||||
loadingMore: boolean;
|
||||
pageStart: number;
|
||||
hasMore: boolean;
|
||||
error: string | null;
|
||||
fetchInitialData: () => Promise<void>;
|
||||
loadMoreData: () => Promise<void>;
|
||||
selectCategory: (category: Category) => void;
|
||||
refreshPlayRecords: () => Promise<void>;
|
||||
}
|
||||
|
||||
const useHomeStore = create<HomeState>((set, get) => ({
|
||||
categories: initialCategories,
|
||||
selectedCategory: initialCategories[0],
|
||||
contentData: [],
|
||||
loading: true,
|
||||
loadingMore: false,
|
||||
pageStart: 0,
|
||||
hasMore: true,
|
||||
error: null,
|
||||
|
||||
fetchInitialData: async () => {
|
||||
const { selectedCategory } = get();
|
||||
set({ loading: true, contentData: [], pageStart: 0, hasMore: true, error: null });
|
||||
await get().loadMoreData();
|
||||
set({ loading: false });
|
||||
},
|
||||
|
||||
loadMoreData: async () => {
|
||||
const { selectedCategory, pageStart, loading, loadingMore, hasMore } = get();
|
||||
if (loading || loadingMore || !hasMore) return;
|
||||
|
||||
if (selectedCategory.type === 'record') {
|
||||
const records = await PlayRecordManager.getAll();
|
||||
const rowItems = Object.entries(records)
|
||||
.map(([key, record]) => {
|
||||
const [source, id] = key.split('+');
|
||||
return { ...record, id, source, progress: record.play_time / record.total_time, poster: record.cover, sourceName: record.source_name, episodeIndex: record.index, totalEpisodes: record.total_episodes, lastPlayed: record.save_time };
|
||||
})
|
||||
.filter(record => record.progress !== undefined && record.progress > 0 && record.progress < 1)
|
||||
.sort((a, b) => (b.lastPlayed || 0) - (a.lastPlayed || 0));
|
||||
|
||||
set({ contentData: rowItems, hasMore: false });
|
||||
return;
|
||||
}
|
||||
|
||||
if (!selectedCategory.type || !selectedCategory.tag) return;
|
||||
|
||||
set({ loadingMore: true });
|
||||
try {
|
||||
const result = await api.getDoubanData(selectedCategory.type, selectedCategory.tag, 20, pageStart);
|
||||
if (result.list.length === 0) {
|
||||
set({ hasMore: false });
|
||||
} else {
|
||||
const newItems = result.list.map(item => ({
|
||||
...item,
|
||||
id: item.title,
|
||||
source: 'douban',
|
||||
})) as RowItem[];
|
||||
set(state => ({
|
||||
contentData: pageStart === 0 ? newItems : [...state.contentData, ...newItems],
|
||||
pageStart: state.pageStart + result.list.length,
|
||||
hasMore: true,
|
||||
}));
|
||||
}
|
||||
} catch (err: any) {
|
||||
if (err.message === 'API_URL_NOT_SET') {
|
||||
set({ error: '请点击右上角设置按钮,配置您的 API 地址' });
|
||||
} else {
|
||||
set({ error: '加载失败,请重试' });
|
||||
}
|
||||
} finally {
|
||||
set({ loadingMore: false });
|
||||
}
|
||||
},
|
||||
|
||||
selectCategory: (category: Category) => {
|
||||
set({ selectedCategory: category });
|
||||
get().fetchInitialData();
|
||||
},
|
||||
|
||||
refreshPlayRecords: async () => {
|
||||
const records = await PlayRecordManager.getAll();
|
||||
const hasRecords = Object.keys(records).length > 0;
|
||||
set(state => {
|
||||
const recordCategoryExists = state.categories.some(c => c.type === 'record');
|
||||
if (hasRecords && !recordCategoryExists) {
|
||||
return { categories: [initialCategories[0], ...state.categories] };
|
||||
}
|
||||
if (!hasRecords && recordCategoryExists) {
|
||||
const newCategories = state.categories.filter(c => c.type !== 'record');
|
||||
if (state.selectedCategory.type === 'record') {
|
||||
get().selectCategory(newCategories[0] || null);
|
||||
}
|
||||
return { categories: newCategories };
|
||||
}
|
||||
return {};
|
||||
});
|
||||
if (get().selectedCategory.type === 'record') {
|
||||
get().fetchInitialData();
|
||||
}
|
||||
},
|
||||
}));
|
||||
|
||||
export default useHomeStore;
|
||||
163
stores/playerStore.ts
Normal file
163
stores/playerStore.ts
Normal file
@@ -0,0 +1,163 @@
|
||||
import { create } from 'zustand';
|
||||
import { AVPlaybackStatus, Video } from 'expo-av';
|
||||
import { RefObject } from 'react';
|
||||
import { api, VideoDetail as ApiVideoDetail } from '@/services/api';
|
||||
import { PlayRecordManager } from '@/services/storage';
|
||||
|
||||
interface Episode {
|
||||
url: string;
|
||||
title: string;
|
||||
}
|
||||
|
||||
interface VideoDetail {
|
||||
videoInfo: ApiVideoDetail['videoInfo'];
|
||||
episodes: Episode[];
|
||||
}
|
||||
|
||||
interface PlayerState {
|
||||
videoRef: RefObject<Video> | null;
|
||||
detail: VideoDetail | null;
|
||||
episodes: Episode[];
|
||||
currentEpisodeIndex: number;
|
||||
status: AVPlaybackStatus | null;
|
||||
isLoading: boolean;
|
||||
showControls: boolean;
|
||||
showEpisodeModal: boolean;
|
||||
showNextEpisodeOverlay: boolean;
|
||||
isSeeking: boolean;
|
||||
seekPosition: number;
|
||||
progressPosition: number;
|
||||
setVideoRef: (ref: RefObject<Video>) => void;
|
||||
loadVideo: (source: string, id: string, episodeIndex: number) => Promise<void>;
|
||||
playEpisode: (index: number) => void;
|
||||
togglePlayPause: () => void;
|
||||
seek: (forward: boolean) => void;
|
||||
handlePlaybackStatusUpdate: (newStatus: AVPlaybackStatus) => void;
|
||||
setLoading: (loading: boolean) => void;
|
||||
setShowControls: (show: boolean) => void;
|
||||
setShowEpisodeModal: (show: boolean) => void;
|
||||
setShowNextEpisodeOverlay: (show: boolean) => void;
|
||||
reset: () => void;
|
||||
}
|
||||
|
||||
const usePlayerStore = create<PlayerState>((set, get) => ({
|
||||
videoRef: null,
|
||||
detail: null,
|
||||
episodes: [],
|
||||
currentEpisodeIndex: 0,
|
||||
status: null,
|
||||
isLoading: true,
|
||||
showControls: true,
|
||||
showEpisodeModal: false,
|
||||
showNextEpisodeOverlay: false,
|
||||
isSeeking: false,
|
||||
seekPosition: 0,
|
||||
progressPosition: 0,
|
||||
|
||||
setVideoRef: (ref) => set({ videoRef: ref }),
|
||||
|
||||
loadVideo: async (source, id, episodeIndex) => {
|
||||
set({ isLoading: true, detail: null, episodes: [], currentEpisodeIndex: 0 });
|
||||
try {
|
||||
const videoDetail = await api.getVideoDetail(source, id);
|
||||
const episodes = videoDetail.episodes.map((ep, index) => ({ url: ep, title: `第 ${index + 1} 集` }));
|
||||
set({
|
||||
detail: { videoInfo: videoDetail.videoInfo, episodes },
|
||||
episodes,
|
||||
currentEpisodeIndex: episodeIndex,
|
||||
isLoading: false,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Failed to load video details", error);
|
||||
set({ isLoading: false });
|
||||
}
|
||||
},
|
||||
|
||||
playEpisode: (index) => {
|
||||
const { episodes, videoRef } = get();
|
||||
if (index >= 0 && index < episodes.length) {
|
||||
set({ currentEpisodeIndex: index, showNextEpisodeOverlay: false });
|
||||
videoRef?.current?.replayAsync();
|
||||
}
|
||||
},
|
||||
|
||||
togglePlayPause: () => {
|
||||
const { status, videoRef } = get();
|
||||
if (status?.isLoaded) {
|
||||
if (status.isPlaying) {
|
||||
videoRef?.current?.pauseAsync();
|
||||
} else {
|
||||
videoRef?.current?.playAsync();
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
seek: (forward) => {
|
||||
const { status, videoRef } = get();
|
||||
if (status?.isLoaded) {
|
||||
const newPosition = status.positionMillis + (forward ? 15000 : -15000);
|
||||
videoRef?.current?.setPositionAsync(Math.max(0, newPosition));
|
||||
}
|
||||
},
|
||||
|
||||
handlePlaybackStatusUpdate: (newStatus) => {
|
||||
set({ status: newStatus });
|
||||
if (!newStatus.isLoaded) {
|
||||
if (newStatus.error) {
|
||||
console.error(`Playback Error: ${newStatus.error}`);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const { detail, currentEpisodeIndex, episodes } = get();
|
||||
if (detail && newStatus.durationMillis) {
|
||||
const { videoInfo } = detail;
|
||||
PlayRecordManager.save(
|
||||
videoInfo.source,
|
||||
videoInfo.id,
|
||||
{
|
||||
title: videoInfo.title,
|
||||
cover: videoInfo.cover || '',
|
||||
index: currentEpisodeIndex,
|
||||
total_episodes: episodes.length,
|
||||
play_time: newStatus.positionMillis,
|
||||
total_time: newStatus.durationMillis,
|
||||
source_name: videoInfo.source_name,
|
||||
}
|
||||
);
|
||||
|
||||
const isNearEnd = newStatus.positionMillis / newStatus.durationMillis > 0.95;
|
||||
if (isNearEnd && currentEpisodeIndex < episodes.length - 1) {
|
||||
set({ showNextEpisodeOverlay: true });
|
||||
} else {
|
||||
set({ showNextEpisodeOverlay: false });
|
||||
}
|
||||
}
|
||||
if (newStatus.didJustFinish) {
|
||||
const { playEpisode, currentEpisodeIndex, episodes } = get();
|
||||
if (currentEpisodeIndex < episodes.length - 1) {
|
||||
playEpisode(currentEpisodeIndex + 1);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
setLoading: (loading) => set({ isLoading: loading }),
|
||||
setShowControls: (show) => set({ showControls: show }),
|
||||
setShowEpisodeModal: (show) => set({ showEpisodeModal: show }),
|
||||
setShowNextEpisodeOverlay: (show) => set({ showNextEpisodeOverlay: show }),
|
||||
|
||||
reset: () => {
|
||||
set({
|
||||
detail: null,
|
||||
episodes: [],
|
||||
currentEpisodeIndex: 0,
|
||||
status: null,
|
||||
isLoading: true,
|
||||
showControls: true,
|
||||
showEpisodeModal: false,
|
||||
showNextEpisodeOverlay: false,
|
||||
});
|
||||
},
|
||||
}));
|
||||
|
||||
export default usePlayerStore;
|
||||
32
stores/settingsStore.ts
Normal file
32
stores/settingsStore.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
import { create } from 'zustand';
|
||||
import { SettingsManager } from '@/services/storage';
|
||||
import { api } from '@/services/api';
|
||||
|
||||
interface SettingsState {
|
||||
apiBaseUrl: string;
|
||||
isModalVisible: boolean;
|
||||
loadSettings: () => Promise<void>;
|
||||
setApiBaseUrl: (url: string) => void;
|
||||
saveSettings: () => Promise<void>;
|
||||
showModal: () => void;
|
||||
hideModal: () => void;
|
||||
}
|
||||
|
||||
export const useSettingsStore = create<SettingsState>((set, get) => ({
|
||||
apiBaseUrl: '',
|
||||
isModalVisible: false,
|
||||
loadSettings: async () => {
|
||||
const settings = await SettingsManager.get();
|
||||
set({ apiBaseUrl: settings.apiBaseUrl });
|
||||
api.setBaseUrl(settings.apiBaseUrl);
|
||||
},
|
||||
setApiBaseUrl: (url) => set({ apiBaseUrl: url }),
|
||||
saveSettings: async () => {
|
||||
const { apiBaseUrl } = get();
|
||||
await SettingsManager.save({ apiBaseUrl });
|
||||
api.setBaseUrl(apiBaseUrl);
|
||||
set({ isModalVisible: false });
|
||||
},
|
||||
showModal: () => set({ isModalVisible: true }),
|
||||
hideModal: () => set({ isModalVisible: false }),
|
||||
}));
|
||||
36
yarn.lock
36
yarn.lock
@@ -7909,16 +7909,7 @@ string-length@^5.0.1:
|
||||
char-regex "^2.0.0"
|
||||
strip-ansi "^7.0.1"
|
||||
|
||||
"string-width-cjs@npm:string-width@^4.2.0":
|
||||
version "4.2.3"
|
||||
resolved "https://registry.yarnpkg.com/string-width/-/string-width-4.2.3.tgz#269c7117d27b05ad2e536830a8ec895ef9c6d010"
|
||||
integrity sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==
|
||||
dependencies:
|
||||
emoji-regex "^8.0.0"
|
||||
is-fullwidth-code-point "^3.0.0"
|
||||
strip-ansi "^6.0.1"
|
||||
|
||||
string-width@^4.1.0, string-width@^4.2.0, string-width@^4.2.3:
|
||||
"string-width-cjs@npm:string-width@^4.2.0", string-width@^4.1.0, string-width@^4.2.0, string-width@^4.2.3:
|
||||
version "4.2.3"
|
||||
resolved "https://registry.yarnpkg.com/string-width/-/string-width-4.2.3.tgz#269c7117d27b05ad2e536830a8ec895ef9c6d010"
|
||||
integrity sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==
|
||||
@@ -7982,7 +7973,7 @@ string_decoder@~1.1.1:
|
||||
dependencies:
|
||||
safe-buffer "~5.1.0"
|
||||
|
||||
"strip-ansi-cjs@npm:strip-ansi@^6.0.1":
|
||||
"strip-ansi-cjs@npm:strip-ansi@^6.0.1", strip-ansi@^6.0.0, strip-ansi@^6.0.1:
|
||||
version "6.0.1"
|
||||
resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-6.0.1.tgz#9e26c63d30f53443e9489495b2105d37b67a85d9"
|
||||
integrity sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==
|
||||
@@ -7996,13 +7987,6 @@ strip-ansi@^5.0.0, strip-ansi@^5.2.0:
|
||||
dependencies:
|
||||
ansi-regex "^4.1.0"
|
||||
|
||||
strip-ansi@^6.0.0, strip-ansi@^6.0.1:
|
||||
version "6.0.1"
|
||||
resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-6.0.1.tgz#9e26c63d30f53443e9489495b2105d37b67a85d9"
|
||||
integrity sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==
|
||||
dependencies:
|
||||
ansi-regex "^5.0.1"
|
||||
|
||||
strip-ansi@^7.0.1:
|
||||
version "7.1.0"
|
||||
resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-7.1.0.tgz#d5b6568ca689d8561370b0707685d22434faff45"
|
||||
@@ -8750,7 +8734,7 @@ wonka@^6.3.2:
|
||||
resolved "https://registry.yarnpkg.com/wonka/-/wonka-6.3.5.tgz#33fa54ea700ff3e87b56fe32202112a9e8fea1a2"
|
||||
integrity sha512-SSil+ecw6B4/Dm7Pf2sAshKQ5hWFvfyGlfPbEd6A14dOH6VDjrmbY86u6nZvy9omGwwIPFR8V41+of1EezgoUw==
|
||||
|
||||
"wrap-ansi-cjs@npm:wrap-ansi@^7.0.0":
|
||||
"wrap-ansi-cjs@npm:wrap-ansi@^7.0.0", wrap-ansi@^7.0.0:
|
||||
version "7.0.0"
|
||||
resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-7.0.0.tgz#67e145cff510a6a6984bdf1152911d69d2eb9e43"
|
||||
integrity sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==
|
||||
@@ -8768,15 +8752,6 @@ wrap-ansi@^6.2.0:
|
||||
string-width "^4.1.0"
|
||||
strip-ansi "^6.0.0"
|
||||
|
||||
wrap-ansi@^7.0.0:
|
||||
version "7.0.0"
|
||||
resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-7.0.0.tgz#67e145cff510a6a6984bdf1152911d69d2eb9e43"
|
||||
integrity sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==
|
||||
dependencies:
|
||||
ansi-styles "^4.0.0"
|
||||
string-width "^4.1.0"
|
||||
strip-ansi "^6.0.0"
|
||||
|
||||
wrap-ansi@^8.1.0:
|
||||
version "8.1.0"
|
||||
resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-8.1.0.tgz#56dc22368ee570face1b49819975d9b9a5ead214"
|
||||
@@ -8953,3 +8928,8 @@ zod@^3.22.4:
|
||||
version "3.25.67"
|
||||
resolved "https://registry.yarnpkg.com/zod/-/zod-3.25.67.tgz#62987e4078e2ab0f63b491ef0c4f33df24236da8"
|
||||
integrity sha512-idA2YXwpCdqUSKRCACDE6ItZD9TZzy3OZMtpfLoh6oPR47lipysRrJfjzMqFxQ3uJuUPyUeWe1r9vLH33xO/Qw==
|
||||
|
||||
zustand@^5.0.6:
|
||||
version "5.0.6"
|
||||
resolved "https://registry.yarnpkg.com/zustand/-/zustand-5.0.6.tgz#a2da43d8dc3d31e314279e5baec06297bea70a5c"
|
||||
integrity sha512-ihAqNeUVhe0MAD+X8M5UzqyZ9k3FFZLBTtqo6JLPwV53cbRB/mJwBI0PxcIgqhBBHlEs8G45OTDTMq3gNcLq3A==
|
||||
|
||||
Reference in New Issue
Block a user