import { useEffect, useState } from "react"; import { useNavigate } from "react-router-dom"; import axiosInstance from "../api/axiosInstance"; import { useAuth } from "../context/authContext"; import { usePlayer } from "../context/playerContext"; import type { BasicPlaylist, BasicSong, SidebarProps } from "../utils/types"; const toEmbedUrl = (url: string): string => { try { const parsed = new URL(url); if ( (parsed.hostname === "www.youtube.com" || parsed.hostname === "youtube.com") && parsed.searchParams.has("v") ) { return `https://www.youtube.com/embed/${parsed.searchParams.get("v")}`; } if (parsed.hostname === "youtu.be") { return `https://www.youtube.com/embed${parsed.pathname}`; } return url; } catch { return url; } }; const Sidebar = ({ isOpen, onClose }: SidebarProps) => { const { user } = useAuth(); const navigate = useNavigate(); const { play, currentSong } = usePlayer(); const [recentlyListened, setRecentlyListened] = useState([]); const [playlists, setPlaylists] = useState([]); useEffect(() => { const fetchData = async () => { try { const data = await axiosInstance.get("/songs/recent"); setRecentlyListened(data.data); } catch (error) { console.error("Error fetching recently listened songs:", error); // todo: show toast } try { const data = await axiosInstance.get("/playlists/user"); setPlaylists(data.data); } catch (error) { console.error("Error fetching playlists:", error); // todo: show toast } }; if (user) { fetchData(); } else { setRecentlyListened([]); setPlaylists([]); } }, [user]); return (
{/* Sidebar Header */}

Library

{/* Recently Listened */}

Recently Played

{recentlyListened.map((song) => (
navigate(`/songs/${song.id}`)} className="flex items-center gap-3 p-2 rounded-lg hover:bg-white/5 cursor-pointer transition-colors group relative" > {song.title} { (e.target as HTMLImageElement).src = "/favicon.png"; }} />

{song.title}

{song.artist}

{song.link && ( )}
))}
{/* Playlists */}

Your Playlists

{playlists.map((playlist) => (

{playlist.name}

{playlist.songCount} songs

))}
); }; export default Sidebar;