feat: favourites in the web app
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
This commit is contained in:
parent
f7c24fa6f4
commit
a93260af05
22 changed files with 396 additions and 17 deletions
|
|
@ -37,7 +37,7 @@ It is a single executable, one database (SQLite by default, PostgreSQL if you pr
|
|||
- **Similar artists.** With Last.fm turned on, `GET /artists/{id}/similar` lists artists similar to an artist, and says which of them you already have. See [External providers](#external-providers). Without it, Sonda makes no outbound network requests at all.
|
||||
- **Friends (federation).** Two Sonda servers can become friends, and the listeners of one can read what the other chose to share. `PUT /federation` (admin) turns federation on, which is off by default, and gives this server a name and a public address (`https`; plain `http` only on a network of your own); the server then makes its own Ed25519 key, kept in the database and never returned. `POST /federation/invites` makes an invite that works once and expires in 24 hours (only a hash of its code is kept). The other admin uses it with `POST /federation/friends`: that server is asked to accept this one, the key it answers with must be the one named in the invite, and the friend waits as `outgoing` until the first admin approves it with `POST /federation/friends/{id}/approve` (`POST /federation/friends/{id}/check` lets the waiting side find out). Either side can remove a friend with `DELETE /federation/friends/{id}`. Nothing is shared until an admin turns on `shared` for a library (`PATCH /libraries/{id}`). A friend's server then reads, with requests signed by its key (the method, the path and query, a date, a nonce and the hash of the body), the routes under `/peer`: the artists, albums and songs that have a file in a shared library, their covers once they are built, and the audio itself with `Range`. A friend never sees a path, a library id, a listen, a taste or a user, never makes this server build a cover or ask a provider, and has a few streams at a time and a number of KiB a second to share (`max_streams`, `max_kib_per_sec`); the admin sees the last requests it made (`GET /federation/requests`, the route and the size, never what was searched for). Sharing a library lets friends play it and, in practice, copy its files. A listener browses the music of a friend with `GET /friends` (the names of the friends whose friendship both admins agreed to, never an address or a key) and `GET /friends/{friend}/artists`, `albums` and `tracks` with `q`, `limit` and `offset`, and one item at a time: this server asks the friend with a signed request, checks the shape of the answer and passes it on, and nothing is kept; the ids are the friend's own. A friend that cannot be reached or no longer takes this server for a friend is told in words. The web app has a Friends section for it, shown only when there is a friend to browse. A listener plays it with `GET /friends/{friend}/tracks/{id}/stream` and sees its covers with `GET /friends/{friend}/albums/{id}/cover`, which accept the access token in the query like the local ones: this server asks the friend with a signed request, forwards `Range` and the conditional headers, and passes on only audio (or a JPEG for a cover) with `Content-Type`, `Content-Length`, `Content-Range`, `Accept-Ranges`, `Last-Modified` and `ETag`, so the friend sees this server and never the listener, and a friend cannot make this server serve anything else. A friend's song plays in the same player as the others but is never reported as a listen and does not feed taste. The admin area has a Federation section for all of it.
|
||||
|
||||
- **Favourites.** `PUT /me/favorites/{kind}/{id}` marks a song, an album or an artist (`kind` is `tracks`, `albums` or `artists`) as a favourite and `DELETE` takes it back; `GET /me/favorites/{kind}` lists them, the newest first, and `GET /me/favorites/ids` gives every id for the hearts of a list. They are yours alone: never shown to a friend and never sent anywhere. Apps that speak OpenSubsonic see them as starred things.
|
||||
- **Favourites.** `PUT /me/favorites/{kind}/{id}` marks a song, an album or an artist (`kind` is `tracks`, `albums` or `artists`) as a favourite and `DELETE` takes it back; `GET /me/favorites/{kind}` lists them, the newest first, and `GET /me/favorites/ids` gives every id for the hearts of a list. They are yours alone: never shown to a friend and never sent anywhere. The web app has a heart on every song, album and artist (and in the player) and a Favourites page. Apps that speak OpenSubsonic see them as starred things.
|
||||
- **Other apps.** Apps that speak OpenSubsonic (Symfonium, Feishin, Amperfy, Supersonic and others) can browse, search, play, show covers, use your playlists and report what you listened to, with a password of their own for each app (see [Other apps](#other-apps-opensubsonic)).
|
||||
|
||||
## What is not there yet
|
||||
|
|
|
|||
59
web/src/api/favorites.ts
Normal file
59
web/src/api/favorites.ts
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
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}`] })
|
||||
},
|
||||
})
|
||||
}
|
||||
64
web/src/components/FavoriteButton.test.tsx
Normal file
64
web/src/components/FavoriteButton.test.tsx
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { render, screen } 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 FavoriteButton from './FavoriteButton'
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.spyOn(navigator, 'language', 'get').mockReturnValue('en-US')
|
||||
await initI18n()
|
||||
})
|
||||
|
||||
function setup(ids = { artists: [] as number[], albums: [] as number[], tracks: [] as number[] }, over: MockRoutes = {}) {
|
||||
let current = ids
|
||||
const mocked = mockFetch({
|
||||
'GET /api/v1/me/favorites/ids': () => current,
|
||||
'PUT /api/v1/me/favorites/tracks/7': () => {
|
||||
current = { ...current, tracks: [7, ...current.tracks] }
|
||||
return new Response(null, { status: 204 })
|
||||
},
|
||||
'DELETE /api/v1/me/favorites/tracks/7': () => {
|
||||
current = { ...current, tracks: current.tracks.filter((x) => x !== 7) }
|
||||
return new Response(null, { status: 204 })
|
||||
},
|
||||
...over,
|
||||
})
|
||||
render(
|
||||
<QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } })}>
|
||||
<FavoriteButton kind="tracks" id={7} />
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
return mocked
|
||||
}
|
||||
|
||||
test('a song that is not a favourite has a heart that adds it', async () => {
|
||||
const { calls } = setup()
|
||||
const button = await screen.findByRole('button', { name: 'Add to favourites' })
|
||||
expect(button).toHaveAttribute('aria-pressed', 'false')
|
||||
await userEvent.click(button)
|
||||
expect(await screen.findByRole('button', { name: 'Remove from favourites' })).toHaveAttribute('aria-pressed', 'true')
|
||||
expect(calls.some((c) => c.key === 'PUT /api/v1/me/favorites/tracks/7')).toBe(true)
|
||||
})
|
||||
|
||||
test('a favourite has a filled heart that takes it back', async () => {
|
||||
const { calls } = setup({ artists: [], albums: [], tracks: [7] })
|
||||
const button = await screen.findByRole('button', { name: 'Remove from favourites' })
|
||||
expect(button).toHaveAttribute('aria-pressed', 'true')
|
||||
expect(button.querySelector('svg')).toHaveAttribute('fill', 'currentColor')
|
||||
await userEvent.click(button)
|
||||
expect(await screen.findByRole('button', { name: 'Add to favourites' })).toHaveAttribute('aria-pressed', 'false')
|
||||
expect(calls.some((c) => c.key === 'DELETE /api/v1/me/favorites/tracks/7')).toBe(true)
|
||||
})
|
||||
|
||||
test('the heart changes before the server answers, and goes back if it refuses', async () => {
|
||||
setup(undefined, { 'PUT /api/v1/me/favorites/tracks/7': () => apiError(404, 'track_not_found') })
|
||||
await userEvent.click(await screen.findByRole('button', { name: 'Add to favourites' }))
|
||||
expect(await screen.findByRole('button', { name: 'Add to favourites' })).toHaveAttribute('aria-pressed', 'false')
|
||||
})
|
||||
|
||||
test('another song being a favourite does not fill this heart', async () => {
|
||||
setup({ artists: [7], albums: [7], tracks: [8] })
|
||||
expect(await screen.findByRole('button', { name: 'Add to favourites' })).toHaveAttribute('aria-pressed', 'false')
|
||||
})
|
||||
30
web/src/components/FavoriteButton.tsx
Normal file
30
web/src/components/FavoriteButton.tsx
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
import { Heart } from 'lucide-react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useIsFavorite, useSetFavorite, type FavoriteKind } from '@/api/favorites'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
interface Props {
|
||||
kind: FavoriteKind
|
||||
id: number
|
||||
className?: string
|
||||
}
|
||||
|
||||
/** A heart that marks a song, an album or an artist of this server as a favourite, and takes it back. */
|
||||
export default function FavoriteButton({ kind, id, className }: Props) {
|
||||
const { t } = useTranslation()
|
||||
const on = useIsFavorite(kind, id)
|
||||
const set = useSetFavorite(kind, id)
|
||||
return (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className={className}
|
||||
aria-pressed={on}
|
||||
aria-label={t(on ? 'favorites.remove' : 'favorites.add')}
|
||||
onClick={() => set.mutate(!on)}
|
||||
>
|
||||
<Heart aria-hidden="true" fill={on ? 'currentColor' : 'none'} className={cn(on && 'text-primary')} />
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
|
@ -1,6 +1,7 @@
|
|||
import type { Track } from '@/api/catalog'
|
||||
import { currentTrack, usePlayer } from '@/player/store'
|
||||
import AddToPlaylist from './AddToPlaylist'
|
||||
import FavoriteButton from './FavoriteButton'
|
||||
import TrackRow from './TrackRow'
|
||||
|
||||
/** The songs of a list. Clicking one plays the whole list from that song. */
|
||||
|
|
@ -20,7 +21,12 @@ export default function TrackList({ tracks }: { tracks: Track[] }) {
|
|||
index={i}
|
||||
active={track.id === playingId}
|
||||
onPlay={() => playTracks(tracks, i)}
|
||||
trailing={<AddToPlaylist track={track} />}
|
||||
trailing={
|
||||
<>
|
||||
<FavoriteButton kind="tracks" id={track.id} />
|
||||
<AddToPlaylist track={track} />
|
||||
</>
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import { Link } from 'react-router-dom'
|
|||
import { useFriends } from '@/api/friends'
|
||||
import { usePeaks } from '@/api/peaks'
|
||||
import Cover from '@/components/Cover'
|
||||
import FavoriteButton from '@/components/FavoriteButton'
|
||||
import FriendChip from '@/components/FriendChip'
|
||||
import FullscreenButton from '@/components/FullscreenButton'
|
||||
import Scrubber from '@/components/Scrubber'
|
||||
|
|
@ -115,9 +116,12 @@ export default function NowPlaying() {
|
|||
|
||||
<div className="flex min-w-0 flex-[1_1_380px] flex-col gap-5 sm:gap-7">
|
||||
<div className="flex flex-col gap-2">
|
||||
<DialogTitle className="text-3xl leading-tight font-extrabold tracking-tight sm:text-4xl md:text-6xl">
|
||||
{track.title}
|
||||
</DialogTitle>
|
||||
<div className="flex items-start gap-3">
|
||||
<DialogTitle className="min-w-0 text-3xl leading-tight font-extrabold tracking-tight sm:text-4xl md:text-6xl">
|
||||
{track.title}
|
||||
</DialogTitle>
|
||||
{track.friend === undefined && <FavoriteButton kind="tracks" id={track.id} className="size-11 flex-none text-muted-foreground" />}
|
||||
</div>
|
||||
<p className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xl font-semibold">
|
||||
{track.artists.length === 0
|
||||
? '—'
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ import { cn } from '@/lib/utils'
|
|||
/** The pages the Home tab leads to (Home itself ends the list of them with links to Discover and, for an admin, Requests). */
|
||||
const HOME = ['/discover', '/requests']
|
||||
/** The pages the Library tab leads to: it is the current tab on all of them. */
|
||||
const LIBRARY = ['/library', '/artists', '/albums', '/songs', '/playlists', '/smart-playlists', '/mixes', '/history', '/stats', '/import']
|
||||
const LIBRARY = ['/library', '/artists', '/albums', '/songs', '/favorites', '/playlists', '/smart-playlists', '/mixes', '/history', '/stats', '/import']
|
||||
const MORE = ['/more', '/settings', '/admin']
|
||||
|
||||
const under = (path: string, prefixes: string[]) => prefixes.some((p) => path === p || path.startsWith(`${p}/`))
|
||||
|
|
|
|||
|
|
@ -380,6 +380,15 @@ test('a track of this server has no note about a friend in the full-screen playe
|
|||
expect(within(dialog).queryByText(/passes through your server/)).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('the full-screen player has a heart for a song of this server, and none for a friend’s', async () => {
|
||||
act(() => usePlayer.getState().playTracks([a]))
|
||||
renderBar()
|
||||
const { dialog } = await openNowPlaying()
|
||||
expect(await within(dialog).findByRole('button', { name: 'Add to favourites' })).toBeInTheDocument()
|
||||
act(() => usePlayer.getState().playTracks([theirs(1)]))
|
||||
await vi.waitFor(() => expect(within(dialog).queryByRole('button', { name: /favourites/ })).not.toBeInTheDocument())
|
||||
})
|
||||
|
||||
test('on a phone the queue button takes me to what comes next', async () => {
|
||||
const scroll = vi.fn()
|
||||
Element.prototype.scrollIntoView = scroll
|
||||
|
|
@ -393,14 +402,28 @@ test('on a phone the queue button takes me to what comes next', async () => {
|
|||
|
||||
test('a local list does not mark a row because a friend’s track with the same id is playing', () => {
|
||||
act(() => usePlayer.getState().playTracks([theirs(1)]))
|
||||
mockFetch({ 'GET /api/v1/me/favorites/ids': () => ({ artists: [], albums: [], tracks: [] }) })
|
||||
render(
|
||||
<MemoryRouter>
|
||||
<TrackList tracks={[a]} />
|
||||
</MemoryRouter>,
|
||||
<QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>
|
||||
<MemoryRouter>
|
||||
<TrackList tracks={[a]} />
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
expect(screen.getByRole('button', { name: /Song 1/ })).not.toHaveAttribute('aria-current')
|
||||
})
|
||||
|
||||
test('the bar has a heart for a song of this server, and none for a friend’s', async () => {
|
||||
act(() => usePlayer.getState().playTracks([a]))
|
||||
const mine = renderBar()
|
||||
expect(await screen.findByRole('button', { name: 'Add to favourites' })).toBeInTheDocument()
|
||||
mine.unmount()
|
||||
act(() => usePlayer.getState().playTracks([theirs(1)]))
|
||||
renderBar()
|
||||
expect(await screen.findByLabelText('From Anna’s server')).toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: /favourites/ })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('the play button is round, and teal for this server’s music', () => {
|
||||
act(() => usePlayer.getState().playTracks([a]))
|
||||
renderBar()
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import { useEffect } from 'react'
|
|||
import { useTranslation } from 'react-i18next'
|
||||
import { Link } from 'react-router-dom'
|
||||
import Cover from '@/components/Cover'
|
||||
import FavoriteButton from '@/components/FavoriteButton'
|
||||
import FriendChip from '@/components/FriendChip'
|
||||
import FullscreenButton from '@/components/FullscreenButton'
|
||||
import Scrubber from '@/components/Scrubber'
|
||||
|
|
@ -107,6 +108,7 @@ export default function PlayerBar() {
|
|||
<PlayerSeek track={track} />
|
||||
|
||||
<div className="player-extras flex items-center justify-end max-sm:hidden">
|
||||
{track && track.friend === undefined && <FavoriteButton kind="tracks" id={track.id} className="size-11 text-muted-foreground" />}
|
||||
<Visualizer size="bar" friend={track?.friend !== undefined} className="mr-3 h-10 w-36 max-lg:hidden" />
|
||||
<VolumeControl />
|
||||
<FullscreenButton />
|
||||
|
|
|
|||
|
|
@ -28,7 +28,7 @@ function renderSidebar(friends: { id: number; name: string }[] = [], path = '/al
|
|||
|
||||
test('the menu has a link for each page, and the page that is open is the current one', () => {
|
||||
const nav = renderSidebar()
|
||||
for (const name of ['Home', 'Search', 'Discover', 'Artists', 'Albums', 'Songs', 'Mixes', 'Playlists', 'Smart playlists', 'History', 'Statistics', 'Import', 'Admin', 'Settings']) {
|
||||
for (const name of ['Home', 'Search', 'Discover', 'Artists', 'Albums', 'Songs', 'Favourites', 'Mixes', 'Playlists', 'Smart playlists', 'History', 'Statistics', 'Import', 'Admin', 'Settings']) {
|
||||
expect(within(nav).getByRole('link', { name })).toBeInTheDocument()
|
||||
}
|
||||
expect(within(nav).getByRole('link', { name: 'Albums' })).toHaveAttribute('aria-current', 'page')
|
||||
|
|
@ -157,7 +157,7 @@ test('the links are in groups, in the order of what you do: find, the library, y
|
|||
await within(nav).findByRole('link', { name: 'Friends' })
|
||||
expect(names(nav)).toEqual([
|
||||
'Home', 'Search', 'Discover', 'Requests',
|
||||
'Artists', 'Albums', 'Songs', 'Playlists', 'Smart playlists', 'Mixes',
|
||||
'Artists', 'Albums', 'Songs', 'Favourites', 'Playlists', 'Smart playlists', 'Mixes',
|
||||
'History', 'Statistics', 'Import',
|
||||
'Friends',
|
||||
'Settings', 'Admin',
|
||||
|
|
@ -167,7 +167,7 @@ test('the links are in groups, in the order of what you do: find, the library, y
|
|||
test('the library and the listening have a quiet heading, and the groups that explain themselves have none', () => {
|
||||
const nav = renderSidebar()
|
||||
const library = within(nav).getByRole('list', { name: 'Library' })
|
||||
expect(within(library).getAllByRole('link').map((a) => a.textContent)).toEqual(['Artists', 'Albums', 'Songs', 'Playlists', 'Smart playlists', 'Mixes'])
|
||||
expect(within(library).getAllByRole('link').map((a) => a.textContent)).toEqual(['Artists', 'Albums', 'Songs', 'Favourites', 'Playlists', 'Smart playlists', 'Mixes'])
|
||||
const listening = within(nav).getByRole('list', { name: 'Your listening' })
|
||||
expect(within(listening).getAllByRole('link').map((a) => a.textContent)).toEqual(['History', 'Statistics', 'Import'])
|
||||
// The headings are words, not links, and not headings of the page.
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { useState } from 'react'
|
||||
import { Blend, ChartNoAxesColumn, Compass, Disc3, History, House, Inbox, ListMusic, MicVocal, Music, PanelLeftClose, PanelLeftOpen, Search, Settings, ShieldCheck, Upload, Users, WandSparkles } from 'lucide-react'
|
||||
import { Blend, ChartNoAxesColumn, Compass, Disc3, Heart, History, House, Inbox, ListMusic, MicVocal, Music, PanelLeftClose, PanelLeftOpen, Search, Settings, ShieldCheck, Upload, Users, WandSparkles } from 'lucide-react'
|
||||
import type { LucideIcon } from 'lucide-react'
|
||||
import { NavLink } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
|
@ -43,6 +43,7 @@ const GROUPS: Group[] = [
|
|||
{ to: '/artists', key: 'nav.artists', icon: MicVocal },
|
||||
{ to: '/albums', key: 'nav.albums', icon: Disc3 },
|
||||
{ to: '/songs', key: 'nav.songs', icon: Music },
|
||||
{ to: '/favorites', key: 'nav.favorites', icon: Heart },
|
||||
{ to: '/playlists', key: 'nav.playlists', icon: ListMusic },
|
||||
{ to: '/smart-playlists', key: 'nav.smartPlaylists', icon: WandSparkles },
|
||||
{ to: '/mixes', key: 'nav.mixes', icon: Blend },
|
||||
|
|
|
|||
|
|
@ -27,7 +27,8 @@
|
|||
"collapse": "Collapse menu",
|
||||
"expand": "Expand menu",
|
||||
"tabs": "Tabs",
|
||||
"stats": "Statistics"
|
||||
"stats": "Statistics",
|
||||
"favorites": "Favourites"
|
||||
},
|
||||
"common": {
|
||||
"loading": "Loading",
|
||||
|
|
@ -105,6 +106,11 @@
|
|||
"copied": "Copied",
|
||||
"done": "Done"
|
||||
},
|
||||
"favorites": {
|
||||
"add": "Add to favourites",
|
||||
"remove": "Remove from favourites",
|
||||
"none": "Nothing here yet. Press the heart on a song, an album or an artist to keep it here."
|
||||
},
|
||||
"settings": {
|
||||
"account": "Account",
|
||||
"admin": "Admin",
|
||||
|
|
|
|||
|
|
@ -27,7 +27,8 @@
|
|||
"collapse": "Comprimi il menu",
|
||||
"expand": "Espandi il menu",
|
||||
"tabs": "Schede",
|
||||
"stats": "Statistiche"
|
||||
"stats": "Statistiche",
|
||||
"favorites": "Preferiti"
|
||||
},
|
||||
"common": {
|
||||
"loading": "Caricamento",
|
||||
|
|
@ -105,6 +106,11 @@
|
|||
"copied": "Copiata",
|
||||
"done": "Fatto"
|
||||
},
|
||||
"favorites": {
|
||||
"add": "Aggiungi ai preferiti",
|
||||
"remove": "Togli dai preferiti",
|
||||
"none": "Ancora niente. Premi il cuore su un brano, un album o un artista per tenerlo qui."
|
||||
},
|
||||
"settings": {
|
||||
"account": "Account",
|
||||
"admin": "Admin",
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import { Link, useParams } from 'react-router-dom'
|
|||
import { useAlbum, useTrackList } from '@/api/catalog'
|
||||
import { ApiError } from '@/api/client'
|
||||
import Cover from '@/components/Cover'
|
||||
import FavoriteButton from '@/components/FavoriteButton'
|
||||
import LoadMore from '@/components/LoadMore'
|
||||
import { EmptyMessage, ErrorMessage, Loading } from '@/components/Status'
|
||||
import TrackList from '@/components/TrackList'
|
||||
|
|
@ -56,11 +57,12 @@ function AlbumView({ id }: { id: number }) {
|
|||
</div>
|
||||
</header>
|
||||
|
||||
<div>
|
||||
<div className="flex items-center gap-3">
|
||||
<Button className="h-12 gap-2 rounded-md px-6" disabled={items.length === 0} onClick={() => playTracks(items, 0)}>
|
||||
<Play />
|
||||
{t('player.play')}
|
||||
</Button>
|
||||
<FavoriteButton kind="albums" id={a.id} className="size-12" />
|
||||
</div>
|
||||
|
||||
{tracks.isError ? (
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import { useParams } from 'react-router-dom'
|
|||
import { useAlbumList, useArtist, useTrackList } from '@/api/catalog'
|
||||
import { ApiError } from '@/api/client'
|
||||
import ArtistPhoto from '@/components/ArtistPhoto'
|
||||
import FavoriteButton from '@/components/FavoriteButton'
|
||||
import { AlbumCard, CARD_GRID } from '@/components/cards'
|
||||
import LidarrButton from '@/components/LidarrButton'
|
||||
import LoadMore from '@/components/LoadMore'
|
||||
|
|
@ -52,11 +53,12 @@ function ArtistView({ id }: { id: number }) {
|
|||
{t('artist.albumCount', { count: a.album_count })} · {t('artist.songCount', { count: a.track_count })}
|
||||
</p>
|
||||
{!nothingHere && (
|
||||
<div>
|
||||
<div className="flex items-center gap-3">
|
||||
<Button className="h-12 gap-2 rounded-md px-6" disabled={songs.length === 0} onClick={() => playTracks(songs, 0)}>
|
||||
<Play />
|
||||
{t('player.play')}
|
||||
</Button>
|
||||
<FavoriteButton kind="artists" id={a.id} className="size-12" />
|
||||
</div>
|
||||
)}
|
||||
<LidarrButton artist={{ id: a.id, name: a.name }} check />
|
||||
|
|
|
|||
89
web/src/pages/FavoritesPage.test.tsx
Normal file
89
web/src/pages/FavoritesPage.test.tsx
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
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 { initI18n } from '@/i18n'
|
||||
import { apiError, mockFetch, type MockRoutes } from '@/test/mockFetch'
|
||||
import FavoritesPage from './FavoritesPage'
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.spyOn(navigator, 'language', 'get').mockReturnValue('en-US')
|
||||
await initI18n()
|
||||
})
|
||||
|
||||
const track = { id: 7, title: 'Karma Police', duration_ms: 264000, track_no: 2, disc_no: 1, album: { id: 3, title: 'OK Computer' }, artists: [{ id: 1, name: 'Radiohead' }], format: 'flac', replay_gain: null }
|
||||
const album = { id: 3, title: 'OK Computer', artist: { id: 1, name: 'Radiohead' }, track_count: 12, duration_ms: 3200000 }
|
||||
const artist = { id: 1, name: 'Radiohead', album_count: 9, track_count: 90 }
|
||||
const page = (items: object[]) => ({ items, total: items.length, limit: 50, offset: 0 })
|
||||
const ids = (t: number[], a: number[], r: number[]) => ({ tracks: t, albums: a, artists: r })
|
||||
|
||||
function setup(routes: MockRoutes = {}) {
|
||||
const mocked = mockFetch({
|
||||
'GET /api/v1/me/favorites/tracks': () => page([track]),
|
||||
'GET /api/v1/me/favorites/albums': () => page([album]),
|
||||
'GET /api/v1/me/favorites/artists': () => page([artist]),
|
||||
'GET /api/v1/me/favorites/ids': () => ids([7], [3], [1]),
|
||||
...routes,
|
||||
})
|
||||
render(
|
||||
<QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } })}>
|
||||
<MemoryRouter>
|
||||
<FavoritesPage />
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
return mocked
|
||||
}
|
||||
|
||||
test('it shows the songs, the albums and the artists that are favourites, each in its own part', async () => {
|
||||
setup()
|
||||
expect(screen.getByRole('heading', { level: 1, name: 'Favourites' })).toBeInTheDocument()
|
||||
const songs = await screen.findByRole('region', { name: 'Songs' })
|
||||
expect(await within(songs).findByText('Karma Police')).toBeInTheDocument()
|
||||
const albums = await screen.findByRole('region', { name: 'Albums' })
|
||||
expect(await within(albums).findByRole('link', { name: /OK Computer/ })).toHaveAttribute('href', '/albums/3')
|
||||
const artists = await screen.findByRole('region', { name: 'Artists' })
|
||||
expect(await within(artists).findByRole('link', { name: /Radiohead/ })).toHaveAttribute('href', '/artists/1')
|
||||
})
|
||||
|
||||
test('a part with nothing in it is left out', async () => {
|
||||
setup({ 'GET /api/v1/me/favorites/albums': () => page([]), 'GET /api/v1/me/favorites/artists': () => page([]) })
|
||||
await screen.findByRole('region', { name: 'Songs' })
|
||||
expect(screen.queryByRole('region', { name: 'Albums' })).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('region', { name: 'Artists' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('with no favourites at all it says how to make one', async () => {
|
||||
setup({
|
||||
'GET /api/v1/me/favorites/tracks': () => page([]),
|
||||
'GET /api/v1/me/favorites/albums': () => page([]),
|
||||
'GET /api/v1/me/favorites/artists': () => page([]),
|
||||
'GET /api/v1/me/favorites/ids': () => ids([], [], []),
|
||||
})
|
||||
expect(await screen.findByText(/Nothing here yet/)).toBeInTheDocument()
|
||||
expect(screen.queryByRole('region')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('taking a song back removes it from the list', async () => {
|
||||
let songs = [track]
|
||||
setup({
|
||||
'GET /api/v1/me/favorites/tracks': () => page(songs),
|
||||
'DELETE /api/v1/me/favorites/tracks/7': () => {
|
||||
songs = []
|
||||
return new Response(null, { status: 204 })
|
||||
},
|
||||
})
|
||||
await userEvent.click(await screen.findByRole('button', { name: 'Remove from favourites' }))
|
||||
expect(await screen.findByRole('region', { name: 'Albums' })).toBeInTheDocument()
|
||||
await vi.waitFor(() => expect(screen.queryByRole('region', { name: 'Songs' })).not.toBeInTheDocument())
|
||||
})
|
||||
|
||||
test('a list that cannot be read has a way to try again', async () => {
|
||||
let fail = true
|
||||
setup({ 'GET /api/v1/me/favorites/tracks': () => (fail ? apiError(500, 'internal', 'x') : page([track])) })
|
||||
const retry = await screen.findByRole('button', { name: 'Try again' })
|
||||
fail = false
|
||||
await userEvent.click(retry)
|
||||
expect(await screen.findByText('Karma Police')).toBeInTheDocument()
|
||||
})
|
||||
65
web/src/pages/FavoritesPage.tsx
Normal file
65
web/src/pages/FavoritesPage.tsx
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
import { useTranslation } from 'react-i18next'
|
||||
import { usePagedList, type Album, type Artist, type Track } from '@/api/catalog'
|
||||
import { AlbumCard, ArtistCard, CARD_GRID } from '@/components/cards'
|
||||
import LoadMore from '@/components/LoadMore'
|
||||
import PageTitle from '@/components/PageTitle'
|
||||
import Section from '@/components/Section'
|
||||
import { EmptyMessage, ErrorMessage, Loading } from '@/components/Status'
|
||||
import TrackList from '@/components/TrackList'
|
||||
|
||||
/** What a person marked with a heart: the songs, the albums and the artists, newest first. A part with nothing is not shown. */
|
||||
export default function FavoritesPage() {
|
||||
const { t } = useTranslation()
|
||||
const tracks = usePagedList<Track>('/me/favorites/tracks', {})
|
||||
const albums = usePagedList<Album>('/me/favorites/albums', {})
|
||||
const artists = usePagedList<Artist>('/me/favorites/artists', {})
|
||||
const all = [tracks, albums, artists]
|
||||
const failed = all.find((q) => q.isError)
|
||||
const empty = all.every((q) => q.data?.total === 0)
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-10">
|
||||
<PageTitle>{t('nav.favorites')}</PageTitle>
|
||||
{failed ? (
|
||||
<ErrorMessage error={failed.error} onRetry={() => all.forEach((q) => q.isError && void q.refetch())} />
|
||||
) : all.some((q) => q.isPending) ? (
|
||||
<Loading />
|
||||
) : empty ? (
|
||||
<EmptyMessage>{t('favorites.none')}</EmptyMessage>
|
||||
) : (
|
||||
<>
|
||||
{(tracks.data?.total ?? 0) > 0 && (
|
||||
<Section title={t('nav.songs')}>
|
||||
<TrackList tracks={tracks.data?.items ?? []} />
|
||||
<LoadMore query={tracks} />
|
||||
</Section>
|
||||
)}
|
||||
{(albums.data?.total ?? 0) > 0 && (
|
||||
<Section title={t('nav.albums')}>
|
||||
<ul className={CARD_GRID}>
|
||||
{(albums.data?.items ?? []).map((album) => (
|
||||
<li key={album.id}>
|
||||
<AlbumCard album={album} />
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<LoadMore query={albums} />
|
||||
</Section>
|
||||
)}
|
||||
{(artists.data?.total ?? 0) > 0 && (
|
||||
<Section title={t('nav.artists')}>
|
||||
<ul className={CARD_GRID}>
|
||||
{(artists.data?.items ?? []).map((artist) => (
|
||||
<li key={artist.id}>
|
||||
<ArtistCard artist={artist} />
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<LoadMore query={artists} />
|
||||
</Section>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
@ -24,6 +24,7 @@ test('Library is a list of the places of the music, each a row that leads there'
|
|||
['Artists', '/artists'],
|
||||
['Albums', '/albums'],
|
||||
['Songs', '/songs'],
|
||||
['Favourites', '/favorites'],
|
||||
['Playlists', '/playlists'],
|
||||
['Smart playlists', '/smart-playlists'],
|
||||
['Mixes', '/mixes'],
|
||||
|
|
|
|||
|
|
@ -14,6 +14,7 @@ export default function LibraryPage() {
|
|||
{ to: '/artists', label: t('nav.artists') },
|
||||
{ to: '/albums', label: t('nav.albums') },
|
||||
{ to: '/songs', label: t('nav.songs') },
|
||||
{ to: '/favorites', label: t('nav.favorites') },
|
||||
{ to: '/playlists', label: t('nav.playlists') },
|
||||
{ to: '/smart-playlists', label: t('nav.smartPlaylists') },
|
||||
{ to: '/mixes', label: t('nav.mixes') },
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@ import {
|
|||
type Playlist,
|
||||
type PlaylistItem,
|
||||
} from '@/api/playlists'
|
||||
import FavoriteButton from '@/components/FavoriteButton'
|
||||
import MixCover from '@/components/MixCover'
|
||||
import { EmptyMessage, ErrorMessage, Loading } from '@/components/Status'
|
||||
import SuggestName from '@/components/SuggestName'
|
||||
|
|
@ -136,6 +137,7 @@ function PlaylistView({ id }: { id: number }) {
|
|||
onPlay={() => play(row)}
|
||||
trailing={
|
||||
<div className="flex flex-none items-center pr-2">
|
||||
{row.available && <FavoriteButton kind="tracks" id={row.track.id} />}
|
||||
<Button variant="ghost" size="icon" aria-label={t('playlists.moveUp')} disabled={busy || i === 0}
|
||||
onClick={() => move.mutate({ id, item: row.id, position: i - 1 })}>
|
||||
<ArrowUp />
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue