mira tengo esto: import React, { useState, useEffect, useRef } from "react"; import…
- User
mira tengo esto:
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, ArrowLeft, MoreHorizontal, Download, UserPlus2, ChevronDown, Share2, Mic2, } 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);
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") { 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);}, []);
// Cargar y reproducir el video cuando cambia la canción actual useEffect(() => { if (playerRef.current && currentSong?.youtubeId) { playerRef.current.loadVideoById(currentSong.youtubeId); setCurrentTime(0); setDuration(0); if (isPlaying) { playerRef.current.playVideo(); } } }, [currentSong, isPlaying]);
// Reproducir o pausar cuando cambia el estado isPlaying useEffect(() => { if (playerRef.current) { if (isPlaying) { playerRef.current.playVideo(); } 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]);
const handlePlayPause = () => { if (isPlaying) { playerRef.current?.pauseVideo(); } else { if (currentSong?.youtubeId) { playerRef.current?.playVideo(); } } setIsPlaying(!isPlaying); };
const handleNextSong = () => { if (!currentSong) return; const currentIndex = songs.indexOf(currentSong); const nextIndex = (currentIndex + 1) % songs.length; const nextSong = songs[nextIndex]; setIsPlaying(false); setCurrentSong(nextSong); };
const handlePreviousSong = () => { if (!currentSong) return; const currentIndex = songs.indexOf(currentSong); const previousIndex = (currentIndex - 1 + songs.length) % songs.length; const previousSong = songs[previousIndex]; setIsPlaying(false); setCurrentSong(previousSong); };
const onPlayerReady: YouTubeProps["onReady"] = (event) => { playerRef.current = event.target; setDuration(event.target.getDuration());
event.target.setVolume(volume); if (isPlaying) { event.target.playVideo(); }};
const onPlayerEnd: YouTubeProps["onEnd"] = () => { handleNextSong(); };
const onPlayerStateChange: YouTubeProps["onStateChange"] = (event) => { if (event.data === window.YT.PlayerState.ENDED) { handleNextSong(); } };
const opts: YouTubeProps["opts"] = { height: "0", width: "0", playerVars: { autoplay: 0, controls: 0, disablekb: 1, fs: 0, modestbranding: 1, rel: 0, }, };
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 handleProgressChange = (e: React.ChangeEvent) => { const newTime = Number(e.target.value); if (playerRef.current) { playerRef.current.seekTo(newTime, true); setCurrentTime(newTime); } };
const handleVolumeChange = (e: React.ChangeEvent) => { const newVolume = Number(e.target.value); setVolume(newVolume); if (playerRef.current) { playerRef.current.setVolume(newVolume); } };
const toggleMute = () => { if (playerRef.current) { if (playerRef.current.isMuted()) { playerRef.current.unMute(); setVolume(playerRef.current.getVolume()); } else { playerRef.current.mute(); setVolume(0); } } };
const toggleFullScreenPlayer = () => { setIsFullScreenPlayer(!isFullScreenPlayer); };
return ( {/* Renderizar el reproductor solo si hay una canción seleccionada */} {currentSong?.youtubeId && ( )}
{/* 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"> {/* 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); } }} > {/* 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.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) */} {isMobile && currentSong && ( <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) { playerRef.current.seekTo(newTime, true); setCurrentTime(newTime); } }} 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.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;
necesito que hagas algunos cambios, primero, que al momento en que se abre el panel de reproduccion en mobil, necesito que se esconda lo de abajo que hace com osi estuviera sonando, com oese footer, ademas necesito que el nvabar se escondan, necesito que al momento que se está esucchando una musica, yo pueda deslizarme por mi playlist, que no haya ningun tipo de error a la hora de navegar, tanto sea para pc como para mobil
- Assistant
Entiendo que deseas mejorar la experiencia de usuario en tu aplicación de clon de Spotify, especialmente en dispositivos móviles. A continuación, te proporcionaré las modificaciones necesarias para:
- Ocultar la barra de navegación superior y el footer de reproducción cuando se abre el panel de reproducción completo en dispositivos móviles.
- Permitir la navegación fluida por la lista de reproducción sin errores tanto en PC como en dispositivos móviles.
Pasos a Seguir:
-
Gestionar la visibilidad de la barra de navegación y el footer de reproducción:
- Cuando se abre el panel de reproducción completo (
isFullScreenPlayer), se debe ocultar la barra de navegación (showNavbar) y el footer de reproducción. - Al cerrar el panel de reproducción completo, se debe restaurar la visibilidad de la barra de navegación y el footer.
- Cuando se abre el panel de reproducción completo (
-
Asegurar que la lista de reproducción sea desplazable independientemente del estado del reproductor:
- Ajustar el diseño y los estilos CSS para asegurar que el contenido principal (lista de reproducción) sea siempre desplazable.
Implementación
A continuación, se muestra el código modificado con los cambios necesarios:
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<boolean>(false); const [isMobile, setIsMobile] = useState<boolean>(window.innerWidth < 1024); const [showNavbar, setShowNavbar] = useState<boolean>(true); const [isFullScreenPlayer, setIsFullScreenPlayer] = useState<boolean>(false); // Nuevo estado 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 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); 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) { // Añadido check para el FullScreen 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]); // Cargar y reproducir el video cuando cambia la canción actual useEffect(() => { if (playerRef.current && currentSong?.youtubeId) { playerRef.current.loadVideoById(currentSong.youtubeId); setCurrentTime(0); setDuration(0); if (isPlaying) { playerRef.current.playVideo(); } } }, [currentSong, isPlaying]); // Reproducir o pausar cuando cambia el estado isPlaying useEffect(() => { if (playerRef.current) { if (isPlaying) { playerRef.current.playVideo(); } 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]); const handlePlayPause = () => { if (isPlaying) { playerRef.current?.pauseVideo(); } else { if (currentSong?.youtubeId) { playerRef.current?.playVideo(); } } setIsPlaying(!isPlaying); }; const handleNextSong = () => { if (!currentSong) return; const currentIndex = songs.indexOf(currentSong); const nextIndex = (currentIndex + 1) % songs.length; const nextSong = songs[nextIndex]; setIsPlaying(false); setCurrentSong(nextSong); }; const handlePreviousSong = () => { if (!currentSong) return; const currentIndex = songs.indexOf(currentSong); const previousIndex = (currentIndex - 1 + songs.length) % songs.length; const previousSong = songs[previousIndex]; setIsPlaying(false); setCurrentSong(previousSong); }; const onPlayerReady: YouTubeProps["onReady"] = (event) => { playerRef.current = event.target; setDuration(event.target.getDuration()); event.target.setVolume(volume); if (isPlaying) { event.target.playVideo(); } }; const onPlayerEnd: YouTubeProps["onEnd"] = () => { handleNextSong(); }; const onPlayerStateChange: YouTubeProps["onStateChange"] = (event) => { if (event.data === window.YT.PlayerState.ENDED) { handleNextSong(); } }; const opts: YouTubeProps["opts"] = { height: "0", width: "0", playerVars: { autoplay: 0, controls: 0, disablekb: 1, fs: 0, modestbranding: 1, rel: 0, }, }; 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 handleProgressChange = (e: React.ChangeEvent<HTMLInputElement>) => { const newTime = Number(e.target.value); if (playerRef.current) { playerRef.current.seekTo(newTime, true); setCurrentTime(newTime); } }; const handleVolumeChange = (e: React.ChangeEvent<HTMLInputElement>) => { const newVolume = Number(e.target.value); setVolume(newVolume); if (playerRef.current) { playerRef.current.setVolume(newVolume); } }; const toggleMute = () => { if (playerRef.current) { if (playerRef.current.isMuted()) { playerRef.current.unMute(); setVolume(playerRef.current.getVolume()); } else { playerRef.current.mute(); setVolume(0); } } }; 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); } }; 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} /> )} {/* 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); } }} > {/* 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.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) { playerRef.current.seekTo(newTime, true); setCurrentTime(newTime); } }} 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.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;Explicación de las Modificaciones:
-
Estado
isFullScreenPlayer:- Se utiliza para determinar si el panel de reproducción completo está abierto.
-
Función
toggleFullScreenPlayer:- Al abrir el panel de reproducción completo, se establece
isFullScreenPlayerentruey se oculta la barra de navegación (setShowNavbar(false)). - Al cerrar el panel, se restablece
isFullScreenPlayery se muestra la barra de navegación nuevamente (setShowNavbar(true)).
- Al abrir el panel de reproducción completo, se establece
-
Ocultar la barra de navegación y el contenido principal al estar en pantalla completa:
- En el
useEffectque maneja el scroll, se ha añadido una condición para no mostrar la barra de navegación cuandoisFullScreenPlayerestrue. - El contenido principal (
divque contiene la lista de reproducción) se oculta cuandoisFullScreenPlayerestruepara evitar cualquier superposición o conflicto de navegación.
- En el
-
Ocultar el footer de reproducción al abrir el panel completo:
- En la renderización del footer (
Now Playing Bar), se ha añadido una condición para que solo se muestre siisFullScreenPlayeresfalse.
- En la renderización del footer (
-
Asegurar que la lista de reproducción sea desplazable:
- Al ocultar el footer y la barra de navegación cuando el panel completo está activo, la lista de reproducción se vuelve completamente desplazable sin superposiciones de elementos.
- Se ha ajustado el
z-indexy las clases CSS para garantizar que el contenido principal permanezca accesible y desplazable.
-
Ajustes UI menores:
- Se aseguraron las clases de Tailwind para mantener una apariencia consistente y responsiva.
- Se añadieron comentarios para facilitar la comprensión de los cambios realizados.
Consideraciones Adicionales:
- Accesibilidad: Asegúrate de que todos los elementos interactivos tengan atributos
aria-labeladecuados para mejorar la accesibilidad. - Optimización de Rendimiento: Si el panel full-screen incluye elementos pesados, considera optimizar las imágenes y otros recursos para mejorar el rendimiento en dispositivos móviles.
- Pruebas en Dispositivos Reales: Es recomendable probar la aplicación en diferentes dispositivos y tamaños de pantalla para asegurar que todos los cambios funcionen correctamente.
Conclusión
Con estos cambios, al abrir el panel de reproducción completo en dispositivos móviles, la barra de navegación y el footer de reproducción se ocultarán, proporcionando una experiencia de usuario más enfocada y libre de distracciones. Además, la lista de reproducción será completamente desplazable sin causar errores de navegación, asegurando una interacción fluida tanto en PC como en dispositivos móviles.