Commit c7c9043b authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Move Liked Songs into the Library tab as a real album-like entry

Favorites are a personal/library concept, not something that should live
only under the separate Playlists page. A "Liked Songs" card now appears
first in Library's own Albums grid (same shape as every other AlbumCard, a
heart tile standing in for cover art) whenever the caller has at least one
liked song - derived from the already-loaded library list's is_liked flags,
no extra request.

New /library/liked page is built to look and behave exactly like a real
album page (AlbumDetail) rather than the plainer list Playlists' own detail
view uses: big header tile, track count, Play button, SongRow list with
working hearts/swipe/add-to-playlist. Sourced from getLibrary() + is_liked
directly, not the playlist endpoints - nothing about playlist
membership/ordering is relevant here. Unliking a song removes it from the
list immediately, since every row is only present because it's liked.

Still backed by the same is_liked_playlist under the hood, so it still
appears in Playlists too - this is a second, more prominent entry point,
not a replacement.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 3254e7c0
...@@ -11,6 +11,7 @@ import { REMIX_ENABLED } from './config/flags' ...@@ -11,6 +11,7 @@ import { REMIX_ENABLED } from './config/flags'
const Home = lazy(() => import('./pages/Home').then((m) => ({ default: m.Home }))) const Home = lazy(() => import('./pages/Home').then((m) => ({ default: m.Home })))
const Library = lazy(() => import('./pages/Library').then((m) => ({ default: m.Library }))) const Library = lazy(() => import('./pages/Library').then((m) => ({ default: m.Library })))
const AlbumDetail = lazy(() => import('./pages/AlbumDetail').then((m) => ({ default: m.AlbumDetail }))) const AlbumDetail = lazy(() => import('./pages/AlbumDetail').then((m) => ({ default: m.AlbumDetail })))
const LikedSongs = lazy(() => import('./pages/LikedSongs').then((m) => ({ default: m.LikedSongs })))
const Playlists = lazy(() => import('./pages/Playlists').then((m) => ({ default: m.Playlists }))) const Playlists = lazy(() => import('./pages/Playlists').then((m) => ({ default: m.Playlists })))
const TelegramLink = lazy(() => import('./pages/TelegramLink').then((m) => ({ default: m.TelegramLink }))) const TelegramLink = lazy(() => import('./pages/TelegramLink').then((m) => ({ default: m.TelegramLink })))
const Upload = lazy(() => import('./pages/Upload').then((m) => ({ default: m.Upload }))) const Upload = lazy(() => import('./pages/Upload').then((m) => ({ default: m.Upload })))
...@@ -48,6 +49,7 @@ export function App() { ...@@ -48,6 +49,7 @@ export function App() {
<Route path="/home" element={protect(<Home />)} /> <Route path="/home" element={protect(<Home />)} />
<Route path="/library" element={protect(<Library />)} /> <Route path="/library" element={protect(<Library />)} />
<Route path="/library/album" element={protect(<AlbumDetail />)} /> <Route path="/library/album" element={protect(<AlbumDetail />)} />
<Route path="/library/liked" element={protect(<LikedSongs />)} />
<Route path="/playlists" element={protect(<Playlists />)} /> <Route path="/playlists" element={protect(<Playlists />)} />
<Route path="/telegram-link" element={protect(<TelegramLink />)} /> <Route path="/telegram-link" element={protect(<TelegramLink />)} />
<Route path="/upload" element={protect(<Upload />)} /> <Route path="/upload" element={protect(<Upload />)} />
......
...@@ -50,6 +50,7 @@ function renderLibrary() { ...@@ -50,6 +50,7 @@ function renderLibrary() {
<Routes> <Routes>
<Route path="/" element={<Library />} /> <Route path="/" element={<Library />} />
<Route path="/library/album" element={<AlbumRouteProbe />} /> <Route path="/library/album" element={<AlbumRouteProbe />} />
<Route path="/library/liked" element={<p>Liked Songs route</p>} />
</Routes> </Routes>
</PlayerProvider> </PlayerProvider>
</AuthProvider> </AuthProvider>
...@@ -123,6 +124,37 @@ describe('Library', () => { ...@@ -123,6 +124,37 @@ describe('Library', () => {
expect(await screen.findByText('Album route: Astronaut by Duran Duran')).toBeInTheDocument() expect(await screen.findByText('Album route: Astronaut by Duran Duran')).toBeInTheDocument()
}) })
it('shows a Liked Songs card in the Albums grid when the caller has at least one liked song', async () => {
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({
status: 'success',
library: [{ ...SONG, album: null, is_liked: true }],
})
renderLibrary()
expect(await screen.findByRole('heading', { name: 'Albums' })).toBeInTheDocument()
expect(screen.getByText('Liked Songs')).toBeInTheDocument()
expect(screen.getByText('1 song')).toBeInTheDocument()
})
it('does not show a Liked Songs card when the caller has no liked songs', async () => {
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [{ ...SONG, album: null }] })
renderLibrary()
await screen.findByText('Invisible')
expect(screen.queryByText('Liked Songs')).not.toBeInTheDocument()
})
it('navigates to the Liked Songs page when its card is tapped', async () => {
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [{ ...SONG, is_liked: true }] })
renderLibrary()
await userEvent.click(await screen.findByText('Liked Songs'))
expect(await screen.findByText('Liked Songs route')).toBeInTheDocument()
})
it('shows a load error using the ApiError message', async () => { it('shows a load error using the ApiError message', async () => {
vi.spyOn(libraryApi, 'getLibrary').mockRejectedValue(new ApiError(500, 'Server exploded', null)) vi.spyOn(libraryApi, 'getLibrary').mockRejectedValue(new ApiError(500, 'Server exploded', null))
......
import { useEffect, useMemo, useState } from 'react' import { useEffect, useMemo, useState } from 'react'
import { Globe2, Music2, Search } from 'lucide-react' import { Globe2, Heart, Music2, Search } from 'lucide-react'
import { useNavigate } from 'react-router-dom' import { useNavigate } from 'react-router-dom'
import { import {
deleteLibrarySong, deleteLibrarySong,
...@@ -71,6 +71,30 @@ function AlbumCard({ album, onOpen }: { album: AlbumMatch; onOpen: () => void }) ...@@ -71,6 +71,30 @@ function AlbumCard({ album, onOpen }: { album: AlbumMatch; onOpen: () => void })
) )
} }
/** Shown first in the Albums grid, same card shape as AlbumCard (per explicit direction: liked
* songs should look and behave like any other album, not live off in the separate Playlists
* page) - a heart tile stands in for cover art since this isn't a single real album. Only
* rendered when the caller actually has at least one liked song, same as every other section
* on this page. */
function LikedSongsCard({ count, onOpen }: { count: number; onOpen: () => void }) {
return (
<button
onClick={onOpen}
className="flex min-w-0 flex-col gap-2 rounded-xl border border-transparent p-3 text-left transition-colors hover:border-outline-variant hover:bg-surface-container focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"
>
<div className="flex aspect-square w-full items-center justify-center rounded-lg bg-primary/15 text-primary">
<Heart size={28} strokeWidth={1.5} fill="currentColor" />
</div>
<div className="min-w-0">
<p className="truncate text-sm font-medium text-on-surface">Liked Songs</p>
<p className="truncate text-xs text-on-surface-variant">
{count} song{count === 1 ? '' : 's'}
</p>
</div>
</button>
)
}
type SearchScope = 'mine' | 'shared' type SearchScope = 'mine' | 'shared'
export function Library() { export function Library() {
...@@ -92,6 +116,7 @@ export function Library() { ...@@ -92,6 +116,7 @@ export function Library() {
const [searching, setSearching] = useState(false) const [searching, setSearching] = useState(false)
const albums = useMemo(() => groupIntoAlbums(songs), [songs]) const albums = useMemo(() => groupIntoAlbums(songs), [songs])
const likedCount = useMemo(() => songs.filter((s) => s.is_liked).length, [songs])
useEffect(() => { useEffect(() => {
getLibrary() getLibrary()
...@@ -312,10 +337,11 @@ export function Library() { ...@@ -312,10 +337,11 @@ export function Library() {
</> </>
) : ( ) : (
<> <>
{albums.length > 0 && ( {(albums.length > 0 || likedCount > 0) && (
<div className="mb-8"> <div className="mb-8">
<h2 className="mb-3 text-xs font-semibold uppercase tracking-[0.1em] text-primary">Albums</h2> <h2 className="mb-3 text-xs font-semibold uppercase tracking-[0.1em] text-primary">Albums</h2>
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5"> <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5">
{likedCount > 0 && <LikedSongsCard count={likedCount} onOpen={() => navigate('/library/liked')} />}
{albums.map((album) => ( {albums.map((album) => (
<AlbumCard key={`${album.album}::${album.artist}`} album={album} onOpen={() => navigate(albumHref(album))} /> <AlbumCard key={`${album.album}::${album.artist}`} album={album} onOpen={() => navigate(albumHref(album))} />
))} ))}
......
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter } from 'react-router-dom'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { LikedSongs } from './LikedSongs'
import { AuthProvider } from '../context/AuthContext'
import { PlayerProvider } from '../context/PlayerContext'
import { ApiError } from '../api/client'
import * as libraryApi from '../api/library'
import * as streamApi from '../api/stream'
const LIKED_SONG = {
id: 1,
user_id: 1,
title: 'Invisible',
artist: 'Duran Duran',
album: 'Astronaut',
genre: 'Pop',
coverart: null,
lyrics: null,
file_path: '/x.mp3',
added_at: '2026-01-01T00:00:00Z',
is_liked: true,
}
const LIKED_SONG_2 = { ...LIKED_SONG, id: 2, title: 'Rio', album: 'Rio' }
const UNLIKED_SONG = { ...LIKED_SONG, id: 3, title: 'Hungry Like the Wolf', is_liked: false }
// Fires the full pointer drag sequence useSwipeAction listens for, targeting a descendant
// (e.g. the row's Play button) since the handlers live on an ancestor and pointer events
// bubble the same way in jsdom as in a real browser.
function swipe(target: HTMLElement, fromX: number, toX: number) {
fireEvent.pointerDown(target, { clientX: fromX, pointerId: 1 })
fireEvent.pointerMove(target, { clientX: toX, pointerId: 1 })
fireEvent.pointerUp(target, { clientX: toX, pointerId: 1 })
}
function renderLikedSongs() {
return render(
<MemoryRouter>
<AuthProvider>
<PlayerProvider>
<LikedSongs />
</PlayerProvider>
</AuthProvider>
</MemoryRouter>,
)
}
describe('LikedSongs', () => {
beforeEach(() => {
vi.stubEnv('VITE_DEV_ACCESS_TOKEN', '')
vi.stubEnv('VITE_DEV_REFRESH_TOKEN', '')
})
afterEach(() => {
vi.unstubAllEnvs()
vi.restoreAllMocks()
})
it('shows the empty state when the caller has no liked songs', async () => {
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [UNLIKED_SONG] })
renderLikedSongs()
expect(await screen.findByText(/No liked songs yet/)).toBeInTheDocument()
})
it('shows only the liked songs from the full library, not every song', async () => {
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [LIKED_SONG, UNLIKED_SONG] })
renderLikedSongs()
expect(await screen.findByText('Invisible')).toBeInTheDocument()
expect(screen.queryByText('Hungry Like the Wolf')).not.toBeInTheDocument()
expect(screen.getByText('1 song')).toBeInTheDocument()
})
it('shows a load error using the ApiError message', async () => {
vi.spyOn(libraryApi, 'getLibrary').mockRejectedValue(new ApiError(500, 'Server exploded', null))
renderLikedSongs()
expect(await screen.findByText('Server exploded')).toBeInTheDocument()
})
it('plays the whole liked list in order when Play is clicked', async () => {
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [LIKED_SONG, LIKED_SONG_2] })
const fetchStreamUrl = vi.spyOn(streamApi, 'fetchStreamUrl').mockResolvedValue('blob:fake-url')
renderLikedSongs()
// Two "Play" buttons exist (the playlist header's own, plus each SongRow's) - the header's
// is first in DOM order.
const [playlistPlayButton] = await screen.findAllByRole('button', { name: 'Play' })
await userEvent.click(playlistPlayButton)
await waitFor(() => expect(fetchStreamUrl).toHaveBeenCalledWith(LIKED_SONG.id))
})
it('unliking a song removes it from the list immediately', async () => {
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [LIKED_SONG, LIKED_SONG_2] })
const unfavoriteSong = vi.spyOn(libraryApi, 'unfavoriteSong').mockResolvedValue({ status: 'success', is_liked: false })
renderLikedSongs()
await screen.findByText('Invisible')
await userEvent.click(screen.getByRole('button', { name: 'Unlike Invisible' }))
await waitFor(() => expect(screen.queryByText('Invisible')).not.toBeInTheDocument())
expect(screen.getByText('Rio')).toBeInTheDocument()
expect(unfavoriteSong).toHaveBeenCalledWith(LIKED_SONG.id)
})
it('re-adds the song if unliking fails', async () => {
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [LIKED_SONG] })
vi.spyOn(libraryApi, 'unfavoriteSong').mockRejectedValue(new ApiError(500, 'Nope', null))
renderLikedSongs()
await screen.findByText('Invisible')
await userEvent.click(screen.getByRole('button', { name: 'Unlike Invisible' }))
await waitFor(() => expect(screen.getByText('Invisible')).toBeInTheDocument())
})
it('deletes a song and removes it from the list', async () => {
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [LIKED_SONG] })
vi.spyOn(libraryApi, 'deleteLibrarySong').mockResolvedValue({ status: 'success' })
vi.spyOn(window, 'confirm').mockReturnValue(true)
renderLikedSongs()
const row = (await screen.findByText('Invisible')).closest('li')!
swipe(within(row).getByRole('button', { name: 'Play' }), 0, -200)
await waitFor(() => expect(screen.queryByText('Invisible')).not.toBeInTheDocument())
})
})
import { useEffect, useState } from 'react'
import { Heart, Pause, Play } from 'lucide-react'
import { deleteLibrarySong, getLibrary, unfavoriteSong, type LibrarySong } from '../api/library'
import { ApiError } from '../api/client'
import { Layout } from '../components/Layout'
import { AddToPlaylistModal } from '../components/AddToPlaylistModal'
import { SongRow, toPlayable } from '../components/SongRow'
import { SkeletonRow } from '../components/ui/Skeleton'
import { EmptyState } from '../components/ui/EmptyState'
import { usePlayer } from '../context/PlayerContext'
/** The caller's liked songs, presented like any other album page (AlbumDetail) rather than the
* plainer Playlists detail list - it's reached from a card in Library's own Albums grid, not
* from the Playlists page, even though it's still backed by the same is_liked_playlist under
* the hood. Sourced directly from getLibrary() + is_liked (same data Library.tsx itself
* already uses), not the playlist endpoints - this is just "my songs, filtered to liked",
* nothing about playlist membership/ordering is relevant here. */
export function LikedSongs() {
const [songs, setSongs] = useState<LibrarySong[]>([])
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const [addingSong, setAddingSong] = useState<LibrarySong | null>(null)
const [deleteError, setDeleteError] = useState<string | null>(null)
const { currentSong, isPlaying, isLoading: streamLoading, toggle } = usePlayer()
useEffect(() => {
getLibrary()
.then((res) => setSongs(res.library.filter((s) => s.is_liked)))
.catch((err) => setError(err instanceof ApiError ? err.message : 'Failed to load liked songs'))
.finally(() => setLoading(false))
}, [])
// Same reasoning as AlbumDetail's own handleDelete - owns the confirm step since it also owns
// the list state that needs updating after.
async function handleDelete(song: LibrarySong) {
if (!window.confirm(`Delete "${song.title}"? This can't be undone.`)) return
setDeleteError(null)
try {
await deleteLibrarySong(song.id)
setSongs((prev) => prev.filter((s) => s.id !== song.id))
} catch (err) {
setDeleteError(err instanceof ApiError ? err.message : `Could not delete "${song.title}"`)
}
}
// Unlike AlbumDetail's handleToggleFavorite (which just flips is_liked in place - album
// membership doesn't depend on it), every row on this page is only here *because* it's
// liked - toggling always means unliking, which has to remove the row from view immediately,
// not just flip a flag nothing here reads anymore.
function handleToggleFavorite(song: LibrarySong) {
setSongs((prev) => prev.filter((s) => s.id !== song.id))
unfavoriteSong(song.id).catch(() => {
setSongs((prev) => (prev.some((s) => s.id === song.id) ? prev : [...prev, song]))
setDeleteError(`Could not unlike "${song.title}"`)
})
}
const isPlaylistCurrent = songs.some((s) => s.id === currentSong?.id)
return (
<Layout title="Liked Songs">
{loading && (
<div className="space-y-1">
<SkeletonRow />
<SkeletonRow />
<SkeletonRow />
</div>
)}
{error && <p className="text-sm text-error">{error}</p>}
{deleteError && <p className="mb-2 text-sm text-error">{deleteError}</p>}
{!loading && !error && songs.length === 0 && (
<EmptyState icon={Heart} message="No liked songs yet - tap the heart on any song to add it here." />
)}
{!loading && !error && songs.length > 0 && (
<div className="animate-content-enter">
<div className="mb-6 flex flex-col items-center gap-4 text-center sm:flex-row sm:items-end sm:text-left">
<div className="flex h-40 w-40 shrink-0 items-center justify-center rounded-2xl bg-primary/15 text-primary shadow-lg shadow-black/30">
<Heart size={40} strokeWidth={1.25} fill="currentColor" />
</div>
<div className="min-w-0">
<p className="text-xs font-semibold uppercase tracking-[0.1em] text-primary">Playlist</p>
<p className="mt-1 text-sm text-on-surface-variant">
{songs.length} song{songs.length === 1 ? '' : 's'}
</p>
<button
onClick={() => toggle(toPlayable(songs[0]), songs.map(toPlayable))}
disabled={isPlaylistCurrent && streamLoading}
aria-label={isPlaylistCurrent && isPlaying ? 'Pause' : 'Play'}
className="mt-4 flex items-center gap-2 rounded-full bg-primary px-5 py-2.5 text-sm font-semibold text-on-primary transition-transform duration-150 ease-out active:scale-95 disabled:opacity-50"
>
{isPlaylistCurrent && streamLoading ? (
<span className="h-4 w-4 animate-spin rounded-full border-2 border-on-primary/30 border-t-on-primary" />
) : isPlaylistCurrent && isPlaying ? (
<Pause size={16} strokeWidth={2} fill="currentColor" />
) : (
<Play size={16} strokeWidth={2} fill="currentColor" />
)}
{isPlaylistCurrent && isPlaying ? 'Pause' : 'Play'}
</button>
</div>
</div>
<ul className="space-y-1">
{songs.map((song) => (
<SongRow
key={song.id}
song={song}
queue={songs}
onAddToPlaylist={setAddingSong}
onDelete={handleDelete}
onToggleFavorite={handleToggleFavorite}
/>
))}
</ul>
</div>
)}
{addingSong && <AddToPlaylistModal song={addingSong} onClose={() => setAddingSong(null)} />}
</Layout>
)
}
...@@ -233,6 +233,7 @@ const FRONTEND_DONE: DoneGroup[] = [ ...@@ -233,6 +233,7 @@ const FRONTEND_DONE: DoneGroup[] = [
'Upload accepts multiple files at once (2026-09-01): each selected file gets its own queued row (removable before upload) and its own progress/result/error state, uploaded sequentially through the same one-file-at-a-time endpoint rather than all at once - the identify/tag pipeline per file is already the heavy part, so nothing would be gained by racing several through it in parallel', 'Upload accepts multiple files at once (2026-09-01): each selected file gets its own queued row (removable before upload) and its own progress/result/error state, uploaded sequentially through the same one-file-at-a-time endpoint rather than all at once - the identify/tag pipeline per file is already the heavy part, so nothing would be gained by racing several through it in parallel',
'Search the shared library from the Library page (2026-09-06), not a separate tab and not folded into Discovery - a deliberate call, since typing a search is the same kind of action as the existing owner-scoped search (just widened in scope), while Discovery\'s own mental model is ambient/mic-driven identification, a genuinely different action. A "My Library" / "Shared" scope toggle appears only while actively searching; switching to Shared re-runs the same query against every user\'s library instead of just the caller\'s. Shared results (SharedSongRow, visually similar to the normal SongRow but with no swipe actions - queue/delete both assume an id the caller already owns) claim-on-tap: playing or adding one to a playlist first calls /library/shared/claim to get a real owned copy, then acts on that - the same "get your own copy, then use it" flow already established for Discovery hits.', 'Search the shared library from the Library page (2026-09-06), not a separate tab and not folded into Discovery - a deliberate call, since typing a search is the same kind of action as the existing owner-scoped search (just widened in scope), while Discovery\'s own mental model is ambient/mic-driven identification, a genuinely different action. A "My Library" / "Shared" scope toggle appears only while actively searching; switching to Shared re-runs the same query against every user\'s library instead of just the caller\'s. Shared results (SharedSongRow, visually similar to the normal SongRow but with no swipe actions - queue/delete both assume an id the caller already owns) claim-on-tap: playing or adding one to a playlist first calls /library/shared/claim to get a real owned copy, then acts on that - the same "get your own copy, then use it" flow already established for Discovery hits.',
'Favorite heart button (2026-10-06) on every song row (Library, search results, album detail), optimistic (flips immediately, reverts only if the request fails - same shape as the existing delete error handling). The caller\'s Liked Songs playlist (once it exists) sorts first on the Playlists page and renders with a filled heart icon instead of the generic playlist icon.', 'Favorite heart button (2026-10-06) on every song row (Library, search results, album detail), optimistic (flips immediately, reverts only if the request fails - same shape as the existing delete error handling). The caller\'s Liked Songs playlist (once it exists) sorts first on the Playlists page and renders with a filled heart icon instead of the generic playlist icon.',
'Liked Songs moved into the Library tab itself (2026-10-07), per explicit direction: favorites are a personal/library concept, not something that should live only under the separate Playlists page. A "Liked Songs" card now appears first in Library\'s own Albums grid (same AlbumCard shape, a heart tile standing in for cover art) whenever the caller has at least one liked song - derived client-side from the already-loaded library list\'s `is_liked` flags, no extra request. Tapping it opens a new /library/liked page built to look and behave exactly like a real AlbumDetail page (big header tile, track count, Play button, SongRow list with working hearts/swipe/add-to-playlist) rather than the plainer list Playlists\' own detail view uses - sourced from getLibrary() + is_liked, not the playlist endpoints, since nothing about playlist membership/ordering is actually relevant here. Unliking a song here removes it from the list immediately (every row is only present *because* it\'s liked, unlike AlbumDetail\'s own toggle which just flips the flag in place). Still backed by the same is_liked_playlist under the hood, so it also still appears in Playlists - this is a second, more prominent entry point, not a replacement.',
], ],
}, },
{ {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment