From 54b19d6d4f61f703193183024ddb5bdc221d2dfb Mon Sep 17 00:00:00 2001 From: tgiachi Date: Thu, 12 Nov 2026 14:03:11 +0100 Subject: [PATCH 01/10] feat(web): lists in query values, request cancelling and Retry-After in the API client A list value is sent once per item (seed=1&seed=2). A signal can cancel a request and a cancelled call rejects with AbortError, not as a lost connection. ApiError keeps Retry-After in seconds. --- web/src/api/client.test.ts | 44 ++++++++++++++++++++++++++++++++++++++ web/src/api/client.ts | 36 ++++++++++++++++++++++++------- 2 files changed, 72 insertions(+), 8 deletions(-) diff --git a/web/src/api/client.test.ts b/web/src/api/client.test.ts index 12ef72d..fe4bb43 100644 --- a/web/src/api/client.test.ts +++ b/web/src/api/client.test.ts @@ -111,3 +111,47 @@ test('a network failure becomes an ApiError with the code network', async () => ) await expect(api.get('/artists')).rejects.toMatchObject({ status: 0, code: 'network' }) }) + +test('a list value is sent once for each item', async () => { + const { calls } = mockFetch({ 'GET /api/v1/discover': () => ({}) }) + await api.get('/discover', { seed: [3, 5], limit: 10 }) + expect(calls[0].url.searchParams.getAll('seed')).toEqual(['3', '5']) + expect(calls[0].url.searchParams.get('limit')).toBe('10') +}) + +test('a signal is given to the request', async () => { + const { calls } = mockFetch({ 'GET /api/v1/discover': () => ({}) }) + const controller = new AbortController() + await api.get('/discover', undefined, { signal: controller.signal }) + expect(calls[0].init.signal).toBe(controller.signal) +}) + +test('a cancelled request is not reported as a network failure', async () => { + vi.stubGlobal( + 'fetch', + vi.fn(async () => { + throw new DOMException('aborted', 'AbortError') + }), + ) + const failure = await api.get('/discover').catch((e: unknown) => e) + expect(failure).not.toBeInstanceOf(ApiError) + expect(failure).toMatchObject({ name: 'AbortError' }) +}) + +test('Retry-After on an error is kept in seconds', async () => { + mockFetch({ + 'GET /api/v1/discover': () => + new Response(JSON.stringify({ error: { code: 'discover_busy', message: 'busy' } }), { + status: 429, + headers: { 'Content-Type': 'application/json', 'Retry-After': '12' }, + }), + }) + const failure = await api.get('/discover').catch((e: unknown) => e) + expect(failure).toMatchObject({ status: 429, code: 'discover_busy', retryAfter: 12 }) +}) + +test('an error without Retry-After has none', async () => { + mockFetch({ 'GET /api/v1/artists': () => apiError(400, 'invalid_input') }) + const failure = (await api.get('/artists').catch((e: unknown) => e)) as ApiError + expect(failure.retryAfter).toBeUndefined() +}) diff --git a/web/src/api/client.ts b/web/src/api/client.ts index 6a33e67..426b2cf 100644 --- a/web/src/api/client.ts +++ b/web/src/api/client.ts @@ -2,12 +2,15 @@ export class ApiError extends Error { status: number code: string + /** Seconds to wait before asking again, when the server said so (`Retry-After`). */ + retryAfter?: number - constructor(status: number, code: string, message: string) { + constructor(status: number, code: string, message: string, retryAfter?: number) { super(message) this.name = 'ApiError' this.status = status this.code = code + this.retryAfter = retryAfter } } @@ -29,13 +32,17 @@ export function setAuthHooks(next: AuthHooks): void { hooks = next } -type Query = Record +type QueryValue = string | number | boolean | undefined +/** A list value is sent once for each item (`seed=1&seed=2`). */ +type Query = Record export interface CallOptions { /** Default true. Login, register, refresh and logout say false: they carry no token and never renew. */ auth?: boolean /** Lets the request finish after the page is closed (the browser allows it for small bodies). */ keepalive?: boolean + /** Cancels the request. A cancelled call rejects with the browser's `AbortError`, not an `ApiError`. */ + signal?: AbortSignal } const BASE = '/api/v1' @@ -43,7 +50,9 @@ const BASE = '/api/v1' function buildUrl(path: string, params?: Query): string { const query = new URLSearchParams() for (const [key, value] of Object.entries(params ?? {})) { - if (value !== undefined) query.set(key, String(value)) + for (const item of Array.isArray(value) ? value : [value]) { + if (item !== undefined) query.append(key, String(item)) + } } const text = query.toString() return `${BASE}${path}${text ? `?${text}` : ''}` @@ -52,18 +61,26 @@ function buildUrl(path: string, params?: Query): string { async function toApiError(res: Response): Promise { try { const body = (await res.json()) as { error?: { code?: string; message?: string } } - return new ApiError(res.status, body.error?.code ?? 'unknown', body.error?.message ?? res.statusText) + return new ApiError(res.status, body.error?.code ?? 'unknown', body.error?.message ?? res.statusText, retryAfter(res)) } catch { - return new ApiError(res.status, 'unknown', res.statusText) + return new ApiError(res.status, 'unknown', res.statusText, retryAfter(res)) } } +/** The `Retry-After` header in whole seconds, or nothing when it is absent or is a date. */ +function retryAfter(res: Response): number | undefined { + const text = res.headers.get('Retry-After') + if (text === null || !/^\d+$/.test(text.trim())) return undefined + return Number(text) +} + async function send( method: string, url: string, body: unknown, token: string | null, keepalive: boolean | undefined, + signal: AbortSignal | undefined, ): Promise { const headers: Record = { Accept: 'application/json' } if (body !== undefined) headers['Content-Type'] = 'application/json' @@ -74,8 +91,11 @@ async function send( headers, body: body === undefined ? undefined : JSON.stringify(body), keepalive: keepalive || undefined, + signal, }) - } catch { + } catch (e) { + // A cancelled request is the caller's own doing: say so as it is, not as a broken connection. + if (e instanceof DOMException && e.name === 'AbortError') throw e throw new ApiError(0, 'network', 'The server cannot be reached') } } @@ -83,11 +103,11 @@ async function send( async function request(method: string, path: string, params: Query | undefined, body: unknown, opts: CallOptions): Promise { const auth = opts.auth ?? true const url = buildUrl(path, params) - let res = await send(method, url, body, auth ? await hooks.getAccessToken() : null, opts.keepalive) + let res = await send(method, url, body, auth ? await hooks.getAccessToken() : null, opts.keepalive, opts.signal) if (res.status === 401 && auth) { const fresh = await hooks.refresh() - if (fresh) res = await send(method, url, body, fresh, opts.keepalive) + if (fresh) res = await send(method, url, body, fresh, opts.keepalive, opts.signal) if (res.status === 401) hooks.signOut() } From 63ed483936895df3e538324657972a400b508011 Mon Sep 17 00:00:00 2001 From: tgiachi Date: Thu, 12 Nov 2026 14:04:16 +0100 Subject: [PATCH 02/10] feat(web): data hooks for Discover, the wishlist, dismissed artists, taste and own settings Suggestions are kept five minutes and cancelled when nobody looks. Wishlist and dismiss change the suggestions at once and go back if the call fails. --- web/src/api/catalog.ts | 2 +- web/src/api/discover.test.tsx | 148 ++++++++++++++++++++++++++++++++++ web/src/api/discover.ts | 113 ++++++++++++++++++++++++++ 3 files changed, 262 insertions(+), 1 deletion(-) create mode 100644 web/src/api/discover.test.tsx create mode 100644 web/src/api/discover.ts diff --git a/web/src/api/catalog.ts b/web/src/api/catalog.ts index 5cfe6ec..719a579 100644 --- a/web/src/api/catalog.ts +++ b/web/src/api/catalog.ts @@ -25,7 +25,7 @@ export interface ListOptions { } /** A list the server pages by `limit` and `offset`, read one page after the other. */ -function usePagedList(path: string, params: Params, opts: ListOptions = {}) { +export function usePagedList(path: string, params: Params, opts: ListOptions = {}) { const pageSize = opts.pageSize ?? PAGE_SIZE return useInfiniteQuery({ queryKey: [path, params, pageSize], diff --git a/web/src/api/discover.test.tsx b/web/src/api/discover.test.tsx new file mode 100644 index 0000000..03409ed --- /dev/null +++ b/web/src/api/discover.test.tsx @@ -0,0 +1,148 @@ +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { act, renderHook, waitFor } from '@testing-library/react' +import type { ReactNode } from 'react' +import { expect, test } from 'vitest' +import { apiError, mockFetch } from '@/test/mockFetch' +import { useArtistMarks, useDiscover, useDismissed, useMySettings, useTaste, useUpdateSettings, useWishlist } from './discover' + +function setup() { + const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } }) + const wrapper = ({ children }: { children: ReactNode }) => {children} + return { client, wrapper } +} + +const suggestion = (id: number, wishlisted = false) => ({ + artist: { id, name: `Artist ${id}` }, + in_library: false, + wishlisted, + score: 0.5, + components: { a: 0.5, g: null, p: 0.5, d: 1 }, + because: [], +}) + +const discover = (items: object[]) => ({ provider_status: 'ok', attribution: 'x', from_listening: false, seeds: [], items }) + +const marked = (id: number) => ({ artist: { id, name: `Artist ${id}` }, in_library: false, marked_at: '2026-11-12T10:00:00Z' }) + +test('Discover sends each seed, and in_library only when it is set', async () => { + const { calls } = mockFetch({ 'GET /api/v1/discover': () => discover([]) }) + const { wrapper } = setup() + const { result } = renderHook(() => useDiscover({ seeds: [3, 5], inLibrary: false }), { wrapper }) + await waitFor(() => expect(result.current.isSuccess).toBe(true)) + expect(calls[0].url.searchParams.getAll('seed')).toEqual(['3', '5']) + expect(calls[0].url.searchParams.get('in_library')).toBe('false') + + const second = renderHook(() => useDiscover({ seeds: [] }), { wrapper }) + await waitFor(() => expect(second.result.current.isSuccess).toBe(true)) + expect(calls[1].url.searchParams.has('seed')).toBe(false) + expect(calls[1].url.searchParams.has('in_library')).toBe(false) +}) + +test('Discover asks for nothing while it is not enabled', async () => { + const { calls } = mockFetch({ 'GET /api/v1/discover': () => discover([]) }) + const { result } = renderHook(() => useDiscover({ seeds: [], enabled: false }), { wrapper: setup().wrapper }) + await new Promise((r) => setTimeout(r, 30)) + expect(calls).toHaveLength(0) + expect(result.current.fetchStatus).toBe('idle') +}) + +test('Discover gives the request a signal, so leaving the page can cancel it', async () => { + const { calls } = mockFetch({ 'GET /api/v1/discover': () => discover([]) }) + const { result } = renderHook(() => useDiscover({ seeds: [1] }), { wrapper: setup().wrapper }) + await waitFor(() => expect(result.current.isSuccess).toBe(true)) + expect(calls[0].init.signal).toBeInstanceOf(AbortSignal) +}) + +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')) }), + 'GET /api/v1/discover/dismissed': () => ({ items: [marked(2)], total: 1, limit: 50, offset: 0 }), + }) + const { wrapper } = setup() + const wish = renderHook(() => useWishlist(), { wrapper }) + const gone = renderHook(() => useDismissed(), { wrapper }) + await waitFor(() => expect(wish.result.current.data?.items).toHaveLength(1)) + await waitFor(() => expect(gone.result.current.data?.items[0].artist.id).toBe(2)) + expect(calls.map((c) => c.key).sort()).toEqual(['GET /api/v1/discover/dismissed', 'GET /api/v1/wishlist']) +}) + +test('taste is read from /me/taste', async () => { + mockFetch({ 'GET /api/v1/me/taste': () => ({ artists: [], tags: [{ tag: 'rock', weight: 1 }] }) }) + const { result } = renderHook(() => useTaste(), { wrapper: setup().wrapper }) + await waitFor(() => expect(result.current.data?.tags[0].tag).toBe('rock')) +}) + +test('a setting is changed with PATCH and the answer replaces what was cached', async () => { + const { calls } = mockFetch({ + 'GET /api/v1/me/settings': () => ({ discover_from_listening: false }), + 'PATCH /api/v1/me/settings': ({ init }) => ({ discover_from_listening: JSON.parse(String(init.body)).discover_from_listening }), + }) + const { wrapper } = setup() + const { result } = renderHook(() => ({ settings: useMySettings(), update: useUpdateSettings() }), { wrapper }) + await waitFor(() => expect(result.current.settings.data?.discover_from_listening).toBe(false)) + await act(() => result.current.update.mutateAsync({ discover_from_listening: true })) + await waitFor(() => expect(result.current.settings.data?.discover_from_listening).toBe(true)) + expect(JSON.parse(String(calls.find((c) => c.key === 'PATCH /api/v1/me/settings')?.init.body))).toEqual({ discover_from_listening: true }) +}) + +test('adding to the wishlist marks the suggestion at once and refreshes the lists', async () => { + const { calls } = mockFetch({ + 'PUT /api/v1/wishlist/7': () => new Response(null, { status: 204 }), + }) + const { client, wrapper } = setup() + const key = ['discover', { seeds: [1], inLibrary: undefined }] + client.setQueryData(key, discover([suggestion(7), suggestion(8)])) + client.setQueryData(['/wishlist', {}, 50], { pages: [], pageParams: [] }) + const { result } = renderHook(() => useArtistMarks(), { wrapper }) + await act(() => result.current.addToWishlist.mutateAsync(7)) + const items = (client.getQueryData(key) as ReturnType).items as ReturnType[] + expect(items.map((i) => i.wishlisted)).toEqual([true, false]) + expect(calls.map((c) => c.key)).toContain('PUT /api/v1/wishlist/7') + expect(client.getQueryState(['/wishlist', {}, 50])?.isInvalidated).toBe(true) +}) + +test('a failed wishlist call puts the suggestion back as it was', async () => { + mockFetch({ 'PUT /api/v1/wishlist/7': () => apiError(404, 'artist_not_found') }) + const { client, wrapper } = setup() + const key = ['discover', { seeds: [1], inLibrary: undefined }] + client.setQueryData(key, discover([suggestion(7)])) + const { result } = renderHook(() => useArtistMarks(), { wrapper }) + await act(() => result.current.addToWishlist.mutateAsync(7).catch(() => undefined)) + const items = (client.getQueryData(key) as ReturnType).items as ReturnType[] + expect(items[0].wishlisted).toBe(false) +}) + +test('removing from the wishlist unmarks the suggestion', async () => { + mockFetch({ 'DELETE /api/v1/wishlist/7': () => new Response(null, { status: 204 }) }) + const { client, wrapper } = setup() + const key = ['discover', { seeds: [1], inLibrary: undefined }] + client.setQueryData(key, discover([suggestion(7, true)])) + const { result } = renderHook(() => useArtistMarks(), { wrapper }) + await act(() => result.current.removeFromWishlist.mutateAsync(7)) + const items = (client.getQueryData(key) as ReturnType).items as ReturnType[] + expect(items[0].wishlisted).toBe(false) +}) + +test('dismissing takes the suggestion out of the list, and a failure brings it back', async () => { + mockFetch({ + 'POST /api/v1/discover/7/dismiss': () => new Response(null, { status: 204 }), + 'POST /api/v1/discover/8/dismiss': () => apiError(404, 'artist_not_found'), + }) + const { client, wrapper } = setup() + const key = ['discover', { seeds: [1], inLibrary: undefined }] + client.setQueryData(key, discover([suggestion(7), suggestion(8)])) + const { result } = renderHook(() => useArtistMarks(), { wrapper }) + await act(() => result.current.dismiss.mutateAsync(7)) + const ids = () => ((client.getQueryData(key) as ReturnType).items as ReturnType[]).map((i) => i.artist.id) + expect(ids()).toEqual([8]) + await act(() => result.current.dismiss.mutateAsync(8).catch(() => undefined)) + expect(ids()).toEqual([8]) +}) + +test('being interested again lifts the dismissal', async () => { + const { calls } = mockFetch({ 'DELETE /api/v1/discover/7/dismiss': () => new Response(null, { status: 204 }) }) + const { wrapper } = setup() + const { result } = renderHook(() => useArtistMarks(), { wrapper }) + await act(() => result.current.undismiss.mutateAsync(7)) + expect(calls.map((c) => c.key)).toEqual(['DELETE /api/v1/discover/7/dismiss']) +}) diff --git a/web/src/api/discover.ts b/web/src/api/discover.ts new file mode 100644 index 0000000..bf386b4 --- /dev/null +++ b/web/src/api/discover.ts @@ -0,0 +1,113 @@ +import { useMutation, useQuery, useQueryClient, type QueryClient } from '@tanstack/react-query' +import { api } from './client' +import { usePagedList, type ListOptions } from './catalog' +import type { components } from './schema' + +export type Discover = components['schemas']['Discover'] +export type Suggestion = components['schemas']['Suggestion'] +export type MarkedArtist = components['schemas']['MarkedArtist'] +export type Taste = components['schemas']['Taste'] +export type UserSettings = components['schemas']['UserSettings'] +type UpdateUserSettings = components['schemas']['UpdateUserSettings'] + +const DISCOVER = 'discover' + +export interface DiscoverOptions { + /** The artists to start from (up to 5). With none, the server uses your listening if you allowed that. */ + seeds: number[] + /** `false` keeps only artists you do not have. Absent keeps both. */ + inLibrary?: boolean + /** False keeps the call from being made yet (default true). */ + enabled?: boolean +} + +/** + * Suggestions. The call is heavy for the server (it may ask Last.fm for several seconds), so it is kept for + * five minutes, never repeated when the window gets focus, and cancelled when nobody is looking any more. + */ +export function useDiscover({ seeds, inLibrary, enabled = true }: DiscoverOptions) { + return useQuery({ + queryKey: [DISCOVER, { seeds, inLibrary }], + enabled, + staleTime: 5 * 60_000, + refetchOnWindowFocus: false, + queryFn: ({ signal }) => api.get('/discover', { seed: seeds, in_library: inLibrary }, { signal }), + }) +} + +export function useWishlist(opts: ListOptions = {}) { + return usePagedList('/wishlist', {}, opts) +} + +export function useDismissed(opts: ListOptions = {}) { + return usePagedList('/discover/dismissed', {}, opts) +} + +export function useTaste() { + return useQuery({ queryKey: ['me', 'taste'], queryFn: () => api.get('/me/taste', { limit: 10 }) }) +} + +const SETTINGS_KEY = ['me', 'settings'] + +export function useMySettings() { + return useQuery({ queryKey: SETTINGS_KEY, queryFn: () => api.get('/me/settings') }) +} + +export function useUpdateSettings() { + const client = useQueryClient() + return useMutation({ + mutationFn: (body: UpdateUserSettings) => api.patch('/me/settings', body), + onSuccess: (settings) => client.setQueryData(SETTINGS_KEY, settings), + }) +} + +type Snapshot = [readonly unknown[], Discover | undefined][] + +/** Changes the suggestions held in the cache, and gives back what to put there if the call fails. */ +function patchSuggestions(client: QueryClient, change: (items: Suggestion[]) => Suggestion[]): Snapshot { + const before = client.getQueriesData({ queryKey: [DISCOVER] }) + client.setQueriesData({ queryKey: [DISCOVER] }, (old) => (old ? { ...old, items: change(old.items) } : old)) + return before +} + +function refreshLists(client: QueryClient) { + return Promise.all([ + client.invalidateQueries({ queryKey: ['/wishlist'] }), + client.invalidateQueries({ queryKey: ['/discover/dismissed'] }), + ]) +} + +/** + * The four things you can say about an artist. The suggestions change at once, as if the call had worked, + * and go back as they were if it fails. The wishlist and the dismissed list are read again afterwards, since + * an artist is on the wishlist or dismissed, never both. + */ +export function useArtistMarks() { + const client = useQueryClient() + + function mark(call: (id: number) => Promise, change: (id: number) => (items: Suggestion[]) => Suggestion[]) { + return { + mutationFn: call, + onMutate: (id: number) => ({ before: patchSuggestions(client, change(id)) }), + onError: (_e: unknown, _id: number, context?: { before: Snapshot }) => { + for (const [key, data] of context?.before ?? []) client.setQueryData(key, data) + }, + onSettled: () => refreshLists(client), + } + } + + const setWishlisted = (id: number, wishlisted: boolean) => (items: Suggestion[]) => + items.map((s) => (s.artist.id === id ? { ...s, wishlisted } : s)) + + return { + addToWishlist: useMutation(mark((id) => api.put(`/wishlist/${id}`), (id) => setWishlisted(id, true))), + removeFromWishlist: useMutation(mark((id) => api.del(`/wishlist/${id}`), (id) => setWishlisted(id, false))), + dismiss: useMutation( + mark( + (id) => api.post(`/discover/${id}/dismiss`), + (id) => (items) => items.filter((s) => s.artist.id !== id), + ), + ), + undismiss: useMutation(mark((id) => api.del(`/discover/${id}/dismiss`), () => (items) => items)), + } +} From 3cd0ef7150cccdb81a5624cded88883b120e546e Mon Sep 17 00:00:00 2001 From: tgiachi Date: Thu, 12 Nov 2026 14:05:49 +0100 Subject: [PATCH 03/10] feat(web): a switch in Settings for starting Discover from your listening Turning it on shows a dialog that says the names of the most played artists go to Last.fm. Turning it off asks nothing, and a failed change leaves the switch as it was. --- web/src/components/ListeningSwitch.test.tsx | 80 +++++++++++++++++++++ web/src/components/ListeningSwitch.tsx | 76 ++++++++++++++++++++ web/src/i18n/locales/en.json | 11 +++ web/src/i18n/locales/it.json | 11 +++ web/src/pages/SettingsPage.test.tsx | 22 ++++-- web/src/pages/SettingsPage.tsx | 5 ++ 6 files changed, 200 insertions(+), 5 deletions(-) create mode 100644 web/src/components/ListeningSwitch.test.tsx create mode 100644 web/src/components/ListeningSwitch.tsx diff --git a/web/src/components/ListeningSwitch.test.tsx b/web/src/components/ListeningSwitch.test.tsx new file mode 100644 index 0000000..71edec9 --- /dev/null +++ b/web/src/components/ListeningSwitch.test.tsx @@ -0,0 +1,80 @@ +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +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 ListeningSwitch from './ListeningSwitch' + +beforeEach(async () => { + vi.spyOn(navigator, 'language', 'get').mockReturnValue('en-US') + await initI18n() +}) + +function setup(initial: boolean, over: MockRoutes = {}) { + let on = initial + const mocked = mockFetch({ + 'GET /api/v1/me/settings': () => ({ discover_from_listening: on }), + 'PATCH /api/v1/me/settings': ({ init }) => { + on = JSON.parse(String(init.body)).discover_from_listening + return { discover_from_listening: on } + }, + ...over, + }) + const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } }) + render( + + + , + ) + return mocked +} + +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') + +test('it says what turning it on sends, before anything is asked', async () => { + setup(false) + expect(await toggle()).toHaveAttribute('aria-checked', 'false') + expect(screen.getByText(/names of the artists you play most go to Last\.fm/i)).toBeInTheDocument() +}) + +test('turning it on asks first and sends nothing until the answer is yes', async () => { + const { calls } = setup(false) + await userEvent.click(await toggle()) + const dialog = await screen.findByRole('dialog') + expect(dialog).toHaveTextContent(/Last\.fm/) + expect(patches(calls)).toHaveLength(0) + + await userEvent.click(screen.getByRole('button', { name: 'Turn on' })) + await waitFor(() => expect(screen.getByRole('switch')).toHaveAttribute('aria-checked', 'true')) + expect(patches(calls)).toHaveLength(1) + expect(JSON.parse(String(patches(calls)[0].init.body))).toEqual({ discover_from_listening: true }) +}) + +test('cancelling leaves it off and sends nothing', async () => { + const { calls } = setup(false) + await userEvent.click(await toggle()) + await userEvent.click(await screen.findByRole('button', { name: 'Cancel' })) + await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument()) + expect(screen.getByRole('switch')).toHaveAttribute('aria-checked', 'false') + expect(patches(calls)).toHaveLength(0) +}) + +test('turning it off needs no question', async () => { + const { calls } = setup(true) + const sw = await toggle() + await waitFor(() => expect(sw).toHaveAttribute('aria-checked', 'true')) + await userEvent.click(sw) + await waitFor(() => expect(screen.getByRole('switch')).toHaveAttribute('aria-checked', 'false')) + expect(screen.queryByRole('dialog')).not.toBeInTheDocument() + expect(JSON.parse(String(patches(calls)[0].init.body))).toEqual({ discover_from_listening: false }) +}) + +test('a failure is shown and the switch stays as it was', async () => { + setup(false, { 'PATCH /api/v1/me/settings': () => apiError(500, 'internal') }) + await userEvent.click(await toggle()) + await userEvent.click(await screen.findByRole('button', { name: 'Turn on' })) + expect(await screen.findByRole('alert')).toBeInTheDocument() + expect(screen.getByRole('switch')).toHaveAttribute('aria-checked', 'false') +}) diff --git a/web/src/components/ListeningSwitch.tsx b/web/src/components/ListeningSwitch.tsx new file mode 100644 index 0000000..6b37dc4 --- /dev/null +++ b/web/src/components/ListeningSwitch.tsx @@ -0,0 +1,76 @@ +import { useState } from 'react' +import { useTranslation } from 'react-i18next' +import { ApiError } from '@/api/client' +import { useMySettings, useUpdateSettings } from '@/api/discover' +import { Button } from '@/components/ui/button' +import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog' +import { errorMessageKey } from '@/i18n' +import { cn } from '@/lib/utils' + +/** + * Whether Discover may start from the artists you play most. Turning it on sends their names to Last.fm + * (when an admin turned Last.fm on), so it asks first and says so; turning it off asks nothing. + */ +export default function ListeningSwitch() { + const { t } = useTranslation() + const settings = useMySettings() + const update = useUpdateSettings() + const [asking, setAsking] = useState(false) + const on = settings.data?.discover_from_listening === true + + function change(value: boolean) { + setAsking(false) + update.mutate({ discover_from_listening: value }) + } + + return ( +
+
+ + + {t('discover.listening.label')} + +
+

{t('discover.listening.help')}

+ {update.isError && ( +

+ {t(errorMessageKey(update.error instanceof ApiError ? update.error.code : 'unknown'))} +

+ )} + + + + + {t('discover.listening.confirmTitle')} + {t('discover.listening.confirmBody')} + + + + + + + +
+ ) +} diff --git a/web/src/i18n/locales/en.json b/web/src/i18n/locales/en.json index 300707c..a57db21 100644 --- a/web/src/i18n/locales/en.json +++ b/web/src/i18n/locales/en.json @@ -58,6 +58,17 @@ "currentPasswordWrong": "The current password is wrong.", "changePassword": "Change password" }, + "discover": { + "title": "Discover", + "listening": { + "label": "Start Discover from my listening", + "help": "When this is on, the names of the artists you play most go to Last.fm, if an admin turned Last.fm on, to find similar artists. When it is off, Discover starts only from artists you pick.", + "confirmTitle": "Send your top artists to Last.fm?", + "confirmBody": "Discover will send the names of the artists you play most to Last.fm, if an admin turned Last.fm on, and ask for similar artists. Nothing else about you is sent. You can turn this off at any time.", + "turnOn": "Turn on", + "cancel": "Cancel" + } + }, "home": { "greeting_morning": "Good morning", "greeting_afternoon": "Good afternoon", diff --git a/web/src/i18n/locales/it.json b/web/src/i18n/locales/it.json index 86c7c62..27281ef 100644 --- a/web/src/i18n/locales/it.json +++ b/web/src/i18n/locales/it.json @@ -58,6 +58,17 @@ "currentPasswordWrong": "La password attuale è sbagliata.", "changePassword": "Cambia password" }, + "discover": { + "title": "Discover", + "listening": { + "label": "Avvia Discover dai miei ascolti", + "help": "Se è acceso, i nomi degli artisti che ascolti di più vanno a Last.fm, se un admin l'ha acceso, per trovare artisti simili. Se è spento, Discover parte solo dagli artisti che scegli tu.", + "confirmTitle": "Mandare i tuoi artisti preferiti a Last.fm?", + "confirmBody": "Discover manderà a Last.fm i nomi degli artisti che ascolti di più, se un admin ha acceso Last.fm, e chiederà artisti simili. Non viene mandato nient'altro su di te. Puoi spegnerlo quando vuoi.", + "turnOn": "Accendi", + "cancel": "Annulla" + } + }, "home": { "greeting_morning": "Buongiorno", "greeting_afternoon": "Buon pomeriggio", diff --git a/web/src/pages/SettingsPage.test.tsx b/web/src/pages/SettingsPage.test.tsx index db500ab..75018db 100644 --- a/web/src/pages/SettingsPage.test.tsx +++ b/web/src/pages/SettingsPage.test.tsx @@ -1,3 +1,4 @@ +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import { render, screen } from '@testing-library/react' import userEvent from '@testing-library/user-event' import { MemoryRouter } from 'react-router-dom' @@ -12,14 +13,18 @@ import SettingsPage from './SettingsPage' const noContent = () => new Response(null, { status: 204 }) function renderSettings() { + const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } }) return render( - - - , + + + + + , ) } beforeEach(async () => { + mockFetch({ 'GET /api/v1/me/settings': () => ({ discover_from_listening: false }) }) vi.spyOn(navigator, 'language', 'get').mockReturnValue('en-US') await initI18n() initTheme() @@ -93,12 +98,19 @@ test('choosing Italian changes the words on the page', async () => { expect(localStorage.getItem('sonda.lang')).toBe('it') }) +test('Discover has its own group with the switch for using your listening, off until you turn it on', async () => { + renderSettings() + expect(screen.getByRole('region', { name: 'Discover' })).toBeInTheDocument() + const sw = await screen.findByRole('switch', { name: 'Start Discover from my listening' }) + expect(sw).toHaveAttribute('aria-checked', 'false') +}) + test('a new password of seven characters is refused here, with no request', async () => { const { calls } = mockFetch({}) renderSettings() await changePassword('old-password', '1234567') expect(await screen.findByRole('alert')).toHaveTextContent('The new password needs 8 to 256 characters.') - expect(calls).toHaveLength(0) + expect(calls.filter((c) => c.url.pathname === '/api/v1/auth/password')).toHaveLength(0) }) test('a new password longer than 256 bytes is refused here, with no request', async () => { @@ -109,7 +121,7 @@ test('a new password longer than 256 bytes is refused here, with no request', as await userEvent.paste('x'.repeat(257)) await userEvent.click(screen.getByRole('button', { name: 'Change password' })) expect(await screen.findByRole('alert')).toHaveTextContent('8 to 256') - expect(calls).toHaveLength(0) + expect(calls.filter((c) => c.url.pathname === '/api/v1/auth/password')).toHaveLength(0) }) test('a changed password signs this session out, because the server ends every session', async () => { diff --git a/web/src/pages/SettingsPage.tsx b/web/src/pages/SettingsPage.tsx index 00f355e..1b670b3 100644 --- a/web/src/pages/SettingsPage.tsx +++ b/web/src/pages/SettingsPage.tsx @@ -3,6 +3,7 @@ import { useTranslation } from 'react-i18next' import { api, ApiError } from '@/api/client' import { logout, useSession } from '@/auth/session' import ChoiceGroup from '@/components/ChoiceGroup' +import ListeningSwitch from '@/components/ListeningSwitch' import Section from '@/components/Section' import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' @@ -136,6 +137,10 @@ export default function SettingsPage() { /> +
+ +
+
From 71b0b39a0772dd23de141e35a46e782f22eb925d Mon Sep 17 00:00:00 2001 From: tgiachi Date: Thu, 12 Nov 2026 14:06:49 +0100 Subject: [PATCH 04/10] feat(web): a card for a Discover suggestion with its score explained Shows the score in percent, the seeds it comes from, a part-by-part explanation (a missing genre is not a zero), and the wishlist and not-interested actions. --- web/src/i18n/locales/en.json | 14 +++ web/src/i18n/locales/it.json | 14 +++ .../pages/discover/SuggestionCard.test.tsx | 110 ++++++++++++++++++ web/src/pages/discover/SuggestionCard.tsx | 77 ++++++++++++ 4 files changed, 215 insertions(+) create mode 100644 web/src/pages/discover/SuggestionCard.test.tsx create mode 100644 web/src/pages/discover/SuggestionCard.tsx diff --git a/web/src/i18n/locales/en.json b/web/src/i18n/locales/en.json index a57db21..1674534 100644 --- a/web/src/i18n/locales/en.json +++ b/web/src/i18n/locales/en.json @@ -60,6 +60,20 @@ }, "discover": { "title": "Discover", + "score": "{{percent}}% match", + "because": "Because of {{names}}", + "inLibrary": "In your library", + "why": "Why this?", + "wishlist": "Wishlist", + "notInterested": "Not interested", + "parts": { + "label": "How the score is made", + "a": "Similar to your starting artists", + "g": "Genres close to your taste", + "p": "What you play", + "d": "Not played yet", + "noGenre": "No genre data" + }, "listening": { "label": "Start Discover from my listening", "help": "When this is on, the names of the artists you play most go to Last.fm, if an admin turned Last.fm on, to find similar artists. When it is off, Discover starts only from artists you pick.", diff --git a/web/src/i18n/locales/it.json b/web/src/i18n/locales/it.json index 27281ef..9b31471 100644 --- a/web/src/i18n/locales/it.json +++ b/web/src/i18n/locales/it.json @@ -60,6 +60,20 @@ }, "discover": { "title": "Discover", + "score": "{{percent}}% di affinità", + "because": "Per via di {{names}}", + "inLibrary": "Nella tua libreria", + "why": "Perché questo?", + "wishlist": "Wishlist", + "notInterested": "Non mi interessa", + "parts": { + "label": "Come si calcola il punteggio", + "a": "Simile agli artisti di partenza", + "g": "Generi vicini ai tuoi gusti", + "p": "Quello che ascolti", + "d": "Non ancora ascoltato", + "noGenre": "Nessun dato sui generi" + }, "listening": { "label": "Avvia Discover dai miei ascolti", "help": "Se è acceso, i nomi degli artisti che ascolti di più vanno a Last.fm, se un admin l'ha acceso, per trovare artisti simili. Se è spento, Discover parte solo dagli artisti che scegli tu.", diff --git a/web/src/pages/discover/SuggestionCard.test.tsx b/web/src/pages/discover/SuggestionCard.test.tsx new file mode 100644 index 0000000..314d8b2 --- /dev/null +++ b/web/src/pages/discover/SuggestionCard.test.tsx @@ -0,0 +1,110 @@ +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { render, screen, 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 type { Suggestion } from '@/api/discover' +import { sessionStore } from '@/auth/session' +import { initI18n } from '@/i18n' +import { apiError, mockFetch } from '@/test/mockFetch' +import SuggestionCard from './SuggestionCard' + +const none = () => new Response(null, { status: 204 }) + +function make(over: Partial = {}): Suggestion { + return { + artist: { id: 7, name: 'Portishead' }, + in_library: false, + wishlisted: false, + score: 0.824, + components: { a: 0.6, g: 0.45, p: 0.5, d: 1 }, + because: [ + { artist: { id: 1, name: 'Björk' }, match: 0.9 }, + { artist: { id: 2, name: 'Massive Attack' }, match: 0.7 }, + ], + ...over, + } +} + +function renderCard(suggestion: Suggestion) { + const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { 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 names the artist with a link, the score in percent, and what it comes from', () => { + renderCard(make()) + expect(screen.getByRole('link', { name: 'Portishead' })).toHaveAttribute('href', '/artists/7') + expect(screen.getByText('82% match')).toBeInTheDocument() + expect(screen.getByText('Because of Björk, Massive Attack')).toBeInTheDocument() +}) + +test('an artist with no reason to give says nothing about one', () => { + renderCard(make({ because: [] })) + expect(screen.queryByText(/Because of/)).not.toBeInTheDocument() +}) + +test('an artist you already have says so', () => { + renderCard(make({ in_library: true })) + expect(screen.getByText('In your library')).toBeInTheDocument() +}) + +test('the score can be explained part by part, and a missing genre is not a zero', async () => { + renderCard(make({ components: { a: 0.6, g: null, p: 0.5, d: 1 } })) + await userEvent.click(screen.getByText('Why this?')) + const parts = screen.getByRole('list', { name: 'How the score is made' }) + expect(within(parts).getByText('Similar to your starting artists').closest('li')).toHaveTextContent('60%') + expect(within(parts).getByText('Genres close to your taste').closest('li')).toHaveTextContent('No genre data') + expect(within(parts).getByText('Genres close to your taste').closest('li')).not.toHaveTextContent('0%') + expect(within(parts).getByText('What you play').closest('li')).toHaveTextContent('50%') + expect(within(parts).getByText('Not played yet').closest('li')).toHaveTextContent('100%') +}) + +test('a known genre part is shown in percent', async () => { + renderCard(make()) + await userEvent.click(screen.getByText('Why this?')) + expect(screen.getByText('Genres close to your taste').closest('li')).toHaveTextContent('45%') +}) + +test('adding to the wishlist puts the artist there', async () => { + const { calls } = mockFetch({ 'PUT /api/v1/wishlist/7': none }) + renderCard(make()) + const button = screen.getByRole('button', { name: 'Wishlist' }) + expect(button).toHaveAttribute('aria-pressed', 'false') + await userEvent.click(button) + expect(calls.map((c) => c.key)).toContain('PUT /api/v1/wishlist/7') +}) + +test('a wishlisted artist is shown as pressed, and a click takes it off', async () => { + const { calls } = mockFetch({ 'DELETE /api/v1/wishlist/7': none }) + renderCard(make({ wishlisted: true })) + const button = screen.getByRole('button', { name: 'Wishlist' }) + expect(button).toHaveAttribute('aria-pressed', 'true') + await userEvent.click(button) + expect(calls.map((c) => c.key)).toContain('DELETE /api/v1/wishlist/7') +}) + +test('"Not interested" dismisses the artist', async () => { + const { calls } = mockFetch({ 'POST /api/v1/discover/7/dismiss': none }) + renderCard(make()) + await userEvent.click(screen.getByRole('button', { name: 'Not interested' })) + expect(calls.map((c) => c.key)).toContain('POST /api/v1/discover/7/dismiss') +}) + +test('an action that fails says so in words', async () => { + mockFetch({ 'PUT /api/v1/wishlist/7': () => apiError(404, 'artist_not_found') }) + renderCard(make()) + await userEvent.click(screen.getByRole('button', { name: 'Wishlist' })) + expect(await screen.findByRole('alert')).toBeInTheDocument() +}) diff --git a/web/src/pages/discover/SuggestionCard.tsx b/web/src/pages/discover/SuggestionCard.tsx new file mode 100644 index 0000000..0e2b893 --- /dev/null +++ b/web/src/pages/discover/SuggestionCard.tsx @@ -0,0 +1,77 @@ +import { useTranslation } from 'react-i18next' +import { Link } from 'react-router-dom' +import { ApiError } from '@/api/client' +import { useArtistMarks, type Suggestion } from '@/api/discover' +import ArtistPhoto from '@/components/ArtistPhoto' +import { Button } from '@/components/ui/button' +import { errorMessageKey } from '@/i18n' + +const percent = (value: number) => `${Math.round(value * 100)}%` + +/** One part of the score, in words, with its share. A part that could not be worked out says so, not "0%". */ +function Part({ label, value, missing }: { label: string; value: number | null; missing: string }) { + return ( +
  • + {label} + {value === null ? missing : percent(value)} +
  • + ) +} + +/** An artist Discover suggests, with how sure it is and why, and what you can do about it. */ +export default function SuggestionCard({ suggestion }: { suggestion: Suggestion }) { + const { t } = useTranslation() + const marks = useArtistMarks() + const { artist, components: parts } = suggestion + const failure = marks.addToWishlist.error ?? marks.removeFromWishlist.error ?? marks.dismiss.error + + return ( +
  • +
    + +
    + + {artist.name} + +
    + {t('discover.score', { percent: Math.round(suggestion.score * 100) })} + {suggestion.in_library && {t('discover.inLibrary')}} +
    + {suggestion.because.length > 0 && ( +

    + {t('discover.because', { names: suggestion.because.map((b) => b.artist.name).join(', ') })} +

    + )} +
    +
    + + +
    +
    + +
    + {t('discover.why')} +
      + + + + +
    +
    + + {failure && ( +

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

    + )} +
  • + ) +} From 60349153c039836fe0e40155ebafd7380380ea3e Mon Sep 17 00:00:00 2001 From: tgiachi Date: Thu, 12 Nov 2026 14:09:24 +0100 Subject: [PATCH 05/10] 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(', ') })} +

    + )} +
    + )} +
    + ) +} From 6d03b1b6619e24e75d04e4168372cdd57364cfd0 Mon Sep 17 00:00:00 2001 From: tgiachi Date: Thu, 12 Nov 2026 14:10:07 +0100 Subject: [PATCH 06/10] feat(web): the wishlist and the not-interested lists Paged rows with remove, not interested and interested again. An artist links to its page only when it is in the library, since one kept alive only by a mark answers 404. The wishlist can hide the artists you already have. --- web/src/i18n/locales/en.json | 7 ++ web/src/i18n/locales/it.json | 7 ++ web/src/pages/discover/MarkedList.test.tsx | 126 +++++++++++++++++++++ web/src/pages/discover/MarkedList.tsx | 81 +++++++++++++ 4 files changed, 221 insertions(+) create mode 100644 web/src/pages/discover/MarkedList.test.tsx create mode 100644 web/src/pages/discover/MarkedList.tsx diff --git a/web/src/i18n/locales/en.json b/web/src/i18n/locales/en.json index b2b1e6b..7a884b2 100644 --- a/web/src/i18n/locales/en.json +++ b/web/src/i18n/locales/en.json @@ -74,6 +74,13 @@ "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", + "marked": { + "hideOwned": "Hide the ones I already have", + "remove": "Remove", + "interestedAgain": "Interested again", + "emptyWishlist": "Nothing on your wishlist yet. Add artists from the suggestions.", + "emptyDismissed": "You have not dismissed any artist." + }, "seeds": { "label": "Find an artist to start from", "list": "Starting artists", diff --git a/web/src/i18n/locales/it.json b/web/src/i18n/locales/it.json index a6c2c8a..890e280 100644 --- a/web/src/i18n/locales/it.json +++ b/web/src/i18n/locales/it.json @@ -74,6 +74,13 @@ "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", + "marked": { + "hideOwned": "Nascondi quelli che ho già", + "remove": "Togli", + "interestedAgain": "Mi interessa di nuovo", + "emptyWishlist": "Ancora niente nella wishlist. Aggiungi artisti dai suggerimenti.", + "emptyDismissed": "Non hai scartato nessun artista." + }, "seeds": { "label": "Cerca un artista da cui partire", "list": "Artisti di partenza", diff --git a/web/src/pages/discover/MarkedList.test.tsx b/web/src/pages/discover/MarkedList.test.tsx new file mode 100644 index 0000000..9aac4e2 --- /dev/null +++ b/web/src/pages/discover/MarkedList.test.tsx @@ -0,0 +1,126 @@ +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 } from '@/test/mockFetch' +import MarkedList from './MarkedList' + +const none = () => new Response(null, { status: 204 }) + +const marked = (id: number, name: string, in_library = false) => ({ + artist: { id, name }, + in_library, + marked_at: '2026-11-12T10:00:00Z', +}) + +const page = (items: object[], total = items.length, offset = 0) => ({ items, total, limit: 50, offset }) + +function renderList(kind: 'wishlist' | 'dismissed') { + const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } }) + return render( + + + + + , + ) +} + +function wishlist(over: MockRoutes = {}): MockRoutes { + return { 'GET /api/v1/wishlist': () => page([marked(1, 'Portishead'), marked(2, 'Björk', true)]), ...over } +} + +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('an artist you have links to its page, one you only wish for is just a name', async () => { + mockFetch(wishlist()) + renderList('wishlist') + expect(await screen.findByRole('link', { name: 'Björk' })).toHaveAttribute('href', '/artists/2') + expect(screen.getByText('Portishead')).toBeInTheDocument() + expect(screen.queryByRole('link', { name: 'Portishead' })).not.toBeInTheDocument() + expect(screen.getByText('In your library')).toBeInTheDocument() +}) + +test('"Hide the ones I already have" leaves only the wishes', async () => { + mockFetch(wishlist()) + renderList('wishlist') + await screen.findByText('Portishead') + await userEvent.click(screen.getByRole('checkbox', { name: 'Hide the ones I already have' })) + expect(screen.queryByText('Björk')).not.toBeInTheDocument() + expect(screen.getByText('Portishead')).toBeInTheDocument() +}) + +test('removing a wish asks the server and the artist is gone when the list is read again', async () => { + let items = [marked(1, 'Portishead'), marked(2, 'Björk', true)] + const { calls } = mockFetch({ + 'GET /api/v1/wishlist': () => page(items), + 'DELETE /api/v1/wishlist/1': () => { + items = items.filter((m) => m.artist.id !== 1) + return none() + }, + }) + renderList('wishlist') + const row = (await screen.findByText('Portishead')).closest('li') as HTMLElement + await userEvent.click(within(row).getByRole('button', { name: 'Remove' })) + await waitFor(() => expect(screen.queryByText('Portishead')).not.toBeInTheDocument()) + expect(calls.map((c) => c.key)).toContain('DELETE /api/v1/wishlist/1') +}) + +test('"Not interested" on a wish dismisses the artist', async () => { + const { calls } = mockFetch(wishlist({ 'POST /api/v1/discover/1/dismiss': none })) + renderList('wishlist') + const row = (await screen.findByText('Portishead')).closest('li') as HTMLElement + await userEvent.click(within(row).getByRole('button', { name: 'Not interested' })) + expect(calls.map((c) => c.key)).toContain('POST /api/v1/discover/1/dismiss') +}) + +test('an empty wishlist says how to fill it', async () => { + mockFetch({ 'GET /api/v1/wishlist': () => page([]) }) + renderList('wishlist') + expect(await screen.findByText('Nothing on your wishlist yet. Add artists from the suggestions.')).toBeInTheDocument() +}) + +test('the dismissed artists can be wanted again', async () => { + const { calls } = mockFetch({ + 'GET /api/v1/discover/dismissed': () => page([marked(5, 'Oasis')]), + 'DELETE /api/v1/discover/5/dismiss': none, + }) + renderList('dismissed') + const row = (await screen.findByText('Oasis')).closest('li') as HTMLElement + await userEvent.click(within(row).getByRole('button', { name: 'Interested again' })) + expect(calls.map((c) => c.key)).toContain('DELETE /api/v1/discover/5/dismiss') +}) + +test('an empty dismissed list says so', async () => { + mockFetch({ 'GET /api/v1/discover/dismissed': () => page([]) }) + renderList('dismissed') + expect(await screen.findByText('You have not dismissed any artist.')).toBeInTheDocument() +}) + +test('a long list is read a page at a time', async () => { + const { calls } = mockFetch({ + 'GET /api/v1/wishlist': ({ url }) => { + const offset = Number(url.searchParams.get('offset')) + return offset === 0 ? page([marked(1, 'First')], 2, 0) : page([marked(2, 'Second')], 2, offset) + }, + }) + renderList('wishlist') + await screen.findByText('First') + await userEvent.click(screen.getByRole('button', { name: 'Show more' })) + expect(await screen.findByText('Second')).toBeInTheDocument() + expect(calls).toHaveLength(2) +}) + +test('a failure is said in words with a way to try again', async () => { + mockFetch({ 'GET /api/v1/wishlist': () => apiError(500, 'internal') }) + renderList('wishlist') + const alert = await screen.findByRole('alert') + expect(within(alert).getByRole('button', { name: 'Try again' })).toBeInTheDocument() +}) diff --git a/web/src/pages/discover/MarkedList.tsx b/web/src/pages/discover/MarkedList.tsx new file mode 100644 index 0000000..c458b5a --- /dev/null +++ b/web/src/pages/discover/MarkedList.tsx @@ -0,0 +1,81 @@ +import { useState } from 'react' +import { useTranslation } from 'react-i18next' +import { Link } from 'react-router-dom' +import { ApiError } from '@/api/client' +import { useArtistMarks, useDismissed, useWishlist, type MarkedArtist } from '@/api/discover' +import LoadMore from '@/components/LoadMore' +import { EmptyMessage, ErrorMessage, Loading } from '@/components/Status' +import { Button } from '@/components/ui/button' +import { errorMessageKey } from '@/i18n' + +/** The wishlist, or the artists you are not interested in: one row each, with what you can do about it. */ +export default function MarkedList({ kind }: { kind: 'wishlist' | 'dismissed' }) { + const { t } = useTranslation() + const wished = useWishlist({ enabled: kind === 'wishlist' }) + const dismissed = useDismissed({ enabled: kind === 'dismissed' }) + const query = kind === 'wishlist' ? wished : dismissed + const marks = useArtistMarks() + const [hideOwned, setHideOwned] = useState(false) + + const all = query.data?.items ?? [] + const items = hideOwned ? all.filter((m) => !m.in_library) : all + const failure = marks.removeFromWishlist.error ?? marks.dismiss.error ?? marks.undismiss.error + + if (query.isError) return void query.refetch()} /> + if (query.isPending) return + + return ( +
    + {kind === 'wishlist' && all.length > 0 && ( + + )} + + {all.length === 0 ? ( + {t(kind === 'wishlist' ? 'discover.marked.emptyWishlist' : 'discover.marked.emptyDismissed')} + ) : ( +
      + {items.map((m: MarkedArtist) => ( +
    • +
      + {m.in_library ? ( + + {m.artist.name} + + ) : ( + {m.artist.name} + )} + {m.in_library && {t('discover.inLibrary')}} +
      +
      + {kind === 'wishlist' ? ( + <> + + + + ) : ( + + )} +
      +
    • + ))} +
    + )} + + {failure ? ( +

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

    + ) : null} + +
    + ) +} From 88d3df9f6164d3c26286a54943c9159bc3461b9b Mon Sep 17 00:00:00 2001 From: tgiachi Date: Thu, 12 Nov 2026 14:11:27 +0100 Subject: [PATCH 07/10] feat(web): the Discover page with its three tabs, a sidebar link and a route The tab is kept in the address (?tab=) and moves with the arrow keys; only the open tab asks the server for its list. README now describes Discover in the web app. --- README.md | 6 +- web/src/components/layout/Shell.test.tsx | 3 +- web/src/components/layout/Sidebar.tsx | 1 + web/src/i18n/locales/en.json | 7 ++ web/src/i18n/locales/it.json | 7 ++ web/src/pages/DiscoverPage.test.tsx | 91 ++++++++++++++++++++++++ web/src/pages/DiscoverPage.tsx | 73 +++++++++++++++++++ web/src/router.tsx | 2 + 8 files changed, 186 insertions(+), 4 deletions(-) create mode 100644 web/src/pages/DiscoverPage.test.tsx create mode 100644 web/src/pages/DiscoverPage.tsx diff --git a/README.md b/README.md index 1c45b13..a91b558 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ It is a single executable, one database (SQLite by default, PostgreSQL if you pr ## What is not there yet -Radio queues, OpenSubsonic compatibility, transcoding, and the ListenBrainz integration. The web client exists (see [Web app](#web-app)) but `sondad` does not serve it yet, and it has no Discover or admin screens yet. +Radio queues, OpenSubsonic compatibility, transcoding, and the ListenBrainz integration. The web client exists (see [Web app](#web-app)) but `sondad` does not serve it yet, and it has no admin screens or Lidarr button yet. ## Requirements @@ -328,9 +328,9 @@ npm install SONDA_URL=http://127.0.0.1:8080 npm run dev # open http://localhost:5173, /api is proxied to Sonda ``` -What it does today: sign in (and create the first account of a new server), browse artists, albums and songs, search, and play with a queue, shuffle, repeat, media keys and a full-screen player. Artist pages show the Wikipedia text, similar artists and tags when those providers are on, each with its credit, and the photo credit next to the photo. It reports one listen per play. There are six themes (Sonda, Tokyo Night, Gruvbox dark, Gruvbox light, Dracula and Neon) and two languages (English and Italian), both chosen in Settings. +What it does today: sign in (and create the first account of a new server), browse artists, albums and songs, search, and play with a queue, shuffle, repeat, media keys and a full-screen player. Artist pages show the Wikipedia text, similar artists and tags when those providers are on, each with its credit, and the photo credit next to the photo. It reports one listen per play. Discover suggests artists from the ones you pick, or from your listening only after you allow it (a dialog says that their names go to Last.fm), explains each score, and keeps your wishlist and the artists you are not interested in. There are six themes (Sonda, Tokyo Night, Gruvbox dark, Gruvbox light, Dracula and Neon) and two languages (English and Italian), both chosen in Settings. -More commands, all run in `web/`: `npm test`, `npm run build`, and `npm run gen:api`, which rebuilds `src/api/schema.d.ts` from the OpenAPI spec (it fetches the generator with `npx`, so it needs the network once). Discover, the admin screens and serving the app from the binary come later. +More commands, all run in `web/`: `npm test`, `npm run build`, and `npm run gen:api`, which rebuilds `src/api/schema.d.ts` from the OpenAPI spec (it fetches the generator with `npx`, so it needs the network once). The Lidarr button, the admin screens and serving the app from the binary come later. ## Development diff --git a/web/src/components/layout/Shell.test.tsx b/web/src/components/layout/Shell.test.tsx index c7df56a..49d0547 100644 --- a/web/src/components/layout/Shell.test.tsx +++ b/web/src/components/layout/Shell.test.tsx @@ -28,7 +28,7 @@ test('at /artists the Artists link is the current page and the others are not', renderAt('/artists') const nav = within(mainNav()) expect(nav.getByRole('link', { name: 'Artists' })).toHaveAttribute('aria-current', 'page') - for (const name of ['Home', 'Search', 'Albums', 'Songs', 'Settings']) { + for (const name of ['Home', 'Search', 'Discover', 'Albums', 'Songs', 'Settings']) { expect(nav.getByRole('link', { name })).not.toHaveAttribute('aria-current') } }) @@ -59,6 +59,7 @@ test.each([ ['/artists', 'Artists'], ['/albums', 'Albums'], ['/songs', 'Songs'], + ['/discover', 'Discover'], ['/settings', 'Settings'], ])('the route %s opens a page headed %s', (path, heading) => { renderAt(path) diff --git a/web/src/components/layout/Sidebar.tsx b/web/src/components/layout/Sidebar.tsx index 3f099b7..3b1c16f 100644 --- a/web/src/components/layout/Sidebar.tsx +++ b/web/src/components/layout/Sidebar.tsx @@ -5,6 +5,7 @@ import { cn } from '@/lib/utils' const LINKS = [ { to: '/', key: 'nav.home', end: true }, { to: '/search', key: 'nav.search', end: false }, + { to: '/discover', key: 'nav.discover', end: false }, { to: '/artists', key: 'nav.artists', end: false }, { to: '/albums', key: 'nav.albums', end: false }, { to: '/songs', key: 'nav.songs', end: false }, diff --git a/web/src/i18n/locales/en.json b/web/src/i18n/locales/en.json index 7a884b2..06b4462 100644 --- a/web/src/i18n/locales/en.json +++ b/web/src/i18n/locales/en.json @@ -7,6 +7,7 @@ "main": "Main", "home": "Home", "search": "Search", + "discover": "Discover", "artists": "Artists", "albums": "Albums", "songs": "Songs", @@ -60,6 +61,12 @@ }, "discover": { "title": "Discover", + "tabs": { + "label": "Discover sections", + "suggestions": "Suggestions", + "wishlist": "Wishlist", + "dismissed": "Not interested" + }, "score": "{{percent}}% match", "because": "Because of {{names}}", "inLibrary": "In your library", diff --git a/web/src/i18n/locales/it.json b/web/src/i18n/locales/it.json index 890e280..f1c015b 100644 --- a/web/src/i18n/locales/it.json +++ b/web/src/i18n/locales/it.json @@ -7,6 +7,7 @@ "main": "Principale", "home": "Home", "search": "Cerca", + "discover": "Discover", "artists": "Artisti", "albums": "Album", "songs": "Brani", @@ -60,6 +61,12 @@ }, "discover": { "title": "Discover", + "tabs": { + "label": "Sezioni di Discover", + "suggestions": "Suggerimenti", + "wishlist": "Wishlist", + "dismissed": "Non mi interessa" + }, "score": "{{percent}}% di affinità", "because": "Per via di {{names}}", "inLibrary": "Nella tua libreria", diff --git a/web/src/pages/DiscoverPage.test.tsx b/web/src/pages/DiscoverPage.test.tsx new file mode 100644 index 0000000..e2688b9 --- /dev/null +++ b/web/src/pages/DiscoverPage.test.tsx @@ -0,0 +1,91 @@ +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { render, screen } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom' +import { beforeEach, expect, test, vi } from 'vitest' +import { sessionStore } from '@/auth/session' +import { initI18n } from '@/i18n' +import { mockFetch } from '@/test/mockFetch' +import DiscoverPage from './DiscoverPage' + +const empty = { items: [], total: 0, limit: 50, offset: 0 } + +function routes() { + return { + 'GET /api/v1/me/settings': () => ({ discover_from_listening: false }), + 'GET /api/v1/me/taste': () => ({ artists: [], tags: [] }), + 'GET /api/v1/wishlist': () => empty, + 'GET /api/v1/discover/dismissed': () => empty, + 'GET /api/v1/discover': () => ({ provider_status: 'ok', attribution: '', from_listening: false, seeds: [], items: [] }), + } +} + +function Where() { + const { pathname, search } = useLocation() + return {pathname + search} +} + +function renderPage(path = '/discover') { + const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } }) + return render( + + + + + } /> + + + , + ) +} + +const tab = (name: string) => screen.getByRole('tab', { name }) + +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 opens on the suggestions', async () => { + mockFetch(routes()) + renderPage() + expect(screen.getByRole('heading', { level: 1, name: 'Discover' })).toBeInTheDocument() + expect(tab('Suggestions')).toHaveAttribute('aria-selected', 'true') + expect(tab('Wishlist')).toHaveAttribute('aria-selected', 'false') + expect(await screen.findByText('Pick an artist to start from, or let Discover start from your listening.')).toBeInTheDocument() +}) + +test('the address names the tab, and only that tab asks the server for its list', async () => { + const { calls } = mockFetch(routes()) + renderPage('/discover?tab=wishlist') + expect(tab('Wishlist')).toHaveAttribute('aria-selected', 'true') + expect(await screen.findByText('Nothing on your wishlist yet. Add artists from the suggestions.')).toBeInTheDocument() + expect(calls.map((c) => c.key)).not.toContain('GET /api/v1/discover') + expect(calls.map((c) => c.key)).not.toContain('GET /api/v1/discover/dismissed') +}) + +test('choosing a tab changes the address', async () => { + mockFetch(routes()) + renderPage() + await userEvent.click(tab('Not interested')) + expect(screen.getByTestId('where')).toHaveTextContent('/discover?tab=dismissed') + expect(await screen.findByText('You have not dismissed any artist.')).toBeInTheDocument() +}) + +test('a tab that does not exist falls back to the suggestions', () => { + mockFetch(routes()) + renderPage('/discover?tab=bogus') + expect(tab('Suggestions')).toHaveAttribute('aria-selected', 'true') +}) + +test('the arrow keys move between the tabs', async () => { + mockFetch(routes()) + renderPage() + tab('Suggestions').focus() + await userEvent.keyboard('{ArrowRight}') + expect(tab('Wishlist')).toHaveAttribute('aria-selected', 'true') + expect(tab('Wishlist')).toHaveFocus() + await userEvent.keyboard('{ArrowLeft}{ArrowLeft}') + expect(tab('Not interested')).toHaveAttribute('aria-selected', 'true') +}) diff --git a/web/src/pages/DiscoverPage.tsx b/web/src/pages/DiscoverPage.tsx new file mode 100644 index 0000000..38024ad --- /dev/null +++ b/web/src/pages/DiscoverPage.tsx @@ -0,0 +1,73 @@ +import { useRef, type KeyboardEvent } from 'react' +import { useTranslation } from 'react-i18next' +import { useSearchParams } from 'react-router-dom' +import { cn } from '@/lib/utils' +import MarkedList from './discover/MarkedList' +import SuggestionsTab from './discover/SuggestionsTab' + +const TABS = [ + { id: 'suggestions', key: 'discover.tabs.suggestions' }, + { id: 'wishlist', key: 'discover.tabs.wishlist' }, + { id: 'dismissed', key: 'discover.tabs.dismissed' }, +] as const + +type TabId = (typeof TABS)[number]['id'] + +function parse(value: string | null): TabId { + return TABS.find((tab) => tab.id === value)?.id ?? 'suggestions' +} + +export default function DiscoverPage() { + const { t } = useTranslation() + const [params, setParams] = useSearchParams() + const current = parse(params.get('tab')) + const buttons = useRef>({}) + + function choose(id: TabId) { + setParams(id === 'suggestions' ? {} : { tab: id }) + } + + function onKeyDown(event: KeyboardEvent) { + const step = event.key === 'ArrowRight' ? 1 : event.key === 'ArrowLeft' ? -1 : 0 + if (step === 0) return + event.preventDefault() + const at = TABS.findIndex((tab) => tab.id === current) + const next = TABS[(at + step + TABS.length) % TABS.length].id + choose(next) + buttons.current[next]?.focus() + } + + return ( +
    +

    {t('discover.title')}

    + +
    + {TABS.map((tab) => ( + + ))} +
    + +
    + {current === 'suggestions' ? : } +
    +
    + ) +} diff --git a/web/src/router.tsx b/web/src/router.tsx index 1771082..2c6c6bd 100644 --- a/web/src/router.tsx +++ b/web/src/router.tsx @@ -4,6 +4,7 @@ import AlbumPage from '@/pages/AlbumPage' import AlbumsPage from '@/pages/AlbumsPage' import ArtistPage from '@/pages/ArtistPage' import ArtistsPage from '@/pages/ArtistsPage' +import DiscoverPage from '@/pages/DiscoverPage' import HomePage from '@/pages/HomePage' import NotFoundPage from '@/pages/NotFoundPage' import SearchPage from '@/pages/SearchPage' @@ -16,6 +17,7 @@ export const routes: RouteObject[] = [ children: [ { path: '/', element: }, { path: '/search', element: }, + { path: '/discover', element: }, { path: '/artists', element: }, { path: '/artists/:id', element: }, { path: '/albums', element: }, From 0198a6d10b645af3f5906973f84317cd02cd505a Mon Sep 17 00:00:00 2001 From: tgiachi Date: Thu, 12 Nov 2026 14:12:57 +0100 Subject: [PATCH 08/10] fix(web): say what to do when Discover starts from a listening that is empty Found against a real server: with the setting on and nothing played, the answer is empty with no seeds. The page now says to play something or pick an artist, instead of a plain 'no suggestions'. --- web/src/i18n/locales/en.json | 1 + web/src/i18n/locales/it.json | 1 + web/src/pages/discover/SuggestionsTab.test.tsx | 7 +++++++ web/src/pages/discover/SuggestionsTab.tsx | 5 ++++- 4 files changed, 13 insertions(+), 1 deletion(-) diff --git a/web/src/i18n/locales/en.json b/web/src/i18n/locales/en.json index 06b4462..bc7c048 100644 --- a/web/src/i18n/locales/en.json +++ b/web/src/i18n/locales/en.json @@ -78,6 +78,7 @@ "fromListening": "Started from your listening: {{names}}", "onlyNew": "Only artists I do not have", "none": "No suggestions yet.", + "nothingPlayed": "You have not played anything to start from yet. Play something, or pick an artist above.", "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", diff --git a/web/src/i18n/locales/it.json b/web/src/i18n/locales/it.json index f1c015b..7994d96 100644 --- a/web/src/i18n/locales/it.json +++ b/web/src/i18n/locales/it.json @@ -78,6 +78,7 @@ "fromListening": "Partito dai tuoi ascolti: {{names}}", "onlyNew": "Solo artisti che non ho", "none": "Ancora nessun suggerimento.", + "nothingPlayed": "Non hai ancora ascoltato niente da cui partire. Ascolta qualcosa, oppure scegli un artista qui sopra.", "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", diff --git a/web/src/pages/discover/SuggestionsTab.test.tsx b/web/src/pages/discover/SuggestionsTab.test.tsx index 4cd85fc..2a15aa9 100644 --- a/web/src/pages/discover/SuggestionsTab.test.tsx +++ b/web/src/pages/discover/SuggestionsTab.test.tsx @@ -144,6 +144,13 @@ test('when Last.fm failed for some artists the rest is shown with a warning', as expect(screen.getByText('Last.fm could not be reached for some artists, so this list may be shorter.')).toBeInTheDocument() }) +test('starting from a listening that is empty says to play something, not just "nothing"', async () => { + mockFetch(routes(true, { 'GET /api/v1/discover': () => answer({ from_listening: true, seeds: [], items: [] }) })) + renderTab() + expect(await screen.findByText('You have not played anything to start from yet. Play something, or pick an artist above.')).toBeInTheDocument() + expect(screen.queryByText('No suggestions yet.')).not.toBeInTheDocument() +}) + test('an empty answer says there is nothing yet', async () => { mockFetch(routes(true, { 'GET /api/v1/discover': () => answer({ items: [] }) })) renderTab() diff --git a/web/src/pages/discover/SuggestionsTab.tsx b/web/src/pages/discover/SuggestionsTab.tsx index f7e75a1..1da125e 100644 --- a/web/src/pages/discover/SuggestionsTab.tsx +++ b/web/src/pages/discover/SuggestionsTab.tsx @@ -101,7 +101,10 @@ export default function SuggestionsTab() {

    )} {data.items.length === 0 ? ( - {t('discover.none')} + + {/* Listening was the only start and it is empty: say what to do, not just "nothing". */} + {data.from_listening && data.seeds.length === 0 && seeds.length === 0 ? t('discover.nothingPlayed') : t('discover.none')} + ) : (
      {data.items.map((item) => ( From edbe212f463f0c7dab35f44e907c6d631bc6362b Mon Sep 17 00:00:00 2001 From: tgiachi Date: Thu, 12 Nov 2026 14:15:51 +0100 Subject: [PATCH 09/10] fix(web): clear the artist box after choosing, wrap suggestion cards on phones Found in a real browser: after choosing a starting artist the box kept its text and claimed nothing matched, the card's buttons squeezed the name on a phone, and the switch knob was almost invisible when off. --- web/src/components/ListeningSwitch.tsx | 4 +-- web/src/pages/discover/SeedPicker.test.tsx | 29 +++++++++++++++++++--- web/src/pages/discover/SeedPicker.tsx | 14 ++++++++--- web/src/pages/discover/SuggestionCard.tsx | 8 +++--- 4 files changed, 43 insertions(+), 12 deletions(-) diff --git a/web/src/components/ListeningSwitch.tsx b/web/src/components/ListeningSwitch.tsx index 6b37dc4..b493bc7 100644 --- a/web/src/components/ListeningSwitch.tsx +++ b/web/src/components/ListeningSwitch.tsx @@ -41,8 +41,8 @@ export default function ListeningSwitch() {