Commit 23de29b2 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Add a global Home landing page, favorite hearts, and fix two mobile overflow bugs

Home replaces Library as the default post-login/catch-all destination: newly
added songs app-wide, new albums, and lightweight suggestions, backed by the
new GET /home/feed. Songs the caller already owns play directly; everyone
else's go through the same claim-then-play flow Library's shared search
already uses (useHomeSongPlayback, shared between the card and row
components). AuthContext now also exposes the caller's own userId, needed to
tell the two cases apart.

Favorite heart button on every song row, optimistic with revert-on-failure;
the Liked Songs playlist sorts first and gets a filled-heart icon once it
exists.

Mobile sweep (live, Playwright, phone viewport) found and fixed two real
bugs: the hover-only play overlay was invisible on touch devices except for
the currently-playing track, and Social's 4-pill tab row pushed the whole
page wider than the viewport on a phone instead of wrapping or scrolling.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent e2fa0f05
......@@ -8,6 +8,7 @@ import { REMIX_ENABLED } from './config/flags'
// route could render, including the very first one someone hits (Login or Library). Splitting
// per-route means the browser only fetches the JS the current page actually needs; navigating
// to a route not visited yet fetches its chunk on demand (and caches it for next time).
const Home = lazy(() => import('./pages/Home').then((m) => ({ default: m.Home })))
const Library = lazy(() => import('./pages/Library').then((m) => ({ default: m.Library })))
const AlbumDetail = lazy(() => import('./pages/AlbumDetail').then((m) => ({ default: m.AlbumDetail })))
const Playlists = lazy(() => import('./pages/Playlists').then((m) => ({ default: m.Playlists })))
......@@ -44,6 +45,7 @@ export function App() {
<Suspense fallback={<RouteFallback />}>
<Routes>
<Route path="/login" element={<Login />} />
<Route path="/home" element={protect(<Home />)} />
<Route path="/library" element={protect(<Library />)} />
<Route path="/library/album" element={protect(<AlbumDetail />)} />
<Route path="/playlists" element={protect(<Playlists />)} />
......@@ -88,7 +90,7 @@ export function App() {
</RequireRole>
}
/>
<Route path="*" element={<Navigate to="/library" replace />} />
<Route path="*" element={<Navigate to="/home" replace />} />
</Routes>
</Suspense>
)
......
import { apiFetch } from './client'
/** A song on the global Home feed - belongs to whichever user actually uploaded it (`user_id`/
* `username`), not necessarily the caller. No `is_liked`/`file_path` here (see library.ts's
* LibrarySong) - a viewer can't have liked a song they don't own yet, and a song owned by
* someone else can't be streamed directly until claimed (see useHomeSongPlayback). */
export interface HomeSong {
id: number
user_id: number
username: string | null
title: string
artist: string
album: string | null
genre: string | null
coverart: string | null
added_at: string
}
export interface HomeAlbum {
album: string
artist: string
user_id: number
coverart: string | null
track_count: number
songs: HomeSong[]
}
/** The Home page's feed - global across every user, unlike the per-user Library page.
* `suggestions` is explicitly a placeholder algorithm for now (see the backend's own comment),
* not a real recommendation engine yet. */
export function getHomeFeed() {
return apiFetch<{ status: string; latest_songs: HomeSong[]; new_albums: HomeAlbum[]; suggestions: HomeSong[] }>(
'/home/feed',
)
}
......@@ -11,12 +11,26 @@ export interface LibrarySong {
lyrics: string | null
file_path: string
added_at: string
/** Membership in the caller's own auto-created Liked Songs playlist - not a real column on
* the song, computed server-side on every endpoint that returns the caller's own songs. */
is_liked: boolean
}
export function getLibrary() {
return apiFetch<{ status: string; library: LibrarySong[] }>('/library')
}
/** Adds the song to the caller's Liked Songs playlist (creating it on first use - see the
* backend's _get_or_create_liked_playlist). Idempotent: calling twice is a no-op, not an error. */
export function favoriteSong(fileId: number) {
return apiFetch<{ status: string; is_liked: boolean }>(`/library/${fileId}/favorite`, { method: 'PUT' })
}
/** Removes the song from Liked Songs. Idempotent, including when it was never liked at all. */
export function unfavoriteSong(fileId: number) {
return apiFetch<{ status: string; is_liked: boolean }>(`/library/${fileId}/favorite`, { method: 'DELETE' })
}
export interface AlbumMatch {
album: string
artist: string
......@@ -97,6 +111,9 @@ export interface Playlist {
user_id: number
name: string
created_at: string
/** True only for the one auto-created-per-user Liked Songs playlist (see the backend's
* Playlist.is_liked_playlist) - GET /playlists always sorts it first when present. */
is_liked_playlist: boolean
}
export function getPlaylists() {
......
......@@ -16,10 +16,11 @@ const SONG = {
lyrics: null,
file_path: '/x.mp3',
added_at: '2026-01-01T00:00:00Z',
is_liked: false,
}
const PLAYLIST_A = { id: 10, user_id: 1, name: 'Chill', created_at: '2026-01-01T00:00:00Z' }
const PLAYLIST_B = { id: 11, user_id: 1, name: 'Party', created_at: '2026-01-02T00:00:00Z' }
const PLAYLIST_A = { id: 10, user_id: 1, name: 'Chill', created_at: '2026-01-01T00:00:00Z', is_liked_playlist: false }
const PLAYLIST_B = { id: 11, user_id: 1, name: 'Party', created_at: '2026-01-02T00:00:00Z', is_liked_playlist: false }
describe('AddToPlaylistModal', () => {
afterEach(() => {
......@@ -68,7 +69,7 @@ describe('AddToPlaylistModal', () => {
it('creates a new playlist and immediately adds the song to it', async () => {
vi.spyOn(libraryApi, 'getPlaylists').mockResolvedValue({ status: 'success', playlists: [] })
const newPlaylist = { id: 12, user_id: 1, name: 'Road Trip', created_at: '2026-01-03T00:00:00Z' }
const newPlaylist = { id: 12, user_id: 1, name: 'Road Trip', created_at: '2026-01-03T00:00:00Z', is_liked_playlist: false }
const createPlaylist = vi.spyOn(libraryApi, 'createPlaylist').mockResolvedValue({ status: 'success', playlist: newPlaylist })
const addToPlaylist = vi.spyOn(libraryApi, 'addToPlaylist').mockResolvedValue({ status: 'success', message: 'ok' })
......
import { useState } from 'react'
import { Music2 } from 'lucide-react'
import { useNavigate } from 'react-router-dom'
import type { HomeAlbum } from '../api/home'
import { useAuth } from '../context/AuthContext'
import { HomeSongRow } from './HomeSongRow'
/** A grid tile for the Home feed's "New albums" section. An album the caller owns navigates to
* the real album detail page (same as Library's AlbumCard); the backend's /library/album is
* scoped to the caller's own songs, so someone else's album has nowhere to navigate to - tapping
* it instead expands the tracks inline as claim-then-play rows (HomeSongRow), the same idea
* /library's shared search already uses for songs with no "detail page" of their own. */
export function HomeAlbumCard({
album,
onAddToPlaylist,
}: {
album: HomeAlbum
onAddToPlaylist: (song: { id: number; title: string }) => void
}) {
const navigate = useNavigate()
const { userId } = useAuth()
const [expanded, setExpanded] = useState(false)
const isOwnAlbum = album.user_id === userId
const uploaderName = album.songs[0]?.username ?? null
function handleOpen() {
if (isOwnAlbum) {
navigate(`/library/album?${new URLSearchParams({ album: album.album, artist: album.artist })}`)
} else {
setExpanded((prev) => !prev)
}
}
return (
<div className="flex min-w-0 flex-col gap-2">
<button
onClick={handleOpen}
aria-expanded={isOwnAlbum ? undefined : expanded}
className="flex min-w-0 flex-col gap-2 rounded-xl border border-transparent p-1 text-left transition-colors hover:border-outline-variant hover:bg-surface-container focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"
>
{album.coverart ? (
<img src={album.coverart} alt="" loading="lazy" decoding="async" className="aspect-square w-full rounded-lg object-cover" />
) : (
<div className="flex aspect-square w-full items-center justify-center rounded-lg bg-surface-container-high text-on-surface-variant">
<Music2 size={28} strokeWidth={1.5} />
</div>
)}
<div className="min-w-0 px-1">
<p className="truncate text-sm font-medium text-on-surface">{album.album}</p>
<p className="truncate text-xs text-on-surface-variant">
{album.artist} · {album.track_count} track{album.track_count === 1 ? '' : 's'}
{!isOwnAlbum && uploaderName ? ` · ${uploaderName}` : ''}
</p>
</div>
</button>
{expanded && (
<ul className="space-y-1 rounded-xl bg-surface-container/60 p-1">
{album.songs.map((song) => (
<HomeSongRow key={song.id} song={song} onAddToPlaylist={onAddToPlaylist} />
))}
</ul>
)}
</div>
)
}
import { Music2, Pause, Play } from 'lucide-react'
import type { HomeSong } from '../api/home'
import { useHomeSongPlayback } from '../hooks/useHomeSongPlayback'
/** A grid tile for the Home feed's "Newly added" section - same square-art-plus-caption shape
* as Library's AlbumCard, but every tile here plays on tap (own songs directly, someone
* else's via claim-then-play - see useHomeSongPlayback) rather than navigating anywhere. */
export function HomeSongCard({ song }: { song: HomeSong }) {
const { isCurrent, isPlaying, streamLoading, claiming, error, handlePlay } = useHomeSongPlayback(song)
const busy = claiming === 'play'
return (
<div className="flex min-w-0 flex-col gap-2">
<button
onClick={handlePlay}
disabled={busy}
aria-label={isCurrent && isPlaying ? `Pause ${song.title}` : `Play ${song.title}`}
className="group relative aspect-square w-full overflow-hidden rounded-xl border border-transparent transition-colors hover:border-outline-variant focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed"
>
{song.coverart ? (
<img src={song.coverart} alt="" loading="lazy" decoding="async" className="h-full w-full object-cover" />
) : (
<div className="flex h-full w-full items-center justify-center bg-surface-container-high text-on-surface-variant">
<Music2 size={28} strokeWidth={1.5} />
</div>
)}
<span
className={`absolute inset-0 flex items-center justify-center bg-black/50 text-white transition-opacity duration-150 ${
isCurrent || busy ? 'opacity-100' : 'opacity-100 sm:opacity-0 sm:group-hover:opacity-100'
}`}
>
{busy || (isCurrent && streamLoading) ? (
<span className="h-4 w-4 animate-spin rounded-full border-2 border-white/40 border-t-white" />
) : isCurrent && isPlaying ? (
<Pause size={20} strokeWidth={2} fill="currentColor" />
) : (
<Play size={20} strokeWidth={2} fill="currentColor" className="ml-0.5" />
)}
</span>
</button>
<div className="min-w-0">
<p className="truncate text-sm font-medium text-on-surface">{song.title}</p>
<p className="truncate text-xs text-on-surface-variant">
{song.artist}
{song.username ? ` · ${song.username}` : ''}
</p>
{error && <p className="truncate text-xs text-error">{error}</p>}
</div>
</div>
)
}
import { ListPlus, Music2, Pause, Play } from 'lucide-react'
import type { HomeSong } from '../api/home'
import { useHomeSongPlayback } from '../hooks/useHomeSongPlayback'
/** A row for the Home feed's "Suggestions" section - visually close to SharedSongRow, but a
* Home-feed song can belong to the caller already (plays directly, shows a real now-playing
* state) as well as to someone else (claim-then-play) - see useHomeSongPlayback for which. */
export function HomeSongRow({
song,
onAddToPlaylist,
}: {
song: HomeSong
onAddToPlaylist: (song: { id: number; title: string }) => void
}) {
const { isOwnSong, isCurrent, isPlaying, streamLoading, claiming, error, handlePlay, handleAddToPlaylist } =
useHomeSongPlayback(song)
return (
<li className="-mx-1 rounded-xl">
<div className="relative flex items-center gap-1 rounded-xl border border-transparent pr-2 hover:border-outline-variant hover:bg-surface-container">
<button
onClick={handlePlay}
disabled={claiming !== null}
aria-label={isCurrent && isPlaying ? `Pause ${song.title}` : `Play ${song.title}`}
className="group flex min-w-0 flex-1 items-center gap-4 rounded-lg px-2 py-3 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed"
>
<div className="relative h-12 w-12 shrink-0">
{song.coverart ? (
<img src={song.coverart} alt="" loading="lazy" decoding="async" className="h-12 w-12 rounded-lg object-cover" />
) : (
<div className="flex h-12 w-12 items-center justify-center rounded-lg bg-surface-container-high text-on-surface-variant">
<Music2 size={18} strokeWidth={1.75} />
</div>
)}
<span
className={`absolute inset-0 flex items-center justify-center rounded-lg bg-black/50 text-white transition-opacity duration-150 ${
isCurrent || claiming === 'play' ? 'opacity-100' : 'opacity-100 sm:opacity-0 sm:group-hover:opacity-100'
}`}
>
{claiming === 'play' || (isCurrent && streamLoading) ? (
<span className="h-3.5 w-3.5 animate-spin rounded-full border-2 border-white/40 border-t-white" />
) : isCurrent && isPlaying ? (
<Pause size={18} strokeWidth={2} fill="currentColor" />
) : (
<Play size={18} strokeWidth={2} fill="currentColor" className="ml-0.5" />
)}
</span>
</div>
<div className="min-w-0 flex-1">
<p className={`truncate font-medium ${isCurrent ? 'text-primary' : 'text-on-surface group-hover:text-primary'}`}>
{song.title}
</p>
<p className="truncate text-sm text-on-surface-variant">
{song.artist}
{song.album ? ` · ${song.album}` : ''}
{!isOwnSong && song.username ? ` · ${song.username}` : ''}
</p>
{error && <p className="mt-0.5 truncate text-xs text-error">{error}</p>}
</div>
</button>
<button
onClick={() => handleAddToPlaylist(onAddToPlaylist)}
disabled={claiming !== null}
aria-label={`Add ${song.title} to a playlist`}
className="shrink-0 rounded-full p-2 text-on-surface-variant transition-colors hover:bg-surface-container-high hover:text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed"
>
{claiming === 'playlist' ? (
<span className="block h-[18px] w-[18px] animate-spin rounded-full border-2 border-outline-variant border-t-on-surface" />
) : (
<ListPlus size={18} strokeWidth={1.75} />
)}
</button>
</div>
</li>
)
}
......@@ -2,6 +2,7 @@ import { useState, type ReactNode } from 'react'
import { Link, useLocation } from 'react-router-dom'
import {
Compass,
Globe,
Headphones,
Library,
Link2,
......@@ -36,6 +37,7 @@ const MORE_SHEET_ANIMATION_MS = 300
// "Soundmarks" destination (both merged 2026-08-23) - each hub page owns its own in-page
// sub-tab switcher instead of splitting related features across the top-level nav.
const ALL_NAV_ITEMS: { to: string; label: string; icon: LucideIcon }[] = [
{ to: '/home', label: 'Home', icon: Globe },
{ to: '/library', label: 'Library', icon: Library },
{ to: '/playlists', label: 'Playlists', icon: ListMusic },
{ to: '/upload', label: 'Upload', icon: Upload },
......@@ -52,7 +54,7 @@ const NAV_ITEMS = REMIX_ENABLED ? ALL_NAV_ITEMS : ALL_NAV_ITEMS.filter((item) =>
// The 5 most-reached destinations get a fixed mobile tab (matches the design system's
// "5-tab reachability" spec); everything else lives behind the More sheet, 6th tab. Desktop's
// sidebar has room to just list all of NAV_ITEMS, so this split is mobile-only.
const MOBILE_TAB_PATHS = new Set(['/library', '/discovery', '/social', '/soundmarks', '/remix'])
const MOBILE_TAB_PATHS = new Set(['/home', '/library', '/discovery', '/social', '/soundmarks', '/remix'])
const mobileTabs = NAV_ITEMS.filter((item) => MOBILE_TAB_PATHS.has(item.to))
const overflowItems = NAV_ITEMS.filter((item) => !MOBILE_TAB_PATHS.has(item.to))
......@@ -88,7 +90,7 @@ export function Layout({ title, children }: { title: string; children: ReactNode
className="fixed inset-y-0 left-0 z-10 hidden w-64 flex-col border-r border-outline-variant bg-surface-container-low sm:flex"
style={{ paddingTop: 'env(safe-area-inset-top)' }}
>
<Link to="/library" className="flex items-center gap-2 px-6 py-6 text-lg font-bold tracking-tight text-primary">
<Link to="/home" className="flex items-center gap-2 px-6 py-6 text-lg font-bold tracking-tight text-primary">
<Headphones size={22} strokeWidth={2} />
Stax
</Link>
......@@ -147,7 +149,7 @@ export function Layout({ title, children }: { title: string; children: ReactNode
style={{ paddingTop: 'env(safe-area-inset-top)' }}
>
<div className="flex h-14 items-center justify-center">
<Link to="/library" className="flex items-center gap-2 text-[15px] font-bold tracking-tight text-primary">
<Link to="/home" className="flex items-center gap-2 text-[15px] font-bold tracking-tight text-primary">
<Headphones size={20} strokeWidth={2} />
Stax
</Link>
......
......@@ -8,6 +8,7 @@ function mockAuth(isAuthenticated: boolean) {
vi.spyOn(AuthContextModule, 'useAuth').mockReturnValue({
isAuthenticated,
role: null,
userId: null,
isBusinessAdmin: false,
isSuperAdmin: false,
logout: vi.fn(),
......
......@@ -17,6 +17,7 @@ function song(id: number, title: string, artist = 'Some Artist'): LibrarySong {
lyrics: null,
file_path: `/x${id}.mp3`,
added_at: '2026-01-01T00:00:00Z',
is_liked: false,
}
}
......
......@@ -8,6 +8,7 @@ function mockAuth(overrides: Partial<ReturnType<typeof AuthContextModule.useAuth
vi.spyOn(AuthContextModule, 'useAuth').mockReturnValue({
isAuthenticated: true,
role: null,
userId: null,
isBusinessAdmin: false,
isSuperAdmin: false,
logout: vi.fn(),
......
......@@ -157,6 +157,7 @@ describe('RoomView', () => {
lyrics: null,
file_path: '/x.mp3',
added_at: '2026-01-01T00:00:00Z',
is_liked: false,
},
],
})
......
......@@ -76,7 +76,7 @@ export function SharedSongRow({ song, onAddToPlaylist }: { song: LibrarySong; on
)}
<span
className={`absolute inset-0 flex items-center justify-center rounded-lg bg-black/50 text-white transition-opacity duration-150 ${
claiming === 'play' ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'
claiming === 'play' ? 'opacity-100' : 'opacity-100 sm:opacity-0 sm:group-hover:opacity-100'
}`}
>
{claiming === 'play' ? (
......
import { ListMusic, ListPlus, Music2, Pause, Play, Trash2 } from 'lucide-react'
import { Heart, ListMusic, ListPlus, Music2, Pause, Play, Trash2 } from 'lucide-react'
import type { LibrarySong } from '../api/library'
import { usePlayer, type PlayableSong } from '../context/PlayerContext'
import { useSwipeAction } from '../hooks/useSwipeAction'
......@@ -27,11 +27,16 @@ export function SongRow({
queue,
onAddToPlaylist,
onDelete,
onToggleFavorite,
}: {
song: LibrarySong
queue: LibrarySong[]
onAddToPlaylist: (song: LibrarySong) => void
onDelete: (song: LibrarySong) => void
/** Owns the actual favorite/unfavorite request (optimistic toggle + revert-on-failure) and
* reconciling `is_liked` across whichever lists this song appears in - same division of
* responsibility as `onDelete`, which already owns reconciling a deletion the same way. */
onToggleFavorite: (song: LibrarySong) => void
}) {
const { currentSong, isPlaying, isLoading: streamLoading, toggle, addToQueue } = usePlayer()
const isCurrent = currentSong?.id === song.id
......@@ -93,7 +98,7 @@ export function SongRow({
)}
<span
className={`absolute inset-0 flex items-center justify-center rounded-lg bg-black/50 text-white transition-opacity duration-150 ${
isCurrent ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'
isCurrent ? 'opacity-100' : 'opacity-100 sm:opacity-0 sm:group-hover:opacity-100'
}`}
>
{isCurrent && streamLoading ? (
......@@ -115,6 +120,16 @@ export function SongRow({
</p>
</div>
</button>
<button
onClick={() => onToggleFavorite(song)}
aria-label={song.is_liked ? `Unlike ${song.title}` : `Like ${song.title}`}
aria-pressed={song.is_liked}
className={`shrink-0 rounded-full p-2 transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary ${
song.is_liked ? 'text-primary hover:bg-surface-container-high' : 'text-on-surface-variant hover:bg-surface-container-high hover:text-primary'
}`}
>
<Heart size={18} strokeWidth={1.75} fill={song.is_liked ? 'currentColor' : 'none'} />
</button>
<button
onClick={() => onAddToPlaylist(song)}
aria-label={`Add ${song.title} to a playlist`}
......
......@@ -9,6 +9,9 @@ interface AuthContextValue {
* check `isAuthenticated` too so a momentarily-null role during that fetch doesn't flash a
* "not allowed" state for someone who actually is an admin. */
role: UserRole | null
/** Same lazy-null-until-/auth/me-resolves shape as `role` - used by the Home feed to tell
* "I already own this song" (play directly) from "someone else's" (claim first). */
userId: number | null
isBusinessAdmin: boolean
isSuperAdmin: boolean
logout: () => Promise<void>
......@@ -36,17 +39,22 @@ const AuthContext = createContext<AuthContextValue | null>(null)
export function AuthProvider({ children }: { children: ReactNode }) {
const [isAuthenticated, setIsAuthenticated] = useState(() => !!getAccessToken())
const [role, setRole] = useState<UserRole | null>(null)
const [userId, setUserId] = useState<number | null>(null)
useEffect(() => {
if (!isAuthenticated) {
setRole(null)
setUserId(null)
return
}
let cancelled = false
authApi
.getMe()
.then((res) => {
if (!cancelled) setRole(res.user.role)
if (!cancelled) {
setRole(res.user.role)
setUserId(res.user.id)
}
})
.catch((err) => {
if (cancelled) return
......@@ -92,7 +100,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
const isSuperAdmin = role === 'super_admin'
return (
<AuthContext.Provider value={{ isAuthenticated, role, isBusinessAdmin, isSuperAdmin, logout, completeLogin }}>
<AuthContext.Provider value={{ isAuthenticated, role, userId, isBusinessAdmin, isSuperAdmin, logout, completeLogin }}>
{children}
</AuthContext.Provider>
)
......
import { useState } from 'react'
import { claimSharedSong } from '../api/library'
import { ApiError } from '../api/client'
import { usePlayer, type PlayableSong } from '../context/PlayerContext'
import { useAuth } from '../context/AuthContext'
import type { HomeSong } from '../api/home'
/** Shared by HomeSongCard and HomeSongRow (the two places a Home-feed song can be tapped) so
* the claim-then-play logic isn't duplicated between them. A Home-feed song the caller already
* owns (`user_id === userId`) plays directly via its real library id; everyone else's goes
* through the same claim-then-play mechanism SharedSongRow already uses for Library's shared
* search results, since that id belongs to someone else's library row and can't be streamed
* until the caller has their own copy. */
export function useHomeSongPlayback(song: HomeSong) {
const { userId } = useAuth()
const { currentSong, isPlaying, isLoading: streamLoading, toggle } = usePlayer()
const [claiming, setClaiming] = useState<'play' | 'playlist' | null>(null)
const [error, setError] = useState<string | null>(null)
const isOwnSong = song.user_id === userId
const isCurrent = isOwnSong && currentSong?.id === song.id
function toPlayable(libraryId: number): PlayableSong {
return { id: libraryId, title: song.title, artist: song.artist, album: song.album, coverart: song.coverart }
}
async function resolveLibraryId(): Promise<number> {
if (isOwnSong) return song.id
const res = await claimSharedSong(song.title, song.artist)
return res.library_song_id
}
async function handlePlay() {
if (isOwnSong) {
toggle(toPlayable(song.id), [toPlayable(song.id)])
return
}
setError(null)
setClaiming('play')
try {
const libraryId = await resolveLibraryId()
toggle(toPlayable(libraryId), [toPlayable(libraryId)])
} catch (err) {
setError(err instanceof ApiError ? err.message : `Could not add "${song.title}"`)
} finally {
setClaiming(null)
}
}
async function handleAddToPlaylist(onClaimed: (song: { id: number; title: string }) => void) {
if (isOwnSong) {
onClaimed({ id: song.id, title: song.title })
return
}
setError(null)
setClaiming('playlist')
try {
const libraryId = await resolveLibraryId()
onClaimed({ id: libraryId, title: song.title })
} catch (err) {
setError(err instanceof ApiError ? err.message : `Could not add "${song.title}"`)
} finally {
setClaiming(null)
}
}
return { isOwnSong, isCurrent, isPlaying, streamLoading, claiming, error, handlePlay, handleAddToPlaylist }
}
......@@ -20,6 +20,7 @@ const SONG_1 = {
lyrics: null,
file_path: '/x.mp3',
added_at: '2026-01-01T00:00:00Z',
is_liked: false,
}
const SONG_2 = { ...SONG_1, id: 2, title: 'Second' }
......@@ -84,6 +85,21 @@ describe('AlbumDetail', () => {
expect(within(rows[1]).getByText('Second')).toBeInTheDocument()
})
it('likes a track from the album page without affecting the other track', async () => {
vi.spyOn(libraryApi, 'getAlbum').mockResolvedValue({ status: 'success', album: ALBUM })
const favorite = vi.spyOn(libraryApi, 'favoriteSong').mockResolvedValue({ status: 'success', is_liked: true })
renderAlbumDetail()
await screen.findByText('Duran Duran · 2 tracks')
const rows = screen.getAllByRole('listitem')
await userEvent.click(within(rows[0]).getByRole('button', { name: 'Like First' }))
expect(favorite).toHaveBeenCalledWith(SONG_1.id)
expect(within(rows[0]).getByRole('button', { name: 'Unlike First' })).toHaveAttribute('aria-pressed', 'true')
expect(within(rows[1]).getByRole('button', { name: 'Like Second' })).toHaveAttribute('aria-pressed', 'false')
})
it('shows a load error using the ApiError message', async () => {
vi.spyOn(libraryApi, 'getAlbum').mockRejectedValue(new ApiError(404, 'Album not found', null))
......
import { useEffect, useState } from 'react'
import { Music2, Pause, Play } from 'lucide-react'
import { useNavigate, useSearchParams } from 'react-router-dom'
import { deleteLibrarySong, getAlbum, type Album, type LibrarySong } from '../api/library'
import { deleteLibrarySong, favoriteSong, getAlbum, unfavoriteSong, type Album, type LibrarySong } from '../api/library'
import { ApiError } from '../api/client'
import { Layout } from '../components/Layout'
import { AddToPlaylistModal } from '../components/AddToPlaylistModal'
......@@ -59,6 +59,22 @@ export function AlbumDetail() {
}
}
// Optimistic - flips is_liked immediately (same instant feel as every other toggle in this
// app), reverting only if the request actually fails, rather than waiting on a round-trip
// before the heart visibly responds.
function handleToggleFavorite(song: LibrarySong) {
const nextLiked = !song.is_liked
setAlbum((prev) =>
prev ? { ...prev, songs: prev.songs.map((s) => (s.id === song.id ? { ...s, is_liked: nextLiked } : s)) } : prev,
)
const request = nextLiked ? favoriteSong(song.id) : unfavoriteSong(song.id)
request.catch(() => {
setAlbum((prev) =>
prev ? { ...prev, songs: prev.songs.map((s) => (s.id === song.id ? { ...s, is_liked: !nextLiked } : s)) } : prev,
)
})
}
const isAlbumCurrent = !!album && album.songs.some((s) => s.id === currentSong?.id)
return (
......@@ -120,7 +136,14 @@ export function AlbumDetail() {
existing separately from the unordered album-grid preview. */}
<ul className="space-y-1">
{album.songs.map((song) => (
<SongRow key={song.id} song={song} queue={album.songs} onAddToPlaylist={setAddingSong} onDelete={handleDelete} />
<SongRow
key={song.id}
song={song}
queue={album.songs}
onAddToPlaylist={setAddingSong}
onDelete={handleDelete}
onToggleFavorite={handleToggleFavorite}
/>
))}
</ul>
</div>
......
......@@ -37,6 +37,7 @@ const MY_SONG = {
lyrics: null,
file_path: '/x.mp3',
added_at: '2026-01-01T00:00:00Z',
is_liked: false,
}
const SUGGESTION: soundmarksApi.SoundmarkSuggestion = {
......
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter, Route, Routes, useSearchParams } from 'react-router-dom'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { Home } from './Home'
import { AuthProvider } from '../context/AuthContext'
import { PlayerProvider } from '../context/PlayerContext'
import { ApiError } from '../api/client'
import { clearTokens, setTokens } from '../api/client'
import * as authApi from '../api/auth'
import * as homeApi from '../api/home'
import * as libraryApi from '../api/library'
import * as streamApi from '../api/stream'
// Stands in for the real AlbumDetail page (its own navigation/data-fetching is covered by
// AlbumDetail's own test file) - just enough to prove Home navigated to the right place with
// the right query params for an album the caller owns.
function AlbumRouteProbe() {
const [params] = useSearchParams()
return <p>Album route: {params.get('album')} by {params.get('artist')}</p>
}
const ME_ID = 1
const OTHER_ID = 42
const OWN_SONG = {
id: 10,
user_id: ME_ID,
username: 'me',
title: 'My Own Track',
artist: 'Me',
album: null,
genre: 'Pop',
coverart: null,
added_at: '2026-01-01T00:00:00Z',
}
const OTHER_SONG = {
id: 20,
user_id: OTHER_ID,
username: 'stranger',
title: "Someone Else's Track",
artist: 'Nobody',
album: null,
genre: 'Rock',
coverart: null,
added_at: '2026-01-01T00:00:00Z',
}
const OWN_ALBUM = {
album: 'My Album',
artist: 'Me',
user_id: ME_ID,
coverart: null,
track_count: 1,
songs: [{ ...OWN_SONG, id: 11, album: 'My Album' }],
}
const OTHER_ALBUM = {
album: 'Their Album',
artist: 'Nobody',
user_id: OTHER_ID,
coverart: null,
track_count: 1,
songs: [{ ...OTHER_SONG, id: 21, album: 'Their Album' }],
}
function renderHome() {
return render(
<MemoryRouter>
<AuthProvider>
<PlayerProvider>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/library/album" element={<AlbumRouteProbe />} />
</Routes>
</PlayerProvider>
</AuthProvider>
</MemoryRouter>,
)
}
describe('Home', () => {
beforeEach(() => {
vi.stubEnv('VITE_DEV_ACCESS_TOKEN', '')
vi.stubEnv('VITE_DEV_REFRESH_TOKEN', '')
// AuthContext only resolves `userId` (needed to tell an own song from someone else's) when
// isAuthenticated is true at mount, which it derives from a real stored token - so every
// test here needs one seeded, plus a mocked /auth/me to actually resolve it to ME_ID.
setTokens('test-access', 'test-refresh')
vi.spyOn(authApi, 'getMe').mockResolvedValue({
status: 'success',
user: { id: ME_ID, username: 'me', role: 'user', privacy: { share_location_enabled: false, allow_direct_messages: false } },
})
})
afterEach(() => {
clearTokens()
vi.unstubAllEnvs()
vi.restoreAllMocks()
})
it('shows the empty state when the feed has nothing yet', async () => {
vi.spyOn(homeApi, 'getHomeFeed').mockResolvedValue({ status: 'success', latest_songs: [], new_albums: [], suggestions: [] })
renderHome()
expect(await screen.findByText(/No songs on Stax yet/)).toBeInTheDocument()
})
it('shows the backend error message when the feed fails to load', async () => {
vi.spyOn(homeApi, 'getHomeFeed').mockRejectedValue(new ApiError(500, 'Server is on fire', null))
renderHome()
expect(await screen.findByText('Server is on fire')).toBeInTheDocument()
})
it('renders the newly added songs, new albums, and suggestions sections', async () => {
vi.spyOn(homeApi, 'getHomeFeed').mockResolvedValue({
status: 'success',
latest_songs: [OWN_SONG],
new_albums: [OWN_ALBUM],
suggestions: [OTHER_SONG],
})
renderHome()
expect(await screen.findByText('Newly added')).toBeInTheDocument()
expect(screen.getByText('My Own Track')).toBeInTheDocument()
expect(screen.getByText('New albums')).toBeInTheDocument()
expect(screen.getByText('My Album')).toBeInTheDocument()
expect(screen.getByText('Suggestions')).toBeInTheDocument()
expect(screen.getByText("Someone Else's Track")).toBeInTheDocument()
})
it('plays a song the caller already owns directly, without claiming it first', async () => {
vi.spyOn(homeApi, 'getHomeFeed').mockResolvedValue({ status: 'success', latest_songs: [OWN_SONG], new_albums: [], suggestions: [] })
const claimSharedSong = vi.spyOn(libraryApi, 'claimSharedSong')
const fetchStreamUrl = vi.spyOn(streamApi, 'fetchStreamUrl').mockResolvedValue('blob:fake-url')
renderHome()
await userEvent.click(await screen.findByRole('button', { name: 'Play My Own Track' }))
await waitFor(() => expect(fetchStreamUrl).toHaveBeenCalledWith(OWN_SONG.id))
expect(claimSharedSong).not.toHaveBeenCalled()
})
it('claims a suggestion from someone else before playing it', async () => {
vi.spyOn(homeApi, 'getHomeFeed').mockResolvedValue({ status: 'success', latest_songs: [], new_albums: [], suggestions: [OTHER_SONG] })
const claimSharedSong = vi.spyOn(libraryApi, 'claimSharedSong').mockResolvedValue({ status: 'success', library_song_id: 77 })
const fetchStreamUrl = vi.spyOn(streamApi, 'fetchStreamUrl').mockResolvedValue('blob:fake-url')
renderHome()
await userEvent.click(await screen.findByRole('button', { name: /Play Someone Else's Track/ }))
await waitFor(() => expect(claimSharedSong).toHaveBeenCalledWith("Someone Else's Track", 'Nobody'))
await waitFor(() => expect(fetchStreamUrl).toHaveBeenCalledWith(77))
})
it('claims a suggestion from someone else before adding it to a playlist', async () => {
vi.spyOn(homeApi, 'getHomeFeed').mockResolvedValue({ status: 'success', latest_songs: [], new_albums: [], suggestions: [OTHER_SONG] })
const claimSharedSong = vi.spyOn(libraryApi, 'claimSharedSong').mockResolvedValue({ status: 'success', library_song_id: 77 })
vi.spyOn(libraryApi, 'getPlaylists').mockResolvedValue({ status: 'success', playlists: [] })
renderHome()
await userEvent.click(await screen.findByRole('button', { name: /Add Someone Else's Track to a playlist/ }))
await waitFor(() => expect(claimSharedSong).toHaveBeenCalledWith("Someone Else's Track", 'Nobody'))
expect(await screen.findByText('Add "Someone Else\'s Track" to playlist')).toBeInTheDocument()
})
it('adds a suggestion the caller already owns to a playlist without claiming it', async () => {
vi.spyOn(homeApi, 'getHomeFeed').mockResolvedValue({ status: 'success', latest_songs: [], new_albums: [], suggestions: [OWN_SONG] })
const claimSharedSong = vi.spyOn(libraryApi, 'claimSharedSong')
vi.spyOn(libraryApi, 'getPlaylists').mockResolvedValue({ status: 'success', playlists: [] })
renderHome()
await userEvent.click(await screen.findByRole('button', { name: /Add My Own Track to a playlist/ }))
expect(await screen.findByText('Add "My Own Track" to playlist')).toBeInTheDocument()
expect(claimSharedSong).not.toHaveBeenCalled()
})
it('tapping an album the caller owns navigates to its real detail page', async () => {
vi.spyOn(homeApi, 'getHomeFeed').mockResolvedValue({ status: 'success', latest_songs: [], new_albums: [OWN_ALBUM], suggestions: [] })
renderHome()
await userEvent.click(await screen.findByText('My Album'))
expect(await screen.findByText('Album route: My Album by Me')).toBeInTheDocument()
})
it('tapping an album from someone else expands its tracks inline instead of navigating', async () => {
vi.spyOn(homeApi, 'getHomeFeed').mockResolvedValue({ status: 'success', latest_songs: [], new_albums: [OTHER_ALBUM], suggestions: [] })
renderHome()
await userEvent.click(await screen.findByText('Their Album'))
expect(await screen.findByRole('button', { name: /Play Someone Else's Track/ })).toBeInTheDocument()
expect(screen.queryByText(/^Album route:/)).not.toBeInTheDocument()
})
})
import { useEffect, useState } from 'react'
import { Globe } from 'lucide-react'
import { getHomeFeed, type HomeAlbum, type HomeSong } from '../api/home'
import { ApiError } from '../api/client'
import { Layout } from '../components/Layout'
import { AddToPlaylistModal } from '../components/AddToPlaylistModal'
import { HomeSongCard } from '../components/HomeSongCard'
import { HomeAlbumCard } from '../components/HomeAlbumCard'
import { HomeSongRow } from '../components/HomeSongRow'
import { SkeletonRow } from '../components/ui/Skeleton'
import { EmptyState } from '../components/ui/EmptyState'
/** The new default landing page - everything here is global (every user's uploads), unlike the
* per-user Library page. `suggestions` is explicitly a placeholder algorithm for now, not real
* personalization yet (see the backend's own comment in home.py). */
export function Home() {
const [latestSongs, setLatestSongs] = useState<HomeSong[]>([])
const [newAlbums, setNewAlbums] = useState<HomeAlbum[]>([])
const [suggestions, setSuggestions] = useState<HomeSong[]>([])
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const [addingSong, setAddingSong] = useState<{ id: number; title: string } | null>(null)
useEffect(() => {
getHomeFeed()
.then((res) => {
setLatestSongs(res.latest_songs)
setNewAlbums(res.new_albums)
setSuggestions(res.suggestions)
})
.catch((err) => setError(err instanceof ApiError ? err.message : 'Failed to load the home feed'))
.finally(() => setLoading(false))
}, [])
const isEmpty = !loading && !error && latestSongs.length === 0 && newAlbums.length === 0 && suggestions.length === 0
return (
<Layout title="Home">
{loading && (
<div className="space-y-1">
<SkeletonRow />
<SkeletonRow />
<SkeletonRow />
</div>
)}
{error && <p className="text-sm text-error">{error}</p>}
{isEmpty && <EmptyState icon={Globe} message="No songs on Stax yet - be the first to tag one." />}
{!loading && !error && (
<div className="animate-content-enter">
{latestSongs.length > 0 && (
<div className="mb-8">
<h2 className="mb-3 text-xs font-semibold uppercase tracking-[0.1em] text-primary">Newly added</h2>
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5">
{latestSongs.map((song) => (
<HomeSongCard key={song.id} song={song} />
))}
</div>
</div>
)}
{newAlbums.length > 0 && (
<div className="mb-8">
<h2 className="mb-3 text-xs font-semibold uppercase tracking-[0.1em] text-primary">New albums</h2>
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5">
{newAlbums.map((album) => (
<HomeAlbumCard
key={`${album.album}::${album.artist}::${album.user_id}`}
album={album}
onAddToPlaylist={setAddingSong}
/>
))}
</div>
</div>
)}
{suggestions.length > 0 && (
<div>
<h2 className="mb-2 text-xs font-semibold uppercase tracking-[0.1em] text-primary">Suggestions</h2>
<ul className="space-y-1">
{suggestions.map((song) => (
<HomeSongRow key={song.id} song={song} onAddToPlaylist={setAddingSong} />
))}
</ul>
</div>
)}
</div>
)}
{addingSong && <AddToPlaylistModal song={addingSong} onClose={() => setAddingSong(null)} />}
</Layout>
)
}
......@@ -28,6 +28,7 @@ const SONG = {
lyrics: null,
file_path: '/x.mp3',
added_at: '2026-01-01T00:00:00Z',
is_liked: false,
}
const SONG_2 = { ...SONG, id: 2, title: 'Rio', album: 'Rio' }
......@@ -179,6 +180,46 @@ describe('Library', () => {
expect(fetchStreamUrl).not.toHaveBeenCalled()
})
it('likes an unliked song, showing the filled heart immediately (optimistic)', async () => {
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [SONG] })
const favorite = vi.spyOn(libraryApi, 'favoriteSong').mockResolvedValue({ status: 'success', is_liked: true })
renderLibrary()
const row = (await screen.findByText('Invisible')).closest('li')!
const heart = within(row).getByRole('button', { name: 'Like Invisible' })
expect(heart).toHaveAttribute('aria-pressed', 'false')
await userEvent.click(heart)
expect(favorite).toHaveBeenCalledWith(SONG.id)
expect(within(row).getByRole('button', { name: 'Unlike Invisible' })).toHaveAttribute('aria-pressed', 'true')
})
it('unlikes an already-liked song', async () => {
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [{ ...SONG, is_liked: true }] })
const unfavorite = vi.spyOn(libraryApi, 'unfavoriteSong').mockResolvedValue({ status: 'success', is_liked: false })
renderLibrary()
const row = (await screen.findByText('Invisible')).closest('li')!
await userEvent.click(within(row).getByRole('button', { name: 'Unlike Invisible' }))
expect(unfavorite).toHaveBeenCalledWith(SONG.id)
expect(within(row).getByRole('button', { name: 'Like Invisible' })).toHaveAttribute('aria-pressed', 'false')
})
it('reverts the optimistic like if the request fails', async () => {
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [SONG] })
vi.spyOn(libraryApi, 'favoriteSong').mockRejectedValue(new ApiError(500, 'Server error', null))
renderLibrary()
const row = (await screen.findByText('Invisible')).closest('li')!
await userEvent.click(within(row).getByRole('button', { name: 'Like Invisible' }))
await waitFor(() => {
expect(within(row).getByRole('button', { name: 'Like Invisible' })).toHaveAttribute('aria-pressed', 'false')
})
})
it('searches and shows separate Songs and Albums sections', async () => {
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [SONG] })
const searchLibrary = vi.spyOn(libraryApi, 'searchLibrary').mockResolvedValue({
......
......@@ -3,9 +3,11 @@ import { Globe2, Music2, Search } from 'lucide-react'
import { useNavigate } from 'react-router-dom'
import {
deleteLibrarySong,
favoriteSong,
getLibrary,
searchLibrary,
searchSharedLibrary,
unfavoriteSong,
type AlbumMatch,
type LibrarySong,
} from '../api/library'
......@@ -150,6 +152,33 @@ export function Library() {
}
}
// Optimistic (flips immediately, reverts only on failure) - and, like handleDelete above,
// has to reconcile every list this song can appear in itself: unlike the default view's
// `albums` (derived from `songs` via useMemo, so it updates for free), search's `albums`
// carry their own separate copy of each song from the backend response, so toggling via an
// album search result row wouldn't otherwise be reflected in `songs` or vice versa.
function setSongLiked(song: LibrarySong, liked: boolean) {
setSongs((prev) => prev.map((s) => (s.id === song.id ? { ...s, is_liked: liked } : s)))
setSearchResults((prev) =>
prev
? {
songs: prev.songs.map((s) => (s.id === song.id ? { ...s, is_liked: liked } : s)),
albums: prev.albums.map((album) => ({
...album,
songs: album.songs.map((s) => (s.id === song.id ? { ...s, is_liked: liked } : s)),
})),
}
: prev,
)
}
function handleToggleFavorite(song: LibrarySong) {
const nextLiked = !song.is_liked
setSongLiked(song, nextLiked)
const request = nextLiked ? favoriteSong(song.id) : unfavoriteSong(song.id)
request.catch(() => setSongLiked(song, !nextLiked))
}
// Not tied to searchResults (which only ever holds "mine"-scope results) - "shared" scope
// populates sharedResults instead, so deriving this from the query itself is what actually
// stays correct across both scopes.
......@@ -268,7 +297,14 @@ export function Library() {
<h2 className="mb-2 text-xs font-semibold uppercase tracking-[0.1em] text-primary">Songs</h2>
<ul className="space-y-1">
{searchResults.songs.map((song) => (
<SongRow key={song.id} song={song} queue={searchResults.songs} onAddToPlaylist={setAddingSong} onDelete={handleDelete} />
<SongRow
key={song.id}
song={song}
queue={searchResults.songs}
onAddToPlaylist={setAddingSong}
onDelete={handleDelete}
onToggleFavorite={handleToggleFavorite}
/>
))}
</ul>
</div>
......@@ -292,7 +328,14 @@ export function Library() {
<h2 className="mb-2 text-xs font-semibold uppercase tracking-[0.1em] text-primary">All Songs</h2>
<ul className="space-y-1">
{songs.map((song) => (
<SongRow key={song.id} song={song} queue={songs} onAddToPlaylist={setAddingSong} onDelete={handleDelete} />
<SongRow
key={song.id}
song={song}
queue={songs}
onAddToPlaylist={setAddingSong}
onDelete={handleDelete}
onToggleFavorite={handleToggleFavorite}
/>
))}
</ul>
</div>
......
......@@ -13,7 +13,7 @@ function renderLogin(initialEntries: { pathname: string; state?: unknown }[] = [
<AuthProvider>
<Routes>
<Route path="/login" element={<Login />} />
<Route path="/library" element={<p>Library page</p>} />
<Route path="/home" element={<p>Home page</p>} />
<Route path="/business" element={<p>Business page</p>} />
</Routes>
</AuthProvider>
......@@ -53,7 +53,7 @@ describe('Login', () => {
await userEvent.click(screen.getByRole('button', { name: 'Sign in' }))
await waitFor(() => expect(login).toHaveBeenCalledWith('alice', 'correcthorse'))
expect(await screen.findByText('Library page')).toBeInTheDocument()
expect(await screen.findByText('Home page')).toBeInTheDocument()
})
it('shows the backend error when login fails, without navigating away', async () => {
......@@ -65,7 +65,7 @@ describe('Login', () => {
await userEvent.click(screen.getByRole('button', { name: 'Sign in' }))
expect(await screen.findByText('Invalid username or password')).toBeInTheDocument()
expect(screen.queryByText('Library page')).not.toBeInTheDocument()
expect(screen.queryByText('Home page')).not.toBeInTheDocument()
})
it('sends the user back to the page they originally tried to reach', async () => {
......@@ -104,7 +104,7 @@ describe('Login', () => {
await userEvent.click(screen.getByRole('button', { name: 'Create account' }))
await waitFor(() => expect(register).toHaveBeenCalledWith('newuser', 'correcthorse'))
expect(await screen.findByText('Library page')).toBeInTheDocument()
expect(await screen.findByText('Home page')).toBeInTheDocument()
})
it('shows the backend error when registration fails (e.g. duplicate username)', async () => {
......@@ -117,7 +117,7 @@ describe('Login', () => {
await userEvent.click(screen.getByRole('button', { name: 'Create account' }))
expect(await screen.findByText('Username already taken')).toBeInTheDocument()
expect(screen.queryByText('Library page')).not.toBeInTheDocument()
expect(screen.queryByText('Home page')).not.toBeInTheDocument()
})
it('lets you toggle back from register to sign-in', async () => {
......
......@@ -31,7 +31,7 @@ export function Login() {
// Sends them back to whatever protected page they originally tried to reach (see
// ProtectedRoute/RequireRole, which stash it as location.state.from), not just a fixed
// default - a business admin bookmarking /business shouldn't land on /library first.
const from = (location.state as { from?: { pathname: string } } | null)?.from?.pathname ?? '/library'
const from = (location.state as { from?: { pathname: string } } | null)?.from?.pathname ?? '/home'
navigate(from, { replace: true })
} catch (err) {
if (err instanceof ApiError) {
......
......@@ -302,6 +302,7 @@ describe('Nearby', () => {
lyrics: null,
file_path: '/x.mp3',
added_at: '2026-01-01T00:00:00Z',
is_liked: false,
},
],
})
......@@ -337,6 +338,7 @@ describe('Nearby', () => {
lyrics: null,
file_path: '/x.mp3',
added_at: '2026-01-01T00:00:00Z',
is_liked: false,
},
],
})
......
......@@ -9,7 +9,7 @@ import { ApiError } from '../api/client'
import * as libraryApi from '../api/library'
import * as streamApi from '../api/stream'
const PLAYLIST = { id: 10, user_id: 1, name: 'Chill', created_at: '2026-01-01T00:00:00Z' }
const PLAYLIST = { id: 10, user_id: 1, name: 'Chill', created_at: '2026-01-01T00:00:00Z', is_liked_playlist: false }
const SONG = {
id: 1,
......@@ -22,6 +22,7 @@ const SONG = {
lyrics: null,
file_path: '/x.mp3',
added_at: '2026-01-01T00:00:00Z',
is_liked: false,
}
function renderPlaylists() {
......@@ -63,6 +64,19 @@ describe('Playlists', () => {
expect(await screen.findByText('Chill')).toBeInTheDocument()
})
it('renders the Liked Songs playlist with a filled heart icon instead of the generic icon', async () => {
const liked = { id: 99, user_id: 1, name: 'Liked Songs', created_at: '2026-01-01T00:00:00Z', is_liked_playlist: true }
vi.spyOn(libraryApi, 'getPlaylists').mockResolvedValue({ status: 'success', playlists: [liked, PLAYLIST] })
renderPlaylists()
const row = (await screen.findByText('Liked Songs')).closest('button')!
// lucide-react icons render as <svg>, distinguishable by their component name on the class.
expect(row.querySelector('svg.lucide-heart')).toBeInTheDocument()
const otherRow = screen.getByText('Chill').closest('button')!
expect(otherRow.querySelector('svg.lucide-heart')).not.toBeInTheDocument()
})
it('shows a load error using the ApiError message', async () => {
vi.spyOn(libraryApi, 'getPlaylists').mockRejectedValue(new ApiError(500, 'Server exploded', null))
......@@ -73,7 +87,7 @@ describe('Playlists', () => {
it('creates a playlist and adds it to the list', async () => {
vi.spyOn(libraryApi, 'getPlaylists').mockResolvedValue({ status: 'success', playlists: [] })
const newPlaylist = { id: 20, user_id: 1, name: 'Road Trip', created_at: '2026-01-03T00:00:00Z' }
const newPlaylist = { id: 20, user_id: 1, name: 'Road Trip', created_at: '2026-01-03T00:00:00Z', is_liked_playlist: false }
const createPlaylist = vi.spyOn(libraryApi, 'createPlaylist').mockResolvedValue({ status: 'success', playlist: newPlaylist })
renderPlaylists()
......
import { useEffect, useState } from 'react'
import { ArrowLeft, ListMusic, Music2, Pause, Play, Plus } from 'lucide-react'
import { ArrowLeft, Heart, ListMusic, Music2, Pause, Play, Plus } from 'lucide-react'
import { createPlaylist, getPlaylist, getPlaylists, type LibrarySong, type Playlist } from '../api/library'
import { ApiError } from '../api/client'
import { Layout } from '../components/Layout'
......@@ -201,8 +201,16 @@ export function Playlists() {
onClick={() => openPlaylist(playlist)}
className="-mx-2 flex w-full items-center gap-4 rounded-lg px-2 py-3 text-left transition-colors hover:bg-surface-container focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"
>
<div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-md bg-surface-container-high text-on-surface-variant">
<div
className={`flex h-12 w-12 shrink-0 items-center justify-center rounded-md ${
playlist.is_liked_playlist ? 'bg-primary/15 text-primary' : 'bg-surface-container-high text-on-surface-variant'
}`}
>
{playlist.is_liked_playlist ? (
<Heart size={18} strokeWidth={1.75} fill="currentColor" />
) : (
<ListMusic size={18} strokeWidth={1.75} />
)}
</div>
<div className="min-w-0 flex-1">
<p className="truncate font-medium text-on-surface">{playlist.name}</p>
......
......@@ -45,6 +45,7 @@ const MY_LIBRARY_SONG = {
lyrics: null,
file_path: '/x.mp3',
added_at: '2026-01-01T00:00:00Z',
is_liked: false,
}
function renderPosts() {
......
......@@ -20,6 +20,7 @@ const SONG: LibrarySong = {
lyrics: null,
file_path: '/x.mp3',
added_at: '2026-01-01T00:00:00Z',
is_liked: false,
}
function renderRemix() {
......
This diff is collapsed.
......@@ -23,14 +23,18 @@ export function Social() {
return (
<Layout title="Social">
<div className="mb-6 flex gap-2">
{/* overflow-x-auto + shrink-0 pills: four full-label pills (Rooms/Channels/Posts/
Messages) don't fit a phone-width viewport without this - confirmed live via a
mobile-viewport sweep, where the row pushed the whole page wider than the screen
instead of wrapping or scrolling. */}
<div className="mb-6 flex gap-2 overflow-x-auto">
{TABS.map((t) => {
const active = tab === t.id
return (
<button
key={t.id}
onClick={() => setTab(t.id)}
className={`flex items-center gap-1.5 rounded-full px-4 py-1.5 text-sm font-medium transition-colors duration-150 ${
className={`flex shrink-0 items-center gap-1.5 rounded-full px-4 py-1.5 text-sm font-medium transition-colors duration-150 ${
active
? 'bg-primary text-on-primary'
: 'border border-outline-variant bg-surface-container text-on-surface-variant hover:border-primary hover:text-on-surface'
......
......@@ -81,7 +81,7 @@ describe('Upload', () => {
await uploadAndWaitForResult()
vi.spyOn(libraryApi, 'getPlaylists').mockResolvedValue({
status: 'success',
playlists: [{ id: 10, user_id: 1, name: 'Chill', created_at: '2026-01-01T00:00:00Z' }],
playlists: [{ id: 10, user_id: 1, name: 'Chill', created_at: '2026-01-01T00:00:00Z', is_liked_playlist: false }],
})
const addToPlaylist = vi.spyOn(libraryApi, 'addToPlaylist').mockResolvedValue({ status: 'success', message: 'ok' })
......
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