hola, necesito modularizar este proyecto para que sea mas facil mantener y tirar codigo,…
- User
hola, necesito modularizar este proyecto para que sea mas facil mantener y tirar codigo, mi app principal donde tengo todo lo del clone se llama App.tsx, necesito que todo esté al nivel de eso, dame los componentes por favor y dame todo el codigo completo:
import React, { useState, useEffect, useRef } from "react"; import YouTube, { YouTubeProps, YouTubePlayer } from "react-youtube"; import { Play, Pause, SkipBack, SkipForward, Shuffle, Repeat, VolumeX, Volume1, Volume2, Maximize2, Search, MoreHorizontal, Download, Share2, Mic2, ChevronDown, } from "lucide-react"; import { Button } from "./components/ui/button"; // Asegúrate de que la ruta sea correcta import { Input } from "./components/ui/input"; // Agregado para el campo de búsqueda import { Slider } from "./components/ui/slider"; // Asegúrate de tener este componente
// Interfaz para las canciones interface Song { title: string; artist: string; album: string; added: string; duration?: number; // Duración en segundos youtubeId?: string; }
// Lista de canciones con youtubeId const songs: Song[] = [ { title: "Las Piponas (Remix)", artist: "Kris R., Blessed", album: "Las Piponas (Remix)", added: "hace 2 horas", duration: 242, youtubeId: "Dftj21lTUIA", }, { title: "La Nueva Gerencia", artist: "Arcángel, Farruko", album: "La Nueva Gerencia", added: "hace 1 día", duration: 210, youtubeId: "ehYg8s7xHbs", }, { title: "Secretos", artist: "C.R.O, Kidd Keo", album: "Secretos", added: "hace 3 días", duration: 180, youtubeId: "GL7Xs9neldo", }, { title: "Lo Siento", artist: "Saigo", album: "Lo Siento", added: "hace una semana", duration: 200, youtubeId: "kLukLxV2J8M", }, // Puedes agregar más canciones aquí ];
// Información de la playlist const playlist = { name: "Time Free", description: "Relajao", owner: "Johan Morales", timesSaved: 8, coverImage: "https://i.postimg.cc/y8KhsW1p/imagen-blessd.jpg", // Asegúrate de que esta URL sea correcta };
// Función para obtener la miniatura de YouTube const getYouTubeThumbnail = (youtubeId: string): string =>
https://img.youtube.com/vi/${youtubeId}/hqdefault.jpg;// Función para formatear la duración total const formatTotalDuration = (totalSeconds: number): string => { const hours = Math.floor(totalSeconds / 3600); const minutes = Math.floor((totalSeconds % 3600) / 60); return
${hours} h ${minutes} min; };const SpotifyClone = () => { const [currentSong, setCurrentSong] = useState<Song | null>(null); const [isPlaying, setIsPlaying] = useState(false); const [isMobile, setIsMobile] = useState(window.innerWidth < 1024); const [showNavbar, setShowNavbar] = useState(true); const [isFullScreenPlayer, setIsFullScreenPlayer] = useState(false); // Nuevo estado
const playerRef = useRef<YouTubePlayer | null>(null);
const [currentTime, setCurrentTime] = useState(0); const [duration, setDuration] = useState(0);
const [volume, setVolume] = useState(100);
// Estado para manejar el último scroll const lastScrollY = useRef(0);
// Calcular el número de canciones y la duración total const songsCount = songs.length; const totalDurationInSeconds = songs.reduce( (sum, song) => sum + (song.duration || 0), 0 ); const totalDuration = formatTotalDuration(totalDurationInSeconds);
// Manejar el cambio de tamaño de la ventana useEffect(() => { const handleResize = () => { setIsMobile(window.innerWidth < 1024); };
handleResize(); window.addEventListener("resize", handleResize); return () => window.removeEventListener("resize", handleResize);}, []);
// Manejar la visibilidad de la barra de navegación al hacer scroll useEffect(() => { const handleScroll = () => { if (typeof window !== "undefined" && !isFullScreenPlayer) { if (window.scrollY > lastScrollY.current && window.scrollY > 100) { // Scroll hacia abajo setShowNavbar(false); } else { // Scroll hacia arriba setShowNavbar(true); } lastScrollY.current = window.scrollY; } };
window.addEventListener("scroll", handleScroll); return () => window.removeEventListener("scroll", handleScroll);}, [isFullScreenPlayer]);
// Función para obtener el índice de la canción actual const getCurrentIndex = (): number => { if (!currentSong?.youtubeId) return -1; return songs.findIndex((song) => song.youtubeId === currentSong.youtubeId); };
// Cargar y configurar el video cuando cambia la canción actual useEffect(() => { if (playerRef.current && currentSong?.youtubeId) { try { playerRef.current.loadVideoById(currentSong.youtubeId); setCurrentTime(0); setDuration(0); // La reproducción se manejará en onPlayerStateChange } catch (error) { console.error("Error al cargar el video:", error); } } }, [currentSong]);
// Reproducir o pausar cuando cambia el estado isPlaying useEffect(() => { if (playerRef.current) { if (isPlaying) { try { playerRef.current.playVideo(); } catch (error) { console.error("Error intentando reproducir el video:", error); } } else { playerRef.current.pauseVideo(); } } }, [isPlaying]);
// Actualizar el tiempo actual y la duración useEffect(() => { let intervalId: NodeJS.Timeout | null = null;
if (playerRef.current && isPlaying) { intervalId = setInterval(() => { const current = playerRef.current!.getCurrentTime(); const dura = playerRef.current!.getDuration(); setCurrentTime(current); setDuration(dura); }, 1000); } return () => { if (intervalId) clearInterval(intervalId); };}, [isPlaying]);
// Función para manejar Play/Pause const handlePlayPause = () => { if (isPlaying) { playerRef.current?.pauseVideo(); setIsPlaying(false); } else { if (currentSong?.youtubeId) { try { playerRef.current?.playVideo(); setIsPlaying(true); } catch (error) { console.error("Error intentando reproducir el video:", error); } } } };
// Función para cambiar a la siguiente canción const handleNextSong = () => { if (!currentSong) return; const currentIndex = getCurrentIndex(); if (currentIndex === -1) { console.error("La canción actual no se encuentra en la lista."); return; } const nextIndex = (currentIndex + 1) % songs.length; const nextSong = songs[nextIndex]; setCurrentSong(nextSong); setIsPlaying(true); // Asegurarse de que se reproduzca };
// Función para cambiar a la canción anterior const handlePreviousSong = () => { if (!currentSong) return; const currentIndex = getCurrentIndex(); if (currentIndex === -1) { console.error("La canción actual no se encuentra en la lista."); return; } const previousIndex = (currentIndex - 1 + songs.length) % songs.length; const previousSong = songs[previousIndex]; setCurrentSong(previousSong); setIsPlaying(true); // Asegurarse de que se reproduzca };
// Función para manejar cuando el reproductor está listo const onPlayerReady: YouTubeProps["onReady"] = (event) => { playerRef.current = event.target; setDuration(event.target.getDuration());
event.target.setVolume(volume); if (isPlaying) { try { event.target.playVideo(); } catch (error) { console.error("Error intentando reproducir el video:", error); } }};
// Función para manejar cuando el video termina const onPlayerEnd: YouTubeProps["onEnd"] = () => { handleNextSong(); };
// Función para manejar los errores del reproductor de YouTube const onPlayerError: YouTubeProps["onError"] = (event) => { console.error("Error del reproductor de YouTube:", event.data); // Puedes manejar diferentes códigos de error aquí si lo deseas };
// Función para manejar los cambios de estado del reproductor const onPlayerStateChange: YouTubeProps["onStateChange"] = (event) => { if (event.data === window.YT.PlayerState.ENDED) { handleNextSong(); } else if ( (event.data === window.YT.PlayerState.CUED || event.data === window.YT.PlayerState.BUFFERING) && isPlaying ) { try { playerRef.current?.playVideo(); } catch (error) { console.error("Error intentando reproducir el video:", error); } } };
// Opciones del reproductor de YouTube const opts: YouTubeProps["opts"] = { height: "0", width: "0", playerVars: { autoplay: 0, // Cambiar a 1 si deseas intentar autoplay, pero puede ser bloqueado controls: 0, disablekb: 1, fs: 0, modestbranding: 1, rel: 0, }, };
// Función para formatear el tiempo const formatTime = (seconds: number): string => { const minutes = Math.floor(seconds / 60); const secs = Math.floor(seconds % 60); const minutesStr = minutes < 10 ?
0${minutes}:${minutes}; const secondsStr = secs < 10 ?0${secs}:${secs}; return${minutesStr}:${secondsStr}; };// Función para manejar el cambio de progreso const handleProgressChange = (e: React.ChangeEvent) => { const newTime = Number(e.target.value); if (playerRef.current) { try { playerRef.current.seekTo(newTime, true); setCurrentTime(newTime); } catch (error) { console.error("Error al cambiar el progreso del video:", error); } } };
// Función para manejar el cambio de volumen const handleVolumeChange = (e: React.ChangeEvent) => { const newVolume = Number(e.target.value); setVolume(newVolume); if (playerRef.current) { try { playerRef.current.setVolume(newVolume); } catch (error) { console.error("Error al cambiar el volumen:", error); } } };
// Función para alternar mute/unmute const toggleMute = () => { if (playerRef.current) { try { if (playerRef.current.isMuted()) { playerRef.current.unMute(); setVolume(playerRef.current.getVolume()); } else { playerRef.current.mute(); setVolume(0); } } catch (error) { console.error("Error al alternar mute/unmute:", error); } } };
// Función para alternar el modo fullscreen del reproductor const toggleFullScreenPlayer = () => { setIsFullScreenPlayer(!isFullScreenPlayer); if (!isFullScreenPlayer) { setShowNavbar(false); // Ocultar la navbar al abrir el fullscreen } else { // Restaurar la visibilidad de la navbar al cerrar el fullscreen setShowNavbar(true); } };
// Función para garantizar la reproducción en dispositivos móviles después de un cambio const ensurePlayback = () => { if (isPlaying && playerRef.current) { try { playerRef.current.playVideo(); console.log("Reproducción iniciada automáticamente."); } catch (error) { console.error("Error al intentar reproducir automáticamente:", error); } } };
// UseEffect adicional para manejar la reproducción después de un cambio de canción useEffect(() => { if (currentSong && isPlaying) { // Utilizar un timeout para dar tiempo al reproductor a cargar el video const timeoutId = setTimeout(() => { ensurePlayback(); }, 1000); // 1 segundo de retraso
return () => clearTimeout(timeoutId); }}, [currentSong, isPlaying]);
return ( {/* Renderizar el reproductor solo si hay una canción seleccionada */} {currentSong?.youtubeId && ( <YouTube videoId={currentSong.youtubeId} opts={opts} onReady={onPlayerReady} onEnd={onPlayerEnd} onStateChange={onPlayerStateChange} onError={onPlayerError} // Añade este manejador de errores /> )}
{/* Barra de navegación superior */} <div className={`flex items-center p-4 bg-gradient-to-b from-gray-600 to-red-900 transition-transform duration-300 ${ showNavbar ? "translate-y-0" : "-translate-y-full" } fixed top-0 left-0 right-0 z-50`} > {/* Foto de perfil */} <div className="flex-shrink-0"> <img src="https://i.postimg.cc/PJPVDPZW/boyaca-yo.webp" // Reemplaza con tu foto de perfil alt="Perfil" className="w-8 h-8 rounded-full" /> </div> {/* Barra de búsqueda */} <div className="flex-1 mx-4"> <div className="relative"> <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 h-5 w-5" /> <Input type="text" placeholder="¿Qué quieres reproducir?" className="pl-10 pr-4 py-2 w-full bg-white/10 text-white placeholder-gray-400 rounded-full focus:outline-none focus:ring-2 focus:ring-green-500" /> </div> </div> </div> {/* Margen superior para evitar que el contenido quede oculto detrás de la barra fija */} <div className={`pt-20 flex-1 overflow-y-auto bg-gradient-to-b from-red-900 to-gray-900 ${ isFullScreenPlayer ? "hidden" : "" }`} // Ocultar el contenido principal cuando se está en fullscreen > {/* Información de la Playlist */} <div className="flex flex-col lg:flex-row mb-6 px-6"> <img src={playlist.coverImage || "/placeholder.svg"} alt="Playlist cover" className="w-40 h-40 object-cover rounded-md mx-auto lg:mx-0" /> <div className="text-left mt-4 lg:mt-0 lg:ml-6"> <h1 className="text-3xl lg:text-5xl font-bold mb-2"> {playlist.name} </h1> <p className="text-sm">{playlist.description}</p> <div className="flex items-center mt-2"> <img src="https://i.postimg.cc/PJPVDPZW/boyaca-yo.webp" alt="Propietario" className="w-6 h-6 rounded-full mr-2" /> <div className="flex flex-col"> <span className="text-sm">{playlist.owner}</span> <span className="text-sm text-gray-400"> {`${songsCount} canciones • ${totalDuration}`} </span> </div> </div> </div> </div> {/* Controles de reproducción */} {currentSong && ( <div className="flex items-center space-x-4 mb-6 px-6"> <Button size="lg" className="rounded-full bg-green-500 hover:bg-green-400" onClick={handlePlayPause} aria-label={isPlaying ? "Pausar" : "Reproducir"} > {isPlaying ? ( <Pause fill="black" className="w-6 h-6 text-black" /> ) : ( <Play fill="black" className="w-6 h-6 text-black" /> )} </Button> <Button variant="outline" size="icon" className="rounded-full" aria-label="Agregar a la cola" > <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" > <path d="M4.5 12.75L19.5 12.75" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" /> <path d="M12 5.25L12 20.25" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" /> </svg> </Button> <Button variant="ghost" size="icon" aria-label="Más opciones"> ••• </Button> </div> )} {/* Lista de canciones */} <div className="px-6"> <table className="w-full"> <thead> <tr className="text-left text-sm text-gray-400 border-b border-gray-800"> {/* Columnas que se ocultarán en móviles */} <th className="hidden lg:table-cell pb-2">#</th> <th className="pb-2">Título</th> <th className="hidden lg:table-cell pb-2">Álbum</th> <th className="hidden lg:table-cell pb-2"> Fecha en que se agregó </th> <th className="hidden lg:table-cell pb-2"> <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" > <path d="M8 3.33337V12.6667" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" /> <path d="M3.33331 8H12.6666" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" /> </svg> </th> </tr> </thead> <tbody> {songs.map((track, index) => ( <tr key={index} className="hover:bg-gray-800 cursor-pointer" onClick={() => { if (track.youtubeId) { setCurrentSong(track); setIsPlaying(true); // Asegurar que se reproduzca al seleccionar } }} > {/* Columna de número oculta en móviles */} <td className="hidden lg:table-cell py-2">{index + 1}</td> <td className="py-2"> <div className="flex items-center"> <img src={ track.youtubeId ? getYouTubeThumbnail(track.youtubeId) : "/placeholder.svg" } alt="Video thumbnail" className="w-10 h-10 mr-4 object-cover rounded-md" /> <div> <p className={`font-medium ${ track.youtubeId === currentSong?.youtubeId ? "text-green-500" : "text-white" }`} > {track.title} </p> <p className="text-sm text-gray-400">{track.artist}</p> </div> </div> </td> {/* Columna de álbum oculta en móviles */} <td className="hidden lg:table-cell py-2 text-sm text-gray-400"> {track.album} </td> {/* Columna de fecha oculta en móviles */} <td className="hidden lg:table-cell py-2 text-sm text-gray-400"> {track.added} </td> {/* Columna de duración oculta en móviles */} <td className="hidden lg:table-cell py-2 text-sm text-gray-400"> {track.duration ? formatTime(track.duration) : "--:--"} </td> </tr> ))} </tbody> </table> </div> </div> {/* Now Playing Bar (solo para dispositivos móviles, solo si hay una canción seleccionada y no está en fullscreen) */} {isMobile && currentSong && !isFullScreenPlayer && ( <div className="bg-gray-900 p-2 fixed bottom-0 left-0 right-0 z-50 cursor-pointer" onClick={toggleFullScreenPlayer} > <div className="flex items-center justify-between"> <div className="flex items-center space-x-2 flex-grow"> <img src={ currentSong.youtubeId ? getYouTubeThumbnail(currentSong.youtubeId) : "/placeholder.svg" } alt="Now playing cover" className="w-12 h-12 rounded" /> <div> <p className="font-medium">{currentSong.title}</p> <p className="text-sm text-gray-400">{currentSong.artist}</p> </div> </div> <div className="flex items-center space-x-4"> <Button variant="ghost" size="icon" className="text-white" onClick={(e) => { e.stopPropagation(); // Evitar que el click se propague al div padre handlePlayPause(); }} aria-label={isPlaying ? "Pausar" : "Reproducir"} > {isPlaying ? ( <Pause className="h-6 w-6" fill="currentColor" /> ) : ( <Play className="h-6 w-6" fill="currentColor" /> )} </Button> </div> </div> </div> )} {/* Panel Completo de Reproducción para Móviles */} {isMobile && isFullScreenPlayer && currentSong && ( <div className="flex flex-col h-screen bg-gradient-to-b from-gray-900 to-black text-white"> {/* Navigation */} <div className="flex justify-between items-center p-4"> <Button variant="ghost" size="icon" className="text-white" onClick={toggleFullScreenPlayer} > <ChevronDown className="h-6 w-6" /> </Button> <span className="text-sm font-semibold">Time Free</span> <Button variant="ghost" size="icon" className="text-white"> <MoreHorizontal className="h-6 w-6" /> </Button> </div> {/* Album Art */} <div className="flex-grow flex items-center justify-center p-4"> <img src={ currentSong.youtubeId ? getYouTubeThumbnail(currentSong.youtubeId) : "/placeholder.svg" } alt="Album Art" className="w-full h-full max-w-xs max-h-xs object-cover rounded-lg" /> </div> {/* Song Info */} <div className="px-4 py-2"> <h2 className="text-2xl font-bold">{currentSong.title}</h2> <p className="text-gray-400">{currentSong.artist}</p> </div> {/* Progress Bar */} <div className="px-4 py-2"> <Slider value={[(currentTime / duration) * 100 || 0]} max={100} step={1} onValueChange={(values) => { const newTime = (values[0] / 100) * duration; if (playerRef.current) { try { playerRef.current.seekTo(newTime, true); setCurrentTime(newTime); } catch (error) { console.error( "Error al cambiar el progreso del video:", error ); } } }} className="w-full" /> <div className="flex justify-between text-xs text-gray-400 mt-1"> <span>{formatTime(currentTime)}</span> <span>-{formatTime(duration - currentTime)}</span> </div> </div> {/* Playback Controls */} <div className="flex justify-between items-center px-4 py-6"> <Button variant="ghost" size="icon" className="text-white" onClick={() => { // Shuffle funcionalidad (seleccionar una canción al azar) const randomIndex = Math.floor(Math.random() * songs.length); setCurrentSong(songs[randomIndex]); setIsPlaying(true); }} aria-label="Shuffle" > <Shuffle className="h-6 w-6" /> </Button> <Button variant="ghost" size="icon" className="text-white" onClick={handlePreviousSong} aria-label="Anterior" > <SkipBack className="h-6 w-6" /> </Button> <Button size="icon" className="bg-white text-black rounded-full hover:bg-gray-200 h-16 w-16" onClick={handlePlayPause} aria-label={isPlaying ? "Pausar" : "Reproducir"} > {isPlaying ? ( <Pause className="h-8 w-8" fill="currentColor" /> ) : ( <Play className="h-8 w-8" fill="currentColor" /> )} </Button> <Button variant="ghost" size="icon" className="text-white" onClick={handleNextSong} aria-label="Siguiente" > <SkipForward className="h-6 w-6" /> </Button> <Button variant="ghost" size="icon" className="text-white" aria-label="Repetir" onClick={() => { // Repeat funcionalidad (repetir la misma canción) setIsPlaying(false); setCurrentSong(currentSong); setIsPlaying(true); }} > <Repeat className="h-6 w-6" /> </Button> </div> {/* Bottom Options */} <div className="flex justify-between items-center px-4 py-4"> <Button variant="ghost" size="icon" className="text-white"> <Download className="w-6 h-6" /> </Button> <Button variant="ghost" size="icon" className="text-white"> <Mic2 className="h-6 w-6" /> </Button> <Button variant="ghost" size="icon" className="text-white"> <Share2 className="h-6 w-6" /> </Button> </div> </div> )} {/* Barra de reproducción (solo para pantallas grandes, solo si hay una canción seleccionada) */} {!isMobile && currentSong && ( <div className={`flex flex-col lg:flex-row items-center justify-between p-4 bg-gray-900 border-t border-gray-800 fixed bottom-0 left-0 right-0 transition-margin duration-300 ease-in-out`} > {/* Información de la canción actual */} <div className="flex items-center mb-4 lg:mb-0 w-full lg:w-1/3 justify-center lg:justify-start"> <img src={ currentSong.youtubeId ? getYouTubeThumbnail(currentSong.youtubeId) : "/placeholder.svg" } alt="Album cover" className="w-10 h-10 mr-4 object-cover rounded-md" /> <div> <p className={`font-medium ${ currentSong.youtubeId === currentSong?.youtubeId ? "text-green-500" : "text-white" }`} > {currentSong.title} </p> <p className="text-sm text-gray-400">{currentSong.artist}</p> </div> </div> {/* Controles de reproducción y progreso */} <div className="flex flex-col items-center w-full lg:w-1/3"> <div className="flex items-center space-x-4 mb-2"> <Button variant="ghost" size="icon" className="text-gray-400 hover:text-white" aria-label="Shuffle" onClick={() => { // Shuffle funcionalidad (seleccionar una canción al azar) const randomIndex = Math.floor(Math.random() * songs.length); setCurrentSong(songs[randomIndex]); setIsPlaying(true); }} > <Shuffle className="w-5 h-5" /> </Button> <Button variant="ghost" size="icon" className="text-gray-400 hover:text-white" onClick={handlePreviousSong} aria-label="Anterior" > <SkipBack className="w-5 h-5" /> </Button> <Button size="icon" className={`rounded-full bg-white hover:bg-gray-200`} onClick={handlePlayPause} aria-label={isPlaying ? "Pausar" : "Reproducir"} > {isPlaying ? ( <Pause className="w-6 h-6 text-black" /> ) : ( <Play className="w-6 h-6 text-black" /> )} </Button> <Button variant="ghost" size="icon" className="text-gray-400 hover:text-white" onClick={handleNextSong} aria-label="Siguiente" > <SkipForward className="w-5 h-5" /> </Button> <Button variant="ghost" size="icon" className="text-gray-400 hover:text-white" aria-label="Repetir" onClick={() => { // Repeat funcionalidad (repetir la misma canción) setIsPlaying(false); setCurrentSong(currentSong); setIsPlaying(true); }} > <Repeat className="w-5 h-5" /> </Button> </div> <div className="flex items-center w-full space-x-2"> <span className="text-xs text-gray-400"> {formatTime(currentTime)} </span> <input type="range" min={0} max={duration} value={currentTime} onChange={handleProgressChange} className="flex-1 h-1 bg-gray-600 rounded-full cursor-pointer appearance-none focus:outline-none" /> <span className="text-xs text-gray-400"> {formatTime(duration)} </span> </div> </div> {/* Controles de volumen y pantalla completa */} <div className="flex items-center justify-end w-full lg:w-1/3 mt-4 lg:mt-0"> <Button variant="ghost" size="icon" className="text-gray-400 hover:text-white mr-2" onClick={toggleMute} aria-label={volume === 0 ? "Desmutear" : "Mute"} > {volume === 0 ? ( <VolumeX className="w-5 h-5" /> ) : volume <= 50 ? ( <Volume1 className="w-5 h-5" /> ) : ( <Volume2 className="w-5 h-5" /> )} </Button> <input type="range" min={0} max={100} value={volume} onChange={handleVolumeChange} className="w-24 h-1 bg-gray-600 rounded-full cursor-pointer appearance-none focus:outline-none" /> <Button variant="ghost" size="icon" className="text-gray-400 hover:text-white ml-2" aria-label="Pantalla completa" onClick={toggleFullScreenPlayer} > <Maximize2 className="w-5 h-5" /> </Button> </div> </div> )} </div>); };
export default SpotifyClone;
- Assistant
¡Hola! Para modularizar tu proyecto y facilitar su mantenimiento, vamos a dividir el componente principal
App.tsxen varios componentes más pequeños y manejables. A continuación, encontrarás una estructura sugerida con todos los componentes necesarios, cada uno en su propio archivo al mismo nivel queApp.tsx.Estructura de Archivos
src/ ├── App.tsx ├── Navbar.tsx ├── PlaylistInfo.tsx ├── PlaybackControls.tsx ├── SongList.tsx ├── NowPlayingBar.tsx ├── FullScreenPlayer.tsx └── PlaybackBar.tsx1.
Navbar.tsxEste componente representa la barra de navegación superior con la foto de perfil y el campo de búsqueda.
// Navbar.tsx import React from "react"; import { Search } from "lucide-react"; import { Input } from "./components/ui/input"; interface NavbarProps { searchValue: string; onSearchChange: (e: React.ChangeEvent<HTMLInputElement>) => void; } const Navbar: React.FC<NavbarProps> = ({ searchValue, onSearchChange }) => { return ( <div className="flex items-center p-4 bg-gradient-to-b from-gray-600 to-red-900 fixed top-0 left-0 right-0 z-50 transition-transform duration-300"> {/* Foto de perfil */} <div className="flex-shrink-0"> <img src="https://i.postimg.cc/PJPVDPZW/boyaca-yo.webp" // Reemplaza con tu foto de perfil alt="Perfil" className="w-8 h-8 rounded-full" /> </div> {/* Barra de búsqueda */} <div className="flex-1 mx-4"> <div className="relative"> <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 h-5 w-5" /> <Input type="text" placeholder="¿Qué quieres reproducir?" value={searchValue} onChange={onSearchChange} className="pl-10 pr-4 py-2 w-full bg-white/10 text-white placeholder-gray-400 rounded-full focus:outline-none focus:ring-2 focus:ring-green-500" /> </div> </div> </div> ); }; export default Navbar;2.
PlaylistInfo.tsxEste componente muestra la información de la playlist, incluyendo la imagen de portada, nombre, descripción, propietario, número de canciones y duración total.
// PlaylistInfo.tsx import React from "react"; interface Playlist { name: string; description: string; owner: string; songsCount: number; totalDuration: string; coverImage: string; } interface PlaylistInfoProps { playlist: Playlist; } const PlaylistInfo: React.FC<PlaylistInfoProps> = ({ playlist }) => { return ( <div className="flex flex-col lg:flex-row mb-6 px-6"> <img src={playlist.coverImage || "/placeholder.svg"} alt="Playlist cover" className="w-40 h-40 object-cover rounded-md mx-auto lg:mx-0" /> <div className="text-left mt-4 lg:mt-0 lg:ml-6"> <h1 className="text-3xl lg:text-5xl font-bold mb-2">{playlist.name}</h1> <p className="text-sm">{playlist.description}</p> <div className="flex items-center mt-2"> <img src="https://i.postimg.cc/PJPVDPZW/boyaca-yo.webp" // Reemplaza con el avatar del propietario alt="Propietario" className="w-6 h-6 rounded-full mr-2" /> <div className="flex flex-col"> <span className="text-sm">{playlist.owner}</span> <span className="text-sm text-gray-400"> {`${playlist.songsCount} canciones • ${playlist.totalDuration}`} </span> </div> </div> </div> </div> ); }; export default PlaylistInfo;3.
PlaybackControls.tsxEste componente contiene los controles de reproducción como Play/Pause, Agregar a la cola y Más opciones.
// PlaybackControls.tsx import React from "react"; import { Play, Pause, MoreHorizontal } from "lucide-react"; import { Button } from "./components/ui/button"; interface PlaybackControlsProps { isPlaying: boolean; onPlayPause: () => void; onAddToQueue: () => void; onMoreOptions: () => void; } const PlaybackControls: React.FC<PlaybackControlsProps> = ({ isPlaying, onPlayPause, onAddToQueue, onMoreOptions, }) => { return ( <div className="flex items-center space-x-4 mb-6 px-6"> <Button size="lg" className="rounded-full bg-green-500 hover:bg-green-400" onClick={onPlayPause} aria-label={isPlaying ? "Pausar" : "Reproducir"} > {isPlaying ? ( <Pause fill="black" className="w-6 h-6 text-black" /> ) : ( <Play fill="black" className="w-6 h-6 text-black" /> )} </Button> <Button variant="outline" size="icon" className="rounded-full" aria-label="Agregar a la cola" onClick={onAddToQueue} > <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" > <path d="M4.5 12.75L19.5 12.75" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" /> <path d="M12 5.25L12 20.25" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" /> </svg> </Button> <Button variant="ghost" size="icon" className="rounded-full" aria-label="Más opciones" onClick={onMoreOptions}> <MoreHorizontal /> </Button> </div> ); }; export default PlaybackControls;4.
SongList.tsxEste componente muestra la lista de canciones en una tabla. Permite seleccionar una canción para reproducir.
// SongList.tsx import React from "react"; interface Song { title: string; artist: string; album: string; added: string; duration?: number; youtubeId?: string; } interface SongListProps { songs: Song[]; currentSong: Song | null; onSongSelect: (song: Song) => void; } const getYouTubeThumbnail = (youtubeId: string): string => `https://img.youtube.com/vi/${youtubeId}/hqdefault.jpg`; const SongList: React.FC<SongListProps> = ({ songs, currentSong, onSongSelect }) => { const formatTime = (seconds: number): string => { const minutes = Math.floor(seconds / 60); const secs = Math.floor(seconds % 60); const minutesStr = minutes < 10 ? `0${minutes}` : `${minutes}`; const secondsStr = secs < 10 ? `0${secs}` : `${secs}`; return `${minutesStr}:${secondsStr}`; }; return ( <div className="px-6"> <table className="w-full"> <thead> <tr className="text-left text-sm text-gray-400 border-b border-gray-800"> {/* Columnas que se ocultarán en móviles */} <th className="hidden lg:table-cell pb-2">#</th> <th className="pb-2">Título</th> <th className="hidden lg:table-cell pb-2">Álbum</th> <th className="hidden lg:table-cell pb-2"> Fecha en que se agregó </th> <th className="hidden lg:table-cell pb-2"> <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" > <path d="M8 3.33337V12.6667" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" /> <path d="M3.33331 8H12.6666" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" /> </svg> </th> </tr> </thead> <tbody> {songs.map((track, index) => ( <tr key={index} className="hover:bg-gray-800 cursor-pointer" onClick={() => { if (track.youtubeId) { onSongSelect(track); } }} > {/* Columna de número oculta en móviles */} <td className="hidden lg:table-cell py-2">{index + 1}</td> <td className="py-2"> <div className="flex items-center"> <img src={ track.youtubeId ? getYouTubeThumbnail(track.youtubeId) : "/placeholder.svg" } alt="Video thumbnail" className="w-10 h-10 mr-4 object-cover rounded-md" /> <div> <p className={`font-medium ${ track.youtubeId === currentSong?.youtubeId ? "text-green-500" : "text-white" }`} > {track.title} </p> <p className="text-sm text-gray-400">{track.artist}</p> </div> </div> </td> {/* Columna de álbum oculta en móviles */} <td className="hidden lg:table-cell py-2 text-sm text-gray-400"> {track.album} </td> {/* Columna de fecha oculta en móviles */} <td className="hidden lg:table-cell py-2 text-sm text-gray-400"> {track.added} </td> {/* Columna de duración oculta en móviles */} <td className="hidden lg:table-cell py-2 text-sm text-gray-400"> {track.duration ? formatTime(track.duration) : "--:--"} </td> </tr> ))} </tbody> </table> </div> ); }; export default SongList;5.
NowPlayingBar.tsxEste componente muestra la barra de "Now Playing" en dispositivos móviles, permitiendo reproducir/pausar y acceder al modo de pantalla completa.
// NowPlayingBar.tsx import React from "react"; import { Pause, Play, ChevronDown } from "lucide-react"; import { Button } from "./components/ui/button"; interface Song { title: string; artist: string; youtubeId?: string; } interface NowPlayingBarProps { currentSong: Song; isPlaying: boolean; onPlayPause: (e: React.MouseEvent<HTMLButtonElement, MouseEvent>) => void; onToggleFullScreen: () => void; } const getYouTubeThumbnail = (youtubeId: string): string => `https://img.youtube.com/vi/${youtubeId}/hqdefault.jpg`; const NowPlayingBar: React.FC<NowPlayingBarProps> = ({ currentSong, isPlaying, onPlayPause, onToggleFullScreen, }) => { return ( <div className="bg-gray-900 p-2 fixed bottom-0 left-0 right-0 z-50 cursor-pointer" onClick={onToggleFullScreen} > <div className="flex items-center justify-between"> <div className="flex items-center space-x-2 flex-grow"> <img src={ currentSong.youtubeId ? getYouTubeThumbnail(currentSong.youtubeId) : "/placeholder.svg" } alt="Now playing cover" className="w-12 h-12 rounded" /> <div> <p className="font-medium">{currentSong.title}</p> <p className="text-sm text-gray-400">{currentSong.artist}</p> </div> </div> <div className="flex items-center space-x-4"> <Button variant="ghost" size="icon" className="text-white" onClick={(e) => { e.stopPropagation(); // Evitar que el click se propague al div padre onPlayPause(e); }} aria-label={isPlaying ? "Pausar" : "Reproducir"} > {isPlaying ? ( <Pause className="h-6 w-6" fill="currentColor" /> ) : ( <Play className="h-6 w-6" fill="currentColor" /> )} </Button> </div> </div> </div> ); }; export default NowPlayingBar;6.
FullScreenPlayer.tsxEste componente representa el panel de reproducción completa en dispositivos móviles, con controles avanzados.
// FullScreenPlayer.tsx import React from "react"; import { Shuffle, SkipBack, Play, Pause, SkipForward, Repeat, Download, Mic2, Share2, Maximize2, VolumeX, Volume1, Volume2, ChevronDown, } from "lucide-react"; import { Button } from "./components/ui/button"; import { Slider } from "./components/ui/slider"; interface Song { title: string; artist: string; youtubeId?: string; } interface FullScreenPlayerProps { currentSong: Song; isPlaying: boolean; onPlayPause: () => void; onNextSong: () => void; onPreviousSong: () => void; onShuffle: () => void; onRepeat: () => void; onVolumeChange: (e: React.ChangeEvent<HTMLInputElement>) => void; volume: number; onProgressChange: (values: number[]) => void; currentTime: number; duration: number; onClose: () => void; } const getYouTubeThumbnail = (youtubeId: string): string => `https://img.youtube.com/vi/${youtubeId}/hqdefault.jpg`; const formatTime = (seconds: number): string => { const minutes = Math.floor(seconds / 60); const secs = Math.floor(seconds % 60); const minutesStr = minutes < 10 ? `0${minutes}` : `${minutes}`; const secondsStr = secs < 10 ? `0${secs}` : `${secs}`; return `${minutesStr}:${secondsStr}`; }; const FullScreenPlayer: React.FC<FullScreenPlayerProps> = ({ currentSong, isPlaying, onPlayPause, onNextSong, onPreviousSong, onShuffle, onRepeat, onVolumeChange, volume, onProgressChange, currentTime, duration, onClose, }) => { return ( <div className="flex flex-col h-screen bg-gradient-to-b from-gray-900 to-black text-white"> {/* Navigation */} <div className="flex justify-between items-center p-4"> <Button variant="ghost" size="icon" className="text-white" onClick={onClose}> <ChevronDown className="h-6 w-6" /> </Button> <span className="text-sm font-semibold">Time Free</span> <Button variant="ghost" size="icon" className="text-white"> <MoreHorizontal className="h-6 w-6" /> </Button> </div> {/* Album Art */} <div className="flex-grow flex items-center justify-center p-4"> <img src={ currentSong.youtubeId ? getYouTubeThumbnail(currentSong.youtubeId) : "/placeholder.svg" } alt="Album Art" className="w-full h-full max-w-xs max-h-xs object-cover rounded-lg" /> </div> {/* Song Info */} <div className="px-4 py-2"> <h2 className="text-2xl font-bold">{currentSong.title}</h2> <p className="text-gray-400">{currentSong.artist}</p> </div> {/* Progress Bar */} <div className="px-4 py-2"> <Slider value={[(currentTime / duration) * 100 || 0]} max={100} step={1} onValueChange={onProgressChange} className="w-full" /> <div className="flex justify-between text-xs text-gray-400 mt-1"> <span>{formatTime(currentTime)}</span> <span>-{formatTime(duration - currentTime)}</span> </div> </div> {/* Playback Controls */} <div className="flex justify-between items-center px-4 py-6"> <Button variant="ghost" size="icon" className="text-white" onClick={onShuffle} aria-label="Shuffle" > <Shuffle className="h-6 w-6" /> </Button> <Button variant="ghost" size="icon" className="text-white" onClick={onPreviousSong} aria-label="Anterior" > <SkipBack className="h-6 w-6" /> </Button> <Button size="icon" className="bg-white text-black rounded-full hover:bg-gray-200 h-16 w-16" onClick={onPlayPause} aria-label={isPlaying ? "Pausar" : "Reproducir"} > {isPlaying ? ( <Pause className="h-8 w-8" fill="currentColor" /> ) : ( <Play className="h-8 w-8" fill="currentColor" /> )} </Button> <Button variant="ghost" size="icon" className="text-white" onClick={onNextSong} aria-label="Siguiente" > <SkipForward className="h-6 w-6" /> </Button> <Button variant="ghost" size="icon" className="text-white" onClick={onRepeat} aria-label="Repetir" > <Repeat className="h-6 w-6" /> </Button> </div> {/* Bottom Options */} <div className="flex justify-between items-center px-4 py-4"> <Button variant="ghost" size="icon" className="text-white"> <Download className="w-6 h-6" /> </Button> <Button variant="ghost" size="icon" className="text-white"> <Mic2 className="h-6 w-6" /> </Button> <Button variant="ghost" size="icon" className="text-white"> <Share2 className="h-6 w-6" /> </Button> </div> </div> ); }; export default FullScreenPlayer;7.
PlaybackBar.tsxEste componente representa la barra de reproducción en la parte inferior de la pantalla para dispositivos de escritorio.
// PlaybackBar.tsx import React from "react"; import { Shuffle, SkipBack, Play, Pause, SkipForward, Repeat, VolumeX, Volume1, Volume2, Maximize2, } from "lucide-react"; import { Button } from "./components/ui/button"; import { Slider } from "./components/ui/slider"; interface PlaybackBarProps { currentSong: { title: string; artist: string; youtubeId?: string; }; isPlaying: boolean; onPlayPause: () => void; onNextSong: () => void; onPreviousSong: () => void; onShuffle: () => void; onRepeat: () => void; onVolumeChange: (e: React.ChangeEvent<HTMLInputElement>) => void; volume: number; onFullScreen: () => void; currentTime: number; duration: number; onProgressChange: (e: React.ChangeEvent<HTMLInputElement>) => void; } const getYouTubeThumbnail = (youtubeId: string): string => `https://img.youtube.com/vi/${youtubeId}/hqdefault.jpg`; const formatTime = (seconds: number): string => { const minutes = Math.floor(seconds / 60); const secs = Math.floor(seconds % 60); const minutesStr = minutes < 10 ? `0${minutes}` : `${minutes}`; const secondsStr = secs < 10 ? `0${secs}` : `${secs}`; return `${minutesStr}:${secondsStr}`; }; const PlaybackBar: React.FC<PlaybackBarProps> = ({ currentSong, isPlaying, onPlayPause, onNextSong, onPreviousSong, onShuffle, onRepeat, onVolumeChange, volume, onFullScreen, currentTime, duration, onProgressChange, }) => { return ( <div className="flex flex-col lg:flex-row items-center justify-between p-4 bg-gray-900 border-t border-gray-800 fixed bottom-0 left-0 right-0 transition-margin duration-300 ease-in-out"> {/* Información de la canción actual */} <div className="flex items-center mb-4 lg:mb-0 w-full lg:w-1/3 justify-center lg:justify-start"> <img src={ currentSong.youtubeId ? getYouTubeThumbnail(currentSong.youtubeId) : "/placeholder.svg" } alt="Album cover" className="w-10 h-10 mr-4 object-cover rounded-md" /> <div> <p className={`font-medium ${ currentSong.youtubeId === currentSong?.youtubeId ? "text-green-500" : "text-white" }`} > {currentSong.title} </p> <p className="text-sm text-gray-400">{currentSong.artist}</p> </div> </div> {/* Controles de reproducción y progreso */} <div className="flex flex-col items-center w-full lg:w-1/3"> <div className="flex items-center space-x-4 mb-2"> <Button variant="ghost" size="icon" className="text-gray-400 hover:text-white" aria-label="Shuffle" onClick={onShuffle} > <Shuffle className="w-5 h-5" /> </Button> <Button variant="ghost" size="icon" className="text-gray-400 hover:text-white" onClick={onPreviousSong} aria-label="Anterior" > <SkipBack className="w-5 h-5" /> </Button> <Button size="icon" className={`rounded-full bg-white hover:bg-gray-200`} onClick={onPlayPause} aria-label={isPlaying ? "Pausar" : "Reproducir"} > {isPlaying ? ( <Pause className="w-6 h-6 text-black" /> ) : ( <Play className="w-6 h-6 text-black" /> )} </Button> <Button variant="ghost" size="icon" className="text-gray-400 hover:text-white" onClick={onNextSong} aria-label="Siguiente" > <SkipForward className="w-5 h-5" /> </Button> <Button variant="ghost" size="icon" className="text-gray-400 hover:text-white" aria-label="Repetir" onClick={onRepeat} > <Repeat className="w-5 h-5" /> </Button> </div> <div className="flex items-center w-full space-x-2"> <span className="text-xs text-gray-400">{formatTime(currentTime)}</span> <input type="range" min={0} max={duration} value={currentTime} onChange={onProgressChange} className="flex-1 h-1 bg-gray-600 rounded-full cursor-pointer appearance-none focus:outline-none" /> <span className="text-xs text-gray-400">{formatTime(duration)}</span> </div> </div> {/* Controles de volumen y pantalla completa */} <div className="flex items-center justify-end w-full lg:w-1/3 mt-4 lg:mt-0"> <Button variant="ghost" size="icon" className="text-gray-400 hover:text-white mr-2" onClick={() => { // Implementa la lógica de mute/unmute en el componente padre }} aria-label={volume === 0 ? "Desmutear" : "Mute"} > {volume === 0 ? ( <VolumeX className="w-5 h-5" /> ) : volume <= 50 ? ( <Volume1 className="w-5 h-5" /> ) : ( <Volume2 className="w-5 h-5" /> )} </Button> <input type="range" min={0} max={100} value={volume} onChange={onVolumeChange} className="w-24 h-1 bg-gray-600 rounded-full cursor-pointer appearance-none focus:outline-none" /> <Button variant="ghost" size="icon" className="text-gray-400 hover:text-white ml-2" aria-label="Pantalla completa" onClick={onFullScreen} > <Maximize2 className="w-5 h-5" /> </Button> </div> </div> ); }; export default PlaybackBar;8.
App.tsxAquí integramos todos los componentes anteriores, manejando el estado y la lógica principal de la aplicación.
// App.tsx import React, { useState, useEffect, useRef } from "react"; import YouTube, { YouTubeProps, YouTubePlayer } from "react-youtube"; import { Shuffle, Repeat, VolumeX, Volume1, Volume2, Maximize2, Search, MoreHorizontal, Download, Share2, Mic2, ChevronDown, } from "lucide-react"; import Navbar from "./Navbar"; import PlaylistInfo from "./PlaylistInfo"; import PlaybackControls from "./PlaybackControls"; import SongList from "./SongList"; import NowPlayingBar from "./NowPlayingBar"; import FullScreenPlayer from "./FullScreenPlayer"; import PlaybackBar from "./PlaybackBar"; import { Button } from "./components/ui/button"; import { Input } from "./components/ui/input"; import { Slider } from "./components/ui/slider"; // Interfaz para las canciones interface Song { title: string; artist: string; album: string; added: string; duration?: number; // Duración en segundos youtubeId?: string; } // Lista de canciones con youtubeId const songs: Song[] = [ { title: "Las Piponas (Remix)", artist: "Kris R., Blessed", album: "Las Piponas (Remix)", added: "hace 2 horas", duration: 242, youtubeId: "Dftj21lTUIA", }, { title: "La Nueva Gerencia", artist: "Arcángel, Farruko", album: "La Nueva Gerencia", added: "hace 1 día", duration: 210, youtubeId: "ehYg8s7xHbs", }, { title: "Secretos", artist: "C.R.O, Kidd Keo", album: "Secretos", added: "hace 3 días", duration: 180, youtubeId: "GL7Xs9neldo", }, { title: "Lo Siento", artist: "Saigo", album: "Lo Siento", added: "hace una semana", duration: 200, youtubeId: "kLukLxV2J8M", }, // Puedes agregar más canciones aquí ]; // Información de la playlist const playlist = { name: "Time Free", description: "Relajao", owner: "Johan Morales", songsCount: songs.length, coverImage: "https://i.postimg.cc/y8KhsW1p/imagen-blessd.jpg", // Asegúrate de que esta URL sea correcta }; // Función para formatear la duración total const formatTotalDuration = (totalSeconds: number): string => { const hours = Math.floor(totalSeconds / 3600); const minutes = Math.floor((totalSeconds % 3600) / 60); return `${hours} h ${minutes} min`; }; const App: React.FC = () => { const [currentSong, setCurrentSong] = useState<Song | null>(null); const [isPlaying, setIsPlaying] = useState<boolean>(false); const [isMobile, setIsMobile] = useState<boolean>(window.innerWidth < 1024); const [showNavbar, setShowNavbar] = useState<boolean>(true); const [isFullScreenPlayer, setIsFullScreenPlayer] = useState<boolean>(false); const playerRef = useRef<YouTubePlayer | null>(null); const [currentTime, setCurrentTime] = useState<number>(0); const [duration, setDuration] = useState<number>(0); const [volume, setVolume] = useState<number>(100); // Estado para manejar el último scroll const lastScrollY = useRef<number>(0); // Calcular la duración total const totalDurationInSeconds = songs.reduce( (sum, song) => sum + (song.duration || 0), 0 ); const totalDuration = formatTotalDuration(totalDurationInSeconds); // Manejar el cambio de tamaño de la ventana useEffect(() => { const handleResize = () => { setIsMobile(window.innerWidth < 1024); }; handleResize(); window.addEventListener("resize", handleResize); return () => window.removeEventListener("resize", handleResize); }, []); // Manejar la visibilidad de la barra de navegación al hacer scroll useEffect(() => { const handleScroll = () => { if (typeof window !== "undefined" && !isFullScreenPlayer) { if (window.scrollY > lastScrollY.current && window.scrollY > 100) { // Scroll hacia abajo setShowNavbar(false); } else { // Scroll hacia arriba setShowNavbar(true); } lastScrollY.current = window.scrollY; } }; window.addEventListener("scroll", handleScroll); return () => window.removeEventListener("scroll", handleScroll); }, [isFullScreenPlayer]); // Función para obtener el índice de la canción actual const getCurrentIndex = (): number => { if (!currentSong?.youtubeId) return -1; return songs.findIndex((song) => song.youtubeId === currentSong.youtubeId); }; // Cargar y configurar el video cuando cambia la canción actual useEffect(() => { if (playerRef.current && currentSong?.youtubeId) { try { playerRef.current.loadVideoById(currentSong.youtubeId); setCurrentTime(0); setDuration(0); // La reproducción se manejará en onPlayerStateChange } catch (error) { console.error("Error al cargar el video:", error); } } }, [currentSong]); // Reproducir o pausar cuando cambia el estado isPlaying useEffect(() => { if (playerRef.current) { if (isPlaying) { try { playerRef.current.playVideo(); } catch (error) { console.error("Error intentando reproducir el video:", error); } } else { playerRef.current.pauseVideo(); } } }, [isPlaying]); // Actualizar el tiempo actual y la duración useEffect(() => { let intervalId: NodeJS.Timeout | null = null; if (playerRef.current && isPlaying) { intervalId = setInterval(() => { const current = playerRef.current!.getCurrentTime(); const dura = playerRef.current!.getDuration(); setCurrentTime(current); setDuration(dura); }, 1000); } return () => { if (intervalId) clearInterval(intervalId); }; }, [isPlaying]); // Función para manejar Play/Pause const handlePlayPause = () => { if (isPlaying) { playerRef.current?.pauseVideo(); setIsPlaying(false); } else { if (currentSong?.youtubeId) { try { playerRef.current?.playVideo(); setIsPlaying(true); } catch (error) { console.error("Error intentando reproducir el video:", error); } } } }; // Función para cambiar a la siguiente canción const handleNextSong = () => { if (!currentSong) return; const currentIndex = getCurrentIndex(); if (currentIndex === -1) { console.error("La canción actual no se encuentra en la lista."); return; } const nextIndex = (currentIndex + 1) % songs.length; const nextSong = songs[nextIndex]; setCurrentSong(nextSong); setIsPlaying(true); // Asegurarse de que se reproduzca }; // Función para cambiar a la canción anterior const handlePreviousSong = () => { if (!currentSong) return; const currentIndex = getCurrentIndex(); if (currentIndex === -1) { console.error("La canción actual no se encuentra en la lista."); return; } const previousIndex = (currentIndex - 1 + songs.length) % songs.length; const previousSong = songs[previousIndex]; setCurrentSong(previousSong); setIsPlaying(true); // Asegurarse de que se reproduzca }; // Función para manejar cuando el reproductor está listo const onPlayerReady: YouTubeProps["onReady"] = (event) => { playerRef.current = event.target; setDuration(event.target.getDuration()); event.target.setVolume(volume); if (isPlaying) { try { event.target.playVideo(); } catch (error) { console.error("Error intentando reproducir el video:", error); } } }; // Función para manejar cuando el video termina const onPlayerEnd: YouTubeProps["onEnd"] = () => { handleNextSong(); }; // Función para manejar los errores del reproductor de YouTube const onPlayerError: YouTubeProps["onError"] = (event) => { console.error("Error del reproductor de YouTube:", event.data); // Puedes manejar diferentes códigos de error aquí si lo deseas }; // Función para manejar los cambios de estado del reproductor const onPlayerStateChange: YouTubeProps["onStateChange"] = (event) => { if (event.data === window.YT.PlayerState.ENDED) { handleNextSong(); } else if ( (event.data === window.YT.PlayerState.CUED || event.data === window.YT.PlayerState.BUFFERING) && isPlaying ) { try { playerRef.current?.playVideo(); } catch (error) { console.error("Error intentando reproducir el video:", error); } } }; // Opciones del reproductor de YouTube const opts: YouTubeProps["opts"] = { height: "0", width: "0", playerVars: { autoplay: 0, // Cambiar a 1 si deseas intentar autoplay, pero puede ser bloqueado controls: 0, disablekb: 1, fs: 0, modestbranding: 1, rel: 0, }, }; // Función para manejar el cambio de progreso const handleProgressChange = (e: React.ChangeEvent<HTMLInputElement>) => { const newTime = Number(e.target.value); if (playerRef.current) { try { playerRef.current.seekTo(newTime, true); setCurrentTime(newTime); } catch (error) { console.error("Error al cambiar el progreso del video:", error); } } }; // Función para manejar el cambio de volumen const handleVolumeChange = (e: React.ChangeEvent<HTMLInputElement>) => { const newVolume = Number(e.target.value); setVolume(newVolume); if (playerRef.current) { try { playerRef.current.setVolume(newVolume); } catch (error) { console.error("Error al cambiar el volumen:", error); } } }; // Función para alternar mute/unmute const toggleMute = () => { if (playerRef.current) { try { if (playerRef.current.isMuted()) { playerRef.current.unMute(); setVolume(playerRef.current.getVolume()); } else { playerRef.current.mute(); setVolume(0); } } catch (error) { console.error("Error al alternar mute/unmute:", error); } } }; // Función para alternar el modo fullscreen del reproductor const toggleFullScreenPlayer = () => { setIsFullScreenPlayer(!isFullScreenPlayer); if (!isFullScreenPlayer) { setShowNavbar(false); // Ocultar la navbar al abrir el fullscreen } else { // Restaurar la visibilidad de la navbar al cerrar el fullscreen setShowNavbar(true); } }; // Función para garantizar la reproducción en dispositivos móviles después de un cambio const ensurePlayback = () => { if (isPlaying && playerRef.current) { try { playerRef.current.playVideo(); console.log("Reproducción iniciada automáticamente."); } catch (error) { console.error("Error al intentar reproducir automáticamente:", error); } } }; // UseEffect adicional para manejar la reproducción después de un cambio de canción useEffect(() => { if (currentSong && isPlaying) { // Utilizar un timeout para dar tiempo al reproductor a cargar el video const timeoutId = setTimeout(() => { ensurePlayback(); }, 1000); // 1 segundo de retraso return () => clearTimeout(timeoutId); } }, [currentSong, isPlaying]); // Función para manejar clic en una canción const handleSongSelect = (song: Song) => { setCurrentSong(song); setIsPlaying(true); }; // Función para manejar cambios en la barra de búsqueda const [searchValue, setSearchValue] = useState<string>(""); const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => { setSearchValue(e.target.value); // Implementa la lógica de búsqueda si lo deseas }; // Funciones de reproducción avanzada const handleShuffle = () => { const randomIndex = Math.floor(Math.random() * songs.length); setCurrentSong(songs[randomIndex]); setIsPlaying(true); }; const handleRepeat = () => { if (currentSong) { setIsPlaying(false); setCurrentSong(currentSong); setIsPlaying(true); } }; return ( <div className="flex flex-col h-screen text-gray-300 bg-black"> {/* Renderizar el reproductor solo si hay una canción seleccionada */} {currentSong?.youtubeId && ( <YouTube videoId={currentSong.youtubeId} opts={opts} onReady={onPlayerReady} onEnd={onPlayerEnd} onStateChange={onPlayerStateChange} onError={onPlayerError} /> )} {/* Barra de navegación superior */} {showNavbar && ( <Navbar searchValue={searchValue} onSearchChange={handleSearchChange} /> )} {/* Margen superior para evitar que el contenido quede oculto detrás de la barra fija */} <div className={`pt-20 flex-1 overflow-y-auto bg-gradient-to-b from-red-900 to-gray-900 ${ isFullScreenPlayer ? "hidden" : "" }`} // Ocultar el contenido principal cuando se está en fullscreen > {/* Información de la Playlist */} <PlaylistInfo playlist={{ name: playlist.name, description: playlist.description, owner: playlist.owner, songsCount: playlist.songsCount, totalDuration: totalDuration, coverImage: playlist.coverImage, }} /> {/* Controles de reproducción */} {currentSong && ( <PlaybackControls isPlaying={isPlaying} onPlayPause={handlePlayPause} onAddToQueue={() => { // Implementa la lógica de agregar a la cola si lo deseas console.log("Agregar a la cola"); }} onMoreOptions={() => { // Implementa la lógica de más opciones si lo deseas console.log("Más opciones"); }} /> )} {/* Lista de canciones */} <SongList songs={songs} currentSong={currentSong} onSongSelect={handleSongSelect} /> </div> {/* Now Playing Bar (solo para dispositivos móviles, solo si hay una canción seleccionada y no está en fullscreen) */} {isMobile && currentSong && !isFullScreenPlayer && ( <NowPlayingBar currentSong={currentSong} isPlaying={isPlaying} onPlayPause={(e) => { e.preventDefault(); handlePlayPause(); }} onToggleFullScreen={toggleFullScreenPlayer} /> )} {/* Panel Completo de Reproducción para Móviles */} {isMobile && isFullScreenPlayer && currentSong && ( <FullScreenPlayer currentSong={currentSong} isPlaying={isPlaying} onPlayPause={handlePlayPause} onNextSong={handleNextSong} onPreviousSong={handlePreviousSong} onShuffle={handleShuffle} onRepeat={handleRepeat} onVolumeChange={handleVolumeChange} volume={volume} onProgressChange={(values) => { const newTime = (values[0] / 100) * duration; if (playerRef.current) { try { playerRef.current.seekTo(newTime, true); setCurrentTime(newTime); } catch (error) { console.error( "Error al cambiar el progreso del video:", error ); } } }} currentTime={currentTime} duration={duration} onClose={toggleFullScreenPlayer} /> )} {/* Barra de reproducción (solo para pantallas grandes, solo si hay una canción seleccionada) */} {!isMobile && currentSong && ( <PlaybackBar currentSong={currentSong} isPlaying={isPlaying} onPlayPause={handlePlayPause} onNextSong={handleNextSong} onPreviousSong={handlePreviousSong} onShuffle={handleShuffle} onRepeat={handleRepeat} onVolumeChange={handleVolumeChange} volume={volume} onFullScreen={toggleFullScreenPlayer} currentTime={currentTime} duration={duration} onProgressChange={handleProgressChange} /> )} </div> ); }; export default App;Notas Adicionales
-
Componentes UI Personalizados: Asegúrate de que los componentes
Button,InputySliderestén correctamente definidos en la carpeta./components/ui/. Si no los tienes, puedes crearlos o utilizar una librería de componentes como Radix UI o Material-UI. -
Iconos: Estás utilizando
lucide-reactpara los iconos. Asegúrate de tenerlo instalado:npm install lucide-react -
YouTube Player: El reproductor de YouTube está integrado en
App.tsx. Asegúrate de cargar la API de YouTube correctamente. Si tienes problemas con la carga del reproductor, revisa la documentación de react-youtube. -
Gestión de Estado y Eventos: Toda la lógica de reproducción y estado se maneja en
App.tsx, mientras que los componentes más pequeños reciben y ejecutan las funciones a través deprops. -
Responsividad: El diseño está pensado para adaptarse a dispositivos móviles y de escritorio. Asegúrate de probar en diferentes tamaños de pantalla para verificar que todo funcione correctamente.
-
Optimización: Dependiendo de tus necesidades futuras, podrías considerar dividir aún más los componentes o utilizar herramientas como Redux o Context API para manejar estados más complejos.
Espero que esta modularización te ayude a mantener y escalar tu proyecto más fácilmente. ¡Buena suerte!
-