feat(federation): browse and search a friend's catalogue
A listener can now browse the music that a friend's server shares.
- GET /friends lists the friends both admins agreed to, by id and name; an
address or a key is for the admin only. It is empty while federation is off.
- GET /friends/{friend}/artists, albums and tracks (q, limit, offset,
artist_id, album_id) and the one-item routes: this server asks the friend
with a request signed by its own key and passes the page on. The answer is
read into this API's own types first, so what a friend adds is dropped and
the shape is the one in the spec. Nothing is kept, and the ids are the
friend's own.
- Only the three kinds of thing can be asked, and only the parameters their
routes take: a listener cannot make this server ask a friend for anything
else. The friend's address and what the connection said never reach a
listener.
- A friend that cannot be reached, no longer takes this server for a friend,
is busy or is not there is told in words, never as an error page.
- The client of friends gets a generic signed GET with a size limit.
- The web app has a Friends entry in the menu, shown only when there is a
friend to browse, a list of friends and a page for each with artists,
albums and songs, a search and links from an artist to its albums and from
an album to its songs, in English and Italian.
- OpenAPI paths and schemas, contract test with a friend that is a whole
server, and two real servers checked end to end.
This commit is contained in:
parent
8702ff9786
commit
29bd46c3ba
12 changed files with 2090 additions and 25 deletions
38
web/src/api/friends.ts
Normal file
38
web/src/api/friends.ts
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
import { useQuery } from '@tanstack/react-query'
|
||||
import { api } from './client'
|
||||
import { usePagedList, type Album, type Artist, type ListOptions, type Track } from './catalog'
|
||||
import type { components } from './schema'
|
||||
|
||||
export type Friend = components['schemas']['FriendRef']
|
||||
|
||||
const FRIENDS = ['friends']
|
||||
|
||||
/** The friends whose music can be browsed: their names, never their addresses. Empty while federation is off. */
|
||||
export function useFriends() {
|
||||
return useQuery({
|
||||
queryKey: FRIENDS,
|
||||
queryFn: () => api.get<{ friends: Friend[] }>('/friends'),
|
||||
select: (data) => data.friends,
|
||||
staleTime: 60_000,
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists of what a friend shares. The ids in them are the friend's own, so a list is always asked for together with
|
||||
* the friend, and an artist or an album id only means something for that friend.
|
||||
*/
|
||||
export function useFriendArtists(friend: number, q: string, opts: ListOptions = {}) {
|
||||
return usePagedList<Artist>(`/friends/${friend}/artists`, { q: q || undefined }, opts)
|
||||
}
|
||||
|
||||
export function useFriendAlbums(friend: number, filter: { q?: string; artistId?: number }, opts: ListOptions = {}) {
|
||||
return usePagedList<Album>(`/friends/${friend}/albums`, { q: filter.q || undefined, artist_id: filter.artistId }, opts)
|
||||
}
|
||||
|
||||
export function useFriendTracks(friend: number, filter: { q?: string; artistId?: number; albumId?: number }, opts: ListOptions = {}) {
|
||||
return usePagedList<Track>(
|
||||
`/friends/${friend}/tracks`,
|
||||
{ q: filter.q || undefined, artist_id: filter.artistId, album_id: filter.albumId },
|
||||
opts,
|
||||
)
|
||||
}
|
||||
472
web/src/api/schema.d.ts
vendored
472
web/src/api/schema.d.ts
vendored
|
|
@ -2398,6 +2398,163 @@ export interface paths {
|
|||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/friends": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
/**
|
||||
* The friends whose music can be browsed
|
||||
* @description The friends that both admins agreed to, by name. A listener never sees an address or a key: those are for the
|
||||
* admin (`GET /federation`). Empty while federation is off.
|
||||
*/
|
||||
get: operations["listFriends"];
|
||||
put?: never;
|
||||
post?: never;
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/friends/{friend}/artists": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path: {
|
||||
/** @description The id from `GET /friends`. */
|
||||
friend: number;
|
||||
};
|
||||
cookie?: never;
|
||||
};
|
||||
/**
|
||||
* The artists a friend shares
|
||||
* @description This server asks the friend, with a request signed by its own key, and passes the page on after checking its
|
||||
* shape; nothing is kept. Only what the friend shares is there. `q`, `limit` and `offset` are the same as in
|
||||
* `GET /artists`. A friend that cannot be reached is `502` (`friend_unreachable`); one that no longer takes this
|
||||
* server for a friend is `409` (`friend_gone`).
|
||||
*/
|
||||
get: operations["listFriendArtists"];
|
||||
put?: never;
|
||||
post?: never;
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/friends/{friend}/artists/{id}": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path: {
|
||||
/** @description The id from `GET /friends`. */
|
||||
friend: number;
|
||||
id: components["parameters"]["Id"];
|
||||
};
|
||||
cookie?: never;
|
||||
};
|
||||
/** One artist of a friend */
|
||||
get: operations["getFriendArtist"];
|
||||
put?: never;
|
||||
post?: never;
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/friends/{friend}/albums": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path: {
|
||||
/** @description The id from `GET /friends`. */
|
||||
friend: number;
|
||||
};
|
||||
cookie?: never;
|
||||
};
|
||||
/**
|
||||
* The albums a friend shares
|
||||
* @description Like `GET /friends/{friend}/artists`, for albums; `artist_id` is the friend's own id of an artist.
|
||||
*/
|
||||
get: operations["listFriendAlbums"];
|
||||
put?: never;
|
||||
post?: never;
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/friends/{friend}/albums/{id}": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path: {
|
||||
/** @description The id from `GET /friends`. */
|
||||
friend: number;
|
||||
id: components["parameters"]["Id"];
|
||||
};
|
||||
cookie?: never;
|
||||
};
|
||||
/** One album of a friend */
|
||||
get: operations["getFriendAlbum"];
|
||||
put?: never;
|
||||
post?: never;
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/friends/{friend}/tracks": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path: {
|
||||
/** @description The id from `GET /friends`. */
|
||||
friend: number;
|
||||
};
|
||||
cookie?: never;
|
||||
};
|
||||
/**
|
||||
* The tracks a friend shares
|
||||
* @description Like `GET /friends/{friend}/artists`, for tracks; `artist_id` and `album_id` are the friend's own ids. The ids in
|
||||
* every answer are the friend's, never this server's: a listener keeps the friend and the id together.
|
||||
*/
|
||||
get: operations["listFriendTracks"];
|
||||
put?: never;
|
||||
post?: never;
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/friends/{friend}/tracks/{id}": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path: {
|
||||
/** @description The id from `GET /friends`. */
|
||||
friend: number;
|
||||
id: components["parameters"]["Id"];
|
||||
};
|
||||
cookie?: never;
|
||||
};
|
||||
/** One track of a friend */
|
||||
get: operations["getFriendTrack"];
|
||||
put?: never;
|
||||
post?: never;
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
}
|
||||
export type webhooks = Record<string, never>;
|
||||
export interface components {
|
||||
|
|
@ -3475,6 +3632,14 @@ export interface components {
|
|||
*/
|
||||
bytes: number;
|
||||
};
|
||||
FriendRef: {
|
||||
/**
|
||||
* Format: int64
|
||||
* @description Names the friend in the routes under `/friends`.
|
||||
*/
|
||||
id: number;
|
||||
name: string;
|
||||
};
|
||||
PeerInfo: {
|
||||
name: string;
|
||||
/** @description How many libraries are shared with friends. */
|
||||
|
|
@ -3539,6 +3704,35 @@ export interface components {
|
|||
"application/json": components["schemas"]["Error"];
|
||||
};
|
||||
};
|
||||
/** @description The friend no longer takes this server for a friend (`friend_gone`). */
|
||||
FriendGone: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["Error"];
|
||||
};
|
||||
};
|
||||
/** @description The friend is busy (`friend_busy`). Try again after `Retry-After` seconds. */
|
||||
FriendBusy: {
|
||||
headers: {
|
||||
/** @description Seconds to wait. */
|
||||
"Retry-After"?: number;
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["Error"];
|
||||
};
|
||||
};
|
||||
/** @description The friend could not be reached, or sent something that is not a catalogue page (`friend_unreachable`). */
|
||||
FriendUnreachable: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["Error"];
|
||||
};
|
||||
};
|
||||
/** @description Federation is off on this server, so the route is as good as missing (`not_found`). */
|
||||
FederationOff: {
|
||||
headers: {
|
||||
|
|
@ -7770,4 +7964,282 @@ export interface operations {
|
|||
};
|
||||
};
|
||||
};
|
||||
listFriends: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody?: never;
|
||||
responses: {
|
||||
/** @description The friends, oldest first. */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": {
|
||||
friends: components["schemas"]["FriendRef"][];
|
||||
};
|
||||
};
|
||||
};
|
||||
401: components["responses"]["Unauthorized"];
|
||||
};
|
||||
};
|
||||
listFriendArtists: {
|
||||
parameters: {
|
||||
query?: {
|
||||
/**
|
||||
* @description Case- and accent-insensitive substring of the name or title: `bjork`, `BJORK` and `BJÖRK` all
|
||||
* find `Björk`, and `strasse` finds `Straße`. At most 200 characters.
|
||||
*/
|
||||
q?: components["parameters"]["Q"];
|
||||
/** @description Page size. 50 when absent or 0; values above 200 are lowered to 200. */
|
||||
limit?: components["parameters"]["Limit"];
|
||||
offset?: components["parameters"]["Offset"];
|
||||
};
|
||||
header?: never;
|
||||
path: {
|
||||
/** @description The id from `GET /friends`. */
|
||||
friend: number;
|
||||
};
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody?: never;
|
||||
responses: {
|
||||
/** @description A page of artists. */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["ArtistPage"];
|
||||
};
|
||||
};
|
||||
400: components["responses"]["InvalidInput"];
|
||||
401: components["responses"]["Unauthorized"];
|
||||
/** @description No such friend, or it is not active (`friend_not_found`). */
|
||||
404: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["Error"];
|
||||
};
|
||||
};
|
||||
409: components["responses"]["FriendGone"];
|
||||
429: components["responses"]["FriendBusy"];
|
||||
502: components["responses"]["FriendUnreachable"];
|
||||
};
|
||||
};
|
||||
getFriendArtist: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path: {
|
||||
/** @description The id from `GET /friends`. */
|
||||
friend: number;
|
||||
id: components["parameters"]["Id"];
|
||||
};
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody?: never;
|
||||
responses: {
|
||||
/** @description The artist. */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["Artist"];
|
||||
};
|
||||
};
|
||||
400: components["responses"]["InvalidInput"];
|
||||
401: components["responses"]["Unauthorized"];
|
||||
/** @description No such friend, or it is not active (`friend_not_found`) or the friend has no such artist (`artist_not_found`). */
|
||||
404: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["Error"];
|
||||
};
|
||||
};
|
||||
409: components["responses"]["FriendGone"];
|
||||
429: components["responses"]["FriendBusy"];
|
||||
502: components["responses"]["FriendUnreachable"];
|
||||
};
|
||||
};
|
||||
listFriendAlbums: {
|
||||
parameters: {
|
||||
query?: {
|
||||
/**
|
||||
* @description Case- and accent-insensitive substring of the name or title: `bjork`, `BJORK` and `BJÖRK` all
|
||||
* find `Björk`, and `strasse` finds `Straße`. At most 200 characters.
|
||||
*/
|
||||
q?: components["parameters"]["Q"];
|
||||
/** @description Page size. 50 when absent or 0; values above 200 are lowered to 200. */
|
||||
limit?: components["parameters"]["Limit"];
|
||||
offset?: components["parameters"]["Offset"];
|
||||
artist_id?: components["parameters"]["ArtistId"];
|
||||
};
|
||||
header?: never;
|
||||
path: {
|
||||
/** @description The id from `GET /friends`. */
|
||||
friend: number;
|
||||
};
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody?: never;
|
||||
responses: {
|
||||
/** @description A page of albums. */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["AlbumPage"];
|
||||
};
|
||||
};
|
||||
400: components["responses"]["InvalidInput"];
|
||||
401: components["responses"]["Unauthorized"];
|
||||
/** @description No such friend, or it is not active (`friend_not_found`). */
|
||||
404: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["Error"];
|
||||
};
|
||||
};
|
||||
409: components["responses"]["FriendGone"];
|
||||
429: components["responses"]["FriendBusy"];
|
||||
502: components["responses"]["FriendUnreachable"];
|
||||
};
|
||||
};
|
||||
getFriendAlbum: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path: {
|
||||
/** @description The id from `GET /friends`. */
|
||||
friend: number;
|
||||
id: components["parameters"]["Id"];
|
||||
};
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody?: never;
|
||||
responses: {
|
||||
/** @description The album. */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["Album"];
|
||||
};
|
||||
};
|
||||
400: components["responses"]["InvalidInput"];
|
||||
401: components["responses"]["Unauthorized"];
|
||||
/** @description No such friend, or it is not active (`friend_not_found`) or the friend has no such album (`album_not_found`). */
|
||||
404: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["Error"];
|
||||
};
|
||||
};
|
||||
409: components["responses"]["FriendGone"];
|
||||
429: components["responses"]["FriendBusy"];
|
||||
502: components["responses"]["FriendUnreachable"];
|
||||
};
|
||||
};
|
||||
listFriendTracks: {
|
||||
parameters: {
|
||||
query?: {
|
||||
/**
|
||||
* @description Case- and accent-insensitive substring of the name or title: `bjork`, `BJORK` and `BJÖRK` all
|
||||
* find `Björk`, and `strasse` finds `Straße`. At most 200 characters.
|
||||
*/
|
||||
q?: components["parameters"]["Q"];
|
||||
/** @description Page size. 50 when absent or 0; values above 200 are lowered to 200. */
|
||||
limit?: components["parameters"]["Limit"];
|
||||
offset?: components["parameters"]["Offset"];
|
||||
artist_id?: components["parameters"]["ArtistId"];
|
||||
album_id?: components["parameters"]["AlbumId"];
|
||||
};
|
||||
header?: never;
|
||||
path: {
|
||||
/** @description The id from `GET /friends`. */
|
||||
friend: number;
|
||||
};
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody?: never;
|
||||
responses: {
|
||||
/** @description A page of tracks. */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["TrackPage"];
|
||||
};
|
||||
};
|
||||
400: components["responses"]["InvalidInput"];
|
||||
401: components["responses"]["Unauthorized"];
|
||||
/** @description No such friend, or it is not active (`friend_not_found`). */
|
||||
404: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["Error"];
|
||||
};
|
||||
};
|
||||
409: components["responses"]["FriendGone"];
|
||||
429: components["responses"]["FriendBusy"];
|
||||
502: components["responses"]["FriendUnreachable"];
|
||||
};
|
||||
};
|
||||
getFriendTrack: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path: {
|
||||
/** @description The id from `GET /friends`. */
|
||||
friend: number;
|
||||
id: components["parameters"]["Id"];
|
||||
};
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody?: never;
|
||||
responses: {
|
||||
/** @description The track. */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["Track"];
|
||||
};
|
||||
};
|
||||
400: components["responses"]["InvalidInput"];
|
||||
401: components["responses"]["Unauthorized"];
|
||||
/** @description No such friend, or it is not active (`friend_not_found`) or the friend has no such track (`track_not_found`). */
|
||||
404: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["Error"];
|
||||
};
|
||||
};
|
||||
409: components["responses"]["FriendGone"];
|
||||
429: components["responses"]["FriendBusy"];
|
||||
502: components["responses"]["FriendUnreachable"];
|
||||
};
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -25,6 +25,9 @@ async function renderAt(path: string) {
|
|||
await screen.findByRole('main')
|
||||
}
|
||||
|
||||
/** The menu asks which friends there are; the tests below are about what an admin page asks. */
|
||||
const notFriends = (c: { url: URL }) => c.url.pathname !== '/api/v1/friends'
|
||||
|
||||
function mainNav() {
|
||||
return screen.getByRole('navigation', { name: 'Main' })
|
||||
}
|
||||
|
|
@ -95,7 +98,7 @@ test('someone who is not an admin who opens the jobs address gets a notice and n
|
|||
await renderAt('/admin/jobs')
|
||||
expect(await screen.findByText('Only admins can see this page.')).toBeInTheDocument()
|
||||
await new Promise((r) => setTimeout(r, 30))
|
||||
expect(calls).toHaveLength(0)
|
||||
expect(calls.filter(notFriends)).toHaveLength(0)
|
||||
})
|
||||
|
||||
test('someone who is not an admin who opens the providers address gets a notice and no request', async () => {
|
||||
|
|
@ -104,7 +107,7 @@ test('someone who is not an admin who opens the providers address gets a notice
|
|||
await renderAt('/admin/providers')
|
||||
expect(await screen.findByText('Only admins can see this page.')).toBeInTheDocument()
|
||||
await new Promise((r) => setTimeout(r, 30))
|
||||
expect(calls).toHaveLength(0)
|
||||
expect(calls.filter(notFriends)).toHaveLength(0)
|
||||
})
|
||||
|
||||
test('someone who is not an admin who opens the users address gets a notice and no request', async () => {
|
||||
|
|
@ -113,7 +116,7 @@ test('someone who is not an admin who opens the users address gets a notice and
|
|||
await renderAt('/admin/users')
|
||||
expect(await screen.findByText('Only admins can see this page.')).toBeInTheDocument()
|
||||
await new Promise((r) => setTimeout(r, 30))
|
||||
expect(calls).toHaveLength(0)
|
||||
expect(calls.filter(notFriends)).toHaveLength(0)
|
||||
})
|
||||
|
||||
test('someone who is not an admin who opens the admin address gets a notice and no request', async () => {
|
||||
|
|
|
|||
|
|
@ -1,9 +1,11 @@
|
|||
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 { sessionStore } from '@/auth/session'
|
||||
import { initI18n } from '@/i18n'
|
||||
import { mockFetch } from '@/test/mockFetch'
|
||||
import Sidebar from './Sidebar'
|
||||
|
||||
const KEY = 'sonda.sidebar'
|
||||
|
|
@ -15,11 +17,14 @@ beforeEach(async () => {
|
|||
sessionStore.setState({ status: 'authenticated', user: { id: 1, email: 'tom@example.org', is_admin: true } })
|
||||
})
|
||||
|
||||
function renderSidebar() {
|
||||
function renderSidebar(friends: { id: number; name: string }[] = []) {
|
||||
mockFetch({ 'GET /api/v1/friends': () => ({ friends }) })
|
||||
render(
|
||||
<MemoryRouter initialEntries={['/albums']}>
|
||||
<Sidebar />
|
||||
</MemoryRouter>,
|
||||
<QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>
|
||||
<MemoryRouter initialEntries={['/albums']}>
|
||||
<Sidebar />
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
return screen.getByRole('navigation', { name: 'Main' })
|
||||
}
|
||||
|
|
@ -79,3 +84,14 @@ test('a browser that will not keep it still folds and opens the sidebar', async
|
|||
await userEvent.click(within(nav).getByRole('button', { name: 'Collapse the sidebar' }))
|
||||
expect(nav).toHaveAttribute('data-collapsed', 'true')
|
||||
})
|
||||
|
||||
test('Friends is in the menu only when there is a friend to browse', async () => {
|
||||
const none = renderSidebar()
|
||||
await screen.findByRole('link', { name: 'Albums' })
|
||||
expect(within(none).queryByRole('link', { name: 'Friends' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('with a friend the menu has a Friends link', async () => {
|
||||
const nav = renderSidebar([{ id: 3, name: 'Anna' }])
|
||||
expect(await within(nav).findByRole('link', { name: 'Friends' })).toHaveAttribute('href', '/friends')
|
||||
})
|
||||
|
|
|
|||
|
|
@ -1,14 +1,15 @@
|
|||
import {
|
||||
Compass, Disc3, House, ListMusic, Mic2, Music, PanelLeftClose, PanelLeftOpen, Search, Settings, ShieldCheck, Sparkles, Wand2, type LucideIcon,
|
||||
Compass, Disc3, House, ListMusic, Mic2, Music, PanelLeftClose, PanelLeftOpen, Search, Settings, ShieldCheck, Sparkles, Users, Wand2, type LucideIcon,
|
||||
} from 'lucide-react'
|
||||
import { useState } from 'react'
|
||||
import { NavLink } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useFriends } from '@/api/friends'
|
||||
import { useSession } from '@/auth/session'
|
||||
import Logo from '@/components/Logo'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
const LINKS: { to: string; key: string; icon: LucideIcon; end: boolean; adminOnly: boolean }[] = [
|
||||
const LINKS: { to: string; key: string; icon: LucideIcon; end: boolean; adminOnly: boolean; friends?: boolean }[] = [
|
||||
{ to: '/', key: 'nav.home', icon: House, end: true, adminOnly: false },
|
||||
{ to: '/search', key: 'nav.search', icon: Search, end: false, adminOnly: false },
|
||||
{ to: '/discover', key: 'nav.discover', icon: Compass, end: false, adminOnly: false },
|
||||
|
|
@ -18,6 +19,7 @@ const LINKS: { to: string; key: string; icon: LucideIcon; end: boolean; adminOnl
|
|||
{ to: '/mixes', key: 'nav.mixes', icon: Sparkles, end: false, adminOnly: false },
|
||||
{ to: '/playlists', key: 'nav.playlists', icon: ListMusic, end: false, adminOnly: false },
|
||||
{ to: '/smart-playlists', key: 'nav.smartPlaylists', icon: Wand2, end: false, adminOnly: false },
|
||||
{ to: '/friends', key: 'nav.friends', icon: Users, end: false, adminOnly: false, friends: true },
|
||||
{ to: '/admin', key: 'nav.admin', icon: ShieldCheck, end: false, adminOnly: true },
|
||||
{ to: '/settings', key: 'nav.settings', icon: Settings, end: false, adminOnly: false },
|
||||
]
|
||||
|
|
@ -48,7 +50,9 @@ export default function Sidebar() {
|
|||
const { t } = useTranslation()
|
||||
const { user } = useSession()
|
||||
const [collapsed, setCollapsed] = useState(readCollapsed)
|
||||
const links = LINKS.filter((link) => !link.adminOnly || user?.is_admin)
|
||||
// Friends is in the menu only when there is a friend to browse (federation on, and a friendship both admins agreed to).
|
||||
const hasFriends = (useFriends().data?.length ?? 0) > 0
|
||||
const links = LINKS.filter((link) => (!link.adminOnly || user?.is_admin) && (!link.friends || hasFriends))
|
||||
|
||||
function toggle() {
|
||||
writeCollapsed(!collapsed)
|
||||
|
|
|
|||
|
|
@ -17,6 +17,7 @@
|
|||
"mixes": "Mixes",
|
||||
"playlists": "Playlists",
|
||||
"smartPlaylists": "Smart playlists",
|
||||
"friends": "Friends",
|
||||
"admin": "Admin",
|
||||
"settings": "Settings"
|
||||
},
|
||||
|
|
@ -543,6 +544,36 @@
|
|||
"cancel": "Cancel"
|
||||
}
|
||||
},
|
||||
"friends": {
|
||||
"title": "Friends",
|
||||
"intro": "Music that the admin of another Sonda server shares with this one. It is asked for from their server when you open a page, and nothing is copied here.",
|
||||
"noneYet": "You have no friends yet. An admin makes friends in Admin → Federation.",
|
||||
"musicOf": "Music of {{name}}",
|
||||
"whose": "{{name}}’s server shares this music. It is asked for when you open a page and is never copied here.",
|
||||
"noPlayYet": "For now you can browse this music; playing it comes next.",
|
||||
"searchLabel": "Search the music of {{name}}",
|
||||
"searchPlaceholder": "Artists, albums and songs",
|
||||
"tabsLabel": "Sections of {{name}}’s music",
|
||||
"tabs": {
|
||||
"artists": "Artists",
|
||||
"albums": "Albums",
|
||||
"songs": "Songs"
|
||||
},
|
||||
"albumCount_one": "{{count}} album",
|
||||
"albumCount_other": "{{count}} albums",
|
||||
"songCount_one": "{{count}} song",
|
||||
"songCount_other": "{{count}} songs",
|
||||
"albumsOf": "Albums of {{name}}",
|
||||
"songsOf": "Songs of {{name}}",
|
||||
"showAll": "Show all",
|
||||
"nothing": "{{name}} has not shared anything yet.",
|
||||
"errors": {
|
||||
"friend_unreachable": "{{name}} could not be reached. Try again later.",
|
||||
"friend_gone": "{{name}} no longer takes this server for a friend. An admin can tell you more.",
|
||||
"friend_busy": "{{name}} is busy. Try again in a moment.",
|
||||
"friend_not_found": "This friend is not there any more."
|
||||
}
|
||||
},
|
||||
"home": {
|
||||
"greeting_morning": "Good morning",
|
||||
"greeting_afternoon": "Good afternoon",
|
||||
|
|
|
|||
|
|
@ -17,6 +17,7 @@
|
|||
"mixes": "Mix",
|
||||
"playlists": "Playlist",
|
||||
"smartPlaylists": "Playlist smart",
|
||||
"friends": "Amici",
|
||||
"admin": "Admin",
|
||||
"settings": "Impostazioni"
|
||||
},
|
||||
|
|
@ -543,6 +544,36 @@
|
|||
"cancel": "Annulla"
|
||||
}
|
||||
},
|
||||
"friends": {
|
||||
"title": "Amici",
|
||||
"intro": "Musica che l'admin di un altro server Sonda condivide con questo. Viene chiesta al loro server quando apri una pagina, e qui non si copia nulla.",
|
||||
"noneYet": "Non hai ancora amici. Un admin li crea in Admin → Federazione.",
|
||||
"musicOf": "Musica di {{name}}",
|
||||
"whose": "Questa musica la condivide il server di {{name}}. Viene chiesta quando apri una pagina e qui non viene mai copiata.",
|
||||
"noPlayYet": "Per ora puoi solo sfogliare questa musica; l'ascolto arriva dopo.",
|
||||
"searchLabel": "Cerca nella musica di {{name}}",
|
||||
"searchPlaceholder": "Artisti, album e brani",
|
||||
"tabsLabel": "Sezioni della musica di {{name}}",
|
||||
"tabs": {
|
||||
"artists": "Artisti",
|
||||
"albums": "Album",
|
||||
"songs": "Brani"
|
||||
},
|
||||
"albumCount_one": "{{count}} album",
|
||||
"albumCount_other": "{{count}} album",
|
||||
"songCount_one": "{{count}} brano",
|
||||
"songCount_other": "{{count}} brani",
|
||||
"albumsOf": "Album di {{name}}",
|
||||
"songsOf": "Brani di {{name}}",
|
||||
"showAll": "Mostra tutto",
|
||||
"nothing": "{{name}} non ha ancora condiviso nulla.",
|
||||
"errors": {
|
||||
"friend_unreachable": "{{name}} non è raggiungibile. Riprova più tardi.",
|
||||
"friend_gone": "{{name}} non considera più questo server un amico. Un admin può dirti di più.",
|
||||
"friend_busy": "{{name}} è occupato. Riprova tra un momento.",
|
||||
"friend_not_found": "Questo amico non c'è più."
|
||||
}
|
||||
},
|
||||
"home": {
|
||||
"greeting_morning": "Buongiorno",
|
||||
"greeting_afternoon": "Buon pomeriggio",
|
||||
|
|
|
|||
157
web/src/pages/FriendPage.test.tsx
Normal file
157
web/src/pages/FriendPage.test.tsx
Normal file
|
|
@ -0,0 +1,157 @@
|
|||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { render, screen, waitFor, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { createMemoryRouter, RouterProvider } from 'react-router-dom'
|
||||
import { beforeEach, expect, test, vi } from 'vitest'
|
||||
import { initI18n } from '@/i18n'
|
||||
import { apiError, mockFetch, type MockRoutes } from '@/test/mockFetch'
|
||||
import FriendPage from './FriendPage'
|
||||
|
||||
const artist = (id: number, name: string, albums = 1, tracks = 3) => ({ id, name, album_count: albums, track_count: tracks })
|
||||
const album = (id: number, title: string, by = 'Shared Band') => ({
|
||||
id, title, artist: { id: 1, name: by }, track_count: 10, duration_ms: 2_400_000,
|
||||
})
|
||||
const track = (id: number, title: string) => ({
|
||||
id, title, duration_ms: 195_000, track_no: id, disc_no: 1, album: { id: 7, title: 'Shared Album' }, artists: [{ id: 1, name: 'Shared Band' }], format: 'mp3',
|
||||
})
|
||||
const page = <T,>(items: T[], total = items.length, offset = 0) => ({ items, total, limit: 50, offset })
|
||||
|
||||
function routes(over: MockRoutes = {}): MockRoutes {
|
||||
return {
|
||||
'GET /api/v1/friends': () => ({ friends: [{ id: 3, name: 'Anna' }] }),
|
||||
'GET /api/v1/friends/3/artists': () => page([artist(1, 'Shared Band', 2, 12), artist(2, 'Other Band', 1, 1)]),
|
||||
'GET /api/v1/friends/3/albums': () => page([album(7, 'Shared Album')]),
|
||||
'GET /api/v1/friends/3/tracks': () => page([track(1, 'Shared Song'), track(2, 'Second Song')]),
|
||||
...over,
|
||||
}
|
||||
}
|
||||
|
||||
function renderAt(url = '/friends/3') {
|
||||
const router = createMemoryRouter([{ path: '/friends/:friend', element: <FriendPage /> }], { initialEntries: [url] })
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
render(
|
||||
<QueryClientProvider client={client}>
|
||||
<RouterProvider router={router} />
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
return router
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.spyOn(navigator, 'language', 'get').mockReturnValue('en-US')
|
||||
await initI18n()
|
||||
})
|
||||
|
||||
test('it is headed with the name of the friend and says whose music this is', async () => {
|
||||
mockFetch(routes())
|
||||
renderAt()
|
||||
expect(await screen.findByRole('heading', { level: 1, name: 'Music of Anna' })).toBeInTheDocument()
|
||||
expect(screen.getByText(/Anna’s server shares this music/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('it opens on the artists, with how much each has', async () => {
|
||||
mockFetch(routes())
|
||||
renderAt()
|
||||
expect(await screen.findByRole('tab', { name: 'Artists', selected: true })).toBeInTheDocument()
|
||||
const item = (await screen.findByText('Shared Band')).closest('li') as HTMLElement
|
||||
expect(item).toHaveTextContent('2 albums')
|
||||
expect(item).toHaveTextContent('12 songs')
|
||||
expect(screen.getByText('Other Band')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('an artist leads to its albums, and an album to its songs, with what was chosen said', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { calls } = mockFetch(routes())
|
||||
renderAt()
|
||||
await user.click(await screen.findByRole('button', { name: /Shared Band/ }))
|
||||
expect(await screen.findByRole('tab', { name: 'Albums', selected: true })).toBeInTheDocument()
|
||||
expect(await screen.findByText('Shared Album')).toBeInTheDocument()
|
||||
expect(screen.getByText('Albums of Shared Band')).toBeInTheDocument()
|
||||
expect(calls.find((c) => c.key === 'GET /api/v1/friends/3/albums')?.url.searchParams.get('artist_id')).toBe('1')
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /Shared Album/ }))
|
||||
expect(await screen.findByRole('tab', { name: 'Songs', selected: true })).toBeInTheDocument()
|
||||
expect(await screen.findByText('Shared Song')).toBeInTheDocument()
|
||||
expect(screen.getByText('Songs of Shared Album')).toBeInTheDocument()
|
||||
expect(calls.filter((c) => c.key === 'GET /api/v1/friends/3/tracks').at(-1)?.url.searchParams.get('album_id')).toBe('7')
|
||||
})
|
||||
|
||||
test('a song shows its length and its artists', async () => {
|
||||
mockFetch(routes())
|
||||
renderAt('/friends/3?tab=songs')
|
||||
const row = (await screen.findByText('Shared Song')).closest('li') as HTMLElement
|
||||
expect(row).toHaveTextContent('3:15')
|
||||
expect(row).toHaveTextContent('Shared Band')
|
||||
})
|
||||
|
||||
test('the tabs are chosen with the keyboard and a click, and the choice stays in the address', async () => {
|
||||
const user = userEvent.setup()
|
||||
mockFetch(routes())
|
||||
const router = renderAt()
|
||||
await user.click(await screen.findByRole('tab', { name: 'Songs' }))
|
||||
expect(await screen.findByText('Shared Song')).toBeInTheDocument()
|
||||
expect(router.state.location.search).toContain('tab=songs')
|
||||
screen.getByRole('tab', { name: 'Songs' }).focus()
|
||||
await user.keyboard('{ArrowLeft}')
|
||||
expect(await screen.findByRole('tab', { name: 'Albums', selected: true })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('a search asks the friend once typing stops, and is kept in the address', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { calls } = mockFetch(routes())
|
||||
const router = renderAt()
|
||||
await screen.findByText('Shared Band')
|
||||
await user.type(screen.getByRole('searchbox', { name: 'Search the music of Anna' }), 'other')
|
||||
await waitFor(() => expect(calls.filter((c) => c.key === 'GET /api/v1/friends/3/artists').some((c) => c.url.searchParams.get('q') === 'other')).toBe(true))
|
||||
expect(router.state.location.search).toContain('q=other')
|
||||
// Not once for each letter.
|
||||
expect(calls.filter((c) => c.key === 'GET /api/v1/friends/3/artists' && c.url.searchParams.get('q')).length).toBe(1)
|
||||
})
|
||||
|
||||
test('more of a long list is one click away', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { calls } = mockFetch(
|
||||
routes({
|
||||
'GET /api/v1/friends/3/artists': ({ url }) => {
|
||||
const offset = Number(url.searchParams.get('offset') ?? 0)
|
||||
return offset === 0 ? page([artist(1, 'First Band')], 2, 0) : page([artist(2, 'Second Band')], 2, 1)
|
||||
},
|
||||
}),
|
||||
)
|
||||
renderAt()
|
||||
await screen.findByText('First Band')
|
||||
await user.click(screen.getByRole('button', { name: 'Show more' }))
|
||||
expect(await screen.findByText('Second Band')).toBeInTheDocument()
|
||||
expect(calls.filter((c) => c.key === 'GET /api/v1/friends/3/artists').map((c) => c.url.searchParams.get('offset'))).toEqual(['0', '1'])
|
||||
})
|
||||
|
||||
test('a friend that shares nothing says so', async () => {
|
||||
mockFetch(routes({ 'GET /api/v1/friends/3/artists': () => page([]) }))
|
||||
renderAt()
|
||||
expect(await screen.findByText('Anna has not shared anything yet.')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('a search that finds nothing says what was searched for', async () => {
|
||||
mockFetch(routes({ 'GET /api/v1/friends/3/artists': () => page([]) }))
|
||||
renderAt('/friends/3?q=zzz')
|
||||
expect(await screen.findByText('Nothing matches “zzz”.')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
test.each([
|
||||
['friend_unreachable', 502, 'Anna could not be reached. Try again later.'],
|
||||
['friend_gone', 409, 'Anna no longer takes this server for a friend. An admin can tell you more.'],
|
||||
['friend_busy', 429, 'Anna is busy. Try again in a moment.'],
|
||||
['friend_not_found', 404, 'This friend is not there any more.'],
|
||||
])('a friend that answers %s is said in words, with a way to try again', async (code, status, text) => {
|
||||
mockFetch(routes({ 'GET /api/v1/friends/3/artists': () => apiError(status, code) }))
|
||||
renderAt()
|
||||
const alert = await screen.findByRole('alert')
|
||||
expect(alert).toHaveTextContent(text)
|
||||
expect(within(alert).getByRole('button', { name: 'Try again' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('a friend that is not in the list is not there', async () => {
|
||||
mockFetch(routes({ 'GET /api/v1/friends': () => ({ friends: [] }) }))
|
||||
renderAt()
|
||||
expect(await screen.findByText('This friend is not there any more.')).toBeInTheDocument()
|
||||
})
|
||||
219
web/src/pages/FriendPage.tsx
Normal file
219
web/src/pages/FriendPage.tsx
Normal file
|
|
@ -0,0 +1,219 @@
|
|||
import { useEffect, useRef, useState, type KeyboardEvent } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useParams, useSearchParams } from 'react-router-dom'
|
||||
import { ApiError } from '@/api/client'
|
||||
import { useFriendAlbums, useFriendArtists, useFriends, useFriendTracks } from '@/api/friends'
|
||||
import LoadMore from '@/components/LoadMore'
|
||||
import { EmptyMessage, ErrorMessage, Loading } from '@/components/Status'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { formatTime } from '@/lib/time'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
const TABS = ['artists', 'albums', 'songs'] as const
|
||||
type Tab = (typeof TABS)[number]
|
||||
|
||||
/** Wait this long after the last keystroke before asking the friend. */
|
||||
const DEBOUNCE_MS = 250
|
||||
/** What the friend's server accepts as search text. */
|
||||
const MAX_QUERY_LENGTH = 200
|
||||
|
||||
const parseTab = (value: string | null): Tab => TABS.find((tab) => tab === value) ?? 'artists'
|
||||
const parseId = (value: string | null): number | undefined => {
|
||||
const n = Number(value)
|
||||
return Number.isInteger(n) && n > 0 ? n : undefined
|
||||
}
|
||||
|
||||
/** What went wrong with a friend, in words that name it. Anything not about a friend gets the usual text. */
|
||||
function FriendError({ error, name, onRetry }: { error: unknown; name: string; onRetry(): void }) {
|
||||
const { t, i18n } = useTranslation()
|
||||
const code = error instanceof ApiError ? error.code : ''
|
||||
const key = `friends.errors.${code}`
|
||||
if (!i18n.exists(key)) return <ErrorMessage error={error} onRetry={onRetry} />
|
||||
return (
|
||||
<div role="alert" className="flex flex-col items-start gap-3">
|
||||
<p>{t(key, { name })}</p>
|
||||
<Button variant="outline" onClick={onRetry}>
|
||||
{t('common.retry')}
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const rowClass = 'flex min-h-14 w-full items-center gap-3 rounded-lg px-4 py-2 text-left'
|
||||
|
||||
/**
|
||||
* The music of one friend: its artists, albums and songs, and a search. Everything is asked of the friend's server
|
||||
* when a page is opened, through this one, and nothing is kept. The ids are the friend's own: an artist leads to
|
||||
* its albums, and an album to its songs, by those.
|
||||
*/
|
||||
export default function FriendPage() {
|
||||
const { t } = useTranslation()
|
||||
const { friend: friendParam } = useParams()
|
||||
const friendId = Number(friendParam)
|
||||
const friends = useFriends()
|
||||
const [params, setParams] = useSearchParams()
|
||||
const tab = parseTab(params.get('tab'))
|
||||
const artistId = parseId(params.get('artist'))
|
||||
const albumId = parseId(params.get('album'))
|
||||
const of = params.get('of') ?? ''
|
||||
const [text, setText] = useState(params.get('q') ?? '')
|
||||
const q = Array.from(text.trim()).slice(0, MAX_QUERY_LENGTH).join('')
|
||||
const buttons = useRef<Record<string, HTMLButtonElement | null>>({})
|
||||
|
||||
// The search is kept in the address, but only once typing stops: the friend is asked once, not for every letter.
|
||||
const [typed, setTyped] = useState(q)
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => setTyped(q), DEBOUNCE_MS)
|
||||
return () => clearTimeout(timer)
|
||||
}, [q])
|
||||
useEffect(() => {
|
||||
setParams(
|
||||
(prev) => {
|
||||
const next = new URLSearchParams(prev)
|
||||
if (typed) next.set('q', typed)
|
||||
else next.delete('q')
|
||||
return next
|
||||
},
|
||||
{ replace: true },
|
||||
)
|
||||
}, [typed, setParams])
|
||||
|
||||
const found = friends.data?.find((f) => f.id === friendId)
|
||||
const name = found?.name ?? ''
|
||||
const ready = found !== undefined
|
||||
const artists = useFriendArtists(friendId, typed, { enabled: ready && tab === 'artists' })
|
||||
const albums = useFriendAlbums(friendId, { q: typed, artistId }, { enabled: ready && tab === 'albums' })
|
||||
const songs = useFriendTracks(friendId, { q: typed, artistId, albumId }, { enabled: ready && tab === 'songs' })
|
||||
const query = tab === 'artists' ? artists : tab === 'albums' ? albums : songs
|
||||
|
||||
function go(next: Record<string, string>) {
|
||||
setText('')
|
||||
setTyped('')
|
||||
setParams(next)
|
||||
}
|
||||
|
||||
function onKeyDown(event: KeyboardEvent) {
|
||||
const step = event.key === 'ArrowRight' ? 1 : event.key === 'ArrowLeft' ? -1 : 0
|
||||
if (step === 0) return
|
||||
event.preventDefault()
|
||||
const next = TABS[(TABS.indexOf(tab) + step + TABS.length) % TABS.length]
|
||||
go(next === 'artists' ? {} : { tab: next })
|
||||
buttons.current[next]?.focus()
|
||||
}
|
||||
|
||||
if (friends.isError) return <FriendError error={friends.error} name="" onRetry={() => void friends.refetch()} />
|
||||
if (friends.isPending) return <Loading />
|
||||
if (!ready) return <EmptyMessage>{t('friends.errors.friend_not_found')}</EmptyMessage>
|
||||
|
||||
const items = query.data?.items ?? []
|
||||
const filter = tab === 'albums' && artistId ? t('friends.albumsOf', { name: of }) : tab === 'songs' && (albumId || artistId) ? t('friends.songsOf', { name: of }) : ''
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
<div className="flex flex-col gap-2">
|
||||
<h1 className="text-3xl font-extrabold tracking-tight">{t('friends.musicOf', { name })}</h1>
|
||||
<p className="text-sm text-muted-foreground">{t('friends.whose', { name })}</p>
|
||||
<p className="text-sm text-muted-foreground">{t('friends.noPlayYet')}</p>
|
||||
</div>
|
||||
|
||||
<div className="max-w-xl">
|
||||
<label htmlFor="friend-search" className="sr-only">
|
||||
{t('friends.searchLabel', { name })}
|
||||
</label>
|
||||
<Input
|
||||
id="friend-search"
|
||||
type="search"
|
||||
value={text}
|
||||
maxLength={MAX_QUERY_LENGTH}
|
||||
placeholder={t('friends.searchPlaceholder')}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div role="tablist" aria-label={t('friends.tabsLabel', { name })} onKeyDown={onKeyDown} className="flex flex-wrap gap-2">
|
||||
{TABS.map((id) => (
|
||||
<button
|
||||
key={id}
|
||||
ref={(el) => {
|
||||
buttons.current[id] = el
|
||||
}}
|
||||
type="button"
|
||||
role="tab"
|
||||
id={`friend-tab-${id}`}
|
||||
aria-selected={tab === id}
|
||||
aria-controls="friend-panel"
|
||||
tabIndex={tab === id ? 0 : -1}
|
||||
onClick={() => go(id === 'artists' ? {} : { tab: id })}
|
||||
className={cn(
|
||||
'min-h-11 rounded-lg px-4 font-semibold focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring',
|
||||
tab === id ? 'bg-secondary text-foreground' : 'text-muted-foreground hover:text-foreground',
|
||||
)}
|
||||
>
|
||||
{t(`friends.tabs.${id}`)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div role="tabpanel" id="friend-panel" aria-labelledby={`friend-tab-${tab}`} className="flex flex-col gap-4">
|
||||
{filter && (
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<p className="font-semibold">{filter}</p>
|
||||
<Button variant="outline" onClick={() => go({ tab })}>
|
||||
{t('friends.showAll')}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{query.isError ? (
|
||||
<FriendError error={query.error} name={name} onRetry={() => void query.refetch()} />
|
||||
) : query.isPending ? (
|
||||
<Loading />
|
||||
) : items.length === 0 ? (
|
||||
<EmptyMessage>{typed ? t('empty.noMatch', { q: typed }) : t('friends.nothing', { name })}</EmptyMessage>
|
||||
) : (
|
||||
<>
|
||||
<ul className="flex flex-col gap-1">
|
||||
{tab === 'artists' &&
|
||||
artists.data?.items.map((a) => (
|
||||
<li key={a.id}>
|
||||
<button type="button" className={cn(rowClass, 'hover:bg-secondary')} onClick={() => go({ tab: 'albums', artist: String(a.id), of: a.name })}>
|
||||
<span className="min-w-0 flex-1 truncate font-semibold">{a.name}</span>
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{t('friends.albumCount', { count: a.album_count })} · {t('friends.songCount', { count: a.track_count })}
|
||||
</span>
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
{tab === 'albums' &&
|
||||
albums.data?.items.map((a) => (
|
||||
<li key={a.id}>
|
||||
<button type="button" className={cn(rowClass, 'hover:bg-secondary')} onClick={() => go({ tab: 'songs', album: String(a.id), of: a.title })}>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate font-semibold">{a.title}</span>
|
||||
<span className="block truncate text-sm text-muted-foreground">{a.artist?.name ?? '—'}</span>
|
||||
</span>
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{t('friends.songCount', { count: a.track_count })} · {formatTime(a.duration_ms)}
|
||||
</span>
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
{tab === 'songs' &&
|
||||
songs.data?.items.map((s, i) => (
|
||||
<li key={s.id} className={cn(rowClass, 'grid grid-cols-[2.5rem_minmax(0,1fr)_4.5rem]')}>
|
||||
<span className="tabular-nums text-muted-foreground">{s.track_no > 0 ? s.track_no : i + 1}</span>
|
||||
<span className="min-w-0">
|
||||
<span className="block truncate font-semibold">{s.title}</span>
|
||||
<span className="block truncate text-sm text-muted-foreground">{s.artists.map((a) => a.name).join(', ') || '—'}</span>
|
||||
</span>
|
||||
<span className="text-right text-sm tabular-nums text-muted-foreground">{formatTime(s.duration_ms)}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<LoadMore query={query} />
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
51
web/src/pages/FriendsPage.test.tsx
Normal file
51
web/src/pages/FriendsPage.test.tsx
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { render, screen, within } from '@testing-library/react'
|
||||
import { MemoryRouter } from 'react-router-dom'
|
||||
import { beforeEach, expect, test, vi } from 'vitest'
|
||||
import { initI18n } from '@/i18n'
|
||||
import { apiError, mockFetch } from '@/test/mockFetch'
|
||||
import FriendsPage from './FriendsPage'
|
||||
|
||||
function renderPage() {
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
return render(
|
||||
<QueryClientProvider client={client}>
|
||||
<MemoryRouter>
|
||||
<FriendsPage />
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.spyOn(navigator, 'language', 'get').mockReturnValue('en-US')
|
||||
await initI18n()
|
||||
})
|
||||
|
||||
test('each friend is a link to its music, by name', async () => {
|
||||
mockFetch({ 'GET /api/v1/friends': () => ({ friends: [{ id: 3, name: 'Anna' }, { id: 5, name: 'Bruno' }] }) })
|
||||
renderPage()
|
||||
expect(await screen.findByRole('heading', { level: 1, name: 'Friends' })).toBeInTheDocument()
|
||||
const list = within(await screen.findByRole('list'))
|
||||
expect(list.getByRole('link', { name: 'Anna' })).toHaveAttribute('href', '/friends/3')
|
||||
expect(list.getByRole('link', { name: 'Bruno' })).toHaveAttribute('href', '/friends/5')
|
||||
})
|
||||
|
||||
test('it says what a friend is, so nobody wonders whose music this is', async () => {
|
||||
mockFetch({ 'GET /api/v1/friends': () => ({ friends: [{ id: 3, name: 'Anna' }] }) })
|
||||
renderPage()
|
||||
expect(await screen.findByText(/Music that the admin of another Sonda server shares/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('with no friend it says where friends are made', async () => {
|
||||
mockFetch({ 'GET /api/v1/friends': () => ({ friends: [] }) })
|
||||
renderPage()
|
||||
expect(await screen.findByText(/no friends yet/i)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('a failure to read them is said in words with a way to try again', async () => {
|
||||
mockFetch({ 'GET /api/v1/friends': () => apiError(500, 'internal') })
|
||||
renderPage()
|
||||
const alert = await screen.findByRole('alert')
|
||||
expect(within(alert).getByRole('button', { name: 'Try again' })).toBeInTheDocument()
|
||||
})
|
||||
37
web/src/pages/FriendsPage.tsx
Normal file
37
web/src/pages/FriendsPage.tsx
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
import { useTranslation } from 'react-i18next'
|
||||
import { Link } from 'react-router-dom'
|
||||
import { useFriends } from '@/api/friends'
|
||||
import { EmptyMessage, ErrorMessage, Loading } from '@/components/Status'
|
||||
|
||||
/** The friends whose music can be browsed. Each is a way into the music that another Sonda server shares. */
|
||||
export default function FriendsPage() {
|
||||
const { t } = useTranslation()
|
||||
const friends = useFriends()
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
<h1 className="text-3xl font-extrabold tracking-tight">{t('friends.title')}</h1>
|
||||
<p className="text-muted-foreground">{t('friends.intro')}</p>
|
||||
{friends.isError ? (
|
||||
<ErrorMessage error={friends.error} onRetry={() => void friends.refetch()} />
|
||||
) : friends.isPending ? (
|
||||
<Loading />
|
||||
) : friends.data.length === 0 ? (
|
||||
<EmptyMessage>{t('friends.noneYet')}</EmptyMessage>
|
||||
) : (
|
||||
<ul className="flex flex-col gap-3">
|
||||
{friends.data.map((friend) => (
|
||||
<li key={friend.id}>
|
||||
<Link
|
||||
to={`/friends/${friend.id}`}
|
||||
className="flex min-h-14 items-center rounded-xl bg-card px-5 text-lg font-bold text-card-foreground hover:bg-secondary focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring"
|
||||
>
|
||||
{friend.name}
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
@ -21,6 +21,8 @@ export const routes: RouteObject[] = [
|
|||
{ path: '/albums', lazy: page(() => import('@/pages/AlbumsPage')) },
|
||||
{ path: '/albums/:id', lazy: page(() => import('@/pages/AlbumPage')) },
|
||||
{ path: '/songs', lazy: page(() => import('@/pages/SongsPage')) },
|
||||
{ path: '/friends', lazy: page(() => import('@/pages/FriendsPage')) },
|
||||
{ path: '/friends/:friend', lazy: page(() => import('@/pages/FriendPage')) },
|
||||
{ path: '/mixes', lazy: page(() => import('@/pages/MixesPage')) },
|
||||
{ path: '/mixes/:id', lazy: page(() => import('@/pages/MixPage')) },
|
||||
{ path: '/playlists', lazy: page(() => import('@/pages/PlaylistsPage')) },
|
||||
|
|
|
|||
Loading…
Reference in a new issue