mira, tengo esto: import React, { useState, useEffect, useRef, useMemo, useCallback, }…
- User
mira, tengo esto:
import React, { useState, useEffect, useRef, useMemo, useCallback, } from "react"; import YouTube, { YouTubeProps, YouTubePlayer } from "react-youtube"; import Navbar from "./components/Navbar"; import PlaylistInfo from "./components/PlaylistInfo"; import PlaybackControls from "./components/PlaybackControls"; import SongList from "./components/SongList"; import NowPlayingBar from "./components/NowPlayingBar"; import FullScreenPlayer from "./components/FullScreenPlayer"; import PlaybackBar from "./components/PlaybackBar"; import { songs as initialSongs, Song } from "./songs";
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(false); const [isMobile, setIsMobile] = useState(window.innerWidth < 1024); const [showNavbar, setShowNavbar] = useState(true); const [isFullScreenPlayer, setIsFullScreenPlayer] = useState(false);
const playerRef = useRef<YouTubePlayer | null>(null);
const [currentTime, setCurrentTime] = useState(0); const [duration, setDuration] = useState(0);
const [volume, setVolume] = useState(100);
const lastScrollY = useRef(0);
const [searchValue, setSearchValue] = useState("");
// Estado de Paginación const [currentPage, setCurrentPage] = useState(1); const songsPerPage = 100; // Puedes ajustar este valor
const handleSearchChange = useCallback( (e: React.ChangeEvent) => { setSearchValue(e.target.value); setCurrentPage(1); // Reiniciar a la primera página al cambiar la búsqueda }, [] );
const handleClearSearch = useCallback(() => { setSearchValue(""); setCurrentPage(1); // Reiniciar a la primera página al limpiar la búsqueda }, []);
const [sortOrder, setSortOrder] = useState<"asc" | "desc" | null>(null);
const sortAscending = useCallback(() => { setSortOrder("asc"); }, []);
const sortDescending = useCallback(() => { setSortOrder("desc"); }, []);
const [isShuffle, setIsShuffle] = useState(false);
// Memoiza las canciones filtradas const filteredSongs = useMemo(() => { return searchValue ? initialSongs.filter( (song) => song.title.toLowerCase().includes(searchValue.toLowerCase()) || song.artist.toLowerCase().includes(searchValue.toLowerCase()) ) : initialSongs; }, [searchValue]);
// Memoiza las canciones ordenadas const sortedSongs = useMemo(() => { const sorted = [...filteredSongs]; if (sortOrder === "asc") { sorted.reverse(); } return sorted; }, [filteredSongs, sortOrder]);
// Cálculo de la duración total const totalDurationInSeconds = useMemo( () => sortedSongs.reduce((sum, song) => sum + (song.duration || 0), 0), [sortedSongs] ); const totalDuration = useMemo( () => formatTotalDuration(totalDurationInSeconds), [totalDurationInSeconds] );
// Información del playlist const playlist = useMemo( () => ({ name: "Time Free", description: "Relajao", owner: "Johan Morales", songsCount: sortedSongs.length, totalDuration: totalDuration, coverImage: "https://i.postimg.cc/y8KhsW1p/imagen-blessd.jpg", }), [sortedSongs.length, totalDuration] );
// Manejo del cambio de tamaño de la ventana useEffect(() => { const handleResize = () => { setIsMobile(window.innerWidth < 1024); };
window.addEventListener("resize", handleResize); return () => window.removeEventListener("resize", handleResize);}, []);
// Manejo del scroll para mostrar/ocultar la Navbar useEffect(() => { const handleScroll = () => { if (!isFullScreenPlayer) { if (window.scrollY > lastScrollY.current && window.scrollY > 100) { setShowNavbar(false); } else { setShowNavbar(true); } lastScrollY.current = window.scrollY; } };
window.addEventListener("scroll", handleScroll); return () => window.removeEventListener("scroll", handleScroll);}, [isFullScreenPlayer]);
const getCurrentIndex = useCallback((): number => { if (!currentSong?.youtubeId) return -1; return sortedSongs.findIndex( (song) => song.youtubeId === currentSong.youtubeId ); }, [currentSong, sortedSongs]);
// Cargar una nueva canción en el reproductor useEffect(() => { if (playerRef.current && currentSong?.youtubeId) { try { playerRef.current.loadVideoById(currentSong.youtubeId); setCurrentTime(0); setDuration(0); } catch (error) { console.error("Error al cargar el video:", error); } } }, [currentSong]);
// Controlar la reproducción/pausa del video 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 y la duración del video cada segundo useEffect(() => { let intervalId: number | null = null;
if (playerRef.current && isPlaying) { intervalId = window.setInterval(() => { if (playerRef.current) { const current = playerRef.current.getCurrentTime(); const dura = playerRef.current.getDuration(); setCurrentTime(current); setDuration(dura); } }, 1000); } return () => { if (intervalId !== null) { window.clearInterval(intervalId); } };}, [isPlaying]);
const handlePlayPause = useCallback(() => { 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); } } } }, [isPlaying, currentSong]);
const handleNextSong = useCallback(() => { if (!currentSong) return; let nextIndex: number;
if (isShuffle) { do { nextIndex = Math.floor(Math.random() * sortedSongs.length); } while (nextIndex === getCurrentIndex()); } else { const currentIndex = getCurrentIndex(); nextIndex = (currentIndex + 1) % sortedSongs.length; } const nextSong = sortedSongs[nextIndex]; setCurrentSong(nextSong); setIsPlaying(true);}, [currentSong, isShuffle, sortedSongs, getCurrentIndex]);
const handlePreviousSong = useCallback(() => { if (!currentSong) return; let previousIndex: number;
if (isShuffle) { do { previousIndex = Math.floor(Math.random() * sortedSongs.length); } while (previousIndex === getCurrentIndex()); } else { const currentIndex = getCurrentIndex(); previousIndex = (currentIndex - 1 + sortedSongs.length) % sortedSongs.length; } const previousSong = sortedSongs[previousIndex]; setCurrentSong(previousSong); setIsPlaying(true);}, [currentSong, isShuffle, sortedSongs, getCurrentIndex]);
const onPlayerReady: YouTubeProps["onReady"] = useCallback( (event: YT.PlayerEvent) => { 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); } } }, [isPlaying, volume]);
const onPlayerEnd: YouTubeProps["onEnd"] = useCallback(() => { handleNextSong(); }, [handleNextSong]);
const onPlayerError: YouTubeProps["onError"] = useCallback( (event: YT.OnErrorEvent) => { console.error("Error del reproductor de YouTube:", event.data); }, [] );
const onPlayerStateChange: YouTubeProps["onStateChange"] = useCallback( (event: YT.OnStateChangeEvent) => { if (window.YT && event.data === YT.PlayerState.ENDED) { handleNextSong(); } else if ( window.YT && (event.data === YT.PlayerState.CUED || event.data === YT.PlayerState.BUFFERING) && isPlaying ) { try { playerRef.current?.playVideo(); } catch (error) { console.error("Error intentando reproducir el video:", error); } } }, [handleNextSong, isPlaying] );
const opts: YouTubeProps["opts"] = useMemo( () => ({ height: "0", width: "0", playerVars: { autoplay: 0, controls: 0, disablekb: 1, fs: 0, modestbranding: 1, rel: 0, }, }), [] );
const handleProgressChange = useCallback( (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); } } }, [] );
const handleVolumeChange = useCallback( (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); } } }, [] );
const toggleMute = useCallback(() => { 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); } } }, []);
const toggleFullScreenPlayer = useCallback(() => { setIsFullScreenPlayer((prev) => !prev); if (!isFullScreenPlayer) { setShowNavbar(false); } else { setShowNavbar(true); } }, [isFullScreenPlayer]);
const ensurePlayback = useCallback(() => { 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); } } }, [isPlaying]);
useEffect(() => { if (currentSong && isPlaying) { const timeoutId = setTimeout(() => { ensurePlayback(); }, 1000);
return () => clearTimeout(timeoutId); }}, [currentSong, isPlaying, ensurePlayback]);
const handleSongSelect = useCallback((song: Song) => { setCurrentSong(song); setIsPlaying(true); }, []);
const handleShuffle = useCallback(() => { setIsShuffle((prev) => !prev); }, []);
const handleRepeat = useCallback(() => { if (currentSong) { setIsPlaying(false); setCurrentSong(currentSong); setIsPlaying(true); } }, [currentSong]);
// Manejo de paginación const indexOfLastSong = currentPage * songsPerPage; const indexOfFirstSong = indexOfLastSong - songsPerPage; const currentSongs = useMemo( () => sortedSongs.slice(indexOfFirstSong, indexOfLastSong), [sortedSongs, indexOfFirstSong, indexOfLastSong] );
const totalPages = useMemo( () => Math.ceil(sortedSongs.length / songsPerPage), [sortedSongs.length, songsPerPage] );
const handleNextPage = useCallback(() => { setCurrentPage((prev) => Math.min(prev + 1, totalPages)); }, [totalPages]);
const handlePrevPage = useCallback(() => { setCurrentPage((prev) => Math.max(prev - 1, 1)); }, []);
return ( {currentSong?.youtubeId && ( )}
{showNavbar && ( <Navbar searchValue={searchValue} onSearchChange={handleSearchChange} onClear={handleClearSearch} onSortAscending={sortAscending} onSortDescending={sortDescending} /> )} <div className={`pt-20 flex-1 overflow-y-auto bg-gradient-to-b from-red-900 to-gray-900 ${ isFullScreenPlayer ? "hidden" : "" } pb-24`} > <PlaylistInfo playlist={playlist} /> {currentSong && ( <PlaybackControls isPlaying={isPlaying} onPlayPause={handlePlayPause} onAddToQueue={() => { console.log("Agregar a la cola"); }} onMoreOptions={() => { console.log("Más opciones"); }} /> )} <SongList songs={currentSongs} currentSong={currentSong} onSongSelect={handleSongSelect} /> {/* Controles de Paginación */} <div className="flex justify-between items-center mt-4 px-6"> <button onClick={handlePrevPage} disabled={currentPage === 1} className={`px-4 py-2 bg-gray-700 text-white rounded ${ currentPage === 1 ? "opacity-50 cursor-not-allowed" : "hover:bg-gray-600" }`} > Anterior </button> <span className="text-sm text-gray-400"> Página {currentPage} de {totalPages} </span> <button onClick={handleNextPage} disabled={currentPage === totalPages} className={`px-4 py-2 bg-red-700 text-white rounded ${ currentPage === totalPages ? "opacity-50 cursor-not-allowed" : "hover:bg-gray-600" }`} > Siguiente </button> </div> </div> {isMobile && currentSong && !isFullScreenPlayer && ( <NowPlayingBar currentSong={currentSong} isPlaying={isPlaying} onPlayPause={(e) => { e.preventDefault(); handlePlayPause(); }} onToggleFullScreen={toggleFullScreenPlayer} /> )} {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} isShuffle={isShuffle} /> )} {!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} isShuffle={isShuffle} /> )} </div>); };
export default App;
pero el paginador lo quiero mas bonito, y ademas, que se cuadre bien cuando se està reproduciendo una cancion
- Assistant
¡Hola! Para mejorar la apariencia del paginador y asegurarte de que se alinee correctamente cuando se está reproduciendo una canción, puedes realizar las siguientes actualizaciones:
-
Mejorar el Estilo del Paginador:
- Utiliza iconos para los botones de "Anterior" y "Siguiente" para una apariencia más intuitiva.
- Añade transiciones y efectos de hover para una mejor interacción visual.
- Utiliza grupos de botones para mantener una consistencia en el diseño.
- Ajusta los colores y los estados de los botones (activo/inactivo) para que coincidan con el tema de tu aplicación.
-
Ajustar el Layout para Acomodar el Paginador:
- Asegúrate de que el paginador tenga suficiente padding al final para que no quede oculto por la barra de reproducción.
- Utiliza Flexbox o Grid para alinear correctamente los elementos dentro del paginador.
- Considera hacer el paginador responsive para que se vea bien en diferentes tamaños de pantalla.
A continuación, te proporciono un ejemplo actualizado del paginador utilizando Tailwind CSS. Este ejemplo incluye iconos mediante Heroicons, pero si prefieres no usar iconos, puedes omitir esa parte o usar imágenes SVG personalizadas.
1. Instalar Heroicons (Opcional)
Si decides usar iconos, instala
@heroicons/react:npm install @heroicons/react2. Actualizar el Paginador
Crea un componente para el Paginador (Opcional pero recomendado):
Crear un componente separado para el paginador puede ayudarte a mantener el código más limpio y reutilizable.
// components/Paginator.tsx import React from 'react'; import { ChevronLeftIcon, ChevronRightIcon } from '@heroicons/react/solid'; interface PaginatorProps { currentPage: number; totalPages: number; onPrev: () => void; onNext: () => void; } const Paginator: React.FC<PaginatorProps> = ({ currentPage, totalPages, onPrev, onNext }) => { return ( <div className="flex justify-between items-center mt-4 px-6"> <button onClick={onPrev} disabled={currentPage === 1} className={`flex items-center px-4 py-2 bg-gray-700 text-white rounded ${currentPage === 1 ? 'opacity-50 cursor-not-allowed' : 'hover:bg-gray-600'} transition duration-200 ease-in-out`} > <ChevronLeftIcon className="h-5 w-5 mr-2" /> Anterior </button> <span className="text-sm text-gray-400"> Página {currentPage} de {totalPages} </span> <button onClick={onNext} disabled={currentPage === totalPages} className={`flex items-center px-4 py-2 bg-gray-700 text-white rounded ${currentPage === totalPages ? 'opacity-50 cursor-not-allowed' : 'hover:bg-gray-600'} transition duration-200 ease-in-out`} > Siguiente <ChevronRightIcon className="h-5 w-5 ml-2" /> </button> </div> ); }; export default Paginator;Actualizar el Componente App:
Importa y utiliza el nuevo componente
Paginatoren tu componenteApp. Además, asegúrate de que el contenedor principal tenga suficiente padding para evitar superposiciones con la barra de reproducción.// App.tsx import React, { /* otros imports */ } from "react"; import YouTube, { YouTubeProps, YouTubePlayer } from "react-youtube"; import Navbar from "./components/Navbar"; import PlaylistInfo from "./components/PlaylistInfo"; import PlaybackControls from "./components/PlaybackControls"; import SongList from "./components/SongList"; import NowPlayingBar from "./components/NowPlayingBar"; import FullScreenPlayer from "./components/FullScreenPlayer"; import PlaybackBar from "./components/PlaybackBar"; import Paginator from "./components/Paginator"; // Importar el paginador import { songs as initialSongs, Song } from "./songs"; // ... rest of the imports const App: React.FC = () => { // ... tu estado y lógica return ( <div className="flex flex-col h-screen text-gray-300 bg-black"> {currentSong?.youtubeId && ( <YouTube videoId={currentSong.youtubeId} opts={opts} onReady={onPlayerReady} onEnd={onPlayerEnd} onStateChange={onPlayerStateChange} onError={onPlayerError} /> )} {showNavbar && ( <Navbar searchValue={searchValue} onSearchChange={handleSearchChange} onClear={handleClearSearch} onSortAscending={sortAscending} onSortDescending={sortDescending} /> )} <div className={`pt-20 flex-1 overflow-y-auto bg-gradient-to-b from-red-900 to-gray-900 ${ isFullScreenPlayer ? "hidden" : "" } pb-24`} > <PlaylistInfo playlist={playlist} /> {currentSong && ( <PlaybackControls isPlaying={isPlaying} onPlayPause={handlePlayPause} onAddToQueue={() => { console.log("Agregar a la cola"); }} onMoreOptions={() => { console.log("Más opciones"); }} /> )} <SongList songs={currentSongs} currentSong={currentSong} onSongSelect={handleSongSelect} /> {/* Controles de Paginación Mejorados */} <Paginator currentPage={currentPage} totalPages={totalPages} onPrev={handlePrevPage} onNext={handleNextPage} /> </div> {isMobile && currentSong && !isFullScreenPlayer && ( <NowPlayingBar currentSong={currentSong} isPlaying={isPlaying} onPlayPause={(e) => { e.preventDefault(); handlePlayPause(); }} onToggleFullScreen={toggleFullScreenPlayer} /> )} {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} isShuffle={isShuffle} /> )} {!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} isShuffle={isShuffle} /> )} </div> ); }; export default App;3. Ajustar el Estilo para Evitar Superposiciones
Asegúrate de que el contenedor principal tenga suficiente padding inferior para que el paginador y el contenido no queden ocultos detrás de la barra de reproducción. En tu código actual, ya tienes
pb-24en el contenedor principal, lo cual es bueno. Asegúrate de que este valor sea suficiente o ajústalo según sea necesario.4. Opcional: Mejorar la Responsividad del Paginador
Puedes hacer que el paginador se adapte mejor a diferentes tamaños de pantalla. Por ejemplo, en pantallas pequeñas, podrías querer centralizar los elementos o ajustar los tamaños de los botones.
// Dentro del componente Paginator <div className="flex flex-col sm:flex-row justify-between items-center mt-4 px-6 space-y-2 sm:space-y-0"> {/* ...resto del código */} </div>5. Personalizar Colores y Temas
Ajusta los colores de los botones y textos para que coincidan con el esquema de colores de tu aplicación. Por ejemplo, puedes cambiar
bg-gray-700a otro color comobg-red-700para resaltar más los botones.6. Implementar Indicadores de Carga (Opcional)
Para una mejor experiencia de usuario, puedes agregar indicadores de carga o deshabilitar los botones temporalmente mientras se carga una página.
<button onClick={onPrev} disabled={currentPage === 1 || isLoading} className={`flex items-center px-4 py-2 bg-gray-700 text-white rounded ${currentPage === 1 || isLoading ? 'opacity-50 cursor-not-allowed' : 'hover:bg-gray-600'} transition duration-200 ease-in-out`} > <ChevronLeftIcon className="h-5 w-5 mr-2" /> Anterior </button>7. Resultado Final
Con estos cambios, tu paginador no solo se verá más atractivo sino que también funcionará mejor dentro de tu diseño actual. Aquí te dejo una vista previa de cómo se verá el paginador mejorado:
<Paginator currentPage={currentPage} totalPages={totalPages} onPrev={handlePrevPage} onNext={handleNextPage} />[image: Ejemplo de Paginador] open
Recursos Adicionales
- Heroicons - Un conjunto gratuito de iconos SVG.
- Tailwind CSS Documentation - Para personalizar y explorar más clases de Tailwind.
Espero que estas sugerencias te ayuden a mejorar el paginador de tu aplicación. Si tienes alguna pregunta adicional o necesitas más ayuda con otros aspectos de tu código, no dudes en preguntar.
-