feat(web): the Suggestions tab of Discover with seeds, taste and clear states
Nothing is asked of Discover until there is an artist the user picked or their listening is allowed. Covers a busy server (Retry-After countdown), Last.fm off or failing, cancelling a slow request when leaving, and no automatic retries. Also adds the starting-artist picker and a taste panel.
This commit is contained in:
parent
71b0b39a07
commit
60349153c0
12 changed files with 647 additions and 4 deletions
|
|
@ -53,6 +53,16 @@ test('Discover gives the request a signal, so leaving the page can cancel it', a
|
|||
expect(calls[0].init.signal).toBeInstanceOf(AbortSignal)
|
||||
})
|
||||
|
||||
test('a failed Discover is not asked again by itself, whatever the app default is', async () => {
|
||||
const { calls } = mockFetch({ 'GET /api/v1/discover': () => apiError(429, 'discover_busy') })
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: 2, retryDelay: 1 } } })
|
||||
const wrapper = ({ children }: { children: ReactNode }) => <QueryClientProvider client={client}>{children}</QueryClientProvider>
|
||||
const { result } = renderHook(() => useDiscover({ seeds: [1] }), { wrapper })
|
||||
await waitFor(() => expect(result.current.isError).toBe(true))
|
||||
await new Promise((r) => setTimeout(r, 50))
|
||||
expect(calls).toHaveLength(1)
|
||||
})
|
||||
|
||||
test('the wishlist and the dismissed list are read page after page', async () => {
|
||||
const { calls } = mockFetch({
|
||||
'GET /api/v1/wishlist': ({ url }) => ({ items: [marked(1)], total: 1, limit: 50, offset: Number(url.searchParams.get('offset')) }),
|
||||
|
|
|
|||
|
|
@ -31,6 +31,8 @@ export function useDiscover({ seeds, inLibrary, enabled = true }: DiscoverOption
|
|||
enabled,
|
||||
staleTime: 5 * 60_000,
|
||||
refetchOnWindowFocus: false,
|
||||
// A busy answer (429) or a slow one is the user's to retry with a button, never repeated behind their back.
|
||||
retry: false,
|
||||
queryFn: ({ signal }) => api.get<Discover>('/discover', { seed: seeds, in_library: inLibrary }, { signal }),
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ import { render, screen, waitFor } from '@testing-library/react'
|
|||
import userEvent from '@testing-library/user-event'
|
||||
import { beforeEach, expect, test, vi } from 'vitest'
|
||||
import { initI18n } from '@/i18n'
|
||||
import { apiError, mockFetch, type MockRoutes } from '@/test/mockFetch'
|
||||
import { apiError, mockFetch, type MockRoutes, type RecordedCall } from '@/test/mockFetch'
|
||||
import ListeningSwitch from './ListeningSwitch'
|
||||
|
||||
beforeEach(async () => {
|
||||
|
|
@ -31,7 +31,7 @@ function setup(initial: boolean, over: MockRoutes = {}) {
|
|||
}
|
||||
|
||||
const toggle = () => screen.findByRole('switch', { name: 'Start Discover from my listening' })
|
||||
const patches = (calls: { key: string }[]) => calls.filter((c) => c.key === 'PATCH /api/v1/me/settings')
|
||||
const patches = (calls: RecordedCall[]) => calls.filter((c) => c.key === 'PATCH /api/v1/me/settings')
|
||||
|
||||
test('it says what turning it on sends, before anything is asked', async () => {
|
||||
setup(false)
|
||||
|
|
|
|||
|
|
@ -66,6 +66,28 @@
|
|||
"why": "Why this?",
|
||||
"wishlist": "Wishlist",
|
||||
"notInterested": "Not interested",
|
||||
"invite": "Pick an artist to start from, or let Discover start from your listening.",
|
||||
"waiting": "Asking Last.fm can take several seconds.",
|
||||
"fromListening": "Started from your listening: {{names}}",
|
||||
"onlyNew": "Only artists I do not have",
|
||||
"none": "No suggestions yet.",
|
||||
"partial": "Last.fm could not be reached for some artists, so this list may be shorter.",
|
||||
"busy": "Discover is busy with another request. Try again in a moment.",
|
||||
"retryIn": "Try again in {{seconds}} s",
|
||||
"seeds": {
|
||||
"label": "Find an artist to start from",
|
||||
"list": "Starting artists",
|
||||
"add": "Add {{name}}",
|
||||
"remove": "Remove {{name}}",
|
||||
"max": "You can pick up to {{count}} artists.",
|
||||
"privacy": "Last.fm is asked about these artists, if an admin turned it on."
|
||||
},
|
||||
"taste": {
|
||||
"title": "Your taste",
|
||||
"empty": "Your taste appears here once you have listened to something.",
|
||||
"tags": "Kinds of music you like",
|
||||
"artists": "Artists you like: {{names}}"
|
||||
},
|
||||
"parts": {
|
||||
"label": "How the score is made",
|
||||
"a": "Similar to your starting artists",
|
||||
|
|
|
|||
|
|
@ -66,6 +66,28 @@
|
|||
"why": "Perché questo?",
|
||||
"wishlist": "Wishlist",
|
||||
"notInterested": "Non mi interessa",
|
||||
"invite": "Scegli un artista da cui partire, oppure lascia che Discover parta dai tuoi ascolti.",
|
||||
"waiting": "Interrogare Last.fm può richiedere diversi secondi.",
|
||||
"fromListening": "Partito dai tuoi ascolti: {{names}}",
|
||||
"onlyNew": "Solo artisti che non ho",
|
||||
"none": "Ancora nessun suggerimento.",
|
||||
"partial": "Last.fm non era raggiungibile per alcuni artisti, quindi la lista può essere più corta.",
|
||||
"busy": "Discover è occupato con un'altra richiesta. Riprova tra poco.",
|
||||
"retryIn": "Riprova tra {{seconds}} s",
|
||||
"seeds": {
|
||||
"label": "Cerca un artista da cui partire",
|
||||
"list": "Artisti di partenza",
|
||||
"add": "Aggiungi {{name}}",
|
||||
"remove": "Togli {{name}}",
|
||||
"max": "Puoi scegliere al massimo {{count}} artisti.",
|
||||
"privacy": "Last.fm viene interrogato su questi artisti, se un admin l'ha acceso."
|
||||
},
|
||||
"taste": {
|
||||
"title": "I tuoi gusti",
|
||||
"empty": "I tuoi gusti compaiono qui dopo che hai ascoltato qualcosa.",
|
||||
"tags": "Generi che ti piacciono",
|
||||
"artists": "Artisti che ti piacciono: {{names}}"
|
||||
},
|
||||
"parts": {
|
||||
"label": "Come si calcola il punteggio",
|
||||
"a": "Simile agli artisti di partenza",
|
||||
|
|
|
|||
81
web/src/pages/discover/SeedPicker.test.tsx
Normal file
81
web/src/pages/discover/SeedPicker.test.tsx
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { render, screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { useState } from 'react'
|
||||
import { beforeEach, expect, test, vi } from 'vitest'
|
||||
import { sessionStore } from '@/auth/session'
|
||||
import { initI18n } from '@/i18n'
|
||||
import { mockFetch } from '@/test/mockFetch'
|
||||
import SeedPicker, { type Seed } from './SeedPicker'
|
||||
|
||||
const artist = (id: number, name: string) => ({ id, name, album_count: 1, track_count: 3 })
|
||||
|
||||
function Harness({ start = [] as Seed[] }) {
|
||||
const [seeds, setSeeds] = useState<Seed[]>(start)
|
||||
return (
|
||||
<SeedPicker
|
||||
seeds={seeds}
|
||||
onAdd={(s) => setSeeds((all) => [...all, s])}
|
||||
onRemove={(id) => setSeeds((all) => all.filter((s) => s.id !== id))}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function renderPicker(start: Seed[] = []) {
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
return render(
|
||||
<QueryClientProvider client={client}>
|
||||
<Harness start={start} />
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
}
|
||||
|
||||
const box = () => screen.getByRole('searchbox', { name: 'Find an artist to start from' })
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.spyOn(navigator, 'language', 'get').mockReturnValue('en-US')
|
||||
await initI18n()
|
||||
sessionStore.setState({ status: 'authenticated', user: { id: 1, username: 'tom', is_admin: false } })
|
||||
})
|
||||
|
||||
test('nothing is asked of the library until something is typed', async () => {
|
||||
const { calls } = mockFetch({ 'GET /api/v1/artists': () => ({ items: [], total: 0, limit: 6, offset: 0 }) })
|
||||
renderPicker()
|
||||
await new Promise((r) => setTimeout(r, 350))
|
||||
expect(calls).toHaveLength(0)
|
||||
})
|
||||
|
||||
test('typing finds artists, and choosing one makes it a chip', async () => {
|
||||
const { calls } = mockFetch({
|
||||
'GET /api/v1/artists': () => ({ items: [artist(1, 'Björk'), artist(2, 'Bjørn')], total: 2, limit: 6, offset: 0 }),
|
||||
})
|
||||
renderPicker()
|
||||
await userEvent.type(box(), 'bj')
|
||||
await userEvent.click(await screen.findByRole('button', { name: 'Add Björk' }))
|
||||
expect(calls.at(-1)?.url.searchParams.get('q')).toBe('bj')
|
||||
expect(screen.getByRole('list', { name: 'Starting artists' })).toHaveTextContent('Björk')
|
||||
// A chosen artist is not offered again.
|
||||
await waitFor(() => expect(screen.queryByRole('button', { name: 'Add Björk' })).not.toBeInTheDocument())
|
||||
expect(screen.getByRole('button', { name: 'Add Bjørn' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('a chip can be taken away', async () => {
|
||||
mockFetch({})
|
||||
renderPicker([{ id: 1, name: 'Björk' }])
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Remove Björk' }))
|
||||
expect(screen.queryByRole('list', { name: 'Starting artists' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('five artists is the most, and the box says why it stopped', async () => {
|
||||
mockFetch({})
|
||||
const five = [1, 2, 3, 4, 5].map((i) => ({ id: i, name: `A${i}` }))
|
||||
renderPicker(five)
|
||||
expect(box()).toBeDisabled()
|
||||
expect(screen.getByText('You can pick up to 5 artists.')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('the privacy note says Last.fm is asked about the chosen artists', () => {
|
||||
mockFetch({})
|
||||
renderPicker([{ id: 1, name: 'Björk' }])
|
||||
expect(screen.getByText(/Last\.fm is asked about these artists/)).toBeInTheDocument()
|
||||
})
|
||||
96
web/src/pages/discover/SeedPicker.tsx
Normal file
96
web/src/pages/discover/SeedPicker.tsx
Normal file
|
|
@ -0,0 +1,96 @@
|
|||
import { useEffect, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useArtistList } from '@/api/catalog'
|
||||
import { EmptyMessage } from '@/components/Status'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
|
||||
export interface Seed {
|
||||
id: number
|
||||
name: string
|
||||
}
|
||||
|
||||
/** What Discover accepts. */
|
||||
export const MAX_SEEDS = 5
|
||||
/** Wait this long after the last keystroke before asking the library. */
|
||||
const DEBOUNCE_MS = 250
|
||||
/** What the server accepts as search text. */
|
||||
const MAX_QUERY_LENGTH = 200
|
||||
const SHOWN = 6
|
||||
|
||||
/** The artists Discover starts from: the chosen ones as chips, and a box to find more in your library. */
|
||||
export default function SeedPicker({
|
||||
seeds,
|
||||
onAdd,
|
||||
onRemove,
|
||||
}: {
|
||||
seeds: Seed[]
|
||||
onAdd: (seed: Seed) => void
|
||||
onRemove: (id: number) => void
|
||||
}) {
|
||||
const { t } = useTranslation()
|
||||
const [text, setText] = useState('')
|
||||
const [typed, setTyped] = useState('')
|
||||
const full = seeds.length >= MAX_SEEDS
|
||||
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => setTyped(text), DEBOUNCE_MS)
|
||||
return () => clearTimeout(timer)
|
||||
}, [text])
|
||||
|
||||
const q = Array.from(typed.trim()).slice(0, MAX_QUERY_LENGTH).join('')
|
||||
const found = useArtistList(q, { pageSize: SHOWN, enabled: q !== '' && !full })
|
||||
const chosen = new Set(seeds.map((s) => s.id))
|
||||
const offered = (found.data?.items ?? []).filter((a) => !chosen.has(a.id))
|
||||
|
||||
return (
|
||||
<div className="flex max-w-xl flex-col gap-3">
|
||||
{seeds.length > 0 && (
|
||||
<ul aria-label={t('discover.seeds.list')} className="flex flex-wrap gap-2">
|
||||
{seeds.map((seed) => (
|
||||
<li key={seed.id} className="flex items-center gap-1 rounded-md bg-secondary py-1 pr-1 pl-3 font-semibold">
|
||||
<span>{seed.name}</span>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t('discover.seeds.remove', { name: seed.name })}
|
||||
onClick={() => onRemove(seed.id)}
|
||||
className="flex size-7 items-center justify-center rounded-sm text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<span aria-hidden="true">×</span>
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
<Input
|
||||
type="search"
|
||||
value={text}
|
||||
disabled={full}
|
||||
placeholder={t('discover.seeds.label')}
|
||||
aria-label={t('discover.seeds.label')}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
/>
|
||||
{full && <p className="text-sm text-muted-foreground">{t('discover.seeds.max', { count: MAX_SEEDS })}</p>}
|
||||
|
||||
{!full && q !== '' && found.isSuccess && offered.length === 0 && <EmptyMessage>{t('empty.noMatch', { q })}</EmptyMessage>}
|
||||
{offered.length > 0 && (
|
||||
<ul className="flex flex-wrap gap-2">
|
||||
{offered.map((artist) => (
|
||||
<li key={artist.id}>
|
||||
<Button
|
||||
variant="outline"
|
||||
aria-label={t('discover.seeds.add', { name: artist.name })}
|
||||
onClick={() => onAdd({ id: artist.id, name: artist.name })}
|
||||
>
|
||||
{artist.name}
|
||||
</Button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
{seeds.length > 0 && <p className="text-sm text-muted-foreground">{t('discover.seeds.privacy')}</p>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
@ -67,11 +67,11 @@ export default function SuggestionCard({ suggestion }: { suggestion: Suggestion
|
|||
</ul>
|
||||
</details>
|
||||
|
||||
{failure && (
|
||||
{failure ? (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{t(errorMessageKey(failure instanceof ApiError ? failure.code : 'unknown'))}
|
||||
</p>
|
||||
)}
|
||||
) : null}
|
||||
</li>
|
||||
)
|
||||
}
|
||||
|
|
|
|||
198
web/src/pages/discover/SuggestionsTab.test.tsx
Normal file
198
web/src/pages/discover/SuggestionsTab.test.tsx
Normal file
|
|
@ -0,0 +1,198 @@
|
|||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { render, screen, waitFor, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { MemoryRouter } from 'react-router-dom'
|
||||
import { beforeEach, expect, test, vi } from 'vitest'
|
||||
import { sessionStore } from '@/auth/session'
|
||||
import { initI18n } from '@/i18n'
|
||||
import { apiError, mockFetch, type MockRoutes, type RecordedCall } from '@/test/mockFetch'
|
||||
import SuggestionsTab from './SuggestionsTab'
|
||||
|
||||
const none = () => new Response(null, { status: 204 })
|
||||
|
||||
const suggestion = (id: number, name: string, wishlisted = false) => ({
|
||||
artist: { id, name },
|
||||
in_library: false,
|
||||
wishlisted,
|
||||
score: 0.7,
|
||||
components: { a: 0.6, g: null, p: 0.5, d: 1 },
|
||||
because: [{ artist: { id: 1, name: 'Björk' }, match: 0.9 }],
|
||||
})
|
||||
|
||||
const answer = (over: object = {}) => ({
|
||||
provider_status: 'ok',
|
||||
attribution: 'Similar artists from Last.fm',
|
||||
from_listening: false,
|
||||
seeds: [],
|
||||
items: [suggestion(7, 'Portishead'), suggestion(8, 'Massive Attack')],
|
||||
...over,
|
||||
})
|
||||
|
||||
function routes(listening: boolean, over: MockRoutes = {}): MockRoutes {
|
||||
return {
|
||||
'GET /api/v1/me/settings': () => ({ discover_from_listening: listening }),
|
||||
'GET /api/v1/me/taste': () => ({ artists: [], tags: [] }),
|
||||
'GET /api/v1/discover': () => answer(),
|
||||
'GET /api/v1/artists': () => ({ items: [{ id: 1, name: 'Björk', album_count: 1, track_count: 3 }], total: 1, limit: 6, offset: 0 }),
|
||||
...over,
|
||||
}
|
||||
}
|
||||
|
||||
function renderTab() {
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } })
|
||||
return render(
|
||||
<QueryClientProvider client={client}>
|
||||
<MemoryRouter>
|
||||
<SuggestionsTab />
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
}
|
||||
|
||||
const discoverCalls = (calls: RecordedCall[]) => calls.filter((c) => c.key === 'GET /api/v1/discover')
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.spyOn(navigator, 'language', 'get').mockReturnValue('en-US')
|
||||
await initI18n()
|
||||
sessionStore.setState({ status: 'authenticated', user: { id: 1, username: 'tom', is_admin: false } })
|
||||
})
|
||||
|
||||
test('with no starting artist and your listening not allowed, nothing is sent and you are invited to pick', async () => {
|
||||
const { calls } = mockFetch(routes(false))
|
||||
renderTab()
|
||||
expect(await screen.findByText('Pick an artist to start from, or let Discover start from your listening.')).toBeInTheDocument()
|
||||
expect(screen.getByRole('switch', { name: 'Start Discover from my listening' })).toBeInTheDocument()
|
||||
await new Promise((r) => setTimeout(r, 50))
|
||||
expect(discoverCalls(calls)).toHaveLength(0)
|
||||
})
|
||||
|
||||
test('nothing is asked of Discover before the settings are known', async () => {
|
||||
const { calls } = mockFetch(routes(true, { 'GET /api/v1/me/settings': () => new Promise(() => {}) }))
|
||||
renderTab()
|
||||
await new Promise((r) => setTimeout(r, 80))
|
||||
expect(discoverCalls(calls)).toHaveLength(0)
|
||||
})
|
||||
|
||||
test('with your listening allowed it starts at once, names no artist, and shows where it started', async () => {
|
||||
const { calls } = mockFetch(
|
||||
routes(true, {
|
||||
'GET /api/v1/discover': () =>
|
||||
answer({ from_listening: true, seeds: [{ id: 1, name: 'Björk', weight: 0.9 }, { id: 2, name: 'Portis', weight: 0.4 }] }),
|
||||
}),
|
||||
)
|
||||
renderTab()
|
||||
expect(await screen.findByRole('link', { name: 'Portishead' })).toBeInTheDocument()
|
||||
expect(discoverCalls(calls)[0].url.searchParams.has('seed')).toBe(false)
|
||||
expect(screen.getByText('Started from your listening: Björk, Portis')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('the suggestions are listed with the credit of the provider', async () => {
|
||||
mockFetch(routes(true))
|
||||
renderTab()
|
||||
expect(await screen.findByRole('link', { name: 'Massive Attack' })).toBeInTheDocument()
|
||||
expect(screen.getByText('Similar artists from Last.fm')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('choosing a starting artist asks Discover about it, and removing it goes back to the invitation', async () => {
|
||||
const { calls } = mockFetch(routes(false))
|
||||
renderTab()
|
||||
await userEvent.type(await screen.findByRole('searchbox', { name: 'Find an artist to start from' }), 'bj')
|
||||
await userEvent.click(await screen.findByRole('button', { name: 'Add Björk' }))
|
||||
expect(await screen.findByRole('link', { name: 'Portishead' })).toBeInTheDocument()
|
||||
expect(discoverCalls(calls)[0].url.searchParams.getAll('seed')).toEqual(['1'])
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Remove Björk' }))
|
||||
expect(await screen.findByText('Pick an artist to start from, or let Discover start from your listening.')).toBeInTheDocument()
|
||||
expect(screen.queryByRole('link', { name: 'Portishead' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('"Only artists I do not have" asks the server for in_library=false', async () => {
|
||||
const { calls } = mockFetch(routes(true))
|
||||
renderTab()
|
||||
await screen.findByRole('link', { name: 'Portishead' })
|
||||
await userEvent.click(screen.getByRole('checkbox', { name: 'Only artists I do not have' }))
|
||||
await waitFor(() => expect(discoverCalls(calls).at(-1)?.url.searchParams.get('in_library')).toBe('false'))
|
||||
})
|
||||
|
||||
test('a first answer can take seconds, and the page says so while it waits', async () => {
|
||||
mockFetch(routes(true, { 'GET /api/v1/discover': () => new Promise(() => {}) }))
|
||||
renderTab()
|
||||
expect(await screen.findByText('Asking Last.fm can take several seconds.')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('leaving the page cancels the request that is still waiting', async () => {
|
||||
const { calls } = mockFetch(routes(true, { 'GET /api/v1/discover': () => new Promise(() => {}) }))
|
||||
const view = renderTab()
|
||||
await waitFor(() => expect(discoverCalls(calls)).toHaveLength(1))
|
||||
const signal = discoverCalls(calls)[0] && (calls.find((c) => c.key === 'GET /api/v1/discover')?.init.signal as AbortSignal)
|
||||
expect(signal.aborted).toBe(false)
|
||||
view.unmount()
|
||||
await waitFor(() => expect(signal.aborted).toBe(true))
|
||||
})
|
||||
|
||||
test('when Last.fm is off it says so, and what was stored is still shown', async () => {
|
||||
mockFetch(routes(true, { 'GET /api/v1/discover': () => answer({ provider_status: 'disabled' }) }))
|
||||
renderTab()
|
||||
expect(await screen.findByRole('link', { name: 'Portishead' })).toBeInTheDocument()
|
||||
expect(screen.getByText('Turn on Last.fm in the server settings to see this.')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('when Last.fm failed for some artists the rest is shown with a warning', async () => {
|
||||
mockFetch(routes(true, { 'GET /api/v1/discover': () => answer({ provider_status: 'error' }) }))
|
||||
renderTab()
|
||||
expect(await screen.findByRole('link', { name: 'Portishead' })).toBeInTheDocument()
|
||||
expect(screen.getByText('Last.fm could not be reached for some artists, so this list may be shorter.')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('an empty answer says there is nothing yet', async () => {
|
||||
mockFetch(routes(true, { 'GET /api/v1/discover': () => answer({ items: [] }) }))
|
||||
renderTab()
|
||||
expect(await screen.findByText('No suggestions yet.')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('a busy server is explained and the button waits for the time the server asked', async () => {
|
||||
let n = 0
|
||||
mockFetch(
|
||||
routes(true, {
|
||||
'GET /api/v1/discover': () =>
|
||||
++n === 1
|
||||
? new Response(JSON.stringify({ error: { code: 'discover_busy', message: 'busy' } }), {
|
||||
status: 429,
|
||||
headers: { 'Content-Type': 'application/json', 'Retry-After': '1' },
|
||||
})
|
||||
: answer(),
|
||||
}),
|
||||
)
|
||||
renderTab()
|
||||
const wait = await screen.findByRole('button', { name: /Try again in/ })
|
||||
expect(wait).toBeDisabled()
|
||||
const again = await screen.findByRole('button', { name: 'Try again' }, { timeout: 3000 })
|
||||
expect(again).toBeEnabled()
|
||||
await userEvent.click(again)
|
||||
expect(await screen.findByRole('link', { name: 'Portishead' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('another failure is shown in words with a way to try again', async () => {
|
||||
mockFetch(routes(true, { 'GET /api/v1/discover': () => apiError(500, 'internal') }))
|
||||
renderTab()
|
||||
const alert = await screen.findByRole('alert')
|
||||
expect(within(alert).getByRole('button', { name: 'Try again' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('putting an artist on the wishlist marks it at once', async () => {
|
||||
mockFetch(routes(true, { 'PUT /api/v1/wishlist/7': none }))
|
||||
renderTab()
|
||||
await screen.findByRole('link', { name: 'Portishead' })
|
||||
const card = screen.getByRole('link', { name: 'Portishead' }).closest('li') as HTMLElement
|
||||
await userEvent.click(within(card).getByRole('button', { name: 'Wishlist' }))
|
||||
await waitFor(() => expect(within(card).getByRole('button', { name: 'Wishlist' })).toHaveAttribute('aria-pressed', 'true'))
|
||||
})
|
||||
|
||||
test('a dismissed artist leaves the list', async () => {
|
||||
mockFetch(routes(true, { 'POST /api/v1/discover/7/dismiss': none }))
|
||||
renderTab()
|
||||
const card = (await screen.findByRole('link', { name: 'Portishead' })).closest('li') as HTMLElement
|
||||
await userEvent.click(within(card).getByRole('button', { name: 'Not interested' }))
|
||||
await waitFor(() => expect(screen.queryByRole('link', { name: 'Portishead' })).not.toBeInTheDocument())
|
||||
expect(screen.getByRole('link', { name: 'Massive Attack' })).toBeInTheDocument()
|
||||
})
|
||||
119
web/src/pages/discover/SuggestionsTab.tsx
Normal file
119
web/src/pages/discover/SuggestionsTab.tsx
Normal file
|
|
@ -0,0 +1,119 @@
|
|||
import { useEffect, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { ApiError } from '@/api/client'
|
||||
import { useDiscover, useMySettings } from '@/api/discover'
|
||||
import Attribution from '@/components/Attribution'
|
||||
import ListeningSwitch from '@/components/ListeningSwitch'
|
||||
import ProviderMessage from '@/components/ProviderMessage'
|
||||
import { EmptyMessage, ErrorMessage, Loading } from '@/components/Status'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import SeedPicker, { type Seed } from './SeedPicker'
|
||||
import SuggestionCard from './SuggestionCard'
|
||||
import TastePanel from './TastePanel'
|
||||
|
||||
/** How long to wait when the server is busy and did not say. */
|
||||
const DEFAULT_WAIT_S = 5
|
||||
|
||||
/** The retry button of a busy server: it counts down the seconds the server asked for. */
|
||||
function BusyRetry({ seconds, onRetry }: { seconds: number; onRetry: () => void }) {
|
||||
const { t } = useTranslation()
|
||||
const [left, setLeft] = useState(seconds)
|
||||
useEffect(() => {
|
||||
if (left <= 0) return
|
||||
const timer = setTimeout(() => setLeft((s) => s - 1), 1000)
|
||||
return () => clearTimeout(timer)
|
||||
}, [left])
|
||||
return (
|
||||
<div className="flex flex-col items-start gap-3">
|
||||
<p>{t('discover.busy')}</p>
|
||||
<Button variant="outline" disabled={left > 0} onClick={onRetry}>
|
||||
{left > 0 ? t('discover.retryIn', { seconds: left }) : t('common.retry')}
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default function SuggestionsTab() {
|
||||
const { t } = useTranslation()
|
||||
const settings = useMySettings()
|
||||
const [seeds, setSeeds] = useState<Seed[]>([])
|
||||
const [onlyNew, setOnlyNew] = useState(false)
|
||||
|
||||
// Nothing goes to the server, and so to Last.fm, until there is something the user chose to start from:
|
||||
// an artist they picked, or their listening once they allowed it and the settings said so.
|
||||
const fromListening = settings.data?.discover_from_listening === true
|
||||
const ready = seeds.length > 0 || fromListening
|
||||
const discover = useDiscover({ seeds: seeds.map((s) => s.id), inLibrary: onlyNew ? false : undefined, enabled: ready })
|
||||
|
||||
const refused = discover.error instanceof ApiError && discover.error.code === 'seed_required'
|
||||
const busy = discover.error instanceof ApiError && discover.error.status === 429
|
||||
const data = discover.data
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-8">
|
||||
<TastePanel />
|
||||
|
||||
<SeedPicker
|
||||
seeds={seeds}
|
||||
onAdd={(seed) => setSeeds((all) => (all.some((s) => s.id === seed.id) ? all : [...all, seed]))}
|
||||
onRemove={(id) => setSeeds((all) => all.filter((s) => s.id !== id))}
|
||||
/>
|
||||
|
||||
{!ready && settings.isPending && <Loading />}
|
||||
{(!ready && !settings.isPending) || refused ? (
|
||||
<div className="flex flex-col gap-4">
|
||||
<EmptyMessage>{t('discover.invite')}</EmptyMessage>
|
||||
<ListeningSwitch />
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{ready && !refused && (
|
||||
<div className="flex flex-col gap-4">
|
||||
<label className="flex min-h-11 items-center gap-3 font-semibold">
|
||||
<input type="checkbox" checked={onlyNew} onChange={(e) => setOnlyNew(e.target.checked)} className="size-5 accent-primary" />
|
||||
{t('discover.onlyNew')}
|
||||
</label>
|
||||
|
||||
{discover.isPending && (
|
||||
<div className="flex flex-col gap-1">
|
||||
<Loading />
|
||||
<p className="text-sm text-muted-foreground">{t('discover.waiting')}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{discover.isError && !refused && (busy ? (
|
||||
<BusyRetry
|
||||
key={discover.errorUpdatedAt}
|
||||
seconds={(discover.error as ApiError).retryAfter ?? DEFAULT_WAIT_S}
|
||||
onRetry={() => void discover.refetch()}
|
||||
/>
|
||||
) : (
|
||||
<ErrorMessage error={discover.error} onRetry={() => void discover.refetch()} />
|
||||
))}
|
||||
|
||||
{data && (
|
||||
<>
|
||||
{data.provider_status === 'disabled' && <ProviderMessage status="disabled" provider="lastfm" />}
|
||||
{data.provider_status === 'error' && <EmptyMessage>{t('discover.partial')}</EmptyMessage>}
|
||||
{data.from_listening && seeds.length === 0 && data.seeds.length > 0 && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('discover.fromListening', { names: data.seeds.map((s) => s.name).join(', ') })}
|
||||
</p>
|
||||
)}
|
||||
{data.items.length === 0 ? (
|
||||
<EmptyMessage>{t('discover.none')}</EmptyMessage>
|
||||
) : (
|
||||
<ul className="flex flex-col gap-3">
|
||||
{data.items.map((item) => (
|
||||
<SuggestionCard key={item.artist.id} suggestion={item} />
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
<Attribution>{data.attribution}</Attribution>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
53
web/src/pages/discover/TastePanel.test.tsx
Normal file
53
web/src/pages/discover/TastePanel.test.tsx
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import { beforeEach, expect, test, vi } from 'vitest'
|
||||
import { sessionStore } from '@/auth/session'
|
||||
import { initI18n } from '@/i18n'
|
||||
import { apiError, mockFetch } from '@/test/mockFetch'
|
||||
import TastePanel from './TastePanel'
|
||||
|
||||
function renderPanel() {
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
return render(
|
||||
<QueryClientProvider client={client}>
|
||||
<TastePanel />
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.spyOn(navigator, 'language', 'get').mockReturnValue('en-US')
|
||||
await initI18n()
|
||||
sessionStore.setState({ status: 'authenticated', user: { id: 1, username: 'tom', is_admin: false } })
|
||||
})
|
||||
|
||||
test('it shows the kinds of music and the artists you like', async () => {
|
||||
mockFetch({
|
||||
'GET /api/v1/me/taste': () => ({
|
||||
artists: [{ id: 1, name: 'Björk', preference: 0.9, listens: 12, last_listened_at: '2026-11-01T00:00:00Z' }],
|
||||
tags: [
|
||||
{ tag: 'electronic', weight: 1 },
|
||||
{ tag: 'art pop', weight: 0.6 },
|
||||
],
|
||||
}),
|
||||
})
|
||||
renderPanel()
|
||||
const panel = await screen.findByRole('region', { name: 'Your taste' })
|
||||
expect(panel).toHaveTextContent('electronic')
|
||||
expect(panel).toHaveTextContent('art pop')
|
||||
expect(panel).toHaveTextContent('Björk')
|
||||
})
|
||||
|
||||
test('before you have listened to anything it says when it will fill in', async () => {
|
||||
mockFetch({ 'GET /api/v1/me/taste': () => ({ artists: [], tags: [] }) })
|
||||
renderPanel()
|
||||
expect(await screen.findByText('Your taste appears here once you have listened to something.')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('if it cannot be read it leaves no hole and no alarm', async () => {
|
||||
mockFetch({ 'GET /api/v1/me/taste': () => apiError(500, 'internal') })
|
||||
renderPanel()
|
||||
await new Promise((r) => setTimeout(r, 50))
|
||||
expect(screen.queryByRole('region', { name: 'Your taste' })).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('alert')).not.toBeInTheDocument()
|
||||
})
|
||||
40
web/src/pages/discover/TastePanel.tsx
Normal file
40
web/src/pages/discover/TastePanel.tsx
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
import { useTranslation } from 'react-i18next'
|
||||
import { useTaste } from '@/api/discover'
|
||||
import Section from '@/components/Section'
|
||||
import { EmptyMessage } from '@/components/Status'
|
||||
|
||||
/**
|
||||
* What Sonda has learned from your listening: the kinds of music and the artists you like. It is only
|
||||
* a hint, so while it loads or when it cannot be read it shows nothing, with no alarm.
|
||||
*/
|
||||
export default function TastePanel() {
|
||||
const { t } = useTranslation()
|
||||
const taste = useTaste()
|
||||
if (!taste.data) return null
|
||||
const { tags, artists } = taste.data
|
||||
|
||||
return (
|
||||
<Section title={t('discover.taste.title')}>
|
||||
{tags.length === 0 && artists.length === 0 ? (
|
||||
<EmptyMessage>{t('discover.taste.empty')}</EmptyMessage>
|
||||
) : (
|
||||
<div className="flex flex-col gap-3">
|
||||
{tags.length > 0 && (
|
||||
<ul aria-label={t('discover.taste.tags')} className="flex flex-wrap gap-2">
|
||||
{tags.map((tag) => (
|
||||
<li key={tag.tag} className="rounded-md bg-secondary px-3 py-1 text-sm font-semibold">
|
||||
{tag.tag}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
{artists.length > 0 && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('discover.taste.artists', { names: artists.map((a) => a.name).join(', ') })}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</Section>
|
||||
)
|
||||
}
|
||||
Loading…
Reference in a new issue