From 60349153c039836fe0e40155ebafd7380380ea3e Mon Sep 17 00:00:00 2001 From: tgiachi Date: Thu, 12 Nov 2026 14:09:24 +0100 Subject: [PATCH] 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. --- web/src/api/discover.test.tsx | 10 + web/src/api/discover.ts | 2 + web/src/components/ListeningSwitch.test.tsx | 4 +- web/src/i18n/locales/en.json | 22 ++ web/src/i18n/locales/it.json | 22 ++ web/src/pages/discover/SeedPicker.test.tsx | 81 +++++++ web/src/pages/discover/SeedPicker.tsx | 96 +++++++++ web/src/pages/discover/SuggestionCard.tsx | 4 +- .../pages/discover/SuggestionsTab.test.tsx | 198 ++++++++++++++++++ web/src/pages/discover/SuggestionsTab.tsx | 119 +++++++++++ web/src/pages/discover/TastePanel.test.tsx | 53 +++++ web/src/pages/discover/TastePanel.tsx | 40 ++++ 12 files changed, 647 insertions(+), 4 deletions(-) create mode 100644 web/src/pages/discover/SeedPicker.test.tsx create mode 100644 web/src/pages/discover/SeedPicker.tsx create mode 100644 web/src/pages/discover/SuggestionsTab.test.tsx create mode 100644 web/src/pages/discover/SuggestionsTab.tsx create mode 100644 web/src/pages/discover/TastePanel.test.tsx create mode 100644 web/src/pages/discover/TastePanel.tsx diff --git a/web/src/api/discover.test.tsx b/web/src/api/discover.test.tsx index 03409ed..eccfd0f 100644 --- a/web/src/api/discover.test.tsx +++ b/web/src/api/discover.test.tsx @@ -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 }) => {children} + 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')) }), diff --git a/web/src/api/discover.ts b/web/src/api/discover.ts index bf386b4..d72375f 100644 --- a/web/src/api/discover.ts +++ b/web/src/api/discover.ts @@ -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', { seed: seeds, in_library: inLibrary }, { signal }), }) } diff --git a/web/src/components/ListeningSwitch.test.tsx b/web/src/components/ListeningSwitch.test.tsx index 71edec9..0e8ec0b 100644 --- a/web/src/components/ListeningSwitch.test.tsx +++ b/web/src/components/ListeningSwitch.test.tsx @@ -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) diff --git a/web/src/i18n/locales/en.json b/web/src/i18n/locales/en.json index 1674534..b2b1e6b 100644 --- a/web/src/i18n/locales/en.json +++ b/web/src/i18n/locales/en.json @@ -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", diff --git a/web/src/i18n/locales/it.json b/web/src/i18n/locales/it.json index 9b31471..a6c2c8a 100644 --- a/web/src/i18n/locales/it.json +++ b/web/src/i18n/locales/it.json @@ -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", diff --git a/web/src/pages/discover/SeedPicker.test.tsx b/web/src/pages/discover/SeedPicker.test.tsx new file mode 100644 index 0000000..8f3c7f7 --- /dev/null +++ b/web/src/pages/discover/SeedPicker.test.tsx @@ -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(start) + return ( + 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( + + + , + ) +} + +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() +}) diff --git a/web/src/pages/discover/SeedPicker.tsx b/web/src/pages/discover/SeedPicker.tsx new file mode 100644 index 0000000..da7041b --- /dev/null +++ b/web/src/pages/discover/SeedPicker.tsx @@ -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 ( +
+ {seeds.length > 0 && ( +
    + {seeds.map((seed) => ( +
  • + {seed.name} + +
  • + ))} +
+ )} + + setText(e.target.value)} + /> + {full &&

{t('discover.seeds.max', { count: MAX_SEEDS })}

} + + {!full && q !== '' && found.isSuccess && offered.length === 0 && {t('empty.noMatch', { q })}} + {offered.length > 0 && ( +
    + {offered.map((artist) => ( +
  • + +
  • + ))} +
+ )} + + {seeds.length > 0 &&

{t('discover.seeds.privacy')}

} +
+ ) +} diff --git a/web/src/pages/discover/SuggestionCard.tsx b/web/src/pages/discover/SuggestionCard.tsx index 0e2b893..d8433aa 100644 --- a/web/src/pages/discover/SuggestionCard.tsx +++ b/web/src/pages/discover/SuggestionCard.tsx @@ -67,11 +67,11 @@ export default function SuggestionCard({ suggestion }: { suggestion: Suggestion - {failure && ( + {failure ? (

{t(errorMessageKey(failure instanceof ApiError ? failure.code : 'unknown'))}

- )} + ) : null} ) } diff --git a/web/src/pages/discover/SuggestionsTab.test.tsx b/web/src/pages/discover/SuggestionsTab.test.tsx new file mode 100644 index 0000000..4cd85fc --- /dev/null +++ b/web/src/pages/discover/SuggestionsTab.test.tsx @@ -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( + + + + + , + ) +} + +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() +}) diff --git a/web/src/pages/discover/SuggestionsTab.tsx b/web/src/pages/discover/SuggestionsTab.tsx new file mode 100644 index 0000000..f7e75a1 --- /dev/null +++ b/web/src/pages/discover/SuggestionsTab.tsx @@ -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 ( +
+

{t('discover.busy')}

+ +
+ ) +} + +export default function SuggestionsTab() { + const { t } = useTranslation() + const settings = useMySettings() + const [seeds, setSeeds] = useState([]) + 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 ( +
+ + + 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 && } + {(!ready && !settings.isPending) || refused ? ( +
+ {t('discover.invite')} + +
+ ) : null} + + {ready && !refused && ( +
+ + + {discover.isPending && ( +
+ +

{t('discover.waiting')}

+
+ )} + + {discover.isError && !refused && (busy ? ( + void discover.refetch()} + /> + ) : ( + void discover.refetch()} /> + ))} + + {data && ( + <> + {data.provider_status === 'disabled' && } + {data.provider_status === 'error' && {t('discover.partial')}} + {data.from_listening && seeds.length === 0 && data.seeds.length > 0 && ( +

+ {t('discover.fromListening', { names: data.seeds.map((s) => s.name).join(', ') })} +

+ )} + {data.items.length === 0 ? ( + {t('discover.none')} + ) : ( +
    + {data.items.map((item) => ( + + ))} +
+ )} + {data.attribution} + + )} +
+ )} +
+ ) +} diff --git a/web/src/pages/discover/TastePanel.test.tsx b/web/src/pages/discover/TastePanel.test.tsx new file mode 100644 index 0000000..002255e --- /dev/null +++ b/web/src/pages/discover/TastePanel.test.tsx @@ -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( + + + , + ) +} + +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() +}) diff --git a/web/src/pages/discover/TastePanel.tsx b/web/src/pages/discover/TastePanel.tsx new file mode 100644 index 0000000..4ced5f3 --- /dev/null +++ b/web/src/pages/discover/TastePanel.tsx @@ -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 ( +
+ {tags.length === 0 && artists.length === 0 ? ( + {t('discover.taste.empty')} + ) : ( +
+ {tags.length > 0 && ( +
    + {tags.map((tag) => ( +
  • + {tag.tag} +
  • + ))} +
+ )} + {artists.length > 0 && ( +

+ {t('discover.taste.artists', { names: artists.map((a) => a.name).join(', ') })} +

+ )} +
+ )} +
+ ) +}