Commit fad9c417 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Survive navigating away from /upload, add a step checklist, and let uploaders…

Survive navigating away from /upload, add a step checklist, and let uploaders correct identification

Uploading used to live in Upload.tsx's own component state, so leaving
the page mid-upload abandoned the in-flight request with no way to see
it finish. Lifts the queue into a new UploadQueueProvider (same tier as
PlayerContext, above the router) so it keeps running and updating
regardless of navigation.

Each queued file now shows a Claude-Code-style step checklist (upload →
identify → artwork) instead of a bare progress bar. Completed results
show the system's 0-100 confidence score, and an "Edit details" form
lets the uploader correct title/artist/album/genre - doing so flips the
song to review_status "pending" ("community noted") via the new
PATCH /library/{id}, reflected immediately in the card without a
refetch. Also adds the review-queue API client functions AdminPanel's
community-review tab uses to approve or reject those songs.
parent 233bcb1f
...@@ -14,6 +14,16 @@ export interface LibrarySong { ...@@ -14,6 +14,16 @@ export interface LibrarySong {
/** Membership in the caller's own auto-created Liked Songs playlist - not a real column on /** 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. */ * the song, computed server-side on every endpoint that returns the caller's own songs. */
is_liked: boolean is_liked: boolean
/** 0-100, how confident identification was - null for a song with no identification step of
* its own (manually entered, claimed, or remixed). Optional (not just nullable) because every
* real backend response includes it, but the many existing test fixtures built before this
* field existed don't need updating just to keep constructing a LibrarySong-shaped mock. */
confidence?: number | null
/** "approved" (visible in the shared library to everyone) | "pending" (the owner edited the
* identification away from what the system found - stays in their own library, withheld from
* everyone else until a super admin reviews it) | "rejected" (reviewed and declined). Optional
* for the same reason as confidence above. */
review_status?: 'approved' | 'pending' | 'rejected'
} }
export function getLibrary() { export function getLibrary() {
...@@ -97,6 +107,55 @@ export function deleteLibrarySong(fileId: number) { ...@@ -97,6 +107,55 @@ export function deleteLibrarySong(fileId: number) {
return apiFetch<{ status: string }>(`/library/${fileId}`, { method: 'DELETE' }) return apiFetch<{ status: string }>(`/library/${fileId}`, { method: 'DELETE' })
} }
export interface LibrarySongEdit {
title?: string
artist?: string
album?: string
genre?: string
coverart?: string
}
/** Corrects what identification found - only call this when the uploader is actually changing
* something; accepting the system's result as-is needs no call at all. Any edit flips the song
* to review_status "pending" ("community noted") server-side: it stays fully visible and
* playable in the caller's own library immediately, but drops out of the shared library/Home
* feed for everyone else until a super admin reviews it (see the review-queue endpoints below). */
export function editLibrarySong(fileId: number, edit: LibrarySongEdit) {
return apiFetch<{ status: string; song: LibrarySong }>(`/library/${fileId}`, { method: 'PATCH', json: edit })
}
export interface LibraryReviewItem {
id: number
user_id: number
title: string
artist: string
album: string | null
genre: string | null
coverart: string | null
confidence: number | null
review_status: 'approved' | 'pending' | 'rejected'
added_at: string
}
/** Super-admin-only: songs community-noted away from the system's identification, waiting on a
* decision (see editLibrarySong above). */
export function getLibraryReviewQueue(status: 'pending' | 'approved' | 'rejected' = 'pending') {
const params = new URLSearchParams({ status })
return apiFetch<{ status: string; songs: LibraryReviewItem[] }>(`/library/admin/review-queue?${params}`)
}
export function approveLibraryReview(songId: number) {
return apiFetch<{ status: string; song: LibraryReviewItem }>(`/library/admin/review-queue/${songId}/approve`, {
method: 'POST',
})
}
export function rejectLibraryReview(songId: number) {
return apiFetch<{ status: string; song: LibraryReviewItem }>(`/library/admin/review-queue/${songId}/reject`, {
method: 'POST',
})
}
/** synced_lyrics is [seconds, text][] - real LRC line timing when a synced source was found /** synced_lyrics is [seconds, text][] - real LRC line timing when a synced source was found
* (see the backend's fetch_lyrics), used to drive the highlighted line-by-line lyrics view. * (see the backend's fetch_lyrics), used to drive the highlighted line-by-line lyrics view.
* Null when only plain-text lyrics (or nothing) exists - callers fall back to `lyrics`. */ * Null when only plain-text lyrics (or nothing) exists - callers fall back to `lyrics`. */
......
...@@ -10,6 +10,16 @@ export interface TagMetadata { ...@@ -10,6 +10,16 @@ export interface TagMetadata {
has_lyrics: boolean has_lyrics: boolean
lyrics: string | null lyrics: string | null
cover_art: string | null cover_art: string | null
// 0-100, how confident the identification was (null for a source with no comparable score -
// see music_identification.py). Optional, not just nullable - every real backend response
// includes it, but the pre-existing test fixtures built before this field existed don't need
// updating just to keep constructing a TagMetadata-shaped mock.
confidence?: number | null
// "approved" (shown in the shared library to everyone) | "pending" (the uploader edited the
// identification away from what the system found - private to them until a super admin
// reviews it) | "rejected" (reviewed and declined, stays private). Absent on a dedupe-cache
// hit from before this field existed.
review_status?: 'approved' | 'pending' | 'rejected'
} }
export interface TagResponse { export interface TagResponse {
......
import { createContext, useContext, useState, type ReactNode } from 'react'
import { uploadDirect, type TagMetadata, type TagResponse } from '../api/music'
export type ItemStage = 'queued' | 'uploading' | 'processing' | 'done' | 'error'
export interface UploadItem {
id: string
file: File
stage: ItemStage
uploadPercent: number
result: TagResponse | null
error: string | null
}
function makeId() {
return `${Date.now()}-${Math.random().toString(36).slice(2)}`
}
interface UploadQueueContextValue {
items: UploadItem[]
busy: boolean
addFiles: (fileList: FileList | null) => void
removeItem: (id: string) => void
uploadAll: () => Promise<void>
/** Merges a successful editLibrarySong() response back into the item's already-tagged result -
* used right after the uploader corrects the identified title/artist/album/genre (see
* UploadItemRow's edit form), so the card immediately reflects the new values and the
* "pending review" state without needing a full re-upload. */
patchItemMetadata: (id: string, metadata: Partial<TagMetadata>) => void
}
const UploadQueueContext = createContext<UploadQueueContextValue | null>(null)
/** Lives above BrowserRouter (see main.tsx), same tier as PlayerContext - the upload queue and
* whichever item is mid-identify must survive the user navigating off /upload entirely, not just
* a re-render. Upload.tsx used to own this as local component state, which meant the in-flight
* uploadDirect() request kept running in the background after a route change (fetch/XHR aren't
* cancelled by React unmounting), but every setItems call after that point landed on a component
* that no longer existed - the user had no way to see it finish, and going back to /upload showed
* an empty queue as if nothing had ever started. */
export function UploadQueueProvider({ children }: { children: ReactNode }) {
const [items, setItems] = useState<UploadItem[]>([])
const [busy, setBusy] = useState(false)
function updateItem(id: string, patch: Partial<UploadItem>) {
setItems((prev) => prev.map((it) => (it.id === id ? { ...it, ...patch } : it)))
}
function addFiles(fileList: FileList | null) {
if (!fileList || fileList.length === 0) return
const newItems: UploadItem[] = Array.from(fileList).map((file) => ({
id: makeId(),
file,
stage: 'queued',
uploadPercent: 0,
result: null,
error: null,
}))
setItems((prev) => [...prev, ...newItems])
}
function removeItem(id: string) {
setItems((prev) => prev.filter((it) => it.id !== id))
}
function patchItemMetadata(id: string, metadata: Partial<TagMetadata>) {
setItems((prev) =>
prev.map((it) =>
it.id === id && it.result
? { ...it, result: { ...it.result, metadata: { ...it.result.metadata, ...metadata } } }
: it,
),
)
}
async function uploadAll() {
setBusy(true)
// Sequential, not Promise.all - the server's identify/tag pipeline is already network-
// and CPU-heavy per file (Shazam/AcoustID lookups, lyrics fetch, tagging), so racing
// several through it at once would just contend with itself for no real benefit. Reads
// `items` fresh each iteration (not a closed-over snapshot) since this whole function can
// now outlive the component that called it.
for (const item of items) {
if (item.stage !== 'queued') continue
updateItem(item.id, { stage: 'uploading', uploadPercent: 0, error: null })
try {
const res = await uploadDirect(item.file, (percent) => {
updateItem(item.id, { uploadPercent: percent, stage: percent >= 100 ? 'processing' : 'uploading' })
})
updateItem(item.id, { stage: 'done', result: res })
} catch (err) {
updateItem(item.id, { stage: 'error', error: err instanceof Error ? err.message : null })
}
}
setBusy(false)
}
return (
<UploadQueueContext.Provider value={{ items, busy, addFiles, removeItem, uploadAll, patchItemMetadata }}>
{children}
</UploadQueueContext.Provider>
)
}
export function useUploadQueue(): UploadQueueContextValue {
const ctx = useContext(UploadQueueContext)
if (!ctx) throw new Error('useUploadQueue must be used within an UploadQueueProvider')
return ctx
}
{ {
"title": "Upload &amp; Tag", "title": "Upload & Tag",
"intro": "Upload untagged tracks - each is fingerprinted, tagged with title/artist/album/art/lyrics, and added to your library.", "intro": "Upload untagged tracks - each is fingerprinted, tagged with title/artist/album/art/lyrics, and added to your library.",
"dropzone.label": "Choose audio files, or drag them here", "dropzone.label": "Choose audio files, or drag them here",
"aria.play": "Play", "aria.play": "Play",
"aria.pause": "Pause", "aria.pause": "Pause",
"button.addToPlaylist": "Add to playlist", "button.addToPlaylist": "Add to playlist",
"aria.remove": "Remove {{filename}}", "aria.remove": "Remove {{filename}}",
"progress.uploading": "Uploading", "steps.uploading": "Uploading ({{percent}}%)",
"progress.identifying": "Identifying & tagging…", "steps.uploaded": "Uploaded",
"steps.identifying": "Identifying song",
"steps.artwork": "Finding album art & lyrics",
"error.uploadFailed": "Upload failed", "error.uploadFailed": "Upload failed",
"button.uploading": "Uploading…", "button.uploading": "Uploading…",
"button.upload_one": "Upload {{count}} file", "button.upload_one": "Upload {{count}} file",
"button.upload_other": "Upload {{count}} files" "button.upload_other": "Upload {{count}} files",
"confidence.match": "{{percent}}% match",
"edit.editDetails": "Edit details",
"edit.communityNoted": "Community noted · pending review",
"edit.titleLabel": "Title",
"edit.artistLabel": "Artist",
"edit.albumLabel": "Album",
"edit.genreLabel": "Genre",
"edit.pendingNotice": "Changing these details marks this song as community noted - it stays in your library but won't appear in the shared library for others until reviewed.",
"edit.save": "Save",
"edit.saving": "Saving…",
"edit.cancel": "Cancel",
"error.editFailed": "Couldn't save changes"
} }
...@@ -6,10 +6,24 @@ ...@@ -6,10 +6,24 @@
"aria.pause": "توقف", "aria.pause": "توقف",
"button.addToPlaylist": "افزودن به پلی‌لیست", "button.addToPlaylist": "افزودن به پلی‌لیست",
"aria.remove": "حذف {{filename}}", "aria.remove": "حذف {{filename}}",
"progress.uploading": "در حال بارگذاری", "steps.uploading": "در حال بارگذاری ({{percent}}٪)",
"progress.identifying": "در حال شناسایی و برچسب‌گذاری…", "steps.uploaded": "بارگذاری شد",
"steps.identifying": "در حال شناسایی آهنگ",
"steps.artwork": "در حال یافتن کاور و متن ترانه",
"error.uploadFailed": "بارگذاری ناموفق بود", "error.uploadFailed": "بارگذاری ناموفق بود",
"button.uploading": "در حال بارگذاری…", "button.uploading": "در حال بارگذاری…",
"button.upload_one": "بارگذاری {{count}} فایل", "button.upload_one": "بارگذاری {{count}} فایل",
"button.upload_other": "بارگذاری {{count}} فایل" "button.upload_other": "بارگذاری {{count}} فایل",
"confidence.match": "{{percent}}٪ تطابق",
"edit.editDetails": "ویرایش جزئیات",
"edit.communityNoted": "یادداشت‌شده توسط کاربر · در انتظار بررسی",
"edit.titleLabel": "عنوان",
"edit.artistLabel": "هنرمند",
"edit.albumLabel": "آلبوم",
"edit.genreLabel": "ژانر",
"edit.pendingNotice": "تغییر این جزئیات این آهنگ را «یادداشت‌شده توسط کاربر» علامت می‌زند - در کتابخانه‌ات باقی می‌ماند اما تا بررسی، در کتابخانه مشترک برای دیگران نمایش داده نمی‌شود.",
"edit.save": "ذخیره",
"edit.saving": "در حال ذخیره…",
"edit.cancel": "لغو",
"error.editFailed": "ذخیره تغییرات ممکن نشد"
} }
...@@ -9,6 +9,7 @@ import { AuthProvider } from './context/AuthContext.tsx' ...@@ -9,6 +9,7 @@ import { AuthProvider } from './context/AuthContext.tsx'
import { PlayerProvider } from './context/PlayerContext.tsx' import { PlayerProvider } from './context/PlayerContext.tsx'
import { ThemeProvider } from './context/ThemeContext.tsx' import { ThemeProvider } from './context/ThemeContext.tsx'
import { LanguageProvider } from './context/LanguageContext.tsx' import { LanguageProvider } from './context/LanguageContext.tsx'
import { UploadQueueProvider } from './context/UploadQueueContext.tsx'
createRoot(document.getElementById('root')!).render( createRoot(document.getElementById('root')!).render(
<StrictMode> <StrictMode>
...@@ -17,7 +18,9 @@ createRoot(document.getElementById('root')!).render( ...@@ -17,7 +18,9 @@ createRoot(document.getElementById('root')!).render(
<BrowserRouter> <BrowserRouter>
<AuthProvider> <AuthProvider>
<PlayerProvider> <PlayerProvider>
<UploadQueueProvider>
<App /> <App />
</UploadQueueProvider>
</PlayerProvider> </PlayerProvider>
</AuthProvider> </AuthProvider>
</BrowserRouter> </BrowserRouter>
......
...@@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' ...@@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { Upload } from './Upload' import { Upload } from './Upload'
import { AuthProvider } from '../context/AuthContext' import { AuthProvider } from '../context/AuthContext'
import { PlayerProvider } from '../context/PlayerContext' import { PlayerProvider } from '../context/PlayerContext'
import { UploadQueueProvider } from '../context/UploadQueueContext'
import * as musicApi from '../api/music' import * as musicApi from '../api/music'
import * as libraryApi from '../api/library' import * as libraryApi from '../api/library'
...@@ -28,7 +29,9 @@ function renderPage() { ...@@ -28,7 +29,9 @@ function renderPage() {
<MemoryRouter> <MemoryRouter>
<AuthProvider> <AuthProvider>
<PlayerProvider> <PlayerProvider>
<UploadQueueProvider>
<Upload /> <Upload />
</UploadQueueProvider>
</PlayerProvider> </PlayerProvider>
</AuthProvider> </AuthProvider>
</MemoryRouter>, </MemoryRouter>,
...@@ -130,6 +133,58 @@ describe('Upload', () => { ...@@ -130,6 +133,58 @@ describe('Upload', () => {
expect(uploadDirect).toHaveBeenCalledTimes(2) expect(uploadDirect).toHaveBeenCalledTimes(2)
}) })
it('shows a confidence badge when the result includes one', async () => {
vi.spyOn(musicApi, 'uploadDirect').mockImplementation(async (_file, onProgress) => {
onProgress?.(100)
return { ...TAG_RESPONSE, metadata: { ...TAG_RESPONSE.metadata, confidence: 87 } }
})
renderPage()
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)
await userEvent.click(screen.getByRole('button', { name: /Upload/ }))
expect(await screen.findByText('87% match')).toBeInTheDocument()
})
it('edits the identified details, marking the song community noted with the new values', async () => {
await uploadAndWaitForResult()
const editLibrarySong = vi.spyOn(libraryApi, 'editLibrarySong').mockResolvedValue({
status: 'success',
song: { ...TAG_RESPONSE.metadata, id: 42, user_id: 1, coverart: null, lyrics: null, file_path: '', added_at: '2026-01-01T00:00:00Z', is_liked: false, review_status: 'pending' },
})
await userEvent.click(screen.getByRole('button', { name: 'Edit details' }))
const titleInput = screen.getByLabelText('Title')
await userEvent.clear(titleInput)
await userEvent.type(titleInput, 'Corrected Title')
await userEvent.click(screen.getByRole('button', { name: 'Save' }))
await waitFor(() =>
expect(editLibrarySong).toHaveBeenCalledWith(42, {
title: 'Corrected Title',
artist: 'Duran Duran',
album: 'Notorious',
genre: 'Pop',
}),
)
expect(await screen.findByText('Corrected Title')).toBeInTheDocument()
expect(screen.getByText('Community noted · pending review')).toBeInTheDocument()
})
it('cancels editing without saving', async () => {
await uploadAndWaitForResult()
const editLibrarySong = vi.spyOn(libraryApi, 'editLibrarySong')
await userEvent.click(screen.getByRole('button', { name: 'Edit details' }))
expect(screen.getByLabelText('Title')).toBeInTheDocument()
await userEvent.click(screen.getByRole('button', { name: 'Cancel' }))
expect(screen.queryByLabelText('Title')).not.toBeInTheDocument()
expect(editLibrarySong).not.toHaveBeenCalled()
})
it('lets a still-queued file be removed before uploading', async () => { it('lets a still-queued file be removed before uploading', async () => {
vi.spyOn(musicApi, 'uploadDirect') vi.spyOn(musicApi, 'uploadDirect')
......
import { useState } from 'react' import { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
import { ListPlus, Pause, Play, UploadCloud, X } from 'lucide-react' import { Check, Circle, ListPlus, Pause, Pencil, Play, UploadCloud, X } from 'lucide-react'
import { Layout } from '../components/Layout' import { Layout } from '../components/Layout'
import { Button } from '../components/ui/Button' import { Button } from '../components/ui/Button'
import { ProgressBar } from '../components/ui/ProgressBar'
import { AddToPlaylistModal } from '../components/AddToPlaylistModal' import { AddToPlaylistModal } from '../components/AddToPlaylistModal'
import { uploadDirect, type TagResponse } from '../api/music' import { useUploadQueue, type UploadItem } from '../context/UploadQueueContext'
import { usePlayer, type PlayableSong } from '../context/PlayerContext' import { usePlayer, type PlayableSong } from '../context/PlayerContext'
import { editLibrarySong } from '../api/library'
type ItemStage = 'queued' | 'uploading' | 'processing' | 'done' | 'error' // 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
interface UploadItem { function useProcessingSubstep(active: boolean): 0 | 1 {
id: string const [substep, setSubstep] = useState<0 | 1>(0)
file: File useEffect(() => {
stage: ItemStage if (!active) {
uploadPercent: number setSubstep(0)
result: TagResponse | null return
error: string | null }
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 makeId() { function UploadSteps({ item }: { item: UploadItem }) {
return `${Date.now()}-${Math.random().toString(36).slice(2)}` 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({ function UploadItemRow({
...@@ -41,6 +174,9 @@ function UploadItemRow({ ...@@ -41,6 +174,9 @@ function UploadItemRow({
onAddToPlaylist: () => void onAddToPlaylist: () => void
}) { }) {
const { t } = useTranslation('upload') const { t } = useTranslation('upload')
const { patchItemMetadata } = useUploadQueue()
const [editing, setEditing] = useState(false)
if (item.stage === 'done' && item.result) { if (item.stage === 'done' && item.result) {
const { metadata } = item.result const { metadata } = item.result
return ( return (
...@@ -86,13 +222,41 @@ function UploadItemRow({ ...@@ -86,13 +222,41 @@ function UploadItemRow({
)} )}
</span> </span>
</button> </button>
<div className="mt-1 flex flex-wrap items-center gap-2 px-1">
<button <button
onClick={onAddToPlaylist} onClick={onAddToPlaylist}
className="mt-1 flex items-center gap-1.5 px-1 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" 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} /> <ListPlus size={15} strokeWidth={1.75} />
{t('button.addToPlaylist')} {t('button.addToPlaylist')}
</button> </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> </div>
) )
} }
...@@ -111,67 +275,18 @@ function UploadItemRow({ ...@@ -111,67 +275,18 @@ function UploadItemRow({
</button> </button>
)} )}
</div> </div>
{(item.stage === 'uploading' || item.stage === 'processing') && ( {(item.stage === 'uploading' || item.stage === 'processing') && <UploadSteps item={item} />}
<div className="mt-2"> {item.stage === 'error' && <p className="mt-2 text-sm text-error">{item.error ?? t('error.uploadFailed')}</p>}
<ProgressBar
percent={item.stage === 'uploading' ? item.uploadPercent : null}
label={item.stage === 'uploading' ? t('progress.uploading') : t('progress.identifying')}
/>
</div>
)}
{item.stage === 'error' && <p className="mt-2 text-sm text-error">{item.error}</p>}
</div> </div>
) )
} }
export function Upload() { export function Upload() {
const { t } = useTranslation('upload') const { t } = useTranslation('upload')
const [items, setItems] = useState<UploadItem[]>([]) const { items, busy, addFiles, removeItem, uploadAll } = useUploadQueue()
const [busy, setBusy] = useState(false)
const [addingToPlaylistId, setAddingToPlaylistId] = useState<string | null>(null) const [addingToPlaylistId, setAddingToPlaylistId] = useState<string | null>(null)
const { currentSong, isPlaying, isLoading: streamLoading, toggle } = usePlayer() const { currentSong, isPlaying, isLoading: streamLoading, toggle } = usePlayer()
function updateItem(id: string, patch: Partial<UploadItem>) {
setItems((prev) => prev.map((it) => (it.id === id ? { ...it, ...patch } : it)))
}
function handleSelectFiles(fileList: FileList | null) {
if (!fileList || fileList.length === 0) return
const newItems: UploadItem[] = Array.from(fileList).map((file) => ({
id: makeId(),
file,
stage: 'queued',
uploadPercent: 0,
result: null,
error: null,
}))
setItems((prev) => [...prev, ...newItems])
}
function removeItem(id: string) {
setItems((prev) => prev.filter((it) => it.id !== id))
}
async function handleUploadAll() {
setBusy(true)
// Sequential, not Promise.all - the server's identify/tag pipeline is already network-
// and CPU-heavy per file (Shazam/AcoustID lookups, lyrics fetch, tagging), so racing
// several through it at once would just contend with itself for no real benefit.
for (const item of items) {
if (item.stage !== 'queued') continue
updateItem(item.id, { stage: 'uploading', uploadPercent: 0, error: null })
try {
const res = await uploadDirect(item.file, (percent) => {
updateItem(item.id, { uploadPercent: percent, stage: percent >= 100 ? 'processing' : 'uploading' })
})
updateItem(item.id, { stage: 'done', result: res })
} catch (err) {
updateItem(item.id, { stage: 'error', error: err instanceof Error ? err.message : t('error.uploadFailed') })
}
}
setBusy(false)
}
const queuedCount = items.filter((it) => it.stage === 'queued').length const queuedCount = items.filter((it) => it.stage === 'queued').length
const addingToPlaylistItem = items.find((it) => it.id === addingToPlaylistId) const addingToPlaylistItem = items.find((it) => it.id === addingToPlaylistId)
...@@ -188,7 +303,7 @@ export function Upload() { ...@@ -188,7 +303,7 @@ export function Upload() {
multiple multiple
disabled={busy} disabled={busy}
onChange={(e) => { onChange={(e) => {
handleSelectFiles(e.target.files) addFiles(e.target.files)
e.target.value = '' e.target.value = ''
}} }}
className="hidden" className="hidden"
...@@ -219,7 +334,7 @@ export function Upload() { ...@@ -219,7 +334,7 @@ export function Upload() {
)} )}
{queuedCount > 0 && ( {queuedCount > 0 && (
<Button onClick={handleUploadAll} disabled={busy} className="mt-4 w-full"> <Button onClick={uploadAll} disabled={busy} className="mt-4 w-full">
{busy ? t('button.uploading') : t('button.upload', { count: queuedCount })} {busy ? t('button.uploading') : t('button.upload', { count: queuedCount })}
</Button> </Button>
)} )}
......
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