Commit 9378c354 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Add a consolidated My Library tab and a build-time flag to shrink prod's nav

Merges Library+Playlists into one My Library page (latest upload, own
playlists, liked/uploaded albums), gated behind the new MINIMAL_NAV_ENABLED
flag so prod can ship a smaller launch surface (upload/tag, discover, one
library tab) while dev keeps every page live. /library, /social, and
/telegram-link redirect to /my-library when the flag is on; /playlists stays
reachable since My Library links there for real playlist management.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 946930e8
Pipeline #1293 failed with stages
import { render, screen } from '@testing-library/react'
import { MemoryRouter } from 'react-router-dom'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { App } from './App'
import { AuthProvider } from './context/AuthContext'
import { PlayerProvider } from './context/PlayerContext'
import { setTokens, clearTokens } from './api/client'
import * as authApi from './api/auth'
import * as libraryApi from './api/library'
// Only the two flags App.tsx itself reads - see config/flags.ts for why MINIMAL_NAV_ENABLED
// exists (restricts prod's launch surface) and why it's tested as its own file rather than
// toggled per-test (vi.mock is hoisted and fixed for the whole module graph of this file).
vi.mock('./config/flags', () => ({ MINIMAL_NAV_ENABLED: true, REMIX_ENABLED: false }))
function renderAppAt(path: string) {
return render(
<MemoryRouter initialEntries={[path]}>
<AuthProvider>
<PlayerProvider>
<App />
</PlayerProvider>
</AuthProvider>
</MemoryRouter>,
)
}
describe('App routing under MINIMAL_NAV_ENABLED', () => {
beforeEach(() => {
vi.stubEnv('VITE_DEV_ACCESS_TOKEN', '')
vi.stubEnv('VITE_DEV_REFRESH_TOKEN', '')
setTokens('test-access', 'test-refresh')
vi.spyOn(authApi, 'getMe').mockResolvedValue({
status: 'success',
user: { id: 1, username: 'me', role: 'user', has_completed_onboarding: true, privacy: { share_location_enabled: false, allow_direct_messages: false } },
})
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [] })
vi.spyOn(libraryApi, 'getPlaylists').mockResolvedValue({ status: 'success', playlists: [] })
})
afterEach(() => {
vi.unstubAllEnvs()
vi.restoreAllMocks()
clearTokens()
})
it('redirects /library to the consolidated My Library page', async () => {
renderAppAt('/library')
expect(await screen.findByRole('heading', { name: 'My Library' })).toBeInTheDocument()
})
it('redirects /social to My Library', async () => {
renderAppAt('/social')
expect(await screen.findByRole('heading', { name: 'My Library' })).toBeInTheDocument()
})
it('redirects /telegram-link to My Library', async () => {
renderAppAt('/telegram-link')
expect(await screen.findByRole('heading', { name: 'My Library' })).toBeInTheDocument()
})
it('does not redirect /playlists - My Library links there for real playlist management', async () => {
renderAppAt('/playlists')
expect(await screen.findByRole('heading', { name: 'Playlists' })).toBeInTheDocument()
})
it('still serves /my-library directly', async () => {
renderAppAt('/my-library')
expect(await screen.findByRole('heading', { name: 'My Library' })).toBeInTheDocument()
})
})
...@@ -2,7 +2,7 @@ import { lazy, Suspense } from 'react' ...@@ -2,7 +2,7 @@ import { lazy, Suspense } from 'react'
import { Navigate, Route, Routes } from 'react-router-dom' import { Navigate, Route, Routes } from 'react-router-dom'
import { ProtectedRoute } from './components/ProtectedRoute' import { ProtectedRoute } from './components/ProtectedRoute'
import { RequireRole } from './components/RequireRole' import { RequireRole } from './components/RequireRole'
import { REMIX_ENABLED } from './config/flags' import { REMIX_ENABLED, MINIMAL_NAV_ENABLED } from './config/flags'
// Lazy, not eager, imports - every page used to ship in one ~590KB bundle loaded before *any* // Lazy, not eager, imports - every page used to ship in one ~590KB bundle loaded before *any*
// route could render, including the very first one someone hits (Login or Library). Splitting // route could render, including the very first one someone hits (Login or Library). Splitting
...@@ -10,6 +10,7 @@ import { REMIX_ENABLED } from './config/flags' ...@@ -10,6 +10,7 @@ import { REMIX_ENABLED } from './config/flags'
// to a route not visited yet fetches its chunk on demand (and caches it for next time). // 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 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 MyLibrary = lazy(() => import('./pages/MyLibrary').then((m) => ({ default: m.MyLibrary })))
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 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 })))
...@@ -47,14 +48,22 @@ export function App() { ...@@ -47,14 +48,22 @@ export function App() {
<Routes> <Routes>
<Route path="/login" element={<Login />} /> <Route path="/login" element={<Login />} />
<Route path="/home" element={protect(<Home />)} /> <Route path="/home" element={protect(<Home />)} />
<Route path="/library" element={protect(<Library />)} /> {/* Prod's minimal nav (see MINIMAL_NAV_ENABLED) collapses Library+Playlists into one
/my-library route; the old routes redirect there instead of 404ing so a stale
link/bookmark still lands somewhere real. Dev keeps both pages fully live. */}
<Route path="/library" element={MINIMAL_NAV_ENABLED ? <Navigate to="/my-library" replace /> : protect(<Library />)} />
<Route path="/my-library" element={protect(<MyLibrary />)} />
<Route path="/library/album" element={protect(<AlbumDetail />)} /> <Route path="/library/album" element={protect(<AlbumDetail />)} />
<Route path="/library/liked" element={protect(<LikedSongs />)} /> <Route path="/library/liked" element={protect(<LikedSongs />)} />
{/* Not redirected even under MINIMAL_NAV_ENABLED, unlike /library above - My Library's
"Your Playlists" section links here for actually creating/opening/downloading a
playlist (see MyLibrary.tsx), the same way it already stays a reachable sub-route
without its own nav entry. Only the standalone nav tab goes away, not the page. */}
<Route path="/playlists" element={protect(<Playlists />)} /> <Route path="/playlists" element={protect(<Playlists />)} />
<Route path="/telegram-link" element={protect(<TelegramLink />)} /> <Route path="/telegram-link" element={MINIMAL_NAV_ENABLED ? <Navigate to="/my-library" replace /> : protect(<TelegramLink />)} />
<Route path="/upload" element={protect(<Upload />)} /> <Route path="/upload" element={protect(<Upload />)} />
<Route path="/discovery" element={protect(<Discovery />)} /> <Route path="/discovery" element={protect(<Discovery />)} />
<Route path="/social" element={protect(<Social />)} /> <Route path="/social" element={MINIMAL_NAV_ENABLED ? <Navigate to="/my-library" replace /> : protect(<Social />)} />
<Route path="/dm/:threadId" element={protect(<DMThreadView />)} /> <Route path="/dm/:threadId" element={protect(<DMThreadView />)} />
<Route path="/settings" element={protect(<Settings />)} /> <Route path="/settings" element={protect(<Settings />)} />
{/* Gated by a build-time flag (see config/flags.ts) rather than removed - fully built {/* Gated by a build-time flag (see config/flags.ts) rather than removed - fully built
......
import { useTranslation } from 'react-i18next'
import { Heart, Music2 } from 'lucide-react'
import type { AlbumMatch } from '../api/library'
/** Shared between Library's default view and My Library's consolidated view - both need the
* exact same album grid tile, so it's extracted here rather than kept duplicated per-page (see
* lib/albums.ts, extracted for the same reason). */
export function AlbumCard({ album, onOpen }: { album: AlbumMatch; onOpen: () => void }) {
const { t } = useTranslation('library')
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"
>
{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">
<p className="truncate text-sm font-medium text-on-surface">{album.album}</p>
<p className="truncate text-xs text-on-surface-variant">
{album.artist} · {t('trackCount', { count: album.track_count, suffix: album.track_count === 1 ? '' : 's' })}
</p>
</div>
</button>
)
}
/** 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 a separate page. Only
* rendered when the caller actually has at least one liked song. */
export function LikedSongsCard({ count, onOpen }: { count: number; onOpen: () => void }) {
const { t } = useTranslation('library')
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">{t('likedSongs.title')}</p>
<p className="truncate text-xs text-on-surface-variant">{t('songCount', { count, suffix: count === 1 ? '' : 's' })}</p>
</div>
</button>
)
}
import { render, screen } from '@testing-library/react'
import { MemoryRouter } from 'react-router-dom'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { Layout } from './Layout'
import { AuthProvider } from '../context/AuthContext'
import { PlayerProvider } from '../context/PlayerContext'
// Separate file, not a describe block in Layout.test.tsx - vi.mock is hoisted and fixed for a
// whole file's module graph, so MINIMAL_NAV_ENABLED can't be toggled per-test within one file.
vi.mock('../config/flags', () => ({ MINIMAL_NAV_ENABLED: true, REMIX_ENABLED: false }))
function renderLayout(path: string) {
return render(
<MemoryRouter initialEntries={[path]}>
<AuthProvider>
<PlayerProvider>
<Layout title="Test Page">
<p>Page content</p>
</Layout>
</PlayerProvider>
</AuthProvider>
</MemoryRouter>,
)
}
describe('Layout nav under MINIMAL_NAV_ENABLED', () => {
beforeEach(() => {
vi.stubEnv('VITE_DEV_ACCESS_TOKEN', '')
vi.stubEnv('VITE_DEV_REFRESH_TOKEN', '')
})
afterEach(() => {
vi.unstubAllEnvs()
vi.restoreAllMocks()
})
it('shows one My Library entry instead of separate Library and Playlists entries', () => {
renderLayout('/my-library')
expect(screen.getAllByRole('link', { name: 'My Library' }).length).toBeGreaterThan(0)
expect(screen.queryByRole('link', { name: 'Library' })).not.toBeInTheDocument()
expect(screen.queryByRole('link', { name: 'Playlists' })).not.toBeInTheDocument()
})
it('hides Social and Telegram from the nav entirely', () => {
renderLayout('/my-library')
expect(screen.queryByRole('link', { name: 'Social' })).not.toBeInTheDocument()
expect(screen.queryByRole('link', { name: 'Telegram' })).not.toBeInTheDocument()
})
it('still shows Home, Upload, Discover, Soundmarks, and Settings', () => {
renderLayout('/my-library')
for (const name of ['Home', 'Upload', 'Discover', 'Soundmarks', 'Settings']) {
expect(screen.getAllByRole('link', { name }).length).toBeGreaterThan(0)
}
})
it('marks My Library as the active page when on /my-library', () => {
renderLayout('/my-library')
for (const link of screen.getAllByRole('link', { name: 'My Library' })) {
expect(link).toHaveAttribute('aria-current', 'page')
}
})
})
...@@ -31,7 +31,7 @@ import { InstallBanner } from './InstallBanner' ...@@ -31,7 +31,7 @@ import { InstallBanner } from './InstallBanner'
import { OfflineBanner } from './OfflineBanner' import { OfflineBanner } from './OfflineBanner'
import { useBackButtonClose } from '../hooks/useBackButtonClose' import { useBackButtonClose } from '../hooks/useBackButtonClose'
import { useMountTransition } from '../hooks/useMountTransition' import { useMountTransition } from '../hooks/useMountTransition'
import { REMIX_ENABLED } from '../config/flags' import { REMIX_ENABLED, MINIMAL_NAV_ENABLED } from '../config/flags'
const MORE_SHEET_ANIMATION_MS = 300 const MORE_SHEET_ANIMATION_MS = 300
...@@ -51,12 +51,29 @@ const ALL_NAV_ITEMS: { to: string; labelKey: string; icon: LucideIcon }[] = [ ...@@ -51,12 +51,29 @@ const ALL_NAV_ITEMS: { to: string; labelKey: string; icon: LucideIcon }[] = [
{ to: '/settings', labelKey: 'nav.settings', icon: SettingsIcon }, { to: '/settings', labelKey: 'nav.settings', icon: SettingsIcon },
] ]
const NAV_ITEMS = REMIX_ENABLED ? ALL_NAV_ITEMS : ALL_NAV_ITEMS.filter((item) => item.to !== '/remix') // Prod's minimal nav (per explicit direction to keep its launch surface to upload/tag +
// discover + one consolidated library view): /library and /playlists collapse into a single
// /my-library entry, placed where /library used to sit; /social and /telegram-link disappear
// entirely. Dev's nav is untouched - this only takes effect when MINIMAL_NAV_ENABLED is on.
const MINIMAL_NAV_ITEMS: { to: string; labelKey: string; icon: LucideIcon }[] = [
{ to: '/home', labelKey: 'nav.home', icon: Globe },
{ to: '/my-library', labelKey: 'nav.myLibrary', icon: Library },
{ to: '/upload', labelKey: 'nav.upload', icon: Upload },
{ to: '/discovery', labelKey: 'nav.discover', icon: Compass },
{ to: '/soundmarks', labelKey: 'nav.soundmarks', icon: MapPin },
{ to: '/settings', labelKey: 'nav.settings', icon: SettingsIcon },
]
const NAV_ITEMS = MINIMAL_NAV_ENABLED
? MINIMAL_NAV_ITEMS
: REMIX_ENABLED
? ALL_NAV_ITEMS
: ALL_NAV_ITEMS.filter((item) => item.to !== '/remix')
// The 5 most-reached destinations get a fixed mobile tab (matches the design system's // 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 // "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. // sidebar has room to just list all of NAV_ITEMS, so this split is mobile-only.
const MOBILE_TAB_PATHS = new Set(['/home', '/library', '/discovery', '/social', '/soundmarks', '/remix']) const MOBILE_TAB_PATHS = new Set(['/home', '/library', '/my-library', '/discovery', '/social', '/soundmarks', '/remix'])
const mobileTabs = NAV_ITEMS.filter((item) => MOBILE_TAB_PATHS.has(item.to)) const mobileTabs = NAV_ITEMS.filter((item) => MOBILE_TAB_PATHS.has(item.to))
const overflowItems = NAV_ITEMS.filter((item) => !MOBILE_TAB_PATHS.has(item.to)) const overflowItems = NAV_ITEMS.filter((item) => !MOBILE_TAB_PATHS.has(item.to))
......
...@@ -13,3 +13,13 @@ export const REMIX_ENABLED = import.meta.env.VITE_ENABLE_REMIX === 'true' ...@@ -13,3 +13,13 @@ export const REMIX_ENABLED = import.meta.env.VITE_ENABLE_REMIX === 'true'
// switcher in Settings.tsx only renders the فارسی option when this is on. Set // switcher in Settings.tsx only renders the فارسی option when this is on. Set
// VITE_ENABLE_FARSI=true at build time once it's ready to go live. // VITE_ENABLE_FARSI=true at build time once it's ready to go live.
export const FARSI_ENABLED = import.meta.env.VITE_ENABLE_FARSI === 'true' export const FARSI_ENABLED = import.meta.env.VITE_ENABLE_FARSI === 'true'
// Inverse polarity from the flags above on purpose: this one *restricts* scope rather than
// unlocking it. Off by default (full nav - every page built so far, same as today). Prod's
// build sets VITE_MINIMAL_NAV=true to cut the nav down to upload/tag + discover + a single
// consolidated library tab, per explicit direction to keep prod's launch surface small.
// /social, /telegram-link, and /library redirect to /my-library (see App.tsx) rather than
// 404 if this flips on with something still linking to them. /playlists is the one exception -
// it stays reachable (no nav entry, same as /library/album) since My Library's own "Your
// Playlists" section links there to actually create/open/download a playlist.
export const MINIMAL_NAV_ENABLED = import.meta.env.VITE_MINIMAL_NAV === 'true'
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
"nav.home": "Home", "nav.home": "Home",
"nav.library": "Library", "nav.library": "Library",
"nav.playlists": "Playlists", "nav.playlists": "Playlists",
"nav.myLibrary": "My Library",
"nav.upload": "Upload", "nav.upload": "Upload",
"nav.discover": "Discover", "nav.discover": "Discover",
"nav.social": "Social", "nav.social": "Social",
......
{
"title": "My Library",
"section.latestUpload": "Latest Upload",
"section.playlists": "Your Playlists",
"section.manage": "Manage",
"section.albums": "Albums",
"empty.noSongs": "Nothing here yet - upload a song to get started.",
"empty.noPlaylists": "No playlists yet - create one in Playlists.",
"error.loadFailed": "Failed to load your library",
"error.deleteFailed": "Could not delete \"{{title}}\"",
"deleteConfirm": "Delete \"{{title}}\"? This can't be undone."
}
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
"nav.home": "خانه", "nav.home": "خانه",
"nav.library": "کتابخانه", "nav.library": "کتابخانه",
"nav.playlists": "پلی‌لیست‌ها", "nav.playlists": "پلی‌لیست‌ها",
"nav.myLibrary": "کتابخانه من",
"nav.upload": "بارگذاری", "nav.upload": "بارگذاری",
"nav.discover": "کاوش", "nav.discover": "کاوش",
"nav.social": "اجتماعی", "nav.social": "اجتماعی",
......
{
"title": "کتابخانه من",
"section.latestUpload": "آخرین بارگذاری",
"section.playlists": "پلی‌لیست‌های شما",
"section.manage": "مدیریت",
"section.albums": "آلبوم‌ها",
"empty.noSongs": "هنوز چیزی اینجا نیست - یک آهنگ بارگذاری کن تا شروع شود.",
"empty.noPlaylists": "هنوز پلی‌لیستی نیست - یکی را در پلی‌لیست‌ها بساز.",
"error.loadFailed": "بارگذاری کتابخانه تو ممکن نشد",
"error.deleteFailed": "حذف «{{title}}» ممکن نشد",
"deleteConfirm": "«{{title}}» حذف شود؟ این کار قابل بازگشت نیست."
}
import type { AlbumMatch, LibrarySong } from '../api/library'
/** Client-side mirror of /library/search's (album, artist) grouping - several pages need the
* same album grid (Library's default view, My Library's consolidated view) but there's no
* reason to round-trip to the backend for it: the full song list (with each song's own album/
* coverart) is already loaded, so it's derived here instead of adding a second endpoint that
* returns the same shape. Skips songs with no album, same as the backend does. Track order
* within each group doesn't matter here - the album detail page fetches its own real ordering,
* this is only used for the grid's cover art / track count / navigation target. */
export function groupIntoAlbums(songs: LibrarySong[]): AlbumMatch[] {
const byKey = new Map<string, AlbumMatch>()
for (const song of songs) {
if (!song.album) continue
const key = `${song.album}::${song.artist}`
const entry = byKey.get(key)
if (entry) {
entry.songs.push(song)
entry.track_count += 1
if (!entry.coverart && song.coverart) entry.coverart = song.coverart
} else {
byKey.set(key, { album: song.album, artist: song.artist, coverart: song.coverart, track_count: 1, songs: [song] })
}
}
return Array.from(byKey.values())
}
export function albumHref(album: { album: string; artist: string }): string {
return `/library/album?${new URLSearchParams({ album: album.album, artist: album.artist })}`
}
import { useEffect, useMemo, useState } from 'react' import { useEffect, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
import { Globe2, Heart, Music2, Search } from 'lucide-react' import { Globe2, Music2, Search } from 'lucide-react'
import { useNavigate } from 'react-router-dom' import { useNavigate } from 'react-router-dom'
import { import {
deleteLibrarySong, deleteLibrarySong,
...@@ -13,89 +13,16 @@ import { ...@@ -13,89 +13,16 @@ import {
type LibrarySong, type LibrarySong,
} from '../api/library' } from '../api/library'
import { ApiError } from '../api/client' import { ApiError } from '../api/client'
import { groupIntoAlbums, albumHref } from '../lib/albums'
import { Layout } from '../components/Layout' import { Layout } from '../components/Layout'
import { AddToPlaylistModal } from '../components/AddToPlaylistModal' import { AddToPlaylistModal } from '../components/AddToPlaylistModal'
import { AlbumCard, LikedSongsCard } from '../components/AlbumCard'
import { SongRow } from '../components/SongRow' import { SongRow } from '../components/SongRow'
import { SharedSongRow } from '../components/SharedSongRow' import { SharedSongRow } from '../components/SharedSongRow'
import { Input } from '../components/ui/Input' import { Input } from '../components/ui/Input'
import { SkeletonRow } from '../components/ui/Skeleton' import { SkeletonRow } from '../components/ui/Skeleton'
import { EmptyState } from '../components/ui/EmptyState' import { EmptyState } from '../components/ui/EmptyState'
/** Client-side mirror of /library/search's (album, artist) grouping - the default library view
* needs the same album grid the search results get, but there's no reason to round-trip to the
* backend for it: the full song list (with each song's own album/coverart) is already loaded,
* so it's derived here instead of adding a second endpoint that returns the same shape. Skips
* songs with no album, same as the backend does. Track order within each group doesn't matter
* here - the album detail page fetches its own real ordering, this is only used for the grid's
* cover art / track count / navigation target. */
function groupIntoAlbums(songs: LibrarySong[]): AlbumMatch[] {
const byKey = new Map<string, AlbumMatch>()
for (const song of songs) {
if (!song.album) continue
const key = `${song.album}::${song.artist}`
const entry = byKey.get(key)
if (entry) {
entry.songs.push(song)
entry.track_count += 1
if (!entry.coverart && song.coverart) entry.coverart = song.coverart
} else {
byKey.set(key, { album: song.album, artist: song.artist, coverart: song.coverart, track_count: 1, songs: [song] })
}
}
return Array.from(byKey.values())
}
function albumHref(album: { album: string; artist: string }): string {
return `/library/album?${new URLSearchParams({ album: album.album, artist: album.artist })}`
}
function AlbumCard({ album, onOpen }: { album: AlbumMatch; onOpen: () => void }) {
const { t } = useTranslation('library')
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"
>
{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">
<p className="truncate text-sm font-medium text-on-surface">{album.album}</p>
<p className="truncate text-xs text-on-surface-variant">
{album.artist} · {t('trackCount', { count: album.track_count, suffix: album.track_count === 1 ? '' : 's' })}
</p>
</div>
</button>
)
}
/** 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 }) {
const { t } = useTranslation('library')
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">{t('likedSongs.title')}</p>
<p className="truncate text-xs text-on-surface-variant">{t('songCount', { count, suffix: count === 1 ? '' : 's' })}</p>
</div>
</button>
)
}
type SearchScope = 'mine' | 'shared' type SearchScope = 'mine' | 'shared'
export function Library() { export function Library() {
......
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { MyLibrary } from './MyLibrary'
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 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: false,
}
const NEWER_SONG = { ...SONG, id: 2, title: 'Rio', album: 'Rio', added_at: '2026-02-01T00:00:00Z' }
const LIKED_PLAYLIST = { id: 1, user_id: 1, name: 'Liked Songs', created_at: '2026-01-01T00:00:00Z', is_liked_playlist: true }
const OWN_PLAYLIST = { id: 2, user_id: 1, name: 'Road Trip', created_at: '2026-01-02T00:00:00Z', is_liked_playlist: false }
// Fires the full pointer drag sequence useSwipeAction listens for, same as Library.test.tsx.
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 renderMyLibrary() {
return render(
<MemoryRouter>
<AuthProvider>
<PlayerProvider>
<Routes>
<Route path="/" element={<MyLibrary />} />
<Route path="/playlists" element={<p>Playlists route</p>} />
<Route path="/library/album" element={<p>Album route</p>} />
<Route path="/library/liked" element={<p>Liked Songs route</p>} />
</Routes>
</PlayerProvider>
</AuthProvider>
</MemoryRouter>,
)
}
describe('MyLibrary', () => {
beforeEach(() => {
vi.stubEnv('VITE_DEV_ACCESS_TOKEN', '')
vi.stubEnv('VITE_DEV_REFRESH_TOKEN', '')
vi.spyOn(libraryApi, 'getPlaylists').mockResolvedValue({ status: 'success', playlists: [] })
})
afterEach(() => {
vi.unstubAllEnvs()
vi.restoreAllMocks()
})
it('shows the empty state when there are no songs and no playlists', async () => {
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [] })
renderMyLibrary()
expect(await screen.findByText(/Nothing here yet/)).toBeInTheDocument()
})
it('shows the single most-recently-uploaded song as the Latest Upload', async () => {
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [SONG, NEWER_SONG] })
renderMyLibrary()
const heading = await screen.findByRole('heading', { name: 'Latest Upload' })
const section = heading.closest('div')!
expect(within(section).getByText('Rio')).toBeInTheDocument()
expect(within(section).queryByText('Invisible')).not.toBeInTheDocument()
})
it('does not show a Latest Upload section when the library is empty', async () => {
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [] })
renderMyLibrary()
await screen.findByText(/Nothing here yet/)
expect(screen.queryByRole('heading', { name: 'Latest Upload' })).not.toBeInTheDocument()
})
it('lists the caller\'s own playlists, excluding the system Liked Songs playlist', async () => {
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [] })
vi.spyOn(libraryApi, 'getPlaylists').mockResolvedValue({ status: 'success', playlists: [LIKED_PLAYLIST, OWN_PLAYLIST] })
renderMyLibrary()
expect(await screen.findByText('Road Trip')).toBeInTheDocument()
expect(screen.queryByText('Liked Songs')).not.toBeInTheDocument()
})
it('shows a message and link to Playlists when the caller has no playlists of their own', async () => {
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [] })
vi.spyOn(libraryApi, 'getPlaylists').mockResolvedValue({ status: 'success', playlists: [] })
renderMyLibrary()
await userEvent.click(await screen.findByText(/No playlists yet/))
expect(await screen.findByText('Playlists route')).toBeInTheDocument()
})
it('navigates to the Playlists page when a playlist row is tapped', async () => {
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [] })
vi.spyOn(libraryApi, 'getPlaylists').mockResolvedValue({ status: 'success', playlists: [OWN_PLAYLIST] })
renderMyLibrary()
await userEvent.click(await screen.findByText('Road Trip'))
expect(await screen.findByText('Playlists route')).toBeInTheDocument()
})
it('shows an Albums grid with a Liked Songs card and navigates to the liked songs page', async () => {
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [{ ...SONG, is_liked: true }] })
renderMyLibrary()
await userEvent.click(await screen.findByText('Liked Songs'))
expect(await screen.findByText('Liked Songs route')).toBeInTheDocument()
})
it('navigates to the album detail page when an album card is tapped', async () => {
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [SONG] })
renderMyLibrary()
await userEvent.click(await screen.findByRole('button', { name: /Astronaut/ }))
expect(await screen.findByText('Album route')).toBeInTheDocument()
})
it('shows a load error using the ApiError message', async () => {
vi.spyOn(libraryApi, 'getLibrary').mockRejectedValue(new ApiError(500, 'Server exploded', null))
renderMyLibrary()
expect(await screen.findByText('Server exploded')).toBeInTheDocument()
})
it('plays the latest upload via its row, same as a normal SongRow', async () => {
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [SONG] })
const fetchStreamUrl = vi.spyOn(streamApi, 'fetchStreamUrl').mockResolvedValue('blob:fake-url')
renderMyLibrary()
const row = (await screen.findByText('Invisible')).closest('li')!
await userEvent.click(within(row).getByRole('button', { name: 'Play' }))
await waitFor(() => expect(fetchStreamUrl).toHaveBeenCalledWith(1))
})
it('deletes the latest upload song when confirmed via swipe-to-delete', async () => {
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [SONG] })
const deleteLibrarySong = vi.spyOn(libraryApi, 'deleteLibrarySong').mockResolvedValue({ status: 'success' })
vi.spyOn(window, 'confirm').mockReturnValue(true)
renderMyLibrary()
const row = (await screen.findByText('Invisible')).closest('li')!
swipe(within(row).getByRole('button', { name: 'Play' }), 0, -100)
await waitFor(() => expect(deleteLibrarySong).toHaveBeenCalledWith(1))
await waitFor(() => expect(screen.queryByText('Invisible')).not.toBeInTheDocument())
})
})
import { useEffect, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useNavigate } from 'react-router-dom'
import { ListMusic, Music2 } from 'lucide-react'
import { deleteLibrarySong, favoriteSong, getLibrary, getPlaylists, unfavoriteSong, type LibrarySong, type Playlist } from '../api/library'
import { ApiError } from '../api/client'
import { groupIntoAlbums, albumHref } from '../lib/albums'
import { Layout } from '../components/Layout'
import { AddToPlaylistModal } from '../components/AddToPlaylistModal'
import { AlbumCard, LikedSongsCard } from '../components/AlbumCard'
import { SongRow } from '../components/SongRow'
import { SkeletonRow } from '../components/ui/Skeleton'
import { EmptyState } from '../components/ui/EmptyState'
/** Prod's minimal nav (see MINIMAL_NAV_ENABLED) collapses the separate Library and Playlists
* tabs into this single consolidated view - per explicit direction: latest upload, the caller's
* own playlists, and their liked/uploaded albums, all in one place. Dev keeps the full separate
* Library/Playlists pages; this page reuses the same data/components those pages already use
* (groupIntoAlbums, AlbumCard/LikedSongsCard, SongRow) rather than duplicating their logic. */
export function MyLibrary() {
const { t } = useTranslation('myLibrary')
const navigate = useNavigate()
const [songs, setSongs] = useState<LibrarySong[]>([])
const [playlists, setPlaylists] = useState<Playlist[]>([])
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 albums = useMemo(() => groupIntoAlbums(songs), [songs])
const likedCount = useMemo(() => songs.filter((s) => s.is_liked).length, [songs])
// Newest first by added_at - the single most-recently-uploaded song, not the whole list.
const latestSong = useMemo(
() => (songs.length === 0 ? null : [...songs].sort((a, b) => new Date(b.added_at).getTime() - new Date(a.added_at).getTime())[0]),
[songs],
)
// The auto-created Liked Songs playlist already has its own card above (LikedSongsCard) -
// listing it again here would just be the same destination twice under two different names.
const ownPlaylists = useMemo(() => playlists.filter((p) => !p.is_liked_playlist), [playlists])
useEffect(() => {
Promise.all([getLibrary(), getPlaylists()])
.then(([libraryRes, playlistsRes]) => {
setSongs(libraryRes.library)
setPlaylists(playlistsRes.playlists)
})
.catch((err) => setError(err instanceof ApiError ? err.message : t('error.loadFailed')))
.finally(() => setLoading(false))
}, [])
async function handleDelete(song: LibrarySong) {
if (!window.confirm(t('deleteConfirm', { title: song.title }))) 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 : t('error.deleteFailed', { title: song.title }))
}
}
function setSongLiked(song: LibrarySong, liked: boolean) {
setSongs((prev) => prev.map((s) => (s.id === song.id ? { ...s, is_liked: liked } : s)))
}
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))
}
const isEmpty = !loading && !error && songs.length === 0 && ownPlaylists.length === 0
return (
<Layout title={t('title')}>
{loading && (
<div className="space-y-1">
<SkeletonRow />
<SkeletonRow />
</div>
)}
{error && <p className="text-sm text-error">{error}</p>}
{deleteError && <p className="text-sm text-error">{deleteError}</p>}
{isEmpty && <EmptyState icon={Music2} message={t('empty.noSongs')} />}
{!loading && !error && (
<div className="animate-content-enter">
{latestSong && (
<div className="mb-8">
<h2 className="mb-2 text-xs font-semibold uppercase tracking-[0.1em] text-primary">{t('section.latestUpload')}</h2>
<ul className="space-y-1">
<SongRow
song={latestSong}
queue={[latestSong]}
onAddToPlaylist={setAddingSong}
onDelete={handleDelete}
onToggleFavorite={handleToggleFavorite}
/>
</ul>
</div>
)}
<div className="mb-8">
<div className="mb-2 flex items-center justify-between">
<h2 className="text-xs font-semibold uppercase tracking-[0.1em] text-primary">{t('section.playlists')}</h2>
<button onClick={() => navigate('/playlists')} className="text-xs font-medium text-on-surface-variant transition-colors hover:text-on-surface">
{t('section.manage')}
</button>
</div>
{ownPlaylists.length === 0 ? (
<button
onClick={() => navigate('/playlists')}
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">
<ListMusic size={18} strokeWidth={1.75} />
</div>
<p className="truncate text-sm text-on-surface-variant">{t('empty.noPlaylists')}</p>
</button>
) : (
<ul className="space-y-1">
{ownPlaylists.map((playlist) => (
<li key={playlist.id}>
<button
onClick={() => navigate('/playlists')}
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">
<ListMusic size={18} strokeWidth={1.75} />
</div>
<p className="min-w-0 flex-1 truncate font-medium text-on-surface">{playlist.name}</p>
</button>
</li>
))}
</ul>
)}
</div>
{(albums.length > 0 || likedCount > 0) && (
<div>
<h2 className="mb-3 text-xs font-semibold uppercase tracking-[0.1em] text-primary">{t('section.albums')}</h2>
<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) => (
<AlbumCard key={`${album.album}::${album.artist}`} album={album} onOpen={() => navigate(albumHref(album))} />
))}
</div>
</div>
)}
</div>
)}
{addingSong && <AddToPlaylistModal song={addingSong} onClose={() => setAddingSong(null)} />}
</Layout>
)
}
...@@ -15,7 +15,7 @@ import * as authApi from '../api/auth' ...@@ -15,7 +15,7 @@ import * as authApi from '../api/auth'
// test time since no build sets VITE_ENABLE_FARSI=true - mocking it on so the switcher actually // test time since no build sets VITE_ENABLE_FARSI=true - mocking it on so the switcher actually
// renders for the one test below that exercises it. Doesn't affect any other test in this file: // renders for the one test below that exercises it. Doesn't affect any other test in this file:
// none of them assert on the full button/switch list, only on specific named roles. // none of them assert on the full button/switch list, only on specific named roles.
vi.mock('../config/flags', () => ({ FARSI_ENABLED: true, REMIX_ENABLED: false })) vi.mock('../config/flags', () => ({ FARSI_ENABLED: true, REMIX_ENABLED: false, MINIMAL_NAV_ENABLED: false }))
function renderSettings() { function renderSettings() {
return render( return render(
......
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