Merge pull request 'feat(web): Discover, wishlist and not-interested lists (F2a)' (#64) from feat/discover-wishlist into main
This commit is contained in:
commit
bfcf954673
28 changed files with 1888 additions and 21 deletions
|
|
@ -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
|
||||
|
||||
|
|
|
|||
|
|
@ -25,7 +25,7 @@ export interface ListOptions {
|
|||
}
|
||||
|
||||
/** A list the server pages by `limit` and `offset`, read one page after the other. */
|
||||
function usePagedList<T>(path: string, params: Params, opts: ListOptions = {}) {
|
||||
export function usePagedList<T>(path: string, params: Params, opts: ListOptions = {}) {
|
||||
const pageSize = opts.pageSize ?? PAGE_SIZE
|
||||
return useInfiniteQuery({
|
||||
queryKey: [path, params, pageSize],
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
})
|
||||
|
|
|
|||
|
|
@ -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<string, string | number | boolean | undefined>
|
||||
type QueryValue = string | number | boolean | undefined
|
||||
/** A list value is sent once for each item (`seed=1&seed=2`). */
|
||||
type Query = Record<string, QueryValue | QueryValue[]>
|
||||
|
||||
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<ApiError> {
|
||||
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<Response> {
|
||||
const headers: Record<string, string> = { 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<T>(method: string, path: string, params: Query | undefined, body: unknown, opts: CallOptions): Promise<T> {
|
||||
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()
|
||||
}
|
||||
|
||||
|
|
|
|||
171
web/src/api/discover.test.tsx
Normal file
171
web/src/api/discover.test.tsx
Normal file
|
|
@ -0,0 +1,171 @@
|
|||
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 }) => <QueryClientProvider client={client}>{children}</QueryClientProvider>
|
||||
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('a failed Discover is not asked again by itself, whatever the app default is', async () => {
|
||||
const { calls } = mockFetch({ 'GET /api/v1/discover': () => apiError(429, 'discover_busy') })
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: 2, retryDelay: 1 } } })
|
||||
const wrapper = ({ children }: { children: ReactNode }) => <QueryClientProvider client={client}>{children}</QueryClientProvider>
|
||||
const { result } = renderHook(() => useDiscover({ seeds: [1] }), { wrapper })
|
||||
await waitFor(() => expect(result.current.isError).toBe(true))
|
||||
await new Promise((r) => setTimeout(r, 50))
|
||||
expect(calls).toHaveLength(1)
|
||||
})
|
||||
|
||||
test('the wishlist and the dismissed list are read page after page', async () => {
|
||||
const { calls } = mockFetch({
|
||||
'GET /api/v1/wishlist': ({ url }) => ({ items: [marked(1)], total: 1, limit: 50, offset: Number(url.searchParams.get('offset')) }),
|
||||
'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<typeof discover>).items as ReturnType<typeof suggestion>[]
|
||||
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<typeof discover>).items as ReturnType<typeof suggestion>[]
|
||||
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<typeof discover>).items as ReturnType<typeof suggestion>[]
|
||||
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<typeof discover>).items as ReturnType<typeof suggestion>[]).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'])
|
||||
})
|
||||
|
||||
test('being interested again makes the kept suggestions old, without asking Discover at once', async () => {
|
||||
const { calls } = mockFetch({ 'DELETE /api/v1/discover/7/dismiss': () => new Response(null, { status: 204 }) })
|
||||
const { client, wrapper } = setup()
|
||||
const key = ['discover', { seeds: [1], inLibrary: undefined }]
|
||||
client.setQueryData(key, discover([suggestion(8)]))
|
||||
const { result } = renderHook(() => useArtistMarks(), { wrapper })
|
||||
await act(() => result.current.undismiss.mutateAsync(7))
|
||||
// The artist is missing from what is kept, so the next visit must read it again; nobody is looking now, and
|
||||
// the call is heavy, so nothing is asked yet.
|
||||
expect(client.getQueryState(key)?.isInvalidated).toBe(true)
|
||||
expect(calls.map((c) => c.key)).not.toContain('GET /api/v1/discover')
|
||||
})
|
||||
120
web/src/api/discover.ts
Normal file
120
web/src/api/discover.ts
Normal file
|
|
@ -0,0 +1,120 @@
|
|||
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,
|
||||
// A busy answer (429) or a slow one is the user's to retry with a button, never repeated behind their back.
|
||||
retry: false,
|
||||
queryFn: ({ signal }) => api.get<Discover>('/discover', { seed: seeds, in_library: inLibrary }, { signal }),
|
||||
})
|
||||
}
|
||||
|
||||
export function useWishlist(opts: ListOptions = {}) {
|
||||
return usePagedList<MarkedArtist>('/wishlist', {}, opts)
|
||||
}
|
||||
|
||||
export function useDismissed(opts: ListOptions = {}) {
|
||||
return usePagedList<MarkedArtist>('/discover/dismissed', {}, opts)
|
||||
}
|
||||
|
||||
export function useTaste() {
|
||||
return useQuery({ queryKey: ['me', 'taste'], queryFn: () => api.get<Taste>('/me/taste', { limit: 10 }) })
|
||||
}
|
||||
|
||||
const SETTINGS_KEY = ['me', 'settings']
|
||||
|
||||
export function useMySettings() {
|
||||
return useQuery({ queryKey: SETTINGS_KEY, queryFn: () => api.get<UserSettings>('/me/settings') })
|
||||
}
|
||||
|
||||
export function useUpdateSettings() {
|
||||
const client = useQueryClient()
|
||||
return useMutation({
|
||||
mutationFn: (body: UpdateUserSettings) => api.patch<UserSettings>('/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<Discover>({ queryKey: [DISCOVER] })
|
||||
client.setQueriesData<Discover>({ 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<unknown>, 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: () => {
|
||||
// What is kept may now lack an artist (interested again) or be wrong if the call failed: mark it old so the
|
||||
// next visit reads it again. Nothing is asked now: Discover is heavy and the screen already shows the change.
|
||||
void client.invalidateQueries({ queryKey: [DISCOVER], refetchType: 'none' })
|
||||
return 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)),
|
||||
}
|
||||
}
|
||||
|
|
@ -6,8 +6,22 @@ function initial(name: string): string {
|
|||
return Array.from(name.trim())[0]?.toUpperCase() ?? '?'
|
||||
}
|
||||
|
||||
/** A round photo of an artist, or the first letter of the name when there is no free picture. */
|
||||
export default function ArtistPhoto({ artistId, name, size }: { artistId: number; name: string; size: number }) {
|
||||
/**
|
||||
* A round photo of an artist, or the first letter of the name when there is no free picture. With `photo`
|
||||
* false it never asks for the picture: asking makes the server look the artist up at the providers, which a
|
||||
* list of names nobody chose should not do.
|
||||
*/
|
||||
export default function ArtistPhoto({
|
||||
artistId,
|
||||
name,
|
||||
size,
|
||||
photo = true,
|
||||
}: {
|
||||
artistId: number
|
||||
name: string
|
||||
size: number
|
||||
photo?: boolean
|
||||
}) {
|
||||
useAccessToken() // the URL carries the token, so it has to follow a renewal
|
||||
const src = mediaUrl(`/artists/${artistId}/image`)
|
||||
const [failed, setFailed] = useState<string | null>(null)
|
||||
|
|
@ -17,7 +31,7 @@ export default function ArtistPhoto({ artistId, name, size }: { artistId: number
|
|||
style={{ width: size, height: size }}
|
||||
className="relative flex shrink-0 items-center justify-center overflow-hidden rounded-md bg-primary text-primary-foreground"
|
||||
>
|
||||
{failed !== src ? (
|
||||
{photo && failed !== src ? (
|
||||
<img
|
||||
src={src}
|
||||
alt={name}
|
||||
|
|
|
|||
80
web/src/components/ListeningSwitch.test.tsx
Normal file
80
web/src/components/ListeningSwitch.test.tsx
Normal file
|
|
@ -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, type RecordedCall } 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(
|
||||
<QueryClientProvider client={client}>
|
||||
<ListeningSwitch />
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
return mocked
|
||||
}
|
||||
|
||||
const toggle = () => screen.findByRole('switch', { name: 'Start Discover from my listening' })
|
||||
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)
|
||||
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')
|
||||
})
|
||||
76
web/src/components/ListeningSwitch.tsx
Normal file
76
web/src/components/ListeningSwitch.tsx
Normal file
|
|
@ -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 (
|
||||
<div className="flex max-w-xl flex-col gap-3">
|
||||
<div className="flex items-center gap-4">
|
||||
<button
|
||||
type="button"
|
||||
role="switch"
|
||||
aria-checked={on}
|
||||
aria-labelledby="listening-label"
|
||||
disabled={settings.data === undefined || update.isPending}
|
||||
onClick={() => (on ? change(false) : setAsking(true))}
|
||||
className={cn(
|
||||
'relative h-7 w-12 shrink-0 rounded-md border border-input transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring disabled:opacity-50',
|
||||
on ? 'bg-primary' : 'bg-secondary',
|
||||
)}
|
||||
>
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className={cn(
|
||||
'absolute top-0.5 left-0.5 size-5 rounded-sm transition-transform motion-reduce:transition-none',
|
||||
on ? 'translate-x-5 bg-primary-foreground' : 'bg-muted-foreground',
|
||||
)}
|
||||
/>
|
||||
</button>
|
||||
<span id="listening-label" className="font-semibold">
|
||||
{t('discover.listening.label')}
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">{t('discover.listening.help')}</p>
|
||||
{update.isError && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{t(errorMessageKey(update.error instanceof ApiError ? update.error.code : 'unknown'))}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<Dialog open={asking} onOpenChange={setAsking}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t('discover.listening.confirmTitle')}</DialogTitle>
|
||||
<DialogDescription>{t('discover.listening.confirmBody')}</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setAsking(false)}>
|
||||
{t('discover.listening.cancel')}
|
||||
</Button>
|
||||
<Button onClick={() => change(true)}>{t('discover.listening.turnOn')}</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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 },
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@
|
|||
"main": "Main",
|
||||
"home": "Home",
|
||||
"search": "Search",
|
||||
"discover": "Discover",
|
||||
"artists": "Artists",
|
||||
"albums": "Albums",
|
||||
"songs": "Songs",
|
||||
|
|
@ -58,6 +59,67 @@
|
|||
"currentPasswordWrong": "The current password is wrong.",
|
||||
"changePassword": "Change password"
|
||||
},
|
||||
"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",
|
||||
"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.",
|
||||
"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",
|
||||
"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",
|
||||
"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",
|
||||
"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.",
|
||||
"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",
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@
|
|||
"main": "Principale",
|
||||
"home": "Home",
|
||||
"search": "Cerca",
|
||||
"discover": "Discover",
|
||||
"artists": "Artisti",
|
||||
"albums": "Album",
|
||||
"songs": "Brani",
|
||||
|
|
@ -58,6 +59,67 @@
|
|||
"currentPasswordWrong": "La password attuale è sbagliata.",
|
||||
"changePassword": "Cambia password"
|
||||
},
|
||||
"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",
|
||||
"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.",
|
||||
"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",
|
||||
"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",
|
||||
"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",
|
||||
"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.",
|
||||
"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",
|
||||
|
|
|
|||
91
web/src/pages/DiscoverPage.test.tsx
Normal file
91
web/src/pages/DiscoverPage.test.tsx
Normal file
|
|
@ -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 <output data-testid="where">{pathname + search}</output>
|
||||
}
|
||||
|
||||
function renderPage(path = '/discover') {
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } })
|
||||
return render(
|
||||
<QueryClientProvider client={client}>
|
||||
<MemoryRouter initialEntries={[path]}>
|
||||
<Where />
|
||||
<Routes>
|
||||
<Route path="/discover" element={<DiscoverPage />} />
|
||||
</Routes>
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
}
|
||||
|
||||
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')
|
||||
})
|
||||
73
web/src/pages/DiscoverPage.tsx
Normal file
73
web/src/pages/DiscoverPage.tsx
Normal file
|
|
@ -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<Record<string, HTMLButtonElement | null>>({})
|
||||
|
||||
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 (
|
||||
<div className="flex flex-col gap-6">
|
||||
<h1 className="text-3xl font-extrabold tracking-tight">{t('discover.title')}</h1>
|
||||
|
||||
<div role="tablist" aria-label={t('discover.tabs.label')} onKeyDown={onKeyDown} className="flex flex-wrap gap-2">
|
||||
{TABS.map((tab) => (
|
||||
<button
|
||||
key={tab.id}
|
||||
ref={(el) => {
|
||||
buttons.current[tab.id] = el
|
||||
}}
|
||||
type="button"
|
||||
role="tab"
|
||||
id={`tab-${tab.id}`}
|
||||
aria-selected={current === tab.id}
|
||||
aria-controls="discover-panel"
|
||||
tabIndex={current === tab.id ? 0 : -1}
|
||||
onClick={() => choose(tab.id)}
|
||||
className={cn(
|
||||
'min-h-11 rounded-lg px-4 font-semibold focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring',
|
||||
current === tab.id ? 'bg-secondary text-foreground' : 'text-muted-foreground hover:text-foreground',
|
||||
)}
|
||||
>
|
||||
{t(tab.key)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div role="tabpanel" id="discover-panel" aria-labelledby={`tab-${current}`}>
|
||||
{current === 'suggestions' ? <SuggestionsTab /> : <MarkedList key={current} kind={current} />}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
@ -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(
|
||||
<MemoryRouter>
|
||||
<SettingsPage />
|
||||
</MemoryRouter>,
|
||||
<QueryClientProvider client={client}>
|
||||
<MemoryRouter>
|
||||
<SettingsPage />
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
}
|
||||
|
||||
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 () => {
|
||||
|
|
|
|||
|
|
@ -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() {
|
|||
/>
|
||||
</Section>
|
||||
|
||||
<Section title={t('discover.title')}>
|
||||
<ListeningSwitch />
|
||||
</Section>
|
||||
|
||||
<Section title={t('settings.password')}>
|
||||
<ChangePassword />
|
||||
</Section>
|
||||
|
|
|
|||
126
web/src/pages/discover/MarkedList.test.tsx
Normal file
126
web/src/pages/discover/MarkedList.test.tsx
Normal file
|
|
@ -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(
|
||||
<QueryClientProvider client={client}>
|
||||
<MemoryRouter>
|
||||
<MarkedList kind={kind} />
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
}
|
||||
|
||||
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()
|
||||
})
|
||||
81
web/src/pages/discover/MarkedList.tsx
Normal file
81
web/src/pages/discover/MarkedList.tsx
Normal file
|
|
@ -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 <ErrorMessage error={query.error} onRetry={() => void query.refetch()} />
|
||||
if (query.isPending) return <Loading />
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
{kind === 'wishlist' && all.length > 0 && (
|
||||
<label className="flex min-h-11 items-center gap-3 font-semibold">
|
||||
<input type="checkbox" checked={hideOwned} onChange={(e) => setHideOwned(e.target.checked)} className="size-5 accent-primary" />
|
||||
{t('discover.marked.hideOwned')}
|
||||
</label>
|
||||
)}
|
||||
|
||||
{all.length === 0 ? (
|
||||
<EmptyMessage>{t(kind === 'wishlist' ? 'discover.marked.emptyWishlist' : 'discover.marked.emptyDismissed')}</EmptyMessage>
|
||||
) : (
|
||||
<ul className="flex flex-col gap-3">
|
||||
{items.map((m: MarkedArtist) => (
|
||||
<li key={m.artist.id} className="flex flex-wrap items-center gap-4 rounded-lg bg-card p-4 text-card-foreground">
|
||||
<div className="flex min-w-0 flex-1 flex-col">
|
||||
{m.in_library ? (
|
||||
<Link to={`/artists/${m.artist.id}`} className="truncate text-lg font-bold hover:underline">
|
||||
{m.artist.name}
|
||||
</Link>
|
||||
) : (
|
||||
<span className="truncate text-lg font-bold">{m.artist.name}</span>
|
||||
)}
|
||||
{m.in_library && <span className="text-sm text-muted-foreground">{t('discover.inLibrary')}</span>}
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{kind === 'wishlist' ? (
|
||||
<>
|
||||
<Button variant="outline" onClick={() => marks.removeFromWishlist.mutate(m.artist.id)}>
|
||||
{t('discover.marked.remove')}
|
||||
</Button>
|
||||
<Button variant="outline" onClick={() => marks.dismiss.mutate(m.artist.id)}>
|
||||
{t('discover.notInterested')}
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<Button variant="outline" onClick={() => marks.undismiss.mutate(m.artist.id)}>
|
||||
{t('discover.marked.interestedAgain')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
{failure ? (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{t(errorMessageKey(failure instanceof ApiError ? failure.code : 'unknown'))}
|
||||
</p>
|
||||
) : null}
|
||||
<LoadMore query={query} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
104
web/src/pages/discover/SeedPicker.test.tsx
Normal file
104
web/src/pages/discover/SeedPicker.test.tsx
Normal file
|
|
@ -0,0 +1,104 @@
|
|||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { render, screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { useState } from 'react'
|
||||
import { beforeEach, expect, test, vi } from 'vitest'
|
||||
import { sessionStore } from '@/auth/session'
|
||||
import { initI18n } from '@/i18n'
|
||||
import { mockFetch } from '@/test/mockFetch'
|
||||
import SeedPicker, { type Seed } from './SeedPicker'
|
||||
|
||||
const artist = (id: number, name: string) => ({ id, name, album_count: 1, track_count: 3 })
|
||||
|
||||
function Harness({ start = [] as Seed[] }) {
|
||||
const [seeds, setSeeds] = useState<Seed[]>(start)
|
||||
return (
|
||||
<SeedPicker
|
||||
seeds={seeds}
|
||||
onAdd={(s) => setSeeds((all) => [...all, s])}
|
||||
onRemove={(id) => setSeeds((all) => all.filter((s) => s.id !== id))}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function renderPicker(start: Seed[] = []) {
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
return render(
|
||||
<QueryClientProvider client={client}>
|
||||
<Harness start={start} />
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
}
|
||||
|
||||
const box = () => screen.getByRole('searchbox', { name: 'Find an artist to start from' })
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.spyOn(navigator, 'language', 'get').mockReturnValue('en-US')
|
||||
await initI18n()
|
||||
sessionStore.setState({ status: 'authenticated', user: { id: 1, username: 'tom', is_admin: false } })
|
||||
})
|
||||
|
||||
test('nothing is asked of the library until something is typed', async () => {
|
||||
const { calls } = mockFetch({ 'GET /api/v1/artists': () => ({ items: [], total: 0, limit: 6, offset: 0 }) })
|
||||
renderPicker()
|
||||
await new Promise((r) => setTimeout(r, 350))
|
||||
expect(calls).toHaveLength(0)
|
||||
})
|
||||
|
||||
test('typing finds artists, and choosing one makes it a chip', async () => {
|
||||
const { calls } = mockFetch({
|
||||
'GET /api/v1/artists': () => ({ items: [artist(1, 'Björk'), artist(2, 'Bjørn')], total: 2, limit: 6, offset: 0 }),
|
||||
})
|
||||
renderPicker()
|
||||
await userEvent.type(box(), 'bj')
|
||||
await userEvent.click(await screen.findByRole('button', { name: 'Add Björk' }))
|
||||
expect(calls.at(-1)?.url.searchParams.get('q')).toBe('bj')
|
||||
expect(screen.getByRole('list', { name: 'Starting artists' })).toHaveTextContent('Björk')
|
||||
// Choosing is done: the box is empty for the next one and offers nothing.
|
||||
expect(box()).toHaveValue('')
|
||||
expect(screen.queryByRole('button', { name: 'Add Bjørn' })).not.toBeInTheDocument()
|
||||
expect(screen.queryByText(/Nothing matches/)).not.toBeInTheDocument()
|
||||
|
||||
// Looking again, a chosen artist is not offered a second time.
|
||||
await userEvent.type(box(), 'bj')
|
||||
expect(await screen.findByRole('button', { name: 'Add Bjørn' })).toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: 'Add Björk' })).not.toBeInTheDocument()
|
||||
expect(screen.queryByText(/Nothing matches/)).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('when the only match is already chosen it does not claim there is no match', async () => {
|
||||
mockFetch({ 'GET /api/v1/artists': () => ({ items: [artist(1, 'Björk')], total: 1, limit: 6, offset: 0 }) })
|
||||
renderPicker([{ id: 1, name: 'Björk' }])
|
||||
await userEvent.type(box(), 'bj')
|
||||
await waitFor(() => expect(box()).toHaveValue('bj'))
|
||||
await new Promise((r) => setTimeout(r, 400))
|
||||
expect(screen.queryByText(/Nothing matches/)).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('a search that finds nothing says so', async () => {
|
||||
mockFetch({ 'GET /api/v1/artists': () => ({ items: [], total: 0, limit: 6, offset: 0 }) })
|
||||
renderPicker()
|
||||
await userEvent.type(box(), 'zzz')
|
||||
expect(await screen.findByText('Nothing matches “zzz”.')).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()
|
||||
})
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue