diff --git a/README.md b/README.md index 81dd740..44f8540 100644 --- a/README.md +++ b/README.md @@ -343,7 +343,7 @@ Back up the database and `sonda.toml`. Your music stays wherever you keep it. ## Web app -A web client lives in `web/` (React, Vite and shadcn/ui). It talks only to the Sonda server: no CDN, no external fonts, no analytics. With the app built into the binary (`make build`, or the Docker image) `sondad` serves it: open the address of the server, for example `http://127.0.0.1:8080`, and sign in. The page carries a strict Content-Security-Policy (only resources of the server itself, no inline scripts), cannot be framed and sends no referrer, and a link inside the app (`/admin/users`) works when you reload it. +A web client lives in `web/` (React, Vite and shadcn/ui). It talks only to the Sonda server: no CDN, no external fonts, no analytics. With the app built into the binary (`make build`, or the Docker image) `sondad` serves it: open the address of the server, for example `http://127.0.0.1:8080`, and sign in. The page carries a strict Content-Security-Policy (only resources of the server itself, no inline scripts), cannot be framed and sends no referrer, and a link inside the app (`/admin/users`) works when you reload it. The player draws a live spectrogram of what is playing, in the browser, from the sound itself (Web Audio): the last seconds, low notes at the bottom, in the colour of this server or, for a friend's track, in the colour of the friend. It listens to the sound and changes nothing of it, and it is drawn only while something plays. To work on the interface itself, run the Vite dev server next to a running `sondad` (set `SONDA_URL` to where it listens: the default is `http://127.0.0.1:8080`): diff --git a/web/src/components/FriendChip.tsx b/web/src/components/FriendChip.tsx new file mode 100644 index 0000000..e261e5c --- /dev/null +++ b/web/src/components/FriendChip.tsx @@ -0,0 +1,21 @@ +import { useTranslation } from 'react-i18next' +import { useFriends } from '@/api/friends' +import { cn } from '@/lib/utils' + +/** + * The name of the friend whose server a track comes from, in the colour of what comes from elsewhere. Nothing while + * the friends are not known yet: a track never shows a wrong name. + */ +export default function FriendChip({ friend, className }: { friend: number; className?: string }) { + const { t } = useTranslation() + const name = useFriends().data?.find((f) => f.id === friend)?.name + if (!name) return null + return ( + + {name} + + ) +} diff --git a/web/src/components/Spectrogram.test.tsx b/web/src/components/Spectrogram.test.tsx new file mode 100644 index 0000000..162248e --- /dev/null +++ b/web/src/components/Spectrogram.test.tsx @@ -0,0 +1,27 @@ +import { render, screen } from '@testing-library/react' +import { beforeEach, expect, test, vi } from 'vitest' +import { initI18n } from '@/i18n' +import Spectrogram from './Spectrogram' + +beforeEach(async () => { + vi.spyOn(navigator, 'language', 'get').mockReturnValue('en-US') + await initI18n() +}) + +test('it is a picture with a name, and a canvas where the browser can draw', () => { + render() + const picture = screen.getByRole('img', { name: 'Spectrogram of what is playing' }) + expect(picture.querySelector('canvas')).not.toBeNull() +}) + +test('where the browser has no Web Audio it draws nothing and breaks nothing', () => { + vi.stubGlobal('AudioContext', undefined) + expect(() => render()).not.toThrow() +}) + +test('it takes the colour of this server, or of a friend', () => { + const { rerender } = render() + expect(screen.getByRole('img').className).toContain('text-primary') + rerender() + expect(screen.getByRole('img').className).toContain('text-friend') +}) diff --git a/web/src/components/Spectrogram.tsx b/web/src/components/Spectrogram.tsx new file mode 100644 index 0000000..fc25ed5 --- /dev/null +++ b/web/src/components/Spectrogram.tsx @@ -0,0 +1,91 @@ +import { useEffect, useRef } from 'react' +import { useTranslation } from 'react-i18next' +import { hasAnalyser, readBins } from '@/player/analyser' +import { currentTrack, usePlayer } from '@/player/store' +import { ColumnBuffer, rowsFromBins } from '@/player/spectrum' +import { cn } from '@/lib/utils' + +/** A new column every this many milliseconds (every quarter of a second with reduced motion: it is a picture, not a show). */ +const FRAME_MS = 80 +const REDUCED_FRAME_MS = 250 + +function colourOf(canvas: HTMLCanvasElement): [number, number, number] { + const match = /rgba?\(\s*(\d+)[,\s]+(\d+)[,\s]+(\d+)/.exec(getComputedStyle(canvas).color) + return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : [255, 255, 255] +} + +function draw(canvas: HTMLCanvasElement, columns: number[][], rows: number) { + const ctx = canvas.getContext('2d') + if (!ctx) return + const ratio = window.devicePixelRatio || 1 + const width = Math.round(canvas.clientWidth * ratio) + const height = Math.round(canvas.clientHeight * ratio) + if (canvas.width !== width) canvas.width = width + if (canvas.height !== height) canvas.height = height + ctx.clearRect(0, 0, width, height) + const [r, g, b] = colourOf(canvas) + const gap = 2 * ratio + const cols = columns.length + const cellW = (width - gap * (cols - 1)) / cols + const cellH = (height - gap * (rows - 1)) / rows + for (let c = 0; c < cols; c++) { + for (let row = 0; row < rows; row++) { + const level = columns[c][row] + ctx.fillStyle = `rgba(${r}, ${g}, ${b}, ${(0.08 + 0.92 * Math.pow(level, 1.25)).toFixed(2)})` + ctx.fillRect(c * (cellW + gap), height - (row + 1) * cellH - row * gap, cellW, cellH) + } + } +} + +interface SpectrogramProps { + /** How many columns it holds: the last seconds, the newest on the right. */ + columns?: number + /** How many rows: low notes at the bottom. */ + rows?: number + /** The track is a friend's: the colour is the friend's. */ + friend?: boolean + className?: string +} + +/** + * A spectrogram of what is playing, drawn from the sound itself: the last seconds, time running to the right and ending + * now, low notes at the bottom, brighter where there is more energy. It is drawn only while something plays and the page + * is in view, and where the browser cannot listen to the sound it stays empty. It is a picture, with a name. + */ +export default function Spectrogram({ columns = 48, rows = 12, friend = false, className }: SpectrogramProps) { + const { t } = useTranslation() + const canvas = useRef(null) + const playing = usePlayer((s) => s.playing) + const now = usePlayer(currentTrack) + const key = now ? `${now.friend ?? 0}:${now.id}` : '' + + useEffect(() => { + const el = canvas.current + if (!el) return + const buffer = new ColumnBuffer(columns, rows) + draw(el, buffer.columns(), rows) + if (!playing) return + const reduced = typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches + const every = reduced ? REDUCED_FRAME_MS : FRAME_MS + let last = 0 + let frame = 0 + const tick = (at: number) => { + frame = requestAnimationFrame(tick) + if (document.hidden || at - last < every || !hasAnalyser()) return + last = at + const bins = readBins() + if (!bins) return + buffer.push(rowsFromBins(bins, rows)) + draw(el, buffer.columns(), rows) + } + frame = requestAnimationFrame(tick) + return () => cancelAnimationFrame(frame) + // A new track starts from an empty picture. + }, [playing, key, columns, rows]) + + return ( +
+
+ ) +} diff --git a/web/src/components/layout/NowPlaying.tsx b/web/src/components/layout/NowPlaying.tsx index 8d9b0ca..ae37b92 100644 --- a/web/src/components/layout/NowPlaying.tsx +++ b/web/src/components/layout/NowPlaying.tsx @@ -3,8 +3,10 @@ import { useEffect } from 'react' import { useTranslation } from 'react-i18next' import { Link } from 'react-router-dom' import Cover from '@/components/Cover' +import FriendChip from '@/components/FriendChip' import FullscreenButton from '@/components/FullscreenButton' import Scrubber from '@/components/Scrubber' +import Spectrogram from '@/components/Spectrogram' import TrackRow from '@/components/TrackRow' import VolumeControl from '@/components/VolumeControl' import { Button } from '@/components/ui/button' @@ -74,7 +76,7 @@ export default function NowPlaying() { {track.title} -

+

{track.artists.length === 0 ? '—' : track.artists.map((a, i) => ( @@ -85,6 +87,7 @@ export default function NowPlaying() { ))} + {track.friend !== undefined && }

{track.album && ( + + diff --git a/web/src/components/layout/Player.test.tsx b/web/src/components/layout/Player.test.tsx index 0602c3f..887f79c 100644 --- a/web/src/components/layout/Player.test.tsx +++ b/web/src/components/layout/Player.test.tsx @@ -1,4 +1,5 @@ import { Profiler } from 'react' +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import { act, fireEvent, render, screen, within } from '@testing-library/react' import userEvent from '@testing-library/user-event' import { MemoryRouter } from 'react-router-dom' @@ -12,6 +13,7 @@ import { initI18n } from '@/i18n' import { usePlayer } from '@/player/store' import { useNowPlayingUi } from '@/player/ui' import { fakeFullscreen } from '@/test/fullscreen' +import { mockFetch } from '@/test/mockFetch' import PlayerBar from './PlayerBar' import PlayerControls from './PlayerControls' @@ -51,11 +53,14 @@ beforeEach(async () => { }) function renderBar(extra?: React.ReactNode) { + mockFetch({ 'GET /api/v1/friends': () => ({ friends: [{ id: 3, name: 'Anna' }] }) }) return render( - - - {extra} - , + + + + {extra} + + , ) } @@ -355,3 +360,41 @@ test('a local list does not mark a row because a friend’s track with the same ) expect(screen.getByRole('button', { name: /Song 1/ })).not.toHaveAttribute('aria-current') }) + +test('the play button is round, and teal for this server’s music', () => { + act(() => usePlayer.getState().playTracks([a])) + renderBar() + const play = screen.getByRole('button', { name: 'Pause' }) + expect(play).toHaveClass('rounded-full', 'bg-primary') + expect(play).not.toHaveClass('bg-friend') +}) + +test('a friend’s music has the play button of the friend colour and says whose it is', async () => { + act(() => usePlayer.getState().playTracks([theirs(1)])) + renderBar() + expect(screen.getByRole('button', { name: 'Pause' })).toHaveClass('bg-friend') + expect(await screen.findByLabelText('From Anna’s server')).toHaveTextContent('Anna') +}) + +test('this server’s own music carries no name of a friend', async () => { + act(() => usePlayer.getState().playTracks([a])) + renderBar() + await screen.findByText('Song 1') + expect(screen.queryByLabelText(/server/)).not.toBeInTheDocument() +}) + +test('the bar and the full-screen player both show the spectrogram of what plays', async () => { + act(() => usePlayer.getState().playTracks([a])) + renderBar() + expect(screen.getAllByRole('img', { name: 'Spectrogram of what is playing' })).toHaveLength(1) + await userEvent.click(screen.getByRole('button', { name: 'Open the full-screen player' })) + // The full-screen player covers the page: what is behind it is not reachable while it is open. + expect(within(screen.getByRole('dialog')).getAllByRole('img', { name: 'Spectrogram of what is playing' })).toHaveLength(1) +}) + +test('the full-screen player says whose music a friend’s track is', async () => { + act(() => usePlayer.getState().playTracks([theirs(1)])) + renderBar() + await userEvent.click(screen.getByRole('button', { name: 'Open the full-screen player' })) + expect((await screen.findAllByLabelText('From Anna’s server')).length).toBeGreaterThanOrEqual(2) +}) diff --git a/web/src/components/layout/PlayerBar.tsx b/web/src/components/layout/PlayerBar.tsx index 57fa1ee..240ddc7 100644 --- a/web/src/components/layout/PlayerBar.tsx +++ b/web/src/components/layout/PlayerBar.tsx @@ -4,8 +4,10 @@ import { useTranslation } from 'react-i18next' import { Link } from 'react-router-dom' import type { Track } from '@/api/catalog' import Cover from '@/components/Cover' +import FriendChip from '@/components/FriendChip' import FullscreenButton from '@/components/FullscreenButton' import Scrubber from '@/components/Scrubber' +import Spectrogram from '@/components/Spectrogram' import VolumeControl from '@/components/VolumeControl' import { Button } from '@/components/ui/button' import { formatTime } from '@/lib/time' @@ -67,17 +69,20 @@ export default function PlayerBar() { - - {track.artists.length === 0 - ? '—' - : track.artists.map((a, i) => ( - - {i > 0 && ', '} - - {a.name} - - - ))} + + + {track.artists.length === 0 + ? '—' + : track.artists.map((a, i) => ( + + {i > 0 && ', '} + + {a.name} + + + ))} + + {track.friend !== undefined && } @@ -93,6 +98,7 @@ export default function PlayerBar() {
+