242 lines
11 KiB
TypeScript
242 lines
11 KiB
TypeScript
import React, { useEffect, useState } from 'react';
|
||
import { View, Text, FlatList, TouchableOpacity, StyleSheet, Dimensions, Alert, Modal, TextInput } from 'react-native';
|
||
import api from '../api/client';
|
||
import { useSongStore } from '../store/songStore';
|
||
import { usePlaylistStore } from '../store/playlistStore';
|
||
|
||
const { width } = Dimensions.get('window');
|
||
|
||
export default function NowPlayingScreen({ navigation }) {
|
||
const {
|
||
currentSong,
|
||
isPlaying,
|
||
setIsPlaying,
|
||
position,
|
||
duration,
|
||
setSeekPosition,
|
||
playNext,
|
||
playPrev
|
||
} = useSongStore();
|
||
|
||
const { playlists } = usePlaylistStore();
|
||
const [isModalVisible, setIsModalVisible] = useState(false);
|
||
const [isCreating, setIsCreating] = useState(false);
|
||
const [newPlaylistName, setNewPlaylistName] = useState('');
|
||
|
||
if (!currentSong) {
|
||
return (
|
||
<View style={styles.container}>
|
||
<Text style={styles.emptyText}>No song currently playing</Text>
|
||
<TouchableOpacity style={styles.button} onPress={() => navigation.navigate('Discovery')}>
|
||
<Text style={styles.buttonText}>Go to Discovery</Text>
|
||
</TouchableOpacity>
|
||
</View>
|
||
);
|
||
}
|
||
|
||
const formatTime = (ms) => {
|
||
if (!ms || isNaN(ms)) return '00:00';
|
||
const seconds = Math.floor(ms / 1000);
|
||
const mins = Math.floor(seconds / 60);
|
||
const secs = seconds % 60;
|
||
return `${mins}:${secs < 10 ? '0' : ''}${secs}`;
|
||
};
|
||
|
||
const handleSaveForOffline = async () => {
|
||
try {
|
||
const response = await api.get(`/songs/${currentSong.id}/stream`, { responseType: 'blob' });
|
||
if (typeof window !== 'undefined') {
|
||
const url = window.URL.createObjectURL(new Blob([response.data]));
|
||
const link = document.createElement('a');
|
||
link.href = url;
|
||
link.setAttribute('download', `${currentSong.title}.mp3`);
|
||
document.body.appendChild(link);
|
||
link.click();
|
||
link.parentNode.removeChild(link);
|
||
} else {
|
||
Alert.alert('Save Offline', 'Offline saving is currently only supported on web.');
|
||
}
|
||
} catch (e) {
|
||
console.error('Error downloading song:', e);
|
||
Alert.alert('Error', 'Failed to save song for offline use');
|
||
}
|
||
};
|
||
|
||
const handleLikeAction = async (type) => {
|
||
try {
|
||
if (type === 'like') await api.post(`/songs/${currentSong.id}/like`);
|
||
else if (type === 'dislike') await api.post(`/songs/${currentSong.id}/dislike`);
|
||
else await api.delete(`/songs/${currentSong.id}/unlike`);
|
||
} catch (e) { console.error(e); }
|
||
};
|
||
|
||
const handleSeekPress = (event) => {
|
||
const touchX = event.nativeEvent.locationX;
|
||
const sliderWidth = width - 40; // padding is 20 on each side
|
||
const percentage = Math.max(0, Math.min(1, touchX / sliderWidth));
|
||
setSeekPosition(Math.floor(percentage * duration));
|
||
};
|
||
|
||
const addSongToPlaylist = async (playlistId) => {
|
||
try {
|
||
await api.post(`/playlists/${playlistId}/songs/${currentSong.id}`);
|
||
Alert.alert('Success', 'Song added to playlist');
|
||
setIsModalVisible(false);
|
||
} catch (e) {
|
||
console.error('Add to playlist error:', e);
|
||
Alert.alert('Error', 'Failed to add song to playlist');
|
||
}
|
||
};
|
||
|
||
const handleCreatePlaylist = async () => {
|
||
if (!newPlaylistName.trim()) {
|
||
Alert.alert('Error', 'Please enter a playlist name');
|
||
return;
|
||
}
|
||
try {
|
||
const response = await api.post('/playlists', { name: newPlaylistName });
|
||
const newPlaylist = response.data;
|
||
// We should ideally update the store here, but since we're just adding a song,
|
||
// and the user might go to Playlists screen later, it's okay for now if not immediate.
|
||
await addSongToPlaylist(newPlaylist.id);
|
||
setNewPlaylistName('');
|
||
setIsCreating(false);
|
||
} catch (e) {
|
||
console.error('Create playlist error:', e);
|
||
Alert.alert('Error', 'Failed to create playlist');
|
||
}
|
||
};
|
||
|
||
return (
|
||
<View style={styles.container}>
|
||
<Text style={styles.title}>{currentSong.title}</Text>
|
||
<Text style={styles.artist}>{currentSong.artist}</Text>
|
||
|
||
<View style={styles.sliderContainer}>
|
||
<TouchableOpacity activeOpacity={1} onPress={handleSeekPress} style={styles.sliderBar}>
|
||
<View style={[styles.progress, { width: `${(position / duration) * 100}%` }]} />
|
||
</TouchableOpacity>
|
||
<View style={styles.timeRow}>
|
||
<Text style={styles.time}>{formatTime(position)} / {formatTime(duration)}</Text>
|
||
</View>
|
||
</View>
|
||
|
||
<View style={styles.mainControls}>
|
||
<TouchableOpacity onPress={() => playPrev()} style={styles.controlButton}>
|
||
<Text style={styles.controlText}>⏮️</Text>
|
||
</TouchableOpacity>
|
||
<TouchableOpacity onPress={() => setIsPlaying(!isPlaying)} style={styles.playButton}>
|
||
<Text style={styles.playText}>{isPlaying ? '⏸️' : '▶️'}</Text>
|
||
</TouchableOpacity>
|
||
<TouchableOpacity onPress={() => playNext()} style={styles.controlButton}>
|
||
<Text style={styles.controlText}>⏭️</Text>
|
||
</TouchableOpacity>
|
||
</View>
|
||
|
||
<View style={styles.actionRow}>
|
||
<TouchableOpacity onPress={() => handleLikeAction('like')} style={styles.actionButton}>
|
||
<Text style={styles.actionText}>❤️ Like</Text>
|
||
</TouchableOpacity>
|
||
<TouchableOpacity onPress={() => handleLikeAction('dislike')} style={styles.actionButton}>
|
||
<Text style={styles.actionText}>👎 Dislike</Text>
|
||
</TouchableOpacity>
|
||
<TouchableOpacity onPress={handleSaveForOffline} style={styles.actionButton}>
|
||
<Text style={styles.actionText}>💾 Save</Text>
|
||
</TouchableOpacity>
|
||
</View>
|
||
|
||
<View style={styles.footerRow}>
|
||
<TouchableOpacity
|
||
style={styles.secondaryButton}
|
||
onPress={() => setIsModalVisible(true)}
|
||
>
|
||
<Text style={styles.secondaryText}>➕ Add to Playlist</Text>
|
||
</TouchableOpacity>
|
||
<TouchableOpacity
|
||
style={styles.secondaryButton}
|
||
onPress={() => navigation.navigate('Queue')}
|
||
>
|
||
<Text style={styles.secondaryText}>📜 View Queue</Text>
|
||
</TouchableOpacity>
|
||
</View>
|
||
|
||
<Modal visible={isModalVisible} transparent={true} animationType="fade">
|
||
<View style={styles.modalOverlay}>
|
||
<View style={styles.modalContent}>
|
||
<Text style={styles.modalTitle}>Add to Playlist</Text>
|
||
{isCreating ? (
|
||
<View style={styles.createPlaylistContainer}>
|
||
<TextInput
|
||
style={styles.playlistInput}
|
||
placeholder="Enter playlist name..."
|
||
value={newPlaylistName}
|
||
onChangeText={setNewPlaylistName}
|
||
/>
|
||
<TouchableOpacity style={styles.confirmBtn} onPress={handleCreatePlaylist}>
|
||
<Text style={{ color: 'white', fontWeight: 'bold' }}>Confirm</Text>
|
||
</TouchableOpacity>
|
||
<TouchableOpacity style={styles.cancelBtn} onPress={() => setIsCreating(false)}>
|
||
<Text style={{ color: 'gray' }}>Cancel</Text>
|
||
</TouchableOpacity>
|
||
</View>
|
||
) : (
|
||
<>
|
||
<FlatList
|
||
data={playlists}
|
||
keyExtractor={(item) => item.id.toString()}
|
||
renderItem={({ item }) => (
|
||
<TouchableOpacity style={styles.playlistOption} onPress={() => addSongToPlaylist(item.id)}>
|
||
<Text>{item.name}</Text>
|
||
</TouchableOpacity>
|
||
)}
|
||
/>
|
||
<TouchableOpacity style={styles.createBtn} onPress={() => setIsCreating(true)}>
|
||
<Text style={{ color: '#ff6347', fontWeight: 'bold' }}>+ Create New Playlist</Text>
|
||
</TouchableOpacity>
|
||
</>
|
||
)}
|
||
<TouchableOpacity style={styles.closeBtn} onPress={() => setIsModalVisible(false)}>
|
||
<Text style={{ color: 'gray' }}>Cancel</Text>
|
||
</TouchableOpacity>
|
||
</View>
|
||
</View>
|
||
</Modal>
|
||
</View>
|
||
);
|
||
}
|
||
|
||
const styles = StyleSheet.create({
|
||
container: { flex: 1, backgroundColor: '#fff', padding: 20, justifyContent: 'center' },
|
||
emptyText: { fontSize: 18, textAlign: 'center', color: '#666', marginBottom: 20 },
|
||
button: { backgroundColor: '#ff6347', padding: 15, borderRadius: 10, alignItems: 'center' },
|
||
buttonText: { color: 'white', fontWeight: 'bold' },
|
||
title: { fontSize: 28, fontWeight: 'bold', textAlign: 'center', marginBottom: 10 },
|
||
artist: { fontSize: 20, color: '#666', textAlign: 'center', marginBottom: 40 },
|
||
sliderContainer: { width: '100%', marginBottom: 40 },
|
||
sliderBar: { height: 8, backgroundColor: '#eee', borderRadius: 4, position: 'relative' },
|
||
progress: { height: '100%', backgroundColor: '#ff6347', borderRadius: 4 },
|
||
timeRow: { flexDirection: 'row', justifyContent: 'center', marginTop: 5 },
|
||
time: { fontSize: 12, color: '#999' },
|
||
mainControls: { flexDirection: 'row', justifyContent: 'center', alignItems: 'center', marginBottom: 40 },
|
||
controlButton: { marginHorizontal: 30 },
|
||
controlText: { fontSize: 40 },
|
||
playButton: { backgroundColor: '#ff6347', width: 80, height: 80, borderRadius: 40, justifyContent: 'center', alignItems: 'center' },
|
||
playText: { fontSize: 40, color: 'white' },
|
||
actionRow: { flexDirection: 'row', justifyContent: 'space-around', marginBottom: 30 },
|
||
actionButton: { padding: 10, backgroundColor: '#f0f0f0', borderRadius: 10, width: '30%', alignItems: 'center' },
|
||
actionText: { fontWeight: 'bold', color: '#333' },
|
||
footerRow: { flexDirection: 'row', justifyContent: 'space-around' },
|
||
secondaryButton: { padding: 12, backgroundColor: '#eee', borderRadius: 10, width: '45%', alignItems: 'center' },
|
||
secondaryText: { color: '#666', fontSize: 14 },
|
||
modalOverlay: { flex: 1, backgroundColor: 'rgba(0,0,0,0.5)', justifyContent: 'center', alignItems: 'center' },
|
||
modalContent: { backgroundColor: 'white', width: '80%', borderRadius: 20, padding: 20, maxHeight: '60%' },
|
||
modalTitle: { fontSize: 18, fontWeight: 'bold', marginBottom: 15, textAlign: 'center' },
|
||
playlistOption: { paddingVertical: 12, borderBottomWidth: 1, borderBottomColor: '#eee', alignItems: 'center' },
|
||
createBtn: { marginTop: 15, alignItems: 'center', padding: 10 },
|
||
closeBtn: { marginTop: 10, alignItems: 'center', padding: 10 },
|
||
createPlaylistContainer: { width: '100%', alignItems: 'center' },
|
||
playlistInput: { width: '100%', borderBottomWidth: 1, borderBottomColor: '#ccc', paddingVertical: 10, fontSize: 16, marginBottom: 20, textAlign: 'center' },
|
||
confirmBtn: { backgroundColor: '#ff6347', padding: 10, borderRadius: 10, width: '100%', alignItems: 'center', marginBottom: 10 },
|
||
cancelBtn: { padding: 10, alignItems: 'center', width: '100%' },
|
||
});
|