import { useEffect, useState } from "react"; import { useNavigate } from "react-router-dom"; import { toast } from "react-toastify"; import axiosInstance, { baseURL } from "../api/axiosInstance"; import { useAuth } from "../context/authContext"; import { usePlayer } from "../context/playerContext"; import type { BasicSong, SidebarProps } from "../utils/types"; import { toEmbedUrl } from "../utils/utils"; import { useCreatedPlaylists } from "../context/playlistContext"; import CreatePlaylistModal from "./playlist/CreatePlaylistModal"; import { getErrorMessage } from "../utils/error"; const Sidebar = ({ isOpen, onClose }: SidebarProps) => { const { user } = useAuth(); const { createdPlaylists, isLoading: playlistsLoading, refreshPlaylists, } = useCreatedPlaylists(); const navigate = useNavigate(); const { play, currentSong } = usePlayer(); const [recentlyListened, setRecentlyListened] = useState([]); const [songsLoading, setSongsLoading] = useState(false); const [isModalOpen, setIsModalOpen] = useState(false); useEffect(() => { const fetchData = async () => { setSongsLoading(true); try { const data = await axiosInstance.get("/songs/recent"); setRecentlyListened(data.data); } catch (error) { toast.error(getErrorMessage(error)); } finally { setSongsLoading(false); } }; if (user) { fetchData(); } else { setRecentlyListened([]); setSongsLoading(false); } }, [user]); const isLoading = songsLoading || playlistsLoading; return ( <>
{/* Sidebar Header */}

Library

{/* Loading State */} {isLoading ? (
) : ( <> {/* Recently Listened */}

Recently Played

{recentlyListened.map((song) => (
{song.title} { (e.target as HTMLImageElement).src = "/favicon.png"; }} />

navigate(`/songs/${song.id}`)} className="text-sm font-medium text-white truncate hover:underline cursor-pointer" > {song.title}

{ e.stopPropagation(); if (song.artistUsername) { navigate(`/users/${song.artistUsername}`); } }} className={`truncate ${ song.artistUsername ? "hover:underline cursor-pointer hover:text-white" : "" }`} > {song.artist} {song.album && ( <> { e.stopPropagation(); if (song.albumId) { navigate( `/collection/album/${song.albumId}`, ); } }} className={`truncate ${ song.albumId ? "hover:underline cursor-pointer hover:text-white" : "" }`} > {song.album} )}
{song.link && ( )}
))}
{/* Playlists */}

Your Playlists

{createdPlaylists?.map((playlist) => (
{ navigate(`/collection/playlist/${playlist.id}`); }} className="flex items-center justify-between p-3 rounded-lg hover:bg-white/5 cursor-pointer transition-colors" >

{playlist.name}

{playlist.songCount} songs

))} {/* Create Playlist Button */}
)}
setIsModalOpen(false)} onSuccess={() => refreshPlaylists(false)} songId={null} /> ); }; export default Sidebar;