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.
This commit is contained in:
tgiachi 2026-11-12 14:04:16 +01:00
commit 63ed483936
3 changed files with 262 additions and 1 deletions

View file

@ -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],

View file

@ -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 }) => <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('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'])
})

113
web/src/api/discover.ts Normal file
View file

@ -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>('/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: () => 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)),
}
}