sonda/web/src/api/discover.ts
tgiachi 44dbc727aa fix(web): no photo lookups for artists you do not have, and stale suggestions after changes
A suggestion for an artist outside the library no longer asks for its photo, since that makes the server look the name up at the providers for every card. Changing a wish or a dismissal marks the kept suggestions old without asking Discover at once. Visible focus on the switch, the tabs and the chip buttons.
2026-11-12 14:17:05 +01:00

120 lines
4.9 KiB
TypeScript

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)),
}
}