From a93260af05f8966bc5e4504018f5782521e61ad4 Mon Sep 17 00:00:00 2001 From: tgiachi Date: Mon, 16 Nov 2026 10:56:12 +0100 Subject: [PATCH] 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 --- README.md | 2 +- web/src/api/favorites.ts | 59 ++++++++++++++ web/src/components/FavoriteButton.test.tsx | 64 ++++++++++++++++ web/src/components/FavoriteButton.tsx | 30 ++++++++ web/src/components/TrackList.tsx | 8 +- web/src/components/layout/NowPlaying.tsx | 10 ++- web/src/components/layout/PhoneTabs.tsx | 2 +- web/src/components/layout/Player.test.tsx | 29 ++++++- web/src/components/layout/PlayerBar.tsx | 2 + web/src/components/layout/Sidebar.test.tsx | 6 +- web/src/components/layout/Sidebar.tsx | 3 +- web/src/i18n/locales/en.json | 8 +- web/src/i18n/locales/it.json | 8 +- web/src/pages/AlbumPage.tsx | 4 +- web/src/pages/ArtistPage.tsx | 4 +- web/src/pages/FavoritesPage.test.tsx | 89 ++++++++++++++++++++++ web/src/pages/FavoritesPage.tsx | 65 ++++++++++++++++ web/src/pages/LibraryPage.test.tsx | 1 + web/src/pages/LibraryPage.tsx | 1 + web/src/pages/PlaylistPage.tsx | 2 + web/src/pages/pages.test.tsx | 15 ++++ web/src/router.tsx | 1 + 22 files changed, 396 insertions(+), 17 deletions(-) create mode 100644 web/src/api/favorites.ts create mode 100644 web/src/components/FavoriteButton.test.tsx create mode 100644 web/src/components/FavoriteButton.tsx create mode 100644 web/src/pages/FavoritesPage.test.tsx create mode 100644 web/src/pages/FavoritesPage.tsx diff --git a/README.md b/README.md index 223888e..73374ee 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/web/src/api/favorites.ts b/web/src/api/favorites.ts new file mode 100644 index 0000000..936eb9b --- /dev/null +++ b/web/src/api/favorites.ts @@ -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>>() + +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('/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(`/me/favorites/${kind}/${id}`) : api.del(`/me/favorites/${kind}/${id}`)), + onMutate: async (on) => { + await client.cancelQueries({ queryKey: IDS_KEY }) + const before = client.getQueryData(IDS_KEY) + if (before) { + const rest = before[kind].filter((x) => x !== id) + client.setQueryData(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}`] }) + }, + }) +} diff --git a/web/src/components/FavoriteButton.test.tsx b/web/src/components/FavoriteButton.test.tsx new file mode 100644 index 0000000..88a23a3 --- /dev/null +++ b/web/src/components/FavoriteButton.test.tsx @@ -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( + + + , + ) + 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') +}) diff --git a/web/src/components/FavoriteButton.tsx b/web/src/components/FavoriteButton.tsx new file mode 100644 index 0000000..b5012c8 --- /dev/null +++ b/web/src/components/FavoriteButton.tsx @@ -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 ( + + ) +} diff --git a/web/src/components/TrackList.tsx b/web/src/components/TrackList.tsx index 63f6e09..b651d9c 100644 --- a/web/src/components/TrackList.tsx +++ b/web/src/components/TrackList.tsx @@ -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={} + trailing={ + <> + + + + } /> ))} diff --git a/web/src/components/layout/NowPlaying.tsx b/web/src/components/layout/NowPlaying.tsx index f2c57a5..1eff8d3 100644 --- a/web/src/components/layout/NowPlaying.tsx +++ b/web/src/components/layout/NowPlaying.tsx @@ -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() {
- - {track.title} - +
+ + {track.title} + + {track.friend === undefined && } +

{track.artists.length === 0 ? '—' diff --git a/web/src/components/layout/PhoneTabs.tsx b/web/src/components/layout/PhoneTabs.tsx index fdff23a..f8a53c3 100644 --- a/web/src/components/layout/PhoneTabs.tsx +++ b/web/src/components/layout/PhoneTabs.tsx @@ -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}/`)) diff --git a/web/src/components/layout/Player.test.tsx b/web/src/components/layout/Player.test.tsx index 826f1b3..9eb12a8 100644 --- a/web/src/components/layout/Player.test.tsx +++ b/web/src/components/layout/Player.test.tsx @@ -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( - - - , + + + + + , ) 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() diff --git a/web/src/components/layout/PlayerBar.tsx b/web/src/components/layout/PlayerBar.tsx index d479ecf..36a49d5 100644 --- a/web/src/components/layout/PlayerBar.tsx +++ b/web/src/components/layout/PlayerBar.tsx @@ -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() {

+ {track && track.friend === undefined && } diff --git a/web/src/components/layout/Sidebar.test.tsx b/web/src/components/layout/Sidebar.test.tsx index 2ea0619..1dfbe28 100644 --- a/web/src/components/layout/Sidebar.test.tsx +++ b/web/src/components/layout/Sidebar.test.tsx @@ -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. diff --git a/web/src/components/layout/Sidebar.tsx b/web/src/components/layout/Sidebar.tsx index e619677..89846b3 100644 --- a/web/src/components/layout/Sidebar.tsx +++ b/web/src/components/layout/Sidebar.tsx @@ -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 }, diff --git a/web/src/i18n/locales/en.json b/web/src/i18n/locales/en.json index 57e7c28..0895c2d 100644 --- a/web/src/i18n/locales/en.json +++ b/web/src/i18n/locales/en.json @@ -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", diff --git a/web/src/i18n/locales/it.json b/web/src/i18n/locales/it.json index 40c786a..9db85ea 100644 --- a/web/src/i18n/locales/it.json +++ b/web/src/i18n/locales/it.json @@ -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", diff --git a/web/src/pages/AlbumPage.tsx b/web/src/pages/AlbumPage.tsx index f3d878a..a19a69e 100644 --- a/web/src/pages/AlbumPage.tsx +++ b/web/src/pages/AlbumPage.tsx @@ -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 }) {
-
+
+
{tracks.isError ? ( diff --git a/web/src/pages/ArtistPage.tsx b/web/src/pages/ArtistPage.tsx index d1ef35d..7f4fcee 100644 --- a/web/src/pages/ArtistPage.tsx +++ b/web/src/pages/ArtistPage.tsx @@ -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 })}

{!nothingHere && ( -
+
+
)} diff --git a/web/src/pages/FavoritesPage.test.tsx b/web/src/pages/FavoritesPage.test.tsx new file mode 100644 index 0000000..4d966bc --- /dev/null +++ b/web/src/pages/FavoritesPage.test.tsx @@ -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( + + + + + , + ) + 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() +}) diff --git a/web/src/pages/FavoritesPage.tsx b/web/src/pages/FavoritesPage.tsx new file mode 100644 index 0000000..0b673f5 --- /dev/null +++ b/web/src/pages/FavoritesPage.tsx @@ -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('/me/favorites/tracks', {}) + const albums = usePagedList('/me/favorites/albums', {}) + const artists = usePagedList('/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 ( +
+ {t('nav.favorites')} + {failed ? ( + all.forEach((q) => q.isError && void q.refetch())} /> + ) : all.some((q) => q.isPending) ? ( + + ) : empty ? ( + {t('favorites.none')} + ) : ( + <> + {(tracks.data?.total ?? 0) > 0 && ( +
+ + +
+ )} + {(albums.data?.total ?? 0) > 0 && ( +
+
    + {(albums.data?.items ?? []).map((album) => ( +
  • + +
  • + ))} +
+ +
+ )} + {(artists.data?.total ?? 0) > 0 && ( +
+
    + {(artists.data?.items ?? []).map((artist) => ( +
  • + +
  • + ))} +
+ +
+ )} + + )} +
+ ) +} diff --git a/web/src/pages/LibraryPage.test.tsx b/web/src/pages/LibraryPage.test.tsx index 9c96400..b188ff8 100644 --- a/web/src/pages/LibraryPage.test.tsx +++ b/web/src/pages/LibraryPage.test.tsx @@ -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'], diff --git a/web/src/pages/LibraryPage.tsx b/web/src/pages/LibraryPage.tsx index 67bc876..71f9395 100644 --- a/web/src/pages/LibraryPage.tsx +++ b/web/src/pages/LibraryPage.tsx @@ -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') }, diff --git a/web/src/pages/PlaylistPage.tsx b/web/src/pages/PlaylistPage.tsx index 17af43f..803577a 100644 --- a/web/src/pages/PlaylistPage.tsx +++ b/web/src/pages/PlaylistPage.tsx @@ -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={
+ {row.available && }