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:
zimplexing
2025-07-06 20:45:42 +08:00
parent b2b667ae91
commit 08e24dd748
11 changed files with 592 additions and 585 deletions

View File

@@ -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 }],
},
});

View File

@@ -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,

View File

@@ -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>