A heart on every song, album and artist, in the player bar and the full-screen player, and a Favourites page with the songs, albums and artists, newest first. The heart changes at once and goes back if the server refuses. Hearts are only for music of this server: a friend's song has none. - FavoriteButton, useIsFavorite and useSetFavorite - /favorites page, a Favourites item in the Library group of the menu, on the Library page and in the phone Library tab
59 lines
2.2 KiB
TypeScript
59 lines
2.2 KiB
TypeScript
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
|
import { api } from '@/api/client'
|
|
import type { components } from '@/api/schema'
|
|
|
|
export type FavoriteKind = 'artists' | 'albums' | 'tracks'
|
|
export type FavoriteIds = components['schemas']['FavoriteIds']
|
|
|
|
const IDS_KEY = ['me', 'favorites', 'ids']
|
|
|
|
// A list of songs has a heart on every row: each asks the same question of the same answer, so the answer is turned into
|
|
// sets once, not once for every heart.
|
|
const sets = new WeakMap<FavoriteIds, Record<FavoriteKind, Set<number>>>()
|
|
|
|
function setsOf(ids: FavoriteIds) {
|
|
let found = sets.get(ids)
|
|
if (!found) {
|
|
found = { artists: new Set(ids.artists), albums: new Set(ids.albums), tracks: new Set(ids.tracks) }
|
|
sets.set(ids, found)
|
|
}
|
|
return found
|
|
}
|
|
|
|
/** Whether this artist, album or song is a favourite of the person. Until the server has answered it is not. */
|
|
export function useIsFavorite(kind: FavoriteKind, id: number): boolean {
|
|
return (
|
|
useQuery({
|
|
queryKey: IDS_KEY,
|
|
queryFn: () => api.get<FavoriteIds>('/me/favorites/ids'),
|
|
select: (ids) => setsOf(ids)[kind].has(id),
|
|
}).data ?? false
|
|
)
|
|
}
|
|
|
|
/**
|
|
* Marks or unmarks one thing. The heart changes at once and goes back if the server refuses; the lists of favourites
|
|
* are read again when it is done.
|
|
*/
|
|
export function useSetFavorite(kind: FavoriteKind, id: number) {
|
|
const client = useQueryClient()
|
|
return useMutation({
|
|
mutationFn: (on: boolean) => (on ? api.put<void>(`/me/favorites/${kind}/${id}`) : api.del<void>(`/me/favorites/${kind}/${id}`)),
|
|
onMutate: async (on) => {
|
|
await client.cancelQueries({ queryKey: IDS_KEY })
|
|
const before = client.getQueryData<FavoriteIds>(IDS_KEY)
|
|
if (before) {
|
|
const rest = before[kind].filter((x) => x !== id)
|
|
client.setQueryData<FavoriteIds>(IDS_KEY, { ...before, [kind]: on ? [id, ...rest] : rest })
|
|
}
|
|
return { before }
|
|
},
|
|
onError: (_error, _on, context) => {
|
|
if (context?.before) client.setQueryData(IDS_KEY, context.before)
|
|
},
|
|
onSettled: () => {
|
|
void client.invalidateQueries({ queryKey: IDS_KEY })
|
|
void client.invalidateQueries({ queryKey: [`/me/favorites/${kind}`] })
|
|
},
|
|
})
|
|
}
|