Commit 04d2c5c1 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Multi-select in Upload and Telegram chat music identification

Upload now takes multiple files in one go: each gets its own queued
row (removable before upload), progress, result, and error state, fed
through the existing one-file-at-a-time endpoint sequentially rather
than in parallel - the per-file identify/tag pipeline is already the
expensive part, so racing several through it wouldn't help.

TelegramLink's chat music list gets the equivalent for saving: a
checkbox per not-yet-saved row and a sticky "Save N selected" action
that calls /music/tag once per song, same sequential reasoning. The
existing per-song Save button still works for saving just one.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 3592c605
Pipeline #1158 canceled with stage
...@@ -160,8 +160,9 @@ const FRONTEND_DONE: DoneGroup[] = [ ...@@ -160,8 +160,9 @@ const FRONTEND_DONE: DoneGroup[] = [
items: [ items: [
'Login page: username/password + register, toggled in place', 'Login page: username/password + register, toggled in place',
'Route guards redirect to /login when signed out instead of showing a blank page', 'Route guards redirect to /login when signed out instead of showing a blank page',
'Telegram linking page: phone + code (+ two-step verification password if the account has it enabled), then browse linked chats and save any found song to the library (tags via /music/tag, one song at a time)', 'Telegram linking page: phone + code (+ two-step verification password if the account has it enabled), then browse linked chats and save any found song to the library (tags via /music/tag)',
'Per-song 30-second preview button in the chat music list, playable through the shared player before deciding whether to save (2026-08-23)', 'Per-song 30-second preview button in the chat music list, playable through the shared player before deciding whether to save (2026-08-23)',
'Multi-select save in the chat music list (2026-09-01): each not-yet-saved row gets a checkbox; selecting any shows a sticky "Save N selected" bar. Still calls /music/tag once per song sequentially - there\'s no batch endpoint, and Shazam/AcoustID lookups are heavy enough per call that racing them wouldn\'t help - but it\'s one tap instead of one per song',
], ],
}, },
{ {
...@@ -192,6 +193,7 @@ const FRONTEND_DONE: DoneGroup[] = [ ...@@ -192,6 +193,7 @@ const FRONTEND_DONE: DoneGroup[] = [
'Add-to-playlist modal from the Library page (add existing or create-and-add)', 'Add-to-playlist modal from the Library page (add existing or create-and-add)',
'Delete-from-library (2026-08-31): swipe a Library row left past a threshold to reveal and trigger delete (right instead adds to queue) - confirms via the same window.confirm pattern already used for soundmark delete, then removes the file on disk and reconciles the song out of every local list it could be showing in (the full library, the current search\'s Songs section, and any album groupings within it)', 'Delete-from-library (2026-08-31): swipe a Library row left past a threshold to reveal and trigger delete (right instead adds to queue) - confirms via the same window.confirm pattern already used for soundmark delete, then removes the file on disk and reconciles the song out of every local list it could be showing in (the full library, the current search\'s Songs section, and any album groupings within it)',
'Upload\'s result card swaps its download link for "Add to playlist" (2026-09-01), reusing AddToPlaylistModal (narrowed its song prop to just {id, title} rather than the full LibrarySong shape, since Upload\'s freshly-tagged result isn\'t one) - the card itself is now tappable to play the track immediately via the shared player instead of only offering a file to save locally', 'Upload\'s result card swaps its download link for "Add to playlist" (2026-09-01), reusing AddToPlaylistModal (narrowed its song prop to just {id, title} rather than the full LibrarySong shape, since Upload\'s freshly-tagged result isn\'t one) - the card itself is now tappable to play the track immediately via the shared player instead of only offering a file to save locally',
'Upload accepts multiple files at once (2026-09-01): each selected file gets its own queued row (removable before upload) and its own progress/result/error state, uploaded sequentially through the same one-file-at-a-time endpoint rather than all at once - the identify/tag pipeline per file is already the heavy part, so nothing would be gained by racing several through it in parallel',
], ],
}, },
{ {
......
...@@ -11,6 +11,7 @@ import * as musicApi from '../api/music' ...@@ -11,6 +11,7 @@ import * as musicApi from '../api/music'
const CHAT = { id: 1, title: 'Music Sharing', type: 'group' } const CHAT = { id: 1, title: 'Music Sharing', type: 'group' }
const MUSIC = { message_id: 1, title: 'Invisible', artist: 'Duran Duran', duration: 200, file_name: 'invisible.mp3' } const MUSIC = { message_id: 1, title: 'Invisible', artist: 'Duran Duran', duration: 200, file_name: 'invisible.mp3' }
const MUSIC_2 = { message_id: 2, title: 'Rio', artist: 'Duran Duran', duration: 210, file_name: 'rio.mp3' }
const TAG_RESPONSE = { const TAG_RESPONSE = {
status: 'success', status: 'success',
metadata: { metadata: {
...@@ -298,4 +299,40 @@ describe('TelegramLink', () => { ...@@ -298,4 +299,40 @@ describe('TelegramLink', () => {
expect(await screen.findByText('Saved')).toBeInTheDocument() expect(await screen.findByText('Saved')).toBeInTheDocument()
expect(tagFromChat).toHaveBeenCalledTimes(2) expect(tagFromChat).toHaveBeenCalledTimes(2)
}) })
it('saves multiple selected songs at once', async () => {
vi.spyOn(authApi, 'getChats').mockResolvedValue({ status: 'success', chats: [CHAT] })
vi.spyOn(authApi, 'getChatMusic').mockResolvedValue({ status: 'success', music: [MUSIC, MUSIC_2] })
const tagFromChat = vi.spyOn(musicApi, 'tagFromChat').mockResolvedValue(TAG_RESPONSE)
renderPage()
await userEvent.click(await screen.findByText('Music Sharing'))
await screen.findByText('Invisible')
await screen.findByText('Rio')
await userEvent.click(screen.getByLabelText('Select Invisible'))
await userEvent.click(screen.getByLabelText('Select Rio'))
expect(screen.getByText('2 selected')).toBeInTheDocument()
await userEvent.click(screen.getByRole('button', { name: 'Save 2 selected' }))
expect(tagFromChat).toHaveBeenCalledWith(1, 1)
expect(tagFromChat).toHaveBeenCalledWith(1, 2)
expect(tagFromChat).toHaveBeenCalledTimes(2)
await waitFor(() => expect(screen.getAllByText('Saved')).toHaveLength(2))
expect(screen.queryByText(/selected/)).not.toBeInTheDocument()
})
it('does not show a select checkbox for a song already saved', async () => {
vi.spyOn(authApi, 'getChats').mockResolvedValue({ status: 'success', chats: [CHAT] })
vi.spyOn(authApi, 'getChatMusic').mockResolvedValue({ status: 'success', music: [MUSIC] })
vi.spyOn(musicApi, 'tagFromChat').mockResolvedValue(TAG_RESPONSE)
renderPage()
await userEvent.click(await screen.findByText('Music Sharing'))
await userEvent.click(await screen.findByRole('button', { name: /Save/ }))
await screen.findByText('Saved')
expect(screen.queryByLabelText('Select Invisible')).not.toBeInTheDocument()
})
}) })
...@@ -49,9 +49,10 @@ export function TelegramLink() { ...@@ -49,9 +49,10 @@ export function TelegramLink() {
const [musicLoading, setMusicLoading] = useState(false) const [musicLoading, setMusicLoading] = useState(false)
const [musicError, setMusicError] = useState<string | null>(null) const [musicError, setMusicError] = useState<string | null>(null)
const [savingId, setSavingId] = useState<number | null>(null) const [savingIds, setSavingIds] = useState<Set<number>>(new Set())
const [savedMeta, setSavedMeta] = useState<Record<number, TagMetadata>>({}) const [savedMeta, setSavedMeta] = useState<Record<number, TagMetadata>>({})
const [saveErrors, setSaveErrors] = useState<Record<number, string>>({}) const [saveErrors, setSaveErrors] = useState<Record<number, string>>({})
const [selectedIds, setSelectedIds] = useState<Set<number>>(new Set())
const { currentSong, isPlaying, toggle } = usePlayer() const { currentSong, isPlaying, toggle } = usePlayer()
...@@ -143,15 +144,25 @@ export function TelegramLink() { ...@@ -143,15 +144,25 @@ export function TelegramLink() {
setMusicLoading(true) setMusicLoading(true)
setSavedMeta({}) setSavedMeta({})
setSaveErrors({}) setSaveErrors({})
setSelectedIds(new Set())
getChatMusic(chat.id) getChatMusic(chat.id)
.then((res) => setMusic(res.music)) .then((res) => setMusic(res.music))
.catch((err) => setMusicError(err instanceof ApiError ? err.message : 'Failed to load music from this chat')) .catch((err) => setMusicError(err instanceof ApiError ? err.message : 'Failed to load music from this chat'))
.finally(() => setMusicLoading(false)) .finally(() => setMusicLoading(false))
} }
function toggleSelected(messageId: number) {
setSelectedIds((prev) => {
const next = new Set(prev)
if (next.has(messageId)) next.delete(messageId)
else next.add(messageId)
return next
})
}
async function handleSave(m: ChatMusic) { async function handleSave(m: ChatMusic) {
if (!selectedChat) return if (!selectedChat) return
setSavingId(m.message_id) setSavingIds((prev) => new Set(prev).add(m.message_id))
setSaveErrors((prev) => { setSaveErrors((prev) => {
const next = { ...prev } const next = { ...prev }
delete next[m.message_id] delete next[m.message_id]
...@@ -166,7 +177,27 @@ export function TelegramLink() { ...@@ -166,7 +177,27 @@ export function TelegramLink() {
[m.message_id]: err instanceof ApiError ? err.message : 'Failed to save this song', [m.message_id]: err instanceof ApiError ? err.message : 'Failed to save this song',
})) }))
} finally { } finally {
setSavingId(null) setSavingIds((prev) => {
const next = new Set(prev)
next.delete(m.message_id)
return next
})
setSelectedIds((prev) => {
const next = new Set(prev)
next.delete(m.message_id)
return next
})
}
}
async function handleSaveSelected() {
if (!music) return
// Sequential, same reasoning as Upload's multi-file queue - /music/tag runs the same
// network- and CPU-heavy identify/tag pipeline per song, so this deliberately doesn't
// race several through it at once.
for (const m of music) {
if (!selectedIds.has(m.message_id) || savedMeta[m.message_id]) continue
await handleSave(m)
} }
} }
...@@ -285,14 +316,32 @@ export function TelegramLink() { ...@@ -285,14 +316,32 @@ export function TelegramLink() {
{!musicLoading && !musicError && music?.length === 0 && ( {!musicLoading && !musicError && music?.length === 0 && (
<EmptyState icon={Music2} message="No music found in this chat." /> <EmptyState icon={Music2} message="No music found in this chat." />
)} )}
{selectedIds.size > 0 && (
<div className="sticky top-0 z-10 -mx-2 mb-2 flex items-center justify-between gap-3 bg-background/95 px-2 py-2 backdrop-blur">
<p className="text-sm text-on-surface-variant">{selectedIds.size} selected</p>
<Button size="sm" disabled={savingIds.size > 0} onClick={handleSaveSelected}>
{savingIds.size > 0 ? 'Saving…' : `Save ${selectedIds.size} selected`}
</Button>
</div>
)}
<ul className="divide-y divide-outline-variant/80"> <ul className="divide-y divide-outline-variant/80">
{music?.map((m) => { {music?.map((m) => {
const saved = savedMeta[m.message_id] const saved = savedMeta[m.message_id]
const saveError = saveErrors[m.message_id] const saveError = saveErrors[m.message_id]
const saving = savingId === m.message_id const saving = savingIds.has(m.message_id)
const isCurrent = currentSong?.id === -m.message_id const isCurrent = currentSong?.id === -m.message_id
return ( return (
<li key={m.message_id} className="flex items-center gap-4 px-2 py-3"> <li key={m.message_id} className="flex items-center gap-4 px-2 py-3">
{!saved && (
<input
type="checkbox"
checked={selectedIds.has(m.message_id)}
onChange={() => toggleSelected(m.message_id)}
disabled={saving}
aria-label={`Select ${m.title}`}
className="h-4 w-4 shrink-0 accent-primary"
/>
)}
<button <button
onClick={() => toggle(toPreviewPlayable(selectedChat.id, m))} onClick={() => toggle(toPreviewPlayable(selectedChat.id, m))}
aria-label={isCurrent && isPlaying ? `Pause ${m.title}` : `Play 30 second preview of ${m.title}`} aria-label={isCurrent && isPlaying ? `Pause ${m.title}` : `Play 30 second preview of ${m.title}`}
......
...@@ -101,4 +101,47 @@ describe('Upload', () => { ...@@ -101,4 +101,47 @@ describe('Upload', () => {
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument()) await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
}) })
it('accepts multiple files at once and tags each one independently', async () => {
const responses: Record<string, typeof TAG_RESPONSE> = {
'one.mp3': { ...TAG_RESPONSE, metadata: { ...TAG_RESPONSE.metadata, library_song_id: 1, title: 'Song One' } },
'two.mp3': { ...TAG_RESPONSE, metadata: { ...TAG_RESPONSE.metadata, library_song_id: 2, title: 'Song Two' } },
}
const uploadDirect = vi.spyOn(musicApi, 'uploadDirect').mockImplementation(async (file, onProgress) => {
onProgress?.(100)
return responses[file.name]
})
renderPage()
const files = [
new File([new Uint8Array([1])], 'one.mp3', { type: 'audio/mpeg' }),
new File([new Uint8Array([2])], 'two.mp3', { type: 'audio/mpeg' }),
]
const input = document.querySelector('input[type="file"]') as HTMLInputElement
await userEvent.upload(input, files)
expect(screen.getByText('one.mp3')).toBeInTheDocument()
expect(screen.getByText('two.mp3')).toBeInTheDocument()
await userEvent.click(screen.getByRole('button', { name: 'Upload 2 files' }))
expect(await screen.findByText('Song One')).toBeInTheDocument()
expect(await screen.findByText('Song Two')).toBeInTheDocument()
expect(uploadDirect).toHaveBeenCalledTimes(2)
})
it('lets a still-queued file be removed before uploading', async () => {
vi.spyOn(musicApi, 'uploadDirect')
renderPage()
const file = new File([new Uint8Array([1])], 'test.mp3', { type: 'audio/mpeg' })
const input = document.querySelector('input[type="file"]') as HTMLInputElement
await userEvent.upload(input, file)
expect(screen.getByText('test.mp3')).toBeInTheDocument()
await userEvent.click(screen.getByRole('button', { name: 'Remove test.mp3' }))
expect(screen.queryByText('test.mp3')).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: /Upload/ })).not.toBeInTheDocument()
})
}) })
import { useState } from 'react' import { useState } from 'react'
import { ListPlus, Pause, Play, UploadCloud } from 'lucide-react' import { ListPlus, Pause, 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 { ProgressBar } from '../components/ui/ProgressBar'
import { AddToPlaylistModal } from '../components/AddToPlaylistModal' import { AddToPlaylistModal } from '../components/AddToPlaylistModal'
import { uploadDirect, type TagResponse } from '../api/music' import { uploadDirect, type TagResponse } from '../api/music'
import { usePlayer } from '../context/PlayerContext' import { usePlayer, type PlayableSong } from '../context/PlayerContext'
type Stage = 'idle' | 'uploading' | 'processing' type ItemStage = 'queued' | 'uploading' | 'processing' | 'done' | 'error'
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)}`
}
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
}) {
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 ? 'Pause' : '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>
<button
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"
>
<ListPlus size={15} strokeWidth={1.75} />
Add to playlist
</button>
</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.file.name}</p>
{item.stage === 'queued' && (
<button
onClick={onRemove}
aria-label={`Remove ${item.file.name}`}
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') && (
<div className="mt-2">
<ProgressBar
percent={item.stage === 'uploading' ? item.uploadPercent : null}
label={item.stage === 'uploading' ? 'Uploading' : 'Identifying & tagging…'}
/>
</div>
)}
{item.stage === 'error' && <p className="mt-2 text-sm text-error">{item.error}</p>}
</div>
)
}
export function Upload() { export function Upload() {
const [file, setFile] = useState<File | null>(null) const [items, setItems] = useState<UploadItem[]>([])
const [stage, setStage] = useState<Stage>('idle') const [busy, setBusy] = useState(false)
const [uploadPercent, setUploadPercent] = useState(0) const [addingToPlaylistId, setAddingToPlaylistId] = useState<string | null>(null)
const [result, setResult] = useState<TagResponse | null>(null) const { currentSong, isPlaying, isLoading: streamLoading, toggle } = usePlayer()
const [error, setError] = useState<string | null>(null)
const [addingToPlaylist, setAddingToPlaylist] = useState(false) function updateItem(id: string, patch: Partial<UploadItem>) {
setItems((prev) => prev.map((it) => (it.id === id ? { ...it, ...patch } : it)))
async function handleUpload() { }
if (!file) return
setStage('uploading') function handleSelectFiles(fileList: FileList | null) {
setUploadPercent(0) if (!fileList || fileList.length === 0) return
setError(null) const newItems: UploadItem[] = Array.from(fileList).map((file) => ({
setResult(null) id: makeId(),
try { file,
const res = await uploadDirect(file, (percent) => { stage: 'queued',
setUploadPercent(percent) uploadPercent: 0,
// The transfer itself is done once this hits 100 - everything after that (identify, result: null,
// lyrics, genre, tag, store) is the server's job and has no progress of its own to error: null,
// report, so the bar switches to an indeterminate state for that part. }))
if (percent >= 100) setStage('processing') setItems((prev) => [...prev, ...newItems])
}) }
setResult(res)
} catch (err) { function removeItem(id: string) {
setError(err instanceof Error ? err.message : 'Upload failed') setItems((prev) => prev.filter((it) => it.id !== id))
} finally { }
setStage('idle')
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 : 'Upload failed' })
}
} }
setBusy(false)
} }
const busy = stage !== 'idle' const queuedCount = items.filter((it) => it.stage === 'queued').length
const { currentSong, isPlaying, isLoading: streamLoading, toggle } = usePlayer() const addingToPlaylistItem = items.find((it) => it.id === addingToPlaylistId)
const isCurrent = !!result && currentSong?.id === result.metadata.library_song_id
return ( return (
<Layout title="Upload &amp; Tag"> <Layout title="Upload &amp; Tag">
<p className="mb-6 text-sm leading-relaxed text-on-surface-variant"> <p className="mb-6 text-sm leading-relaxed text-on-surface-variant">
Upload an untagged track - it's fingerprinted, tagged with title/artist/album/art/lyrics, and Upload untagged tracks - each is fingerprinted, tagged with title/artist/album/art/lyrics, and
added to your library. added to your library.
</p> </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"> <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" /> <UploadCloud size={28} strokeWidth={1.5} className="text-outline" />
<span className="text-sm text-on-surface-variant"> <span className="text-sm text-on-surface-variant">Choose audio files, or drag them here</span>
{file ? file.name : 'Choose an audio file, or drag one here'}
</span>
<input <input
type="file" type="file"
accept="audio/*" accept="audio/*"
multiple
disabled={busy} disabled={busy}
onChange={(e) => setFile(e.target.files?.[0] ?? null)} onChange={(e) => {
handleSelectFiles(e.target.files)
e.target.value = ''
}}
className="hidden" className="hidden"
/> />
</label> </label>
{busy && ( {items.length > 0 && (
<div className="mt-4"> <div className="mt-6 space-y-3">
<ProgressBar {items.map((item) => (
percent={stage === 'uploading' ? uploadPercent : null} <UploadItemRow
label={stage === 'uploading' ? 'Uploading' : 'Identifying & tagging…'} key={item.id}
/> 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>
)} )}
<Button onClick={handleUpload} disabled={!file || busy} className="mt-4 w-full"> {queuedCount > 0 && (
{stage === 'uploading' ? 'Uploading…' : stage === 'processing' ? 'Processing…' : 'Upload'} <Button onClick={handleUploadAll} disabled={busy} className="mt-4 w-full">
</Button> {busy ? 'Uploading…' : `Upload ${queuedCount} file${queuedCount === 1 ? '' : 's'}`}
</Button>
{error && <p className="mt-4 text-sm text-error">{error}</p>}
{result && (
<div className="mt-6 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={() =>
toggle({
id: result.metadata.library_song_id,
title: result.metadata.title,
artist: result.metadata.artist,
album: result.metadata.album,
coverart: result.metadata.cover_art,
lyrics: result.metadata.lyrics,
})
}
disabled={isCurrent && streamLoading}
aria-label={isCurrent && isPlaying ? 'Pause' : '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"
>
{result.metadata.cover_art ? (
<img src={result.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">{result.metadata.title}</p>
<p className="truncate text-sm text-on-surface-variant">
{result.metadata.artist} · {result.metadata.album} · {result.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>
<button
onClick={() => setAddingToPlaylist(true)}
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"
>
<ListPlus size={15} strokeWidth={1.75} />
Add to playlist
</button>
</div>
)} )}
{result && addingToPlaylist && ( {addingToPlaylistItem?.result && (
<AddToPlaylistModal <AddToPlaylistModal
song={{ id: result.metadata.library_song_id, title: result.metadata.title }} song={{
onClose={() => setAddingToPlaylist(false)} id: addingToPlaylistItem.result.metadata.library_song_id,
title: addingToPlaylistItem.result.metadata.title,
}}
onClose={() => setAddingToPlaylistId(null)}
/> />
)} )}
</Layout> </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