Commit 48490dae authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Move Upload inline into My Library instead of its own nav tab

Prod feedback: upload shouldn't be a separate destination - it belongs
inside the library view itself. Extracts the dropzone/queue UI into a
shared UploadPanel used by both the standalone dev /upload page and an
inline section at the top of My Library; /upload now redirects to
/my-library under MINIMAL_NAV_ENABLED, same as the other merged routes.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 0854f96b
Pipeline #1299 failed with stages
......@@ -4,9 +4,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { App } from './App'
import { AuthProvider } from './context/AuthContext'
import { PlayerProvider } from './context/PlayerContext'
import { UploadQueueProvider } from './context/UploadQueueContext'
import { setTokens, clearTokens } from './api/client'
import * as authApi from './api/auth'
import * as libraryApi from './api/library'
import * as musicApi from './api/music'
// 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
......@@ -18,7 +20,9 @@ function renderAppAt(path: string) {
<MemoryRouter initialEntries={[path]}>
<AuthProvider>
<PlayerProvider>
<App />
<UploadQueueProvider>
<App />
</UploadQueueProvider>
</PlayerProvider>
</AuthProvider>
</MemoryRouter>,
......@@ -36,6 +40,9 @@ describe('App routing under MINIMAL_NAV_ENABLED', () => {
})
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [] })
vi.spyOn(libraryApi, 'getPlaylists').mockResolvedValue({ status: 'success', playlists: [] })
// My Library now embeds the upload panel inline (see MyLibrary.tsx) - its queue context
// reconciles against this on mount, same as Upload.test.tsx's own default mock.
vi.spyOn(musicApi, 'listUploadJobs').mockResolvedValue({ status: 'success', jobs: [] })
})
afterEach(() => {
......@@ -59,6 +66,11 @@ describe('App routing under MINIMAL_NAV_ENABLED', () => {
expect(await screen.findByRole('heading', { name: 'My Library' })).toBeInTheDocument()
})
it('redirects /upload to My Library - upload lives inline there, not as its own page', async () => {
renderAppAt('/upload')
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()
......
......@@ -66,7 +66,9 @@ export function App() {
without its own nav entry. Only the standalone nav tab goes away, not the page. */}
<Route path="/playlists" element={protect(<Playlists />)} />
<Route path="/telegram-link" element={MINIMAL_NAV_ENABLED ? <Navigate to="/my-library" replace /> : protect(<TelegramLink />)} />
<Route path="/upload" element={protect(<Upload />)} />
{/* Upload lives inline inside My Library under the minimal nav (see MyLibrary.tsx's
embedded UploadPanel) rather than as its own page - redirect same as /library etc. */}
<Route path="/upload" element={MINIMAL_NAV_ENABLED ? <Navigate to="/my-library" replace /> : protect(<Upload />)} />
<Route path="/discovery" element={protect(<Discovery />, { allowGuest: true })} />
<Route path="/social" element={MINIMAL_NAV_ENABLED ? <Navigate to="/my-library" replace /> : protect(<Social />)} />
<Route path="/dm/:threadId" element={protect(<DMThreadView />)} />
......
......@@ -59,14 +59,20 @@ describe('Layout nav under MINIMAL_NAV_ENABLED', () => {
expect(screen.queryByRole('link', { name: 'Telegram' })).not.toBeInTheDocument()
})
it('still shows Home, Upload, Discover, Soundmarks, and Settings', () => {
it('still shows Home, Discover, Soundmarks, and Settings', () => {
renderLayout('/my-library')
for (const name of ['Home', 'Upload', 'Discover', 'Soundmarks', 'Settings']) {
for (const name of ['Home', 'Discover', 'Soundmarks', 'Settings']) {
expect(screen.getAllByRole('link', { name }).length).toBeGreaterThan(0)
}
})
it('does not show Upload as its own nav entry - it lives inline inside My Library', () => {
renderLayout('/my-library')
expect(screen.queryByRole('link', { name: 'Upload' })).not.toBeInTheDocument()
})
it('marks My Library as the active page when on /my-library', () => {
renderLayout('/my-library')
......
......@@ -52,14 +52,15 @@ const ALL_NAV_ITEMS: { to: string; labelKey: string; icon: LucideIcon }[] = [
{ to: '/settings', labelKey: 'nav.settings', icon: SettingsIcon },
]
// 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.
// Prod's minimal nav (per explicit direction to keep its launch surface to 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.
// /upload isn't a nav destination here either - it lives inline inside My Library itself (see
// MyLibrary.tsx's embedded UploadPanel) per explicit direction that upload shouldn't be its
// own tab. 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 },
......
import { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { Check, Circle, ListPlus, Pause, Pencil, Play, UploadCloud, X } from 'lucide-react'
import { Button } from './ui/Button'
import { AddToPlaylistModal } from './AddToPlaylistModal'
import { useUploadQueue, type UploadItem } from '../context/UploadQueueContext'
import { usePlayer, type PlayableSong } from '../context/PlayerContext'
import { editLibrarySong } from '../api/library'
// The upload+identify+tag pipeline is one opaque network call server-side (see api/music.ts'
// own comment) - there's no real per-step progress to report once the byte upload finishes.
// This sub-step split is presentational, not a literal trace of server state: both phases
// genuinely happen in this order server-side (identify_audio runs Shazam/AcoustID before
// fetch_lyrics/artwork), just without a real boundary signal to switch on, hence the fixed
// delay rather than claiming precision the backend doesn't give us.
const PROCESSING_SUBSTEP_DELAY_MS = 3000
function useProcessingSubstep(active: boolean): 0 | 1 {
const [substep, setSubstep] = useState<0 | 1>(0)
useEffect(() => {
if (!active) {
setSubstep(0)
return
}
const timer = setTimeout(() => setSubstep(1), PROCESSING_SUBSTEP_DELAY_MS)
return () => clearTimeout(timer)
}, [active])
return substep
}
type StepState = 'done' | 'active' | 'pending'
function StepRow({ state, label }: { state: StepState; label: string }) {
return (
<div className="flex items-center gap-2.5 text-sm">
{state === 'done' && <Check size={15} strokeWidth={2.5} className="shrink-0 text-primary" />}
{state === 'active' && (
<span className="h-[15px] w-[15px] shrink-0 animate-spin rounded-full border-2 border-outline-variant border-t-primary" />
)}
{state === 'pending' && <Circle size={15} strokeWidth={2} className="shrink-0 text-outline-variant" />}
<span className={state === 'pending' ? 'text-on-surface-variant' : 'text-on-surface'}>{label}</span>
</div>
)
}
function UploadSteps({ item }: { item: UploadItem }) {
const { t } = useTranslation('upload')
const substep = useProcessingSubstep(item.stage === 'processing')
const uploadState: StepState = item.stage === 'uploading' ? 'active' : 'done'
const identifyState: StepState = item.stage === 'uploading' ? 'pending' : item.stage === 'processing' && substep === 0 ? 'active' : 'done'
const artworkState: StepState =
item.stage === 'uploading' || (item.stage === 'processing' && substep === 0) ? 'pending' : item.stage === 'processing' ? 'active' : 'done'
return (
<div className="mt-3 space-y-2">
<StepRow state={uploadState} label={item.stage === 'uploading' ? t('steps.uploading', { percent: item.uploadPercent }) : t('steps.uploaded')} />
<StepRow state={identifyState} label={t('steps.identifying')} />
<StepRow state={artworkState} label={t('steps.artwork')} />
</div>
)
}
// Below this, confidence reads as "maybe" rather than "probably" - rough enough that an
// uploader should actually look at the result instead of trusting it blindly, but not so low
// a threshold that most real matches (which tend to land in the 80-100 range) get flagged.
const LOW_CONFIDENCE_THRESHOLD = 60
function ConfidenceBadge({ confidence }: { confidence: number }) {
const { t } = useTranslation('upload')
const low = confidence < LOW_CONFIDENCE_THRESHOLD
return (
<span
className={`inline-flex shrink-0 items-center gap-1 rounded-full px-2 py-0.5 text-xs font-medium ${
low ? 'bg-error-container text-on-error-container' : 'bg-primary-container text-on-primary-container'
}`}
>
{t('confidence.match', { percent: Math.round(confidence) })}
</span>
)
}
function EditDetailsForm({
item,
onCancel,
onSaved,
}: {
item: UploadItem
onCancel: () => void
onSaved: (fields: { title: string; artist: string; album: string; genre: string }) => void
}) {
const { t } = useTranslation('upload')
const metadata = item.result!.metadata
const [title, setTitle] = useState(metadata.title)
const [artist, setArtist] = useState(metadata.artist)
const [album, setAlbum] = useState(metadata.album)
const [genre, setGenre] = useState(metadata.genre)
const [saving, setSaving] = useState(false)
const [error, setError] = useState<string | null>(null)
async function handleSave() {
setSaving(true)
setError(null)
try {
await editLibrarySong(metadata.library_song_id, { title, artist, album, genre })
onSaved({ title, artist, album, genre })
} catch (err) {
setError(err instanceof Error ? err.message : t('error.editFailed'))
} finally {
setSaving(false)
}
}
return (
<div className="mt-3 space-y-2 border-t border-outline-variant pt-3">
<input
value={title}
onChange={(e) => setTitle(e.target.value)}
aria-label={t('edit.titleLabel')}
placeholder={t('edit.titleLabel')}
className="w-full rounded-lg border border-outline-variant bg-surface px-3 py-2 text-sm text-on-surface focus:outline-none focus-visible:ring-2 focus-visible:ring-primary"
/>
<input
value={artist}
onChange={(e) => setArtist(e.target.value)}
aria-label={t('edit.artistLabel')}
placeholder={t('edit.artistLabel')}
className="w-full rounded-lg border border-outline-variant bg-surface px-3 py-2 text-sm text-on-surface focus:outline-none focus-visible:ring-2 focus-visible:ring-primary"
/>
<input
value={album}
onChange={(e) => setAlbum(e.target.value)}
aria-label={t('edit.albumLabel')}
placeholder={t('edit.albumLabel')}
className="w-full rounded-lg border border-outline-variant bg-surface px-3 py-2 text-sm text-on-surface focus:outline-none focus-visible:ring-2 focus-visible:ring-primary"
/>
<input
value={genre}
onChange={(e) => setGenre(e.target.value)}
aria-label={t('edit.genreLabel')}
placeholder={t('edit.genreLabel')}
className="w-full rounded-lg border border-outline-variant bg-surface px-3 py-2 text-sm text-on-surface focus:outline-none focus-visible:ring-2 focus-visible:ring-primary"
/>
{error && <p className="text-sm text-error">{error}</p>}
<p className="text-xs text-on-surface-variant">{t('edit.pendingNotice')}</p>
<div className="flex gap-2">
<Button onClick={handleSave} disabled={saving} className="flex-1">
{saving ? t('edit.saving') : t('edit.save')}
</Button>
<Button onClick={onCancel} disabled={saving} variant="secondary" className="flex-1">
{t('edit.cancel')}
</Button>
</div>
</div>
)
}
function UploadItemRow({
item,
isCurrent,
isPlaying,
streamLoading,
onToggle,
onRemove,
onAddToPlaylist,
}: {
item: UploadItem
isCurrent: boolean
isPlaying: boolean
streamLoading: boolean
onToggle: (song: PlayableSong) => void
onRemove: () => void
onAddToPlaylist: () => void
}) {
const { t } = useTranslation('upload')
const { patchItemMetadata } = useUploadQueue()
const [editing, setEditing] = useState(false)
if (item.stage === 'done' && item.result) {
const { metadata } = item.result
return (
<div className="rounded-xl border border-outline-variant bg-surface-container p-3">
{/* Tapping anywhere on the card plays it, not just a small button - the icon on the
right is a status indicator rendered inside this same button. Add to playlist
stays a separate control below since it's a genuinely different action. */}
<button
onClick={() =>
onToggle({
id: metadata.library_song_id,
title: metadata.title,
artist: metadata.artist,
album: metadata.album,
coverart: metadata.cover_art,
lyrics: metadata.lyrics,
})
}
disabled={isCurrent && streamLoading}
aria-label={isCurrent && isPlaying ? t('aria.pause') : t('aria.play')}
className="flex w-full items-center gap-4 rounded-lg p-1 text-left transition-colors hover:bg-surface-container focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed"
>
{metadata.cover_art ? (
<img src={metadata.cover_art} alt="" className="h-16 w-16 shrink-0 rounded-lg object-cover" />
) : (
<div className="flex h-16 w-16 shrink-0 items-center justify-center rounded-lg bg-surface-container-high text-on-surface-variant">
<Play size={20} strokeWidth={1.75} />
</div>
)}
<div className="min-w-0 flex-1">
<p className="truncate font-semibold text-on-surface">{metadata.title}</p>
<p className="truncate text-sm text-on-surface-variant">
{metadata.artist} · {metadata.album} · {metadata.genre}
</p>
</div>
<span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-surface-container-high text-on-surface">
{isCurrent && streamLoading ? (
<span className="h-3.5 w-3.5 animate-spin rounded-full border-2 border-outline-variant border-t-on-surface" />
) : isCurrent && isPlaying ? (
<Pause size={16} strokeWidth={2} fill="currentColor" />
) : (
<Play size={16} strokeWidth={2} fill="currentColor" className="ml-0.5" />
)}
</span>
</button>
<div className="mt-1 flex flex-wrap items-center gap-2 px-1">
<button
onClick={onAddToPlaylist}
className="flex items-center gap-1.5 py-1 text-sm text-on-surface-variant transition-colors hover:text-on-surface focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"
>
<ListPlus size={15} strokeWidth={1.75} />
{t('button.addToPlaylist')}
</button>
{!editing && (
<button
onClick={() => setEditing(true)}
className="flex items-center gap-1.5 py-1 text-sm text-on-surface-variant transition-colors hover:text-on-surface focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"
>
<Pencil size={14} strokeWidth={1.75} />
{t('edit.editDetails')}
</button>
)}
<span className="flex-1" />
{typeof metadata.confidence === 'number' && <ConfidenceBadge confidence={metadata.confidence} />}
{metadata.review_status === 'pending' && (
<span className="inline-flex shrink-0 items-center rounded-full bg-surface-container-high px-2 py-0.5 text-xs font-medium text-on-surface-variant">
{t('edit.communityNoted')}
</span>
)}
</div>
{editing && (
<EditDetailsForm
item={item}
onCancel={() => setEditing(false)}
onSaved={(fields) => {
patchItemMetadata(item.id, { ...fields, review_status: 'pending' })
setEditing(false)
}}
/>
)}
</div>
)
}
return (
<div className="rounded-xl border border-outline-variant bg-surface-container p-3">
<div className="flex items-center gap-3">
<p className="min-w-0 flex-1 truncate text-sm text-on-surface">{item.filename}</p>
{item.stage === 'queued' && (
<button
onClick={onRemove}
aria-label={t('aria.remove', { filename: item.filename })}
className="shrink-0 rounded-full p-1 text-on-surface-variant transition-colors hover:bg-surface-container-high hover:text-on-surface focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"
>
<X size={16} strokeWidth={2} />
</button>
)}
</div>
{(item.stage === 'uploading' || item.stage === 'processing') && <UploadSteps item={item} />}
{item.stage === 'error' && <p className="mt-2 text-sm text-error">{item.error ?? t('error.uploadFailed')}</p>}
</div>
)
}
/** The actual upload+tag UI - shared by the standalone /upload page (dev's full nav) and
* embedded directly inside My Library (prod's minimal nav, per explicit direction that upload
* should live inside the library view rather than be its own nav destination). Renders with no
* outer Layout/heading of its own so either caller can place it freely. */
export function UploadPanel() {
const { t } = useTranslation('upload')
const { items, busy, addFiles, removeItem, uploadAll } = useUploadQueue()
const [addingToPlaylistId, setAddingToPlaylistId] = useState<string | null>(null)
const { currentSong, isPlaying, isLoading: streamLoading, toggle } = usePlayer()
const queuedCount = items.filter((it) => it.stage === 'queued').length
const addingToPlaylistItem = items.find((it) => it.id === addingToPlaylistId)
return (
<>
<p className="mb-6 text-sm leading-relaxed text-on-surface-variant">{t('intro')}</p>
<label className="flex cursor-pointer flex-col items-center gap-3 rounded-xl border border-dashed border-outline-variant p-10 text-center transition-colors duration-150 hover:border-outline-variant hover:bg-surface-container/50">
<UploadCloud size={28} strokeWidth={1.5} className="text-outline" />
<span className="text-sm text-on-surface-variant">{t('dropzone.label')}</span>
<input
type="file"
accept="audio/*"
multiple
disabled={busy}
onChange={(e) => {
addFiles(e.target.files)
e.target.value = ''
}}
className="hidden"
/>
</label>
{items.length > 0 && (
<div className="mt-6 space-y-3">
{/* animate-message-enter on the wrapper, not UploadItemRow itself: it plays once on
this DOM node's initial mount, which - since each item keeps its own stable
key={item.id} across re-renders as its stage changes - only actually happens when
a genuinely new file is added to the queue, not on every status update. A file
queuing up used to just appear with no transition at all. */}
{items.map((item) => (
<div key={item.id} className="animate-message-enter">
<UploadItemRow
item={item}
isCurrent={!!item.result && currentSong?.id === item.result.metadata.library_song_id}
isPlaying={isPlaying}
streamLoading={streamLoading}
onToggle={toggle}
onRemove={() => removeItem(item.id)}
onAddToPlaylist={() => setAddingToPlaylistId(item.id)}
/>
</div>
))}
</div>
)}
{queuedCount > 0 && (
<Button onClick={uploadAll} disabled={busy} className="mt-4 w-full">
{busy ? t('button.uploading') : t('button.upload', { count: queuedCount })}
</Button>
)}
{addingToPlaylistItem?.result && (
<AddToPlaylistModal
song={{
id: addingToPlaylistItem.result.metadata.library_song_id,
title: addingToPlaylistItem.result.metadata.title,
}}
onClose={() => setAddingToPlaylistId(null)}
/>
)}
</>
)
}
......@@ -16,10 +16,11 @@ 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.
// build sets VITE_MINIMAL_NAV=true to cut the nav down to discover + a single consolidated
// library tab (which itself embeds upload/tag inline, not as a separate destination), per
// explicit direction to keep prod's launch surface small. /social, /telegram-link, /upload,
// and /library all 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'
{
"title": "My Library",
"section.upload": "Upload",
"section.latestUpload": "Latest Upload",
"section.playlists": "Your Playlists",
"section.manage": "Manage",
......
{
"title": "کتابخانه من",
"section.upload": "بارگذاری",
"section.latestUpload": "آخرین بارگذاری",
"section.playlists": "پلی‌لیست‌های شما",
"section.manage": "مدیریت",
......
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import { act, 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 { UploadQueueProvider } from '../context/UploadQueueContext'
import { ApiError } from '../api/client'
import * as libraryApi from '../api/library'
import * as streamApi from '../api/stream'
import * as musicApi from '../api/music'
const SONG = {
id: 1,
......@@ -40,12 +42,14 @@ function renderMyLibrary() {
<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>
<UploadQueueProvider>
<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>
</UploadQueueProvider>
</PlayerProvider>
</AuthProvider>
</MemoryRouter>,
......@@ -57,6 +61,9 @@ describe('MyLibrary', () => {
vi.stubEnv('VITE_DEV_ACCESS_TOKEN', '')
vi.stubEnv('VITE_DEV_REFRESH_TOKEN', '')
vi.spyOn(libraryApi, 'getPlaylists').mockResolvedValue({ status: 'success', playlists: [] })
// My Library now embeds the upload panel inline (see UploadPanel.tsx) - its queue context
// reconciles against this on mount, same default-empty mock Upload.test.tsx itself uses.
vi.spyOn(musicApi, 'listUploadJobs').mockResolvedValue({ status: 'success', jobs: [] })
})
afterEach(() => {
......@@ -72,6 +79,69 @@ describe('MyLibrary', () => {
expect(await screen.findByText(/Nothing here yet/)).toBeInTheDocument()
})
it('shows an inline Upload section with a dropzone - upload is not a separate page under minimal nav', async () => {
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [] })
renderMyLibrary()
expect(await screen.findByRole('heading', { name: 'Upload' })).toBeInTheDocument()
expect(screen.getByText('Choose audio files, or drag them here')).toBeInTheDocument()
})
it('uploads a file from the inline My Library panel and shows the tagged result', async () => {
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [] })
vi.spyOn(musicApi, 'uploadDirect').mockImplementation(async (_file, onProgress) => {
onProgress?.(100)
return { job_id: 1, status: 'queued' }
})
vi.spyOn(musicApi, 'listUploadJobs')
.mockResolvedValueOnce({ status: 'success', jobs: [] })
.mockResolvedValue({
status: 'success',
jobs: [
{
job_id: 1,
original_filename: 'test.mp3',
status: 'done',
error: null,
metadata: {
library_song_id: 42,
title: 'Invisible (Remastered)',
artist: 'Duran Duran',
album: 'Notorious',
genre: 'Pop',
year: '1986',
has_lyrics: false,
lyrics: null,
cover_art: null,
},
},
],
})
renderMyLibrary()
// The upload section only mounts once getLibrary's own loading state resolves (see
// MyLibrary.tsx) - wait for it rather than querying the input immediately.
await screen.findByRole('heading', { name: 'Upload' })
const file = new File([new Uint8Array([1, 2, 3])], 'test.mp3', { type: 'audio/mpeg' })
const input = document.querySelector('input[type="file"]') as HTMLInputElement
await userEvent.upload(input, file)
vi.useFakeTimers()
try {
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: /Upload 1 file/ }))
})
await act(async () => {
await vi.advanceTimersByTimeAsync(3000)
})
} finally {
vi.useRealTimers()
}
expect(await screen.findByText('Invisible (Remastered)')).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] })
......
......@@ -6,6 +6,7 @@ import { deleteLibrarySong, favoriteSong, getLibrary, getPlaylists, unfavoriteSo
import { ApiError } from '../api/client'
import { groupIntoAlbums, albumHref } from '../lib/albums'
import { Layout } from '../components/Layout'
import { UploadPanel } from '../components/UploadPanel'
import { AddToPlaylistModal } from '../components/AddToPlaylistModal'
import { AlbumCard, LikedSongsCard } from '../components/AlbumCard'
import { SongRow } from '../components/SongRow'
......@@ -86,6 +87,15 @@ export function MyLibrary() {
{!loading && !error && (
<div className="animate-content-enter">
{/* Upload lives inline here rather than as its own nav tab/page under the minimal
nav (per explicit direction: "upload should not be a different tab" - it's part
of the library view, not a separate destination) - reuses the exact same panel
dev's standalone /upload page renders, see UploadPanel.tsx. */}
<div className="mb-8">
<h2 className="mb-2 text-xs font-semibold uppercase tracking-[0.1em] text-primary">{t('section.upload')}</h2>
<UploadPanel />
</div>
{latestSong && (
<div className="mb-8">
<h2 className="mb-2 text-xs font-semibold uppercase tracking-[0.1em] text-primary">{t('section.latestUpload')}</h2>
......
import { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { Check, Circle, ListPlus, Pause, Pencil, Play, UploadCloud, X } from 'lucide-react'
import { Layout } from '../components/Layout'
import { Button } from '../components/ui/Button'
import { AddToPlaylistModal } from '../components/AddToPlaylistModal'
import { useUploadQueue, type UploadItem } from '../context/UploadQueueContext'
import { usePlayer, type PlayableSong } from '../context/PlayerContext'
import { editLibrarySong } from '../api/library'
// The upload+identify+tag pipeline is one opaque network call server-side (see api/music.ts'
// own comment) - there's no real per-step progress to report once the byte upload finishes.
// This sub-step split is presentational, not a literal trace of server state: both phases
// genuinely happen in this order server-side (identify_audio runs Shazam/AcoustID before
// fetch_lyrics/artwork), just without a real boundary signal to switch on, hence the fixed
// delay rather than claiming precision the backend doesn't give us.
const PROCESSING_SUBSTEP_DELAY_MS = 3000
function useProcessingSubstep(active: boolean): 0 | 1 {
const [substep, setSubstep] = useState<0 | 1>(0)
useEffect(() => {
if (!active) {
setSubstep(0)
return
}
const timer = setTimeout(() => setSubstep(1), PROCESSING_SUBSTEP_DELAY_MS)
return () => clearTimeout(timer)
}, [active])
return substep
}
type StepState = 'done' | 'active' | 'pending'
function StepRow({ state, label }: { state: StepState; label: string }) {
return (
<div className="flex items-center gap-2.5 text-sm">
{state === 'done' && <Check size={15} strokeWidth={2.5} className="shrink-0 text-primary" />}
{state === 'active' && (
<span className="h-[15px] w-[15px] shrink-0 animate-spin rounded-full border-2 border-outline-variant border-t-primary" />
)}
{state === 'pending' && <Circle size={15} strokeWidth={2} className="shrink-0 text-outline-variant" />}
<span className={state === 'pending' ? 'text-on-surface-variant' : 'text-on-surface'}>{label}</span>
</div>
)
}
function UploadSteps({ item }: { item: UploadItem }) {
const { t } = useTranslation('upload')
const substep = useProcessingSubstep(item.stage === 'processing')
const uploadState: StepState = item.stage === 'uploading' ? 'active' : 'done'
const identifyState: StepState = item.stage === 'uploading' ? 'pending' : item.stage === 'processing' && substep === 0 ? 'active' : 'done'
const artworkState: StepState =
item.stage === 'uploading' || (item.stage === 'processing' && substep === 0) ? 'pending' : item.stage === 'processing' ? 'active' : 'done'
return (
<div className="mt-3 space-y-2">
<StepRow state={uploadState} label={item.stage === 'uploading' ? t('steps.uploading', { percent: item.uploadPercent }) : t('steps.uploaded')} />
<StepRow state={identifyState} label={t('steps.identifying')} />
<StepRow state={artworkState} label={t('steps.artwork')} />
</div>
)
}
// Below this, confidence reads as "maybe" rather than "probably" - rough enough that an
// uploader should actually look at the result instead of trusting it blindly, but not so low
// a threshold that most real matches (which tend to land in the 80-100 range) get flagged.
const LOW_CONFIDENCE_THRESHOLD = 60
function ConfidenceBadge({ confidence }: { confidence: number }) {
const { t } = useTranslation('upload')
const low = confidence < LOW_CONFIDENCE_THRESHOLD
return (
<span
className={`inline-flex shrink-0 items-center gap-1 rounded-full px-2 py-0.5 text-xs font-medium ${
low ? 'bg-error-container text-on-error-container' : 'bg-primary-container text-on-primary-container'
}`}
>
{t('confidence.match', { percent: Math.round(confidence) })}
</span>
)
}
function EditDetailsForm({
item,
onCancel,
onSaved,
}: {
item: UploadItem
onCancel: () => void
onSaved: (fields: { title: string; artist: string; album: string; genre: string }) => void
}) {
const { t } = useTranslation('upload')
const metadata = item.result!.metadata
const [title, setTitle] = useState(metadata.title)
const [artist, setArtist] = useState(metadata.artist)
const [album, setAlbum] = useState(metadata.album)
const [genre, setGenre] = useState(metadata.genre)
const [saving, setSaving] = useState(false)
const [error, setError] = useState<string | null>(null)
async function handleSave() {
setSaving(true)
setError(null)
try {
await editLibrarySong(metadata.library_song_id, { title, artist, album, genre })
onSaved({ title, artist, album, genre })
} catch (err) {
setError(err instanceof Error ? err.message : t('error.editFailed'))
} finally {
setSaving(false)
}
}
return (
<div className="mt-3 space-y-2 border-t border-outline-variant pt-3">
<input
value={title}
onChange={(e) => setTitle(e.target.value)}
aria-label={t('edit.titleLabel')}
placeholder={t('edit.titleLabel')}
className="w-full rounded-lg border border-outline-variant bg-surface px-3 py-2 text-sm text-on-surface focus:outline-none focus-visible:ring-2 focus-visible:ring-primary"
/>
<input
value={artist}
onChange={(e) => setArtist(e.target.value)}
aria-label={t('edit.artistLabel')}
placeholder={t('edit.artistLabel')}
className="w-full rounded-lg border border-outline-variant bg-surface px-3 py-2 text-sm text-on-surface focus:outline-none focus-visible:ring-2 focus-visible:ring-primary"
/>
<input
value={album}
onChange={(e) => setAlbum(e.target.value)}
aria-label={t('edit.albumLabel')}
placeholder={t('edit.albumLabel')}
className="w-full rounded-lg border border-outline-variant bg-surface px-3 py-2 text-sm text-on-surface focus:outline-none focus-visible:ring-2 focus-visible:ring-primary"
/>
<input
value={genre}
onChange={(e) => setGenre(e.target.value)}
aria-label={t('edit.genreLabel')}
placeholder={t('edit.genreLabel')}
className="w-full rounded-lg border border-outline-variant bg-surface px-3 py-2 text-sm text-on-surface focus:outline-none focus-visible:ring-2 focus-visible:ring-primary"
/>
{error && <p className="text-sm text-error">{error}</p>}
<p className="text-xs text-on-surface-variant">{t('edit.pendingNotice')}</p>
<div className="flex gap-2">
<Button onClick={handleSave} disabled={saving} className="flex-1">
{saving ? t('edit.saving') : t('edit.save')}
</Button>
<Button onClick={onCancel} disabled={saving} variant="secondary" className="flex-1">
{t('edit.cancel')}
</Button>
</div>
</div>
)
}
function UploadItemRow({
item,
isCurrent,
isPlaying,
streamLoading,
onToggle,
onRemove,
onAddToPlaylist,
}: {
item: UploadItem
isCurrent: boolean
isPlaying: boolean
streamLoading: boolean
onToggle: (song: PlayableSong) => void
onRemove: () => void
onAddToPlaylist: () => void
}) {
const { t } = useTranslation('upload')
const { patchItemMetadata } = useUploadQueue()
const [editing, setEditing] = useState(false)
if (item.stage === 'done' && item.result) {
const { metadata } = item.result
return (
<div className="rounded-xl border border-outline-variant bg-surface-container p-3">
{/* Tapping anywhere on the card plays it, not just a small button - the icon on the
right is a status indicator rendered inside this same button. Add to playlist
stays a separate control below since it's a genuinely different action. */}
<button
onClick={() =>
onToggle({
id: metadata.library_song_id,
title: metadata.title,
artist: metadata.artist,
album: metadata.album,
coverart: metadata.cover_art,
lyrics: metadata.lyrics,
})
}
disabled={isCurrent && streamLoading}
aria-label={isCurrent && isPlaying ? t('aria.pause') : t('aria.play')}
className="flex w-full items-center gap-4 rounded-lg p-1 text-left transition-colors hover:bg-surface-container focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed"
>
{metadata.cover_art ? (
<img src={metadata.cover_art} alt="" className="h-16 w-16 shrink-0 rounded-lg object-cover" />
) : (
<div className="flex h-16 w-16 shrink-0 items-center justify-center rounded-lg bg-surface-container-high text-on-surface-variant">
<Play size={20} strokeWidth={1.75} />
</div>
)}
<div className="min-w-0 flex-1">
<p className="truncate font-semibold text-on-surface">{metadata.title}</p>
<p className="truncate text-sm text-on-surface-variant">
{metadata.artist} · {metadata.album} · {metadata.genre}
</p>
</div>
<span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-surface-container-high text-on-surface">
{isCurrent && streamLoading ? (
<span className="h-3.5 w-3.5 animate-spin rounded-full border-2 border-outline-variant border-t-on-surface" />
) : isCurrent && isPlaying ? (
<Pause size={16} strokeWidth={2} fill="currentColor" />
) : (
<Play size={16} strokeWidth={2} fill="currentColor" className="ml-0.5" />
)}
</span>
</button>
<div className="mt-1 flex flex-wrap items-center gap-2 px-1">
<button
onClick={onAddToPlaylist}
className="flex items-center gap-1.5 py-1 text-sm text-on-surface-variant transition-colors hover:text-on-surface focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"
>
<ListPlus size={15} strokeWidth={1.75} />
{t('button.addToPlaylist')}
</button>
{!editing && (
<button
onClick={() => setEditing(true)}
className="flex items-center gap-1.5 py-1 text-sm text-on-surface-variant transition-colors hover:text-on-surface focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"
>
<Pencil size={14} strokeWidth={1.75} />
{t('edit.editDetails')}
</button>
)}
<span className="flex-1" />
{typeof metadata.confidence === 'number' && <ConfidenceBadge confidence={metadata.confidence} />}
{metadata.review_status === 'pending' && (
<span className="inline-flex shrink-0 items-center rounded-full bg-surface-container-high px-2 py-0.5 text-xs font-medium text-on-surface-variant">
{t('edit.communityNoted')}
</span>
)}
</div>
{editing && (
<EditDetailsForm
item={item}
onCancel={() => setEditing(false)}
onSaved={(fields) => {
patchItemMetadata(item.id, { ...fields, review_status: 'pending' })
setEditing(false)
}}
/>
)}
</div>
)
}
return (
<div className="rounded-xl border border-outline-variant bg-surface-container p-3">
<div className="flex items-center gap-3">
<p className="min-w-0 flex-1 truncate text-sm text-on-surface">{item.filename}</p>
{item.stage === 'queued' && (
<button
onClick={onRemove}
aria-label={t('aria.remove', { filename: item.filename })}
className="shrink-0 rounded-full p-1 text-on-surface-variant transition-colors hover:bg-surface-container-high hover:text-on-surface focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"
>
<X size={16} strokeWidth={2} />
</button>
)}
</div>
{(item.stage === 'uploading' || item.stage === 'processing') && <UploadSteps item={item} />}
{item.stage === 'error' && <p className="mt-2 text-sm text-error">{item.error ?? t('error.uploadFailed')}</p>}
</div>
)
}
import { UploadPanel } from '../components/UploadPanel'
export function Upload() {
const { t } = useTranslation('upload')
const { items, busy, addFiles, removeItem, uploadAll } = useUploadQueue()
const [addingToPlaylistId, setAddingToPlaylistId] = useState<string | null>(null)
const { currentSong, isPlaying, isLoading: streamLoading, toggle } = usePlayer()
const queuedCount = items.filter((it) => it.stage === 'queued').length
const addingToPlaylistItem = items.find((it) => it.id === addingToPlaylistId)
return (
<Layout title={t('title')}>
<p className="mb-6 text-sm leading-relaxed text-on-surface-variant">{t('intro')}</p>
<label className="flex cursor-pointer flex-col items-center gap-3 rounded-xl border border-dashed border-outline-variant p-10 text-center transition-colors duration-150 hover:border-outline-variant hover:bg-surface-container/50">
<UploadCloud size={28} strokeWidth={1.5} className="text-outline" />
<span className="text-sm text-on-surface-variant">{t('dropzone.label')}</span>
<input
type="file"
accept="audio/*"
multiple
disabled={busy}
onChange={(e) => {
addFiles(e.target.files)
e.target.value = ''
}}
className="hidden"
/>
</label>
{items.length > 0 && (
<div className="mt-6 space-y-3">
{/* animate-message-enter on the wrapper, not UploadItemRow itself: it plays once on
this DOM node's initial mount, which - since each item keeps its own stable
key={item.id} across re-renders as its stage changes - only actually happens when
a genuinely new file is added to the queue, not on every status update. A file
queuing up used to just appear with no transition at all. */}
{items.map((item) => (
<div key={item.id} className="animate-message-enter">
<UploadItemRow
item={item}
isCurrent={!!item.result && currentSong?.id === item.result.metadata.library_song_id}
isPlaying={isPlaying}
streamLoading={streamLoading}
onToggle={toggle}
onRemove={() => removeItem(item.id)}
onAddToPlaylist={() => setAddingToPlaylistId(item.id)}
/>
</div>
))}
</div>
)}
{queuedCount > 0 && (
<Button onClick={uploadAll} disabled={busy} className="mt-4 w-full">
{busy ? t('button.uploading') : t('button.upload', { count: queuedCount })}
</Button>
)}
{addingToPlaylistItem?.result && (
<AddToPlaylistModal
song={{
id: addingToPlaylistItem.result.metadata.library_song_id,
title: addingToPlaylistItem.result.metadata.title,
}}
onClose={() => setAddingToPlaylistId(null)}
/>
)}
<UploadPanel />
</Layout>
)
}
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